text
stringlengths 2
6.14k
|
|---|
/**
* @file
* Preview for the Bartik theme.
*/
(function ($, Drupal, drupalSettings) {
'use strict';
Drupal.color = {
logoChanged: false,
callback: function (context, settings, $form) {
// Change the logo to be the real one.
if (!this.logoChanged) {
$('.color-preview .color-preview-logo img').attr('src', drupalSettings.color.logo);
this.logoChanged = true;
}
// Remove the logo if the setting is toggled off.
if (drupalSettings.color.logo === null) {
$('div').remove('.color-preview-logo');
}
var $colorPreview = $form.find('.color-preview');
var $colorPalette = $form.find('.js-color-palette');
// Solid background.
$colorPreview.css('backgroundColor', $colorPalette.find('input[name="palette[bg]"]').val());
// Text preview.
$colorPreview.find('.color-preview-main h2, .color-preview .preview-content').css('color', $colorPalette.find('input[name="palette[text]"]').val());
$colorPreview.find('.color-preview-content a').css('color', $colorPalette.find('input[name="palette[link]"]').val());
// Sidebar block.
var $colorPreviewBlock = $colorPreview.find('.color-preview-sidebar .color-preview-block');
$colorPreviewBlock.css('background-color', $colorPalette.find('input[name="palette[sidebar]"]').val());
$colorPreviewBlock.css('border-color', $colorPalette.find('input[name="palette[sidebarborders]"]').val());
// Footer wrapper background.
$colorPreview.find('.color-preview-footer-wrapper').css('background-color', $colorPalette.find('input[name="palette[footer]"]').val());
// CSS3 Gradients.
var gradient_start = $colorPalette.find('input[name="palette[top]"]').val();
var gradient_end = $colorPalette.find('input[name="palette[bottom]"]').val();
$colorPreview.find('.color-preview-header').attr('style', 'background-color: ' + gradient_start + '; background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, from(' + gradient_start + '), to(' + gradient_end + ')); background-image: -moz-linear-gradient(-90deg, ' + gradient_start + ', ' + gradient_end + ');');
$colorPreview.find('.color-preview-site-name').css('color', $colorPalette.find('input[name="palette[titleslogan]"]').val());
}
};
})(jQuery, Drupal, drupalSettings);
|
define(
"dojo/cldr/nls/cs/roc", //begin v1.x content
{
"field-sat-relative+0": "tuto sobotu",
"field-sat-relative+1": "příští sobotu",
"field-dayperiod": "AM/PM",
"field-sun-relative+-1": "minulou neděli",
"field-mon-relative+-1": "minulé pondělí",
"field-minute": "Minuta",
"field-day-relative+-1": "včera",
"field-weekday": "Den v týdnu",
"field-day-relative+-2": "předevčírem",
"field-era": "Letopočet",
"field-hour": "Hodina",
"field-sun-relative+0": "tuto neděli",
"field-sun-relative+1": "příští neděli",
"field-wed-relative+-1": "minulou středu",
"field-day-relative+0": "dnes",
"field-day-relative+1": "zítra",
"eraAbbr": [
"Před R. O. C."
],
"field-day-relative+2": "pozítří",
"field-tue-relative+0": "toto úterý",
"field-zone": "Časové pásmo",
"field-tue-relative+1": "příští úterý",
"field-week-relative+-1": "minulý týden",
"field-year-relative+0": "tento rok",
"field-year-relative+1": "příští rok",
"field-sat-relative+-1": "minulou sobotu",
"field-year-relative+-1": "minulý rok",
"field-year": "Rok",
"field-fri-relative+0": "tento pátek",
"field-fri-relative+1": "příští pátek",
"field-week": "Týden",
"field-week-relative+0": "tento týden",
"field-week-relative+1": "příští týden",
"field-month-relative+0": "tento měsíc",
"field-month": "Měsíc",
"field-month-relative+1": "příští měsíc",
"field-fri-relative+-1": "minulý pátek",
"field-second": "Sekunda",
"field-tue-relative+-1": "minulé úterý",
"field-day": "Den",
"field-mon-relative+0": "toto pondělí",
"field-mon-relative+1": "příští pondělí",
"field-thu-relative+0": "tento čtvrtek",
"field-second-relative+0": "nyní",
"field-thu-relative+1": "příští čtvrtek",
"field-wed-relative+0": "tuto středu",
"field-wed-relative+1": "příští středu",
"field-month-relative+-1": "minulý měsíc",
"field-thu-relative+-1": "minulý čtvrtek"
}
//end v1.x content
);
|
// Adds useful constructs for performing atomic
// modifications of JSON in Redis.
function AtomicJSON() {}
AtomicJSON.prototype.wrap = function(redisClient) {
this.redisClient = redisClient;
// Add JSON extensions to Redis client.
redisClient.jgetall = function(json, cb) {
this.jgetall(json, cb);
}.bind(this);
redisClient.jset = function(json, key, value, cb) {
this.jset(json, key, value, cb);
}.bind(this);
redisClient.jdel = function(json, key, cb) {
this.jdel(json, key, cb);
}.bind(this);
return redisClient;
};
// return the object representation of a stored JSON string.
AtomicJSON.prototype.jgetall = function(json, cb) {
this.redisClient.get(json, function(err, value) {
if (err) {
cb(err);
} else {
try {
cb(null, JSON.parse(value) || {});
} catch (e) {
cb(e);
}
}
});
};
// Atomically set the key on a stored JSON string.
AtomicJSON.prototype.jset = function(json, key, value, cb) {
var obj = {};
// Allow for .jset(id, {}) and .jset(id, key, value)
if (typeof value === 'function') {
cb = value, obj = key;
} else {
obj[key] = value;
}
this.redisClient.eval([_jsetLua(), 1, json, JSON.stringify(obj)], cb);
};
function _jsetLua() {
return "local key = KEYS[1];\
local t1 = redis.call('get', key);\
if t1 then t1 = cjson.decode(t1) else t1 = {} end;\
local t2 = cjson.decode(ARGV[1]);\
for k,v in pairs(t2) do t1[k] = v end;\
redis.call('set', key, cjson.encode(t1));";
}
// Atomically unset a key on a stored JSON string.
AtomicJSON.prototype.jdel = function(json, key, cb) {
this.redisClient.eval([_jdelLua(), 1, json, key], cb);
};
function _jdelLua() {
return "local key = KEYS[1];\
local t1 = redis.call('get', key);\
if t1 then t1 = cjson.decode(t1) else t1 = {} end;\
t1[ARGV[1]] = nil;\
redis.call('set', key, cjson.encode(t1));";
}
exports.AtomicJSON = AtomicJSON;
|
var tooBusy = require("toobusy-js")
var healthCheck = function(req,res){
res.send(tooBusy.lag()+"")
}
module.exports = healthCheck
|
'use strict'
var childProcess = require('child_process')
var Timer = require('./timer')
module.exports = runner
function runner (options, reporter, last) {
return function runFiles (err, files) {
if (err) {
return reporter(err)
}
var current = 0
var finished = 0
for (var i = 0; i < options.jobs; ++i) {
trigger()
}
function startTest (file) {
var timer = new Timer(true)
var proc = childProcess.spawn(
'node',
[file],
{stdio: 'ignore'}
)
var timeout = setTimeout(function childprocessTimeout () {
proc.kill()
}, options.timeout * 1000)
proc.on('exit', function onChildProcessExit (code, signal) {
timer.end()
clearTimeout(timeout)
var timestamps = timer.getTimestamps()
trigger()
finished++
setTimeout(function delayReport (end) {
reporter(null, {
filename: file,
exitCode: code,
exitSignal: signal,
duration: timer.durationInMillis(),
start: timestamps[0],
end: timestamps[1]
})
if (end) {
last()
}
}, 0, current === finished)
})
}
function trigger () {
if (current < files.length) {
startTest(files[current])
current++
}
}
}
}
|
import { t } from '../util/locale';
import {
actionChangePreset,
actionJoin,
actionMerge,
actionMergePolygon
} from '../actions';
import { behaviorOperation } from '../behavior';
import { modeSelect } from '../modes';
export function operationMerge(selectedIDs, context) {
function updatePresetTags(oldGraph, newGraph, ids) {
var id = ids[0],
oldEntity = oldGraph.hasEntity(id),
newEntity = newGraph.hasEntity(id);
if (!oldEntity || !newEntity) return;
var oldPreset = context.presets().match(oldEntity, oldGraph),
newPreset = context.presets().match(newEntity, newGraph);
context.replace(actionChangePreset(id, oldPreset, newPreset));
}
var join = actionJoin(selectedIDs),
merge = actionMerge(selectedIDs),
mergePolygon = actionMergePolygon(selectedIDs);
var operation = function() {
var origGraph = context.graph(),
action;
if (!join.disabled(origGraph)) {
action = join;
} else if (!merge.disabled(origGraph)) {
action = merge;
} else {
action = mergePolygon;
}
context.perform(action, operation.annotation());
var ids = selectedIDs.filter(function(id) {
var entity = context.hasEntity(id);
return entity && entity.type !== 'node';
});
// if we merged tags, rematch preset and update tags if necessary (#3851)
if (action === merge) {
updatePresetTags(origGraph, context.graph(), ids);
}
context.enter(modeSelect(context, ids));
};
operation.available = function() {
return selectedIDs.length >= 2;
};
operation.disabled = function() {
return join.disabled(context.graph()) &&
merge.disabled(context.graph()) &&
mergePolygon.disabled(context.graph());
};
operation.tooltip = function() {
var j = join.disabled(context.graph()),
m = merge.disabled(context.graph()),
p = mergePolygon.disabled(context.graph());
if (j === 'restriction' && m && p) {
return t('operations.merge.restriction',
{ relation: context.presets().item('type/restriction').name() });
}
if (p === 'incomplete_relation' && j && m) {
return t('operations.merge.incomplete_relation');
}
if (j && m && p) {
return t('operations.merge.' + j);
}
return t('operations.merge.description');
};
operation.annotation = function() {
return t('operations.merge.annotation', { n: selectedIDs.length });
};
operation.id = 'merge';
operation.keys = [t('operations.merge.key')];
operation.title = t('operations.merge.title');
operation.behavior = behaviorOperation(context).which(operation);
return operation;
}
|
"use strict";
var Mouse;
Mouse = function () {
var x, y, mapX, mapY, canvasLeftOffset, canvasTopOffset, tileWidth,
tileHeight, tileWidthHalf, mapXOffset, mapYOffset;
tileWidth = TilesDefinition.getType(0).imageData.width - 1;
tileHeight = TilesDefinition.getType(0).imageData.height / 2 - 1;
tileWidthHalf = tileWidth / 2;
mapXOffset = 0;
mapYOffset = 0;
this.getX = function () {
return x;
};
this.getY = function () {
return y;
};
this.getMapX = function () {
return mapX;
};
this.getMapY = function () {
return mapY;
};
this.setCanvasOffset = function (left, top) {
canvasLeftOffset = left;
canvasTopOffset = top;
};
this.setMapOffset = function (x, y) {
mapXOffset = x;
mapYOffset = y;
};
addEventListener('mousemove', function (e) {
var xShift, yShift;
x = e.pageX - canvasLeftOffset + mapXOffset;
y = e.pageY - canvasTopOffset + mapYOffset;
mapX = Math.floor(x / tileWidth);
mapY = Math.floor(y / tileHeight);
xShift = x - mapX * tileWidth;
yShift = y - mapY * tileHeight;
if (mapY % 2) {
if (xShift >= tileWidthHalf) {
xShift -= tileWidthHalf;
mapY -= (xShift + yShift < tileWidthHalf) ? 1 : 0;
} else {
if (tileWidthHalf - xShift + yShift < tileWidthHalf) {
mapY--;
} else {
mapX--;
}
}
} else {
if (xShift >= tileWidthHalf) {
xShift -= tileWidthHalf;
mapY -= (tileWidthHalf - xShift + yShift < tileWidthHalf) ?
1 : 0;
} else {
if (xShift + yShift < tileWidthHalf) {
mapX--;
mapY--;
}
}
}
}, false);
};
|
Number.prototype.toMaxFiexed = function (digits) {
var ret = this.toFixed(digits);
ret = ret.replace(/0+$/, '').replace(/\.$/, '');
return ret;
}
function HTMLEncode (input) {
var converter = document.createElement("DIV");
converter.innerText = input;
var output = converter.innerHTML;
converter = null;
return output;
}
function HTMLDecode (input) {
var converter = document.createElement("DIV");
converter.innerHTML = input;
var output = converter.innerText;
converter = null;
return output;
}
|
// adopted from: to-object-path <>
//
var isArguments = require('../lang/isArguments')
var flatten = require('../array/flatten')
var slice = require('../array/slice')
function dotPath (args) {
if (isArguments(args)) args = slice(args)
else args = slice(arguments)
return flatten(args).join('.')
}
module.exports = dotPath
|
'use strict';
/*
* Dependencies
*/
var VitalSigns = require('vitalsigns');
var zoologist = require('./zoologist');
var fsUtil = require('./utils/file-util');
var path = require('path');
var log = require('./logger');
/**
* VitalSignsConfig Constructor
*
* @public
* @constructor VitalSignsConfig
*
*/
function VitalSignsConfig() {
this.vitals = null;
}
/**
* Initialise the VitalSigns instance.
*
* @public
* @method initialise
*/
VitalSignsConfig.prototype.initialise = function (options) {
var vitals;
// Try and load custom monitors
if (fsUtil.checkFileExistsSync(path.resolve(options.callerPath, options.monitorsPath))) {
vitals = require(path.resolve(options.callerPath, options.monitorsPath))();
} else if (options.monitorsPath) {
log.error({ caller: options.callerPath, monitorsPath: options.monitorsPath }, 'monitorsPath was provided but is unresolveable');
}
// Use provided VitalSigns instance or create new
this.vitals = (vitals && vitals instanceof VitalSigns) ? vitals : new VitalSigns();
// Standard Vitals
this.vitals.monitor('mem', { units: 'MB' });
this.vitals.monitor('uptime');
if (zoologist.isInitialised()) {
// ZooKeeper Vitals
this.vitals.monitor(require('./monitors/zookeeper-monitor'));
this.vitals.unhealthyWhen('zookeeper', 'status').equals("DOWN");
// Microservice Vitals
this.vitals.monitor(require('./monitors/microservice-monitor'));
this.vitals.unhealthyWhen('microservice', 'status').equals("DOWN");
}
};
/**
* Return the vitals instance.
*
* @public
* @method getVitals
*/
VitalSignsConfig.prototype.getVitals = function () {
return this.vitals;
};
/**
* Return the Express endpoint for vitals.
*
* The endpoint is a GET route that responds with a JSON represenation of the monitors. A healthy
* service returns a 200 status code, an-unhealthy returns 500 status code.
*
* @public
* @method getExpress
*/
VitalSignsConfig.prototype.getExpress = function () {
return this.vitals.express;
};
var vitalSignsConfig = module.exports = exports = new VitalSignsConfig;
|
class FS_Transformer_Classes extends FS_Transformer {
transform(file_contents, callback) {
var cleaned_contents = Utility_ClassHelper.transformFileContents(
this.getFilepath(),
file_contents,
// This second argument indicates whether or not classnames
// should use relative paths. We need relative paths in order
// for module loading to work correctly on the client:
true
);
return void callback(null, cleaned_contents);
}
}
module.exports = FS_Transformer_Classes;
|
// For info about this file refer to webpack and webpack-hot-middleware documentation
// For info on how we're generating bundles with hashed filenames for cache busting: https://medium.com/@okonetchnikov/long-term-caching-of-static-assets-with-webpack-1ecb139adb95#.w99i89nsz
import webpack from 'webpack'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import WebpackMd5Hash from 'webpack-md5-hash'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import autoprefixer from 'autoprefixer'
import path from 'path'
const GLOBALS = {
'process.env.NODE_ENV': JSON.stringify('production'),
__DEV__: false
}
export default {
resolve: {
extensions: ['', '.js', '.jsx', '.json']
},
debug: true,
devtool: 'source-map', // more info:https://webpack.github.io/docs/build-performance.html#sourcemaps and https://webpack.github.io/docs/configuration.html#devtool
noInfo: true, // set to false to see a list of every file being bundled.
entry: path.resolve(__dirname, 'src/index'),
target: 'web', // necessary per https://webpack.github.io/docs/testing.html#compile-and-test
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: '/',
filename: '[name].[chunkhash].js'
},
plugins: [
// Hash the files using MD5 so that their names change when the content changes.
new WebpackMd5Hash(),
// Optimize the order that items are bundled. This assures the hash is deterministic.
new webpack.optimize.OccurenceOrderPlugin(),
// Tells React to build in prod mode. https://facebook.github.io/react/downloads.html
new webpack.DefinePlugin(GLOBALS),
// Generate an external css file with a hash in the filename
new ExtractTextPlugin('[name].[contenthash].css'),
// Generate HTML file that contains references to generated bundles. See here for how this works: https://github.com/ampedandwired/html-webpack-plugin#basic-usage
new HtmlWebpackPlugin({
template: 'src/index.ejs',
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true
},
inject: true,
// Note that you can add custom options here if you need to handle other custom logic in index.html
// To track JavaScript errors via TrackJS, sign up for a free trial at TrackJS.com and enter your token below.
trackJSToken: ''
}),
// Eliminate duplicate packages when generating bundle
new webpack.optimize.DedupePlugin(),
// Minify JS
new webpack.optimize.UglifyJsPlugin()
],
module: {
loaders: [
{test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel'},
{test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: 'url?name=[name].[ext]'},
{test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url?limit=10000&mimetype=application/font-woff&name=[name].[ext]'},
{test: /\.[ot]tf(\?v=\d+.\d+.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream&name=[name].[ext]'},
{test: /\.svg(\?v=\d+.\d+.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml&name=[name].[ext]'},
{test: /\.(jpe?g|png|gif)$/i, loader: 'file?name=[name].[ext]'},
{test: /\.ico$/, loader: 'file?name=[name].[ext]'},
{test: /(\.css|\.scss)$/, loader: ExtractTextPlugin.extract('css?sourceMap!postcss!sass?sourceMap')},
{test: /\.json$/, loader: "json"}
]
},
postcss: ()=> [autoprefixer]
}
|
var path = require('path');
var fs = require('fs');
var FileHash = require('./filehash').FileHash;
var FileManager = function (config) {
this.config = config;
};
/**
* Hash file data and store file in contracts filesystem.
*/
FileManager.prototype.storeFileData = function (data) {
var hash = FileHash.hash(data);
this._storeFile(hash, data);
};
/**
* Write the given file to the filesystem using the given filename (should
* be the hash if the file.)
*/
FileManager.prototype.storeFileWithHash = function (hash, file) {
var file_path = path.join(this.config.contractsFilesystemPath, hash);
if (!fs.existsSync(file_path)) {
fs.writeFileSync(file_path, file);
}
};
exports.FileManager = FileManager;
|
/** @license ISC License (c) copyright 2016 original and current authors */
/** @author Ian Hofmann-Hicks (evil) */
const isFunction = require('../core/isFunction')
const err = 'compose: Functions required'
function applyPipe(f, g) {
if(!isFunction(g)) {
throw new TypeError(err)
}
return (...args) =>
g.call(null, f.apply(null, args))
}
// compose : ((y -> z), (x -> y), ..., (a -> b)) -> a -> z
function compose(...args) {
if(!arguments.length) {
throw new TypeError(err)
}
const fns =
args.slice().reverse()
const head =
fns[0]
if(!isFunction(head)) {
throw new TypeError(err)
}
const tail =
fns.slice(1).concat(x => x)
return tail.reduce(applyPipe, head)
}
module.exports = compose
|
var d = require('./pokedex.js');
var f = require('./formats-data.js')
dex = d.BattlePokedex;
for (var k in dex)
{
if ('tier' in f.BattleFormatsData[k])
{
dex[k].tier = f.BattleFormatsData[k].tier;
}
}
for (var k in dex)
{
if (!('tier' in f.BattleFormatsData[k]))
{
dex[k].tier = f.BattleFormatsData[dex[k].baseSpecies.toLowerCase()].tier;
}
}
console.log(JSON.stringify(d.BattlePokedex));
|
/*
Require configs from each module
*/
"use strict";
const env = process.env.NODE_ENV || 'dev',
defaultConfig = require('./' + env);
let config = {
env: env,
port: process.env.PORT || defaultConfig.port,
dynamodb: process.env.DDB || defaultConfig.dynamodb
};
console.log(config.dynamodb);
module.exports = config;
|
// ==UserScript==
// @id iitc-plugin-show-less-portals@jonatkins
// @name IITC plugin: Show less portals when zoomed out
// @category 調整
// @version 0.3.0.20170210.164403
// @namespace https://github.com/jonatkins/ingress-intel-total-conversion
// @updateURL https://raw.githubusercontent.com/ifchen0/IITC_TW/master/build/Release/plugins/show-less-portals-zoomed-out.meta.js
// @downloadURL https://raw.githubusercontent.com/ifchen0/IITC_TW/master/build/Release/plugins/show-less-portals-zoomed-out.user.js
// @description [Release-2017-02-10-164403] Vastly reduce the detail level when zoomed out to level 11 or less (L4+ portals), to significantly reduce data usage when viewing large areas.
// @include https://*.ingress.com/intel*
// @include http://*.ingress.com/intel*
// @match https://*.ingress.com/intel*
// @match http://*.ingress.com/intel*
// @include https://*.ingress.com/mission/*
// @include http://*.ingress.com/mission/*
// @match https://*.ingress.com/mission/*
// @match http://*.ingress.com/mission/*
// @grant none
// ==/UserScript==
|
'use strict';
const PgPatcher = require('./pg-patcher');
let basicReporter = require('./reporters/basic-reporter');
let consoleReporter = require('./reporters/console-reporter');
let api = {
create: function(config){
return new PgPatcher(config);
}
};
['run','stepUp', 'stepDown'].forEach(key => { //setting aliases to pgPatcher
api[key] = function(config){
return this.create()[key](config);
};
});
//add reporters
api.reporters = {
basic: basicReporter,
console: consoleReporter
};
module.exports = api;
|
/*!
* watch.js
* Licensed under the MIT license
*
* Copyright (c) 2017 Tony Li
*/
"use strict"
// keep tracking file changes
|
(function () {
angular.module("app").directive("appSetFocus", [
"$timeout",
SetFocusDirective
]);
function SetFocusDirective($timeout) {
return {
restrict: "A",
scope: {
focus: "=appSetFocus"
},
link: function ($scope, $element, attrs) {
$scope.$watch("focus", function (focus) {
if (focus) {
$timeout(function () {
$element.focus();
});
}
});
}
};
}
})();
|
version https://git-lfs.github.com/spec/v1
oid sha256:314b917716d7e47cbe7591046a834689fc98e6dc427905e4231b388b048d2676
size 20371
|
version https://git-lfs.github.com/spec/v1
oid sha256:22e43fe2089c321fe4be33f7a0e533a0a0eb5192e939b33d2fa543cc3093f471
size 16106
|
import winston from 'winston'
export default new winston.Logger({
transports: [
new winston.transports.Console({
level: 'info',
timestamp: true,
prettyPrint: true
})
]
})
|
var config = require('./config.js');
var SkyChat = require('node-redsky').init(config);
SkyChat.on('log_once', function() {
var Banque = require('./Banque.js');
var CommandManager = require('./CommandManager.js');
});
|
import { moduleFor, test } from 'ember-qunit';
moduleFor('controller:process/memory', 'Unit | Controller | process/memory', {
// Specify the other units that are required for this test.
// needs: ['controller:foo']
});
// Replace this with your real tests.
test('it exists', function(assert) {
let controller = this.subject();
assert.ok(controller);
});
|
import { isInlineComment } from "../";
import postcss from "postcss";
import scss from "postcss-scss";
function logError(err) {
console.log(err.stack); // eslint-disable-line no-console
}
test("Single-line comment, after ruleset.", () => {
expect.assertions(1);
return postcss()
.process(
`
a {} // comment
`,
{ syntax: scss, from: undefined, parser: scss }
)
.then(result => {
result.root.walkComments(comment => {
expect(isInlineComment(comment)).toBe(true);
});
})
.catch(logError);
});
test("CSS comment, after ruleset.", () => {
expect.assertions(1);
return postcss()
.process(
`
a {} /* comment */
`,
{ syntax: scss, from: undefined, parser: scss }
)
.then(result => {
result.root.walkComments(comment => {
expect(isInlineComment(comment)).toBe(true);
});
})
.catch(logError);
});
test("Single-line comment, after a decl.", () => {
expect.assertions(1);
return postcss()
.process(
`
a {
width: 10px; // hmm
}
`,
{ syntax: scss, from: undefined, parser: scss }
)
.then(result => {
result.root.walkComments(comment => {
expect(isInlineComment(comment)).toBe(true);
});
})
.catch(logError);
});
test("CSS comment, before a decl.", () => {
expect.assertions(1);
return postcss()
.process(
`
a {
/* CSS comment, before a decl */ width: 10px;
}
`,
{ syntax: scss, from: undefined, parser: scss }
)
.then(result => {
result.root.walkComments(comment => {
expect(isInlineComment(comment)).toBe(true);
});
})
.catch(logError);
});
test("Inline comment, after a {.", () => {
expect.assertions(1);
return postcss()
.process(
`
a { // Inline comment, after a {.
width: 10px;
}
`,
{ syntax: scss, from: undefined, parser: scss }
)
.then(result => {
result.root.walkComments(comment => {
expect(isInlineComment(comment)).toBe(true);
});
})
.catch(logError);
});
test("Inline comment, after a selector (in a list). IGNORED.", () => {
expect.assertions(1);
return postcss()
.process(
`
a, // comment
b {
width: 10px;
}
`,
{ syntax: scss, from: undefined, parser: scss }
)
.then(result => {
let res = null;
result.root.walkComments(comment => {
res = isInlineComment(comment);
});
expect(res).toBeNull();
})
.catch(logError);
});
test("Inline comment, after a selector, comment prior. IGNORED.", () => {
expect.assertions(1);
return postcss()
.process(
`
a,
b {
width: /* comment inside decl */ 10px;
}
`,
{ syntax: scss, from: undefined, parser: scss }
)
.then(result => {
let res = null;
result.root.walkComments(comment => {
res = isInlineComment(comment);
});
expect(res).toBeNull();
})
.catch(logError);
});
test("Multi-line comment, after a ruleset (new line).", () => {
expect.assertions(1);
return postcss()
.process(
`
a {}
/* comment */
`,
{ syntax: scss, from: undefined, parser: scss }
)
.then(result => {
result.root.walkComments(comment => {
expect(isInlineComment(comment)).toBe(false);
});
})
.catch(logError);
});
test("Single-line comment, after a ruleset (new line).", () => {
expect.assertions(1);
return postcss()
.process(
`
a {}
// comment
`,
{ syntax: scss, from: undefined, parser: scss }
)
.then(result => {
result.root.walkComments(comment => {
expect(isInlineComment(comment)).toBe(false);
});
})
.catch(logError);
});
|
import React from 'react';
import moment from 'moment';
import ProfilePhoto from './ProfilePhoto';
import Currency from './Currency';
export default ({transaction, user, precision=0}) => {
return (
<div className='TransactionItem'>
<ProfilePhoto
hasBorder={true}
url={user && user.avatar} />
<div className='TransactionItem-info'>
<div className='TransactionItem-amount'>
<Currency value={getAmount(transaction)} currency={transaction.currency} precision={precision}/>
</div>
<div className='TransactionItem-description'>
{transaction.title || transaction.description}
</div>
<div className='TransactionItem-created'>
{transaction.createdAt && moment(transaction.createdAt).fromNow()}
</div>
</div>
</div>
);
}
function getAmount(transaction) {
return transaction.amount * 100;
}
|
// Default options.
module.exports = {
// Tag this Seneca instance, will be appended to instance identifier.
tag: '-',
// Standard length of identifiers for actions.
idlen: 12,
// Standard timeout for actions.
timeout: 11111,
// Register (true) default plugins. Set false to not register when
// using custom versions.
default_plugins: {
basic: true,
'mem-store': true,
transport: true,
web: true,
},
// Settings for network REPL.
repl:{
port: 30303,
host: null,
},
// Debug settings.
debug: {
// Throw (some) errors from seneca.act.
fragile: false,
// Fatal errors ... aren't fatal. Not for production!
undead: false,
// Print debug info to console
print: {
// Print options. Best used via --seneca.print.options.
options: false,
},
// Trace action caller and place in args.caller$.
act_caller: false,
// Shorten all identifiers to 2 characters.
short_logs: false,
// Record and log callpoints (calling code locations).
callpoint: false,
},
// Enforce strict behaviours. Relax when backwards compatibility needed.
strict: {
// Action result must be a plain object.
result: true,
// Delegate fixedargs override action args.
fixedargs: true,
// Adding a pattern overrides existing pattern only if matches exactly.
add: false,
},
// Action cache. Makes inbound messages idempotent.
actcache: {
active: true,
size: 11111,
},
// Action executor tracing. See gate-executor module.
trace: {
act: false,
stack: false,
unknown: 'warn'
},
// Action statistics settings. See rolling-stats module.
stats: {
size: 1024,
interval: 60000,
running: false
},
// Wait time for plugins to close gracefully.
deathdelay: 11111,
// Default seneca-admin settings.
// TODO: move to seneca-admin!
admin: {
local: false,
prefix: '/admin'
},
// Plugin settings
plugin: {},
// Internal settings.
internal: {
// Close instance on these signals, if true.
close_signals: {
SIGHUP: true,
SIGTERM: true,
SIGINT: true,
SIGBREAK: true,
},
},
// Log status at periodic intervals.
status: {
interval: 60000,
// By default, does not run.
running: false,
},
// zig module settings for seneca.start() chaining.
zig:{},
}
|
exports.default = {
servers: {
net: function(api){
return {
enabled: true,
// passed to tls.createServer if secure=true. Should contain SSL certificates
serverOptions: {},
// Port or Socket
port: 9001,
// which IP to listen on (use 0.0.0.0 for all)
bindIP: '0.0.0.0',
// Enabple TCP KeepAlive pings on each connection?
setKeepAlive: false
}
}
}
}
|
import React from 'react';
import IconBase from '@suitejs/icon-base';
function SpStumbleUpon(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M39.08 25.562c0-.415.336-.751.751-.751h5.418a.75.75 0 0 1 .751.75v4.887c0 5.462-4.485 9.896-9.966 9.812-5.384-.082-9.66-4.576-9.66-9.961v-4.157a.83.83 0 0 1 1.134-.772l1.52.6a.83.83 0 0 0 .593.006l2.554-.943a.83.83 0 0 1 1.118.779v4.636a2.897 2.897 0 0 0 2.844 2.893c1.619.028 2.943-1.35 2.943-2.97v-4.81zM26.373 17.1c0-1.276-.979-2.376-2.253-2.439a2.376 2.376 0 0 0-2.493 2.37v13.417c0 5.462-4.485 9.896-9.966 9.812C6.276 40.178 2 35.684 2 30.3V25.56a.75.75 0 0 1 .75-.75H8.17a.75.75 0 0 1 .75.75v4.887a2.897 2.897 0 0 0 2.845 2.893c1.619.028 2.943-1.35 2.943-2.97v-13.34c0-5.172 4.247-9.37 9.437-9.291 5.1.077 9.149 4.333 9.149 9.432v1.951a.83.83 0 0 1-.543.779l-3.075 1.137a.83.83 0 0 1-.593-.007l-2.183-.861a.83.83 0 0 1-.526-.772V17.1z" />
</IconBase>
);
}
export default SpStumbleUpon;
|
"use strict";
function TownManager() {
Object.defineProperties(this, {
level: {
value: 1,
configurable: false,
writable: true
},
currentBuildPoints: {
value: 0,
configurable: false,
writable: true
},
buildPointsToNextLevel: {
value: 125,
configurable: false,
writable: true
},
manualFoodTechLevel: {
value: 1,
configurable: false,
writable: true
},
manualFoodperCkick: {
value: 1,
configurable: false,
writable: true
},
manualOreTechLevel: {
value: 1,
configurable: false,
writable: true
},
manualOreperCkick: {
value: 1,
configurable: false,
writable: true
},
manualBuildTechLevel: {
value: 1,
configurable: false,
writable: true
},
manualBPperClick: {
value: 1,
configurable: false,
writable: true
},
buildPointPerSecond: {
value: 0,
configurable: false,
writable: true
},
unitManager: {
value: new UnitManager(),
configurable: false,
writable: false
}
});
this.unitManager.maxUnit = 100;
}
TownManager.prototype = Object.create(Object.prototype);
Object.defineProperties(TownManager.prototype, {
checkLevelUp: {
value: function () {
if (this.currentBuildPoints >= this.buildPointsToNextLevel) {
this.currentBuildPoints = this.currentBuildPoints - this.buildPointsToNextLevel;
this.level++;
//Current Build Points required to next level is effectively on power series - 5^3, 7^3, 9^3, etc. Revisit as needed.
var points = (this.level * 2) + 3;
this.buildPointsToNextLevel = Math.pow(points, 3);
var unitCount = (this.level * 2) + 8;
this.unitManager.maxUnit = Math.pow(unitCount, 2);
}
},
configurable: false,
writable: false
},
manualBuild: {
value: function () {
this.currentBuildPoints += this.manualBPperClick;
},
configurable: false,
writable: false
},
manualBuildTechLevelChange: {
value: function (newLevel) {
this.manualBuildTechLevel = newLevel;
//For Each Level after 1, multiply by four.
this.manualBPperClick = Math.pow(4, (newLevel - 1));
},
configurable: false,
writable: false
},
manualFoodTechLevelChange: {
value: function (newLevel) {
this.manualFoodTechLevel = newLevel;
//For Each Level after 1, multiply by three.
this.manualFoodperCkick = Math.pow(3, (newLevel - 1));
},
configurable: false,
writable: false
},
manualOreTechLevelChange: {
value: function (newLevel) {
this.manualOreTechLevel = newLevel;
//For Each Level after 1, multiply by 2.
this.manualOreperCkick = Math.pow(2, (newLevel - 1));
},
configurable: false,
writable: false
},
printString: {
value: function () {
return "Town Level: " + this.level + ", " + Math.floor(this.currentBuildPoints) + "/" + this.buildPointsToNextLevel + " Points for next level. " + this.unitManager.currentUnit + "/" + this.unitManager.maxUnit + " Units in play.";
}
}
});
|
/**
* Created by 路佳 on 2014/12/13.
*/
var express = require('express')
, session = require('express-session')
, bodyParser = require('body-parser')
, user = require('./router/user')
, app = new express();
app.use(function (req, res, next) {
res.set('Access-Control-Allow-Origin', 'http://meagazine.com');
res.set('Access-Control-Allow-Credentials', true);
next();
});
app.use(session({
secret: 'muimui'
}));
app.use(bodyParser.json());
app.get('/', function (req, res) {
res.send('hello, world');
});
// user
app.options('/user/:token', user.options);
app.get('/user/', user.check);
app.put('/user/:token', user.login);
var server = app.listen(3000, function () {
var host = server.address().address
, port = server.address().port;
console.log('listening at http://%s:%s', host, port);
});
|
//循环体内有function
var Benchmark = require('benchmark');
var suite = new Benchmark.Suite();
var obj = {};
for(var i=0;i<20;i++){
var key = 'ww';
obj[key] = i;
}
suite
.add('use for-in', function () {
for(var key in obj){
var value = obj[key];
}
})
.add('use for', function () {
var keys = Object.keys(obj);
for(var i=0,length=keys.length;i<length;i++){
var value = obj[keys[i]];
}
})
// add listeners
.on('cycle', function (event) {
console.log(String(event.target));
})
.on('complete', function () {
console.log('Fastest is ' + this.filter('fastest').pluck('name'));
})
.run({ async: true });
|
/**
* Created by crossApp on 16/8/8.
*/
var DrawViewTest = ca.CAViewController.extend({
ctor: function () {
this._super();
},
viewDidLoad: function() {
var drawView = ca.CADrawView.create() ;
drawView.setLayout(ca.DLayout.set(ca.DHorizontalLayout_L_R(0,0) , ca.DVerticalLayout_T_B(0,40)));
this.getView().addSubview(drawView) ;
var win_wid = ca.winSize.width ;
/** 线 */
drawView.drawLine(ca.DPoint.set(win_wid * 0.2, 50), ca.DPoint.set(win_wid * 0.8 ,50),ca.CAColor4B.BLUE) ;
//point (left-bottom , right-bottom , right-top , left-top)
/** 矩形 */
drawView.drawRect(ca.DPoint.set(win_wid * 0.25,100) , ca.DPoint.set(win_wid * 0.75, 100) , ca.DPoint.set(win_wid * 0.75 , 220) , ca.DPoint.set(win_wid * 0.25 , 220) , ca.CAColor4B.RED) ;
/** 实心多边形 */
drawView.drawSolidCircle(ca.DPoint.set(win_wid * 0.5 , 400) , 100 , 270 ,5 , 1 , 1 , ca.CAColor4B.YELLOW) ;
/** 斜线 */
drawView.drawSegment(ca.DPoint.set(win_wid * 0.3 , 600) , ca.DPoint.set(win_wid * 0.7 ,600) , 5.0, ca.CAColor4B.BLUE) ;
/** 带中线的圆 */
drawView.drawCircle(ca.DPoint.set(win_wid * 0.3 , 800), 30 , 270 , 360 , true , 3 , 3 , ca.CAColor4B.MAGENTA) ;
/** 不带中线的圆 */
drawView.drawCircle(ca.DPoint.set(win_wid * 0.7 , 800), 30 , 270 , 360 , false , 3 , 3 , ca.CAColor4B.MAGENTA) ;
/* 菱形 */
drawView.drawCircle(ca.DPoint.set(win_wid * 0.5 , 990), 30 , 270 , 4 , false , 3 , 3 , ca.CAColor4B.ORANGE) ;
},
});
|
import test from 'tape'
import { compose, createStore, applyMiddleware } from 'redux'
import createAnalyticsStub from './helpers/segment-stub'
import { createTracker, EventTypes } from '../src/index'
import { root } from './helpers/env-setup'
test('Track - spec', t => {
t.test('default', st => {
st.plan(1)
root.analytics = createAnalyticsStub()
const EVENT_TYPE = 'LOGOUT'
const action = {
type: EVENT_TYPE,
meta: {
analytics: {
eventType: EventTypes.reset
}
}
}
const identity = val => val
const tracker = createTracker()
const store = compose(
applyMiddleware(tracker)
)(createStore)(identity)
store.dispatch(action)
const defaultEvent = [
root.analytics[0] && root.analytics[0][0],
root.analytics[0] && root.analytics[0][1]
]
st.deepEqual(defaultEvent, ['reset', undefined], 'emits a reset event')
root.analytics = null
})
})
|
module.exports.word = function (objectTemplate, getTemplate) {
var Letter = getTemplate('./models/letter.js').Letter;
var Word = objectTemplate.create('Word', {
letters: {
type: Array,
of: Letter,
value: []
},
pointValue: function () {
return _.reduce(this.letters, function(l1, l2){
return l1 + l2.pointValue;
}, 0);
},
toString: function () {
return _.reduce(this.letters, function(l1, l2){
return l1 + l2.character;
}, '');
},
init: function (letters) {
this.letters = letters;
}
});
return {
Word: Word
};
};
|
/* global module:false */
module.exports = function (grunt) {
// Project configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
meta: {
banner:
'/*!\n' +
' * PAPI <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' +
' * https://github.com/e-sites/PAPI\n' +
' * MIT licensed\n' +
' *\n' +
' * Copyright (C) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>, <%= pkg.author.web %>\n' +
' */'
},
jshint: {
files: [ 'Gruntfile.js', 'jquery.papi.js' ]
},
uglify: {
options: {
banner: '<%= meta.banner %>\n'
},
build: {
files: {
'jquery.papi.min.js': ['jquery.papi.js']
}
}
},
qunit: {
all: {
options: {
timeout: 7000,
urls: [
'tests/index.html'
]
}
}
}
});
// Dependencies
grunt.loadNpmTasks( 'grunt-contrib-jshint' );
grunt.loadNpmTasks( 'grunt-contrib-uglify' );
grunt.loadNpmTasks( 'grunt-contrib-qunit' );
// Default task
grunt.registerTask( 'default', [ 'jshint', 'uglify', 'qunit'] );
};
|
(function (angular) {
'use strict';
angular
.module('cogeoApp')
.filter('privateChannels', privateChannels);
privateChannels.$inject = [];
function privateChannels() {
return privateChannelsFilter;
function privateChannelsFilter(channels, isActivated) {
if (isActivated) {
var newChannels = [];
channels.forEach(function (channel) {
if (channel.private) {
newChannels.push(channel);
}
});
return newChannels;
}
else {
return channels;
}
}
}
})(window.angular);
|
import React, { PropTypes, Component } from 'react';
import EntrypointCard from './EntrypointCard';
import './EntrypointLists.scss';
export default class EntrypointLists extends Component {
componentDidMount() {
const hash = window.location.hash;
window.location.hash = '';
window.location.hash = hash;
}
render() {
const { lists } = this.props;
return (
<div className="listWrapper">
{
lists.map(({ title, description, entrypoints }) =>
<section
key={title}
id={title}
name={title}
className="section scrollspy entrypoint-tagList"
ref={ref => $(document).ready(() => {
$(ref).scrollSpy({ scrollOffset: 0 });
})}
>
<a className="black-text" href={`#${title}`}>
<h2 className="listTitle">{title}</h2>
<span className="grey-text listSubtitle">{description}</span>
</a>
<div className="entrypointList">
{entrypoints.map(entrypoint =>
<EntrypointCard
key={entrypoint.method + entrypoint.path}
method={entrypoint.method}
path={entrypoint.path}
operation={entrypoint.operation}
/>)}
</div>
</section>
)
}
</div>
);
}
}
EntrypointLists.propTypes = {
lists: PropTypes.arrayOf(PropTypes.shape({
title: PropTypes.string,
description: PropTypes.string,
entrypoints: PropTypes.arrayOf(PropTypes.shape({
method: PropTypes.string,
path: PropTypes.string,
operation: PropTypes.object,
})),
})),
};
|
module.exports = {
port: process.env.PORT || 8081,
db: {
database: process.env.DB_NAME || 'vue-express',
user: process.env.DB_USER || 'vue-express',
password: process.env.DB_PASS || 'vue-express',
options: {
dialect: process.env.DIALECT || 'sqlite',
host: process.env.HOST || 'localhost',
storage: './vue-express.sqlite'
}
}
}
|
"use strict";
angular.module('mdtbackoffice')
.controller('CustomerQuotesCtrl', ['$scope', function ($scope) {
}])
|
'use strict';
const Sequelize = require('sequelize');
const pluralize = Sequelize.Utils.pluralize;
const { errors } = require('./constants');
/**
* Format result set(s) from database queries
*
* @param {Array<Object>|Object} results - Either a single result or multiple
* @param {Sequelize.Model} model - Sequelize data model
* @param {Object} options - Controller configuration
* @returns {Object} Returns a slightly manipulated object to be sent to the client
*/
const formatOutput = (results, model, options) => {
let response = {};
let plural = Array.isArray(results);
if (options.disableNestedData === true) {
return results;
}
let outputName;
if (options.overrideOutputName) {
outputName = options.overrideOutputName;
} else {
outputName = model.name;
}
if (plural) {
outputName = pluralize(outputName);
}
response[outputName] = results;
return response;
};
/**
* Check is the value passed in is a valid Sequelize type
*
* @param {Sequelize.Model} model - Sequelize model
* @returns {boolean} True if the value is a model
*/
const isSequelizeModel = (model) => {
if (model instanceof Sequelize.Model) {
return true;
} else if (model.prototype && model.prototype instanceof Sequelize.Model) {
return true;
}
return false;
};
/**
* Translates various error types into HTTP responses
*
* @param {Express.Request} req - Express HTTP request
* @param {Express.Response} res - Express HTTP response
* @returns {undefined} Return only used to shortcircuit the function
*/
const handleRequestError = (req, res) => {
return (e) => {
switch (e.name) {
case 'SequelizeForeignKeyConstraintError':
return res.status(400).json({ errors: [{ message: 'foreign key constraint error' }] });
case 'SequelizeValidationError':
case 'SequelizeUniqueConstraintError':
return res.status(422).json({
errors: e.errors.map((x) => {
return {
message: x.message,
field: x.path
};
})
});
case 'SequelizeDatabaseError':
return res.status(422).json({ errors: [{ message: e.message }] });
}
switch (e) {
case errors.notFound:
return res.status(404).json({ errors: [{ message: e.message }] });
}
return res.status(500).json({ errors: [{ message: e.message }] });
};
};
/**
* Execute the named hook with provided arguments
*
* @param {string} name - Hook name
* @param {Object} options - Controller configuration
* @param {Array<Any>} args - Hook arguments
*/
const execHook = (name, options, ...args) => {
if (options.hooks && typeof options.hooks[name] === 'function') {
options.hooks[name](...args);
}
};
/**
* Apply provided Express middleware to an existing router
*
* @param {Express.Router} router - Express router
* @param {Object} options - Router/controller configuration
* @param {Array<Function>} [options.middleware] - Middleware to be applied in order
*/
const applyMiddleware = (router, options) => {
if (options) {
if (Array.isArray(options.middleware) && options.middleware.length > 0) {
router.use(options.middleware);
}
}
};
module.exports = {
formatOutput,
isSequelizeModel,
handleRequestError,
execHook,
applyMiddleware
};
|
/* jshint latedef:false */
/* jshint forin:false */
/* jshint noempty:false */
'use strict';
var util = require('util');
var msRest = require('ms-rest');
var msRestAzure = require('ms-rest-azure');
var ServiceClient = msRestAzure.AzureServiceClient;
var WebResource = msRest.WebResource;
var models = require('./models');
var operations = require('./operations');
/**
* @class
* Initializes a new instance of the MicrosoftAzureTestUrl class.
* @constructor
*
* @param {ServiceClientCredentials} [credentials] Subscription credentials which uniquely identify Microsoft Azure subscription.
*
* @param {String} [subscriptionId] Subscription Id.
*
* @param {string} [baseUri] - The base URI of the service.
*
* @param {object} [options] - The parameter options
*
* @param {Array} [options.filters] - Filters to be added to the request pipeline
*
* @param {object} [options.requestOptions] - Options for the underlying request object
* {@link https://github.com/request/request#requestoptions-callback Options doc}
*
* @param {bool} [options.noRetryPolicy] - If set to true, turn off default retry policy
*/
function MicrosoftAzureTestUrl(credentials, subscriptionId, baseUri, options) {
if (credentials === null || credentials === undefined) {
throw new Error('\'credentials\' cannot be null.');
}
if (subscriptionId === null || subscriptionId === undefined) {
throw new Error('\'subscriptionId\' cannot be null.');
}
if (!options) options = {};
MicrosoftAzureTestUrl['super_'].call(this, credentials, options);
this.baseUri = baseUri;
if (!this.baseUri) {
this.baseUri = 'https://management.azure.com/';
}
this.credentials = credentials;
this.subscriptionId = subscriptionId;
if(!this.apiVersion) {
this.apiVersion = '2014-04-01-preview';
}
this.group = new operations.Group(this);
this._models = models;
}
util.inherits(MicrosoftAzureTestUrl, ServiceClient);
module.exports = MicrosoftAzureTestUrl;
|
import angular from 'angular';
import app from './app/boot/app.js';
import oclazyload from 'oclazyload';
{
window.addEventListener('load', () => {
window.app = angular
.bootstrap(document.getElementById('root'), [app.name, 'oc.lazyLoad'], {strictDi: true});
});
}
|
/**
*
* Supersample Anti-Aliasing Render Pass
*
* @author bhouston / http://clara.io/
*
* This manual approach to SSAA re-renders the scene ones for each sample with camera jitter and accumulates the results.
*
* References: https://en.wikipedia.org/wiki/Supersampling
*
*/
B3D.SSAARenderPass = function ( scene, camera, clearColor, clearAlpha ) {
B3D.Pass.call( this );
this.scene = scene;
this.camera = camera;
this.sampleLevel = 4; // specified as n, where the number of samples is 2^n, so sampleLevel = 4, is 2^4 samples, 16.
this.unbiased = true;
// as we need to clear the buffer in this pass, clearColor must be set to something, defaults to black.
this.clearColor = ( clearColor !== undefined ) ? clearColor : 0x000000;
this.clearAlpha = ( clearAlpha !== undefined ) ? clearAlpha : 0;
if ( B3D.CopyShader === undefined ) console.error( "B3D.SSAARenderPass relies on B3D.CopyShader" );
var copyShader = B3D.CopyShader;
this.copyUniforms = B3D.UniformsUtils.clone( copyShader.uniforms );
this.copyMaterial = new B3D.ShaderMaterial( {
uniforms: this.copyUniforms,
vertexShader: copyShader.vertexShader,
fragmentShader: copyShader.fragmentShader,
premultipliedAlpha: true,
transparent: true,
blending: B3D.AdditiveBlending,
depthTest: false,
depthWrite: false
} );
this.camera2 = new B3D.OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
this.scene2 = new B3D.Scene();
this.quad2 = new B3D.Mesh( new B3D.PlaneGeometry( 2, 2 ), this.copyMaterial );
this.quad2.frustumCulled = false; // Avoid getting clipped
this.scene2.add( this.quad2 );
};
B3D.SSAARenderPass.prototype = Object.assign( Object.create( B3D.Pass.prototype ), {
constructor: B3D.SSAARenderPass,
dispose: function () {
if ( this.sampleRenderTarget ) {
this.sampleRenderTarget.dispose();
this.sampleRenderTarget = null;
}
},
setSize: function ( width, height ) {
if ( this.sampleRenderTarget ) this.sampleRenderTarget.setSize( width, height );
},
render: function ( renderer, writeBuffer, readBuffer ) {
if ( ! this.sampleRenderTarget ) {
this.sampleRenderTarget = new B3D.WebGLRenderTarget( readBuffer.width, readBuffer.height, { minFilter: B3D.LinearFilter, magFilter: B3D.LinearFilter, format: B3D.RGBAFormat } );
this.sampleRenderTarget.texture.name = "SSAARenderPass.sample";
}
var jitterOffsets = B3D.SSAARenderPass.JitterVectors[ Math.max( 0, Math.min( this.sampleLevel, 5 ) ) ];
var autoClear = renderer.autoClear;
renderer.autoClear = false;
var oldClearColor = renderer.getClearColor().getHex();
var oldClearAlpha = renderer.getClearAlpha();
var baseSampleWeight = 1.0 / jitterOffsets.length;
var roundingRange = 1 / 32;
this.copyUniforms[ "tDiffuse" ].value = this.sampleRenderTarget.texture;
var width = readBuffer.width, height = readBuffer.height;
// render the scene multiple times, each slightly jitter offset from the last and accumulate the results.
for ( var i = 0; i < jitterOffsets.length; i ++ ) {
var jitterOffset = jitterOffsets[ i ];
if ( this.camera.setViewOffset ) {
this.camera.setViewOffset( width, height,
jitterOffset[ 0 ] * 0.0625, jitterOffset[ 1 ] * 0.0625, // 0.0625 = 1 / 16
width, height );
}
var sampleWeight = baseSampleWeight;
if ( this.unbiased ) {
// the theory is that equal weights for each sample lead to an accumulation of rounding errors.
// The following equation varies the sampleWeight per sample so that it is uniformly distributed
// across a range of values whose rounding errors cancel each other out.
var uniformCenteredDistribution = ( - 0.5 + ( i + 0.5 ) / jitterOffsets.length );
sampleWeight += roundingRange * uniformCenteredDistribution;
}
this.copyUniforms[ "opacity" ].value = sampleWeight;
renderer.setClearColor( this.clearColor, this.clearAlpha );
renderer.render( this.scene, this.camera, this.sampleRenderTarget, true );
if ( i === 0 ) {
renderer.setClearColor( 0x000000, 0.0 );
}
renderer.render( this.scene2, this.camera2, this.renderToScreen ? null : writeBuffer, ( i === 0 ) );
}
if ( this.camera.clearViewOffset ) this.camera.clearViewOffset();
renderer.autoClear = autoClear;
renderer.setClearColor( oldClearColor, oldClearAlpha );
}
} );
// These jitter vectors are specified in integers because it is easier.
// I am assuming a [-8,8) integer grid, but it needs to be mapped onto [-0.5,0.5)
// before being used, thus these integers need to be scaled by 1/16.
//
// Sample patterns reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476218%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
B3D.SSAARenderPass.JitterVectors = [
[
[ 0, 0 ]
],
[
[ 4, 4 ], [ - 4, - 4 ]
],
[
[ - 2, - 6 ], [ 6, - 2 ], [ - 6, 2 ], [ 2, 6 ]
],
[
[ 1, - 3 ], [ - 1, 3 ], [ 5, 1 ], [ - 3, - 5 ],
[ - 5, 5 ], [ - 7, - 1 ], [ 3, 7 ], [ 7, - 7 ]
],
[
[ 1, 1 ], [ - 1, - 3 ], [ - 3, 2 ], [ 4, - 1 ],
[ - 5, - 2 ], [ 2, 5 ], [ 5, 3 ], [ 3, - 5 ],
[ - 2, 6 ], [ 0, - 7 ], [ - 4, - 6 ], [ - 6, 4 ],
[ - 8, 0 ], [ 7, - 4 ], [ 6, 7 ], [ - 7, - 8 ]
],
[
[ - 4, - 7 ], [ - 7, - 5 ], [ - 3, - 5 ], [ - 5, - 4 ],
[ - 1, - 4 ], [ - 2, - 2 ], [ - 6, - 1 ], [ - 4, 0 ],
[ - 7, 1 ], [ - 1, 2 ], [ - 6, 3 ], [ - 3, 3 ],
[ - 7, 6 ], [ - 3, 6 ], [ - 5, 7 ], [ - 1, 7 ],
[ 5, - 7 ], [ 1, - 6 ], [ 6, - 5 ], [ 4, - 4 ],
[ 2, - 3 ], [ 7, - 2 ], [ 1, - 1 ], [ 4, - 1 ],
[ 2, 1 ], [ 6, 2 ], [ 0, 4 ], [ 4, 4 ],
[ 2, 5 ], [ 7, 5 ], [ 5, 6 ], [ 3, 7 ]
]
];
|
'use strict';
var path = require('path'),
_ = require('lodash'),
mongoose = require('mongoose'),
Task = mongoose.model('Task'),
User = mongoose.model('User'),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));
exports.list = function(req, res) {
Task.find().populate('createdBy', 'username').exec(function(err, tasks) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
}
res.json(tasks);
});
};
exports.listByStatus = function(req, res) {
var status = req.taskStatus;
Task.find({ status: status }).populate('createdBy', 'username').exec(function(err, tasks) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
}
res.json(tasks);
});
};
exports.listByAuthor = function(req, res) {
var userID = req.params.userID;
Task.find({ createdBy: userID }).exec(function(err, tasks) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
}
res.json(tasks);
});
};
exports.create = function(req, res) {
var task = new Task({
taskName: req.body.taskName,
createdBy: req.body.createdBy,
projectBelongs: req.body.projectBelongs,
description: req.body.description,
value: req.body.value,
pluses: req.body.pluses,
taskType: req.body.taskType,
status: req.body.status
});
task.save().then(function() {
return User.populate(task, { path: 'createdBy', select: 'username' });
}).then(function(task) {
res.json(task);
}).then(null, function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
}
});
};
exports.populateTaskByID = function(req, res) {
var task = req.task;
if (task) {
User.populate(task, { path: 'createdBy', select: 'username' }).then(function(task) {
res.json(task);
}, function(err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
});
}
};
exports.delete = function(req, res) {
var task = req.task;
if (task) {
task.remove(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
}
res.json({
status: 'ok',
message: 'A task is removed.'
});
});
}
};
exports.update = function(req, res) {
var task = req.task;
if (task) {
task = _.extend(task, req.body);
task.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
}
res.json(task);
});
}
};
// Middlewares
exports.taskByID = function(req, res, next, id) {
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).send({
message: 'Task is invalid'
});
}
Task.findOne({ _id: id }, function(err, task) {
if (err) {
return next(err);
} else if (!task) {
return next(new Error('Failed to load Task ' + id));
}
req.task = task;
next();
});
};
var statusMap = {
notstarted: 'Not started',
inprogress: 'In progress',
pause: 'Pause',
completed: 'Completed',
terminated: 'Terminated'
};
exports.statusTrans = function(req, res, next, status) {
req.taskStatus = statusMap[status];
if (!req.taskStatus) {
return res.status(400).send({
message: 'Status is invalid'
});
}
next();
};
|
const Promise = require(`bluebird`)
const os = require(`os`)
const { onCreateNode } = require(`../gatsby-node`)
// Make some fake functions its expecting.
const loadNodeContent = node => Promise.resolve(node.content)
const bootstrapTest = async (node, pluginOptions = {}) => {
const createNode = jest.fn()
const createParentChildLink = jest.fn()
const actions = { createNode, createParentChildLink }
const createNodeId = jest.fn()
createNodeId.mockReturnValue(`uuid-from-gatsby`)
const createContentDigest = jest.fn().mockReturnValue(`contentDigest`)
return await onCreateNode(
{
node,
loadNodeContent,
actions,
createNodeId,
createContentDigest,
},
pluginOptions
).then(() => {
return {
createNode,
createParentChildLink,
}
})
}
describe(`Process JSON nodes correctly`, () => {
const baseNode = {
id: `whatever`,
parent: null,
children: [],
internal: {
contentDigest: `whatever`,
mediaType: `application/json`,
},
}
const baseFileNode = {
...baseNode,
name: `nodeName`,
dir: `${os.tmpdir()}/foo/`,
internal: {
...baseNode.internal,
type: `File`,
},
}
const baseNonFileNode = {
...baseNode,
internal: {
...baseNode.internal,
type: `NotFile`,
},
}
it(`correctly creates nodes from JSON which is an array of objects`, async () => {
const data = [
{ id: `foo`, blue: true, funny: `yup` },
{ blue: false, funny: `nope` },
]
const node = {
...baseFileNode,
content: JSON.stringify(data),
}
return bootstrapTest(node).then(({ createNode, createParentChildLink }) => {
expect(createNode.mock.calls).toMatchSnapshot()
expect(createParentChildLink.mock.calls).toMatchSnapshot()
expect(createNode).toHaveBeenCalledTimes(2)
expect(createParentChildLink).toHaveBeenCalledTimes(2)
})
})
it(`correctly creates a node from JSON which is a single object`, async () => {
const data = { id: `foo`, blue: true, funny: `yup` }
const node = {
...baseFileNode,
content: JSON.stringify(data),
}
return bootstrapTest(node).then(({ createNode, createParentChildLink }) => {
expect(createNode.mock.calls).toMatchSnapshot()
expect(createParentChildLink.mock.calls).toMatchSnapshot()
expect(createNode).toHaveBeenCalledTimes(1)
expect(createParentChildLink).toHaveBeenCalledTimes(1)
})
})
it(`correctly sets node type for array of objects`, async () => {
;[
{
typeName: null,
expectedNodeTypes: [`NodeNameJson`, `NodeNameJson`],
},
{
typeName: `fixed`,
expectedNodeTypes: [`fixed`, `fixed`],
},
{
typeName: ({ node, object }) => object.funny,
expectedNodeTypes: [`yup`, `nope`],
},
].forEach(
async ({ typeName, expectedNodeTypes: [expectedOne, expectedTwo] }) => {
const data = [
{ id: `foo`, blue: true, funny: `yup` },
{ blue: false, funny: `nope` },
]
const node = {
...baseFileNode,
content: JSON.stringify(data),
}
return bootstrapTest(node, { typeName }).then(
({ createNode, createParentChildLink }) => {
expect(createNode).toBeCalledWith(
expect.objectContaining({
internal: expect.objectContaining({
type: expectedOne,
}),
})
)
expect(createNode).toBeCalledWith(
expect.objectContaining({
internal: expect.objectContaining({
type: expectedTwo,
}),
})
)
}
)
}
)
})
it(`correctly sets node type for single object`, async () => {
;[
{
typeName: null,
expectedNodeType: `FooJson`,
},
{
typeName: `fixed`,
expectedNodeType: `fixed`,
},
{
typeName: ({ node, object }) => object.funny,
expectedNodeType: `yup`,
},
].forEach(async ({ typeName, expectedNodeType }) => {
const data = { id: `foo`, blue: true, funny: `yup` }
const node = {
...baseFileNode,
content: JSON.stringify(data),
}
return bootstrapTest(node, { typeName }).then(
({ createNode, createParentChildLink }) => {
expect(createNode).toBeCalledWith(
expect.objectContaining({
internal: expect.objectContaining({
type: expectedNodeType,
}),
})
)
}
)
})
})
it(`correctly creates nodes from JSON which is an array of objects and doesn't come from fs`, async () => {
const data = [
{ id: `foo`, blue: true, funny: `yup` },
{ blue: false, funny: `nope` },
]
const node = {
...baseNonFileNode,
content: JSON.stringify(data),
}
return bootstrapTest(node).then(({ createNode, createParentChildLink }) => {
expect(createNode.mock.calls).toMatchSnapshot()
expect(createParentChildLink.mock.calls).toMatchSnapshot()
expect(createNode).toHaveBeenCalledTimes(2)
expect(createParentChildLink).toHaveBeenCalledTimes(2)
})
})
it(`correctly creates a node from JSON which is a single object and doesn't come from fs`, async () => {
const data = { id: `foo`, blue: true, funny: `yup` }
const node = {
...baseNonFileNode,
content: JSON.stringify(data),
}
return bootstrapTest(node).then(({ createNode, createParentChildLink }) => {
expect(createNode.mock.calls).toMatchSnapshot()
expect(createParentChildLink.mock.calls).toMatchSnapshot()
expect(createNode).toHaveBeenCalledTimes(1)
expect(createParentChildLink).toHaveBeenCalledTimes(1)
})
})
})
|
/*
Name: Tables / Editable - Examples
Written by: Okler Themes - (http://www.okler.net)
Theme Version: 1.3.0
*/
(function( $ ) {
'use strict';
var EditableTable = {
options: {
table: '#datatable-editable',
dialog: {
wrapper: '#dialog',
cancelButton: '#dialogCancel',
confirmButton: '#dialogConfirm',
}
},
initialize: function() {
this
.setVars()
.build()
.events();
},
setVars: function() {
this.$table = $( this.options.table );
// dialog
this.dialog = {};
this.dialog.$wrapper = $( this.options.dialog.wrapper );
this.dialog.$cancel = $( this.options.dialog.cancelButton );
this.dialog.$confirm = $( this.options.dialog.confirmButton );
return this;
},
build: function() {
this.datatable = this.$table.DataTable({
aoColumns: [
null,
null,
null,
null,
null,
{ "bSortable": false }
]
});
window.dt = this.datatable;
return this;
},
events: function() {
var _self = this;
this.$table
.on( 'click', 'a.restore-row', function( e ) {
e.preventDefault();
var $row = $(this).closest( 'tr' );
$.magnificPopup.open({
items: {
src: '#dialog',
type: 'inline'
},
preloader: false,
modal: true,
callbacks: {
change: function() {
_self.dialog.$confirm.on( 'click', function( e ) {
e.preventDefault();
_self.rowRestore( $row );
$.magnificPopup.close();
});
},
close: function() {
_self.dialog.$confirm.off( 'click' );
}
}
});
});
this.dialog.$cancel.on( 'click', function( e ) {
e.preventDefault();
$.magnificPopup.close();
});
return this;
},
// ==========================================================================================
// ROW FUNCTIONS
// ==========================================================================================
rowRestore: function( $row ) {
var tmpDataTable = this.datatable;
$.ajax({
url : "restore/" + $row.data('id'),
success : function(response) {
if(!response.status) {
tmpDataTable.row( $row.get(0) ).remove().draw();
} else {
alert(response.message);
}
},
});
},
};
$(function() {
EditableTable.initialize();
});
}).apply( this, [ jQuery ]);
|
search_result['4332']=["topic_0000000000000A4F.html","StatusVm.SetInterview Property",""];
|
/*jslint browser:true */
/**
* CallBaker
*
* Event system based on data attributes. Register and listen to element bound
* functions and trigger custom event types.
*
* @author: Martin Helmut Fieber <info@martin-fieber.de>
* @github: https://github.com/MartinHelmut/callbaker
*/
(function (window) {
'use strict';
var callbaker = {
registry: []
};
function registryFindEntry(element, eventType) {
var i = 0;
for (i = callbaker.registry.length - 1; i >= 0; i -= 1) {
if (callbaker.registry[i].target === element && callbaker.registry[i].type === eventType) {
return callbaker.registry[i];
}
}
return null;
}
/**
* Create event object from element
*
* @param {Node} element DOM node
* @param {Object} params Event parameter
*/
function Event(element, params) {
this.target = element;
this.params = params;
// Get all events by data attribute
this.registry = (function () {
var attributes = element.attributes,
events = [],
match,
i = 0;
for (i = attributes.length - 1; i >= 0; i -= 1) {
match = /data-cb-([a-z]+)/i.exec(attributes[i].nodeName);
if (!!match) {
events.push(match[1]);
}
}
return events;
}());
}
/**
* Trigger event type
*
* @param {String} eventType Event type name
*/
Event.prototype.trigger = function (eventType) {
var entry = registryFindEntry(this.target, eventType);
if (!!entry && !!entry.callback && typeof entry.callback === 'function') {
entry.callback(this);
}
};
/**
* Register callback event
*
* @param {Node} element DOM node
* @param {Object} params Optional event parameter
* @return {Function} Event object
*/
callbaker.register = function (element, params) {
params = params || {};
return new Event(element, params);
};
/**
* Listen to custom event
*
* @param {Node} element DOM node
* @param {String} eventType Custom event type to listen to
* @param {Function} callback Executable callback
*/
callbaker.on = function (element, eventType, callback) {
var entry = registryFindEntry(element, eventType);
if (!!entry) {
return;
}
this.registry.push({
target: element,
type: eventType,
callback: callback
});
};
// Add to global scope
window.callbaker = callbaker;
}(window));
|
var WebSocket = require('ws');
/** @public module */
module.exports = function( b9 ){
/**
* the frequency of socket pings
* @public option
*/
b9._interval = b9._interval || 5000;
/**
* ref to [active] websocket instance
* @private
*/
var ws;
/**
* map of pending [sent] messages, by id
* @private
*/
var pending = Object.create( null );
/**
* unique message id counter
* @private
*/
var guid = 1;
b9.self = {};
/**
* authenticate with slack real-time-message api
* https://api.slack.com/methods/rtm.start
* @public method
*/
b9.start = function start ( callback ){
// handle success handshake...
function success ( msg ){
complete( null, msg );
}
// handle complete callback...
function complete ( err, msg ){
b9.off('hello', success ); // cleanup
// optional callback, error-first...
if ( typeof callback == 'function' ){
callback( err, msg );
}
}
// close prev connection
b9.stop();
// handle successful handshake
b9.on('hello', success );
// make the connection attempt...
b9.post('rtm.start', {
simple_latest: true,
no_unreads: true
}, function( err, msg ){
if ( err == null && msg.ok === true ){
// slack user settings
b9.self = msg.self;
try { // create a new connection
ws = new WebSocket( msg.url );
}
catch ( ex ){ // bad socket input
return complete( ex );
}
// handle socket `error` events, error-first
ws.on('error', complete );
// listen to the socket for messages
ws.on('message', receive );
}
// handle connection errors
else {
// error-first callback
complete( err || new Error( msg.error ), msg );
}
});
return b9;
};
/**
* close a websocket
* @public method
*/
b9.stop = function stop (){
if ( ws != null ){
ws.close();
ws = null;
}
};
/**
* send a websocket message
* @public method
*/
b9.send = function send ( msg ){
ping(); // clear/schedule next ping
// clean up the channel, in case encoded one is passed
if ( msg.channel ){
msg.channel = msg.channel.replace(/^<#|>$/g,'');
}
msg.id = msg.id || guid++;
pending[ msg.id ] = msg;
if ( ws != null ) {
b9.emit('rtm.send', msg );
ws.send( JSON.stringify( msg ) );
}
};
/**
* handle a websocket message
* @private method
*/
function receive ( str ){
ping(); // clear/schedule next ping
var msg = typeof str === 'string' ? JSON.parse( str ) : str;
b9.emit('rtm.read', msg, replyTo( null ) );
// acknowledge that a pending message was sent successfully
if ( msg.reply_to ){
delete pending[ msg.reply_to ];
}
else if ( msg.type != null ){
b9.emit( msg.type, msg, replyTo( msg.channel ) );
}
};
/**
* self-addressed stamped envelope -- for replies
* @private method
*/
function replyTo ( channel ){
return function ( txt ){
b9.send({ type:'message', channel:channel, text:txt });
};
};
/**
* keep the connection alive
* @private method
*/
function ping (){
clearTimeout( ping.timer );
ping.timer = setTimeout(function(){
b9.send({ type: 'ping', time: Date.now() });
}, b9._interval );
};
};
|
'use strict';
var path = require('path');
var csso = require('csso');
var loaderUtils = require('loader-utils');
module.exports = function(source) {
var query = loaderUtils.getOptions(this) || {};
var cssoOptions = this.options ? this.options.csso : false;
var filename = path.basename(this.resourcePath || '');
var options = {};
var result;
if (this.cacheable) {
this.cacheable();
}
if (typeof query.debug === 'boolean') {
options.debug = query.debug;
}
if (typeof query.restructure === 'boolean') {
options.restructure = query.restructure;
}
if (typeof query.comments === 'boolean') {
options.comments = query.comments;
}
if (typeof cssoOptions === 'object') {
if (typeof cssoOptions.debug === 'boolean' || [1, 2, 3].indexOf(cssoOptions.debug) !== -1) {
options.debug = cssoOptions.debug;
}
if (typeof cssoOptions.restructure === 'boolean') {
options.restructure = cssoOptions.restructure;
}
if (typeof cssoOptions.usage === 'object') {
options.usage = cssoOptions.usage;
}
if (typeof cssoOptions.logger === 'function') {
options.logger = cssoOptions.logger;
}
if (typeof cssoOptions.comments === 'boolean' || ['exclamation', 'first-exclamation'].indexOf(cssoOptions.comments) !== -1) {
options.comments = cssoOptions.comments;
}
}
try {
result = csso.minify(source, options);
} catch (error) {
console.error([' ',
error.name + ' ' + filename + ': ' + error.message,
'Line: ' + error.parseError.line,
'Column: ' + error.parseError.column
].join('\n'));
}
if (result) {
return result.css;
}
return source;
};
|
(function(){
var states = {
'India': ['Maharashtra','Rajasthan'],
'Australia': ['New South Wales', 'Victoria']
};
var cities = {
'Maharashtra': ['Mumbai', 'Pune'],
'Rajasthan': ['Jaipur', 'Udaipur'],
'New South Wales': ['Sydney', 'Albury', 'Armidale', 'Dubbo'],
'Victoria': ['Melbourne', 'Ararat', 'Portland']
};
var slCntry = document.getElementById("country");
var slState = document.getElementById("state");
var slCity = document.getElementById("city");
if(!slCntry.addEventListener) {
slCntry.attachEvent("onchange", function(){
empty(slState, 'State');
fill(slState, states[slCntry.value]);
empty(slCity, 'City');
}, false);
} else {
slCntry.addEventListener("change", function(){
empty(slState, 'State');
fill(slState, states[slCntry.value]);
empty(slCity, 'City');
}, false);
}
if(!slState.addEventListener) {
slState.attachEvent("onchange", function(){
empty(slCity, 'City');
fill(slCity, cities[slState.value]);
}, false);
} else {
slState.addEventListener("change", function(){
empty(slCity, 'City');
fill(slCity, cities[slState.value]);
}, false);
}
var fill = function(elem, data){
if (elem.options === undefined) {
throw "supplied argument is not a form select element";
}
if (data.constructor !== Array) {
throw "supplied argument is not an Array";
}
for(var i = 1; i <= data.length; i++) {
elem.options[i] = document.createElement("option");
elem.options[i].value = data[i - 1];
elem.options[i].innerHTML = data[i - 1];
}
};
var empty = function(elem, data){
if (elem.options === undefined) {
throw "supplied argument is not a form select element";
}
if (data.constructor !== String) {
throw "second argument should be a String"
}
elem.innerHTML = "";
elem.options[0] = document.createElement("option");
elem.options[0].disabled = "disabled";
elem.options[0].value = "";
elem.options[0].innerHTML = data;
};
})();
|
'use strict';
const polls = require('../data/actions')('polls');
const Users = require('./users');
class Poll {
constructor(name, options, submitter, voted) {
this.name = name.trim() || '';
this.options = options || {};
this.submitter = submitter || '';
this.voted = voted || [];
}
edit(newOptions) {
this.options = Polls.formatOptions(newOptions, this.options)
this.saveToDB();
return this;
}
vote(option, ip) {
this.options[option] += 1;
this.voted.push(ip);
this.saveToDB();
return this;
}
hasVoted(ip) {
return this.voted.find(x => x === ip)
}
format() {
return Polls.format(this);
}
saveToDB() {
polls.set(Polls.toCamelCase(this.name), this);
return this;
}
}
const Polls = (
name,
options,
submitter,
voted
) => (
new Poll(name, options, submitter, voted)
);
Polls.get = (pollName) => (
polls.get(Polls.toCamelCase(pollName))
.then(poll => Polls(
poll.name, poll.options, poll.submitter, poll.voted
))
);
Polls.edit = (req, res) => {
Polls.get(req.body.pollName)
.then(poll => {
poll.edit(req.body.newOptions);
res.json(poll.format());
})
.catch(err => {
res.status(400).send('Unable to find poll, please check the name and try again');
})
}
Polls.delete = (req, res) => {
Users.get(req.user.username).
then(user => {
user.deletePoll(req.body.pollName);
polls.del(Polls.toCamelCase(req.body.pollName));
res.json(user.username);
})
}
Polls.getAll = (req, res) => {
if (!req) {return polls.getAll()}
polls.getAll().then(polls => {
if (polls) {polls = polls.map(Polls.format)}
res.json(polls || {'no-data': 'No active polls found'})
});
};
Polls.exists = (pollName) => (
polls.exists(Polls.toCamelCase(pollName))
);
Polls.create = (req, res) => {
Polls.exists(req.body.pollName)
.then(exists => {
if (exists) {
res.status(409).send('A poll with that name already exists, please try again.');
} else {
const poll = Polls(
req.body.pollName,
Polls.formatOptions(req.body.options, {}),
req.user.username
);
Users.get(req.user.username)
.then(user => {
user.addPoll(poll.name);
poll.saveToDB();
res.status(201).json(poll.format());
})
}
});
};
Polls.vote = (req, res) => {
Polls.get(req.body.pollName)
.then(poll => {
if (poll.hasVoted(req.ip)) {
res.status(409).send('Sorry, you can only vote on a poll once.');
} else {
poll.vote(req.body.option, req.ip);
res.json(Polls.format(poll));
}
})
}
Polls.format = (poll) => ({
name: poll.name,
options: poll.options,
submitter: poll.submitter
});
Polls.formatOptions = (newOptions, oldOptions) => (
newOptions.reduce((x, y) => {
if (y) {
return Object.assign(x, {[y]: oldOptions[y] || 0})
}
return x;
}, {})
)
Polls.toCamelCase = (name) => (
name.trim()
.toLowerCase()
.replace(/[^\s[a-z]/ig, '')
.replace(
/(?:\s+([a-z]))/ig,
(match) => match.substring(match.length-1).toUpperCase()
)
)
module.exports = Polls;
|
'use strict';
/* global bootstrapModeler, inject */
var TestHelper = require('../../../TestHelper');
var modelingModule = require('../../../../lib/features/modeling'),
coreModule = require('../../../../lib/core');
describe('features/modeling - #removeConnection', function() {
var diagramXML = require('../../../fixtures/bpmn/sequence-flows.bpmn');
var testModules = [ coreModule, modelingModule ];
beforeEach(bootstrapModeler(diagramXML, { modules: testModules }));
describe('shape handling', function() {
it('should execute', inject(function(elementRegistry, modeling) {
// given
var sequenceFlowShape = elementRegistry.get('SequenceFlow_2'),
sequenceFlow = sequenceFlowShape.businessObject;
// when
modeling.removeConnection(sequenceFlowShape);
// then
expect(sequenceFlow.$parent).to.be.null;
}));
});
describe('undo support', function() {
it('should undo', inject(function(elementRegistry, modeling, commandStack) {
// given
var sequenceFlowShape = elementRegistry.get('SequenceFlow_2'),
sequenceFlow = sequenceFlowShape.businessObject,
parent = sequenceFlow.$parent;
// when
modeling.removeConnection(sequenceFlowShape);
commandStack.undo();
// then
expect(sequenceFlow.$parent).to.eql(parent);
}));
});
describe('redo support', function() {
it('redo', inject(function(elementRegistry, modeling, commandStack) {
// given
var sequenceFlowShape = elementRegistry.get('SequenceFlow_2'),
sequenceFlow = sequenceFlowShape.businessObject;
// when
modeling.removeConnection(sequenceFlowShape);
commandStack.undo();
commandStack.redo();
// then
expect(sequenceFlow.$parent).to.be.null;
}));
});
});
|
/**
* This file uses the Page Object pattern to define the main page for tests
* https://docs.google.com/presentation/d/1B6manhG0zEXkC-H-tPo2vwU06JhL8w9-XCF9oehXzAQ
*/
'use strict';
var MainPage = function() {
this.navBarBlock = $('.nav-bar-block[nav-bar="active"]');
this.headerTitleEl = this.navBarBlock.element(by.css('.title.header-item'));
this.jumbEl = element(by.css('.jumbotron'));
this.imgEl = this.jumbEl.element(by.css('img'));
this.thumbnailEls = element(by.css('body')).all(by.repeater('awesomeThing in main.awesomeThings'));
};
module.exports = new MainPage();
|
#!/usr/bin/env node
import program from "commander";
import say from "say";
import quotes from "../index.js";
const quote = quotes.random();
import { readFile } from 'fs/promises';
const pkg = JSON.parse(await readFile(new URL("../package.json", import.meta.url)));
const { log } = console;
program
.usage("desmotivacional [options]")
.option("-a, --all", "Exibe todas as frases")
.option("-l, --listen", "Ouça uma frase única")
.helpOption("-h, --help", "Exibe informações de uso")
.version(`${pkg.version}`, "-v, --version", "Exibe o número da versão")
program.on("--help", function(){});
program.parse(process.argv);
const options = program.opts();
if(program.args.length >= 1) program.help();
const listenQuote = () => {
say.speak(quote, 1.0, err => {
if(err) log(err);
});
}
if(options.listen) listenQuote();
(options && options.all) ? log(quotes.all.sort().join("\n")) : log(quote);
|
'use strict';
angularEditApp.controller('EditCtrl', function ($scope, $location, $timeout, editingPage, editorCommandSvc) {
// get the iframe
var frame = $('#editing-page-frame');
var editingPage;
var init = function () {
var resizeFrame = function () {
var t = $('#tool-bar').height() + 5;
var sb = $('#status-bar').height() + 5;
var wh = $(window).height();
var h = wh - t - sb;
if (h < 200) h = 200;
$('#frame-container').css('margin-top', t + 'px');
$('#frame-container').css('height', h + 'px');
};
// resize the iframe on window resize
$(function () {
$(window).resize(function () {
resizeFrame();
});
});
// set the url for the iframe
$scope.pageURL = $location.search()["url"];
resizeFrame();
$(frame).load(function () {
editingPage = editingPage.newPage(frame[0].contentWindow.document);
})
};
var issueCommand = function (cmd) {
console.log(cmd);
var message = editorCommandSvc.executeCommand(cmd, editingPage);
onSuccess(message);
};
var onSuccess = function (message) {
flash(message);
};
var flash = function (message) {
$scope.flashMessage = message;
$timeout(clearFlash, 1500);
};
var clearFlash = function () {
$scope.flashMessage = '';
};
$scope.autoCompleteCommands = function () {
return editorCommandSvc.getPossibleCommands(editingPage);
};
$scope.setAutoCompleteCommand = function () {
if ($scope.command.lastIndexOf('...') === $scope.command.length - 3) {
return $scope.command.substring(0, $scope.command.length - 3);
} else {
$scope.executeCommand();
return '';
}
};
$scope.executeCommand = function () {
issueCommand($scope.command);
$scope.command = '';
};
$scope.exec = function(cmd) {
issueCommand(cmd);
};
var updateMenu = function (el) {
var neverDisabled = false;
var editHTMLDisabled = true;
var editLINKDisabled = true;
var editIMAGEDisabled = true;
var editLinkFn = function() {link();};
var editImageFn = function() {image();};
if (angular.isDefined(el) && el !== null) {
switch (el.type) {
case 'HTML':
editHTMLDisabled = false;
editLINKDisabled = false;
editLinkFn = function() {link();};
break;
case 'LINK':
editLINKDisabled = false;
editLinkFn = function() {issueCommand('edit ' + el.id + ' --link')};
break;
case 'IMAGE-LINK':
editLINKDisabled = false;
editIMAGEDisabled = false;
editLinkFn = function() {issueCommand('edit ' + el.id + ' --link')};
editImageFn = function() {issueCommand('edit ' + el.id + ' --image')}
break;
case 'IMAGE':
editImageFn = function() {issueCommand('edit ' + el.id + ' --image')}
editIMAGEDisabled = false;
break;
}
}
$scope.showHTMLEditMenu = !editHTMLDisabled;
$scope.menuButtons = [];
$scope.menuButtons.push({title:"Save",icon:'save',disabled:neverDisabled,action:function() {issueCommand('save')}});
$scope.menuButtons.push({title:"Title",icon:'comment',disabled:neverDisabled,action:function() {issueCommand('edit _title')}});
$scope.menuButtons.push({title:"Undo",icon:'undo',disabled:neverDisabled,action:function() {issueCommand('undo')}});
$scope.menuButtons.push({title:"Redo",icon:'repeat',disabled:neverDisabled,action:function() {issueCommand('redo')}});
$scope.menuButtons.push({title:"Link",icon:'link',disabled:editLINKDisabled,action:function() {editLinkFn()}});
$scope.menuButtons.push({title:"Media",icon:'picture',disabled:editIMAGEDisabled,action:function() {editImageFn()}});
$scope.menuButtons.push({title:"Edit",icon:'edit',disabled:editHTMLDisabled,action:function() {issueCommand('edit')}});
};
$scope.$on('editingSelection', function (evt, el) {
updateMenu(el);
$scope.$apply();
});
$scope.$on('executeCommand', function (evt, cmd) {
issueCommand(cmd);
});
var updateSelection = function(el) {
var sel = rangy.getIframeSelection(frame[0]);
var range = sel.rangeCount ? sel.getRangeAt(0) : null;
if (range.startContainer.parentElement.localName === el) {
var el = $(range.startContainer.parentElement);
$(el).replaceWith(el.html());
return null;
} else {
var element = document.createElement(el);
range.surroundContents(element);
return element;
}
};
$scope.style = function(style) {
var el = updateSelection(style);
issueCommand('changed');
return false;
};
var link = function() {
var sel = rangy.getIframeSelection(frame[0]);
var range = sel.rangeCount ? sel.getRangeAt(0) : null;
$scope.$apply($scope.$broadcast('editLinkSelection', range, {'html':"link"}));
};
var image = function() {
};
init();
updateMenu();
});
|
var api = {
bluetooth: null,
genericAttributionProfile: null,
enumeration: null,
deviceWatcher: null,
devices: new Array()
}
document.addEventListener("DOMContentLoaded", function () {
api.bluetooth = Windows.Devices.Bluetooth;
api.genericAttributionProfile = Windows.Devices.Bluetooth.GenericAttributeProfile;
api.enumeration = Windows.Devices.Enumeration;
api.deviceWatcher = Windows.Devices.Enumeration.DeviceWatcher;
if (typeof api.bluetooth === 'undefined') { throw "app.bluetooth is undefined"; }
if (typeof api.genericAttributionProfile === 'undefined') { throw "app.genericAttributionProfile is undefined"; }
if (typeof api.enumeration === 'undefined') { throw "app.enumeration is undefined"; }
if (typeof api.deviceWatcher === 'undefined') { throw "app.deviceWatcher is undefined"; }
api.bluetooth.BluetoothAdapter.getDefaultAsync()
.then(bluetoothAdapterCreated, bluetoothAdapterFailed);
document.getElementById("reloadBtn").addEventListener("click", reload);
});
function bluetoothAdapterCreated(adapter) {
renderDataToDOM("Bluetooth Address", adapter.bluetoothAddress);
renderDataToDOM("DeviceID", adapter.deviceId);
renderDataToDOM("Is Advertisement Offload Supported", adapter.isAdvertisementOffloadSupported);
renderDataToDOM("Is Peripheral Role Supported", adapter.isPeripheralRoleSupported);
renderDataToDOM("Is Low Energy Supported", adapter.isLowEnergySupported);
renderDataToDOM("Is Central Role Supported", adapter.isCentralRoleSupported);
renderDataToDOM("Is Classis Supported", adapter.isClassicSupported);
// start a device watcher
startDeviceWatcher();
}
function bluetoothAdapterFailed(error) {
renderDataToDOM("Error", error);
}
function startDeviceWatcher() {
var requestedProperties = ["System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected"];
api.deviceWatcher = Windows.Devices.Enumeration.DeviceInformation.createWatcher(
'System.Devices.Aep.ProtocolId:="{bb7bb05e-5972-42b5-94fc-76eaa7084d49}"',
null, //requestedProperties,
Windows.Devices.Enumeration.DeviceInformationKind.associationEndpoint);
api.deviceWatcher.addEventListener("added", deviceWatcherAdded);
api.deviceWatcher.addEventListener("updated", deviceWatcherUpdated);
api.deviceWatcher.addEventListener("removed", deviceWatcherRemoved);
api.deviceWatcher.addEventListener("enumerationcompleted", deviceWatcherEnumerationCompleted);
api.deviceWatcher.addEventListener("stopped", deviceWatcherStopped);
api.deviceWatcher.start();
}
function deviceWatcherAdded(evt) {
console.log("deviceWatcherAdded");
// Add device information to devices array
api.devices.push(evt.detail[0]);
renderDataToDOM("id", evt.detail[0].id);
renderDeviceConnectButtonToDOM(evt.detail[0].id);
renderDataToDOM("name", evt.detail[0].name);
renderDataToDOM("kind", evt.detail[0].kind);
renderDataToDOM("Can Pair", evt.detail[0].pairing.canPair);
renderDataToDOM("Protection Level", evt.detail[0].pairing.protectionLevel);
//renderDataToDOM("Is Default", evt.detail[0].isDefault);
//renderDataToDOM("Is Enabled", evt.detail[0].isEnabled);
}
function deviceWatcherUpdated(evt) {
console.log("deviceWatcherUpdated");
}
function deviceWatcherRemoved(evt) {
console.log("deviceWatcherRemoved");
}
function deviceWatcherEnumerationCompleted(evt) {
console.log("deviceWatcherEnumerationCompleted");
}
function deviceWatcherStopped(evt) {
console.log("deviceWatcherStopped");
}
// Helper function to display data
function renderDataToDOM(label, text) {
var infoElem = document.createElement("div");
infoElem.setAttribute("class", "labelContainer");
var labelElem = document.createElement("span");
var textElem = document.createElement("span");
labelElem.setAttribute("class", "label");
var labelElemText = document.createTextNode(label + ":");
var textElemText = document.createTextNode(text);
labelElem.appendChild(labelElemText);
textElem.appendChild(textElemText);
infoElem.appendChild(labelElem);
infoElem.appendChild(textElem);
document.body.appendChild(infoElem);
}
function renderDeviceConnectButtonToDOM(id) {
var buttonElem = document.createElement("button");
buttonElem.setAttribute("id", id);
buttonElem.appendChild(document.createTextNode("Connect"));
buttonElem.addEventListener('click', function () { connectToDevice(id); });
document.body.appendChild(buttonElem);
}
function connectToDevice(id) {
var bluetoothLEDevice = api.bluetooth.BluetoothLEDevice.fromIdAsync(id)
.then(deviceFromIdAsyncCompleted, deviceFromIdAsyncError)
.done(console.log("Promise is finished for fromIdAsync"));
}
function deviceFromIdAsyncCompleted(device) {
device.getGattServicesAsync(api.bluetooth.BluetoothCacheMode.uncached)
.then(getGattServicesCompleted, getGattServicesError)
.done(console.log("Promise is finised for getGattServicesAsync"));
}
function deviceFromIdAsyncError(error) {
}
function getGattServicesCompleted(obj) {
}
function getGattServicesError(obj) {
}
function reload(){
document.location.reload(true);
}
|
// Karma configuration
// Generated on Thu Nov 07 2013 22:03:46 GMT-0700 (Mountain Standard Time)
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// frameworks to use
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'angular-1.2.0/angular.js',
'angular-1.2.0/angular-*.js',
'../../Web/**/*.js',
'**/*.js'
],
// list of files to exclude
exclude: [
'angular-1.2.0/angular-loader.js',
'angular-1.2.0/*.min.js',
'angular-1.2.0/angular-scenario.js',
'../../Web/Content/bootstrap-*/**/*.js',
'../../Web/obj/**/*.js'
],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera (has to be installed with `npm install karma-opera-launcher`)
// - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
// - PhantomJS
// - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
browsers: ['PhantomJS'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
// report which specs are slower than 500ms
// CLI --report-slower-than 500
reportSlowerThan: 500,
plugins: [
'karma-jasmine',
'karma-phantomjs-launcher'
]
});
};
|
/* @flow */
'use strict'
/* ::
import type {
CLIFlags,
CLIOptions
} from '../types.js'
*/
const scope = require('../lib/scope')
module.exports = function(
input /* : Array<string> */,
flags /* : CLIFlags */,
logger /* : typeof console */,
options /* : CLIOptions */
) /* : Promise<void> */ {
const cwd = flags.cwd
const project = input[0]
const tenant = flags.tenant
return Promise.resolve()
.then(() => {
if (project) {
return scope.write(cwd, {
project,
tenant
})
}
})
.then(() => scope.display(logger, cwd))
}
|
Rx.Observable.prototype.$apply = function (scope, thisArg) {
var self = this;
return new Rx.AnonymousObservable(function (observer) {
return self.subscribe(
function (e) {
scope.$apply(function () { observer.onNext(e); });
},
observer.onError.bind(observer),
observer.onCompleted.bind(observer)
);
});
};
|
/* eslint-disable react/prefer-stateless-function, react/no-multi-comp, react/prop-types
eslint-disable prefer-template, react/prefer-es6-class, react/jsx-filename-extension, camelcase,
react/no-unused-prop-types */
import React from 'react';
import { dep } from 'worona-deps';
import { connect } from 'react-redux';
import { Route, IndexRoute } from 'react-router';
import CssLoader from '../components/CssLoader';
import * as selectors from '../selectors';
import * as deps from '../deps';
const mapStateToProps = state => ({ themeName: deps.selectors.getThemeName(state) });
class ThemeLoaderClass extends React.Component {
render() {
const Theme = dep('theme', 'components', 'Theme');
return (
<div id="root">
<CssLoader />
<Theme {...this.props} />
</div>
);
}
}
const ThemeLoader = connect(mapStateToProps)(ThemeLoaderClass);
class EntryClass extends React.Component {
render() {
try {
const Component = dep('theme', 'components', this.props.component);
return <Component {...this.props} />;
} catch (error) {
const Component = dep('theme', 'components', 'Home');
return <Component {...this.props} />;
}
}
}
EntryClass.propTypes = { component: React.PropTypes.string };
const Entry = connect(mapStateToProps)(EntryClass);
const Content = connect(state => ({
contentType: selectors.getContentType(state),
}))(({ contentType }) => <Entry component={contentType} />);
const addSiteId = store =>
(prevState, nextState, replace) => {
if (!nextState.location.query.siteId) {
const siteId = store.getState().router.siteId;
if (siteId) {
replace({
pathname: nextState.location.pathname,
query: { ...nextState.location.query, siteId },
});
}
}
};
export const routes = store => (
<Route path="/" component={ThemeLoader}>
<IndexRoute component={Content} onChange={addSiteId(store)} />
<Route path="*" component={Content} onChange={addSiteId(store)} />
</Route>
);
export default routes;
|
'use strict';
const bcrypt = require('bcrypt');
const _ = require('lodash');
module.exports = function (sequelize, DataTypes) {
var User = sequelize.define('User', {
email: {
type: DataTypes.STRING
},
password: {
type: DataTypes.STRING,
},
firstName: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING,
allowNull: false
},
facebookId: {
type: DataTypes.BIGINT
},
googleId: {
type: DataTypes.BIGINT
}
}, {
indexes: [
{
unique: true,
fields: ['facebookId']
},
{
unique: true,
fields: ['googleId']
},
{
unique: true,
fields: ['email']
}
],
classMethods: {
associate: function (models) {
// associations can be defined here
},
generateHash: function (password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
}
},
instanceMethods: {
validPassword: function (password) {
return bcrypt.compareSync(password, this.password);
},
toJSON: function () {
var privateAttributes = [ 'password' ];
return _.omit(this.dataValues, privateAttributes);
}
}
});
return User;
};
|
(function($){
var DicePicker = function(character, brain){
this.brain = brain;
this.character = character;
this.rolling_ctr = 0;
};
DicePicker.prototype.pick_die = function(task) {
//console.log("pick_die");
if(this.is_rolling()){
//console.log("is_rolling");
//Add a check to not wait more than 10 times; instead end the task, start a new SCA task
//This will prevent getting stuck on the dice rolling screen, as has happened.
if(this.rolling_ctr++ > 10){
return {
error: false,
delay: 1000
};
}
return {
error: true,
delay: 500 * this.rolling_ctr + 500
};
}
var die = this.brain.find_die();
if(!die){
//console.log("no die");
return {
error: false,
delay: 1000
}
}
die.trigger('click');
task.insert(this.pick_die.bind(this));
return {
error: false,
delay: 1000
};
};
DicePicker.prototype.is_rolling = function() {
return $('.combatDiceBox').is(':visible') && !$('.modal-window').is(':visible');
};
$.extend(true, $.nwg, {
dicePicker: {
create:function(character, brain){
return new DicePicker(character, brain);
}
}
});
}(jQuery));
|
/**
* Test case for knListItemText.
* Runs with mocha.
*/
"use strict";
const knListItemText = require('../lib/kn_list_item_text.js'),
assert = require('assert');
describe('kn-list-item-text', () => {
before((done) => {
done();
});
after((done) => {
done();
});
it('Kn list item text', (done) => {
done();
});
});
|
/*
Simple OpenID Plugin
http://code.google.com/p/openid-selector/
This code is licensed under the New BSD License.
*/
var providers_large = {
google : {
name : 'Google',
url : 'https://www.google.com/accounts/o8/id'
},
yahoo : {
name : 'Yahoo',
url : 'http://me.yahoo.com/'
}
// aol : {
// name : 'AOL',
// label : 'Enter your AOL screenname.',
// url : 'http://openid.aol.com/{username}'
// }
// paypal : {
// name : 'Paypal',
// label : 'Enter your paypal screenname.',
// url : 'http://openid.aol.com/{username}'
// },
// myopenid : {
// name : 'MyOpenID',
// label : 'Enter your MyOpenID username.',
// url : 'http://{username}.myopenid.com/'
// },
// openid : {
// name : 'OpenID',
// label : 'Enter your OpenID.',
// url : null
// }
};
var providers_small = {
// livejournal : {
// name : 'LiveJournal',
// label : 'Enter your Livejournal username.',
// url : 'http://{username}.livejournal.com/'
// },
/* flickr: {
name: 'Flickr',
label: 'Enter your Flickr username.',
url: 'http://flickr.com/{username}/'
}, */
/* technorati: {
name: 'Technorati',
label: 'Enter your Technorati username.',
url: 'http://technorati.com/people/technorati/{username}/'
}, */
// wordpress : {
// name : 'Wordpress',
// label : 'Enter your Wordpress.com username.',
// url : 'http://{username}.wordpress.com/'
// },
// blogger : {
// name : 'Blogger',
// label : 'Your Blogger account',
// url : 'http://{username}.blogspot.com/'
// },
// verisign : {
// name : 'Verisign',
// label : 'Your Verisign username',
// url : 'http://{username}.pip.verisignlabs.com/'
// },
/* vidoop: {
name: 'Vidoop',
label: 'Your Vidoop username',
url: 'http://{username}.myvidoop.com/'
}, */
/* launchpad: {
name: 'Launchpad',
label: 'Your Launchpad username',
url: 'https://launchpad.net/~{username}'
}, */
// claimid : {
// name : 'ClaimID',
// label : 'Your ClaimID username',
// url : 'http://claimid.com/{username}'
// },
// clickpass : {
// name : 'ClickPass',
// label : 'Enter your ClickPass username',
// url : 'http://clickpass.com/public/{username}'
// },
// google_profile : {
// name : 'Google Profile',
// label : 'Enter your Google Profile username',
// url : 'http://www.google.com/profiles/{username}'
// }
};
openid.locale = 'en';
openid.sprite = 'en'; // reused in german& japan localization
openid.demo_text = 'In client demo mode. Normally would have submitted OpenID:';
openid.signin_text = 'Sign-In';
openid.image_title = 'log in with {provider}';
|
var mdWidget = function(srcEle, destEle){
$(srcEle).on('keyup', 'textarea', function(){
// get the text
// ask the model to convert it to html
// ask the view to display it
identityTransform(srcEle, destEle);
});
}
|
// In production, we register a service worker to serve assets from local cache.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since previously
// cached resources are updated in the background.
// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
// This link also includes instructions on opting out of this behavior.
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
)
export default function register () {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location)
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
return
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`
if (!isLocalhost) {
// Is not local host. Just register service worker
registerValidSW(swUrl)
} else {
// This is running on localhost. Lets check if a service worker still exists or not.
checkValidServiceWorker(swUrl)
}
})
}
}
function registerValidSW (swUrl) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and
// the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
if (window.confirm('Nueva versión de la aplicacion disponible, actualizar la página por favor')) {
window.location.reload(true)
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.')
}
}
}
}
})
.catch(error => {
console.error('Error during service worker registration:', error)
})
}
function checkValidServiceWorker (swUrl) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
if (
response.status === 404 ||
response.headers.get('content-type').indexOf('javascript') === -1
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload()
})
})
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl)
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
)
})
}
export function unregister () {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister()
})
}
}
|
$(document).ready(function() {
$('#institution_id').change(function() {
$('#collection_select').val('');
loadSummary();
});
$('#collection').on("change", "#collection_select", function() {
loadSummary();
});
function loadIndicator(show) {
if (show) {
$('#summary-stats').attr('aria-busy', 'true')
.prepend('<h3 id="summary-stats__loading">Loading...</h3>')
}
else {
$('#summary-stats__loading').remove();
$('#summary-stats').attr('aria-busy', 'false');
}
}
function loadSummary() {
var institutionId = $("#institution_id").val() || 0
var collectionId = (
institutionId === 0 ?
0 :
$("#collection_select").val() || 0
);
loadIndicator(true);
$.ajax({
method: 'get',
url: '/admin/summary/details',
data: {
institution_id: institutionId,
collection_id: collectionId
},
type: 'script',
success: function(data, testStatus, jqXHR) {
loadIndicator(false);
}
});
}
loadSummary();
})
|
'use strict';
var Command = require('./command');
module.exports = function (grunt, path, classToRun) {
var cmd = new Command();
if (grunt.file.isDir(path)) {
cmd.append(path);
} else {
cmd.append(classToRun, path);
}
return {
command: function () {
return cmd.toString();
}
};
};
|
/**
* Haku : a mobile and web build framework based on Phonegap and Backbone.
* @url https://github.com/shukriadams/haku
* @author Shukri Adams (shukri.adams@gmail.com)
*
* WARNING : This file is managed by Haku's own build scripts, and may be overwritten as part of the normal build process.
* Do not change its contents unless you know what you're doing.
*/
/*
Namespaces reference
haku.app; Running instance of app. Global dependency, must be initialized. Starting app sets it.
haku.router; Router instance
haku.settings; Global settings holder
haku.application. : App class (type).
*/
(function () {
'use strict';
// ===========================================================================
// Router. Override this and add routes and route handlers for your own app.
// ---------------------------------------------------------------------------
var router = Backbone.Router.extend({
currentView: null,
root: null,
initialize: function () {
// causes routes to appear as full pages
Backbone.history.start({ pushState: true });
// get absolute path of app resources - required by ios
if (haku.settings.getSystemPathRootAtStart){
haku.settings.systemPathRoot = window.location.pathname.replace("index.html", "");
}
},
// transitions page view in. If page supports sliding transition,
// slide is done. Else a hard attachment is done.
_showPageView: function (view) {
// removes old page out, if page supports t
var previousView = this.currentView || null;
if (previousView && previousView.transitionOut) {
previousView.transitionOut(function () {
previousView.remove();
});
}
view.render();
view.$el.addClass('page');
if (view.transitionIn) {
view.transitionIn();
}
this.currentView = view;
this.root.empty();
this.root.append(view.$el);
// call method that tells view its content is now visible
if (view.__proto__.hasOwnProperty("onShow")){
view.onShow();
}
}
});
klon.register('haku.routers', router);
// ===========================================================================
// App. Override this if necessary, then create an instance and .start().
// ---------------------------------------------------------------------------
var app = Backbone.Model.extend({
initialize : function(){
haku.app = this;
},
/**
* Loads a CSS file dynamically; use this as workaround to lack of RequireJS css loader
* @param {string} href - Path to css file
* @param {string} [id] - Optional unique key for resource. Assign a key to an href if you want to replace it a later stage with something else.
* */
requireCss : function (href, key){
// partial IE 7 fallback. Reimplement unique checks.
if (document.createStyleSheet)
{
document.createStyleSheet(href);
return;
}
var head = document.getElementsByTagName("head")[0];
var fileRef;
if (key)
fileRef = head.querySelectorAll('link[id="' + key + '"]');
else
fileRef = head.querySelectorAll('link[href="' + href + '"]');
if (fileRef && fileRef.length === 0) {
fileRef = document.createElement("link");
} else {
fileRef = fileRef[0];
}
// note : append element BEFORE setting attributes, due to an IE quirk
head.appendChild(fileRef);
fileRef.setAttribute("type", "text/css");
fileRef.setAttribute("rel", "stylesheet");
if (key){
fileRef.setAttribute("id", key);
}
// note : href must be added LAST because of an IE quirk
fileRef.setAttribute("href", href);
},
start : function(){
// start router
haku.router = haku.routers.instance();
// start foundation. Do this after router initializes with default views
$(document).foundation();
}
});
klon.register('haku.application', app);
// ===========================================================================
// Global instances provider
// ---------------------------------------------------------------------------
haku.app = null;
haku.router = null;
haku.settings = haku.settings || null;
haku.authentication = null;
haku.storage = null;
}());
|
module.exports = function(grunt) {
grunt.initConfig({
uglify: {
options: {
compress: {}
},
in_view: {
files: {
'jquery.in-view.min.js': ['jquery.in-view.js']
}
}
},
watch: {
uglify: {
files: ['jquery.in-view.js', 'Gruntfile.js'],
tasks: ['uglify']
}
},
release: {
}
});
grunt.loadNpmTasks('grunt-release');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask('default', ['watch']);
grunt.registerTask('publish', ['release']);
};
|
const express = require('express');
const morgan = require('morgan');
const path = require('path');
const app = express();
// Setup logger
app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] :response-time ms'));
// Serve static assets
app.use(express.static(path.resolve(__dirname, '..', 'build')));
// Always return the main index.html, so react-router render the route in the client
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});
module.exports = app;
|
/* eslint-disable no-underscore-dangle */
import React from 'react';
import PropTypes from 'prop-types';
import hoistNonReactStatics from 'hoist-non-react-statics';
import { getDisplayName, ponyfillGlobal } from '@material-ui/utils';
import createMuiTheme from './createMuiTheme';
import themeListener from './themeListener';
let defaultTheme;
function getDefaultTheme() {
if (defaultTheme) {
return defaultTheme;
}
defaultTheme = createMuiTheme({
typography: {
suppressWarning: true,
},
});
return defaultTheme;
}
// Provide the theme object as a property to the input component.
const withThemeOld = () => Component => {
class WithTheme extends React.Component {
constructor(props, context) {
super();
this.state = {
// We use || as the function call is lazy evaluated.
theme: themeListener.initial(context) || getDefaultTheme(),
};
}
componentDidMount() {
this.unsubscribeId = themeListener.subscribe(this.context, theme => {
this.setState({ theme });
});
}
componentWillUnmount() {
if (this.unsubscribeId !== null) {
themeListener.unsubscribe(this.context, this.unsubscribeId);
}
}
render() {
const { innerRef, ...other } = this.props;
return <Component theme={this.state.theme} ref={innerRef} {...other} />;
}
}
WithTheme.propTypes = {
/**
* Use that property to pass a ref callback to the decorated component.
*/
innerRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
};
WithTheme.contextTypes = themeListener.contextTypes;
if (process.env.NODE_ENV !== 'production') {
WithTheme.displayName = `WithTheme(${getDisplayName(Component)})`;
}
hoistNonReactStatics(WithTheme, Component);
if (process.env.NODE_ENV !== 'production') {
// Exposed for test purposes.
WithTheme.Naked = Component;
}
return WithTheme;
};
/* istanbul ignore if */
if (!ponyfillGlobal.__MUI_STYLES__) {
ponyfillGlobal.__MUI_STYLES__ = {};
}
if (!ponyfillGlobal.__MUI_STYLES__.withTheme) {
ponyfillGlobal.__MUI_STYLES__.withTheme = withThemeOld;
}
export default ponyfillGlobal.__MUI_STYLES__.withTheme;
|
var React = require("react") // eslint-disable-line
module.exports = function(props) {
var content = React.createElement("div", { // eslint-disable-line
dangerouslySetInnerHTML: { __html: props.file.contents },
})
return React.createElement("div", null, [ "Hello", content ])
}
|
function save_options() {
var showIMDB = document.getElementById('imdb').checked;
var showTrakt = document.getElementById('trakt').checked;
var showTrailer = document.getElementById('trailer').checked;
var showMissing = document.getElementById('missing').checked;
var showMissingSpecials = document.getElementById('missingSpecials').checked;
chrome.storage.sync.set({
showIMDB: showIMDB,
showTrakt: showTrakt,
showTrailer: showTrailer,
showMissing: showMissing,
showMissingSpecials: showMissingSpecials
}, function() {
var status = document.getElementById('status');
status.textContent = 'Options saved. Plex application page needs to be reloaded.';
setTimeout(function() {
status.textContent = '';
}, 3000);
});
}
function restore_options() {
chrome.storage.sync.get({
showIMDB: true,
showTrakt: true,
showTrailer: true,
showMissing: true,
showMissingSpecials: true
}, function(items) {
document.getElementById('imdb').checked = items.showIMDB;
document.getElementById('trakt').checked = items.showTrakt;
document.getElementById('trailer').checked = items.showTrailer;
document.getElementById('missing').checked = items.showMissing;
document.getElementById('missingSpecials').checked = items.showMissingSpecials;
});
}
document.addEventListener('DOMContentLoaded', restore_options);
document.getElementById('save').addEventListener('click',
save_options);
|
import {LOAD_FORM_ID} from './constant'
export default {
[LOAD_FORM_ID](state, payload) {
state.id = payload
}
}
|
cg.Ball = function Ball(args){
if (!args) return this;
//this.owningPlayer = args.playerId;
this.createShape(args.pos);
//this.move(args.pos); //Why did we do this?
};
cg.Ball.prototype = {};
cg.Ball.prototype.createShape = function createShape(pos){
this.shape = new fabric.Circle({
left: pos[0],
top: pos[1],
fill: '#FF8600',
radius: 10,
opacity:1
});
canvas.add(this.shape);
};
cg.Ball.prototype.move = function move(x, y){
this.shape.set('left', x);
this.shape.set('top', y);
};
cg.Ball.prototype.destroy = function destroy(){
canvas.fxRemove(this.shape);
};
|
/**
* @author Lars Rohwedder
*
* Classes for managing any large data object in presentation files (like imported Images).
* Those are transmitted from/to server in Base64 encoding.
* Includes retain/release functions for finding unused objects.
*/
(function(Resource) {
// dependencies
var Misc = sp.module("misc");
Resource.Model.Resource = Backbone.Model.extend({
"initialize" : function() {
this._retainCount = 0;
if(!this.get("_data"))
this.set("_data", 0);
this.on("destroy", function() {
if(this._texture) {
this.collection.renderer.deallocateTexture(this._texture);
}
}, this);
},
"retain" : function() {
this.trigger("retain");
this._retainCount++;
},
"release" : function() {
this.trigger("release");
if(--this._retainCount <= 0) {
this.destroy();
}
},
"destroy" : function() {
this.trigger("destroy", this, this.collection);
},
"getText" : function() {
if(this._text)
return this._text;
return this._text = decodeURIComponent(escape(window.atob(this.get("_data"))));
},
"getImage" : function() {
if(this._image)
return this._image;
var im = this._image = new Image();
im.src = "data:"+(this.get("content_type") || "application/octet-stream")+";base64,"+this.get("_data");
return im;
},
"getTexture" : function() {
if(this._texture)
return this._texture;
//don't use THREE.ImageUtils.loadTexture,
//it doesn't work with data urls
var scope = this,
im = this.getImage(),
texture = this._texture = new THREE.Texture(im);
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
if(im.width && im.height) {
// no mipmaps only allowed for sizes 2, 4, 8, 16...
if((Math.log(im.width) / Math.log(2)) % 1 > 0
|| (Math.log(im.height) / Math.log(2)) % 1 > 0) {
texture.generateMipmaps = false;
}
}
im.onload = function() {
if((Math.log(im.width) / Math.log(2)) % 1 > 0
|| (Math.log(im.height) / Math.log(2)) % 1 > 0) {
texture.generateMipmaps = false;
}
scope.trigger("load");
texture.needsUpdate = true;
};
return texture;
},
"getGeometry" : function() {
if(this._geometry)
return this._geometry;
this._geometry = new THREE.Geometry();
var group = new THREE.OBJLoader().parse(this.getText());
for(var i=0; i<group.children.length; i++)
THREE.GeometryUtils.merge(this._geometry, group.children[i]);
return this._geometry;
},
"toJSON" : function(stubs) {
if(stubs && !this._dirty) {
return {
"content_type" : this.get("content_type") || "application/octet-stream",
"stub" : true,
"length" : this.get("_data").length
}
} else {
return {
"content_type" : this.get("content_type") || "application/octet-stream",
"stub" : false,
"length" : this.get("_data").length,
"data" : this.get("_data")
}
}
}
}, {
"fromFile" : function(file, callback, context) {
var reader = new FileReader();
reader.onload = function(e) {
var dataUrl = e.target.result;
//trim to actual data
var i=4;
while(dataUrl[i] !== ",")
i++;
var result = new Resource.Model.Resource({"_data":dataUrl.substring(i+1), "name":file.name, "content_type" : file.type});
if(context)
callback.call(context, result);
else
callback(result);
};
reader.readAsDataURL(file);
},
"fromPlainText" : function(text) {
return new Resource.Model.Resource({
"_data" : window.btoa(unescape(encodeURIComponent(text))),
"_text" : text
});
},
"fromJSON" : function(json, id) {
return new Resource.Model.Resource({
"content_type" : json.content_type,
"_data" : json.data,
"id" : id
});
}
});
Resource.Model.ResourceCollection = Backbone.Collection.extend({
"createID" : function() {
var id;
do {
// IDs 0x0 to 0xFFF are reserved
id = 0x100 * (Math.round(Math.random() * 0xFFEF) + 0x0010);
} while(this.get(id));
return id;
},
"toJSON" : function(stubs) {
var result = {};
for(var i=0; i<this.models.length; i++) {
result[this.models[i].id] = this.models[i].toJSON(stubs);
}
return result;
}
});
}(sp.module("resource")));
|
// Use javascript sort function
process.stdin.resume();
process.stdin.setEncoding('utf8');
function sorter(a,b){return a-b}
var data = '';
var t;
var start = process.hrtime();
var elapsed_time = function(note){
var precision = 3; // 3 decimal places
var elapsed = process.hrtime(start)[1] / 1000000; // divide by a million to get nano to milli
console.log(elapsed.toFixed(precision) + " ms - " + note); // print message + time
start = process.hrtime(); // reset the timer
}
function numericize(elem, pos, self) {
self[pos] = Number(elem);
return true;
}
process.stdin.on('data', function(chunk) {
data += chunk;
});
process.stdin.on('end', function() {
var arr = data.split('\n');
t = arr.shift();
arr.every(numericize);
arr.sort(sorter);
process.stdout.write(arr.join("\n") + "\n");
elapsed_time("Execution");
var util = require('util');
console.log(util.inspect(process.memoryUsage()));
});
|
import moment from 'moment'
const FORMAT = 'YYYY-MM-DD HH:mm:ss.SSSSSSSSSZZ'
export const NOW_STRING = 'time.Now()'
export function parse (timeString) {
return moment(timeString, FORMAT)
}
export function stringify () {
return moment().format(FORMAT)
}
|
var getState = require('get-state.js');
describe('getState', function () {
it('successfully gets the state if passed number zero', function () {
var result = getState(
{_radiumStyleState: {'0': {':hover': true}}},
0,
':hover'
);
expect(result).to.equal(true);
});
});
|
/**
* The examples provided by Formidable Labs are for non-commercial testing and
* evaluation purposes only. Formidable Labs reserves all rights not expressly
* granted.
*
* 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
* FORMIDABLE LABS 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.
*/
var path = require('path');
var webpack = require('webpack');
module.exports = {
cache: true,
entry: {
index: "./examples/index.js"
},
output: {
path: path.join(__dirname),
publicPath: '/',
filename: '[name].js',
chunkFilename: '[chunkhash].js'
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader?stage=0'
},
{
test: /\.jsx$/,
loader: 'babel-loader?stage=0'
}
]
}
}
|
angular.module('app', ['ng-clamper'])
.controller('AppController', ['$rootScope', '$scope', function AppCtrl($rootScope, $scope) {
var app = this;
app.loaded = true;
app.author = 'Kevin Chappell';
app.clampSize = 3;
app.introClamp = {
clamp: app.clampSize,
toggle: true,
end: '…'
};
$scope.$watch('app.clampSize', function(){
app.introClamp.clamp = app.clampSize;
});
}]);
|
angular.module('mean', ['ngCookies', 'ngResource', 'ngRoute', 'ui.bootstrap', 'ui.route', 'mean.system', 'mean.buckets', 'mean.s3objects', 'mean.musers', 'mean.logevents']);
angular.module('mean.system', []);
angular.module('mean.buckets', []);
angular.module('mean.s3objects', []);
angular.module('mean.musers', []);
angular.module('mean.logevents', []);
|
/*
* shufle.js
* ---------
* Randomize array element order in-place.
* Using Fisher-Yates shuffle algorithm.
*
*/
function shuffle(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
|
import styled from "styled-components";
import { COLOR_WHITE, COLOR_HIGHLIGHT } from "style/styleVariables";
import { form_control } from "components/globalPatterns";
const InspectorSearch = styled.input`
${form_control};
appearance: none;
margin: 8px;
box-shadow: inset 0 0 0 rgba(0, 0, 0, 0), 0 0 0 rgba(0, 0, 0, 0),
0 0 0 rgba(0, 0, 0, 0);
text-align: left;
user-select: auto;
width: calc(100% - 16px);
&[type="text"],
&[type="search"] {
cursor: text;
&:focus {
&::placeholder {
opacity: 0;
}
}
}
&::placeholder {
color: currentColor;
opacity: 1;
text-align: center;
}
&::-ms-expand {
background-color: transparent;
border: 0;
}
&:focus {
box-shadow: inset 0 0 0 rgba(255, 255, 255, 0.5),
0 0 0 1px ${COLOR_HIGHLIGHT.mix(COLOR_WHITE, 0.25).string()},
0 0 0 4px ${COLOR_HIGHLIGHT.mix(COLOR_WHITE, 0.75).string()};
outline: none;
}
`;
export default InspectorSearch;
|
const db = require('../database/index.js');
const dbQuery = require('../controller/index.js');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const managerController = require('../controller/manager.js');
const userController = require('../controller/user.js');
const util = require('../controller/util.js');
passport.use(new LocalStrategy(
{ passReqToCallback: true },
function(req, username, password, done) {
const additionalLoginData = req.body;
if (additionalLoginData.role === 'manager') {
dbQuery.getManagerInfo(username)
.then(user => {
if (!user) {
return done(null, false, { message: 'incorrect username' });
}
var inputPassword = util.genPassword(password, user.passwordSalt);
if (user.passwordHash !== inputPassword.passwordHash) {
return done(null, false, { message: 'incorrect password' });
}
return done(null, user);
})
.catch(err => done(err));
} else if (additionalLoginData.role === 'customer') {
// TODO: User is only used for authentication, right now the Customer object
// being used, so we probably want to switch to using User at some point
dbQuery.getUserInfo(username)
.then(user => {
if (!user) {
return done(null, false, { message: 'incorrect username' });
}
// only allow customers to login
if (user.dataValues.role !== 'customer') {
return done(null, false, { message: 'attempt to login with incorrect user type' });
}
var inputPassword = util.genPassword(password, user.passwordSalt);
if (user.passwordHash !== inputPassword.passwordHash) {
return done(null, false, { message: 'incorrect password' });
}
return done(null, user);
})
.catch(err => done(err));
} else {
return done(null, false, { message: 'invalid role' });
}
}
));
passport.serializeUser(function(user, done) {
// console.log('serializing user: ', user.id);
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
// console.log('deserializing user: ', id);
dbQuery.getUserProfileInfo(id)
.then(user => {
//TODO: At this point our UserProfile data is valid.
// We need to figure out what we want to do next
// console.log('found user: ', user.id);
return done(null, user);
})
.catch(err => {
// console.log('error finding user: ', err);
return done(err, null);
});
// db.Manager.findById(id).then(user => done(null, user)).catch(err => done(err, null));
});
module.exports = passport;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var SurveyMeasurement_1 = require("../../../../services/surveyDb/types/SurveyMeasurement");
var survey_measurement_1 = require("../../survey-measurement");
var material_1 = require("@angular/material");
var edit_survey_point_1 = require("../../survey-point/edit/edit-survey-point");
var TraverseEditBaseComponent = (function () {
function TraverseEditBaseComponent(_dialogService, surveyCalc, travProvider, pointProvider, measProvider, pointService) {
this._dialogService = _dialogService;
this.surveyCalc = surveyCalc;
this.travProvider = travProvider;
this.pointProvider = pointProvider;
this.measProvider = measProvider;
this.pointService = pointService;
}
Object.defineProperty(TraverseEditBaseComponent.prototype, "Traverse", {
get: function () {
return this.travProvider.Traverse;
},
set: function (value) {
this.travProvider.Traverse = value;
},
enumerable: true,
configurable: true
});
TraverseEditBaseComponent.prototype.onAddMeasurement = function () {
var _this = this;
var config = new material_1.MdDialogConfig();
this.measProvider.SurveyMeasurement = new SurveyMeasurement_1.SurveyMeasurement();
if (this.Traverse.SurveyMeasurement.length) {
this.measProvider.SurveyMeasurement.PointFrom = this.Traverse.SurveyMeasurement[this.Traverse.SurveyMeasurement.length - 1].PointTo;
}
else if (this.Traverse.StartPoint) {
this.measProvider.SurveyMeasurement.PointFrom = this.Traverse.StartPoint;
}
this._dialogService.open(survey_measurement_1.AddSurveyMeasurementComponent, config)
.afterClosed()
.subscribe(function (result) {
if (result) {
result.Bearing = _this.surveyCalc.toDegrees(result.Bearing);
result.SurveyID = 1;
_this.addMeasurementToTraverse(result);
}
else {
console.log("Cancel");
}
});
};
TraverseEditBaseComponent.prototype.isValidPoint = function (ptTest) {
// TODO: improve this test...
if (ptTest.X === 0 && ptTest.Y === 0 && ptTest.Y === 0) {
return false;
}
return true;
};
TraverseEditBaseComponent.prototype.addMeasurementToTraverse = function (measAdd) {
var _this = this;
if (!this.isValidPoint(measAdd.PointTo)) {
this.surveyCalc.updateMeasurement(measAdd);
this.pointProvider.SurveyPoint = measAdd.PointTo;
var config = new material_1.MdDialogConfig();
this._dialogService.open(edit_survey_point_1.EditSurveyPointComponent, config)
.afterClosed()
.subscribe(function (result) {
if (result) {
var firstReturn = _this.pointService.saveSurveyPointForSurvey(result).first();
firstReturn.subscribe(function (point) {
measAdd.PointTo = point;
_this.Traverse.addSurveyMeasurement(measAdd);
});
}
else {
console.log("Cancel");
}
});
}
else {
this.Traverse.addSurveyMeasurement(measAdd);
}
};
return TraverseEditBaseComponent;
}());
exports.TraverseEditBaseComponent = TraverseEditBaseComponent;
//# sourceMappingURL=add-edit-traverse.js.map
|
// Credits: borrowed code from fcomb/redux-logger
/* eslint-disable */
import { deepCopy } from '../util'
export default function createLogger ({
collapsed = true,
filter = (mutation, stateBefore, stateAfter) => true,
transformer = state => state,
mutationTransformer = mut => mut
} = {}) {
return store => {
let prevState = deepCopy(store.state)
store.subscribe((mutation, state) => {
if (typeof console === 'undefined') {
return
}
const nextState = deepCopy(state)
if (filter(mutation, prevState, nextState)) {
const time = new Date()
const formattedTime = ` @ ${pad(time.getHours(), 2)}:${pad(time.getMinutes(), 2)}:${pad(time.getSeconds(), 2)}.${pad(time.getMilliseconds(), 3)}`
const formattedMutation = mutationTransformer(mutation)
const message = `mutation ${mutation.type}${formattedTime}`
const startMessage = collapsed
? console.groupCollapsed
: console.group
// render
try {
startMessage.call(console, message)
} catch (e) {
console.log(message)
}
console.log('%c prev state', 'color: #9E9E9E; font-weight: bold', transformer(prevState))
console.log('%c mutation', 'color: #03A9F4; font-weight: bold', formattedMutation)
console.log('%c next state', 'color: #4CAF50; font-weight: bold', transformer(nextState))
try {
console.groupEnd()
} catch (e) {
console.log('—— log end ——')
}
}
prevState = nextState
})
}
}
function repeat (str, times) {
return (new Array(times + 1)).join(str)
}
function pad (num, maxLength) {
return repeat('0', maxLength - num.toString().length) + num
}
|
var keystone = require('../../../../index.js');
var demand = require('must');
var request = require('supertest');
var demand = require('must');
var getExpressApp = require('../../../helpers/getExpressApp');
var app = getExpressApp();
var frameGuard = require('../../../../lib/security/frameGuard');
describe('Keystone "frame guard" setting', function () {
before(function() {
app.use(frameGuard(keystone));
app.get('/', function(req, res) {
res.send('OK');
});
});
describe('default setting', function() {
it('should be "sameorigin"', function() {
demand(keystone.get('frame guard')).to.be('sameorigin');
});
});
describe('keystone.set("frame guard")', function() {
it('should allow setting to "sameorigin"', function() {
keystone.set('frame guard', 'sameorigin');
demand(keystone.get('frame guard')).to.be('sameorigin');
});
it('should allow setting to "deny"', function() {
keystone.set('frame guard', 'deny');
demand(keystone.get('frame guard')).to.be('deny');
});
it('should allow setting to TRUE, converts to "deny"', function() {
keystone.set('frame guard', true);
demand(keystone.get('frame guard')).to.be('deny');
});
it('should allow setting to FALSE', function() {
keystone.set('frame guard', false);
demand(keystone.get('frame guard')).to.be(false);
});
it('should translate invalid options to FALSE', function() {
keystone.set('frame guard', 'xxx');
demand(keystone.get('frame guard')).to.be(false);
keystone.set('frame guard', 999);
demand(keystone.get('frame guard')).to.be(false);
keystone.set('frame guard', []);
demand(keystone.get('frame guard')).to.be(false);
keystone.set('frame guard', {});
demand(keystone.get('frame guard')).to.be(false);
});
});
describe('X-Frame-Options header', function() {
it('should be set to "deny" when "frame guard" is "deny"', function(done) {
keystone.set('frame guard', 'deny');
request(app)
.get('/')
.expect('x-frame-options', 'deny')
.expect(200, done);
});
it('should be set to "sameorigin" when "frame guard" is "sameorigin"', function(done) {
keystone.set('frame guard', 'sameorigin');
request(app)
.get('/')
.expect('x-frame-options', 'sameorigin')
.expect(200, done);
});
it('should be set to "deny" when "frame guard" is TRUE', function(done) {
keystone.set('frame guard', true);
request(app)
.get('/')
.expect('x-frame-options', 'deny')
.expect(200, done);
});
it('should not be set when "frame guard" is FALSE', function(done) {
keystone.set('frame guard', false);
request(app)
.get('/')
.expect(function(res) {
if (res.headers['x-frame-options']) {
return 'X-Frame-Options key exists';
}
})
.expect(200, done);
});
});
});
|
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('carousel-container', 'Integration | Component | carousel container', {
integration: true
});
test('it renders', function(assert) {
assert.expect(2);
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
this.render(hbs`{{carousel-container}}`);
assert.equal(this.$().text(), '');
// Template block usage:
this.render(hbs`
{{#carousel-container}}
template block text
{{/carousel-container}}
`);
assert.equal(this.$().text().trim(), 'template block text');
});
|
const Errors = require('../errors');
const DefaultValidationError = require('../errors/DefaultValidationError');
exports.for = function strictModeFor(schema, StructureClass) {
const StructureValidationError =
schema.options.strictValidationErrorClass || DefaultValidationError;
return {
buildStrict(...constructorArgs) {
const instance = new StructureClass(...constructorArgs);
const { valid, errors } = instance.validate();
if (!valid) {
throw Errors.invalidAttributes(errors, StructureValidationError);
}
return instance;
},
};
};
|
'use strict';
var gulp = require('gulp');
var connect = require('gulp-connect');
var config = require('../config').watch;
gulp.task('build', ['browserify', 'styles', 'html'], function () {
gulp.src(config.src).pipe(connect.reload());
});
//# sourceMappingURL=build-compiled.js.map
|
import allAssertions from './assertions';
import ContractError from './contract-error';
import isArray from 'lodash/lang/isArray';
import isError from 'lodash/lang/isError';
export class Assertron {
constructor({assertions = allAssertions} = {}) {
this.assertions = assertions;
}
toss(errors) {
let error = isArray(errors) ? errors[0] : errors;
if (error !== undefined && !isError(error)) {
error = new ContractError(error);
}
if (error) {
throw error;
}
}
validate(victim, contract) {
const baseAss = new this.assertions.base({assertions: this.assertions});
const errors = baseAss._validate(victim, contract);
this.toss(errors);
return true;
}
}
export const assertron = new Assertron();
const validate = assertron.validate.bind(assertron);
export default validate;
|
if (!/[a-z0-9]*/.test(id)) {
throw new Error("Invalid id: " + id);
}
|
function umdrehen() {
linksDrehen();
linksDrehen();
}
for (var i = 0; i < 4; i++) {
for (var j = 0; j < 12; j++) {
while (nichtIstWand()) {
hinlegen();
schritt();
}
linksDrehen();
}
linksDrehen();
for (var k = 0; k < 2; k++) {
schritt();
}
rechtsDrehen();
for (var l = 0; l < 3; l++) {
hinlegen();
}
schritt();
while (nichtIstZiegel()) {
for (var m = 0; m < 3; m++) {
hinlegen();
}
schritt();
umdrehen();
for (var n = 0; n < 3; n++) {
aufheben();
}
umdrehen();
}
schritt();
umdrehen();
for (var o = 0; o < 3; o++) {
aufheben();
}
umdrehen();
rechtsDrehen();
for (var p = 0; p < 2; p++) {
schritt();
}
rechtsDrehen();
for (var q = 0; q < 12; q++) {
while (nichtIstWand()) {
aufheben();
schritt();
}
rechtsDrehen();
}
while (nichtIstWand()) {
schritt();
}
umdrehen();
}
|
module.exports = {
context: {
breadcrumbs: {
categories: [
{
name: 'Home',
href: '#',
linkClass: 'breadcrumbs__link'
},
{
name: 'CMS page',
href: '#',
linkClass: 'breadcrumbs__link'
}
]
},
mainHeading: {
text: 'CMS Page View',
class: 'margin-vc-xl text-center'
}
}
}
|
(function () {
/**
* History Modal Controller
*/
angular.module('PanteonApp.home')
.controller('HistoryModalCtrl',
['$scope', 'logger', '$modalInstance', 'viewModel', HistoryModalCtrl]
);
function HistoryModalCtrl($scope, logger, $modalInstance, viewModel) {
/* jshint validthis: true */
var vm = this;
vm.model = viewModel;
vm.model.itemsByPage = 15;
vm.model.displayedPages = 7;
vm.close = function () {
$modalInstance.close();
};
}
})();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.