code stringlengths 2 1.05M |
|---|
var getRequest = function(val) {
console.log(val);
var phrase = val,
key = '3ed40dc640c04223adba52fddb235425',
capitolWordsAPI = 'http://capitolwords.org/api/1/dates.json',
startDate = '1995',
granularity = 'year';
phrase = phrase.replace(/\s/, '+');
var requestURI = capitolWordsAPI + '?phrase=' + phrase
+ '&' + 'start_date=' + startDate
+ '&' + 'granularity=' + granularity
+ '&' + 'apikey=' + key;
$.get(requestURI, function( data ) {
var arr = [['year', 'occurances']];
data.results.forEach(function(obj){
arr.push([obj.year, obj.count]);
});
google.load('visualization', '1', {packages: ['corechart', 'bar']});
google.setOnLoadCallback(drawMaterial);
console.log(arr);
function drawMaterial() {
var data = google.visualization.arrayToDataTable(arr);
var options = {
chart: {
title: "Frequency of " + val + " in Congress by year"
},
hAxis: {
title: 'Number of Occurances',
minValue: 0,
},
vAxis: {
title: 'Year'
},
bars: 'horizontal'
};
var material = new google.charts.Bar(document.getElementById('chart_div'));
console.log(data);
console.log(options);
material.draw(data, options);
}
/*
google.load('visualization', '1', {packages: ['corechart', 'bar']});
google.setOnLoadCallback(drawMaterial);
function drawMaterial() {
var data = google.visualization.arrayToDataTable([
['City', '2010 Population', '2000 Population'],
['New York City, NY', 8175000, 8008000],
['Los Angeles, CA', 3792000, 3694000],
['Chicago, IL', 2695000, 2896000],
['Houston, TX', 2099000, 1953000],
['Philadelphia, PA', 1526000, 1517000]
]);
var options = {
chart: {
title: 'Population of Largest U.S. Cities'
},
hAxis: {
title: 'Total Population',
minValue: 0,
},
vAxis: {
title: 'City'
},
bars: 'horizontal'
var material = new google.charts.Bar(document.getElementById('chart_div'));
material.draw(data, options);
}
*/
});
};
//mike's work
$(function(){
var $button = $('#button');
var $input = $('#input');
$button.on('click', function() {
var value = $input.val();
$input.val('');
getRequest(value);
});
});
|
function rangestart_loop_object_firstSubRule (start) {
// Common properties
this.idx = -1
this.length = 1
this.next = lastSubRule
// Specific properties
this.start = start
}
rangestart_loop_object_firstSubRule.prototype.test = function (buf, offset) {
var isString = typeof buf === 'string'
var start = this.start
var pos = offset
var bufLen = buf.length
if (isString) {
while (pos < bufLen) {
var c = buf.charCodeAt(pos)
// No match, end of the main loop
if ( c < start ) break
// Match, try for more
pos++
}
} else {
while (pos < bufLen) {
var c = buf[offset]
// No match, end of the main loop
if ( c < start ) break
// Match, try for more
pos++
}
}
// At least one match if the offset changed
return pos > offset ? this.next.test(buf, pos) : -1
} |
"use strict";
const _ = require ('underscore'),
http = require ('http'),
util = require ('./base/util'),
ass = require ('./base/assertion_syntax'),
fs = require ('./base/fs'),
url = require ('url'),
path = require ('path'),
stringify = require ('string.ify'),
bullet = require ('string.bullet'),
O = Object
/* ------------------------------------------------------------------------ */
StackTracey.isThirdParty.except (path => path.includes ('useless/server'))
/* ------------------------------------------------------------------------ */
module.exports = $trait ({
$depends: [require ('./api')],
/* ------------------------------------------------------------------------ */
$defaults: {
config: {
port: 1333,
maxFileSize: 16 * 1024 * 1024,
requestTimeout: undefined,
production: false
}
},
/* The $http thing prototype
------------------------------------------------------------------------ */
HttpContext: $component ({
$property: _.object (_.map ({
400: 'Bad Request',
401: 'Unauthorized',
403: 'Forbidden',
404: 'Not Found',
500: 'Internal Server',
501: 'Not Implemented',
}, (desc, code) =>
/* generates 'InternalServerError': $property (() => $http.Error (500, 'Internal Server')) */
[`${desc.replace (/\s/g, '')}Error`, $property (function () { return this.Error (code, desc) })]
)
),
Error: (code, desc = 'HTTP Error') => O.assign (new Error (`${desc} Error (${code})`), { httpErrorCode: code, stackOffset: 3 }),
mime: {
'html' : 'text/html',
'xml' : 'text/xml',
'text' : 'text/plain',
'json' : 'application/json',
'binary' : 'binary/octet-stream',
'jpeg' : 'image/jpeg',
'jpg' : 'image/jpeg',
'png' : 'image/png',
'js' : 'text/javascript',
'javascript' : 'application/javascript',
'css' : 'text/css',
'svg' : 'image/svg+xml',
'ico' : 'image/x-icon',
'mp4' : 'video/mp4',
'webm' : 'video/webm',
'appcache' : 'text/cache-manifest',
guess (x) {
return _.isString (x) ? this.text : this.json },
guessFromFileName (x) {
return this[path.extname (x).split ('.')[1]] },
addUTF8 (x) {
return x && (x + (((x.split ('/')[0] === 'text') ||
(x === 'application/json') ||
(x === 'application/javascript'))
? '; charset=utf-8'
: '')) } },
coerce: $static (function (what) {
return (what instanceof this) ? what : this.stub (what) }),
stub: $static (function (cfg) {
return new this ({
request: _.extend ({ method: 'POST', pause: _.identity },
cfg.request,
_.pick (cfg, 'url', 'method', 'code', 'nonce', 'headers', 'cookies')),
response: cfg.response,
cookies: cfg.cookies,
stub: true,
writeHead: function () { return this },
write: function () { return this },
end: function () { return this },
receiveData: () => Promise.resolve ((cfg.data &&
(_.isString (cfg.data)
? cfg.data
: JSON.stringify (cfg.data))) || '') }) }),
init () {
_.defaults (this, {
code: undefined,
timeout: undefined,
headers: {},
nonce: String.randomHex (6),
cookies: _.fromPairs (_.map ((this.request.headers &&
this.request.headers.cookie &&
this.request.headers.cookie.split (';')) || [], cookie => cookie.split ('=').map (
val => (val || '').trimmed))),
env: _.extend ({ when: Date.now (), who: null }, $env, this.env) })
this.url = this.request.url || ''
this.uri = this.url && url.parse (this.url)
this.path = this.uri.pathname.split ('/')
this.method = this.request.method
this.isJSONAPI = this.path[1] === 'api'
if (this.method === 'POST') {
this.request.pause () } }, // pauses incoming data receiving, until explicitly resumed
setCode (code) {
this.code = code; return this },
setHeaders (headers) {
_.extend (this.headers, headers); return this },
setMime (x) { return this.setHeaders ({ 'Content-Type': $http.mime[x] || x }) },
setMimeIfNotAlready (x) { return this.setMime (this.headers['Content-Type'] || x) },
redirect (to) {
return this.setCode (302)
.setHeaders ({ 'Location': to }) },
setCookies (cookies) {
return _.extend2 (this, {
cookies: cookies,
headers: {
'Set-Cookie': _.map (cookies, (value, name) =>
name + '=' + (value || '<<deleted>>') + '; Expires=Wed, 13-Jan-2100 22:23:01 GMT; Path=/') } } ) },
removeCookies (cookies) {
return this.cookies (_.fromPairs (cookies.map (x => [x, undefined]))) },
receiveData () {
return new Promise ((then, err) => {
var data = ''
this.request.on ('data', chunk => { data += chunk })
this.request.on ('end', () => { then (data) })
this.request.on ('error', err)
this.request.resume () }) },
nocache () { // iOS aggressively caches even POST requests, so this is needed to prevent that
return this.setHeaders ({
'Pragma': 'no-cache',
'Cache-control': 'no-cache' }) },
writeHead () {
if (!this.headWritten) {
this.headWritten = true
this.response.writeHead (this.code || 200,
_.nonempty (_.extended (
this.headers, {
'Content-Type': this.mime.addUTF8 (this.headers['Content-Type']) }))) }; return this },
write (x) {
if (!this.headWritten) {
this.writeHead () }
if (!this.ended) {
this.response.write (_.isString (x) ? x : JSON.stringify (x)) }; return this },
end () {
if (!this.ended) {
this.ended = true
this.response.end () }; return this },
file (file) {
return fs.stat (file)
.then (stat => {
if (!stat.isFile ()) {
throw this.NotFoundError
}
let [, start, end] = (this.request.headers.range || 'bytes=0-').match (/bytes=(\d+)-(\d+)?/)
const isPartial = (end !== undefined)
start = Number (start)
end = isPartial ? Number (end) : (stat.size - 1)
if (isPartial) {
this.setCode (206)
this.setHeaders ({
'Accept-Ranges': 'bytes',
'Content-Range': `bytes ${start}-${end}/${stat.size}`,
'Content-Type': 'multipart/byteranges',
'Content-Length': (end - start) + 1,
'Connection': 'keep-alive'
})
} else {
this.setHeaders ({
'Content-Length': stat.size,
'Content-Type': ($http.mime.guessFromFileName (file) || this.mime.binary)
})
}
this.writeHead ()
return new Promise ((then, err) =>
fs.createReadStream (file, { bufferSize: 4 * 1024, start: start, end: end })
.on ('error', err)
.on ('close', then.arity0)
.pipe (this.response))
})
.catch (e => {
throw this.NotFoundError
})
}
}),
/* Entry point
------------------------------------------------------------------------ */
beforeInit () {
log.i ('Starting HTTP @ ', log.color.boldBlue, `localhost:${this.config.port}`)
/* Creates pseudo-global properties bound to the current HTTP request context
*/
$global.property ('$http', {
get: () => AndrogeneProcessContext.current && AndrogeneProcessContext.current.env,
set: x => AndrogeneProcessContext.current && (AndrogeneProcessContext.current.env = x) })
$global.property ('$env', {
get: () => ($http && $http.env) || {},
set: x => _.extend ($http.env, x) })
$global.property ('$this', {
get: () => ($http && $http.this_) || this,
})
/* Starts HTTP server
*/
return new Promise (then => {
this.httpServer = http.createServer ((request, response) => {
this.serveRequest (new this.HttpContext ({ // @hide
request: request,
response: response,
this_: this })) })
.listen (this.config.port, then.arity0) }) },
/* Entry point for all requests, now accepting either actual Context or
it's config for ad-hoc evaluation.
------------------------------------------------------------------------ */
serveRequest (context) { context = this.HttpContext.coerce (context)
if (!this.initialized.already) {
context.setCode (500).write ('Starting up...').end ()
return
}
context.timeout = this.config.requestTimeout
var result = new AndrogenePromise (resolve => { $global.$http = context
resolve (this.callAPIHandler ()
.timeout (context.timeout)) })
.then (this.writeResult,
this.writeError)
return result
.disarmAndrogene ()
.finally ((e, x) => {
result.processContext.within (() => context.writeHead ().end ()) () // finalizes request
log (e ? log.color.red : (context.method === 'GET'
? log.color.green
: log.color.pink), context.method.pad (4), ': ', e ? log.color.boldRed
: log.color.bright, context.request.url)
const androgene = result.processContext.root
if (androgene.hasSomethingToReport) {
log.withConfig (log.config ({ indentPattern: ' ', indent: 1 }), () => {
log.newline ()
androgene.displayReport (androgene.report ({ verbose: e ? true : false }))
})
}
})
.catch (function (e) {
log.ee (log.config ({ indent: 1, location: false }), '\n', e)
throw e
})
},
callAPIHandler: function () {
var match = APISchema.match (this.apiSchema, $http.method, $http.url)
if (!match) { log.newline ()
APISchema.debugTrace (this.apiSchema, $http.method, $http.url)
throw $http.NotFoundError }
else {
_.extend ($env, match.vars); return __(match.fn ()) } },
writeResult: function (x) {
if (x === $http) { // for $http-returning handlers like () => $http.setCookies (..)
x = undefined }
if (x !== undefined || $http.isJSONAPI) {
/* Make /api/ URLS respond with { success: true, value: .. } pattern by default, but only if
no Content-Type was explicitly specified. So that a handler can override that behavior by
specifying a Content-Type. */
if (!$http.headers['Content-Type']) {
$http.headers['Content-Type'] = $http.mime.guess (
x = ($http.isJSONAPI ? { success: true, value : x } : x)) }
$http.writeHead ()
.write (x)
if (AndrogeneProcessContext.current.root.hasSomethingToReport) {
log.gg (_.isString (x) ? x.limitedTo (120) : x, '\n')
}
}
return x },
writeError: function (e) { // TODO: construct asynchronous error stack from AndrogeneProcessContext
if ( ($http.headers['Content-Type'] === $http.mime.json) || // if JSON
(!$http.headers['Content-Type'] && $http.isJSONAPI)) { // or if /api/ and no Content-Type explicitly specified
$http.setCode (((e instanceof Error) && e.httpErrorCode) || $http.code || 500)
.setMime ('json')
.writeHead ()
.write ({
success: false,
error: e.message,
...((e instanceof Error) ? { parsedStack: new StackTracey (e).map (e => _.extend (e, { remote: true })) } : {})
})
} else {
const x = log.impl.stringify (e)
const isHTML = $http.headers['Content-Type'] === $http.mime.html
$http.setCode (((e instanceof Error) && e.httpErrorCode) || $http.code || 500)
.setMime (isHTML ? 'html' : 'text')
.writeHead ()
.write (isHTML ? ('<html><body><pre>' + _.escape (x) + '</pre></body></html>') : x)
}
throw e
},
/* REQUEST PROCESSING PRIMITIVES
------------------------------------------------------------------------ */
env: x => () => { $env = x },
mime (x) {
$http.setMime (x) },
timeout (ms) {
$http.timeout = ms },
noTimeout () {
$http.timeout = undefined },
interlocked (then) {
return _.interlocked (releaseLock => { _.onAfter ($http, 'end', releaseLock); then () }) },
allowOrigin (value) {
return x => ($http.headers['Access-Control-Allow-Origin'] = value, x) },
jsVariable (rvalue, lvalue) {
$http.setHeaders ({ 'Content-Type': $http.mime.javascript })
return bullet ('window.' + rvalue + ' = ', stringify.configure ({ pure: true, pretty: true }) (lvalue)) },
receiveText () {
return $http.receiveData ().then (log.ii) },
receiveJSON () {
return $http.receiveData ()
.then (log.ii)
.then (JSON.parse) },
receiveForm () {
return $http.receiveData ()
.then (data => {
return log.i ('POST vars:',
_.fromPairs (
_.map (data.split ('&'), kv => kv.split ('=').map (decodeURIComponent)))) }) },
receiveFile () {
if ($http.request.headers['content-type'] !== $http.mime.binary) {
throw new Error ('Content-Type should be ' + $http.mime.binary + ' (found ' + $http.request.headers['content-type'] + ')') }
var maxFileSize = this.config.maxFileSize
var fileSize = parseInt ($http.request.headers['x-file-size'], 10)
if (fileSize <= 0) {
throw new Error ('file is empty') }
else if (fileSize > maxFileSize) {
throw new Error ('file is too big') }
else {
return util.writeRequestDataToFile ({
request: $http.request,
filePath: path.join (process.env.TMP || process.env.TMPDIR || process.env.TEMP || '/tmp' || process.cwd (), String.randomHex (32)) }) } },
safeFilePath ({ location, dirRoot = process.cwd () }) {
if (location.split ('/').includes ('..')) {
log.e ('Contains forbidden symbols:', location.bright)
throw $http.ForbiddenError }
else {
return path.join (path.resolve (dirRoot), location) }
},
async file (location, subLocation = $env.file) {
const locatedPath = this.safeFilePath ({ location })
const isDirectory = (await fs.stat (locatedPath)).isDirectory ()
return $http.file (isDirectory ? this.safeFilePath ({ location: subLocation, dirRoot: locatedPath }) : locatedPath)
},
redirect (to) {
return x => ($http.redirect (to), x) },
hideFromProduction () {
if (this.config.production === true) {
throw $http.NotFoundError
}
}
/* ------------------------------------------------------------------------ */
})
|
var quad = require('./')
var test = require('tape')
var bufferEqual = require('buffer-equals')
test('creates the indices for a quad mesh (two triangles)', function(t) {
t.deepEqual(quad({ type: 'array' }), [0, 1, 2, 0, 2, 3], 'clockwise array')
t.deepEqual(quad({ clockwise: false, type: 'array' }), [0, 1, 2, 2, 1, 3], 'counter-clockwise')
t.deepEqual(quad({ count: 2, type: 'array' }),
[0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7],
'counter-clockwise')
t.deepEqual(quad(),
new Uint16Array([0, 1, 2, 0, 2, 3]),
'default uint16')
t.deepEqual(quad({ type: 'uint8' }),
new Uint8Array([0, 1, 2, 0, 2, 3]),
'dtype uint8')
t.deepEqual(quad({ type: 'uint8_clamped' }),
new Uint8ClampedArray([0, 1, 2, 0, 2, 3]),
'dtype uint8_clamped')
var empty = []
for (var i=0; i<12; i++)
empty.push(0)
var out = empty.slice()
var ret = quad(out)
t.equal(ret, out, 'returns input array')
t.deepEqual(out, [ 0, 1, 2, 0, 2, 3, 0, 0, 0, 0, 0, 0 ])
out = empty.slice()
quad(out, { start: 6 })
t.deepEqual(out, [ 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3 ])
var buf = new Buffer(6)
quad(buf)
t.equal(bufferEqual(buf, new Buffer([0, 1, 2, 0, 2, 3])), true)
//number param is no longer documented but still supported
out = empty.slice()
quad(out, 2)
t.deepEqual(out, [ 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7 ])
t.deepEqual(quad(2),
new Uint16Array([0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7]),
'accepts number')
t.end()
}) |
import { API_EVENTS_URL } from '../constants';
export const getEvents = async () => {
try {
const response = await fetch(API_EVENTS_URL, {
method: 'GET',
mode: 'cors',
});
const data = await response.json();
return data.results;
} catch {
return null;
}
};
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 Ricardo Pallas
*
* 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.
*
*/
import daggy from 'daggy';
const GetUserDetails = daggy.tagged('userRepository');
//User :: Task (User)
GetUserDetails.prototype.execute = function(userId) {
return this.userRepository.getUserById(userId);
}
module.exports = {
GetUserDetails: GetUserDetails
} |
'use strict';
if (typeof Promise === 'undefined') {
// Rejection tracking prevents a common issue where React gets into an
// inconsistent state due to an error, but it gets swallowed by a Promise,
// and the user has no idea what causes React's erratic future behavior.
require('promise/lib/rejection-tracking').enable();
window.Promise = require('promise/lib/es6-extensions.js');
}
// Object.assign() is commonly used with React.
// It will use the native implementation if it's present and isn't buggy.
Object.assign = require('object-assign');
require('babel-polyfill');
// ResizeObserver is a polyfill for a tool that subscribes to resize
// events on an element https://wicg.github.io/ResizeObserver/
require('resize-observer');
const encoding = require('text-encoding');
window.TextEncoder = encoding.TextEncoder;
window.TextDecoder = encoding.TextDecoder;
|
var x$;
x$ = angular.module('loadingio', []);
x$.directive('ldbar', ['$compile', '$timeout'].concat(function($compile, $timeout){
return {
restrict: 'A',
scope: {
model: '=ngModel',
config: '=config'
},
link: function(s, e, a, c){
var bar;
if (e[0]) {
bar = !e[0].ldBar
? new ldBar(e[0], s.config || {})
: e[0].ldBar;
}
return s.$watch('model', function(n, o){
return bar.set(n);
});
}
};
})); |
'use strict'
const WSlibp2p = require('libp2p-websockets')
const multiaddr = require('multiaddr')
const pull = require('pull-stream')
const multiplex = require('./src')
let listener
const boot = (done) => {
const ws = new WSlibp2p()
const mh = multiaddr('/ip4/127.0.0.1/tcp/9095/ws')
listener = ws.createListener((transportSocket) => {
const muxedConn = multiplex.listener(transportSocket)
muxedConn.on('stream', (connRx) => {
const connTx = muxedConn.newStream()
pull(connRx, connTx, connRx)
})
})
listener.listen(mh, done)
}
const shutdown = (done) => {
listener.close(done)
}
module.exports = {
hooks: {
browser: {
pre: boot,
post: shutdown
}
}
}
|
import assert from 'assert'
import float from './support/float.js'
import { julian, jupitermoons, planetposition } from '../src/index.js'
import data from '../data/index.js'
describe('#jupitermoons', function () {
describe('positions', function () {
it('positions()', function () {
const pos = jupitermoons.positions(2448972.50068)
assert.strictEqual(float(pos[0].x).toFixed(2), -3.44)
assert.strictEqual(float(pos[1].x).toFixed(2), +7.44)
assert.strictEqual(float(pos[2].x).toFixed(2), +1.24)
assert.strictEqual(float(pos[3].x).toFixed(2), +7.08)
assert.strictEqual(float(pos[0].y).toFixed(2), +0.21)
assert.strictEqual(float(pos[1].y).toFixed(2), +0.25)
assert.strictEqual(float(pos[2].y).toFixed(2), +0.65)
assert.strictEqual(float(pos[3].y).toFixed(2), +1.10)
// Output:
// X -3.44 +7.44 +1.24 +7.08
// Y +0.21 +0.25 +0.65 +1.10
})
it('conjuction', function () {
// Exercise, p. 314.
// The exercise of finding the zero crossing is not coded here, but computed
// are offsets at the times given by Meeus, showing the X coordinates near
// zero (indicating conjunction) and Y coordinates near the values given by
// Meeus.
let jde = new julian.Calendar().fromDate(new Date('1988-11-23T07:28:00Z')).toJDE()
const pos3 = jupitermoons.positions(jde)
jde = new julian.Calendar().fromDate(new Date('1988-11-23T05:15:00Z')).toJDE()
const pos4 = jupitermoons.positions(jde)
assert.deepStrictEqual(xyToFixed(pos3[2]), {
x: -0.0016,
y: -0.8424
})
assert.deepStrictEqual(xyToFixed(pos4[3]), {
x: +0.0555,
y: +1.4811
})
// Output:
// III 7ʰ28ᵐ X = -0.00 Y = -0.84
// IV 5ʰ15ᵐ X = +0.06 Y = +1.48
})
})
describe('e5 positions', function () {
it('e5()', function () {
const e = new planetposition.Planet(data.earth)
const j = new planetposition.Planet(data.jupiter)
const pos = jupitermoons.e5(2448972.50068, e, j)
assert.strictEqual(float(pos[0].x).toFixed(4), -3.4503)
assert.strictEqual(float(pos[1].x).toFixed(4), +7.4418)
assert.strictEqual(float(pos[2].x).toFixed(4), +1.2010)
assert.strictEqual(float(pos[3].x).toFixed(4), +7.0720)
assert.strictEqual(float(pos[0].y).toFixed(4), +0.2137)
assert.strictEqual(float(pos[1].y).toFixed(4), +0.2752)
assert.strictEqual(float(pos[2].y).toFixed(4), +0.5900)
assert.strictEqual(float(pos[3].y).toFixed(4), +1.0290)
// Output:
// X -3.4503 +7.4418 +1.2010 +7.0720
// Y +0.2137 +0.2752 +0.5900 +1.0290
})
it('conjunction', function () {
// Exercise, p. 314.
// The exercise of finding the zero crossing is not coded here, but computed
// are offsets at the times given by Meeus, showing the X coordinates near
// zero (indicating conjunction) and Y coordinates near the values given by
// Meeus.
const e = new planetposition.Planet(data.earth)
const j = new planetposition.Planet(data.jupiter)
let jde = new julian.Calendar().fromDate(new Date('1988-11-23T07:28:00Z')).toJDE()
const pos3 = jupitermoons.e5(jde, e, j)
jde = new julian.Calendar().fromDate(new Date('1988-11-23T05:15:00Z')).toJDE()
const pos4 = jupitermoons.e5(jde, e, j)
assert.deepStrictEqual(xyToFixed(pos3[2]), {
x: +0.0032,
y: -0.8042
})
assert.deepStrictEqual(xyToFixed(pos4[3]), {
x: +0.0002,
y: +1.3990
})
// Output:
// III 7ʰ28ᵐ X = +0.0032 Y = -0.8042
// IV 5ʰ15ᵐ X = +0.0002 Y = +1.3990
})
})
})
function xyToFixed (xy, n) {
n = n || 4
return {
x: float(xy.x).toFixed(n),
y: float(xy.y).toFixed(n)
}
}
|
;(function(){
// Consider cross browser compatibility
var DOMReady = function(a,b,c){b=document,c='addEventListener';b[c]?b[c]('DOMContentLoaded',a):window.attachEvent('onload',a)}
// Some mock-jQuery helper methods, whoo!
var querySelectorAll = function(selector){
var elements = document.querySelectorAll(selector);
// Convert NodeList to Array
return [].slice.call(elements)
};
var addEventListener = function(elements, type, eventListener) {
elements.forEach(function(element){
element.addEventListener(type, eventListener);
});
}
var attr = function(element, attr) {
return element.attributes.getNamedItem(attr).value;
}
// When we are ready to remove marker from the map
var remove = function(elements) {
elements.forEach(function(element) {
if (element.parentNode)
element.parentNode.removeChild(element);
});
}
DOMReady(function() {
var map = querySelectorAll('google-map')[0];
var markers = querySelectorAll('google-map-marker');
var checkboxes = querySelectorAll('[data-drug]');
// Each time we use the checkboxes to refine display
var updateMap= function() {
// Read the state of each of the checkboxes
var filters = {};
checkboxes.forEach(function(checkbox){
var drug = attr(checkbox, 'data-drug');
filters[drug] = checkbox.checked;
});
// Remove all markers from the map to start
remove(markers);
// Add back the markers that match the checked checkboxes
var visibleMarkers = markers.filter(function(marker){
return filters[marker.className]
});
visibleMarkers.forEach(function(marker){
map.appendChild(marker);
});
};
addEventListener(checkboxes, 'change', updateMap);
// Experiment with this if have time
// _mouseEventsChanged: function() {
// if (this.map) {
// if (this.mouseEvents) {
// this._forwardEvent('mouseover');
// } else {
// this._clearListener('mouseover');
// }
// }
// },
})
})(); |
/**
* A series of helpers around the migration database.
*
* @author bshai date 8/12/15.
*/
var mysqlHelpers = require('./MysqlHelpers');
var MigrationDatabseHelpers = {
MIGRATION_TABLE: 'migration_versions',
MIGRATION_TABLE_CREATE:
"CREATE TABLE migration_versions ( " +
"table_name VARCHAR(64) NOT NULL, " +
"version INT NOT NULL DEFAULT 1, " +
"PRIMARY KEY (table_name));",
tableExists: function(connection) {
return mysqlHelpers.convertQueryToPromise(connection, "SHOW TABLES LIKE '" + this.MIGRATION_TABLE + "'")
.then(function(rows) {
return !!rows.length;
});
},
createMigrationTable: function(connection) {
return mysqlHelpers.convertQueryToPromise(connection, this.MIGRATION_TABLE_CREATE);
},
insertMigrationVersion: function(connection, table, version) {
var query = "INSERT INTO " + this.MIGRATION_TABLE + " (table_name" + (version ? ", version" : "") + ") VALUES ('" + table + (version ? "', '" + version : "") +"')";
return mysqlHelpers.convertQueryToPromise(connection, query);
}
};
module.exports = MigrationDatabseHelpers; |
/*
* grunt-util
* http://gruntjs.com/
*
* Copyright (c) 2012 "Cowboy" Ben Alman
* Licensed under the MIT license.
* https://github.com/gruntjs/grunt-util/blob/master/LICENSE-MIT
*/
'use strict';
// What "kind" is a value?
// I really need to rework https://github.com/cowboy/javascript-getclass
var kindsOf = {};
'Number String Boolean Function RegExp Array Date Error'.split(' ').forEach(function(k) {
kindsOf['[object ' + k + ']'] = k.toLowerCase();
});
module.exports = function (value) {
// Null or undefined.
if (value === null) { return String(value); }
// Everything else.
return kindsOf[kindsOf.toString.call(value)] || 'object';
};
|
$(document).ready(function(){
$('#FirstName').bind("cut copy paste",function(e) {
e.preventDefault();
});
});
$(document).ready(function(){
$('#MiddleName').bind("cut copy paste",function(e) {
e.preventDefault();
});
});
$(document).ready(function(){
$('#LastName').bind("cut copy paste",function(e) {
e.preventDefault();
});
});
$(document).ready(function(){
$('#Email').bind("cut copy paste",function(e) {
e.preventDefault();
});
});
//Modal Registration Number
$(document).ready(function(){
$('#regNo').bind("cut copy paste",function(e) {
e.preventDefault();
});
});
//Modal Sign In Password
$(document).ready(function(){
$('#password').bind("cut copy paste",function(e) {
e.preventDefault();
});
});
//Registration Form Registration Number
$(document).ready(function(){
$('#RegNo').bind("cut copy paste",function(e) {
e.preventDefault();
});
});
//Registration Form Password
$(document).ready(function(){
$('#Password').bind("cut copy paste",function(e) {
e.preventDefault();
});
});
$(document).ready(function(){
$('#ConfirmPassword').bind("cut copy paste",function(e) {
e.preventDefault();
});
});
|
module.exports = {
entry: './src/index.js',
output: {
path: './dist',
filename: `bundle.js`,
},
resolve: ['', '.js', '.jsx'],
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel'
},
{
test : /\.css$/,
loader : "style-loader!css-loader!postcss-loader!"
},
{
test : /\.json$/,
loader : "json-loader"
},
{
test : /\.(png|jpg|svg|eot|ttf|woff|woff2)$/,
loader : "url-loader"
}
],
},
babel: {
"presets": ['es2015','stage-0','react']
}
}
|
'use strict';
const _ = require('lodash');
function populateValues (object, map) {
if (!map) {
map = {};
}
return _.mapValues(object, value => {
if (typeof value === 'string') {
_.forIn(map, function (v, k) {
value = value.replace(new RegExp(k, 'g'), v);
});
return value;
} else if (Array.isArray(value)) {
return _.map(value, item => {
if (typeof item === 'object') {
return populateValues(item, map);
} else if (typeof item === 'string') {
_.forIn(map, function (v, k) {
item = item.replace(new RegExp(k, 'g'), v);
});
return item;
} else {
return item;
}
});
} else if (typeof value === 'object') {
return populateValues(value, map);
} else {
return value;
}
});
}
function populateTemplate (object, map) {
if (!map) {
map = {};
}
map = mapKeysRegExp(map);
return populateValues(object, map);
}
function mapKeysRegExp (object) {
return _.mapKeys(object, (v, k) => {
if (/^\$\{.*\}$/.test(k)) {
return _.escapeRegExp(k);
} else {
return _.escapeRegExp('${' + k + '}');
}
});
}
module.exports = { populateTemplate, populateValues, mapKeysRegExp };
|
define(["require", "exports", '../../../unitTesting/grid/base', '../column-chooser', '../column-reordering', '../toolbox'], function (require, exports, base_1, column_chooser_1, column_reordering_1, toolbox_1) {
"use strict";
describe('Column chooser component', function () {
var h;
var columns;
var getComponent = function (codeBased, domBased) {
if (codeBased === void 0) { codeBased = { columnChooser: true }; }
if (domBased === void 0) { domBased = ""; }
var gridOptions = h.getGridOptions(codeBased, domBased + "<columns><column field=\"FirstName\"></column><column field=\"LastName\"></column><column field=\"Age\"></column></column><column field=\"DateOfBirth\"></column></columns>");
gridOptions.columns = [columns.firstName, columns.lastName, columns.age];
var subject = new column_chooser_1.ColumnChooserComponent(h.gridInternals, gridOptions, h.components);
subject.tryEnable();
return subject;
};
var reorderingRegistration;
var toolboxRegistration;
beforeEach(function () {
h = new base_1.GridTestHelpers();
h.beforeEach();
columns = {
firstName: h.getColumn({
field: 'FirstName'
}),
lastName: h.getColumn({
field: 'LastName',
hidden: true
}),
age: h.getColumn({
field: 'Age',
hidden: true
}),
dateOfBirth: h.getColumn({
field: 'DateOfBirth'
})
};
columns.lastName.owner = column_chooser_1.ColumnChooserComponent;
columns.age.owner = column_chooser_1.ColumnChooserComponent;
h.gridInternals.mainColumns = [columns.firstName, columns.dateOfBirth];
reorderingRegistration = {
enable: sinon.spy()
};
toolboxRegistration = {
instance: {
addButton: sinon.spy()
},
enable: sinon.spy()
};
h.components.get.for(column_reordering_1.ColumnReorderingComponent, reorderingRegistration);
h.components.get.for(toolbox_1.ToolboxComponent, toolboxRegistration);
});
describe('on init', function () {
it('should enable ColumnReorderingComponent', function () {
var component = getComponent();
expect(reorderingRegistration.enable.calledOnce).toBe(true);
});
it('should make columns draggable', function () {
var component = getComponent();
expect(h.gridInternals.makeColumnsDraggable.called).toBe(true);
});
it('should initialize toolbox', function () {
var component = getComponent();
component.togglePopUp = sinon.spy();
expect(toolboxRegistration.instance.addButton.calledOnce).toBe(true);
var arg = toolboxRegistration.instance.addButton.firstCall.args[0];
arg.click();
expect(arg.text).toBeTruthy();
expect(component.togglePopUp.calledOnce).toBe(true);
});
it('should enable toolbox automaticaly if autoToolboxInit enabled', function () {
var component = getComponent({ columnChooser: { autoToolboxInit: true } });
expect(toolboxRegistration.enable.calledOnce).toBe(true);
});
it("shouldn't enable toolbox automaticaly if autoToolboxInit disabled", function () {
var component = getComponent({ columnChooser: { autoToolboxInit: false } });
expect(toolboxRegistration.enable.called).toBe(false);
});
it('should take all hidden columns', function () {
var component = getComponent();
expect(component.columns.length).toBe(2);
expect(component.columns).toContain(columns.lastName);
expect(component.columns).toContain(columns.age);
});
});
describe('save state', function () {
it('should attach columns to state', function () {
var component = getComponent();
var state = {};
component.saveState(state);
expect(state.columns).toEqual([columns.lastName.getUniqueId(), columns.age.getUniqueId()]);
});
});
describe('load state', function () {
it('load columns from state', function () {
var component = getComponent();
var state = {
columns: [columns.age.getUniqueId(), columns.firstName.getUniqueId()]
};
component.loadState(state);
expect(component.columns).toEqual([columns.age, columns.firstName]);
expect(component.columns.map(function (x) { return x.owner; })).toEqual([column_chooser_1.ColumnChooserComponent, column_chooser_1.ColumnChooserComponent]);
});
});
describe('should be able to react on ColumnOwnerChanged event', function () {
it('by removing item from columns array and marking it as not hidden any more', function () {
var component = getComponent();
columns.lastName.owner = toolbox_1.ToolboxComponent;
var msg = { column: columns.lastName };
expect(columns.lastName.hidden).toBe(true);
h.gridInternals.subscribe.emit('ColumnOwnerChanged', msg);
expect(columns.lastName.hidden).toBe(false);
expect(component.columns).toEqual([columns.age]);
});
it('and do nothing if column owner is still column chooser', function () {
var component = getComponent();
var msg = { column: columns.lastName };
var length = component.columns.length;
expect(columns.lastName.hidden).toBe(true);
h.gridInternals.subscribe.emit('ColumnOwnerChanged', msg);
expect(columns.lastName.hidden).toBe(true);
expect(component.columns.length).toEqual(length);
});
});
describe('should react on columns drag and drop', function () {
it('dropped should change owner of column', function () {
var component = getComponent();
component.overDroppable = true;
columns.firstName.setOwner = sinon.spy();
h.gridInternals.listenOnDragAndDrop.dropped(undefined, undefined, columns.firstName);
expect(columns.firstName.setOwner.calledWithExactly(column_chooser_1.ColumnChooserComponent)).toBe(true);
});
it('dropped should change owner of column only if main grid has at least 2 columns', function () {
var component = getComponent();
component.overDroppable = true;
columns.firstName.setOwner = sinon.spy();
h.gridInternals.mainColumns.splice(1);
h.gridInternals.listenOnDragAndDrop.dropped(undefined, undefined, columns.firstName);
expect(columns.firstName.setOwner.called).toBe(false);
});
it('dropped should change owner of column only column does not belong already to column chooser', function () {
var component = getComponent();
component.overDroppable = true;
columns.lastName.setOwner = sinon.spy();
h.gridInternals.listenOnDragAndDrop.dropped(undefined, undefined, columns.lastName);
expect(columns.lastName.setOwner.called).toBe(false);
});
it('dropped should change overDroppable state', function () {
var component = getComponent();
component.overDroppable = true;
h.gridInternals.listenOnDragAndDrop.dropped(undefined, undefined, columns.lastName);
expect(component.overDroppable).toBe(false);
});
it('dropped should move column from main to column chooser', function () {
var component = getComponent();
component.overDroppable = true;
expect(h.gridInternals.mainColumns).toContain(columns.firstName);
expect(component.columns).not.toContain(columns.firstName);
expect(columns.firstName.hidden).toBeFalsy();
h.gridInternals.listenOnDragAndDrop.dropped(undefined, undefined, columns.firstName);
expect(h.gridInternals.mainColumns).not.toContain(columns.firstName);
expect(component.columns).toContain(columns.firstName);
expect(columns.firstName.hidden).toBe(true);
});
it('dropped should maintain columns sorted', function () {
var component = getComponent();
component.overDroppable = true;
expect(component.columns).not.toContain(columns.firstName);
h.gridInternals.listenOnDragAndDrop.dropped(undefined, undefined, columns.firstName);
expect(component.columns).toEqual([columns.age, columns.firstName, columns.lastName]);
});
it('overDroppable should change state if column is not already in the column chooser', function () {
var component = getComponent();
component.overDroppable = false;
h.gridInternals.listenOnDragAndDrop.overDroppable(undefined, undefined, columns.firstName);
expect(component.overDroppable).toBe(true);
});
it('overDroppable should not change state if column is already in the column chooser', function () {
var component = getComponent();
component.overDroppable = false;
h.gridInternals.listenOnDragAndDrop.overDroppable(undefined, undefined, columns.lastName);
expect(component.overDroppable).toBe(false);
});
it('outsideDroppable should change overDroppable state', function () {
var component = getComponent();
component.overDroppable = true;
h.gridInternals.listenOnDragAndDrop.outsideDroppable(undefined, undefined, columns.lastName);
expect(component.overDroppable).toBe(false);
});
it('canceled should change overDroppable state', function () {
var component = getComponent();
component.overDroppable = true;
h.gridInternals.listenOnDragAndDrop.canceled(undefined, undefined, columns.lastName);
expect(component.overDroppable).toBe(false);
});
});
describe('togglePopUp method', function () {
it('should show popup if hidden', function () {
var component = getComponent();
component.hidden = true;
component.togglePopUp();
expect(component.hidden).toBe(false);
});
it('should hide popup if visible', function () {
var component = getComponent();
component.hidden = false;
component.togglePopUp();
expect(component.hidden).toBe(true);
});
});
describe('should be able to create options', function () {
it('from code based settings', function () {
var component = getComponent({ columnChooser: {
autoToolboxInit: false
} }, "");
expect(component.options).not.toEqual(component.defaultOptions);
expect(component.options).toEqual({
autoToolboxInit: false
});
});
it('from DOM based settings', function () {
var component = getComponent({}, "<column-chooser auto-toolbox-init.bind=\"false\"></column-chooser>");
expect(component.options).not.toEqual(component.defaultOptions);
expect(component.options).toEqual({
autoToolboxInit: false
});
});
it('using default options as a fallback plan', function () {
var component = getComponent({ columnChooser: true }, "");
expect(component.options).toEqual(component.defaultOptions);
});
it('when configuration is not available', function () {
var pagination = getComponent({}, "");
var options = pagination.createOptions();
expect(options).toBeFalsy();
});
});
it('should unregister correctly', function () {
var component = getComponent();
expect(h.gridInternals.subscribe.subscribers.length).toBeGreaterThan(0);
component.stop();
expect(h.gridInternals.subscribe.subscribers.length).toBe(0);
});
});
});
|
'use strict';
/**
* Module dependencies.
*/
var acl = require('acl');
// Using the memory backend
acl = new acl(new acl.memoryBackend());
/**
* Invoke Restaurants Permissions
*/
exports.invokeRolesPolicies = function() {
acl.allow([{
roles: ['admin'],
allows: [{
resources: '/api/restaurants',
permissions: '*'
}, {
resources: '/api/restaurants/:restaurantId',
permissions: '*'
}]
}, {
roles: ['user'],
allows: [{
resources: '/api/restaurants',
permissions: ['get', 'post']
}, {
resources: '/api/restaurants/:restaurantId',
permissions: ['get']
}]
}, {
roles: ['guest'],
allows: [{
resources: '/api/restaurants',
permissions: ['get']
}, {
resources: '/api/restaurants/:restaurantId',
permissions: ['get']
}]
}]);
};
/**
* Check If Articles Policy Allows
*/
exports.isAllowed = function(req, res, next) {
var roles = (req.user) ? req.user.roles : ['guest'];
// If an restaurant is being processed and the current user created it then allow any manipulation
if (req.restaurant && req.user && req.restaurant.user.id === req.user.id) {
return next();
}
// Check for user roles
acl.areAnyRolesAllowed(roles, req.route.path, req.method.toLowerCase(), function(err, isAllowed) {
if (err) {
// An authorization error occurred.
return res.status(500).send('Unexpected authorization error');
} else {
if (isAllowed) {
// Access granted! Invoke next middleware
return next();
} else {
return res.status(403).json({
message: 'User is not authorized'
});
}
}
});
};
|
/**
* Created by cecheveria on 2/9/14.
*/
function Page(page) {
this.page = [];
this.totalRows = 0;
this.totalPages = 0;
this.pageNumber = 0;
this.pageSize = 0;
if (page) {
this.page = page.page ? page.page : [];
this.totalRows = page.totalRows ? page.totalRows : 0;
this.totalPages = page.totalPages ? page.totalPages : 0;
this.pageNumber = page.pageNumber ? page.pageNumber : 0;
this.pageSize = page.pageSize ? page.pageSize : 0;
}
}
Page.create = function (page) { return new Page(page); }
function ResponseBase(response) {
this.data = "";
this.error = 0;
this.msg = "";
if (response) {
this.error = response.error ? response.error : 0;
this.msg = response.msg ? response.msg : "";
this.data = response.data ? response.data : "";
}
}
ResponseBase.create = function (response) { return new ResponseBase(response); }
function ResponsePage(page) {
this.data = Page.create();
this.error = 0;
this.msg = "";
if (page) {
/*if(Object.prototype.toString.call( page ) == "[object Array]") {
}
else {*/
this.data.page = page.page ? page.page : [];
this.data.totalRows = page.totalRows ? page.totalRows : 0;
this.data.totalPages = page.totalPages ? page.totalPages : 0;
this.data.pageNumber = page.pageNumber ? page.pageNumber : 0;
this.data.pageSize = page.pageSize ? page.pageSize : 0;
//}
}
}
ResponsePage.create = function (page) { return new ResponsePage(page); }
function PageHelper() {
}
PageHelper.create = function () { return new PageHelper(); }
PageHelper.prototype.getPage = function (data, pageSize, pageNumber, fromIndex) {
//
var responsePage = ResponsePage.create();
if(!data || data.length == 0) {
responsePage.data.page = [];
responsePage.data.totalRows = 0;
responsePage.data.totalPages = 0;
responsePage.data.pageNumber = 0;
responsePage.data.pageSize = 0;
responsePage.error = !data ? 1 : 0;
responsePage.msg = !data ? "Undefined data" : "";
}
else {
if(pageNumber <= 0) {
/**
* No tenemos parametro pageNumber, entonces enviamos todod el buffer
*/
//responsePage.page = data;
responsePage.error = 1;
responsePage.msg = "Page does not exists, it must be great than cero";
}
else {
var totalPages = 0;
//
//totalPages = (int) (pageSize == 1 ? data.size() : (int)(Math.round(((float)data.size()/pageSize) + .499)));
totalPages = pageSize == 1 ? data.length : (data.length/pageSize) + .499;
totalPages = Math.round(totalPages);
/**
* return page using pageNumber parameter
*/
if(pageNumber > totalPages) {
responsePage.data.page = [];
responsePage.error = 1;
responsePage.msg = "Page does not exists, it must be less or equal than " + totalPages;
}
else {
fromIndex = (pageNumber-1) * pageSize;
var toIndex = fromIndex + pageSize < data.length ? fromIndex + pageSize : data.length;
//responsePage.page = data.subList(fromIndex, toIndex);
responsePage.data.page = data.slice(fromIndex, toIndex);
}
responsePage.data.totalRows = data.length;
responsePage.data.totalPages = Math.round(totalPages);
responsePage.data.pageNumber = pageNumber;
responsePage.data.pageSize = pageSize;
}
}
return responsePage;
}
module.exports.Page = Page;
module.exports.ResponseBase = ResponseBase;
module.exports.ResponsePage = ResponsePage;
module.exports.PageHelper = PageHelper; |
/*
* Copyright (c) 2012 Dmitri Melikyan
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
module.exports = function(nt) {
nt.on('sample', function(sample) {
console.log(indent({sample: sample}));
});
};
function indent(obj, depth) {
if(!depth) depth = 0;
if(depth > 20) return '';
var tab = '';
for(var i = 0; i < depth; i++) tab += "\t";
var str = ''
var arr = Array.isArray(obj);
for(var prop in obj) {
var val = obj[prop];
if(val == undefined || prop.match(/^_/)) continue;
var label = val._label || (arr ? ('[' + prop + ']') : prop);
if(typeof val === 'string' || typeof val === 'number') {
str += tab + label + ': \033[33m' + val + '\033[0m\n';
}
else if(typeof val === 'object') {
str += tab + '\033[1m' + label + '\033[0m\n';
str += indent(val, depth + 1);
}
}
return str;
}
|
'use strict'
const test = require('ava')
let h = require('../lib/helpers')
let fakeSpawn = function (closeVal) {
return {
stderr: {
on: function (str, cb) {
cb(str)
}
},
on: function (str, cb) {
cb(closeVal)
}
}
}
test('#promisify() should return a promise', function (t) {
return h.promisify(fakeSpawn(0)).then(function () {
t.pass()
})
})
test('#promisify() should fail promise if child process errors', function (t) {
return h.promisify(fakeSpawn(1)).catch(function () {
t.pass()
})
})
test('#promisify() should fail promise if error is is caught', function (t) {
return h.promisify().catch(function () {
t.pass()
})
})
|
/* jshint node: true, esversion: 6 */
'use strict';
const router = require("express").Router();
const Invoice = require("../models/invoice");
const { requireLogin, requireToken } = require("../services/auth");
router.get("/", (req, res) => {
res.json({ version: 1 });
});
router.post("/", requireToken, (req, res) => {
const invoiceData = req.body;
const sender = req.user;
const recipientId = invoiceData.recipient;
const recipient = req.user.contacts.reduce((acc, contact) => (contact._id == recipientId) ? contact : acc, undefined);
invoiceData.sender = sender;
invoiceData.recipient = recipient;
//console.log(invoiceData);
var invoice = new Invoice(invoiceData);
invoice.save().then((filename) => {
res.json({
status: 'ok',
filename: filename
});
}, (err) => {
res.json(err);
});
});
router.post("/login", requireLogin, (req, res) => {
res.send({
token: req.user.token()
});
});
module.exports = router; |
var http = require('http')
, https = require('https')
, url = require('url')
, Serializer = require('./serializer')
, Deserializer = require('./deserializer')
, Cookies = require('./cookies');
/**
* Creates a Client object for making XML-RPC method calls.
*
* @constructor
* @param {Object|String} options - Server options to make the HTTP request to.
* Either a URI string
* (e.g. 'http://localhost:9090') or an object
* with fields:
* - {String} host - (optional)
* - {Number} port
* - {String} url - (optional) - may be used instead of host/port pair
* - {Boolean} cookies - (optional) - if true then cookies returned by server will be stored and sent back on the next calls.
* Also it will be possible to access/manipulate cookies via #setCookie/#getCookie methods
* @param {Boolean} isSecure - True if using https for making calls,
* otherwise false.
* @return {Client}
*/
function Client(options, isSecure) {
// Invokes with new if called without
if (false === (this instanceof Client)) {
return new Client(options, isSecure);
}
// If a string URI is passed in, converts to URI fields
if (typeof options === 'string') {
options = url.parse(options);
options.host = options.hostname;
options.path = options.pathname;
}
if (typeof options.url !== 'undefined') {
var parsedUrl = url.parse(options.url);
options.host = parsedUrl.hostname;
options.path = parsedUrl.pathname;
options.port = parsedUrl.port;
}
// Set the HTTP request headers
var headers = {
'User-Agent': 'NodeJS XML-RPC Client', 'Content-Type': 'text/xml', 'Accept': 'text/xml', 'Accept-Charset': 'UTF8', 'Connection': 'Keep-Alive'
};
options.headers = options.headers || {};
if (options.headers.Authorization == null &&
options.basic_auth != null &&
options.basic_auth.user != null &&
options.basic_auth.pass != null) {
var auth = options.basic_auth.user + ':' + options.basic_auth.pass;
options.headers['Authorization'] = 'Basic ' + new Buffer(auth).toString('base64');
}
for (var attribute in headers) {
if (options.headers[attribute] === undefined) {
options.headers[attribute] = headers[attribute];
}
}
options.method = 'POST';
this.options = options;
this.isSecure = isSecure;
this.headersProcessors = {
processors: [],
composeRequest: function(headers) {
this.processors.forEach(function(p) {
p.composeRequest(headers);
})
},
parseResponse: function(headers) {
this.processors.forEach(function(p) {
p.parseResponse(headers);
})
}
};
if (options.cookies) {
this.cookies = new Cookies();
this.headersProcessors.processors.unshift(this.cookies);
}
}
/**
* Makes an XML-RPC call to the server specified by the constructor's options.
*
* @param {String} method - The method name.
* @param {Array} params - Params to send in the call.
* @param {Function} callback - function(error, value) { ... }
* - {Object|null} error - Any errors when making the call, otherwise null.
* - {mixed} value - The value returned in the method response.
*/
Client.prototype.methodCall = function methodCall(method, params, callback) {
var xml = Serializer.serializeMethodCall(method, params)
, transport = this.isSecure ? https : http
, options = this.options;
options.headers['Content-Length'] = Buffer.byteLength(xml, 'utf8');
this.headersProcessors.composeRequest(options.headers);
var callback_handled = false;
var request = transport.request(options, function(response) {
callback_handled = true;
if (response.statusCode == 404) {
callback(new Error('Not Found'));
} else {
this.headersProcessors.parseResponse(response.headers);
var deserializer = new Deserializer(options.responseEncoding);
deserializer.deserializeMethodResponse(response, callback);
}
}.bind(this));
request.on('error', function(){
callback();
});
request.write(xml, 'utf8');
request.end();
};
/**
* Gets the cookie value by its name. The latest value received from servr with 'Set-Cookie' header is returned
* Note that method throws an error if cookies were not turned on during client creation (see comments for constructor)
*
* @param {String} name name of the cookie to be obtained or changed
* @return {*} cookie's value
*/
Client.prototype.getCookie = function getCookie(name) {
if (!this.cookies) {
throw 'Cookies support is not turned on for this client instance';
}
return this.cookies.get(name);
};
/**
* Sets the cookie value by its name. The cookie will be sent to the server during the next xml-rpc call.
* The method returns client itself, so it is possible to chain calls like the following:
*
* <code>
* client.cookie('login', 'alex').cookie('password', '123');
* </code>
*
* Note that method throws an error if cookies were not turned on during client creation (see comments for constructor)
*
* @param {String} name name of the cookie to be changed
* @param {String} value value to be set.
* @return {*} client object itself
*/
Client.prototype.setCookie = function setCookie(name, value) {
if (!this.cookies) {
throw 'Cookies support is not turned on for this client instance';
}
this.cookies.set(name, value);
return this;
};
module.exports = Client;
|
/* */
var Url = require("url");
var Code = require("code");
var Hawk = require("../lib/index");
var Hoek = require("hoek");
var Lab = require("lab");
var Browser = require("../lib/browser");
var internals = {};
var lab = exports.lab = Lab.script();
var describe = lab.experiment;
var it = lab.test;
var expect = Code.expect;
describe('Browser', function() {
var credentialsFunc = function(id, callback) {
var credentials = {
id: id,
key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
algorithm: (id === '1' ? 'sha1' : 'sha256'),
user: 'steve'
};
return callback(null, credentials);
};
it('should generate a bewit then successfully authenticate it', function(done) {
var req = {
method: 'GET',
url: '/resource/4?a=1&b=2',
host: 'example.com',
port: 80
};
credentialsFunc('123456', function(err, credentials) {
var bewit = Browser.client.bewit('http://example.com/resource/4?a=1&b=2', {
credentials: credentials,
ttlSec: 60 * 60 * 24 * 365 * 100,
ext: 'some-app-data'
});
req.url += '&bewit=' + bewit;
Hawk.uri.authenticate(req, credentialsFunc, {}, function(err, credentials, attributes) {
expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(attributes.ext).to.equal('some-app-data');
done();
});
});
});
it('should generate a bewit then successfully authenticate it (no ext)', function(done) {
var req = {
method: 'GET',
url: '/resource/4?a=1&b=2',
host: 'example.com',
port: 80
};
credentialsFunc('123456', function(err, credentials) {
var bewit = Browser.client.bewit('http://example.com/resource/4?a=1&b=2', {
credentials: credentials,
ttlSec: 60 * 60 * 24 * 365 * 100
});
req.url += '&bewit=' + bewit;
Hawk.uri.authenticate(req, credentialsFunc, {}, function(err, credentials, attributes) {
expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
done();
});
});
});
describe('#bewit', function() {
it('returns a valid bewit value', function(done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha256'
};
var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', {
credentials: credentials,
ttlSec: 300,
localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(),
ext: 'xandyandz'
});
expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdca3NjeHdOUjJ0SnBQMVQxekRMTlBiQjVVaUtJVTl0T1NKWFRVZEc3WDloOD1ceGFuZHlhbmR6');
done();
});
it('returns a valid bewit value (explicit HTTP port)', function(done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha256'
};
var bewit = Browser.client.bewit('http://example.com:8080/somewhere/over/the/rainbow', {
credentials: credentials,
ttlSec: 300,
localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(),
ext: 'xandyandz'
});
expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdcaFpiSjNQMmNLRW80a3kwQzhqa1pBa1J5Q1p1ZWc0V1NOYnhWN3ZxM3hIVT1ceGFuZHlhbmR6');
done();
});
it('returns a valid bewit value (explicit HTTPS port)', function(done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha256'
};
var bewit = Browser.client.bewit('https://example.com:8043/somewhere/over/the/rainbow', {
credentials: credentials,
ttlSec: 300,
localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(),
ext: 'xandyandz'
});
expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdcL2t4UjhwK0xSaTdvQTRnUXc3cWlxa3BiVHRKYkR4OEtRMC9HRUwvVytTUT1ceGFuZHlhbmR6');
done();
});
it('returns a valid bewit value (null ext)', function(done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha256'
};
var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', {
credentials: credentials,
ttlSec: 300,
localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(),
ext: null
});
expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdcSUdZbUxnSXFMckNlOEN4dktQczRKbFdJQStValdKSm91d2dBUmlWaENBZz1c');
done();
});
it('errors on invalid options', function(done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha256'
};
var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', 4);
expect(bewit).to.equal('');
done();
});
it('errors on missing uri', function(done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha256'
};
var bewit = Browser.client.bewit('', {
credentials: credentials,
ttlSec: 300,
localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(),
ext: 'xandyandz'
});
expect(bewit).to.equal('');
done();
});
it('errors on invalid uri', function(done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha256'
};
var bewit = Browser.client.bewit(5, {
credentials: credentials,
ttlSec: 300,
localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(),
ext: 'xandyandz'
});
expect(bewit).to.equal('');
done();
});
it('errors on invalid credentials (id)', function(done) {
var credentials = {
key: '2983d45yun89q',
algorithm: 'sha256'
};
var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', {
credentials: credentials,
ttlSec: 3000,
ext: 'xandyandz'
});
expect(bewit).to.equal('');
done();
});
it('errors on missing credentials', function(done) {
var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', {
ttlSec: 3000,
ext: 'xandyandz'
});
expect(bewit).to.equal('');
done();
});
it('errors on invalid credentials (key)', function(done) {
var credentials = {
id: '123456',
algorithm: 'sha256'
};
var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', {
credentials: credentials,
ttlSec: 3000,
ext: 'xandyandz'
});
expect(bewit).to.equal('');
done();
});
it('errors on invalid algorithm', function(done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'hmac-sha-0'
};
var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', {
credentials: credentials,
ttlSec: 300,
ext: 'xandyandz'
});
expect(bewit).to.equal('');
done();
});
it('errors on missing options', function(done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'hmac-sha-0'
};
var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow');
expect(bewit).to.equal('');
done();
});
});
it('generates a header then successfully parse it (configuration)', function(done) {
var req = {
method: 'GET',
url: '/resource/4?filter=a',
host: 'example.com',
port: 8080
};
credentialsFunc('123456', function(err, credentials) {
req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, {
credentials: credentials,
ext: 'some-app-data'
}).field;
expect(req.authorization).to.exist();
Hawk.server.authenticate(req, credentialsFunc, {}, function(err, credentials, artifacts) {
expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
done();
});
});
});
it('generates a header then successfully parse it (node request)', function(done) {
var req = {
method: 'POST',
url: '/resource/4?filter=a',
headers: {
host: 'example.com:8080',
'content-type': 'text/plain;x=y'
}
};
var payload = 'some not so random text';
credentialsFunc('123456', function(err, credentials) {
var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, {
credentials: credentials,
ext: 'some-app-data',
payload: payload,
contentType: req.headers['content-type']
});
req.headers.authorization = reqHeader.field;
Hawk.server.authenticate(req, credentialsFunc, {}, function(err, credentials, artifacts) {
expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true);
var res = {
headers: {'content-type': 'text/plain'},
getResponseHeader: function(header) {
return res.headers[header.toLowerCase()];
}
};
res.headers['server-authorization'] = Hawk.server.header(credentials, artifacts, {
payload: 'some reply',
contentType: 'text/plain',
ext: 'response-specific'
});
expect(res.headers['server-authorization']).to.exist();
expect(Browser.client.authenticate(res, credentials, artifacts, {payload: 'some reply'})).to.equal(true);
done();
});
});
});
it('generates a header then successfully parse it (browserify)', function(done) {
var req = {
method: 'POST',
url: '/resource/4?filter=a',
headers: {
host: 'example.com:8080',
'content-type': 'text/plain;x=y'
}
};
var payload = 'some not so random text';
credentialsFunc('123456', function(err, credentials) {
var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, {
credentials: credentials,
ext: 'some-app-data',
payload: payload,
contentType: req.headers['content-type']
});
req.headers.authorization = reqHeader.field;
Hawk.server.authenticate(req, credentialsFunc, {}, function(err, credentials, artifacts) {
expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true);
var res = {
headers: {'content-type': 'text/plain'},
getHeader: function(header) {
return res.headers[header.toLowerCase()];
}
};
res.headers['server-authorization'] = Hawk.server.header(credentials, artifacts, {
payload: 'some reply',
contentType: 'text/plain',
ext: 'response-specific'
});
expect(res.headers['server-authorization']).to.exist();
expect(Browser.client.authenticate(res, credentials, artifacts, {payload: 'some reply'})).to.equal(true);
done();
});
});
});
it('generates a header then successfully parse it (time offset)', function(done) {
var req = {
method: 'GET',
url: '/resource/4?filter=a',
host: 'example.com',
port: 8080
};
credentialsFunc('123456', function(err, credentials) {
req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, {
credentials: credentials,
ext: 'some-app-data',
localtimeOffsetMsec: 100000
}).field;
expect(req.authorization).to.exist();
Hawk.server.authenticate(req, credentialsFunc, {localtimeOffsetMsec: 100000}, function(err, credentials, artifacts) {
expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
done();
});
});
});
it('generates a header then successfully parse it (no server header options)', function(done) {
var req = {
method: 'POST',
url: '/resource/4?filter=a',
headers: {
host: 'example.com:8080',
'content-type': 'text/plain;x=y'
}
};
var payload = 'some not so random text';
credentialsFunc('123456', function(err, credentials) {
var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, {
credentials: credentials,
ext: 'some-app-data',
payload: payload,
contentType: req.headers['content-type']
});
req.headers.authorization = reqHeader.field;
Hawk.server.authenticate(req, credentialsFunc, {}, function(err, credentials, artifacts) {
expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true);
var res = {
headers: {'content-type': 'text/plain'},
getResponseHeader: function(header) {
return res.headers[header.toLowerCase()];
}
};
res.headers['server-authorization'] = Hawk.server.header(credentials, artifacts);
expect(res.headers['server-authorization']).to.exist();
expect(Browser.client.authenticate(res, credentials, artifacts)).to.equal(true);
done();
});
});
});
it('generates a header then successfully parse it (no server header)', function(done) {
var req = {
method: 'POST',
url: '/resource/4?filter=a',
headers: {
host: 'example.com:8080',
'content-type': 'text/plain;x=y'
}
};
var payload = 'some not so random text';
credentialsFunc('123456', function(err, credentials) {
var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, {
credentials: credentials,
ext: 'some-app-data',
payload: payload,
contentType: req.headers['content-type']
});
req.headers.authorization = reqHeader.field;
Hawk.server.authenticate(req, credentialsFunc, {}, function(err, credentials, artifacts) {
expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true);
var res = {
headers: {'content-type': 'text/plain'},
getResponseHeader: function(header) {
return res.headers[header.toLowerCase()];
}
};
expect(Browser.client.authenticate(res, credentials, artifacts)).to.equal(true);
done();
});
});
});
it('generates a header with stale ts and successfully authenticate on second call', function(done) {
var req = {
method: 'GET',
url: '/resource/4?filter=a',
host: 'example.com',
port: 8080
};
credentialsFunc('123456', function(err, credentials) {
Browser.utils.setNtpOffset(60 * 60 * 1000);
var header = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, {
credentials: credentials,
ext: 'some-app-data'
});
req.authorization = header.field;
expect(req.authorization).to.exist();
Hawk.server.authenticate(req, credentialsFunc, {}, function(err, credentials, artifacts) {
expect(err).to.exist();
expect(err.message).to.equal('Stale timestamp');
var res = {
headers: {'www-authenticate': err.output.headers['WWW-Authenticate']},
getResponseHeader: function(header) {
return res.headers[header.toLowerCase()];
}
};
expect(Browser.utils.getNtpOffset()).to.equal(60 * 60 * 1000);
expect(Browser.client.authenticate(res, credentials, header.artifacts)).to.equal(true);
expect(Browser.utils.getNtpOffset()).to.equal(0);
req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, {
credentials: credentials,
ext: 'some-app-data'
}).field;
expect(req.authorization).to.exist();
Hawk.server.authenticate(req, credentialsFunc, {}, function(err, credentials, artifacts) {
expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
done();
});
});
});
});
it('generates a header with stale ts and successfully authenticate on second call (manual localStorage)', function(done) {
var req = {
method: 'GET',
url: '/resource/4?filter=a',
host: 'example.com',
port: 8080
};
credentialsFunc('123456', function(err, credentials) {
var localStorage = new Browser.internals.LocalStorage();
Browser.utils.setStorage(localStorage);
Browser.utils.setNtpOffset(60 * 60 * 1000);
var header = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, {
credentials: credentials,
ext: 'some-app-data'
});
req.authorization = header.field;
expect(req.authorization).to.exist();
Hawk.server.authenticate(req, credentialsFunc, {}, function(err, credentials, artifacts) {
expect(err).to.exist();
expect(err.message).to.equal('Stale timestamp');
var res = {
headers: {'www-authenticate': err.output.headers['WWW-Authenticate']},
getResponseHeader: function(header) {
return res.headers[header.toLowerCase()];
}
};
expect(parseInt(localStorage.getItem('hawk_ntp_offset'))).to.equal(60 * 60 * 1000);
expect(Browser.utils.getNtpOffset()).to.equal(60 * 60 * 1000);
expect(Browser.client.authenticate(res, credentials, header.artifacts)).to.equal(true);
expect(Browser.utils.getNtpOffset()).to.equal(0);
expect(parseInt(localStorage.getItem('hawk_ntp_offset'))).to.equal(0);
req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, {
credentials: credentials,
ext: 'some-app-data'
}).field;
expect(req.authorization).to.exist();
Hawk.server.authenticate(req, credentialsFunc, {}, function(err, credentials, artifacts) {
expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
done();
});
});
});
});
it('generates a header then fails to parse it (missing server header hash)', function(done) {
var req = {
method: 'POST',
url: '/resource/4?filter=a',
headers: {
host: 'example.com:8080',
'content-type': 'text/plain;x=y'
}
};
var payload = 'some not so random text';
credentialsFunc('123456', function(err, credentials) {
var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, {
credentials: credentials,
ext: 'some-app-data',
payload: payload,
contentType: req.headers['content-type']
});
req.headers.authorization = reqHeader.field;
Hawk.server.authenticate(req, credentialsFunc, {}, function(err, credentials, artifacts) {
expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true);
var res = {
headers: {'content-type': 'text/plain'},
getResponseHeader: function(header) {
return res.headers[header.toLowerCase()];
}
};
res.headers['server-authorization'] = Hawk.server.header(credentials, artifacts);
expect(res.headers['server-authorization']).to.exist();
expect(Browser.client.authenticate(res, credentials, artifacts, {payload: 'some reply'})).to.equal(false);
done();
});
});
});
it('generates a header then successfully parse it (with hash)', function(done) {
var req = {
method: 'GET',
url: '/resource/4?filter=a',
host: 'example.com',
port: 8080
};
credentialsFunc('123456', function(err, credentials) {
req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, {
credentials: credentials,
payload: 'hola!',
ext: 'some-app-data'
}).field;
Hawk.server.authenticate(req, credentialsFunc, {}, function(err, credentials, artifacts) {
expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
done();
});
});
});
it('generates a header then successfully parse it then validate payload', function(done) {
var req = {
method: 'GET',
url: '/resource/4?filter=a',
host: 'example.com',
port: 8080
};
credentialsFunc('123456', function(err, credentials) {
req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, {
credentials: credentials,
payload: 'hola!',
ext: 'some-app-data'
}).field;
Hawk.server.authenticate(req, credentialsFunc, {}, function(err, credentials, artifacts) {
expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
expect(Hawk.server.authenticatePayload('hola!', credentials, artifacts)).to.be.true();
expect(Hawk.server.authenticatePayload('hello!', credentials, artifacts)).to.be.false();
done();
});
});
});
it('generates a header then successfully parse it (app)', function(done) {
var req = {
method: 'GET',
url: '/resource/4?filter=a',
host: 'example.com',
port: 8080
};
credentialsFunc('123456', function(err, credentials) {
req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, {
credentials: credentials,
ext: 'some-app-data',
app: 'asd23ased'
}).field;
Hawk.server.authenticate(req, credentialsFunc, {}, function(err, credentials, artifacts) {
expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
expect(artifacts.app).to.equal('asd23ased');
done();
});
});
});
it('generates a header then successfully parse it (app, dlg)', function(done) {
var req = {
method: 'GET',
url: '/resource/4?filter=a',
host: 'example.com',
port: 8080
};
credentialsFunc('123456', function(err, credentials) {
req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, {
credentials: credentials,
ext: 'some-app-data',
app: 'asd23ased',
dlg: '23434szr3q4d'
}).field;
Hawk.server.authenticate(req, credentialsFunc, {}, function(err, credentials, artifacts) {
expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
expect(artifacts.app).to.equal('asd23ased');
expect(artifacts.dlg).to.equal('23434szr3q4d');
done();
});
});
});
it('generates a header then fail authentication due to bad hash', function(done) {
var req = {
method: 'GET',
url: '/resource/4?filter=a',
host: 'example.com',
port: 8080
};
credentialsFunc('123456', function(err, credentials) {
req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, {
credentials: credentials,
payload: 'hola!',
ext: 'some-app-data'
}).field;
Hawk.server.authenticate(req, credentialsFunc, {payload: 'byebye!'}, function(err, credentials, artifacts) {
expect(err).to.exist();
expect(err.output.payload.message).to.equal('Bad payload hash');
done();
});
});
});
it('generates a header for one resource then fail to authenticate another', function(done) {
var req = {
method: 'GET',
url: '/resource/4?filter=a',
host: 'example.com',
port: 8080
};
credentialsFunc('123456', function(err, credentials) {
req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, {
credentials: credentials,
ext: 'some-app-data'
}).field;
req.url = '/something/else';
Hawk.server.authenticate(req, credentialsFunc, {}, function(err, credentials, artifacts) {
expect(err).to.exist();
expect(credentials).to.exist();
done();
});
});
});
describe('client', function() {
describe('#header', function() {
it('returns a valid authorization header (sha1)', function(done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha1'
};
var header = Browser.client.header('http://example.net/somewhere/over/the/rainbow', 'POST', {
credentials: credentials,
ext: 'Bazinga!',
timestamp: 1353809207,
nonce: 'Ygvqdz',
payload: 'something to write about'
}).field;
expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="bsvY3IfUllw6V5rvk4tStEvpBhE=", ext="Bazinga!", mac="qbf1ZPG/r/e06F4ht+T77LXi5vw="');
done();
});
it('returns a valid authorization header (sha256)', function(done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha256'
};
var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', {
credentials: credentials,
ext: 'Bazinga!',
timestamp: 1353809207,
nonce: 'Ygvqdz',
payload: 'something to write about',
contentType: 'text/plain'
}).field;
expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", ext="Bazinga!", mac="q1CwFoSHzPZSkbIvl0oYlD+91rBUEvFk763nMjMndj8="');
done();
});
it('returns a valid authorization header (empty payload)', function(done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha1'
};
var header = Browser.client.header('http://example.net/somewhere/over/the/rainbow', 'POST', {
credentials: credentials,
ext: 'Bazinga!',
timestamp: 1353809207,
nonce: 'Ygvqdz',
payload: ''
}).field;
expect(header).to.equal('Hawk id=\"123456\", ts=\"1353809207\", nonce=\"Ygvqdz\", hash=\"404ghL7K+hfyhByKKejFBRGgTjU=\", ext=\"Bazinga!\", mac=\"Bh1sj1DOfFRWOdi3ww52nLCJdBE=\"');
done();
});
it('returns a valid authorization header (no ext)', function(done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha256'
};
var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', {
credentials: credentials,
timestamp: 1353809207,
nonce: 'Ygvqdz',
payload: 'something to write about',
contentType: 'text/plain'
}).field;
expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="');
done();
});
it('returns a valid authorization header (null ext)', function(done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha256'
};
var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', {
credentials: credentials,
timestamp: 1353809207,
nonce: 'Ygvqdz',
payload: 'something to write about',
contentType: 'text/plain',
ext: null
}).field;
expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="');
done();
});
it('returns a valid authorization header (uri object)', function(done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha256'
};
var uri = Browser.utils.parseUri('https://example.net/somewhere/over/the/rainbow');
var header = Browser.client.header(uri, 'POST', {
credentials: credentials,
timestamp: 1353809207,
nonce: 'Ygvqdz',
payload: 'something to write about',
contentType: 'text/plain'
}).field;
expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="');
done();
});
it('errors on missing options', function(done) {
var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST');
expect(header.field).to.equal('');
expect(header.err).to.equal('Invalid argument type');
done();
});
it('errors on empty uri', function(done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha256'
};
var header = Browser.client.header('', 'POST', {
credentials: credentials,
timestamp: 1353809207,
nonce: 'Ygvqdz',
payload: 'something to write about',
contentType: 'text/plain'
});
expect(header.field).to.equal('');
expect(header.err).to.equal('Invalid argument type');
done();
});
it('errors on invalid uri', function(done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha256'
};
var header = Browser.client.header(4, 'POST', {
credentials: credentials,
timestamp: 1353809207,
nonce: 'Ygvqdz',
payload: 'something to write about',
contentType: 'text/plain'
});
expect(header.field).to.equal('');
expect(header.err).to.equal('Invalid argument type');
done();
});
it('errors on missing method', function(done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha256'
};
var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', '', {
credentials: credentials,
timestamp: 1353809207,
nonce: 'Ygvqdz',
payload: 'something to write about',
contentType: 'text/plain'
});
expect(header.field).to.equal('');
expect(header.err).to.equal('Invalid argument type');
done();
});
it('errors on invalid method', function(done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha256'
};
var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 5, {
credentials: credentials,
timestamp: 1353809207,
nonce: 'Ygvqdz',
payload: 'something to write about',
contentType: 'text/plain'
});
expect(header.field).to.equal('');
expect(header.err).to.equal('Invalid argument type');
done();
});
it('errors on missing credentials', function(done) {
var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', {
ext: 'Bazinga!',
timestamp: 1353809207
});
expect(header.field).to.equal('');
expect(header.err).to.equal('Invalid credentials object');
done();
});
it('errors on invalid credentials (id)', function(done) {
var credentials = {
key: '2983d45yun89q',
algorithm: 'sha256'
};
var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', {
credentials: credentials,
ext: 'Bazinga!',
timestamp: 1353809207
});
expect(header.field).to.equal('');
expect(header.err).to.equal('Invalid credentials object');
done();
});
it('errors on invalid credentials (key)', function(done) {
var credentials = {
id: '123456',
algorithm: 'sha256'
};
var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', {
credentials: credentials,
ext: 'Bazinga!',
timestamp: 1353809207
});
expect(header.field).to.equal('');
expect(header.err).to.equal('Invalid credentials object');
done();
});
it('errors on invalid algorithm', function(done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'hmac-sha-0'
};
var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', {
credentials: credentials,
payload: 'something, anything!',
ext: 'Bazinga!',
timestamp: 1353809207
});
expect(header.field).to.equal('');
expect(header.err).to.equal('Unknown algorithm');
done();
});
it('uses a pre-calculated payload hash', function(done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha256'
};
var options = {
credentials: credentials,
ext: 'Bazinga!',
timestamp: 1353809207,
nonce: 'Ygvqdz',
payload: 'something to write about',
contentType: 'text/plain'
};
options.hash = Browser.crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', options).field;
expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", ext="Bazinga!", mac="q1CwFoSHzPZSkbIvl0oYlD+91rBUEvFk763nMjMndj8="');
done();
});
});
describe('#authenticate', function() {
it('skips tsm validation when missing ts', function(done) {
var res = {
headers: {'www-authenticate': 'Hawk error="Stale timestamp"'},
getResponseHeader: function(header) {
return res.headers[header.toLowerCase()];
}
};
var credentials = {
id: '123456',
key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
algorithm: 'sha256',
user: 'steve'
};
var artifacts = {
ts: 1402135580,
nonce: 'iBRB6t',
method: 'GET',
resource: '/resource/4?filter=a',
host: 'example.com',
port: '8080',
ext: 'some-app-data'
};
expect(Browser.client.authenticate(res, credentials, artifacts)).to.equal(true);
done();
});
it('returns false on invalid header', function(done) {
var res = {
headers: {'server-authorization': 'Hawk mac="abc", bad="xyz"'},
getResponseHeader: function(header) {
return res.headers[header.toLowerCase()];
}
};
expect(Browser.client.authenticate(res, {})).to.equal(false);
done();
});
it('returns false on invalid mac', function(done) {
var res = {
headers: {
'content-type': 'text/plain',
'server-authorization': 'Hawk mac="_IJRsMl/4oL+nn+vKoeVZPdCHXB4yJkNnBbTbHFZUYE=", hash="f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=", ext="response-specific"'
},
getResponseHeader: function(header) {
return res.headers[header.toLowerCase()];
}
};
var artifacts = {
method: 'POST',
host: 'example.com',
port: '8080',
resource: '/resource/4?filter=a',
ts: '1362336900',
nonce: 'eb5S_L',
hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
ext: 'some-app-data',
app: undefined,
dlg: undefined,
mac: 'BlmSe8K+pbKIb6YsZCnt4E1GrYvY1AaYayNR82dGpIk=',
id: '123456'
};
var credentials = {
id: '123456',
key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
algorithm: 'sha256',
user: 'steve'
};
expect(Browser.client.authenticate(res, credentials, artifacts)).to.equal(false);
done();
});
it('returns true on ignoring hash', function(done) {
var res = {
headers: {
'content-type': 'text/plain',
'server-authorization': 'Hawk mac="XIJRsMl/4oL+nn+vKoeVZPdCHXB4yJkNnBbTbHFZUYE=", hash="f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=", ext="response-specific"'
},
getResponseHeader: function(header) {
return res.headers[header.toLowerCase()];
}
};
var artifacts = {
method: 'POST',
host: 'example.com',
port: '8080',
resource: '/resource/4?filter=a',
ts: '1362336900',
nonce: 'eb5S_L',
hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
ext: 'some-app-data',
app: undefined,
dlg: undefined,
mac: 'BlmSe8K+pbKIb6YsZCnt4E1GrYvY1AaYayNR82dGpIk=',
id: '123456'
};
var credentials = {
id: '123456',
key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
algorithm: 'sha256',
user: 'steve'
};
expect(Browser.client.authenticate(res, credentials, artifacts)).to.equal(true);
done();
});
it('errors on invalid WWW-Authenticate header format', function(done) {
var res = {
headers: {'www-authenticate': 'Hawk ts="1362346425875", tsm="PhwayS28vtnn3qbv0mqRBYSXebN/zggEtucfeZ620Zo=", x="Stale timestamp"'},
getResponseHeader: function(header) {
return res.headers[header.toLowerCase()];
}
};
expect(Browser.client.authenticate(res, {})).to.equal(false);
done();
});
it('errors on invalid WWW-Authenticate header format', function(done) {
var credentials = {
id: '123456',
key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
algorithm: 'sha256',
user: 'steve'
};
var res = {
headers: {'www-authenticate': 'Hawk ts="1362346425875", tsm="hwayS28vtnn3qbv0mqRBYSXebN/zggEtucfeZ620Zo=", error="Stale timestamp"'},
getResponseHeader: function(header) {
return res.headers[header.toLowerCase()];
}
};
expect(Browser.client.authenticate(res, credentials)).to.equal(false);
done();
});
});
describe('#message', function() {
it('generates an authorization then successfully parse it', function(done) {
credentialsFunc('123456', function(err, credentials) {
var auth = Browser.client.message('example.com', 8080, 'some message', {credentials: credentials});
expect(auth).to.exist();
Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function(err, credentials) {
expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
done();
});
});
});
it('generates an authorization using custom nonce/timestamp', function(done) {
credentialsFunc('123456', function(err, credentials) {
var auth = Browser.client.message('example.com', 8080, 'some message', {
credentials: credentials,
nonce: 'abc123',
timestamp: 1398536270957
});
expect(auth).to.exist();
expect(auth.nonce).to.equal('abc123');
expect(auth.ts).to.equal(1398536270957);
done();
});
});
it('errors on missing host', function(done) {
credentialsFunc('123456', function(err, credentials) {
var auth = Browser.client.message(null, 8080, 'some message', {credentials: credentials});
expect(auth).to.not.exist();
done();
});
});
it('errors on invalid host', function(done) {
credentialsFunc('123456', function(err, credentials) {
var auth = Browser.client.message(5, 8080, 'some message', {credentials: credentials});
expect(auth).to.not.exist();
done();
});
});
it('errors on missing port', function(done) {
credentialsFunc('123456', function(err, credentials) {
var auth = Browser.client.message('example.com', 0, 'some message', {credentials: credentials});
expect(auth).to.not.exist();
done();
});
});
it('errors on invalid port', function(done) {
credentialsFunc('123456', function(err, credentials) {
var auth = Browser.client.message('example.com', 'a', 'some message', {credentials: credentials});
expect(auth).to.not.exist();
done();
});
});
it('errors on missing message', function(done) {
credentialsFunc('123456', function(err, credentials) {
var auth = Browser.client.message('example.com', 8080, undefined, {credentials: credentials});
expect(auth).to.not.exist();
done();
});
});
it('errors on null message', function(done) {
credentialsFunc('123456', function(err, credentials) {
var auth = Browser.client.message('example.com', 8080, null, {credentials: credentials});
expect(auth).to.not.exist();
done();
});
});
it('errors on invalid message', function(done) {
credentialsFunc('123456', function(err, credentials) {
var auth = Browser.client.message('example.com', 8080, 5, {credentials: credentials});
expect(auth).to.not.exist();
done();
});
});
it('errors on missing credentials', function(done) {
var auth = Browser.client.message('example.com', 8080, 'some message', {});
expect(auth).to.not.exist();
done();
});
it('errors on missing options', function(done) {
var auth = Browser.client.message('example.com', 8080, 'some message');
expect(auth).to.not.exist();
done();
});
it('errors on invalid credentials (id)', function(done) {
credentialsFunc('123456', function(err, credentials) {
var creds = Hoek.clone(credentials);
delete creds.id;
var auth = Browser.client.message('example.com', 8080, 'some message', {credentials: creds});
expect(auth).to.not.exist();
done();
});
});
it('errors on invalid credentials (key)', function(done) {
credentialsFunc('123456', function(err, credentials) {
var creds = Hoek.clone(credentials);
delete creds.key;
var auth = Browser.client.message('example.com', 8080, 'some message', {credentials: creds});
expect(auth).to.not.exist();
done();
});
});
it('errors on invalid algorithm', function(done) {
credentialsFunc('123456', function(err, credentials) {
var creds = Hoek.clone(credentials);
creds.algorithm = 'blah';
var auth = Browser.client.message('example.com', 8080, 'some message', {credentials: creds});
expect(auth).to.not.exist();
done();
});
});
});
describe('#authenticateTimestamp', function(done) {
it('validates a timestamp', function(done) {
credentialsFunc('123456', function(err, credentials) {
var tsm = Hawk.crypto.timestampMessage(credentials);
expect(Browser.client.authenticateTimestamp(tsm, credentials)).to.equal(true);
done();
});
});
it('validates a timestamp without updating local time', function(done) {
credentialsFunc('123456', function(err, credentials) {
var offset = Browser.utils.getNtpOffset();
var tsm = Hawk.crypto.timestampMessage(credentials, 10000);
expect(Browser.client.authenticateTimestamp(tsm, credentials, false)).to.equal(true);
expect(offset).to.equal(Browser.utils.getNtpOffset());
done();
});
});
it('detects a bad timestamp', function(done) {
credentialsFunc('123456', function(err, credentials) {
var tsm = Hawk.crypto.timestampMessage(credentials);
tsm.ts = 4;
expect(Browser.client.authenticateTimestamp(tsm, credentials)).to.equal(false);
done();
});
});
});
});
describe('internals', function() {
describe('LocalStorage', function() {
it('goes through the full lifecycle', function(done) {
var storage = new Browser.internals.LocalStorage();
expect(storage.length).to.equal(0);
expect(storage.getItem('a')).to.equal(null);
storage.setItem('a', 5);
expect(storage.length).to.equal(1);
expect(storage.key()).to.equal('a');
expect(storage.key(0)).to.equal('a');
expect(storage.getItem('a')).to.equal('5');
storage.setItem('b', 'test');
expect(storage.key()).to.equal('a');
expect(storage.key(0)).to.equal('a');
expect(storage.key(1)).to.equal('b');
expect(storage.length).to.equal(2);
expect(storage.getItem('b')).to.equal('test');
storage.removeItem('a');
expect(storage.length).to.equal(1);
expect(storage.getItem('a')).to.equal(null);
expect(storage.getItem('b')).to.equal('test');
storage.clear();
expect(storage.length).to.equal(0);
expect(storage.getItem('a')).to.equal(null);
expect(storage.getItem('b')).to.equal(null);
done();
});
});
});
describe('utils', function() {
describe('#setStorage', function() {
it('sets storage for the first time', function(done) {
Browser.utils.storage = new Browser.internals.LocalStorage();
expect(Browser.utils.storage.getItem('hawk_ntp_offset')).to.not.exist();
Browser.utils.storage.setItem('test', '1');
Browser.utils.setStorage(new Browser.internals.LocalStorage());
expect(Browser.utils.storage.getItem('test')).to.not.exist();
Browser.utils.storage.setItem('test', '2');
expect(Browser.utils.storage.getItem('test')).to.equal('2');
done();
});
});
describe('#setNtpOffset', function(done) {
it('catches localStorage errors', function(done) {
var orig = Browser.utils.storage.setItem;
var error = console.error;
var count = 0;
console.error = function() {
if (count++ === 2) {
console.error = error;
}
};
Browser.utils.storage.setItem = function() {
Browser.utils.storage.setItem = orig;
throw new Error();
};
expect(function() {
Browser.utils.setNtpOffset(100);
}).not.to.throw();
done();
});
});
describe('#parseAuthorizationHeader', function(done) {
it('returns null on missing header', function(done) {
expect(Browser.utils.parseAuthorizationHeader()).to.equal(null);
done();
});
it('returns null on bad header syntax (structure)', function(done) {
expect(Browser.utils.parseAuthorizationHeader('Hawk')).to.equal(null);
done();
});
it('returns null on bad header syntax (parts)', function(done) {
expect(Browser.utils.parseAuthorizationHeader(' ')).to.equal(null);
done();
});
it('returns null on bad scheme name', function(done) {
expect(Browser.utils.parseAuthorizationHeader('Basic asdasd')).to.equal(null);
done();
});
it('returns null on bad attribute value', function(done) {
expect(Browser.utils.parseAuthorizationHeader('Hawk test="\t"', ['test'])).to.equal(null);
done();
});
it('returns null on duplicated attribute', function(done) {
expect(Browser.utils.parseAuthorizationHeader('Hawk test="a", test="b"', ['test'])).to.equal(null);
done();
});
});
describe('#parseUri', function() {
it('returns empty port when unknown scheme', function(done) {
var uri = Browser.utils.parseUri('ftp://domain');
expect(uri.port).to.equal('');
done();
});
it('returns default port when missing', function(done) {
var uri = Browser.utils.parseUri('http://');
expect(uri.port).to.equal('80');
done();
});
});
var str = "https://www.google.ca/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=url";
var base64str = "aHR0cHM6Ly93d3cuZ29vZ2xlLmNhL3dlYmhwP3NvdXJjZWlkPWNocm9tZS1pbnN0YW50Jmlvbj0xJmVzcHY9MiZpZT1VVEYtOCNxPXVybA";
describe('#base64urlEncode', function() {
it('should base64 URL-safe decode a string', function(done) {
expect(Browser.utils.base64urlEncode(str)).to.equal(base64str);
done();
});
});
});
});
|
function eventCalendar() {
var parameter = $('#calendar').attr('data-room-id');
return $('#calendar').fullCalendar({
locale: 'ru',
contentHeight: 600,
header: {
left: 'month,agendaWeek,agendaDay',
center: 'title'
},
views: {
month: {
buttonText: 'месяц'
},
agendaWeek: {
type: 'agenda',
duration: {
days: 7
},
buttonText: 'неделя'
},
agendaDay: {
type: 'agenda',
duration: {
days: 1
},
buttonText: 'сегодня'
}
},
events: '/orders.json?room_id='+parameter,
timeFormat: 'HH:mm'
});
};
function clearCalendar() {
$('#calendar').fullCalendar('delete');
$('#calendar').html('');
};
$(document).on('turbolinks:load', eventCalendar);
$(document).on('turbolinks:before-cache', clearCalendar);
|
const { jest: lernaAliases } = require('lerna-alias');
module.exports = {
preset: 'ts-jest',
moduleNameMapper: lernaAliases(),
transform: {
// process *.vue files with vue-jest
'^.+\\.vue$': require.resolve('vue-jest')
}
};
|
/*
-----------------------------------------------------------------------------
Copyright (c) 2014-2018 Seth Anderson
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.
-----------------------------------------------------------------------------
*/
(function(){
var RowExpand = function(){
return {
restrict: "C",
link: function(scope, element, attrs){
var resizeRow = function(){
var parentHeight = element.parent()[0].offsetHeight,
otherRowHeights = 0,
siblings = element.parent().children();
for(var i = 0; i < siblings.length; i += 1){
var siblingElement = angular.element(siblings[i]);
if(siblingElement.hasClass("row")
&& !siblingElement.hasClass("row-expand")){
otherRowHeights += siblingElement[0].offsetHeight;
}
}
element.css({
height: (parentHeight - otherRowHeights) + "px"
});
};
element.parent().on("resize", resizeRow);
resizeRow();
}
};
};
angular
.module("3akm.admin.styling", [])
.directive("rowExpand", RowExpand);
RowExpand.$inject = [];
})();
|
const defaultErrorToString = require('./errorToString');
const defaultDateToString = require('./dateToString');
const defaultColors = require('./colors');
const defaultConfig = {
indent: ' ',
prefix: '\n',
postfix: '',
};
module.exports = function getConfig (config = {}) {
return {
indent: simpleChoice(config.indent, defaultConfig.indent),
prefix: simpleChoice(config.prefix, defaultConfig.prefix),
postfix: simpleChoice(config.postfix, defaultConfig.postfix),
errorToString: config.errorToString || defaultErrorToString,
dateToString: config.dateToString || defaultDateToString,
colors: Object.assign({}, defaultColors, config.colors),
};
};
function simpleChoice (userValue, defaultValue) {
if (typeof userValue === 'undefined') {
return defaultValue;
}
return userValue;
}
|
const bubble = require('../bubble');
/**
* @param {Event} event
*/
module.exports = function (event) {
bubble.bubbling(event.currentTarget);
};
|
/* global document */
import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import AnnotationEditorWidget from '..';
import SelectionBuilder from '../../../../Common/Misc/SelectionBuilder';
import AnnotationBuilder from '../../../../Common/Misc/AnnotationBuilder';
import LegendProvider from '../../../../InfoViz/Core/LegendProvider';
// Load CSS
require('normalize.css');
const scores = [
{ name: 'Yes', color: '#00C900', value: 100 },
{ name: 'Maybe', color: '#FFFF00', value: 0 },
{ name: 'No', color: '#C90000', value: -Number.MAX_VALUE },
];
const rangeSelection = SelectionBuilder.range({
pressure: [
{ interval: [0, 101.3], endpoints: 'oo', uncertainty: 15 },
{ interval: [200, 400], endpoints: '*o', uncertainty: 30 },
],
temperature: [
{ interval: [233, Number.MAX_VALUE], endpoints: 'oo', uncertainty: 15 },
],
});
const partitionSelection = SelectionBuilder.partition('pressure', [
{ value: 90, uncertainty: 0 },
{ value: 101.3, uncertainty: 10 },
{ value: 200, uncertainty: 40, closeToLeft: true },
]);
const ranges = {
pressure: [0, 600],
temperature: [-270, 1000],
};
const annotations = [
AnnotationBuilder.annotation(rangeSelection, [0]),
AnnotationBuilder.annotation(partitionSelection, [1, 0, 1, 2]),
AnnotationBuilder.annotation(SelectionBuilder.convertToRuleSelection(rangeSelection), [1]),
];
const legendService = LegendProvider.newInstance({ legendEntries: ['pressure', 'temperature'] });
// Get react component
document.body.style.padding = '10px';
function render() {
ReactDOM.render(
<div>
{annotations.map((annotation, idx) =>
<div key={idx}>
<AnnotationEditorWidget
scores={scores}
ranges={ranges}
annotation={annotation}
getLegend={legendService.getLegend}
// rationaleOpen={true}
onChange={(newAnnotation, save) => {
annotations[idx] = newAnnotation;
if (save) {
console.log('Push annotation', newAnnotation.generation, newAnnotation);
}
render();
}}
/>
<hr />
</div>
)}
</div>,
document.querySelector('.content'));
}
render();
|
'use strict';
var path = require('path');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('gulp-autoprefixer');
var imagemin = require('gulp-imagemin');<% if (jade || nunjucks) { %>
var data = require('gulp-data');
var frontMatter = require('gulp-front-matter');
var markdown = require('gulp-markdown');
var layout = require('gulp-layout');<% } %><% if (jade) { %>
var jade = require('gulp-jade');<% } %><% if (nunjucks) { %>
var nunjucks = require('gulp-nunjucks-render');<% } %><% if (ts) { %>
var ts = require('gulp-typescript');<% } %><% if (coffee) { %>
var coffee = require('gulp-coffee');<% } %><% if (less) { %>
var less = require('gulp-less');<% } %><% if (sass) { %>
var sass = require('gulp-sass');<% } %>
var config = require('../config');
var helpers = require('./helpers');
gulp.task('html', function() {
return gulp.src(helpers.src(config.paths.src, '.html'))
.pipe(gulp.dest(config.paths.tmp));
});<% if (jade) { %>
gulp.task('jade', function() {
return gulp.src(helpers.src(config.paths.src, '.jade'))
.pipe(data(function(file) {
return helpers.locals(file);
}))
.pipe(jade({
pretty: true,
}))
.pipe(gulp.dest(config.paths.tmp));
});<% } %><% if (nunjucks) { %>
gulp.task('nunjucks', function() {
return gulp.src(helpers.src(config.paths.src, '.nunjucks'))
.pipe(data(function(file) {
return helpers.locals(file);
}))
.pipe(nunjucks())
.pipe(gulp.dest(config.paths.tmp));
});<% } %><% if (jade || nunjucks) { %>
gulp.task('markdown', function() {
return gulp.src(helpers.src(config.paths.src, ['.md', '.markdown']))
.pipe(frontMatter())
.pipe(markdown())
.pipe(layout(function(file) {
var fmData = file.frontMatter;
fmData.layout = helpers.absPath(fmData.layout);
return fmData;
}))
.pipe(gulp.dest(config.paths.tmp));
});<% } %>
gulp.task('js', function() {
return gulp.src(helpers.src(config.paths.src, '.js'))
.pipe(gulp.dest(config.paths.tmp));
});<% if (ts) { %>
gulp.task('ts', function() {
return gulp.src(helpers.src(config.paths.src, '.ts'))
.pipe(gulpif(config.sourcemaps, sourcemaps.init()))
.pipe(ts())
.js
.pipe(gulpif(config.sourcemaps, sourcemaps.write()))
.pipe(gulp.dest(config.paths.tmp));
});<% } %><% if (coffee) { %>
gulp.task('coffee', function() {
return gulp.src(helpers.src(config.paths.src, '.coffee'))
.pipe(gulpif(config.sourcemaps, sourcemaps.init()))
.pipe(coffee())
.pipe(gulpif(config.sourcemaps, sourcemaps.write()))
.pipe(gulp.dest(config.paths.tmp));
});<% } %>
gulp.task('css', function() {
return gulp.src(helpers.src(config.paths.src, '.css'))
.pipe(gulpif(config.sourcemaps, sourcemaps.init()))
.pipe(autoprefixer())
.pipe(gulpif(config.sourcemaps, sourcemaps.write()))
.pipe(gulp.dest(config.paths.tmp));
});<% if (less) { %>
gulp.task('less', function() {
return gulp.src(helpers.src(config.paths.src, '.less'))
.pipe(gulpif(config.sourcemaps, sourcemaps.init()))
.pipe(less())
.pipe(autoprefixer())
.pipe(gulpif(config.sourcemaps, sourcemaps.write()))
.pipe(gulp.dest(config.paths.tmp));
});<% } %><% if (sass) { %>
gulp.task('sass', function() {
return gulp.src(helpers.src(config.paths.src, ['.sass', '.scss']))
.pipe(gulpif(config.sourcemaps, sourcemaps.init()))
.pipe(sass())
.pipe(autoprefixer())
.pipe(gulpif(config.sourcemaps, sourcemaps.write()))
.pipe(gulp.dest(config.paths.tmp));
});<% } %>
gulp.task('images', function() {
return gulp.src(helpers.src(config.paths.src, ['.gif', '.jpeg', '.jpg', '.png', '.svg']))
.pipe(imagemin())
.pipe(gulp.dest(config.paths.tmp));
});
gulp.task('other', function() {
return gulp.src(helpers.others(config.paths.src))
.pipe(gulp.dest(config.paths.tmp));
});
|
import Table from "./table";
import Column from "./column";
export Table from "./table";
export Column from "./column";
export default {Table, Column};
|
'use strict'
import readCache from '../lib/read-cache'
import test from 'blue-tape'
import Request from './helpers/req'
import debug from 'debug'
const log = debug('readCache')
test('readCache closure', t => {
const closure = readCache({})
t.equals(typeof closure, 'function', 'reading from cache should return a closure')
t.end()
})
test('readCache closure is a promise', t => {
const closure = readCache({})
t.ok(closure() instanceof Promise, 'reading from cache should return a promise')
t.end()
})
test('readCache cache success', t => {
const value = {
expires: 0,
data: {
body: {
responseType: 'text',
responseText: 'Hello world',
status: 200,
statusText: 'OK'
},
headers: 'content-type: text/plain'
}
}
const req = new Request()
return new Promise(resolve => {
readCache(req, log)(value)
.then(res => {
t.equals(res.body, value.data.body.responseText, 'response should be defined')
resolve()
})
.catch(err => {
// add test in case of error
t.error(err, 'hydration should not throw')
resolve()
})
})
})
test('readCache cache miss', t => {
const req = new Request()
return new Promise(resolve => {
readCache(req, log)(false)
.then(res => {
t.error('response should not be defined on cache miss')
resolve()
})
.catch(err => {
// add test in case of error
t.equals(err.reason, 'cache-miss', 'reading from cache should throw on cache miss')
resolve()
})
})
})
test('readCache cache stale', t => {
const req = new Request()
const value = {
expires: -1,
data: {
body: {
responseType: 'text',
responseText: 'Hello world',
status: 200,
statusText: 'OK'
},
headers: 'content-type: text/plain'
}
}
return new Promise(resolve => {
readCache(req, log)(value)
.then(res => {
t.error('response should not be defined on cache stale')
resolve()
})
.catch(err => {
// add test in case of error
t.equals(err.reason, 'cache-stale', 'reading a stale value from cache should throw')
resolve()
})
})
})
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2015 Sébastien CAPARROS (GlitchyVerse)
*
* 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.
*/
/**
* The Camera object handles the position, rotation and configuration of the camera
*/
var Camera = function(world) {
this.world = world;
this._rotation = quat.create();
this._eulerRotation = vec3.create(); // FPS mode
this.moveSpeed = 0.003;
this._position = vec3.fromValues(0, 0, 0);
this.lastAnimationTime = 0;
this.screenSize = null;
this.projectionMatrix = null;
this.lastModelViewMatrix = mat4.create();
this.fovy = 45;
this.viewDistance = 1000000;
this.targetBuilding = null;
this.controls = new Controls(this);
this.clipMode = false;
// TODO customizable fovy and view distance (+fog ?)
};
Camera.prototype.updateProjectionMatrix = function(screenWidth, screenHeight) {
this.screenSize = vec2.fromValues(screenWidth, screenHeight);
this.projectionMatrix = mat4.create();
mat4.perspective(this.projectionMatrix, this.fovy, screenWidth / screenHeight, 0.1, this.viewDistance);
return this.projectionMatrix;
};
Camera.prototype.init = function(canvas) {
this.controls.init(canvas);
};
/**
* Resets the camera if the building which has been removed is the one targetted by the camera.
* @param Building The removed building
*/
Camera.prototype.notifyBuildingRemoved = function(building) {
if(building == this.targetBuilding) {
this.setTargetBuilding(null);
}
};
Camera.prototype.setTargetBuilding = function(newTarget) {
if(this.targetBuilding != null) this.targetBuilding.isVisible = true;
if(newTarget != null) newTarget.isVisible = false;
this.targetBuilding = newTarget;
};
Camera.prototype.getRotation = function() {
var rotation = quat.create();
if(this.clipMode || this.targetBuilding == null) {
quat.copy(rotation, this._rotation);
quat.invert(rotation, rotation);
if(this.world.userSpaceShip != null) {
var ssRotation = quat.create();
quat.rotateX(ssRotation, ssRotation, degToRad(this.world.userSpaceShip.rotation[0]));
quat.rotateY(ssRotation, ssRotation, degToRad(this.world.userSpaceShip.rotation[1]));
quat.rotateZ(ssRotation, ssRotation, degToRad(this.world.userSpaceShip.rotation[2]));
quat.multiply(rotation, rotation, ssRotation);
}
} else {
quat.copy(rotation, this._eulerRotation);
}
return rotation;
};
/**
* @return The camera absolute position in the world
*/
Camera.prototype.getAbsolutePosition = function() { // TODO optimize by caching it for each frame
var pos = vec3.create();
if(this.clipMode || this.targetBuilding == null) {
vec3.copy(pos, this._position);
if(this.world.userSpaceShip != null) {
var ssRotation = quat.create();
quat.rotateX(ssRotation, ssRotation, degToRad(this.world.userSpaceShip.rotation[0]));
quat.rotateY(ssRotation, ssRotation, degToRad(this.world.userSpaceShip.rotation[1]));
quat.rotateZ(ssRotation, ssRotation, degToRad(this.world.userSpaceShip.rotation[2]));
quat.invert(ssRotation, ssRotation);
vec3.transformQuat(pos, pos, ssRotation);
vec3.add(pos, pos, this.world.userSpaceShip.getPosition());
}
} else {
vec3.copy(pos, this.targetBuilding.position);
}
return pos;
};
/**
* Updates the projection, model and view matrix, depending of Controls.
* @return mat4 The model/view matrix
*/
Camera.prototype.update = function() {
var userSpaceShip = this.world.userSpaceShip;
// TODO add an inventory button in hud
// TODO optimize by not creating temp vectors everytime
if(this.targetBuilding == null && userSpaceShip != null) {
for(var k in userSpaceShip.entities) {
if(userSpaceShip.entities[k].type.isControllable) {
this.setTargetBuilding(userSpaceShip.entities[k]);
break;
}
}
}
var invertedRotation = mat4.create();
var negatedPosition = vec3.create();
// TODO only for tests, remove it
if(this.controls._keys[107]) this.moveSpeed *= 1.05;
if(this.controls._keys[109]) this.moveSpeed /= 1.05;
// Moves depends of elapsed time
var timeNow = TimerManager.lastUpdateTimeStamp;
if(this.lastAnimationTime != 0) {
var elapsed = timeNow - this.lastAnimationTime;
var movement = this.controls.getMovement();
var rotationRate = this.controls.getRotation();
if(this.clipMode || this.targetBuilding == null) {
// Moves
var currentMove = vec3.create();
vec3.scale(currentMove, movement, this.moveSpeed * elapsed);
vec3.transformQuat(currentMove, currentMove, this._rotation);
vec3.add(this._position, this._position, currentMove);
vec3.negate(negatedPosition, this._position);
// Rotation
var tempQuat = quat.create();
quat.rotateX(tempQuat, tempQuat, degToRad(rotationRate[0] * elapsed));
quat.rotateY(tempQuat, tempQuat, degToRad(rotationRate[1] * elapsed));
quat.rotateZ(tempQuat, tempQuat, degToRad(rotationRate[2] * elapsed));
quat.normalize(tempQuat, tempQuat);
quat.multiply(this._rotation, this._rotation, tempQuat);
mat4.fromQuat(invertedRotation, this._rotation);
mat4.invert(invertedRotation, invertedRotation);
} else {
var halfPI = Math.PI / 2;
// First person euler rotation
var yEulerRotation = degToRad(rotationRate[1] * elapsed);
this._eulerRotation[0] += degToRad(rotationRate[0] * elapsed);
if(this._eulerRotation[0] > halfPI) this._eulerRotation[0] = halfPI;
if(this._eulerRotation[0] < -halfPI) this._eulerRotation[0] = -halfPI;
// Moves
var currentMove = vec3.create();
vec3.scale(currentMove, movement, this.moveSpeed * elapsed);
// Only rotating the character over the Y axis
var targetBuildingRotation = quat.create();
quat.rotateY(targetBuildingRotation, targetBuildingRotation, yEulerRotation);
this.targetBuilding.moveAndLookInSpaceShip(currentMove, targetBuildingRotation);
// Camera rotation
var cameraQuat = quat.create();
quat.rotateX(cameraQuat, cameraQuat, this._eulerRotation[0]);
quat.multiply(cameraQuat, this.targetBuilding.rotationInSpaceShip, cameraQuat);
mat4.fromQuat(invertedRotation, cameraQuat);
mat4.invert(invertedRotation, invertedRotation);
var eye = this.targetBuilding.model.meshGroups["eye"];
if(eye) {
var vertices = eye[0].vertices;
negatedPosition[0] += vertices[0];
negatedPosition[1] += vertices[1];
negatedPosition[2] += vertices[2];
vec3.transformQuat(negatedPosition, negatedPosition, this.targetBuilding.rotationInSpaceShip);
}
vec3.add(negatedPosition, negatedPosition, this.targetBuilding.positionInSpaceShip);
vec3.negate(negatedPosition, negatedPosition);
// TODO send building moves to server and other players (+ animate on other clients)
// TODO stop animation when the character stops walking
}
}
this.lastAnimationTime = timeNow;
// TODO separate mtl files ?
mat4.identity(this.lastModelViewMatrix);
mat4.multiply(this.lastModelViewMatrix, this.lastModelViewMatrix, invertedRotation);
mat4.translate(this.lastModelViewMatrix, this.lastModelViewMatrix, negatedPosition);
// TODO camera lagging --> webworker ?
if(userSpaceShip != null) {
var ssRotation = quat.create();
quat.rotateX(ssRotation, ssRotation, degToRad(userSpaceShip.rotation[0]));
quat.rotateY(ssRotation, ssRotation, degToRad(userSpaceShip.rotation[1]));
quat.rotateZ(ssRotation, ssRotation, degToRad(userSpaceShip.rotation[2]));
mat4.fromQuat(invertedRotation, ssRotation);
//mat4.translate(this.lastModelViewMatrix, this.lastModelViewMatrix, negatedPosition);
mat4.multiply(this.lastModelViewMatrix, this.lastModelViewMatrix, invertedRotation);
}
// TODO character rotation is inverted ?!?
return this.lastModelViewMatrix;
};
|
var _ = require('underscore');
var assert = require('chai').assert;
var RED = require('./lib/red-stub')();
var AuthorizedBlock = require('../chatbot-authorized');
describe('Chat authorized node', function() {
it('should pass to the second output for unauthorized nodes', function () {
var msg = RED.createMessage({content: 'I am the input message'});
RED.node.config({
command: 'start'
});
AuthorizedBlock(RED);
RED.environment.chat(msg.originalMessage.chat.id, {authorized: false});
RED.node.get().emit('input', msg);
assert.equal(RED.node.message(0), null);
assert.equal(RED.node.message(1).originalMessage.chat.id, 42);
assert.equal(RED.node.message(1).payload.content, 'I am the input message');
});
it('should pass to the first output for authorized nodes', function () {
var msg = RED.createMessage({content: 'I am the input message'});
RED.node.config({
command: 'start'
});
AuthorizedBlock(RED);
RED.environment.chat(msg.originalMessage.chat.id, {authorized: true});
RED.node.get().emit('input', msg);
assert.equal(RED.node.message(0).originalMessage.chat.id, 42);
assert.equal(RED.node.message(0).payload.content, 'I am the input message');
assert.equal(RED.node.message(1), null);
});
});
|
'use strict';
//Setting up route
angular.module('eventos').config(['$stateProvider',
function ($stateProvider) {
// Eventos state routing
$stateProvider.
state('listEventos', {
url: '/eventos',
templateUrl: 'modules/eventos/views/list-eventos.client.view1.html'
}).
state('createEvento', {
url: '/eventos/create',
templateUrl: 'modules/eventos/views/create-evento.client.view.html'
}).
state('viewEvento', {
url: '/eventos/:eventoId',
templateUrl: 'modules/eventos/views/view-evento.client.view.html'
}).
state('editEvento', {
url: '/eventos/:eventoId/edit',
templateUrl: 'modules/eventos/views/edit-evento.client.view.html'
}).
// state('viewEvento', {
// url: '/eventos/:eventoId',
// templateUrl: 'modules/eventos/views/view-evento.client.view.html'
// }).
// state('viewEvento', {
// url: '/eventos/:eventoId',
// templateUrl: 'modules/eventos/views/view-evento.client.view.html'
// }).
state('aprobadosEvento', {
url: '/eventos/aprobados',
templateUrl: 'modules/eventos/views/list-eventos.client.view.html'
});
}
]); |
var BookCalendar = function(options) {
this.locale = options.locale ? options.locale : 'en';
this.daysCount = options.daysCount ? options.daysCount : 7;
this.el = options.el;
this.data = options.data;
this.dateGroup = null;
this.moveOnExisting = options.moveOnExisting;
this.step = options.step ? options.step : 1;
this.startDate = options.startDate ? options.startDate : new Date();
this.minDate = options.minDate ? options.minDate : new Date();
this.onMoveLeft = options.onMoveLeft ? options.onMoveLeft : function(callback) {
callback();
};
this.onMoveRight = options.onMoveRight ? options.onMoveRight : function(callback) {
callback();
};
this.cellPercentsWidth = (100 / this.daysCount).toFixed(2);
this.getLocale = function() {
if (!this.language || this.language.locale != this.locale) {
this.language = {
locale: 'ro',
months: 'ianuarie_februarie_martie_aprilie_mai_iunie_iulie_august_septembrie_octombrie_noiembrie_decembrie'.split('_'),
monthsShort: 'ian._febr._mart._apr._mai_iun._iul._aug._sept._oct._nov._dec.'.split('_'),
weekdays: 'duminică_luni_marți_miercuri_joi_vineri_sâmbătă'.split('_'),
weekdaysShort: 'Du_Lu_Ma_Mi_Jo_Vi_Sa'.split('_')
};
}
return this.language;
};
this.getStartDate = function() {
return new Date(this.startDate);
};
this.getEndDate = function() {
var ino = new Date(this.startDate);
ino.setDate(ino.getDate() + this.daysCount);
return new Date(ino);
};
this.init = function() {
var template = '<div class="book-calendar-wrapper"><table width="100%" class="book-calendar-main-container"> <tr> <td> <table class="book-calendar-header"> <thead> <tr class="book-calendar-months"><button style="border: none;" class="nav-arrow book-calendar-prev"></button><button style="border: none;" class="nav-arrow book-calendar-next"></button></tr><tr class="book-calendar-days"> </tr></thead> </table> </td></tr><tr> <td> <div class="book-calendar-data-container"> <table width="100%" class="book-calendar-data"> <tbody> </tbody> </table> </div></td></tr></table></div>';
var container = document.getElementById(this.el);
container.innerHTML = template;
// for (var i in this.data) {
// this.data[i] = moment.utc(this.data[i]).format();
// }
this.dateGroup = this.groupHoursByDay(this.data);
this.draw();
};
this.getKeyElements = function() {
var container = document.getElementById(this.el);
return {
element: this.el,
container: container,
calendarWrapper: container.getElementsByClassName('book-calendar-wrapper')[0],
dataContainer: container.getElementsByClassName('book-calendar-data')[0],
monthsContainer: container.getElementsByClassName('book-calendar-months')[0],
daysContainer: container.getElementsByClassName('book-calendar-days')[0],
nextButton: container.getElementsByClassName('book-calendar-next')[0],
prevButton: container.getElementsByClassName('book-calendar-prev')[0],
activeCells: container.getElementsByClassName('book-calendar-cell-active' + this.el)
};
};
this.getDate = function(timestamp) {
var date = new Date(timestamp);
var year = date.getUTCFullYear();
var month = date.getUTCMonth();
var day = date.getUTCDate();
var hours = date.getUTCHours();
var minutes = date.getUTCMinutes();
var seconds = date.getUTCSeconds();
month = (month < 10) ? '0' + month : month;
day = (day < 10) ? '0' + day : day;
hours = (hours < 10) ? '0' + hours : hours;
minutes = (minutes < 10) ? '0' + minutes : minutes;
seconds = (seconds < 10) ? '0' + seconds : seconds;
return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes;
}
this.groupHoursByDay = function(dates) {
// for(var i in dates) {
// dates[i] = new Date(this.getDate(new Date(dates[0]).getTime()))
// };
var dob = {};
for(var i in dates) {
var day = new Date(dates[i]);
day.setHours(day.getHours() + (day.getTimezoneOffset() / 60));
day.setHours(0,0,0,0);
if (!dob.hasOwnProperty(day)) {
dob[day] = [];
}
dob[day].push(new Date(dates[i]));
}
// var groups = _.groupBy(dates, function(date) {
// return moment(date).startOf('day').format();
// });
// console.log(dob);
// console.log("+++");
// console.log(groups);
var obj = _.map(dob, function(group, day) {
return {
day: day,
times: group
}
});
// var obj = dates.reduce(function(acc, d) {
// var pk = new Date(d);
// pk.setHours(0,0,0,0);
// var p = pk.toString();
// if (!acc[0].hasOwnProperty(p)) acc[0][p] = [];
// acc[0][p].push(d);
// return acc;
// },[{}])
// .reduce(function(acc, v){
// Object.keys(v).forEach(function(k){acc.push({day:k, times:v[k]});});
// return acc;
// },[]);
// console.log("???????");
// console.log(obj);
// console.log("???????");
return obj;
};
this.getHoursByDate = function(date) {
date.setHours(0, 0, 0, 0);
var dates = this.dateGroup;
for (var i in dates) {
var day = new Date(dates[i].day);
// console.log("?????");
// console.log(day);
// console.log("?????");
if (day.getTime() == date.getTime()) {
var times = dates[i].times.sort();
return times;
}
}
return [];
};
this.moveExistingLeft = function() {
var sd = new Date(this.startDate);
sd.setHours(0, 0, 0, 0);
var dd = this.data;
var collectedDates = [];
for (var i in dd) {
var da = new Date(dd[i]).setHours(0, 0, 0, 0);
if (da.getTime() < sd.getTime()) {
collectedDates.push(da);
}
}
collectedDates.sort();
if (collectedDates.length > 0)
this.startDate = collectedDates.pop();
this.draw();
this.onMoveLeft(function() {});
};
this.moveExistingRight = function() {
var sd = new Date(this.startDate);
sd.setHours(0, 0, 0, 0);
var dd = this.data;
var collectedDates = [];
for (var i in dd) {
var da = new Date(dd[i]).setHours(0, 0, 0, 0);
if (da.getTime() > sd.getTime()) {
collectedDates.push(da);
}
}
collectedDates.sort();
if (collectedDates.length > 0)
this.startDate = collectedDates[0];
this.draw();
this.onMoveRight(function() {});
};
this.moveLeft = function(step) {
var ms = step ? step : this.step;
this.startDate.setDate(this.startDate.getDate() - parseInt(ms));
this.draw();
this.onMoveLeft(function() {});
};
this.moveRight = function(step) {
var ms = step ? step : this.step;
this.startDate.setDate(this.startDate.getDate() + parseInt(ms));
this.draw();
this.onMoveRight(function() {});
};
this.prevDisabled = function(disabled) {
var keyElements = this.getKeyElements();
keyElements.prevButton.disabled = disabled;
};
this.getDisplayDates = function() {
var today = new Date(this.startDate);
var displayArray = [];
for (var dd = 0; dd < this.daysCount; dd++) {
var x = new Date(today);
displayArray.push(x);
today.setDate(today.getDate() + 1);
}
return displayArray;
};
this.getMonth = function(n) {
return {
long: this.getLocale().months[n].charAt(0).toUpperCase() + this.getLocale().months[n].slice(1),
short: this.getLocale().monthsShort[n].charAt(0).toUpperCase() + this.getLocale().monthsShort[n].slice(1),
};
};
this.getDay = function(n) {
return {
long: this.getLocale().weekdays[n],
short: this.getLocale().weekdaysShort[n],
};
};
this.getMaxInputs = function() {
var max = 0;
var gData = this.dateGroup;
for (var i in gData) {
if (gData[i].times.length > max) max = gData[i].times.length;
}
return max;
};
this.getHead = function() {
var startMonth = this.startDate.getMonth();
var displayDates = this.getDisplayDates();
var colspans = {
first: 0,
second: 0,
};
colspans.firstMonth = this.getMonth(startMonth).short + " " + this.startDate.getFullYear();
var ix = 0;
for (var i in displayDates) {
if (displayDates[i].getMonth() == startMonth) {
colspans.first++;
colspans.lastMonth = this.getMonth(startMonth).short + " " + displayDates[i].getFullYear();
} else {
colspans.second++;
var sm = startMonth;
if (sm > 11) sm = 0;
var fm = sm + 1;
if (fm == 12) fm = 0;
colspans.lastMonth = this.getMonth(fm).short + " " + displayDates[i].getFullYear();
}
}
return colspans;
};
this.addListeners = function() {
var self = this;
var keyElements = this.getKeyElements();
var classname = document.getElementsByClassName("book-calendar-cell-active-" + self.el);
var listenerFunction = function() {
for (var i = 0; i < classname.length; i++) {
classname[i].className = 'book-calendar-cell-active book-calendar-cell-active-' + self.el;
}
this.className = this.className + " book-calendar-cell-active-selected";
self.selectedDate = new Date(this.dataset.date);
self.onSelect(self.selectedDate);
};
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', listenerFunction, false);
}
self = this;
keyElements.prevButton.onclick = function() {
if (self.moveOnExisting) {
self.moveExistingLeft();
} else {
self.moveLeft();
}
};
keyElements.nextButton.onclick = function() {
if (self.moveOnExisting) {
self.moveExistingRight();
} else {
self.moveRight();
}
};
};
this.onSelect = options.onSelect ? options.onSelect : function(selectedDate) {
return selectedDate;
};
this.afterDraw = options.afterDraw ? options.afterDraw : function(callback) {
callback();
};
this.draw = function() {
var keyElements = this.getKeyElements();
if (keyElements.dataContainer && keyElements.monthsContainer && keyElements.daysContainer && keyElements.nextButton && keyElements.prevButton) {
var displayArray = this.getDisplayDates();
var colspans = this.getHead();
var dt = '';
var lastCell = '';
for (var i in displayArray) {
var nextDay = new Date(displayArray[i]);
nextDay.setDate(nextDay.getDate() + 1);
if (displayArray[i].getMonth() != nextDay.getMonth()) {
lastCell = "book-calendar-cell-last";
} else {
lastCell = '';
}
dt += '<td style="width: ' + this.cellPercentsWidth + '%" class="book-calendar-day ' + lastCell + '">' + (displayArray[i].getDate() < 10 ? '0' : '') + displayArray[i].getDate() + '<br><span class="book-calendar-day-name">' + this.getDay(displayArray[i].getDay()).short + '</span></td>';
}
var thead = '';
if (colspans.first > 0) {
thead += '<th colspan="' + colspans.first + '"> ' + colspans.firstMonth + ' </th>';
}
if (colspans.second > 0) {
thead += '<th colspan="' + colspans.second + '"> ' + colspans.lastMonth + ' </th>';
}
keyElements.daysContainer.innerHTML = dt;
keyElements.monthsContainer.innerHTML = thead;
var dataText = '';
var displayDates = this.getDisplayDates();
var dc = this.daysCount - 1;
for (i = 0; i < this.getMaxInputs(); i++) {
dataText += '<tr>';
for (var j = 0; j <= dc; j++) {
var hours = this.getHoursByDate(displayDates[j]);
var cellActive = '';
var display = new Date(hours[i]);
var displayHours = display.getUTCHours() + "<sup>" + (display.getUTCMinutes() < 10 ? '0' : '') + display.getUTCMinutes() + '</sup>';
var nd = new Date(display);
if (hours[i]) {
cellActive = "book-calendar-cell-active book-calendar-cell-active-" + this.el;
nd.setDate(nd.getDate() + 1);
if (display.getUTCMonth() != nd.getUTCMonth()) {
cellActive += " book-calendar-cell-last";
}
if (this.selectedDate) {
var tempDate = new Date(this.selectedDate);
//TODO: do this with getTime();
if (display.getFullYear() == this.selectedDate.getFullYear() && display.getMonth() == this.selectedDate.getMonth() && display.getDate() == this.selectedDate.getDate() && display.getUTCHours() == this.selectedDate.getUTCHours() && display.getUTCMinutes() == this.selectedDate.getUTCMinutes()) {
cellActive += " book-calendar-cell-active-selected";
}
}
} else {
displayHours = ' ';
cellActive = "book-calendar-cell-disabled";
}
dataText += '<td style="width: ' + this.cellPercentsWidth + '%" data-date="' + display.toUTCString() + '" class="book-calendar-cell ' + cellActive + '"> ' + displayHours + ' </td>';
}
dataText += '</tr>';
}
keyElements.dataContainer.innerHTML = dataText;
this.addListeners();
} else {
console.log('Error. Key elements not found!');
}
//alert(keyElements.container.offsetWidth);
keyElements.calendarWrapper.style.width = keyElements.container.offsetWidth - 40 + 'px';
var ms = this.step;
var cd = new Date(this.minDate);
var csd = new Date(this.startDate);
if (csd.getTime() <= cd.getTime()) {
this.prevDisabled(true);
} else {
this.prevDisabled(false);
}
this.afterDraw(function() {});
};
return this.init();
};
|
var Spaceship = function (stage, assetManager) {
// variable initialization
var sprite = assetManager.getSprite('assets');
var maxVelocity = 1;
var velocity = [0, 0];
var position = [stage.canvas.width, 0];
var accelerant = 0.1;
var isDestroyed = false;
var xSpeed = 0;
var ySpeed = 0;
var whichGunFiredLast = 0; // 0 = left, 1 = right
var timeSinceLastShot = 0;
var fireRate = 500;
var keyPressed = 0;
// add spaceship to stage
stage.addChild(sprite);
// ---------------------------------------------- get/set methods
this.isDestroyed = function () {
return isDestroyed;
};
this.getSprite = function () {
return sprite;
};
// ----------------------------------------------- event handlers
function onVelocityChange() {
sprite.scaleX = 1;
// up arrow
if (keyPressed === 3) {
xSpeed = velocity[0] + accelerant * Math.sin(sprite.rotation * Math.PI / 180);
ySpeed = velocity[1] - accelerant * Math.cos(sprite.rotation * Math.PI / 180);
velocity = [xSpeed, ySpeed];
}
position = [position[0] + xSpeed, position[1] + ySpeed];
sprite.x = position[0];
sprite.y = position[1];
if (position[0] < 0) {
position[0] = position[0] + canvas.width;
}
if (position[0] > canvas.width) {
position[0] = 0;
}
if (position[1] < 0) {
position[1] = position[1] + canvas.height;
}
if (position[1] > canvas.height) {
position[1] = 0;
}
//console.log('spaceship x: ' + sprite.x);
//console.log('spaceship y: ' + sprite.y);
}
// ---------------------------------------------- public methods
this.getClip = function () {
return sprite;
}
this.accelerate = function (key) {
keyPressed = key;
createjs.Ticker.addEventListener('tick', onVelocityChange);
};
this.fire = function () {
var now = Date.now();
var projectile = new Projectile(sprite, stage, assetManager, projectileID);
if (now - timeSinceLastShot < fireRate) {
return;
}
if (whichGunFiredLast === 0) {
projectile.spawn(8, -25);
whichGunFiredLast = 1;
} else {
projectile.spawn(-30, -25);
whichGunFiredLast = 0;
}
timeSinceLastShot = now;
projectiles.push(projectile);
projectileID++;
};
this.rotate = function (key) {
sprite.gotoAndStop('spaceshipIdle');
sprite.scaleX = 1;
if (key === 1) {
// rotating left
sprite.rotation -= 10;
} else if (key === 2) {
// rotating right
sprite.rotation += 10;
}
};
this.reset = function () {
sprite.gotoAndStop('spaceshipIdle');
sprite.regX = sprite.getBounds().width / 2;
sprite.regY = sprite.getBounds().height / 2;
xSpeed = 0;
ySpeed = 0;
position = [canvas.width / 2, canvas.height / 2];
velocity = [0, 0];
isDestroyed = false;
if (isRestart) {
stage.addChild(sprite);
}
createjs.Ticker.addEventListener('tick', onVelocityChange);
};
this.destroy = function () {
isDestroyed = true;
sprite.stop();
// remove listener to stop animation
createjs.Ticker.removeEventListener('tick', onVelocityChange);
sprite.gotoAndPlay('spaceshipDestroyed');
sprite.addEventListener('animationend', function () {
// cleanup
sprite.stop();
sprite.removeEventListener('animationend', this);
stage.removeChild(sprite);
sprite.x = -999;
sprite.y = -999;
onGameOver();
});
};
};
|
/*
Copyright 2014, KISSY v1.49
MIT Licensed
build time: May 22 12:31
*/
KISSY.add("stylesheet",["dom"],function(m,l){function h(a){a.el&&(a=a.el);a=this.el=j.get(a);this.sheet=a=a.sheet||a.styleSheet;var d={};this.cssRules=d;var b=a&&"cssRules"in a?"cssRules":"rules";this.rulesName=b;var b=a[b],e,c,f,g;for(e=b.length-1;0<=e;e--)c=b[e],f=c.selectorText,(g=d[f])?(g.style.cssText+=";"+g.style.cssText,c=a,f=e,c.deleteRule?c.deleteRule(f):c.removeRule&&c.removeRule(f)):d[f]=c}function k(a,d){i.style.cssText=d||"";j.css(i,a);return i.style.cssText}var j=l("dom");h.prototype=
{constructor:h,enable:function(){this.sheet.disabled=!1;return this},disable:function(){this.sheet.disabled=!0;return this},isEnabled:function(){return!this.sheet.disabled},set:function(a,d){var b=this.sheet,e=this.rulesName,c=this.cssRules,f=c[a],g=a.split(/\s*,\s*/);if(1<g.length){for(c=0;c<g.length-1;c++)this.set(g[c],d);return this}if(f)if(d=k(d,f.style.cssText))f.style.cssText=d;else{delete c[a];for(c=b[e].length-1;0<=c;c--)if(b[e][c]===f){e=c;b.deleteRule?b.deleteRule(e):b.removeRule&&b.removeRule(e);
break}}else if(f=b[e].length,d=k(d))g=d,b.insertRule?b.insertRule(a+" {"+g+"}",f):b.addRule&&b.addRule(a,g,f),c[a]=b[e][f];return this},get:function(a){var d,b,e=this.cssRules;if(a)return(a=e[a])?a.style.cssText:null;d=[];for(b in e)a=e[b],d.push(a.selectorText+" {"+a.style.cssText+"}");return d.join("\n")}};var i=document.createElement("p");return h});
|
'use strict';
// Declare app level module which depends on filters, and services
angular.module('myApp', [
'ngRoute',
'myApp.filters',
'myApp.services',
'myApp.directives',
'myApp.controllers'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'TaskController'});
$routeProvider.otherwise({redirectTo: '/view1'});
}]);
|
const path = require('path');
module.exports = relationParser;
function relationParser(entries, pptx) {
let relations = {};
entries.sort().filter(x => {
if(x.indexOf('ppt') === 0 && x.indexOf('.rels') > -1)
return true;
return false;
}).forEach(y => {
pptx[y].$$.forEach(z => {
let key = y
.split(path.sep)
.filter(u => {
if(u === '_rels') return false;
return true;
})
.join(path.sep);
key = key.substr(0, key.length - 5);
if(!relations[key]) {
relations[key] = {};
}
if(key === 'ppt/presentation.xml') {
relations[key][z.$.Id] = 'ppt' + path.sep + z.$.Target
relations[key]['ppt' + path.sep + z.$.Target] = z.$.Id;
} else {
relations[key][z.$.Id] = z.$.Target.replace('..', 'ppt');
relations[key][z.$.Target.replace('..', 'ppt')] = z.$.Id;
}
})
});
return relations;
}
|
import React from 'react'
import ReactTooltip from 'react-tooltip'
import isString from 'lodash/isString'
import autobind from 'autobind-decorator'
import uniqueId from 'lodash/uniqueId'
import PropTypes from 'prop-types'
export default class Tooltip extends React.Component {
static propTypes = {
children: PropTypes.node,
content: PropTypes.node,
place: PropTypes.string
}
@autobind
getContent () {
if (isString(this.props.content)) {
return this.props.content.split('\n').map((line, index) => <div key={index}>{line}</div>)
}
return this.props.content
}
render () {
const id = uniqueId('os-tooltip')
return (
<div style={{display: 'inline-block'}}>
<div data-tip='' data-for={id}>
{this.props.children}
</div>
<ReactTooltip id={id} place={this.props.place} effect='solid' getContent={this.getContent} />
</div>
)
}
}
|
TestCase("IMSetDebugTest", sinon.testCase({
setUp: function()
{
},
"test should return false": function()
{
var bResult = IM.setDebug(false);
assertFalse(bResult);
},
"test should return true": function()
{
var bResult = IM.setDebug(true);
assertTrue(bResult);
},
tearDown: function()
{
}
}));
TestCase("IMSetAsynchronousTest", sinon.testCase({
setUp: function()
{
},
"test should return false if asynchronous is set to false": function()
{
var bResult = IM.setAsynchronous(false);
assertFalse(bResult);
},
"test should return true if asynchronous is set to true": function()
{
var bResult = IM.setAsynchronous(true);
assertTrue(bResult);
},
tearDown: function()
{
}
}));
TestCase("IMDataCompareTest", sinon.testCase({
setUp: function()
{
sinon.stub(window, "Date");
},
"test should call new Date if nStart is not supplied and bDebug is set to true": function()
{
IM.setDebug(true);
IM.setAsynchronous(false);
IM.compare([], function(){}, function(){});
assertEquals(2, window.Date.callCount);
},
"test should not call new Date if nStart is not supplied and bDebug is set to false": function()
{
IM.setDebug(false);
IM.setAsynchronous(false);
IM.compare([], function(){}, function(){});
assertEquals(0, window.Date.callCount);
},
tearDown: function()
{
window.Date.restore();
}
}));
TestCase("IM.Image.ConstructorTest", sinon.testCase({
setUp: function()
{
},
"test should return an object with src, width and height": function()
{
var oImageToCompare = new IM.image('test', 300, 300);
assertObject(oImageToCompare);
assertEquals("test?0", oImageToCompare.src);
assertEquals(300, oImageToCompare.width);
assertEquals(300, oImageToCompare.height);
},
tearDown: function()
{
}
}));
TestCase("IMCompare2Test", sinon.testCase({
setUp: function()
{
sinon.stub(window, "Date");
},
"test should call new Date if nStart is not supplied and bDebug is set to true": function()
{
IM.setDebug(true);
IM.setAsynchronous(false);
IM.compare(document.body, [], function(){}, function(){});
assertEquals(3, window.Date.callCount);
},
"test should not call new Date if nStart is not supplied and bDebug is set to false": function()
{
IM.setDebug(false);
IM.setAsynchronous(false);
IM.compare(document.body, [], function(){}, function(){});
assertEquals(0, window.Date.callCount);
},
tearDown: function()
{
window.Date.restore();
}
})); |
Meteor.publish("images", function () {
return Images.find();
});
// Add access points for `GET`, `POST`, `PUT`, `DELETE`
HTTP.publish({
collection: Images
}, function (data) {
// this.userId, this.query, this.params
return Images.find({});
}); |
'use strict';
angular.module('sbAdminApp')
.controller('BillingCtrl', function($scope,$position,$http,$stateParams,$rootScope,$httpParamSerializer,$filter,$location,$interval,NgTableParams,growl,WS) {
var idSeller = $rootScope.globals.currentUser.idSeller;
$scope.contract = '';
$scope.datiTabella= '';
$scope.gauge = {
name: ' ',
opacity: 0.75,
value: 65,
text: false,
arcColor: '#81c04d',
bgArcColor:'#37444e',
opacity: true
};
function init(){
$http({
method: 'POST',
url: WS.ws + 'sellers/getsellercontract',
dataType: 'jsonp',
headers: {
'idSeller': idSeller
},
contentType: 'application/json',
})
.success (function (data) {
$scope.contract = data.data;
$scope.gauge.value = ($scope.contract.n_articles/$scope.contract.number_articles)*100;
})
.error(function(data){
console.log('Error in seller' + data);
});
}//init
function getInvoices(){
$http({
method: 'POST',
url: WS.ws + 'sellers/getsellercontractinvoices',
dataType: 'jsonp',
headers: {
'idSeller': idSeller
},
contentType: 'application/json',
})
.success (function (data) {
console.log(JSON.stringify(data));
var initialParams = {
count: 10 // initial page size
};
var initialSettings = {
total: data.data.length,
counts: [],
data: data.data
};
$scope.datiTabella = new NgTableParams(initialParams,initialSettings);
})
.error(function(data){
console.log('Error in seller' + data);
});
}//getInvoices
$scope.showDetails = function(invoice){
var url = 'index.html#'+$location.url()+'/invoice/'+invoice.id_invoice;
console.log('url ' + url);
location.href=url;
}//SHOW details
init();
getInvoices();
});
|
const tape = require('tape-catch');
tape('Verify home / route', { skip: false }, (describe) => {
const hapi = require('@hapi/hapi');
const hapiReactViews = require('hapi-react-views');
const joi = require('@hapi/joi');
const inert = require('@hapi/inert');
const path = require('path');
const querystring = require('querystring');
const vision = require('@hapi/vision');
const config = require('../../../../../config.json');
const lib = require('../lib');
const utils = require('../../utils');
const plugins = [inert, vision, lib];
const port = utils.config.get('apiPort');
describe.test('* Check home response', { skip: false }, async (assert) => {
const server = hapi.Server({ port });
server.validator(joi);
const url = `/?${querystring.stringify({
raw: true,
})}`;
const viewsConfig = {
engines: {
jsx: hapiReactViews,
},
relativeTo: path.join(__dirname, '../../../../../'),
};
const request = {
method: 'GET',
url,
};
try {
await server.register(plugins);
server.views(viewsConfig);
const response = await server.inject(request);
let actual;
let expected;
actual = response.statusCode;
expected = 200;
assert.equal(actual, expected, 'HTTP status is okay');
actual = response.result.galleries.includes(config.defaultGallery);
expected = true;
assert.equal(actual, expected, 'Default gallery found');
} catch (error) {
assert.fail(error);
}
assert.end();
});
});
|
/*
This is the module that creates beings, be they alien, player, or crew.
*/
function Person(name, profession) {
// constant variables
this.MAXIMUM_WOUNDS = 4;
this.MAXIMUM_SPEED = 6;
this.MAXIMUM_WEIGHT = 10;
this.WEIGHT_PER_STRENGTH = 1;
this.MAXIMUM_XP = 20;
// local variables
this.wounds = 0;
this.speedBonus = 0;
this.strength = 1;
this.damage = 0;
this.weapons = [];
this.armor = {
head: ['none', 0],
torso: ['none', 0],
legs: ['none', 0],
acc: ['none', 0]
};
this.inventory = [];
this.xp = 0;
this.name = name;
this.profession = profession;
this.id = Die.generateId();
this.alive = true;
};
Person.prototype.die = function() {
this.alive = false;
this.xp = 0;
this.profession = 'corpse';
this.strength = 0;
this.wounds = 0;
};
Person.prototype.checkWounds = function() {
if (this.wounds > this.MAXIMUM_WOUNDS) {
this.die();
return false;
} else {
return true;
};
}; |
$(document).ready(function() {
function setHeight() {
windowHeight = $(window).innerHeight();
$('.first-row, .second-row, .third-row, .fourth-row, .fifth-row, .sixth-row, .mirrors-row, .onboard-row, .group-row, .first-row img').css('min-height', windowHeight);
};
setHeight();
$(window).resize(function() {
setHeight();
});
windowHeight = $(window).innerHeight();
$(window).scroll(function () {
console.log($(window).scrollTop())
if ($(window).scrollTop() > windowHeight) {
$('.navbar').addClass('navbar-fixed');
}
if ($(window).scrollTop() < windowHeight) {
$('.navbar').removeClass('navbar-fixed');
}
});
$('body').hide();
$('body').fadeIn(4000);
$('.centerpiece-tag, .centerpiece-credits, .loop-img').hide();
$('.centerpiece-tag, .centerpiece-credits').fadeIn(5000);
$('.loop-img').delay(2000).fadeIn(6000);
});
|
"use strict";
var Redis = require("ioredis");
let db = 0;
if (process.env.NODE_ENV === "development") db = 1;
if (process.env.NODE_ENV === "test") db = 2;
var client = new Redis({
path: "/tmp/redis.sock",
db: db
});
var Logger = require("../inc/Logger");
client.on("error", function (err) {
Logger.redis(err);
});
module.exports = client; |
/**
* Test for form.js
* @author Rafal Marguzewicz
* @license MIT
* @return {undefined}
*
* .toBe()
* .toBeCloseTo(expected, precisionopt)
* .toEqual() // Equal object
* .toBeDefined() - "The 'toBeDefined' matcher compares against `undefined`"
* .toBeUndefined()
* .toBeFalsy()
* .toBeGreaterThan(expected)
* .toBeGreaterThanOrEqual(expected)
* .toBeLessThan(expected)
* .toBeLessThanOrEqual(expected)
* .toBeNan()
* .toBeNull()
* .toBeTruthy()
* .toBeLessThanOrEqual(expected)
* .toHaveBeenCalled()
* .toHaveBeenCalledBefore()
* .toHaveBeenCalledTimes(3)
* .toHaveBeenCalledWith()
* .toMatch()
* .toThrow()
*/
console.log("FormTest: 1.0.0");
var field_input = {
"field": "input",
"type": "text",
"width": "col-md-12",
"name": "name",
"label": "label",
"value": "value",
"require": true
},
field_radio = {
"field": "radio",
"width": "col-md-12",
"items": [
{ "text": "item1", "value": 1 },
{ "text": "item2", "value": 2 },
{ "text": "item3", "checked": true, "value": 3 }
],
"name": "radio",
"label": "radio"
},
body_form = {
"url": "testurl",
"title": "testtitle",
"maximum": 30,
"date_end": "2017-12-31",
"action": "index.php",
"id": "testid",
"method": "get",
"class": "testclass",
"body":'[[{ "field": "input", "type": "text", "width": "col-md-12", "name": "name", "label": "label", "value": "value", "require": true }]]',
}
describe("Test1 form: init", function() {
var form = new MyFORM.Form();
form.init({"autosave": true});
form.setView('text');
it("Generate form", function(){
form.generate(body_form);
//expect(form.model.body).toEqual([[field_input]]);
expect(form.model.title).toBe("testtitle");
expect(form.model.url).toBe("testurl");
expect(form.model.maximum).toBe(30);
expect(form.model.date_end).toBe("2017-12-31");
expect(form.model.action).toBe("index.php");
expect(form.model.class).toBe("testclass");
expect(form.model.method).toBe("get");
expect(form.model.language).toBe("en");
});
it("form init", function() {
expect(form.c.autosave).toBe(true);
expect(form.c.get).toBe(false);
});
it("Add bad field", function() {
var add = form.add({});
expect(add).toBeFalsy();
});
});
describe("Test2 form: add, delete, add unique", function() {
var form2 = new MyFORM.Form();
form2.init({"autosave": true});
form2.setView('text');
it("Add field", function() {
form2.add(field_input);
//expect(form2.model.body).toEqual([[field_input]]);
});
it("delete field", function() {
//expect(form2.deleteField(0,0)).toBe(true);
});
it("Add field and unique name", function() {
var field_copy = field_input;
field_copy.name = field_input.name + '_2';
form2.add(field_input);
//expect(form2.model.body).toEqual([[], [field_input]]);
form2.add(field_input);
//expect(form2.model.body).toEqual( [field_copy]);
});
});
describe("Test3 form: change table names", function() {
var form = new MyFORM.Form();
form.init({"autosave": true});
form.viewMode = 'text';
it("change name", function() {
expect(form.editTableName({"old_name": "name", "new_name": "name"})).toBe(false);
expect(form.editTableName({"old_name": "" ,"new_name": "name"})).toBe(false);
expect(form.editTableName({"old_name": "" ,"new_name": ""})).toBe(false);
expect(form.editTableName({"old_name": "good" ,"new_name": "well"})).toBe(true);
form.c.autosave = false;
expect(form.editTableName({"old_name": "good" ,"new_name": "well"})).toBe(false); // if autosace is false editTableName() return false
});
it("form filter", function() {
expect(form.filter(field_input)).toEqual(field_input);
expect(form.filter()).toBe(false);
});
});
describe("Test3 form: add clone delete add clone", function() {
var form = new MyFORM.Form(),
field = { "field": "input", "type": "text", "width": "col-md-12", "name": "name", "label": "label", },
field2 = { "field": "input", "type": "text", "width": "col-md-12", "name": "name_2", "label": "label_2", },
field3 = { "field": "input", "type": "text", "width": "col-md-12", "name": "name_2_2", "label": "label_2", };
form.init({"autosave": true});
form.viewMode = 'text';
form.add(field); // 1 field name
it("clone field", function() {
var field = form.model.body[0][0];
form.cloneField(0,0); // 2 fields name_2
expect(form.model.body[0][1]).toEqual(field2);
form.deleteField(0,1) // 1 fields
form.add(field); // 2 fields name_2
form.cloneField(1,0) // 3 fileds name_2_2
expect(form.model.body[1][1]).toEqual(field3);
});
});
|
import React from 'react'
import PropTypes from 'prop-types'
import Link from 'gatsby-link'
import styled from 'emotion/react'
import cx from 'classnames'
import { sansfont, childLink, breakpoint1 } from '../layouts/emotion-base'
const Container = styled.section``
const Bio = styled.div`
composes: ${childLink}, ${sansfont};
font-size: 16px;
font-weight: 300;
line-height: 1.4;
& p {
margin-bottom: 24px;
}
`
const DesignerProjects = ({ bioHtml }) => {
return (
<Container>
<Bio dangerouslySetInnerHTML={{ __html: bioHtml }} />
</Container>
)
}
DesignerProjects.propTypes = {
bioHtml: PropTypes.string.isRequired,
}
export default DesignerProjects
|
/*
* Module dependencies.
*/
var PhoneGap = require('../../lib/phonegap'),
project = require('../../lib/phonegap/util/project'),
cordova = require('cordova'),
phonegap,
options;
/*
* Specification: phonegap.local.plugin.list(options, [callback])
*/
describe('phonegap.local.plugin.list(options, [callback])', function() {
beforeEach(function() {
phonegap = new PhoneGap();
options = {};
spyOn(cordova, 'plugin');
spyOn(project, 'cd').andReturn(true);
});
it('should require options', function() {
expect(function() {
options = undefined;
phonegap.local.plugin.list(options, callback);
}).toThrow();
});
it('should not require callback', function() {
expect(function() {
phonegap.local.plugin.list(options);
}).not.toThrow();
});
it('should change to project directory', function() {
phonegap.local.plugin.list(options);
expect(project.cd).toHaveBeenCalledWith({
emitter: phonegap,
callback: jasmine.any(Function)
});
});
it('should return itself', function() {
expect(phonegap.local.plugin.list(options)).toEqual(phonegap);
});
it('should try to list the plugins', function() {
phonegap.local.plugin.list(options);
expect(cordova.plugin).toHaveBeenCalledWith(
'list',
[],
jasmine.any(Function)
);
});
describe('successfully list plugins', function() {
beforeEach(function() {
cordova.plugin.andCallFake(function(command, targets, callback) {
callback(null, [
'org.cordova.core.geolocation',
'org.cordova.core.contacts'
]);
});
});
it('should trigger callback without an error', function(done) {
phonegap.local.plugin.list(options, function(e, plugins) {
expect(e).toBeNull();
done();
});
});
it('should trigger callback with a list of plugin names', function(done) {
phonegap.local.plugin.list(options, function(e, plugins) {
expect(plugins).toEqual([
'org.cordova.core.geolocation',
'org.cordova.core.contacts'
]);
done();
});
});
});
describe('failed to list plugins', function() {
beforeEach(function() {
cordova.plugin.andCallFake(function(command, targets, callback) {
callback(new Error('read access denied'));
});
});
it('should trigger called with an error', function(done) {
phonegap.local.plugin.list(options, function(e, plugins) {
expect(e).toEqual(jasmine.any(Error));
done();
});
});
it('should trigger "error" event', function(done) {
phonegap.on('error', function(e) {
expect(e).toEqual(jasmine.any(Error));
done();
});
phonegap.local.plugin.list(options);
});
});
});
|
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Commandor = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
// Commandor constructor : rootElement is the element
// from wich we capture commands
var Commandor = function Commandor(rootElement, prefix) {
// Event handlers
var _pointerDownListener;
var _pointerUpListener;
var _pointerClickListener;
var _touchstartListener;
var _touchendListener;
var _clickListener;
var _keydownListener;
var _keyupListener;
var _formChangeListener;
var _formSubmitListener;
// Commands hashmap
var _commands = {
'____internal': true
};
// Command prefix
this.prefix = prefix || 'app:';
// Testing rootElement
if(!rootElement) {
throw Error('No rootElement given');
}
// keeping a reference to the rootElement
this.rootElement = rootElement;
// MS Pointer events : should unify pointers, but... read and see by yourself.
if(!!('onmsgesturechange' in window)) {
// event listeners for buttons
(function() {
var curElement = null;
_pointerDownListener = function(event) {
curElement = this.findButton(event.target) || this.findForm(event.target);
curElement && event.preventDefault() || event.stopPropagation();
}.bind(this);
_pointerUpListener = function(event) {
if(curElement) {
if(curElement === this.findButton(event.target)) {
this.captureButton(event);
} else if(curElement === this.findForm(event.target)) {
this.captureForm(event);
}
event.preventDefault();
event.stopPropagation();
curElement = null;
}
}.bind(this);
this.rootElement.addEventListener('MSPointerDown', _pointerDownListener, true);
this.rootElement.addEventListener('MSPointerUp', _pointerUpListener, true);
}).call(this);
// fucking IE10 bug : it doesn't cancel click event
// when gesture events are cancelled
_pointerClickListener = function(event) {
if(this.findButton(event.target)) {
event.preventDefault();
event.stopPropagation();
}
}.bind(this);
this.rootElement.addEventListener('click', _pointerClickListener,true);
} else {
// Touch events
if(!!('ontouchstart' in window)) {
(function() {
// a var keepin' the touchstart element
var curElement = null;
_touchstartListener = function(event) {
curElement = this.findButton(event.target) || this.findForm(event.target);
curElement && event.preventDefault() || event.stopPropagation();
}.bind(this);
this.rootElement.addEventListener('touchstart', _touchstartListener, true);
// checking it's the same at touchend, capturing command if so
_touchendListener = function(event) {
if(curElement == this.findButton(event.target)) {
this.captureButton(event);
} else if(curElement === this.findForm(event.target)) {
this.captureForm(event);
} else {
curElement = null;
}
}.bind(this);
this.rootElement.addEventListener('touchend', _touchendListener, true);
}).call(this);
}
// Clic events
_clickListener = this.captureButton.bind(this);
this.rootElement.addEventListener('click', _clickListener, true);
}
// Keyboard events
// Cancel keydown action (no click event)
_keydownListener = function(event) {
if(
13 === event.keyCode && (
this.findButton(event.target) ||
this.findForm(event.target)
)
) {
event.preventDefault() && event.stopPropagation();
}
}.bind(this);
this.rootElement.addEventListener('keydown', _keydownListener, true);
// Fire on keyup
_keyupListener = function(event) {
if(
13 === event.keyCode &&
!event.ctrlKey
) {
if(this.findButton(event.target)) {
this.captureButton.apply(this, arguments);
} else {
this.captureForm.apply(this, arguments);
}
}
}.bind(this);
this.rootElement.addEventListener('keyup', _keyupListener, true);
// event listeners for forms submission
_formSubmitListener = this.captureForm.bind(this);
this.rootElement.addEventListener('submit', _formSubmitListener, true);
// event listeners for form changes
_formChangeListener = this.formChange.bind(this);
this.rootElement.addEventListener('change', _formChangeListener, true);
this.rootElement.addEventListener('select', _formChangeListener, true);
// Common command executor
this.executeCommand = function (event,command,element) {
if(!_commands) {
throw Error('Cannot execute command on a disposed Commandor object.');
}
// checking for the prefix
if(0 !== command.indexOf(this.prefix)) {
return false;
}
// removing the prefix
command = command.substr(this.prefix.length);
var chunks = command.split('?');
// the first chunk is the command path
var callback = _commands;
var nodes = chunks[0].split('/');
for(var i = 0, j = nodes.length; i < j-1; i++) {
if(!callback[nodes[i]]) {
throw Error('Cannot execute the following command "' + command + '".');
}
callback = callback[nodes[i]];
}
if('function' !== typeof callback[nodes[i]]) {
throw Error('Cannot execute the following command "' + command + '", not a function.');
}
// Preparing arguments
var args = {};
if(chunks[1]) {
chunks = chunks[1].split('&');
for(var k = 0, l = chunks.length; k < l; k++) {
var parts = chunks[k].split('=');
if(undefined !== parts[0] && undefined !== parts[1]) {
args[parts[0]] = decodeURIComponent(parts[1]);
}
}
}
// executing the command fallback
if(callback.____internal) {
return !!!((callback[nodes[i]])(event, args, element));
} else {
return !!!(callback[nodes[i]](event, args, element));
}
return !!!callback(event, args, element);
};
// Add a callback or object for the specified path
this.suscribe = function(path, callback) {
if(!_commands) {
throw Error('Cannot suscribe commands on a disposed Commandor object.');
}
var nodes = path.split('/');
var command = _commands;
for(var i = 0, j = nodes.length-1; i < j; i++) {
if((!command[nodes[i]]) || !(command[nodes[i]] instanceof Object)) {
if(!command.____internal) {
throw Error('Cannot suscribe commands on an external object.');
}
command[nodes[i]] = {
'____internal': true
};
}
command = command[nodes[i]];
}
if(!command.____internal) {
throw Error('Cannot suscribe commands on an external object.');
}
command[nodes[i]] = callback;
};
// Delete callback for the specified path
this.unsuscribe = function(path) {
if(!_commands) {
throw Error('Cannot unsuscribe commands of a disposed Commandor object.');
}
var nodes = path.split('/'),
command = _commands;
for(var i = 0, j = nodes.length-1; i < j; i++) {
command = command[nodes[i]] = {};
}
if(!command.____internal) {
throw Error('Cannot unsuscribe commands of an external object.');
}
command[nodes[i]] = null;
};
// Dispose the commandor object (remove event listeners)
this.dispose = function() {
_commands = null;
if(_pointerDownListener) {
this.rootElement.removeEventListener('MSPointerDown',
_pointerDownListener, true);
this.rootElement.removeEventListener('MSPointerUp',
_pointerUpListener, true);
this.rootElement.removeEventListener('click',
_pointerClickListener, true);
}
if(_touchstartListener) {
this.rootElement.removeEventListener('touchstart',
_touchstartListener, true);
this.rootElement.removeEventListener('touchend',
_touchendListener, true);
}
this.rootElement.removeEventListener('click', _clickListener, true);
this.rootElement.removeEventListener('keydown', _keydownListener, true);
this.rootElement.removeEventListener('keyup', _keyupListener, true);
this.rootElement.removeEventListener('change', _formChangeListener, true);
this.rootElement.removeEventListener('select', _formChangeListener, true);
this.rootElement.removeEventListener('submit', _formSubmitListener, true);
};
};
// Look for a button
Commandor.prototype.findButton = function(element) {
while(element && element.parentNode) {
if(
'A' === element.nodeName &&
element.getAttribute('href') &&
-1 !== element.getAttribute('href').indexOf(this.prefix)
) {
return element;
}
if(
'INPUT' === element.nodeName &&
element.getAttribute('type') && (
element.getAttribute('type') == 'submit' ||
element.getAttribute('type') == 'button'
) &&
element.getAttribute('formaction') &&
-1 !== element.getAttribute('formaction').indexOf(this.prefix)
) {
return element;
}
if(element === this.rootElement) {
return null;
}
element = element.parentNode;
}
return null;
};
// Look for a form
Commandor.prototype.findForm = function(element) {
if(
'FORM' === element.nodeName || (
'INPUT' === element.nodeName &&
element.getAttribute('type') &&
'submit' === element.getAttribute('type')
)
) {
while(element && element.parentNode) {
if(
'FORM' === element.nodeName &&
element.getAttribute('action') &&
-1 !== element.getAttribute('action').indexOf(this.prefix)
) {
return element;
}
if(element === this.rootElement) {
return null;
}
element = element.parentNode;
}
return element;
}
return null;
};
// Look for form change
Commandor.prototype.findFormChange = function(element) {
while(element && element.parentNode) {
if(
'FORM' === element.nodeName &&
element.getAttribute('action') &&
-1 !== element.getAttribute('action').indexOf(this.prefix)
) {
return element;
}
if(element === this.rootElement) {
return null;
}
element = element.parentNode;
}
return element;
};
// Extract the command for a button
Commandor.prototype.doCommandOfButton = function(element, event) {
var command = '';
// looking for a button with formaction attribute
if('INPUT' === element.nodeName) {
command = element.getAttribute('formaction');
// looking for a link
} else if('A' === element.nodeName) {
command = element.getAttribute('href');
}
// executing the command
this.executeCommand(event, command, element);
};
// Button event handler
Commandor.prototype.captureButton = function(event) {
var element = this.findButton(event.target);
// if there is a button, stop event
if(element) {
// if the button is not disabled, run the command
if('disabled' !== element.getAttribute('disabled')) {
this.doCommandOfButton(element, event);
}
event.stopPropagation() || event.preventDefault();
}
};
// Form change handler
Commandor.prototype.formChange = function(event) {
// find the evolved form
var element = this.findFormChange(event.target);
var command = '';
// searching the data-change attribute containing the command
if(element && 'FORM' === element.nodeName) {
command = element.getAttribute('data-change');
}
// executing the command
command && this.executeCommand(event, command, element);
};
// Extract the command for a button
Commandor.prototype.doCommandOfForm = function(element, event) {
var command = '';
// looking for the closest form action attribute
if('FORM' === element.nodeName) {
command = element.getAttribute('action');
}
// executing the command
this.executeCommand(event, command, element);
};
// Form command handler
Commandor.prototype.captureForm = function(event) {
var element = this.findForm(event.target);
// if there is a button, stop event
if(element) {
// if the button is not disabled, run the command
if('disabled' !== element.getAttribute('disabled')) {
this.doCommandOfForm(element, event);
}
event.stopPropagation() || event.preventDefault();
}
};
module.exports = Commandor;
},{}]},{},[1])(1)
}); |
var q = require('q');
var getDeviceAttribute = function(device, attribute, isRegister) {
var saveAttribute = function(bundle) {
var defered = q.defer();
var onSucc = function(res) {
bundle[attribute] = {'result': res};
defered.resolve(bundle);
};
var onErr = function(err) {
bundle[attribute] = {'result': "----", 'error': err};
defered.resolve(bundle);
};
if(isRegister) {
// Perform Device IO & save result to bundle
device.read(attribute)
.then(onSucc, onErr);
} else {
// Perform query for Device Attribute
device[attribute]()
.then(onSucc, onErr);
}
return defered.promise;
};
return saveAttribute;
};
var getDeviceKey = function(device) {
var defered = q.defer();
var bundle = {};
getDeviceAttribute(device, 'deviceType')(bundle)
.then(getDeviceAttribute(device, 'connectionType'))
.then(getDeviceAttribute(device, 'serialNumber'))
.then(function(bundle) {
var key = bundle.deviceType.toString() + '_';
key += bundle.connectionType.toString() + '_';
key += serialNumber.toString();
defered.resolve(key);
});
return defered.promise;
};
exports.getKey = getKey; |
'use strict';
describe('Controller: SubformeditorCtrl', function () {
// load the controller's module
beforeEach(module('umm3601ursamajorApp'));
var SubformeditorCtrl, scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
SubformeditorCtrl = $controller('SubformeditorCtrl', {
$scope: scope
});
}));
it('should ...', function () {
expect(1).toEqual(1);
});
}); |
// JavaScript Document
/* ---------------------------------------------------------------------- */
/* "Polyglot" Language Switcher
/* ----------------------------------------------------------------------
Version: 1.4
Author: Ixtendo
Author URI: http://www.ixtendo.com
License: MIT License
License URI: http://www.opensource.org/licenses/mit-license.php
------------------------------------------------------------------------- */
(function ($) {
$.fn.polyglotLanguageSwitcher = function (op) {
var ls = $.fn.polyglotLanguageSwitcher;
var rootElement = $(this);
var rootElementId = $(this).attr('id');
var aElement;
var ulElement = $("<ul class=\"dropdown\">");
var length = 0;
var isOpen = false;
var liElements = new Array();
var settings = $.extend({}, ls.defaults, op);
var closePopupTimer;
var isStaticWebSite = settings.websiteType == 'static';
var store;
if (isStaticWebSite) {
store = new Persist.Store('Polyglot Language Switcher');
}
init();
installListeners();
function open() {
aElement.addClass("active");
doAnimation(true);
setTimeout(function () {
isOpen = true;
}, 100);
}
function close() {
doAnimation(false);
aElement.removeClass("active");
isOpen = false;
if (closePopupTimer && closePopupTimer.active) {
closePopupTimer.clearTimer();
}
}
function suspendCloseAction() {
if (closePopupTimer && closePopupTimer.active) {
closePopupTimer.pause();
}
}
function resumeCloseAction() {
if (closePopupTimer) {
closePopupTimer.play(false);
}
}
function doAnimation(open) {
if (settings.effect == 'fade') {
if (open) {
ulElement.fadeIn(settings.animSpeed);
} else {
ulElement.fadeOut(settings.animSpeed);
}
} else {
if (open) {
ulElement.slideDown(settings.animSpeed);
} else {
ulElement.slideUp(settings.animSpeed);
}
}
}
function doAction(item) {
if (isOpen) {
close();
}
var selectedAElement = $(item).children(":first-child");
var selectedId = $(selectedAElement).attr("id");
var selectedText = $(selectedAElement).text();
$(ulElement).children().each(function () {
$(this).detach();
});
for (var i = 0; i < liElements.length; i++) {
if ($(liElements[i]).children(":first-child").attr("id") != selectedId) {
ulElement.append(liElements[i]);
}
}
var innerSpanElement = aElement.children(":first-child");
aElement.attr("id", selectedId);
aElement.text(selectedText);
aElement.append(innerSpanElement);
if (isStaticWebSite) {
store.set('lang', selectedId);
}
}
function installListeners() {
$(document).click(function () {
if (isOpen) {
close();
}
});
$(document).keyup(function (e) {
if (e.which == 27 && isOpen) {
close();
}
});
if (settings.openMode == 'hover') {
closePopupTimer = $.timer(function () {
close();
});
closePopupTimer.set({ time:settings.hoverTimeout, autostart:true });
}
}
function init() {
var selectedItem;
$("#" + rootElementId + " > form > select > option").each(function () {
var selected = $(this).attr("selected");
if (isStaticWebSite) {
var selectedId;
store.get('lang', function (ok, val) {
if (ok) {
selectedId = val;
}
});
if (selectedId == $(this).attr("id")) {
selected = true;
}
}
var liElement = toLiElement($(this));
if (selected) {
selectedItem = liElement;
}
liElements.push(liElement);
if (length > 0) {
ulElement.append(liElement);
} else {
aElement = $("<a id=\"" + $(this).attr("id") + "\" class=\"current\" href=\"#\">" + $(this).text() + " <span class=\"trigger\">»</span></a>");
if (settings.openMode == 'hover') {
aElement.hover(function () {
if (!isOpen) {
open();
}
suspendCloseAction();
}, function () {
resumeCloseAction();
});
} else {
aElement.click(
function () {
if (!isOpen) {
open();
}
}
);
}
}
length++;
});
$("#" + rootElementId + " form:first-child").remove();
rootElement.append(aElement);
rootElement.append(ulElement);
if (selectedItem) {
doAction(selectedItem);
}
}
function toLiElement(option) {
var id = $(option).attr("id");
var value = $(option).attr("value");
var text = $(option).text();
var liElement;
if (isStaticWebSite) {
var urlPage = 'http://' + document.domain + '/' + settings.pagePrefix + id + '/' + settings.indexPage;
liElement = $("<li><a id=\"" + id + "\" href=\"" + urlPage + "\">" + text + "</a></li>");
} else {
var href = document.URL.replace('#', '');
var params = parseQueryString();
params[settings.paramName] = value;
if (href.indexOf('?') > 0) {
href = href.substring(0, href.indexOf('?'));
}
href += toQueryString(params);
liElement = $("<li><a id=\"" + id + "\" href=\"" + href + "\">" + text + "</a></li>");
}
liElement.bind('click', function () {
doAction($(this));
if (settings.callback) {
settings.callback.call($(this), $(this).children(":first").attr('id'));
}
});
if (settings.openMode == 'hover') {
liElement.hover(function () {
suspendCloseAction();
}, function () {
resumeCloseAction();
});
}
return liElement;
}
function parseQueryString() {
var params = {};
var query = window.location.search.substr(1).split('&');
if (query.length > 0) {
for (var i = 0; i < query.length; ++i) {
var p = query[i].split('=');
if (p.length != 2) {
continue;
}
params[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
}
return params;
}
function toQueryString(params) {
if (settings.testMode) {
return '#';
} else {
var queryString = '?';
var i = 0;
for (var param in params) {
var x = '';
if (i > 0) {
x = '&';
}
queryString += x + param + "=" + params[param];
i++;
}
return queryString;
}
}
};
var ls = $.fn.polyglotLanguageSwitcher;
ls.defaults = {
openMode:'click',
hoverTimeout:1500,
animSpeed:200,
effect:'slide',
paramName:'lang',
pagePrefix:'',
indexPage:'index.html',
websiteType:'dynamic',
testMode:false,
callback:NaN
};
})(jQuery); |
;(function (root, factory, NULL) {
var BEHAVIOR_GLOBAL_NAME = 'Platformer';
if (typeof define === 'function' && define.amd) {
define(factory);
} else if (typeof module === 'object' && module.exports) {
module.exports = factory();
} else {
var Phaser = root.Phaser;
if (Phaser === NULL) {
root[BEHAVIOR_GLOBAL_NAME] = factory();
} else {
Phaser.Behavior = Phaser.Behavior || {};
Phaser.Behavior[BEHAVIOR_GLOBAL_NAME] = factory();
}
}
}(this, function (NULL) {
'use strict';
function addKeys(game, keyCodes) {
if (!Array.isArray(keyCodes)) {
keyCodes = [keyCodes];
}
return keyCodes.map(function(keyCode) {
return game.input.keyboard.addKey(keyCode);
});
}
function isDown(keys) {
for (let key of keys) {
if (key.isDown) {
return true;
}
}
return false;
}
var Behavior = {
// default settings
options: {
gravity: 600,
velocity: 200,
jumpStrength: 250,
controls: {
left: [Phaser.KeyCode.LEFT],
right: [Phaser.KeyCode.RIGHT],
jump: [Phaser.KeyCode.UP]
}
},
create: function(object, options) {
var gravity = options.gravity;
var controls = options.controls;
if (gravity > 0) {
object.body.gravity.y = gravity;
}
options._control_keys = {
left: addKeys(object.game, controls.left),
right: addKeys(object.game, controls.right),
jump: addKeys(object.game, controls.jump)
};
},
preUpdate: function(object, options) {
var controlKeys = options._control_keys;
var velocity = options.velocity;
if (isDown(controlKeys.left)) {
object.body.velocity.x = -velocity;
} else if (isDown(controlKeys.right)) {
object.body.velocity.x = velocity;
} else {
object.body.velocity.x = 0;
}
if (isDown(controlKeys.jump) && (object.body.touching.down || object.body.blocked.down)) {
object.body.velocity.y = -options.jumpStrength;
}
}
};
return Behavior;
}));
|
import { createSelector } from 'reselect';
import * as commons from './commons';
/**
* Select similar shows from state
*
* @alias module:Shows.getSimilarShows
* @category selectors
*
* @example
* const mapStateToProps = (state, props) => ({
* show: BetaSeries.getSelector('shows', 'getSimilarShows')(state, { showId: props.showId });
* });
*
* @param {Object} [state] Redux state
* @param {Object} [obj] Accept the following:
* @param {Object} [obj.showId] Show ID
*
* @returns {Array} Shows list or `undefined`
*/
const getSimilarShows = createSelector(
[commons.getSimilarShows, commons.getShowId],
(similarShows, showId) =>
!Object.prototype.hasOwnProperty.call(similarShows, showId)
? undefined
: similarShows[showId]
);
export default getSimilarShows;
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M21.98 14H22h-.02zM5.35 13c1.19 0 1.42 1 3.33 1 1.95 0 2.09-1 3.33-1 1.19 0 1.42 1 3.33 1 1.95 0 2.09-1 3.33-1 1.19 0 1.4.98 3.31 1v-2c-1.19 0-1.42-1-3.33-1-1.95 0-2.09 1-3.33 1-1.19 0-1.42-1-3.33-1-1.95 0-2.09 1-3.33 1-1.19 0-1.42-1-3.33-1-1.95 0-2.09 1-3.33 1v2c1.9 0 2.17-1 3.35-1zm13.32 2c-1.95 0-2.09 1-3.33 1-1.19 0-1.42-1-3.33-1-1.95 0-2.1 1-3.34 1-1.24 0-1.38-1-3.33-1-1.95 0-2.1 1-3.34 1v2c1.95 0 2.11-1 3.34-1 1.24 0 1.38 1 3.33 1 1.95 0 2.1-1 3.34-1 1.19 0 1.42 1 3.33 1 1.94 0 2.09-1 3.33-1 1.19 0 1.42 1 3.33 1v-2c-1.24 0-1.38-1-3.33-1zM5.35 9c1.19 0 1.42 1 3.33 1 1.95 0 2.09-1 3.33-1 1.19 0 1.42 1 3.33 1 1.95 0 2.09-1 3.33-1 1.19 0 1.4.98 3.31 1V8c-1.19 0-1.42-1-3.33-1-1.95 0-2.09 1-3.33 1-1.19 0-1.42-1-3.33-1-1.95 0-2.09 1-3.33 1-1.19 0-1.42-1-3.33-1C3.38 7 3.24 8 2 8v2c1.9 0 2.17-1 3.35-1z" />
, 'Water');
|
import React from 'react';
import {
Card, CardText, CardBody, CardLink,
CardTitle, CardSubtitle
} from 'reactstrap';
const Example = (props) => {
return (
<div>
<Card>
<CardBody>
<CardTitle tag="h5">Card title</CardTitle>
<CardSubtitle tag="h6" className="mb-2 text-muted">Card subtitle</CardSubtitle>
</CardBody>
<img width="100%" src="https://picsum.photos/318/180" alt="Card image cap" />
<CardBody>
<CardText>Some quick example text to build on the card title and make up the bulk of the card's content.</CardText>
<CardLink href="#">Card Link</CardLink>
<CardLink href="#">Another Link</CardLink>
</CardBody>
</Card>
</div>
);
};
export default Example;
|
export Elevation from './Elevation'
export default from './Elevation'
|
/**
* @file btoa polyfill
* @since 0.2.9
*/
/*#ifndef(UMD)*/
"use strict";
/*global _GPF_12_BITS*/ // 12
/*global _GPF_18_BITS*/ // 18
/*global _GPF_1_BYTE*/ // 1
/*global _GPF_2_BYTES*/ // 2
/*global _GPF_6_BITS*/ // 6
/*global _GPF_6_BITS_MASK*/ // 63
/*global _GPF_START*/ // 0
/*global _gpfBase64*/ // Base64 encoding string
/*global _gpfMaxUnsignedByte*/ // 255
/*exported _gpfBtoa*/ // btoa polyfill
/*#endif*/
var _GPF_BTOA_MAX_PADDING = 3,
_GPF_BTOA_INDEX_INCREMENT = 3;
function _gpfBtoaCheck (stringToEncode, index) {
var value = stringToEncode.charCodeAt(index);
if (value > _gpfMaxUnsignedByte) {
throw new TypeError("The string to be encoded contains characters outside of the Latin1 range.");
}
return value;
}
function _gpfBtoaRead (input, from) {
var index = from,
a,
b,
c;
a = _gpfBtoaCheck(input, index++);
b = _gpfBtoaCheck(input, index++);
c = _gpfBtoaCheck(input, index++);
return a << _GPF_2_BYTES | b << _GPF_1_BYTE | c;
}
function _gpfBtoaEncodeChar (bitmap, shift, mask) {
return _gpfBase64.charAt(bitmap >> shift & mask);
}
function _gpfBtoaEncode (bitmap) {
return _gpfBtoaEncodeChar(bitmap, _GPF_18_BITS, _GPF_6_BITS_MASK)
+ _gpfBtoaEncodeChar(bitmap, _GPF_12_BITS, _GPF_6_BITS_MASK)
+ _gpfBtoaEncodeChar(bitmap, _GPF_6_BITS, _GPF_6_BITS_MASK)
+ _gpfBtoaEncodeChar(bitmap, _GPF_START, _GPF_6_BITS_MASK);
}
function _gpfBtoa (stringToEncode) {
var index = 0,
result = "",
rest = stringToEncode.length % _GPF_BTOA_MAX_PADDING; // To determine the final padding
for (; index < stringToEncode.length; index += _GPF_BTOA_INDEX_INCREMENT) {
result += _gpfBtoaEncode(_gpfBtoaRead(stringToEncode, index));
}
// If there's need of padding, replace the last 'A's with equal signs
if (rest) {
return result.slice(_GPF_START, rest - _GPF_BTOA_MAX_PADDING) + "===".substring(rest);
}
return result;
}
/*#ifndef(UMD)*/
gpf.internals._gpfBtoa = _gpfBtoa;
/*#endif*/
|
/**
* Module dependencies.
*/
let Base = require('mocha/lib/reporters/base');
let inherits = require('mocha/lib/utils').inherits;
let ms = require('ms');
let color = Base.color;
/**
* Expose `BaseReporter`.
*/
exports = module.exports = BaseReporter;
/**
* Expose all `Base` exports.
*/
Object.assign(exports, Base);
/**
* Initialize a new Bocha `Base` reporter.
*
* All other bocha reporters generally
* inherit from this reporter,
* providing additional stats
* as number of skipped and focused tests
*
* @param {Runner} runner
* @api public
*/
function BaseReporter(runner) {
Base.call(this, runner);
let self = this;
let stats = self.stats;
stats.focused = 0;
stats.skipped = 0;
// skipped
runner.on('pending', function (test) {
if (test.isSkipped) {
stats.skipped++;
stats.pending--;
}
});
// focused
runner.on('test', function (test) {
if (test.isFocused) {
stats.focused++;
}
});
runner.on('end', function () {
// remove hook-related output
self.failures.forEach(function (failure) {
overrideFullTitle(failure);
});
});
}
/**
* Inherit from `Base.prototype`.
*/
inherits(BaseReporter, Base);
BaseReporter.prototype.focusRocket = function () {
let stats = this.stats;
let pluralizedTestText = stats.focused === 1 ? 'test' : 'tests';
let fmt = color('bright yellow', ' ')
+ color('bright yellow', ' %s')
+ color('light', ' (running %d ' + pluralizedTestText + ')');
console.log(fmt, '=> Focus rocket engaged', stats.focused);
console.log();
};
BaseReporter.prototype.epilogue = function () {
let stats = this.stats;
let fmt;
// focus rocket
if (stats.focused) {
this.focusRocket();
}
// passes
fmt = color('bright pass', ' ') + color('green', ' %d passing') + color('light', ' (%s)');
console.log(fmt, stats.passes || 0, ms(stats.duration));
// failures
fmt = color('fail', ' ') + color('fail', ' %d failing');
console.log(fmt, stats.failures || 0);
// pending
if (stats.pending) {
fmt = color('pending', ' ') + color('pending', ' %d pending');
console.log(fmt, stats.pending);
}
// skipped
if (stats.skipped) {
fmt = color('pending', ' ') + color('pending', ' %d skipped');
console.log(fmt, stats.skipped);
}
console.log();
};
function overrideFullTitle(test) {
test.fullTitle = function () {
return test.type === 'hook' ? test.title.replace(/.+:\sbound\s/, '') : test.title;
};
} |
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string'),
urls: DS.attr('string'),
contacts: DS.hasMany('contact')
});
|
"use strict";
var log_load_time = function() {
var t0 = new Date().getTime();
$(document).ready(function(){
var t1 = new Date().getTime();
var td = t1 - t0;
chrome.storage.local.get(null, function(value) {
var current_date = (new Date()).toISOString().substr(0, 10);
if (current_date in value) {
value[current_date] += td;
} else {
value[current_date] = td;
}
chrome.storage.local.set(value, function () { });
});
});
}();
|
/*jslint browser: true, nomen: true, regexp: true, vars: true, white: true */
/*global define, window, console, describe, it, before, beforeEach, after, afterEach */
/*
* Utilities
*/
define(['underscore'],
function(_) {
'use strict';
function Callback(cb, ctx) {
this.callback = cb;
this.context = ctx;
}
function Bus() {
this._data = [];
}
Bus.prototype = {
push: function(callback, object) {
//console.log("[Bus:push]", arguments);
if(!this.has(callback, object)) {
this._data.push(new Callback(callback, object));
}
},
pop: function(callback, object) {
//console.log("[Bus:pop]", arguments);
var index = this.indexOf(callback, object);
if(index>=0) {
delete(this._data[index]);
}
},
call: function(args) {
//console.log("[Bus:call]", arguments);
_.each(this._data, function(cb) {
//console.log("", "[Bus:call]", cb);
cb.callback.call(cb.context||this, args);
}, this);
},
has: function(callback, object) {
//console.log("[Bus:has]", arguments);
return _.some(this._data, function(cb, index) {
//console.log("[Bus:index:some]", arguments);
return (callback===cb.callback) && (object===cb.context);
}, this);
},
indexOf: function(callback, object) {
//console.log("[Bus:indexOf]", arguments);
return _.indexOf(_.findWhere(this._data, {
callback: callback,
context: object
}));
}
};
function Utils() {
}
Utils.prototype = {
type: function(val) {
return Object.prototype.toString.call(val).replace(/^\[object (.+)\]$/,"$1").toLowerCase();
},
merge: function (object, add) {
var This = this;
_.each(add, function(value, key) {
if (This.type(key) === "string" &&
"type" === key.toLowerCase() &&
"merge" === key.toLowerCase() &&
"update" === key.toLowerCase()) {
return;
}
if(typeof (value) === "object") {
this[key] = This.type(value) === "array" ? [] : {};
This.merge(this[key], value);
} else {
this[key] = value;
}
}, object);
},
update: function(object, add, space) {
var This = this;
if(typeof (space) === "undefined") {
space = "";
}
_.each(add, function (value, key) {
if (This.type(key) === "string" &&
"type" === key.toLowerCase() &&
"merge" === key.toLowerCase() &&
"update" === key.toLowerCase() &&
"guid" === key.toLowerCase()) {
return;
}
if(typeof (value) === "object") {
//console.log(space, key, "= {");
this[key] = This.type(value) === "array" ? [] : {};
This.update(this[key], value, space + " ");
//console.log(space, "}");
} else {
//console.log(space, key, "=", value);
this[key] = value;
}
}, object);
},
guid: function () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random()*16 | 0,
v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
},
// Changes XML to JSON
xmlToJson: function (xml) {
// Create the return object
var obj = {};
if (xml.nodeType === 1) { // element
// do attributes
if (xml.attributes.length > 0) {
obj["@attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType == 3) { // text
obj = xml.nodeValue;
}
// do children
if (xml.hasChildNodes()) {
for(var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
if (typeof(obj[nodeName]) == "undefined") {
obj[nodeName] = this.xmlToJson(item);
} else {
if (typeof(obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(this.xmlToJson(item));
}
}
}
return obj;
},
bus: {
_events: {},
trigger: function (evt, args) {
//console.log('[bus:trigger]', arguments, this);
if (this._events.hasOwnProperty(evt)) {
this._events[evt].call(args);
}
},
on: function (evt, callback, object) {
//console.log('[bus:on]', arguments, this);
if (!this._events.hasOwnProperty(evt)) {
this._events[evt] = new Bus();
}
this._events[evt].push(callback, object);
},
off: function (evt, callback, object) {
//console.log('[bus:off]', arguments, this);
if(this._events.hasOwnProperty(evt)) {
this._events[evt].pop(callback, object);
}
}
}
};
return new Utils();
}); |
'use strict';
var $ = require('jquery');
var Backbone = require('backbone');
Backbone.$ = $;
var _ = require('underscore');
var FdaService = require('../../service/fdaService');
var DrugRecallInfoView = Backbone.View.extend({
initialize: function(options) {
this.isRecalled = options.isRecalled;
this.template = _.template($('#drug-recall-info').html());
//get drug info
var recallDrug;
if(typeof options.drug === 'object') {
recallDrug = options.drug;
recallDrug.isRecalled = options.isRecalled;
} else {
recallDrug = {
id: options.drug,
isRecalled: options.isRecalled
};
}
this.drug = recallDrug;
},
render: function() {
console.log('rendering label: ', this.drug);
this.$el.html(this.template(this.drug));
this.deleteLastResults();
return this;
},
deleteLastResults: function() {
var self = this;
var numChildren = $('#primary-content').length;
if(numChildren > 1)
{
$('#primary-content:last-child').remove();
}
}
});
module.exports = DrugRecallInfoView; |
/* global process, __dirname */
const path = require('path')
const PROD_EXT = '.prod'
function fixImportSource ({ node: { source } }, { filename }) {
if (shouldIgnoreImport(source)) return
let resolvedShort = ''
try {
const paths = [filename && path.dirname(filename), __dirname, process.cwd()].filter((p) => !!p)
const resolved = require.resolve(source.value, { paths })
const resolvedWithoutScopePath = resolved.replace(/.*[\\/]@interactjs[\\/]/, '')
resolvedShort = path
.join('@interactjs', resolvedWithoutScopePath)
// windows path to posix
.replace(/\\/g, '/')
source.value = resolvedShort.replace(/(\.js)?$/, PROD_EXT)
} catch (e) {}
}
function babelPluginInteractjsProd () {
if (process.env.NODE_ENV === 'development') {
// eslint-disable-next-line no-console
console.warn(
"[@interactjs/dev-tools] You're using the production plugin in the development environment. You might lose out on some helpful hints!",
)
}
return {
visitor: {
ImportDeclaration: fixImportSource,
ExportNamedDeclaration: fixImportSource,
ExportAllDeclaration: fixImportSource,
ExportDefaultSpecifier: fixImportSource,
},
}
}
function shouldIgnoreImport (source) {
return (
!source ||
// only change @interactjs scoped imports
!source.value.startsWith('@interactjs/') ||
// ignore imports of prod files
source.value.endsWith(PROD_EXT) ||
source.value.endsWith(PROD_EXT + '.js')
)
}
module.exports = babelPluginInteractjsProd
Object.assign(module.exports, {
default: babelPluginInteractjsProd,
fixImportSource,
})
|
// Inspired by and adapted from
// https://github.com/angular/angular.js/blob/master/src/auto/injector.js
function Injector(options) {
// Class variables
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,\s*/;
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var extractArgumentNames = function(fn) {
var fnCode = fn.toString().replace(STRIP_COMMENTS, '');
var argDeclaration = fnCode.match(FN_ARGS);
var argNames = argDeclaration[1].split(FN_ARG_SPLIT);
return argNames;
};
this.inject = function(fn, context) {
context = context || {};
return function() {
var argName;
var args = [];
var fnArgs = extractArgumentNames(fn);
var len = fnArgs.length;
for(var i = 0; i < len; i += 1) {
argName = fnArgs[i];
args.push(options[argName]);
}
return fn.apply(context, args);
};
};
this.update = function(moreOptions) {
var option;
for (option in moreOptions) {
if (moreOptions.hasOwnProperty(option)) {
options[option] = moreOptions[option];
}
}
};
}
module.exports = Injector;
|
// flow-typed signature: fec0f703a9e8334c274a5a19c1c5f0a6
// flow-typed version: <<STUB>>/recursive-readdir-sync_v^1.0.6/flow_v0.54.0
/**
* This is an autogenerated libdef stub for:
*
* 'recursive-readdir-sync'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'recursive-readdir-sync' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'recursive-readdir-sync/test/index' {
declare module.exports: any;
}
declare module 'recursive-readdir-sync/test/nested/a/b/file2' {
declare module.exports: any;
}
// Filename aliases
declare module 'recursive-readdir-sync/index' {
declare module.exports: $Exports<'recursive-readdir-sync'>;
}
declare module 'recursive-readdir-sync/index.js' {
declare module.exports: $Exports<'recursive-readdir-sync'>;
}
declare module 'recursive-readdir-sync/test/index.js' {
declare module.exports: $Exports<'recursive-readdir-sync/test/index'>;
}
declare module 'recursive-readdir-sync/test/nested/a/b/file2.js' {
declare module.exports: $Exports<'recursive-readdir-sync/test/nested/a/b/file2'>;
}
|
'use strict';
const app = require('express')();
const tape = require('tape');
const PORT_RANGE_START = 9000;
// -----------------------------------------------------------------------------
app.get('/alpha.html', (req, res) => {
res.type('html');
res.send('<html><body><h1>alpha</h1></body></html>');
});
app.get('/alpha.json', (req, res) => {
res.json({
name: 'alpha'
});
});
// -----------------------------------------------------------------------------
let lastPort = PORT_RANGE_START;
function getHostInfo() {
const info = {
port: lastPort,
hostname: `localhost:${lastPort}`
};
lastPort = lastPort + 1;
return info;
}
function start(callback) {
const hostInfo = getHostInfo();
const server = app.listen(hostInfo.port, callback);
return server;
}
function test(testDesc, testFn) {
const server = start(() => {
tape(testDesc, (assert) => {
testFn(assert, server, () => {
server.close();
});
});
});
}
// -----------------------------------------------------------------------------
module.exports = {
start,
test
};
|
'use strict';
describe('Controller: HighwaysCtrl', function () {
// load the controller's module
beforeEach(module('intelliroadsApp'));
var HighwaysCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
HighwaysCtrl = $controller('HighwaysCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(scope.awesomeThings.length).toBe(3);
});
});
|
import { expect } from "chai";
import sinon from "sinon";
import { buildSchema } from "#/helpers/schema.helper.js";
describe("Schema", () => {
it("should be a valid GraphQL schema", () => {
sinon.stub(console, "warn");
let schema = buildSchema();
if (console.warn.called) {
throw new Error(console.warn.getCall(0).args.join(", "));
}
console.warn.restore();
expect(schema).to.be.an("object");
});
});
|
module.exports = {
presets: ['@babel/preset-env'],
plugins: [
['@babel/plugin-transform-runtime', {
useESModules: true,
}],
'@babel/plugin-proposal-object-rest-spread',
'@babel/plugin-proposal-class-properties',
],
};
|
'use strict'
const path = require('path')
const pkg = require('./app/package.json')
const settings = require('./config.js')
const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
let config = {
devtool: '#eval-source-map',
eslint: {
formatter: require('eslint-friendly-formatter')
},
entry: {
build: path.join(__dirname, 'app/src/main.js')
},
module: {
preLoaders: [],
loaders: [{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
}, {
test: /\.html$/,
loader: 'vue-html-loader'
},
/**
* Temporary fix for electron-settings being written in es6, since uglifyjs doesn't work well with es6
**/
{
test: [/node_modules[\\\/](?:electron-settings|key-path-helpers)[\\\/]lib[\\\/](?:.+).js/],
loaders: ['babel-loader']
}, {
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
}, {
test: /\.json$/,
loader: 'json-loader'
}, {
test: /\.vue$/,
loader: 'vue-loader'
}, {
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 10000,
name: 'imgs/[name].[hash:7].[ext]'
}
}, {
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 10000,
name: 'fonts/[name].[hash:7].[ext]'
}
}
]
},
plugins: [
new ExtractTextPlugin('styles.css'),
new HtmlWebpackPlugin({
filename: 'index.html',
template: './app/index.ejs',
title: settings.name
}),
new HtmlWebpackPlugin({
filename: 'loading.html',
template: './app/loading.ejs',
title: settings.name,
inject: false
}),
new CopyWebpackPlugin([{
from: 'app/assets',
to: 'assets'
}]),
new webpack.NoErrorsPlugin()
],
output: {
filename: '[name].js',
path: path.join(__dirname, 'app/dist')
},
resolve: {
alias: {
'components': path.join(__dirname, 'app/src/components'),
'src': path.join(__dirname, 'app/src')
},
extensions: ['', '.js', '.vue', '.json', '.css'],
fallback: [path.join(__dirname, 'app/node_modules')]
},
resolveLoader: {
root: path.join(__dirname, 'node_modules')
},
target: 'electron-renderer',
vue: {
loaders: {
sass: 'vue-style-loader!css-loader!sass-loader?indentedSyntax=1',
scss: 'vue-style-loader!css-loader!sass-loader'
}
}
}
if (process.env.NODE_ENV !== 'production') {
/**
* Apply ESLint
*/
if (settings.eslint) {
config.module.preLoaders.push({
test: /\.js$/,
loader: 'eslint-loader',
exclude: /node_modules/
}, {
test: /\.vue$/,
loader: 'eslint-loader'
})
}
}
/**
* Adjust config for production settings
*/
if (process.env.NODE_ENV === 'production') {
config.devtool = ''
config.plugins.push(
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"production"'
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
)
}
module.exports = config |
'use strict';
var path = require('path');
var test = require('ava');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');
test.before(() => {
var pkg = require('../package.json');
var deps = [
[helpers.createDummyGenerator(), 'statisk:gulp']
];
return helpers.run(path.join(__dirname, '../generators/app'))
.withOptions({
name: pkg.name,
version: pkg.version,
uploading: 'None'
})
.withGenerators(deps)
.toPromise();
});
test('creates gulpfile', () => {
assert.file('gulpfile.js');
});
test('creates package.json', () => {
assert.file('package.json');
});
test('creates comment about creation', () => {
const pkg = require('../package.json');
const date = (new Date()).toISOString().split('T')[0];
assert.fileContent('gulpfile.js', '// generated on ' + date + ' using ' + pkg.name + ' ' + pkg.version);
});
test('creates gulp task files', () => {
assert.file([
'gulp/tasks/assets.js',
'gulp/tasks/clean.js',
'gulp/tasks/copy.js',
'gulp/tasks/fonts.js',
'gulp/tasks/html.js',
'gulp/tasks/images.js',
'gulp/tasks/inject.js',
'gulp/tasks/uploading.js'
]);
});
|
'use strict';
var app = angular.module('Fablab');
app.controller('UserPaymentListController', function ($scope, $filter, $location,$rootScope,
ngTableParams, UserPaymentService, NotificationService) {
$scope.currency = App.CONFIG.CURRENCY;
$scope.showRole = $rootScope.hasAnyRole('PAYMENT_MANAGE');
$scope.tableParams = new ngTableParams(
angular.extend({
page: 1, // show first page
count: 25, // count per page
sorting: {
datePayment: 'desc'
}
}, $location.search()), {
getData: function ($defer, params) {
if ($scope.userPayments) {
params.total($scope.userPayments.length);
$location.search(params.url());
var filteredData = params.filter() ? $filter('filter')($scope.userPayments, params.filter()) : $scope.userPayments;
var orderedData = params.sorting() ? $filter('orderBy')(filteredData, params.orderBy()) : filteredData;
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
}
});
var updateUserPaymentList = function () {
UserPaymentService.list(function (data) {
if ($rootScope.hasAnyRole('PAYMENT_MANAGE')) {
for (var i = 0; i < data.length; i++) {
data[i].userFirstname = ""; //initialization of new property
data[i].userFirstname = $filter('prettyUser')(data[i].user); //set the data from nested obj into new property
}
$scope.userPayments = data;
} else {
var res = [];
for (var i = 0; i < data.length; i++) {
if (data[i].user.id === $rootScope.connectedUser.user.id) {
data[i].userFirstname = ""; //initialization of new property
data[i].userFirstname = $filter('prettyUser')(data[i].user); //set the data from nested obj into new property
res.push(data[i]);
}
}
$scope.userPayments = res;
}
$scope.tableParams.reload();
});
};
$scope.remove = function (userPayment) {
UserPaymentService.remove(userPayment.id, function () {
NotificationService.notify("success", "userPayment.notification.removed");
updateUserPaymentList();
});
};
$scope.softRemove = function (userPayment) {
UserPaymentService.softRemove(userPayment.id, function () {
NotificationService.notify("success", "userPayment.notification.removed");
updateUserPaymentList();
});
};
updateUserPaymentList();
});
|
define(["require", "exports", "@microsoft/load-themed-styles"], function (require, exports, load_themed_styles_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
load_themed_styles_1.loadTheme({
'themePrimary': 'red'
});
});
//# sourceMappingURL=ThemeCode.Example.js.map
|
const express = require('express')
const router = module.exports = express.Router()
router.use('/rest', require('./rest'))
router.use('/graphql', require('./graphql'))
router.get('*', function (req, res) {
res.status(404).send({ message: 'resource not found' })
})
|
// Basic utility functions for srt.js
// Kazutaka Kurihara @qurihara
// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
//alert('ok');
} else {
alert('The File APIs are not fully supported in this browser.');
}
var getUrlVars = function(){
var vars = {};
var param = location.search.substring(1).split('&');
for(var i = 0; i < param.length; i++) {
var keySearch = param[i].search(/=/);
var key = '';
if(keySearch != -1) key = param[i].slice(0, keySearch);
var val = param[i].slice(param[i].indexOf('=', 0) + 1);
if(key != '') vars[key] = decodeURIComponent(val);
}
return vars;
}
//console.log(getUrlVars());
function unescapeHTML(str) {
return str.replace(/</g,'<')
.replace(/>/g,'>')
.replace(/&/g,'&');
}
var hasSubtitle = false;
var sTimeList = [];
var eTimeList = [];
var subList = [];
var totalSubTime = 0;
function parseSrt(srt) {
sTimeList = [];
eTimeList = [];
subList = [];
var i=0;
var lines = srt.replace( /\r\n/g , "\n" ).split('\n');
// console.log(lines);
do{
if (lines[i] == '')break;
//lines[i] is a number
// console.log(lines[i]);
i++; // index number can be any string.
//lines[i] is a timespan
var time = parseTimeSpan(lines[i]);
sTimeList.push(time[0]);
eTimeList.push(time[1]);
totalSubTime += (time[1]-time[0]);
var sub = '';
i++;
do{
//lines[i] is a sub
sub += lines[i] + '\n';
i++;
}while(i<lines.length && lines[i] != '');
sub = unescapeHTML(sub);
subList.push(sub);
i++;
} while (i<lines.length);
if (srt.length>0){
console.log("subtitles loaded.");
hasSubtitle = true;
}
}
function parseTimeSpan(tm) {
var t = tm.split(" --> ");
var p1,p2;
if (t.length === 1){ // simplified timespan notation
p1 = parseTime(t[0]);
p2 = p1 + 100;
}else{ // normal timespan notation
p1 = parseTime(t[0]);
p2 = parseTime(t[1]);
}
var time = [p1,p2];
return time;
}
function parseTime(t){
// 00:02:09,230
// var d = new Date(2012, 0, 30, 14, 29, 50, 500);
var d = t.replace(".",",").split(",");
var d2 = d[0].split(":");
var dat = new Date(0,0,0,parseInt(d2[0]),parseInt(d2[1]),parseInt(d2[2]) ,parseInt(d[1]));
// console.log(dat.getHours());
// console.log(dat.getMinutes());
// console.log(dat.getSeconds());
// console.log(dat.getMilliseconds());
return dat.getTime();
}
var ref = new Date(0,0,0,0,0,0,0).getTime();
function isInSub(time,offset){
var tt = ref + time*1000;
for(var i=0;i<sTimeList.length;i++){
if (sTimeList[i]-offset<=tt && tt < eTimeList[i]) {
return true;
}
}
return false;
}
function isInWhichSub(time,offset){
var tt = ref + time*1000;
for(var i=0;i<sTimeList.length;i++){
if (sTimeList[i]-offset<=tt && tt < eTimeList[i]) {
return i;
}
}
return -1;
}
function getNewDuration(ms,ss,offset,dur){
//return totalSubTime / ss + (dur - totalSubTime) / ms;
var first=true;
var teTimeList = [];
var tsTimeList = [];
for(var i=0;i<sTimeList.length;i++){
tsTimeList.push(sTimeList[i]);
teTimeList.push(eTimeList[i]);
if (first == true) {
first = false;
continue;
}
var int = sTimeList[i] - eTimeList[i-1];
if (offset > int){
tsTimeList.push(eTimeList[i-1]);
teTimeList.push(sTimeList[i]);
}else{
tsTimeList.push(sTimeList[i]-offset);
teTimeList.push(sTimeList[i]);
}
}
var ttotalSubTime=0;
for(var i=0;i<tsTimeList.length;i++){
ttotalSubTime += (teTimeList[i]-tsTimeList[i]);
}
//console.log(ttotalSubTime + " " + totalSubTime);
var newDuration = ttotalSubTime / ss + (dur - ttotalSubTime) / ms;
var earned = (dur - newDuration) / 1000;
var percent = newDuration / dur * 100;
var d = new Date(0);
var utc = d.getTimezoneOffset() * 60000;
var nd = new Date(utc + newDuration);
return [newDuration,earned,percent,nd];
}
var formatDate = function (date, format) {
if (!format) format = 'YYYY-MM-DD hh:mm:ss.SSS';
format = format.replace(/YYYY/g, date.getFullYear());
format = format.replace(/MM/g, ('0' + (date.getMonth() + 1)).slice(-2));
format = format.replace(/DD/g, ('0' + date.getDate()).slice(-2));
format = format.replace(/hh/g, ('0' + date.getHours()).slice(-2));
format = format.replace(/mm/g, ('0' + date.getMinutes()).slice(-2));
format = format.replace(/ss/g, ('0' + date.getSeconds()).slice(-2));
if (format.match(/S/g)) {
var milliSeconds = ('00' + date.getMilliseconds()).slice(-3);
var length = format.match(/S/g).length;
for (var i = 0; i < length; i++) format = format.replace(/S/, milliSeconds.substring(i, i + 1));
}
return format;
};
function getSubFromUrl(sUrl, callback){
var a=new XMLHttpRequest();
a.onreadystatechange=function()
{
if(a.readyState==4&&a.status==200)
{
parseSrt(a.responseText);
callback(false);
}else{
callback(true);
}
}
a.open("GET",sUrl);
a.send(null);
}
function shiftBackSubtitles(shift){
for (var i=0;i<sTimeList.length;i++){
sTimeList[i] -= shift;
eTimeList[i] -= shift;
}
}
|
function WidgetModel(theFreeboardModel, widgetPlugins) {
function disposeWidgetInstance() {
if (!_.isUndefined(self.widgetInstance)) {
if (_.isFunction(self.widgetInstance.onDispose)) {
self.widgetInstance.onDispose();
}
self.widgetInstance = undefined;
}
}
var self = this;
this.datasourceRefreshNotifications = {};
this.calculatedSettingScripts = {};
this.title = ko.observable();
this.fillSize = ko.observable(false);
this.type = ko.observable();
this.type.subscribe(function (newValue) {
disposeWidgetInstance();
if ((newValue in widgetPlugins) && _.isFunction(widgetPlugins[newValue].newInstance)) {
var widgetType = widgetPlugins[newValue];
function finishLoad() {
widgetType.newInstance(self.settings(), function (widgetInstance) {
self.fillSize((widgetType.fill_size === true));
self.widgetInstance = widgetInstance;
self.shouldRender(true);
self._heightUpdate.valueHasMutated();
});
}
// Do we need to load any external scripts?
if (widgetType.external_scripts) {
head.js(widgetType.external_scripts.slice(0), finishLoad); // Need to clone the array because head.js adds some weird functions to it
}
else {
finishLoad();
}
}
});
this.settings = ko.observable({});
this.settings.subscribe(function (newValue) {
if (!_.isUndefined(self.widgetInstance) && _.isFunction(self.widgetInstance.onSettingsChanged)) {
self.widgetInstance.onSettingsChanged(newValue);
}
self.updateCalculatedSettings();
self._heightUpdate.valueHasMutated();
});
this.processDatasourceUpdate = function (datasourceName) {
var refreshSettingNames = self.datasourceRefreshNotifications[datasourceName];
if (_.isArray(refreshSettingNames)) {
_.each(refreshSettingNames, function (settingName) {
self.processCalculatedSetting(settingName);
});
}
}
this.callValueFunction = function (theFunction) {
return theFunction.call(undefined, theFreeboardModel.datasourceData);
}
this.processSizeChange = function () {
if (!_.isUndefined(self.widgetInstance) && _.isFunction(self.widgetInstance.onSizeChanged)) {
self.widgetInstance.onSizeChanged();
}
}
this.processCalculatedSetting = function (settingName) {
if (_.isFunction(self.calculatedSettingScripts[settingName])) {
var returnValue = undefined;
try {
returnValue = self.callValueFunction(self.calculatedSettingScripts[settingName]);
}
catch (e) {
var rawValue = self.settings()[settingName];
// If there is a reference error and the value just contains letters and numbers, then
if (e instanceof ReferenceError && (/^\w+$/).test(rawValue)) {
returnValue = rawValue;
}
}
if (!_.isUndefined(self.widgetInstance) && _.isFunction(self.widgetInstance.onCalculatedValueChanged) && !_.isUndefined(returnValue)) {
try {
self.widgetInstance.onCalculatedValueChanged(settingName, returnValue);
}
catch (e) {
console.log(e.toString());
}
}
}
}
this.updateCalculatedSettings = function () {
self.datasourceRefreshNotifications = {};
self.calculatedSettingScripts = {};
if (_.isUndefined(self.type())) {
return;
}
// Check for any calculated settings
var settingsDefs = widgetPlugins[self.type()].settings;
var datasourceRegex = new RegExp("datasources.([\\w_-]+)|datasources\\[['\"]([^'\"]+)", "g");
var currentSettings = self.settings();
_.each(settingsDefs, function (settingDef) {
if (settingDef.type == "calculated") {
var script = currentSettings[settingDef.name];
if (!_.isUndefined(script)) {
// If there is no return, add one
if ((script.match(/;/g) || []).length <= 1 && script.indexOf("return") == -1) {
script = "return " + script;
}
var valueFunction;
try {
valueFunction = new Function("datasources", script);
}
catch (e) {
var literalText = currentSettings[settingDef.name].replace(/"/g, '\\"').replace(/[\r\n]/g, ' \\\n');
// If the value function cannot be created, then go ahead and treat it as literal text
valueFunction = new Function("datasources", "return \"" + literalText + "\";");
}
self.calculatedSettingScripts[settingDef.name] = valueFunction;
self.processCalculatedSetting(settingDef.name);
// Are there any datasources we need to be subscribed to?
var matches;
while (matches = datasourceRegex.exec(script)) {
var dsName = (matches[1] || matches[2]);
var refreshSettingNames = self.datasourceRefreshNotifications[dsName];
if (_.isUndefined(refreshSettingNames)) {
refreshSettingNames = [];
self.datasourceRefreshNotifications[dsName] = refreshSettingNames;
}
if(_.indexOf(refreshSettingNames, settingDef.name) == -1) // Only subscribe to this notification once.
{
refreshSettingNames.push(settingDef.name);
}
}
}
}
});
}
this._heightUpdate = ko.observable();
this.height = ko.computed({
read: function () {
self._heightUpdate();
if (!_.isUndefined(self.widgetInstance) && _.isFunction(self.widgetInstance.getHeight)) {
return self.widgetInstance.getHeight();
}
return 1;
}
});
this.shouldRender = ko.observable(false);
this.render = function (element) {
self.shouldRender(false);
if (!_.isUndefined(self.widgetInstance) && _.isFunction(self.widgetInstance.render)) {
self.model = self.widgetInstance.render(element);
self.updateCalculatedSettings();
}
}
this.dispose = function () {
}
this.serialize = function () {
return {
title: self.title(),
type: self.type(),
settings: self.settings()
};
}
this.deserialize = function (object) {
self.title(object.title);
self.settings(object.settings);
self.type(object.type);
}
}
|
import Wms from 'ember-flexberry-gis/locales/ru/components/layers-dialogs/settings/wms';
export default Wms;
|
import React, { Component, PropTypes } from 'react';
import Helmet from 'react-helmet';
import {connect} from 'react-redux';
import { routeActions } from 'react-router-redux';
@connect(
null,
{pushState: routeActions.push}
)
export default class Home extends Component {
static propTypes = {
pushState: PropTypes.func.isRequired
};
submitUrl = (event) => {
event.preventDefault();
const codeUrl = btoa(this.refs.Url.value);
this.props.pushState(`/clean/${codeUrl}`);
};
render() {
return (
<div>
<Helmet title="Главная"/>
<header id="header">
<div className="inner">
<a href="index.html" className="logo">
<span className="symbol"><img src="images/logo.svg" alt="" /></span><span className="title">Lucy25</span>
</a>
</div>
</header>
<div id="main">
<div className="inner">
<header>
<h1>Делаем некрасивое красивым.</h1>
</header>
<section className="tiles">
<h2 style={{width: '100%'}}>Введите адресс страницы</h2>
<br />
<form style={{width: '50%'}} action="">
<div className="field half first">
<input ref="Url" type="text" name="url" id="url" placeholder="URL" />
</div>
<ul className="actions">
<li><input onClick={this.submitUrl} type="submit" value="Обработать" className="special" /></li>
</ul>
</form>
</section>
</div>
</div>
<footer id="footer">
<div className="inner">
<ul className="copyright">
<li>© Lucy25. All rights reserved</li>
<li><a target="_blank" href="http://github.com/suribit/Lucy25">suribit</a> 2016</li>
</ul>
</div>
</footer>
</div>
);
}
}
|
// ------------------------------------
// Nodeload configuration
// ------------------------------------
//
// The functions in this file control the behavior of the nodeload globals, like HTTP_SERVER and
// REPORT_MANAGER. They should be called when the library is included:
//
// var nl = require('./lib/nodeload').quiet().usePort(10000);
// nl.runTest(...);
//
// Or, when using individual modules:
//
// var nlconfig = require('./lib/config').quiet().usePort(10000);
// var reporting = require('./lib/reporting');
//
var BUILD_AS_SINGLE_FILE, NODELOAD_CONFIG;
if (!BUILD_AS_SINGLE_FILE) {
var EventEmitter = require('events').EventEmitter;
}
/** Suppress all console output */
exports.quiet = function() {
NODELOAD_CONFIG.QUIET = true;
return exports;
};
/** Start the nodeload HTTP server on the given port */
exports.usePort = function(port) {
NODELOAD_CONFIG.HTTP_PORT = port;
return exports;
};
/** Do not start the nodeload HTTP server */
exports.disableServer = function() {
NODELOAD_CONFIG.HTTP_ENABLED = false;
return exports;
};
/** Set the default number of milliseconds between 'update' events from a LoadTest created by run(). */
exports.setMonitorIntervalMs = function(milliseconds) {
NODELOAD_CONFIG.MONITOR_INTERVAL_MS = milliseconds;
return exports;
};
/** Set the number of milliseconds between auto-refreshes for the summary webpage */
exports.setAjaxRefreshIntervalMs = function(milliseconds) {
NODELOAD_CONFIG.AJAX_REFRESH_INTERVAL_MS = milliseconds;
return exports;
};
/** Set the optionnal comment for the summary webpage */
exports.setReportComment = function(reportComment) {
NODELOAD_CONFIG.REPORT_COMMENT = reportComment;
return exports;
};
/** Do not write any logs to disk */
exports.disableLogs = function() {
NODELOAD_CONFIG.LOGS_ENABLED = false;
return exports;
};
/** Set the number of milliseconds between pinging slaves when running distributed load tests */
exports.setSlaveUpdateIntervalMs = function(milliseconds) {
NODELOAD_CONFIG.SLAVE_UPDATE_INTERVAL_MS = milliseconds;
};
// =================
// Singletons
// =================
var timestamp = new Date();
var NODELOAD_CONFIG = exports.NODELOAD_CONFIG = {
START: timestamp,
START_DATE_FORMATED: timestamp.getFullYear() +
(timestamp.getMonth()<9 ? '0' : '')+ (timestamp.getMonth()+1) +
(timestamp.getDate()<10 ? '0' : '')+ timestamp.getDate() + '_' +
(timestamp.getHours()<10 ? '0' : '')+ timestamp.getHours() +
(timestamp.getMinutes()<10 ? '0' : '')+ timestamp.getMinutes() +
(timestamp.getSeconds()<10 ? '0' : '')+ timestamp.getSeconds(),
QUIET: Boolean(process.env.QUIET) || false,
HTTP_ENABLED: true,
HTTP_PORT: Number(process.env.HTTP_PORT) || 8000,
MONITOR_INTERVAL_MS: 2000,
AJAX_REFRESH_INTERVAL_MS: 2000,
LOGS_ENABLED: process.env.LOGS ? process.env.LOGS !== '0' : true,
SLAVE_UPDATE_INTERVAL_MS: 3000,
eventEmitter: new EventEmitter(),
on: function(event, fun) {
this.eventEmitter.on(event, fun);
},
apply: function() {
this.eventEmitter.emit('apply');
}
};
process.nextTick(function() { NODELOAD_CONFIG.apply(); }); |
/**
* The UIAButton class allows access to, and control of, button elements in your app.
* @constructor
* @extends UIAElement
*/
var UIAButton = function () {
};
UIAButton.prototype = UIAElement.prototype;
|
(function(){
var requireNode = window.require;
var WINDOW_WIDTH = 290;
var gui = null;
var counter = 0;
if(requireNode){
gui = requireNode('nw.gui');
}
if(!window.LOCAL_NW){
window.LOCAL_NW = {};
}
function makeNewNotifyWindow(){
var win = gui.Window.open(
'lib/nw-desktop-notifications.html', {
frame: false,
toolbar: false,
width: WINDOW_WIDTH,
height: 60,
'always-on-top': true,
show: false,
resizable: false
});
window.LOCAL_NW.DesktopNotificationsWindow = win;
window.LOCAL_NW.DesktopNotificationsWindowIsLoaded = false;
win.on('loaded', function(){
window.LOCAL_NW.DesktopNotificationsWindowIsLoaded = true;
$(win.window.document.body).find('#closer').click(function(){
slideOutNotificationWindow();
});
});
}
function closeAnyOpenNotificationWindows(){
if(!gui){
return false;
}
if(window.LOCAL_NW.DesktopNotificationsWindow){
window.LOCAL_NW.DesktopNotificationsWindow.close(true);
window.LOCAL_NW.DesktopNotificationsWindow = null;
}
}
function notify(icon, title, content, onClick){
if(!gui){
return false;
}
if(!window.LOCAL_NW.DesktopNotificationsWindow){
makeNewNotifyWindow();
}
var continuation = function(){
appendNotificationToWindow(icon, title, content, onClick);
slideInNotificationWindow();
$(window.LOCAL_NW.DesktopNotificationsWindow.window.document.body).find('#shouldstart').text('true');
};
if(window.LOCAL_NW.DesktopNotificationsWindowIsLoaded){
continuation();
}
else{
window.LOCAL_NW.DesktopNotificationsWindow.on('loaded',continuation);
}
return true;
}
function makeNotificationMarkup(iconUrl, title, content, id){
return "<li id='"+id+"'>"+
"<div class='icon'>" +
"<img src='"+iconUrl+"' />" +
"</div>" +
"<div class='title'>"+truncate(title, 35)+"</a></div>" +
"<div class='description'>"+content+"</div>" +
"</li>";
}
function appendNotificationToWindow(iconUrl, title, content, onClick){
var elemId = getUniqueId();
var markup = makeNotificationMarkup(iconUrl, title, content, elemId);
var jqBody = $(window.LOCAL_NW.DesktopNotificationsWindow.window.document.body);
jqBody.find('#notifications').append(markup);
jqBody.find('#'+elemId).click(onClick);
}
function slideInNotificationWindow(){
var win = window.LOCAL_NW.DesktopNotificationsWindow;
if(win.NOTIFICATION_IS_SHOWING){
return;
}
var y = screen.availTop;
var x = WINDOW_WIDTH;
win.moveTo(getXPositionOfNotificationWindow(win),-60);
win.resizeTo(x,60);
win.show();
win.NOTIFICATION_IS_SHOWING = true;
if(document.hasFocus()){
//win.blur();
}
function animate(){
setTimeout(function(){
if(y<60){
win.moveBy(0,1);
y+=1;
animate();
}
},5);
}
animate();
}
function slideOutNotificationWindow(callback){
var win = window.LOCAL_NW.DesktopNotificationsWindow;
var y = win.height;
var x = WINDOW_WIDTH;
function animate(){
setTimeout(function(){
if(y>0){
win.moveBy(0,-1);
y-=1;
animate();
}
else{
win.hide();
if(callback){
callback();
}
}
},5);
}
animate();
win.NOTIFICATION_IS_SHOWING = false;
}
function getXPositionOfNotificationWindow(win){
return screen.availLeft + screen.availWidth - (WINDOW_WIDTH+10);
}
function getUniqueId(){
return (+(new Date())) + '-' + (counter ++);
}
function truncate(str, size){
str = $.trim(str);
if(str.length > size){
return $.trim(str.substr(0,size))+'...';
}
else{
return str;
}
}
window.LOCAL_NW.desktopNotifications = {
notify: notify,
closeAnyOpenNotificationWindows: closeAnyOpenNotificationWindows
};
})(); |
import { Hand as ComponentHand } from 'components/cards';
export const Hand = connect()
|
var path = require('path');
const entryPath = path.join(__dirname, 'src'),
outputPath = path.join(__dirname, 'dist');
const webpack = require('webpack');
module.exports = {
devtool: "source-map",
entry: {
main: './src/index.js'
},
output: {
path: path.resolve(__dirname, 'dist/js'),
filename: '[name].js',
publicPath: "./js/"
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: [/node_modules/],
use: ['babel-loader'],
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
'file-loader'
]
}
]
},
resolve: {
// Leaflet image Alias resolutions
alias: {
'./images/layers.png$': path.resolve(__dirname, './node_modules/leaflet/dist/images/layers.png'),
'./images/layers-2x.png$': path.resolve(__dirname, './node_modules/leaflet/dist/images/layers-2x.png'),
'./images/marker-icon.png$': path.resolve(__dirname, './node_modules/leaflet/dist/images/marker-icon.png'),
'./images/marker-icon-2x.png$': path.resolve(__dirname, './node_modules/leaflet/dist/images/marker-icon-2x.png'),
'./images/marker-shadow.png$': path.resolve(__dirname, './node_modules/leaflet/dist/images/marker-shadow.png')
}
},
plugins: [
new webpack.HotModuleReplacementPlugin(), // Enable HMR
new webpack.NamedModulesPlugin(),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
jquery: 'jquery',
'window.$': 'jquery',
'window.jQuery': 'jquery',
})
],
node: {
fs: 'empty',
}
};
|
var colapse = 0;
$(document).ready(function(){
var validation;
if (typeof(reglas) != "undefined") {
validation = {
debug: false,
errorPlacement: function(error, element) {
// Append error within linked label
$( element )
.closest( "div" )
.append( error );
},
invalidHandler: function(event, validator) {
$('input[type=submit]').prop( "disabled", false );
$('input[type=submit]').val('Guardar');
},
rules: reglas.rules,
messages: reglas.messages,
};
}
$('form').submit(function() {
$('input[type=submit]').val('Procesando');
$('input[type=submit]').prop( "disabled", true );
$("form input[type=text]").each(function(){
$(this).val($(this).val().toUpperCase());
});
return true;
}).validate(validation);
// menu
var w = $(window).width();
if(w > 767) {
$('.cbp-vimenu > li').hover(function() {
if (colapse == 0) {
var i = $(this).index();
$('.cbp-vimenu > li:eq('+i+') a span').show(100);
}
}, function () {
if (colapse == 0) {
var i = $(this).index();
$('.cbp-vimenu > li:eq('+i+') a span').hide(50);
}
});
$("li.content-submenu").click(function() {
var i = $(this).index()-1;
var submenu = '.submenu-'+i;
$(submenu).show(500);
$('.cbp-vimenu > li a span').hide(50);
if (0 == colapse) {
$('ul'+submenu+' > li').hover(function() {
if (0 == colapse) {
var i = $(this).index();
$('ul'+submenu+' > li:eq('+i+') a span').show(100);
}
}, function () {
if (0 == colapse) {
var i = $(this).index();
$('ul'+submenu+' > li:eq('+i+') a span').hide(50);
}
});
} else if (1 == colapse) {
$('ul'+submenu+' > li a span').show(100);
}
});
$("li.content-subsubmenu").click(function() {
var padre = $(this).parent().attr('class').split(" ")[1].split("-")[1];
var i = $(this).index()-1;
var subsubmenu = '.submenu-'+padre+'-'+i;
$(subsubmenu).css('z-index', '10000');
$(subsubmenu).show(500);
$('.cbp-submenu > li a span').hide(50);
if (0 == colapse) {
$('ul'+subsubmenu+' > li').hover(function() {
if (0 == colapse) {
var i = $(this).index();
$('ul'+subsubmenu+' > li:eq('+i+') a span').show(100);
}
}, function () {
if (0 == colapse) {
var i = $(this).index();
$('ul'+subsubmenu+' > li:eq('+i+') a span').hide(50);
}
});
} else if (1 == colapse) {
$('ul'+subsubmenu+' > li a span').show(100);
}
});
$(".undo").click(function() {
$(this).parent().parent().hide(500);
if (1 == colapse) {
var clases = $(this).parent().parent().attr('class').split(" ");
var menus = clases[1].split("-");
if (2 == menus.length) {
// se puede cargar el menu principal
$('.cbp-vimenu .cbp-vimenu-oc').each(function() {
$(this).show(500);
});
} if (3 == menus.length) {
// se puede cargar un submenu con numero ??
$('.submenu-'+menus[1]+' .cbp-vimenu-oc').each(function() {
$(this).show(500);
});
}
}
});
$(".pull").click(function() {
if (0 == colapse) {
//colapse activo
colapse = 1;
$('.cbp-vimenu').css({'width': '13.65em'});
$(this).parent().siblings().each(function() {
$(this).find('span').show(500);
});
} else if (1 == colapse) {
colapse = 0;
$('.cbp-vimenu').css('width', '3em');
$('.cbp-vimenu-oc').each(function() {
$(this).hide(500);
});
}
});
}
$(function() {
var pull = $('.pull');
menu = $('nav ul.cbp-vimenu');
menuHeight = menu.height();
w = $(window).width();
if(w < 767){
$(".hbp-vimenu li:nth-child(2) > #usuario_sistema").text("");
$(pull).on('click', function(e) {
e.preventDefault();
menu.slideToggle();
$(".cbp-submenu").hide(250);
$("li.content-submenu").click(function() {
var i = $(this).index()-1;
var submenu = '.submenu-'+i;
$(submenu).show(500);
});
$("li.content-subsubmenu").click(function() {
var padre = $(this).parent().attr('class').split(" ")[1].split("-")[1];
var i = $(this).index()-1;
var subsubmenu = '.submenu-'+padre+'-'+i;
$(subsubmenu).css('z-index', '10000');
$(subsubmenu).show(500);
});
});
$(".undo").click(function() {
$(this).parent().parent().hide(500)
});
}
});
$(window).resize(function() {
if(w > 767 && menu.is(':hidden')) {
menu.removeAttr('style');
}
});
// termina menu
$(".close").click(function(){
$("#myAlert").slideUp();
});
setInterval(function() {
$("#myAlert").slideUp();
}, 5000);
$('#buscar').keyup(
function (event) {
var code = event.keyCode;
if((code>47 && code<91)||(code>96 && code<123) || code == 8 ) {
$('.table').remove();
$.ajax({
type: 'post',
url: baseurl + $(this).attr('url'),
data: { busca: $('#buscar').val().toUpperCase() },
beforeSend: function(){
$(".content_table > .limit-content").html("<p id='cargando' align='center'><span class='fa fa-spin fa-spinner'></span> Cargando...</p>");
var angulo = 0;
},
success: function(result) {
$('.content_table > .limit-content').html(result);
$("[data-toggle='tooltip']").tooltip();
$('.icon-eliminar').click(confirmar);
cambiar_iconos();
},
});
}
}
);
/*Tablas*/
$('.icon-eliminar').click(confirmar);
$(".limit-content").on('click', '.aprobar_compra', aprobar_compra);
$(".limit-content").on('click', '.denegar_compra', denegar_compra);
$("[data-toggle='tooltip']").tooltip();
/*Formulario*/
$.stepForm("Atrás", "Siguiente");
$("form").keypress(function(e){
if(e == 13){
return false;
}
});
$('input').keypress(function(e){
if(e.which == 13){
return false;
}
});
$('button[type=reset]').click(function () {
$('select > option').removeAttr('selected');$('select > option').removeAttr('selected');
$('select > option[value="default"]').attr('selected', 'selected');
});
});
/*FUNCIONES*/
var confirmar = function() {
var elemet = $(this);
swal({
title: "Seguro que desea eliminar?",
text: "Usted no será capaz de recuperar la información eliminada!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Si, eliminar",
cancelButtonText: "No, eliminar",
closeOnConfirm: false,
closeOnCancel: false },
function(isConfirm){
if (isConfirm) {
var url = elemet.attr('uri');
$(location).attr('href',url);
} else {
swal("Cancelando", "La información no ha sido eliminada.", "error");
}
});
}
/*
* Los campos select_name y select_value son opcionales solo cuando haya
* algun select que haya que poner.
*/
function llenarFormulario(tabla, name, value, select_name, select_value, atributo, textarea_name, textarea_value) {
var defecto = false;
var defecto1 = false;
$.extend(defecto, select_name);
$.extend(defecto, select_value);
$.extend(defecto, atributo);
$.extend(defecto, textarea_name);
$.extend(defecto, textarea_value);
abrir_mantenimiento();
for (var i = 0; i < name.length; i++) {
$('input[name='+name[i]+']').val(value[i]);
}
if (select_name != false && select_value != false) {
if (Array.isArray(select_name) && Array.isArray(select_value)) {
for (var i = 0; i < select_name.length; i++) {
$('select[name='+select_name[i]+'] > option').removeAttr('selected');
$('select[name='+select_name[i]+'] > option[value='+select_value[i]+']').attr('selected', true);
}
} else {
$('select[name='+select_name+'] > option').removeAttr('selected');
$('select[name='+select_name+'] > option[value='+select_value+']').attr('selected', true);
}
}
if (atributo) {
if ((atributo.length % 3) == 0) {
for (var i = 0; i < atributo.length; i=i+3) {
$('input[name='+atributo[i]+']').attr(atributo[i+1] , atributo[i+2]);
}
}
}
if (textarea_name != false && textarea_value != false) {
if (Array.isArray(textarea_name) && Array.isArray(textarea_value)) {
for (var i = 0; i < textarea_name.length; i++) {
$('textarea[name='+textarea_name[i]+']').val(textarea_value[i]);
}
} else {
$('textarea[name='+textarea_name+']').val(textarea_value);
}
}
$('html,body').animate({
scrollTop: $(".content-form").offset().top
}, 700);
}
/*
* mensajes
*/
function aprobar_compra() {
var elemet = $(this);
var titulo = elemet.data("title")
if(!titulo) {
titulo = "Desea Aprobar?";
}
swal({
title: titulo,
text: "Escriba un Comentario (Opcional):",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
confirmButtonText: "Aceptar",
cancelButtonText: "Cancelar",
animation: "slide-from-top",
inputPlaceholder: "Comentario"
},
function(inputValue){
if (inputValue === false) return false;
$.ajax({
type: 'post',
url: baseurl + elemet.data("url"),
data: {comentario : inputValue},
success: function(result) {
if (result || result == '') {
$(".content_table .limit-content > .table-responsive").remove();
$.ajax({
type: 'post',
url: baseurl + elemet.data("url-table"),
data: '',
success: function(result) {
$(".content_table .limit-content").html(result);
if( typeof open_modal !== 'undefined' && jQuery.isFunction( open_modal ) ) {
if ( $(".modal_open").length > 0 ){
$('.modal_open').click(open_modal);
}
}
}
});
swal({
title: "Exito!",
text: "La solicitud a sido autorizada.",
type: "success",
confirmButtonText: "Aceptar",
});
} else {
swal({
title: "Error!",
text: "La solicitud no a podido ser autorizada.",
type: "error",
confirmButtonText: "Aceptar",
});
}
},
});
}
);
}
function denegar_compra() {
var elemet = $(this);
var titulo = elemet.data("title")
if(!titulo) {
titulo = "Desea Denega?";
}
swal({
title: titulo,
text: "Escriba un Comentario (Obligatorio):",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
confirmButtonText: "Aceptar",
cancelButtonText: "Cancelar",
animation: "slide-from-top",
inputPlaceholder: "Comentario"
},
function(inputValue){
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("Necesitas escribir algo.");
return false;
}
$.ajax({
type: 'post',
url: baseurl + elemet.data("url"),
data: {comentario : inputValue},
success: function(result) {
if (result || result == '') {
$(".content_table .limit-content > .table-responsive").remove();
$.ajax({
type: 'post',
url: baseurl + elemet.data("url-table"),
data: '',
success: function(result) {
$(".content_table .limit-content").html(result);
if( typeof open_modal !== 'undefined' && jQuery.isFunction( open_modal ) ) {
if ( $(".modal_open").length > 0 ){
$('.modal_open').click(open_modal);
}
}
}
});
swal({
title: "Exito!",
text: "La solicitud a sido denegada.",
type: "success",
confirmButtonText: "Aceptar",
});
} else {
swal({
title: "Error!",
text: "La solicitud no a podido ser denegada.",
type: "error",
confirmButtonText: "Aceptar",
});
}
},
});
}
);
}
/*
* El campo select son opcionales solo cuando haya
* algun select que haya que eliminar.
*/
function limpiar(array, select, textarea) {
var defecto = false;
$.extend(defecto, select);
$.extend(defecto, textarea);
for (i = 0; i < array.length; i++) {
$('input[name='+array[i]+']').val('');
}
if (select != defecto) {
for (i = 0; i < select.length; i++) {
$('select[name='+select[i]+'] > option[value="default"]').removeAttr('selected');
$('select[name='+select[i]+'] > option[value="default"]').attr('selected', 'selected');
}
}
if (textarea != defecto) {
for (i = 0; i < textarea.length; i++) {
$('textarea[name='+textarea[i]+']').val('');
}
}
}
jQuery.extend({
stepForm: function(txtBack, txtNext, token){
var fieldsets = $((token || 'fieldset'), $("form.stepMe"));
var cont_form = $('.content-form');
var barra = $('.barra_carga', $('.content-form'));
var w = $(cont_form).width();
var total = $(fieldsets).length;
var pcu = w/total;
$(barra).css('width', pcu + 'px');
$(fieldsets).each(function(x,el){
if (x > 0) {
$(el).hide();
$(el).append('<a class="backStep btn btn-primary" href="#">'+ (txtBack || 'Volver') +'</a>');
$(".backStep", $(el)).bind("click", function(){
$("#x_" + (x - 1)).show();
$(el).hide();
$(barra).css('width', pcu*(x) + 'px');
});
}
if ((x+1)< total) {
$(el).append('<a class="nextStep btn btn-primary" href="#">'+(txtNext || 'Seguir')+'</a>');
$(".nextStep", $(el)).bind("click", function(){
$("#x_" + (x + 1)).show();
$(el).hide();
$(barra).css('width', pcu*(x+2) + 'px');
});
}
$(el).attr("id", "x_" + x);
});
},
/*
* ajaxdata: es el data que recibe el controlador desde el data del ajax
*/
autocomplete : function ( param ) {
//variable que controla los autocomplete para teclados
var mark = 0;
var act = 0;
var elemet = param['elemet'];
var content = param['content'];
var uri = param['url'];
var ajaxdata = {autocomplete: ''}
if (param.hasOwnProperty('addfunction')) {
var func = param['addfunction'];
}
if (param.hasOwnProperty('asociacion')) {
var asociacion = param['asociacion'];
}
if (param.hasOwnProperty('ajaxdata')) {
ajaxdata = param['ajaxdata'];
}
elemet.focus(function() {
if (act == 0) {
act = 1;
ajaxdata['autocomplete'] = elemet.val();
$.ajax({
type: 'post',
url: baseurl + uri,
data: ajaxdata,
beforeSend: function(){
$("#"+content).html("<p id='cargando' align='center' class='icono icon-spinner'></p>");
var angulo = 0;
setInterval(function(){
angulo += 3;
$("#cargando").rotate(angulo);
},10);
},
success: function(result) {
$('#'+content).fadeIn(300).html(result);
$('.suggest-element').click(function(){
//Obtenemos la id unica de la sugerencia pulsada
var id = $(this).attr('ida');
//Editamos el valor del input con data de la sugerencia pulsada
elemet.val($('#'+id).attr("data1"));
$('input[name='+param['name']+']').val($('#'+id).attr("data"));
//Hacemos desaparecer el resto de sugerencias
$('#'+content).fadeOut(300);
$('label[for='+elemet['0'].name+']').fadeOut();
elemet.removeClass("error");
elemet.addClass("valid");
//Ejecutamos funcion obtenida
if (param.hasOwnProperty('addfunction')) {
func();
}
if (param.hasOwnProperty('asociacion')) {
var i = 2;
for (asoc of asociacion) {
$('[name='+asoc+']').val($('#'+id).attr("data"+i));
i++;
}
}
});
},
});
} else {
$('#'+content).fadeIn(300);
}
});
elemet.keyup( function(event) {
var code = event.keyCode;
if((code>47 && code<91)||(code>96 && code<123) || code == 8 ) {
ajaxdata['autocomplete'] = elemet.val();
$.ajax({
type: 'post',
url: baseurl + uri,
data: ajaxdata,
beforeSend: function(){
$("#"+content).html("<p id='cargando' align='center' class='icono icon-spinner'></p>");
var angulo = 0;
setInterval(function(){
angulo += 3;
$("#cargando").rotate(angulo);
},10);
},
success: function(result) {
$('#'+content).fadeIn(300).html(result);
$('.suggest-element').click(function(){
//Obtenemos la id unica de la sugerencia pulsada
var id = $(this).attr('ida');
//Editamos el valor del input con data de la sugerencia pulsada
elemet.val($('#'+id).attr("data1"));
$('input[name='+param['name']+']').val($('#'+id).attr("data"));
//Hacemos desaparecer el resto de sugerencias
$('#'+content).fadeOut(300);
$('label[for='+elemet['0'].name+']').fadeOut();
elemet.removeClass("error");
elemet.addClass("valid");
//Ejecutamos funcion obtenida
if (param.hasOwnProperty('addfunction')) {
func();
}
if (param.hasOwnProperty('asociacion')) {
var i = 2;
for (asoc of asociacion) {
$('[name='+asoc+']').val($('#'+id).attr("data"+i));
i++;
}
}
});
},
});
} else if(code==40 || code ==38 ) {
var elements = $('#'+content+' .suggest-element');
elements.removeClass('suggest-element-select');
if (elements.size() > 0) {
if (code==38){
mark --;
}else{
mark ++;
}
if (mark > elements.size()){
mark=0;
}else if (mark < 0){
mark=elements.size();
}
elements.each(function(){
if ($(this).attr('id') == mark) {
var posicion = $(this).offset().top;
var height = $(this).height();
if (code == 40) {
if (posicion > 338) {
if (height <= 20) {
height += 11;
} else {
height = 38;
}
$('#'+content).animate({scrollTop:height*(mark-4)+"px"});
}
if (posicion < 0) {
if (mark == 1) {
$('#'+content).animate({scrollTop:posicion+"px"});
}
}
} else if (code == 38) {
if (posicion < 244) {
if (height <= 20) {
height += 11;
} else {
height = 38;
}
$('#'+content).animate({scrollTop:(height*(mark-4))+"px"});
}
if (mark == elements.size()) {
$('#'+content).animate({scrollTop:posicion+"px"});
}
}
$(this).addClass('suggest-element-select');
}
});
}
} else if (code == 13) {
var elements = $('#'+content+' .suggest-element');
elements.each(function(){
if ($(this).attr('id') == mark)
{
//Obtenemos la id unica de la sugerencia pulsada
var id = $(this).attr('ida');
//Editamos el valor del input con data de la sugerencia pulsada
elemet.val($('#'+id).attr("data1"));
$('input[name='+param['name']+']').val($('#'+id).attr("data"));
//Hacemos desaparecer el resto de sugerencias
$('#'+content).fadeOut(300);
$('label[for='+elemet['0'].name+']').fadeOut();
elemet.removeClass("error");
elemet.addClass("valid");
//Ejecutamos funcion obtenida
if (param.hasOwnProperty('addfunction')) {
func();
}
if (param.hasOwnProperty('asociacion')) {
var i = 2;
for (asoc of asociacion) {
$('[name='+asoc+']').val($('#'+id).attr("data"+i));
i++;
}
}
return false;
}
});
}
}
);
//$('body').click(function(){ $('#'+content).fadeOut(300); });
elemet.focusout(function () {
$('#'+content).fadeOut(300);
});
$('input[name='+param['siguiente']+']').focus(function(){ $('#'+content).fadeOut(300); });
}
});
|
$(function() {
var mainContainer = 'svg#content';
window.svgEditor = new JSYG.FullEditor(mainContainer);
(function initContextMenu() {
var contextMenu = svgEditor.createMenu({
items:["copy","cut","remove","duplicate","divider","editPathCtrlPoints"],
type:"contextMenu"
});
contextMenu.addItem({
text:"Position",
icon:"ledicon bnw shape_move_backwards",
submenu:svgEditor.createMenu("moveBack","moveBackwards","moveForwards","moveFront","divider","centerVerti","centerHoriz")
});
contextMenu.setNode(svgEditor.shapeEditor.container);
contextMenu.enable();
svgEditor.shapeEditor.on("changetarget",function(target) {
contextMenu.getItem("editPathCtrlPoints").disabled = new JSYG(target).getTag() != "path";
});
}());
(function initGlobalContextMenu() {
var globalContextMenu = svgEditor.createMenu({
items:["paste","undo","redo","divider","selectionTool"],
type:"contextMenu"
});
globalContextMenu.addItem({
text:"Draw",
icon:"ledicon bnw pencil",
submenu:svgEditor.createMenu("drawRect","drawCircle","drawEllipse","drawLine","drawPolyline","drawPolygon","drawPath","drawFreeHandPath")
});
globalContextMenu.setNode(svgEditor.zoomAndPan.outerFrame);
globalContextMenu.enable();
})();
(function initMenuBar() {
$('#confirmExample').on("click",function() {
svgEditor.loadURL("examples/"+$('#examples').val()+".svg");
$('#exampleChoice').modal("hide");
});
$('#confirmDim').on("click",function() {
svgEditor.newDocument( $('#width').val(), $('#height').val() );
$('#dimChoice').modal("hide");
});
var fileMenu = svgEditor.createMenu("openFile","print","downloadSVG","downloadPNG").set({title:"File"});
fileMenu.addItem({
text:"New Document",
icon:"ledicon bnw page_white_add",
action:function() { $('#dimChoice').modal(); }
},0);
fileMenu.addItem({
text:"Open example",
icon:"ledicon bnw image",
action:function() { $('#exampleChoice').modal(); }
},1);
fileMenu.addItem({
text:"Open image",
icon:"ledicon bnw image",
action:function() {
svgEditor.chooseFile().then(svgEditor.loadImageAsDoc).catch(alert);
}
},2);
var editMenu = svgEditor.createMenu("undo","redo","divider","copy","cut","paste","duplicate","remove","divider","selectAll","deselectAll","group","ungroup").set({title:"Edit"});
var viewMenu = svgEditor.createMenu("zoomIn","zoomOut","fitToCanvas","fitToDoc","realSize","marqueeZoom","mousePan","fullScreen").set({title:"View"});
var positionMenu = svgEditor.createMenu("moveBack","moveBackwards","moveForwards","moveFront","divider","alignTop","alignMiddle","alignBottom","divider","alignLeft","alignCenter","alignRight","divider","centerVerti","centerHoriz").set({title:"Position"});
var optionsMenu = svgEditor.createMenu("editPosition","editSize","editRotation","editPathMainPoints","editPathCtrlPoints","autoSmoothPaths","useTransformAttr","keepShapesRatio","editText","canvasResizable").set({title:"Options"});
var toolsMenu = svgEditor.createMenu("selectionTool","insertText","insertImageFile","drawRect","drawLine","drawPolyline","drawPolygon","drawPath","drawFreeHandPath").set({"title":"Tools"});
new JSYG("#menuBar").menuBar([fileMenu,editMenu,toolsMenu,positionMenu,viewMenu,optionsMenu]);
}());
svgEditor.editableShapes = "> *";
svgEditor.autoSmoothPaths = true;
svgEditor.enable();
svgEditor.newDocument(500,500);
svgEditor.shapeDrawerModel = new JSYG("<path>").addClass("perso");
svgEditor.enableDropFiles();
svgEditor.enableMouseWheelZoom();
}); |
module.exports = {
findMergeable: function(translations, locales) {
var translation,
l,
lenLocales,
keyHash = {},
keyCollision,
translationHash,
translationCollision,
translationSet,
keys = {},
mergeable = [];
if (!translations || !locales) {
return {
keys: {},
mergeable: []
};
}
l = translations.length;
lenLocales = locales.length;
while(l--){
translation = translations[l];
keyCollision = keyHash[translation.key];
if (keyCollision) {
keyCollision.push(translation);
} else {
keyHash[translation.key] = [translation];
}
}
for (var key in keyHash) {
keyCollision = keyHash[key];
if (keyCollision.length >= 2) {
translationHash = {};
for (var j=0, kc; j < keyCollision.length; j++) {
translationSet = "";
kc = keyCollision[j];
for (var i=0; i < lenLocales; i++) {
translationSet += (kc[ locales[i] ] ? kc[ locales[i] ] : "");
}
translationCollision = translationHash[translationSet];
if (translationCollision) {
translationCollision.push(kc);
} else {
translationHash[translationSet] = [kc];
}
}
for (var innerKey in translationHash) {
if (translationHash[innerKey].length >= 2) {
keys[key] = true;
mergeable.push(translationHash[innerKey]);
}
}
}
}
return {
keys: keys,
mergeable: mergeable
};
}
}
|
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-concat');
function concatFileLists() {
var args = Array.prototype.slice.call(arguments);
var ret = [];
while(args.length) {
var list = args.shift();
if (list instanceof Array) {
ret = ret.concat(list);
} else {
ret.push(list);
}
}
return ret;
}
var coreFiles = [
'lib/tracker.js',
'lib/mapper.js',
'lib/ptam.js'
];
// Project configuration.
grunt.initConfig({
pkg: '<json:package.json>',
test: {
files: ['test/**/*.js']
},
lint: {
files: ['grunt.js', 'lib/**/*.js', 'test/**/*.js']
},
watch: {
files: '<config:lint.files>',
tasks: 'default'
},
jshint: {
options: {
curly: true,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
boss: true,
eqnull: true,
node: true,
strict: false
},
globals: {
exports: true
}
},
concat: {
node:{
src : concatFileLists(['lib/node_deps.js'], coreFiles, ['lib/node_exports.js']),
dest: 'build/ptam_node.js',
separator : '\n'
},
browser:{
src : concatFileLists(['lib/browser_deps.js'], coreFiles),
dest: 'temp/ptam_browser.js',
separator : '\n'
}
},
min: {
browser: {
src: 'build/ptam.js',
dest: 'build/ptam.min.js'
}
}
});
// Default task.
grunt.registerTask('default', 'lint concat wrapbrowser min');
grunt.registerTask('wrapbrowser', 'things', function() {
var fs = require('fs');
var body = fs.readFileSync('temp/ptam_browser.js', 'utf8');
var browserTemplate = fs.readFileSync('helper/browser.mustache', 'utf8');
fs.writeFileSync('build/ptam.js', require('mustache').render(browserTemplate, {
body : body
}));
});
}; |
define(['jquery', 'app', 'services/User'], function ($, app) {
var services = [
{ name: 'Facebook' },
{ name: 'Github' },
{ name: 'Google' }
];
return app.controller('SignInController', ['$scope', '$window', 'userService', 'historyService', 'settingsService',
function (scope, win, User, historyService, settingsService) {
scope.services = services;
scope.userAvatar = User.getUserHash() || '';
scope.signInWithStrategy = function () {
win.location = '/auth/' + this.service.name.toLowerCase();
};
scope.signedIn = function () {
return User.signedIn();
};
scope.signOut = function () {
return User.signOut().then(function () {
historyService.destroy();
settingsService.destroy();
});
};
scope.toggleTOS = function () {
scope.tosExpanded = !scope.tosExpanded;
};
$('#signIn')
.on('opened', function () {
$(this).find('button')[0].focus();
})
.on('closed', function () {
$('[data-dropdown="signIn"]').focus();
});
}]);
});
|
/**
* @file mongo工具类
* @author r2space@gmail.com
* @module light.core.mongo.helper
* @version 1.0.0
*/
"use strict";
var _ = require("underscore")
, pluralize = require("pluralize")
, constant = require("../../constant")
, ObjectID = require("mongodb").ObjectID
;
/**
* collection名统一用小写
* 与之前使用的mongoose保持兼容,collection名后面加s
* @param code
* @returns {string}
*/
exports.collection = function (code) {
if (code) {
return pluralize(code.toLowerCase());
}
return code;
};
/**
* 将字段字符串,转换成mongodb的选择字段格式
* `col1 col2, col3` => {col1: 1, col2: 1, col3: 1}
* @param {Object} select 空格或逗号分隔的字符串或select对象
* @return {Object} mongodb格式
*/
exports.fields = function (select) {
if (!select) {
return {};
}
if (typeof select === 'string') {
return select.trim().split(/[ ]+|[ ]*,[ ]*/).reduce((data, item) => {
data[item] = 1;
return data;
}, {});
}
return select;
};
/**
* 格式化排序项目
* @param object
* @returns {*}
*/
exports.sort = function(object) {
// 数组形式的排序 sort: [['a': 1], ['b': -1]]
if (_.isArray(object)) {
return object;
}
// 对象形式的排序 sort: {valid:1, createAt:1}}。当排序值是文字asc,desc时,转换为数字
return _.mapObject(object, (val, key) => {
if (_.isString(val)) {
return val.toLowerCase() === 'asc' ? 1 : -1;
}
return val;
});
}; |
var assert = require('assert');
var EventEmitter = require('events').EventEmitter;
var file = '../../lib/eventemitter2';
var EventEmitter2;
if (typeof require !== 'undefined') {
EventEmitter2 = require(file).EventEmitter2;
} else {
EventEmitter2 = window.EventEmitter2;
}
module.exports = {
'1. should listen events': function () {
var isEmitted= false;
var ee = new EventEmitter();
var ee2 = new EventEmitter2();
ee2.listenTo(ee, 'test');
ee2.on('test', function () {
isEmitted = true;
});
ee.emit('test');
assert.equal(isEmitted, true);
},
'2. should attach listeners to the target object on demand if newListener & removeListener options activated': function () {
var isEmitted= false;
var ee = new EventEmitter();
var ee2 = new EventEmitter2({
newListener: true,
removeListener: true
});
ee2.listenTo(ee, {
'foo': 'bar'
});
assert.equal(ee.listenerCount('foo'), 0);
ee2.on('bar', function () {
isEmitted = true;
});
assert.equal(ee.listenerCount('foo'), 1);
ee.emit('foo');
assert.equal(isEmitted, true);
},
'3. should handle listener data': function () {
var isEmitted= false;
var ee = new EventEmitter();
var ee2 = new EventEmitter2();
ee2.listenTo(ee, 'test');
ee2.on('test', function (a, b, c) {
isEmitted = true;
assert.equal(a, 1);
assert.equal(b, 2);
assert.equal(c, 3);
});
assert.equal(ee.listenerCount('test'), 1);
ee.emit('test', 1, 2, 3);
assert.equal(isEmitted, true);
},
'4. should support stopListeningTo method': function () {
var counter= 0;
var ee = new EventEmitter();
var ee2 = new EventEmitter2();
ee2.listenTo(ee, 'test');
ee2.on('test', function () {
counter++;
});
assert.equal(ee.listenerCount('test'), 1);
ee.emit('test');
ee.emit('test');
ee2.stopListeningTo(ee);
ee.emit('test');
assert.equal(counter, 2);
assert.equal(ee.listenerCount('test'), 0);
},
'5. should support listening of multiple events': function () {
var emitted1= false;
var emitted2= false;
var ee = new EventEmitter();
var ee2 = new EventEmitter2();
ee2.listenTo(ee, 'test1 test2');
ee2.on('test1', function () {
emitted1= true;
});
ee2.on('test2', function () {
emitted2= true;
});
assert.equal(ee.listenerCount('test1'), 1);
assert.equal(ee.listenerCount('test2'), 1);
ee.emit('test1');
ee.emit('test2');
assert.equal(emitted1, true);
assert.equal(emitted2, true);
},
'6. should support events mapping': function () {
var emitted1= false;
var emitted2= false;
var ee = new EventEmitter();
var ee2 = new EventEmitter2();
ee2.listenTo(ee, {
test1: 'foo',
test2: 'bar'
});
ee2.on('foo', function (x) {
emitted1= true;
assert.equal(x, 1);
});
ee2.on('bar', function (y) {
emitted2= true;
assert.equal(y, 2);
});
assert.equal(ee.listenerCount('test1'), 1);
assert.equal(ee.listenerCount('test2'), 1);
ee.emit('test1', 1);
ee.emit('test2', 2);
assert.equal(emitted1, true);
assert.equal(emitted2, true);
},
'7. should support event reducer': function () {
var counter1= 0;
var counter2= 0;
var ee = new EventEmitter();
var ee2 = new EventEmitter2();
ee2.listenTo(ee, {
test1: 'foo',
test2: 'bar'
}, {
reducers: {
test1: function(event){
assert.equal(event.name, 'foo');
return event.data[0]!=='ignoreTest';
},
test2: function(event){
assert.equal(event.name, 'bar');
event.data[0]= String(event.data[0]);
}
}
});
ee2.on('foo', function (x) {
counter1++;
assert.equal(x, 456);
});
ee2.on('bar', function (y) {
counter2++;
assert.equal(y, '123');
});
ee.emit('test1', 'ignoreTest');
ee.emit('test1', 456);
ee.emit('test2', 123);
ee.emit('test2', 123);
assert.equal(counter1, 1);
assert.equal(counter2, 2);
},
'8. should support a single reducer for multiple events': function () {
var counter1= 0;
var ee = new EventEmitter();
var ee2 = new EventEmitter2();
ee2.listenTo(ee, {
test1: 'foo',
test2: 'bar'
}, {
reducers: function(){
counter1++;
}
});
ee.emit('test1');
ee.emit('test2');
assert.equal(counter1, 2);
},
'9. should detach the listener from the target when the last listener was removed from the emitter': function () {
var ee = new EventEmitter();
var ee2 = new EventEmitter2({
newListener: true,
removeListener: true
});
ee2.listenTo(ee, {
'foo': 'bar'
});
assert.equal(ee.listenerCount('foo'), 0);
var handler= function(){};
ee2.on('bar', handler);
assert.equal(ee.listenerCount('foo'), 1);
ee2.off('bar', handler);
assert.equal(ee.listenerCount('foo'), 0);
}
};
|
'use strict';
module.exports = function ($, appConf, moduleConf, args) {
return function (mod, modulePath, appPath) {
return new Promise(function (resolve, reject) {
var autoprefixer = require('autoprefixer');
var vfs = require('vinyl-fs');
var fs = require('fs');
var path = require('path');
var sprites = require('postcss-athena-spritesmith');
var pxtorem = require('postcss-pxtorem');
var athenaMate = require('../athena_mate');
var Util = require('../../util');
//是否开启px转rem
var px2rem = moduleConf.support.px2rem;
//是否开启雪碧图合并
var csssprite = moduleConf.support.csssprite;
var platform = appConf.platform ? appConf.platform : 'mobile';
var autoprefixerConf = moduleConf.support.autoprefixer;
var browsers = [];
if (autoprefixerConf) {
browsers = autoprefixerConf[platform];
} else {
browsers = ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1'];
}
var processors = [
autoprefixer({browsers: browsers}),
];
if( px2rem && px2rem.enable !== false ){
processors.push(pxtorem({
root_value: px2rem.root_value,
unit_precision: px2rem.unit_precision,
prop_white_list: px2rem.prop_white_list,
selector_black_list: px2rem.selector_black_list,
replace: px2rem.replace,
media_query: px2rem.media_query
}))
}
if( csssprite && csssprite.enable !== false ){
var opts = {
stylesheetPath: path.join(modulePath, 'dist', '_static', 'css'),
spritePath: path.join(modulePath, 'dist', '_static', 'images', 'sprite.png'),
retina: csssprite.retina || false,
rootvalue: csssprite.rootvalue,
padding: csssprite.padding
}
}
$.util.log($.util.colors.green('开始' + mod + '模块任务styles!'));
vfs.src([path.join(modulePath, 'dist', '_static', 'css', '*.css'), path.join('!' + modulePath, 'dist', '_static', 'css', '*.min.css')])
.pipe(athenaMate.plumber())
.pipe($.postcss(processors))
.pipe(vfs.dest(path.join(modulePath, 'dist', '_static', 'css')))
.pipe(
$.postcss([
sprites(opts)
])
)
.pipe(vfs.dest(path.join(modulePath, 'dist', '_static', 'css')))
.on('end', function () {
$.util.log($.util.colors.green('结束' + mod + '模块任务styles!'));
resolve();
})
.on('error', function (err) {
$.util.log($.util.colors.red(mod + '模块任务styles失败!'));
reject(err);
});
});
};
};
|
var passport = require('passport');
var session = require('express-session');
var localStrategy = require('./localStrategy.js');
var jwtStrategy = require('./jwtStrategy.js')
var createSendToken = require('./jwt.js');
module.exports= function(app){
//app.use(session({ secret: 'sshhh!!!', resave: false, saveUninitialized: false})); // session secret
app.use(passport.initialize());
//app.use(passport.session()); // persistent login sessions
passport.serializeUser(function (user, done) {
console.log('inside passport.serializeUser');
/*done(null, user.id);*/
done(null, user);
});
/*passport.deserializeUser(function(id, cb) {
db.users.findById(id, function (err, user) {
if (err) { return cb(err); }
cb(null, user);
});
});*/
passport.deserializeUser(function(user, done) {
console.log('inside passport.deserializeUser');
done(null, user);
});
passport.use('local-register', localStrategy.register);
passport.use('local-login', localStrategy.login);
passport.use(jwtStrategy);
/*app.post('/auth/signup', passport.authenticate('local-register',{session:false}), function (req, res) {
//emailVerification.send(req.user.email);
createSendToken(req.user, res);
//res.send('user created successfully!');
});*/
app.post('/auth/signup', function(req, res, next) {
passport.authenticate('local-register', function(err, user, info) {
if(err){
return next(err);
}
if(!user){
return res.status(401).send(info);
}
createSendToken(user, res);
})(req, res, next);
});
/*app.post('/auth/login', passport.authenticate('local-login',{session:false}), function (req, res) {
createSendToken(req.user, res);
});*/
app.post('/auth/login', function(req, res, next) {
passport.authenticate('local-login', function(err, user, info) {
if(err){
return next(err);
}
if(!user){
return res.status(401).send(info);
}
createSendToken(user, res);
})(req, res, next);
});
return passport;
} |
'use strict';
var config = require('../config.js');
function handleGET (req, res) {
// Do something with the GET request
console.log('config variable is ->'+JSON.stringify(config));
res.status(200).send('Hello World! ..bar ran successfully - config[]' + config.consumer_key);
}
function handlePUT (req, res) {
// Do something with the PUT request
res.status(403).send('Forbidden!');
}
exports.handler = function(req, res, database, config) {
// Use database to declare databaseRefs:
var usersRef = database.ref('users');
switch (req.method) {
case 'GET':
handleGET(req, res, config);
break;
case 'PUT':
handlePUT(req, res, config);
break;
default:
res.status(500).send({ error: 'Something blew up!' });
break;
}
};
|
window.bs.nc.core.ui.tables.sessions = {
init: function() {
var oTable = $('[nc-interface-unit="data-table-sessions"]').dataTable({
"bJQueryUI": false,
"bAutoWidth": false,
"sDom": '<"row" <"col-xs-12"<"tablePars" <"H"fl>>t<"F"i> <"col-xs-12"p>>>',
// <'row'<'col-xs-6'T><'col-xs-6'f>r>t<'row'<'col-xs-6'i><'col-xs-6'p>>"
"sAjaxSource": window.bs.nc.core.paths.path_session_personalsession,
"oLanguage": {
"sLengthMenu": "Display _MENU_ records per page",
"sZeroRecords": "Ничего не найдено",
"sInfo": "Показано с _START_ по _END_ из _TOTAL_ записей",
"sInfoEmpty": "Показано 0 записей",
"sInfoFiltered": "( Всего в таблице _MAX_ записей)",
"sSearch": "Поиск"
},
"aoColumns": [{
"mData": "cartCode"
}, {
"mData": "cartType"
}, {
"mData": "clientFullName"
}, {
"mData": "startDate"
}, {
"mData": null
}, {
"mData": null
},
// { "mData": "platform" },
// { "mData": "version", "sClass": "center" },
// { "mData": "grade", "sClass": "center" }
],
"aoColumnDefs": [{
"bVisible": false,
"aTargets": [5]
}, {
// "sTitle": ""
"aTargets": [4],
"fnCreatedCell": function(nTd, sData, oData, iRow, iCol) {
var b = $('<button class="btn btn-xs btn-danger" bs-nc-type="trigger" bs-nc-sessionId="' + oData.sessionId + '">Завершить сессию</button>');
b.button();
b.on('click', function() {
window.bs.nc.core.controllers.sessionController.click.showRemoveSessionAction($(this).attr('bs-nc-sessionId'));
return false;
});
$(nTd).empty();
$(nTd).prepend(b);
}
}, ]
});
oTable.fnSort([
[3, 'desc']
]);
},
destroy: function() {
$('[nc-interface-unit="data-table-sessions"]').dataTable().fnDestroy();
},
reinit: function() {
this.destroy();
this.init();
}
} |
import { assert } from 'chai';
import { stub } from 'sinon';
import parsePullRequestReviewFactory from './parsePullRequestReview';
describe('review parsing', () => {
const request = {
body: {
action: 'submitted',
diff_hunk: 'diff hunk', // @TODO Use fixture
position: 'diff position',
pull_request: { number: 42, head: { ref: 'master' } },
repository: { name: 'Sedy', owner: { login: 'Marmelab' } },
review: {
id: 'review id',
user: { login: 'Someone who reviewed' },
},
},
headers: { 'X-GitHub-Event': 'submitted' },
};
it('should retrieve the review comments', function* () {
const client = {
getCommentsFromReviewId: stub().returns(Promise.resolve([])),
};
yield parsePullRequestReviewFactory(client)(request);
assert(client.getCommentsFromReviewId.calledWith({
pullRequestNumber: request.body.pull_request.number,
repoName: request.body.repository.name,
repoUser: request.body.repository.owner.login,
reviewId: request.body.review.id,
}));
});
it('should find correct data', function* () {
const client = {
getCommentsFromReviewId: () => Promise.resolve([]),
};
const { pullRequest, repository, sender } = yield parsePullRequestReviewFactory(client)(request);
assert.deepEqual(pullRequest, {
number: request.body.pull_request.number,
ref: `refs/heads/${request.body.pull_request.head.ref}`,
});
assert.deepEqual(repository, {
name: request.body.repository.name,
user: request.body.repository.owner.login,
});
assert.deepEqual(sender, request.body.review.user.login);
});
it('should find correct comments', function* () {
const client = {
getCommentsFromReviewId: () => Promise.resolve([{
body: 'comment body',
commit_id: 'commit_id',
created_at: 'comment date',
diff_hunk: 'diff hunk',
html_url: 'comment url',
id: 'comment id',
path: 'comment path',
position: 'diff position',
user: {
login: 'Someone',
},
}, {
body: 'comment body',
commit_id: 'commit_id',
created_at: 'comment date',
diff_hunk: 'diff hunk',
html_url: 'comment url',
id: 'comment id 2',
path: 'comment path',
position: 'diff position',
user: {
login: 'Someone',
},
}]),
};
const { fixes: [{ comment: comment1 }, { comment: comment2 }] } = yield parsePullRequestReviewFactory(client)(request);
assert.deepEqual(comment1, {
body: 'comment body',
createdDate: 'comment date',
diffHunk: 'diff hunk',
id: 'comment id',
path: 'comment path',
position: 'diff position',
url: 'comment url',
});
assert.deepEqual(comment2, {
body: 'comment body',
createdDate: 'comment date',
diffHunk: 'diff hunk',
id: 'comment id 2',
path: 'comment path',
position: 'diff position',
url: 'comment url',
});
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.