code stringlengths 2 1.05M |
|---|
// import routes
import { matchRoutes } from 'react-router-config';
import Routes from './../../client/routes/Routes';
import renderer from './renderer';
import template from './template';
import createStore from './createStore';
module.exports = (app, req, res) => {
// set up the redux store on the server side
const store = createStore(req);
// check all react routes vs req path and return a list of components to be rendered
const promises = matchRoutes(Routes, req.path).map(({ route }) => (
// if route.loadData exists then call loadData(), else do nothing
route.loadData ? route.loadData(store) : null)
).map(promise => {
// if null value from promise (something went wrong)
if (promise) {
return new Promise((resolve) => {
// return a resolved promise
promise.then(resolve).catch(resolve);
});
}
return null;
});
// once all our data requests have been completed
Promise.all(promises).then(() => {
const context = {};
const content = renderer(req, store, context);
const response = template(req, store, content);
// context.url = req.path;
// if a url is loaded into the context then redirect to the url in the context
if (context.url) return res.redirect(301, context.url);
// if context has not found stored then respond with 404 error
if (context.notFound) res.status(404);
// send initialised store to the renderer
res.send(response);
});
};
|
import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../actions/backpackActions';
class Backpack extends Component {
componentDidMount() {
this.props.recalcutateTotalPrice();
}
handleAddItem(id) {
this.props.addItemToBackpack(id);
}
handleDelItem(id) {
this.props.delItemFromBackpack(id);
}
handleRemoveItem(id) {
this.props.removeItemFromBackpack(id);
}
handleRecalculate() {
this.props.recalcutateTotalPrice();
}
handleDiscard(id) {
this.props.discardBackpack(id);
}
handleSave(backpack) {
this.props.saveBackpack(backpack);
}
handleCheckout(id) {
this.props.checkoutBackpack(id);
}
handleDate(e) {
this.props.changeRentalDuration(e.target.value);
}
renderItems() {
if (!this.props.backpack) {
return (
<tr>
<td>Empty Items DB...</td>
</tr>
);
}
if (!this.props.backpack.items) {
return (
<tr>
<td>Loading Items...</td>
</tr>
);
}
return this.props.backpack.items.map(item => {
return this.renderItem(item);
});
}
renderItem(item) {
const i = _.findIndex(this.props.items, ['_id', item._id]);
const { name, price } = this.props.items[i];
return (
<tr key={item._id} style={{ textAlign: 'center' }}>
<td>{name}</td>
<td>{item.itemQuantity}</td>
<td>{price}</td>
</tr>
);
}
renderBackPack() {
if (this.props.backpack) {
return (
<div
className="col-lg-3 d-md-none d-lg-block bg-info"
style={{ maxWidth: '100%', height: '100%' }}
>
<div className="row py-2">
<div>
<div className="pt-4 pb-4 ">
<h5 className="text-center">
Rental Duration{' '}
<select
className="btn-warning"
onChange={this.handleDate.bind(this)}
value={this.props.backpack.rentalDuration}
>
<option>1</option>
<option>5</option>
<option>10</option>
</select>
{' '}
days
</h5>
</div>
<table className="px-2 table table-light table-striped">
<thead>
<tr className="bg-warning">
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
</tr>
</thead>
<tbody>
{this.renderItems()}
<tr style={{ textAlign: 'center' }}>
<td colSpan="3" className="font-weight-bold">
Total: {this.props.backpack.totalPrice}€
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div className="row py-2">
<div className="btn-group mx-auto">
<button
className="btn btn-dark"
onClick={this.handleRecalculate.bind(this)}
>
ReCalculate
</button>
<button
onClick={this.handleCheckout.bind(
this,
this.props.backpack._id
)}
className="btn btn-secondary"
type="button"
>
Checkout
</button>
<button
type="button"
className="btn btn-warning dropdown-toggle dropdown-toggle-split"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false"
>
<span className="sr-only">Toggle Dropdown</span>
</button>
<div className="dropdown-menu">
<a
className="dropdown-item"
onClick={this.handleDiscard.bind(
this,
this.props.backpack._id
)}
href="#"
>
Discard
</a>
<a
className="dropdown-item"
onClick={this.handleSave.bind(this, this.props.backpack)}
href="#"
>
Save
</a>
</div>
</div>
</div>
</div>
);
}
}
render() {
//console.log('render', this.props);
return <div>{this.renderBackPack()}</div>;
}
}
function mapStateToProps(state) {
//console.log(state);
return {
backpack: state.backpack,
user: state.user,
items: state.items,
isLoading: state.isLoading,
hasErrored: state.hasErrored
};
}
export default connect(mapStateToProps, actions)(Backpack);
|
/* global module:false */
module.exports = function(grunt) {
var port = grunt.option('port') || 8000;
// Project configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
meta: {
banner:
'/*!\n' +
' * reveal.js <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' +
' * http://lab.hakim.se/reveal-js\n' +
' * MIT licensed\n' +
' *\n' +
' * Copyright (C) 2014 Hakim El Hattab, http://hakim.se\n' +
' */'
},
qunit: {
files: [ 'test/*.html' ]
},
uglify: {
options: {
banner: '<%= meta.banner %>\n'
},
build: {
src: 'js/reveal.js',
dest: 'js/reveal.min.js'
}
},
cssmin: {
compress: {
files: {
'css/reveal.min.css': [ 'css/reveal.css' ]
}
}
},
sass: {
main: {
files: {
'css/theme/default.css': 'css/theme/source/default.scss',
'css/theme/beige.css': 'css/theme/source/beige.scss',
'css/theme/night.css': 'css/theme/source/night.scss',
'css/theme/serif.css': 'css/theme/source/serif.scss',
'css/theme/simple.css': 'css/theme/source/simple.scss',
'css/theme/rb_simple.css': 'css/theme/source/rb_simple.scss',
'css/theme/sky.css': 'css/theme/source/sky.scss',
'css/theme/moon.css': 'css/theme/source/moon.scss',
'css/theme/solarized.css': 'css/theme/source/solarized.scss',
'css/theme/blood.css': 'css/theme/source/blood.scss'
}
}
},
jshint: {
options: {
curly: false,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
eqnull: true,
browser: true,
expr: true,
globals: {
head: false,
module: false,
console: false,
unescape: false
}
},
files: [ 'Gruntfile.js', 'js/reveal.js' ]
},
connect: {
server: {
options: {
port: port,
base: '.'
}
}
},
zip: {
'reveal-js-presentation.zip': [
'index.html',
'css/**',
'js/**',
'lib/**',
'images/**',
'plugin/**'
]
},
watch: {
main: {
files: [ 'Gruntfile.js', 'js/reveal.js', 'css/reveal.css' ],
tasks: 'default'
},
theme: {
files: [ 'css/theme/source/*.scss', 'css/theme/template/*.scss' ],
tasks: 'themes'
}
}
});
// Dependencies
grunt.loadNpmTasks( 'grunt-contrib-qunit' );
grunt.loadNpmTasks( 'grunt-contrib-jshint' );
grunt.loadNpmTasks( 'grunt-contrib-cssmin' );
grunt.loadNpmTasks( 'grunt-contrib-uglify' );
grunt.loadNpmTasks( 'grunt-contrib-watch' );
grunt.loadNpmTasks( 'grunt-contrib-sass' );
grunt.loadNpmTasks( 'grunt-contrib-connect' );
grunt.loadNpmTasks( 'grunt-zip' );
// Default task
grunt.registerTask( 'default', [ 'jshint', 'cssmin', 'uglify', 'qunit' ] );
// Theme task
grunt.registerTask( 'themes', [ 'sass' ] );
// Package presentation to archive
grunt.registerTask( 'package', [ 'default', 'zip' ] );
// Serve presentation locally
grunt.registerTask( 'serve', [ 'connect', 'watch' ] );
// Run tests
grunt.registerTask( 'test', [ 'jshint', 'qunit' ] );
};
|
export function convertRegionToBounds(region) {
const {
latitude: centerLat,
longitude: centerLong,
latitudeDelta,
longitudeDelta,
} = region;
return {
north: centerLat + latitudeDelta,
south: centerLat - latitudeDelta,
west: centerLong - longitudeDelta,
east: centerLong + longitudeDelta,
};
}
export function convertBoundsToRegion(bounds) {
const {
north,
south,
east,
west,
} = bounds;
const latitude = (north + south) / 2;
const longitude = (east + west) / 2;
const latitudeDelta = Math.abs(north - latitude);
const longitudeDelta = Math.abs(east - longitude);
return {
latitude,
longitude,
latitudeDelta,
longitudeDelta,
};
}
|
import React from 'react';
import { Redirect } from 'react-static';
//
export default () => <Redirect to="/" />;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const crosshair_1 = require("./crosshair");
it("decode crosshair", () => {
expect((0, crosshair_1.decodeCrosshairCode)("CSGO-miBcy-2S2P7-h9var-ZqwE3-wmb3K")).toEqual({
alpha: 205,
blue: 47,
gap: 1.0,
green: 253,
hasAlpha: false,
hasCenterDot: true,
hasOutline: true,
innerSplitAlpha: 1,
isTStyle: false,
length: 3,
outerSplitAlpha: 0.5,
outline: 1,
red: 55,
splitDistance: 7,
splitSizeRatio: 0.3,
style: "ClassicDynamic",
thickness: 0.5
});
expect((0, crosshair_1.decodeCrosshairCode)("CSGO-TJ2Ft-7QNVV-UwtJJ-uNFVb-BVJGG")).toEqual({
alpha: 36,
blue: 184,
gap: -3.5,
green: 64,
hasAlpha: true,
hasCenterDot: false,
hasOutline: false,
innerSplitAlpha: 0.1,
isTStyle: true,
length: 6.1,
outerSplitAlpha: 0.8,
outline: 2,
red: 123,
splitDistance: 12,
splitSizeRatio: 0.5,
style: "Classic",
thickness: 4.8
});
});
it("invalid share code throws", () => {
expect(() => {
(0, crosshair_1.decodeCrosshairCode)("CZG0-TJ2Ft-7QNVV-UwtJJ-uNFVb-BVJGF");
}).toThrowError("invalid share code");
});
it("invalid crosshair code throws", () => {
expect(() => {
(0, crosshair_1.decodeCrosshairCode)("CSGO-TJ2Ft-7QNVV-UwtJJ-uNFVb-BVJGF");
}).toThrowError("invalid crosshair code");
});
//# sourceMappingURL=crosshair.test.js.map |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function(){
"use strict";
function EventEmitter(){
this.events = {};
}
EventEmitter.prototype.on = function(eventName, callback, instance) {
if(!this.events[eventName]) {
this.events[eventName] = [];
}
this.events[eventName].push({callback : callback, instance : instance});
};
EventEmitter.prototype.trigger = function(events) {
var args = Array.prototype.slice.call(arguments);
args.shift();
if(!Array.isArray(events)) {
events = [events];
}
for(var i = 0; i < events.length; i++) {
var eventName = events[i],
splitName = eventName.split("*");
if(splitName.length <= 1){
if(!this.events[eventName]) {
continue;
}
for(var o = 0; o < this.events[eventName].length; o++) {
this.events[eventName][o].callback.apply(this.events[eventName][o].instance , args);
}
} else{
for(var x in this.events) {
if(x.indexOf(splitName[1]) > -1) {
eventName = x;
for(var o = 0; o < this.events[eventName].length; o++) {
this.events[eventName][o].callback.apply(this.events[eventName][o].instance, args);
}
}
}
}
}
};
module.exports = EventEmitter;
})();
},{}],2:[function(require,module,exports){
(function() {
"use strict";
var EventEmitter = require("./events");
// Detect if we have a touch event
var isTouch = !!('ontouchstart' in window);
var eventName = (isTouch) ? 'touchmove' : 'mousemove';
//request anim frame, allow fluid gameLoop to draw canvases
var requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
/**
* ScratchCard component
* Ex configuration
* {
* "picture" : [{ // Different conditions
* "path" : "images",
* "file": "step2.jpg",
* "luck" : 60 // luck percentage for this step,
* "event" : "fail", // name of the event to trigger
* },{
* "path" : "images",
* "file": "step3.jpg",
* "luck" : 40,
* "event" : "success",
* }],
* "foreground" : {
* "path" : "images",
* "file" : "step1.jpg"
* },
* "brushRadius" : 40, // Width of the scracth touch
* "minCompletion" : 40 // Percentage to trigger the event,
* "width" : 500, // Width of the canvas
* "height" : 500 // Height of the canvas
* }
* @param {DOMElement} element
* @param {Object} params
*/
function ScratchCard(element,params) {
EventEmitter.call(this);
this.$el = element;
this.params = params;
this.canvas = {};
this.complete = false;
this.eventName = 'error';
this.requestId = 'error';
var init = function init(self) {
Kiwapp.log('[ScratchCard@init] Create a new instance of the game');
Kiwapp.log('[ScratchCard@init] configuration : ' + JSON.stringify(params));
self.$el.innerHTML = '';
self.params.brushRadius = self.params.brushRadius || 40;
self.params.minCompletion = self.params.minCompletion || 50;
self.setSize();
self.make();
self.loop();
return self.canvas;
}(this);
}
ScratchCard.prototype = Object.create(EventEmitter.prototype);
/**
* Draw the canvas and the buffer
*/
ScratchCard.prototype.draw = function() {
var render = this.canvas,
height = this.params.height,
width = this.params.width;
// Clean the canvas
render.ctx.clearRect(0,0,width,height);
//draw foreground
if (render.foreground !== null) {
render.ctx.drawImage(render.foreground,0,0,width,height);
}
// debugger;
//draw the already scrached surface on it
render.ctx.drawImage(render.buffer,0,0,width,height);
};
/**
* RequestAnimation frame loop to draw the game
*/
ScratchCard.prototype.loop = function() {
var that = this;
that.draw();
if(!this.complete) {
this.requestId = requestAnimFrame(function(){
that.loop();
});
}
};
/**
* Find teh condition for the current game based on your luck percentage's
*/
ScratchCard.prototype.chooseSituations = function() {
var leftChances = 100,
diceRoll = Math.random() * leftChances,
pictures = this.params.picture;
for (var i in pictures) {
if (diceRoll <= pictures[i].luck) {
return pictures[i];
}else {
leftChances -= pictures[i].luck;
diceRoll = Math.random() * leftChances;
}
}
};
/**
* Set size for the canvas based of the container if you do not set
* width and height in the params
*/
ScratchCard.prototype.setSize = function() {
var size = this.$el.getBoundingClientRect(),
that = this;
that.params.width = that.params.width || Math.round(size.width);
that.params.height = that.params.height || Math.round(size.height);
Kiwapp.log('[ScratchCard@setSize] Display the scracthcard for ' + that.params.width + 'x' + that.params.height);
};
/**
* Build the canvas and the buffer.
* @return {[type]} [description]
*/
ScratchCard.prototype.make = function() {
var canvas = document.createElement("canvas"),
buffer = document.createElement("canvas"),
img = new Image(),
foreground = new Image(),
params = this.params,
picture = this.chooseSituations();
canvas.id = 'canvas-' + Math.round(Math.random()*100);
buffer.id = 'canvas-' + Math.round(Math.random()*1001);
params.details = picture.details;
this.eventName = picture.event;
// Event listener to detect the scracth and if we have won
this.listener(canvas);
img.src = picture.path + '/' + picture.file;
img.width = canvas.width = buffer.width = params.width;
img.height = canvas.height = buffer.height = params.height;
var resizeBuffer = document.createElement("canvas");
var resizeBufferCtx = resizeBuffer.getContext("2d");
// peut etre virer canvas brush pas necessaire maybe
resizeBuffer.width = canvas.width;
resizeBuffer.height = canvas.height;
// Append the canvas into the dom
this.$el.appendChild(canvas);
if("foreground" in params) {
foreground.src = params.foreground.path + '/' + params.foreground.file;
foreground.width = params.width;
foreground.height = params.height;
}
// My little config
this.canvas = {
"canvas" : canvas,
"ctx" : canvas.getContext("2d"),
"buffer" : buffer,
"bufferCtx" : buffer.getContext("2d"),
"img" : img,
"foreground" : foreground || null,
"grid" : this.generateGrid(canvas),
"fillCount" : 0,
"bufferSizer": resizeBuffer,
"resizeBufferCtx" : resizeBufferCtx,
"count" : 0
};
if("foreground" in params) {
foreground.src = params.foreground.path + '/' + params.foreground.file;
foreground.width = params.width;
foreground.height = params.height;
}
Kiwapp.log('[ScratchCard@make] The canvas is ready');
};
/**
* Set an invisible grid to allow completion tracking
* @param {DOMElement} canvas
* @return {Array} the grid
*/
ScratchCard.prototype.generateGrid = function(canvas) {
var grid = [];
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {
grid.push({
"width" : canvas.width/10,
"height" : canvas.width/10,
"x" : i*(canvas.width/10),
"y" : j*(canvas.height/10),
"active" : true
});
}
}
return grid;
};
/**
* Event listener
* -Detect the scracth completion
* -Detect if we have won based on this.minCompletion
* @param {DOMElement} element the canvas
*/
ScratchCard.prototype.listener = function(element) {
var that = this;
// Canvas listener
var listenerCanvas = function(e){
if(!that.complete) {
if( navigator.userAgent.match(/Android/i) ) {
e.preventDefault();
}
// Actions on the canvas
that.actions(e);
that.isComplete(element, listenerCanvas);
return;
}
};
element.addEventListener(eventName, listenerCanvas,false);
};
/**
* Some tasks to run when the user scracth
* @param {Event} evt
*/
ScratchCard.prototype.actions = function(evt) {
var mouseX = 0,
mouseY = 0,
config = this.canvas,
params = this.params,
gridLength = config.grid.length;
// Draw of the img into the canvas used for resize the img
if (this.canvas.count%30===0)
{
config.resizeBufferCtx.drawImage(config.img,0,0,config.canvas.width,config.canvas.height);
}
this.canvas.count++;
if(isTouch) {
mouseX = evt.targetTouches[0].pageX - (config.canvas.offsetLeft);
mouseY = evt.targetTouches[0].pageY - (config.canvas.offsetTop);
}else {
mouseX = evt.pageX;
mouseY = evt.pageY;
}
config.img.width = params.width;
config.img.height = params.height;
//we draw on the buffer the surface scratched by the mouse and the img use is from bufferSizer who containe one canvas use for resize img with canvas size.
config.bufferCtx.beginPath();
config.bufferCtx.fillStyle = config.bufferCtx.createPattern(config.bufferSizer, "no-repeat");
config.bufferCtx.arc(mouseX, mouseY, params.brushRadius, 0, 2*Math.PI, false);
config.bufferCtx.fill();
//we check if we have draw into a cell
for (var cellNum in config.grid) {
//if yes, we put the cell to an inactive state
if (!config.grid[cellNum].active){
continue;
}else if (
mouseX + params.brushRadius >= config.grid[cellNum].x &&
mouseX - params.brushRadius < config.grid[cellNum].x + config.grid[cellNum].width &&
mouseY + params.brushRadius >= config.grid[cellNum].y &&
mouseY - params.brushRadius < config.grid[cellNum].y + config.grid[cellNum].height) {
config.grid[cellNum].active = false;
}
}
//we refresh the fill percentage of the grid of the selected canvas
config.fillCount = 0;
for (var i = 0 ; i < gridLength ; i ++) {
if (!config.grid[i].active){
config.fillCount++;
}
}
};
/**
* Is it done ?
*/
ScratchCard.prototype.isComplete = function(element, callback) {
var that = this;
if(that.canvas.fillCount >= that.params.minCompletion) {
element.removeEventListener(eventName,callback);
that.complete = true;
that.trigger(that.eventName,that.params.details);
Kiwapp.log('[ScratchCard@isComplete] Trigger an event : ' + that.eventName);
}
return that.canvas.fillCount >= that.params.minCompletion;
};
window.ScratchCard = ScratchCard;
module.exports = ScratchCard;
})();
},{"./events":1}]},{},[2]) |
/**
* phantomjs script for printing presentations to PDF.
*
* Example:
* phantomjs print-pdf.js "http://lab.hakim.se/reveal-js?print-pdf" reveal-demo.pdf
*
* By Manuel Bieh (https://github.com/manuelbieh)
*/
// html2pdf.js
var page = new WebPage();
var system = require( 'system' );
var slideWidth = system.args[3] ? system.args[3].split( 'x' )[0] : 960;
var slideHeight = system.args[3] ? system.args[3].split( 'x' )[1] : 700;
page.viewportSize = {
width: slideWidth,
height: slideHeight
};
// TODO
// Something is wrong with these config values. An input
// paper width of 1920px actually results in a 756px wide
// PDF.
page.paperSize = {
width: Math.round( slideWidth * 2 ),
height: Math.round( slideHeight * 2 ),
border: 0
};
var inputFile = system.args[1] || 'index.html?print-pdf';
var outputFile = system.args[2] || 'slides.pdf';
if( outputFile.match( /\.pdf$/gi ) === null ) {
outputFile += '.pdf';
}
console.log( 'Printing PDF (Paper size: '+ page.paperSize.width + 'x' + page.paperSize.height +')' );
page.open( inputFile, function( status ) {
window.setTimeout( function() {
console.log( 'Printed succesfully' );
page.render( outputFile );
phantom.exit();
}, 1000 );
} );
|
/**
* @file app.js
* @desc Controllers for back-end connection and front-end services.
*/
/*********************************************************
* ALL Variables
**********************************************************/
var problemListApp = angular.module('ProblemListApp', []);
var LOGGING = true;
var PROBLEMS_TYPE = 'problems';
var homepage = {};
var categoryData = {};
var lastResponseTime = 0;
var clientOptions = {
orgName: 'sdipu',
appName: 'problemsolvinglist',
logging: LOGGING
};
/*********************************************************
* APIGEE Client Controller.
**********************************************************/
function doLogin(username, password) {
// if (LOGGING) console.log("+LOG IN");
//Call the login function below
homepage.apiClient.login(username, password, function (error, data, user) {
if (error) {
// if (LOGGING) console.log(error);
homepage.apiClient.set("token", null);
return alert(error.message || "Could not log in");
}
homepage.loggedIn = true;
homepage.client = user._data;
homepage.$apply();
});
}
function doLogout() {
// if (LOGGING) console.log("+LOG OUT");
homepage.apiClient.logoutAndDestroyToken(homepage.client.username, null, null, function (error, data) {
if (error) {
// if (LOGGING) console.log(error);
return alert(error.message || "Could not log out");
}
homepage.apiClient.set("token", null);
homepage.loggedIn = false;
homepage.$apply();
});
}
function getProblems() {
setTimeout(function () {
// if (LOGGING) console.log("+GET PROBLEMS");
var refreshButton = $("#refresh-button");
refreshButton.attr("disabled", true);
var options = {
endpoint: PROBLEMS_TYPE,
qs: {limit: 100000000}
};
homepage.apiClient.request(options, function (error, response) {
refreshButton.attr("disabled", false);
if (error) {
// if (LOGGING) console.log(error);
} else {
//console.log(response);
// check timestamp
if (response.timestamp < lastResponseTime) {
return;
}
lastResponseTime = response.timestamp;
// set problems
homepage.categoryData = {};
homepage.problems = response.entities;
//build category
homepage.problems.forEach(function (prob) {
formatProblem(prob);
if (prob.category) {
categoryData[prob.category] = prob.category;
}
});
// set category
homepage.categories = Object.getOwnPropertyNames(categoryData);
// if (LOGGING) console.log(homepage.problems);
homepage.$apply();
}
});
}, 10);
}
function addProblem(prob) {
var addButton = $("#add-button");
addButton.attr("disabled", true);
setTimeout(function () {
// if (LOGGING) console.log("+ADD PROBLEM");
// validity check
if (!validatePROB(prob)) return;
// if (LOGGING) console.log("++VALIDATED");
// define data type
formatProblem(prob);
prob.type = PROBLEMS_TYPE;
// send request to api client
homepage.apiClient.createEntity(prob, function (error, response) {
addButton.attr("disabled", false);
if (error) {
return alert(error.message || "Error - there was a problem creating the entity");
}
var addProb = $('#add-problem');
addProb.modal('hide');
addProb.find('form')[0].reset();
getProblems();
});
}, 10);
}
function deleteProblem(prob) {
if (!confirm("Are your sure to delete this problem?")) {
return;
}
var deleteButton = $("#delete-" + prob.uuid);
deleteButton.attr('disabled', true);
setTimeout(function () {
// if (LOGGING) console.log("+DELETE PROBLEM");
var properties = {
client: homepage.apiClient,
data: {
type: PROBLEMS_TYPE,
uuid: prob.uuid
}
};
// create a local Entity object that we can call destroy() on
var entity = new Apigee.Entity(properties);
// call the destroy() method to initiate the API DELETE request */
entity.destroy(function (error, response) {
if (error) {
deleteButton.attr('disabled', false);
return alert(error.message || "Error - there was a problem deleting the entity");
}
getProblems();
});
}, 10);
}
function updateUser() {
// if (LOGGING) console.log("+UPDATE USER");
homepage.loggedIn = homepage.apiClient.isLoggedIn();
setTimeout(function () {
homepage.apiClient.getLoggedInUser(function (err, data, user) {
homepage.client = user._data || {};
homepage.$apply();
});
}, 0);
}
/*********************************************************
* HomePage Controller
**********************************************************/
function canShow(prob) {
if (homepage.selectedCat && prob.category != homepage.selectedCat) {
return false;
}
if (homepage.filterText) {
var pin = homepage.filterText.toLowerCase().trim();
var hay = prob.name + " " + prob.link + " " + prob.category;
hay = hay.toLowerCase().trim();
return hay.search(pin) >= 0;
}
return true;
}
function sortBy(prop) {
homepage.problems.sort(function (a, b) {
return a[prop] < b[prop] ? -1 : a[prop] > b[prop];
});
homepage.sortedBy = prop;
}
(function () {
problemListApp.controller('HomePageController', ['$scope', function ($scope) {
homepage = $scope;
homepage.problem = {}; // for add problem
homepage.problems = []; // for problem list
homepage.categories = []; // for category list
homepage.selectedCat = ""; // for selected category
homepage.filterText = ""; // for search text
// load client
homepage.apiClient = new Apigee.Client(clientOptions);
// download and show list of problems
getProblems();
//setInterval(getProblems, 10000); // update in every 10sec
updateUser();
// define functions
homepage.sortBy = sortBy;
homepage.canShow = canShow;
homepage.doLogin = doLogin;
homepage.doLogout = doLogout;
homepage.deleteProblem = deleteProblem;
homepage.addProblem = addProblem;
homepage.loadProblems = getProblems;
homepage.setCategory = function (cat) {
homepage.selectedCat = cat;
};
homepage.clearFilter = function () {
homepage.filterText = "";
};
}]);
/****************************************************
* All Directives
****************************************************/
problemListApp.directive('navBar', function () {
return {
restrict: 'E',
templateUrl: 'views/navbar.html'
};
});
problemListApp.directive('problemList', function () {
return {
restrict: 'E',
templateUrl: 'views/problem-list.html'
};
});
problemListApp.directive('bottomBar', function () {
return {
restrict: 'E',
templateUrl: 'views/bottom.html'
};
});
problemListApp.directive('addProblems', function () {
return {
restrict: 'E',
templateUrl: 'views/add-problems.html'
};
});
problemListApp.directive('searchProblem', function () {
return {
restrict: 'E',
templateUrl: 'views/search-problems.html'
};
});
problemListApp.directive('loginForm', function () {
return {
restrict: 'E',
templateUrl: 'views/login-form.html'
};
});
problemListApp.directive('problemToolbar', function () {
return {
restrict: 'E',
templateUrl: 'views/problem-toolbar.html'
};
});
})();
|
require(['app']) |
module.exports = (function (){
function Templar(){
}
Templar.prototype.sayHello() = function (){
return 'hello'
}
return Templar
})()
|
(function () {
// Copiado do Detector do Mr Doob - THREE JS
ON_DAED["WEBGL_SUPPORT"] = (function () {
try {
return !!window.WebGLRenderingContext && !!document.createElement('canvas').getContext('experimental-webgl');
} catch (e) {
return false;
}
})();
ON_DAED["3D"] = {};
ON_DAED["3D"].objects = [];
ON_DAED["3D"].intersectObjects = [];
ON_DAED["3D"].workerLogica = new Worker('lib/on-daed-js/worker.js');
// private
var texturesTextLabel = {};
var TEXT_LABEL = {
PONTO_VERNAL: "ɤ",
ECLIPTICA: "ε",
ASCENSAO_RETA: "α",
DECLINACAO: "δ",
LATITUDE_ECLIPTICA: "β",
LONGITUDE_ECLIPTICA: "λ",
LATITUDE_GALACTICA: "b",
LONGITUDE_GALACTICA: "l",
LATITUDE_SUPERGALACTICA: "B",
LONGITUDE_SUPERGALACTICA: "L",
ALTURA: "h",
AZIMUTE: "A",
NORTE: "N",
SUL: "S",
OESTE: "O",
LESTE: "L",
ZENITE: "z",
PONTO_LIBRA: "Ω"
};
ON_DAED["3D"].TEXT_LABEL = TEXT_LABEL;
ON_DAED["3D"].createTextLabel = function (cod, parent) {
if (!texturesTextLabel[cod]) {
texturesTextLabel[cod] = criarTexturaLetraComBorda(cod);
}
var texture = texturesTextLabel[cod];
var mat = new THREE.SpriteMaterial({
map: texture
});
var obj = new THREE.Sprite(mat);
obj.scale.multiplyScalar(40);
if (parent) {
parent.add(obj);
}
return obj;
};
ON_DAED["3D"].addQtipHelp = function (scene, object, showCallback, clickCallback) {
object.mover = function (event) {
if ($('.qtip:visible').length === 0) {
showCallback(object);
}
};
object.mout = function (event) {
$('.qtip').qtip('hide');
};
if (clickCallback instanceof Function) {
object.mclick = function (event) {
clickCallback(object);
};
}
ON_DAED["3D"].register(scene, object, function () {
});
};
var flareObject = null;
ON_DAED["3D"].ativarFlaresSol = function (cb) {
if ($('#load-modal').data('loadOBJMTL') instanceof Function) {
var flareMat = new THREE.MeshBasicMaterial();
flareMat.side = THREE.DoubleSide;
flareMat.transparent = true;
flareMat.map = new THREE.ImageUtils.loadTexture("lib/on-daed-js/models/sol/uv-test2.png");
flareMat.depthWrite = false;
flareMat.color = new THREE.Color(0xFF0000);
$('#load-modal').data('loadOBJMTL')('sol', 'lib/on-daed-js/models/sol/solarflare.obj', 'lib/on-daed-js/models/sol/solarflare.mtl', function (object) {
object.scale.multiplyScalar(50);
var wrap = new THREE.Object3D();
object.traverse(function (o) {
if (o.material instanceof THREE.MeshPhongMaterial || o.material instanceof THREE.MeshLambertMaterial) {
o.material = flareMat;
}
});
wrap.add(object);
flareObject = wrap;
if (cb instanceof Function) {
cb();
}
});
}
};
ON_DAED["3D"].criarSol = function (scene) {
var tamanho = 90;
var sol = new THREE.Mesh(
new THREE.SphereGeometry(tamanho, 64, 32),
new THREE.MeshBasicMaterial({
color: 0xFFFF00,
map: THREE.ImageUtils.loadTexture('imgs/texturas/sol/sol.png')
})
);
var objetoSol = new THREE.Object3D();
objetoSol.add(sol);
var brilho = new THREE.Sprite(
new THREE.SpriteMaterial({
map: THREE.ImageUtils.loadTexture('imgs/texturas/sol/glow.png'),
depthBuffer: false
}));
var mod = 4.5;
var escalaBase = tamanho / mod;
objetoSol.add(brilho);
var factSolAnimacao = 0;
var flares = [];
function addFlare() {
var flare = flareObject.clone();
var scale = 1 - parseInt(Math.random() * 4) / 10;
flare.children[0].children[0].children[1].position.z = -1;
flare.children[0].children[0].children[1].scale.multiplyScalar(scale);
flare.children[0].children[0].rotation.y = Math.random() * Math.PI * 2;
flare.children[0].children[0].rotation.z = Math.random() * Math.PI * 2;
flare.children[0].children[0].rotation.x = Math.random() * Math.PI * 2;
flare.children[0].children[0].children[1].rotation.y = -Math.PI;
objetoSol.add(flare);
flare.speed = (Math.PI - Math.random() * Math.PI / 5) / 100;
return flare;
}
;
ON_DAED["3D"].register(scene, objetoSol, function () {
var anim = ++factSolAnimacao / mod;
brilho.scale.x = (escalaBase + Math.cos(anim)) * escalaBase;
brilho.scale.y = (escalaBase + Math.sin(anim)) * escalaBase;
for (var i = flares.length - 1; i >= 0; i--) {
flares[i].children[0].children[0].children[1].rotation.y += flares[i].speed;
if (flares[i].children[0].children[0].children[1].rotation.y >= Math.PI) {
var removed = flares[i];
objetoSol.remove(removed);
flares.splice(i, 1);
flares.push(addFlare());
}
}
if (flares.length === 0 && flareObject) {
for (var i = 0; i < 10; i++) {
flares.push(addFlare());
}
}
}, true);
return objetoSol;
};
function circuloContext2D(ctx, x, y, radius, iniAngulo, fimAngulo) {
ctx.beginPath();
ctx.arc(x, y, radius, iniAngulo, fimAngulo, true);
ctx.fill();
ctx.stroke();
}
// stemkoski
function roundRect(ctx, x, y, w, h, r)
{
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
ctx.lineTo(x + w, y + h - r);
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
ctx.lineTo(x + r, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
function criarTexturaLetraComBorda(message, parameters) {
if (parameters === undefined)
parameters = {};
var fontSize = 400;
var canvasSize = 512;
var fontface = parameters.hasOwnProperty("fontface") ?
parameters["fontface"] : "Arial";
var fontsize = parameters.hasOwnProperty("fontsize") ?
parameters["fontsize"] : fontSize;
var borderThickness = parameters.hasOwnProperty("borderThickness") ?
parameters["borderThickness"] : 8;
var borderColor = parameters.hasOwnProperty("borderColor") ?
parameters["borderColor"] : {r: 0, g: 0, b: 0, a: 1.0};
var backgroundColor = parameters.hasOwnProperty("backgroundColor") ?
parameters["backgroundColor"] : {r: 255, g: 255, b: 255, a: 1.0};
var canvas = document.createElement('canvas');
canvas.height = canvas.width = canvasSize;
var context = canvas.getContext('2d');
context.font = "" + fontsize + "px " + fontface;
// text color
context.fillStyle = "rgba(" + backgroundColor.r + "," + backgroundColor.g + ","
+ backgroundColor.b + "," + backgroundColor.a + ")";
// get size data (height depends only on font size)
var metrics = context.measureText(message);
var textWidth = metrics.width;
var textX = canvasSize / 2 - textWidth / 2;
var textY = (canvasSize - fontsize) / 2 + fontsize / 1.4 + borderThickness;
context.fillText(message, textX, textY);
context.lineWidth = borderThickness;
// border color
context.strokeStyle = "rgba(" + borderColor.r + "," + borderColor.g + ","
+ borderColor.b + "," + borderColor.a + ")";
context.strokeText(message, textX, textY);
// canvas contents will be used for a texture
var texture = new THREE.Texture(canvas);
texture.needsUpdate = true;
return texture;
}
// stemkoski
function makeTextSprite(message, parameters)
{
if (parameters === undefined)
parameters = {};
var fontface = parameters.hasOwnProperty("fontface") ?
parameters["fontface"] : "Arial";
var fontsize = parameters.hasOwnProperty("fontsize") ?
parameters["fontsize"] : 18;
var borderThickness = parameters.hasOwnProperty("borderThickness") ?
parameters["borderThickness"] : 4;
var borderColor = parameters.hasOwnProperty("borderColor") ?
parameters["borderColor"] : {r: 0, g: 0, b: 0, a: 1.0};
var backgroundColor = parameters.hasOwnProperty("backgroundColor") ?
parameters["backgroundColor"] : {r: 255, g: 255, b: 255, a: 1.0};
var depthTest = parameters.hasOwnProperty("depthTest") ?
parameters["depthTest"] : false;
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.font = "Bold " + fontsize + "px " + fontface;
// get size data (height depends only on font size)
var metrics = context.measureText(message);
var textWidth = metrics.width;
// background color
context.fillStyle = "rgba(" + backgroundColor.r + "," + backgroundColor.g + ","
+ backgroundColor.b + "," + backgroundColor.a + ")";
// border color
context.strokeStyle = "rgba(" + borderColor.r + "," + borderColor.g + ","
+ borderColor.b + "," + borderColor.a + ")";
context.lineWidth = borderThickness;
roundRect(context, borderThickness / 2, borderThickness / 2, textWidth + borderThickness, fontsize * 1.4 + borderThickness, 0);
// 1.4 is extra height factor for text below baseline: g,j,p,q.
// text color
context.fillStyle = "rgba(0, 0, 0, 1.0)";
context.fillText(message, borderThickness, fontsize + borderThickness);
// canvas contents will be used for a texture
var texture = new THREE.Texture(canvas);
texture.needsUpdate = true;
var spriteMaterial = new THREE.SpriteMaterial(
{map: texture, depthTest: depthTest});
var sprite = new THREE.Sprite(spriteMaterial);
sprite.scale.set(100, 50, 1.0);
return sprite;
}
// public
ON_DAED["3D"].setMouseOverPossible = function (parent, renderer, camera) {
var obj = $(parent);
var mouse = new THREE.Vector2();
var intersected;
var element = renderer.domElement;
// MOUSE
function onDocumentMouseMove(event) {
var x = event.clientX - parseInt($(element).offset().left);
var y = event.clientY - parseInt($(element).offset().top);
mouse.x = (x / element.offsetWidth) * 2 - 1;
mouse.y = -(y / element.offsetHeight) * 2 + 1;
var vector = new THREE.Vector3(mouse.x, mouse.y, 0.5);
vector.unproject(camera);
var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());
var intersections = raycaster.intersectObjects(ON_DAED["3D"].intersectObjects, true);
if (intersections.length > 0) {
if (intersected !== intersections[ 0 ].object) {
if (intersected) {
if (intersected.mout instanceof Function) {
intersected.mout(event, intersected);
}
}
$('body').css('cursor', 'auto');
}
intersected = intersections[ 0 ].object;
$('body').css('cursor', 'pointer');
if (intersected.mover instanceof Function) {
intersected.mover(event, intersected);
}
} else if (intersected) {
if (intersected.mout instanceof Function) {
intersected.mout(event, intersected);
}
$('body').css('cursor', 'auto');
intersected = null;
} else {
$('body').css('cursor', 'auto');
}
}
obj.bind('mousemove', onDocumentMouseMove);
function onMouseOut(event) {
if (('.qtip:visible').length > 0) {
$('.qtip').qtip('hide');
}
$('body').css('cursor', 'auto');
}
obj.bind('mouseout', onMouseOut);
function onClick(event) {
if (intersected && intersected.mclick instanceof Function) {
intersected.mclick(event, intersected);
}
}
obj.bind('click', onClick);
}
;
ON_DAED["3D"].register = function (scene, obj, updateFunction, ignoreMouse) {
scene.add(obj);
obj.update = updateFunction;
if (!ignoreMouse) {
ON_DAED["3D"].intersectObjects.push(obj);
}
ON_DAED["3D"].objects.push(obj);
};
ON_DAED["3D"].unregister = function (scene, obj) {
var idx = ON_DAED["3D"].objects.indexOf(obj);
if (idx !== -1) {
ON_DAED["3D"].objects.splice(idx, 1);
scene.remove(obj);
}
};
ON_DAED["3D"].update = function () {
var list = ON_DAED["3D"].objects;
for (var i = 0; i < list.length; i++) {
if (list[i].update instanceof Function) {
list[i].update();
}
}
};
ON_DAED['3D'].START_RENDER = null;
ON_DAED["3D"].create = function (buildScene, render, element, controls, color) {
if (!ON_DAED["WEBGL_SUPPORT"]) {
console.log("Sem suporte a WEBGL");
return null;
}
var renderer;
var scene;
var camera;
var clock = new THREE.Clock();
var cameraControl;
var stats = new Stats();
function rendering() {
requestAnimationFrame(rendering);
render(cameraControl, renderer, scene, camera, stats, clock);
}
scene = new THREE.Scene();
var w = element !== window ? element.offsetWidth : window.innerWidth,
h = element !== window ? element.offsetHeight : window.innerHeight;
// camera
camera = new THREE.PerspectiveCamera(45, w / h, 1, 10000000000);
// renderer
renderer = new THREE.WebGLRenderer({preserveDrawingBuffer: true, antialias: true, alpha: true, logarithmicDepthBuffer: true});
renderer.domElement.id = 'main-canvas';
renderer.setClearColor(0x000000, 1);
renderer.setSize(w, h);
renderer.gammaInput = true;
renderer.gammaOutput = true;
renderer.shadowMapEnabled = true;
renderer.shadowSoftMap = true;
renderer.shadowMapType = THREE.PCFSoftShadowMap;
scene.add(camera);
(function () {
var width = window.innerWidth;
var height = window.innerHeight;
setInterval(function () {
if ((width !== window.innerWidth) || (height !== window.innerHeight)) {
width = window.innerWidth;
height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
}
}, 300);
})();
// controls, return camera control if any
if (controls instanceof Function) {
cameraControl = controls(camera, renderer, scene, stats);
}
element.style['overflow'] = 'hidden';
element.appendChild(renderer.domElement);
// Build scene
buildScene(scene, camera);
if (color !== undefined) {
renderer.setClearColor(color);
}
ON_DAED['3D'].START_RENDER = function() {
var width = window.innerWidth;
var height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
rendering();
};
return {
scene: scene
};
};
ON_DAED["3D"].createManager = function (component) {
var manager = new THREE.LoadingManager();
manager.onProgress = function (item, loaded, total) {
console.log(item, loaded, total);
};
manager.onLoad = function () {
console.log("Finished loading: " + component);
};
manager.onError = function () {
console.log("Error loading: " + component);
};
return manager;
};
})(); |
/**
* @author oosmoxiecode
*/
import { Geometry } from '../core/Geometry';
function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
Geometry.call( this );
this.type = 'TorusKnotGeometry';
this.parameters = {
radius: radius,
tube: tube,
tubularSegments: tubularSegments,
radialSegments: radialSegments,
p: p,
q: q
};
if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
this.mergeVertices();
}
TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
/**
* @author Mugen87 / https://github.com/Mugen87
* see: http://www.blackpawn.com/texts/pqtorus/
*/
import { BufferAttribute } from '../core/BufferAttribute';
import { BufferGeometry } from '../core/BufferGeometry';
import { Vector3 } from '../math/Vector3';
import { Vector2 } from '../math/Vector2';
function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
BufferGeometry.call( this );
this.type = 'TorusKnotBufferGeometry';
this.parameters = {
radius: radius,
tube: tube,
tubularSegments: tubularSegments,
radialSegments: radialSegments,
p: p,
q: q
};
radius = radius || 100;
tube = tube || 40;
tubularSegments = Math.floor( tubularSegments ) || 64;
radialSegments = Math.floor( radialSegments ) || 8;
p = p || 2;
q = q || 3;
// used to calculate buffer length
var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) );
var indexCount = radialSegments * tubularSegments * 2 * 3;
// buffers
var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ), 1 );
var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
// helper variables
var i, j, index = 0, indexOffset = 0;
var vertex = new Vector3();
var normal = new Vector3();
var uv = new Vector2();
var P1 = new Vector3();
var P2 = new Vector3();
var B = new Vector3();
var T = new Vector3();
var N = new Vector3();
// generate vertices, normals and uvs
for ( i = 0; i <= tubularSegments; ++ i ) {
// the radian "u" is used to calculate the position on the torus curve of the current tubular segement
var u = i / tubularSegments * p * Math.PI * 2;
// now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
// these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
calculatePositionOnCurve( u, p, q, radius, P1 );
calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
// calculate orthonormal basis
T.subVectors( P2, P1 );
N.addVectors( P2, P1 );
B.crossVectors( T, N );
N.crossVectors( B, T );
// normalize B, N. T can be ignored, we don't use it
B.normalize();
N.normalize();
for ( j = 0; j <= radialSegments; ++ j ) {
// now calculate the vertices. they are nothing more than an extrusion of the torus curve.
// because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
var v = j / radialSegments * Math.PI * 2;
var cx = - tube * Math.cos( v );
var cy = tube * Math.sin( v );
// now calculate the final vertex position.
// first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
vertex.x = P1.x + ( cx * N.x + cy * B.x );
vertex.y = P1.y + ( cx * N.y + cy * B.y );
vertex.z = P1.z + ( cx * N.z + cy * B.z );
// vertex
vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
// normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
normal.subVectors( vertex, P1 ).normalize();
normals.setXYZ( index, normal.x, normal.y, normal.z );
// uv
uv.x = i / tubularSegments;
uv.y = j / radialSegments;
uvs.setXY( index, uv.x, uv.y );
// increase index
index ++;
}
}
// generate indices
for ( j = 1; j <= tubularSegments; j ++ ) {
for ( i = 1; i <= radialSegments; i ++ ) {
// indices
var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
var b = ( radialSegments + 1 ) * j + ( i - 1 );
var c = ( radialSegments + 1 ) * j + i;
var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
// face one
indices.setX( indexOffset, a ); indexOffset ++;
indices.setX( indexOffset, b ); indexOffset ++;
indices.setX( indexOffset, d ); indexOffset ++;
// face two
indices.setX( indexOffset, b ); indexOffset ++;
indices.setX( indexOffset, c ); indexOffset ++;
indices.setX( indexOffset, d ); indexOffset ++;
}
}
// build geometry
this.setIndex( indices );
this.addAttribute( 'position', vertices );
this.addAttribute( 'normal', normals );
this.addAttribute( 'uv', uvs );
// this function calculates the current position on the torus curve
function calculatePositionOnCurve( u, p, q, radius, position ) {
var cu = Math.cos( u );
var su = Math.sin( u );
var quOverP = q / p * u;
var cs = Math.cos( quOverP );
position.x = radius * ( 2 + cs ) * 0.5 * cu;
position.y = radius * ( 2 + cs ) * su * 0.5;
position.z = radius * Math.sin( quOverP ) * 0.5;
}
}
TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
export { TorusKnotGeometry, TorusKnotBufferGeometry };
|
define( [
'link-list/singlyLinkListSpec',
'link-list/doublyLinkListSpec',
'link-list/singlyCircularLinkListSpec',
'link-list/doublyCircularLinkListSpec'
], function(
singlyLinkListSpec,
doublyLinkListSpec,
singlyCircularLinkListSpec,
doublyCircularLinkListSpec
) {
} );
|
rock.namespace('rock.geometry');
/**
* Represents a 3x3 matrix.
*
* @constructor
* @author Luis Alberto Jiménez
*/
rock.geometry.Matrix3 = function () {
// column major
this.matrix = new Array(9);
this.identity();
// This properties are used to avoid allocate new memory
this.point3_ma = new rock.geometry.Point3(0, 0, 0);
};
rock.geometry.Matrix3.prototype.getAuxiliaryPoint3 = function () {
var point3 = this.point3_ma;
point3.setX(0);
point3.setY(0);
point3.setZ(0);
return point3;
};
/**
* Returns the matrix as an array
*
* @returns {Array.9}
*/
rock.geometry.Matrix3.prototype.getMatrixAsArray = function () {
return this.matrix;
};
/**
* Do this matrix as identity matrix
*
*/
rock.geometry.Matrix3.prototype.identity = function () {
for (var i = 0; i < 9; i++) {
this.matrix[i] = 0;
}
this.matrix[0] = 1; // this.setValue(0, 0, 1);
this.matrix[4] = 1; // this.setValue(1, 1, 1);
this.matrix[8] = 1; // this.setValue(2, 2, 1);
};
/**
* Calculate the determinant
*
* @returns the determinant
*/
rock.geometry.Matrix3.prototype.getDeterminant = function () {
var determinant = ((this.matrix[0] * this.matrix[4] * this.matrix[8])
+ (this.matrix[3] * this.matrix[7] * this.matrix[2]) + (this.matrix[6]
* this.matrix[1] * this.matrix[5]))
- ((this.matrix[6] * this.matrix[4] * this.matrix[2])
+ (this.matrix[3] * this.matrix[1] * this.matrix[8]) + (this.matrix[0]
* this.matrix[7] * this.matrix[5]));
return determinant;
};
/**
* This function multiply a point with a matrix
*
* @param {rock.geometry.Point3} point3
* the point
*
* @return {rock.geometry.Point3}
*/
rock.geometry.Matrix3.prototype.multiplyByPoint3 = function (point3) {
var result = this.getAuxiliaryPoint3();
var point3X = point3.getX();
var point3Y = point3.getY();
var point3Z = point3.getZ();
result.setX(point3X * this.getValue(0, 0) + point3Y * this.getValue(0, 1) + point3Z * this.getValue(0, 2));
result.setY(point3X * this.getValue(1, 0) + point3Y * this.getValue(1, 1) + point3Z * this.getValue(1, 2));
result.setZ(point3X * this.getValue(2, 0) + point3Y * this.getValue(2, 1) + point3Z * this.getValue(2, 2));
return result;
};
/**
* Set a value
*
* @param i
* the row
* @param j
* the column
* @param value
* the value to set
*/
rock.geometry.Matrix3.prototype.setValue = function (i, j, value) {
var pos = j * 3 + i;
this.matrix[pos] = value;
};
/**
* Return a value
*
* @param i
* the row
* @param j
* the column
* @returns the value
*/
rock.geometry.Matrix3.prototype.getValue = function (i, j) {
var pos = j * 3 + i;
return this.matrix[pos];
};
|
// const request = require('supertest'),
// app = require('../test_util/test_server_app');
//
// function expectRespondsWithAppHtml(url, done) {
// request(app)
// .get(url)
// .expect(200)
// .expect(function (res) {
// expect(res.text.startsWith('<!doctype html>')).toBeTruthy();
// expect(res.text).toMatch(/.*<script src="js\/main\.js".*/);
// expect(res.text).toMatch(/.*<link.*href="css\/main\.css".*/);
// })
// .end(function (err) {
// if(err) {
// done.fail(err);
// } else {
// done()
// }
// });
// }
//
// describe('request to non /api url', function () {
// it('/ should responds with app html', function (done) {
// expectRespondsWithAppHtml('/', done);
// });
// it('/foobar should responds with app html', function (done) {
// expectRespondsWithAppHtml('/foobar', done);
// });
// });
|
import { Map, List, fromJS } from 'immutable';
import { memoize, compose, partialRight, call } from 'ramda';
import { Promise } from 'es6-promise';
function createHookStructure() {
return fromJS({hooks: Map() });
}
function hookAtom() {
return Map({
'before': List(),
'after': List(),
});
}
function Hook() {
const hookAPI = {};
hookAPI.getHookStructure = memoize(()=> createHookStructure());
function updateHookStructure(newStructure) {
hookAPI.getHookStructure = memoize(()=> newStructure);
return newStructure;
}
function setHookType(hookName) {
return hookAPI.getHookStructure().set(
'hooks',
hookAPI.getHookStructure().get('hooks').set(hookName, hookAtom())
);
}
function removeHookType(hookName) {
return hookAPI.getHookStructure().set(
'hooks',
hookAPI.getHookStructure().get('hooks').remove(hookName)
);
}
function clearHooks() {
return hookAPI.getHookStructure().set('hooks', Map());
}
function addHook(name, position, hook) {
return hookAPI.getHookStructure().setIn(
['hooks', name, position],
hookAPI.getHookStructure().getIn(['hooks', name, position]).push(hook)
);
}
function resolveHook(name, pos) {
const sequence = hookAPI.getHookStructure().getIn(['hooks', name, pos]);
return function(...args) {
return sequence.reduce(
function(initialValue, hook) {
return initialValue.then(()=> hook.apply(this, args));
},
Promise.resolve(null)
);
};
}
function wrapHandler(name, handler) {
return function(...args) {
return call(resolveHook(name, 'before'), args)
.then(function(beforeSeq) {
return Promise.resolve(beforeSeq).then(handler).then(resolveHook(name, 'after'));
});
};
}
hookAPI.addHookType = compose(
updateHookStructure,
(type)=> setHookType(type)
);
hookAPI.removeHookType = compose(
updateHookStructure,
(type)=> removeHookType(type)
);
hookAPI.clearHooks = compose(
updateHookStructure,
()=> clearHooks()
);
hookAPI.addHook = compose(
updateHookStructure,
addHook
);
hookAPI.addHookBefore = (name, hook)=> hookAPI.addHook(name, 'before', hook);
hookAPI.addHookAfter = (name, hook)=> hookAPI.addHook(name, 'after', hook);
hookAPI.resolveHook = resolveHook;
hookAPI.resolveHookBefore = partialRight(resolveHook, 'before');
hookAPI.resolveHookAfter = partialRight(resolveHook, 'after');
hookAPI.wrap = wrapHandler;
return hookAPI;
}
export default Hook;
|
import Ember from 'ember';
export default Ember.Service.extend({
log(context, error) {
if (error) {
//eslint-disable-next-line no-console
console.error('ember-error-handler:', error.stack);
} else {
//eslint-disable-next-line no-console
console.error('ember-error-handler:', 'Failed with undefined error');
}
}
})
|
module.exports = {
printCanvas (canvasToPrint, state) {
let w = canvasToPrint.canvas.width;
let h = canvasToPrint.canvas.height;
let data = canvasToPrint.context.getImageData(0,0,w,h);
let compositeOperation = canvasToPrint.context.globalCompositeOperation;
canvasToPrint.context.globalCompositeOperation = "destination-over";
canvasToPrint.context.fillStyle = state.backgroundColor;
canvasToPrint.context.fillRect(0,0,w,h);
let canvasDataURL = canvasToPrint.canvas.toDataURL('image/png');
canvasToPrint.context.clearRect(0,0,w,h);
canvasToPrint.context.putImageData(data, 0,0);
canvasToPrint.context.globalCompositeOperation = compositeOperation;
let win=window.open();
win.document.write("<br><img src='"+canvasDataURL+"'/>");
},
} |
'use strict';
/**
* Policy to set necessary create data to body.
*
* @param {Request} request Request object
* @param {Response} response Response object
* @param {Function} next Callback function
*/
function alphanum(value) {
if (/[^a-zA-Z0-9]/.test(value)) {
return false;
}
return true;
}
module.exports = function createUser(request, response, next) {
sails.log.verbose(__filename + ':' + __line + ' [Policy.createUser() called]');
if (!request.body.passports) return next()
var password = request.body.passports.password
var confirmation = request.body.password_confirmation
sails.log('[Policy.createUser()] -> password : ' + password);
sails.log('[Policy.createUser()] -> confirmation : ' + confirmation);
if (!password) {
var error = new Error();
error.Errors = {
password: [
{
message: 'The password field is required.'
}
]
}
error.status = 400;
return next(error);
}
if (password.length < 7) {
var error = new Error();
error.Errors = {
password: [
{
message: 'The password must be at least 7 characters long.'
}
]
}
error.status = 400;
return next(error);
}
if (!alphanum(password)) {
var error = new Error();
error.Errors = {
password: [
{
message: 'Only alphanumeric characters are allowed'
}
]
}
error.status = 400;
return next(error);
}
if (password != confirmation) {
var error = new Error();
error.Errors = {
password_confirmation: [
{
message: 'Password and password confirmation don\'t match'
}
]
}
error.status = 400;
return next(error);
} else {
next();
}
};
|
'use strict';
exports.__esModule = true;
var _postcss = require('postcss');
var postcss = _interopRequireWildcard(_postcss);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
exports.default = postcss.plugin('postcss-define-units', function () {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return function (css) {
var save = {};
css.walkDecls(function (decl) {
if (decl.prop === '--define') {
var _postcss$list$space = postcss.list.space(decl.value),
type = _postcss$list$space[0],
value = _postcss$list$space[1];
if (value.charAt(0) == '(') {
var _value$match = value.match(/\((.+)\)(\w+|\%)/),
_ = _value$match[0],
expression = _value$match[1],
postfix = _value$match[2];
save[type] = [new Function('value', ['return', '(', expression, ')'].join(' ')), postfix];
} else {
var _value$match2 = value.match(/(\d+)(\w+)/),
_2 = _value$match2[0],
count = _value$match2[1],
_postfix = _value$match2[2];
save[type] = [function (value) {
return count * value;
}, _postfix];
}
decl.remove();
} else {
var _loop = function _loop(_type) {
var _save$_type = save[_type],
f = _save$_type[0],
postfix = _save$_type[1];
var reg = new RegExp("(([\\d\.]+)" + _type + ")", 'g');
decl.value = decl.value.replace(reg, function (a, b, c) {
return [f(c), postfix].join('');
});
};
for (var _type in save) {
_loop(_type);
}
}
});
};
});
|
Template.presentationDisplay.helpers({
slides: function () {
var slides = [];
presentationslides.find({presentation: this._id}, {sort: [['order', 'asc']]}).forEach(function (slide) {
slide.action = this.action;
slides.push(slide);
}.bind(this));
return slides;
}
});
|
'use strict';
var fs = require('then-fs');
var Promise = require('promise');
var RegClient = require('npm-registry-client');
var tar = require('tar-pack');
var registry = new RegClient({});
// returns {src, rfile}
function getReadme(directory, cb) {
return fs.readdir(directory).then(function (files) {
var rfile = files.filter(function (file) {
return /^readme(\.(md|markdown|txt))?$/i.test(file)
}).sort()[0]
if (!rfile) throw new Error('No readme found');
return fs.readFile(rfile, 'utf8').then(function (src) {
return {src: src, file: rfile};
})
});
}
function prepare(directory) {
// returns pkg
var readme = getReadme(directory);
var pkg = fs.readFile(directory + '/package.json', 'utf8').then(JSON.parse);
return Promise.all([readme, pkg]).then(function (res) {
var readme = res[0];
var pkg = res[1];
pkg.readme = readme.src;
pkg.readmeFile = readme.file;
return pkg;
});
}
function publish(directory) {
var registryBase = "http://registry.npmjs.org/";
var auth = {
username: process.env.NPM_USERNAME,
password: process.env.NPM_PASSWORD,
email: process.env.NPM_EMAIL,
alwaysAuth: true
};
return prepare(directory).then(function (pkg) {
pkg._npmUser = {
name : auth.username,
email : auth.email
};
var params = {
metadata : pkg,
access : 'public',
body : tar.pack(directory),
auth : auth
}
return new Promise(function (resolve, reject) {
registry.publish(registryBase, params, function (err) {
if (err) reject(err);
else resolve();
});
});
});
}
module.exports = publish;
|
require('angular');
module.exports = {
'route-mount': angular.module('route-mount', [])
.provider('$mount', require('./providers/mount/provider'))
}; |
var pages_register = {
'public render_register': function()
{
r.inject(
this.dom.form = form({
c:['table', 'box', 'align_center'],
e:
{
submit: this.event_submit_register.bind(this)
}
},
div({c:['column', 'title']}, 'Please Register'),
this.dom.message = div({c:['column', 'message']}),
div({c:['column', 'body']},
span({c:'label'},
'A username can contain any combination of letters, numbers, or underscores.'
),
br, br,
input({
type:'text',
name:'user',
placeholder:'Username'
}),
br, br, br,
span({c:'label'},
'A password should be at least 4 characters.'
),
br, br,
input({
type:'password',
name:'password',
placeholder:'Password'
}),
br, br,
span({c:'label'},
'Please confirm password'
),
br, br,
input({
type:'password',
name:'password_confirm',
placeholder:'Password (Confirm)'
}),
br, br, br,
button({
type:'submit',
name:'submit'
},
'Register'
),
br, br,
span('If you already have an account, you can login '),
span({c:'a', e:{click:this.render_login.bind(this)}}, 'here'),
span('.')
)
),
r._(this.dom.content)
);
},
'public event_submit_register': function(event)
{
event.preventDefault();
r._(this.dom.message);
var data = r.form.to(this.dom.form),
flag = true;
if(flag && !data.user)
{
this.render_error('Please enter a username!', 'error');
flag = false;
}
if(flag && !/^[a-zA-Z_0-9]+$/.test(data.user))
{
this.render_error('The username must only have letters, numbers, or underscores!', 'error');
flag = false;
}
if(flag && (data.user == 'anonymous' || data.user == 'root'))
{
this.render_error('The username may not be anonymous or root!', 'error');
flag = false;
}
if(flag && data.user.length > 64)
{
this.render_error('The username may not be larger than 64 characters!', 'error');
flag = false;
}
if(flag && !data.password)
{
this.render_error('Please enter a password for the account!', 'error');
flag = false;
}
if(flag && data.password.length < 4)
{
this.render_error('Please enter a password that is at least 4 characters!', 'error');
flag = false;
}
if(flag && !data.password_confirm)
{
this.render_error('Please enter a confirmation password for the account!', 'error');
flag = false;
}
if(flag && data.password != data.password_confirm)
{
this.render_error('Please enter a confirmation password that matches the original password!', 'error');
flag = false;
}
if(flag)
{
r.xhr.rpc('token', 'POST', data, this.rpc, this);
}
}
}; |
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Utilities for manipulating arrays.
*
* @author arv@google.com (Erik Arvidsson)
*/
goog.provide('goog.array');
goog.provide('goog.array.ArrayLike');
goog.require('goog.asserts');
/**
* @define {boolean} NATIVE_ARRAY_PROTOTYPES indicates whether the code should
* rely on Array.prototype functions, if available.
*
* The Array.prototype functions can be defined by external libraries like
* Prototype and setting this flag to false forces closure to use its own
* goog.array implementation.
*
* If your javascript can be loaded by a third party site and you are wary about
* relying on the prototype functions, specify
* "--define goog.NATIVE_ARRAY_PROTOTYPES=false" to the JSCompiler.
*
* Setting goog.TRUSTED_SITE to false will automatically set
* NATIVE_ARRAY_PROTOTYPES to false.
*/
goog.define('goog.NATIVE_ARRAY_PROTOTYPES', goog.TRUSTED_SITE);
/**
* @define {boolean} If true, JSCompiler will use the native implementation of
* array functions where appropriate (e.g., {@code Array#filter}) and remove the
* unused pure JS implementation.
*/
goog.define('goog.array.ASSUME_NATIVE_FUNCTIONS', false);
/**
* @typedef {Array|NodeList|Arguments|{length: number}}
*/
goog.array.ArrayLike;
/**
* Returns the last element in an array without removing it.
* Same as goog.array.last.
* @param {Array<T>|goog.array.ArrayLike} array The array.
* @return {T} Last item in array.
* @template T
*/
goog.array.peek = function(array) {
return array[array.length - 1];
};
/**
* Returns the last element in an array without removing it.
* Same as goog.array.peek.
* @param {Array<T>|goog.array.ArrayLike} array The array.
* @return {T} Last item in array.
* @template T
*/
goog.array.last = goog.array.peek;
/**
* Reference to the original {@code Array.prototype}.
* @private {!Object}
*/
goog.array.ARRAY_PROTOTYPE_ = Array.prototype;
// NOTE(arv): Since most of the array functions are generic it allows you to
// pass an array-like object. Strings have a length and are considered array-
// like. However, the 'in' operator does not work on strings so we cannot just
// use the array path even if the browser supports indexing into strings. We
// therefore end up splitting the string.
/**
* Returns the index of the first element of an array with a specified value, or
* -1 if the element is not present in the array.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-indexof}
*
* @param {Array<T>|goog.array.ArrayLike} arr The array to be searched.
* @param {T} obj The object for which we are searching.
* @param {number=} opt_fromIndex The index at which to start the search. If
* omitted the search starts at index 0.
* @return {number} The index of the first matching array element.
* @template T
*/
goog.array.indexOf = goog.NATIVE_ARRAY_PROTOTYPES &&
(goog.array.ASSUME_NATIVE_FUNCTIONS ||
goog.array.ARRAY_PROTOTYPE_.indexOf) ?
function(arr, obj, opt_fromIndex) {
goog.asserts.assert(arr.length != null);
return goog.array.ARRAY_PROTOTYPE_.indexOf.call(arr, obj, opt_fromIndex);
} :
function(arr, obj, opt_fromIndex) {
var fromIndex = opt_fromIndex == null ?
0 : (opt_fromIndex < 0 ?
Math.max(0, arr.length + opt_fromIndex) : opt_fromIndex);
if (goog.isString(arr)) {
// Array.prototype.indexOf uses === so only strings should be found.
if (!goog.isString(obj) || obj.length != 1) {
return -1;
}
return arr.indexOf(obj, fromIndex);
}
for (var i = fromIndex; i < arr.length; i++) {
if (i in arr && arr[i] === obj)
return i;
}
return -1;
};
/**
* Returns the index of the last element of an array with a specified value, or
* -1 if the element is not present in the array.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-lastindexof}
*
* @param {!Array<T>|!goog.array.ArrayLike} arr The array to be searched.
* @param {T} obj The object for which we are searching.
* @param {?number=} opt_fromIndex The index at which to start the search. If
* omitted the search starts at the end of the array.
* @return {number} The index of the last matching array element.
* @template T
*/
goog.array.lastIndexOf = goog.NATIVE_ARRAY_PROTOTYPES &&
(goog.array.ASSUME_NATIVE_FUNCTIONS ||
goog.array.ARRAY_PROTOTYPE_.lastIndexOf) ?
function(arr, obj, opt_fromIndex) {
goog.asserts.assert(arr.length != null);
// Firefox treats undefined and null as 0 in the fromIndex argument which
// leads it to always return -1
var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;
return goog.array.ARRAY_PROTOTYPE_.lastIndexOf.call(arr, obj, fromIndex);
} :
function(arr, obj, opt_fromIndex) {
var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;
if (fromIndex < 0) {
fromIndex = Math.max(0, arr.length + fromIndex);
}
if (goog.isString(arr)) {
// Array.prototype.lastIndexOf uses === so only strings should be found.
if (!goog.isString(obj) || obj.length != 1) {
return -1;
}
return arr.lastIndexOf(obj, fromIndex);
}
for (var i = fromIndex; i >= 0; i--) {
if (i in arr && arr[i] === obj)
return i;
}
return -1;
};
/**
* Calls a function for each element in an array. Skips holes in the array.
* See {@link http://tinyurl.com/developer-mozilla-org-array-foreach}
*
* @param {Array<T>|goog.array.ArrayLike} arr Array or array like object over
* which to iterate.
* @param {?function(this: S, T, number, ?): ?} f The function to call for every
* element. This function takes 3 arguments (the element, the index and the
* array). The return value is ignored.
* @param {S=} opt_obj The object to be used as the value of 'this' within f.
* @template T,S
*/
goog.array.forEach = goog.NATIVE_ARRAY_PROTOTYPES &&
(goog.array.ASSUME_NATIVE_FUNCTIONS ||
goog.array.ARRAY_PROTOTYPE_.forEach) ?
function(arr, f, opt_obj) {
goog.asserts.assert(arr.length != null);
goog.array.ARRAY_PROTOTYPE_.forEach.call(arr, f, opt_obj);
} :
function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = 0; i < l; i++) {
if (i in arr2) {
f.call(opt_obj, arr2[i], i, arr);
}
}
};
/**
* Calls a function for each element in an array, starting from the last
* element rather than the first.
*
* @param {Array<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this: S, T, number, ?): ?} f The function to call for every
* element. This function
* takes 3 arguments (the element, the index and the array). The return
* value is ignored.
* @param {S=} opt_obj The object to be used as the value of 'this'
* within f.
* @template T,S
*/
goog.array.forEachRight = function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = l - 1; i >= 0; --i) {
if (i in arr2) {
f.call(opt_obj, arr2[i], i, arr);
}
}
};
/**
* Calls a function for each element in an array, and if the function returns
* true adds the element to a new array.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-filter}
*
* @param {Array<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?):boolean} f The function to call for
* every element. This function
* takes 3 arguments (the element, the index and the array) and must
* return a Boolean. If the return value is true the element is added to the
* result array. If it is false the element is not included.
* @param {S=} opt_obj The object to be used as the value of 'this'
* within f.
* @return {!Array<T>} a new array in which only elements that passed the test
* are present.
* @template T,S
*/
goog.array.filter = goog.NATIVE_ARRAY_PROTOTYPES &&
(goog.array.ASSUME_NATIVE_FUNCTIONS ||
goog.array.ARRAY_PROTOTYPE_.filter) ?
function(arr, f, opt_obj) {
goog.asserts.assert(arr.length != null);
return goog.array.ARRAY_PROTOTYPE_.filter.call(arr, f, opt_obj);
} :
function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var res = [];
var resLength = 0;
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = 0; i < l; i++) {
if (i in arr2) {
var val = arr2[i]; // in case f mutates arr2
if (f.call(opt_obj, val, i, arr)) {
res[resLength++] = val;
}
}
}
return res;
};
/**
* Calls a function for each element in an array and inserts the result into a
* new array.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-map}
*
* @param {Array<VALUE>|goog.array.ArrayLike} arr Array or array like object
* over which to iterate.
* @param {function(this:THIS, VALUE, number, ?): RESULT} f The function to call
* for every element. This function takes 3 arguments (the element,
* the index and the array) and should return something. The result will be
* inserted into a new array.
* @param {THIS=} opt_obj The object to be used as the value of 'this' within f.
* @return {!Array<RESULT>} a new array with the results from f.
* @template THIS, VALUE, RESULT
*/
goog.array.map = goog.NATIVE_ARRAY_PROTOTYPES &&
(goog.array.ASSUME_NATIVE_FUNCTIONS ||
goog.array.ARRAY_PROTOTYPE_.map) ?
function(arr, f, opt_obj) {
goog.asserts.assert(arr.length != null);
return goog.array.ARRAY_PROTOTYPE_.map.call(arr, f, opt_obj);
} :
function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var res = new Array(l);
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = 0; i < l; i++) {
if (i in arr2) {
res[i] = f.call(opt_obj, arr2[i], i, arr);
}
}
return res;
};
/**
* Passes every element of an array into a function and accumulates the result.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-reduce}
*
* For specs:
* var a = [1, 2, 3, 4];
* goog.array.reduce(a, function(r, v, i, arr) {return r + v;}, 0);
* returns 10
*
* @param {Array<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {function(this:S, R, T, number, ?) : R} f The function to call for
* every element. This function
* takes 4 arguments (the function's previous result or the initial value,
* the value of the current array element, the current array index, and the
* array itself)
* function(previousValue, currentValue, index, array).
* @param {?} val The initial value to pass into the function on the first call.
* @param {S=} opt_obj The object to be used as the value of 'this'
* within f.
* @return {R} Result of evaluating f repeatedly across the values of the array.
* @template T,S,R
*/
goog.array.reduce = goog.NATIVE_ARRAY_PROTOTYPES &&
(goog.array.ASSUME_NATIVE_FUNCTIONS ||
goog.array.ARRAY_PROTOTYPE_.reduce) ?
function(arr, f, val, opt_obj) {
goog.asserts.assert(arr.length != null);
if (opt_obj) {
f = goog.bind(f, opt_obj);
}
return goog.array.ARRAY_PROTOTYPE_.reduce.call(arr, f, val);
} :
function(arr, f, val, opt_obj) {
var rval = val;
goog.array.forEach(arr, function(val, index) {
rval = f.call(opt_obj, rval, val, index, arr);
});
return rval;
};
/**
* Passes every element of an array into a function and accumulates the result,
* starting from the last element and working towards the first.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-reduceright}
*
* For specs:
* var a = ['a', 'b', 'c'];
* goog.array.reduceRight(a, function(r, v, i, arr) {return r + v;}, '');
* returns 'cba'
*
* @param {Array<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, R, T, number, ?) : R} f The function to call for
* every element. This function
* takes 4 arguments (the function's previous result or the initial value,
* the value of the current array element, the current array index, and the
* array itself)
* function(previousValue, currentValue, index, array).
* @param {?} val The initial value to pass into the function on the first call.
* @param {S=} opt_obj The object to be used as the value of 'this'
* within f.
* @return {R} Object returned as a result of evaluating f repeatedly across the
* values of the array.
* @template T,S,R
*/
goog.array.reduceRight = goog.NATIVE_ARRAY_PROTOTYPES &&
(goog.array.ASSUME_NATIVE_FUNCTIONS ||
goog.array.ARRAY_PROTOTYPE_.reduceRight) ?
function(arr, f, val, opt_obj) {
goog.asserts.assert(arr.length != null);
if (opt_obj) {
f = goog.bind(f, opt_obj);
}
return goog.array.ARRAY_PROTOTYPE_.reduceRight.call(arr, f, val);
} :
function(arr, f, val, opt_obj) {
var rval = val;
goog.array.forEachRight(arr, function(val, index) {
rval = f.call(opt_obj, rval, val, index, arr);
});
return rval;
};
/**
* Calls f for each element of an array. If any call returns true, some()
* returns true (without checking the remaining elements). If all calls
* return false, some() returns false.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-some}
*
* @param {Array<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?) : boolean} f The function to call for
* for every element. This function takes 3 arguments (the element, the
* index and the array) and should return a boolean.
* @param {S=} opt_obj The object to be used as the value of 'this'
* within f.
* @return {boolean} true if any element passes the test.
* @template T,S
*/
goog.array.some = goog.NATIVE_ARRAY_PROTOTYPES &&
(goog.array.ASSUME_NATIVE_FUNCTIONS ||
goog.array.ARRAY_PROTOTYPE_.some) ?
function(arr, f, opt_obj) {
goog.asserts.assert(arr.length != null);
return goog.array.ARRAY_PROTOTYPE_.some.call(arr, f, opt_obj);
} :
function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = 0; i < l; i++) {
if (i in arr2 && f.call(opt_obj, arr2[i], i, arr)) {
return true;
}
}
return false;
};
/**
* Call f for each element of an array. If all calls return true, every()
* returns true. If any call returns false, every() returns false and
* does not continue to check the remaining elements.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-every}
*
* @param {Array<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?) : boolean} f The function to call for
* for every element. This function takes 3 arguments (the element, the
* index and the array) and should return a boolean.
* @param {S=} opt_obj The object to be used as the value of 'this'
* within f.
* @return {boolean} false if any element fails the test.
* @template T,S
*/
goog.array.every = goog.NATIVE_ARRAY_PROTOTYPES &&
(goog.array.ASSUME_NATIVE_FUNCTIONS ||
goog.array.ARRAY_PROTOTYPE_.every) ?
function(arr, f, opt_obj) {
goog.asserts.assert(arr.length != null);
return goog.array.ARRAY_PROTOTYPE_.every.call(arr, f, opt_obj);
} :
function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = 0; i < l; i++) {
if (i in arr2 && !f.call(opt_obj, arr2[i], i, arr)) {
return false;
}
}
return true;
};
/**
* Counts the array elements that fulfill the predicate, i.e. for which the
* callback function returns true. Skips holes in the array.
*
* @param {!(Array<T>|goog.array.ArrayLike)} arr Array or array like object
* over which to iterate.
* @param {function(this: S, T, number, ?): boolean} f The function to call for
* every element. Takes 3 arguments (the element, the index and the array).
* @param {S=} opt_obj The object to be used as the value of 'this' within f.
* @return {number} The number of the matching elements.
* @template T,S
*/
goog.array.count = function(arr, f, opt_obj) {
var count = 0;
goog.array.forEach(arr, function(element, index, arr) {
if (f.call(opt_obj, element, index, arr)) {
++count;
}
}, opt_obj);
return count;
};
/**
* Search an array for the first element that satisfies a given condition and
* return that element.
* @param {Array<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?) : boolean} f The function to call
* for every element. This function takes 3 arguments (the element, the
* index and the array) and should return a boolean.
* @param {S=} opt_obj An optional "this" context for the function.
* @return {T|null} The first array element that passes the test, or null if no
* element is found.
* @template T,S
*/
goog.array.find = function(arr, f, opt_obj) {
var i = goog.array.findIndex(arr, f, opt_obj);
return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i];
};
/**
* Search an array for the first element that satisfies a given condition and
* return its index.
* @param {Array<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?) : boolean} f The function to call for
* every element. This function
* takes 3 arguments (the element, the index and the array) and should
* return a boolean.
* @param {S=} opt_obj An optional "this" context for the function.
* @return {number} The index of the first array element that passes the test,
* or -1 if no element is found.
* @template T,S
*/
goog.array.findIndex = function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = 0; i < l; i++) {
if (i in arr2 && f.call(opt_obj, arr2[i], i, arr)) {
return i;
}
}
return -1;
};
/**
* Search an array (in reverse order) for the last element that satisfies a
* given condition and return that element.
* @param {Array<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?) : boolean} f The function to call
* for every element. This function
* takes 3 arguments (the element, the index and the array) and should
* return a boolean.
* @param {S=} opt_obj An optional "this" context for the function.
* @return {T|null} The last array element that passes the test, or null if no
* element is found.
* @template T,S
*/
goog.array.findRight = function(arr, f, opt_obj) {
var i = goog.array.findIndexRight(arr, f, opt_obj);
return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i];
};
/**
* Search an array (in reverse order) for the last element that satisfies a
* given condition and return its index.
* @param {Array<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?) : boolean} f The function to call
* for every element. This function
* takes 3 arguments (the element, the index and the array) and should
* return a boolean.
* @param {S=} opt_obj An optional "this" context for the function.
* @return {number} The index of the last array element that passes the test,
* or -1 if no element is found.
* @template T,S
*/
goog.array.findIndexRight = function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = l - 1; i >= 0; i--) {
if (i in arr2 && f.call(opt_obj, arr2[i], i, arr)) {
return i;
}
}
return -1;
};
/**
* Whether the array contains the given object.
* @param {goog.array.ArrayLike} arr The array to test for the presence of the
* element.
* @param {*} obj The object for which to test.
* @return {boolean} true if obj is present.
*/
goog.array.contains = function(arr, obj) {
return goog.array.indexOf(arr, obj) >= 0;
};
/**
* Whether the array is empty.
* @param {goog.array.ArrayLike} arr The array to test.
* @return {boolean} true if empty.
*/
goog.array.isEmpty = function(arr) {
return arr.length == 0;
};
/**
* Clears the array.
* @param {goog.array.ArrayLike} arr Array or array like object to clear.
*/
goog.array.clear = function(arr) {
// For non real arrays we don't have the magic length so we delete the
// indices.
if (!goog.isArray(arr)) {
for (var i = arr.length - 1; i >= 0; i--) {
delete arr[i];
}
}
arr.length = 0;
};
/**
* Pushes an item into an array, if it's not already in the array.
* @param {Array<T>} arr Array into which to insert the item.
* @param {T} obj Value to add.
* @template T
*/
goog.array.insert = function(arr, obj) {
if (!goog.array.contains(arr, obj)) {
arr.push(obj);
}
};
/**
* Inserts an object at the given index of the array.
* @param {goog.array.ArrayLike} arr The array to modify.
* @param {*} obj The object to insert.
* @param {number=} opt_i The index at which to insert the object. If omitted,
* treated as 0. A negative index is counted from the end of the array.
*/
goog.array.insertAt = function(arr, obj, opt_i) {
goog.array.splice(arr, opt_i, 0, obj);
};
/**
* Inserts at the given index of the array, all elements of another array.
* @param {goog.array.ArrayLike} arr The array to modify.
* @param {goog.array.ArrayLike} elementsToAdd The array of elements to add.
* @param {number=} opt_i The index at which to insert the object. If omitted,
* treated as 0. A negative index is counted from the end of the array.
*/
goog.array.insertArrayAt = function(arr, elementsToAdd, opt_i) {
goog.partial(goog.array.splice, arr, opt_i, 0).apply(null, elementsToAdd);
};
/**
* Inserts an object into an array before a specified object.
* @param {Array<T>} arr The array to modify.
* @param {T} obj The object to insert.
* @param {T=} opt_obj2 The object before which obj should be inserted. If obj2
* is omitted or not found, obj is inserted at the end of the array.
* @template T
*/
goog.array.insertBefore = function(arr, obj, opt_obj2) {
var i;
if (arguments.length == 2 || (i = goog.array.indexOf(arr, opt_obj2)) < 0) {
arr.push(obj);
} else {
goog.array.insertAt(arr, obj, i);
}
};
/**
* Removes the first occurrence of a particular value from an array.
* @param {Array<T>|goog.array.ArrayLike} arr Array from which to remove
* value.
* @param {T} obj Object to remove.
* @return {boolean} True if an element was removed.
* @template T
*/
goog.array.remove = function(arr, obj) {
var i = goog.array.indexOf(arr, obj);
var rv;
if ((rv = i >= 0)) {
goog.array.removeAt(arr, i);
}
return rv;
};
/**
* Removes from an array the element at index i
* @param {goog.array.ArrayLike} arr Array or array like object from which to
* remove value.
* @param {number} i The index to remove.
* @return {boolean} True if an element was removed.
*/
goog.array.removeAt = function(arr, i) {
goog.asserts.assert(arr.length != null);
// use generic form of splice
// splice returns the removed items and if successful the length of that
// will be 1
return goog.array.ARRAY_PROTOTYPE_.splice.call(arr, i, 1).length == 1;
};
/**
* Removes the first value that satisfies the given condition.
* @param {Array<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?) : boolean} f The function to call
* for every element. This function
* takes 3 arguments (the element, the index and the array) and should
* return a boolean.
* @param {S=} opt_obj An optional "this" context for the function.
* @return {boolean} True if an element was removed.
* @template T,S
*/
goog.array.removeIf = function(arr, f, opt_obj) {
var i = goog.array.findIndex(arr, f, opt_obj);
if (i >= 0) {
goog.array.removeAt(arr, i);
return true;
}
return false;
};
/**
* Removes all values that satisfy the given condition.
* @param {Array<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?) : boolean} f The function to call
* for every element. This function
* takes 3 arguments (the element, the index and the array) and should
* return a boolean.
* @param {S=} opt_obj An optional "this" context for the function.
* @return {number} The number of items removed
* @template T,S
*/
goog.array.removeAllIf = function(arr, f, opt_obj) {
var removedCount = 0;
goog.array.forEachRight(arr, function(val, index) {
if (f.call(opt_obj, val, index, arr)) {
if (goog.array.removeAt(arr, index)) {
removedCount++;
}
}
});
return removedCount;
};
/**
* Returns a new array that is the result of joining the arguments. If arrays
* are passed then their items are added, however, if non-arrays are passed they
* will be added to the return array as is.
*
* Note that ArrayLike objects will be added as is, rather than having their
* items added.
*
* goog.array.concat([1, 2], [3, 4]) -> [1, 2, 3, 4]
* goog.array.concat(0, [1, 2]) -> [0, 1, 2]
* goog.array.concat([1, 2], null) -> [1, 2, null]
*
* There is bug in all current versions of IE (6, 7 and 8) where arrays created
* in an iframe become corrupted soon (not immediately) after the iframe is
* destroyed. This is common if loading data via goog.net.IframeIo, for specs.
* This corruption only affects the concat method which will start throwing
* Catastrophic Errors (#-2147418113).
*
* See http://endoflow.com/scratch/corrupted-arrays.html for a test case.
*
* Internally goog.array should use this, so that all methods will continue to
* work on these broken array objects.
*
* @param {...*} var_args Items to concatenate. Arrays will have each item
* added, while primitives and objects will be added as is.
* @return {!Array<?>} The new resultant array.
*/
goog.array.concat = function(var_args) {
return goog.array.ARRAY_PROTOTYPE_.concat.apply(
goog.array.ARRAY_PROTOTYPE_, arguments);
};
/**
* Returns a new array that contains the contents of all the arrays passed.
* @param {...!Array<T>} var_args
* @return {!Array<T>}
* @template T
*/
goog.array.join = function(var_args) {
return goog.array.ARRAY_PROTOTYPE_.concat.apply(
goog.array.ARRAY_PROTOTYPE_, arguments);
};
/**
* Converts an object to an array.
* @param {Array<T>|goog.array.ArrayLike} object The object to convert to an
* array.
* @return {!Array<T>} The object converted into an array. If object has a
* length property, every property indexed with a non-negative number
* less than length will be included in the result. If object does not
* have a length property, an empty array will be returned.
* @template T
*/
goog.array.toArray = function(object) {
var length = object.length;
// If length is not a number the following it false. This case is kept for
// backwards compatibility since there are callers that pass objects that are
// not array like.
if (length > 0) {
var rv = new Array(length);
for (var i = 0; i < length; i++) {
rv[i] = object[i];
}
return rv;
}
return [];
};
/**
* Does a shallow copy of an array.
* @param {Array<T>|goog.array.ArrayLike} arr Array or array-like object to
* clone.
* @return {!Array<T>} Clone of the input array.
* @template T
*/
goog.array.clone = goog.array.toArray;
/**
* Extends an array with another array, element, or "array like" object.
* This function operates 'in-place', it does not create a new Array.
*
* Example:
* var a = [];
* goog.array.extend(a, [0, 1]);
* a; // [0, 1]
* goog.array.extend(a, 2);
* a; // [0, 1, 2]
*
* @param {Array<VALUE>} arr1 The array to modify.
* @param {...(Array<VALUE>|VALUE)} var_args The elements or arrays of elements
* to add to arr1.
* @template VALUE
*/
goog.array.extend = function(arr1, var_args) {
for (var i = 1; i < arguments.length; i++) {
var arr2 = arguments[i];
if (goog.isArrayLike(arr2)) {
var len1 = arr1.length || 0;
var len2 = arr2.length || 0;
arr1.length = len1 + len2;
for (var j = 0; j < len2; j++) {
arr1[len1 + j] = arr2[j];
}
} else {
arr1.push(arr2);
}
}
};
/**
* Adds or removes elements from an array. This is a generic version of Array
* splice. This means that it might work on other objects similar to arrays,
* such as the arguments object.
*
* @param {Array<T>|goog.array.ArrayLike} arr The array to modify.
* @param {number|undefined} index The index at which to start changing the
* array. If not defined, treated as 0.
* @param {number} howMany How many elements to remove (0 means no removal. A
* value below 0 is treated as zero and so is any other non number. Numbers
* are floored).
* @param {...T} var_args Optional, additional elements to insert into the
* array.
* @return {!Array<T>} the removed elements.
* @template T
*/
goog.array.splice = function(arr, index, howMany, var_args) {
goog.asserts.assert(arr.length != null);
return goog.array.ARRAY_PROTOTYPE_.splice.apply(
arr, goog.array.slice(arguments, 1));
};
/**
* Returns a new array from a segment of an array. This is a generic version of
* Array slice. This means that it might work on other objects similar to
* arrays, such as the arguments object.
*
* @param {Array<T>|goog.array.ArrayLike} arr The array from
* which to copy a segment.
* @param {number} start The index of the first element to copy.
* @param {number=} opt_end The index after the last element to copy.
* @return {!Array<T>} A new array containing the specified segment of the
* original array.
* @template T
*/
goog.array.slice = function(arr, start, opt_end) {
goog.asserts.assert(arr.length != null);
// passing 1 arg to slice is not the same as passing 2 where the second is
// null or undefined (in that case the second argument is treated as 0).
// we could use slice on the arguments object and then use apply instead of
// testing the length
if (arguments.length <= 2) {
return goog.array.ARRAY_PROTOTYPE_.slice.call(arr, start);
} else {
return goog.array.ARRAY_PROTOTYPE_.slice.call(arr, start, opt_end);
}
};
/**
* Removes all duplicates from an array (retaining only the first
* occurrence of each array element). This function modifies the
* array in place and doesn't change the order of the non-duplicate items.
*
* For objects, duplicates are identified as having the same unique ID as
* defined by {@link goog.getUid}.
*
* Alternatively you can specify a custom hash function that returns a unique
* value for each item in the array it should consider unique.
*
* Runtime: N,
* Worstcase space: 2N (no dupes)
*
* @param {Array<T>|goog.array.ArrayLike} arr The array from which to remove
* duplicates.
* @param {Array=} opt_rv An optional array in which to return the results,
* instead of performing the removal inplace. If specified, the original
* array will remain unchanged.
* @param {function(T):string=} opt_hashFn An optional function to use to
* apply to every item in the array. This function should return a unique
* value for each item in the array it should consider unique.
* @template T
*/
goog.array.removeDuplicates = function(arr, opt_rv, opt_hashFn) {
var returnArray = opt_rv || arr;
var defaultHashFn = function(item) {
// Prefix each type with a single character representing the type to
// prevent conflicting keys (e.g. true and 'true').
return goog.isObject(item) ? 'o' + goog.getUid(item) :
(typeof item).charAt(0) + item;
};
var hashFn = opt_hashFn || defaultHashFn;
var seen = {}, cursorInsert = 0, cursorRead = 0;
while (cursorRead < arr.length) {
var current = arr[cursorRead++];
var key = hashFn(current);
if (!Object.prototype.hasOwnProperty.call(seen, key)) {
seen[key] = true;
returnArray[cursorInsert++] = current;
}
}
returnArray.length = cursorInsert;
};
/**
* Searches the specified array for the specified target using the binary
* search algorithm. If no opt_compareFn is specified, elements are compared
* using <code>goog.array.defaultCompare</code>, which compares the elements
* using the built in < and > operators. This will produce the expected
* behavior for homogeneous arrays of String(s) and Number(s). The array
* specified <b>must</b> be sorted in ascending order (as defined by the
* comparison function). If the array is not sorted, results are undefined.
* If the array contains multiple instances of the specified target value, any
* of these instances may be found.
*
* Runtime: O(log n)
*
* @param {Array<VALUE>|goog.array.ArrayLike} arr The array to be searched.
* @param {TARGET} target The sought value.
* @param {function(TARGET, VALUE): number=} opt_compareFn Optional comparison
* function by which the array is ordered. Should take 2 arguments to
* compare, and return a negative number, zero, or a positive number
* depending on whether the first argument is less than, equal to, or
* greater than the second.
* @return {number} Lowest index of the target value if found, otherwise
* (-(insertion point) - 1). The insertion point is where the value should
* be inserted into arr to preserve the sorted property. Return value >= 0
* iff target is found.
* @template TARGET, VALUE
*/
goog.array.binarySearch = function(arr, target, opt_compareFn) {
return goog.array.binarySearch_(arr,
opt_compareFn || goog.array.defaultCompare, false /* isEvaluator */,
target);
};
/**
* Selects an index in the specified array using the binary search algorithm.
* The evaluator receives an element and determines whether the desired index
* is before, at, or after it. The evaluator must be consistent (formally,
* goog.array.map(goog.array.map(arr, evaluator, opt_obj), goog.math.sign)
* must be monotonically non-increasing).
*
* Runtime: O(log n)
*
* @param {Array<VALUE>|goog.array.ArrayLike} arr The array to be searched.
* @param {function(this:THIS, VALUE, number, ?): number} evaluator
* Evaluator function that receives 3 arguments (the element, the index and
* the array). Should return a negative number, zero, or a positive number
* depending on whether the desired index is before, at, or after the
* element passed to it.
* @param {THIS=} opt_obj The object to be used as the value of 'this'
* within evaluator.
* @return {number} Index of the leftmost element matched by the evaluator, if
* such exists; otherwise (-(insertion point) - 1). The insertion point is
* the index of the first element for which the evaluator returns negative,
* or arr.length if no such element exists. The return value is non-negative
* iff a match is found.
* @template THIS, VALUE
*/
goog.array.binarySelect = function(arr, evaluator, opt_obj) {
return goog.array.binarySearch_(arr, evaluator, true /* isEvaluator */,
undefined /* opt_target */, opt_obj);
};
/**
* Implementation of a binary search algorithm which knows how to use both
* comparison functions and evaluators. If an evaluator is provided, will call
* the evaluator with the given optional data object, conforming to the
* interface defined in binarySelect. Otherwise, if a comparison function is
* provided, will call the comparison function against the given data object.
*
* This implementation purposefully does not use goog.bind or goog.partial for
* performance reasons.
*
* Runtime: O(log n)
*
* @param {Array<?>|goog.array.ArrayLike} arr The array to be searched.
* @param {function(?, ?, ?): number | function(?, ?): number} compareFn
* Either an evaluator or a comparison function, as defined by binarySearch
* and binarySelect above.
* @param {boolean} isEvaluator Whether the function is an evaluator or a
* comparison function.
* @param {?=} opt_target If the function is a comparison function, then
* this is the target to binary search for.
* @param {Object=} opt_selfObj If the function is an evaluator, this is an
* optional this object for the evaluator.
* @return {number} Lowest index of the target value if found, otherwise
* (-(insertion point) - 1). The insertion point is where the value should
* be inserted into arr to preserve the sorted property. Return value >= 0
* iff target is found.
* @private
*/
goog.array.binarySearch_ = function(arr, compareFn, isEvaluator, opt_target,
opt_selfObj) {
var left = 0; // inclusive
var right = arr.length; // exclusive
var found;
while (left < right) {
var middle = (left + right) >> 1;
var compareResult;
if (isEvaluator) {
compareResult = compareFn.call(opt_selfObj, arr[middle], middle, arr);
} else {
compareResult = compareFn(opt_target, arr[middle]);
}
if (compareResult > 0) {
left = middle + 1;
} else {
right = middle;
// We are looking for the lowest index so we can't return immediately.
found = !compareResult;
}
}
// left is the index if found, or the insertion point otherwise.
// ~left is a shorthand for -left - 1.
return found ? left : ~left;
};
/**
* Sorts the specified array into ascending order. If no opt_compareFn is
* specified, elements are compared using
* <code>goog.array.defaultCompare</code>, which compares the elements using
* the built in < and > operators. This will produce the expected behavior
* for homogeneous arrays of String(s) and Number(s), unlike the native sort,
* but will give unpredictable results for heterogenous lists of strings and
* numbers with different numbers of digits.
*
* This sort is not guaranteed to be stable.
*
* Runtime: Same as <code>Array.prototype.sort</code>
*
* @param {Array<T>} arr The array to be sorted.
* @param {?function(T,T):number=} opt_compareFn Optional comparison
* function by which the
* array is to be ordered. Should take 2 arguments to compare, and return a
* negative number, zero, or a positive number depending on whether the
* first argument is less than, equal to, or greater than the second.
* @template T
*/
goog.array.sort = function(arr, opt_compareFn) {
// TODO(arv): Update type annotation since null is not accepted.
arr.sort(opt_compareFn || goog.array.defaultCompare);
};
/**
* Sorts the specified array into ascending order in a stable way. If no
* opt_compareFn is specified, elements are compared using
* <code>goog.array.defaultCompare</code>, which compares the elements using
* the built in < and > operators. This will produce the expected behavior
* for homogeneous arrays of String(s) and Number(s).
*
* Runtime: Same as <code>Array.prototype.sort</code>, plus an additional
* O(n) overhead of copying the array twice.
*
* @param {Array<T>} arr The array to be sorted.
* @param {?function(T, T): number=} opt_compareFn Optional comparison function
* by which the array is to be ordered. Should take 2 arguments to compare,
* and return a negative number, zero, or a positive number depending on
* whether the first argument is less than, equal to, or greater than the
* second.
* @template T
*/
goog.array.stableSort = function(arr, opt_compareFn) {
for (var i = 0; i < arr.length; i++) {
arr[i] = {index: i, value: arr[i]};
}
var valueCompareFn = opt_compareFn || goog.array.defaultCompare;
function stableCompareFn(obj1, obj2) {
return valueCompareFn(obj1.value, obj2.value) || obj1.index - obj2.index;
};
goog.array.sort(arr, stableCompareFn);
for (var i = 0; i < arr.length; i++) {
arr[i] = arr[i].value;
}
};
/**
* Sort the specified array into ascending order based on item keys
* returned by the specified key function.
* If no opt_compareFn is specified, the keys are compared in ascending order
* using <code>goog.array.defaultCompare</code>.
*
* Runtime: O(S(f(n)), where S is runtime of <code>goog.array.sort</code>
* and f(n) is runtime of the key function.
*
* @param {Array<T>} arr The array to be sorted.
* @param {function(T): K} keyFn Function taking array element and returning
* a key used for sorting this element.
* @param {?function(K, K): number=} opt_compareFn Optional comparison function
* by which the keys are to be ordered. Should take 2 arguments to compare,
* and return a negative number, zero, or a positive number depending on
* whether the first argument is less than, equal to, or greater than the
* second.
* @template T,K
*/
goog.array.sortByKey = function(arr, keyFn, opt_compareFn) {
var keyCompareFn = opt_compareFn || goog.array.defaultCompare;
goog.array.sort(arr, function(a, b) {
return keyCompareFn(keyFn(a), keyFn(b));
});
};
/**
* Sorts an array of objects by the specified object key and compare
* function. If no compare function is provided, the key values are
* compared in ascending order using <code>goog.array.defaultCompare</code>.
* This won't work for keys that get renamed by the compiler. So use
* {'foo': 1, 'bar': 2} rather than {foo: 1, bar: 2}.
* @param {Array<Object>} arr An array of objects to sort.
* @param {string} key The object key to sort by.
* @param {Function=} opt_compareFn The function to use to compare key
* values.
*/
goog.array.sortObjectsByKey = function(arr, key, opt_compareFn) {
goog.array.sortByKey(arr,
function(obj) { return obj[key]; },
opt_compareFn);
};
/**
* Tells if the array is sorted.
* @param {!Array<T>} arr The array.
* @param {?function(T,T):number=} opt_compareFn Function to compare the
* array elements.
* Should take 2 arguments to compare, and return a negative number, zero,
* or a positive number depending on whether the first argument is less
* than, equal to, or greater than the second.
* @param {boolean=} opt_strict If true no equal elements are allowed.
* @return {boolean} Whether the array is sorted.
* @template T
*/
goog.array.isSorted = function(arr, opt_compareFn, opt_strict) {
var compare = opt_compareFn || goog.array.defaultCompare;
for (var i = 1; i < arr.length; i++) {
var compareResult = compare(arr[i - 1], arr[i]);
if (compareResult > 0 || compareResult == 0 && opt_strict) {
return false;
}
}
return true;
};
/**
* Compares two arrays for equality. Two arrays are considered equal if they
* have the same length and their corresponding elements are equal according to
* the comparison function.
*
* @param {goog.array.ArrayLike} arr1 The first array to compare.
* @param {goog.array.ArrayLike} arr2 The second array to compare.
* @param {Function=} opt_equalsFn Optional comparison function.
* Should take 2 arguments to compare, and return true if the arguments
* are equal. Defaults to {@link goog.array.defaultCompareEquality} which
* compares the elements using the built-in '===' operator.
* @return {boolean} Whether the two arrays are equal.
*/
goog.array.equals = function(arr1, arr2, opt_equalsFn) {
if (!goog.isArrayLike(arr1) || !goog.isArrayLike(arr2) ||
arr1.length != arr2.length) {
return false;
}
var l = arr1.length;
var equalsFn = opt_equalsFn || goog.array.defaultCompareEquality;
for (var i = 0; i < l; i++) {
if (!equalsFn(arr1[i], arr2[i])) {
return false;
}
}
return true;
};
/**
* 3-way array compare function.
* @param {!Array<VALUE>|!goog.array.ArrayLike} arr1 The first array to
* compare.
* @param {!Array<VALUE>|!goog.array.ArrayLike} arr2 The second array to
* compare.
* @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison
* function by which the array is to be ordered. Should take 2 arguments to
* compare, and return a negative number, zero, or a positive number
* depending on whether the first argument is less than, equal to, or
* greater than the second.
* @return {number} Negative number, zero, or a positive number depending on
* whether the first argument is less than, equal to, or greater than the
* second.
* @template VALUE
*/
goog.array.compare3 = function(arr1, arr2, opt_compareFn) {
var compare = opt_compareFn || goog.array.defaultCompare;
var l = Math.min(arr1.length, arr2.length);
for (var i = 0; i < l; i++) {
var result = compare(arr1[i], arr2[i]);
if (result != 0) {
return result;
}
}
return goog.array.defaultCompare(arr1.length, arr2.length);
};
/**
* Compares its two arguments for order, using the built in < and >
* operators.
* @param {VALUE} a The first object to be compared.
* @param {VALUE} b The second object to be compared.
* @return {number} A negative number, zero, or a positive number as the first
* argument is less than, equal to, or greater than the second,
* respectively.
* @template VALUE
*/
goog.array.defaultCompare = function(a, b) {
return a > b ? 1 : a < b ? -1 : 0;
};
/**
* Compares its two arguments for inverse order, using the built in < and >
* operators.
* @param {VALUE} a The first object to be compared.
* @param {VALUE} b The second object to be compared.
* @return {number} A negative number, zero, or a positive number as the first
* argument is greater than, equal to, or less than the second,
* respectively.
* @template VALUE
*/
goog.array.inverseDefaultCompare = function(a, b) {
return -goog.array.defaultCompare(a, b);
};
/**
* Compares its two arguments for equality, using the built in === operator.
* @param {*} a The first object to compare.
* @param {*} b The second object to compare.
* @return {boolean} True if the two arguments are equal, false otherwise.
*/
goog.array.defaultCompareEquality = function(a, b) {
return a === b;
};
/**
* Inserts a value into a sorted array. The array is not modified if the
* value is already present.
* @param {Array<VALUE>|goog.array.ArrayLike} array The array to modify.
* @param {VALUE} value The object to insert.
* @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison
* function by which the array is ordered. Should take 2 arguments to
* compare, and return a negative number, zero, or a positive number
* depending on whether the first argument is less than, equal to, or
* greater than the second.
* @return {boolean} True if an element was inserted.
* @template VALUE
*/
goog.array.binaryInsert = function(array, value, opt_compareFn) {
var index = goog.array.binarySearch(array, value, opt_compareFn);
if (index < 0) {
goog.array.insertAt(array, value, -(index + 1));
return true;
}
return false;
};
/**
* Removes a value from a sorted array.
* @param {!Array<VALUE>|!goog.array.ArrayLike} array The array to modify.
* @param {VALUE} value The object to remove.
* @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison
* function by which the array is ordered. Should take 2 arguments to
* compare, and return a negative number, zero, or a positive number
* depending on whether the first argument is less than, equal to, or
* greater than the second.
* @return {boolean} True if an element was removed.
* @template VALUE
*/
goog.array.binaryRemove = function(array, value, opt_compareFn) {
var index = goog.array.binarySearch(array, value, opt_compareFn);
return (index >= 0) ? goog.array.removeAt(array, index) : false;
};
/**
* Splits an array into disjoint buckets according to a splitting function.
* @param {Array<T>} array The array.
* @param {function(this:S, T,number,Array<T>):?} sorter Function to call for
* every element. This takes 3 arguments (the element, the index and the
* array) and must return a valid object key (a string, number, etc), or
* undefined, if that object should not be placed in a bucket.
* @param {S=} opt_obj The object to be used as the value of 'this' within
* sorter.
* @return {!Object} An object, with keys being all of the unique return values
* of sorter, and values being arrays containing the items for
* which the splitter returned that key.
* @template T,S
*/
goog.array.bucket = function(array, sorter, opt_obj) {
var buckets = {};
for (var i = 0; i < array.length; i++) {
var value = array[i];
var key = sorter.call(opt_obj, value, i, array);
if (goog.isDef(key)) {
// Push the value to the right bucket, creating it if necessary.
var bucket = buckets[key] || (buckets[key] = []);
bucket.push(value);
}
}
return buckets;
};
/**
* Creates a new object built from the provided array and the key-generation
* function.
* @param {Array<T>|goog.array.ArrayLike} arr Array or array like object over
* which to iterate whose elements will be the values in the new object.
* @param {?function(this:S, T, number, ?) : string} keyFunc The function to
* call for every element. This function takes 3 arguments (the element, the
* index and the array) and should return a string that will be used as the
* key for the element in the new object. If the function returns the same
* key for more than one element, the value for that key is
* implementation-defined.
* @param {S=} opt_obj The object to be used as the value of 'this'
* within keyFunc.
* @return {!Object<T>} The new object.
* @template T,S
*/
goog.array.toObject = function(arr, keyFunc, opt_obj) {
var ret = {};
goog.array.forEach(arr, function(element, index) {
ret[keyFunc.call(opt_obj, element, index, arr)] = element;
});
return ret;
};
/**
* Creates a range of numbers in an arithmetic progression.
*
* Range takes 1, 2, or 3 arguments:
* <pre>
* range(5) is the same as range(0, 5, 1) and produces [0, 1, 2, 3, 4]
* range(2, 5) is the same as range(2, 5, 1) and produces [2, 3, 4]
* range(-2, -5, -1) produces [-2, -3, -4]
* range(-2, -5, 1) produces [], since stepping by 1 wouldn't ever reach -5.
* </pre>
*
* @param {number} startOrEnd The starting value of the range if an end argument
* is provided. Otherwise, the start value is 0, and this is the end value.
* @param {number=} opt_end The optional end value of the range.
* @param {number=} opt_step The step size between range values. Defaults to 1
* if opt_step is undefined or 0.
* @return {!Array<number>} An array of numbers for the requested range. May be
* an empty array if adding the step would not converge toward the end
* value.
*/
goog.array.range = function(startOrEnd, opt_end, opt_step) {
var array = [];
var start = 0;
var end = startOrEnd;
var step = opt_step || 1;
if (opt_end !== undefined) {
start = startOrEnd;
end = opt_end;
}
if (step * (end - start) < 0) {
// Sign mismatch: start + step will never reach the end value.
return [];
}
if (step > 0) {
for (var i = start; i < end; i += step) {
array.push(i);
}
} else {
for (var i = start; i > end; i += step) {
array.push(i);
}
}
return array;
};
/**
* Returns an array consisting of the given value repeated N times.
*
* @param {VALUE} value The value to repeat.
* @param {number} n The repeat count.
* @return {!Array<VALUE>} An array with the repeated value.
* @template VALUE
*/
goog.array.repeat = function(value, n) {
var array = [];
for (var i = 0; i < n; i++) {
array[i] = value;
}
return array;
};
/**
* Returns an array consisting of every argument with all arrays
* expanded in-place recursively.
*
* @param {...*} var_args The values to flatten.
* @return {!Array<?>} An array containing the flattened values.
*/
goog.array.flatten = function(var_args) {
var CHUNK_SIZE = 8192;
var result = [];
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (goog.isArray(element)) {
for (var c = 0; c < element.length; c += CHUNK_SIZE) {
var chunk = goog.array.slice(element, c, c + CHUNK_SIZE);
var recurseResult = goog.array.flatten.apply(null, chunk);
for (var r = 0; r < recurseResult.length; r++) {
result.push(recurseResult[r]);
}
}
} else {
result.push(element);
}
}
return result;
};
/**
* Rotates an array in-place. After calling this method, the element at
* index i will be the element previously at index (i - n) %
* array.length, for all values of i between 0 and array.length - 1,
* inclusive.
*
* For specs, suppose list comprises [t, a, n, k, s]. After invoking
* rotate(array, 1) (or rotate(array, -4)), array will comprise [s, t, a, n, k].
*
* @param {!Array<T>} array The array to rotate.
* @param {number} n The amount to rotate.
* @return {!Array<T>} The array.
* @template T
*/
goog.array.rotate = function(array, n) {
goog.asserts.assert(array.length != null);
if (array.length) {
n %= array.length;
if (n > 0) {
goog.array.ARRAY_PROTOTYPE_.unshift.apply(array, array.splice(-n, n));
} else if (n < 0) {
goog.array.ARRAY_PROTOTYPE_.push.apply(array, array.splice(0, -n));
}
}
return array;
};
/**
* Moves one item of an array to a new position keeping the order of the rest
* of the items. Example use case: keeping a list of JavaScript objects
* synchronized with the corresponding list of DOM elements after one of the
* elements has been dragged to a new position.
* @param {!(Array|Arguments|{length:number})} arr The array to modify.
* @param {number} fromIndex Index of the item to move between 0 and
* {@code arr.length - 1}.
* @param {number} toIndex Target index between 0 and {@code arr.length - 1}.
*/
goog.array.moveItem = function(arr, fromIndex, toIndex) {
goog.asserts.assert(fromIndex >= 0 && fromIndex < arr.length);
goog.asserts.assert(toIndex >= 0 && toIndex < arr.length);
// Remove 1 item at fromIndex.
var removedItems = goog.array.ARRAY_PROTOTYPE_.splice.call(arr, fromIndex, 1);
// Insert the removed item at toIndex.
goog.array.ARRAY_PROTOTYPE_.splice.call(arr, toIndex, 0, removedItems[0]);
// We don't use goog.array.insertAt and goog.array.removeAt, because they're
// significantly slower than splice.
};
/**
* Creates a new array for which the element at position i is an array of the
* ith element of the provided arrays. The returned array will only be as long
* as the shortest array provided; additional values are ignored. For specs,
* the result of zipping [1, 2] and [3, 4, 5] is [[1,3], [2, 4]].
*
* This is similar to the zip() function in Python. See {@link
* http://docs.python.org/library/functions.html#zip}
*
* @param {...!goog.array.ArrayLike} var_args Arrays to be combined.
* @return {!Array<!Array<?>>} A new array of arrays created from
* provided arrays.
*/
goog.array.zip = function(var_args) {
if (!arguments.length) {
return [];
}
var result = [];
var minLen = arguments[0].length;
for (var i = 1; i < arguments.length; i++) {
if (arguments[i].length < minLen) {
minLen = arguments[i].length;
}
}
for (var i = 0; i < minLen; i++) {
var value = [];
for (var j = 0; j < arguments.length; j++) {
value.push(arguments[j][i]);
}
result.push(value);
}
return result;
};
/**
* Shuffles the values in the specified array using the Fisher-Yates in-place
* shuffle (also known as the Knuth Shuffle). By default, calls Math.random()
* and so resets the state of that random number generator. Similarly, may reset
* the state of the any other specified random number generator.
*
* Runtime: O(n)
*
* @param {!Array<?>} arr The array to be shuffled.
* @param {function():number=} opt_randFn Optional random function to use for
* shuffling.
* Takes no arguments, and returns a random number on the interval [0, 1).
* Defaults to Math.random() using JavaScript's built-in Math library.
*/
goog.array.shuffle = function(arr, opt_randFn) {
var randFn = opt_randFn || Math.random;
for (var i = arr.length - 1; i > 0; i--) {
// Choose a random array index in [0, i] (inclusive with i).
var j = Math.floor(randFn() * (i + 1));
var tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
};
/**
* Returns a new array of elements from arr, based on the indexes of elements
* provided by index_arr. For specs, the result of index copying
* ['a', 'b', 'c'] with index_arr [1,0,0,2] is ['b', 'a', 'a', 'c'].
*
* @param {!Array<T>} arr The array to get a indexed copy from.
* @param {!Array<number>} index_arr An array of indexes to get from arr.
* @return {!Array<T>} A new array of elements from arr in index_arr order.
* @template T
*/
goog.array.copyByIndex = function(arr, index_arr) {
var result = [];
goog.array.forEach(index_arr, function(index) {
result.push(arr[index]);
});
return result;
};
|
/*! Buefy v0.9.10 | MIT License | github.com/buefy/buefy */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.Loading = {}));
}(this, function (exports) { 'use strict';
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
/**
* Merge function to replace Object.assign with deep merging possibility
*/
var isObject = function isObject(item) {
return _typeof(item) === 'object' && !Array.isArray(item);
};
var mergeFn = function mergeFn(target, source) {
var deep = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (deep || !Object.assign) {
var isDeep = function isDeep(prop) {
return isObject(source[prop]) && target !== null && target.hasOwnProperty(prop) && isObject(target[prop]);
};
var replaced = Object.getOwnPropertyNames(source).map(function (prop) {
return _defineProperty({}, prop, isDeep(prop) ? mergeFn(target[prop], source[prop], deep) : source[prop]);
}).reduce(function (a, b) {
return _objectSpread2({}, a, {}, b);
}, {});
return _objectSpread2({}, target, {}, replaced);
} else {
return Object.assign(target, source);
}
};
var merge = mergeFn;
function removeElement(el) {
if (typeof el.remove !== 'undefined') {
el.remove();
} else if (typeof el.parentNode !== 'undefined' && el.parentNode !== null) {
el.parentNode.removeChild(el);
}
}
// Polyfills for SSR
var isSSR = typeof window === 'undefined';
var HTMLElement = isSSR ? Object : window.HTMLElement;
var File = isSSR ? Object : window.File;
//
var script = {
name: 'BLoading',
// deprecated, to replace with default 'value' in the next breaking change
model: {
prop: 'active',
event: 'update:active'
},
props: {
active: Boolean,
programmatic: Boolean,
container: [Object, Function, HTMLElement],
isFullPage: {
type: Boolean,
default: true
},
animation: {
type: String,
default: 'fade'
},
canCancel: {
type: Boolean,
default: false
},
onCancel: {
type: Function,
default: function _default() {}
}
},
data: function data() {
return {
isActive: this.active || false,
displayInFullPage: this.isFullPage
};
},
watch: {
active: function active(value) {
this.isActive = value;
},
isFullPage: function isFullPage(value) {
this.displayInFullPage = value;
}
},
methods: {
/**
* Close the Modal if canCancel.
*/
cancel: function cancel() {
if (!this.canCancel || !this.isActive) return;
this.close();
},
/**
* Emit events, and destroy modal if it's programmatic.
*/
close: function close() {
var _this = this;
this.onCancel.apply(null, arguments);
this.$emit('close');
this.$emit('update:active', false); // Timeout for the animation complete before destroying
if (this.programmatic) {
this.isActive = false;
setTimeout(function () {
_this.$destroy();
removeElement(_this.$el);
}, 150);
}
},
/**
* Keypress event that is bound to the document.
*/
keyPress: function keyPress(_ref) {
var key = _ref.key;
if (key === 'Escape' || key === 'Esc') this.cancel();
}
},
created: function created() {
if (typeof window !== 'undefined') {
document.addEventListener('keyup', this.keyPress);
}
},
beforeMount: function beforeMount() {
// Insert the Loading component in body tag
// only if it's programmatic
if (this.programmatic) {
if (!this.container) {
document.body.appendChild(this.$el);
} else {
this.displayInFullPage = false;
this.$emit('update:is-full-page', false);
this.container.appendChild(this.$el);
}
}
},
mounted: function mounted() {
if (this.programmatic) this.isActive = true;
},
beforeDestroy: function beforeDestroy() {
if (typeof window !== 'undefined') {
document.removeEventListener('keyup', this.keyPress);
}
}
};
function normalizeComponent(template, style, script, scopeId, isFunctionalTemplate, moduleIdentifier
/* server only */
, shadowMode, createInjector, createInjectorSSR, createInjectorShadow) {
if (typeof shadowMode !== 'boolean') {
createInjectorSSR = createInjector;
createInjector = shadowMode;
shadowMode = false;
} // Vue.extend constructor export interop.
var options = typeof script === 'function' ? script.options : script; // render functions
if (template && template.render) {
options.render = template.render;
options.staticRenderFns = template.staticRenderFns;
options._compiled = true; // functional template
if (isFunctionalTemplate) {
options.functional = true;
}
} // scopedId
if (scopeId) {
options._scopeId = scopeId;
}
var hook;
if (moduleIdentifier) {
// server build
hook = function hook(context) {
// 2.3 injection
context = context || // cached call
this.$vnode && this.$vnode.ssrContext || // stateful
this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext; // functional
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__;
} // inject component styles
if (style) {
style.call(this, createInjectorSSR(context));
} // register component module identifier for async chunk inference
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier);
}
}; // used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook;
} else if (style) {
hook = shadowMode ? function () {
style.call(this, createInjectorShadow(this.$root.$options.shadowRoot));
} : function (context) {
style.call(this, createInjector(context));
};
}
if (hook) {
if (options.functional) {
// register for functional component in vue file
var originalRender = options.render;
options.render = function renderWithStyleInjection(h, context) {
hook.call(context);
return originalRender(h, context);
};
} else {
// inject component registration as beforeCreate hook
var existing = options.beforeCreate;
options.beforeCreate = existing ? [].concat(existing, hook) : [hook];
}
}
return script;
}
var normalizeComponent_1 = normalizeComponent;
/* script */
const __vue_script__ = script;
/* template */
var __vue_render__ = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('transition',{attrs:{"name":_vm.animation}},[(_vm.isActive)?_c('div',{staticClass:"loading-overlay is-active",class:{ 'is-full-page': _vm.displayInFullPage }},[_c('div',{staticClass:"loading-background",on:{"click":_vm.cancel}}),_vm._t("default",[_c('div',{staticClass:"loading-icon"})])],2):_vm._e()])};
var __vue_staticRenderFns__ = [];
/* style */
const __vue_inject_styles__ = undefined;
/* scoped */
const __vue_scope_id__ = undefined;
/* module identifier */
const __vue_module_identifier__ = undefined;
/* functional template */
const __vue_is_functional_template__ = false;
/* style inject */
/* style inject SSR */
var Loading = normalizeComponent_1(
{ render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ },
__vue_inject_styles__,
__vue_script__,
__vue_scope_id__,
__vue_is_functional_template__,
__vue_module_identifier__,
undefined,
undefined
);
var VueInstance;
var use = function use(plugin) {
if (typeof window !== 'undefined' && window.Vue) {
window.Vue.use(plugin);
}
};
var registerComponent = function registerComponent(Vue, component) {
Vue.component(component.name, component);
};
var registerComponentProgrammatic = function registerComponentProgrammatic(Vue, property, component) {
if (!Vue.prototype.$buefy) Vue.prototype.$buefy = {};
Vue.prototype.$buefy[property] = component;
};
var localVueInstance;
var LoadingProgrammatic = {
open: function open(params) {
var defaultParam = {
programmatic: true
};
var propsData = merge(defaultParam, params);
var vm = typeof window !== 'undefined' && window.Vue ? window.Vue : localVueInstance || VueInstance;
var LoadingComponent = vm.extend(Loading);
return new LoadingComponent({
el: document.createElement('div'),
propsData: propsData
});
}
};
var Plugin = {
install: function install(Vue) {
localVueInstance = Vue;
registerComponent(Vue, Loading);
registerComponentProgrammatic(Vue, 'loading', LoadingProgrammatic);
}
};
use(Plugin);
exports.BLoading = Loading;
exports.LoadingProgrammatic = LoadingProgrammatic;
exports.default = Plugin;
Object.defineProperty(exports, '__esModule', { value: true });
}));
|
/**
* @description Google Chart Api Directive Module for AngularJS
* @version 0.0.8
* @author Nicolas Bouillon <nicolas@bouil.org>
* @author GitHub contributors
* @license MIT
* @year 2013
*/
(function (document, window) {
'use strict';
angular.module('googlechart', [])
.constant('googleChartApiConfig', {
version: '1',
optionalSettings: {
packages: ['corechart']
}
})
.provider('googleJsapiUrl', function () {
var protocol = 'https:';
var url = '//www.google.com/jsapi';
this.setProtocol = function(newProtocol) {
protocol = newProtocol;
};
this.setUrl = function(newUrl) {
url = newUrl;
};
this.$get = function() {
return (protocol ? protocol : '') + url;
};
})
.factory('googleChartApiPromise', ['$rootScope', '$q', 'googleChartApiConfig', 'googleJsapiUrl', function ($rootScope, $q, apiConfig, googleJsapiUrl) {
var apiReady = $q.defer();
var onLoad = function () {
// override callback function
var settings = {
callback: function () {
var oldCb = apiConfig.optionalSettings.callback;
$rootScope.$apply(function () {
apiReady.resolve();
});
if (angular.isFunction(oldCb)) {
oldCb.call(this);
}
}
};
settings = angular.extend({}, apiConfig.optionalSettings, settings);
window.google.load('visualization', apiConfig.version, settings);
};
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.src = googleJsapiUrl;
head.appendChild(script);
script.onreadystatechange = function () {
if (this.readyState == 'complete') {
onLoad();
}
};
script.onload = onLoad;
return apiReady.promise;
}])
.directive('googleChart', ['$timeout', '$window', '$rootScope', 'googleChartApiPromise', function ($timeout, $window, $rootScope, googleChartApiPromise) {
return {
restrict: 'A',
scope: {
chart: '=chart',
onReady: '&',
select: '&'
},
link: function ($scope, $elm, $attr) {
// Watches, to refresh the chart when its data, title or dimensions change
$scope.$watch('chart', function () {
drawAsync();
}, true); // true is for deep object equality checking
// Redraw the chart if the window is resized
$rootScope.$on('resizeMsg', function (e) {
$timeout(function () {
// Not always defined yet in IE so check
if($scope.chartWrapper) {
drawAsync();
}
});
});
function applyFormat(formatType, formatClass, dataTable) {
if (typeof($scope.chart.formatters[formatType]) != 'undefined') {
if ($scope.formatters[formatType] == null) {
$scope.formatters[formatType] = new Array();
if (formatType === 'color') {
for (var cIdx = 0; cIdx < $scope.chart.formatters[formatType].length; cIdx++) {
var colorFormat = new formatClass();
for (var i = 0; i < $scope.chart.formatters[formatType][cIdx].formats.length; i++) {
var data = $scope.chart.formatters[formatType][cIdx].formats[i];
if (typeof(data.fromBgColor) != 'undefined' && typeof(data.toBgColor) != 'undefined')
colorFormat.addGradientRange(data.from, data.to, data.color, data.fromBgColor, data.toBgColor);
else
colorFormat.addRange(data.from, data.to, data.color, data.bgcolor);
}
$scope.formatters[formatType].push(colorFormat)
}
} else {
for (var i = 0; i < $scope.chart.formatters[formatType].length; i++) {
$scope.formatters[formatType].push(new formatClass(
$scope.chart.formatters[formatType][i])
);
}
}
}
//apply formats to dataTable
for (var i = 0; i < $scope.formatters[formatType].length; i++) {
if ($scope.chart.formatters[formatType][i].columnNum < dataTable.getNumberOfColumns())
$scope.formatters[formatType][i].format(dataTable, $scope.chart.formatters[formatType][i].columnNum);
}
//Many formatters require HTML tags to display special formatting
if (formatType === 'arrow' || formatType === 'bar' || formatType === 'color')
$scope.chart.options.allowHtml = true;
}
}
function draw() {
if (!draw.triggered && ($scope.chart != undefined)) {
draw.triggered = true;
$timeout(function () {
draw.triggered = false;
if (typeof($scope.formatters) === 'undefined')
$scope.formatters = {};
var dataTable;
if ($scope.chart.data instanceof google.visualization.DataTable)
dataTable = $scope.chart.data;
else if (Array.isArray($scope.chart.data))
dataTable = google.visualization.arrayToDataTable($scope.chart.data);
else
dataTable = new google.visualization.DataTable($scope.chart.data, 0.5);
if (typeof($scope.chart.formatters) != 'undefined') {
applyFormat("number", google.visualization.NumberFormat, dataTable);
applyFormat("arrow", google.visualization.ArrowFormat, dataTable);
applyFormat("date", google.visualization.DateFormat, dataTable);
applyFormat("bar", google.visualization.BarFormat, dataTable);
applyFormat("color", google.visualization.ColorFormat, dataTable);
}
var customFormatters = $scope.chart.customFormatters;
if (typeof(customFormatters) != 'undefined') {
for (name in customFormatters) {
applyFormat(name, customFormatters[name], dataTable);
}
}
var chartWrapperArgs = {
chartType: $scope.chart.type,
dataTable: dataTable,
view: $scope.chart.view,
options: $scope.chart.options,
containerId: $elm[0]
};
if ($scope.chartWrapper == null) {
$scope.chartWrapper = new google.visualization.ChartWrapper(chartWrapperArgs);
google.visualization.events.addListener($scope.chartWrapper, 'ready', function () {
$scope.chart.displayed = true;
$scope.$apply(function (scope) {
scope.onReady({chartWrapper: scope.chartWrapper});
});
});
google.visualization.events.addListener($scope.chartWrapper, 'error', function (err) {
console.log("Chart not displayed due to error: " + err.message + ". Full error object follows.");
console.log(err);
});
google.visualization.events.addListener($scope.chartWrapper, 'select', function () {
var selectedItem = $scope.chartWrapper.getChart().getSelection()[0];
if (selectedItem) {
$scope.$apply(function () {
$scope.select({selectedItem: selectedItem});
});
}
});
}
else {
$scope.chartWrapper.setChartType($scope.chart.type);
$scope.chartWrapper.setDataTable(dataTable);
$scope.chartWrapper.setView($scope.chart.view);
$scope.chartWrapper.setOptions($scope.chart.options);
}
$timeout(function () {
$scope.chartWrapper.draw();
});
}, 0, true);
}
}
function drawAsync() {
googleChartApiPromise.then(function () {
draw();
})
}
}
};
}])
.run(['$rootScope', '$window', function ($rootScope, $window) {
angular.element($window).bind('resize', function () {
$rootScope.$emit('resizeMsg');
});
}]);
})(document, window); |
var babylon = require('babylonjs');
const TEXTURE_PATH = 'textures/dragon.png';
export default class Dragon {
constructor(options) {
// First animated player
this.sprite = new babylon.Sprite("player", new babylon.SpriteManager('dragonManager', TEXTURE_PATH, 2, 128, options.scene));
this.sprite.playAnimation(12, 16, true, 100);
this.sprite.position.z = 2;
this.sprite.position.y = 2;
this.sprite.size = 1;
this.sprite.isPickable = true;
var player = options.player;
options.scene.registerBeforeRender(() => {
var baseSpeed = 0.05;
var maxSpeed = player.camera.speed + baseSpeed;
var curSpeed = baseSpeed;
//distance between dragon and player in XZ plane
var distance = Math.sqrt(Math.pow(player.position.x-this.sprite.position.x, 2)+Math.pow(player.position.z-this.sprite.position.z, 2));
if (distance <= 1){
curSpeed = maxSpeed;
}
else if (distance <= 20) {
curSpeed = (20-distance)/20 * player.camera.speed;
if (player.crazy) {
curSpeed *= 0.5;
}
else {
curSpeed *= 1.5;
}
}
this.sprite.position.z += curSpeed;
});
}
}
|
"use strict";
angular.module('frsApp.login', ['firebase.utils', 'firebase.auth', 'ngRoute', 'frsApp.countries'])
.controller('LoginCtrl', ['$scope', 'Auth', '$location', 'fbutil', 'APPNAME', 'CountryService',
function($scope, Auth, $location, fbutil, APPNAME, countries) {
$scope.email = null;
$scope.pass = null;
$scope.confirm = null;
$scope.createMode = false;
$scope.countries = [];
$scope.account = {
country: "",
users: []
};
countries.ref().on('child_added', function(snapshot) {
$scope.countries.push({
code: snapshot.key(),
name: snapshot.child('name').val()
});
$scope.$apply();
});
$scope.login = function(email, pass) {
$scope.err = null;
Auth.$authWithPassword({
email: email,
password: pass
}, {
rememberMe: true
})
.then(function( /* user */ ) {
$location.path('/home');
}, function(err) {
$scope.err = errMessage(err);
});
};
$scope.createAccount = function() {
$scope.err = null;
var email = $scope.email;
var pass = $scope.pass;
// create user credentials in Firebase auth system
Auth.$createUser({
email: email,
password: pass
})
.then(function() {
// authenticate so we have permission to write to Firebase
return Auth.$authWithPassword({
email: email,
password: pass
});
})
.then(function(user) {
// create a user profile in our data store
var usersRef = fbutil.ref('users', user.uid);
usersRef.set({
email: email,
name: firstPartOfEmail(email),
app: APPNAME
}, function(error) {
if (error) {
$scope.err = error;
}
else {
var accountsRef = fbutil.ref('accounts');
var newAccountRef = accountsRef.push($scope.account);
newAccountRef.child('users/' + Auth.$getAuth().uid).set(true, function(error) {
if (error) {
$scope.err = error;
} else {
$location.path("/account");
}
});
}
});
});
};
function assertValidAccountProps() {
if (!$scope.email) {
$scope.err = 'Please enter an email address';
}
else if (!$scope.pass || !$scope.confirm) {
$scope.err = 'Please enter a password';
}
else if ($scope.createMode && $scope.pass !== $scope.confirm) {
$scope.err = 'Passwords do not match';
}
return !$scope.err;
}
function errMessage(err) {
return angular.isObject(err) && err.code ? err.code : err + '';
}
function firstPartOfEmail(email) {
return ucfirst(email.substr(0, email.indexOf('@')) || '');
}
function ucfirst(str) {
// inspired by: http://kevin.vanzonneveld.net
str += '';
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
}
}])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {
controller: 'LoginCtrl',
templateUrl: 'login/login.html'
});
$routeProvider.when('/signup', {
templateUrl: 'login/signup.html',
controller: 'LoginCtrl'
});
}]); |
// import jwtUtils from './jsonwebtoken';
const store = global.localStorage;
const document = global.document;
const fetchFromStore = (key) => {
// load any stored value from sessionStorage
let initValue = store && store.getItem(key);
if (typeof initValue !== 'undefined') {
try {
initValue = JSON.parse(initValue);
} catch (e) {
// Nothing
}
}
return initValue;
};
const storeValue = (key, value) => {
store.setItem(key, value);
};
const storeCookie = (name, value, days) => {
let expires;
if (days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = `; expires=${date.toGMTString()}`;
} else {
expires = '';
}
document.cookie = `${name}=${value}${expires}; path=/`;
};
const eraseCookie = (name) => {
storeCookie(name, '', -1);
};
let userProfile;
const decodeUserFromJwt = (jwt) => {
const decoded = jwtUtils.decode(jwt, { complete: true });
userProfile = decoded.payload.profile;
return userProfile;
};
const decodeAllJwt = (jwt) => {
const decoded = jwtUtils.decode(jwt, { complete: true });
const { payload } = decoded;
return payload;
};
let refreshJwtTimerId;
function storeJwt(data, refreshJwt) {
if (data.jwt && data.jwt !== 'undefined') {
// store raw jwt
storeValue('jwt', data.jwt);
// decode and store mapUserId
decodeUserFromJwt(data.jwt);
}
if (typeof refreshJwt === 'function') {
clearInterval(refreshJwtTimerId);
refreshJwtTimerId = setInterval(refreshJwt, 5 * 60 * 1000);
}
if (data.refresh_token) {
// Store refresh token
storeValue('refreshToken', data.refresh_token);
}
}
function storePolicy(data) {
const { policy, signature } = data;
const keyId = data.key_id;
storeCookie('CloudFront-Policy', policy);
storeCookie('CloudFront-Key-Pair-Id', keyId);
storeCookie('CloudFront-Signature', signature);
}
function clearPolicy() {
eraseCookie('CloudFront-Policy', '');
eraseCookie('CloudFront-Key-Pair-Id', '');
eraseCookie('CloudFront-Signature', '');
}
// Init JWT from session store
let sessionJwt = fetchFromStore('jwt');
if (sessionJwt) {
storeJwt({ jwt: sessionJwt });
}
function readOnlyJwt() {
return fetchFromStore('jwt');
}
function readOnlyRefreshToken() {
return fetchFromStore('refreshToken');
}
function readOnlyPolicy() {
const policy = fetchFromStore('policy');
const keyId = fetchFromStore('keyId');
const signature = fetchFromStore('signature');
return { policy, keyId, signature };
}
function readOnlyUser() {
sessionJwt = fetchFromStore('jwt');
if (sessionJwt) {
if (sessionJwt === 'undefined') {
storeValue('jwt', null);
} else {
return decodeUserFromJwt(sessionJwt);
}
}
return null;
}
function readOnlyUserData() {
sessionJwt = fetchFromStore('jwt');
if (sessionJwt) {
if (sessionJwt === 'undefined') {
storeValue('jwt', null);
} else {
return decodeAllJwt(sessionJwt);
}
}
return null;
}
function logout() {
// clear JWT
storeValue('jwt', null);
// clear user data
userProfile = null;
// Clear refresh token
storeValue('refreshToken', null);
clearInterval(refreshJwtTimerId);
clearPolicy();
}
module.exports = {
storeJwt,
storePolicy,
jwt: readOnlyJwt,
refreshToken: readOnlyRefreshToken,
userData: readOnlyUserData,
user: readOnlyUser,
policy: readOnlyPolicy,
logout,
};
|
const { compactThemeSingle } = require('./theme');
const defaultTheme = require('./default-theme');
module.exports = {
...compactThemeSingle,
...defaultTheme
} |
// Minimum Moves to Equal Array Elements
// Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal,
// where a move is incrementing n - 1 elements by 1.
// Example:
// Input:
// [1,2,3]
// Output:
// 3
// Explanation:
// Only three moves are needed (remember each move increments two elements):
// [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
/**
* @param {array[]} nums
* @return {number}
*/
// --------------------------------------------------
// Adding 1 to n - 1 elements is the same as subtracting 1 from one element, goal of making the elements in the array equal.
// So, best way to do this is make all the elements in the array equal to the min element.
// sum(array) - n * minimum
// create var steps to keep track of steps and return at the end
// create var min by grabbing the min val of array
// loop through nums
// subtract the current value by the minimum value and add it to the steps var
// return steps
var minMoves = function(nums) { // 132 ms
var steps = 0,
min = Math.min(...nums);
for(var i=0; i<nums.length; i++){
steps+= nums[i] - min;
}
return steps;
};
// ---------- TIME LIMIT EXCEEDS OVER 9,999,999 STEPS
// create var index to keep track of smallest value's place in the array
// create var steps to keep track of steps and return at the end
// create helper function to check if all elements in the arr are the same value
// create while loop that breaks once every element in arr are the same
// grab place of the smallest element in arr
// incrememnt element
// increment steps
// return steps
var minMoves = function(nums) {
var index,
steps = 0;
function sameVals(arr){
return arr.every(x => x === arr[0]);
}
while( !sameVals(nums) ){
index = nums.indexOf( Math.min.apply(null, nums) );
nums[index]++;
steps++;
}
return steps;
};
|
"use strict";
/**
* @license
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
Object.defineProperty(exports, "__esModule", { value: true });
var tf = require("./index");
var jasmine_util_1 = require("./jasmine_util");
var test_util_1 = require("./test_util");
var fn2workerURL = function (fn) {
var blob = new Blob(['(' + fn.toString() + ')()'], { type: 'application/javascript' });
return URL.createObjectURL(blob);
};
// The source code of a web worker.
var workerTest = function () {
//@ts-ignore
importScripts('http://bs-local.com:12345/base/dist/tf-core.min.js');
var a = tf.tensor1d([1, 2, 3]);
var b = tf.tensor1d([3, 2, 1]);
a = a.add(b);
//@ts-ignore
self.postMessage({ data: a.dataSync() });
};
jasmine_util_1.describeWithFlags('computation in worker', jasmine_util_1.HAS_WORKER, function () {
it('tensor in worker', function (done) {
var worker = new Worker(fn2workerURL(workerTest));
worker.onmessage = function (msg) {
var data = msg.data.data;
test_util_1.expectArraysClose(data, [4, 4, 4]);
done();
};
});
});
//# sourceMappingURL=worker_test.js.map |
import { darken, lighten, adjust, invert } from 'khroma';
import { mkBorder } from './theme-helpers';
class Theme {
constructor() {
/* Base vales */
this.background = '#f4f4f4';
this.primaryColor = '#cde498';
this.secondaryColor = '#cdffb2';
this.background = 'white';
this.mainBkg = '#cde498';
this.secondBkg = '#cdffb2';
this.lineColor = 'green';
this.border1 = '#13540c';
this.border2 = '#6eaa49';
this.arrowheadColor = 'green';
this.fontFamily = '"trebuchet ms", verdana, arial, sans-serif';
this.fontSize = '16px';
this.tertiaryColor = lighten('#cde498', 10);
this.primaryBorderColor = mkBorder(this.primaryColor, this.darkMode);
this.secondaryBorderColor = mkBorder(this.secondaryColor, this.darkMode);
this.tertiaryBorderColor = mkBorder(this.tertiaryColor, this.darkMode);
this.primaryTextColor = invert(this.primaryColor);
this.secondaryTextColor = invert(this.secondaryColor);
this.tertiaryTextColor = invert(this.primaryColor);
this.lineColor = invert(this.background);
this.textColor = invert(this.background);
/* Flowchart variables */
this.nodeBkg = 'calculated';
this.nodeBorder = 'calculated';
this.clusterBkg = 'calculated';
this.clusterBorder = 'calculated';
this.defaultLinkColor = 'calculated';
this.titleColor = '#333';
this.edgeLabelBackground = '#e8e8e8';
/* Sequence Diagram variables */
this.actorBorder = 'calculated';
this.actorBkg = 'calculated';
this.actorTextColor = 'black';
this.actorLineColor = 'grey';
this.signalColor = '#333';
this.signalTextColor = '#333';
this.labelBoxBkgColor = 'calculated';
this.labelBoxBorderColor = '#326932';
this.labelTextColor = 'calculated';
this.loopTextColor = 'calculated';
this.noteBorderColor = 'calculated';
this.noteBkgColor = '#fff5ad';
this.noteTextColor = 'calculated';
this.activationBorderColor = '#666';
this.activationBkgColor = '#f4f4f4';
this.sequenceNumberColor = 'white';
/* Gantt chart variables */
this.sectionBkgColor = '#6eaa49';
this.altSectionBkgColor = 'white';
this.sectionBkgColor2 = '#6eaa49';
this.taskBorderColor = 'calculated';
this.taskBkgColor = '#487e3a';
this.taskTextLightColor = 'white';
this.taskTextColor = 'calculated';
this.taskTextDarkColor = 'black';
this.taskTextOutsideColor = 'calculated';
this.taskTextClickableColor = '#003163';
this.activeTaskBorderColor = 'calculated';
this.activeTaskBkgColor = 'calculated';
this.gridColor = 'lightgrey';
this.doneTaskBkgColor = 'lightgrey';
this.doneTaskBorderColor = 'grey';
this.critBorderColor = '#ff8888';
this.critBkgColor = 'red';
this.todayLineColor = 'red';
/* state colors */
this.labelColor = 'black';
this.errorBkgColor = '#552222';
this.errorTextColor = '#552222';
}
updateColors() {
/* Flowchart variables */
this.nodeBkg = this.mainBkg;
this.nodeBorder = this.border1;
this.clusterBkg = this.secondBkg;
this.clusterBorder = this.border2;
this.defaultLinkColor = this.lineColor;
/* Sequence Diagram variables */
this.actorBorder = darken(this.mainBkg, 20);
this.actorBkg = this.mainBkg;
this.labelBoxBkgColor = this.actorBkg;
this.labelTextColor = this.actorTextColor;
this.loopTextColor = this.actorTextColor;
this.noteBorderColor = this.border2;
this.noteTextColor = this.actorTextColor;
/* Gantt chart variables */
this.taskBorderColor = this.border1;
this.taskTextColor = this.taskTextLightColor;
this.taskTextOutsideColor = this.taskTextDarkColor;
this.activeTaskBorderColor = this.taskBorderColor;
this.activeTaskBkgColor = this.mainBkg;
/* state colors */
/* class */
this.classText = this.primaryTextColor;
/* journey */
this.fillType0 = this.primaryColor;
this.fillType1 = this.secondaryColor;
this.fillType2 = adjust(this.primaryColor, { h: 64 });
this.fillType3 = adjust(this.secondaryColor, { h: 64 });
this.fillType4 = adjust(this.primaryColor, { h: -64 });
this.fillType5 = adjust(this.secondaryColor, { h: -64 });
this.fillType6 = adjust(this.primaryColor, { h: 128 });
this.fillType7 = adjust(this.secondaryColor, { h: 128 });
}
calculate(overrides) {
if (typeof overrides !== 'object') {
// Calculate colors form base colors
this.updateColors();
return;
}
const keys = Object.keys(overrides);
// Copy values from overrides, this is mainly for base colors
keys.forEach(k => {
this[k] = overrides[k];
});
// Calculate colors form base colors
this.updateColors();
// Copy values from overrides again in case of an override of derived value
keys.forEach(k => {
this[k] = overrides[k];
});
}
}
export const getThemeVariables = userOverrides => {
const theme = new Theme();
theme.calculate(userOverrides);
return theme;
};
|
/* global module:false */
module.exports = function(grunt) {
var port = grunt.option('port') || 8000;
var base = 'http://localhost';
// Project configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
connect: {
server: {
options: {
port: port,
hostname: '*',
livereload: true,
open: true
}
}
},
watch: {
options: {
livereload: true
},
html: {
files: ['*/**/*.html']
}
}
});
// Dependencies;
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-stylus');
// Serve presentation locally
grunt.registerTask('serve', ['connect', 'watch']);
};
|
/**
* @file child.js
* Colorbox Modal iframe pages' JS
*/
(function($) {
/**
* Colorbox Modal object for child windows.
*/
Drupal.cbmodal_child = Drupal.cbmodal_child || {
processed: false,
behaviors: {}
};
/**
* Child modal behavior.
*/
Drupal.cbmodal_child.attach = function(context) {
var self = Drupal.cbmodal_child;
var settings = Drupal.settings.bare_pages || {};
// If we cannot reach the parent window or if it doesn't have a Colorbox instance,
// then we have nothing else todo here.
try {
if (!self.isObject(parent.Drupal) || !$.isFunction(parent.jQuery.colorbox)) {
return;
}
}
catch(e) {
return;
}
// Make sure this behavior is not processed more than once.
if (!self.processed) {
self.processed = true;
// If a form has been submitted successfully, then the server side script
// may have decided to tell us the parent window to close the popup modal.
if (settings.closeModal) {
// Hack 2014/06/25 15:44:01 - modalframe original method for sending
// drupal messages of child page to the parent page appears now broken
// since the introduction of 'rebuild' to stay on the same page
// @see bare_pages_close_modal()
// @see bare_pages_form_submit()
// -> ugly copy/paste workaround, for now.
// Assumes <div id="js-messages-wrap"></div> always present in parent page theme page.tpl.php -_-
// @todo think about this (now rushing)
var $drupal_messages = $('.drupal-messages');
if ($drupal_messages.length) {
parent.jQuery('#js-messages-wrap').html('<div class="drupal-messages">' + $drupal_messages.html() + '</div>');
}
// Colorbox in parent window : close
parent.jQuery.colorbox.close();
return;
}
}
// Attach child related behaviors to the current context.
self.attachBehaviors(context);
};
/**
* Check if the given variable is an object.
*/
Drupal.cbmodal_child.isObject = function(something) {
return (something !== null && typeof something === 'object');
};
/**
* Attach child related behaviors to the iframed document.
*/
Drupal.cbmodal_child.attachBehaviors = function(context) {
$.each(this.behaviors, function() {
this(context);
});
};
/**
* Add target="_blank" to all external URLs.
*/
Drupal.cbmodal_child.behaviors.parseLinks = function(context) {
$('a:not(.cbmodal-processed)', context).addClass('cbmodal-processed').each(function() {
// Do not process links that have the class "cbmodal-exclude".
if ($(this).hasClass('cbmodal-exclude')) {
return;
}
// Obtain the href attribute of the link.
var href = $(this).attr('href');
// Do not process links with an empty href, javascript or that only have the fragment.
if (!href || href.length <= 0 || href.charAt(0) == '#' || href.indexOf('javascript') >= 0) {
return;
}
$(this).attr('target', '_blank');
});
};
/**
* Set iframe scrollbar visibility
* Only display scrollbar if parent browser viewport height is enough
* Hacky : if any interaction inside iframe changes the height, no way to scroll anymore...
*/
Drupal.cbmodal_child.behaviors.RemoveIframeScrollbar = function(context) {
// Delay a bit in case there are any post-load client-side modifications inside the iframe
setTimeout(function() {
var parent_browser_viewport_height = $(parent).height(),
child_page_body_height = $('body').outerHeight(),
margin = 50;
if (parent_browser_viewport_height > child_page_body_height + margin) {
parent.jQuery('#cboxLoadedContent .cboxIframe')
.css({
'height': child_page_body_height,
//'overflow-y': 'hidden'
})
.attr('scrolling','no');
}
}, 30);
};
/**
* Update Colorbox size to auto fit its content.
* From documentation :
* $.colorbox.resize() allows Colorbox to be resized based on it's own auto-calculations,
* or to a specific size. This must be called manually after Colorbox's content has loaded.
* The optional parameters object can accept width or innerWidth and height or innerHeight.
* Without specifying a width or height, Colorbox will attempt to recalculate the height
* of it's current content.
*/
Drupal.cbmodal_child.behaviors.resizeColorbox = function(context) {
// Delay a bit in case there are any post-load client-side modifications
setTimeout(function() {
parent.jQuery.colorbox.resize();
}, 50);
};
/**
* Attach our own behavior on top of the list of existing behaviors.
*
* We need to execute before everything else because the child frame is not
* visible until we bind the child window to the parent, and this may cause
* problems with other behaviors that need the document visible in order to
* do its own job.
*/
Drupal.behaviors.cbmodal_child = {};
Drupal.behaviors.cbmodal_child.attach = function (context, settings) {
Drupal.cbmodal_child.attach(context);
}
})(jQuery);
|
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var gutil = require('gulp-util');
var coffee = require('gulp-coffee');
// browserify bundle for direct browser use.
gulp.task("bundle", function(){
bundler = browserify('./src/javascript_sandbox.coffee',
{
transform: ['coffeeify'],
standalone: 'javascriptSandbox',
extensions: ['.coffee'],
debug: false
});
return bundler.bundle()
.pipe(source('javascript_sandbox.js'))
.pipe(gulp.dest('dist'));
});
// simple transpile if you want to bundle it yourself
// using this can reduce the size of your own bundle
gulp.task("transpile", function(){
gulp.src('./src/**/*.coffee')
.pipe(coffee({bare: true}).on('error', gutil.log))
.pipe(gulp.dest('./lib/'))
});
gulp.task("build", ["bundle", "transpile"]);
gulp.task("default", ["build"]);
|
import {generateId, passwordToHash, loadConfig} from './helper';
const escapeHTML = require('escape-html');
let config = loadConfig();
/* datastore */
import DataStore from './datastore';
var datastore = new DataStore(config);
var room_dicebot = {};
datastore.getAllDicebot(function(dicebots) {
room_dicebot = dicebots;
});
/* dicebot */
var dicebotList = {
'dicebot': '標準ダイスボット',
'cthulhu': 'クトゥルフ神話TRPG',
};
var dicebots = {};
for (const id in dicebotList) {
var c = require(`./dicebot/${id}`);
dicebots[id] = new c();
}
/* express */
const express = require('express');
const helmet = require('helmet');
const bodyParser = require('body-parser');
const app = express();
const server = require('http').Server(app);
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'", `${config.hostname}`, `ws://${config.hostname}`],
imgSrc: ["'self'", '*'],
},
},
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
var ECT = require('ect');
var ectRenderer = ECT({ watch: true, root: `${__dirname}/views`, ext : '.ect' });
app.engine('ect', ectRenderer.render);
app.set('view engine', 'ect');
app.get('/', function(req, res) {
datastore.getRooms(function(rooms, passwords) {
res.render('index', {
rooms: rooms,
passwords: passwords,
dicebot: dicebotList,
escape: escapeHTML,
});
});
});
app.post('/create-room', function (req, res) {
var room_id = generateId();
var room_name = req.param('room-name');
var room_password = req.param('room-password');
var dicebot_id = req.param('dicebot');
if (room_password != '') {
var hash = passwordToHash(room_password);
datastore.setPassword(room_id, hash);
}
if (!(dicebot_id in dicebotList)) {
dicebot_id = 'dicebot';
}
room_dicebot[room_id] = dicebot_id;
datastore.setDicebot(room_id, dicebot_id);
res.redirect('./' + room_id);
datastore.setRoom(room_id, room_name);
datastore.updateTime(room_id);
});
app.get('/licenses', function(req, res) {
res.sendFile(`${__dirname }/licenses.html`);
});
app.get('/:room_id', function(req, res) {
var room_id = req.params.room_id;
datastore.isExistRoom(room_id, function(err, is_exist) {
if (is_exist) {
datastore.isExistPassword(room_id, function (err, is_need_password) {
res.render('room', {
room_id: room_id,
is_need_password: is_need_password,
dicebots: dicebotList,
dicebot: room_dicebot[room_id],
escape: escapeHTML,
});
});
}
else {
res.redirect('./');
}
});
});
app.use(express.static('public'));
server.listen(config.port, function() {
console.log(`listening on ${config.host}`);
});
/* socketio */
var io = require('socket.io')(server);
var user_hash = {};
io.sockets.on('connection', function(socket) {
socket.on('connected', function(user) {
datastore.isExistRoom(user.room, function(err, is_exist) {
if (!is_exist) {
socket.disconnect();
return;
}
datastore.getPassword(user.room, function (err, pass) {
if (pass == null || pass == passwordToHash(user.password)) {
socket.emit('accepted');
datastore.getAllResult(user.room, function (err, results) {
results = results.map(JSON.parse);
socket.emit('init-result', results);
});
datastore.getAllMemo(user.room, function (err, memos) {
var res = {};
for (const memo_id in memos) {
res[memo_id] = JSON.parse(memos[memo_id]);
}
socket.emit('init-memo', res);
});
datastore.getAllPiece(user.room, function (err, pieces) {
var res = {};
for (const piece_id in pieces) {
res[piece_id] = JSON.parse(pieces[piece_id]);
}
socket.emit('init-piece', res);
});
datastore.getMap(user.room, function (err, url) {
if (url == null) {
url = './image/tsukuba.jpg';
}
socket.emit('map', {url: url});
});
datastore.updateTime(user.room);
var dicebot_id = room_dicebot[user.room];
var bot = dicebots[dicebot_id];
var res = {id: dicebot_id, name: bot.name, description: bot.description};
socket.emit('dicebot', res);
user_hash[socket.id] = user.name;
socket.name = user.name;
socket.room = user.room;
socket.join(user.room);
}
else {
socket.emit('rejected');
}
});
});
});
socket.on('user-name', function (user_name) {
user_hash[socket.id] = user_name;
});
socket.on('roll', function(request) {
var dicebot_id = room_dicebot[socket.room];
var dicebot = dicebots[dicebot_id];
var res = dicebot.roll(request);
if (res == null) {
return;
}
res['name'] = user_hash[socket.id];
res['request'] = request;
io.sockets.to(socket.room).emit('roll', res);
var result_text = `${request}→${(res.total || res.result)}`;
var json = JSON.stringify({name: user_hash[socket.id], text: result_text});
datastore.setResult(socket.room, json);
});
socket.on('dicebot', function(dicebot_id) {
if (!(dicebot_id in dicebotList)) {
return;
}
room_dicebot[socket.room] = dicebot_id;
var bot = dicebots[dicebot_id];
var res = {id: dicebot_id, name: bot.name, description: bot.description};
io.sockets.to(socket.room).emit('dicebot', res);
});
socket.on('memo', function(request) {
datastore.createMemo(socket.room, request.title, request.body, function(data) {
io.sockets.to(socket.room).emit('memo', data);
});
});
socket.on('update-memo', function(request) {
var data = {
memo_id: request.memo_id,
title: request.title,
body: request.body,
};
io.sockets.to(socket.room).emit('update-memo', data);
datastore.setMemo(socket.room, request.memo_id, JSON.stringify(data));
});
socket.on('delete-memo', function(memo_id) {
io.sockets.to(socket.room).emit('remove-memo', memo_id);
datastore.deleteMemo(socket.room, memo_id);
});
socket.on('map', function(request) {
io.sockets.to(socket.room).emit('map', request);
datastore.setMap(socket.room, request.url);
});
socket.on('add-piece', function(request) {
datastore.createPiece(socket.room, request, 0.5, 0.5, function(data) {
io.sockets.to(socket.room).emit('add-piece', data);
});
});
socket.on('move-piece', function(request) {
datastore.updatePiece(socket.room, request.piece_id, request.url, request.x, request.y);
io.sockets.to(socket.room).emit('move-piece', request);
});
socket.on('delete-piece', function(request) {
datastore.deletePiece(socket.room, request);
io.sockets.to(socket.room).emit('delete-piece', request);
});
socket.on('delete-room', function() {
io.sockets.to(socket.room).emit('room-deleted');
datastore.deleteRoom(socket.room);
});
socket.on('disconnect', function() {
if (user_hash[socket.id]) {
delete user_hash[socket.id];
}
datastore.updateTime(socket.room);
});
});
|
'use strict'
const BaseDelete = require('../delete');
/**
* `DELETE` statement.
*/
class Delete extends BaseDelete {
/**
* Sets some fields to the `RETURNING` clause.
*
* @param Object|Array fields The fields.
* @return Function Returns `this`.
*/
returning(fields) {
const arr = Array.isArray(fields) && arguments.length === 1
? fields
: Array.prototype.slice.call(arguments);
if (fields) {
this._parts.returning.push(...arr);
}
return this;
}
}
module.exports = Delete;
|
var socketIO=require("socket.io");
module.exports=function(server,params){
var defParams={
auth:undefined,
banner:"Welcome to HssH server",
log:"error"
};
var args={};
for (var key in defParams){
args[key]=defParams[key];
if (params[key]!=undefined){
args[key]=params[key];
}
}
var io=socketIO(server);
require("../log").transports.console.level=args.log;
io.on("connection",require("./onNewConnection")(io,args));
} |
// Set up a bridge between Model-R and postmessage.
//
// The convention is that everything sent via post-message is a JSON-encoded object with a
// field called "action" which is used to determine which message was sent.
//
// So, if we receive '{"action":"complete","status":200}' from the iframe,
// that will get converted into _public.triggerComplete({action:"complete", // "status":200});
//
// Conversely, if you call _public.triggerSubmit({to_url:"http://rapportive.com/foo"})
// that will be sent to the iframe as // '{"action":"submit","to_url","http://rapportive.com/foo"}'
//
// opts is an object with:
// {
// iframe|window: the iframe to send messages to and receive messages from
// receive: [a list of actions we expect to receive],
// send: [a list of actions we expect to send],
// model: [a list of fields to copy around amoungst the frames]
// remote_base_url: the url to send with postMessage to ensure it arrives at the correct domain
// }
//
// remote_base_url can be a function, in which case it is evaluated every time a message is sent.
// (useful if the destination URL cannot be determined at the time postMessageShim is declared).
lib.postMessageShim = function (_public, _protected, opts) {
var other = opts.iframe || opts.window,
debug = true;
function sendMessage(msg) {
if (debug) {
console.log((opts.name || 'pmshim') + " SENT-->: " + JSON.stringify(msg));
}
$.message(other, msg, (_.isFunction(opts.remote_base_url) ? opts.remote_base_url() : opts.remote_base_url));
}
if (opts.model) {
lib.model(_public, _protected, opts.model);
opts.receive = (opts.receive || []).concat(_(opts.model).map(function (field) {
return field + '_sync';
}));
_(opts.model).each(function (name) {
var syncedValue;
_public.on(name + '_sync', function (value) {
syncedValue = value.value;
_public[name] = value.value;
syncedValue = undefined;
});
_public.on(name + '_change', function (value) {
if (value !== syncedValue) {
sendMessage({action: name + '_sync', rapportive: true, value: value});
}
});
});
}
if (opts.receive) {
lib.hasEvent(_public, _protected, opts.receive);
// TODO: make sure "rapportive:true" is being set on all messages.
$.message(other, loggily("postmessageshim.message", function (msg, reply, e) {
if (_(opts.receive).include(msg.action)) {
if (debug) {
console.log((opts.name || 'pmshim') + " -->RECV: " + JSON.stringify(msg));
}
_public.trigger(msg.action, msg);
} else if (msg.rapportive) {
console.log((opts.name || 'pmshim') + " got unexpected postMessage: " + JSON.stringify(msg));
}
}));
}
if (opts.send) {
lib.hasEvent(_public, _protected, opts.send);
_(opts.send).each(function (name) {
_public.on(name, function (msg) {
sendMessage(_.extend({action: name, rapportive: true}, msg));
});
});
}
};
|
window.console&&console.log||function(){for(var i=function(){},n=["assert","clear","count","debug","dir","dirxml","error","exception","group","groupCollapsed","groupEnd","info","log","markTimeline","profile","profileEnd","markTimeline","table","time","timeEnd","timeStamp","trace","warn"],t=n.length,r=window.console={};t--;)r[n[t]]=i}(),function(n){n.validator&&(n.fn.updateValidation=function(){var t=this.closest("form").removeData("validator").removeData("unobtrusiveValidation");return n.validator.unobtrusive.parse(t),this})}(jQuery);$(function(){try{window.prettyPrint&&prettyPrint()}catch(n){console.log(n.message)}});
//# sourceMappingURL=plugins.min.js.map
|
// /*
// * @Author: Austen Morgan
// * @Date: 2016-07-03 20:04:37
// * @Last Modified by: AustenMorgan
// * @Last Modified time: 2016-10-26 19:37:48
// */
// 'use strict';
// function openOptions() {
// chrome.runtime.openOptionsPage();
// }
// document.querySelector('#openOptions').addEventListener('click', openOptions);
|
var Gym = require('../client/gym')
, sizzle = require('sizzle')
, getkeycode = require('keycode')
var iekeyup = function(k) {
var oEvent = document.createEvent('KeyboardEvent');
// Chromium Hack
Object.defineProperty(oEvent, 'keyCode', {
get : function() {
return this.keyCodeVal;
}
});
Object.defineProperty(oEvent, 'which', {
get : function() {
return this.keyCodeVal;
}
});
if (oEvent.initKeyboardEvent) {
oEvent.initKeyboardEvent("keypress", true, true, document.defaultView, false, false, false, false, k, k);
} else {
oEvent.initKeyEvent("keypress", true, true, document.defaultView, false, false, false, false, k, 0);
}
oEvent.keyCodeVal = k;
if (oEvent.keyCode !== k) {
alert("keyCode mismatch " + oEvent.keyCode + "(" + oEvent.which + ")");
}
document.dispatchEvent(oEvent);
}
function keyup(el, letter)
{
var keyCode = getkeycode(letter)
keyupcode(el, keyCode)
}
function keyupcode(el, keyCode) {
var eventObj = document.createEventObject ?
document.createEventObject() : document.createEvent("Events");
if(eventObj.initEvent){
eventObj.initEvent("keypress", true, true);
}
eventObj.keyCode = keyCode;
eventObj.which = keyCode;
//el.dispatchEvent ? el.dispatchEvent(eventObj) : el.fireEvent("onkeyup", eventObj);
if (eventObj.initEvent) {
el.dispatchEvent(eventObj)
} else {
iekeyup(keyCode)
}
}
describe('Gym page', function(){
var gym
var typedText
beforeEach(function(){
gym = new Gym({id: 1})
spyOn(gym.model, 'load')
gym.init()
gym.model.data = {
id: 1,
title: "Moby dick",
text: "Ishmael"
}
gym.render()
typedText = sizzle('#typedText', gym.element)
})
it('should show the excerpt text', function(){
var text = sizzle('#excerpt-text', gym.element)
expect(text[0].textContent).toContain('Ishmael')
})
describe('typing the "o" key', function(){
beforeEach(function(){
keyup(document.body, 'o')
})
it('should show the letter "o" on the screen', function(){
expect(typedText[0].textContent).toEqual("o")
})
describe('then typing the "e" key', function(){
beforeEach(function(){
keyup(document.body, 'e')
})
it('should show "oe" on the screen', function(){
expect(typedText[0].textContent).toEqual("oe")
})
describe('then clicking backspace', function(){
it('should show "o" on the screen', function(){
keyupcode(document.body, 8)
expect(typedText[0].innerHTML).toEqual("o")
})
})
})
})
describe('clicking the space key', function(){
beforeEach(function(){
keyup(document.body, ' ')
})
it('should show a space on the screen', function(){
expect(typedText[0].innerHTML).toEqual(" ")
})
describe('then clicking backspace', function(){
it('should empty line', function(){
keyupcode(document.body, 8)
expect(typedText[0].innerHTML).toEqual("")
})
})
})
})
|
import React, {Component} from "react";
import {Link} from "react-router-dom";
import AppBar from "material-ui/AppBar";
import Drawer from "material-ui/Drawer";
import MenuItem from "material-ui/MenuItem";
export default class Layout extends Component {
constructor() {
super();
this.state = {
open: false
};
}
closeMenu = () => this.setState({ open: false });
toggleMenu = () => this.setState(prevState => ({ open: !prevState.open }));
render() {
const {children, className} = this.props;
return (
<div id="app-container">
<AppBar title="Crapshoot Scaffolded App"
onLeftIconButtonClick={this.toggleMenu} />
<Drawer className="nav-bar"
docked={false}
width={200}
open={this.state.open}
onRequestChange={open => this.setState({open})}>
<Link to="/" onClick={this.closeMenu}>
<MenuItem>Home</MenuItem>
</Link>
<Link to="/todo" onClick={this.closeMenu}>
<MenuItem>Todos</MenuItem>
</Link>
</Drawer>
<div id="app-content">
<div className={className}>
{children}
</div>
</div>
</div>
);
}
}
|
'use strict';
(function(exports, undefined) {
function _emit(type, data) {
var handlers = Util.slice.call(this._notifyHash[type]);
for (var i = 0, l = handlers.length; i < l; i++) {
var j = Util.extend({}, handlers[i]);
var scope = (j.scope) ? j.scope : this;
j.scope = scope;
j.handler.call(j.scope, data, j);
}
};
function _detach(type) {
var handlers = this._notifyHash;
if (type) {
delete handlers[type];
} else {
this._notifyHash = {};
}
};
function _bind(key, handle) {
var events = key.split(' ');
for (var i = 0, l = events.length; i < l; i++) {
var t = events[i];
if (!this._notifyHash[t]) {
this._notifyHash[t] = [];
}
this._notifyHash[t].push({
'handler': handle,
'type': t
});
}
}
function Base() {
this._dataHash = {};
this._notifyHash = {};
};
var proto = {};
proto.on = function(arg1, arg2) {
if (Util.type(arg1) === 'object') {
for (var j in arg1) {
_bind.call(this, j, arg1[j]);
}
} else {
_bind.call(this, arg1, arg2);
}
return this;
};
proto.emit = function(types, data) {
var items = types.split(' ');
for (var i = 0, l = items.length; i < l; i++) {
var type = items[i];
if (this._notifyHash[type]) {
_emit.call(this, type, Util.type(data) === 'undefined' ? null : data);
}
}
return this;
};
proto.detach = function() {
_detach.apply(this, arguments);
return this;
};
proto.set = function(id, value) {
this._dataHash[id] = value;
};
proto.get = function(id) {
return this._dataHash[id];
};
proto.has = function(id) {
return !!this._dataHash[id];
};
proto.all = function() {
return this._dataHash;
};
proto.remove = function(id){
if(this._dataHash[id]) delete this._dataHash[id];
};
Util.augment(Base, proto);
exports.Base = Base;
})(this);
|
// Generated on 2017-07-04 using generator-angular-fullstack 3.8.0
'use strict';
import _ from 'lodash';
import del from 'del';
import gulp from 'gulp';
import grunt from 'grunt';
import path from 'path';
import gulpLoadPlugins from 'gulp-load-plugins';
import http from 'http';
import open from 'open';
import lazypipe from 'lazypipe';
import {stream as wiredep} from 'wiredep';
import nodemon from 'nodemon';
import {Server as KarmaServer} from 'karma';
import runSequence from 'run-sequence';
import {protractor, webdriver_update} from 'gulp-protractor';
import {Instrumenter} from 'isparta';
import nib from 'nib';
var plugins = gulpLoadPlugins();
var config;
const clientPath = require('./bower.json').appPath || 'client';
const serverPath = 'server';
const paths = {
client: {
assets: `${clientPath}/assets/**/*`,
images: `${clientPath}/assets/images/**/*`,
scripts: [
`${clientPath}/**/!(*.spec|*.mock).js`,
`!${clientPath}/bower_components/**/*`
],
styles: [`${clientPath}/{app,components}/**/*.styl`],
mainStyle: `${clientPath}/app/app.styl`,
views: `${clientPath}/{app,components}/**/*.html`,
mainView: `${clientPath}/index.html`,
test: [`${clientPath}/{app,components}/**/*.{spec,mock}.js`],
e2e: ['e2e/**/*.spec.js'],
bower: `${clientPath}/bower_components/`
},
server: {
scripts: [
`${serverPath}/**/!(*.spec|*.integration).js`,
`!${serverPath}/config/local.env.sample.js`
],
json: [`${serverPath}/**/*.json`],
test: {
integration: [`${serverPath}/**/*.integration.js`, 'mocha.global.js'],
unit: [`${serverPath}/**/*.spec.js`, 'mocha.global.js']
}
},
karma: 'karma.conf.js',
dist: 'dist'
};
/********************
* Helper functions
********************/
function onServerLog(log) {
console.log(plugins.util.colors.white('[') +
plugins.util.colors.yellow('nodemon') +
plugins.util.colors.white('] ') +
log.message);
}
function checkAppReady(cb) {
var options = {
host: 'localhost',
port: config.port
};
http
.get(options, () => cb(true))
.on('error', () => cb(false));
}
// Call page until first success
function whenServerReady(cb) {
var serverReady = false;
var appReadyInterval = setInterval(() =>
checkAppReady((ready) => {
if (!ready || serverReady) {
return;
}
clearInterval(appReadyInterval);
serverReady = true;
cb();
}),
100);
}
function sortModulesFirst(a, b) {
var module = /\.module\.js$/;
var aMod = module.test(a.path);
var bMod = module.test(b.path);
// inject *.module.js first
if (aMod === bMod) {
// either both modules or both non-modules, so just sort normally
if (a.path < b.path) {
return -1;
}
if (a.path > b.path) {
return 1;
}
return 0;
} else {
return (aMod ? -1 : 1);
}
}
/********************
* Reusable pipelines
********************/
let lintClientScripts = lazypipe()
.pipe(plugins.jshint, `${clientPath}/.jshintrc`)
.pipe(plugins.jshint.reporter, 'jshint-stylish');
let lintServerScripts = lazypipe()
.pipe(plugins.jshint, `${serverPath}/.jshintrc`)
.pipe(plugins.jshint.reporter, 'jshint-stylish');
let lintServerTestScripts = lazypipe()
.pipe(plugins.jshint, `${serverPath}/.jshintrc-spec`)
.pipe(plugins.jshint.reporter, 'jshint-stylish');
let styles = lazypipe()
.pipe(plugins.sourcemaps.init)
.pipe(plugins.stylus, {
use: [nib()],
errors: true
})
.pipe(plugins.autoprefixer, {browsers: ['last 1 version']})
.pipe(plugins.sourcemaps.write, '.');
let transpileClient = lazypipe()
.pipe(plugins.sourcemaps.init)
.pipe(plugins.babel)
.pipe(plugins.sourcemaps.write, '.');
let transpileServer = lazypipe()
.pipe(plugins.sourcemaps.init)
.pipe(plugins.babel, {
plugins: [
'transform-class-properties',
'transform-runtime'
]
})
.pipe(plugins.sourcemaps.write, '.');
let mocha = lazypipe()
.pipe(plugins.mocha, {
reporter: 'spec',
timeout: 5000,
require: [
'./mocha.conf'
]
});
let istanbul = lazypipe()
.pipe(plugins.istanbul.writeReports)
.pipe(plugins.istanbulEnforcer, {
thresholds: {
global: {
lines: 80,
statements: 80,
branches: 80,
functions: 80
}
},
coverageDirectory: './coverage',
rootDirectory : ''
});
/********************
* Env
********************/
gulp.task('env:all', () => {
let localConfig;
try {
localConfig = require(`./${serverPath}/config/local.env`);
} catch (e) {
localConfig = {};
}
plugins.env({
vars: localConfig
});
});
gulp.task('env:test', () => {
plugins.env({
vars: {NODE_ENV: 'test'}
});
});
gulp.task('env:prod', () => {
plugins.env({
vars: {NODE_ENV: 'production'}
});
});
/********************
* Tasks
********************/
gulp.task('inject', cb => {
runSequence(['inject:js', 'inject:css', 'inject:styl'], cb);
});
gulp.task('inject:js', () => {
return gulp.src(paths.client.mainView)
.pipe(plugins.inject(
gulp.src(_.union(paths.client.scripts, [`!${clientPath}/**/*.{spec,mock}.js`, `!${clientPath}/app/app.js`]), {read: false})
.pipe(plugins.sort(sortModulesFirst)),
{
starttag: '<!-- injector:js -->',
endtag: '<!-- endinjector -->',
transform: (filepath) => '<script src="' + filepath.replace(`/${clientPath}/`, '') + '"></script>'
}))
.pipe(gulp.dest(clientPath));
});
gulp.task('inject:css', () => {
return gulp.src(paths.client.mainView)
.pipe(plugins.inject(
gulp.src(`${clientPath}/{app,components}/**/*.css`, {read: false})
.pipe(plugins.sort()),
{
starttag: '<!-- injector:css -->',
endtag: '<!-- endinjector -->',
transform: (filepath) => '<link rel="stylesheet" href="' + filepath.replace(`/${clientPath}/`, '').replace('/.tmp/', '') + '">'
}))
.pipe(gulp.dest(clientPath));
});
gulp.task('inject:styl', () => {
return gulp.src(paths.client.mainStyle)
.pipe(plugins.inject(
gulp.src(_.union(paths.client.styles, ['!' + paths.client.mainStyle]), {read: false})
.pipe(plugins.sort()),
{
starttag: '/* inject:styl */',
endtag: '/* endinject */',
transform: (filepath) => {
let newPath = filepath
.replace(`/${clientPath}/app/`, '')
.replace(`/${clientPath}/components/`, '../components/')
.replace(/_(.*).styl/, (match, p1, offset, string) => p1)
.replace('.styl', '');
return `@import '${newPath}';`;
}
}))
.pipe(gulp.dest(`${clientPath}/app`));
});
gulp.task('styles', () => {
return gulp.src(paths.client.mainStyle)
.pipe(styles())
.pipe(gulp.dest('.tmp/app'));
});
gulp.task('transpile:client', () => {
return gulp.src(paths.client.scripts)
.pipe(transpileClient())
.pipe(gulp.dest('.tmp'));
});
gulp.task('transpile:server', () => {
return gulp.src(_.union(paths.server.scripts, paths.server.json))
.pipe(transpileServer())
.pipe(gulp.dest(`${paths.dist}/${serverPath}`));
});
gulp.task('lint:scripts', cb => runSequence(['lint:scripts:client', 'lint:scripts:server'], cb));
gulp.task('lint:scripts:client', () => {
return gulp.src(_.union(
paths.client.scripts,
_.map(paths.client.test, blob => '!' + blob),
[`!${clientPath}/app/app.constant.js`]
))
.pipe(lintClientScripts());
});
gulp.task('lint:scripts:server', () => {
return gulp.src(_.union(paths.server.scripts, _.map(paths.server.test, blob => '!' + blob)))
.pipe(lintServerScripts());
});
gulp.task('lint:scripts:clientTest', () => {
return gulp.src(paths.client.test)
.pipe(lintClientScripts());
});
gulp.task('lint:scripts:serverTest', () => {
return gulp.src(paths.server.test)
.pipe(lintServerTestScripts());
});
gulp.task('jscs', () => {
return gulp.src(_.union(paths.client.scripts, paths.server.scripts))
.pipe(plugins.jscs())
.pipe(plugins.jscs.reporter());
});
gulp.task('clean:tmp', () => del(['.tmp/**/*'], {dot: true}));
gulp.task('start:client', cb => {
whenServerReady(() => {
open('http://localhost:' + config.port);
cb();
});
});
gulp.task('start:server', () => {
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
config = require(`./${serverPath}/config/environment`);
nodemon(`-w ${serverPath} ${serverPath}`)
.on('log', onServerLog);
});
gulp.task('start:server:prod', () => {
process.env.NODE_ENV = process.env.NODE_ENV || 'production';
config = require(`./${paths.dist}/${serverPath}/config/environment`);
nodemon(`-w ${paths.dist}/${serverPath} ${paths.dist}/${serverPath}`)
.on('log', onServerLog);
});
gulp.task('start:inspector', () => {
gulp.src([])
.pipe(plugins.nodeInspector({
debugPort: 5858
}));
});
gulp.task('start:server:debug', () => {
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
config = require(`./${serverPath}/config/environment`);
nodemon(`-w ${serverPath} --debug=5858 --debug-brk ${serverPath}`)
.on('log', onServerLog);
});
gulp.task('watch', () => {
var testFiles = _.union(paths.client.test, paths.server.test.unit, paths.server.test.integration);
plugins.livereload.listen();
plugins.watch(paths.client.styles, () => { //['inject:styl']
gulp.src(paths.client.mainStyle)
.pipe(plugins.plumber())
.pipe(styles())
.pipe(gulp.dest('.tmp/app'))
.pipe(plugins.livereload());
});
plugins.watch(paths.client.views)
.pipe(plugins.plumber())
.pipe(plugins.livereload());
plugins.watch(paths.client.scripts) //['inject:js']
.pipe(plugins.plumber())
.pipe(transpileClient())
.pipe(gulp.dest('.tmp'))
.pipe(plugins.livereload());
plugins.watch(_.union(paths.server.scripts, testFiles))
.pipe(plugins.plumber())
.pipe(lintServerScripts())
.pipe(plugins.livereload());
gulp.watch('bower.json', ['wiredep:client']);
});
gulp.task('serve', cb => {
runSequence(['clean:tmp', 'constant', 'env:all'],
['lint:scripts', 'inject'],
['wiredep:client'],
['transpile:client', 'styles'],
['start:server', 'start:client'],
'watch',
cb);
});
gulp.task('serve:dist', cb => {
runSequence(
'build',
'env:all',
'env:prod',
['start:server:prod', 'start:client'],
cb);
});
gulp.task('serve:debug', cb => {
runSequence(['clean:tmp', 'constant'],
['lint:scripts', 'inject'],
['wiredep:client'],
['transpile:client', 'styles'],
'start:inspector',
['start:server:debug', 'start:client'],
'watch',
cb);
});
gulp.task('test', cb => {
return runSequence('test:server', 'test:client', cb);
});
gulp.task('test:server', cb => {
runSequence(
'env:all',
'env:test',
'mocha:unit',
'mocha:integration',
'mocha:coverage',
cb);
});
gulp.task('mocha:unit', () => {
return gulp.src(paths.server.test.unit)
.pipe(mocha());
});
gulp.task('mocha:integration', () => {
return gulp.src(paths.server.test.integration)
.pipe(mocha());
});
gulp.task('test:client', ['wiredep:test', 'constant'], (done) => {
new KarmaServer({
configFile: `${__dirname}/${paths.karma}`,
singleRun: true
}, done).start();
});
// inject bower components
gulp.task('wiredep:client', () => {
return gulp.src(paths.client.mainView)
.pipe(wiredep({
exclude: [
/bootstrap.js/,
'/json3/',
'/es5-shim/',
/font-awesome\.css/,
/bootstrap\.css/
],
ignorePath: clientPath
}))
.pipe(gulp.dest(`${clientPath}/`));
});
gulp.task('wiredep:test', () => {
return gulp.src(paths.karma)
.pipe(wiredep({
exclude: [
/bootstrap.js/,
'/json3/',
'/es5-shim/',
/font-awesome\.css/,
/bootstrap\.css/
],
devDependencies: true
}))
.pipe(gulp.dest('./'));
});
/********************
* Build
********************/
//FIXME: looks like font-awesome isn't getting loaded
gulp.task('build', cb => {
runSequence(
[
'clean:dist',
'clean:tmp'
],
'inject',
'wiredep:client',
[
'transpile:client',
'transpile:server'
],
[
'build:images',
'copy:extras',
'copy:fonts',
'copy:assets',
'copy:server',
'build:client'
],
cb);
});
gulp.task('clean:dist', () => del([`${paths.dist}/!(.git*|.openshift|Procfile)**`], {dot: true}));
gulp.task('build:client', ['styles', 'html', 'constant', 'build:images'], () => {
var manifest = gulp.src(`${paths.dist}/${clientPath}/assets/rev-manifest.json`);
var appFilter = plugins.filter('**/app.js', {restore: true, dot: true});
var jsFilter = plugins.filter('**/*.js', {restore: true, dot: true});
var cssFilter = plugins.filter('**/*.css', {restore: true, dot: true});
var htmlBlock = plugins.filter(['**/*.!(html)'], {restore: true, dot: true});
return gulp.src(paths.client.mainView)
.pipe(plugins.useref())
.pipe(appFilter)
.pipe(plugins.addSrc.append('.tmp/templates.js'))
.pipe(plugins.concat('app/app.js'))
.pipe(appFilter.restore)
.pipe(jsFilter)
.pipe(plugins.ngAnnotate())
.pipe(plugins.uglify())
.pipe(jsFilter.restore)
.pipe(cssFilter)
.pipe(plugins.cleanCss({
processImportFrom: ['!fonts.googleapis.com']
}))
.pipe(cssFilter.restore)
.pipe(htmlBlock)
.pipe(plugins.rev())
.pipe(htmlBlock.restore)
.pipe(plugins.revReplace({manifest}))
.pipe(gulp.dest(`${paths.dist}/${clientPath}`));
});
gulp.task('html', function() {
return gulp.src(`${clientPath}/{app,components}/**/*.html`)
.pipe(plugins.angularTemplatecache({
module: 'administracionRemotaApp'
}))
.pipe(gulp.dest('.tmp'));
});
gulp.task('constant', function() {
let sharedConfig = require(`./${serverPath}/config/environment/shared`);
return plugins.ngConstant({
name: 'administracionRemotaApp.constants',
deps: [],
wrap: true,
stream: true,
constants: { appConfig: sharedConfig }
})
.pipe(plugins.rename({
basename: 'app.constant'
}))
.pipe(gulp.dest(`${clientPath}/app/`))
});
gulp.task('build:images', () => {
return gulp.src(paths.client.images)
.pipe(plugins.imagemin({
optimizationLevel: 5,
progressive: true,
interlaced: true
}))
.pipe(plugins.rev())
.pipe(gulp.dest(`${paths.dist}/${clientPath}/assets/images`))
.pipe(plugins.rev.manifest(`${paths.dist}/${clientPath}/assets/rev-manifest.json`, {
base: `${paths.dist}/${clientPath}/assets`,
merge: true
}))
.pipe(gulp.dest(`${paths.dist}/${clientPath}/assets`));
});
gulp.task('copy:extras', () => {
return gulp.src([
`${clientPath}/favicon.ico`,
`${clientPath}/robots.txt`,
`${clientPath}/.htaccess`
], { dot: true })
.pipe(gulp.dest(`${paths.dist}/${clientPath}`));
});
gulp.task('copy:fonts', () => {
return gulp.src(`${clientPath}/bower_components/{bootstrap,font-awesome}/fonts/**/*`, { dot: true })
.pipe(gulp.dest(`${paths.dist}/${clientPath}/bower_components`));
});
gulp.task('copy:assets', () => {
return gulp.src([paths.client.assets, '!' + paths.client.images])
.pipe(gulp.dest(`${paths.dist}/${clientPath}/assets`));
});
gulp.task('copy:server', () => {
return gulp.src([
'package.json',
'bower.json',
'.bowerrc'
], {cwdbase: true})
.pipe(gulp.dest(paths.dist));
});
gulp.task('coverage:pre', () => {
return gulp.src(paths.server.scripts)
// Covering files
.pipe(plugins.istanbul({
instrumenter: Instrumenter, // Use the isparta instrumenter (code coverage for ES6)
includeUntested: true
}))
// Force `require` to return covered files
.pipe(plugins.istanbul.hookRequire());
});
gulp.task('coverage:unit', () => {
return gulp.src(paths.server.test.unit)
.pipe(mocha())
.pipe(istanbul())
// Creating the reports after tests ran
});
gulp.task('coverage:integration', () => {
return gulp.src(paths.server.test.integration)
.pipe(mocha())
.pipe(istanbul())
// Creating the reports after tests ran
});
gulp.task('mocha:coverage', cb => {
runSequence('coverage:pre',
'env:all',
'env:test',
'coverage:unit',
'coverage:integration',
cb);
});
// Downloads the selenium webdriver
gulp.task('webdriver_update', webdriver_update);
gulp.task('test:e2e', ['env:all', 'env:test', 'start:server', 'webdriver_update'], cb => {
gulp.src(paths.client.e2e)
.pipe(protractor({
configFile: 'protractor.conf.js',
})).on('error', err => {
console.log(err)
}).on('end', () => {
process.exit();
});
});
/********************
* Grunt ported tasks
********************/
grunt.initConfig({
buildcontrol: {
options: {
dir: paths.dist,
commit: true,
push: true,
connectCommits: false,
message: 'Built %sourceName% from commit %sourceCommit% on branch %sourceBranch%'
},
heroku: {
options: {
remote: 'heroku',
branch: 'master'
}
},
openshift: {
options: {
remote: 'openshift',
branch: 'master'
}
}
}
});
grunt.loadNpmTasks('grunt-build-control');
gulp.task('buildcontrol:heroku', function(done) {
grunt.tasks(
['buildcontrol:heroku'], //you can add more grunt tasks in this array
{gruntfile: false}, //don't look for a Gruntfile - there is none. :-)
function() {done();}
);
});
gulp.task('buildcontrol:openshift', function(done) {
grunt.tasks(
['buildcontrol:openshift'], //you can add more grunt tasks in this array
{gruntfile: false}, //don't look for a Gruntfile - there is none. :-)
function() {done();}
);
});
|
'use strict';
/* https://github.com/angular/protractor/blob/master/docs/toc.md */
describe('my app', function() {
it('should automatically redirect to /view1 when location hash/fragment is empty', function() {
browser.get('index.html');
expect(browser.getLocationAbsUrl()).toMatch("/home");
});
describe('profile', function() {
beforeEach(function() {
browser.get('index.html#!/profile');
});
// it('should render view1 when user navigates to /view1', function() {
// expect(element.all(by.css('[ng-view] p')).first().getText()).
// toMatch(/partial for view 1/);
// });
});
describe('view2', function() {
beforeEach(function() {
browser.get('index.html#!/view2');
});
// it('should render view2 when user navigates to /view2', function() {
// expect(element.all(by.css('[ng-view] p')).first().getText()).
// toMatch(/partial for view 2/);
// });
});
});
|
/*
*--------------------------------------------------------------------
* jQuery-Plugin "timetable-weekly"
* Version: 3.0
* Copyright (c) 2016 TIS
*
* Released under the MIT License.
* http://tis2010.jp/license.txt
* -------------------------------------------------------------------
*/
jQuery.noConflict();
(function($,PLUGIN_ID){
"use strict";
/*---------------------------------------------------------------
valiable
---------------------------------------------------------------*/
var vars={
cellposition:0,
cellwidth:13,
fromdate:new Date(),
todate:new Date(),
calendar:null,
table:null,
apps:{},
config:{},
levels:{},
offset:{},
segments:{},
colors:[],
displays:[],
fields:[],
segmentkeys:[],
fieldinfos:{}
};
var events={
lists:[
'app.record.index.show'
]
};
var limit=500;
var functions={
/* rebuild view */
build:function(filter,columnindex){
var color='';
var cells=[];
var positions={
min:vars.cellposition,
max:vars.cellposition
};
if (filter.length!=0)
{
var date=new Date(filter[0][vars.config['date']].value.dateformat());
for (var i=0;i<filter.length;i++)
{
/* create cell */
var fromtime=new Date((date.format('Y-m-d')+'T'+filter[i][vars.config['fromtime']].value+':00+09:00').dateformat());
var totime=new Date((date.format('Y-m-d')+'T'+filter[i][vars.config['totime']].value+':00+09:00').dateformat());
var from=(fromtime.getHours())*parseInt(vars.config['scale'])+Math.floor(fromtime.getMinutes()/(60/parseInt(vars.config['scale'])));
var to=(totime.getHours())*parseInt(vars.config['scale'])+Math.ceil(totime.getMinutes()/(60/parseInt(vars.config['scale'])))-1;
var row=vars.table.contents.find('tr').eq(from);
var position=positions.min;
if (from<parseInt(vars.config['starthour'])*parseInt(vars.config['scale']))
{
from=parseInt(vars.config['starthour'])*parseInt(vars.config['scale']);
row=vars.table.contents.find('tr').eq(from);
}
if (to<parseInt(vars.config['starthour'])*parseInt(vars.config['scale'])) continue;
if (to>(parseInt(vars.config['endhour'])+1)*parseInt(vars.config['scale'])-1) to=(parseInt(vars.config['endhour'])+1)*parseInt(vars.config['scale'])-1;
from=vars.table.contents.find('tr').eq(from).position().top;
to=vars.table.contents.find('tr').eq(to).position().top+vars.table.contents.find('tr').eq(to).outerHeight(false);
/* check color */
for (var i2=0;i2<vars.colors.length;i2++)
{
var match=$.conditionsmatch(filter[i],vars.fieldinfos,JSON.parse(vars.colors[i2].conditions));
if (match) color=vars.colors[i2].color;
}
/* check cell appended */
var appended=[];
$.each(cells,function(index){
var cell=$(this);
var exists=false;
if ($.data(cell[0],'from')<from && $.data(cell[0],'to')>to) exists=true;
if ($.data(cell[0],'from')>from && $.data(cell[0],'from')<to) exists=true;
if ($.data(cell[0],'to')>from && $.data(cell[0],'to')<to) exists=true;
if (exists)
if ($.inArray($.data(cell[0],'position'),appended)<0) appended.push($.data(cell[0],'position'));
});
/* adds 1 to the maximum value for the new position */
for (var i2=positions.min;i2<positions.max+2;i2++) if ($.inArray(i2,appended)<0) {position=i2;break;}
if (positions.max<position) positions.max=position;
/* append cell */
var cell=$('<div class="timetable-weekly-cell">');
cell.css({
'background-color':'#'+color,
'cursor':'pointer',
'height':(to-from)+'px',
'left':(vars.cellwidth*position)+'px'
})
.on('click',function(){
sessionStorage.setItem('fromdate_timetable-weekly',vars.fromdate.format('Y-m-d').dateformat());
sessionStorage.setItem('todate_timetable-weekly',vars.todate.format('Y-m-d').dateformat());
window.location.href=kintone.api.url('/k/', true).replace(/\.json/g,'')+kintone.app.getId()+'/show#record='+$(this).find('input#id').val()+'&mode=show';
})
.append($('<input type="hidden">').attr('id','id').val(filter[i]['$id'].value));
cells.push(cell);
row.find('td').eq(columnindex).append(cell);
/* append balloon */
var balloon=$('<div class="timetable-balloon">');
var inner='';
inner='';
inner+='<p>';
if (vars.levels.lookup)
{
var levels=$.grep(vars.apps[vars.levels.app],function(item,index){
return item[vars.levels.relatedkey].value==filter[i][vars.levels.lookup].value;
});
if (levels.length!=0)
for (var i2=0;i2<vars.segmentkeys.length;i2++) inner+='<span>'+$.fieldvalue(levels[0][vars.segmentkeys[i2]])+'</span>';
}
else
{
$.each(vars.segments,function(key,values){
if (key!=vars.segmentkeys[0])
for (var i2=0;i2<values.records.length;i2++)
if (filter[i][key].value==values.records[i2].field) inner+='<span>'+values.records[i2].display+'</span>';
});
}
for (var i2=0;i2<vars.displays.length;i2++) inner+='<p>'+$.fieldvalue(filter[i][vars.displays[i2]])+'</p>';
inner+='<p>'+filter[i][vars.config['fromtime']].value+' ~ '+filter[i][vars.config['totime']].value+'</p>';
$('body').append(
balloon.css({
'z-index':(i+filter.length).toString()
})
.html(inner)
);
/* setup cell datas */
$.data(cell[0],'balloon',balloon);
$.data(cell[0],'columnindex',columnindex);
$.data(cell[0],'from',from);
$.data(cell[0],'position',position);
$.data(cell[0],'to',to);
/* mouse events */
cell.on({
'mouseenter':function(){$.data($(this)[0],'balloon').addClass('timetable-balloon-show');},
'mouseleave':function(){$.data($(this)[0],'balloon').removeClass('timetable-balloon-show');}
});
}
vars.cellposition=positions.max+1;
vars.table.head.find('th').eq(columnindex).css({'min-width':vars.cellwidth*vars.cellposition+'px'});
}
},
/* reload view */
load:function(){
/* after apprecords acquisition,rebuild view */
vars.apps[kintone.app.getId()]=null;
vars.offset[kintone.app.getId()]=0;
functions.loaddatas(kintone.app.getId(),function(){
var records=vars.apps[kintone.app.getId()];
/* initialize cells */
$('div.timetable-weekly-cell').remove();
$('div.timetable-balloon').remove();
$.each(vars.table.head.find('th'),function(index){
$(this).css({'width':'auto'}).empty();
})
for (var i=0;i<7;i++)
{
vars.cellposition=0;
vars.table.head.find('th').eq(i+1).append($('<p class="customview-p">').text(vars.fromdate.calc(i+' day').format('Y-m-d')))
vars.table.head.find('th').eq(i+1).append($('<button class="customview-button time-button">').text('タイムテーブルを表示').on('click',function(){
var query='';
query+='view='+vars.config.datetimetable;
query+='&'+vars.config['date']+'='+$(this).closest('th').find('p').text();
sessionStorage.setItem('fromdate_timetable-weekly',vars.fromdate.format('Y-m-d').dateformat());
sessionStorage.setItem('todate_timetable-weekly',vars.todate.format('Y-m-d').dateformat());
window.location.href=kintone.api.url('/k/', true).replace(/\.json/g,'')+kintone.app.getId()+'/?'+query;
}));
if (vars.levels.lookup)
{
var added=[];
for (var i2=0;i2<vars.apps[vars.levels.app].length;i2++)
{
var legend=$.fieldvalue(vars.apps[vars.levels.app][i2][vars.levels.relatedkey]);
if (added.indexOf(legend)<0)
{
var filter=$.grep(records,function(item,index){
var exists=0;
if (item[vars.config['date']].value==vars.fromdate.calc(i+' day').format('Y-m-d')) exists++;
if (item[vars.levels.lookup].value==legend) exists++;
return exists==2;
});
/* rebuild view */
functions.build(filter,i+1);
}
}
}
else
{
var key=vars.segmentkeys[0];
for (var i2=0;i2<vars.segments[key].records.length;i2++)
{
var filter=$.grep(records,function(item,index){
var exists=0;
if (item[vars.config['date']].value==vars.fromdate.calc(i+' day').format('Y-m-d')) exists++;
if (item[key].value==vars.segments[key].records[i2].field) exists++;
return exists==2;
});
/* rebuild view */
functions.build(filter,i+1);
}
}
}
},function(error){});
},
/* reload datas */
loaddatas:function(appkey,callback){
var sort='';
var query=kintone.app.getQueryCondition();
var body={
app:appkey,
query:'',
fields:vars.fields
};
query+=((query.length!=0)?' and ':'');
query+=vars.config['date']+'>"'+vars.fromdate.calc('-1 day').format('Y-m-d')+'"';
query+=' and '+vars.config['date']+'<"'+vars.todate.calc('1 day').format('Y-m-d')+'"';
sort=' order by ';
sort+=vars.config['date']+' asc,';
$.each(vars.segments,function(key,values){sort+=key+' asc,';});
sort+=vars.config['fromtime']+' asc limit '+limit.toString()+' offset '+vars.offset[appkey].toString();
body.query+=query+sort;
kintone.api(kintone.api.url('/k/v1/records',true),'GET',body,function(resp){
if (vars.apps[appkey]==null) vars.apps[appkey]=resp.records;
else Array.prototype.push.apply(vars.apps[appkey],resp.records);
vars.offset[appkey]+=limit;
if (resp.records.length==limit) functions.loaddatas(appkey,callback);
else callback();
},function(error){});
},
/* reload datas of level */
loadlevels:function(callback){
var body={
app:vars.levels.app,
query:vars.fieldinfos[vars.levels.lookup].lookup.filterCond
};
body.query+=' order by ';
for (var i=0;i<vars.segmentkeys.length;i++) body.query+=vars.segmentkeys[i]+' asc,';
body.query=body.query.replace(/,$/g,'');
body.query+=' limit '+limit.toString()+' offset '+vars.offset[vars.levels.app].toString();
kintone.api(kintone.api.url('/k/v1/records',true),'GET',body,function(resp){
Array.prototype.push.apply(vars.apps[vars.levels.app],resp.records);
vars.offset[vars.levels.app]+=limit;
if (resp.records.length==limit) functions.loadlevels(callback);
else callback();
},function(error){});
},
/* reload datas of segment */
loadsegments:function(param,callback){
var body={
app:param.app,
query:vars.fieldinfos[param.code].lookup.filterCond+' order by '+param.field+' '+param.sort+' limit '+limit.toString()+' offset '+param.offset.toString()
};
kintone.api(kintone.api.url('/k/v1/records',true),'GET',body,function(resp){
var records=[]
$.each(resp.records,function(index,values){
records.push({display:values[param.display].value,field:values[param.field].value});
});
Array.prototype.push.apply(param.records,records);
param.offset+=limit;
if (resp.records.length==limit) functions.loadsegments(param,callback);
else {param.loaded=1;callback(param);}
},function(error){});
},
/* check for completion of load */
checkloaded:function(){
var loaded=0;
var total=0;
$.each(vars.segments,function(key,values){loaded+=values.loaded;total++;});
/* reload view */
if (loaded==total) functions.load();
}
};
/*---------------------------------------------------------------
mouse events
---------------------------------------------------------------*/
$(window).on('mousemove',function(e){
/* move balloon */
$('div.timetable-balloon').css({
'left':e.clientX,
'top':e.clientY
});
});
/*---------------------------------------------------------------
kintone events
---------------------------------------------------------------*/
kintone.events.on(events.lists,function(event){
vars.config=kintone.plugin.app.getConfig(PLUGIN_ID);
if (!vars.config) return false;
/* check viewid */
if (event.viewId!=vars.config.weektimetable) return;
/* initialize valiable */
var container=$('div#timetable-container').css({'padding-bottom':'100px'});
var feed=$('<div class="timetable-dayfeed">');
var week=$('<span id="week" class="customview-span">');
var button=$('<button id="datepick" class="customview-button calendar-button">');
var prev=$('<button id="prev" class="customview-button prev-button">');
var next=$('<button id="next" class="customview-button next-button">');
/* append elements */
feed.append(prev);
feed.append(week);
feed.append(button);
feed.append(next);
if ($('.timetable-dayfeed').size()) $('.timetable-dayfeed').remove();
kintone.app.getHeaderMenuSpaceElement().appendChild(feed[0]);
/* setup date value */
if (sessionStorage.getItem('fromdate_timetable-weekly'))
{
vars.fromdate=new Date(sessionStorage.getItem('fromdate_timetable-weekly'));
sessionStorage.removeItem('fromdate_timetable-weekly');
}
if (sessionStorage.getItem('todate_timetable-weekly'))
{
vars.todate=new Date(sessionStorage.getItem('todate_timetable-weekly'));
sessionStorage.removeItem('todate_timetable-weekly');
}
vars.fromdate.setDate(vars.fromdate.getDate()+vars.fromdate.getDay()*-1);
vars.todate=vars.fromdate.calc('6 day');
week.text(vars.fromdate.format('Y-m-d')+' ~ '+vars.todate.format('Y-m-d'));
/* day pickup button */
vars.calendar=$('body').calendar({
selected:function(target,value){
vars.fromdate=new Date(value.dateformat());
vars.fromdate.setDate(vars.fromdate.getDate()+vars.fromdate.getDay()*-1);
vars.todate=vars.fromdate.calc('6 day');
week.text(vars.fromdate.format('Y-m-d')+' ~ '+vars.todate.format('Y-m-d'));
/* reload view */
functions.load();
}
});
button.on('click',function(){
vars.calendar.show({activedate:vars.fromdate});
});
/* day feed button */
$.each([prev,next],function(){
$(this).on('click',function(){
var days=($(this).attr('id')=='next')?7:-7;
vars.fromdate=vars.fromdate.calc(days+' day');
vars.todate=vars.todate.calc(days+' day');
week.text(vars.fromdate.format('Y-m-d')+' ~ '+vars.todate.format('Y-m-d'));
/* reload view */
functions.load();
});
});
/* setup colors value */
vars.colors=('colors' in vars.config)?JSON.parse(vars.config['colors']):[];
/* setup displays value */
vars.displays=vars.config['displays'].split(',');
/* setup levels value */
vars.levels=JSON.parse(vars.config['levels']);
/* setup segments value */
vars.segments=JSON.parse(vars.config['segment']);
if (vars.levels.lookup) vars.segmentkeys=vars.levels.levels;
else vars.segmentkeys=Object.keys(vars.segments);
/* create table */
var head=$('<tr>').append($('<th>'));
var template=$('<tr>').append($('<td>'));
for (var i=0;i<7;i++)
{
head.append($('<th>'));
template.append($('<td>'));
}
vars.table=$('<table id="timetable" class="customview-table timetable-weekly">').mergetable({
container:container,
head:head,
template:template
});
/* insert row */
for (var i=0;i<24;i++)
{
var hide=false;
if (i<parseInt(vars.config['starthour'])) hide=true;
if (i>parseInt(vars.config['endhour'])) hide=true;
vars.table.insertrow(null,function(row){
for (var i2=0;i2<parseInt(vars.config['scale'])-1;i2++)
{
vars.table.insertrow(row,function(row){
row.find('td').eq(0).hide();
if (hide) row.addClass('hide');
});
}
row.find('td').eq(0).attr('rowspan',parseInt(vars.config['scale'])).text(i);
if (hide) row.addClass('hide');
});
}
/* get fields of app */
kintone.api(kintone.api.url('/k/v1/app/form/fields',true),'GET',{app:kintone.app.getId()},function(resp){
vars.fields=['$id'];
vars.fieldinfos=$.fieldparallelize(resp.properties);
$.each(resp.properties,function(key,values){
vars.fields.push(values.code);
});
/* get datas of segment */
if (vars.levels.lookup)
{
vars.apps[vars.levels.app]=[];
vars.offset[vars.levels.app]=0;
functions.loadlevels(function(){functions.load();});
}
else
{
$.each(vars.segments,function(key,values){
var param=values;
param.code=key;
param.loaded=0;
param.offset=0;
param.records=[];
if (param.app.length!=0) functions.loadsegments(param,function(res){functions.checkloaded();});
else
{
param.records=[resp.properties[key].options.length];
$.each(resp.properties[key].options,function(key,values){
param.records[values.index]={display:values.label,field:values.label};
});
param.loaded=1;
}
});
functions.checkloaded();
}
},function(error){});
return event;
});
})(jQuery,kintone.$PLUGIN_ID);
|
//= link_directory ../stylesheets/blorgh .css
|
var classHelix_1_1Glob_1_1ActionMap =
[
[ "~ActionMap", "classHelix_1_1Glob_1_1ActionMap.html#a7d4aa57074e069641ab6bbb68884c25b", null ],
[ "ActionMap", "classHelix_1_1Glob_1_1ActionMap.html#a7f8755d9865b2a6285b8ed894dec6469", null ],
[ "ActionMap", "classHelix_1_1Glob_1_1ActionMap.html#afeedaa145c9fb85986699eaa8f37295c", null ],
[ "addAction", "classHelix_1_1Glob_1_1ActionMap.html#a55947c98d682c283f4627702c327ace7", null ],
[ "addHtmlAction", "classHelix_1_1Glob_1_1ActionMap.html#ae157f17e64ec5a86d1591fee474689a6", null ],
[ "addLogicAction", "classHelix_1_1Glob_1_1ActionMap.html#a7813c9ac72a1952afb3dbe5b5e84b3dc", null ],
[ "clearMap", "classHelix_1_1Glob_1_1ActionMap.html#af82dac2490e7cb2c67e63958ea35b88f", null ],
[ "findAction", "classHelix_1_1Glob_1_1ActionMap.html#ade80860583fc614a59c160bfa6e13c30", null ],
[ "getInstance", "classHelix_1_1Glob_1_1ActionMap.html#aa1f8334816ab7310d58a35bd0ce10e63", null ],
[ "listHandlers", "classHelix_1_1Glob_1_1ActionMap.html#a85e67a90450be94108ab43d8e7149a1a", null ],
[ "operator=", "classHelix_1_1Glob_1_1ActionMap.html#a57d2d882b3e1f7314dc891e2cc1176c7", null ],
[ "m_html", "classHelix_1_1Glob_1_1ActionMap.html#a55e5586755d084aa68ca3a9a9b6c620d", null ],
[ "m_logics", "classHelix_1_1Glob_1_1ActionMap.html#a9fc709910f7882158f224c07f64749ff", null ],
[ "m_mut", "classHelix_1_1Glob_1_1ActionMap.html#af0920429dce1505a52f876555e259d78", null ]
]; |
// Content below is autogenerated by ojster template engine
// usually there is no reason to edit it manually
(function (root, factory) {
"use strict";
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ojster', './my_lib'], factory);
} else {
// Browser globals
root.ojster = factory(root.ojster, root.MyLib);
}
}(this, function (ojster, MyLib) {
"use strict";
// variables can be safely defined at any place
// they are bound to produced module only
var tmp;
// the same is true for functions
function abc() {
return 'abc';
}
// @require needs path and optional subpath, fully qualified names can be provided for browser global
// equivalent to: ojster = 'ojster'
// @template and @inherits need alias only
var Base = function (opt_data, opt_ctx, opt_writer) {
ojster.Template.call(this, opt_data, opt_ctx, opt_writer);
};
inherits(Base, ojster.Template);
// any code within and outside of blocks can use any of aliases defined above
var tmp1 = Base.prototype;
Base.prototype.renderBlockMain = function () { // @25:1
var self = this;
var d = this.data, vars = this.vars;
};
return Base;
}));
|
export const StatusReportStates = {
assigned : 0,
inProgress: 1,
submitted : 2
}; |
import './module.scss';
import directive from './directive';
import facetsModule from './../facets/module';
const name = 'list';
export default angular.module(`${name}`, [
facetsModule.name
])
.directive(`${name}`, directive)
|
define([
'color',
'spellquest',
'entities/entity'
], function( Color, Game, Entity ) {
'use strict';
function Letter() {
Entity.call( this );
this._char = ' ';
this._fontSize = 12;
this._textColor = new Color();
}
Letter.prototype = new Entity();
Letter.prototype.constructor = Letter;
Letter.prototype.update = function( x, y ) {
Entity.prototype.update.call( this, x, y );
// TODO: This should be removed at some point.
if ( Game && Game.instance !== undefined && Game.instance !== null ) {
// Snap letter to form element.
var formElements = Game.instance.getForm().getFormElements();
for ( var i = formElements.length - 1; i >= 0; i-- ) {
if ( formElements[i].hit( this.getX(), this.getY() ) !== null ) {
this.setPosition( formElements[i].getPosition() );
this.setVelocity( 0, 0 );
formElements[i].setLetter( this );
// Set it to used.
var index = Game.instance.getPool()._letterEntities.lastIndexOf( this );
if ( index !== -1 ) {
Game.instance.getPool()._isUsed[ index ] = true;
}
break;
}
}
}
};
Letter.prototype.draw = function( ctx ) {
Entity.prototype.draw.call( this, ctx );
ctx.font = this.getFontSize() + 'pt Helvetica';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = this.getTextColor().toString();
ctx.fillText( this.getChar(), this.getX(), this.getY() );
};
Letter.prototype.getChar = function() {
return this._char;
};
Letter.prototype.setChar = function( character ) {
this._char = character;
};
Letter.prototype.getFontSize = function() {
return this._fontSize;
};
Letter.prototype.setFontSize = function( fontSize ) {
this._fontSize = fontSize;
};
Letter.prototype.getTextColor = function() {
return this._textColor;
};
Letter.prototype.setTextColor = function() {
this.getTextColor().set.apply( this.getTextColor(), arguments );
};
Letter.prototype.getTextRed = function() {
return this.getTextColor().getRed();
};
Letter.prototype.setTextRed = function( red ) {
this.getTextColor().setRed( red );
};
Letter.prototype.getTextGreen = function() {
return this.getTextColor().getGreen();
};
Letter.prototype.setTextGreen = function( green ) {
this.getTextColor().setGreen( green );
};
Letter.prototype.getTextBlue = function() {
return this.getTextColor().getBlue();
};
Letter.prototype.setTextBlue = function( blue ) {
this.getTextColor().setBlue( blue );
};
Letter.prototype.getTextAlpha = function() {
return this.getTextColor().getAlpha();
};
Letter.prototype.setTextAlpha = function( alpha ) {
this.getTextColor().setAlpha( alpha );
};
return Letter;
});
|
var Util = {
/**
* Rounds a given number to 4 decimal places. Seems to be safe for most
* exchanges.
*
* @param {Number} number
* @returns {Number}
*/
round: function(number) {
return Math.ceil(number * 10000) / 10000;
}
/**
* Finds a random number between the two values
*
* @param {Number} min
* @param {Number} max
* @returns {Number}
*/
, rand: function(min, max) {
return Math.random() * (max - min) + min;
}
};
module.exports = Util;
|
function QueryBuilder(dictionary, minSubset) {
if (!(this instanceof QueryBuilder)) {
return new QueryBuilder(dictionary, minSubset);
}
var queries = combine(dictionary, minSubset);
var self = this;
this.queryList = queries;
QueryBuilder.prototype.getQueryList = function(){
return this.queryList;
};
}
var combine = function (a, min) {
var fn = function (n, src, got, all) {
if (n === 0) {
if (got.length > 0) {
all[all.length] = got;
}
return;
}
for (var j = 0; j < src.length; j++) {
fn(n - 1, src.slice(j + 1), got.concat([src[j]]), all);
}
return;
}
var all = [];
for (var i = min; i < a.length; i++) {
fn(i, a, [], all);
}
all.push(a);
return all;
}
module.exports = QueryBuilder; |
var columnDimensions = {
w: 80,
h: 640,
d: 80
};
function createFig(box, type) {
"use strict";
var fig = document.createElement("figure");
fig.className = type;
box.appendChild(fig);
return fig;
}
function createBox(w, h, d) {
"use strict";
var box = document.createElement("div");
box.className = "box";
box.style.cssText = "position: absolute; transform-style: preserve-3d;";
var front = createFig(box, "front");
front.style.cssText = "width: " + w + "px; height: " + h + "px; transform: translateZ(" + (d/2) + "px);";
var back = createFig(box, "back");
back.style.cssText = "width: " + w + "px; height: " + h + "px; transform: translateZ(" + (-d/2) + "px) rotateY(180deg);";
var left = createFig(box, "left");
left.style.cssText = "width: " + d + "px; height: " + h + "px; transform: translateX(" + (-d/2) + "px) rotateY(270deg);";
var right = createFig(box, "right");
right.style.cssText = "width: " + d + "px; height: " + h + "px; transform: translateX(" + (d/2) + "px) rotateY(-270deg);";
var top = createFig(box, "top");
top.style.cssText = "width: " + w + "px; height: " + d + "px; transform: translateY(" + (-d/2) + "px) rotateX(-90deg);";
var bottom = createFig(box, "bottom");
bottom.style.cssText = "width: " + w + "px; height: " + d + "px; transform: translateY(" + (h - d/2) + "px) rotateX(90deg);";
return box;
}
function createColumn(viewpaneEl, x, y, z) {
"use strict";
var w = columnDimensions.w; var h = columnDimensions.h; var d = columnDimensions.d;
var box = createBox(w, h, d);
box.className += " column";
box.style.transform = "translate3d(" + x + "px, " + y + "px, " + z + "px)";
viewpaneEl.appendChild(box);
var pedestral = createBox(260, 40, 260);
pedestral.className += " pedestral";
pedestral.style.transform = "translate3d(" + (x - 90) + "px, " + (y + h) + "px, " + (z) + "px)";
viewpaneEl.appendChild(pedestral);
}
|
'use strict';
var whoamiControllers = angular.module('whoamiControllers', ['angularSpinner']);
whoamiControllers.controller('indexCtrl', ['$scope', '$sce', '$window', 'usSpinnerService', 'getHeadersService', 'getAppStats', 'getAppDiagStaticData', 'getAppDiagDynamicData',
function($scope, $sce, $window, usSpinnerService, getHeadersService, getAppStats, getAppDiagStaticData, getAppDiagDynamicData) {
$scope.title = 'WhoAmI Microservice';
$scope.buttons = {'github':'GitHub Repo', 'diag':'App Diag', 'whoami':'Know Who You Are', 'stats': 'Application Usage Stats'};
$scope.description = 'Shows details about your computer';
$scope.loading = true;
$scope.$watch('loading', (newValue) => {
if (newValue) { usSpinnerService.spin('root-spinner'); }
if (!newValue) { usSpinnerService.stop('root-spinner'); }
});
$scope.error = {
noData: 'No data'
};
$scope.serverHeaders = undefined;
$scope.navigator = {};
$scope.navigatorKeys = Object.keys($scope.navigator);
$scope.$watch('navigator', (newValue) => {
$scope.navigatorKeys = Object.keys(newValue);
});
$scope.navigatorExists = () => (navigator) ? true : false;
$scope.getUserMediaCrossbrowser = () => navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || null;
$scope.mediaDevices = [];
$scope.videoStream = undefined;
$scope.trustSrc = (src) => $sce.trustAsResourceUrl(src);
$scope.localStorage = {};
$scope.localStorageKeys = Object.keys($scope.localStorage);
$scope.$watch('localStorage', (newValue) => {
$scope.localStorageKeys = Object.keys(newValue);
console.log('newValue:', newValue);
});
$scope.localStorageExists = () => ($window.localStorage) ? true : false;
$scope.sessionStorage = {};
$scope.sessionStorageKeys = Object.keys($scope.sessionStorage);
$scope.$watch('sessionStorage', (newValue) => {
$scope.sessionStorageKeys = Object.keys(newValue);
});
$scope.sessionStorageExists = () => ($window.sessionStorage) ? true : false;
$scope.performance = {};
$scope.performanceKeys = Object.keys($scope.performance);
$scope.$watch('performance', (newValue) => {
$scope.performanceKeys = Object.keys(newValue);
});
$scope.performanceExists = () => ($window.performance) ? true : false;
$scope.bars = {};
$scope.barsKeys = Object.keys($scope.bars);
$scope.$watch('bars', (newValue) => {
$scope.barsKeys = Object.keys(newValue);
});
$scope.barsExist = () => ($window.toolbar && $window.statusbar && $window.scrollbars) ? true : false;
$scope.screen = {};
$scope.screenKeys = Object.keys($scope.bars);
$scope.$watch('screen', (newValue) => {
$scope.screenKeys = Object.keys(newValue);
});
$scope.screenExists = () => ($window.screen) ? true : false;
$scope.show = { // initialize tbodies display state
server: false,
localStorage: false,
sessionStorage: false,
performance: false,
navigator: false,
bars: false,
screen: false,
stats: true
};
$scope.toggleTbody = (event, section) => {
const key = (!section) ? event.target.innerHTML : section;
$scope.show[key] = ($scope.show[key]) ? false : true;
};
$scope.isObject = (value) => (typeof value === 'object') ? true : false;
$scope.objectLength = (value) => (typeof value === 'object') ? Object.keys(value).length : false;
$scope.objectKeys = (value) => (typeof value === 'object') ? Object.keys(value) : false;
$scope.extractSubObject = (targetObj) => {
let result = {};
for (const subkey in targetObj) {
if (typeof targetObj[subkey] !== 'function' && targetObj[subkey] !== null) {
result[subkey] = targetObj[subkey];
}
}
return result;
};
$scope.getData = () => {
if ($scope.appStatsMode) { $scope.switchAppStatsMode(); }
$scope.loading = true;
getHeadersService.query({}).$promise.then((response) => {
$scope.serverHeaders = response;
$scope.loading = false;
});
if ($scope.navigatorExists()) {
for (const key in navigator) {
if (typeof navigator[key] !== 'object') {
if (typeof navigator[key] === 'function') {
console.log('navigator function found, ignoring');
/*
* TODO - do something with navigator functions
*
* $scope.navigatorFunctions[key] = navigator[key];
*/
} else { $scope.navigator[key] = navigator[key]; }
} else {
$scope.navigator[key] = $scope.extractSubObject(navigator[key]);
//console.log('navigator ', key, $scope.navigator[key]);
}
}
// get media devices
if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) {
navigator.mediaDevices.enumerateDevices().then((devices) => {
devices.forEach((item) => {
console.log('device:', item);
$scope.mediaDevices.push(item);
});
});
}
// init webRTC
navigator.getUserMedia = $scope.getUserMediaCrossbrowser();
if (navigator.getUserMedia) {
navigator.getUserMedia(
{
video: {
width: {
min: 320
},
height: {
min: 240
}
},
audio: true
},
(stream) => {
console.log('getUserMedia success', stream);
$scope.videoStream = $window.URL.createObjectURL(stream);
},
(error) => {
console.log('getUserMedia error:', error);
$scope.videoStream = 'http://techslides.com/demos/sample-videos/small.webm';
}
);
}
}
if ($window.localStorage) {
for (const key in $window.localStorage) {
if (typeof $window.localStorage[key] !== 'object') {
if (typeof $window.localStorage[key] === 'function') {
console.log('performance function found, ignoring');
/*
* TODO - do something with localStorage functions
*/
} else { $scope.localStorage[key] = $window.localStorage[key]; }
} else {
$scope.localStorage[key] = $scope.extractSubObject($window.localStorage[key]);
//console.log('localStorage ', key, $scope.localStorage[key]);
}
}
}
if ($window.sessionStorage) {
for (const key in $window.sessionStorage) {
if (typeof $window.sessionStorage[key] !== 'object') {
if (typeof $window.sessionStorage[key] === 'function') {
console.log('performance function found, ignoring');
/*
* TODO - do something with sessionStorage functions
*/
} else { $scope.sessionStorage[key] = $window.sessionStorage[key]; }
} else {
$scope.sessionStorage[key] = $scope.extractSubObject($window.sessionStorage[key]);
//console.log('sessionStorage ', key, $scope.sessionStorage[key]);
}
}
}
if ($window.performance) {
for (const key in $window.performance) {
if (typeof $window.performance[key] !== 'object') {
if (typeof $window.performance[key] === 'function') {
console.log('performance function found, ignoring');
/*
* TODO - do something with performance functions
*/
} else { $scope.performance[key] = $window.performance[key]; }
} else {
$scope.performance[key] = $scope.extractSubObject($window.performance[key]);
//console.log('performance ', key, $scope.performance[key]);
}
}
}
if ($window.statusbar) {
$scope.bars.statusbar = $window.statusbar.visible;
//console.log('$scope.bars.statusbar',$scope.bars.statusbar);
}
if ($window.toolbar) {
$scope.bars.toolbar = $window.toolbar.visible;
//console.log('$scope.bars.toolbar',$scope.bars.toolbar);
}
if ($window.scrollbars) {
$scope.bars.scrollbars = $window.scrollbars.visible;
//console.log('$scope.bars.scrollbars',$scope.bars.scrollbars);
}
if ($window.locationbar) {
$scope.bars.locationbar = $window.locationbar.visible;
//console.log('$scope.bars.locationbar',$scope.bars.locationbar);
}
if ($window.menubar) {
$scope.bars.menubar = $window.menubar.visible;
//console.log('$scope.bars.menubar',$scope.bars.menubar);
}
if ($window.personalbar) {
$scope.bars.personalbar = $window.personalbar.visible;
//console.log('$scope.bars.personalbar',$scope.bars.personalbar);
}
if ($window.screen) {
for (const key in $window.screen) {
if (typeof $window.screen[key] !== 'object') {
if (typeof $window.screen[key] === 'function') {
console.log('screen function found, ignoring');
/*
* TODO - do something with screen functions
*/
} else { $scope.screen[key] = $window.screen[key]; }
} else {
$scope.screen[key] = $scope.extractSubObject($window.screen[key]);
//console.log('screen ', key, $scope.screen[key]);
}
}
}
};
$scope.appStats = [];
$scope.appStatsMode = false;
$scope.switchAppStatsMode = () => {
($scope.appStatsMode) ? $scope.appStatsMode = false : $scope.appStatsMode = true;
if ($scope.appStatsMode) {
$scope.loading = true;
getAppStats.query({}).$promise.then((response) => {
$scope.appStats = response;
console.log('$scope.appStats:', $scope.appStats);
$scope.loading = false;
});
}
};
$scope.showChart = false;
$scope.$watch('appStats', (newValue) => {
if (newValue !== []) {
console.log('app stats newValue',newValue);
$scope.chart.userAgent.labels = [];
$scope.chart.userAgent.data = [];
$scope.chart.acceptLanguage.labels = [];
$scope.chart.acceptLanguage.data = [];
newValue.forEach((item) => {
const languageArr = item.serverHeaders[0].acceptLanguage;
languageArr.forEach((langItem) => {
const langItemIndex = $scope.chart.acceptLanguage.labels.indexOf(langItem);
if (langItemIndex === -1) {
$scope.chart.acceptLanguage.labels.push(langItem);
$scope.chart.acceptLanguage.data.push(1);
} else {
$scope.chart.acceptLanguage.data[langItemIndex]++;
}
});
const agentArr = item.serverHeaders[0].userAgent;
agentArr.forEach((agentItem) => {
const agentSubstr = agentItem.substring(agentItem.lastIndexOf(' ') + 1, agentItem.length);
const agentItemIndex = $scope.chart.userAgent.labels.indexOf(agentSubstr);
if (agentItemIndex === -1) {
$scope.chart.userAgent.labels.push(agentSubstr);
$scope.chart.userAgent.data.push(1);
} else {
$scope.chart.userAgent.data[agentItemIndex]++;
}
});
});
$scope.showChart = true;
console.log('$scope.chart: ',$scope.chart);
}
});
$scope.chartOptions = {
// see chartjs.org/docs#doughnut-pie-chart-chart-options for options
responsive: true,
tooltipFontSize: 18
};
$scope.chart = {
userAgent: {
labels: ['label 1', 'label 2', 'label 3', 'label 4', 'label 5'],
data: [300, 500, 100, 40, 120]
},
acceptLanguage: {
labels: ['label 1', 'label 2', 'label 3', 'label 4', 'label 5'],
data: [300, 500, 100, 40, 120]
}
};
$scope.showModal = false;
$scope.modalText = {title: 'Application Diagnostic Information'};
$scope.appDiagData = {
static: [],
dynamic: []
};
$scope.toggleModal = () => {
$scope.showModal = (!$scope.showModal) ? true : false;
if ($scope.showModal) {
$scope.loading = true;
getAppDiagStaticData.query({}).$promise.then((response) => {
$scope.appDiagData.static = response;
$scope.loading = false;
});
getAppDiagDynamicData.status();
getAppDiagDynamicData.get();
} else {
getAppDiagDynamicData.pause();
}
};
$scope.$on('$viewContentLoaded', () => {
console.log('controller initialized');
$scope.getData();
});
$scope.$on('$destroy', () => {
console.log('controller destroyed');
});
}
]);
|
import React from 'react';
import { scaleOrdinal, scaleLinear, range } from 'd3';
import * as chromatic from 'd3-scale-chromatic';
import chroma from 'chroma-js';
import colorClasses from '../utils/colorClasses';
const colors0 = [
'#7fcdbb',
'#a1dab4',
'#41b6c4',
'#a1dab4',
'#41b6c4',
'#2c7fb8',
'#c7e9b4',
'#7fcdbb',
'#41b6c4',
'#2c7fb8',
'#c7e9b4',
'#7fcdbb',
'#41b6c4',
'#1d91c0',
'#225ea8',
'#edf8b1',
'#c7e9b4',
'#7fcdbb',
'#41b6c4',
'#1d91c0',
'#225ea8',
'#edf8b1',
'#c7e9b4',
'#7fcdbb',
'#41b6c4',
'#1d91c0',
'#225ea8',
'#253494'
];
const colors2 = [
'#eeeee5',
'#6c843e',
'#dc383a',
'#687d99',
'#705f84',
'#fc9a1a',
'#aa3a33',
'#9c4257'
];
const mediaTypes = ['article', 'photo', 'gif', 'video'];
const challengeTypes = ['quiz', 'gap text', 'hangman'];
export const mediaScale = scaleOrdinal()
.domain(mediaTypes)
.range(['fa-link', 'fa-camera', 'fa-video-camera']);
export const colorScaleRandom = scaleLinear()
.domain(range(colors0.length))
.range(colorClasses)
.clamp(true);
export const colorClass = (title = 'title') =>
colorScaleRandom(title.length % colors0.length);
export const profileSrc = () => {
const gender = Math.random() < 0.5 ? 'men' : 'women';
const i = Math.round(Math.random() * 100);
return `https://randomuser.me/api/portraits/thumb/${gender}/${i}.jpg`;
};
// export const shadowStyle = {
// boxShadow: '0.2rem 0.2rem 0.1rem grey'
// // border: '1px solid black'
// };
const colors = [...chromatic.schemePastel1, 'wheat'];
const ordinalColScale = scaleOrdinal()
.domain(challengeTypes)
.range(colors);
export function colorScale(type) {
if (type === null) return 'whitesmoke';
return ordinalColScale(type);
}
export const darkerColorScale = scaleOrdinal()
.domain(challengeTypes)
.range(ordinalColScale.range().map(c => chroma(c).darker()));
// TODO: chroma alpha does not seem to work
export const brighterColorScale = scaleOrdinal()
.domain(challengeTypes)
.range(ordinalColScale.range().map(c => chroma(c).alpha(0.5)));
// TODO: make meaningful
export const cardTypeColorScale = scaleOrdinal()
.domain(challengeTypes)
.range(ordinalColScale.range().map(c => chroma(c).alpha(0.5)));
// export {
// cardLayout,
// shadowStyle,
// colorScale,
// mediaScale,
// colorClass,
// profileSrc,
// colorScaleRandom
// };
//
//
export const createShadowStyle = (color = 'grey') => ({
border: `1px solid ${color}`,
boxShadow: `6px 6px ${color}`
});
export const modalBorder = color => ({ borderTop: `1px solid ${color}` });
// export const coverPhotoStyle = { height: '50%', maxHeight: 400, width: '100%' };
export const UIthemeContext = React.createContext({
uiColor: 'orange',
background: 'grey'
});
|
module.exports = {
port:3000,
timeout:120000
}
|
var TasksViewController = $V.classes.VViewController.extend({
displayName: "TasksViewController",
viewWillInit: function() {
this.initNewProperty('tabId', 'tasks');
this.setTitle('Tasks');
},
viewDidLoad: function(aView) {
var self = this;
aView.setContent("TasksViewController");
}
});
|
/* global expect test */
const { Lyric } = require('./j-lyric');
async function testLyric(object) {
const { url, title, artist, lyricist, composer, arranger, length } = object;
const inst = new Lyric(url);
await inst.get();
expect(inst.title).toBe(title);
expect(inst.artist).toBe(artist);
if (lyricist) expect(inst.lyricist).toBe(lyricist);
if (composer) expect(inst.composer).toBe(composer);
if (arranger) expect(inst.arranger).toBe(arranger);
if (length > 0) expect(inst.lyric.length).toBe(length);
}
test('', async () => {
await testLyric({
url: 'https://j-lyric.net/artist/a002723/l001e83.html',
title: 'tune the rainbow',
artist: '坂本真綾',
lyricist: '岩里祐穂',
composer: '菅野よう子',
length: 447,
});
});
test('', async () => {
await testLyric({
url: 'https://j-lyric.net/artist/a000673/l000bea.html',
title: '天体観測',
artist: 'BUMP OF CHICKEN',
lyricist: '藤原基央',
composer: '藤原基央',
length: 734,
});
});
|
var express = require('express');
var app = express();
var router = express.Router();
router.dashboard = function(req, res) {
} |
import * as React from "react"
import loadable from "@loadable/component"
import PropTypes from "prop-types"
import { useStaticQuery, graphql } from "gatsby"
import "./layout.css"
const Header = loadable(() => import("./header"))
const Layout = ({ children }) => {
const data = useStaticQuery(graphql`
query SiteTitleQuery {
site {
siteMetadata {
title
}
}
}
`)
return (
<>
<Header siteTitle={data.site.siteMetadata?.title || `Title`} />
<div
style={{
margin: `0 auto`,
maxWidth: 960,
padding: `0 1.0875rem 1.45rem`,
}}
>
<main>{children}</main>
<footer
style={{
marginTop: `2rem`,
}}
>
© {new Date().getFullYear()}, Built with
{` `}
<a href="https://www.gatsbyjs.com">Gatsby</a>
</footer>
</div>
</>
)
}
Layout.propTypes = {
children: PropTypes.node.isRequired,
}
export default Layout
|
'use strict';
/**
*
* @type {exports}
*/
var _ = require('lodash'),
express = require('express'),
passport = require('passport'),
auth = require('../auth.service'),
User = require('../../api/user/user.model'),
json = require('../../components/protocol/json');
var router = express.Router();
// 로그인
router.post('/', function (req, res, next) {
passport.authenticate('local', function (err, user, info) {
var error = err || info;
if (error) return next(error);
res._data = {
token: auth.makeToken(user)
};
next();
})(req, res, next)
}, json);
module.exports = router; |
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["Scada"] = factory();
else
root["Scada"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 2);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
/**
* @author Garens
* @date 2017年4月7日10:12:15
*/
let EventEmitter = __webpack_require__(1);
// let RenderPath = require('./RenderPath');
class Scada extends EventEmitter
{
constructor(objs) {
super();
this.objects = objs;
}
init(objs) {
this.objects = objs;
this.distCenter();
}
distCenter() {
let objs = this.objects;
for(var i in objs) {
if(objs[i].type != 'svg') {
objs[i].data = JSON.parse(objs[i].data);
}
this.emit(objs[i].type,objs[i].data);
// switch (objs[i].type) {
// case 'path':
// // new RenderPath(objs[i]);
// this.emit('path',objs[i].data);
// break;
// default:
// break;
// }
}
}
/**
* 此处必须要设置为this._objects,否则会Uncaught RangeError: Maximum call stack size exceeded错误
* @return {Array} objects
*/
get objects()
{
return this._objects;
}
set objects(arr)
{
this._objects = arr;
}
}
// function Scada(){
// console.log(123);
// }
// Scada.prototype.init = function(objs){
// this.objs = objs;
// console.log(1);
// }
//
module.exports = Scada;
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var has = Object.prototype.hasOwnProperty
, prefix = '~';
/**
* Constructor to create a storage for our `EE` objects.
* An `Events` instance is a plain object whose properties are event names.
*
* @constructor
* @api private
*/
function Events() {}
//
// We try to not inherit from `Object.prototype`. In some engines creating an
// instance in this way is faster than calling `Object.create(null)` directly.
// If `Object.create(null)` is not supported we prefix the event names with a
// character to make sure that the built-in object properties are not
// overridden or used as an attack vector.
//
if (Object.create) {
Events.prototype = Object.create(null);
//
// This hack is needed because the `__proto__` property is still inherited in
// some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
//
if (!new Events().__proto__) prefix = false;
}
/**
* Representation of a single event listener.
*
* @param {Function} fn The listener function.
* @param {Mixed} context The context to invoke the listener with.
* @param {Boolean} [once=false] Specify if the listener is a one-time listener.
* @constructor
* @api private
*/
function EE(fn, context, once) {
this.fn = fn;
this.context = context;
this.once = once || false;
}
/**
* Minimal `EventEmitter` interface that is molded against the Node.js
* `EventEmitter` interface.
*
* @constructor
* @api public
*/
function EventEmitter() {
this._events = new Events();
this._eventsCount = 0;
}
/**
* Return an array listing the events for which the emitter has registered
* listeners.
*
* @returns {Array}
* @api public
*/
EventEmitter.prototype.eventNames = function eventNames() {
var names = []
, events
, name;
if (this._eventsCount === 0) return names;
for (name in (events = this._events)) {
if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
}
if (Object.getOwnPropertySymbols) {
return names.concat(Object.getOwnPropertySymbols(events));
}
return names;
};
/**
* Return the listeners registered for a given event.
*
* @param {String|Symbol} event The event name.
* @param {Boolean} exists Only check if there are listeners.
* @returns {Array|Boolean}
* @api public
*/
EventEmitter.prototype.listeners = function listeners(event, exists) {
var evt = prefix ? prefix + event : event
, available = this._events[evt];
if (exists) return !!available;
if (!available) return [];
if (available.fn) return [available.fn];
for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) {
ee[i] = available[i].fn;
}
return ee;
};
/**
* Calls each of the listeners registered for a given event.
*
* @param {String|Symbol} event The event name.
* @returns {Boolean} `true` if the event had listeners, else `false`.
* @api public
*/
EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return false;
var listeners = this._events[evt]
, len = arguments.length
, args
, i;
if (listeners.fn) {
if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
switch (len) {
case 1: return listeners.fn.call(listeners.context), true;
case 2: return listeners.fn.call(listeners.context, a1), true;
case 3: return listeners.fn.call(listeners.context, a1, a2), true;
case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
}
for (i = 1, args = new Array(len -1); i < len; i++) {
args[i - 1] = arguments[i];
}
listeners.fn.apply(listeners.context, args);
} else {
var length = listeners.length
, j;
for (i = 0; i < length; i++) {
if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
switch (len) {
case 1: listeners[i].fn.call(listeners[i].context); break;
case 2: listeners[i].fn.call(listeners[i].context, a1); break;
case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
default:
if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
args[j - 1] = arguments[j];
}
listeners[i].fn.apply(listeners[i].context, args);
}
}
}
return true;
};
/**
* Add a listener for a given event.
*
* @param {String|Symbol} event The event name.
* @param {Function} fn The listener function.
* @param {Mixed} [context=this] The context to invoke the listener with.
* @returns {EventEmitter} `this`.
* @api public
*/
EventEmitter.prototype.on = function on(event, fn, context) {
var listener = new EE(fn, context || this)
, evt = prefix ? prefix + event : event;
if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++;
else if (!this._events[evt].fn) this._events[evt].push(listener);
else this._events[evt] = [this._events[evt], listener];
return this;
};
/**
* Add a one-time listener for a given event.
*
* @param {String|Symbol} event The event name.
* @param {Function} fn The listener function.
* @param {Mixed} [context=this] The context to invoke the listener with.
* @returns {EventEmitter} `this`.
* @api public
*/
EventEmitter.prototype.once = function once(event, fn, context) {
var listener = new EE(fn, context || this, true)
, evt = prefix ? prefix + event : event;
if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++;
else if (!this._events[evt].fn) this._events[evt].push(listener);
else this._events[evt] = [this._events[evt], listener];
return this;
};
/**
* Remove the listeners of a given event.
*
* @param {String|Symbol} event The event name.
* @param {Function} fn Only remove the listeners that match this function.
* @param {Mixed} context Only remove the listeners that have this context.
* @param {Boolean} once Only remove one-time listeners.
* @returns {EventEmitter} `this`.
* @api public
*/
EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return this;
if (!fn) {
if (--this._eventsCount === 0) this._events = new Events();
else delete this._events[evt];
return this;
}
var listeners = this._events[evt];
if (listeners.fn) {
if (
listeners.fn === fn
&& (!once || listeners.once)
&& (!context || listeners.context === context)
) {
if (--this._eventsCount === 0) this._events = new Events();
else delete this._events[evt];
}
} else {
for (var i = 0, events = [], length = listeners.length; i < length; i++) {
if (
listeners[i].fn !== fn
|| (once && !listeners[i].once)
|| (context && listeners[i].context !== context)
) {
events.push(listeners[i]);
}
}
//
// Reset the array, or remove it completely if we have no more listeners.
//
if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
else if (--this._eventsCount === 0) this._events = new Events();
else delete this._events[evt];
}
return this;
};
/**
* Remove all listeners, or those of the specified event.
*
* @param {String|Symbol} [event] The event name.
* @returns {EventEmitter} `this`.
* @api public
*/
EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
var evt;
if (event) {
evt = prefix ? prefix + event : event;
if (this._events[evt]) {
if (--this._eventsCount === 0) this._events = new Events();
else delete this._events[evt];
}
} else {
this._events = new Events();
this._eventsCount = 0;
}
return this;
};
//
// Alias methods names because people roll like that.
//
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
//
// This function doesn't apply anymore.
//
EventEmitter.prototype.setMaxListeners = function setMaxListeners() {
return this;
};
//
// Expose the prefix.
//
EventEmitter.prefixed = prefix;
//
// Allow `EventEmitter` to be imported as module namespace.
//
EventEmitter.EventEmitter = EventEmitter;
//
// Expose the module.
//
if (true) {
module.exports = EventEmitter;
}
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(0);
/***/ })
/******/ ]);
}); |
const Turbolinks = require('turbolinks');
// Monkey patch Turbolinks to render 403, 404 & 500 normally
// See https://github.com/turbolinks/turbolinks/issues/179
Turbolinks.HttpRequest.prototype.requestLoaded = function() {
return this.endRequest(function() {
var code = this.xhr.status;
if (200 <= code && code < 300 ||
code === 403 || code === 404 || code === 500) {
this.delegate.requestCompletedWithResponse(
this.xhr.responseText,
this.xhr.getResponseHeader("Turbolinks-Location"));
} else {
this.failed = true;
this.delegate.requestFailedWithStatusCode(code, this.xhr.responseText);
}
}.bind(this));
};
// Turbolinks nonce CSP support.
// See https://github.com/turbolinks/turbolinks/issues/430
document.addEventListener('turbolinks:request-start', function(event) {
var nonceTag = document.querySelector("meta[name='csp-nonce']");
if (nonceTag) event.data.xhr.setRequestHeader('X-Turbolinks-Nonce', nonceTag.content);
});
document.addEventListener('turbolinks:before-cache', function() {
Array.prototype.forEach.call(document.querySelectorAll('script[nonce]'), function(element) {
if (element.nonce) element.setAttribute('nonce', element.nonce);
});
});
|
$wnd.showcase.runAsyncCallback20("function Hhb(a){this.a=a}\nfunction IEb(a){oh(this,(hwb(),a))}\nfunction HEb(){Nyb();IEb.call(this,So($doc,'file'));(hwb(),this.hb).className='gwt-FileUpload'}\nUX(442,1,G9b,Hhb);_.Sc=function Ihb(a){var b;b=gh(this.a).value;(SXb(),b).length==0?($wnd.alert('\\u4F60\\u5FC5\\u987B\\u9009\\u62E9\\u8981\\u4E0A\\u4F20\\u7684\\u6587\\u4EF6'),undefined):($wnd.alert('\\u6587\\u4EF6\\u4E0A\\u4F20\\u5B8C\\u6BD5\\uFF01'),undefined)};var gO=$Wb(bac,'CwFileUpload/1',442);UX(443,1,Q9b);_.Bc=function Lhb(){var a,b,c;h$(this.a,(a=new pQb,mQb(a,new _Cb('<b>\\u9009\\u62E9\\u4E00\\u4E2A\\u6587\\u4EF6\\uFF1A<\\/b>')),b=new HEb,$Pb((hwb(),b.hb),'','cwFileUpload'),mQb(a,b),c=new ozb('\\u4E0A\\u4F20\\u6587\\u4EF6'),Mh(c,new Hhb(b),(Ot(),Ot(),Nt)),mQb(a,new _Cb('<br>')),mQb(a,c),a))};UX(314,244,J7b,HEb);var FR=$Wb(I7b,'FileUpload',314);Q6b(Cl)(20);\n//# sourceURL=showcase-20.js\n")
|
const AUTOPREFIXER_BROWSERS = [
'Android 2.3',
'Android >= 4',
'Chrome >= 35',
'Firefox >= 31',
'Explorer >= 9',
'iOS >= 7',
'Opera >= 12',
'Safari >= 7.1',
];
module.exports = {
plugins: [
require('autoprefixer')({ browsers: AUTOPREFIXER_BROWSERS })
]
} |
Main.k.CreatePopup = function() {
var popup = {};
popup.dom = $("<td>").attr("id", "usPopup").addClass("usPopup chat_box");
popup.mask = $("<div>").addClass("usPopupMask").attr('onclick','Main.k.ClosePopup();').appendTo(popup.dom);
popup.content = $("<div>").addClass("usPopupContent chattext").css({
"width": (Main.k.window.innerWidth - 300) + "px",
"height": (Main.k.window.innerHeight - 100) + "px"
}).appendTo(popup.dom);
return popup;
};
Main.k.OpenPopup = function(popup) {
$("body").append(popup);
};
Main.k.ClosePopup = function() {
var popup = $("#usPopup");
if (!popup.get()) return;
popup.remove();
var tgt = $("#formattingpopuptgt");
if (tgt.get()) {
tgt.focus();
tgt.attr("id", "");
}
};
exportFunction(Main.k.ClosePopup, unsafeWindow.Main.k, {defineAs: "ClosePopup"});
|
import Browsable from 'appkit/libs/browsable';
var LtiAppBrowseController = Ember.ObjectController.extend({
isLoaded : true,
targetRoute: 'ltiApp.browseDetails',
showDashboard: function() {
return Ember.isEmpty(Ember.ENV.TOOL_ID);
}.property('Ember.ENV.TOOL_ID'),
parentFolderChain: function() {
if (this.get('folderChain') === 'root') {
return null;
} else {
return this.get('folderChain').split('.').slice(0, -1).join('.');
}
}.property('folderChain'),
parentFolder: function() {
if (this.get('folderChain') === 'root') {
return null;
} else {
return this.get('folderChain').split('.').pop();
}
}.property('folderChain'),
currentFolder: function() {
return this.get('folderChain').split('.').pop();
}.property('folderChain'),
loadData: function() {
var _this = this;
this.set('isLoaded', false);
Browsable.findFolder(
this.get('ltiApp.toolId'),
this.get('currentFolder'),
this.get('parentFolderChain')
).then(
function(browsable) {
_this.set('isLoaded', true);
_this.set('folders', browsable.get('folders'));
_this.set('items', browsable.get('items'));
},
function(err) {
//console.log(err);
_this.set('isLoaded', true);
}
);
}.observes('folderChain'),
isEmptyResults: function() {
return (Em.isEmpty(this.get('items')) && Em.isEmpty(this.get('folders')));
}.property('items.@each', 'folders.@each'),
actions: {
goToFolder: function(folder) {
var newFolderChain = this.get('folderChain') + '.' + folder.id;
this.transitionToRoute('ltiApp.browse', { folderChain: newFolderChain });
},
goUpFolder: function() {
var newFolderChain = this.get('parentFolderChain');
this.transitionToRoute('ltiApp.browse', { folderChain: newFolderChain });
},
goToItem: function(item) {
this.transitionToRoute('ltiApp.browseDetails', { folderChain: this.get('folderChain'), item: item });
}
}
});
export default LtiAppBrowseController;
|
PhaxMachine.pages['user-form'] = {
render: function() {
$('#addUserEmail').on('click', function() {
var emailInputs = $('#userEmailList input[type=email]');
var nextIdx = emailInputs.length;
var newInput = emailInputs.first().clone();
newInput.attr('id', 'user_user_emails_attributes_' + nextIdx + '_email');
newInput.attr('name', 'user[user_emails_attributes][' + nextIdx + '][email]');
newInput.attr('value', '');
newInput.val('');
// Super ugly, but it's 2 AM and this needs to go out.
var inputGroup = $('<div class="input-group"></div>')
var hiddenFieldHtml = '<input class="destroy-field" type="hidden" value="false" name="user[user_emails_attributes][' + nextIdx + '][_destroy]" id="user_user_emails_attributes_' + nextIdx + '__destroy">';
var inputGroupBtn = $('<span class="input-group-btn">' + hiddenFieldHtml + '<a class="btn btn-secondary btn-remove-email" ><i class="glyphicon glyphicon-trash"></i></a></span>');
inputGroup.append(newInput);
inputGroup.append(inputGroupBtn);
$('#userEmailList').append(inputGroup);
});
$(document).on('click', '.btn-remove-email', function() {
var inputGroup = $(this).closest('.input-group');
inputGroup.find('input[type="email"]').val('pending@deletion.com')
inputGroup.find('.destroy-field').val(true)
inputGroup.hide();
});
}
} |
/**
* emit events
* websocket-error
* websocket-message
* session-expired
* logined
* error
* connected
*/
/**
* @param {string} sessionId
* @param {string} url
* @constructor
*/
var AppWebSocket = function (sessionId, url) {
this.url = url;
this.websocket = null;
this.sessionId = sessionId;
//window.localStorage.session_id
this.createSessionMsg = '-1';
this.restoreSessionMsg = '-1';
this.logined = false;
};
inherits(AppWebSocket, EventEmitter);
AppWebSocket.prototype.connect = function () {
console.log('AppWebSocket.connect');
try {
this.websocket = new WebSocket(this.url);
} catch (e) {
//self.win.window.loadFailed();
this.emit('websocket-error');
}
this.websocket.onopen = this.onOpen.bind(this);
this.websocket.onerror = this.onError.bind(this);
this.websocket.onmessage = this.onMessage.bind(this);
};
AppWebSocket.prototype.reconnect = function () {
if (this.websocket && this.websocket) {
console.log('AppWebSocket.reconnect');
this.websocket.close();
this.connect();
}
};
AppWebSocket.prototype.onOpen = function (e) {
this.emit('connected');
this.restoreSessionMsg = _.uniqueId('msg');
this.websocket.send(JSON.stringify({
REQ_ID: this.restoreSessionMsg,
REQ_CMD: 'USER:SESSION:AUTH',
REQ: {
session_id: this.sessionId
}
}));
};
AppWebSocket.prototype.onError = function (e) {
console.log('ws error', e);
this.emit('websocket-error');
//loginButton.disabled = false;
//this.showFailed();
//this.win.window.loadFailed();
};
AppWebSocket.prototype.onMessage = function (e) {
console.log('onmessage', e);
var data;
//try {
data = JSON.parse(e.data);
//data: "{"REP_TYPE":"USER","REP_CMD":"CONNECTION","REP_STATUS":"SUCCESS","REP":{"server_time":1426244990130,"connection_id":"06d392557c94c34212cc6ae77a1efd71"}}"defaultPrevented: falseeventPhase: 0lastEventId: ""origin: "wss://witkit.com"path: NodeList[0]ports: Array[0]returnValue: truesource: nullsrcElement: WebSockettarget: WebSockettimeStamp: 1426244990186type: "message"__proto__: MessageEvent
if (data.REP_CMD === 'CONNECTION') {
this.websocketConnectionId = data.REP.connection_id;
// this.win.window.login();
// return;
}
if (data.REP_REQ_ID === this.createSessionMsg || data.REP_CMD === 'USER:SESSION:CREATE') {
if (data.REP_STATUS === 'SUCCESS') {
this.createSessionMsg = null;
this.logined = true;
this.emit('logined', data.REP);
//return;
} else {
//this.win.window.alert('Wrong email or password');
//this.win.window.document.querySelector('.wkErrorMessage').style.visibility = 'visible';
this.logined = false;
this.emit('error', 'Wrong email or password');
//todo add settimeout hide
}
} else if (data.REP_REQ_ID === this.restoreSessionMsg) {
if (data.REP_STATUS === 'SUCCESS') {
this.logined = true;
this.emit('logined', data.REP);
} else {
//this.win.window.login();
this.logined = false;
this.emit('session-expired');
}
this.restoreSessionMsg = null;
}
//} catch (e) {
// //todo process catch
// console.log(e);
//}
this.emit('websocket-message');
};
AppWebSocket.prototype.userCreateSession = function (login, password, keepSignIn) {
this.createSessionMsg = _.uniqueId('msg');
this.websocket.send(JSON.stringify(
{
REQ_ID: this.createSessionMsg,
REQ_CMD: 'USER:SESSION:CREATE',
REQ: {
login: login,
password: password,
session_ttl: keepSignIn ? 30 * 24 * 60 * 60 : 0
}
}
));
};
AppWebSocket.prototype.getSessionUrl = function (rep) {
rep.client = 'desktop_app';
rep.platform = process.platform;
rep.session_ttl = rep.session_ttl || '';
rep.session_timestamp = rep.session_timestamp || (new Date()).getTime().toString();
//return '?' + _.reduce(_.pairs(rep), function (a, b) {return (_.isArray(a) ? a.join('=') : a) + '&' + b.join('=');});
var url = '?';
var skipParams = ['session_pwd', 'user_id', 'total_found', 'total_unvisited'];
for (var prop in rep) {
if (skipParams.indexOf(prop) !== -1) {
continue;
}
url += prop + '=' + rep[prop] + '&';
}
return url;
}; |
(function () {
'use strict';
angular.module('Data')
.controller('MenuDataController', MenuDataController);
MenuDataController.$inject = ['MenuDataService', 'categories'];
function MenuDataController(MenuDataService, categories) {
var menuData = this;
menuData.categories = categories;
}
})();
|
var rx_1 = require("rx");
var Omni = require('../../omni-sharp-server/omni');
var dock_1 = require("../atom/dock");
var find_pane_view_1 = require("../views/find-pane-view");
var FindUsages = (function () {
function FindUsages() {
this.selectedIndex = 0;
this.scrollTop = 0;
this.usages = [];
}
FindUsages.prototype.activate = function () {
var _this = this;
this.disposable = new rx_1.CompositeDisposable();
var observable = rx_1.Observable.merge(
// Listen to find usages
Omni.listener.observeFindusages,
// We also want find implementations, where we found more than one
Omni.listener.observeFindimplementations
.where(function (z) { return z.response.QuickFixes.length > 1; }))
.map(function (z) { return z.response.QuickFixes || []; })
.share();
var updated = rx_1.Observable.ofObjectChanges(this);
this.observe = {
find: observable,
// NOTE: We cannot do the same for find implementations because find implementation
// just goes to the item if only one comes back.
open: Omni.listener.requests.where(function (z) { return z.command === "findusages"; }).map(function () { return true; }),
reset: Omni.listener.requests.where(function (z) { return z.command === "findimplementations" || z.command === "findusages"; }).map(function () { return true; }),
updated: updated
};
this.disposable.add(Omni.addTextEditorCommand("omnisharp-atom:find-usages", function () {
Omni.request(function (client) { return client.findusages(client.makeRequest()); });
}));
this.disposable.add(Omni.addTextEditorCommand("omnisharp-atom:go-to-implementation", function () {
Omni.request(function (client) { return client.findimplementations(client.makeRequest()); });
}));
this.disposable.add(atom.commands.add("atom-workspace", 'omnisharp-atom:next-usage', function () {
_this.updateSelectedItem(_this.selectedIndex + 1);
}));
this.disposable.add(atom.commands.add("atom-workspace", 'omnisharp-atom:go-to-usage', function () {
if (_this.usages[_this.selectedIndex])
Omni.navigateTo(_this.usages[_this.selectedIndex]);
}));
this.disposable.add(atom.commands.add("atom-workspace", 'omnisharp-atom:previous-usage', function () {
_this.updateSelectedItem(_this.selectedIndex - 1);
}));
this.disposable.add(atom.commands.add("atom-workspace", 'omnisharp-atom:go-to-next-usage', function () {
_this.updateSelectedItem(_this.selectedIndex + 1);
if (_this.usages[_this.selectedIndex])
Omni.navigateTo(_this.usages[_this.selectedIndex]);
}));
this.disposable.add(atom.commands.add("atom-workspace", 'omnisharp-atom:go-to-previous-usage', function () {
_this.updateSelectedItem(_this.selectedIndex - 1);
if (_this.usages[_this.selectedIndex])
Omni.navigateTo(_this.usages[_this.selectedIndex]);
}));
this.disposable.add(this.observe.find.subscribe(function (s) {
_this.usages = s;
}));
this.disposable.add(rx_1.Observable.merge(exports.findUsages.observe.find.map(function (z) { return true; }), exports.findUsages.observe.open.map(function (z) { return true; })).subscribe(function () {
_this.ensureWindowIsCreated();
dock_1.dock.selectWindow("find");
}));
this.disposable.add(this.observe.reset.subscribe(function () {
_this.usages = [];
_this.scrollTop = 0;
_this.selectedIndex = 0;
}));
this.disposable.add(Omni.listener.observeFindimplementations.subscribe(function (data) {
if (data.response.QuickFixes.length == 1) {
Omni.navigateTo(data.response.QuickFixes[0]);
}
}));
};
FindUsages.prototype.updateSelectedItem = function (index) {
if (index < 0)
index = 0;
if (index >= this.usages.length)
index = this.usages.length - 1;
if (this.selectedIndex !== index)
this.selectedIndex = index;
};
FindUsages.prototype.ensureWindowIsCreated = function () {
var _this = this;
if (!this.window) {
this.window = new rx_1.CompositeDisposable();
var windowDisposable = dock_1.dock.addWindow('find', 'Find', find_pane_view_1.FindWindow, {
scrollTop: function () { return _this.scrollTop; },
setScrollTop: function (scrollTop) { return _this.scrollTop = scrollTop; },
findUsages: this
}, {
priority: 2000,
closeable: true
}, this.window);
this.window.add(windowDisposable);
this.window.add(rx_1.Disposable.create(function () {
_this.disposable.remove(_this.window);
_this.window = null;
}));
this.disposable.add(this.window);
}
};
FindUsages.prototype.dispose = function () {
this.disposable.dispose();
};
FindUsages.prototype.navigateToSelectedItem = function () {
Omni.navigateTo(this.usages[this.selectedIndex]);
};
return FindUsages;
})();
exports.findUsages = new FindUsages;
|
define([
"dojo/_base/declare",
"dojo/_base/lang",
"dojo/on",
"dojo/mouse",
"dojo/dom",
"dojo/dom-construct",
"dojo/dom-style",
"dojo/dom-geometry",
"dojo/window",
"dojo/request",
"dojo/fx",
"dojo/fx/Toggler",
"dijit/Tooltip",
"dojox/widget/DialogSimple",
"cool/dijit/LazyContentPane", //allows script execution
"cool/dijit/iconButton"
], function(declare, lang, on, mouse, dom, domConstruct, domStyle, domGeometry, win, request, dojoFx, Toggler, Tooltip, Dialog, ContentPane, iconButton) {
return {
openWidgetDialog: function(serverId, title, parameters, onClose, onWidgetInstantiation, onWidgetBindSuccess, config) {
parameters = parameters || {};
config = config || {};
title = title || "TITLE?";
var t = this;
var vs = win.getBox();
var w = config.w || Math.max(vs.w-100, 1200);
var h = config.h || Math.max(vs.h-200, 700);
var d = t._getModalDialog(title);
domStyle.set(d.domNode, {
width: w + "px",
height: h + "px"
});
d.containerNode.style['overflow'] = config.overflow || "auto";
domStyle.set(d.containerNode, {
'height' : (h-25)+'px'
});
COOL.widgetFactory(serverId, parameters, function(widget) {
if(lang.isFunction(onWidgetInstantiation))
onWidgetInstantiation(widget);
widget.onlyContent = true;
d.addChild( widget );
setTimeout(function() { widget.resize(); }, 3000);
widget.dialog = d;
d.widget = widget;
d.show();
}, function(widget) {
if(lang.isFunction(onWidgetBindSuccess))
onWidgetBindSuccess(widget);
});
if(typeof(onClose)=='function')
d.connect(d, "hide", function(e){
onClose();
});
return d;
},
_getModalDialog: function(title, href, sizeRatio, dialogMixin) {
sizeRatio = sizeRatio || 80;
var vs = win.getBox();
var w = Math.floor((vs.w/100)*sizeRatio);
var h = Math.floor((vs.h/100)*sizeRatio);
var d = new Dialog(lang.mixin({
title: title,
content: "",
draggable: true,
closable: true,
href: href,
maxRatio: sizeRatio,
scriptHasHooks: true,
style: "background-color: #FFFFFF;"
}, dialogMixin || {}));
d._forcedWidth = w;
d._forcedHeight = h;
domStyle.set(d.containerNode, {
'position' : "relative",
'padding' : 0
});
return d;
},
trackMouseOver: function(node) {
if(!node._mouseEnterSignal) {
node._mouseEnterSignal = on(node, mouse.enter, function(){ node._mouseOver = true;});
node._mouseLeaveSignal = on(node, mouse.leave, function(){ node._mouseOver = false;});
return false;
}
return true;
},
showTooltip: function(node, content) {
Tooltip.show(content, node);
on.once(node, mouse.leave, function(){
Tooltip.hide(node);
});
console.log("showTooltip is deprecated, use bindTooltip")
},
hideTooltip: function(node) {
Tooltip.hide(node);
},
bindTooltip: function(node, content, maxWidth, url) {
/*
innerHTML, aroundNode, position, rtl, textDir, onMouseEnter, onMouseLeave
*/
var renderFunc = function(rawContent) {
return maxWidth ? "<div style='max-width:"+maxWidth+"px; max-height:600px; overflow-y: scroll;'>" + rawContent + "</div>" : rawContent;
};
var hideFunc = function() {
setTimeout( function() {
if(!node._mouseOverTip)
Tooltip.hide(node);
}, 500 );
};
var showFunc = function() {
Tooltip.show(node._tooltip_content, node, null, null, null, function() {
node._mouseOverTip = true;
}, function() {
node._mouseOverTip = false;
hideFunc();
});
};
node._tooltip_content = renderFunc(content);
node._tooltip_url = url;
node._toolTipEnterSignal = on(node, mouse.enter, function(){
if(node._tooltip_url) {
if(!node._last_tooltip_url || node._last_tooltip_url != node._tooltip_url) {
request(node._tooltip_url).then(function(fetchedContent){
node._last_tooltip_url = node._tooltip_url;
node._tooltip_content = renderFunc(fetchedContent);
showFunc();
});
} else showFunc();
} else showFunc();
});
node._toolTipLeaveSignal = on(node, mouse.leave, hideFunc);
if(this.trackMouseOver(node)) {
if(node._mouseOver)
on.emit(node, "mouseover", {
bubbles: true,
cancelable: true
});
} else {
console.log("node was not tracked. To solve this issue, call COOL.getDialogManager().trackMouseOver() over it before calling bindTooltip the first time");
}
},
unbindTooltip: function(node) {
if(node._toolTipEnterSignal) {
node._toolTipEnterSignal.remove();
node._toolTipLeaveSignal.remove();
}
},
showXhrError: function (error) {
console.log(error);
errDialog = new Dialog({
title: "XHR error "+error.status,
content: '<div style="padding:5px; border:1px solid black; margin-bottom:10px;">'+error.response.url+'</div>'+error.responseText,
style: "width: 1000px; height:600px; overflow:auto;"
});
errDialog.show();
},
openRouteInTabContainer: function (tabContainer, title, route, routeParameters, parameters) {
parameters = parameters || {};
var url = Routing.generate(route, routeParameters || {});
var uid = parameters.uid;
var existingChildren, contentPaneToSelect;
try {
if (uid && (existingChildren = tabContainer.get('child_' + uid))) {
contentPaneToSelect = existingChildren;
} else {
contentPaneToSelect = this._getNewContentPane(title, parameters);
contentPaneToSelect.set('href', url);
contentPaneToSelect.on('reload', function() {
contentPaneToSelect.set('href', url);
});
tabContainer.addChild(contentPaneToSelect);
if (parameters.uid) {
tabContainer.set('child_' + uid, contentPaneToSelect);
contentPaneToSelect.on('close', function () {
tabContainer.set('child_' + uid, null);
});
}
}
tabContainer.selectChild(contentPaneToSelect);
} catch (e) {}
},
_getNewContentPane: function (title, parameters) {
parameters = parameters || {};
var contentPane = new ContentPane({
title: title,
closable: true,
executeScripts: true,
scriptHasHooks: true,
parseOnLoad: false,
onLoad: function (data) {
if (!this.reloadButton) {
this.reloadButton = new iconButton({
onClick: function () { contentPane.emit('reload'); },
iconSrc: "/bower_components/fugue/icons/arrow-circle.png",
showLabel: false,
tooltip: "Refresh"
});
this.buttonToggler = new Toggler({
node: this.reloadButton.domNode,
showFunc: dojoFx.wipeIn,
hideFunc: dojoFx.wipeOut
});
domConstruct.place(this.reloadButton.domNode, this.controlButton.domNode, "first");
}
},
onShow: function () {
if (this.buttonToggler)
this.buttonToggler.show();
},
onHide: function () {
if (this.buttonToggler)
this.buttonToggler.hide();
}
});
return contentPane;
}
}
}); |
/*jslint node: true, nomen: true */
"use strict";
var _ = require('underscore');
function getObjValue(field, data) {
return _.reduce(field.split("."), function (obj, f) {
if (obj) {
return obj[f];
}
}, data);
}
function setObjValue(field, data, value) {
var fieldArr = field.split('.');
return _.reduce(fieldArr, function (o, f, i) {
if (i === fieldArr.length - 1) {
o[f] = value;
} else {
if (!o[f]) {
o[f] = {};
}
}
return o[f];
}, data);
}
exports.updateDocument = function (doc, SchemaTarget, data) {
var newValue,
field;
for (field in SchemaTarget.schema.paths) {
if (SchemaTarget.schema.paths.hasOwnProperty(field)) {
if ((field !== '_id') && (field !== '__v')) {
newValue = getObjValue(field, data);
if (newValue !== undefined) {
setObjValue(field, doc, newValue);
}
}
}
}
return doc;
}; |
// Karma configuration
// Generated on Mon Jul 21 2014 11:48:34 GMT+0200 (CEST)
module.exports = function (config) {
config.set({
// base path used to resolve all patterns (e.g. files, exclude)
basePath: '',
// frameworks to use
frameworks: ['mocha', 'chai-sinon'],
// list of files / patterns to load in the browser
files: [
//start-vendor
//end-vendor
'app/bower_components/jassa/jassa.js',
'app/bower_components/Blob.js/Blob.js',
'app/**/angular-mocks.js',
//start-app
//end-app
'node_modules/chai-string/chai-string.js',
'app/**/*.spec.js'
],
// list of files to exclude
exclude: [
'app/bower_components/**/*.spec.js'
],
// preprocess matching files before serving them to the browser
preprocessors: {
'app/!(bower_components)/**/!(*spec).js': ['coverage']
},
coverageReporter: {
type: 'html',
dir: '.tmp/coverage/'
},
// test results reporter to use
reporters: ['progress', 'coverage'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests on file changes
autoWatch: true,
// start these browsers
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
}; |
module.exports = require('./variadic')(pipe)
function pipe(rest) {
return apply(compose, rest.reverse())
}
var compose = require('./compose')
, apply = require('./apply') |
(function (angular) {
'use strict';
angular.module('DiaryModule')
.controller('ListDiaryController', ['$scope', '$state', 'Diarys', 'toastr',
function ($scope, $state, Diarys, toastr) {
$scope.me = window.SAILS_LOCALS.me;
if (!$scope.me.kadr && !$scope.me.admin) $state.go('home');
$scope.nameArea = 'Наименование';
$scope.descriptionArea = 'Описание';
$scope.descriptionEnArea = 'Описание на английском';
/**
* Поле сортировки объекта по умолчанию.
* @type {string}
*/
$scope.sort = 'name';
$scope.debug = false;
/**
* Название кнопки в интерфейсе
* @type {string}
*/
$scope.addNameButton = 'Добавить дневник';
/**
* URL кнопки в интерфейсе
* @type {string}
*/
$scope.urlButton = 'home.admin.diarys.create';
/**
* Кол-во строу, по умолчанию, выбраных в объект
*/
$scope.limit = 300;
$scope.refresh = function () {
/**
* При обращении к службе $resource возвращается сгенерированный конструктор,
* дополненный методами для взаимодействия с конечной точкой
* RESTful: query, get, save и delete.
*/
// Сортировка наоборот sort: 'name DESC'
$scope.items = Diarys.query({limit: $scope.limit, sort: $scope.sort}, function (diarys) {
// console.log('TITLES ITEMS:', diarys);
$scope.items = diarys;
}, function (err) {
toastr.error(err, 'Ошибка ListDiaryController!');
});
};
$scope.propertyName = 'name';
$scope.reverse = false;
$scope.sortBy = function (propertyName) {
$scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
$scope.propertyName = propertyName;
};
$scope.msd = ['settings', 'home', 'options', 'other'];
$scope.selectionMode = $scope.msd[0];
// конструктор хлебных крошек
function BreadCrumb() {
var name;
var path;
this.arr = [];
}
BreadCrumb.prototype.add = function () {
this.arr.push({name: this.name, path: this.path});
};
BreadCrumb.prototype.set = function (name, path) {
this.name = name;
this.path = path;
this.add();
};
BreadCrumb.prototype.getAll = function () {
return this.arr;
};
var breadcrumb = new BreadCrumb();
breadcrumb.set('Home', 'home');
if ($scope.me.admin) breadcrumb.set('Admin', 'home.admin');
breadcrumb.set('Diarys', 'home.admin.diarys' + $state.current.url);
$scope.breadcrumbs = breadcrumb;
$scope.delete = function (item) {
console.log(item);
item.$delete(item, function (success) {
console.log(success);
$scope.refresh();
}, function (err) {
console.log(err);
})
};
$scope.refresh();
}])
;
})(window.angular); |
describe('basic functionality (text input)', function() {
before(function() {
this.genericPage = require('../lib/page/generic');
this.getTextarea = false;
});
require('./shared-tests/basic')();
it('should work well with the auto focus component', function() {
var page = this.genericPage.create('/auto-focus');
var extendTextComponent = page.getExtendTextComponent(this.getTextarea);
extendTextComponent.isFocused();
});
it('should be able to configure that the form submit when hitting enter on none tagging element', function() {
var page = this.genericPage.create('/allow-submit-on-enter');
var extendTextComponent = page.getExtendTextComponent(this.getTextarea);
extendTextComponent.type('test\uE007');
page.redirectedToFormSubmitPage('test');
});
}); |
'use strict';
var path = require('path'),
log4js = require('log4js'),
ucparam = require('./ucparam'),
util = require('./util'),
proto = Log.prototype;
function Log(options) {
if (!(this instanceof Log)) {
return new Log(options);
}
options = options || {};
options.filename = options.filename || 'app';
options.logLevel = options.logLevel || 'warn';
options.appID = options.appID || '0';
options.logDir = options.logDir || path.join(process.cwd(), 'private/log');
util.dir(options.logDir);
this.config = util.extend(true, {}, options);
this.logger = {};
log4js.clearAppenders();
// 只构造一次,重复调用返回已构造的实例
var that = this;
module.exports = function () {
return that;
};
}
module.exports = Log;
proto.getLogger = function (category, type) {
if (typeof category !== 'string' || category.length === 0) {
category = 'global';
}
if (!this.logger[category]) {
switch (category) {
case 'stat':
category = type;
this.logger[category] = getStatLogger(this, category);
break;
case 'email':
this.logger[category] = getEmailLogger(this);
break;
default:
this.logger[category] = getCategoryLogger(this, category);
}
}
return this.logger[category];
};
function getStatLogger(self, category) {
var options = self.config,
logger;
log4js.loadAppender('dateFile');
log4js.addAppender(log4js.appenderMakers.dateFile({
filename: options.filename + '_' + options.appID + '_' + category,
pattern: '_yyyyMMddhh.log',
alwaysIncludePattern: true,
layout: {
type: 'pattern',
pattern: '%x{data}',
tokens: {data: options.statFormater || function (e) {
var data = {},
line;
e.data.forEach(function (d) {
util.extend(data, d);
});
line = ucparam.stringify(data, {sep: '`', sort: false});
line = 'tm=' + formatDateTime(e.startTime) + (line.length ? '`' + line : '');
return line;
}}
}
}, {
cwd: options.logDir
}), category);
logger = log4js.getLogger(category);
logger.setLevel('info');
return logger;
}
function getEmailLogger(self) {
var options = self.config,
category = 'email',
logger;
log4js.loadAppender('dateFile');
log4js.addAppender(log4js.appenderMakers.dateFile({
filename: options.filename,
pattern: '.yyyyMMddhh.log',
alwaysIncludePattern: true
}, {
cwd: options.logDir
}), category);
log4js.addAppender(log4js.appenders.console(), category);
// 只在生产环境发送邮件
if (process.env.NODE_ENV === 'production') {
log4js.loadAppender('smtp');
log4js.addAppender(log4js.appenders.smtp({
sender: options.email.from,
recipients: options.email.to,
subject: options.email.subject,
transport: 'direct'
}), category);
}
logger = log4js.getLogger(category);
logger.setLevel(options.logLevel);
return logger;
}
function getCategoryLogger(self, category) {
var options = self.config,
logger;
log4js.loadAppender('dateFile');
log4js.addAppender(log4js.appenderMakers.dateFile({
filename: options.filename + '_' + options.appID,
pattern: '_default_yyyyMMddhh.log',
alwaysIncludePattern: true
}, {
cwd: options.logDir
}), category);
log4js.addAppender(log4js.appenders.console(), category);
logger = log4js.getLogger(category);
logger.setLevel(options.logLevel);
return logger;
}
function formatDateTime(date) {
function addZero(str) {
str = '0000' + str;
return str.substr(str.length - 2);
}
var dateObj = [
date.getFullYear(),
addZero(date.getMonth() + 1),
addZero(date.getDate())
],
timeObj = [
addZero(date.getHours()),
addZero(date.getMinutes()),
addZero(date.getSeconds())
];
return dateObj.join('-') + ' ' + timeObj.join(':');
} |
"use strict";
var async = require('async');
var Anyfetch = require('anyfetch');
module.exports.get = function get(req, res, next) {
async.waterfall([
function getDocument(cb) {
var anyfetchClient = new Anyfetch(req.accessToken.token);
anyfetchClient.getDocumentById(req.params.id, {
search: req.query.context,
render_templates: true
}, cb);
},
function mapDocument(documentRes, cb) {
var document = documentRes.body;
res.send(200, {
typeId: document.document_type.id,
providerId: document.provider.client.id,
documentId: document.id,
date: document.modification_date,
full: document.rendered_full,
title: document.rendered_title,
link: document.actions.show,
});
cb();
}
], next);
};
|
/*
*
* FileContainer actions
*
*/
import {
DEFAULT_ACTION,
UPDATE_FILE_INFO,
RECEIVE_FILE_ID,
UPDATE_BY_FILE_ID,
NEW_CONTAINER_ACTION,
ADD_NEW_ROW,
EDIT_ROW,
MAKE_SAVE_METADATA_ACTION,
MAKE_SAVE_METADATA_FROM_BACKEND,
DONT_SHOW_METADATA_FOR_DIRECTORY,
} from './constants';
// import { ADD_NEW_CONTAINER_ACTION } from '../../constants';
export function defaultAction({ frontendId }) {
return {
type: DEFAULT_ACTION,
frontendId,
};
}
export function makeUpdateFileInfoAction( fileInfo ) {
return {
type: UPDATE_FILE_INFO,
fileInfo,
};
}
export function receiveFileById({ fileId })
{
return {
type: RECEIVE_FILE_ID,
fileId,
};
}
export function updateFileById({ fileInfo }) {
return {
type: UPDATE_BY_FILE_ID,
fileInfo,
};
}
export function makeNewContainerAction(container) {
return {
type: NEW_CONTAINER_ACTION,
container,
};
}
export function makeChangeNewRowAction(row){
return {
type: ADD_NEW_ROW,
row,
};
}
export function makeEditRowAction(row,cellName,cellValue){
return {
type: EDIT_ROW,
row,
cellName,
cellValue,
};
}
export function makeSaveMetaDataAction() {
return {
type: MAKE_SAVE_METADATA_ACTION,
};
}
export function makeSaveMetaDataFromBackendAction( fileInfo ) {
return {
type: MAKE_SAVE_METADATA_FROM_BACKEND,
fileInfo,
};
}
export function makeDontShowMetaDataForDirectoryAction( ) {
return {
type: DONT_SHOW_METADATA_FOR_DIRECTORY,
}
}
|
"use strict";
var fs = require('fs-extra'),
async = require('async'),
path = require('path');
module.exports = function(ctx, done){
if(!ctx.includes || ctx.includes.length === 0){
return done();
}
async.parallel(Object.keys(ctx.includes).map(function(src){
return function(cb){
fs.mkdirs(path.dirname(ctx.dest('includes', src)), function(){
ctx.copyFile(src, ctx.dest('includes', src), cb);
});
};
}), done);
}; |
var gulp = require('gulp'),
stylus = require('gulp-stylus'),
connect = require('gulp-connect'),
concat = require('gulp-concat'),
changed = require('gulp-changed');
gulp.task('stylus', function () {
gulp.src('./client/app/styl/**/*.styl')
.pipe(changed('./client/public/css', { extension: '.css' }))
.pipe(stylus())
.pipe(concat('style.css'))
.pipe(gulp.dest('./client/public/css'))
.pipe(connect.reload());
}); |
var db = require( './../models/mysqlUser' );
var errors = require( './errors' );
var get_user_friends_list = function ( req, res, next ) {
var id = req.params.id1; // Given User ID
// Geting user friends list
db.get_user_friends( id, function ( err, data ) {
if ( err )
// If during getting friends list error occured, return an error message
return next( errors.new_std_error( err.status, 'Selecting friends error: ' + err.message ) );
// Send response with an array containing user friends IDs.
// If user have no friends empty array is sended
var showList = {
"friendsList": ( data ) ? data.map( function ( elem ) { return elem.id2 } ) : []
};
res.status( 200 ).end( JSON.stringify( showList ) );
} );
};
var users_connect = function ( req, res, next ) {
var id1 = req.params.id1; // Given first User ID
var id2 = req.params.id2; // Given second User ID
// Create friendship
db.create_users_friendship( id1, id2, function ( err ) {
if ( err )
// If during creating friends error occured, return an error message
return next( errors.new_std_error( err.status, 'Creating friends error: ' + err.message ) );
// Send positive response
res.status( 200 ).send( { message: "Users became friends" } );
} );
};
var users_disconnect = function ( req, res, next ) {
var id1 = req.params.id1; // Given first User ID
var id2 = req.params.id2; // Given second User ID
// Destroy friendship
db.destroy_user_friendship( id1, id2, function ( err ) {
if ( err )
// If during removing friends error occured, create an error message
return next( errors.new_std_error( err.status, 'Removing friends error: ' + err.message ) );
// Send positive response
res.status( 200 ).send( { message: "Users are not friends anymore" } );
} );
};
module.exports = {
get_user_friends_list: get_user_friends_list,
users_connect: users_connect,
users_disconnect: users_disconnect
}; |
/*
Highcharts JS v9.3.3 (2022-02-01)
Item series type for Highcharts
(c) 2019 Torstein Honsi
License: www.highcharts.com/license
*/
'use strict';(function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/modules/item-series",["highcharts"],function(b){a(b);a.Highcharts=b;return a}):a("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(a){function b(a,g,c,b){a.hasOwnProperty(g)||(a[g]=b.apply(null,c))}a=a?a._modules:{};b(a,"Series/Item/ItemPoint.js",[a["Core/Series/SeriesRegistry.js"],a["Core/Utilities.js"]],function(a,b){var c=this&&
this.__extends||function(){var a=function(b,e){a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,b){a.__proto__=b}||function(a,b){for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e])};return a(b,e)};return function(b,e){function f(){this.constructor=b}a(b,e);b.prototype=null===e?Object.create(e):(f.prototype=e.prototype,new f)}}(),g=a.series;b=b.extend;a=function(a){function b(){var b=null!==a&&a.apply(this,arguments)||this;b.graphics=void 0;b.options=void 0;b.series=void 0;return b}
c(b,a);return b}(a.seriesTypes.pie.prototype.pointClass);b(a.prototype,{haloPath:g.prototype.pointClass.prototype.haloPath});return a});b(a,"Series/Item/ItemSeries.js",[a["Core/Globals.js"],a["Series/Item/ItemPoint.js"],a["Core/DefaultOptions.js"],a["Core/Series/SeriesRegistry.js"],a["Core/Utilities.js"]],function(a,b,c,w,f){var g=this&&this.__extends||function(){var a=function(b,d){a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,d){a.__proto__=d}||function(a,d){for(var b in d)d.hasOwnProperty(b)&&
(a[b]=d[b])};return a(b,d)};return function(b,d){function z(){this.constructor=b}a(b,d);b.prototype=null===d?Object.create(d):(z.prototype=d.prototype,new z)}}(),e=c.defaultOptions,x=w.seriesTypes.pie,F=f.defined,y=f.extend,J=f.fireEvent,A=f.isNumber,B=f.merge,K=f.objectEach,L=f.pick;c=function(b){function c(){var a=null!==b&&b.apply(this,arguments)||this;a.data=void 0;a.options=void 0;a.points=void 0;return a}g(c,b);c.prototype.animate=function(a){a?this.group.attr({opacity:0}):this.group.animate({opacity:1},
this.options.animation)};c.prototype.drawDataLabels=function(){this.center&&this.slots?a.seriesTypes.pie.prototype.drawDataLabels.call(this):this.points.forEach(function(a){a.destroyElements({dataLabel:1})})};c.prototype.drawPoints=function(){var a=this,b=this.options,c=a.chart.renderer,e=b.marker,f=this.borderWidth%2?.5:1,C=0,r=this.getRows(),g=Math.ceil(this.total/r),t=this.chart.plotWidth/g,u=this.chart.plotHeight/r,v=this.itemSize||Math.min(t,u);this.points.forEach(function(d){var n,z,l=d.marker||
{},p=l.symbol||e.symbol;l=L(l.radius,e.radius);var H=F(l)?2*l:v,q=H*b.itemPadding,I;d.graphics=n=d.graphics||{};a.chart.styledMode||(z=a.pointAttribs(d,d.selected&&"select"));if(!d.isNull&&d.visible){d.graphic||(d.graphic=c.g("point").add(a.group));for(var h=0;h<d.y;h++){if(a.center&&a.slots){var m=a.slots.shift();var k=m.x-v/2;m=m.y-v/2}else"horizontal"===b.layout?(k=C%g*t,m=u*Math.floor(C/g)):(k=t*Math.floor(C/r),m=C%r*u);k+=q;m+=q;var M=I=Math.round(H-2*q);a.options.crisp&&(k=Math.round(k)-f,m=
Math.round(m)+f);k={x:k,y:m,width:I,height:M};"undefined"!==typeof l&&(k.r=l);n[h]?n[h].animate(k):n[h]=c.symbol(p,null,null,null,null,{backgroundSize:"within"}).attr(y(k,z)).add(d.graphic);n[h].isActive=!0;C++}}K(n,function(a,b){a.isActive?a.isActive=!1:(a.destroy(),delete n[b])})})};c.prototype.getRows=function(){var a=this.options.rows;if(!a){var b=this.chart.plotWidth/this.chart.plotHeight;a=Math.sqrt(this.total);if(1<b)for(a=Math.ceil(a);0<a;){var c=this.total/a;if(c/a>b)break;a--}else for(a=
Math.floor(a);a<this.total;){c=this.total/a;if(c/a<b)break;a++}}return a};c.prototype.getSlots=function(){function a(a){0<E&&(a.row.colCount--,E--)}for(var b=this.center,c=b[2],e=b[3],f,g=this.slots,r,w,t,u,v,x,n,D,l=0,p,G=this.endAngleRad-this.startAngleRad,q=Number.MAX_VALUE,y,h,m,k=this.options.rows,A=(c-e)/c,B=0===G%(2*Math.PI),F=this.total||0;q>F+(h&&B?h.length:0);)for(y=q,q=g.length=0,h=m,m=[],l++,p=c/l/2,k?(e=(p-k)/p*c,0<=e?p=k:(e=0,A=1)):p=Math.floor(p*A),f=p;0<f;f--)t=(e+f/p*(c-e-l))/2,u=
G*t,v=Math.ceil(u/l),m.push({rowRadius:t,rowLength:u,colCount:v}),q+=v+1;if(h){for(var E=y-this.total-(B?h.length:0);0<E;)h.map(function(a){return{angle:a.colCount/a.rowLength,row:a}}).sort(function(a,b){return b.angle-a.angle}).slice(0,Math.min(E,Math.ceil(h.length/2))).forEach(a);h.forEach(function(a){var c=a.rowRadius;x=(a=a.colCount)?G/a:0;for(D=0;D<=a;D+=1)n=this.startAngleRad+D*x,r=b[0]+Math.cos(n)*c,w=b[1]+Math.sin(n)*c,g.push({x:r,y:w,angle:n})},this);g.sort(function(a,b){return a.angle-b.angle});
this.itemSize=l;return g}};c.prototype.translate=function(b){0===this.total&&(this.center=this.getCenter());this.slots||(this.slots=[]);A(this.options.startAngle)&&A(this.options.endAngle)?(a.seriesTypes.pie.prototype.translate.apply(this,arguments),this.slots=this.getSlots()):(this.generatePoints(),J(this,"afterTranslate"))};c.defaultOptions=B(x.defaultOptions,{endAngle:void 0,innerSize:"40%",itemPadding:.1,layout:"vertical",marker:B(e.plotOptions.line.marker,{radius:null}),rows:void 0,crisp:!1,
showInLegend:!0,startAngle:void 0});return c}(x);y(c.prototype,{markerAttribs:void 0});c.prototype.pointClass=b;w.registerSeriesType("item",c);"";return c});b(a,"masters/modules/item-series.src.js",[],function(){})});
//# sourceMappingURL=item-series.js.map |
const test = require('ava')
const RingBuffer = require('../lib/RingBuffer')
test.beforeEach(t => {
t.context.ringBuffer = new RingBuffer({size: 5})
})
test('setArray', t => {
const expectArray = [1, 2, 3, 4, 5]
t.context.ringBuffer.setArray(expectArray)
t.deepEqual(t.context.ringBuffer._arr, expectArray, 'setArray within size')
t.context.ringBuffer.setArray([1, 2, 3, 4, 5, 6, 7])
t.deepEqual(t.context.ringBuffer._arr, expectArray, 'setArray over size')
})
test('push one', t => {
t.context.ringBuffer.push(1)
t.deepEqual(t.context.ringBuffer._arr, [1], 'push one')
})
test('push multi', t => {
t.context.ringBuffer.push(1)
t.context.ringBuffer.push(2)
t.context.ringBuffer.push(3)
t.context.ringBuffer.push(4)
t.context.ringBuffer.push(5)
t.context.ringBuffer.push(6)
t.deepEqual(
t.context.ringBuffer._arr, [2, 3, 4, 5, 6],
'push multi over buffer size'
)
})
test('read', t => {
t.context.ringBuffer.setArray([1, 2, 3])
t.is(t.context.ringBuffer.read(), 1, 'read index 0')
t.is(t.context.ringBuffer.read(1), 2, 'read index 1')
t.is(t.context.ringBuffer.read(-1), 3, 'read index -1')
t.is(t.context.ringBuffer.read(-2), 2, 'read index -2')
t.is(t.context.ringBuffer.read(5), 3, 'read index 5')
t.is(t.context.ringBuffer.read(6), 1, 'read index 6')
t.is(t.context.ringBuffer.read(-5), 2, 'read index -5')
t.is(t.context.ringBuffer.read(-6), 1, 'read index -6')
})
test('readAll basic behavior', t => {
t.context.ringBuffer.setArray([1, 2, 3, 4])
t.true(
t.context.ringBuffer !== t.context.ringBuffer.readAll(),
'readAll() return copy of ringBuffer._arr'
)
t.context.ringBuffer.setArray([1, 2])
t.deepEqual(
t.context.ringBuffer.readAll(), [1, 2],
'readAll() return same size of buffer'
)
})
test('readAll with startIndex', t => {
t.context.ringBuffer.setArray([1, 2, 3, 4])
t.context.ringBuffer.push(5)
t.context.ringBuffer.push(6)
t.deepEqual(
t.context.ringBuffer.readAll(), [2, 3, 4, 5, 6],
'readAll with startIndex: 0'
)
t.deepEqual(
t.context.ringBuffer.readAll(1), [3, 4, 5, 6, 2],
'readAll with startIndex: 1'
)
t.deepEqual(
t.context.ringBuffer.readAll(-1), [6, 2, 3, 4, 5],
'readAll with startIndex: -1'
)
})
test('clear', t => {
t.context.ringBuffer.setArray([1, 2])
t.notDeepEqual(t.context.ringBuffer._arr, [], 'before clear()')
t.context.ringBuffer.clear()
t.deepEqual(t.context.ringBuffer._arr, [], 'after clear()')
})
|
app.config(function ($stateProvider) {
$stateProvider.state('layout', {
abstract: true,
url: '',
views: {
'layout': {
templateUrl: 'static/core/views/layout.html'
}
}
})
})
|
function drt_triplets_from_api(cb){
var request = new XMLHttpRequest();
request.open('POST', 'api/relations', true);
request.setRequestHeader("Content-type", "application/json");
request.onload = function () {
data = this.response;
console.log(data)
err = '';
cb(data, err);
}
request.send(JSON.stringify({'text': document.getElementById('query').value}));
}
function submit_rules_to_api(cb){
var request = new XMLHttpRequest();
request.open('POST', 'api/set_rules', true);
request.setRequestHeader("Content-type", "application/json");
request.onload = function () {
data = this.response;
console.log(data)
err = '';
cb(data, err);
}
request.send(JSON.stringify({'text': document.getElementById('rules').value}));
} |
/*
* CSVJSON Application - SQL to JSON
*
* Copyright (c) 2014 Martin Drapeau
*/
APP.sql2json = function() {
var uploadUrl = "/sql2json/upload";
var $file = $('#fileupload'),
$format = $('input[type=radio][name=format]'),
$sql = $('#sql'),
$result = $('#result'),
$clear = $('#clear, a.clear'),
$convert = $('#convert, a.convert'),
$minify = $('#minify');
$convert.click(function(e) {
e.preventDefault();
var sql = _.trim($sql.val());
if (sql.length == 0) return err(errorEmpty);
var json;
try {
json = CSVJSON.sql2json(sql);
} catch(error) {
APP.reportError($result, error);
return false;
}
// Output requested format
var format = $format.filter(':checked').val(),
space = $minify.is(':checked') ? undefined : 2,
result = '';
if (format == "json")
result = JSON.stringify(json, null, space);
else
result = _.reduce(json, function(result, table, name) {
return result + "var " + name + " = " + JSON.stringify(table, null, space) + ";\n";
}, '');
$result.removeClass('error').val(result).change();
});
APP.start({
$convert: $convert,
$clear: $clear,
$saveElements: $('input.save, textarea.save'),
upload: {
$file: $file,
url: uploadUrl,
$textarea: $sql
}
});
}; |
'use strict';
/**
* Generates catalog.json
* Inherits EventEmitter
* Emits: log
* */
var EventEmitter = require('events').EventEmitter,
Promise = require('bluebird'),
_ = require('lodash'),
path = require('path'),
moment = require('moment'),
fse = Promise.promisifyAll(require('fs-extra'));
module.exports = function createCataloger(options){
var that = new EventEmitter();
that.config = options;
that.catalog = {};
function log(message){
that.emit('log', message);
}
that.read = function read(){
log('loading');
return fse.readJsonAsync(path.join(options.catalogDir, options.catalogName))
.then(function (obj){
that.catalog = obj;
return that.catalog;
})
.catch(function (err){
log('cataloger: error reading catalog: ' + path.join(options.catalogDir, options.catalogName) + ', doing rebuildAll');
log(err);
return that.rebuildAll()
.then(that.write);
});
};
that.write = function write(){
log('writing');
return fse.outputJsonAsync(path.join(options.catalogDir, options.catalogName), that.catalog)
.catch(function (err){
log('error writing catalog: ' + path.join(options.catalogDir, options.catalogName));
log(err);
});
};
that.rebuildAll = function rebuildAll(){
log('rebuilding all');
that.catalog = {
cameras: []
};
options.cameras.forEach(function (camera){
that.catalog.cameras.push({
cameraName: camera[0],
folders: []
});
});
return Promise.map(that.catalog.cameras, function (camera){
return fse.readdirAsync(path.join(options.catalogDir, camera.cameraName))
.call('filter', function (dateFolder){
return dateFolder.length === 8 && moment(dateFolder, 'YYYYMMDD').format('YYYYMMDD') === dateFolder;
})
.map(function (dateFolder){
return that.rebuildDay(camera.cameraName, dateFolder);
})
.then(function (){
return that.catalog;
})
.catch(function (err){
log('rebuildAll error read dir: ' + path.join(options.catalogDir, camera.cameraName));
log(err);
return that.catalog;
});
});
};
that.rebuildDay = function rebuildDay(cameraName, dateFolder){
log('rebuilding day: ' + cameraName + '/' + dateFolder);
var camera = _.find(that.catalog.cameras, 'cameraName', cameraName);
if (!camera) {
log('Camera: ' + cameraName + ' not found');
return Promise.resolve();
}
return fse.readdirAsync(path.join(options.catalogDir, cameraName, dateFolder))
.call('filter', function (fileName){
var p = path.parse(fileName);
return p.ext === '.mp4' && (p.name.slice(0, 3) === 'out' || p.name.slice(0, 6) === 'motion');
})
.then(function (files){
var folder = {
folderName: dateFolder,
out: [],
motion: []
};
files.forEach(function (fileName){
if (fileName.slice(0, 3) === 'out') {
folder.out.push(fileName.slice(3, 100).slice(0, -4));
} else if (fileName.slice(0, 6) === 'motion') {
folder.motion.push(fileName.slice(6, 100).slice(0, -4));
}
});
var found = _.find(camera.folders, 'folderName', folder.folderName);
if (found) {
_.assign(found, folder);
} else {
camera.folders.push(folder);
}
camera.folders = _.sortBy(camera.folders, 'folderName');
})
.catch(function (err){
log('rebuildDay error read dir: ' + path.join(options.catalogDir, cameraName, dateFolder));
log(err);
});
};
return that;
}; |
((win, ns, undefined) => {
var namespace = win[ns] || {}
win[ns] = namespace
const newWindowBtn = document.getElementById('frameless-window')
newWindowBtn.addEventListener('click', (event) => {
let win = new BrowserWindow({
frame: false,
//transparent: true
})
win.on('closed', () => { win = null })
win.loadURL(appUrl + '/modal?closable=true')
win.show()
})
})(window, 'electron')
|
(() => {
return {
mixins: [bbn.vue.basicComponent, bbn.vue.localStorageComponent],
props: {
storage: {
default: true
},
storageFullName: {
default: 'appui-ide-popup-new'
}
},
data(){
let rep = this.source.type !== false ? this.source.repositoryProject : this.source.repositories[this.source.currentRep];
let defaultTab = '';
let defaultExt = '';
let storage = this.getStorage();
let template = storage.template || 'file';
if ( rep.tabs ){
bbn.fn.each(rep.tabs, (a, k) => {
if ( a.default ){
defaultTab = k;
if ( this.source.isFile ){
defaultExt = a.extensions[0].ext;
}
}
});
}
if ( this.source.isFile && rep.extensions ){
defaultExt = rep.extensions[0].ext;
}
return {
isMVC: ((rep !== undefined) && (rep.tabs !== undefined) && ((rep.alias_code !== "components") && (rep.alias_code !== "bbn-project"))) || ((rep !== undefined) && (this.source.type === "mvc")),
isComponent: ((rep !== undefined) && (rep.tabs !== undefined) && ((rep.alias_code === "components") && (rep.alias_code !== "bbn-project"))) || (this.source.type === "components"),
rep: rep,
type: this.source.type || false,
templates: [
{value: 'mvc_vue', text: bbn._('Page with Vue component')},
{value: 'mvc_js', text: bbn._('Page with Javascript function')},
{value: 'mvc', text: bbn._('Simple page (combo)')},
{value: 'action', text: bbn._('Action')},
{value: 'file', text: bbn._('Single MVC file')}
],
data: {
tab: ((this.source.tab_mvc !== undefined) && this.source.tab_mvc.length && (this.source.type === 'mvc')) ?
bbn.fn.search(rep.tabs, 'url', this.source.tab_mvc) :
defaultTab,
name: '',
controller: '',
model: '',
html: '',
js: '',
css: '',
container: '',
class: '',
template: template,
extension: defaultExt,
is_file: this.source.isFile,
type: this.source.type || false,
path: (this.source.path === './') ? './' : this.source.path + '/'
},
window: null
}
},
computed: {
availableExtensions(){
if ( this.rep && this.source.isFile ){
if ( this.rep.tabs ){
this.data.extension = this.rep.tabs[this.data.tab].extensions[0].ext;
return this.rep.tabs[this.data.tab].extensions
}
else{
this.numExt = 0;
this.numExt = this.rep.extensions.length;
return this.rep.extensions
}
}
return [];
},
types(){
let res = [];
if ( this.isMVC || (this.source.isFile && this.isComponent) ){
bbn.fn.each(this.rep.tabs, (v, i) => {
if ( !v.fixed ){
res.push({
text: v.title,
value: i
});
}
});
}
return res;
},
defaultText(){
if ( this.availableExtensions ){
for ( let i in this.availableExtensions ){
if ( this.availableExtensions[i].ext === this.data.extension ){
return this.availableExtensions[i].default;
}
}
;
}
return false
},
formData(){
return {
tab_path: this.isMVC && this.rep && this.rep.tabs[this.data.tab] ? this.rep.tabs[this.data.tab].path : '',
tab_url: this.isMVC && this.rep && this.rep.tabs[this.data.tab] ? this.rep.tabs[this.data.tab].url : '',
default_text: this.defaultText,
repository: this.rep,
type: this.source.type
}
},
extensions(){
if ( this.rep && this.source.isFile ){
if ( this.rep.tabs ){
this.data.extension = this.rep.tabs[this.data.tab].extensions[0].ext;
return this.rep.tabs[this.data.tab].extensions
}
else{
this.numExt = 0;
this.numExt = this.rep.extensions.length;
return this.rep.extensions
}
}
return [];
},
hasFileDetails(){
return this.data.template && !['file', 'action'].includes(this.data.template);
},
},
methods: {
onSuccess(){
let componentEditor = this.closest('bbn-container').find('appui-ide-editor');
if ( this.source.isFile ){
let link = this.source.root + 'editor/file/' + this.source.currentRep + '/' +
(this.isMVC && this.source.type === 'mvc' ? 'mvc/' : '');
if ( this.data.path.startsWith('./') ){
link += this.data.path.slice(2);
}
else if ( this.data.path.startsWith('mvc/') ){
link += this.data.path.slice(4);
}
else{
link += this.data.path;
}
link += this.data.name + (this.isComponent === true ? '/'+ this.data.name : '' ) + '/_end_';
if ( (this.data.tab > 0) && this.data.extension.length ){
link += '/' + this.rep.tabs[this.data.tab]['url'];
}
else if ( (this.data.tab === 0) && this.data.extension ){
link += '/code';
}
if ( link.indexOf('//') !== -1 ){
link= link.replace('//', '/');
}
bbn.fn.link(link);
appui.success(this.isComponent === true ? bbn._("Component created!") : bbn._("File created!"));
}
else{
appui.success(bbn._("Directory created!"));
}
if ( (this.data.path === './') ||
(this.data.path === 'components/') ||
(this.data.path === 'mvc/') ||
(this.data.path === 'lib/') ||
(this.data.path === 'cli/') ||
(this.source.parent === false)
){
componentEditor.treeReload();
}
else{
if ( componentEditor.nodeParent !== false ){
componentEditor.nodeParent.reload();
this.$nextTick(()=>{
componentEditor.$set(componentEditor, 'nodeParent', false);
});
}
//this.source.parent.reload();
}
},
failureActive(){
appui.error(bbn._("Error!"));
},
selectDir(){
this.closest("bbn-container").getPopup({
width: 300,
height: 400,
title: bbn._('Path'),
component: 'appui-ide-popup-path',
source: bbn.fn.extend(this.$data, {operation: 'create'})
});
},
getRoot(){
if ( this.source.isProject ){
this.data.path = this.source.type + '/';
}
else{
this.data.path = './';
}
}
},
mounted(){
this.window = this.closest('bbn-floater');
},
watch: {
"data.template"(v){
if (this.window) {
this.window.onResize(true)
}
if (!this.data.name) {
this.$refs.filename.focus();
}
let storage = this.getStorage();
if (!storage) {
storage = {};
}
bbn.fn.log("TEMPLATE", storage, v);
if (v !== storage.template) {
storage.template = v;
this.setStorage(storage);
}
}
}
}
})();
|
import './parser.js'
|
//contains code to manage the page routing
var log = new Logger('router.js', CLL.error);
//This adds our default layout
Router.configure({
layoutTemplate: 'layout'
});
//configures the router to change the navigation highlighting after routed page
Router.onAfterAction(function () {
//handles updated the navigation view after a page is routed
log.trace("onAfterAction: " + this.url);
//After a page is routed trigger the PageRouted event
//EventBroker.trigger('router.routeCompleted');
var routeCounter = 0;
var routerName = Router.current().route.getName();
for (routeCounter = 0; routeCounter < Router.routes.length; routeCounter++) {
if (Router.routes[routeCounter].path() === "/" + routerName) {
Navigation.updateCurrentPage(Router.routes[routeCounter].url());
return false;
}
}
});
//This will creat the default routed page, the '/' is the default key
//The string used must match the template name
Router.route('/', function () {
this.render('Home');
});
//Setup the other route paths for each page
Router.route('/Home');
Router.route('/MRP_Table');
Router.route('/MRPButton');
Router.route('/MRPCheckBox');
Router.route('/MRPTextBox');
Router.route('/MRPDropDown');
Router.route('/MRPAlert');
Router.route('/MRPButtonSet');
Router.route('/Brokers');
Router.route('/Dev');
//passing parameters to a routed page - or you can just use a global variable (much easier)
Router.route('/ConsumableRequest/:id', function () {
this.render('ConsumableRequest', {
//This is how you cna pass parrameters
data: function () {
return {id: this.params.id};//use {{id}} in the template to access this variable
}
});
}, {
//You must add a name to the route so it can be called parameters
name: 'ConsumableRequest.show'
});
|
'use strict';
const unescape = require('lodash/unescape');
const marked = require('marked');
const chalk = require('chalk');
const index = require('./index');
const allElements = [
'blockquote', 'html', 'strong', 'em', 'br', 'del',
'heading', 'hr', 'image', 'link', 'list', 'listitem',
'paragraph', 'strikethrough', 'table', 'tablecell', 'tablerow'
];
function unhtml(text){
return unescape(text);
}
exports.parse = (markdown) => {
// Creating the page structure
let page = {
name: '',
description: '',
examples: [],
seeAlso: []
};
// Initializing the markdown renderer
let r = new marked.Renderer();
// ignore all syntax by default
allElements.forEach((e) => {
r[e] = () => { return ''; };
});
// Overriding the different elements to incorporate the custom tldr format
r.codespan = (text) => {
if (index.hasPage(text) && text !== page.name) {
if (page.seeAlso.indexOf(text) < 0) {
page.seeAlso.push(text);
}
}
let example = page.examples[page.examples.length-1];
// If example exists and a code is already not added
if (example && !example.code) {
example.code = unhtml(text);
}
return text;
};
// underline links
r.link = (uri) => {
return uri;
};
// paragraphs just pass through (automatically created by new lines)
r.paragraph = (text) => {
return text;
};
r.heading = (text, level) => {
if (level === 1) {
page.name = text.trim();
}
return text;
};
r.blockquote = (text) => {
page.description += unhtml(text);
return text;
};
r.strong = (text) => {
return chalk.bold(text);
};
r.em = (text) => {
return chalk.italic(text);
};
r.listitem = (text) => {
page.examples.push({
description: unhtml(text)
});
return text;
};
marked.parse(markdown, {
renderer: r
});
page.examples = page.examples.filter((example) => {
return example.description && example.code;
});
return page;
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.