code
stringlengths 2
1.05M
|
---|
ECS.System("batter",
{
order: 2,
init: function(state)
{
},
update: function(state, dt)
{
var entities = ECS.Entities.get(
ECS.Components.Bat,
ECS.Components.Transform,
ECS.Components.Direction);
while(e = entities.next())
{
var bat = e.getBat();
var transform = e.getTransform();
var dir = e.getDirection().direction;
dir = Util.Vector.normalized(dir);
var upperLeft = [];
var lowerRight = [];
var batPos = [
transform.position[0] + dir[0] * bat.range,
transform.position[1] + dir[1] * bat.range];
upperLeft[0] = batPos[0] - bat.bounds[0] / 2;
upperLeft[1] = batPos[1] - bat.bounds[1] / 2;
lowerRight[0] = batPos[0] + bat.bounds[0] / 2;
lowerRight[1] = batPos[1] + bat.bounds[1] / 2;
bat.batting -= dt;
if (bat.batting < 0)
{
bat.batting = 0;
if (bat.target != null)
{
var health = bat.target.getHealth();
if (health.blink < 0)
{
health.blink = 0.1;
}
health.health -= bat.damage;
bat.target = null;
}
Util.Collider.findIntersectingTransforms(upperLeft, lowerRight, function(otherT)
{
if (otherT.entityId != e.id && (bat.batting <= 0))
{
var other = ECS.Entities.find(otherT.entityId);
var team = other.getTeam();
var myTeam = e.getTeam();
var health = other.getHealth();
if (health)
{
if (myTeam && team &&
myTeam.team == team.team)
{
return;
}
bat.target = other;
bat.batting = 0.2;
}
}
});
}
}
}
});
|
'use strict';
var config = require('../config.json');
var gulp = require('gulp');
var env = require('gulp-environments');
var dev = env.development;
var prod = env.production;
var errorAlert = require('../libs/errorAlert');
var logAlert = require('../libs/logAlert');
var plumber = require('gulp-plumber');
var gutil = require('gulp-util');
var browserSync = require('browser-sync');
var joinPath = require('path.join');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var rename = require('gulp-rename');
var browserify = require('browserify');
var sourcemaps = require('gulp-sourcemaps');
var glob = require('glob');
var es = require('event-stream');
var flatten = require('gulp-flatten');
var watchify = require('watchify');
var uglify = require('gulp-uglify');
var streamify = require('gulp-streamify');
var js = config.tasks.js;
var paths = {
src : joinPath(config.root.src, js.src, js.extensions),
dest: joinPath(config.root.dest, js.dest)
}
var browserifyBundle = function () {
glob(paths.src, function(err, files) {
var tasks = files.map(function(entry) {
return browserify({ entries: [entry] }).bundle()
.on('error', function(err) {
errorAlert(err);
})
.pipe(source(entry))
.pipe(dev(buffer()))
.pipe(dev(sourcemaps.init({
loadMaps: true
})))
.pipe(rename({
extname: js.browserify.bundle
}))
.pipe(flatten())
.pipe(dev(sourcemaps.write('./')))
.pipe(prod(streamify(uglify())))
.pipe(gulp.dest(paths.dest))
.pipe(browserSync.stream({once: true}))
});
es.merge(tasks);
})
}
var browserifyTask = function() {
var b = watchify(browserify(paths.src, config.tasks.js.browserify.options));
b.on('update', function(ids) {
browserifyBundle(b);
});
return browserifyBundle(b);
}
gulp.task('browserify', browserifyTask);
module.exports = browserifyTask
|
/*
* http://love.hackerzhou.me
*/
// variables
var $win = $(window);
var clientWidth = $win.width();
var clientHeight = $win.height();
$(window).resize(function() {
var newWidth = $win.width();
var newHeight = $win.height();
if (newWidth != clientWidth && newHeight != clientHeight) {
location.replace(location);
}
});
(function($) {
$.fn.typewriter = function() {
this.each(function() {
var $ele = $(this), str = $ele.html(), progress = 0;
$ele.html('');
var timer = setInterval(function() {
var current = str.substr(progress, 1);
if (current == '<') {
progress = str.indexOf('>', progress) + 1;
} else {
progress++;
}
$ele.html(str.substring(0, progress) + (progress & 1 ? '_' : ''));
if (progress >= str.length) {
clearInterval(timer);
}
}, 75);
});
return this;
};
})(jQuery);
function timeElapse(date){
var current = Date();
var seconds = (Date.parse(current) - Date.parse(date)) / 1000;
var days = Math.floor(seconds / (3600 * 24));
seconds = seconds % (3600 * 24);
var hours = Math.floor(seconds / 3600);
if (hours < 10) {
hours = "0" + hours;
}
seconds = seconds % 3600;
var minutes = Math.floor(seconds / 60);
if (minutes < 10) {
minutes = "0" + minutes;
}
seconds = seconds % 60;
if (seconds < 10) {
seconds = "0" + seconds;
}
var result = "<span class=\"digit\">" + days + "</span> 天 <span class=\"digit\">" + hours + "</span> 小时 <span class=\"digit\">" + minutes + "</span> 分钟 <span class=\"digit\">" + seconds + "</span> 秒";
$("#clock").html(result);
}
|
//pizza.js
var hapi = require("hapi"),
server = new hapi.Server(),
orders = require("./orders");
server.connection({ port: 8000 });
server.start();
server.views({
path: "templates",
engines: {
html: require("handlebars")
},
isCached: false
});
server.route({
method: "GET",
path: "/{name?}",
handler: function(req, reply) {
var name = req.params.name || "Anon";
reply.view("index.html", {
user: name
});
}
});
server.route({
method: "POST",
path: "/order",
handler: function(req, reply) {
orders.add(req.payload);
reply.view("index.html", {
pizzas: orders.pizzas
});
}
});
|
'use strict';
module.exports = function(sequelize, DataTypes) {
var Probe = sequelize.define('Probe', {
channel: { type: DataTypes.INTEGER, primaryKey: true},
createdAt: DataTypes.DATE,
updatedAt: DataTypes.DATE
}, {
classMethods: {
associate: function(models) {
Probe.hasMany(models.TemperatureLog);
}
}
});
return Probe;
};
|
var proto = require('proto')
var testUtils = require('testUtils')
var Gem = require("../Gem.browser")
var domUtils = require('domUtils')
var syn = require("fsyn")
var Style = Gem.Style
var Text = Gem.Text
var Button = Gem.Button
var CheckBox = Gem.CheckBox
var Block = Gem.Block
var Svg = Gem.Svg
var defaultBackgroundColor = 'rgba(0, 0, 0, 0)'; var defaultBgColor = defaultBackgroundColor
module.exports = function(t) {
// this.timeout(60*1000) ugh it looks like this isn't working properly
// todo:
// test mix and copy
//*
this.test('simple styling',function(t) {
this.count(2)
var S = Style({
color: 'rgb(0, 128, 0)'
})
var C = proto(Gem, function(superclass) {
this.name = 'C'
this.build = function() {
this.style = S
this.domNode.textContent = "hi"
}
})
var node = C()
testUtils.demo("simple styling", node) // node has to be apart of the page before css class styles are applied to it
var div = $(node.domNode)
this.eq(div.css('color'), 'rgb(0, 128, 0)')
node.style = undefined // unset a style (should return to default)
setTimeout(function() { // looks like when a css classname is changed, it doesn't take effect immediately (is this really true????)
t.eq(div.css('color'), 'rgb(0, 0, 0)')
},0)
})
this.test('styling a more complex component with inner components', function() {
var S = Style({
backgroundColor: 'rgb(0, 128, 0)',
Text: {backgroundColor: 'rgb(128, 0, 0)'},
CheckBox: {backgroundColor: 'rgb(0, 0, 128)'}
})
var C = proto(Gem, function(superclass) {
this.name = 'C'
this.build = function() {
this.style = S
this.add(Text('one'), CheckBox())
}
})
var node = C()
testUtils.demo('styling a more complex component with inner components', node)
var color = $(node.domNode).css('backgroundColor')
this.ok(color === 'rgb(0, 128, 0)', color)
var children = node.domNode.children
color = $(children[0]).css('backgroundColor')
this.ok(color === 'rgb(128, 0, 0)', color)
color = $(children[1]).css('backgroundColor')
this.ok(color === 'rgb(0, 0, 128)', color)
})
this.test('styling a component via its class-parent', function() {
var S = Style({
Text: {backgroundColor: 'rgb(128, 0, 0)'}
})
var NextText = proto(Text, function(superclass) {
this.name = 'NextText'
})
var C = proto(Gem, function(superclass) {
this.name = 'C'
this.build = function() {
this.style = S
this.add(NextText('one'))
}
})
var node = C()
testUtils.demo('styling a component via its class-parent', node)
var children = node.domNode.children
var color = $(children[0]).css('backgroundColor')
this.ok(color === 'rgb(128, 0, 0)', color)
})
this.test("styling inner components with the 'components' initialization", function() {
var textStyle1 = Style({
color: 'rgb(0, 128, 0)'
})
var S = Style({
textAlign: 'center',
Text: textStyle1
})
var C = proto(Gem, function(superclass) {
this.name = 'C'
this.build = function() {
this.add(Text('test'))
this.style = S
}
})
var node = C()
testUtils.demo("styling inner components with the 'components' initialization", node)
var textNode = $(node.domNode.children[0])
this.eq(textNode.css('color'), 'rgb(0, 128, 0)')
this.eq($(node.domNode).css('textAlign'), 'center')
this.eq(textNode.css('textAlign'), 'left') // certain inheritable properties shouldn't be inherited by inner components
node.style = undefined // unset style
this.eq(textNode.css('color'), 'rgb(0, 0, 0)')
this.eq(textNode.css('textAlign'), 'left')
this.eq($(node.domNode).css('textAlign'), 'left')
})
this.test('default Gem styles',function(t) {
this.test('simple default styles', function(t) {
this.count(10)
var S = Style({
color: 'rgb(0, 0, 128)'
})
var C = proto(Text, function(superclass) {
this.defaultStyle = Style({
color: 'rgb(0, 128, 0)',
backgroundColor: 'rgb(0, 100, 100)',
borderColor: 'rgb(120, 130, 140)'
})
})
var D = proto(C, function(superclass) {
this.defaultStyle = Style({
backgroundColor: 'rgb(1, 2, 3)'
})
})
var node = C("yeahhh")
var node2 = D("NOOOOO")
var container = Block(node, node2)
testUtils.demo('default Gem styles', container) // node has to be apart of the page before css class styles are applied to it
var div = $(node.domNode)
this.eq(div.css('color'), 'rgb(0, 128, 0)')
this.eq(div.css('backgroundColor'), 'rgb(0, 100, 100)')
var div2 = $(node2.domNode)
this.eq(div2.css('color'), 'rgb(0, 128, 0)')
this.eq(div2.css('backgroundColor'), 'rgb(1, 2, 3)')
this.eq(div2.css('borderColor'), 'rgb(120, 130, 140)')
node.style = S
node2.style = S
setTimeout(function() { // looks like when a css classname is changed, it doesn't take effect immediately (is this really true????)
t.eq(div.css('color'), 'rgb(0, 0, 128)')
t.eq(div.css('backgroundColor'), 'rgb(0, 100, 100)') // the default backgroundColor bleeds through for default stylings (unlike normal stylings)
t.eq(div2.css('color'), 'rgb(0, 0, 128)')
t.eq(div2.css('backgroundColor'), 'rgb(1, 2, 3)')
t.eq(div2.css('borderColor'), 'rgb(120, 130, 140)')
},0)
})
this.test("complex default Gem styles", function(t) {
var C = proto(Text, function(superclass) {
this.defaultStyle = Style({
color: 'rgb(0, 128, 0)',
Text: {
color: 'rgb(2, 20, 200)',
$setup: function(block) {
block.yes = true
}
}
})
})
var c = C()
c.add(Text("moooose"))
testUtils.demo("complex default Gem styles", c)
var node = $(c.domNode)
var child = c.children[0]
var childNode = $(child.domNode)
t.eq(node.css('color'), 'rgb(0, 128, 0)')
t.eq(childNode.css('color'), 'rgb(2, 20, 200)')
t.eq(child.yes, true)
})
this.test('Testing various inheritance from default styles', function(t) {
var X = proto(Block, function() {
this.name = 'X'
this.defaultStyle = Style({
$a: {
color: 'rgb(100, 200, 250)',
$setup: function(gem) {
gem.yes = true
},
$kill: function(gem) {
gem.no = true
},
$state: function(state) {
return {
width: 10
}
}
},
$setup: function(gem) {
gem.yes = true
},
$kill: function(gem) {
gem.no = true
},
$state: function(state) {
return {
width: 10
}
}
})
})
var x = X()
var block = Block(x)
block.style = Style({
X: {
$a: {
$inherit: true
}
}
})
var text = Text('a','hi')
x.add(text)
x.attach()
testUtils.demo('Inheriting from an inner style in a defaultStyle wasnt working', x)
t.eq($(text.domNode).css('color'), 'rgb(100, 200, 250)')
t.eq($(text.domNode).css('display'), 'inline-block') // should be the base default value
t.eq(x.yes, true)
t.eq(text.yes, true)
t.eq(x.no, undefined)
t.eq(text.no, undefined)
t.eq($(x.domNode).css('width'), '10px')
t.eq($(text.domNode).css('width'), '10px')
})
})
this.test("inheritance of component styles", function() {
// (e.g. gramparent sets Label style, parent doesn't but has a Label component in it)
var S = Style({
Text: Style({
color: 'rgb(0, 128, 0)'
})
})
var Parent = proto(Gem, function(superclass) {
this.name = 'Parent'
this.build = function() {
this.add(Text('inParent'))
}
})
var Grandparent = proto(Gem, function(superclass) {
this.name = 'Grandparent'
this.build = function() {
this.style = S // setting the style before adding components should also work
this.add(Parent())
this.add(Text('inGrandparent'))
}
})
var node = Grandparent()
testUtils.demo("inheritance of component styles", node)
var grandparentText = $(node.children[1].domNode)
var parentText = $(node.children[0].children[0].domNode)
this.eq(grandparentText.css('color'), 'rgb(0, 128, 0)')
this.eq(parentText.css('color'), 'rgb(0, 128, 0)')
node.style = undefined // unset style
this.eq(grandparentText.css('color'), 'rgb(0, 0, 0)')
this.eq(parentText.css('color'), 'rgb(0, 0, 0)')
})
this.test("the 'setup' javascript initialization", function(t) {
this.count(4)
var S = Style({
$setup: function(component, style) {
t.eq(style, S)
component.mahdiv = domUtils.div()
component.mahdiv.textContent = "It is set up"
component.domNode.appendChild(component.mahdiv)
return "some value to pass to kill"
},
$kill: function(component, state) {
component.mahdiv.textContent = 'It has been killed'
t.eq(state, "some value to pass to kill")
}
})
var S2 = Style({}) // empty style
var C = proto(Gem, function(superclass) {
this.name = 'C'
this.build = function() {
this.style = S
}
})
var node = C()
testUtils.demo("the 'setup' javascript initialization", node)
var innerDiv = $($(node.domNode).children('div')[0])
this.eq(innerDiv.html(), "It is set up")
node.style = S2
this.eq(innerDiv.html(), 'It has been killed')
})
this.test("changing style objects on the fly", function() {
var C = proto(Gem, function(superclass) {
this.name = 'C'
this.build = function(style) {
this.style = style
this.add(Text('testLabel'))
}
})
var TextStyle1 = Style({
color:'rgb(0,128,0)'
})
var TextStyle2 = Style({
color:'rgb(128,0,0)'
})
var S1 = Style({
color: 'rgb(0,0,128)',
Text: TextStyle1,
$setup: function(component) {
component.mahdiv = domUtils.div()
component.mahdiv.textContent = "It is set up"
component.domNode.appendChild(component.mahdiv)
},
$kill: function(component) {
component.domNode.removeChild(component.mahdiv)
}
})
var S2 = Style({
color: 'rgb(0,128,128)',
Text: TextStyle2,
$setup: function(component) {
component.mahdiv = domUtils.div()
component.mahdiv.textContent = "Me is set up dood"
component.domNode.appendChild(component.mahdiv)
}
})
var node = C(S1)
testUtils.demo("changing styles on the fly", node)
node.style = S2 // reset style
var mainComponent = $(node.domNode)
var labelDiv = $(mainComponent.children('div')[0])
var textDiv = $(mainComponent.children('div')[1])
this.eq(mainComponent.css('color'), 'rgb(0, 128, 128)')
this.eq(labelDiv.css('color'), 'rgb(128, 0, 0)')
this.eq(textDiv.html(), "Me is set up dood")
this.test('errors', function() {
this.count(1)
try {
node.style = S1 // if a style that has a 'setup' but no 'kill' is changed, an exception should be thrown
} catch(e) {
this.eq(e.message, 'style has been unset but does not have a "kill" function to undo its "setup" function')
}
})
})
this.test("reinheritance of parent styles", function() {
// (e.g. gramparent sets Text style, parent doesn't but has a Text component in it)
var textStyle1 = Style({
color: 'rgb(128, 0, 128)'
})
var textStyle2 = Style({
color: 'rgb(128, 128, 0)'
})
var textStyle3 = Style({
color: 'rgb(0, 128, 0)'
})
var S = Style({
Text: textStyle1
})
var S2 = Style({
Text: textStyle2
})
var Parent = proto(Gem, function(superclass) {
this.name = 'Parent'
this.build = function() {
this.style = S2
this.text = Text('inParent')
this.text.style = textStyle3
this.add(this.text)
}
})
var Grandparent = proto(Gem, function(superclass) {
this.name = 'Grandparent'
this.build = function() {
this.style = S
this.parentComponent = Parent()
this.add(this.parentComponent)
}
})
var node = Grandparent()
testUtils.demo("reinheritance of parent styles", node)
var parentText = $(node.parentComponent.text.domNode)
this.eq(parentText.css('color'), 'rgb(0, 128, 0)')
node.parentComponent.text.style = undefined // reinherit from parent
this.eq(parentText.css('color'), 'rgb(128, 128, 0)')
node.parentComponent.style = undefined // reinherit from grandparent
this.eq(parentText.css('color'), 'rgb(128, 0, 128)')
})
this.test('component label styling', function() {
var C = proto(Gem, function(superclass) {
this.name = 'C'
this.build = function() {
this.style = style
this.add(
Text('one'),
Text('inner', 'two'),
Block([Text('three')]),
Block('inner2', [Text('four')]),
Block('inner2', [Text('inner', 'five')])
)
}
})
var style = Style({
color: 'rgb(128, 0, 0)',
Text: {
color: 'rgb(0, 128, 0)',
backgroundColor: 'rgb(1, 2, 3)'
},
$inner: {
color: 'rgb(128, 128, 128)'
},
$inner2: {
Text: {
color: 'rgb(0, 128, 128)'
}
},
Block: {
backgroundColor: 'rgb(0, 120, 130)',
Text: {
color: 'rgb(0, 0, 128)'
}
}
})
var component = C()
testUtils.demo('component label styling', component)
var children = $(component.domNode).children()
this.eq($(children[0]).css('color'), 'rgb(0, 128, 0)')
this.eq($(children[0]).css('backgroundColor'), 'rgb(1, 2, 3)')
this.eq($(children[1]).css('color'), 'rgb(128, 128, 128)')
this.eq($(children[1]).css('backgroundColor'), 'rgba(0, 0, 0, 0)') // the $inner style doesn't have a backgroundColor set and doesn't inherit from the Gem style
this.eq($(children[2]).css('backgroundColor'), 'rgb(0, 120, 130)')
this.eq($(children[2].children[0]).css('color'), 'rgb(0, 0, 128)')
this.eq($(children[3]).css('backgroundColor'), 'rgba(0, 0, 0, 0)') // uses the label style, not the Gem style
this.eq($(children[3].children[0]).css('color'), 'rgb(0, 128, 128)')
this.eq($(children[4]).css('backgroundColor'), 'rgba(0, 0, 0, 0)') // uses the label style, not the Gem style
this.eq($(children[4].children[0]).css('color'), 'rgb(128, 128, 128)') // comes from the $inner style rather than the component style (this behavior is a little weird, but is how it works for now)
this.eq($(children[4].children[0]).css('backgroundColor'), 'rgba(0, 0, 0, 0)') // nothing should be inherited from the non-label style
// just here to make sure there's no error:
Style({
Anything: {
$someLabel: {
$someInnerLabel: {} // nested labels used to not be legal - now they mean something different and so are valid
}
}
})
})
this.test('pseudoclass styling', function() {
this.test("Style.addPseudoClass", function(t) {
var applies = false, changeState;
this.test("events", function(t) {
this.count(40)
var event = testUtils.seq(function(type, element) {
t.eq(type, 'setup')
t.eq(element, 'x')
},function(type, element, applies) {
t.eq(type, 'check')
t.eq(element, 'x')
t.eq(applies, false)
},function(type, element, startArg) {
t.eq(type, 'changeState')
t.eq(element, 'x')
t.eq(startArg, false)
},function(type, element, startArg) {
t.eq(type, 'changeState')
t.eq(element, 'x')
t.eq(startArg, true)
},function(type, element, startArg) {
t.eq(type, 'changeState')
t.eq(element, 'x')
t.eq(startArg, true)
},function(type, element, startArg) {
t.eq(type, 'changeState')
t.eq(element, 'x')
t.eq(startArg, false)
},function(type, element, state) {
t.eq(type, 'kill')
t.eq(element, 'x')
t.eq(state, 'whoHA')
},function(type, element) {
t.eq(type, 'setup')
t.eq(element, 'y')
},function(type, element, applies) {
t.eq(type, 'check')
t.eq(element, 'y')
t.eq(applies, true)
},function(type, element, startArg) {
t.eq(type, 'changeState')
t.eq(element, 'y')
t.eq(startArg, true)
},function(type, element, startArg) {
t.eq(type, 'changeState')
t.eq(element, 'y')
t.eq(startArg, false)
},function(type, element, startArg) {
t.eq(type, 'changeState')
t.eq(element, 'y')
t.eq(startArg, false)
},function(type, element, startArg) {
t.eq(type, 'changeState')
t.eq(element, 'y')
t.eq(startArg, true)
},function(type, element, state) {
t.eq(type, 'kill')
t.eq(element, 'y')
t.eq(state, 'whoHA')
})
Style.addPseudoClass("test-pseudoclass", {
check: function(block) {
event('check', block.domNode.textContent, applies)
return applies
},
setup: function(block, start, end) {
event('setup', block.domNode.textContent)
changeState = function(startArg) {
event('changeState', block.domNode.textContent, startArg)
if(startArg === true) {
start()
} else {
end()
}
}
return "whoHA"
},
kill: function(block, state) {
event('kill', block.domNode.textContent, state)
changeState = undefined
}
})
})
var style = Style({
$$testPseudoclass: {
color: 'rgb(10, 30, 50)'
}
})
var x = Text('x')
x.attached = true // pretend its attached so it'll render the style
x.style = style
t.eq($(x.domNode).css('rgb(0, 0, 0)')) // starts out not applying
changeState(false) // no change
t.eq($(x.domNode).css('rgb(0, 0, 0)'))
changeState(true)
t.eq($(x.domNode).css('rgb(10, 30, 50)'))
changeState(true) // no change
t.eq($(x.domNode).css('rgb(10, 30, 50)'))
changeState(false)
t.eq($(x.domNode).css('rgb(0, 0, 0)'))
x.style = undefined
applies = true
var y = Text('y')
y.attached = true // pretend its attached so it'll render the style
y.style = style // note that changeState should now be a different function that won't affect x
t.eq($(x.domNode).css('rgb(10, 30, 50)')) // starts out applying thing time
changeState(true) // no change
t.eq($(y.domNode).css('rgb(10, 30, 50)'))
changeState(false)
t.eq($(y.domNode).css('rgb(0, 0, 0)'))
changeState(false) // no change
t.eq($(y.domNode).css('rgb(0, 0, 0)'))
changeState(true)
t.eq($(y.domNode).css('rgb(10, 30, 50)'))
y.style = Style({
color: 'blue'
})
})
//*
this.test("native-only psuedoclass styling", function() {
this.count(30)
var style = Style({
color: 'rgb(128, 0, 0)',
CheckBox: {
color: 'rgb(0, 128, 0)',
$$disabled: {
color: 'rgb(123, 130, 130)',
outline: '1px solid rgb(60, 60, 200)'
},
$$checked: {
color: 'rgb(128, 128, 128)',
outline: '4px solid rgb(80, 90, 100)',
$$required: {
color: 'rgb(130, 0, 130)',
backgroundColor: 'rgb(1, 2, 3)'
}
}
},
Block: {
CheckBox: {
color: 'rgb(0, 128, 0)',
width: 100 // make sure this doesn't bleed through to the readWrite CheckBox style
},
$$readWrite: {
CheckBox: {
color: 'rgb(128, 128, 128)',
$$checked: {
color: 'rgb(12, 19, 50)'
}
}
}
}
})
var block = Block([
CheckBox(),
Block([CheckBox()])
])
block.style = style
testUtils.demo("native-only psuedoclass styling", block)
var children = block.children
var firstCheckBoxComponent = children[0]
var firstCheckBox = $(firstCheckBoxComponent.domNode)
this.eq(firstCheckBox.css('color'), 'rgb(0, 128, 0)')
this.log('just disabled')
firstCheckBoxComponent.attr('disabled', true)
setTimeout(function() { // need to use a timeout every time an attribute changes because the MutationObserver that listens for attribute changes is asynchornous and won't fire until the scheduler is reached
this.eq(firstCheckBox.css('color'), 'rgb(123, 130, 130)')
this.eq(firstCheckBox.css('outlineColor'), 'rgb(60, 60, 200)')
this.eq(firstCheckBox.css('backgroundColor'), defaultBackgroundColor)
firstCheckBoxComponent.attr('disabled', undefined)
setTimeout(function() {
this.log("just checked")
firstCheckBoxComponent.selected = true
this.eq(firstCheckBox.css('color'), 'rgb(128, 128, 128)')
this.ok(firstCheckBox.css('outlineColor') !== 'rgb(0, 0, 0)', firstCheckBox.css('outlineColor'))
this.eq(firstCheckBox.css('backgroundColor'), defaultBackgroundColor)
this.eq(firstCheckBox.css('outlineWidth'), '4px')
firstCheckBoxComponent.selected = false
this.log("just required")
firstCheckBoxComponent.attr('required', true)
setTimeout(function() {
this.eq(firstCheckBox.css('color'), 'rgb(0, 128, 0)') // the required pseudoclass doesn't apply because its within the checked psudeoclass (and the box isn't checked)
this.ok(firstCheckBox.css('outlineColor') !== 'rgb(60, 60, 200)', firstCheckBox.css('outlineColor'))
this.eq(firstCheckBox.css('backgroundColor'), defaultBackgroundColor)
this.log("required and disabled")
firstCheckBoxComponent.attr('disabled', true)
setTimeout(function() {
this.eq(firstCheckBox.css('color'), 'rgb(123, 130, 130)')
this.eq(firstCheckBox.css('outlineColor'), 'rgb(60, 60, 200)')
this.eq(firstCheckBox.css('backgroundColor'), defaultBackgroundColor)
firstCheckBoxComponent.attr('required', undefined)
setTimeout(function() {
this.log("disabled and checked")
firstCheckBoxComponent.selected = true
this.eq(firstCheckBox.css('color'), 'rgb(128, 128, 128)')
this.eq(firstCheckBox.css('outlineColor'), 'rgb(80, 90, 100)')
this.eq(firstCheckBox.css('backgroundColor'), defaultBackgroundColor)
firstCheckBoxComponent.attr('disabled', undefined)
this.log("checked and required")
firstCheckBoxComponent.attr('required', true)
setTimeout(function() {
this.eq(firstCheckBox.css('color'), 'rgb(130, 0, 130)')
this.eq(firstCheckBox.css('outlineColor'), 'rgb(80, 90, 100)')
this.eq(firstCheckBox.css('backgroundColor'), 'rgb(1, 2, 3)')
this.eq(firstCheckBox.css('outlineWidth'), '4px')
this.log("all 3: checked, required, and disabled")
firstCheckBoxComponent.attr('disabled', true)
setTimeout(function() {
this.eq(firstCheckBox.css('color'), 'rgb(130, 0, 130)')
this.eq(firstCheckBox.css('outlineColor'), 'rgb(80, 90, 100)')
this.eq(firstCheckBox.css('backgroundColor'), 'rgb(1, 2, 3)')
this.log("just required (again)")
firstCheckBoxComponent.attr('disabled', false)
firstCheckBoxComponent.selected = false
setTimeout(function() {
var secondCheckBoxComponent = children[1].children[0]
var secondCheckBox = $(secondCheckBoxComponent.domNode)
this.eq(secondCheckBox.css('color'), 'rgb(0, 128, 0)')
this.log("just readWrite (2nd)")
children[1].attr('contenteditable', true)
setTimeout(function() {
this.eq(secondCheckBox.css('color'), 'rgb(128, 128, 128)')
this.eq(secondCheckBox.css('width'), '13px') // completely separate styles from outside the pseudoclass style shouldn't bleed through (unless the style explicitly inherits)
children[1].attr('contenteditable', undefined)
setTimeout(function() {
this.log("just checked (2nd)")
secondCheckBoxComponent.selected = true
this.eq(secondCheckBox.css('color'), 'rgb(0, 128, 0)')
this.log("checked and readWrite (2nd)")
children[1].attr('contenteditable', true)
setTimeout(function() {
this.eq(secondCheckBox.css('color'), 'rgb(12, 19, 50)')
this.eq(secondCheckBox.css('width'), '13px') // i guess 13px is the default for checkboxes? whatever..
}.bind(this),0)
}.bind(this),0)
}.bind(this),0)
}.bind(this),0)
}.bind(this),0)
}.bind(this),0)
}.bind(this),0)
}.bind(this),0)
}.bind(this),0)
}.bind(this),0)
}.bind(this),0)
})
this.test("native pseudoclass styling broken by a sibling pseudoclass", function() {
this.count(12)
var setupCalled= 0, killCalled=0
var style = Style({
CheckBox: {
$setup: function() { // this makes CheckBox unable to be rendered with pure css
setupCalled++
},
$kill: function() {
killCalled++
}
},
'$$nthChild(2)': {
backgroundColor: 'rgb(1, 9, 56)',
CheckBox: {
color: 'rgb(128, 129, 230)'
}
}
})
var checkbox = CheckBox()
var inner = Block([checkbox])
var block = Block([inner])
inner.style = style
testUtils.demo("native psuedoclass styling broken by a block's computedStyleMap", block)
this.log("not second child")
setTimeout(function() {
var checkboxNode = $(checkbox.domNode)
var innerNode = $(inner.domNode)
this.eq(checkboxNode.css('color'), 'rgb(0, 0, 0)')
this.eq(innerNode.css('backgroundColor'), defaultBgColor)
this.eq(setupCalled, 1)
this.eq(killCalled, 0)
this.log("second child")
block.addAt(0, Text("nope"))
setTimeout(function() {
this.eq(checkboxNode.css('color'), 'rgb(128, 129, 230)')
this.eq(innerNode.css('backgroundColor'), 'rgb(1, 9, 56)')
this.eq(setupCalled, 1)
this.eq(killCalled, 1)
this.log("not second child (again)")
block.remove(0)
setTimeout(function() {
this.eq(checkboxNode.css('color'), 'rgb(0, 0, 0)')
this.eq(innerNode.css('backgroundColor'), defaultBgColor)
this.eq(setupCalled, 2)
this.eq(killCalled, 1)
}.bind(this),0)
}.bind(this),0)
}.bind(this),0)
})
this.test("native pseudoclass styling broken by a block's computedStyleMap", function() {
this.count(12)
var setupCalled= 0, killCalled=0
var style = Style({
CheckBox: {
$setup: function() { // this makes CheckBox unable to be rendered with pure css
setupCalled++
},
$kill: function() {
killCalled++
}
},
'$$nthChild(2)': {
Block:{
backgroundColor: 'rgb(1, 10, 57)',
CheckBox: {
color: 'rgb(128, 129, 230)'
}
},
}
})
var checkbox, inner, evenInner
var block = Block([
inner = Block([
evenInner = Block([
checkbox = CheckBox()
])
])
])
inner.style = style
testUtils.demo("native psuedoclass styling broken by a block's computedStyleMap", block)
this.log("not second child")
setTimeout(function() {
var checkboxNode = $(checkbox.domNode)
var innerNode = $(evenInner.domNode)
this.eq(checkboxNode.css('color'), 'rgb(0, 0, 0)')
this.eq(innerNode.css('backgroundColor'), defaultBgColor)
this.eq(setupCalled, 1)
this.eq(killCalled, 0)
this.log("second child")
block.addAt(0, Text("nope"))
setTimeout(function() {
this.eq(checkboxNode.css('color'), 'rgb(128, 129, 230)')
this.eq(innerNode.css('backgroundColor'), 'rgb(1, 10, 57)')
this.eq(setupCalled, 1)
this.eq(killCalled, 1)
this.log("not second child (again)")
block.remove(0)
setTimeout(function() {
this.eq(checkboxNode.css('color'), 'rgb(0, 0, 0)')
this.eq(innerNode.css('backgroundColor'), defaultBgColor)
this.eq(setupCalled, 2)
this.eq(killCalled, 1)
}.bind(this),0)
}.bind(this),0)
}.bind(this),0)
})
this.test("native pseudoclass styling broken by a block's computedStyleMap (2)", function() {
this.count(12)
var setupCalled= 0, killCalled=0
var style = Style({
CheckBox: {
$setup: function() { // this makes CheckBox unable to be rendered with pure css
setupCalled++
},
$kill: function() {
killCalled++
}
}
})
var checkbox = CheckBox()
var inner = Block([checkbox])
var block = Block([inner])
block.style = style
inner.style = Style({
'$$nthChild(2)': {
backgroundColor: 'rgb(1, 11, 57)',
CheckBox: {
color: 'rgb(128, 129, 230)'
}
}
})
testUtils.demo("native psuedoclass styling broken by a block's computedStyleMap", block)
this.log("not second child")
setTimeout(function() {
var checkboxNode = $(checkbox.domNode)
var innerNode = $(inner.domNode)
this.eq(checkboxNode.css('color'), 'rgb(0, 0, 0)')
this.eq(innerNode.css('backgroundColor'), defaultBgColor)
this.eq(setupCalled, 1)
this.eq(killCalled, 0)
this.log("second child")
block.addAt(0, Text("nope"))
setTimeout(function() {
this.eq(checkboxNode.css('color'), 'rgb(128, 129, 230)')
this.eq(innerNode.css('backgroundColor'), 'rgb(1, 11, 57)')
this.eq(setupCalled, 1)
this.eq(killCalled, 1)
this.log("not second child (again)")
block.remove(0)
setTimeout(function() {
this.eq(checkboxNode.css('color'), 'rgb(0, 0, 0)')
this.eq(innerNode.css('backgroundColor'), defaultBgColor)
this.eq(setupCalled, 2)
this.eq(killCalled, 1)
}.bind(this),0)
}.bind(this),0)
}.bind(this),0)
})
this.test("basic psuedoclass styling (some emulated some not)", function() {
this.count(40)
var C = proto(Gem, function(superclass) {
this.name = 'C'
this.build = function() {
this.style = style
var container = Block([CheckBox()])
this.add(
CheckBox(),
container
)
}
})
var style = Style({
color: 'rgb(128, 0, 0)',
CheckBox: {
color: 'rgb(0, 128, 0)',
$$disabled: {
color: 'rgb(123, 130, 130)',
outline: '1px solid rgb(60, 60, 200)'
},
$$checked: {
color: 'rgb(128, 128, 128)',
outline: '4px solid rgb(80, 90, 100)',
$$required: {
color: 'rgb(130, 0, 130)',
backgroundColor: 'rgb(1, 2, 3)',
$setup: function(c) {
c.someProperty = 'required'
},
$kill: function(c) {
c.someProperty = 'optional'
}
}
}
},
Block: {
CheckBox: {color: 'rgb(0, 128, 0)'},
$$required: {
CheckBox: {
color: 'rgb(128, 128, 128)',
$$checked: {
$setup: function(c) {
c.someProperty = 'required'
},
$kill: function(c) {
c.someProperty = 'optional'
}
}
}
}
}
})
var component = C()
testUtils.demo("basic psuedo-class styling", component)
var children = component.children
var firstCheckBoxComponent = children[0]
var firstCheckBox = $(firstCheckBoxComponent.domNode)
this.eq(firstCheckBox.css('color'), 'rgb(0, 128, 0)')
this.log('just disabled')
firstCheckBoxComponent.attr('disabled', true)
setTimeout(function() { // need to use a timeout every time an attribute changes because the MutationObserver that listens for attribute changes is asynchornous and won't fire until the scheduler is reached
this.eq(firstCheckBox.css('color'), 'rgb(123, 130, 130)')
this.eq(firstCheckBox.css('outlineColor'), 'rgb(60, 60, 200)')
this.eq(firstCheckBox.css('backgroundColor'), defaultBackgroundColor)
this.eq(firstCheckBoxComponent.someProperty, undefined)
firstCheckBoxComponent.attr('disabled', undefined)
setTimeout(function() {
this.log("just checked")
firstCheckBoxComponent.selected = true
this.eq(firstCheckBox.css('color'), 'rgb(128, 128, 128)')
this.eq(firstCheckBox.css('outlineColor') , 'rgb(80, 90, 100)')
this.eq(firstCheckBox.css('backgroundColor'), defaultBackgroundColor)
this.eq(firstCheckBox.css('outlineWidth'), '4px')
this.eq(firstCheckBoxComponent.someProperty, undefined)
firstCheckBoxComponent.selected = false
this.log("just required")
firstCheckBoxComponent.attr('required', true)
setTimeout(function() {
this.eq(firstCheckBox.css('color'), 'rgb(0, 128, 0)') // the required pseudoclass doesn't apply because its within the checked psudeoclass (and the box isn't checked)
this.eq(firstCheckBox.css('outlineColor'), 'rgb(0, 128, 0)') // default outline color is whatever the 'color' property is
this.eq(firstCheckBox.css('backgroundColor'), defaultBackgroundColor)
this.eq(firstCheckBoxComponent.someProperty, undefined)
this.log("required and disabled")
firstCheckBoxComponent.attr('disabled', true)
setTimeout(function() {
this.eq(firstCheckBox.css('color'), 'rgb(123, 130, 130)')
this.eq(firstCheckBox.css('outlineColor'), 'rgb(60, 60, 200)')
this.eq(firstCheckBox.css('backgroundColor'), defaultBackgroundColor)
this.eq(firstCheckBoxComponent.someProperty, undefined)
firstCheckBoxComponent.attr('required', undefined)
setTimeout(function() {
this.log("disabled and checked")
firstCheckBoxComponent.selected = true
this.eq(firstCheckBox.css('color'), 'rgb(128, 128, 128)')
this.eq(firstCheckBox.css('outlineColor'), 'rgb(80, 90, 100)')
this.eq(firstCheckBox.css('backgroundColor'), defaultBackgroundColor)
this.eq(firstCheckBoxComponent.someProperty, undefined)
firstCheckBoxComponent.attr('disabled', undefined)
this.log("checked and required")
firstCheckBoxComponent.attr('required', true)
setTimeout(function() {
this.eq(firstCheckBox.css('color'), 'rgb(130, 0, 130)')
this.eq(firstCheckBox.css('outlineColor'), 'rgb(80, 90, 100)')
this.eq(firstCheckBox.css('backgroundColor'), 'rgb(1, 2, 3)')
this.eq(firstCheckBox.css('outlineWidth'), '4px')
this.eq(firstCheckBoxComponent.someProperty, 'required')
this.log("all 3: checked, required, and disabled")
firstCheckBoxComponent.attr('disabled', true)
setTimeout(function() {
this.eq(firstCheckBox.css('color'), 'rgb(130, 0, 130)')
this.eq(firstCheckBox.css('outlineColor'), 'rgb(80, 90, 100)')
this.eq(firstCheckBox.css('backgroundColor'), 'rgb(1, 2, 3)')
this.eq(firstCheckBoxComponent.someProperty, 'required')
this.log("just required (again)")
firstCheckBoxComponent.attr('disabled', false)
firstCheckBoxComponent.selected = false
setTimeout(function() {
this.eq(firstCheckBoxComponent.someProperty, 'optional')
var secondCheckBoxComponent = children[1].children[0]
var secondCheckBox = $(secondCheckBoxComponent.domNode)
this.eq(secondCheckBox.css('color'), 'rgb(0, 128, 0)')
this.eq(secondCheckBoxComponent.someProperty, undefined)
this.log("just required")
children[1].attr('required', true)
setTimeout(function() {
this.eq(secondCheckBox.css('color'), 'rgb(128, 128, 128)')
this.eq(secondCheckBoxComponent.someProperty, undefined)
children[1].attr('required', undefined)
setTimeout(function() {
this.log("just checked")
secondCheckBoxComponent.selected = true
this.eq(secondCheckBox.css('color'), 'rgb(0, 128, 0)')
this.eq(secondCheckBoxComponent.someProperty, undefined)
this.log("checked and required")
children[1].attr('required', true)
setTimeout(function() {
this.eq(secondCheckBox.css('color'), 'rgb(128, 128, 128)')
this.eq(secondCheckBoxComponent.someProperty, 'required')
}.bind(this),0)
}.bind(this),0)
}.bind(this),0)
}.bind(this),0)
}.bind(this),0)
}.bind(this),0)
}.bind(this),0)
}.bind(this),0)
}.bind(this),0)
}.bind(this),0)
}.bind(this),0)
})
this.test('combination of side-by-side emulated psuedoclasses', function(t) {
var red = 'rgb(128, 0, 0)'
var style = Style({
'$$nthChild(1)': {
textDecoration: 'underline'
},
'$$nthChild(2n+1)': {
color: red
}
})
var x,y;
var c = Block([
x = Text('a'),
y = Text('b')
])
testUtils.demo('combination of side-by-side emulated psuedoclasses', c)
x.style = style
y.style = style
t.eq($(x.domNode).css('color'), red)
t.ok($(x.domNode).css('textDecoration').indexOf('underline') !== -1)
t.ok($(y.domNode).css('color') !== red)
t.eq($(y.domNode).css('textDecoration').indexOf('underline'), -1)
})
this.test('validate manually', function() {
this.test("pseudo elements (native)", function() {
var red = 'rgb(128, 0, 0)'
var style = Style({
$$selection: {
color: red
}
})
var c = Text('When you select this, it should turn red')
testUtils.manualDemo("pseudo elements (native)", c)
c.style = style
})
this.test('visited', function() {
var C = proto(Gem, function(superclass) {
this.name = 'C'
this.build = function(text, link) {
this.domNode = domUtils.node('a')
this.attr('href', link)
this.attr('style', "display:block;")
this.domNode.textContent = text
this.on('click', function(e) {
e.preventDefault() // prevents you from going to the link location on-click
})
this.style = style
}
})
var style = Style({
color: 'rgb(150, 0, 0)',
$$visited: {
color: 'rgb(0, 128, 0)',
$$focus: {
color: 'rgb(0, 70, 200)'
}
}
})
var component1 = C("This should be green when not in focus, and blue when you click on it (if its not, visit google then try again)", "https://www.google.com/")
component1.attr('tabindex', 1) // to make it focusable
var component3 = C("This should be red (even when clicked on)", "http://www.thisdoesntexistatall.com/notatall")
component3.attr('tabindex', 1) // to make it focusable
// these need to be manually verified because the 'visited' pseudClass styles can't be verified via javascript for "security" reasons (privacy really)
testUtils.manualDemo('component :visited pseudo-class styling', Block([component1, component3]))
component1.focus = true
this.test('errors', function() {
this.count(1)
try {
Style({
Anything: {
$$visited: {
CheckBox: {
$setup: function() {
}
}
}
}
})
} catch(e) {
this.eq(e.message, "Pseudoclass visited isn\'t emulated, but has a style that can\'t be rendered in pure css")
}
})
})
})
this.test('not', function(t) {
var red = 'rgb(128, 0, 0)'
var teal = 'rgb(0, 128, 128)'
var style = Style({
Text: {
'$$not(:nthChild(1))': {
color: red
}
},
Block:{
'$$not(:nthChild(3))': {
Text: {
color: teal
}
}
}
})
var c = Block([
Text('a'),
Text('b'),
Block([Text('c')]),
Block([Text('d')])
])
testUtils.demo('not', c)
c.style = style
t.eq($(c.children[0].domNode).css('color'), 'rgb(0, 0, 0)')
t.eq($(c.children[1].domNode).css('color'), red)
t.eq($(c.children[2].children[0].domNode).css('color'), 'rgb(0, 0, 0)')
t.eq($(c.children[3].children[0].domNode).css('color'), teal)
})
this.test('js-rendered pseudoclasses', function() {
this.test('last-child', function(t) {
this.count(7)
var C = proto(Gem, function(superclass) {
this.name = 'C'
this.build = function() {
this.add(Text("a"))
this.add(Text("b"))
this.add(Text("c"))
this.add(Text("d"))
this.style = style
}
})
var style = Style({
Text:{
$$lastChild: {
color: 'rgb(128, 0, 0)',
$setup: function() {}, // forces it to render in javascript
$kill: function() {}
}
}
})
var component1 = C()
testUtils.demo('last-child', component1)
var children = component1.domNode.children
this.eq($(children[0]).css('color'), 'rgb(0, 0, 0)')
this.eq($(children[1]).css('color'), 'rgb(0, 0, 0)')
this.eq($(children[2]).css('color'), 'rgb(0, 0, 0)')
this.eq($(children[3]).css('color'), 'rgb(128, 0, 0)')
var classes = children[3].classList
this.eq(classes.length, 2) // one is the main default, and the other is the set active styling
// dynamically adding elements
component1.add(Text('e'))
setTimeout(function() { // the styles won't actually be applied until the thread runs back to the scheduler
t.eq($(children[3]).css('color'), 'rgb(0, 0, 0)')
t.eq($(children[4]).css('color'), 'rgb(128, 0, 0)')
},0)
})
this.test('nth-child', function() {
var parameterParseTestCases = {
'2': {constant:2, variable:0},
'n': {constant:0, variable:1},
'2n': {constant:0, variable:2},
'2+n': {constant:2, variable:1},
'n+2': {constant:2, variable:1},
'2n+2': {constant:2, variable:2},
'2+2n': {constant:2, variable:2},
'2-n': {constant:2, variable:-1},
'n-2': {constant:-2, variable:1},
'2n-2': {constant:-2, variable:2},
'2-2n': {constant:2, variable:-2}
}
for(var param in parameterParseTestCases) {
this.log(param)
this.ok(testUtils.equal(Style.parseNthChildParameter(param), parameterParseTestCases[param]), Style.parseNthChildParameter(param), parameterParseTestCases[param])
}
var C = proto(Gem, function(superclass) {
this.name = 'C'
this.build = function() {
this.add(Text("a"))
this.add(Text("b"))
this.add(Text("c"))
this.add(Text("d"))
this.style = style
}
})
var style = Style({
Text:{
'$$nthChild(1)': {
color: 'rgb(128, 0, 0)',
$setup: function() {}, // forces it to render in javascript
$kill: function() {}
},
'$$nthChild(2n)': {
color: 'rgb(0, 128, 128)',
$setup: function() {}, // forces it to render in javascript
$kill: function() {}
}
}
})
var component1 = C()
testUtils.demo('nth-child', component1)
var children = component1.domNode.children
this.eq($(children[0]).css('color'), 'rgb(128, 0, 0)')
this.eq($(children[1]).css('color'), 'rgb(0, 128, 128)')
this.eq($(children[2]).css('color'), 'rgb(0, 0, 0)')
this.eq($(children[3]).css('color'), 'rgb(0, 128, 128)')
this.test('more nth-child?', function(t) {
this.count(5)
var red = 'rgb(128, 0, 0)'
var teal = 'rgb(0, 128, 128)'
var style = Style({
Block:{
'$$nthChild(2)': {
Text: {
color: red,
$setup: function() {}, // forces it to render in javascript
$kill: function() {}
}
},
'$$nthChild(2n+1)': {
Text: {
color: teal,
$setup: function() {}, // forces it to render in javascript
$kill: function() {}
}
}
}
})
var c = Block([])
testUtils.demo('nth-child emulation', c)
c.style = style
c.add(Block([Text('a')]))
c.add(Block([Text('b')]))
c.add(Block([Text('c')]))
c.add(Block([Text('d')]))
c.add(Block([Text('e')]))
setTimeout(function() {
t.eq($(c.children[0].children[0].domNode).css('color'), teal)
t.eq($(c.children[1].children[0].domNode).css('color'), red)
t.eq($(c.children[2].children[0].domNode).css('color'), teal)
t.eq($(c.children[3].children[0].domNode).css('color'), 'rgb(0, 0, 0)')
t.eq($(c.children[4].children[0].domNode).css('color'), teal)
},0)
})
this.test("nth-child without parent", function(t) {
this.count(3)
var black = 'rgb(0, 0, 0)'
var red = 'rgb(128, 0, 0)'
var style = Style({
'$$nthChild( 1 + 1 n )': {
color: red,
$setup: function() {}, // forces it to render in javascript
$kill: function() {}
}
})
var box = Block([])
var c = Block([])
c.style = style
c.add(Text("moo"))
c.add(Text("moo2"))
box.add(c)
testUtils.demo("nth-child without parent", box)
setTimeout(function() { // allow the changes to propagate
t.eq($(c.children[0].domNode).css('color'), red)
t.eq($(c.children[1].domNode).css('color'), red)
var one = c.children[1]
c.remove(one)
setTimeout(function() { // allow the changes to propagate
box.add(one)
t.eq($(one.domNode).css('color'), black)
},0)
},0)
})
})
// todo: do this when you can figure out how syn.move works
// this.test("hover", function(t) {
// this.count(3)
//
// var style = Style({
// $$hover: {
// color: 'rgb(200, 0, 0)'
// }
// })
//
// var text = Text("a")
// text.style = style
//
// testUtils.demo('hover', text)
//
// this.eq($(text.domNode).css('color'), 'rgb(0, 0, 0)')
//
// syn.move({pageX: 100, pageY:100}, text.domNode).then(function() {
// t.eq($(text.domNode).css('color'), 'rgb(200, 0, 0)')
//
// return syn.move(text.domNode, {pageX: 100, pageY:100})
// }).then(function() {
// t.eq($(text.domNode).css('color'), 'rgb(0, 0, 0)')
// }).done()
// })
})
})
this.test("test styling objects that inherit from a component", function() {
var S = Style({
Text: Style({
color: 'rgb(128, 0, 0)'
})
})
var inheritsFromText = proto(Text, function() {})
var C = proto(Gem, function(superclass) {
this.name = 'C'
this.build = function() {
this.style = S
this.add(inheritsFromText('inParent'))
}
})
var node = C()
testUtils.demo("test styling objects that inherit from a component", node)
var text = $($(node.domNode).children('div')[0])
this.eq(text.css('color'), 'rgb(128, 0, 0)')
})
this.test("component state", function(t) {
var setupCalled = 0
var S = Style({
color: 'rgb(0, 100, 0)',
backgroundColor: 'rgb(23, 45, 99)',
$state: function(state) {
if(state.boggled) {
var color = 'rgb(100, 0, 0)'
} else {
var color = 'rgb(0, 0, 100)'
}
// note: do not create styles like this within the $state function if at all possible
// a new Style object is created every run, and probably won't get garbage collected, also obviously creating a new style is much slower than just referencing an already-created one
return Style({
color: color,
$setup: function() {
setupCalled++
},
$kill: function() {
// requisite
}
})
}
})
var c = Text("hi")
c.style = S
testUtils.demo("component state", c)
var text = $(c.domNode)
this.eq(text.css('color'), 'rgb(0, 0, 100)')
this.eq(text.css('backgroundColor'), 'rgb(23, 45, 99)')
this.eq(setupCalled, 1)
c.state.set('boggled', true)
this.eq(text.css('color'), 'rgb(100, 0, 0)')
this.eq(text.css('backgroundColor'), 'rgb(23, 45, 99)')
this.eq(setupCalled, 2)
c.style = undefined
this.eq(text.css('color'), 'rgb(0, 0, 0)')
this.eq(text.css('backgroundColor'), defaultBackgroundColor)
this.eq(setupCalled, 2)
})
this.test("$inherit", function() {
this.test("$inherit from component style map", function() {
var style = Style({
Block: {
backgroundColor: 'rgb(12, 14, 19)',
Block: {
$inherit: true,
color: 'rgb(15, 25, 35)'
}
}
})
var inner;
var thing = Block([Block([inner = Block([Text("hi")])])])
thing.style = style
testUtils.demo("$inherit from component style map", thing)
var innerNode = $(inner.domNode)
this.eq(innerNode.css('color'), 'rgb(15, 25, 35)')
this.eq(innerNode.css('backgroundColor'), 'rgb(12, 14, 19)')
})
this.test("label style inheriting from from sibling", function() {
var style = Style({
Text: {
backgroundColor: 'rgb(12, 14, 19)'
},
$textLabel: {
$inherit: true,
color: 'rgb(15, 25, 35)'
}
})
var text;
var thing = Block([text=Text('textLabel', "hi")])
thing.style = style
testUtils.demo("label style inheriting from from sibling", thing)
var textNode = $(text.domNode)
this.eq(textNode.css('color'), 'rgb(15, 25, 35)')
this.eq(textNode.css('backgroundColor'), 'rgb(12, 14, 19)')
})
this.test("explicit styling inheriting from component style map", function() {
var style = Style({
Text: {
backgroundColor: 'rgb(12, 14, 19)'
}
})
var text;
var thing = Block([text=Text('textLabel', "hi")])
thing.style = style
text.style = Style({
$inherit: true,
color: 'rgb(15, 25, 35)'
})
testUtils.demo("label style inheriting from from sibling", thing)
var textNode = $(text.domNode)
this.eq(textNode.css('color'), 'rgb(15, 25, 35)')
this.eq(textNode.css('backgroundColor'), 'rgb(12, 14, 19)')
})
this.test("inheriting from multiple levels of componentStyleMap", function() {
var style = Style({
Text: {
backgroundColor: 'rgb(12, 14, 19)'
},
Block: {
Text: {
$inherit: true,
color: 'rgb(15, 25, 35)'
},
Block: {
Text: {
$inherit: true,
width: 30
}
}
}
})
var inner;
var thing = Block([Block([Block([inner = Text("hi")])])])
thing.style = style
testUtils.demo("$inherit from component style map", thing)
var innerNode = $(inner.domNode)
this.eq(innerNode.css('backgroundColor'), 'rgb(12, 14, 19)')
this.eq(innerNode.css('color'), 'rgb(15, 25, 35)')
this.eq(innerNode.css('width'), '30px')
})
this.test("inheriting from multiple names of the same component", function() {
var Text2 = proto(Text, function(superclass) {
this.name = 'Text2'
})
var Text3 = proto(Text2, function(superclass) {
this.name = 'Text3'
})
var style = Style({
Text: {
backgroundColor: 'rgb(12, 14, 19)'
},
Text2: {
$inherit: true,
color: 'rgb(15, 25, 35)'
},
Text3: {
$inherit: true,
width: 30
},
$label: {
$inherit: true,
height: 30
}
})
var inner;
var thing = Block([
inner=Text3('label', "hi")
])
thing.style = style
testUtils.demo("$inherit from component style map", thing)
var innerNode = $(inner.domNode)
this.eq(innerNode.css('backgroundColor'), 'rgb(12, 14, 19)')
this.eq(innerNode.css('color'), 'rgb(15, 25, 35)')
this.eq(innerNode.css('width'), '30px')
this.eq(innerNode.css('height'), '30px')
})
this.test("inheriting from a label style", function() {
var inner = Gem.Text('something', "der")
var x = Gem.Block('a',[
Gem.Text('something', 'hi'),
Gem.Block('b', inner)
])
x.style = Gem.Style({
$something: {
color: 'rgb(150, 250, 255)'
},
$b: {
$something: {
$inherit: true
}
}
})
testUtils.demo("inheriting from a label style", x)
var innerNode = $(inner.domNode)
this.eq(innerNode.css('color'), 'rgb(150, 250, 255)')
})
this.test("inheriting from multiple levels of componentStyleMap with a label", function() {
var style = Style({
Text: {
backgroundColor: 'rgb(12, 14, 19)'
},
Block: {
$textLabel: {
$inherit: true,
color: 'rgb(15, 25, 35)'
},
Block: {
Text: {
$inherit: true,
width: 30
}
}
}
})
var inner;
var thing = Block([
Block([
Block([
inner = Text('textLabel',"hi")
])
])
])
thing.style = style
testUtils.demo("$inherit from component style map", thing)
var innerNode = $(inner.domNode)
this.eq(innerNode.css('backgroundColor'), 'rgb(12, 14, 19)')
this.eq(innerNode.css('color'), 'rgb(15, 25, 35)')
this.eq(innerNode.css('width'), '12px') // default (isn't affected)
})
this.test("inheriting from inside a pseudoclass", function() {
var inner1, inner2, outer
var x = Block('a',[
Block('b', inner1=Text('something', "hi ")),
Block('b', inner2=Text('something', "der ")),
outer=Text('something', 'yo'),
])
x.style = Gem.Style({
$b: {
$$firstChild: {
$something: {
$inherit: true,
backgroundColor: 'rgb(123, 150, 190)'
}
}
},
$something: {
color: 'rgb(12, 15, 19)'
}
})
window.moose = inner1
testUtils.demo("inheriting from inside a pseudoclass", x)
var innerNode1 = $(inner1.domNode)
var innerNode2 = $(inner2.domNode)
var outerNode = $(outer.domNode)
this.eq(innerNode1.css('color'), 'rgb(12, 15, 19)')
this.eq(innerNode1.css('backgroundColor'), 'rgb(123, 150, 190)')
this.eq(innerNode2.css('color'), 'rgb(12, 15, 19)')
this.eq(innerNode2.css('backgroundColor'), 'rgba(0, 0, 0, 0)') // the default
this.eq(outerNode.css('color'), 'rgb(12, 15, 19)')
this.eq(outerNode.css('backgroundColor'), 'rgba(0, 0, 0, 0)') // the default
})
this.test("inheriting from inside an emulated pseudoclass", function() {
var inner1, inner2, outer
var x = Block('a',[
outer=Text('something', 'hi'),
Block('b', inner1=Text('something', "der ")),
Block('b', inner2=Text('something', "yo ")),
])
x.style = Gem.Style({
$b: {
$$lastChild: {
$setup: function(){}, // requires emulation
$something: {
$inherit: true,
backgroundColor: 'rgb(123, 150, 190)'
}
}
},
$something: {
color: 'rgb(12, 15, 19)'
}
})
window.moose = inner1
testUtils.demo("inheriting from inside a pseudoclass", x)
var innerNode1 = $(inner1.domNode)
var innerNode2 = $(inner2.domNode)
var outerNode = $(outer.domNode)
this.eq(outerNode.css('color'), 'rgb(12, 15, 19)')
this.eq(outerNode.css('backgroundColor'), 'rgba(0, 0, 0, 0)') // the default
this.eq(innerNode1.css('color'), 'rgb(12, 15, 19)')
this.eq(innerNode1.css('backgroundColor'), 'rgba(0, 0, 0, 0)')
this.eq(innerNode2.css('color'), 'rgb(12, 15, 19)')
this.eq(innerNode2.css('backgroundColor'), 'rgb(123, 150, 190)') // the default
})
})
this.test('Style toObject and toString',function(t) {
this.test("basic", function() {
var styleObj = {
color: 'rgb(0, 128, 0)',
backgroundColor: "blue",
$inherit: true,
$$hover: {
color: 'orange'
},
A: {
color: "green",
AA: {
color: "yellow"
}
},
$B: {
color: 'red'
}
}
var S = Style(styleObj)
// hyphenate test object values
var testObj = {}
for(var p in styleObj) {
testObj[p] = styleObj[p]
}
testObj['background-color'] = testObj.backgroundColor
delete testObj.backgroundColor
this.ok(testUtils.equal(S.toObject(), testObj), S.toObject())
this.ok(testUtils.equal(S.fromString(S+'').toObject(), testObj), S+"")
})
this.test('functions', function() {
var styleObj = {
$state: function() {
return Style({
color: 'red'
})
},
$setup: function() {
return blippityBlue
},
$kill: function() {
return Style({
color: 'green'
})
},
}
var S = Style(styleObj)
this.ok(testUtils.equal(S.toObject(), styleObj), S.toObject())
var resultObj = S.fromString(S+'', {blippityBlue:'blue'}).toObject()
this.eq(resultObj.$state+'', styleObj.$state+'')
this.eq(resultObj.$setup+'', styleObj.$setup+'')
this.eq(resultObj.$kill+'', styleObj.$kill+'')
// Style should be a defined object
this.ok(testUtils.equal(resultObj.$state().toObject().color, 'red'), resultObj.$state().toObject())
this.ok(testUtils.equal(resultObj.$setup(), 'blue'), resultObj.$setup())
})
this.test("nested pseudoclasses", function() {
var styleObj = {
$$firstChild: {
color: 'green',
$$visited: {
backgroundColor: 'red',
}
}
}
var S = Style(styleObj)
var expectedResult = {
'$$first-child': {
color: 'green',
$$visited: {
color: 'green',
'background-color': 'red',
}
}
}
this.ok(testUtils.equal(S.toObject(), expectedResult), S.toObject())
var resultObj = S.fromString(S+'').toObject()
this.ok(testUtils.equal(resultObj, expectedResult), resultObj)
})
})
this.test('former bugs', function() {
this.test('propogating inner style wasnt working', function() {
var S = Style({
Block: {
Button: {
color: 'rgb(1,2,3)'
}
}
})
var C = Text('X')
C.style = S
var A = Block()
var B = Button('b')
A.add(B)
C.add(A)
testUtils.demo('propogating inner style wasnt working', C)
this.eq($(B.domNode).css('color'), 'rgb(1, 2, 3)')
})
this.test('inner styles inside labels werent working right', function() {
var S = Style({
$label: {
Text: {
color: 'rgb(1,2,3)'
}
}
})
var c = Block([
Block('label', [Text('hi')])
])
c.style = S
testUtils.demo('inner styles inside labels werent working right', c)
this.eq($(c.children[0].children[0].domNode).css('color'), 'rgb(1, 2, 3)')
})
this.test('inner styles inside labels werent working right when there was a style outside the label', function() {
var S = Style({
$label: {
Text: {
color: 'rgb(1,2,3)'
}
},
Text: {
color: 'rgb(20,50,90)'
}
})
var c = Block([
Block('label', [Text('hi')])
])
c.style = S
var superBlock = Block([c]) // the component has to be added to a parent for the bug to manifest
testUtils.demo('inner styles inside labels werent working right when there was a style outside the label', superBlock)
this.eq($(c.children[0].children[0].domNode).css('color'), 'rgb(1, 2, 3)')
})
this.test('removing the last child component failed', function() {
var c = Block([Text('a')])
c.remove(0)
})
this.test("loading Gem.js twice caused weird behavior - defaulting overriding main styling", function(t) {
this.count(6)
var container = Block()
testUtils.demo("loading Gem.js twice caused weird behavior - defaulting overriding main styling", container)
var c = Text('a')
c.defaultStyle = Style({
display: 'block'
})
c.style = Style({
position: 'absolute'
})
container.add(c)
t.eq($(c.domNode).css('position'), 'absolute')
t.eq($(c.domNode).css('display'), 'block')
// because of webpack's shaddowing (i'm guessing) this will cause window.Gem to get populated instead of being passed back to require.js (thus the "undefinedResult")
requirejs(["/dist/Gem.umd.js"], function(undefinedResult) {
t.eq($(c.domNode).css('position'), 'absolute')
t.eq($(c.domNode).css('display'), 'block')
var d = window.Gem.Text("d")
d.defaultStyle = Style({
display: 'block'
})
d.style = Style({
position: 'absolute'
})
container.add(d)
t.eq($(d.domNode).css('position'), 'absolute')
t.eq($(d.domNode).css('display'), 'block')
})
})
this.test("exception for Style with undefined value", function() {
return Style({
backgroundColor: undefined
})
})
this.test('last-child not working when more children are added asynchronously', function(t) {
this.count(10)
var C = proto(Gem, function(superclass) {
this.name = 'C'
this.build = function() {
this.add(Text("a"))
this.style = style
}
})
var style = Style({
Text:{
$$lastChild: {
color: 'rgb(128, 0, 0)'
}
}
})
var component1 = C()
testUtils.demo('last-child', component1)
t.eq($(component1.children[0].domNode).css('color'), 'rgb(128, 0, 0)')
setTimeout(function() {
component1.add(Text('b'))
t.eq($(component1.children[0].domNode).css('color'), 'rgb(0, 0, 0)')
t.eq($(component1.children[1].domNode).css('color'), 'rgb(128, 0, 0)')
setTimeout(function() {
component1.add(Text('c'))
t.eq($(component1.children[0].domNode).css('color'), 'rgb(0, 0, 0)')
t.eq($(component1.children[1].domNode).css('color'), 'rgb(0, 0, 0)')
t.eq($(component1.children[2].domNode).css('color'), 'rgb(128, 0, 0)')
setTimeout(function() {
component1.add(Text('d'))
t.eq($(component1.children[0].domNode).css('color'), 'rgb(0, 0, 0)')
t.eq($(component1.children[1].domNode).css('color'), 'rgb(0, 0, 0)')
t.eq($(component1.children[2].domNode).css('color'), 'rgb(0, 0, 0)')
t.eq($(component1.children[3].domNode).css('color'), 'rgb(128, 0, 0)')
},0)
},0)
},0)
})
this.test('native pseudoclass style overriding block default styles when they must override a StyleMap style with "initial"', function(t) {
var C = proto(Text, function(superclass) {
this.name = 'blah'
this.defaultStyle = Style({
color: 'rgb(100, 200, 250)'
})
})
var text = C("a'llo")
var c = Block([
Block('a', [text])
])
c.style = Style({
Text: {
color: 'rgb(12, 25, 36)',
display: "block"
},
$a: {
'$$nthChild(1)': {
Text: {
// color left as default (which should override the 'red' above)
}
}
}
})
testUtils.demo('native pseudoclass style overriding block default styles when they must override a StyleMap style with "initial"', c)
t.eq($(text.domNode).css('color'), 'rgb(100, 200, 250)')
t.eq($(text.domNode).css('display'), 'inline-block') // should be the base default value
})
this.test('native pseudoclass style not using default styles when they must override a StyleMap style with "initial" when there is no default style', function(t) {
var C = proto(Block, function(superclass) {
this.name = 'blah'
})
var text = C(Text("a'llo"))
var c = Block([
Block('a', [text])
])
c.style = Style({
Block: {
display: "block"
},
$a: {
'$$nthChild(1)': {
Block: {
// color left as default (which should override the 'red' above)
}
}
}
})
testUtils.demo('native pseudoclass style not using default styles when they must override a StyleMap style with "initial" when there is no default style', c)
t.eq($(text.domNode).css('display'), 'inline-block') // should be the base default value
})
this.test('native pseudoclass style not using default styles when they must override a StyleMap style with "initial" when there is no default style', function(t) {
var C = proto(Block, function(superclass) {
this.name = 'TicketView'
})
var thing = C(Text("a'llo"))
var c = Block([
C([thing])
])
c.style = Style({
TicketView: {
display: 'block',
TicketView: {
display: 'block',
minHeight: 22,
borderBottom: "1px solid red",
$$lastChild: {
borderBottom: 'none'
},
$componentBlock: {
display: 'flex',
alignItems: 'center',
}
}
}
})
testUtils.demo('native pseudoclass style not using default styles when they must override a StyleMap style with "initial" when there is no default style', c)
t.eq($(thing.domNode).css('display'), 'block') // should be the set value
t.eq($(thing.domNode).css('minHeight'), '22px')
t.eq($(thing.domNode).css('borderBottom'), '0px none rgb(0, 0, 0)') // this is what you get back for "none"
})
this.test('native pseudoclass style not using "inherit" for color, fontSize, etc when overriding a selector', function(t) {
var text = Text('hi')
var textContainer = Block(text)
var parent = Block(textContainer)
textContainer.style = Style({
Text: {
color: 'rgb(100, 0, 0)',
display: 'flex',
},
'$$nthChild(1)': {
color: 'rgb(0, 100, 0)',
display: 'block', // here to make sure display doesn't get 'inherit'
Text: {
// color should be set to 'inherit' here
// display should be set to 'initial'
}
}
})
testUtils.demo('native pseudoclass style not using "inherit" for color, fontSize, etc when overriding a selector', parent)
t.eq($(text.domNode).css('display'), 'inline-block') // should be the initial value
t.eq($(text.domNode).css('color'), 'rgb(0, 100, 0)')
})
this.test('native pseudoclass style not overriding competing psuedoclass styles', function(t) {
var C = proto(Block, function(superclass) {
this.name = 'Whatever'
})
var thing = C(Text("a'llo"))
var c = Block([
Block([thing])
])
c.style = Style({
Block: {
Whatever: {
display: 'table-cell',
$$firstChild: {
color: 'rgb(45, 46, 49)'
}
},
$$firstChild: {
Whatever: {
}
}
},
})
testUtils.demo('native pseudoclass style not using default styles when they must override a StyleMap style with "initial" when there is no default style', c)
t.eq($(thing.domNode).css('color'), 'rgb(0, 0, 0)')
t.eq($(thing.domNode).css('display'), 'inline-block')
})
this.test("improper caching caused invalid styles to be returned - case 1", function() {
var text = Text("text")
var inner = Block([Block('wrapper', [text])])
inner.style = Style({
marginRight: 2,
Text: {
minWidth: 22,
}
})
var component = Block(Block([inner]))
component.style = Style({
Block: {
display: 'block'
}
})
testUtils.demo('improper caching caused invalid styles to be returned - case 1', component)
this.eq($(text.domNode).css('minWidth'), '22px')
})
this.test("improper caching caused invalid styles to be returned - case 2", function() {
var text = Text()
var inner = Block([Block('wrapper', [text])])
inner.style = Style({
marginRight: 2,
Text: {
minWidth: 22,
padding: '0 2px',
textAlign: 'center',
border: '1px solid black',
minHeight: 18,
lineHeight: '15px',
cursor: 'pointer'
},
UserSelection: {
$setup: function(){},
Block: {} /// ????? why does removing this make the style *not* work?
}
})
var component = Block(Block([inner]))
component.style = Style({
Block: {
display: 'block'
}
})
testUtils.demo("improper caching caused invalid styles to be returned - case 2", component)
this.eq($(text.domNode).css('borderWidth'), '1px')
})
this.test("inherit inside pseudoclass style was causing an exception", function() {
var style = Style({
TableRow: {
'$$last-child':{
TableCell: {
},
$layoutCell: {
$inherit: true,
color: 'red'
}
}
}
})
var Table = Gem.Table
var component = Table([
['a1','b1','c1'],
['a2','b2','c2'],
['a3','b3','c3']
])
component.style = style
testUtils.demo("something", component)
// the point of this test is just to not throw an exception
})
// // todo:
// this.test("inherit inside a mixed in style wasn't inheriting properly", function() {
// var rightFirst
// var x = Block([
// Block('left',
// Block('icon', Text('something', "der")),
// Block('icon', Text('something', " kamiser"))
// ),
// Block('right',
// rightFirst = Block('icon', Text('something', "der")),
// Block('icon', Text('something', " kamiser"))
// )
// ])
//
// var firstStyle = {
// color: 'rgb(0,128,0)',
//
// $icon: {
// backgroundColor: 'yellow',
// },
//
// $$firstChild: {
// $icon: {
// $inherit: true,
// border: '1px solid rgb(128, 0, 0)'
// }
// },
// }
//
// x.style = Style({
// $left: firstStyle,
// $right: Style(firstStyle).mix({
// $icon: Style(firstStyle.$icon).mix({
// backgroundColor: 'rgb(0, 0, 128)'
// }),
// $$firstChild: firstStyle.$$firstChild
// })
// })
//
// testUtils.demo("inherit inside a mixed in style wasn't inheriting properly", x)
//
// var rightFirstNode = $(rightFirst.domNode)
// this.eq(rightFirstNode.css('border'), '1px solid rgb(128, 0, 0)')
// this.eq(rightFirstNode.css('backgroundColor'), 'rgb(0, 0, 128)')
// })
this.test('$inherit directly inside a pseudoclass was? working', function(t) {
var innerText
var x = Block(
Text("a", "red"),
Block('b', innerText=Text('a', 'redAndGreen'))
)
x.style = Style({
$a: {
$$firstChild: {
color: 'rgb(128, 0, 0)'
}
},
$b: {
$a: {
$inherit: true,
$$firstChild: {
$inherit: true, // doesn't inherit color: red
backgroundColor: 'rgb(0, 128, 0)'
}
}
}
})
testUtils.demo('$inherit directly inside a pseudoclass wasnt working', x)
t.eq($(innerText.domNode).css('color'), 'rgb(128, 0, 0)')
t.eq($(innerText.domNode).css('backgroundColor'), 'rgb(0, 128, 0)')
})
this.test("Svg styling throws an error because className is used differently for svg", function() {
var component = Svg("<svg></svg>")
component.style = Style({
color: 'green'
})
testUtils.demo("svg", component)
// the point of this test is just to not throw an exception
})
this.test("lower selectors were incorrectly propagating up the tree", function() {
var style = Style({
Block: {
$textLabel: {
color: 'blue'
}
},
})
var inner1, inner2
var thing = Block(inner1=Block(
))
thing.style = style
thing.attach()
this.eq(Object.keys(thing.computedStyleMap).length, 1)
this.ok(thing.computedStyleMap.Block !== undefined)
this.eq(Object.keys(inner1.computedStyleMap).length, 2)
this.ok(inner1.computedStyleMap.$textLabel !== undefined)
})
this.test("pseudoclass parameters with capitals were being transformed into dashes", function(t) {
this.count(1)
Style.addPseudoClass("testPseudoclass11", { // the psuedoclass here should be parsed
check: function(block, parameter) {
t.eq(parameter, 'SomeParameter')
},
setup: function() {
},
kill: function() {
}
})
var x = Block()
x.style = Style({
'$$testPseudoclass11(SomeParameter)': { // the parameter here should *not* be parsed
color: 'red'
}
})
testUtils.demo("pseudoclass parameters with capitals were being transformed into dashes", x)
})
})
//*/
}
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
///<reference path="../../../typings/jquery.d.ts" />
var core_1 = require('@angular/core');
var router_deprecated_1 = require('@angular/router-deprecated');
var http_1 = require('@angular/http');
var common_1 = require('@angular/common');
var control_messages_component_1 = require('../controls/control-messages.component');
var validation_service_1 = require('../../services/validation.service');
var logger_service_1 = require('../../services/logger.service');
var member_service_1 = require('../../services/member.service');
var author_service_1 = require('../../services/author.service');
var level_service_1 = require('../../services/level.service');
var position_service_1 = require('../../services/position.service');
var location_service_1 = require('../../services/location.service');
var teammember_service_1 = require('../../services/teammember.service');
var processmessage_service_1 = require('../../services/processmessage.service');
var pagetitle_service_1 = require('../../services/pagetitle.service');
var classes_1 = require('../../helpers/classes');
var AddMemberComponent = (function () {
//*****************************************************
// CONSTRUCTOR IMPLEMENTAION
//*****************************************************
function AddMemberComponent(_routeParams, _router, _memberService, _authorService, _locationService, _levelService, _positionService, _pmService, _pageTitleService, _teamMembersService, _loggerService, _formBuilder) {
this._routeParams = _routeParams;
this._router = _router;
this._memberService = _memberService;
this._authorService = _authorService;
this._locationService = _locationService;
this._levelService = _levelService;
this._positionService = _positionService;
this._pmService = _pmService;
this._pageTitleService = _pageTitleService;
this._teamMembersService = _teamMembersService;
this._loggerService = _loggerService;
this._formBuilder = _formBuilder;
this.newMember = new classes_1.ApplicationUser();
this.returnedMember = new classes_1.ApplicationUser();
this._members = [];
this._authors = [];
this._teams = [];
this._locations = [];
this._levels = [];
this._positions = [];
this._teammembers = [];
this.isSubmitted = false;
this.isAuthenticated = false;
this.isAllowed = false;
this.isRequesting = false;
this.memberForm = this._formBuilder.group({
'Name': ['', common_1.Validators.compose([common_1.Validators.required, validation_service_1.ValidationService.nameValidator])],
'Username': ['', common_1.Validators.compose([common_1.Validators.required, validation_service_1.ValidationService.usernameValidator])],
'Email': ['', common_1.Validators.compose([common_1.Validators.required, validation_service_1.ValidationService.emailValidator, validation_service_1.ValidationService.emailDomainValidator])],
'Phone': ['', common_1.Validators.compose([common_1.Validators.required, validation_service_1.ValidationService.phoneValidator])],
'Workpoint': ['', common_1.Validators.compose([common_1.Validators.required, validation_service_1.ValidationService.workpointValidator])],
'Manager': ['', common_1.Validators.required],
'Level': ['', common_1.Validators.required],
'Position': ['', common_1.Validators.required],
'Location': ['', common_1.Validators.required],
});
}
AddMemberComponent.prototype.ngOnInit = function () {
this._pageTitleService.emitPageTitle(new classes_1.PageTitle("Add Member"));
this._pmService.emitRoute("nill");
this.isRequesting = true;
this.newMember.TeamId = +this._routeParams.get('teamid');
this.getMembers();
this.getAuthors();
this.getLocations();
this.getLevels();
this.getPositions();
this.getTeamMembers();
};
AddMemberComponent.prototype.ngAfterViewInit = function () {
//$('#contact').validate({
// errorClass: 'error has-error',
// validClass: 'valid has-success'
//});
};
//****************************************************
// GET DATA
//****************************************************
AddMemberComponent.prototype.getMembers = function () {
var _this = this;
this._memberService.getMembers()
.subscribe(function (returnedMembers) {
_this._members = returnedMembers;
}, function (err) { return _this.onError(err, "Members"); });
};
AddMemberComponent.prototype.getAuthors = function () {
var _this = this;
this._authorService.getAuthors()
.subscribe(function (returnedAuthors) {
_this._authors = returnedAuthors;
_this._members.concat(_this._authors);
}, function (err) { return _this.onError(err, "Authors"); });
};
// get the locations based on the observable stream
AddMemberComponent.prototype.getLocations = function () {
var _this = this;
this._locationService.getLocalities()
.subscribe(function (returnedLocations) {
_this._locations = returnedLocations;
}, function (err) { return _this.onError(err, "Locations"); });
};
// get the levels based on the observable stream
AddMemberComponent.prototype.getLevels = function () {
var _this = this;
this._levelService.getLevels()
.subscribe(function (returnedLevels) {
_this._levels = returnedLevels;
}, function (err) { return _this.onError(err, "Levels"); });
};
// get the positions based on the observable stream
AddMemberComponent.prototype.getPositions = function () {
var _this = this;
this._positionService.getPositions()
.subscribe(function (returnedPositions) {
_this._positions = returnedPositions;
_this.isRequesting = false;
}, function (err) { return _this.onError(err, "Positions"); });
};
// this is needed to check is the user already in the team
// based on the email and the record in the teammember table
// not only on team id as the member can be a member of other teams
// but will have only one record for the team id
AddMemberComponent.prototype.getTeamMembers = function () {
var _this = this;
this._teamMembersService.getTeamMembers()
.subscribe(function (returnedTeamMembers) {
_this._teammembers = returnedTeamMembers;
_this.isRequesting = false;
}, function (err) { return _this.onError(err, "TeamMembers"); });
};
//****************************************************
// SUBMIT REQUEST
//****************************************************
AddMemberComponent.prototype.saveMember = function () {
if (this.memberForm.dirty && this.memberForm.valid) {
// if we are adding a member in the team
if (this.newMember.TeamId !== null) {
if (this.doesMemberExistsInTeam()) {
this._pmService.emitProcessMessage("PMME");
}
else {
this.addMember(this.newMember);
}
}
}
};
// try to add the member to the team
AddMemberComponent.prototype.addMember = function (member) {
var _this = this;
if (!member) {
return;
}
this.isRequesting = true;
this._memberService.addMember(member)
.subscribe(function (retmember) {
_this._members.push(retmember);
_this.onSuccessAddMember(retmember);
}, function (error) { return _this.onError(error, "AddMember"); });
};
// toggles the submitted flag which should disable the form and show the succes small form
AddMemberComponent.prototype.onSubmit = function () { this.isSubmitted = true; };
//****************************************************
// PRIVATE METHODS
//****************************************************
// success, the member has been added to the team
AddMemberComponent.prototype.onSuccessAddMember = function (passedMember) {
this.isSubmitted = true;
this.isRequesting = false;
this.returnedMember = passedMember;
this._pmService.emitProcessMessage("PMAMS");
};
// does member already exists in the list of team members, based on the username and email provided
// the members are all members of all teams , the teammember are records of a individual members in all teams
AddMemberComponent.prototype.doesMemberExistsInTeam = function () {
var _this = this;
var flag = false;
// Busesiness Rule: User with same user name or email can be set in a different team
this._members.forEach(function (x) {
_this._teammembers.forEach(function (y) {
if (x.Email == _this.newMember.Email && y.TeamId == _this.newMember.TeamId) {
flag = true;
}
});
});
return flag;
};
// an error has occured
AddMemberComponent.prototype.onError = function (err, type) {
var message;
// stop the spinner
this.isRequesting = false;
// we will log the error in the server side by calling the logger, or that is already
// done on the server side if the error has been caught
this._loggerService.logErrors(err, "add member page");
// we will display a fiendly process message using the process message service
if (err.status !== 200 || err.status !== 300) {
var data = err.json();
if (data.ModelState) {
for (var key in data.ModelState) {
for (var i = 0; i < data.ModelState[key].length; i++) {
//errors.push(data.modelState[key][i]);
if (message == null) {
message = data.ModelState[key][i];
}
else {
message = message + data.ModelState[key][i];
} // end if else
} // end for
} // end for
this._pmService.emitProcessMessage("PME", message);
} // end if
else {
// we will display a fiendly process message using the process message service
switch (type) {
case "Members":
this._pmService.emitProcessMessage("PMGMs");
break;
case "TeamMembers":
this._pmService.emitProcessMessage("PMGTMs");
break;
case "Authors":
this._pmService.emitProcessMessage("PMGAUs");
break;
case "Levels":
this._pmService.emitProcessMessage("PMGLs");
break;
case "Positions":
this._pmService.emitProcessMessage("PMGPs");
break;
case "Locations":
this._pmService.emitProcessMessage("PMGLos");
break;
case "AddMember":
this._pmService.emitProcessMessage("PMAM");
break;
default:
this._pmService.emitProcessMessage("PMG");
}
}
}
};
AddMemberComponent = __decorate([
core_1.Component({
selector: 'Add-Member-Form',
templateUrl: './app/views/members/add.member.component.html',
directives: [router_deprecated_1.ROUTER_DIRECTIVES, control_messages_component_1.ControlMessages],
providers: [http_1.Http, http_1.HTTP_BINDINGS, member_service_1.MemberService, author_service_1.AuthorService, location_service_1.LocationService, level_service_1.LevelService, position_service_1.PositionService, teammember_service_1.TeamMemberService]
}),
__metadata('design:paramtypes', [router_deprecated_1.RouteParams, router_deprecated_1.Router, member_service_1.MemberService, author_service_1.AuthorService, location_service_1.LocationService, level_service_1.LevelService, position_service_1.PositionService, processmessage_service_1.ProcessMessageService, pagetitle_service_1.PageTitleService, teammember_service_1.TeamMemberService, logger_service_1.LoggerService, common_1.FormBuilder])
], AddMemberComponent);
return AddMemberComponent;
}());
exports.AddMemberComponent = AddMemberComponent;
//# sourceMappingURL=add.member.component.js.map
|
module.exports = {
mqttServer: 'mqtt://k33g-orgs-macbook-pro.local:1883'
}
|
/* Created by Lumpychen on 16/5/23.*/
const verify = (state = ['empty','empty'], action) => {
switch (action.type) {
case 'VERIFY_STATE':
if (action.stk&&action.rf)
return [action.stk,action.rf];
else if (action.stk)
return [action.stk,state[1]]
else if (action.rf)
return [state[0],action.rf]
else return state;
default:
return state
}
}
export default verify
|
/**
* Created by cmiles on 9/21/2017.
*/
var express = require('express');
var router = express.Router();
router.get('/', function (req, res, next) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(oui_data));
});
module.exports = router;
|
// export class Point {
// constructor(x,y){
// public x=x;
// public y=y;
// }
// }
"use strict";
|
const assert = require('assert');
const parseurl = require('parseurl');
const util = require('./util');
const PATHNAME = '/whistle';
const {
WHISTLE_POLICY_HEADER,
DEFAULT_NAME,
WHISTLE_RULES_HEADER,
WHISTLE_VALUES_HEADER,
} = util;
const getPathname = (pathname) => {
if (typeof pathname !== 'string' || !pathname) {
return PATHNAME;
}
// 支持通过设置pathname = '?' 来禁用
// pathname = pathname.replace(/[#?].*/, '');
pathname = pathname.replace(/^\/|\/$/g, '');
if (!pathname) {
return PATHNAME;
}
return `/${pathname}`;
};
const normalizeOptions = (options) => {
options = Object.assign({}, options);
options.pathname = getPathname(options.pathname);
assert(options.serverPort > 0, ' Integer options.serverPort > 0 is required.');
options.serverHost = util.getHost(options.serverHost);
if (!options.name || typeof options.name !== 'string') {
options.name = DEFAULT_NAME;
} else {
options.name = encodeURIComponent(options.name);
}
options.host = `host://${options.serverHost}:${options.serverPort}`;
return options;
};
module.exports = (options) => {
options = normalizeOptions(options);
const pathname = options.pathname;
const absPath = `${pathname}/`;
const relPath = `${pathname.slice(pathname.lastIndexOf('/') + 1)}/`;
const PROXY_ID_HEADER = `x-${options.name}-${Date.now()}`;
const request = util.getProxy(options).request;
const { rules, values } = options;
return (req, filter) => {
const headers = req.headers;
if (headers[PROXY_ID_HEADER]) {
delete headers[PROXY_ID_HEADER];
delete headers[WHISTLE_RULES_HEADER];
delete headers[WHISTLE_VALUES_HEADER];
delete headers[WHISTLE_POLICY_HEADER];
return false;
}
const opts = parseurl(req);
headers[WHISTLE_RULES_HEADER] = encodeURIComponent(`${headers.host || opts.host} ${options.host}`);
headers[PROXY_ID_HEADER] = 1;
if (opts.pathname === pathname) {
return Promise.resolve({
statusCode: 302,
headers: { location: `${relPath}${opts.search || ''}` },
});
}
const path = opts.path;
let isWhistleUI;
if (path.indexOf(absPath) === 0) {
req.url = path.replace(pathname, '');
req.headers.host = 'local.wproxy.org';
isWhistleUI = true;
} else {
req.rules = rules;
req.values = values;
}
req.followRedirect = false;
if (isWhistleUI || !filter) {
return request(req);
}
return filter(req).then((result) => {
return result === false ? false : request(req);
});
};
};
|
// ========================================= ========================================= =========================================
//*************** -------------- ___________ EFFET HIGHLIGHT POUR HOVER
// ========================================= ========================================= =========================================
/*
* Exemple d'utilisation:
* $('#menu_display ul li a').mousemove(function(e) {
highlight(e, this,"rgba(255,255,255,1)", "rgba(227,227,226,1)" , 150);
}).mouseleave(function() {
$(this).css({ background: originalBG });
});
*
* @param eventObject event. Evenement
* @param object item. Objet du DOM concerne
* @param string colorBackground. Couleur de fond
* @param integer colorLight. Couleur du point lumineux
* @param integer diameter. Diametre du point lumineux
* @param integer factor. Diametre de l''ampleur de la lumiere
*/
function highlight(event, item, colorBackground, colorLight, diameter, diameterLight)
{
//var x = event.pageX - item.offsetLeft; //Ne marche pas sur le menu top
var x = event.pageX - $(item).offset().left
//var y = event.pageY - item.offsetTop //Ne marche pas sur le menu top
var y = event.pageY - $(item).offset().top;
var xy = x + " " + y;
var bgWebKit = "-webkit-gradient(radial, " + xy + ", " + diameter +", " + xy + ", "+ diameterLight + ", from(" + colorLight +"), to( " + colorBackground + ")) ";
var bgMoz = "-moz-radial-gradient(" + x + "px " + y + "px 45deg, circle, " + colorLight + diameter +"px, " + colorBackground + " " + diameterLight + "px)";
$(item).css({ background: bgWebKit }).css({ background: bgMoz });
}
// ========================================= ========================================= =========================================
//*************** -------------- ___________ ANIMATIONS AU SCROLLING
// ========================================= ========================================= =========================================
/**
* Calcule et renvoie un attribut d'une valeur de depart jusqu'a une valeur d'arrivee en fonction de la position du scroll,
* d'un offset de depart et d'arrivee.
* Exemple d'utilisation:
* var posTop = $(window).scrollTop();
var posStart = $(" #formation div.description_aside").offset().top - 500;
var posEnd = posStart + 300;
$("#formation div.description_aside").css({
"opacity": anime_div(posTop, posStart, posEnd, 0, 1)
})
*
* @param integer offset. offset = $(window).scrollTop() a passer en parametre (la fonction anime_div est prevue d'etre utilisee plusieurs fois, on economisera du proc)
* @param integer start. offset haut du declechement de l'anim en px
* @param integer end. offset bas du declenchement de l'anim en px
* @param integer posXCenter. Attribut left du centre(en absolu) dans le parent de notre element concerne
* @param integer posYCenter. Attribut top du centre(en absolu) dans le parent de notre element concerne
*/
function anime_div(offset, start, end, valStart ,valEnd){
// Si on se situe en dehors des limites d'offset de l'animation, rien ne se passe.
if(offset < start){
return valStart;
} else if(offset > end){
return valEnd;
}
// Cas ou l'on se situe dans les limites
var offsetRelative = (offset - start);
var coeffDir = (valEnd - valStart)/(end - start)
var result = valStart + coeffDir*offsetRelative;
return result;
}
/**
* Meme chose que pour anim_div mais cette fonction est prevue pour creer une animation de rotation.
* Attributs css concernes: "top" et "left".
*
* @param integer start. offset haut du declechement de l'anim en px
* @param integer end. offset bas du declenchement de l'anim en px
* @param integer posXCenter. Attribut left du centre(en absolu) dans le parent de notre element concerne
* @param integer posYCenter. Attribut top du centre(en absolu) dans le parent de notre element concerne
* @param integer radius. rayon du cercle en px.
* @param integer angleStart. L'angle de depart de l'animation (en degre)
* @param integer angleEnd. L'angle d'arrivee de l'animation (en degre)
*/
function anime_divRound(start, end, posXCenter, posYCenter , radius, angleStart, angleEnd)
{
var offset = $(window).scrollTop();
var position = new Array();
if(offset < start){
position["x"] = posXCenter + radius*Math.cos(degToRad(angleStart));
position["y"] = posYCenter - radius*Math.sin(degToRad(angleStart));
return position;
}
else if(offset > end){
position["x"] = posXCenter + radius*Math.cos(degToRad(angleEnd));
position["y"] = posYCenter - radius*Math.sin(degToRad(angleEnd));
return position;
}
// Cas ou l'on se situe dans les limites
var offsetRelative = degToRad((offset - start)*(angleEnd - angleStart)/(end - start));
position["x"] = posXCenter + radius*Math.cos(offsetRelative);
position["y"] = posYCenter - radius*Math.sin(offsetRelative);
return position;
}
/*
* Convertit un angle en degres vers sa valeur en radians.
*
* @param integer angle. Angle en degre
*
* @return angle. Angle en radians
*/
function degToRad(angle)
{
return angle*(Math.PI)/180;
}
// ========================================= ========================================= =========================================
//*************** -------------- ___________ SLIDER A DOUBLE CHAMPS
// ========================================= ========================================= =========================================
/**
* Scroll du slider et de la description associee
*
* @param integer next. Direction du scrolling
*/
function newsscoller(next, speed)
{
var $current_image = $(".gallery li.selected");
var $current_gallery = $current_image.parents(".gallery");
var index_current_image = $current_gallery.find("li").index($current_image[0]);
var index_current_gallery = $(".gallery").index($current_gallery[0]);
// ============= IMAGE SUIVANTE
if(next){
// On determince l'index de l'element li de l'image suivante
var indexImage = index_current_image + 1;
indexImage = ($current_gallery.find("li").eq(indexImage)[0] != undefined) ? indexImage : 0;
// On determine l'index de la gallerie suivante
if(indexImage == 0){
var indexGallery = index_current_gallery + 1;
indexGallery = (indexGallery < $(".gallery").length) ? indexGallery : 0;
} else {
var indexGallery = index_current_gallery;
}
// ============= IMAGE PRECEDENTE
} else {
// On initialise l'index de l'image precedente
var indexImage = index_current_image - 1;
// On determince l'index de l'element li de l'image precedente et de la gallerie precedente
if(indexImage < 0){
var indexGallery = (index_current_gallery == 0) ? sizeGallery.length-1 : index_current_gallery -1;
console.log(indexGallery)
indexImage = sizeGallery[indexGallery] -1;
} else {
indexGallery = index_current_gallery;
}
}
// Attribution de la classe ".selected" uniquement aux elements a afficher
$(".gallery li , .excerpt li").removeClass("selected");
var $imageSelected = $(".gallery").eq(indexGallery).find("li").eq(indexImage);
var $excerptSelected = $(".excerpt").eq(indexGallery).find("li").eq(indexImage);
$imageSelected.addClass("selected");
$excerptSelected.addClass("selected");
$('#mask-gallery').scrollTo($imageSelected, speed);
$('#mask-excerpt').scrollTo($excerptSelected, speed);
}
|
;(function(){
var tpl_edit = QNML.TPL.CODE_EDIT;
var tpl_view = QNML.TPL.CODE_VIEW;
qnml.addLanguage({
nodeName:"qnml:code",
parse:function(match,attr,text,option){
var language = /language=[\"\']?(\w*)[\"\']?/i.exec(attr)[1];
var languageText = language,oRet;
//向前兼容
if(oRet = /text=[\"\']?(\w*)[\"\']?/i.exec(attr)){
languageText = oRet[1];
}
if(option && option.status == "edit")
return qnml.lib.tmpl(tpl_edit, {language:language,languageText:languageText,tag:encodeURIComponent(match),source:text,isNew:option.isNew});
else{
//decode
var div = document.createElement("textarea");
div.innerHTML = text.replace(/\n/g,"%@%");
var value = div.value.replace(/%@%/g,"\n");
if(value =="") value=" ";
if(value[value.length-1]=="\n")
value += " ";
return qnml.lib.tmpl(tpl_view, {language:language,languageText:languageText,hilightcode:qnml.parseAll("<qnml:code-"+language+">"+value+"</qnml:code-"+language+">")});
}
},
style:QNML.STYLE.CODE
});
})();
|
import Future from './future';
import {isFuture, isNever, never, of, reject} from './core';
import * as dispatchers from './dispatchers';
import {after, rejectAfter} from './after';
import {attempt} from './attempt';
import {cache} from './cache';
import {chainRec} from './chain-rec';
import {encase} from './encase';
import {encase2} from './encase2';
import {encase3} from './encase3';
import {encaseN} from './encase-n';
import {encaseN2} from './encase-n2';
import {encaseN3} from './encase-n3';
import {encaseP} from './encase-p';
import {encaseP2} from './encase-p2';
import {encaseP3} from './encase-p3';
import {go} from './go';
import {hook} from './hook';
import {node} from './node';
import {Par, seq} from './par';
import {parallel} from './parallel';
import {tryP} from './try-p';
import {error} from './internal/throw';
if(typeof Object.create !== 'function') error('Please polyfill Object.create to use Fluture');
if(typeof Object.assign !== 'function') error('Please polyfill Object.assign to use Fluture');
if(typeof Array.isArray !== 'function') error('Please polyfill Array.isArray to use Fluture');
export default Object.assign(Future, dispatchers, {
Future,
after,
attempt,
cache,
chainRec,
do: go,
encase,
encase2,
encase3,
encaseN,
encaseN2,
encaseN3,
encaseP,
encaseP2,
encaseP3,
go,
hook,
isFuture,
isNever,
never,
node,
of,
Par,
parallel,
reject,
rejectAfter,
seq,
try: attempt,
tryP,
});
|
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS205: Consider reworking code to avoid use of IIFEs
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const sinon = require("sinon")
const rewire = require("rewire")
const proxyToReflection = rewire("../../../lib/middleware/proxy_to_reflection")
describe("proxyToReflection", function () {
beforeEach(function () {
this.req = { query: {} }
this.res = {}
this.next = sinon.stub()
this.request = sinon.stub()
this.request.returns(this.request)
this.request.head = sinon.stub().returns(this.request)
this.request.end = sinon.stub().returns(this.request)
proxyToReflection.__set__("request", this.request)
proxyToReflection.__set__("proxy", (this.proxy = { web: sinon.stub() }))
return proxyToReflection.__set__("REFLECTION_URL", "reflection.url")
})
it("passes through when there is no escaped fragment query param", function () {
this.req.query._escaped_fragment_ = null
proxyToReflection(this.req, this.res, this.next)
return this.next.called.should.be.ok()
})
it("passes through if reflection fails", function () {
this.req.query._escaped_fragment_ = null
const err = new Error("Unauthorized")
err.status = 403
this.request.end.callsArgWith(0, err)
proxyToReflection(this.req, this.res, this.next)
return this.next.called.should.be.ok()
})
return context("with _escaped_fragment_", function () {
const paths = {
"/artwork/foo-bar?_escaped_fragment_=": "/artwork/foo-bar",
"/artwork/foo-bar?a=b&c=d&_escaped_fragment_=":
"/artwork/foo-bar%3Fa%3Db%26c%3Dd",
"/artwork/foo-bar?a=b&c=d%3Ae&_escaped_fragment_=":
"/artwork/foo-bar%3Fa%3Db%26c%3Dd%3Ae",
}
return (() => {
const result = []
for (let source in paths) {
let dest = paths[source]
result.push(
it(`proxies ${source} to ${dest}`, function () {
this.req.url = source
this.req.query._escaped_fragment_ = ""
this.request.end.callsArg(0)
proxyToReflection(this.req, this.res, this.next)
const options = this.proxy.web.args[0][2]
return options.target.should.equal(`reflection.url${dest}`)
})
)
}
return result
})()
})
})
|
/* */
'use strict';
Object.defineProperty(exports, "__esModule", {value: true});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin');
var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin);
var _svgIcon = require('../../svg-icon');
var _svgIcon2 = _interopRequireDefault(_svgIcon);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
var DeviceUsb = _react2.default.createClass({
displayName: 'DeviceUsb',
mixins: [_reactAddonsPureRenderMixin2.default],
render: function render() {
return _react2.default.createElement(_svgIcon2.default, this.props, _react2.default.createElement('path', {d: 'M15 7v4h1v2h-3V5h2l-3-4-3 4h2v8H8v-2.07c.7-.37 1.2-1.08 1.2-1.93 0-1.21-.99-2.2-2.2-2.2-1.21 0-2.2.99-2.2 2.2 0 .85.5 1.56 1.2 1.93V13c0 1.11.89 2 2 2h3v3.05c-.71.37-1.2 1.1-1.2 1.95 0 1.22.99 2.2 2.2 2.2 1.21 0 2.2-.98 2.2-2.2 0-.85-.49-1.58-1.2-1.95V15h3c1.11 0 2-.89 2-2v-2h1V7h-4z'}));
}
});
exports.default = DeviceUsb;
module.exports = exports['default'];
|
module.exports = function findStopPosition(index, arraySize) {
if (index === 0) {
return 'first-'
} else if (index === arraySize - 1) {
return 'last-'
} else {
return ''
}
};
|
"use strict";
/**
* @internalapi
* @module vanilla
*/
/** */
var predicates_1 = require("../common/predicates");
/** A `LocationConfig` that delegates to the browser's `location` object */
var BrowserLocationConfig = (function () {
function BrowserLocationConfig(router, _isHtml5) {
if (_isHtml5 === void 0) { _isHtml5 = false; }
this._isHtml5 = _isHtml5;
this._baseHref = undefined;
this._hashPrefix = "";
}
BrowserLocationConfig.prototype.port = function () {
return parseInt(location.port);
};
BrowserLocationConfig.prototype.protocol = function () {
return location.protocol;
};
BrowserLocationConfig.prototype.host = function () {
return location.host;
};
BrowserLocationConfig.prototype.html5Mode = function () {
return this._isHtml5;
};
BrowserLocationConfig.prototype.hashPrefix = function (newprefix) {
return predicates_1.isDefined(newprefix) ? this._hashPrefix = newprefix : this._hashPrefix;
};
;
BrowserLocationConfig.prototype.baseHref = function (href) {
return predicates_1.isDefined(href) ? this._baseHref = href : this._baseHref || this.applyDocumentBaseHref();
};
BrowserLocationConfig.prototype.applyDocumentBaseHref = function () {
var baseTags = document.getElementsByTagName("base");
return this._baseHref = baseTags.length ? baseTags[0].href.substr(location.origin.length) : "";
};
BrowserLocationConfig.prototype.dispose = function () { };
return BrowserLocationConfig;
}());
exports.BrowserLocationConfig = BrowserLocationConfig;
//# sourceMappingURL=browserLocationConfig.js.map
|
import { equals } from 'dummy/helpers/equals';
import { module, test } from 'qunit';
module('Unit | Helper | equals', function() {
test('it returns true if two primitives are equal', function(assert) {
let result = equals([42, 42]);
assert.ok(result);
});
test('it returns true if both values are null/undefined/empty', function(assert) {
let result = equals([null, undefined]);
assert.ok(result);
result = equals([null, '']);
assert.ok(result);
result = equals(['', undefined]);
assert.ok(result);
});
test('it returns true if two objects are reference equal', function(assert) {
var foo = {};
var bar = foo;
let result = equals([foo, bar]);
assert.ok(result);
});
test('it returns false if two primitives are not equal', function(assert) {
let result = equals([7, 42]);
assert.notOk(result);
});
test('it returns false if two objects are not reference equal', function(assert) {
var foo = {};
var bar = {};
let result = equals([foo, bar]);
assert.notOk(result);
});
});
|
export default /* glsl */`
#ifdef MAPCOLOR
uniform vec3 material_specular;
#endif
#ifdef MAPTEXTURE
uniform sampler2D texture_specularMap;
#endif
void getSpecularity() {
dSpecularity = vec3(1.0);
#ifdef MAPCOLOR
dSpecularity *= material_specular;
#endif
#ifdef MAPTEXTURE
dSpecularity *= texture2D(texture_specularMap, $UV).$CH;
#endif
#ifdef MAPVERTEX
dSpecularity *= saturate(vVertexColor.$VC);
#endif
}
`;
|
/**
* Created by Manhhailua on 11/30/16.
*/
import Entity from './Entity';
import { term, adsStorage, util } from '../vendor';
class Banner extends Entity {
constructor(banner) {
super(banner);
this.id = `banner-${banner.id}`;
this.isRelative = banner.isRelative;
this.keyword = banner.keyword;
this.terms = banner.terms;
this.location = banner.location;
this.fr = banner.fr;
this.channel = banner.channel;
this.bannerType = banner.bannerType;
this.test = banner.test;
this.bannerType = banner.bannerType;
this.dataBannerHtml = banner.dataBannerHtml;
this.linkFormatBannerHtml = banner.linkFormatBannerHtml;
this.isIFrame = banner.isIFrame;
this.imageUrl = banner.imageUrl;
this.zoneId = banner.zoneId;
this.placementId = banner.placementId;
this.optionBanners = banner.optionBanners;
this.isRotate = banner.isRotate;
this.campaignId = banner.campaignId;
this.isAvailable = undefined;
}
// Banner Checking Process
isRenderable() {
if (window.cacheBannerCheck && window.cacheBannerCheck[this.id]) return window.cacheBannerCheck[this.id];
console.log('runCheckBanner', this.isAvailable);
const isBannerAvailable = this.id !== 'banner-undefined';
const isFitChannel = this.checkChannel.check && this.checkChannel.checkGlobal;
// const isFitLocation = this.checkLocation;
const isFitFrequency = this.checkFrequency;
const res = (isBannerAvailable && isFitChannel) && isFitFrequency;
console.log(`${this.id}: fre:${isFitFrequency}, channel: ${isFitChannel}, isBannerAvailable: ${isBannerAvailable}, res: ${res}`);
window.cacheBannerCheck = window.cacheBannerCheck || {};
window.cacheBannerCheck[this.id] = res;
return res;
}
checkGlobalFilter(typeInChannel, valueInChannel) {
const globalFilters = this.globalFilters;
console.log('globalFilterInBanner', globalFilters);
if (globalFilters.length === 0) return true;
let strChk = '';
for (let i = 0, length = globalFilters.length; i < length; i += 1) {
console.log('testAAAA');
if (i > 0) strChk += '&&';
const type = globalFilters[i].type;
const startTime = globalFilters[i].startTime;
const endTime = globalFilters[i].endTime;
const value = globalFilters[i].value;
const comparison = globalFilters[i].comparison;
const isExpire = util.checkTime(startTime, endTime);
if (isExpire) {
if (type === typeInChannel) {
strChk += (comparison === '==' ? valueInChannel === value : valueInChannel !== value);
} else strChk += true;
} else strChk += true;
console.log('checkGlobalFilter', strChk, valueInChannel, comparison, value, isExpire, type, typeInChannel); // eslint-disable-line
}
return eval(strChk); // eslint-disable-line
}
// check term old data (not use)
get checkTerm() {
if (this.terms) {
const terms = this.terms;
const len = terms.length;
const a = eval; // eslint-disable-line no-eval
let str = '';
let operator = '';
for (let i = 0; i < len; i += 1) {
if (i !== 0) operator = (terms[i].join === 'or' ? '||' : '&&');
if (terms[i].channel) {
str += `${operator + ((terms[i].logic === '!~') ? '!' : '')}(${term.checkPath(terms[i].data, ((terms[i].logic === '==') ? '&&' : '||'))})`;
} else {
str += operator +
term.checkPathLogic(terms[i].data, terms[i].type, terms[i].logic);
}
}
return a(str);
}
return true;
}
/* eslint-disable */
// get checkChannel() {
// const channelData = this.channel;
// if (channelData !== undefined && channelData !== null && channelData !== '') {
// const channel = channelData;
// const options = channel.options.filter(item => item.name !== 'Location' && item.name !== 'Browser');
// const optionsLength = options.length;
// const a = eval; // eslint-disable-line no-eval
// let strChk = '';
//
// for (let i = 0; i < optionsLength; i += 1) {
// const optionChannelType = options[i].optionChannelType;
// const value = options[i].value.toString().split(',');
// const comparison = options[i].comparison;
// const logical = options[i].logical === 'and' ? '&&' : '||';
// const globalVariableName = options[i].globalVariables;
// console.log('globalVariableName', globalVariableName, i);
// // eslint-disable-next-line
// let globalVariable = (globalVariableName !== '' && a(`typeof (${globalVariableName}) !== 'undefined'`)) ? a(globalVariableName) : undefined;
// globalVariable = encodeURIComponent(globalVariable);
// console.log('globalVariable', globalVariable);
// const globalVariableTemp = (typeof (globalVariable) !== 'undefined' && globalVariable !== '') ? globalVariable : '';
// console.log('globalVariableTemp', globalVariableTemp);
// let currentAdditionalDetail = '';
// let type = optionChannelType.isInputLink ? 'isInputLink' : '';
// let stringCheck = '';
// let additionalDetail = []; // get optionChannelValueProperties
// type = optionChannelType.isSelectOption ? 'isSelectOption' : type;
// type = optionChannelType.isVariable ? 'isVariable' : type;
// console.log('type', type);
// // console.log('valueCheck', value);
// if (optionChannelType.optionChannelValues.length > 0) {
// additionalDetail = optionChannelType.optionChannelValues.filter(item =>
// value.reduce((acc, valueItem) => acc || (item.value === valueItem
// && item.optionChannelValueProperties.length > 0), 0));
// }
// console.log('value', value);
// for (let j = 0; j < value.length; j += 1) {
// if (j > 0) stringCheck += '||';
// switch (type) {
// case 'isVariable': {
// if ((globalVariableName !== '' && eval(`typeof (${globalVariableName}) !== 'undefined'`))) { // eslint-disable-line no-eval
// if (typeof (globalVariable) !== 'undefined' && globalVariable !== '') {
// stringCheck += term.checkPathLogic(value[j], 'Site:Pageurl', globalVariableName, comparison);
// console.log('checkChannel', type, term.getPath2Check('Site:Pageurl', globalVariableName), comparison, value[j]);
// }
// } else {
// stringCheck += term.checkPathLogic(value[j], 'Site:Pageurl', '', comparison);
// console.log('checkChannel', type, term.getPath2Check('Site:Pageurl', ''), comparison, value[j]);
// }
// break;
// }
// case 'isInputLink': {
// stringCheck += term.checkPathLogic(value[j], 'Site:Pageurl', '', comparison);
// console.log('checkChannel', type, term.getPath2Check('Site:Pageurl', ''), comparison, value[j]);
// break;
// }
// case 'isSelectOption': {
// const pageUrl = term.getPath2Check('Site:Pageurl', globalVariableName);
// const thisChannel = util.getThisChannel(pageUrl);
// thisChannel.shift();
//
// // do smt with additionalDetail
// if (additionalDetail.length > 0) {
// // region : get link detail
// if (typeof (globalVariable) !== 'undefined' && globalVariable !== '') {
// a(`${globalVariableName} = ''`);
// }
// currentAdditionalDetail = util.getThisChannel(pageUrl).pop();
// currentAdditionalDetail.shift();
// if (typeof (globalVariable) !== 'undefined' && globalVariable !== '') {
// a(`${globalVariableName} = globalVariableTemp`);
// }
// // endregion : get link detail
//
// console.log('additionalDetail', additionalDetail, currentAdditionalDetail);
// }
// console.log('checkChannel', type, thisChannel[0], comparison, value[j]);
// switch (comparison) {
// case '==': {
// stringCheck += value[j] === thisChannel[0];
// break;
// }
// case '!=': {
// stringCheck += value[j] !== thisChannel[0];
// break;
// }
// default: {
// stringCheck += false;
// break;
// }
// }
// break;
// }
// default: {
// stringCheck += false;
// break;
// }
// }
// }
// const CheckValue = a(stringCheck);
// if (i > 0) strChk += logical;
// strChk += CheckValue;
// }
// console.log('strChk', strChk, a(strChk));
// return a(strChk);
// }
// return true;
// }
/* eslint-enable */
get checkChannel() {
if (this.optionBanners !== undefined &&
(this.optionBanners.length === 0 || this.optionBanners === null)) return { check: true, checkGlobal: true };
if (this.optionBanners !== undefined && this.optionBanners !== null) {
const optionBanner = this.optionBanners;
const checkLength = optionBanner.length;
const checkChannel = (channelData) => {
if (channelData !== undefined && channelData !== null && channelData !== '') {
const channel = channelData;
console.log('channell', channel);
const options = channel.optionChannels.filter(item => (item.name !== 'Location'));
const optionsLength = options.length;
const a = eval; // eslint-disable-line no-eval
let strChk = '';
let strCheckGlobal = '';
if (optionsLength > 0) {
for (let i = 0; i < optionsLength; i += 1) {
const optionChannelType = options[i].optionChannelType;
const value = options[i].value.toString().split(',');
const comparison = options[i].comparison;
const logical = options[i].logical === 'and' ? '&&' : '||';
const globalVariableName = options[i].globalVariables;
console.log('globalVariableName', globalVariableName, i);
// eslint-disable-next-line
let globalVariable = (globalVariableName !== '' && a(`typeof (${globalVariableName}) !== 'undefined'`)) ? a(globalVariableName) : undefined;
globalVariable = encodeURIComponent(globalVariable);
console.log('globalVariable', globalVariable);
const globalVariableTemp = (typeof (globalVariable) !== 'undefined' && globalVariable !== '') ? globalVariable : '';
console.log('globalVariableTemp', globalVariableTemp);
let currentAdditionalDetail = '';
let type = optionChannelType.isInputLink ? 'isInputLink' : '';
let stringCheck = '';
let stringCheckGlobal = '';
let additionalDetail = []; // get optionChannelValueProperties
type = optionChannelType.isSelectOption ? 'isSelectOption' : type;
type = optionChannelType.isVariable ? 'isVariable' : type;
console.log('type', type);
// console.log('valueCheck', value);
if (optionChannelType.optionChannelValues.length > 0) {
additionalDetail = optionChannelType.optionChannelValues.filter(item =>
value.reduce((acc, valueItem) => acc || (item.value === valueItem
&& item.optionChannelValueProperties.length > 0), 0));
}
console.log('value', value);
for (let j = 0; j < value.length; j += 1) {
if (j > 0) {
stringCheck += '||';
stringCheckGlobal += '&&';
}
switch (type) {
case 'isVariable': {
if (globalVariableName !== '') { // eslint-disable-line no-eval
if (a(`typeof (${globalVariableName}) !== 'undefined'`)) {
stringCheck += (term.checkPathLogic(value[j], 'Site:Pageurl', globalVariableName, comparison));
stringCheckGlobal += this.checkGlobalFilter('variable', value[j]);
console.log('checkChannel', type, term.getPath2Check('Site:Pageurl', globalVariableName), comparison, value[j]);
} else {
stringCheck += false;
}
} else {
stringCheck += (term.checkPathLogic(value[j], 'Site:Pageurl', '', comparison));
stringCheckGlobal += this.checkGlobalFilter('variable', value[j]);
// console.log('checkChannel', type, term.getPath2Check('Site:Pageurl', ''),
// comparison, value[j]);
// switch (comparison) {
// case '==': {
// stringCheck += false;
// break;
// }
// case '!=': {
// stringCheck += true;
// break;
// }
// default: {
// stringCheck += false;
// break;
// }
// }
}
console.log('stringCheckVariable', stringCheck, stringCheckGlobal, this.id);
break;
}
case 'isInputLink': {
stringCheck += (term.checkPathLogic(value[j], 'Site:Pageurl', '', comparison));
stringCheckGlobal += this.checkGlobalFilter('url', value[j]);
console.log('checkChannel', type, term.getPath2Check('Site:Pageurl', ''), comparison, value[j]);
console.log('stringCheckUrl', stringCheck, stringCheckGlobal);
break;
}
case 'isSelectOption': {
console.log('checkBrowser0', options[i].name);
if (options[i].name !== 'Browser' && options[i].name !== 'Location') {
const pageUrl = term.getPath2Check('Site:Pageurl', globalVariableName);
const thisChannel = util.getThisChannel(pageUrl);
thisChannel.shift();
// do smt with additionalDetail
if (additionalDetail.length > 0) {
// region : get link detail
if (typeof (globalVariable) !== 'undefined' && globalVariable !== '') {
a(`${globalVariableName} = ''`);
}
currentAdditionalDetail = util.getThisChannel(pageUrl).pop();
currentAdditionalDetail.shift();
if (typeof (globalVariable) !== 'undefined' && globalVariable !== '') {
a(`${globalVariableName} = globalVariableTemp`);
}
// endregion : get link detail
console.log('additionalDetail', additionalDetail, currentAdditionalDetail);
}
console.log('checkChannel', type, thisChannel[0], comparison, value[j]);
switch (comparison) {
case '==': {
stringCheck += (value[j] === thisChannel[0]);
break;
}
case '!=': {
stringCheck += (value[j] !== thisChannel[0]);
break;
}
default: {
stringCheck += false;
break;
}
}
} else if (options[i].name === 'Browser') {
console.log('checkBrowser1');
const checkBrowser = util.checkBrowser(value[j]);
switch (comparison) {
case '==': {
stringCheck += checkBrowser;
break;
}
case '!=': {
stringCheck += (checkBrowser !== true);
break;
}
default: {
stringCheck += false;
break;
}
}
console.log('checkBrowser', stringCheck, comparison);
}
break;
}
default: {
stringCheck += false;
stringCheckGlobal += true;
break;
}
}
}
const CheckValue = a(stringCheck);
const checkValueGlobal = a(stringCheckGlobal);
console.log('stringCheckGlobal', stringCheckGlobal);
if (i > 0) strChk += logical;
if (i > 0) strCheckGlobal += '&&';
strChk += CheckValue;
strCheckGlobal += checkValueGlobal;
}
} else {
strChk += 'true';
strCheckGlobal += 'true';
}
console.log('strChk', strChk, strCheckGlobal, strChk.match(/&&+(true|false)*/ig));
// const andValue = strChk.match(/&&+(true|false)*/ig);
// if (andValue !== null && andValue.length > 0) {
// andValue.reduce((acc, item) => { strChk = strChk.replace(item, '') }, 0); // eslint-disable-line
// const orValue = a(strChk);
// let res = `${orValue}`;
// res = andValue.reduce((acc, item, index) => index === 0 ? eval(`${res}${item}`) : (`${acc}${item}`), 0); // eslint-disable-line
// return res;
// }
return { check: a(strChk), checkGlobal: a(strCheckGlobal) };
}
return true;
};
let stringCheckTotal = '';
let stringCheckTotalGlobal = '';
for (let i = 0; i < checkLength; i += 1) {
let stringCheck = '';
let stringCheckGlobal = '';
const logical = optionBanner[i].logical === 'and' ? '&&' : '||';
const type = optionBanner[i].type;
const comparison = optionBanner[i].comparison;
const value = optionBanner[i].value;
console.log('BigType', type);
switch (type) {
case 'pageUrl' : {
stringCheck += term.checkPathLogic(value, 'Site:Pageurl', '', comparison);
stringCheckGlobal += this.checkGlobalFilter('url', value);
console.log('BigStringCheck', stringCheck, stringCheckGlobal);
break;
}
case 'channel' : {
const optionBannerChannels = optionBanner[i].optionBannerChannels;
let stringCheckChannelType = '';
let stringCheckChannelGlobal = '';
for (let j = 0; j < optionBannerChannels.length; j += 1) {
const channel = optionBannerChannels[j].channel;
const check = checkChannel(channel);
const result = check.check;
const resultGlobal = check.checkGlobal;
// const comparisonChar = comparison === '==' ? '||' : '&&';
console.log('resultChannel', result, resultGlobal, channel, comparison);
if (comparison === '==') {
stringCheckChannelType += (j > 0 ? '||' : '') + result;
} else {
stringCheckChannelType += (j > 0 ? '&&' : '') + result;
}
stringCheckChannelGlobal += (j > 0 ? '&&' : '') + resultGlobal;
}
console.log('stringCheckChannelType', stringCheckChannelType, stringCheckChannelGlobal);
const resultCheckChannel = eval(stringCheckChannelType); // eslint-disable-line
const resultCheckChannelGlobal = eval(stringCheckChannelGlobal); // eslint-disable-line
stringCheck += resultCheckChannel;
stringCheckGlobal += resultCheckChannelGlobal;
break;
}
case 'referringPage' : {
stringCheck += term.checkPathLogic(value, 'Site:Pageurl', '', comparison);
stringCheckGlobal += this.checkGlobalFilter('url', value);
break;
}
default: {
stringCheck += false;
break;
}
}
console.log('stringCheck', stringCheck, stringCheckGlobal, logical, i);
const checkValue = eval(stringCheck); // eslint-disable-line
const checkValueGlobal = eval(stringCheckGlobal); // eslint-disable-line
// if (i === 0 && logical === '||') {
// if (checkValue) {
// stringCheckTotal += checkValue;
// break;
// }
// }
if (i > 0) {
stringCheckTotal += logical;
stringCheckTotalGlobal += '&&';
}
stringCheckTotal += checkValue;
stringCheckTotalGlobal += checkValueGlobal;
}
console.log('stringCheckTotal', stringCheckTotal, stringCheckTotalGlobal);
// const andValue = stringCheckTotal.match(/&&+(true|false)*/ig);
// if (andValue !== null && andValue.length > 0) {
// andValue.reduce((acc, item) => { stringCheckTotal = stringCheckTotal.replace(item, '') }, 0); // eslint-disable-line
// const orValue = eval(stringCheckTotal); // eslint-disable-line
// let res = `${orValue}`;
// res = andValue.reduce((acc, item, index) => index === 0 ? eval(`${res}${item}`) : (`${acc}${item}`), 0); // eslint-disable-line
// return res;
// }
return { check: eval(stringCheckTotal), checkGlobal: eval(stringCheckTotalGlobal) }; // eslint-disable-line
}
return { check: true, checkGlobal: true };
}
// get CheckLocation() {
// let location = this.location;
// location = (typeof (location) === 'undefined' ||
// location === 'undefined' ||
// location == null ||
// location === '') ? 0 : location;
// location = `,${location},`;
// const strlocation = `,${window.ADSData.ADSLocation},`;
// const strcity = `,${window.ADSData.ADSCity},`;
// const strcitymain = `,${window.ADSData.ADSCityMain},`;
// const regBool = /,[1|2|3],[1|2|3],[1|2|3],/g;
// return (!!((location === ',,') ||
// (regBool.test(location)) ||
// (location === ',0,') ||
// ((`${location}`).indexOf(strcity) !== -1) ||
// ((`${location}`).indexOf(strcitymain) !== -1) ||
// ((`${location}`).indexOf(strlocation) !== -1)));
// }
// check Location with new data (using)
get checkLocation() {
let location = this.getLocation;
if (location !== undefined && location !== 0) {
location = (typeof (location) === 'undefined' ||
location === undefined || location == null) ? 0 : location;
const strlocation = `${util.convertLocation(window.ADSData.ADSLocation).R}`;
const strcity = `${util.convertLocation(window.ADSData.ADSCity).RC}`;
const strcitymain = `${util.convertLocation(window.ADSData.ADSCityMain).RC}`;
console.log(`Check Location ${strcity} isBelongTo ${location.location}`);
return (!!((location === '0') ||
((`${location.location}`).indexOf(strcity) !== -1 && location.comparison === '==') ||
((`${location.location}`).indexOf(strcitymain) !== -1 && location.comparison === '==') ||
((`${location.location}`).indexOf(strlocation) !== -1 && location.comparison === '==')));
}
return true;
}
// get location from channel's options
get getLocation() {
if (this.channel !== undefined && this.channel !== null && this.channel !== '') {
// console.log('getLocation run');
const onLocations = this.channel.options.filter(item => item.name === 'Location' && item.comparison === '==');
const exceptLocation = this.channel.options.filter(item => item.name === 'Location' && item.comparison === '!=');
if (onLocations.length > 0) {
return {
location: onLocations.reduce((acc, item, index) => (index > 0 ? `${acc},` : '') + item.value, 0),
comparison: '==',
};
}
return {
location: exceptLocation.reduce((acc, item, index) => (index > 0 ? `${acc},` : '') + item.value, 0),
comparison: '!=',
};
}
return 0;
}
get checkFrequency() {
let fr = this.fr;
const count = this.getFrequency();
if (fr === '' || fr === 'undefined' || fr === undefined) {
return true;
}
fr = parseInt(fr, 10);
if (count > fr) {
console.log(`${this.id}: `, this.getFrequency());
return false;
}
return true;
}
countFrequency() {
const domain = term.getCurrentDomain('Site:Pageurl');
const bannerID = this.id;
let cookie = adsStorage.getStorage('_fr');
const checkCookie = adsStorage.subCookie(cookie, 'Ver:', 0);
if (checkCookie === '') {
cookie = 'Ver:25;';
}
adsStorage.setStorage('_fr', cookie, '', '/', domain);
if (`${cookie}`.indexOf(bannerID) !== -1) {
const FrequencyStr = adsStorage.subCookie(cookie, `${bannerID}:`, 0).toString();
const currentCount = this.getFrequency();
if (window.arfBanners[bannerID] && bannerID !== 'banner-undefined') {
cookie = `${cookie}`.replace(FrequencyStr, `${bannerID}:${currentCount + 1}`);
// console.log(`${bannerID}:${currentCount + 1}`);
}
} else {
cookie = bannerID === 'banner-undefined' ? cookie : `${cookie};${bannerID}:1;`;
console.log(adsStorage.subCookie(cookie, `${bannerID}:`, 0).toString());
}
adsStorage.setStorage('_fr', cookie, '', '/', domain);
}
getFrequency() {
const cookie = adsStorage.getStorage('_fr');
if (cookie !== '') {
const bannerID = this.id;
const a = adsStorage.subCookie(cookie, `${bannerID}:`, 0).toString();
const currentCount = parseInt(a.slice(a.indexOf(':') + 1), 10);
console.log(`${this.id}: ${currentCount}`);
return currentCount;
}
return '';
}
bannerLogging(cov) {
// cov=0 OR cov=-1: view placement, banner.
// cov=1: click
// cov=2: true view
// cov=3: load box when using rotate.
const zoneID = this.zoneId.indexOf('zone-') !== -1 ? this.zoneId.replace('zone-', '') : this.zoneId;
const bannerId = this.id.indexOf('banner-') !== -1 ? this.id.replace('banner-', '') : this.id;
const placementId = this.placementId.indexOf('placement-') !== -1 ? this.placementId.replace('placement-', '') : this.placementId;
const domain = encodeURIComponent(term.getCurrentDomain('Site:Pageurl'));
const campaignID = this.campaignId;
console.log('campaignId', campaignID);
const domainLog = 'http://lg1.logging.admicro.vn';
const linkLog = `${domainLog}/cpx_cms?dmn=${domain}&zid=${zoneID}&pli=${placementId}&cmpg=${campaignID}&items=${bannerId}&cov=${cov}`;
console.log('BannerLog', linkLog);
const img = new Image();
img.src = linkLog;
}
}
export default Banner;
|
const mongoose = require('mongoose');
const archiveSchema = new mongoose.Schema({
email: String,
codmateria: Number,
materia: String,
codigo: String,
semestre: String,
paralelo: String,
docente: String,
item01: String,
item02: String,
item03: String,
item04: String,
item05: String,
item06: String,
item07: String,
item08: String,
item09: String,
item10: String,
item11: String,
item12: String,
item13: String,
item14: String,
item15: String,
status: String
});
const Archive = mongoose.model('Syllabu', archiveSchema);
module.exports = Archive;
|
module.exports = require("./lib/pn532-spi.min")
|
function isitArrays(a, b)
{
var isit = false;
for(var i = 0; i < a.length; i++)
{
if($.inArray(a[i], b) != -1)
{
isit = true;
}
}
return isit;
}
function focusField(obj)
{
obj.addClass("unFocus");
obj.focus(function()
{
$(this).toggleClass("unFocus").toggleClass("Focus");
if (this.value == this.defaultValue)
{
this.value = '';
}
if(this.value != this.defaultValue)
{
this.select();
}
});
obj.blur(function()
{
$(this).toggleClass("unFocus").toggleClass("Focus");
if ($.trim(this.value) == '')
{
this.value = (this.defaultValue ? this.defaultValue : '');
}
});
}
function ImageLoadFailed(image, src)
{
image.onerror = "";
image.src = src;
return true;
}
function writeHash(a)
{
var temp = '#?';
for(var i = 0; i < a.length; i++)
{
if(a[i] != undefined && a[i] != '')
{
temp += a[i];
if( i < a.length - 1 )
{
temp += '&';
}
}
}
window.location.hash = temp;
}
function json( $url )
{
var feed = null;
$.ajax({
'async': false,
'global': false,
'url': $url,
'dataType': "json",
'success': function (data)
{
feed = data;
}
});
return feed;
};
window.alert = function (message)
{
var prompt = $(document.createElement('div')).addClass('prompt').html( '<p>' + message + '</p>' ).appendTo( $('body') );
var newY = prompt.prev().outerHeight() + prompt.prev().position().top + 10;
prompt.css({'opacity': 0, 'position':'fixed','top':newY, 'right':50,'z-index':1000}).animate({opacity:1},150);
setTimeout(function(){ toRemove(prompt); },2000);
function toRemove( obj )
{
obj.next().animate({top:obj.position().top},350);
obj.animate({opacity:0}, 350, function(){ obj.remove(); });
}
};
function trace( t )
{
if(typeof console === "undefined") {
console = { log: function()
{
alert(t);
}
};
}
console.log(t);
}
// Custom Event. Back pocket shit. Please leave it here.
$( window ).on( "custom", function( event, param1, param2 )
{
trace( param1 + "\n" + param2 );
}).trigger( "custom", [ "Pop", "PoP" ] );
|
'use strict';
var React = require('react');
var SvgIcon = require('../../svg-icon');
var EditorModeComment = React.createClass({
displayName: 'EditorModeComment',
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: "M21.99 4c0-1.1-.89-2-1.99-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4-.01-18z" })
);
}
});
module.exports = EditorModeComment;
|
/**
* get-tweets.js
* http://github.com/kevindeleon/get-tweets
*
* Copyright 2013, Kevin deLeon
* Licensed under the MIT license.
* http://github.com/kevindeleon/get-tweets/blob/master/LICENSE
*
* Much of this logic was derrived from blogger.js from Twitter and converted to jQuery
* The releative_time function was take directly from Twitter's blogger.js
*
* Author: Kevin deLeon (http://github.com/kevindeleon)
*/
// Receives JSON object returned by get_most_recent from get-tweets.php
function display_tweets(tweets) {
var statusHTML = "";
jQuery.each(tweets, function(i, tweet) {
//let's check to make sure we actually have a tweet
if (tweet.text !== undefined) {
var username = tweet.user.screen_name;
//let's grab the tweet, and do some housekeeping to display it properly
var status = tweet.text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
return '<a href="'+url+'">'+url+'</a>';
}).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
return reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
});
statusHTML = '<p><span>'+status+'</span> <a style="font-size:85%" href="http://twitter.com/'+username+'/statuses/'+tweet.id_str+'">'+relative_time(tweet.created_at)+'</a></p>';
//remove the loader
jQuery('.tweet-loader').remove();
//display tweet(s)
jQuery('#twitter_update_list').append(statusHTML);
}
});
}
// taken from Twitter's blogger.js
// Makes our "x time ago" data prettier for display
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
if (delta < 60) {
return 'less than a minute ago';
} else if(delta < 120) {
return 'about a minute ago';
} else if(delta < (60*60)) {
return (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (120*60)) {
return 'about an hour ago';
} else if(delta < (24*60*60)) {
return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
return '1 day ago';
} else {
return (parseInt(delta / 86400)).toString() + ' days ago';
}
}
|
import React from 'react';
import {SelectButton} from './SelectButton';
import {ConditionalSelectButton} from './ConditionalSelectButton';
import {ApiButton} from './ApiButton';
import {DownloadButton} from './DownloadButton';
import {SliderInput} from './SliderInput';
import {DynamicSearchInput} from './DynamicSearchInput';
import {CheckboxGroup} from './CheckboxGroup';
var FilterFactory = function(type) {
if (typeof FilterFactory[type] != 'function'){
throw new Error(type + ' is not a valid filter.');
}
return FilterFactory[type];
};
FilterFactory.SliderInput = SliderInput;
FilterFactory.SelectButton = SelectButton;
FilterFactory.ConditionalSelectButton = ConditionalSelectButton;
FilterFactory.ApiButton = ApiButton;
FilterFactory.DownloadButton = DownloadButton;
FilterFactory.DynamicSearch = DynamicSearchInput;
FilterFactory.CheckboxGroup = CheckboxGroup;
export class Filter extends React.Component {
constructor(props) {
super(props);
}
render() {
var Z = FilterFactory(this.props.type);
return (
<Z
ref={"filter"}
id={this.props.id}
dynamic={this.props.dynamic}
onChange={this.props.onChange}
options={this.props.options} />
);
}
}
export {FilterFactory};
|
/**
* @file WebGLMath Mat4Array class
* @copyright Laszlo Szecsi 2017
*/
/**
* @class Mat4Array
* @classdesc Array of four by four matrices of 32-bit floats. May reflect an ESSL array-of-mat4s uniform variable.
* <BR> Individual [Mat4]{@link Mat4} elements are available through the index operator [].
* @param {Number} size - The number of Mat4 elements in the array.
* @constructor
*/
var Mat4Array = function(size){
this.length = size;
this.storage = new Float32Array(size * 16);
for(var i=0; i<size; i++){
var proxy = Object.create(Mat4.prototype);
proxy.storage = this.storage.subarray(i*16, (i+1)*16);
Object.defineProperty(this, i, {value: proxy} );
}
};
/**
* @method subarray
* @memberof Mat4Array.prototype
* @description Returns a new Mat4Array object that captures a subrange of the array. The new array is a view on the original data, not a copy.
* @param {Number} [begin=0] - Element to begin at. The offset is inclusive. The whole array will be cloned if this value is not specified.
* @param {Number} [end=length] - Element to end at. The offset is exclusive. If not specified, all elements from the one specified by begin to the end of the array are included in the new view.
* @return {Mat4Array} new view on some of the array's elements
*/
Mat4Array.prototype.subarray = function(begin, end){
var result = Object.create(Mat4Array.prototype);
result.storage = this.storage.subarray(begin*16, end*16);
return result;
};
/**
* @method commit
* @memberof Mat4Array.prototype
* @description Sets the value of the matrix array to a WebGL mat4 array uniform variable.
* @param {WebGLRenderingContext} gl - rendering context
* @param {WebGLUniformLocation} uniformLocation - location of the uniform variable in the currently used WebGL program
*/
Mat4Array.prototype.commit = function(gl, uniformLocation){
gl.uniformMatrix4fv(uniformLocation, false, this.storage);
};
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {Response} from './ReactFlightClientHostConfigStream';
import {
resolveModule,
resolveModel,
resolveProvider,
resolveSymbol,
resolveError,
createResponse as createResponseBase,
parseModelString,
parseModelTuple,
} from './ReactFlightClient';
import {
readPartialStringChunk,
readFinalStringChunk,
supportsBinaryStreams,
createStringDecoder,
} from './ReactFlightClientHostConfig';
export type {Response};
function processFullRow(response: Response, row: string): void {
if (row === '') {
return;
}
const tag = row[0];
// When tags that are not text are added, check them here before
// parsing the row as text.
// switch (tag) {
// }
const colon = row.indexOf(':', 1);
const id = parseInt(row.substring(1, colon), 16);
const text = row.substring(colon + 1);
switch (tag) {
case 'J': {
resolveModel(response, id, text);
return;
}
case 'M': {
resolveModule(response, id, text);
return;
}
case 'P': {
resolveProvider(response, id, text);
return;
}
case 'S': {
resolveSymbol(response, id, JSON.parse(text));
return;
}
case 'E': {
const errorInfo = JSON.parse(text);
resolveError(response, id, errorInfo.message, errorInfo.stack);
return;
}
default: {
throw new Error(
"Error parsing the data. It's probably an error code or network corruption.",
);
}
}
}
export function processStringChunk(
response: Response,
chunk: string,
offset: number,
): void {
let linebreak = chunk.indexOf('\n', offset);
while (linebreak > -1) {
const fullrow = response._partialRow + chunk.substring(offset, linebreak);
processFullRow(response, fullrow);
response._partialRow = '';
offset = linebreak + 1;
linebreak = chunk.indexOf('\n', offset);
}
response._partialRow += chunk.substring(offset);
}
export function processBinaryChunk(
response: Response,
chunk: Uint8Array,
): void {
if (!supportsBinaryStreams) {
throw new Error("This environment don't support binary chunks.");
}
const stringDecoder = response._stringDecoder;
let linebreak = chunk.indexOf(10); // newline
while (linebreak > -1) {
const fullrow =
response._partialRow +
readFinalStringChunk(stringDecoder, chunk.subarray(0, linebreak));
processFullRow(response, fullrow);
response._partialRow = '';
chunk = chunk.subarray(linebreak + 1);
linebreak = chunk.indexOf(10); // newline
}
response._partialRow += readPartialStringChunk(stringDecoder, chunk);
}
function createFromJSONCallback(response: Response) {
return function(key: string, value: JSONValue) {
if (typeof value === 'string') {
// We can't use .bind here because we need the "this" value.
return parseModelString(response, this, value);
}
if (typeof value === 'object' && value !== null) {
return parseModelTuple(response, value);
}
return value;
};
}
export function createResponse(): Response {
// NOTE: CHECK THE COMPILER OUTPUT EACH TIME YOU CHANGE THIS.
// It should be inlined to one object literal but minor changes can break it.
const stringDecoder = supportsBinaryStreams ? createStringDecoder() : null;
const response: any = createResponseBase();
response._partialRow = '';
if (supportsBinaryStreams) {
response._stringDecoder = stringDecoder;
}
// Don't inline this call because it causes closure to outline the call above.
response._fromJSON = createFromJSONCallback(response);
return response;
}
export {reportGlobalError, close} from './ReactFlightClient';
|
const Storage = require('./storage');
let storage;
/**
* Handle every persistence-related task
* The interface Datastore expects to be implemented is
* * Persistence.loadDatabase(callback) and callback has signature err
* * Persistence.persistNewState(newDocs, callback) where newDocs is an array of documents and callback has signature err
*/
var path = {
join: function(...args) {
return args.join('_');
},
},
model = require('./model'),
async = require('async'),
customUtils = require('./customUtils'),
Index = require('./indexes');
/**
* Create a new Persistence object for database options.db
* @param {Datastore} options.db
* @param {Boolean} options.nodeWebkitAppName Optional, specify the name of your NW app if you want options.filename to be relative to the directory where
* Node Webkit stores application data such as cookies and local storage (the best place to store data in my opinion)
*/
function Persistence(options) {
var i, j, randomString;
this.db = options.db;
this.inMemoryOnly = this.db.inMemoryOnly;
this.filename = this.db.filename;
this.corruptAlertThreshold =
options.corruptAlertThreshold !== undefined ? options.corruptAlertThreshold : 0.1;
storage = new Storage(this.db.storage);
if (
!this.inMemoryOnly &&
this.filename &&
this.filename.charAt(this.filename.length - 1) === '~'
) {
throw new Error(
"The datafile name can't end with a ~, which is reserved for crash safe backup files",
);
}
// After serialization and before deserialization hooks with some basic sanity checks
if (options.afterSerialization && !options.beforeDeserialization) {
throw new Error(
'Serialization hook defined but deserialization hook undefined, cautiously refusing to start NeDB to prevent dataloss',
);
}
if (!options.afterSerialization && options.beforeDeserialization) {
throw new Error(
'Serialization hook undefined but deserialization hook defined, cautiously refusing to start NeDB to prevent dataloss',
);
}
this.afterSerialization =
options.afterSerialization ||
function(s) {
return s;
};
this.beforeDeserialization =
options.beforeDeserialization ||
function(s) {
return s;
};
for (i = 1; i < 30; i += 1) {
for (j = 0; j < 10; j += 1) {
randomString = customUtils.uid(i);
if (this.beforeDeserialization(this.afterSerialization(randomString)) !== randomString) {
throw new Error(
'beforeDeserialization is not the reverse of afterSerialization, cautiously refusing to start NeDB to prevent dataloss',
);
}
}
}
// For NW apps, store data in the same directory where NW stores application data
if (this.filename && options.nodeWebkitAppName) {
console.log('==================================================================');
console.log('WARNING: The nodeWebkitAppName option is deprecated');
console.log('To get the path to the directory where Node Webkit stores the data');
console.log('for your app, use the internal nw.gui module like this');
//for some reason, react native was trying to run the "require" code that is inside the console.log...
console.log("require('nw.gui').App.dataPath");
console.log('See https://github.com/rogerwang/node-webkit/issues/500');
console.log('==================================================================');
this.filename = Persistence.getNWAppFilename(options.nodeWebkitAppName, this.filename);
}
}
/**
* Check if a directory exists and create it on the fly if it is not the case
* cb is optional, signature: err
*/
Persistence.ensureDirectoryExists = function(dir, cb) {
var callback = cb || function() {};
storage.mkdirp(dir, function(err) {
return callback(err);
});
};
/**
* Return the path the datafile if the given filename is relative to the directory where Node Webkit stores
* data for this application. Probably the best place to store data
*/
Persistence.getNWAppFilename = function(appName, relativeFilename) {
var home;
switch (process.platform) {
case 'win32':
case 'win64':
home = process.env.LOCALAPPDATA || process.env.APPDATA;
if (!home) {
throw new Error("Couldn't find the base application data folder");
}
home = path.join(home, appName);
break;
case 'darwin':
home = process.env.HOME;
if (!home) {
throw new Error("Couldn't find the base application data directory");
}
home = path.join(home, 'Library', 'Application Support', appName);
break;
case 'linux':
home = process.env.HOME;
if (!home) {
throw new Error("Couldn't find the base application data directory");
}
home = path.join(home, '.config', appName);
break;
default:
throw new Error("Can't use the Node Webkit relative path for platform " + process.platform);
break;
}
return path.join(home, 'nedb-data', relativeFilename);
};
/**
* Persist cached database
* This serves as a compaction function since the cache always contains only the number of documents in the collection
* while the data file is append-only so it may grow larger
* @param {Function} cb Optional callback, signature: err
*/
Persistence.prototype.persistCachedDatabase = function(cb) {
var callback = cb || function() {},
toPersist = '',
self = this;
if (this.inMemoryOnly) {
return callback(null);
}
this.db.getAllData().forEach(function(doc) {
toPersist += self.afterSerialization(model.serialize(doc)) + '\n';
});
Object.keys(this.db.indexes).forEach(function(fieldName) {
if (fieldName != '_id') {
// The special _id index is managed by datastore.js, the others need to be persisted
toPersist +=
self.afterSerialization(
model.serialize({
$$indexCreated: {
fieldName: fieldName,
unique: self.db.indexes[fieldName].unique,
sparse: self.db.indexes[fieldName].sparse,
},
}),
) + '\n';
}
});
storage.crashSafeWriteFile(this.filename, toPersist, function(err) {
if (err) {
return callback(err);
}
self.db.emit('compaction.done');
return callback(null);
});
};
/**
* Queue a rewrite of the datafile
*/
Persistence.prototype.compactDatafile = function() {
this.db.executor.push({ this: this, fn: this.persistCachedDatabase, arguments: [] });
};
/**
* Set automatic compaction every interval ms
* @param {Number} interval in milliseconds, with an enforced minimum of 5 seconds
*/
Persistence.prototype.setAutocompactionInterval = function(interval) {
var self = this,
minInterval = 5000,
realInterval = Math.max(interval || 0, minInterval);
this.stopAutocompaction();
this.autocompactionIntervalId = setInterval(function() {
self.compactDatafile();
}, realInterval);
};
/**
* Stop autocompaction (do nothing if autocompaction was not running)
*/
Persistence.prototype.stopAutocompaction = function() {
if (this.autocompactionIntervalId) {
clearInterval(this.autocompactionIntervalId);
}
};
/**
* Persist new state for the given newDocs (can be insertion, update or removal)
* Use an append-only format
* @param {Array} newDocs Can be empty if no doc was updated/removed
* @param {Function} cb Optional, signature: err
*/
Persistence.prototype.persistNewState = function(newDocs, cb) {
var self = this,
toPersist = '',
callback = cb || function() {};
// In-memory only datastore
if (self.inMemoryOnly) {
return callback(null);
}
newDocs.forEach(function(doc) {
toPersist += self.afterSerialization(model.serialize(doc)) + '\n';
});
if (toPersist.length === 0) {
return callback(null);
}
storage.appendFile(self.filename, toPersist, 'utf8', function(err) {
return callback(err);
});
};
/**
* From a database's raw data, return the corresponding
* machine understandable collection
*/
Persistence.prototype.treatRawData = function(rawData) {
var data = rawData.split('\n'),
dataById = {},
tdata = [],
i,
indexes = {},
corruptItems = -1; // Last line of every data file is usually blank so not really corrupt
for (i = 0; i < data.length; i += 1) {
var doc;
try {
doc = model.deserialize(this.beforeDeserialization(data[i]));
if (doc._id) {
if (doc.$$deleted === true) {
delete dataById[doc._id];
} else {
dataById[doc._id] = doc;
}
} else if (doc.$$indexCreated && doc.$$indexCreated.fieldName != undefined) {
indexes[doc.$$indexCreated.fieldName] = doc.$$indexCreated;
} else if (typeof doc.$$indexRemoved === 'string') {
delete indexes[doc.$$indexRemoved];
}
} catch (e) {
corruptItems += 1;
}
}
// A bit lenient on corruption
if (data.length > 0 && corruptItems / data.length > this.corruptAlertThreshold) {
throw new Error(
'More than ' +
Math.floor(100 * this.corruptAlertThreshold) +
'% of the data file is corrupt, the wrong beforeDeserialization hook may be used. Cautiously refusing to start NeDB to prevent dataloss',
);
}
Object.keys(dataById).forEach(function(k) {
tdata.push(dataById[k]);
});
return { data: tdata, indexes: indexes };
};
/**
* Load the database
* 1) Create all indexes
* 2) Insert all data
* 3) Compact the database
* This means pulling data out of the data file or creating it if it doesn't exist
* Also, all data is persisted right away, which has the effect of compacting the database file
* This operation is very quick at startup for a big collection (60ms for ~10k docs)
* @param {Function} cb Optional callback, signature: err
*/
Persistence.prototype.loadDatabase = function(cb) {
var callback = cb || function() {},
self = this;
self.db.resetIndexes();
// In-memory only datastore
if (self.inMemoryOnly) {
return callback(null);
}
async.waterfall(
[
function(cb) {
Persistence.ensureDirectoryExists(self.filename, function(err) {
storage.ensureDatafileIntegrity(self.filename, function(err) {
storage.readFile(self.filename, 'utf8', function(err, rawData) {
if (err) {
return cb(err);
}
try {
var treatedData = self.treatRawData(rawData);
} catch (e) {
return cb(e);
}
// Recreate all indexes in the datafile
Object.keys(treatedData.indexes).forEach(function(key) {
self.db.indexes[key] = new Index(treatedData.indexes[key]);
});
// Fill cached database (i.e. all indexes) with data
try {
self.db.resetIndexes(treatedData.data);
} catch (e) {
self.db.resetIndexes(); // Rollback any index which didn't fail
return cb(e);
}
self.db.persistence.persistCachedDatabase(cb);
});
});
});
},
],
function(err) {
if (err) {
return callback(err);
}
self.db.executor.processBuffer();
return callback(null);
},
);
};
// Interface
module.exports = Persistence;
|
/*
---
name: SubtleLocationProxy
description: |
SubtleLocationProxy will proxy the location of one frame to the hash of another and vice-versa.
It's handy for sites that simply wrap a fancy UI around simple HTML pages.
authors: Thomas Aylott <oblivious@subtlegradient.com>
copyright: © 2010 Thomas Aylott
license: MIT
provides: SubtleLocationProxy
# requires: document.querySelector || $$ || $
...
*/
function SubtleLocationProxy() { /*! Copyright © 2010 Thomas Aylott <oblivious@subtlegradient.com> MIT License*/ }
;
(function(SubtleLocationProxy) {
var has_iframe_onreadystatechange = typeof document.createElement('iframe').onreadystatechange != 'undefined'
,
location = window.location
,
ID = SubtleLocationProxy.ID = +new Date
SubtleLocationProxy.setLocation = setLocation
function setLocation(newLocation) {
if (typeof newLocation == 'string') newLocation = convertStringToLocation(newLocation)
newLocation = newLocation.pathname + newLocation.search + newLocation.hash
if (SubtleLocationProxy.getLocation() == newLocation) return
ignoreHashChange = true
location.replace(('' + location).split('#')[0] + '#' + newLocation)
}
SubtleLocationProxy.getLocation = getLocation
function getLocation() {
// When location is "foo.com/#/bar?baz"
// In IE6 location.hash == '#/bar' && location.search == '?baz' in IE6
var loc = ('' + location).split('#')
loc.splice(0, 1)
return decodeURIComponent(loc.join('#'))
}
SubtleLocationProxy.setProxy = setProxy
function setProxy(element) {
if (!element) return
ignoreLocationChanges()
SubtleLocationProxy.proxyElement = element
listenForLocationChanges()
setProxyLocation(SubtleLocationProxy.getLocation())
}
SubtleLocationProxy.setProxyLocation
function setProxyLocation(location) {
if (!location) return
var proxyElement = SubtleLocationProxy.proxyElement
if ('' + convertStringToLocation(location) != '' + convertStringToLocation(proxyElement.contentWindow.location))
proxyElement.contentWindow.location.replace(location)
}
SubtleLocationProxy.toLocation = convertStringToLocation
var locationObject = document.createElement('a')
function convertStringToLocation(locationString) {
locationObject.href = '' + locationString
return locationObject
}
var listenForLocationChanges_interval
function listenForLocationChanges() {
var proxyElement = SubtleLocationProxy.proxyElement
if (proxyElement.addEventListener) proxyElement.addEventListener('load', handleProxyUrlChange, false)
else if (proxyElement.attachEvent) proxyElement.attachEvent('onload', handleProxyUrlChange)
if (has_iframe_onreadystatechange) {
if (proxyElement.addEventListener) proxyElement.addEventListener('readystatechange', handleProxyUrlChange, false)
else if (proxyElement.attachEvent) proxyElement.attachEvent('onreadystatechange', handleProxyUrlChange)
} else {
proxyElement.contentWindow._SlPiD = SubtleLocationProxy.ID
clearInterval(listenForLocationChanges_interval)
listenForLocationChanges_interval = setInterval(function() {
var id
try {
id = proxyElement.contentWindow._SlPiD
} catch (e) {
clearInterval(listenForLocationChanges_interval)
}
if (id != ID) handleProxyUrlChange({
target: proxyElement /*, type:'poll'*/
})
}, 250)
}
}
function ignoreLocationChanges() {
var proxyElement = SubtleLocationProxy.proxyElement
if (!proxyElement) return
if (proxyElement.removeEventListener) proxyElement.removeEventListener('load', handleProxyUrlChange, false)
else if (proxyElement.detachEvent) proxyElement.detachEvent('onload', handleProxyUrlChange)
if (has_iframe_onreadystatechange) {
if (proxyElement.removeEventListener) proxyElement.removeEventListener('readystatechange', handleProxyUrlChange, false)
else if (proxyElement.detachEvent) proxyElement.detachEvent('onreadystatechange', handleProxyUrlChange)
}
clearInterval(listenForLocationChanges_interval)
var window = proxyElement.contentWindow
if (window.addEventListener) window.removeEventListener('hashchange', handleProxyHashChange, false)
else if (window.attachEvent) window.detachEvent('onhashchange', handleProxyHashChange)
}
function listenForHashchange(window, handler) {
if (window._SlPiDhc == ID) return
window._SlPiDhc = ID
if (window.addEventListener) window.addEventListener('hashchange', handler, false)
else if (window.attachEvent) window.attachEvent('onhashchange', handler)
}
function handleProxyUrlChange() {
var proxyElement = SubtleLocationProxy.proxyElement
if (proxyElement.contentWindow._SlPiD == ID) return
proxyElement.contentWindow._SlPiD = ID
SubtleLocationProxy.setLocation(proxyElement.contentWindow.location)
listenForHashchange(proxyElement.contentWindow, handleProxyHashChange)
}
function handleProxyHashChange() {
SubtleLocationProxy.setLocation(SubtleLocationProxy.proxyElement.contentWindow.location)
}
var ignoreHashChange
function handleMasterHashChange() {
if (ignoreHashChange) {
ignoreHashChange = false;
return
}
setProxyLocation(SubtleLocationProxy.getLocation())
}
// Setup the master page and default state
listenForHashchange(window, handleMasterHashChange)
setTimeout(function() {
SubtleLocationProxy.setProxy(window.SubtleLocationProxy_element)
var iframes = document.getElementsByTagName('iframe')
for (var i = -1, iframe; iframe = iframes[++i];) {
if (!iframe || iframe.getAttribute('data-history') != 'proxy') continue
SubtleLocationProxy.setProxy(iframe)
}
}, 100)
}(SubtleLocationProxy));
|
import module from "other";
if(typeof window !== "undefined" && window.assert) {
assert.ok(module, "got basics/module");
assert.equal(module, "bar", "module name is right");
done();
} else {
console.log("basics loaded", module);
}
|
import React from 'react';
import PropTypes from 'prop-types';
import getAttrs from '../util/getAttrs';
export default function Callout(props) {
return (
<table {...getAttrs(props, ['children'], 'callout')}>
<tr>
<th className="callout-inner">{props.children}</th>
<th className="expander"/>
</tr>
</table>
);
}
/**
* Prop types for `<Callout />`.
* @type Object
* @prop [children] - Child elements.
*/
Callout.propTypes = {
children: PropTypes.node
};
/**
* Default props for `<Callout />`.
* @type Object
*/
Callout.defaultProps = {
children: null
};
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M4 6h18V4H4c-1.1 0-2 .9-2 2v11H0v3h14v-3H4V6zm19 2h-6c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h6c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1zm-1 9h-4v-7h4v7z" /></g>
, 'Devices');
|
var KEY = {
UP: 38,
DOWN: 40,
W: 87,
S: 83
}
function listeningPaddles()
{
$(document).keydown(function(e){
switch(e.which){
case KEY.UP:
// get the current paddle B's top value in Int type
var top = parseInt($("#paddleB").css("top"));
// move the paddle B up 5 pixels
$("#paddleB").css("top",top-5);
break;
case KEY.DOWN:
// get the current paddle B's top value in Int type
var top = parseInt($("#paddleB").css("top"));
// move the paddle B down 5 pixels
$("#paddleB").css("top",top+5);
break;
case KEY.W:
// get the current paddle A's top value in Int type
var top = parseInt($("#paddleA").css("top"));
// move the paddle A up 5 pixels
$("#paddleA").css("top",top-5);
break;
case KEY.S:
// get the current paddle A's top value in Int type
var top = parseInt($("#paddleA").css("top"));
// move the paddle A down 5 pixels
$("#paddleA").css("top",top+5);
break;
}
});
}
function startPaddles()
{
$("#paddleB").css("top", "20px");
$("#paddleA").css("top", "60px");
}
$(function(){
//startPaddles();
listeningPaddles();
});
|
// Use this library to handle this libraries' errors
const selfErrors = require('./self');
// Repeat a character N times
const char = (ch = ' ', n = 0) => Array(n + 1).join(ch);
// Make a line of length >= width with filling spaces
// It cannot cut it because we risk breaking links or others
const line = (msg = '', width = 80) => {
if (/\n/g.test(msg)) {
return msg.split('\n').map(l => line(l, width)).join(' │\n│ ');
}
if (msg.length + 4 < width) {
return msg + char(' ', width - msg.length - 4);
}
return msg;
};
const buildError = ({ key, message = '', url, width, opts = {}, plain }) => {
// DISPLAY
message = message
.replace(/^\s+/, '') // Remove leading space from 1st line
.replace(/\s+$/, '') // Remove trailing space from last line
.replace(/^\ +/mg, '') // Remove leading indentation
.replace(/\ +$/mg, ''); // Remove trailing indentation
let errorUrl = false;
if (url) {
const realUrl = url instanceof Function ? url(key) : url;
if (plain) {
errorUrl = '\nMore info: ' + realUrl;
} else {
errorUrl = `
│ ${line(`Info: ${realUrl}`, width)} │
`.replace(/^\ +/mg, '');
}
}
if (plain) {
return new Error('\n' + `
Error: ${key}
Message: ${message}
Code: ${key}
URL: ${errorUrl ? errorUrl : ''}
Arguments: ${JSON.stringify(opts, null, 2)}
`.replace(/^\s+/mg, ''));
}
return new Error('\n' + `
┌${char('─', width - 2)}┐
│ ${line(key + ' Error', width)} │
├${char('─', width - 2)}┤
│ ${line(message, width)} │
├${char('─', width - 2)}┤
│ ${line('Code: ' + key, width)} │
${errorUrl ? errorUrl : ''}
│ ${line('Arguments: ' + JSON.stringify(opts, null, 2), width)} │
└${char('─', width - 2)}┘
`.replace(/^\s+/mg, ''));
};
const globalErrors = {};
const errorFactory = ({ url, width = 80, plain, extra = {} } = {}) => {
const errors = function (key, opts = {}){
let message = errors[key];
if (!message){
throw new Error(selfErrors.NotDefined({ name: key, available: Object.keys(errors) }));
}
if (message instanceof Function) {
message = message(opts);
}
// Extend the options with the defaults
for (let key in extra) {
if (!opts[key]) {
opts[key] = extra[key];
}
}
let error = new Error(buildError({ key, message, url, width, plain, opts }));
error.name = key;
for (let key in opts) {
error[key] = opts[key];
}
return error;
};
return errors;
}
module.exports = errorFactory;
module.exports.char = char;
module.exports.line = line;
|
/**
* marked - a markdown parser
* Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
* https://github.com/chjj/marked
*/
;
(function () {
/**
* Block-Level Grammar
*/
var block = {
newline: /^\n+/,
code: /^( {4}[^\n]+\n*)+/,
fences: noop,
hr: /^( *[-*_]){3,} *(?:\n+|$)/,
heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
nptable: noop,
lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
html: /^ *(?:comment|closed|closing) *(?:\n{2,}|\s*$)/,
def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
def_list: /^((\n*((.+\n)+): +.+[\n]{2}(:? +.+[\n]{2})*)+)/,
bibliography: /^ *\[\#\_(bibliography)\] *(?:\n+|$)/,
task: noop,
table: noop,
paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
text: /^[^\n]+/
};
block.bullet = /(?:[*+-]|\d+\.)/;
block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
block.item = replace(block.item, 'gm')
(/bull/g, block.bullet)
();
block.list = replace(block.list)
(/bull/g, block.bullet)
('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
('def', '\\n+(?=' + block.def.source + ')')
();
block.blockquote = replace(block.blockquote)
('def', block.def)
();
block._tag = '(?!(?:'
+ 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
+ '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
+ '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
block.html = replace(block.html)
('comment', /<!--[\s\S]*?-->/)
('closed', /<(tag)[\s\S]+?<\/\1>/)
('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
(/tag/g, block._tag)
();
block.paragraph = replace(block.paragraph)
('hr', block.hr)
('heading', block.heading)
('lheading', block.lheading)
('blockquote', block.blockquote)
('tag', '<' + block._tag)
('def', block.def)
();
/**
* Normal Block Grammar
*/
block.normal = merge({}, block);
/**
* GFM Block Grammar
*/
block.gfm = merge({}, block.normal, {
task: /^(\s*\[[x ]\][^\n]+\n)+\n*/,
fences: /^ *(`{3,}|~{3,}) *(\S+)? *\n([\s\S]+?)\s*\1 *(?:\n+|$)/,
paragraph: /^/
});
block.gfm.paragraph = replace(block.paragraph)
('(?!', '(?!'
+ block.gfm.fences.source.replace('\\1', '\\2') + '|'
+ block.list.source.replace('\\1', '\\3') + '|')
();
/**
* GFM + Tables Block Grammar
*/
block.tables = merge({}, block.gfm, {
nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)(\[.+\])?\n*/
});
/**
* Block Lexer
*/
function Lexer(options) {
this.tokens = [];
this.tokens.links = {};
this.tokens.citations = {};
this.options = options || marked.defaults;
this.rules = block.normal;
if (this.options.gfm) {
if (this.options.tables) {
this.rules = block.tables;
} else {
this.rules = block.gfm;
}
}
}
/**
* Expose Block Rules
*/
Lexer.rules = block;
/**
* Static Lex Method
*/
Lexer.lex = function (src, options) {
var lexer = new Lexer(options);
return lexer.lex(src);
};
/**
* Preprocessing
*/
Lexer.prototype.lex = function (src) {
src = src
.replace(/\r\n|\r/g, '\n')
.replace(/\t/g, ' ')
.replace(/\u00a0/g, ' ')
.replace(/\u2424/g, '\n');
return this.token(src, true);
};
/**
* Lexing
*/
Lexer.prototype.token = function (src, top, bq) {
var src = src.replace(/^ +$/gm, '')
, next
, loose
, cap
, bull
, b
, item
, space
, i
, l;
while (src) {
// newline
if (cap = this.rules.newline.exec(src)) {
src = src.substring(cap[0].length);
if (cap[0].length > 1) {
this.tokens.push({
type: 'space'
});
}
}
// code
if (cap = this.rules.code.exec(src)) {
src = src.substring(cap[0].length);
cap = cap[0].replace(/^ {4}/gm, '');
this.tokens.push({
type: 'code',
text: !this.options.pedantic
? cap.replace(/\n+$/, '')
: cap
});
continue;
}
// fences (gfm)
if (cap = this.rules.fences.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'code',
lang: cap[2],
text: cap[3]
});
continue;
}
// heading
if (cap = this.rules.heading.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'heading',
depth: cap[1].length,
text: cap[2]
});
continue;
}
// table no leading pipe (gfm)
if (top && (cap = this.rules.nptable.exec(src))) {
src = src.substring(cap[0].length);
item = {
type: 'table',
header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3].replace(/\n$/, '').split('\n')
};
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right';
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center';
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left';
} else {
item.align[i] = null;
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = item.cells[i].split(/ *\| */);
}
this.tokens.push(item);
continue;
}
// lheading
if (cap = this.rules.lheading.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'heading',
depth: cap[2] === '=' ? 1 : 2,
text: cap[1]
});
continue;
}
// hr
if (cap = this.rules.hr.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'hr'
});
continue;
}
// blockquote
if (cap = this.rules.blockquote.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'blockquote_start'
});
cap = cap[0].replace(/^ *> ?/gm, '');
// Pass `top` to keep the current
// "toplevel" state. This is exactly
// how markdown.pl works.
this.token(cap, top, true);
this.tokens.push({
type: 'blockquote_end'
});
continue;
}
// def_list
if (cap = this.rules.def_list.exec(src)) {
// Top-level should never reach here.
src = src.substring(cap[0].length);
var matches;
var ddd = cap[0];
var def_list_items = [];
while (matches = /^\n*((.+\n)+)(: +.+[\n]{2}(:? +.+[\n]{2})*)/g.exec(ddd)) {
var titles = matches[1].trim().split(/\n/g);
var definitions = matches[3].trim().replace(/^: */, '').split(/\n\n:? */g);
def_list_items.push({
type: 'def_list_item',
titles: titles,
definitions: definitions
});
ddd = ddd.substring(matches[0].length);
}
// TODO sort by key
// TODO group by initial letter of the key
// TODO automatically generate See XXX for multiple key entries.
this.tokens.push({
type: 'def_list',
items: def_list_items
});
continue;
}
// bibliography
if (cap = this.rules.bibliography.exec(src)) {
// Top-level should never reach here.
src = src.substring(cap[0].length);
this.tokens.push({
type: 'bibliography'
});
continue;
}
// list
if (cap = this.rules.list.exec(src)) {
src = src.substring(cap[0].length);
bull = cap[2];
this.tokens.push({
type: 'list_start',
ordered: bull.length > 1
});
// Get each top-level item.
cap = cap[0].match(this.rules.item);
next = false;
l = cap.length;
i = 0;
for (; i < l; i++) {
item = cap[i];
// Remove the list item's bullet
// so it is seen as the next token.
space = item.length;
item = item.replace(/^ *([*+-]|\d+\.) +/, '');
// Outdent whatever the
// list item contains. Hacky.
if (~item.indexOf('\n ')) {
space -= item.length;
item = !this.options.pedantic
? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
: item.replace(/^ {1,4}/gm, '');
}
// Determine whether the next list item belongs here.
// Backpedal if it does not belong in this list.
if (this.options.smartLists && i !== l - 1) {
b = block.bullet.exec(cap[i + 1])[0];
if (bull !== b && !(bull.length > 1 && b.length > 1)) {
src = cap.slice(i + 1).join('\n') + src;
i = l - 1;
}
}
// Determine whether item is loose or not.
// Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
// for discount behavior.
loose = next || /\n\n(?!\s*$)/.test(item);
if (i !== l - 1) {
next = item.charAt(item.length - 1) === '\n';
if (!loose) loose = next;
}
this.tokens.push({
type: loose
? 'loose_item_start'
: 'list_item_start'
});
// Recurse.
this.token(item, false, bq);
this.tokens.push({
type: 'list_item_end'
});
}
this.tokens.push({
type: 'list_end'
});
continue;
}
// html
if (cap = this.rules.html.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: this.options.sanitize
? 'paragraph'
: 'html',
pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style',
text: cap[0]
});
continue;
}
// def
if ((!bq && top) && (cap = this.rules.def.exec(src))) {
src = src.substring(cap[0].length);
this.tokens.links[cap[1].toLowerCase()] = {
href: cap[2],
title: cap[3]
};
continue;
}
// task (gfm)
if (top && (cap = this.rules.task.exec(src))) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'task_list_start'
});
cap[0] = cap[0].replace(/^\s+|\s+$/g, '');
cap = cap[0].split(/\n+/);
i = 0;
l = cap.length;
for (; i < l; i++) {
this.tokens.push({
type: 'task_item',
checked: /^\s*\[x\]/.test(cap[i]),
text: cap[i].replace(/^\s*\[[x ]\]\s*/, '')
});
}
this.tokens.push({
type: 'task_list_end'
});
}
// table (gfm)
if (top && (cap = this.rules.table.exec(src))) {
src = src.substring(cap[0].length);
item = {
type: 'table',
header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n'),
caption: cap[4].replace(/(\[|\])/g, '')
};
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right';
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center';
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left';
} else {
item.align[i] = null;
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = item.cells[i]
.replace(/^ *\| *| *\| *$/g, '')
.split(/ *\| */);
}
this.tokens.push(item);
continue;
}
// top-level paragraph
if (top && (cap = this.rules.paragraph.exec(src))) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'paragraph',
text: cap[1].charAt(cap[1].length - 1) === '\n'
? cap[1].slice(0, -1)
: cap[1]
});
continue;
}
// text
if (cap = this.rules.text.exec(src)) {
// Top-level should never reach here.
src = src.substring(cap[0].length);
this.tokens.push({
type: 'text',
text: cap[0]
});
continue;
}
if (src) {
throw new
Error('Infinite loop on byte: ' + src.charCodeAt(0));
}
}
return this.tokens;
};
/**
* Inline-Level Grammar
*/
var inline = {
escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
url: noop,
tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
link: /^!?\[(inside)\]\(href\)/,
reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
citelink: /^!?(\[(book|chapter|column|figure|folio|issue|line|note|opus|page|paragraph|part|section|sub verbo|verse|volume) ([^\]]*)\])? *\n*\[#([^\]]*)\]/,
critique: /^!?\[([^\]]*)\] *\[\?([^\:]*)\: *([^\]]*)\]/,
footnote: /^!?\[\^([^\]]*)\]/,
nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
em: /^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
br: /^ {2,}\n(?!\s*$)/,
del: noop,
text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
};
inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
inline.link = replace(inline.link)
('inside', inline._inside)
('href', inline._href)
();
inline.reflink = replace(inline.reflink)
('inside', inline._inside)
();
/**
* Normal Inline Grammar
*/
inline.normal = merge({}, inline);
/**
* Pedantic Inline Grammar
*/
inline.pedantic = merge({}, inline.normal, {
strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
});
/**
* GFM Inline Grammar
*/
inline.gfm = merge({}, inline.normal, {
escape: replace(inline.escape)('])', '~|])')(),
url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
del: /^~~(?=\S)([\s\S]*?\S)~~/,
text: replace(inline.text)
(']|', '~]|')
('|', '|https?://|')
()
});
/**
* GFM + Line Breaks Inline Grammar
*/
inline.breaks = merge({}, inline.gfm, {
br: replace(inline.br)('{2,}', '*')(),
text: replace(inline.gfm.text)('{2,}', '*')()
});
/**
* Inline Lexer & Compiler
*/
function InlineLexer(links, options) {
this.options = options || marked.defaults;
this.links = links;
this.rules = inline.normal;
this.renderer = this.options.renderer || new Renderer;
this.renderer.options = this.options;
if (!this.links) {
throw new
Error('Tokens array requires a `links` property.');
}
if (this.options.gfm) {
if (this.options.breaks) {
this.rules = inline.breaks;
} else {
this.rules = inline.gfm;
}
} else if (this.options.pedantic) {
this.rules = inline.pedantic;
}
}
/**
* Expose Inline Rules
*/
InlineLexer.rules = inline;
/**
* Static Lexing/Compiling Method
*/
InlineLexer.output = function (src, links, options) {
var inline = new InlineLexer(links, options);
return inline.output(src);
};
/**
* Lexing/Compiling
*/
InlineLexer.prototype.output = function (src) {
var out = ''
, link
, text
, href
, cap;
while (src) {
// escape
if (cap = this.rules.escape.exec(src)) {
src = src.substring(cap[0].length);
out += cap[1];
continue;
}
// autolink
if (cap = this.rules.autolink.exec(src)) {
src = src.substring(cap[0].length);
if (cap[2] === '@') {
text = cap[1].charAt(6) === ':'
? this.mangle(cap[1].substring(7))
: this.mangle(cap[1]);
href = this.mangle('mailto:') + text;
} else {
text = escape(cap[1]);
href = text;
}
out += this.renderer.link(href, null, text);
continue;
}
// url (gfm)
if (!this.inLink && (cap = this.rules.url.exec(src))) {
src = src.substring(cap[0].length);
text = escape(cap[1]);
href = text;
out += this.renderer.link(href, null, text);
continue;
}
// tag
if (cap = this.rules.tag.exec(src)) {
if (!this.inLink && /^<a /i.test(cap[0])) {
this.inLink = true;
} else if (this.inLink && /^<\/a>/i.test(cap[0])) {
this.inLink = false;
}
src = src.substring(cap[0].length);
out += this.options.sanitize
? escape(cap[0])
: cap[0];
continue;
}
// citelink
if ((cap = this.rules.citelink.exec(src))) {
src = src.substring(cap[0].length);
var citations = require('citations');
var cite;
try {
cite = citations.cite(
{
citationItems: [
{
id: cap[4],
locator: cap[3],
label: cap[2]
}
],
properties: {
noteIndex: 0
}
}
);
out += this.renderer.link("#cite_" + cap[4], citations.getItemBib(cap[4]), cite);
} catch (e) {
console.log(e);
out += cap[0].charAt(0);
src = cap[0].substring(1) + src;
}
continue;
}
// critique
if ((cap = this.rules.critique.exec(src))) {
src = src.substring(cap[0].length);
// g1 target
// g2 author
// g3 comment
var target = cap[1];
var critic = cap[2];
var comment = cap[3];
out += this.renderer.critique(target, critic, comment);
continue;
}
// footnote
if ((cap = this.rules.footnote.exec(src))) {
src = src.substring(cap[0].length);
// g1 footnote content
var content = cap[1];
out += this.renderer.footnote(content);
continue;
}
// link
if (cap = this.rules.link.exec(src)) {
src = src.substring(cap[0].length);
this.inLink = true;
out += this.outputLink(cap, {
href: cap[2],
title: cap[3]
});
this.inLink = false;
continue;
}
// reflink, nolink
if ((cap = this.rules.reflink.exec(src))
|| (cap = this.rules.nolink.exec(src))) {
src = src.substring(cap[0].length);
link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
link = this.links[link.toLowerCase()];
if (!link || !link.href) {
out += cap[0].charAt(0);
src = cap[0].substring(1) + src;
continue;
}
this.inLink = true;
out += this.outputLink(cap, link);
this.inLink = false;
continue;
}
// strong
if (cap = this.rules.strong.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.strong(this.output(cap[2] || cap[1]));
continue;
}
// em
if (cap = this.rules.em.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.em(this.output(cap[2] || cap[1]));
continue;
}
// code
if (cap = this.rules.code.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.codespan(escape(cap[2], true));
continue;
}
// br
if (cap = this.rules.br.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.br();
continue;
}
// del (gfm)
if (cap = this.rules.del.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.del(this.output(cap[1]));
continue;
}
// text
if (cap = this.rules.text.exec(src)) {
src = src.substring(cap[0].length);
out += escape(this.smartypants(cap[0]));
continue;
}
if (src) {
throw new
Error('Infinite loop on byte: ' + src.charCodeAt(0));
}
}
return out;
};
/**
* Compile Link
*/
InlineLexer.prototype.outputLink = function (cap, link) {
var href = escape(link.href)
, title = link.title ? escape(link.title) : null;
return cap[0].charAt(0) !== '!'
? this.renderer.link(href, title, this.output(cap[1]))
: this.renderer.image(href, title, escape(cap[1]));
};
/**
* Compile Link
*/
InlineLexer.prototype.outputLink = function (cap, link) {
var href = escape(link.href)
, title = link.title ? escape(link.title) : null;
return cap[0].charAt(0) !== '!'
? this.renderer.link(href, title, this.output(cap[1]))
: this.renderer.image(href, title, escape(cap[1]));
};
/**
* Smartypants Transformations
*/
InlineLexer.prototype.smartypants = function (text) {
if (!this.options.smartypants) return text;
return text
// em-dashes
.replace(/--/g, '\u2014')
// opening singles
.replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
// closing singles & apostrophes
.replace(/'/g, '\u2019')
// opening doubles
.replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
// closing doubles
.replace(/"/g, '\u201d')
// ellipses
.replace(/\.{3}/g, '\u2026');
};
/**
* Mangle Links
*/
InlineLexer.prototype.mangle = function (text) {
var out = ''
, l = text.length
, i = 0
, ch;
for (; i < l; i++) {
ch = text.charCodeAt(i);
if (Math.random() > 0.5) {
ch = 'x' + ch.toString(16);
}
out += '&#' + ch + ';';
}
return out;
};
/**
* Renderer
*/
function Renderer(options) {
this.options = options || {};
}
Renderer.prototype.code = function (code, lang, escaped) {
if (this.options.highlight) {
var out = this.options.highlight(code, lang);
if (out != null && out !== code) {
escaped = true;
code = out;
}
}
if (!lang) {
return '<pre><code>'
+ (escaped ? code : escape(code, true))
+ '\n</code></pre>';
}
return '<pre><code class="'
+ this.options.langPrefix
+ escape(lang, true)
+ '">'
+ (escaped ? code : escape(code, true))
+ '\n</code></pre>\n';
};
Renderer.prototype.tasklist = function (text) {
return '<ul class="task-list">\n' + text + '</ul>\n';
};
Renderer.prototype.taskitem = function (text, checked, disabled, i) {
return '<li class="task-list-item"><label>'
+ '<input type="checkbox"'
+ ' class="task-list-item-checkbox"'
+ ' data-item-index="' + i + '"'
+ ' data-item-complete="' + (checked ? 1 : 0) + '"'
+ (disabled ? ' disabled=""' : '') + '>'
+ ' ' + text
+ '</label></li>';
};
Renderer.prototype.blockquote = function (quote) {
return '<blockquote>\n' + quote + '</blockquote>\n';
};
Renderer.prototype.def_list = function (items) {
var body = '';
items.forEach(function (item) {
item.titles.forEach(function (title) {
var id = 'glossary/' + title.toLowerCase().replace(' ', '_');
body += '<dt id="' + id + '">' + title + '</dt>\n';
});
item.definitions.forEach(function (definition) {
body += '<dd>' + definition + '</dd>\n';
});
}, this);
items.forEach(function (item) {
item.titles.forEach(function (title) {
var id = 'glossary/' + title.toLowerCase().replace(' ', '_');
body += '<dt id="' + id + '">' + title + '</dt>\n';
});
item.definitions.forEach(function (definition) {
body += '<dd>' + definition + '</dd>\n';
});
}, this);
return '<dl id="glossary">\n' + body + '</dl>\n';
};
Renderer.prototype.html = function (html) {
return html;
};
Renderer.prototype.heading = function (text, level, raw) {
return '<h'
+ level
+ ' id="'
+ this.options.headerPrefix
+ raw.toLowerCase().replace(/[^\w]+/g, '-')
+ '">'
+ text
+ '</h'
+ level
+ '>\n';
};
Renderer.prototype.hr = function () {
return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
};
Renderer.prototype.list = function (body, ordered) {
var type = ordered ? 'ol' : 'ul';
return '<' + type + '>\n' + body + '</' + type + '>\n';
};
Renderer.prototype.listitem = function (text) {
return '<li>' + text + '</li>\n';
};
Renderer.prototype.paragraph = function (text) {
if (text.trim().length > 0) {
return '<p>' + text + '</p>\n';
}else{
return '\n';
}
};
Renderer.prototype.table = function (header, body, caption) {
return '<table>\n'
+ '<caption>\n'
+ caption
+ '</caption>\n'
+ '<thead>\n'
+ header
+ '</thead>\n'
+ '<tbody>\n'
+ body
+ '</tbody>\n'
+ '</table>\n';
};
Renderer.prototype.tablerow = function (content) {
return '<tr>\n' + content + '</tr>\n';
};
Renderer.prototype.tablecell = function (content, flags) {
var type = flags.header ? 'th' : 'td';
var tag = flags.align
? '<' + type + ' style="text-align:' + flags.align + '">'
: '<' + type + '>';
return tag + content + '</' + type + '>\n';
};
// span level renderer
Renderer.prototype.strong = function (text) {
return '<strong>' + text + '</strong>';
};
Renderer.prototype.em = function (text) {
return '<em>' + text + '</em>';
};
Renderer.prototype.codespan = function (text) {
return '<code>' + text + '</code>';
};
Renderer.prototype.br = function () {
return this.options.xhtml ? '<br/>' : '<br>';
};
Renderer.prototype.del = function (text) {
return '<del>' + text + '</del>';
};
Renderer.prototype.link = function (href, title, text) {
if (this.options.sanitize) {
try {
var prot = decodeURIComponent(unescape(href))
.replace(/[^\w:]/g, '')
.toLowerCase();
} catch (e) {
return '';
}
if (prot.indexOf('javascript:') === 0) {
return '';
}
}
var out = '<a href="' + href + '"';
if (title) {
out += ' title="' + title + '"';
}
out += '>' + text + '</a>';
return out;
};
Renderer.prototype.critique = function (target, critic, comment) {
return '<span class="critique" data-critic="' + critic + '" data-comment="' + comment + '" >' + target + '</span>';
}
Renderer.prototype.footnote = function (content) {
return '<a class="footnote" data-footnote="'+content+'"></a>';
}
Renderer.prototype.bibliography = function () {
var citations = require('citations');
return citations.renderBibliography();
}
Renderer.prototype.image = function (href, title, text) {
var out = '<figure><img src="' + href + '" alt="' + text + '"';
if (title) {
out += ' title="' + title + '"';
}
out += this.options.xhtml ? '/>' : '>';
out += '<figcaption>' + text + '</figcaption></figure>';
return out;
};
/**
* Parsing & Compiling
*/
function Parser(options) {
this.tokens = [];
this.token = null;
this.options = options || marked.defaults;
this.options.renderer = this.options.renderer || new Renderer;
this.renderer = this.options.renderer;
this.renderer.options = this.options;
}
/**
* Static Parse Method
*/
Parser.parse = function (src, options, renderer) {
var parser = new Parser(options, renderer);
return parser.parse(src);
};
/**
* Parse Loop
*/
Parser.prototype.parse = function (src) {
this.inline = new InlineLexer(src.links, this.options, this.renderer);
this.tokens = src.reverse();
var out = '';
while (this.next()) {
out += this.tok();
}
return out;
};
/**
* Next Token
*/
Parser.prototype.next = function () {
return this.token = this.tokens.pop();
};
/**
* Preview Next Token
*/
Parser.prototype.peek = function () {
return this.tokens[this.tokens.length - 1] || 0;
};
/**
* Parse Text Tokens
*/
Parser.prototype.parseText = function () {
var body = this.token.text;
while (this.peek().type === 'text') {
body += '\n' + this.next().text;
}
return this.inline.output(body);
};
/**
* Parse Current Token
*/
Parser.prototype.tok = function () {
switch (this.token.type) {
case 'space':
{
return '';
}
case 'hr':
{
return this.renderer.hr();
}
case 'heading':
{
return this.renderer.heading(
this.inline.output(this.token.text),
this.token.depth,
this.token.text);
}
case 'code':
{
return this.renderer.code(this.token.text,
this.token.lang,
this.token.escaped);
}
case 'task_list_start':
{
var body = ''
, i = 1;
while (this.next().type !== 'task_list_end') {
body += this.renderer.taskitem(
this.inline.output(this.token.text),
this.token.checked,
this.token.disabled,
i++);
}
return this.renderer.tasklist(body);
}
case 'table':
{
var header = ''
, body = ''
, caption
, i
, row
, cell
, flags
, j;
// header
cell = '';
for (i = 0; i < this.token.header.length; i++) {
flags = { header: true, align: this.token.align[i] };
cell += this.renderer.tablecell(
this.inline.output(this.token.header[i]),
{ header: true, align: this.token.align[i] }
);
}
header += this.renderer.tablerow(cell);
for (i = 0; i < this.token.cells.length; i++) {
row = this.token.cells[i];
cell = '';
for (j = 0; j < row.length; j++) {
cell += this.renderer.tablecell(
this.inline.output(row[j]),
{ header: false, align: this.token.align[j] }
);
}
body += this.renderer.tablerow(cell);
}
//caption
caption = this.token.caption === undefined ? '' : this.token.caption;
return this.renderer.table(header, body, caption);
}
case 'blockquote_start':
{
var body = '';
while (this.next().type !== 'blockquote_end') {
body += this.tok();
}
return this.renderer.blockquote(body);
}
case 'def_list':
{
return this.renderer.def_list(this.token.items);
}
case 'list_start':
{
var body = ''
, ordered = this.token.ordered;
while (this.next().type !== 'list_end') {
body += this.tok();
}
return this.renderer.list(body, ordered);
}
case 'list_item_start':
{
var body = '';
while (this.next().type !== 'list_item_end') {
body += this.token.type === 'text'
? this.parseText()
: this.tok();
}
return this.renderer.listitem(body);
}
case 'loose_item_start':
{
var body = '';
while (this.next().type !== 'list_item_end') {
body += this.tok();
}
return this.renderer.listitem(body);
}
case 'html':
{
var html = !this.token.pre && !this.options.pedantic
? this.inline.output(this.token.text)
: this.token.text;
return this.renderer.html(html);
}
case 'paragraph':
{
return this.renderer.paragraph(this.inline.output(this.token.text));
}
case 'text':
{
return this.renderer.paragraph(this.parseText());
}
case 'bibliography':
{
return this.renderer.bibliography();
}
}
};
/**
* Helpers
*/
function escape(html, encode) {
return html
.replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function unescape(html) {
return html.replace(/&([#\w]+);/g, function (_, n) {
n = n.toLowerCase();
if (n === 'colon') return ':';
if (n.charAt(0) === '#') {
return n.charAt(1) === 'x'
? String.fromCharCode(parseInt(n.substring(2), 16))
: String.fromCharCode(+n.substring(1));
}
return '';
});
}
function replace(regex, opt) {
regex = regex.source;
opt = opt || '';
return function self(name, val) {
if (!name) return new RegExp(regex, opt);
val = val.source || val;
val = val.replace(/(^|[^\[])\^/g, '$1');
regex = regex.replace(name, val);
return self;
};
}
function noop() {
}
noop.exec = noop;
function merge(obj) {
var i = 1
, target
, key;
for (; i < arguments.length; i++) {
target = arguments[i];
for (key in target) {
if (Object.prototype.hasOwnProperty.call(target, key)) {
obj[key] = target[key];
}
}
}
return obj;
}
/**
* Marked
*/
function marked(src, opt, callback) {
if (callback || typeof opt === 'function') {
if (!callback) {
callback = opt;
opt = null;
}
opt = merge({}, marked.defaults, opt || {});
var highlight = opt.highlight
, tokens
, pending
, i = 0;
try {
tokens = Lexer.lex(src, opt)
} catch (e) {
return callback(e);
}
pending = tokens.length;
var done = function (err) {
if (err) {
opt.highlight = highlight;
return callback(err);
}
var out;
try {
out = Parser.parse(tokens, opt);
} catch (e) {
err = e;
}
opt.highlight = highlight;
return err
? callback(err)
: callback(null, out);
};
if (!highlight || highlight.length < 3) {
return done();
}
delete opt.highlight;
if (!pending) return done();
for (; i < tokens.length; i++) {
(function (token) {
if (token.type !== 'code') {
return --pending || done();
}
return highlight(token.text, token.lang, function (err, code) {
if (err) return done(err);
if (code == null || code === token.text) {
return --pending || done();
}
token.text = code;
token.escaped = true;
--pending || done();
});
})(tokens[i]);
}
return;
}
try {
if (opt) opt = merge({}, marked.defaults, opt);
return Parser.parse(Lexer.lex(src, opt), opt);
} catch (e) {
e.message += '\nPlease report this to https://github.com/chjj/marked.';
if ((opt || marked.defaults).silent) {
return '<p>An error occured:</p><pre>'
+ escape(e.message + '', true)
+ '</pre>';
}
throw e;
}
}
/**
* Options
*/
marked.options =
marked.setOptions = function (opt) {
merge(marked.defaults, opt);
return marked;
};
marked.defaults = {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: true,
silent: false,
highlight: null,
langPrefix: 'lang-',
smartypants: true,
headerPrefix: '',
renderer: new Renderer,
xhtml: true
};
/**
* Expose
*/
marked.Parser = Parser;
marked.parser = Parser.parse;
marked.Renderer = Renderer;
marked.Lexer = Lexer;
marked.lexer = Lexer.lex;
marked.InlineLexer = InlineLexer;
marked.inlineLexer = InlineLexer.output;
marked.parse = marked;
if (typeof module !== 'undefined' && typeof exports === 'object') {
module.exports = marked;
} else if (typeof define === 'function' && define.amd) {
define(function () {
return marked;
});
} else {
this.marked = marked;
}
}).call(function () {
return this || (typeof window !== 'undefined' ? window : global);
}());
|
define (
[
'kbwidget',
'bootstrap',
'jquery',
'kbwidget',
'kbaseAuthenticatedWidget'
], function(
KBWidget,
bootstrap,
$,
KBWidget,
kbaseAuthenticatedWidget
) {
return KBWidget({
name: "KBaseGWASPopKinshipTable",
parent : kbaseAuthenticatedWidget,
version: "1.0.0",
options: {
width: 500,
type:"KBaseGwasData.GwasPopulationKinship"
},
workspaceURL: "https://kbase.us/services/ws/",
init: function(options) {
this._super(options);
this.workspaceClient = new Workspace(this.workspaceURL, {token: this.authToken()});
return this.render();
},
render: function () {
var self = this;
this.workspaceClient.get_objects([{name : this.options.id, workspace: this.options.ws}],
function(data){
self.collection = data[0];
self.$elem.append($("<div />").
append($("<table/>").addClass("kbgo-table")
.append($("<tr/>").append("<td>Gwas Population Object</td><td>" + self.collection.data.GwasPopulation_obj_id+ "</td>"))
.append($("<tr/>").append("<td>Gwas Population Variation Object</td><td>" + self.collection.data.GwasPopulationVariation_obj_id+ "</td>"))
.append($("<tr/>").append("<td>object_name</td><td>" + self.collection.info[1] + "</td>"))
.append($("<tr/>").append("<td>kbase_genome_id</td><td>" + self.collection.data.genome.kbase_genome_id + "</td>"))
.append($("<tr/>").append("<td>kbase_genome_name</td><td>" + self.collection.data.genome.kbase_genome_name + "</td>"))
.append($("<tr/>").append("<td>source_genome_name</td><td>" + self.collection.data.genome.source_genome_name + "</td>"))
));
},
function (e) {
self.$elem.append("<div class='alert alert-danger'>" + e.error.message + "</div>");
}
);
return this;
},
getData: function() {
return {
type: this.options.type,
id: this.options.id,
workspace: this.options.ws,
title: "GWAS Kinship Details",
draggable: false,
resizable: false,
dialogClass: 'no-close'
};
}
});
});
|
'use strict';
describe('Controller: AboutCtrl', function () {
// load the controller's module
beforeEach(module('chipsApp'));
var AboutCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
AboutCtrl = $controller('AboutCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(scope.awesomeThings.length).toBe(3);
});
});
|
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const config = require('./webpack.local.config');
/* eslint-disable no-console */
new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
inline: true,
historyApiFallback: true,
}).listen(3000, config.ip, (err) => {
if (err) {
console.log(err);
}
console.log(`Listening at ${config.ip}:3000`);
});
/* eslint-enable no-console */
|
'use strict';
(function() {
var planner = angular.module('cashewApp.Planner', ['ngRoute']);
planner.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/plan', {
templateUrl: 'views/Planner/Planner.html',
controller: 'Planner',
controllerAs: 'planner'
});
}]);
planner.controller('Planner', ['$scope', 'LineItemsService', function($scope, LineItemsService) {
var me = this;
var getDTIGraphParts = function(lineItems) {
var debt_amt = {'mo': 0, 'yr': 0};
var earn_amt = {'mo': 0, 'yr': 0};
lineItems.forEach(function(item) {
if (item.isAmountless) {
return;
}
if (item.type === 'minus') {
debt_amt[item.freq.per] += item.amount * item.freq.on.length;
} else if (item.type === 'plus') {
earn_amt[item.freq.per] += item.amount * item.freq.on.length;
}
});
earn_amt.mo *= 12;
debt_amt.mo *= 12;
var earn_sum = earn_amt.mo + earn_amt.yr;
if (earn_sum > 0) {
var debt_mo_width = Math.round(debt_amt.mo / earn_sum * 100);
var debt_yr_width = Math.round(debt_amt.yr / earn_sum * 100);
var result = [];
if (debt_amt.mo > 0) {
result.push({name: 'Monthly costs', color: '#FF4747', width: debt_mo_width});
}
if (debt_amt.yr > 0) {
result.push({name: 'Yearly costs', color: '#FFDD45', width: debt_yr_width});
}
result.push({name: 'Earnings', color: '#A5E85D', width: 100 - (debt_mo_width + debt_yr_width)});
return result;
}
if (debt_amt.mo + debt_amt.yr === 0) {
return [ {name: 'No data', color: '#EEE', width: 100} ];
}
return [ {name: 'All debt :(', color: '#FF4747', width: 100} ];
};
var processLineItems = function(lineItems) {
lineItems.forEach(function(item) {
item.isAmountless = !item.amount;
});
return lineItems;
};
me.lineItems = [];
me.updateLineItems = function() {
me.lineItems = processLineItems(LineItemsService.lineItems);
me.graphParts = getDTIGraphParts(me.lineItems);
};
me.closeLineItem = function(item) {
LineItemsService.close(item);
};
me.removeLineItem = function(item) {
LineItemsService.remove(item);
};
me.getPartStyle = function(part) {
return 'background-color: ' + part.color + '; width: ' + part.width + '%';
};
$scope.$on('lineitems.added', me.updateLineItems);
$scope.$on('lineitems.refreshed', me.updateLineItems);
$scope.$on('lineitems.removed', me.updateLineItems);
$scope.$on('lineitems.updated', me.updateLineItems);
LineItemsService.refresh(moment().startOf('day'));
}]);
})();
|
global.gulp = require('gulp');
global.gutil = require('gulp-util');
global.fs = require('fs');
global.argv = require('minimist')(process.argv.slice(2));
global.karma = require('karma').server;
global.path = require('path');
global.rename = require('gulp-rename');
global.filter = require('gulp-filter');
global._ = require('lodash');
global.glob = require('glob').sync;
global.lazypipe = require('lazypipe');
global.series = require('stream-series');
global.through2 = require('through2');
global.autoprefixer = require('gulp-autoprefixer');
global.concat = require('gulp-concat');
global.filter = require('gulp-filter');
global.gulpif = require('gulp-if');
global.insert = require('gulp-insert');
global.jshint = require('gulp-jshint');
global.minifyCss = require('gulp-minify-css');
global.ngAnnotate = require('gulp-ng-annotate');
global.plumber = require('gulp-plumber');
global.sass = require('gulp-sass');
global.uglify = require('gulp-uglify');
global.webserver = require('gulp-webserver');
global.IS_RELEASE_BUILD = !!argv.release;
global.IS_DEMO_BUILD = (!!argv.module || !!argv.m || !!argv.c);
global.VERSION = argv.version || require('../package.json').version;
global.LR_PORT = argv.port || argv.p || 8080;
global.config = require('./config');
global.utils = require(root + '/scripts/gulp-utils.js');
global.BUILD_MODE = getBuildMode(global.IS_DEMO_BUILD ? 'demos' : argv.mode);
function getBuildMode (mode) {
switch (mode) {
case 'closure': return {
transform: utils.addClosurePrefixes,
outputDir: path.join(config.outputDir, 'modules/closure') + path.sep,
useBower: false
};
case 'demos': return {
transform: utils.addJsWrapper,
outputDir: path.join(config.outputDir, 'demos') + path.sep,
useBower: false
};
default: return {
transform: utils.addJsWrapper,
outputDir: path.join(config.outputDir, 'modules/js') + path.sep,
useBower: true
};
}
}
|
var app = app || {};
//var Codemirror = require('../../node_modules/react-codemirror/dist/react-codemirror.min.js')
(function() {
app.APP_TEST = 1;
app.STANDARD_TEST = 2;
app.SERVER_TEST = 3;
var TestButton = app.TestButton;
var CodeEditor = app.CodeEditor;
var UrlEditor = app.UrlEditor;
var ResultDisplay = app.ResultDisplay;
function onChange(newCode) {
console.log(newCode)
}
function updateCode(newCode){
console.log(newCode);
}
var options = {
lineNumbers: true,
mode:'java'
};
var TesterApp = React.createClass({displayName: "TesterApp",
getInitialState: function() {
return {code:"",url:"", isResultReady:false, isLoading:false, isTestPass:true, isTestFail:false};
},
updateCode:function(newCode){
this.state.code = newCode;
},
handleTaskSubmit:function(submitType){
//this.state.isLoading = !this.state.isLoading;
this.setState({isLoading:!this.state.isLoading});
console.log(submitType, this.state.code);
},
render:function(){
return (
React.createElement("div", {className: "box"},
React.createElement("div", {className: "test-input"},
React.createElement("div", {className: "btnArea"},
React.createElement(TestButton, {btn_name: "App Test", submitTestTask: this.handleTaskSubmit, btnType: app.APP_TEST}),
React.createElement(TestButton, {btn_name: "Server Test", submitTestTask: this.handleTaskSubmit, btnType: app.APP_TEST}),
React.createElement(TestButton, {btn_name: "Standard Test", submitTestTask: this.handleTaskSubmit, btnType: app.APP_TEST})
),
React.createElement(UrlEditor, null),
React.createElement(CodeEditor, {updateCode: this.updateCode, language: "python"})
),
React.createElement("div", {className: "result-area"},
React.createElement("div", {className: "loading", hidden: !this.state.isLoading},
React.createElement("img", {src: "../img/5.png", alt: "loading", class: "img-responsive loading-img"})
),
"// ", React.createElement(ResultDisplay, {hidden: !this.isResultReady})
)
)
);
}
});
function render() {
ReactDOM.render(
React.createElement(TesterApp, null),
document.getElementById('main')
);
}
render();
})();
|
const uuid = require('uuid')
const sessionData = require('./session.data')
const config = require('../../config/auth')
const token = require('../../helper/token')
/**
* @param {number} expiresIn Session ttl in ms
* @return {number} Session expiration timestamp
*/
function getExpiresAt (expiresIn) {
const nowUnixEpoch = Math.floor(new Date().getTime() / 1000)
return nowUnixEpoch + expiresIn
}
/**
* @param {string} userId User id
* @return {string} Generated token meant to be stored in the database
*/
function getDbToken (userId) {
return `${new Date().getTime()}-${userId}-${uuid.v4()}`
}
module.exports = {
async create (userId) {
const dbToken = getDbToken(userId)
const expiresIn = config.expires_in_seconds
const payload = {
user_id: userId,
db_token: dbToken
}
const sessionToken = await token.create(payload, expiresIn)
await sessionData.create(userId, dbToken, getExpiresAt(expiresIn))
return sessionToken
},
async delete (userId) {
await sessionData.delete(userId)
}
}
|
define(["require", "exports", "./puzzle", "./main"], function (require, exports, puzzle_1, main_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var FullRebuildGameUI = (function () {
function FullRebuildGameUI(afterDone) {
this.afterDone = afterDone;
}
Object.defineProperty(FullRebuildGameUI.prototype, "interactive", {
get: function () {
return window.dux.solver;
},
enumerable: true,
configurable: true
});
FullRebuildGameUI.prototype.zoomIntoWorld = function (from_world, to_world) {
};
FullRebuildGameUI.prototype.zoomIntoPuzzle = function (from_world, to_puzzle) {
};
// for initial schema selection/deselection
FullRebuildGameUI.prototype.depictSchemaSelect = function (schema, loc) {
this.interactable();
};
FullRebuildGameUI.prototype.depictSchemaDeselect = function (schema, loc) {
this.interactable();
};
FullRebuildGameUI.prototype.showValidMoves = function (movement_loc_pairs) {
this.interactable();
};
FullRebuildGameUI.prototype.hideValidMoves = function (movement_loc_pairs) {
this.interactable();
};
FullRebuildGameUI.prototype.depictMove = function (move) {
this.interactable();
};
// Would be cool, and feasible, to play all our animations in reverse for undo
FullRebuildGameUI.prototype.depictUndoMove = function (move) {
this.interactable();
};
// This is probably just implemented by move()
FullRebuildGameUI.prototype.depictRedoMove = function (move) {
this.interactable();
};
FullRebuildGameUI.prototype.loadPuzzle = function (puz) {
this.interactable();
};
// Use this to gracefully recover from exceptions. An InstantPuzzleState is the part of InteractiveSolver without the undo/redo stack, sequence of moves, etc. Our current DfsSolver.stateString() characterizes the InstantaniousPuzzleState.
FullRebuildGameUI.prototype.setViewToInstantPuzzleState = function (state) {
this.interactable();
};
FullRebuildGameUI.prototype.getHtml = function () {
var adjacent = this.interactive.validMoves().map(function (x) { return x[1]; });
var sideEffects = this.interactive.listSideEffects();
// console.error(sideEffects);
var result = "";
result += "<div id=\"puzzleTable\" >"; // style="height: ${tabledim[0]}px; width: ${tabledim[1]}px;"
for (var ix in this.interactive.puzzle.grid) {
var rowNum = Number(ix);
result += "\n ";
result += "<div class=\"puzzlerow\" id=\"puzzlerow" + rowNum + "\">";
var row = this.interactive.puzzle.grid[rowNum];
for (var jx in row) {
var colNum = Number(jx);
var sq = row[colNum];
var loc = new puzzle_1.Loc(rowNum, colNum);
var reachable = false;
var sideEffect = sideEffects.has(loc.toString());
var suddenEffect = this.interactive.puzzle.getSquare(loc).sudden;
for (var _i = 0, adjacent_1 = adjacent; _i < adjacent_1.length; _i++) {
var s = adjacent_1[_i];
if (s.equals(loc)) {
reachable = true;
}
}
var isGold = sq.isGold;
var isPortal = sq.portal != null;
var visitsMade = this.interactive.visits.getVisitCount(loc);
var visitsNeeded = this.interactive.puzzle.visitsNeeded(loc);
var visitsRemaining = visitsNeeded - visitsMade;
var schema = this.interactive.puzzle.getSchemaChange(loc);
var currentLocation = this.interactive.currentLoc() != null && this.interactive.currentLoc().equals(loc);
var classes = "puzzlecell visitsNeeded" + visitsNeeded + " visitsRemaining" + visitsRemaining + " visitsMade" + visitsMade;
if (visitsRemaining != 0 && schema != null) {
classes += " bgpic schema_" + schema.name;
}
if (currentLocation) {
classes += ' currentLocation bgpic';
classes += " schema_" + this.interactive.currentSchema.name;
}
if (reachable) {
classes += ' reachable';
}
if (sideEffect) {
classes += ' sideEffect';
}
if (suddenEffect != null) {
classes += " bgpic sudden_" + suddenEffect.name;
}
if (isGold) {
classes += ' goldSquare';
}
if (isPortal) {
classes += " " + sq.portal.shortName() + "-portal";
}
result += "\n ";
result += "<div class=\"" + classes + "\" id=\"puzzlesquare" + rowNum + "_" + colNum + "\">";
// style="width:${puzzlecelldim}px !important; height:${puzzlecelldim}px !important;">`;
result += "";
result += "</div>";
}
result += "\n ";
result += "</div>";
}
result += '</div>';
if (this.interactive.validMoves().length === 0 && !this.interactive.done()) {
result += "<p>you lose, dumbshit</p>";
}
if (this.interactive.done()) {
result += '<p>you won</p>';
}
return result;
};
FullRebuildGameUI.prototype.interactable = function () {
var _this = this;
$('#gameboard').empty().append(this.getHtml());
main_1.resizeGame();
var _loop_1 = function (mloc) {
var mov = mloc[0];
var loc = mloc[1];
var id = "puzzlesquare" + loc.row + "_" + loc.col;
var makeMove = function () {
_this.interactive.move(mov, loc);
console.log("Move to " + loc);
_this.interactable();
// $('#gameboard').replaceWith(this.getHtml());
};
$("#" + id).mousemove(function ($event) {
$event.preventDefault();
// This error is a lie. "buttons" does totally exist.
if ($event.buttons != 1) {
return;
}
$("#" + id).mousedown();
}).bind("mousedown touchstart", function ($event) {
$event.preventDefault();
makeMove();
});
};
for (var _i = 0, _a = this.interactive.validMoves(); _i < _a.length; _i++) {
var mloc = _a[_i];
_loop_1(mloc);
}
if (this.interactive.done()) {
this.afterDone();
$('#ratings').show();
}
else {
$('#ratings').hide();
}
};
return FullRebuildGameUI;
}());
exports.FullRebuildGameUI = FullRebuildGameUI;
});
//# sourceMappingURL=fullRebuildGameUI.js.map
|
const { default: uninstall } = require('../uninstall')
const { expect } = require('chai')
describe('uninstall', () => {
it('removes plugin/preset from .babelrc', () => {
const plugins = ['transform-class-properties']
const babelRC = {
plugins,
presets: [],
}
uninstall({
babelRC,
plugins,
})
expect(
babelRC.plugins
).not.to.include.members(plugins)
})
})
|
export const startTimer = () => {
return {
type: 'START_TIMER',
startTime: new Date().getTime()
};
};
export const updateTimer = () => {
return {
type: 'UPDATE_TIMER',
time: new Date().getTime()
};
};
export const pauseTimer = () => {
return {
type: 'PAUSE_TIMER'
};
};
export const resetTimer = () => {
return {
type: 'RESET_TIMER'
};
};
export const setTimer = (timeRemaining) =>{
return {
type: 'SET_TIMER',
timeRemaining
};
};
export const updateSteeps = (steepCount) =>{
return {
type: 'UPDATE_STEEPS',
steepCount
};
};
export const selectTea = (teaName) => {
return {
type: 'SELECT_TEA',
teaName
};
};
export const setTeas = (teas) =>{
return {
type: 'SET_TEAS',
teas
};
};
|
function itemGenerator(dataArr) {
const template = Handlebars.templates.li;
let result = dataArr;
if (!Array.isArray(dataArr)) {
result = [dataArr];
}
const rendered = template({ listItems: result });
return rendered.trim();
}
export default itemGenerator;
|
var cFiles = [];
var hFiles = [];
function main(){
// Check if all submission conditions are satisfied
$('form').submit(function(event){
if(checkClassInfo() && checkFiles()){
loading();
return;
}
event.preventDefault();
});
$('#add-code-file').on('click', addCFile);
}
function addCFile(){
var nFiles = $('#code-files-table >tbody >tr').length + 1;
$('#code-files-table').find('tbody').append('<tr><td><a class="rem-file"><img src="close.svg" width=20></a></td><td><input type="file" accept=".c, .h" class="code-file" name="cfile_'+nFiles+'" size="45"></td></tr>');
$('.rem-file').on('click', function(){
$(this).parent().parent().remove();
$('input[type=file]').each(function( index ){
$(this).attr('name', 'cfile_'+(index+1));
});
});
}
function loading(){
$(".loading").show();
$(".content").hide();
}
function checkClassInfo(){
var ok = true;
if($('input[name="disciplina"]').val()==='') {
notification('Informe a disciplina');
ok = false;
}
else if ($('input[name="turma"]').val()==='') {
notification('Informe a turma');
ok = false;
}
else if ($('input[name="lab"]').val()==='') {
notification('Informe o número do laboratório');
ok = false;
}
return ok;
}
function checkFiles(){
var files = [];
$('input[type=file]').each(function(){
files.push($(this).val());
});
for(var i=0; i<files.length; i++){
if(!(files[i])){
notification('É necessário que todos os negócios contenham arquivos');
return false;
}
}
if(!files){
notification('Fornceça ao menos um arquivo de código');
return false;
}
return true;
}
// Notifica o usuario de uma mensagem de erro
function notification(msg) {
alert(msg);
}
addCFile();
$(document).ready(main);
|
SystematicCyclicCode = function (infoLen, codeLen, genePoly, genePolyDigree) {
//Properties
this.infoLen = infoLen;
this.codeLen = codeLen;
this.genePolyDigree = genePolyDigree;
this.recoveryLen = Math.floor(genePolyDigree / 2);
this.genePoly = genePoly;
this.surplusPoly = 0b0;
this.syndrome = [];
this.zero = "";
//Constructor
for (var i = 0; i < codeLen; i++) {
var errorPoly = 1 << i;
this.syndrome[this.polyDiv(errorPoly,this.codeLen-1,this.genePoly,this.genePolyDigree)[1]] = errorPoly;
}
for (var i = 0; i < this.codeLen; i++) {
this.zero += 0;
}
}
//多項式除算のローカルメソッド(x/y)
//x,yはそれぞれモニック多項式, 返り値は[商,剰余]の配列
//Memo:ひっ算をシミュレート
SystematicCyclicCode.prototype.polyDiv = function (x, xRank, y, yRank) {
//商の格納変数
var quotient = 0;
//徐式を被徐式に左で桁合わせ
y = y << xRank - yRank;
//元の徐式と被徐式が右で揃うまでループ
for (var i = 0; i <= xRank - yRank; i++) {
//現在の被徐式の最上位桁が1なら割る
if ((x >> xRank - i) & 1 == 1) {
x ^= y;
quotient += 1;
}
//徐式を一つ右にシフト
y = y >> 1;
//商は一つ左にシフト
quotient = quotient << 1;
}
//for最後の余分なシフトを調整
quotient = quotient >> 1;
return [quotient, x];
}
SystematicCyclicCode.prototype.generate = function (infoCode) {
var shiftedCode = infoCode << (this.codeLen - this.infoLen);
//console.log("infoCode: " + infoCode.toString(2).slice(-this.infoLen));
//console.log("shiftCode: " + shiftedCode.toString(2).slice(-this.codeLen));
this.surplusPoly = this.polyDiv(shiftedCode, this.codeLen - 1, this.genePoly, this.genePolyDigree)[1];
return shiftedCode + this.surplusPoly;
};
SystematicCyclicCode.prototype.generateToString = function (infoCode) {
return (this.zero + this.generate(infoCode).toString(2)).substr(-this.codeLen);
};
SystematicCyclicCode.prototype.encode = this.generate;
SystematicCyclicCode.prototype.encodeToString = this.generateToString;
SystematicCyclicCode.prototype.decode = function (reciveCode) {
//シンドロームの計算
var syndrome = this.polyDiv(reciveCode, codeLen - 1, genePoly, genePolyDigree)[1];
//エラー箇所の選定
var error = this.syndrome[syndrome];
//エラー訂正
var sentCode = reciveCode ^ error;
return sentCode >> genePolyDigree;
}
SystematicCyclicCode.prototype.decodeToString = function (reciveCode) {
return (this.zero + this.decode(reciveCode).toString(2)).substr(-this.infoLen);
}
|
'use strict';
module.exports = {
db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + '/solutionsdash',
assets: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.min.css',
'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
],
js: [
'public/lib/angular/angular.min.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-cookies/angular-cookies.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-touch/angular-touch.js',
'public/lib/angular-sanitize/angular-sanitize.js',
'public/lib/angular-ui-router/release/angular-ui-router.min.js',
'public/lib/angular-ui-utils/ui-utils.min.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js'
]
},
css: 'public/dist/application.min.css',
js: 'public/dist/application.min.js'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: '/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: '/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: '/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: '/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: '/auth/github/callback'
},
mailer: {
from: process.env.MAILER_FROM || 'MAILER_FROM',
options: {
service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
auth: {
user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
}
}
}
};
|
app.service('RegisterService', function (SortingService) {
var registers = [];
var defaultN = 50; //default register length, when not provided in constructor args
this.getState = function(key, regNumber){
var registerNumber = regNumber || 0; //set regNumber to 0 if not provided
return registers[registerNumber].state[key];
}
this.setState = function(key, value, regNumber){
var registerNumber = regNumber || 0; //set regNumber to 0 if not provided
registers[registerNumber].state[key] = value;
}
this.get = function(N){
if(N){
return registers[N];
} else {
return registers;
}
}
this.createRegister = function(args){
if(args){
// set parameters sent via args
var N = args[0];
var configVals = args[1];
var newRegister = {
values: null,
state: [
]
};
var algorithm= args[2];
var speed= args[3];
var color= args[4];
var squareWidth = args[4];
var depth = args[5];
var ctx = args[6];
var smallestElement = args[7];
if (configVals === 'random'){
var values = [];
for (var i = 0; i < N; i++) {
values.push(Math.random());
};
newRegister.values = values;
pushRegister();
return registers.length;
} else if (configVals === 'sorted'){
var values = [];
for (var i = 0; i < N; i++) {
values.push(i/N);
};
newRegister.values = values;
pushRegister();
return registers.length;
}
else if (configVals.length<0){ // if an array was passed as second argument
newRegister.values = [];
for (var i = 0; i < configVals.length; i++) {
newRegister.values[i] = configVals[i];
};
pushRegister();
return registers.length;
}
} else {
registers.push('invalid create() register params');
}
// set add register to registers array
function pushRegister(){
initState();
registers[registers.length] = newRegister;
}
// initilize state parameters to their provided (or default, if not) values
function initState(){
newRegister.state = {};
newRegister.state['position'] = 0;
newRegister.state['comparing'] = {
block1: null,
block2: null
};
newRegister.state['sorted'] = false;
newRegister.state['speed'] = speed || 200;
newRegister.state['color'] = color;
newRegister.state['swapping'] = {
block1: null,
block2: null
};
newRegister.state['squareWidth'] = squareWidth || 0;
newRegister.state['outerIndex'] = 0;
newRegister.state['innerIndex'] = 0;
newRegister.state['depth'] = depth || 'quick';
newRegister.state['ctx'] = ctx || undefined;
newRegister.state['smallestElement'] = smallestElement || undefined;
}
}
this.clearRegisters = function(){
registers = [];
}
// SORTING METHODS
this.sort = function(regNumber, args){
var registerNumber = regNumber || 0;
registers[registerNumber].state['algorithm'] = args[0][0];
// registers[registerNumber].state['swapped'] = args[0][1];
registers[registerNumber].state['squareWidth'] = args[0][2];
registers[registerNumber].state['depth'] = args[0][3];
// registers[registerNumber].state['comparing'] = args[0][4];
// registers[registerNumber].state['swapping'] = args[0][5];
// registers[registerNumber].state['speed'] = args[0][6];
// registers[registerNumber].state['color'] = args[0][7];
registers[registerNumber].state['ctx'] = args[0][8];
// registers[registerNumber].state['position'] = args[0][9];
// implement individual drawing methods depending on parameters
if(registers[registerNumber].state['algorithm'] === 'selectionSort'){
this.selectionSort();
} else if(registers[registerNumber].state['algorithm'] === 'insertionSort'){
this.insertionSort();
} else {
console.log("not yet implemented");
}
}
///// DRAWING METHODS /////
// takes in a 0-1 float and returns a color value depending on the register's color variables
this.getColorValue = function(value, colorScheme){
if(registers[0].state['color'] === 'grayscale'){
var scaled = Math.round(value*255);
return 'rgb('+scaled+', '+scaled+', '+scaled+')';
}
if(registers[0].state['color'] === 'color'){
var vR, vG, vB , scaledVal= null; // rgb() values
//all R values
if(value<=(1/6)){
scaledVal = 255 * (value) * 6;
vR = 0;
vG = scaledVal;
vB = 255;
} else if (value>(1/6)&&value<=(2/6)){
scaledVal = 255 * (value - (1/6)) * 6;
vR = 0;
vG = 255;
vB = 255-scaledVal;
} else if (value>(2/6)&&value<=(3/6)){
scaledVal = 255 * (value - (2/6)) * 6;
vR = scaledVal;
vG = 255;
vB = 0;
} else if (value>(3/6)&&value<=(4/6)){
scaledVal = 255 * (value - (3/6)) * 6;
vR = 255;
vG = 255-scaledVal;
vB = 0;
} else if (value>(4/6)&&value<=(5/6)){
scaledVal = 255 * (value - (4/6)) * 6;
vR = 255;
vG = 0;
vB = scaledVal;
} else if (value>(5/6)&&value<=(6/6)){
scaledVal = 255 * (value - (5/6)) * 6;
vR = 255-scaledVal;
vG = 0;
vB = 255;
}
// console.log(scaledVal);
return 'rgb('+Math.round(vR)+', '+Math.round(vG)+', '+Math.round(vB)+')';
}
}
// draws the entire register
this.drawRegister = function(){
var ctx = registers[0].state['ctx'];
for (var i = 0; i < this.get(0)[0].values.length; i++) {
// set color options
var val = this.get(0)[0].values[i];
ctx.fillStyle = this.getColorValue(val, registers[0].state['color']);
ctx.fillRect(
i*registers[0].state['squareWidth']-1,
(registers[0].state['squareWidth']*registers[0].state['outerIndex'])-1,
registers[0].state['squareWidth']+2,
registers[0].state['squareWidth']+2
)
}
}
this.innerLoopSelectionSortFull = function(sorted, unsorted){
//before each pass:
//set innerIndex to 1 block past the outerIndex
// registers[0].state['innerIndex'] = registers[0].state['outerIndex']+1;
if(registers[0].state['innerIndex'] === 0){
registers[0].state['innerIndex'] = registers[0].state['outerIndex']+1;
registers[0].state['smallestElement'] = registers[0].state['outerIndex'];
}
//outline smallestElement
registers[0].state['ctx'].strokeStyle="blue";
registers[0].state['ctx'].lineWidth=4;
registers[0].state['ctx'].strokeRect(
registers[0].state['smallestElement']*registers[0].state['squareWidth']+1,
registers[0].state['squareWidth']*registers[0].state['outerIndex']+1,
registers[0].state['squareWidth']-4,
registers[0].state['squareWidth']-4)
//outline innerIndex
registers[0].state['ctx'].strokeStyle="green";
registers[0].state['ctx'].lineWidth=4;
registers[0].state['ctx'].strokeRect(
registers[0].state['innerIndex']*registers[0].state['squareWidth']+1,
registers[0].state['squareWidth']*registers[0].state['outerIndex']+1,
registers[0].state['squareWidth']-4,
registers[0].state['squareWidth']-4)
// for each block in unsorted array
// for (registers[0].state['innerIndex'] = registers[0].state['outerIndex']+1; registers[0].state['innerIndex'] < registers[0].values.length; registers[0].state['innerIndex']++) {
if(registers[0].state['innerIndex'] < registers[0].values.length){
//check to see if the value at innerIndex is less than the value at smallestElement
if(registers[0].values[registers[0].state['innerIndex']] < registers[0].values[registers[0].state['smallestElement']]){
registers[0].state['smallestElement'] = registers[0].state['innerIndex'];
}
}
registers[0].state['innerIndex']++;
}
this.innerLoopSelectionSort = function(sorted, unsorted){
//before each pass:
//set innerIndex to 1 block past the outerIndex
registers[0].state['innerIndex'] = registers[0].state['outerIndex']+1;
//outline outerIndex
registers[0].state['ctx'].strokeStyle="green";
registers[0].state['ctx'].lineWidth=4;
registers[0].state['ctx'].strokeRect(
registers[0].state['outerIndex']*registers[0].state['squareWidth']+1,
registers[0].state['squareWidth']*registers[0].state['outerIndex']+1,
registers[0].state['squareWidth']-4,
registers[0].state['squareWidth']-4)
//set the smallest element to innerIndex
registers[0].state['smallestElement'] = registers[0].state['outerIndex'];
// for each block in unsorted array
for (registers[0].state['innerIndex'] = registers[0].state['outerIndex']+1; registers[0].state['innerIndex'] < registers[0].values.length; registers[0].state['innerIndex']++) {
//check to see if the value at innerIndex is less than the value at smallestElement
if(registers[0].values[registers[0].state['innerIndex']] < registers[0].values[registers[0].state['smallestElement']]){
registers[0].state['smallestElement'] = registers[0].state['innerIndex'];
}
};
//outline the final smallest element and then swap the elements
registers[0].state['ctx'].strokeStyle="blue";
registers[0].state['ctx'].lineWidth=4;
registers[0].state['ctx'].strokeRect(
registers[0].state['smallestElement']*registers[0].state['squareWidth']+1,
registers[0].state['squareWidth']*registers[0].state['outerIndex']+1,
registers[0].state['squareWidth']-4,
registers[0].state['squareWidth']-4)
this.swap(registers[0].state['outerIndex'], registers[0].state['smallestElement']);
registers[0].state['innerIndex'] = 0;
}
this.selectionSort = function(){
// console.log(registers[0].values);
if(registers[0].state['outerIndex'] === registers[0].values.length-1){
registers[0].state['sorted'] = true;
return;
}
// divide register into sorted and unsorted portion based on position value
var sorted = registers[0].values.slice(0, registers[0].state['outerIndex']);
var unsorted = registers[0].values.slice(registers[0].state['outerIndex'], registers[0].values.length);
// for each item in the register
// console.log(unsorted.length);
if(registers[0].state['outerIndex']<registers[0].values.length){
if(registers[0].state['innerIndex'] === 0){ //if this is the first pass
this.drawRegister();
}
// loop through all remaining items and find smallest
if(registers[0].state['depth'] === 'quick'){
this.innerLoopSelectionSort(sorted, unsorted);
registers[0].state['outerIndex']++;
} else if (registers[0].state['depth'] === 'full'){
this.drawRegister();
if(registers[0].state['innerIndex'] === registers[0].values.length){
//outline the final smallest element and then swap the elements
registers[0].state['ctx'].strokeStyle="blue";
registers[0].state['ctx'].lineWidth=4;
registers[0].state['ctx'].strokeRect(
registers[0].state['smallestElement']*registers[0].state['squareWidth']+1,
registers[0].state['squareWidth']*registers[0].state['outerIndex']+1,
registers[0].state['squareWidth']-4,
registers[0].state['squareWidth']-4)
//draw final register display state, then increment
this.drawRegister();
registers[0].state['ctx'].strokeStyle="red";
registers[0].state['ctx'].lineWidth=2;
registers[0].state['ctx'].strokeRect(
registers[0].state['outerIndex']*registers[0].state['squareWidth']+0,
registers[0].state['squareWidth']*registers[0].state['outerIndex']+0,
registers[0].state['squareWidth']-2,
registers[0].state['squareWidth']-2)
registers[0].state['ctx'].strokeStyle="red";
registers[0].state['ctx'].lineWidth=2;
registers[0].state['ctx'].strokeRect(
registers[0].state['smallestElement']*registers[0].state['squareWidth']+0,
registers[0].state['squareWidth']*registers[0].state['outerIndex']+0,
registers[0].state['squareWidth']-2,
registers[0].state['squareWidth']-2)
this.swap(registers[0].state['outerIndex'], registers[0].state['smallestElement']);
registers[0].state['innerIndex'] = 0;
registers[0].state['outerIndex']++;
}
this.innerLoopSelectionSortFull(sorted, unsorted);
}
};
}
this.swap = function(a, b, regNumber){
// console.log(registers[0].values);
// var 0 = regNumber || 0;
// console.log(registers[0].values[a]+' '+registers[0].values[b]);
var temp = registers[0].values[a];
registers[0].values[a] = registers[0].values[b];
registers[0].values[b] = temp;
// console.log(registers[0].values[a]+' '+registers[0].values[b]);
}
this.insertionSort = function(){
if(registers[0].state['outerIndex'] === registers[0].values.length){
registers[0].state['sorted'] = true;
this.drawRegister();
return;
}
if(registers[0].state['outerIndex'] < registers[0].values.length+1){
// draw register
if(registers[0].state['depth'] === 'quick'){
this.drawRegister();
}
// store the current value because it may shift later
registers[0].state['position'] = registers[0].values[registers[0].state['outerIndex']];
this.insertionSortInner();
registers[0].values[registers[0].state['innerIndex']+1] = registers[0].state['position'];
}
// }
registers[0].state['outerIndex']++;
// return registers[0].values
}
this.insertionSortInner = function(){
for (registers[0].state['innerIndex']=registers[0].state['outerIndex']-1; registers[0].state['innerIndex'] > -1 && registers[0].values[registers[0].state['innerIndex']] > registers[0].state['position']; registers[0].state['innerIndex']--) {
registers[0].values[registers[0].state['innerIndex']+1] = registers[0].values[registers[0].state['innerIndex']];
}
}
// EXIT CRITERIA STRUCTURES
});
|
(function () {
'use strict';
var Hospital = require('../models/hospital');
var HospitalController = function () {
};
// Return all hospitals
HospitalController.prototype.getHospitals = function (req, res) {
Hospital.find().exec(function (err, hospitals) {
if (err) {
res.send(500, err);
}
else {
res.json(hospitals);
}
});
};
// Return hospitals boxed to lat/long received
HospitalController.prototype.getBoundedHospitals = function (req, res) {
console.log('Requested Location box:' + JSON.stringify(req.body.box));
if (!req.body.box) {
res.send(400, 'Bad Request');
}
else {
var location = [
[req.body.box[0][1], req.body.box[0][0]],
[req.body.box[1][1], req.body.box[1][0] ]
];
Hospital.where({
location: { $within: {$box: location}}
}).exec(function (err, hospitals) {
if (err) {
res.send(500, err);
}
else {
res.json(hospitals);
}
});
}
};
module.exports = new HospitalController();
})();
|
var values = [1,2,3,4,5]
var reduceFunc = function(prev, curr, index, array){
return prev + curr;
};
var sum = "Reduce: " + values.reduce(reduceFunc);
console.log(sum);
var sumRight = "Reduce right: " + values.reduceRight(reduceFunc);
console.log(sumRight);
|
"use strict";
const Board = require('../Board');
const movement = require('../services/Movement');
const specialMovement = require('../services/SpecialMovement')
const squaresControl = require('../services/squareControl')
const seneca = require('seneca')({
log: 'silent'
})
.use(movement)
.use(specialMovement)
.use(squaresControl)
const chaiSubset = require('chai-subset');
const expect = require('chai')
.use(chaiSubset)
.expect;
describe('controlled by, Board 1', () => {
var board = new Board({
white: ['Kf6', 'Pf7'],
black: ['Kf3', 'Ne3', 'Bg3']
})
it('White controlled', (done) => {
seneca.error(done);
seneca.act({
role: "board",
cmd: "squaresControlledBy",
board: board,
color: 'white'
}, (err, msg) => {
expect(err)
.to.be.null;
expect(msg.controlled)
.to.have.all.deep.members( [{
file: 'e',
rank: '6'
}, {
file: 'g',
rank: '6'
},
{
file: 'g',
rank: '7'
}, {
file: 'e',
rank: '7'
}, {
file: 'g',
rank: '5'
}, {
file: 'f',
rank: '8'
}] );
done();
});
});
it('Black controlled', (done) => {
seneca.error(done);
seneca.act({
role: "board",
cmd: "squaresControlledBy",
board: board,
color: 'black'
}, (err, msg) => {
// console.log({
// color: 'black',
// controlled: msg.controlled
// })
expect(err)
.to.be.null;
expect(msg.controlled)
.to.have.all.deep.members([{
file: 'f',
rank: '4'
},
{
file: 'f',
rank: '2'
},
{
file: 'e',
rank: '2'
},
{
file: 'g',
rank: '4'
},
{
file: 'e',
rank: '4'
},
{
file: 'g',
rank: '2'
},
{
file: 'c',
rank: '2'
},
{
file: 'd',
rank: '1'
},
{
file: 'c',
rank: '4'
},
{
file: 'f',
rank: '1'
},
{
file: 'd',
rank: '5'
},
{
file: 'f',
rank: '5'
},
{
file: 'e',
rank: '1'
},
{
file: 'h',
rank: '4'
},
{
file: 'e',
rank: '5'
},
{
file: 'd',
rank: '6'
},
{
file: 'c',
rank: '7'
},
{
file: 'b',
rank: '8'
},
{
file: 'h',
rank: '2'
}]);
done();
});
});
})
|
class Just {
constructor(value) {
this.value = value;
}
isJust() {
return true;
}
isNothing() {
return false;
}
getOr(orElse) { // eslint-disable-line no-unused-vars
return this.value;
}
then(func) {
return func(this.value);
}
recover(func) { // eslint-disable-line no-unused-vars
return this;
}
}
export function just(value) {
return new Just(value);
}
export const nothing = {
isJust() {
return false;
},
isNothing() {
return true;
},
getOr(value) {
return value;
},
then(func) { // eslint-disable-line no-unused-vars
return nothing;
},
recover(func) {
return just(func());
}
};
|
export const sort = sortBy => {
switch (sortBy) {
case 'Latest':
return { createdAt: -1 }
case 'Most Popular':
return { favoritesCount: -1, downloadCount: -1, createdAt: -1 }
case 'Least Tags':
return { tagsCount: 1, createdAt: -1 }
default:
return { createdAt: -1 }
}
}
export const CONVERT_TO_SCREENSHOTS = [
{
$project: {
_id: '$screenshot._id',
createdAt: '$screenshot.createdAt',
favorites: '$screenshot.favorites',
tags: '$screenshot.tags',
user: '$screenshot.user',
nsfw: '$screenshot.nsfw',
file: '$screenshot.file',
downloadCount: '$screenshot.downloadCount',
favoritesCount: { $size: '$screenshot.favorites' },
tagsCount: { $size: '$screenshot.tags' }
}
}
]
|
const {
series, crossEnv, concurrent, rimraf
} = require('nps-utils');
module.exports = {
scripts: {
default: 'nps webpack',
test: {
default: 'nps test.jest',
jest: {
default: series(
rimraf('test/coverage-jest'),
crossEnv('BABEL_TARGET=node jest')
),
accept: crossEnv('BABEL_TARGET=node jest -u'),
watch: crossEnv('BABEL_TARGET=node jest --watch'),
},
karma: {
default: series(
rimraf('test/coverage-karma'),
'karma start test/karma.conf.js'
),
watch: 'karma start test/karma.conf.js --auto-watch --no-single-run',
debug: 'karma start test/karma.conf.js --auto-watch --no-single-run --debug'
},
lint: {
default: 'eslint . --ext .html,.js',
fix: 'eslint . --ext .html,.js --fix'
},
react: {
default: crossEnv('BABEL_TARGET=node jest --no-cache --config jest.React.json --notify'),
accept: crossEnv('BABEL_TARGET=node jest -u --no-cache --config jest.React.json --notify --updateSnapshot'),
watch: crossEnv('BABEL_TARGET=node jest --watch --no-cache --config jest.React.json --notify')
},
all: concurrent({
browser: series.nps('test.karma', 'e2e'),
jest: 'nps test.jest',
lint: 'nps test.lint'
})
},
build: 'nps webpack.build',
webpack: {
default: 'nps webpack.server',
build: {
before: rimraf('dist'),
default: 'nps webpack.build.production',
development: {
default: series(
'nps webpack.build.before',
'webpack --progress -d'
),
extractCss: series(
'nps webpack.build.before',
'webpack --progress -d --env.extractCss'
),
serve: series.nps(
'webpack.build.development',
'serve'
)
},
production: {
inlineCss: series(
'nps webpack.build.before',
crossEnv('NODE_ENV=production webpack --progress -p --env.production')
),
default: series(
'nps webpack.build.before',
crossEnv('NODE_ENV=production webpack --progress -p --env.production --env.extractCss')
),
serve: series.nps(
'webpack.build.production',
'serve'
)
}
},
server: {
default: 'webpack-dev-server -d --inline --env.server',
extractCss: 'webpack-dev-server -d --inline --env.server --env.extractCss',
hmr: 'webpack-dev-server -d --inline --hot --env.server'
}
},
serve: 'pushstate-server dist'
}
};
|
var config = require('../config')
var webpack = require('webpack')
var merge = require('webpack-merge')
var utils = require('./utils')
var baseWebpackConfig = require('./webpack.base.conf')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var WebpackVisualizerPlugin = require('webpack-visualizer-plugin');
// add hot-reload related code to entry chunks
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})
module.exports = merge(baseWebpackConfig, {
module: {
loaders: utils.styleLoaders({ extract: true })
},
// eval-source-map is faster for development
devtool: '#eval-source-map',
plugins: [
new webpack.DefinePlugin({
'process.env': config.dev.env
}),
// https://github.com/glenjamin/webpack-hot-middleware#installation--usage
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new ExtractTextPlugin('[name].css'),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
new WebpackVisualizerPlugin(),
],
vue: {
loaders: utils.cssLoaders({
extract: true
})
},
})
|
var cordova = require('cordova'),
UrbanAirshipWindows = require('./UrbanAirshipWindows');
function listenAndDispatch() {
if(RuntimeComponentTest.Class1) {
try {
RuntimeComponentTest.Class1.addEventListener('registrationstatechanged', function(e) {
console.info('UrbanAirshipWindows will dispatch Event: ', e);
var event = new CustomEvent('urbanairship.registration', { detail: e });
document.dispatchEvent(event);
});
} catch(exception) {
console.error('UrbanAirshipWindows could not add Event Listener for registrationstatechanged', exception);
}
try{
RuntimeComponentTest.Class1.addEventListener('pushstatechanged', function(e) {
console.info('UrbanAirshipWindows will dispatch Event: ', e);
var event = new CustomEvent('urbanairship.push', { detail: e });
document.dispatchEvent(event);
});
} catch(exception) {
console.error('UrbanAirshipWindows could not add Event Listener for pushstatechanged', exception);
}
try{
RuntimeComponentTest.Class1.addEventListener('pushparseerror', function(e) {
console.info('UrbanAirshipWindows will dispatch Event: ', e);
var event = new CustomEvent('urbanairship.pusherror', { detail: e });
document.dispatchEvent(event);
});
} catch(exception) {
console.error('UrbanAirshipWindows could not add Event Listener for pushparseerror', exception);
}
}
}
module.exports = {
init: function(success, failure, uaConfig) {
listenAndDispatch();
var res = RuntimeComponentTest.Class1.setUAConfig(uaConfig['key'], uaConfig['secret'], uaConfig['production']);
if (res.indexOf('Error') > -1) {
failure(res);
} else {
var takeOffRes = RuntimeComponentTest.Class1.initUA();
if (takeOffRes.indexOf('Error') > -1) failure(takeOffRes);
else success(res + '\n' + takeOffRes);
}
},
setUserNotificationsEnabled: function(success, failure, enabled) {
var res = RuntimeComponentTest.Class1.setUserNotificationsEnabled(enabled);
if (res.indexOf('Error') > -1) {
failure(res);
} else {
success(res);
}
},
setAlias: function(success, failure, aliasString) {
var res = RuntimeComponentTest.Class1.setApid(aliasString);
if (res.indexOf('Error') > -1) {
failure(res);
} else {
success(res);
}
},
getAlias: function(success, failure) {
var res = RuntimeComponentTest.Class1.getAlias();
if (res.indexOf('Error') > -1) {
failure(res);
} else {
success(res);
}
}
};
require("cordova/exec/proxy").add("UrbanAirshipWindows", module.exports);
|
describe("About Expects", function() {
//We shall contemplate truth by testing reality, via spec expectations.
it("should expect true", function() {
expect(true).toBeTruthy(); //This should be true
});
//To understand reality, we must compare our expectations against reality.
it("should expect equality", function () {
var expectedValue = 2;
var actualValue = 1 + 1;
expect(actualValue === expectedValue).toBeTruthy();
});
//Some ways of asserting equality are better than others.
it("should assert equality a better way", function () {
var expectedValue = 2;
var actualValue = 1 + 1;
// toEqual() compares using common sense equality.
expect(actualValue).toEqual(expectedValue);
});
//Sometimes you need to be really exact about what you "type".
it("should assert equality with ===", function () {
var expectedValue = "2";
var actualValue = (1 + 1).toString();
// toBe() will always use === to compare.
expect(actualValue).toBe(expectedValue);
});
//Sometimes we will ask you to fill in the values.
it("should have filled in values", function () {
expect(1 + 1).toBe(2);
});
});
|
var settings = require(process.env.settingsFile || '../settings');
var util = require('util');
var _ = require('underscore');
var db = require('../lib/db');
var coinRPC = require('../lib/coinRPC');
module.exports.settings = function(req, res, next){
res.locals.settings = settings;
res.locals.payoutRange = {min: settings.payout.bracket[0].amt, max: settings.payout.bracket[settings.payout.bracket.length-1].amt};
res.locals.address = _.isUndefined(req.cookies.get('lastAddress')) ? '' : req.cookies.get('lastAddress')
res.locals.ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
coinRPC.getBalance(function(err, balance) {
db.getFaucetStats(function(err, stats) {
res.locals.faucetStats = stats || {outstandingPayments: 0};
res.locals.faucetBalance = balance - stats.outstandingPayments;
next();
});
});
};
module.exports.defaults = function(req, res, next){
res.locals.meta = {
title: settings.site.name
, description: settings.site.name
};
next();
};
|
app.controller('WorldCtrl', ['$scope', '$location','World',
function($scope, $location, World){
}]);
|
'use strict';
angular.module('myApp.calendar', [])
.controller('CalendarCtrl', ["$scope",function($scope) {
}])
.directive("dateRangePicker", ["$rootScope",function($rootScope) {
return {
restrict: "A",
link: function(scope, elem, attrs) {
$(elem).daterangepicker();
$(elem).on('show.daterangepicker', function(ev, picker) {
$rootScope.$broadcast('showDatePicker');
});
$(elem).on('hide.daterangepicker', function(ev, picker) {
$rootScope.$broadcast('hideDatePicker');
});
$(elem).on('apply.daterangepicker', function(ev, picker) {
$rootScope.$broadcast('datesSelected',{ dates:{startDate:picker.startDate.toDate(),endDate:picker.endDate.toDate()}});
});
}
}
}]);
|
var path = require('path')
var pify = require('pify')
var webpack = pify(require('webpack'))
export default function (input, output) {
return webpack({
entry: [input],
output: {
path: path.dirname(output),
filename: path.basename(output),
libraryTarget: 'commonjs2'
},
target: 'node',
externals: {
'aws-sdk': 'commonjs aws-sdk'
},
module: {
loaders: [
{
test: '.js',
loaders: ['babel'],
query: {
presets: ['es2015']
}
}
]
}
})
}
|
/**
* jquery.dp-pdf.js v0.1.0
* Copyright (c) 2015, dolphilia.
* Licensed under the MIT License.
* http://dolphilia.html.xdomain.jp/
*/
/*
import
https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"
https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.138/jspdf.min.js"
*/
//画像をPDF化
(function( $ ) {
$.fn.dpPDF = function( options ) {
//オプションを設定する
var settings = $.extend( {
selector : '.dp-pdf-item',
imageSelector : '.dp-pdf-item-image',
insertPosition: 'after', //or before
filename: '',
buttonText: 'PDFをダウンロード',
beforePDF: '',
afterPDF: '',
isFirstOnly: false,
callback : function(){},
}, options);
//--- 変数
var this_selector = this.selector; //指定されたセレクター
var this_selector_name = this_selector.substr(1,this_selector.length-1); //先頭の . を取り除く
var item_selector = settings.selector;
var item_selector_name = item_selector.substr(1,item_selector.length-1); //先頭の . を取り除く
var image_selector = settings.imageSelector;
var image_selector_name = image_selector.substr(1,image_selector.length-1); //先頭の . を取り除く
//
var pdf_selector = this_selector + '-pdf';
var pdf_selector_name = this_selector_name + '-pdf';
//
var before_pdf = settings.beforePDF;
var after_pdf = settings.afterPDF;
//
var item_count = $(image_selector).length;
var images = [];
$(image_selector).each(function(i, elem) {
images.push( $(elem).attr('src') );
});
var filename = settings.filename;
if(filename=='') {
filename = this_selector_name;
}
var button_text = settings.buttonText;
//
if(settings.insertPosition=='after') {
$(this_selector).after(before_pdf+'<button id="'+pdf_selector_name+'">'+button_text+'</button>'+after_pdf);
}
else {
$(this_selector).before(before_pdf+'<button id="'+pdf_selector_name+'">'+button_text+'</button>'+after_pdf);
}
$(pdf_selector).click(function(){
var pdf = new jsPDF('p', 'pt', 'a4');
for(var n=0; n<item_count; n++) {
if(n>0) {
pdf.addPage();
}
pdf.addImage(images[n], 'JPEG', -1, -1, 595.28+1, 841.89+1);
}
pdf.save(filename+'.pdf');
});
if(settings.isFirstOnly) { //最初のページではないとき
$.each($(image_selector),function(i, elem) {
if(i!=0) {
$(elem).remove();
}
});
}
//コールバック関数を呼ぶ
settings.callback.call(this);
return this;
};
})( jQuery );
|
import { appActionTypes as actionTypes } from './app-action-types';
export const getLoggedInUser = (username) => ({ type: actionTypes.GET_LOGGED_IN_USER, username: username });
export const setLoggedInUser = (user) => ({ type: actionTypes.SET_LOGGED_IN_USER, user: user });
export const logout = (history) => ({ type: actionTypes.LOGOUT, history: history });
export const logoutSuccess = () => ({ type: actionTypes.LOGOUT_SUCCESS });
|
/*!
*
* JSource Javascript
*
* The MIT License (MIT)
*
* Copyright (c) 2014 Brandon Lee Kitajchuk
*
* 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.
*
*/
|
var GameOfLife = GameOfLife || {};
GameOfLife.Play = function () {};
GameOfLife.Play.prototype = {
create: function() {
this.game.stage.backgroundColor = "#00000";
this.cellsToLive = [];
this.cellsToDead = [];
// Create cell group
this.cellGroup = this.game.add.group();
this.generateWorldCells();
this.resetCell(25, 25);
this.resetCell(26, 25);
this.resetCell(26, 26);
this.resetCell(26, 27);
this.resetCell(27, 26);
},
update: function() {
this.cellsToDead.forEach(function(point) {
this.killCell(point[0], point[1]);
}, this);
this.cellsToLive.forEach(function(point) {
this.resetCell(point[0], point[1]);
}, this);
this.cellsToDead = [];
this.cellsToLive = [];
var cellsToCheck = this.getCellsToCheckLife();
_.compact(cellsToCheck).forEach(function(cell) {
this.checkLife(cell);
}, this);
console.log("generation complete");
},
getCellsToCheckLife: function(){
// We need the alive cells and their neighbours
var cellsToCheck = _(this.cellGroup.children).filter(function(cell){ return cell.alive; });
// Now we need to calculate the neighbours
cellsToCheck.forEach(function(cell) {
var neighboursPoints = this.getCellPointsAround(cell.x, cell.y);
neighboursPoints.forEach(function(points){
cellsToCheck.push(this.findCell(points[0], points[1]));
}, this);
}, this);
return cellsToCheck;
},
generateWorldCells: function(){
for(var i = 0; i < GameOfLife.width; i++) {
for(var j = 0; j < GameOfLife.height; j++) {
cell = this.generateCell(i, j);
cell.kill();
cell.alive = false;
}
}
},
checkLife: function(cell){
var cellsAround = 0;
var x = cell.x;
var y = cell.y;
var pointsToCheck = this.getCellPointsAround(x, y);
pointsToCheck.forEach(function(point) {
var cellAround = this.findCell(point[0], point[1]);
if ( cellAround && cellAround.alive && cellAround != cell ) {
cellsAround++;
if ( cellsAround >= 3 ){
return false;
}
}
}, this);
this.applyRules(cell, cellsAround);
},
// RULES
// Any live cell with fewer than two live neighbours dies, as if caused by under-population.
// Any live cell with two or three live neighbours lives on to the next generation.
// Any live cell with more than three live neighbours dies, as if by over-population.
// Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
applyRules: function(cell, cellsAround) {
if ( cell.alive && cellsAround < 2 ) {
this.cellsToDead.push([cell.x, cell.y]);
}
if ( cell.alive && cellsAround >= 2 && cellsAround <= 3 ) {
// nothing to do
}
if ( cell.alive && cellsAround > 3 ) {
this.cellsToDead.push([cell.x, cell.y]);
}
if ( !cell.alive && cellsAround === 3 ) {
this.cellsToLive.push([cell.x, cell.y]);
}
},
getCellPointsAround: function(x, y) {
return [
[x-1, y+1],
[x-1, y],
[x-1, y-1],
[x, y-1],
[x+1, y-1],
[x+1, y],
[x+1, y+1],
[x, y+1]
];
},
generateCell: function(x, y) {
cell = new GameOfLife.Cell(this.game, x, y);
this.cellGroup.add(cell);
return cell;
},
resetCell: function(x, y) {
var cell = this.findCell(x, y);
if ( cell ) {
cell.reset(x, y);
cell.alive = true;
}
},
killCell: function(x, y) {
var cell = this.findCell(x, y);
if ( cell ) {
cell.alive = false;
cell.kill();
}
},
findCell: function(x, y) {
return _(this.cellGroup.children).find(function(cell){ return cell.x == x && cell.y == y; });
},
// Auxiliar functions in order to create patterns
// Still lifes
generateBlock: function(x, y) {
var elementPoints = [[x, y], [x, y+1], [x+1, y], [x+1, y+1]];
elementPoints.forEach(function(point) {
this.resetCell(point[0], point[1]);
}, this);
},
generateLoaf: function(x, y) {
var elementPoints = [[x, y], [x+1, y+1], [x+2, y+2], [x+1, y-1], [x+2, y-1], [x+3, y], [x+3, y+1]];
elementPoints.forEach(function(point) {
this.resetCell(point[0], point[1]);
}, this);
},
generateBoat: function(x, y) {
var elementPoints = [[x, y], [x+1, y], [x, y+1], [x+2, y+1], [x+1, y+2]];
elementPoints.forEach(function(point) {
this.resetCell(point[0], point[1]);
}, this);
},
// Oscillators
generateBlinker: function(x, y) {
var elementPoints = [[x, y], [x-1, y], [x-2, y]];
elementPoints.forEach(function(point) {
this.resetCell(point[0], point[1]);
}, this);
},
generateToad: function(x, y){
var elementPoints = [[x, y], [x, y+1], [x+1, y+2], [x+2, y-1], [x+3, y], [x+3, y+1]];
elementPoints.forEach(function(point) {
this.resetCell(point[0], point[1]);
}, this);
},
generateBacon: function(x, y){
var elementPoints = [[x, y], [x, y+1], [x+1, y], [x+2, y+3], [x+3, y+3], [x+3, y+2]];
elementPoints.forEach(function(point) {
this.resetCell(point[0], point[1]);
}, this);
},
generatePulsar: function(x, y){
var elementPoints = [
[x, y+2], [x, y+3], [x, y+4], [x+2, y], [x+3, y], [x+4, y],
[x+2, y+5],[x+3, y+5],[x+4, y+5],[x+5, y+2],[x+5, y+3],[x+5, y+4],
[x+8, y], [x+9, y], [x+10, y], [x+7, y+2], [x+7, y+3], [x+7, y+4],
[x+8, y+5],[x+9, y+5],[x+10, y+5],[x+12, y+2],[x+12, y+3],[x+12, y+4],
[x, y+8], [x, y+9], [x, y+10], [x+2, y+7], [x+3, y+7], [x+4, y+7],
[x+2, y+12],[x+3, y+12],[x+4, y+12],[x+5, y+8],[x+5, y+9],[x+5, y+10],
[x+7, y+8], [x+7, y+9], [x+7, y+10], [x+8, y+7], [x+9, y+7], [x+10, y+7],
[x+8, y+12],[x+9, y+12],[x+10, y+12],[x+12, y+8],[x+12, y+9],[x+12, y+10],
];
elementPoints.forEach(function(point) {
this.resetCell(point[0], point[1]);
}, this);
},
generatePentadecathlon: function(x, y) {
var elementPoints = [
[x+1, y], [x+1, y+1], [x+1, y+2], [x, y+2], [x+2, y+2],
[x, y+5],[x+1, y+5],[x+2, y+5], [x+1, y+6], [x+1, y+6], [x+1, y+7],
[x+1, y+8], [x+1, y+9], [x+1, y+10], [x, y+10], [x+2, y+10],
[x, y+13], [x+1, y+13], [x+2, y+13], [x+1, y+14], [x+1, y+15],
];
elementPoints.forEach(function(point) {
this.resetCell(point[0], point[1]);
}, this);
},
// Spaceships
generateGlider: function(x, y) {
var elementPoints = [[x, y], [x+1, y], [x+2, y], [x+2, y-1], [x+1, y-2]];
elementPoints.forEach(function(point) {
this.resetCell(point[0], point[1]);
}, this);
},
generateLightweightSpaceship: function(x, y) {
var elementPoints = [
[x+1, y], [x+2, y], [x, y+1], [x, y+2], [x+1, y+1], [x+1, y+2],
[x+2, y+1],[x+3, y+1], [x+3, y+2], [x+4, y+2], [x+2, y+3], [x+3, y+2], [x+3, y+3]
];
elementPoints.forEach(function(point) {
this.resetCell(point[0], point[1]);
}, this);
}
};
|
var fs = null
, path = require('path')
, jsonFile = require('jsonfile')
, fse = {};
try {
// optional dependency
fs = require("graceful-fs")
} catch (er) {
fs = require("fs")
}
Object.keys(fs).forEach(function(key) {
var func = fs[key];
if (typeof func == 'function')
fse[key] = func;
});
fs = fse;
// copy
fs.copy = require('./copy').copy;
// remove
var remove = require('./remove');
fs.remove = remove.remove;
fs.removeSync = remove.removeSync;
fs['delete'] = fs.remove
fs.deleteSync = fs.removeSync
// mkdir
var mkdir = require('./mkdir')
fs.mkdirs = mkdir.mkdirs
fs.mkdirsSync = mkdir.mkdirsSync
fs.mkdirp = mkdir.mkdirs
fs.mkdirpSync = mkdir.mkdirsSync
// create
var create = require('./create')
fs.createFile = create.createFile;
fs.createFileSync = create.createFileSync;
//deprecated
fs.touch = function touch() {
console.log('fs.touch() is deprecated. Please use fs.createFile().')
fs.createFile.apply(null, arguments)
}
fs.touchSync = function touchSync() {
console.log('fs.touchSync() is deprecated. Please use fs.createFileSync().')
fs.createFileSync.apply(null, arguments)
}
// output
var output = require('./output');
fs.outputFile = output.outputFile;
fs.outputFileSync = output.outputFileSync;
// read
/*fs.readTextFile = function(file, callback) {
return fs.readFile(file, 'utf8', callback)
}
fs.readTextFileSync = function(file, callback) {
return fs.readFileSync(file, 'utf8')
}*/
// json files
fs.readJsonFile = jsonFile.readFile;
fs.readJSONFile = jsonFile.readFile;
fs.readJsonFileSync = jsonFile.readFileSync;
fs.readJSONFileSync = jsonFile.readFileSync;
fs.readJson = jsonFile.readFile;
fs.readJSON = jsonFile.readFile;
fs.readJsonSync = jsonFile.readFileSync;
fs.readJSONSync = jsonFile.readFileSync;
fs.writeJsonFile = jsonFile.writeFile;
fs.writeJSONFile = jsonFile.writeFile;
fs.writeJsonFileSync = jsonFile.writeFileSync;
fs.writeJSONFileSync = jsonFile.writeFileSync;
fs.writeJson = jsonFile.writeFile;
fs.writeJSON = jsonFile.writeFile;
fs.writeJsonSync = jsonFile.writeFileSync;
fs.writeJSONSync = jsonFile.writeFileSync;
module.exports = fs
jsonFile.spaces = 2; //set to 2
module.exports.jsonfile = jsonFile; //so users of fs-extra can modify jsonFile.spaces;
|
/* global process */
var ARGV = process.argv;
var DEBUG = +ARGV[2] >= 2;
var FILTER = ARGV[3] && ARGV[3].toLowerCase();
// console.log(ARGV);
var doTA = require('../dist/doTA' + (DEBUG ? '' : '.min'));
var templates = require('../fixtures/custom');
var timer = require('./timer');
timer(1);
for (var k in templates) {
if (FILTER && k.toLowerCase().indexOf(FILTER) === -1) { continue; }
var v = templates[k];
var fn = doTA.compile(v, {debug: 0, encode: 0, event: 1, strip: 1, optimize: 1, watchDiff: 1, diffLevel: 2});
console.log(k, v, v.length);
var fnStr = fn.toString();
console.log(fnStr, fnStr.length, '\n');
}
timer(1, 'compile');
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails oncall+relay
* @flow strict-local
* @format
*/
// flowlint ambiguous-object-type:error
'use strict';
const invariant = require('invariant');
const {
__internal: RelayRuntimeInternal,
createOperationDescriptor,
getRequest,
} = require('relay-runtime');
import type {
CacheConfig,
GraphQLTaggedNode,
IEnvironment,
Observable,
OperationType,
} from 'relay-runtime';
/**
* Fetches the given query and variables on the provided environment,
* and de-dupes identical in-flight requests.
*
* Observing a request:
* ====================
* fetchQuery returns an Observable which you can call .subscribe()
* on. Subscribe optionally takes an Observer, which you can provide to
* observe network events:
*
* ```
* fetchQuery(environment, query, variables).subscribe({
* // Called when network requests starts
* start: (subsctiption) => {},
*
* // Called after a payload is received and written to the local store
* next: (payload) => {},
*
* // Called when network requests errors
* error: (error) => {},
*
* // Called when network requests fully completes
* complete: () => {},
*
* // Called when network request is unsubscribed
* unsubscribe: (subscription) => {},
* });
* ```
*
* Request Promise:
* ================
* The obervable can be converted to a Promise with .toPromise(), which will
* resolve to a snapshot of the query data when the first response is received
* from the server.
*
* ```
* fetchQuery(environment, query, variables).then((data) => {
* // ...
* });
* ```
*
* In-flight request de-duping:
* ============================
* By default, calling fetchQuery multiple times with the same
* environment, query and variables will not initiate a new request if a request
* for those same parameters is already in flight.
*
* A request is marked in-flight from the moment it starts until the moment it
* fully completes, regardless of error or successful completion.
*
* NOTE: If the request completes _synchronously_, calling fetchQuery
* a second time with the same arguments in the same tick will _NOT_ de-dupe
* the request given that it will no longer be in-flight.
*
*
* Data Retention:
* ===============
* This function will NOT retain query data, meaning that it is not guaranteed
* that the fetched data will remain in the Relay store after the request has
* completed.
* If you need to retain the query data outside of the network request,
* you need to use `environment.retain()`.
*
*
* Cancelling requests:
* ====================
* If the disposable returned by subscribe is called while the
* request is in-flight, the request will be cancelled.
*
* ```
* const disposable = fetchQuery(...).subscribe(...);
*
* // This will cancel the request if it is in-flight.
* disposable.dispose();
* ```
* NOTE: When using .toPromise(), the request cannot be cancelled.
*/
function fetchQuery<TQuery: OperationType>(
environment: IEnvironment,
query: GraphQLTaggedNode,
variables: $ElementType<TQuery, 'variables'>,
options?: {|
networkCacheConfig?: CacheConfig,
|},
): Observable<$ElementType<TQuery, 'response'>> {
const queryNode = getRequest(query);
invariant(
queryNode.params.operationKind === 'query',
'fetchQuery: Expected query operation',
);
const operation = createOperationDescriptor(queryNode, variables);
const networkCacheConfig = {
force: true,
...options?.networkCacheConfig,
};
return RelayRuntimeInternal.fetchQuery(environment, operation, {
networkCacheConfig,
}).map(() => environment.lookup(operation.fragment).data);
}
module.exports = fetchQuery;
|
/** Schema des donnees de combat du gladiateur */
Schema.Domains = new SimpleSchema({
'name': {
type: String,
label: "Domaine",
index: true,
unique: true,
min: 3,
max: 30
},
'desc': {
type: String,
label: "Description",
min: 1,
max: 300
},
'createdAt': {
type: Date,
label: "Date de création",
optional: true
},
'updatedAt': {
type: Date,
label: "Date de modification",
optional: true
}
});
|
(function(d){"function"===typeof $define?$define(["Nex.jqueryui.Core"],function(){d(jQuery)}):d(jQuery)})(function(d){d.widget("ui.tooltip",{version:"1.11.3",options:{content:function(){var a=d(this).attr("title")||"";return d("<a>").text(a).html()},hide:!0,items:"[title]:not([disabled])",position:{my:"left top+15",at:"left bottom",collision:"flipfit flip"},show:!0,tooltipClass:null,track:!1,close:null,open:null},_addDescribedBy:function(a,c){var b=(a.attr("aria-describedby")||"").split(/\s+/);b.push(c);
a.data("ui-tooltip-id",c).attr("aria-describedby",d.trim(b.join(" ")))},_removeDescribedBy:function(a){var c=a.data("ui-tooltip-id"),b=(a.attr("aria-describedby")||"").split(/\s+/),c=d.inArray(c,b);-1!==c&&b.splice(c,1);a.removeData("ui-tooltip-id");(b=d.trim(b.join(" ")))?a.attr("aria-describedby",b):a.removeAttr("aria-describedby")},_create:function(){this._on({mouseover:"open",focusin:"open"});this.tooltips={};this.parents={};this.options.disabled&&this._disable();this.liveRegion=d("<div>").attr({role:"log",
"aria-live":"assertive","aria-relevant":"additions"}).addClass("ui-helper-hidden-accessible").appendTo(this.document[0].body)},_setOption:function(a,c){var b=this;"disabled"===a?(this[c?"_disable":"_enable"](),this.options[a]=c):(this._super(a,c),"content"===a&&d.each(this.tooltips,function(a,c){b._updateContent(c.element)}))},_disable:function(){var a=this;d.each(this.tooltips,function(c,b){var e=d.Event("blur");e.target=e.currentTarget=b.element[0];a.close(e,!0)});this.element.find(this.options.items).addBack().each(function(){var a=
d(this);a.is("[title]")&&a.data("ui-tooltip-title",a.attr("title")).removeAttr("title")})},_enable:function(){this.element.find(this.options.items).addBack().each(function(){var a=d(this);a.data("ui-tooltip-title")&&a.attr("title",a.data("ui-tooltip-title"))})},open:function(a){var c=this,b=d(a?a.target:this.element).closest(this.options.items);b.length&&!b.data("ui-tooltip-id")&&(b.attr("title")&&b.data("ui-tooltip-title",b.attr("title")),b.data("ui-tooltip-open",!0),a&&"mouseover"===a.type&&b.parents().each(function(){var a=
d(this),b;a.data("ui-tooltip-open")&&(b=d.Event("blur"),b.target=b.currentTarget=this,c.close(b,!0));a.attr("title")&&(a.uniqueId(),c.parents[this.id]={element:this,title:a.attr("title")},a.attr("title",""))}),this._updateContent(b,a))},_updateContent:function(a,c){var b;b=this.options.content;var d=this,f=c?c.type:null;if("string"===typeof b)return this._open(c,a,b);(b=b.call(a[0],function(b){a.data("ui-tooltip-open")&&d._delay(function(){c&&(c.type=f);this._open(c,a,b)})}))&&this._open(c,a,b)},
_open:function(a,c,b){function e(a){h.of=a;g.is(":hidden")||g.position(h)}var f,g,k,h=d.extend({},this.options.position);b&&((f=this._find(c))?f.tooltip.find(".ui-tooltip-content").html(b):(c.is("[title]")&&(a&&"mouseover"===a.type?c.attr("title",""):c.removeAttr("title")),f=this._tooltip(c),g=f.tooltip,this._addDescribedBy(c,g.attr("id")),g.find(".ui-tooltip-content").html(b),this.liveRegion.children().hide(),b.clone&&(b=b.clone(),b.removeAttr("id").find("[id]").removeAttr("id")),d("<div>").html(b).appendTo(this.liveRegion),
this.options.track&&a&&/^mouse/.test(a.type)?(this._on(this.document,{mousemove:e}),e(a)):g.position(d.extend({of:c},this.options.position)),g.hide(),this._show(g,this.options.show),this.options.show&&this.options.show.delay&&(k=this.delayedShow=setInterval(function(){g.is(":visible")&&(e(h.of),clearInterval(k))},d.fx.interval)),this._trigger("open",a,{tooltip:g}),b={keyup:function(a){a.keyCode===d.ui.keyCode.ESCAPE&&(a=d.Event(a),a.currentTarget=c[0],this.close(a,!0))}},c[0]!==this.element[0]&&(b.remove=
function(){this._removeTooltip(g)}),a&&"mouseover"!==a.type||(b.mouseleave="close"),a&&"focusin"!==a.type||(b.focusout="close"),this._on(!0,c,b)))},close:function(a){var c,b=this,e=d(a?a.currentTarget:this.element),f=this._find(e);f&&(c=f.tooltip,f.closing||(clearInterval(this.delayedShow),e.data("ui-tooltip-title")&&!e.attr("title")&&e.attr("title",e.data("ui-tooltip-title")),this._removeDescribedBy(e),f.hiding=!0,c.stop(!0),this._hide(c,this.options.hide,function(){b._removeTooltip(d(this))}),e.removeData("ui-tooltip-open"),
this._off(e,"mouseleave focusout keyup"),e[0]!==this.element[0]&&this._off(e,"remove"),this._off(this.document,"mousemove"),a&&"mouseleave"===a.type&&d.each(this.parents,function(a,c){d(c.element).attr("title",c.title);delete b.parents[a]}),f.closing=!0,this._trigger("close",a,{tooltip:c}),f.hiding||(f.closing=!1)))},_tooltip:function(a){var c=d("<div>").attr("role","tooltip").addClass("ui-tooltip ui-widget ui-corner-all ui-widget-content "+(this.options.tooltipClass||"")),b=c.uniqueId().attr("id");
d("<div>").addClass("ui-tooltip-content").appendTo(c);c.appendTo(this.document[0].body);return this.tooltips[b]={element:a,tooltip:c}},_find:function(a){return(a=a.data("ui-tooltip-id"))?this.tooltips[a]:null},_removeTooltip:function(a){a.remove();delete this.tooltips[a.attr("id")]},_destroy:function(){var a=this;d.each(this.tooltips,function(c,b){var e=d.Event("blur"),f=b.element;e.target=e.currentTarget=f[0];a.close(e,!0);d("#"+c).remove();f.data("ui-tooltip-title")&&(f.attr("title")||f.attr("title",
f.data("ui-tooltip-title")),f.removeData("ui-tooltip-title"))});this.liveRegion.remove()}})});
|
import { NodeComponent, FontAwesomeIcon as Icon } from 'substance'
/*
Edit affiliations for a publication in this MetadataSection
*/
export default class AffiliationsComponent extends NodeComponent {
render($$) {
const affGroup = this.props.node
const TextPropertyEditor = this.getComponent('text-property-editor')
let el = $$('div').addClass('sc-affiliations')
affGroup.getChildren().forEach((aff) => {
let stringAff = aff.findChild('string-aff')
// at the moment we only render string-affs
if (stringAff) {
el.append(
$$('div').addClass('se-aff').append(
$$(TextPropertyEditor, {
placeholder: 'Enter affiliation title',
path: stringAff.getTextPath(),
disabled: this.props.disabled
}).addClass('se-text-input').ref(stringAff.id),
$$('div').addClass('se-remove-aff').append(
$$(Icon, { icon: 'fa-trash' })
).on('click', this._removeAffiliation.bind(this, aff.id))
)
)
}
})
el.append(
$$('button').addClass('se-metadata-affiliation-add')
.append('Add Affiliation')
.on('click', this._addAffiliation)
)
return el
}
_addAffiliation() {
const nodeId = this.props.node.id
const editorSession = this.context.editorSession
editorSession.transaction((doc) => {
let affGroup = doc.get(nodeId)
let aff = doc.createElement('aff').attr('aff-type', 'foo')
aff.append(
doc.createElement('string-aff')
)
affGroup.append(aff)
})
}
_removeAffiliation(affId) {
const nodeId = this.props.node.id
const editorSession = this.context.editorSession
editorSession.transaction((doc) => {
const affGroup = doc.get(nodeId)
let aff = affGroup.find(`aff#${affId}`)
affGroup.removeChild(aff)
})
}
}
|
'use strict';
import forOwn from 'lodash/object/forOwn';
import assign from 'lodash/object/assign';
import functions from 'lodash/function';
import bind from './bind/bind';
import tap from './tap';
import bindAll from './bind/bindAll';
import { createDecorator, createInstanceDecorator } from './decoratorFactory';
import { applicators } from './Applicator';
import normalizeExport from './utils/normalizeExport';
const methods = {
instance: {
single: [
'once'
],
pre: [
'debounce',
'throttle',
'memoize'
],
post: [
'after',
'before'
]
},
proto: {
single: [
'spread',
'rearg',
'negate'
],
pre: [
'modArgs',
'ary',
'curry',
'curryRight',
'restParam'
],
partial: [
'partial',
'partialRight'
],
wrap: [
'wrap'
],
compose: [
'compose',
'flow',
'flowRight',
'backflow'
],
partialed: [
'delay',
'defer'
]
}
};
let result = {};
forOwn(methods, (hash, createType) => {
forOwn(hash, (list, type) => {
result = list.reduce((res, fnName) => {
res[fnName] = createType === 'instance'
? createInstanceDecorator(functions[fnName], applicators[type])
: createDecorator(functions[fnName], applicators[type]);
return res;
}, result);
});
});
// All other decorators
assign(result, {
bind,
tap,
bindAll
});
export default normalizeExport(result);
|
/* global Laravel,moment,$w,$body */
(function($){
'use strict';
if (Laravel.locale === 'hu')
moment.locale('hu');
// document.createElement shortcut
window.mk = function(){ return document.createElement.apply(document,arguments) };
// $(document.createElement) shortcut
$.mk = (name, id) => {
let $el = $(document.createElement.call(document,name));
if (typeof id === 'string')
$el.attr('id', id);
return $el;
};
// Globalize common elements
window.$w = $(window);
window.$d = $(document);
window.CommonElements = function(){
window.$header = $('header');
window.$main = $('#main');
window.$footer = $('footer');
window.$body = $('body');
window.$head = $('head');
};
window.CommonElements();
// Common key codes for easy reference
window.Key = {
Enter: 13,
Esc: 27,
Space: 32,
PageUp: 33,
PageDown: 34,
LeftArrow: 37,
UpArrow: 38,
RightArrow: 39,
DownArrow: 40,
Delete: 46,
Backspace: 8,
Tab: 9,
Comma: 188,
Period: 190,
};
$.isKey = function(Key, e){
return e.keyCode === Key;
};
// Time class
(function($){
let dateformat = { order: 'Do MMMM YYYY, H:mm:ss' };
dateformat.orderwd = `dddd, ${dateformat.order}`;
class DateFormatError extends Error {
constructor(message, element){
super(message);
this.name = 'DateFormatError';
this.element = element;
}
}
class Time {
static Update(){
$('time[datetime]:not(.nodt)').addClass('dynt').each(function(){
let $this = $(this),
date = $this.attr('datetime');
if (typeof date !== 'string') throw new TypeError('Invalid date data type: "'+(typeof date)+'"');
let Timestamp = moment(date);
if (!Timestamp.isValid())
throw new DateFormatError('Invalid date format: "'+date+'"', this);
let Now = moment(),
showDayOfWeek = !$this.attr('data-noweekday'),
timeAgoStr = Timestamp.from(Now),
$elapsedHolder = $this.parent().children('.dynt-el'),
updateHandler = $this.data('dyntime-beforeupdate');
if (typeof updateHandler === 'function'){
let result = updateHandler(Time.Difference(Now.toDate(), Timestamp.toDate()));
if (result === false) return;
}
if ($elapsedHolder.length > 0 || $this.hasClass('no-dynt-el')){
$this.html(Timestamp.format(showDayOfWeek ? dateformat.orderwd : dateformat.order));
$elapsedHolder.html(timeAgoStr);
}
else $this.attr('title', Timestamp.format(dateformat.order)).html(timeAgoStr);
});
}
static Difference(now, timestamp) {
let substract = (now.getTime() - timestamp.getTime())/1000,
d = {
past: substract > 0,
time: Math.abs(substract),
target: timestamp
},
time = d.time;
d.day = Math.floor(time/this.InSeconds.day);
time -= d.day * this.InSeconds.day;
d.hour = Math.floor(time/this.InSeconds.hour);
time -= d.hour * this.InSeconds.hour;
d.minute = Math.floor(time/this.InSeconds.minute);
time -= d.minute * this.InSeconds.minute;
d.second = Math.floor(time);
if (d.day >= 7){
d.week = Math.floor(d.day/7);
d.day -= d.week*7;
}
if (d.week >= 4){
d.month = Math.floor(d.week/4);
d.week -= d.month*4;
}
if (d.month >= 12){
d.year = Math.floor(d.month/12);
d.month -= d.year*12;
}
return d;
}
}
Time.InSeconds = {
'year': 31557600,
'month': 2592000,
'week': 604800,
'day': 86400,
'hour': 3600,
'minute': 60,
};
window.Time = Time;
Time.Update();
setInterval(Time.Update, 10e3);
})(jQuery);
// Make the first letter of the first or all word(s) uppercase
$.capitalize = (str, all) => {
if (all) return str.replace(/((?:^|\s)[a-z])/g, match => match.toUpperCase());
else return str.length === 1 ? str.toUpperCase() : str[0].toUpperCase()+str.substring(1);
};
$.strRepeat = (str, times = 1) => new Array(times+1).join(str);
$.pad = function(str, char, len, dir){
if (typeof str !== 'string')
str = ''+str;
if (typeof char !== 'string')
char = '0';
if (typeof len !== 'number' && !isFinite(len) && isNaN(len))
len = 2;
else len = parseInt(len, 10);
if (typeof dir !== 'boolean')
dir = true;
if (len <= str.length)
return str;
const padstr = new Array(len-str.length+1).join(char);
str = dir === $.pad.left ? padstr+str : str+padstr;
return str;
};
$.pad.right = !($.pad.left = true);
$.toArray = (args, n = 0) => [].slice.call(args, n);
// Create AJAX response handling function
$w.on('ajaxerror',function(){
let details = '';
if (arguments.length > 1){
let data = $.toArray(arguments, 1);
if (data[1] === 'abort')
return;
details = ' Details:<pre><code>' + data.slice(1).join('\n').replace(/</g,'<') + '</code></pre>Response body:';
let xdebug = /^(?:<br \/>\n)?(<pre class='xdebug-var-dump'|<font size='1')/;
if (xdebug.test(data[0].responseText))
details += `<div class="reset">${data[0].responseText.replace(xdebug, '$1')}</div>`;
else if (typeof data[0].responseText === 'string')
details += `<pre><code>${data[0].responseText.replace(/</g,'<')}</code></pre>`;
}
$.Dialog.fail(false,`There was an error while processing your request.${details}`);
});
$.mkAjaxHandler = function(f){
return function(data){
if (typeof data !== 'object'){
//noinspection SSBasedInspection
console.log(data);
$w.triggerHandler('ajaxerror');
return;
}
if (typeof f === 'function') f.call(data);
};
};
// Checks if a variable is a function and if yes, runs it
// If no, returns default value (undefined or value of def)
$.callCallback = (func, params, def) => {
if (typeof params !== 'object' || !$.isArray(params)){
def = params;
params = [];
}
if (typeof func !== 'function')
return def;
return func.apply(window, params);
};
// Convert .serializeArray() result to object
$.fn.mkData = function(obj){
let tempdata = $(this).serializeArray(), data = {};
$.each(tempdata,function(i,el){
data[el.name] = el.value;
});
if (typeof obj === 'object')
$.extend(data, obj);
return data;
};
// Get CSRF token
$.getCSRFToken = function(){
let n = document.cookie.match(/MLPNOW-XSRF-TOKEN=([^;]+)/i);
if (n && n.length)
return n[1];
else throw new Error('Missing XSRF-TOKEN');
};
let lasturl,
statusCodeHandlers = {
404: function(){
$.Dialog.fail(false, window.Laravel.ajaxErrors[404].replace(':endpoint',lasturl.replace(/</g,'<').replace(/\//g,'/<wbr>')));
},
500: function(){
$.Dialog.fail(false, window.Laravel.ajaxErrors[500]);
},
503: function(){
$.Dialog.fail(false, window.Laravel.ajaxErrors[503]);
}
};
$.ajaxSetup({
dataType: "json",
error: function(xhr){
if (typeof statusCodeHandlers[xhr.status] !== 'function')
$w.triggerHandler('ajaxerror',$.toArray(arguments));
$body.removeClass('loading');
},
beforeSend: function(_, settings){
lasturl = settings.url;
},
statusCode: statusCodeHandlers,
headers: { 'X-CSRF-TOKEN': $.getCSRFToken() }
});
// Copy any text to clipboard
// Must be called from within an event handler
let $notif;
$.copy = (text, e) => {
if (!document.queryCommandSupported('copy')){
prompt('Copy with Ctrl+C, close with Enter', text);
return true;
}
let $helper = $.mk('textarea'),
success = false;
$helper
.css({
opacity: 0,
width: 0,
height: 0,
position: 'fixed',
left: '-10px',
top: '50%',
display: 'block',
})
.text(text)
.appendTo('body')
.focus();
$helper.get(0).select();
try {
success = document.execCommand('copy');
} catch(err){}
setTimeout(function(){
$helper.remove();
if (typeof $notif === 'undefined' || e){
if (typeof $notif === 'undefined')
$notif = $.mk('span')
.attr({
id: 'copy-notify',
'class': ! success ? 'fail' : undefined,
})
.html('<span class="glyphicon glyphicon-copy"></span> <span class="glyphicon glyphicon-'+(success?'ok':'remove')+'"></span>')
.appendTo($body);
if (e){
let w = $notif.outerWidth(),
h = $notif.outerHeight(),
top = e.clientY - (h/2);
return $notif.stop().css({
top: top,
left: (e.clientX - (w/2)),
bottom: 'initial',
right: 'initial',
opacity: 1,
}).animate({top: top-20, opacity: 0}, 1000, function(){
$(this).remove();
$notif = undefined;
});
}
$notif.fadeTo('fast',1);
}
else $notif.stop().css('opacity',1);
$notif.delay(success ? 300 : 1000).fadeTo('fast',0,function(){
$(this).remove();
$notif = undefined;
});
}, 1);
};
$.fn.toggleHtml = function(contentArray){
return this.html(contentArray[$.rangeLimit(contentArray.indexOf(this.html())+1, true, contentArray.length-1)]);
};
$.fn.enable = function(){
return this.attr('disabled', false);
};
$.fn.disable = function(){
return this.attr('disabled', true);
};
$.fn.htmlIfNotMatches = function(newHtml){
if (this.html() !== newHtml)
this.html(newHtml);
return this;
};
$.roundTo = (number, precision) => {
let pow = Math.pow(10, precision);
return Math.round(number*pow)/pow;
};
$.rangeLimit = function(input, overflow){
let min, max, paramCount = 2;
switch (arguments.length-paramCount){
case 1:
min = 0;
max = arguments[paramCount];
break;
case 2:
min = arguments[paramCount];
max = arguments[paramCount+1];
break;
default:
throw new Error('Invalid number of parameters for $.rangeLimit');
}
if (overflow){
if (input > max)
input = min;
else if (input < min)
input = max;
}
return Math.min(max, Math.max(min, input));
};
$.translatePlaceholders = (string, params)=>{
$.each(params, (k,v)=>{
string = string.replace(new RegExp(':'+k,'g'),v);
});
return string;
};
})(jQuery);
|
// Regular expression that matches all symbols in the Avestan block as per Unicode v8.0.0:
/\uD802[\uDF00-\uDF3F]/;
|
/** Class represents a view */
import { Component } from './component';
class LinearGradient extends Component {
tag(instance) {
let tag = instance || document.createElement('div');
tag.style.background = `linear-gradient(0deg, ${this.props.colors[0]}, ${
this.props.colors[1]
})`;
return tag;
}
}
export { LinearGradient };
|
app.service('loginService', function ($q) {
Parse.Object.extend({
className: "User",
attrs: ['profileImg']
});
return {
login: function () {
var dfd = $q.defer();
if (this.isLoggedIn()) {
dfd.resolve(true);
return dfd.promise;
}
// Run code after the Facebook SDK is loaded.
Parse.FacebookUtils.logIn('email', {
success: function (user) {
userJson = angular.fromJson(user.get('authData'));
var faceBookUserId = userJson.facebook.id;
var email = userJson.facebook.email;
console.log('facebook id ' + faceBookUserId);
var profileImg = '//graph.facebook.com/' + faceBookUserId + '/picture';
user.set('profileImg', profileImg);
user.set('email',email);
user.save();
dfd.resolve(true);
},
error: function (user, error) {
dfd.reject(false);
}
});
return dfd.promise;
},
isLoggedIn: function () {
if (Parse.User.current()) {
return true;
}
else {
return false;
}
},
logout: function () {
if (this.isLoggedIn()) {
Parse.User.logOut();
}
return;
},
getUserImg: function () {
if (this.isLoggedIn()) {
return Parse.User.current().get('profileImg');
}
return null;
}
}
})
|
/*global defineSuite*/
defineSuite([
'Core/IntersectionTests',
'Core/Cartesian3',
'Core/Ellipsoid',
'Core/Math',
'Core/Plane',
'Core/Ray'
], function(
IntersectionTests,
Cartesian3,
Ellipsoid,
CesiumMath,
Plane,
Ray) {
"use strict";
/*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn,runs,waits,waitsFor*/
it('rayPlane intersects', function() {
var ray = new Ray(new Cartesian3(2.0, 0.0, 0.0), new Cartesian3(-1.0, 0.0, 0.0));
var plane = new Plane(Cartesian3.UNIT_X, -1.0);
var intersectionPoint = IntersectionTests.rayPlane(ray, plane);
expect(intersectionPoint).toEqual(new Cartesian3(1.0, 0.0, 0.0));
});
it('rayPlane misses', function() {
var ray = new Ray(new Cartesian3(2.0, 0.0, 0.0), new Cartesian3(1.0, 0.0, 0.0));
var plane = new Plane(Cartesian3.UNIT_X, -1.0);
var intersectionPoint = IntersectionTests.rayPlane(ray, plane);
expect(intersectionPoint).not.toBeDefined();
});
it('rayPlane misses (parallel)', function() {
var ray = new Ray(new Cartesian3(2.0, 0.0, 0.0), new Cartesian3(0.0, 1.0, 0.0));
var plane = new Plane(Cartesian3.UNIT_X, -1.0);
var intersectionPoint = IntersectionTests.rayPlane(ray, plane);
expect(intersectionPoint).not.toBeDefined();
});
it('rayPlane throws without ray', function() {
expect(function() {
IntersectionTests.rayPlane();
}).toThrowDeveloperError();
});
it('rayPlane throws without plane', function() {
expect(function() {
IntersectionTests.rayPlane(new Ray(new Cartesian3(), new Cartesian3()));
}).toThrowDeveloperError();
});
it('rayEllipsoid throws without ray', function() {
expect(function() {
IntersectionTests.rayEllipsoid();
}).toThrowDeveloperError();
});
it('rayEllipsoid throws without ellipsoid', function() {
expect(function() {
IntersectionTests.rayEllipsoid(new Ray(new Cartesian3(), new Cartesian3()));
}).toThrowDeveloperError();
});
it('rayEllipsoid outside intersections', function() {
var unitSphere = Ellipsoid.UNIT_SPHERE;
var ray = new Ray(new Cartesian3(2.0, 0.0, 0.0), new Cartesian3(-1.0, 0.0, 0.0));
var intersections = IntersectionTests.rayEllipsoid(ray, unitSphere);
expect(intersections.start).toEqualEpsilon(1.0, CesiumMath.EPSILON14);
expect(intersections.stop).toEqualEpsilon(3.0, CesiumMath.EPSILON14);
ray = new Ray(new Cartesian3(0.0, 2.0, 0.0), new Cartesian3(0.0, -1.0, 0.0));
intersections = IntersectionTests.rayEllipsoid(ray, unitSphere);
expect(intersections.start).toEqualEpsilon(1.0, CesiumMath.EPSILON14);
expect(intersections.stop).toEqualEpsilon(3.0, CesiumMath.EPSILON14);
ray = new Ray(new Cartesian3(0.0, 0.0, 2.0), new Cartesian3(0.0, 0.0, -1.0));
intersections = IntersectionTests.rayEllipsoid(ray, unitSphere);
expect(intersections.start).toEqualEpsilon(1.0, CesiumMath.EPSILON14);
expect(intersections.stop).toEqualEpsilon(3.0, CesiumMath.EPSILON14);
ray = new Ray(new Cartesian3(1.0, 1.0, 0.0), new Cartesian3(-1.0, 0.0, 0.0));
intersections = IntersectionTests.rayEllipsoid(ray, unitSphere);
expect(intersections.start).toEqualEpsilon(1.0, CesiumMath.EPSILON14);
ray = new Ray(new Cartesian3(-2.0, 0.0, 0.0), new Cartesian3(1.0, 0.0, 0.0));
intersections = IntersectionTests.rayEllipsoid(ray, unitSphere);
expect(intersections.start).toEqualEpsilon(1.0, CesiumMath.EPSILON14);
expect(intersections.stop).toEqualEpsilon(3.0, CesiumMath.EPSILON14);
ray = new Ray(new Cartesian3(0.0, -2.0, 0.0), new Cartesian3(0.0, 1.0, 0.0));
intersections = IntersectionTests.rayEllipsoid(ray, unitSphere);
expect(intersections.start).toEqualEpsilon(1.0, CesiumMath.EPSILON14);
expect(intersections.stop).toEqualEpsilon(3.0, CesiumMath.EPSILON14);
ray = new Ray(new Cartesian3(0.0, 0.0, -2.0), new Cartesian3(0.0, 0.0, 1.0));
intersections = IntersectionTests.rayEllipsoid(ray, unitSphere);
expect(intersections.start).toEqualEpsilon(1.0, CesiumMath.EPSILON14);
expect(intersections.stop).toEqualEpsilon(3.0, CesiumMath.EPSILON14);
ray = new Ray(new Cartesian3(-1.0, -1.0, 0.0), new Cartesian3(1.0, 0.0, 0.0));
intersections = IntersectionTests.rayEllipsoid(ray, unitSphere);
expect(intersections.start).toEqualEpsilon(1.0, CesiumMath.EPSILON14);
ray = new Ray(new Cartesian3(-2.0, 0.0, 0.0), new Cartesian3(-1.0, 0.0, 0.0));
intersections = IntersectionTests.rayEllipsoid(ray, unitSphere);
expect(intersections).toBeUndefined();
ray = new Ray(new Cartesian3(0.0, -2.0, 0.0), new Cartesian3(0.0, -1.0, 0.0));
intersections = IntersectionTests.rayEllipsoid(ray, unitSphere);
expect(intersections).toBeUndefined();
ray = new Ray(new Cartesian3(0.0, 0.0, -2.0), new Cartesian3(0.0, 0.0, -1.0));
intersections = IntersectionTests.rayEllipsoid(ray, unitSphere);
expect(intersections).toBeUndefined();
});
it('rayEllipsoid ray inside pointing in intersection', function() {
var ellipsoid = Ellipsoid.WGS84;
var origin = new Cartesian3(20000.0, 0.0, 0.0);
var direction = Cartesian3.negate(Cartesian3.normalize(origin, new Cartesian3()), new Cartesian3());
var ray = new Ray(origin, direction);
var expected = {
start : 0.0,
stop : ellipsoid.radii.x + origin.x
};
var actual = IntersectionTests.rayEllipsoid(ray, ellipsoid);
expect(actual).toBeDefined();
expect(actual.start).toEqual(expected.start);
expect(actual.stop).toEqual(expected.stop);
});
it('rayEllipsoid ray inside pointing out intersection', function() {
var ellipsoid = Ellipsoid.WGS84;
var origin = new Cartesian3(20000.0, 0.0, 0.0);
var direction = Cartesian3.normalize(origin, new Cartesian3());
var ray = new Ray(origin, direction);
var expected = {
start : 0.0,
stop : ellipsoid.radii.x - origin.x
};
var actual = IntersectionTests.rayEllipsoid(ray, ellipsoid);
expect(actual).toBeDefined();
expect(actual.start).toEqual(expected.start);
expect(actual.stop).toEqual(expected.stop);
});
it('rayEllipsoid tangent intersections', function() {
var unitSphere = Ellipsoid.UNIT_SPHERE;
var ray = new Ray(Cartesian3.UNIT_X, Cartesian3.UNIT_Z);
var intersections = IntersectionTests.rayEllipsoid(ray, unitSphere);
expect(intersections).not.toBeDefined();
});
it('rayEllipsoid no intersections', function() {
var unitSphere = Ellipsoid.UNIT_SPHERE;
var ray = new Ray(new Cartesian3(2.0, 0.0, 0.0), new Cartesian3(0.0, 0.0, 1.0));
var intersections = IntersectionTests.rayEllipsoid(ray, unitSphere);
expect(intersections).not.toBeDefined();
ray = new Ray(new Cartesian3(2.0, 0.0, 0.0), new Cartesian3(0.0, 0.0, -1.0));
intersections = IntersectionTests.rayEllipsoid(ray, unitSphere);
expect(intersections).not.toBeDefined();
ray = new Ray(new Cartesian3(2.0, 0.0, 0.0), new Cartesian3(0.0, 1.0, 0.0));
intersections = IntersectionTests.rayEllipsoid(ray, unitSphere);
expect(intersections).not.toBeDefined();
ray = new Ray(new Cartesian3(2.0, 0.0, 0.0), new Cartesian3(0.0, -1.0, 0.0));
intersections = IntersectionTests.rayEllipsoid(ray, unitSphere);
expect(intersections).not.toBeDefined();
});
it('grazingAltitudeLocation throws without ray', function() {
expect(function() {
IntersectionTests.grazingAltitudeLocation();
}).toThrowDeveloperError();
});
it('grazingAltitudeLocation throws without ellipsoid', function() {
expect(function() {
IntersectionTests.grazingAltitudeLocation(new Ray());
}).toThrowDeveloperError();
});
it('grazingAltitudeLocation is origin of ray', function() {
var ellipsoid = Ellipsoid.UNIT_SPHERE;
var ray = new Ray(new Cartesian3(3.0, 0.0, 0.0), Cartesian3.UNIT_X);
expect(IntersectionTests.grazingAltitudeLocation(ray, ellipsoid)).toEqual(ray.origin);
});
it('grazingAltitudeLocation outside ellipsoid', function() {
var ellipsoid = Ellipsoid.UNIT_SPHERE;
var ray = new Ray(new Cartesian3(-2.0, -2.0, 0.0), Cartesian3.UNIT_X);
var expected = new Cartesian3(0.0, -2.0, 0.0);
var actual = IntersectionTests.grazingAltitudeLocation(ray, ellipsoid);
expect(actual).toEqualEpsilon(expected, CesiumMath.EPSILON15);
ray = new Ray(new Cartesian3(0.0, 2.0, 2.0), Cartesian3.negate(Cartesian3.UNIT_Y, new Cartesian3()));
expected = new Cartesian3(0.0, 0.0, 2.0);
actual = IntersectionTests.grazingAltitudeLocation(ray, ellipsoid);
expect(actual).toEqualEpsilon(expected, CesiumMath.EPSILON15);
});
it('grazingAltitudeLocation outside ellipsoid 2', function() {
var ellipsoid = Ellipsoid.WGS84;
var origin = new Cartesian3(6502435.411150063, -6350860.759819263, -7230794.954832983);
var direction = new Cartesian3(-0.6053473557455881, 0.002372596412575323, 0.7959578818493397);
var ray = new Ray(origin, direction);
var expected = new Cartesian3(628106.8386515155, -6327836.936616249, 493230.07552381355);
var actual = IntersectionTests.grazingAltitudeLocation(ray, ellipsoid);
expect(actual).toEqualEpsilon(expected, CesiumMath.EPSILON8);
});
it('grazingAltitudeLocation outside ellipsoid 3', function() {
var ellipsoid = Ellipsoid.WGS84;
var origin = new Cartesian3(-6546204.940468501, -10625195.62660887, -6933745.82875373);
var direction = new Cartesian3(0.5130076305689283, 0.38589525779680295, 0.766751603185799);
var ray = new Ray(origin, direction);
var expected = new Cartesian3(-125.9063174739769, -5701095.640722358, 2850156.57342018);
var actual = IntersectionTests.grazingAltitudeLocation(ray, ellipsoid);
expect(actual).toEqualEpsilon(expected, CesiumMath.EPSILON10);
});
it('grazingAltitudeLocation inside ellipsoid', function() {
var ellipsoid = Ellipsoid.UNIT_SPHERE;
var ray = new Ray(new Cartesian3(0.5, 0.0, 0.0), Cartesian3.UNIT_Z);
var actual = IntersectionTests.grazingAltitudeLocation(ray, ellipsoid);
expect(actual).toEqual(ray.origin);
});
it('grazingAltitudeLocation is undefined', function() {
var ellipsoid = Ellipsoid.UNIT_SPHERE;
var ray = new Ray(Cartesian3.ZERO, Cartesian3.UNIT_Z);
expect(IntersectionTests.grazingAltitudeLocation(ray, ellipsoid)).not.toBeDefined();
});
it('lineSegmentPlane intersects', function() {
var normal = Cartesian3.clone(Cartesian3.UNIT_Y);
var point = new Cartesian3(0.0, 2.0, 0.0);
var plane = Plane.fromPointNormal(point, normal);
var endPoint0 = new Cartesian3(1.0, 1.0, 0.0);
var endPoint1 = new Cartesian3(1.0, 3.0, 0.0);
var intersectionPoint = IntersectionTests.lineSegmentPlane(endPoint0, endPoint1, plane);
expect(intersectionPoint).toEqual(new Cartesian3(1.0, 2.0, 0.0));
});
it('lineSegmentPlane misses (entire segment behind plane)', function() {
var plane = new Plane(Cartesian3.UNIT_X, 0.0);
var endPoint0 = new Cartesian3(-2.0, 0.0, 0.0);
var endPoint1 = new Cartesian3(-5.0, 0.0, 0.0);
var intersectionPoint = IntersectionTests.lineSegmentPlane(endPoint0, endPoint1, plane);
expect(intersectionPoint).not.toBeDefined();
});
it('lineSegmentPlane misses (entire segment in front of plane)', function() {
var plane = new Plane(Cartesian3.UNIT_X, 0.0);
var endPoint0 = new Cartesian3(5.0, 0.0, 0.0);
var endPoint1 = new Cartesian3(2.0, 0.0, 0.0);
var intersectionPoint = IntersectionTests.lineSegmentPlane(endPoint0, endPoint1, plane);
expect(intersectionPoint).not.toBeDefined();
});
it('lineSegmentPlane misses (parallel)', function() {
var plane = new Plane(Cartesian3.UNIT_X, 0.0);
var endPoint0 = new Cartesian3(0.0, -1.0, 0.0);
var endPoint1 = new Cartesian3(0.0, 1.0, 0.0);
var intersectionPoint = IntersectionTests.lineSegmentPlane(endPoint0, endPoint1, plane);
expect(intersectionPoint).not.toBeDefined();
});
it('lineSegmentPlane throws without endPoint0', function() {
expect(function() {
IntersectionTests.lineSegmentPlane();
}).toThrowDeveloperError();
});
it('lineSegmentPlane throws without endPoint1', function() {
expect(function() {
IntersectionTests.lineSegmentPlane(new Cartesian3());
}).toThrowDeveloperError();
});
it('lineSegmentPlane throws without plane', function() {
expect(function() {
IntersectionTests.lineSegmentPlane(new Cartesian3(), new Cartesian3());
}).toThrowDeveloperError();
});
it('triangle is front of a plane', function() {
var plane = new Plane(Cartesian3.UNIT_Z, 0.0);
var p0 = new Cartesian3(0.0, 0.0, 2.0);
var p1 = new Cartesian3(0.0, 1.0, 2.0);
var p2 = new Cartesian3(1.0, 0.0, 2.0);
var triangles = IntersectionTests.trianglePlaneIntersection(p0, p1, p2, plane);
expect(triangles).not.toBeDefined();
});
it('triangle is behind a plane', function() {
var plane = new Plane(Cartesian3.negate(Cartesian3.UNIT_Z, new Cartesian3()), 0.0);
var p0 = new Cartesian3(0.0, 0.0, 2.0);
var p1 = new Cartesian3(0.0, 1.0, 2.0);
var p2 = new Cartesian3(1.0, 0.0, 2.0);
var triangles = IntersectionTests.trianglePlaneIntersection(p0, p1, p2, plane);
expect(triangles).not.toBeDefined();
});
it('triangle intersects plane with p0 behind', function() {
var plane = new Plane(Cartesian3.UNIT_Z, -1.0);
var p0 = new Cartesian3(0.0, 0.0, 0.0);
var p1 = new Cartesian3(0.0, 1.0, 2.0);
var p2 = new Cartesian3(0.0, -1.0, 2.0);
var triangles = IntersectionTests.trianglePlaneIntersection(p0, p1, p2, plane);
expect(triangles).toBeDefined();
expect(triangles.indices.length).toEqual(3 + 6);
expect(Cartesian3.equals(triangles.positions[triangles.indices[0]], p0)).toEqual(true);
});
it('triangle intersects plane with p1 behind', function() {
var plane = new Plane(Cartesian3.UNIT_Z, -1.0);
var p0 = new Cartesian3(0.0, -1.0, 2.0);
var p1 = new Cartesian3(0.0, 0.0, 0.0);
var p2 = new Cartesian3(0.0, 1.0, 2.0);
var triangles = IntersectionTests.trianglePlaneIntersection(p0, p1, p2, plane);
expect(triangles).toBeDefined();
expect(triangles.indices.length).toEqual(3 + 6);
expect(Cartesian3.equals(triangles.positions[triangles.indices[0]], p1)).toEqual(true);
});
it('triangle intersects plane with p2 behind', function() {
var plane = new Plane(Cartesian3.UNIT_Z, -1.0);
var p0 = new Cartesian3(0.0, 1.0, 2.0);
var p1 = new Cartesian3(0.0, -1.0, 2.0);
var p2 = new Cartesian3(0.0, 0.0, 0.0);
var triangles = IntersectionTests.trianglePlaneIntersection(p0, p1, p2, plane);
expect(triangles).toBeDefined();
expect(triangles.indices.length).toEqual(3 + 6);
expect(Cartesian3.equals(triangles.positions[triangles.indices[0]], p2)).toEqual(true);
});
it('triangle intersects plane with p0 in front', function() {
var plane = new Plane(Cartesian3.UNIT_Y, -1.0);
var p0 = new Cartesian3(0.0, 2.0, 0.0);
var p1 = new Cartesian3(1.0, 0.0, 0.0);
var p2 = new Cartesian3(-1.0, 0.0, 0.0);
var triangles = IntersectionTests.trianglePlaneIntersection(p0, p1, p2, plane);
expect(triangles).toBeDefined();
expect(triangles.indices.length).toEqual(6 + 3);
expect(Cartesian3.equals(triangles.positions[triangles.indices[0]], p1)).toEqual(true); // p0 is in front
expect(Cartesian3.equals(triangles.positions[triangles.indices[1]], p2)).toEqual(true);
});
it('triangle intersects plane with p1 in front', function() {
var plane = new Plane(Cartesian3.UNIT_Y, -1.0);
var p0 = new Cartesian3(-1.0, 0.0, 0.0);
var p1 = new Cartesian3(0.0, 2.0, 0.0);
var p2 = new Cartesian3(1.0, 0.0, 0.0);
var triangles = IntersectionTests.trianglePlaneIntersection(p0, p1, p2, plane);
expect(triangles).toBeDefined();
expect(triangles.indices.length).toEqual(6 + 3);
expect(Cartesian3.equals(triangles.positions[triangles.indices[0]], p2)).toEqual(true); // p1 is in front
expect(Cartesian3.equals(triangles.positions[triangles.indices[1]], p0)).toEqual(true);
});
it('triangle intersects plane with p2 in front', function() {
var plane = new Plane(Cartesian3.UNIT_Y, -1.0);
var p0 = new Cartesian3(1.0, 0.0, 0.0);
var p1 = new Cartesian3(-1.0, 0.0, 0.0);
var p2 = new Cartesian3(0.0, 2.0, 0.0);
var triangles = IntersectionTests.trianglePlaneIntersection(p0, p1, p2, plane);
expect(triangles).toBeDefined();
expect(triangles.indices.length).toEqual(6 + 3);
expect(Cartesian3.equals(triangles.positions[triangles.indices[0]], p0), true); // p2 is in front
expect(Cartesian3.equals(triangles.positions[triangles.indices[1]], p1)).toEqual(true);
});
it('trianglePlaneIntersection throws without p0', function() {
expect(function() {
return IntersectionTests.trianglePlaneIntersection();
}).toThrowDeveloperError();
});
it('trianglePlaneIntersection throws without p1', function() {
var p = Cartesian3.UNIT_X;
expect(function() {
return IntersectionTests.trianglePlaneIntersection(p);
}).toThrowDeveloperError();
});
it('trianglePlaneIntersection throws without p2', function() {
var p = Cartesian3.UNIT_X;
expect(function() {
return IntersectionTests.trianglePlaneIntersection(p, p);
}).toThrowDeveloperError();
});
it('trianglePlaneIntersection throws without plane', function() {
var p = Cartesian3.UNIT_X;
expect(function() {
return IntersectionTests.trianglePlaneIntersection(p, p, p);
}).toThrowDeveloperError();
});
});
|
import { expect } from 'chai'
import { clean, runMocha } from '../helper'
describe('Issue', () => {
beforeEach(clean)
it('should add issue to test cases', () => {
return runMocha(['issue']).then(results => {
expect(results).to.have.lengthOf(1)
const result = results[0]
expect(result('ns2\\:test-suite > name').text()).to.be.equal(
'Suite with issues'
)
expect(
result('test-case > name')
.eq(0)
.text()
).to.be.equal('Test #1')
expect(
result('test-case > name')
.eq(1)
.text()
).to.be.equal('Test #2')
expect(
result('test-case label[name="issue"]')
.eq(0)
.attr('value')
).to.be.equal('1')
expect(
result('test-case label[name="issue"]')
.eq(1)
.attr('value')
).to.be.equal('2')
})
})
})
|
import HttpTransport from 'lokka-transport-http';
import {parse} from 'url';
import basicAuthHeader from 'basic-auth-header';
export default class HttpAuthTransport {
constructor(endpoint, options = {}) {
if (!endpoint) {
throw new Error('endpoint is required!');
}
options.headers = options.headers || {};
const {
protocol,
auth,
hostname,
port ,
pathname
} = parse(endpoint);
const defaultPort = (protocol === 'https:') ? 443 : 80;
const finalPort = port || defaultPort;
const newEndpoint = `${protocol}//${hostname}:${finalPort}${pathname}`;
const user = auth.split(':')[0].trim();
const pass = auth.split(':')[1].trim();
const headers = {
Authorization: basicAuthHeader(user, pass)
};
Object.assign(options.headers, headers);
this._transport = new HttpTransport(newEndpoint, options);
}
send(query, variables, operationName) {
return this._transport.send(query, variables, operationName);
}
}
|
'use strict';
module.exports = function(grunt) {
// Unified Watch Object
var watchFiles = {
serverViews: ['app/views/**/*.*'],
serverJS: ['gruntfile.js', 'server.js', 'config/**/*.js', 'app/**/*.js'],
clientViews: ['public/modules/**/views/**/*.html'],
clientJS: ['public/js/*.js', 'public/modules/**/*.js'],
clientCSS: ['public/modules/**/*.css'],
mochaTests: ['app/tests/**/*.js', 'app/carryScore/tests/**/*.js']
};
// Project Configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
serverViews: {
files: watchFiles.serverViews,
options: {
livereload: true
}
},
serverJS: {
files: watchFiles.serverJS,
tasks: ['jshint'],
options: {
livereload: true
}
},
clientViews: {
files: watchFiles.clientViews,
options: {
livereload: true,
}
},
clientJS: {
files: watchFiles.clientJS,
tasks: ['jshint'],
options: {
livereload: true
}
},
clientCSS: {
files: watchFiles.clientCSS,
tasks: ['csslint'],
options: {
livereload: true
}
}
},
jshint: {
all: {
src: watchFiles.clientJS.concat(watchFiles.serverJS),
options: {
jshintrc: true
}
}
},
csslint: {
options: {
csslintrc: '.csslintrc',
},
all: {
src: watchFiles.clientCSS
}
},
uglify: {
production: {
options: {
mangle: false
},
files: {
'public/dist/application.min.js': 'public/dist/application.js'
}
}
},
cssmin: {
combine: {
files: {
'public/dist/application.min.css': '<%= applicationCSSFiles %>'
}
}
},
nodemon: {
dev: {
script: 'server.js',
options: {
nodeArgs: ['--debug'],
ext: 'js,html',
watch: watchFiles.serverViews.concat(watchFiles.serverJS)
}
}
},
'node-inspector': {
custom: {
options: {
'web-port': 1337,
'web-host': 'localhost',
'debug-port': 5858,
'save-live-edit': true,
'no-preload': true,
'stack-trace-limit': 50,
'hidden': []
}
}
},
ngAnnotate: {
production: {
files: {
'public/dist/application.js': '<%= applicationJavaScriptFiles %>'
}
}
},
concurrent: {
default: ['nodemon', 'watch'],
debug: ['nodemon', 'watch', 'node-inspector'],
options: {
logConcurrentOutput: true,
limit: 10
}
},
env: {
test: {
NODE_ENV: 'test'
},
secure: {
NODE_ENV: 'secure'
}
},
mochaTest: {
src: watchFiles.mochaTests,
options: {
reporter: 'spec',
require: 'server.js'
}
},
karma: {
unit: {
configFile: 'karma.conf.js'
}
}
});
// Load NPM tasks
require('load-grunt-tasks')(grunt);
// Making grunt default to force in order not to break the project.
grunt.option('force', true);
// A Task for loading the configuration object
grunt.task.registerTask('loadConfig', 'Task that loads the config into a grunt option.', function() {
var init = require('./config/init')();
var config = require('./config/config');
grunt.config.set('applicationJavaScriptFiles', config.assets.js);
grunt.config.set('applicationCSSFiles', config.assets.css);
});
// Default task(s).
grunt.registerTask('default', ['lint', 'concurrent:default']);
// Debug task.
grunt.registerTask('debug', ['lint', 'concurrent:debug']);
// Secure task(s).
grunt.registerTask('secure', ['env:secure', 'lint', 'concurrent:default']);
// Lint task(s).
grunt.registerTask('lint', ['jshint', 'csslint']);
// Build task(s).
grunt.registerTask('build', ['lint', 'loadConfig', 'ngAnnotate', 'uglify', 'cssmin']);
// Test task.
grunt.registerTask('test', ['env:test', 'mochaTest', 'karma:unit']);
};
|
var fs = require('fs'),
glob = require('glob'),
base = './',
appName = 'shell',
sourcePath = '/src',
__DEV__ = false,
routeStream = fs.createWriteStream(base + appName + sourcePath + '/routes.js'),
modulesStream = fs.createWriteStream(base + appName + '/modules.json'),
modules = [],
content = '/*@ngInject*/ \nlet Routes = function ($routeProvider, $provide) {' +
'\n$routeProvider';
glob(base + 'plugins/**/module.json', {}, function(err, fileNames) {
var obj = {};
for (var index = 0; index < fileNames.length; index++) {
var moduleContent = fs.readFileSync(fileNames[index], 'utf-8');
if (moduleContent) {
obj = getRoutesJSFile(JSON.parse(moduleContent));
content += obj.jsFileContent;
modules = modules.concat(obj.modules);
}
}
content += '.otherwise({redirectTo: \'/unauthorized\'}); ' +
'\n/*@ngInject*/\n$provide.decorator("$exceptionHandler", function($delegate, $injector) { ' +
'return function(exception, cause) { ' +
'/* eslint-disable no-constant-condition */' +
'if (' + __DEV__ + ') { $delegate(exception, cause); }' +
'/* eslint-enable no-constant-condition */' +
'$injector.get(\'toaster\').pop({ type: \'error\', title: exception.name, body: exception.message, showCloseButton: true}); };' +
'});' +
'};' +
'Routes.$inject = [\'$routeProvider\', \'$provide\'];' +
'export default Routes; ';
routeStream.write(content);
routeStream.end();
routeStream.close();
modulesStream.write(JSON.stringify(modules));
modulesStream.end();
modulesStream.close();
console.log('route.js is generated..');
});
function getRoutesJSFile(json) {
var jsFileContent = '',
modules = [];
for (var moduleIndex = 0; json.routes.length > moduleIndex; moduleIndex++) {
var route = json.routes[moduleIndex],
name = json.name.toLowerCase();
if (!route.isDev) {
modules.push(json);
jsFileContent += '\n.when(\'' + route.url + '\',\n' +
'{ template: require(\'' + name + '/src/' + name + '.html\'),\n' +
'controller: \'' + route.controller + '\',\n' +
'controllerAs:\'' + route.controllerAs + '\'';
if (route.lazyLoad) {
jsFileContent += ',\nresolve: { /*@ngInject*/ \n loadHomeModule: [\'$q\', \'authService\', \'moduleProvider\', \'$location\', function ($q, authService, moduleProvider, $location) {\n' +
'var defered = $q.defer(),' +
'path = $location.path().split(\'/\');\n ' +
'if (authService.hasAccessToRoute(path[path.length-1]) || ' + route.isPublic + ') {\n ' +
'require.ensure([], function () { \n' +
'require(\'' + name + '\');\n' +
'moduleProvider.load({ name: \'' + json.namespace + '.' + json.name + '\', path: \'./' + name + '\' });\n' +
'defered.resolve();\n' +
'}, \'' + name + '\');\n' +
' } else { \n' +
' defered.reject(); \n' +
' $location.path(\'/unauthorized\'); ' +
' } \n' +
' return defered.promise; \n' +
' }] } \n';
}
jsFileContent += '})\n';
if (route.isDefault) {
jsFileContent += '.when(\'/\', { redirectTo: \'' + route.url + '\' })';
}
}
}
return {
jsFileContent: jsFileContent,
modules: modules
};
}
|
o2.slides = {
currentSlideNum : o2.urlMod.getHash().replace(/page/, '') || 1,
slides : new Array(),
fontSizes : new Array(),
numUnavailablePixelsAtTheTop : 60,
numUnavailablePixelsAtTheBottom : 60,
init : function(e) {
o2.slides.makeSlides();
o2.addEvent( window, "click", o2.slides.showNextSlide );
o2.addEvent( window, "resize", o2.slides.reload );
// keypress doesn't work in ie7 for some reason.. We'll remove 1 of these events in the handleKeyPress function
o2.addEvent( document, "keypress", o2.slides.handleKeyPress );
o2.addEvent( document, "keydown", o2.slides.handleKeyPress );
// Don't go to next slide if a link is clicked
var slidesTag = o2.getElementsByClassName("slides")[0];
var links = slidesTag.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
links[i].onclick = function(e) {
e.stopPropagation();
}
}
},
makeSlides : function() {
o2.slides.slides = o2.getElementsByClassName("slideMain", null, "div");
o2.slides.calculateFontSizePerPage();
o2.slides.hideSlides();
o2.slides.showCurrentSlide();
o2.getElementsByClassName("slides")[0].style.visibility = "visible"; // Make content visible
},
reload : function(e) {
// Have to make some change to the url to be able to reload. Strange..
var url;
if (o2.urlMod.getQueryString()) {
url = o2.urlMod.urlMod({ removeParams : "1" });
}
else {
url = o2.urlMod.urlMod({ setParam : "a=1" });
}
window.location.href = url;
},
calculateFontSizePerPage : function() {
var bodyHeight = o2.slides.getBodyHeight() - o2.slides.numUnavailablePixelsAtTheTop - o2.slides.numUnavailablePixelsAtTheBottom;
var bodyWidth = o2.slides.getBodyWidth();
for (var i = 0; i < o2.slides.slides.length; i++) {
var slide = o2.slides.slides[i];
var contentHeight = o2.getComputedStyle( slide, "height" );
var contentWidth = o2.getComputedStyle( slide, "width" );
var yEnlargement = bodyHeight / contentHeight;
var xEnlargement = bodyWidth / contentWidth;
var enlargement = Math.min(yEnlargement, xEnlargement);
o2.slides.fontSizes.push( parseInt( parseInt(o2.getComputedStyle(slide, "fontSize")) * enlargement - 1) + "px" );
}
},
hideSlides : function() {
for (var i = 0; i < o2.slides.slides.length; i++) {
o2.slides.slides[i].parentNode.style.display = "none";
}
},
showCurrentSlide : function() {
var slide = o2.slides.slides[ o2.slides.currentSlideNum-1 ];
slide.style.fontSize = o2.slides.fontSizes[ o2.slides.currentSlideNum-1 ];
slide.parentNode.style.display = "";
slide.style.float = "";
var unusedHeight = o2.slides.getBodyHeight() - o2.getComputedStyle( slide, "height" ) - o2.slides.numUnavailablePixelsAtTheTop - o2.slides.numUnavailablePixelsAtTheBottom;
var unusedWidth = o2.slides.getBodyWidth() - o2.getComputedStyle( slide, "width" );
slide.style.top = unusedHeight/2 + o2.slides.numUnavailablePixelsAtTheTop + "px";
slide.style.left = unusedWidth/2 + "px";
window.location.hash = "page" + o2.slides.currentSlideNum;
},
showNextSlide : function() {
if (o2.slides.currentSlideNum === o2.slides.slides.length) {
return;
}
var currentSlide = o2.slides.slides[ o2.slides.currentSlideNum-1 ];
currentSlide.parentNode.style.display = "none";
o2.slides.currentSlideNum++;
o2.slides.showCurrentSlide();
},
showPreviousSlide : function() {
if (o2.slides.currentSlideNum === 1) {
return;
}
o2.slides.hideCurrentSlide();
o2.slides.currentSlideNum--;
o2.slides.showCurrentSlide();
},
showFinalSlide : function() {
o2.slides.hideCurrentSlide();
o2.slides.currentSlideNum = o2.slides.slides.length;
o2.slides.showCurrentSlide();
},
showFirstSlide : function() {
o2.slides.hideCurrentSlide();
o2.slides.currentSlideNum = 1;
o2.slides.showCurrentSlide();
},
hideCurrentSlide : function() {
o2.slides.slides[ o2.slides.currentSlideNum-1 ].parentNode.style.display = "none";
},
handleKeyPress : function(e) {
switch (e.getKeyCode()) {
case 8: // Backspace
case 33: // Page up
case 37: // Left arrow
case 38: o2.slides.showPreviousSlide(); e.preventDefault(); break; // Up arrow
case 13: // Enter
case 32: // Space bar
case 34: // Page down
case 39: // Right arrow
case 40: o2.slides.showNextSlide(); e.preventDefault(); break; // Down arrow
case 35: o2.slides.showFinalSlide(); break; // End
case 36: o2.slides.showFirstSlide(); break; // Home
}
// Remove the event we're not using (browser dependent)
if (e.getType() === "keypress") {
o2.removeEvent(document, "keydown", o2.slides.handleKeyPress);
}
else if (e.getType() === "keydown") {
o2.removeEvent(document, "keypress", o2.slides.handleKeyPress);
}
e.stopPropagation();
},
getBodyWidth : function() {
var marginLeft = o2.getComputedStyle( document.body, "marginLeft" );
var marginRight = o2.getComputedStyle( document.body, "marginRight" );
if (marginLeft.match(/%$/)) {
marginLeft = parseInt( o2.getWindowWidth() * parseInt(marginLeft) / 100 );
}
if (marginRight.match(/%$/)) {
marginRight = parseInt( o2.getWindowWidth() * parseInt(marginRight) / 100 );
}
return parseInt(o2.getWindowWidth() - parseInt(marginLeft) - parseInt(marginRight));
},
getBodyHeight : function() {
return o2.getWindowHeight();
}
};
o2.addLoadEvent(o2.slides.init);
|
import Component from '@ember/component';
import { get } from '@ember/object';
import { inject as service } from '@ember/service';
import { isEmpty } from '@ember/utils';
import layout from '../templates/components/do-feedback';
import hasOnlyEmberView from '../utils/has-only-ember-view';
import setDataTestSelector from '../utils/set-data-test-selector';
const DoFeedbackComponent = Component.extend({
layout,
config: service('ember-do-forms/config'),
tagName: '',
wrapperTagName: 'div',
showFeedback: false,
init() {
setDataTestSelector(this, {
testSelector: 'do-feedback',
autoTestSelector: get(this, 'config.autoDataTestSelectors'),
testSelectorValue: get(this, 'propertyName')
});
this._super(...arguments);
let defaultClasses = get(this, 'config.defaultClasses.feedback');
if (isEmpty(this.classNames) || hasOnlyEmberView(this.classNames)) {
this.classNames = this.classNames.concat(defaultClasses);
}
}
});
export default DoFeedbackComponent;
|
const DifficultyFilterToggleList = require('../presentational/difficulty-filter-toggle-list')
const { connect } = require('react-redux')
const { toggleDifficultyFilter } = require('../../store/actions/filters')
function mapDispatchToProps (dispatch) {
return {
onDifficultyFilterUpdate (difficulty) {
dispatch(toggleDifficultyFilter(difficulty))
}
}
}
function mapStateToProps () {
return {
filters: ['Very Easy', 'Easy', 'Average', 'Hard', 'Very Hard']
}
}
module.exports = connect(mapStateToProps, mapDispatchToProps)(DifficultyFilterToggleList)
|
'use strict';
var paramOwner = {
name : 'owner',
required : true,
type : 'string',
location : 'uri',
description : 'The owner of the repo.'
};
var paramRepo = {
name : 'repo',
required : true,
type : 'string',
location : 'uri',
description : 'The name of the repo.'
};
var paramIssueNumber = {
name : 'issue_number',
required : true,
type : 'integer',
location : 'uri',
description : 'The issue number.'
};
module.exports = {
name : 'Events',
endpoints : [
{
name : 'List events for an issue',
synopsis : '',
method : 'GET',
uri : '/repos/:owner/:repo/issues/:issue_number/events',
oauth : false,
params : [
paramOwner,
paramRepo,
paramIssueNumber
]
},
{
name : 'List events for a repository',
synopsis : '',
method : 'GET',
uri : '/repos/:owner/:repo/issues/events',
oauth : true,
params : [
paramOwner,
paramRepo
]
},
{
name : 'Get a single event',
synopsis : '',
method : 'GET',
uri : '/repos/:owner/:repo/issues/events/:id',
oauth : true,
params : [
paramOwner,
paramRepo,
{
name : 'id',
required : true,
type : 'integer',
location : 'uri',
description : 'The event ID'
}
]
}
]
};
|
//Autogenerated by ../../build_app.js
import clinical_impression_investigations_component from 'ember-fhir-adapter/serializers/clinical-impression-investigations-component';
export default clinical_impression_investigations_component;
|
define([
"esri/units",
"dojo/_base/array"
], function(Units, array) {
var util = {};
var HOURS = "Hours";
var MINUTES = "Minutes";
var SECONDS = "Seconds";
// Tests the units to be time units.
util.testTimeUnits = function (units) {
return units === HOURS || units === SECONDS || units === MINUTES;
}
var measureUnits = {};
// Linear units multiples
measureUnits[Units.FEET] = 0.3048;
measureUnits[Units.YARDS] = 0.9144;
measureUnits[Units.METERS] = 1;
measureUnits[Units.KILOMETERS] = 1000;
measureUnits[Units.MILES] = 1609.3472186944374;
measureUnits[Units.NAUTICAL_MILES] = 1852;
// Drive time units multiples (average drive time speed is 60 km per hour)
measureUnits[HOURS] = 60000;
measureUnits[SECONDS] = 16.66666666666667;
measureUnits[MINUTES] = 1000;
// Square units multiples
measureUnits[Units.SQUARE_FEET] = measureUnits[Units.FEET] * measureUnits[Units.FEET];
measureUnits[Units.SQUARE_YARDS] = measureUnits[Units.YARDS] * measureUnits[Units.YARDS];
measureUnits[Units.SQUARE_METERS] = 1;
measureUnits[Units.SQUARE_KILOMETERS] = measureUnits[Units.KILOMETERS] * measureUnits[Units.KILOMETERS];
measureUnits[Units.SQUARE_MILES] = measureUnits[Units.MILES] * measureUnits[Units.MILES];
measureUnits[Units.ACRES] = 4046.8564224;
measureUnits[Units.HECTARES] = 10000;
// Gets a value of linear unit in meters.
// value: Number
// A value to convert.
// sourceUnits: String
// ArcGIS units or time units 'Seconds', 'Minutes', or 'Hours'.
// targetUnits: String
// Optional ArcGIS units or time units 'Seconds', 'Minutes', or 'Hours'.
// If missing, the meters or square meters are used as target units.
// The source and target units should be both linear units or square units.
// Time units are considered as linear units. The time to distance conversion is applied for the average speed of 90 km in hour.
// Returns a value in converted units or 0 if source units were wrong.
util.convertUnits = function (value, sourceUnits, targetUnits) {
var multiple = measureUnits[sourceUnits] || 0;
var divider = targetUnits && measureUnits[targetUnits] || 1;
return value * multiple / divider;
};
var WALK_TIME = "WalkTime";
// Calculates the max radius of site buffer in kilometers.
// The supported units are kilometers, miles, and minutes.
// In the case of minutes, we calculate the max radius using an average drive time speed of 60 km per hour
// and walk time speed of 5 km per hour.
// options: Object
// Site or buffer area parameters.
util.getMaxRadiusInKilometers = function(options, isWalkTime) {
var maxRadius = 0;
if (options && options.bufferRadii) {
array.forEach(options.bufferRadii, function (radius) { if (radius > maxRadius) maxRadius = radius });
maxRadius = util.convertUnits(maxRadius, options.bufferUnits || Units.MILES, Units.KILOMETERS);
if (isWalkTime && util.testTimeUnits(options.bufferUnits))
maxRadius /= 12;
}
return maxRadius;
};
return util;
});
|
const TRAILING_WHITESPACE = /[ \u0020\t\n]*$/;
// This escapes some markdown but there's a few cases that are TODO -
// - List items
// - Back tics (see https://github.com/Rosey/markdown-draft-js/issues/52#issuecomment-388458017)
// - Complex markdown, like links or images. Not sure it's even worth it, because if you're typing
// that into draft chances are you know its markdown and maybe expect it convert? :/
const MARKDOWN_STYLE_CHARACTERS = ['*', '_', '~', '`'];
const MARKDOWN_STYLE_CHARACTER_REGXP = /(\*|_|~|\\|`)/g;
// I hate this a bit, being outside of the function’s scope
// but can’t think of a better way to keep track of how many ordered list
// items were are on, as draft doesn’t explicitly tell us in the raw object 😢.
// This is a hash that will be assigned values based on depth, so like
// orderedListNumber[0] = 1 would mean that ordered list at depth 0 is on number 1.
// orderedListNumber[0] = 2 would mean that ordered list at depth 0 is on number 2.
// This is so we have the right number of numbers when doing a list, eg
// 1. Item One
// 2. Item two
// 3. Item three
// And so on.
var orderedListNumber = {},
previousOrderedListDepth = 0;
// A map of draftjs block types -> markdown open and close characters
// Both the open and close methods must exist, even if they simply return an empty string.
// They should always return a string.
const StyleItems = {
// BLOCK LEVEL
'unordered-list-item': {
open: function () {
return '- ';
},
close: function () {
return '';
}
},
'ordered-list-item': {
open: function (block, number = 1) {
return `${number}. `;
},
close: function () {
return '';
}
},
'blockquote': {
open: function () {
return '> ';
},
close: function () {
return '';
}
},
'header-one': {
open: function () {
return '# ';
},
close: function () {
return '';
}
},
'header-two': {
open: function () {
return '## ';
},
close: function () {
return '';
}
},
'header-three': {
open: function () {
return '### ';
},
close: function () {
return '';
}
},
'header-four': {
open: function () {
return '#### ';
},
close: function () {
return '';
}
},
'header-five': {
open: function () {
return '##### ';
},
close: function () {
return '';
}
},
'header-six': {
open: function () {
return '###### ';
},
close: function () {
return '';
}
},
'code-block': {
open: function (block) {
return '```' + (block.data.language || '') + '\n';
},
close: function () {
return '\n```';
}
},
// INLINE LEVEL
'BOLD': {
open: function () {
return '**';
},
close: function () {
return '**';
}
},
'ITALIC': {
open: function () {
return '_';
},
close: function () {
return '_';
}
},
'STRIKETHROUGH': {
open: function () {
return '~~';
},
close: function () {
return '~~';
}
},
'CODE': {
open: function () {
return '`';
},
close: function () {
return '`';
}
}
};
// A map of draftjs entity types -> markdown open and close characters
// entities are different from block types because they have additional data attached to them.
// an entity object is passed in to both open and close, in case it's needed for string generation.
//
// Both the open and close methods must exist, even if they simply return an empty string.
// They should always return a string.
const EntityItems = {
'LINK': {
open: function (entity) {
return '[';
},
close: function (entity) {
return `](${entity.data.url || entity.data.href})`;
}
}
}
// Bit of a hack - we normally want a double newline after a block,
// but for list items we just want one (unless it's the _last_ list item in a group.)
const SingleNewlineAfterBlock = [
'unordered-list-item',
'ordered-list-item'
];
function isEmptyBlock(block) {
return block.text.length === 0 && block.entityRanges.length === 0 && Object.keys(block.data || {}).length === 0;
}
/**
* Generate markdown for a single block javascript object
* DraftJS raw object contains an array of blocks, which is the main "structure"
* of the text. Each block = a new line.
*
* @param {Object} block - block to generate markdown for
* @param {Number} index - index of the block in the blocks array
* @param {Object} rawDraftObject - entire raw draft object (needed for accessing the entityMap)
* @param {Object} options - additional options passed in by the user calling this method.
*
* @return {String} markdown string
**/
function renderBlock(block, index, rawDraftObject, options) {
var openInlineStyles = [],
markdownToAdd = [];
var markdownString = '',
customStyleItems = options.styleItems || {},
customEntityItems = options.entityItems || {},
escapeMarkdownCharacters = options.hasOwnProperty('escapeMarkdownCharacters') ? options.escapeMarkdownCharacters : true;
var type = block.type;
var markdownStyleCharactersToEscape = [];
// draft-js emits empty blocks that have type set… don’t style them unless the user wants to preserve new lines
// (if newlines are preserved each empty line should be "styled" eg in case of blockquote we want to see a blockquote.)
// but if newlines aren’t preserved then we'd end up having double or triple or etc markdown characters, which is a bug.
if (isEmptyBlock(block) && !options.preserveNewlines) {
type = 'unstyled';
}
// Render main block wrapping element
if (customStyleItems[type] || StyleItems[type]) {
if (type === 'unordered-list-item' || type === 'ordered-list-item') {
markdownString += ' '.repeat(block.depth * 4);
}
if (type === 'ordered-list-item') {
orderedListNumber[block.depth] = orderedListNumber[block.depth] || 1;
markdownString += (customStyleItems[type] || StyleItems[type]).open(block, orderedListNumber[block.depth]);
orderedListNumber[block.depth]++;
// Have to reset the number for orderedListNumber if we are breaking out of a list so that if
// there's another nested list at the same level further down, it starts at 1 again.
// COMPLICATED 😭
if (previousOrderedListDepth > block.depth) {
orderedListNumber[previousOrderedListDepth] = 1;
}
previousOrderedListDepth = block.depth;
} else {
orderedListNumber = {};
markdownString += (customStyleItems[type] || StyleItems[type]).open(block);
}
} else {
orderedListNumber = {};
}
// A stack to keep track of open tags
var openTags = [];
function openTag(tag) {
openTags.push(tag);
if (tag.style) {
// Open inline tag
if (customStyleItems[tag.style] || StyleItems[tag.style]) {
var styleToAdd = (
customStyleItems[tag.style] || StyleItems[tag.style]
).open();
markdownToAdd.push({
type: 'style',
style: tag,
value: styleToAdd
});
}
} else {
// Open entity tag
var entity = rawDraftObject.entityMap[tag.key];
if (customEntityItems[entity.type] || EntityItems[entity.type]) {
var entityToAdd = (
customEntityItems[entity.type] || EntityItems[entity.type]
).open(entity, block);
markdownToAdd.push({
type: 'entity',
value: entityToAdd
});
}
}
}
function closeTag(tag) {
const popped = openTags.pop();
if (tag !== popped) {
throw new Error(
'Invariant violation: Cannot close a tag before all inner tags have been closed'
);
}
if (tag.style) {
// Close inline tag
if (customStyleItems[tag.style] || StyleItems[tag.style]) {
// Have to trim whitespace first and then re-add after because markdown can't handle leading/trailing whitespace
var trailingWhitespace = TRAILING_WHITESPACE.exec(markdownString);
markdownString = markdownString.slice(
0,
markdownString.length - trailingWhitespace[0].length
);
markdownString += (
customStyleItems[tag.style] || StyleItems[tag.style]
).close();
markdownString += trailingWhitespace[0];
}
} else {
// Close entity tag
var entity = rawDraftObject.entityMap[tag.key];
if (customEntityItems[entity.type] || EntityItems[entity.type]) {
markdownString += (
customEntityItems[entity.type] || EntityItems[entity.type]
).close(entity, block);
}
}
}
const compareTagsLastCloseFirst = (a, b) =>
b.offset + b.length - (a.offset + a.length);
// reverse array without mutating the original
const reverse = (array) => array.concat().reverse();
// Render text within content, along with any inline styles/entities
Array.from(block.text).some(function (character, characterIndex) {
// Close any tags that need closing, starting from top of the stack
reverse(openTags).forEach(function (tag) {
if (tag.offset + tag.length === characterIndex) {
// Take all tags stacked on top of the current one, meaning they opened after it.
// Since they have not been popped, they'll close only later. So we need to split them.
var tagsToSplit = openTags.slice(openTags.indexOf(tag) + 1);
// Close in reverse order as they were opened
reverse(tagsToSplit).forEach(closeTag);
// Now we can close the current tag
closeTag(tag);
// Reopen split tags, ordered so that tags that close last open first
tagsToSplit.sort(compareTagsLastCloseFirst).forEach(openTag);
}
});
// Open any tags that need opening, using the correct nesting order.
var inlineTagsToOpen = block.inlineStyleRanges.filter(
(tag) => tag.offset === characterIndex
);
var entityTagsToOpen = block.entityRanges.filter(
(tag) => tag.offset === characterIndex
);
inlineTagsToOpen
.concat(entityTagsToOpen)
.sort(compareTagsLastCloseFirst)
.forEach(openTag);
// These are all the opening entity and style types being added to the markdown string for this loop
// we store in an array and add here because if the character is WS character, we want to hang onto it and not apply it until the next non-whitespace
// character before adding the markdown, since markdown doesn’t play nice with leading whitespace (eg '** bold**' is no good, whereas ' **bold**' is good.)
if (character !== ' ' && markdownToAdd.length) {
markdownString += markdownToAdd.map(function (item) {
return item.value;
}).join('');
markdownToAdd = [];
}
if (block.type !== 'code-block' && escapeMarkdownCharacters) {
let insideInlineCodeStyle = openTags.find((style) => style.style === 'CODE');
if (insideInlineCodeStyle) {
// Todo - The syntax to escape backtics when inside backtic code already is to use MORE backtics wrapping.
// So we need to see how many backtics in a row we have and then when converting to markdown, use that # + 1
// EG ``Test ` Hllo ``
// OR ```Test `` Hello```
// OR ````Test ``` Hello ````
// Similar work has to be done for codeblocks.
} else {
// Special escape logic for blockquotes and heading characters
if (characterIndex === 0 && character === '#' && block.text[1] && block.text[1] === ' ') {
character = character.replace('#', '\\#');
} else if (characterIndex === 0 && character === '>') {
character = character.replace('>', '\\>');
}
// Escaping inline markdown characters
// 🧹 If someone can think of a more elegant solution, I would love that.
// orginally this was just a little char replace using a simple regular expression, but there’s lots of cases where
// a markdown character does not actually get converted to markdown, like this case: http://google.com/i_am_a_link
// so this code now tries to be smart and keeps track of potential “opening” characters as well as potential “closing”
// characters, and only escapes if both opening and closing exist, and they have the correct whitepace-before-open, whitespace-or-end-of-string-after-close pattern
if (MARKDOWN_STYLE_CHARACTERS.includes(character)) {
let openingStyle = markdownStyleCharactersToEscape.find(function (item) {
return item.character === character;
});
if (!openingStyle && block.text[characterIndex - 1] === ' ' && block.text[characterIndex + 1] !== ' ') {
markdownStyleCharactersToEscape.push({
character: character,
index: characterIndex,
markdownStringIndexStart: markdownString.length + character.length - 1,
markdownStringIndexEnd: markdownString.length + character.length
});
} else if (openingStyle && block.text[characterIndex - 1] === character && characterIndex === openingStyle.index + 1) {
openingStyle.markdownStringIndexEnd += 1;
} else if (openingStyle) {
let openingStyleLength = openingStyle.markdownStringIndexEnd - openingStyle.markdownStringIndexStart;
let escapeCharacter = false;
let popOpeningStyle = false;
if (openingStyleLength === 1 && (block.text[characterIndex + 1] === ' ' || !block.text[characterIndex + 1])) {
popOpeningStyle = true;
escapeCharacter = true;
}
if (openingStyleLength === 2 && block.text[characterIndex + 1] === character) {
escapeCharacter = true;
}
if (openingStyleLength === 2 && block.text[characterIndex - 1] === character && (block.text[characterIndex + 1] === ' ' || !block.text[characterIndex + 1])) {
popOpeningStyle = true;
escapeCharacter = true;
}
if (popOpeningStyle) {
markdownStyleCharactersToEscape.splice(markdownStyleCharactersToEscape.indexOf(openingStyle), 1);
let replacementString = markdownString.slice(openingStyle.markdownStringIndexStart, openingStyle.markdownStringIndexEnd);
replacementString = replacementString.replace(MARKDOWN_STYLE_CHARACTER_REGXP, '\\$1');
markdownString = (markdownString.slice(0, openingStyle.markdownStringIndexStart) + replacementString + markdownString.slice(openingStyle.markdownStringIndexEnd));
}
if (escapeCharacter) {
character = `\\${character}`;
}
}
}
}
}
if (character === '\n' && type === 'blockquote') {
markdownString += '\n> ';
} else {
markdownString += character;
}
});
// Finally, close all remaining open tags
reverse(openTags).forEach(closeTag);
// Close block level item
if (customStyleItems[type] || StyleItems[type]) {
markdownString += (customStyleItems[type] || StyleItems[type]).close(block);
}
// Determine how many newlines to add - generally we want 2, but for list items we just want one when they are succeeded by another list item.
if (SingleNewlineAfterBlock.indexOf(type) !== -1 && rawDraftObject.blocks[index + 1] && SingleNewlineAfterBlock.indexOf(rawDraftObject.blocks[index + 1].type) !== -1) {
markdownString += '\n';
} else if (rawDraftObject.blocks[index + 1]) {
if (rawDraftObject.blocks[index].text) {
if (SingleNewlineAfterBlock.indexOf(type) !== -1
&& SingleNewlineAfterBlock.indexOf(rawDraftObject.blocks[index + 1].type) === -1) {
markdownString += '\n\n';
} else if (!options.preserveNewlines) {
// 2 newlines if not preserving
markdownString += '\n\n';
} else {
markdownString += '\n';
}
} else if (options.preserveNewlines) {
markdownString += '\n';
}
}
return markdownString;
}
/**
* Generate markdown for a raw draftjs object
* DraftJS raw object contains an array of blocks, which is the main "structure"
* of the text. Each block = a new line.
*
* @param {Object} rawDraftObject - draftjs object to generate markdown for
* @param {Object} options - optional additional data, see readme for what options can be passed in.
*
* @return {String} markdown string
**/
function draftToMarkdown(rawDraftObject, options) {
options = options || {};
var markdownString = '';
rawDraftObject.blocks.forEach(function (block, index) {
markdownString += renderBlock(block, index, rawDraftObject, options);
});
orderedListNumber = {}; // See variable definitions at the top of the page to see why we have to do this sad hack.
return markdownString;
}
export default draftToMarkdown;
|
// import dependencies
import template from './tags.html'
// export component object
export default {
template: template,
replace: true,
computed: {
labelVariant() {
return !this.variant || this.variant === `default` ? `tag-default` : `tag-${this.variant}`
},
labelType() {
return !this.type ? `` : `tag-${this.type}`
}
},
props: {
variant: {
type: String,
default: 'default'
},
type: {
type: String,
default: ''
}
}
}
|
// = test_with_crlf.js =
// ** {{{ Test with CRLF }}} **
//
// Edit the file preserving the end line terminator: CRLF.
// [[#test_with_cr.js| see cr]]
// [[#test_with_lf.js| see lf]]
//
// The used structure for each block is:
// {{{
// <div class="documentation"> (...) </div>
// <pre class="code prettyprint"> (...) </pre>
// <div class="divider"/>
// }}}
function dummy() {
}
|
var express = require('express');
var app = express();
var path = require('path');
var engines = require('consolidate');
app.set('views', __dirname + '/views');
app.use(express.static(path.join(__dirname, '/public')));
app.engine('html', engines.jade);
app.set('view engine', 'html');
app.get('/', function(req, res){
res.render('ipsum.html');
});
var server = app.listen(process.env.PORT || 5000)
app.use(function(req, res, next){
res.send(404, 'Sorry cant find that!');
});
//using consolidate after reading this:
//http://stackoverflow.com/questions/16111386/node-js-cannot-find-module-html
|
var expect = require('chai').expect
, support = require('./support')
, async = require('async')
, client = support.client;
describe('Response', function() {
beforeEach(function(done) {
support.startServer(this, done);
});
afterEach(function(done) {
support.stopServer(this, done);
});
describe('properties', function() {
it('should be exposed', function(done) {
this.io.connect(function(socket) {
socket.on('foo', function(req, res) {
expect(res.method).to.eql('foo');
expect(res.socket).to.equal(socket);
done();
});
});
var socket = client();
socket.on('connect', function() {
socket.emit('foo');
});
});
});
describe('.get(field)', function() {
it('should get the response header field', function(done) {
this.io.connect(function(socket) {
socket.on('foo', function(req, res) {
res.setHeader('Content-Type', 'text/x-foo');
expect(res.get('Content-Type')).to.equal('text/x-foo');
expect(res.get('Content-type')).to.equal('text/x-foo');
expect(res.get('content-type')).to.equal('text/x-foo');
done();
});
});
var socket = client();
socket.on('connect', function() {
socket.emit('foo');
});
});
});
describe('.set(field, value)', function() {
it('should set the response header field', function(done) {
this.io.connect(function(socket) {
socket.on('foo', function(req, res) {
res.set('Content-Type', 'text/x-foo');
res.send();
});
});
var socket = client();
socket.on('connect', function() {
socket.emit('foo', function(err, body, headers) {
expect(headers).to.have.property('content-type', 'text/x-foo');
done();
});
});
});
it('should coerce to a string', function(done) {
this.io.connect(function(socket) {
socket.on('foo', function(req, res) {
res.set('ETag', 123);
expect(res.get('ETag')).to.equal('123');
done();
});
});
var socket = client();
socket.on('connect', function() {
socket.emit('foo')
});
});
});
describe('.set(field, values)', function() {
it('should set multiple response header fields', function(done) {
this.io.connect(function(socket) {
socket.on('foo', function(req, res) {
res.set('Set-Cookie', ["type=ninja", "language=javascript"]);
res.send(JSON.stringify(res.get('Set-Cookie')));
});
});
var socket = client();
socket.on('connect', function() {
socket.emit('foo', function(err, data) {
expect(data).to.equal('["type=ninja","language=javascript"]');
done();
});
});
});
it('should coerce to an array of strings', function() {
this.io.connect(function(socket) {
socket.on('foo', function(req, res) {
res.set('ETag', [123, 456]);
expect(JSON.stringify(res.get('ETag'))).to.equal('["123","456"]');
done();
});
});
var socket = client();
socket.on('connect', function() {
socket.emit('foo');
});
});
});
describe('.set(object)', function() {
it('should set multiple fields', function(done) {
this.io.connect(function(socket) {
socket.on('foo', function(req, res) {
res.set({
'X-Foo': 'bar',
'X-Bar': 'baz'
});
res.send();
});
});
var socket = client();
socket.on('connect', function() {
socket.emit('foo', function(err, data, headers) {
expect(headers).to.have.property('x-foo', 'bar');
expect(headers).to.have.property('x-bar', 'baz');
done();
});
});
});
it('should coerce to a string', function(done) {
this.io.connect(function(socket) {
socket.on('foo', function(req, res) {
res.set({ ETag: 123 });
expect(res.get('ETag')).to.equal('123');
done();
});
});
var socket = client();
socket.on('connect', function() {
socket.emit('foo');
});
});
});
describe('.status(code)', function() {
it('should set the response .statusCode', function(done) {
this.io.connect(function(socket) {
socket.on('foo', function(req, res) {
res.status(201);
expect(res.statusCode).to.equal(201);
done();
});
});
var socket = client();
socket.on('connect', function() {
socket.emit('foo');
});
});
});
describe('.to(name)', function() {
it('should broadcast only to the room', function(done) {
this.io.connect(function(socket) {
socket.on('join', function(req, res) {
socket.join('foo', res.send.bind(res));
});
socket.on('broadcast', function(req, res) {
res.broadcast.to('foo').send(req.body);
});
});
var socket1 = client();
var socket2 = client();
var socket3 = client();
async.each([socket1, socket2, socket3], function(socket, callback) {
socket.on('connect', callback);
}, function(err) {
if (err) throw err;
socket2.emit('join', function(err) {
if (err) throw err;
socket1.emit('broadcast', 'woot', function(err, body) {
expect(body).to.eql('woot');
});
socket2.on('broadcast', function(body) {
expect(body).to.eql('woot');
done();
});
socket3.on('broadcast', function() {
throw new Error('Called unexpectedly');
});
});
});
});
});
describe('.send(status)', function() {
it('should send error as a response', function(done) {
this.io.connect(function(socket) {
socket.on('foo', function(req, res) {
res.send(500);
});
});
var socket = client();
socket.on('connect', function() {
socket.emit('foo', function(err) {
expect(err).to.eql({status: 500});
done();
});
});
});
});
});
|
import React, { Component } from 'react'
// import local css as s.
import s from './styles.css'
// import global css as gs
import gs from './../../styles/grid.css'
class Article extends Component {
render() {
return (
<div className={gs.container}>
<div className={gs.line}>
<div className={s.articleHeadline}>
Idiotic Tree Keeps Trying To Plant Seeds On Sidewalk
</div>
</div>
<div className={gs.line}>
<div className={s.articleBody}>
PORTLAND, OR—Pointing out that the total dipshit had dropped dozens
of acorns all along the length of pavement, sources confirmed Thursday
that a completely idiotic tree keeps trying to plant seeds on the sidewalk.
“Come on, you fucking moron, what are you doing? That’s concrete,” said local
pedestrian Frank Brogden, who shook his head while pondering why the
dumbshit California black oak was stupid enough to believe its saplings
could grow in an area devoid of soil, nutrients, and water. “Oh, yeah,
I can’t wait to see the tree sprouting right up in the middle of 5-inch-thick cement.
The dirt’s that way, Einstein.” At press time, Brogden was reportedly overheard
muttering “What the fuck?” under his breath as the tree attempted to plant
a seed on a parked car.
</div>
</div>
</div>
)
}
}
export default Article
|
/**
* @name stripTags
* @kind function
*
* @description
* strip html tags from string
*/
function stripTags(input) {
return isString(input)
? input.replace(/<\S[^><]*>/g, '')
: input;
}
|
var path = require('path');
describe("Static Array", function() {
var data = '';
beforeEach(function(done) {
neutrino.run(path.resolve('./examples/staticarray/test.neu'), function(result) {
data = result;
done();
});
});
it("should parse a static array", function(done) {
data = data.split('\n');
expect(parseInt(data[0])).toBe(67108860);
done();
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.