code stringlengths 2 1.05M |
|---|
import {Trait} from '../entity.js';
export default class Velocity extends Trait {
constructor() {
super('velocity');
}
update(entity, deltaTime) {
entity.pos.x += entity.vel.x * deltaTime;
entity.pos.y += entity.vel.y * deltaTime;
}
}
|
/* globals describe, it */
var chai = require('chai')
chai.should()
chai.use(require('chai-interface'))
describe('Nullable', function () {
var Nullable = require('../')
it('callable with or without new', function () {
Nullable(null).should.be.instanceof(Nullable)
new Nullable(null).should.be.instanceof(Nullable)
})
it('newable with static of', function () {
Nullable.of(null).should.be.instanceof(Nullable)
})
it('newable with instance of', function () {
const a = Nullable.of('a')
const b = a.of('b')
b.should.be.instanceof(Nullable)
})
it('has interface', function () {
Nullable.empty().should.be.instanceof(Nullable)
var x = Nullable(null)
x.should.have.interface({
call: Function,
map: Function,
get: Function,
toString: Function,
valueOf: Function,
orDefault: Function,
// and props
hasValue: Boolean,
isNull: Boolean,
isUndefined: Boolean,
type: String,
// and aliases:
orElse: Function,
of: Function
})
x.should.have.ownProperty('value')
})
it('sets properties', function () {
var x = Nullable(null)
chai.expect(x.value).to.equal(null)
x.hasValue.should.equal(false)
x.isNull.should.equal(true)
x.isUndefined.should.equal(false)
x.type.should.equal('object')
var x2 = Nullable(undefined)
x2.hasValue.should.equal(false)
x2.isNull.should.equal(false)
x2.isUndefined.should.equal(true)
var y = Nullable('brontosaurus')
y.value.should.equal('brontosaurus')
y.hasValue.should.equal(true)
y.isNull.should.equal(false)
y.isUndefined.should.equal(false)
y.type.should.equal('string')
})
describe('.call', function () {
it('calls methods', function () {
var x = Nullable(null)
chai.expect(x.call('toString').value).to.equal(null)
var y = Nullable(123)
y.call('toString').value.should.equal('123')
y.call('toString', 16).value.should.equal('7b')
})
})
describe('.map', function () {
it('calls another function if there is a value', function () {
function double (x) { return x * 2 }
var x = Nullable(null)
chai.expect(x.map(double).value).to.equal(null)
var y = Nullable(2)
y.map(double).value.should.equal(4)
})
})
describe('.get', function () {
describe('when there is a value', () => {
const x = Nullable({a: 1})
describe('when there is a property', () => {
it('returns a nullable with that value', () => {
var a = x.get('a')
a.value.should.equal(1)
})
})
describe('when there is no property', () => {
it('returns a nullable of undefined', () => {
var b = x.get('b')
b.should.be.instanceof(Nullable)
chai.expect(b.value).to.equal(undefined)
})
})
})
describe('when there is not a value', () => {
const x = Nullable()
it('returns an empty nullable', () => {
var b = x.get('b')
b.should.be.instanceof(Nullable)
b.hasValue.should.equal(false)
})
})
})
describe('.orDefault', function () {
it('returns default argument if not hasValue', function () {
var x = Nullable(null)
x.orDefault(108).should.equal(108)
})
it('returns the value if hasValue', function () {
var y = Nullable(23)
y.orDefault(108).should.equal(23)
})
})
describe('.valueOf', function () {
it('returns the same as .value', function () {
chai.expect(Nullable(null).valueOf()).to.equal(null)
Nullable(12).valueOf().should.equal(12)
})
})
describe('.toString', function () {
it('is custom', function () {
Nullable.empty().toString().should.equal('')
Nullable.of(12).toString().should.equal('12')
Nullable.of('abc').toString().should.equal('abc')
Nullable.of({}).toString().should.equal('[object Object]')
})
})
describe('properties', () => {
const a = Nullable.of('a')
describe('empty', () => {
it('empty', () => {
Nullable.empty().should.be.instanceof(Nullable)
Nullable().eq(Nullable.empty()).should.equal(true)
})
})
describe('eq', () => {
it('undef eq null', () => {
Nullable.of(undefined).eq(Nullable.of(null)).should.equal(true)
})
})
it('identity', () => {
const a2 = a.map(x => x)
a2.eq(a).should.equal(true)
})
it('composition', () => {
const a = Nullable.of('a')
const b = Nullable.of(a)
a.eq(b).should.equal(true)
})
})
})
|
apos.define('apostrophe-workflow-modified-documents-manager-modal', {
extend: 'apostrophe-pieces-manager-modal',
construct: function(self, option) {
self.onChange = function() {
// We refresh list view on *all* doc changes, not just one piece type
self.refresh();
};
var superBeforeShow = self.beforeShow;
self.beforeShow = function(callback) {
// Watch for more types of changes that should refresh the list
apos.on('workflowSubmitted', self.onChange);
apos.on('workflowCommitted', self.onChange);
apos.on('workflowRevertedToLive', self.onChange);
return superBeforeShow(callback);
};
var superAfterHide = self.afterHide;
self.afterHide = function() {
superAfterHide();
// So we don't leak memory and keep refreshing
// after we're gone
apos.off('workflowSubmitted', self.onChange);
apos.off('workflowCommitted', self.onChange);
apos.off('workflowRevertedToLive', self.onChange);
};
}
});
|
'use strict';
/* import all background scripts */
import './background';
|
define([], function () {
'use strict';
function WizardService($filter, Restangular) {
this.getConfig = getConfig;
/**
* Implementation
*/
function getConfig(configName, filter, successCbk) {
var config = Restangular.oneUrl('config','./app/modules/pce/data/' + configName + '.json');
return config.get().then(function (response) {
if ( response.steps ) {
var data = filterConfig(filter, response.steps);
successCbk(data);
} else {
console.warn('INFO :: couldn\'t load wizard config file');
}
}, function () {
console.warn('INFO :: couldn\'t load wizard config file');
});
}
function filterConfig(filter, config) {
if(!filter) {
return config;
}
return config.filter(function(step) {
if(step['visible-value'].indexOf(filter) >= 0) {
return step;
}
});
}
}
WizardService.$inject=['$filter', 'Restangular'];
return WizardService;
});
|
import dotenv from 'dotenv'
import { join } from 'path'
const cwd = process.cwd()
export const CONFIG = 'chenv.config.js'
export const loadCredentials = (envValue) => {
const { error } = dotenv.config({
path: (envValue && typeof envValue === 'string')
? envValue
: join(cwd, '.env')
})
if (error) console.warn(error.message)
const {
CLIENT_ID: client_id,
CLIENT_SECRET: client_secret,
REFRESH_TOKEN: refresh_token,
} = process.env
return { client_id, client_secret, refresh_token }
}
export const loadConfig = (configValue) => {
let config = {}
if (configValue) {
config = require(join(cwd, configValue))
} else {
try {
config = require(join(cwd, CONFIG))
} catch(err) {
if (!err.message.includes(CONFIG)) throw err
try {
const { chenv = {} } = require(join(cwd, 'package.json')) || {}
config = chenv
} catch(err) {
if (!err.message.includes('package.json')) throw err
}
}
}
return 'default' in config ? config['default'] : config
}
/*
export const loadRequire = (requireValue) =>
requireValue
.split(',')
.forEach(moduleName => require(moduleName))
*/ |
var React = require('react');
var Results = require('../components/Results');
var ErrorMsg = require('../components/Error');
var PropTypes = React.PropTypes;
var apiHelper = require('../utils/apiHelper');
var ResultsContainer = React.createClass({
contextTypes: {
router: React.PropTypes.object.isRequired
},
getInitialState: function() {
return {
isLoading: true,
airQuality: {}
}
},
componentDidMount: function() {
var query = this.props.params.location;
apiHelper.getAirQuality(query)
.then(function(data){
this.setState({
isLoading: false,
airQuality: data,
})
}.bind(this))
},
render: function() {
return (
<Results
header={this.props.params.location}
isLoading={this.state.isLoading}
airQuality={this.state.airQuality}
/>
)
}
});
module.exports = ResultsContainer;
|
// Defines routes for app.
var AppRouter = Backbone.Router.extend({
routes: {
// Basic route:
"register" : "registerUser",
// Route with params:
"market/:id" : "getMarket",
// Route with optional params:
"paypalpaymentapproved(/:params)" : "paypalPaymentApproved",
// Default route.
"*actions" : "defaultRoute"
}
});
|
/* ===================================================
* jquery-sortable.js v0.9.13
* http://johnny.github.com/jquery-sortable/
* ===================================================
* Copyright (c) 2012 Jonas von Andrian
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ========================================================== */
!function ( $, window, pluginName, undefined){
var containerDefaults = {
// If true, items can be dragged from this container
drag: true,
// If true, items can be droped onto this container
drop: true,
// Exclude items from being draggable, if the
// selector matches the item
exclude: "",
// If true, search for nested containers within an item.If you nest containers,
// either the original selector with which you call the plugin must only match the top containers,
// or you need to specify a group (see the bootstrap nav example)
nested: true,
// If true, the items are assumed to be arranged vertically
vertical: true
}, // end container defaults
groupDefaults = {
// This is executed after the placeholder has been moved.
// $closestItemOrContainer contains the closest item, the placeholder
// has been put at or the closest empty Container, the placeholder has
// been appended to.
afterMove: function ($placeholder, container, $closestItemOrContainer) {
},
// The exact css path between the container and its items, e.g. "> tbody"
containerPath: "",
// The css selector of the containers
containerSelector: "ol, ul",
// Distance the mouse has to travel to start dragging
distance: 0,
// Time in milliseconds after mousedown until dragging should start.
// This option can be used to prevent unwanted drags when clicking on an element.
delay: 0,
// The css selector of the drag handle
handle: "",
// The exact css path between the item and its subcontainers.
// It should only match the immediate items of a container.
// No item of a subcontainer should be matched. E.g. for ol>div>li the itemPath is "> div"
itemPath: "",
// The css selector of the items
itemSelector: "li",
// The class given to "body" while an item is being dragged
bodyClass: "dragging",
// The class giving to an item while being dragged
draggedClass: "dragged",
// Check if the dragged item may be inside the container.
// Use with care, since the search for a valid container entails a depth first search
// and may be quite expensive.
isValidTarget: function ($item, container) {
return true
},
// Executed before onDrop if placeholder is detached.
// This happens if pullPlaceholder is set to false and the drop occurs outside a container.
onCancel: function ($item, container, _super, event) {
},
// Executed at the beginning of a mouse move event.
// The Placeholder has not been moved yet.
onDrag: function ($item, position, _super, event) {
$item.css(position)
},
// Called after the drag has been started,
// that is the mouse button is being held down and
// the mouse is moving.
// The container is the closest initialized container.
// Therefore it might not be the container, that actually contains the item.
onDragStart: function ($item, container, _super, event) {
$item.css({
height: $item.outerHeight(),
width: $item.outerWidth()
})
$item.addClass(container.group.options.draggedClass)
$("body").addClass(container.group.options.bodyClass)
},
// Called when the mouse button is being released
onDrop: function ($item, container, _super, event) {
$item.removeClass(container.group.options.draggedClass).removeAttr("style")
$("body").removeClass(container.group.options.bodyClass)
},
// Called on mousedown. If falsy value is returned, the dragging will not start.
// Ignore if element clicked is input, select or textarea
onMousedown: function ($item, _super, event) {
if (!event.target.nodeName.match(/^(input|select|textarea)$/i)) {
event.preventDefault()
return true
}
},
// The class of the placeholder (must match placeholder option markup)
placeholderClass: "placeholder",
// Template for the placeholder. Can be any valid jQuery input
// e.g. a string, a DOM element.
// The placeholder must have the class "placeholder"
placeholder: '<li class="placeholder"></li>',
// If true, the position of the placeholder is calculated on every mousemove.
// If false, it is only calculated when the mouse is above a container.
pullPlaceholder: true,
// Specifies serialization of the container group.
// The pair $parent/$children is either container/items or item/subcontainers.
serialize: function ($parent, $children, parentIsContainer) {
var result = $.extend({}, $parent.data())
if(parentIsContainer)
return [$children]
else if ($children[0]){
result.children = $children
}
delete result.subContainers
delete result.sortable
return result
},
// Set tolerance while dragging. Positive values decrease sensitivity,
// negative values increase it.
tolerance: 0
}, // end group defaults
containerGroups = {},
groupCounter = 0,
emptyBox = {
left: 0,
top: 0,
bottom: 0,
right:0
},
eventNames = {
start: "touchstart.sortable mousedown.sortable",
drop: "touchend.sortable touchcancel.sortable mouseup.sortable",
drag: "touchmove.sortable mousemove.sortable",
scroll: "scroll.sortable"
},
subContainerKey = "subContainers"
/*
* a is Array [left, right, top, bottom] 140 845 100 138
* b is array [left, top]
*/
function d(a,b) {
var x = Math.max(
0,
a[0] - b[0],
b[0] - a[1]
),
y = Math.max(
0,
a[2] - b[1],
b[1] - a[3]
);
return x+y;
}
// 设置坐标,得到container的坐标及每个item的坐标
function setDimensions(array, dimensions, tolerance, useOffset) {
var i = array.length,
offsetMethod = useOffset ? "offset" : "position"
tolerance = tolerance || 0
while(i--){
var el = array[i].el ? array[i].el : $(array[i]),
// use fitting method
pos = el[offsetMethod]()
pos.left += parseInt(el.css('margin-left'), 10)
pos.top += parseInt(el.css('margin-top'),10)
dimensions[i] = [
pos.left - tolerance,
pos.left + el.outerWidth() + tolerance,
pos.top - tolerance,
pos.top + el.outerHeight() + tolerance
]
}
}
function getRelativePosition(pointer, element) {
var offset = element.offset()
return {
left: pointer.left - offset.left,
top: pointer.top - offset.top
}
}
function sortByDistanceDesc(dimensions, pointer, lastPointer) {
pointer = [pointer.left, pointer.top]
lastPointer = lastPointer && [lastPointer.left, lastPointer.top]
var dim,
i = dimensions.length,
distances = []
while(i--){
dim = dimensions[i]
distances[i] = [i,d(dim,pointer), lastPointer && d(dim, lastPointer)]
}
distances = distances.sort(function (a,b) {
return b[1] - a[1] || b[2] - a[2] || b[0] - a[0]
})
// last entry is the closest
return distances
}
function ContainerGroup(options) {
this.options = $.extend({}, groupDefaults, options)
this.containers = []
if(!this.options.rootGroup){
this.scrollProxy = $.proxy(this.scroll, this)
this.dragProxy = $.proxy(this.drag, this)
this.dropProxy = $.proxy(this.drop, this)
this.placeholder = $(this.options.placeholder)
if(!options.isValidTarget)
this.options.isValidTarget = undefined
}
}
ContainerGroup.get = function (options) {
if(!containerGroups[options.group]) {
if(options.group === undefined)
options.group = groupCounter ++
containerGroups[options.group] = new ContainerGroup(options)
}
return containerGroups[options.group]
}
ContainerGroup.prototype = {
dragInit: function (e, itemContainer) {
this.$document = $(itemContainer.el[0].ownerDocument)
// get item to drag
var closestItem = $(e.target).closest(this.options.itemSelector);
// using the length of this item, prevents the plugin from being started if there is no handle being clicked on.
// this may also be helpful in instantiating multidrag.
if (closestItem.length) {
this.item = closestItem;
this.itemContainer = itemContainer;
if (this.item.is(this.options.exclude) || !this.options.onMousedown(this.item, groupDefaults.onMousedown, e)) {
return;
}
this.setPointer(e);
this.toggleListeners('on');
this.setupDelayTimer();
this.dragInitDone = true;
console.log(this);
}
},
drag: function (e) {
if(!this.dragging){
if(!this.distanceMet(e) || !this.delayMet)
return
this.options.onDragStart(this.item, this.itemContainer, groupDefaults.onDragStart, e)
this.item.before(this.placeholder)
this.dragging = true
}
this.setPointer(e)
//把 item 跟随光标
this.options.onDrag(this.item,
getRelativePosition(this.pointer, this.item.offsetParent()),
groupDefaults.onDrag,
e)
var p = this.getPointer(e),
box = this.sameResultBox,
t = this.options.tolerance
if(!box || box.top - t > p.top || box.bottom + t < p.top || box.left - t > p.left || box.right + t < p.left)
if(!this.searchValidTarget()){
this.placeholder.detach()
this.lastAppendedItem = undefined
}
},
drop: function (e) {
this.toggleListeners('off')
this.dragInitDone = false
if(this.dragging){
// processing Drop, check if placeholder is detached
if(this.placeholder.closest("html")[0]){
this.placeholder.before(this.item).detach()
} else {
this.options.onCancel(this.item, this.itemContainer, groupDefaults.onCancel, e)
}
this.options.onDrop(this.item, this.getContainer(this.item), groupDefaults.onDrop, e)
// cleanup
this.clearDimensions()
this.clearOffsetParent()
this.lastAppendedItem = this.sameResultBox = undefined
this.dragging = false
}
},
searchValidTarget: function (pointer, lastPointer) {
if(!pointer){
pointer = this.relativePointer || this.pointer
lastPointer = this.lastRelativePointer || this.lastPointer
}
var distances = sortByDistanceDesc(this.getContainerDimensions(),
pointer,
lastPointer),
i = distances.length
while(i--){
var index = distances[i][0],
distance = distances[i][1]
if(!distance || this.options.pullPlaceholder){
var container = this.containers[index]
if(!container.disabled){
if(!this.$getOffsetParent()){
var offsetParent = container.getItemOffsetParent()
pointer = getRelativePosition(pointer, offsetParent)
lastPointer = getRelativePosition(lastPointer, offsetParent)
}
if(container.searchValidTarget(pointer, lastPointer))
return true
}
}
}
if(this.sameResultBox)
this.sameResultBox = undefined
},
movePlaceholder: function (container, item, method, sameResultBox) {
var lastAppendedItem = this.lastAppendedItem
if(!sameResultBox && lastAppendedItem && lastAppendedItem[0] === item[0])
return;
item[method](this.placeholder)
this.lastAppendedItem = item
this.sameResultBox = sameResultBox
this.options.afterMove(this.placeholder, container, item)
},
getContainerDimensions: function () {
if(!this.containerDimensions)
setDimensions(this.containers, this.containerDimensions = [], this.options.tolerance, !this.$getOffsetParent())
return this.containerDimensions
},
getContainer: function (element) {
return element.closest(this.options.containerSelector).data(pluginName)
},
$getOffsetParent: function () {
if(this.offsetParent === undefined){
var i = this.containers.length - 1,
offsetParent = this.containers[i].getItemOffsetParent()
if(!this.options.rootGroup){
while(i--){
if(offsetParent[0] != this.containers[i].getItemOffsetParent()[0]){
// If every container has the same offset parent,
// use position() which is relative to this parent,
// otherwise use offset()
// compare #setDimensions
offsetParent = false
break;
}
}
}
this.offsetParent = offsetParent
}
return this.offsetParent
},
setPointer: function (e) {
var pointer = this.getPointer(e)
if(this.$getOffsetParent()){
var relativePointer = getRelativePosition(pointer, this.$getOffsetParent())
this.lastRelativePointer = this.relativePointer
this.relativePointer = relativePointer
}
this.lastPointer = this.pointer
this.pointer = pointer
},
distanceMet: function (e) {
var currentPointer = this.getPointer(e)
return (Math.max(
Math.abs(this.pointer.left - currentPointer.left),
Math.abs(this.pointer.top - currentPointer.top)
) >= this.options.distance)
},
getPointer: function(e) {
var o = e.originalEvent || e.originalEvent.touches && e.originalEvent.touches[0]
return {
left: e.pageX || o.pageX,
top: e.pageY || o.pageY
}
},
setupDelayTimer: function () {
var that = this
this.delayMet = !this.options.delay
// init delay timer if needed
if (!this.delayMet) {
clearTimeout(this._mouseDelayTimer);
this._mouseDelayTimer = setTimeout(function() {
that.delayMet = true
}, this.options.delay)
}
},
scroll: function (e) {
this.clearDimensions()
this.clearOffsetParent() // TODO is this needed?
},
toggleListeners: function (method) {
var that = this,
events = ['drag','drop','scroll']
$.each(events,function (i,event) {
that.$document[method](eventNames[event], that[event + 'Proxy'])
})
},
clearOffsetParent: function () {
this.offsetParent = undefined
},
// Recursively clear container and item dimensions
clearDimensions: function () {
this.traverse(function(object){
object._clearDimensions()
})
},
traverse: function(callback) {
callback(this)
var i = this.containers.length
while(i--){
this.containers[i].traverse(callback)
}
},
_clearDimensions: function(){
this.containerDimensions = undefined
},
_destroy: function () {
containerGroups[this.options.group] = undefined
}
}
function Container(element, options) {
this.el = element
this.options = $.extend( {}, containerDefaults, options)
this.group = ContainerGroup.get(this.options)
this.rootGroup = this.options.rootGroup || this.group
this.handle = this.rootGroup.options.handle || this.rootGroup.options.itemSelector
var itemPath = this.rootGroup.options.itemPath
this.target = itemPath ? this.el.find(itemPath) : this.el
this.target.on(eventNames.start, this.handle, $.proxy(this.dragInit, this))
if(this.options.drop)
this.group.containers.push(this)
}
Container.prototype = {
dragInit: function (e) {
var rootGroup = this.rootGroup
if( !this.disabled &&
!rootGroup.dragInitDone &&
this.options.drag &&
this.isValidDrag(e)) {
rootGroup.dragInit(e, this)
}
},
isValidDrag: function(e) {
return e.which == 1 ||
e.type == "touchstart" && e.originalEvent.touches.length == 1
},
searchValidTarget: function (pointer, lastPointer) {
var distances = sortByDistanceDesc(this.getItemDimensions(),
pointer,
lastPointer),
i = distances.length,
rootGroup = this.rootGroup,
validTarget = !rootGroup.options.isValidTarget ||
rootGroup.options.isValidTarget(rootGroup.item, this)
if(!i && validTarget){
rootGroup.movePlaceholder(this, this.target, "append")
return true
} else
while(i--){
var index = distances[i][0],
distance = distances[i][1]
if(!distance && this.hasChildGroup(index)){
var found = this.getContainerGroup(index).searchValidTarget(pointer, lastPointer)
if(found)
return true
}
else if(validTarget){
this.movePlaceholder(index, pointer)
return true
}
}
},
movePlaceholder: function (index, pointer) {
var item = $(this.items[index]),
dim = this.itemDimensions[index],
method = "after",
width = item.outerWidth(),
height = item.outerHeight(),
offset = item.offset(),
sameResultBox = {
left: offset.left,
right: offset.left + width,
top: offset.top,
bottom: offset.top + height
}
if(this.options.vertical){
var yCenter = (dim[2] + dim[3]) / 2,
inUpperHalf = pointer.top <= yCenter
if(inUpperHalf){
method = "before"
sameResultBox.bottom -= height / 2
} else
sameResultBox.top += height / 2
} else {
var xCenter = (dim[0] + dim[1]) / 2,
inLeftHalf = pointer.left <= xCenter
if(inLeftHalf){
method = "before"
sameResultBox.right -= width / 2
} else
sameResultBox.left += width / 2
}
if(this.hasChildGroup(index))
sameResultBox = emptyBox
this.rootGroup.movePlaceholder(this, item, method, sameResultBox)
},
getItemDimensions: function () {
if(!this.itemDimensions){
this.items = this.$getChildren(this.el, "item").filter(
":not(." + this.group.options.placeholderClass + ", ." + this.group.options.draggedClass + ")"
).get()
setDimensions(this.items, this.itemDimensions = [], this.options.tolerance)
}
return this.itemDimensions
},
getItemOffsetParent: function () {
var offsetParent,
el = this.el
// Since el might be empty we have to check el itself and
// can not do something like el.children().first().offsetParent()
if(el.css("position") === "relative" || el.css("position") === "absolute" || el.css("position") === "fixed")
offsetParent = el
else
offsetParent = el.offsetParent()
return offsetParent
},
hasChildGroup: function (index) {
return this.options.nested && this.getContainerGroup(index)
},
getContainerGroup: function (index) {
var childGroup = $.data(this.items[index], subContainerKey)
if( childGroup === undefined){
var childContainers = this.$getChildren(this.items[index], "container")
childGroup = false
if(childContainers[0]){
var options = $.extend({}, this.options, {
rootGroup: this.rootGroup,
group: groupCounter ++
})
childGroup = childContainers[pluginName](options).data(pluginName).group
}
$.data(this.items[index], subContainerKey, childGroup)
}
return childGroup
},
$getChildren: function (parent, type) {
var options = this.rootGroup.options,
path = options[type + "Path"],
selector = options[type + "Selector"]
parent = $(parent)
if(path)
parent = parent.find(path)
return parent.children(selector)
},
_serialize: function (parent, isContainer) {
var that = this,
childType = isContainer ? "item" : "container",
children = this.$getChildren(parent, childType).not(this.options.exclude).map(function () {
return that._serialize($(this), !isContainer)
}).get()
return this.rootGroup.options.serialize(parent, children, isContainer)
},
traverse: function(callback) {
$.each(this.items || [], function(item){
var group = $.data(this, subContainerKey)
if(group)
group.traverse(callback)
});
callback(this)
},
_clearDimensions: function () {
this.itemDimensions = undefined
},
_destroy: function() {
var that = this;
this.target.off(eventNames.start, this.handle);
this.el.removeData(pluginName)
if(this.options.drop)
this.group.containers = $.grep(this.group.containers, function(val){
return val != that
})
$.each(this.items || [], function(){
$.removeData(this, subContainerKey)
})
}
}
var API = {
enable: function() {
this.traverse(function(object){
object.disabled = false
})
},
disable: function (){
this.traverse(function(object){
object.disabled = true
})
},
serialize: function () {
return this._serialize(this.el, true)
},
refresh: function() {
this.traverse(function(object){
object._clearDimensions()
})
},
destroy: function () {
this.traverse(function(object){
object._destroy();
})
}
}
$.extend(Container.prototype, API)
/**
* jQuery API
*
* Parameters are
* either options on init
* or a method name followed by arguments to pass to the method
*/
$.fn[pluginName] = function(methodOrOptions) {
var args = Array.prototype.slice.call(arguments, 1)
return this.map(function(){
var $t = $(this),
object = $t.data(pluginName)
if(object && API[methodOrOptions])
return API[methodOrOptions].apply(object, args) || this
else if(!object && (methodOrOptions === undefined ||
typeof methodOrOptions === "object"))
$t.data(pluginName, new Container($t, methodOrOptions))
return this
});
};
}(jQuery, window, 'sortable');
|
var create = require('./create');
var render = require('../../var/string/html');
var html = require('./html');
var isString = require('../../var/is/string');
var tmp_div;
module.exports = function(attrs, tag, inner) {
tmp_div = tmp_div || create();
html((isString(attrs) && attrs.indexOf('<') > -1) ? attrs : render(inner, attrs, tag), tmp_div);
return tmp_div.removeChild(tmp_div.firstChild);
};
|
var appConstants = {
'EVENT_SHOW_LOGIN': 'event:show:login',
'EVENT_SHOW_HOME': 'event:show:home',
'EVENT_REDIRECT_TO_HOME': 'rcommand:redirect-to:home'
}
export {appConstants as default} |
/*
* ProductHighlights Messages
*
* This contains all the text for the ProductHighlights component.
*/
import { defineMessages } from 'react-intl';
export default defineMessages({
header: {
id: 'app.components.ProductHighlights.header',
defaultMessage: 'product highlights',
},
});
|
module.exports = {
InitializedEvent: require('./event/InitializedEvent.js'),
ShutdownEvent: require('./event/ShutdownEvent.js'),
NewArticleEvent: require('./event/NewArticleEvent.js'),
ArticleCommentChangedEvent: require('./event/ArticleCommentChangedEvent.js'),
CafeMemberChangedEvent: require('./event/CafeMemberChangedEvent.js')
};
|
yarr.controller('PlaceController', ['$scope', '$stateParams', '$state' , 'Places', 'Ratings', 'Users', 'Auth', function($scope, $stateParams, $state, Places, Ratings, Users, Auth) {
$scope.place = Places.get({ id: $stateParams.id });
$scope.ratings = Ratings.query({ place: $stateParams.id });
$scope.ratings.$promise.then(function(ratings) {
var functionForger = function(index) {
return function(user) {
ratings[index].username = user.username;
}
}
for (var i = 0; i < ratings.length; i++) {
var rating = ratings[i];
Users.get({id : rating.user}).$promise.then(functionForger(i));
}
});
$scope.loadMoreRatings = function() {
$scope.ratingsLoading = true;
var page = Ratings.query({ offset: $scope.ratings.length, place: $stateParams.id });
page.$promise.then(function(ratings) {
var functionForger = function(index) {
return function(users) {
ratings[index].username = users.username;
}
}
for (var i = 0; i < ratings.length; i++) {
var rating = ratings[i];
Users.get({id : rating.user}).$promise.then(functionForger(i));
}
$scope.ratingsLoading = false;
[].push.apply($scope.ratings, ratings);
});
}
$scope.writeRating = false;
$scope.ratingData = {
stars : null,
commentary : null,
place : $stateParams.id,
user : null
};
$scope.initialRatingData = {
stars : null,
commentary : null,
place : $stateParams.id,
user: null
}
if (Auth.user()) {
$scope.ratingData.user = Auth.user().id;
$scope.initialRatingData.user = Auth.user().id;
}
$scope.userHasRating = false;
$scope.userRatingId = null;
if ($scope.initialRatingData.user) {
Ratings.query({place: $scope.initialRatingData.place, user: $scope.initialRatingData.user}).$promise.then(function(data) {
if (data.length > 0) {
$scope.userRatingId = data[0].id;
$scope.userHasRating = true;
$scope.ratingData.stars = data[0].stars;
$scope.ratingData.commentary = data[0].commentary;
$scope.initialRatingData.stars = data[0].stars;
$scope.initialRatingData.commentary = data[0].commentary;
}
});
}
$scope.submitRating = function() {
var serializedRating = JSON.stringify($scope.ratingData);
if ($scope.userHasRating) {
Ratings.update({ id : $scope.userRatingId } ,serializedRating).$promise.then(function(response) {
alert('Rating updated!');
$state.transitionTo($state.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});
}, function(error) {
alert('Unable to update rating!');
});
} else {
Ratings.save(serializedRating).$promise.then(function(response){
alert('Rating submitted!');
$state.transitionTo($state.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});
}, function(error) {
alert('Unable to submit rating!');
});
}
};
$scope.cancelWriteRating = function() {
$scope.writeRating = false;
$scope.ratingData.stars = $scope.initialRatingData.stars;
$scope.ratingData.commentary = $scope.initialRatingData.commentary;
};
}]);
|
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define('/Site', ['exports', 'jquery', 'Base', 'Menubar', 'Sidebar', 'PageAside'], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require('jquery'), require('Base'), require('Menubar'), require('Sidebar'), require('PageAside'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.jQuery, global.Base, global.SectionMenubar, global.SectionSidebar, global.SectionPageAside);
global.Site = mod.exports;
}
})(this, function (exports, _jquery, _Base2, _Menubar, _Sidebar, _PageAside) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getInstance = exports.run = exports.Site = undefined;
var _jquery2 = babelHelpers.interopRequireDefault(_jquery);
var _Base3 = babelHelpers.interopRequireDefault(_Base2);
var _Menubar2 = babelHelpers.interopRequireDefault(_Menubar);
var _Sidebar2 = babelHelpers.interopRequireDefault(_Sidebar);
var _PageAside2 = babelHelpers.interopRequireDefault(_PageAside);
var DOC = document;
var $DOC = (0, _jquery2.default)(document);
var $BODY = (0, _jquery2.default)('body');
var Site = function (_Base) {
babelHelpers.inherits(Site, _Base);
function Site() {
babelHelpers.classCallCheck(this, Site);
return babelHelpers.possibleConstructorReturn(this, (Site.__proto__ || Object.getPrototypeOf(Site)).apply(this, arguments));
}
babelHelpers.createClass(Site, [{
key: 'willProcess',
value: function willProcess() {
this.startLoading();
this.initializePluginAPIs();
this.initializePlugins();
}
}, {
key: 'processed',
value: function processed() {
this.polyfillIEWidth();
this.initBootstrap();
this.setupMenubar();
this.setupFullScreen();
this.setupMegaNavbar();
// Dropdown menu setup
// ===================
this.$el.on('click', '.dropdown-menu-media', function (e) {
e.stopPropagation();
});
}
}, {
key: '_getDefaultMeunbarType',
value: function _getDefaultMeunbarType() {
return 'hide';
}
}, {
key: 'getDefaultState',
value: function getDefaultState() {
var menubarType = this._getDefaultMeunbarType();
return {
menubarType: menubarType
};
}
}, {
key: 'getDefaultActions',
value: function getDefaultActions() {
return {
menubarType: function menubarType(type) {
(0, _jquery2.default)('[data-toggle="menubar"]').each(function () {
var $this = (0, _jquery2.default)(this);
var $hamburger = (0, _jquery2.default)(this).find('.hamburger');
if ($hamburger.length > 0) {
$hamburger.toggleClass('hided', !(type === 'open'));
} else {
$this.toggleClass('hided', !(type === 'open'));
}
});
}
};
}
}, {
key: 'getDefaultChildren',
value: function getDefaultChildren() {
this.menubar = new _Menubar2.default({
$el: (0, _jquery2.default)('.site-menubar')
});
this.sidebar = new _Sidebar2.default();
var children = [this.menubar, this.sidebar];
var $aside = (0, _jquery2.default)('.page-aside');
if ($aside.length > 0) {
children.push(new _PageAside2.default({
$el: $aside
}));
}
return children;
}
}, {
key: 'getCurrentBreakpoint',
value: function getCurrentBreakpoint() {
var bp = Breakpoints.current();
return bp ? bp.name : 'lg';
}
}, {
key: 'initBootstrap',
value: function initBootstrap() {
// Tooltip setup
// =============
$DOC.tooltip({
selector: '[data-tooltip=true]',
container: 'body'
});
(0, _jquery2.default)('[data-toggle="tooltip"]').tooltip();
(0, _jquery2.default)('[data-toggle="popover"]').popover();
}
}, {
key: 'polyfillIEWidth',
value: function polyfillIEWidth() {
if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
var msViewportStyle = DOC.createElement('style');
msViewportStyle.appendChild(DOC.createTextNode('@-ms-viewport{width:auto!important}'));
DOC.querySelector('head').appendChild(msViewportStyle);
}
}
}, {
key: 'setupFullScreen',
value: function setupFullScreen() {
if (typeof screenfull !== 'undefined') {
$DOC.on('click', '[data-toggle="fullscreen"]', function () {
if (screenfull.enabled) {
screenfull.toggle();
}
return false;
});
if (screenfull.enabled) {
DOC.addEventListener(screenfull.raw.fullscreenchange, function () {
(0, _jquery2.default)('[data-toggle="fullscreen"]').toggleClass('active', screenfull.isFullscreen);
});
}
}
}
}, {
key: 'setupMegaNavbar',
value: function setupMegaNavbar() {
$DOC.on('click', '.navbar-mega .dropdown-menu', function (e) {
e.stopPropagation();
}).on('show.bs.dropdown', function (e) {
var $target = (0, _jquery2.default)(e.target);
var $trigger = e.relatedTarget ? (0, _jquery2.default)(e.relatedTarget) : $target.children('[data-toggle="dropdown"]');
var animation = $trigger.data('animation');
if (animation) {
(function () {
var $menu = $target.children('.dropdown-menu');
$menu.addClass('animation-' + animation).one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function () {
$menu.removeClass('animation-' + animation);
});
})();
}
}).on('shown.bs.dropdown', function (e) {
var $menu = (0, _jquery2.default)(e.target).find('.dropdown-menu-media > .list-group');
if ($menu.length > 0) {
var api = $menu.data('asScrollable');
if (api) {
api.update();
} else {
$menu.asScrollable({
namespace: 'scrollable',
contentSelector: '> [data-role=\'content\']',
containerSelector: '> [data-role=\'container\']'
});
}
}
});
}
}, {
key: 'setupMenubar',
value: function setupMenubar() {
var _this2 = this;
(0, _jquery2.default)(document).on('click', '[data-toggle="menubar"]', function () {
var type = _this2.getState('menubarType');
switch (type) {
case 'open':
type = 'hide';
break;
case 'hide':
type = 'open';
break;
// no default
}
_this2.setState('menubarType', type);
return false;
});
(0, _jquery2.default)(document).on('collapsed.site.menu expanded.site.menu', function () {
var type = _this2.getState('menubarType');
if (type === 'open' && _this2.menubar && _this2.menubar.scrollable) {
_this2.menubar.scrollable.update();
}
});
Breakpoints.on('change', function () {
_this2.setState('menubarType', _this2._getDefaultMeunbarType());
});
}
}, {
key: 'startLoading',
value: function startLoading() {
if (typeof _jquery2.default.fn.animsition === 'undefined') {
return false;
}
// let loadingType = 'default';
$BODY.animsition({
inClass: 'fade-in',
inDuration: 800,
loading: true,
loadingClass: 'loader-overlay',
loadingParentElement: 'html',
loadingInner: '\n <div class="loader-content">\n <img src="' + Config.get('assets') + '/images/logo-mbl.png">\n <h2>OnDefend</h2>\n <div class="loader-index">\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n </div>\n </div>',
onLoadEvent: true
});
}
}]);
return Site;
}(_Base3.default);
var instance = null;
function getInstance() {
if (!instance) {
instance = new Site();
}
return instance;
}
function run() {
var site = getInstance();
site.run();
}
exports.default = Site;
exports.Site = Site;
exports.run = run;
exports.getInstance = getInstance;
});
|
const mysqlCmds = require('./commands.js')
var rssConfig = require('../../config.json')
var mysql, sqlite3
if (rssConfig.sqlType.toLowerCase() == "mysql") mysql = require('mysql');
else if (rssConfig.sqlType.toLowerCase() == "sqlite3") sqlite3 = require('sqlite3').verbose();
const credentials = require('../../mysqlCred.json')
module.exports = function (callback) {
if (typeof rssConfig.sqlType !== "string") return null;
else if (rssConfig.sqlType.toLowerCase() == "mysql") {
var con, iterations = 0;
(function startDataProcessing() {
con = mysql.createConnection(credentials); //MySQL connections will automatically close unless new connections are made
con.connect(function(err){
if(err){
throw err;
console.log('Error connecting to database ' + rssConfig.databaseName + '. Attempting to reconnect.');
//setTimeout(startDataProcessing, 2000);
}
else {
con.query('create database if not exists `' + rssConfig.databaseName + '`', function (err) {
if (err) throw err;
})
con.query('use ' + rssConfig.databaseName, function (err) {
if (err) throw err;
})
callback();
}
});
// con.on('error', function(err) {
// if(err.code === 'PROTOCOL_CONNECTION_LOST') {
// startDataProcessing();
// iterations++;
// }
// else throw err;
// });
})()
return con;
}
//so much simpler!
else if (rssConfig.sqlType.toLowerCase() == "sqlite3") {
return new sqlite3.Database(`./${rssConfig.databaseName}.db`, callback);
}
else return null;
}
|
const each = require("./each.js");
const flatten = require("./flatten.js");
const isBool = require("../object/isBool.js");
/**
* Get a new array of values transformed by a function.
* @param {Object} col The collection to evaluate
* @param {Function} fn The function to apply
* @param {Object} scope The context to bound to
* @param {Boolean} deep If true, make iteration on nested arrays and objects
* @returns {Array} The new array of values
*/
function map(col, fn, scope, deep)
{
deep = deep || isBool(scope) ? scope : false;
var ret = [];
each(deep ? flatten(col) : col, function (value, index, ref)
{
ret.push(fn.call(scope || this, value, index, ref));
});
return ret;
}
module.exports = map; |
'use strict';
var fs = require('fs');
var expect = require('chai').expect;
var LintReporter = require('../src/js/lint-reporter');
describe('LintReporter', function() {
describe('runReport(jsonOutput)', function() {
});
});
|
/*******************************
Install Task
*******************************/
/*
Install tasks
For more notes
* Runs automatically after npm update (hooks)
* (NPM) Install - Will ask for where to put semantic (outside pm folder)
* (NPM) Upgrade - Will look for semantic install, copy over files and update if new version
* Standard installer runs asking for paths to site files etc
*/
var
gulp = require('gulp'),
// node dependencies
console = require('better-console'),
extend = require('extend'),
fs = require('fs'),
mkdirp = require('mkdirp'),
path = require('path'),
runSequence = require('run-sequence'),
// gulp dependencies
chmod = require('gulp-chmod'),
del = require('del'),
jsonEditor = require('gulp-json-editor'),
plumber = require('gulp-plumber'),
prompt = require('gulp-prompt'),
rename = require('gulp-rename'),
replace = require('gulp-replace'),
requireDotFile = require('require-dot-file'),
wrench = require('wrench'),
// install config
install = require('./config/project/install'),
// user config
config = require('./config/user'),
// release config (name/title/etc)
release = require('./config/project/release'),
// shorthand
questions = install.questions,
files = install.files,
folders = install.folders,
regExp = install.regExp,
settings = install.settings,
source = install.source
;
// Export install task
module.exports = function (callback) {
var
currentConfig = requireDotFile('semantic.json'),
manager = install.getPackageManager(),
rootQuestions = questions.root,
installFolder = false,
answers
;
console.clear();
/* Test NPM install
manager = {
name : 'NPM',
root : path.normalize(__dirname + '/../')
};
*/
/* Don't do end user config if SUI is a sub-module */
if( install.isSubModule() ) {
console.info('SUI is a sub-module, skipping end-user install');
return;
}
/*-----------------
Update SUI
-----------------*/
// run update scripts if semantic.json exists
if(currentConfig && manager.name === 'NPM') {
var
updateFolder = path.join(manager.root, currentConfig.base),
updatePaths = {
config : path.join(manager.root, files.config),
tasks : path.join(updateFolder, folders.tasks),
themeImport : path.join(updateFolder, folders.themeImport),
definition : path.join(currentConfig.paths.source.definitions),
site : path.join(currentConfig.paths.source.site),
theme : path.join(currentConfig.paths.source.themes),
defaultTheme : path.join(currentConfig.paths.source.themes, folders.defaultTheme)
}
;
// duck-type if there is a project installed
if( fs.existsSync(updatePaths.definition) ) {
// perform update if new version
if(currentConfig.version !== release.version) {
console.log('Updating Semantic UI from ' + currentConfig.version + ' to ' + release.version);
console.info('Updating ui definitions...');
wrench.copyDirSyncRecursive(source.definitions, updatePaths.definition, settings.wrench.overwrite);
console.info('Updating default theme...');
wrench.copyDirSyncRecursive(source.themes, updatePaths.theme, settings.wrench.merge);
wrench.copyDirSyncRecursive(source.defaultTheme, updatePaths.defaultTheme, settings.wrench.overwrite);
console.info('Updating tasks...');
wrench.copyDirSyncRecursive(source.tasks, updatePaths.tasks, settings.wrench.overwrite);
console.info('Updating gulpfile.js');
gulp.src(source.userGulpFile)
.pipe(plumber())
.pipe(gulp.dest(updateFolder))
;
// copy theme import
console.info('Updating theme import file');
gulp.src(source.themeImport)
.pipe(plumber())
.pipe(gulp.dest(updatePaths.themeImport))
;
console.info('Adding new site theme files...');
wrench.copyDirSyncRecursive(source.site, updatePaths.site, settings.wrench.merge);
console.info('Updating version...');
// update version number in semantic.json
gulp.src(updatePaths.config)
.pipe(plumber())
.pipe(rename(settings.rename.json)) // preserve file extension
.pipe(jsonEditor({
version: release.version
}))
.pipe(gulp.dest(manager.root))
;
console.info('Update complete! Run "\033[92mgulp build\033[0m" to rebuild dist/ files.');
return;
}
else {
console.log('Current version of Semantic UI already installed');
return;
}
}
else {
console.error('Cannot locate files to update at path: ', updatePaths.definition);
console.log('Running installer');
}
}
/*--------------
Determine Root
---------------*/
// PM that supports Build Tools (NPM Only Now)
if(manager.name == 'NPM') {
rootQuestions[0].message = rootQuestions[0].message
.replace('{packageMessage}', 'We detected you are using \033[92m' + manager.name + '\033[0m. Nice! ')
.replace('{root}', manager.root)
;
// set default path to detected PM root
rootQuestions[0].default = manager.root;
rootQuestions[1].default = manager.root;
// insert PM questions after "Install Type" question
Array.prototype.splice.apply(questions.setup, [2, 0].concat(rootQuestions));
// omit cleanup questions for managed install
questions.cleanup = [];
}
/*--------------
Create SUI
---------------*/
gulp.task('run setup', function() {
return gulp
.src('gulpfile.js')
.pipe(prompt.prompt(questions.setup, function(setupAnswers) {
// hoist
answers = setupAnswers;
}))
;
});
gulp.task('create install files', function(callback) {
/*--------------
Exit Conditions
---------------*/
// if config exists and user specifies not to proceed
if(answers.overwrite !== undefined && answers.overwrite == 'no') {
return;
}
console.clear();
console.log('Installing');
console.log('------------------------------');
/*--------------
Paths
---------------*/
var
installPaths = {
config : files.config,
configFolder : folders.config,
site : answers.site || folders.site,
themeConfig : files.themeConfig,
themeConfigFolder : folders.themeConfig
}
;
/*--------------
NPM Install
---------------*/
// Check if PM install
if(answers.useRoot || answers.customRoot) {
// Set root to custom root path if set
if(answers.customRoot) {
if(answers.customRoot === '') {
console.log('Unable to proceed, invalid project root');
return;
}
manager.root = answers.customRoot;
}
// special install paths only for PM install
installPaths = extend(false, {}, installPaths, {
definition : folders.definitions,
lessImport : folders.lessImport,
tasks : folders.tasks,
theme : folders.themes,
defaultTheme : path.join(folders.themes, folders.defaultTheme),
themeImport : folders.themeImport
});
// add project root to semantic root
installFolder = path.join(manager.root, answers.semanticRoot);
// add install folder to all output paths
for(var destination in installPaths) {
if( installPaths.hasOwnProperty(destination) ) {
// config goes in project root, rest in install folder
installPaths[destination] = (destination == 'config' || destination == 'configFolder')
? path.normalize( path.join(manager.root, installPaths[destination]) )
: path.normalize( path.join(installFolder, installPaths[destination]) )
;
}
}
// create project folders
try {
mkdirp.sync(installFolder);
mkdirp.sync(installPaths.definition);
mkdirp.sync(installPaths.theme);
mkdirp.sync(installPaths.tasks);
}
catch(error) {
console.error('NPM does not have permissions to create folders at your specified path. Adjust your folders permissions and run "npm install" again');
}
console.log('Installing to \033[92m' + answers.semanticRoot + '\033[0m');
console.info('Copying UI definitions');
wrench.copyDirSyncRecursive(source.definitions, installPaths.definition, settings.wrench.overwrite);
console.info('Copying UI themes');
wrench.copyDirSyncRecursive(source.themes, installPaths.theme, settings.wrench.merge);
wrench.copyDirSyncRecursive(source.defaultTheme, installPaths.defaultTheme, settings.wrench.overwrite);
console.info('Copying gulp tasks');
wrench.copyDirSyncRecursive(source.tasks, installPaths.tasks, settings.wrench.overwrite);
// copy theme import
console.info('Adding theme files');
gulp.src(source.themeImport)
.pipe(plumber())
.pipe(gulp.dest(installPaths.themeImport))
;
gulp.src(source.lessImport)
.pipe(plumber())
.pipe(gulp.dest(installPaths.lessImport))
;
// create gulp file
console.info('Creating gulpfile.js');
gulp.src(source.userGulpFile)
.pipe(plumber())
.pipe(gulp.dest(installFolder))
;
}
/*--------------
Site Theme
---------------*/
// Copy _site templates folder to destination
if( fs.existsSync(installPaths.site) ) {
console.info('Site folder exists, merging files (no overwrite)', installPaths.site);
}
else {
console.info('Creating site theme folder', installPaths.site);
}
wrench.copyDirSyncRecursive(source.site, installPaths.site, settings.wrench.merge);
/*--------------
Theme Config
---------------*/
gulp.task('create theme.config', function() {
var
// determine path to site theme folder from theme config
// force CSS path variable to use forward slashes for paths
pathToSite = path.relative(path.resolve(installPaths.themeConfigFolder), path.resolve(installPaths.site)).replace(/\\/g,'/'),
siteVariable = "@siteFolder : '" + pathToSite + "/';"
;
// rewrite site variable in theme.less
console.info('Adjusting @siteFolder to: ', pathToSite + '/');
if(fs.existsSync(installPaths.themeConfig)) {
console.info('Modifying src/theme.config (LESS config)', installPaths.themeConfig);
return gulp.src(installPaths.themeConfig)
.pipe(plumber())
.pipe(replace(regExp.siteVariable, siteVariable))
.pipe(gulp.dest(installPaths.themeConfigFolder))
;
}
else {
console.info('Creating src/theme.config (LESS config)', installPaths.themeConfig);
return gulp.src(source.themeConfig)
.pipe(plumber())
.pipe(rename({ extname : '' }))
.pipe(replace(regExp.siteVariable, siteVariable))
.pipe(gulp.dest(installPaths.themeConfigFolder))
;
}
});
/*--------------
Semantic.json
---------------*/
gulp.task('create semantic.json', function() {
var
jsonConfig = install.createJSON(answers)
;
// adjust variables in theme.less
if( fs.existsSync(files.config) ) {
console.info('Extending config file (semantic.json)', installPaths.config);
return gulp.src(installPaths.config)
.pipe(plumber())
.pipe(rename(settings.rename.json)) // preserve file extension
.pipe(jsonEditor(jsonConfig))
.pipe(gulp.dest(installPaths.configFolder))
;
}
else {
console.info('Creating config file (semantic.json)', installPaths.config);
return gulp.src(source.config)
.pipe(plumber())
.pipe(rename({ extname : '' })) // remove .template from ext
.pipe(jsonEditor(jsonConfig))
.pipe(gulp.dest(installPaths.configFolder))
;
}
});
runSequence(
'create theme.config',
'create semantic.json',
callback
);
});
gulp.task('clean up install', function() {
// Completion Message
if(installFolder) {
console.log('\n Setup Complete! \n Installing Peer Dependencies. \033[0;31mPlease refrain from ctrl + c\033[0m... \n After completion navigate to \033[92m' + answers.semanticRoot + '\033[0m and run "\033[92mgulp build\033[0m" to build');
process.exit();
}
else {
console.log('');
console.log('');
}
return gulp
.src('gulpfile.js')
.pipe(prompt.prompt(questions.cleanup, function(answers) {
if(answers.cleanup == 'yes') {
del(install.setupFiles);
}
if(answers.build == 'yes') {
gulp.start('build');
}
}))
;
});
runSequence(
'run setup',
'create install files',
'clean up install',
callback
);
}; |
'use strict';
angular.module('myApp.a', ['ngRoute'])
.controller('pageController', ['$scope', function ($scope) {
console.log('hello');
}]) |
// <script>
/*
=============================================================
WebIntelligence(r) Report Panel
Copyright(c) 2001-2003 Business Objects S.A.
All rights reserved
Use and support of this software is governed by the terms
and conditions of the software license agreement and support
policy of Business Objects S.A. and/or its subsidiaries.
The Business Objects products and technology are protected
by the US patent number 5,555,403 and 6,247,008
File: labels.js
=============================================================
*/
_default="Domyślny"
_black="Czarny"
_brown="Brązowy"
_oliveGreen="Oliwkowozielony"
_darkGreen="Ciemnozielony"
_darkTeal="Ciemnozielonomodry"
_navyBlue="Granatowy"
_indigo="Indygo"
_darkGray="Ciemnoszary"
_darkRed="Ciemnoczerwony"
_orange="Pomarańczowy"
_darkYellow="Ciemnożółty"
_green="Zielony"
_teal="Zielonomodry"
_blue="Niebieski"
_blueGray="Niebieskoszary"
_mediumGray="Średnioszary"
_red="Czerwony"
_lightOrange="Jasnopomarańczowy"
_lime="Limonowy"
_seaGreen="Morska zieleń"
_aqua="Akwamaryna"
_lightBlue="Jasnoniebieski"
_violet="Fioletowy"
_gray="Szary"
_magenta="Amarantowy"
_gold="Złoty"
_yellow="Żółty"
_brightGreen="Intensywny zielony"
_cyan="Błękitny"
_skyBlue="Lazurowy"
_plum="Śliwkowy"
_lightGray="Jasnoszary"
_pink="Różowy"
_tan="Pastelowobrązowy"
_lightYellow="Jasnożółty"
_lightGreen="Jasnozielony"
_lightTurquoise="Jasnoturkusowy"
_paleBlue="Bladoniebieski"
_lavender="Lawendowy"
_white="Biały"
_lastUsed="Ostatnio używany:"
_moreColors="Więcej kolorów..."
_month=new Array
_month[0]="Styczeń"
_month[1]="Luty"
_month[2]="Marzec"
_month[3]="Kwiecień"
_month[4]="Maj"
_month[5]="Czerwiec"
_month[6]="Lipiec"
_month[7]="Sierpień"
_month[8]="Wrzesień"
_month[9]="Październik"
_month[10]="Listopad"
_month[11]="Grudzień"
_day=new Array
_day[0]="Ni"
_day[1]="Pn"
_day[2]="Wt"
_day[3]="Śr"
_day[4]="Cz"
_day[5]="Pt"
_day[6]="So"
_today="Dziś"
_AM="AM"
_PM="PM"
_closeDialog="Zamknij okno"
_lstMoveUpLab="Przenieś w górę"
_lstMoveDownLab="Przenieś w dół"
_lstMoveLeftLab="Przenieś w lewo"
_lstMoveRightLab="Przenieś w prawo"
_lstNewNodeLab="Dodaj filtr zagnieżdżony"
_lstAndLabel="i"
_lstOrLabel="OR"
_lstSelectedLabel="Wybrano"
_lstQuickFilterLab="Dodaj szybki filtr"
_openMenuPart1="Kliknij tutaj, aby uzyskać dostęp do opcji "
_openMenuPart2=" options"
_openCalendarLab="Otwórz kalendarz"
_scroll_first_tab="Przewiń do pierwszej karty"
_scroll_previous_tab="Przewiń do poprzedniej karty"
_scroll_next_tab="Przewiń do następnej karty"
_scroll_last_tab="Przewiń do ostatniej karty"
_expandedLab="Rozwinięty"
_collapsedLab="Zwinięty"
_selectedLab="Wybrano"
_expandNode="Rozwiń węzeł %1"
_collapseNode="Zwiń węzeł %1"
_checkedPromptLab="Ustawiony"
_nocheckedPromptLab="Nieustawiony"
_selectionPromptLab="wartości równe"
_noselectionPromptLab="bez wartości"
_lovTextFieldLab="Tutaj wpisz wartości"
_lovCalendarLab="Tutaj wpisz datę"
_lovPrevChunkLab="Przejdź do poprzedniej porcji danych"
_lovNextChunkLab="Przejdź do następnej porcji danych"
_lovComboChunkLab="Porcja danych"
_lovRefreshLab="Odśwież"
_lovSearchFieldLab="Tutaj wpisz tekst do wyszukania"
_lovSearchLab="Wyszukaj"
_lovNormalLab="Normalna"
_lovMatchCase="Uwzględnij wielkość liter"
_lovRefreshValuesLab="Odśwież wartości"
_calendarNextMonthLab="Przejdź do następnego miesiąca"
_calendarPrevMonthLab="Przejdź do poprzedniego miesiąca"
_calendarNextYearLab="Przejdź do następnego roku"
_calendarPrevYearLab="Przejdź do poprzedniego roku"
_calendarSelectionLab="Wybrany dzień"
_menuCheckLab="Zaznaczone"
_menuDisableLab="Wyłączone"
_RGBTxtBegin= "RGB("
_RGBTxtEnd= ")"
_helpLab="Pomoc"
_waitTitleLab="Czekaj"
_cancelButtonLab="Anuluj"
_modifiers= new Array
_modifiers[0]="Ctrl+"
_modifiers[1]="Shift+"
_modifiers[2]="Alt+"
_bordersMoreColorsLabel="Więcej krawędzi..."
_bordersTooltip=new Array
_bordersTooltip[0]="Bez obramowania"
_bordersTooltip[1]="Lewa krawędź"
_bordersTooltip[2]="Prawa krawędź"
_bordersTooltip[3]="Krawędź dolna"
_bordersTooltip[4]="Średnia dolna krawędź"
_bordersTooltip[5]="Gruba dolna krawędź"
_bordersTooltip[6]="Górna i dolna krawędź"
_bordersTooltip[7]="Górna i średnia dolna krawędź"
_bordersTooltip[8]="Górna i gruba dolna krawędź"
_bordersTooltip[9]="Wszystkie krawędzie"
_bordersTooltip[10]="Wszystkie średnie krawędzie"
_bordersTooltip[11]="Wszystkie grube krawędzie" |
'use strict';
// Posts controller
angular.module('posts').controller('PostsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Posts',
function($scope, $stateParams, $location, Authentication, Posts) {
$scope.authentication = Authentication;
// Create new Post
$scope.create = function() {
// Create new Post object
var post = new Posts({
name: this.name,
body: this.body
});
// Redirect after save
post.$save(function(response) {
$location.path('posts/' + response._id);
// Clear form fields
$scope.name = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Remove existing Post
$scope.remove = function(post) {
if (post) {
post.$remove();
for (var i in $scope.posts) {
if ($scope.posts[i] === post) {
$scope.posts.splice(i, 1);
}
}
} else {
$scope.post.$remove(function() {
$location.path('posts');
});
}
};
// Update existing Post
$scope.update = function() {
var post = $scope.post;
post.$update(function() {
$location.path('posts/' + post._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Create new Comment
$scope.createComment = function() {
var post = $scope.post;
var createdAt = Date.now();
var newComment = {
commenter : this.commentName,
body : this.commentBody,
createdAt: createdAt
};
post.comments.push(newComment);
post.$update(function() {
//redirect
$location.path('posts/' + post._id);
//clear form fields
$scope.commentName = '';
$scope.commentBody = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Posts
$scope.find = function() {
$scope.posts = Posts.query();
};
// Find existing Post
$scope.findOne = function() {
$scope.post = Posts.get({
postId: $stateParams.postId
});
};
}
]); |
"use strict";
var chai = require('chai');
var sinon = require('sinon');
var Person = require("../lib/Person");
var expect = chai.expect;
describe('Person test', function () {
var per;
beforeEach(function () {
per = new Person("Ganesh");
});
afterEach(function () {
per = null;
});
it('Person should be defined', function () {
expect(per).to.be.ok;
});
it('person getName should return string with name', function () {
expect(per.getName()).to.be.a('string');
expect(per.getName()).to.equal('Ganesh');
});
});
describe('Person with callback test ', function () {
var per;
beforeEach(function () {
per = new Person("Ganesh");
});
afterEach(function () {
per = null;
});
it('callback should called', function () {
var callback = sinon.spy();
per.callbackTest(callback);
expect(callback.called).to.be.true;
expect(callback.calledWith(true, "stringParam")).to.be.true;
});
});
//# sourceMappingURL=PersonTest.js.map |
/*jshint node: true, globalstrict: true */
"use strict";
// Imports
// -------------------------------------------------------------------------------------------------
var del = require("del");
var gulp = require("gulp");
var to5 = require("gulp-6to5");
// Configuration
// -------------------------------------------------------------------------------------------------
var settings =
{ scripts:
{ source: "source/{index,array,object}.js"
, target:
{ es5: "."
, es6: "./dist.es6"
, test: "./test.modules"
}
}
};
// Tasks
// =================================================================================================
// `gulp`
// -------------------------------------------------------------------------------------------------
gulp.task("default", ["build"]);
// `gulp build`
// -------------------------------------------------------------------------------------------------
gulp.task("build", ["scripts"]);
// `gulp scripts`
// -------------------------------------------------------------------------------------------------
gulp.task("scripts", ["scripts:es6", "scripts:es5"]);
gulp.task("scripts:es6", function () {
return gulp.src(settings.scripts.source)
.pipe(gulp.dest(settings.scripts.target.es6))
;
});
gulp.task("scripts:es5", function () {
return gulp.src(settings.scripts.source)
.pipe(to5({modules: "umd"}))
.pipe(gulp.dest(settings.scripts.target.es5))
;
});
// `gulp prepare-test`
// -------------------------------------------------------------------------------------------------
gulp.task("prepare-test", function () {
return gulp.src(settings.scripts.source)
.pipe(to5({modules: "common"}))
.pipe(gulp.dest(settings.scripts.target.test))
;
});
// `gulp teardown-test`
// -------------------------------------------------------------------------------------------------
gulp.task("teardown-test", function (done) {
del("test.modules", done);
});
|
import Ember from 'ember';
export default Ember.Mixin.create({
isStart: Ember.computed.equal('model.type', 'start'),
isEnd: Ember.computed.equal('model.type', 'end'),
isCondition: Ember.computed.equal('model.type', 'condition'),
isProcess: Ember.computed.equal('model.type', 'process'),
isStartOrEnd: Ember.computed('model.type', function () {
return this.get('model.type') === 'start' || this.get('model.type') === 'end';
})
});
|
// jQuery
$(document).ready(function() {
// Définition des textareas redimentionnables
$("textarea").addClass("ui-widget-content").resizable( { handles: "s", minHeight: 50 });
// Simulation click sur avis au rechargement
var jqoTmp = $("input[name='Forms_E5_Avis']:checked");
if(jqoTmp.length != 0) jqoTmp.click();
});
// Namespace
var PRESBOU = PRESBOU || {};
PRESBOU.actions = PRESBOU.actions || {};
// Soumission
PRESBOU.actions.submit = function() {
// Anti double clic
if(fmr.document.hasBeenSent) return false;
// Numéro de bordereau
if($("#PRESBOU_SlipNumber").val().trim() == "") { DisplayErrMsgOnField("PRESBOU_SlipNumber", l_Forms_Err_ChampObligatoire + "\"" + l_PRESBOU_SlipNumber + "\" !"); return false; }
// Soumission
fmr.document.submit();
}; |
/*
mustache.js — Logic-less templates in JavaScript
See http://mustache.github.com/ for more info.
*/
var Mustache = module.exports = function () {
var _toString = Object.prototype.toString;
Array.isArray = Array.isArray || function (obj) {
return _toString.call(obj) == "[object Array]";
}
var _trim = String.prototype.trim, trim;
if (_trim) {
trim = function (text) {
return text == null ? "" : _trim.call(text);
}
} else {
var trimLeft, trimRight;
// IE doesn't match non-breaking spaces with \s.
if ((/\S/).test("\xA0")) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
} else {
trimLeft = /^\s+/;
trimRight = /\s+$/;
}
trim = function (text) {
return text == null ? "" :
text.toString().replace(trimLeft, "").replace(trimRight, "");
}
}
var escapeMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": '''
};
function escapeHTML(string) {
return String(string).replace(/&(?!#?\w+;)|[<>"']/g, function (s) {
return escapeMap[s] || s;
});
}
var regexCache = {};
var Renderer = function () {};
Renderer.prototype = {
otag: "{{",
ctag: "}}",
pragmas: {},
buffer: [],
pragmas_implemented: {
"IMPLICIT-ITERATOR": true
},
context: {},
render: function (template, context, partials, in_recursion) {
// reset buffer & set context
if (!in_recursion) {
this.context = context;
this.buffer = []; // TODO: make this non-lazy
}
// fail fast
if (!this.includes("", template)) {
if (in_recursion) {
return template;
} else {
this.send(template);
return;
}
}
// get the pragmas together
template = this.render_pragmas(template);
// render the template
var html = this.render_section(template, context, partials);
// render_section did not find any sections, we still need to render the tags
if (html === false) {
html = this.render_tags(template, context, partials, in_recursion);
}
if (in_recursion) {
return html;
} else {
this.sendLines(html);
}
},
/*
Sends parsed lines
*/
send: function (line) {
if (line !== "") {
this.buffer.push(line);
}
},
sendLines: function (text) {
if (text) {
var lines = text.split("\n");
for (var i = 0; i < lines.length; i++) {
this.send(lines[i]);
}
}
},
/*
Looks for %PRAGMAS
*/
render_pragmas: function (template) {
// no pragmas
if (!this.includes("%", template)) {
return template;
}
var that = this;
var regex = this.getCachedRegex("render_pragmas", function (otag, ctag) {
return new RegExp(otag + "%([\\w-]+) ?([\\w]+=[\\w]+)?" + ctag, "g");
});
return template.replace(regex, function (match, pragma, options) {
if (!that.pragmas_implemented[pragma]) {
throw({message:
"This implementation of mustache doesn't understand the '" +
pragma + "' pragma"});
}
that.pragmas[pragma] = {};
if (options) {
var opts = options.split("=");
that.pragmas[pragma][opts[0]] = opts[1];
}
return "";
// ignore unknown pragmas silently
});
},
/*
Tries to find a partial in the curent scope and render it
*/
render_partial: function (name, context, partials) {
name = trim(name);
if (!partials || partials[name] === undefined) {
throw({message: "unknown_partial '" + name + "'"});
}
if (!context || typeof context[name] != "object") {
return this.render(partials[name], context, partials, true);
}
return this.render(partials[name], context[name], partials, true);
},
/*
Renders inverted (^) and normal (#) sections
*/
render_section: function (template, context, partials) {
if (!this.includes("#", template) && !this.includes("^", template)) {
// did not render anything, there were no sections
return false;
}
var that = this;
var regex = this.getCachedRegex("render_section", function (otag, ctag) {
// This regex matches _the first_ section ({{#foo}}{{/foo}}), and captures the remainder
return new RegExp(
"^([\\s\\S]*?)" + // all the crap at the beginning that is not {{*}} ($1)
otag + // {{
"(\\^|\\#)\\s*(.+?)\\s*" +// #foo (# == $2, foo == $3), not greedy
ctag + // }}
"\n*([\\s\\S]*?)" + // between the tag ($2). leading newlines are dropped
otag + // {{
"\\/\\s*\\3\\s*" + // /foo (backreference to the opening tag).
ctag + // }}
"\\s*([\\s\\S]*)$", // everything else in the string ($4). leading whitespace is dropped.
"g");
});
// for each {{#foo}}{{/foo}} section do...
return template.replace(regex, function (match, before, type, name, content, after) {
// before contains only tags, no sections
var renderedBefore = before ? that.render_tags(before, context, partials, true) : "",
// after may contain both sections and tags, so use full rendering function
renderedAfter = after ? that.render(after, context, partials, true) : "",
// will be computed below
renderedContent,
value = that.find(name, context);
if (type === "^") { // inverted section
if (!value || Array.isArray(value) && value.length === 0) {
// false or empty list, render it
renderedContent = that.render(content, context, partials, true);
} else {
renderedContent = "";
}
} else if (type === "#") { // normal section
if (Array.isArray(value)) { // Enumerable, Let's loop!
renderedContent = that.map(value, function (row) {
return that.render(content, that.create_context(row), partials, true);
}).join("");
} else if (that.is_object(value)) { // Object, Use it as subcontext!
renderedContent = that.render(content, that.create_context(value),
partials, true);
} else if (typeof value == "function") {
// higher order section
renderedContent = value.call(context, content, function (text) {
return that.render(text, context, partials, true);
});
} else if (value) { // boolean section
renderedContent = that.render(content, context, partials, true);
} else {
renderedContent = "";
}
}
return renderedBefore + renderedContent + renderedAfter;
});
},
/*
Replace {{foo}} and friends with values from our view
*/
render_tags: function (template, context, partials, in_recursion) {
// tit for tat
var that = this;
var new_regex = function () {
return that.getCachedRegex("render_tags", function (otag, ctag) {
return new RegExp(otag + "(=|!|>|&|\\{|%)?([^#\\^]+?)\\1?" + ctag + "+", "g");
});
};
var regex = new_regex();
var tag_replace_callback = function (match, operator, name) {
switch(operator) {
case "!": // ignore comments
return "";
case "=": // set new delimiters, rebuild the replace regexp
that.set_delimiters(name);
regex = new_regex();
return "";
case ">": // render partial
return that.render_partial(name, context, partials);
case "{": // the triple mustache is unescaped
case "&": // & operator is an alternative unescape method
return that.find(name, context);
default: // escape the value
return escapeHTML(that.find(name, context));
}
};
var lines = template.split("\n");
for(var i = 0; i < lines.length; i++) {
lines[i] = lines[i].replace(regex, tag_replace_callback, this);
if (!in_recursion) {
this.send(lines[i]);
}
}
if (in_recursion) {
return lines.join("\n");
}
},
set_delimiters: function (delimiters) {
var dels = delimiters.split(" ");
this.otag = this.escape_regex(dels[0]);
this.ctag = this.escape_regex(dels[1]);
},
escape_regex: function (text) {
// thank you Simon Willison
if (!arguments.callee.sRE) {
var specials = [
'/', '.', '*', '+', '?', '|',
'(', ')', '[', ']', '{', '}', '\\'
];
arguments.callee.sRE = new RegExp(
'(\\' + specials.join('|\\') + ')', 'g'
);
}
return text.replace(arguments.callee.sRE, '\\$1');
},
/*
find `name` in current `context`. That is find me a value
from the view object
*/
find: function (name, context) {
name = trim(name);
// Checks whether a value is thruthy or false or 0
function is_kinda_truthy(bool) {
return bool === false || bool === 0 || bool;
}
var value;
// check for dot notation eg. foo.bar
if (name.match(/([a-z_]+)\./ig)) {
var childValue = this.walk_context(name, context);
if (is_kinda_truthy(childValue)) {
value = childValue;
}
} else {
if (is_kinda_truthy(context[name])) {
value = context[name];
} else if (is_kinda_truthy(this.context[name])) {
value = this.context[name];
}
}
if (typeof value == "function") {
return value.apply(context);
}
if (value !== undefined) {
return value;
}
// silently ignore unkown variables
return "";
},
walk_context: function (name, context) {
var path = name.split('.');
// if the var doesn't exist in current context, check the top level context
var value_context = (context[path[0]] != undefined) ? context : this.context;
var value = value_context[path.shift()];
while (value != undefined && path.length > 0) {
value_context = value;
value = value[path.shift()];
}
// if the value is a function, call it, binding the correct context
if (typeof value == "function") {
return value.apply(value_context);
}
return value;
},
// Utility methods
/* includes tag */
includes: function (needle, haystack) {
return haystack.indexOf(this.otag + needle) != -1;
},
// by @langalex, support for arrays of strings
create_context: function (_context) {
if (this.is_object(_context)) {
return _context;
} else {
var iterator = ".";
if (this.pragmas["IMPLICIT-ITERATOR"]) {
iterator = this.pragmas["IMPLICIT-ITERATOR"].iterator;
}
var ctx = {};
ctx[iterator] = _context;
return ctx;
}
},
is_object: function (a) {
return a && typeof a == "object";
},
/*
Why, why, why? Because IE. Cry, cry cry.
*/
map: function (array, fn) {
if (typeof array.map == "function") {
return array.map(fn);
} else {
var r = [];
var l = array.length;
for(var i = 0; i < l; i++) {
r.push(fn(array[i]));
}
return r;
}
},
getCachedRegex: function (name, generator) {
var byOtag = regexCache[this.otag];
if (!byOtag) {
byOtag = regexCache[this.otag] = {};
}
var byCtag = byOtag[this.ctag];
if (!byCtag) {
byCtag = byOtag[this.ctag] = {};
}
var regex = byCtag[name];
if (!regex) {
regex = byCtag[name] = generator(this.otag, this.ctag);
}
return regex;
}
};
return({
name: "mustache.js",
version: "0.4.2",
/*
Turns a template and view into HTML
*/
to_html: function (template, view, partials, send_fun) {
var renderer = new Renderer();
if (send_fun) {
renderer.send = send_fun;
}
renderer.render(template, view || {}, partials);
if (!send_fun) {
return renderer.buffer.join("\n");
}
}
});
}();
|
export { default } from './GitPlainWordmark'
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _defineProperty2 = require('babel-runtime/helpers/defineProperty');
var _defineProperty3 = _interopRequireDefault(_defineProperty2);
exports.getScroll = getScroll;
var _utils = require('./utils');
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _classnames2 = require('classnames');
var _classnames3 = _interopRequireDefault(_classnames2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function getScroll(w, top) {
var ret = w['page' + (top ? 'Y' : 'X') + 'Offset'];
var method = 'scroll' + (top ? 'Top' : 'Left');
if (typeof ret !== 'number') {
var d = w.document;
// ie6,7,8 standard mode
ret = d.documentElement[method];
if (typeof ret !== 'number') {
// quirks mode
ret = d.body[method];
}
}
return ret;
}
function offset(elem) {
var box = void 0;
var x = void 0;
var y = void 0;
var doc = elem.ownerDocument;
var body = doc.body;
var docElem = doc && doc.documentElement;
box = elem.getBoundingClientRect();
x = box.left;
y = box.top;
x -= docElem.clientLeft || body.clientLeft || 0;
y -= docElem.clientTop || body.clientTop || 0;
var w = doc.defaultView || doc.parentWindow;
x += getScroll(w);
y += getScroll(w, true);
return {
left: x, top: y
};
}
function _componentDidUpdate(component, init) {
var refs = component.refs;
var wrapNode = refs.nav || refs.root;
var containerOffset = offset(wrapNode);
var inkBarNode = refs.inkBar;
var activeTab = refs.activeTab;
var inkBarNodeStyle = inkBarNode.style;
var tabBarPosition = component.props.tabBarPosition;
if (init) {
// prevent mount animation
inkBarNodeStyle.display = 'none';
}
if (activeTab) {
var tabNode = activeTab;
var tabOffset = offset(tabNode);
var transformSupported = (0, _utils.isTransformSupported)(inkBarNodeStyle);
if (tabBarPosition === 'top' || tabBarPosition === 'bottom') {
var left = tabOffset.left - containerOffset.left;
// use 3d gpu to optimize render
if (transformSupported) {
(0, _utils.setTransform)(inkBarNodeStyle, 'translate3d(' + left + 'px,0,0)');
inkBarNodeStyle.width = tabNode.offsetWidth + 'px';
inkBarNodeStyle.height = '';
} else {
inkBarNodeStyle.left = left + 'px';
inkBarNodeStyle.top = '';
inkBarNodeStyle.bottom = '';
inkBarNodeStyle.right = wrapNode.offsetWidth - left - tabNode.offsetWidth + 'px';
}
} else {
var top = tabOffset.top - containerOffset.top;
if (transformSupported) {
(0, _utils.setTransform)(inkBarNodeStyle, 'translate3d(0,' + top + 'px,0)');
inkBarNodeStyle.height = tabNode.offsetHeight + 'px';
inkBarNodeStyle.width = '';
} else {
inkBarNodeStyle.left = '';
inkBarNodeStyle.right = '';
inkBarNodeStyle.top = top + 'px';
inkBarNodeStyle.bottom = wrapNode.offsetHeight - top - tabNode.offsetHeight + 'px';
}
}
}
inkBarNodeStyle.display = activeTab ? 'block' : 'none';
}
exports['default'] = {
getDefaultProps: function getDefaultProps() {
return {
inkBarAnimated: true
};
},
componentDidUpdate: function componentDidUpdate() {
_componentDidUpdate(this);
},
componentDidMount: function componentDidMount() {
_componentDidUpdate(this, true);
},
getInkBarNode: function getInkBarNode() {
var _classnames;
var _props = this.props,
prefixCls = _props.prefixCls,
styles = _props.styles,
inkBarAnimated = _props.inkBarAnimated;
var className = prefixCls + '-ink-bar';
var classes = (0, _classnames3['default'])((_classnames = {}, (0, _defineProperty3['default'])(_classnames, className, true), (0, _defineProperty3['default'])(_classnames, inkBarAnimated ? className + '-animated' : className + '-no-animated', true), _classnames));
return _react2['default'].createElement('div', {
style: styles.inkBar,
className: classes,
key: 'inkBar',
ref: 'inkBar'
});
}
}; |
/* global namespace */
(function() {
'use strict';
var ViewModel = namespace('ca.wbac.blog.model.Blog');
var mithrilUtils = namespace('ca.wbac.collectionJson.utils.Mithril');
var selected = -1;
var response = {
collection: {
items: [],
template: {
data: [
{ 'prompt': 'Title', 'name': 'title', 'value': '', 'type': 'text' },
{ 'prompt': 'Content', 'name': 'content', 'value': '', 'type': 'markdown' },
{ 'prompt': 'Tags', 'name': 'tags', 'value': [], 'type': 'array' }
]
}
}
};
ViewModel.posts = response.collection.items;
ViewModel.post = mithrilUtils.getMithrilTemplate(response);
ViewModel.add = function() {
if (selected < 0) {
ViewModel.posts.unshift(mithrilUtils.asPlainObject(ViewModel.post));
} else {
ViewModel.posts[selected] = mithrilUtils.asPlainObject(ViewModel.post);
selected = -1;
}
ViewModel.clear();
};
ViewModel.cancel = function() {
selected = -1;
ViewModel.clear();
};
ViewModel.remove = function(index) {
ViewModel.posts.splice(index, 1);
};
ViewModel.edit = function(index) {
selected = index;
mithrilUtils.setMithrilTemplate(ViewModel.posts[index].data, ViewModel.post);
};
ViewModel.clear = function() {
mithrilUtils.resetMithrilTemplate(response, ViewModel.post);
};
})();
|
// Copyright (c) 2014 Titanium I.T. LLC. All rights reserved. For license, see "README" or "LICENSE" file.
"use strict";
// Release build file. Automates our deployment process.
var git = require("../util/git_runner.js");
var branches = require("../config/branches.js");
var sh = require("../util/sh.js");
//*** RELEASE TASKS
task("default", function() {
console.log("Use 'major', 'minor', or 'patch' to perform release");
});
desc("Increment major version number and release");
task("major", function() {
fail("Major version releases are disabled while we're in 0.x releases.");
});
createReleaseTask("minor");
createReleaseTask("patch");
function createReleaseTask(level) {
desc("Increment " + level + " version number and release");
task(level, [ level + "Release", "npm", "updateDevBranch", "docs", "github" ], function() {
console.log("\n\nRELEASE OK");
}, { async: true });
task(level + "Release", [ "readyToRelease", "integrationBranch" ], function() {
console.log("Updating npm version: ");
sh.run("npm version " + level, complete, fail);
}, { async: true });
}
//*** PUBLISH
desc("Push source code to GitHub");
task("github", function() {
console.log("Publishing to GitHub: ");
sh.run("git push --all && git push --tags", complete, fail);
}, { async: true });
desc("Publish documentation to website");
task("docs", function() {
console.log("Publishing documentation site: ");
sh.run(
"rsync --recursive --keep-dirlinks --perms --times --delete --delete-excluded " +
"--human-readable --progress --exclude=.DS_Store --include=.* " +
"docs/* jdlshore_quixote-css@ssh.phx.nearlyfreespeech.net:/home/public/",
complete, fail
);
}, { async: true });
task("npm", function() {
console.log("Publishing to npm: ");
sh.run("npm publish", complete, fail);
}, { async: true });
//*** MANIPULATE REPO
task("integrationBranch", function() {
console.log("Switching to " + branches.integration + " branch: .");
git.checkoutBranch(branches.integration, complete, fail);
}, { async: true });
task("devBranch", function() {
console.log("Switching to " + branches.dev + " branch: .");
git.checkoutBranch(branches.dev, complete, fail);
}, { async: true });
task("updateDevBranch", [ "devBranch" ], function() {
console.log("Updating " + branches.dev + " with release changes: .");
git.fastForwardBranch(branches.integration, complete, fail);
}, { async: true });
//*** ENSURE RELEASE READINESS
task("readyToRelease", [ "allCommitted", "integrated" ]);
task("allCommitted", function() {
console.log("Checking for uncommitted files: .");
git.checkNothingToCommit(complete, fail);
}, { async: true });
task("integrated", function() {
console.log("Checking if " + branches.dev + " branch is integrated: .");
git.checkFastForwardable(branches.dev, branches.integration, complete, fail);
}, { async: true }); |
'use strict';
var advance = require('../util').advance;
var addPrefix = function (message) {
return 'Inline-block format violation: ' + message;
};
/**
* Error messages.
* @readonly
*/
var messages = {
empty: addPrefix('can\'t be empty.'),
noFirstSpace: addPrefix('no space after "/*".'),
extraFirstSpace: addPrefix('more that a single space after "/*".'),
noLastSpace: addPrefix('no space before "*/".'),
extraLastSpace: addPrefix('more than a single space before "*/".')
};
/**
* Format: inline-block.
*
* @type {FormatParser}
*/
module.exports = function (comment, location, report) {
comment = comment.slice(2, -2);
var position = advance(location.start, {
column: 2
});
if (!comment.length) {
report(messages.empty, position);
}
else {
if (comment[0] != ' ') {
report(messages.noFirstSpace, position);
}
else {
if (comment[1] == ' ') {
report(messages.extraFirstSpace, position);
}
position.column += 1;
comment = comment.slice(1);
}
if (comment.slice(-1) != ' ') {
report(messages.noLastSpace, advance(position, {
column: comment.length
}));
}
else {
if (comment.slice(-2)[0] == ' ') {
report(messages.extraLastSpace, advance(position, {
column: comment.length - comment.match(/\s+$/)[0].length
}));
}
comment = comment.slice(0, -1);
}
}
return {
format: 'inline-block',
lines: [comment],
position: position
};
};
module.exports.messages = messages;
|
import test from 'ava';
import {arrayToObject, cardId} from '../src/utilities';
// Card ID tests
test('card id pilot', async t => {
let response = cardId({
id: 12,
slot: 'pilot'
});
t.is(response, '12p');
});
test('card id condition', async t => {
let response = cardId({
id: 0,
slot: 'condition'
});
t.is(response, '0c');
});
test('card id modification', async t => {
let response = cardId({
id: 256,
slot: 'modification'
});
t.is(response, '256u');
});
test('card id unknown', async t => {
let response = cardId({
id: 10,
slot: 'hat'
});
t.is(response, '10u');
});
test('array to object', async t => {
let baseArr = [
{ id: 'one',text: 'cats' },
{ id: 'two',text: 'in' },
{ id: 'three',text: 'hats' }
];
let response = arrayToObject(baseArr, (element) => element.id);
t.deepEqual(response, {
one: { id: 'one',text: 'cats' },
two: { id: 'two',text: 'in' },
three: { id: 'three',text: 'hats' }
});
});
|
export default function createValidator(rules) {
return (data = {}) => {
const errors = {}
Object.keys(rules).forEach((key) => {
const rule = join([].concat(rules[key])) // concat enables both functions and arrays of functions
const error = rule(data[key], data)
if (error) {
errors[key] = error
}
})
return errors
}
}
const isEmpty = value => value === undefined || value === null || value === ''
const join = (rules) => (value, data) => rules.map(rule => rule(value, data)).filter(error => !!error)[0 /* first error */ ]
export function email(value) {
const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i
if (!isEmpty(value) && !emailRegex.test(value)) {
return 'Invalid email address'
}
}
export function alphaDash(value) {
const regex = /^[a-zA-Z0-9\-_]+$/
if (!isEmpty(value) && !regex.test(value)) {
return 'Must only contain letters, numbers, dashes and underscores.'
}
}
export function required(value) {
if (isEmpty(value)) {
return 'Required'
}
}
export function minLength(min) {
return value => {
if (!isEmpty(value) && value.length < min) {
return `Must be at least ${min} characters`
}
}
}
export function maxLength(max) {
return value => {
if (!isEmpty(value) && value.length > max) {
return `Must be no more than ${max} characters`
}
}
}
export function integer(value) {
if (!Number.isInteger(Number(value))) {
return 'Must be an integer'
}
}
export function oneOf(enumeration) {
return value => {
if (!~enumeration.indexOf(value)) {
return `Must be one of: ${enumeration.join(', ')}`
}
}
}
export function match(field) {
return (value, data) => {
if (data) {
if (value !== data[field]) {
return 'Do not match'
}
}
}
}
|
import Koa from 'koa'
import logger from 'koa-logger'
import session from 'koa-session-minimal'
import redisStore from 'koa-redis'
import Router from 'koa-router'
import bodyParser from 'koa-bodyparser'
import { graphqlKoa, graphiqlKoa } from 'graphql-server-koa'
import schema from './schema'
import formidable from './formidable'
const ONE_MONTH = 30 * 24 * 3600000
const PORT = 3000
const app = new Koa()
const router = new Router()
// ALLOW PROXY REQUESTS
app.proxy = true
app.use(logger())
app.use(session({
key: 'sid',
store: redisStore(),
cookie: {
maxAge: ONE_MONTH,
httpOnly: false,
},
}))
app.use(bodyParser())
router.post('/upload', formidable())
router.post('/graphql', graphqlKoa(ctx => ({
schema,
context: ctx,
})))
router.get('/graphiql', graphiqlKoa({ endpointURL: '/graphql' }))
app.use(router.routes())
app.use(router.allowedMethods())
app.on('error', err =>
process.stderr.write(`server error ${err}\n`),
)
app.listen(PORT)
|
/*global describe, beforeEach, it*/
'use strict';
var assert = require('assert');
describe('astrogenerator generator', function () {
it('can be imported without blowing up', function () {
var app = require('../app');
assert(app !== undefined);
});
});
|
import sinon from "sinon";
import Database from "almaden";
import Model from "../../../";
import databaseConfig from "../databaseConfig.json";
import {User} from "../testClasses.js";
describe(".fetch(callback)", () => {
let user,
userAttributes,
clock;
beforeEach(() => {
clock = sinon.useFakeTimers();
Model.database = new Database(databaseConfig);
Model.database.mock({}); // Catch-all for database
userAttributes = {
id: 1,
name: "Bob Builder",
age: 35,
hasChildren: false,
addressId: undefined,
primaryPhotoId: undefined,
postalCodeId: undefined
};
user = new User(userAttributes);
});
afterEach(() => {
// Remove database from model to prevent
// polluting another file via the prototype
Model.database = undefined;
clock.restore();
});
describe("(Model.database is set)", () => {
beforeEach(() => {
Model.database.mock({
"select * from `users` where `id` = 1 limit 1": [userAttributes]
});
});
describe("(when model has a primary key set)", () => {
beforeEach(() => {
user = new User({
id: 1
});
});
it("should fetch a record from the correct table", done => {
user.fetch(() => {
user.attributes.should.eql(userAttributes);
done();
});
});
it("should fetch a record from the correct table", done => {
user.fetch(() => {
user.attributes.should.eql(userAttributes);
done();
});
});
});
describe("(when model does not have a primary key set)", () => {
beforeEach(() => {
delete user.id;
});
it("should throw an error", () => {
(() => {
user.fetch();
}).should.throw("Cannot fetch this model by the 'id' field because it is not set.");
});
});
describe("(when there is no model with that id)", () => {
beforeEach(() => {
Model.database.mock({
"select * from `users` where `id` = 1 limit 1": []
});
user = new User({
id: 1
});
});
it("should throw an error on the callback", done => {
user.fetch((error) => {
error.should.be.instanceOf(Error);
done();
});
});
});
});
describe("(Model.database not set)", () => {
beforeEach(() => {
Model.database = undefined;
});
it("should throw an error", () => {
(() => {
user.fetch();
}).should.throw("Cannot fetch without Model.database set.");
});
});
describe("(when the type of the strategy is a string)", () => {
describe("(Model.database is set)", () => {
beforeEach(() => {
Model.database.mock({
"select * from `users` where `name` = 'someuser' limit 1": [userAttributes]
});
});
describe("(when model has the specified attribute set)", () => {
beforeEach(() => {
user = new User({
name: "someuser"
});
});
it("should fetch a record from the correct table", done => {
user.fetch("name", () => {
user.attributes.should.eql(userAttributes);
done();
});
});
it("should fetch a record from the correct table", done => {
user.fetch("name", () => {
user.attributes.should.eql(userAttributes);
done();
});
});
});
describe("(when model does not have the specified attribute set)", () => {
beforeEach(() => {
delete user.name;
});
it("should throw an error", () => {
(() => {
user.fetch("name");
}).should.throw("Cannot fetch this model by the 'name' field because it is not set.");
});
});
describe("(when there is no model with the specified attribute)", () => {
beforeEach(() => {
Model.database.mock({
"select * from `users` where `name` = 'someuser' limit 1": []
});
user = new User({
name: "someuser"
});
});
it("should throw an error on the callback", done => {
user.fetch("name", (error) => {
error.should.be.instanceOf(Error);
done();
});
});
});
});
describe("(Model.database not set)", () => {
beforeEach(() => {
Model.database = undefined;
});
it("should throw an error", () => {
(() => {
user.fetch("name");
}).should.throw("Cannot fetch without Model.database set.");
});
});
});
describe("(when the type of the strategy is an array)", () => {
describe("(Model.database is set)", () => {
beforeEach(() => {
Model.database.mock({
"select * from `users` where `name` = 'someuser' and `lastName` = 'someuserLastName' limit 1": [userAttributes]
});
});
describe("(when model has the specified attribute set)", () => {
beforeEach(() => {
user = new User({
name: "someuser",
lastName: "someuserLastName"
});
userAttributes.lastName = "someuserLastName";
});
it("should fetch a record from the correct table", done => {
user.fetch(["name", "lastName"], () => {
user.attributes.should.eql(userAttributes);
done();
});
});
it("should fetch a record from the correct table", done => {
user.fetch(["name", "lastName"], () => {
user.attributes.should.eql(userAttributes);
done();
});
});
});
describe("(when model does not have one of the specified attributes set)", () => {
beforeEach(() => {
delete user.lastName;
});
it("should throw an error", () => {
(() => {
user.fetch(["name", "lastName"]);
}).should.throw("Cannot fetch this model by the 'lastName' field because it is not set.");
});
});
describe("(when there is no model with the specified attribute)", () => {
beforeEach(() => {
Model.database.mock({
"select * from `users` where `name` = 'someuser' and `lastName` = 'someuserLastName' limit 1": []
});
user = new User({
name: "someuser",
lastName: "someuserLastName"
});
});
it("should throw an error on the callback", done => {
user.fetch(["name", "lastName"], (error) => {
error.should.be.instanceOf(Error);
done();
});
});
});
});
describe("(Model.database not set)", () => {
beforeEach(() => {
Model.database = undefined;
});
it("should throw an error", () => {
(() => {
user.fetch("name");
}).should.throw("Cannot fetch without Model.database set.");
});
});
});
});
|
var fileExtensionRE = /\.\w+$/;
var specialCharsRE = /[!@#\$%\^\&\*\)\(\\[\]+=]+/g;
var spaceLikeCharsRE = /[_-]/g;
var whiteSpaceRE = /[\s\.]+/g;
var seasonEpisodeRE = /s(\d+)(\s+)?e(\d+)/gi;
var leadingZeroesRE = /0+(\d+)/g;
module.exports = function simplifyFileName(fileName){
return fileName.replace(fileExtensionRE, '').replace(specialCharsRE, '').replace(spaceLikeCharsRE, ' ')
.replace(whiteSpaceRE, ' ').replace(seasonEpisodeRE, '$1 $3').replace(leadingZeroesRE, '$1')
.trim().toLowerCase();
};
|
'use strict';
class CorsMiddleware extends Skyer.AppMiddleware {
constructor( options ) {
super(options);
this.order = 70;
}
__default() {
const cors = require('kcors');
return cors();
}
}
module.exports = CorsMiddleware;
|
import React, { Component } from 'react';
import { changeTraining, getData} from '../reducers/'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import axios from 'axios';
let trainings;
class Capitol extends Component {
constructor(props){
super(props);
this.state={
training: "State Capitol Senate Conference Room 016",
capitol: false,
inputList: ''
};
this.handleSelection = this.handleSelection.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.fetchTrain = this.fetchTrain.bind(this);
this.handleTimes = this.handleTimes.bind(this);
}
handleSelection(e){
this.props.changeTraining(document.getElementById('capitol-training').value);
}
handleTimes(e){
e.preventDefault();
this.setState({time: e.target.value});
console.log('target', e.target.value);
this.props.changeTraining(e.target.value);
}
handleSubmit(e){
e.preventDefault();
this.props.changeTraining(document.getElementById('capitol-training').value);
// this.props.changeDistrict(this.state.district);
let sites;
let siteArr = [];
for (var i = 1; i < trainings.length; i++){
if (trainings[i].site === "State Capitol Auditorium"){
let newArr = [];
newArr.push(trainings[i]);
for (var keyVal in newArr){
var newVal = newArr[keyVal];
sites = [newVal.day + ' ', newVal.date + ' ', newVal.site + ' ', newVal.address + ' ', newVal.city + ' ', newVal.zip + ' ', newVal.time];
siteArr.push(sites);
}
}
}
for (var j = 0; j < siteArr.length; j++){
var radioInputArr = [];
var breakPoint = <br/>;
let valuesArr = [siteArr[j][0] + siteArr[j][1] + siteArr[j][3] + siteArr[j][4] + siteArr[j][5] + siteArr[j][6]];
var radioInput = <div className="cap-radio">
<label>
<input type="radio" id={`capitol${j}`} key={j} name={`capitol${j}`}
value={valuesArr}
checked={this.state.time===siteArr[j][6]}
onChange={this.handleTimes}
/>
{siteArr[j][6]}
</label>
</div>;
radioInputArr.push(radioInput);
siteArr[j].splice(6);
siteArr[j].splice(6, 0, radioInputArr);
siteArr[j].push(breakPoint);
}
this.state.trainings = siteArr.sort(function(a, b){
if (a[1] > b[1]){
return 1;
}
if (a[1] < b[1]){
return -1;
}
return 0;
});
const inputList = this.state.trainings;
this.setState({
inputList: this.state.trainings
});
}
fetchTrain(data){
axios({
method: 'GET',
url: "http://localhost:3001/training/",
responseType: 'json'
})
.then(function(response){
trainings = response.data;
});
}
componentDidMount() {
this.fetchTrain();
}
render(){
return(
<form onSubmit={this.handleSubmit}>
<label>
Training Location:
<select value={this.state.training} onChange={this.handleSelection}>
<option id="capitol-training" defaultValue="State Capitol Senate Conference Room 016"
checked={this.state.training === "State Capitol Senate Conference Room 016"}
>State Capitol Senate Conference Room 016</option>
</select>
</label>
<button type="submit" onClick={this.handleSubmit}>View Schedule</button>
<div>{this.state.inputList}</div>
</form>
);
}
}
const mapStateToProps = (state) => {
return {
...state
};
}
const mapDispatchToProps = dispatch => bindActionCreators({
changeTraining,
getData,
}, dispatch)
export default connect(mapStateToProps, mapDispatchToProps)(Capitol); |
import PropTypes from 'prop-types';
import React from 'react';
import injectT from '../../i18n/injectT';
function AccessibilityShortcuts({ t, mainContentId }) {
const mainContentHref = `#${mainContentId}`;
return (
<div className="app-AccessibilityShortcuts">
<a
className="sr-only app-AccessibilityShortcuts__skip-link"
href={mainContentHref}
>
{t('AccessibilityShortcuts.skipToContent')}
</a>
</div>
);
}
AccessibilityShortcuts.propTypes = {
t: PropTypes.func.isRequired,
mainContentId: PropTypes.string.isRequired,
};
export default injectT(AccessibilityShortcuts);
|
'use strict'
var request = require('request')
var cheerio = require('cheerio')
var moment = require('moment')
var async = require('async')
var tracker = require('../')
var trackingInfo = function (number) {
return {
method: 'POST',
url: 'http://www.rincos.co.kr/tracking/tracking_web.asp',
data: {
invoice: number
}
}
}
var parser = {
trace: function (body, cb) {
var $ = cheerio.load(body)
var courier = {
code: tracker.COURIER.RINCOS.CODE,
name: tracker.COURIER.RINCOS.NAME
}
var result = {
courier: courier,
number: '',
status: tracker.STATUS.PENDING
}
var checkpoints = []
var $area = $('div.border > table > tr').eq(1)
var $infoTable = $area.find('> td > table')
var $summary = $infoTable.eq(0).find('tr').eq(1).find('> td')
var $checkpoints = $infoTable.eq(1).find('> tr')
result.number = $summary.eq(2).text().trim()
if (!result.number) {
return cb(tracker.error(tracker.ERROR.INVALID_NUMBER))
}
$checkpoints.each(function (idx) {
if (idx < 3 || $(this).find('> td').length === 1) {
return true
}
var $cols = $(this).find('> td')
var checkpoint = {
courier: courier,
location: $cols.eq(4).text().trim(),
message: $cols.eq(6).text().trim(),
status: tracker.STATUS.IN_TRANSIT,
time: moment([$cols.eq(0).text().trim(), $cols.eq(2).text().trim()].join(' '), 'YYYY.MM.DD HH:mm').format('YYYY-MM-DDTHH:mm')
}
if (/Picked Up/i.test(checkpoint.message) === true) {
checkpoint.status = tracker.STATUS.INFO_RECEIVED
} else if (/SUCCEED RECEIVED BY|Delivered|RELEASED TO REPRESENTATIVE|FINAL DELIVERY|DELIVERD/i.test(checkpoint.message) === true) {
checkpoint.status = tracker.STATUS.DELIVERED
}
checkpoints.push(checkpoint)
})
result.checkpoints = checkpoints.reverse()
result.status = tracker.normalizeStatus(result.checkpoints)
cb(null, result)
}
}
module.exports = function (opts) {
return {
trackingInfo: trackingInfo,
trace: function (number, cb) {
var tracking = trackingInfo(number)
async.waterfall([
function (cb) {
request.post({
url: tracking.url,
form: tracking.data
}, function (err, res, body) {
cb(err, body)
})
},
function (body, cb) {
try {
parser.trace(body, cb)
} catch (e) {
cb(tracker.error(e.message))
}
}
], cb)
}
}
}
|
sap.ui.define([
"flp/no/unit/model/models",
"sap/ui/thirdparty/sinon",
"sap/ui/thirdparty/sinon-qunit"
], function (models) {
"use strict";
QUnit.module("createDeviceModel", {
afterEach : function () {
this.oDeviceModel.destroy();
}
});
function isPhoneTestCase(assert, bIsPhone) {
// Arrange
this.stub(sap.ui.Device, "system", { phone : bIsPhone });
// System under test
this.oDeviceModel = models.createDeviceModel();
// Assert
assert.strictEqual(this.oDeviceModel.getData().system.phone, bIsPhone, "IsPhone property is correct");
}
QUnit.test("Should initialize a device model for desktop", function (assert) {
isPhoneTestCase.call(this, assert, false);
});
QUnit.test("Should initialize a device model for phone", function (assert) {
isPhoneTestCase.call(this, assert, true);
});
function isTouchTestCase(assert, bIsTouch) {
// Arrange
this.stub(sap.ui.Device, "support", { touch : bIsTouch });
// System under test
this.oDeviceModel = models.createDeviceModel();
// Assert
assert.strictEqual(this.oDeviceModel.getData().support.touch, bIsTouch, "IsTouch property is correct");
}
QUnit.test("Should initialize a device model for non touch devices", function (assert) {
isTouchTestCase.call(this, assert, false);
});
QUnit.test("Should initialize a device model for touch devices", function (assert) {
isTouchTestCase.call(this, assert, true);
});
QUnit.test("The binding mode of the device model should be one way", function (assert) {
// System under test
this.oDeviceModel = models.createDeviceModel();
// Assert
assert.strictEqual(this.oDeviceModel.getDefaultBindingMode(), "OneWay", "Binding mode is correct");
});
}
);
|
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import { useLayoutEffect } from 'react';
import { useCollector } from './useCollector';
export function useMonitorOutput(monitor, collect, onCollect) {
var _useCollector = useCollector(monitor, collect, onCollect),
_useCollector2 = _slicedToArray(_useCollector, 2),
collected = _useCollector2[0],
updateCollected = _useCollector2[1];
useLayoutEffect(function subscribeToMonitorStateChange() {
var handlerId = monitor.getHandlerId();
if (handlerId == null) {
return undefined;
}
return monitor.subscribeToStateChange(updateCollected, {
handlerIds: [handlerId]
});
}, [monitor, updateCollected]);
return collected;
} |
version https://git-lfs.github.com/spec/v1
oid sha256:380dcffd8a7564b74871bebe87bbc24f985be39513d4970874ede3401bd70e1d
size 57476
|
// ==UserScript==
// @name Spacom.Addons.Fleets.Sort
// @version 0.1.4
// @namespace http://dimio.org/
// @description Add a sorting and filters for fleets tabs
// @author dimio (dimio@dimio.org)
// @license MIT
// @homepage https://github.com/dimio/userscripts-spacom.ru-addons
// @supportURL https://github.com/dimio/userscripts-spacom.ru-addons/issues
// @supportURL https://spacom.ru/forum/discussion/47/polzovatelskie-skripty
// @encoding utf-8
// @match http*://spacom.ru/?act=game/map*
// @include http*://spacom.ru/?act=game/map*
// @run-at document-end
// ==/UserScript==
console.log(GM_info.script.name, 'booted v.', GM_info.script.version);
const homePage = GM_info.scriptMetaStr.split('\n')[6].split(' ')[6];
const ERR_MSG = {
NO_LIB: `Для работы ${GM_info.script.name} необходимо установить и включить последние версии следующих дополнений:
<ul>
<li>Spacom.Addons</li>
<li>Spacom.Addons.Fleets.Common</li>
</ul>
<a href="${homePage}">${homePage}</a>`,
NO_FILTER_PARAMS: `Не найдены параметры для фильтрации.
Для сброса фильтров закройте и откройте заново текущую вкладку флотов.`,
NO_FILTER_SELECTED: `Условия фильтрации не указаны.`,
};
(function (window) {
'use strict';
window.unsafeWindow = window.unsafeWindow || window;
const w = unsafeWindow;
const Addons = w.Addons;
if (w.self !== w.top) {
return;
}
if (!Addons) {
// if (!Addons || !Addons.Fleets.Common) {
w.showSmallMessage(ERR_MSG.NO_LIB);
return;
}
function Filter(by, isExclude = false) {
this.by = by;
this.isExclude = isExclude;
}
Addons.Fleets.Sort = {
/**
* contains current fleets by fleet tab
* note: use Proxy or Object.observe for watch to map.fleets changes
* and cache filtered fleets for each tab?
*/
fleets: [],
filters: {},
sort: {},
garrisonIco: (Addons.Fleets.Common) ? Addons.Fleets.Common.garrisonIco : "5.png",
toggleSubMenu(owner, fleetType, redraw) {
const subMenu = `fleets_${owner}_${fleetType}`;
// Current Fleets tab was closed, purge filters & drop filtered fleets for current tab
if (w.sub_menu === subMenu && !redraw) {
this.clearFilters(subMenu);
return false;
}
return subMenu;
},
createDefaultFilters(owner, fleetType) {
if (!Addons.Common.isVariableDefined(this.filters[w.sub_menu])) {
this.filters[w.sub_menu] = [
new Filter({'type': [fleetType], 'owner': [owner]}),
new Filter({'weight': ["0"]}, true)
];
}
if (!Addons.Common.isVariableDefined(this.sort[w.sub_menu])) {
this.sort[w.sub_menu] = {};
}
},
clearFilters(subMenu) {
delete this.filters[subMenu];
delete this.sort[subMenu];
},
showFleets(opt) {
const owner = opt.owner;
const fleetType = opt.fleetType || 'fleet';
const sortBy = opt.sortBy || 'weight';
let redraw = opt.redraw || false; //true for sort & filter buttons
w.map.clearInfo();
if ((w.sub_menu = this.toggleSubMenu(owner, fleetType, redraw)) === false) {
return false;
}
this.createDefaultFilters(owner, fleetType);
this.fleets = w.map.fleets.slice();
this.fleets.forEach(fleet => {
fleet['type'] = this.getFleetType(fleet);
// hack for sorting by ship type (== ship icon) for garrisons
fleet.ico = this.setDummyGarrisonIco(fleet);
});
// apply filters for current fleets tab
this.filters[w.sub_menu].forEach(filter => {
this.fleets = this.filterBy(this.fleets, filter);
});
// apply sorting for current fleets tab
this.sortFleets(owner, sortBy, redraw);
// show fleets for current fleets tab
this.drawFleetsTab(this.fleets);
// add sorting & filtering buttons to current fleets tab
this.addButtons(owner, fleetType);
// add mark/unmark buttons
if (Addons.Fleets.MarkOnMap) {
Addons.Fleets.MarkOnMap.init();
}
// add summary button
if (Addons.Fleets.Summary) {
Addons.Fleets.Summary.init();
}
return true;
},
showFilteredFleets(owner, fleetType, filterBy) {
const filterParams = this.getFilterParams(filterBy);
if (Addons.Common.isObjNotEmpty(filterParams)) {
this.getFilter(filterParams, filterBy)
.then(
filter => {
this.filters[w.sub_menu].push(filter);
this.showFleets({
'owner': owner,
'fleetType': fleetType,
'redraw': true,
})
},
error => w.showSmallMessage(ERR_MSG.NO_FILTER_SELECTED)
);
}
else {
w.showSmallMessage(ERR_MSG.NO_FILTER_PARAMS);
}
},
getFilterParams(filterBy) {
let filterParams = {};
this.fleets.forEach(fleet => {
filterParams[this.getFilterParam(filterBy, fleet)] = fleet[filterBy];
});
filterParams = Object.fromEntries(
Object.entries(filterParams).sort((a, b) => {
return Addons.Sort.alphabetically(a[0], b[0])
})
);
return filterParams;
},
getFilterParam(filterBy, fleet) {
if (filterBy === 'star_id') {
const star = w.map.stars[fleet[filterBy]];
return star.name + ' ' + star.x + ':' + star.y;
}
return fleet[filterBy];
},
getFilter(params, filterBy) {
const isExcludeId = 'filtering-list-exclude';
const filter = new Filter({[filterBy]: []});
let message = `Отфильтровать по:</br>
<select id='fl_filter' size='
${Object.keys(params).length < 8 ? Object.keys(params).length + 1 : 8}'
multiple='multiple'>`;
for (const i in params) {
if (params.hasOwnProperty(i)) {
message += `<option value="${params[i]}">${i}</option>`;
}
}
message += '</select></br>';
message += `<input type="checkbox" id="${isExcludeId}"/>`;
message += `<label for="${isExcludeId}">Исключить выбранное</label>`;
w.showSmallMessage(message);
$(`#${isExcludeId}`).change(function () {
filter.isExclude = $(this).is(':checked');
});
$('#fl_filter').change(function () {
filter.by[filterBy] = $(this).val();
});
return new Promise(function (resolve, reject) {
$('#data_modal > button').removeAttr("onclick")
.click(function () {
$('#fl_filter').change();
$.modal.close();
Addons.Common.isVariableDefined(filter.by[filterBy])
? resolve(filter) : reject();
});
});
},
sortFleets(owner, sortBy, redraw) {
if (Addons.Common.isVariableDefined(this.sort[w.sub_menu]["last"])
&& (!redraw || sortBy === 'weight')) {
this.sortBy(this.fleets, this.sort[w.sub_menu]["last"], owner);
}
else {
this.sortBy(this.fleets, sortBy, owner);
if (sortBy === this.sort[w.sub_menu]["last"]) {
this.sort[w.sub_menu]["isReverse"] = !this.sort[w.sub_menu]["isReverse"];
}
this.sort[w.sub_menu]["last"] = (sortBy === 'weight') ? undefined : sortBy;
}
if (this.sort[w.sub_menu]["isReverse"]) {
this.fleets.reverse();
}
},
getFleetType(fleet) {
/** non-own garrisons have a `fleet.garrison: "0"`
* own garrisons have a `fleet.garrison: "1"`
* all garrisons name is `fleet.fleet_name: "Гарнизон"`
* and ico is `fleet.ico: null`
*/
return (+fleet.garrison === 0) ? 'fleet' : 'garrison';
},
setDummyGarrisonIco(fleet) {
// hack for sorting by ship type (== ship icon)
return (fleet.ico !== null) ? fleet.ico : this.garrisonIco;
},
filterBy(fleets, filter) {
if (Addons.Common.isObjNotEmpty(fleets)) {
const keys = Object.keys(filter.by);
const values = Object.values(filter.by);
return fleets.filter(fleet => {
// it's a dark magic :)
return keys.every((key, index) => {
return filter.isExclude ?
values[index].every((value) => {
return fleet[key] !== value
})
:
values[index].some((value) => {
return fleet[key] === value
})
})
// && +fleet.weight !== 0;
});
}
return [];
},
sortBy(fleets, sortBy, owner) {
switch (sortBy) {
case 'weight':
fleets.sort(w.fleetOrder);
break;
case 'fleet_speed':
fleets.sort(this.sorter.speed);
fleets.map((fleet) => {
fleet.fleet_speed = parseFloat(fleet.fleet_speed).toFixed(2);
return fleet;
});
break;
case 'turn': // by fleet state
if (owner !== 'own') {
fleets.sort(this.sorter.state.other);
}
else {
fleets.sort(this.sorter.own).reverse();
}
break;
case 'ico': // by fleet type
fleets.sort(this.sorter.type);
break;
case 'fleet_name': // by owner & fleet names
if (owner === 'own') {
fleets.sort(this.sorter.fleetName);
break;
}
fleets.sort(this.sorter.fleetName);
fleets.sort(this.sorter.playerName);
break;
case 'stat':
fleets.sort(this.sorter.combatPower.hp);
// fleets.sort(this.sorter.combatPower.health);
fleets.reverse();
break;
case 'player_id':
if (owner !== 'other') {
break;
}
fleets.sort(this.sorter.playerId);
break;
default:
fleets.sort(w.fleetOrder);
break;
}
// sort in-place
// return fleets;
},
drawFleetsTab(fleets) {
if (fleets && Addons.Common.isObjNotEmpty(fleets)) {
$('#items_list').append(w.tmpl('fleets_title', fleets));
for (const fleet of fleets) {
if (Addons.Common.isVariableDefined(fleet)) {
w.map.showBlockFleet(fleet, fleet.owner);
}
}
$('#items_list>>>[title],#items_list>>>>[title]').qtip({
position: {
my: 'bottom center', // at the bottom right of...
at: 'top center', // Position my top left...
},
style: {
classes: 'qtip-dark tips',
},
});
}
else {
$('#items_list').html(
'<div class="player_fleet_title">Нет подходящих флотов</div>');
}
},
getNaviDivs() {
const divs = {};
divs.fleet_speed = $('#items_list .fleet_speed')[0];
divs.fleet_name = $('#items_list .fleet_name')[0];
divs.turn = $('#items_list .fleet_state')[0];
divs.ico = $('#items_list .fleet_ico_list')[0];
divs.stat = $('#items_list .fleet_stat')[0];
return divs;
},
addButtons(owner, fleetType) {
const timerID = setInterval(() => {
const divs = this.getNaviDivs();
if (Addons.Common.isObjNotEmpty(divs)) {
clearInterval(timerID);
this.addSortButtons(divs, owner, fleetType);
this.addFilterButtons(divs, owner, fleetType);
}
}, 0);
},
addSortButtons(divs, owner, fleetType) {
// div match a sortBy
for (let div in divs) {
if (divs.hasOwnProperty(div) && Addons.Common.isVariableDefined(divs[div])) {
if (fleetType === "garrison") {
if (div !== "ico" && div !== "stat") {
continue;
}
}
Addons.DOM.makeClickable({
elem: divs[div],
icon: 'fa-sort',
css_name: `sort-by-${div}`,
title: 'Отсортировать',
cb: `Addons.Fleets.Sort.showFleets({owner:'${owner}',fleetType:'${fleetType}',sortBy:'${div}',redraw:true})`
});
}
}
},
addFilterButtons(divs, owner, fleetType) {
// div match a filterBy
for (let div in divs) {
if (divs.hasOwnProperty(div) && Addons.Common.isVariableDefined(divs[div])) {
if (div === 'fleet_speed' || div === 'stat') {
continue;
}
if (fleetType === 'garrison' &&
(div === 'turn' || div === 'fleet_name')) {
continue;
}
if ((owner === 'other' || owner === 'peace') &&
div === 'fleet_name') {
// add the additional button before current
Addons.DOM.appendClickableIcon({
elem: divs[div],
icon: 'fa-id-badge',
css_name: `filter-by-${div}`,
title: 'Отфильтровать по владельцу',
cb: `Addons.Fleets.Sort.showFilteredFleets('${owner}','${fleetType}','player_name')`
});
}
if (div === 'turn') {
// add the additional button before current
Addons.DOM.appendClickableIcon({
elem: divs[div],
icon: 'fa-crosshairs',
css_name: `filter-by-star_id`,
title: 'Отфильтровать по системе',
cb: `Addons.Fleets.Sort.showFilteredFleets('${owner}','${fleetType}','star_id')`
});
}
Addons.DOM.appendClickableIcon({
elem: divs[div],
icon: 'fa-filter',
css_name: `filter-by-${div}`,
title: 'Отфильтровать',
cb: `Addons.Fleets.Sort.showFilteredFleets('${owner}','${fleetType}','${div}')`
});
}
}
},
init() {
$('#navi > div:nth-child(2)').attr('onclick',
'Addons.Fleets.Sort.showFleets({owner:\'own\'});return false;');
$('#navi > div:nth-child(3)').attr('onclick',
'Addons.Fleets.Sort.showFleets({owner:\'other\'});return false;');
Addons.DOM.createNaviBarButton('Гарнизон', 1,
'Addons.Fleets.Sort.showFleets({owner:\'own\',fleetType: \'garrison\'});return false;');
Addons.DOM.createNaviBarButton('Союзные', 3,
'Addons.Fleets.Sort.showFleets({owner:\'peace\'});return false;');
Addons.DOM.createNaviBarButton('Пираты', 5,
'Addons.Fleets.Sort.showFleets({owner:\'pirate\'});return false;');
},
sorter: {
state: {
own(a, b) {
if (a.allow_explore > b.allow_explore) {
return 1;
}
else if (a.allow_explore < b.allow_explore) {
return -1;
}
if (a.allow_fly > b.allow_fly) {
return 1;
}
else if (a.allow_fly < b.allow_fly) {
return -1;
}
if (a.allow_transfer > b.allow_transfer) {
return 1;
}
else if (a.allow_transfer < b.allow_transfer) {
return -1;
}
if (a.allow_garrison > b.allow_garrison) {
return 1;
}
else if (a.allow_garrison < b.allow_garrison) {
return -1;
}
if (a.allow_station > b.allow_station) {
return -1; // изучает аномалию - опускаем ниже
}
else if (a.allow_station < b.allow_station) {
return 1; // готов изучить или не станция - поднять
}
if (a.start_turn > b.start_turn) {
return -1; // будет дольше в полёте - опустить
}
else if (a.start_turn < b.start_turn) {
return 1;
}
return 0;
},
other(a, b) {
return Addons.Sort.numerically(a.turn, b.turn);
},
},
combatPower: {
health(a, b) {
return Addons.Sort.numerically(a.health, b.health);
},
hp(a, b) {
return Addons.Sort.numerically(
a.hp + a.laser_hp,
b.hp + b.laser_hp
);
},
},
speed(a, b) {
// order desc
return -Addons.Sort.numerically(a.fleet_speed, b.fleet_speed);
},
type(a, b) {
return Addons.Sort.alphabetically(a.ico, b.ico);
},
fleetName(a, b) {
return Addons.Sort.alphabetically(a.fleet_name, b.fleet_name);
},
playerName(a, b) {
return Addons.Sort.alphabetically(a.player_name, b.player_name);
},
playerId(a, b) {
// order asc
return Addons.Sort.numerically(a.player_id, b.player_id);
},
},
};
Addons.Fleets.Sort.init(this);
})(window);
|
"use strict";
module.exports = {
"rules": {
// Enforces getter/setter pairs in objects
"accessor-pairs": 0,
// treat var statements as if they were block scoped
"block-scoped-var": 0,
// specify the maximum cyclomatic complexity allowed in a program
"complexity": [0, 11],
// require return statements to either always or never specify values
"consistent-return": 0,
// specify curly brace conventions for all control statements
"curly": [0, "all"],
// require default case in switch statements
"default-case": 0,
// encourages use of dot notation whenever possible
"dot-notation": [0, { "allowKeywords": true }],
// enforces consistent newlines before or after dots
"dot-location": 0,
// require the use of === and !==
"eqeqeq": 0,
// make sure for-in loops have an if statement
"guard-for-in": 0,
// disallow the use of alert, confirm, and prompt
"no-alert": 0,
// disallow use of arguments.caller or arguments.callee
"no-caller": 0,
// disallow division operators explicitly at beginning of regular expression
"no-div-regex": 0,
// disallow else after a return in an if
"no-else-return": 0,
// disallow use of labels for anything other then loops and switches
"no-empty-label": 0,
// disallow comparisons to null without a type-checking operator
"no-eq-null": 0,
// disallow use of eval()
"no-eval": 0,
// disallow adding to native types
"no-extend-native": 0,
// disallow unnecessary function binding
"no-extra-bind": 0,
// disallow fallthrough of case statements
"no-fallthrough": 2,
// disallow the use of leading or trailing decimal points in numeric literals
"no-floating-decimal": 0,
// disallow the type conversions with shorter notations
"no-implicit-coercion": 0,
// disallow use of eval()-like methods
"no-implied-eval": 0,
// disallow this keywords outside of classes or class-like objects
"no-invalid-this": 0,
// disallow usage of __iterator__ property
"no-iterator": 0,
// disallow use of labeled statements
"no-labels": 0,
// disallow unnecessary nested blocks
"no-lone-blocks": 0,
// disallow creation of functions within loops
"no-loop-func": 0,
// disallow use of multiple spaces
"no-multi-spaces": 0,
// disallow use of multiline strings
"no-multi-str": 0,
// disallow reassignments of native objects
"no-native-reassign": 0,
// disallow use of new operator when not part of the assignment or comparison
"no-new": 0,
// disallow use of new operator for Function object
"no-new-func": 0,
// disallows creating new instances of String,Number, and Boolean
"no-new-wrappers": 0,
// disallow use of (old style) octal literals
"no-octal": 2,
// disallow use of octal escape sequences in string literals, such as
// var foo = "Copyright \251";
"no-octal-escape": 0,
// disallow reassignment of function parameters
"no-param-reassign": 0,
// disallow use of process.env
"no-process-env": 0,
// disallow usage of __proto__ property
"no-proto": 0,
// disallow declaring the same variable more then once
"no-redeclare": 2,
// disallow use of assignment in return statement
"no-return-assign": 0,
// disallow use of `javascript:` urls.
"no-script-url": 0,
// disallow comparisons where both sides are exactly the same
"no-self-compare": 0,
// disallow use of comma operator
"no-sequences": 0,
// restrict what can be thrown as an exception
"no-throw-literal": 0,
// disallow usage of expressions in statement position
"no-unused-expressions": 0,
// disallow unnecessary .call() and .apply()
"no-useless-call": 0,
// disallow use of void operator
"no-void": 0,
// disallow usage of configurable warning terms in comments: e.g. todo
"no-warning-comments": [0, { "terms": ["todo", "fixme", "xxx"], "location": "start" }],
// disallow use of the with statement
"no-with": 0,
// require use of the second argument for parseInt()
"radix": 0,
// requires to declare all vars on top of their containing scope
"vars-on-top": 0,
// require immediate function invocation to be wrapped in parentheses
"wrap-iife": 0,
// require or disallow Yoda conditions
"yoda": [0, "never"]
}
};
|
const personalData = require('../personalData');
const webModel = require('../webModel');
const webModelFunctions = require('../webModelFunctions');
const robotModel = require('../robotModel');
const masterRelay = require('../MasterRelay');
const wait = require('../wait');
async function handleUsbHubPower() {
if (webModel.debugging && webModel.logBehaviorMessages) {
const message = ' - Checking: Handle Power without ROS';
console.log(message);
webModelFunctions.scrollingStatusUpdate(message);
}
// Power off the Master Relay and all regular Relays after the idle timeout,
// whether plugged in or not.
// NOTE: My last try at running this "continuously" it drained the 12v batteries,
// even when plugged in. Maybe my batteries are old, but it seems best to NOT do that.
// Hence, idle power off, even when plugged in.
// NOTE2: The idle timeout for while ROS is running is handled in polling right now.
/** @namespace personalData.idleTimeoutInMinutes */
if (
!webModel.ROSisRunning &&
webModel.idleTimeout &&
personalData.idleTimeoutInMinutes > 0 &&
webModel.masterRelayOn
) {
// NOTE: If you turn on debugging, this will update every behavior loop (1 second)
const dateNow = new Date();
const lastActionDate = new Date(webModel.lastUpdateTime);
const idleMinutes = (dateNow - lastActionDate) / 1000 / 60;
if (webModel.debugging && webModel.logOtherMessages) {
console.log(
`Idle Check: ${dateNow} - ${lastActionDate} = ${idleMinutes}`,
);
}
if (idleMinutes > personalData.idleTimeoutInMinutes) {
console.log('Idle power down.');
webModelFunctions.scrollingStatusUpdate('Idle power down.');
if (personalData.useMasterPowerRelay) {
await wait(1); // The usbRelay calls just made by polling can clobber this if we don't wait.
masterRelay('off');
}
/** @namespace personalData.useUSBrelay */
if (personalData.useUSBrelay) {
await wait(1); // The usbRelay calls just made by polling can clobber this if we don't wait.
robotModel.usbRelay.switchRelay('all', 'off');
}
// In theory this is 100% done,
// but since we did act, make the loop start over
return false;
}
}
// This behavior is idle, allow behave loop to continue to next entry.
return true;
}
module.exports = handleUsbHubPower;
|
var x;
x = $(document);
x.ready(proyecto);
function proyecto(){
$( "input" ).on( "click", function() {
var anho = $("#anhopro option:selected");
var opciones = $("input:checked").val();
if(anho.val() != ''){
var v3;
v3 = anho.val();
alert(v3);
var postForm ={'v3' : v3};
alert(opciones);
if (opciones == "p1") {
$("#mejorv3").DataTable({
"ajax":{
"method":"POST",
"url":"cmosproyect/p1"
},
"columns":[
{ }
]
});
}
}
});
}
|
Template.RecipeSingle.onCreated(function(){
var self = this;
self.autorun(function() {
var id = FlowRouter.getParam('id');
self.subscribe('SingleRecipe', id);
});
});
Template.RecipeSingle.helpers({
recipe: ()=> {
var id = FlowRouter.getParam('id');
return Recipes.findOne({_id: id});
}
}); |
'use strict';
export default class BoardCtrl {
constructor($location, metaDataService, menuService, boardService) {
this.title = 'BoardOfShame Список мошенников';
metaDataService.setPageTitle(this.title);
menuService.setActiveItem('/');
this.$location = $location;
this.boardService = boardService;
this.scammers = [];
this.loading = false;
this.activate();
}
activate() {
this.search = this.getSearchQuery();
this.loading = true;
return this.boardService.getAllScammers()
.then((res) => {
this.scammers = res.data;
return this.scammers;
})
.catch((err) => {
console.error(err.statusText);
return false;
})
.finally(() => {
this.loading = false;
});
}
changeQuery() {
this.$location.search('search', this.search);
}
getSearchQuery() {
let query = this.$location.search();
console.log(query);
if (query.hasOwnProperty('search') && query.search !== true) {
return query.search;
}
return '';
}
}
BoardCtrl.$inject = ['$location', 'metaDataService', 'menuService', 'boardService']; |
'use strict';
module.exports.tester = require('./tester.js')
module.exports.cli = require('./cli.js');
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
// = require jquery2
// = require bootstrap
// = require angular
// = require angular-ui-router
// = require angular-resource
// require_tree .
// = require spa/app.module
// = require spa/app.constant
// = require spa/app.router
// = require spa/states/states.module
// = require spa/states/states.service
// = require spa/states/states.controller
// = require spa/states/states.directive
|
var yield = function yield(){}; |
(function () {
$("#ProdutoId").change(
function () {
$.get("/Produtos/ObterPrecoDoProduto/" + $("#ProdutoId").val(),
function (data) {
$("#PrecoUnitarioCobrado").val(data.replace(".",","));
});
});
})(); |
module.exports = {
_: '/cond/:val1(\\d+)',
get: (controller) => `/globally_replaced_to_root_all/cond/${controller.params('val1', true)}`,
};
|
'use strict'
var subclassOf = require('../util/subclassOf');
var Character = require('./Character');
function Player(){
Character.apply(this, arguments);
}
Player.prototype = subclassOf(Character);
module.exports = Player; |
/**
* @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'a11yhelp', 'sv', {
title: 'Hjälpmedelsinstruktioner',
contents: 'Hjälpinnehåll. För att stänga denna dialogruta trycker du på ESC.',
legend: [
{
name: 'Allmänt',
items: [
{
name: 'Editor verktygsfält',
legend: 'Tryck på ${toolbarFocus} för att navigera till verktygsfältet. Flytta till nästa och föregående verktygsfältsgrupp med TAB och SHIFT+TAB. Flytta till nästa och föregående knapp i verktygsfältet med HÖGERPIL eller VÄNSTERPIL. Tryck SPACE eller ENTER för att aktivera knappen i verktygsfältet.'
},
{
name: 'Dialogeditor',
legend:
'Inuti en dialogruta, tryck TAB för att navigera till nästa fält i dialogrutan, tryck SKIFT+TAB för att flytta till föregående fält, tryck ENTER för att skicka. Du avbryter och stänger dialogen med ESC. För dialogrutor som har flera flikar, tryck ALT+F10 eller TAB för att navigera till fliklistan. med fliklistan vald flytta till nästa och föregående flik med HÖGER- eller VÄNSTERPIL.'
},
{
name: 'Editor för innehållsmeny',
legend: 'Tryck på $ {contextMenu} eller PROGRAMTANGENTEN för att öppna snabbmenyn. Flytta sedan till nästa menyalternativ med TAB eller NEDPIL. Flytta till föregående alternativ med SHIFT + TABB eller UPPIL. Tryck Space eller ENTER för att välja menyalternativ. Öppna undermeny av nuvarande alternativ med SPACE eller ENTER eller HÖGERPIL. Gå tillbaka till överordnade menyalternativ med ESC eller VÄNSTERPIL. Stäng snabbmenyn med ESC.'
},
{
name: 'Editor för list-box',
legend: 'Inuti en list-box, gå till nästa listobjekt med TAB eller NEDPIL. Flytta till föregående listobjekt med SHIFT+TAB eller UPPIL. Tryck SPACE eller ENTER för att välja listan alternativet. Tryck ESC för att stänga list-boxen.'
},
{
name: 'Editor för elementens sökväg',
legend: 'Tryck på ${elementsPathFocus} för att navigera till verktygsfältet för elementens sökvägar. Flytta till nästa elementknapp med TAB eller HÖGERPIL. Flytta till föregående knapp med SKIFT+TAB eller VÄNSTERPIL. Tryck SPACE eller ENTER för att välja element i redigeraren.'
}
]
},
{
name: 'Kommandon',
items: [
{
name: 'Ångra kommando',
legend: 'Tryck på ${undo}'
},
{
name: 'Gör om kommando',
legend: 'Tryck på ${redo}'
},
{
name: 'Kommandot fet stil',
legend: 'Tryck på ${bold}'
},
{
name: 'Kommandot kursiv',
legend: 'Tryck på ${italic}'
},
{
name: 'Kommandot understruken',
legend: 'Tryck på ${underline}'
},
{
name: 'Kommandot länk',
legend: 'Tryck på ${link}'
},
{
name: 'Verktygsfält Dölj kommandot',
legend: 'Tryck på ${toolbarCollapse}'
},
{
name: 'Gå till föregående fokus plats',
legend: 'Tryck på ${accessPreviousSpace} för att gå till närmast onåbara utrymme före markören, exempel: två intilliggande HR element. Repetera tangentkombinationen för att gå till nästa.'
},
{
name: 'Tillgå nästa fokuskommandots utrymme',
legend: 'Tryck ${accessNextSpace} på för att komma åt den närmaste onåbar fokus utrymme efter cirkumflex, till exempel: två intilliggande HR element. Upprepa tangentkombinationen för att nå avlägsna fokus utrymmen.'
},
{
name: 'Hjälp om tillgänglighet',
legend: 'Tryck ${a11yHelp}'
},
{
name: 'Klistra in som vanlig text',
legend: 'Tryck ${pastetext}',
legendEdge: 'Tryck ${pastetext}, följt av ${paste}'
}
]
}
],
tab: 'Tab',
pause: 'Paus',
capslock: 'Caps lock',
escape: 'Escape',
pageUp: 'Sida Up',
pageDown: 'Sida Ned',
leftArrow: 'Vänsterpil',
upArrow: 'Uppil',
rightArrow: 'Högerpil',
downArrow: 'Nedåtpil',
insert: 'Infoga',
leftWindowKey: 'Vänster Windowstangent',
rightWindowKey: 'Höger Windowstangent',
selectKey: 'Välj tangent',
numpad0: 'Nummer 0',
numpad1: 'Nummer 1',
numpad2: 'Nummer 2',
numpad3: 'Nummer 3',
numpad4: 'Nummer 4',
numpad5: 'Nummer 5',
numpad6: 'Nummer 6',
numpad7: 'Nummer 7',
numpad8: 'Nummer 8',
numpad9: 'Nummer 9',
multiply: 'Multiplicera',
add: 'Addera',
subtract: 'Minus',
decimalPoint: 'Decimalpunkt',
divide: 'Dividera',
f1: 'F1',
f2: 'F2',
f3: 'F3',
f4: 'F4',
f5: 'F5',
f6: 'F6',
f7: 'F7',
f8: 'F8',
f9: 'F9',
f10: 'F10',
f11: 'F11',
f12: 'F12',
numLock: 'Num Lock',
scrollLock: 'Scroll Lock',
semiColon: 'Semikolon',
equalSign: 'Lika med tecken',
comma: 'Komma',
dash: 'Minus',
period: 'Punkt',
forwardSlash: 'Snedstreck framåt',
graveAccent: 'Accent',
openBracket: 'Öppningsparentes',
backSlash: 'Snedstreck bakåt',
closeBracket: 'Slutparentes',
singleQuote: 'Enkelt Citattecken'
} );
|
'use strict';
/**
* Clone helper
*
* Clone an array or object
*
* @param items
* @returns {*}
*/
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
module.exports = function clone(items) {
var cloned = void 0;
if (Array.isArray(items)) {
var _cloned;
cloned = [];
(_cloned = cloned).push.apply(_cloned, _toConsumableArray(items));
} else {
cloned = {};
Object.keys(items).forEach(function (prop) {
cloned[prop] = items[prop];
});
}
return cloned;
}; |
songist.controller('PlayerCtrl', ['$scope', '$location', '$route', 'Tracks', 'MediaGalleries', 'Queue', function($scope, $location, $route, Tracks, MediaGalleries, Queue) {
var shuffled = false;
$scope.player = document.getElementById('player');
$scope.history = [];
$scope.duration;
$scope.currentTime;
$scope.repeatPressed = false;
$scope.playpause = function(clicked) {
var playPauseIcon = $('#playPause');
if ($scope.player.paused) {
if (!$scope.currentTrack.track && clicked) {
$.when(Queue.getFirst()).then(function(track) {
$scope.$apply(function() {
if (track) {
$scope.playNextInQueue(track);
} else {
$scope.playNextFiltered();
}
});
});
} else {
$scope.player.play();
playPauseIcon
.removeClass('icon-play')
.removeClass('icon-spinner')
.removeClass('icon-spin')
.addClass('icon-pause');
}
} else {
$scope.player.pause();
playPauseIcon
.removeClass('icon-pause')
.removeClass('icon-spinner')
.removeClass('icon-spin')
.addClass('icon-play');
}
if (clicked) {
console.log("Event: Play/Pause");
}
};
$scope.playNextInQueue = function(track) {
$scope.selectTrack(track, true);
};
$scope.playNextFiltered = function() {
$.when(Tracks.getNext(
$scope.currentTrackFiltered.track,
$scope.genre.name,
$scope.artist.name,
$scope.album.name,
$location.search().q)
).then(function(track) {
if (track) {
$scope.$apply(function() {
$scope.selectTrack(track);
});
} else {
// rewind list
$.when(Tracks.getNext(
null,
$scope.genre.name,
$scope.artist.name,
$scope.album.name,
$location.search().q)
).then(function(track) {
if (track) {
$scope.$apply(function() {
$scope.selectTrack(track);
});
}
});
}
});
};
$scope.selectTrack = function(track, queued) {
// selecting the next track might take a couple of secs.
// Stop currently play one to avoid confusion
$scope.player.pause();
if (queued) {
$scope.currentTrackQueued.track = track;
$scope.currentTrack = $scope.currentTrackQueued;
$scope.history.push({track: track, queued: true});
} else {
$scope.currentTrackQueued.track = null;
$scope.currentTrackFiltered.track = track;
$scope.currentTrack = $scope.currentTrackFiltered;
$scope.history.push({track: track, queued: false});
}
$('#playPause').removeClass('icon-play').addClass('icon-spinner').addClass('icon-spin');
$.when(MediaGalleries.selectTrack(track)).then(function(result) {
$scope.$apply(function() {
$scope.player.src = result;
$scope.playpause();
if ($scope.trackArtShown) {
$scope.showTrackArt();
}
});
});
};
$scope.lastSongWasInQueue = function() {
return $scope.currentTrackQueued.track != null;
};
$scope.forward = function(clicked) {
if ($scope.lastSongWasInQueue()) {
$.when(Queue.getNext(shuffled? null : $scope.currentTrackQueued.track)).then(function(track) {
$scope.$apply(function() {
if (track) {
$scope.playNextInQueue(track);
} else {
$.when(Queue.getFirst()).then(function(track) {
$scope.$apply(function() {
if (track) {
// rewind queue
$scope.playNextInQueue(track);
} else {
// continue with next in current filter
$scope.msg('Continuing with songs in the current filter...');
$scope.playNextFiltered();
}
});
});
}
});
});
shuffled = false;
} else {
$.when(Queue.getFirst()).then(function(track) {
$scope.$apply(function() {
if (track) {
$scope.msg('Continuing with songs in the queue...');
$scope.playNextInQueue(track);
} else {
$scope.playNextFiltered();
}
});
});
}
if (clicked) {
console.log('Event: Forward');
}
};
$scope.backwards = function(replay, clicked) {
if (!replay && !$scope.player.paused && $scope.currentTime > 2) {
$scope.player.currentTime = 0;
} else {
if (!replay) {
$scope.history.pop();
}
var obj = $scope.history.pop();
if (obj) {
$scope.selectTrack(obj.track, obj.queued);
}
}
if (clicked) {
console.log('Event: Backwards');
}
};
$scope.shuffle = function(clicked) {
$scope.msg('shuffling queue <i class="icon-spinner icon-spin"></i>', false);
$.when(Queue.shuffle()).then(function() {
$scope.$apply(function() {
if ($location.path() == '/queue') {
$route.reload();
}
$scope.msg('Queue has been shuffled');
shuffled = true;
});
}, function(msg) {
$scope.$apply(function() {
$scope.msg(msg);
});
});
if (clicked) {
console.log('Event: Shuffle');
}
};
$scope.repeat = function(clicked) {
if ($scope.repeatPressed) {
$scope.repeatPressed = false;
$('#btnRepeat').css('color', '#fff');
} else {
$scope.repeatPressed = true;
$('#btnRepeat').css('color', '#ccc');
}
if (clicked) {
console.log('Event: Repeat');
}
};
$scope.updatePlaying = function() {
$scope.duration = $scope.player.duration;
$scope.currentTime = $scope.player.currentTime;
var percent = $scope.currentTime / $scope.duration * 100;
$('#playingPosition').css('width', percent + '%');
var currentTime = new Date().valueOf();
if (currentTime - $scope.mouseMoveTime > 10000) {
$scope.mouseMoveTime = currentTime;
if ($scope.currentTrack.track) {
if (!$scope.trackArtShown) {
$scope.showTrackArt();
}
}
}
};
$scope.seek = function(e) {
if ($scope.currentTrack.track) {
var width = e.currentTarget.offsetWidth;
var begin = e.currentTarget.offsetLeft;
var seek = e.clientX;
var percent = (seek - begin) / width;
var secs = percent * $scope.duration;
$scope.player.currentTime = secs;
}
};
$scope.playEnded = function() {
if ($scope.repeatPressed) {
$scope.backwards(true);
} else {
$scope.forward();
}
};
$($scope.player).bind('timeupdate', $scope.updatePlaying);
$($scope.player).bind('ended', $scope.playEnded);
$('#volume input').slider().on('slide', function(e) {
$scope.player.volume = e.value / 100;
});
}]);
|
/**
*
* @providesModule restful
*
*/
import 'react-native';
// o tipo do corpo de uma requisição
export type PayloadType = string | Object;
// o tipo do retorno de um pedido
export type ResultType = { status: string,
error: null | string,
response: null | Promise<Object>
};
export interface Restful {
get(resource: string): Promise<Response>;
post(resource: string, data: PayloadType): Promise<Response>;
put(resource: string, data: PayloadType): Promise<Response>;
patch(resource: string, data: PayloadType): Promise<Response>;
delete(resource: string, data: PayloadType): Promise<Response>;
}
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { gear } from "/gen/libs.js";
import { wgl } from "../djee/index.js";
import { required } from "../utils/misc.js";
const mySketch = new Image();
const square = [
-1, +1,
-1, -1,
+1, +1,
+1, -1
];
export function init() {
window.onload = doInit;
}
function doInit() {
return __awaiter(this, void 0, void 0, function* () {
const shaders = yield gear.fetchTextFiles({
vertexShaderCode: "mandelbrot.vert",
fragmentShaderCode: "home.frag"
}, "/shaders");
const context = wgl.Context.of("canvas");
const vertexShader = context.shader(wgl.ShaderType.VertexShader, shaders.vertexShaderCode);
const fragmentShader = context.shader(wgl.ShaderType.FragmentShader, shaders.fragmentShaderCode);
const program = vertexShader.linkTo(fragmentShader);
program.use();
const texture = context.newTexture2D();
texture.setRawImage({
format: WebGL2RenderingContext.RGBA,
width: 2,
height: 2,
pixels: new Uint8Array([
0xFF, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF,
0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF
])
});
const buffer = context.newAttributesBuffer();
buffer.float32Data = square;
const effect = program.uniform("effect");
effect.data = [0];
const mousePos = program.uniform("mousePos");
mousePos.data = [0x10000, 0x10000];
const sampler = program.uniform("sampler");
sampler.data = [texture.unit];
const vertex = program.attribute("vertex");
vertex.pointTo(buffer);
draw(context);
mySketch.onload = () => updateTexture(texture);
mySketch.src = "/MySketch.png";
context.canvas.ontouchmove = event => event.preventDefault();
context.canvas.onpointermove = event => distortImage(event, mousePos);
context.canvas.onpointerleave = () => restoreImage(mousePos, effect);
context.canvas.onclick = event => useCurrentImage(event, mousePos, texture);
context.canvas.ondblclick = event => restoreOriginalImage(event, texture);
context.canvas.ondragover = event => tearImage(event, mousePos, effect);
context.canvas.ondrop = event => loadImage(event, effect);
});
}
function draw(context) {
const gl = context.gl;
gl.viewport(0, 0, context.canvas.width, context.canvas.height);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
gl.flush();
}
function updateTexture(texture) {
return __awaiter(this, void 0, void 0, function* () {
const context = texture.context;
const canvas = context.canvas;
const image = yield createImageBitmap(mySketch, 0, 0, mySketch.naturalWidth, mySketch.naturalHeight, {
resizeWidth: canvas.width,
resizeHeight: canvas.height
});
texture.setImageSource(image);
draw(context);
});
}
function useCurrentImage(e, mousePos, texture) {
return __awaiter(this, void 0, void 0, function* () {
distortImage(e, mousePos);
const image = yield createImageBitmap(texture.context.canvas, 0, 0, mySketch.naturalWidth, mySketch.naturalHeight);
texture.setImageSource(image);
});
}
function distortImage(e, mousePos) {
e.preventDefault();
mousePos.data = normalizePosition(e);
draw(mousePos.program.context);
}
function restoreImage(mousePos, effect) {
mousePos.data = [0x10000, 0x10000];
effect.data = [(effect.data[0] + 1) % 3];
draw(mousePos.program.context);
}
function restoreOriginalImage(e, texture) {
e.preventDefault();
updateTexture(texture);
}
function tearImage(e, mousePos, effect) {
e.preventDefault();
mousePos.data = normalizePosition(e);
if (effect.data[0] < 3) {
effect.data = [effect.data[0] + 3];
}
draw(mousePos.program.context);
}
function loadImage(e, effect) {
return __awaiter(this, void 0, void 0, function* () {
e.preventDefault();
effect.data = [effect.data[0] - 3];
if (e.dataTransfer) {
const item = e.dataTransfer.items[0];
if (item.kind == 'file') {
const url = URL.createObjectURL(required(item.getAsFile()));
mySketch.src = url;
}
else {
item.getAsString(url => {
mySketch.crossOrigin = isCrossOrigin(url) ? "anonymous" : null;
mySketch.src = url;
});
}
}
});
}
function isCrossOrigin(url) {
const urlObj = new URL(url, window.location.href);
const isCrossOrigin = urlObj.origin != window.location.origin;
return isCrossOrigin;
}
function normalizePosition(e) {
const canvas = e.target;
return [
(2 * e.offsetX - canvas.clientWidth) / canvas.clientWidth,
(canvas.clientHeight - 2 * e.offsetY) / canvas.clientHeight
];
}
//# sourceMappingURL=toy.js.map |
var t = require('babel-types');
function toES5Component(name, jsxElement) {
return t.variableDeclaration(
'const',
[t.variableDeclarator(
t.identifier(name),
t.callExpression(
t.memberExpression(
t.identifier('React'),
t.identifier('createClass')),
[t.objectExpression([
t.objectMethod(
'method',
t.identifier('render'),
[],
t.blockStatement([t.returnStatement(jsxElement)])
)
])]))]);
}
function toES6Component(name, jsxElement) {
return t.classDeclaration(
t.identifier(name),
t.memberExpression(
t.identifier('React'),
t.identifier('Component')),
t.classBody([
t.classMethod(
'method',
t.identifier('render'),
[],
t.blockStatement([t.returnStatement(jsxElement)])
)
]),
[]);
}
function toStatelessComponent(name, jsxElement) {
return t.variableDeclaration(
'const',
[t.variableDeclarator(
t.identifier(name),
t.arrowFunctionExpression(
[],
jsxElement))]);
}
function toReactComponents(componentType, components) {
return Object.keys(components)
.reduce(function(cs, name) {
var ast;
var expr = components[name].body.program.body[0].expression;
switch (componentType) {
case 'es5':
ast = toES5Component(name, expr);
break;
case 'es6':
ast = toES6Component(name, expr);
break;
case 'stateless':
ast = toStatelessComponent(name, expr);
break;
default:
ast = toES5Component(name, expr);
}
cs[name] = {
body: ast,
children: components[name].children
};
return cs;
}, {});
}
module.exports = toReactComponents;
|
var register = require('./register')
var stream = require('stream')
var cadence = require('cadence')
module.exports = cadence(function (step, directory, params, argv, stdin) {
if (Array.isArray(params)) {
stdin = argv
argv = params
params = {}
}
step(function () {
register.once(__dirname, directory, params, argv, stdin, step())
}, function (request, server) {
var stdout = new stream.PassThrough
stdout.setEncoding('utf8')
step(function () {
request.pipe(stdout)
request.on('end', step(-1))
server.on('close', step(-1))
}, function () {
return {
statusCode: request.statusCode,
headers: request.headers,
body: stdout.read()
}
})
})
})
|
var digger = require('../src');
var async = require('async');
var _ = require('lodash');
var Bridge = require('digger-bridge');
describe('contractresolver', function(){
it('should run a basic pipe contract', function(done){
var warehouse = digger.warehouse();
warehouse.use(digger.middleware.contractresolver(warehouse));
warehouse.use('/apples', function(req, res){
res.send([1,2]);
})
warehouse.use('/oranges', function(req, res){
var answer = _.map(req.body, function(digit){
return digit*2;
})
res.send(answer);
})
var contract = Bridge.contract('pipe');
var req1 = Bridge.request({
method:'post',
url:'/apples'
})
var req2 = Bridge.request({
method:'post',
url:'/oranges'
})
contract.add(req1);
contract.add(req2);
var res = Bridge.response(function(){
res.statusCode.should.equal(200);
res.body.length.should.equal(2);
res.body[0].should.equal(2);
res.body[1].should.equal(4);
done();
})
warehouse(contract, res);
})
it('should run a basic merge contract', function(done){
var warehouse = digger.warehouse();
warehouse.use(digger.middleware.contractresolver(warehouse));
warehouse.use('/apples', function(req, res){
res.send([1,2]);
})
warehouse.use('/oranges', function(req, res){
res.send([3,4]);
})
var contract = Bridge.contract('merge');
var req1 = Bridge.request({
method:'get',
url:'/apples'
})
var req2 = Bridge.request({
method:'get',
url:'/oranges'
})
contract.add(req1);
contract.add(req2);
var res = Bridge.response(true);
res.on('success', function(results){
res.statusCode.should.equal(200);
results.length.should.equal(4);
results[1].should.equal(2);
results[3].should.equal(4);
done();
})
warehouse(contract, res);
})
it('should run a basic sequence contract', function(done){
var warehouse = digger.warehouse();
warehouse.use(digger.middleware.contractresolver(warehouse));
var starttime = new Date().getTime();
warehouse.use('/apples', function(req, res){
setTimeout(function(){
res.send([1,2]);
}, 50)
})
warehouse.use('/oranges', function(req, res){
req.body.should.equal(123);
var nowtime = new Date().getTime();
var timegap = nowtime-starttime;
var isless = timegap<50;
isless.should.equal(false);
res.send([3,4]);
})
var contract = Bridge.contract('sequence');
var req1 = Bridge.request({
method:'get',
url:'/apples'
})
var req2 = Bridge.request({
method:'post',
url:'/oranges',
body:123
})
contract.add(req1);
contract.add(req2);
var res = Bridge.response(true);
res.on('success', function(results){
res.statusCode.should.equal(200);
results.length.should.equal(2);
results[0].should.equal(3);
results[1].should.equal(4);
done();
})
warehouse(contract, res);
})
})
|
'use strict';
/**
* The gameboard controller is responsible for setting up a level and managing gameplay for
* a level
* */
var Gameboard = function (canvas, hdim, vdim) {
this.canvas = canvas;
this.camera = new Camera(canvas);
this.grid = new GameGrid(768 * hdim, 1024 * vdim, 768, 1024);
this.waterfall = new ParticleWorld(canvas, this.grid);
this.editorui = new EditorUI(this.waterfall);
this.hdim = hdim || 3;
this.vdim = vdim || 3;
this.drawDt = 0;
this.framerate = 30;
this.currentDrawTime = 0;
this.lastDrawTime = 0;
this.selectedLevel = -1;
this.hoverLevel = -1;
this.clickLevel = -1;
this.levelButtons = [];
this.zoomTime = 0;
this.startZoomFactor = 1;
this.finalZoomFactor = 1;
this.zoomTransition = false;
this.loadLevels();
this.camera.setExtents(768, 1024);
this.camera.setCenter(768 * 0.5, 1025 * 0.5);
this.startZoomCenter = new Vector(this.camera.center.x, this.camera.center.y);
this.finalZoomCenter = new Vector(this.camera.center.x, this.camera.center.y);
this.startZoomExtents = new Vector(this.camera.viewportWidth, this.camera.viewportHeight);
this.finalZoomExtents = new Vector(this.camera.viewportWidth, this.camera.viewportHeight);
this.editmode = true;
//setup ui...
//$("#object-form").html('');
//$("#object-form").off();
};
Gameboard.prototype = {
setHandlers: function () {
//$('canvas').unbind();
//$(document).unbind();
this.hide();
this.editorui.show();
//$(document).bind('opendoor', $.proxy(function (e) {
// console.log("open door message");
// //this.doorIsOpen = true;
//}, this));
$("#editor-toggle").append('<pre>Edit Mode: <input id="edit-mode-input" type="checkbox" value="' + this.editmode + '"></span><br></pre>');
$("#edit-mode-input").change($.proxy(function () {
this.editmode = $("#edit-mode-input").prop('checked');
if (this.editmode) {
this.editorui.show();
} else {
this.editorui.hide();
}
}, this));
$("#edit-mode-input").prop('checked', true);
$('canvas').bind('mousedown touchstart', $.proxy(function (e) {
var x = Math.floor((e.pageX - $("#canvas").offset().left)),
y = Math.floor((e.pageY - $("#canvas").offset().top)),
p = this.camera.screenToWorld(x, y);
this.waterfall.mouseDown = true;
this.waterfall.hitInteractable(p.x, p.y, this.editmode);
this.editorui.gameObjectForm.gameObject = this.waterfall.interactable;
this.editorui.gameObjectForm.hide();
if (this.waterfall.interactable) {
this.editorui.gameObjectForm.show();
} else {
this.selectLevel(this.levelButtonHit(p.x, p.y));
}
}, this));
$(document).bind('mouseup touchend', $.proxy(function (e) {
this.waterfall.mouseDown = false;
this.waterfall.interactable = null;
}, this));
$('canvas').bind('mousemove touchmove', $.proxy(function (e) {
if (this.waterfall.mouseDown === false) {
return;
}
var x = Math.floor((e.pageX - $("#canvas").offset().left)),
y = Math.floor((e.pageY - $("#canvas").offset().top)),
p = this.camera.screenToWorld(x, y);
if (this.waterfall.interactable && this.waterfall.interactable.grabberSelected) {
//move the sinks grabber...
this.waterfall.interactable.moveGrabber(p);
} else if (this.waterfall.interactable) {
this.waterfall.interactable.setxy(p.x, p.y);
this.editorui.gameObjectForm.updateLocation();
}
this.hoverLevel = this.levelButtonHit(p.x, p.y);
}, this));
$(document).bind('keydown', $.proxy(function (e) {
var obj, obj2;
//console.log(e.keyCode);
switch (e.keyCode) {
case 39: //right arrow
this.moveRight();
break;
case 37:
this.moveLeft();
break;
case 38:
this.moveUp();
break;
case 40:
this.moveDown();
break;
default:
break;
}
}, this));
$(document).bind('keypress', $.proxy(function (e) {
var obj, obj2;
console.log(e.keyCode);
switch (e.keyCode) {
case 45: //minus
this.home();
break;
default:
break;
}
}, this));
$(document).bind('levelup', $.proxy(function (e) {
this.home();
}, this));
this.waterfall.setHandlers();
},
hide: function () {
$("#editor-toggle").html('');
$("#editor-toggle").off();
this.editorui.hide();
},
update: function (dt) {
if (this.zoomTransition) {
this.onZoomTransition(dt);
}
this.waterfall.update(dt);
this.draw(dt);
},
loadLevels: function () {
var w = 768, h = 1024, r, x, y, i, j;
for (j = 0; j < this.vdim; j += 1) {
for (i = 0; i < this.hdim; i += 1) {
x = w * i;
y = h * j;
r = new Rectangle(x + w * 0.5, y + h * 0.5, w, h, 0);
this.levelButtons.push(r);
}
}
//level0
//LevelLoader.load(this.waterfall, level4, 768, 1024);
//LevelLoader.load(this.waterfall, levels[0], 768, 1024);
//LevelLoader.load(this.waterfall, awesomelevel, 0, 0);
//LevelLoader.addLevel(this.waterfall, level3, 768 * 2, 1024);
},
levelButtonHit: function (x, y) {
var i = 0, p = new Particle(x, y), b;
for (i = 0; i < this.levelButtons.length; i += 1) {
b = this.levelButtons[i].bbHit(p);
if (b) {
return i;
}
}
return -1;
},
selectLevel: function (i) {
//zoom to level and enable interactabble object handlers
var r = this.levelButtons[i];
this.selectedLevel = i;
this.zoomTransition = true;
this.startZoomCenter = new Vector(this.camera.center.x, this.camera.center.y);
this.finalZoomCenter = new Vector(r.x, r.y);
this.startZoomExtents = new Vector(this.camera.viewportWidth, this.camera.viewportHeight);
this.finalZoomExtents = new Vector(r.w, r.h);
this.zoomTime = 0;
},
onZoomTransition: function (dt) {
var duration = 500,
centerDeltaX = this.finalZoomCenter.x - this.startZoomCenter.x,
centerDeltaY = this.finalZoomCenter.y - this.startZoomCenter.y,
extentDeltaX = this.finalZoomExtents.x - this.startZoomExtents.x,
extentDeltaY = this.finalZoomExtents.y - this.startZoomExtents.y,
x,
y;
//when this.zoomTime = duration we should be fully transitioned
if (this.zoomTime > duration) {
this.zoomTime = duration;
this.zoomTransition = false;
}
x = this.zoomTime / duration * centerDeltaX + this.startZoomCenter.x;
y = this.zoomTime / duration * centerDeltaY + this.startZoomCenter.y;
this.camera.setCenter(x, y);
x = this.zoomTime / duration * extentDeltaX + this.startZoomExtents.x;
y = this.zoomTime / duration * extentDeltaY + this.startZoomExtents.y;
this.camera.setExtents(x, y);
this.zoomTime += dt;
},
home: function () {
this.zoomTransition = true;
this.selectedLevel = 4;
this.startZoomCenter = new Vector(this.camera.center.x, this.camera.center.y);
this.finalZoomCenter = new Vector(768 * 1.5, 1024 * 1.5);
this.startZoomExtents = new Vector(this.camera.viewportWidth, this.camera.viewportHeight);
this.finalZoomExtents = new Vector(768 * 3, 1024 * 3);
this.zoomTime = 0;
},
moveRight: function () {
var i = Math.min(this.selectedLevel + 1, this.hdim * this.vdim);
this.selectLevel(i);
},
moveLeft: function () {
var i = Math.max(this.selectedLevel - 1, 0);
this.selectLevel(i);
},
moveUp: function () {
var i = Math.max(this.selectedLevel - this.vdim, 0);
this.selectLevel(i);
},
moveDown: function () {
var i = Math.min(this.selectedLevel + this.vdim, this.hdim * this.vdim);
this.selectLevel(i);
},
draw: function (dt) {
this.drawDt += dt;
if (this.drawDt > this.framerate) {
this.currentDrawTime = new Date().getTime();
this.lastDrawTime = this.currentDrawTime;
this.camera.reset(this.waterfall.bgColor);
this.camera.show();
/*if (this.hoverLevel > -1) {
var color = 'rgba(100,100,255,1)',
b = this.levelButtons[this.hoverLevel];
this.canvas.rectangleOutline(b.p1, b.p2, b.p3, b.p4, 4, color);
}*/
this.waterfall.draw(this.drawDt);
this.drawDt = 0;
}
}
};
|
// Dev Mode Webpack Configuration
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: {
app: [
'webpack-dev-server/client?http://0.0.0.0:3000',
'webpack/hot/only-dev-server',
'./src/main/js/mountApp'
]
},
output: {
path: path.join(__dirname, 'public'),
filename: '[name].bundle.js',
publicPath: '/'
},
devtool: 'source-map',
module: {
loaders: [{
test: /\.js?$/,
loaders: ['react-hot', 'babel'],
include: path.join(__dirname, 'src')
}, {
test: /\.less$/,
loader: 'style!css!less!autoprefixer'
}]
},
plugins: [
new webpack.HotModuleReplacementPlugin()
]
};
|
var orderly = function () {
var a = function () {
var a = {}, b = {}, c = function (d) {
a[d] || (console.log (d), a[d] = {}, b[d] (c, a[d], {id: d}));
return a[d]
};
c.def = function (a, c) {
console.log ("def", a), b[a] = c.factory
};
return c
} ();
a.def ("orderly", {
factory: function (a, b, c) {
var d = a ("parser").parser;
d.yy = a ("scope");
var e = b.parse = function (a) {
return d.parse (a)
}, f = b.compile = function (a, b) {
return JSON.stringify (e (a), null, b || " ")
};
b.main = function (b) {
var c = a ("file"), d = c.path (c.cwd ());
if (!b[1])throw new Error ("Usage: " + b[0] + " FILE [OUTFILE]");
var e = d.join (b[1]).read ({charset: "utf-8"}), g = f (e), h = d.join (b[2] || c.basename (b[1], ".orderly") + ".jsonschema").open ("w");
h.print (g).close ()
}
}, requires: ["parser", "scope", "file"]
}), a.def ("parser", {
factory: function (a, b, c) {
var d = function () {
var a = {
trace: function () {
},
yy: {},
symbols_: {
error: 2,
file: 3,
orderly_schema: 4,
EOF: 5,
unnamed_entry: 6,
";": 7,
named_entries: 8,
named_entry: 9,
unnamed_entries: 10,
definition_prefix: 11,
property_name: 12,
definition_suffix: 13,
string_prefix: 14,
string_suffix: 15,
INTEGER: 16,
optional_range: 17,
NUMBER: 18,
BOOLEAN: 19,
NULL: 20,
ANY: 21,
ARRAY: 22,
"{": 23,
"}": 24,
optional_additional_marker: 25,
"[": 26,
"]": 27,
OBJECT: 28,
UNION: 29,
STRING: 30,
optional_perl_regex: 31,
optional_enum_values: 32,
optional_default_value: 33,
optional_requires: 34,
optional_optional_marker: 35,
optional_extra_properties: 36,
csv_property_names: 37,
",": 38,
"`": 39,
JSONObject: 40,
"<": 41,
">": 42,
"?": 43,
"*": 44,
JSONArray: 45,
"=": 46,
JSONValue: 47,
JSONNumber: 48,
JSONString: 49,
PROPERTY: 50,
REGEX: 51,
STRING_LIT: 52,
NUMBER_LIT: 53,
JSONNullLiteral: 54,
JSONBooleanLiteral: 55,
TRUE: 56,
FALSE: 57,
JSONText: 58,
JSONMemberList: 59,
JSONMember: 60,
":": 61,
JSONElementList: 62,
$accept: 0,
$end: 1
},
terminals_: {
2: "error",
5: "EOF",
7: ";",
16: "INTEGER",
18: "NUMBER",
19: "BOOLEAN",
20: "NULL",
21: "ANY",
22: "ARRAY",
23: "{",
24: "}",
26: "[",
27: "]",
28: "OBJECT",
29: "UNION",
30: "STRING",
38: ",",
39: "`",
41: "<",
42: ">",
43: "?",
44: "*",
46: "=",
50: "PROPERTY",
51: "REGEX",
52: "STRING_LIT",
53: "NUMBER_LIT",
56: "TRUE",
57: "FALSE",
61: ":"
},
productions_: [0, [3, 2], [4, 2], [4, 1], [8, 3], [8, 1], [8, 0], [10, 3], [10, 1], [10, 0], [9, 3], [9, 3], [6, 2], [6, 2], [11, 2], [11, 2], [11, 1], [11, 1], [11, 1], [11, 6], [11, 6], [11, 5], [11, 4], [14, 2], [15, 2], [13, 5], [37, 3], [37, 1], [36, 3], [36, 0], [34, 3], [34, 0], [35, 1], [35, 0], [25, 1], [25, 0], [32, 1], [32, 0], [33, 2], [33, 0], [17, 5], [17, 4], [17, 4], [17, 3], [17, 0], [12, 1], [12, 1], [31, 1], [31, 0], [49, 1], [48, 1], [54, 1], [55, 1], [55, 1], [58, 1], [47, 1], [47, 1], [47, 1], [47, 1], [47, 1], [47, 1], [40, 2], [40, 3], [60, 3], [59, 1], [59, 3], [45, 2], [45, 3], [62, 1], [62, 3]],
performAction: function (a, b, c, d, e, f, g) {
var h = f.length - 1;
switch (e) {
case 1:
return f[h - 1];
case 4:
this.$ = f[h], this.$.unshift (f[h - 2]);
break;
case 5:
this.$ = [f[h]];
break;
case 6:
this.$ = [];
break;
case 7:
this.$ = f[h], f[h].unshift (f[h - 2]);
break;
case 8:
this.$ = [f[h]];
break;
case 9:
this.$ = [];
break;
case 10:
this.$ = [f[h - 1], f[h - 2]], d.Type.addOptionals (f[h - 2], f[h]);
break;
case 11:
this.$ = [f[h - 1], f[h - 2]], d.Type.addOptionals (f[h - 2], f[h]);
break;
case 12:
this.$ = f[h - 1], d.Type.addOptionals (this.$, f[h]);
break;
case 13:
this.$ = f[h - 1], d.Type.addOptionals (this.$, f[h]);
break;
case 14:
this.$ = new d.Type ("integer", f[h]);
break;
case 15:
this.$ = new d.Type ("number", f[h]);
break;
case 16:
this.$ = new d.Type ("boolean");
break;
case 17:
this.$ = new d.Type ("null");
break;
case 18:
this.$ = new d.Type ("any");
break;
case 19:
this.$ = new d.Type ("array", f[h], f[h - 3], f[h - 1]);
break;
case 20:
this.$ = new d.Type ("array", f[h], f[h - 3], f[h - 1]);
break;
case 21:
this.$ = new d.Type ("object", null, f[h - 2], f[h]);
break;
case 22:
this.$ = new d.Type (f[h - 1]);
break;
case 23:
this.$ = new d.Type ("string", f[h]);
break;
case 24:
this.$ = f[h], this.$.pattern = f[h - 1];
break;
case 25:
this.$ = {enums: f[h - 4], defaultv: f[h - 3], requires: f[h - 2], optional: f[h - 1], extras: f[h]};
break;
case 26:
this.$ = f[h - 2], this.$.push (f[h]);
break;
case 27:
this.$ = [f[h]];
break;
case 28:
this.$ = f[h - 1];
break;
case 29:
this.$ = null;
break;
case 30:
this.$ = f[h - 1];
break;
case 31:
this.$ = null;
break;
case 32:
this.$ = !0;
break;
case 33:
this.$ = null;
break;
case 34:
this.$ = !0;
break;
case 35:
this.$ = null;
break;
case 37:
this.$ = null;
break;
case 38:
this.$ = f[h];
break;
case 39:
this.$ = d.NOVALUE;
break;
case 40:
this.$ = [f[h - 3], f[h - 1]];
break;
case 41:
this.$ = [f[h - 2], null];
break;
case 42:
this.$ = [null, f[h - 1]];
break;
case 43:
this.$ = null;
break;
case 44:
this.$ = null;
break;
case 46:
this.$ = a;
break;
case 47:
this.$ = a.substr (1, a.length - 2);
break;
case 48:
this.$ = null;
break;
case 49:
this.$ = a;
break;
case 50:
this.$ = Number (a);
break;
case 51:
this.$ = null;
break;
case 52:
this.$ = !0;
break;
case 53:
this.$ = !1;
break;
case 61:
this.$ = {};
break;
case 62:
this.$ = f[h - 1];
break;
case 63:
this.$ = [f[h - 2], f[h]];
break;
case 64:
this.$ = {}, this.$[f[h][0]] = f[h][1];
break;
case 65:
this.$ = f[h - 2], f[h - 2][f[h][0]] = f[h][1];
break;
case 66:
this.$ = [];
break;
case 67:
this.$ = f[h - 1];
break;
case 68:
this.$ = [f[h]];
break;
case 69:
this.$ = f[h - 2], f[h - 2].push (f[h])
}
},
table: [{
3: 1,
4: 2,
6: 3,
11: 4,
14: 5,
16: [1, 6],
18: [1, 7],
19: [1, 8],
20: [1, 9],
21: [1, 10],
22: [1, 11],
28: [1, 12],
29: [1, 13],
30: [1, 14]
}, {1: [3]}, {5: [1, 15]}, {5: [2, 3], 7: [1, 16]}, {
5: [2, 37],
7: [2, 37],
13: 17,
24: [2, 37],
26: [1, 20],
27: [2, 37],
32: 18,
39: [2, 37],
41: [2, 37],
43: [2, 37],
45: 19,
46: [2, 37]
}, {
5: [2, 48],
7: [2, 48],
15: 21,
24: [2, 48],
26: [2, 48],
27: [2, 48],
31: 22,
39: [2, 48],
41: [2, 48],
43: [2, 48],
46: [2, 48],
51: [1, 23]
}, {
5: [2, 44],
7: [2, 44],
17: 24,
23: [1, 25],
24: [2, 44],
26: [2, 44],
27: [2, 44],
39: [2, 44],
41: [2, 44],
43: [2, 44],
46: [2, 44],
50: [2, 44],
52: [2, 44]
}, {
5: [2, 44],
7: [2, 44],
17: 26,
23: [1, 25],
24: [2, 44],
26: [2, 44],
27: [2, 44],
39: [2, 44],
41: [2, 44],
43: [2, 44],
46: [2, 44],
50: [2, 44],
52: [2, 44]
}, {
5: [2, 16],
7: [2, 16],
24: [2, 16],
26: [2, 16],
27: [2, 16],
39: [2, 16],
41: [2, 16],
43: [2, 16],
46: [2, 16],
50: [2, 16],
52: [2, 16]
}, {
5: [2, 17],
7: [2, 17],
24: [2, 17],
26: [2, 17],
27: [2, 17],
39: [2, 17],
41: [2, 17],
43: [2, 17],
46: [2, 17],
50: [2, 17],
52: [2, 17]
}, {
5: [2, 18],
7: [2, 18],
24: [2, 18],
26: [2, 18],
27: [2, 18],
39: [2, 18],
41: [2, 18],
43: [2, 18],
46: [2, 18],
50: [2, 18],
52: [2, 18]
}, {23: [1, 27], 26: [1, 28]}, {23: [1, 29]}, {23: [1, 30]}, {
5: [2, 44],
7: [2, 44],
17: 31,
23: [1, 25],
24: [2, 44],
26: [2, 44],
27: [2, 44],
39: [2, 44],
41: [2, 44],
43: [2, 44],
46: [2, 44],
50: [2, 44],
51: [2, 44],
52: [2, 44]
}, {1: [2, 1]}, {5: [2, 2]}, {5: [2, 12], 7: [2, 12], 24: [2, 12], 27: [2, 12]}, {
5: [2, 39],
7: [2, 39],
24: [2, 39],
27: [2, 39],
33: 32,
39: [2, 39],
41: [2, 39],
43: [2, 39],
46: [1, 33]
}, {
5: [2, 36],
7: [2, 36],
24: [2, 36],
27: [2, 36],
39: [2, 36],
41: [2, 36],
43: [2, 36],
46: [2, 36]
}, {
20: [1, 43],
23: [1, 48],
26: [1, 20],
27: [1, 34],
40: 41,
45: 42,
47: 36,
48: 40,
49: 39,
52: [1, 46],
53: [1, 47],
54: 37,
55: 38,
56: [1, 44],
57: [1, 45],
62: 35
}, {5: [2, 13], 7: [2, 13], 24: [2, 13], 27: [2, 13]}, {
5: [2, 37],
7: [2, 37],
13: 49,
24: [2, 37],
26: [1, 20],
27: [2, 37],
32: 18,
39: [2, 37],
41: [2, 37],
43: [2, 37],
45: 19,
46: [2, 37]
}, {
5: [2, 47],
7: [2, 47],
24: [2, 47],
26: [2, 47],
27: [2, 47],
39: [2, 47],
41: [2, 47],
43: [2, 47],
46: [2, 47]
}, {
5: [2, 14],
7: [2, 14],
24: [2, 14],
26: [2, 14],
27: [2, 14],
39: [2, 14],
41: [2, 14],
43: [2, 14],
46: [2, 14],
50: [2, 14],
52: [2, 14]
}, {38: [1, 51], 48: 50, 53: [1, 47]}, {
5: [2, 15],
7: [2, 15],
24: [2, 15],
26: [2, 15],
27: [2, 15],
39: [2, 15],
41: [2, 15],
43: [2, 15],
46: [2, 15],
50: [2, 15],
52: [2, 15]
}, {
6: 53,
10: 52,
11: 4,
14: 5,
16: [1, 6],
18: [1, 7],
19: [1, 8],
20: [1, 9],
21: [1, 10],
22: [1, 11],
24: [2, 9],
28: [1, 12],
29: [1, 13],
30: [1, 14]
}, {
6: 54,
11: 4,
14: 5,
16: [1, 6],
18: [1, 7],
19: [1, 8],
20: [1, 9],
21: [1, 10],
22: [1, 11],
28: [1, 12],
29: [1, 13],
30: [1, 14]
}, {
8: 55,
9: 56,
11: 57,
14: 58,
16: [1, 6],
18: [1, 7],
19: [1, 8],
20: [1, 9],
21: [1, 10],
22: [1, 11],
24: [2, 6],
28: [1, 12],
29: [1, 13],
30: [1, 14]
}, {
6: 53,
10: 59,
11: 4,
14: 5,
16: [1, 6],
18: [1, 7],
19: [1, 8],
20: [1, 9],
21: [1, 10],
22: [1, 11],
24: [2, 9],
28: [1, 12],
29: [1, 13],
30: [1, 14]
}, {
5: [2, 23],
7: [2, 23],
24: [2, 23],
26: [2, 23],
27: [2, 23],
39: [2, 23],
41: [2, 23],
43: [2, 23],
46: [2, 23],
50: [2, 23],
51: [2, 23],
52: [2, 23]
}, {
5: [2, 31],
7: [2, 31],
24: [2, 31],
27: [2, 31],
34: 60,
39: [2, 31],
41: [1, 61],
43: [2, 31]
}, {
20: [1, 43],
23: [1, 48],
26: [1, 20],
40: 41,
45: 42,
47: 62,
48: 40,
49: 39,
52: [1, 46],
53: [1, 47],
54: 37,
55: 38,
56: [1, 44],
57: [1, 45]
}, {
5: [2, 66],
7: [2, 66],
24: [2, 66],
27: [2, 66],
38: [2, 66],
39: [2, 66],
41: [2, 66],
43: [2, 66],
46: [2, 66]
}, {27: [1, 63], 38: [1, 64]}, {27: [2, 68], 38: [2, 68]}, {
5: [2, 55],
7: [2, 55],
24: [2, 55],
27: [2, 55],
38: [2, 55],
39: [2, 55],
41: [2, 55],
43: [2, 55]
}, {
5: [2, 56],
7: [2, 56],
24: [2, 56],
27: [2, 56],
38: [2, 56],
39: [2, 56],
41: [2, 56],
43: [2, 56]
}, {
5: [2, 57],
7: [2, 57],
24: [2, 57],
27: [2, 57],
38: [2, 57],
39: [2, 57],
41: [2, 57],
43: [2, 57]
}, {
5: [2, 58],
7: [2, 58],
24: [2, 58],
27: [2, 58],
38: [2, 58],
39: [2, 58],
41: [2, 58],
43: [2, 58]
}, {
5: [2, 59],
7: [2, 59],
24: [2, 59],
27: [2, 59],
38: [2, 59],
39: [2, 59],
41: [2, 59],
43: [2, 59]
}, {
5: [2, 60],
7: [2, 60],
24: [2, 60],
27: [2, 60],
38: [2, 60],
39: [2, 60],
41: [2, 60],
43: [2, 60]
}, {
5: [2, 51],
7: [2, 51],
24: [2, 51],
27: [2, 51],
38: [2, 51],
39: [2, 51],
41: [2, 51],
43: [2, 51]
}, {
5: [2, 52],
7: [2, 52],
24: [2, 52],
27: [2, 52],
38: [2, 52],
39: [2, 52],
41: [2, 52],
43: [2, 52]
}, {
5: [2, 53],
7: [2, 53],
24: [2, 53],
27: [2, 53],
38: [2, 53],
39: [2, 53],
41: [2, 53],
43: [2, 53]
}, {
5: [2, 49],
7: [2, 49],
24: [2, 49],
26: [2, 49],
27: [2, 49],
38: [2, 49],
39: [2, 49],
41: [2, 49],
42: [2, 49],
43: [2, 49],
46: [2, 49],
51: [2, 49],
61: [2, 49]
}, {
5: [2, 50],
7: [2, 50],
24: [2, 50],
27: [2, 50],
38: [2, 50],
39: [2, 50],
41: [2, 50],
43: [2, 50]
}, {24: [1, 65], 49: 68, 52: [1, 46], 59: 66, 60: 67}, {
5: [2, 24],
7: [2, 24],
24: [2, 24],
27: [2, 24]
}, {38: [1, 69]}, {24: [1, 71], 48: 70, 53: [1, 47]}, {24: [1, 72]}, {
7: [1, 73],
24: [2, 8]
}, {27: [1, 74]}, {24: [1, 75]}, {7: [1, 76], 24: [2, 5]}, {12: 77, 49: 78, 50: [1, 79], 52: [1, 46]}, {
12: 80,
49: 78,
50: [1, 79],
52: [1, 46]
}, {24: [1, 81]}, {5: [2, 33], 7: [2, 33], 24: [2, 33], 27: [2, 33], 35: 82, 39: [2, 33], 43: [1, 83]}, {
12: 85,
37: 84,
49: 78,
50: [1, 79],
52: [1, 46]
}, {5: [2, 38], 7: [2, 38], 24: [2, 38], 27: [2, 38], 39: [2, 38], 41: [2, 38], 43: [2, 38]}, {
5: [2, 67],
7: [2, 67],
24: [2, 67],
27: [2, 67],
38: [2, 67],
39: [2, 67],
41: [2, 67],
43: [2, 67],
46: [2, 67]
}, {
20: [1, 43],
23: [1, 48],
26: [1, 20],
40: 41,
45: 42,
47: 86,
48: 40,
49: 39,
52: [1, 46],
53: [1, 47],
54: 37,
55: 38,
56: [1, 44],
57: [1, 45]
}, {
5: [2, 61],
7: [2, 61],
24: [2, 61],
27: [2, 61],
38: [2, 61],
39: [2, 61],
41: [2, 61],
43: [2, 61]
}, {24: [1, 87], 38: [1, 88]}, {24: [2, 64], 38: [2, 64]}, {61: [1, 89]}, {
24: [1, 91],
48: 90,
53: [1, 47]
}, {24: [1, 92]}, {
5: [2, 43],
7: [2, 43],
24: [2, 43],
26: [2, 43],
27: [2, 43],
39: [2, 43],
41: [2, 43],
43: [2, 43],
46: [2, 43],
50: [2, 43],
51: [2, 43],
52: [2, 43]
}, {
5: [2, 35],
7: [2, 35],
23: [2, 35],
24: [2, 35],
25: 93,
26: [2, 35],
27: [2, 35],
39: [2, 35],
41: [2, 35],
43: [2, 35],
44: [1, 94],
46: [2, 35],
50: [2, 35],
52: [2, 35]
}, {
6: 53,
10: 95,
11: 4,
14: 5,
16: [1, 6],
18: [1, 7],
19: [1, 8],
20: [1, 9],
21: [1, 10],
22: [1, 11],
24: [2, 9],
28: [1, 12],
29: [1, 13],
30: [1, 14]
}, {
5: [2, 35],
7: [2, 35],
23: [2, 35],
24: [2, 35],
25: 96,
26: [2, 35],
27: [2, 35],
39: [2, 35],
41: [2, 35],
43: [2, 35],
44: [1, 94],
46: [2, 35],
50: [2, 35],
52: [2, 35]
}, {
5: [2, 35],
7: [2, 35],
24: [2, 35],
25: 97,
26: [2, 35],
27: [2, 35],
39: [2, 35],
41: [2, 35],
43: [2, 35],
44: [1, 94],
46: [2, 35],
50: [2, 35],
52: [2, 35]
}, {
8: 98,
9: 56,
11: 57,
14: 58,
16: [1, 6],
18: [1, 7],
19: [1, 8],
20: [1, 9],
21: [1, 10],
22: [1, 11],
24: [2, 6],
28: [1, 12],
29: [1, 13],
30: [1, 14]
}, {
7: [2, 37],
13: 99,
24: [2, 37],
26: [1, 20],
32: 18,
39: [2, 37],
41: [2, 37],
43: [2, 37],
45: 19,
46: [2, 37]
}, {
7: [2, 45],
24: [2, 45],
26: [2, 45],
38: [2, 45],
39: [2, 45],
41: [2, 45],
42: [2, 45],
43: [2, 45],
46: [2, 45],
51: [2, 45]
}, {
7: [2, 46],
24: [2, 46],
26: [2, 46],
38: [2, 46],
39: [2, 46],
41: [2, 46],
42: [2, 46],
43: [2, 46],
46: [2, 46],
51: [2, 46]
}, {
7: [2, 48],
15: 100,
24: [2, 48],
26: [2, 48],
31: 22,
39: [2, 48],
41: [2, 48],
43: [2, 48],
46: [2, 48],
51: [1, 23]
}, {
5: [2, 22],
7: [2, 22],
24: [2, 22],
26: [2, 22],
27: [2, 22],
39: [2, 22],
41: [2, 22],
43: [2, 22],
46: [2, 22],
50: [2, 22],
52: [2, 22]
}, {5: [2, 29], 7: [2, 29], 24: [2, 29], 27: [2, 29], 36: 101, 39: [1, 102]}, {
5: [2, 32],
7: [2, 32],
24: [2, 32],
27: [2, 32],
39: [2, 32]
}, {38: [1, 104], 42: [1, 103]}, {38: [2, 27], 42: [2, 27]}, {27: [2, 69], 38: [2, 69]}, {
5: [2, 62],
7: [2, 62],
24: [2, 62],
27: [2, 62],
38: [2, 62],
39: [2, 62],
41: [2, 62],
43: [2, 62]
}, {49: 68, 52: [1, 46], 60: 105}, {
20: [1, 43],
23: [1, 48],
26: [1, 20],
40: 41,
45: 42,
47: 106,
48: 40,
49: 39,
52: [1, 46],
53: [1, 47],
54: 37,
55: 38,
56: [1, 44],
57: [1, 45]
}, {24: [1, 107]}, {
5: [2, 41],
7: [2, 41],
24: [2, 41],
26: [2, 41],
27: [2, 41],
39: [2, 41],
41: [2, 41],
43: [2, 41],
46: [2, 41],
50: [2, 41],
51: [2, 41],
52: [2, 41]
}, {
5: [2, 42],
7: [2, 42],
24: [2, 42],
26: [2, 42],
27: [2, 42],
39: [2, 42],
41: [2, 42],
43: [2, 42],
46: [2, 42],
50: [2, 42],
51: [2, 42],
52: [2, 42]
}, {
5: [2, 44],
7: [2, 44],
17: 108,
23: [1, 25],
24: [2, 44],
26: [2, 44],
27: [2, 44],
39: [2, 44],
41: [2, 44],
43: [2, 44],
46: [2, 44],
50: [2, 44],
52: [2, 44]
}, {
5: [2, 34],
7: [2, 34],
23: [2, 34],
24: [2, 34],
26: [2, 34],
27: [2, 34],
39: [2, 34],
41: [2, 34],
43: [2, 34],
46: [2, 34],
50: [2, 34],
52: [2, 34]
}, {24: [2, 7]}, {
5: [2, 44],
7: [2, 44],
17: 109,
23: [1, 25],
24: [2, 44],
26: [2, 44],
27: [2, 44],
39: [2, 44],
41: [2, 44],
43: [2, 44],
46: [2, 44],
50: [2, 44],
52: [2, 44]
}, {
5: [2, 21],
7: [2, 21],
24: [2, 21],
26: [2, 21],
27: [2, 21],
39: [2, 21],
41: [2, 21],
43: [2, 21],
46: [2, 21],
50: [2, 21],
52: [2, 21]
}, {24: [2, 4]}, {7: [2, 10], 24: [2, 10]}, {7: [2, 11], 24: [2, 11]}, {
5: [2, 25],
7: [2, 25],
24: [2, 25],
27: [2, 25]
}, {23: [1, 48], 40: 110}, {
5: [2, 30],
7: [2, 30],
24: [2, 30],
27: [2, 30],
39: [2, 30],
43: [2, 30]
}, {12: 111, 49: 78, 50: [1, 79], 52: [1, 46]}, {24: [2, 65], 38: [2, 65]}, {
24: [2, 63],
38: [2, 63]
}, {
5: [2, 40],
7: [2, 40],
24: [2, 40],
26: [2, 40],
27: [2, 40],
39: [2, 40],
41: [2, 40],
43: [2, 40],
46: [2, 40],
50: [2, 40],
51: [2, 40],
52: [2, 40]
}, {
5: [2, 19],
7: [2, 19],
24: [2, 19],
26: [2, 19],
27: [2, 19],
39: [2, 19],
41: [2, 19],
43: [2, 19],
46: [2, 19],
50: [2, 19],
52: [2, 19]
}, {
5: [2, 20],
7: [2, 20],
24: [2, 20],
26: [2, 20],
27: [2, 20],
39: [2, 20],
41: [2, 20],
43: [2, 20],
46: [2, 20],
50: [2, 20],
52: [2, 20]
}, {39: [1, 112]}, {38: [2, 26], 42: [2, 26]}, {5: [2, 28], 7: [2, 28], 24: [2, 28], 27: [2, 28]}],
defaultActions: {15: [2, 1], 16: [2, 2], 95: [2, 7], 98: [2, 4]},
parseError: function (a, b) {
throw new Error (a)
},
parse: function (a) {
function o () {
var a;
a = b.lexer.lex () || 1, typeof a != "number" && (a = b.symbols_[a] || a);
return a
}
function n (a) {
c.length = c.length - 2 * a, d.length = d.length - a, e.length = e.length - a
}
var b = this, c = [0], d = [null], e = [], f = this.table, g = "", h = 0, i = 0, j = 0, k = 2, l = 1;
this.lexer.setInput (a), this.lexer.yy = this.yy, this.yy.lexer = this.lexer, typeof this.lexer.yylloc == "undefined" && (this.lexer.yylloc = {});
var m = this.lexer.yylloc;
e.push (m), typeof this.yy.parseError == "function" && (this.parseError = this.yy.parseError);
var p, q, r, s, t, u, v = {}, w, x, y, z;
for (; ;) {
r = c[c.length - 1], this.defaultActions[r] ? s = this.defaultActions[r] : (p == null && (p = o ()), s = f[r] && f[r][p]);
if (typeof s == "undefined" || !s.length || !s[0]) {
if (!j) {
z = [];
for (w in f[r])this.terminals_[w] && w > 2 && z.push ("'" + this.terminals_[w] + "'");
var A = "";
this.lexer.showPosition ? A = "Parse error on line " + (h + 1) + ":\n" + this.lexer.showPosition () + "\nExpecting " + z.join (", ") : A = "Parse error on line " + (h + 1) + ": Unexpected " + (p == 1 ? "end of input" : "'" + (this.terminals_[p] || p) + "'"), this.parseError (A, {
text: this.lexer.match,
token: this.terminals_[p] || p,
line: this.lexer.yylineno,
loc: m,
expected: z
})
}
if (j == 3) {
if (p == l)throw new Error (A || "Parsing halted.");
i = this.lexer.yyleng, g = this.lexer.yytext, h = this.lexer.yylineno, m = this.lexer.yylloc, p = o ()
}
for (; ;) {
if (k.toString () in f[r])break;
if (r == 0)throw new Error (A || "Parsing halted.");
n (1), r = c[c.length - 1]
}
q = p, p = k, r = c[c.length - 1], s = f[r] && f[r][k], j = 3
}
if (s[0] instanceof Array && s.length > 1)throw new Error ("Parse Error: multiple actions possible at state: " + r + ", token: " + p);
switch (s[0]) {
case 1:
c.push (p), d.push (this.lexer.yytext), e.push (this.lexer.yylloc), c.push (s[1]), p = null, q ? (p = q, q = null) : (i = this.lexer.yyleng, g = this.lexer.yytext, h = this.lexer.yylineno, m = this.lexer.yylloc, j > 0 && j--);
break;
case 2:
x = this.productions_[s[1]][1], v.$ = d[d.length - x], v._$ = {
first_line: e[e.length - (x || 1)].first_line,
last_line: e[e.length - 1].last_line,
first_column: e[e.length - (x || 1)].first_column,
last_column: e[e.length - 1].last_column
}, u = this.performAction.call (v, g, i, h, this.yy, s[1], d, e);
if (typeof u != "undefined")return u;
x && (c = c.slice (0, -1 * x * 2), d = d.slice (0, -1 * x), e = e.slice (0, -1 * x)), c.push (this.productions_[s[1]][0]), d.push (v.$), e.push (v._$), y = f[c[c.length - 2]][c[c.length - 1]], c.push (y);
break;
case 3:
return !0
}
}
return !0
}
}, f = function () {
var a = {
EOF: 1, parseError: function (a, b) {
if (this.yy.parseError)this.yy.parseError (a, b); else throw new Error (a)
}, setInput: function (a) {
this._input = a, this._more = this._less = this.done = !1, this.yylineno = this.yyleng = 0, this.yytext = this.matched = this.match = "", this.conditionStack = ["INITIAL"], this.yylloc = {
first_line: 1,
first_column: 0,
last_line: 1,
last_column: 0
};
return this
}, input: function () {
var a = this._input[0];
this.yytext += a, this.yyleng++, this.match += a, this.matched += a;
var b = a.match (/\n/);
b && this.yylineno++, this._input = this._input.slice (1);
return a
}, unput: function (a) {
this._input = a + this._input;
return this
}, more: function () {
this._more = !0;
return this
}, pastInput: function () {
var a = this.matched.substr (0, this.matched.length - this.match.length);
return (a.length > 20 ? "..." : "") + a.substr (-20).replace (/\n/g, "")
}, upcomingInput: function () {
var a = this.match;
a.length < 20 && (a += this._input.substr (0, 20 - a.length));
return (a.substr (0, 20) + (a.length > 20 ? "..." : "")).replace (/\n/g, "")
}, showPosition: function () {
var a = this.pastInput (), b = Array (a.length + 1).join ("-");
return a + this.upcomingInput () + "\n" + b + "^"
}, next: function () {
if (this.done)return this.EOF;
this._input || (this.done = !0);
var a, b, c, d;
this._more || (this.yytext = "", this.match = "");
var e = this._currentRules ();
for (var f = 0; f < e.length; f++) {
b = this._input.match (this.rules[e[f]]);
if (b) {
d = b[0].match (/\n.*/g), d && (this.yylineno += d.length), this.yylloc = {
first_line: this.yylloc.last_line,
last_line: this.yylineno + 1,
first_column: this.yylloc.last_column,
last_column: d ? d[d.length - 1].length - 1 : this.yylloc.last_column + b[0].length
}, this.yytext += b[0], this.match += b[0], this.matches = b, this.yyleng = this.yytext.length, this._more = !1, this._input = this._input.slice (b[0].length), this.matched += b[0], a = this.performAction.call (this, this.yy, this, e[f], this.conditionStack[this.conditionStack.length - 1]);
if (a)return a;
return
}
}
if (this._input === "")return this.EOF;
this.parseError ("Lexical error on line " + (this.yylineno + 1) + ". Unrecognized text.\n" + this.showPosition (), {
text: "",
token: null,
line: this.yylineno
})
}, lex: function () {
var a = this.next ();
return typeof a != "undefined" ? a : this.lex ()
}, begin: function (a) {
this.conditionStack.push (a)
}, popState: function () {
return this.conditionStack.pop ()
}, _currentRules: function () {
return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules
}
};
a.performAction = function (a, b, c, d) {
var e = d;
switch (c) {
case 0:
break;
case 1:
break;
case 2:
break;
case 3:
return 7;
case 4:
return 38;
case 5:
return 23;
case 6:
return 24;
case 7:
return 26;
case 8:
return 27;
case 9:
return 39;
case 10:
return 41;
case 11:
return 42;
case 12:
return 61;
case 13:
return 28;
case 14:
return 16;
case 15:
return 18;
case 16:
return 20;
case 17:
return 19;
case 18:
return 21;
case 19:
return 22;
case 20:
return 29;
case 21:
return 30;
case 22:
return 56;
case 23:
return 57;
case 24:
b.yytext = b.yytext.substr (1, b.yyleng - 2);
return 52;
case 25:
return 53;
case 26:
return 50;
case 27:
return 43;
case 28:
return 44;
case 29:
return 46;
case 30:
return 51;
case 31:
return 5
}
}, a.rules = [/^\s+/, /^\/\/[^\n]*/, /^#[^\n]*/, /^;/, /^,/, /^\{/, /^\}/, /^\[/, /^\]/, /^`/, /^</, /^>/, /^:/, /^object\b/, /^integer\b/, /^number\b/, /^null\b/, /^boolean\b/, /^any\b/, /^array\b/, /^union\b/, /^string\b/, /^true\b/, /^false\b/, /^"(?:\\["bfnrt/\\]|\\u[a-fA-F0-9]{4}|[^"\\])*"/, /^-?(?:[0-9]|[1-9][0-9]+)(?:\.[0-9]+)?(?:[eE][-+]?[0-9]+)?\b/, /^[A-Za-z_0-9-]+/, /^\?/, /^\*/, /^=/, /^\/(?:[^\/]|\\\/)*\//, /^$/], a.conditions = {
INITIAL: {
rules: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31],
inclusive: !0
}
};
return a
} ();
a.lexer = f;
return a
} ();
typeof a != "undefined" && typeof b != "undefined" && (b.parser = d, b.parse = function () {
return d.parse.apply (d, arguments)
}, b.main = function (c) {
if (!c[1])throw new Error ("Usage: " + c[0] + " FILE");
if (typeof process != "undefined")var d = a ("fs").readFileSync (a ("path").join (process.cwd (), c[1]), "utf8"); else var e = a ("file").path (a ("file").cwd ()), d = e.join (c[1]).read ({charset: "utf-8"});
return b.parser.parse (d)
}, typeof c != "undefined" && a.main === c && b.main (typeof process != "undefined" ? process.argv.slice (1) : a ("system").args))
}, requires: ["fs", "path", "file", "file", "system"]
}), a.def ("scope", {
factory: function (a, b, c) {
if (typeof a != "undefined")var d = b; else var d = parser.yy;
d.NOVALUE = {}, d.Type = function () {
return this.init.apply (this, arguments)
}, d.Type.prototype = {
init: function (a, b, c, d) {
this.json = {}, this.json.type = a;
if (a instanceof Array && a.length < 2)throw new Error ("must have at least two members in a union");
b && this.addRange (b), c && (this.addEntries (c), !d && (c.length || c.type) && (this.json.additionalProperties = !1));
return this.json
}, addEntries: function (a) {
if (this.json.type !== "array" || a instanceof Array && !(a.length > 0)) {
if (a.length) {
this.json.properties = {};
for (var b = 0; b < a.length; b++)this.json.properties[a[b][0]] = a[b][1]
}
} else this.json.items = a
}, addRange: function (a) {
var b = this.json.type === "array" ? "Items" : this.json.type === "string" ? "Length" : "imum";
a[0] !== null && (this.json["min" + b] = a[0]), a[1] !== null && (this.json["max" + b] = a[1])
}
}, d.Type.addOptionals = function (a, b) {
if (b.extras) {
var c;
for (c in b.extras)b.extras.hasOwnProperty (c) && (a[c] = b.extras[c])
}
b.optional && (a.optional = !0), b.enums && (a["enum"] = b.enums), b.requires && (a.requires = b.requires.length > 1 ? b.requires : b.requires[0]), b.defaultv !== d.NOVALUE && (a["default"] = b.defaultv), b.pattern && (a.pattern = b.pattern)
}
}, requires: []
});
return a ("orderly")
} () |
export default () => (
<div className="footer">
<div className="widgets">
<iframe src="https://ghbtns.com/github-btn.html?user=getbem&repo=getbem.com&type=star&count=true&size=large" frameBorder="0" scrolling="0" width="130px" height="30px"></iframe>
</div>
<br/>
<p>Brought to you by <a href="https://github.com/floatdrop">@floatdrop</a> and <a href="https://twitter.com/iamstarkov">@iamstarkov</a>.
<br/>
Maintained by the <a href="https://github.com/orgs/getbem/people">core team</a> with the help of our <a href="https://github.com/getbem/getbem.com/graphs/contributors">contributors</a>.<br/>
Code licensed under <a href="https://github.com/getbem/getbem.com/blob/master/LICENSE.md">MIT</a>, documentation under <a href="https://github.com/getbem/getbem.com/blob/master/src/markdown/LICENSE.md">CC BY 3.0</a>.</p>
<br/>
<ul className="footer__links">
<li><a href="https://twitter.com/getbem">Twitter</a></li>
<li><a href="https://github.com/getbem/getbem.com/">GitHub</a></li>
<li><a href="https://github.com/getbem/getbem.com/issues">Issues</a></li>
<li><a href="https://github.com/getbem/getbem.com/issues/8">Project goals</a></li>
<li><a href="https://github.com/getbem/getbem.com/issues/1">Are you using BEM?</a></li>
</ul>
</div>
);
|
var exec = require('child_process').exec;
var curl = require('node-curl');
var fs = require('fs');
var regenerate = require('regenerate');
var parseLine = function (line) {
if (line.indexOf('#') < 1) {
return null;
}
var category = line.match(/# ([A-Z][a-z&])/)[1];
var fields = line.replace(/#.*/, '').trim().split(';');
return {
codePoint: fields[0],
Line_Break: fields[1],
category: category
};
}
var addCodePoint = function (regenerate, codePoint) {
if (codePoint.indexOf('..') > 0) {
var range = codePoint.split('..');
regenerate.addRange(parseInt(range[0], 16), parseInt(range[1], 16));
} else {
regenerate.add(parseInt(codePoint, 16));
}
}
module.exports = function (grunt) {
grunt.registerTask('default', 'Build the library', function () {
grunt.log.write("Building dist/");
exec("rm -rf dist");
exec("broccoli build dist");
});
grunt.registerTask('update-character-map', 'Pull character map from unicode.org', function () {
var done = this.async();
grunt.log.write("Fetching LineBreak.txt from unicode.org\n");
curl('http://www.unicode.org/Public/UNIDATA/LineBreak.txt', function (err) {
grunt.log.write("Fetched LineBreak.txt\n");
grunt.log.write("Parsing code points\n");
var lines = this.body.split('\n');
var softWrapOpportunities = regenerate(0x0020, 0x0009, 0x002D); // Spaces, Tabs, and Hyphens
var Line_Break = {
CJ: regenerate(),
IN: regenerate(),
};
var Category = {
Sc: regenerate()
};
var header = [];
lines.forEach(function (line) {
if (header.length < 2) {
header.push(line.replace('#', '//'));
}
line = parseLine(line);
if (line) {
switch (line.Line_Break) {
case 'CJ':
addCodePoint(Line_Break.CJ, line.codePoint);
break;
case 'In':
addCodePoint(Line_Break.In, line.codePoint);
break;
case 'WJ':
case 'ZW':
case 'GL':
addCodePoint(softWrapOpportunities, line.codePoint);
break;
}
if (line.Category === 'Sc') {
addCodePoint(Category.Sc, line.codePoint);
}
}
});
grunt.log.write("Parsed code points. Creating regexes...\n");
var normalBreak = softWrapOpportunities.clone();
// Breaks before Japanese small kana or
// the Katakana-Hirigana prolonged sound mark
normalBreak.add(Line_Break.CJ.toArray());
// If the content language is Chinese or Japanese,
// then additionally allow
var cjkNormalBreak = normalBreak.clone();
// breaks before hyphens
cjkNormalBreak.add(0x2010, 0x2013, 0x301C, 0x30A0);
var looseBreak = normalBreak.clone();
var cjkLooseBreak = cjkNormalBreak.clone();
// breaks before iteration marks
looseBreak.add(0x3005, 0x303B, 0x309D, 0x309E, 0x30FD, 0x30FE);
cjkLooseBreak.add(0x3005, 0x303B, 0x309D, 0x309E, 0x30FD, 0x30FE);
// breaks between inseparable characters
looseBreak.add(Line_Break.IN.toArray());
cjkLooseBreak.add(Line_Break.IN.toArray());
// breaks before certain centered punctuation marks:
cjkLooseBreak.add(0x003A, 0x003B, 0x30FB, 0xFF1A, 0xFF1B, 0xFF65, 0x0021, 0x003F, 0x203C, 0x2047, 0x2048, 0x2049, 0xFF01, 0xFF1F);
// breaks before suffixes:
cjkLooseBreak.add(0x0025, 0x00A2, 0x00B0, 0x2030, 0x2032, 0x2033, 0x2103, 0xFF05, 0xFFE0);
// breaks after prefixes:
// № U+2116
cjkLooseBreak.add(0x2116);
// and all currency symbols (Unicode general category Sc) other than ¢ U+00A2 and ¢ U+FFE0
cjkLooseBreak.add(Category.Sc.remove(0x00A2, 0xFFE0).toArray());
grunt.log.write("Parsed code points");
fs.readFile('./blueprints/css.js', function (err, data) {
fs.writeFile("./lib/truncate/css.js", data.toString()
.replace("{{HEADER}}", header.join('\n'))
.replace("{{STRICT}}", softWrapOpportunities.toString())
.replace("{{NORMAL}}", normalBreak.toString())
.replace("{{CJK_NORMAL}}", cjkNormalBreak.toString())
.replace("{{LOOSE}}", looseBreak.toString())
.replace("{{CJK_LOOSE}}", cjkLooseBreak.toString()));
done();
});
});
});
};
|
import styles from './header.css'
import HeaderService from './header.service'
import userSection from './user-section/user-section.component'
import navigation from './navigation/navigation.component'
export default window.angular
.module('header', [userSection.name, navigation.name, 'ui.router'])
.service('HeaderService', HeaderService)
.component('header', {
bindings: {
},
controller: class HeaderCtrl {
constructor (HeaderService, AuthService, $state) {
'ngInject'
this.Auth = AuthService
this.Header = HeaderService
this.state = {
brand: 'Angular Component-based'
}
this.state.menu = this.Header.getMenu()
this.$state = $state
}
$onInit () {
console.log('Header Initialized')
this.Auth.restoreSessionFromToken().then((user) => {
this.state.user = user
})
}
$onDestroy () {
console.log('Header Destroyed')
// Clean $postLink DOM event listeners
}
onLogout () {
this.Auth.logout()
this.$state.go('home')
}
onLogin ($event) {
this.Auth.login($event).then(user => {
this.state.user = user
})
}
},
template: `
<div class="${styles.header}">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">{{ $ctrl.state.brand }}</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<navigation items="$ctrl.state.menu"></navigation>
<user-section user="$ctrl.state.user" on-logout="$ctrl.onLogout($event)" on-login="$ctrl.onLogin($event)"></user-section>
</div>
</div>
</nav>
</div>
`
})
|
/**
* Init wrapper for the core module.
* @param {Object} The Object that the library gets attached to in library.init.js. If the library was not loaded with an AMD loader such as require.js, this is the global Object.
*/
function initVlilleCore(context) {
'use strict';
/**
* @constructor
* @param {Object} opt_config [description]
* @return {Vlille} [description]
*/
function Vlille(opt_config) {
// enforces new
if (!(this instanceof Vlille)) {
return new Vlille(opt_config);
}
opt_config = opt_config || {};
if (!opt_config.apiProxyUrl) {
throw new Error('You have to provide a proxy URL.');
}
this.apiProxyBase = opt_config.apiProxyUrl.substr(-1) === '/' ? opt_config.apiProxyUrl : opt_config.apiProxyUrl + '/';
return this;
}
context.Vlille = Vlille;
/**
* Privates
*/
/**
*
* @param {Document} xml [description]
* @return {Object} [description]
*/
function xmlStationsToJson(xml) {
var i,
j,
len,
len2,
markers = xml.childNodes[0].children || [],
attributes,
jsonMarker,
jsonArray = [];
// imperative way
for (i = 0, len = markers.length; i < len; i += 1) {
jsonMarker = {};
attributes = markers[i].attributes;
for (j = 0, len2 = attributes.length; j < len2; j += 1) {
jsonMarker[attributes[j].name] = attributes[j].value;
}
jsonArray.push(jsonMarker);
}
return jsonArray;
}
/**
*
* @param {Document} xmlNode [description]
* @return {Object} [description]
*/
function xmlStationToJson(xml) {
var i,
len,
stationData = xml.childNodes[0].children || [],
jsonStation = {};
for (i = 0, len = stationData.length; i < len; i += 1) {
jsonStation[stationData[i].nodeName] = stationData[i].innerHTML;
}
return jsonStation;
}
/**
* Publics
*/
/**
* Gets full stations list.
* @return {Promise} [description]
*/
Vlille.prototype.stations = function () {
return Vlille.requestXML(this.apiProxyBase + 'xml-stations.aspx', null).then(function (xml) {
return xmlStationsToJson(xml);
});
};
/**
* Gets informations about the station whit the given `id`.
* @param {String} id [description]
* @return {Promise} [description]
*/
Vlille.prototype.station = function (id) {
var params = {
borne: id
};
return Vlille.requestXML(this.apiProxyBase + 'xml-station.aspx', params).then(function (xml) {
return xmlStationToJson(xml);
});
};
/**
* Gets closest stations using Haversine formula.
* The second parameter `max` (default value = 3) allow one to configure the maximum number of results.
* @param {Object} coord [description]
* @param {Int} max [description]
* @return {Promise} [description]
*/
Vlille.prototype.closestStations = function (coords, max) {
if (max === undefined) {
max = 3;
}
return this.stations().then(function (stations) {
var closetStations = stations
// computes distances
.map(function (station) {
var stationCoords = {
lat: parseFloat(station.lat),
lon: parseFloat(station.lng)
};
station.distance = Vlille.haversineDistance(coords, stationCoords);
return station;
})
// sort by distance
.sort(function (a, b) {
return a.distance - b.distance;
});
if (closetStations.length > max) {
closetStations.length = max;
}
return closetStations;
});
};
} |
// external dependencies
const bPromise = require('bluebird');
// internal dependencies
const PsmImagePicker = require('../image-picker');
// logic
exports = module.exports = function(filePath) {
var imageDictionary;
// try parsing the input file
try {
imageDictionary = require(filePath);
} catch (error) {
return bPromise.reject(new Error('Invalid input file format'));
}
return bPromise.resolve(new PsmImagePicker(imageDictionary));
};
|
'use strict';
var cssom = require('cssom'),
os = require('os');
/**
* Returns Media Query text for a CSS source.
*
* @param {String} css source
* @api public
*/
module.exports = function (css) {
var rules = cssom.parse(css).cssRules || [];
var queries = [];
for (var i = 0, l = rules.length; i < l; i++) {
/* CSS types
STYLE: 1,
IMPORT: 3,
MEDIA: 4,
FONT_FACE: 5,
*/
if (rules[i].type === cssom.CSSMediaRule.prototype.type) {
var query = rules[i];
var queryString = [];
queryString.push(os.EOL + '@media ' + query.media[0] + ' {');
for (var ii = 0, ll = query.cssRules.length; ii < ll; ii++) {
var rule = query.cssRules[ii];
if (rule.type === cssom.CSSStyleRule.prototype.type || rule.type === cssom.CSSFontFaceRule.prototype.type) {
queryString.push(' ' + (rule.type === cssom.CSSStyleRule.prototype.type ? rule.selectorText : '@font-face') + ' {');
for (var style = 0; style < rule.style.length; style++) {
var property = rule.style[style];
var value = rule.style[property];
var important = rule.style._importants[property] ? ' !important' : '';
queryString.push(' ' + property + ': ' + value + important + ';');
}
queryString.push(' }');
}
}
queryString.push('}');
var result = queryString.length ? queryString.join(os.EOL) + os.EOL : '';
queries.push(result);
}
}
return queries.join(os.EOL);
};
|
/**
* @fileoverview Prevent missing displayName in a React component definition
* @author Yannick Croissant
*/
'use strict';
const Components = require('../util/Components');
const astUtil = require('../util/ast');
const docsUrl = require('../util/docsUrl');
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: 'Prevent missing displayName in a React component definition',
category: 'Best Practices',
recommended: true,
url: docsUrl('display-name')
},
schema: [{
type: 'object',
properties: {
ignoreTranspilerName: {
type: 'boolean'
}
},
additionalProperties: false
}]
},
create: Components.detect((context, components, utils) => {
const config = context.options[0] || {};
const ignoreTranspilerName = config.ignoreTranspilerName || false;
const MISSING_MESSAGE = 'Component definition is missing display name';
/**
* Checks if we are declaring a display name
* @param {ASTNode} node The AST node being checked.
* @returns {Boolean} True if we are declaring a display name, false if not.
*/
function isDisplayNameDeclaration(node) {
switch (node.type) {
case 'ClassProperty':
return node.key && node.key.name === 'displayName';
case 'Identifier':
return node.name === 'displayName';
case 'Literal':
return node.value === 'displayName';
default:
return false;
}
}
/**
* Mark a prop type as declared
* @param {ASTNode} node The AST node being checked.
*/
function markDisplayNameAsDeclared(node) {
components.set(node, {
hasDisplayName: true
});
}
/**
* Reports missing display name for a given component
* @param {Object} component The component to process
*/
function reportMissingDisplayName(component) {
context.report({
node: component.node,
message: MISSING_MESSAGE,
data: {
component: component.name
}
});
}
/**
* Checks if the component have a name set by the transpiler
* @param {ASTNode} node The AST node being checked.
* @returns {Boolean} True if component has a name, false if not.
*/
function hasTranspilerName(node) {
const namedObjectAssignment = (
node.type === 'ObjectExpression' &&
node.parent &&
node.parent.parent &&
node.parent.parent.type === 'AssignmentExpression' &&
(
!node.parent.parent.left.object ||
node.parent.parent.left.object.name !== 'module' ||
node.parent.parent.left.property.name !== 'exports'
)
);
const namedObjectDeclaration = (
node.type === 'ObjectExpression' &&
node.parent &&
node.parent.parent &&
node.parent.parent.type === 'VariableDeclarator'
);
const namedClass = (
(node.type === 'ClassDeclaration' || node.type === 'ClassExpression') &&
node.id &&
node.id.name
);
const namedFunctionDeclaration = (
(node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression') &&
node.id &&
node.id.name
);
const namedFunctionExpression = (
astUtil.isFunctionLikeExpression(node) &&
node.parent &&
(node.parent.type === 'VariableDeclarator' || node.parent.method === true) &&
(!node.parent.parent || !utils.isES5Component(node.parent.parent))
);
if (
namedObjectAssignment || namedObjectDeclaration ||
namedClass ||
namedFunctionDeclaration || namedFunctionExpression
) {
return true;
}
return false;
}
// --------------------------------------------------------------------------
// Public
// --------------------------------------------------------------------------
return {
ClassProperty: function(node) {
if (!isDisplayNameDeclaration(node)) {
return;
}
markDisplayNameAsDeclared(node);
},
MemberExpression: function(node) {
if (!isDisplayNameDeclaration(node.property)) {
return;
}
const component = utils.getRelatedComponent(node);
if (!component) {
return;
}
markDisplayNameAsDeclared(component.node);
},
FunctionExpression: function(node) {
if (ignoreTranspilerName || !hasTranspilerName(node)) {
return;
}
markDisplayNameAsDeclared(node);
},
FunctionDeclaration: function(node) {
if (ignoreTranspilerName || !hasTranspilerName(node)) {
return;
}
markDisplayNameAsDeclared(node);
},
ArrowFunctionExpression: function(node) {
if (ignoreTranspilerName || !hasTranspilerName(node)) {
return;
}
markDisplayNameAsDeclared(node);
},
MethodDefinition: function(node) {
if (!isDisplayNameDeclaration(node.key)) {
return;
}
markDisplayNameAsDeclared(node);
},
ClassExpression: function(node) {
if (ignoreTranspilerName || !hasTranspilerName(node)) {
return;
}
markDisplayNameAsDeclared(node);
},
ClassDeclaration: function(node) {
if (ignoreTranspilerName || !hasTranspilerName(node)) {
return;
}
markDisplayNameAsDeclared(node);
},
ObjectExpression: function(node) {
if (ignoreTranspilerName || !hasTranspilerName(node)) {
// Search for the displayName declaration
node.properties.forEach(property => {
if (!property.key || !isDisplayNameDeclaration(property.key)) {
return;
}
markDisplayNameAsDeclared(node);
});
return;
}
markDisplayNameAsDeclared(node);
},
'Program:exit': function() {
const list = components.list();
// Report missing display name for all components
Object.keys(list).filter(component => !list[component].hasDisplayName).forEach(component => {
reportMissingDisplayName(list[component]);
});
}
};
})
};
|
$(function () {
var flag=true;
getDoctorInfo();
var userName;
//按钮发送消息 ------------------------------------------------
$("#send").click(function() {
var msg = $("#sendMsg").val();
if(msg=="" || msg==" " ||msg==null){//消息判断----------------
alert("消息不能为空");
return false;
}
//医生回复---------------------------------------------------------
$("#sendMsg").val("");//清空输入框----------------
JIM.sendSingleMsg({//发送单聊消息
'target_username' : userName ,
'target_nickname' : userName ,
'content' : msg ,
'appkey' : '7c2a0e6211914830a77efa41'
}).onSuccess(function(data) {
$("#ChatContent").empty();//清空聊天框-----------------------
console.log(data);
console.log("发送成功");
for(var i=0;i<Conversation.length;i++){//循环历史记录
var msgs=Conversation[i].msgs.length;
if(id==Conversation[i].key){//如果历史记录有当前点击用户的消息
if(msgs>99){//判断储存的历史消息条数,如果大于99条 就减去前面20条
Conversation[i].msgs.splice(0,20);
}
var content={'content':{'from_id':''+$.cookies.get("phone")+'','msg_body':{"text":msg}}};
Conversation[i].msgs.push(content);
for(var k=0;k<Conversation[i].msgs.length;k++){
if(Conversation[i].msgs[k].content.from_id==$.cookies.get("phone")){
$("#ChatContent").append('<div class="docterMsg"><img src="'+icon+'" class="doctoricon"/><span>'+Conversation[i].msgs[k].content.msg_body.text+'</span></div>');
}else {
$("#ChatContent").append('<div class="userMsg"><img src="imgs/server.jpg" class="usericon"/><span>'+Conversation[i].msgs[k].content.msg_body.text+'</span></div>');
}
}
break;
}else {
var content={messages:[{'content':{'msg_body':{"text":msg},'from_type':'doctor'},'from_uid':''+id+''}]};
msgContent.push(content);
for(var b=0;b<msgContent.length;b++){
if(id == msgContent[b].messages[0].from_uid){
if( msgContent[b].messages[0].content.from_type == "user"){
alert("用户");
$("#ChatContent").append('<div class="userMsg"><img src="imgs/server.jpg" class="usericon"/><span>'+msgContent[b].messages[0].content.msg_body.text+'</span></div>');
}
if(msgContent[b].messages[0].content.from_type == "doctor"){
alert("医生");
$("#ChatContent").append('<div class="docterMsg"><img src="'+icon+'" class="doctoricon"/><span>'+msgContent[b].messages[0].content.msg_body.text+'</span></div>');
}
}
}
break;
}
}
}).onFail(function(data) {
console.log("发送失败"+JSON.stringify(data));
});
});
//Ctrl+Enter发送消息---------------------------------------------
$("#sendMsg").keydown(function() {
if (event.ctrlKey && event.keyCode == 13) {//键盘事件
var msg = $("#sendMsg").val();
if(msg=="" || msg==" " ||msg==null){//消息判断----------------
alert("消息不能为空");
return false;
}
//医生回复---------------------------------------------------------
$("#sendMsg").val("");//清空输入框----------------
JIM.sendSingleMsg({//发送单聊消息
'target_username' : userName ,
'target_nickname' : userName ,
'content' : msg ,
'appkey' : '7c2a0e6211914830a77efa41'
}).onSuccess(function(data) {
$("#ChatContent").empty();//清空聊天框-----------------------
console.log("发送成功");
for(var i=0;i<Conversation.length;i++){//循环历史记录
var msgs=Conversation[i].msgs.length;
if(id==Conversation[i].key){//如果历史记录有当前点击用户的消息
if(msgs>99){//判断储存的历史消息条数,如果大于99条 就减去前面20条
Conversation[i].msgs.splice(0,20);
}
var content={'content':{'from_id':''+$.cookies.get("phone")+'','msg_body':{"text":msg}}};
Conversation[i].msgs.push(content);
for(var k=0;k<Conversation[i].msgs.length;k++){
if(Conversation[i].msgs[k].content.from_id==$.cookies.get("phone")){
$("#ChatContent").append('<div class="docterMsg"><img src="'+icon+'" class="doctoricon"/><span>'+Conversation[i].msgs[k].content.msg_body.text+'</span></div>');
}else {
$("#ChatContent").append('<div class="userMsg"><img src="imgs/server.jpg" class="usericon"/><span>'+Conversation[i].msgs[k].content.msg_body.text+'</span></div>');
}
}
break;
}else {
var content={messages:[{'content':{'msg_body':{"text":msg},'from_type':'doctor'},'from_uid':''+id+''}]};
msgContent.push(content);
for(var b=0;b<msgContent.length;b++){
if(id == msgContent[b].messages[0].from_uid){
if( msgContent[b].messages[0].content.from_type == "user"){
alert("用户");
$("#ChatContent").append('<div class="userMsg"><img src="imgs/server.jpg" class="usericon"/><span>'+msgContent[b].messages[0].content.msg_body.text+'</span></div>');
}
if(msgContent[b].messages[0].content.from_type == "doctor"){
alert("医生");
$("#ChatContent").append('<div class="docterMsg"><img src="'+icon+'" class="doctoricon"/><span>'+msgContent[b].messages[0].content.msg_body.text+'</span></div>');
}
}
}
break;
}
}
}).onFail(function(data) {
console.log("发送失败"+JSON.stringify(data));
});
}
});
//左边手风琴事件----------------------------------------------
$(".leftnav h2").click(function(){
$(this).next().slideToggle(200);
$(this).toggleClass("on");
});
$(".leftnav ul li a").click(function(){
$("#a_leader_txt").text($(this).text());
$(".leftnav ul li a").removeClass("on");
$(this).addClass("on");
});
//点击查看消息-----------------------------------------------
$(".user_tab").on("click","li",function (){
$("#dialog").css("display",'block');
$("#ChatContent").empty();
id=$(this).attr("id");
var text=$(this).children("span").text();
userName=text;
$(".username").text(text);
for(var i=0;i<Conversation.length;i++){
if(id==Conversation[i].key){
console.log("进历史");
for(var k=0;k<Conversation[i].msgs.length;k++){
if(Conversation[i].msgs[k].content.from_id==$.cookies.get("phone")){
$("#ChatContent").append('<div class="docterMsg"><img src="'+icon+'" class="doctoricon"/><span>'+Conversation[i].msgs[k].content.msg_body.text+'</span></div>');
}else {
$("#ChatContent").append('<div class="userMsg"><img src="imgs/server.jpg" class="usericon"/><span>'+Conversation[i].msgs[k].content.msg_body.text+'</span></div>');
}
}
return false;
}
}
for(var b=0;b<msgContent.length;b++){
console.log("进新用户");
if(id == msgContent[b].messages[0].from_uid){
if( msgContent[b].messages[0].content.from_type !== "doctor"){
$("#ChatContent").append('<div class="userMsg"><img src="imgs/server.jpg" class="usericon"/><span>'+msgContent[b].messages[0].content.msg_body.text+'</span></div>');
}else {
$("#ChatContent").append('<div class="docterMsg"><img src="'+icon+'" class="doctoricon"/><span>'+msgContent[b].messages[0].content.msg_body.text+'</span></div>');
}
}
}
});
//关闭对话框------------------------------------------
$('.close').click(function(){
$('#dialog').css('display','none');
var user_li=$(".user_tab>li");
for(var i=0;i<user_li.length;i++){
if(user_li.eq(i).attr("id")==id){
user_li.eq(i).remove();
}
}
});
function getDoctorInfo() {
var iphone=$.cookies.get("phone");
var docId;
///获取医生信息------------------------------------
if(iphone!==null&&iphone!==undefined){
$.ajax({
url: serUrl+"doctor/getDocByPhone?phone="+iphone,
type: "post",
dataType: "json",
success:function(data){
icon=data.icon;
$.cookies.set("icon", data.icon);
docId=data.id;
$(".information").html($(".information").html() + "<img src=" + data.icon +" />" + "<div class='section'>"+"<p>"+data.name + "</p>"+"<p>" +data.section + "</p>"+"</div>");
if(data.id){
$.cookies.set("id", data.id);
}
var doctorId = $.cookies.get("id");
}
});
}
}
});
|
(function(){$(function(){return ko.bindingHandlers.immybox_choices={init:function(i,o,a){var n,e;n=ko.utils.unwrapObservable(o()),(e=ko.utils.unwrapObservable(a().immybox_options)||{}).choices=n,$(i).immybox(e),ko.utils.domNodeDisposal.addDisposeCallback(i,function(){$(i).immybox("destroy")})},update:function(i,o,a){var n,e;e=ko.utils.unwrapObservable(o()),$(i).immybox("setChoices",e),a.has("immybox_value")&&"function"==typeof(n=a.get("immybox_value")).valueHasMutated&&n.valueHasMutated()}},ko.bindingHandlers.immybox_value={init:function(i,o){var a;a=o(),$(i).on("update",function(i,o){a(o)})},update:function(i,o){var a;a=ko.utils.unwrapObservable(o()),$(i).immybox("setValue",a)}}})}).call(this); |
'use strict';
describe('Editor List and Entry', function () {
var constants = require('../../../../testConstants');
var loginPage = require('../../../../bellows/pages/loginPage.js');
var projectsPage = require('../../../../bellows/pages/projectsPage.js');
var util = require('../../../../bellows/pages/util.js');
var editorPage = require('../../pages/editorPage.js');
var editorUtil = require('../../pages/editorUtil.js');
var configPage = require('../../pages/configurationPage.js');
var viewSettingsPage = require('../../pages/viewSettingsPage.js');
it('setup: login, click on test project', function () {
loginPage.loginAsManager();
projectsPage.get();
projectsPage.clickOnProject(constants.testProjectName);
});
it('browse page has correct word count', function () {
expect(editorPage.browse.entriesList.count()).toEqual(editorPage.browse.getEntryCount());
expect(editorPage.browse.getEntryCount()).toBe(3);
});
it('search function works correctly', function () {
editorPage.browse.search.input.sendKeys('asparagus');
expect(editorPage.browse.search.getMatchCount()).toBe(1);
editorPage.browse.search.clearBtn.click();
});
it('refresh returns to list view', function () {
browser.refresh();
expect(editorPage.browse.getEntryCount()).toBe(3);
});
it('click on first word', function () {
editorPage.browse.findEntryByLexeme(constants.testEntry1.lexeme.th.value).click();
});
it('refresh returns to entry view', function () {
expect(editorPage.edit.getFirstLexeme()).toEqual(constants.testEntry1.lexeme.th.value);
browser.refresh();
expect(editorPage.edit.getFirstLexeme()).toEqual(constants.testEntry1.lexeme.th.value);
});
it('edit page has correct word count', function () {
expect(editorPage.edit.entriesList.count()).toEqual(editorPage.edit.getEntryCount());
expect(editorPage.edit.getEntryCount()).toBe(3);
});
it('word 1: edit page has correct definition, part of speech', function () {
expect(editorPage.edit.getFieldValues('Definition')).toEqual([
{ en: constants.testEntry1.senses[0].definition.en.value }
]);
expect(editorPage.edit.getFieldValues('Part of Speech')).toEqual([
editorUtil.expandPartOfSpeech(constants.testEntry1.senses[0].partOfSpeech.value)
]);
});
it('dictionary citation reflects lexeme form', function () {
expect(editorPage.edit.renderedDiv.getText()).toContain(constants.testEntry1.lexeme.th.value);
expect(editorPage.edit.renderedDiv.getText())
.toContain(constants.testEntry1.lexeme['th-fonipa'].value);
expect(editorPage.edit.renderedDiv.getText()).not.toContain('citation form');
});
it('add citation form as visible field', function () {
configPage.get();
configPage.getTabByName('Fields').click();
configPage.showAllFieldsButton.click();
configPage.getFieldByName('Citation Form').click();
util.setCheckbox(configPage.hiddenIfEmpty, false);
configPage.applyButton.click();
util.clickBreadcrumb(constants.testProjectName);
editorPage.browse.findEntryByLexeme(constants.testEntry1.lexeme.th.value).click();
});
it('citation form field overrides lexeme form in dictionary citation view', function () {
editorPage.edit.showHiddenFields();
var citationFormMultiTextInputs = editorPage.edit.getMultiTextInputs('Citation Form');
editorPage.edit.selectElement.sendKeys(citationFormMultiTextInputs.first(), 'citation form');
expect(editorPage.edit.renderedDiv.getText()).toContain('citation form');
expect(editorPage.edit.renderedDiv.getText())
.not.toContain(constants.testEntry1.lexeme.th.value);
expect(editorPage.edit.renderedDiv.getText())
.toContain(constants.testEntry1.lexeme['th-fonipa'].value);
editorPage.edit.selectElement.clear(citationFormMultiTextInputs.first());
expect(editorPage.edit.renderedDiv.getText()).not.toContain('citation form');
expect(editorPage.edit.renderedDiv.getText()).toContain(constants.testEntry1.lexeme.th.value);
expect(editorPage.edit.renderedDiv.getText())
.toContain(constants.testEntry1.lexeme['th-fonipa'].value);
editorPage.edit.hideHiddenFields();
});
it('one picture and caption is present', function () {
expect(editorPage.edit.pictures.getFileName(0))
.toContain('_' + constants.testEntry1.senses[0].pictures[0].fileName);
expect(editorPage.edit.pictures.getCaption(0))
.toEqual({ en: constants.testEntry1.senses[0].pictures[0].caption.en.value });
});
it('file upload drop box is displayed when Add Picture is clicked', function () {
expect(editorPage.edit.pictures.addPictureLink.isPresent()).toBe(true);
expect(editorPage.edit.pictures.addDropBox.isDisplayed()).toBe(false);
expect(editorPage.edit.pictures.addCancelButton.isDisplayed()).toBe(false);
editorPage.edit.pictures.addPictureLink.click();
expect(editorPage.edit.pictures.addPictureLink.isPresent()).toBe(false);
expect(editorPage.edit.pictures.addDropBox.isDisplayed()).toBe(true);
});
it('file upload drop box is not displayed when Cancel Adding Picture is clicked', function () {
expect(editorPage.edit.pictures.addCancelButton.isDisplayed()).toBe(true);
editorPage.edit.pictures.addCancelButton.click();
expect(editorPage.edit.pictures.addPictureLink.isPresent()).toBe(true);
expect(editorPage.edit.pictures.addDropBox.isDisplayed()).toBe(false);
expect(editorPage.edit.pictures.addCancelButton.isDisplayed()).toBe(false);
});
it('change config to show Pictures and hide captions', function () {
configPage.get();
configPage.getTabByName('Fields').click();
configPage.showAllFieldsButton.click();
configPage.getFieldByName('Pictures').click();
util.setCheckbox(configPage.hiddenIfEmpty, false);
util.setCheckbox(configPage.captionHiddenIfEmpty(), true);
configPage.applyButton.click();
});
it('caption is hidden when empty if "Hidden if empty" is set in config', function () {
util.clickBreadcrumb(constants.testProjectName);
editorPage.browse.findEntryByLexeme(constants.testEntry1.lexeme.th.value).click();
editorPage.edit.hideHiddenFields();
expect(editorPage.edit.pictures.captions.first().isDisplayed()).toBe(true);
editorPage.edit.selectElement.clear(editorPage.edit.pictures.captions.first());
expect(editorPage.edit.pictures.captions.count()).toBe(0);
});
it('change config to show Pictures and show captions', function () {
configPage.get();
configPage.getTabByName('Fields').click();
configPage.showAllFieldsButton.click();
configPage.getFieldByName('Pictures').click();
util.setCheckbox(configPage.hiddenIfEmpty, false);
util.setCheckbox(configPage.captionHiddenIfEmpty(), false);
configPage.applyButton.click();
});
it('when caption is empty, it is visible if "Hidden if empty" is cleared in config', function () {
util.clickBreadcrumb(constants.testProjectName);
editorPage.browse.findEntryByLexeme(constants.testEntry1.lexeme.th.value).click();
expect(editorPage.edit.pictures.captions.first().isDisplayed()).toBe(true);
});
it('picture is removed when Delete is clicked', function () {
expect(editorPage.edit.pictures.images.first().isPresent()).toBe(true);
expect(editorPage.edit.pictures.removeImages.first().isPresent()).toBe(true);
editorPage.edit.pictures.removeImages.first().click();
util.clickModalButton('Delete Picture');
expect(editorPage.edit.pictures.images.count()).toBe(0);
});
it('change config to hide Pictures and hide captions', function () {
configPage.get();
configPage.getTabByName('Fields').click();
configPage.showAllFieldsButton.click();
configPage.getFieldByName('Pictures').click();
util.setCheckbox(configPage.hiddenIfEmpty, true);
util.setCheckbox(configPage.captionHiddenIfEmpty(), true);
configPage.applyButton.click();
});
it('while Show Hidden Fields has not been clicked, Pictures field is hidden', function () {
util.clickBreadcrumb(constants.testProjectName);
editorPage.browse.findEntryByLexeme(constants.testEntry1.lexeme.th.value).click();
expect(editorPage.edit.getFields('Pictures').count()).toBe(0);
editorPage.edit.showHiddenFields();
expect(editorPage.edit.pictures.list.isPresent()).toBe(true);
editorPage.edit.hideHiddenFields();
expect(editorPage.edit.getFields('Pictures').count()).toBe(0);
});
it('audio Input System is present, playable and has "more" control (manager)', function () {
expect(editorPage.edit.audio.playerIcons('Word').count()).toEqual(1);
expect(editorPage.edit.audio.playerIcons('Word').first().isDisplayed()).toBe(true);
expect(editorPage.edit.audio.playerIcons('Word').first().getAttribute('class'))
.toContain('fa-play');
expect(editorPage.edit.audio.players('Word').first().isDisplayed()).toBe(true);
expect(editorPage.edit.audio.players('Word').first().isEnabled()).toBe(true);
expect(editorPage.edit.audio.moreControls('Word').first().isDisplayed()).toBe(true);
expect(editorPage.edit.audio.moreControls('Word').first().isEnabled()).toBe(true);
expect(editorPage.edit.audio.uploadButtons('Word').first().isDisplayed()).toBe(false);
expect(editorPage.edit.audio.downloadButtons('Word').first().isDisplayed()).toBe(false);
});
it('file upload drop box is displayed when Upload is clicked', function () {
expect(editorPage.edit.audio.moreControls('Word').first().isDisplayed()).toBe(true);
expect(editorPage.edit.audio.uploadDropBoxes('Word').first().isDisplayed()).toBe(false);
expect(editorPage.edit.audio.uploadCancelButtons('Word').first().isDisplayed()).toBe(false);
editorPage.edit.audio.moreControls('Word').first().click();
editorPage.edit.audio.moreUpload('Word', 0).click();
expect(editorPage.edit.audio.moreControls('Word').first().isDisplayed()).toBe(false);
expect(editorPage.edit.audio.uploadDropBoxes('Word').first().isDisplayed()).toBe(true);
});
it('file upload drop box is not displayed when Cancel Uploading Audio is clicked', function () {
expect(editorPage.edit.audio.uploadCancelButtons('Word').first().isDisplayed()).toBe(true);
editorPage.edit.audio.uploadCancelButtons('Word').first().click();
expect(editorPage.edit.audio.moreControls('Word').first().isDisplayed()).toBe(true);
expect(editorPage.edit.audio.uploadDropBoxes('Word').first().isDisplayed()).toBe(false);
expect(editorPage.edit.audio.uploadCancelButtons('Word').first().isDisplayed()).toBe(false);
});
it('click on second word (found by definition)', function () {
editorPage.edit.findEntryByDefinition(constants.testEntry2.senses[0].definition.en.value)
.click();
});
it('word 2: audio Input System is not playable but has "upload" button (manager)', function () {
expect(editorPage.edit.audio.playerIcons('Word').first().isDisplayed()).toBe(false);
expect(editorPage.edit.audio.players('Word').first().isDisplayed()).toBe(false);
expect(editorPage.edit.audio.moreControls('Word').first().isDisplayed()).toBe(false);
expect(editorPage.edit.audio.uploadButtons('Word').first().isDisplayed()).toBe(true);
expect(editorPage.edit.audio.uploadButtons('Word').first().isEnabled()).toBe(true);
expect(editorPage.edit.audio.downloadButtons('Word').first().isDisplayed()).toBe(false);
});
it('login as member, click on first word', function () {
loginPage.loginAsMember();
projectsPage.get();
projectsPage.clickOnProject(constants.testProjectName);
editorPage.browse.findEntryByLexeme(constants.testEntry1.lexeme.th.value).click();
});
it('audio Input System is present, playable and has "more" control (member)', function () {
expect(editorPage.edit.audio.playerIcons('Word').count()).toEqual(1);
expect(editorPage.edit.audio.playerIcons('Word').first().isDisplayed()).toBe(true);
expect(editorPage.edit.audio.playerIcons('Word').first().getAttribute('class'))
.toContain('fa-play');
expect(editorPage.edit.audio.players('Word').first().isDisplayed()).toBe(true);
expect(editorPage.edit.audio.players('Word').first().isEnabled()).toBe(true);
expect(editorPage.edit.audio.moreControls('Word').first().isDisplayed()).toBe(true);
expect(editorPage.edit.audio.moreControls('Word').first().isEnabled()).toBe(true);
expect(editorPage.edit.audio.uploadButtons('Word').first().isDisplayed()).toBe(false);
expect(editorPage.edit.audio.downloadButtons('Word').first().isDisplayed()).toBe(false);
});
it('click on second word (found by definition)', function () {
editorPage.edit.findEntryByDefinition(constants.testEntry2.senses[0].definition.en.value)
.click();
});
it('word 2: audio Input System is not playable but has "upload" button (member)', function () {
expect(editorPage.edit.audio.playerIcons('Word').first().isDisplayed()).toBe(false);
expect(editorPage.edit.audio.players('Word').first().isDisplayed()).toBe(false);
expect(editorPage.edit.audio.moreControls('Word').first().isDisplayed()).toBe(false);
expect(editorPage.edit.audio.uploadButtons('Word').first().isDisplayed()).toBe(true);
expect(editorPage.edit.audio.uploadButtons('Word').first().isEnabled()).toBe(true);
expect(editorPage.edit.audio.downloadButtons('Word').first().isDisplayed()).toBe(false);
});
it('login as observer, click on first word', function () {
loginPage.loginAsObserver();
projectsPage.get();
projectsPage.clickOnProject(constants.testProjectName);
editorPage.browse.findEntryByLexeme(constants.testEntry1.lexeme.th.value).click();
});
it('audio Input System is playable but does not have "more" control (observer)', function () {
expect(editorPage.edit.audio.playerIcons('Word').count()).toEqual(1);
expect(editorPage.edit.audio.playerIcons('Word').first().isDisplayed()).toBe(true);
expect(editorPage.edit.audio.playerIcons('Word').first().getAttribute('class'))
.toContain('fa-play');
expect(editorPage.edit.audio.players('Word').first().isDisplayed()).toBe(true);
expect(editorPage.edit.audio.players('Word').first().isEnabled()).toBe(true);
expect(editorPage.edit.audio.moreControls('Word').first().isDisplayed()).toBe(false);
expect(editorPage.edit.audio.uploadButtons('Word').first().isDisplayed()).toBe(false);
expect(editorPage.edit.audio.downloadButtons('Word').first().isDisplayed()).toBe(true);
});
it('click on second word (found by definition)', function () {
editorPage.edit.findEntryByDefinition(constants.testEntry2.senses[0].definition.en.value)
.click();
});
it('word 2: audio Input System is not playable and does not have "upload" button (observer)',
function () {
expect(editorPage.edit.audio.playerIcons('Word').first().isDisplayed()).toBe(false);
expect(editorPage.edit.audio.players('Word').first().isDisplayed()).toBe(false);
expect(editorPage.edit.audio.moreControls('Word').first().isDisplayed()).toBe(false);
expect(editorPage.edit.audio.uploadButtons('Word').first().isDisplayed()).toBe(false);
expect(editorPage.edit.audio.downloadButtons('Word').first().isDisplayed()).toBe(false);
});
it('login as manager, click on first word', function () {
loginPage.loginAsManager();
projectsPage.get();
projectsPage.clickOnProject(constants.testProjectName);
editorPage.browse.findEntryByLexeme(constants.testEntry1.lexeme.th.value).click();
});
it('can delete audio Input System', function () {
expect(editorPage.edit.audio.moreControls('Word').first().isDisplayed()).toBe(true);
editorPage.edit.audio.moreControls('Word').first().click();
editorPage.edit.audio.moreDelete('Word', 0).click();
util.clickModalButton('Delete Audio');
expect(editorPage.edit.audio.uploadButtons('Word').first().isDisplayed()).toBe(true);
});
it('file upload drop box is displayed when Upload is clicked', function () {
expect(editorPage.edit.audio.uploadButtons('Word').first().isDisplayed()).toBe(true);
expect(editorPage.edit.audio.uploadDropBoxes('Word').first().isDisplayed()).toBe(false);
expect(editorPage.edit.audio.uploadCancelButtons('Word').first().isDisplayed()).toBe(false);
editorPage.edit.audio.uploadButtons('Word').first().click();
expect(editorPage.edit.audio.uploadButtons('Word').first().isDisplayed()).toBe(false);
expect(editorPage.edit.audio.uploadDropBoxes('Word').first().isDisplayed()).toBe(true);
});
it('file upload drop box is not displayed when Cancel Uploading Audio is clicked', function () {
expect(editorPage.edit.audio.uploadCancelButtons('Word').first().isDisplayed()).toBe(true);
editorPage.edit.audio.uploadCancelButtons('Word').first().click();
expect(editorPage.edit.audio.uploadButtons('Word').first().isDisplayed()).toBe(true);
expect(editorPage.edit.audio.uploadDropBoxes('Word').first().isDisplayed()).toBe(false);
expect(editorPage.edit.audio.uploadCancelButtons('Word').first().isDisplayed()).toBe(false);
});
describe('Mock file upload', function () {
it('can\'t upload a non-audio file', function () {
expect(editorPage.noticeList.count()).toBe(0);
editorPage.edit.audio.uploadButtons('Word').first().click();
editorPage.edit.audio.control('Word', 0).mockUpload.enableButton.click();
expect(editorPage.edit.audio.control('Word', 0).mockUpload.fileNameInput.isDisplayed())
.toBe(true);
editorPage.edit.audio.control('Word', 0).mockUpload.fileNameInput
.sendKeys(constants.testMockPngUploadFile.name);
editorPage.edit.audio.control('Word', 0).mockUpload.fileSizeInput
.sendKeys(constants.testMockPngUploadFile.size);
editorPage.edit.audio.control('Word', 0).mockUpload.uploadButton.click();
expect(editorPage.noticeList.count()).toBe(1);
expect(editorPage.noticeList.first().getText())
.toContain(constants.testMockPngUploadFile.name +
' is not an allowed audio file. Ensure the file is');
expect(editorPage.edit.audio.uploadDropBoxes('Word').first().isDisplayed()).toBe(true);
editorPage.edit.audio.control('Word', 0).mockUpload.fileNameInput.clear();
editorPage.edit.audio.control('Word', 0).mockUpload.fileSizeInput.clear();
editorPage.firstNoticeCloseButton.click();
});
it('can upload an audio file', function () {
expect(editorPage.noticeList.count()).toBe(0);
editorPage.edit.audio.control('Word', 0).mockUpload.fileNameInput
.sendKeys(constants.testMockMp3UploadFile.name);
editorPage.edit.audio.control('Word', 0).mockUpload.fileSizeInput
.sendKeys(constants.testMockMp3UploadFile.size);
editorPage.edit.audio.control('Word', 0).mockUpload.uploadButton.click();
editorPage.edit.audio.control('Word', 0).mockUpload.enableButton.click();
expect(editorPage.noticeList.count()).toBe(1);
expect(editorPage.noticeList.first().getText()).toContain('File uploaded successfully');
expect(editorPage.edit.audio.playerIcons('Word').first().isDisplayed()).toBe(true);
expect(editorPage.edit.audio.playerIcons('Word').first().getAttribute('class'))
.toContain('fa-play');
expect(editorPage.edit.audio.players('Word').first().isDisplayed()).toBe(true);
expect(editorPage.edit.audio.players('Word').first().isEnabled()).toBe(true);
expect(editorPage.edit.audio.moreControls('Word').first().isDisplayed()).toBe(true);
});
});
it('click on second word (found by definition)', function () {
editorPage.edit.findEntryByDefinition(constants.testEntry2.senses[0].definition.en.value)
.click();
});
it('word 2: edit page has correct definition, part of speech', function () {
expect(editorPage.edit.getFieldValues('Definition')).toEqual([
{ en: constants.testEntry2.senses[0].definition.en.value }
]);
expect(editorPage.edit.getFieldValues('Part of Speech')).toEqual([
editorUtil.expandPartOfSpeech(constants.testEntry2.senses[0].partOfSpeech.value)
]);
});
it('setup: click on word with multiple definitions (found by lexeme)', function () {
editorPage.edit.findEntryByLexeme(constants.testMultipleMeaningEntry1.lexeme.th.value).click();
editorPage.edit.senses.first().click();
});
it('word with multiple definitions: edit page has correct definitions, parts of speech',
function () {
expect(editorPage.edit.getFieldValues('Definition')).toEqual([
{ en: constants.testMultipleMeaningEntry1.senses[0].definition.en.value },
{ en: constants.testMultipleMeaningEntry1.senses[1].definition.en.value }
]);
expect(editorPage.edit.getFieldValues('Part of Speech')).toEqual([
editorUtil
.expandPartOfSpeech(constants.testMultipleMeaningEntry1.senses[0].partOfSpeech.value),
editorUtil
.expandPartOfSpeech(constants.testMultipleMeaningEntry1.senses[1].partOfSpeech.value)
]);
});
it('word with multiple meanings: edit page has correct example sentences, translations',
function () {
// Empty array elements are a work-around for getFieldValues after SemDom directive added. DDW
expect(editorPage.edit.getFieldValues('Sentence')).toEqual([
'', { th: constants.testMultipleMeaningEntry1.senses[0].examples[0].sentence.th.value },
{ th: constants.testMultipleMeaningEntry1.senses[0].examples[1].sentence.th.value },
'', { th: constants.testMultipleMeaningEntry1.senses[1].examples[0].sentence.th.value },
{ th: constants.testMultipleMeaningEntry1.senses[1].examples[1].sentence.th.value }
]);
expect(editorPage.edit.getFieldValues('Translation')).toEqual([
{ en: constants.testMultipleMeaningEntry1.senses[0].examples[0].translation.en.value },
{ en: constants.testMultipleMeaningEntry1.senses[0].examples[1].translation.en.value },
{ en: constants.testMultipleMeaningEntry1.senses[1].examples[0].translation.en.value },
{ en: constants.testMultipleMeaningEntry1.senses[1].examples[1].translation.en.value }
]);
});
it('while Show Hidden Fields has not been clicked, hidden fields are hidden if they are empty',
function () {
expect(editorPage.edit.getFields('Semantics Note').count()).toBe(0);
expect(editorPage.edit.getOneField('General Note').isPresent()).toBe(true);
editorPage.edit.showHiddenFields();
expect(editorPage.edit.getOneField('Semantics Note').isPresent()).toBe(true);
expect(editorPage.edit.getOneField('General Note').isPresent()).toBe(true);
});
it('word with multiple meanings: edit page has correct general notes, sources', function () {
expect(editorPage.edit.getFieldValues('General Note')).toEqual([
{ en: constants.testMultipleMeaningEntry1.senses[0].generalNote.en.value },
{ en: constants.testMultipleMeaningEntry1.senses[1].generalNote.en.value }
]);
// First item is empty Etymology Source, now that View Settings all default to visible. IJH
// Empty array elements are a work-around for getFieldValues after SemDom directive added. IJH
expect(editorPage.edit.getFieldValues('Source')).toEqual([
{ en: '' }, '',
{ en: constants.testMultipleMeaningEntry1.senses[0].source.en.value }, '',
{ en: constants.testMultipleMeaningEntry1.senses[1].source.en.value }
]);
});
it('back to browse page, create new word', function () {
editorPage.edit.toListLink.click();
editorPage.browse.newWordBtn.click();
});
it('check that word count is still correct', function () {
expect(editorPage.edit.entriesList.count()).toEqual(editorPage.edit.getEntryCount());
expect(editorPage.edit.getEntryCount()).toEqual(4);
});
it('modify new word', function () {
var word = constants.testEntry3.lexeme.th.value;
var definition = constants.testEntry3.senses[0].definition.en.value;
editorPage.edit.getMultiTextInputs('Word').first().sendKeys(word);
editorPage.edit.getMultiTextInputs('Definition').first().sendKeys(definition);
util.clickDropdownByValue(editorPage.edit.getOneField('Part of Speech').$('select'),
'Noun \\(n\\)');
util.scrollTop();
editorPage.edit.saveBtn.click();
});
it('new word is visible in edit page', function () {
editorPage.edit.search.input.sendKeys(constants.testEntry3.senses[0].definition.en.value);
expect(editorPage.edit.search.getMatchCount()).toBe(1);
editorPage.edit.search.clearBtn.click();
});
it('check that Semantic Domain field is visible (for view settings test later)', function () {
expect(editorPage.edit.getOneField('Semantic Domain').isPresent()).toBeTruthy();
});
describe('Configuration check', function () {
it('Word has only "th", "tipa" and "taud" visible', function () {
expect(editorPage.edit.getMultiTextInputSystems('Word').count()).toEqual(3);
expect(editorPage.edit.getMultiTextInputSystems('Word').get(0).getText()).toEqual('th');
expect(editorPage.edit.getMultiTextInputSystems('Word').get(1).getText()).toEqual('tipa');
expect(editorPage.edit.getMultiTextInputSystems('Word').get(2).getText()).toEqual('taud');
});
it('make "en" input system visible for "Word" field', function () {
configPage.get();
configPage.getTabByName('Fields').click();
configPage.getFieldByName('Word').click();
expect(configPage.fieldsTab.inputSystemTags.get(3).getText()).toEqual('en');
util.setCheckbox(configPage.fieldsTab.inputSystemCheckboxes.get(3), true);
configPage.applyButton.click();
util.clickBreadcrumb(constants.testProjectName);
editorPage.browse.findEntryByLexeme(constants.testEntry1.lexeme.th.value).click();
});
it('Word has "th", "tipa", "taud" and "en" visible', function () {
expect(editorPage.edit.getMultiTextInputSystems('Word').count()).toEqual(4);
expect(editorPage.edit.getMultiTextInputSystems('Word').get(0).getText()).toEqual('th');
expect(editorPage.edit.getMultiTextInputSystems('Word').get(1).getText()).toEqual('tipa');
expect(editorPage.edit.getMultiTextInputSystems('Word').get(2).getText()).toEqual('taud');
expect(editorPage.edit.getMultiTextInputSystems('Word').get(3).getText()).toEqual('en');
});
it('make "en" input system invisible for "Word" field', function () {
configPage.get();
configPage.getTabByName('Fields').click();
configPage.getFieldByName('Word').click();
expect(configPage.fieldsTab.inputSystemTags.get(3).getText()).toEqual('en');
util.setCheckbox(configPage.fieldsTab.inputSystemCheckboxes.get(3), false);
configPage.applyButton.click();
util.clickBreadcrumb(constants.testProjectName);
editorPage.browse.findEntryByLexeme(constants.testEntry1.lexeme.th.value).click();
});
it('Word has only "th", "tipa" and "taud" visible', function () {
expect(editorPage.edit.getMultiTextInputSystems('Word').count()).toEqual(3);
expect(editorPage.edit.getMultiTextInputSystems('Word').get(0).getText()).toEqual('th');
expect(editorPage.edit.getMultiTextInputSystems('Word').get(1).getText()).toEqual('tipa');
expect(editorPage.edit.getMultiTextInputSystems('Word').get(2).getText()).toEqual('taud');
});
});
it('first entry is selected if entryId unknown', function () {
editorPage.edit.findEntryByLexeme(constants.testEntry3.lexeme.th.value).click();
editorPage.getProjectIdFromUrl().then(function (projectId) {
editorPage.get(projectId, '_unknown_id_1234');
});
expect(editorPage.edit.getFirstLexeme()).toEqual(constants.testEntry1.lexeme.th.value);
});
it('URL entry id changes with entry', function () {
var entry1Id = editorPage.getEntryIdFromUrl();
expect(entry1Id).toMatch(/[0-9a-z_]{6,24}/);
editorPage.edit.findEntryByLexeme(constants.testEntry3.lexeme.th.value).click();
expect(editorPage.edit.getFirstLexeme()).toEqual(constants.testEntry3.lexeme.th.value);
var entry3Id = editorPage.getEntryIdFromUrl();
expect(entry3Id).toMatch(/[0-9a-z_]{6,24}/);
expect(entry1Id).not.toEqual(entry3Id);
editorPage.edit.findEntryByLexeme(constants.testEntry1.lexeme.th.value).click();
expect(editorPage.edit.getFirstLexeme()).toEqual(constants.testEntry1.lexeme.th.value);
expect(editorPage.getEntryIdFromUrl()).not.toEqual(entry3Id);
});
it('new word is visible in browse page', function () {
editorPage.edit.toListLink.click();
editorPage.browse.search.input.sendKeys(constants.testEntry3.senses[0].definition.en.value);
expect(editorPage.browse.search.getMatchCount()).toBe(1);
editorPage.browse.search.clearBtn.click();
});
it('check that word count is still correct in browse page', function () {
expect(editorPage.browse.entriesList.count()).toEqual(editorPage.browse.getEntryCount());
expect(editorPage.browse.getEntryCount()).toBe(4);
});
it('remove new word to restore original word count', function () {
editorPage.browse.findEntryByLexeme(constants.testEntry3.lexeme.th.value).click();
editorPage.edit.deleteBtn.click();
util.clickModalButton('Delete Entry');
expect(editorPage.edit.getEntryCount()).toBe(3);
});
it('previous entry is selected after delete', function () {
expect(editorPage.edit.getFirstLexeme()).toEqual(constants.testEntry1.lexeme.th.value);
});
});
|
let Statment = require('../base').Statment;
let errors = require('../../../basics/errors');
let events = require('../../events');
module.exports = Statment.extend('ACTION','FOR_LOOP', {
}, {
$init(variable, source, scope){
this.variable = variable;
if (!this.variable["#addressable"]){
throw new errors.RuntimeError(
"$init",
`for loop must use a variable not ${variable.$type} ${variable.$subtype}`,
this.variable
);
}
this.source = source;
this.scope = scope;
},
async exec(eenv){
let source = await this.source.__update__(eenv, null, (result)=>{
if (!result["#indexable"]){
if (result["#morphable"]){
throw new errors.RuntimeError(
"exec",
`Could not determine value for looping`
);
}
throw new errors.RuntimeError(
"exec",
`Invalid value for looping ${result.$type} ${result.$subtype}`
);
}
});
let size = source.$$len();
for (let i = 0; i < size; i++){
await this.variable.__assign__(eenv, source.$$index(i))
let code = await eenv.execChild(this.scope, (child)=>{
child.on(events.BREAK, (e)=>{
e.stopPropagation();
child.terminate("BREAK");
});
child.on(events.CONTINUE, (e)=>{
e.stopPropagation();
child.terminate("CONTINUE");
});
});
if (code === "BREAK"){
break;
}
}
return null;
}
}, [
'no-context',
'only-exec',
'not-signable',
'not-encloseable'
]);
|
import gulp from 'gulp';
// Babel
import babel from 'gulp-babel';
// Cleaning filesystem
import del from 'del';
// Contact and ordering
import runSequence from 'run-sequence';
// Minification Javascript and Browserify
import browserify from 'browserify';
import uglify from 'gulp-uglify';
import source from 'vinyl-source-stream';
import buffer from 'vinyl-buffer';
import sourcemaps from 'gulp-sourcemaps';
import babelify from 'babelify';
// Minification CSS
import minifyCss from 'gulp-minify-css';
// Load Javascript Configurations
import js from './configurations/javascript';
// console.log(js);
/**
* Task will delete application production files.
*/
gulp.task('contact:clear-main-files', () => {
const javascriptMainFile = `${js.configuration.folderStructure.baseProduction}/${js.configuration.concatenationLocations.mainfile}`;
const sourceMap = javascriptMainFile + '.map';
del([
javascriptMainFile,
sourceMap
]);
});
gulp.task('browserify-transform', ['contact:clear-main-files'], () => {
return GulpHelper.browserifyTransform(false);
});
/**
* Minify application styling file.
* This task will be used only in production.
*/
gulp.task('minify:styles', () => {
});
/**
* Minify application javascript file.
* This task will be used only in production.
*/
gulp.task('minify:javascript', ['contact:clear-main-files'], () => {
return GulpHelper.browserifyTransform(true);
});
gulp.task('minify', (callback) => {
runSequence(['minify:javascript', 'minify:styles'], callback);
});
gulp.task('copy-views', () => {
// Target
const htmlFiles = '**/views/*.html';
const targetFolder = `${js.configuration.folderStructure.angular.base}/${htmlFiles}`;
// Destination
const destination = js.configuration.folderStructure.angular.base.replace('.', './public');
console.log('Target folder', targetFolder);
console.log('Destination folder', destination);
gulp.src(targetFolder).pipe(gulp.dest(destination));
});
gulp.task('copy-index-html', ['copy-views'], () => {
gulp.src('./index.html').pipe(gulp.dest('./public'));
});
class GulpHelper {
/**
* Browserify has become an important and indispensable tool but requires being wrapped before working well with gulp.
* Below is a simple recipe for using Browserify with transforms.
* See also: the Combining Streams to Handle Errors recipe for handling errors with browserify or uglify in your stream.
*
* Source: https://github.com/gulpjs/gulp/blob/master/docs/recipes/browserify-transforms.md
*/
static browserifyTransform(uglifyIsEnable) {
// set up the browserify instance on a task basis
const browserifyStream = browserify({
'entries': `${js.configuration.folderStructure.baseDevelopment}/entry.js`,
// When opts.debug is true, add a source map inline to the end of the bundle.
// This makes debugging easier because you can see all the original files if you are in a modern enough browser.
'debug': (uglifyIsEnable ? false : true),
// opts.paths is an array of directories that browserify searches when looking for
// modules which are not referenced using relative path. Can be absolute or relative to basedir.
// Equivalent of setting NODE_PATH environmental variable when calling browserify command.
// Get idea from: https://github.com/vigetlabs/gulp-starter/issues/17
paths: [
'../node_modules',
'../bower_components',
'../app/development/'
],
// defining transforms here will avoid crashing your stream
'transform': [babelify]
});
const tempConfiguration = browserifyStream.bundle()
.pipe(source(js.configuration.concatenationLocations.mainfile))
.pipe(buffer())
.pipe(sourcemaps.init({ loadMaps: true }))
if (uglifyIsEnable) {
tempConfiguration
// Add transformation tasks to the pipeline here.
.pipe(uglify())
}
return tempConfiguration
.pipe(sourcemaps.write('/', { addComment: false }))
.pipe(gulp.dest(js.configuration.folderStructure.baseProduction));
}
}
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var stylus = require('stylus');
var nib = require('nib');
var environment = require('./env');
var index = require('./routes/index');
var auth = require('./routes/auth');
var http = require('http');
var mongoose = require('mongoose');
var passport = require('passport');
var passportLocalStrategy = require('passport-local').Strategy;
var app = express();
var compileStylus = function compile(str, path) {
return stylus(str).set('filename', path).use(nib());
};
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
//Middleware setuip
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(stylus.middleware({
src: __dirname + '/public',
compile: compileStylus
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req, res, next) {
req.db = db;
next();
});
//Route setup
app.use('/', index);
app.use('/auth', auth);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
|
(function () {
angular
.module('app')
.controller('ControlPanelController', [
'$mdDialog', '$interval',
ControlPanelController
]);
function ControlPanelController($mdDialog, $interval) {
var vm = this;
vm.buttonEnabled = false;
vm.showProgress = false;
vm.reloadServer = 'Staging';
vm.performProgress = performProgress;
vm.determinateValue = 10;
function performProgress() {
vm.showProgress = true;
interval = $interval(function() {
vm.determinateValue += 1;
if (vm.determinateValue > 100) {
vm.determinateValue = 10;
vm.showProgress = false;
showAlert();
$interval.cancel(interval)
}
}, 50, 0, true);
}
function showAlert() {
alert = $mdDialog.alert({
title: 'Reloading complete !',
content: vm.reloadServer + " region reloaded.",
ok: 'Close'
});
$mdDialog
.show(alert)
.finally(function () {
alert = undefined;
});
}
}
})();
|
var cookbookApp = angular.module('cookbookApp', ["ngRoute", "cookbookController", "cookbookFilter"]);
cookbookApp.config(["$routeProvider", function($routeProvider){
$routeProvider.
when("/cookbooks",{
templateUrl: 'partials/cookbook-list.html',
controller: 'cookbookListCrl'
}).
when("/cookbooks/new",{
templateUrl: 'partials/cookbook-form.html',
controller: 'cookbookNewCrl'
}).
when("/cookbooks/:cookbookId", {
templateUrl: 'partials/cookbook-detail.html',
controller: 'cookbookDetailCrl'
}).
when("/cookbooks/:cookbookId/edit",{
templateUrl: 'partials/cookbook-form.html',
controller: 'cookbookEditCrl'
}).
otherwise({
redirectTo: '/cookbooks'
});
}]);
|
import Phaser from 'phaser';
export default class extends Phaser.Sprite{
constructor(game,x,y,asset){
super(game,x,y,asset);
this.colorMap = new Map([
[0,'flash-red'],
[1,'flash-blue'],
[2,'flash-green'],
[3,'flash-pink'],
[4,'flash-gold'],
[5,'flash-lb']
]);
// console.log("This is the parent, Item class.",game,x,y,asset);
// this.game.physics.arcade.enable([this]);
// this.scale.setTo(this.scaleRatio(), this.scaleRatio());
//enable input on the bomb
// this.inputEnabled = true;
//then when user clicks it, activate the method on the object
}
checkWorldBounds() {
if (!this.destroyed && this.body.position.x < 0) {
// this.body.position.x = this.game.physics.arcade.bounds.x;
this.body.velocity.x *= -this.body.bounce.x;
this.body.blocked.left = true;
} else if (!this.destroyed && this.body.position.x > this.game.world.width-70) {
// this.position.x = this.game.physics.arcade.bounds.right - this.width;
this.body.velocity.x *= -this.body.bounce.x;
this.body.blocked.right = true;
}
}
update(){
super.update();
if(this.y > this.game.world.height){
this.destroySelf();
}
this.checkWorldBounds()
}
destroySelf(){
this.destroyed = true;
this.destroy();
}
}
|
import React from 'react';
import ReactShallowRenderer from 'react-test-renderer/shallow';
import Progress from 'chamel/Progress';
/**
* Test rendering the Progress
*/
describe("Progress Component", () => {
// Basic validation that render works in edit mode and returns children
it("Should render", () => {
const renderer = new ReactShallowRenderer();
const renderedDocument = renderer.render(
<Progress
value={100}
/>
);
expect(renderedDocument.props.type).toBe('linear');
expect(renderedDocument.props.value).toBe(100);
});
});
|
/**********************************************************
examples.js - Some use cases and tests for Dcor
Alan Zawari
May 2014
Note:
First define all sample functions (Block #1)
and then try different test cases one by one (Block #2)
***********************************************************/
//first include Dcor.js
//------------------------------------------------------------
//Block #1. Define some sample functions...
//------------------------------------------------------------
function foo(a, b) {
console.log("inside foo. this:", this);
return "hello " + a + " " + b;
}
function bar(a, b, c) {
var d = 1;
return a + b + c + d;
}
var myLib = {
foo: function (s) {
return "myLib.foo says: " + s;
},
bar: 10
};
var MySinglton = function () {
this.a = 1024;
};
function MyCtor(c) {
var prvt = 9;
var d = c || 0;
this.a = "foo";
this.b = d + prvt + 1;
console.log("this.b: ", this.b); //10
}
function isPrime(value) {
var prime = value != 1; // 1 can never be prime
for (var i = 2; i < value; i++) {
console.log("Checking " + i);
if (value % i === 0) {
prime = false;
break;
}
}
return prime;
}
function recursiveFunc(n) {
return n > 1 ? recursiveFunc(n - 1) + "-Hi" : "Hi";
}
function lengthyOperation(n) {
console.log("lengthyOperation started. n:" + n);
var res = 0;
for (var i = 0; i < n; i++) {
for (var j = 0; j < n; j++) {
res += (i + j);
}
}
console.log("lengthyOperation completed. res:" + res);
return res;
}
//------------------------------------------------------------
//Block #2: Decorate functions and call them
//------------------------------------------------------------
//************************************************************
//normal call:
foo("beautiful", "world");
//decorate it:
Dcor.logged("foo", function (fname, fargs, res) {
console.log("Log> function " + fname + " called with: ", fargs, " and returned: ", res);
});
//expect:
foo("beautiful", "world"); //should be logged
//************************************************************
//normal call:
new MyCtor();
//decorate it:
Dcor.decorate("MyCtor", [{
type: "safeConstructor"
}]);
//expect:
MyCtor(); //should be the same as new MyCtor().
new MyCtor();
console.log(typeof b == "undefined"); //global context shouldn't affected and therefore 'b' must not exist
//************************************************************
//normal call:
lengthyOperation(30000); //should take about 5 seconds and UI is blocked
console.log("hooray! lengthyOperation is done."); //no result until lengthyOperation is completed
//decorate it:
Dcor.decorate("lengthyOperation", [{
type: "async",
callback: function (fname, fargs, res, f, ns) {
console.log("Async> function " + fname + " called with: ", fargs, " and returned: ", res);
}
}]);
//expect:
lengthyOperation(30000); //async. shouldn't block the UI
console.log("hooray! lengthyOperation is done."); //we should see this immediately
//************************************************************
//normal call:
mySinglton1 = new MySinglton();
mySinglton2 = MySinglton();
console.log("mySinglton1 === mySinglton2?", mySinglton1 === mySinglton2) //false. two different instances
//decorate it:
Dcor.singleton("MySinglton");
//expect:
mySinglton1 = new MySinglton();
mySinglton2 = MySinglton();
console.log("mySinglton1 === mySinglton2?", mySinglton1 === mySinglton2) //true. two instances are the same
//************************************************************
//normal call:
isPrime(173);
isPrime(173); //both calls take the same amount of time
//decorate it: with "cached" and "performanceLogged"
Dcor.decorate("isPrim.*", [{
type: "cached",
callback: function (fromCache, fname, fargs, res, f, ns) {
if (fromCache) console.log("Cache> function " + fname + " called with: ", fargs, " and returned result: ", res + " from cache");
else console.log("Cache> function " + fname + " called with: ", fargs, " and stored result: ", res + " to cache");
}
}, {
type: "performanceLogged",
callback: function (duration, fname, fargs, res, f, ns) {
console.log("Perf> function " + fname + " called with: ", fargs, " and ran for:", duration + "ms");
}
}]);
//expect: isPrime is now cached and performanceLogged
isPrime(173); //must be calculated and show the execution time
isPrime(173); //this time must be retrieved from cache with faster execution time
//************************************************************
//normal call:
recursiveFunc(25); //25 recursion
//decorate it:
Dcor.cached("recursiveFunc", function (fromCache, fname, fargs, res, f, ns) {
if (fromCache) console.log("Cache> function " + fname + " called with: ", fargs, " and returned result: ", res + " from cache");
else console.log("Cache> function " + fname + " called with: ", fargs, " and stored result: ", res + " to cache");
});
//expect:
recursiveFunc(25); //25 recursion
recursiveFunc(10); //no recursion. should use cache
recursiveFunc(17); //no recursion. should use cache
//************************************************************
//normal call:
myLib.foo("hi"); //runs normally. no authorization required
//decorate it:
Dcor.secured("foo", function (fname, fargs) {
var authorized = false; //check whether it is allowed to call this function...
if (!authorized)
//return false to silently prevent running this function
throw new Error("Not authorized to run function " + fname + " with: " + fargs);
else
return true;
//console.log("Authorization> Not authorized to run function " + fname + " with: ", fargs);
}, [myLib]);
//expect:
myLib.foo("hi"); //won't run. should give authorization error
//************************************************************
|
define(function(require) {
var Position = require('../src/position');
var $ = require('$');
describe('position', function() {
var pinElement, baseElement, noopDiv;
$(document.body).css('margin', 0);
beforeEach(function() {
pinElement = $('<div style="width:100px;height:100px;">pinElement</div>').appendTo(document.body);
// for ie6 bug
noopDiv = $('<div></div>').appendTo(document.body);
baseElement = $('<div style="margin:20px;border:5px solid #000;padding:20px;width:200px;height:200px;">baseElement</div>').appendTo(document.body);
});
afterEach(function() {
baseElement.remove();
noopDiv.remove();
pinElement.remove();
});
test('相对屏幕定位:Position.pin(pinElement, { x: 100, y: 100 })', function() {
Position.pin(pinElement, { x: 100, y: 100 });
expect(pinElement.offset().top).toBe(100);
expect(pinElement.offset().left).toBe(100);
});
test('基本情况:Position.pin({ element: pinElement, x: 0, y: 0 }, { element:baseElement, x: 100, y: 100 })', function() {
Position.pin({ element: pinElement, x: 0, y: 0 }, { element:baseElement, x: 100, y: 100 });
expect(pinElement.offset().top).toBe(120);
expect(pinElement.offset().left).toBe(120);
});
test('第一个参数简略写法:Position.pin(pinElement, { element:baseElement, x: 100, y: 100 })', function() {
Position.pin({ element: pinElement, x: 0, y: 0 }, { element:baseElement, x: 100, y: 100 });
expect(pinElement.offset().top).toBe(120);
expect(pinElement.offset().left).toBe(120);
});
test('带px的字符串参数:Position.pin(pinElement, { element:baseElement, x: "100px", y: "100px" })', function() {
Position.pin({ element: pinElement, x: 0, y: 0 }, { element:baseElement, x: "100px", y: "100px" });
expect(pinElement.offset().top).toBe(120);
expect(pinElement.offset().left).toBe(120);
});
test('负数定位点:Position.pin({ element: pinElement, x: -100, y: -100 }, { element:baseElement, x: 0, y: 0 })', function() {
Position.pin({ element: pinElement, x: -100, y: -100 }, { element:baseElement, x: 0, y: 0 });
expect(pinElement.offset().top).toBe(120);
expect(pinElement.offset().left).toBe(120);
});
test('百分比:Position.pin(pinElement, { element:baseElement, x: "100%", y: "50%" })', function() {
Position.pin(pinElement, { element:baseElement, x: '100%', y: '50%' });
expect(pinElement.offset().top).toBe(145);
expect(pinElement.offset().left).toBe(270);
});
test('负百分比:Position.pin(pinElement, { element:baseElement, x: "-100%", y: "-50%" })', function() {
Position.pin(pinElement, { element:baseElement, x: '-100%', y: '-50%' });
expect(pinElement.offset().top).toBe(-105);
expect(pinElement.offset().left).toBe(-230);
});
test('别名:Position.pin({ element:pinElement, x: "left", y: "left" }, { element:baseElement, x: "right", y: "center" })', function() {
Position.pin({ element:pinElement, x: "left", y: "left" }, { element:baseElement, x: 'right', y: 'center' });
expect(pinElement.offset().top).toBe(145);
expect(pinElement.offset().left).toBe(270);
});
test('百分比小数:Position.pin(pinElement, { element:baseElement, x: "99.5%", y: "50.5%" })', function() {
Position.pin(pinElement, { element:baseElement, x: "99.5%", y: "50.5%" });
expect(pinElement.offset().top).toBeGreaterThan(145.99);
expect(pinElement.offset().top).toBeLessThan(147.01);
expect(pinElement.offset().left).toBeGreaterThan(267.99);
expect(pinElement.offset().left).toBeLessThan(269.01);
});
test('居中定位:Position.center(pinElement, baseElement);', function() {
Position.center(pinElement, baseElement);
expect(pinElement.offset().top).toBe(95);
expect(pinElement.offset().left).toBe(95);
});
test('屏幕居中定位:Position.center(pinElement );', function() {
Position.center(pinElement);
expect(($(window).outerHeight()-100)/2).toBeGreaterThan(pinElement.offset().top-0.51);
expect(($(window).outerHeight()-100)/2).toBeLessThan(pinElement.offset().top+0.51);
expect(($(window).outerWidth()-100)/2).toBeGreaterThan(pinElement.offset().left-0.51);
expect(($(window).outerWidth()-100)/2).toBeLessThan(pinElement.offset().left+0.51);
});
test('offsetParent不为body:', function() {
var offsetParent = $('<div style="margin:20px;border:10px solid #000;padding:20px;position:relative;"></div>').appendTo(document.body);
baseElement.appendTo(offsetParent);
Position.pin(pinElement, { element:baseElement, x: 100, y: 100 });
expect(parseInt(pinElement.offset().top) - parseInt(baseElement.offset().top)).toBe(100);
expect(parseInt(pinElement.offset().left) - parseInt(baseElement.offset().left)).toBe(100);
offsetParent.remove();
});
test('offsetParent绝对定位:', function() {
var offsetParent = $('<div style="position:absolute;top:50px;left:50px;"></div>').appendTo(document.body);
baseElement.appendTo(offsetParent);
Position.pin(pinElement, { element:baseElement, x: 100, y: 100 });
expect(parseInt(pinElement.offset().top)).toBe(170);
expect(parseInt(pinElement.offset().left)).toBe(170);
offsetParent.remove();
});
test('加号应用:', function() {
Position.pin(pinElement, { element:baseElement, x: "100%+20px", y: "50%+15px" });
expect(parseInt(pinElement.offset().top)).toBe(160);
expect(parseInt(pinElement.offset().left)).toBe(290);
});
test('减号应用:', function() {
Position.pin(pinElement, { element:baseElement, x: "100%-20px", y: "50%-15px" });
expect(parseInt(pinElement.offset().top)).toBe(130);
expect(parseInt(pinElement.offset().left)).toBe(250);
});
test('加减号混用:', function() {
Position.pin(pinElement, { element:baseElement, x: "100%-20px+10px", y: "50%-15px+5px" });
expect(parseInt(pinElement.offset().top)).toBe(135);
expect(parseInt(pinElement.offset().left)).toBe(260);
});
test('相对自身定位:', function() {
baseElement.remove();
Position.pin(pinElement, { element:pinElement, x: "100%", y: 0 });
expect(parseInt(pinElement.offset().top)).toBe(0);
expect(parseInt(pinElement.offset().left)).toBe(100);
});
test('fixed定位:', function() {
pinElement.css('position', 'fixed');
Position.pin(pinElement, { x: "300px", y: 250 });
expect(pinElement.css('position')).toBe('fixed');
expect(pinElement.css('top')).toBe('250px');
expect(pinElement.css('left')).toBe('300px');
});
});
});
|
var page = div();
page.innerHTML = Main;
class Renderer {
PARTICLE_COUNT = 150;
PARTICLE_RADIUS = 6;
MAX_ROTATION_ANGLE = Math.PI / 60;
TRANSLATION_COUNT = 500;
constructor(strategy) {
if (strategy) {
this.init(strategy);
}
}
init(strategy) {
this.setParameters(strategy);
this.createParticles();
this.setupFigure();
this.reconstructMethod();
this.bindEvent();
this.drawFigure();
}
setParameters(strategy) {
this.container = page;
var offset = getScreenPosition(this.container);
this.width = offset.width;
this.height = offset.height;
var canvas = this.canvas = document.querySelector('canvas');
canvas.width = this.width;
canvas.height = this.height;
this.context = this.canvas.getContext('2d');
this.center = { x: this.width / 2, y: this.height / 2 };
this.rotationX = this.MAX_ROTATION_ANGLE;
this.rotationY = this.MAX_ROTATION_ANGLE;
this.strategyIndex = 0;
this.translationCount = 0;
this.theta = 0;
this.strategies = strategy.getStrategies();
this.particles = [];
}
createParticles() {
for (var i = 0; i < this.PARTICLE_COUNT; i++) {
this.particles.push(new Partice(this.center));
}
}
reconstructMethod() {
this.setupFigure = this.setupFigure.bind(this);
this.drawFigure = this.drawFigure.bind(this);
this.changeAngle = this.changeAngle.bind(this);
}
bindEvent() {
on('click')(this.container, this.setupFigure);
on('mousemove')(this.container, this.changeAngle);
}
changeAngle(event) {
var offset = getScreenPosition(this.container),
x = event.clientX - offset.left,
y = event.clientY - offset.top;
this.rotationX = (this.center.y - y) / this.center.y * this.MAX_ROTATION_ANGLE;
this.rotationY = (this.center.x - x) / this.center.x * this.MAX_ROTATION_ANGLE;
}
setupFigure() {
for (var i = 0, length = this.particles.length; i < length; i++) {
this.particles[i].setAxis(this.strategies[this.strategyIndex]());
}
if (++this.strategyIndex == this.strategies.length) {
this.strategyIndex = 0;
}
this.translationCount = 0;
}
drawFigure() {
requestAnimationFrame(this.drawFigure);
analyser.getFloatTimeDomainData(arr);
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
for (var cx = 0, dx = this.particles.length; cx < dx; cx++) {
var axis = this.particles[cx].getAxis2D(this.theta);
this.context.beginPath();
this.context.fillStyle = axis.color;
this.context.arc(axis.x + (axis.x - this.center.x) * (arr[cx % arr.length]) | 0, axis.y + (axis.y - this.center.y) * (arr[cx % arr.length]) | 0, this.PARTICLE_RADIUS, 0, Math.PI * 2);
this.context.fill();
}
// console.log(this.context);
this.theta++;
this.theta %= 360;
for (var cx = 0, dx = this.particles.length; cx < dx; cx++) {
this.particles[cx].rotateX(this.rotationX);
this.particles[cx].rotateY(this.rotationY);
}
this.translationCount++;
this.translationCount %= this.TRANSLATION_COUNT;
if (this.translationCount == 0) {
this.setupFigure();
}
}
};
class Strategy {
SCATTER_RADIUS = 200;
CONE_ASPECT_RATIO = 5;
RING_COUNT = 5;
constructor() {
}
getStrategies() {
var strategies = [];
for (var i in this) {
if (this[i] === this.getStrategies || typeof this[i] != 'function') {
continue;
}
strategies.push(this[i].bind(this));
}
return strategies;
}
createSphere() {
var cosTheta = Math.random() * 2 - 1,
sinTheta = Math.sqrt(1 - cosTheta * cosTheta),
phi = Math.random() * 2 * Math.PI;
return {
x: this.SCATTER_RADIUS * sinTheta * Math.cos(phi),
y: this.SCATTER_RADIUS * sinTheta * Math.sin(phi),
z: this.SCATTER_RADIUS * cosTheta,
hue: Math.round(phi / Math.PI * 30)
};
}
createTorus() {
var theta = Math.random() * Math.PI * 2,
x = this.SCATTER_RADIUS + this.SCATTER_RADIUS / 6 * Math.cos(theta),
y = this.SCATTER_RADIUS / 6 * Math.sin(theta),
phi = Math.random() * Math.PI * 2;
return {
x: x * Math.cos(phi),
y: y,
z: x * Math.sin(phi),
hue: Math.round(phi / Math.PI * 30)
};
}
createCone() {
var status = Math.random() > 1 / 3,
x,
y,
phi = Math.random() * Math.PI * 2,
rate = Math.tan(30 / 180 * Math.PI) / this.CONE_ASPECT_RATIO;
if (status) {
y = this.SCATTER_RADIUS * (1 - Math.random() * 2);
x = (this.SCATTER_RADIUS - y) * rate;
} else {
y = -this.SCATTER_RADIUS;
x = this.SCATTER_RADIUS * 2 * rate * Math.random();
}
return {
x: x * Math.cos(phi),
y: y,
z: x * Math.sin(phi),
hue: Math.round(phi / Math.PI * 30)
};
}
createVase() {
var theta = Math.random() * Math.PI,
x = Math.abs(this.SCATTER_RADIUS * Math.cos(theta) / 2) + this.SCATTER_RADIUS / 8,
y = this.SCATTER_RADIUS * Math.cos(theta) * 1.2,
phi = Math.random() * Math.PI * 2;
return {
x: x * Math.cos(phi),
y: y,
z: x * Math.sin(phi),
hue: Math.round(phi / Math.PI * 30)
};
}
};
class Partice {
constructor(center) {
this.center = center;
this.init();
}
SPRING = 0.01;
FRICTION = 0.9;
FOCUS_POSITION = 300;
COLOR = 'hsl(%hue, 100%, 70%)';
init() {
this.x = 0;
this.y = 0;
this.z = 0;
this.vx = 0;
this.vy = 0;
this.vz = 0;
this.color;
}
setAxis(axis) {
this.translating = true;
this.nextX = axis.x;
this.nextY = axis.y;
this.nextZ = axis.z;
this.hue = axis.hue;
}
rotateX(angle) {
var sin = Math.sin(angle),
cos = Math.cos(angle),
nextY = this.nextY * cos - this.nextZ * sin,
nextZ = this.nextZ * cos + this.nextY * sin,
y = this.y * cos - this.z * sin,
z = this.z * cos + this.y * sin;
this.nextY = nextY;
this.nextZ = nextZ;
this.y = y;
this.z = z;
}
rotateY(angle) {
var sin = Math.sin(angle),
cos = Math.cos(angle),
nextX = this.nextX * cos - this.nextZ * sin,
nextZ = this.nextZ * cos + this.nextX * sin,
x = this.x * cos - this.z * sin,
z = this.z * cos + this.x * sin;
this.nextX = nextX;
this.nextZ = nextZ;
this.x = x;
this.z = z;
}
rotateZ(angle) {
var sin = Math.sin(angle),
cos = Math.cos(angle),
nextX = this.nextX * cos - this.nextY * sin,
nextY = this.nextY * cos + this.nextX * sin,
x = this.x * cos - this.y * sin,
y = this.y * cos + this.x * sin;
this.nextX = nextX;
this.nextY = nextY;
this.x = x;
this.y = y;
}
getAxis3D() {
this.vx += (this.nextX - this.x) * this.SPRING;
this.vy += (this.nextY - this.y) * this.SPRING;
this.vz += (this.nextZ - this.z) * this.SPRING;
this.vx *= this.FRICTION;
this.vy *= this.FRICTION;
this.vz *= this.FRICTION;
this.x += this.vx;
this.y += this.vy;
this.z += this.vz;
return { x: this.x, y: this.y, z: this.z };
}
getAxis2D(theta) {
var axis = this.getAxis3D(),
scale = this.FOCUS_POSITION / (this.FOCUS_POSITION + axis.z);
return { x: this.center.x + axis.x * scale, y: this.center.y - axis.y * scale, color: this.COLOR.replace('%hue', this.hue + theta) };
}
}
function play(url) {
var AudioContext = window.mozAudioContext || window.webkitAudioContext || window.AudioContext;
if (!AudioContext) {
alert("error", "不支持的浏览器!");
throw "不支持的浏览器";
}
var xhr = cross("get", url).done(function () {
console.log(xhr.response);
audioContext.decodeAudioData(xhr.response, function (buffer) {
var source = audioContext.createBufferSource();
source.buffer = buffer;
source.connect(analyser);
analyser.connect(gainNode);
gainNode.connect(audioContext.destination);
source.start ? source.start(0) : source.noteOn(0);
}, alert.bind("error"))
});
xhr.responseType = "arraybuffer";
}
var audioContext = new AudioContext;
var gainNode = audioContext.createGain ? audioContext.createGain() : audioContext.createGainNode();
var analyser = audioContext.createAnalyser();
analyser.fftSize = 512;
var arr = new Float32Array(analyser.frequencyBinCount);
var arrFloat = new Float32Array(analyser.frequencyBinCount);
var seeAudio = function () {
var canvas = document.querySelector("canvas");
canvas.width = page.offsetWidth;
canvas.height = page.offsetHeight;
var context = canvas.getContext("2d");
context.strokeStyle = "#ffffff";
var run = function () {
requestAnimationFrame(run);
analyser.getFloatTimeDomainData(arrFloat);
view$audio(context, arrFloat);
}
requestAnimationFrame(run);
}
once("append")(page, function () {
seeAudio();
// new Renderer(new Strategy);
});
render(page, { gainNode });
function main() {
play("http://fs.open.kugou.com/ef34b2e46b9d7e8b2199c4943d2eb81c/5c830a93/G073/M04/17/11/iQ0DAFePd5OIBXTgAA98qfjcK2YAAAacACmTFkAD3zB338.m4a");
return page;
} |
/**
* Created by vedi on 11/21/13.
*/
'use strict';
const Bb = require('bluebird');
const mongoose = require('mongoose');
const GridStore = Bb.promisifyAll(mongoose.mongo.GridStore);
const ObjectID = mongoose.mongo.ObjectID;
class GridFsStorage {
initialize(options) {
this.db = options.dataSource.ModelClass.db.db;
}
getStream(fileMeta) {
const id = fileMeta.fileId;
const store = new GridStore(this.db, new ObjectID(id.toString()), 'r', { root: 'fs' });
Bb.promisifyAll(store);
return store.openAsync().then(db => ({
contentType: fileMeta.contentType,
contentLength: db.stream(true).totalBytesToRead,
stream: db.stream(true),
}));
}
putFile(path, options) {
const { fileName, ...rest } = options;
options = rest || {};
const gridStore = Bb
.promisifyAll(new GridStore(this.db, new ObjectID(), fileName, 'w', options));
return Bb
.try(() => gridStore.openAsync())
.then(() => gridStore.writeFileAsync(path))
.then(doc => ({
contentType: doc.contentType,
fileName: doc.filename,
fileId: doc.fileId,
root: doc.root,
uploadDate: doc.uploadDate,
}));
}
replaceFile(fileMeta, path, options) {
const id = fileMeta.fileId;
const { fileName, ...rest } = options;
return Bb
.bind(this)
.then(() => {
options = rest || {};
options.root = 'fs';
const store = Bb.promisifyAll(new GridStore(this.db, id, fileName, 'w', options));
return store.openAsync();
})
.then(store => store.rewindAsync())
.then(gridStore => gridStore.writeFileAsync(path))
.then(doc => ({
contentType: doc.contentType,
fileName: doc.filename,
fileId: doc.fileId,
root: doc.root,
uploadDate: doc.uploadDate,
}))
;
}
deleteFile(fileMeta) {
const id = fileMeta.fileId;
return GridStore.unlinkAsync(this.db, id);
}
}
module.exports = GridFsStorage;
|
import gulp from 'gulp';
import mocha from 'gulp-mocha';
export const testunit = 'test:unit';
function handleError(err){
console.log(err.toString());
this.emit('end');
}
gulp.task(testunit, () => {
return gulp.src('src/**/*_test.js', {read: false})
.pipe(mocha({
compilers: 'js:babel-core/register',
useColors: false,
reporter: 'mocha-jenkins-reporter',
reporterOptions: {
junit_report_path: './test-reports/mocha/test-results_mocha.xml'
}
}))
.on('error', handleError);
}); |
/*
*
* WeChatLogin constants
*
*/
export const DEFAULT_ACTION = 'app/WeChatLogin/DEFAULT_ACTION';
export const DO_WECHAT_LOGIN = 'DO_WECHAT_LOGIN';
|
var firebaseData = new Firebase('https://burning-fire-9280.firebaseio.com');
var commentsDB = firebaseData.child("comments");
var getEpoch = function() {
return (new Date()).getTime();
}
var epochToDate = function(epoch) {
var d = new Date(0);
d.setUTCMilliseconds(epoch);
return d;
}
var handleCommentKeypress = function (e) {
if (e.keyCode == 13) {
var author = $("#author-field").val();
var comment = $("#comment-field").val();
if (author && comment) {
var date = new Date();
date = date.toString();
commentsDB.push(
{author: author, comment: comment, date: getEpoch()}
);
} else {
alert("Author and Comment are required fields!");
}
}
};
commentsDB.on("child_added", function (snap) {
var entry = snap.val();
var entryLI = $("<li></li>").text(
entry.author + ": " + entry.comment + " [ " + epochToDate(entry.date).toString() + " ] "
)
$("#comments-list").append(entryLI);
$("#comment-field").val("");
})
$("#comment-field").keypress(handleCommentKeypress)
//$("#author-field").keypress(handleCommentKeypress)
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs");
ref.orderByChild("height").on("child_added", function (snapshot) {
console.log(snapshot.key() + " was " + snapshot.val().height + " meters tall");
});
|
angular.module('pl.paprikka.directives.haiku', ['pl.paprikka.services.haiku.slides', 'pl.paprikka.services.hammerjs', 'pl.paprikka.haiku.services.remote', 'pl.paprikka.directives.haiku.hTap', 'ngSanitize']).directive('haiku', [
'$window', 'Slides', 'Hammer', 'Remote', '$rootScope', function($window, Slides, Hammer, Remote, $rootScope) {
return {
templateUrl: 'haiku/partials/haiku.html',
restrict: 'AE',
link: function(scope, elm, attrs) {
var initSettings, onKeyDown, onMouseWheel;
scope.categories = Slides.get();
initSettings = function(scope) {
scope.currentCategory = 0;
scope.currentSlide = 0;
scope.isLastCategory = false;
scope.isLastSlide = false;
scope.isFirstCategory = false;
return scope.isFirstSlide = false;
};
initSettings(scope);
scope.$watch('categories.length', function(n, o) {
if (n === o) {
return;
}
return initSettings(scope);
});
scope.updatePosition = function() {
var currCat, currSlide, _ref, _ref1;
console.log("" + scope.currentCategory + " " + scope.currentSlide);
_.each(scope.categories, function(cat, catIndex) {
if (catIndex < scope.currentCategory) {
cat.status = 'prev';
} else if (catIndex === scope.currentCategory) {
cat.status = 'current';
} else if (catIndex > scope.currentCategory) {
cat.status = 'next';
}
console.log(cat.status);
return _.each(cat.slides, function(slide, slideIndex) {
if (slideIndex < scope.currentSlide) {
return slide.status = 'prev';
} else if (slideIndex === scope.currentSlide) {
return slide.status = 'current';
} else if (slideIndex > scope.currentSlide) {
return slide.status = 'next';
}
});
});
currCat = scope.currentCategory;
currSlide = scope.currentSlide;
scope.isLastCategory = currCat === scope.categories.length - 1 ? true : false;
scope.isLastSlide = currSlide === ((_ref = scope.categories[currCat]) != null ? (_ref1 = _ref.slides) != null ? _ref1.length : void 0 : void 0) - 1 ? true : false;
scope.isFirstCategory = currCat === 0 ? true : false;
scope.isFirstSlide = currSlide === 0 ? true : false;
return console.log(scope.currentCategory + ' : ' + scope.currentSlide);
};
scope.prevCategory = function() {
if (!scope.isFirstCategory) {
scope.currentCategory = scope.currentCategory - 1;
return scope.currentSlide = 0;
}
};
scope.nextCategory = function() {
if (!scope.isLastCategory) {
scope.currentCategory = scope.currentCategory + 1;
return scope.currentSlide = 0;
}
};
scope.prevSlide = function() {
if (!scope.isFirstSlide) {
return scope.currentSlide = scope.currentSlide - 1;
}
};
scope.nextSlide = function() {
if (!scope.isLastSlide) {
return scope.currentSlide = scope.currentSlide + 1;
}
};
scope.$watch('currentCategory', scope.updatePosition);
scope.$watch('currentSlide', scope.updatePosition);
Hammer(elm).on('swipeleft', function(e) {
e.gesture.srcEvent.preventDefault();
scope.$apply(scope.nextCategory);
return false;
});
Hammer(elm).on('swiperight', function(e) {
e.gesture.srcEvent.preventDefault();
scope.$apply(scope.prevCategory);
return false;
});
Hammer(elm).on('swipeup', function(e) {
e.gesture.srcEvent.preventDefault();
scope.$apply(scope.nextSlide);
return false;
});
Hammer(elm).on('swipedown', function(e) {
e.gesture.srcEvent.preventDefault();
scope.$apply(scope.prevSlide);
return false;
});
onKeyDown = function(e) {
if (!scope.$$phase) {
return scope.$apply(function() {
switch (e.keyCode) {
case 37:
return scope.prevCategory();
case 38:
return scope.prevSlide();
case 39:
return scope.nextCategory();
case 40:
return scope.nextSlide();
}
});
}
};
onMouseWheel = function(e) {
var delta, treshold;
delta = e.originalEvent.wheelDelta;
treshold = 100;
return scope.$apply(function() {
if (delta < -treshold) {
scope.nextSlide();
}
if (delta > treshold) {
return scope.prevSlide();
}
});
};
$($window).on('keydown', onKeyDown);
$($window).on('mousewheel', onMouseWheel);
$rootScope.$on('remote:control', function(e, data) {
return scope.$apply(function() {
switch (data.params.direction) {
case 'up':
return scope.prevSlide();
case 'down':
return scope.nextSlide();
case 'left':
return scope.prevCategory();
case 'right':
return scope.nextCategory();
}
});
});
scope.getCategoryClass = function(category) {
return 'haiku__category--' + (category.status || 'prev');
};
scope.getSlideClass = function(slide) {
return 'haiku__slide--' + (slide.status || 'prev');
};
scope.getSlideStyle = function(slide) {
return {
'background': slide.background || '#333',
'background-size': 'cover'
};
};
scope.isCurrentSlide = function(slide) {
return slide.index === scope.currentSlide && slide.categoryIndex === scope.currentCategory;
};
scope.goto = function(slide) {
scope.currentCategory = slide.categoryIndex;
return scope.currentSlide = slide.index;
};
scope.getThemeClass = function() {
return 'haiku--default';
};
scope.files = [];
return scope.onFileDropped = function(markdownContent) {
return _.defer(function() {
return scope.$apply(function() {
scope.categories = Slides.getFromMarkdown(markdownContent);
return scope.updatePosition();
});
});
};
}
};
}
]);
|
$(function () {
$(".logo-image").hover(
function () {
$('.logo-image.color').stop().animate({"opacity": "1"}, 600);
},
function () {
$('.logo-image.color').stop().animate({"opacity": "0"}, 100);
});
// $("img.lazy").lazyload();
$('.bxslider').bxSlider({
mode: 'fade',
auto: false,
// autoControls: true,
nextText: "",
prevText: "",
pause: 2000,
slideWidth: 450,
responsive: false,
adaptiveHeight: false,
pager:false
});
$('.modalBXSlider').bxSlider({
mode: 'fade',
auto: true,
autoControls: true,
pause: 2000
});
var slider = $('#slider').leanSlider({
directionNav: '#slider-direction-nav',
controlNav: '#slider-control-nav'
});
}); |
import './node_check_edit_list.html';
import { Template } from 'meteor/templating';
import { RobaDialog } from 'meteor/austinsand:roba-dialog';
import { NodeChecks } from '../../../../imports/api/nodes/node_checks.js';
import { NodeCheckTypes, NodeCheckTypesLookup } from '../../../../imports/api/nodes/node_check_types.js';
import { NodeReadyCheckFns } from '../../../../imports/api/nodes/node_ready_check_fns.js';
import { NodeValidCheckFns } from '../../../../imports/api/nodes/node_valid_check_fns.js';
import { Util } from '../../../../imports/api/util.js';
import '../editable_fields/editable_enum selector.js';
import '../editable_fields/editable_xpath.js';
/**
* Template Helpers
*/
Template.NodeCheckEditList.helpers({
/**
* Get the list of node checks for this node
*/
nodeChecks () {
return NodeChecks.find({
parentId : this.node.staticId,
projectVersionId: this.node.projectVersionId,
type : this.type
});
},
/**
* Get the correct enum for this list
*/
checkFnType () {
return Util.camelToTitle(NodeCheckTypesLookup[ this.type ])
},
/**
* Get the correct enum for this list
*/
checkFnEnum () {
if (this.type == NodeCheckTypes.ready) {
return NodeReadyCheckFns;
} else {
return NodeValidCheckFns;
}
},
/**
* Get the list of args for this function
*/
checkFnArgList () {
let fnList = this.type == NodeCheckTypes.ready ? NodeReadyCheckFns : NodeValidCheckFns,
checkFn = fnList[ this.checkFn ];
if (checkFn && checkFn.args && checkFn.args.length) {
return checkFn.args
}
},
/**
* Get the list of args for this function
*/
checkFnArgEmptyText () {
let fnList = this.type == NodeCheckTypes.ready ? NodeReadyCheckFns : NodeValidCheckFns,
checkFn = fnList[ this.checkFn ];
if (checkFn && checkFn.args && checkFn.args.length) {
//console.log("checkFnArgEmptyText: ", checkFn.args[0].label);
return checkFn.args[ 0 ].label
}
}
});
/**
* Template Event Handlers
*/
Template.NodeCheckEditList.events({
"edited .editable"(e, instance, newValue){
e.stopImmediatePropagation();
let target = $(e.target),
checkId = target.closest(".sortable-table-row").attr("data-pk"),
dataKey = target.attr("data-key"),
update = { $set: {} };
update.$set[ dataKey ] = newValue;
console.log("Edited: ", checkId, dataKey, newValue, update);
if (checkId && dataKey) {
NodeChecks.update({ _id: checkId }, update, (error) => {
if (error) {
RobaDialog.error("Update failed: " + error.toString());
}
});
}
},
"click .btn-delete"(e, instance){
let target = $(e.target),
checkId = target.closest(".sortable-table-row").attr("data-pk");
RobaDialog.ask("Delete Server?", "Are you sure that you want to delete this check?", () => {
NodeChecks.remove(checkId, function (error, response) {
RobaDialog.hide();
if (error) {
RobaDialog.error("Delete failed: " + error.message);
}
});
}
);
}
});
/**
* Template Created
*/
Template.NodeCheckEditList.onCreated(() => {
});
/**
* Template Rendered
*/
Template.NodeCheckEditList.onRendered(() => {
let instance = Template.instance();
// Setup the sortable table
instance.$(".sortable-table")
.sortable({
items : "> .sortable-table-row",
handle : ".drag-handle",
helper(e, ui) {
// fix the width
ui.children().each(function () {
$(this).width($(this).width());
});
return ui;
},
axis : "y",
forcePlaceholderSize: true,
update(event, ui) {
var order;
instance.$(".sortable-table-row").each(function (i, el) {
order = $(el).attr("data-sort-order");
if (order != i) {
console.log("Updating order: ", i, $(el).attr("data-pk"));
NodeChecks.update($(el).attr("data-pk"), { $set: { order: i } }, function (error, response) {
if (error) {
RobaDialog.error("Order update failed: " + error.message);
}
});
}
});
}
})
.disableSelection();
// Make sure items added to the list are sortable
instance.autorun(function () {
let data = Template.currentData(),
nodeChecks = NodeChecks.find({
parentId : data.node.staticId,
projectVersionId: data.node.projectVersionId,
type : data.type
});
instance.$(".sortable-table").sortable("refresh");
});
});
/**
* Template Destroyed
*/
Template.NodeCheckEditList.onDestroyed(() => {
});
|
requirejs.config({
paths : {
'vlib' : 'core/Vlib',
'config' : 'config.vlib',
'pluginLoader' : 'pluginLoader',
'jquery' : 'libs/jquery/jquery.min',
'underscore' : 'libs/underscore/underscore.min',
'three' : 'libs/three/build/three.min',
'three_trackball_controls' : 'libs/three/controls/TrackballControls',
'three_orbit_controls' : 'libs/three/controls/OrbitAndPanControls',
'orgChart' : 'libs/jOrgChart/jquery.jOrgChart',
'd3':'libs/novus/lib/d3.v3',
'nv':'libs/novus/nv.d3'
},
shim : {
'underscore' : {
exports : '_'
},
'three' : {
exports : 'THREE'
},
'three_trackball_controls' : {
exports : 'THREE',
'deps' : ['three']
},
'three_orbit_controls' : {
exports : 'THREE',
'deps' : ['three']
},
'orgChart' : {
exports : '$',
'deps' : ['jquery']
},
'd3':{
exports: 'd3'
},
'nv':{
'deps' : ['d3'],
exports: 'd3'
}
}
});
/**
* MAIN EDIT-MODE
*/
define(function(require) {
require(
[ 'jquery', 'config'],
function($,Config) {
var surface_1 = require('templates/t1_surface.tmpl.vlib');
var surface1 = {
sceneGraph : surface_1,
name : 'Surface test ',
description : 'T1: 3d surface and axes using a plane dataset. FUNCTION z = cos(x)'
};
// ************************************************************************
// INIT LIB
// ************************************************************************
var VLib = require('vlib');
var v = new VLib();
var plotModule = require('core/modules/plot/plot.vlib');
var plot = new plotModule();
var run = function(){
$('.vlib-plot').each(function(e){
var templ_id = $(this).attr('id');
var plot = new plotModule();
v.registerModule(plot);
plot.init('#'+templ_id);
//AJAX-load template
//var template = load(templ_id);
v.load(surface1,plot);
});
}
$(document).ready(function(){
run();
});
});
});
|
import * as api from '../api/app'
import { push } from 'react-router-redux';
import { submit } from 'redux-form'
export const requestResource = (resource_id, diff = 0) => ({
type : 'RESOURCE/REQUEST',
isFetching : true,
resource_id,
diff
})
export const requestCurrent = (resource_id) => ({
type : 'RESOURCE/CURRENT',
isFetching : true,
resource_id
})
export const failureResource = (resource_id, diff, response) => ({
type : 'RESOURCE/FAILURE',
isFetching : false,
resource_id,
diff,
data : response.data
})
export const successResource = (resource_id, diff, response) => ({
type : 'RESOURCE/SUCCESS',
isFetching : false,
resource_id,
diff,
data : response.data
})
export const emptyResource = (resource_id, diff) => ({
type : 'RESOURCE/EMPTY',
isFetching : false,
diff,
resource_id
})
export const openModal = () => ({
type : 'RESOURCE/OPEN_MODAL'
})
export const closeModal = () => ({
type : 'RESOURCE/CLOSE_MODAL'
})
// export const formSubmit = (form) => ({
// type : 'RESOURCE/FORM_SUBMIT',
// form
// })
export const formSubmitSuccess = () => ({
type : 'RESOURCE/FORM_SUBMIT_SUCCESS'
})
export const setStatus = (status) => ({
type : 'RESOURCE/SET_STATUS',
status
})
export const setInitialValues = (name, value) => ({
type : 'RESOURCE/INITIAL_VALUES',
name,
value
})
export const defer = (resource_id, minutes) => ({
type : 'RESOURCE/DEFER',
resource_id,
minutes
})
export const reserve = (resource_id, diff, commentary = "") => ({
type : 'RESOURCE/RESERVE',
resource_id,
diff,
commentary
})
export const transfer = (resource_id, manager_id, commentary = "") => ({
type : 'RESOURCE/TRANSFER',
resource_id,
manager_id,
commentary
})
export const anotherPhone = (resource_id, driver_id, phone) => ({
type : 'RESOURCE/ANOTHER_PHONE',
resource_id,
driver_id,
phone
})
export const formSubmit = (form) => {
return (dispatch, getState) => {
return api.formSubmit(form)
.then((response) => {
console.log(response)
if(response.data.success){
dispatch(formSubmitSuccess())
dispatch(push('/'))
}
})
}
}
export const fieldToggle = (resource_id, field, index, key, values) => ({
type : 'RESOURCE/FIELD_TOGGLE',
resource_id,
field,
index,
key,
values,
})
export const fieldReset = (field, key, values) => ({
type : 'RESOURCE/FIELD_RESET',
field,
key,
values,
})
export const fieldEdit = (field, key) => ({
type : 'RESOURCE/FIELD_EDIT',
field,
key,
})
export const fieldSave = (resource_id, field, key, values) => ({
type : 'RESOURCE/FIELD_SAVE',
resource_id,
field,
key,
values
})
export const fieldSaveFailure = (field, error) => ({
type : 'RESOURCE/FIELD_SAVE_FAILURE',
field,
error,
})
export const fieldToggleFailure = (field, error) => ({
type : 'RESOURCE/FIELD_TOGGLE_FAILURE',
field,
error,
})
export const driverFormInitialValues = (name, value) => ({
type : 'RESOURCE/INITIAL_VALUES_DRIVER',
name,
value
})
export const policyFormInitialValues = (name, value) => ({
type : 'RESOURCE/INITIAL_VALUES_POLICY',
name,
value
})
export const vehicleFormInitialValues = (name, value) => ({
type : 'RESOURCE/INITIAL_VALUES_VEHICLE',
name,
value
})
export const formSubmitButton = (form) => {
return submit(form)
}
//
// export const getResource = (resource_id, diff) => {
// return (dispatch, getState) => {
// dispatch(requestResource(resource_id))
// return api.get(resource_id, diff)
// .then(response => {
// if(Object.keys(response.data).length === 0){
// dispatch(emptyResource(resource_id, diff))
// }
// else{
// dispatch(successResource(resource_id, diff, response))
// }
// })
// .catch(error => {
// dispatch(failureResource(resource_id, error.response))
// })
// }
// }
//
// export const reserve = (resource_id, diff, commentary) => {
// return (dispatch, getState) => {
// return api.reserve(resource_id, diff, commentary)
// .then((response) => {
// if(response.data.success){
// dispatch(formSubmited())
// dispatch(closeModal())
// dispatch(push('/'))
// }
// })
// }
// }
//
// export const defer = (resource_id, minutes) => {
// return (dispatch, getState) => {
// return api.defer(resource_id, minutes)
// .then((response) => {
// if(response.data.success){
// dispatch(formSubmited())
// dispatch(closeModal())
// dispatch(push('/'))
// }
// })
// }
// }
|
$(function(){$.widget("primeui.puicarousel",{options:{datasource:null,numVisible:3,firstVisible:0,headerText:null,effectDuration:500,circular:false,breakpoint:560,itemContent:null,responsive:true,autoplayInterval:0,easing:"easeInOutCirc",pageLinks:3,styleClass:null},_create:function(){this.id=this.element.attr("id");
if(!this.id){this.id=this.element.uniqueId().attr("id")
}this.element.wrap('<div class="pui-carousel ui-widget ui-widget-content ui-corner-all"><div class="pui-carousel-viewport"></div></div>');
this.container=this.element.parent().parent();
this.element.addClass("pui-carousel-items");
this.container.prepend('<div class="pui-carousel-header ui-widget-header"><div class="pui-carousel-header-title"></div></div>');
this.viewport=this.element.parent();
this.header=this.container.children(".pui-carousel-header");
this.header.append('<span class="pui-carousel-button pui-carousel-next-button fa fa-arrow-circle-right"></span><span class="pui-carousel-button pui-carousel-prev-button fa fa-arrow-circle-left"></span>');
if(this.options.headerText){this.header.children(".pui-carousel-header-title").html(this.options.headerText)
}if(this.options.styleClass){this.container.addClass(this.options.styleClass)
}if(this.options.datasource){this._loadData()
}else{this._render()
}},_loadData:function(){if($.isArray(this.options.datasource)){this._render(this.options.datasource)
}else{if($.type(this.options.datasource)==="function"){this.options.datasource.call(this,this._render)
}}},_updateDatasource:function(a){this.options.datasource=a;
this.element.children().remove();
this.header.children(".pui-carousel-page-links").remove();
this.header.children("select").remove();
this._loadData()
},_render:function(b){this.data=b;
if(this.data){for(var a=0;
a<b.length;
a++){var c=this.options.itemContent.call(this,b[a]);
if($.type(c)==="string"){this.element.append("<li>"+c+"</li>")
}else{this.element.append($("<li></li>").wrapInner(c))
}}}this.items=this.element.children("li");
this.items.addClass("pui-carousel-item ui-widget-content ui-corner-all");
this.itemsCount=this.items.length;
this.columns=this.options.numVisible;
this.first=this.options.firstVisible;
this.page=parseInt(this.first/this.columns);
this.totalPages=Math.ceil(this.itemsCount/this.options.numVisible);
this._renderPageLinks();
this.prevNav=this.header.children(".pui-carousel-prev-button");
this.nextNav=this.header.children(".pui-carousel-next-button");
this.pageLinks=this.header.find("> .pui-carousel-page-links > .pui-carousel-page-link");
this.dropdown=this.header.children(".pui-carousel-dropdown");
this.mobileDropdown=this.header.children(".pui-carousel-mobiledropdown");
this._bindEvents();
if(this.options.responsive){this.refreshDimensions()
}else{this.calculateItemWidths();
this.container.width(this.container.width());
this.updateNavigators()
}},_renderPageLinks:function(){if(this.totalPages<=this.options.pageLinks){this.pageLinksContainer=$('<div class="pui-carousel-page-links"></div>');
for(var b=0;
b<this.totalPages;
b++){this.pageLinksContainer.append('<a href="#" class="pui-carousel-page-link fa fa-circle-o"></a>')
}this.header.append(this.pageLinksContainer)
}else{this.dropdown=$('<select class="pui-carousel-dropdown ui-widget ui-state-default ui-corner-left"></select>');
for(var b=0;
b<this.totalPages;
b++){var a=(b+1);
this.dropdown.append('<option value="'+a+'">'+a+"</option>")
}this.header.append(this.dropdown)
}if(this.options.responsive){this.mobileDropdown=$('<select class="pui-carousel-mobiledropdown ui-widget ui-state-default ui-corner-left"></select>');
for(var b=0;
b<this.itemsCount;
b++){var a=(b+1);
this.mobileDropdown.append('<option value="'+a+'">'+a+"</option>")
}this.header.append(this.mobileDropdown)
}},calculateItemWidths:function(){var b=this.items.eq(0);
if(b.length){var a=b.outerWidth(true)-b.width();
this.items.width((this.viewport.innerWidth()-a*this.columns)/this.columns)
}},refreshDimensions:function(){var a=$(window);
if(a.width()<=this.options.breakpoint){this.columns=1;
this.calculateItemWidths(this.columns);
this.totalPages=this.itemsCount;
this.mobileDropdown.show();
this.pageLinks.hide()
}else{this.columns=this.options.numVisible;
this.calculateItemWidths();
this.totalPages=Math.ceil(this.itemsCount/this.options.numVisible);
this.mobileDropdown.hide();
this.pageLinks.show()
}this.page=parseInt(this.first/this.columns);
this.updateNavigators();
this.element.css("left",(-1*(this.viewport.innerWidth()*this.page)))
},_bindEvents:function(){var b=this;
if(this.eventsBound){return
}this.prevNav.on("click.puicarousel",function(){if(b.page!==0){b.setPage(b.page-1)
}else{if(b.options.circular){b.setPage(b.totalPages-1)
}}});
this.nextNav.on("click.puicarousel",function(){var c=(b.page===(b.totalPages-1));
if(!c){b.setPage(b.page+1)
}else{if(b.options.circular){b.setPage(0)
}}});
this.element.swipe({swipe:function(c,d){if(d==="left"){if(b.page===(b.totalPages-1)){if(b.options.circular){b.setPage(0)
}}else{b.setPage(b.page+1)
}}else{if(d==="right"){if(b.page===0){if(b.options.circular){b.setPage(b.totalPages-1)
}}else{b.setPage(b.page-1)
}}}}});
if(this.pageLinks.length){this.pageLinks.on("click",function(c){b.setPage($(this).index());
c.preventDefault()
})
}this.header.children("select").on("change",function(){b.setPage(parseInt($(this).val())-1)
});
if(this.options.autoplayInterval){this.options.circular=true;
this.startAutoplay()
}if(this.options.responsive){var a="resize."+this.id;
$(window).off(a).on(a,function(){b.refreshDimensions()
})
}this.eventsBound=true
},updateNavigators:function(){if(!this.options.circular){if(this.page===0){this.prevNav.addClass("ui-state-disabled");
this.nextNav.removeClass("ui-state-disabled")
}else{if(this.page===(this.totalPages-1)){this.prevNav.removeClass("ui-state-disabled");
this.nextNav.addClass("ui-state-disabled")
}else{this.prevNav.removeClass("ui-state-disabled");
this.nextNav.removeClass("ui-state-disabled")
}}}if(this.pageLinks.length){this.pageLinks.filter(".fa-dot-circle-o").removeClass("fa-dot-circle-o");
this.pageLinks.eq(this.page).addClass("fa-dot-circle-o")
}if(this.dropdown.length){this.dropdown.val(this.page+1)
}if(this.mobileDropdown.length){this.mobileDropdown.val(this.page+1)
}},setPage:function(b){if(b!==this.page&&!this.element.is(":animated")){var a=this;
this.element.animate({left:-1*(this.viewport.innerWidth()*b),easing:this.options.easing},{duration:this.options.effectDuration,easing:this.options.easing,complete:function(){a.page=b;
a.first=a.page*a.columns;
a.updateNavigators();
a._trigger("pageChange",null,{page:b})
}})
}},startAutoplay:function(){var a=this;
this.interval=setInterval(function(){if(a.page===(a.totalPages-1)){a.setPage(0)
}else{a.setPage(a.page+1)
}},this.options.autoplayInterval)
},stopAutoplay:function(){clearInterval(this.interval)
},_setOption:function(a,b){if(a==="datasource"){this._updateDatasource(b)
}else{$.Widget.prototype._setOption.apply(this,arguments)
}},_destroy:function(){}})
}); |
import Util from '../common/Util';
import Activity from './Activity';
import UserPointer from './UserPointer';
import UserKeyboard from './UserKeyboard';
class SelectCoords extends Activity {
constructor(...args) {
super(...args);
this.init();
}
/**
* Initialises local helpers
*/
init() {
this.dispatcher = new Util.EventDispatcher();
this.prepareCallbacks();
}
/**
* Sets the callbacks against user events
*/
prepareCallbacks() {
this.onSelect = (mousePointer) => {
this.dispatcher.dispatch('select', mousePointer);
if (this.cancelable !== false) {
this.getActivityManager().willBeCanceled();
}
};
this.onCancel = () => {
this.dispatcher.dispatch('cancel');
this.getActivityManager().cancel();
};
}
/**
* Activates the Activity
*/
activate() {
super.activate();
UserPointer.getInstance().on('leftbutton/down/activity', this.onSelect);
UserPointer.getInstance().on('rightbutton/down/activity', this.onCancel);
UserKeyboard.getInstance().on('key/esc', this.onCancel);
}
/**
* Removes event listeners and tear down helpers
*/
deactivate() {
super.deactivate();
UserPointer.getInstance().remove('leftbutton/down/activity', this.onSelect);
UserPointer.getInstance().remove(
'rightbutton/down/activity',
this.onCancel,
);
UserKeyboard.getInstance().remove('key/esc', this.onCancel);
}
/**
* Registers listeners against the given event
* @param {string} event - event id
* @param {function} callback
*/
on(event, callback) {
this.dispatcher.addEventListener(event, callback);
}
/**
* Flags the Acticity so that it won't cancel itself on select.
*/
doNotCancel() {
this.cancelable = false;
}
/**
* Flags the Acticity that it can be cancelled.
*/
doCancel() {
this.cancelable = true;
}
}
export default SelectCoords;
|
function matchTrackingsOnShopotam(){var a=chrome.i18n.getMessage("track_package"),b=0;$("a[title='отследить посылку']").each(function(){b++;var c=$(this).text();if(c&&void 0!==c){var d=GdePosylkaExt.generateGoUrlSync("/detect/"+c);$('<a href="'+d+'" target="_blank" class="button button-danger button-mini shopotam-track-it_'+b+'">'+a+"</a>").insertAfter($(this)),$(".shopotam-track-it_"+b).click(function(a){a.preventDefault(),locateItOnTab(c,{},"Отслеживание","ShopoTam: список посылок","Ссылка отслеживания")})}})}checkSiteAllowedForTracking("shopotam.ru",function(){matchTrackingsOnShopotam()}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.