code
stringlengths 2
1.05M
|
|---|
// load the configuration settings
var config = require('./config');
var self = {};
// the log singleton
var logObject = function() {
if ( logObject.prototype._singletonInstance ) {
return logObject.prototype._singletonInstance;
}
logObject.prototype._singletonInstance = this;
self = this;
};
// define each action as a function available within the configuration
logObject.prototype = {
msg : function(msg) {
if (config.get('config:verbose:console'))
console.log(msg);
},
err : function(msg) {
if (config.get('config:verbose:errors'))
console.error(msg);
}
};
module.exports = new logObject();
|
import * as Constants from '../constants';
export default function(parent, startVertex, endVertex) {
const startCoord = startVertex.geometry.coordinates;
const endCoord = endVertex.geometry.coordinates;
// If a coordinate exceeds the projection, we can't calculate a midpoint,
// so run away
if (startCoord[1] > Constants.LAT_RENDERED_MAX ||
startCoord[1] < Constants.LAT_RENDERED_MIN ||
endCoord[1] > Constants.LAT_RENDERED_MAX ||
endCoord[1] < Constants.LAT_RENDERED_MIN) {
return null;
}
const mid = {
lng: (startCoord[0] + endCoord[0]) / 2,
lat: (startCoord[1] + endCoord[1]) / 2
};
return {
type: Constants.geojsonTypes.FEATURE,
properties: {
meta: Constants.meta.MIDPOINT,
parent,
lng: mid.lng,
lat: mid.lat,
coord_path: endVertex.properties.coord_path
},
geometry: {
type: Constants.geojsonTypes.POINT,
coordinates: [mid.lng, mid.lat]
}
};
}
|
// not actually mocking wotblitz; providing a single instance, mimicking the bot code
const wotblitz = require('wotblitz')();
exports.commands = {
client: {
user: {
id: '0101',
username: 'testbot'
}
},
wotblitz: wotblitz
};
exports.createMessage = function(content, author, mentions) {
if (mentions && !('size' in mentions)) mentions.size = mentions.length || Object.keys(mentions).length;
return {
'author': {
send: text => Promise.resolve(text),
username: author
},
channel: {
send: text => Promise.resolve(text)
},
'content': content,
'mentions': {
users: mentions
},
reply: text => Promise.resolve(`@${author}, ${text}`)
};
};
|
'use strict';
module.exports = geojsonvt;
var convert = require('./convert'), // GeoJSON conversion and preprocessing
transform = require('./transform'), // coordinate transformation
clip = require('./clip'), // stripe clipping algorithm
wrap = require('./wrap'), // date line processing
createTile = require('./tile'); // final simplified tile generation
function geojsonvt(data, options) {
return new GeoJSONVT(data, options);
}
function GeoJSONVT(data, options) {
options = this.options = extend(Object.create(this.options), options);
var debug = options.debug;
if (debug) console.time('preprocess data');
var z2 = 1 << options.maxZoom, // 2^z
features = convert(data, options.tolerance / (z2 * options.extent));
this.tiles = {};
this.tileCoords = [];
if (debug) {
console.timeEnd('preprocess data');
console.log('index: maxZoom: %d, maxPoints: %d', options.indexMaxZoom, options.indexMaxPoints);
console.time('generate tiles');
this.stats = {};
this.total = 0;
}
features = wrap(features, options.buffer / options.extent, intersectX);
// start slicing from the top tile down
if (features.length) this.splitTile(features, 0, 0, 0);
if (debug) {
if (features.length) console.log('features: %d, points: %d', this.tiles[0].numFeatures, this.tiles[0].numPoints);
console.timeEnd('generate tiles');
console.log('tiles generated:', this.total, JSON.stringify(this.stats));
}
}
GeoJSONVT.prototype.options = {
maxZoom: 14, // max zoom to preserve detail on
indexMaxZoom: 5, // max zoom in the tile index
indexMaxPoints: 100000, // max number of points per tile in the tile index
solidChildren: false, // whether to tile solid square tiles further
tolerance: 3, // simplification tolerance (higher means simpler)
extent: 4096, // tile extent
buffer: 64, // tile buffer on each side
debug: 0 // logging level (0, 1 or 2)
};
GeoJSONVT.prototype.splitTile = function (features, z, x, y, cz, cx, cy) {
var stack = [features, z, x, y],
options = this.options,
debug = options.debug;
// avoid recursion by using a processing queue
while (stack.length) {
y = stack.pop();
x = stack.pop();
z = stack.pop();
features = stack.pop();
var z2 = 1 << z,
id = toID(z, x, y),
tile = this.tiles[id],
tileTolerance = z === options.maxZoom ? 0 : options.tolerance / (z2 * options.extent);
if (!tile) {
if (debug > 1) console.time('creation');
tile = this.tiles[id] = createTile(features, z2, x, y, tileTolerance, z === options.maxZoom);
this.tileCoords.push({z: z, x: x, y: y});
if (debug) {
if (debug > 1) {
console.log('tile z%d-%d-%d (features: %d, points: %d, simplified: %d)',
z, x, y, tile.numFeatures, tile.numPoints, tile.numSimplified);
console.timeEnd('creation');
}
var key = 'z' + z;
this.stats[key] = (this.stats[key] || 0) + 1;
this.total++;
}
}
// save reference to original geometry in tile so that we can drill down later if we stop now
tile.source = features;
// stop tiling if the tile is solid clipped square
if (!options.solidChildren && isClippedSquare(tile, options.extent, options.buffer)) continue;
// if it's the first-pass tiling
if (!cz) {
// stop tiling if we reached max zoom, or if the tile is too simple
if (z === options.indexMaxZoom || tile.numPoints <= options.indexMaxPoints) continue;
// if a drilldown to a specific tile
} else {
// stop tiling if we reached base zoom or our target tile zoom
if (z === options.maxZoom || z === cz) continue;
// stop tiling if it's not an ancestor of the target tile
var m = 1 << (cz - z);
if (x !== Math.floor(cx / m) || y !== Math.floor(cy / m)) continue;
}
// if we slice further down, no need to keep source geometry
tile.source = null;
if (debug > 1) console.time('clipping');
// values we'll use for clipping
var k1 = 0.5 * options.buffer / options.extent,
k2 = 0.5 - k1,
k3 = 0.5 + k1,
k4 = 1 + k1,
tl, bl, tr, br, left, right;
tl = bl = tr = br = null;
left = clip(features, z2, x - k1, x + k3, 0, intersectX, tile.min[0], tile.max[0]);
right = clip(features, z2, x + k2, x + k4, 0, intersectX, tile.min[0], tile.max[0]);
if (left) {
tl = clip(left, z2, y - k1, y + k3, 1, intersectY, tile.min[1], tile.max[1]);
bl = clip(left, z2, y + k2, y + k4, 1, intersectY, tile.min[1], tile.max[1]);
}
if (right) {
tr = clip(right, z2, y - k1, y + k3, 1, intersectY, tile.min[1], tile.max[1]);
br = clip(right, z2, y + k2, y + k4, 1, intersectY, tile.min[1], tile.max[1]);
}
if (debug > 1) console.timeEnd('clipping');
if (tl) stack.push(tl, z + 1, x * 2, y * 2);
if (bl) stack.push(bl, z + 1, x * 2, y * 2 + 1);
if (tr) stack.push(tr, z + 1, x * 2 + 1, y * 2);
if (br) stack.push(br, z + 1, x * 2 + 1, y * 2 + 1);
}
};
GeoJSONVT.prototype.getTile = function (z, x, y) {
var options = this.options,
extent = options.extent,
debug = options.debug;
var z2 = 1 << z;
x = ((x % z2) + z2) % z2; // wrap tile x coordinate
var id = toID(z, x, y);
if (this.tiles[id]) return transform.tile(this.tiles[id], extent);
if (debug > 1) console.log('drilling down to z%d-%d-%d', z, x, y);
var z0 = z,
x0 = x,
y0 = y,
parent;
while (!parent && z0 > 0) {
z0--;
x0 = Math.floor(x0 / 2);
y0 = Math.floor(y0 / 2);
parent = this.tiles[toID(z0, x0, y0)];
}
if (!parent) return null;
if (debug > 1) console.log('found parent tile z%d-%d-%d', z0, x0, y0);
// if we found a parent tile containing the original geometry, we can drill down from it
if (parent.source) {
if (isClippedSquare(parent, extent, options.buffer)) return transform.tile(parent, extent);
if (debug > 1) console.time('drilling down');
this.splitTile(parent.source, z0, x0, y0, z, x, y);
if (debug > 1) console.timeEnd('drilling down');
}
if (!this.tiles[id]) return null;
return transform.tile(this.tiles[id], extent);
};
function toID(z, x, y) {
return (((1 << z) * y + x) * 32) + z;
}
function intersectX(a, b, x) {
return [x, (x - a[0]) * (b[1] - a[1]) / (b[0] - a[0]) + a[1], 1];
}
function intersectY(a, b, y) {
return [(y - a[1]) * (b[0] - a[0]) / (b[1] - a[1]) + a[0], y, 1];
}
function extend(dest, src) {
for (var i in src) dest[i] = src[i];
return dest;
}
// checks whether a tile is a whole-area fill after clipping; if it is, there's no sense slicing it further
function isClippedSquare(tile, extent, buffer) {
var features = tile.source;
if (features.length !== 1) return false;
var feature = features[0];
if (feature.type !== 3 || feature.geometry.length > 1) return false;
var len = feature.geometry[0].length;
if (len !== 5) return false;
for (var i = 0; i < len; i++) {
var p = transform.point(feature.geometry[0][i], extent, tile.z2, tile.x, tile.y);
if ((p[0] !== -buffer && p[0] !== extent + buffer) ||
(p[1] !== -buffer && p[1] !== extent + buffer)) return false;
}
return true;
}
|
'use strict';
var Trunc = require('lodash.trunc');
function capture(fn) {
var oldLog = console.log;
var oldWarn = console.warn;
var oldError = console.error;
console.log = function() {
fn('log', arguments);
oldLog.apply(console, arguments);
};
console.warn = function() {
fn('warn', arguments);
oldWarn.apply(console, arguments);
};
console.error = function() {
fn('error', arguments);
oldError.apply(console, arguments);
};
}
function printDebug(inst, thing) {
printMessage('DEBUG', inst, thing);
}
function printWarning(inst, thing) {
printMessage('WARN', inst, thing);
}
function printError(inst, thing, state) {
printMessage('ERROR', inst, thing);
printMessage('ERROR', inst, 'Error occurred while processing list ' + inst.counter + '');
if (state) printMessage('ERROR', inst, state);
}
function printMessage(type, inst, thing) {
var meth = 'info';
if (type === 'ERROR') meth = 'error';
if (type === 'WARN') meth = 'warn';
var info =
'Runiq [' + type + ']: ' +
'(' + inst.counter + ') ' +
Trunc(JSON.stringify(thing), 60)
console[meth](info);
}
module.exports = {
capture: capture,
printDebug: printDebug,
printWarning: printWarning,
printError: printError,
printMessage: printMessage
};
|
function sanitize(string) {
return string.replace(/[^\x00-\xFFF]|[\r\n]/g, '');
}
module.exports = sanitize;
|
var qunit = require("qunit");
homebridge = require("../../node_modules/homebridge/lib/api.js");
qunit.options.coverage = { dir: "/tmp/" };
qunit.run({
code : "index.js",
tests : [
'switchBinary',
'issue-48.js',
'issue-69.js',
'issue-72.js',
'issue-70.js',
'update-without-change.js'
].map(function (v) { return './tests/js/' + v; })
});
|
var HashTree = require('../../lib/hash-tree'),
path = require('path');
describe('Hash Tree', function() {
it('computes hashes', function( done ) {
HashTree(path.resolve(__dirname, '../')).computeHashes(function( err, nodes ) {
if (err) {
return done(err);
}
assert.property(nodes, 'unit');
assert.property(nodes.unit, 'hash-tree.js');
assert.match(nodes.unit['hash-tree.js'], /[a-f0-9]{24}/i);
done(err);
});
});
it('includes paths', function( done ) {
HashTree(path.resolve(__dirname, '../'), {
include: [
'**/*.opts'
]
}).computeHashes(function( err, nodes ) {
if (err) {
return done(err);
}
assert.deepEqual(nodes, {
'mocha.opts': '807f8a5b99ece3cb0352d14953fe260a',
unit: {}
});
done(err);
});
});
it('excludes paths', function( done ) {
HashTree(path.resolve(__dirname, '../'), {
exclude: [
'**/*.opts'
]
}).computeHashes(function( err, nodes ) {
if (err) {
return done(err);
}
assert.notProperty(nodes, 'mocha.opts');
done(err);
});
});
describe('File Diffs', function() {
beforeEach(function( done ) {
var hashTree = this.unitTree = new HashTree(path.resolve(__dirname, '../'));
hashTree.computeHashes(done);
});
beforeEach(function( done ) {
var hashTree = this.libTree = new HashTree(path.resolve(__dirname, '../../lib'));
hashTree.computeHashes(done);
});
it("lists paths that don't match", function() {
var diffList = this.unitTree.computeDiff(this.libTree.nodes);
assert.include(diffList, 'unit/hash-tree.js');
});
it("doesn't false positive", function() {
var diffList = this.unitTree.computeDiff(this.unitTree.nodes);
assert.lengthOf(diffList, 0);
});
});
});
|
/// <reference path="typings/tsd.d.ts"/>
var through = require('through');
var DependencyResolver = require('dependency-resolver');
var path = require('path');
function getFileReferences(contents) {
var regex = 'reference path="(.+)"';
var matches = contents.match(new RegExp(regex, 'g'));
if (!matches) {
return [];
}
return matches.map(function (m) {
return m.match(new RegExp(regex))[1];
});
}
function tsOrder() {
var res = new DependencyResolver();
var files = {};
function onFile(file) {
files[file.path] = file;
res.add(file.path);
getFileReferences(file.contents.toString()).forEach(function (p) {
var depPath = path.resolve(path.dirname(file.path), p);
res.setDependency(file.path, depPath);
});
}
function onEnd() {
var _this = this;
res.sort().forEach(function (serv) {
_this.emit('data', files[serv]);
});
return this.emit('end');
}
return through(onFile, onEnd);
}
module.exports = tsOrder;
|
const os = require("os")
module.exports = {
args: [
{name: "name", message: "The source file's name"},
],
files: ({name}) => [
{
name: `${name}.c`,
content: ``
},
{
name: `${name}.h`,
content: `
#ifndef ${name.constCase()}_H
#define ${name.constCase()}_H
#endif
`
}
]
}
|
'use strict';
module.exports = function(config) {
config.set({
files: [
'https://code.jquery.com/jquery-3.1.1.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-route.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.14/angular-filter.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-mocks.js',
'./google.js',
'./bin/app.js',
'./test.js',
{pattern: './bin/templates/*.html', included: false, served: true}
],
frameworks: ['mocha', 'chai'],
port: 9876,
browsers: ['Chrome'],
proxies: {
'/templates/': 'http://localhost:9876/base/bin/templates/'
}
});
};
|
import parent from '../render/dom/parent'
import { property } from '../render/static'
const injectable = {}
export default injectable
if (typeof window === 'undefined') {
Object.defineProperty(global.Element.prototype, 'value', {
configurable: true,
get () { return this.getAttribute('value') },
set (val) { this.setAttribute('value', val) }
})
}
/*
element.setAttributeNS(
namespace,
name,
value)
element.removeAttributeNS(
namespace,
attrName);
*/
if (typeof window === 'undefined') {
global.Element.prototype.setAttributeNS = function (ns, key, value) {
this.setAttribute(key, value)
}
global.Element.prototype.getAttributeNS = function (ns, key) {
this.getAttribute(key)
}
global.Element.prototype.removeAttributeNS = function (ns, key) {
this.removeAttribute(key)
}
}
injectable.props = {
attr: {
type: 'property',
render: {
static: property,
state (t, state, type, subs, tree, id, pid) {
const pnode = parent(tree, pid)
if (pnode && !pnode._propsStaticParsed) {
property(t, pnode)
pnode._propsStaticParsed = true
}
}
},
props: {
type: null, // default to wrong one --- it defaults to element....
default: {
props: { name: true },
render: {
static (t, pnode) {
const val = t.compute()
const key = t.name || t.key
if (~key.indexOf(':')) {
const namespace = 'http://www.w3.org/1999/xlink'
if (val === t || val === void 0) {
pnode.removeAttributeNS(namespace, key)
} else {
pnode.setAttributeNS(namespace, key, val)
}
} else {
if (val === t || val === void 0) {
pnode.removeAttribute(key)
} else {
pnode.setAttribute(key, val)
}
}
},
state (t, state, type, subs, tree, id, pid) {
const pnode = parent(tree, pid)
const key = t.name || t.key
if (~key.indexOf(':')) {
const namespace = 'http://www.w3.org/1999/xlink'
if (type === 'remove') {
if (pnode) {
pnode.removeAttributeNS(namespace, key)
}
} else {
let val = t.compute(state, state)
const type = typeof val
if (type === 'boolean') { val = val + '' }
if (val && (type === 'object' && val.inherits) || val === void 0) {
if (pnode.getAttributeNS(namespace, key)) {
pnode.removeAttribute(namespace, key) // missing
}
} else {
if (!val && type === 'object') {
if (pnode) pnode.removeAttribute(key)
} else if (pnode.getAttributeNS(namespace, key) != val) { // eslint-disable-line
pnode.setAttributeNS(namespace, key, val)
}
}
}
} else {
if (type === 'remove') {
if (pnode) {
pnode.removeAttribute(key)
}
} else {
let val = t.compute(state, state)
const type = typeof val
if (type === 'boolean') { val = val + '' }
if ((type === 'object' && (!val || val.inherits)) || val === void 0) {
if (pnode.getAttribute(key)) {
pnode.removeAttribute(key) // missing
}
} else {
if (pnode.getAttribute(key) != val) { // eslint-disable-line
pnode.setAttribute(key, val)
}
}
}
}
}
}
},
value: {
render: {
static (t, pnode) {
const val = t.compute() // missing
pnode.value = val // missing (needs a way on server this does not work)
},
state (t, state, type, subs, tree, id, pid) {
const pnode = parent(tree, pid)
if (type === 'remove') {
if (pnode) { pnode.value = '' } // missing
} else {
const val = t.compute(state, state)
if (val != pnode.value) { // eslint-disable-line
pnode.value = val === t ? '' : val
}
}
}
}
}
}
}
}
|
import { ipcRenderer } from 'electron'
import {
ADD_REQUEST,
ADD_RESPONSE,
UPDATE_FILTER,
GET_HTTP_MESSAGE_DETAILS_SUCCESS,
TOGGLE_FILTER_INPUT
} from '../../constants/actionTypes'
import {
REQUEST_HTTP_MESSAGE_DETAILS,
HTTP_MESSAGE_DETAILS,
HTTP_MESSAGE_REQUEST,
REQUEST_HTTP_MESSAGE_REQUEST
} from '../../constants/ipcMessages'
import { sendToProxyWindow } from '../../windows'
import http from 'http'
import { load as loadConfig } from '../../lib/config'
const config = loadConfig()
export function addRequest (request) {
return {type: ADD_REQUEST, payload: request}
}
export function addResponse (response) {
return {type: ADD_RESPONSE, payload: response}
}
export function getHttpMessageDetailsSuccess (data) {
return {type: GET_HTTP_MESSAGE_DETAILS_SUCCESS, payload: data}
}
export function getHttpMessageDetails (requestId) {
return (dispatch) => {
sendToProxyWindow(REQUEST_HTTP_MESSAGE_DETAILS, requestId)
ipcRenderer.on(HTTP_MESSAGE_DETAILS, (e, details) => {
dispatch(getHttpMessageDetailsSuccess(details))
})
}
}
export function replayRequest (requestId) {
return (dispatch) => {
sendToProxyWindow(REQUEST_HTTP_MESSAGE_REQUEST, requestId)
ipcRenderer.once(HTTP_MESSAGE_REQUEST, (e, request) => {
const options = {
port: config.port,
hostname: 'localhost',
method: request.method,
path: `${request.protocol}//${request.host}${request.path}`,
headers: request.headers
}
const req = http.request(options)
req.write(Buffer.from(request.body.data))
req.end()
})
}
}
export function updateFilter (filter) {
return {type: UPDATE_FILTER, payload: filter}
}
export function toggleFilterInput () {
return {type: TOGGLE_FILTER_INPUT}
}
|
var glob = require('glob')
module.exports = function globTests() {
return glob.sync('./test/spec/**/*.spec.{js,jsx}')
}
|
'use strict'
var _url = document.createElement('a')
module.exports = function (url) {
_url.href = url
return {
hash: _url.hash,
href: _url.href,
urlpath: _url.pathname,
search: _url.search,
host: _url.hostname,
port: _url.port
}
}
|
var eos = require('end-of-stream')
module.exports = each
function each (stream, fn, cb) {
var waiting = false
var error = null
var ended = false
stream.on('readable', onreadable)
read(null)
if (cb) eos(stream, {readable: true, writable: false}, done)
return stream
function done (err) {
error = err
ended = true
if (waiting) return cb(error)
}
function onreadable () {
if (waiting) read(null)
}
function read (err) {
if (err) {
waiting = true
stream.destroy(err)
return
}
var data = stream.read()
waiting = !data
if (waiting && ended) return cb(error)
if (data) fn(data, read)
}
}
|
const readline = require('readline');
const Spinner = function (text = '%s') {
if ('string' == typeof text) {
text = { text };
}
this._text = text.text || '';
this._list = text.spinners || function (
spin = (t) => ['|', '/', '-', '\\'][t % 4], list = []
) {
for (let n = 0; n < 19; n++) list.push(
`[[37m${"█".repeat(n)}[30m${".".repeat(18 - n)}[37m] ${spin(n)}`
);
for (let n = 19; n < 36; n++) list.push(
`[[30m${".".repeat(n - 18)}[37m${"█".repeat(36 - n)}] ${spin(n)}`
);
return list;
}();
this._second = text.delay || 60;
this._output = text.stream || process.stdout;
this.onTick = text.onTick || function (t) {
this.clear(this._output);
this._output.write(t);
};
};
Spinner.prototype.start = function (index = 0) {
this._id = setInterval(() => {
this.onTick(this._text.indexOf('%s') > -1
? this._text.replace('%s', this._list[index])
: this._list[index] + ' ' + this._text);
index = ++index % this._list.length;
}, this._second);
};
Spinner.prototype.stop = function (clear) {
clearInterval(this._id);
this._id = undefined;
clear && this.clear();
};
Spinner.prototype.clear = function () {
readline.clearLine(this._output, 0);
readline.cursorTo(this._output, 0);
};
module.exports = Spinner;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Tiles = void 0;
var tile_size_1 = require("./tile-size");
var tile_sizes_1 = require("./tile-sizes");
var Tiles = /** @class */ (function () {
function Tiles() {
// #region Properties
this.showTiles = true;
this.tiles = new Array();
this.isTilesLoaded = false;
this.hideTileIfOnlyOne = true; // not yet evaluated in HTML, but this is the standard behavior
this.tileSizes = tile_size_1.TileSize.getTileSizes();
this.nextLeft = 0;
this.nextTop = 0;
this.columnHeightMax = 0;
// #endregion
}
// #endregion
// #region Methods
Tiles.prototype.addTile = function (tile) {
this.isTilesLoaded = true;
var tileSize = this.tileSizes[tile.tileSize];
tile.size = tile_sizes_1.TileSizes[tile.tileSize]; // Get CSS Name
tile.top = this.nextTop + 'px';
tile.left = this.nextLeft + 'px';
this.nextLeft += tileSize.width;
if (tileSize.height > this.columnHeightMax) {
this.columnHeightMax = tileSize.height;
}
if (this.nextLeft > 540) {
this.nextLeft = 0;
this.nextTop += this.columnHeightMax;
this.columnHeightMax = 0;
}
this.tiles.push(tile);
return tile;
};
return Tiles;
}());
exports.Tiles = Tiles;
//# sourceMappingURL=tiles.js.map
|
function getTypes (types) {
return function (raw) {
return types[raw.type]
}
}
module.exports = getTypes
|
'use strict'
let gulp = require("gulp");
let sourcemaps = require("gulp-sourcemaps");
let babel = require("gulp-babel");
let watch = require('gulp-watch');
let changed = require('gulp-changed');
let nodemon = require('gulp-nodemon');
let plumber = require('gulp-plumber');
let path = require('path');
let demon;
gulp.task("default", ['es6']);
gulp.task("sourcemaps", function() {
return gulp.src("src/**/*.js")
.pipe(sourcemaps.init())
.pipe(babel())
.pipe(sourcemaps.write("./maps"))
.pipe(gulp.dest("build"));
});
gulp.task("es6-js", function() {
return gulp.src(["src/**/*.js", "tests/**/*.js"])
.pipe(changed("build"))
.pipe(plumber({
errorHandler: function(e) {
console.log('error', e);
}
}))
.pipe(babel())
.pipe(gulp.dest("build"))
.on('end', function() {
console.log('end build');
});
});
gulp.task("json", function() {
return gulp.src(["src/**/*.json", "tests/**/*.json"])
.pipe(gulp.dest("build"));
});
gulp.task('es6', ['es6-js', 'json']);
gulp.task('upd', ['es6'], function() {
return gulp.src(["build/**/*.js"])
.pipe(gulp.dest("../iris-v2/node_modules/iris-service-sound-conjunct/build"));
});
gulp.task('test-upd', ['start-test'], function() {
gulp.watch(["src/**/*.js", "tests/**/*.js"], ['upd']);
});
gulp.task('test', ['start-test'], function() {
gulp.watch(["src/**/*.js", "tests/**/*.js"], ['es6']);
});
gulp.task('serve', ['start-serve'], function() {
gulp.watch(["src/**/*.js", "tests/**/*.js"], ['es6']);
});
gulp.task('start-test', function() {
demon = nodemon({
script: 'build/run.js',
watch: ['build/'],
execMap: {
"js": "node --harmony "
},
env: {
'NODE_ENV': 'development'
}
});
});
gulp.task('start-serve', function() {
demon = nodemon({
script: 'build/index.js',
watch: ['build/'],
execMap: {
"js": "node --harmony "
},
env: {
'NODE_ENV': 'development'
}
});
});
|
'use strict';
/**
* Returns the result of applying concat to the result of applying a function to values.
*
* @param {array} vals - an array of values
* @param {function} fn
* @param {object} ctx
*
* @return {array}
*/
module.exports = function mapconcat(vals, fn, ctx) {
return Array.prototype.concat.apply([], vals.map(fn, ctx));
};
|
export const ADD_REQUEST = 'ADD_REQUEST'
export const ADD_RESPONSE = 'ADD_RESPONSE'
export const GET_HTTP_MESSAGE_DETAILS_SUCCESS = 'GET_HTTP_MESSAGE_DETAILS_SUCCESS'
export const UPDATE_FILTER = 'UPDATE_FILTER'
export const TOGGLE_FILTER_INPUT = 'TOGGLE_FILTER_INPUT'
|
// We need to import the CSS so that webpack will load it.
// The MiniCssExtractPlugin is used to separate it out into
// its own CSS file.
import "../css/app.css"
// webpack automatically bundles all modules in your
// entry points. Those entry points can be configured
// in "webpack.config.js".
//
// Import deps with the dep name or local files with a relative path, for example:
//
// import {Socket} from "phoenix"
// import socket from "./socket"
//
import "phoenix_html"
import {Socket} from "phoenix"
import NProgress from "nprogress"
import {LiveSocket} from "phoenix_live_view"
import hooks from "./hooks"
window.addEventListener('phx:hook:svelte', (e) => {
Object.values(liveSocket.main.viewHooks)
.filter(x => x.el.id == e.detail.svelteID)[0]._instance.serverEvent(e.detail)
})
let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
let liveSocket = new LiveSocket("/live", Socket, {
hooks,
params: {_csrf_token: csrfToken},
/* metadata: {
click: (e, el) => {
return {
svelteID: el.closest('[phx-hook="svelte-component"]').id
}
}
} */
})
// Show progress bar on live navigation and form submits
window.addEventListener("phx:page-loading-start", info => NProgress.start())
window.addEventListener("phx:page-loading-stop", info => NProgress.done())
// connect if there are any LiveViews on the page
liveSocket.connect()
// expose liveSocket on window for web console debug logs and latency simulation:
liveSocket.enableDebug()
// >> liveSocket.enableLatencySim(1000) // enabled for duration of browser session
// >> liveSocket.disableLatencySim()
|
var gulp = require('gulp');
var mocha = require('gulp-mocha');
var eslint = require('gulp-eslint');
var istanbul = require('gulp-istanbul');
var formatter = require('eslint-friendly-formatter');
var lint = ['gulpfile.js', 'index.js', 'utils.js'];
gulp.task('coverage', function() {
return gulp.src(lint.concat(['!gulpfile.js']))
.pipe(istanbul({
includeUntested: true
}))
.pipe(istanbul.hookRequire());
});
gulp.task('test', ['coverage'], function() {
return gulp.src('test.js')
.pipe(mocha({
reporter: 'spec'
}))
.pipe(istanbul.writeReports())
.pipe(istanbul.writeReports({
reporters: [ 'text' ],
reportOpts: {dir: 'coverage', file: 'summary.txt'}
}));
});
gulp.task('lint', function() {
return gulp.src(lint.concat(['test.js']))
.pipe(eslint())
.pipe(eslint.format(formatter));
});
gulp.task('default', ['test']);
|
/**
* 分类栏条目
*/
import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
import { Link } from 'react-router';
export default class CategoryBar extends Component {
render(){
const { text , active , link ,...other } = this.props;
return (
<li {...other}>
<Link to={link} className={classnames({active})} >
{text}
</Link>
</li>
);
}
}
|
/* Project architecture can be changed if the project grows - instead of using 'type' oriented
* architecture, i.e. to have directories such as 'controllers', 'services' etc.,
* we can use 'feature' oriented structure, where each feature has its own
* directory with all the needed components, e.g. feature for 'login' form can
* have its controller, service, directive and etc in one folder called 'login'
* which can be placed under a common folder in /scripts/ called for example
* 'modules' or 'components'.
* */
var abApp = angular.module('address-book',
['LocalStorageModule', 'ngRoute', 'ngAnimate', 'addressBookServices', 'addressBookFactories', 'addressBookControllers']);
abApp.config(['localStorageServiceProvider', '$routeProvider', function (localStorageServiceProvider, $routeProvider) {
localStorageServiceProvider.setPrefix('address-book');
$routeProvider
.when('/', {
templateUrl: 'views/address-list/address-list.html',
controller: 'AddressListController',
resolve: {
addresses: ['AddressEntryFactory', function (AddressEntryFactory) {
return AddressEntryFactory.getAllEntries();
}]
}
})
.otherwise({redirectTo: '/'});
}]).constant('_', window._)
.run(['CountryListFactory', function (CountryListFactory) {
// Get the counties data
var cl = require('country-list')();
CountryListFactory.setCountryListService(cl);
}]);
|
version https://git-lfs.github.com/spec/v1
oid sha256:8e85cd0bba914ed57ac03ce72804dbe6e83dbef37296bdcacb969c811c7aeecd
size 1568
|
//getter methods
console.log("Syntax: ");
console.log("The get syntax binds an object property \n to a function that will be called when that property is looked up.");
console.log("{get prop() { ... } }");
console.log("{get [expression]() { ... } }");
// prop: The name of the property to bind to the given function.
// expression: Starting with ECMAScript 6, you can also use expressions for a computed property name to bind to the given function.
/*
Description
Sometimes it is desirable to allow access to a property that returns a dynamically computed value,
or you may want reflect the status of an internal variable without requiring the use of explicit method calls.
In JavaScript, this can be accomplished with the use of a getter.
It is not possible to simultaneously have a getter bound to a property and have that property actually hold a value,
although it is possible to use a getter and a setter in conjunction to create a type of pseudo-property.
- It can have an identifier which is either a number or a string;
-It must have exactly zero parameters
(see Incompatible ES5 change: literal getter and setter functions must now have exactly zero or one arguments for more information);
-It must not appear in an object literal with another get or
with a data entry for the same property ({ get x() { }, get x() { } } and { x: ..., get x() { } } are forbidden).
A getter can be removed using the delete operator
*/
console.log("Example");
var log = ['test'];
var obj ={
get latest(){
if (log.length == 0) return undefined;
return log[log.length -1]
}
}
console.log(obj.latest);
console.log("If you want to remove the getter, you can just delete it: delete obj.latest;");
|
const AstNode = require('./ast-node');
class ForLoopBodyWithValue extends AstNode {
type() {
return 'for_loop_body_with_value';
}
/**
* @param {ParseContext} context
* @return {AstNodeParseResult}
*/
parse(context) {
const tm = context.sourceTextManager();
tm.whitespace();
const v = context.parse('temp_var').expr;
tm.whitespaceRequired();
tm.next('in');
tm.whitespaceRequired();
const keys = context.parse('var').keys;
return {
type: this.type(),
tmp_k: null,
tmp_v: v,
keys: keys,
};
}
}
module.exports = ForLoopBodyWithValue;
|
// task browserSync
const gulp = require('gulp');
const config = require('../gulp.config');
const path = require('path');
const browserSync = require('browser-sync').create();
const browserSyncTask = () => {
browserSync.init(config.tasks.browserSync);
let watchableTasks = [
'scripts',
'html',
'styles'
];
watchableTasks.forEach((taskName) => {
let files = path.join(
config.root,
config.tasks[taskName].src,
`/**/*.{${config.tasks[taskName].extensions}}`
);
if (taskName === 'scripts') {
files = [
path.join(
config.root,
config.tasks[taskName].src,
`/**/*.{${config.tasks[taskName].extensions}}`
),
path.join(
config.root,
config.tasks.vueify.src,
`/**/*.{${config.tasks.vueify.extensions}}`
)
];
}
let watchTaskName = `watch${taskName[0]
.toUpperCase()
.concat(taskName.slice(1))}`;
gulp.task(watchTaskName, [taskName], (done) => {
browserSync.reload();
done();
}
);
gulp.watch(files, [watchTaskName]);
});
};
gulp.task('browserSync', browserSyncTask);
module.exports = browserSyncTask;
|
var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
name:'YouTube',
prepareImgLinks:function (callback) {
var res = [],
repl = 'http://i1.ytimg.com/vi/$1/0.jpg';
function decodeQueryString(queryString) {
var keyValPairs = queryString.split("&"), params = {};
for (var i = 0; i < keyValPairs.length; i++) {
var key = decodeURIComponent(keyValPairs[i].split("=")[0]);
params[key] = decodeURIComponent(keyValPairs[i].split("=")[1] || "");
}
return params;
}
function decodeStreamMap(url_encoded_fmt_stream_map) {
var streams = url_encoded_fmt_stream_map.split(","), sources = {};
for (var i = 0; i < streams.length; i++) {
var stream = decodeQueryString(streams[i]);
var type = stream.type.split(";")[0];
var quality = stream.quality.split(",")[0];
stream.original_url = stream.url;
stream.url = "" + stream.url + "&signature=" + stream.sig;
sources["" + type + " " + quality] = stream;
}
return sources;
}
function getSource(sources, type, quality) {
var lowest = null, exact = null;
for (var key in sources) {
var source = sources[key];
if (source.type.match(type)) {
if (source.quality.match(quality)) {
exact = source;
} else {
lowest = source;
}
}
}
return exact || lowest;
}
function prepareVideoPreview(link, id) {
if (link.hasClass('hoverZoomLoading') || link.hasClass('hoverZoomLink') || link.hasClass('ytp-title-link')) return;
link.addClass('hoverZoomLoading');
var match = link.attr('href').match(/[\?&]t=([\dhm]+)/);
var start = match && match.length >= 2 ? match[1] : null;
if (start && start.indexOf('m') !== -1) {
var parts = start.split('m');
if (parts.length == 2) {
var parts2 = start.split('h');
if (parts2.length == 2)
parts[0] = parseInt(parts2[0]) * 60 + parseInt(parts2[1]);
start = parseInt(parts[0]) * 60 + parseInt(parts[1] || 0);
}
}
chrome.runtime.sendMessage({action: 'ajaxGet', url: location.protocol + "//www.youtube.com/get_video_info?video_id=" + id, method: 'GET'}, function (video_info) {
link.removeClass('hoverZoomLoading');
var video = decodeQueryString(video_info);
if (video.status === "fail") {
cLog(video.reason);
return;
}
var sources = decodeStreamMap(video.url_encoded_fmt_stream_map);
var src = getSource(sources, "webm", "hd720") || getSource(sources, "mp4", "hd720");
if (src) {
link.data().hoverZoomSrc = [start ? src.url + '#t=' + start : src.url];
link.addClass('hoverZoomLink');
hoverZoom.displayPicFromElement(link);
}
});
}
$('a[href*="youtu.be/"]').one('mouseenter', function () {
var link = $(this), match = this.href.match(/^.*youtu.be\/([\w-]+).*$/);
if (!match || match.length < 2) return;
prepareVideoPreview(link, match[1]);
});
$('a[href*="youtube.com/watch"]').one('mouseenter', function () {
var link = $(this), match = this.href.match(/^.*v=([\w-]+).*$/);
if (!match || match.length < 2) return;
prepareVideoPreview(link, match[1]);
});
// $('a[href*="youtu.be/"] img').each(function () {
// var link = $(parentNodeName(this, 'a')),
// img = $(this);
// img.data().hoverZoomSrc = [link.attr('href').replace(/^.*youtu.be\/([\w-]+).*$/, repl)];
// res.push(img);
// });
// $('a[href*="youtube.com/watch"] img').each(function () {
// var link = $(parentNodeName(this, 'a')),
// img = $(this);
// img.data().hoverZoomSrc = [link.attr('href').replace(/^.*v=([\w-]+).*$/, repl)];
// res.push(img);
// });
hoverZoom.urlReplace(res,
'img[src*="ytimg.com/vi/"], img[src*="ytimg.com/vi_webp/"]',
/\/([1-9]|default|hqdefault|mqdefault)\.(jpg|webp)/,
'/0.$2'
);
$('a img[data-thumb*="ytimg.com/vi/"]').each(function () {
var img = $(this);
img.data().hoverZoomSrc = [this.getAttribute('data-thumb').replace(/\/([1-9]|default|hqdefault|mqdefault)\.jpg/, '/0.jpg')];
res.push(img);
});
callback($(res));
}
});
|
import _ from 'lodash'
export const composite = (commands) => {
if (!Array.isArray(commands)) { return commands; }
if (commands.length === 1) { return commands[0]; }
return {
'composite': _.chain(commands).reduce((o, v, idx) => { o[idx] = v; return o; }, {}).value()
};
};
export const addElement = (json) => ({ 'add-element' : json });
export const addConnector = (json) => ({ 'add-connector' : json });
export const addRelationship = (json) => ({ 'add-relationship' : json });
export const modViewObject = (viewId, voId, payload) => ({
'mod-view-object': {
viewId: viewId,
id: voId,
...payload
}
});
export const modConcept = (id, payload) => ({
'mod-concept': {
id: id,
...payload
}
});
export const deleteViewObject = (viewId, voId) => ({
'del-view-object': {
viewId: viewId,
id: voId
}
});
export const moveViewNode = (viewId, voId, pos, size) => ({
'mov-view-node': {
viewId: viewId,
id: voId,
pos: { x:pos.x, y:pos.y },
size: { width: size.width, height: size.height }
}
});
export const moveViewEdge = (viewId, voId, points) => ({
'mov-view-edge': {
viewId: viewId,
id: voId,
points: _.chain(points).map((p) => ({ x:p.x, y:p.y })).value()
}
});
export const addViewNodeConcept = (viewId, concept, pos, size) => ({
'add-view-node-concept': {
viewId: viewId,
concept: concept,
pos: { x:pos.x, y:pos.y },
size: { width: size.width, height: size.height }
}
});
export const addViewRelationship = (viewId, concept, src, dst) => ({
'add-view-relationship': {
viewId: viewId,
concept: concept,
src, dst
}
});
export const addViewNotes = (viewId, pos, size) => ({
'add-view-notes': {
viewId: viewId,
pos: { x:pos.x, y:pos.y },
size: { width: size.width, height: size.height }
}
});
export const addViewConnection = (viewId, src, dst) => ({
'add-view-connection': {
viewId: viewId,
src, dst
}
});
export const addView = (viewpoint, name, payload={}) => ({
'add-view': {
viewpoint: viewpoint,
name: name,
...payload
}
});
export const modView = (id, name, payload={}) => ({
'mod-view': {
id: id,
name: name,
...payload
}
});
|
const Program = require('../models/Program'),
Campus = require('../models/Campus'),
fixtures = require('node-mongoose-fixtures');
/**
* GET /
* Home page.
*/
exports.index = (req, res) => {
//load programs
Program.find({}, (err, programs) => {
if(err) return console.error(err);
res.render('home', {title: 'Home', programs: programs})
});
};
|
var relationsMapper = require('./map_relations');
var Promise = require('bluebird');
var DEFAULT_LIST_RELATIONS = require('./constants').LIST_RELATIONS;
var DEFAULT_ITEM_LIST = require('./constants').ITEM_TYPE_LIST;
var SAMPLE_DATA = require('./data-demo');
var CLOUD_TOPIC_PREFIX = require('./topics_constants').CLOUD_TOPIC_PREFIX;
/**
* Returns build data function singleton
* @param {Object} mediator - mediator object used for communication
* @returns {Function} - buildData function
*/
function getBuildDataFunction(mediator) {
/**
* Synchronously publishes 'wfm:cloud:{itemType}:create topic for each item type.
* @param {Object} mediator - mediator object used for communication
* @returns {Promise} Promise, resolved if all items are successfully created.
*/
return function buildData() {
var relationsMap = [];
/**
* Iterator function for mapSeries, creates all sample items for given item type
* @param itemType
* @returns {Promise}
*/
function createDataForType(itemType) {
return createItemsForType(mediator, itemType, relationsMap)
.then(function(mappingsForType) {
relationsMap[itemType] = mappingsForType;
});
}
return Promise.mapSeries(DEFAULT_ITEM_LIST, createDataForType).return();
};
}
/**
* Creates all items of a given type
* @param {Object} mediator - mediator object used for communication
* @param {String} itemType - type of the item to remove e.g. result, workorder
* @param {Array} relationsMap - An array mapping out relations between seed and newly created data-reset
* @returns {Promise} with mappings for given type.
*/
function createItemsForType(mediator, itemType, relationsMap) {
var topic = CLOUD_TOPIC_PREFIX + itemType + ':create';
function createForType(dataItem) {
var mapping = {
seedId: dataItem.id,
newId: ''
};
dataItem = relationsMapper.mapRelations(itemType, dataItem, relationsMap[DEFAULT_LIST_RELATIONS[itemType]]);
return mediator.request(topic, [dataItem, dataItem.id], {uid: dataItem.id})
.then(function(createdItem) {
mapping.newId = createdItem.id;
return mapping;
});
}
//map series resolves to an array of results returned by its iterator func. i.e. an array of mappings for a type
return Promise.mapSeries(SAMPLE_DATA[itemType](), createForType);
}
module.exports = {
getBuildDataFunction: getBuildDataFunction,
createItemsForType: createItemsForType
};
|
'use strict';
var fs = require('fs'),
request = require('request'),
wikiParser = require('./wikiparser'),
_ = require('lodash');
var fns = {
getSlugNameFor: function(str) {
var slug = str.replace(/\s+/g, '-').toLowerCase();
return slug;
},
extendWithJSONs: function(series) {
for (var ser in series) {
var fileName = './cache/' + fns.getSlugNameFor(ser) + '.json';
if (!fs.existsSync(fileName)) {
console.error('json for "', ser, '" not exists. Filename should be: ', fileName);
continue;
}
series[ser].jsonData = require('./.' + fileName);
}
},
writeJSON: function(fileName, jsonData) {
return new Promise(function (fulfill, reject) {
fs.writeFile(fileName, JSON.stringify(jsonData, null, 2), function(err) {
if (err) {
reject()
} else {
fulfill();
}
});
});
},
findSeriesByTitle: function(title, series) {
var hit = _.find(series, function(value, key, fullObj) {
return key === title;
});
if (!hit) {
console.error('Couldn\'t find this show in the db:', title);
return '';
}
return hit;
},
loadUrl: function(url) {
return new Promise(function (fulfill, reject) {
request(url, function (error, response, body) {
if (error || response.statusCode != 200) {
throw new Error(error);
}
fulfill(body);
});
});
},
updateCacheFromWiki: function(seriesData) {
return fns.loadUrl(seriesData.wikiUrl)
.then(function(body) {
return wikiParser.extractDataFromWikiPage(seriesData, body);
});
},
populateEpisodes: function(series, date, beforeDays, afterDays) {
var showsBefore = [], showsAfter = [],
beforeDate = date.getTime() - beforeDays * 1000 * 24 * 60 * 60,
afterDate = date.getTime() + afterDays * 1000 * 24 * 60 * 60,
nowDate = date.getTime();
_.each(series, function(data, key) {
if (data.jsonData) {
_.each(data.jsonData, function(season) {
_.each(season.episodes, function(episode) {
episode.dateObj = new Date(episode.date);
if (episode.dateObj.getTime() > beforeDate && episode.dateObj.getTime() < nowDate) {
showsBefore.push({ series: key, season: season.season, episode: episode});
} else if (episode.dateObj.getTime() > nowDate && episode.dateObj.getTime() < afterDate) {
showsAfter.push({ series: key, season: season.season, episode: episode});
}
});
});
}
});
return {
showsBefore: _.sortBy(showsBefore, function(n) {
return n.episode.dateObj.getTime();
}),
showsAfter: _.sortBy(showsAfter, function(n) {
return n.episode.dateObj.getTime();
})
};
},
formatDate: function(date) {
var month = date.getMonth() + 1,
day = date.getDay(),
dayText = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][day];
return date.getFullYear() + '-' +
(month < 10 ? '0' + month : month) + '-' +
(date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) +
' (' + dayText + ')';
}
}
module.exports = fns;
|
'use strict';
const _ = require('lodash');
const Parse = require('../lib/parse');
const Account = Parse.Object.extend('account');
const querystring = require('querystring');
module.exports = app => {
/**
* 用户相关
*/
class UserService extends app.Service {
constructor(ctx) {
super(ctx);
this.config = this.ctx.app.config;
}
* mobile(id) {
return 'Helle Man!';
}
* register(user) {
const isExist = yield this.checkUserName(user.userName);
const ret = {
code: 0,
msg: '',
data: [],
};
if (isExist) {
ret.code = 1;
ret.msg = '用户名已存在';
return ret;
}
const account = new Account();
account.set(user);
ret.data = account.save();
return ret;
}
* checkUserName(userName) {
const query = new Parse.Query('account');
query.equalTo('userName', userName);
const userInfo = yield userQuery.first().then(function(user) {
if (user) {
user.set('id', user.id);
return user.toJSON();
}
return null;
}, function(err) {
app.logger.error(err);
return null;
});
}
//
// * checkAuth(options) {
// const {ctx,service}=this;
// const query = querystring.stringify(options)
// const redirectUrl = `${app.config.baseUrl}/wechat/callback?${query}`;
// const userInfo = yield service.user.info(ctx.session.user_id);
// if (!userInfo||!ctx.session.user_id) {
// ctx.session.user_id = null;
//
// const wechatClient = yield ctx.helper.oauthClient(function (err, client) {
// if (err) {
// app.logger.error(err);
// }
// app.logger.info(client);
// });
// const url = wechatClient.getAuthorizeURL(redirectUrl, 'state', 'snsapi_userinfo');
//
// ctx.redirect(url);
//
// } else {
// return true;
// }
//
// }
//
// * cache(wuser) {
// if (wuser) {
// yield app.redis.hset('users', wuser.id, wuser.toJSON());
// }
// }
//
// * fansToWall(bpwall_id, user_id) {
// const Bpwall = Parse.Object.extend('bpwall');
// const bpwall = new Bpwall();
// bpwall.id = bpwall_id;
// const wechatUser = new WechatUser();
// wechatUser.id = user_id;
//
// let isExist = yield app.redis.sadd(`wallfans:${bpwall_id}`, user_id);
// console.log(isExist)
// if (isExist == 1) {
// yield wechatUser.fetch().then(function (wechatUser) {
// console.log(wechatUser);
// bpwall.relation('wechat_user').add(wechatUser);
// return bpwall.save();
// });
// }
//
//
// }
//
// /**
// * 登录之后用户相关操作
// * @param wuser
// */
// * processUser(wuser) {
// // const userId = yield app.redis.hget("openids", wuser.openid);
// const {ctx}=this;
//
// let userInfo = yield this.infoByOpenid(wuser.openid);
// ///app.logger.debug('user:check:%s:%s', bpwall_id, JSON.stringify(userInfo));
//
// // 如果不存
// if (!userInfo) {
// wuser.money = 0;
// const user = yield this.save(wuser);
// if (user) {
// userInfo = user.toJSON();
// }
// yield this.cache(user);
// }
//
// app.logger.info(userInfo)
// console.log(this.ctx.session)
// ctx.session.user_id = userInfo.objectId;
//
// return userInfo;
// }
//
// * save(user) {
// const wechatUser = new WechatUser();
// wechatUser.set(user);
// // 0正常 1拉黑
// // wechatUser.set("status",1)
// wechatUser.set('disabled_permission', 0);
// return wechatUser.save();
// }
//
//
// /**
// * 获取当前用户信息
// */
// * info(user_id) {
// let userInfo = yield app.redis.hget('users', user_id);
// app.logger.info('info:user: %s:%s', JSON.stringify(userInfo), _.isEmpty(userInfo));
//
// if (_.isEmpty(userInfo)) {
// const userQuery = new Parse.Query('wechat_user');
// userQuery.equalTo('objectId', user_id);
// userInfo = yield userQuery.first().then(function (user) {
// if (user) {
// user.set('id', user.id);
// return user.toJSON();
// }
// return null;
//
// }, function (err) {
// app.logger.error(err);
// return null;
// });
//
// if (userInfo) {
// yield app.redis.hset('users', user_id, userInfo);
// yield app.redis.hset('openids', userInfo.openid, userInfo.objectId);
//
// return userInfo;
// }
// }
// if(userInfo==null){
//
// this.ctx.session.user_id = null;
// }
//
// return userInfo;
//
// }
//
//
// /**
// * 获取当前用户信息
// */
// * infoByOpenid(openid) {
// const userId = yield app.redis.hget('openids', openid);
//
// app.logger.info('check:userid: %s openid:%s', userId, openid);
//
// if (!userId) {
// const userQuery = new Parse.Query('wechat_user');
// userQuery.equalTo('openid', openid);
// const userInfo = yield userQuery.first().then(function (user) {
// if (user) {
// user.set('id', user.id);
// return user.toJSON();
// }
// return null;
//
// }, function (err) {
// app.logger.error(err);
// return null;
// });
//
// if (userInfo) {
//
// yield app.redis.hset('users', userInfo.objectId, userInfo);
// yield app.redis.hset('openids', openid, userInfo.objectId);
//
//
// return userInfo;
// }
//
// } else {
// return yield this.info(userId);
// }
//
// return null;
//
// }
//
//
// * getUserList(options) {
// const {ctx, service} = this;
//
// const ret = {
// list: [],
// };
//
// console.log(options);
//
// const Bpwall = Parse.Object.extend('bpwall');
// const bpwall = new Bpwall();
// bpwall.id = options.bpwall_id;
// const relation = bpwall.relation('wechat_user');
// const userQuery = relation.query();
//
// if (options.type != 0) {
// userQuery.equalTo('sex', options.type);
// }
//
//
// userQuery.limit(options.pagesize);
// userQuery.skip(options.pagesize * options.page);
//
//
// yield userQuery.count().then(function (count) {
// ret.count = count + 1;
// return userQuery.find();
//
// }).then(function (users) {
//
// const temp = [];
//
//
// _.forEach(users, function (n, i) {
// const user = n.toJSON();
// user.uid = user.objectId;
// user.m_nickname = user.nickname;
// user.m_avatar = user.headimgurl;
// user.m_sex = user.sex + '';
// user.nickname = user.nickname;
// user.avatar = user.headimgurl;
// // user.sex = user.sex == 1 ? 'male' : 'female';
// user.present = false;
// temp.push(user);
// });
// ret.list = temp;
// }, function (error) {
//
// });
//
// return ret;
// }
}
return UserService;
};
|
/*
* The MIT License (MIT)
* Copyright (c) 2016 Jim Liu
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
xdescribe('uiMask', function () {
var inputHtml = "<input ui-mask=\"'(9)9'\" ng-model='x'>";
var $compile, $rootScope, element;
beforeEach(module('ui.directives'));
beforeEach(inject(function (_$rootScope_, _$compile_) {
$rootScope = _$rootScope_;
$compile = _$compile_;
}));
describe('ui changes on model changes', function () {
it('should update ui valid model value', function () {
$rootScope.x = undefined;
element = $compile(inputHtml)($rootScope);
$rootScope.$digest();
expect(element.val()).toBe('');
$rootScope.$apply(function () {
$rootScope.x = 12;
});
expect(element.val()).toBe('(1)2');
});
it('should wipe out ui on invalid model value', function () {
$rootScope.x = 12;
element = $compile(inputHtml)($rootScope);
$rootScope.$digest();
expect(element.val()).toBe('(1)2');
$rootScope.$apply(function () {
$rootScope.x = 1;
});
expect(element.val()).toBe('');
});
});
describe('model binding on ui change', function () {
//TODO: was having har time writing those tests, will open a separate issue for those
});
describe('should fail', function() {
it('errors on missing quotes', function() {
$rootScope.x = 42;
var errorInputHtml = "<input ui-mask=\"(9)9\" ng-model='x'>";
element = $compile(errorInputHtml)($rootScope);
expect($rootScope.$digest).toThrow('The Mask widget is not correctly set up');
});
});
});
|
var log = console.log
, Alice = require( '../' )
, ed = Alice()
, path = null
;
// same edge
ed.add( 1, 2 );
ed.add( 2, 1, true );
ed.add( 1, 2, true );
// vertex loop
ed.add( 2, 2 );
ed.cut( 2, 2 );
// same edge
ed.add( 2, 1, true );
ed.cut( 1, 2 );
ed.add( 1, 2 );
ed.cut( 2, 1 );
// add some edges
ed.add( 5, 4 );
ed.add( 4, 3 );
ed.add( 4, 1 );
ed.add( 2, 5 );
// add a cycle
ed.add( 2, 1 );
log();
log( '- 2-partite graph edges:', ed.e );
log();
log( '- 2-partite graph vertices:', ed.v );
log();
log( '- pruning edges to find cycles..' );
path = ed.prune( true );
log();
log( '- pruning results:', path );
log();
log( '- edge set is %sempty! (%d edges found)', ed.edges ? 'not ' : '', ed.edges );
log();
if ( ed.edges ) log( '- cycle found:', ed.e );
else log( '- no cycle found!' );
log();
|
(function () {
'use strict';
var $$compile = null,
$$rootScope = null,
scope = null;
describe('minItems validation directive', function () {
beforeEach(function () {
module('dynamic-forms');
inject(function ($compile, $rootScope) {
$$rootScope = $rootScope;
$$compile = $compile;
});
});
function createDynamicList(minItems, items) {
scope = $$rootScope.$new();
scope.model = items;
var element = angular.element('<div ng-model="model"></div>');
element.attr('data-min-items', minItems);
element = $$compile(element)(scope);
scope.$digest();
return element;
}
it('passes validation when the minItems is not a number', function() {
var element = createDynamicList('string', [1, 2, 3]);
expect(element.hasClass('ng-valid')).toBeTruthy();
expect(element.hasClass('ng-invalid')).not.toBeTruthy();
});
it('fails validation when the array length is less than the value', function () {
var element = createDynamicList(2, [1]);
expect(element.hasClass('ng-valid')).not.toBeTruthy();
expect(element.hasClass('ng-invalid')).toBeTruthy();
});
it('passes validation when the array length is equal to the value', function () {
var element = createDynamicList(3, [1, 2, 3]);
expect(element.hasClass('ng-invalid')).not.toBeTruthy();
expect(element.hasClass('ng-valid')).toBeTruthy();
});
it('fails validation when an item is removed and causes array length to be less than the min value', function () {
var element = createDynamicList(2, [1, 2]);
expect(element.hasClass('ng-invalid')).not.toBeTruthy();
expect(element.hasClass('ng-valid')).toBeTruthy();
scope.model.splice(0, 1);
scope.$digest();
expect(element.hasClass('ng-valid')).not.toBeTruthy();
expect(element.hasClass('ng-invalid')).toBeTruthy();
});
it('passes validation when min items is less than min value and then an item is added to be equal to the minItems', function () {
var element = createDynamicList(2, [1]);
expect(element.hasClass('ng-invalid')).toBeTruthy();
expect(element.hasClass('ng-valid')).not.toBeTruthy();
scope.model.push(2);
scope.$digest();
expect(element.hasClass('ng-valid')).toBeTruthy();
expect(element.hasClass('ng-invalid')).not.toBeTruthy();
});
});
}());
|
'use strict';
/**
* Scales an image or video to fill the screen in one dimension, preserving its
* aspect ratio.
*
* Serves as a polyfill for the CSS object-fit: contain property if it is not
* supported (mostly for IE).
*
* Should be applied to an <img> or <video> tag or a <div ng-bind-html> that
* will load content with either an <img> or <video> tag.
*/
function MediaContainDirective($timeout) {
return {
// Must be a class since this depends on CSS classes. ("-directive" is in
// the classname to differentiate a class-based directive from normal CSS).
restrict: 'C',
// Execute last.
priority: -1,
link: function ($scope, $element, $attrs) {
// If object-fit is supported, no need for rest of the directive.
// TODO(dbow): Make sure this is actually a viable feature detect...
// Could use Modernizr with non-core detect added.
if ('objectFit' in document.documentElement.style) {
return;
}
// Add polyfill class to override default object-fit styles.
$element.addClass('media-contain-directive-polyfill');
/**
* The IMG or VIDEO element found within $element.
* @type {Element}
*/
var mediaElement;
/**
* The angular.element version of mediaElement.
* @type {Object}
*/
var $mediaElement;
// Check if directive is applied directly to IMG or VIDEO element.
if ($element[0].tagName === 'IMG' || $element[0].tagName === 'VIDEO') {
$mediaElement = $element;
mediaElement = $element[0];
}
/**
* Checks an image or video to see if it needs to be adjusted to fill the
* screen. Media defaults to 100% width with no limit on height. This
* function checks to see if the image or video's aspect ratio is less
* than the window's. If so, adds a class that will make it 100% height
* with no limit on width. If an image or video with height and width
* cannot be found returns false so we can check again.
*
* @return {boolean} Whether a media element with width and height was
* found.
*/
function checkMedia() {
// If we haven't found the mediaElement yet, try to find an IMG or
// VIDEO in the $element's children.
var child;
if (!mediaElement) {
child = $element.find('IMG')[0] || $element.find('VIDEO')[0];
if (child) {
mediaElement = child;
$mediaElement = angular.element(mediaElement);
}
}
// If we've found the mediaElement and it has dimensions, adjust the
// class applied based on aspect ratio of the window and that of the
// mediaElement.
if (mediaElement) {
var mediaHeight = mediaElement.height || mediaElement.videoHeight;
var mediaWidth = mediaElement.width || mediaElement.videoWidth;
if (mediaHeight && mediaWidth) {
var windowAspectRatio = window.innerWidth / window.innerHeight;
$mediaElement.toggleClass('media-contain-directive-y',
mediaWidth / mediaHeight < windowAspectRatio);
// Remove listeners.
if (mediaElement.tagName === 'IMG') {
$mediaElement.off('load', checkMedia);
} else {
$mediaElement.off('loadedmetadata', checkMedia);
}
return true;
}
}
return false;
}
/**
* Checks if a mediaElement has been found yet, and if so, attaches
* the appropriate load listener ('load' for IMG, 'loadedmetadata' for
* VIDEO) based on tagName.
*
* @return {boolean} Whether a listener was set up.
*/
function listenForMediaLoad() {
if (mediaElement) {
if (mediaElement.tagName === 'IMG') {
$mediaElement.on('load', checkMedia);
} else {
$mediaElement.on('loadedmetadata', checkMedia);
}
return true;
}
return false;
}
/**
* Initialize the directive.
*
* Calls checkMedia to determine if the mediaElement has been found and
* its media has loaded. If not, tries to set up media load listeners to
* check again.
*
* @return {boolean} Whether either checkMedia or listenForMediaLoad
* was successful and the directive was initialized.
*/
function init() {
return checkMedia() || listenForMediaLoad();
}
// Try to inititalize the directive.
if (!init() && $attrs.ngBindHtml) {
// If we can't init yet and there is an ng-bind-html tag, wait for that
// to populate and then init again.
$scope.$watch('ngBindHtml', function() {
$timeout(init, 50); // Give HTML a chance to load.
});
}
// Update on resize (debounced).
angular.element(window).on('resize', _.debounce(checkMedia, 150));
}
};
}
angular
.module('angular-multimedia')
.directive('mediaContainDirective', ['$timeout', MediaContainDirective]);
|
(function(module){
'use strict';
//this comment set up here to turn off eslint warnings about unused vars
/*global issues issueView helpers d3Chart:true*/
//set up constructor for easier use of data
function RepoIssue (opts){
this.repoOwner = opts.html_url.split('/')[3];
this.repoName = opts.html_url.split('/')[4];
this.issueUser = opts.user.login;
this.issueUserAvatarURL = opts.user.avatar_url;
this.issueUserAcctURL = opts.user.html_url;
this.dateCreated = helpers.parseGitHubDate(opts.created_at),
this.daysAgo = helpers.numberOfDaysAgo(this.dateCreated);
this.daysAgoString = this.daysAgo;
if(this.daysAgo !== 'today' && this.daysAgo !== 1) this.daysAgoString = `${this.daysAgo} days ago`;
if(this.daysAgo === 1) this.daysAgoString = `${this.daysAgo} day ago`;
this.repoURL = helpers.parseRepoURL(opts.html_url),
this.issueURL = opts.html_url,
this.labels = opts.labels,
this.title = opts.title,
this.body = opts.body;
if (this.body === '') this.body = 'This user did not enter any text for this issue.';
this.id = opts.id;
}
let issues = {};
module.issues = issues;
issues.data = [];
issues.owner;
issues.repo;
issues.pageNumber = 1;
issues.perPage = 100;
issues.getIt = function(num, callback){
return $.ajax({
type: 'GET',
url: `/github/repos/${issues.owner}/${issues.repo}/issues?page=${num}&per_page=100`,
success: function(data){
issueView.noIssuesAlert(data, num);
data.forEach((element) => {
let issue = new RepoIssue(element);
issues.data.push(issue);
});
callback(issues.data);
},
error: function () {
issueView.badRequest();
},
});
};
issues.fetchData = function(num){
$.when(
$.get(`/github/repos/Automattic/mongoose/issues?page=${num}&per_page=100`)
.done((data) => {
if(data.length){
data.forEach((element) => {
let issue = new RepoIssue(element);
issues.data.push(issue);
});
num++;
issues.fetchData(num);
console.log(num, issues.data);
} else {
console.log('no more data');
}
})
.fail(() => {
issues.success = false;
})
);
};
})(window);
|
import { combineReducers } from 'redux';
import graph from './graph';
export default combineReducers({
graph
});
|
const PlotCard = require('../../plotcard');
const GameActions = require('../../GameActions');
class ThePrinceWhoCameTooLate extends PlotCard {
setupCardAbilities(ability) {
this.action({
title: 'Search your deck',
phase: 'standing',
handler: context => {
this.game.resolveGameAction(
GameActions.search({
title: 'Select a character',
match: { type: 'character' },
message: '{player} uses {source} to search their deck and put {searchTarget} into play',
cancelMessage: '{player} uses {source} to search their deck but does not find a card',
gameAction: GameActions.putIntoPlay(context => ({
player: context.player,
card: context.searchTarget
}))
}),
context
);
},
limit: ability.limit.perRound(1)
});
}
}
ThePrinceWhoCameTooLate.code = '15052';
module.exports = ThePrinceWhoCameTooLate;
|
/**
* A simple styled li element
*/
import styled from 'styled-components';
const Li = styled.li`
`;
export default Li;
|
/**
* Async is a utility module which provides straight-forward, powerful functions
* for working with asynchronous JavaScript. Although originally designed for
* use with [Node.js](http://nodejs.org) and installable via
* `npm install --save async`, it can also be used directly in the browser.
* @module async
*/
/**
* A collection of `async` functions for manipulating collections, such as
* arrays and objects.
* @module Collections
*/
/**
* A collection of `async` functions for controlling the flow through a script.
* @module ControlFlow
*/
/**
* A collection of `async` utility functions.
* @module Utils
*/
import applyEach from './applyEach';
import applyEachSeries from './applyEachSeries';
import apply from './apply';
import asyncify from './asyncify';
import auto from './auto';
import autoInject from './autoInject';
import cargo from './cargo';
import compose from './compose';
import concat from './concat';
import concatSeries from './concatSeries';
import constant from './constant';
import detect from './detect';
import detectLimit from './detectLimit';
import detectSeries from './detectSeries';
import dir from './dir';
import doDuring from './doDuring';
import doUntil from './doUntil';
import doWhilst from './doWhilst';
import during from './during';
import each from './each';
import eachLimit from './eachLimit';
import eachOf from './eachOf';
import eachOfLimit from './eachOfLimit';
import eachOfSeries from './eachOfSeries';
import eachSeries from './eachSeries';
import ensureAsync from './ensureAsync';
import every from './every';
import everyLimit from './everyLimit';
import everySeries from './everySeries';
import filter from './filter';
import filterLimit from './filterLimit';
import filterSeries from './filterSeries';
import forever from './forever';
import log from './log';
import map from './map';
import mapLimit from './mapLimit';
import mapSeries from './mapSeries';
import mapValues from './mapValues';
import mapValuesLimit from './mapValuesLimit';
import mapValuesSeries from './mapValuesSeries';
import memoize from './memoize';
import nextTick from './nextTick';
import parallel from './parallel';
import parallelLimit from './parallelLimit';
import priorityQueue from './priorityQueue';
import queue from './queue';
import race from './race';
import reduce from './reduce';
import reduceRight from './reduceRight';
import reflect from './reflect';
import reject from './reject';
import reflectAll from './reflectAll';
import rejectLimit from './rejectLimit';
import rejectSeries from './rejectSeries';
import retry from './retry';
import retryable from './retryable';
import seq from './seq';
import series from './series';
import setImmediate from './setImmediate';
import some from './some';
import someLimit from './someLimit';
import someSeries from './someSeries';
import sortBy from './sortBy';
import timeout from './timeout';
import times from './times';
import timesLimit from './timesLimit';
import timesSeries from './timesSeries';
import transform from './transform';
import unmemoize from './unmemoize';
import until from './until';
import waterfall from './waterfall';
import whilst from './whilst';
export default {
applyEach: applyEach,
applyEachSeries: applyEachSeries,
apply: apply,
asyncify: asyncify,
auto: auto,
autoInject: autoInject,
cargo: cargo,
compose: compose,
concat: concat,
concatSeries: concatSeries,
constant: constant,
detect: detect,
detectLimit: detectLimit,
detectSeries: detectSeries,
dir: dir,
doDuring: doDuring,
doUntil: doUntil,
doWhilst: doWhilst,
during: during,
each: each,
eachLimit: eachLimit,
eachOf: eachOf,
eachOfLimit: eachOfLimit,
eachOfSeries: eachOfSeries,
eachSeries: eachSeries,
ensureAsync: ensureAsync,
every: every,
everyLimit: everyLimit,
everySeries: everySeries,
filter: filter,
filterLimit: filterLimit,
filterSeries: filterSeries,
forever: forever,
log: log,
map: map,
mapLimit: mapLimit,
mapSeries: mapSeries,
mapValues: mapValues,
mapValuesLimit: mapValuesLimit,
mapValuesSeries: mapValuesSeries,
memoize: memoize,
nextTick: nextTick,
parallel: parallel,
parallelLimit: parallelLimit,
priorityQueue: priorityQueue,
queue: queue,
race: race,
reduce: reduce,
reduceRight: reduceRight,
reflect: reflect,
reflectAll: reflectAll,
reject: reject,
rejectLimit: rejectLimit,
rejectSeries: rejectSeries,
retry: retry,
retryable: retryable,
seq: seq,
series: series,
setImmediate: setImmediate,
some: some,
someLimit: someLimit,
someSeries: someSeries,
sortBy: sortBy,
timeout: timeout,
times: times,
timesLimit: timesLimit,
timesSeries: timesSeries,
transform: transform,
unmemoize: unmemoize,
until: until,
waterfall: waterfall,
whilst: whilst,
// aliases
all: every,
any: some,
forEach: each,
forEachSeries: eachSeries,
forEachLimit: eachLimit,
forEachOf: eachOf,
forEachOfSeries: eachOfSeries,
forEachOfLimit: eachOfLimit,
inject: reduce,
foldl: reduce,
foldr: reduceRight,
select: filter,
selectLimit: filterLimit,
selectSeries: filterSeries,
wrapSync: asyncify
};
export {
applyEach as applyEach,
applyEachSeries as applyEachSeries,
apply as apply,
asyncify as asyncify,
auto as auto,
autoInject as autoInject,
cargo as cargo,
compose as compose,
concat as concat,
concatSeries as concatSeries,
constant as constant,
detect as detect,
detectLimit as detectLimit,
detectSeries as detectSeries,
dir as dir,
doDuring as doDuring,
doUntil as doUntil,
doWhilst as doWhilst,
during as during,
each as each,
eachLimit as eachLimit,
eachOf as eachOf,
eachOfLimit as eachOfLimit,
eachOfSeries as eachOfSeries,
eachSeries as eachSeries,
ensureAsync as ensureAsync,
every as every,
everyLimit as everyLimit,
everySeries as everySeries,
filter as filter,
filterLimit as filterLimit,
filterSeries as filterSeries,
forever as forever,
log as log,
map as map,
mapLimit as mapLimit,
mapSeries as mapSeries,
mapValues as mapValues,
mapValuesLimit as mapValuesLimit,
mapValuesSeries as mapValuesSeries,
memoize as memoize,
nextTick as nextTick,
parallel as parallel,
parallelLimit as parallelLimit,
priorityQueue as priorityQueue,
queue as queue,
race as race,
reduce as reduce,
reduceRight as reduceRight,
reflect as reflect,
reflectAll as reflectAll,
reject as reject,
rejectLimit as rejectLimit,
rejectSeries as rejectSeries,
retry as retry,
retryable as retryable,
seq as seq,
series as series,
setImmediate as setImmediate,
some as some,
someLimit as someLimit,
someSeries as someSeries,
sortBy as sortBy,
timeout as timeout,
times as times,
timesLimit as timesLimit,
timesSeries as timesSeries,
transform as transform,
unmemoize as unmemoize,
until as until,
waterfall as waterfall,
whilst as whilst,
// Aliases
every as all,
everyLimit as allLimit,
everySeries as allSeries,
some as any,
someLimit as anyLimit,
someSeries as anySeries,
detect as find,
detectLimit as findLimit,
detectSeries as findSeries,
each as forEach,
eachSeries as forEachSeries,
eachLimit as forEachLimit,
eachOf as forEachOf,
eachOfSeries as forEachOfSeries,
eachOfLimit as forEachOfLimit,
reduce as inject,
reduce as foldl,
reduceRight as foldr,
filter as select,
filterLimit as selectLimit,
filterSeries as selectSeries,
asyncify as wrapSync
};
|
!function(a){"function"==typeof define&&define.amd?define(a):a()}(function(){var a="";return window.location.origin||(""!==window.location.port&&(a=":"),window.location.origin=window.location.protocol+"//"+window.location.hostname+a+window.location.port),{}});
|
var http = require("http").createServer(handler); // handler will be the function with req, res as in previous example, just separated
var io = require("socket.io").listen(http); // socket.io for permanent connection between server and client
var fs = require("fs"); // variable fo "file system", i.e. fs
var firmata = require("firmata"); // make pins on Arduin oaccesible via serial-USB communication
var sendValueViaSocket = function() {}; // function to send message over socket
var sendStaticMsgViaSocket = function() {}; // function to send static message over socket
function handler(req, res) { // function with request and response, that is used in the first line of this example
fs.readFile(__dirname + "/Untitled13.html",
function (err, data){
if (err) {
res.writeHead(500, {"Content-Type": "text/plain"});
return res.end("Error loading html page.");
}
res.writeHead(200);
res.end(data);
})
}
var desiredValue = 0; // variable for desired value (reference value or input)
var actualValue = 0; // variable for actual value (output value)
// PID Algorithm variables
var Kp = 0.55; // proportional factor
var Ki = 0.008; // integral factor
var Kd = 0.15; // differential factor
var pwm = 0;
var pwmLimit = 254;
var err = 0; // variable for second pid implementation
var errSum = 0; // sum of errors
var dErr = 0; // difference of error
var lastErr = 0; // to keep the value of previous error
var controlAlgorithmStartedFlag = 0; // flag in global scope to see weather ctrlAlg has been started
var intervalCtrl; // var for setInterval in global space
var KpE = 0; // multiplication of Kp x error
var KiIedt = 0; // multiplication of Ki x integral of error
var KdDe_dt = 0; // multiplication of Kd x differential of error i.e.e Derror/dt
http.listen(8080); // determine on which port to listen (8080)
console.log("Starting the system"); // print the message to the console
var board = new firmata.Board("/dev/ttyACM0", function(){ // ACM Abstract Control Model for serial communication with Arduino (could be USB)
console.log("Connecting to Arduino");
board.pinMode(0, board.MODES.ANALOG); // analog pin 0
board.pinMode(1, board.MODES.ANALOG); // analog pin 1
board.pinMode(2, board.MODES.OUTPUT); // direction of DC motor
board.pinMode(3, board.MODES.PWM); // PWM of motor i.e. speed of rotation
board.pinMode(4, board.MODES.OUTPUT); // direction DC motor
});
board.on("ready", function() {
board.analogRead(0, function(value) {
desiredValue = value; // continuous read of pin A0
});
board.analogRead(1, function(value) {
actualValue = value; // continuous read of pin A1
});
io.sockets.on('connection', function(socket) { // from bracket ( onward, we have an argument of the function on -> at 'connection' the argument is transfered i.e. function(socket)
socket.emit("messageToClient", "Server connected, board ready.");
socket.emit("staticMsgToClient", "Server connected, board ready.")
setInterval(sendValues, 40, socket); // na 40ms we send message to client
socket.on("startControlAlgorithm", function(numberOfControlAlgorithm){
startControlAlgorithm(numberOfControlAlgorithm);
});
socket.on("stopControlAlgorithm", function(){
stopControlAlgorithm();
});
sendValueViaSocket = function (value) {
io.sockets.emit("messageToClient", value);
}
sendStaticMsgViaSocket = function (value) {
io.sockets.emit("staticMsgToClient", value);
}
});
});
function controlAlgorithm (parameters) {
if (parameters.ctrlAlgNo == 1) {
pwm = parameters.pCoeff*(desiredValue-actualValue);
if(pwm > pwmLimit) {pwm = pwmLimit}; // to limit the value for pwm / positive
if(pwm < -pwmLimit) {pwm = -pwmLimit}; // to limit the value for pwm / negative
if (pwm > 0) {board.digitalWrite(2,1); board.digitalWrite(4,0);}; // določimo smer če je > 0
if (pwm < 0) {board.digitalWrite(2,0); board.digitalWrite(4,1);}; // določimo smer če je < 0
board.analogWrite(3, Math.round(Math.abs(pwm)));
console.log(Math.round(pwm));
}
if (parameters.ctrlAlgNo == 2) {
err = desiredValue - actualValue; // error
errSum += err; // sum of errors, like integral
dErr = err - lastErr; // difference of error
// for sending to client we put the parts to global scope
KpE=parameters.Kp1*err;
KiIedt=parameters.Ki1*errSum;
KdDe_dt=parameters.Kd1*dErr;
pwm = KpE + KiIedt + KdDe_dt; // above parts are used
lastErr = err; // save the value for the next cycle
if(pwm > pwmLimit) {pwm = pwmLimit}; // to limit the value for pwm / positive
if(pwm < -pwmLimit) {pwm = -pwmLimit}; // to limit the value for pwm / negative
if (pwm > 0) {board.digitalWrite(2,1); board.digitalWrite(4,0);}; // določimo smer če je > 0
if (pwm < 0) {board.digitalWrite(2,0); board.digitalWrite(4,1);}; // določimo smer če je < 0
board.analogWrite(3, Math.abs(pwm));
}
};
function sendValues (socket) {
socket.emit("clientReadValues",
{ // json notation between curly braces
"desiredValue": desiredValue,
"actualValue": actualValue,
"pwm": pwm,
"err": err,
"errSum": errSum,
"dErr": dErr,
"KpE": KpE,
"KiIedt": KiIedt,
"KdDe_dt": KdDe_dt });
};
function startControlAlgorithm (parameters) {
if (controlAlgorithmStartedFlag == 0) {
controlAlgorithmStartedFlag = 1; // set flag that the algorithm has started
intervalCtrl = setInterval(function() {controlAlgorithm(parameters); }, 30); // na 30ms klic
console.log("Control algorithm " + parameters.ctrlAlgNo + " started");
sendStaticMsgViaSocket("Control algorithm " + parameters.ctrlAlgNo + " started | " + json2txt(parameters));
}
};
function stopControlAlgorithm () {
clearInterval(intervalCtrl); // clear the interval of control algorihtm
board.analogWrite(3,0); // write 0 on pwm pin to stop the motor
controlAlgorithmStartedFlag = 0; // set flag that the algorithm has stopped
pwm = 0; // set pwm to 0
console.log("ctrlAlg STOPPED");
sendStaticMsgViaSocket("Stop");
};
function json2txt(obj) // function to print out the json names and values
{
var txt = '';
var recurse = function(_obj) {
if ('object' != typeof(_obj)) {
txt += ' = ' + _obj + '\n';
}
else {
for (var key in _obj) {
if (_obj.hasOwnProperty(key)) {
txt += '.' + key;
recurse(_obj[key]);
}
}
}
};
recurse(obj);
return txt;
}
|
var gulp = require('gulp');
var phpspec = require('gulp-phpspec');
var run = require('gulp-run');
var plumber = require('gulp-plumber');
var notify = require('gulp-notify');
gulp.task('test', function() {
gulp.src('spec/**/*.php')
.pipe(run('clear'))
.pipe(phpspec('', { 'verbose': 'v', notify: true }))
.on('error', notify.onError({
title: "Crap",
message: "The tests failed.",
icon: __dirname + '/fail.png'
}))
.pipe(notify({
title: "Success",
message: "All tests have returned green!"
}));
});
gulp.task('watch', function() {
gulp.watch(['spec/**/*.php', 'src/**/*.php'], ['test']);
});
gulp.task('default', ['test', 'watch']);
|
export const selectGallery = (gallery) => ({
type: 'SELECT_GALLERY',
gallery
})
|
// moment.js locale configuration
// locale : tibetan (bo)
// author : Thupten N. Chakrishar : https://github.com/vajradog
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['../moment'], factory); // AMD
} else if (typeof exports === 'object') {
module.exports = factory(require('../moment')); // Node
} else {
factory(window.moment); // Browser global
}
}(function (moment) {
var symbolMap = {
'1': '༡',
'2': '༢',
'3': '༣',
'4': '༤',
'5': '༥',
'6': '༦',
'7': '༧',
'8': '༨',
'9': '༩',
'0': '༠'
},
numberMap = {
'༡': '1',
'༢': '2',
'༣': '3',
'༤': '4',
'༥': '5',
'༦': '6',
'༧': '7',
'༨': '8',
'༩': '9',
'༠': '0'
};
return moment.defineLocale('bo', {
months : 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split("_"),
monthsShort : 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split("_"),
weekdays : 'གཟའ་ཉི་མ་_གཟའ་ཟླ་བ་_གཟའ་མིག་དམར་_གཟའ་ལྷག་པ་_གཟའ་ཕུར་བུ_གཟའ་པ་སངས་_གཟའ་སྤེན་པ་'.split("_"),
weekdaysShort : 'ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་'.split("_"),
weekdaysMin : 'ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་'.split("_"),
longDateFormat : {
LT : "A h:mm",
L : "DD/MM/YYYY",
LL : "D MMMM YYYY",
LLL : "D MMMM YYYY, LT",
LLLL : "dddd, D MMMM YYYY, LT"
},
calendar : {
sameDay : '[དི་རིང] LT',
nextDay : '[སང་ཉིན] LT',
nextWeek : '[བདུན་ཕྲག་རྗེས་མ], LT',
lastDay : '[ཁ་སང] LT',
lastWeek : '[བདུན་ཕྲག་མཐའ་མ] dddd, LT',
sameElse : 'L'
},
relativeTime : {
future : "%s ལ་",
past : "%s སྔན་ལ",
s : "ལམ་སང",
m : "སྐར་མ་གཅིག",
mm : "%d སྐར་མ",
h : "ཆུ་ཚོད་གཅིག",
hh : "%d ཆུ་ཚོད",
d : "ཉིན་གཅིག",
dd : "%d ཉིན་",
M : "ཟླ་བ་གཅིག",
MM : "%d ཟླ་བ",
y : "ལོ་གཅིག",
yy : "%d ལོ"
},
preparse: function (string) {
return string.replace(/[༡༢༣༤༥༦༧༨༩༠]/g, function (match) {
return numberMap[match];
});
},
postformat: function (string) {
return string.replace(/\d/g, function (match) {
return symbolMap[match];
});
},
meridiem : function (hour, minute, isLower) {
if (hour < 4) {
return "མཚན་མོ";
} else if (hour < 10) {
return "ཞོགས་ཀས";
} else if (hour < 17) {
return "ཉིན་གུང";
} else if (hour < 20) {
return "དགོང་དག";
} else {
return "མཚན་མོ";
}
},
week : {
dow : 0, // Sunday is the first day of the week.
doy : 6 // The week that contains Jan 1st is the first week of the year.
}
});
}));
|
/**
* Created by JinWYP on 7/27/16.
*/
var expect = require('chai').expect;
var colorConverter = require('../../../business-libs/colorConverter');
describe('Color Code Converter', function() {
describe('RGB to Hex conversion', function() {
it('converts the basic colors', function() {
var redHex = colorConverter.rgbToHex(255, 0, 0);
var greenHex = colorConverter.rgbToHex(0, 255, 0);
var blueHex = colorConverter.rgbToHex(0, 0, 255);
expect(redHex).to.equal('ff0000');
expect(greenHex).to.equal('00ff00');
expect(blueHex).to.equal('0000ff');
});
});
describe('Hex to RGB conversion', function() {
it('converts the basic colors', function() {
var red = colorConverter.hexToRgb('ff0000');
var green = colorConverter.hexToRgb('00ff00');
var blue = colorConverter.hexToRgb('0000ff');
expect(red).to.deep.equal([255, 0, 0]);
expect(green).to.deep.equal([0, 255, 0]);
expect(blue).to.deep.equal([0, 0, 255]);
});
});
});
|
/*jslint node: true*/
/*jslint nomen: true*/
"use strict";
var
React = require('react'),
ActionBindingMixin = require('../mixins/ActionBindingMixin'),
serialize = require('form-serialize');
module.exports = React.createClass({
mixins: [ActionBindingMixin],
render: function () {
return React.createElement("form", React.__spread({}, this.props, {onSubmit: this.onSubmit}), this.props.children);
},
onSubmit: function (event) {
event.preventDefault();
this.callAction(serialize(event.target, {
hash: !this.props.urlEncoding
}));
}
});
|
var Easel = require('easel');
var app = new Easel();
app.server.start();
|
/* eslint-env mocha, jest */
import getActualComponentFactory from '../../lib/testUtils';
import Task from '../Task';
const defaultProps = {
index: 0,
color: 'red',
text: 'a cool task',
estimation: '60',
due: '',
repeat: '',
done: false,
onRequestDo() {},
onRequestDelete() {},
onRequestSnackbar() {},
onRequestEditTaskOpen() {},
};
const getActualTask = getActualComponentFactory(Task, defaultProps);
jest.useFakeTimers();
it('should render', () => {
getActualTask();
});
it('should be a div', () => {
const wrapper = getActualTask();
expect(wrapper.is('div.Task')).toBe(true);
});
it('should have 1 text div', () => {
const wrapper = getActualTask();
expect(wrapper.find('div.text').length).toBe(1);
});
it('should have 1 Estimation', () => {
const wrapper = getActualTask();
expect(wrapper.find('Estimation').length).toBe(1);
});
it('should have 1 DueDate', () => {
const wrapper = getActualTask();
expect(wrapper.find('DueDate').length).toBe(1);
});
it('should have 1 Repeat', () => {
const wrapper = getActualTask();
expect(wrapper.find('Repeat').length).toBe(1);
});
it('should have 1 Actions', () => {
const wrapper = getActualTask();
expect(wrapper.find('Actions').length).toBe(1);
});
it('should set Circle color based on props', () => {
const wrapper = getActualTask({ color: 'blue' });
expect(wrapper.find('Circle').prop('color')).toBe('blue');
});
it('should set Circle signal based on props', () => {
const wrapper = getActualTask({ signal: true });
expect(wrapper.find('Circle').prop('signal')).toBe(true);
});
it('should set text div text based on props', () => {
const wrapper = getActualTask({ text: 'a cooler idea' });
expect(wrapper.find('div.text').text()).toBe('a cooler idea');
});
it('should set Estimation estimation based on props', () => {
const wrapper = getActualTask({ estimation: '30' });
expect(wrapper.find('Estimation').prop('estimation')).toBe('30');
});
it('should set DueDate due based on props', () => {
const wrapper = getActualTask({ due: 'tomorrow' });
expect(wrapper.find('DueDate').prop('due')).toBe('tomorrow');
});
it('should set Repeat repeat based on props', () => {
const wrapper = getActualTask({ repeat: '5' });
expect(wrapper.find('Repeat').prop('repeat')).toBe('5');
});
it('should set Actions done based on props', () => {
const wrapper = getActualTask({ done: true });
expect(wrapper.find('Actions').prop('done')).toBe(true);
});
it('should call onRequestDelete inside Actions onRequestDelete', () => {
const wrapper = getActualTask({
index: 3,
onRequestDelete(index) {
expect(index).toBe(3);
},
});
wrapper.find('Actions').props().onRequestDelete();
jest.runAllTimers();
});
it('should call onRequestSnackbar inside Actions onRequestDelete', () => {
const wrapper = getActualTask({
onRequestSnackbar(message) {
expect(message).toBe('Task deleted');
},
});
wrapper.find('Actions').props().onRequestDelete();
jest.runAllTimers();
});
it('should call onRequestDo inside Actions onRequestDo', () => {
const wrapper = getActualTask({
index: 3,
onRequestDo(index) {
expect(index).toBe(3);
},
});
wrapper.find('Actions').props().onRequestDo();
jest.runAllTimers();
});
it('should call onRequestSnackbar inside Actions onRequestDo', () => {
const wrapper = getActualTask({
onRequestSnackbar(message) {
expect(message).toBe('Task done');
},
});
wrapper.find('Actions').props().onRequestDo();
jest.runAllTimers();
});
it('should call onRequestEditTaskOpen inside Actions onRequestEditDialogOpen', () => {
const wrapper = getActualTask({
index: 3,
onRequestEditTaskOpen(index) {
expect(index).toBe(3);
},
});
wrapper.find('Actions').props().onRequestEditDialogOpen();
jest.runAllTimers();
});
it('should remove its done class based on state', () => {
const wrapper = getActualTask({
repeat: '5',
});
wrapper.find('Actions').props().onRequestDo();
wrapper.update();
jest.runAllTimers();
expect(wrapper.props().className.includes('done')).toBe(false);
});
|
import React from 'react'
import { ScrollView, StyleSheet, View } from 'react-native'
import { Video as ExpoVideo } from 'expo'
import VideoPlayer from '@expo/videoplayer'
import { Ionicons } from '@expo/vector-icons'
import PropTypes from 'prop-types'
import { Colors } from 'constants'
const styles = StyleSheet.create( {
container: {
flex: 1,
backgroundColor: Colors.baseWhite,
},
} )
const Video = ( { uri, shouldPlay } ) => {
const icon = ( name, size = 36 ) => () => (
<Ionicons
name={name}
size={size}
color={Colors.tintColor}
style={{ textAlign: 'center' }}
/>
)
return (
<View style={styles.container}>
<ScrollView style={styles.container}>
<VideoPlayer
videoProps={{
isLooping: true,
isMuted: true,
repeat: true,
shouldPlay: shouldPlay,
resizeMode: ExpoVideo.RESIZE_MODE_CONTAIN,
source: {
uri,
},
}}
textStyle={{
color: Colors.tintColor,
fontSize: 12,
}}
playIcon={icon( 'ios-play-outline' )}
pauseIcon={icon( 'ios-pause-outline' )}
fullscreenEnterIcon={icon( 'ios-expand-outline', 0 )}
fullscreenExitIcon={icon( 'ios-contract-outline', 0 )}
switchToLandscape={e => console.log( e )}
switchToPortrait={e => console.log( e )}
playFromPositionMillis={0}
/>
</ScrollView>
</View>
)
}
Video.propTypes = {
shouldPlay: PropTypes.bool.isRequired,
uri: PropTypes.string.isRequired,
}
Video.defaultProps = {
shouldPlay: false,
}
export default Video
|
import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import page from '../../../pages/components/kinetic-form/radios';
import sinon from 'sinon';
const { run, set, get } = Ember;
moduleForComponent('kinetic-form/radios', 'Integration | Component | kinetic form/radios', {
integration: true,
beforeEach() {
page.setContext(this);
set(this, 'updateSpy', sinon.spy());
},
afterEach() {
page.removeContext();
}
});
test('displays field.title', function(assert) {
set(this, 'testField', {title: 'test-title'});
page.render(hbs`{{kinetic-form/radios field=testField update=(action updateSpy)}}`);
assert.ok(page.hasInTitle('test-title'), 'expected field.title to be displayed');
});
test('highlights as required when field.required is true', function(assert) {
set(this, 'testField', {required: false});
page.render(hbs`{{kinetic-form/radios field=testField update=(action updateSpy)}}`);
assert.notOk(page.isRequired, 'expected component to not be highlighted as required');
run(() => set(this, 'testField.required', true));
assert.ok(page.isRequired, 'expected component to be highlighted as required');
});
test('shows the current value', function(assert) {
set(this, 'testValue', true);
page.render(hbs`{{kinetic-form/radios value=testValue update=(action updateSpy)}}`);
assert.ok(page.isOn, 'expected on button to be active');
assert.notOk(page.isOff, 'expected off button to not be active');
run(() => set(this, 'testValue', false));
assert.notOk(page.isOn, 'expected on button to not be active');
assert.ok(page.isOff, 'expected off button to be active');
});
test('calls update action when user enters text', function() {
page.render(hbs`{{kinetic-form/radios update=(action updateSpy)}}`);
run(() => page.turnOn());
sinon.assert.calledWith(get(this, 'updateSpy'), true);
run(() => page.turnOff());
sinon.assert.calledWith(get(this, 'updateSpy'), false);
});
test('highlights as an error when error is truthy', function(assert) {
set(this, 'testError', null);
page.render(hbs`{{kinetic-form/radios error=testError update=(action updateSpy)}}`);
assert.notOk(page.hasError, 'expected to not have error highlight');
run(() => set(this, 'testError', {message: 'test-error'}));
assert.ok(page.hasError, 'expected to have error highlight');
});
|
// Copyright 2012 Ofir Picazo. All Rights Reserved.
/**
* @fileoverview Foundation object, fill one per suit to complete the game.
*
* @author ofirpicazo@gmail.com (Ofir Picazo)
*/
goog.provide('solitario.game.Foundation');
goog.require('goog.dom.dataset');
goog.require('solitario.game.Card');
goog.require('solitario.game.Pile');
/**
* Class to represent a foundation in the game.
*
* @param {!Element} el DOM element representing the foundation.
* @constructor
* @extends {solitario.game.Pile}
*/
solitario.game.Foundation = function(el) {
goog.base(this, el);
/**
* Type of pile, workaround to avoid using instanceof.
* @type {solitario.game.constants.PileTypes}
*/
this.pileType = solitario.game.constants.PileTypes.FOUNDATION;
/**
* Suit this foundation contains.
* @type {?solitario.game.constants.SUIT}
*/
this.suit = null;
};
goog.inherits(solitario.game.Foundation, solitario.game.Pile);
/**
* Return true if this foundation can accept the passed card given the game
* rules.
*
* @param {solitario.game.Card} card The card to be evaluated.
* @return {boolean} true if the card can be pushed to the tableu, false if not.
* @override
*/
solitario.game.Foundation.prototype.canAcceptCard = function(card) {
// If the super class says no, we cannot say yes.
if (!solitario.game.Foundation.superClass_.canAcceptCard.call(this, card)) {
return false;
}
// Check that card is a Ace when the foundation is empty, otherwise it must be
// the next card for the suit of the pile.
if (this.isEmpty()) {
return (card.number == solitario.game.constants.CardNumber.ACE);
} else {
var topCard = this.getTopCard();
return (card.suit == this.suit && (card.value - topCard.value == 1));
}
};
/**
* Pop a card off of the foundation.
*
* @return {?solitario.game.Card} The card popped from the pile.
* @override
*/
solitario.game.Foundation.prototype.pop = function() {
var card = solitario.game.Foundation.superClass_.pop.call(this);
if (this.isEmpty()) {
this.suit = null;
}
return card;
};
/**
* Adds a new card to the foundation. Sets the foundation's suit if it's not yet
* set.
*
* @param {solitario.game.Card} card Card to be pushed.
* @override
*/
solitario.game.Foundation.prototype.push = function(card) {
solitario.game.Foundation.superClass_.push.call(this, card);
if (!this.suit) {
this.suit = card.suit;
}
};
|
(function() {
"use strict";
define(
function() {
var interactiveToolConfig = new function() {
var self = this;
//This is the default value for the textbox that holds the value of the number of units to buffer in the buffering tool
self.defaultBufferValue = 1;
//his is a configurable list of units that can be used to buffer search areas.
self.bufferUnits = [{
text: "Mile",
value: esri.tasks.GeometryService.UNIT_NAUTICAL_MILE
}, {
text: "Kilometer",
value: esri.tasks.GeometryService.UNIT_KILOMETER
}, {
text: "Feet",
value: esri.tasks.GeometryService.UNIT_FOOT
}, {
text: "Meter",
value: esri.tasks.GeometryService.UNIT_METER
}];
//This is the default selected index in the unit selector for the buffering tool
self.selectedBufferUnitIndex = 0;
//This is the URl to the geometry service that performs the buffering for the buffering tool.
self.geometryServiceURL = "http://geo.azmag.gov/gismag/rest/services/Utilities/Geometry/GeometryServer";
//This is the spatial reference specified for the buffered area.
self.bufferSpatialReference = {
wkid: 26949
};
// JSON respresentation of an ESRI Simple Fill Symbol
// http://resources.arcgis.com/en/help/arcgis-rest-api/#/Symbol_Objects/02r3000000n5000000/
self.selectionPointSymbol = {
type: "simplemarkersymbol",
style: "esriSFSNull",
color: [255, 0, 255, 191]
};
self.selectionSymbol = {
type: "esriSFS",
style: "esriSFSNull",
color: [0, 0, 0, 0],
outline: {
type: "esriSLS",
style: "esriSLSDash",
color: [255, 0, 255, 191],
width: 3
}
};
self.bufferSymbol = {
type: "esriSFS",
style: "esriSFSNull",
color: [0, 0, 0, 0],
outline: {
type: "esriSLS",
style: "esriSLSDash",
color: [255, 0, 0, 191],
width: 3
}
};
};
return interactiveToolConfig;
}
);
}());
|
module.exports.generator = function () {
// This should return a new bite code in the form of a String
}
|
export const encodeArrayForUrl = (values) => {
const encodedValues = values.map(encodeURIComponent)
return encodedValues.join(',')
}
export const getArrayFromUrlParam = (urlParam) => {
const encodedValues = urlParam.split(',')
return encodedValues.map(decodeURIComponent)
}
export const buildQueryForUrl = (filterParams) => {
const query = []
if (filterParams) {
for (let fieldName in filterParams) {
const fieldValue = filterParams[fieldName]
if (fieldValue !== undefined && fieldValue !== null && fieldValue !== '') {
const param = `${fieldName}=${encodeURIComponent(fieldValue.toString())}`
query.push(param)
}
}
}
if (query.length) {
const urlParams = `?${query.join('&')}`
return urlParams
}
return ''
}
export const buildUrl = (basePath, filterParams) => {
const urlParams = buildQueryForUrl(filterParams)
return basePath + urlParams
}
|
import defaultCardConfig from '../defaultCardConfig';
/**
* Maps room to limited set of properties for export (room as file download).
*
* @param room
* @return {undefined|{stories: *, exportedAt: number, roomId}}
*/
export function mapRoomExportDto(room) {
if (!room) {
return undefined;
}
return {
roomId: room.id,
exportedAt: Date.now(),
stories: room.stories
.filter((story) => !story.trashed)
.map((story) => mapStoryExportDto(story, room.users))
};
}
function mapStoryExportDto(story, users) {
const usernamesMap = users.reduce((total, currentUser) => {
total[currentUser.id] = currentUser.username || currentUser.id;
return total;
}, {});
return {
title: story.title,
description: story.description,
consensus: story.consensus,
estimations: Object.entries(story.estimations).map((entry) => {
const matchingUser = usernamesMap[entry[0]];
const mappedEstm = {
username: matchingUser ? matchingUser : entry[0],
value: entry[1]
};
if (matchingUser) {
mappedEstm.userId = entry[0];
}
if (story.estimationsConfidence && story.estimationsConfidence[entry[0]]) {
mappedEstm.confidence = story.estimationsConfidence[entry[0]];
}
return mappedEstm;
})
};
}
/**
* Maps to extensive set of properties. This is used to re-sync client state with backend state and should return the same information as contained in the "joinedRoom" event.
*
* @param room
* @return {undefined|{selectedStory, stories, autoReveal, id, cardConfig: *, users}}
*/
export function mapRoomStateDto(room) {
if (!room) {
return undefined;
}
const {
id,
autoReveal,
withConfidence,
issueTrackingUrl,
selectedStory,
stories,
users,
cardConfig
} = room;
return {
id,
autoReveal,
withConfidence,
issueTrackingUrl,
selectedStory,
stories,
users,
passwordProtected: !!room.password,
cardConfig: cardConfig ? cardConfig : defaultCardConfig
};
}
/**
*
* @param {object[]} allRooms List of all rooms from the store
* @param {string} storeType
* @return {{roomCount: number, rooms: {userCount: *, created: number|*, userCountDisconnected: *, lastActivity: number|*, markedForDeletion: boolean|[]|*, storyCount: *}[], storeInfo: (string|*), uptime: number}}
*/
export function mapAppStatusDto(allRooms, storeType) {
const rooms = Object.values(allRooms).map((room) => ({
storyCount: room.stories.length,
userCount: room.users.length,
userCountDisconnected: room.users.filter((user) => user.disconnected).length,
lastActivity: room.lastActivity,
markedForDeletion: room.markedForDeletion,
created: room.created
}));
return {
rooms,
roomCount: rooms.length,
uptime: Math.floor(process.uptime()),
storeInfo: storeType
};
}
|
//9.2.1
//Pseudocode -------------------------------------------
//create function to make a new list,
// that takes a string and split it and create a object with the splited words
//go through each element inside the object
//display the list
//create a function that adds an item with quantity to the list.
//if the item is not on the list, give it a value otherwise add to qty.
//create a function that removes an item.
//if the item is in the list, delete the item.
//create a function that displays the list.
//the list should list "You have QUANTITY ITEM in your list."
//initial solution-------------------------------------
function newList(stuff){
var list = {};
var items = stuff.split(" ");
for (var x = 0; x < items.length; x++){
list[items[x]] = 1;
}
return list
}
function addQuanity(list_name, item, qty){
if (list_name[item] === undefined){
list_name[item] = qty
}
else {
list_name[item] += qty
}
}
function removeItem(list_name, item) {
delete list_name[item]
}
function updateQuanity(list_name, item, qty){
list_name[item] = qty
}
function printList(list_name) {
for(var item in list_name) {
console.log('You have ' + list_name[item] + " " + [item] + ' in your list.' )
}
}
//Driver code
var something = new newList("apple bread coffee chocolate");
// console.log(something)
addQuanity(something, "herbs", 1)
// console.log(something)
removeItem(something, "apple");
// console.log(something)
updateQuanity(something, "bread", 30)
console.log(something)
printList(something)
//Refactor --------------------------------------
function newList(stuff){
var list = {};
var items = stuff.split(" ");
for (var x = 0; x < items.length; x++){
list[items[x]] = 1;
}
return list
}
function changeQuanity(list_name, item, qty){
if (list_name[item] === undefined){
list_name[item] = qty
} else {
list_name[item] += qty
}
}
function removeItem(list_name, item) {
delete list_name[item]
}
function printList(list_name) {
for(var item in list_name) {
console.log('You have ' + list_name[item] + " " + [item] + ' in your list.' )
}
}
//Reflection -------------------------------------
/*
What concepts did you solidify in working on this challenge? (reviewing the passing of information, objects, constructors, etc.)
This challenge solidified my understanding of arguments in functions. It is nice to be able to pass as many arguments we want. I also had more practice with accessing objects and manipulating them to do what I want of them. And as I was trying to figure out how to do string intrapolation, I realized that they were just variables, so why not concat variables into my strings?
What was the most difficult part of this challenge?
The most difficult part for me was how to find a way to access my list outside the function. Then I realized that I could just create a new list and manipulate them that way.
Did an array or object make more sense to use and why?
Yes it did, when I worked on the tallyvotes challenge I was getting really confused with what I was accessing from the object, even after giving them variables. With more practice I was able to easily see what I was accessing and control the object the way I wanted.
*/
//9.2.2
//Pseudocode -------------------------------------------
//input: array from 1 to 10
//output:
//multiples of 3 display RETURN fizz
//multiples of 5 display RETURN buzz
//multiples of 15 display RETURN fizbuzz
//make a function that takes an array as an input
//iterate the array through each element of the array as the array iterates each element we need to return the elements into "fizzbuzzed"(maybe)
//if the element is divisible by 15 RETURN "FizzBuzz"
//if the element is divisible by 5 RETURN "Buzz"
//if the element is divisible by 3 RETURN "Fizz"
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
function super_fizz_buzz(input){
for(var x = 0;x<=input.length;x++) {
if (input[x] % 15 == 0)
console.log("FizzBuzz");
else if (input[x] % 3 == 0)
console.log("Fizz");
else if (input[x] % 5 == 0)
console.log("Buzz");
else
console.log(input[x]);
};
};
//Driver code
console.log(super_fizz_buzz(array));
//Refactor --------------------------------------
function super_fizz_buzz(input){
for(var x = 0;x<=input.length;x++) {
var fizz = input[x] % 3 == 0, buzz = input[x] % 5 == 0;
console.log(fizz ? buzz ? "FizzBuzz" : "Fizz" : buzz ? "Buzz" : x);
};
};
//Reflection -------------------------------------
/*
What concepts did you solidify in working on this challenge?
It was good practice with loops, if/else statements and functions.
What was the most difficult part of this challenge?
The most difficult part was the refactoring. I found a way to use tiernary operator similar to one of ruby to refactor the if/else conditions into one line.
Did you solve the problem in a new way this time?
No, I just translated how I had in ruby. The only difference is instead of using the map enumerable, I used a FOR loop to iterate through the array.
Was your pseudocode different from the Ruby version? What was the same and what was different?
My pseudocode was the same as my ruby version. The only differnce was my syntax which I ended using a FOR loop and counted from each index in the array.
*/
|
import chalk from 'chalk'
import moment from 'moment'
import Table from 'cli-table'
import bugger from 'debug'
const debug = bugger('todo:util')
/**
* Format console.log calls for readability and structure
* @param {String} data message to be logged
*/
function log(data) {
let time = moment().format('MM/DD hh:mm:ss:SS')
let prefix = chalk.cyan(`[ ${time} ] - `)
let content = chalk.red(data)
debug('Logging out content %o', data)
console.log(content)
}
/**
* A collection of utility functions for formatting
* logged output.
* @type {Object}
*/
const format = {
task: function(group, source) {
return source.map(item => {
return `@${group} - ${item.task}`
}).join('\n')
}
}
/**
* A collection of error templates
* @type {Object}
*/
const err = {
group: function(group, exists) {
let output = group == '_'
? 'general group'
: group
let message = exists
? `No tasks found in ${output}`
: `Group "${output}" doesn't exist`
return message
}
}
export { log, format, err }
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.8/esri/copyright.txt for details.
//>>built
define(["require","exports","../2d/engine/webgl/Geometry","./GeometryUtils"],function(m,n,p,r){Object.defineProperty(n,"__esModule",{value:!0});m=function(){function g(a,b,e,c){this.left=a;this.top=b;this.right=e;this.bottom=c}g.prototype.clone=function(){return new g(this.left,this.top,this.right,this.bottom)};g.prototype.move=function(a,b){this.left+=a;this.top+=b;this.right+=a;this.bottom+=b};g.prototype.rotate=function(a,b){var e=this.left,c=this.right,d=this.top,f=this.bottom,g=e*a-d*b,k=e*b+
d*a,h=c*a-d*b,d=c*b+d*a,l=e*a-f*b,e=e*b+f*a,m=c*a-f*b;a=c*b+f*a;this.left=Math.min(g,h,l,m);this.top=Math.min(k,d,e,a);this.right=Math.max(g,h,l,m);this.bottom=Math.max(k,d,e,a)};g.overlaps=function(a,b){return a.right>b.left&&a.left<b.right&&a.bottom>b.top&&a.top<b.bottom};return g}();n.Box=m;var t=function(){function g(a,b,e,c){this.anchor=a;this.corners=b;this.minzoom=e;this.maxzoom=c}g.prototype.left=function(){return this.corners[0].x};g.prototype.right=function(){return this.corners[2].x};g.prototype.top=
function(){return this.corners[1].y};g.prototype.bottom=function(){return this.corners[3].y};return g}();n.Obstacle=t;m=function(){function g(a,b,e){this.obstacles=[];this.mapAngle=a;this.padding=b;this.isScreenAligned=e;this.minzoom=u}g.prototype.addBox=function(a,b,e,c,d,f,g){var k=b.left*e-this.padding,h=b.top*e-this.padding,l=b.right*e+this.padding;b=b.bottom*e+this.padding;k=[new p.Point(k,h),new p.Point(l,h),new p.Point(l,b),new p.Point(k,b)];0!==this.mapAngle&&(h=Math.cos(this.mapAngle),l=
Math.sin(this.mapAngle),a=a.clone(),a.rotate(h,l));this.isScreenAligned||(c+=this.mapAngle);if(0!==c){h=Math.cos(c);l=Math.sin(c);k[0].rotate(h,l);k[1].rotate(h,l);k[2].rotate(h,l);k[3].rotate(h,l);c=0;for(h=1;4>h;h++)k[h].x<k[c].x?c=h:k[h].x===k[c].x&&k[h].y<k[c].y&&(c=h);if(c){l=[];for(h=0;4>h;h++)l.push(k[(h+c)%4]);k=l}}if(d)for(c=0,h=k;c<h.length;c++)h[c].move(d[0],d[1]);this.obstacles.push(new t(a,k,f,g))};return g}();n.Footprint=m;var u=.5;m=function(){function g(){this._grid=[]}g.prototype.setAngle=
function(a){};g.prototype.reset=function(){this._grid=[]};g.prototype.add=function(a){var b=this._grid,e=0;for(a=a.obstacles;e<a.length;e++)for(var c=a[e],d=c.anchor,f=g._gridClamp(Math.min(c.left()+d.x,d.x)),q=g._gridClamp(Math.max(c.right()+d.x,d.x)),k=g._gridClamp(Math.min(c.top()+d.y,d.y)),d=g._gridClamp(Math.max(c.bottom()+d.y,d.y));k<=d;k++)for(var h=f;h<=q;h++){var l=b[16*k+h];l||(l=b[16*k+h]=[]);l.push(c)}};g.prototype.getMinZoom=function(a,b,e,c){if(0===a.obstacles.length)return r.C_INFINITY;
e=this._grid;c=0;for(a=a.obstacles;c<a.length;c++)for(var d=a[c],f=d.anchor,q=g._gridClamp(Math.min(d.left()+f.x,f.x)),k=g._gridClamp(Math.max(d.right()+f.x,f.x)),h=g._gridClamp(Math.min(d.top()+f.y,f.y)),f=g._gridClamp(Math.max(d.bottom()+f.y,f.y));h<=f;h++)for(var l=q;l<=k;l++){var m=e[16*h+l];if(m)for(var n=0;n<m.length;n++){var p=m[n];if(!(d.minzoom>=p.maxzoom||p.minzoom>=d.maxzoom)&&(b=g._calcPlacementZoom(d,p,b),2<=b))return r.C_INFINITY}}return 2>b?b:r.C_INFINITY};g._gridClamp=function(a){return r.clamp(a>>
9,-7,8)};g._calcPlacementZoom=function(a,b,e){var c=b.anchor.x-a.anchor.x;if(0===c&&(a.right()<b.left()||b.right()<a.left()))return e;var d=b.anchor.y-a.anchor.y;if(0===d&&(a.bottom()<b.top()||b.bottom()<a.top()))return e;var f=r.C_INFINITY;if(0!==c){var q=(0<c?a.right()-b.left():a.left()-b.right())/c;q<f&&(f=q);c=0<c?g._calcExtZoomX(a,b,q):g._calcExtZoomX(b,a,q);c<f&&(f=c)}0!==d&&(c=(0<d?a.bottom()-b.top():a.top()-b.bottom())/d,c<f&&(f=c),d=0<d?g._calcExtZoomY(a,b,c):g._calcExtZoomY(b,a,c),d<f&&
(f=d));if(f<a.minzoom||f<b.minzoom)return e;f=Math.min(f,a.maxzoom,b.maxzoom);f<e&&(f=e);return f};g._calcExtZoomX=function(a,b,e){var c,d,f;if(a.anchor.y+a.corners[2].y/e<b.anchor.y+b.corners[0].y/e){c=a.corners[2].x-a.corners[3].x;f=a.corners[2].y-a.corners[3].y;var g=b.corners[1].x-b.corners[0].x;d=b.corners[1].y-b.corners[0].y;0<=c*d-f*g?a.anchor.y+a.corners[3].y/e<b.anchor.y+b.corners[0].y/e?(e=a.corners[3],c=b.corners[0],d=b.corners[1],f=1):(e=b.corners[0],c=a.corners[3],d=a.corners[2],f=-1):
a.anchor.y+a.corners[2].y/e>b.anchor.y+b.corners[1].y/e?(e=a.corners[2],c=b.corners[0],d=b.corners[1],f=1):(e=b.corners[1],c=a.corners[3],d=a.corners[2],f=-1)}else c=a.corners[2].x-a.corners[1].x,f=a.corners[2].y-a.corners[1].y,g=b.corners[3].x-b.corners[0].x,d=b.corners[3].y-b.corners[0].y,0>c*d-f*g?a.anchor.y+a.corners[1].y/e>b.anchor.y+b.corners[0].y/e?(e=a.corners[1],c=b.corners[0],d=b.corners[3],f=1):(e=b.corners[0],c=a.corners[1],d=a.corners[2],f=-1):a.anchor.y+a.corners[2].y/e<b.anchor.y+b.corners[3].y/
e?(e=a.corners[2],c=b.corners[0],d=b.corners[3],f=1):(e=b.corners[3],c=a.corners[1],d=a.corners[2],f=-1);g=d.x-c.x;d=d.y-c.y;return f*((e.y-c.y)*g-(e.x-c.x)*d)/((a.anchor.x-b.anchor.x)*d-(a.anchor.y-b.anchor.y)*g)};g._calcExtZoomY=function(a,b,e){var c,d,f;if(a.anchor.x+a.corners[3].x/e<b.anchor.x+b.corners[1].x/e){c=a.corners[3].x-a.corners[2].x;f=a.corners[3].y-a.corners[2].y;var g=b.corners[0].x-b.corners[1].x;d=b.corners[0].y-b.corners[1].y;0>c*d-f*g?a.anchor.x+a.corners[2].x/e<b.anchor.x+b.corners[1].x/
e?(e=a.corners[2],c=b.corners[1],d=b.corners[0],f=1):(e=b.corners[1],c=a.corners[2],d=a.corners[3],f=-1):a.anchor.x+a.corners[3].x/e>b.anchor.x+b.corners[0].x/e?(e=a.corners[3],c=b.corners[1],d=b.corners[0],f=1):(e=b.corners[0],c=a.corners[2],d=a.corners[3],f=-1)}else c=a.corners[3].x-a.corners[0].x,f=a.corners[3].y-a.corners[0].y,g=b.corners[2].x-b.corners[1].x,d=b.corners[2].y-b.corners[1].y,0<c*d-f*g?a.anchor.x+a.corners[0].x/e>b.anchor.x+b.corners[1].x/e?(e=a.corners[0],c=b.corners[1],d=b.corners[2],
f=1):(e=b.corners[1],c=a.corners[0],d=a.corners[3],f=-1):a.anchor.x+a.corners[3].x/e<b.anchor.x+b.corners[2].x/e?(e=a.corners[3],c=b.corners[1],d=b.corners[2],f=1):(e=b.corners[2],c=a.corners[0],d=a.corners[3],f=-1);g=d.x-c.x;d=d.y-c.y;return f*((e.y-c.y)*g-(e.x-c.x)*d)/((a.anchor.x-b.anchor.x)*d-(a.anchor.y-b.anchor.y)*g)};return g}();n.ConflictEngine=m});
|
import React from 'react'
import { filter, get } from 'lodash'
import utils from '~/utils'
import Filter from '~/components/filter/Filter'
import InfiniteScroll from '~/components/infinite-scroll/InfiniteScroll'
import RepositoryCard from '~/components/repository-list/repository-card/RepositoryCard'
/**
* The RepositoryList object class.
*/
class RepositoryList extends React.Component {
// Initial state.
state = {
repos: this.props.repos,
filteredRepos: this.props.repos,
}
// Default props.
static defaultProps = {
repos: [],
}
/**
* Update the internal state when this component receive new repos prop.
* @param {Object} nextProps
*/
componentWillReceiveProps(nextProps) {
const currRepos = get(this.props, 'repos', [])
const nextRepos = get(nextProps, 'repos', [])
if (currRepos.length !== nextRepos.length) {
this.setState({
repos: nextRepos,
filteredRepos: nextRepos,
})
}
}
/**
* Render this component.
*/
render() {
const { filteredRepos } = this.state
return (
<div>
<Filter
placeholder="Filter repositories by name or author..."
onChange={ (value) => this.filterChanged(value) }
/>
<InfiniteScroll
items={ filteredRepos }
render={ (repo) => (
<RepositoryCard
key={ repo.id }
repo={ repo }
/>
) }
/>
</div>
)
}
/**
* Handle filter value changes.
* @param {String} value The new filter value.
*/
filterChanged(value) {
const { repos } = this.state
// Filter repos.
const query = utils.unicodeNormalize(value)
const matcher = new RegExp(utils.escapeRegExp(query), 'i')
const filteredRepos = filter(repos, (repo) => {
return matcher.test(repo.normalizedName) || matcher.test(repo.normalizedDescription) || matcher.test(repo.user.normalizedName)
})
// Update the state.
this.setState((state) => ({
filteredRepos,
}))
}
}
export default RepositoryList
|
module.exports = {
push: {
options: {
recursive: true,
src: '<%= vars.wplocal %>',
dest: '<%= vars.wpremote %>',
host: 'n72f3258732714@p3nlpaas001.shr.prod.phx3.secureserver.net',
delete: true,
exclude: [
'node_modules',
'.gitignore',
'grunt',
'.git',
'gruntfile.js',
'.DS_Store',
'_design'
],
ssh: true,
args: ['--verbose']
}
}
};
|
exports.seed = function(knex, Promise) {
return knex('users')
.del()
.then(function() {
// Inserts seed entries
return knex('users').insert([
{
id: 1,
first_name: 'Steve',
last_name: 'Morse',
email: 'steve@gmail.com',
hashed_password:
'$2a$10$Sc1JH2uOZ1Cv0t3hoWoc1OyWCdy6Q6BP07b8zWqjT2A2bBbZr6Ab6'
},
{
id: 2,
first_name: 'Steve',
last_name: 'Vaughan',
email: 'steve2@gmail.com',
hashed_password:
'$2a$10$ha5HzJWYkRcwQLhT9kHb.eZJ0sT26edJnHAcbpPrF5tMqo3w26Ux2'
}
]);
})
.then(() =>
knex.raw("SELECT setval('users_id_seq', (SELECT MAX(id) FROM users))")
);
};
|
"use strict";
let ImageVol = require('./ImageVol');
const DEFAULTS = {
// declare size of input
// output Vol is of size 128x128x4 here
input: {
type: 'input',
out_sx: 128,
out_sy: 128,
out_depth: 4
},
conv: [
// the first layer will perform convolution with 16 kernels, each of size 5x5.
// the input will be padded with 2 pixels on all sides to make the output Vol of the same size
// output Vol will thus be 128x128x16 at this point W2 = (W1 - sx + pad*2)/stride + 1
{
type: 'conv',
sx: 5, // width is (128 - 5 + 4) + 1 = 128
filters: 16,
stride: 1,
pad: 2,
activation:'relu'
},
// output Vol is of size 128x128x20 here
{
type: 'conv',
sx: 5,
filters: 20,
stride: 1,
pad: 2,
activation:'relu'
}
],
// output Vol is of size 16x16x16 here
pool: {
type: 'pool',
sx: 8,
stride: 2
},
// output Vol is of size 1x1x10 here
softmax: {
type: 'softmax',
num_classes: 10
},
// tweak this
trainer: {
method: 'adadelta',
l2_decay: 0.001,
batch_size: 10
}
};
var ConvNetJS = require("ConvNetJS");
class DigitReader {
constructor(options) {
if (!options) options = {};
this.net = new ConvNetJS.Net();
if (options.net) {
console.log('Using previously saved neural network');
this.net.fromJSON(options.net);
} else {
console.log('Creating fresh neural network');
let layerDefinitions = [];
layerDefinitions.push(DigitReader.mergeDefaults(options, 'input'));
layerDefinitions.push(DigitReader.mergeDefaults(options, 'conv', 0));
layerDefinitions.push(DigitReader.mergeDefaults(options, 'pool'));
layerDefinitions.push(DigitReader.mergeDefaults(options, 'conv', 1));
layerDefinitions.push(DigitReader.mergeDefaults(options, 'pool'));
// experiment here with adding more from the defaults.
// layerDefinitions.push(DigitReader.mergeDefaults(options, 'conv', 1));
// layerDefinitions.push(DigitReader.mergeDefaults(options, 'pool'));
// layerDefinitions.push(DigitReader.mergeDefaults(options, 'conv', 1));
// layerDefinitions.push(DigitReader.mergeDefaults(options, 'pool'));
layerDefinitions.push(DigitReader.mergeDefaults(options, 'softmax'));
this.net.makeLayers(layerDefinitions);
}
this.length = 10;
this.trainer = new ConvNetJS.SGDTrainer(this.net, DigitReader.mergeDefaults(options, 'trainer'));
}
train(image, fact) {
if (!image) throw new Error({message: "Missing Image"});
if (typeof fact === 'undefined') throw new Error({message: "Missing fact"});
if(typeof fact !== 'number') throw new Error({
message: "Expected fact to be a number, not a " + fact.class.name,
context: fact
});
if (fact < 0 || fact >= this.length) throw new Error({
message: "Fact must be between 0 and " + (this.length - 1),
context: fact
});
let imageVol = new ImageVol(image);
imageVol.toVol(function(vol) {
this.trainer.train(vol, fact);
}.bind(this));
}
predict(image, callback) {
let imageVol = new ImageVol(image);
imageVol.toVol(function(vol) {
let probabilities = this.net.forward(vol);
let guess = null;
let bestGuess = null;
for (let i = 0, l = this.length; i < l; i++) {
if (guess === null || probabilities.w[i] > guess) {
guess = probabilities.w[i];
bestGuess = i;
}
}
callback(bestGuess, probabilities.w[bestGuess]);
}.bind(this));
}
static option(key, options, label, iteration) {
if (!options || !options[label]) return null;
if (typeof iteration === 'number') {
return options[label][iteration][key];
}
return options[label][key];
}
static validate(label, iteration) {
if (!label || !DEFAULTS[label])
throw new Error({message: "Invalid label", context: label});
if (typeof iteration !== 'undefined') {
if (typeof iteration !== 'number')
throw new Error({message: "Iteration must be a number", context: iteration});
if (!DEFAULTS[label][iteration])
throw new Error({message: "Invalid iteration for " + label, context: iteration});
}
}
static cleanOptions(options, label, iteration) {
DigitReader.validate(label, iteration);
let newOptions = {};
let allowedKeys = Object.keys((typeof iteration === 'number') ? DEFAULTS[label][iteration] : DEFAULTS[label]);
allowedKeys.forEach(function(key) {
let opt = DigitReader.option(key, options, label, iteration);
if (opt) newOptions[key] = opt;
});
return newOptions;
}
static mergeDefaults(options, label, iteration) {
let newOptions = DigitReader.cleanOptions(options, label, iteration);
if (typeof iteration === 'number') {
Object.assign(newOptions, DEFAULTS[label][iteration], newOptions);
} else {
Object.assign(newOptions, DEFAULTS[label], newOptions);
}
return newOptions;
}
}
module.exports = DigitReader;
|
function StrUtils(stdlib, ffi, heap){
"use asm";
var buffer = new stdlib.Uint16Array(heap);
var log = ffi.log;
function strlen(){
var i = 0;
var length = 0;
while(buffer[i << 1 >> 1] | 0 != 0){
log((i | 0) >> 0);
log((buffer[i << 1 >> 1] | 0) >> 0 );
i = ((i + 1) | 0);
length = (length + 1) | 0;
}
return length | 0;
}
return {
strlen: strlen
};
}
function AsmText(){
this.initialize.apply(this, arguments);
}
AsmText.prototype = {
initialize: function(text){
this.text = text;
console.log(this.buffer);
this.util = StrUtils(window, {log: text => {
console.log(text);
}}, this.buffer);
},
get buffer(){
if(this._buffer == null){
this._buffer = new Uint16Array(new ArrayBuffer(0x10000));
this.text.split("").forEach((char, index) => {
this._buffer[index] = char.charCodeAt(0);
});
}
return this._buffer.buffer;
},
get uint16(){
return this._buffer;
},
get length(){
return this.util.strlen();
}
};
(function(){
function App(){
this.initialize.apply(this, arguments);
};
App.prototype = {
initialize: function(){
this.el = null;
},
render: function(){
if(this.el == null){
this._render();
}
return this.el;
},
_render: function(){
this.el = document.createElement("div");
const input = document.createElement("textarea");
const output = document.createElement("p");
const button = document.createElement("button");
button.textContent = "strlen";
this.el.appendChild(button);
this.el.appendChild(input);
this.el.appendChild(output);
button.addEventListener("click", event => {
const t = new AsmText(input.value);
console.log(t.text);
output.textContent = "length = " + t.length;
});
}
};
window.addEventListener("load", event =>{
const app = new App();
document.querySelector("#strutils").appendChild(app.render());
});
})();
|
import { merge, omit } from 'lodash'
export { account } from './account'
export { files } from './files'
export { projects } from './projects'
// Updates an entity cache in response to any action with response.entities.
export function entities (state = { users: {}, projects: {} }, action) {
if (action.response && action.response.entities) {
return merge({}, state, action.response.entities)
}
if (action.method === 'remove') {
console.debug('****************** state before:', state)
if (!state.entities[action.model.toLowerCase()]) throw new Error('Entity does not exist')
const stateWithoutEntity = omit(state[action.model.toLowerCase()], `${action.modelData[1]}/${action.modelData[0]}`)
console.debug('returning state:', stateWithoutEntity)
return stateWithoutEntity
}
return state
}
|
function editCustomer(router,connection){
var self=this;
self.handleRoutes(router,connection);
}
editCustomer.prototype.handleRoutes = function(router,connection){
router.post('/editCustomer',function(req,res){
var sessionCode = req.body.sessionCode;
var idCustomer = req.body.idCustomer;
var name = req.body.name;
var phone = req.body.phone;
var email = req.body.email;
var birthdate = req.body.birthdate;
var membershipId = req.body.membershipId;
if(sessionCode == null || sessionCode == undefined || sessionCode == ''){
res.json({"message":"err.. no param s_c received"});
}else{
if(idCustomer == null || idCustomer == undefined || idCustomer == ''){
res.json({"message":"err.. no param s_c received"});
}else{
if(name == null || name == undefined || name == ''){
res.json({"message":"err.. no param name received"});
}else{
if(phone == null || phone == undefined || phone == ''){
res.json({"message":"err.. no param name received"});
}else{
var q0 = "update `customer` set name='"+name+"',phone='"+phone+"'where id="+idCustomer;
connection.query(q0,function(err,rows){
if(err){
res.json({"message":"err.. error on updating cust 1st query"});
}else{
if(membershipId == null || membershipId == undefined || membershipId == '' ){
if(birthdate == null || birthdate == undefined || birthdate == ''){
if(email == null || email == undefined || email == ''){
res.json({"message":"success update customer non-member"});
}else{
var q1 = "update `customer` set email='"+email+"' where id="+idCustomer;
connection.query(q1,function(err,rows){
if(err){
res.json({"message":"err.. error on updating customer","q1":q1});
}else{
res.json({"message":"success updating customer"});
}
});
}
}else{
if(email == null || email == undefined || email == ''){
var q2 = "update `customer` set birthdate='"+birthdate+"' where id="+idCustomer;
connection.query(q2,function(err,rows){
if(err){
res.json({"message":"err.. error on updating customer","q2":q2});
}else{
res.json({"message":"success updating customer"});
}
});
}else{
var q3 = "update `customer` set email='"+email+"',birthdate='"+birthdate+"' where id="+idCustomer;
connection.query(q3,function(err,rows){
if(err){
res.json({"message":"err.. error on updating customer","q3":q3});
}else{
res.json({"message":"success updating customer"});
}
});
}
}
}else{
if(birthdate == null || birthdate == undefined || birthdate == ''){
if(email == null || email == undefined || email == ''){
var q4 = "update `customer` set membershipId="+membershipId+" where id="+idCustomer;
connection.query(q4,function(err,rows){
if(err){
res.json({"message":"err.. error on updating customer","q4":q4});
}else{
res.json({"message":"success updating customer"});
}
});
}else{
var q5 = "update `customer` set membershipId="+membershipId+",email='"+email+"' where id="+idCustomer;
connection.query(q5,function(err,rows){
if(err){
res.json({"message":"err.. error on updating customer","q5":q5});
}else{
res.json({"message":"success updating customer"});
}
});
}
}else{
if(email == null || email == undefined || email == ''){
var q6 = "update `customer` set membershipId="+membershipId+",birthdate='"+birthdate+"' where id="+idCustomer;
connection.query(q6,function(err,rows){
if(err){
res.json({"message":"err.. error on updating customer","q6":q6});
}else{
res.json({"message":"success updating customer"});
}
});
}else{
var q7 = "update `customer` set membershipId="+membershipId+",birthdate='"+birthdate+"',email='"+email+"' where id="+idCustomer;
connection.query(q7,function(err,rows){
if(err){
res.json({"message":"err.. error on updating customer","q7":q7});
}else{
res.json({"message":"success updating customer"});
}
});
}
}
}
}
});
}
}
}
}
});
}
module.exports = editCustomer;
|
const array = [1, 42, 7, 9, 13, 10, 20, 35, 45, -7, -3, 0, 4, -1, 15];
Array.prototype.find = function(isOk) {
const len = this.length;
for(let i = 0; i < len; i += 1) {
if(isOk(this[i], i, this)) {
return this[i];
}
}
}
Array.prototype.findIndex = function(isOk) {
const len = this.length;
for(let i = 0; i < len; i += 1) {
if(isOk(this[i], i, this)) {
return i;
}
}
return -1;
}
console.log(array.find(x => x % 2 === 0));
console.log(array.find(x => x % 2 === 1));
console.log(array.find(x => x > 10 && x < 20));
console.log(array.find(x => x === 45));
console.log(array.find(x => x === 46));
console.log(array.findIndex(x => x % 2 === 0));
console.log(array.findIndex(x => x % 2 === 1));
console.log(array.findIndex(x => x > 10 && x < 20));
console.log(array.findIndex(x => x === 45));
console.log(array.findIndex(x => x === 46));
|
module.exports = function resolve(vector) {
if (Array.isArray(vector.direction)) {
var dimensions = vector.direction.length + 1
var result = new Array(dimensions)
for (var dimension = 1; dimension <= dimensions; dimension++) {
var axis = vector.magnitude
for (var i = 1; i <= dimension; i++) {
if (i !== dimensions) {
if (i === dimension) {
axis *= Math.cos(vector.direction[i - 1])
} else {
axis *= Math.sin(vector.direction[i - 1])
}
}
}
result[dimension - 1] = axis
}
return result
} else {
return [
vector.magnitude * Math.cos(vector.direction),
vector.magnitude * Math.sin(vector.direction)
]
}
}
|
'use strict';
const reactions = require('./reactions.js');
class Rule {
constructor(expression, reaction) {
this.expression = expression;
this.reaction = reaction;
}
}
class Rules {
constructor() {
this.rules = [];
}
add(rule) {
this.rules.push(rule);
}
length() {
return this.rules.length;
}
}
function rulesFromJson(json) {
if (!json || !json.rules || json.rules.length <= 0) {
throw new Error('No rules found');
}
const rules = new Rules();
json.rules.map((entry) => {
if (entry.term && entry.reaction) {
rules.add(
new Rule(
new RegExp(entry.term, 'i'),
new reactions.ReactionDirectMessage(entry.reaction)
)
);
}
return entry;
});
if (rules.length() <= 0) {
throw new Error('No rules found');
}
return rules;
}
module.exports = {
rulesFromJson,
Rules,
Rule,
};
|
/* @flow */
import React from 'react'
export function withDOM<T>(cb: (el: Element) => T): T {
var div = document.createElement('div')
document.body.appendChild(div)
var result = cb(div)
document.body.removeChild(div)
return result
}
export function cleanHtml(html: string): string {
return html.replace(/ data\-reactid=".*?"/g, '')
}
export function renderToHtml(tree: ReactElement): string {
return withDOM(el => {
React.render(tree, el)
return cleanHtml(el.innerHTML)
})
}
type map = {[key: string]: any}
// Converts Object({...}) to null({...})
export function removeProto(source: map): map {
var result = Object.create(null)
var keys = Object.keys(source)
var i
for (i = 0; i < keys.length; i++) {
result[keys[i]] = source[keys[i]]
}
return result
}
|
var path = require('path');
var EventEmitterPrototype = require('events').EventEmitter.prototype;
var colors = require('colors');
var utils = require('./utils');
var extend = utils.extend;
var dateFormat = utils.dateFormat;
var pagerun = {};
pagerun.mode = 'product'; // default mode: product (product | test | debug)
pagerun.package = require('../package.json');
pagerun.version = pagerun.package.version;
var runConfigs ={};
var arrFilters = [];
var arrLogs = [];
var arrMessages = [];
var arrNpmPlugins = [];
// request map
var mapRequests = {};
// copy event function
pagerun.on = EventEmitterPrototype.on;
pagerun.emit = EventEmitterPrototype.emit;
// load plugin from core
var mapLoadedPlugins = {};
pagerun.loadPlugin = function(pluginName, bNpm){
if(mapLoadedPlugins[pluginName] !== true){
mapLoadedPlugins[pluginName] = true;
var modulesRoot = pagerun.modulesRoot || path.resolve('node_modules');
var plugin = bNpm ? require(path.resolve(modulesRoot, 'pagerun-'+pluginName)) : require('./plugins/'+pluginName);
var pluginEnv = {};
pluginEnv.config = function(defConfig){
return pagerun.getConfig(pluginName, defConfig);
};
pluginEnv.log = function(type, message){
return pagerun.log(pluginName, type, message);
};
pluginEnv.error = function(message){
return pagerun.message(pluginName, 'error', message);
};
pluginEnv.warn = function(message){
return pagerun.message(pluginName, 'warn', message);
};
pluginEnv.info = function(message){
return pagerun.message(pluginName, 'info', message);
};
plugin.call(pluginEnv, pagerun);
pagerun.log('pagerun', 'loadPlugin', pluginName + ' ('+(bNpm?'npm':'core')+')');
}
}
// load plugin from npm
pagerun.loadNpmPlugin = function(pluginName){
arrNpmPlugins.push(pluginName);
};
// set run config
pagerun.setConfig = function(configs){
var newConfig;
var oldConfig;
for(var name in configs){
oldConfig = runConfigs[name];
newConfig = configs[name];
if(typeof newConfig === 'object'){
newConfig = extend(oldConfig?oldConfig:{}, newConfig);
}
runConfigs[name] = newConfig;
}
};
// get filter config
pagerun.getConfig = function(name, defConfig){
var config = runConfigs[name];
if(typeof config === 'object'){
config = extend(defConfig?defConfig:{}, config?config:{});
}
else if(config === undefined){
config = defConfig?defConfig:'';
}
return config;
}
// add request map
pagerun.addRequestMap = function(path, data){
mapRequests[path] = data;
}
// check url matched
pagerun.isMatchUrl = function(url, arrChecks){
if(arrChecks !== undefined){
for(var i=0,c=arrChecks.length;i<c;i++){
if(isMatchUrl(url, arrChecks[i])){
return true;
}
}
}
else{
return true;
}
return false;
}
function isMatchUrl(url, check){
var bMatch = false,
regCheck = str2Reg(check);
if(regCheck !== undefined){
if(regCheck.test(url) === true){
bMatch = true;
}
}
else if(check.substr(0,1) === '!' && url === check.substr(1)){
bMatch = true;
}
else if(url.indexOf(check) === 0){
bMatch = true;
}
return bMatch;
}
function str2Reg(str){
var match = str.match(/^\/(.+)\/([i])?$/);
if(match !== null){
var reg;
try {
reg = RegExp(match[1], match[2]);
}
catch(ex) {}
if(reg !== undefined){
return reg;
}
}
}
// save log
pagerun.log = function(module, type, message){
message = message?message:'';
var dateString = dateFormat('yyyy-MM-dd hh:mm:ss');
arrLogs.push({
module: module,
type: type,
message: message,
time: new Date().getTime()
});
if(pagerun.mode !== 'product'){
console.log('[' + dateString.green + ']: ',module,type,message);
}
};
// save result
pagerun.message = function(module, type, message){
arrMessages.push({
type: type,
module: module,
message: message,
time: new Date().getTime()
});
}
// run
pagerun.run = function(done){
// load core plugins
pagerun.loadPlugin('pageproxy');
pagerun.loadPlugin('hosts');
pagerun.loadPlugin('webdriver');
pagerun.loadPlugin('inject');
pagerun.loadPlugin('bridge');
// load npm plugins
arrNpmPlugins.forEach(function(pluginName){
pagerun.loadPlugin(pluginName, true);
});
var runState = false;
pagerun.on('webdriverEnd', function(bSuccess){
runState = bSuccess
});
pagerun.on('proxyStart', function(msg){
var proxy = msg.proxy;
proxy.addFilter(function(httpData, next, end){
if(httpData.type === 'request' && httpData.hostname === 'pagerun'){
var responseData = mapRequests[httpData.hostname + httpData.path];
if(responseData !== undefined){
httpData.responseCode = responseData.responseCode;
httpData.responseHeaders = responseData.responseHeaders;
httpData.responseData = responseData.responseData;
return end();
}
}
next();
});
});
pagerun.on('proxyEnd', function(){
pagerun.log('pagerun','end');
pagerun.emit('runEnd');
done({
success: runState,
messages: arrMessages,
logs: arrLogs
});
});
pagerun.log('pagerun','start');
pagerun.emit('runStart');
};
pagerun.localIp = utils.localIp();
module.exports = pagerun;
|
/* Set the defaults for DataTables initialisation */
$.extend( true, $.fn.dataTable.defaults, {
"sDom": "<'row'<'col-sm-12'<'pull-right'f><'pull-left'l>r<'clearfix'>>>t<'row'<'col-sm-12'<'pull-left'i><'pull-right'p><'clearfix'>>>",
"sPaginationType": "bs_normal",
"oLanguage": {
"sLengthMenu": "Show _MENU_ Rows",
"sSearch": ""
}
} );
/* Default class modification */
$.extend( $.fn.dataTableExt.oStdClasses, {
"sWrapper": "dataTables_wrapper form-inline"
} );
/* API method to get paging information */
$.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings )
{
return {
"iStart": oSettings._iDisplayStart,
"iEnd": oSettings.fnDisplayEnd(),
"iLength": oSettings._iDisplayLength,
"iTotal": oSettings.fnRecordsTotal(),
"iFilteredTotal": oSettings.fnRecordsDisplay(),
"iPage": oSettings._iDisplayLength === -1 ?
0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ),
"iTotalPages": oSettings._iDisplayLength === -1 ?
0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength )
};
};
/* Bootstrap style pagination control */
$.extend( $.fn.dataTableExt.oPagination, {
"bs_normal": {
"fnInit": function( oSettings, nPaging, fnDraw ) {
var oLang = oSettings.oLanguage.oPaginate;
var fnClickHandler = function ( e ) {
e.preventDefault();
if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) {
fnDraw( oSettings );
}
};
$(nPaging).append(
'<ul class="pagination">'+
'<li class="prev disabled"><a href="#"><span class="glyphicon glyphicon-chevron-left"></span> '+oLang.sPrevious+'</a></li>'+
'<li class="next disabled"><a href="#">'+oLang.sNext+' <span class="glyphicon glyphicon-chevron-right"></span></a></li>'+
'</ul>'
);
var els = $('a', nPaging);
$(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler );
$(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler );
},
"fnUpdate": function ( oSettings, fnDraw ) {
var iListLength = 5;
var oPaging = oSettings.oInstance.fnPagingInfo();
var an = oSettings.aanFeatures.p;
var i, ien, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2);
if ( oPaging.iTotalPages < iListLength) {
iStart = 1;
iEnd = oPaging.iTotalPages;
}
else if ( oPaging.iPage <= iHalf ) {
iStart = 1;
iEnd = iListLength;
} else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) {
iStart = oPaging.iTotalPages - iListLength + 1;
iEnd = oPaging.iTotalPages;
} else {
iStart = oPaging.iPage - iHalf + 1;
iEnd = iStart + iListLength - 1;
}
for ( i=0, ien=an.length ; i<ien ; i++ ) {
$('li:gt(0)', an[i]).filter(':not(:last)').remove();
for ( j=iStart ; j<=iEnd ; j++ ) {
sClass = (j==oPaging.iPage+1) ? 'class="active"' : '';
$('<li '+sClass+'><a href="#">'+j+'</a></li>')
.insertBefore( $('li:last', an[i])[0] )
.bind('click', function (e) {
e.preventDefault();
if ( oSettings.oApi._fnPageChange(oSettings, parseInt($('a', this).text(),10)-1) ) {
fnDraw( oSettings );
}
} );
}
if ( oPaging.iPage === 0 ) {
$('li:first', an[i]).addClass('disabled');
} else {
$('li:first', an[i]).removeClass('disabled');
}
if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) {
$('li:last', an[i]).addClass('disabled');
} else {
$('li:last', an[i]).removeClass('disabled');
}
}
}
},
"bs_two_button": {
"fnInit": function ( oSettings, nPaging, fnCallbackDraw )
{
var oLang = oSettings.oLanguage.oPaginate;
var oClasses = oSettings.oClasses;
var fnClickHandler = function ( e ) {
if ( oSettings.oApi._fnPageChange( oSettings, e.data.action ) )
{
fnCallbackDraw( oSettings );
}
};
var sAppend = '<ul class="pagination">'+
'<li class="prev"><a href="#" class="'+oSettings.oClasses.sPagePrevDisabled+'" tabindex="'+oSettings.iTabIndex+'" role="button"><span class="glyphicon glyphicon-chevron-left"></span> '+oLang.sPrevious+'</a></li>'+
'<li class="next"><a href="#" class="'+oSettings.oClasses.sPageNextDisabled+'" tabindex="'+oSettings.iTabIndex+'" role="button">'+oLang.sNext+' <span class="glyphicon glyphicon-chevron-right"></span></a></li>'+
'</ul>';
$(nPaging).append( sAppend );
var els = $('a', nPaging);
var nPrevious = els[0],
nNext = els[1];
oSettings.oApi._fnBindAction( nPrevious, {action: "previous"}, fnClickHandler );
oSettings.oApi._fnBindAction( nNext, {action: "next"}, fnClickHandler );
if ( !oSettings.aanFeatures.p )
{
nPaging.id = oSettings.sTableId+'_paginate';
nPrevious.id = oSettings.sTableId+'_previous';
nNext.id = oSettings.sTableId+'_next';
nPrevious.setAttribute('aria-controls', oSettings.sTableId);
nNext.setAttribute('aria-controls', oSettings.sTableId);
}
},
"fnUpdate": function ( oSettings, fnCallbackDraw )
{
if ( !oSettings.aanFeatures.p )
{
return;
}
var oPaging = oSettings.oInstance.fnPagingInfo();
var oClasses = oSettings.oClasses;
var an = oSettings.aanFeatures.p;
var nNode;
for ( var i=0, iLen=an.length ; i<iLen ; i++ )
{
if ( oPaging.iPage === 0 ) {
$('li:first', an[i]).addClass('disabled');
} else {
$('li:first', an[i]).removeClass('disabled');
}
if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) {
$('li:last', an[i]).addClass('disabled');
} else {
$('li:last', an[i]).removeClass('disabled');
}
}
}
},
"bs_four_button": {
"fnInit": function ( oSettings, nPaging, fnCallbackDraw )
{
var oLang = oSettings.oLanguage.oPaginate;
var oClasses = oSettings.oClasses;
var fnClickHandler = function ( e ) {
e.preventDefault()
if ( oSettings.oApi._fnPageChange( oSettings, e.data.action ) )
{
fnCallbackDraw( oSettings );
}
};
$(nPaging).append(
'<ul class="pagination">'+
'<li class="disabled"><a href="#" tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButton+" "+oClasses.sPageFirst+'"><span class="glyphicon glyphicon-backward"></span> '+oLang.sFirst+'</a></li>'+
'<li class="disabled"><a href="#" tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButton+" "+oClasses.sPagePrevious+'"><span class="glyphicon glyphicon-chevron-left"></span> '+oLang.sPrevious+'</a></li>'+
'<li><a href="#" tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButton+" "+oClasses.sPageNext+'">'+oLang.sNext+' <span class="glyphicon glyphicon-chevron-right"></span></a></li>'+
'<li><a href="#" tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButton+" "+oClasses.sPageLast+'">'+oLang.sLast+' <span class="glyphicon glyphicon-forward"></span></a></li>'+
'</ul>'
);
var els = $('a', nPaging);
var nFirst = els[0],
nPrev = els[1],
nNext = els[2],
nLast = els[3];
oSettings.oApi._fnBindAction( nFirst, {action: "first"}, fnClickHandler );
oSettings.oApi._fnBindAction( nPrev, {action: "previous"}, fnClickHandler );
oSettings.oApi._fnBindAction( nNext, {action: "next"}, fnClickHandler );
oSettings.oApi._fnBindAction( nLast, {action: "last"}, fnClickHandler );
if ( !oSettings.aanFeatures.p )
{
nPaging.id = oSettings.sTableId+'_paginate';
nFirst.id =oSettings.sTableId+'_first';
nPrev.id =oSettings.sTableId+'_previous';
nNext.id =oSettings.sTableId+'_next';
nLast.id =oSettings.sTableId+'_last';
}
},
"fnUpdate": function ( oSettings, fnCallbackDraw )
{
if ( !oSettings.aanFeatures.p )
{
return;
}
var oPaging = oSettings.oInstance.fnPagingInfo();
var oClasses = oSettings.oClasses;
var an = oSettings.aanFeatures.p;
var nNode;
for ( var i=0, iLen=an.length ; i<iLen ; i++ )
{
if ( oPaging.iPage === 0 ) {
$('li:eq(0)', an[i]).addClass('disabled');
$('li:eq(1)', an[i]).addClass('disabled');
} else {
$('li:eq(0)', an[i]).removeClass('disabled');
$('li:eq(1)', an[i]).removeClass('disabled');
}
if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) {
$('li:eq(2)', an[i]).addClass('disabled');
$('li:eq(3)', an[i]).addClass('disabled');
} else {
$('li:eq(2)', an[i]).removeClass('disabled');
$('li:eq(3)', an[i]).removeClass('disabled');
}
}
}
},
"bs_full": {
"fnInit": function ( oSettings, nPaging, fnCallbackDraw )
{
var oLang = oSettings.oLanguage.oPaginate;
var oClasses = oSettings.oClasses;
var fnClickHandler = function ( e ) {
if ( oSettings.oApi._fnPageChange( oSettings, e.data.action ) )
{
fnCallbackDraw( oSettings );
}
};
$(nPaging).append(
'<ul class="pagination">'+
'<li class="disabled"><a href="#" tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButton+" "+oClasses.sPageFirst+'">'+oLang.sFirst+'</a></li>'+
'<li class="disabled"><a href="#" tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButton+" "+oClasses.sPagePrevious+'">'+oLang.sPrevious+'</a></li>'+
'<li><a href="#" tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButton+" "+oClasses.sPageNext+'">'+oLang.sNext+'</a></li>'+
'<li><a href="#" tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButton+" "+oClasses.sPageLast+'">'+oLang.sLast+'</a></li>'+
'</ul>'
);
var els = $('a', nPaging);
var nFirst = els[0],
nPrev = els[1],
nNext = els[2],
nLast = els[3];
oSettings.oApi._fnBindAction( nFirst, {action: "first"}, fnClickHandler );
oSettings.oApi._fnBindAction( nPrev, {action: "previous"}, fnClickHandler );
oSettings.oApi._fnBindAction( nNext, {action: "next"}, fnClickHandler );
oSettings.oApi._fnBindAction( nLast, {action: "last"}, fnClickHandler );
if ( !oSettings.aanFeatures.p )
{
nPaging.id = oSettings.sTableId+'_paginate';
nFirst.id =oSettings.sTableId+'_first';
nPrev.id =oSettings.sTableId+'_previous';
nNext.id =oSettings.sTableId+'_next';
nLast.id =oSettings.sTableId+'_last';
}
},
"fnUpdate": function ( oSettings, fnCallbackDraw )
{
if ( !oSettings.aanFeatures.p )
{
return;
}
var oPaging = oSettings.oInstance.fnPagingInfo();
var iPageCount = $.fn.dataTableExt.oPagination.iFullNumbersShowPages;
var iPageCountHalf = Math.floor(iPageCount / 2);
var iPages = Math.ceil((oSettings.fnRecordsDisplay()) / oSettings._iDisplayLength);
var iCurrentPage = Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength) + 1;
var sList = "";
var iStartButton, iEndButton, i, iLen;
var oClasses = oSettings.oClasses;
var anButtons, anStatic, nPaginateList, nNode;
var an = oSettings.aanFeatures.p;
var fnBind = function (j) {
oSettings.oApi._fnBindAction( this, {"page": j+iStartButton-1}, function(e) {
if ( oSettings.oApi._fnPageChange( oSettings, e.data.page ) ) {
fnCallbackDraw( oSettings );
}
e.preventDefault();
} );
};
if ( oSettings._iDisplayLength === -1 )
{
iStartButton = 1;
iEndButton = 1;
iCurrentPage = 1;
}
else if (iPages < iPageCount)
{
iStartButton = 1;
iEndButton = iPages;
}
else if (iCurrentPage <= iPageCountHalf)
{
iStartButton = 1;
iEndButton = iPageCount;
}
else if (iCurrentPage >= (iPages - iPageCountHalf))
{
iStartButton = iPages - iPageCount + 1;
iEndButton = iPages;
}
else
{
iStartButton = iCurrentPage - Math.ceil(iPageCount / 2) + 1;
iEndButton = iStartButton + iPageCount - 1;
}
for ( i=iStartButton ; i<=iEndButton ; i++ )
{
sList += (iCurrentPage !== i) ?
'<li><a tabindex="'+oSettings.iTabIndex+'">'+oSettings.fnFormatNumber(i)+'</a></li>' :
'<li class="active"><a tabindex="'+oSettings.iTabIndex+'">'+oSettings.fnFormatNumber(i)+'</a></li>';
}
for ( i=0, iLen=an.length ; i<iLen ; i++ )
{
nNode = an[i];
if ( !nNode.hasChildNodes() )
{
continue;
}
$('li:gt(1)', an[i]).filter(':not(li:eq(-2))').filter(':not(li:eq(-1))').remove();
if ( oPaging.iPage === 0 ) {
$('li:eq(0)', an[i]).addClass('disabled');
$('li:eq(1)', an[i]).addClass('disabled');
} else {
$('li:eq(0)', an[i]).removeClass('disabled');
$('li:eq(1)', an[i]).removeClass('disabled');
}
if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) {
$('li:eq(-1)', an[i]).addClass('disabled');
$('li:eq(-2)', an[i]).addClass('disabled');
} else {
$('li:eq(-1)', an[i]).removeClass('disabled');
$('li:eq(-2)', an[i]).removeClass('disabled');
}
$(sList)
.insertBefore('li:eq(-2)', an[i])
.bind('click', function (e) {
e.preventDefault();
if ( oSettings.oApi._fnPageChange(oSettings, parseInt($('a', this).text(),10)-1) ) {
fnCallbackDraw( oSettings );
}
});
}
}
}
} );
/*
* TableTools Bootstrap compatibility
* Required TableTools 2.1+
*/
if ( $.fn.DataTable.TableTools ) {
// Set the classes that TableTools uses to something suitable for Bootstrap
$.extend( true, $.fn.DataTable.TableTools.classes, {
"container": "DTTT btn-group",
"buttons": {
"normal": "btn",
"disabled": "disabled"
},
"collection": {
"container": "DTTT_dropdown dropdown-menu",
"buttons": {
"normal": "",
"disabled": "disabled"
}
},
"print": {
"info": "DTTT_print_info modal"
},
"select": {
"row": "active"
}
} );
// Have the collection use a bootstrap compatible dropdown
$.extend( true, $.fn.DataTable.TableTools.DEFAULTS.oTags, {
"collection": {
"container": "ul",
"button": "li",
"liner": "a"
}
} );
}
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.fetchPushCertificates = exports.ensureAppId = exports.fetchAppleCertificates = exports.validateCredentialsForPlatform = exports.removeCredentialsForPlatform = exports.updateCredentialsForPlatform = exports.getCredentialsForPlatform = exports.credentialsExistForPlatformAsync = undefined;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
let credentialsExistForPlatformAsync = exports.credentialsExistForPlatformAsync = (() => {
var _ref = _asyncToGenerator(function* (metadata) {
return fetchCredentials(metadata, false);
});
return function credentialsExistForPlatformAsync(_x) {
return _ref.apply(this, arguments);
};
})();
let getCredentialsForPlatform = exports.getCredentialsForPlatform = (() => {
var _ref2 = _asyncToGenerator(function* (metadata) {
return fetchCredentials(metadata, true);
});
return function getCredentialsForPlatform(_x2) {
return _ref2.apply(this, arguments);
};
})();
let fetchCredentials = (() => {
var _ref3 = _asyncToGenerator(function* ({ username, experienceName, bundleIdentifier, platform }, decrypt) {
// this doesn't hit our mac rpc channel, so it needs significantly less debugging
const {
err,
credentials
} = yield (_Api || _load_Api()).default.callMethodAsync('getCredentials', [], 'post', {
username,
experienceName,
bundleIdentifier,
platform,
decrypt
});
if (err) {
throw new Error('Error fetching credentials.');
}
return credentials;
});
return function fetchCredentials(_x3, _x4) {
return _ref3.apply(this, arguments);
};
})();
let updateCredentialsForPlatform = exports.updateCredentialsForPlatform = (() => {
var _ref4 = _asyncToGenerator(function* (platform, newCredentials, metadata) {
// this doesn't go through the mac rpc, no request id needed
const {
err,
credentials
} = yield (_Api || _load_Api()).default.callMethodAsync('updateCredentials', [], 'post', _extends({
credentials: newCredentials,
platform
}, metadata));
if (err || !credentials) {
throw new Error('Error updating credentials.');
}
return;
});
return function updateCredentialsForPlatform(_x5, _x6, _x7) {
return _ref4.apply(this, arguments);
};
})();
let removeCredentialsForPlatform = exports.removeCredentialsForPlatform = (() => {
var _ref5 = _asyncToGenerator(function* (platform, metadata) {
// doesn't go through mac rpc, no request id needed
const { err } = yield (_Api || _load_Api()).default.callMethodAsync('deleteCredentials', [], 'post', _extends({
platform
}, metadata));
if (err) {
throw new Error('Error deleting credentials.');
}
return;
});
return function removeCredentialsForPlatform(_x8, _x9) {
return _ref5.apply(this, arguments);
};
})();
let validateCredentialsForPlatform = exports.validateCredentialsForPlatform = (() => {
var _ref6 = _asyncToGenerator(function* (platform, validationType, credentials, metadata) {
const {
requestId,
isValid,
error,
errorCode,
errorMessage
} = yield (_Api || _load_Api()).default.callMethodAsync('validateCredentials', [], 'post', _extends({
credentials,
platform,
validationType
}, metadata));
if (!isValid || error) {
throw new (_XDLError || _load_XDLError()).default(errorCode, `Unable to validate credentials. Request ID ${requestId}, message: ${errorMessage}`);
}
return;
});
return function validateCredentialsForPlatform(_x10, _x11, _x12, _x13) {
return _ref6.apply(this, arguments);
};
})();
let fetchAppleCertificates = exports.fetchAppleCertificates = (() => {
var _ref7 = _asyncToGenerator(function* (metadata) {
const {
requestId,
err,
success,
error,
errorCode,
errorMessage
} = yield (_Api || _load_Api()).default.callMethodAsync('fetchAppleCertificates', [], 'post', _extends({}, metadata));
if (err || !success || error) {
throw new (_XDLError || _load_XDLError()).default(errorCode, `Unable to fetch distribution certificate. Request ID ${requestId}, message: ${errorMessage}`);
}
return success;
});
return function fetchAppleCertificates(_x14) {
return _ref7.apply(this, arguments);
};
})();
let ensureAppId = exports.ensureAppId = (() => {
var _ref8 = _asyncToGenerator(function* (metadata) {
const {
requestId,
err,
success,
errorCode,
errorMessage
} = yield (_Api || _load_Api()).default.callMethodAsync('ensureAppId', [], 'post', _extends({}, metadata));
if (err || !success) {
throw new (_XDLError || _load_XDLError()).default(errorCode, `Unable to create app id. Request ID ${requestId}, message: ${errorMessage}`);
}
return success;
});
return function ensureAppId(_x15) {
return _ref8.apply(this, arguments);
};
})();
let fetchPushCertificates = exports.fetchPushCertificates = (() => {
var _ref9 = _asyncToGenerator(function* (metadata) {
const result = yield (_Api || _load_Api()).default.callMethodAsync('fetchPushCertificates', [], 'post', _extends({}, metadata));
if (result.err || !result.success) {
throw new (_XDLError || _load_XDLError()).default(result.errorCode, `Unable to fetch push certificate. Request ID ${result.requestId}, message: ${result.errorMessage}`);
}
return result.success;
});
return function fetchPushCertificates(_x16) {
return _ref9.apply(this, arguments);
};
})();
var _Api;
function _load_Api() {
return _Api = _interopRequireDefault(require('./Api'));
}
var _XDLError;
function _load_XDLError() {
return _XDLError = _interopRequireDefault(require('./XDLError'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
//# sourceMappingURL=__sourcemaps__/Credentials.js.map
|
var test = require('tape');
var sinon = require('sinon');
var consts = require('../src/constants');
var playerSync = require('../src/playerSync/controller');
var THREE = require('three');
var testId = 'id1';
var testId2 = 'id2';
var initialPosition = consts.playerSync.AVATAR_INITIAL_POSITION;
var initialPositionVector = new THREE.Vector3();
initialPositionVector.set(initialPosition[0], initialPosition[1], initialPosition[2]);
var slightlyMovedVector = new THREE.Vector3();
slightlyMovedVector.set(initialPosition[0] + consts.playerSync.ROUGH_MOVEMENT_THRESHOLD / 10, initialPosition[1], initialPosition[2]);
var brutallyMovedVector = new THREE.Vector3();
brutallyMovedVector.set(initialPosition[0], initialPosition[1] + consts.playerSync.ROUGH_MOVEMENT_THRESHOLD * 1000, initialPosition[2]);
var initialRotationXY = {
x: 0,
y: 0
};
var setup = function() {
playerSync.onLeave(testId, function() {});
playerSync.onLeave(testId2, function() {});
};
test('PlayerSyncController::onJoin', function(t) {
setup();
var broadcast = sinon.spy();
playerSync.onJoin(testId, broadcast);
t.ok(broadcast.calledWith(testId), 'should call broadcast with id passed');
playerSync.sendUpdates(function(update) {
var playerInfo = update.positions[testId];
t.deepEqual(playerInfo.position, initialPositionVector, 'position should be equal to initial as defined in consts');
t.deepEqual(playerInfo.rotation, initialRotationXY, 'rotation should be equal to zero');
t.end();
});
});
test('PlayerSyncController::onLeave', function(t) {
setup();
var broadcast = sinon.spy();
playerSync.onJoin(testId, function() {});
playerSync.onJoin(testId2, function() {});
playerSync.onLeave(testId, broadcast);
t.ok(broadcast.calledWith(testId), 'should call broadcast with id passed');
playerSync.sendUpdates(function(update) {
var playerInfo = update.positions[testId];
t.ok(!playerInfo, 'there should be no info for a player that left');
t.end();
});
});
test('PlayerSyncController::sendUpdates', function(t) {
setup();
var broadcast = sinon.spy();
playerSync.sendUpdates(broadcast);
t.ok(!broadcast.called, 'doesnt call callback if there are no logged users');
playerSync.onJoin(testId, function() {});
playerSync.onJoin(testId2, function() {});
var now = new Date();
playerSync.sendUpdates(function(update) {
t.pass('calls callback if there is at least one logged user');
t.equal(Object.keys(update.positions).length, 2, 'contains information of all logged users');
t.deepEqual(update.date, now, 'date should be now');
t.end();
});
});
test('PlayerSyncController::onState when movement is normal', function(t) {
setup();
playerSync.onJoin(testId, function() {});
var state = {
position: slightlyMovedVector,
rotation: new THREE.Vector3(1, 2)
};
playerSync.onState(testId, state);
playerSync.sendUpdates(function(update) {
var playerInfo = update.positions[testId];
t.deepEqual(playerInfo.rotation, {x: 1, y: 2}, 'should alter rotation');
t.deepEqual(playerInfo.position, state.position, 'should alter position if the movement is not too rough');
t.end();
});
});
test('PlayerSyncController::onState when movement is rough', function(t) {
setup();
playerSync.onJoin(testId, function() {});
var state = {
position: brutallyMovedVector,
rotation: new THREE.Vector3()
};
playerSync.onState(testId, state);
playerSync.sendUpdates(function(update) {
var lerpedYPosition = initialPosition[1] + (consts.playerSync.ROUGH_MOVEMENT_THRESHOLD * 1000 * consts.playerSync.LERP_PERCENT);
var playerInfo = update.positions[testId];
t.deepEqual(playerInfo.rotation, {x: 0, y: 0}, 'should alter rotation');
t.deepEqual(playerInfo.position, {x: state.position.x, y: lerpedYPosition, z: state.position.z}, 'should lerp position vector');
t.end();
});
});
|
import React from "react"
import Header from "../components/Header"
import Button from "../components/Button"
import { Div, P, Span } from "../components/Base"
import Img from "../images/Hangout"
import Layout from "../components/Layout"
export default function Meetings() {
return (
<Layout
pageTitle="Meetings"
description="Want to come join in on the fun at our next meetup? Visit the link below to find out when we will be having our next event."
>
<Div
maxWidth="1200px"
flexd
flexWrap="wrap"
mt={12}
mx="auto"
mb={24}
jc="space-around"
ai="center"
>
<Span p={[4]} width={[1, 1, 1 / 2]} maxWidth="400px">
<Img />
</Span>
<Div p={[8, 8, 4]} pb={[4, 0]} width={[1, 1, 1 / 2]} ff="sans.0">
<Header type={1} fs={["2xl", "3xl"]} color="grey8">
Next Meetup Event
</Header>
<P fs="lg" color="grey8" lh="normal">
Want to come join in on the fun at our next meetup? Visit the link
below to find out when we will be having our next event.
</P>
<Span>
<Button
as="a"
href="https://www.meetup.com/TulsaJS/"
target="_blank"
rel="nofollow"
type="primary"
small
>
Meetup Page
</Button>
</Span>
</Div>
</Div>
</Layout>
)
}
|
import React from 'react'
export default React.createClass ({
render() {
return (
<span>
<h2> {this.props.name} </h2>
</span>
)
}
})
|
"use strict";
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
/*
* The UTC datetime that the user account was created on Twitter.
*
* Example: "created_at": "Mon Nov 29 21:18:15 +0000 2010"
*/
created_at: String,
/*
* When true, indicates that the user has not altered the theme or background of their user profile.
*/
default_profile: Boolean,
/*
* When true, indicates that the user has not uploaded their own avatar and
* a default egg avatar is used instead.
*/
default_profile_image: Boolean,
/*
* Nullable. The user-defined UTF-8 string describing their account
*/
description: String,
/*
* The number of tweets this user has favorited in the account’s lifetime.
* British spelling used in the field name for historical reasons.
*/
favourites_count: Number,
/*
* The number of followers this account currently has.
* Under certain conditions of duress, this field will temporarily indicate “0.”
*/
followers_count: Number,
/*
* The number of users this account is following (AKA their “followings”).
* Under certain conditions of duress, this field will temporarily indicate “0.”
*/
friends_count: Number,
/*
* The string representation of the unique identifier for this User.
* Implementations should use this rather than the large, possibly un-consumable integer in id.
*/
id_str: {
type: String,
index: {
unique: true,
sparse: true
},
lowercase: true,
trim: true,
default: ''
},
/*
* The BCP 47 code for the user’s self-declared user interface language.
* May or may not have anything to do with the content of their Tweets.
*/
lang: String,
/*
* The number of public lists that this user is a member of.
*/
listed_count: Number,
/*
* Nullable. The user-defined location for this account’s profile.
* Not necessarily a location nor parseable.
* This field will occasionally be fuzzily interpreted by the Search service.
*
* Example: "location": "San Francisco, CA"
*/
location: String,
/*
* The name of the user, as they’ve defined it. Not necessarily a person’s name.
* Typically capped at 20 characters, but subject to change.
*/
name: String,
/*
* A HTTPS-based URL pointing to the background image the user has uploaded for their profile.
*/
profile_background_image_url_https: String,
/*
* The HTTPS-based URL pointing to the standard web representation of the user’s uploaded profile banner.
* By adding a final path element of the URL, you can obtain different image sizes optimized
* for specific displays. In the future, an API method will be provided to serve these URLs
* so that you need not modify the original URL. For size variations, please see User Profile Images
* and Banners.
*
* Example: "profile_banner_url": "https://si0.twimg.com/profile_banners/819797/1348102824"
*/
profile_banner_url: String,
/*
* A HTTPS-based URL pointing to the user’s avatar image.
*/
profile_image_url_https: String,
/*
* The screen name, handle, or alias that this user identifies themselves with.
* screen_names are unique but subject to change. Use id_str as a user identifier whenever possible.
* Typically a maximum of 15 characters long, but some historical accounts may exist with longer names.
*/
screen_name: String,
/*
* The number of tweets (including retweets) issued by the user.
*/
statuses_count: Number,
/*
* Nullable. A string describing the Time Zone this user declares themselves within.
*
* Example: "time_zone":"Pacific Time (US & Canada)"
*/
time_zone: String,
/*
* Nullable. A URL provided by the user in association with their profile.
*/
url: String,
/*
* When true, indicates that the user has a verified account. See Verified Accounts.
*/
verified: Boolean,
/*
* When present, indicates a textual representation of the two-letter country codes this user is withheld from.
*/
withheld_in_countries: String
});
module.exports = mongoose.model('User', userSchema);
|
'use strict';
module.exports = {
app: {
title: 'FrogBan',
description: 'A KanBan system for FogBugz using MeanJS',
keywords: 'KanBan, FogBugz, MeanJS'
},
port: process.env.PORT || 3000,
templateEngine: 'swig',
sessionSecret: 'MEAN',
sessionCollection: 'sessions',
assets: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.css',
'public/lib/bootstrap/dist/css/bootstrap-theme.css',
],
js: [
'public/lib/angular/angular.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-cookies/angular-cookies.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-touch/angular-touch.js',
'public/lib/angular-sanitize/angular-sanitize.js',
'public/lib/angular-ui-router/release/angular-ui-router.js',
'public/lib/angular-ui-utils/ui-utils.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.js'
]
},
css: [
'public/modules/**/css/*.css'
],
js: [
'public/config.js',
'public/application.js',
'public/modules/*/*.js',
'public/modules/*/*[!tests]*/*.js'
],
tests: [
'public/lib/angular-mocks/angular-mocks.js',
'public/modules/*/tests/*.js'
]
}
};
|
(function (ang) {
var app = ang.module('app');
app.config(function ($resourcesProvider, $stateProvider, $urlRouterProvider) {
// Resources
$resourcesProvider.init({
resources: {
Users: {
route: '/api/v1/users/:userId?:query'
},
Logout: {
route: '/auth/v1/logout'
}
}
});
// Router
$urlRouterProvider.otherwise("/");
$stateProvider
.state('users', {
url: '/users',
template: '<div class="cover" ui-view></div>'
})
.state('users.registered', {
url: '/registered',
templateUrl: '/front/modules/console-seed/dev/users/registered.html',
controller: 'usersRegisteredController'
})
});
})(angular);
|
import React, { Component } from 'react';
import './App.css';
import Articles from './components/Articles';
class App extends Component {
constructor(props) {
super(props)
this.state = {sortOrder: "VOTES"}
}
handleTopClick = () => {
this.setState({sortOrder: "VOTES"})
}
handleNewestClick = () => {
this.setState({sortOrder: "DATE"})
}
render() {
const { articles } = this.props;
const { sortOrder } = this.state;
return (
<div className="App">
<div className="navigation">
<button data-testid="top-link" onClick={this.handleTopClick}>Top</button>
<button data-testid="newest-link" onClick={this.handleNewestClick}>Newest</button>
</div>
<Articles articles={articles} sortOrder={sortOrder} />
</div>
);
}
}
export default App;
|
'use strict';
const SwiftTransformStream = require('swift-transform').Transform;
const pTry = require('p-try');
class IteratorCallerStream extends SwiftTransformStream {
constructor(iterator, concurrency) {
super({ objectMode: true, concurrency });
this._iterator = iterator;
this._count = 0;
}
getCount() {
return this._count;
}
// -------------------------------------------------
_transform(data, encoding, callback) {
data.index = this._count++; // eslint-disable-line no-plusplus
// Execute the iterator
// Note that the iterator can throw synchronously as well as return non-promise values
pTry(() => this._iterator(data))
// Invoke callback asyncronously so that errors are not swalled by the promise
// This also guarantees that the promise chain is broken so that they don't stack (avoiding possible leaks)
.then(
() => setImmediate(() => callback(null, data)),
(err) => setImmediate(() => callback(err))
);
}
}
module.exports = function (iterator, concurrency) {
return new IteratorCallerStream(iterator, concurrency);
};
|
// preview and play in JSBin - http://jsbin.com/aviyuf/edit#source
//loggging for JSBin
var log = function(msg){
if (document.getElementById('log')) {
document.getElementById('log').innerHTML = document.getElementById('log').innerHTML + "<br/>" + msg;
}
};
/* helper functions */
var getProp = function(property){
log(property + " - " + this[property]);
};
var setProp = function(property, value){
this[property] = value;
}
/* Function calls */
Sugarless({name: "Tom"})(
getProp, "name"
, setProp, "name", "Tommy"
, getProp, "name"
);
Sugarless({name: "Jerry"})(
getProp, "name"
, setProp, "age", 10
, getProp, "age"
);
|
/* jshint esversion: 6, mocha: true, node: true */
'use strict';
const utils = require('../lib/utils');
const Promise = require('bluebird');
const assert = require('assert');
const avro = require('avsc');
suite('utils', function () {
suite('promisify', function () {
const svc = avro.Service.forProtocol({
protocol: 'Math',
messages: {
neg: {
request: [{name: 'n', type: 'int'}],
response: 'int',
errors: [
{
type: 'error',
name: 'MathError',
fields: [{name: 'code', type: 'int'}]
}
]
},
max: {
request: [
{name: 'n1', type: 'int'},
{name: 'n2', type: 'int'}
],
response: 'int'
}
}
}, {wrapUnions: true});
let client, server;
setup(function () {
server = svc.createServer({silent: true});
client = svc.createClient({buffering: true, server});
});
teardown(function () {
client = undefined;
server = undefined;
});
test('promisify client ok path underlying method', function (done) {
utils.promisify(client);
server.onNeg(function (n, cb) { cb(null, -n); });
client.emitMessage('neg', {n: 2}, {}).then(function (n) {
assert.equal(n, -2);
done();
});
});
test('promisify client ok path convenience handler', function (done) {
utils.promisify(client);
server.onNeg(function (n, cb) { cb(null, -n); });
client.neg(2).then(function (n) {
assert.equal(n, -2);
done();
});
});
test('promisify client catch wrapped custom error', function (done) {
utils.promisify(client);
const MathError = svc.type('MathError').recordConstructor;
server.onNeg(function (n, cb) { cb({MathError: {code: 123}}); });
client.neg(2).catch(MathError, function (err) {
assert.equal(err.code, 123);
assert.strictEqual(this.channel.client, client);
done();
});
});
test('promisify client catch wrapped custom error', function (done) {
utils.promisify(client);
const err = new Error('bar');
server.onNeg(function (n, cb) { cb(err); });
client.neg(2).catch(function (err_) {
assert(err_ instanceof Error);
assert(/bar/.test(err_), err_);
done();
});
});
test('promisify client callback api', function (done) {
utils.promisify(client);
server.onNeg(function (n, cb) { cb(null, -n); });
client.neg(2, function (err, n) {
assert.ifError(err);
assert.equal(n, -2);
assert.strictEqual(this.channel.client, client);
done();
});
});
test('promisify client middleware early return', function (done) {
utils.promisify(client);
server.onNeg(function (n, cb) { cb(null, -n); });
client
.use(function (wreq, wres, next) {
wreq.request = {n: 1};
this.locals.one = 1;
setTimeout(function () {
next();
}, 10);
return Promise.reject(new Error('bar'));
})
.neg(2).catch(function (err) {
assert(/early/.test(err), err);
assert.strictEqual(this.locals.one, 1);
done();
});
});
test('promisify client middleware custom errors', function (done) {
utils.promisify(client);
const MathError = svc.type('MathError').recordConstructor;
client
.use(function (wreq, wres, next) {
return next().catch(function (err) {
const type = err && err.constructor && err.constructor.type;
if (type && type.typeName === 'error') {
wres.error = this.message.errorType.typeName === 'union:wrapped' ?
err.wrap() :
err;
} else {
throw err;
}
});
})
.use(function (wreq, wres, next) {
return next().then(function () { throw new MathError(123); });
})
.neg(2)
.catch(function (err) {
assert.equal(err.code, 123);
done();
});
});
test('promisify server throw system error', function (done) {
utils.promisify(server);
server.onNeg(function () { throw new Error('bar'); });
client.neg(2, function (err) {
assert(/bar/.test(err), err);
done();
});
});
test('promisify server throw custom error', function (done) {
utils.promisify(server);
const MathError = svc.type('MathError').recordConstructor;
server.onNeg(function () { throw new MathError(123); });
client.neg(2, function (err) {
assert.equal(err.MathError.code, 123);
done();
});
});
test('promisify server ok response', function (done) {
utils.promisify(server);
server.onNeg(function (n) { return -n; });
client.neg(2, function (err, n) {
assert.ifError(err);
assert.equal(n, -2);
done();
});
});
test('promisify server ok response skip argument', function (done) {
utils.promisify(server);
server.onMax(function (n1) { return n1; }); // Ignore second argument.
client.max(2, 3, function (err, n) {
assert.ifError(err);
assert.equal(n, 2);
done();
});
});
test('promisify server callback api', function (done) {
utils.promisify(server);
server.onMax(function (n1, n2, cb) { cb(null, Math.max(n1, n2)); });
client.max(2, 3, function (err, n) {
assert.ifError(err);
assert.equal(n, 3);
done();
});
});
test('promisify server middleware propagate error', function (done) {
utils.promisify(server);
const arr = [];
server
.use(function (wreq, wres, next) {
arr.push('in');
return next().catch(function (err) {
arr.push('out');
wres.error = {string: err.message};
});
})
.use(function (wreq, wres, next) {
arr.push('on');
if (true) {
throw new Error('bar');
} else {
// Avoid the `next` unused argument.
next();
}
});
client.neg(2, function (err) {
assert(/bar/.test(err), err);
assert.deepEqual(arr, ['in', 'on', 'out']);
done();
});
});
test('promisify server middleware swallow error', function (done) {
utils.promisify(server);
const arr = [];
server
.use(function (wreq, wres, next) {
arr.push('in');
return next().catch(function () {
arr.push('out');
wres.response = -3;
});
})
.use(function (wreq, wres, next) {
arr.push('on');
next(new Error('baz'), function () {});
});
client.neg(2, function (err, n) {
assert.ifError(err);
assert.equal(n, -3);
assert.deepEqual(arr, ['in', 'on', 'out']);
done();
});
});
test('promisify server middleware', function (done) {
utils.promisify(server);
server
.use(function (wreq, wres, next) {
assert.strictEqual(this.channel.server, server);
wreq.request = {n: 1};
return next().then(function () {
assert.strictEqual(this.channel.server, server);
wres.response = -1;
});
})
.onNeg(function (n, cb) {
assert.equal(n, 1);
cb(null, -2);
});
client.neg(2, function (err, n) {
assert.ifError(err);
assert.equal(n, -1);
done();
});
});
test('promisify server middleware callback api', function (done) {
utils.promisify(server);
let called = false;
server
.use(function (wreq, wres, next) {
next().then(function () {
called = true;
});
// Don't return anything so the callback API will be used.
})
.onNeg(function (n) {
return -n;
});
client.neg(2, function (err, n) {
assert.ifError(err);
assert.equal(n, -2);
assert(called);
done();
});
});
});
});
|
ActiveNavigation = {
bootstrap: function() {
this.create_main_menu();
this.create_sub_menus();
this.attach_events();
},
create_main_menu: function() {
chrome.contextMenus.removeAll();
chrome.contextMenus.create({
id: 'active_navigation_content_menu',
title: 'Active Navigation',
contexts: ['page']
});
return this;
},
create_sub_menus: function() {
chrome.tabs.query({}, function(tabs) {
var tabs_length = tabs.length;
for (var i = 0; i < tabs_length; i++) {
var tab = tabs[i];
var context_menu_item = {
id: "" + tab.id,
title: tab.title,
parentId: "active_navigation_content_menu",
}
if (tab.highlighted && tab.selected && tab.active) {
context_menu_item.type = "checkbox";
context_menu_item.checked = true;
}
chrome.contextMenus.create(context_menu_item);
}
});
return this;
},
attach_events: function() {
this.attach_context_menu_item_clicked();
this.attach_tab_highlighted();
},
attach_context_menu_item_clicked: function() {
chrome.contextMenus.onClicked.addListener(function(info, tab) {
chrome.tabs.update(parseInt(info.menuItemId), {highlighted: true});
});
},
attach_tab_highlighted: function() {
chrome.tabs.onHighlighted.addListener(function(tab) {
ActiveNavigation.create_main_menu().create_sub_menus();
});
}
}
ActiveNavigation.bootstrap();
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import classnames from 'classnames';
import styleShape from 'react-style-proptype';
import { themr } from 'react-css-themr';
import { round, range } from '../utils/utils';
import { SLIDER } from '../identifiers';
import events from '../utils/events';
import InjectProgressBar from '../progress_bar/ProgressBar';
import InjectInput from '../input/Input';
const KEYS = {
ENTER: 'Enter',
ESC: 'Escape',
ARROW_UP: 'ArrowUp',
ARROW_DOWN: 'ArrowDown',
};
const factory = (ProgressBar, Input) => {
class Slider extends Component {
static propTypes = {
buffer: PropTypes.number,
className: PropTypes.string,
disabled: PropTypes.bool,
editable: PropTypes.bool,
max: PropTypes.number,
min: PropTypes.number,
onChange: PropTypes.func,
onDragStart: PropTypes.func,
onDragStop: PropTypes.func,
pinned: PropTypes.bool,
snaps: PropTypes.bool,
step: PropTypes.number,
style: styleShape,
theme: PropTypes.shape({
container: PropTypes.string,
editable: PropTypes.string,
innerknob: PropTypes.string,
innerprogress: PropTypes.string,
input: PropTypes.string,
knob: PropTypes.string,
pinned: PropTypes.string,
pressed: PropTypes.string,
progress: PropTypes.string,
ring: PropTypes.string,
slider: PropTypes.string,
snap: PropTypes.string,
snaps: PropTypes.string,
}),
value: PropTypes.number,
};
static defaultProps = {
buffer: 0,
className: '',
editable: false,
max: 100,
min: 0,
onDragStart: () => {},
onDragStop: () => {},
pinned: false,
snaps: false,
step: 0.01,
value: 0,
};
state = {
inputFocused: false,
inputValue: null,
sliderLength: 0,
sliderStart: 0,
};
componentDidMount() {
window.addEventListener('resize', this.handleResize);
this.handleResize();
}
componentWillReceiveProps(nextProps) {
if (this.state.inputFocused && this.props.value !== nextProps.value) {
this.setState({ inputValue: this.valueForInput(nextProps.value) });
}
}
shouldComponentUpdate(nextProps, nextState) {
return this.state.inputFocused || !nextState.inputFocused;
}
componentWillUpdate(nextProps, nextState) {
if (nextState.pressed !== this.state.pressed) {
if (nextState.pressed) {
this.props.onDragStart();
} else {
this.props.onDragStop();
}
}
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize);
events.removeEventsFromDocument(this.getMouseEventMap());
events.removeEventsFromDocument(this.getTouchEventMap());
events.removeEventsFromDocument(this.getKeyboardEvents());
}
getKeyboardEvents() {
return {
keydown: this.handleKeyDown,
};
}
getMouseEventMap() {
return {
mousemove: this.handleMouseMove,
mouseup: this.handleMouseUp,
};
}
getTouchEventMap() {
return {
touchmove: this.handleTouchMove,
touchend: this.handleTouchEnd,
};
}
handleInputFocus = () => {
this.setState({
inputFocused: true,
inputValue: this.valueForInput(this.props.value),
});
};
handleInputChange = (value) => {
this.setState({ inputValue: value });
};
handleInputBlur = (event) => {
const value = this.state.inputValue || 0;
this.setState({ inputFocused: false, inputValue: null }, () => {
this.props.onChange(this.trimValue(value), event);
});
};
handleKeyDown = (event) => {
const { disabled, step } = this.props;
const {
ARROW_DOWN, ARROW_UP, ENTER, ESC,
} = KEYS;
if (disabled) return;
if ([ENTER, ESC].includes(event.code)) this.inputNode.blur();
if (event.code === ARROW_UP) this.addToValue(step);
if (event.code === ARROW_DOWN) this.addToValue(-step);
};
handleMouseDown = (event) => {
if (this.state.inputFocused) this.inputNode.blur();
events.addEventsToDocument(this.getMouseEventMap());
this.start(events.getMousePosition(event));
events.pauseEvent(event);
};
handleMouseMove = (event) => {
events.pauseEvent(event);
this.move(events.getMousePosition(event));
};
handleMouseUp = () => {
this.end(this.getMouseEventMap());
};
handleResize = (event, callback) => {
const { left, right } = ReactDOM.findDOMNode(this.progressbarNode).getBoundingClientRect();
const cb = (callback) || (() => {});
this.setState({ sliderStart: left, sliderLength: right - left }, cb);
};
handleSliderBlur = () => {
events.removeEventsFromDocument(this.getKeyboardEvents());
};
handleSliderFocus = () => {
events.addEventsToDocument(this.getKeyboardEvents());
};
handleTouchEnd = () => {
this.end(this.getTouchEventMap());
};
handleTouchMove = (event) => {
this.move(events.getTouchPosition(event));
};
handleTouchStart = (event) => {
if (this.state.inputFocused) this.inputNode.blur();
this.start(events.getTouchPosition(event));
events.addEventsToDocument(this.getTouchEventMap());
events.pauseEvent(event);
};
addToValue(increment) {
let value = this.state.inputFocused ? parseFloat(this.state.inputValue) : this.props.value;
value = this.trimValue(value + increment);
if (value !== this.props.value) this.props.onChange(value);
}
end(revents) {
events.removeEventsFromDocument(revents);
this.setState({ pressed: false });
}
knobOffset() {
const { max, min, value } = this.props;
return 100 * ((value - min) / (max - min));
}
move(position) {
const newValue = this.positionToValue(position);
if (newValue !== this.props.value) this.props.onChange(newValue);
}
positionToValue(position) {
const { sliderStart: start, sliderLength: length } = this.state;
const { max, min, step } = this.props;
const pos = ((position.x - start) / length) * (max - min);
return this.trimValue((Math.round(pos / step) * step) + min);
}
start(position) {
this.handleResize(null, () => {
this.setState({ pressed: true });
this.props.onChange(this.positionToValue(position));
});
}
stepDecimals() {
return (this.props.step.toString().split('.')[1] || []).length;
}
trimValue(value) {
if (value < this.props.min) return this.props.min;
if (value > this.props.max) return this.props.max;
return round(value, this.stepDecimals());
}
valueForInput(value) {
const decimals = this.stepDecimals();
return decimals > 0 ? value.toFixed(decimals) : value.toString();
}
renderSnaps() {
if (!this.props.snaps) return undefined;
return (
<div className={this.props.theme.snaps}>
{range(0, (this.props.max - this.props.min) / this.props.step).map(i => <div key={`span-${i}`} className={this.props.theme.snap} />)}
</div>
);
}
renderInput() {
if (!this.props.editable) return undefined;
return (
<Input
innerRef={(node) => { this.inputNode = node; }}
className={this.props.theme.input}
disabled={this.props.disabled}
onFocus={this.handleInputFocus}
onChange={this.handleInputChange}
onBlur={this.handleInputBlur}
value={this.state.inputFocused
? this.state.inputValue
: this.valueForInput(this.props.value)}
/>
);
}
render() {
const { theme } = this.props;
const knobStyles = { left: `${this.knobOffset()}%` };
const className = classnames(theme.slider, {
[theme.editable]: this.props.editable,
[theme.disabled]: this.props.disabled,
[theme.pinned]: this.props.pinned,
[theme.pressed]: this.state.pressed,
[theme.ring]: this.props.value === this.props.min,
}, this.props.className);
return (
<div
className={className}
disabled={this.props.disabled}
data-react-toolbox="slider"
onBlur={this.handleSliderBlur}
onFocus={this.handleSliderFocus}
style={this.props.style}
tabIndex={this.props.disabled ? -1 : 0}
>
<div
ref={(node) => { this.sliderNode = node; }}
className={theme.container}
onMouseDown={this.handleMouseDown}
onTouchStart={this.handleTouchStart}
>
<div
ref={(node) => { this.knobNode = node; }}
className={theme.knob}
onMouseDown={this.handleMouseDown}
onTouchStart={this.handleTouchStart}
style={knobStyles}
>
<div className={theme.innerknob} data-value={parseInt(this.props.value, 10)} />
</div>
<div className={theme.progress}>
<ProgressBar
disabled={this.props.disabled}
ref={(node) => { this.progressbarNode = node; }}
className={theme.innerprogress}
max={this.props.max}
min={this.props.min}
mode="determinate"
value={this.props.value}
buffer={this.props.buffer}
/>
{this.renderSnaps()}
</div>
</div>
{this.renderInput()}
</div>
);
}
}
return Slider;
};
const Slider = factory(InjectProgressBar, InjectInput);
export default themr(SLIDER)(Slider);
export { factory as sliderFactory };
export { Slider };
|
/**
* @file Option
*
* @author Leo Wang(leowang721@gmail.com)
*/
var _ = require('lodash');
var React = require('react-native');
var {
PickerIOS,
View,
Text,
TouchableOpacity,
} = React;
var FormElement = require('./FormElement');
var ICON = {
checkbox: '□▣',
radio: '○◉'
};
var styles = require('./styles/option');
/**
* Option
* when setting props.value, watch out Float Number < 1, the comparation would have problem
* @class Option
* @extends FormElement
* @requires FormElement
*/
class Option extends FormElement {
/**
* @constructor
*
* @param {Object} props properties
*
* @param {string} props.id element's id, setting id will set props.ref with the same value
* @param {?Object} props.style style
* @param {string=} props.type type of the current form element, will try to set styles[type]
*
* @param {string|number} value value, watch out Float Number < 1, the comparation would have problem
* @param {?string} label label for this option
* @param {?(Object} props.labelStyle styles for label
* @param {?(string|Component)} props.icon icon for option, you can use either unicode characters or a Component
* @param {?(Object} props.iconStyle styles for icon
*
* @param {?Object} context context
*/
constructor(props, context) {
super(props, context);
}
render() {
var optionStyles = this.getStyles(styles);
var icon;
var selectedIcon;
var iconProp = this.props.icon || ICON[this.props.type];
if (iconProp) {
if (typeof iconProp === 'string') {
if (iconProp.length === 1) {
icon = selectedIcon = (<Text style={[optionStyles.icon, this.props.iconStyle]}>{iconProp}</Text>);
}
else {
icon = (<Text style={[optionStyles.icon, this.props.iconStyle]}>{iconProp[0]}</Text>);
selectedIcon = (<Text style={[optionStyles.icon, this.props.iconStyle]}>{iconProp[1]}</Text>);
}
}
else if (iconProp.isReactElement) {
icon = selectedIcon = (<View style={[optionStyles.icon, this.props.iconStyle]}>{iconProp}</View>);
}
else if (_.isArray(iconProp)) {
icon = (<View style={[optionStyles.icon, this.props.iconStyle]}>{iconProp[0]}</View>);
selectedIcon = (<View style={[optionStyles.icon, this.props.iconStyle]}>{iconProp[1]}</View>);
}
}
return (
<TouchableOpacity onPress={this.onPress.bind(this)} style={[
...optionStyles.container,
this.props.style,
this.props.selected ? optionStyles.selected : [],
]} {..._.omit(this.props, ['children', 'style', 'onPress'])}>
<View style={optionStyles.labelContainer}>
{this.props.selected ? selectedIcon : icon}
<Text style={[...optionStyles.label, this.props.labelStyle]}>
{this.props.label || this.props.value}
</Text>
</View>
</TouchableOpacity>
);
}
onPress() {
if (this.props.onPress) {
this.props.onPress(this.props.value);
}
}
}
Option.propTypes = FormElement.assignPropTypes(PickerIOS.propTypes, {
label: React.PropTypes.string,
icon: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.element]),
labelStyle: React.PropTypes.object,
iconStyle: React.PropTypes.object,
onPress: React.PropTypes.func,
});
Option.defaultProps = {};
module.exports = Option;
|
class ehstorshell_ehstorfolder_1 {
constructor() {
}
// System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
CreateObjRef() {
}
// bool Equals(System.Object obj)
Equals() {
}
// int GetHashCode()
GetHashCode() {
}
// System.Object GetLifetimeService()
GetLifetimeService() {
}
// type GetType()
GetType() {
}
// System.Object InitializeLifetimeService()
InitializeLifetimeService() {
}
// string ToString()
ToString() {
}
}
module.exports = ehstorshell_ehstorfolder_1;
|
IonicBBS.controller("LoginCtrl",function($scope,$rootScope){
console.log("app..");
//表单部分
$scope.fm = {
// userName : "",
// passWord : ""
}
$scope.login = function(){
console.log("login...");
}
});
|
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var numConstants = require('../../constants/numerical');
var BADNUM = numConstants.BADNUM;
var LOG_CLIP = numConstants.LOG_CLIP;
var LOG_CLIP_PLUS = LOG_CLIP + 0.5;
var LOG_CLIP_MINUS = LOG_CLIP - 0.5;
var Lib = require('../../lib');
var segmentsIntersect = Lib.segmentsIntersect;
var constrain = Lib.constrain;
var constants = require('./constants');
module.exports = function linePoints(d, opts) {
var xa = opts.xaxis;
var ya = opts.yaxis;
var xLog = xa.type === 'log';
var yLog = ya.type === 'log';
var xLen = xa._length;
var yLen = ya._length;
var connectGaps = opts.connectGaps;
var baseTolerance = opts.baseTolerance;
var shape = opts.shape;
var linear = shape === 'linear';
var segments = [];
var minTolerance = constants.minTolerance;
var pts = new Array(d.length);
var pti = 0;
var i;
// pt variables are pixel coordinates [x,y] of one point
// these four are the outputs of clustering on a line
var clusterStartPt, clusterEndPt, clusterHighPt, clusterLowPt;
// "this" is the next point we're considering adding to the cluster
var thisPt;
// did we encounter the high point first, then a low point, or vice versa?
var clusterHighFirst;
// the first two points in the cluster determine its unit vector
// so the second is always in the "High" direction
var clusterUnitVector;
// the pixel delta from clusterStartPt
var thisVector;
// val variables are (signed) pixel distances along the cluster vector
var clusterRefDist, clusterHighVal, clusterLowVal, thisVal;
// deviation variables are (signed) pixel distances normal to the cluster vector
var clusterMinDeviation, clusterMaxDeviation, thisDeviation;
// turn one calcdata point into pixel coordinates
function getPt(index) {
var di = d[index];
if(!di) return false;
var x = xa.c2p(di.x);
var y = ya.c2p(di.y);
// if non-positive log values, set them VERY far off-screen
// so the line looks essentially straight from the previous point.
if(x === BADNUM) {
if(xLog) x = xa.c2p(di.x, true);
if(x === BADNUM) return false;
// If BOTH were bad log values, make the line follow a constant
// exponent rather than a constant slope
if(yLog && y === BADNUM) {
x *= Math.abs(xa._m * yLen * (xa._m > 0 ? LOG_CLIP_PLUS : LOG_CLIP_MINUS) /
(ya._m * xLen * (ya._m > 0 ? LOG_CLIP_PLUS : LOG_CLIP_MINUS)));
}
x *= 1000;
}
if(y === BADNUM) {
if(yLog) y = ya.c2p(di.y, true);
if(y === BADNUM) return false;
y *= 1000;
}
return [x, y];
}
function crossesViewport(xFrac0, yFrac0, xFrac1, yFrac1) {
var dx = xFrac1 - xFrac0;
var dy = yFrac1 - yFrac0;
var dx0 = 0.5 - xFrac0;
var dy0 = 0.5 - yFrac0;
var norm2 = dx * dx + dy * dy;
var dot = dx * dx0 + dy * dy0;
if(dot > 0 && dot < norm2) {
var cross = dx0 * dy - dy0 * dx;
if(cross * cross < norm2) return true;
}
}
var latestXFrac, latestYFrac;
// if we're off-screen, increase tolerance over baseTolerance
function getTolerance(pt, nextPt) {
var xFrac = pt[0] / xLen;
var yFrac = pt[1] / yLen;
var offScreenFraction = Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1);
if(offScreenFraction && (latestXFrac !== undefined) &&
crossesViewport(xFrac, yFrac, latestXFrac, latestYFrac)
) {
offScreenFraction = 0;
}
if(offScreenFraction && nextPt &&
crossesViewport(xFrac, yFrac, nextPt[0] / xLen, nextPt[1] / yLen)
) {
offScreenFraction = 0;
}
return (1 + constants.toleranceGrowth * offScreenFraction) * baseTolerance;
}
function ptDist(pt1, pt2) {
var dx = pt1[0] - pt2[0];
var dy = pt1[1] - pt2[1];
return Math.sqrt(dx * dx + dy * dy);
}
// last bit of filtering: clip paths that are VERY far off-screen
// so we don't get near the browser's hard limit (+/- 2^29 px in Chrome and FF)
var maxScreensAway = constants.maxScreensAway;
// find the intersections between the segment from pt1 to pt2
// and the large rectangle maxScreensAway around the viewport
// if one of pt1 and pt2 is inside and the other outside, there
// will be only one intersection.
// if both are outside there will be 0 or 2 intersections
// (or 1 if it's right at a corner - we'll treat that like 0)
// returns an array of intersection pts
var xEdge0 = -xLen * maxScreensAway;
var xEdge1 = xLen * (1 + maxScreensAway);
var yEdge0 = -yLen * maxScreensAway;
var yEdge1 = yLen * (1 + maxScreensAway);
var edges = [
[xEdge0, yEdge0, xEdge1, yEdge0],
[xEdge1, yEdge0, xEdge1, yEdge1],
[xEdge1, yEdge1, xEdge0, yEdge1],
[xEdge0, yEdge1, xEdge0, yEdge0]
];
var xEdge, yEdge, lastXEdge, lastYEdge, lastFarPt, edgePt;
// for linear line shape, edge intersections should be linearly interpolated
// spline uses this too, which isn't precisely correct but is actually pretty
// good, because Catmull-Rom weights far-away points less in creating the curvature
function getLinearEdgeIntersections(pt1, pt2) {
var out = [];
var ptCount = 0;
for(var i = 0; i < 4; i++) {
var edge = edges[i];
var ptInt = segmentsIntersect(pt1[0], pt1[1], pt2[0], pt2[1],
edge[0], edge[1], edge[2], edge[3]);
if(ptInt && (!ptCount ||
Math.abs(ptInt.x - out[0][0]) > 1 ||
Math.abs(ptInt.y - out[0][1]) > 1
)) {
ptInt = [ptInt.x, ptInt.y];
// if we have 2 intersections, make sure the closest one to pt1 comes first
if(ptCount && ptDist(ptInt, pt1) < ptDist(out[0], pt1)) out.unshift(ptInt);
else out.push(ptInt);
ptCount++;
}
}
return out;
}
function onlyConstrainedPoint(pt) {
if(pt[0] < xEdge0 || pt[0] > xEdge1 || pt[1] < yEdge0 || pt[1] > yEdge1) {
return [constrain(pt[0], xEdge0, xEdge1), constrain(pt[1], yEdge0, yEdge1)];
}
}
function sameEdge(pt1, pt2) {
if(pt1[0] === pt2[0] && (pt1[0] === xEdge0 || pt1[0] === xEdge1)) return true;
if(pt1[1] === pt2[1] && (pt1[1] === yEdge0 || pt1[1] === yEdge1)) return true;
}
// for line shapes hv and vh, movement in the two dimensions is decoupled,
// so all we need to do is constrain each dimension independently
function getHVEdgeIntersections(pt1, pt2) {
var out = [];
var ptInt1 = onlyConstrainedPoint(pt1);
var ptInt2 = onlyConstrainedPoint(pt2);
if(ptInt1 && ptInt2 && sameEdge(ptInt1, ptInt2)) return out;
if(ptInt1) out.push(ptInt1);
if(ptInt2) out.push(ptInt2);
return out;
}
// hvh and vhv we sometimes have to move one of the intersection points
// out BEYOND the clipping rect, by a maximum of a factor of 2, so that
// the midpoint line is drawn in the right place
function getABAEdgeIntersections(dim, limit0, limit1) {
return function(pt1, pt2) {
var ptInt1 = onlyConstrainedPoint(pt1);
var ptInt2 = onlyConstrainedPoint(pt2);
var out = [];
if(ptInt1 && ptInt2 && sameEdge(ptInt1, ptInt2)) return out;
if(ptInt1) out.push(ptInt1);
if(ptInt2) out.push(ptInt2);
var midShift = 2 * Lib.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) -
((ptInt1 || pt1)[dim] + (ptInt2 || pt2)[dim]);
if(midShift) {
var ptToAlter;
if(ptInt1 && ptInt2) {
ptToAlter = (midShift > 0 === ptInt1[dim] > ptInt2[dim]) ? ptInt1 : ptInt2;
}
else ptToAlter = ptInt1 || ptInt2;
ptToAlter[dim] += midShift;
}
return out;
};
}
var getEdgeIntersections;
if(shape === 'linear' || shape === 'spline') {
getEdgeIntersections = getLinearEdgeIntersections;
}
else if(shape === 'hv' || shape === 'vh') {
getEdgeIntersections = getHVEdgeIntersections;
}
else if(shape === 'hvh') getEdgeIntersections = getABAEdgeIntersections(0, xEdge0, xEdge1);
else if(shape === 'vhv') getEdgeIntersections = getABAEdgeIntersections(1, yEdge0, yEdge1);
// a segment pt1->pt2 entirely outside the nearby region:
// find the corner it gets closest to touching
function getClosestCorner(pt1, pt2) {
var dx = pt2[0] - pt1[0];
var m = (pt2[1] - pt1[1]) / dx;
var b = (pt1[1] * pt2[0] - pt2[1] * pt1[0]) / dx;
if(b > 0) return [m > 0 ? xEdge0 : xEdge1, yEdge1];
else return [m > 0 ? xEdge1 : xEdge0, yEdge0];
}
function updateEdge(pt) {
var x = pt[0];
var y = pt[1];
var xSame = x === pts[pti - 1][0];
var ySame = y === pts[pti - 1][1];
// duplicate point?
if(xSame && ySame) return;
if(pti > 1) {
// backtracking along an edge?
var xSame2 = x === pts[pti - 2][0];
var ySame2 = y === pts[pti - 2][1];
if(xSame && (x === xEdge0 || x === xEdge1) && xSame2) {
if(ySame2) pti--; // backtracking exactly - drop prev pt and don't add
else pts[pti - 1] = pt; // not exact: replace the prev pt
}
else if(ySame && (y === yEdge0 || y === yEdge1) && ySame2) {
if(xSame2) pti--;
else pts[pti - 1] = pt;
}
else pts[pti++] = pt;
}
else pts[pti++] = pt;
}
function updateEdgesForReentry(pt) {
// if we're outside the nearby region and going back in,
// we may need to loop around a corner point
if(pts[pti - 1][0] !== pt[0] && pts[pti - 1][1] !== pt[1]) {
updateEdge([lastXEdge, lastYEdge]);
}
updateEdge(pt);
lastFarPt = null;
lastXEdge = lastYEdge = 0;
}
function addPt(pt) {
latestXFrac = pt[0] / xLen;
latestYFrac = pt[1] / yLen;
// Are we more than maxScreensAway off-screen any direction?
// if so, clip to this box, but in such a way that on-screen
// drawing is unchanged
xEdge = (pt[0] < xEdge0) ? xEdge0 : (pt[0] > xEdge1) ? xEdge1 : 0;
yEdge = (pt[1] < yEdge0) ? yEdge0 : (pt[1] > yEdge1) ? yEdge1 : 0;
if(xEdge || yEdge) {
// to get fills right - if first point is far, push it toward the
// screen in whichever direction(s) are far
if(!pti) {
pts[pti++] = [xEdge || pt[0], yEdge || pt[1]];
}
else if(lastFarPt) {
// both this point and the last are outside the nearby region
// check if we're crossing the nearby region
var intersections = getEdgeIntersections(lastFarPt, pt);
if(intersections.length > 1) {
updateEdgesForReentry(intersections[0]);
pts[pti++] = intersections[1];
}
}
// we're leaving the nearby region - add the point where we left it
else {
edgePt = getEdgeIntersections(pts[pti - 1], pt)[0];
pts[pti++] = edgePt;
}
var lastPt = pts[pti - 1];
if(xEdge && yEdge && (lastPt[0] !== xEdge || lastPt[1] !== yEdge)) {
// we've gone out beyond a new corner: add the corner too
// so that the next point will take the right winding
if(lastFarPt) {
if(lastXEdge !== xEdge && lastYEdge !== yEdge) {
if(lastXEdge && lastYEdge) {
// we've gone around to an opposite corner - we
// need to add the correct extra corner
// in order to get the right winding
updateEdge(getClosestCorner(lastFarPt, pt));
}
else {
// we're coming from a far edge - the extra corner
// we need is determined uniquely by the sectors
updateEdge([lastXEdge || xEdge, lastYEdge || yEdge]);
}
}
else if(lastXEdge && lastYEdge) {
updateEdge([lastXEdge, lastYEdge]);
}
}
updateEdge([xEdge, yEdge]);
}
else if((lastXEdge - xEdge) && (lastYEdge - yEdge)) {
// we're coming from an edge or far corner to an edge - again the
// extra corner we need is uniquely determined by the sectors
updateEdge([xEdge || lastXEdge, yEdge || lastYEdge]);
}
lastFarPt = pt;
lastXEdge = xEdge;
lastYEdge = yEdge;
}
else {
if(lastFarPt) {
// this point is in range but the previous wasn't: add its entry pt first
updateEdgesForReentry(getEdgeIntersections(lastFarPt, pt)[0]);
}
pts[pti++] = pt;
}
}
// loop over ALL points in this trace
for(i = 0; i < d.length; i++) {
clusterStartPt = getPt(i);
if(!clusterStartPt) continue;
pti = 0;
lastFarPt = null;
addPt(clusterStartPt);
// loop over one segment of the trace
for(i++; i < d.length; i++) {
clusterHighPt = getPt(i);
if(!clusterHighPt) {
if(connectGaps) continue;
else break;
}
// can't decimate if nonlinear line shape
// TODO: we *could* decimate [hv]{2,3} shapes if we restricted clusters to horz or vert again
// but spline would be verrry awkward to decimate
if(!linear || !opts.simplify) {
addPt(clusterHighPt);
continue;
}
var nextPt = getPt(i + 1);
clusterRefDist = ptDist(clusterHighPt, clusterStartPt);
if(clusterRefDist < getTolerance(clusterHighPt, nextPt) * minTolerance) continue;
clusterUnitVector = [
(clusterHighPt[0] - clusterStartPt[0]) / clusterRefDist,
(clusterHighPt[1] - clusterStartPt[1]) / clusterRefDist
];
clusterLowPt = clusterStartPt;
clusterHighVal = clusterRefDist;
clusterLowVal = clusterMinDeviation = clusterMaxDeviation = 0;
clusterHighFirst = false;
clusterEndPt = clusterHighPt;
// loop over one cluster of points that collapse onto one line
for(i++; i < d.length; i++) {
thisPt = nextPt;
nextPt = getPt(i + 1);
if(!thisPt) {
if(connectGaps) continue;
else break;
}
thisVector = [
thisPt[0] - clusterStartPt[0],
thisPt[1] - clusterStartPt[1]
];
// cross product (or dot with normal to the cluster vector)
thisDeviation = thisVector[0] * clusterUnitVector[1] - thisVector[1] * clusterUnitVector[0];
clusterMinDeviation = Math.min(clusterMinDeviation, thisDeviation);
clusterMaxDeviation = Math.max(clusterMaxDeviation, thisDeviation);
if(clusterMaxDeviation - clusterMinDeviation > getTolerance(thisPt, nextPt)) break;
clusterEndPt = thisPt;
thisVal = thisVector[0] * clusterUnitVector[0] + thisVector[1] * clusterUnitVector[1];
if(thisVal > clusterHighVal) {
clusterHighVal = thisVal;
clusterHighPt = thisPt;
clusterHighFirst = false;
} else if(thisVal < clusterLowVal) {
clusterLowVal = thisVal;
clusterLowPt = thisPt;
clusterHighFirst = true;
}
}
// insert this cluster into pts
// we've already inserted the start pt, now check if we have high and low pts
if(clusterHighFirst) {
addPt(clusterHighPt);
if(clusterEndPt !== clusterLowPt) addPt(clusterLowPt);
} else {
if(clusterLowPt !== clusterStartPt) addPt(clusterLowPt);
if(clusterEndPt !== clusterHighPt) addPt(clusterHighPt);
}
// and finally insert the end pt
addPt(clusterEndPt);
// have we reached the end of this segment?
if(i >= d.length || !thisPt) break;
// otherwise we have an out-of-cluster point to insert as next clusterStartPt
addPt(thisPt);
clusterStartPt = thisPt;
}
// to get fills right - repeat what we did at the start
if(lastFarPt) updateEdge([lastXEdge || lastFarPt[0], lastYEdge || lastFarPt[1]]);
segments.push(pts.slice(0, pti));
}
return segments;
};
|
/**
* class InteractiveBehavior < Behavior
*
* `Physics.behavior('interactive')`.
*
* User interaction helper.
*
* Used to get mouse/touch events and add a mouse grab interaction.
*
* Additional options include:
* - el: The element of the renderer. What you input as the `el` for the renderer.
* - moveThrottle: The min time between move events (default: `10`).
* - minVel: The minimum velocity clamp [[Vectorish]] (default: { x: -5, y: -5 }) to restrict velocity a user can give to a body
* - maxVel: The maximum velocity clamp [[Vectorish]] (default: { x: 5, y: 5 }) to restrict velocity a user can give to a body
*
* The behavior also triggers the following events on the world:
* ```javascript
* // a body has been grabbed
* world.on('interact:grab', function( data ){
* data.x; // the x coord
* data.y; // the y coord
* data.body; // the body that was grabbed
* });
* // no body was grabbed, but the renderer area was clicked, or touched
* world.on('interact:poke', function( data ){
* data.x; // the x coord
* data.y; // the y coord
* });
* world.on('interact:move', function( data ){
* data.x; // the x coord
* data.y; // the y coord
* data.body; // the body that was grabbed (if applicable)
* });
* // when the viewport is released (mouseup, touchend)
* world.on('interact:release', function( data ){
* data.x; // the x coord
* data.y; // the y coord
* });
* ```
**/
Physics.behavior('interactive', function( parent ){
if ( !document ){
// must be in node environment
return {};
}
var defaults = {
// the element to monitor
el: null,
// time between move events
moveThrottle: 1000 / 100 | 0,
// minimum velocity clamp
minVel: { x: -5, y: -5 },
// maximum velocity clamp
maxVel: { x: 5, y: 5 }
}
,getElementOffset = function( el ){
var curleft = 0
,curtop = 0
;
if (el.offsetParent) {
do {
curleft += el.offsetLeft;
curtop += el.offsetTop;
} while (el = el.offsetParent);
}
return { left: curleft, top: curtop };
}
,getCoords = function( e ){
var offset = getElementOffset( e.target )
,obj = ( e.changedTouches && e.changedTouches[0] ) || e
,x = obj.pageX - offset.left
,y = obj.pageY - offset.top
;
return {
x: x
,y: y
};
}
;
return {
// extended
init: function( options ){
var self = this
,prevTreatment
,time
;
// call parent init method
parent.init.call( this );
this.options.defaults( defaults );
this.options( options );
// vars
this.mousePos = new Physics.vector();
this.mousePosOld = new Physics.vector();
this.offset = new Physics.vector();
this.el = typeof this.options.el === 'string' ? document.getElementById(this.options.el) : this.options.el;
if ( !this.el ){
throw "No DOM element specified";
}
// init events
var grab = function grab( e ){
var pos = getCoords( e )
,body
;
time = Physics.util.ticker.now();
if ( self._world ){
body = self._world.findOne({ $at: new Physics.vector( pos.x, pos.y ) });
if ( body ){
// we're trying to grab a body
// fix the body in place
prevTreatment = body.treatment;
body.treatment = 'kinematic';
body.state.vel.zero();
body.state.angular.vel = 0;
// remember the currently grabbed body
self.body = body;
// remember the mouse offset
self.mousePos.clone( pos );
self.mousePosOld.clone( pos );
self.offset.clone( pos ).vsub( body.state.pos );
pos.body = body;
self._world.emit('interact:grab', pos);
} else {
self._world.emit('interact:poke', pos);
}
}
};
var move = Physics.util.throttle(function move( e ){
var pos = getCoords( e )
,state
;
if ( self.body ){
time = Physics.util.ticker.now();
self.mousePosOld.clone( self.mousePos );
// get new mouse position
self.mousePos.set(pos.x, pos.y);
pos.body = self.body;
}
self._world.emit('interact:move', pos);
}, self.options.moveThrottle);
var release = function release( e ){
var pos = getCoords( e )
,body
,dt = Math.max(Physics.util.ticker.now() - time, self.options.moveThrottle)
;
// get new mouse position
self.mousePos.set(pos.x, pos.y);
// release the body
if (self.body){
self.body.treatment = prevTreatment;
// calculate the release velocity
self.body.state.vel.clone( self.mousePos ).vsub( self.mousePosOld ).mult( 1 / dt );
// make sure it's not too big
self.body.state.vel.clamp( self.options.minVel, self.options.maxVel );
self.body = false;
}
if ( self._world ){
self._world.emit('interact:release', pos);
}
};
this.el.addEventListener('mousedown', grab);
this.el.addEventListener('touchstart', grab);
this.el.addEventListener('mousemove', move);
this.el.addEventListener('touchmove', move);
this.el.addEventListener('mouseup', release);
this.el.addEventListener('touchend', release);
},
// extended
connect: function( world ){
// subscribe the .behave() method to the position integration step
world.on('integrate:positions', this.behave, this);
},
// extended
disconnect: function( world ){
// unsubscribe when disconnected
world.off('integrate:positions', this.behave);
},
// extended
behave: function( data ){
var self = this
,state
,dt = Math.max(data.dt, self.options.moveThrottle)
;
if ( self.body ){
// if we have a body, we need to move it the the new mouse position.
// we'll do this by adjusting the velocity so it gets there at the next step
state = self.body.state;
state.vel.clone( self.mousePos ).vsub( self.offset ).vsub( state.pos ).mult( 1 / dt );
}
}
};
});
|
/**
* meta 配置
* hidden=true表示在导航上默认不展示
* requiresAuth=true 表示需要身份验证即需要登录
* scrollTop=true 切换路由时,页面滚动到顶部,默认是true
* type: resource/node 对应的侧边栏
*/
import Vue from 'vue'
import Router from 'vue-router'
import Views from '@/views/index'
import store from '../store'
import nodeRoute from './node'
import resourceRoute from './resource'
import {gotoLogin} from "../lib/utils";
Vue.use(Router)
const scrollBehavior = (to, from, savedPosition) => {
if (savedPosition) {
return savedPosition
}
const position = {}
if (to.hash) {
position.selector = to.hash
}
if (to.meta.scrollToTop !== false) {
position.x = 0
position.y = 0
}
return position
}
const router = new Router({
mode: 'history',
scrollBehavior,
routes: [
{
path: '/',
meta: {title: '资源市场'},
component: Views.layout,
children: [resourceRoute, nodeRoute, {
path: 'about',
hidden: true,
meta: {
requiresAuth: false,
title: '关于freelog'
},
component: Views.aboutView
}, {
path: 'setting',
hidden: true,
meta: {
requiresAuth: true,
title: '账号设置'
},
component: Views.userView
}, {
path: 'help',
hidden: true,
meta: {
requiresAuth: false,
title: '帮助中心'
},
component: Views.helpView
}, {
path: '/',
hidden: true,
meta: {
requiresAuth: false,
title: '资源市场',
theme: 'gray'
},
component: Views.mainView
}]
},
{
path: '*',
meta: {
requiresAuth: false,
title: 'not found'
},
component: Views.layout,
children: [{
name: '404',
path: '',
meta: {
requiresAuth: false,
title: '404'
},
component: Views.error
}]
}
]
})
function listenWindowVisibility() {
let hidden = 'hidden'
const doc = document
if (hidden in doc) {
doc.addEventListener('visibilitychange', onchange)
} else if ('mozHidden' in doc) {
hidden = 'mozHidden'
doc.addEventListener('mozvisibilitychange', onchange)
} else if ('webkitHidden' in doc) {
hidden = 'webkitHidden'
doc.addEventListener('webkitvisibilitychange', onchange)
} else if ('msHidden' in doc) {
hidden = 'msHidden'
doc.addEventListener('msvisibilitychange', onchange)
} else {
const events = ['onpageshow', 'onpagehide', 'onfocus', 'onblur']
events.forEach((name) => {
window[name] = onchange()
})
}
function onchange(evt) {
const v = 'visible'
const h = 'hidden'
const evtMap = {
focus: v, focusin: v, pageshow: v, blur: h, focusout: h, pagehide: h
}
let type
evt = evt || window.event
if (evt.type in evtMap) {
type = evtMap[evt.type]
} else {
type = this[hidden] ? 'hidden' : 'visible'
}
if (type === 'visible') {
isChecked = false
}
}
}
//避免每次跳转都判断登录态的判断,只有切换tab后回来再重新判断
var isChecked = false
listenWindowVisibility()
router.beforeEach((to, from, next) => {
if (isChecked) {
return next()
}
store.dispatch('checkUserSession')
.then(isSameSession => {
isChecked = true
if (isSameSession) {
next()
} else {
store.dispatch('getCurrentUserInfo')
.then(user => {
if (user) {
window.location = to.fullPath
} else {
gotoLogin()
}
})
}
})
})
export default router
|
export const api_key = "dc6zaTOxFJmzC";
|
import {expect} from 'chai';
import formatCurrency from '../../../frontend/src/lib/format_currency';
describe('formatCurrency', () => {
it('should return $12.34', () => {
expect(formatCurrency(12.34)).to.equal('$12.34');
});
it('should return $12,345.67', () => {
expect(formatCurrency(12345.67)).to.equal('$12,345.67');
});
it('should return £12.34', () => {
expect(formatCurrency(12.34, 'GBP')).to.equal('£12.34');
});
it('should return 12.34', () => {
expect(formatCurrency(12.34, 'SEK')).to.equal('kr12,34');
});
it('should return €12.34', () => {
expect(formatCurrency(12.34,'EUR')).to.equal('€12,34');
});
it('should return €12 345.67', () => {
expect(formatCurrency(12345.67,'EUR')).to.equal('€12 345,67');
});
it('should return -€12.34', () => {
expect(formatCurrency(-12.34,'EUR')).to.equal('-€12,34');
});
it('should return MXN$10', () => {
expect(formatCurrency(10,'MXN',{precision: 0, compact: false})).to.equal('MXN $10');
})
});
|
/*
python_runner:
Python code runner.
*/
var currentPythonContext = null;
function PythonInterpreter(context, msgCallback) {
this.context = context;
this.messageCallback = msgCallback;
this._code = '';
this._editor_filename = "<stdin>";
this.context.runner = this;
this._maxIterations = 4000;
this._maxIterWithoutAction = 50;
this._resetCallstackOnNextStep = false;
this._paused = false;
this._isRunning = false;
this._stepInProgress = false;
this._resetDone = true;
this.stepMode = false;
this._steps = 0;
this._stepsWithoutAction = 0;
this._lastNbActions = null;
this._hasActions = false;
this._nbActions = 0;
this._allowStepsWithoutDelay = 0;
this._timeouts = [];
this._editorMarker = null;
this.availableModules = [];
this._argumentsByBlock = {};
this._definedFunctions = [];
this.nbNodes = 0;
this.curNode = 0;
this.readyNodes = [];
this.finishedNodes = [];
this.nodeStates = [];
this.waitingOnReadyNode = false;
var that = this;
this._skulptifyHandler = function (name, generatorName, blockName, nbArgs, type) {
if(!arrayContains(this._definedFunctions, name)) { this._definedFunctions.push(name); }
var handler = '';
handler += "\tcurrentPythonContext.runner.checkArgs('" + name + "', '" + generatorName + "', '" + blockName + "', arguments);";
handler += "\n\tvar susp = new Sk.misceval.Suspension();";
handler += "\n\tvar result = Sk.builtin.none.none$;";
// If there are arguments, convert them from Skulpt format to the libs format
handler += "\n\tvar args = Array.prototype.slice.call(arguments);";
handler += "\n\tfor(var i=0; i<args.length; i++) { args[i] = currentPythonContext.runner.skToJs(args[i]); };";
handler += "\n\tsusp.resume = function() { return result; };";
handler += "\n\tsusp.data = {type: 'Sk.promise', promise: new Promise(function(resolve) {";
handler += "\n\targs.push(resolve);";
// Count actions
if(type == 'actions') {
handler += "\n\tcurrentPythonContext.runner._nbActions += 1;";
}
handler += "\n\ttry {";
handler += '\n\t\tcurrentPythonContext["' + generatorName + '"]["' + blockName + '"].apply(currentPythonContext, args);';
handler += "\n\t} catch (e) {";
handler += "\n\t\tcurrentPythonContext.runner._onStepError(e)}";
handler += '\n\t}).then(function (value) {\nresult = value;\nreturn value;\n })};';
handler += '\n\treturn susp;';
return '\nmod.' + name + ' = new Sk.builtin.func(function () {\n' + handler + '\n});\n';
};
this._skulptifyValue = function(value) {
if(typeof value === "number") {
var handler = 'Sk.builtin.int_(' + value + ')';
} else if(typeof value === "boolean") {
var handler = 'Sk.builtin.bool(' + value.toString() + ')';
} else if(typeof value === "string") {
var handler = 'Sk.builtin.str(' + JSON.stringify(value) + ')';
} else if(Array.isArray(value)) {
var list = [];
for(var i=0; i<value.length; i++) {
list.push(this._skulptifyValue(value[i]));
}
var handler = 'Sk.builtin.list([' + list.join(',') + '])';
} else {
throw "Unable to translate value '" + value + "' into a Skulpt constant.";
}
return 'new ' + handler;
}
this._skulptifyConst = function(name, value) {
var handler = this._skulptifyValue(value);
return '\nmod.' + name + ' = ' + handler + ';\n';
};
this._injectFunctions = function () {
// Generate Python custom libraries from all generated blocks
this._definedFunctions = [];
if(this.context.infos && this.context.infos.includeBlocks && this.context.infos.includeBlocks.generatedBlocks) {
// Flatten customBlocks information for easy access
var blocksInfos = {};
for (var generatorName in this.context.customBlocks) {
for (var typeName in this.context.customBlocks[generatorName]) {
var blockList = this.context.customBlocks[generatorName][typeName];
for (var iBlock=0; iBlock < blockList.length; iBlock++) {
var blockInfo = blockList[iBlock];
blocksInfos[blockInfo.name] = {
nbArgs: 0, // handled below
type: typeName};
blocksInfos[blockInfo.name].nbsArgs = [];
if(blockInfo.anyArgs) {
// Allows to specify the function can accept any number of arguments
blocksInfos[blockInfo.name].nbsArgs.push(Infinity);
}
var variants = blockInfo.variants ? blockInfo.variants : (blockInfo.params ? [blockInfo.params] : []);
if(variants.length) {
for(var i=0; i < variants.length; i++) {
blocksInfos[blockInfo.name].nbsArgs.push(variants[i].length);
}
}
}
}
}
// Generate functions used in the task
for (var generatorName in this.context.infos.includeBlocks.generatedBlocks) {
var blockList = this.context.infos.includeBlocks.generatedBlocks[generatorName];
if(!blockList.length) { continue; }
var modContents = "var $builtinmodule = function (name) {\n\nvar mod = {};\nmod.__package__ = Sk.builtin.none.none$;\n";
if(!this._argumentsByBlock[generatorName]) {
this._argumentsByBlock[generatorName] = {};
}
for (var iBlock=0; iBlock < blockList.length; iBlock++) {
var blockName = blockList[iBlock];
var code = this.context.strings.code[blockName];
if (typeof(code) == "undefined") {
code = blockName;
}
var nbsArgs = blocksInfos[blockName] ? (blocksInfos[blockName].nbsArgs ? blocksInfos[blockName].nbsArgs : []) : [];
var type = blocksInfos[blockName] ? blocksInfos[blockName].type : 'actions';
if(type == 'actions') {
this._hasActions = true;
}
this._argumentsByBlock[generatorName][blockName] = nbsArgs;
modContents += this._skulptifyHandler(code, generatorName, blockName, nbsArgs, type);
}
// TODO :: allow selection of constants available in a task
// if(this.context.infos.includeBlocks.constants && this.context.infos.includeBlocks.constants[generatorName]) {
if(this.context.customConstants && this.context.customConstants[generatorName]) {
var constList = this.context.customConstants[generatorName];
for(var iConst=0; iConst < constList.length; iConst++) {
var name = constList[iConst].name;
if(this.context.strings.constant && this.context.strings.constant[name]) {
name = this.context.strings.constant[name];
}
modContents += this._skulptifyConst(name, constList[iConst].value)
}
}
modContents += "\nreturn mod;\n};";
Sk.builtinFiles["files"]["src/lib/"+generatorName+".js"] = modContents;
this.availableModules.push(generatorName);
}
}
};
this.checkArgs = function (name, generatorName, blockName, args) {
// Check the number of arguments corresponds to a variant of the function
if(!this._argumentsByBlock[generatorName] || !this._argumentsByBlock[generatorName][blockName]) {
console.error("Couldn't find the number of arguments for " + generatorName + "/" + blockName + ".");
return;
}
var nbsArgs = this._argumentsByBlock[generatorName][blockName];
if(nbsArgs.length == 0) {
// This function doesn't have arguments
if(args.length > 0) {
msg = name + "() takes no arguments (" + args.length + " given)";
throw new Sk.builtin.TypeError(msg);
}
} else if(nbsArgs.indexOf(args.length) == -1 && nbsArgs.indexOf(Infinity) == -1) {
var minArgs = nbsArgs[0];
var maxArgs = nbsArgs[0];
for(var i=1; i < nbsArgs.length; i++) {
minArgs = Math.min(minArgs, nbsArgs[i]);
maxArgs = Math.max(maxArgs, nbsArgs[i]);
}
if (minArgs === maxArgs) {
msg = name + "() takes exactly " + minArgs + " arguments";
} else if (args.length < minArgs) {
msg = name + "() takes at least " + minArgs + " arguments";
} else if (args.length > maxArgs){
msg = name + "() takes at most " + maxArgs + " arguments";
} else {
msg = name + "() doesn't have a variant accepting this number of arguments";
}
msg += " (" + args.length + " given)";
throw new Sk.builtin.TypeError(msg);
}
};
this._definePythonNumber = function() {
// Create a class which behaves as a Number, but can have extra properties
this.pythonNumber = function(val) {
this.val = new Number(val);
}
this.pythonNumber.prototype = Object.create(Number.prototype);
function makePrototype(func) {
return function() { return Number.prototype[func].call(this.val); }
}
var funcs = ['toExponential', 'toFixed', 'toLocaleString', 'toPrecision', 'toSource', 'toString', 'valueOf'];
for(var i = 0; i < funcs.length ; i++) {
this.pythonNumber.prototype[funcs[i]] = makePrototype(funcs[i]);
}
}
this.skToJs = function(val) {
// Convert Skulpt item to JavaScript
// TODO :: Might be partly replaceable with Sk.ffi.remapToJs
if(val instanceof Sk.builtin.bool) {
return val.v ? true : false;
} else if(val instanceof Sk.builtin.func) {
return function() {
var args = [];
for(var i = 0; i < arguments.length; i++) {
args.push(that._createPrimitive(arguments[i]));
}
var retp = new Promise(function(resolve, reject) {
var p = Sk.misceval.asyncToPromise(function() { return val.tp$call(args); });
p.then(function(val) { resolve(that.skToJs(val)); });
});
return retp;
}
} else if(val instanceof Sk.builtin.dict) {
var dictKeys = Object.keys(val);
var retVal = {};
for(var i = 0; i < dictKeys.length; i++) {
var key = dictKeys[i];
if(key == 'size' || key == '__class__') { continue; }
var subItems = val[key].items;
for(var j = 0; j < subItems.length; j++) {
var subItem = subItems[j];
retVal[subItem.lhs.v] = this.skToJs(subItem.rhs);
}
}
return retVal;
} else {
var retVal = val.v;
if(val instanceof Sk.builtin.tuple || val instanceof Sk.builtin.list) {
retVal = [];
for(var i = 0; i < val.v.length; i++) {
retVal[i] = this.skToJs(val.v[i]);
}
}
if(val instanceof Sk.builtin.tuple) {
retVal.isTuple = true;
}
if(val instanceof Sk.builtin.float_) {
retVal = new this.pythonNumber(retVal);
retVal.isFloat = true;
}
return retVal;
}
};
this.getDefinedFunctions = function() {
this._injectFunctions();
return this._definedFunctions.slice();
};
this._setTimeout = function(func, time) {
var timeoutId = null;
var that = this;
function wrapper() {
var idx = that._timeouts.indexOf(timeoutId);
if(idx > -1) { that._timeouts.splice(idx, 1); }
func();
}
timeoutId = window.setTimeout(wrapper, time);
this._timeouts.push(timeoutId);
}
this.waitDelay = function (callback, value, delay) {
this._paused = true;
if (delay > 0) {
var _noDelay = this.noDelay.bind(this, callback, value);
this._setTimeout(_noDelay, delay);
// We just waited some time, allow next steps to not be delayed
this._allowStepsWithoutDelay = Math.min(this._allowStepsWithoutDelay + Math.ceil(delay / 10), 100);
} else {
this.noDelay(callback, value);
}
};
this.waitEvent = function (callback, target, eventName, func) {
this._paused = true;
var listenerFunc = null;
var that = this;
listenerFunc = function(e) {
target.removeEventListener(eventName, listenerFunc);
that.noDelay(callback, func(e));
};
target.addEventListener(eventName, listenerFunc);
};
this.waitCallback = function (callback) {
// Returns a callback to be called once we can continue the execution
this._paused = true;
var that = this;
return function(value) {
that.noDelay(callback, value);
};
};
this.noDelay = function (callback, value) {
var primitive = this._createPrimitive(value);
if (primitive !== Sk.builtin.none.none$) {
// Apparently when we create a new primitive, the debugger adds a call to
// the callstack.
this._resetCallstackOnNextStep = true;
this.reportValue(value);
}
this._paused = false;
callback(primitive);
this._setTimeout(this._continue.bind(this), 10);
};
this.allowSwitch = function(callback) {
// Tells the runner that we can switch the execution to another node
var curNode = context.curNode;
var ready = function(readyCallback) {
that.readyNodes[curNode] = function() {
readyCallback(callback);
};
if(that.waitingOnReadyNode) {
that.waitingOnReadyNode = false;
that.startNode(that.curNode, curNode);
}
};
this.readyNodes[curNode] = false;
this.startNextNode(curNode);
return ready;
};
this.defaultSelectNextNode = function(runner, previousNode) {
var i = previousNode + 1;
if(i >= runner.nbNodes) { i = 0; }
do {
if(runner.readyNodes[i]) {
break;
} else {
i++;
}
if(i >= runner.nbNodes) { i = 0; }
} while(i != previousNode);
return i;
};
// Allow the next node selection process to be customized
this.selectNextNode = this.defaultSelectNextNode;
this.startNextNode = function(curNode) {
// Start the next node when one has been switched from
var newNode = this.selectNextNode(this, curNode);
this._paused = true;
if(newNode == curNode) {
// No ready node
this.waitingOnReadyNode = true;
} else {
// TODO :: switch execution
this.startNode(curNode, newNode);
}
};
this.startNode = function(curNode, newNode) {
setTimeout(function() {
that.nodeStates[curNode] = that._debugger.suspension_stack.slice();
that._debugger.suspension_stack = that.nodeStates[newNode];
that.curNode = newNode;
var ready = that.readyNodes[newNode];
if(ready) {
that.readyNodes[newNode] = false;
context.setCurNode(newNode);
if(typeof ready == 'function') {
ready();
} else {
that._paused = false;
that._continue();
}
} else {
that.waitingOnReadyNode = true;
}
}, 0);
};
this._createPrimitive = function (data) {
// TODO :: Might be replaceable with Sk.ffi.remapToPy
if (data === undefined || data === null) {
return Sk.builtin.none.none$; // Reuse the same object.
}
var type = typeof data;
var result = {v: data}; // Emulate a Skulpt object as default
if (type === 'number') {
if(Math.floor(data) == data) { // isInteger isn't supported by IE
result = new Sk.builtin.int_(data);
} else {
result = new Sk.builtin.float_(data);
}
} else if (type === 'string') {
result = new Sk.builtin.str(data);
} else if (type === 'boolean') {
result = new Sk.builtin.bool(data);
} else if (typeof data.length != 'undefined') {
var skl = [];
for(var i = 0; i < data.length; i++) {
skl.push(this._createPrimitive(data[i]));
}
result = new Sk.builtin.list(skl);
} else if (data) {
// Create a dict if it's an object with properties
var props = [];
for(var prop in data) {
if(data.hasOwnProperty(prop)) {
// We can pass a list [prop1name, prop1val, ...] to Skulpt's dict
// constructor ; however to work properly they need to be Skulpt
// primitives too
props.push(this._createPrimitive(prop));
props.push(this._createPrimitive(data[prop]));
}
}
if(props.length > 0) {
result = new Sk.builtin.dict(props);
}
}
return result;
};
this._onOutput = function (_output) {
that.print(_output);
};
this._onDebugOut = function (text) {
// console.log('DEBUG: ', text);
};
this._configure = function () {
Sk.configure({
output: this._onOutput,
debugout: this._onDebugOut,
read: this._builtinRead.bind(this),
yieldLimit: null,
execLimit: null,
debugging: true,
breakpoints: this._debugger.check_breakpoints.bind(this._debugger),
__future__: Sk.python3
});
Sk.pre = "edoutput";
Sk.pre = "codeoutput";
// Disable document library
delete Sk.builtinFiles["files"]["src/lib/document.js"];
this._definePythonNumber();
this.context.callCallback = this.noDelay.bind(this);
};
this.print = function (message, className) {
if (message.trim() === 'Program execution complete') {
this._onFinished();
}
if (message) {
//console.log('PRINT: ', message, className || '');
}
};
this._onFinished = function () {
this.finishedNodes[this.curNode] = true;
this.readyNodes[this.curNode] = false;
if(this.finishedNodes.indexOf(false) != -1) {
// At least one node is not finished
this.startNextNode(this.curNode);
} else {
// All nodes are finished, stop the execution
this.stop();
}
try {
this.context.infos.checkEndCondition(this.context, true);
} catch (e) {
this._onStepError(e);
}
};
this._builtinRead = function (x) {
if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
throw "File not found: '" + x + "'";
return Sk.builtinFiles["files"][x];
};
this.get_source_line = function (lineno) {
return this._code.split('\n')[lineno];
};
this._continue = function () {
if (this.context.infos.checkEndEveryTurn) {
try {
this.context.infos.checkEndCondition(context, false);
} catch(e) {
this._onStepError(e);
return;
}
}
if (!this.context.allowInfiniteLoop && this._steps >= this._maxIterations) {
this._onStepError(window.languageStrings.tooManyIterations);
} else if (!this.context.allowInfiniteLoop && this._stepsWithoutAction >= this._maxIterWithoutAction) {
this._onStepError(window.languageStrings.tooManyIterationsWithoutAction);
} else if (!this._paused && this._isRunning) {
this.step();
}
};
this.initCodes = function (codes) {
// For reportValue in Skulpt.
window.currentPythonRunner = this;
if(Sk.running) {
if(typeof Sk.runQueue === 'undefined') {
Sk.runQueue = [];
}
Sk.runQueue.push({ctrl: this, codes: codes});
return;
}
currentPythonContext = this.context;
this._debugger = new Sk.Debugger(this._editor_filename, this);
this._configure();
this._injectFunctions();
/**
* Add a last instruction at the end of the code so Skupt will generate a Suspension state
* for after the user's last instruction. Otherwise it would be impossible to retrieve the
* modifications made by the last user's line. For skulpt analysis.
*/
this._code = codes[0] + "\npass";
this._setBreakpoint(1, false);
if(typeof this.context.infos.maxIter !== 'undefined') {
this._maxIterations = Math.ceil(this.context.infos.maxIter/10);
}
if(typeof this.context.infos.maxIterWithoutAction !== 'undefined') {
this._maxIterWithoutAction = Math.ceil(this.context.infos.maxIterWithoutAction/10);
}
if(!this._hasActions) {
// No limit on
this._maxIterWithoutAction = this._maxIterations;
}
var susp_handlers = {};
susp_handlers["*"] = this._debugger.suspension_handler.bind(this);
this.nbNodes = codes.length;
this.curNode = 0;
context.setCurNode(this.curNode);
this.readyNodes = [];
this.finishedNodes = [];
this.nodeStates = [];
for(var i = 0; i < codes.length ; i++) {
this.readyNodes.push(true);
this.finishedNodes.push(false);
try {
var promise = this._debugger.asyncToPromise(this._asyncCallback(this._editor_filename, codes[i]), susp_handlers, this._debugger);
promise.then(this._debugger.success.bind(this._debugger), this._debugger.error.bind(this._debugger));
} catch (e) {
this._onOutput(e.toString() + "\n");
}
this.nodeStates.push(this._debugger.suspension_stack);
this._debugger.suspension_stack = [];
}
this._debugger.suspension_stack = this.nodeStates[0];
this._resetInterpreterState();
Sk.running = true;
this._isRunning = true;
};
this.run = function () {
if(this.stepMode) {
this._paused = this._stepInProgress;
this.stepMode = false;
}
this._setTimeout(this._continue.bind(this), 100);
};
this.runCodes = function(codes) {
this.initCodes(codes);
this.run();
};
this.runStep = function (resolve, reject) {
this.stepMode = true;
if (this._isRunning && !this._stepInProgress) {
this.step(resolve, reject);
}
};
this.nbRunning = function () {
return this._isRunning ? 1 : 0;
};
this.removeEditorMarker = function () {
var editor = this.context.blocklyHelper._aceEditor;
if(editor && this._editorMarker) {
editor.session.removeMarker(this._editorMarker);
this._editorMarker = null;
}
};
this.unSkulptValue = function (origValue) {
// Transform a value, possibly a Skulpt one, into a printable value
if(typeof origValue !== 'object' || origValue === null) {
var value = origValue;
} else if(origValue.constructor === Sk.builtin.dict) {
var keys = Object.keys(origValue);
var dictElems = [];
for(var i=0; i<keys.length; i++) {
if(keys[i] == 'size' || keys[i] == '__class__'
|| !origValue[keys[i]].items
|| !origValue[keys[i]].items[0]) {
continue;
}
var items = origValue[keys[i]].items[0];
dictElems.push('' + this.unSkulptValue(items.lhs) + ': ' + this.unSkulptValue(items.rhs));
}
var value = '{' + dictElems.join(',' ) + '}';
} else if(origValue.constructor === Sk.builtin.list) {
var oldArray = origValue.v;
var newArray = [];
for(var i=0; i<oldArray.length; i++) {
newArray.push(this.unSkulptValue(oldArray[i]));
}
var value = '[' + newArray.join(', ') + ']';
} else if(origValue.v !== undefined) {
var value = origValue.v;
if(typeof value == 'string') {
value = '"' + value + '"';
}
} else if(typeof origValue == 'object') {
var value = origValue;
}
return value;
};
this.reportValue = function (origValue, varName) {
// Show a popup displaying the value of a block in step-by-step mode
if(origValue === undefined
|| (origValue && origValue.constructor === Sk.builtin.func)
|| !this._editorMarker
|| !context.display
|| !this.stepMode) {
return origValue;
}
var value = this.unSkulptValue(origValue);
var highlighted = $('.aceHighlight');
if(highlighted.length == 0) {
return origValue;
} else if(highlighted.find('.ace_start').length > 0) {
var target = highlighted.find('.ace_start')[0];
} else {
var target = highlighted[0];
}
var bbox = target.getBoundingClientRect();
var leftPos = bbox.left+10;
var topPos = bbox.top-14;
if(typeof value == 'boolean') {
var displayStr = value ? window.languageStrings.valueTrue : window.languageStrings.valueFalse;
} else if(value === null) {
var displayStr = "None"
} else {
var displayStr = value.toString();
}
if(typeof value == 'boolean') {
displayStr = value ? window.languageStrings.valueTrue : window.languageStrings.valueFalse;
}
if(varName) {
displayStr = '' + varName + ' = ' + displayStr;
}
var dropDownDiv = '' +
'<div class="blocklyDropDownDiv" style="transition: transform 0.25s, opacity 0.25s; background-color: rgb(255, 255, 255); border-color: rgb(170, 170, 170); left: '+leftPos+'px; top: '+topPos+'px; display: block; opacity: 1; transform: translate(0px, -20px);">' +
' <div class="blocklyDropDownContent">' +
' <div class="valueReportBox">' +
displayStr +
' </div>' +
' </div>' +
' <div class="blocklyDropDownArrow arrowBottom" style="transform: translate(22px, 15px) rotate(45deg);"></div>' +
'</div>';
$('.blocklyDropDownDiv').remove();
$('body').append(dropDownDiv);
return origValue;
};
this.stop = function () {
for (var i = 0; i < this._timeouts.length; i += 1) {
window.clearTimeout(this._timeouts[i]);
}
this._timeouts = [];
this.removeEditorMarker();
if(Sk.runQueue) {
for (var i=0; i<Sk.runQueue.length; i++) {
if(Sk.runQueue[i].ctrl === this) {
Sk.runQueue.splice(i, 1);
i--;
}
}
}
if(window.quickAlgoInterface) {
window.quickAlgoInterface.setPlayPause(false);
}
this._resetInterpreterState();
};
this.isRunning = function () {
return this._isRunning;
};
this._resetInterpreterState = function () {
this._steps = 0;
this._stepsWithoutAction = 0;
this._lastNbActions = 0;
this._nbActions = 0;
this._allowStepsWithoutDelay = 0;
this._isRunning = false;
this._resetDone = false;
this.stepMode = false;
this._stepInProgress = false;
this._resetCallstackOnNextStep = false;
this._paused = false;
this.waitingOnReadyNode = false;
Sk.running = false;
if(Sk.runQueue && Sk.runQueue.length > 0) {
var nextExec = Sk.runQueue.shift();
setTimeout(function () { nextExec.ctrl.runCodes(nextExec.codes); }, 100);
}
};
this._resetCallstack = function () {
if (this._resetCallstackOnNextStep) {
this._resetCallstackOnNextStep = false;
this._debugger.suspension_stack.pop();
}
};
this.reset = function() {
if(this._resetDone) { return; }
if(this.isRunning()) {
this.stop();
}
this.context.reset();
this._resetDone = true;
};
this.step = function (resolve, reject) {
this._resetCallstack();
this._stepInProgress = true;
var editor = this.context.blocklyHelper._aceEditor;
var markDelay = this.context.infos ? Math.floor(this.context.infos.actionDelay/4) : 0;
if(this.context.display && (this.stepMode || markDelay > 30)) {
var curSusp = this._debugger.suspension_stack[this._debugger.suspension_stack.length-1];
if(curSusp && curSusp.$lineno) {
this.removeEditorMarker();
var splitCode = this._code.split(/[\r\n]/);
var Range = ace.require('ace/range').Range;
this._editorMarker = editor.session.addMarker(
new Range(curSusp.$lineno-1, curSusp.$colno, curSusp.$lineno, 0),
"aceHighlight",
"line");
}
} else {
this.removeEditorMarker();
}
var stepDelay = 0;
if(!this.stepMode && this.context.allowInfiniteLoop) {
// Add a delay in infinite loops to avoid using all CPU
if(this._allowStepsWithoutDelay > 0) {
// We just had a waitDelay, don't delay further
this._allowStepsWithoutDelay -= 1;
} else {
stepDelay = 10;
}
}
var realStepDelay = markDelay + stepDelay;
if(realStepDelay > 0) {
this._paused = true;
var self = this;
setTimeout(function() {
self.realStep(resolve, reject);
}, realStepDelay);
} else {
this.realStep(resolve, reject);
}
};
this.realStep = function (resolve, reject) {
this._paused = this.stepMode;
this._debugger.enable_step_mode();
this._debugger.resume.call(this._debugger, resolve, reject);
this._steps += 1;
if(this._lastNbActions != this._nbActions) {
this._lastNbActions = this._nbActions;
this._stepsWithoutAction = 0;
} else {
this._stepsWithoutAction += 1;
}
};
this._onStepSuccess = function (callback) {
// If there are still timeouts, there's still a step in progress
this._stepInProgress = !!this._timeouts.length;
this._continue();
if (typeof callback === 'function') {
callback();
}
};
this._onStepError = function (message, callback) {
context.onExecutionEnd && context.onExecutionEnd();
// We always get there, even on a success
this.stop();
message = '' + message;
// Skulpt doesn't support well NoneTypes
if(message.indexOf("TypeError: Cannot read property") > -1 && message.indexOf("undefined") > -1) {
message = message.replace(/^.* line/, "TypeError: NoneType value used in operation on line");
}
if(message.indexOf('undefined') > -1) {
message += '. ' + window.languageStrings.undefinedMsg;
}
// Transform message depending on whether we successfully
if(this.context.success) {
message = "<span style='color:green;font-weight:bold'>" + message + "</span>";
} else {
message = this.context.messagePrefixFailure + message;
}
this.messageCallback(message);
if (typeof callback === 'function') {
callback();
}
};
this._setBreakpoint = function (bp, isTemporary) {
this._debugger.add_breakpoint(this._editor_filename + ".py", bp, "0", isTemporary);
};
this._asyncCallback = function (editor_filename, code) {
var dumpJS = false;
return function() {
return Sk.importMainWithBody(editor_filename, dumpJS, code, true);
};
};
this.signalAction = function () {
// Allows a context to signal an "action" happened
this._stepsWithoutAction = 0;
};
}
function initBlocklyRunner(context, msgCallback) {
return new PythonInterpreter(context, msgCallback);
};
|
const MongoClient = require('mongodb').MongoClient;
const config = require('./../config');
const dbName = config.DB_NAME;
let currentConnection = null;
async function connect() {
if (currentConnection === null) {
currentConnection = await MongoClient.connect(config.DB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
}
return currentConnection;
}
async function close() {
if (currentConnection !== null) {
currentConnection.close();
currentConnection = null;
}
}
async function insertMany(collectionName, items) {
const collection = currentConnection.db(dbName).collection(collectionName);
const queryResult = await collection.insertMany(items);
return queryResult;
}
async function findAll(collectionName) {
const collections = await currentConnection.db(dbName).collections();
const queryResult = new Map();
for (collection of collections) {
const collectionName = collection.collectionName;
if (!queryResult.has(collectionName)) {
queryResult.set(collectionName, []);
}
const collectionResults = await collection.find().toArray();
queryResult.get(collectionName).push(...collectionResults);
}
return queryResult;
}
async function dropIfExists(collectionName) {
let queryResult = null;
if (await isCollectionExists(collectionName)) {
const collection = currentConnection.db(dbName).collection(collectionName);
queryResult = await collection.drop();
}
return queryResult;
}
async function isCollectionExists(collectionName) {
const collections = await currentConnection.db(dbName).listCollections().toArray();
return collections.some((collection) => collection.name === collectionName);
}
module.exports = {
isCollectionExists,
dropIfExists,
findAll,
insertMany,
close,
connect,
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.