code stringlengths 2 1.05M |
|---|
var analyzerPlugins = analyzerPlugins || [];
analyzerPlugins.push(
{
init:function () {
// Register visualizations to display in Analyzer
cv.pentahoVisualizations.push(pentaho.visualizations.getById("sample_calc"));
/*
Helpers contain code that knows about the Analyzer specific context. The one function that's required
"generateOptionsFromAnalyzerState" is called so the visualization can set it's own options based on
Analyzers current report.
*/
cv.pentahoVisualizationHelpers["sample_calc"] = {
// use one of Analyzer's stock placeholder images
placeholderImageSrc: CONTEXT_PATH + "content/analyzer/images/viz/VERTICAL_BAR.png",
// set visualization options based on analyzer's state.
generateOptionsFromAnalyzerState:function (report) {
return {}; // perform no work
}
};
/*
LayoutConfig objects manage the interaction between Analyzer's Layout Panel and the visualization's settings.
*/
// Declare a new class which extends the built-in version from Analyzer
dojo.declare("SampleConfig", [analyzer.LayoutConfig], {
/**
* @param config The parse Configuration object which serves as the model of of the Panel
* @param item The item in the panel which originated the event.
* @param eventName The name of the event (clicked, value, etc)
* @param args A Hash Object containing relevent values (prevVal, newVal, etc)
*/
onModelEvent: function(config, item, eventName, args) {
this.report.visualization.args["calc"] = config.byId("calc").value;
this.inherited(arguments); // Let super class handle the insertAt and removedGem events
},
/**
* Return the JSON configuration object which the panel will use to create the UI and it's model
*/
getConfiguration: function() {
var config = this.inherited(arguments);
dojo.forEach(config.properties, function (item) {
if (this.report.visualization.args[item.id] !== "undefined") {
item.value = this.report.visualization.args[item.id];
}
}, this);
return config;
}
});
// Register the Layout Panel Configuration Manager
analyzer.LayoutPanel.configurationManagers["JSON_sample_calc"] = SampleConfig;
}
}
);
|
'use strict';
angular.module('app')
.controller('SignupCtrl', ['$scope', '$sce', '$location', '$auth', 'toastr', 'GetPredefinedVars', 'WizardHandler', 'Register', 'CheckForUnique', function($scope, $sce, $location, $auth, toastr, GetPredefinedVars, WizardHandler, Register, CheckForUnique) {
$scope.languages = [];
$scope.countries = [];
$scope.categories = [];
$scope.networks = [];
$scope.postTypes = [];
$scope.price = {};
$scope.user = {};
$scope.dateOptions = {
maxDate: '-10y',
dateFormat: 'yy-mm-dd'
};
$scope.initIntlVars = function() {
GetPredefinedVars.getIntl().then(function(resp) {
if (resp.data.countries) {
$scope.countries = resp.data.countries;
}
if (resp.data.languages){
$scope.languages = resp.data.languages;
}
});
GetPredefinedVars.getCategories().then(function(resp) {
if (resp.data.categories) {
$scope.categories = resp.data.categories;
}
});
GetPredefinedVars.getTypes().then(function(resp) {
if (resp.data.types) {
$scope.postTypes = resp.data.types;
}
});
GetPredefinedVars.getSocialNetworks().then(function(resp) {
if (resp.data.networks) {
$scope.networks = resp.data.networks;
}
});
};
$scope.sizeOf = function(obj) {
return Object.keys(obj).length;
};
$scope.steps = {
main: false,
audience: false,
campaign: false
};
$scope.trustAsHtml = function(value) {
return $sce.trustAsHtml(value);
};
$scope.registrationFinished = function() {
Register.submitInfluencerData($scope.user).then(function(resp) {
if (resp.token) {
$location.path('/');
} else {
alert(resp.error);
}
});
};
$scope.goToStep = function(step){
WizardHandler.wizard().goTo(step - 1);
};
$scope.getCurrentStep = function(){
return WizardHandler.wizard().currentStepNumber();
};
$scope.goBack = function() {
WizardHandler.wizard().goTo(0);
};
$scope.setSubmitted = function(form) {
angular.forEach(form.$error, function (field) {
angular.forEach(field, function(errorField){
errorField.$setTouched();
errorField.$pristine = false;
})
});
form.$setSubmitted();
};
$scope.setProfileImage = function($file, $event, $flow) {
var fileReader = new FileReader();
fileReader.onload = function(event) {
$scope.user.profileImage = event.target.result;
//delete $flow.files[0];
$scope.$apply(function($scope){
$scope.myImage=event.target.result;
});
};
fileReader.readAsDataURL($file.file);
};
$scope.cropProfileImage = function(obj) {
$scope.sourceImage = '';
$scope.croppedImage = '';
var fileReader = new FileReader();
fileReader.onload = function(event) {
$scope.$apply(function($scope){
$scope.sourceImage = event.target.result;
});
};
fileReader.readAsDataURL(obj.files[0].file);
};
$scope.saveCroppedImage = function(croppedImage) {
$scope.user.profileImage = croppedImage;
};
$scope.removeProfileImage = function(obj) {
obj.cancel();
$scope.user.profileImage = null;
};
$scope.checkForMain = function() {
return $scope.steps['main'];
};
$scope.checkForAudience = function() {
return $scope.steps['audience'];
};
$scope.checkForCampaign = function() {
return $scope.steps['campaign'];
};
$scope.saveMainInfo = function(mainInfluencerInfo) {
if (mainInfluencerInfo.$valid) {
$scope.steps['main'] = true;
WizardHandler.wizard().next();
} else {
$scope.setSubmitted(mainInfluencerInfo);
$scope.steps['main'] = false;
}
};
$scope.saveAudienceInfo = function(audienceAndInfluencerDataInfo) {
$scope.user.audience = [];
if ($scope.user.website === undefined) {
$scope.user.website = '';
}
if (audienceAndInfluencerDataInfo.$valid) {
$scope.steps['audience'] = true;
WizardHandler.wizard().next();
} else {
$scope.setSubmitted(audienceAndInfluencerDataInfo);
$scope.steps['audience'] = false;
}
};
$scope.saveCampaignInfo = function(campaignInfluencerInfo) {
if (campaignInfluencerInfo.$valid) {
$scope.steps['campaign'] = true;
WizardHandler.wizard().next();
} else {
$scope.setSubmitted(campaignInfluencerInfo);
$scope.steps['campaign'] = false;
}
};
$scope.connectAccount = function(network) {
$auth.link(network, {'link_account': 1}).then(function(resp) {
if ($scope.user.socials === undefined) {
$scope.user.socials = {};
}
if (resp.data.profile.id) {
$scope.user.socials[network] = {
id: resp.data.profile.id,
token: resp.data.token
};
}
if (resp.data.profile.sub) {
$scope.user.socials[network] = {
id: resp.data.profile.sub,
token: resp.data.token
};
}
});
};
$scope.connectBlog = function(blogRss) {
if (blogRss) {
if (!$scope.user.socials) {
$scope.user.socials = {};
}
$scope.user.socials['blog'] = {
'name': 'Blog',
'tag': 'blog',
'rss': blogRss
};
}
console.log($scope.socials);
};
}]).directive('ensureUnique', ['$http', function($http) {
return {
require: 'ngModel',
link: function(scope, ele, attrs, c) {
scope.$watch(attrs.ngModel, function() {
$http({
url: Routing.generate('inf_check_for_email'),
method: 'POST',
data: {'email': ele.val()}
}).then(function(resp) {
if (resp.data.status == 'fail') {
c.$setValidity('unique', false);
} else {
c.$setValidity('unique', true);
}
});
});
}
}
}]).directive('positiveNumber', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, ele, attrs, c) {
var regexp = /\d+\.(\d{1,2})?/;
if (!regexp.test(ele.val())) {
c.$setValidity('negative', true);
}
ele.bind('keypress', function(event) {
if (event.keyCode === 32) {
event.preventDefault();
}
});
}
};
});
|
// { "path" : "imports/ui/routes/index.js" }
import './mainRoutes'
|
import React from 'react';
import ReactDOM from 'react-dom';
import createReactClass from 'create-react-class';
import classNames from 'classnames';
import createHistory from 'history/createBrowserHistory';
import { Router, Route, Link, Switch } from 'react-router-dom';
const browserHistory = createHistory();
const NavItems = [
{ value: '/css', label: 'CSS' },
{ value: '/grid', label: 'Grid' },
{ value: '/buttons', label: 'Buttons' },
{ value: '/glyphs', label: 'Glyphs' },
{ value: '/forms', label: 'Forms' },
{ value: '/spinner', label: 'Spinner' },
{ value: '/modal', label: 'Modal' },
{ value: '/misc', label: 'Misc' }
// { value: 'date-picker', label: 'Date Picker' }
];
const PageNav = createReactClass({
getInitialState () {
return {
mobileMenuIsVisible: false,
windowHeight: window.innerHeight,
windowWidth: window.innerWidth
};
},
componentDidMount () {
window.addEventListener('resize', this.handleResize);
},
componentWillUnmount () {
window.removeEventListener('resize', this.handleResize);
},
handleResize () {
this.setState({
windowHeight: window.innerHeight,
windowWidth: window.innerWidth
});
},
toggleMenu () {
this.setState({
mobileMenuIsVisible: !this.state.mobileMenuIsVisible
});
},
render () {
var self = this;
var height = (this.state.windowWidth < 768) ? this.state.windowHeight : 'auto';
var menuClass = this.state.mobileMenuIsVisible ? 'primary-nav-menu is-visible' : 'primary-nav-menu is-hidden';
var menuItems = NavItems.map(function(item) {
return (
<Route key={item.value} path={item.value} exact children={({ match }) => (
<Link className={classNames('primary-nav__item', { active: match })} onClick={self.toggleMenu} to={item.value}>
<span className="primary-nav__item-inner">{item.label}</span>
</Link>
)}/>
);
});
return (
<nav className="primary-nav">
<Link to="/home" className="primary-nav__brand special" title="Home">
<img src="./images/elemental-logo-paths.svg" className="primary-nav__brand-src" />
</Link>
{/*<Link to="home">Home</Link>*/}
<button onClick={this.toggleMenu} className="primary-nav__item primary-nav-menu-trigger">
<span className="primary-nav-menu-trigger-icon octicon octicon-navicon" />
<span className="primary-nav-menu-trigger-label">{this.state.mobileMenuIsVisible ? 'Close' : 'Menu'}</span>
</button>
<div className={menuClass} style={{ height }}>
<div className="primary-nav-menu-inner">
{menuItems}
</div>
</div>
<a href="https://github.com/elementalui/elemental" target="_blank" title="View on GitHub" className="primary-nav__brand right">
<img src="./images/github-logo.svg" className="primary-nav__brand-src" />
</a>
</nav>
);
}
});
const App = createReactClass({
render () {
return (
<div className="page-wrapper">
<PageNav />
<div className="page-body">
{this.props.children}
</div>
<div className="page-footer">
<div className="demo-container container">
Copyright © 2016 · (MIT) License · Built by <a href="http://www.thinkmill.com.au" target="_blank">Thinkmill</a>, initially for integration with <a href="http://www.keystonejs.com" target="_blank">KeystoneJS</a>
</div>
</div>
</div>
);
}
});
const basepath = (window.location.pathname.slice(0, 10) === '/elemental') ? '/elemental' : '';
ReactDOM.render(
<Router history={browserHistory} onUpdate={() => window.scrollTo(0, 0)}>
<App>
<Switch>
<Route path="/home" component={require('./pages/Home')} />
<Route path="/css" component={require('./pages/CSS')} />
<Route path="/grid" component={require('./pages/Grid')} />
<Route path="/buttons" component={require('./pages/Buttons')} />
<Route path="/glyphs" component={require('./pages/Glyphs')} />
<Route path="/forms" component={require('./pages/Forms')} />
<Route path="/spinner" component={require('./pages/Spinner')} />
<Route path="/modal" component={require('./pages/Modal')} />
<Route path="/misc" component={require('./pages/Misc')} />
<Route component={require('./pages/Home')} />
</Switch>
</App>
</Router>,
document.getElementById('app')
);
|
"use strict";
var PeshOS = PeshOS || {};
PeshOS.Poll = PeshOS.Poll || {};
PeshOS.Poll.constants = {
ConfigurationList: 'PollConfiguration',
VotesList: 'PollVotes',
ExportList: 'PollExports',
VotesListTemplate: 10001,
VotesListTemplateFeatureId: '89836f36-72ea-4af4-9b3f-8550a00d5875'
};
PeshOS.Poll.configObj = {}; |
var data = {gui-js: {}} |
module.exports = (options) => {
return (link) => {
switch (link.type) {
case "link":
return !!options.checkLinks
case "anchor":
return !options.allowAnchors
case "image":
return !!options.checkImages
default:
return false
}
}
}
|
window.addEventListener("deviceorientation", on_device_orientation);
// parametri senzor miscare
var alpha = 0;
var beta = 0;
var gamma = 0;
var vechi = [];
var pasi = 100; // minim 3
var pondere_curenta = pasi;
var run_function = false;
for (var i = 0 ; i < pasi ; i++)
{
p = pasi - i;
vechi.push({importanta:p, v_alpha:0, v_beta:0, v_gamma:0});
}
// creare canvas si context
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.width = window.innerWidth-20;
canvas.height = window.innerHeight-200;
var color = "red";
// functii
function on_device_orientation(evt)
{
if (run_function)
return 0;
run_function = true;
// citire valori de la senzor
var t_alpha = Math.round(evt.alpha);
var t_beta = Math.round(evt.beta);
var t_gamma = Math.round(evt.gamma);
var vechime_alpha = 0;
var vechime_beta = 0;
var vechime_gamma = 0;
var vechime_importanta = 0;
for (i = pasi - 1; i >= 0; i--)
{
// adunare ponderat valori vechi
vechime_alpha = vechime_alpha + (vechi[i].importanta * vechi[i].v_alpha);
vechime_beta = vechime_beta + (vechi[i].importanta * vechi[i].v_beta);
vechime_gamma = vechime_gamma + (vechi[i].importanta * vechi[i].v_gamma);
// adunare importanta
vechime_importanta = vechime_importanta + vechi[i].importanta;
if (i>0)
{
// mutare valori cu un pas ("invechire date")
vechi[i].v_alpha = vechi[i-1].v_alpha;
vechi[i].v_beta = vechi[i-1].v_beta;
vechi[i].v_gamma = vechi[i-1].v_gamma;
}
else
{
// valorile actuale devin vechi
vechi[0].v_alpha = t_alpha;
vechi[0].v_beta = t_beta;
vechi[0].v_gamma = t_gamma;
}
}
// calculare valori poderate
alpha = Math.round((t_alpha*pondere_curenta + vechime_alpha) / (vechime_importanta + pondere_curenta));
beta = Math.round((t_beta*pondere_curenta + vechime_beta) / (vechime_importanta + pondere_curenta));
gamma = Math.round((t_gamma*pondere_curenta + vechime_gamma) / (vechime_importanta + pondere_curenta));
// afisare valori
document.getElementById("valori").innerHTML =
"      alpha = " + alpha.toString() +
",       beta = " + beta.toString() +
",       gamma = " + gamma.toString();
// stergere zona ecran (canvas)
ctx.clearRect(0, 0, canvas.width, canvas.height);
// raza si calcul centru cerc
var raza = 60;
var centru = {x:canvas.width/2, y:canvas.height/2};
ctx.lineWidth = 15;
ctx.beginPath();
// desenare cerc
ctx.arc(centru.x + gamma * (canvas.width/2 - raza)/90, centru.y + beta * (canvas.height/2 - raza)/90, raza, 0, 2 * Math.PI);
// calcul culoare
var a = Math.round(alpha * 255 / 360);
var b = 255 - a;
ctx.fillStyle = "#" + a.toString(16) + "0F" + b.toString(16);
ctx.strokeStyle = color;
ctx.fill();
ctx.stroke();
// vibreaza daca bila se apropie de margine
if ((Math.abs(beta) > 70) || (Math.abs(gamma) > 70))
{
navigator.vibrate(1000);
}
run_function = false;
}
|
/**
* 简单API服务器
*
* @author Zongmin Lei <leizongmin@gmail.com>
*/
var clone = require('clone');
var parseUrl = require('url').parse;
var formatUrl = require('url').format;
var utils = module.exports = exports = clone(require('lei-utils'));
// 将参数添加到URL
utils.addQueryParamsToUrl = function (url, params) {
var info = parseUrl(url, true);
for (var i in params) {
info.query[i] = params[i];
}
delete info.search;
return formatUrl(info);
};
// 如果数值不大于0则返回默认值
utils.defaultNumber = function (n, d) {
n = Number(n);
return n > 0 ? n : d;
};
// 创建出错对象,code=出错代码,msg=出错描述信息
utils.createApiError = function (code, msg) {
var err = new Error(msg);
err.error_code = code;
err.error_message = msg;
return err;
};
// 缺少参数错误
utils.missingParameterError = function (name) {
return utils.createApiError('MISSING_PARAMETER', '缺少参数`' + name + '`');
};
// 回调地址不正确错误
utils.redirectUriNotMatchError = function (url) {
return utils.createApiError('REDIRECT_URI_NOT_MATCH', '回调地址不正确:' + url);
};
// 参数错误
utils.invalidParameterError = function (name) {
return utils.createApiError('INVALID_PARAMETER', '参数`' + name + '`不正确');
};
// 超出请求频率限制错误
utils.outOfRateLimitError = function () {
return utils.createApiError('OUT_OF_RATE_LIMIT', '超出请求频率限制');
};
|
function (c, arg) { //start:0, pages:1, level:4
function is_npc(name) {
var last_action = #s.users.last_action({
name: [name, 'gibson']
});
return last_action[0] && last_action[0].t.getTime() == last_action[1].t.getTime();
}
function getLevel(level, start) {
var a = { start: start };
switch(level) {
case 4:
return #s.scripts.fullsec(a);
case 3:
return #s.scripts.highsec(a);
case 2:
return #s.scripts.midsec(a);
case 1:
return #s.scripts.lowsec(a);
case 0:
return #s.scripts.nullsec(a);
default:
throw 'Unknown level';
}
}
var scripts = [],
ind = arg.start * 128,
t = getLevel(arg.level, ind);
while (t.length > 0 && arg.pages > 0) {
scripts = scripts.concat(t);
ind = ind + 128;
t = getLevel(arg.level, ind);
arg.pages--;
}
var usrs = scripts
.filter(x => {
var y = x.split('.')[0];
return is_npc(y);
});
return {
ok: true,
msg: usrs
};
}; |
/*
* regular-replace <https://github.com/hingisr/regular-replace
*
* Copyright (c) 2015, hingsir.
* Licensed under the MIT License.
*/
var regularReplace = {
thousands: function(number) {
return number.replace(/^(\d+)(\.\d+)?$/, function($, $1, $2) {
return $1.replace(/\d{1,3}(?=(\d{3})+$)/g, '$&,') + ($2 ? $2.replace(/\d{3}/g, '$&,').replace(/,$/, '') : '')
})
},
bankCard: function(bankCard) {
return bankCard.replace(/.{4}/g, '$& ');
},
mobilePhone: function(mobilePhone, separator) {
separator = separator || " ";
return mobilePhone.replace(/\d{3,4}(?=(\d{4})+$)/g, "$&" + separator);
}
};
if (typeof module !== 'undefined' && module && typeof module.exports !== 'undefined') {
module.exports = regularReplace;
} else {
this.regularReplace = regularReplace;
} |
// This test shows: ReactElement vs ReactComponent vs ReactClass vs React.Component
// For more information see: https://github.com/DJCordhose/react-component-test/blob/master/README.md
import jsdom from 'mocha-jsdom';
import ReactTestUtils from 'react-addons-test-utils';
import unexpected from 'unexpected';
const expect = unexpected.clone();
import React from 'react';
import ReactDOM from 'react-dom';
class MyClassComponentIntrospection extends React.Component {
constructor(props) {
super(props);
MyClassComponentIntrospection.constructorCalled = true;
}
render() {
MyClassComponentIntrospection.renderCalled = true;
return <div>hello</div>;
}
}
MyClassComponentIntrospection.constructorCalled = false;
MyClassComponentIntrospection.renderCalled = false;
class MyClassComponent extends React.Component {
render() {
return <div>hello</div>;
}
}
function MyFunctionalComponent() {
return <div>hello</div>;
}
const MyES5Component = React.createClass({
render() {
return <div>Hello ES5</div>;
}
});
describe('React', () => {
jsdom();
describe('component', () => {
beforeEach(() => {
MyClassComponentIntrospection.constructorCalled = false;
MyClassComponentIntrospection.renderCalled = false;
});
it('does not call the constructor on createElement', () => {
React.createElement(MyClassComponentIntrospection);
expect(MyClassComponentIntrospection.constructorCalled, 'to be false');
expect(MyClassComponentIntrospection.renderCalled, 'to be false');
});
it('calls the constructor after render', () => {
const container = document.createElement('div');
const element = React.createElement(MyClassComponentIntrospection);
ReactDOM.render(element, container);
expect(MyClassComponentIntrospection.constructorCalled, 'to be true');
expect(MyClassComponentIntrospection.renderCalled, 'to be true');
});
});
describe('render', () => {
let component;
describe('for an ES6 component', () => {
beforeEach(() => {
const container = document.createElement('div');
component = ReactDOM.render(<MyClassComponent />, container);
});
it('returns an instance of React.Component', () => {
expect(component instanceof React.Component, 'to be true');
});
it('has a prototype of the original component prototype', () => {
expect(component.__proto__, 'to be', MyClassComponent.prototype);
});
it('has a grand-parent prototype of the React.Component prototype', () => {
expect(component.__proto__.__proto__, 'to be', React.Component.prototype);
});
it('returns an instance of MyClassComponent', () => {
expect(component instanceof MyClassComponent, 'to be true');
});
it('does not return the component itself', () => {
expect(component, 'not to be', MyClassComponent);
});
});
describe('for an ES5 component', () => {
beforeEach(() => {
const container = document.createElement('div');
component = ReactDOM.render(<MyES5Component />, container);
});
it('does not return an instance of React.Component', () => {
expect(component instanceof React.Component, 'to be false');
});
it('protoype shares methods with React.Component', () => {
// but rather something really weird:
expect(React.Component.prototype, 'not to be', component.__proto__.__proto__);
expect(React.Component.prototype.setState, 'to be', component.__proto__.__proto__.setState);
expect(React.Component.prototype.forceUpdate, 'to be', component.__proto__.__proto__.forceUpdate);
});
it('returns an instance of MyClassComponent', () => {
expect(component instanceof MyES5Component, 'to be true');
});
it('does not return the component itself', () => {
expect(component, 'not to be', MyES5Component);
});
});
describe('for a functional component', () => {
beforeEach(() => {
const container = document.createElement('div');
component = ReactDOM.render(<MyFunctionalComponent />, container);
});
it('returns null', () => {
expect(component, 'to be null');
});
});
});
describe('createElement', () => {
let element;
describe('for an ES6 component', () => {
beforeEach(() => {
element = <MyClassComponent />;
});
it('is an object', () => {
expect(element, 'to be an object');
});
it('has props', () => {
expect(element.props, 'to be an object');
});
it('has a type of the MyClassComponent function', () => {
expect(element.type, 'to be', MyClassComponent);
});
});
describe('for an ES5 component', () => {
beforeEach(() => {
element = <MyES5Component />;
});
it('is an object', () => {
expect(element, 'to be an object');
});
it('has props', () => {
expect(element.props, 'to be an object');
});
it('has a type of the MyES5Component function', () => {
expect(element.type, 'to be', MyES5Component);
});
});
describe('for an functional component', () => {
beforeEach(() => {
element = <MyFunctionalComponent />;
});
it('is an object', () => {
expect(element, 'to be an object');
});
it('has props', () => {
expect(element.props, 'to be an object');
});
it('has a type of the MyFunctionalComponent function', () => {
expect(element.type, 'to be', MyFunctionalComponent);
});
});
});
describe('Shallow Renderer', () => {
let element;
describe('for an ES6 component', () => {
beforeEach(() => {
const renderer = ReactTestUtils.createRenderer();
renderer.render(<MyClassComponent />);
element = renderer.getRenderOutput();
});
it('returns an object', () => {
expect(element, 'to be an object');
});
it('returns a $$typeof symbol', () => {
expect(typeof element.$$typeof, 'to be', 'symbol');
});
it('returns a symbol react.element', () => {
const symbol = Symbol.for('react.element');
expect(element.$$typeof, 'to be', symbol);
});
it('returns the same object as createElement(div)', () => {
expect(element, 'to equal', React.createElement('div', {}, 'hello'));
});
});
});
});
|
/**********************************************************************
File : wr3d-canvas.js
Project : N Simulator Library
Purpose : Source file for a WR3D canvas component.
Revisions: Original definition by Lawrence Gunn.
2014/09/27
Copyright (c) 2014 by Lawrence Gunn
All Rights Reserved.
*/
'use strict';
angular.module('wr3dApp').directive('wr3dCanvas', [function() {
return {
restrict: 'E',
controller: ['ComponentExtensions', '$scope', '$element', '$attrs', '$timeout', function (ComponentExtensions, $scope, $element, $attrs, $timeout) {
ComponentExtensions.initialize(this, 'wr3dCanvas', $scope, $element, $attrs);
$scope.notifyHost = function() {
$timeout(function() {
$scope.$emit('wr3d-canvas:canvas-ready', $scope.canvas);
}, 1);
};
}],
link: function($scope, $element, $attrs, $timeout) {
var w = $element.width();
var h = $element.height();
if(!w) { w = 600; }
if(!h) { h = 400; }
$scope.canvas = $element.append('<canvas width="'+w+'" height="'+h+'"></canvas>').find('canvas');
$scope.notifyHost();
}
};
}]);
|
/* global moment */
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import $ from 'jquery';
import { A } from "@ember/array";
import EmberObject from '@ember/object';
moduleForComponent('elessar-range', 'Integration | Component | elessar range', {
integration: true,
});
test('it renders with values', function(assert) {
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
assert.expect(3);
this.set('values', [[20, 40], [75, 85]]);
this.render(hbs`{{elessar-range values=values}}`);
assert.equal(this.$('.elessar-range').length, 2);
this.set('values', [[20, 40], [55, 65], [75, 85]]);
assert.equal(this.$('.elessar-range').length, 3);
assert.equal($(this.$('.elessar-range')[0]).find('.elessar-barlabel').text(), '20 - 40');
});
test('it renders with model', function(assert) {
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
assert.expect(1);
let model = A([
EmberObject.create({ id: 1, range: [10, 30] }),
EmberObject.create({ id: 2, range: [50, 70] }),
]);
this.set('model', model);
this.render(hbs`{{elessar-range values=model bindModel=true}}`);
assert.equal(this.$('.elessar-range').length, 2);
// Still looking for a good solution
// model.pushObject(Ember.Object.create({ id: 3, range: [80, 90] }));
// this.set('model', model);
// assert.equal(this.$('.elessar-range').length, 3);
});
test('it renders with moment.js', function(assert) {
assert.expect(2);
this.set('minCtrl', moment().startOf('day').format('LLLL'));
this.set('maxCtrl', moment().endOf('day').format('LLLL'));
this.set('snap', 1000 * 60 * 15);
this.set('minSize', 1000 * 60 * 60);
let timeValues = [
[
moment().startOf('day').add(6, 'hours').format('LLLL'),
moment().startOf('day').add(13, 'hours').format('LLLL'),
],
[
moment().startOf('day').add(15.5, 'hours').format('LLLL'),
moment().startOf('day').add(19.5, 'hours').format('LLLL'),
],
];
this.set('timeValues', timeValues);
this.set('valueParse', function(date) {
return moment(date).valueOf();
});
this.set('valueFormat', function(ts) {
return moment(ts).format('LLLL');
});
this.set('label', function(a) {
return moment(a[1]).from(a[0], true);
});
this.render(hbs`{{elessar-range
values=timeValues
snap=1
rangeClass="dummy-range-time"
barClass="dummy-bar"
valueParse=valueParse
valueFormat=valueFormat
label=label
snap=snap
minSize=minSize
min=minCtrl
max=maxCtrl
}}`);
assert.equal(this.$('.elessar-range').length, 2);
assert.equal(this.$('.dummy-range-time').length, 2);
});
|
import * as objectInspections from './objectInspections';
const RowSeparator = '\n';
const ColumnsSeparator = '\t';
var isString = (value) => {
return (typeof value === 'string' || value instanceof String);
};
var splitWithoutEmptyEntries = (array, separator) => {
return array.split(separator).filter(v => v);
};
var tryDeduceSeparator = (value) => {
var result = [];
let matches = value.match(/(\s+)/g);
if(matches === null) {
throw `Missing space in line '${value}'.`
}
matches.forEach(match => {
var isTab = match.indexOf('\t') !== -1;
result.push({
priority: isTab ? match.length * 4 : match.length,
value: match
});
});
result.sort((a, b) => a.priority < b.priority);
if (result.length === 0) {
throw `Can not deduce separator for line '${value}'`;
}
var separator = result[0];
var numberOfSeparators = result.filter(i => i.value == separator.value ).length;
if(numberOfSeparators > 1) {
throw `Characters '${separator.value}' was elected as separator but it contains ${numberOfSeparators} times in line '${value}'.
Allowed is only one occurrence of selected separator`;
}
return separator.value;
};
var normalizeSpace = (value) => {
return value.replace(/\s/g, ' ');
};
export function toTable(text, columnNames = {first: "left", second: "right"}) {
if (objectInspections.isArray(text)) {
return text;
}
var result = [];
for (let row of splitWithoutEmptyEntries(text, RowSeparator)) {
var rowValue = row.trim();
if (rowValue === '') {
continue;
}
var separator = tryDeduceSeparator(rowValue);
var [left, right] = splitWithoutEmptyEntries(row, separator);
left = normalizeSpace(left);
right = normalizeSpace(right);
result.push({
[columnNames.first]: left,
[columnNames.second]: right
});
}
return result;
}
export function toText(rows, columnNames = {first: "left", second: "right"}) {
if (isString(rows)) {
return rows;
}
var result = '';
for (let row of rows) {
result += row[columnNames.first] + ColumnsSeparator + row[columnNames.second] + RowSeparator;
}
return result;
} |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class TextureCache {
add(t) {
this.entity.set(t.name, t);
}
get(k) {
return this.entity.get(k);
}
constructor() {
this.entity = new Map();
}
}
exports.TextureCache = TextureCache;
|
var Firebase = require("firebase");
var _ = require("lodash");
var User = function(snap) {
var user = snap.val();
this.rootRef = snap.ref().root();
if(user) {
this.id = snap.key();
this.name = user.name;
this.email = user.email;
this.data - snap.val();
}
}
module.exports = function(rootRef) {
this.find = function(uid) {
uid = uid || 'google:100424084914655768945';
var userRef = rootRef.child('users').child(uid);
userRef.once('value', function(snap) {
cb(new User(snap));
});
};
} |
export default function LowPassFilter (
{
frequency = 1,
ramp = 0,
resonance = 0
} = {}
) {
return {
frequency, // Low-pass filter cutoff
ramp, // Low-pass filter cutoff sweep (SIGNED)
resonance // Low-pass filter resonance
};
} |
var perfmon = require('../perfmon');
var counters = [
'\\processor(_total)\\% processor time',
'\\Memory\\Available bytes'
];
perfmon({counters:counters, sampleInterval:5, sampleCount:5}, function(err, data) {
var date = new Date(data.time);
// display in format HH:MM:SS
data.time = twoDigits(date.getHours())
+ ':' + twoDigits(date.getMinutes())
+ ':' + twoDigits(date.getSeconds());
console.log(data);
});
function twoDigits(value) {
if(value < 10) {
return '0' + value;
}
return value;
} |
/*global rg2:false */
/*global rg2Config:false */
/*global console */
(function () {
function reportJSONFail(errorText) {
$("#rg2-load-progress").hide();
$('body').css('cursor', 'auto');
rg2.utils.showWarningDialog('Configuration error', errorText);
}
function getEvents() {
var eventID;
$.getJSON(rg2Config.json_url, {
type : "events",
cache : false
}).done(function (json) {
console.log("Events: " + json.data.events.length);
rg2.events.deleteAllEvents();
$.each(json.data.events, function () {
rg2.events.addEvent(new rg2.Event(this));
});
rg2.ui.createEventMenu();
// load requested event if set
// input is kartat ID so need to find internal ID first
if (rg2.requestedHash.getID()) {
eventID = rg2.events.getEventIDForKartatID(rg2.requestedHash.getID());
if (eventID !== undefined) {
rg2.loadEvent(eventID);
}
}
if (rg2.config.managing) {
rg2.manager.eventListLoaded();
}
}).fail(function (jqxhr, textStatus, error) {
/*jslint unparam:true*/
reportJSONFail("Events request failed: " + error);
});
}
function getGPSTracks() {
$("#rg2-load-progress-label").text(rg2.t("Loading routes"));
$.getJSON(rg2Config.json_url, {
id : rg2.events.getKartatEventID(),
type : "tracks",
cache : false
}).done(function (json) {
var active, i, event, routes, crs;
$("#rg2-load-progress-label").text(rg2.t("Saving routes"));
console.log("Tracks: " + json.data.routes.length);
// TODO remove temporary (?) fix to get round RG1 events with no courses defined: see #179
if (rg2.courses.getNumberOfCourses() > 0) {
rg2.results.addTracks(json.data.routes);
}
rg2.ui.createCourseMenu();
rg2.ui.createResultMenu();
rg2.animation.updateAnimationDetails();
$('body').css('cursor', 'auto');
if (rg2.config.managing) {
rg2.manager.eventFinishedLoading();
} else {
$("#rg2-info-panel").tabs("enable", rg2.config.TAB_COURSES);
$("#rg2-info-panel").tabs("enable", rg2.config.TAB_RESULTS);
$("#rg2-info-panel").tabs("enable", rg2.config.TAB_DRAW);
// open courses tab for new event: else stay on draw tab
active = $("#rg2-info-panel").tabs("option", "active");
// don't change tab if we have come from DRAW since it means
// we have just reloaded following a save
if (active !== rg2.config.TAB_DRAW) {
$("#rg2-info-panel").tabs("option", "active", rg2.requestedHash.getTab());
}
$("#rg2-info-panel").tabs("refresh");
$("#btn-show-splits").show();
if ((rg2Config.enable_splitsbrowser) && (rg2.events.hasResults())) {
$("#rg2-splitsbrowser").off().click(function () {
window.open(rg2Config.json_url + "?type=splitsbrowser&id=" + rg2.events.getKartatEventID());
}).show();
} else {
$("#rg2-splitsbrowser").off().hide();
}
// set up screen as requested in hash
event = $.Event('click');
event.target = {};
event.target.checked = true;
routes = rg2.requestedHash.getRoutes();
for (i = 0; i < routes.length; i += 1) {
event.target.id = routes[i];
$(".showtrack").filter("#" + routes[i]).trigger(event).prop('checked', true);
}
crs = rg2.requestedHash.getCourses();
for (i = 0; i < crs.length; i += 1) {
event.target.id = crs[i];
$(".showcourse").filter("#" + crs[i]).trigger(event).prop('checked', true);
}
}
$("#rg2-load-progress-label").text("");
$("#rg2-load-progress").hide();
rg2.redraw(false);
}).fail(function (jqxhr, textStatus, error) {
/*jslint unparam:true*/
reportJSONFail("Routes request failed for event " + rg2.events.getKartatEventID() + ": " + error);
});
}
function getResults() {
var isScoreEvent;
$("#rg2-load-progress-label").text(rg2.t("Loading results"));
$.getJSON(rg2Config.json_url, {
id : rg2.events.getKartatEventID(),
type : "results",
cache : false
}).done(function (json) {
console.log("Results: " + json.data.results.length);
$("#rg2-load-progress-label").text(rg2.t("Saving results"));
isScoreEvent = rg2.events.isScoreEvent();
// TODO remove temporary (?) fix to get round RG1 events with no courses defined: see #179
if (rg2.courses.getNumberOfCourses() > 0) {
rg2.results.addResults(json.data.results, isScoreEvent);
}
rg2.courses.setResultsCount();
if (isScoreEvent) {
rg2.controls.deleteAllControls();
rg2.results.generateScoreCourses();
rg2.courses.generateControlList(rg2.controls);
}
$("#rg2-result-list").accordion("refresh");
getGPSTracks();
}).fail(function (jqxhr, textStatus, error) {
/*jslint unparam:true*/
reportJSONFail("Results request failed for event " + rg2.events.getKartatEventID() + ": " + error);
});
}
function getCourses() {
// get courses for event
$.getJSON(rg2Config.json_url, {
id : rg2.events.getKartatEventID(),
type : "courses",
cache : false
}).done(function (json) {
$("#rg2-load-progress-label").text(rg2.t("Saving courses"));
console.log("Courses: " + json.data.courses.length);
$.each(json.data.courses, function () {
rg2.courses.addCourse(new rg2.Course(this, rg2.events.isScoreEvent()));
});
rg2.courses.updateCourseDropdown();
rg2.courses.generateControlList(rg2.controls);
$("#btn-toggle-controls").show();
$("#btn-toggle-names").show();
getResults();
}).fail(function (jqxhr, textStatus, error) {
/*jslint unparam:true*/
reportJSONFail("Courses request failed for event " + rg2.events.getKartatEventID() + ": " + error);
});
}
function getNewLanguage(lang) {
$.getJSON(rg2Config.json_url, {
id : lang,
type : 'lang',
cache : false
}).done(function (json) {
rg2.ui.setNewLanguage(json.data.dict);
}).fail(function (jqxhr, textStatus, error) {
/*jslint unparam:true*/
reportJSONFail("Language request failed: " + error);
});
}
rg2.getEvents = getEvents;
rg2.getCourses = getCourses;
rg2.getResults = getResults;
rg2.getGPSTracks = getGPSTracks;
rg2.getNewLanguage = getNewLanguage;
}());
|
var Agenda = require("Agenda");
var agenda = new Agenda({db: { address: 'localhost:27017/agenda-example'}});
var time1 ='at 10:11:14pm';
agenda.define('greet the world', function(job, done) {
console.log(job.attrs.data.time, 'hello world!');
done();
});
agenda.on('start', function(job) {
console.log("Job : %s starting", job.attrs.name);
});
agenda.on('complete:greet the world', function(job) {
console.log("Job : %s finished", job.attrs.name);
});
agenda.schedule('at 08:42:36am', 'greet the world', {time: new Date()});
agenda.start();
console.log('Wait...');
console.log(new Date()); |
const TODO_LS_PREFIX = "todos-ConnectJS.";
class Todo extends Model {
constructor(islots) {
ast( islots.title, 'new Todo: title property is required');
let netSlots = Object.assign(
{dbKey: TODO_LS_PREFIX + uuidv4()
, created: Date.now()}
, islots
// CELLSGLUE "box" certain islots in input Cells to support dataflow
, { title: cI( islots.title )
, completed: cI( islots.completed || null)
, deleted: islots.deleted || cI( null)});
super(null, null, netSlots, false); // CELLSGLUE: Model constructor does a *lot*
if ( !islots.dbKey) { // ie, if not already stored, ie if being instantiated from DB
this.store();
}
}
toJSON () {
return { dbKey: this.dbKey
, title: this.title
, created: this.created
, completed: this.completed
, deleted: this.deleted }
}
static fromJSON ( json) {
return new Todo( json )
}
static load (dbKey) {
return new Todo( localStorage.getObject( dbKey))
}
// CELLSGLUE no matter what changed, re-write the whole thing...
static obsTodoChange ( slot, todo, newv, priorv, c) {
todo.store(); // FLOW OUTSIDE MODEL BY OBSERVER
}
slotObserverResolve(slot) {
// ignore which slot chnaged since localStorage does not support that granularity
return Todo.obsTodoChange }
static loadAllItems() {
// CELLSGLUE load all items into container model so various widgets can watch via Cell dependencies
return mkm( null, 'Todo'
, { itemsRaw: cI( Object.keys(localStorage)
.filter( k => k.startsWith(TODO_LS_PREFIX))
.map( Todo.load)
.sort( (a,b) => a.created < b.created ? -1 : 1) || [])
, items: cF( c => c.md.itemsRaw.filter( td => !td.deleted))}) // IN-FLOW
}
store () {
localStorage.setObject( this.dbKey, this.toJSON());
}
} |
// reused function for all Internal Server Errors
var internalServerError = generateErrorResponses(
500
);
|
/**
* This is the transient application state. By using a `Backbone.Model` this also makes it an
* instance of `Backbone.Events` allowing subscription to state changes. An instance of AppState created after
* definition allows any other subsequent code to access this instance.
*/
define([
'backbone'
], function(Backbone)
{
'use strict';
var AppState = Backbone.Model.extend(
{
/**
* Default value for AppState which is set in `Backbone.Model` when initializing an instance of `AppState`.
*/
defaults: { filter: 'all' }
});
/**
* Returns an instance of AppState shared between router, views and main app.
*/
return new AppState();
}); |
(function() {
var MemoryWidget = function(widget) {
BaseWidget.call(this, widget);
};
MemoryWidget.prototype = Object.create(BaseWidget.prototype);
MemoryWidget.prototype.getTitle = function() {
return "Used Memory";
};
MemoryWidget.prototype.getWidthClass = function() {
return "one";
};
MemoryWidget.prototype.initialize = function(history) {
this.addData({
memory: history.memory[history.memory.length - 1]
});
};
MemoryWidget.prototype.addData = function(data) {
if (!data.memory) {
return;
}
var usedMemMB =
Math.floor((data.memory.total - data.memory.free) / 1000000);
var totalMemMB = Math.floor(data.memory.total / 1000000);
this.div.innerText =
"Used Memory: " + usedMemMB + "MB / " + totalMemMB + "MB";
};
window.MemoryWidget = MemoryWidget;
})();
|
/*!
* connect-mongo
* Copyright(c) 2011 Casey Banner <kcbanner@gmail.com>
* MIT Licensed
*/
/**
* Module dependencies
*/
var Store = require('connect').session.Store;
var mongo = require('mongodb');
var url = require('url');
/**
* Default options
*/
var defaultOptions = {host: '127.0.0.1',
port: 27017,
collection: 'sessions',
auto_reconnect: false,
clear_interval: -1};
/**
* Initialize MongoStore with the given `options`.
* Calls `callback` when db connection is ready (mainly for testing purposes).
*
* @param {Object} options
* @param {Function} callback
* @api public
*/
var MongoStore = module.exports = function MongoStore(options, callback) {
options = options || {};
Store.call(this, options);
if(options.url) {
var db_url = url.parse(options.url);
if (db_url.port) {
options.port = parseInt(db_url.port);
}
if (db_url.pathname != undefined) {
var pathname = db_url.pathname.split('/');
if (pathname.length >= 2) {
options.db = pathname[1];
}
if (pathname.length >= 3) {
options.collection = pathname[2];
}
}
if (db_url.hostname != undefined) {
options.host = db_url.hostname;
}
if (db_url.auth != undefined) {
var auth = db_url.auth.split(':');
if (auth.length >= 1) {
options.username = auth[0];
}
if (auth.length >= 2) {
options.password = auth[1];
}
}
}
if(!options.db) {
throw new Error('Required MongoStore option `db` missing');
}
this.db = new mongo.Db(options.db,
new mongo.Server(options.host || defaultOptions.host,
options.port || defaultOptions.port,
{
auto_reconnect: options.auto_reconnect ||
defaultOptions.auto_reconnect
}));
this.db_collection_name = options.collection || defaultOptions.collection;
var self = this;
this._get_collection = function(callback) {
if (self.collection) {
callback && callback(self.collection);
} else {
self.db.collection(self.db_collection_name, function(err, collection) {
if (err) {
throw new Error('Error getting collection: ' + self.db_collection_name);
} else {
self.collection = collection;
var clear_interval = options.clear_interval || defaultOptions.clear_interval;
if (clear_interval > 0) {
self.clear_interval = setInterval(function() {
self.collection.remove({expires: {$lte: new Date()}});
}, clear_interval * 1000, self);
}
callback && callback(self.collection);
}
});
}
};
this.db.open(function(err, db) {
if (err) {
throw new Error('Error connecting to database');
}
if (options.username && options.password) {
db.authenticate(options.username, options.password, function () {
self._get_collection(callback);
});
} else {
self._get_collection(callback);
}
});
};
/**
* Inherit from `Store`.
*/
MongoStore.prototype.__proto__ = Store.prototype;
/**
* Attempt to fetch session by the given `sid`.
*
* @param {String} sid
* @param {Function} fn
* @api public
*/
MongoStore.prototype.get = function(sid, callback) {
var self = this;
this._get_collection(function(collection) {
collection.findOne({_id: sid}, function(err, session) {
try {
if (err) {
callback(err, null);
} else {
if (session) {
if (!session.expires || new Date < session.expires) {
callback(null, JSON.parse(session.session));
} else {
self.destroy(sid, callback);
}
} else {
callback();
}
}
} catch (err) {
callback(err);
}
});
});
};
/**
* Commit the given `sess` object associated with the given `sid`.
*
* @param {String} sid
* @param {Session} sess
* @param {Function} fn
* @api public
*/
MongoStore.prototype.set = function(sid, session, callback) {
try {
var s = {_id: sid, session: JSON.stringify(session)};
if (session && session.cookie && session.cookie._expires) {
s.expires = new Date(session.cookie._expires);
}
this._get_collection(function(collection) {
collection.update({_id: sid}, s, {upsert: true, safe: true}, function(err, data) {
if (err) {
callback && callback(err);
} else {
callback && callback(null);
}
});
});
} catch (err) {
callback && callback(err);
}
};
/**
* Destroy the session associated with the given `sid`.
*
* @param {String} sid
* @api public
*/
MongoStore.prototype.destroy = function(sid, callback) {
this._get_collection(function(collection) {
collection.remove({_id: sid}, function() {
callback && callback();
});
});
};
/**
* Fetch number of sessions.
*
* @param {Function} fn
* @api public
*/
MongoStore.prototype.length = function(callback) {
this._get_collection(function(collection) {
collection.count({}, function(err, count) {
if (err) {
callback && callback(err);
} else {
callback && callback(null, count);
}
});
});
};
/**
* Clear all sessions.
*
* @param {Function} fn
* @api public
*/
MongoStore.prototype.clear = function(callback) {
this._get_collection(function(collection) {
collection.drop(function() {
callback && callback();
});
});
};
|
"use strict";
const path = require('path');
function isEmptyDir(grunt, dirPath) {
if( grunt.file.isDir(dirPath) ){
let files = grunt.file.expand( { 'cwd' : dirPath }, '*');
return files.length === 0;
}
return false;
}
function normalizeName(name) {
return name.split(' ').join('-').toLowerCase();
}
exports.initIntegration = function(grunt,name) {
// validate arguments ////////////////////////////////////////////////////////
if( ! name ) {
grunt.log.error('missing name');
return false;
}
name = normalizeName(name);
//grunt.log.ok('')
// path to the folder where templates are stored
grunt.config.requires('init-integration.templatePath');
let templatePath = grunt.config('init-integration.templatePath');
if( ! grunt.file.isDir(templatePath) ) {
grunt.log.error('Template Path not found : '+templatePath);
return false;
}
// name of the template to use : exists as a sub folder of 'templatePath'
grunt.config.requires('init-integration.templateName');
let templateName = grunt.config('init-integration.templateName');
if( ! grunt.file.isDir(templateName) ) {
grunt.log.error('Template name missing : '+templateName);
return false;
}
// path to the folder where the new int folder will be created under the name 'name'
grunt.config.requires('init-integration.targetPath');
let targetPath = grunt.config('init-integration.targetPath');
if( ! grunt.file.isDir(targetPath) ) {
grunt.log.error('Target Path not found : '+targetPath);
return false;
}
let templateFolder = path.posix.join(templatePath, templateName);
if( ! grunt.file.exists(templateFolder) ) {
grunt.log.error('template not found : '+templateName);
return false;
}
let projectPath = path.posix.join(targetPath,name);
if( grunt.file.exists(projectPath) ) {
grunt.log.error('path already exists : '+projectPath);
return false;
} else {
grunt.verbose.ok('creating folder '+projectPath);
grunt.file.mkdir(projectPath);
}
////////////////////////////////////////////////////////////////////////////
grunt.file.expand(`${templateFolder}/**`)
.forEach( srcFile => {
let destFile =srcFile.replace(templateFolder, projectPath);
if( isEmptyDir(grunt, srcFile))
{
grunt.verbose.ok("creating empty folder : "+destFile);
grunt.file.mkdir(destFile);
grunt.file.write(path.posix.join(destFile,'.gitignore'),'');
}
else if( grunt.file.isFile(srcFile))
{
grunt.verbose.ok("copying file : "+srcFile);
grunt.file.copy(srcFile, destFile);
}
});
grunt.log.ok('new folder created ');
};
|
;(function (window, global_mod, global_expts, undefined) {
var xmod = {}
//+ getFreeGlobal :: a -> b
, getFreeGlobal = function(_window) {
return (typeof global == "object") ? global : window;
// previous implementation - not working on node for me.
var env_global = _window
, free_global = typeof env_global == 'object' && env_global;
if (free_global.global === free_global) {
return free_global;
}
return _window;
}
//TODO omit noConflict and getFreeGlobal from exposure to env
//+ exposeFunctionsToEnvironment :: a -> IO
, exposeFunctionsToEnvironment = function(env, mod) {
var f, win;
win = getFreeGlobal(window);
for (f in mod) {
if (f !== 'expose' && mod.hasOwnProperty(f)) {
win[f] = mod[f];
}
}
}
//+ noConflict :: String -> b -> f
, noConflict = function(conflicting_lib, _window) {
return function() {
_window[conflicting_lib] = _window[conflicting_lib]
return this;
};
}
//+ exportModule :: String -> Module -> IO
, exportModule = function(name, my_module, other_mod, other_exports) {
var define_exists = typeof define == 'function'
, has_amd_property = define_exists ? typeof define.amd == 'object' && define.amd : false
, using_AMD_loader = define_exists && has_amd_property
, global_exports = typeof other_exports == 'object' && other_exports
, global_module = typeof other_mod == 'object' && other_mod
, using_nodejs_or_ringojs = global_module ? global_module.exports == global_exports : false
;
if (using_AMD_loader) {
// Expose module to the global object even when an AMD loader
// is present, in case this module was injected by a third-party
// script and not intended to be loaded as module. The global
// assignment can be reverted in the module via its
// "noConflict()" method.
window[name] = my_module;
// Define an anonymous AMD module
define(function () { return my_module; });
}
// Check for "exports" after "define", in case a build optimizer adds
// an "exports" object.
else if (global_exports) {
if (using_nodejs_or_ringojs) {
global_module.exports = my_module;
}
else { // Narwhal or RingoJS v0.7.0-
global_exports[name] = my_module;
}
}
else { // browser or Rhino
window[name] = my_module;
}
}
;
xmod.getFreeGlobal = getFreeGlobal;
xmod.expose = exposeFunctionsToEnvironment;
xmod.noConflict = noConflict;
xmod.exportModule = exportModule;
exportModule('xmod', xmod, global_mod, global_expts);
}(this, (typeof module == 'object' && module), (typeof exports == 'object' && exports)));
|
import React, { Component } from 'react';
import AceEditor from 'react-ace';
import {globalState} from '../state';
import 'brace/mode/yaml'
import 'brace/theme/monokai'
export default class GuildConfigEdit extends Component {
constructor() {
super();
this.messageTimer = null;
this.initialConfig = null;
this.state = {
message: null,
guild: null,
contents: null,
hasUnsavedChanges: false,
}
}
componentWillMount() {
globalState.getGuild(this.props.params.gid).then((guild) => {
globalState.currentGuild = guild;
guild.getConfig(true).then((config) => {
this.initialConfig = config.contents;
this.setState({
guild: guild,
contents: config.contents,
});
});
}).catch((err) => {
console.error('Failed to find guild for config edit', this.props.params.gid);
});
}
componentWillUnmount() {
globalState.currentGuild = null;
}
onEditorChange(newValue) {
let newState = {contents: newValue, hasUnsavedChanges: false};
if (this.initialConfig != newValue) {
newState.hasUnsavedChanges = true;
}
this.setState(newState);
}
onSave() {
this.state.guild.putConfig(this.state.contents).then(() => {
this.initialConfig = this.state.contents;
this.setState({
hasUnsavedChanges: false,
});
this.renderMessage('success', 'Saved Configuration!');
}).catch((err) => {
this.renderMessage('danger', `Failed to save configuration: ${err}`);
});
}
renderMessage(type, contents) {
this.setState({
message: {
type: type,
contents: contents,
}
})
if (this.messageTimer) clearTimeout(this.messageTimer);
this.messageTimer = setTimeout(() => {
this.setState({
message: null,
});
this.messageTimer = null;
}, 5000);
}
render() {
return (<div>
{this.state.message && <div className={"alert alert-" + this.state.message.type}>{this.state.message.contents}</div>}
<div className="row">
<div className="col-md-12">
<div className="panel panel-default">
<div className="panel-heading">
Configuration Editor
</div>
<div className="panel-body">
<AceEditor
mode="yaml"
theme="monokai"
width="100%"
value={this.state.contents == null ? '' : this.state.contents}
onChange={(newValue) => this.onEditorChange(newValue)}
/>
</div>
<div className="panel-footer">
{
this.state.guild && this.state.guild.role != 'viewer' &&
<button onClick={() => this.onSave()} type="button" className="btn btn-success btn-circle btn-lg">
<i className="fa fa-check"></i>
</button>
}
{ this.state.hasUnsavedChanges && <i style={{paddingLeft: '10px'}}>Unsaved Changes!</i>}
</div>
</div>
</div>
</div>
</div>);
}
}
|
var searchData=
[
['sel_5fchange_5fin_5find',['sel_change_in_ind',['../amak_8tpl.html#a31bc71d99a3f1d839ef9e8a619efc5f1',1,'amak.tpl']]],
['sel_5fdinf_5fin_5ffsh',['sel_dinf_in_fsh',['../amak_8tpl.html#a133d508fb8bec692ef00005a83852d24',1,'amak.tpl']]],
['sel_5fdinf_5fin_5findv',['sel_dinf_in_indv',['../amak_8tpl.html#a29441edac8b92b2b9640725e2a7ac5d2',1,'amak.tpl']]],
['sel_5fdslp_5fin_5ffsh',['sel_dslp_in_fsh',['../amak_8tpl.html#a30fb6eb99437cf9263f7d1139a3ad75f',1,'amak.tpl']]],
['sel_5ffsh_5ftmp',['sel_fsh_tmp',['../amak_8tpl.html#a89fbcef20e2fe383771543752cb2f727',1,'amak.tpl']]],
['sel_5find_5ftmp',['sel_ind_tmp',['../amak_8tpl.html#a018f4e19901813a40502904d196f24ee',1,'amak.tpl']]],
['sel_5finf_5fin_5find',['sel_inf_in_ind',['../amak_8tpl.html#a7a7e16da07374b6540dcea6e736417fb',1,'amak.tpl']]],
['sel_5finf_5fin_5findv',['sel_inf_in_indv',['../amak_8tpl.html#ac0f6cbcc4acb57bf37b7707ca672bfd7',1,'amak.tpl']]],
['sel_5fmap',['sel_map',['../amak_8tpl.html#a43bb1e213038ba3d83c2d14e1e88cb53',1,'amak.tpl']]],
['sel_5fsigma_5ffsh',['sel_sigma_fsh',['../amak_8tpl.html#a10ebe622febf14fd15b27bbe8caf64d1',1,'amak.tpl']]],
['sel_5fsigma_5find',['sel_sigma_ind',['../amak_8tpl.html#a654529b996660a4d670f7f28fbad5309',1,'amak.tpl']]],
['sel_5fslp_5fin_5find',['sel_slp_in_ind',['../amak_8tpl.html#a2a0a088f1dde84e619b3f928e990fcd3',1,'amak.tpl']]],
['seldecage',['seldecage',['../amak_8tpl.html#a22c9a73ab3cbc7da50fc49d044876453',1,'amak.tpl']]],
['sigma_5frw_5fm',['sigma_rw_M',['../amak_8tpl.html#abf484b91cc7848afa3a5631af81dfea0',1,'amak.tpl']]],
['sigma_5frw_5fq',['sigma_rw_q',['../amak_8tpl.html#a3d12123942f5255eb33a158b7b2763fd',1,'amak.tpl']]],
['styr',['styr',['../amak_8tpl.html#a582acf080b4ba12b2645bd9624b7c64e',1,'amak.tpl']]]
];
|
app.factory('MapApi', ['$http', function($http) {
var _url = function() {
return 'http://107.170.68.187:5000';
};
return {
getRegions: function() {
var url = _url() +'/regions';
return $http.get(url);
},
getMap: function(id){
var url = _url() + '/map/' + id;
return $http.get(url);
}
};
}]);
|
'use strict';
const expansions = require('npm-expansions');
module.exports = () => expansions[Math.floor(Math.random() * expansions.length)];
|
/** Return true if tuning contains only letters from A to G
* @param {String} tuning | Required | The instrument tuning
* @return {Boolean}
*/
export function isValid (tuning) {
let pattern = new RegExp("^[#a-g]+$", "i");
if (pattern.test(tuning)) {
return true;
} else {
return false;
}
}
/** Split tuning into notes
* @param {String} tuning | Required | The tuning of the instrument (e.g: "EADGBE" or "E#A#D#G#B#E#")
* @return {Array} | Containing each note
*/
export function parse(tuning) {
let tuningArray = [],
noSharps = new RegExp("^[a-g]+$", "i"),
containSharps = new RegExp("^[#a-g]+$", "i");
if (noSharps.test(tuning)) {
return tuning.toUpperCase().split("");
} else if (containSharps.test(tuning)) {
tuning = tuning.toUpperCase();
for (let i = 0; i < tuning.length; i++) {
if (tuning.charAt(i) !== "#") {
if (tuning.charAt(i+1) !== "#") {
tuningArray.push(tuning.slice(i, i+1));
} else {
tuningArray.push(tuning.slice(i, i+2));
i++;
}
}
}
return tuningArray;
} else {
return false;
}
}
export const GET = {
guitar: {
standard: ["E", "A", "D", "G", "B", "E"],
halfstepdown: ["D#", "G#", "C#", "F#", "A#", "D#"],
drop_d: ["D", "A", "D", "G", "B", "E"],
d_modal: ["D", "A", "D", "G", "A", "D"],
open_g: ["G", "G", "D", "G", "B", "D"]
},
bass: {
standard: ["E", "A", "D", "G"],
drop_d: ["C", "A", "D", "G"]
},
ukulele: {
standard: ["G", "C", "E", "A"]
},
violin: {
standard: ["G", "D", "A", "E"]
}
}; |
var existingComments = [
{
"sectionId": "1",
"comments": [
{
"id": 88,
"authorAvatarUrl": "/assets/css/images/jon_snow.png",
"authorName": "Jon Sno",
"authorId": 1,
"authorUrl": "http://en.wikipedia.org/wiki/Kit_Harington",
"comment": "I'm Ned Stark's bastard. Related: I know nothing."
},
{
"id": 112,
"authorAvatarUrl": "/assets/css/images/donald_draper.png",
"authorName": "Donald Draper",
"authorId": 2,
"comment": "I need a scotch."
}
]
},
{
"sectionId": "3",
"comments": [
{
"id": 66,
"authorAvatarUrl": "/assets/css/images/clay_davis.png",
"authorName": "Senator Clay Davis",
"authorId": 3,
"comment": "These Side Comments are incredible. Sssshhhiiiiieeeee."
}
]
}
];
var currentUser = {
"id": 4,
"avatarUrl": "/assets/css/images/user.png",
"authorUrl": "http://google.com/",
"name": "You"
};
|
'use strict';
var integration = require('@astronomerio/analytics.js-integration');
/*
*Expose 'Netmining' integration.
*/
var Netmining = module.exports = integration('Netmining')
.option('src', '')
.option('aid', '')
.tag('<script type="text/javascript" async src="{{ src }}?aid={{ aid }}&siclientid=">')
/*
* Initialize Netmining
*/
Netmining.prototype.initialize = function() {
this.load(this.ready);
};
|
const Db = require('../db').Db;
const constants = require('../db').constants;
const BasicCollection = require('../lib/basic-collection');
const TypedCollection = require('../lib/typed-collection');
const schema = require('../sample-schemas/books');
const ObjectDescriptor = require('../lib/object-descriptor');
const configuration = {
mongo: {
serverUrl:"mongodb://localhost:27017/books"
}
}
var db = new Db(configuration);
beforeEach(async()=>{
await db.connect(schema);
await db.edges.clear();
await db.books.clear();
await db.authors.clear();
});
afterEach(async()=>{
db.disconnect();
});
test('db initialization and save', async ()=>{
let books = await db.books.merge({
isbn:'01',
title:'Local Host is Vicious',
published: Date.now(),
pageCount: 901
});
let authors = await db.authors.merge({
name: 'Tokugava Miusiza',
born: 0
});
let book = books[0];
book.author = authors[0];
expect(book._descriptor).toBeInstanceOf(ObjectDescriptor);
expect(book).toBeInstanceOf(db.books.schema.type);
expect(db.books.state(book).isNew).toBeTruthy();
await db.commit();
expect(db.books.state(book).isUnchanged).toBeTruthy();
book.pageCount = 100;
db.sync();
expect(db.books.state(book).isModified).toBeTruthy();
await db.commit();
//delete sequence
await db.books.remove({isbn:'01'});
expect(authors[0].books.length).toBe(0);
});
|
"use strict";
var util = require('util');
var google = require('googleapis');
var Promise = require('bluebird');
var _ = require('lodash');
var Cordova = require('node-cordova');
var Console = require("console").Console;
var logger = new Console(process.stdout, process.stderr);
module.exports = function(grunt) {
grunt.initConfig({
pkg : grunt.file.readJSON('package.json'),
play : {
beta : {
track : 'beta',
options : {
packadeName : 'dk.socialite.sclclubapp',
apkFile : './platforms/android/build/outputs/apk/android-release.apk',
googleAccountFile : 'secret.json'
}
}
},
bump : {
options : {
versionFrom : 'json',
xml : 'config.xml',
json : 'package.json'
}
},
sftp : {
all : {
files : {
"./" : "platforms/android/build/outputs/apk/android-release.apk"
},
options : {
path : '/app/',
srcBasePath : "platforms/android/build/outputs/apk/",
host : 'club.socialite.dk',
username: '<%= sshprod.user %>',
password: '<%= sshprod.password %>',
showProgress : true
}
}
},
sshexec : {
test : {
command : 'cd /test/clubdatabase && git pull',
options : {
host : 'socialite.dk',
username: '<%= sshprod.user %>',
password: '<%= sshprod.password %>'
}
},
testhard : {
command : 'cd /test/clubdatabase && git reset --hard && git pull',
options : {
host : 'socialite.dk',
username: '<%= sshprod.user %>',
password: '<%= sshprod.password %>'
}
}
},
gta : {
commit : {
command : 'commit --all -m "grunt commit for app only [skip ci]" --author="Allan Schytt <as@ascsi.dk>"',
options : {
stdout : true,
stderr : true,
}
},
push : {
command : 'push --all https://<%= git.user %>:<%= git.password %>@bitbucket.org/fountainhouse/clubdatabase.git',
options : {
stdout : false,
stderr : false,
}
}
}
});
grunt.loadNpmTasks('grunt-ssh');
grunt.loadNpmTasks('grunt-git-them-all');
grunt.registerTask('git', [ 'crypt', 'force_on', 'gta:commit', 'force_off', 'gta:push','sshexec:test' ]);
grunt.registerTask('githard', [ 'crypt', 'force_on', 'gta:commit', 'force_off', 'gta:push','sshexec:testhard' ]);
grunt.registerTask('go', [ 'bump', 'play' ]);
grunt.registerTask('deploy', ['crypt', 'sftp' ]);
grunt.registerMultiTask('build', 'custom cordova build task runner', function() {
var done = this.async();
var app = new Cordova('./').compile('android', function() {
grunt.log.ok('new android build generated ');
done();
})
});
grunt.registerTask('bump', 'custom bump task runner', function() {
var done = this.async();
var args = this.args;
if (args.length === 0)
args = [ 'sub' ];
grunt.log.verbose.ok('reading local package.json file');
grunt.file.defaultEncoding = 'utf8';
var pkg = grunt.file.readJSON('package.json');
var parts = pkg.version.split('.');
var oldVersion = "version=\"" + pkg.version + "\"";
for (var i = 0; i < parts.length; ++i) {
switch (i) {
case 0:
if (args.indexOf('major') !== -1) {
parts[i] = (Number(parts[i]) + 1).toString();
parts[1] = '0';
parts[2] = '0';
pkg.version = parts[0] + '.' + parts[1] + '.' + parts[2];
}
break;
case 1:
if (args.indexOf('minor') !== -1) {
parts[i] = (Number(parts[i]) + 1).toString();
parts[2] = '0';
pkg.version = parts[0] + '.' + parts[1] + '.' + parts[2];
}
break;
case 2:
if (args.indexOf('sub') !== -1) {
parts[i] = (Number(parts[i]) + 1).toString();
pkg.version = parts[0] + '.' + parts[1] + '.' + parts[2];
}
}
}
grunt.file.write('package.json', JSON.stringify(pkg, null, 2));
if (grunt.file.exists('config.xml')){
var regex = /(.+)version *= *\"[0-9]+\.?[0-9]+?\.?[0-9]+?\"(.+)/g
var config = grunt.file.read('config.xml');
config = config.replace(regex, "$1version=\"" + pkg.version + "\"$2");
grunt.file.write("config.xml", config);
}
grunt.log.ok('bumped to version ' + pkg.version);
done();
});
grunt.registerTask('play', 'custom play release task runner', function() {
var done = this.async();
var key = require('./secret.json');
var version = require('./package.json').version;
var editId = '' + (new Date().getTime());
var scopes = [
'https://www.googleapis.com/auth/androidpublisher'
];
// here, we'll initialize our client
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2();
var jwtClient = new google.auth.JWT(key.client_email, null, key.private_key, scopes, null);
var play = google.androidpublisher({
version : 'v2',
auth : oauth2Client,
params : {
packageName : 'dk.socialite.sclclubapp'
}
});
google.options({
auth : oauth2Client
});
var apkfile = './platforms/android/build/outputs/apk/android-release.apk';
startEdit() // "open" our edit
.then(function(data) {
var apk = require('fs').readFileSync(apkfile); // stage the upload
// (doesn't actually
// upload anything)
return upload({
edit : data.edit,
apk : apk
});
}).then(function(data) {
return setTrack(data); // set our track
}).then(function(data) {
return commitToPlayStore(data); // commit our changes
}).then(function(data) {
console.log('Successful upload:', data); // log our success!
}).catch(function(err) {
console.log(err);
process.exit(0);
});
/**
* Sets our authorization token and begins an edit transaction.
*/
function startEdit() {
return new Promise(function(resolve, reject) {
jwtClient.authorize(function(err, tokens) { // get the tokens
if (err) {
console.log(err);
return;
}
oauth2Client.setCredentials(tokens); // set the credentials from
// the tokens
play.edits.insert({
resource : {
id : editId,
expiryTimeSeconds : 600 // this edit will be valid for 10
// minutes
}
}, function(err, edit) {
if (err || !edit) {
reject(err);
}
resolve({
edit : edit
});
});
});
});
}
/**
* Stages an upload of the APK (but doesn't actually upload anything)
*/
function upload(data) {
var edit = data.edit;
var apk = data.apk;
return new Promise(function(resolve, reject) {
play.edits.apks.upload({
editId : edit.id,
media : {
mimeType : 'application/vnd.android.package-archive',
body : apk
}
}, function(err, res) {
if (err || !res) {
reject(err);
}
resolve(_.omit(_.extend(data, {
uploadResults : res
}), 'apk'));
}); // pass any data we care about to the next function call
});
}
/**
* Sets our track (beta, production, etc.)
*/
function setTrack(data) {
var edit = data.edit;
var track = 'beta';
return new Promise(function(resolve, reject) {
play.edits.tracks.update({
editId : edit.id,
track : track,
resource : {
track : track,
versionCodes : [ +data.uploadResults.versionCode ]
}
}, function(err, res) {
if (err || !res) {
reject(err);
}
resolve(_.extend(data, {
setTrackResults : res
}));
});
});
}
/**
* Commits our edit transaction and makes our changes live.
*/
function commitToPlayStore(data) {
return new Promise(function(resolve, reject) {
play.edits.commit({
editId : data.edit.id
}, function(err, res) {
if (err || !res) {
reject(err);
}
resolve(_.extend(data, {
commitToPlayStoreResults : res
}));
grunt.log.ok('new version committed');
done();
});
});
}
});
grunt.registerMultiTask('junit', 'custom junit task runner', function() {
var done = this.async();
var jv = require('junit_viewer')
var parsedData = jv.parse(this.data.options.input);
var renderedData = jv.render(parsedData)
var parsedAndRenderedData = jv.junit_viewer(this.data.options.output)
grunt.log.ok('new junit generated in ' + this.data.options.output);
done();
});
grunt.registerTask('force_on', 'force the force option on',
function() {
grunt.option('force', true);
});
grunt.registerTask('force_off', 'turn force option off',
function() {
grunt.option('force', false);
});
grunt.registerTask('crypt', 'crypto plugin', function() {
// grunt crypt --encrypt
var done = this.async();
var crypto = require('crypto');
function encrypt(key) {
var cipher = crypto.createCipher('aes-256-ctr', key)
var text = JSON.stringify(JSON.parse(grunt.file.read('../keys/keys.json')));
var crypted = cipher.update(text, 'utf8', 'hex');
crypted += cipher.final('hex');
grunt.file.write('../keys/keys.enc', crypted);
}
function decrypt(key) {
var decipher = crypto.createDecipher('aes-256-ctr', key)
var dec = decipher.update(grunt.file.read('../keys/keys.enc'), 'hex', 'utf8')
dec += decipher.final('utf8');
return JSON.parse(dec);
}
require('inquirer').createPromptModule()({
type : 'password',
name : 'password',
message : 'password'
}).then(answers => {
var key = answers['password'];
if (grunt.option('encrypt'))
encrypt(key);
grunt.config.merge(decrypt(key));
done();
});
});
}; |
export const ic_gif_twotone = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M11.5 9H13v6h-1.5V9zM9 9H6c-.6 0-1 .5-1 1v4c0 .5.4 1 1 1h3c.6 0 1-.5 1-1v-2H8.5v1.5h-2v-3H10V10c0-.5-.4-1-1-1zm10 1.5V9h-4.5v6H16v-2h2v-1.5h-2v-1h3z","opacity":".87"},"children":[]}]}; |
var ConnectionParameters = require(__dirname + '/../lib/connection-parameters');
var config = new ConnectionParameters(process.argv[2]);
for(var i = 0; i < process.argv.length; i++) {
switch(process.argv[i].toLowerCase()) {
case 'native':
config.native = true;
break;
case 'binary':
config.binary = true;
break;
case 'down':
config.down = true;
break;
default:
break;
}
}
module.exports = config;
|
module.exports = function(grunt) {
// http://gruntjs.com/getting-started
// https://github.com/gruntjs/grunt-contrib-uglify
var js_path = "../../../public/js/external/dbgraph/";
var css_path = "../../../public/css/external/dbgraph/";
var img_path = "../../../public/img/external/dbgraph/";
var deploy_path = "../../../public/dbgraph_deploy/";
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
step1: {
options: {
compress: false,
mangle: false,
beautify: false
},
files: {
'temp/wwwsqldesigner.min.js': [
'wwwsqldesigner/js/oz.js',
'wwwsqldesigner/js/config.js',
'wwwsqldesigner/js/globals.js',
'wwwsqldesigner/js/visual.js',
'wwwsqldesigner/js/row.js',
'wwwsqldesigner/js/table.js',
'wwwsqldesigner/js/relation.js',
'wwwsqldesigner/js/key.js',
'wwwsqldesigner/js/rubberband.js',
'wwwsqldesigner/js/map.js',
'wwwsqldesigner/js/toggle.js',
'wwwsqldesigner/js/io.js',
'wwwsqldesigner/js/tablemanager.js',
'wwwsqldesigner/js/options.js',
'wwwsqldesigner/js/rowmanager.js',
'wwwsqldesigner/js/keymanager.js',
'wwwsqldesigner/js/window.js',
'wwwsqldesigner/js/wwwsqldesigner.js',
'app/js/draggable.js',
'app/js/mapon_dbgraph.js',]
}
}
},
cssmin: {
options: {
shorthandCompacting: false,
roundingPrecision: -1
},
target: {
files: {
'temp/wwwsqldesigner.css': [
'temp/wwwsqldesigner.css'
]
}
}
},
css_selectors: {
step1: {
options: {
mutations: [
{prefix: '.dbgraph'}
]
},
files: {
'temp/wwwsqldesigner.css': [
'wwwsqldesigner/styles/style.css',
'app/css/mapon_dbgraph.css'
],
},
},
},
copy: {
step2: {
files: [
{expand: true, cwd: "temp", src: ["wwwsqldesigner.min.js"], dest: js_path},
{expand: true, cwd: "wwwsqldesigner/db/", src: ['**'], dest: js_path + '/db'},
{expand: true, cwd: "temp", src: ["wwwsqldesigner.css"], dest: css_path},
{expand: true, cwd: "wwwsqldesigner/images", src: ["back.png"], dest: img_path},
]
},
step2_deploy: {
files: [
{expand: true, cwd: "temp", src: ["wwwsqldesigner.min.js"], dest: deploy_path},
{expand: true, cwd: "wwwsqldesigner/db/", src: ['**'], dest: deploy_path + '/db'},
{expand: true, cwd: "temp", src: ["wwwsqldesigner.css"], dest: deploy_path},
{expand: true, cwd: "app", src: ["index.html"], dest: deploy_path},
]
}
},
clean: {
build: {
src: ["temp"]
}
}
});
// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-css-selectors');
grunt.loadNpmTasks('grunt-contrib-clean');
// tasks
grunt.registerTask('uglify_files', [ 'uglify:step1', 'css_selectors:step1', 'cssmin' ]);
grunt.registerTask('copy_files', [ 'copy:step2', 'copy:step2_deploy']);
grunt.registerTask('clean_temp', [ 'clean' ]);
grunt.registerTask('default', ['uglify_files', 'copy_files', 'clean_temp']);
}; |
var util = require("./util");
exports['test RegExp'] = function() {
// Valid RegExp
util.assertLint("var s = '';\n" +
"s.match('/(chapter \d+(\.\d)*)/i')", {
messages : []
}, [ "ecma5" ]);
// Invalid RegExp
util.assertLint("var s = '';\n" +
"s.match('/(chapter \d+(\.\d)*)/i)", {
messages : [ {
"message" : "Invalid argument at 1: SyntaxError: Invalid regular expression: //(chapter d+(.d)*)/i)/: Unmatched ')'",
"from" : 20,
"to" : 42,
"severity" : "error",
"file" : "test1.js"
}]
}, [ "ecma5" ]);
}
if (module == require.main) require("test").run(exports); |
"use strict";
var s = require('./support');
var t = s.t;
var bootDefinitions = require('../lib/boot/definitions');
var bootDatabase = require('../lib/boot/database');
describe('boot/database', function () {
var app;
beforeEach(function () {
app = s.mockApplication();
bootDefinitions('test/fixtures/base-app/models').call(app);
});
it('should connect database and build schemas', function (done) {
bootDatabase().call(app, function () {
t.lengthOf(app.schemas, 1);
t.lengthOf(Object.keys(app.models), 2);
var Car = app.models['Car'];
t.isTrue(Car.setupCar);
done();
});
});
}); |
'use strict';
var transformation = require('../lib/manifest');
var should = require('should');
describe('transformation: Windows 10 Manifest', function () {
describe('convertFromBase()', function () {
it('Should return an Error if manifest info is undefined', function (done) {
transformation.convertFromBase(undefined, function (err) {
should.exist(err);
err.should.have.property('message', 'Manifest content is empty or not initialized.');
done();
});
});
it('Should return an Error if content property is undefined', function (done) {
var originalManifest = { key: 'value' };
transformation.convertFromBase(originalManifest, function (err) {
should.exist(err);
err.should.have.property('message', 'Manifest content is empty or not initialized.');
done();
});
});
it('Should return an Error if start_url is missing', function (done) {
var originalManifestInfo = {
content: {}
};
transformation.convertFromBase(originalManifestInfo, function (err) {
should.exist(err);
err.should.have.property('message', 'Start URL is required.');
done();
});
});
it('Should return the transformed manifest', function (done) {
var name = 'name';
var siteUrl = 'http://url.com/something?query';
var shortName = 'shortName';
var orientation = 'landscape';
var storeLogoSrc = 'icon/store.png';
var smallLogoSrc = 'icon/small';
var logoSrc = 'icon/medium.png';
var splashScreenSrc = 'icon/splash.png';
var originalManifestInfo = {
content: {
'start_url': siteUrl,
'short_name': shortName,
'name': name,
'orientation' : orientation,
'icons': [
{
'src': storeLogoSrc,
'sizes': '50x50',
},
{
'src': smallLogoSrc,
'sizes': '44x44',
'type': 'image/png'
},
{
'src': logoSrc,
'sizes': '150x150'
},
{
'src': splashScreenSrc,
'sizes': '620x300',
'density': '2'
}]
}
};
transformation.convertFromBase(originalManifestInfo, function (err, result) {
should.not.exist(err);
should.exist(result);
/*jshint -W030 */
result.should.have.property('content').which.is.an.Object;
result.should.have.property('format', 'windows10');
var manifest = result.content;
manifest.should.have.property('rawData');
manifest.rawData.indexOf('<DisplayName>' + shortName + '</DisplayName>').should.be.above(-1);
manifest.rawData.indexOf('DisplayName="' + shortName + '"').should.be.above(-1);
manifest.rawData.indexOf('<Application Id="' + shortName + '"').should.be.above(-1);
manifest.rawData.indexOf('StartPage="' + siteUrl + '"').should.be.above(-1);
manifest.rawData.indexOf('Description="' + name + '"').should.be.above(-1);
manifest.rawData.indexOf('<uap:Rotation Preference="' + orientation + '" />').should.be.above(-1);
manifest.rawData.replace(/[\t\r\n]/g, '').indexOf('<uap:ApplicationContentUriRules><uap:Rule Type="include" WindowsRuntimeAccess="none" Match="http://url.com/" /></uap:ApplicationContentUriRules>').should.be.above(-1);
manifest.should.have.property('icons').which.is.an.Object;
manifest.icons.should.containEql({ '44x44': { 'url': smallLogoSrc, 'fileName': 'Square44x44Logo.scale-100.png' } });
manifest.icons.should.containEql({ '50x50': { 'url': storeLogoSrc, 'fileName': 'StoreLogo.scale-100.png' } });
manifest.icons.should.containEql({ '150x150': { 'url': logoSrc, 'fileName': 'Square150x150Logo.scale-100.png' } });
manifest.icons.should.containEql({ '620x300': { 'url': splashScreenSrc, 'fileName': 'SplashScreen.scale-100.png' } });
done();
});
});
it('Should keep generatedFrom information if present', function (done) {
var originalManifestInfo = {
content: {
'start_url': 'http://url.com/something?query',
'short_name': 'shortName'
},
generatedFrom: 'CLI'
};
transformation.convertFromBase(originalManifestInfo, function (err, result) {
should.not.exist(err);
should.exist(result);
/*jshint -W030 */
result.should.have.property('generatedFrom', 'CLI');
done();
});
});
it('Should keep generatedUrl information if present', function (done) {
var originalManifestInfo = {
content: {
'start_url': 'http://url.com/something?query',
'short_name': 'shortName'
},
generatedUrl: 'http://url.com/manifest.json'
};
transformation.convertFromBase(originalManifestInfo, function (err, result) {
should.not.exist(err);
should.exist(result);
/*jshint -W030 */
result.should.have.property('generatedUrl', 'http://url.com/manifest.json');
done();
});
});
it('Should keep timestamp information if present', function (done) {
var expectedDate = new Date().toISOString();
var originalManifestInfo = {
content: {
'start_url': 'http://url.com/something?query',
'short_name': 'shortName'
},
timestamp: expectedDate
};
transformation.convertFromBase(originalManifestInfo, function (err, result) {
should.not.exist(err);
should.exist(result);
/*jshint -W030 */
result.should.have.property('timestamp', expectedDate);
done();
});
});
it('Should add timestamp', function (done) {
var originalManifestInfo = {
content: {
'start_url': 'http://url.com/something?query',
'short_name': 'shortName'
},
};
transformation.convertFromBase(originalManifestInfo, function (err, result) {
should.not.exist(err);
should.exist(result);
/*jshint -W030 */
result.should.have.property('timestamp');
done();
});
});
it('Should return the transformed manifest with content uri rules', function (done) {
var siteUrl = 'http://url.com/something?query';
var shortName = 'shortName';
var originalManifestInfo = {
content: {
'start_url': siteUrl,
'short_name': shortName,
'scope': '/scope-path/',
'mjs_access_whitelist': [
{ 'url': 'http://example.com/' }
]
}
};
transformation.convertFromBase(originalManifestInfo, function (err, result) {
should.not.exist(err);
should.exist(result);
/*jshint -W030 */
result.should.have.property('content').which.is.an.Object;
result.should.have.property('format', 'windows10');
var manifest = result.content;
manifest.should.have.property('rawData');
var expectedContentUriRules = '<uap:ApplicationContentUriRules>' +
'<uap:Rule Type="include" WindowsRuntimeAccess="none" Match="http://url.com/scope-path/" />' +
'<uap:Rule Type="include" WindowsRuntimeAccess="none" Match="http://example.com/" />' +
'</uap:ApplicationContentUriRules>';
manifest.rawData.replace(/[\t\r\n]/g, '').indexOf(expectedContentUriRules).should.be.above(-1);
done();
});
});
it('Should return the transformed manifest with no duplicated content uri rules', function (done) {
var siteUrl = 'http://url.com/something?query';
var shortName = 'shortName';
var originalManifestInfo = {
content: {
'start_url': siteUrl,
'short_name': shortName,
'scope': '/scope-path/',
'mjs_access_whitelist': [
{ 'url': 'http://url.com/scope-path/' }
]
}
};
transformation.convertFromBase(originalManifestInfo, function (err, result) {
should.not.exist(err);
should.exist(result);
/*jshint -W030 */
result.should.have.property('content').which.is.an.Object;
result.should.have.property('format', 'windows10');
var manifest = result.content;
manifest.should.have.property('rawData');
var expectedContentUriRules = '<uap:ApplicationContentUriRules>' +
'<uap:Rule Type="include" WindowsRuntimeAccess="none" Match="http://url.com/scope-path/" />' +
'</uap:ApplicationContentUriRules>';
manifest.rawData.replace(/[\t\r\n]/g, '').indexOf(expectedContentUriRules).should.be.above(-1);
done();
});
});
it('Should ignore wildcard access rule ("*")', function (done) {
var siteUrl = 'http://url.com/something?query';
var shortName = 'shortName';
var originalManifestInfo = {
content: {
'start_url': siteUrl,
'short_name': shortName,
'scope': '*',
'mjs_access_whitelist': [
{ 'url': '*' }
]
}
};
transformation.convertFromBase(originalManifestInfo, function (err, result) {
should.not.exist(err);
should.exist(result);
/*jshint -W030 */
result.should.have.property('content').which.is.an.Object;
result.should.have.property('format', 'windows10');
var manifest = result.content;
manifest.should.have.property('rawData');
var expectedContentUriRules = '<uap:ApplicationContentUriRules><uap:Rule Type="include" WindowsRuntimeAccess="none" Match="http://url.com/" /></uap:ApplicationContentUriRules>';
manifest.rawData.replace(/[\t\r\n]/g, '').indexOf(expectedContentUriRules).should.be.above(-1);
done();
});
});
it('Should ignore wildcard character at the end of the rule', function (done) {
var siteUrl = 'http://url.com/something?query';
var shortName = 'shortName';
var originalManifestInfo = {
content: {
'start_url': siteUrl,
'short_name': shortName,
'scope': '/scope-path/*',
'mjs_access_whitelist': [
{ 'url': 'http://example.com/*' }
]
}
};
transformation.convertFromBase(originalManifestInfo, function (err, result) {
should.not.exist(err);
should.exist(result);
/*jshint -W030 */
result.should.have.property('content').which.is.an.Object;
result.should.have.property('format', 'windows10');
var manifest = result.content;
manifest.should.have.property('rawData');
var expectedContentUriRules = '<uap:ApplicationContentUriRules>' +
'<uap:Rule Type="include" WindowsRuntimeAccess="none" Match="http://url.com/scope-path/" />' +
'<uap:Rule Type="include" WindowsRuntimeAccess="none" Match="http://example.com/" />' +
'</uap:ApplicationContentUriRules>';
manifest.rawData.replace(/[\t\r\n]/g, '').indexOf(expectedContentUriRules).should.be.above(-1);
done();
});
});
it('Should add scope as rule if scope is full URL', function (done) {
var siteUrl = 'http://url.com:3000/';
var shortName = 'shortName';
var originalManifestInfo = {
content: {
'start_url': siteUrl,
'short_name': shortName,
'scope': 'http://subdomain.url.com:3000/'
}
};
transformation.convertFromBase(originalManifestInfo, function (err, result) {
should.not.exist(err);
should.exist(result);
/*jshint -W030 */
result.should.have.property('content').which.is.an.Object;
result.should.have.property('format', 'windows10');
var manifest = result.content;
manifest.should.have.property('rawData');
var expectedContentUriRules = '<uap:ApplicationContentUriRules>' +
'<uap:Rule Type="include" WindowsRuntimeAccess="none" Match="http://subdomain.url.com:3000/" />' +
'</uap:ApplicationContentUriRules>';
manifest.rawData.replace(/[\t\r\n]/g, '').indexOf(expectedContentUriRules).should.be.above(-1);
done();
});
});
it('Should add scope as rule if scope is full URL but has subdomain as wildcard', function (done) {
var siteUrl = 'http://url.com:3000/';
var shortName = 'shortName';
var originalManifestInfo = {
content: {
'start_url': siteUrl,
'short_name': shortName,
'scope': 'http://*.url.com:3000/'
}
};
transformation.convertFromBase(originalManifestInfo, function (err, result) {
should.not.exist(err);
should.exist(result);
/*jshint -W030 */
result.should.have.property('content').which.is.an.Object;
result.should.have.property('format', 'windows10');
var manifest = result.content;
manifest.should.have.property('rawData');
var expectedContentUriRules = '<uap:ApplicationContentUriRules>' +
'<uap:Rule Type="include" WindowsRuntimeAccess="none" Match="http://*.url.com:3000/" />' +
'</uap:ApplicationContentUriRules>';
manifest.rawData.replace(/[\t\r\n]/g, '').indexOf(expectedContentUriRules).should.be.above(-1);
done();
});
});
it('Should use mjs_access_whitelist to enable API access in base ACUR', function (done) {
var siteUrl = 'http://url.com/something?query';
var shortName = 'shortName';
var originalManifestInfo = {
content: {
'start_url': siteUrl,
'short_name': shortName,
'mjs_access_whitelist': [
{ 'url': 'http://url.com/', 'apiAccess': 'all' }
]
}
};
transformation.convertFromBase(originalManifestInfo, function (err, result) {
should.not.exist(err);
should.exist(result);
/*jshint -W030 */
result.should.have.property('content').which.is.an.Object;
result.should.have.property('format', 'windows10');
var manifest = result.content;
manifest.should.have.property('rawData');
var expectedContentUriRules = '<uap:ApplicationContentUriRules>' +
'<uap:Rule Type="include" WindowsRuntimeAccess="all" Match="http://url.com/" />' +
'</uap:ApplicationContentUriRules>';
manifest.rawData.replace(/[\t\r\n]/g, '').indexOf(expectedContentUriRules).should.be.above(-1);
done();
});
});
it('Should use mjs_access_whitelist to enable API access in secondary ACUR but not in base ACUR', function (done) {
var siteUrl = 'http://url.com/something?query';
var shortName = 'shortName';
var originalManifestInfo = {
content: {
'start_url': siteUrl,
'short_name': shortName,
'mjs_access_whitelist': [
{ 'url': 'http://url.com/somepath/', 'apiAccess': 'all' }
]
}
};
transformation.convertFromBase(originalManifestInfo, function (err, result) {
should.not.exist(err);
should.exist(result);
/*jshint -W030 */
result.should.have.property('content').which.is.an.Object;
result.should.have.property('format', 'windows10');
var manifest = result.content;
manifest.should.have.property('rawData');
var expectedContentUriRules = '<uap:ApplicationContentUriRules>' +
'<uap:Rule Type="include" WindowsRuntimeAccess="none" Match="http://url.com/" />' +
'<uap:Rule Type="include" WindowsRuntimeAccess="all" Match="http://url.com/somepath/" />' +
'</uap:ApplicationContentUriRules>';
manifest.rawData.replace(/[\t\r\n]/g, '').indexOf(expectedContentUriRules).should.be.above(-1);
done();
});
});
it('Should use mjs_api_access to enable API access in base ACUR', function (done) {
var siteUrl = 'http://url.com/something?query';
var shortName = 'shortName';
var originalManifestInfo = {
content: {
'start_url': siteUrl,
'short_name': shortName,
'mjs_api_access': [
{ 'match': 'http://url.com/', 'access': 'all' }
]
}
};
transformation.convertFromBase(originalManifestInfo, function (err, result) {
should.not.exist(err);
should.exist(result);
/*jshint -W030 */
result.should.have.property('content').which.is.an.Object;
result.should.have.property('format', 'windows10');
var manifest = result.content;
manifest.should.have.property('rawData');
var expectedContentUriRules = '<uap:ApplicationContentUriRules>' +
'<uap:Rule Type="include" WindowsRuntimeAccess="all" Match="http://url.com/" />' +
'</uap:ApplicationContentUriRules>';
manifest.rawData.replace(/[\t\r\n]/g, '').indexOf(expectedContentUriRules).should.be.above(-1);
done();
});
});
it('Should use mjs_api_access to enable API access in secondary ACUR but not in base ACUR', function (done) {
var siteUrl = 'http://url.com/something?query';
var shortName = 'shortName';
var originalManifestInfo = {
content: {
'start_url': siteUrl,
'short_name': shortName,
'mjs_api_access': [
{ 'match': 'http://url.com/somepath/', 'access': 'all' }
]
}
};
transformation.convertFromBase(originalManifestInfo, function (err, result) {
should.not.exist(err);
should.exist(result);
/*jshint -W030 */
result.should.have.property('content').which.is.an.Object;
result.should.have.property('format', 'windows10');
var manifest = result.content;
manifest.should.have.property('rawData');
var expectedContentUriRules = '<uap:ApplicationContentUriRules>' +
'<uap:Rule Type="include" WindowsRuntimeAccess="none" Match="http://url.com/" />' +
'<uap:Rule Type="include" WindowsRuntimeAccess="all" Match="http://url.com/somepath/" />' +
'</uap:ApplicationContentUriRules>';
manifest.rawData.replace(/[\t\r\n]/g, '').indexOf(expectedContentUriRules).should.be.above(-1);
done();
});
});
it('Should add different ACURs from mjs_api_access and mjs_access_whitelist if match setting is different', function (done) {
var siteUrl = 'http://url.com/something?query';
var shortName = 'shortName';
var originalManifestInfo = {
content: {
'start_url': siteUrl,
'short_name': shortName,
'mjs_access_whitelist': [
{ 'url': 'http://url.com/otherpath/' }
],
'mjs_api_access': [
{ 'match': 'http://url.com/somepath/', 'access': 'all' }
]
}
};
transformation.convertFromBase(originalManifestInfo, function (err, result) {
should.not.exist(err);
should.exist(result);
/*jshint -W030 */
result.should.have.property('content').which.is.an.Object;
result.should.have.property('format', 'windows10');
var manifest = result.content;
manifest.should.have.property('rawData');
var expectedContentUriRules = '<uap:ApplicationContentUriRules>' +
'<uap:Rule Type="include" WindowsRuntimeAccess="none" Match="http://url.com/" />' +
'<uap:Rule Type="include" WindowsRuntimeAccess="none" Match="http://url.com/otherpath/" />' +
'<uap:Rule Type="include" WindowsRuntimeAccess="all" Match="http://url.com/somepath/" />' +
'</uap:ApplicationContentUriRules>';
manifest.rawData.replace(/[\t\r\n]/g, '').indexOf(expectedContentUriRules).should.be.above(-1);
done();
});
});
it('Should add single ACUR from mjs_api_access and mjs_access_whitelist if both have same match setting', function (done) {
var siteUrl = 'http://url.com/something?query';
var shortName = 'shortName';
var originalManifestInfo = {
content: {
'start_url': siteUrl,
'short_name': shortName,
'mjs_access_whitelist': [
{ 'url': 'http://url.com/somepath/' }
],
'mjs_api_access': [
{ 'match': 'http://url.com/somepath/', 'access': 'all' }
]
}
};
transformation.convertFromBase(originalManifestInfo, function (err, result) {
should.not.exist(err);
should.exist(result);
/*jshint -W030 */
result.should.have.property('content').which.is.an.Object;
result.should.have.property('format', 'windows10');
var manifest = result.content;
manifest.should.have.property('rawData');
var expectedContentUriRules = '<uap:ApplicationContentUriRules>' +
'<uap:Rule Type="include" WindowsRuntimeAccess="none" Match="http://url.com/" />' +
'<uap:Rule Type="include" WindowsRuntimeAccess="all" Match="http://url.com/somepath/" />' +
'</uap:ApplicationContentUriRules>';
manifest.rawData.replace(/[\t\r\n]/g, '').indexOf(expectedContentUriRules).should.be.above(-1);
done();
});
});
it('Should add ACUR from mjs_api_access if windows10 is in platform', function (done) {
var siteUrl = 'http://url.com/something?query';
var shortName = 'shortName';
var originalManifestInfo = {
content: {
'start_url': siteUrl,
'short_name': shortName,
'mjs_api_access': [
{ 'match': 'http://url.com/somepath/', 'platform': 'windows10', 'access': 'all' }
]
}
};
transformation.convertFromBase(originalManifestInfo, function (err, result) {
should.not.exist(err);
should.exist(result);
/*jshint -W030 */
result.should.have.property('content').which.is.an.Object;
result.should.have.property('format', 'windows10');
var manifest = result.content;
manifest.should.have.property('rawData');
var expectedContentUriRules = '<uap:ApplicationContentUriRules>' +
'<uap:Rule Type="include" WindowsRuntimeAccess="none" Match="http://url.com/" />' +
'<uap:Rule Type="include" WindowsRuntimeAccess="all" Match="http://url.com/somepath/" />' +
'</uap:ApplicationContentUriRules>';
manifest.rawData.replace(/[\t\r\n]/g, '').indexOf(expectedContentUriRules).should.be.above(-1);
done();
});
});
it('Should add ACUR from mjs_api_access with default access type \'all\' if no access type is specified', function (done) {
var siteUrl = 'http://url.com/something?query';
var shortName = 'shortName';
var originalManifestInfo = {
content: {
'start_url': siteUrl,
'short_name': shortName,
'mjs_api_access': [
{ 'match': 'http://url.com/somepath/', 'platform': 'windows10'}
]
}
};
transformation.convertFromBase(originalManifestInfo, function (err, result) {
should.not.exist(err);
should.exist(result);
/*jshint -W030 */
result.should.have.property('content').which.is.an.Object;
result.should.have.property('format', 'windows10');
var manifest = result.content;
manifest.should.have.property('rawData');
var expectedContentUriRules = '<uap:ApplicationContentUriRules>' +
'<uap:Rule Type="include" WindowsRuntimeAccess="none" Match="http://url.com/" />' +
'<uap:Rule Type="include" WindowsRuntimeAccess="all" Match="http://url.com/somepath/" />' +
'</uap:ApplicationContentUriRules>';
manifest.rawData.replace(/[\t\r\n]/g, '').indexOf(expectedContentUriRules).should.be.above(-1);
done();
});
});
it('Should not add ACUR from mjs_api_access if windows10 is not in platform', function (done) {
var siteUrl = 'http://url.com/something?query';
var shortName = 'shortName';
var originalManifestInfo = {
content: {
'start_url': siteUrl,
'short_name': shortName,
'mjs_api_access': [
{ 'match': 'http://url.com/somepath/', 'platform': 'other', 'access': 'all' }
]
}
};
transformation.convertFromBase(originalManifestInfo, function (err, result) {
should.not.exist(err);
should.exist(result);
/*jshint -W030 */
result.should.have.property('content').which.is.an.Object;
result.should.have.property('format', 'windows10');
var manifest = result.content;
manifest.should.have.property('rawData');
var expectedContentUriRules = '<uap:ApplicationContentUriRules>' +
'<uap:Rule Type="include" WindowsRuntimeAccess="none" Match="http://url.com/" />' +
'</uap:ApplicationContentUriRules>';
manifest.rawData.replace(/[\t\r\n]/g, '').indexOf(expectedContentUriRules).should.be.above(-1);
done();
});
});
it('Should not add ACUR from mjs_api_access if access type is \'none\' and match setting is not whitelisted', function (done) {
var siteUrl = 'http://url.com/something?query';
var shortName = 'shortName';
var originalManifestInfo = {
content: {
'start_url': siteUrl,
'short_name': shortName,
'mjs_api_access': [
{ 'match': 'http://url.com/somepath/', 'platform': 'windows10', 'access': 'none' }
]
}
};
transformation.convertFromBase(originalManifestInfo, function (err, result) {
should.not.exist(err);
should.exist(result);
/*jshint -W030 */
result.should.have.property('content').which.is.an.Object;
result.should.have.property('format', 'windows10');
var manifest = result.content;
manifest.should.have.property('rawData');
var expectedContentUriRules = '<uap:ApplicationContentUriRules>' +
'<uap:Rule Type="include" WindowsRuntimeAccess="none" Match="http://url.com/" />' +
'</uap:ApplicationContentUriRules>';
manifest.rawData.replace(/[\t\r\n]/g, '').indexOf(expectedContentUriRules).should.be.above(-1);
done();
});
});
});
});
|
/** @babel */
/** @jsx etch.dom */
import etch from 'etch'
import StatusBarComponent from './status-bar-component'
export default class ConnectedStatusComponent extends StatusBarComponent {
constructor(properties) {
super()
this.setupProperties(properties)
}
setupProperties(properties) {
this.connected = properties.connected
this.serConnStatus = this.connected ? 'Connected' : 'Disconnected'
this.comPort = properties.port
if (this.comPort === '0') {
this.comPort = "No Port Selected"
}
}
render() {
return(
<div className={'status-bar-component inline-block '
+ (this.active ? '' : 'hidden')}>
<span className={'item ' + (this.connected ? 'connected' : '')}>
{this.serConnStatus}
</span>
<span className='item'>{this.comPort}</span>
</div>
)
}
update(properties){
this.setupProperties(properties)
return etch.update(this)
}
}
|
var Plumage = require('plumage');
var City = require('example/model/City');
module.exports = Plumage.model.Model.extend({
idAttribute: 'name',
urlIdAttribute: 'name',
urlRoot: '/',
queryAttrs: ['name', 'region'],
relationships: {
'capital': {
modelCls: City,
reverse: 'parent'
},
'language': {
modelCls: Plumage.collection.DataCollection
}
}
}); |
"use strict";
var net = require('net');
let Packetizer = require('../index.js');
var HOST = '127.0.0.1';
var PORT = 6969;
net.createServer(function (socket) {
console.log('Talking to: ' + socket.remoteAddress +':'+ socket.remotePort);
Packetizer.receive(socket).then(
function ( msg ) {
console.log("Heard: "+msg);
socket.write(Packetizer.send('You said \"'+msg+'"'));
}
);
socket.on('close', function(data) {
console.log('CLOSED: ' + socket.remoteAddress +' '+ socket.remotePort);
});
})
.listen(PORT, HOST);
console.log('Server listening on ' + HOST +':'+ PORT);
|
import React, {Component, PropTypes} from 'react';
import IconButton from '../IconButton';
import NavigationMenu from '../svg-icons/navigation/menu';
import Paper from '../Paper';
import propTypes from '../utils/propTypes';
import warning from 'warning';
export function getStyles(props, context) {
const {
appBar,
button: {
iconButtonSize,
},
zIndex,
} = context.muiTheme;
const flatButtonSize = 36;
const styles = {
root: {
position: 'relative',
zIndex: zIndex.appBar,
width: '100%',
display: 'flex',
backgroundColor: appBar.color,
paddingLeft: appBar.padding,
paddingRight: appBar.padding,
},
title: {
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
margin: 0,
paddingTop: 0,
letterSpacing: 0,
fontSize: 24,
fontWeight: appBar.titleFontWeight,
color: appBar.textColor,
height: appBar.height,
lineHeight: `${appBar.height}px`,
},
mainElement: {
boxFlex: 1,
flex: '1',
},
iconButtonStyle: {
marginTop: (appBar.height - iconButtonSize) / 2,
marginRight: 8,
marginLeft: -16,
},
iconButtonIconStyle: {
fill: appBar.textColor,
color: appBar.textColor,
},
flatButton: {
color: appBar.textColor,
marginTop: (iconButtonSize - flatButtonSize) / 2 + 1,
},
};
return styles;
}
class AppBar extends Component {
static muiName = 'AppBar';
static propTypes = {
/**
* Can be used to render a tab inside an app bar for instance.
*/
children: PropTypes.node,
/**
* Applied to the app bar's root element.
*/
className: PropTypes.string,
/**
* The classname of the icon on the left of the app bar.
* If you are using a stylesheet for your icons, enter the class name for the icon to be used here.
*/
iconClassNameLeft: PropTypes.string,
/**
* Similiar to the iconClassNameLeft prop except that
* it applies to the icon displayed on the right of the app bar.
*/
iconClassNameRight: PropTypes.string,
/**
* The custom element to be displayed on the left side of the
* app bar such as an SvgIcon.
*/
iconElementLeft: PropTypes.element,
/**
* Similiar to the iconElementLeft prop except that this element is displayed on the right of the app bar.
*/
iconElementRight: PropTypes.element,
/**
* Override the inline-styles of the element displayed on the left side of the app bar.
*/
iconStyleLeft: PropTypes.object,
/**
* Override the inline-styles of the element displayed on the right side of the app bar.
*/
iconStyleRight: PropTypes.object,
/**
* Callback function for when the left icon is selected via a touch tap.
*
* @param {object} event TouchTap event targeting the left `IconButton`.
*/
onLeftIconButtonTouchTap: PropTypes.func,
/**
* Callback function for when the right icon is selected via a touch tap.
*
* @param {object} event TouchTap event targeting the right `IconButton`.
*/
onRightIconButtonTouchTap: PropTypes.func,
/**
* Callback function for when the title text is selected via a touch tap.
*
* @param {object} event TouchTap event targeting the `title` node.
*/
onTitleTouchTap: PropTypes.func,
/**
* Determines whether or not to display the Menu icon next to the title.
* Setting this prop to false will hide the icon.
*/
showMenuIconButton: PropTypes.bool,
/**
* Override the inline-styles of the root element.
*/
style: PropTypes.object,
/**
* The title to display on the app bar.
*/
title: PropTypes.node,
/**
* Override the inline-styles of the app bar's title element.
*/
titleStyle: PropTypes.object,
/**
* The zDepth of the component.
* The shadow of the app bar is also dependent on this property.
*/
zDepth: propTypes.zDepth,
};
static defaultProps = {
showMenuIconButton: true,
title: '',
zDepth: 1,
};
static contextTypes = {
muiTheme: PropTypes.object.isRequired,
};
componentDidMount() {
warning(!this.props.iconElementLeft || !this.props.iconClassNameLeft, `Properties iconElementLeft
and iconClassNameLeft cannot be simultaneously defined. Please use one or the other.`);
warning(!this.props.iconElementRight || !this.props.iconClassNameRight, `Properties iconElementRight
and iconClassNameRight cannot be simultaneously defined. Please use one or the other.`);
}
handleTouchTapLeftIconButton = (event) => {
if (this.props.onLeftIconButtonTouchTap) {
this.props.onLeftIconButtonTouchTap(event);
}
};
handleTouchTapRightIconButton = (event) => {
if (this.props.onRightIconButtonTouchTap) {
this.props.onRightIconButtonTouchTap(event);
}
};
handleTitleTouchTap = (event) => {
if (this.props.onTitleTouchTap) {
this.props.onTitleTouchTap(event);
}
};
render() {
const {
title,
titleStyle,
iconStyleLeft,
iconStyleRight,
showMenuIconButton,
iconElementLeft,
iconElementRight,
iconClassNameLeft,
iconClassNameRight,
className,
style,
zDepth,
children,
...other,
} = this.props;
const {prepareStyles} = this.context.muiTheme;
const styles = getStyles(this.props, this.context);
let menuElementLeft;
let menuElementRight;
// If the title is a string, wrap in an h1 tag.
// If not, wrap in a div tag.
const titleComponent = typeof title === 'string' || title instanceof String ? 'h1' : 'div';
const titleElement = React.createElement(titleComponent, {
onTouchTap: this.handleTitleTouchTap,
style: prepareStyles(Object.assign(styles.title, styles.mainElement, titleStyle)),
}, title);
const iconLeftStyle = Object.assign({}, styles.iconButtonStyle, iconStyleLeft);
if (showMenuIconButton) {
let iconElementLeftNode = iconElementLeft;
if (iconElementLeft) {
if (iconElementLeft.type.muiName === 'IconButton') {
const iconButtonIconStyle = !(iconElementLeft.props.children &&
iconElementLeft.props.children.props.color) ? styles.iconButtonIconStyle : null;
iconElementLeftNode = React.cloneElement(iconElementLeft, {
iconStyle: Object.assign({}, iconButtonIconStyle, iconElementLeft.props.iconStyle),
});
}
menuElementLeft = (
<div style={prepareStyles(iconLeftStyle)}>
{iconElementLeftNode}
</div>
);
} else {
const child = iconClassNameLeft ? '' : <NavigationMenu style={Object.assign({}, styles.iconButtonIconStyle)} />;
menuElementLeft = (
<IconButton
style={iconLeftStyle}
iconStyle={styles.iconButtonIconStyle}
iconClassName={iconClassNameLeft}
onTouchTap={this.handleTouchTapLeftIconButton}
>
{child}
</IconButton>
);
}
}
const iconRightStyle = Object.assign({}, styles.iconButtonStyle, {
marginRight: -16,
marginLeft: 'auto',
}, iconStyleRight);
if (iconElementRight) {
let iconElementRightNode = iconElementRight;
switch (iconElementRight.type.muiName) {
case 'IconMenu':
case 'IconButton':
const iconElemRightChildren = iconElementRight.props.children;
const iconButtonIconStyle = !(iconElemRightChildren && iconElemRightChildren.props &&
iconElemRightChildren.props.color) ? styles.iconButtonIconStyle : null;
iconElementRightNode = React.cloneElement(iconElementRight, {
iconStyle: Object.assign({}, iconButtonIconStyle, iconElementRight.props.iconStyle),
});
break;
case 'FlatButton':
iconElementRightNode = React.cloneElement(iconElementRight, {
style: Object.assign({}, styles.flatButton, iconElementRight.props.style),
});
break;
default:
}
menuElementRight = (
<div style={prepareStyles(iconRightStyle)}>
{iconElementRightNode}
</div>
);
} else if (iconClassNameRight) {
menuElementRight = (
<IconButton
style={iconRightStyle}
iconStyle={styles.iconButtonIconStyle}
iconClassName={iconClassNameRight}
onTouchTap={this.handleTouchTapRightIconButton}
/>
);
}
return (
<Paper
{...other}
rounded={false}
className={className}
style={Object.assign({}, styles.root, style)}
zDepth={zDepth}
>
{menuElementLeft}
{titleElement}
{menuElementRight}
{children}
</Paper>
);
}
}
export default AppBar;
|
import del from 'del'
import path from 'path'
import runSequence from 'run-sequence'
import git from 'gulp-git'
import babel from 'gulp-babel'
import bump from 'gulp-bump'
import mocha from 'gulp-mocha'
import filter from 'gulp-filter'
import tagVersion from 'gulp-tag-version'
import webpack from 'gulp-webpack-build'
import mochaPhantomJS from 'gulp-mocha-phantomjs'
export default function (gulp, rootDir) {
var src = `${rootDir}/src`
, test = `${rootDir}/test`
, tools = `${rootDir}/tools`
, dist = `${rootDir}/dist`
, lib = `${rootDir}/lib`
, mochaPhantomConfig = {
phantomjs: {
useColors: true,
settings: {
webSecurityEnabled: false
}
}
}
runSequence.use(gulp)
gulp.task('default', ['watch'])
gulp.task('watch', ['test'], () => {
gulp.watch([src + '/**/*', test + '/**/*'], ['test'])
})
gulp.task('prepublish', ['build'])
gulp.task('build',
(cb) => runSequence('clean', ['copy-nonjs', 'build-js'], cb)
)
gulp.task('test', (cb) => runSequence('build', 'test-browser', cb))
gulp.task('test-browser', ['webpack'], () =>
gulp.src('test/runner.html')
.pipe(mochaPhantomJS(mochaPhantomConfig))
.on('error', onerror)
)
gulp.task('test-node', () => {
gulp.src(['test/**/*.js'])
.pipe(mocha())
.on('error', onerror)
})
gulp.task('webpack', () => {
var stream = gulp.src(path.join(tools, 'webpackConfig.js'))
.pipe(webpack.compile())
.pipe(webpack.format({
version: false,
timings: true
}))
.pipe(webpack.failAfter({
errors: true,
warnings: true
}))
.pipe(gulp.dest(dist))
return stream
})
gulp.task('clean',
(cb) => del(lib, cb)
)
gulp.task('copy-nonjs',
() => gulp.src([`${src}/**/*`, `!${src}/**/*.js`])
.pipe(gulp.dest(lib))
)
gulp.task('build-js',
() => gulp.src(`${src}/**/*.js`)
.pipe(babel({experimental: true}))
.pipe(gulp.dest(lib))
)
/*
* gulp patch # makes v0.1.0 → v0.1.1
* gulp feature # makes v0.1.1 → v0.2.0
* gulp release # makes v0.2.1 → v1.0.0
*/
gulp.task('patch', () => inc('patch') )
gulp.task('feature', () => inc('minor') )
gulp.task('release', () => inc('major') )
function onerror(err) {
console.error(err)
this.emit('end')
}
function inc(importance) {
return gulp.src(['./package.json', './bower.json'])
.pipe(bump({type: importance}))
.pipe(gulp.dest('./'))
.pipe(git.commit('version bump'))
.pipe(filter('package.json'))
.pipe(tagVersion({ prefix: '' }))
}
}
|
const ArrayPrototype = {
Length: struct.PropertyDescriptor({
Get: ($) => $.Internal,
Set: ($, value) => {
$.Internal = value
},
Enumerable: FALSE,
Configurable: FALSE
}),
ForEach($, fn) {
const $R = $.Reflect;
const size = $R.get($, 'Length');
for (let index = 0; index < size; index++) {
const item = $R.get(index);
fn.Reflect.apply(fn, item, index, $);
}
},
Reduce($, fn, initialValue) {
const $R = $.Reflect;
const size = $R.get($, 'Length');
let result = initialValue;
for (let index = 0; index < size; index++) {
const item = $R.get($, index);
result = fn.Reflect.apply(fn, result, item, index, $);
}
return result;
},
Map($, fn) {
const $R = $.Reflect;
const size = $R.get($, 'Length');
let result = [];
for (let index = 0; index < size; index++) {
const item = $R.get($, index);
result.push(fn.Reflect.apply(fn, item, index, $));
}
return ARRAY(...result);
},
Filter($, fn) {
const $R = $.Reflect;
const size = $R.get($, 'Length');
let result = [];
for (let index = 0; index < size; index++) {
const item = $R.get($, index);
if (fn.Reflect.apply(fn, item, index, $)) {
result.push(item);
}
}
return ARRAY(...result);
},
Push: ($, value) => {
const $R = $.Reflect;
const size = $R.get($, 'Length');
$R.set($, size, value);
},
IndexOf($, X) {
const $R = $.Reflect;
const size = $R.get($, 'Length');
for (let index = 0; index < size; index++) {
const item = $R.get($, index);
if (EQUAL(item, X)) {
return index;
}
}
return UNDEFINED;
},
Join($, sep = '') {
const $R = $.Reflect;
const size = $R.get($, 'Length');
let result = '';
for (let index = 0; index < size; index++) {
const item = $R.get($, index);
result += (index ? sep : '') + TO_STRING(item);
}
return result;
},
ToString($) {
return CALL_METHOD($, 'Join', ', ');
}
};
|
/* globals describe it expect */
import {transform} from 'babel-core'
import {Tag} from 'cerebral/tags'
import plugin from '../index'
const pluginOptions = {
babelrc: false,
presets: ['es2015'],
plugins: [plugin]
}
describe('Run optimized tags', () => {
it('should evaluate to a tag', () => {
const code = `
import {state} from 'cerebral/tags';
state\`hello.world\`;
`
const {code: result} = transform(code, pluginOptions)
const tag = eval(result) // eslint-disable-line no-eval
expect(tag).toBeInstanceOf(Tag)
expect(tag).toMatchSnapshot()
})
it('should evaluate to a tag with nested tags', () => {
const code = `
import {state, input} from 'cerebral/tags';
state\`a.\${input\`b\`}\`;
`
const getters = {
state: {
a: {
c: 'Working!'
}
},
input: {
b: 'c'
}
}
const {code: result} = transform(code, pluginOptions)
const tag = eval(result) // eslint-disable-line no-eval
expect(tag).toMatchSnapshot()
expect(tag).toBeInstanceOf(Tag)
expect(tag.getValue(getters)).toEqual(getters.state.a.c)
})
it('should allow to access with expressions in ${}', () => {
const code = `
import {state} from 'cerebral/tags';
const name = 'c';
state\`a.\${name}.\${1+1}\`;
`
const getters = {
state: {
a: {
c: {
2: 'Working!'
}
}
}
}
const {code: result} = transform(code, pluginOptions)
const tag = eval(result) // eslint-disable-line no-eval
expect(tag).toBeInstanceOf(Tag)
expect(tag.getValue(getters)).toEqual(getters.state.a.c[2])
})
})
|
var EPUBJS = EPUBJS || {};
EPUBJS.replace = {};
//-- Replaces the relative links within the book to use our internal page changer
EPUBJS.replace.hrefs = function(callback, renderer){
var book = this;
var replacments = function(link, done){
var href = link.getAttribute("href"),
isRelative = href.search("://"),
directory,
relative,
location,
base,
uri,
url;
if(isRelative != -1){
link.setAttribute("target", "_blank");
}else{
// Links may need to be resolved, such as ../chp1.xhtml
base = renderer.render.docEl.querySelector('base');
url = base.getAttribute("href");
uri = EPUBJS.core.uri(url);
directory = uri.directory;
if(directory) {
// We must ensure that the file:// protocol is preserved for
// local file links, as in certain contexts (such as under
// Titanium), file links without the file:// protocol will not
// work
if (uri.protocol === "file") {
relative = EPUBJS.core.resolveUrl(uri.base, href);
} else {
relative = EPUBJS.core.resolveUrl(directory, href);
}
} else {
relative = href;
}
link.onclick = function(){
book.goto(relative);
return false;
};
}
done();
};
renderer.replace("a[href]", replacments, callback);
};
EPUBJS.replace.head = function(callback, renderer) {
renderer.replaceWithStored("link[href]", "href", EPUBJS.replace.links, callback);
};
//-- Replaces assets src's to point to stored version if browser is offline
EPUBJS.replace.resources = function(callback, renderer){
//srcs = this.doc.querySelectorAll('[src]');
renderer.replaceWithStored("[src]", "src", EPUBJS.replace.srcs, callback);
};
EPUBJS.replace.svg = function(callback, renderer) {
renderer.replaceWithStored("svg image", "xlink:href", function(_store, full, done){
_store.getUrl(full).then(done);
}, callback);
};
EPUBJS.replace.srcs = function(_store, full, done){
_store.getUrl(full).then(done);
};
//-- Replaces links in head, such as stylesheets - link[href]
EPUBJS.replace.links = function(_store, full, done, link){
//-- Handle replacing urls in CSS
if(link.getAttribute("rel") === "stylesheet") {
EPUBJS.replace.stylesheets(_store, full).then(function(url, full){
// done
done(url, full);
}, function(reason) {
// we were unable to replace the style sheets
done(null);
});
}else{
_store.getUrl(full).then(done, function(reason) {
// we were unable to get the url, signal to upper layer
done(null);
});
}
};
EPUBJS.replace.stylesheets = function(_store, full) {
var deferred = new RSVP.defer();
if(!_store) return;
_store.getText(full).then(function(text){
var url;
EPUBJS.replace.cssImports(_store, full, text).then(function (importText) {
text = importText + text;
EPUBJS.replace.cssUrls(_store, full, text).then(function(newText){
var _URL = window.URL || window.webkitURL || window.mozURL;
var blob = new Blob([newText], { "type" : "text\/css" }),
url = _URL.createObjectURL(blob);
deferred.resolve(url);
}, function(reason) {
deferred.reject(reason);
});
},function(reason) {
deferred.reject(reason);
});
}, function(reason) {
deferred.reject(reason);
});
return deferred.promise;
};
EPUBJS.replace.cssImports = function (_store, base, text) {
var deferred = new RSVP.defer();
if(!_store) return;
// check for css @import
var importRegex = /@import\s+(?:url\()?\'?\"?((?!data:)[^\'|^\"^\)]*)\'?\"?\)?/gi;
var importMatches, importFiles = [], allImportText = '';
while (importMatches = importRegex.exec(text)) {
importFiles.push(importMatches[1]);
}
if (importFiles.length === 0) {
deferred.resolve(allImportText);
}
importFiles.forEach(function (fileUrl) {
var full = EPUBJS.core.resolveUrl(base, fileUrl);
full = EPUBJS.core.uri(full).path;
_store.getText(full).then(function(importText){
allImportText += importText;
if (importFiles.indexOf(fileUrl) === importFiles.length - 1) {
deferred.resolve(allImportText);
}
}, function(reason) {
deferred.reject(reason);
});
});
return deferred.promise;
};
EPUBJS.replace.cssUrls = function(_store, base, text){
var deferred = new RSVP.defer(),
promises = [],
matches = text.match(/url\(\'?\"?((?!data:)[^\'|^\"^\)]*)\'?\"?\)/g);
if(!_store) return;
if(!matches){
deferred.resolve(text);
return deferred.promise;
}
matches.forEach(function(str){
var full = EPUBJS.core.resolveUrl(base, str.replace(/url\(|[|\)|\'|\"]|\?.*$/g, ''));
var replaced = _store.getUrl(full).then(function(url){
text = text.replace(str, 'url("'+url+'")');
}, function(reason) {
deferred.reject(reason);
});
promises.push(replaced);
});
RSVP.all(promises).then(function(){
deferred.resolve(text);
});
return deferred.promise;
};
|
window.jermaine.util.namespace("window.ide", function (ns) {
var Project = ns.models.Project,
IDEView = ns.views.IDEView;
var DirectoryView = new window.jermaine.View (function () {
this.hasA("url").which.isA("string");
this.hasAn("ideView").which.validatesWith(function (v) {
return v instanceof ns.views.IDEView;
});
this.isBuiltWith("url", "ideView", function () {
var instance = this.ideView().instance(),
that = this;
$.getJSON(this.url(), function (result) {
var directoryTemplate = Handlebars.compile($("#directory-template").html());
Handlebars.registerPartial("directory-entry", $("#directory-entry-partial").html());
for (i = 0; i < result.length; ++i) {
result[i].name = result[i].url.match(/(.*).json/)[1];
}
$("#IDE-directory").append(directoryTemplate({project:result}));
$(".directory_listing").each(function (i, elt) {
$(elt).click(function () {
that.setActiveMenuItem(this);
return false;
});
});
$("#IDE-editor_button").click(function () {
that.ideView().toggleEditorAndDirectory();
});
$(".edit_sketch_button").click(function () {
that.ideView().toggleEditorAndDirectory();
});
if ($("#ide").hasClass("server")) {
$("#new_sketch_button").click(function () {
if ($("#new_sketch_div").is(":visible")) {
$("#new_sketch_div").slideUp(function () {
$("#new_sketch_input").val("");
});
} else {
$("#new_sketch_div").slideDown();
}
});
$("#new_sketch_input").keypress(function (e) {
if (e.keyCode === 13 && $(this).val() !== "" ) {
if ($(this).val().length > 30) {
that.ideView().instance().messages().add("sketch title can't be more than 30 characters");
} else {
that.createNewSketch($(this).val());
}
}
});
$(".delete_sketch_button").click(function () {
that.deleteSketch($(this).parent("div").attr("id"));
return false;
});
}
if (result.length > 0) {
instance.project(new Project("sketches/" + result[0].url));
} else {
//show directory
that.ideView().toggleEditorAndDirectory();
that.setUpEmptyDirectory();
}
});
});
this.respondsTo("deleteSketch", function (name) {
var that = this;
var instance = this.instance();
if (confirm("Are you sure you want to delete '"+name+"'?")) {
$.post("sketches/"+name+"/delete", function (response) {
if ($("#"+name).hasClass("active")) {
if ($("#"+name).next("div.directory_listing").size() > 0) {
$("#"+name).next("div.directory_listing").trigger("click");
} else if ($("#"+name).prev("div.directory_listing").size() > 0) {
$("#"+name).prev("div.inactive").trigger("click");
} else {
that.setUpEmptyDirectory();
}
}
$("#"+name).fadeOut(function () {
$("#"+name).remove();
});
});
}
});
this.respondsTo("createNewSketch", function (name) {
var that = this,
instance = this.instance(),
directoryEntryTemplate = Handlebars.compile($("#directory-entry-partial").html());
$.post("sketches/new", {"title":name}, function (sketch) {
var p = {"title":sketch.title,"name":sketch.slug,"url":sketch.slug+".json"};
//because this is returning strings on error :(
if (typeof (sketch) === "object") {
var menuEntry = $($.trim(directoryEntryTemplate(p)));
menuEntry.hide();
menuEntry.insertAfter("#new_sketch_div");
if ($("#empty_directory").size() > 0) {
$("#empty_directory").remove();
$("#IDE-editor_button").click(function () {
that.ideView().toggleEditorAndDirectory();
});
}
menuEntry.children(".delete_sketch_button").click(function () {
that.deleteSketch($(this).parent("div").attr("id"));
return false;
});
menuEntry.children(".edit_sketch_button").click(function () {
that.ideView().toggleEditorAndDirectory();
return false;
});
menuEntry.click(function () {
that.setActiveMenuItem(this);
return false;
});
$("#new_sketch_div").fadeOut(function () {
$("#new_sketch_input").val("");
menuEntry.fadeIn(function () {
menuEntry.trigger("click");
});
});
//if there is only one element in the list,
//we need to re-enable the editor button
if ($(".directory_listing").size() === 1) {
$("#IDE-editor_button").click(function () {
that.ideView().toggleEditorAndDirectory();
});
}
} else {
that.ideView().instance().messages().add(sketch);
}
});
});
this.respondsTo("setActiveMenuItem", function (elt) {
var project = this.ideView().instance().project();
if (project !== undefined) {
$("#"+project.url().match(/\/(.*)\.json/)[1])
.removeClass("active")
.addClass("inactive");
}
$(elt).addClass("active").removeClass("inactive");
this.ideView().instance().project(new Project($(elt).find("a").attr("href")));
//this.ideView().toggleEditorAndDirectory();
});
this.respondsTo("setUpEmptyDirectory", function () {
$("#IDE-editor_button").unbind("click");
$("#IDE-title").html(" ");
if (!$("#new_sketch_input").is(":visible")) {
$("#new_sketch_button").trigger("click");
}
});
});
ns.views.DirectoryView = DirectoryView;
});
|
'use strict';
describe('Service: Users', function () {
// load the service's module
beforeEach(module('resourceManagementApp'));
// instantiate service
var Users;
beforeEach(inject(function (_Users_) {
Users = _Users_;
}));
it('should do something', function () {
expect(!!Users).toBe(true);
});
});
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M21 13h-6c-.55 0-1-.45-1-1s.45-1 1-1h6c.55 0 1 .45 1 1s-.45 1-1 1zm0-6h-6c-.55 0-1 .45-1 1s.45 1 1 1h6c.55 0 1-.45 1-1s-.45-1-1-1zm-6 10h6c.55 0 1-.45 1-1s-.45-1-1-1h-6c-.55 0-1 .45-1 1s.45 1 1 1zm-3-8v6c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V9c0-1.1.9-2 2-2h6c1.1 0 2 .9 2 2zm-2.1 5.2l-1.26-1.68c-.2-.26-.59-.27-.8-.01L6.5 14.26l-.85-1.03c-.2-.25-.58-.24-.78.01l-.74.95c-.26.33-.02.81.39.81H9.5c.41 0 .65-.47.4-.8z" />
, 'ArtTrackRounded');
|
#!/usr/bin/env node
var fs = require('fs')
var path = require('path')
var mkdirp = require('mkdrip')
var minimist = require('minimist')
var level = require('level')
var strftime = require('strftime')
var sprintf = require('sprintf')
var through = require('through')
var argv = minimist(process.argv.slice(2))
var HOME = process.env.HOME || process.env.USERPROFILE
var datadir = argv.d || path.join(HOME, '.todo')
mkdirp.sync(datadir)
var db = level(path.join(datadir, 'db'), { encoding: 'json' })
if (argv.h) usage(0)
else if (argv._[0] === 'add') {
}
else if (argv._[0] === 'rm') {
}
else if (argv._[0] === 'done') {
}
else if (argv._[0] === 'list') {
}
else if (argv._[0] === 'destroy') {
}
else usage(1) |
import Walk from './Walk'
export default Walk
|
import React from 'react';
import { Provider } from 'react-redux';
import PlayerList from '../../client/components/player_list';
import { store } from '../../client/store';
import { mockData } from '../mockData';
describe('PlayerList', () => {
let mockMove = jest.fn();
let wrapper = shallow( <PlayerList searchValue={''} all={false} move={mockMove}/> );
test('should match the snapshot', () => {
expect(wrapper).toMatchSnapshot();
});
test('should not render the CreatePlayer component if all is false', () => {
expect(wrapper.find('CreatePlayer').length).toBe(0);
});
test('should render Components correctly based on props', () => {
expect(wrapper.find('CreatePlayer').length).toBe(0);
expect(wrapper.find('PlayerListItem').length).toBe(0);
wrapper.setProps({
all: true,
players: mockData.players
});
expect(wrapper).toMatchSnapshot();
expect(wrapper.find('Connect(CreatePlayer)').length).toBe(1);
expect(wrapper.find('PlayerListItem').length).toBe(3);
});
});
|
function Person(firstName, lastName) { //Function constructor is just sintax sugar :/
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype.getFullName = function () { //function.prototype is not the __proto__ object and it is safe to use
return `${this.firstName} ${this.lastName}`;
}
var gui = new Person("Guilherme", "de Castro");
console.log(gui.getFullName());
var dimi = new Person("Dimitrius", "Gabriel de Paiva");
console.log(dimi.getFullName());
console.log({} instanceof Person); //Nope
console.log(dimi instanceof Person); //Hell yeah |
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import * as mutations from './mutations'
import {localStoragePlugin} from '../plugin/localStoragePlugin'
Vue.use(Vuex)
export const store = new Vuex.Store({
state,
mutations,
plugins: [localStoragePlugin]
})
export const dispatch = store.dispatch
export const commit = store.commit
|
'use strict';
/* jshint ignore:start */
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
/* jshint ignore:end */
var _ = require('lodash'); /* jshint ignore:line */
var Holodeck = require('../../../../../holodeck'); /* jshint ignore:line */
var Request = require(
'../../../../../../../lib/http/request'); /* jshint ignore:line */
var Response = require(
'../../../../../../../lib/http/response'); /* jshint ignore:line */
var RestException = require(
'../../../../../../../lib/base/RestException'); /* jshint ignore:line */
var Twilio = require('../../../../../../../lib'); /* jshint ignore:line */
var client;
var holodeck;
describe('ExecutionContext', function() {
beforeEach(function() {
holodeck = new Holodeck();
client = new Twilio('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', 'AUTHTOKEN', {
httpClient: holodeck
});
});
it('should generate valid fetch request',
function() {
holodeck.mock(new Response(500, '{}'));
var promise = client.studio.v1.flows('FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.executions('FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.executionContext().fetch();
promise = promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
});
promise.done();
var solution = {
flowSid: 'FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
executionSid: 'FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
};
var url = _.template('https://studio.twilio.com/v1/Flows/<%= flowSid %>/Executions/<%= executionSid %>/Context')(solution);
holodeck.assertHasRequest(new Request({
method: 'GET',
url: url
}));
}
);
it('should generate valid fetch response',
function() {
var body = JSON.stringify({
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'context': {
'foo': 'bar'
},
'flow_sid': 'FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'execution_sid': 'FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'url': 'https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Context'
});
holodeck.mock(new Response(200, body));
var promise = client.studio.v1.flows('FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.executions('FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.executionContext().fetch();
promise = promise.then(function(response) {
expect(response).toBeDefined();
}, function() {
throw new Error('failed');
});
promise.done();
}
);
});
|
import coreComponentTests from './core-component-tests';
import { moduleForComponent, test } from 'ember-qunit';
let component;
moduleForComponent('spotify-follow-button', 'Unit | Component | spotify follow button', {
unit: true,
setup() {
component = this.subject();
},
});
test('It has the core Spotify component functionality', function(assert) {
let element;
assert.expect(18);
coreComponentTests(this, assert, component, {
expectedBaseUrl: '//embed.spotify.com/follow/1',
expectedClassName: 'spotify-follow-button',
expectedSize: 'basic',
expectedTheme: 'dark',
});
element = component.get('element');
assert.equal(element.getAttribute('scrolling'), 'no',
'Should not allow for scrolling in iframe');
});
test('It resizes based on size attribute', function(assert) {
assert.equal(component.get('height'), 25,
"Should have the default height with size='compact'");
assert.equal(component.get('width'), 200,
"Should have the default width with size='compact'");
component.set('size', 'detail');
assert.equal(component.get('height'), 56,
"Should have the new height with size='large'");
assert.equal(component.get('width'), 300,
"Should have the new width with size='large'");
});
|
!
function (a) {
"use strict";
"function" == typeof define && define.amd ? define(["jquery", "../grid.base"], a) : a(jQuery)
}(function (a) {
a.jgrid = a.jgrid || {},
a.jgrid.hasOwnProperty("regional") || (a.jgrid.regional = []),
a.jgrid.regional.en = {
defaults: {
recordtext: "正在浏览{0}-{1},共{2}",
emptyrecords: "没有数据",
loadtext: "载入中...",
savetext: "正在保存...",
pgtext: "第 {0} 页 {1}",
pgfirst: "第一页",
pglast: "最后一页",
pgnext: "下一页",
pgprev: "上一页",
pgrecs: "Records per Page",
showhide: "Toggle Expand Collapse Grid",
pagerCaption: "Grid::Page Settings",
pageText: "Page:",
recordPage: "Records per Page",
nomorerecs: "No more records...",
scrollPullup: "Pull up to load more...",
scrollPulldown: "Pull down to refresh...",
scrollRefresh: "Release to refresh..."
},
search: {
caption: "查找记录...",
Find: "查找",
Reset: "重置",
odata: [{
oper: "eq",
text: "等于"
},
{
oper: "ne",
text: "不等于"
},
{
oper: "lt",
text: "小于"
},
{
oper: "le",
text: "小于等于"
},
{
oper: "gt",
text: "大于"
},
{
oper: "ge",
text: "大于等于"
},
{
oper: "bw",
text: "开始于"
},
{
oper: "bn",
text: "不开始于"
},
{
oper: "in",
text: "包含"
},
{
oper: "ni",
text: "不包含"
},
{
oper: "ew",
text: "结束于"
},
{
oper: "en",
text: "不结束于"
},
{
oper: "cn",
text: "包含"
},
{
oper: "nc",
text: "不结束于"
},
{
oper: "nu",
text: "为空"
},
{
oper: "nn",
text: "不为空"
}],
groupOps: [{
op: "AND",
text: "所有"
},
{
op: "OR",
text: "任一"
}],
operandTitle: "Click to select search operation.",
resetTitle: "Reset Search Value"
},
edit: {
addCaption: "增加",
editCaption: "编辑",
bSubmit: "确定",
bCancel: "取消",
bClose: "关闭",
saveData: "Data has been changed! Save changes?",
bYes: "是",
bNo: "否",
bExit: "取消",
msg: {
required: "必填项",
number: "请输入有效数字",
minValue: "value must be greater than or equal to ",
maxValue: "value must be less than or equal to",
email: "不是有效邮箱地址is not a valid e-mail",
integer: "请输入有效数字",
date: "请输入有效日期",
url: "不是一个有效链接,链接必须以'http://'或者'https://'开头",
nodefined: " is not defined!",
novalue: " return value is required!",
customarray: "Custom function should return array!",
customfcheck: "Custom function should be present in case of custom checking!"
}
},
view: {
caption: "查看",
bClose: "关闭"
},
del: {
caption: "删除",
msg: "确定要删除吗?",
bSubmit: "删除",
bCancel: "取消"
},
nav: {
edittext: "",
edittitle: "编辑所选",
addtext: "",
addtitle: "添加",
deltext: "",
deltitle: "删除所选",
searchtext: "",
searchtitle: "查找",
refreshtext: "",
refreshtitle: "刷新",
alertcap: "警告",
alerttext: "请先选择",
viewtext: "",
viewtitle: "查看所选",
savetext: "",
savetitle: "保存",
canceltext: "",
canceltitle: "取消编辑",
selectcaption: "Actions..."
},
col: {
caption: "选择列",
bSubmit: "确定",
bCancel: "取消"
},
errors: {
errcap: "错误",
nourl: "No url is set",
norecords: "No records to process",
model: "Length of colNames <> colModel!"
},
formatter: {
integer: {
thousandsSeparator: ",",
defaultValue: "0"
},
number: {
decimalSeparator: ".",
thousandsSeparator: ",",
decimalPlaces: 2,
defaultValue: "0.00"
},
currency: {
decimalSeparator: ".",
thousandsSeparator: ",",
decimalPlaces: 2,
prefix: "",
suffix: "",
defaultValue: "0.00"
},
date: {
dayNames: ["Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
monthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
AmPm: ["am", "pm", "AM", "PM"],
S: function (a) {
return 11 > a || a > 13 ? ["st", "nd", "rd", "th"][Math.min((a - 1) % 10, 3)] : "th"
},
srcformat: "Y-m-d",
newformat: "n/j/Y",
parseRe: /[#%\\\/:_;.,\t\s-]/,
masks: {
ISO8601Long: "Y-m-d H:i:s",
ISO8601Short: "Y-m-d",
ShortDate: "n/j/Y",
LongDate: "l, F d, Y",
FullDateTime: "l, F d, Y g:i:s A",
MonthDay: "F d",
ShortTime: "g:i A",
LongTime: "g:i:s A",
SortableDateTime: "Y-m-d\\TH:i:s",
UniversalSortableDateTime: "Y-m-d H:i:sO",
YearMonth: "F, Y"
},
reformatAfterEdit: !1,
userLocalTime: !1
},
baseLinkUrl: "",
showAction: "",
target: "",
checkbox: {
disabled: !0
},
idName: "id"
}
}
}); |
(function() {
var getFortune, http;
http = require("http");
exports.getFortune = getFortune = function(callback) {
var opts, request;
opts = {
host: "www.fortunefortoday.com",
path: "/getfortuneonly.php"
};
request = http.request(opts, function(response) {
var data;
data = "";
response.on("data", function(chunk) {
return data += chunk;
});
response.on("end", function() {
var body;
data = data.replace(/(\r\n|\n|\r)/gm, "");
data = data.replace(/\s\s+/g, " ");
body = data;
if (!body) {
return callback("Could not find fortune");
} else {
return callback(null, body);
}
});
return response.on("error", function(error) {
return callback(error);
});
});
request.on("error", function(error) {
return callback(error);
});
return request.end();
};
}).call(this);
|
/* eslint-disable no-undef */
document.addEventListener('DOMContentLoaded', () => {
const setChatTarget = (target) => {
if (!target) {
target = 'Channel'
}
dom('.chat_target').text(target)
}
/***
* This is more like a confidence setup
* for the interface. It does not really help
* with the chat functionality.
*/
/**
* Before we start hide the error
* message.
*/
dom('.connection_alert').hide()
dom('.client_chat').on('keyup', (evt) => {
if (evt.target.value.length > 0) {
registerTyping(true)
} else {
registerTyping(false)
}
})
/**
* Just to make it feel like a real chat.
* Send the message if enter has been pressed.
*/
dom('.client_chat').on('keypress', (evt) => {
if (evt.key === 'Enter') {
sendMessage()
}
})
dom('.user_list').on('change', (evt) => {
const list = evt.target
let to = null
if (list.selectedIndex >= 0) {
to = list.options[list.selectedIndex].text
}
setChatTarget(to)
})
/**
* Submit has been pressed execute sending
* to server.
*/
dom('.btn-send.chat_btn').on('click', () => {
sendMessage()
registerTyping(false)
})
setChatTarget()
})
/* eslint-enable no-undef */
|
const debug = require('ghost-ignition').debug('services:url:resources'),
Promise = require('bluebird'),
_ = require('lodash'),
Resource = require('./Resource'),
config = require('../../config'),
models = require('../../models'),
common = require('../../lib/common');
/**
* These are the default resources and filters.
* These are the minimum filters for public accessibility of resources.
*/
const resourcesConfig = [
{
type: 'posts',
modelOptions: {
modelName: 'Post',
filter: 'visibility:public+status:published+page:false',
exclude: [
'title',
'mobiledoc',
'html',
'plaintext',
'amp',
'codeinjection_head',
'codeinjection_foot',
'meta_title',
'meta_description',
'custom_excerpt',
'og_image',
'og_title',
'og_description',
'twitter_image',
'twitter_title',
'twitter_description',
'custom_template',
'feature_image',
'locale'
],
withRelated: ['tags', 'authors'],
withRelatedPrimary: {
primary_tag: 'tags',
primary_author: 'authors'
},
withRelatedFields: {
tags: ['tags.id', 'tags.slug'],
authors: ['users.id', 'users.slug']
}
},
events: {
add: 'post.published',
update: 'post.published.edited',
remove: 'post.unpublished'
}
},
{
type: 'pages',
modelOptions: {
modelName: 'Post',
exclude: [
'title',
'mobiledoc',
'html',
'plaintext',
'amp',
'codeinjection_head',
'codeinjection_foot',
'meta_title',
'meta_description',
'custom_excerpt',
'og_image',
'og_title',
'og_description',
'twitter_image',
'twitter_title',
'twitter_description',
'custom_template',
'feature_image',
'locale',
'tags',
'authors',
'primary_tag',
'primary_author'
],
filter: 'visibility:public+status:published+page:true'
},
events: {
add: 'page.published',
update: 'page.published.edited',
remove: 'page.unpublished'
}
},
{
type: 'tags',
keep: ['id', 'slug', 'updated_at', 'created_at'],
modelOptions: {
modelName: 'Tag',
exclude: [
'description',
'meta_title',
'meta_description'
],
filter: 'visibility:public'
},
events: {
add: 'tag.added',
update: 'tag.edited',
remove: 'tag.deleted'
}
},
{
type: 'users',
modelOptions: {
modelName: 'User',
exclude: [
'bio',
'website',
'location',
'facebook',
'twitter',
'accessibility',
'meta_title',
'meta_description',
'tour'
],
filter: 'visibility:public'
},
events: {
add: 'user.activated',
update: 'user.activated.edited',
remove: 'user.deactivated'
}
}
];
/**
* NOTE: We are querying knex directly, because the Bookshelf ORM overhead is too slow.
*/
class Resources {
constructor(queue) {
this.queue = queue;
this.data = {};
this.listeners = [];
this._listeners();
}
_listenOn(eventName, listener) {
this.listeners.push({
eventName: eventName,
listener: listener
});
common.events.on(eventName, listener);
}
_listeners() {
/**
* We fetch the resources as early as possible.
* Currently the url service needs to use the settings cache,
* because we need to `settings.permalink`.
*/
this._listenOn('db.ready', this._onDatabaseReady.bind(this));
}
_onDatabaseReady() {
const ops = [];
debug('db ready. settings cache ready.');
_.each(resourcesConfig, (resourceConfig) => {
this.data[resourceConfig.type] = [];
ops.push(this._fetch(resourceConfig));
this._listenOn(resourceConfig.events.add, (model) => {
return this._onResourceAdded.bind(this)(resourceConfig.type, model);
});
this._listenOn(resourceConfig.events.update, (model) => {
return this._onResourceUpdated.bind(this)(resourceConfig.type, model);
});
this._listenOn(resourceConfig.events.remove, (model) => {
return this._onResourceRemoved.bind(this)(resourceConfig.type, model);
});
});
Promise.all(ops)
.then(() => {
// CASE: all resources are fetched, start the queue
this.queue.start({
event: 'init',
tolerance: 100,
requiredSubscriberCount: 1
});
});
}
_fetch(resourceConfig, options = {offset: 0, limit: 999}) {
debug('_fetch', resourceConfig.type, resourceConfig.modelOptions);
let modelOptions = _.cloneDeep(resourceConfig.modelOptions);
const isSQLite = config.get('database:client') === 'sqlite3';
// CASE: prevent "too many SQL variables" error on SQLite3
if (isSQLite) {
modelOptions.offset = options.offset;
modelOptions.limit = options.limit;
}
return models.Base.Model.raw_knex.fetchAll(modelOptions)
.then((objects) => {
debug('fetched', resourceConfig.type, objects.length);
_.each(objects, (object) => {
this.data[resourceConfig.type].push(new Resource(resourceConfig.type, object));
});
if (objects.length && isSQLite) {
options.offset = options.offset + options.limit;
return this._fetch(resourceConfig, {offset: options.offset, limit: options.limit});
}
});
}
_onResourceAdded(type, model) {
const resourceConfig = _.find(resourcesConfig, {type: type});
const exclude = resourceConfig.modelOptions.exclude;
const withRelatedFields = resourceConfig.modelOptions.withRelatedFields;
const obj = _.omit(model.toJSON(), exclude);
if (withRelatedFields) {
_.each(withRelatedFields, (fields, key) => {
if (!obj[key]) {
return;
}
obj[key] = _.map(obj[key], (relation) => {
const relationToReturn = {};
_.each(fields, (field) => {
const fieldSanitized = field.replace(/^\w+./, '');
relationToReturn[fieldSanitized] = relation[fieldSanitized];
});
return relationToReturn;
});
});
const withRelatedPrimary = resourceConfig.modelOptions.withRelatedPrimary;
if (withRelatedPrimary) {
_.each(withRelatedPrimary, (relation, primaryKey) => {
if (!obj[primaryKey] || !obj[relation]) {
return;
}
const targetTagKeys = Object.keys(obj[relation].find((item) => {return item.id === obj[primaryKey].id;}));
obj[primaryKey] = _.pick(obj[primaryKey], targetTagKeys);
});
}
}
const resource = new Resource(type, obj);
debug('_onResourceAdded', type);
this.data[type].push(resource);
this.queue.start({
event: 'added',
action: 'added:' + model.id,
eventData: {
id: model.id,
type: type
}
});
}
/**
* CASE:
* - post was fetched on bootstrap
* - that means, the post is already published
* - resource exists, but nobody owns it
* - if the model changes, it can be that somebody will then own the post
*
* CASE:
* - post was fetched on bootstrap
* - that means, the post is already published
* - resource exists and is owned by somebody
* - but the data changed and is maybe no longer owned?
* - e.g. featured:false changes and your filter requires featured posts
*/
_onResourceUpdated(type, model) {
debug('_onResourceUpdated', type);
this.data[type].every((resource) => {
if (resource.data.id === model.id) {
const resourceConfig = _.find(resourcesConfig, {type: type});
const exclude = resourceConfig.modelOptions.exclude;
const withRelatedFields = resourceConfig.modelOptions.withRelatedFields;
const obj = _.omit(model.toJSON(), exclude);
if (withRelatedFields) {
_.each(withRelatedFields, (fields, key) => {
if (!obj[key]) {
return;
}
obj[key] = _.map(obj[key], (relation) => {
const relationToReturn = {};
_.each(fields, (field) => {
const fieldSanitized = field.replace(/^\w+./, '');
relationToReturn[fieldSanitized] = relation[fieldSanitized];
});
return relationToReturn;
});
});
const withRelatedPrimary = resourceConfig.modelOptions.withRelatedPrimary;
if (withRelatedPrimary) {
_.each(withRelatedPrimary, (relation, primaryKey) => {
if (!obj[primaryKey] || !obj[relation]) {
return;
}
const targetTagKeys = Object.keys(obj[relation].find((item) => {return item.id === obj[primaryKey].id;}));
obj[primaryKey] = _.pick(obj[primaryKey], targetTagKeys);
});
}
}
resource.update(obj);
// CASE: pretend it was added
if (!resource.isReserved()) {
this.queue.start({
event: 'added',
action: 'added:' + model.id,
eventData: {
id: model.id,
type: type
}
});
}
// break!
return false;
}
return true;
});
}
_onResourceRemoved(type, model) {
let index = null;
let resource;
this.data[type].every((_resource, _index) => {
if (_resource.data.id === model._previousAttributes.id) {
resource = _resource;
index = _index;
// break!
return false;
}
return true;
});
// CASE: there are possible cases that the resource was not fetched e.g. visibility is internal
if (index === null) {
debug('can\'t find resource', model._previousAttributes.id);
return;
}
this.data[type].splice(index, 1);
resource.remove();
}
getAll() {
return this.data;
}
getAllByType(type) {
return this.data[type];
}
getByIdAndType(type, id) {
return _.find(this.data[type], {data: {id: id}});
}
reset() {
_.each(this.listeners, (obj) => {
common.events.removeListener(obj.eventName, obj.listener);
});
this.listeners = [];
this.data = {};
}
softReset() {
this.data = {};
_.each(resourcesConfig, (resourceConfig) => {
this.data[resourceConfig.type] = [];
});
}
}
module.exports = Resources;
|
'use strict';
import React from 'react';
import Heading from 'app/components/common/Heading';
import Board from 'app/components/productivity/boards/Show';
import { Row } from 'antd';
import _ from 'lodash';
const GroupShow = (props) => {
const { group, boards } = props;
const currentBoards = _.filter( boards, { group: group.id } );
return (
<div key={ group.id } className="item_group">
<Heading
title={ group.name }
subtitle={ group.description } />
{ currentBoards.length > 0 &&
<Row type="flex" className="component__productivity__board m-t-30">
{ currentBoards.map( board => <Board key={board.id} data={board} /> )}
</Row>
}
{ currentBoards.length < 1 &&
<div className="empty">
<p>No boards have been added/associated with this group yet.</p>
<p>As soon as you associate any Board with this Group, It will appear here.</p>
</div>
}
</div>
)
}
export default GroupShow;
|
class skbmonitor_keystrokemonitor {
constructor() {
}
// System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
CreateObjRef() {
}
// bool Equals(System.Object obj)
Equals() {
}
// int GetHashCode()
GetHashCode() {
}
// System.Object GetLifetimeService()
GetLifetimeService() {
}
// type GetType()
GetType() {
}
// System.Object InitializeLifetimeService()
InitializeLifetimeService() {
}
// string ToString()
ToString() {
}
}
module.exports = skbmonitor_keystrokemonitor;
|
var request = require('request'),
querystring = require('querystring');
exports.worker = function (task, config) {
var input = JSON.parse(task.config.input);
console.log(task.config.input);
var q = {
q: 'select * from search.termextract where context=' + JSON.stringify(input.text),
format: "json",
diagnostics: "false"
};
var url = "http://query.yahooapis.com/v1/public/yql?" + querystring.stringify(q);
request(url, function (error, response, body) {
console.log("Got response. Code = " + response.statusCode);
if (!error && response.statusCode === 200) {
var result = JSON.parse(body).query.results.Result;
var results = [];
if (Array.isArray(result)) {
results = result.map(function (i) { return {content: i}; });
}
task.respondCompleted({
terms: results
});
}
});
};
|
/**
* Created by bryangill on 12/23/16.
*/
var rest = require('restling');
var utilityService = require('./UtilityService');
var parser = require("./ParserService");
var _ = require('lodash');
var S = require('string');
module.exports = {
win: function (file_id, team_short_name) {
/* this method determines whether a team has won for a given game */
"use strict";
var result = false;
return new Promise(function (resolve, reject) {
try {
Team.getFullname(team_short_name)
.then(function (team_full_name) {
Game.find({file_id: file_id, winning_team: team_full_name})
.then(function (game) {
if (game) {
result = true;
}
resolve(result);
})
})
} catch (error) {
sails.log.error(error);
reject(error);
}
})
},
loss: function (file_id, team_short_name) {
/* this method determines whether a team has lost for a given game */
"use strict";
var result = false;
return new Promise(function (resolve, reject) {
try {
Team.getFullname(team_short_name)
.then(function (team_full_name) {
Game.find({file_id: file_id, losing_team: team_full_name})
.then(function (game) {
if (game) {
result = true;
}
resolve(result);
})
})
} catch (error) {
sails.log.error(error);
reject(error);
}
})
},
model_object: function (model) {
"use strict";
var self = this;
var promise = new Promise(function (resolve, reject) {
var obj = {
game_id: model.filename,
date: model.date_of_game,
home_team: model.match_up.substr(model.match_up.indexOf(' at ')+4, model.match_up.length),
home_score: model.score.substr(model.score.lastIndexOf('-')+1, model.score.length),
visiting_team: model.match_up.substr(0, model.match_up.indexOf(' at ')),
visiting_score: model.score.substr(model.match_up.indexOf(': ')-2, model.match_up.indexOf(': ')+2),
winning_team: "",
losing_team: "",
winning_score: "",
losing_score: ""
}
obj.home_score = self.determineHomeScore(obj, model);
obj.visiting_score = self.determineVisitingScore(obj, model);
obj.winning_team = self.determineWinner(obj);
obj.losing_team = self.determineLoser(obj);
obj.winning_score = self.determineWinningScore(obj);
obj.losing_score = self.determineLosingScore(obj);
res.model = obj;
resolve(res);
});
return promise;
},
determineHomeScore: function (obj, model) {
"use strict";
try {
var winner = model.score.substr(0, model.score.indexOf('WIN:')-1);
if (S(obj.home_team.toLowerCase()).contains(winner.toLowerCase())) {
return model.score.substring(model.score.indexOf(': ')+2, model.score.lastIndexOf('-'));
} else {
return model.score.substring(model.score.lastIndexOf('-')+1, model.score.length);
}
} catch (error) {
sails.log.error(error);
}
},
determineVisitingScore: function (obj, model) {
"use strict";
try {
var winner = model.score.substr(0, model.score.indexOf('WIN:')-1);
if (S(obj.visiting_team.toLowerCase()).contains(winner.toLowerCase())) {
return model.score.substring(model.score.indexOf(': ')+2, model.score.lastIndexOf('-'));
} else {
return model.score.substring(model.score.lastIndexOf('-')+1, model.score.length);
}
} catch (error) {
sails.log.error(error);
}
},
determineWinner: function (obj) {
"use strict";
if (S(obj.home_score).toInt() > S(obj.visiting_score).toInt()) {
return obj.home_team;
} else {
return obj.visiting_team;
}
},
determineWinningScore: function (obj) {
"use strict";
if (S(obj.home_score).toInt() > S(obj.visiting_score).toInt()) {
return S(obj.home_score).toInt();
} else {
return S(obj.visiting_score).toInt();
}
},
determineLoser: function (obj) {
"use strict";
if (S(obj.home_score).toInt() > S(obj.visiting_score).toInt()) {
return obj.visiting_team;
} else {
return obj.home_team;
}
},
determineLosingScore: function (obj) {
"use strict";
if (S(obj.home_score).toInt() > S(obj.visiting_score).toInt()) {
return S(obj.visiting_score).toInt();
} else {
return S(obj.home_score).toInt();
}
},
};
|
import * as types from './types';
export const authToHttp = urls => fetchFunc => {
const { login, signup, verify } = urls;
const next = (type, params) => {
const init = {
method: 'POST',
body: JSON.stringify(params),
headers: new Headers({ 'Content-Type': 'application/json' }),
};
switch (type) {
case types.VERIFY:
if (localStorage.getItem('token')) {
return fetchFunc(verify, init);
}
return Promise.resolve({ error: { detail: 'No token' } });
case types.LOGIN:
return fetchFunc(login, init);
case types.SIGNUP:
return fetchFunc(signup, init);
case types.LOGOUT:
localStorage.removeItem('token');
return Promise.resolve({ response: true });
default:
throw new Error('Unknow method in simpleTokenAuthProvider');
}
};
return next;
};
|
beforeEach(function() {
});
afterEach(function () {
$("#spec-dom").html("");
});
|
import { takeEvery, apply, put } from 'redux-saga/effects';
import {
fetchUserFollowDetailSuccess,
fetchUserFollowDetailFailure,
} from '../actions/userFollowDetail';
import { addError } from '../actions/error';
import pixiv from '../helpers/apiClient';
import { USER_FOLLOW_DETAIL } from '../constants/actionTypes';
export function* handleFetchUserFollowDetail(action) {
const { userId } = action.payload;
try {
const response = yield apply(pixiv, pixiv.userFollowDetail, [userId]);
yield put(fetchUserFollowDetailSuccess(response.follow_detail, userId));
} catch (err) {
yield put(fetchUserFollowDetailFailure(userId));
yield put(addError(err));
}
}
export function* watchFetchUserFollowDetail() {
yield takeEvery(USER_FOLLOW_DETAIL.REQUEST, handleFetchUserFollowDetail);
}
|
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { VueLoaderPlugin } = require('vue-loader')
module.exports = (env, { mode = 'production' }) => {
const isProd = mode === 'production'
return {
mode: mode,
devtool: 'cheap-module-source-map',
entry: {
main: './example/webpack-entry.ts',
},
output: {
path: path.resolve(__dirname, './example/dist'),
filename: isProd ? '[name].[contenthash].js' : '[name].js',
},
resolve: {
extensions: ['.ts', '.js'],
mainFields: ['module', 'main'],
alias: {
vue$: isProd
? 'vue/dist/vue.esm-browser.prod.js'
: 'vue/dist/vue.esm-browser.js'
},
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
},
{
test: /\.ts$/,
loader: 'ts-loader',
options: {
appendTsSuffixTo: [/\.vue$/],
}
},
{
test: /\.svg$/,
loader: 'file-loader',
},
],
},
plugins: [
new VueLoaderPlugin(),
new HtmlWebpackPlugin({
template: 'example/webpack.html',
minify: {
minifyCSS: true,
collapseWhitespace: true,
keepClosingSlash: true,
removeComments: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
useShortDoctype: true,
},
}),
],
devServer: {
hot: 'only',
client: {
overlay: true,
progress: true,
},
historyApiFallback: true,
},
}
}
|
var sirmutex_8h =
[
[ "_sirmutex_create", "d0/dfe/group__intern.html#gabb7fa2627bf9b269840231c50723c34e", null ],
[ "_sirmutex_destroy", "d0/dfe/group__intern.html#ga5ac9f33affaf105f0476bf022f7b42ef", null ],
[ "_sirmutex_lock", "d0/dfe/group__intern.html#ga1f350df79dd4baa18a77e115384fe04e", null ],
[ "_sirmutex_trylock", "d0/dfe/group__intern.html#ga218de99ef58f518efdb6204876a10a29", null ],
[ "_sirmutex_unlock", "d0/dfe/group__intern.html#gac71abdf9aec294011fe8492bd74d875d", null ]
]; |
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
var src = [
'./src/cookies-mirror.module.js',
'./src/**/*.js'
];
var dist = 'angular-cookies-mirror.js';
gulp.task('default', function(){
return gulp
.src(src)
.pipe(plugins.sourcemaps.init())
.pipe(plugins.concat(dist))
.pipe(plugins.ngAnnotate({
remove: true,
add: true,
single_quotes: true
}))
.pipe(gulp.dest('./'))
.pipe(plugins.uglify())
.pipe(plugins.rename({
suffix: '.min'
}))
.pipe(gulp.dest('./'))
.pipe(plugins.sourcemaps.write())
.pipe(plugins.rename({
suffix: '.sourcemaps'
}))
.pipe(gulp.dest('./'));
}); |
import React from "react";
import clone from "clone";
import PropTypes from "prop-types";
export default class TableDragSelect extends React.Component {
static propTypes = {
value: props => {
const error = new Error(
"Invalid prop `value` supplied to `TableDragSelect`. Validation failed."
);
if (!Array.isArray(props.value)) {
return error;
}
if (props.value.length === 0) {
return;
}
const columnCount = props.value[0].length;
for (const row of props.value) {
if (!Array.isArray(row) || row.length !== columnCount) {
return error;
}
for (const cell of row) {
if (typeof cell !== "boolean") {
return error;
}
}
}
},
maxRows: PropTypes.number,
maxColumns: PropTypes.number,
onSelectionStart: PropTypes.func,
onInput: PropTypes.func,
onChange: PropTypes.func,
children: props => {
if (TableDragSelect.propTypes.value(props)) {
return; // Let error be handled elsewhere
}
const error = new Error(
"Invalid prop `children` supplied to `TableDragSelect`. Validation failed."
);
const trs = React.Children.toArray(props.children);
const rowCount = props.value.length;
const columnCount = props.value.length === 0 ? 0 : props.value[0].length;
if (trs.length !== rowCount) {
return error;
}
for (const tr of trs) {
const tds = React.Children.toArray(tr.props.children);
if (tr.type !== "tr" || tds.length !== columnCount) {
return error;
}
for (const td of tds) {
if (td.type !== "td") {
return error;
}
}
}
}
};
static defaultProps = {
value: [],
maxRows: Infinity,
maxColumns: Infinity,
onSelectionStart: () => {},
onInput: () => {},
onChange: () => {}
};
state = {
selectionStarted: false,
startRow: null,
startColumn: null,
endRow: null,
endColumn: null,
addMode: null
};
componentDidMount = () => {
window.addEventListener("mouseup", this.handleTouchEndWindow);
window.addEventListener("touchend", this.handleTouchEndWindow);
};
componentWillUnmount = () => {
window.removeEventListener("mouseup", this.handleTouchEndWindow);
window.removeEventListener("touchend", this.handleTouchEndWindow);
};
render = () => {
return (
<table className="table-drag-select">
<tbody>{this.renderRows()}</tbody>
</table>
);
};
renderRows = () =>
React.Children.map(this.props.children, (tr, i) => {
return (
<tr key={i} {...tr.props}>
{React.Children.map(tr.props.children, (cell, j) => (
<Cell
key={j}
onTouchStart={this.handleTouchStartCell}
onTouchMove={this.handleTouchMoveCell}
selected={this.props.value[i][j]}
beingSelected={this.isCellBeingSelected(i, j)}
{...cell.props}
>
{cell.props.children}
</Cell>
))}
</tr>
);
});
handleTouchStartCell = e => {
const isLeftClick = e.button === 0;
const isTouch = e.type !== "mousedown";
if (!this.state.selectionStarted && (isLeftClick || isTouch)) {
e.preventDefault();
const { row, column } = eventToCellLocation(e);
this.props.onSelectionStart({ row, column });
this.setState({
selectionStarted: true,
startRow: row,
startColumn: column,
endRow: row,
endColumn: column,
addMode: !this.props.value[row][column]
});
}
};
handleTouchMoveCell = e => {
if (this.state.selectionStarted) {
e.preventDefault();
const { row, column } = eventToCellLocation(e);
const { startRow, startColumn, endRow, endColumn } = this.state;
if (endRow !== row || endColumn !== column) {
const nextRowCount =
startRow === null && endRow === null
? 0
: Math.abs(row - startRow) + 1;
const nextColumnCount =
startColumn === null && endColumn === null
? 0
: Math.abs(column - startColumn) + 1;
if (nextRowCount <= this.props.maxRows) {
this.setState({ endRow: row });
}
if (nextColumnCount <= this.props.maxColumns) {
this.setState({ endColumn: column });
}
}
}
};
handleTouchEndWindow = e => {
const isLeftClick = e.button === 0;
const isTouch = e.type !== "mousedown";
if (this.state.selectionStarted && (isLeftClick || isTouch)) {
const value = clone(this.props.value);
const minRow = Math.min(this.state.startRow, this.state.endRow);
const maxRow = Math.max(this.state.startRow, this.state.endRow);
for (let row = minRow; row <= maxRow; row++) {
const minColumn = Math.min(
this.state.startColumn,
this.state.endColumn
);
const maxColumn = Math.max(
this.state.startColumn,
this.state.endColumn
);
for (let column = minColumn; column <= maxColumn; column++) {
value[row][column] = this.state.addMode;
}
}
this.setState({ selectionStarted: false });
this.props.onChange(value);
}
};
isCellBeingSelected = (row, column) => {
const minRow = Math.min(this.state.startRow, this.state.endRow);
const maxRow = Math.max(this.state.startRow, this.state.endRow);
const minColumn = Math.min(this.state.startColumn, this.state.endColumn);
const maxColumn = Math.max(this.state.startColumn, this.state.endColumn);
return (
this.state.selectionStarted &&
(row >= minRow &&
row <= maxRow &&
column >= minColumn &&
column <= maxColumn)
);
};
}
class Cell extends React.Component {
// This optimization gave a 10% performance boost while drag-selecting
// cells
shouldComponentUpdate = nextProps =>
this.props.beingSelected !== nextProps.beingSelected ||
this.props.selected !== nextProps.selected;
componentDidMount = () => {
// We need to call addEventListener ourselves so that we can pass
// {passive: false}
this.td.addEventListener("touchstart", this.handleTouchStart, {
passive: false
});
this.td.addEventListener("touchmove", this.handleTouchMove, {
passive: false
});
};
componentWillUnmount = () => {
this.td.removeEventListener("touchstart", this.handleTouchStart);
this.td.removeEventListener("touchmove", this.handleTouchMove);
};
render = () => {
let {
className = "",
disabled,
beingSelected,
selected,
onTouchStart,
onTouchMove,
...props
} = this.props;
if (disabled) {
className += " cell-disabled";
} else {
className += " cell-enabled";
if (selected) {
className += " cell-selected";
}
if (beingSelected) {
className += " cell-being-selected";
}
}
return (
<td
ref={td => (this.td = td)}
className={className}
onMouseDown={this.handleTouchStart}
onMouseMove={this.handleTouchMove}
{...props}
>
{this.props.children || <span> </span>}
</td>
);
};
handleTouchStart = e => {
if (!this.props.disabled) {
this.props.onTouchStart(e);
}
};
handleTouchMove = e => {
if (!this.props.disabled) {
this.props.onTouchMove(e);
}
};
}
// Takes a mouse or touch event and returns the corresponding row and cell.
// Example:
//
// eventToCellLocation(event);
// {row: 2, column: 3}
const eventToCellLocation = e => {
let target;
// For touchmove and touchend events, e.target and e.touches[n].target are
// wrong, so we have to rely on elementFromPoint(). For mouse clicks, we have
// to use e.target.
if (e.touches) {
const touch = e.touches[0];
target = document.elementFromPoint(touch.clientX, touch.clientY);
} else {
target = e.target;
while (target.tagName !== "TD") {
target = target.parentNode;
}
}
return {
row: target.parentNode.rowIndex,
column: target.cellIndex
};
};
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* RollwiseEntry Schema
*/
var RollwiseEntrySchema = new Schema({
date: {
type: Date,
required: 'Please fill date name'
},
shift: {
type: String,
required: 'Please fill shift name'
},
machineNo: {
type: String,
required: 'Please fill machineNo name'
},
dia: {
type: Number,
required: 'Please fill dia name'
},
make: {
type: String,
required: 'Please fill make name'
},
sNo: {
type: Number,
required: 'Please fill sNo name'
},
jobNo: {
type: String,
required: 'Please fill jobNo name'
},
party: {
type: String,
required: 'Please fill party name'
},
fabric: {
type: String,
required: 'Please fill fabric name'
},
operator: {
type: String,
required: 'Please fill operator name'
},
rollNo: {
type: Number,
required: 'Please fill rollNo name'
},
weight: {
type: Number,
required: 'Please fill weight name'
},
holes: {
type: String,
required: 'Please fill holes name'
},
lycraCut: {
type: String,
required: 'Please fill lycraCut name'
},
puVari: {
type: String,
required: 'Please fill puVari name'
},
shutoff: {
type: String,
required: 'Please fill shutoff name'
},
needleLine: {
type: String,
required: 'Please fill needleLine name'
},
remarks: {
type: String,
required: 'Please fill remarks name'
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('RollwiseEntry', RollwiseEntrySchema); |
'use strict';
var test = require('tap').test;
var expressMongoDb = require('./');
test('throws on invalid uri', function (t) {
t.throws(function () {
expressMongoDb();
}, /Expected uri to be a string/);
t.end();
});
test('middleware pass error on fail', function (t) {
var middleware = expressMongoDb('mongodb://localhost:31337');
middleware({}, {}, function (err) {
t.ok(err);
middleware({}, {}, function (err) {
t.ok(err);
t.end();
});
});
});
test('middleware stores connection to mongodb', function (t) {
var middleware = expressMongoDb('mongodb://localhost:27017');
var req = {};
middleware(req, {}, function (err) {
t.error(err);
t.ok(req.db);
req.db.close(true, t.end);
});
});
test('middleware stores connection in custom property', function (t) {
var middleware = expressMongoDb('mongodb://localhost:27017', {
property: 'myDb'
});
var req = {};
middleware(req, {}, function (err) {
t.error(err);
t.ok(req.myDb);
req.myDb.close(true, t.end);
});
});
test('returns same connection for multiple requests', function (t) {
var middleware = expressMongoDb('mongodb://localhost:27017', {
property: 'myDb'
});
var req = {};
var _db;
middleware(req, {}, function (err) {
t.error(err);
t.ok(req.myDb);
_db = req.myDb;
middleware(req, {}, function (err) {
t.error(err);
t.equal(_db, req.myDb);
req.myDb.close(true, t.end);
});
});
});
|
import React from 'react';
import Icon from '../Icon';
export default class MessageIcon extends Icon {
getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M40 4H8C5.79 4 4.02 5.79 4.02 8L4 44l8-8h28c2.21 0 4-1.79 4-4V8c0-2.21-1.79-4-4-4zm-4 24H12v-4h24v4zm0-6H12v-4h24v4zm0-6H12v-4h24v4z"/></svg>;}
}; |
const pgconfig = require('./pgconfig');
const knex = require('knex')(pgconfig);
module.exports = {
test() {
knex.select(knex.raw(1))
},
deleteCategory(id) {
return knex('category').where('category_id', id).del();
},
insertCategory(name) {
return knex('category').insert({
category_name: name
});
},
getCategories() {
return knex.select('category_id AS id', 'category_name AS name').from('category');
},
updateCategory(id, name) {
return knex('category').where('category_id', id).update({
category_name: name
});
},
} |
export default from './components/chrome/Chrome'
|
/*
* __ ______ __ __ ______
* /\ \ /\ __ \ /\ \ _ \ \ /\ __ \
* \ \ \\ \ \/\ \\ \ \/ ".\ \\ \ __ \
* \ \_\\ \_____\\ \__/".~\_\\ \_\ \_\
* \/_/ \/_____/ \/_/ \/_/ \/_/\/_/
*
* Institute of War Aptitude
*
* Web-based tool to give insight to players based on their ranked match statistics
* and champion mastery data, with tools to learn about the champion and their
* performance with it.
* Built by williamtdr & Kellvas (NA) for the Riot API Challenge 2016.
*
* This file validates the configuration then launches the main app.
*/
const log = require("./src/util/log")("System", "cyan"),
HTTP = require("./src/interface/http"),
colors = require("colors"),
cache = require("./src/api/cache").engine,
core = require("./src/iowa/iowa"),
client = require("./src/api/client"),
Config = require("./src/util/config");
const iowa = {
async init() {
log.info("IoWA".yellow + " - Institute of War Aptitude".white);
log.info("Reading configuration...");
this.config = new Config("config/config.json");
if(this.config.get("credentials.riot_api_key").length === 0) {
log.warn("This project requires a developer key for the Riot Games API " +
"to retrieve summoner stats and other data. Please get one from " +
"developer.riotgames.com and enter it in config/config.json.");
return process.exit(1);
}
cache.init(this.config);
client.init(this.config);
core.init(this.config);
log.info("Starting web server...");
this.http = new HTTP();
await this.http.init(this.config.get("http.bind"));
log.info("Ready!");
}
};
module.exports = iowa;
iowa.init();
|
'use strict';
var os = require('os');
require('colors');
module.exports = function (app) {
// global settings
app.domain = 'gabba.io';
app.env = 'production';
app.address = app.config.protocol + app.domain + '/'; // base url
// directories
app.public = {
build : app.address + 'build/',
components : app.address + 'components/',
css : app.address + 'css/',
img : app.address + 'img/',
lib : app.address + 'lib/',
js : app.address + 'js/'
};
app.log('INFO:'.blue + ' ' + app.env.yellow + ' config loaded' );
};
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var vows = require("vows"),
assert = require("assert"),
jwcrypto = require("../index"),
assertion = jwcrypto.assertion,
cert = jwcrypto.cert,
testUtils= require("./utils");
var suite = vows.describe('cert');
testUtils.addBatches(suite, function(alg, keysize) {
var keypair = null;
return {
"invocation of verifyBundle" : {
topic: function() {
var str = new String("bogus bundle");
cert.verifyBundle(str, new Date(), function() {}, this.callback);
},
"fails as expected with a bogus string parameter": function(err, r) {
assert.equal(err, "no certificates provided");
}
},
"generate cert" : {
topic: function() {
var self = this;
// generate a key
jwcrypto.generateKeypair({algorithm: alg, keysize: keysize}, function(err, kp) {
// stash it away
keypair = kp;
var assertionParams = {
issuer : "issuer.com",
issuedAt : new Date(),
expiresAt : new Date((new Date()).getTime() + (6 * 60 * 60 * 1000))
};
// yes, we're signing our own public key, cause it's easier for now
cert.sign({publicKey: keypair.publicKey, principal:{email: "john@issuer.com"}},
assertionParams, null, keypair.secretKey, self.callback);
});
},
"cert is approximately proper format": function(err, signedObj) {
assert.lengthOf(signedObj.split('.'), 3);
},
"verifying the cert using normal sig verify": {
topic: function(signedObj) {
jwcrypto.verify(signedObj, keypair.publicKey, this.callback);
},
"works out ok": function(err, payload) {
assert.isNull(err);
assert.isObject(payload);
},
"has right fields": function(err, payload) {
assert.isString(payload.iss);
assert.equal(payload.iss, "issuer.com");
assert.isNumber(payload.iat);
assert.isNumber(payload.exp);
assert.isObject(payload.principal);
assert.equal(payload.principal.email, "john@issuer.com");
}
},
"verifying the cert using cert verify": {
topic: function(signedObj) {
// now is really now
cert.verify(signedObj, keypair.publicKey, new Date(), this.callback);
},
"works out ok": function(err, payload, assertionParams, certParams) {
assert.isNull(err);
assert.isObject(payload);
assert.isObject(assertionParams);
assert.isObject(certParams);
},
"has right fields": function(err, payload, assertionParams, certParams) {
assert.isString(assertionParams.issuer);
assert.equal(assertionParams.issuer, "issuer.com");
assert.isNotNull(assertionParams.issuedAt);
assert.isNotNull(assertionParams.expiresAt);
assert.isObject(certParams.principal);
assert.isObject(certParams.publicKey);
// make sure iss and exp are dates
assert.isFunction(assertionParams.issuedAt.getFullYear);
assert.isFunction(assertionParams.expiresAt.getFullYear);
assert.equal(certParams.principal.email, "john@issuer.com");
}
}
},
"generate cert chain" : {
topic: function() {
var self = this;
// expiration date
var expiration = new Date(new Date().valueOf() + 120000);
// once the cert chain is done, sign a
function signAssertion(rootPK, certs, user_keypair) {
assertion.sign({}, {audience: "https://fakesite.com",
expiresAt: expiration},
user_keypair.secretKey,
function(err, signedAssertion) {
var bundle = cert.bundle(certs, signedAssertion);
self.callback(null, {
certs: certs,
bundle: bundle,
rootPK: rootPK,
userPK: user_keypair.publicKey
});
});
}
// generate three keypairs to chain things
jwcrypto.generateKeypair({algorithm: alg, keysize: keysize}, function(err, root_kp) {
jwcrypto.generateKeypair({algorithm: alg, keysize: keysize}, function(err, intermediate_kp) {
jwcrypto.generateKeypair({algorithm: alg, keysize: keysize}, function(err, user_kp) {
// generate the two certs
cert.sign({publicKey: intermediate_kp.publicKey, principal: {host: "intermediate.root.com"}},
{issuer: "root.com", issuedAt: new Date(), expiresAt: expiration}, null,
root_kp.secretKey, function (err, signedIntermediate) {
cert.sign({publicKey: user_kp.publicKey, principal: {email: "john@root.com"}},
{issuer: "intermediate.root.com", issuedAt: new Date(), expiresAt: expiration},
null, intermediate_kp.secretKey,
function(err, signedUser) {
signAssertion(root_kp.publicKey,
[signedIntermediate, signedUser],
user_kp);
});
});
});
});
});
},
"proper root - just chain": {
topic: function(stuff) {
cert.verifyChain(stuff.certs, new Date(),
function(issuer, next) {
if (issuer == "root.com")
next(null, stuff.rootPK);
else
next("no root found");
},
this.callback
);
},
"verifies": function(err, certParamsArray) {
assert.isNull(err);
assert.isArray(certParamsArray);
}
},
"proper root": {
topic: function(stuff) {
cert.verifyBundle(stuff.bundle, new Date(),
function(issuer, next) {
if (issuer == "root.com")
next(null, stuff.rootPK);
else
next("no root found");
},
this.callback
);
},
"verifies": function(err, certParamsArray, payload, assertionParams) {
assert.isNull(err);
assert.isArray(certParamsArray);
assert.isObject(payload);
assert.isObject(assertionParams);
assert.isNotNull(assertionParams.audience);
}
},
"improper root - just chain": {
topic: function(stuff) {
cert.verifyChain(stuff.certs, new Date(),
function(issuer, next) {
if (issuer == "root.com")
// wrong public key!
next(stuff.userPK);
else
next(null);
},
this.callback
);
},
"does not verify": function(err, certParamsArray) {
assert.isNotNull(err);
assert.isUndefined(certParamsArray);
}
},
"improper root": {
topic: function(stuff) {
cert.verifyBundle(stuff.bundle, new Date(),
function(issuer, next) {
if (issuer == "root.com")
// wrong public key!
next(stuff.userPK);
else
next(null);
},
this.callback
);
},
"does not verify": function(err, certParamsArray, payload, assertionParams) {
assert.isNotNull(err);
assert.isUndefined(certParamsArray);
}
}
},
"null issued_at" : {
topic: function() {
var self = this;
// generate a key
jwcrypto.generateKeypair({algorithm: alg, keysize: keysize}, function(err, keypair) {
var assertionParams = {
issuer : "foo.com",
issuedAt : null,
expiresAt : new Date((new Date()).getTime() + (6 * 60 * 60 * 1000))
};
// yes, we're signing our own public key, cause it's easier for now
cert.sign({publicKey: keypair.publicKey, principal: {email: "user@example.com"}},
assertionParams, null, keypair.secretKey, function(err, signedObj) {
cert.verify(signedObj, keypair.publicKey, new Date(), self.callback);
});
});
},
"doesn't yield an erroneous date object": function(err, payload, assertionParams, certParams) {
assert.isNull(assertionParams.issuedAt);
}
}
};
});
// run or export the suite.
if (process.argv[1] === __filename) suite.run();
else suite.export(module);
|
var express = require('express');
var fs = require('fs');
var path = require('path');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var app = express();
// Define how to log events
app.use(morgan('tiny'));
app.use(bodyParser.urlencoded({
extended: true
}));
app.engine('html', require('ejs').renderFile)
app.set('view engine', 'ejs')
// Load all routes in the routes directory
fs.readdirSync('./routes').forEach(function(file) {
// There might be non-js files in the directory that should not be loaded
if (path.extname(file) == '.js') {
console.log("Adding routes in " + file);
require('./routes/' + file).init(app);
}
});
// Handle static files
app.use(express.static(__dirname + '/public'));
// Catch any routes not already handed with an error message
app.use(function(req, res) {
var message = 'Error, did not understand path ' + req.path;
// Set the status to 404 not found, and render a message to the user.
res.status(404).render('error', {
'message': message
});
});
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log('Ready to start helping people manage their time!');
}); |
import React from 'react';
import ReactDOM from 'react-dom';
import FriendList from '../lib/components/FriendList';
import Login from '../lib/components/Login';
import Message from '../lib/components/Message';
import NavHeader from '../lib/components/NavHeader';
import MessageView from '../lib/components/MessageView';
export const mockFriend = () => {
return {
name: 'David Becker',
profileImg: 'url.com',
currentLocation: 'Denver, Colorado',
messageFriend: jest.fn(),
friendId: '1',
openMessageView: jest.fn(),
};
};
export const makeMessageFriendData = () => {
return {
name: 'Forrest Sansing',
id: '562272102',
};
};
export const makeFriends = () => {
return [
{
name: 'Dave1',
picture: { data: { url: 'url.com' } },
id: '1',
location: { location: { name: 'Denver, Colorado' } },
},
{
name: 'Dave2',
picture: { data: { url: 'url2.com' } },
id: '2',
location: { location: { name: 'Denver, Colorado' } },
},
{
name: 'Dave3',
picture: { data: { url: 'url3.com' } },
id: '3',
location: { location: { name: 'Denver, Colorado' } },
},
];
};
export const makeUserData = () => {
return {
hometown: {
id: '1',
name: 'Memphis, Tennessee',
},
currentLocation: {
id: '2',
name: 'Denver, Colorado',
},
fullName: 'David Becker',
};
};
export const makeLoggedInUser = () => {
return {
displayName: 'David Becker2',
userName: 'dave',
photo: 'url.com',
location: 'Denver, Colorado',
};
};
export const makeLoggedInUser1 = () => {
return {
displayName: 'David Becker2',
userName: 'dave',
photo: 'url.com',
location: 'Denver, Colorado',
};
};
export const makeLoggedInUser3 = () => {
return {
displayName: 'David Becker3',
userName: 'dave',
photo: 'url.com',
location: 'Denver, Colorado',
};
};
export const makeMessage = () => {
return {
recipient: {
name: 'David Becker',
id: '0000000000',
},
sender: {
name: 'David Becker2',
id: '111111111',
},
message: 'Send a Message to Someone',
date: '03 30 2017',
};
};
export const makeArrayOfMessages = () => {
return [
{
recipient: {
name: 'David Becker',
id: '0000000000',
},
sender: {
name: 'David Becker2',
id: '111111111',
},
message: 'Send a Message to Someone1',
date: '2014 March',
},
{
recipient: {
name: 'David Becker',
id: '0000000000',
},
sender: {
name: 'David Becker2',
id: '111111111',
},
message: 'Send a Message to Someone2',
date: '2014 March',
},
{
recipient: {
name: 'David Becker2',
id: '111111111',
},
sender: {
name: 'David Becker',
id: '0000000000',
},
message: 'Send a Message to Someone3',
date: '2014 March',
},
];
};
export const makeMessageView = () => {
return (
<MessageView
messages={makeArrayOfMessages()}
userDataFacebook={makeUserData()}
messageFriendData={makeMessageFriendData()}
loggedInUser={makeLoggedInUser()}
sendMessageToFirebase={jest.fn()}
retrieveMessagesFromFirebase={jest.fn()}
/>
);
};
export const makeMessageViewNoFriend = () => {
return (
<MessageView
messages={[]}
userDataFacebook={makeUserData()}
messageFriendData={{}}
loggedInUser={makeLoggedInUser()}
sendMessageToFirebase={jest.fn()}
retrieveMessagesFromFirebase={jest.fn()}
/>
);
};
export const makeFriendList = () => {
return (
<FriendList
friends={makeFriends()}
userDataFacebook={makeUserData()}
messageFriendData={makeMessageFriendData()}
loggedInUser={makeLoggedInUser()}
fetchFriends={jest.fn()}
messageFriend={jest.fn()}
/>
);
};
export const makeLogin = () => {
return <Login storeLoggedInUserData={jest.fn()} />;
};
export const makeMockMessage = () => {
return <Message key={1} {...makeMessage()} loggedInUser={makeLoggedInUser()} />;
};
export const makeMockMessage2 = () => {
return <Message key={1} {...makeMessage()} loggedInUser={makeLoggedInUser3()} />;
};
export const makeNavHeader = () => {
return <NavHeader loggedInUser={makeLoggedInUser()} userDataFacebook={makeUserData()} />;
};
|
/**
* Serialize contents
* @typedef {string | number | Array<string | number>} Contents
* @param {Contents} contents
*/
const serialize = contents =>
Array.isArray(contents) ? contents.join('') : contents.toString();
/**
* A helper to generate innerHTML validation strings containing spans
* @param {Contents} contents The contents of the span, as a string
*/
export const span = contents => `<span>${serialize(contents)}</span>`;
/**
* A helper to generate innerHTML validation strings containing divs
* @param {Contents} contents The contents of the div, as a string
*/
export const div = contents => `<div>${serialize(contents)}</div>`;
/**
* A helper to generate innerHTML validation strings containing p
* @param {Contents} contents The contents of the p, as a string
*/
export const p = contents => `<p>${serialize(contents)}</p>`;
/**
* A helper to generate innerHTML validation strings containing sections
* @param {Contents} contents The contents of the section, as a string
*/
export const section = contents => `<section>${serialize(contents)}</section>`;
/**
* A helper to generate innerHTML validation strings containing uls
* @param {Contents} contents The contents of the ul, as a string
*/
export const ul = contents => `<ul>${serialize(contents)}</ul>`;
/**
* A helper to generate innerHTML validation strings containing ols
* @param {Contents} contents The contents of the ol, as a string
*/
export const ol = contents => `<ol>${serialize(contents)}</ol>`;
/**
* A helper to generate innerHTML validation strings containing lis
* @param {Contents} contents The contents of the li, as a string
*/
export const li = contents => `<li>${serialize(contents)}</li>`;
/**
* A helper to generate innerHTML validation strings containing inputs
*/
export const input = () => `<input type="text">`;
/**
* A helper to generate innerHTML validation strings containing h1
* @param {Contents} contents The contents of the h1
*/
export const h1 = contents => `<h1>${serialize(contents)}</h1>`;
/**
* A helper to generate innerHTML validation strings containing h2
* @param {Contents} contents The contents of the h2
*/
export const h2 = contents => `<h2>${serialize(contents)}</h2>`;
|
$(document).ready(function() {
$.getJSON('../data/result.json', function(jd) {
test_list = jd.report.tests;
$(".time-exe").append(Math.round(find_slowest_test(test_list).duration));
$("#check_slw_test").attr("onclick", "location.href='test_result.html?test_name=" + fetch_test_name(find_slowest_test(test_list).name) + "';");
$(".time-module").append(Math.round(sorted_module_arr(create_module_dict_arr(jd), "avg_test_time").slice(-1)[0].duration));
$("#check_slw_mod").attr("onclick", "location.href='test_result.html?module=" + sorted_module_arr(create_module_dict_arr(jd), "avg_test_time").slice(-1)[0].module + "';");
$(".vul-module").append(Math.round(sorted_module_arr(create_module_dict_arr(jd), "failure_rate").slice(-1)[0].failure_rate));
$("#check_vul_mod").attr("onclick", "location.href='test_result.html?module=" + sorted_module_arr(create_module_dict_arr(jd), "failure_rate").slice(-1)[0].module + "';");
$(".fastest-module").append(Math.round(sorted_module_arr(create_module_dict_arr(jd), "avg_test_time")[0].avg_test_time));
$("#check_fast_mod").attr("onclick", "location.href='test_result.html?module=" + sorted_module_arr(create_module_dict_arr(jd), "avg_test_time")[0].module + "';");
$(".avg-time").append(Math.round(avg_test_execution_time(jd)));
$("#avg_test").attr("onclick", "location.href='test_execution_time_graph.html';");
});
});
function avg_test_execution_time(json_data){
var avg_test_exe_time = Math.round(json_data.report.summary.duration/json_data.report.summary.num_tests);
return avg_test_exe_time;
}
function find_slowest_test(test_list){
var new_sorted_list = sortByKey(test_list, "duration")
return new_sorted_list.slice(-1)[0];
}
function sorted_module_arr(module_object_list, sort_key){
var sorted_module_list = sortByKey(module_object_list, sort_key);
return sorted_module_list;
}
function sortByKey(array, key) {
return array.sort(function(a, b) {
var x = a[key]; var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
function fetch_module_name(name_string){
module_name = name_string.split("::")[1];
return module_name;
}
function fetch_test_name(name_string){
module_name = name_string.split("::")[2];
return module_name;
}
function SecondsTohhmmss(totalSeconds) {
var hours = Math.floor(totalSeconds / 3600);
var minutes = Math.floor((totalSeconds - (hours * 3600)) / 60);
var seconds = totalSeconds - (hours * 3600) - (minutes * 60);
// round seconds
seconds = Math.round(seconds * 100) / 100
var result = (hours < 10 ? "0" + hours : hours);
result += " : " + (minutes < 10 ? "0" + minutes : minutes);
result += " : " + (seconds < 10 ? "0" + seconds : seconds);
return result;
}
function create_module_dict_arr(jd){
var module = {};
var modules = {};
var my_array = [];
for(i=0; i<jd.report.tests.length; i++){
value = jd.report.tests[i].name;
module_name = value.split("::")[1]
var count = (module[module_name] || 0) + 1;
module[module_name] = count;
}
for (key in module) {
var details = {};
pass_count_key = "pass_count";
var pass_count = 0;
fail_count_key = "fail_count";
var fail_count = 0;
skip_count_key = "skip_count";
var skip_count = 0;
error_count_key = "error_count";
var error_count = 0;
total_time = "duration";
var duration = 0.0;
for (i=0; i < jd.report.tests.length; i++){
if(jd.report.tests[i].name.split("::")[1] == key){
if (jd.report.tests[i].outcome == 'passed'){
pass_count = pass_count + 1;
}
else if (jd.report.tests[i].outcome == 'failed'){
fail_count = fail_count + 1;
}
else if (jd.report.tests[i].outcome == 'skipped'){
skip_count = skip_count + 1;
}
else if (jd.report.tests[i].outcome == 'error'){
error_count = error_count + 1;
}
duration = duration + jd.report.tests[i].duration;
}
}
details['total'] = module[key];
details['failure_rate'] = Math.round((fail_count + error_count)*100/module[key]);
details[pass_count_key] = pass_count;
details[fail_count_key] = fail_count;
details[skip_count_key] = skip_count;
details[error_count_key] = error_count;
details[total_time] = duration;
details['module'] = key;
details['avg_test_time'] = Math.round(duration/module[key]);
my_array.push(details);
}
return my_array;
}
|
//Directive that removes the default HL7 syntax from the message
//USAGE ex: <div ng-repeat="message in messages" formathl7="<message>"></div>
myApp.directive('formathl7',
function($filter,$sce){
return {
restrict: 'A',
scope: { formathl7: '='},
link: function(scope) {
var message = scope.formathl7.split('\n');
var rebuiltMessage = '';
//Regexs to find '|' and '^' in a message;
var fieldSeparator = new RegExp('\\|+','g');
var componentCharJoin = new RegExp('\\^+','g');
//Replace/removing default HL7 syntax
for(var segmentIndex in message) {
rebuiltMessage += message[segmentIndex].replace(fieldSeparator, ' ').replace(componentCharJoin,',') + '\n';
}
scope.formathl7 = rebuiltMessage;
}
};
});
|
import expect from 'expect';
import React from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
import FetchingBasicExample from '../demo/src/demo-containers/fetching-basic';
describe('FetchingBasicExample tests', () => {
let node;
beforeEach(() => {
node = document.createElement('div');
});
afterEach(() => {
unmountComponentAtNode(node);
});
it('renders demo app', () => {
render(<FetchingBasicExample />, node, () => {
expect(node.innerHTML).toExist();
});
});
});
|
(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["MindmapLayouts"] = factory();
else
root["MindmapLayouts"] = 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 = 31);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
const randomInt = __webpack_require__(2);
module.exports = arr => {
if (!Array.isArray(arr) || !arr.length) {
return null;
}
return arr[randomInt(arr.length - 1)];
};
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
const randomInt = __webpack_require__(2);
module.exports = (start, end) => start + randomInt(end - start);
/***/ }),
/* 2 */
/***/ (function(module, exports) {
module.exports = n => Math.round(Math.random() * n);
/***/ }),
/* 3 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_zero_colors__ = __webpack_require__(18);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_zero_colors___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_zero_colors__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_random_graph__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_random_graph___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_random_graph__);
/* harmony default export */ __webpack_exports__["a"] = () => {
const rgba = `rgba(${__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1_random_graph__["randomInt"])(255)}, ${__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1_random_graph__["randomInt"])(255)}, ${__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1_random_graph__["randomInt"])(255)}, 0.6)`;
return new __WEBPACK_IMPORTED_MODULE_0_zero_colors___default.a(rgba);
};
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
const randomTree = __webpack_require__(15);
const utils = __webpack_require__(5);
const res = Object.assign({
randomTree
}, utils);
module.exports = res;
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = {
randomCharFromCategories: __webpack_require__(6),
randomChinese: __webpack_require__(7),
randomFromArray: __webpack_require__(0),
randomFromRange: __webpack_require__(1),
randomInt: __webpack_require__(2),
randomJapanese: __webpack_require__(8),
randomLetter: __webpack_require__(9),
randomNumber: __webpack_require__(10),
randomSpecial: __webpack_require__(11),
randomString: __webpack_require__(16),
uuid: __webpack_require__(17)
};
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
const randomFromArray = __webpack_require__(0);
const randomByCats = {
chinese: __webpack_require__(7),
japanese: __webpack_require__(8),
letter: __webpack_require__(9),
number: __webpack_require__(10),
special: __webpack_require__(11)
};
module.exports = cats => {
const cat = randomFromArray(cats);
return randomByCats[cat]();
};
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
const randomFromRange = __webpack_require__(1);
const range = {
start: 0x4E00,
end: 0x9FA5
};
module.exports = () => String.fromCharCode(randomFromRange(range.start, range.end));
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
const randomFromArray = __webpack_require__(0);
const randomFromRange = __webpack_require__(1);
const ranges = [{
start: 0x3040,
end: 0x309F
}, {
start: 0x30A0,
end: 0x30FF
}];
module.exports = () => {
const range = randomFromArray(ranges);
return String.fromCharCode(randomFromRange(range.start, range.end));
};
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
const randomFromArray = __webpack_require__(0);
const letters = 'abcdefghijklmnopqrstuvwxyz'.split('');
module.exports = () => randomFromArray(letters);
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
const randomFromArray = __webpack_require__(0);
const numbers = '0123456789'.split('');
module.exports = () => randomFromArray(numbers);
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
const randomFromArray = __webpack_require__(0);
const specialChars = '!$%^&*()_+|~-=`{}[]:;<>?,./'.split('');
module.exports = () => randomFromArray(specialChars);
/***/ }),
/* 12 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__random_color__ = __webpack_require__(3);
const lineColor = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__random_color__["a" /* default */])().toGrey().toString(true);
/* harmony default export */ __webpack_exports__["a"] = (n, c, ctx, isHorizontal) => {
let beginNode = n;
let endNode = c;
let beginX;
let beginY;
let endX;
let endY;
if (isHorizontal) {
if (n.x > c.x) {
beginNode = c;
endNode = n;
}
beginX = Math.round(beginNode.x + beginNode.width - beginNode.hgap);
beginY = Math.round(beginNode.y + beginNode.height / 2);
endX = Math.round(endNode.x + endNode.hgap);
endY = Math.round(endNode.y + endNode.height / 2);
} else {
if (n.y > c.y) {
beginNode = c;
endNode = n;
}
beginX = Math.round(beginNode.x + beginNode.width / 2);
beginY = Math.round(beginNode.y + beginNode.height - beginNode.vgap);
endX = Math.round(endNode.x + endNode.width / 2);
endY = Math.round(endNode.y + endNode.vgap);
}
if (beginNode.isRoot()) {
beginX = Math.round(beginNode.x + beginNode.width / 2);
beginY = Math.round(beginNode.y + beginNode.height / 2);
}
if (endNode.isRoot()) {
endX = Math.round(endNode.x + endNode.width / 2);
endY = Math.round(endNode.y + endNode.height / 2);
}
// console.log(`(${beginX}, ${beginY}), (${endX}, ${endY})`)
ctx.strokeStyle = lineColor;
ctx.beginPath();
ctx.moveTo(beginX, beginY);
if (isHorizontal) {
ctx.bezierCurveTo(Math.round(beginX + (beginNode.hgap + endNode.hgap) / 2), beginY, Math.round(endX - (beginNode.hgap + endNode.hgap) / 2), endY, endX, endY);
} else {
ctx.bezierCurveTo(beginX, Math.round(beginY + (beginNode.vgap + endNode.vgap) / 2), endX, Math.round(endY - (beginNode.vgap + endNode.vgap) / 2), endX, endY);
}
ctx.stroke();
};
/***/ }),
/* 13 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__random_color__ = __webpack_require__(3);
/* harmony default export */ __webpack_exports__["a"] = (node, ctx) => {
const color = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__random_color__["a" /* default */])();
// console.log(color.toRgba());
const x = Math.round(node.x + node.hgap);
const y = Math.round(node.y + node.vgap);
const width = Math.round(node.width - node.hgap * 2);
const height = Math.round(node.height - node.vgap * 2);
// const x = Math.round(node.x)
// const y = Math.round(node.y)
// const width = Math.round(node.width)
// const height = Math.round(node.height)
ctx.clearRect(x, y, width, height);
ctx.fillStyle = color.toString();
ctx.fillRect(x, y, width, height);
ctx.strokeStyle = color.toGrey().toString();
ctx.strokeRect(x, y, width, height);
};
/***/ }),
/* 14 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_random_graph__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_random_graph___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_random_graph__);
/* harmony default export */ __webpack_exports__["a"] = size => __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_random_graph__["randomTree"])({
size,
attributes: {
id: {
type: 'uuid'
},
name: {
type: 'randomString',
options: {
length: 0,
maxLength: 12
}
}
}
});
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
const utils = __webpack_require__(5);
function generateRoot(options) {
const root = {
children: []
};
const attributes = options.attributes;
for (let key in attributes) {
root[key] = utils[attributes[key].type](attributes[key].options);
}
return root;
}
function generateNode(root, child) {
const rand = utils.randomInt(root.children.length);
if (rand === root.children.length) {
root.children.push(child);
} else {
generateNode(root.children[rand], child);
}
}
const DEFAULT_OPTIONS = {
size: 10,
attributes: {
id: {
type: 'uuid'
},
name: {
type: 'randomString',
options: {
maxLength: 10
}
}
}
};
function randomTree(customizedOptions) {
const options = Object.assign({}, DEFAULT_OPTIONS, customizedOptions);
const root = generateRoot(options);
for (let i = 0; i < options.size; i++) {
generateNode(root, generateRoot(options));
}
return root;
}
module.exports = randomTree;
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
const randomCharFromCats = __webpack_require__(6);
const randomFromRange = __webpack_require__(1);
const DEFAULT_OPTIONS = {
length: 6,
maxLength: 6,
capitalization: 'lowercase', // lowercase, uppercase
categories: [
// 'number',
'letter']
};
module.exports = customizedOptions => {
const options = Object.assign({}, DEFAULT_OPTIONS, customizedOptions);
let res = '';
const len = options.length ? options.length : randomFromRange(1, options.maxLength);
for (let i = 0; i < len; i++) {
res += randomCharFromCats(options.categories);
}
if (options.capitalization === 'uppercase') {
res = res.toUpperCase();
}
return res;
};
/***/ }),
/* 17 */
/***/ (function(module, exports) {
module.exports = () => 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : r & 0x3 | 0x8;
return v.toString(16);
});
/***/ }),
/* 18 */
/***/ (function(module, exports, __webpack_require__) {
const namedColor = __webpack_require__(19);
const round = Math.round;
function isString(obj) {
return typeof obj === 'string';
}
function lc(str) {
return str.toLowerCase();
}
function confine(c, low, high) {
c = Number(c);
if (isFinite(c)) {
if (c < low) {
return low;
}
return c > high ? high : c;
}
return high;
}
function hue2rgb(m1, m2, h) {
if (h < 0) {
++h;
}
if (h > 1) {
--h;
}
const h6 = 6 * h;
if (h6 < 1) {
return m1 + (m2 - m1) * h6;
}
if (2 * h < 1) {
return m2;
}
if (3 * h < 2) {
return m1 + (m2 - m1) * (2 / 3 - h) * 6;
}
return m1;
}
function rgb2hsl(r, g, b, a) {
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
let h;
let s;
const l = (max + min) / 2;
if (max === min) {
h = s = 0;
} else {
const d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
default:
break;
}
h /= 6;
}
return [h, s, l, a];
}
class Color {
// init props
// r: 255,
// g: 255,
// b: 255,
// a: 1,
constructor( /* Array|String|Object */color) {
let me = this;
if (color) {
if (isString(color)) {
me = Color.fromString(color);
} else if (Array.isArray(color)) {
me = Color.fromArray(color, me);
} else {
me.set(color.r, color.g, color.b, color.a);
if (!(color instanceof Color)) {
me.sanitize();
}
}
} else {
me.set(255, 255, 255, 1);
}
return me;
}
set(r, g, b, a) {
const me = this;
me.r = r;
me.g = g;
me.b = b;
me.a = a;
}
sanitize() {
const me = this;
me.r = round(confine(me.r, 0, 255));
me.g = round(confine(me.g, 0, 255));
me.b = round(confine(me.b, 0, 255));
me.a = confine(me.a, 0, 1);
return me;
}
toRgba() {
const me = this;
return [me.r, me.g, me.b, me.a];
}
toHsla() {
const me = this;
return rgb2hsl(me.r, me.g, me.b, me.a);
}
toHex() {
const me = this;
const arr = ['r', 'g', 'b'].map(x => {
const str = me[x].toString(16);
return str.length < 2 ? `0${str}` : str;
});
return `#${arr.join('')}`;
}
toCss( /* Boolean? */includeAlpha) {
const me = this;
const rgb = `${me.r},${me.g},${me.b}`;
return includeAlpha ? `rgba(${rgb},${me.a})` : `rgb(${rgb})`;
}
toString() {
return this.toCss(true);
}
toGrey() {
const me = this;
const g = round((me.r + me.g + me.b) / 3);
return Color.makeGrey(g, me.a);
}
}
Object.assign(Color, {
hexByName: namedColor,
makeGrey( /* Number */g, /* Number? */a) {
return Color.fromArray([g, g, g, a]);
},
blendColors( /* Color */start, /* Color */end, /* Number */weight, /* Color? */obj) {
const t = obj || new Color();
['r', 'g', 'b', 'a'].forEach(x => {
t[x] = start[x] + (end[x] - start[x]) * weight;
if (x !== 'a') {
t[x] = Math.round(t[x]);
}
});
return t.sanitize();
},
fromHex( /* String */color) {
const result = new Color();
const bits = color.length === 4 ? 4 : 8;
const mask = (1 << bits) - 1;
color = Number(`0x${color.substr(1)}`);
if (isNaN(color)) {
return null;
}
['b', 'g', 'r'].forEach(x => {
const c = color & mask;
color >>= bits;
result[x] = bits === 4 ? 17 * c : c;
});
return result;
},
fromRgb( /* String */color) {
const matches = lc(color).match(/^rgba?\(([\s.,0-9]+)\)/);
return matches && Color.fromArray(matches[1].split(/\s*,\s*/));
},
fromHsl( /* String */color) {
const matches = lc(color).match(/^hsla?\(([\s.,0-9]+)\)/);
if (matches) {
const c = matches[2].split(/\s*,\s*/);
const l = c.length;
const H = (parseFloat(c[0]) % 360 + 360) % 360 / 360;
const S = parseFloat(c[1]) / 100;
const L = parseFloat(c[2]) / 100;
const m2 = L <= 0.5 ? L * (S + 1) : L + S - L * S;
const m1 = 2 * L - m2;
const a = [hue2rgb(m1, m2, H + 1 / 3) * 256, hue2rgb(m1, m2, H) * 256, hue2rgb(m1, m2, H - 1 / 3) * 256, 1];
if (l === 4) {
a[3] = c[3];
}
return Color.fromArray(a);
}
return null;
},
fromArray( /* Array */arr) {
const result = new Color();
result.set(Number(arr[0]), Number(arr[1]), Number(arr[2]), Number(arr[3]));
if (isNaN(result.a)) {
result.a = 1;
}
return result.sanitize();
},
fromString( /* String */str) {
const s = Color.hexByName[str];
return s && Color.fromHex(s) || Color.fromRgb(str) || Color.fromHex(str) || Color.fromHsl(str);
}
});
Color.named = Color.namedColor = namedColor;
module.exports = Color;
/***/ }),
/* 19 */
/***/ (function(module, exports) {
module.exports = {
aliceblue: '#f0f8ff',
antiquewhite: '#faebd7',
aqua: '#00ffff',
aquamarine: '#7fffd4',
azure: '#f0ffff',
beige: '#f5f5dc',
bisque: '#ffe4c4',
black: '#000000',
blanchedalmond: '#ffebcd',
blue: '#0000ff',
blueviolet: '#8a2be2',
brown: '#a52a2a',
burlywood: '#deb887',
burntsienna: '#ea7e5d',
cadetblue: '#5f9ea0',
chartreuse: '#7fff00',
chocolate: '#d2691e',
coral: '#ff7f50',
cornflowerblue: '#6495ed',
cornsilk: '#fff8dc',
crimson: '#dc143c',
cyan: '#00ffff',
darkblue: '#00008b',
darkcyan: '#008b8b',
darkgoldenrod: '#b8860b',
darkgray: '#a9a9a9',
darkgreen: '#006400',
darkgrey: '#a9a9a9',
darkkhaki: '#bdb76b',
darkmagenta: '#8b008b',
darkolivegreen: '#556b2f',
darkorange: '#ff8c00',
darkorchid: '#9932cc',
darkred: '#8b0000',
darksalmon: '#e9967a',
darkseagreen: '#8fbc8f',
darkslateblue: '#483d8b',
darkslategray: '#2f4f4f',
darkslategrey: '#2f4f4f',
darkturquoise: '#00ced1',
darkviolet: '#9400d3',
deeppink: '#ff1493',
deepskyblue: '#00bfff',
dimgray: '#696969',
dimgrey: '#696969',
dodgerblue: '#1e90ff',
firebrick: '#b22222',
floralwhite: '#fffaf0',
forestgreen: '#228b22',
fuchsia: '#ff00ff',
gainsboro: '#dcdcdc',
ghostwhite: '#f8f8ff',
gold: '#ffd700',
goldenrod: '#daa520',
gray: '#808080',
green: '#008000',
greenyellow: '#adff2f',
grey: '#808080',
honeydew: '#f0fff0',
hotpink: '#ff69b4',
indianred: '#cd5c5c',
indigo: '#4b0082',
ivory: '#fffff0',
khaki: '#f0e68c',
lavender: '#e6e6fa',
lavenderblush: '#fff0f5',
lawngreen: '#7cfc00',
lemonchiffon: '#fffacd',
lightblue: '#add8e6',
lightcoral: '#f08080',
lightcyan: '#e0ffff',
lightgoldenrodyellow: '#fafad2',
lightgray: '#d3d3d3',
lightgreen: '#90ee90',
lightgrey: '#d3d3d3',
lightpink: '#ffb6c1',
lightsalmon: '#ffa07a',
lightseagreen: '#20b2aa',
lightskyblue: '#87cefa',
lightslategray: '#778899',
lightslategrey: '#778899',
lightsteelblue: '#b0c4de',
lightyellow: '#ffffe0',
lime: '#00ff00',
limegreen: '#32cd32',
linen: '#faf0e6',
magenta: '#ff00ff',
maroon: '#800000',
mediumaquamarine: '#66cdaa',
mediumblue: '#0000cd',
mediumorchid: '#ba55d3',
mediumpurple: '#9370db',
mediumseagreen: '#3cb371',
mediumslateblue: '#7b68ee',
mediumspringgreen: '#00fa9a',
mediumturquoise: '#48d1cc',
mediumvioletred: '#c71585',
midnightblue: '#191970',
mintcream: '#f5fffa',
mistyrose: '#ffe4e1',
moccasin: '#ffe4b5',
navajowhite: '#ffdead',
navy: '#000080',
oldlace: '#fdf5e6',
olive: '#808000',
olivedrab: '#6b8e23',
orange: '#ffa500',
orangered: '#ff4500',
orchid: '#da70d6',
palegoldenrod: '#eee8aa',
palegreen: '#98fb98',
paleturquoise: '#afeeee',
palevioletred: '#db7093',
papayawhip: '#ffefd5',
peachpuff: '#ffdab9',
peru: '#cd853f',
pink: '#ffc0cb',
plum: '#dda0dd',
powderblue: '#b0e0e6',
purple: '#800080',
rebeccapurple: '#663399',
red: '#ff0000',
rosybrown: '#bc8f8f',
royalblue: '#4169e1',
saddlebrown: '#8b4513',
salmon: '#fa8072',
sandybrown: '#f4a460',
seagreen: '#2e8b57',
seashell: '#fff5ee',
sienna: '#a0522d',
silver: '#c0c0c0',
skyblue: '#87ceeb',
slateblue: '#6a5acd',
slategray: '#708090',
slategrey: '#708090',
snow: '#fffafa',
springgreen: '#00ff7f',
steelblue: '#4682b4',
tan: '#d2b48c',
teal: '#008080',
thistle: '#d8bfd8',
tomato: '#ff6347',
turquoise: '#40e0d0',
violet: '#ee82ee',
wheat: '#f5deb3',
white: '#ffffff',
whitesmoke: '#f5f5f5',
yellow: '#ffff00',
yellowgreen: '#9acd32'
};
/***/ }),
/* 20 */,
/* 21 */,
/* 22 */,
/* 23 */,
/* 24 */,
/* 25 */,
/* 26 */,
/* 27 */,
/* 28 */,
/* 29 */,
/* 30 */,
/* 31 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_random_tree__ = __webpack_require__(14);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils_draw_line__ = __webpack_require__(12);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_draw_node__ = __webpack_require__(13);
const RightLogicalLayout = MindmapLayouts.RightLogical;
const count = 20;
const root = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__utils_random_tree__["a" /* default */])(count);
Object.assign(root, {
'height': 80,
'width': 300,
'hgap': 100
});
const layout = new RightLogicalLayout(root);
const t0 = window.performance.now();
const rootNode = layout.doLayout();
const t1 = window.performance.now();
const bb = rootNode.getBoundingBox();
// console.log(rootNode, bb)
const canvas = document.getElementById('canvas');
canvas.width = bb.width > 30000 ? 30000 : bb.width;
canvas.height = bb.height > 30000 ? 30000 : bb.height;
// rootNode.translate(0, -100) // test
// rootNode.right2left() // test
if (canvas.getContext) {
const ctx = canvas.getContext('2d');
rootNode.eachNode(node => {
node.children.forEach(child => {
__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_draw_line__["a" /* default */])(node, child, ctx, true);
});
__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__utils_draw_node__["a" /* default */])(node, ctx);
});
}
const t2 = window.performance.now();
console.log(`there are ${count} tree nodes`);
console.log(`layout algorithm took ${t1 - t0}ms, and drawing took ${t2 - t1}ms.`);
/***/ })
/******/ ]);
}); |
var StarsFrame = React.createClass({
render: function() {
return (
<div>
...
</div>
);
}
});
var ButtonFrame = React.createClass({
render: function() {
return (
<div>
...
</div>
);
}
});
var AnswerFrame = React.createClass({
render: function() {
return (
<div>
...
</div>
);
}
});
var Game = React.createClass({
render: function() {
return (
<div id="game">
<h2>Play Nine</h2>
<StarsFrame />
<ButtonFrame />
<AnswerFrame />
</div>
);
}
});
ReactDOM.render(
<Game />,
document.getElementById('container')
); |
'use strict';
describe('Course e2e test', function () {
var username = element(by.id('username'));
var password = element(by.id('password'));
var entityMenu = element(by.id('entity-menu'));
var accountMenu = element(by.id('account-menu'));
var login = element(by.id('login'));
var logout = element(by.id('logout'));
beforeAll(function () {
browser.get('/');
accountMenu.click();
login.click();
username.sendKeys('admin');
password.sendKeys('admin');
element(by.css('button[type=submit]')).click();
});
it('should load Courses', function () {
entityMenu.click();
element.all(by.css('[ui-sref="course"]')).first().click().then(function() {
element.all(by.css('h2')).first().getAttribute('data-translate').then(function (value) {
expect(value).toMatch(/artemisApp.course.home.title/);
});
});
});
it('should load create Course dialog', function () {
element(by.css('[ui-sref="course.new"]')).click().then(function() {
element(by.css('h4.modal-title')).getAttribute('data-translate').then(function (value) {
expect(value).toMatch(/artemisApp.course.home.createOrEditLabel/);
});
element(by.css('button.close')).click();
});
});
afterAll(function () {
accountMenu.click();
logout.click();
});
});
|
exports.up = async function (db) {
await db.runSql(`
CREATE MATERIALIZED VIEW ranked_matchmaking_ratings_view AS
SELECT RANK() OVER (ORDER BY r.rating DESC) as rank, r.user_id, r.rating,
r.wins, r.losses, r.last_played_date
FROM matchmaking_ratings r
WHERE r.num_games_played > 0
`)
await db.runSql(`
CREATE UNIQUE INDEX ranked_matchmaking_ratings_view_user_id
ON ranked_matchmaking_ratings_view (user_id)
`)
await db.runSql(`
CREATE INDEX ranked_matchmaking_ratings_view_rating
ON ranked_matchmaking_ratings_view (rating DESC)
`)
}
exports.down = async function (db) {
await db.runSql(`DROP MATERIALIZED VIEW ranked_matchmaking_ratings_view`)
}
exports._meta = {
version: 1,
}
|
/*!
* 4K || fourKay
* Calculate breakpoints and base font-size values
* so that your site will keep the same layout on larger
* screens as on narrower screens.
*
* Use 'em' instead of 'px' values for the site to scale up
*
* Created by Rabbe Walter
*/
function fourKay(params) {
'use strict';
// Default settings for the fourKay script
var settings = {
minWidth: 1440, // common screen width starting point
maxWidth: 4096, // 4K screen width
precision: 2, // 2 = 1.0||11, 3 = 1.00||123 - ie. how exact the script will be (2 is fine and will produce less code)
codeOut: 'console' // use 'inline' to add a ´<style>´ tag in html head || 'id-tag' to insert as textNode
};
// Loop related variables
var i = typeof params !== 'undefined' && typeof params.minWidth !== 'undefined' ? params.minWidth : settings.minWidth;
var len = typeof params !== 'undefined' && typeof params.maxWidth !== 'undefined' ? params.maxWidth : settings.maxWidth;
var threshold = typeof params !== 'undefined' && typeof params.threshold !== 'undefined' ? params.threshold : settings.threshold;
var aspectRatio = i;
var precision = typeof params !== 'undefined' && typeof params.precision !== 'undefined' ? params.precision : settings.precision;
var lastFontSize = 0;
var finalFontSize = 0;
var finalMediaQuery = 0;
var codeOut = typeof params !== 'undefined' && typeof params.codeOut !== 'undefined' ? params.codeOut : settings.codeOut;
var inlineCSS = '';
// Default min and max valuesset
if (i <= 1439) {
i = 1440;
alert('Sorry, ' + i + 'px is the recommended minimum value…'); //(87.5em)
}
if (len >= 8499) {
len = 8500;
alert('Sorry, ' + len + 'px is the recommended maxinum value for now.'); //(531.25em)
}
// Generate media query list containing breakpoints and font-size values
for (i; i < len; (i = i + 1)) {
// Set font-size to 'em'
finalFontSize = (i / aspectRatio).toPrecision(precision);
// Set media query values to 'em'
finalMediaQuery = i / 16;
// Compare to last generated value not to produce too many lines of code
if (finalFontSize > lastFontSize) {
// Generate CSS
inlineCSS += '@media screen and (min-width:' + finalMediaQuery + 'em){body{font-size:' + finalFontSize + 'em}}\n';
}
// Reset font size for next loop through
lastFontSize = finalFontSize;
}
// Output code in console
if (codeOut === 'console') {
console.log(inlineCSS);
}
// Output code as a style tag in document head
else if (codeOut === 'inline') {
var htmlHead = document.head || document.getElementsByTagName('head')[0];
var inlineStyle = document.createElement('style');
inlineStyle.type = 'text/css'; // Non HTML5
if (inlineStyle.styleSheet){
inlineStyle.styleSheet.cssText = inlineCSS;
} else {
inlineStyle.appendChild(document.createTextNode(inlineCSS));
}
htmlHead.appendChild(inlineStyle);
}
// Output code in defined container and wrap in a paragraph
else {
// Create textNode for styles and append
var paragraph = document.createElement('p');
var paragraphContent = document.createTextNode(inlineCSS);
paragraph.appendChild(paragraphContent);
document.getElementById(codeOut).appendChild(paragraph);
}
}
|
/**
* Created by heaven on 2015/1/12.
*/
decribe('A suite',function(){
it('contains spec with an expectation', function () {
console.log('this is msg from log ..');
expect(true).toBe(true);
})
});
decribe('A suite of basic functions', function () {
it('reverse word', function () {
expect('DABC').toEqual(reverse('CBDA'));
expect('QWER').toEqual(reverse('REWQ'));
});
});
|
'use strict';
const nedb = require(`nedb`);
const bluebird = require(`bluebird`);
const path = require(`path`);
const bcrypt = require(`bcrypt`);
const crypto = require(`crypto`);
const sinon = require(`sinon`);
const chai = require(`chai`);
const chaiAsPromised = require(`chai-as-promised`);
chai.use(chaiAsPromised);
const expect = chai.expect;
const userModule = require(path.join(`..`, `..`, `lib`, `user.js`));
describe(`User`, function() {
let user;
let sandbox = sinon.sandbox.create();
beforeEach(function() {
user = new userModule();
});
afterEach(function() {
sandbox.restore();
});
describe(`#register()`, function() {
it(`should reject if the user already exists`, function() {
sandbox.stub(user.userData, 'findOneAsync', function() {
return bluebird.resolve({username: 'test'});
});
const userPromise = user.register('test', 'password');
return expect(userPromise).to.be.rejectedWith(`Username test already exists`);
});
it(`should resolve with a user object`, function() {
sandbox.stub(user.userData, 'insertAsync', function(userObject) {
return bluebird.resolve(userObject);
});
const userPromise = user.register('test', 'password');
return expect(userPromise).to.eventually.have.deep.property('username', 'test');
});
});
describe(`#authenticate()`, function(){
it(`should reject if the user does not exist`, function() {
sandbox.stub(user.userData, 'findOneAsync', function() {
return bluebird.resolve();
});
const userPromise = user.authenticate('test', 'password');
return expect(userPromise).to.be.rejectedWith(`Incorrect account details`);
});
it(`should reject if the password does not match`, function() {
sandbox.stub(user.userData, 'findOneAsync', function() {
return bluebird.resolve({username: 'test', password: 'wrong'});
});
const userPromise = user.authenticate('test', 'password');
return expect(userPromise).to.be.rejectedWith(`Incorrect account details`);
});
it(`should resolve if authentication is successful`, function() {
return bcrypt.hash(`password`, 10).then((password) => {
sandbox.stub(user.userData, 'findOneAsync', function() {
return bluebird.resolve({username: 'test', password});
});
sandbox.stub(user, 'generateToken', function() {
return bluebird.resolve(12345);
});
const userPromise = user.authenticate('test', 'password');
return expect(userPromise).to.eventually.equal(12345);
});
});
});
describe(`#verifyToken()`, function(){
it(`should reject if the token is invalid`, function() {
sandbox.stub(user.userData, 'findOneAsync', function() {
return bluebird.resolve();
});
const userPromise = user.verifyToken('invalid-token');
return expect(userPromise).to.be.rejectedWith(`Invalid token`);
});
it(`should resolve if the token is valid`, function() {
sandbox.stub(user.userData, 'findOneAsync', function() {
return bluebird.resolve({username: 'test'});
});
const userPromise = user.verifyToken('12345');
return expect(userPromise).to.eventually.be.true;
});
});
describe(`#generateToken()`, function(){
it(`should return a token for the user`, function() {
sandbox.stub(user.userData, 'updateAsync', function() {
return bluebird.resolve();
});
const date = Date.now();
sandbox.useFakeTimers(date);
const hash = crypto.createHash(`sha256`);
hash.update(`test` + date);
const token = hash.digest(`hex`);
const userPromise = user.generateToken(`test`);
return expect(userPromise).to.eventually.equal(token);
});
});
});
|
System.register([], function (exports_1, context_1) {
"use strict";
var estonia;
var __moduleName = context_1 && context_1.id;
return {
setters: [],
execute: function () {
exports_1("estonia", estonia = {
name: 'Estonia',
codes: ['EE', 'EST', '233'],
calcFn: (vat) => {
let total = 0;
let expect;
// Extract the next digit and multiply by the counter.
for (let i = 0; i < 8; i++) {
total += Number(vat.charAt(i)) * estonia.rules.multipliers.common[i];
}
// Establish check digits using modulus 10.
total = 10 - (total % 10);
if (total === 10)
total = 0;
// Compare it with the last character of the VAT number. If it's the same, then it's valid.
expect = Number(vat.slice(8, 9));
return total === expect;
},
rules: {
multipliers: {
common: [3, 7, 1, 3, 7, 1, 3, 7]
},
regex: [/^(EE)(10\d{7})$/]
}
});
}
};
});
|
// Gravity Constant
var GRAVITY;
// Constant for a multiplier to try and ensure disc doesn't get stuck in obstacle
var ESC_VELOCITY_MULT = 1.06;
// has the ball been dropped?
var isDiscDropping = false;
//The user's input names
var names = [];
// the PlinkoBoard object that contains the pegs and discs
var Board;
//This will become true when everything is ready
var loadAllDataFinished = false;
var foundWinner = false;
//The winner name index
var winner = null;
//Start button
var removeNameBtn;
// Hide the names before the ball has been dropped toggle
var hideNames = true;
function setup() {
GRAVITY = createVector(0, .5); // init gravity
// Make the canvas full screen size
canvas = createCanvas(windowWidth, windowHeight);
canvas.position(0, 0);
ellipseMode(CENTER);
// Make a silly github thing
var github = createA('https://github.com/shiffman/randomizer', '');
var gitimg = createImg('https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png');
gitimg.id('gitimg');
github.child('gitimg');
gitimg.attribute('style', 'position: absolute; top: 0; right: 0; border: 0;');
// button for removing winner and restarting
removeNameBtn = createButton("Remove & Restart");
removeNameBtn.class('button');
removeNameBtn.position(20, windowHeight - 40);
removeNameBtn.mousePressed(removeName);
removeNameBtn.hide();
Board = new PlinkoBoard(createVector(50, 25), windowWidth - 100, windowHeight - 100);
loadFirebase(initialize);
textSize(15);
textStyle(BOLD);
}
function draw() {
background(20);
Board.show();
Board.update();
if (isDiscDropping && loadAllDataFinished && foundWinner) {
//Show the winner text
textSize(35);
fill(255);
text("And the winner is...", width / 2 - 160, height / 2 - height / 4);
textSize(55);
fill(0);
text(Board.names[winner], width / 2 - Board.names[winner].length * 16, height / 2 - height / 8);
}
}
function initialize() {
Board.setNames(names);
//Everything is ready to go!
loadAllDataFinished = true;
}
function mousePressed() {
// if disc isn't moving already and mouse is outside board (hitting remove button)
if (!isDiscDropping && (mouseY < Board.size_height+Board.position.y)) {
startSimulation();
}
}
function removeName() {
if (isDiscDropping) {
removeNameBtn.hide();
Board = new PlinkoBoard(createVector(50, 25), windowWidth - 100, windowHeight - 100);
loadAllDataFinished = false;
isDiscDropping = false;
foundWinner = false;
names.splice(winner, 1);
winner = null;
initialize();
}
}
function startSimulation() {
//If the sketch is already "running" then reset all the variables
if (isDiscDropping) {
Board = new PlinkoBoard(createVector(50, 25), windowWidth - 100, windowHeight - 100);
loadAllDataFinished = false;
foundWinner = false;
winner = null;
}
isDiscDropping = true;
}
|
Asyncplify.prototype.flatMapLatest = function (options) {
return new Asyncplify(FlatMapLatest, options, this);
};
function FlatMapLatest(options, sink, source) {
this.mapper = options || identity;
this.sink = sink;
this.sink.source = this;
this.source = null;
this.subscription = null;
source._subscribe(this);
}
FlatMapLatest.prototype = {
childEnd: function (err, item) {
this.subscription = null;
if (err && this.source) {
this.source.setState(Asyncplify.states.CLOSED);
this.source = null;
this.mapper = noop;
}
if (err || !this.source) this.sink.end(err);
},
emit: function (v) {
var item = this.mapper(v);
if (item) {
if (this.subscription) this.subscription.setState(Asyncplify.states.CLOSED);
this.subscription = new FlatMapItem(this);
item._subscribe(this.subscription);
}
},
end: function (err) {
this.mapper = noop;
this.source = null;
if (err && this.subscription) {
this.subscription.setState(Asyncplify.states.CLOSED);
this.subscription = null;
}
if (err || !this.subscription) this.sink.end(err);
},
setState: function (state) {
if (this.source) this.source.setState(state);
if (this.subscription) this.subscription.setState(state);
}
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.