text
stringlengths 2
6.14k
|
|---|
version https://git-lfs.github.com/spec/v1
oid sha256:ef8207110cddbc9ab9a056d5d654bd6d8615dca91bbba5f04af60bfa0a82e780
size 408546
|
const jwt = require("jwt-simple");
const co = require('co');
const config = require('../config');
const dbX = require('../db');
const coForEach = require('co-foreach');
module.exports = (io) => {
const collectionVersionsNS = io.of('/collectionVersions');
collectionVersionsNS.use((socket, next) => {
let token = socket.handshake.query.token;
// let isReconnect = socket.handshake.query.isReconnect;
// console.log('isReconnect:', isReconnect);
let decoded = null;
try {
decoded = jwt.decode(token, config.jwtSecret);
} catch(error) {
switch (error) {
case 'Signature verification failed':
return next(new Error('authentication error: the jwt has been falsified'));
case 'Token expired':
return next(new Error('authentication error: the jwt has been expired'));
}
}
console.log('decoded:', decoded);
return next();
})
//
collectionVersionsNS.on('connection', (socket) => {
// const roomId = socket.client.id;
console.log(`${new Date()}: ${socket.client.id} connected to socket /collectionVersions`);
socket.on('clientCollectionVersions', (data) => {
const versionsClient = data['versions'];
co(function*() {
const db = yield dbX.dbPromise;
const versionsLatest = yield db.collection('versions').find({}).toArray();
const clientCollectionUpdates = {};
// console.log('versionsClient', versionsClient);
versionsClient.reduce((acc, curr) => {
switch (true) {
case curr['collection'] === 'gd': // prices is called gd at client
const pricesVersionLatest = versionsLatest.find(v => v['collection'] === 'prices');
if (curr['version'] !== pricesVersionLatest['version']) {
acc['gd'] = {version: pricesVersionLatest['version']};
}
break;
default:
const versionLatest = versionsLatest.find(v => {
return v['collection'] === curr['collection'];
});
if (curr['version'] !== versionLatest['version']) {
acc[curr['collection']] = {version: versionLatest['version']};
}
}
return acc;
}, clientCollectionUpdates);
const hasUpdates = Object.keys(clientCollectionUpdates).length;
if (hasUpdates) {
const collectionsToUpdate = Object.keys(clientCollectionUpdates);
// types, titles, staffs
yield coForEach(Object.keys(clientCollectionUpdates), function*(k) {
console.log('adding to clientCollectionUpdates:', k);
switch (k) {
case 'gd':
clientCollectionUpdates[k]['data'] = JSON.stringify(yield db.collection('prices').find({}, {
createdAt: 0, createdBy: 0, modifiedAt: 0, modifiedBy: 0
}).toArray());
break;
default:
// need two stringifies, otherwise, error at heroku without details
clientCollectionUpdates[k]['data'] = [{a: 1}];
// clientCollectionUpdates[k]['data'] = JSON.stringify(JSON.stringify(yield db.collection(k).find({}).toArray()));
}
});
socket.emit('collectionUpdate', clientCollectionUpdates);
} else {
socket.send({message: 'all collections up-to-date'});
}
}).catch(error => {
console.log(error.stack);
socket.emit('error', {
error: error.stack
})
})
})
// after connection, client sends collectionVersions, then server compares
// each time a collection is updated, update its version in the 'versions' collection
})
}
|
var gulp = require('gulp');
var setup = require('web3-common-build-setup');
var DEPS_FOLDER = setup.depsFolder;
// Build tools
var _ = require(DEPS_FOLDER + 'lodash');
var insert = require(DEPS_FOLDER + 'gulp-insert');
var del = require(DEPS_FOLDER + 'del');
var plugins = {};
plugins.sass = require(DEPS_FOLDER + 'gulp-sass');
plugins.tsc = require(DEPS_FOLDER + 'gulp-tsc');
plugins.ngHtml2js = require(DEPS_FOLDER + 'gulp-ng-html2js');
plugins.concat = require(DEPS_FOLDER + 'gulp-concat');
// Customize build configuration
var CONFIG = setup.buildConfig;
CONFIG.FOLDER.APP = _.constant("./src/app/web3-demo/");
CONFIG.PARTIALS.MAIN = function() {
return [
"./src/app/web3-demo/view/content.html"
];
};
var tmpLibs = CONFIG.SRC.JS.LIBS();
tmpLibs.push('./bower_components/angular-mocks/angular-mocks.js');
tmpLibs.push('./bower_components/jquery/dist/jquery.js');
tmpLibs.push('./bower_components/bootstrap/dist/js/bootstrap.min.js');
CONFIG.SRC.JS.LIBS = function() { return tmpLibs; };
CONFIG.DEV.NG_MODULE_DEPS = function() { return ['httpBackendMock']; };
var deployDir = "./dist";
// Initialize gulp
var gulpInstance = setup.initGulp(gulp, CONFIG);
gulpInstance.task('dist', ['tscompile:templates', 'tscompile:app', 'resources']);
gulpInstance.task('deploy', ['dist'], function() {
gulp.src([
CONFIG.DIST.FOLDER() + "app.js",
CONFIG.DIST.FOLDER() + "templates.js",
CONFIG.DIST.FOLDER() + "app.js.map",
])
.pipe(gulp.dest(deployDir));
});
gulp.task("tscompile:templates", function (cb) {
var camelCaseModuleName = CONFIG.DYNAMIC_META.MODULE_NAME().replace(/-([a-z])/g, function(g) {
return g[1].toUpperCase();
});
gulp.src(CONFIG.SRC.ANGULAR_HTMLS())
.pipe(plugins.ngHtml2js({
moduleName: camelCaseModuleName + "Templatecache",
prefix: "/"
}))
.pipe(plugins.concat(CONFIG.DIST.JS.FILES.TEMPLATES()))
.pipe(insert.wrap(requireJSTemplatesPrefix, requireJSSuffix))
.pipe(gulp.dest(CONFIG.DIST.FOLDER()))
.on('error', cb);
cb();
});
gulpInstance.task('tscompile:app', ['prod:init-app'], function(cb) {
// Exclude bootstrap.ts when compiling distributables since
// Camunda's tasklist app takes care of bootrapping angular
var srcFiles = [CONFIG.FOLDER.SRC() + "**/*.ts",
//"!" + CONFIG.FOLDER.SRC() + "**/*Interceptor.ts",
//"!" + CONFIG.FOLDER.SRC() + "**/bootstrap.ts",
"!" + CONFIG.SRC.TS.GLOBAL_TS_UNIT_TEST_FILES()];
gulp.src(srcFiles.concat(CONFIG.SRC.TS.TS_DEFINITIONS()))
.pipe(plugins.tsc(
{
allowBool: true,
out: CONFIG.DIST.JS.FILES.APP(),
sourcemap: true,
sourceRoot: "/",
target: "ES5"
}))
.pipe(insert.wrap(requireJSAppPrefix, requireJSSuffix))
.pipe(gulp.dest(CONFIG.DIST.FOLDER()))
.on('error', cb);
cb();
});
gulpInstance.task('sass', function (cb) {
gulp.src("./sass/main.scss")
.pipe(plugins.sass({
precision: 8,
errLogToConsole: true
}))
.pipe(gulp.dest("./target/css"))
.on('error', cb);
cb();
});
gulpInstance.task('watchSass', function (cb) {
gulp.watch(['sass/**/*.scss'], ['sass']);
});
|
angular.module('africaXpress')
.controller('ShopController', function($scope, Item){
$scope.allItems;
$scope.getAll = function () {
Item.getAll().success(function(data){
$scope.allItems = data
});
};
$scope.getAll();
});
|
var REGEX = require('REGEX'),
MAX_SINGLE_TAG_LENGTH = 30,
create = require('DIV/create');
var parseString = function(parentTagName, htmlStr) {
var parent = create(parentTagName);
parent.innerHTML = htmlStr;
return parent;
};
var parseSingleTag = function(htmlStr) {
if (htmlStr.length > MAX_SINGLE_TAG_LENGTH) { return null; }
var singleTagMatch = REGEX.singleTagMatch(htmlStr);
return singleTagMatch ? [create(singleTagMatch[1])] : null;
};
module.exports = function(htmlStr) {
var singleTag = parseSingleTag(htmlStr);
if (singleTag) { return singleTag; }
var parentTagName = REGEX.getParentTagName(htmlStr),
parent = parseString(parentTagName, htmlStr);
var child,
idx = parent.children.length,
arr = Array(idx);
while (idx--) {
child = parent.children[idx];
parent.removeChild(child);
arr[idx] = child;
}
parent = null;
return arr.reverse();
};
|
import { module, test } from "qunit";
import argvInjector from "inject-loader?nwjs/App!nwjs/argv";
module( "nwjs/argv" );
test( "Default values", assert => {
const argv = argvInjector({
"nwjs/App": {
argv: []
}
});
assert.propEqual(
argv.argv,
{
"_": [],
"tray": false,
"hide": false,
"hidden": false,
"max": false,
"maximize": false,
"maximized": false,
"min": false,
"minimize": false,
"minimized": false,
"reset-window": false,
"versioncheck": true,
"version-check": true,
"logfile": true,
"loglevel": "",
"l": "",
"goto": "",
"launch": ""
},
"Has the correct parameters"
);
assert.deepEqual(
Object.keys( argv ).sort(),
[
"argv",
"parseCommand",
"ARG_GOTO",
"ARG_LAUNCH",
"ARG_LOGFILE",
"ARG_LOGLEVEL",
"ARG_MAX",
"ARG_MIN",
"ARG_RESET_WINDOW",
"ARG_TRAY",
"ARG_VERSIONCHECK"
].sort(),
"Exports the correct constants"
);
});
test( "Custom parameters", assert => {
const { argv } = argvInjector({
"nwjs/App": {
argv: [
// boolean without values
"--tray",
"--max",
"--min",
"--reset-window",
// boolean with "no-" prefix
"--no-versioncheck",
// boolean with value
"--logfile=false",
// string
"--loglevel",
"debug",
"--goto",
"foo",
"--launch",
"bar",
"positional"
]
}
});
assert.propEqual(
argv,
{
"_": [ "positional" ],
"tray": true,
"hide": true,
"hidden": true,
"max": true,
"maximize": true,
"maximized": true,
"min": true,
"minimize": true,
"minimized": true,
"reset-window": true,
"versioncheck": false,
"version-check": false,
"logfile": false,
"loglevel": "debug",
"l": "debug",
"goto": "foo",
"launch": "bar"
},
"Has the correct parameters"
);
});
test( "Aliases", assert => {
const { argv } = argvInjector({
"nwjs/App": {
argv: [
"--hide",
"--maximize",
"--minimize",
"--no-version-check",
"-l",
"debug"
]
}
});
assert.propEqual(
argv,
{
"_": [],
"tray": true,
"hide": true,
"hidden": true,
"max": true,
"maximize": true,
"maximized": true,
"min": true,
"minimize": true,
"minimized": true,
"reset-window": false,
"versioncheck": false,
"version-check": false,
"logfile": true,
"loglevel": "debug",
"l": "debug",
"goto": "",
"launch": ""
},
"Has the correct parameters"
);
});
test( "Parse command", assert => {
const { parseCommand } = argvInjector({
"nwjs/App": {
argv: [],
manifest: {
"chromium-args": "--foo --bar"
}
}
});
assert.propEqual(
// this is unfortunately how NW.js passes through the command line string from second
// application starts: parameters with leading dashes get moved to the beginning
parseCommand([
"/path/to/executable",
"--goto",
"--unrecognized-parameter-name",
"--foo",
"--bar",
"--user-data-dir=baz",
"--no-sandbox",
"--no-zygote",
"--flag-switches-begin",
"--flag-switches-end",
"foo"
].join( " " ) ),
{
"_": [],
"tray": false,
"hide": false,
"hidden": false,
"max": false,
"maximize": false,
"maximized": false,
"min": false,
"minimize": false,
"minimized": false,
"reset-window": false,
"versioncheck": true,
"version-check": true,
"logfile": true,
"loglevel": "",
"l": "",
"goto": "foo",
"launch": ""
},
"Correctly parses parameters"
);
});
|
module.exports.default = undefined;
|
var tpl = [
'<div id="{uuid}" class="datepicker ui-d-n">',
' <div class="datepicker__mask"></div>',
' <div class="datepicker__main">',
' <div class="datepicker__header">',
' <div class="datepicker__time-toggle"></div>',
' <div class="datepicker__time-selector-list">',
' <div class="datepicker__time-selector-item">',
' <a href="javascript:;" class="datepicker__time-selector-arrow datepicker__time-selector-prev" id="_j_year_prev"><</a>',
' <a href="javascript:;" class="datepicker__time-selector-text" id="_j_year_text">{year}年</a>',
' <a href="javascript:;" class="datepicker__time-selector-arrow datepicker__time-selector-next" id="_j_year_next">></a>',
' </div>',
' <div class="datepicker__time-selector-item">',
' <a href="javascript:;" class="datepicker__time-selector-arrow datepicker__time-selector-prev" id="_j_month_prev"><</a>',
' <a href="javascript:;" class="datepicker__time-selector-text" id="_j_month_text">{month}月</a>',
' <a href="javascript:;" class="datepicker__time-selector-arrow datepicker__time-selector-next" id="_j_month_next" >></a>',
' </div>',
' </div>',
' </div>',
' <div class="datepicker__panel">',
' <ul class="datepicker__week-list">',
' <li class="datepicker__week-item">日</li>',
' <li class="datepicker__week-item">一</li>',
' <li class="datepicker__week-item">二</li>',
' <li class="datepicker__week-item">三</li>',
' <li class="datepicker__week-item">四</li>',
' <li class="datepicker__week-item">五</li>',
' <li class="datepicker__week-item">六</li>',
' </ul>',
' <div class="datepicker__day-wrap">',
' <ul class="datepicker__day-list datepicker__day-list-curr">',
' {all_days}',
' </ul>',
' </div>',
' </div>',
' ',
' <div class="datepicker__footer">',
' <div class="datepicker__btn" id="_j_confirm_btn">确定</div>',
' <div class="datepicker__btn" id="_j_cancel_btn">取消</div>',
' </div>',
' </div>',
'</div>'
].join("");
module.exports = tpl;
|
(function () {
'use strict';
angular
.module('password', [
'ngMaterial',
/*@@DIST-TEMPLATE-CACHE*/
'ngRoute',
'password.analytics',
'password.title',
'password.nav',
'password.welcome',
'password.forgot',
'password.recovery',
'password.change',
'password.profile',
'password.mfa',
'password.reset',
'password.help',
'password.logo'
]);
})();
|
const greetings = {
morning: ['God morgon!', 'Kaffe?', 'Ha en bra dag!', 'Hoppas du får en bra dag!', 'Sovit gott?'],
afternoon: ['Ganska fin du!', 'Trevlig eftermiddag!', 'Eftermiddags kaffe?', 'Glömde väl inte att fika?'],
evening: ['Trevlig kväll!', 'Ser bra ut!', 'Myskväll?!'],
};
module.exports = {
getMessage: function(callback) {
const d = new Date();
var hour = d.getHours();
if (hour >= 5 && hour < 12) {
return greetings.morning[Math.floor(Math.random() * greetings.morning.length)];
} else if (hour >= 12 && hour < 18) {
return greetings.afternoon[Math.floor(Math.random() * greetings.afternoon.length)];
} else if (hour >= 18 || (hour >= 0 && hour < 5)) {
return greetings.evening[Math.floor(Math.random() * greetings.evening.length)];
} else {
return 'Something wrong, hour is: ' + hour;
}
},
};
|
import auth from '../auth';
import clone from 'clone';
import storage from './storage';
async function addBlockOrItem(dbConn, token, codeObj, props, type) {
let user = await auth.getUser(token);
console.log(`Adding new ${type} for user ${user.login}`);
let add;
let newType = {
code: codeObj,
name: props.name,
icon: 'code',
owner: user.login
};
if(type == 'item') {
add = storage.addItemType;
newType.crosshairIcon = props.crosshairIcon;
newType.adjacentActive = props.adjacentActive;
} else {
add = storage.addBlockType;
newType.material = props.material;
}
await add(dbConn, newType);
return newType;
}
async function updateBlockOrItemCode(dbConn, token, id, codeObj, type) {
let user = await auth.getUser(token);
console.log(`Updating ${type} ${id} for user ${user.login}`);
let get, add, update;
if(type == 'item') {
get = storage.getItemType;
add = storage.addItemType;
update = storage.updateItemType;
} else {
get = storage.getBlockType;
add = storage.addBlockType;
update = storage.updateBlockType;
}
let original = await get(dbConn, id);
if(original.owner != user.login) {
throw new Error(`${type} ${id} belongs to ${original.owner} - ${user.login} doesn't have access.`);
}
let updated = clone(original);
updated.code = codeObj;
delete updated.newerVersion;
await add(dbConn, updated);
original.newerVersion = updated.id;
await update(dbConn, original);
return updated;
}
export default {
async getToolbar(dbConn, token) {
let user = await auth.getUser(token);
return await storage.getToolbar(dbConn, user.login);
},
async setToolbarItem(dbConn, token, position, type, id) {
let user = await auth.getUser(token);
await storage.updateToolbarItem(dbConn, user.login, position, {type, id});
},
async removeToolbarItem(dbConn, token, position) {
let user = await auth.getUser(token);
await storage.updateToolbarItem(dbConn, user.login, position, null);
},
async getAll(dbConn) {
let itemTypes = await storage.getAllItemTypes(dbConn);
let blockTypes = await storage.getAllBlockTypes(dbConn);
return {
itemTypes,
blockTypes
};
},
async getItemTypes(dbConn, token, ids) {
return await storage.getItemTypes(dbConn, ids);
},
async getBlockTypes(dbConn, token, ids) {
return await storage.getBlockTypes(dbConn, ids);
},
async updateBlockCode(dbConn, token, id, codeObj) {
return await updateBlockOrItemCode(dbConn, token, id, codeObj, 'block');
},
async updateItemCode(dbConn, token, id, codeObj) {
return await updateBlockOrItemCode(dbConn, token, id, codeObj, 'item');
},
async addBlockType(dbConn, token, codeObj, props) {
return await addBlockOrItem(dbConn, token, codeObj, props, 'block');
},
async addItemType(dbConn, token, codeObj, props) {
return await addBlockOrItem(dbConn, token, codeObj, props, 'item');
}
};
|
import { globalShortcut } from 'electron'
import playbackControls from '../actions/playbackControls'
function initGlobalShortcuts () {
globalShortcut.register('MediaNextTrack', playbackControls.clickNextSong)
globalShortcut.register('MediaPreviousTrack', playbackControls.clickPreviousSong)
globalShortcut.register('MediaStop', playbackControls.clickPlayPause)
globalShortcut.register('MediaPlayPause', playbackControls.clickPlayPause)
}
export default initGlobalShortcuts
|
/**
* @package EntegreJS
* @subpackage Widgets
* @subpackage fontawesome
* @author James Linden <kodekrash@gmail.com>
* @copyright 2016 James Linden
* @license MIT
*/
E.widget.fontawesome = class extends E.factory.node {
constructor( icon ) {
super( 'i' );
this.attr( 'class', `fa fa-${icon.toString().toLowerCase()}` );
}
static css() {
return 'https:/' + '/maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css';
}
size( size ) {
if( !E.empty( size ) ) {
var sizes = [ 'lg', '2x', '3x', '4x', '5x' ];
size = size.toString().toLowerCase();
if( sizes.includes( size ) ) {
this.attr( 'class', `fa-${size}` );
}
}
return this;
}
fixedwidth() {
this.attr( 'class', 'fa-fw' );
return this;
}
border() {
this.attr( 'class', 'fa-border' );
return this;
}
rotate( angle ) {
angle = parseInt( angle );
if( angle >= 0 && angle <= 360 ) {
this.attr( 'class', `fa-rotate-${angle}` );
}
return this;
}
flip( dir ) {
if( !E.empty( dir ) ) {
switch( dir.toString().toLowerCase() ) {
case 'h':
case 'horz':
dir = 'horizontal';
break;
case 'v':
case 'vert':
dir = 'vertical';
break;
}
if( dir in [ 'horizontal', 'vertical' ] ) {
this.attr( 'class', `fa-flip-${dir}` );
}
}
return this;
}
};
|
require("kaoscript/register");
var Type = require("@kaoscript/runtime").Type;
module.exports = function() {
var Shape = require("../export/export.class.default.ks")().Shape;
function foobar() {
if(arguments.length === 1 && Type.isString(arguments[0])) {
let __ks_i = -1;
let x = arguments[++__ks_i];
if(x === void 0 || x === null) {
throw new TypeError("'x' is not nullable");
}
else if(!Type.isString(x)) {
throw new TypeError("'x' is not of type 'String'");
}
return x;
}
else if(arguments.length === 1) {
let __ks_i = -1;
let x = arguments[++__ks_i];
if(x === void 0 || x === null) {
throw new TypeError("'x' is not nullable");
}
else if(!Type.isClassInstance(x, Shape)) {
throw new TypeError("'x' is not of type 'Shape'");
}
return x;
}
else {
throw new SyntaxError("Wrong number of arguments");
}
};
return {
foobar: foobar
};
};
|
/**
* Node class
* @param {object} value
* @constructor
*/
class Node {
constructor(value) {
this._data = value;
}
value() {
return this._data;
}
}
export default Node;
|
;(function(){
'use strict';
angular.module('TTT')
.config(function($routeProvider){
$routeProvider
.when('/emu',{
templateUrl: 'views/emu.html',
controller: 'emuController',
controllerAs: 'emu'
});
});
})();
|
(function (window) {
'use strict';
var applicationModuleName = 'mean';
var service = {
applicationModuleName: applicationModuleName,
applicationModuleVendorDependencies: ['ngResource', 'ngAnimate', 'ngMessages', 'ui.router', 'angularFileUpload', 'ngMaterial'],
registerModule: registerModule
};
window.ApplicationConfiguration = service;
// Add a new vertical module
function registerModule(moduleName, dependencies) {
// Create angular module
angular.module(moduleName, dependencies || []);
// Add the module to the AngularJS configuration file
angular.module(applicationModuleName).requires.push(moduleName);
}
}(window));
|
/*
The main entry point for the client side of the app
*/
// Create the main app object
this.App = {};
// Create the needed collections on the client side
this.Surprises = new Meteor.Collection("surprises");
// Subscribe to the publishes in server/collections
Meteor.subscribe('surprises');
// Start the app
Meteor.startup(function() {
$(function() {
App.routes = new Routes();
});
});
|
// Copyright (c) 2016, Frappe Technologies and contributors
// For license information, please see license.txt
frappe.ui.form.on('Address Template', {
refresh: function(frm) {
if(frm.is_new() && !frm.doc.template) {
// set default template via js so that it is translated
frappe.call({
method: 'frappe.geo.doctype.address_template.address_template.get_default_address_template',
callback: function(r) {
frm.set_value('template', r.message);
}
});
}
}
});
|
/**
* A debounce method that has a sliding window, there's a minimum and maximum wait time
**/
module.exports = function (cb, min, max, settings) {
var ctx, args, next, limit, timeout;
if (!settings) {
settings = {};
}
function fire() {
limit = null;
cb.apply(settings.context || ctx, args);
}
function run() {
var now = Date.now();
if (now >= limit || now >= next) {
fire();
} else {
timeout = setTimeout(run, Math.min(limit, next) - now);
}
}
let fn = function windowed() {
var now = Date.now();
ctx = this;
args = arguments;
next = now + min;
if (!limit) {
limit = now + max;
timeout = setTimeout(run, min);
}
};
fn.clear = function () {
clearTimeout(timeout);
timeout = null;
limit = null;
};
fn.flush = function () {
fire();
fn.clear();
};
fn.shift = function (diff) {
limit += diff;
};
fn.active = function () {
return !!limit;
};
return fn;
};
|
var gulp = require('gulp'),
jshint = require('gulp-jshint'),
mocha = require('gulp-mocha'),
cover = require('gulp-coverage'),
jscs = require('gulp-jscs');
gulp.task('default', ['jscs', 'lint', 'test'], function () {
});
gulp.task('lint', function () {
return gulp.src(['./lib/*.js', './test/*.js'])
.pipe(jshint())
.pipe(jshint.reporter('default', {verbose: true}));
});
gulp.task('test', ['jscs', 'lint'], function () {
return gulp.src('./test', {read: false})
.pipe(cover.instrument({
pattern: ['*lib/*.js'],
debugDirectory: 'debug'
}))
.pipe(mocha({reporter: 'nyan'}))
.pipe(cover.gather())
.pipe(cover.format())
.pipe(gulp.dest('reports'));
});
gulp.task('jscs', function () {
return gulp.src(['./lib/*.js', './test/*.js'])
.pipe(jscs());
});
|
if (typeof window !== 'undefined') {
var less = require('npm:less/lib/less-browser/index')(window, window.less || {})
var head = document.getElementsByTagName('head')[0];
// get all injected style tags in the page
var styles = document.getElementsByTagName('style');
var styleIds = [];
for (var i = 0; i < styles.length; i++) {
if (!styles[i].hasAttribute("data-href")) continue;
styleIds.push(styles[i].getAttribute("data-href"));
}
var loadStyle = function (url) {
return new Promise(function (resolve, reject) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function () {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = request.responseText;
var options = window.less || {};
options.filename = url;
options.rootpath = url.replace(/[^\/]*$/, '');
//render it using less
less.render(data, options).then(function (data) {
//inject it into the head as a style tag
var style = document.createElement('style');
style.textContent = '\r\n' + data.css;
style.setAttribute('type', 'text/css');
//store original type in the data-type attribute
style.setAttribute('data-type', 'text/less');
//store the url in the data-href attribute
style.setAttribute('data-href', url);
head.appendChild(style);
resolve('');
});
} else {
// We reached our target server, but it returned an error
reject()
}
};
request.onerror = function (e) {
reject(e)
};
request.send();
});
}
exports.fetch = function (load) {
// don't reload styles loaded in the head
for (var i = 0; i < styleIds.length; i++)
if (load.address == styleIds[i])
return '';
return loadStyle(load.address);
}
}
else {
exports.translate = function (load) {
// setting format = 'defined' means we're managing our own output
load.metadata.format = 'defined';
};
exports.bundle = function (loads, opts) {
var loader = this;
if (loader.buildCSS === false)
return '';
return loader.import('./less-builder', {name: module.id}).then(function (builder) {
return builder.call(loader, loads, opts);
});
}
}
|
(function () {
"use strict";
angular.module("myApp.components.notifications")
.factory("KudosNotificationService", KudosNotificationService);
KudosNotificationService.$inject = [
"Transaction"
];
function KudosNotificationService(transactionBackend) {
var service = {
getNewTransactions: getNewTransactions,
setLastTransaction: setLastSeenTransaction
};
return service;
function getNewTransactions() {
return transactionBackend.getNewTransactions()
}
function setLastSeenTransaction(timestamp) {
return transactionBackend.setLastSeenTransactionTimestamp(timestamp)
}
}
})();
|
/**
(function(){
window.saveUser();
saveBlog();
var util_v1 = new window.util_v1();
util_v1.ajax();
test1();
test2();
test3(); //当$(function(){window.test3=fn});时,报错!
test4();
})();
**/
/**
(function(w){
w.saveUser();
saveBlog();
var util_v1 = new w.util_v1();
util_v1.ajax();
test1();
test2();
test3(); //当$(function(){window.test3=fn});时,报错!
test4();
})(window);
*/
/**
$(function(w){
w.saveUser();
saveBlog();
var util_v1 = new w.util_v1();
util_v1.ajax();
test1();
test2();
test3(); //当$(function(){window.test3=fn});时,报错!
test4();
}(window));
*/
//最保险的方式
$(function(){
window.saveUser();
saveBlog();
var util_v1 = new window.util_v1();
util_v1.ajax();
test1();
test2();
test3();
test4();
});
//note: 当在$(function(){window.test=fn;});赋值到window时,只能在$(function(){})中调用到window.test!
//ques:
/**Q1
$(function(){
window.test = function(){
alert('test');
};
});
// ok
$(function(){
test();
});
// fail
$(function(w){
w.test();
}(window));
// fail
(function(){
test();
})();
*/
|
Template.login.events({
'submit form': function(){
event.preventDefault();
var email = event.target.email.value;
var password = event.target.password.value;
//error handling
Meteor.loginWithPassword(email, password, function(error){
if (error) {
alert(error.reason);
} else{
Router.go('/');
};
});
}
});
|
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// Flags: --expose_externalize_string
'use strict';
const common = require('../common');
const assert = require('assert');
const path = require('path');
const fs = require('fs');
const tmpdir = require('../common/tmpdir');
tmpdir.refresh();
const fn = path.join(tmpdir.path, 'write.txt');
const fn2 = path.join(tmpdir.path, 'write2.txt');
const fn3 = path.join(tmpdir.path, 'write3.txt');
const expected = 'ümlaut.';
const constants = fs.constants;
/* eslint-disable no-undef */
common.allowGlobals(externalizeString, isOneByteString, x);
{
const expected = 'ümlaut eins'; // Must be a unique string.
externalizeString(expected);
assert.strictEqual(true, isOneByteString(expected));
const fd = fs.openSync(fn, 'w');
fs.writeSync(fd, expected, 0, 'latin1');
fs.closeSync(fd);
assert.strictEqual(expected, fs.readFileSync(fn, 'latin1'));
}
{
const expected = 'ümlaut zwei'; // Must be a unique string.
externalizeString(expected);
assert.strictEqual(true, isOneByteString(expected));
const fd = fs.openSync(fn, 'w');
fs.writeSync(fd, expected, 0, 'utf8');
fs.closeSync(fd);
assert.strictEqual(expected, fs.readFileSync(fn, 'utf8'));
}
{
const expected = '中文 1'; // Must be a unique string.
externalizeString(expected);
assert.strictEqual(false, isOneByteString(expected));
const fd = fs.openSync(fn, 'w');
fs.writeSync(fd, expected, 0, 'ucs2');
fs.closeSync(fd);
assert.strictEqual(expected, fs.readFileSync(fn, 'ucs2'));
}
{
const expected = '中文 2'; // Must be a unique string.
externalizeString(expected);
assert.strictEqual(false, isOneByteString(expected));
const fd = fs.openSync(fn, 'w');
fs.writeSync(fd, expected, 0, 'utf8');
fs.closeSync(fd);
assert.strictEqual(expected, fs.readFileSync(fn, 'utf8'));
}
/* eslint-enable no-undef */
fs.open(fn, 'w', 0o644, common.mustCall(function(err, fd) {
assert.ifError(err);
const done = common.mustCall(function(err, written) {
assert.ifError(err);
assert.strictEqual(Buffer.byteLength(expected), written);
fs.closeSync(fd);
const found = fs.readFileSync(fn, 'utf8');
fs.unlinkSync(fn);
assert.strictEqual(expected, found);
});
const written = common.mustCall(function(err, written) {
assert.ifError(err);
assert.strictEqual(0, written);
fs.write(fd, expected, 0, 'utf8', done);
});
fs.write(fd, '', 0, 'utf8', written);
}));
const args = constants.O_CREAT | constants.O_WRONLY | constants.O_TRUNC;
fs.open(fn2, args, 0o644, common.mustCall((err, fd) => {
assert.ifError(err);
const done = common.mustCall((err, written) => {
assert.ifError(err);
assert.strictEqual(Buffer.byteLength(expected), written);
fs.closeSync(fd);
const found = fs.readFileSync(fn2, 'utf8');
fs.unlinkSync(fn2);
assert.strictEqual(expected, found);
});
const written = common.mustCall(function(err, written) {
assert.ifError(err);
assert.strictEqual(0, written);
fs.write(fd, expected, 0, 'utf8', done);
});
fs.write(fd, '', 0, 'utf8', written);
}));
fs.open(fn3, 'w', 0o644, common.mustCall(function(err, fd) {
assert.ifError(err);
const done = common.mustCall(function(err, written) {
assert.ifError(err);
assert.strictEqual(Buffer.byteLength(expected), written);
fs.closeSync(fd);
});
fs.write(fd, expected, done);
}));
[false, 'test', {}, [], null, undefined].forEach((i) => {
common.expectsError(
() => fs.write(i, common.mustNotCall()),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError
}
);
common.expectsError(
() => fs.writeSync(i),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError
}
);
});
|
var through = require('through2');
var cheerio = require('cheerio');
var gulp = require('gulp');
var url = require('url');
var path = require('path');
var fs = require('fs');
var typeMap = {
css: {
tag: 'link',
template: function(contents, el) {
var attribute = el.attr('media');
attribute = attribute ? ' media="' + attribute + '" ' : '';
return '<style' + attribute + '>\n' + String(contents) + '\n</style>';
},
filter: function(el) {
return el.attr('rel') === 'stylesheet' && isLocal(el.attr('href'));
},
getSrc: function(el) {
return el.attr('href');
}
},
js: {
tag: 'script',
template: function(contents) {
return '<script type="text/javascript">\n' + String(contents) + '\n</script>';
},
filter: function(el) {
return isLocal(el.attr('src'));
},
getSrc: function(el) {
return el.attr('src');
}
},
img: {
tag: 'img',
template: function(contents, el) {
el.attr('src', 'data:image/unknown;base64,' + contents.toString('base64'));
return cheerio.html(el);
},
filter: function(el) {
var src = el.attr('src');
return !/\.svg$/.test(src);
},
getSrc: function(el) {
return el.attr('src');
}
},
svg: {
tag: 'img',
template: function(contents) {
return String(contents);
},
filter: function(el) {
var src = el.attr('src');
return /\.svg$/.test(src) && isLocal(src);
},
getSrc: function(el) {
return el.attr('src');
}
}
};
function noop() {
return through.obj(function(file, enc, cb) {
this.push(file);
cb();
});
}
function after(n, cb) {
var i = 0;
return function() {
i++;
if(i === n) cb.apply(this, arguments);
};
}
function isLocal(href) {
return href && href.slice(0, 2) !== '//' && ! url.parse(href).hostname;
}
function replace(el, tmpl) {
return through.obj(function(file, enc, cb) {
el.replaceWith(tmpl(file.contents, el));
this.push(file);
cb();
});
}
function inject($, process, base, cb, opts, relative, ignoredFiles) {
var items = [];
$(opts.tag).each(function(idx, el) {
el = $(el);
if(opts.filter(el)) {
items.push(el);
}
});
if(items.length) {
var done = after(items.length, cb);
items.forEach(function(el) {
var src = opts.getSrc(el) || '';
var file = path.join(src[0] === '/' ? base : relative, src);
if (fs.existsSync(file) && ignoredFiles.indexOf(src) === -1) {
gulp.src(file)
.pipe(process || noop())
.pipe(replace(el, opts.template))
.pipe(through.obj(function(file, enc, cb) {
cb();
}, done));
} else {
done();
}
});
} else {
cb();
}
}
module.exports = function(opts) {
opts = opts || {};
opts.base = opts.base || '';
opts.ignore = opts.ignore || [];
opts.disabledTypes = opts.disabledTypes || [];
return through.obj(function(file, enc, cb) {
var self = this;
var $ = cheerio.load(String(file.contents), {decodeEntities: false});
var typeKeys = Object.getOwnPropertyNames(typeMap);
var done = after(typeKeys.length, function() {
file.contents = new Buffer($.html());
self.push(file);
cb();
});
typeKeys.forEach(function(type) {
if (opts.disabledTypes.indexOf(type) === -1) {
inject($, opts[type], opts.base, done, typeMap[type], path.dirname(file.path), opts.ignore);
} else {
done();
}
});
});
};
|
'use strict';
angular.module('app.directives')
.directive('questionBlock',function() {
return {
restrict: 'E',
scope: {
question:'='
},
templateUrl:'/directives/questions/question-block.html'
};
});
|
// All symbols in the `Runic` script as per Unicode v10.0.0:
[
'\u16A0',
'\u16A1',
'\u16A2',
'\u16A3',
'\u16A4',
'\u16A5',
'\u16A6',
'\u16A7',
'\u16A8',
'\u16A9',
'\u16AA',
'\u16AB',
'\u16AC',
'\u16AD',
'\u16AE',
'\u16AF',
'\u16B0',
'\u16B1',
'\u16B2',
'\u16B3',
'\u16B4',
'\u16B5',
'\u16B6',
'\u16B7',
'\u16B8',
'\u16B9',
'\u16BA',
'\u16BB',
'\u16BC',
'\u16BD',
'\u16BE',
'\u16BF',
'\u16C0',
'\u16C1',
'\u16C2',
'\u16C3',
'\u16C4',
'\u16C5',
'\u16C6',
'\u16C7',
'\u16C8',
'\u16C9',
'\u16CA',
'\u16CB',
'\u16CC',
'\u16CD',
'\u16CE',
'\u16CF',
'\u16D0',
'\u16D1',
'\u16D2',
'\u16D3',
'\u16D4',
'\u16D5',
'\u16D6',
'\u16D7',
'\u16D8',
'\u16D9',
'\u16DA',
'\u16DB',
'\u16DC',
'\u16DD',
'\u16DE',
'\u16DF',
'\u16E0',
'\u16E1',
'\u16E2',
'\u16E3',
'\u16E4',
'\u16E5',
'\u16E6',
'\u16E7',
'\u16E8',
'\u16E9',
'\u16EA',
'\u16EE',
'\u16EF',
'\u16F0',
'\u16F1',
'\u16F2',
'\u16F3',
'\u16F4',
'\u16F5',
'\u16F6',
'\u16F7',
'\u16F8'
];
|
/**
* Central storage with in-memory cache
*/
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const app = process.type === 'renderer'
? require('electron').remote.app
: require('electron').app;
const _defaultDir = path.join(app.getPath('userData'), 'data');
const _storage = {};
function getPath(options) {
if(options.prefix) {
return path.join(_defaultDir, options.prefix, options.fileName);
}
return path.join(_defaultDir, options.fileName);
}
function ensureDirectoryExists(dir) {
if (!fs.existsSync(dir)){
mkdirp.sync(dir);
}
}
function ensurePrefixExists(prefix) {
ensureDirectoryExists(path.join(_defaultDir, prefix));
}
ensureDirectoryExists(_defaultDir);
const Storage = {};
Storage.set = function(options, callback) {
if(options.prefix) {
ensurePrefixExists(options.prefix);
}
const file = getPath(options);
_storage[file] = options.value;
fs.writeFile(file, options.value, callback);
};
Storage.get = function(options, callback) {
const file = getPath(options);
if(file in _storage) {
callback(null, _storage[file]);
return;
}
fs.readFile(file, callback);
};
Storage.append = function(options, callback) {
if(options.prefix) {
ensurePrefixExists(options.prefix);
}
const file = getPath(options);
if(!(file in _storage)) {
_storage[file] = [];
}
_storage[file].push(options.value);
fs.appendFile(file, options.value, callback);
};
Storage.delete = function(options, callback) {
const file = getPath(options);
delete _storage[file];
fs.unlink(file, callback);
};
module.exports = Storage;
|
'use strict';
/* global $: true */
/* global animation: true */
/* global boidWeights: true */
//Slider for selecting initial number of boids
//---------------------------------------------
$('#numBoidsSlider').slider({
min: 0,
max: 400,
step: 10,
value: animation.numBoids
});
$('#numBoidsVal').text(animation.numBoids);
$('#numBoidsSlider').on('slide', function (slideEvt) {
$('#numBoidsVal').text(slideEvt.value);
animation.numBoids = slideEvt.value;
});
//Sliders for weights
//--------------------
$('#slider1').slider({
min: 0,
max: 20,
step: 0.1,
value: boidWeights.separation
});
$('#slider1val').text(boidWeights.separation);
$('#slider1').on('slide', function (slideEvt) {
$('#slider1val').text(slideEvt.value);
boidWeights.separation = slideEvt.value;
});
$('#slider2').slider({
min: 0,
max: 20,
step: 0.1,
value: boidWeights.alginment
});
$('#slider2').on('slide', function (slideEvt) {
$('#slider2val').text(boidWeights.alginment);
$('#slider2val').text(slideEvt.value);
boidWeights.alginment = slideEvt.value;
});
$('#slider3').slider({
min: 0,
max: 20,
step: 0.1,
value: boidWeights.cohesion
});
$('#slider3val').text(boidWeights.cohesion);
$('#slider3').on('slide', function (slideEvt) {
$('#slider3val').text(slideEvt.value);
boidWeights.cohesion = slideEvt.value;
});
$('#slider4').slider({
min: 0,
max: 20,
step: 0.1,
value: boidWeights.obstacle
});
$('#slider4val').text(boidWeights.obstacle);
$('#slider4').on('slide', function (slideEvt) {
$('#slider4val').text(slideEvt.value);
boidWeights.obstacle = slideEvt.value;
});
$('#slider5').slider({
min: 0,
max: 20,
step: 0.1,
value: boidWeights.predators
});
$('#slider5val').text(boidWeights.predators);
$('#slider5').on('slide', function (slideEvt) {
$('#slider5val').text(slideEvt.value);
boidWeights.predators = slideEvt.value;
});
|
/*
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', 'ko', {
border: '프레임 테두리 표시',
noUrl: '아이프레임 주소(URL)를 입력해주세요.',
scrolling: '스크롤바 사용',
title: '아이프레임 속성',
toolbar: '아이프레임'
} );
|
/**
* Hydro configuration
*
* @param {Hydro} hydro
*/
module.exports = function(hydro) {
hydro.set({
suite: 'equals',
timeout: 500,
plugins: [
require('hydro-chai'),
require('hydro-bdd')
],
chai: {
chai: require('chai'),
styles: ['should'],
stack: true
}
})
}
|
module.exports = function(params) {
params = params || {};
_.extend(this, params);
this.validate = params.validate || function() {
return true;
};
}
|
class DataControl {
constructor() {
this.appData
updateData()
}
updateData() {
this.appData = fetcherama()
}
fetcherama() {
lib.fetch(`http://localhost:8080/api/class/getNearbyClasses/${coor.long}/${coor.lat}`, opt, data => {
if (data.success === true) {
return data.classes
}
})
}
}
export default DataControl
|
/* */
"format cjs";
(function(e){if("function"==typeof bootstrap)bootstrap("csv2geojson",e);else if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else if("undefined"!=typeof ses){if(!ses.ok())return;ses.makeCsv2geojson=e}else"undefined"!=typeof window?window.csv2geojson=e():global.csv2geojson=e()})(function(){var define,ses,bootstrap,module,exports;
return (function(e,t,n){function r(n,i){if(!t[n]){if(!e[n]){var s=typeof require=="function"&&require;if(!i&&s)return s(n,!0);throw new Error("Cannot find module '"+n+"'")}var o=t[n]={exports:{}};e[n][0](function(t){var i=e[n][1][t];return r(i?i:t)},o,o.exports)}return t[n].exports}for(var i=0;i<n.length;i++)r(n[i]);return r})({1:[function(require,module,exports){
function csv(text) {
var header;
return csv_parseRows(text, function(row, i) {
if (i) {
var o = {}, j = -1, m = header.length;
while (++j < m) o[header[j]] = row[j];
return o;
} else {
header = row;
return null;
}
});
function csv_parseRows (text, f) {
var EOL = {}, // sentinel value for end-of-line
EOF = {}, // sentinel value for end-of-file
rows = [], // output rows
re = /\r\n|[,\r\n]/g, // field separator regex
n = 0, // the current line number
t, // the current token
eol; // is the current token followed by EOL?
re.lastIndex = 0; // work-around bug in FF 3.6
/** @private Returns the next token. */
function token() {
if (re.lastIndex >= text.length) return EOF; // special case: end of file
if (eol) { eol = false; return EOL; } // special case: end of line
// special case: quotes
var j = re.lastIndex;
if (text.charCodeAt(j) === 34) {
var i = j;
while (i++ < text.length) {
if (text.charCodeAt(i) === 34) {
if (text.charCodeAt(i + 1) !== 34) break;
i++;
}
}
re.lastIndex = i + 2;
var c = text.charCodeAt(i + 1);
if (c === 13) {
eol = true;
if (text.charCodeAt(i + 2) === 10) re.lastIndex++;
} else if (c === 10) {
eol = true;
}
return text.substring(j + 1, i).replace(/""/g, "\"");
}
// common case
var m = re.exec(text);
if (m) {
eol = m[0].charCodeAt(0) !== 44;
return text.substring(j, m.index);
}
re.lastIndex = text.length;
return text.substring(j);
}
while ((t = token()) !== EOF) {
var a = [];
while ((t !== EOL) && (t !== EOF)) {
a.push(t);
t = token();
}
if (f && !(a = f(a, n++))) continue;
rows.push(a);
}
return rows;
}
}
function csv2geojson(x, lonfield, latfield) {
var features = [],
featurecollection = {
type: 'FeatureCollection',
features: features
};
var parsed = csv(x);
if (!parsed.length) return featurecollection;
latfield = latfield || '';
lonfield = lonfield || '';
for (var f in parsed[0]) {
if (!latfield && f.match(/^Lat/i)) latfield = f;
if (!lonfield && f.match(/^Lon/i)) lonfield = f;
}
if (!latfield || !lonfield) {
var fields = [];
for (var k in parsed[0]) fields.push(k);
return fields;
}
for (var i = 0; i < parsed.length; i++) {
if (parsed[i][lonfield] !== undefined &&
parsed[i][lonfield] !== undefined) {
features.push({
type: 'Feature',
properties: parsed[i],
geometry: {
type: 'Point',
coordinates: [
parseFloat(parsed[i][lonfield]),
parseFloat(parsed[i][latfield])]
}
});
}
}
return featurecollection;
}
function toline(gj) {
var features = gj.features;
var line = {
type: 'Feature',
geometry: {
type: 'LineString',
coordinates: []
}
};
for (var i = 0; i < features.length; i++) {
line.geometry.coordinates.push(features[i].geometry.coordinates);
}
line.properties = features[0].properties;
return {
type: 'FeatureSet',
features: [line]
};
}
function topolygon(gj) {
var features = gj.features;
var poly = {
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: [[]]
}
};
for (var i = 0; i < features.length; i++) {
poly.geometry.coordinates[0].push(features[i].geometry.coordinates);
}
poly.properties = features[0].properties;
return {
type: 'FeatureSet',
features: [poly]
};
}
module.exports = {
csv: csv,
toline: toline,
topolygon: topolygon,
csv2geojson: csv2geojson
};
},{}]},{},[1])(1)
});
;
|
var module = angular.module('mtg', ['ngRoute', 'timer']);
DEBUG = true;
module.controller('main', function($scope, $filter) {
$scope.matches = [];
$scope.players = [{}, {}];
var orderBy = $filter('orderBy');
$scope.importFromStorage = function() {
console.log("Importing from local storage");
tourney = JSON.parse(localStorage.tourney);
console.log(tourney);
$scope.title = tourney.title;
$scope.players = tourney.players;
$scope.matches = tourney.matches;
// ugly way of rebind players to respective matches.
for(var m = 0; m < $scope.matches.length; m++)
{
for(var i = 0; i < $scope.players.length; i++) {
if($scope.matches[m].players[0].id == $scope.players[i].id)
$scope.matches[m].players[0] = $scope.players[i];
if($scope.matches[m].players[1].id == $scope.players[i].id)
$scope.matches[m].players[1] = $scope.players[i];
}
}
$scope.inited = true;
$scope.updatePlayerRanks();
};
$scope.exportToStorage = function() {
localStorage.tourney = JSON.stringify({
players: $scope.players,
matches: $scope.matches,
title: $scope.title,
inited: $scope.inited,
});
console.log("Exported to storage");
};
$scope.initPlayers = function() {
for(var p = 0; p < $scope.players.length; p++) {
$scope.players[p].won =
$scope.players[p].lost =
$scope.players[p].draw = 0;
$scope.players[p].rank = 1;
$scope.players[p].id = p;
}
};
$scope.updatePlayerRanks = function() {
$scope.players = orderBy($scope.players, ['-won','-draw']);
prev = $scope.players[0];
prev.rank = 1;
for(var i = 1; i < $scope.players.length; i++) {
curr = $scope.players[i];
if(curr.won == prev.won && curr.draw == prev.draw) // Not counting losses here.
{
curr.rank = prev.rank;
} else {
curr.rank = prev.rank + 1;
prev = curr;
}
}
console.log($scope.players);
};
$scope.createMatches = function() {
$scope.matches = [];
index = 0;
for(var p = 0; p < $scope.players.length; p++) {
var player1 = $scope.players[p];
for(var p2 = p+1; p2 < $scope.players.length; p2++) {
var player2 = $scope.players[p2];
var match = {
players: [player1, player2],
scores: [0, 0],
status: 'queued',
index: -1
}
$scope.matches.push(match);
}
}
// Semi-Random ordering of the matches.
// Should be so that min n-1 players have a match in the first
// round. This problem could be reduced to finding a Hamilton path...
indexes = [];
for(var i = 0; i < $scope.matches.length; i++)
indexes.push(i);
// Random shuffle. This could probably be improved in terms of efficiency.
matches_without_index = [];
while(indexes.length > 0) {
pick = Math.floor(Math.random() * indexes.length);
ind = indexes[pick];
matches_without_index.push(ind);
indexes.splice(pick, 1);
}
console.log(matches_without_index);
picked_players = [];
for(var i = 0; i < $scope.matches.length;) {
var m = 0;
for(; m < $scope.matches.length; m++) {
var match = $scope.matches[matches_without_index[m]]; // accessing the random order.
if(match.index > -1)
continue; // already visited.
if(picked_players.indexOf(match.players[0]) > -1 || picked_players.indexOf(match.players[1]) > -1)
continue; // at least one of the players already has a matchup this round.
match.index = i++;
picked_players.push(match.players[0]);
picked_players.push(match.players[1]);
break;
}
if(m == $scope.matches.length) {
picked_players = []; // new round.
}
}
$scope.matchesLeft = $scope.matches.length;
};
$scope.init = function() {
console.log("Init was called");
$scope.inited = true;
$scope.initPlayers();
$scope.createMatches();
$scope.exportToStorage();
};
$scope.matchEvaluator = function(a) {
statusorder = ['playing','queued','ended']
letters = ['a','b','c'];
return letters[statusorder.indexOf(a.status)] + a.index;
};
$scope.getMatchesLeft = function() {
var count = 0;
for(var i = 0; i < $scope.matches.length; i++)
if($scope.matches[i].status != 'ended')
count++;
return count;
};
$scope.reorderMatches = function() {
$scope.matches = orderBy($scope.matches, $scope.matchEvaluator, false);
$scope.exportToStorage();
};
$scope.startMatch = function(match) {
match.status = 'playing';
match.endtime = new Date().getTime() + 45*60*1000; // todo flytta till setting.
$scope.reorderMatches();
};
$scope.editMatch = function(match) {
match.status = 'playing';
if(match.scores[0] == match.scores[1])
{
match.players[0].draw -= 1;
match.players[1].draw -= 1;
} else if(match.scores[0] > match.scores[1]) {
match.players[0].won -= 1;
match.players[1].lost -= 1;
} else {
match.players[1].won -= 1;
match.players[0].lost -= 1;
}
$scope.updatePlayerRanks();
$scope.reorderMatches();
};
$scope.endMatch = function(match) {
match.status = 'ended';
if(match.scores[0] == match.scores[1])
{
match.players[0].draw += 1;
match.players[1].draw += 1;
} else if(match.scores[0] > match.scores[1]) {
match.players[0].won += 1;
match.players[1].lost += 1;
} else {
match.players[1].won += 1;
match.players[0].lost += 1;
}
$scope.reorderMatches();
$scope.updatePlayerRanks();
};
$scope.reset = function() {
$scope.matches = [];
$scope.players = [{}, {}];
$scope.inited = false;
if(DEBUG) {
$scope.players = [{name:'Herp'}, {name:'Derp'}, {name:'Merp'}];
}
$scope.exportToStorage();
};
if (localStorage.tourney) {
$scope.importFromStorage();
}
});
|
// Demo component
// this is only example component
// you can find tests in __test__ folder
import React from 'react';
import Button from './components/Button'
class TeamCatfish extends React.Component {
render() {
return (
<div className="team-catfish">
<p>TC</p>
</div>
)
}
};
module.exports = {
TeamCatfish,
...Button
}
|
var LOTUS = Symbol.for('lotus');
var lotus = global[LOTUS];
if (!lotus) {
var lotusPath = process.env.LOTUS_PATH;
// Try using the local version.
if (lotusPath) {
lotusPath += '/lotus-require';
if (__dirname === lotusPath) {
// We are already using the local version.
}
else if (require('fs').existsSync(lotusPath)) {
lotus = require(lotusPath);
}
}
// Default to using the installed remote version.
if (!lotus) {
lotus = require('./js/index');
}
global[LOTUS] = lotus;
}
module.exports = lotus;
|
import { compose, combineReducers, createStore } from 'redux';
import { devTools } from 'redux-devtools';
import twist from './reducers/twist';
import form from './reducers/form';
const twister = combineReducers({
twist,
form
});
const finalCreateStore = compose(devTools())(createStore);
export default finalCreateStore(twister);
|
'use strict';
describe('Controller: HomeCtrl', function () {
it('should make a unit test ...', function () {
});
});
|
const
pObj=pico.export('pico/obj'),
fb=require('api/fbJSON'),
rdTrip=require('redis/trip')
return {
setup(context,cb){
cb()
},
addPickup(user,action,evt,name,next){
const text=pObj.dotchain(evt,['message','text'])
if(!text) return next(null,`fb/ask${action[action.length-1]}`)
const a=action.pop()
switch(a){
case 'TripFirstPickup':
switch(text.toLowerCase()){
case 'done': return next(null,`fb/ask${a}`)
default:
action.push('-',text)
this.set(name,'TripPickup')
break
}
break
case 'TripPickup':
switch(text.toLowerCase()){
case 'done':
action.push('+:pickup',null)
this.set(name,'TripFirstDropoff')
break
default:
action.push('-',text)
this.set(name,'TripPickup')
break
}
break
default: return next(null,`fb/ask${a}`)
}
next()
},
addDropoff(user,action,evt,name,next){
const text=pObj.dotchain(evt,['message','text'])
if(!text) return next(null,`fb/ask${action[action.length-1]}`)
const a=action.pop()
switch(a){
case 'TripFirstDropoff':
switch(text.toLowerCase()){
case 'done': return next(null,`fb/ask${a}`)
default:
action.push('-',text)
this.set(name,'TripDropoff')
break
}
break
case 'TripDropoff':
switch(text.toLowerCase()){
case 'done':
action.push('+:dropoff',null)
this.set(name,'TripSeat')
break
default:
action.push('-',text)
this.set(name,'TripDropoff')
break
}
break
default: return next(null,`fb/ask${a}`)
}
next()
},
done(user,cmd,msg,next){
console.log('addTrp.done',user,cmd)
rdTrip.set(user,cmd,(err)=>{
if (err) Object.assign(msg, fb.message(user,fb.text(`An error has encountered when adding your trip: ${err}.\ntype help for more action`)))
else Object.assign(msg, fb.message(user,fb.text(`New trip on ${fb.toDateTime(user,cmd.date)} has been added.\ntype help for more action`)))
next()
})
}
}
|
Clazz.declarePackage ("J.renderspecial");
Clazz.load (["J.render.ShapeRenderer"], "J.renderspecial.PolyhedraRenderer", ["JU.P3i", "JM.Atom", "JU.C"], function () {
c$ = Clazz.decorateAsClass (function () {
this.drawEdges = 0;
this.isAll = false;
this.frontOnly = false;
this.screens = null;
this.vibs = false;
Clazz.instantialize (this, arguments);
}, J.renderspecial, "PolyhedraRenderer", J.render.ShapeRenderer);
Clazz.overrideMethod (c$, "render",
function () {
var polyhedra = this.shape;
var polyhedrons = polyhedra.polyhedrons;
this.drawEdges = polyhedra.drawEdges;
this.g3d.addRenderer (1073742182);
this.vibs = (this.ms.vibrations != null && this.tm.vibrationOn);
var needTranslucent = false;
for (var i = polyhedra.polyhedronCount; --i >= 0; ) if (polyhedrons[i].isValid && this.render1 (polyhedrons[i])) needTranslucent = true;
return needTranslucent;
});
Clazz.defineMethod (c$, "render1",
function (p) {
if (p.visibilityFlags == 0) return false;
var colixes = (this.shape).colixes;
var iAtom = p.centralAtom.i;
var colix = (colixes == null || iAtom >= colixes.length ? 0 : colixes[iAtom]);
colix = JU.C.getColixInherited (colix, p.centralAtom.colixAtom);
var needTranslucent = false;
if (JU.C.renderPass2 (colix)) {
needTranslucent = true;
} else if (!this.g3d.setC (colix)) {
return false;
}var vertices = p.vertices;
var planes;
if (this.screens == null || this.screens.length < vertices.length) {
this.screens = new Array (vertices.length);
for (var i = vertices.length; --i >= 0; ) this.screens[i] = new JU.P3i ();
}planes = p.planes;
for (var i = vertices.length; --i >= 0; ) {
var atom = (Clazz.instanceOf (vertices[i], JM.Atom) ? vertices[i] : null);
if (atom == null) {
this.tm.transformPtScr (vertices[i], this.screens[i]);
} else if (!atom.isVisible (this.myVisibilityFlag)) {
this.screens[i].setT (this.vibs && atom.hasVibration () ? this.tm.transformPtVib (atom, this.ms.vibrations[atom.i]) : this.tm.transformPt (atom));
} else {
this.screens[i].set (atom.sX, atom.sY, atom.sZ);
}}
this.isAll = (this.drawEdges == 1);
this.frontOnly = (this.drawEdges == 2);
if (!needTranslucent || this.g3d.setC (colix)) for (var i = 0, j = 0; j < planes.length; ) this.fillFace (p.normixes[i++], this.screens[planes[j++]], this.screens[planes[j++]], this.screens[planes[j++]]);
if (p.colixEdge != 0) colix = p.colixEdge;
if (this.g3d.setC (JU.C.getColixTranslucent3 (colix, false, 0))) for (var i = 0, j = 0; j < planes.length; ) this.drawFace (p.normixes[i++], this.screens[planes[j++]], this.screens[planes[j++]], this.screens[planes[j++]]);
return needTranslucent;
}, "J.shapespecial.Polyhedron");
Clazz.defineMethod (c$, "drawFace",
function (normix, A, B, C) {
if (this.isAll || this.frontOnly && this.vwr.gdata.isDirectedTowardsCamera (normix)) {
this.drawCylinderTriangle (A.x, A.y, A.z, B.x, B.y, B.z, C.x, C.y, C.z);
}}, "~N,JU.P3i,JU.P3i,JU.P3i");
Clazz.defineMethod (c$, "drawCylinderTriangle",
function (xA, yA, zA, xB, yB, zB, xC, yC, zC) {
var d = (this.g3d.isAntialiased () ? 6 : 3);
this.g3d.fillCylinderScreen (3, d, xA, yA, zA, xB, yB, zB);
this.g3d.fillCylinderScreen (3, d, xB, yB, zB, xC, yC, zC);
this.g3d.fillCylinderScreen (3, d, xA, yA, zA, xC, yC, zC);
}, "~N,~N,~N,~N,~N,~N,~N,~N,~N");
Clazz.defineMethod (c$, "fillFace",
function (normix, A, B, C) {
this.g3d.fillTriangleTwoSided (normix, A.x, A.y, A.z, B.x, B.y, B.z, C.x, C.y, C.z);
}, "~N,JU.P3i,JU.P3i,JU.P3i");
});
|
var buttons = function(req, res, next) {
var request = require('request');
var cheerio = require('cheerio');
var Case = require('case');
// var url = "http://clas.asu.edu";
var url = req.body.page;
var parsedResults = [];
//testing url argument site buttons casing
request(url, function (error, response, html) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(html);
$('.btn').each(function(i, element){
var text = $(this).text().trim();
var casing = Case.of($(this).text().trim());
if ( (casing == "sentence") || (casing == "header") ){
var passfail = "PASS";
} else {
var passfail = "FAIL";
}
var testResults = {
text: text,
casing: casing,
passfail: passfail
};
parsedResults.push(testResults);
});
req.pf = parsedResults;
next();
};
});
};
module.exports = buttons;
|
var taxi = require('..');
var chromedriver = require('chromedriver');
var fs = require('fs');
var user = process.env.SAUCE_USERNAME;
var accessKey = process.env.SAUCE_ACCESS_KEY;
var sauceLabsUrl = "http://" + user + ":" + accessKey + "@ondemand.saucelabs.com/wd/hub";
var tests = [
{ url:'http://localhost:9515/', capabilities: { browserName:'chrome' }, beforeFn: function () { chromedriver.start(); }, afterFn: function () { chromedriver.stop() } },
{ url:'http://localhost:9517/', capabilities: { browserName:'phantomjs', browserVersion:'1.9.8' } },
{ url:'http://localhost:4444/wd/hub', capabilities: { browserName:'firefox' } },
{ url:'http://makingshaking.corp.ne1.yahoo.com:4444', capabilities: { browserName:'phantomjs', browserVersion: '2.0.0 dev' } },
{ url:sauceLabsUrl, capabilities: { browserName:'chrome', version:'41.0', platform:'Windows 8.1' } },
{ url:sauceLabsUrl, capabilities: { browserName:'firefox', version:'37.0', platform:'Windows 8.1' } },
{ url:sauceLabsUrl, capabilities: { browserName:'internet explorer', version:'11.0', platform:'Windows 8.1' } },
{ url:sauceLabsUrl, capabilities: { browserName:'internet explorer', version:'10.0', platform:'Windows 8' } },
{ url:sauceLabsUrl, capabilities: { browserName:'internet explorer', version:'9.0', platform:'Windows 7' } },
{ url:sauceLabsUrl, capabilities: { browserName:'safari', version:'5.1', platform:'Windows 7' } },
{ url:sauceLabsUrl, capabilities: { browserName:'safari', version:'8.0', platform:'OS X 10.10' } },
{ url:sauceLabsUrl, capabilities: { browserName:'iphone', version:'8.2', platform: 'OS X 10.10', deviceName:'iPad Simulator', "device-orientation":'portrait' } },
{ url:sauceLabsUrl, capabilities: { browserName:'iphone', version:'8.2', platform: 'OS X 10.10', deviceName:'iPad Simulator', "device-orientation":'landscape' } },
{ url:sauceLabsUrl, capabilities: { browserName:'iphone', version:'8.2', platform: 'OS X 10.10', deviceName:'iPhone Simulator', "device-orientation":'portrait' } },
{ url:sauceLabsUrl, capabilities: { browserName:'iphone', version:'8.2', platform: 'OS X 10.10', deviceName:'iPhone Simulator', "device-orientation":'landscape' } }
];
tests.forEach(function (test) {
// Do we need to run something before the test-run?
if (test.beforeFn) {
test.beforeFn();
}
try {
var driver = taxi(test.url, test.capabilities, {mode: taxi.Driver.MODE_SYNC, debug: true, httpDebug: true});
var browser = driver.browser();
var activeWindow = browser.activeWindow();
// Navigate to Yahoo
activeWindow.navigator().setUrl('http://www.yahoo.com');
var browserId = (driver.deviceName() != '' ? driver.deviceName() : driver.browserName()) + " " + driver.deviceOrientation() + " " + driver.browserVersion() + " " + driver.platform();
// Write screenshot to a file
fs.writeFileSync(__dirname + '/' + browserId.trim() + '.png', activeWindow.documentScreenshot({
eachFn: function (index) {
// Remove the header when the second screenshot is reached.
// The header keeps following the scrolling position.
// So, we want to turn it off here.
if (index >= 1 && document.getElementById('masthead')) {
document.getElementById('masthead').style.display = 'none';
}
},
completeFn: function () {
// When it has a "masthead", then display it again
if (document.getElementById('masthead')) {
document.getElementById('masthead').style.display = '';
}
},
// Here is a list of areas that should be blocked-out
blockOuts: [
// Block-out all text-boxes
'input',
// Custom block-out at static location with custom color
{x:60, y: 50, width: 200, height: 200, color:{red:255,green:0,blue:128}}
]
// The element cannot be found in mobile browsers since they have a different layout
//, activeWindow.getElement('.footer-section')]
}));
} catch (err) {
console.error(err.stack);
} finally {
driver.dispose();
// Do we need to run something after the test-run?
if (test.afterFn) {
test.afterFn();
}
}
});
|
/**
* @author Chine
*/
function switchTheme(theme) {
$.cookie('blog_theme', theme, { expires: 30 });
location.href = location.href;
}
|
(function() {
function Base(props) {
this.id = Ambient.getID();
$.extend(this, props || {});
}
Base.extend = function(methods) {
if (typeof methods === "function") {
methods = methods();
}
methods = (methods || {});
var self = this;
var Controller = function() {
self.apply(this, arguments);
};
Controller.prototype = Object.create(self.prototype);
Controller.prototype.constructor = Controller;
for (var key in methods) {
Controller.prototype[key] = methods[key];
}
Controller.extend = Base.extend.bind(Controller);
return Controller;
};
window.Ambient.Controller = Base;
})();
|
import React from 'react'
import { Router, Route, hashHistory, browserHistory, IndexRoute } from 'react-router'
import MainContainer from '../components/MainContainer'
import Login from '../components/hello/Login'
import Register from '../components/hello/Register'
import Index from '../components/index/Index'
import HelloWorld from '../components/hello/HelloWorld'
import Header from '../components/common/Header'
import Xiexie from '../components/write/Write'
import ArticleDetail from '../components/index/ArticleDetail'
class Root extends React.Component {
render() {
return (
<Router history={browserHistory}>
<Route path="/" component={Header}>
<IndexRoute component={Index}/>
<Route path="/xiexie" component={Xiexie}/>
<Route path="/articleDetail" component={ArticleDetail}/>
</Route>
</Router>
)
}
}
export default Root
|
var gulp = require('gulp');
var blocksConfig = require('../config').geniblocksRsrc;
var gvConfig = require('../config').geniverseRsrc;
// Copy files directly simple
exports.geniblocksRsrc = function geniblocksRsrc() {
return gulp.src(blocksConfig.src)
.pipe(gulp.dest(blocksConfig.dest));
};
exports.geniverseRsrc = function geniverseRsrc() {
gulp.src(gvConfig.index)
.pipe(gulp.dest(gvConfig.destIndex));
return gulp.src(gvConfig.src)
.pipe(gulp.dest(gvConfig.dest));
};
|
import express from 'express'
import adminOnly from 'desktop/lib/admin_only'
import { buildServerApp } from 'reaction/Router'
import { routes } from './routes'
import { renderLayout } from '@artsy/stitch'
import { Meta } from './components/Meta'
const app = (module.exports = express())
app.get('/isomorphic-relay-example*', adminOnly, async (req, res, next) => {
try {
const { ServerApp, redirect, status } = await buildServerApp({
routes,
url: req.url,
})
if (redirect) {
res.redirect(302, redirect.url)
return
}
const layout = await renderLayout({
basePath: __dirname,
layout: '../../components/main_layout/templates/react_index.jade',
config: {
styledComponents: true,
},
blocks: {
head: Meta,
body: ServerApp,
},
locals: {
...res.locals,
assetPackage: 'relay',
styledComponents: true,
},
})
res.status(status).send(layout)
} catch (error) {
console.log(error)
next(error)
}
})
|
var view = require("ui/core/view");
var proxy = require("ui/core/proxy");
var dependencyObservable = require("ui/core/dependency-observable");
var color = require("color");
var bindable = require("ui/core/bindable");
var types;
function ensureTypes() {
if (!types) {
types = require("utils/types");
}
}
var knownCollections;
(function (knownCollections) {
knownCollections.items = "items";
})(knownCollections = exports.knownCollections || (exports.knownCollections = {}));
var SegmentedBarItem = (function (_super) {
__extends(SegmentedBarItem, _super);
function SegmentedBarItem() {
_super.apply(this, arguments);
this._title = "";
}
Object.defineProperty(SegmentedBarItem.prototype, "title", {
get: function () {
return this._title;
},
set: function (value) {
if (this._title !== value) {
this._title = value;
this._update();
}
},
enumerable: true,
configurable: true
});
SegmentedBarItem.prototype._update = function () {
};
return SegmentedBarItem;
}(bindable.Bindable));
exports.SegmentedBarItem = SegmentedBarItem;
var SegmentedBar = (function (_super) {
__extends(SegmentedBar, _super);
function SegmentedBar() {
_super.apply(this, arguments);
}
SegmentedBar.prototype._addArrayFromBuilder = function (name, value) {
if (name === "items") {
this._setValue(SegmentedBar.itemsProperty, value);
}
};
SegmentedBar.prototype._adjustSelectedIndex = function (items) {
if (this.items) {
if (this.items.length > 0) {
ensureTypes();
if (types.isUndefined(this.selectedIndex) || (this.selectedIndex > this.items.length - 1)) {
this._setValue(SegmentedBar.selectedIndexProperty, 0);
}
}
else {
this._setValue(SegmentedBar.selectedIndexProperty, undefined);
}
}
else {
this._setValue(SegmentedBar.selectedIndexProperty, undefined);
}
};
Object.defineProperty(SegmentedBar.prototype, "selectedIndex", {
get: function () {
return this._getValue(SegmentedBar.selectedIndexProperty);
},
set: function (value) {
this._setValue(SegmentedBar.selectedIndexProperty, value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(SegmentedBar.prototype, "items", {
get: function () {
return this._getValue(SegmentedBar.itemsProperty);
},
set: function (value) {
this._setValue(SegmentedBar.itemsProperty, value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(SegmentedBar.prototype, "selectedBackgroundColor", {
get: function () {
return this._getValue(SegmentedBar.selectedBackgroundColorProperty);
},
set: function (value) {
this._setValue(SegmentedBar.selectedBackgroundColorProperty, value instanceof color.Color ? value : new color.Color(value));
},
enumerable: true,
configurable: true
});
SegmentedBar.prototype._onBindingContextChanged = function (oldValue, newValue) {
_super.prototype._onBindingContextChanged.call(this, oldValue, newValue);
if (this.items && this.items.length > 0) {
var i = 0;
var length = this.items.length;
for (; i < length; i++) {
this.items[i].bindingContext = newValue;
}
}
};
SegmentedBar.selectedBackgroundColorProperty = new dependencyObservable.Property("selectedBackgroundColor", "SegmentedBar", new proxy.PropertyMetadata(undefined));
SegmentedBar.selectedIndexProperty = new dependencyObservable.Property("selectedIndex", "SegmentedBar", new proxy.PropertyMetadata(undefined));
SegmentedBar.itemsProperty = new dependencyObservable.Property("items", "SegmentedBar", new proxy.PropertyMetadata(undefined));
SegmentedBar.selectedIndexChangedEvent = "selectedIndexChanged";
return SegmentedBar;
}(view.View));
exports.SegmentedBar = SegmentedBar;
|
'use strict';
module.exports = ({ app, controllers, authentication }) => {
const controller = controllers.auth;
const authRoute = '/api/auth';
app.post(authRoute + '/register', controller.register);
app.post(authRoute + '/login', controller.loginLocal);
app.get(authRoute + '/logout', controller.logout);
// app.get(authRoute + '//getLoggedUser', authController.getLoggedUser);
}
|
'use strict';
// Setting up route
angular.module('core').config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
// Redirect to home view when route not found
$urlRouterProvider.otherwise('/');
// Home state routing
$stateProvider.
state('home', {
url: '/',
templateUrl: 'modules/core/views/home.client.view.html'
}).
state('presupuesto',{
url: '/presupuesto',
templateUrl: 'modules/productos/views/productos.pedido.client.view.html'
});
}
]);
|
var m2pong = require('./m2pong');
Player = function(connection, name, nr){
this.connection = connection;
this.name = name;
this.nr = nr;
this.x = 0;
this.y = 0;
this.height = 0;
this.width = 0;
this.score = 0;
this.move = function(x, y){
this.x = x;
this.y = y;
m2pong.sendToDisplays('movePlayer', {
nr: this.nr,
x: this.x,
y: this.y
});
};
this.setScore = function(score){
this.score = score;
m2pong.sendToDisplays('setScore', {
nr: this.nr,
score: score
});
};
};
exports.Player = Player;
|
var _ = require("underscore");
var os = require("os");
var path = require("path");
var assert = require("assert");
// All of these functions are attached to files.js for the tool;
// they live here because we need them in boot.js as well to avoid duplicating
// a lot of the code.
//
// Note that this file does NOT contain any of the "perform I/O maybe
// synchronously" functions from files.js; this is intentional, because we want
// to make it very hard to accidentally use fs.*Sync functions in the app server
// after bootup (since they block all concurrency!)
var files = module.exports;
var toPosixPath = function (p, partialPath) {
// Sometimes, you can have a path like \Users\IEUser on windows, and this
// actually means you want C:\Users\IEUser
if (p[0] === "\\" && (! partialPath)) {
p = process.env.SystemDrive + p;
}
p = p.replace(/\\/g, '/');
if (p[1] === ':' && ! partialPath) {
// transform "C:/bla/bla" to "/c/bla/bla"
p = '/' + p[0] + p.slice(2);
}
return p;
};
var toDosPath = function (p, partialPath) {
if (p[0] === '/' && ! partialPath) {
if (! /^\/[A-Za-z](\/|$)/.test(p))
throw new Error("Surprising path: " + p);
// transform a previously windows path back
// "/C/something" to "c:/something"
p = p[1] + ":" + p.slice(2);
}
p = p.replace(/\//g, '\\');
return p;
};
var convertToOSPath = function (standardPath, partialPath) {
if (process.platform === "win32") {
return toDosPath(standardPath, partialPath);
}
return standardPath;
};
var convertToStandardPath = function (osPath, partialPath) {
if (process.platform === "win32") {
return toPosixPath(osPath, partialPath);
}
return osPath;
}
var convertToOSLineEndings = function (fileContents) {
return fileContents.replace(/\n/g, os.EOL);
};
var convertToStandardLineEndings = function (fileContents) {
// Convert all kinds of end-of-line chars to linuxy "\n".
return fileContents.replace(new RegExp("\r\n", "g"), "\n")
.replace(new RegExp("\r", "g"), "\n");
};
// Return the Unicode Normalization Form of the passed in path string, using
// "Normalization Form Canonical Composition"
const unicodeNormalizePath = (path) => {
return (path) ? path.normalize('NFC') : path;
};
// wrappings for path functions that always run as they were on unix (using
// forward slashes)
var wrapPathFunction = function (name, partialPaths) {
var f = path[name];
assert.strictEqual(typeof f, "function");
return function (/* args */) {
if (process.platform === 'win32') {
var args = _.toArray(arguments);
args = _.map(args, function (p, i) {
// if partialPaths is turned on (for path.join mostly)
// forget about conversion of absolute paths for Windows
return toDosPath(p, partialPaths);
});
var result = f.apply(path, args);
if (typeof result === "string") {
result = toPosixPath(result, partialPaths);
}
return result;
}
return f.apply(path, arguments);
};
};
files.pathJoin = wrapPathFunction("join", true);
files.pathNormalize = wrapPathFunction("normalize");
files.pathRelative = wrapPathFunction("relative");
files.pathResolve = wrapPathFunction("resolve");
files.pathDirname = wrapPathFunction("dirname");
files.pathBasename = wrapPathFunction("basename");
files.pathExtname = wrapPathFunction("extname");
// The path.isAbsolute function is implemented in Node v4.
files.pathIsAbsolute = wrapPathFunction("isAbsolute");
files.pathSep = '/';
files.pathDelimiter = ':';
files.pathOsDelimiter = path.delimiter;
files.convertToStandardPath = convertToStandardPath;
files.convertToOSPath = convertToOSPath;
files.convertToWindowsPath = toDosPath;
files.convertToPosixPath = toPosixPath;
files.convertToStandardLineEndings = convertToStandardLineEndings;
files.convertToOSLineEndings = convertToOSLineEndings;
files.unicodeNormalizePath = unicodeNormalizePath;
|
import DS from 'ember-data';
export default DS.Model.extend({
user: DS.belongsTo('user'),
userUsername: DS.attr('string'),
emailNotifications: DS.attr('boolean')
});
|
'use strict';
// Tasks controller
angular.module('tasks').controller('TasksController', ['$scope', '$stateParams', '$location', 'Authentication', 'Tasks',
function($scope, $stateParams, $location, Authentication, Tasks) {
$scope.authentication = Authentication;
$scope.bases = [
{name: 'Squat', lift: 'squat'},
{name: 'Deadlift', lift: 'deadlift'},
{name: 'Bench Press', lift: 'benchPress'},
{name: 'Clean and Jerk', lift: 'cleanJerk'},
{name: 'Snatch', lift: 'snatch'},
{name: 'Front Squat', lift: 'frontSquat'}
];
// Create new Task
$scope.create = function() {
// Create new Task object
var task = new Tasks ({
name: this.name,
description: this.description,
reps: this.reps,
sets: this.sets,
weights: this.weights,
baseLift: this.baseLift
});
// Redirect after save
task.$save(function(response) {
$location.path('workoutplans/' + response._id);
// Clear form fields
$scope.name = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Remove existing Task
$scope.remove = function(task) {
if ( task ) {
task.$remove();
for (var i in $scope.tasks) {
if ($scope.tasks [i] === task) {
$scope.tasks.splice(i, 1);
}
}
} else {
$scope.task.$remove(function() {
$location.path('tasks');
});
}
};
// Update existing Task
$scope.update = function() {
var task = $scope.task;
task.$update(function() {
$location.path('tasks/' + task._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Tasks
$scope.find = function() {
$scope.tasks = Tasks.query();
};
// Find existing Task
$scope.findOne = function() {
$scope.task = Tasks.get({
taskId: $stateParams.taskId
});
};
}
]);
|
angular
.module('eventApp', [
'ngResource',
'ui.bootstrap',
'ui.select',
'ui.bootstrap.datetimepicker',
'global',
'messagingApp',
'datasetApp'
])
.constant('HEK_URL', 'http://www.lmsal.com/hek/her')
.constant('HEK_QUERY_PARAMS', {
'cosec': 2, // ask for json
'cmd': 'search', // search command
'type': 'column',
'event_coordsys': 'helioprojective', //always specify wide coordinates, otherwise does not work
'x1': '-5000',
'x2': '5000',
'y1': '-5000',
'y2': '5000',
'return': 'event_type,event_starttime,event_endtime,kb_archivid,gs_thumburl,frm_name,frm_identifier', // limit the returned fields
'result_limit': 10, // limit the number of results
'event_type': '**', // override to only select some event types
'event_starttime': new Date(Date.UTC(1975, 9, 1)).toISOString(), // The first HEK event is in september 1975
'event_endtime': new Date().toISOString()
})
.constant('HEK_GET_PARAMS', {
'cosec': 2, // ask for json
'cmd': 'export-voevent' // search command
})
.constant('EVENT_TYPES', {
AR : 'Active Region',
CE : 'CME',
CD : 'Coronal Dimming',
CH : 'Coronal Hole',
CW : 'Coronal Wave',
FI : 'Filament',
FE : 'Filament Eruption',
FA : 'Filament Activation',
FL : 'Flare',
C_FL : 'Flare (C1+)',
M_FL : 'Flare (M1+)',
X_FL : 'Flare (X1+)',
LP : 'Loop',
OS : 'Oscillation',
SS : 'Sunspot',
EF : 'Emerging Flux',
CJ : 'Coronal Jet',
PG : 'Plage',
OT : 'Other',
NR : 'Nothing Reported',
SG : 'Sigmoid',
SP : 'Spray Surge',
CR : 'Coronal Rain',
CC : 'Coronal Cavity',
ER : 'Eruption',
TO : 'Topological Object'
});
|
'use strict';
module.exports = {
db: 'mongodb://localhost/qaapp-dev',
//db: 'mongodb://nodejitsu:e0b737c9d532fc27e1e753a25a4f823e@troup.mongohq.com:10001/nodejitsudb3924701379',
mongoose: {
debug: true
},
app: {
name: 'AskOn'
},
facebook: {
clientID: 'DEFAULT_APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/facebook/callback'
},
twitter: {
clientID: 'DEFAULT_CONSUMER_KEY',
clientSecret: 'CONSUMER_SECRET',
callbackURL: 'http://localhost:3000/auth/twitter/callback'
},
github: {
clientID: 'DEFAULT_APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/github/callback'
},
google: {
clientID: 'DEFAULT_APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/google/callback'
},
linkedin: {
clientID: 'DEFAULT_API_KEY',
clientSecret: 'SECRET_KEY',
callbackURL: 'http://localhost:3000/auth/linkedin/callback'
},
emailFrom: 'SENDER EMAIL ADDRESS', // sender address like ABC <abc@example.com>
mailer: {
service: 'SERVICE_PROVIDER', // Gmail, SMTP
auth: {
user: 'EMAIL_ID',
pass: 'PASSWORD'
}
}
};
|
module.exports = function ( grunt ) {
grunt.initConfig( {
pkg: grunt.file.readJSON( 'package.json' ),
banner: '/*!\n' +
'* <%= pkg.name %> v<%= pkg.version %> - <%= pkg.description %>\n' +
'* Copyright (c) <%= grunt.template.today(\'yyyy\') %> <%= pkg.author %>. All rights reserved.\n' +
'* Licensed under <%= pkg.license %> License.\n' +
'*/',
connect: {
docs: {
options: {
protocol: 'http',
port: 8080,
hostname: 'localhost',
livereload: true,
base: {
path: 'docs/',
options: {
index: 'index.htm'
}
},
open: 'http://localhost:8080/index.htm'
}
}
},
sass: {
docs: {
options: {
style: 'expanded'
},
files: {
'dist/autoc.css': 'src/sass/autoc.scss',
'docs/css/layout.css': 'sass/layout.scss'
}
}
},
csslint: {
docs: {
options: {
'bulletproof-font-face': false,
'order-alphabetical': false,
'box-model': false,
'vendor-prefix': false,
'known-properties': false
},
src: [
'dist/autoc.css',
'docs/css/layout.css'
]
}
},
cssmin: {
dist: {
files: {
'dist/autoc.min.css': [
'dist/autoc.css'
]
}
},
docs: {
files: {
'docs/css/layout.min.css': [
'node_modules/normalize.css/normalize.css',
'docs/css/layout.css',
'dist/autoc.css'
]
}
}
},
jshint: {
src: {
options: {
jshintrc: '.jshintrc'
},
src: [
'src/**/*.js'
],
filter: 'isFile'
}
},
uglify: {
options: {
banner: '<%= banner %>'
},
docs: {
files: {
'docs/js/autoc.min.js': [
'src/autoc.js'
]
}
},
dist: {
files: {
'dist/autoc.min.js': [
'src/autoc.js'
]
}
}
},
copy: {
docs: {
files: [
{
'docs/js/jquery.js': 'node_modules/jquery/dist/jquery.js'
}
]
},
dist: {
files: [
{
'dist/autoc.js': 'src/autoc.js'
}
]
}
},
pug: {
docs: {
options: {
pretty: true,
data: {
debug: true
}
},
files: {
// create api home page
'docs/index.htm': 'pug/api/index.pug'
}
}
},
watch: {
css: {
files: [
'sass/**/**.scss'
],
tasks: [
'sass',
'csslint',
'cssmin'
]
},
js: {
files: [
'src/**/*.js'
],
tasks: [
'jshint:src',
'uglify',
'copy:docs'
]
},
pug: {
files: [
'pug/**/**.pug'
],
tasks: [
'pug:docs'
]
},
docs: {
files: [
'docs/**/**.html',
'docs/**/**.js',
'docs/**/**.css'
],
options: {
livereload: true
}
}
}
} );
grunt.loadNpmTasks( 'grunt-contrib-connect' );
grunt.loadNpmTasks( 'grunt-contrib-copy' );
grunt.loadNpmTasks( 'grunt-contrib-sass' );
grunt.loadNpmTasks( 'grunt-contrib-csslint' );
grunt.loadNpmTasks( 'grunt-contrib-cssmin' );
grunt.loadNpmTasks( 'grunt-contrib-jshint' );
grunt.loadNpmTasks( 'grunt-contrib-uglify' );
grunt.loadNpmTasks( 'grunt-contrib-pug' );
grunt.loadNpmTasks( 'grunt-contrib-watch' );
grunt.registerTask( 'html', [ 'pug' ] );
grunt.registerTask( 'http', [
'connect:docs',
'watch'
] );
grunt.registerTask( 'hint', [ 'jshint:src' ] );
grunt.registerTask( 'scripts', [
'jshint',
'uglify',
'copy'
] );
grunt.registerTask( 'styles', [
'sass',
'csslint',
'cssmin'
] );
grunt.registerTask( 'default', [
'connect:docs',
'sass',
'csslint',
'cssmin',
'jshint:src',
'uglify',
'copy',
'pug',
'watch'
] );
};
|
/*
setInterval(function() {
console.log(document.activeElement);
}, 1000);
*/
/*
* Notes regarding app state/modes, activeElements, focusing etc.
* ==============================================================
*
* 1) There is always exactly one item selected. All executed commands
* operate on this item.
*
* 2) The app distinguishes three modes with respect to focus:
* 2a) One of the UI panes has focus (inputs, buttons, selects).
* Keyboard shortcuts are disabled.
* 2b) Current item is being edited. It is contentEditable and focused.
* Blurring ends the edit mode.
* 2c) ELSE the Clipboard is focused (its invisible textarea)
*
* In 2a, we try to lose focus as soon as possible
* (after clicking, after changing select's value), switching to 2c.
*
* 3) Editing mode (2b) can be ended by multiple ways:
* 3a) By calling current.stopEditing();
* this shall be followed by some resolution.
* 3b) By executing MM.Command.{Finish,Cancel};
* these call 3a internally.
* 3c) By blurring the item itself (by selecting another);
* this calls MM.Command.Finish (3b).
* 3b) By blurring the currentElement;
* this calls MM.Command.Finish (3b).
*
*/
MM.App = {
keyboard: null,
current: null,
editing: false,
history: [],
historyIndex: 0,
portSize: [0, 0],
map: null,
ui: null,
io: null,
help: null,
_port: null,
_throbber: null,
_drag: {
pos: [0, 0],
item: null,
ghost: null
},
_fontSize: 100,
action: function(action) {
if (this.historyIndex < this.history.length) { /* remove undoed actions */
this.history.splice(this.historyIndex, this.history.length-this.historyIndex);
}
this.history.push(action);
this.historyIndex++;
action.perform();
return this;
},
setMap: function(map) {
if (this.map) { this.map.hide(); }
this.history = [];
this.historyIndex = 0;
this.map = map;
this.map.show(this._port);
},
select: function(item) {
if (this.current && this.current != item) { this.current.deselect(); }
this.current = item;
this.current.select();
},
adjustFontSize: function(diff) {
this._fontSize = Math.max(30, this._fontSize + 10*diff);
this._port.style.fontSize = this._fontSize + "%";
this.map.update();
this.map.ensureItemVisibility(this.current);
},
handleMessage: function(message, publisher) {
switch (message) {
case "ui-change":
this._syncPort();
break;
case "item-change":
if (publisher.isRoot() && publisher.getMap() == this.map) {
document.title = this.map.getName() + " :: 启示工作室";
}
break;
}
},
handleEvent: function(e) {
switch (e.type) {
case "resize":
this._syncPort();
break;
case "beforeunload":
e.preventDefault();
return "";
break;
}
},
setThrobber: function(visible) {
this._throbber.classList[visible ? "add" : "remove"]("visible");
},
init: function() {
this._port = document.querySelector("#port");
this._throbber = document.querySelector("#throbber");
this.ui = new MM.UI();
this.io = new MM.UI.IO();
this.help = new MM.UI.Help();
MM.Tip.init();
MM.Keyboard.init();
MM.Menu.init(this._port);
MM.Mouse.init(this._port);
MM.Clipboard.init();
window.addEventListener("resize", this);
window.addEventListener("beforeunload", this);
MM.subscribe("ui-change", this);
MM.subscribe("item-change", this);
this._syncPort();
this.setMap(new MM.Map());
},
_syncPort: function() {
this.portSize = [window.innerWidth - this.ui.getWidth(), window.innerHeight];
this._port.style.width = this.portSize[0] + "px";
this._port.style.height = this.portSize[1] + "px";
this._throbber.style.right = (20 + this.ui.getWidth())+ "px";
if (this.map) { this.map.ensureItemVisibility(this.current); }
}
}
|
'use strict';
// Setting up route
angular.module('publications').config(['$stateProvider',
function ($stateProvider) {
// publications state routing
$stateProvider
.state('publications', {
abstract: true,
url: '/publications',
template: '<ui-view/>'
})
.state('publications.list', {
url: '',
templateUrl: 'modules/publications/client/views/list-publications.client.view.html',
data: {
roles: ['user', 'admin']
}
})
.state('publications.search', {
url: '/search',
templateUrl: 'modules/publications/client/views/pagination-publications.client.view.html',
data: {
roles: ['user', 'admin']
}
})
.state('publications.create', {
url: '/create',
templateUrl: 'modules/publications/client/views/create-publication.client.view.html',
data: {
roles: ['user', 'admin']
}
})
.state('publications.view', {
url: '/:publicationId',
templateUrl: 'modules/publications/client/views/view-publication.client.view.html',
data: {
roles: ['user', 'admin']
}
})
.state('publications.edit', {
url: '/:publicationId/edit',
templateUrl: 'modules/publications/client/views/edit-publication.client.view.html',
data: {
roles: ['user', 'admin']
}
});
}
]);
|
define(function() {
var ctor = function () {
};
//Note: This module exports a function. That means that you, the developer, can create multiple instances.
//This pattern is also recognized by Durandal so that it can create instances on demand.
//If you wish to create a singleton, you should export an object instead of a function.
return ctor;
});
|
import should from 'should';
import Schema from '../../src/schema';
const SIMPEL_OBJECT = {
type: 'object',
properties: {
name: { type: 'string' }
}
};
describe('Schema', () => {
describe('#getType', () => {
it('should return string type for child', () => {
const schema = new Schema(SIMPEL_OBJECT);
schema.getType('name').should.equal('string');
});
});
describe('#isObject', () => {
it('should return true with no path', () => {
const schema = new Schema(SIMPEL_OBJECT);
const r = schema.isObject();
r.should.equal(true);
});
it('should return false with name path', () => {
const schema = new Schema(SIMPEL_OBJECT);
const r = schema.isObject('name');
r.should.equal(false);
});
});
describe('#getProperties', () => {
it('should return array with length same as properties', () => {
const schema = new Schema(SIMPEL_OBJECT);
const r = schema.getProperties();
Object.keys(r).length.should.equal(1);
});
});
});
|
import { key, PLAY, PAUSE, MUTE, UNMUTE, UPDATE_VOLUME, UPDATE_TIME, SET_SONG, SET_TIME, updateTime } from './actions'
import { store } from '../store'
let audio = new Audio()
audio.addEventListener('timeupdate', event => store.dispatch(updateTime(event)))
const initialState = {
isPlaying: false,
muted: false,
volume: audio.volume,
src: '',
currentTime: '',
duration: 0.0,
completed: 0.0
}
export const selectors = {
audio: state => state[key].audio
}
export default function reducer (state = initialState, { type, payload }) {
switch (type) {
case PLAY:
{
audio.play()
return { ...state, isPlaying: !state.isPlaying }
}
case PAUSE:
{
audio.pause()
return { ...state, isPlaying: !state.isPlaying }
}
case MUTE:
{
audio.muted = true
return { ...state, muted: true }
}
case UNMUTE:
{
audio.muted = false
return { ...state, muted: false }
}
case UPDATE_TIME:
{
const { currentTime, duration, completed } = payload
return { ...state, currentTime, duration, completed }
}
case UPDATE_VOLUME:
{
audio.volume = payload
return { ...state, volume: payload }
}
case SET_TIME:
{
const newCurrentTime = state.currentTime * parseFloat(payload) / 100
audio.currentTime = newCurrentTime
return { ...state, currentTime: newCurrentTime }
}
case SET_SONG:
{
audio.src = payload
return { ...state, src: payload }
}
default:
return state
}
}
|
/* eslint-env mocha */
import expect from 'expect';
import FunctionChecker from '../src/FunctionChecker.js';
import OptionsManager from '../src/OptionsManager.js';
import Structure from '../src/Structure.js';
describe('optionsManager', () => {
let manager;
beforeEach(() => {
manager = new OptionsManager();
});
context('#constructor', () => {
it('exposes .typeManager', () => {
expect(manager.typeManager).toNotBe(undefined);
});
});
context('#structure', () => {
it('returns a Structure object', () => {
expect(manager.structure('arg1', {type: 'string'})).toBeA(Structure);
});
});
context('#check', () => {
it('returns a FunctionChecker object', () => {
expect(manager.check('customFunc')).toBeA(FunctionChecker);
});
});
});
|
angular.module('schemaForm').config(
['schemaFormProvider', 'schemaFormDecoratorsProvider', 'sfPathProvider',
function(schemaFormProvider, schemaFormDecoratorsProvider, sfPathProvider) {
var download = function(name, schema, options) {
if (schema.type === 'string' && schema.format === 'download') {
var f = schemaFormProvider.stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'download';
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
schemaFormProvider.defaults.string.unshift(download);
//Add to the bootstrap directive
schemaFormDecoratorsProvider.addMapping(
'bootstrapDecorator',
'download',
'directives/decorators/bootstrap/download/angular-schema-form-download.html'
);
schemaFormDecoratorsProvider.createDirective(
'download',
'directives/decorators/bootstrap/download/angular-schema-form-download.html'
);
}
]);
angular.module('schemaForm').directive('downloadOptions', function() {
return {
restrict : 'A',
controller : function($scope, $rootScope) {
$scope.notifyClick = function(ele) {
$rootScope.$emit('DownloadTriggered', {
element : ele
})
};
},
link : function(scope, ele, attr) {
angular.element(ele).click(function() {
scope.notifyClick(ele);
});
}
};
});
|
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
// 'use strict';
// global
var data = {
"taskCount": 0,
"tasks": []
}
var count = 0;
// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
initializePage();
})
function saveText(text, filename){
var a = document.createElement('a');
a.setAttribute('href', 'data:text/plain;charset=utf-u,'+encodeURIComponent(text));
a.setAttribute('download', filename);
a.click()
}
function writeToFile(d1, d2){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data2.json", 8, false, 0);
fh.WriteLine(d1 + ',' + d2);
fh.Close();
}
/*
* Function that is called when the document is ready.
*/
function initializePage() {
// add any functionality and listeners you want here
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
var saveTask = document.getElementById("saveTask");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("blarg")[0];
// When the user clicks on the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
saveTask.onclick = function createDiv() {
var newDiv = document.createElement("div");
//newDiv.id = "displayName"+count;
newDiv.innerHTML =
'<div class="panel panel-default">' +
'<div class="panel-heading clearfix">' +
'<h3 class="panel-title pull-left"><span id="displayName'+count+'"></span></h3>'+
'<a class="btn btn-primary pull-right" href="#">'+
'<i class="fa fa-pencil"></i>'+
'Edit'+
'</a>'+
'</div>'+
'<div class="list-group">'+
'<div class="list-group-item">'+
'<p class="list-group-item-text">Reward</p>'+
'<h4 class="list-group-item-heading"><span id="displayReward'+count+'"></span></h4>'+
'</div>'+
'<div class="list-group-item">'+
'<p class="list-group-item-text"><span id="displayDescription'+count+'"></p>'+
'</div>'+
'</div>'+
'<div class="panel-footer">'+
'<small></small>'+
'</div>'+
'</div>';
var currentDiv = document.getElementById("tasks");
currentDiv.appendChild(newDiv);
var a = document.getElementById('displayName'+count).innerHTML =
document.getElementById("taskName").value;
var b =document.getElementById('displayReward'+count).innerHTML =
document.getElementById("taskReward").value;
var c = document.getElementById('displayDescription'+count).innerHTML =
document.getElementById("taskDescription").value;
// I've tried a lot of json writing under here but it did not work , even simple ones
data.tasks.push({
"taskName":a,
"taskReward":b,
"taskDescription":c
});
data.taskCount++;
count++;
// writeData();
// USE THIS TO CLEAR LOCAL STORAGE
// window.localStorage.clear();
//THIS SAVES CRAP TO LOCAL STORAGE.
var json = JSON.stringify(data);
localStorage.setItem('task'+count, json);
var fs = require('fs');
fs.writeFile('data2.json', json, 'utf8', callback);
// looping just to see whats in storage
// for(var i = 0; i < 5; i++)
// console.log(JSON.parse(localStorage.getItem('task'+i)))
modal.style.display = "none";
return data;
};
}
},{"fs":2}],2:[function(require,module,exports){
},{}]},{},[1]);
|
'use strict';
describe('service', function() {
var countKeys = function(data) {
var count = 0
for(var k in data) {
count++;
}
return count;
}
// load modules
beforeEach(module('mavrixAgenda'));
// Test service availability
it('check the existence of Storage factory', inject(function(usersSrv) {
expect(usersSrv).toBeDefined();
}));
// Test users
it('testing set/get users', inject(function(usersSrv){
usersSrv.setCurrentUser("test-user");
var user = usersSrv.getCurrentUser();
expect(user).toBe("test-user");
}));
});
|
var crossBrowser = function (browser, x, y) {
if (browser === 'Firefox 39') {
x = x - 490;
y = y + 10;
} else if (browser === 'MSIE 10') {
x = x - 588.7037353;
y = y + 3 - 0.32638931;
} else if (browser === 'IE 11') {
x = x - 641;
y = y + 2.5;
} else if (browser === 'Opera 12') {
x = x - 500;
}
return {
x: x,
y: y
}
};
|
/* ************************************************************************
*
* qxcompiler - node.js based replacement for the Qooxdoo python
* toolchain
*
* https://github.com/qooxdoo/qooxdoo-compiler
*
* Copyright:
* 2011-2018 Zenesis Limited, http://www.zenesis.com
*
* License:
* MIT: https://opensource.org/licenses/MIT
*
* This software is provided under the same licensing terms as Qooxdoo,
* please see the LICENSE file in the Qooxdoo project's top-level directory
* for details.
*
* Authors:
* * John Spackman (john.spackman@zenesis.com, @johnspackman)
*
* ************************************************************************/
qx.Class.define("testapp.test.TestPlugins", {
extend: qx.dev.unit.TestCase,
members: {
testSimple: function() {
qx.io.PartLoader.require(["pluginFramework", "pluginOne"], () => {
this.debug("pluginOne loaded");
var plugin = new testapp.plugins.PluginOne();
this.assertEquals("testapp.plugins.PluginOne: Plugin One Hello\n", plugin.sayHello());
}, this);
qx.io.PartLoader.require(["pluginFramework", "pluginTwo"], () => {
this.debug("pluginTwo loaded");
var plugin = new testapp.plugins.PluginTwo();
this.assertEquals("testapp.plugins.PluginTwo: Plugin One Hello\n", plugin.sayHello());
}, this);
}
}
});
|
/*
* Background sketch
* Author: Uriel Sade
* Date: Feb. 22, 2017
*/
var canvas;
var time_x, time_y, time_z, time_inc;
var field = [];
var particles = [];
var rows, cols;
var scl = 20;
function setup() {
canvas = createCanvas(windowWidth, windowHeight);
canvas.position(0,0);
canvas.style('z-value', '-1');
canvas.style('opacity', '0.99');
background(0,0,0,0);
rows = 25;
scl = floor(height/rows);
cols = floor(width/scl);
time_inc = 0.2;
time_x = time_y = time_z = 0;
for(var i = 0; i < 20; i++){
particles[i] = new Particle();
}
}
function draw(){
background(0,0,0,10);
fill(255);
// text("by Uriel Sade", width/40, height- height/40);
noFill();
field = [];
time_y = 0;
for(var y = 0; y < rows; y++){
time_x = 0;
for(var x = 0; x < cols; x++){
push();
translate(x*scl + scl/2, y*scl + scl/2);
var direction_vector = p5.Vector.fromAngle(noise(time_x, time_y, time_z)*2*PI + PI);
rotate(direction_vector.heading());
stroke(0,255,0, 7);
strokeWeight(1);
line(-scl/6,0,scl/6,0);
pop();
field[y* cols + x] = direction_vector;
time_x += time_inc;
}
time_y += time_inc;
time_z += 0.0002;
}
updateParticles();
}
function updateParticles(){
for(var i = 0; i < particles.length; i++){
particles[i].accelerate(field);
}
}
function windowResized(){
setup();
}
|
'use strict';
/* Filters */
angular.module('multi-screen-demo.filters', [
]).
// create your own filter here
filter('yourFilterName', function () {
return function () {
return;
};
});
|
import test from 'tape'
import { forEach, get, isArray, isMatch, isNumber, omit } from 'lodash'
import {
entityDel, ENTITY_DEL, entityPut, ENTITY_PUT, entityPutAll, ENTITY_PUTALL,
entityUpdate, ENTITY_UPDATE, pickTypeId, tripleDel, TRIPLE_DEL, triplePut, TRIPLE_PUT,
} from '../src'
import { agent, creator, item, mainEntity } from './mock'
test('entityDel', (t) => {
const act = entityDel(creator)
t.equal(act.type, ENTITY_DEL)
t.deepEqual(act.payload, pickTypeId(creator))
t.end()
})
test('entityPut', (t) => {
const act = entityPut(creator)
t.equal(act.type, ENTITY_PUT)
t.ok(isNumber(act.payload.dateCreated))
t.ok(isMatch(act.payload, creator))
t.end()
})
function testIsMatch(t, object, prototype, str) {
forEach(prototype, (val, key) => {
t.equal(get(object, key), val, str + key)
})
}
test('entityPutAll', (t) => {
const act = entityPutAll([ agent, creator, item, mainEntity ])
t.equal(act.type, ENTITY_PUTALL)
t.ok(isArray(act.payload))
t.equal(act.payload.length, 4)
t.ok(isNumber(act.payload[0].dateCreated), '0 dateCreated number')
t.ok(isMatch(act.payload[0], agent))
t.ok(isNumber(act.payload[1].dateCreated), '1 dateCreated number')
t.ok(isMatch(act.payload[1], creator))
t.ok(isNumber(act.payload[2].dateCreated), '2 dateCreated number')
testIsMatch(t, act.payload[2], item, 'payload 3: ')
t.ok(isNumber(act.payload[3].dateCreated), '3 dateCreated number')
t.ok(isMatch(act.payload[3], omit(mainEntity, 'dog')))
t.end()
})
test('entityUpdate', (t) => {
const act = entityUpdate(creator)
t.equal(act.type, ENTITY_UPDATE)
t.false(isNumber(act.payload.dateCreated))
t.ok(isNumber(act.payload.dateModified))
t.end()
})
test('triplePut', (t) => {
const act = triplePut({ subject: creator, predicate: 'item', object: item, extra: true })
t.equal(act.type, TRIPLE_PUT, 'action type')
t.deepEqual(act.payload, {
predicate: 'item', subject: pickTypeId(creator), object: pickTypeId(item),
})
t.end()
})
test('tripleDel', (t) => {
const act = tripleDel({ subject: creator, predicate: 'item', object: item, single: true })
t.equal(act.type, TRIPLE_DEL, 'action type')
t.deepEqual(act.payload, {
predicate: 'item', subject: pickTypeId(creator), object: null, single: true,
})
const act2 = tripleDel({ subject: creator, predicate: 'item', object: item })
t.deepEqual(act2.payload, {
predicate: 'item', subject: pickTypeId(creator), object: pickTypeId(item),
})
t.end()
})
|
var searchData=
[
['neighbours',['neighbours',['../struct_parser_1_1_cell_atom_grammar.html#a6367dce3041506f4112c82e2ba5998a9',1,'Parser::CellAtomGrammar']]],
['newgrid',['newGrid',['../struct_compiler_1_1_state.html#a3a949d5132b7854fee15d6d13344652c',1,'Compiler::State']]]
];
|
'use strict';
/* http://docs.angularjs.org/guide/dev_guide.e2e-testing */
describe('my app', function() {
beforeEach(function() {
browser().navigateTo('app/index-old.html');
});
it('should automatically redirect to /view1 when location hash/fragment is empty', function() {
expect(browser().location().url()).toBe("/view1");
});
describe('view1', function() {
beforeEach(function() {
browser().navigateTo('#/view1');
});
it('should render view1 when user navigates to /view1', function() {
expect(element('[ng-view] p:first').text()).
toMatch(/partial for view 1/);
});
});
describe('view2', function() {
beforeEach(function() {
browser().navigateTo('#/view2');
});
it('should render view2 when user navigates to /view2', function() {
expect(element('[ng-view] p:first').text()).
toMatch(/partial for view 2/);
});
});
});
|
export default from './Input';
|
app.router = Backbone.Router.extend({
el : $('main'),
routes: {
// '': 'home',
// '!/': 'home',
'!/event-list/': function () {
app.preRoute('event-list', this.el);
new app.eventListView({ el: this.el });
},
'!/event-detail/:key': function (key) {
app.preRoute('event-detail', this.el);
new app.eventDetailView({ el: this.el, key: key });
},
'!/event-create/': function () {
app.preRoute('event-create', this.el);
new app.eventCreateView({ el: this.el });
},
'!/account/': function () {
app.preRoute('account', this.el);
new app.accountView({ el: this.el });
},
},
initialize: function () {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
Backbone.history.start();
new app.headerView();
new app.footerView();
// TODO: hook up email verification
// if (!user.emailVerified)
// firebase.auth().currentUser.sendEmailVerification()
var database = firebase.database();
var currentUser = firebase.auth().currentUser;
// add user to database of users
// TODO: show add photo wizard if no photo
database.ref('users/' + currentUser.uid).update({
email: currentUser.email,
displayName: currentUser.displayName,
});
} else {
window.location = '/';
}
}, function(error) {
console.error(error);
});
},
// home: function () {
// app.preRoute(this.el);
// new app.homeView({ el: this.el });
// },
});
$(function () {
app.router = new app.router();
});
|
"use strict";
const mongoose = require('mongoose');
module.exports = (()=>{
mongoose.connect('mongodb://192.168.56.101:30000/blog');
let db = mongoose.connection;
db.on('error', function(err){
console.log(err);
});
db.once('open', (err)=> {
console.log('connect success');
})
})();
|
/* eslint-disable */
"use strict";
var express = require("express"),
path = require("path"),
webpack = require("webpack"),
config = require("./examples.config");
config.module.loaders[0].query = {presets: ["react-hmre"]};
config.entry.unshift("webpack-hot-middleware/client");
config.plugins = [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
];
var app = express();
var compiler = webpack(config);
app.use(require("webpack-dev-middleware")(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.use(require("webpack-hot-middleware")(compiler));
app.use(express.static(path.resolve(process.cwd(), "examples")));
app.get("*", function(req, res) {
res.sendFile(path.join(__dirname, "examples", "index.html"));
});
app.listen(3000, "localhost", function(err) {
if (err) {
console.log(err);
return;
}
console.log("Listening at http://localhost:3000");
});
|
import { $, util } from './util-node'
import Taglet from './taglet'
var
lace,
version = '1.0.0',
defaults = {
opts: {}
},
warehouse = {
singleton: null,
compiled_dom: null,
laces: {
global: null
},
taglets: {}
}
;
class Lace {
constructor(name) {
this.name = name;
}
/**
*
* @param name
* @param def
* @param global, true when make available only for this lace
* @returns {*}
*/
annotation(name, def, global = false) {
/*if (typeof def !== Type.UNDEFINED) {
this.definition('annotation', name, def);
}
return this.instance('annotation', name);*/
}
taglet(name, def, global = false) {
/*if (typeof def !== Type.UNDEFINED) {
this.definition('taglet', name, def);
}
return this.instance('taglet', name);*/
}
compile() {
}
render(template, data) {
var $tmpl = $(template);
console.log($tmpl);
}
definition(type, name, def) {
return this.__lace__[type]['definitions'][name] = def || this.__lace__[type]['definitions'][name];
}
instance(type, name, inst) {
return this.__lace__[type]['instances'][name] = inst || this.__lace__[type]['instances'][name];
}
}
//TODO: should I declare in prototype?
Lace.prototype.__lace__ = {
annotation: {
definitions: {},
instances: {}
},
taglet: {
definitions: {},
instances: {}
}
};
Lace.init = function (name) {
return warehouse.laces[name] = warehouse.laces[name] || new Lace(name);
};
Lace.parse = function(template) {
};
/**
* MODULE function for lace
* @param name
* @returns {Function|*}
*/
lace = function(name) {
name = name || 'global';
return Lace.init(name);
};
export default lace;
|
import angular from 'rollup-plugin-angular';
import commonjs from 'rollup-plugin-commonjs';
import nodeResolve from 'rollup-plugin-node-resolve';
import typescript from 'rollup-plugin-typescript';
import uglify from 'rollup-plugin-uglify';
import { minify } from 'uglify-es';
// rollup-plugin-angular addons
import sass from 'node-sass';
import CleanCSS from 'clean-css';
import { minify as minifyHtml } from 'html-minifier';
const cssmin = new CleanCSS();
const htmlminOpts = {
caseSensitive: true,
collapseWhitespace: true,
removeComments: true,
};
export default {
input: 'dist/index.js',
output: {
// core output options
file: 'dist/bundle.umd.js', // required
format: 'umd', // required
name: 'ngx-form.element',
globals: {
'@angular/core': 'ng.core',
'rxjs/Subject': 'Subject',
'@angular/forms': 'ng.forms',
'@ngx-core/common': 'ngx-core.common',
'@ngx-form/interface': 'ngx-form.interface',
'@angular/common': 'ng.common',
'@angular/material': 'ng.material'
},
// advanced output options
// paths: ,
// banner: ,
// footer: ,
// intro:,
// outro: ,
sourcemap: true, // true | inline
// sourcemapFile: ,
// interop: ,
// danger zone
exports: 'named',
// amd: ,
// indent: ,
// strict:
},
onwarn,
plugins: [
angular({
preprocessors: {
template: template => minifyHtml(template, htmlminOpts),
style: scss => {
const css = sass.renderSync({ data: scss }).css;
return cssmin.minify(css).styles;
},
}
}),
commonjs(),
nodeResolve({
// use "module" field for ES6 module if possible
module: true, // Default: true
// use "jsnext:main" if possible
// – see https://github.com/rollup/rollup/wiki/jsnext:main
jsnext: true, // Default: false
// use "main" field or index.js, even if it's not an ES6 module
// (needs to be converted from CommonJS to ES6
// – see https://github.com/rollup/rollup-plugin-commonjs
main: true, // Default: true
// some package.json files have a `browser` field which
// specifies alternative files to load for people bundling
// for the browser. If that's you, use this option, otherwise
// pkg.browser will be ignored
browser: true, // Default: false
// not all files you want to resolve are .js files
extensions: [ '.js', '.json' ], // Default: ['.js']
// whether to prefer built-in modules (e.g. `fs`, `path`) or
// local ones with the same names
preferBuiltins: true, // Default: true
// Lock the module search in this path (like a chroot). Module defined
// outside this path will be mark has external
jail: '/src', // Default: '/'
// If true, inspect resolved files to check that they are
// ES2015 modules
modulesOnly: false, // Default: false
// Any additional options that should be passed through
// to node-resolve
customResolveOptions: {}
}),
typescript({
typescript: require('./node_modules/typescript')
}),
uglify({}, minify)
]
};
function onwarn(message) {
const suppressed = [
'UNRESOLVED_IMPORT',
'THIS_IS_UNDEFINED'
];
if (!suppressed.find(code => message.code === code)) {
return console.warn(message.message);
}
}
|
import isEnabled from 'ember-metal/features';
import run from 'ember-metal/run_loop';
import { observer } from 'ember-metal/mixin';
import { set } from 'ember-metal/property_set';
import { bind } from 'ember-metal/binding';
import {
beginPropertyChanges,
endPropertyChanges
} from 'ember-metal/property_events';
import { testBoth } from 'ember-metal/tests/props_helper';
import EmberObject from 'ember-runtime/system/object';
import { peekMeta } from 'ember-metal/meta';
QUnit.module('ember-runtime/system/object/destroy_test');
testBoth('should schedule objects to be destroyed at the end of the run loop', function(get, set) {
var obj = EmberObject.create();
var meta;
run(function() {
obj.destroy();
meta = peekMeta(obj);
ok(meta, 'meta is not destroyed immediately');
ok(get(obj, 'isDestroying'), 'object is marked as destroying immediately');
ok(!get(obj, 'isDestroyed'), 'object is not destroyed immediately');
});
meta = peekMeta(obj);
ok(!meta, 'meta is destroyed after run loop finishes');
ok(get(obj, 'isDestroyed'), 'object is destroyed after run loop finishes');
});
if (isEnabled('mandatory-setter')) {
// MANDATORY_SETTER moves value to meta.values
// a destroyed object removes meta but leaves the accessor
// that looks it up
QUnit.test('should raise an exception when modifying watched properties on a destroyed object', function() {
var obj = EmberObject.extend({
fooDidChange: observer('foo', function() { })
}).create({
foo: 'bar'
});
run(function() {
obj.destroy();
});
throws(function() {
set(obj, 'foo', 'baz');
}, Error, 'raises an exception');
});
}
QUnit.test('observers should not fire after an object has been destroyed', function() {
var count = 0;
var obj = EmberObject.extend({
fooDidChange: observer('foo', function() {
count++;
})
}).create();
obj.set('foo', 'bar');
equal(count, 1, 'observer was fired once');
run(function() {
beginPropertyChanges();
obj.set('foo', 'quux');
obj.destroy();
endPropertyChanges();
});
equal(count, 1, 'observer was not called after object was destroyed');
});
QUnit.test('destroyed objects should not see each others changes during teardown but a long lived object should', function () {
var shouldChange = 0;
var shouldNotChange = 0;
var objs = {};
var A = EmberObject.extend({
objs: objs,
isAlive: true,
willDestroy() {
this.set('isAlive', false);
},
bDidChange: observer('objs.b.isAlive', function () {
shouldNotChange++;
}),
cDidChange: observer('objs.c.isAlive', function () {
shouldNotChange++;
})
});
var B = EmberObject.extend({
objs: objs,
isAlive: true,
willDestroy() {
this.set('isAlive', false);
},
aDidChange: observer('objs.a.isAlive', function () {
shouldNotChange++;
}),
cDidChange: observer('objs.c.isAlive', function () {
shouldNotChange++;
})
});
var C = EmberObject.extend({
objs: objs,
isAlive: true,
willDestroy() {
this.set('isAlive', false);
},
aDidChange: observer('objs.a.isAlive', function () {
shouldNotChange++;
}),
bDidChange: observer('objs.b.isAlive', function () {
shouldNotChange++;
})
});
var LongLivedObject = EmberObject.extend({
objs: objs,
isAliveDidChange: observer('objs.a.isAlive', function () {
shouldChange++;
})
});
objs.a = new A();
objs.b = new B();
objs.c = new C();
new LongLivedObject();
run(function () {
var keys = Object.keys(objs);
for (var i = 0; i < keys.length; i++) {
objs[keys[i]].destroy();
}
});
equal(shouldNotChange, 0, 'destroyed graph objs should not see change in willDestroy');
equal(shouldChange, 1, 'long lived should see change in willDestroy');
});
QUnit.test('bindings should be synced when are updated in the willDestroy hook', function() {
var bar = EmberObject.create({
value: false,
willDestroy() {
this.set('value', true);
}
});
var foo = EmberObject.create({
value: null,
bar: bar
});
run(function() {
bind(foo, 'value', 'bar.value');
});
ok(bar.get('value') === false, 'the initial value has been bound');
run(function() {
bar.destroy();
});
ok(foo.get('value'), 'foo is synced when the binding is updated in the willDestroy hook');
});
|
var axios = require('axios')
module.exports = function (app) {
app.get('/context_all.jsonld', function (req, res) {
axios.get(app.API_URL + 'context_all.jsonld')
.then(function (response) {
res.type('application/ld+json')
res.status(200).send(JSON.stringify(response.data, null, 2))
})
.catch(function (response) {
res.type('application/ld+json')
res.status(500).send('{}')
})
return
})
// other routes..
}
|
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component } from '@angular/core';
import { SettingsService } from "../../shared/service/settings.service";
import { DataService } from "../../shared/service/data.service";
var SettingsComponent = (function () {
function SettingsComponent(settingsService, dataService) {
this.settingsService = settingsService;
this.dataService = dataService;
// Do stuff
}
SettingsComponent.prototype.save = function () {
this.settingsService.save();
this.dataService.getParameterNames();
};
return SettingsComponent;
}());
SettingsComponent = __decorate([
Component({
selector: 'my-home',
templateUrl: 'settings.component.html',
styleUrls: ['settings.component.scss']
}),
__metadata("design:paramtypes", [SettingsService, DataService])
], SettingsComponent);
export { SettingsComponent };
//# sourceMappingURL=settings.component.js.map
|
'use strict';
import React from 'react-native'
import {
AppRegistry,
Component,
Navigator,
ToolbarAndroid,
View,
} from 'react-native';
import globalStyle, { colors } from './globalStyle';
class NavBar extends Component {
onClickBackToHome() {
this.props.navigator.push({
name: 'home',
sceneConfig: Navigator.SceneConfigs.FloatFromLeft,
});
}
getToolbarActions(route) {
const actionsByRoute = {
'home': [],
'boop-view': [{
title: 'Back',
show: 'always'
}],
}
if (actionsByRoute[route.name]) {
return actionsByRoute[route.name];
}
return [];
}
render() {
const { navigator } = this.props;
const currentRoute = navigator.getCurrentRoutes()[navigator.getCurrentRoutes().length - 1];
const toolbarActions = this.getToolbarActions(currentRoute);
return (
<ToolbarAndroid
style={globalStyle.toolbar}
title='boop'
titleColor={colors.darkTheme.text1}
actions={toolbarActions}
onActionSelected={this.onClickBackToHome.bind(this)}
/>
);
}
};
AppRegistry.registerComponent('NavBar', () => NavBar);
export default NavBar;
|
import React, { Component, PropTypes } from 'react';
import ItemTypes from './ItemTypes';
import { DragSource, DropTarget } from 'react-dnd';
import flow from 'lodash.flow';
function isNullOrUndefined(o) {
return o == null;
}
const cardSource = {
beginDrag(props) {
return {
id: props.id,
index: props.index,
originalIndex: props.index
};
},
endDrag(props, monitor) {
if (props.noDropOutside) {
const { id, index, originalIndex } = monitor.getItem();
const didDrop = monitor.didDrop();
if (!didDrop) {
props.moveCard(isNullOrUndefined(id) ? index : id, originalIndex);
}
}
if (props.endDrag) {
props.endDrag();
}
}
};
const cardTarget = {
hover(props, monitor) {
const { id: dragId, index: dragIndex } = monitor.getItem();
const { id: hoverId, index: hoverIndex } = props;
if (!isNullOrUndefined(dragId)) {
// use id
if (dragId !== hoverId) {
props.moveCard(dragId, hoverIndex);
}
} else {
// use index
if (dragIndex !== hoverIndex) {
props.moveCard(dragIndex, hoverIndex);
// Note: we're mutating the monitor item here!
// Generally it's better to avoid mutations,
// but it's good here for the sake of performance
// to avoid expensive index searches.
monitor.getItem().index = hoverIndex;
}
}
}
};
const propTypes = {
index: PropTypes.number.isRequired,
source: PropTypes.any.isRequired,
createItem: PropTypes.func.isRequired,
moveCard: PropTypes.func.isRequired,
endDrag: PropTypes.func,
isDragging: PropTypes.bool.isRequired,
connectDragSource: PropTypes.func.isRequired,
connectDropTarget: PropTypes.func.isRequired,
noDropOutside: PropTypes.bool
};
class DndCard extends Component {
render() {
const {
id,
index,
source,
createItem,
noDropOutside, // remove from restProps
moveCard, // remove from restProps
endDrag, // remove from restProps
isDragging,
connectDragSource,
connectDropTarget,
...restProps
} = this.props;
if (id === null) {
console.warn('Warning: `id` is null. Set to undefined to get better performance.');
}
const item = createItem(source, isDragging, index);
if (typeof item === 'undefined') {
console.warn('Warning: `createItem` returns undefined. It should return a React element or null.');
}
const finalProps = Object.keys(restProps).reduce((result, k) => {
const prop = restProps[k];
result[k] = typeof prop === 'function' ? prop(isDragging) : prop;
return result;
}, {});
return connectDragSource(connectDropTarget(
<div {...finalProps}>
{item}
</div>
));
}
}
DndCard.propTypes = propTypes;
export default flow(
DropTarget(ItemTypes.DND_CARD, cardTarget, connect => ({
connectDropTarget: connect.dropTarget()
})),
DragSource(ItemTypes.DND_CARD, cardSource, (connect, monitor) => ({
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging()
}))
)(DndCard);
|
// @license
// Redistribution and use in source and binary forms ...
// Copyright 2012 Carnegie Mellon University. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ''AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of Carnegie Mellon University.
//
// Author:
// Randy Sargent (randy.sargent@cs.cmu.edu)
"use strict";
var org;
org = org || {};
org.gigapan = org.gigapan || {};
org.gigapan.timelapse = org.gigapan.timelapse || {};
org.gigapan.timelapse.MercatorProjection = function(west, north, east, south, width, height) {
function rawProjectLat(lat) {
return Math.log((1 + Math.sin(lat * Math.PI / 180)) / Math.cos(lat * Math.PI / 180));
}
function rawUnprojectLat(y) {
return (2 * Math.atan(Math.exp(y)) - Math.PI / 2) * 180 / Math.PI;
}
function interpolate(x, fromLow, fromHigh, toLow, toHigh) {
return (x - fromLow) / (fromHigh - fromLow) * (toHigh - toLow) + toLow;
}
this.latlngToPoint = function(latlng) {
var x = interpolate(latlng.lng, west, east, 0, width);
var y = interpolate(rawProjectLat(latlng.lat), rawProjectLat(north), rawProjectLat(south), 0, height);
return {
"x": x,
"y": y
};
};
this.pointToLatlng = function(point) {
var lng = interpolate(point.x, 0, width, west, east);
var lat = rawUnprojectLat(interpolate(point.y, 0, height, rawProjectLat(north), rawProjectLat(south)));
return {
"lat": lat,
"lng": lng
};
};
};
|
var searchData=
[
['setdebugflags',['setDebugFlags',['../dwarfDbgDebugInfo_8c.html#ab42dd1f5e0f83cb14eed0902aa036a95',1,'dwarfDbgDebugInfo.c']]],
['showchildren',['showChildren',['../dwarfDbgDieInfo_8c.html#a7e7301f838fc67cbb4555c6c250c2dc0',1,'dwarfDbgDieInfo.c']]],
['showcontents',['showContents',['../dwarfDbgLocationInfo_8c.html#af177f930f13d0122065173a8bfbd0317',1,'dwarfDbgLocationInfo.c']]],
['showdieentries',['showDieEntries',['../dwarfDbgDieInfo_8c.html#a01c1ab81a588e24d9d82a9aa8ace1a09',1,'dwarfDbgDieInfo.c']]],
['showsiblings',['showSiblings',['../dwarfDbgDieInfo_8c.html#a6d210b422753428ebf1edc2694a5563f',1,'dwarfDbgDieInfo.c']]]
];
|
import 'reflect-metadata';
import 'rxjs/Rx';
import 'zone.js';
import AppComponent from './components/AppComponent.js';
import { bootstrap } from 'angular2/platform/browser';
bootstrap(AppComponent);
|
/**
* Returns an Express Router with bindings for the Admin UI static resources,
* i.e files, less and browserified scripts.
*
* Should be included before other middleware (e.g. session management,
* logging, etc) for reduced overhead.
*/
var browserify = require('../middleware/browserify');
var express = require('express');
var less = require('less-middleware');
var path = require('path');
module.exports = function createStaticRouter (keystone) {
var router = express.Router();
/* Prepare browserify bundles */
var bundles = {
fields: browserify('utils/fields.js', 'FieldTypes'),
signin: browserify('Signin/index.js'),
index: browserify('index.js'),
};
// prebuild static resources on the next tick
// improves first-request performance
process.nextTick(function () {
bundles.fields.build();
bundles.signin.build();
bundles.index.build();
});
/* Prepare LESS options */
var elementalPath = path.join(path.dirname(require.resolve('elemental')), '..');
var reactSelectPath = path.join(path.dirname(require.resolve('react-select')), '..');
var customStylesPath = keystone.getPath('adminui custom styles') || '';
var lessOptions = {
render: {
modifyVars: {
elementalPath: JSON.stringify(elementalPath),
reactSelectPath: JSON.stringify(reactSelectPath),
customStylesPath: JSON.stringify(customStylesPath),
adminPath: JSON.stringify(keystone.get('admin path')),
},
},
};
/* Configure router */
router.use('/styles', less(path.resolve(__dirname + '/../../public/styles'), lessOptions));
router.use('/styles/fonts', express.static(path.resolve(__dirname + '/../../public/js/lib/tinymce/skins/keystone/fonts')));
router.get('/js/fields.js', bundles.fields.serve);
router.get('/js/signin.js', bundles.signin.serve);
router.get('/js/index.js', bundles.index.serve);
router.use(express.static(path.resolve(__dirname + '/../../public')));
return router;
};
|
'use strict'
const isPlainObject = require('lodash.isplainobject')
const getPath = require('lodash.get')
const StaticComponent = require('./StaticComponent')
const DynamicComponent = require('./DynamicComponent')
const LinkedComponent = require('./LinkedComponent')
const ContainerComponent = require('./ContainerComponent')
const MissingComponent = require('./MissingComponent')
module.exports = {
coerce,
value: makeStaticComponent,
factory: makeDynamicComponent,
link: makeLinkedComponent,
container: makeContainerComponent,
missing: makeMissingComponent
}
function makeStaticComponent(value) {
return new StaticComponent(value)
}
makeDynamicComponent.predefinedFrom = PredefinedComponentBuilder
function makeDynamicComponent(factory, context) {
return new DynamicComponent(factory, context)
}
function PredefinedComponentBuilder(implementations) {
return function PredefinedComponent(implementationName, context) {
let implementation = getPath(implementations, implementationName)
return makeDynamicComponent(implementation, context)
}
}
makeLinkedComponent.boundTo = BoundLinkBuilder
function makeLinkedComponent(context, targetKey) {
return new LinkedComponent(context, targetKey)
}
function BoundLinkBuilder(container) {
return function BoundLink(targetKey) {
return makeLinkedComponent(container, targetKey)
}
}
function makeContainerComponent(container) {
return new ContainerComponent(container)
}
function makeMissingComponent(key) {
return new MissingComponent(key)
}
function coerce(component) {
switch (true) {
case _isComponent(component):
return component
case isPlainObject(component):
return makeContainerComponent(component)
default:
return makeStaticComponent(component)
}
}
function _isComponent(component) {
return component && component.instantiate && component.unwrap && true
}
|
'use strict';
var program = require('commander');
var Q = require('q');
var fs = require('fs');
var resolve = require('path').resolve;
var stat = Q.denodeify(fs.stat);
var readFile = Q.denodeify(fs.readFile);
var writeFile = Q.denodeify(fs.writeFile);
var assign = require('./util/assign');
program
.option('--get', 'Gets configuration property')
.option('--set', 'Sets a configuration value: Ex: "hello=world". If no value is set, then the property is unset from the config file');
program.parse(process.argv);
var args = program.args;
var opts = program.opts();
// Remove options that are not set in the same order as described above
var selectedOpt = Object.keys(opts).reduce(function (arr, next) {
if (opts[next]) {
arr.push(next);
}
return arr;
}, [])[0];
if (!args.length) {
process.exit(1);
}
args = [];
args.push(program.args[0].replace(/=.*$/, ''));
args.push(program.args[0].replace(new RegExp(args[0] + '=?'), ''));
if (args[1] === '') {
args[1] = undefined;
}
stat(resolve('./fxc.json'))
.then(function (stat) {
if (stat.isFile()) {
return readFile(resolve('./fxc.json'));
}
})
.catch(function () {
return Q.when(null);
})
.then(function (fileContent) {
fileContent = assign({}, fileContent && JSON.parse(fileContent.toString('utf8')));
if (selectedOpt === 'get') {
return fileContent[args[0]];
}
if (typeof args[1] !== 'undefined') {
fileContent[args[0]] = args[1];
} else {
delete fileContent[args[0]];
}
return writeFile(resolve('./fxc.json'), JSON.stringify(fileContent));
})
.then(function (output) {
if (output) {
console.log(output);
} else {
console.log('Property "' + args[0] + '" ' + (args[1] ? ('set to "' + args[1] + '"') : 'removed'));
}
process.exit();
});
|
import qambi, {
getMIDIInputs
} from 'qambi'
document.addEventListener('DOMContentLoaded', function(){
console.time('loading and parsing assets took')
qambi.init({
song: {
type: 'Song',
url: '../data/minute_waltz.mid'
},
piano: {
type: 'Instrument',
url: '../../instruments/heartbeat/city-piano-light-concat.json'
}
})
.then(main)
})
function main(data){
console.timeEnd('loading and parsing assets took')
let {song, piano} = data
song.getTracks().forEach(track => {
track.setInstrument(piano)
track.monitor = true
track.connectMIDIInputs(...getMIDIInputs())
})
let btnPlay = document.getElementById('play')
let btnPause = document.getElementById('pause')
let btnStop = document.getElementById('stop')
let divLoading = document.getElementById('loading')
divLoading.innerHTML = ''
btnPlay.disabled = false
btnPause.disabled = false
btnStop.disabled = false
btnPlay.addEventListener('click', function(){
song.play()
})
btnPause.addEventListener('click', function(){
song.pause()
})
btnStop.addEventListener('click', function(){
song.stop()
})
}
|
export default function widget(widget=null, action) {
switch (action.type) {
case 'widget.edit':
return action.widget;
case 'widget.edit.close':
return null;
default:
return widget;
}
}
|
'use strict';
var MemoryStats = require('../../src/models/memory_stats')
, SQliteAdapter = require('../../src/models/sqlite_adapter')
, chai = require('chai')
, expect = chai.expect
, chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
describe('MemoryStats', function() {
describe('.constructor', function() {
it('returns an instantiated memory stats and its schema attributes', function() {
expect(MemoryStats().schemaAttrs).to.include.members(['container_name', 'timestamp_day']);
});
it('returns an instantiated memory stats and its table name', function() {
expect(MemoryStats().tableName).to.eql('memory_stats');
});
});
after(function() {
return SQliteAdapter.deleteDB()
.then(null)
.catch(function(err) {
console.log(err.stack);
});
});
});
|
module.exports = {
resolve: {
alias: {
'vue': 'vue/dist/vue.js'
}
}
}
|
/**
* Created by kalle on 12.5.2014.
*/
/// <reference path="jquery.d.ts" />
var TheBall;
(function (TheBall) {
(function (Interface) {
(function (UI) {
var ResourceLocatedObject = (function () {
function ResourceLocatedObject(isJSONUrl, urlKey, onUpdate, boundToElements, boundToObjects, dataSourceObjects) {
this.isJSONUrl = isJSONUrl;
this.urlKey = urlKey;
this.onUpdate = onUpdate;
this.boundToElements = boundToElements;
this.boundToObjects = boundToObjects;
this.dataSourceObjects = dataSourceObjects;
// Initialize to empty arrays if not given
this.onUpdate = onUpdate || [];
this.boundToElements = boundToElements || [];
this.boundToObjects = boundToObjects || [];
this.dataSourceObjects = dataSourceObjects || [];
}
return ResourceLocatedObject;
})();
UI.ResourceLocatedObject = ResourceLocatedObject;
var UpdatingDataGetter = (function () {
function UpdatingDataGetter() {
this.TrackedURLDictionary = {};
}
UpdatingDataGetter.prototype.registerSourceUrls = function (sourceUrls) {
var _this = this;
sourceUrls.forEach(function (sourceUrl) {
if (!_this.TrackedURLDictionary[sourceUrl]) {
var sourceIsJson = _this.isJSONUrl(sourceUrl);
if (!sourceIsJson)
throw "Local source URL needs to be defined before using as source";
var source = new ResourceLocatedObject(sourceIsJson, sourceUrl);
_this.TrackedURLDictionary[sourceUrl] = source;
}
});
};
UpdatingDataGetter.prototype.isJSONUrl = function (url) {
return url.indexOf("/") != -1;
};
UpdatingDataGetter.prototype.getOrRegisterUrl = function (url) {
var rlObj = this.TrackedURLDictionary[url];
if (!rlObj) {
var sourceIsJson = this.isJSONUrl(url);
rlObj = new ResourceLocatedObject(sourceIsJson, url);
this.TrackedURLDictionary[url] = rlObj;
}
return rlObj;
};
UpdatingDataGetter.prototype.RegisterAndBindDataToElements = function (boundToElements, url, onUpdate, sourceUrls) {
var _this = this;
if (sourceUrls)
this.registerSourceUrls(sourceUrls);
var rlObj = this.getOrRegisterUrl(url);
if (sourceUrls) {
rlObj.dataSourceObjects = sourceUrls.map(function (sourceUrl) {
return _this.TrackedURLDictionary[sourceUrl];
});
}
};
UpdatingDataGetter.prototype.RegisterDataURL = function (url, onUpdate, sourceUrls) {
if (sourceUrls)
this.registerSourceUrls(sourceUrls);
var rlObj = this.getOrRegisterUrl(url);
};
UpdatingDataGetter.prototype.UnregisterDataUrl = function (url) {
if (this.TrackedURLDictionary[url])
delete this.TrackedURLDictionary[url];
};
UpdatingDataGetter.prototype.GetData = function (url, callback) {
var rlObj = this.TrackedURLDictionary[url];
if (!rlObj)
throw "Data URL needs to be registered before GetData: " + url;
if (rlObj.isJSONUrl) {
$.getJSON(url, function (content) {
callback(content);
});
}
};
return UpdatingDataGetter;
})();
UI.UpdatingDataGetter = UpdatingDataGetter;
})(Interface.UI || (Interface.UI = {}));
var UI = Interface.UI;
})(TheBall.Interface || (TheBall.Interface = {}));
var Interface = TheBall.Interface;
})(TheBall || (TheBall = {}));
//# sourceMappingURL=UpdatingDataGetter.js.map
|
'use strict';
module.exports = function(config) {
config.set({
autoWatch : true,
frameworks: ['jasmine'],
browsers : ['PhantomJS'],
plugins : [
'karma-phantomjs-launcher',
'karma-jasmine',
'karma-coverage'
],
preprocessors: {
'src/**/*.js': ['coverage']
},
reporters: ['progress', 'coverage'],
coverageReporter: {
type: 'lcov',
dir: 'reports',
subdir: 'coverage'
},
colors: true
});
};
|
var Chartist = require('chartist');
module.exports = makePluginInstance;
makePluginInstance.calculateScaleFactor = calculateScaleFactor;
makePluginInstance.scaleValue = scaleValue;
function makePluginInstance(userOptions) {
var defaultOptions = {
dot: {
min: 8,
max: 10,
unit: 'px'
},
line: {
min: 2,
max: 4,
unit: 'px'
},
svgWidth: {
min: 360,
max: 1000
}
};
var options = Chartist.extend({}, defaultOptions, userOptions);
return function scaleLinesAndDotsInstance(chart) {
var actualSvgWidth;
chart.on('draw', function(data) {
if (data.type === 'point') {
setStrokeWidth(data, options.dot, options.svgWidth);
} else if (data.type === 'line') {
setStrokeWidth(data, options.line, options.svgWidth);
}
});
/**
* Set stroke-width of the element of a 'data' object, based on chart width.
*
* @param {Object} data - Object passed to 'draw' event listener
* @param {Object} widthRange - Specifies min/max stroke-width and unit.
* @param {Object} thresholds - Specifies chart width to base scaling on.
*/
function setStrokeWidth(data, widthRange, thresholds) {
var scaleFactor = calculateScaleFactor(thresholds.min, thresholds.max, getActualSvgWidth(data));
var strokeWidth = scaleValue(widthRange.min, widthRange.max, scaleFactor);
data.element.attr({
style: 'stroke-width: ' + strokeWidth + widthRange.unit
});
}
/**
* @param {Object} data - Object passed to 'draw' event listener
*/
function getActualSvgWidth(data) {
return data.element.root().width();
}
};
}
function calculateScaleFactor(min, max, value) {
if (max <= min) {
throw new Error('max must be > min');
}
var delta = max - min;
var scaleFactor = (value - min) / delta;
scaleFactor = Math.min(scaleFactor, 1);
scaleFactor = Math.max(scaleFactor, 0);
return scaleFactor;
}
function scaleValue(min, max, scaleFactor) {
if (scaleFactor > 1) throw new Error('scaleFactor cannot be > 1');
if (scaleFactor < 0) throw new Error('scaleFactor cannot be < 0');
if (max < min) throw new Error('max cannot be < min');
var delta = max - min;
return (delta * scaleFactor) + min;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.