code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
---|---|---|---|---|---|
import React, {Component} from 'react';
import LanguageSwitcher from './LanguageSwitcher';
import Navigation from './Navigation';
import $ from 'jquery';
const Translate = require('react-i18nify').Translate;
export default class Menu extends Component{
constructor(){
super();
let self = this;
this.state = {currentPage: '#home', isOpen: 0};
this.bindSidebarCallback();
$("body").on("click", (event) => {
let countElementClicks = (counter, element) => counter + event.target.className.indexOf(element);
let elements = ['nav-item', 'menu-toggler', 'language-switcher', "lang", "toggler"];
let isClicked = elements.reduce(countElementClicks, elements.length);
if(isClicked == 0)
this.setState({isOpen: 0});
});
}
handleClick(e){
e.preventDefault();
var section = e.target.getAttribute('href') || e.target.parentNode.getAttribute('href');
Navigation.goTo(section);
}
toggleMenu(e){
e.preventDefault();
this.setState(prevState => ({ isOpen: !prevState.isOpen }));
}
bindSidebarCallback(){
let self = this;
function setStateOnResizeWindow(){
if($(this).width() <= 768)
self.setState((previousState) => ({isOpen: 0}));
}
$(window).resize(setStateOnResizeWindow);
setStateOnResizeWindow();
}
render(){
return (
<div className="menu">
<div className="container ">
<nav className={this.state.isOpen > 0 ? "nav-item is-open" : "nav-item"}>
<a href="#home" className="manguezal-logo-small" onClick={this.handleClick.bind(this)}> Manguez.al</a>
<a href="#" className={this.state.isOpen > 0 ? "menu-toggler menu-toggler__is-open" : "menu-toggler"} onClick={this.toggleMenu.bind(this)}> </a>
<div className="menu-group">
<a href="#welcome" onClick={this.handleClick.bind(this)}><Translate value="nav_about"/></a>
<a href="#startups" onClick={this.handleClick.bind(this)}><Translate value="nav_startups"/></a>
<a href="#events" onClick={this.handleClick.bind(this)}><Translate value="nav_events"/></a>
<a href="#newsletter" onClick={this.handleClick.bind(this)}><Translate value="nav_newsletter"/></a>
<a href="https://medium.com/comunidade-empreendedora-manguezal" target="_blank"><Translate value="nav_blog"/></a>
</div>
<LanguageSwitcher />
</nav>
</div>
</div>
)
}
} | lhew/manguezal-test | src/components/Menu.js | JavaScript | mit | 2,593 |
define(
['polygonjs/math/Color'],
function (Color) {
"use strict";
var Surface = function (opts) {
opts = opts || {};
this.width = opts.width || 640;
this.height = opts.height || 480;
this.cx = this.width / 2;
this.cy = this.height / 2;
var canvas = this.createEl('canvas', {
style: 'background: black',
width: this.width,
height: this.height
});
var container = typeof opts.container === 'string' ?
document.getElementById(opts.container) :
opts.container;
container.appendChild(canvas);
this.container = container;
this.canvas = canvas;
this.context = canvas.getContext('2d');
return this;
};
Surface.create = function (opts) {
return new Surface(opts);
};
Surface.prototype = {
createEl: function (name, attrs) {
var el = document.createElement(name);
attrs = attrs || {};
for (var attr in attrs)
this.setAttr(el, attr, attrs[attr]);
return el;
},
setAttr: function (el, name, value) {
el.setAttribute(name, value);
},
setAttrNS: function (el, namespace, name, value) {
el.setAttributeNS(namespace, name, value);
},
clear: function () {
this.context.clearRect(0, 0, this.width, this.height);
},
polygon: function (points, color) {
var len = points.length;
if (len > 1) {
var ctx = this.context;
var a = points[0];
// var b = points[1];
// var tint = Color.create({r: 0.0, g: 0.05, b: 0.0});
// var gradient = ctx.createLinearGradient(
// a.x + this.cx, -a.y + this.cy,
// b.x + this.cx, -b.y + this.cy);
//
// gradient.addColorStop(0, color.clone().subtract(tint).clamp().getHexStyle());
// gradient.addColorStop(1, color.clone().add(tint).clamp().getHexStyle());
ctx.fillStyle = color.getHexStyle();
// ctx.strokeStyle = color;
ctx.beginPath();
ctx.moveTo(a.x + this.cx, -a.y + this.cy);
for (var i = 1; i < len; i++) {
a = points[i];
ctx.lineTo(a.x + this.cx, -a.y + this.cy);
}
ctx.closePath();
ctx.fill();
// ctx.stroke(); // Gets rid of seams but performance hit
}
},
line: function (from, to, color) {
var ctx = this.context;
ctx.strokeStyle = color.getHexStyle();
ctx.beginPath();
ctx.moveTo(from.x + this.cx, -from.x + this.cy);
ctx.lineTo(to.x + this.cx, -to.y + this.cy);
ctx.stroke();
},
render: function () {}
};
return Surface;
}
);
| WebSeed/PolygonJS | polygonjs/surfaces/CanvasSurface.js | JavaScript | mit | 3,361 |
'use strict';
var handler = {
fragments: null,
tab: null,
tabId: 0,
windowId: 0,
captureCmd: '',
initContextMenu: function () {},
queryActiveTab: function (callback) {
chrome.tabs.query({
active: true,
lastFocusedWindow: true
}, function (tabs) {
var tab = tabs && tabs[0] || {};
handler.tab = tab;
handler.tabId = tab.id;
handler.windowId = tab.windowId;
callback && callback(tab);
});
},
checkContentScript: function () {
handler.queryActiveTab(function () {
handler.executeScript({
file: "js/isLoaded.js"
});
});
},
injectContentScript: function () {
handler.executeScript({ file: "js/content.js" }, function () {
handler.onContentReady();
});
},
executeScript: function (details, callback) {
if (handler.tabId) {
chrome.tabs.executeScript(handler.tabId, details, callback);
}
},
onContentReady: function () {
if (handler.captureCmd) {
handler.sendCaptureCmd(handler.captureCmd);
handler.captureCmd = '';
}
},
sendCaptureCmd: function (cmd) {
handler.queryActiveTab(function (tab) {
chrome.tabs.sendMessage(tab.id, {
action: cmd
});
});
},
captureElement: function () {
// capture the selected html element
handler.captureCmd = 'captureElement';
handler.checkContentScript();
},
captureRegion: function () {
// capture the crop region
handler.captureCmd = 'captureRegion';
handler.checkContentScript();
},
captureEntire: function () {
// capture entire page
handler.captureCmd = 'captureEntire';
handler.checkContentScript();
},
captureVisible: function () {
// capture the visible part of page
handler.captureCmd = 'captureVisible';
handler.checkContentScript();
},
captureWindow: function () {
// capture desktop window
},
editContent: function () {
// TODO: 更好的编辑模式提示,可离开编辑模式
handler.queryActiveTab(function () {
handler.executeScript({
allFrames: true,
code: 'document.designMode="on"'
}, function () {
alert('Now you can edit this page');
});
});
},
clearFragments: function () {
handler.fragments = null;
},
onFragment: function (message, sender) {
chrome.tabs.captureVisibleTab(sender.tab.windowId, {
format: 'png'
}, function (dataURI) {
var fragments = handler.fragments;
var fragment = message.fragment;
fragment.dataURI = dataURI;
if (!fragments) {
fragments = handler.fragments = [];
}
fragments.push(fragment);
chrome.tabs.sendMessage(sender.tab.id, { action: 'nextFragment' });
});
},
onCaptureEnd: function (message, sender) {
var fragments = handler.fragments;
if (fragments && fragments.length) {
var fragment = fragments[0];
var totalWidth = fragment.totalWidth;
var totalHeight = fragment.totalHeight;
if (fragment.ratio !== 1) {
totalWidth *= fragment.ratio;
totalHeight *= fragment.ratio;
}
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.width = Math.round(totalWidth);
canvas.height = Math.round(totalHeight);
var totalCount = fragments.length;
var loadedCount = 0;
fragments.forEach(function (data) {
var image = new Image();
var ratio = data.ratio;
var sx = Math.round(data.sx * ratio);
var sy = Math.round(data.sy * ratio);
var dx = Math.round(data.dx * ratio);
var dy = Math.round(data.dy * ratio);
var width = Math.round(data.width * ratio);
var height = Math.round(data.height * ratio);
image.onload = function () {
context.drawImage(image,
sx, sy,
width, height,
dx, dy,
width, height
);
loadedCount++;
if (loadedCount === totalCount) {
handler.clearFragments();
var croppedDataUrl = canvas.toDataURL('image/png');
chrome.tabs.create({
url: croppedDataUrl,
windowId: sender.tab.windowId
});
}
};
image.src = data.dataURI;
});
}
console.log(fragments);
},
};
// handle message from tabs
chrome.runtime.onMessage.addListener(function (message, sender, callback) {
console.log(message);
if (!sender || sender.id !== chrome.runtime.id || !sender.tab) {
return;
}
var action = message.action;
if (action && handler[action]) {
return handler[action](message, sender, callback);
}
});
| bubkoo/crx-element-capture | src/js/background.js | JavaScript | mit | 4,787 |
const isAsync = (caller) => caller && caller.ASYNC;
module.exports = api => {
const ASYNC = api.caller(isAsync);
return {
babelrc: false,
plugins: [
['./babel-plugin-$-identifiers-and-imports', { ASYNC }],
['macros', { async: { ASYNC } }],
// use dead code elimination to clean up if(false) {} and if(true) {}
['minify-dead-code-elimination', { keepFnName: true, keepFnArgs: true, keepClassName: true }],
],
}
}
| sithmel/iter-tools | generate/babel-generate.config.js | JavaScript | mit | 456 |
import React from 'react';
import PropTypes from 'prop-types';
import Post from './Post';
const Posts = ({ posts }) => (
<div>
{posts
.filter(post => post.frontmatter.title.length > 0)
.map((post, index) => <Post key={index} post={post} />)}
</div>
);
Posts.propTypes = {
posts: PropTypes.arrayOf(PropTypes.object),
};
export default Posts;
| kbariotis/kostasbariotis.com | src/components/blog/Posts.js | JavaScript | mit | 367 |
'use strict';
const Promise = require('bluebird');
const { Transform } = require('readable-stream');
const vfs = require('vinyl-fs');
module.exports = function assets(src, dest, options = {}) {
const { parser, env } = options;
Reflect.deleteProperty(options, 'parser');
Reflect.deleteProperty(options, 'env');
const opts = Object.assign({ allowEmpty: true }, options);
return new Promise((resolve, reject) => {
let stream = vfs.src(src, opts);
if (parser) {
const transform = new Transform({
objectMode: true,
transform: (file, enc, cb) => {
parser(file, enc, env);
return cb(null, file);
},
});
stream = stream.pipe(transform);
}
stream.pipe(vfs.dest(dest)).on('error', reject).on('finish', resolve);
});
};
| oddbird/sassdoc-theme-herman | lib/utils/assets.js | JavaScript | mit | 801 |
'use strict';
function injectJS(src, cb) {
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.onreadystatechange = script.onload = function () {
var readyState = script.readyState;
if (!readyState || readyState == 'loaded' || readyState == 'complete' || readyState == 'uninitialized') {
cb && cb();
script.onload = script.onreadystatechange = script.onerror = null;
}
};
script.src = src;
document.body.appendChild(script);
}
| elpadi/js-library | dist/utils.js | JavaScript | mit | 496 |
/**
* Created by desen on 2017/7/24.
*/
function isArray(value) {
if (typeof Array.isArray === "function") {
return Array.isArray(value);
} else {
return Object.prototype.toString.call(value) === "[object Array]";
}
}
// 进行虚拟DOm的类型的判断
function isVtext(vNode) {
return true;
}
| enmeen/2017studyPlan | someDemo/虚拟DOM实现/util.js | JavaScript | mit | 307 |
import babel from 'rollup-plugin-babel';
export default {
plugins: [babel()]
};
| alexeyraspopov/message-script | rollup.config.js | JavaScript | mit | 83 |
var lang = navigator.language;
exports.set_lang=function(_lang,msgs){
lang = _lang || navigator.language;
if(lang.indexOf('en')===0){
lang = 'en';
}else if(lang.indexOf('es')===0){
lang = 'es';
}else{
lang = 'en';
}
var nodes = document.querySelectorAll('[msg]');
for(var i = 0; i < nodes.length; i++){
var node = nodes.item(i);
if(node.getAttribute("placeholder")){
node.setAttribute("placeholder",property(msgs,lang+"."+node.getAttribute("msg")));
}else{
node.innerText = property(msgs,lang+"."+node.getAttribute("msg"));
node.textContent = node.innerText;
}
}
window.userLang = lang;
};
exports.get=function(msg,msgs){
return property(msgs,lang+"."+msg);
};
function property(o,s){
if(typeof s === 'undefined'){
return '';
}
if(typeof o === 'undefined'){
return s;
}
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
s = s.replace(/^\./, ''); // strip a leading dot
var a = s.split('.');
while (a.length) {
var n = a.shift();
if (n in o) {
o = o[n];
} else {
return s;
}
}
return o;
}
| Technogi/website | src/scripts/msg.js | JavaScript | mit | 1,145 |
'use strict';
const postcodeApi = require('../index.js');
const sinon = require('sinon');
const chai = require('chai');
const expect = chai.expect;
const sinonChai = require('sinon-chai');
const requestApi = require('../lib/requestApi.js');
before(() => {
chai.use(sinonChai);
});
var sandbox;
beforeEach(() => {
sandbox = sinon.createSandbox();
});
afterEach(() => {
sandbox.restore();
});
// Loading assets
const response1 = require('./assets/followNext/response1.json');
const response2 = require('./assets/followNext/response2.json');
const response3 = require('./assets/followNext/response3.json');
const expectedResult = require('./assets/followNext/expected.json');
const rateLimit = {
limit: 123,
remaining: 123
};
const rateLimitLast = {
limit: 123,
remaining: 0
};
describe('helpers/followNext()', () => {
it('should be able to follow next-href of the _links object in a response', () => {
// Preparing requestApi
const requestApiStub = sandbox.stub(requestApi, 'get').callsFake((options, callback) => {
switch (options.url) {
// Respond with the correct json
case 'https://www.test.nl/page1':
return callback(null, response1, rateLimit);
case 'https://www.test.nl/page2':
return callback(null, response2, rateLimit);
case 'https://www.test.nl/page3':
return callback(null, response3, rateLimitLast);
}
});
// Preparing options
let options = {
url: 'https://www.test.nl/page1'
};
// Run the function
return postcodeApi.helpers.followNext(options, (error, body, rateLimit) => {
expect(error).to.eql(null);
expect(body).to.eql(expectedResult);
expect(rateLimit).to.eql(undefined);
expect(requestApiStub).to.be.calledWith(options);
expect(requestApiStub).to.be.calledThrice;
});
});
it('should be to return the correct rateLimits after performing several requests', () => {
// Preparing requestApi
const requestApiStub = sandbox.stub(requestApi, 'get').callsFake((options, callback) => {
switch (options.url) {
// Respond with the correct json
case 'https://www.test.nl/page1':
return callback(null, response1, rateLimit);
case 'https://www.test.nl/page2':
return callback(null, response2, rateLimit);
case 'https://www.test.nl/page3':
return callback(null, response3, rateLimitLast);
}
});
// Setting options
let options = {
url: 'https://www.test.nl/page1',
returnRateLimit: true
};
// Run the function
return postcodeApi.helpers.followNext(options, (error, body, rateLimit) => {
expect(error).to.eql(null);
expect(body).to.eql(expectedResult);
expect(rateLimit).to.eql(rateLimitLast);
expect(requestApiStub).to.be.calledWith(options);
expect(requestApiStub).to.be.calledThrice;
});
});
it('should be able to handle a single response without next-href', () => {
// Preparing requestApi
const requestApiStub = sandbox.stub(requestApi, 'get').callsFake((options, callback) => {
return callback(null, response3);
});
postcodeApi.helpers.followNext({}, (error, body, rateLimit) => {
expect(error).to.eql(null);
expect(body).to.eql(response3);
expect(rateLimit).to.eql(undefined);
expect(requestApiStub).to.be.calledOnce;
});
});
it('should be able to handle a single response without next-href and return the right rateLimit', () => {
// Preparing requestApi
const requestApiStub = sandbox.stub(requestApi, 'get').callsFake((options, callback) => {
return callback(null, response3, rateLimitLast);
});
// Setting options
let options = {
returnRateLimit: true
};
return postcodeApi.helpers.followNext(options, (error, body, rateLimit) => {
expect(error).to.eql(null);
expect(body).to.eql(response3);
expect(rateLimit).to.eql(rateLimitLast);
expect(requestApiStub).to.be.calledWith(options);
expect(requestApiStub).to.be.calledOnce;
});
});
it('should be able to handle errors from requestApi.get()', () => {
// Preparing requestApi
const requestApiStub = sandbox.stub(requestApi, 'get').callsFake((options, callback) => {
return callback(new Error('Error'), null);
});
return postcodeApi.helpers.followNext({}, (error, body, rateLimit) => {
expect(error).to.be.instanceof(Error);
expect(body).to.eql(null);
expect(rateLimit).to.eql(undefined);
expect(requestApiStub).to.be.calledOnce;
});
});
it('should be able to handle no results from the external API', () => {
// Preparing requestApi
const requestApiStub = sandbox.stub(requestApi, 'get').callsFake((options, callback) => {
return callback(null, null);
});
return postcodeApi.helpers.followNext({}, (error, body, rateLimit) => {
expect(error).to.eql(null);
expect(body).to.eql(null);
expect(rateLimit).to.eql(undefined);
expect(requestApiStub).to.be.calledOnce;
});
});
it('should be able to handle errors from mergeResults() when performing there is a next-href', () => {
// Preparing requestApi
const requestApiStub = sandbox.stub(requestApi, 'get').callsFake((options, callback) => {
return callback(null, response1);
});
const mergeResults = sandbox.stub(postcodeApi.helpers, 'mergeResults')
.callsFake((source, destination, callback) => {
return callback(new Error('Error'), null);
});
return postcodeApi.helpers.followNext({}, (error, body, rateLimit) => {
expect(error).to.be.instanceof(Error);
expect(body).to.eql(null);
expect(rateLimit).to.eql(undefined);
expect(requestApiStub).to.be.calledTwice;
expect(mergeResults).to.be.calledOnce;
});
});
it('should be able to handle errors from mergeResults() when performing there is no next-href', () => {
// Preparing requestApi
const requestApiStub = sandbox.stub(requestApi, 'get').callsFake((options, callback) => {
return callback(null, response3);
});
const mergeResults = sandbox.stub(postcodeApi.helpers, 'mergeResults')
.callsFake((source, destination, callback) => {
return callback(new Error('Error'), null);
});
return postcodeApi.helpers.followNext({}, response2, (error, body, rateLimit) => {
expect(error).to.be.instanceof(Error);
expect(body).to.eql(null);
expect(rateLimit).to.eql(undefined);
expect(requestApiStub).to.be.calledOnce;
expect(mergeResults).to.be.calledOnce;
});
});
});
| joostdebruijn/node-postcode-nl | test/helpers.followNext.js | JavaScript | mit | 6,658 |
import test from 'ava';
import { actionTest } from 'redux-ava';
import {
ADD_POST_REQUEST,
DELETE_POST_REQUEST,
} from '../constants';
import {
addPostRequest,
deletePostRequest,
} from '../PostActions';
const post = { name: 'Prashant', title: 'Hello Mern', cuid: 'f34gb2bh24b24b2', content: "All cats meow 'mern!'", slug: 'hello-mern', _id: 1 };
test('should return the correct type for addPostRequest', actionTest(
addPostRequest,
post,
{ type: ADD_POST_REQUEST, post },
));
test('should return the correct type for deletePostRequest', actionTest(
deletePostRequest,
post.cuid,
{ type: DELETE_POST_REQUEST, cuid: post.cuid },
));
| Skrpk/mern-sagas | client/modules/Post/__tests__/PostActions.spec.js | JavaScript | mit | 657 |
version https://git-lfs.github.com/spec/v1
oid sha256:ba1edb37cd9663c92048dc14cd2f7e9e81d2ce7364194e973ba9e1238f9198a2
size 878
| yogeshsaroya/new-cdnjs | ajax/libs/extjs/4.2.1/src/lang/Number.min.js | JavaScript | mit | 128 |
/**
* Module dependencies
*/
var uuid = require('uuid');
var utils = require('../utils');
var safeRequire = utils.safeRequire;
var helpers = utils.helpers;
var couchbase = safeRequire('couchbase');
var CouchBase;
exports.initialize = function (schema, callback) {
var db, opts;
opts = schema.settings || {};
if (!opts.url) {
var host = opts.host || 'localhost';
var port = opts.port || '8091';
var database = opts.database || 'test';
var proto = opts.ssl ? 'couchbases' : 'couchbase';
opts.url = proto + '://' + host + ':' + port;
}
schema.client = new couchbase.Cluster(opts.url);
db = schema.client.openBucket(database);
schema.adapter = new CouchBase(schema.client, db);
process.nextTick(function () {
schema.adapter.db = schema.client.openBucket(database);
return callback && callback();
}.bind(this));
};
function CouchBase(client, db, callback) {
this.name = 'couchbase';
this.client = client;
this.db = db;
this._models = {};
}
CouchBase.prototype.define = function (descr) {
var m, self = this;
m = descr.model.modelName;
descr.properties._rev = {
type: String
};
var design = {
views: {
all: {
map: 'function (doc, meta) { if (doc._type === "' + m.toLowerCase() + '") { return emit(doc._type, doc); } }',
reduce: '_count'
}
}
};
return self.db.manager().insertDesignDocument('caminte_' + m.toLowerCase(), design, function (err, doc) {
return self.db.get('caminte_' + m.toLowerCase() + '_counter', function (err, doc) {
if (!doc) {
self.db.insert('caminte_' + m.toLowerCase() + '_counter', 0, function () {
return self._models[m] = descr;
});
} else {
return self._models[m] = descr;
}
});
});
};
CouchBase.prototype.create = function (model, data, callback) {
var self = this;
data._type = model.toLowerCase();
helpers.savePrep(data);
return self.db.counter('caminte_' + data._type + '_counter', +1, function (err, res) {
if (err) {
console.log('create counter for ' + data._type + ' failed', err);
}
var uid = res && res.value ? (data._type + '_' + res.value) : uuid.v1();
var key = data.id || uid;
data.id = key;
return self.db.upsert(key, self.forDB(model, data), function (err, doc) {
return callback(err, key);
});
});
};
CouchBase.prototype.save = function (model, data, callback) {
var self = this;
data._type = model.toLowerCase();
helpers.savePrep(data);
var uid = uuid.v1();
var key = data.id || data._id || uid;
if (data.id) {
delete data.id;
}
if (data._id) {
delete data._id;
}
return self.db.replace(key, self.forDB(model, data), function (err, doc) {
return callback(err, key);
});
};
CouchBase.prototype.updateOrCreate = function (model, data, callback) {
var self = this;
return self.exists(model, data.id, function (err, exists) {
if (exists) {
return self.save(model, data, callback);
} else {
return self.create(model, data, function (err, id) {
data.id = id;
return callback(err, data);
});
}
});
};
CouchBase.prototype.exists = function (model, id, callback) {
return this.db.get(id, function (err, doc) {
if (err) {
return callback(null, false);
}
return callback(null, doc);
});
};
CouchBase.prototype.findById = function (model, id, callback) {
var self = this;
return self.db.get(id, function (err, data) {
var doc = data && (data.doc || data.value) ? (data.doc || data.value) : null;
if (doc) {
if (doc._type) {
delete doc._type;
}
doc = self.fromDB(model, doc);
if (doc._id) {
doc.id = doc._id;
delete doc._id;
}
}
return callback(err, doc);
});
};
CouchBase.prototype.destroy = function (model, id, callback) {
var self = this;
return self.db.remove(id, function (err, doc) {
if (err) {
return callback(err);
}
callback.removed = true;
return callback();
});
};
CouchBase.prototype.updateAttributes = function (model, id, data, callback) {
var self = this;
return self.findById(model, id, function (err, base) {
if (err) {
return callback(err);
}
if (base) {
data = helpers.merge(base, data);
data.id = id;
}
return self.save(model, data, callback);
});
};
CouchBase.prototype.count = function (model, callback, where) {
var self = this;
var query = new couchbase.ViewQuery()
.from('caminte_' + model, 'all')
.reduce(true)
.stale(1)
.include_docs(true);
return self.db.query(query, function (err, body) {
return callback(err, docs.length);
});
};
CouchBase.prototype.destroyAll = function (model, callback) {
var self = this;
return self.all(model, {}, function (err, docs) {
return callback(err, docs);
});
};
CouchBase.prototype.forDB = function (model, data) {
var k, props, v;
if (data === null) {
data = {};
}
props = this._models[model].properties;
for (k in props) {
v = props[k];
if (data[k] && props[k].type.name === 'Date'
&& (data[k].getTime !== null)
&& (typeof data[k].getTime === 'function')) {
data[k] = data[k].getTime();
}
}
return data;
};
CouchBase.prototype.fromDB = function (model, data) {
var date, k, props, v;
if (!data) {
return data;
}
props = this._models[model].properties;
for (k in props) {
v = props[k];
if ((data[k] !== null) && props[k].type.name === 'Date') {
date = new Date(data[k]);
date.setTime(data[k]);
data[k] = date;
}
}
return data;
};
CouchBase.prototype.remove = function (model, filter, callback) {
var self = this;
return self.all(model, filter, function (err, docs) {
var doc;
console.log(docs)
// return _this.db.bulk({
// docs: docs
// }, function (err, body) {
return callback(err, docs);
// });
});
};
/*
CouchBase.prototype.destroyById = function destroyById(model, id, callback) {
var self = this;
return self.db.remove(id, function (err, doc) {
console.log(err, doc)
return callback(err, doc);
});
};
*/
CouchBase.prototype.all = function (model, filter, callback) {
if ('function' === typeof filter) {
callback = filter;
filter = {};
}
if (!filter) {
filter = {};
}
var self = this;
var query = new couchbase.ViewQuery()
.from('caminte_' + model, 'all')
.reduce(false)
.include_docs(true);
if (filter.order) {
if (/desc/gi.test()) {
query.order(couchbase.ViewQuery.Order.DESCENDING);
}
// query.order(filter.order);
}
if (filter.skip) {
query.skip(filter.skip);
}
if (filter.limit) {
query.limit(filter.limit);
}
if (filter.where) {
query.custom(filter.where);
}
return self.db.query(query, function (err, body) {
var doc, docs, i, k, key, orders, row, sorting, v, where, _i, _len;
if (err) {
if (err.statusCode == 404) {
return err;
} else {
return err;
}
}
docs = body.map(function (row) {
var item = row.value;
item.id = row.id;
return item;
});
// console.log('docs:', docs)
where = filter !== null ? filter.where : void 0;
if (where) {
docs = docs ? docs.filter(helpers.applyFilter(filter)) : docs;
}
orders = filter !== null ? filter.order : void 0;
if (orders) {
if (typeof orders === 'string') {
orders = [orders];
}
sorting = function (a, b) {
var ak, bk, i, item, rev, _i, _len;
for (i = _i = 0, _len = this.length; _i < _len; i = ++_i) {
item = this[i];
ak = a[this[i].key];
bk = b[this[i].key];
rev = this[i].reverse;
if (ak > bk) {
return 1 * rev;
}
if (ak < bk) {
return -1 * rev;
}
}
return 0;
};
for (i = _i = 0, _len = orders.length; _i < _len; i = ++_i) {
key = orders[i];
orders[i] = {
reverse: helpers.reverse(key),
key: helpers.stripOrder(key)
};
}
docs.sort(sorting.bind(orders));
}
return callback(err, (function () {
var _j, _len1, _results;
_results = [];
for (_j = 0, _len1 = docs.length; _j < _len1; _j++) {
doc = docs[_j];
_results.push(this.fromDB(model, doc));
}
return _results;
}).call(self));
});
};
CouchBase.prototype.autoupdate = function (callback) {
this.client.manager().createBucket(database, {}, function (err) {
if (err) console.log('createBucket', err)
return callback && callback();
});
};
| biggora/caminte | lib/adapters/couchbase.js | JavaScript | mit | 9,831 |
var ObjectExplorer = require('../')
var explorer = document.getElementById('explorer')
var add = document.getElementById('add')
var obj = {
a: 10,
b: true,
reg: /foo/g,
dat: new Date('2013-08-29'),
str: "fooo, bar"
}
obj.self = obj
obj.arr = [obj, obj, obj]
obj.longArr = []
for (i = 0; i < 500; i++) obj.longArr.push(i)
var state = null
function next() {
var e = new ObjectExplorer(obj, state)
e.appendTo(explorer)
state = e.state
}
next()
add.addEventListener('click', next, false) | ForbesLindesay/object-explorer | demo/client.js | JavaScript | mit | 503 |
var global = window;
var Stack = require('lib/swing/stack'),
Card = require('lib/swing/card');
global.gajus = global.gajus || {};
global.gajus.Swing = {
Stack: Stack,
Card: Card
};
module.exports = {
Stack: Stack,
Card: Card
};
| unbug/generator-webappstarter | app/templates/app/src/lib/swing/swing.js | JavaScript | mit | 242 |
const FliprYaml = require('../lib/flipr-yaml');
const source = new FliprYaml({
filePath: 'sample/config/basic.yaml',
});
source.preload()
.then(() => {
console.log('Config file has been read and cached. Any changes to the .yaml file will not be read by flipr-yaml.');
})
.then(() => source.flush())
.then(() => {
console.log('Cache has been flushed. The next call to flipr-yaml will result in the file being read and cached again.');
});
| godaddy/node-flipr-yaml | sample/flush-cache.js | JavaScript | mit | 461 |
/*
Copyright 2019 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
const expect = require('chai').expect;
const activateAndControlSW = require('../../../infra/testing/activate-and-control');
const cleanSWEnv = require('../../../infra/testing/clean-sw');
const runInSW = require('../../../infra/testing/comlink/node-interface');
describe(`[workbox-precaching] cleanupOutdatedCaches()`, function () {
const baseURL = `${global.__workbox.server.getAddress()}/test/workbox-precaching/static/cleanup-outdated-caches/`;
beforeEach(async function () {
// Navigate to our test page and clear all caches before this test runs.
await cleanSWEnv(global.__workbox.webdriver, `${baseURL}integration.html`);
});
it(`should clean up outdated precached after activation`, async function () {
// Add an item to an outdated cache.
const preActivateKeys = await global.__workbox.webdriver.executeAsyncScript(
(cb) => {
// Opening a cache with a given name will cause it to "exist", even if it's empty.
caches
.open(
'workbox-precache-http://localhost:3004/test/workbox-precaching/static/cleanup-outdated-caches/',
)
.then(() => caches.keys())
.then((keys) => cb(keys))
.catch((err) => cb(err.message));
},
);
expect(preActivateKeys).to.include(
'workbox-precache-http://localhost:3004/test/workbox-precaching/static/cleanup-outdated-caches/',
);
expect(preActivateKeys).to.not.include(
'workbox-precache-v2-http://localhost:3004/test/workbox-precaching/static/cleanup-outdated-caches/',
);
// Register the first service worker.
await activateAndControlSW(`${baseURL}sw.js`);
const postActivateKeys = await runInSW('cachesKeys');
expect(postActivateKeys).to.not.include(
'workbox-precache-http://localhost:3004/test/workbox-precaching/static/cleanup-outdated-caches/',
);
expect(postActivateKeys).to.include(
'workbox-precache-v2-http://localhost:3004/test/workbox-precaching/static/cleanup-outdated-caches/',
);
});
});
| GoogleChrome/workbox | test/workbox-precaching/integration/test-cleanup-outdated-caches.js | JavaScript | mit | 2,212 |
import { AudioStreamFormat } from 'microsoft-cognitiveservices-speech-sdk';
export { AudioStreamFormat };
| billba/botchat | packages/testharness/pre/external/microsoft-cognitiveservices-speech-sdk/index.js | JavaScript | mit | 107 |
app.controller('MapsCTRL2', function($scope) {
app.value('NEW_TODO_ID', -1);
app.service('mapService', function () {
var map;
this.setMap = function (myMap) {
map = myMap;
};
this.getMap = function () {
if (map) return map;
throw new Error("Map not defined");
};
this.getLatLng = function () {
var center = map.getCenter();
return {
lat: center.lat(),
lng: center.lng()
};
};
});
app.service('todosService', function ($filter) {
// nextId and list both have mock starting data
this.nextId = 4;
this.items = [
{
id: 1,
completed: false,
title: 'Play Tennis',
desc: '',
lat: 43.09278984218124,
lng: -89.36774236078266
}, {
id: 2,
completed: true,
title: 'Buy Groceries',
desc: 'Steak, Pasta, Spinach',
lat: 43.06487353914984,
lng: -89.41749499107603
}, {
id: 3,
completed: false,
title: 'Picnic Time',
desc: 'Hang out with friends',
lat: 43.0869882068853,
lng: -89.42141638065578
}
];
this.filter = {};
this.filtered = function () {
return $filter('filter')(this.items, this.filter);
};
this.remainingCount = function () {
return $filter('filter')(this.items, {completed: false}).length;
};
this.getTodoById = function (todoId) {
var todo, i;
for (i = this.items.length - 1; i >= 0; i--) {
todo = this.items[i];
if (todo.id === todoId) {
return todo;
}
}
return false;
};
this.addTodo = function (title, desc, lat, lng) {
var newTodo = {
id: this.nextId++,
completed: false,
title: title,
desc: desc,
lat: lat,
lng: lng
};
this.items.push(newTodo);
};
this.updateTodo = function (todoId, title, desc, lat, lng, comp) {
var todo = this.getTodoById(todoId);
if (todo) {
todo.title = title;
todo.desc = desc;
todo.lat = lat;
todo.lng = lng;
todo.completed = comp;
todo.id = this.nextId++;
}
};
this.prune = function () {
var flag = false, i;
for (var i = this.items.length - 1; i >= 0; i--) {
if (this.items[i].completed) {
flag = true;
this.items.splice(i, 1);
}
}
if (flag) this.nextId++;
};
});
app.service('markersService', function () {
this.markers = [];
this.getMarkerByTodoId = function (todoId) {
var marker, i;
for (i = this.markers.length - 1; i >= 0; i--) {
marker = this.markers[i];
if (marker.get("id") === todoId) {
return marker;
}
}
return false;
};
});
app.service('infoWindowService', function (mapService) {
var infoWindow;
this.data = {};
this.registerInfoWindow = function (myInfoWindow) {
infowindow = myInfoWindow;
};
this.setData = function (todoId, todoTitle, todoDesc) {
this.data.id = todoId;
this.data.title = todoTitle;
this.data.desc = todoDesc;
};
this.open = function (marker) {
infowindow.open(mapService.getMap(), marker);
};
this.close = function () {
if (infowindow) {
infowindow.close();
this.data = {};
}
};
});
app.service('mapControlsService', function (infoWindowService, markersService, NEW_TODO_ID) {
this.editTodo = false;
this.editTodoId = NEW_TODO_ID;
this.newTodo = function () {
this.editTodoById();
};
this.editTodoById = function (todoId) {
this.editTodoId = todoId || NEW_TODO_ID;
this.editTodo = true;
};
this.openInfoWindowByTodoId = function (todoId) {
var marker = markersService.getMarkerByTodoId(todoId);
if (marker) {
infoWindowService.setData(todoId, marker.getTitle(), marker.get("desc"));
infoWindowService.open(marker);
return;
}
};
});
app.controller('EditTodoCtrl', function ($scope, mapService, todosService, infoWindowService, mapControlsService, NEW_TODO_ID) {
var editPinImage,
editMarker;
$scope.editTodo = {};
// editMarker Setup Start
editPinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + "55FF00",
new google.maps.Size(21, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
editMarker = new google.maps.Marker({
title: "Drag Me",
draggable: true,
clickable: false,
icon: editPinImage,
position: new google.maps.LatLng(0, 0)
});
function editMarkerDragCallback (scope, myMarker) {
return function () {
var pos = myMarker.getPosition();
scope.editTodo.lat = pos.lat();
scope.editTodo.lng = pos.lng();
if(!scope.$$phase) scope.$apply();
};
}
google.maps.event.addListener(editMarker, 'drag', editMarkerDragCallback($scope, editMarker));
function editMarkerDblClickCallback (scope) {
return function () {
scope.$apply(function () {
scope.submitTodo();
});
};
}
google.maps.event.addListener(editMarker, 'dblclick', editMarkerDblClickCallback($scope));
$scope.$watch('editTodo.lat + editTodo.lng', function (newValue, oldValue) {
if (newValue !== oldValue) {
var pos = editMarker.getPosition(),
latitude = pos.lat(),
longitude = pos.lng();
if ($scope.editTodo.lat !== latitude || $scope.editTodo.lng !== longitude)
editMarker.setPosition(new google.maps.LatLng($scope.editTodo.lat || 0, $scope.editTodo.lng || 0));
}
});
// editMarker Setup End
$scope.$watch('controls.editTodo + controls.editTodoId', function () {
var pos, todo = mapControlsService.editTodoId !== NEW_TODO_ID && todosService.getTodoById(mapControlsService.editTodoId);
infoWindowService.close();
if (mapControlsService.editTodo) {
if (todo) {
$scope.editTodo = {
id: todo.id,
title: todo.title,
desc: todo.desc,
lat: todo.lat,
lng: todo.lng,
comp: todo.completed,
saveMsg: "Update Todo",
cancelMsg: "Discard Changes"
};
} else {
pos = mapService.getLatLng();
$scope.editTodo = {
id: NEW_TODO_ID,
lat: pos.lat,
lng: pos.lng,
saveMsg: "Save Todo",
cancelMsg: "Discard Todo"
};
}
editMarker.setMap(mapService.getMap());
}
});
$scope.submitTodo = function () {
if ($scope.editTodoForm.$valid) {
if ($scope.editTodo.id === NEW_TODO_ID)
addTodo();
else
editTodo();
}
}
$scope.resetCloseTodoForm = function () {
editMarker.setMap(null);
mapControlsService.editTodo = false;
mapControlsService.editTodoId = NEW_TODO_ID;
$scope.editTodo = {};
}
function addTodo () {
todosService.addTodo(
$scope.editTodo.title,
$scope.editTodo.desc,
$scope.editTodo.lat,
$scope.editTodo.lng);
$scope.resetCloseTodoForm();
}
function editTodo () {
todosService.updateTodo(
$scope.editTodo.id,
$scope.editTodo.title,
$scope.editTodo.desc,
$scope.editTodo.lat,
$scope.editTodo.lng,
$scope.editTodo.comp);
$scope.resetCloseTodoForm();
}
});
app.directive('todoMaps', function ($compile) {
return {
controller: function ($scope, $location, mapService, mapControlsService, infoWindowService, todosService, markersService) {
if ($location.path() === '') {
$location.path('/');
}
$scope.location = $location;
$scope.infow = infoWindowService;
$scope.controls = mapControlsService;
this.registerInfoWindow = function (myInfoWindow) {
infoWindowService.registerInfoWindow(myInfoWindow);
};
this.registerMap = function (myMap) {
mapService.setMap(myMap);
$scope.todos = todosService;
};
$scope.$watch('location.path()', function (path) {
todosService.filter = (path === '/active') ?
{ completed: false } : (path === '/completed') ?
{ completed: true } : null;
});
$scope.$watch('location.path() + todos.nextId + todos.remainingCount()', function () {
var i,
todos = todosService.filtered(),
map = mapService.getMap(),
todoId,
marker,
markers = markersService.markers,
markerId,
uniqueTodos = {};
function addMarkerByTodoIndex (todoIndex) {
var marker,
markerOptions,
todo = todos[todoIndex];
markerOptions = {
map: map,
title: todo.title,
position: new google.maps.LatLng(todo.lat, todo.lng)
};
marker = new google.maps.Marker(markerOptions);
marker.setValues({
id: todo.id,
desc: todo.desc
});
markersService.markers.push(marker);
function markerClickCallback (scope, todoId) {
return function () {
scope.$apply(function () {
mapControlsService.openInfoWindowByTodoId(todoId);
});
};
}
google.maps.event.addListener(marker, 'click', markerClickCallback($scope, todo.id));
function markerDblClickCallback (scope, todoId) {
return function () {
scope.$apply(function () {
mapControlsService.editTodoById(todoId);
});
};
}
google.maps.event.addListener(marker, 'dblclick', markerDblClickCallback($scope, todo.id));
}
for (i = todos.length - 1; i >= 0; i--) {
uniqueTodos[todos[i].id] = i;
}
for (i = markers.length - 1; i >= 0; i--) {
marker = markers[i];
markerId = marker.get("id");
if (uniqueTodos[markerId] !== undefined) {
delete uniqueTodos[markerId];
} else {
marker.setMap(null);
markers.splice(i,1);
}
}
for (todoId in uniqueTodos) {
if (uniqueTodos.hasOwnProperty(todoId)) {
addMarkerByTodoIndex(uniqueTodos[todoId]);
}
}
});
},
link: function (scope, elem, attrs, ctrl) {
var mapOptions,
latitude = attrs.latitude,
longitude = attrs.longitude,
infoWindowTemplate,
infoWindowElem,
infowindow,
todosControlTemplate,
todosControlElem,
editTodoControlTemplate,
editTodoControlElem,
mapStyles,
map;
latitude = latitude && parseFloat(latitude, 10) || 43.074688;
longitude = longitude && parseFloat(longitude, 10) || -89.384294;
infoWindowTemplate = document.getElementById('infoWindowTemplate').innerHTML.trim();
infoWindowElem = $compile(infoWindowTemplate)(scope);
infowindow = new google.maps.InfoWindow({
content: infoWindowElem[0]
});
ctrl.registerInfoWindow(infowindow);
mapStyles = [{
featureType: 'water',
stylers: [
{hue: '#000b0'},
{invert_lightness: 'false'},
{saturation: -30}
]
}];
mapOptions = {
zoom: 12,
disableDefaultUI: false,
center: new google.maps.LatLng(latitude, longitude),
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: mapStyles
};
google.maps.visualRefresh = true;
map = new google.maps.Map(elem[0], mapOptions);
ctrl.registerMap(map);
todosControlTemplate = document.getElementById('todosControlTemplate').innerHTML.trim();
todosControlElem = $compile(todosControlTemplate)(scope);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(todosControlElem[0]);
editTodoControlTemplate = document.getElementById('editTodoControlTemplate').innerHTML.trim();
editTodoControlElem = $compile(editTodoControlTemplate)(scope);
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(editTodoControlElem[0]);
}
};
});
}); | hopeeen/instaApp | www/scripts/controllers/maps2.js | JavaScript | mit | 13,504 |
import mongoose from 'mongoose';
import request from 'supertest-as-promised';
import httpStatus from 'http-status';
import chai, { expect } from 'chai';
import app from '../../index';
chai.config.includeStack = true;
/**
* root level hooks
*/
after((done) => {
// required because https://github.com/Automattic/mongoose/issues/1251#issuecomment-65793092
mongoose.models = {};
mongoose.modelSchemas = {};
mongoose.connection.close();
done();
});
before()
describe('## User APIs', () => {
let user = {
username: 'KK123',
mobileNumber: '1234567890'
};
describe('# POST /api/users', () => {
it('should create a new user', (done) => {
request(app)
.post('/api/users')
.send(user)
.expect(httpStatus.OK)
.then((res) => {
expect(res.body.username).to.equal(user.username);
expect(res.body.mobileNumber).to.equal(user.mobileNumber);
user = res.body;
done();
})
.catch(done);
});
});
describe('# GET /api/users/:userId', () => {
it('should get user details', (done) => {
request(app)
.get(`/api/users/${user._id}`)
.expect(httpStatus.OK)
.then((res) => {
expect(res.body.username).to.equal(user.username);
expect(res.body.mobileNumber).to.equal(user.mobileNumber);
done();
})
.catch(done);
});
it('should report error with message - Not found, when user does not exists', (done) => {
request(app)
.get('/api/users/56c787ccc67fc16ccc1a5e92')
.expect(httpStatus.NOT_FOUND)
.then((res) => {
expect(res.body.message).to.equal('Not Found');
done();
})
.catch(done);
});
});
describe('# PUT /api/users/:userId', () => {
it('should update user details', (done) => {
user.username = 'KK';
request(app)
.put(`/api/users/${user._id}`)
.send(user)
.expect(httpStatus.OK)
.then((res) => {
expect(res.body.username).to.equal('KK');
expect(res.body.mobileNumber).to.equal(user.mobileNumber);
done();
})
.catch(done);
});
});
describe('# GET /api/users/', () => {
it('should get all users', (done) => {
request(app)
.get('/api/users')
.expect(httpStatus.OK)
.then((res) => {
expect(res.body).to.be.an('array');
done();
})
.catch(done);
});
it('should get all users (with limit and skip)', (done) => {
request(app)
.get('/api/users')
.query({ limit: 10, skip: 1 })
.expect(httpStatus.OK)
.then((res) => {
expect(res.body).to.be.an('array');
done();
})
.catch(done);
});
});
describe('# DELETE /api/users/', () => {
it('should delete user', (done) => {
request(app)
.delete(`/api/users/${user._id}`)
.expect(httpStatus.OK)
.then((res) => {
expect(res.body.username).to.equal('KK');
expect(res.body.mobileNumber).to.equal(user.mobileNumber);
done();
})
.catch(done);
});
});
});
| CaptainSid/WarSid-Swissport | server/tests/Compte.test.js | JavaScript | mit | 3,205 |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import AppActions from '../../actions/AppActions';
/*
|--------------------------------------------------------------------------
| Child - Audio settings
|--------------------------------------------------------------------------
*/
export default class SettingsAudio extends Component {
static propTypes = {
config: PropTypes.object,
}
constructor(props) {
super(props);
}
setPlaybackRate(e) {
AppActions.player.setPlaybackRate(e.currentTarget.value);
}
render() {
const config = this.props.config;
return (
<div className='setting setting-audio'>
<div className='setting-section'>
<h4>Playback rate</h4>
<div className='formGroup'>
<label>
Increase the playback rate: a value of 2 will play your music at a 2x speed
</label>
<input type='number'
className='form-control'
defaultValue={config.audioPlaybackRate}
onChange={this.setPlaybackRate}
min='0.5'
max='5'
step='0.1'
/>
</div>
</div>
</div>
);
}
}
| Eeltech/SpaceMusik | src/ui/components/Settings/SettingsAudio.react.js | JavaScript | mit | 1,248 |
var path = require('path');
var config = {
contentBase: path.join(__dirname, "docs"),
watchContentBase: true,
host: 'localhost',
port: 8080,
// Recommended for hot module replacement
hot: true,
inline: true,
// Open the browser does not work when webpack dev server called from node.
// open: true,
// Showing errors
overlay: {
errors: true,
warnings: true,
},
// Proxy API requests
// proxy: {
// 'api': "http://localhost:3000"
// },
// Show only error information
stats: "errors-only",
// Using HTML 5 History API Webpack Dev Server will redirect routes to index.html, so SPA can handle it
historyApiFallback: true,
};
module.exports = config; | manu-garcia/react-pwa-from-scratch | webpack.devserver.config.js | JavaScript | mit | 712 |
/**
Copyright (c) 2015, 2017, Oracle and/or its affiliates.
The Universal Permissive License (UPL), Version 1.0
*/
/**
* # oraclejet-build.js
* This script allows users to configure and customize the grunt build tasks.
* Configurable tasks include:
* copySrcToStaging
* copyCustomLibsToStaging
* injectTheme
* injectPaths
* uglify
* requireJs
* sass
* To configure a task, uncomment the corresponding sections below, and pass in your configurations.
* Any options will be merged with default configuration found in node_modules/oraclejet-tooling/lib/defaultconfig.js
* Any fileList options will replace the corresponding option defined by the default configuration in its entirety - ie. arrays are not merged.
*/
module.exports = function (grunt) {
return {
/**
* # copyCustomLibsToStaging
* This task copies any custom libraries that are not provided by JET to staging directory.
* This task supports a single option: fileList. The fileList option defines an array of file objects.
* Each file object contains the following properties:
* cwd, current working directory
* dest, destination path
* src, array of source file patterns
* rename, function to return the full path of desired destination
* If a fileList value is specified, it completely replaces the default fileList value defined by JET
* Example: {cwd: 'app', src: ['**', '!test.js'], dest: 'staging', rename: function (dest, file) {return renamed path}}
*/
copyCustomLibsToStaging: {
fileList: [
{cwd: 'node_modules/font-awesome/fonts', src: ['*'], dest: 'web/css/fonts/'},
{cwd: 'node_modules/font-awesome/css', src: ['*'], dest: 'web/css/font-awesome/'}
]
},
/**
* # copySrcToStaging
* This task copies all source files and libraries to staging directory.
* This task supports a single option: fileList. The fileList option defines an array of file objects.
* See descriptions and example in copyCustomLibsToStaging for configuring the fileList.
*/
// copySrcToStaging: {
// fileList: [],
// },
/**
* # injectTheme
* This task injects css stylesheet links for the current theme into index.html using the injection start and end markers defined below.
*/
// injectTheme: {
// startTag: '<!-- injector:theme -->',
// endTag: '<!-- endinjector -->'
// }
/**
* # injectPaths
* Configuration for path injection during build in release mode
* This task reads the release paths from the mainReleasePaths json file and injects the path configuration in main.js when run in release mode.
*/
// injectPaths: paths => ({
// startTag: '//injector:mainReleasePaths',
// endTag: '//endinjector',
// mainJs: 'path to mainjs',
// destMainJs: 'path to the inject destination',
// mainReleasePaths: 'path to the main-release-paths.json'
// }),
/**
* # uglify
* This task minifies source files and libraries that don't have minified distributions.
* It runs only when build in release mode. Support input of fileList that contains an array of file objects.
* See the example in copyCustomLibsToStaging for configuring the fileList.
* See detailed uglify options at https://github.com/mishoo/UglifyJS
*/
// uglify: {
// fileList: [{}],
// options: {}
// },
/**
* # requireJs
* This task runs requirejs optimizer to bundle all scripts in to a large minified main.js for release.
* It runs only when build in release mode.
* The task mirrors the configuration in this link https://github.com/gruntjs/grunt-contrib-requirejs
*/
// requireJs: {
// baseUrl: 'path to the js directory in staging area',
// name: 'the main.js file name',
// mainConfigFile: `the main configuration file`,
// optimize: 'option for optimize',
// out: 'output file path'
// },
/**
* # sass
* This task runs sass compile for scss files.
* It takes a fileList as input, see copyCustomLibsToStaging section for examples of fileList
* See detailed node sass options available here https://github.com/sass/node-sass
*/
// sass: {
// fileList: [],
// options: {}
// },
/**
* This is the web specific configuration. You can specify configurations targeted only for web apps.
* The web specific configurations will override the general configuration.
*/
web: {
},
/**
* This is the hybrid specific configuration. You can specify configurations targeted only hybrid apps.
* The hybrid specific configurations will override the general configuration.
*/
hybrid: {
}
};
};
| amalbose/media-manager | scripts/grunt/config/oraclejet-build.js | JavaScript | mit | 4,603 |
// @flow
import type { ChooView } from "../app";
const html = require("choo/html");
const messages = require("../messages");
const textInput = ({ label, name }) => html`
<label>
${label}
<input name=${name}/>
</label>`;
const signupForm = ({ onSubmit }) => html`
<form onsubmit=${onSubmit}>
${textInput({ label: messages.form.name, name: "name" })}
${textInput({ label: messages.form.email, name: "email" })}
<input type="submit" value=${messages.form.signup} />
</form>`;
const signupView: ChooView = (state, emit) => {
const onSubmit = event => {
event.preventDefault();
const formElements = event.target.elements;
const name = formElements.namedItem("name").value;
const email = formElements.namedItem("email").value;
const user = { name, email };
emit("api:signup", user);
};
return html`
<div>
${signupForm({ onSubmit })}
<a href="#">back</a>
</div>`;
};
module.exports = signupView;
| fczuardi/videochat-client | src/views/signup.js | JavaScript | mit | 981 |
var notice_this_is_a_global_var = "WAT?";
window.getGlobalTemplate = function() {
var compiled = _.template('<h1>Hello from a <strong>Global</strong> module running a <%= templateName %>!</h1>');
return compiled({
'templateName': 'Lodash template'
});
};
| staxmanade/jspm-presentation | demo-commonjs-amd-global/globalModule.js | JavaScript | mit | 270 |
const DrawCard = require('../../drawcard.js');
const { Locations, Players, CardTypes } = require('../../Constants');
class MyAncestorsStrength extends DrawCard {
setupCardAbilities(ability) { // eslint-disable-line no-unused-vars
this.action({
title: 'Modify base military and political skills',
condition: () => this.game.isDuringConflict(),
targets: {
shugenja: {
activePromptTitle: 'Choose a shugenja character',
cardType: CardTypes.Character,
controller: Players.Self,
cardCondition: card => card.hasTrait('shugenja') && card.isParticipating()
},
ancestor: {
dependsOn: 'shugenja',
activePromptTitle: 'Choose a character to copy from',
cardType: CardTypes.Character,
location: Locations.DynastyDiscardPile,
controller: Players.Self,
gameAction: ability.actions.cardLastingEffect(context => {
let effects = [];
let ancestor = context.targets.ancestor;
if(ancestor.hasDash('military')) {
effects.push(ability.effects.setDash('military'));
} else {
effects.push(ability.effects.setBaseMilitarySkill(ancestor.militarySkill));
}
if(ancestor.hasDash('political')) {
effects.push(ability.effects.setDash('political'));
} else {
effects.push(ability.effects.setBasePoliticalSkill(ancestor.politicalSkill));
}
return {
target: context.targets.shugenja,
effect: effects
};
})
}
},
effect: 'set {1}\'s base skills to those of {2}',
effectArgs: context => [context.targets.shugenja, context.targets.ancestor]
});
}
}
MyAncestorsStrength.id = 'my-ancestor-s-strength';
module.exports = MyAncestorsStrength;
| jeremylarner/ringteki | server/game/cards/04.4-TEaF/MyAncestorsStrength.js | JavaScript | mit | 2,289 |
import { createStore } from 'redux';
import reducers from './reducers';
const store = createStore(reducers);
if (module.hot) {
module.hot.accept(() => {
const nextRootReducer = require('./reducers').default;
store.replaceReducer(nextRootReducer);
});
}
export default store;
| entria/entria-components | storybook/store.js | JavaScript | mit | 291 |
(function () {
var fullpage = (function () {
'use strict';
var Cell = function (initial) {
var value = initial;
var get = function () {
return value;
};
var set = function (v) {
value = v;
};
var clone = function () {
return Cell(get());
};
return {
get: get,
set: set,
clone: clone
};
};
var PluginManager = tinymce.util.Tools.resolve('tinymce.PluginManager');
var Tools = tinymce.util.Tools.resolve('tinymce.util.Tools');
var DomParser = tinymce.util.Tools.resolve('tinymce.html.DomParser');
var Node = tinymce.util.Tools.resolve('tinymce.html.Node');
var Serializer = tinymce.util.Tools.resolve('tinymce.html.Serializer');
var shouldHideInSourceView = function (editor) {
return editor.getParam('fullpage_hide_in_source_view');
};
var getDefaultXmlPi = function (editor) {
return editor.getParam('fullpage_default_xml_pi');
};
var getDefaultEncoding = function (editor) {
return editor.getParam('fullpage_default_encoding');
};
var getDefaultFontFamily = function (editor) {
return editor.getParam('fullpage_default_font_family');
};
var getDefaultFontSize = function (editor) {
return editor.getParam('fullpage_default_font_size');
};
var getDefaultTextColor = function (editor) {
return editor.getParam('fullpage_default_text_color');
};
var getDefaultTitle = function (editor) {
return editor.getParam('fullpage_default_title');
};
var getDefaultDocType = function (editor) {
return editor.getParam('fullpage_default_doctype', '<!DOCTYPE html>');
};
var $_e0ugg1bdje5nvbsm = {
shouldHideInSourceView: shouldHideInSourceView,
getDefaultXmlPi: getDefaultXmlPi,
getDefaultEncoding: getDefaultEncoding,
getDefaultFontFamily: getDefaultFontFamily,
getDefaultFontSize: getDefaultFontSize,
getDefaultTextColor: getDefaultTextColor,
getDefaultTitle: getDefaultTitle,
getDefaultDocType: getDefaultDocType
};
var parseHeader = function (head) {
return DomParser({
validate: false,
root_name: '#document'
}).parse(head);
};
var htmlToData = function (editor, head) {
var headerFragment = parseHeader(head);
var data = {};
var elm, matches;
function getAttr(elm, name) {
var value = elm.attr(name);
return value || '';
}
data.fontface = $_e0ugg1bdje5nvbsm.getDefaultFontFamily(editor);
data.fontsize = $_e0ugg1bdje5nvbsm.getDefaultFontSize(editor);
elm = headerFragment.firstChild;
if (elm.type === 7) {
data.xml_pi = true;
matches = /encoding="([^"]+)"/.exec(elm.value);
if (matches) {
data.docencoding = matches[1];
}
}
elm = headerFragment.getAll('#doctype')[0];
if (elm) {
data.doctype = '<!DOCTYPE' + elm.value + '>';
}
elm = headerFragment.getAll('title')[0];
if (elm && elm.firstChild) {
data.title = elm.firstChild.value;
}
Tools.each(headerFragment.getAll('meta'), function (meta) {
var name = meta.attr('name');
var httpEquiv = meta.attr('http-equiv');
var matches;
if (name) {
data[name.toLowerCase()] = meta.attr('content');
} else if (httpEquiv === 'Content-Type') {
matches = /charset\s*=\s*(.*)\s*/gi.exec(meta.attr('content'));
if (matches) {
data.docencoding = matches[1];
}
}
});
elm = headerFragment.getAll('html')[0];
if (elm) {
data.langcode = getAttr(elm, 'lang') || getAttr(elm, 'xml:lang');
}
data.stylesheets = [];
Tools.each(headerFragment.getAll('link'), function (link) {
if (link.attr('rel') === 'stylesheet') {
data.stylesheets.push(link.attr('href'));
}
});
elm = headerFragment.getAll('body')[0];
if (elm) {
data.langdir = getAttr(elm, 'dir');
data.style = getAttr(elm, 'style');
data.visited_color = getAttr(elm, 'vlink');
data.link_color = getAttr(elm, 'link');
data.active_color = getAttr(elm, 'alink');
}
return data;
};
var dataToHtml = function (editor, data, head) {
var headerFragment, headElement, html, elm, value;
var dom = editor.dom;
function setAttr(elm, name, value) {
elm.attr(name, value ? value : undefined);
}
function addHeadNode(node) {
if (headElement.firstChild) {
headElement.insert(node, headElement.firstChild);
} else {
headElement.append(node);
}
}
headerFragment = parseHeader(head);
headElement = headerFragment.getAll('head')[0];
if (!headElement) {
elm = headerFragment.getAll('html')[0];
headElement = new Node('head', 1);
if (elm.firstChild) {
elm.insert(headElement, elm.firstChild, true);
} else {
elm.append(headElement);
}
}
elm = headerFragment.firstChild;
if (data.xml_pi) {
value = 'version="1.0"';
if (data.docencoding) {
value += ' encoding="' + data.docencoding + '"';
}
if (elm.type !== 7) {
elm = new Node('xml', 7);
headerFragment.insert(elm, headerFragment.firstChild, true);
}
elm.value = value;
} else if (elm && elm.type === 7) {
elm.remove();
}
elm = headerFragment.getAll('#doctype')[0];
if (data.doctype) {
if (!elm) {
elm = new Node('#doctype', 10);
if (data.xml_pi) {
headerFragment.insert(elm, headerFragment.firstChild);
} else {
addHeadNode(elm);
}
}
elm.value = data.doctype.substring(9, data.doctype.length - 1);
} else if (elm) {
elm.remove();
}
elm = null;
Tools.each(headerFragment.getAll('meta'), function (meta) {
if (meta.attr('http-equiv') === 'Content-Type') {
elm = meta;
}
});
if (data.docencoding) {
if (!elm) {
elm = new Node('meta', 1);
elm.attr('http-equiv', 'Content-Type');
elm.shortEnded = true;
addHeadNode(elm);
}
elm.attr('content', 'text/html; charset=' + data.docencoding);
} else if (elm) {
elm.remove();
}
elm = headerFragment.getAll('title')[0];
if (data.title) {
if (!elm) {
elm = new Node('title', 1);
addHeadNode(elm);
} else {
elm.empty();
}
elm.append(new Node('#text', 3)).value = data.title;
} else if (elm) {
elm.remove();
}
Tools.each('keywords,description,author,copyright,robots'.split(','), function (name) {
var nodes = headerFragment.getAll('meta');
var i, meta;
var value = data[name];
for (i = 0; i < nodes.length; i++) {
meta = nodes[i];
if (meta.attr('name') === name) {
if (value) {
meta.attr('content', value);
} else {
meta.remove();
}
return;
}
}
if (value) {
elm = new Node('meta', 1);
elm.attr('name', name);
elm.attr('content', value);
elm.shortEnded = true;
addHeadNode(elm);
}
});
var currentStyleSheetsMap = {};
Tools.each(headerFragment.getAll('link'), function (stylesheet) {
if (stylesheet.attr('rel') === 'stylesheet') {
currentStyleSheetsMap[stylesheet.attr('href')] = stylesheet;
}
});
Tools.each(data.stylesheets, function (stylesheet) {
if (!currentStyleSheetsMap[stylesheet]) {
elm = new Node('link', 1);
elm.attr({
rel: 'stylesheet',
text: 'text/css',
href: stylesheet
});
elm.shortEnded = true;
addHeadNode(elm);
}
delete currentStyleSheetsMap[stylesheet];
});
Tools.each(currentStyleSheetsMap, function (stylesheet) {
stylesheet.remove();
});
elm = headerFragment.getAll('body')[0];
if (elm) {
setAttr(elm, 'dir', data.langdir);
setAttr(elm, 'style', data.style);
setAttr(elm, 'vlink', data.visited_color);
setAttr(elm, 'link', data.link_color);
setAttr(elm, 'alink', data.active_color);
dom.setAttribs(editor.getBody(), {
style: data.style,
dir: data.dir,
vLink: data.visited_color,
link: data.link_color,
aLink: data.active_color
});
}
elm = headerFragment.getAll('html')[0];
if (elm) {
setAttr(elm, 'lang', data.langcode);
setAttr(elm, 'xml:lang', data.langcode);
}
if (!headElement.firstChild) {
headElement.remove();
}
html = Serializer({
validate: false,
indent: true,
apply_source_formatting: true,
indent_before: 'head,html,body,meta,title,script,link,style',
indent_after: 'head,html,body,meta,title,script,link,style'
}).serialize(headerFragment);
return html.substring(0, html.indexOf('</body>'));
};
var $_6ivrn3b9je5nvbsd = {
parseHeader: parseHeader,
htmlToData: htmlToData,
dataToHtml: dataToHtml
};
var open = function (editor, headState) {
var data = $_6ivrn3b9je5nvbsd.htmlToData(editor, headState.get());
editor.windowManager.open({
title: 'Document properties',
data: data,
defaults: {
type: 'textbox',
size: 40
},
body: [
{
name: 'title',
label: 'Title'
},
{
name: 'keywords',
label: 'Keywords'
},
{
name: 'description',
label: 'Description'
},
{
name: 'robots',
label: 'Robots'
},
{
name: 'author',
label: 'Author'
},
{
name: 'docencoding',
label: 'Encoding'
}
],
onSubmit: function (e) {
var headHtml = $_6ivrn3b9je5nvbsd.dataToHtml(editor, Tools.extend(data, e.data), headState.get());
headState.set(headHtml);
}
});
};
var $_12r4fvb7je5nvbsa = { open: open };
var register = function (editor, headState) {
editor.addCommand('mceFullPageProperties', function () {
$_12r4fvb7je5nvbsa.open(editor, headState);
});
};
var $_f7sik6b6je5nvbs9 = { register: register };
var protectHtml = function (protect, html) {
Tools.each(protect, function (pattern) {
html = html.replace(pattern, function (str) {
return '<!--mce:protected ' + escape(str) + '-->';
});
});
return html;
};
var unprotectHtml = function (html) {
return html.replace(/<!--mce:protected ([\s\S]*?)-->/g, function (a, m) {
return unescape(m);
});
};
var $_54m0yxbfje5nvbst = {
protectHtml: protectHtml,
unprotectHtml: unprotectHtml
};
var each = Tools.each;
var low = function (s) {
return s.replace(/<\/?[A-Z]+/g, function (a) {
return a.toLowerCase();
});
};
var handleSetContent = function (editor, headState, footState, evt) {
var startPos, endPos, content, headerFragment, styles = '';
var dom = editor.dom;
var elm;
if (evt.selection) {
return;
}
content = $_54m0yxbfje5nvbst.protectHtml(editor.settings.protect, evt.content);
if (evt.format === 'raw' && headState.get()) {
return;
}
if (evt.source_view && $_e0ugg1bdje5nvbsm.shouldHideInSourceView(editor)) {
return;
}
if (content.length === 0 && !evt.source_view) {
content = Tools.trim(headState.get()) + '\n' + Tools.trim(content) + '\n' + Tools.trim(footState.get());
}
content = content.replace(/<(\/?)BODY/gi, '<$1body');
startPos = content.indexOf('<body');
if (startPos !== -1) {
startPos = content.indexOf('>', startPos);
headState.set(low(content.substring(0, startPos + 1)));
endPos = content.indexOf('</body', startPos);
if (endPos === -1) {
endPos = content.length;
}
evt.content = Tools.trim(content.substring(startPos + 1, endPos));
footState.set(low(content.substring(endPos)));
} else {
headState.set(getDefaultHeader(editor));
footState.set('\n</body>\n</html>');
}
headerFragment = $_6ivrn3b9je5nvbsd.parseHeader(headState.get());
each(headerFragment.getAll('style'), function (node) {
if (node.firstChild) {
styles += node.firstChild.value;
}
});
elm = headerFragment.getAll('body')[0];
if (elm) {
dom.setAttribs(editor.getBody(), {
style: elm.attr('style') || '',
dir: elm.attr('dir') || '',
vLink: elm.attr('vlink') || '',
link: elm.attr('link') || '',
aLink: elm.attr('alink') || ''
});
}
dom.remove('fullpage_styles');
var headElm = editor.getDoc().getElementsByTagName('head')[0];
if (styles) {
dom.add(headElm, 'style', { id: 'fullpage_styles' }, styles);
elm = dom.get('fullpage_styles');
if (elm.styleSheet) {
elm.styleSheet.cssText = styles;
}
}
var currentStyleSheetsMap = {};
Tools.each(headElm.getElementsByTagName('link'), function (stylesheet) {
if (stylesheet.rel === 'stylesheet' && stylesheet.getAttribute('data-mce-fullpage')) {
currentStyleSheetsMap[stylesheet.href] = stylesheet;
}
});
Tools.each(headerFragment.getAll('link'), function (stylesheet) {
var href = stylesheet.attr('href');
if (!href) {
return true;
}
if (!currentStyleSheetsMap[href] && stylesheet.attr('rel') === 'stylesheet') {
dom.add(headElm, 'link', {
'rel': 'stylesheet',
'text': 'text/css',
'href': href,
'data-mce-fullpage': '1'
});
}
delete currentStyleSheetsMap[href];
});
Tools.each(currentStyleSheetsMap, function (stylesheet) {
stylesheet.parentNode.removeChild(stylesheet);
});
};
var getDefaultHeader = function (editor) {
var header = '', value, styles = '';
if ($_e0ugg1bdje5nvbsm.getDefaultXmlPi(editor)) {
var piEncoding = $_e0ugg1bdje5nvbsm.getDefaultEncoding(editor);
header += '<?xml version="1.0" encoding="' + (piEncoding ? piEncoding : 'ISO-8859-1') + '" ?>\n';
}
header += $_e0ugg1bdje5nvbsm.getDefaultDocType(editor);
header += '\n<html>\n<head>\n';
if (value = $_e0ugg1bdje5nvbsm.getDefaultTitle(editor)) {
header += '<title>' + value + '</title>\n';
}
if (value = $_e0ugg1bdje5nvbsm.getDefaultEncoding(editor)) {
header += '<meta http-equiv="Content-Type" content="text/html; charset=' + value + '" />\n';
}
if (value = $_e0ugg1bdje5nvbsm.getDefaultFontFamily(editor)) {
styles += 'font-family: ' + value + ';';
}
if (value = $_e0ugg1bdje5nvbsm.getDefaultFontSize(editor)) {
styles += 'font-size: ' + value + ';';
}
if (value = $_e0ugg1bdje5nvbsm.getDefaultTextColor(editor)) {
styles += 'color: ' + value + ';';
}
header += '</head>\n<body' + (styles ? ' style="' + styles + '"' : '') + '>\n';
return header;
};
var handleGetContent = function (editor, head, foot, evt) {
if (!evt.selection && (!evt.source_view || !$_e0ugg1bdje5nvbsm.shouldHideInSourceView(editor))) {
evt.content = $_54m0yxbfje5nvbst.unprotectHtml(Tools.trim(head) + '\n' + Tools.trim(evt.content) + '\n' + Tools.trim(foot));
}
};
var setup = function (editor, headState, footState) {
editor.on('BeforeSetContent', function (evt) {
handleSetContent(editor, headState, footState, evt);
});
editor.on('GetContent', function (evt) {
handleGetContent(editor, headState.get(), footState.get(), evt);
});
};
var $_g4dxr5beje5nvbsp = { setup: setup };
var register$1 = function (editor) {
editor.addButton('fullpage', {
title: 'Document properties',
cmd: 'mceFullPageProperties'
});
editor.addMenuItem('fullpage', {
text: 'Document properties',
cmd: 'mceFullPageProperties',
context: 'file'
});
};
var $_e0bg5mbgje5nvbsu = { register: register$1 };
PluginManager.add('fullpage', function (editor) {
var headState = Cell(''), footState = Cell('');
$_f7sik6b6je5nvbs9.register(editor, headState);
$_e0bg5mbgje5nvbsu.register(editor);
$_g4dxr5beje5nvbsp.setup(editor, headState, footState);
});
function Plugin () {
}
return Plugin;
}());
})();
| AnttiKurittu/kirjuri | vendor/tinymce/tinymce/plugins/fullpage/plugin.js | JavaScript | mit | 16,270 |
$(document).ready(function(){
SC.initialize({
client_id: "472760520d39b9fa470e56cdffc71923",
});
$('.leaderboard tr').each(function(){
var datacell = $(this).find('.datacell').data('url');
var data = datacell.data('url');
SC.oEmbed(data, {auto_play: false}, datacell);
})
/*
SC.oEmbed($('#crunch1').attr('url'), {auto_play: false}, document.getElementById('crunch1'));
SC.oEmbed($('#crunch2').attr('url'), {auto_play: false}, document.getElementById('crunch2'));
*/
}) | srhoades28/CI_Crunchoff | assets/js/leaderboard.js | JavaScript | mit | 498 |
"use strict";
describe("PROXY", function () {
beforeEach(function () {
this.p = new PubnubProxy();
});
describe('setFlashObjectId ', function () {
it('should accept flash object name (string) as only argument', function () {
var _test = this,
failFn = function () {
_test.p.setFlashObjectId(15);
},
successFn = function () {
_test.p.setFlashObjectId('someId');
};
expectFailAndSuccessFns(failFn, successFn, TypeError);
});
});
describe('initialization', function () {
it('should have empty instances object', function () {
expect(Object.keys(this.p.instances)).to.have.length(0);
});
it('should set default value for flash object', function () {
expect(this.p.flashObjectId).to.equal('pubnubFlashObject');
});
it('should set default value for flash object', function () {
expect(this.p.flashObject).to.be(null);
});
});
describe('delegate methods', function () {
it('should accept array as only argument', function () {
var _test = this,
failFn = function () {
_test.p.delegateAsync('oneMethod');
},
successFn = function () {
_test.p.delegateAsync(['oneMethod']);
};
expectFailAndSuccessFns(failFn, successFn, TypeError);
});
it('should dynamically define methods that are passed as params', function () {
var methods = ['oneMethod', 'anotherMethod'];
this.p.delegateAsync(methods);
expect(this.p.oneMethod).to.be.a('function');
expect(this.p.anotherMethod).to.be.a('function');
});
});
describe('delegate synchronous methods', function () {
it('should accept array as only argument', function () {
var _test = this,
failFn = function () {
_test.p.delegateSync('oneMethod');
},
successFn = function () {
_test.p.delegateSync(['oneMethod']);
};
expectFailAndSuccessFns(failFn, successFn, TypeError);
});
it('should dynamically define methods that are passed as params', function () {
var methods = ['oneMethod', 'anotherMethod'];
this.p.delegateSync(methods);
expect(this.p.oneMethod).to.be.a('function');
expect(this.p.anotherMethod).to.be.a('function');
});
});
describe('instance creation', function () {
beforeEach(function () {
this.setupObject = {};
this.i = this.p.createInstance('uglyInstanceId', this.setupObject);
});
it('should accept only string as instanceId', function () {
var _test = this,
failFn = function () {
_test.p.createInstance([], {});
},
successFn = function () {
_test.p.createInstance('correctInstanceId');
};
expectFailAndSuccessFns(failFn, successFn, TypeError);
});
it('should add created instance to instances object', function () {
var ids = Object.keys(this.p.instances);
expect(ids[0]).to.equal('uglyInstanceId');
});
});
describe('instance getter', function () {
it('should throw error when instanceId is not present in instances object', function () {
var _test = this,
failFn = function () {
_test.p.getInstance('wrongInstanceId');
},
successFn = function () {
_test.p.getInstance('uglyInstanceId');
};
this.p.instances = {uglyInstanceId: {}};
expectFailAndSuccessFns(failFn, successFn, Error);
});
});
}); | pubnub/flash | pubnub-as2js-proxy/test/unit/pubnubProxy_test.js | JavaScript | mit | 4,174 |
#!/usr/bin/env node
/**
* Extremely simple static website serving script
* This is provided in case you need to deploy a quick demo
*
* Install + run:
*
* # from parent directory
*
* cd demo
* npm install
* node server
*
*/
var bodyParser = require('body-parser');
var express = require('express');
var humanize = require('humanize');
var fs = require('fs');
var multer = require('multer');
var root = __dirname + '/..';
var app = express();
app.use(bodyParser.json());
app.use('/node_modules', express.static(root + '/node_modules'));
app.get('/', function(req, res) {
res.sendFile('index.html', {root: __dirname});
});
app.get('/app.js', function(req, res) {
res.sendFile('app.js', {root: root + '/demo'});
});
app.get('/dist/angular-ui-history.js', function(req, res) {
res.sendFile('angular-ui-history.js', {root: root + '/dist'});
});
app.get('/dist/angular-ui-history.css', function(req, res) {
res.sendFile('angular-ui-history.css', {root: root + '/dist'});
});
// Fake server to originally serve history.json + then mutate it with incomming posts
var history = JSON.parse(fs.readFileSync(root + '/demo/history.json', 'utf-8')).map(post => {
post.date = new Date(post.date);
return post;
});
app.get('/history.json', function(req, res) {
res.send(history);
});
app.post('/history.json', multer().any(), function(req, res) {
if (req.files) { // Uploading file(s)
history.push({
_id: history.length,
type: 'user.upload',
date: new Date(),
user: {
name: 'Fake User',
email: '[email protected]',
},
files: req.files.map(f => ({
filename: f.originalname,
size: humanize.filesize(f.size),
icon:
// Very abridged list of mimetypes -> font-awesome lookup {{{
/^audio\//.test(f.mimetype) ? 'fa fa-file-audio-o' :
/^image\//.test(f.mimetype) ? 'fa fa-file-image-o' :
/^text\//.test(f.mimetype) ? 'fa fa-file-text-o' :
/^video\//.test(f.mimetype) ? 'fa fa-file-video-o' :
f.mimetype == 'application/vnd.ms-excel' || f.mimetype == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || f.mimetype == 'application/vnd.openxmlformats-officedocument.spreadsheetml.template' ? 'fa fa-file-excel-o' :
f.mimetype == 'application/msword' || f.mimetype == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || f.mimetype == 'application/vnd.openxmlformats-officedocument.wordprocessingml.template' ? 'fa fa-file-word-o' :
f.mimetype == 'application/vnd.ms-powerpoint' || f.mimetype == 'application/vnd.openxmlformats-officedocument.presentationml.presentation' || f.mimetype == 'application/vnd.openxmlformats-officedocument.presentationml.slideshow' || f.mimetype == 'application/vnd.openxmlformats-officedocument.presentationml.template' ? 'fa fa-file-word-o' :
f.mimetype == 'application/pdf' ? 'fa fa-file-pdf-o' :
f.mimetype == 'application/zip' || f.mimetype == 'application/x-compressed-zip' || f.mimetype == 'application/x-tar' || f.mimetype == 'application/x-bzip2' ? 'fa fa-file-archive-o' :
'fa fa-file-o',
// }}}
})),
});
// If we did want to actually save the file we would do something like:
// req.files.forEach(f => fs.writeFile(`/some/directory/${f.originalname}`, f.buffer));
}
if (req.body.body) { // Posting a comment
history.push({
_id: history.length,
date: new Date(),
user: {
name: 'Fake User',
email: '[email protected]',
},
type: 'user.comment',
body: req.body.body,
tags: req.body.tags,
});
}
// Respond that all was well
res.status(200).end();
});
app.use(function(err, req, res, next){
console.error(err.stack);
res.status(500).send('Something broke!').end();
});
var port = process.env.PORT || process.env.VMC_APP_PORT || 8080;
var server = app.listen(port, function() {
console.log('Web interface listening on port', port);
});
| MomsFriendlyDevCo/angular-ui-history | demo/server.js | JavaScript | mit | 3,855 |
'use strict';
/**
* Password based signin and OAuth signin functions.
*/
var qs = require('querystring'),
route = require('koa-route'),
parse = require('co-body'),
jwt = require('koa-jwt'),
request = require('co-request'),
config = require('../config/config'),
mongo = require('../config/mongo');
// register koa routes
exports.init = function (app) {
app.use(route.post('/signin', signin));
app.use(route.get('/signin/facebook', facebookSignin));
app.use(route.get('/signin/facebook/callback', facebookCallback));
app.use(route.get('/signin/google', googleSignin));
app.use(route.get('/signin/google/callback', googleCallback));
};
/**
* Retrieves the user credentials and returns a JSON Web Token along with user profile info in JSON format.
*/
function *signin() {
var credentials = yield parse(this);
var user = yield mongo.users.findOne({email: credentials.email}, {email: 1, name: 1, password: 1});
if (!user) {
this.throw(401, 'Incorrect e-mail address.');
} else if (user.password !== credentials.password) {
this.throw(401, 'Incorrect password.');
} else {
user.id = user._id;
delete user._id;
delete user.password;
user.picture = '/api/users/' + user.id + '/picture';
}
// sign and send the token along with the user info
var token = jwt.sign(user, config.app.secret, {expiresInMinutes: 90 * 24 * 60 /* 90 days */});
this.body = {token: token, user: user};
}
/**
* Facebook OAuth 2.0 signin endpoint.
*/
function *facebookSignin() {
this.redirect(
'https://www.facebook.com/dialog/oauth?client_id=' + config.oauth.facebook.clientId +
'&redirect_uri=' + config.oauth.facebook.callbackUrl + '&response_type=code&scope=email');
}
/**
* Facebook OAuth 2.0 callback endpoint.
*/
function *facebookCallback() {
if (this.query.error) {
this.redirect('/signin');
return;
}
// get an access token from facebook in exchange for oauth code
var tokenResponse = yield request.get(
'https://graph.facebook.com/oauth/access_token?client_id=' + config.oauth.facebook.clientId +
'&redirect_uri=' + config.oauth.facebook.callbackUrl +
'&client_secret=' + config.oauth.facebook.clientSecret +
'&code=' + this.query.code);
var token = qs.parse(tokenResponse.body);
if (!token.access_token) {
this.redirect('/signin');
return;
}
// get user profile (including email address) from facebook and save user data in our database if necessary
var profileResponse = yield request.get('https://graph.facebook.com/me?fields=name,email,picture&access_token=' + token.access_token);
var profile = JSON.parse(profileResponse.body);
var user = yield mongo.users.findOne({email: profile.email}, {email: 1, name: 1});
if (!user) {
user = {
_id: (yield mongo.getNextSequence('userId')),
email: profile.email,
name: profile.name,
picture: (yield request.get(profile.picture.data.url, {encoding: 'base64'})).body
};
var results = yield mongo.users.insert(user);
}
// redirect the user to index page along with user profile object as query string
user.id = user._id;
delete user._id;
user.picture = '/api/users/' + user.id + '/picture';
var token = jwt.sign(user, config.app.secret, {expiresInMinutes: 90 * 24 * 60 /* 90 days */});
this.redirect('/?user=' + encodeURIComponent(JSON.stringify({token: token, user: user})));
}
/**
* Google OAuth 2.0 signin endpoint.
*/
function *googleSignin() {
this.redirect(
'https://accounts.google.com/o/oauth2/auth?client_id=' + config.oauth.google.clientId +
'&redirect_uri=' + config.oauth.google.callbackUrl + '&response_type=code&scope=profile%20email');
}
function *googleCallback() {
if (this.query.error) {
this.redirect('/signin');
return;
}
// get an access token from google in exchange for oauth code
var tokenResponse = yield request.post('https://accounts.google.com/o/oauth2/token', {form: {
code: this.query.code,
client_id: config.oauth.google.clientId,
client_secret: config.oauth.google.clientSecret,
redirect_uri: config.oauth.google.callbackUrl,
grant_type: 'authorization_code'
}});
var token = JSON.parse(tokenResponse.body);
if (!token.access_token) {
this.redirect('/signin');
return;
}
// get user profile (including email address) from facebook and save user data in our database if necessary
var profileResponse = yield request.get('https://www.googleapis.com/plus/v1/people/me?access_token=' + token.access_token);
var profile = JSON.parse(profileResponse.body);
var user = yield mongo.users.findOne({email: profile.emails[0].value}, {email: 1, name: 1});
if (!user) {
user = {
_id: (yield mongo.getNextSequence('userId')),
email: profile.emails[0].value,
name: profile.displayName,
picture: (yield request.get(profile.image.url, {encoding: 'base64'})).body
};
var results = yield mongo.users.insert(user);
}
// redirect the user to index page along with user profile object as query string
user.id = user._id;
delete user._id;
user.picture = '/api/users/' + user.id + '/picture';
var token = jwt.sign(user, config.app.secret, {expiresInMinutes: 90 * 24 * 60 /* 90 days */});
this.redirect('/?user=' + encodeURIComponent(JSON.stringify({token: token, user: user})));
}
| nileshlg2003/koan | server/controllers/signin.js | JavaScript | mit | 5,541 |
/**
* Plural rules for the fi (Finnish, suomi, suomen kieli) language
*
* This plural file is generated from CLDR-DATA
* (http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html)
* using js-simple-plurals and universal-i18n
*
* @param {number} p
* @return {number} 0 - one, 1 - other
*
* @example
* function pluralize_en(number, one, many) {
* var rules = [one, many];
* var position = plural.en(number)
* return rules[position];
* }
*
* console.log('2 ' + pluralize_en(2, 'day', 'days')); // prints '2 days'
*/
plural = window.plural || {};
plural.fi = function (p) { var n = Math.abs(p)||0, i = Math.floor(n,10)||0, v = ((p+'').split('.')[1]||'').length; return i === 1 && v === 0 ? 0 : 1; }; | megahertz/js-simple-plurals | web/fi.js | JavaScript | mit | 750 |
/*global Ghetto*/
(function ($) {
$('div').on('click', '.save-button', function (e) {
var id = $(this).attr('data-id');
//trim genre off the end of id (it was there for uniqueness on the page)
id = id.substring(0, id.indexOf('_'));
$('[id^=save-button-div-' + id + ']').collapse('hide');
$('[id^=watched-buttons-' + id + ']').collapse('show');
});
$('.delete-btn').click(function (e) {
e.preventDefault();
var id = $(this).attr('data-id');
if (!id) {
return;
}
var req = {
url: '/api/user/removeMovie',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({
id: id
})
};
$.ajax(req).then(function (res) {
if (res.success === true) {
$('.movie-' + id).collapse('hide');
Ghetto.alert('Movie deleted!');
} else {
Ghetto.alert(res.error, { level: 'danger' });
}
});
});
$('div').on('click', '.watched-btn', function (e) {
var id = $(this).attr('data-id');
var state = $(this).attr('data-state');
//trim genre off the end of id (it was there for uniqueness on the page)
id = id.substring(0, id.indexOf('_'));
var request = {
url: '/api/user/watchMovie/' + id,
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({
state: state
})
};
$.ajax(request).then(function (response) {
if (!response.err) {
$('[id^=watched-buttons-' + id + ']').collapse('hide');
if (state == 2) {
$('[id^=movie-panel-' + id + ']').unbind('mouseleave mouseenter');
$('[id^=rate-' + id + ']').collapse('show');
} else {
$('.save-button[data-id^="' + id + '"]').attr('disabled', 'disabled');
$('[id^=save-button-div-' + id + ']').collapse('show');
}
} else {
console.log(response.err);
}
});
});
$('.featured .btn').click( function (e) {
e.preventDefault();
var mid = $(this).attr('data-id');
var request = {
url: '/movies/my/feature/' + mid,
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({})
};
$.ajax(request).then(function (response) {
if(response.err) {
console.log(response.err);
Ghetto.alert(response.err, { level: 'danger' });
} else {
Ghetto.alert('Featured movie saved!');
}
});
});
$('.save-rating-btn').click(function (e) {
var id = $(this).attr('data-id');
var rating = parseInt($('#rating-' + id).val());
//trim genre off the end of id (it was there for uniqueness on the page)
id = id.substring(0, id.indexOf('_'));
if (rating) {
var request = {
url: '/api/movies/' + id + '/vote',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({
rating: rating
})
};
$.ajax(request).then(function (response) {
resetButtons(id);
});
}
});
$('.cancel-rating-btn').click(function (e) {
var id = $(this).attr('data-id');
resetButtons(id);
});
function resetButtons (id) {
// Reset buttons and re-attach event handler
$('[id^=rate-' + id + ']').collapse('hide');
$('.save-button[data-id^="' + id + '"]').attr('disabled', 'disabled');
$('[id^=save-button-div-' + id + ']').collapse('show');
$('[id^=movie-panel-' + id + ']').bind('mouseenter', function () {
$(this).find('.movie-panel-overlay').finish();
$(this).find('.movie-panel-overlay').fadeIn(150);
}).bind('mouseleave', function () {
$(this).find('.movie-panel-overlay').fadeOut(150);
});
}
$('h2').on('click', '.btn-collapse', function (e) {
if (this.dataset.expanded === 'true') {
$(this).animate({ rotateAmount: -90 }, {
step: function (now, fx) {
$(this).css('transform', 'rotate(' + now + 'deg)');
},
duration: 150
});
this.dataset.expanded = false;
} else {
$(this).animate({ rotateAmount: 0 }, {
step: function (now, fx) {
$(this).css('transform', 'rotate(' + now + 'deg)');
},
duration: 150
});
this.dataset.expanded = true;
}
});
// For every <li><a href=[path]></a></li>, if the path is equal to the current
// browser location, give the anchor the 'active' class so it is properly
// highlighted by bootstrap
$('.navbar .navbar-nav li').each(function (_, li) {
if (li.children instanceof HTMLCollection && li.children.length > 0) {
$(li.children).each(function (_, child) {
if (child.href === document.location.href.split('#')[0]) {
li.classList.add('active');
}
});
}
});
// Display overlay when the user hovers over a movie panel
$('.movie-panel').on('mouseenter', function () {
$(this).find('.movie-panel-overlay').finish();
$(this).find('.movie-panel-overlay').fadeIn(150);
}).on('mouseleave', function () {
$(this).find('.movie-panel-overlay').fadeOut(150);
});
// Why do I need to specify this hook? I'm not sure -- maybe because
// bootstrap = dick
$('.input-group').on('focus', '.form-control', function () {
$(this).closest('.form-group, .input-group').addClass('focus');
}).on('blur', '.form-control', function () {
$(this).closest('.form-group, .input-group').removeClass('focus');
});
})(window.jQuery);
| jajmo/Ghetto-IMDB | static/js/movies.js | JavaScript | mit | 6,246 |
'use strict';
var fs = require( 'fs' );
var path = require( 'path' );
var readlineSync = require( 'readline-sync' );
require( 'plus_arrays' );
require( 'colors' );
var freqTable = require( './freqTable' );
function annotateRandomSample( inputFile, options ) {
// if path is not absolute, make it absolute with respect to dirname
if ( path.resolve( inputFile ) !== path.normalize( inputFile ) ) {
inputFile = path.normalize(__dirname + '/../' + inputFile);
}
var input = require(inputFile);
if ( options.output === undefined ){
throw new TypeError( 'Invalid argument for --output. Must provide a file name. Value: `' + options.output + '`.' );
}
if ( options.categories === undefined ) {
throw new TypeError('Invalid argument for --categories. Must provide a space-separated list of categories. Value: `' + options.categories + '`.' );
}
var categories = options.categories.split(' ');
var result = input.map(function( elem, index ) {
var o = {};
o.text = elem;
console.log('DOCUMENT ' + index + ':');
console.log(elem.green.bold);
console.log('CATEGORIES:');
console.log(categories.map(function(e,i){
return i + ':' + e;
}).join('\t'));
console.log('Please enter correct category:'.grey);
var chosenCategories = [];
function isSelection(e, i) {
return selection.contains(i) === true;
}
while ( chosenCategories.length === 0 ) {
var selection = readlineSync.question('CHOICE(S):'.white.inverse + ': ').split(' ');
chosenCategories = categories.filter(isSelection);
if ( chosenCategories.length === 0){
console.log('Not a valid input. Try again.');
}
}
o.categories = chosenCategories;
return o;
});
fs.writeFileSync(options.output, JSON.stringify(result) );
var table = freqTable( result, categories );
console.log(table);
}
module.exports = exports = annotateRandomSample;
| Planeshifter/node-wordnetify-sample | lib/annotateRandomSample.js | JavaScript | mit | 1,860 |
/*!
* datastructures-js
* priorityQueue
* Copyright(c) 2015 Eyas Ranjous <[email protected]>
* MIT Licensed
*/
var queue = require('./queue');
function priorityQueue() {
'use strict';
var prototype = queue(), // queue object as the prototype
self = Object.create(prototype);
// determine the top priority element
self.getTopPriorityIndex = function() {
var length = this.elements.length;
if (length > 0) {
var pIndex = 0;
var p = this.elements[0].priority;
for (var i = 1; i < length; i++) {
var priority = this.elements[i].priority;
if (priority < p) {
pIndex = i;
p = priority;
}
}
return pIndex;
}
return -1;
};
self.enqueue = function(el, p) {
p = parseInt(p);
if (isNaN(p)) {
throw {
message: 'priority should be an integer'
};
}
this.elements.push({ // element is pushed as an object with a priority
element: el,
priority: p
});
};
self.dequeue = function() {
var pIndex = self.getTopPriorityIndex();
return pIndex > -1 ? this.elements.splice(pIndex, 1)[0].element : null;
};
self.front = function() {
return !this.isEmpty() ? this.elements[0].element : null;
};
self.back = function() {
return !self.isEmpty() ? this.elements[this.elements.length - 1].element : null;
};
return self;
}
module.exports = priorityQueue; | Bryukh/datastructures-js | lib/priorityQueue.js | JavaScript | mit | 1,632 |
Minder.run(function($rootScope) {
angular.element("body").fadeIn(300);
// Add runtime tasks here
}); | jeremythuff/minderui | app/config/runTime.js | JavaScript | mit | 107 |
var Scene = function(gl) {
this.noiseTexture = new Texture2D(gl, "media/lab4_noise.png");
this.brainTexture = new Texture2D(gl, "media/brain-at_1024.jpg");
this.brainTextureHD = new Texture2D(gl, "media/brain-at_4096.jpg");
this.matcapGreen = new Texture2D(gl, "media/Matcap/matcap4.jpg");
this.skyCubeTexture = new
TextureCube(gl, [
"media/posx.jpg",
"media/negx.jpg",
"media/posy.jpg",
"media/negy.jpg",
"media/posz.jpg",
"media/negz.jpg",]
);
this.timeAtLastFrame = new Date().getTime();
this.vsEnvirCube = new Shader(gl, gl.VERTEX_SHADER, "cube_vs.essl");
this.fsEnvirCube = new Shader(gl, gl.FRAGMENT_SHADER, "cube_fs.essl");
this.vsNoiseShader = new Shader(gl, gl.VERTEX_SHADER, "vsNoiseShader.essl");
this.fsNoiseShader = new Shader(gl, gl.FRAGMENT_SHADER, "fsNoiseShader.essl");
this.cubeEnvirProgram = new Program (gl, this.vsEnvirCube, this.fsEnvirCube);
this.noiseProgram = new Program (gl, this.vsNoiseShader, this.fsNoiseShader);
this.quadGeometry = new QuadGeometry(gl);
this.brainMaterial = new Material (gl, this.noiseProgram);
this.brainMaterial.background.set (this.skyCubeTexture);
this.brainMaterial.noiseTexture.set (this.noiseTexture);
this.brainMaterial.brainTex.set (this.brainTextureHD);
//this.brainMaterial.brainTex.set (this.brainTexture);
this.brainMaterial.matcapTex.set (this.matcapGreen);
this.NoiseMaterial = new Material(gl, this.noiseProgram);
this.NoiseMaterial.background.set (this.skyCubeTexture);
this.NoiseMaterial.noiseTexture.set (this.noiseTexture);
this.NoiseMesh = new Mesh (this.quadGeometry, this.brainMaterial);
this.NoiseObj = new GameObject2D(this.NoiseMesh);
this.cubeMaterial = new Material(gl, this.cubeEnvirProgram);
this.cubeMaterial. envMapTexture.set (
this.skyCubeTexture);
this.envirMesh = new Mesh (this.quadGeometry, this.cubeMaterial);
this.environment = new GameObject2D (this.envirMesh);
this.gameObjects = [this.NoiseObj /*, this.environment*/];
this.camera = new PerspectiveCamera();
gl.disable(gl.BLEND);
gl.enable(gl.DEPTH_TEST);
gl.blendFunc(
gl.SRC_ALPHA,
gl.ONE_MINUS_SRC_ALPHA);
this.elapsedTime = 0.0;
this.zSetTime = 0.0;
this.zValue = 0;
};
Scene.prototype.update = function(gl, keysPressed) {
//jshint bitwise:false
//jshint unused:false
var timeAtThisFrame = new Date().getTime();
var dt = (timeAtThisFrame - this.timeAtLastFrame) / 1000.0;
this.elapsedTime += dt;
this.timeAtLastFrame = timeAtThisFrame;
this.zSetTime += dt;
if (this.zSetTime > 0.03)
{
this.zSetTime = 0.0
//this.brainMaterial.z.set (this.zValue);
this.zValue += 1;
}
// clear the screen
gl.clearColor(0.6, 0.0, 0.3, 1.0);
gl.clearDepth(1.0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
this.camera.move(dt, keysPressed);
for(var i=0; i<this.gameObjects.length; i++) {
this.gameObjects[i].move (dt);
this.gameObjects[i].updateModelTransformation ();
this.gameObjects[i].draw(this.camera);
}
};
Scene.prototype.mouseMove = function(event) {
this.camera.mouseMove(event);
}
Scene.prototype.mouseDown = function(event) {
this.camera.mouseDown(event);
}
Scene.prototype.mouseUp = function(event) {
this.camera.mouseUp(event);
} | RyperHUN/RenderingExamples | RayMarchingVolumetric_Brain/js/Scene.js | JavaScript | mit | 3,266 |
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _imageWriter = require('./image-writer');
var _imageWriter2 = _interopRequireDefault(_imageWriter);
var Message = (function (_DBModel) {
_inherits(Message, _DBModel);
function Message(conf) {
_classCallCheck(this, Message);
_get(Object.getPrototypeOf(Message.prototype), 'constructor', this).call(this);
this.writer = new _imageWriter2['default'](conf.IMAGE_PATH);
}
_createClass(Message, [{
key: 'create',
value: function create(user, text) {
return regeneratorRuntime.async(function create$(context$2$0) {
while (1) switch (context$2$0.prev = context$2$0.next) {
case 0:
context$2$0.next = 2;
return regeneratorRuntime.awrap(this.query.getOne('createMessage', [user.id, text]));
case 2:
return context$2$0.abrupt('return', context$2$0.sent);
case 3:
case 'end':
return context$2$0.stop();
}
}, null, this);
}
}, {
key: 'createImage',
value: function createImage(user, raw, type) {
var name;
return regeneratorRuntime.async(function createImage$(context$2$0) {
while (1) switch (context$2$0.prev = context$2$0.next) {
case 0:
context$2$0.next = 2;
return regeneratorRuntime.awrap(this.writer.write(raw, type));
case 2:
name = context$2$0.sent;
context$2$0.next = 5;
return regeneratorRuntime.awrap(this.query.getOne('createImageMessage', [user.id, 'img/' + name]));
case 5:
return context$2$0.abrupt('return', context$2$0.sent);
case 6:
case 'end':
return context$2$0.stop();
}
}, null, this);
}
}, {
key: 'getLatest',
value: function getLatest(id) {
return regeneratorRuntime.async(function getLatest$(context$2$0) {
while (1) switch (context$2$0.prev = context$2$0.next) {
case 0:
if (!id || id == null || id < 1) id = 999999;
context$2$0.next = 3;
return regeneratorRuntime.awrap(this.query.getAll('getMessageInterval', [id]));
case 3:
return context$2$0.abrupt('return', context$2$0.sent);
case 4:
case 'end':
return context$2$0.stop();
}
}, null, this);
}
}]);
return Message;
})(DBModel);
exports['default'] = Message;
module.exports = exports['default']; | ordinarygithubuser/chat-es7 | server/model/message.js | JavaScript | mit | 4,285 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var RandomFloat = /** @class */ (function () {
function RandomFloat() {
}
RandomFloat.nextFloat = function (min, max) {
if (max === void 0) { max = null; }
if (max == null) {
max = min;
min = 0;
}
if (max - min <= 0)
return min;
return min + Math.random() * (max - min);
};
RandomFloat.updateFloat = function (value, range) {
if (range === void 0) { range = null; }
if (range == null)
range = 0;
range = range == 0 ? 0.1 * value : range;
var minValue = value - range;
var maxValue = value + range;
return RandomFloat.nextFloat(minValue, maxValue);
};
return RandomFloat;
}());
exports.RandomFloat = RandomFloat;
//# sourceMappingURL=RandomFloat.js.map | pip-services/pip-services-commons-node | obj/src/random/RandomFloat.js | JavaScript | mit | 892 |
! function() {
"use strict";
function t(t, i, n, e) {
function r(t, i) {
for (var n = 0; n < t.length; n++) {
var e = t[n];
i(e, n)
}
}
function a(t) {
s(t), o(t), u(t)
}
function s(t) {
t.addEventListener("mouseover", function(i) {
r(f, function(i, n) {
document.getElementById('now').innerHTML = parseInt(t.getAttribute("data-index")) + 1;
n <= parseInt(t.getAttribute("data-index")) ? i.classList.add("is-active") : i.classList.remove("is-active")
})
})
}
function o(t) {
t.addEventListener("mouseout", function(t) {
document.getElementById('now').innerHTML = i;
-1 === f.indexOf(t.relatedTarget) && c(null, !1)
})
}
function u(t) {
t.addEventListener("click", function(i) {
i.preventDefault(), c(parseInt(t.getAttribute("data-index")) + 1, !0)
})
}
function c(t, a) {
t && 0 > t || t > n || (void 0 === a && (a = !0), i = t || i, r(f, function(t, n) {
i > n ? t.classList.add("is-active") : t.classList.remove("is-active")
}), e && a/* && e(d())*/)
}
function d() {
return i
}
var f = [];
return function() {
if (!t) throw Error("No element supplied.");
if (!n) throw Error("No max rating supplied.");
if (i || (i = 0), 0 > i || i > n) throw Error("Current rating is out of bounds.");
for (var e = 0; n > e; e++) {
var r = document.createElement("li");
r.classList.add("c-rating__item"), r.setAttribute("data-index", e), i > e && r.classList.add("is-active"), t.appendChild(r), f.push(r), a(r)
}
}(), {
setRating: c,
getRating: d
}
}
window.rating = t
}();
| teacher144123/npo_map | server/js/dict/rating.min.js | JavaScript | mit | 1,615 |
"use strict";
// INCLUDES
if (typeof exports !== "undefined")
{
global.URL = require("url");
global.fs = require("fs");
global.http = require("http");
global.https = require("https");
global.WSServer = require("websocket").server;
global.WebSocketConnection = require("./websocketconnection");
global.logger = require("winston");
}
/**
* @class WebSocketServer
*/
function WebSocketServer()
{
var self = this;
var options = {};
var connectionListener = null;
var wsServer = null;
var webServer = null;
self.setConnectionListener = function(listener)
{
connectionListener = listener;
};
self.listen = function(opts, callback)
{
try {
options.host = opts.host || null;
options.port = opts.port || "";
options.isSsl = opts.isSsl || false;
options.sslKey = opts.sslKey || "";
options.sslCert = opts.sslCert || "";
options.sslAuthCert = opts.sslAuthCert || "";
options.owner = opts.owner || "-";
options.connectionListener = opts.connectionListener || null;
options.unknMethodListener = opts.unknownMethodListener || null;
options.protocol = (!options.isSsl ? "ws" : "wss");
options.class = "WebSocketServer";
if (!options.isSsl) // Start a http server
{
webServer = http.createServer(function(request, response)
{
logger.log("httpServer::on(request)");
response.writeHead(501);
response.end("Not implemented");
});
}
else // Start a https server
{
console.log("Trying to start https server: "+ JSON.stringify({ key: options.sslKey, cert: options.sslCert, ca: options.sslAuthCert}));
var key = fs.readFileSync(options.sslKey);
var crt = fs.readFileSync(options.sslCert);
var ca_crt = fs.readFileSync(options.sslAuthCert, "utf8");
//webServer = https.createServer({ key: options.sslKey, cert: options.sslCert, ca: options.sslAuthCert}, function(request, response)
webServer = https.createServer({ key: key, cert: crt, ca: ca_crt}, function(request, response)
{
logger.log("httpsServer::on(request)");
response.writeHead(501);
response.end("Not implemented");
});
}
webServer.listen(options.port, options.host, 511, function()
{
console.log("webserver of websocketserver listening");
callback(null, true);
});
webServer.on("error", function(err)
{
console.log(err);
callback(err, null);
});
// Create the WebSocket server
console.log("Creating WSServer");
wsServer = new WSServer(
{
httpServer: webServer,
autoAcceptConnections: false,
keepalive: true, // Keepalive connections and
keepaliveInterval: 60000, // ping them once a minute and
dropConnectionOnKeepaliveTimeout: true, // drop a connection if there's no answer
keepaliveGracePeriod: 10000 // within the grace period.
});
// Connection request
wsServer.on("request", function(request)
{
logger.info("wsServer::on(request)");
// Accept connection - Should the request.origin be checked somehow?{ request.reject(404, <message>); throw ""; }?
try
{
var connection = new WebSocketConnection();
connection.setSocket(request.accept("json-rpc", request.origin));
connection.setRemoteAddress(request.remoteAddress);
connection.setRemotePort(request.remotePort);
connection.setOrigin(request.origin);
var query = URL.parse(request.resourceURL,true).query;
console.log("WebSocketServer::listen() accepting connection, given id was "+query.id);
if (query && query.id)
connection.setId(query.id);
connectionListener.addConnection(connection);
}
catch(err)
{
console.log(err);
return;
}
});
// Connection closed
wsServer.on("close", function(webSocketConnection, closeReason, description)
{
logger.info("wsServer::on(close) ");
});
}
catch (e)
{
console.log(e);
}
};
self.close = function()
{
try {
if(wsServer)
{
wsServer.shutDown();
wsServer = null;
}
if(webServer)
{
webServer.close();
webServer = null;
}
}
catch (e)
{
console.log(e);
}
};
}
if (typeof exports !== "undefined")
{
module.exports = WebSocketServer;
}
| ptesavol/webjsonrpc | websocketserver.js | JavaScript | mit | 4,196 |
/**
* Layout component that queries for data
* with Gatsby's useStaticQuery component
*
* See: https://www.gatsbyjs.org/docs/use-static-query/
*/
import React from "react"
import PropTypes from "prop-types"
import { useStaticQuery, graphql } from "gatsby"
import "./layout.css"
import "./fonts.css"
import "./james_daydreams.css"
const Layout = ({ children }) => {
const data = useStaticQuery(graphql`
query SiteTitleQuery {
site {
siteMetadata {
title
}
}
}
`)
return (
<>
<div
style={{
margin: `200px 25% 0 30px`,
maxWidth: 960,
padding: `0px 1.0875rem 1.45rem`,
paddingTop: 0,
}}
>
<main>{children}</main>
<footer>
{console.log(data)}
</footer>
</div>
</>
)
}
Layout.propTypes = {
children: PropTypes.node.isRequired,
}
export default Layout
| parisminton/james.da.ydrea.ms | src/components/layout.js | JavaScript | mit | 928 |
/**
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
app: 'app',
// angular bundles
'@angular/core': 'npm:@angular/core/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common/bundles/common.umd.js',
'@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router/bundles/router.umd.js',
'@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular2-in-memory-web-api': 'npm:angular2-in-memory-web-api',
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: 'main.js',
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
},
'angular2-in-memory-web-api': {
main: './index.js',
defaultExtension: 'js'
}
}
});
})(this); | nz-andy/electron-test | systemjs.config.js | JavaScript | mit | 1,529 |
import React,{ Component } from 'react'
import { {{ name }}List } from './list'
export { {{ name }}List }
| team4yf/yf-fpm-admin | src_template/index.js | JavaScript | mit | 107 |
angular.module('Techtalk')
.factory('socket', function ($rootScope, config) {
if (typeof (io) != "undefined") {
var socket = io.connect(config.Urls.URLService, { reconnection: false });
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
}
};
}
return;
})
.directive('serverError', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
element.on('keydown', function () {
ctrl.$setValidity('server', true)
});
}
}
})
.directive('ngEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if (event.which === 13) {
scope.$apply(function () {
scope.$eval(attrs.ngEnter);
});
var $id = $("." + attrs.ngScrollBottomText);
$id.scrollTop($id[0].scrollHeight + 250);
event.preventDefault();
}
});
};
})
.directive("ngScrollBottom", function () {
return {
link: function (scope, element, attr) {
var $id = $("." + attr.ngScrollBottom);
$(element).on("click", function () {
$id.scrollTop($id[0].scrollHeight + 250);
$('.msg-field').focus();
});
}
}
});
| RafaSousa/techtalk-node | client/app/directives/main-directive.js | JavaScript | mit | 1,844 |
// Regular expression that matches all symbols with the `IDS_Binary_Operator` property as per Unicode v7.0.0:
/[\u2FF0\u2FF1\u2FF4-\u2FFB]/; | mathiasbynens/unicode-data | 7.0.0/properties/IDS_Binary_Operator-regex.js | JavaScript | mit | 140 |
(function(){
console.log("Message");
})(); | curvecode/chrome-ext-js | app/helloworld/js/app.js | JavaScript | mit | 46 |
var express = require('express');
var morphine = require('./api');
var app = express();
// Mounts the rpc layer middleware. This will enable remote function calls
app.use(morphine.router);
// Serve static files in this folder
app.use('/', express.static(__dirname + '/'));
// Listen on port 3000
app.listen(3000, function(err) {
if (err) return console.log(err.stack);
// Creates a user when you boot up the server
// This is only to demostrate we can use the same code on server side...
var User = morphine.User;
User.create({ _id: 5, name: 'someone' }, function(err, user) {
if (err) console.error(err.stack);
console.log('App listening on http://127.0.0.1:3000');
});
});
| d-oliveros/isomorphine | examples/barebone/src/server.js | JavaScript | mit | 703 |
#!/usr/bin/env node
require('yargs')
.commandDir('cmd')
.demand(1)
.strict()
.help()
.argv;
| dobbydog/webpack-porter | cli.js | JavaScript | mit | 93 |
// flow-typed signature: a4cf0a15120e85fc382b90182181b521
// flow-typed version: <<STUB>>/grunt_v^1.0.1/flow_v0.49.1
/**
* This is an autogenerated libdef stub for:
*
* 'grunt'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'grunt' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'grunt/lib/grunt' {
declare module.exports: any;
}
declare module 'grunt/lib/grunt/cli' {
declare module.exports: any;
}
declare module 'grunt/lib/grunt/config' {
declare module.exports: any;
}
declare module 'grunt/lib/grunt/event' {
declare module.exports: any;
}
declare module 'grunt/lib/grunt/fail' {
declare module.exports: any;
}
declare module 'grunt/lib/grunt/file' {
declare module.exports: any;
}
declare module 'grunt/lib/grunt/help' {
declare module.exports: any;
}
declare module 'grunt/lib/grunt/option' {
declare module.exports: any;
}
declare module 'grunt/lib/grunt/task' {
declare module.exports: any;
}
declare module 'grunt/lib/grunt/template' {
declare module.exports: any;
}
declare module 'grunt/lib/util/task' {
declare module.exports: any;
}
// Filename aliases
declare module 'grunt/lib/grunt.js' {
declare module.exports: $Exports<'grunt/lib/grunt'>;
}
declare module 'grunt/lib/grunt/cli.js' {
declare module.exports: $Exports<'grunt/lib/grunt/cli'>;
}
declare module 'grunt/lib/grunt/config.js' {
declare module.exports: $Exports<'grunt/lib/grunt/config'>;
}
declare module 'grunt/lib/grunt/event.js' {
declare module.exports: $Exports<'grunt/lib/grunt/event'>;
}
declare module 'grunt/lib/grunt/fail.js' {
declare module.exports: $Exports<'grunt/lib/grunt/fail'>;
}
declare module 'grunt/lib/grunt/file.js' {
declare module.exports: $Exports<'grunt/lib/grunt/file'>;
}
declare module 'grunt/lib/grunt/help.js' {
declare module.exports: $Exports<'grunt/lib/grunt/help'>;
}
declare module 'grunt/lib/grunt/option.js' {
declare module.exports: $Exports<'grunt/lib/grunt/option'>;
}
declare module 'grunt/lib/grunt/task.js' {
declare module.exports: $Exports<'grunt/lib/grunt/task'>;
}
declare module 'grunt/lib/grunt/template.js' {
declare module.exports: $Exports<'grunt/lib/grunt/template'>;
}
declare module 'grunt/lib/util/task.js' {
declare module.exports: $Exports<'grunt/lib/util/task'>;
}
| kaitamkun/frisktol | flow-typed/npm/grunt_vx.x.x.js | JavaScript | mit | 2,626 |
/**
* @desc express config
* @author awwwesssooooome <[email protected]>
* @date 2015-09-21
*/
'use strict';
/**
* Module dependencies
*/
import express from 'express';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import favicon from 'serve-favicon';
import compression from 'compression';
import swig from 'swig';
import pkg from '../package.json';
/**
* Expose
*/
export default ((app) => {
// Compression middleware (should be placed before express.static)
app.use(compression({
threshold: 512
}));
// Set favicon
app.use(favicon(`${__dirname}/../public/favicon.ico`));
// Static files middleware
app.use(express.static(`${__dirname}/../public`));
// Set views path, template engine and default layout
app.engine('html', swig.renderFile);
app.set('views', `${__dirname}/../app/views`);
app.set('view engine', 'html');
// For development
app.set('view cache', false);
swig.setDefaults({ cache: false });
// Expose package.json to views
app.use((req, res, next) => {
res.locals.pkg = pkg;
res.locals.env = process.env.NODE_ENV || 'development';
next();
});
// bodyParser should be above methodOverride
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// CookieParser should be above session
app.use(cookieParser());
//app.use(cookieSession({ secret: 'secret' }));
});
| playwolsey/Robin | config/express.js | JavaScript | mit | 1,492 |
var Type = function(Bookshelf) {
return Bookshelf.Model.extend({
tableName: 'types',
model: function() {
return this.belongsTo('model');
}
});
};
module.exports = Type;
| ericclemmons/bookshelf-manager | test/models/type.js | JavaScript | mit | 193 |
var Mocha = require('mocha');
var path = require('path');
var Module = require('module');
var generateSauceReporter = require('./mocha-sauce-reporter');
var fs = require('fs');
var path = require('path');
module.exports = function (opts, fileGroup, browser, grunt, onTestFinish) {
//browserTitle means we're on a SL test
if (browser.browserTitle) {
opts.reporter = generateSauceReporter(browser);
}
var cwd = process.cwd();
module.paths.push(cwd, path.join(cwd, 'node_modules'));
if (opts && opts.require) {
var mods = opts.require;
if (!(mods instanceof Array)) { mods = [mods]; }
mods.forEach(function(mod) {
var abs = fs.existsSync(mod) || fs.existsSync(mod + '.js');
if (abs) {
mod = path.resolve(mod);
}
require(mod);
});
}
var mocha = new Mocha(opts);
mocha.suite.on('pre-require', function (context, file, m) {
this.ctx.browser = browser;
});
grunt.file.expand({filter: 'isFile'}, fileGroup.src).forEach(function (f) {
var filePath = path.resolve(f);
if (Module._cache[filePath]) {
delete Module._cache[filePath];
}
mocha.addFile(filePath);
});
try {
mocha.run(function(errCount) {
var err;
if (errCount !==0) {
err = new Error('Tests encountered ' + errCount + ' errors.');
}
onTestFinish(err);
});
} catch (e) {
grunt.log.error("Mocha failed to run");
grunt.log.error(e.stack);
onTestFinish(false);
}
};
| pdehaan/grunt-mocha-webdriver | tasks/lib/mocha-runner.js | JavaScript | mit | 1,479 |
exports.BattleMovedex = {
//-----------------------------------------------------------------------------------------------
//Misc changes
//-----------------------------------------------------------------------------------------------
"shellsmash": {
inherit: true,
boosts: {
atk: 2,
spa: 2,
spe: 2,
def: -1,
spd: -1
},
onModifyMove: function(move, user) {
if (user.ability === 'shellarmor') {
move.boosts = {
spa: 1,
atk: 1,
spe: 2,
};
}
}
},
//-----------------------------------------------------------------------------------------------
//The freeze status was removed from the game entirely and replaced by flinch
//-----------------------------------------------------------------------------------------------
icebeam: {
inherit: true,
secondary: {
chance: 10,
volatileStatus: 'flinch'
}
},
icefang: {
inherit: true,
secondary: {
chance: 20,
volatileStatus: 'flinch'
}
},
icepunch: {
inherit: true,
secondary: {
chance: 10,
volatileStatus: 'flinch'
}
},
powdersnow: {
inherit: true,
secondary: {
chance: 10,
volatileStatus: 'flinch'
}
},
blizzard: {
inherit: true,
secondary: {
chance: 10,
volatileStatus: 'flinch'
}
},
triattack: {
inherit: true,
secondary: {
chance: 20,
onHit: function(target, source) {
var result = this.random(3);
if (result===0) {
target.trySetStatus('brn', source);
} else if (result===1) {
target.trySetStatus('par', source);
} else {
target.trySetStatus('tox', source);
}
}
}
},
//-----------------------------------------------------------------------------------------------
//Various nerfed moves
//-----------------------------------------------------------------------------------------------
thunder: {
inherit: true,
secondary: {
chance: 10
}
},
hurricane: {
inherit: true,
secondary: {
chance: 0
}
},
darkvoid: {
inherit: true,
target: "foes"
},
stealthrock: {
inherit: true,
effect: {
// this is a side condition
onStart: function(side) {
this.add('-sidestart',side,'move: Stealth Rock');
},
onSwitchIn: function(pokemon) {
var typeMod = this.getEffectiveness('Rock', pokemon);
var factor = 8;
if (typeMod == 1) factor = 4;
if (typeMod >= 2) factor = 4;
if (typeMod == -1) factor = 16;
if (typeMod <= -2) factor = 32;
var damage = this.damage(pokemon.maxhp/factor);
}
}
},
//-----------------------------------------------------------------------------------------------
//More good critting moves
//-----------------------------------------------------------------------------------------------
explosion: {
inherit: true,
basePower: 200,
willCrit: true
},
selfdestruct: {
inherit: true,
basePower: 125,
willCrit: true
},
twineedle: {
num: 41,
accuracy: 100,
basePower: 20,
willCrit: true,
category: "Physical",
desc: "Deals damage to one adjacent target and hits twice, with each hit having a 20% chance to poison it. If the first hit breaks the target's Substitute, it will take damage for the second hit.",
shortDesc: "Hits 2 times. Each hit has 20% chance to poison.",
id: "twineedle",
name: "Twineedle",
pp: 20,
priority: 0,
multihit: [2,2],
secondary: {
chance: 20,
status: 'psn'
},
target: "normal",
type: "Bug"
},
drillrun: {
inherit: true,
basePower: 40,
accuracy: 90,
willCrit: true
},
frostbreath: {
inherit: true,
power: 50,
accuracy: 100
},
stormthrow: {
inherit: true,
power: 50,
accuracy: 100
},
nightslash: {
inherit: true,
power: 50,
willCrit: true
},
//-----------------------------------------------------------------------------------------------
//Various buffs
//-----------------------------------------------------------------------------------------------
bulldoze: {
num: 523,
accuracy: 100,
basePower: 80,
category: "Physical",
desc: "Deals damage to all adjacent Pokemon with a 100% chance to lower their Speed by 1 stage each.",
shortDesc: "100% chance to lower adjacent Pkmn Speed by 1.",
id: "bulldoze",
name: "Bulldoze",
pp: 20,
priority: 0,
secondary: {
chance: 50,
boosts: {
spe: -1
}
},
target: "adjacent",
type: "Ground"
},
crosspoison: {
inherit: true,
basePower: 90
},
razorshell: {
inherit: true,
basePower: 100,
accuracy: 85
},
glaciate: {
inherit: true,
basePower: 100,
accuracy: 100,
secondary: {
chance: 50,
boosts: {
spe: -1
}
}
},
heatwave: {
inherit: true,
basePower: 90,
accuracy: 100,
secondary: {
chance: 0
},
basePowerCallback: function() {
if (this.isWeather('sunnyday')) {
return 120;
}
return 90;
}
},
poisontail: {
inherit: true,
basePower: 95
},
xscissor: {
inherit: true,
basePower: 90
},
rockslide: {
inherit: true,
basePower: 80,
accuracy: 100
},
stoneedge: {
inherit: true,
accuracy: 85
},
hammerarm: {
inherit: true,
secondary: {
chance: 20,
boosts: {
spe: -1
}
}
},
toxic: {
inherit: true,
accuracy: 100
},
willowisp: {
inherit: true,
accuracy: 100
},
acidspray: {
inherit: true,
target: "adjacent",
power: 70
},
relicsong: {
inherit: true,
secondary: {
chance: 20,
self: {
boosts: {
atk: 1,
spa: 1
}
}
}
},
honeclaws: {
inherit: true,
boosts: {
atk: 1,
accuracy: 2
}
},
shadowpunch: {
inherit: true,
basePower: 85
},
wildcharge: {
inherit: true,
basePower: 100,
},
nightdaze: {
inherit: true,
basePower: 90,
accuracy: 100,
secondary: {
chance: 20,
boosts: {
accuracy: -1
}
}
},
meditate: {
inherit: true,
boosts: {
atk: 1,
spd: 1
}
},
//-----------------------------------------------------------------------------------------------
//Massively changed moves that are pretty much new ones
//-----------------------------------------------------------------------------------------------
"lockon": {
num: 199,
accuracy: true,
basePower: 0,
category: "Status",
desc: "On the following turn, one adjacent target cannot avoid the user's moves, even if the target is in the middle of a two-turn move. Fails if the user tries to use this move again during effect.",
shortDesc: "User's next move will not miss the target.",
id: "lockon",
name: "Lock-On",
pp: 5,
priority: 0,
self: {
boosts: {
spa: 1,
accuracy: 1
}
},
secondary: false,
target: "self",
type: "Normal"
},
lunardance: {
num: 461,
accuracy: true,
basePower: 0,
category: "Status",
desc: "The user faints and the Pokemon brought out to replace it has its HP and PP fully restored along with having any major status condition cured. Fails if the user is the last unfainted Pokemon in its party.",
shortDesc: "User faints. Replacement is fully healed, with PP.",
id: "lunardance",
isViable: true,
name: "Lunar Dance",
pp: 20,
priority: 0,
isSnatchable: true,
boosts: {
spa: 1,
spe: 1
},
secondary: false,
target: "self",
type: "Psychic"
},
rage: {
inherit: true,
basePower: 100,
onHit: function(target, source) {
source.addVolatile('confusion');
}
},
poisonjab: {
inherit: true,
basePower: 40,
priority: 1,
secondary: {
chance: 0
}
},
skyattack: {
num: 143,
accuracy: 90,
basePower: 100,
category: "Physical",
desc: "Deals damage to one adjacent or non-adjacent target with a 30% chance to flinch it and a higher chance for a critical hit. This attack charges on the first turn and strikes on the second. The user cannot make a move between turns. If the user is holding a Power Herb, the move completes in one turn.",
shortDesc: "Charges, then hits turn 2. 30% flinch. High crit.",
id: "skyattack",
name: "Sky Attack",
pp: 15,
isViable: true,
priority: 0,
isTwoTurnMove: false,
isContact: true,
secondary: {
chance: 20,
boosts: {
def: -1
}
},
target: "any",
type: "Flying"
},
electroweb: {
inherit: true,
accuracy: 85,
basePower: 70,
secondary: {
chance: 100,
status: 'par'
}
},
payday: {
inherit: true,
basePower: 25,
multihit: [2,5]
},
barrage: {
inherit: true,
basePower: 25,
type: "Fighting",
multihit: [2,5]
},
doubleslap: {
inherit: true,
basePower: 40,
type: "Fighting",
multihit: [2,2]
},
"hydrocannon": {
num: 308,
accuracy: 100,
basePower: 150,
category: "Special",
desc: "Deals damage to one adjacent target. If this move is successful, the user must recharge on the following turn and cannot make a move.",
shortDesc: "User cannot move next turn.",
id: "hydrocannon",
name: "Hydro Cannon",
pp: 20,
priority: -3,
beforeTurnCallback: function(pokemon) {
pokemon.addVolatile('hydrocannon');
this.add('-message', pokemon.name+" is focusing it's aim!");
},
beforeMoveCallback: function(pokemon) {
if (!pokemon.removeVolatile('hydrocannon')) {
return false;
}
if (pokemon.lastAttackedBy && pokemon.lastAttackedBy.damage && pokemon.lastAttackedBy.thisTurn) {
this.add('cant', pokemon, 'flinch', 'Hydro Cannon');
return true;
}
},
effect: {
duration: 1,
onStart: function(pokemon) {
this.add('-singleturn', pokemon, 'move: Hydro Cannon');
}
},
secondary: false,
target: "normal",
type: "Water"
},
"blastburn": {
inherit: true,
accuracy: 100,
basePower: 60,
pp: 5,
willCrit: true,
selfdestruct: true,
secondary: {
chance: 100,
status: 'brn'
},
target: "allAdjacent",
self: false
},
"frenzyplant": {
inherit: true,
accuracy: 80,
basePower: 100,
category: "Physical",
pp: 5,
volatileStatus: 'partiallytrapped',
self: false
},
"triplekick": {
inherit: true,
basePowerCallback: function(pokemon) {
pokemon.addVolatile('triplekick');
return 5 + (10 * pokemon.volatiles['triplekick'].hit);
},
accuracy: 100
},
"dualchop": {
inherit: true,
accuracy: 100
},
"bonerush": {
inherit: true,
accuracy: 100
},
"feint": {
inherit: true,
basePower: 65
},
"spikecannon": {
num: 131,
accuracy: 80,
basePower: 60,
category: "Physical",
desc: "Deals damage to one adjacent target and hits two to five times. Has a 35% chance to hit two or three times, and a 15% chance to hit four or five times. If one of the hits breaks the target's Substitute, it will take damage for the remaining hits. If the user has the Ability Skill Link, this move will always hit five times.",
shortDesc: "Hits 2-5 times in one turn.",
id: "spikecannon",
name: "Spike Cannon",
pp: 15,
priority: 0,
secondary: false,
sideCondition: 'spikes',
target: "normal",
type: "Ground"
},
"gastroacid": {
inherit: true,
basePower: 50,
category: "Special",
isBounceable: false
},
"naturepower": {
inherit: true,
basePower: 80,
accuracy: 100,
priority: 0,
category: "Physical",
target: "normal",
type: "Ground",
onHit: false,
onModifyMove: function(move, source, target) {
if (source.hasType('Grass')) {
move.basePower = 100;
}
}
},
"electroweb": {
inherit: true,
target: "normal",
},
"leechseed": {
inherit: true,
accuracy: 100,
}
};
| DreMZ/PS | mods/duskmod/moves.js | JavaScript | mit | 18,661 |
// Admin main
//
// This is the main execution loop of the admin panel. It provides basic
// configuration, routing, and default imports.
require.config({
paths: {
'jquery': 'lib/jquery-1.10.2.min',
'underscore': 'lib/underscore',
'backbone': 'lib/backbone',
'require-css': 'lib/require-css.min',
'require-text': 'lib/require-text',
'pure-min': '//yui.yahooapis.com/pure/0.5.0/pure-min',
'pure-responsive': '//yui.yahooapis.com/pure/0.5.0/grids-responsive-min'
},
shim: {
jquery: {
exports: '$'
},
underscore: {
exports: '_'
},
backbone: {
deps: ['jquery', 'underscore'],
exports: 'Backbone'
}
},
map: {
'*': {
'css': 'require-css',
'text': 'require-text'
}
}
});
require(
[
'jquery',
'backbone',
'css!pure-min',
'css!pure-responsive',
'css!styles/base'
], function($, Backbone) {
var
add_app_header = function(xhr) {
xhr.setRequestHeader(
'x-peanuts-application',
'6752e4b0-8122-4c9a-ad1d-19d703fdfed0'
);
};
// The whole thing is wrapped in the success callback of a GET request for the
// CSRF token. This is necessary since all requests to the peanuts API will
// fail without it.
$.ajax({
url: '/csrf/',
beforeSend: add_app_header,
success: function(data) {
var
add_csrf_token = function(xhr) {
xhr.setRequestHeader(
'x-peanuts-csrf',
data.csrf
);
},
Router = Backbone.Router.extend({
routes: {
'first-use': 'firstUse'
},
render: function(controllerFile) {
var router = this;
require([controllerFile], function(controller) {
router.view = controller();
router.view.render();
$(document).prop(
'title',
$(document).prop('title') + ' - ' + router.view.title
);
});
},
firstUse: function() {
this.render('views/first-use');
}
}),
router = new Router(),
// The old backbone.sync method is retreived here so that the new one
// can call it.
old_sync = Backbone.sync;
// We redefine the global app header here to add in the csrf token.
Backbone.sync = function(method, model, options) {
var beforeSend = options.beforeSend;
options.beforeSend = function(xhr) {
add_app_header(xhr);
add_csrf_token(xhr);
if (beforeSend) {
beforeSend(xhr);
}
};
// Call the default method with our modified options.
old_sync(method, model, options);
};
Backbone.history.start();
}
});
});
| astex/peanuts.admin | static/main.js | JavaScript | mit | 2,817 |
import angular from 'angular-fix';
import utils from '../other/utils';
export default formlyConfig;
// @ngInject
function formlyConfig(formlyUsabilityProvider, formlyErrorAndWarningsUrlPrefix, formlyApiCheck) {
const typeMap = {};
const templateWrappersMap = {};
const defaultWrapperName = 'default';
const _this = this;
const getError = formlyUsabilityProvider.getFormlyError;
angular.extend(this, {
setType,
getType,
getTypeHeritage,
setWrapper,
getWrapper,
getWrapperByType,
removeWrapperByName,
removeWrappersForType,
disableWarnings: false,
extras: {
disableNgModelAttrsManipulator: false,
fieldTransform: [],
ngModelAttrsManipulatorPreferUnbound: false,
removeChromeAutoComplete: false,
defaultHideDirective: 'ng-if',
getFieldId: null
},
templateManipulators: {
preWrapper: [],
postWrapper: []
},
$get: () => this
});
function setType(options) {
if (angular.isArray(options)) {
const allTypes = [];
angular.forEach(options, item => {
allTypes.push(setType(item));
});
return allTypes;
} else if (angular.isObject(options)) {
checkType(options);
if (options.extends) {
extendTypeOptions(options);
}
typeMap[options.name] = options;
return typeMap[options.name];
} else {
throw getError(`You must provide an object or array for setType. You provided: ${JSON.stringify(arguments)}`);
}
}
function checkType(options) {
formlyApiCheck.throw(formlyApiCheck.formlyTypeOptions, options, {
prefix: 'formlyConfig.setType',
url: 'settype-validation-failed'
});
if (!options.overwriteOk) {
checkOverwrite(options.name, typeMap, options, 'types');
} else {
options.overwriteOk = undefined;
}
}
function extendTypeOptions(options) {
const extendsType = getType(options.extends, true, options);
extendTypeControllerFunction(options, extendsType);
extendTypeLinkFunction(options, extendsType);
extendTypeDefaultOptions(options, extendsType);
utils.reverseDeepMerge(options, extendsType);
extendTemplate(options, extendsType);
}
function extendTemplate(options, extendsType) {
if (options.template && extendsType.templateUrl) {
delete options.templateUrl;
} else if (options.templateUrl && extendsType.template) {
delete options.template;
}
}
function extendTypeControllerFunction(options, extendsType) {
const extendsCtrl = extendsType.controller;
if (!angular.isDefined(extendsCtrl)) {
return;
}
const optionsCtrl = options.controller;
if (angular.isDefined(optionsCtrl)) {
options.controller = function($scope, $controller) {
$controller(extendsCtrl, {$scope});
$controller(optionsCtrl, {$scope});
};
options.controller.$inject = ['$scope', '$controller'];
} else {
options.controller = extendsCtrl;
}
}
function extendTypeLinkFunction(options, extendsType) {
const extendsFn = extendsType.link;
if (!angular.isDefined(extendsFn)) {
return;
}
const optionsFn = options.link;
if (angular.isDefined(optionsFn)) {
options.link = function() {
extendsFn(...arguments);
optionsFn(...arguments);
};
} else {
options.link = extendsFn;
}
}
function extendTypeDefaultOptions(options, extendsType) {
const extendsDO = extendsType.defaultOptions;
if (!angular.isDefined(extendsDO)) {
return;
}
const optionsDO = options.defaultOptions;
const optionsDOIsFn = angular.isFunction(optionsDO);
const extendsDOIsFn = angular.isFunction(extendsDO);
if (extendsDOIsFn) {
options.defaultOptions = function defaultOptions(opts, scope) {
const extendsDefaultOptions = extendsDO(opts, scope);
const mergedDefaultOptions = {};
utils.reverseDeepMerge(mergedDefaultOptions, opts, extendsDefaultOptions);
let extenderOptionsDefaultOptions = optionsDO;
if (optionsDOIsFn) {
extenderOptionsDefaultOptions = extenderOptionsDefaultOptions(mergedDefaultOptions, scope);
}
utils.reverseDeepMerge(extendsDefaultOptions, extenderOptionsDefaultOptions);
return extendsDefaultOptions;
};
} else if (optionsDOIsFn) {
options.defaultOptions = function defaultOptions(opts, scope) {
const newDefaultOptions = {};
utils.reverseDeepMerge(newDefaultOptions, opts, extendsDO);
return optionsDO(newDefaultOptions, scope);
};
}
}
function getType(name, throwError, errorContext) {
if (!name) {
return undefined;
}
const type = typeMap[name];
if (!type && throwError === true) {
throw getError(
`There is no type by the name of "${name}": ${JSON.stringify(errorContext)}`
);
} else {
return type;
}
}
function getTypeHeritage(parent) {
const heritage = [];
let type = parent;
if (angular.isString(type)) {
type = getType(parent);
}
parent = type.extends;
while (parent) {
type = getType(parent);
heritage.push(type);
parent = type.extends;
}
return heritage;
}
function setWrapper(options, name) {
if (angular.isArray(options)) {
return options.map(wrapperOptions => setWrapper(wrapperOptions));
} else if (angular.isObject(options)) {
options.types = getOptionsTypes(options);
options.name = getOptionsName(options, name);
checkWrapperAPI(options);
templateWrappersMap[options.name] = options;
return options;
} else if (angular.isString(options)) {
return setWrapper({
template: options,
name
});
}
}
function getOptionsTypes(options) {
if (angular.isString(options.types)) {
return [options.types];
}
if (!angular.isDefined(options.types)) {
return [];
} else {
return options.types;
}
}
function getOptionsName(options, name) {
return options.name || name || options.types.join(' ') || defaultWrapperName;
}
function checkWrapperAPI(options) {
formlyUsabilityProvider.checkWrapper(options);
if (options.template) {
formlyUsabilityProvider.checkWrapperTemplate(options.template, options);
}
if (!options.overwriteOk) {
checkOverwrite(options.name, templateWrappersMap, options, 'templateWrappers');
} else {
delete options.overwriteOk;
}
checkWrapperTypes(options);
}
function checkWrapperTypes(options) {
const shouldThrow = !angular.isArray(options.types) || !options.types.every(angular.isString);
if (shouldThrow) {
throw getError(`Attempted to create a template wrapper with types that is not a string or an array of strings`);
}
}
function checkOverwrite(property, object, newValue, objectName) {
if (object.hasOwnProperty(property)) {
warn('overwriting-types-or-wrappers', [
`Attempting to overwrite ${property} on ${objectName} which is currently`,
`${JSON.stringify(object[property])} with ${JSON.stringify(newValue)}`,
`To supress this warning, specify the property "overwriteOk: true"`
].join(' '));
}
}
function getWrapper(name) {
return templateWrappersMap[name || defaultWrapperName];
}
function getWrapperByType(type) {
/* eslint prefer-const:0 */
const wrappers = [];
for (let name in templateWrappersMap) {
if (templateWrappersMap.hasOwnProperty(name)) {
if (templateWrappersMap[name].types && templateWrappersMap[name].types.indexOf(type) !== -1) {
wrappers.push(templateWrappersMap[name]);
}
}
}
return wrappers;
}
function removeWrapperByName(name) {
const wrapper = templateWrappersMap[name];
delete templateWrappersMap[name];
return wrapper;
}
function removeWrappersForType(type) {
const wrappers = getWrapperByType(type);
if (!wrappers) {
return undefined;
}
if (!angular.isArray(wrappers)) {
return removeWrapperByName(wrappers.name);
} else {
wrappers.forEach((wrapper) => removeWrapperByName(wrapper.name));
return wrappers;
}
}
function warn() {
if (!_this.disableWarnings && console.warn) {
/* eslint no-console:0 */
const args = Array.prototype.slice.call(arguments);
const warnInfoSlug = args.shift();
args.unshift('Formly Warning:');
args.push(`${formlyErrorAndWarningsUrlPrefix}${warnInfoSlug}`);
console.warn(...args);
}
}
}
| kentcdodds/angular-formly | src/providers/formlyConfig.js | JavaScript | mit | 8,628 |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { HomeComponent as Home } from '../components';
import { ProtectedContainer } from '.';
class HomeContainer extends Component {
render () {
return (
<ProtectedContainer>
<Home user={this.props.user} />
</ProtectedContainer>
);
}
}
HomeContainer.navigationOptions = {
title: 'Home',
drawerLabel: 'Home'
};
export default connect(
state => ({
user: state.user
})
)(HomeContainer);
| advantys/workflowgen-templates | integration/azure/authentication/azure-v1/auth-code-pkce/WorkflowGenExample/containers/HomeContainer.js | JavaScript | mit | 515 |
// generated by Neptune Namespaces v4.x.x
// file: Art/Engine/Elements/ShapeChildren/index.js
(module.exports = require('./namespace'))
.addModules({
FillElement: require('./FillElement'),
OutlineElement: require('./OutlineElement')
}); | art-suite/art-engine | source/Art/Engine/Elements/ShapeChildren/index.js | JavaScript | mit | 245 |
module.exports = {
transform: {
'^.+\\.(t|j)sx?$': 'ts-jest'
},
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$',
moduleFileExtensions: [
'ts',
'tsx',
'js',
'jsx',
'json',
'node'
],
globals: {
'ts-jest': {
tsConfig: {
jsx: 'react'
}
}
}
}
| KeitIG/react-keybinding-component | jest.config.js | JavaScript | mit | 323 |
'use strict';
// Setting up route
angular.module('users').config(['$stateProvider',
function ($stateProvider) {
// Users state routing
$stateProvider
.state('settings', {
abstract: true,
url: '/settings',
templateUrl: 'modules/users/client/views/settings/settings.client.view.html',
data: {
roles: ['user', 'admin']
}
})
.state('settings.profile', {
url: '/profile',
templateUrl: 'modules/users/client/views/settings/edit-profile.client.view.html'
})
.state('settings.password', {
url: '/password',
templateUrl: 'modules/users/client/views/settings/change-password.client.view.html'
})
.state('settings.accounts', {
url: '/accounts',
templateUrl: 'modules/users/client/views/settings/manage-social-accounts.client.view.html'
})
.state('settings.picture', {
url: '/picture',
templateUrl: 'modules/users/client/views/settings/change-profile-picture.client.view.html'
})
.state('authentication', {
abstract: true,
url: '/authentication',
templateUrl: 'modules/users/client/views/authentication/authentication.client.view.html'
//templateUrl: 'modules/core/client/views/home.client.view.html'
})
.state('authentication.signup', {
url: '/',
templateUrl: 'modules/users/client/views/authentication/signup.client.view.html'
//templateUrl: 'modules/core/client/views/home.client.view.html'
})
.state('authentication.signin', {
url: '/signin?err',
templateUrl: 'modules/core/client/views/home.client.view.html'
//templateUrl: 'modules/users/client/views/authentication/signin.client.view.html'
})
.state('password', {
abstract: true,
url: '/password',
template: '<ui-view/>'
})
.state('password.forgot', {
url: '/forgot',
templateUrl: 'modules/users/client/views/password/forgot-password.client.view.html'
})
.state('password.reset', {
abstract: true,
url: '/reset',
template: '<ui-view/>'
})
.state('password.reset.invalid', {
url: '/invalid',
templateUrl: 'modules/users/client/views/password/reset-password-invalid.client.view.html'
})
.state('password.reset.success', {
url: '/success',
templateUrl: 'modules/users/client/views/password/reset-password-success.client.view.html'
})
.state('password.reset.form', {
url: '/:token',
templateUrl: 'modules/users/client/views/password/reset-password.client.view.html'
});
}
]);
| dpxxdp/segue4 | modules/users/client/config/users.client.routes.js | JavaScript | mit | 2,704 |
import test from 'tape'
import lerp from './'
test('snap-lerp', t => {
t.equal(lerp(1, 3, 0.5, 0.01), 2)
t.equal(lerp(1, 3, 0.5, 2, false), 3)
t.equal(lerp(1, 3, 0.5, 2, true), 3)
t.equal(lerp(3, 1, 0.5, 0.01), 2)
t.equal(lerp(3, 1, 0.5, 2, false), 1)
t.equal(lerp(3, 1, 0.5, 2, true), 1)
t.equal(lerp(1, 3, 0.6, 1), 2.2)
t.equal(lerp(3, 1, 0.6, 1), 1.8)
t.equal(lerp(1, 3, 0.4, 1), 1.8)
t.equal(lerp(3, 1, 0.4, 1), 2.2)
t.equal(lerp(1, 3, 0.6, 2, false), 3)
t.equal(lerp(1, 3, 0.6, 2, true), 3)
t.equal(lerp(3, 1, 0.6, 2, false), 1)
t.equal(lerp(3, 1, 0.6, 2, true), 1)
t.equal(lerp(1, 3, 0.4, 2, false), 1)
t.equal(lerp(1, 3, 0.4, 2, true), 3)
t.equal(lerp(3, 1, 0.4, 2, false), 3)
t.equal(lerp(3, 1, 0.4, 2, true), 1)
t.equal(lerp(1, 3, 0.6, 2), 3)
t.equal(lerp(3, 1, 0.6, 2), 1)
t.equal(lerp(1, 3, 0.4, 2), 1)
t.equal(lerp(3, 1, 0.4, 2), 3)
t.equal(lerp(10, 20, 0.5, 1), 15)
t.equal(lerp(10, 20, 0.5, 10), 20)
t.equal(lerp(10, 20, 0.4, 10), 10)
t.end()
})
| hughsk/snap-lerp | test.js | JavaScript | mit | 1,018 |
var raf = require('raf');
var createCaption = require('vendors/caption');
var glslify = require('glslify');
var windowSize = new THREE.Vector2(window.innerWidth, window.innerHeight);
var SwapRenderer = require('vendors/swapRenderer'), swapRenderer;
var velocityRenderer, pressureRenderer;
var Solver = require('./fluid/solver');
var solver;
var scene, camera, renderer;
var object, id;
var stats, wrapper;
var mouse = new THREE.Vector2(-9999, -9999);
var isAnimation = true;
var orthShaderMaterial;
var orthScene, orthCamera, orthPlane;
var renderPlane, renderMaterial;
var renderScene, renderCamera;
var clock;
var grid = {
size : new THREE.Vector2(window.innerWidth/4, window.innerHeight/4),
scale : 1
};
var time = {
step : 1
};
var outputRenderer;
function init(){
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.z = 200;
renderer = new THREE.WebGLRenderer({alpha: true});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
solver = Solver.make(grid, time, windowSize, renderer)
outputRenderer = new SwapRenderer({
width : grid.size.width, height : grid.size.height,
renderer : renderer
});
setComponent();
raf(animate);
}
function setComponent(){
var title = 'Swap Rendering with the texture of random color';
var caption = 'Swap rendering with the texture of random color.';
var url = 'https://github.com/kenjiSpecial/webgl-sketch-dojo/tree/master/sketches/theme/swap-renderer/app00';
wrapper = createCaption(title, caption, url);
wrapper.style.position = "absolute";
wrapper.style.top = '50px';
wrapper.style.left = '30px';
stats = new Stats();
stats.setMode( 0 ); // 0: fps, 1: ms, 2: mb
// align top-left
stats.domElement.style.position = 'absolute';
stats.domElement.style.bottom = '30px';
stats.domElement.style.left = '30px';
stats.domElement.style.zIndex= 9999;
document.body.appendChild( stats.domElement );
}
function animate() {
/** --------------------- **/
renderScene = new THREE.Scene();
renderCamera = new THREE.OrthographicCamera( -window.innerWidth/2, window.innerWidth/2, -window.innerHeight/2, window.innerHeight/2, -10000, 10000 );
console.log(solver.density.output);
renderMaterial = new THREE.ShaderMaterial({
depthTest : false,
side : THREE.DoubleSide,
uniforms : {
"tDiffuse" : {type: "t", value: solver.velocity.output }
},
vertexShader : glslify('./display/shader.vert'),
fragmentShader : glslify('./display/shader.frag')
});
renderPlane = new THREE.Mesh(
new THREE.PlaneBufferGeometry(window.innerWidth, window.innerHeight),
renderMaterial
);
renderScene.add(renderPlane);
clock = new THREE.Clock();
clock.start();
id = raf(loop);
//
}
function loop(){
stats.begin();
var dt = clock.getDelta();
solver.step(mouse);
renderer.render(renderScene, renderCamera);
stats.end();
id=raf(loop);
}
window.addEventListener('click', function(ev){
// renderer.render(scene, camera, swapRenderer.target);
});
window.addEventListener('keydown', function(ev){
if(ev.keyCode == 27){
if(isAnimation) raf.cancel(id);
else id = raf(animate);
isAnimation = !isAnimation;
}
});
window.addEventListener('mousemove', function(ev){
mouse.x = ev.clientX;
mouse.y = ev.clientY;
// swapRenderer.uniforms.uMouse.value = mouse;
});
init(); | kenjiSpecial/webgl-sketch-dojo | sketches/theme/fluid/app00temp01/app.js | JavaScript | mit | 3,670 |
module.exports = function() {
return {
connectionString : "mongodb://127.0.0.1:27017/mongolayer"
}
} | simpleviewinc/mongolayer | testing/config.js | JavaScript | mit | 108 |
'use strict';
const clone = require('../helpers/clone');
class SaveOptions {
constructor(obj) {
if (obj == null) {
return;
}
Object.assign(this, clone(obj));
}
}
module.exports = SaveOptions; | aguerny/LacquerTracker | node_modules/mongoose/lib/options/saveOptions.js | JavaScript | mit | 216 |
import React from 'react';
import ShiftKey from './ShiftKey';
import 'scss/vigenere.scss';
export default class VigenereKeys extends React.Component {
constructor(props) {
super(props);
this.state = {
keyword: ''
};
this.keywordHandler = this.keywordHandler.bind(this);
}
keywordHandler(event) {
this.setState({
keyword: event.target.value
})
}
render() {
const {
characters
} = this.props;
const charactersArray = characters.split('');
let {
keyword
} = this.state;
keyword = keyword.toUpperCase();
return (
<div>
<input type='text'
value={keyword}
onChange={this.keywordHandler}
placeholder='Keyword' />
<div className='shift-keys'>
{
keyword.split('').map((char, index) => (
<div key={index} className='vigenere-char'>
<p>{index}</p>
<ShiftKey
characters={charactersArray}
noControls
initialShift={charactersArray.indexOf(char)} />
</div>
))
}
</div>
</div>
);
}
}
export const EnglishVigenereKeys = props => (
<VigenereKeys characters='ABCDEFGHIJKLMNOPQRSTUVWXYZ' />
);
| pshrmn/cryptonite | src/components/tools/VigenereKeys.js | JavaScript | mit | 1,314 |
/*
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/configuration
*/
module.exports = {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "/private/var/folders/n6/2v5277g578510lpgbl7zbf6r0000gn/T/jest_dx",
// Automatically clear mock calls and instances between every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,
// The directory where Jest should output its coverage files
coverageDirectory: 'coverage',
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: 'v8',
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "jsx",
// "ts",
// "tsx",
// "json",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state between every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state between every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
// testEnvironment: "jest-environment-node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "/node_modules/"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
// testURL: "http://localhost",
// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
// timers: "real",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/",
// "\\.pnp\\.[^\\/]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
| C2FO/gofigure | jest.config.js | JavaScript | mit | 6,865 |
'use strict';
import UserNotificationConstants from '../constants/UserNotificationConstants';
import UserNotificationService from '../services/UserNotificationService';
const _initiateRequest = (type, data) => {
return {
'type': type,
'data': data
};
};
const _returnResponse = (type, data) => {
return {
'type': type,
'data': data,
'receivedAt': Date.now()
};
};
export default {
getByUserId: (id) => {
return (dispatch) => {
dispatch(_initiateRequest(UserNotificationConstants.INITIATE_USER_NOTIFICATION_REQUEST));
return UserNotificationService.getByUserId(criteria).then((response) => {
dispatch(_returnResponse(UserNotificationConstants.GET_USER_NOTIFICATIONS, response.results));
return response.pagination;
});
};
},
search: (criteria) => {
return (dispatch) => {
dispatch(_initiateRequest(UserNotificationConstants.INITIATE_USER_NOTIFICATION_REQUEST));
return UserNotificationService.search(criteria).then((response) => {
dispatch(_returnResponse(UserNotificationConstants.GET_USER_NOTIFICATIONS, response.results));
return response.pagination;
});
};
},
create: (data) => {
return (dispatch) => {
dispatch(_initiateRequest(UserNotificationConstants.INITIATE_USER_NOTIFICATION_REQUEST));
return UserNotificationService.create(data).then((userNotification) => {
dispatch(_returnResponse(UserNotificationConstants.CREATE_USER_NOTIFICATION, userNotification));
return userNotification;
});
};
},
update: (id, data) => {
return (dispatch) => {
dispatch(_initiateRequest(UserNotificationConstants.INITIATE_USER_NOTIFICATION_REQUEST));
return UserNotificationService.update(id, data).then((userNotification) => {
dispatch(_returnResponse(UserNotificationConstants.UPDATE_USER_NOTIFICATION, userNotification));
return userNotification;
});
};
},
remove: (id) => {
return (dispatch) => {
dispatch(_initiateRequest(UserNotificationConstants.INITIATE_USER_NOTIFICATION_REQUEST, id));
return UserNotificationService.remove(id).then((response) => {
dispatch(_returnResponse(UserNotificationConstants.REMOVE_USER_NOTIFICATION, id));
return response;
});
};
}
};
| zdizzle6717/battle-comm | src/actions/UserNotificationActions.js | JavaScript | mit | 2,189 |
/*jshint node: true, eqnull: true*/
exports.purge = require('./lib/purge').AkamaiPurge; | patrickkettner/grunt-akamai-clear | node_modules/akamai/akamai.js | JavaScript | mit | 88 |
() => {
const [startDate, setStartDate] = useState(new Date());
let handleColor = (time) => {
return time.getHours() > 12 ? "text-success" : "text-error";
};
return (
<DatePicker
showTimeSelect
selected={startDate}
onChange={(date) => setStartDate(date)}
timeClassName={handleColor}
/>
);
};
| Hacker0x01/react-datepicker | docs-site/src/examples/customTimeClassName.js | JavaScript | mit | 340 |
'use strict';
var arg = require('../util').arg;
var oneDHeightmapFactory = require('../1d-heightmap');
var rng = require('../rng');
var random = rng.float;
var randomRange = rng.range;
var randomRangeInt = rng.rangeInt;
var randomSpacedIndexes = rng.spacedIndexes;
var interpolators = require('../interpolators');
var math = require('../math');
var getDistance = math.getDistance;
var getNormalizedVector = math.getNormalizedVector;
module.exports = {
keyIndexes: createKeyIndexes,
fromKeyIndexes: fromKeyIndexes,
interpolateKeyIndexes: interpolateKeyIndexes,
addKeyIndexes: addKeyIndexes,
addDisplacementKeyIndexes: addDisplacementKeyIndexes,
}
function createKeyIndexes(settings) {
var defaults = {
length: null,
startHeight: undefined,
endHeight: undefined,
minSpacing: undefined,
maxSpacing: undefined,
interpolator: null,
min: 0,
max: 100,
minSlope: undefined,
maxSlope: undefined,
};
var s = Object.assign({}, defaults, settings);
var length = s.length;
var startHeight = s.startHeight;
var endHeight = s.endHeight;
var minSpacing = arg(s.minSpacing, length * 0.1);
var maxSpacing = arg(s.maxSpacing, length * 0.1);
var minHeight = s.min;
var maxHeight = s.max;
var minSlope = s.minSlope;
var maxSlope = s.maxSlope;
var keyIndexes = randomSpacedIndexes(length, minSpacing, maxSpacing);
var prev;
var out = keyIndexes.map(function(index, i, data) {
var value;
if (i === 0 && startHeight !== undefined) {
value = startHeight;
} else {
value = getValue(prev, index, minHeight, maxHeight, minSlope, maxSlope);
}
var result = {
index: index,
value: value,
};
prev = result;
return result;
});
if (endHeight !== undefined) {
out[out.length - 1].value = endHeight;
}
return out;
}
function getValue(prev, index, minHeight, maxHeight, minSlope, maxSlope) {
var min = minHeight;
var max = maxHeight;
if (prev !== undefined) {
var prevVal = prev.value;
var distance = index - prev.index;
if (minSlope !== undefined) {
min = Math.max(min, prevVal + (distance * minSlope));
}
if (maxSlope !== undefined) {
max = Math.min(max, prevVal + (distance * maxSlope));
}
}
return randomRangeInt(min, max);
}
function interpolateKeyIndexes(keyIndexes, interpolator) {
var results = [];
interpolator = arg(interpolator, interpolators.linear);
keyIndexes.forEach(function(item, i) {
results.push(item.value);
var next = keyIndexes[i + 1];
if (!next) {
return;
}
var curerntKeyIndex = item.index;
var nextKeyIndex = next.index;
var wavelength = Math.abs(nextKeyIndex - curerntKeyIndex - 1);
var a = item.value;
var b = next.value;
for (var j = 0; j < wavelength; j++) {
var x = j / wavelength;
var interpolatedVal = interpolator(a, b, x);
results.push(interpolatedVal);
}
});
return results;
}
function fromKeyIndexes(keyIndexes, interpolator) {
return oneDHeightmapFactory({
data: this.interpolateKeyIndexes(keyIndexes, interpolator)
});
}
function addKeyIndexes(settings) {
var defaults = {
keyIndexes: null,
// position on line determined by percent of distance between points
posRatioMin: 0.33,
posRatioMax: 0.66,
// distance from pos on line determined by percent of distance between points
distRatioMin: 0.1,
distRatioMax: 0.2,
// absolute min / max distance
distMin: undefined,
distMax: undefined,
direction: undefined,
upDirection: undefined,
downDirection: undefined,
upPosRatioMin: undefined,
upPosRatioMax: undefined,
downPosRatioMin: undefined,
downPosRatioMax: undefined,
upDistRatioMin: undefined,
upDistRatioMax: undefined,
downDistRatioMin: undefined,
downDistRatioMax: undefined,
};
var s = Object.assign({}, defaults, settings);
var keyIndexes = s.keyIndexes;
var result = [];
keyIndexes.forEach(function(item, i, data) {
var next = data[i + 1];
if (!next) {
result.push(item);
return;
}
var splitSettings = Object.assign({
left: item,
right: next,
}, settings);
var add = splitKeyIndexes(splitSettings);
result.push(item);
result.push(add);
});
return result;
}
function splitKeyIndexes(settings) {
var defaults = {
left: null,
right: null,
// position on line determined by percent of distance between points
posRatioMin: 0.33,
posRatioMax: 0.66,
// distance from pos on line determined by percent of distance between points
distRatioMin: 0.1,
distRatioMax: 0.2,
// absolute min / max distance
distMin: undefined,
distMax: undefined,
direction: undefined,
upDirection: undefined,
downDirection: undefined,
upPosRatioMin: undefined,
upPosRatioMax: undefined,
downPosRatioMin: undefined,
downPosRatioMax: undefined,
upDistRatioMin: undefined,
upDistRatioMax: undefined,
downDistRatioMin: undefined,
downDistRatioMax: undefined,
};
var s = Object.assign({}, defaults, settings);
var left = s.left;
var right = s.right;
var slopeUp = left.value < right.value;
var posRatioMin = s.posRatioMin;
var posRatioMax = s.posRatioMax;
var distRatioMin = s.distRatioMin;
var distRatioMax = s.distRatioMax;
var direction = s.direction;
var distMin = s.distMin;
var distMax = s.distMax;
if (slopeUp) {
posRatioMin = arg(s.upPosRatioMin, posRatioMin);
posRatioMax = arg(s.upPosRatioMax, posRatioMax);
distRatioMin = arg(s.upDistRatioMin, distRatioMin);
distRatioMax = arg(s.upDistRatioMax, distRatioMax);
direction = arg(s.upDirection, direction);
} else {
posRatioMin = arg(s.downPosRatioMin, posRatioMin);
posRatioMax = arg(s.downPosRatioMax, posRatioMax);
distRatioMin = arg(s.downDistRatioMin, distRatioMin);
distRatioMax = arg(s.downDistRatioMax, distRatioMax);
direction = arg(s.downDirection, direction);
}
direction = arg(direction, random() < 0.5 ? 'up' : 'down');
var posRatio = randomRange(posRatioMin, posRatioMax);
var distRatio = randomRange(distRatioMin, distRatioMax);
var a = {
x: left.index,
y: left.value,
};
var b = {
x: right.index,
y: right.value,
};
var p = generateMidPoint(a, b, posRatio, distRatio, direction, distMin, distMax);
return {
value: p.y,
index: p.x
};
}
function generateMidPoint(a, b, cPosRatio, distRatio, direction, distMin, distMax) {
var vDist = getDistance(a, b);
var v = getNormalizedVector(a, b, vDist);
var dx = b.x - a.x;
var dy = b.y - a.y;
// c is a point on line ab at given ratio
var c = {
x: (dx * cPosRatio),
y: (dy * cPosRatio)
};
// distance proportional to ab length
var dist = vDist * distRatio;
if (distMin !== undefined) {
dist = Math.max(distMin);
}
if (distMax !== undefined) {
dist = Math.min(distMax);
}
var vDir = vectorRotate90(v, direction);
var d = {
x: vDir.x * dist,
y: vDir.y * dist,
};
// width of line ab
var ab = dx;
// postion of d offset from c
var dC = c.x + d.x;
// scale to fit horizontal bounds of ab
var scale = false;
// d left of a
if (dC < 0) {
scale = -(c.x / d.x);
}
// d right of b
else if (dC > ab) {
scale = (dx - c.x) / (d.x);
}
if (scale !== false) {
d.x *= scale;
d.y *= scale;
}
// add offsets to d
d.x += c.x + a.x;
d.y += c.y + a.y;
d.x = Math.round(d.x);
if (d.x === a.x) {
d.x += 1;
}
if (d.x === b.x) {
d.x -= 1;
}
// set c offset for debug
// c.x += a.x;
// c.y += a.y;
return d;
}
function vectorRotate90(v, direction){
if (direction === 'left' || direction === 'up') {
return {
x: -v.y,
y: v.x,
}
}
else if (direction === 'right' || direction === 'down') {
return {
x: v.y,
y: -v.x,
}
}
}
function addDisplacementKeyIndexes(settings) {
var defaults = {
keyIndexes: null,
startingDisplacement: 50,
roughness: 0.77,
maxIterations: 1,
calcDisplacement: defaultCalcDisplacement,
};
var s = Object.assign({}, defaults, settings);
var keyIndexes = s.keyIndexes;
var roughness = s.roughness;
var maxIterations = s.maxIterations;
var calcDisplacement = s.calcDisplacement;
var startingDisplacement = s.startingDisplacement;
keyIndexes = keyIndexes.map(function(item) {
return Object.assign({}, item);
});
var results = [];
keyIndexes.forEach(function(item, i, data) {
var next = data[i + 1];
if (!next) {
results.push(item);
return;
}
var arr = split(item, next, startingDisplacement);
results = results.concat(item, arr);
});
return results;
function defaultCalcDisplacement(current, left, right, iteration) {
if (iteration == 1) {
return current;
}
return current * roughness;
}
function split(left, right, displacement, iteration) {
iteration = iteration || 0;
iteration++;
if (left.index + 1 == right.index) {
return false;
}
displacement = calcDisplacement(displacement, left, right, iteration);
var mid = splitNodes(left, right, displacement);
if (iteration >= maxIterations) {
return mid;
}
var result = [];
var canSplitLeft = left.index + 1 !== mid.index;
var canSplitRight = right.index - 1 !== mid.index;
if (canSplitLeft) {
var leftSplit = split(left, mid, displacement, iteration);
if (leftSplit) {
result = result.concat(leftSplit);
}
}
result.push(mid);
if (canSplitRight) {
var rightSplit = split(mid, right, displacement, iteration);
if (rightSplit) {
result = result.concat(rightSplit);
}
}
return result;
}
}
function splitNodes(left, right, displacement) {
var midIndex = Math.floor((left.index + right.index) * 0.5);
var midValue = (left.value + right.value) * 0.5;
var adjustment = (randomRange(-1, 1) * displacement);
return {
index: midIndex,
value: midValue + adjustment,
};
} | unstoppablecarl/1d-heightmap | src/key-indexes/index.js | JavaScript | mit | 11,619 |
'use strict';
/**
* practice Node.js project
*
* @author Huiming Hou <[email protected]>
*/
import mongoose from 'mongoose';
module.exports = function(done){
const debug = $.createDebug('init:mongodb');
debug('connecting to MongoDB...');
const conn = mongoose.createConnection($.config.get('db.mongodb'));
$.mongodb = conn;
$.model = {};
const ObjectId = mongoose.Types.ObjectId;
$.utils.ObjectId = ObjectId;
done();
};
| hhmpro/node-practice-project | src/init/mongodb.js | JavaScript | mit | 450 |
var request = require('request'),
Q = require('q'),
xml2js = require('xml2js'),
_ = require('lodash');
module.exports = {
/**
* Helper function that handles the http request
*
* @param {string} url
*/
httprequest: function(url) {
var deferred = Q.defer();
request(url, function(err, response, body) {
if (err) {
deferred.reject(new Error(err));
} else if (!err && response.statusCode !== 200) {
deferred.reject(new Error(response.statusCode));
} else {
deferred.resolve(body);
}
});
return deferred.promise;
},
/**
* Helper function that converts xml to json
*
* @param {xml} xml
*/
toJson: function(xml) {
var deferred = Q.defer();
xml2js.parseString(xml, function(err, result) {
if (err) {
deferred.reject(new Error(err));
} else {
deferred.resolve(result);
}
});
return deferred.promise;
},
/**
* Helper function that takes params hash and converts it into query string
*
* @param {object} params
* @param {Number} id
*/
toQueryString: function(params, id) {
var paramsString = '';
for (var key in params) {
if (params.hasOwnProperty(key)) {
paramsString += '&' + key + '=' + encodeURIComponent(params[key]);
}
}
return 'zws-id=' + id + paramsString;
},
/**
* Helper function that checks for the required params
*
* @param {object} params
* @param {array} reqParams -- required parameters
*/
checkParams: function(params, reqParams) {
if ( reqParams.length < 1 ) return;
if ( (_.isEmpty(params) || !params) && (reqParams.length > 0) ){
throw new Error('Missing parameters: ' + reqParams.join(', '));
}
var paramsKeys = _.keys(params);
_.each(reqParams, function(reqParam) {
if ( paramsKeys.indexOf(reqParam) === -1 ) {
throw new Error('Missing parameter: ' + reqParam);
}
});
}
};
| LoganArnett/node-zillow | lib/helpers.js | JavaScript | mit | 1,998 |
var closet = closet || {};
(function($) {
closet.folders = (function() {
var iconPlus = '<img class="icon" style="width:10px" src="/static/image/16x16/Plus.png"/>';
var iconMinus = '<img class="icon" style="width:10px" src="/static/image/16x16/Minus.png"/>';
var iconEmpty = '<img class="icon" style="width:10px" src="/static/image/16x16/Folder3.png"/>';
var toggle = function($root) {
var $children = $root.children('div.children');
var $toggle = $root.children('a.toggle');
if ($children.css('display') === 'none') {
$children.css('display', '');
$toggle.html(iconMinus);
} else {
$children.css('display', 'none');
$toggle.html(iconPlus);
}
};
var addFolders = function($root, depth, cb) {
var root = $root.data('path');
var $children = $root.children('div.children');
toggle($root);
var url = '/pcaps/1/list?by=path';
if (depth > 1) {
var paths = root.split('/');
var startkey = paths.concat([0]);
var endkey = paths.concat([{}]);
url += '&startkey=' + JSON.stringify(startkey);
url += '&endkey=' + JSON.stringify(endkey);
}
$.ajax({
url: url,
data: { group_level: depth, limit: 20 },
dataType: 'json',
success: function(kvs) {
if (kvs.rows.length === 0 && depth > 1) {
$root.find('a.toggle').replaceWith(iconEmpty);
return;
}
$.each(kvs.rows, function(_, kv) {
if (kv.key.length !== depth) { return; }
var path = kv.key.join('/');
$children.append(
'<div class="folder">' +
'<a class="toggle"/> ' +
'<a class="link" title="' + path + '">' + kv.key[depth-1] + '</a>' +
' ' +
'<sup style="font-size:smaller">' + kv.value + '</sup>' +
'<div class="children" style="margin-left:20px;display:none"/>' +
'</div>'
).find('div.folder:last').data('path', path);
});
$children
.find('a.toggle').attr('href', 'javascript:void(0)')
.html('<img class="icon" style="width:10px" src="/static/image/16x16/Plus.png"/>')
.click(function() {
var folder = $(this).parent('div.folder');
var children = $(this).nextAll('div.children');
if (children.children().length === 0) {
addFolders(folder, depth+1, cb);
} else {
toggle(folder);
}
})
.end()
.find('a.link').attr('href', 'javascript:void(0)')
.click(function() {
cb($(this).parent('div.folder').data('path'));
});
}
});
};
return {
manage: function($root, cb) {
var $f = $root.data('folders');
if (!$f) {
$f = $('<div class="folder" style="margin-top: 20px;margin-bottom:20px"><div class="children" style="display:none"/></div>');
$f.data('path', '/');
$root.data('folders', $f);
addFolders($f, 1, cb);
}
$root.empty().append($f);
}
};
}());
}(jQuery));
| mudynamics/pcapr-local | lib/pcapr_local/www/static/script/closet/closet.folders.js | JavaScript | mit | 3,861 |
define(function(require) {
var $ = require('jquery');
var Point = require('joss/geometry/Point');
var _scrollIsRelative = !($.browser.opera || $.browser.safari && $.browser.version < "532");
/**
* Returns a DOM element lying at a point
*
* @param {joss/geometry/Point} p
* @return {Element}
*/
var fromPoint = function(x, y) {
if(!document.elementFromPoint) {
return null;
}
var p;
if (x.constructor === Point) {
p = x;
}
else {
p = new Point(x, y);
}
if(_scrollIsRelative)
{
p.x -= $(document).scrollLeft();
p.y -= $(document).scrollTop();
}
return document.elementFromPoint(p.x, p.y);
};
return fromPoint;
});
| zship/joss | src/joss/util/elements/fromPoint.js | JavaScript | mit | 681 |
import gulp from 'gulp';
import runSequence from 'run-sequence';
gulp.task('dev', ['clean'], function(cb) {
global.isProd = false;
runSequence(['styles', 'images', 'fonts', 'views','vendor'], 'browserify', 'watch', cb);
});
| tungptvn/tungpts-ng-blog | gulp/tasks/development.js | JavaScript | mit | 239 |
/**
*
* @type {*}
* @private
*/
jDoc.Engines.RTF.prototype._specialControlWords = [
"chpgn",
"chftn",
"chdate",
"chtime",
"chatn",
"chftnsep",
"/",
":",
"*",
"~",
"-",
"_",
"'hh",
"page",
"line",
"раr",
"sect",
"tab",
"сеll",
"row",
"colortbl",
"fonttbl",
"stylesheet",
"pict"
]; | pavel-voronin/jDoc | js/engines/RTF/reader/private/_specialControlWords.js | JavaScript | mit | 383 |
export default function album() {
return {
getAlbum: id => this.request(`${this.apiURL}/albums/${id}`),
getAlbums: ids => this.request(`${this.apiURL}/albums/?ids=${ids}`),
getTracks: id => this.request(`${this.apiURL}/albums/${id}/tracks`),
};
}
| dtfialho/js-tdd-course | module-06/src/album.js | JavaScript | mit | 263 |
function airPollution(sofiaMap, forces) {
for (let i = 0; i < sofiaMap.length; i++) {
sofiaMap[i] = sofiaMap[i].split(' ').map(Number)
}
for (let i = 0; i < forces.length; i++) {
forces[i] = forces[i].split(' ')
}
for (let i = 0; i < forces.length; i++) {
for (let k = 0; k < sofiaMap.length; k++) {
for (let l = 0; l < sofiaMap[k].length; l++) {
if (forces[i][0] === 'breeze') {
if (Number(forces[i][1]) === k) {
sofiaMap[k][l] = sofiaMap[k][l] - 15
if (sofiaMap[k][l] < 0) {
sofiaMap[k][l] = 0
}
}
} else if (forces[i][0] === 'gale') {
if (Number(forces[i][1]) === l) {
sofiaMap[k][l] = sofiaMap[k][l] - 20
if (sofiaMap[k][l] < 0) {
sofiaMap[k][l] = 0
}
}
} else if (forces[i][0] === 'smog') {
sofiaMap[k][l] = sofiaMap[k][l] + Number(forces[i][1])
}
}
}
}
let isPolluted = false
let result = []
let k = 0
for (let i = 0; i < sofiaMap.length; i++) {
for (let j = 0; j < sofiaMap[i].length; j++) {
if (sofiaMap[i][j] >= 50) {
if (!isPolluted) {
isPolluted = true
}
result[k++] = `[${i}-${j}]`
}
}
}
if (!isPolluted) {
console.log('No polluted areas')
} else {
console.log('Polluted areas: ' + result.join(', '))
}
}
airPollution([
"5 7 72 14 4",
"41 35 37 27 33",
"23 16 27 42 12",
"2 20 28 39 14",
"16 34 31 10 24",
],
["breeze 1", "gale 2", "smog 25"])
// Polluted areas: [0-2], [1-0], [2-3], [3-3], [4-1]
| b0jko3/SoftUni | JavaScript/Core/Fundamentals/Exams/11_Feb_2018/02._Air_Pollution.js | JavaScript | mit | 1,937 |
"use strict";
exports.default = {
type: "html",
url: "http://www.xnview.com/en/xnviewmp/",
getVersion: function($) {
return $("#downloads p")
.contains("Download")
.find("strong")
.version("XnView MP @version");
}
};
| foxable/app-manager | storage/apps/xnview-mp/versionProvider.js | JavaScript | mit | 277 |
///////////////////////////////////////////////////////////////////////////
// Copyright © Esri. All Rights Reserved.
//
// Licensed under the Apache License Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////////
define({
"_widgetLabel": "Yapı Taslağı Oluşturucu",
"newTraverseButtonLabel": "Yeni Çapraz Çizgi Başlat",
"invalidConfigMsg": "Geçersiz Yapılandırma",
"geometryServiceURLNotFoundMSG": "Geometri Servisi URL’si alınamıyor",
"editTraverseButtonLabel": "Çapraz Çizgiyi Düzenle",
"mapTooltipForStartNewTraverse": "Başlamak için haritada bir nokta seçin veya aşağıya girin",
"mapTooltipForEditNewTraverse": "Düzenlenecek yapıyı seçin",
"mapTooltipForUpdateStartPoint": "Başlangıç noktasını güncellemek için tıklayın",
"mapTooltipForScreenDigitization": "Yapı noktası eklemek için tıklayın",
"mapTooltipForUpdatingRotaionPoint": "Döndürme noktasını güncellemek için tıklayın",
"mapTooltipForRotate": "Döndürmek için sürükleyin",
"mapTooltipForScale": "Ölçeklendirmek için sürükleyin",
"backButtonTooltip": "Geri",
"newTraverseTitle": "Yeni Çapraz Çizgi",
"editTraverseTitle": "Çapraz Çizgiyi Düzenle",
"clearingDataConfirmationMessage": "Değişiklikler atılacak, devam etmek istiyor musunuz?",
"unableToFetchParcelMessage": "Yapı alınamıyor.",
"unableToFetchParcelLinesMessage": "Yapı çizgileri alınamıyor.",
"planSettings": {
"planSettingsTitle": "Ayarlar",
"directionOrAngleTypeLabel": "Yön veya Açı Türü",
"directionOrAngleUnitsLabel": "Yön veya Açı Birimi",
"distanceAndLengthUnitsLabel": "Mesafe ve Uzunluk Birimleri",
"areaUnitsLabel": "Alan Birimleri:",
"circularCurveParameters": "Dairesel Eğri Parametreleri",
"northAzimuth": "Kuzey Azimut",
"southAzimuth": "Güney Azimut",
"quadrantBearing": "Çeyrek Semt Açısı",
"radiusAndChordLength": "Yarıçap ve Kiriş Uzunluğu",
"radiusAndArcLength": "Yarıçap ve Yay Uzunluğu",
"expandGridTooltipText": "Kılavuzu genişlet",
"collapseGridTooltipText": "Kılavuzu daralt",
"zoomToLocationTooltipText": "Konuma yaklaştır",
"onScreenDigitizationTooltipText": "Sayısallaştırma",
"updateRotationPointTooltipText": "Döndürme noktasını güncelle"
},
"traverseSettings": {
"bearingLabel": "Yön",
"lengthLabel": "Uzunluk",
"radiusLabel": "Yarıçap",
"noMiscloseCalculated": "Kapanmama hesaplanamadı",
"traverseMiscloseBearing": "Kapanmama Yönü",
"traverseAccuracy": "Doğruluk",
"accuracyHigh": "Yüksek",
"traverseDistance": "Kapanmama Mesafesi",
"traverseMiscloseRatio": "Kapanmama Oranı",
"traverseStatedArea": "Belirtilen Alan",
"traverseCalculatedArea": "Hesaplanan Alan",
"addButtonTitle": "Ekle",
"deleteButtonTitle": "Kaldır"
},
"parcelTools": {
"rotationToolLabel": "Açı",
"scaleToolLabel": "Ölçek"
},
"newTraverse": {
"invalidBearingMessage": "Geçersiz Yön.",
"invalidLengthMessage": "Geçersiz Uzunluk.",
"invalidRadiusMessage": "Geçersiz Yarıçap.",
"negativeLengthMessage": "Yalnızca eğriler için geçerlidir",
"enterValidValuesMessage": "Geçerli değer girin.",
"enterValidParcelInfoMessage": "Kaydedilecek geçerli yapı bilgisi girin.",
"unableToDrawLineMessage": "Çizgi çizilemiyor.",
"invalidEndPointMessage": "Geçersiz Bitiş Noktası, çizgi çizilemiyor.",
"lineTypeLabel": "Çizgi Tipi"
},
"planInfo": {
"requiredText": "(gerekli)",
"optionalText": "(isteğe bağlı)",
"parcelNamePlaceholderText": "Yapı adı",
"parcelDocumentTypeText": "Belge türü",
"planNamePlaceholderText": "Plan adı",
"cancelButtonLabel": "İptal Et",
"saveButtonLabel": "Kaydet",
"saveNonClosedParcelConfirmationMessage": "Girilen yapı kapatılmamış, yine de devam etmek ve yalnızca yapı çizgilerini kaydetmek istiyor musunuz?",
"unableToCreatePolygonParcel": "Yapı alanı oluşturulamıyor.",
"unableToSavePolygonParcel": "Yapı alanı kaydedilemiyor.",
"unableToSaveParcelLines": "Yapı çizgileri kaydedilemiyor.",
"unableToUpdateParcelLines": "Yapı çizgileri güncellenemiyor.",
"parcelSavedSuccessMessage": "Yapı başarıyla kaydedildi.",
"parcelDeletedSuccessMessage": "Parsel başarıyla silindi.",
"parcelDeleteErrorMessage": "Parselin silinmesinde hata oluştu.",
"enterValidParcelNameMessage": "Geçerli yapı adı girin.",
"enterValidPlanNameMessage": "Geçerli plan adı girin.",
"enterValidDocumentTypeMessage": "Geçersiz belge türü.",
"enterValidStatedAreaNameMessage": "Geçerli belirtilen alan girin."
},
"xyInput": {
"explanation": "Parsel katmanınızın mekansal referansında"
}
}); | tmcgee/cmv-wab-widgets | wab/2.13/widgets/ParcelDrafter/nls/tr/strings.js | JavaScript | mit | 5,323 |
/*globals $:false, _:false, Firebase:false */
'use strict';
var url = 'https://jengaship.firebaseio.com/',
fb = new Firebase(url),
gamesFb = new Firebase(url + 'games'),
games,
avaGames = [],
emptyGames = [],
myGames = [],
myBoardPositions = [],
currentGame,
$playerName = $('#playerName'),
$chosenName,
sunkShips = [];
// booleans to check if ships have been placed
// Tasks Left:
//// 1. Write Jade code which consists of a container for each type of ship,
// directing the user to place that type of ship (i.e. 2-destroyer, 3-cruiser, 3-submarine, 4-battleship, or 5-aircraft carrier)
// there should be a button in the jade to rotate the ship placement 90 degrees carried out in task 2
// unhide each container on clicking the '.myBoard' container, cycling through each
//// 2. Write javascript function that creates a gameboard array every time the user clicks the '.myBoard' container
// it should be a length 100 array of mostly 0's but replacing in the correct position a number corresponding
// to the boat that the user is currently placing (i.e. the ship container that is not hidden)
// it should end with a gameboard array of a user's complete ship placement. Push that to the correct user's gameboard on fb.
// you can use findCurrentGameId() to get the necessary fb info
//// 3. Write a javascript function that compares the gameboard of the other user stored on fb (written in step 2),
// and compares it to the user's '.theirBoard' clicked cell
//// 4. Style each type of ship div (2,3,4,5)
//// 5. Check for hit or miss and update other user's firebase gameboard with X or M.
////
// set .cell height equal to width
$(window).ready(function() {
console.log('resizing window');
var cw = $('.cell').width();
$('.cell').css({'height':cw+'px'});
});
$(window).on('resize', function() {
console.log('resizing window');
var cw = $('.cell').width();
$('.cell').css({'height':cw+'px'});
});
//populate list of available and empty games
function checkGames (callback1, callback2) {
gamesFb.once('value', function (res) {
var data = res.val();
games = _.keys(data);
_.forEach(games, function(g){
if(g !== 'undefined'){
var gUrl = new Firebase(url+'games/'+g+'/');
gUrl.once('value', function(games){
var gameValue = games.val();
if (gameValue.user1 && gameValue.user2 === '') {
avaGames = [];
avaGames.push(g);
} else if(gameValue.user1 === $chosenName){
myGames = [];
myGames.push(g);
}
callback1(avaGames);
})
} else {}
});
});
callback2(avaGames);
}
//find current game id
//this is how we can find which game the curent user is in, at any time
// It returns an array in the callback with the current game id and the current user number (i.e. 1 or 2)
// used in the cell click function
function findCurrentGameId(gamesFb, callback){
var foundGame = [];
gamesFb.once('value', function(n){
var games = n.val(),
currentUser = $chosenName;
_.forEach(games, function(m, key){
if(m.user1===currentUser){
currentGame = key;
foundGame.push([key,1]);
} else if(m.user2 === currentUser){
currentGame = key;
foundGame.push([key,2]);
}
});
callback(foundGame);
});
}
//create empty game with host user
function createEmptyGame (user1) {
var gameBoard1 = [],
gameBoard2 = [],
user1 = user1,
user2 = '';
for (var i = 0;i < 100; i++) {
gameBoard1.push(0);
gameBoard2.push(0);
}
var game = {'gameBoard1': gameBoard1, 'gameBoard2': gameBoard2, 'user1': user1, 'user2': user2, 'userTurn': 1};
return game;
}
//switches the turn of the player
function switchTurn (foundGame) {
var turnUrl = new Firebase(url + 'games/' + foundGame + '/userTurn');
turnUrl.once('value', function(user){
if (user.val() === 1) {
turnUrl.set(2)
} else {turnUrl.set(1)}
});
}
//this gameboard is taken from the local users gameboard layout, just the ship placement
//it needs to run when the user's ship placement is done
function createMyGameBoard(){
var gameboard = [],
$myBoard = $('.myBoard'),
$myBoardCells = $myBoard.find('.cell');
_.forEach($myBoardCells, function(cell){
//key: x = hit, m = miss, 2=2 hole ship, 3=3 hole ship, 4=4 hole ship, 5 = 5 hole ship, 0 = untouched
var $cell = $(cell);
if($cell.hasClass('ship2')){
gameboard.push('2');
} else if($cell.hasClass('ship3')){
gameboard.push('3');
} else if($cell.hasClass('ship4')){
gameboard.push('4');
} else if($cell.hasClass('ship5')){
gameboard.push('5');
} else {gameboard.push(0)};
});
return gameboard;
}
//this gameboard is taken from the remote users computed hitOrMissArray
//this needs to run on cell click
function appendMyGuessesGameboard(gb){
var $theirBoard = $('.theirBoard');
for(var i=0;i<gb.length-1;i++){
var $theirBoardCells = $('.theirBoard .cell:eq('+i+')');
if(gb[i] === 'x'){
$theirBoardCells.addClass('hit');
//$('.theirBoard').effect('shake');
} else if(gb[i] === 'm'){
$theirBoardCells.addClass('miss');
} else {}
}
}
function appendTheirGuessesGameboard(gb){
var $myBoard = $('.myBoard');
for(var i=0;i<gb.length-1;i++){
var $myBoardCells = $('.myBoard .cell:eq('+i+')');
if(gb[i] === 'x'){
$myBoardCells.addClass('hit');
} else if(gb[i] === 'm'){
$myBoardCells.addClass('miss');
} else if(gb[i] === '2'){
$myBoardCells.addClass('ship2');
} else if(gb[i] === '3'){
$myBoardCells.addClass('ship3');
} else if(gb[i] === '4'){
$myBoardCells.addClass('ship4');
} else if(gb[i] === '5'){
$myBoardCells.addClass('ship5');
} else{}
}
}
function createBoardPosition(cell) {
var $cell = $('.myBoard .cell'),
index = $cell.index(cell),
currentShip = $('.current'),
$shipList = $('.ship-list'),
$ship2 = $('.destroyer'),
$ship3a = $('.cruiser'),
$ship3b = $('.submarine'),
$ship4 = $('.battleship'),
$ship5 = $('.aircraft-carrier'),
vertical = $shipList.hasClass('vertical'),
remainingRowCells = cell.nextAll().length,
remainingRows = cell.parent().nextAll().length + 1,
nextShipInRow = cell.nextUntil('.ship'),
shipSize = $('.current').find('li').length;
for (var i=0; i < 100; i++) {
if (myBoardPositions[i] === undefined) {
myBoardPositions[i] = 0;
}
}
// check available cells against ship size before placing
if ((!vertical && (remainingRowCells < shipSize)) || (!vertical && (nextShipInRow < shipSize)) || (vertical && remainingRows < shipSize)) {
console.log('cant place ship here, not enough cells');
} else if ($ship2.hasClass('current') && vertical) {
myBoardPositions[index] = 2;
myBoardPositions[index + 10] = 2;
$ship2.toggleClass('placed');
appendShipToBoard(cell, 2);
console.log('placed destroyer');
} else if ($ship2.hasClass('current')) {
myBoardPositions[index] = 2;
myBoardPositions[index + 1] = 2;
$ship2.toggleClass('placed');
appendShipToBoard(cell, 2);
console.log('placed destroyer');
} else if ($ship3a.hasClass('current') && vertical) {
myBoardPositions[index] = 3;
myBoardPositions[index + 10] = 3;
myBoardPositions[index + 20] = 3;
$ship3a.toggleClass('placed');
appendShipToBoard(cell, 3);
console.log('placed cruiser');
} else if ($ship3a.hasClass('current')) {
myBoardPositions[index] = 3;
myBoardPositions[index + 1] = 3;
myBoardPositions[index + 2] = 3;
$ship3a.toggleClass('placed');
appendShipToBoard(cell, 3);
console.log('placed cruiser');
} else if ($ship3b.hasClass('current') && vertical) {
myBoardPositions[index] = 3;
myBoardPositions[index + 10] = 3;
myBoardPositions[index + 20] = 3;
$ship3b.toggleClass('placed');
appendShipToBoard(cell, 3);
console.log('placed submarine');
} else if ($ship3b.hasClass('current')) {
myBoardPositions[index] = 3;
myBoardPositions[index + 1] = 3;
myBoardPositions[index + 2] = 3;
$ship3b.toggleClass('placed');
appendShipToBoard(cell, 3);
console.log('placed submarine');
} else if ($ship4.hasClass('current') && vertical) {
myBoardPositions[index] = 4;
myBoardPositions[index + 10] = 4;
myBoardPositions[index + 20] = 4;
myBoardPositions[index + 30] = 4;
$ship4.toggleClass('placed');
appendShipToBoard(cell, 4);
console.log('placed battleship');
} else if ($ship4.hasClass('current')) {
myBoardPositions[index] = 4;
myBoardPositions[index + 1] = 4;
myBoardPositions[index + 2] = 4;
myBoardPositions[index + 3] = 4;
$ship4.toggleClass('placed');
appendShipToBoard(cell, 4);
console.log('placed battleship');
} else if ($ship5.hasClass('current') && vertical) {
myBoardPositions[index] = 5;
myBoardPositions[index + 10] = 5;
myBoardPositions[index + 20] = 5;
myBoardPositions[index + 30] = 5;
myBoardPositions[index + 40] = 5;
$ship5.toggleClass('placed');
console.log('placed aircraft carrier');
appendShipToBoard(cell, 5);
} else if ($ship5.hasClass('current')) {
myBoardPositions[index] = 5;
myBoardPositions[index + 1] = 5;
myBoardPositions[index + 2] = 5;
myBoardPositions[index + 3] = 5;
myBoardPositions[index + 4] = 5;
$ship5.toggleClass('placed');
appendShipToBoard(cell, 5);
console.log('placed aircraft carrier');
} else {
console.log('no more ships to play');
}
return myBoardPositions;
}
function sendBoardToFb(user, array) {
findCurrentGameId(gamesFb, function(foundGame){
var thisGame = new Firebase (url + 'games/' + foundGame[0][0]),
myGameBoard = thisGame.child('gameBoard' + user);
myGameBoard.set(array);
});
}
function appendShipToBoard(cell, shipSize) {
var vertical = $('.ship-list').hasClass('vertical'),
shipType = 'ship' + shipSize;
cell.addClass('ship').addClass(shipType);
for (var i=0; i < shipSize - 1; i++) {
if (vertical) {
cell.parent().nextAll().eq(i).find('.cell').eq(cell.index() - 1).addClass('ship').addClass(shipType);
} else {
cell.nextAll('.cell').eq(i).addClass('ship').addClass(shipType);
}
}
}
function checkBoardForShips (theirGameboard) {
function filter3(number){return number === 3};
if ($.inArray(2, theirGameboard) === -1 && $.inArray(2,sunkShips) === -1) {
alert('Ship 2 is sunk!');
sunkShips.push(2);
} else if (theirGameboard.filter(filter3).length === 3 && $.inArray(8,sunkShips) === -1) {
alert('One 3 ship is sunk!');
sunkShips.push(8);
} else if ($.inArray(3, theirGameboard) === -1 && $.inArray(9,sunkShips) === -1) {
alert('Both 3 ships are sunk!');
sunkShips.push(9);
} else if ($.inArray(4, theirGameboard) === -1 && $.inArray(4,sunkShips) === -1) {
alert('Ship 4 is sunk');
sunkShips.push(4);
} else if ($.inArray(5, theirGameboard) === -1 && $.inArray(5,sunkShips) === -1) {
alert('ship 5 is sunk');
sunkShips.push(5);
} else if ($.inArray(2, theirGameboard) === -1 && $.inArray(3, theirGameboard) === -1 && $.inArray(4, theirGameboard) === -1 && $.inArray(5, theirGameboard) === -1) {
alert('All ships are destroyed!');
}
}
///////////////////////////////////////////////////
///////////////// State Listeners /////////////////
///////////////////////////////////////////////////
function listenForUser2(){
findCurrentGameId(gamesFb, function(foundGame){
var thisGameUrl = new Firebase (url + 'games/' + foundGame[0][0]);
var otherPlayer = new Firebase (url + 'games/' + foundGame[0][0] + '/user2');
thisGameUrl.on('child_changed', function(childsnap){
var childvalue = childsnap.val();
thisGameUrl.once('value', function(snap){
var p2 = snap.val().user2;
if(p2 !== ''){
$('.game-status-p').text('player 2 joined');
thisGameUrl.off('child_changed');
listenforShipPlacement();
}
})
});
});
}
function listenforShipPlacement(){
//delete stranded game
checkGames((function(avaGames){
var deleteGame = new Firebase (url + 'games/' + avaGames[0]);
deleteGame.set(null);
}),function(avaGames){
});
//attach event listeners to game
findCurrentGameId(gamesFb, function(foundGame){
var thisGameUrl = new Firebase (url + 'games/' + foundGame[0][0]);
function otherPlayer(){if(foundGame[0][1] === 1){return 2}else{return 1}};
var otherGameboard = new Firebase (url + 'games/' + foundGame[0][0] + '/gameboard'+otherPlayer());
thisGameUrl.on('child_changed', function(childsnap){
var snap = childsnap.val();
if(otherPlayer()===1){
thisGameUrl.once('value', function(g){
if($.inArray(2,g.val().gameBoard1) !== -1){
thisGameUrl.off('child_changed');
listenforMyBoardChange();
listenforTheirBoardChange();
}
})
} else {
thisGameUrl.once('value', function(g){
if($.inArray(2,g.val().gameBoard2) !== -1){
thisGameUrl.off('child_changed');
listenforMyBoardChange();
listenforTheirBoardChange();
}
})
}
});
});
}
function listenforMyBoardChange(){
findCurrentGameId(gamesFb, function(foundGame){
var thisGameUrl = new Firebase (url + 'games/' + foundGame[0][0]);
function otherPlayer(){if(foundGame[0][1] === 1){return 2}else{return 1}};
var otherGameboard = new Firebase (url + 'games/' + foundGame[0][0] + '/gameboard'+otherPlayer());
var myGameboard = new Firebase (url + 'games/' + foundGame[0][0] + '/gameboard'+foundGame[0][1]);
thisGameUrl.on('child_changed', function(childsnap){
var snap = childsnap.val();
if(otherPlayer()===1){
thisGameUrl.once('value', function(g){
var mygb = g.val().gameBoard2;
appendTheirGuessesGameboard(mygb);
checkBoardForShips(mygb);
})
} else {
thisGameUrl.once('value', function(g){
var mygb = g.val().gameBoard1;
appendTheirGuessesGameboard(mygb);
checkBoardForShips(mygb);
})
}
});
});
}
function listenforTheirBoardChange(){
findCurrentGameId(gamesFb, function(foundGame){
var thisGameUrl = new Firebase (url + 'games/' + foundGame[0][0]);
function otherPlayer(){if(foundGame[0][1] === 1){return 2}else{return 1}};
var otherGameboard = new Firebase (url + 'games/' + foundGame[0][0] + '/gameboard'+otherPlayer());
var myGameboard = new Firebase (url + 'games/' + foundGame[0][0] + '/gameboard'+foundGame[0][1]);
thisGameUrl.on('child_changed', function(childsnap){
var snap = childsnap.val();
if(otherPlayer()===1){
thisGameUrl.once('value', function(g){
var mygb = g.val().gameBoard1;
appendMyGuessesGameboard(mygb);
checkBoardForShips(mygb);
})
} else {
thisGameUrl.once('value', function(g){
var mygb = g.val().gameBoard2;
appendMyGuessesGameboard(mygb);
checkBoardForShips(mygb);
})
}
});
});
}
//////////////////////////////////////////////////////
////////////////// Click Events //////////////////////
//////////////////////////////////////////////////////
// get the current player
$playerName.click( function () {
if ($('#playerNameValue').val()) {
$chosenName = $('#playerNameValue').val();
$('#playerName').toggleClass('hidden');
$('#newGame').toggleClass('hidden');
$('#playerNameValue').toggleClass('hidden');
}
});
// send user to an available or empty game
$('#newGame').click(function () {
$('#newGame').toggleClass('hidden');
$('#newGame').toggleClass('unclicked');
$('.ship-controls').toggleClass('hidden');
checkGames((function(avaGames){
if (avaGames[0]) {
var thisGame = new Firebase (url + 'games/' + avaGames[0] + '/user2');
thisGame.set($chosenName);
listenforShipPlacement();
} //else {gamesFb.push(createEmptyGame($chosenName))}
}), function(){
findCurrentGameId(gamesFb, function(foundGame){
if(!foundGame[0]) {
gamesFb.push(createEmptyGame($chosenName));
$('.game-status').toggleClass('hidden');
listenForUser2();
}
});
});
});
function gameBoardClick() {
$('.theirBoard .cell').click(function(){
var $thisCell = $(this);
findCurrentGameId(gamesFb, function(foundGame){
var thisGameUrl = new Firebase (url + 'games/' + foundGame[0][0]),
thisGameUserTurn = new Firebase (url + 'games/' + foundGame[0][0] + '/userTurn');
function otherPlayer(){if(foundGame[0][1] === 1){return 2}else{return 1}};
var theirGameboard = new Firebase (url + 'games/' + foundGame[0][0] + '/gameBoard' + otherPlayer());
//the function to check to see if it is a hit or miss should go here
//it compares the cell clicked to 'theirGameboard'
//it should return a gameboard array of 'x''s,'m''s, and 0's which is passed into the appendYourGuessesGameboard
//append computed guesses array to the right gameboard
//appendYourGuessesGameboard(hitOrMissArray);
var $target = $('.theirBoard .cell').index($thisCell);
thisGameUrl.once('value', function(res){
var val = res.val();
function findUser(){
if(val.userTurn === 2){return val.user2} else {return val.user1}
}
if($chosenName === findUser()){
theirGameboard.once('value', function(gb){
var gbFound = gb.val();
if (gbFound[$target] === 0) {
gbFound.splice($target, 1, 'm');
} else if (gbFound[$target] > 0) {
gbFound.splice($target, 1, 'x');
}
sendBoardToFb(otherPlayer(), gbFound);
});
// theirGameboard.once('value', function(gb){
// var updatedGb = gb.val();
// appendMyGuessesGameboard(updatedGb);
// });
switchTurn(foundGame[0][0]);
} else {}
});
});
});
} // end function gameBoardClick
gameBoardClick();
// Click a cell to place a ship if placement is valid
$('.myBoard .cell').click(function() {
var $cell = $(this);
if ($cell.hasClass('ship')) {
console.log('ship already placed here');
} else if ($('#newGame').hasClass('unclicked')) {
console.log('click New Game before placing ships');
} else {
createBoardPosition($cell);
}
});
// Send player's completed board state array to firebase
$('.myBoard').click(function() {
if ($('.placed').length === 5) {
findCurrentGameId(gamesFb, function(foundGame){
if (foundGame[0]) {
sendBoardToFb(foundGame[0][1], myBoardPositions);
console.log('board sent to firebase');
$('.myBoard').unbind('click');
} else {
console.log('could not find game, create a new game first');
}
});
}
});
// Firebase reset switch for clearing games
$('#resetFirebase').click(function () {
fb.remove();
});
// Rotate ship
$('#rotate').click(function() {
$('.ship-list').toggleClass('vertical');
});
// Cycle through ships during placement
$('.myBoard').click(function() {
var $shipPlaced = $('.ship-controls').find('.current').hasClass('placed');
if ($shipPlaced) {
$('.ship-controls').find('.current').next().toggleClass('hidden current');
$('.ship-controls').find('.current').first().toggleClass('hidden current');
} else {
console.log('cannot place ship here');
}
}); | kylemcco/jengaship | app/scripts/index.js | JavaScript | mit | 19,418 |
import { Durations } from '../../Constants.js';
const DrawCard = require('../../drawcard.js');
const AbilityDsl = require('../../abilitydsl.js');
class MatsuKoso extends DrawCard {
setupCardAbilities() {
this.action({
title: 'Lower military skill',
condition: context => context.source.isParticipating(),
gameAction: AbilityDsl.actions.cardLastingEffect(context => ({
target: context.game.currentConflict.getParticipants(),
duration: Durations.UntilEndOfConflict,
effect: AbilityDsl.effects.modifyMilitarySkill(card => isNaN(card.printedPoliticalSkill) ? 0 : -card.printedPoliticalSkill)
})),
effect: 'lower the military skill of {1} by their respective pirnted political skill',
effectArgs: context => [context.game.currentConflict.getParticipants()]
});
}
}
MatsuKoso.id = 'matsu-koso';
module.exports = MatsuKoso;
| gryffon/ringteki | server/game/cards/12-SoW/MastuKoso.js | JavaScript | mit | 964 |
'use strict';
require('../../../TestHelper');
/* global bootstrapDiagram, inject */
var modelingModule = require('../../../../lib/features/modeling'),
bendpointsModule = require('../../../../lib/features/bendpoints'),
rulesModule = require('./rules'),
interactionModule = require('../../../../lib/features/interaction-events'),
canvasEvent = require('../../../util/MockEvents').createCanvasEvent;
describe('features/bendpoints', function() {
beforeEach(bootstrapDiagram({ modules: [ modelingModule, bendpointsModule, interactionModule, rulesModule ] }));
beforeEach(inject(function(dragging) {
dragging.setOptions({ manual: true });
}));
var rootShape, shape1, shape2, shape3, connection, connection2;
beforeEach(inject(function(elementFactory, canvas) {
rootShape = elementFactory.createRoot({
id: 'root'
});
canvas.setRootElement(rootShape);
shape1 = elementFactory.createShape({
id: 'shape1',
type: 'A',
x: 100, y: 100, width: 300, height: 300
});
canvas.addShape(shape1, rootShape);
shape2 = elementFactory.createShape({
id: 'shape2',
type: 'A',
x: 500, y: 100, width: 100, height: 100
});
canvas.addShape(shape2, rootShape);
shape3 = elementFactory.createShape({
id: 'shape3',
type: 'B',
x: 500, y: 400, width: 100, height: 100
});
canvas.addShape(shape3, rootShape);
connection = elementFactory.createConnection({
id: 'connection',
waypoints: [ { x: 250, y: 250 }, { x: 550, y: 250 }, { x: 550, y: 150 } ],
source: shape1,
target: shape2
});
canvas.addConnection(connection, rootShape);
connection2 = elementFactory.createConnection({
id: 'connection2',
waypoints: [ { x: 250, y: 250 }, { x: 550, y: 450 } ],
source: shape1,
target: shape2
});
canvas.addConnection(connection2, rootShape);
}));
describe('activation', function() {
it('should show on hover', inject(function(eventBus, canvas, elementRegistry) {
// given
var layer = canvas.getLayer('overlays');
// when
eventBus.fire('element.hover', { element: connection, gfx: elementRegistry.getGraphics(connection) });
// then
// 3 visible + 1 invisible bendpoint are shown
expect(layer.node.querySelectorAll('.djs-bendpoint').length).to.equal(4);
expect(layer.node.querySelectorAll('.djs-segment-dragger').length).to.equal(2);
}));
it('should show on select', inject(function(selection, canvas, elementRegistry) {
// given
var layer = canvas.getLayer('overlays');
// when
selection.select(connection);
// then
// 3 visible + 1 invisible bendpoint are shown
expect(layer.node.querySelectorAll('.djs-bendpoint').length).to.equal(4);
expect(layer.node.querySelectorAll('.djs-segment-dragger').length).to.equal(2);
}));
it('should activate bendpoint move', inject(function(dragging, eventBus, elementRegistry, bendpoints) {
// when
eventBus.fire('element.hover', { element: connection, gfx: elementRegistry.getGraphics(connection) });
eventBus.fire('element.mousemove', {
element: connection,
originalEvent: canvasEvent({ x: 500, y: 250 })
});
eventBus.fire('element.mousedown', {
element: connection,
originalEvent: canvasEvent({ x: 500, y: 250 })
});
var draggingContext = dragging.active();
// then
expect(draggingContext).to.exist;
expect(draggingContext.prefix).to.eql('bendpoint.move');
}));
it('should activate parallel move', inject(function(dragging, eventBus, elementRegistry, bendpoints) {
// precondition
var intersectionStart = connection.waypoints[0].x,
intersectionEnd = connection.waypoints[1].x,
intersectionMid = intersectionEnd - (intersectionEnd - intersectionStart) / 2;
// when
eventBus.fire('element.hover', { element: connection, gfx: elementRegistry.getGraphics(connection) });
eventBus.fire('element.mousemove', {
element: connection,
originalEvent: canvasEvent({ x: intersectionMid, y: 250 })
});
eventBus.fire('element.mousedown', {
element: connection,
originalEvent: canvasEvent({ x: intersectionMid, y: 250 })
});
var draggingContext = dragging.active();
// then
expect(draggingContext).to.exist;
expect(draggingContext.prefix).to.eql('connectionSegment.move');
}));
});
});
| camunda-internal/bpmn-quiz | node_modules/diagram-js/test/spec/features/bendpoints/BendpointsSpec.js | JavaScript | mit | 4,569 |
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import Landing from './../Landing'
import * as UserActions from './../actions/User'
function mapStateToProps(state) {
return {
user: state.userStore.user
}
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators(UserActions, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(Landing) | Briseus/Kape | src/containers/Landing.js | JavaScript | mit | 425 |
import Resolver from 'ember/resolver';
import loadInitializers from 'ember/load-initializers';
Ember.MODEL_FACTORY_INJECTIONS = true;
var App = Ember.Application.extend({
modulePrefix: 'tvdb', // TODO: loaded via config
Resolver: Resolver
});
loadInitializers(App, 'tvdb');
export default App;
| bolotyuh/ember-symfony-starterkit | web/ember/foo/app/app.js | JavaScript | mit | 302 |
YUI.add('dataschema-array', function (Y, NAME) {
/**
* Provides a DataSchema implementation which can be used to work with data
* stored in arrays.
*
* @module dataschema
* @submodule dataschema-array
*/
/**
Provides a DataSchema implementation which can be used to work with data
stored in arrays.
See the `apply` method below for usage.
@class DataSchema.Array
@extends DataSchema.Base
@static
**/
var LANG = Y.Lang,
SchemaArray = {
////////////////////////////////////////////////////////////////////////
//
// DataSchema.Array static methods
//
////////////////////////////////////////////////////////////////////////
/**
Applies a schema to an array of data, returning a normalized object
with results in the `results` property. The `meta` property of the
response object is present for consistency, but is assigned an empty
object. If the input data is absent or not an array, an `error`
property will be added.
The input array is expected to contain objects, arrays, or strings.
If _schema_ is not specified or _schema.resultFields_ is not an array,
`response.results` will be assigned the input array unchanged.
When a _schema_ is specified, the following will occur:
If the input array contains strings, they will be copied as-is into the
`response.results` array.
If the input array contains arrays, `response.results` will contain an
array of objects with key:value pairs assuming the fields in
_schema.resultFields_ are ordered in accordance with the data array
values.
If the input array contains objects, the identified
_schema.resultFields_ will be used to extract a value from those
objects for the output result.
_schema.resultFields_ field identifiers are objects with the following properties:
* `key` : <strong>(required)</strong> The locator name (String)
* `parser`: A function or the name of a function on `Y.Parsers` used
to convert the input value into a normalized type. Parser
functions are passed the value as input and are expected to
return a value.
If no value parsing is needed, you can use strings as identifiers
instead of objects (see example below).
@example
// Process array of arrays
var schema = { resultFields: [ 'fruit', 'color' ] },
data = [
[ 'Banana', 'yellow' ],
[ 'Orange', 'orange' ],
[ 'Eggplant', 'purple' ]
];
var response = Y.DataSchema.Array.apply(schema, data);
// response.results[0] is { fruit: "Banana", color: "yellow" }
// Process array of objects
data = [
{ fruit: 'Banana', color: 'yellow', price: '1.96' },
{ fruit: 'Orange', color: 'orange', price: '2.04' },
{ fruit: 'Eggplant', color: 'purple', price: '4.31' }
];
response = Y.DataSchema.Array.apply(schema, data);
// response.results[0] is { fruit: "Banana", color: "yellow" }
// Use parsers
schema.resultFields = [
{
key: 'fruit',
parser: function (val) { return val.toUpperCase(); }
},
{
key: 'price',
parser: 'number' // Uses Y.Parsers.number
}
];
response = Y.DataSchema.Array.apply(schema, data);
// Note price was converted from a numeric string to a number
// response.results[0] looks like { fruit: "BANANA", price: 1.96 }
@method apply
@param {Object} [schema] Schema to apply. Supported configuration
properties are:
@param {Array} [schema.resultFields] Field identifiers to
locate/assign values in the response records. See above for
details.
@param {Array} data Array data.
@return {Object} An Object with properties `results` and `meta`
@static
**/
apply: function(schema, data) {
var data_in = data,
data_out = {results:[],meta:{}};
if(LANG.isArray(data_in)) {
if(schema && LANG.isArray(schema.resultFields)) {
// Parse results data
data_out = SchemaArray._parseResults.call(this, schema.resultFields, data_in, data_out);
}
else {
data_out.results = data_in;
}
}
else {
data_out.error = new Error("Array schema parse failure");
}
return data_out;
},
/**
* Schema-parsed list of results from full data
*
* @method _parseResults
* @param fields {Array} Schema to parse against.
* @param array_in {Array} Array to parse.
* @param data_out {Object} In-progress parsed data to update.
* @return {Object} Parsed data object.
* @static
* @protected
*/
_parseResults: function(fields, array_in, data_out) {
var results = [],
result, item, type, field, key, value, i, j;
for(i=array_in.length-1; i>-1; i--) {
result = {};
item = array_in[i];
type = (LANG.isObject(item) && !LANG.isFunction(item)) ? 2 : (LANG.isArray(item)) ? 1 : (LANG.isString(item)) ? 0 : -1;
if(type > 0) {
for(j=fields.length-1; j>-1; j--) {
field = fields[j];
key = (!LANG.isUndefined(field.key)) ? field.key : field;
value = (!LANG.isUndefined(item[key])) ? item[key] : item[j];
result[key] = Y.DataSchema.Base.parse.call(this, value, field);
}
}
else if(type === 0) {
result = item;
}
else {
//TODO: null or {}?
result = null;
}
results[i] = result;
}
data_out.results = results;
return data_out;
}
};
Y.DataSchema.Array = Y.mix(SchemaArray, Y.DataSchema.Base);
}, '3.10.3', {"requires": ["dataschema-base"]});
| braz/mojito-helloworld | node_modules/mojito/node_modules/yui/dataschema-array/dataschema-array.js | JavaScript | mit | 6,625 |
module.exports = (function () {
var moduleName = 'cut-media-queries';
var lolArrayDiff = function(array1, array2) {
var diff1 = array1.filter(function(elem){
return array2.indexOf(elem) === -1;
});
var diff2 = array2.filter(function(elem){
return array1.indexOf(elem) === -1;
});
return diff1.concat(diff2);
}
return {
/**
* Option's name as it should be used in config.
*/
name: moduleName,
/**
* List of syntaxes that this options supports.
* This depends on Gonzales PE possibilities.
* Currently the following work fine: css, less, sass, scss.
*/
syntax: ['css'],
/**
* List patterns for option's acceptable value.
* You can play with following:
* - boolean: [true, false]
* - string: /^panda$/
* - number: true
*/
accepts: {
string: /.*/
},
/**
* If `accepts` is not enough for you, replace it with custom `setValue`
* function.
*
* @param {Object} value Value that a user sets in configuration
* @return {Object} Value that you would like to use in `process` method
*
* setValue: function(value) {
* // Do something with initial value.
* var final = value * 4;
*
* // Return final value you will use in `process` method.
* return final;
* },
*/
/**
* Fun part.
* Do something with AST.
* For example, replace all comments with flipping tables.
*
* @param {String} nodeType Type of current node
* @param {Array} node Node's content
*/
process: function (nodeType, node) {
if (nodeType === 'stylesheet') {
var length = node.length;
var options = this.getValue(moduleName).split(',');
while (length--) {
if (node[length][0] == 'atruler') {
var removeNode = false;
//Gather media query info
node[length].forEach(function (innerNode) {
if (removeNode == true) return;
if (innerNode[0] == 'atrulerq') {
var queries = [];
innerNode.forEach(function (query) {
if (query[0] == 'braces') {
var ident = query.filter(function (elem) {
return elem[0] == 'ident';
});
var dimensions = query.filter(function (elem) {
return elem[0] == 'dimension';
});
if (ident.length != 0) {
queries.push(ident[0][1] + ":" + dimensions[0][1][1] + dimensions[0][2][1]);
}
}
});
if (lolArrayDiff(queries, options).length == 0) {
removeNode = true;
}
}
});
if (removeNode) {
node.splice(length, 1);
}
}
}
}
}
};
})();
| iVariable/csscomb-cut-media-queries | options/cut-media-queries.js | JavaScript | mit | 2,636 |
// Dependencies
const {types} = require('focus').component;
// Components
const ContextualActions = require('../action-contextual').component;
const CheckBox = require('../../common/input/checkbox').component;
// Mixins
const translationMixin = require('../../common/i18n').mixin;
const referenceMixin = require('../../common/mixin/reference-property');
const definitionMixin = require('../../common/mixin/definition');
const builtInComponentsMixin = require('../mixin/built-in-components');
const lineMixin = {
/**
* React component name.
*/
displayName: 'ListLine',
/**
* Mixin dependancies.
*/
mixins: [translationMixin, definitionMixin, referenceMixin, builtInComponentsMixin],
/**
* Get default props
* @return {object} default props
*/
getDefaultProps(){
return {
isSelection: true,
operationList: []
};
},
/**
* line property validation.
* @type {Object}
*/
propTypes: {
data: types('object'),
isSelected: types('bool'),
isSelection: types('bool'),
onLineClick: types('func'),
onSelection: types('func'),
operationList: types('array')
},
/**
* State initialization.
* @return {object} initial state
*/
getInitialState() {
return {
isSelected: this.props.isSelected || false
};
},
/**
* Component will receive props
* @param {object} nextProps new component's props
*/
componentWillReceiveProps({isSelected}) {
if (isSelected !== undefined) {
this.setState({isSelected});
}
},
/**
* Get the line value.
* @return {object} the line value
*/
getValue() {
const {data: item, isSelected} = this.props;
return {item, isSelected};
},
/**
* Selection Click handler.
*/
_handleSelectionClick() {
const isSelected = !this.state.isSelected;
const {data, onSelection} = this.props;
this.setState({isSelected});
if(onSelection){
onSelection(data, isSelected);
}
},
/**
* Line Click handler.
*/
_handleLineClick() {
const {data, onLineClick} = this.props;
if(onLineClick){
onLineClick(data);
}
},
/**
* Render the left box for selection
* @return {XML} the rendered selection box
*/
_renderSelectionBox() {
const {isSelection} = this.props;
const {isSelected} = this.state;
if (isSelection) {
const selectionClass = isSelected ? 'selected' : 'no-selection';
//const image = this.state.isSelected? undefined : <img src={this.state.lineItem[this.props.iconfield]}/>
return (
<div className={`sl-selection ${selectionClass}`}>
<CheckBox onChange={this._handleSelectionClick} value={isSelected}/>
</div>
);
}
return null;
},
/**
* render content for a line.
* @return {XML} the rendered line content
*/
_renderLineContent() {
const {data} = this.props;
const {title, body} = data;
if (this.renderLineContent) {
return this.renderLineContent(data);
} else {
return (
<div>
<div>{title}</div>
<div>{body}</div>
</div>
);
}
},
/**
* Render actions which can be applied on the line
* @return {XML} the rendered actions
*/
_renderActions() {
const props = {operationParam: this.props.data, ...this.props};
if (0 < props.operationList.length) {
return (
<div className='sl-actions'>
<ContextualActions {...props}/>
</div>
);
}
},
/**
* Render line in list.
* @return {XML} the rendered line
*/
render() {
if(this.renderLine){
return this.renderLine();
} else {
return (
<li data-focus='sl-line'>
{this._renderSelectionBox()}
<div className='sl-content' onClick={this._handleLineClick}>
{this._renderLineContent()}
</div>
{this._renderActions()}
</li>
);
}
}
};
module.exports = {mixin: lineMixin};
| JRLK/focus-components | src/list/selection/line.js | JavaScript | mit | 4,528 |
'use strict';
var assert = require('assert');
var extraStep = require('../../../lib/tasks/extra-step');
var MockUI = require('../../helpers/mock-ui');
describe('Extra Step', function() {
var ui;
var dummySteps = [
{ command: 'echo "command number 1"' },
{ command: 'echo "command number 2"' },
{ command: 'echo "command number 3"' }
];
var dummyCommands = [
'echo "command number 1"',
'echo "command number 2"',
'echo "command number 3"'
];
var failingStep = [ { command: 'exit 1', fail: true } ];
var nonFailingStep = [ { command: 'exit 1', fail: false } ];
var singleFailingStep = [ nonFailingStep[0], failingStep[0], nonFailingStep[0] ];
var dummyOptions = {
foo: 'bar',
truthy: true,
falsy: false,
someOption: 'i am a string',
num: 24
};
var dummyStepsWithOptions = [
{
command: 'echo "command number 4"',
includeOptions: ['foo', 'falsy', 'num']
},
{
command: 'echo "command number 5"',
includeOptions: ['truthy', 'someOption', 'nonExistent']
}
];
var dummyCommandsWithOptions = [
"echo \"command number 4\" --foo bar --num 24",
"echo \"command number 5\" --truthy --some-option 'i am a string'",
];
beforeEach(function() {
ui = new MockUI;
});
it('Runs an array of commands passed to it', function() {
return extraStep(dummySteps, dummyOptions, ui).then(function(result) {
assert.deepEqual(result, dummyCommands, 'Correct commands were run.');
}, function(error) {
assert.ok(false, 'An error occurred');
});
});
it('The proper commands are built and run', function() {
return extraStep(dummyStepsWithOptions, dummyOptions, ui).then(function(result) {
assert.deepEqual(result, dummyCommandsWithOptions, 'Correct commands were built and run.');
}, function(error) {
assert.ok(false, 'An error occurred');
});
});
it('Fail-safe command, with non 0 exit code, returns rejected promise', function() {
return extraStep(failingStep, null, ui).then(function(result) {
assert.ok(false, 'steps should have failed.');
}, function(err) {
assert.ok(true, 'steps failed as expected.');
});
});
it('Fail-friendly command, with non 0 exit code, returns resolved promise', function() {
return extraStep(nonFailingStep, null, ui).then(function(result) {
assert.ok(true, 'steps kept running after failed command, as expected.');
}, function(err) {
assert.ok(false, 'Steps did not continue running as expected');
});
});
});
| AReallyGoodName/ember-cli-s3-sync-index-last-no-cache | tests/unit/tasks/extra-step-test.js | JavaScript | mit | 2,577 |
/* eslint-disable comma-style, operator-linebreak, space-unary-ops, no-multi-spaces, key-spacing, indent */
'use strict'
const analyzeHoldem = require('./lib/holdem')
/**
* Analyzes a given PokerHand which has been parsed by the HandHistory Parser hhp.
* Relative player positions are calculated, i.e. cutoff, button, etc.
* Players are included in order of action on flop.
*
* The analyzed hand then can be visualized by [hhv](https://github.com/thlorenz/hhv).
*
* For an example of an analyzed hand please view [json output of an analyzed
* hand](https://github.com/thlorenz/hhv/blob/master/test/fixtures/holdem/actiononall.json).
*
* @name analyze
* @function
* @param {object} hand hand history as parsed by [hhp](https://github.com/thlorenz/hhp)
* @return {object} the analyzed hand
*/
exports = module.exports = function analyze(hand) {
if (!hand.info) throw new Error('Hand is missing info')
if (hand.info.pokertype === 'holdem') return analyzeHoldem(hand)
}
exports.script = require('./lib/script')
exports.storyboard = require('./lib/storyboard')
exports.summary = require('./lib/summary')
exports.strategicPositions = require('./lib/strategic-positions').list
function wasActive(x) {
return x.preflop[0] && x.preflop[0].type !== 'fold'
}
/**
* Filters all players who didn't act in the hand or just folded.
*
* @name filterInactives
* @function
* @param {Array.<Object>} players all players in the hand
* @return {Array.<Object>} all players that were active in the hand
*/
exports.filterInactives = function filterInactives(players) {
if (players == null) return []
return players.filter(wasActive)
}
| thlorenz/hha | hha.js | JavaScript | mit | 1,658 |
import { h, render, rerender, Component } from '../../src/preact';
let { expect } = chai;
/*eslint-env browser, mocha */
/*global sinon, chai*/
/** @jsx h */
describe('render()', () => {
let scratch;
before( () => {
scratch = document.createElement('div');
(document.body || document.documentElement).appendChild(scratch);
});
beforeEach( () => {
scratch.innerHTML = '';
});
after( () => {
scratch.parentNode.removeChild(scratch);
scratch = null;
});
it('should create empty nodes (<* />)', () => {
render(<div />, scratch);
expect(scratch.childNodes)
.to.have.length(1)
.and.to.have.deep.property('0.nodeName', 'DIV');
scratch.innerHTML = '';
render(<span />, scratch);
expect(scratch.childNodes)
.to.have.length(1)
.and.to.have.deep.property('0.nodeName', 'SPAN');
scratch.innerHTML = '';
render(<foo />, scratch);
render(<x-bar />, scratch);
expect(scratch.childNodes).to.have.length(2);
expect(scratch.childNodes[0]).to.have.property('nodeName', 'FOO');
expect(scratch.childNodes[1]).to.have.property('nodeName', 'X-BAR');
});
it('should nest empty nodes', () => {
render((
<div>
<span />
<foo />
<x-bar />
</div>
), scratch);
expect(scratch.childNodes)
.to.have.length(1)
.and.to.have.deep.property('0.nodeName', 'DIV');
let c = scratch.childNodes[0].childNodes;
expect(c).to.have.length(3);
expect(c).to.have.deep.property('0.nodeName', 'SPAN');
expect(c).to.have.deep.property('1.nodeName', 'FOO');
expect(c).to.have.deep.property('2.nodeName', 'X-BAR');
});
it('should apply string attributes', () => {
render(<div foo="bar" data-foo="databar" />, scratch);
let div = scratch.childNodes[0];
expect(div).to.have.deep.property('attributes.length', 2);
expect(div).to.have.deep.property('attributes[0].name', 'foo');
expect(div).to.have.deep.property('attributes[0].value', 'bar');
expect(div).to.have.deep.property('attributes[1].name', 'data-foo');
expect(div).to.have.deep.property('attributes[1].value', 'databar');
});
it('should apply class as String', () => {
render(<div class="foo" />, scratch);
expect(scratch.childNodes[0]).to.have.property('className', 'foo');
});
it('should alias className to class', () => {
render(<div className="bar" />, scratch);
expect(scratch.childNodes[0]).to.have.property('className', 'bar');
});
it('should apply style as String', () => {
render(<div style="top:5px; position:relative;" />, scratch);
expect(scratch.childNodes[0]).to.have.deep.property('style.cssText')
.that.matches(/top\s*:\s*5px\s*/)
.and.matches(/position\s*:\s*relative\s*/);
});
it('should only register on* functions as handlers', () => {
let click = () => {},
onclick = () => {};
let proto = document.createElement('div').constructor.prototype;
sinon.spy(proto, 'addEventListener');
render(<div click={ click } onClick={ onclick } />, scratch);
expect(scratch.childNodes[0]).to.have.deep.property('attributes.length', 0);
expect(proto.addEventListener).to.have.been.calledOnce
.and.to.have.been.calledWithExactly('click', sinon.match.func);
proto.addEventListener.restore();
});
it('should serialize style objects', () => {
render(<div style={{
color: 'rgb(255, 255, 255)',
background: 'rgb(255, 100, 0)',
backgroundPosition: '0 0',
'background-size': 'cover',
padding: 5,
top: 100,
left: '100%'
}} />, scratch);
let { style } = scratch.childNodes[0];
expect(style).to.have.property('color', 'rgb(255, 255, 255)');
expect(style).to.have.property('background').that.contains('rgb(255, 100, 0)');
expect(style).to.have.property('backgroundPosition').that.matches(/0(px)? 0(px)?/);
expect(style).to.have.property('backgroundSize', 'cover');
expect(style).to.have.property('padding', '5px');
expect(style).to.have.property('top', '100px');
expect(style).to.have.property('left', '100%');
});
it('should serialize class/className', () => {
render(<div class={{
no1: false,
no2: 0,
no3: null,
no4: undefined,
no5: '',
yes1: true,
yes2: 1,
yes3: {},
yes4: [],
yes5: ' '
}} />, scratch);
let { className } = scratch.childNodes[0];
expect(className).to.be.a.string;
expect(className.split(' '))
.to.include.members(['yes1', 'yes2', 'yes3', 'yes4', 'yes5'])
.and.not.include.members(['no1', 'no2', 'no3', 'no4', 'no5']);
});
it('should reconcile mutated DOM attributes', () => {
let check = p => render(<input type="checkbox" checked={p} />, scratch, scratch.lastChild),
value = () => scratch.lastChild.checked,
setValue = p => scratch.lastChild.checked = p;
check(true);
expect(value()).to.equal(true);
check(false);
expect(value()).to.equal(false);
check(true);
expect(value()).to.equal(true);
setValue(true);
check(false);
expect(value()).to.equal(false);
setValue(false);
check(true);
expect(value()).to.equal(true);
});
it('should render components', () => {
class C1 extends Component {
render() {
return <div>C1</div>;
}
}
sinon.spy(C1.prototype, 'render');
render(<C1 />, scratch);
expect(C1.prototype.render)
.to.have.been.calledOnce
.and.to.have.been.calledWithMatch({}, {})
.and.to.have.returned(sinon.match({ nodeName:'div' }));
expect(scratch.innerHTML).to.equal('<div>C1</div>');
});
it('should render components with props', () => {
const PROPS = { foo:'bar', onBaz:()=>{} };
let constructorProps;
class C2 extends Component {
constructor(props) {
super(props);
constructorProps = props;
}
render(props) {
return <div {...props} />;
}
}
sinon.spy(C2.prototype, 'render');
render(<C2 {...PROPS} />, scratch);
expect(constructorProps).to.deep.equal(PROPS);
expect(C2.prototype.render)
.to.have.been.calledOnce
.and.to.have.been.calledWithMatch(PROPS, {})
.and.to.have.returned(sinon.match({
nodeName: 'div',
attributes: PROPS
}));
expect(scratch.innerHTML).to.equal('<div foo="bar"></div>');
});
it('should render functional components', () => {
const PROPS = { foo:'bar', onBaz:()=>{} };
const C3 = sinon.spy( props => <div {...props} /> );
render(<C3 {...PROPS} />, scratch);
expect(C3)
.to.have.been.calledOnce
.and.to.have.been.calledWithExactly(PROPS)
.and.to.have.returned(sinon.match({
nodeName: 'div',
attributes: PROPS
}));
expect(scratch.innerHTML).to.equal('<div foo="bar"></div>');
});
it('should render nested functional components', () => {
const PROPS = { foo:'bar', onBaz:()=>{} };
const Outer = sinon.spy(
props => <Inner {...props} />
);
const Inner = sinon.spy(
props => <div {...props}>inner</div>
);
render(<Outer {...PROPS} />, scratch);
expect(Outer)
.to.have.been.calledOnce
.and.to.have.been.calledWithExactly(PROPS)
.and.to.have.returned(sinon.match({
nodeName: Inner,
attributes: PROPS
}));
expect(Inner)
.to.have.been.calledOnce
.and.to.have.been.calledWithExactly(PROPS)
.and.to.have.returned(sinon.match({
nodeName: 'div',
attributes: PROPS,
children: ['inner']
}));
expect(scratch.innerHTML).to.equal('<div foo="bar">inner</div>');
});
it('should re-render nested functional components', () => {
let doRender = null;
class Outer extends Component {
componentDidMount() {
let i = 1;
doRender = () => this.setState({ i: ++i });
}
componentWillUnmount() {}
render(props, { i }) {
return <Inner i={i} {...props} />;
}
}
sinon.spy(Outer.prototype, 'render');
sinon.spy(Outer.prototype, 'componentWillUnmount');
let j = 0;
const Inner = sinon.spy(
props => <div j={ ++j } {...props}>inner</div>
);
render(<Outer foo="bar" />, scratch);
// update & flush
doRender();
rerender();
expect(Outer.prototype.componentWillUnmount)
.not.to.have.been.called;
expect(Inner).to.have.been.calledTwice;
expect(Inner.secondCall)
.to.have.been.calledWithExactly({ foo:'bar', i:2 })
.and.to.have.returned(sinon.match({
attributes: {
j: 2,
i: 2,
foo: 'bar'
}
}));
expect(scratch.innerHTML).to.equal('<div j="2" foo="bar" i="2">inner</div>');
// update & flush
doRender();
rerender();
expect(Inner).to.have.been.calledThrice;
expect(Inner.thirdCall)
.to.have.been.calledWithExactly({ foo:'bar', i:3 })
.and.to.have.returned(sinon.match({
attributes: {
j: 3,
i: 3,
foo: 'bar'
}
}));
expect(scratch.innerHTML).to.equal('<div j="3" foo="bar" i="3">inner</div>');
});
it('should re-render nested components', () => {
let doRender = null;
class Outer extends Component {
componentDidMount() {
let i = 1;
doRender = () => this.setState({ i: ++i });
}
componentWillUnmount() {}
render(props, { i }) {
return <Inner i={i} {...props} />;
}
}
sinon.spy(Outer.prototype, 'render');
sinon.spy(Outer.prototype, 'componentDidMount');
sinon.spy(Outer.prototype, 'componentWillUnmount');
let j = 0;
class Inner extends Component {
constructor(...args) {
super();
this._constructor(...args);
}
_constructor() {}
componentDidMount() {}
componentWillUnmount() {}
render(props) {
return <div j={ ++j } {...props}>inner</div>;
}
}
sinon.spy(Inner.prototype, '_constructor');
sinon.spy(Inner.prototype, 'render');
sinon.spy(Inner.prototype, 'componentDidMount');
sinon.spy(Inner.prototype, 'componentWillUnmount');
render(<Outer foo="bar" />, scratch);
expect(Outer.prototype.componentDidMount).to.have.been.calledOnce;
// update & flush
doRender();
rerender();
expect(Outer.prototype.componentWillUnmount).not.to.have.been.called;
expect(Inner.prototype._constructor).to.have.been.calledOnce;
expect(Inner.prototype.componentWillUnmount).not.to.have.been.called;
expect(Inner.prototype.componentDidMount).to.have.been.calledOnce;
expect(Inner.prototype.render).to.have.been.calledTwice;
expect(Inner.prototype.render.secondCall)
.to.have.been.calledWith({ foo:'bar', i:2 })
.and.to.have.returned(sinon.match({
attributes: {
j: 2,
i: 2,
foo: 'bar'
}
}));
expect(scratch.innerHTML).to.equal('<div j="2" foo="bar" i="2">inner</div>');
// update & flush
doRender();
rerender();
expect(Inner.prototype.componentWillUnmount).not.to.have.been.called;
expect(Inner.prototype.componentDidMount).to.have.been.calledOnce;
expect(Inner.prototype.render).to.have.been.calledThrice;
expect(Inner.prototype.render.thirdCall)
.to.have.been.calledWith({ foo:'bar', i:3 })
.and.to.have.returned(sinon.match({
attributes: {
j: 3,
i: 3,
foo: 'bar'
}
}));
expect(scratch.innerHTML).to.equal('<div j="3" foo="bar" i="3">inner</div>');
});
});
| okmttdhr/preact-fork | test/browser/render.js | JavaScript | mit | 10,825 |
version https://git-lfs.github.com/spec/v1
oid sha256:f7df841464cae1b61b2fb488b6174926c0e0251ceddf1dd360b031ab9fb83c3c
size 4289
| yogeshsaroya/new-cdnjs | ajax/libs/angular.js/1.2.6/angular-sanitize.min.js | JavaScript | mit | 129 |
const React = require('react')
const Layout = require('./src/components/layout').default
// Logs when the client route changes
exports.onRouteUpdate = ({ location, prevLocation }) => {
const body = document.querySelector('body')
body.setAttribute('data-current-page', location.pathname)
body.setAttribute('data-previous-page', prevLocation ? prevLocation.pathname : '/')
}
// Wraps every page in a component
exports.wrapPageElement = ({ element, props }) => <Layout {...props}>{element}</Layout>
| yowainwright/yowainwright.github.io | gatsby-browser.js | JavaScript | mit | 504 |
import { handleActions } from 'redux-actions';
import { Map, OrderedMap } from 'immutable';
import initialState from '../store/initialState';
const App = handleActions({
WINDOW_LOADED: (state) => ({
...state,
windowLoaded: true
}),
CLOSE_LEGAL_HINT: (state) => ({
...state,
showLegalHint: false
}),
CONFIGURE_FIREBASE: (state, action) => ({
...state,
fireRef: action.payload
}),
SAVE_UID: (state, action) => ({
...state,
uid: action.payload
}),
SAVE_NAME: (state, action) => ({
...state,
userName: action.payload
}),
SAVE_USER_REF: (state, action) => ({
...state,
userRef: action.payload
}),
CONNECTED_TO_CHAT: (state) => ({
...state,
records: state.records.set('system:connected_to_chat', {
msg: '歡迎加入聊天室!',
user: 'system',
send_time: Date.now(),
user_color: '#ffc106'
})
}),
SET_MSG_TO_LIST: (state, action) => ({
...state,
records: OrderedMap(action.payload).map(record => ({ ...record, inActive: true }))
}),
ADD_MSG_TO_LIST: (state, action) => ({
...state,
records: state.records.set(action.payload.key, action.payload.value)
}),
REMOVE_MSG_FROM_LIST: (state, action) => ({
...state,
records: state.records.delete(action.payload)
}),
SET_WILL_SCROLL: (state, action) => ({
...state,
willScroll: action.payload
}),
SWITCH_MONITOR: (state, action) => ({
...state,
monitor: action.payload
}),
SET_PRESENCE: (state, action) => ({
...state,
presence: Map(action.payload)
}),
COUNTER_CHANGED: (state, action) => ({
...state,
onlineCounter: state.onlineCounter.update(
state.presence.get(action.payload.key), 1,
v => v - 1
).update(
action.payload.value.toString(), 0,
v => v + 1
),
presence: state.presence.set(action.payload.key, action.payload.value)
}),
COUNTER_ADDED: (state, action) => ({
...state,
onlineCounter: state.onlineCounter.update(
action.payload.value.toString(), 0,
v => v + 1
),
presence: state.presence.set(action.payload.key, action.payload.value)
}),
COUNTER_REMOVED: (state, action) => ({
...state,
onlineCounter: state.onlineCounter.update(
action.payload.value.toString(), 1,
v => v - 1
),
presence: state.presence.delete(action.payload.key)
}),
SET_PLAYER: (state, action) => ({
...state,
player: action.payload
}),
TOGGLE_SHOW_CHAT: (state) => ({
...state,
showChat: !state.showChat
}),
CONTROL_UP: state => ({
...state,
control: 'up'
}),
CONTROL_DOWN: state => ({
...state,
control: 'down'
}),
CONTROL_LEFT: state => ({
...state,
control: 'left',
controlStop: false
}),
CONTROL_RIGHT: state => ({
...state,
control: 'right',
controlStop: false
}),
CONTROL_STOP: state => ({
...state,
control: 'stop'
}),
CONTROL_PAUSE: state => ({
...state,
control: state.pause ? 'pause' : 'play'
}),
CONTROL_SET_PAUSE: state => ({
...state,
control: 'pause'
}),
CONTROL_SET_PLAY: state => ({
...state,
control: 'play'
}),
STOP_CONTROL: state => ({
...state,
controlStop: true
}),
CONTROL_INTERACT: state => ({
...state,
control: 'interact'
}),
ON_ERROR: (state, action) => ({
...state,
players: state.players.update(
action.payload.toString(),
r => r.set("error", true)
)
}),
ON_LOAD: (state, action) => ({
...state,
players: state.players.update(
action.payload.toString(),
r => r.set("error", false)
)
}),
UPDATE_FRAMES: (state, action) => ({
...state,
players: state.players.update(
action.payload.monitor.toString(),
r => r.update("frames", frames => frames.push(action.payload.src).takeLast(10))
)
}),
TOGGLE_LOADING: (state) => ({
...state,
loading: !state.loading
}),
PAUSE: (state) => ({
...state,
pause: !state.pause
}),
RELOAD: state => ({
...state,
reload: Math.floor(Math.random() * 10000).toString(),
lastReload: state.reload
})
}, initialState);
export default App;
| NTU-ArtFest22/Monitor-web | src/Reducers/index.js | JavaScript | mit | 4,611 |
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactcss = require('reactcss');
var _reactcss2 = _interopRequireDefault(_reactcss);
var SliderPointer = (function (_ReactCSS$Component) {
_inherits(SliderPointer, _ReactCSS$Component);
function SliderPointer() {
_classCallCheck(this, SliderPointer);
_get(Object.getPrototypeOf(SliderPointer.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(SliderPointer, [{
key: 'classes',
value: function classes() {
return {
'default': {
picker: {
width: '14px',
height: '14px',
borderRadius: '6px',
transform: 'translate(-7px, -1px)',
backgroundColor: 'rgb(248, 248, 248)',
boxShadow: '0 1px 4px 0 rgba(0, 0, 0, 0.37)'
}
}
};
}
}, {
key: 'render',
value: function render() {
return _react2['default'].createElement('div', { style: this.styles().picker });
}
}]);
return SliderPointer;
})(_reactcss2['default'].Component);
module.exports = SliderPointer; | 9o/react-color | lib/components/slider/SliderPointer.js | JavaScript | mit | 3,128 |
'use strict';
// Declare app level module which depends on views, and components
angular.module('collegeScorecard', [
'ngRoute',
'ui.bootstrap',
'nemLogging',
'uiGmapgoogle-maps',
'collegeScorecard.common',
'collegeScorecard.footer',
'collegeScorecard.home',
'collegeScorecard.schools',
'collegeScorecard.compare',
'collegeScorecard.details',
'collegeScorecard.selectedSchoolsDirective',
'collegeScorecard.scorecardDataService',
'collegeScorecard.schoolsListService',
'collegeScorecard.schoolDataTranslationService'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/home'});
}]);
| brianyamasaki/collegeScorecard | app/app.js | JavaScript | mit | 658 |
// © Copyright 2013 Paul Thomas <[email protected]>. All Rights Reserved.
// sf-virtual-repeat directive
// ===========================
// Like `ng-repeat` with reduced rendering and binding
//
(function(){
'use strict';
// (part of the sf.virtualScroll module).
var mod = angular.module('sf.virtualScroll');
var DONT_WORK_AS_VIEWPORTS = ['TABLE', 'TBODY', 'THEAD', 'TR', 'TFOOT'];
var DONT_WORK_AS_CONTENT = ['TABLE', 'TBODY', 'THEAD', 'TR', 'TFOOT'];
var DONT_SET_DISPLAY_BLOCK = ['TABLE', 'TBODY', 'THEAD', 'TR', 'TFOOT'];
// Utility to clip to range
function clip(value, min, max){
if( angular.isArray(value) ){
return angular.forEach(value, function(v){
return clip(v, min, max);
});
}
return Math.max(min, Math.min(value, max));
}
mod.directive('sfVirtualRepeat', ['$log', '$rootElement', function($log, $rootElement){
return {
require: '?ngModel',
transclude: 'element',
priority: 1000,
terminal: true,
compile: sfVirtualRepeatCompile
};
// Turn the expression supplied to the directive:
//
// a in b
//
// into `{ value: "a", collection: "b" }`
function parseRepeatExpression(expression){
var match = expression.match(/^\s*([\$\w]+)\s+in\s+([\S\s]*)$/);
if (! match) {
throw new Error("Expected sfVirtualRepeat in form of '_item_ in _collection_' but got '" +
expression + "'.");
}
return {
value: match[1],
collection: match[2]
};
}
// Utility to filter out elements by tag name
function isTagNameInList(element, list){
var t, tag = element.tagName.toUpperCase();
for( t = 0; t < list.length; t++ ){
if( list[t] === tag ){
return true;
}
}
return false;
}
// Utility to find the viewport/content elements given the start element:
function findViewportAndContent(startElement){
/*jshint eqeqeq:false, curly:false */
var root = $rootElement[0];
var e, n;
// Somewhere between the grandparent and the root node
for( e = startElement.parent().parent()[0]; e !== root; e = e.parentNode ){
// is an element
if( e.nodeType != 1 ) break;
// that isn't in the blacklist (tables etc.),
if( isTagNameInList(e, DONT_WORK_AS_VIEWPORTS) ) continue;
// has a single child element (the content),
if( e.childElementCount != 1 ) continue;
// which is not in the blacklist
if( isTagNameInList(e.firstElementChild, DONT_WORK_AS_CONTENT) ) continue;
// and no text.
for( n = e.firstChild; n; n = n.nextSibling ){
if( n.nodeType == 3 && /\S/g.test(n.textContent) ){
break;
}
}
if( n == null ){
// That element should work as a viewport.
return {
viewport: angular.element(e),
content: angular.element(e.firstElementChild)
};
}
}
throw new Error("No suitable viewport element");
}
// Apply explicit height and overflow styles to the viewport element.
//
// If the viewport has a max-height (inherited or otherwise), set max-height.
// Otherwise, set height from the current computed value or use
// window.innerHeight as a fallback
//
function setViewportCss(viewport){
var viewportCss = {'overflow': 'auto'},
style = window.getComputedStyle ?
window.getComputedStyle(viewport[0]) :
viewport[0].currentStyle,
maxHeight = style && style.getPropertyValue('max-height'),
height = style && style.getPropertyValue('height');
if( maxHeight && maxHeight !== '0px' ){
viewportCss.maxHeight = maxHeight;
}else if( height && height !== '0px' ){
viewportCss.height = height;
}else{
viewportCss.height = window.innerHeight;
}
viewport.css(viewportCss);
}
// Apply explicit styles to the content element to prevent pesky padding
// or borders messing with our calculations:
function setContentCss(content){
var contentCss = {
margin: 0,
padding: 0,
border: 0,
'box-sizing': 'border-box'
};
content.css(contentCss);
}
// TODO: compute outerHeight (padding + border unless box-sizing is border)
function computeRowHeight(element){
var style = window.getComputedStyle ? window.getComputedStyle(element)
: element.currentStyle,
maxHeight = style && style.getPropertyValue('max-height'),
height = style && style.getPropertyValue('height');
if( height && height !== '0px' && height !== 'auto' ){
$log.debug('Row height is "%s" from css height', height);
}else if( maxHeight && maxHeight !== '0px' && maxHeight !== 'none' ){
height = maxHeight;
$log.debug('Row height is "%s" from css max-height', height);
}else if( element.clientHeight ){
height = element.clientHeight+'px';
$log.debug('Row height is "%s" from client height', height);
}else{
throw new Error("Unable to compute height of row");
}
angular.element(element).css('height', height);
return parseInt(height, 10);
}
// The compile gathers information about the declaration. There's not much
// else we could do in the compile step as we need a viewport parent that
// is exculsively ours - this is only available at link time.
function sfVirtualRepeatCompile(element, attr, linker) {
var ident = parseRepeatExpression(attr.sfVirtualRepeat);
return {
post: sfVirtualRepeatPostLink
};
// ----
// Set up the initial value for our watch expression (which is just the
// start and length of the active rows and the collection length) and
// adds a listener to handle child scopes based on the active rows.
function sfVirtualRepeatPostLink(scope, iterStartElement, attrs){
var rendered = [];
var rowHeight = 0;
var scrolledToBottom = false;
var stickyEnabled = "sticky" in attrs;
var dom = findViewportAndContent(iterStartElement);
// The list structure is controlled by a few simple (visible) variables:
var state = 'ngModel' in attrs ? scope.$eval(attrs.ngModel) : {};
// - The index of the first active element
state.firstActive = 0;
// - The index of the first visible element
state.firstVisible = 0;
// - The number of elements visible in the viewport.
state.visible = 0;
// - The number of active elements
state.active = 0;
// - The total number of elements
state.total = 0;
// - The point at which we add new elements
state.lowWater = state.lowWater || 100;
// - The point at which we remove old elements
state.highWater = state.highWater || 300;
// - Keep the scroll event from constantly firing
state.threshold = state.threshold || 1;
var lastFixPos = 0;
// TODO: now watch the water marks
setContentCss(dom.content);
setViewportCss(dom.viewport);
// When the user scrolls, we move the `state.firstActive`
dom.viewport.bind('scroll', sfVirtualRepeatOnScroll);
// The watch on the collection is just a watch on the length of the
// collection. We don't care if the content changes.
scope.$watch(sfVirtualRepeatWatchExpression, sfVirtualRepeatListener, true);
// and that's the link done! All the action is in the handlers...
return;
// ----
// Apply explicit styles to the item element
function setElementCss (element) {
var elementCss = {
// no margin or it'll screw up the height calculations.
margin: '0'
};
if( !isTagNameInList(element[0], DONT_SET_DISPLAY_BLOCK) ){
// display: block if it's safe to do so
elementCss.display = 'block';
}
if( rowHeight ){
elementCss.height = rowHeight+'px';
}
element.css(elementCss);
}
function makeNewScope (idx, colExpr, containerScope) {
var childScope = containerScope.$new(),
collection = containerScope.$eval(colExpr);
childScope[ident.value] = collection[idx];
childScope.$index = idx;
childScope.$first = (idx === 0);
childScope.$last = (idx === (collection.length - 1));
childScope.$middle = !(childScope.$first || childScope.$last);
childScope.$watch(function updateChildScopeItem(){
collection = containerScope.$eval(colExpr);
childScope[ident.value] = collection[idx];
});
return childScope;
}
function addElements (start, end, colExpr, containerScope, insPoint) {
var frag = document.createDocumentFragment();
var newElements = [], element, idx, childScope;
for( idx = start; idx !== end; idx ++ ){
childScope = makeNewScope(idx, colExpr, containerScope);
element = linker(childScope, angular.noop);
setElementCss(element);
newElements.push(element);
frag.appendChild(element[0]);
}
insPoint.after(frag);
return newElements;
}
function recomputeActive() {
// We want to set the start to the low water mark unless the current
// start is already between the low and high water marks.
var start = clip(state.firstActive, state.firstVisible - state.lowWater, state.firstVisible - state.highWater);
// Similarly for the end
var end = clip(state.firstActive + state.active,
state.firstVisible + state.visible + state.lowWater,
state.firstVisible + state.visible + state.highWater );
state.firstActive = clip(start, 0, state.total - state.visible - state.lowWater);
state.active = Math.min(end, state.total) - state.firstActive;
}
function sfVirtualRepeatOnScroll(evt){
if( !rowHeight ){
return;
}
var diff = Math.abs(evt.target.scrollTop - lastFixPos);
if(diff > (state.threshold * rowHeight)){
// Enter the angular world for the state change to take effect.
scope.$apply(function(){
state.firstVisible = Math.floor(evt.target.scrollTop / rowHeight);
state.visible = Math.ceil(dom.viewport[0].clientHeight / rowHeight);
$log.debug('scroll to row %o', state.firstVisible);
var sticky = evt.target.scrollTop + evt.target.clientHeight >= evt.target.scrollHeight;
recomputeActive();
$log.debug(' state is now %o', state);
$log.debug(' sticky = %o', sticky);
});
lastFixPos = evt.target.scrollTop;
}
}
function sfVirtualRepeatWatchExpression(scope){
var coll = scope.$eval(ident.collection);
if( coll && coll.length !== state.total ){
state.total = coll.length;
recomputeActive();
}
return {
start: state.firstActive,
active: state.active,
len: coll ? coll.length : 0
};
}
function destroyActiveElements (action, count) {
var dead, ii, remover = Array.prototype[action];
for( ii = 0; ii < count; ii++ ){
dead = remover.call(rendered);
dead.scope().$destroy();
dead.remove();
}
}
// When the watch expression for the repeat changes, we may need to add
// and remove scopes and elements
function sfVirtualRepeatListener(newValue, oldValue, scope){
var oldEnd = oldValue.start + oldValue.active,
newElements;
if( newValue === oldValue ){
$log.debug('initial listen');
newElements = addElements(newValue.start, oldEnd, ident.collection, scope, iterStartElement);
rendered = newElements;
if( rendered.length ){
rowHeight = computeRowHeight(newElements[0][0]);
}
}else{
var newEnd = newValue.start + newValue.active;
var forward = newValue.start >= oldValue.start;
var delta = forward ? newValue.start - oldValue.start
: oldValue.start - newValue.start;
var endDelta = newEnd >= oldEnd ? newEnd - oldEnd : oldEnd - newEnd;
var contiguous = delta < (forward ? oldValue.active : newValue.active);
$log.debug('change by %o,%o rows %s', delta, endDelta, forward ? 'forward' : 'backward');
if( !contiguous ){
$log.debug('non-contiguous change');
destroyActiveElements('pop', rendered.length);
rendered = addElements(newValue.start, newEnd, ident.collection, scope, iterStartElement);
}else{
if( forward ){
$log.debug('need to remove from the top');
destroyActiveElements('shift', delta);
}else if( delta ){
$log.debug('need to add at the top');
newElements = addElements(
newValue.start,
oldValue.start,
ident.collection, scope, iterStartElement);
rendered = newElements.concat(rendered);
}
if( newEnd < oldEnd ){
$log.debug('need to remove from the bottom');
destroyActiveElements('pop', oldEnd - newEnd);
}else if( endDelta ){
var lastElement = rendered[rendered.length-1];
$log.debug('need to add to the bottom');
newElements = addElements(
oldEnd,
newEnd,
ident.collection, scope, lastElement);
rendered = rendered.concat(newElements);
}
}
if( !rowHeight && rendered.length ){
rowHeight = computeRowHeight(rendered[0][0]);
}
dom.content.css({'padding-top': newValue.start * rowHeight + 'px'});
}
dom.content.css({'height': newValue.len * rowHeight + 'px'});
if( scrolledToBottom && stickyEnabled ){
dom.viewport[0].scrollTop = dom.viewport[0].clientHeight + dom.viewport[0].scrollHeight;
}
}
}
}
}]);
}());
| looker/angular-virtual-scroll | src/virtual-repeat.js | JavaScript | mit | 14,764 |
require('../helpers');
const assert = require('assert');
const ironium = require('../../src');
const Promise = require('bluebird');
describe('processing', ()=> {
const errorCallbackQueue = ironium.queue('error-callback');
const errorPromiseQueue = ironium.queue('error-promise');
const errorGeneratorQueue = ironium.queue('error-generator');
function untilSuccessful(done) {
ironium.runOnce((error)=> {
if (error)
setTimeout(()=> untilSuccessful(done));
else
done();
});
}
describe('with callback error', ()=> {
// First two runs should fail, runs ends at 3
let runs = 0;
before(()=> {
errorCallbackQueue.eachJob((job, callback)=> {
runs++;
if (runs > 2)
callback();
else
callback(new Error('fail'));
});
});
before(()=> errorCallbackQueue.queueJob('job'));
before(untilSuccessful);
it('should repeat until processed', ()=> {
assert.equal(runs, 3);
});
});
describe('with rejected promise', ()=> {
// First two runs should fail, runs ends at 3
let runs = 0;
before(()=> {
errorPromiseQueue.eachJob(()=> {
runs++;
if (runs > 2)
return Promise.resolve();
else
return Promise.reject(new Error('fail'));
});
});
before(()=> errorPromiseQueue.queueJob('job'));
before(untilSuccessful);
it('should repeat until processed', ()=> {
assert.equal(runs, 3);
});
});
describe('with generator error', ()=> {
// First two runs should fail, runs ends at 3
let runs = 0;
before(()=> {
errorGeneratorQueue.eachJob(function*() {
runs++;
switch (runs) {
case 1: {
throw new Error('fail');
}
case 2: {
yield Promise.reject(Error('fail'));
break;
}
}
});
});
before(()=> errorGeneratorQueue.queueJob('job'));
before(untilSuccessful);
it('should repeat until processed', ()=> {
assert.equal(runs, 3);
});
});
});
| djanowski/ironium | test/queues/error_test.js | JavaScript | mit | 2,127 |
Subsets and Splits