code stringlengths 2 1.05M |
|---|
module.exports = {
name: 'oreo-icons'
} |
var apiRecipeConfig = null;
var waitingForWords = false;
var apiRecipeConfigLoaded = false;
var shortcutManager = {
hadShortcut: false,
createShortcut: function(recipe) {
return false;
},
hasShortcutCalled: function() {
return false;
},
execExtra: function() {
return false;
}
};
var voiceManager = {
listener: null,
listening: false,
setted: false,
disabled: false,
say: function(text){
var msg = new SpeechSynthesisUtterance();
msg.volume = 1; // 0 to 1
msg.rate = 1; // 0.1 to 10
msg.pitch = 2; //0 to 2
msg.text = text;
msg.lang = 'fr-FR';
speechSynthesis.speak(msg);
}
};
if (typeof hostApi == 'undefined' || null == hostApi) {
hostApi = 'http://'+window.location.host;
}
var app = angular.module('app', ['ngTouch', 'pr.longpress']).service('currentTag', function(){
var currentTag = 'all';
return {
getCurrentTag: function() {
return currentTag;
},
setCurrentTag: function(tag){
currentTag = tag;
}
};
});
|
'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; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var Immutable = require('immutable');
var Spec = (function () {
function Spec(root) {
_classCallCheck(this, Spec);
this._root = root;
}
_createClass(Spec, [{
key: 'toJS',
value: function toJS() {
return this._root.toJS();
}
}]);
return Spec;
})();
Spec.FileExtension = {
GHERKIN: '.feature'
};
module.exports = Spec; |
/**
* Created by 斌 on 2017/4/19.
*/
import {UPDATE_LOADING_STATUS, SHOW_TOAST, HIDE_TOAST, DESTINATION, TEMP_HIDING} from '../../lib/constant'
import _ from 'lodash'
export default {
state: {
isLoading: false,
toast: {
value: false,
time: 1000,
width: '80%',
type: 'text',
position: 'default',
text: ''
},
destination: {},
tempHiding: false
},
mutations: {
[UPDATE_LOADING_STATUS] (state, payload) {
state.isLoading = payload.isLoading
},
[SHOW_TOAST] (state, payload) {
if (_.isString(payload)) {
state.toast = _.assign(state.toast, {value: true, text: payload})
} else {
state.toast = _.assign(state.toast, payload, {value: true})
}
},
[HIDE_TOAST] (state) {
state.toast.value = false
},
[DESTINATION] (state, destination) {
state.destination = destination
},
[TEMP_HIDING] (state, payload) {
state.tempHiding = payload
}
}
}
|
var http = require("http");
function getWeatherbyID(cityID, callback) {
var options = {
//http:///data/2.5/weather?id=4487042&units=imperial
host: "api.openweathermap.org",
//path: "/data/2.5/weather?id=" + cityID + "&units=imperial",
path: "/data/2.5/weather?q=" + cityID + "&units=imperial",
method: "GET",
headers: {
"user-agent": "Node.js"
}
};
var request = http.request(options, function(res) {
//If large data sometimes API will send in chunks
var body = "";
//Each time data is sent which could be a couple times
//this event is caught with the data event
res.on("data", function(chunk) {
body += chunk.toString("utf8");
});
//After all the responses have been sent
//an end event will emit
res.on('end', function() {
var json = JSON.parse(body);
callback(json); //Calls the callback function provided
});
});
request.end();
}
module.exports.getWeatherbyID = getWeatherbyID;
|
/**
* Here I'm redirect all the server process in server/server.js
* There I will execute all the server stuff.
* autor: mauromandracchia@gmail.com
*
*/
var server = require('./server/server');
server.init();
|
/*
The Quarry Desktop App
*/
angular
.module('quarrydesktop', ['quarry.core', 'quarry.ui', 'quarry.app.digger'])
.config(['$stateProvider', '$routeProvider', '$urlRouterProvider',
function ($stateProvider, $routeProvider, $urlRouterProvider) {
$urlRouterProvider
//.when('/c?id', '/contacts/:id')
.otherwise('/loading');
$stateProvider
.state('loading', {
url: '/loading',
templateUrl: 'views/loading.html',
controller:
['$scope', '$state', '$location', function ($scope, $state, $location){
$scope.init(function(){
$location.path('/project/' + $scope.currentproject.id());
})
}]
})
.state('welcome', {
url: '/welcome',
templateUrl: 'views/welcome.html',
controller:
['$scope', '$state', function ($scope, $state){
}]
})
.state('project', {
url: '/project/:projectid',
templateUrl: 'views/project.html',
controller:
['$scope', '$state', '$location', function ($scope, $state, $location){
$scope.init(function(){
})
}]
})
.state('digger', {
url: '/digger/:projectid',
templateUrl: 'views/digger.html',
controller:'DiggerCtrl'
})
}
])
/*
THE MAIN CONTROLLER
*/
.controller('MainCtrl', ['$scope', '$warehouse', '$location', '$digger', function($scope, $warehouse, $location, $digger){
/*
warehouse and user
*/
var warehouse = $scope.warehouse = $warehouse;
var user = $scope.user = $warehouse.user;
$scope.authurl = '/auth';
$scope.hasuser = $scope.user.full();
/*
projects
*/
var projects = $scope.projectlist = [];
var projects_loaded = false;
var projectdigger = $scope.projectdigger = $digger({
$scope:$scope,
})
/*
get things kicked off by loading the projects
*/
$scope.init = function(done){
if(!$scope.hasuser){
$location.path('/welcome');
return false;
}
if(projects_loaded){
done && done(warehouse);
}
else{
done && $scope.load_projects(done);
}
projects_loaded = true;
return true;
}
/*
get the projects loaded for the topbar
*/
$scope.load_projects = function(done){
if(!$scope.user.full()){
return;
}
$scope.user('project').ship(function(loadedprojects){
$scope.$apply(function(){
$scope.projectlist = loadedprojects.containers();
var currentproject = loadedprojects.find('#' + $scope.user.attr('projectid'));
if(!currentproject.full()){
currentproject = loadedprojects.eq(0);
}
$scope.currentproject = currentproject;
currentproject('blueprint').ship(function(blueprints){
$scope.$apply(function(){
$scope.projectblueprints = blueprints;
done && done(warehouse);
})
})
})
})
}
$scope.$on('loadproject', function(ev, project){
$scope.load_project(project);
})
$scope.load_projects();
}])
/*
THE DIGGER CONTROLLER
*/
.controller('DiggerCtrl', ['$scope', '$state', '$location', '$warehouse', '$http', '$templateCache', '$dialog', '$digger', function ($scope, $state, $location, $warehouse, $http, $templateCache, $dialog, $digger){
/*
these can be augmented by project blueprints also
*/
var baseblueprints = $warehouse.create([{
meta:{
tagname:'folder',
icon:'box.png'
},
attr:{
name:'Folder'
}
},{
meta:{
tagname:'container',
icon:'container.png',
leaf:true
},
attr:{
name:'Container'
}
},{
meta:{
tagname:'blueprint',
icon:'cube_molecule.png'
},
attr:{
name:'Blueprint'
}
}])
/*
this loads the HTML from the external templates
*/
baseblueprints.each(function(blueprint){
if(blueprint.attr('path')){
$http
.get(blueprint.attr('path'), {cache:$templateCache})
.success(function(data){
blueprint.attr('html', data);
})
}
})
var digger = $scope.digger = $digger({
$scope:$scope,
render:function(container){
if(!container){
return null;
}
return null;
},
create:function(container, done){
console.log('-------------------------------------------');
console.log('-------------------------------------------');
console.log('-------------------------------------------');
if(container.tagname()=='blueprint'){
alert('blueprint')
}
done(container);
},
/*
the blueprints we have for the digger
*/
baseblueprints:baseblueprints
})
/*
get the user loaded then assign the warehouse an ting
*/
$scope.init(function(warehouse){
/*
get connected to the actual database the current project points to
*/
var projectwarehouse = warehouse.connect('/project/' + $scope.currentproject.id());
projectwarehouse.attr('name', $scope.currentproject.title());
//var iconwarehouse = warehouse.connect('file:/icons');
digger.setwarehouse(projectwarehouse);
})
}])
/*
The icon factory
*/
$quarry.Proto.prototype.icon = function(){
var icon = '/files/icon/'
if(this.meta('icon')){
return icon + this.meta('icon');
}
else{
return '/files/icon/box.png';
}
} |
$("#mydiv").html('<object data="http://google.com.au"/>');
|
(function () {
"use strict";
angular.module('ngSeApi').factory('seaPatch', ['SeaRequest', 'seaPatchContainer', 'seaPatchViewFilter', 'seaPatchHelper', 'seaPatchTask',
function seaUser(SeaRequest, seaPatchContainer, seaPatchViewFilter, seaPatchHelper, seaPatchTask) {
var request = new SeaRequest(seaPatchHelper.getUrl('patch/customers')),
requestCategories = new SeaRequest(seaPatchHelper.getUrl('patch/{customerId}/categories'));
function listCustomers() {
return request.get();
}
function listCategories(customerId) {
return requestCategories.get({ customerId: customerId });
}
return {
customer: {
list: listCustomers
},
category: {
list: function (customerId) {
return listCategories(customerId)
},
},
container: seaPatchContainer,
viewFilter: seaPatchViewFilter,
task: seaPatchTask,
};
}]);
})(); |
var DAL = require('../db/DAL').DAL;
var debug = require('debug')('scorm-profile-viewer:util');
module.exports = {
mustBeLoggedIn: function(req, res, next) {
if (req.user) return next();
else res.redirect('/users/login?r=' + encodeURIComponent(req.originalUrl));
},
testAuth: function (req, res, next) {
var auth = req.get("authorization");
if (!auth) {
res.set("WWW-Authenticate", "Basic realm=\"Authorization Required\"");
return res.status(401).send("Authorization Required");
} else {
var credentials = new Buffer(auth.split(" ").pop(), "base64").toString("ascii").split(":");
var username = credentials[0],
password = credentials[1];
DAL.getUser(username, function (err, user) {
debug(username, user._id, user.username);
if (err || !user) {
debug('got error in auth verification - getUser');
return res.status(403).send("Access Denied (incorrect credentials)");
}
DAL.validatePassword(user, password, function (err, valid) {
if (err || !valid) {
debug('invalid password on existing user');
return res.status(403).send("Access Denied (incorrect credentials)");
} else {
debug('valid password on existing user -- all good')
req.user = user;
return next();
}
});
});
}
},
testForParams: function (params) {
return function (req, res, next) {
params.forEach((param) => {
if (!req.query[param]) return res.status(400).send(`Bad Request - missing ${param} param`);
});
return next();
};
}
}
|
class RecoverableError extends Error {
constructor(...args) {
super(...args);
this.name = this.constructor.name;
}
}
class UnrecoverableError extends Error {
constructor(...args) {
super(...args);
this.name = this.constructor.name;
this.unrecoverable = true;
}
}
class SharpError extends UnrecoverableError {}
class InvalidContentTypeError extends UnrecoverableError {}
class InvalidHttpResponseError extends RecoverableError {}
class RedisError extends RecoverableError {}
class InvalidUrl extends UnrecoverableError {}
class HttpRequestError extends RecoverableError {}
class InvalidTask extends UnrecoverableError {}
class LockExistsError extends Error {
constructor(message) {
super(message);
this.name = this.constructor.name;
this.code = 'ELOCKEXISTS';
}
}
module.exports = {
SharpError,
InvalidContentTypeError,
InvalidHttpResponseError,
RedisError,
LockExistsError,
InvalidUrl,
HttpRequestError,
InvalidTask,
};
|
import map from 'funny-map'
/**
* Partial functions.
*
* @param {Function} fn Function to partial.
* @return {Function} Partially implemented function.
*/
export default function partial (fn, ...partialArgs) {
if (!partialArgs.length) {
return fn
}
return (...args) => {
let index = 0
return fn(...map(arg => arg === undefined ? args[index++] : arg, partialArgs))
}
}
|
var cout = require('../cout.js');
cout.config({
//should only display level 'warn' and 'silly'
cout: ['normal', 'warn'],
timestamp: {
locale: 'ja',
}
});
cout("Hello", "World", {
hello: "world"
}, ['hello', 'world'], 1, 2, 3).end();
cout(['one', 'two', 2], {
hello: "world"
}, ['hello', 'world']).warn({
bg: 'black',
style: 'bold'
});
cout(['one', 'two', 2], {
hello: "world"
}, ['hello', 'world']).data();
cout(['one', 'two', 2], {
hello: "world"
}, ['hello', 'world']).debug();
cout(['one', 'two', 2], {
hello: "world"
}, ['hello', 'world']).silly({
bg: 'white'
});
cout(cout.kawari('I\'m known as %s', "iwatakeshi")).warn();
|
/*
*
* login-register modal
* Autor: Creative Tim
* Web-autor: creative.tim
* Web script: http://creative-tim.com
*
*/
function showRegisterForm(){
$('.loginBox').fadeOut('fast',function(){
$('.registerBox').fadeIn('fast');
$('.login-footer').fadeOut('fast',function(){
$('.register-footer').fadeIn('fast');
});
$('.modal-title').html(localization('Register','Inscription'));
});
$('.error').removeClass('alert alert-danger').html('');
}
function showLoginForm(){
$('#loginModal .registerBox').fadeOut('fast',function(){
$('.loginBox').fadeIn('fast');
$('.register-footer').fadeOut('fast',function(){
$('.login-footer').fadeIn('fast');
});
$('.modal-title').html(localization('Login','Connection'));
});
$('.error').removeClass('alert alert-danger').html('');
}
function openLoginModal(){
showLoginForm();
setTimeout(function(){
$('#loginModal').modal('show');
}, 230);
}
function openRegisterModal(){
showRegisterForm();
setTimeout(function(){
$('#loginModal').modal('show');
}, 230);
}
function loginAjax(){
$.ajax({
type : 'POST',
url : 'login.php',
data : $('.loginBox form').serialize(),
encode : true
}).done(function( data ) {
if(data == 1){
window.location.reload();
} else {
shakeModal([localization(
"Invalid email/password combination",
"Identifiant ou mot de passe invalide"
)]);
}
});
}
function registerAjax(){
$.ajax({
type : 'POST',
url : 'sign-up.php',
data : $('.registerBox form').serialize(),
dataType : 'json',
encode : true
}).done(function( data ) {
if(data['success']){
window.location.href = 'index.php?signedup';
} else {
shakeModal(data.error);
}
});
}
function shakeModal(errors){
$('#loginModal .modal-dialog').addClass('shake');
$('.error').addClass('alert alert-danger').html('<ul><li>'+errors.join('</li><li>')+'</li></ul>');
$('input[type="password"]').val('');
setTimeout( function(){
$('#loginModal .modal-dialog').removeClass('shake');
}, 1000 );
}
|
var searchData=
[
['udpconnection',['UdpConnection',['../classcrap_1_1_udp_connection.html#a795feae71a319cc5a82ea1f610e4a494',1,'crap::UdpConnection']]],
['udperrorgenerator',['UdpErrorGenerator',['../classcrap_1_1_udp_error_generator.html#aa20c6432764f4e0498decd46e19ec6c2',1,'crap::UdpErrorGenerator']]],
['udpnetwork',['UdpNetwork',['../classcrap_1_1_udp_network.html#adcb731ce23b46c95ba91a7acb42614dc',1,'crap::UdpNetwork']]],
['udpreliability',['UdpReliability',['../classcrap_1_1_udp_reliability.html#aee71353a45b3fe47dca9a8ed738364c8',1,'crap::UdpReliability']]],
['unload',['unload',['../classcrap_1_1_plugin_manager.html#a8d7bf2d50979c84ccd4c669e1fc89f16',1,'crap::PluginManager']]],
['unloadall',['unloadAll',['../classcrap_1_1_plugin_manager.html#a74669b5ebf7c9fe9f8c48abefc45f426',1,'crap::PluginManager']]],
['unlock',['unlock',['../structcrap_1_1no__mutex.html#a56d77194a18047876ad2cfcb3d9c39be',1,'crap::no_mutex::unlock()'],['../structcrap_1_1atomic__mutex.html#a1c239a2b3ceef7083189c3523ad5df52',1,'crap::atomic_mutex::unlock()'],['../classcrap_1_1system__mutex.html#a47051096449f83f99980d2d2da16fc9d',1,'crap::system_mutex::unlock()']]],
['unregistercommand',['unregisterCommand',['../classcrap_1_1_network_command_queue.html#a24f8c08337b976139692fdf5ebfb29e3',1,'crap::NetworkCommandQueue']]],
['unregisterfromevents',['unregisterFromEvents',['../classcrap_1_1_udp_connection.html#ae5aab27d269cef91ce602095b6f77c51',1,'crap::UdpConnection::unregisterFromEvents(C *instance)'],['../classcrap_1_1_udp_connection.html#aaf7813466db45a74f0c040c55bcf565a',1,'crap::UdpConnection::unregisterFromEvents(void)'],['../classcrap_1_1_udp_network.html#a0c5c0732d1ec608c9347ad4393179d36',1,'crap::UdpNetwork::unregisterFromEvents(C *instance)'],['../classcrap_1_1_udp_network.html#af5129d1be9ba7226136d0e92472c1c69',1,'crap::UdpNetwork::unregisterFromEvents(void)']]],
['unsignedattribute',['UnsignedAttribute',['../classtinyxml2_1_1_x_m_l_element.html#aa5a41367b5118acec42a87f5f94cec2d',1,'tinyxml2::XMLElement']]],
['unsignedvalue',['UnsignedValue',['../classtinyxml2_1_1_x_m_l_attribute.html#a4c7a179907836a136d1ce5acbe53389d',1,'tinyxml2::XMLAttribute']]],
['untracked',['Untracked',['../classtinyxml2_1_1_mem_pool_t.html#a524b90d0edeac41964c06510757dce0f',1,'tinyxml2::MemPoolT']]],
['update',['update',['../classcrap_1_1_directory_listener.html#a03a5bf5dd2dbc0f1c910c6e7f20976b4',1,'crap::DirectoryListener::update()'],['../classcrap_1_1_task_manager.html#a60e539f23acdd395d15fad88e0f77d14',1,'crap::TaskManager::update()'],['../classcrap_1_1_udp_connection.html#affad8946093cb93e228af5452cee5bee',1,'crap::UdpConnection::update()'],['../classcrap_1_1_udp_network.html#a2da693f836a8ae12aa0d2a21ab4b25e2',1,'crap::UdpNetwork::update()'],['../classcrap_1_1_udp_reliability.html#ae4004c16b0b1dc5dcfffeb8af065e485',1,'crap::UdpReliability::update()'],['../classcrap_1_1_input_manager.html#a5aa76f41add8212ba22bb7c88d3a28e8',1,'crap::InputManager::update()']]]
];
|
(function() {
var canvas = document.querySelector('#canvas');
var context = canvas.getContext('2d');
// Tracer un rectangle de 50 sur 80 pixels
// rectangle plein
// context.fillStyle = "gold";
// context.fillRect(50, 35, 50, 80);
//ou vide
context.lineWidth = "5";
context.strokeStyle = "gold";
context.strokeRect(50, 35, 50, 80);
context.fillStyle = "rgba(23, 145, 167, 0.5)";
context.fillRect(40, 25, 40, 40);
context.clearRect(45, 40, 30, 10);
// Les chemins simples
context.strokeStyle = "rgb(23, 145, 167)";
context.beginPath();
context.moveTo(20, 20); // 1er point
context.lineTo(130, 20); // 2e point
context.lineTo(130, 50); // 3e
context.lineTo(75, 130); // 4e
context.lineTo(20, 50); // 5e
context.closePath(); // On relie le 5e au 1er
context.stroke();
// Les arcs
context.beginPath(); // Le cercle extérieur
context.arc(75, 75, 50, 0, Math.PI * 2); // Ici le calcul est simplifié
context.stroke();
context.beginPath(); // La bouche, un arc de cercle
context.arc(75, 75, 40, 0, Math.PI); // Ici aussi
context.fill();
context.beginPath(); // L'œil gauche
context.arc(55, 70, 20, (Math.PI / 180) * 220, (Math.PI / 180) * 320);
context.stroke();
context.beginPath(); // L'œil droit
context.arc(95, 70, 20, (Math.PI / 180) * 220, (Math.PI / 180) * 320);
context.stroke();
context.beginPath(); // La bouche, un arc de cercle
context.arc(75, 75, 40, 0, Math.PI);
context.fill();
context.beginPath(); // Le cercle extérieur
context.arc(75, 75, 50, 0, Math.PI * 2);
context.moveTo(41, 58); // L'œil gauche
context.arc(55, 70, 20, (Math.PI / 180) * 220, (Math.PI / 180) * 320);
context.moveTo(81, 58); // L'œil droit
context.arc(95, 70, 20, (Math.PI / 180) * 220, (Math.PI / 180) * 320);
context.stroke();
//Image
var zozor = new Image();
zozor.src = 'zozor.png'; // Image de 80x80 pixels
context.drawImage(zozor, 35, 35);
})();
|
var fs = require('fs'),
request = require('request');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
const GHOST_ENDPOINT = {
protocol: 'https:',
host: '52.49.91.111',
port: 8443,
path: '/ghost'
};
const GHOST_URL = GHOST_ENDPOINT.protocol + '//' + GHOST_ENDPOINT.host + ':' +
GHOST_ENDPOINT.port + GHOST_ENDPOINT.path;
var base64Image = '';
var bytesRead = 0;
var getImage = function(callback) {
var options = {
url: GHOST_URL,
headers: {
'Range': `bytes=${bytesRead}-${bytesRead + 12}`
}
}
request.get(options, function(err, res, body){
if (err) {
throw err;
}
base64Image += body;
// bytesRead += parseInt(res.headers['content-length']); // Can be wrong data
bytesRead += body.length;
if (res.statusCode === 206) {
getImage(callback);
} else {
callback();
}
});
};
getImage(function() {
var buffer = Buffer.from(base64Image, 'base64');
var wstream = fs.createWriteStream('ghost.png');
wstream.write(buffer);
wstream.end();
console.log('done with ' + bytesRead + ' bytes read');
});
// After watching the image, with code 4017-8120, we request that Range, with HTTP/2.0
var options = {
protocol: GHOST_ENDPOINT.protocol,
host: GHOST_ENDPOINT.host,
port: GHOST_ENDPOINT.port,
path: GHOST_ENDPOINT.path,
headers: {
'Range': `bytes=4017-8120`
}
}
var request2 = require('http2').get(options);
// Ignore the response
request2.on('response', function(response) {
// Ignore
//response.pipe(process.stdout);
});
// Receive push streams
request2.on('push', function(pushRequest) {
pushRequest.on('response', function(pushResponse) {
pushResponse.pipe(process.stdout);
pushResponse.on('finish', process.exit);
});
});
|
'use strict';
var superagent = require('superagent');
var assert = require('chai').assert;
var tools = require('../test-tools');
var config = tools.config;
var dataLoader = require('../../test-data/data-loader');
var Category = tools.Category;
var User = tools.User;
var categoriesData = dataLoader.categoriesData;
var handleResponse = tools.handleResponse;
var loadCategories = dataLoader.loadCategories;
describe('Category API', function () {
it('can get all categories', function (done) {
// load local categories test data to server database
loadCategories(Category, categoriesData, function (err, categories) {
assert.equal(categories.length, categoriesData.length);
var url = config.TEST.SERVER + 'api/blu-store/categories';
// send get request to get all categories
superagent.get(url).end(handleResponse(categories, null, done));
});
});
it('can add new category', function (done) {
dataLoader.loginAdmin(User, function (err, user) {
assert.isNotOk(err);
assert.isOk(user.token);
var url = config.TEST.SERVER + 'api/blu-store/categories';
var catObj = {
name: "just another category 0909"
};
// add category without parent
superagent
.post(url)
.set('x-access-token', user.token)
.send(catObj)
.end(handleResponse(catObj, ['name'], function (err, res) {
// add category with parent
var catObj2 = { name: 'cate object two', parent: catObj._id };
superagent
.post(url)
.set('x-access-token', user.token)
.send(catObj2)
.end(handleResponse(catObj2, ['parent'], done));
}));
});
});
});
|
'use strict';
/***********************
* Test dependencies
***********************/
const Promise = require('bluebird');
const path = require('path');
const fs = Promise.promisifyAll(require('fs'));
const TranscriptParser = require('../app.js');
const chai = require('chai');
const should = chai.should();
const Readable = require('stream').Readable;
const TEST_DIR = path.join(__dirname, 'transcripts');
const EXPECTED_DIR = path.join(__dirname, 'expected');
/***********************
* Tests
***********************/
describe('TranscriptParser', function() {
describe('#parseStream()', function() {
const tp = new TranscriptParser();
it('should parse a transcript correctly', function(done) {
readSample(1)
.bind({})
.then(info => {
const stream = fs.createReadStream(path.join(TEST_DIR, '1.txt'), 'utf8');
return Promise.fromCallback(cb => tp.parseStream(stream, cb));
}).then(result => {
this.result = result;
return readExpected(1);
}).then(expected => {
this.result.should.be.eql(JSON.parse(expected));
done();
})
.catch(e => done(e));
});
it('should use the newLine regex', function(done) {
const rs = new Readable();
const parser = new TranscriptParser({
regex: { newLine: /\|/ },
});
rs.push('A: Testing.\nLF.|B: OK.\r\nCR.');
rs.push(null);
parser.parseStream(rs, (err, parsed) => {
if(err) return done(err);
const ideal = {
speaker: {
A: ['Testing.\nLF.'],
B: ['OK.\r\nCR.']
},
order: ['A', 'B']
};
parsed.should.eql(ideal);
done();
});
});
it('should respect the blacklist setting', function(done) {
const rs = new Readable();
const parser = new TranscriptParser({blacklist: [ 'B' ]});
const testStr = 'A: Blah blah blah\nB: This should be\nignored\nA: Blah blah';
rs.push(testStr);
rs.push(null);
Promise.fromCallback(cb => parser.parseStream(rs, cb))
.then(parsed => {
parsed.should.eql({
speaker: {
A: ['Blah blah blah', 'Blah blah'],
},
order: ['A', 'A']
});
done();
});
});
it('should respect the removeUnknownSpeakers setting', function(done) {
const rs = new Readable();
const parser = new TranscriptParser({removeUnknownSpeakers: true});
const testStr = 'The quick [brown] fox jumps over the (lazy) dog.';
rs.push(testStr);
rs.push(null);
parser.parseStream(rs,
(err, result) => {
if(err) return done(err);
result.should.eql({
speaker: {},
order: []
});
done();
}
);
});
it('should respect the removeActions setting', function(done) {
const rs = new Readable();
const parser = new TranscriptParser({removeActions: false});
const testStr = 'PERSON A: Hello, (PAUSES) (DRINKS WATER) my name is Bob.(APPLAUSE)';
rs.push(testStr);
rs.push(null);
parser.parseStream(rs, (err, result) => {
if(err) return done(err);
result.speaker.should.eql({
'PERSON A': ['Hello, (PAUSES) (DRINKS WATER) my name is Bob.(APPLAUSE)']
});
done();
});
});
it('should respect the removeTimestamps setting', function(done) {
const parser = new TranscriptParser({removeAnnotations: false, removeTimestamps: false});
const rs = new Readable();
const testStr = '[20:20:34] BERMAN: [2:1:41] The...';
rs.push(testStr);
rs.push(null);
parser.parseStream(rs, (err, result) => {
if(err) return done(err);
result.speaker.should.eql({'[20:20:34] BERMAN': [ '[2:1:41] The...' ]});
done();
});
});
it('should be able to remove timestamps without removing annotations', function(done) {
const parser = new TranscriptParser({removeAnnotations: false, removeTimestamps: true});
const rs = new Readable();
const testStr = '[20:20:34] BERMAN [2:1:41] : The [first] name...';
rs.push(testStr);
rs.push(null);
parser.parseStream(rs, (err, result) => {
if(err) return done(err);
result.speaker.should.eql({
'BERMAN': [ 'The [first] name...' ]
});
done();
});
});
});
/*
* For the synchronous parseOne method
*
*/
describe('#parseOneSync()', function() {
const tp = new TranscriptParser();
it('should remove actions by default', function() {
const parser = new TranscriptParser();
const result = parser.parseOneSync('PERSON A: Hello, (PAUSES) (DRINKS WATER) my name is Bob.(APPLAUSE)');
result.speaker.should.eql({
'PERSON A': [ 'Hello, my name is Bob.' ]
});
});
it('should use the newLine regex', function() {
const parser = new TranscriptParser({
regex: { newLine: /\|/ },
});
const result = parser.parseOneSync('A: Testing.\nLF.|B: OK.\r\nCR.');
result.should.eql({
speaker: {
A: ['Testing.\nLF.'],
B: ['OK.\r\nCR.']
},
order: ['A', 'B']
});
});
it('should respect the removeActions setting', function() {
const parser = new TranscriptParser({removeActions: false});
const result = parser.parseOneSync('PERSON A: Hello, (PAUSES) (DRINKS WATER) my name is Bob.(APPLAUSE)');
result.speaker.should.eql({
'PERSON A': [ 'Hello, (PAUSES) (DRINKS WATER) my name is Bob.(APPLAUSE)' ]
});
});
it('should respect the removeTimestamps setting', function() {
const parser = new TranscriptParser({removeAnnotations: false, removeTimestamps: false});
const result = parser.parseOneSync('[20:20:34] BERMAN: [2:1:41] The...');
result.speaker.should.eql({'[20:20:34] BERMAN': ['[2:1:41] The...']});
});
it('should be able to remove timestamps without removing annotations', function() {
const parser = new TranscriptParser({removeAnnotations: false, removeTimestamps: true});
const result = parser.parseOneSync('[20:20:34] BERMAN [2:1:41] : The [first] name...');
result.speaker.should.eql({'BERMAN': ['The [first] name...']});
});
it('should respect the removeUnknownSpeakers setting', function() {
const parser = new TranscriptParser({removeUnknownSpeakers: true});
const result = parser.parseOneSync('The quick [brown] fox jumps over the (lazy) dog.');
result.should.eql({
speaker: {},
order: []
});
});
it('should respect the conciseSpeakers setting', function() {
const parser = new TranscriptParser({conciseSpeakers: true});
const result = parser.parseOneSync(`
A: abc
A: abc
B: def
A: ghi
B: jkl
B: mno`);
result.should.eql({
speaker: {
A: ['abc', 'abc', 'ghi'],
B: ['def', 'jkl', 'mno']
},
order: [
['A', 2],
['B', 1],
['A', 1],
['B', 2]
]
});
});
it('should parse a transcript correctly', function(done) {
readSample(1)
.bind({})
.then(info => {
this.result = tp.parseOneSync(info);
return readExpected(1);
}).then(expected => {
this.result.should.be.eql(JSON.parse(expected));
done();
})
.catch(e => done(e));
});
it('should respect the blacklist setting', function() {
const parser = new TranscriptParser({blacklist: [ 'B' ]});
const testStr = 'A: Blah blah blah\nB: This should be\nignored\nA: Blah blah';
parser.parseOneSync(testStr).should.eql({
speaker: {
A: ['Blah blah blah', 'Blah blah'],
},
order: ['A', 'A']
});
});
});
/*
* For the asynchronous parseOne method
*
*/
describe('#parseOne()', function() {
const tp = new TranscriptParser();
it('should remove actions by default', function(done) {
const parser = new TranscriptParser();
parser.parseOne('PERSON A: Hello, (PAUSES) (DRINKS WATER) my name is Bob.(APPLAUSE)',
function(err, result) {
if(err) return done(err);
result.speaker.should.eql({'PERSON A': [ 'Hello, my name is Bob.' ]});
done();
});
});
it('should use the newLine regex', function(done) {
const parser = new TranscriptParser({
regex: { newLine: /\|/ },
});
parser.parseOne('A: Testing.\nLF.|B: OK.\r\nCR.', (err, parsed) => {
if(err) return done(err);
parsed.should.eql({
speaker: {
A: ['Testing.\nLF.'],
B: ['OK.\r\nCR.']
},
order: ['A', 'B']
});
done();
});
});
it('should respect the removeActions setting', function(done) {
const parser = new TranscriptParser({removeActions: false});
parser.parseOne('PERSON A: Hello, (PAUSES) (DRINKS WATER) my name is Bob.(APPLAUSE)',
(err, result) => {
if(err) return done(err);
result.speaker.should.eql({
'PERSON A': [ 'Hello, (PAUSES) (DRINKS WATER) my name is Bob.(APPLAUSE)' ]
});
done();
});
});
it('should respect the removeTimestamps setting', function(done) {
const parser = new TranscriptParser({removeAnnotations: false, removeTimestamps: false});
parser.parseOne('[20:20:34] BERMAN: [2:1:41] The...',
(err, result) => {
if(err) return done(err);
result.speaker.should.eql({
'[20:20:34] BERMAN': [ '[2:1:41] The...' ]
});
done();
}
);
});
it('should be able to remove timestamps without removing annotations', function(done) {
const parser = new TranscriptParser({removeAnnotations: false, removeTimestamps: true});
parser.parseOne('[20:20:34] BERMAN: The [first] name...',
(err, result) => {
if(err) return done(err);
result.speaker.should.eql({
'BERMAN': ['The [first] name...']
});
done();
}
);
});
it('should respect the removeUnknownSpeakers setting', function(done) {
const parser = new TranscriptParser({removeUnknownSpeakers: true});
parser.parseOne('The quick [brown] fox jumps over the (lazy) dog.',
(err, result) => {
if(err) return done(err);
result.should.eql({
speaker: {},
order: []
});
done();
}
);
});
it('should respect the conciseSpeakers setting', function(done) {
const parser = new TranscriptParser({conciseSpeakers: true});
parser.parseOne(`
A: abc
A: abc
B: def
A: ghi
B: jkl
B: mno`,
(err, result) => {
if(err) return done(err);
result.should.eql({
speaker: {
A: ['abc', 'abc', 'ghi'],
B: ['def', 'jkl', 'mno']
},
order: [
['A', 2],
['B', 1],
['A', 1],
['B', 2]
]
});
done();
}
);
});
it('should parse a transcript correctly', function(done) {
readSample(1)
.bind({})
.then(info => {
return Promise.fromCallback(cb => {
tp.parseOne(info, cb);
});
})
.then(result => {
this.result = result;
return readExpected(1);
}).then(expected => {
this.result.should.be.eql(JSON.parse(expected));
done();
})
.catch(e => done(e));
});
it('should return a promise when callback is not set', function(done) {
readSample(1)
.bind({})
.then(info => {
return tp.parseOne(info);
})
.then(result => {
this.result = result;
return readExpected(1);
}).then(expected => {
this.result.should.be.eql(JSON.parse(expected));
done();
})
.catch(e => done(e));
});
it('should handle errors properly', function(done) {
tp.parseOne(null).then(output => {
should.not.exist(output);
}).catch(err => {
should.exist(err);
}).finally(() => {
tp.parseOne(null, function(err, output) {
should.exist(err);
should.not.exist(output);
done();
});
});
});
it('should respect the blacklist setting', function(done) {
const parser = new TranscriptParser({blacklist: [ 'B' ]});
const testStr = 'A: Blah blah blah\nB: This should be\nignored\nA: Blah blah';
parser.parseOne(testStr).then(parsed => {
parsed.should.eql({
speaker: {
A: ['Blah blah blah', 'Blah blah'],
},
order: ['A', 'A']
});
done();
});
});
});
/*
* For the synchronous resolveAliases method
*
*/
describe('#resolveAliasesSync()', function() {
it('should resolve aliases correctly', function(done) {
const tp = new TranscriptParser({
aliases: {
'TRUMP': [ /.*TRUMP.*/ ],
'FREDERICK RYAN JR.': [ /FREDERICK RYAN JR\.[A-Z,\ ]*/ ]
}
});
readSample(2)
.bind({})
.then(info => {
this.result = tp.parseOneSync(info);
this.result = tp.resolveAliasesSync(this.result);
return readExpected(2);
}).then(expected => {
this.result.should.eql(JSON.parse(expected));
done();
})
.catch(e => done(e));
});
it('should not change the input data', function(done) {
const tp = new TranscriptParser({aliases: {}});
readSample(2)
.then(info => {
const parsed = tp.parseOneSync(info);
const old = JSON.parse(JSON.stringify(parsed));
tp.resolveAliasesSync(parsed);
parsed.should.eql(old);
done();
})
.catch(e => done(e));
});
it('should return unchanged data if aliases are not set', function(done) {
const tp = new TranscriptParser({aliases: {}});
readSample(2)
.then(info => {
const parsed = tp.parseOneSync(info);
const resolved = tp.resolveAliasesSync(parsed);
parsed.should.equal(resolved);
done();
})
.catch(e => done(e));
});
});
/*
* For the asynchronous resolveAliases method
*
*/
describe('#resolveAliases()', function() {
it('should resolve aliases correctly', function(done) {
const tp = new TranscriptParser({
aliases: {
'TRUMP': [ /.*TRUMP.*/ ],
'FREDERICK RYAN JR.': [ /FREDERICK RYAN JR\.[A-Z,\ ]*/ ]
}
});
readSample(2)
.bind({})
.then(info => {
return Promise.fromCallback(cb => tp.parseOne(info, cb));
}).then(result => {
return Promise.fromCallback(cb => tp.resolveAliases(result, cb));
}).then(result => {
this.result = result;
return readExpected(2);
}).then(expected => {
this.result.should.eql(JSON.parse(expected));
done();
})
.catch(e => done(e));
});
it('should not change the input data', function(done) {
const tp = new TranscriptParser({aliases: {}});
readSample(2)
.bind({})
.then(info => {
this.parsed = tp.parseOneSync(info);
this.old = JSON.parse(JSON.stringify(this.parsed));
return Promise.fromCallback(cb => tp.resolveAliases(this.parsed, cb));
}).then(() => {
this.parsed.should.eql(this.old);
done();
})
.catch(e => done(e));
});
it('should return a promise when callback is not set', function(done) {
const tp = new TranscriptParser({
aliases: {
'TRUMP': [ /.*TRUMP.*/ ],
'FREDERICK RYAN JR.': [ /FREDERICK RYAN JR\.[A-Z,\ ]*/ ]
}
});
readSample(2)
.bind({})
.then(info => {
return tp.parseOne(info);
}).then(result => {
return tp.resolveAliases(result);
}).then(result => {
this.result = result;
return readExpected(2);
}).then(expected => {
this.result.should.eql(JSON.parse(expected));
done();
})
.catch(e => done(e));
});
it('should return unchanged data if aliases are not set', function(done) {
const tp = new TranscriptParser({aliases: {}});
readSample(2)
.bind({})
.then(info => {
return Promise.fromCallback(cb => tp.parseOne(info, cb));
}).then(parsed => {
this.parsed = parsed;
// With callback
return Promise.fromCallback(cb => tp.resolveAliases(parsed, cb));
}).then(resolved => {
this.parsed.should.equal(resolved);
// With Promise
return tp.resolveAliases(this.parsed);
}).then(resolved => {
this.parsed.should.equal(resolved);
done();
})
.catch(e => done(e));
});
it('should handle errors properly', function(done) {
const tp = new TranscriptParser({
aliases: { 'TRUMP': [ /.*TRUMP.*/ ] }
});
tp.resolveAliases(null).then(output => {
should.not.exist(output);
}).catch(err => {
should.exist(err);
}).finally(() => {
tp.resolveAliases(null, (err, output) => {
should.exist(err);
should.not.exist(output);
done();
});
});
});
});
});
function readSample(sampleName) {
return fs.readFileAsync(path.join(TEST_DIR, `${sampleName}.txt`), {encoding: 'utf8'});
}
function readExpected(expectedName) {
return fs.readFileAsync(path.join(EXPECTED_DIR, `${expectedName}.txt`), {encoding: 'utf8'});
}
|
var searchData=
[
['timedworker',['TimedWorker',['../namespace_sensorberg_s_d_k_1_1_internal_1_1_data.html#a685ae1aafd94a7e47975b9347bb66422a2185f32b38f0ad63b40647aaa92ec5af',1,'SensorbergSDK::Internal::Data']]]
];
|
define('draggabilly',function(require, exports, module) {
/*!
* Draggabilly PACKAGED v1.0.4
* Make that shiz draggable
* http://draggabilly.desandro.com
*/
/*!
* classie - class helper functions
* from bonzo https://github.com/ded/bonzo
*
* classie.has( elem, 'my-class' ) -> true/false
* classie.add( elem, 'my-new-class' )
* classie.remove( elem, 'my-unwanted-class' )
* classie.toggle( elem, 'my-class' )
*/
/*jshint browser: true, strict: true, undef: true */
/*global define: false */
var $ = require('jquery');
( function( window ) {
'use strict';
// class helper functions from bonzo https://github.com/ded/bonzo
function classReg( className ) {
return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}
// classList support for class management
// altho to be fair, the api sucks because it won't accept multiple classes at once
var hasClass, addClass, removeClass;
if ( 'classList' in document.documentElement ) {
hasClass = function( elem, c ) {
return elem.classList.contains( c );
};
addClass = function( elem, c ) {
elem.classList.add( c );
};
removeClass = function( elem, c ) {
elem.classList.remove( c );
};
}
else {
hasClass = function( elem, c ) {
return classReg( c ).test( elem.className );
};
addClass = function( elem, c ) {
if ( !hasClass( elem, c ) ) {
elem.className = elem.className + ' ' + c;
}
};
removeClass = function( elem, c ) {
elem.className = elem.className.replace( classReg( c ), ' ' );
};
}
function toggleClass( elem, c ) {
var fn = hasClass( elem, c ) ? removeClass : addClass;
fn( elem, c );
}
var classie = {
// full names
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
toggleClass: toggleClass,
// short names
has: hasClass,
add: addClass,
remove: removeClass,
toggle: toggleClass
};
// transport
if ( typeof define === 'function' && define.amd ) {
// AMD
define( classie );
} else {
// browser global
window.classie = classie;
}
})( window );
/**
* EventEmitter v4.0.5 - git.io/ee
* Oliver Caldwell
* MIT license
* @preserve
*/
;(function(exports) {
// JSHint config - http://www.jshint.com/
/*jshint laxcomma:true*/
/*global define:true*/
// Place the script in strict mode
'use strict';
/**
* Class for managing events.
* Can be extended to provide event functionality in other classes.
*
* @class Manages event registering and emitting.
*/
function EventEmitter(){}
// Shortcuts to improve speed and size
// Easy access to the prototype
var proto = EventEmitter.prototype
// Existence of a native indexOf
, nativeIndexOf = Array.prototype.indexOf ? true : false;
/**
* Finds the index of the listener for the event in it's storage array
*
* @param {Function} listener Method to look for.
* @param {Function[]} listeners Array of listeners to search through.
* @return {Number} Index of the specified listener, -1 if not found
*/
function indexOfListener(listener, listeners) {
// Return the index via the native method if possible
if(nativeIndexOf) {
return listeners.indexOf(listener);
}
// There is no native method
// Use a manual loop to find the index
var i = listeners.length;
while(i--) {
// If the listener matches, return it's index
if(listeners[i] === listener) {
return i;
}
}
// Default to returning -1
return -1;
}
/**
* Fetches the events object and creates one if required.
*
* @return {Object} The events storage object.
*/
proto._getEvents = function() {
return this._events || (this._events = {});
};
/**
* Returns the listener array for the specified event.
* Will initialise the event object and listener arrays if required.
*
* @param {String} evt Name of the event to return the listeners from.
* @return {Function[]} All listener functions for the event.
* @doc
*/
proto.getListeners = function(evt) {
// Create a shortcut to the storage object
// Initialise it if it does not exists yet
var events = this._getEvents();
// Return the listener array
// Initialise it if it does not exist
return events[evt] || (events[evt] = []);
};
/**
* Adds a listener function to the specified event.
* The listener will not be added if it is a duplicate.
* If the listener returns true then it will be removed after it is called.
*
* @param {String} evt Name of the event to attach the listener to.
* @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.
* @return {Object} Current instance of EventEmitter for chaining.
* @doc
*/
proto.addListener = function(evt, listener) {
// Fetch the listeners
var listeners = this.getListeners(evt);
// Push the listener into the array if it is not already there
if(indexOfListener(listener, listeners) === -1) {
listeners.push(listener);
}
// Return the instance of EventEmitter to allow chaining
return this;
};
/**
* Alias of addListener
* @doc
*/
proto.on = proto.addListener;
/**
* Removes a listener function from the specified event.
*
* @param {String} evt Name of the event to remove the listener from.
* @param {Function} listener Method to remove from the event.
* @return {Object} Current instance of EventEmitter for chaining.
* @doc
*/
proto.removeListener = function(evt, listener) {
// Fetch the listeners
// And get the index of the listener in the array
var listeners = this.getListeners(evt)
, index = indexOfListener(listener, listeners);
// If the listener was found then remove it
if(index !== -1) {
listeners.splice(index, 1);
// If there are no more listeners in this array then remove it
if(listeners.length === 0) {
this.removeEvent(evt);
}
}
// Return the instance of EventEmitter to allow chaining
return this;
};
/**
* Alias of removeListener
* @doc
*/
proto.off = proto.removeListener;
/**
* Adds listeners in bulk using the manipulateListeners method.
* If you pass an object as the second argument you can add to multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
* You can also pass it an event name and an array of listeners to be added.
*
* @param {String|Object} evt An event name if you will pass an array of listeners next. An object if you wish to add to multiple events at once.
* @param {Function[]} [listeners] An optional array of listener functions to add.
* @return {Object} Current instance of EventEmitter for chaining.
* @doc
*/
proto.addListeners = function(evt, listeners) {
// Pass through to manipulateListeners
return this.manipulateListeners(false, evt, listeners);
};
/**
* Removes listeners in bulk using the manipulateListeners method.
* If you pass an object as the second argument you can remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
* You can also pass it an event name and an array of listeners to be removed.
*
* @param {String|Object} evt An event name if you will pass an array of listeners next. An object if you wish to remove from multiple events at once.
* @param {Function[]} [listeners] An optional array of listener functions to remove.
* @return {Object} Current instance of EventEmitter for chaining.
* @doc
*/
proto.removeListeners = function(evt, listeners) {
// Pass through to manipulateListeners
return this.manipulateListeners(true, evt, listeners);
};
/**
* Edits listeners in bulk. The addListeners and removeListeners methods both use this to do their job. You should really use those instead, this is a little lower level.
* The first argument will determine if the listeners are removed (true) or added (false).
* If you pass an object as the second argument you can add/remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
* You can also pass it an event name and an array of listeners to be added/removed.
*
* @param {Boolean} remove True if you want to remove listeners, false if you want to add.
* @param {String|Object} evt An event name if you will pass an array of listeners next. An object if you wish to add/remove from multiple events at once.
* @param {Function[]} [listeners] An optional array of listener functions to add/remove.
* @return {Object} Current instance of EventEmitter for chaining.
* @doc
*/
proto.manipulateListeners = function(remove, evt, listeners) {
// Initialise any required variables
var i
, value
, single = remove ? this.removeListener : this.addListener
, multiple = remove ? this.removeListeners : this.addListeners;
// If evt is an object then pass each of it's properties to this method
if(typeof evt === 'object') {
for(i in evt) {
if(evt.hasOwnProperty(i) && (value = evt[i])) {
// Pass the single listener straight through to the singular method
if(typeof value === 'function') {
single.call(this, i, value);
}
else {
// Otherwise pass back to the multiple function
multiple.call(this, i, value);
}
}
}
}
else {
// So evt must be a string
// And listeners must be an array of listeners
// Loop over it and pass each one to the multiple method
i = listeners.length;
while(i--) {
single.call(this, evt, listeners[i]);
}
}
// Return the instance of EventEmitter to allow chaining
return this;
};
/**
* Removes all listeners from a specified event.
* If you do not specify an event then all listeners will be removed.
* That means every event will be emptied.
*
* @param {String} [evt] Optional name of the event to remove all listeners for. Will remove from every event if not passed.
* @return {Object} Current instance of EventEmitter for chaining.
* @doc
*/
proto.removeEvent = function(evt) {
// Remove different things depending on the state of evt
if(evt) {
// Remove all listeners for the specified event
delete this._getEvents()[evt];
}
else {
// Remove all listeners in all events
delete this._events;
}
// Return the instance of EventEmitter to allow chaining
return this;
};
/**
* Emits an event of your choice.
* When emitted, every listener attached to that event will be executed.
* If you pass the optional argument array then those arguments will be passed to every listener upon execution.
* Because it uses `apply`, your array of arguments will be passed as if you wrote them out separately.
* So they will not arrive within the array on the other side, they will be separate.
*
* @param {String} evt Name of the event to emit and execute listeners for.
* @param {Array} [args] Optional array of arguments to be passed to each listener.
* @return {Object} Current instance of EventEmitter for chaining.
* @doc
*/
proto.emitEvent = function(evt, args) {
// Get the listeners for the event
// Also initialise any other required variables
var listeners = this.getListeners(evt)
, i = listeners.length
, response;
// Loop over all listeners assigned to the event
// Apply the arguments array to each listener function
while(i--) {
// If the listener returns true then it shall be removed from the event
// The function is executed either with a basic call or an apply if there is an args array
response = args ? listeners[i].apply(null, args) : listeners[i]();
if(response === true) {
this.removeListener(evt, listeners[i]);
}
}
// Return the instance of EventEmitter to allow chaining
return this;
};
/**
* Alias of emitEvent
* @doc
*/
proto.trigger = proto.emitEvent;
/**
* Subtly different from emitEvent in that it will pass its arguments on to the listeners, as
* opposed to taking a single array of arguments to pass on.
*
* @param {String} evt Name of the event to emit and execute listeners for.
* @param {...*} Optional additional arguments to be passed to each listener.
* @return {Object} Current instance of EventEmitter for chaining.
* @doc
*/
proto.emit = function(evt) {
var args = Array.prototype.slice.call(arguments, 1);
return this.emitEvent(evt, args);
};
// Expose the class either via AMD or the global object
if(typeof define === 'function' && define.amd) {
define(function() {
return EventEmitter;
});
}
else {
exports.EventEmitter = EventEmitter;
}
}(this));
/*!
* eventie v1.0.2
* event binding helper
* eventie.bind( elem, 'click', myFn )
* eventie.unbind( elem, 'click', myFn )
*/
/*jshint browser: true, undef: true, unused: true */
/*global define: false */
( function( window ) {
'use strict';
var docElem = document.documentElement;
var bind = function() {};
if ( docElem.addEventListener ) {
bind = function( obj, type, fn ) {
obj.addEventListener( type, fn, false );
};
} else if ( docElem.attachEvent ) {
bind = function( obj, type, fn ) {
obj[ type + fn ] = fn.handleEvent ?
function() {
var event = window.event;
// add event.target
event.target = event.target || event.srcElement;
fn.handleEvent.call( fn, event );
} :
function() {
var event = window.event;
// add event.target
event.target = event.target || event.srcElement;
fn.call( obj, event );
};
obj.attachEvent( "on" + type, obj[ type + fn ] );
};
}
var unbind = function() {};
if ( docElem.removeEventListener ) {
unbind = function( obj, type, fn ) {
obj.removeEventListener( type, fn, false );
};
} else if ( docElem.detachEvent ) {
unbind = function( obj, type, fn ) {
obj.detachEvent( "on" + type, obj[ type + fn ] );
try{
delete obj[ type + fn ];
} catch (e) {}
};
}
var eventie = {
bind: bind,
unbind: unbind
};
// transport
if ( typeof define === 'function' && define.amd ) {
// AMD
define( eventie );
} else {
// browser global
window.eventie = eventie;
}
})( this );
/*!
* docReady
* Cross browser DOMContentLoaded event emitter
*/
/*jshint browser: true, strict: true, undef: true, unused: true*/
( function( window ) {
'use strict';
var EventEmitter = window.EventEmitter;
var eventie = window.eventie;
var document = window.document;
function docReady( fn ) {
if ( docReady.isReady ) {
fn();
} else {
docReady.on( 'ready', fn );
}
}
docReady.isReady = false;
for ( var prop in EventEmitter.prototype ) {
docReady[ prop ] = EventEmitter.prototype[ prop ];
}
// triggered on various doc ready events
function init( event ) {
// bail if IE8 document is not ready just yet
var isIE8NotReady = event.type === 'readystatechange' && document.readyState !== 'complete';
if ( docReady.isReady || isIE8NotReady ) {
return;
}
docReady.isReady = true;
docReady.emit( 'ready', event );
}
eventie.bind( document, 'DOMContentLoaded', init );
eventie.bind( document, 'readystatechange', init );
eventie.bind( window, 'load', init );
// transport
window.docReady = docReady;
})( this );
/*!
* getStyleProperty by kangax
* http://perfectionkills.com/feature-testing-css-properties/
*/
/*jshint browser: true, strict: true, undef: true */
/*globals define: false */
( function( window ) {
'use strict';
var prefixes = 'Webkit Moz ms Ms O'.split(' ');
var docElemStyle = document.documentElement.style;
function getStyleProperty( propName ) {
if ( !propName ) {
return;
}
// test standard property first
if ( typeof docElemStyle[ propName ] === 'string' ) {
return propName;
}
// capitalize
propName = propName.charAt(0).toUpperCase() + propName.slice(1);
// test vendor specific properties
var prefixed;
for ( var i=0, len = prefixes.length; i < len; i++ ) {
prefixed = prefixes[i] + propName;
if ( typeof docElemStyle[ prefixed ] === 'string' ) {
return prefixed;
}
}
}
// transport
if ( typeof define === 'function' && define.amd ) {
// AMD
define( function() {
return getStyleProperty;
});
} else {
// browser global
window.getStyleProperty = getStyleProperty;
}
})( window );
/**
* getSize v1.1.2
* measure size of elements
*/
/*jshint browser: true, strict: true, undef: true, unused: true */
/*global define: false */
( function( window, undefined ) {
'use strict';
// -------------------------- helpers -------------------------- //
var defView = document.defaultView;
var getStyle = defView && defView.getComputedStyle ?
function( elem ) {
return defView.getComputedStyle( elem, null );
} :
function( elem ) {
return elem.currentStyle;
};
// get a number from a string, not a percentage
function getStyleSize( value ) {
var num = parseFloat( value );
// not a percent like '100%', and a number
var isValid = value.indexOf('%') === -1 && !isNaN( num );
return isValid && num;
}
// -------------------------- measurements -------------------------- //
var measurements = [
'paddingLeft',
'paddingRight',
'paddingTop',
'paddingBottom',
'marginLeft',
'marginRight',
'marginTop',
'marginBottom',
'borderLeftWidth',
'borderRightWidth',
'borderTopWidth',
'borderBottomWidth'
];
function getZeroSize() {
var size = {
width: 0,
height: 0,
innerWidth: 0,
innerHeight: 0,
outerWidth: 0,
outerHeight: 0
};
for ( var i=0, len = measurements.length; i < len; i++ ) {
var measurement = measurements[i];
size[ measurement ] = 0;
}
return size;
}
function defineGetSize( getStyleProperty ) {
// -------------------------- box sizing -------------------------- //
var boxSizingProp = getStyleProperty('boxSizing');
var isBoxSizeOuter;
/**
* WebKit measures the outer-width on style.width on border-box elems
* IE & Firefox measures the inner-width
*/
( function() {
if ( !boxSizingProp ) {
return;
}
var div = document.createElement('div');
div.style.width = '200px';
div.style.padding = '1px 2px 3px 4px';
div.style.borderStyle = 'solid';
div.style.borderWidth = '1px 2px 3px 4px';
div.style[ boxSizingProp ] = 'border-box';
var body = document.body || document.documentElement;
body.appendChild( div );
var style = getStyle( div );
isBoxSizeOuter = getStyleSize( style.width ) === 200;
body.removeChild( div );
})();
// -------------------------- getSize -------------------------- //
function getSize( elem ) {
// do not proceed on non-objects
if ( typeof elem !== 'object' || !elem.nodeType ) {
return;
}
var style = getStyle( elem );
// if hidden, everything is 0
if ( style.display === 'none' ) {
return getZeroSize();
}
var size = {};
size.width = elem.offsetWidth;
size.height = elem.offsetHeight;
var isBorderBox = size.isBorderBox = !!( boxSizingProp &&
style[ boxSizingProp ] && style[ boxSizingProp ] === 'border-box' );
// get all measurements
for ( var i=0, len = measurements.length; i < len; i++ ) {
var measurement = measurements[i];
var value = style[ measurement ];
var num = parseFloat( value );
// any 'auto', 'medium' value will be 0
size[ measurement ] = !isNaN( num ) ? num : 0;
}
var paddingWidth = size.paddingLeft + size.paddingRight;
var paddingHeight = size.paddingTop + size.paddingBottom;
var marginWidth = size.marginLeft + size.marginRight;
var marginHeight = size.marginTop + size.marginBottom;
var borderWidth = size.borderLeftWidth + size.borderRightWidth;
var borderHeight = size.borderTopWidth + size.borderBottomWidth;
var isBorderBoxSizeOuter = isBorderBox && isBoxSizeOuter;
// overwrite width and height if we can get it from style
var styleWidth = getStyleSize( style.width );
if ( styleWidth !== false ) {
size.width = styleWidth +
// add padding and border unless it's already including it
( isBorderBoxSizeOuter ? 0 : paddingWidth + borderWidth );
}
var styleHeight = getStyleSize( style.height );
if ( styleHeight !== false ) {
size.height = styleHeight +
// add padding and border unless it's already including it
( isBorderBoxSizeOuter ? 0 : paddingHeight + borderHeight );
}
size.innerWidth = size.width - ( paddingWidth + borderWidth );
size.innerHeight = size.height - ( paddingHeight + borderHeight );
size.outerWidth = size.width + marginWidth;
size.outerHeight = size.height + marginHeight;
return size;
}
return getSize;
}
// transport
if ( typeof define === 'function' && define.amd ) {
// AMD
define( [ 'get-style-property' ], defineGetSize );
} else {
// browser global
window.getSize = defineGetSize( window.getStyleProperty );
}
})( window );
/*!
* Draggabilly v1.0.4
* Make that shiz draggable
* http://draggabilly.desandro.com
*/
( function( window ) {
'use strict';
// vars
var document = window.document;
// -------------------------- helpers -------------------------- //
// extend objects
function extend( a, b ) {
for ( var prop in b ) {
a[ prop ] = b[ prop ];
}
return a;
}
function noop() {}
// ----- get style ----- //
var defView = document.defaultView;
var getStyle = defView && defView.getComputedStyle ?
function( elem ) {
return defView.getComputedStyle( elem, null );
} :
function( elem ) {
return elem.currentStyle;
};
// http://stackoverflow.com/a/384380/182183
var isElement = ( typeof HTMLElement === 'object' ) ?
function isElementDOM2( obj ) {
return obj instanceof HTMLElement;
} :
function isElementQuirky( obj ) {
return obj && typeof obj === 'object' &&
obj.nodeType === 1 && typeof obj.nodeName === 'string';
};
// -------------------------- requestAnimationFrame -------------------------- //
// https://gist.github.com/1866474
var lastTime = 0;
var prefixes = 'webkit moz ms o'.split(' ');
// get unprefixed rAF and cAF, if present
var requestAnimationFrame = window.requestAnimationFrame;
var cancelAnimationFrame = window.cancelAnimationFrame;
// loop through vendor prefixes and get prefixed rAF and cAF
var prefix;
for( var i = 0; i < prefixes.length; i++ ) {
if ( requestAnimationFrame && cancelAnimationFrame ) {
break;
}
prefix = prefixes[i];
requestAnimationFrame = requestAnimationFrame || window[ prefix + 'RequestAnimationFrame' ];
cancelAnimationFrame = cancelAnimationFrame || window[ prefix + 'CancelAnimationFrame' ] ||
window[ prefix + 'CancelRequestAnimationFrame' ];
}
// fallback to setTimeout and clearTimeout if either request/cancel is not supported
if ( !requestAnimationFrame || !cancelAnimationFrame ) {
requestAnimationFrame = function( callback ) {
var currTime = new Date().getTime();
var timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
var id = window.setTimeout( function() {
callback( currTime + timeToCall );
}, timeToCall );
lastTime = currTime + timeToCall;
return id;
};
cancelAnimationFrame = function( id ) {
window.clearTimeout( id );
};
}
// -------------------------- definition -------------------------- //
function draggabillyDefinition( classie, EventEmitter, eventie, getStyleProperty, getSize ) {
// -------------------------- support -------------------------- //
var transformProperty = getStyleProperty('transform');
// TODO fix quick & dirty check for 3D support
var is3d = !!getStyleProperty('perspective');
// -------------------------- -------------------------- //
function Draggabilly( element, options ) {
this.element = element;
this.options = extend( {}, this.options );
extend( this.options, options );
this._create();
}
// inherit EventEmitter methods
extend( Draggabilly.prototype, EventEmitter.prototype );
Draggabilly.prototype.options = {
};
Draggabilly.prototype._create = function() {
// properties
this.position = {};
this._getPosition();
this.startPoint = { x: 0, y: 0 };
this.dragPoint = { x: 0, y: 0 };
this.startPosition = extend( {}, this.position );
// set relative positioning
var style = getStyle( this.element );
if ( style.position !== 'relative' && style.position !== 'absolute' ) {
this.element.style.position = 'relative';
}
this.enable();
this.setHandles();
};
/**
* set this.handles and bind start events to 'em
*/
Draggabilly.prototype.setHandles = function() {
this.handles = this.options.handle ?
// this.element.querySelectorAll( this.options.handle ) : [ this.element ];
$(this.element).find(this.options.handle) : [ this.element ];
for ( var i=0, len = this.handles.length; i < len; i++ ) {
var handle = this.handles[i];
// bind pointer start event
// listen for both, for devices like Chrome Pixel
// which has touch and mouse events
eventie.bind( handle, 'mousedown', this );
eventie.bind( handle, 'touchstart', this );
disableImgOndragstart( handle );
}
};
// remove default dragging interaction on all images in IE8
// IE8 does its own drag thing on images, which messes stuff up
function noDragStart() {
return false;
}
// TODO replace this with a IE8 test
var isIE8 = 'attachEvent' in document.documentElement;
// IE8 only
var disableImgOndragstart = !isIE8 ? noop : function( handle ) {
if ( handle.nodeName === 'IMG' ) {
handle.ondragstart = noDragStart;
}
// var images = handle.querySelectorAll('img');
var images = $(handle).find('img');
for ( var i=0, len = images.length; i < len; i++ ) {
var img = images[i];
img.ondragstart = noDragStart;
}
};
// get left/top position from style
Draggabilly.prototype._getPosition = function() {
// properties
var style = getStyle( this.element );
var x = parseInt( style.left, 10 );
var y = parseInt( style.top, 10 );
// clean up 'auto' or other non-integer values
this.position.x = isNaN( x ) ? 0 : x;
this.position.y = isNaN( y ) ? 0 : y;
this._addTransformPosition( style );
};
// add transform: translate( x, y ) to position
Draggabilly.prototype._addTransformPosition = function( style ) {
if ( !transformProperty ) {
return;
}
var transform = style[ transformProperty ];
// bail out if value is 'none'
if ( transform.indexOf('matrix') !== 0 ) {
return;
}
// split matrix(1, 0, 0, 1, x, y)
var matrixValues = transform.split(',');
// translate X value is in 12th or 4th position
var xIndex = transform.indexOf('matrix3d') === 0 ? 12 : 4;
var translateX = parseInt( matrixValues[ xIndex ], 10 );
// translate Y value is in 13th or 5th position
var translateY = parseInt( matrixValues[ xIndex + 1 ], 10 );
this.position.x += translateX;
this.position.y += translateY;
};
// -------------------------- events -------------------------- //
// trigger handler methods for events
Draggabilly.prototype.handleEvent = function( event ) {
var method = 'on' + event.type;
if ( this[ method ] ) {
this[ method ]( event );
}
};
// returns the touch that we're keeping track of
Draggabilly.prototype.getTouch = function( touches ) {
for ( var i=0, len = touches.length; i < len; i++ ) {
var touch = touches[i];
if ( touch.identifier === this.pointerIdentifier ) {
return touch;
}
}
};
// ----- start event ----- //
Draggabilly.prototype.onmousedown = function( event ) {
this.dragStart( event, event );
};
Draggabilly.prototype.ontouchstart = function( event ) {
// disregard additional touches
if ( this.isDragging ) {
return;
}
this.dragStart( event, event.changedTouches[0] );
};
function setPointerPoint( point, pointer ) {
point.x = pointer.pageX !== undefined ? pointer.pageX : pointer.clientX;
point.y = pointer.pageY !== undefined ? pointer.pageY : pointer.clientY;
}
/**
* drag start
* @param {Event} event
* @param {Event or Touch} pointer
*/
Draggabilly.prototype.dragStart = function( event, pointer ) {
if ( !this.isEnabled ) {
return;
}
if ( event.preventDefault ) {
event.preventDefault();
} else {
event.returnValue = false;
}
var isTouch = event.type === 'touchstart';
// save pointer identifier to match up touch events
this.pointerIdentifier = pointer.identifier;
this._getPosition();
this.measureContainment();
// point where drag began
setPointerPoint( this.startPoint, pointer );
// position _when_ drag began
this.startPosition.x = this.position.x;
this.startPosition.y = this.position.y;
// reset left/top style
this.setLeftTop();
this.dragPoint.x = 0;
this.dragPoint.y = 0;
// bind move and end events
this._bindEvents({
events: isTouch ? [ 'touchmove', 'touchend', 'touchcancel' ] :
[ 'mousemove', 'mouseup' ],
// IE8 needs to be bound to document
node: event.preventDefault ? window : document
});
classie.add( this.element, 'is-dragging' );
// reset isDragging flag
this.isDragging = true;
this.emitEvent( 'dragStart', [ this, event, pointer ] );
// start animation
this.animate();
};
Draggabilly.prototype._bindEvents = function( args ) {
for ( var i=0, len = args.events.length; i < len; i++ ) {
var event = args.events[i];
eventie.bind( args.node, event, this );
}
// save these arguments
this._boundEvents = args;
};
Draggabilly.prototype._unbindEvents = function() {
var args = this._boundEvents;
for ( var i=0, len = args.events.length; i < len; i++ ) {
var event = args.events[i];
eventie.unbind( args.node, event, this );
}
delete this._boundEvents;
};
Draggabilly.prototype.measureContainment = function() {
var containment = this.options.containment;
if ( !containment ) {
return;
}
this.size = getSize( this.element );
var elemRect = this.element.getBoundingClientRect();
// use element if element
var container = isElement( containment ) ? containment :
// fallback to querySelector if string
// typeof containment === 'string' ? document.querySelector( containment ) :
typeof containment === 'string' ? $( containment )[0] :
// otherwise just `true`, use the parent
this.element.parentNode;
this.containerSize = getSize( container );
var containerRect = container.getBoundingClientRect();
this.relativeStartPosition = {
x: elemRect.left - containerRect.left,
y: elemRect.top - containerRect.top
};
};
// ----- move event ----- //
Draggabilly.prototype.onmousemove = function( event ) {
this.dragMove( event, event );
};
Draggabilly.prototype.ontouchmove = function( event ) {
var touch = this.getTouch( event.changedTouches );
if ( touch ) {
this.dragMove( event, touch );
}
};
/**
* drag move
* @param {Event} event
* @param {Event or Touch} pointer
*/
Draggabilly.prototype.dragMove = function( event, pointer ) {
setPointerPoint( this.dragPoint, pointer );
this.dragPoint.x -= this.startPoint.x;
this.dragPoint.y -= this.startPoint.y;
if ( this.options.containment ) {
var relX = this.relativeStartPosition.x;
var relY = this.relativeStartPosition.y;
this.dragPoint.x = Math.max( this.dragPoint.x, -relX );
this.dragPoint.y = Math.max( this.dragPoint.y, -relY );
this.dragPoint.x = Math.min( this.dragPoint.x, this.containerSize.width - relX - this.size.width );
this.dragPoint.y = Math.min( this.dragPoint.y, this.containerSize.height - relY - this.size.height );
}
this.position.x = this.startPosition.x + this.dragPoint.x;
this.position.y = this.startPosition.y + this.dragPoint.y;
this.emitEvent( 'dragMove', [ this, event, pointer ] );
};
// ----- end event ----- //
Draggabilly.prototype.onmouseup = function( event ) {
this.dragEnd( event, event );
};
Draggabilly.prototype.ontouchend = function( event ) {
var touch = this.getTouch( event.changedTouches );
if ( touch ) {
this.dragEnd( event, touch );
}
};
/**
* drag end
* @param {Event} event
* @param {Event or Touch} pointer
*/
Draggabilly.prototype.dragEnd = function( event, pointer ) {
this.isDragging = false;
delete this.pointerIdentifier;
// use top left position when complete
if ( transformProperty ) {
this.element.style[ transformProperty ] = '';
this.setLeftTop();
}
// remove events
this._unbindEvents();
classie.remove( this.element, 'is-dragging' );
this.emitEvent( 'dragEnd', [ this, event, pointer ] );
};
// ----- cancel event ----- //
// coerce to end event
Draggabilly.prototype.ontouchcancel = function( event ) {
var touch = this.getTouch( event.changedTouches );
this.dragEnd( event, touch );
};
// -------------------------- animation -------------------------- //
Draggabilly.prototype.animate = function() {
// only render and animate if dragging
if ( !this.isDragging ) {
return;
}
this.positionDrag();
var _this = this;
requestAnimationFrame( function animateFrame() {
_this.animate();
});
};
// transform translate function
var translate = is3d ?
function( x, y ) {
return 'translate3d( ' + x + 'px, ' + y + 'px, 0)';
} :
function( x, y ) {
return 'translate( ' + x + 'px, ' + y + 'px)';
};
// left/top positioning
Draggabilly.prototype.setLeftTop = function() {
this.element.style.left = this.position.x + 'px';
this.element.style.top = this.position.y + 'px';
};
Draggabilly.prototype.positionDrag = transformProperty ?
function() {
// position with transform
this.element.style[ transformProperty ] = translate( this.dragPoint.x, this.dragPoint.y );
} : Draggabilly.prototype.setLeftTop;
Draggabilly.prototype.enable = function() {
this.isEnabled = true;
};
Draggabilly.prototype.disable = function() {
this.isEnabled = false;
if ( this.isDragging ) {
this.dragEnd();
}
};
return Draggabilly;
} // end definition
// -------------------------- transport -------------------------- //
if ( typeof define === 'function' && define.amd ) {
// AMD
define( [
'classie',
'eventEmitter',
'eventie',
'get-style-property',
'get-size'
],
draggabillyDefinition );
} else {
// browser global
window.Draggabilly = draggabillyDefinition(
window.classie,
window.EventEmitter,
window.eventie,
window.getStyleProperty,
window.getSize
);
}
})( window );
}); |
import { MESSAGES_REQUESTED_BATCH_LOCAL, MESSAGES_RECEIVED_BATCH_LOCAL } from './MessagesConstants';
// TODO: need to deal with error cases
export function fetchAll(callback) {
// NOTE: this could be done without the requested/received pair, but
// kept for consistency
return dispatch => {
dispatch({ type: MESSAGES_REQUESTED_BATCH_LOCAL });
var messages = localStorage.getItem('glimpseMessages');
dispatch({
type: MESSAGES_RECEIVED_BATCH_LOCAL,
source: 'local',
messages
});
if (callback) {
callback(messages);
}
};
}
// WEBPACK FOOTER //
// ./src/client/modules/messages/messages-actions-local.js |
'use strict'
const describe = require('mocha').describe
const music = require('./fixtures/music')
const test = require('./fixtures/test')
const types = Object.keys(music)
describe('Music', () => {
types.forEach(type => {
test(music[type])
})
})
|
(function() {
"use strict";
var image, master, product, store, variants;
module('App.Product', {
setup: function() {
Ember.run(function() {
store = dataStore();
product = store.find('product', 'some-shirt');
});
},
teardown: function() {
store = undefined;
product = undefined;
}
});
// ---------------------------------------------------------
// Relationships
// ---------------------------------------------------------
test('#master', function() {
Ember.run(function() {
master = product.get('master');
});
equal(master.get('id'), 'shirt-master');
});
test('#variants', function() {
Ember.run(function() {
variants = product.get('variants');
});
equal(variants.get('length'), 2);
});
// ---------------------------------------------------------
// Attributes
// ---------------------------------------------------------
test('#availableOn', function() {
ok(product.get('availableOn').isSame(moment('January 1, 2014', 'MMMM D, YYYY')));
});
test('#description', function() {
equal(product.get('description'), 'Some description about some shirt.');
});
test('#displayPrice', function() {
equal(product.get('price'), 24.99);
});
test('#metaDescription', function() {
equal(product.get('metaDescription'), 'This shirt is awesome!');
});
test('#metaKeywords', function() {
equal(product.get('metaKeywords'), 'some, shirt, tshirt, codelation');
});
test('#name', function() {
equal(product.get('name'), 'Some Shirt');
});
test('#permalink', function() {
equal(product.get('permalink'), 'some-shirt');
});
test('#price', function() {
equal(product.get('price'), 24.99);
});
// ---------------------------------------------------------
// Computed Properties
// ---------------------------------------------------------
test('#masterImage', function() {
Ember.run(function() {
image = product.get('masterImage');
});
equal(image.get('id'), 'shirt-front');
});
})();
|
import ComponentView from '../Base/ComponentView';
/**
* The repeater component creates a component for each model in a collection (its model property)
* modelComponent option is the constructor for the component to make
* modelOptions is the options to pass to each new component
* @constructor
*/
var RepeaterComponent = ComponentView.extend({
initialize: function() {
this.template = "";
this.components = {};
this.components[this.getTagName()] = [];
RepeaterComponent.__super__.initialize.apply(this, arguments);
},
render: function() {
this.updateComponents();
RepeaterComponent.__super__.render.apply(this, arguments);
},
updateComponents: function() {
var componentList = this.components[this.getTagName()],
actualLength = this.model.length,
currentLength = componentList ? componentList.length : 0,
smallestLength = actualLength < currentLength ? actualLength : currentLength;
//update the model for each component (important if the collection's order has changed)
for (var i = 0; i < smallestLength; i++) {
if(componentList[i] && !this.alwaysFresh) componentList[i].setModel(this.getModelAt(i));
else componentList[i] = this.makeNewComponent({
model: this.getModelAt(i)
});
}
if (currentLength < actualLength) {
//there aren't enough components on the repeater
for (var j = smallestLength; j < actualLength; j++) {
//create a new component
componentList[j] = this.makeNewComponent({
model: this.getModelAt(j)
});
}
} else if (actualLength < currentLength) {
//there are too many components on the repeater
for (var k = smallestLength; k < currentLength; k++) {
delete componentList[k];
}
}
},
getModelAt: function (i) {
//using a backbone collection V.S. an array
return this.model.models ? this.model.models[i] : this.model[i];
},
makeNewComponent: function(options) {
return new this.modelComponent(
_.extend(
//the new component should use the correct model
options,
//pass it any extra options
this.modelOptions
)
);
}
});
export default RepeaterComponent;
|
'use strict';
const Koa = require('koa');
const Cleantalk = require('../src/middlewares/koa');
const app = new Koa();
|
//aqui começa o hamburger menu
var botaoMenuHamburguer = document.querySelector("#hamburgerMenu");
function abrirMenu() {
this.classList.toggle("clicked");
var menu = document.querySelector("#hamburgerList");
menu.classList.toggle("visible");
}
botaoMenuHamburguer.onclick = abrirMenu;
//aqui começa o social media scroll
var menuScroll = document.querySelector("#socialMediaScroll");
var menuUnscroll = document.querySelector("#socialMedia");
window.addEventListener("scroll", function(event){
if (window.scrollY > 70) {
menuScroll.classList.add("visivel");
menuUnscroll.classList.remove("visivel");
}
else {
menuScroll.classList.remove("visivel");
menuUnscroll.classList.add("visivel");
}
});
// var senadores = document.querySelectorAll('#senadores .senadoresBox');
// Seleciona o <select>
/*var party = document.querySelector('.party');
party.onchange = function (e) { // Quando a gente mudar o valor ...
var filtrados = document.querySelectorAll('.senadoresBox.' + party.value)
filtrados.forEach(function (senador) {
senador.classList.add('selected');
})
O forEach:
filtrados.forEach(function (senador) {
})
é a mesma coisa de fazer o for assim:
for (var i = filtrados.length - 1; i >= 0; i--) {
var senador = filtrados[i]
}
}*/
//aqui começa o fitler de senadores por party and uf
var a, b;
var senadores = $('#senadores .senadoresBox');
function filterSenadores () {
$(senadores).removeClass('selected').addClass('unselected');
$('.senadoresBox.'+this.value).removeClass('unselected').addClass('selected');
a = this.value;
}
$('.party').change(filterSenadores);
function filterUf () {
if(this.value == 'senadoresBox') {
$(senadores).removeClass('unselected').addClass('selected');
return false;
}
b = this.value;
$(senadores).removeClass('selected').addClass('unselected');
var classePesquisa = '';
if(a) {
classePesquisa = '.'+a;
}
classePesquisa += '.uF'+this.value;
$(classePesquisa).removeClass('unselected').addClass('selected');
}
$('.uf').change(filterUf);
//aqui começa a minha search bar
var senadoresFiltrados;
var containerSenadores = document.querySelector("#senadores");
var searchBar = document.querySelector(".searchName");
searchBar.addEventListener("keyup", function() {
if(searchBar.value != "") {
senadoresFiltrados = senadores.filter(function(senadorIndex, senador) {
var name = senador.querySelector(".senadoresName");
var party = senador.querySelector(".senadoresParty");
var name = name.innerText.toLowerCase();
var party = party.innerText.toLowerCase();
if(name.indexOf(searchBar.value.toLowerCase()) > -1) {
return senador;
} else if(party.indexOf(searchBar.value.toLowerCase()) > -1) {
return senador;
}
});
} else {
while (containerSenadores.firstChild) {
containerSenadores.removeChild(containerSenadores.firstChild);
}
for(var i = 0; i < senadores.length; i++) {
containerSenadores.appendChild(senadores[i]);
}
}
while (containerSenadores.firstChild) {
containerSenadores.removeChild(containerSenadores.firstChild);
}
for(var i = 0; i < senadoresFiltrados.length; i++) {
containerSenadores.appendChild(senadoresFiltrados[i]);
}
})
|
"use strict";
module.exports = () => {
/**
* Checks the config has all necessary properties to work with the
* backend-plugin. It will fail loudly if something isn't present.
*
* @param {Object} config
* @param {Function} callback
*/
function validateConfig(config) {
var configKeys;
if (typeof config !== "object") {
throw new Error("Config must be an object.");
}
configKeys = {
backend: "string",
backendConfig: "object",
heartbeatDelayMs: "number",
maxProcessingMessages: "number"
};
Object.keys(configKeys).forEach((key) => {
if (!config[key]) {
throw new Error(`Config.${key} must be defined.`);
} else if (typeof config[key] !== configKeys[key]) {
throw new Error(`Config.${key} must be a ${configKeys[key]}`);
}
});
}
return {
validateConfig
};
};
|
import {HttpClient} from 'aurelia-http-client';
import {SERVICES} from 'config/services.js';
export class Customer{
static inject() { return [HttpClient]; }
constructor(http, orangeMoney) {
this.http = http;
this.heading = 'List Customers';
this.customers = [];
}
activate() {
var self = this;
return this.http.get(SERVICES.CUSTOMERS).then(response => {
self.customers = JSON.parse(response.response);
});
}
}
|
'use strict';
var gulp = require('gulp'),
debug = require('gulp-debug'),
inject = require('gulp-inject'),
tsc = require('gulp-typescript'),
tslint = require('gulp-tslint'),
sourcemaps = require('gulp-sourcemaps'),
rimraf = require('gulp-rimraf'),
Config = require('./gulpfile.config'),
karma = require('karma').Server;
var config = new Config();
/**
* Generates the app.d.ts references file dynamically from all application *.ts files.
*/
gulp.task('gen-ts-refs', function () {
var target = gulp.src(config.appTypeScriptReferences);
var sources = gulp.src([config.allTypeScript], {read: false});
return target.pipe(inject(sources, {
starttag: '//{',
endtag: '//}',
transform: function (filepath) {
return '/// <reference path="../..' + filepath + '" />';
}
})).pipe(gulp.dest(config.typings));
});
/**
* Lint all custom TypeScript files.
*/
gulp.task('ts-lint', function () {
return gulp.src(config.allTypeScript).pipe(tslint()).pipe(tslint.report('prose'));
});
/**
* Compile TypeScript and include references to library and app .d.ts files.
*/
gulp.task('compile-ts', function () {
var sourceTsFiles = [config.allTypeScript, //path to typescript files
config.libraryTypeScriptDefinitions, //reference to library .d.ts files
config.appTypeScriptReferences]; //reference to app.d.ts files
var tsResult = gulp.src(sourceTsFiles)
.pipe(sourcemaps.init())
.pipe(tsc({
target: 'ES5',
declarationFiles: false,
noExternalResolve: true
}));
tsResult.dts.pipe(gulp.dest(config.tsOutputPath));
return tsResult.js
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(config.tsOutputPath));
});
/**
* Remove all generated JavaScript files from TypeScript compilation.
*/
gulp.task('clean-ts', function () {
var typeScriptGenFiles = [config.tsOutputPath, // path to generated JS files
config.sourceApp +'**/*.js', // path to all JS files auto gen'd by editor
config.sourceApp +'**/*.js.map' // path to all sourcemap files auto gen'd by editor
];
// delete the files
return gulp.src(typeScriptGenFiles, {read: false})
.pipe(rimraf());
});
gulp.task('test', function() {
new karma({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}).start();
});
var uglify = require('gulp-uglifyjs');
gulp.task('uglify', function() {
gulp.src('dist/*.js')
.pipe(uglify())
.pipe(gulp.dest('dist/bin'))
});
gulp.task('watch', function() {
gulp.watch([config.allTypeScript], ['ts-lint', 'compile-ts', 'gen-ts-refs', 'test']);
gulp.watch([config.testFiles], ['test']);
});
gulp.task('default', ['ts-lint', 'compile-ts', 'gen-ts-refs', 'test', 'uglify', 'watch']);
|
var test = require('tape');
var file = require('../src/codility/prefix-sums/minAvgTwoSlice.js');
test('minAvgTwoSlice', function(t) {
t.plan(8);
t.equal(1, file.minAvgTwoSlice([ 4, 2, 2, 5, 1, 5, 8 ]), 'example test');
t.equal(0, file.minAvgTwoSlice([ -10000, -10000 ]), 'two or four elements');
t.equal(0, file.minAvgTwoSlice([ 10000, -10000 ]), 'two or four elements');
t.equal(0, file.minAvgTwoSlice([ 10000, -10000 ]), 'two or four elements');
t.equal(1, file.minAvgTwoSlice([ 10000, -10000, -10000, 10000 ]), 'two or four elements');
t.equal(2, file.minAvgTwoSlice([ 5, 6, 3, 4, 9 ]), 'simple test, the best slice has length 3');
t.equal(5, file.minAvgTwoSlice([ 10, 10, -1, 2, 4, -1, 2, -1 ]), 'simple test, the best slice has length 3');
t.equal(2, file.minAvgTwoSlice([ -3, -5, -8, -4, -10 ]), 'simple test, the best slice has length 3');
});
|
import d3 from 'd3'
import logger from '../logger'
const formatCandleData = (data) => data.map(d => ({
begins_at: d.begins_at,
open_price: parseFloat(d.open_price),
close_price: parseFloat(d.close_price),
high_price: parseFloat(d.high_price),
low_price: parseFloat(d.low_price),
volume: d.volume,
interpolated: d.interpolated,
}))
const parseCandleData = (chartData) => {
const formattedData = formatCandleData(chartData.data)
const isTrendingUp = (chartData.displayPrevClose
? formattedData[formattedData.length - 1].open_price > chartData.prevClose
: formattedData[formattedData.length - 1].close_price > formattedData[0].close_price)
return {
data: formattedData,
minValue: Math.min(chartData.prevClose || Number.MAX_VALUE,
Math.min(...formattedData.map(d => Math.min(d.open_price, d.close_price)))),
maxValue: Math.max(chartData.prevClose || Number.MIN_VALUE,
Math.max(...formattedData.map(d => Math.max(d.open_price, d.close_price)))),
klass: isTrendingUp ? 'quote-up' : 'quote-down',
}
}
/** returns a list of the indices of the data points representing the first day of each month */
const getTickValues = (data, inputTimeFormat) => {
const dayTimeFormat = d3.time.format('%e')
const monthTimeFormat = d3.time.format('%m')
const yearTimeFormat = d3.time.format('%Y')
const indices = []
const formattedDates = data.map(d => inputTimeFormat.parse(d.begins_at))
.map((d) => ({
day: parseInt(dayTimeFormat(d).trim(), 10),
month: parseInt(monthTimeFormat(d), 10),
year: parseInt(yearTimeFormat(d), 10),
}))
formattedDates.forEach((d, i) => {
if (i === 0 || d.month > formattedDates[i - 1].month || d.year > formattedDates[i - 1].year) {
indices.push(i)
}
})
return indices
}
const drawCandles = (svg, data, x, y, candleWidth) => {
const candleHeight = (d) => Math.abs(
y(Math.min(d.open_price, d.close_price)) - y(Math.max(d.open_price, d.close_price)))
const candleClass = (d) => (d.open_price < d.close_price ? 'quote-up' : 'quote-down')
const container = svg.append('g')
.attr('clip-path', 'url(#clip)')
.append('g')
.attr("class", "candlesContainer")
container.selectAll('*').remove()
container.selectAll("line.stem")
.data(data)
.enter()
.append("line")
.attr("class", "stem")
.attr("x1", (d, i) => x(i))
.attr("x2", (d, i) => x(i))
.attr("y1", (d) => y(d.high_price))
.attr("y2", (d) => y(d.low_price))
.attr("stroke", () => 'black')
.attr("transform", () => `translate(${candleWidth / 2}, 0)`)
container.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("class", (d) => `candle ${candleClass(d)}`)
.attr("x", (d, i) => x(i))
.attr("y", (d) => y(Math.max(d.open_price, d.close_price)))
.attr("width", () => candleWidth)
.attr("height", (d) => candleHeight(d))
}
const drawXAxis = (svg, xAxis, height) => {
svg.append("g")
.attr('clip-path', 'url(#clip)')
.append("g")
.attr("class", "x axis")
.attr("transform", `translate(0, ${height - 20})`)
.call(xAxis)
}
const drawYAxis = (svg, yAxis, containerWidth) => {
svg.append("g")
.attr("class", "y axis")
.attr("transform", `translate(${containerWidth - 30}, -30)`)
.call(yAxis)
}
/** Draws a solid gray rectangle in the svg so the candle chart can be dragged around */
const drawFill = (svg) => {
const g = svg.selectAll('g.fill-group')
.data(['1'])
g.enter().append('g')
.attr('class', 'fill-group')
const fill = g.selectAll('.fill')
.data(['1'])
fill.enter().append('rect')
.attr('class', 'fill')
.attr('width', '100%')
.attr('height', '100%')
}
const onZoom = (svg, xAxis) => {
svg.select(".x.axis").call(xAxis)
svg.select('.candlesContainer').attr('transform', `translate(${d3.event.translate[0]},0)`)
}
const drawCandleChart = (chartData) => {
const containerWidth = d3.select(chartData.selector).node().getBoundingClientRect().width
logger.log(`width: ${containerWidth}`)
const metadata = parseCandleData(chartData)
const height = chartData.height
const candleMargin = 1.5
const minCandleWidth = 8
const totalItems = metadata.data.length
const candleWidth = minCandleWidth
const inputTimeFormat = d3.time.format('%Y-%m-%dT%H:%M:%SZ')
const xAxisOutputFormat = d3.time.format('%b %Y')
// Label to be displayed on X axis by converting the data item into a formatted date
const formatXAxis = (i) => {
if (i >= 0 && i < totalItems) {
const item = metadata.data[i]
return xAxisOutputFormat(inputTimeFormat.parse(item.begins_at))
}
return ''
}
const tickValues = getTickValues(metadata.data, inputTimeFormat)
const start = metadata.data[0].begins_at
const end = metadata.data[totalItems - 1].begins_at
logger.log(
`start date: ${inputTimeFormat.parse(start)}, end date: ${inputTimeFormat.parse(end)}`)
const x = d3.scale.linear()
.domain([0, totalItems])
.range([0, totalItems * (candleWidth + (candleMargin * 2))])
.nice()
const y = d3.scale.linear()
.domain([metadata.minValue, metadata.maxValue])
.range([height, 0])
.nice()
const xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickValues(tickValues)
.tickFormat(formatXAxis)
const yAxis = d3.svg.axis()
.scale(y)
.orient('right')
.ticks(30)
const zoom = d3.behavior.zoom()
.x(x)
.y(y)
.scaleExtent([1, 1])
.on('zoom', () => onZoom(svg, xAxis))
d3.selectAll(`${chartData.selector} > *`).remove()
const svgNode = d3.select(chartData.selector)
.append("svg")
.attr('class', `chart candle`)
.attr("width", chartData.width)
.attr("height", height)
.call(zoom)
const svg = svgNode.append('g')
svg.append('clipPath')
.attr('id', 'clip')
.append('rect')
.attr('x', 0)
.attr('y', 0)
.attr('width', containerWidth - 30)
.attr('height', height)
drawFill(svg)
drawXAxis(svg, xAxis, height)
drawYAxis(svg, yAxis, containerWidth)
drawCandles(svg, metadata.data, x, y, candleWidth)
}
export { parseCandleData, drawCandleChart, getTickValues }
|
/*!
* ncss - compilers
* Copyright (c) 2011 Wil Asche <wil@wickedspiral.com>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var deps = {};
/**
* Compiliers
*/
module.exports = {
'css': function(str, path, callback, next) {
callback(str);
},
'styl': function(str, path, callback, next) {
if ( ! load('stylus') ) next();
deps.stylus(str).set('filename', path).render(function(err, css, js) {
if (err) return next(err);
callback(css);
});
},
'sass': function(str, path, callback, next) {
if ( ! load('sass') ) next();
var css = deps.sass(str);
callback(css);
}
};
/**
* Generic module loader.
*
* @api private
*/
function load(name) {
if (deps[name] === false) return false;
deps[name] = require(name);
return deps[name] !== null;
}
|
const test = require('tape')
const barracks = require('./index.js')
test('.on() should assert input arguments', function (t) {
t.plan(2)
const d = barracks()
t.throws(d.on.bind(null), /string/)
t.throws(d.on.bind(null, ''), /function/)
})
test('.on() should bind functions', function (t) {
t.plan(3)
const d = barracks()
const key = 'foo'
d.on(key, noop)
t.ok(Array.isArray(d._actions[key]), 'is array')
t.equal(d._actions[key].length, 1)
d.on('foo', noop)
t.equal(d._actions[key].length, 2)
})
test('.emit() should assert action exists', function (t) {
t.plan(1)
const d = barracks()
t.throws(d.bind(null, 'yo'), /action/)
})
test('.emit() should call a function', function (t) {
t.plan(2)
const d = barracks()
d.on('foo', function () {
t.pass('is called')
})
d('foo')
d.on('bar', function (data) {
t.equal(data, 'hello you')
})
d('bar', 'hello you')
})
test('wait() should be able to chain 2 functions', function (t) {
t.plan(4)
const d = barracks()
d.on('foo', function (data, wait) {
t.pass('is called')
t.equal(typeof wait, 'function')
wait('bar')
})
d.on('bar', function (data) {
t.pass('is called')
t.equal(data, 'hello me')
})
d('foo', 'hello me')
})
test('wait should be able to chain 4 functions', function (t) {
t.plan(10)
const d = barracks()
d.on('foo', function (data, wait) {
t.pass('is called')
return wait(['bar', 'bin', 'baz'])
})
d.on('bar', cbFn)
d.on('bin', cbFn)
d.on('baz', cbFn)
d('foo', 'hello me')
function cbFn (data, wait) {
t.pass('is called')
t.equal(data, 'hello me')
t.equal(typeof wait, 'function')
wait()
}
})
test('wait() should call a callback on end', function (t) {
t.plan(2)
const d = barracks()
var i = 0
d.on('foo', function (data, wait) {
return wait('bar', function () {
t.equal(i, 1)
})
})
d.on('bar', function (data) {
t.pass('is called')
i++
})
d('foo', 'hello me')
})
test('wait() should be able to call functions 4 levels deep', function (t) {
t.plan(16)
const d = barracks()
var n = 0
d.on('foo', function (data, wait) {
t.pass('is called')
t.equal(data, 'hello me')
t.equal(typeof wait, 'function')
t.equal(n++, 0)
return wait('bar')
})
d.on('bar', function (data, wait) {
t.pass('is called')
t.equal(data, 'hello me')
t.equal(typeof wait, 'function')
t.equal(n++, 1)
return wait('bin')
})
d.on('bin', function (data, wait) {
t.pass('is called')
t.equal(data, 'hello me')
t.equal(typeof wait, 'function')
t.equal(n++, 2)
return wait('bon')
})
d.on('bon', function (data, wait) {
t.pass('is called')
t.equal(data, 'hello me')
t.equal(typeof wait, 'function')
t.equal(n++, 3)
})
d('foo', 'hello me')
})
test('.emit() should emit `error` on circular dependencies', function (t) {
t.plan(1)
const d = barracks()
d.on('bin', function (data, wait) {
return wait('bar')
})
d.on('bar', function (data, wait) {
return wait('bin')
})
d.on('error', function (err) {
t.equal(err, 'circular dependency detected')
})
d('bin')
})
test('.emit() should throw if no error handler is bound', function (t) {
t.plan(1)
const d = barracks()
d.on('bin', function (data, wait) {
return wait('bar')
})
d.on('bar', function (data, wait) {
return wait('bin')
})
t.throws(d.bind(null, 'bin'), /unhandled 'error' event/)
})
test('.emit() should be able to handle flux standard actions', function (t) {
t.plan(2)
const d = barracks()
d.on('foo', function (data) {
t.equal(data.type, 'foo')
t.equal(data.payload, 'bar')
})
d({ type: 'foo', payload: 'bar' })
})
function noop () {}
noop()
|
// Avatar.setOptions({
// gravatarDefault: "identicon"
// }); |
// Global javascript (loaded on all pages in Pattern Lab and Drupal)
// Should be used sparingly because javascript files can be used in components
// See https://github.com/fourkitchens/macchiato/wiki/Drupal-Components#javascript-in-drupal for more details on using component javascript in Drupal.
// Typekit Example
// try {
// Typekit.load({ async: true });
// }
// catch (e) {
// alert('An error has occurred: ' + e.message);
// }
|
/*jshint boss:true, expr:true, onevar:false */
var ProjectsView;
var VIEW_TITLE = 'Projects';
ProjectsView = Y.Base.create('projectsView', Y.View, [ ], {
// -- Public properties ----------------------------------------------------
/**
* Automagicly created events.
*
* @see {View}
*/
events: {
'a': {
click: '_handleItemClicked'
}
},
template: '<div><ul class="nav nav-tabs nav-stacked"></ul></div>',
titleTemplate: '<h3>' + VIEW_TITLE + '</h3>',
itemTemplate: '<li><a href="#"><i class="icon-tasks"></i> </a></li>',
// -- Protected Properties -------------------------------------------------
/**
* @type {Array}
*/
_events: null,
// -- Lifecycle Methods ----------------------------------------------------
/**
* Constructor
*/
initializer: function () {
this._events = [];
this._events.push(
this.after('modelChange', this.render, this)
);
},
/**
* Destructor
*/
destructor: function () {
this.detach(this._events);
this._events = null;
},
// -- Public Methods -------------------------------------------------------
/**
* (Re-)Render the view
*/
render: function () {
var container = this.get('container');
container.all('*').remove();
container.append(this.template);
container.one('div').prepend(this.titleTemplate);
this._renderProjectItems();
this._openFirstProject();
},
// -- Protected Methods ----------------------------------------------------
/**
* Render a list of projects and add it to the container node
*
* @private
*/
_renderProjectItems: function () {
var self = this,
first = true,
container = this.get('container'),
list = container.one('ul'),
projects = this.get('model');
Y.each(projects, function(project) {
var item = Y.Node.create(self.itemTemplate),
anchor = item.one('a');
anchor.append(project.get('name'));
anchor.setData('model', project);
if (first) {
item.addClass('active');
first = false;
}
list.append(item);
});
},
/**
* Open the first project
*
* @private
*/
_openFirstProject: function () {
var container = this.get('container'),
firstNode = container.one('ul').one('.active');
if (firstNode) {
this._handleItemClicked({ currentTarget: firstNode.one('a') });
}
},
/**
* Callback fired when a project is clicked
*
* @param {EventFacade} e
* @private
*/
_handleItemClicked: function (e) {
var node = e.currentTarget,
model = node.getData('model');
node.ancestor('ul').all('.active').removeClass('active');
node.get('parentNode').addClass('active');
this.fire('openProject', { model: model });
}
}, {
ATTRS: {
/**
* The projects model
*
* @attribute elementModel
* @type {Y.TodoApp.Projects}
*/
model: {
value: null
}
}
});
Y.namespace('TodoApp').ProjectsView = ProjectsView;
|
var gulp = require('gulp');
var runSequence = require('run-sequence');
gulp.task('build', function(callback) {
runSequence(
'clean',
['htdocs', 'javascripts', 'templates', 'stylesheets', 'images', 'fonts', 'bower', 'config:development'],
callback
);
});
|
module.exports = function(source) {
return source.replace(/^.*#!.*$/mg, "");
};
|
'use strict';
/*jshint expr: true*/
const path = require('path');
const events = require('events');
const chai = require('chai');
const sinon = require('sinon');
const fs = require('fs-extra');
const expect = require('chai').expect;
const periodic = require('../../../index');
const periodicClass = require('../../../lib/periodicClass');
const setup = require('../../../lib/extension/setup');
chai.use(require('sinon-chai'));
chai.use(require('chai-as-promised'));
const testPathDir = path.resolve(__dirname, '../../mock/spec/periodic');
const setupDir = path.join(testPathDir, 'ExtSetup');
const containerConfigDir = path.join(setupDir, '/my-example-app/content/container/sample-container/config');
const emptyContainerDir = path.join(setupDir, '/my-example-app/content/container/empty-container');
const sampleExtensionDir = path.join(setupDir, '/my-example-app/node_modules/sample-extension');
const extensionStandardModelDir = path.join(sampleExtensionDir, '/config/databases/standard/models');
const sampleContainerDir = path.join(setupDir, '/my-example-app/content/container/sample-container');
const sampleContainerRouterDir = path.join(sampleContainerDir, '/routers');
const sampleContainerControllerDir = path.join(sampleContainerDir, '/controllers');
const sampleContainerUtilityDir = path.join(sampleContainerDir, '/utilities');
const sampleContainerCommandDir = path.join(sampleContainerDir, '/commands');
const sampleContainerTransformDir = path.join(sampleContainerDir, '/transforms');
const sampleModelFile = path.join(extensionStandardModelDir, '/sample_model.js');
const containerConfigurationFile = path.join(containerConfigDir, '/settings.js');
const extensionConfigurationFile = path.join(sampleExtensionDir, '/config/settings.js');
const containerRuntimeConfigFile = path.join(sampleContainerDir, '/test_runtime.json');
const extensionRuntimeConfigFile = path.join(setupDir, '/my-example-app/content/extension/sample-extension/test_runtime.json');
const containerExtensionModuleFile = path.join(sampleContainerDir, '/index.js');
const emptyContainerExtensionModuleFile = path.join(emptyContainerDir, '/index.js');
const containerRouterFile = path.join(sampleContainerRouterDir, '/index.js');
const containerControllerFile = path.join(sampleContainerControllerDir, '/index.js');
const containerUtilityFile = path.join(sampleContainerUtilityDir, '/index.js');
const containerCommandFile = path.join(sampleContainerCommandDir, '/index.js');
const containerTransformFile = path.join(sampleContainerTransformDir, '/index.js');
describe('Periodic Extension setup', function() {
this.timeout(10000);
before('initialize test periodic dir', (done) => {
Promise.all([
fs.ensureDir(sampleExtensionDir),
fs.ensureDir(extensionStandardModelDir),
fs.ensureDir(containerConfigDir),
fs.ensureDir(emptyContainerDir),
fs.ensureDir(sampleContainerRouterDir),
fs.ensureDir(sampleContainerControllerDir),
fs.ensureDir(sampleContainerUtilityDir),
fs.ensureDir(sampleContainerCommandDir),
fs.ensureDir(sampleContainerTransformDir),
])
.then((result) => {
return Promise.all([
fs.outputFile(sampleModelFile, '', function(jsFileCreated) {
return true;
}),
fs.outputFile(containerConfigurationFile, 'module.exports = {test: true}', function(jsFileCreated) {
return true;
}),
fs.outputFile(containerRuntimeConfigFile, 'module.exports = {test: true}', function(jsFileCreated) {
return true;
}),
fs.outputFile(extensionConfigurationFile, 'module.exports = {test: true}', function(jsFileCreated) {
return true;
}),
fs.outputFile(extensionRuntimeConfigFile, 'module.exports = {test: true}', function(jsFileCreated) {
return true;
}),
fs.outputFile(containerExtensionModuleFile, 'module.exports = function(){return true}', function(fileCreated) { return true; }),
fs.outputFile(containerRouterFile, 'module.exports = {}', function(fileCreated) { return true; }),
fs.outputFile(containerControllerFile, 'module.exports = {}', function(fileCreated) { return true; }),
fs.outputFile(containerUtilityFile, 'module.exports = {}', function(fileCreated) { return true; }),
fs.outputFile(containerCommandFile, 'module.exports = {}', function(fileCreated) { return true; }),
fs.outputFile(containerTransformFile, 'module.exports = { pre:{"DELETE":function(req, res, next){next()}}, post: {"GET":function(req, res, next){next()}}}', function(fileCreated) { return true; }),
fs.outputFile(emptyContainerExtensionModuleFile, 'module.exports = function(){return true}', function(fileCreated) { return true; }),
]);
})
.then((created) => {
done();
}).catch(done);
});
describe('getModelFilesMap', () => {
it('should return fullpath of the model file', () => {
expect(setup.getModelFilesMap('/dirname', '/path/to/file')).to.eql('/dirname/path/to/file/___FULLPATH___');
});
});
describe('loadExtensionFiles -- has models', () => {
it('should load extension files', (done) => {
const mockThis = {
resources: {
standard_models: [],
},
config: {
app_root: path.join(setupDir, '/my-example-app'),
},
};
const mockOptions = {
extension: {
name: 'sample-extension',
},
container: {},
};
setup.loadExtensionFiles.call(mockThis, mockOptions)
.then((hasLoadedExtensions) => {
expect(hasLoadedExtensions).to.be.true;
done();
})
.catch(e => {
done();
});
});
});
describe('loadExtensionFiles -- doesnt have models', () => {
it('should return a message if files dont exist', (done) => {
const mockThis = {
resources: {
standard_models: [],
},
config: {
app_root: path.join(setupDir, '/app-does-not-exist'),
},
configuration: {
load: (options) => {
return new Promise((resolve, reject) => {
done();
resolve(true);
})
}
}
};
const mockOptions = {
extension: {
name: 'sample-extension',
},
container: {},
}
setup.loadExtensionFiles.call(mockThis, mockOptions)
.then((loadedExtensions) => {
expect(loadedExtensions).to.equal('does not have standard models')
done();
})
.catch(e => {
done();
});
});
});
describe('loadExtensionSettings', () => {
it('should set default settings for container', (done) => {
const mockThis = {
settings: {
container: {
'sample-container': {
databases: {
'sample_db': {}
}
}
},
},
resources: {
standard_models: [],
databases: {
container: {}
}
},
config: {
app_root: path.join(setupDir, '/my-example-app'),
process: {
runtime: 'test_runtime',
}
},
configuration: {
load: (options) => {
return new Promise((resolve, reject) => {
done();
resolve({ db_based_configs: true });
})
}
}
}
const mockOptions = {
container: {
name: 'sample-container',
type: 'local',
},
};
setup.loadExtensionSettings.call(mockThis, mockOptions)
.then(resolvedSettings => {
expect(resolvedSettings).to.be.true;
})
.catch(done);
});
it('should set default settings for extensions', (done) => {
const mockThis = {
settings: {
extensions: {},
},
resources: {
standard_models: [],
databases: {
extensions: {}
}
},
config: {
app_root: path.join(setupDir, '/my-example-app'),
process: {
runtime: 'test_runtime',
}
},
configuration: {
load: (options) => {
return new Promise((resolve, reject) => {
done();
resolve({ db_based_configs: true });
})
}
}
}
const mockOptions = {
extension: {
name: sampleExtensionDir,
type: 'local',
},
};
setup.loadExtensionSettings.call(mockThis, mockOptions)
.then(resolvedSettings => {
expect(resolvedSettings).to.be.true;
})
.catch(done);
});
it('should fail when default settings is missing', (done) => {
const warnSpy = sinon.spy();
const mockThis = {
settings: {},
resources: {},
config: {
app_root: path.join(setupDir, '/my-example-app'),
debug: true,
},
configuration: {
process: {
runtime: 'test_runtime',
},
},
logger: {
warn: warnSpy,
},
routers: new Map(),
}
const mockOptions = {
container: {
name: 'sample-container'
}
};
try {
setup.loadExtensionSettings.call(mockThis, mockOptions)
.then(resolvedSettings => {
return;
})
} catch (e) {
expect(warnSpy.called).to.be.true;
done();
}
});
});
describe('getExtensionFromMap', () => {
it('should return objectified extension', () => {
expect(setup.getExtensionFromMap('sample-extension')).to.deep.eql({ extension: 'sample-extension' });
});
});
describe('assignExtensionResources', () => {
it('should load resources for container', (done) => {
const warnSpy = sinon.spy();
const mockThis = {
resources: {
standard_models: [],
commands: {
container: new Map(),
}
},
logger: {
warn: warnSpy,
},
transforms: {
pre: {
},
post: {
}
},
config: {
app_root: path.join(setupDir, '/my-example-app'),
},
routers: new Map(),
controller: {
container: new Map(),
},
locals: {
container: new Map(),
}
};
const mockOptions = {
container: {
name: 'sample-container',
type: 'local',
},
};
setup.assignExtensionResources.call(mockThis, mockOptions)
.then((assignedResources) => {
//extensionModule file must export a function
expect(assignedResources).to.be.true;
expect(warnSpy.called).to.be.false;
expect(warnSpy.callCount).to.eql(0);
done();
})
.catch(e => {
console.log({ e });
done();
});
});
it('should log warnings if files don\'t exist', (done) => {
const warnSpy = sinon.spy();
const mockThis = {
resources: {
standard_models: [],
commands: {
container: new Map(),
}
},
logger: {
warn: warnSpy,
},
transforms: {
pre: {
},
post: {
}
},
config: {
app_root: path.join(setupDir, '/my-example-app'),
debug: true,
},
routers: new Map(),
controller: {
container: new Map(),
},
locals: {
container: new Map(),
}
};
const mockOptions = {
container: {
name: 'empty-container',
type: 'local',
},
};
setup.assignExtensionResources.call(mockThis, mockOptions)
.then((assignedResources) => {
//extensionModule file must export a function
expect(assignedResources).to.be.true;
expect(warnSpy.called).to.be.true;
expect(warnSpy.callCount).to.eql(4);
done();
})
.catch(e => {
console.log({ e });
done();
});
});
});
// describe('setupExtensions', () => {
// it('should load resources for extension', (done) => {
// const warnSpy = sinon.spy();
// const mockThis = {
// extensions: new Map(),
// config: {
// process: {},
// },
// settings: {
// extensions: {
// 'sample-extension': {
// databases: {
// 'sample_db': {}
// }
// }
// },
// },
// resources: {
// standard_models: [],
// databases: {
// extensions: {}
// }
// },
// configuration: {
// load: (options) => {
// return new Promise((resolve, reject) => {
// done();
// resolve(true);
// })
// }
// }
// };
// mockThis.extensions.set('sample-extension', {
// name: 'sample-extension',
// resources: {
// standard_models: [],
// commands: {
// extensions: new Map(),
// }
// },
// logger: {
// warn: warnSpy,
// },
// transforms: {
// pre: {
// },
// post: {
// }
// },
// config: {
// app_root: path.join(setupDir, '/my-example-app'),
// },
// routers: new Map(),
// controller: {
// extensions: new Map(),
// },
// locals: {
// extensions: new Map(),
// }
// });
// setup.setupExtensions.call(mockThis)
// .then((setupExtensions) => {
// //extensionModule file must export a function
// console.log({ setupExtensions })
// expect(setupExtensions).to.be.true;
// done();
// })
// .catch(e => {
// console.log({ e });
// done();
// });
// });
// });
describe('setupContainer', () => {
it('should setup container', (done) => {
const warnSpy = sinon.spy();
const mockThis = {
config: {
process: {},
app_root: path.join(setupDir, '/my-example-app')
},
resources: {
standard_models: [],
commands: {
container: new Map(),
}
},
databases: {
'sample_db': {}
},
settings: {
container: {
name: 'sample-container',
type: 'local',
logger: {
warn: warnSpy,
},
transforms: {
pre: {
},
post: {
}
},
config: {
app_root: path.join(setupDir, '/my-example-app'),
},
routers: new Map(),
controller: {
container: new Map(),
},
locals: {
container: new Map(),
}
},
},
resources: {
standard_models: [],
databases: {
container: {}
}
},
configuration: {
load: (options) => {
return new Promise((resolve, reject) => {
resolve(true);
})
}
}
};
setup.setupContainer.call(mockThis)
.then((setupContainer) => {
expect(setupContainer).to.equal('does not have standard models');
done();
})
.catch(e => {
console.log({ e });
done();
});
});
});
after('remove test periodic dir', (done) => {
Promise.all([
fs.remove(setupDir),
])
.then(() => {
done();
}).catch(done);
});
}); |
/**
* @author mrdoob / http://mrdoob.com/
*/
import { UIPanel } from './libs/ui.js';
import { MenubarFile } from './MenubarFile.js';
import { MenubarEdit } from './MenubarEdit.js';
import { MenubarExamples } from './MenubarExamples.js';
import { MenubarHelp } from './MenubarHelp.js';
function Menubar( editor ) {
var container = new UIPanel();
container.setId( 'menubar' );
container.add( new MenubarFile( editor ) );
container.add( new MenubarEdit( editor ) );
container.add( new MenubarExamples( editor ) );
container.add( new MenubarHelp( editor ) );
return container;
}
export { Menubar };
|
require('babel-polyfill');
let MOCK_CONFIG = require('../config');
const onenetPassport = require('../index');
const assert = require('power-assert');
MOCK_CONFIG = process.env.NODE_ENV === 'test' ? MOCK_CONFIG.test : MOCK_CONFIG.prod;
describe('onenet-passport-token', () => {
it('getToken', async () => {
const result = await onenetPassport.getToken({
app_id: MOCK_CONFIG.APP_ID,
secret: MOCK_CONFIG.SECRET
});
assert.equal(result.code, 0);
});
describe('onenet-passport-method', () => {
let resUser = null;
before(async () => {
const user = {
username: `node-passport-name${(Math.random()).toString().slice(3, 9)}`,
password: '123456',
email: `node-passport-email${(Math.random()).toString().slice(3, 9)}@qq.com`,
user_type: MOCK_CONFIG.USER_TYPE.INDIVIDUAL,
reg_way: MOCK_CONFIG.REG_WAY.EMAIL,
};
const response = await onenetPassport.register(
user.username,
user.user_type,
user.reg_way,
user.email, null,
user.password);
assert.equal(response.code, 0);
assert(response.data.id);
resUser = Object.assign(user, response.data);
});
it('varifyName', async () => {
const response = await onenetPassport.validateName('a_none_existent_name');
assert.equal(response.code, 0);
});
it('login', async () => {
const response = await onenetPassport.login(resUser.username, resUser.password, '127.0.0.1', 'web');
assert.equal(response.code, 0);
});
it('changePassword', async () => {
const response = await onenetPassport.changePassword(resUser.id, resUser.password, '22222222');
assert.equal(response.code, 0);
});
it('patch', async () => {
const response = await onenetPassport.patch(resUser.id, 'leo');
assert.equal(response.code, 0);
});
it('getUserByName', async () => {
const response = await onenetPassport.getUserByName(resUser.username);
assert.equal(response.code, 0);
});
it('getUserListByName', async () => {
const response = await onenetPassport.getUserListByName(resUser.username);
assert.equal(response.code, 0);
});
it('getUserById', async () => {
const response = await onenetPassport.getUserById(resUser.id.toString());
assert.equal(response.code, 0);
});
});
});
|
$(function(){
//To DO: port this to backbone.js
var mapMarkersView = new window.MapMarkersView();
//this handles the tweet submission.
$('#tweet_form').submit(function(e){
e.preventDefault();
e.stopPropagation();
$('#tweet_btn').removeClass('btn-primary').text('Saving...').prop('disabled', true);
//get what is in the textarea
var tweet_string = $('#tweet_text').val();
var lat_out = 0;
var long_out = 0;
var send_tweet = function(gotCoordinatesIn)
{
//get uri from the form
var uri = $('form').attr('action');
//retrieve the token
var csrfToken = $('input[name="csrfmiddlewaretoken"]').val();
//data to send in json object to the server
var formData = {csrfmiddlewaretoken: csrfToken, tweet: tweet_string, status: status,latitude: lat_out,longitude: long_out,gotCoordinates: gotCoordinatesIn};
$.ajax({
type: "POST",
url: uri,
data: formData,
timeout: 7500,
//for showing user after bad tweet completion
after_tweet_modal: function(header,body){
$('#tweet_result_modal_header').html(header);
$('#tweet_result_modal_body').html(body);
$('#tweet_result_modal_body').addClass('text-error');
window.setTimeout($('#tweet_result_modal').modal('show'), 2000);
},
success: function (data) {
if(gotCoordinatesIn){
var center = new google.maps.LatLng(data.map_points[0]['latitude'],data.map_points[0]['longitude'])
mapMarkersView.geomap.setCenter(center);
mapMarkersView.collection.add(data.map_points);
renderNewMapMarker = function(){
mapMarkersView.collection.get(data.map_points[0]['id']).render(data.tweet_html);
}
window.setTimeout(renderNewMapMarker,3500);
}
$('#tweet_text').val('');
$(this).prop('disabled', false);
$('#word-counter').text(140);
},
error: function(jqXHR,textstatus,message) {
this.after_tweet_modal("Error: " +textstatus, message);
console.log("jqXHR.status: " + jqXHR.status);
console.log("textstatus: " + textstatus);
//console.log("message: " + message);
//alert("ok");
}
}).always(function() {
//analougous to a fnally in other languages
$('#tweet_btn').prop('disabled', false).addClass('btn-primary').text('Tweet');
});
}//end send tweet function
getCoor = function(position){
lat_out = position.coords.latitude;
long_out = position.coords.longitude;
send_tweet('True');
}
errorCoor = function(){
send_tweet('False');
console.log("");
}
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(getCoor, errorCoor, {maximumAge:60000, timeout:5000, enableHighAccuracy:true});
}
else
{
console.log("");
}
});
//this is a global variable
var toggle_warning = true;
function tweet_keylogger(inhere,toggler){
//don't know if this verios of javascript has trim()
var trimmed_str = inhere.val().replace(/^\s+|\s+$/g, '');
//check the trimmed string length
var str_len = trimmed_str.length;
//update the counter to reflect how many characters can still be displayed
$('#word-counter').text(140-str_len);
//if the characters are more then 140
if (str_len > 140){
//if toggler is true then action needs to be performed
if (toggler==true){
toggler = false;//reset toggler state
$('#word-counter').addClass('text-error lead');
$('#tweet_btn').prop('disabled', true).removeClass('btn-primary');
}
}
else if (str_len > 0)
{
if (toggler==false){
toggler = true;//reset toggler stat
$('#word-counter').removeClass('text-error lead');
$('#tweet_btn').prop('disabled', false).addClass('btn-primary');
}
}
else if (str_len == 0)
{
toggler = false;
$('#tweet_btn').prop('disabled', true).removeClass('btn-primary');
}
//toggler is only true between 1 and 140
return toggler
}
//This handles any modification or change in the text area
$('#tweet_text').on('keyup keypress keydown', function(e){
toggle_warning = tweet_keylogger($(this),toggle_warning);
});
})/*end jquery*/
|
function setup() {
createCanvas(1000, 600); //Create the canvas
background(0); //Make the background black
fill(255); //Change the fill color to white
ellipse(500, 300, 100, 100); //Draw the circle in the center of the screen
rect(10, 250, 20, 100); //Draw the rectangle on the left side of the screen
}
function draw() {
} |
import * as types from '../constants/ActionTypes';
export function fetchDataFailure(error) {
console.error(error);
if (error.response) {
return {
type: types.FETCH_DATA_FAILURE,
payload: {
status: error.response.status,
statusText: error.response.statusText
}
}
}
return {
type: types.FETCH_DATA_FAILURE,
payload: {
status: 909,
statusText: error
}
}
}
export function fetchDataRequest() {
return {
type: types.FETCH_DATA_REQUEST
}
}
export function receiveData(data) {
return {
type: types.RECEIVE_DATA,
payload: {
data: data
}
}
}
export function fetchData() {
return (dispatch) => {
dispatch(fetchDataRequest());
dispatch(receiveData('TEST'));
}
}
|
/* global require, describe, it */
'use strict';
// MODULES //
var // Expectation library:
chai = require( 'chai' ),
// Matrix data structure:
matrix = require( 'dstructs-matrix' ),
// Deep close to:
deepCloseTo = require( './utils/deepcloseto.js' ),
// Validate a value is NaN:
isnan = require( 'validate.io-nan' ),
// Module to be tested:
median = require( './../lib' ),
// Function to apply element-wise
MEDIAN = require( './../lib/number.js' );
// VARIABLES //
var expect = chai.expect,
assert = chai.assert;
// TESTS //
describe( 'compute-median', function tests() {
it( 'should export a function', function test() {
expect( median ).to.be.a( 'function' );
});
it( 'should throw an error if provided an invalid option', function test() {
var values = [
'5',
5,
true,
undefined,
null,
NaN,
[],
{}
];
for ( var i = 0; i < values.length; i++ ) {
expect( badValue( values[i] ) ).to.throw( TypeError );
}
function badValue( value ) {
return function() {
median( [1,2,3], {
'accessor': value
});
};
}
});
it( 'should throw an error if provided an array and an unrecognized/unsupported data type option', function test() {
var values = [
'beep',
'boop'
];
for ( var i = 0; i < values.length; i++ ) {
expect( badValue( values[i] ) ).to.throw( Error );
}
function badValue( value ) {
return function() {
median( [1,2,3], {
'dtype': value
});
};
}
});
it( 'should throw an error if provided a typed-array and an unrecognized/unsupported data type option', function test() {
var values = [
'beep',
'boop'
];
for ( var i = 0; i < values.length; i++ ) {
expect( badValue( values[i] ) ).to.throw( Error );
}
function badValue( value ) {
return function() {
median( new Int8Array([1,2,3]), {
'dtype': value
});
};
}
});
it( 'should throw an error if provided a matrix and an unrecognized/unsupported data type option', function test() {
var values = [
'beep',
'boop'
];
for ( var i = 0; i < values.length; i++ ) {
expect( badValue( values[i] ) ).to.throw( Error );
}
function badValue( value ) {
return function() {
median( matrix( [2,2] ), {
'dtype': value
});
};
}
});
it( 'should return NaN if the first argument is neither a number, array-like, or matrix-like', function test() {
var values = [
// '5', // valid as is array-like (length)
true,
undefined,
null,
// NaN, // allowed
function(){},
{}
];
for ( var i = 0; i < values.length; i++ ) {
assert.isTrue( isnan( median( values[ i ] ) ) );
}
});
it( 'should compute the distribution median when provided a number', function test() {
assert.closeTo( median( 0.5 ), 1.3862944, 1e-5 );
assert.closeTo( median( 1 ), 0.6931472, 1e-5 );
assert.closeTo( median( 2 ), 0.3465736, 1e-5 );
assert.closeTo( median( 4 ), 0.1732868, 1e-5 );
});
it( 'should compute the distribution median when provided a plain array', function test() {
var lambda, actual, expected;
lambda = [ 0.5, 1, 2, 4 ];
expected = [ 1.3862944, 0.6931472, 0.3465736, 0.1732868 ];
actual = median( lambda );
assert.notEqual( actual, lambda );
assert.isTrue( deepCloseTo( actual, expected, 1e-5 ) );
// Mutate...
actual = median( lambda, {
'copy': false
});
assert.strictEqual( actual, lambda );
assert.isTrue( deepCloseTo( actual, expected, 1e-5 ) );
});
it( 'should compute the distribution median when provided a typed array', function test() {
var lambda, actual, expected;
lambda = new Float64Array ( [ 0.5,1,2,4 ] );
expected = new Float64Array( [ 1.3862944,0.6931472,0.3465736,0.1732868 ] );
actual = median( lambda );
assert.notEqual( actual, lambda );
assert.isTrue( deepCloseTo( actual, expected, 1e-5 ) );
// Mutate:
actual = median( lambda, {
'copy': false
});
expected = new Float64Array( [ 1.3862944,0.6931472,0.3465736,0.1732868 ] );
assert.strictEqual( actual, lambda );
assert.isTrue( deepCloseTo( actual, expected, 1e-5 ) );
});
it( 'should compute the distribution median and return an array of a specific type', function test() {
var lambda, actual, expected;
lambda = [ 0.5, 1, 2, 4 ];
expected = new Int32Array( [ 1.3862944,0.6931472,0.3465736,0.1732868 ] );
actual = median( lambda, {
'dtype': 'int32'
});
assert.notEqual( actual, lambda );
assert.strictEqual( actual.BYTES_PER_ELEMENT, 4 );
assert.isTrue( deepCloseTo( actual, expected, 1e-5 ) );
});
it( 'should compute the distribution median using an accessor', function test() {
var lambda, actual, expected;
lambda = [
{'lambda':0.5},
{'lambda':1},
{'lambda':2},
{'lambda':4}
];
expected = [ 1.3862944, 0.6931472, 0.3465736, 0.1732868 ];
actual = median( lambda, {
'accessor': getValue
});
assert.notEqual( actual, lambda );
assert.isTrue( deepCloseTo( actual, expected, 1e-5 ) );
// Mutate:
actual = median( lambda, {
'accessor': getValue,
'copy': false
});
assert.strictEqual( actual, lambda );
assert.isTrue( deepCloseTo( actual, expected, 1e-5 ) );
function getValue( d ) {
return d.lambda;
}
});
it( 'should compute an element-wise distribution median and deep set', function test() {
var data, actual, expected;
data = [
{'x':[9,0.5]},
{'x':[9,1]},
{'x':[9,2]},
{'x':[9,4]}
];
expected = [
{'x':[9,1.3862944]},
{'x':[9,0.6931472]},
{'x':[9,0.3465736]},
{'x':[9,0.1732868]}
];
actual = median( data, {
'path': 'x.1'
});
assert.strictEqual( actual, data );
assert.isTrue( deepCloseTo( actual, expected, 1e-5 ) );
// Specify a path with a custom separator...
data = [
{'x':[9,0.5]},
{'x':[9,1]},
{'x':[9,2]},
{'x':[9,4]}
];
actual = median( data, {
'path': 'x/1',
'sep': '/'
});
assert.strictEqual( actual, data );
assert.isTrue( deepCloseTo( actual, expected, 1e-5 ) );
});
it( 'should compute an element-wise distribution median when provided a matrix', function test() {
var mat,
out,
d1,
d2,
i;
d1 = new Float64Array( 25 );
d2 = new Float64Array( 25 );
for ( i = 0; i < d1.length; i++ ) {
d1[ i ] = i / 10;
d2[ i ] = MEDIAN( i / 10 );
}
mat = matrix( d1, [5,5], 'float64' );
out = median( mat );
assert.deepEqual( out.data, d2 );
// Mutate...
out = median( mat, {
'copy': false
});
assert.strictEqual( mat, out );
assert.deepEqual( mat.data, d2 );
});
it( 'should compute an element-wise distribution median and return a matrix of a specific type', function test() {
var mat,
out,
d1,
d2,
i;
d1 = new Float64Array( 25 );
d2 = new Float32Array( 25 );
for ( i = 0; i < d1.length; i++ ) {
d1[ i ] = i + 1;
d2[ i ] = MEDIAN( i + 1 );
}
mat = matrix( d1, [5,5], 'float64' );
out = median( mat, {
'dtype': 'float32'
});
assert.strictEqual( out.dtype, 'float32' );
assert.deepEqual( out.data, d2 );
});
it( 'should return an empty data structure if provided an empty data structure', function test() {
assert.deepEqual( median( [] ), [] );
assert.deepEqual( median( matrix( [0,0] ) ).data, new Float64Array() );
assert.deepEqual( median( new Int8Array() ), new Float64Array() );
});
});
|
/*jshint node: true, esnext: true*/
const path = require('path');
const MinifyPlugin = require("babel-minify-webpack-plugin");
module.exports = {
entry: {
NuCore: 'nucore.js',
test: 'test.js',
widgets: 'widgets.js',
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'js'),
publicPath: 'js/',
library: '[name]',
libraryTarget: 'var',
},
module: {
rules: [{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
babelrc: true
},
}
}]
},
plugins: [
new MinifyPlugin(),
],
resolve: {
alias: {
maquette$: path.resolve(__dirname, 'node_modules/maquette/dist/index.js'),
},
modules: [
path.resolve(__dirname, 'src'),
'node_modules',
]
}
};
|
Crafty.viewport.followEdge = (function() {
var oldTarget, offx, offy, edx, edy
function change() {
var scale = Crafty.viewport._scale
// if (this.x > -Crafty.viewport.x + Crafty.viewport.width / 2 + edx - 10) {
Crafty.viewport.scroll('_x', -(this.x + (this.w / 2) - (Crafty.viewport.width / 2 / scale) - offx * scale) + edx)
Crafty.viewport.scroll('_y', -(this.y + (this.h / 2) - (Crafty.viewport.height / 2 / scale) - offy * scale))
Crafty.viewport._clamp()
// }
}
function stopFollow() {
if (oldTarget) {
oldTarget.unbind('Move', change)
oldTarget.unbind('ViewportScale', change)
oldTarget.unbind('ViewportResize', change)
}
}
Crafty._preBind("StopCamera", stopFollow)
return function(target, offsetx, offsety, edgex, edgey) {
if (!target || !target.has('2D'))
return
Crafty.trigger("StopCamera")
oldTarget = target
offx = (typeof offsetx !== 'undefined') ? offsetx : 0
offy = (typeof offsety !== 'undefined') ? offsety : 0
edy = (typeof edgex !== 'undefined') ? edgex : 0
edx = (typeof edgey !== 'undefined') ? edgey : 0
target.bind('Move', change)
target.bind('ViewportScale', change)
target.bind('ViewportResize', change)
change.call(target)
}
})()
|
module.exports = {
escape: function(html) {
return String(html)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
},
unescape: function(html) {
return String(html)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, '\'')
.replace(/</g, '<')
.replace(/>/g, '>');
}
}
|
// The MIT License (MIT)
//
// Copyright (c) 2015-2021 Camptocamp SA
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import angular from 'angular';
import olMap from 'ol/Map';
import olView from 'ol/View';
describe('ngeo.map.scaleselector', () => {
/** @type {JQuery<HTMLElement>} */
let element;
/** @type {import('ol/Map').default} */
let map;
beforeEach(() => {
map = new olMap({
view: new olView({
center: [0, 0],
zoom: 0,
}),
});
element = angular.element('<div ngeo-scaleselector ngeo-scaleselector-map="map"></div>');
// Silent warnings throw by the ngeo-scaleselector component.
const logWarnFn = console.warn;
console.warn = () => {};
angular.mock.inject(($rootScope, $compile, $sce) => {
$rootScope.map = map;
$compile(element)($rootScope);
$rootScope.$digest();
});
// Enable again warnings
console.warn = logWarnFn;
});
it('creates an element with expected number of li elements', () => {
const lis = element.find('li');
expect(lis.length).toBe(29);
expect(lis[0].innerText.trim()).toBe('1\u00a0:\u00a0500');
});
describe('calling setZoom in Angular context', () => {
it('does not throw', () => {
const scope = element.scope();
/**
*
*/
function test() {
scope.$apply(() => {
map.getView().setZoom(4);
});
}
expect(test).not.toThrow();
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.currentScale).toBe(50000);
});
});
it('calls getScale', () => {
const scope = element.scope();
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(0)).toBe(500);
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(0.5)).toEqual(750);
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(4)).toBe(50000);
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(28)).toBe(2);
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(28.1)).toBeUndefined();
// @ts-ignore: scope ...
expect(scope.scaleselectorCtrl.getScale(undefined)).toBeUndefined();
});
});
|
import {Ellipse} from '../shapes/ellipse'
import {EllipticalArc} from '../shapes/elliptical-arc'
import {Circle} from '../shapes/circle'
import {EditCircleTool} from './circle'
import {DragTool} from './drag'
import {EllipseTool, STATE_RADIUS} from './ellipse'
export function GetShapeEditTool(viewer, obj, alternative) {
if (obj instanceof Circle && !alternative) {
const tool = new EditCircleTool(viewer);
tool.circle = obj;
return tool;
} else if (obj instanceof Ellipse && !alternative) {
// even for an ell-arc we should act as it would be an ellipse to
// avoid stabilize constraints added and demoing B point on move
// so second arg must be FALSE!
const tool = new EllipseTool(viewer, false);
tool.ellipse = obj;
tool.state = STATE_RADIUS;
return tool;
} else {
return new DragTool(obj, viewer);
}
}
|
$(document).ready(function() {
onTableAjaxEscalaFun();
filtrarEscalas();
habilitarEscala();
})
function onTableAjaxEscalaFun(){
var servico = $(".servico").val();
if (!$(".servico").val()){
servico = 0;
}
oTableEscalaFun = $('.tableEscalaFun').dataTable({
"bJQueryUI": true,
"oLanguage": {
"sProcessing": "Processando...",
"sLengthMenu": "Mostrar _MENU_ registros",
"sZeroRecords": "Não foram encontrados resultados",
"sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
"sInfoEmpty": "Mostrando de 0 até 0 de 0 registros",
"sInfoFiltered": "(filtrado de _MAX_ registros no total)",
"sInfoPostFix": "",
"sSearch": "Buscar:",
"sUrl": "",
"oPaginate": {
"sFirst": "Primeiro",
"sPrevious": "Anterior",
"sNext": "Seguinte",
"sLast": "Último"
}
},
"sPaginationType": "full_numbers",
"bPaginate": false,
"bLengthChange": false,
"bInfo": false,
"bRetrieve": true,
"bProcessing": true,
"sAjaxSource": Routing.generate("escalaFunAjax", {
// 'inicio' : $(".inicio").val(),
// 'fim' : $(".fim").val(),
'status' : $(".status").val(),
'servico' : servico,
'inicio' : $(".inicio").val()
}),
"aoColumns": [
{ "mDataProp": "funcionariosString" },
// { "mDataProp": "escalaN",
// "sClass": "center"},
{ "mDataProp": "servicoEscala.nome"},
{ "mDataProp": "local" },
{ "mDataProp": "descricao"},
{ "mDataProp": "escalaEx",
"sClass": "center"},
{ "mDataProp": "ativo",
"sClass": "center check"},
{ "mDataProp": "id" },
],
"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
if (aData['ativo'] == true){
$('td:eq(5)', nRow).html('<img src="'+imageUrl+'check2.png">');
}else{
$('td:eq(5)', nRow).html('<img src="'+imageUrl+'uncheck2.png">');
}
},
"aoColumnDefs": [{"bVisible": false, "aTargets": [6]},
{"bSortable": false, "aTargets": [5]}],
"bAutoWidth": false,
// "fnDrawCallback": function ( oSettings ) {
// if ( oSettings.aiDisplay.length == 0 )
// {
// return;
// }
//
// var nTrs = $('.tableEscalaFun tbody tr');
// var iColspan = nTrs[0].getElementsByTagName('td').length;
// var sLastGroup = "";
// for ( var i=0 ; i<nTrs.length ; i++ )
// {
// var iDisplayIndex = oSettings._iDisplayStart + i;
// var sGroup = oSettings.aoData[ oSettings.aiDisplay[iDisplayIndex] ]._aData['funcionario']['nome'];
// if ( sGroup != sLastGroup )
// {
// var nGroup = document.createElement( 'tr' );
// var nCell = document.createElement( 'td' );
// nCell.colSpan = iColspan;
// nCell.className = "group";
// nCell.innerHTML = sGroup;
// nGroup.appendChild( nCell );
// nTrs[i].parentNode.insertBefore( nGroup, nTrs[i] );
// sLastGroup = sGroup;
// }
// }
// },
"sDom": '<"H"Tfr<"toolbar02">>t<"F"ip>',
"oTableTools": {
"sRowSelect": "single",
"sSwfPath": url_dominio+"/fnxadmin/table/tools/swf/copy_csv_xls_pdf.swf",
"sSelectedClass": "row_selected",
"aButtons": [
{
"sExtends": "print",
"sButtonText": '<img src="'+imageUrl+'print-icone.png">Print'
},
{
"sExtends": "pdf",
"mColumns": "visible",
"sPdfOrientation": "landscape",
"sPdfMessage": "Escalas",
"sButtonText": '<img src="'+imageUrl+'pdf-icone.png">PDF'
},
{
"sExtends": "text",
"sButtonText": '<img src="'+imageUrl+'add-icone.png">Adicionar',
"fnClick" : function(){
ajaxLoadDialog(Routing.generate("escalaFunAdd"), "Adicionar compromisso");
}
},
{
"sExtends": "select_single",
"sButtonText": '<img src="'+imageUrl+'edit-icone.png">Editar',
"sButtonClass": "hidden",
"fnClick" : function(){
var aaData = this.fnGetSelectedData()
id = aaData[0]["id"];
ajaxLoadDialog(Routing.generate("escalaFunEdit", {"id" : id}),"Editar compromisso");
}
},
{
"sExtends": "select_single",
"sButtonText": '<img src="'+imageUrl+'delete-icone.png">Deletar',
"sButtonClass": "hidden",
"fnClick" : function(){
var aaData = this.fnGetSelectedData()
id = aaData[0]["id"];
$( "#dialog-confirm" ).dialog("open");
$("#dialog-confirm").dialog("option", "title", "Remover compromisso");
$( "#dialog-confirm" ).dialog("option", "buttons", {
"Deletar": function() {
ajaxDelete(Routing.generate("escalaFunRemove", {"id" : id}));
$(this).dialog("close");
},
"Cancelar": function(){
$(this).dialog("close");
}
} );
return false;
}
}
]
}
});
}
function filtrarEscalas(){
$('#filtrarEscala').click(function(){
var servico = $(".servico").val();
if (!$(".servico").val()){
servico = 0;
}
var flag = false;
if ($(".inicio").val() == ""){
notifityParcela('erro01');
flag = true;
}
if ($(".fim").val() == ""){
notifityParcela('erro02')
flag = true
}
if (flag){
return false;
}
oTableEscalaFun.fnNewAjax(Routing.generate("escalaFunAjax", {
// 'inicio' : $(".inicio").val(),
// 'fim' : $(".fim").val(),
'status' : $(".status").val(),
'servico' : servico,
'inicio' : $(".inicio").val()
}));
oTableEscalaFun.dataTable().fnReloadAjax();
return false;
})
}
function habilitarEscala(){
$("#habilitarEscala").change(function(){
if ($('#habilitarEscala').is(':checked')){
$(".inicio").removeAttr("disabled");
$(".fim").removeAttr("disabled");
}else{
$(".inicio").attr("disabled", "disabled");
$(".fim").attr("disabled", "disabled")
}
});
}
$(".tableEscalaFun tbody td.check").live("click", function(){
var data = oTableEscalaFun.fnGetData(this.parentNode);
var url = Routing.generate("escalaFunCheck", {"id" : data['id']})
$.ajax({
type: 'POST',
url: url,
success: function(){
$('.redraw').dataTable().fnReloadAjax();
onReadyAjax();
return false;
}
})
}) |
"use strict";
var Disk = require('../');
var disk = new Disk();
disk.init(function() {
disk.getBlockDevice('sdb1', function(err, device) {
console.log('Delete Partition ...');
device.deletePartition(function() {
console.log('Done');
process.exit();
});
});
});
|
require('./dist/config/lib/app').Application.run();
|
var page = require('webpage').create(),
system = require('system'),
address, output, selector;
if (system.args.length < 2) {
console.log('Usage: snapa.js URL output [selector]');
console.log(' opens a page and renders the contents of selector to output file');
phantom.exit(1);
} else {
address = system.args[1];
output = system.args[2];
selector = system.args[3] || 'body';
page.open(address, function () {
page.clipRect = page.evaluate(function(selector) {
return document.querySelector(selector).getBoundingClientRect();
}, selector);
page.render(output);
phantom.exit();
});
}
|
"use strict";
let datafire = require('datafire');
let openapi = require('./openapi.json');
module.exports = datafire.Integration.fromOpenAPI(openapi, "twilio"); |
'use strict';
// Declare app level module which depends on filters, and services
angular.module('myApp', [
'ngRoute',
'myApp.filters',
'myApp.services',
'myApp.directives',
'myApp.controllers'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'views/partials/partial1.html',
controller: 'MyCtrl1'
});
$routeProvider.when('/view2', {
templateUrl: 'views/partials/partial2.html',
controller: 'MyCtrl2'
});
// $routeProvider.otherwise({
// redirectTo: '/view1'
// });
}]);
|
/**
* User: Jomaras
* Date: 23.08.12.
* Time: 10:30
*/
var HtmlModelMapping =
{
models: [],
push: function(model)
{
this.models.push(model)
},
getModel: function(url)
{
for(var i = 0; i < this.models.length; i++)
{
var model = this.models[i];
if(model.url == url)
{
return model.model;
}
}
return null;
},
getWholeFileModel: function(url)
{
for(var i = 0; i < this.models.length; i++)
{
var model = this.models[i];
if(model.url == url)
{
return model;
}
}
return null;
},
getFirstModelMapping: function()
{
return this.models[0];
}
}; |
var config = require("./config");
var mongoose = require("mongoose");
module.exports = function() {
//mongoose.Promise = global.Promise;
var db = mongoose.connect(config.db);
require("../Core/Users/server/models/user.server.model");
require("../GameTracker/server/models/game.server.model");
return db;
};
|
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ngRoute',
'myApp.presentation',
'myApp.content',
'myApp.version'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/presentation'});
}]);
|
var path = require('path'),
rootPath = path.normalize(__dirname + '/..'),
env = process.env.NODE_ENV || 'development';
var config = {
development: {
root: rootPath,
app: {
name: 'specialblog-node-js'
},
port: 3000,
db: 'mongodb://localhost/specialblog-node-js-development'
},
test: {
root: rootPath,
app: {
name: 'specialblog-node-js'
},
port: 3000,
db: 'mongodb://localhost/specialblog-node-js-test'
},
production: {
root: rootPath,
app: {
name: 'specialblog-node-js'
},
port: 3000,
db: 'mongodb://localhost/specialblog-node-js-production'
}
};
module.exports = config[env];
|
module.exports.apiCurrentUserDelete = function(DELETE, urlApiCurrentUser) {
return DELETE(urlApiCurrentUser(), function(currentUser, endForbiddenTokenRequired, deleteUserWhereId, end) {
if (currentUser == null) {
return endForbiddenTokenRequired();
}
return deleteUserWhereId(currentUser.id).then(function() {
return end();
});
});
};
|
module.exports = {
game:{},
scope:{},
}
|
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ui.router',
'myApp.home',
'myApp.about'
]).
config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
// $urlRouterProvider.otherwise("/view1");
$stateProvider
.state('home', {
url: "/home",
templateUrl: 'app/templates/views/home.html',
controller: 'homeCtrl'
})
.state('about', {
url: "/about",
templateUrl: 'app/templates/views/about.html',
controller: 'aboutCtrl'
})
}]);
|
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const { API_URL } = require('sharify').data;
export const ArtworkRelations = {
related() {
if (this.__related__ != null) { return this.__related__; }
const { Artist } = require('../../artist');
const { SaleArtwork } = require('../../sale_artwork');
const { Partner } = require('../../partner');
const { Artworks } = require('../../../collections/artworks');
const { Sales } = require('../../../collections/sales');
const { Artists } = require('../../../collections/artists');
const artist = new Artist(this.get('artist'));
const saleArtwork = new SaleArtwork(this.get('sale_artwork'));
const partner = new Partner(this.get('partner'));
const artists = new Artists(this.get('artists'));
const sales = new Sales;
sales.url = `${API_URL}/api/v1/related/sales?artwork[]=${this.id}&active=true&cache_bust=${Math.random()}`;
const artworks = new Artworks;
artworks.url = `${API_URL}/api/v1/related/layer/synthetic/main/artworks?artwork[]=${this.id}`;
return this.__related__ = {
artist,
saleArtwork,
partner,
sales,
artists,
artworks
};
}
};
|
'use strict';
jest.mock('../../../src/lib/analytics');
jest.mock('../../../src/lib/create-assets-url');
jest.mock('../../../src/lib/create-deferred-client');
const analytics = require('../../../src/lib/analytics');
const createDeferredClient = require('../../../src/lib/create-deferred-client');
const PreferredPaymentMethods = require('../../../src/preferred-payment-methods/preferred-payment-methods');
describe('PreferredPaymentMethods', () => {
let testContext;
beforeEach(() => {
testContext = {};
testContext.fakeClient = {};
jest.spyOn(createDeferredClient, 'create').mockImplementation(() => new Promise(resolve => {
process.nextTick(() => {
resolve(testContext.fakeClient);
});
}));
});
describe('initialize', () => {
it('creates a deferred client', () => {
testContext.instance = new PreferredPaymentMethods();
testContext.fakeClient = {};
return testContext.instance.initialize({
authorization: 'fake-auth'
}).then(() => {
expect(createDeferredClient.create).toHaveBeenCalledTimes(1);
expect(createDeferredClient.create).toHaveBeenCalledWith({
authorization: 'fake-auth',
assetsUrl: 'https://example.com/assets',
name: 'PreferredPaymentMethods'
});
});
});
it('resolves with self', () => {
expect(new PreferredPaymentMethods().initialize({ client: testContext.fakeClient }))
.resolves.toBeInstanceOf(PreferredPaymentMethods);
});
it('sends an initialized analytics event', () =>
new PreferredPaymentMethods().initialize({ client: {}}).then(() => {
expect(analytics.sendEvent).toHaveBeenCalledTimes(1);
expect(analytics.sendEvent).toHaveBeenCalledWith(expect.anything(), 'preferred-payment-methods.initialized');
}));
});
describe('fetchPreferredPaymentMethods', () => {
beforeEach(() => {
testContext.fakeClient = {
request: jest.fn().mockResolvedValue(null)
};
testContext.instance = new PreferredPaymentMethods();
return testContext.instance.initialize({ client: testContext.fakeClient }).then(() => {
analytics.sendEvent.mockClear();
});
});
it('sends a GraphQL request for preferred payment methods', () => {
testContext.fakeClient.request.mockResolvedValue({
data: {
preferredPaymentMethods: {
paypalPreferred: true,
venmoPreferred: true
}
}
});
return testContext.instance.fetchPreferredPaymentMethods().then(() => {
expect(testContext.fakeClient.request).toHaveBeenCalledTimes(1);
expect(testContext.fakeClient.request).toHaveBeenCalledWith({
api: 'graphQLApi',
data: {
query: 'query PreferredPaymentMethods { ' +
'preferredPaymentMethods { ' +
'paypalPreferred ' +
'venmoPreferred ' +
'} ' +
'}'
}
});
});
});
it('returns a promise with both Venmo and PayPal preferred true when GraphQL returns true', () => {
testContext.fakeClient.request.mockResolvedValue({
data: {
preferredPaymentMethods: {
paypalPreferred: true,
venmoPreferred: true
}
}
});
return testContext.instance.fetchPreferredPaymentMethods().then(({ paypalPreferred, venmoPreferred }) => {
expect(paypalPreferred).toBe(true);
expect(venmoPreferred).toBe(true);
expect(analytics.sendEvent).toHaveBeenCalledTimes(2);
expect(analytics.sendEvent).toHaveBeenCalledWith(testContext.fakeClient, 'preferred-payment-methods.paypal.api-detected.true');
expect(analytics.sendEvent).toHaveBeenCalledWith(testContext.fakeClient, 'preferred-payment-methods.venmo.api-detected.true');
});
});
it('returns a promise with both PayPal and Venmo preferred false when GraphQL returns false', () => {
testContext.fakeClient.request.mockResolvedValue({
data: {
preferredPaymentMethods: {
paypalPreferred: false,
venmoPreferred: false
}
}
});
return testContext.instance.fetchPreferredPaymentMethods().then(({ paypalPreferred, venmoPreferred }) => {
expect(paypalPreferred).toBe(false);
expect(venmoPreferred).toBe(false);
expect(analytics.sendEvent).toHaveBeenCalledTimes(2);
expect(analytics.sendEvent).toHaveBeenCalledWith(testContext.fakeClient, 'preferred-payment-methods.paypal.api-detected.false');
expect(analytics.sendEvent).toHaveBeenCalledWith(testContext.fakeClient, 'preferred-payment-methods.venmo.api-detected.false');
});
});
it('returns a promise with both PayPal and Venmo preferred false when an error occurs', () => {
testContext.fakeClient.request.mockRejectedValue(new Error('No preferred payment methods for you!'));
return testContext.instance.fetchPreferredPaymentMethods().then(({ paypalPreferred, venmoPreferred }) => {
expect(paypalPreferred).toBe(false);
expect(venmoPreferred).toBe(false);
expect(analytics.sendEvent).toHaveBeenCalledTimes(1);
expect(analytics.sendEvent).toHaveBeenCalledWith(testContext.fakeClient, 'preferred-payment-methods.api-error');
});
});
it('waits for deferred client to complete before making a request', () => {
let clientFinished = false;
const fakeClient = testContext.fakeClient;
const instance = new PreferredPaymentMethods();
fakeClient.request.mockResolvedValue({
data: {
preferredPaymentMethods: {
paypalPreferred: true,
venmoPreferred: true
}
}
});
jest.spyOn(createDeferredClient, 'create').mockImplementation(() => new Promise(resolve => {
process.nextTick(() => {
clientFinished = true;
resolve(fakeClient);
});
}));
return instance.initialize({ authorization: 'fake-auth' }).then(() => {
expect(clientFinished).toBe(false);
return instance.fetchPreferredPaymentMethods();
}).then(() => {
expect(clientFinished).toBe(true);
});
});
it('rejects if a setup error occurs creating the deferred client', () => {
let didNotErrorOnInitialize = true;
const setupError = new Error('setup');
const instance = new PreferredPaymentMethods();
jest.spyOn(createDeferredClient, 'create').mockRejectedValue(setupError);
return instance.initialize({ authorization: 'fake-auth' }).catch(() => {
// should not get here
didNotErrorOnInitialize = false;
}).then(() => instance.fetchPreferredPaymentMethods()).catch(err => {
expect(didNotErrorOnInitialize).toBe(true);
expect(err).toBe(setupError);
});
});
});
});
|
!function () {
'use strict';
function CacheProvider() {}
CacheProvider.prototype.startSession = function (cacheKey) {
throw new Error('CacheProvider.startSession must be implemented');
};
CacheProvider.prototype.endSession = function () {
throw new Error('CacheProvider.endSession must be implemented');
};
CacheProvider.prototype.load = function (name, callback) {
callback(new Error('CacheProvider.load must be implemented'));
};
CacheProvider.prototype.save = function (name, inputs, outputs, callback) {
callback(new Error('CacheProvider.save must be implemented'));
};
module.exports = CacheProvider;
}(); |
version https://git-lfs.github.com/spec/v1
oid sha256:6a9267589457fe911713acdd6d9af4b893b598e85da38247fbade2026ff99ca6
size 95226
|
import './ChapterHeader.styl'
import Store from './../../../../../../flux/store/mobile/index'
import EventsConstants from './../../../../../../flux/constants/EventsConstants'
class ChapterHeader extends React.Component {
constructor() {
super()
this.state = {
index: '',
title: ''
}
this.nextState = {
index: '',
title: ''
}
this.routeChanged = this.routeChanged.bind( this )
}
componentDidMount() {
Store.on( EventsConstants.ROUTE_CHANGED, this.routeChanged )
this.swapTl = new TimelineMax({
paused: true,
onComplete: () => {
this.setState( this.nextState )
}
})
this.swapTl.fromTo( this.refs.index, 0.5, { y: 0, opacity: 1 }, { y: 10, opacity: 0, ease: Sine.easeInOut }, 0 )
this.swapTl.fromTo( this.refs.title, 0.5, { y: 0, opacity: 1 }, { y: 10, opacity: 0, ease: Sine.easeInOut }, 0.2 )
}
render() {
return (
<div className="chapter-header">
<strong className="chapter-header__index" ref="index">{ this.state.index }</strong>
<h3 className="chapter-header__title" ref="title">{ this.state.title }</h3>
</div>
)
}
componentDidUpdate() {
this.swapTl.reverse()
}
routeChanged( routes ) {
switch ( routes.newRoute ) {
case '/indochine':
this.nextState.index = '01'
this.nextState.title = 'Indochine'
break
case '/troubles':
this.nextState.index = '02'
this.nextState.title = 'Troubles'
break
case '/notoriete':
this.nextState.index = '03'
this.nextState.title = 'Notoriété'
break
case '/duras-song':
this.nextState.index = '04'
this.nextState.title = 'Duras Song'
break
default:
this.nextState.index = ''
this.nextState.title = ''
}
this.swapTl.play( 0 )
}
}
export default ChapterHeader |
module.exports = {
Reader: require('./reader')
} |
var express = require('express')
var PORT = 3000
var app = express()
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html')
})
app.listen(PORT, function () {
console.log('Patiently waiting for aliens to make contact on port: ', PORT)
})
|
module.exports = {
extends: [
'plugin:vue/recommended'
],
rules: {
// override/add rules' settings here
// see rules at https://www.npmjs.com/package/eslint-plugin-vue#bulb-rules
// modify level: strongly-recommended
//
//
'vue/html-self-closing': ['error', {
html: {
void: 'always', // html.void : The style of well-known HTML void elements like <br/>
normal: 'never' // The style of well-known HTML elements except void elements.
}
}],
'vue/max-attributes-per-line': ['error', {
singleline: 2,
multiline: {
max: 2,
allowFirstLine: true
}
}],
'vue/mustache-interpolation-spacing': ['error', 'never'],
'vue/name-property-casing': ['error', 'kebab-case'],
'vue/require-default-prop': 'off', // TODO: actuellement c'est undefined
'vue/require-prop-types': 'off', //on ne type pas en js, on desactive cette regle
'vue/v-bind-style': ['error', 'longform'],
'vue/v-on-style': ['error', 'longform'],
//
//
// modify level: recommended
//
//
'vue/attributes-order': ['off', // TODO: souhitable ? valider l'ordre alternatif ?
{
order: [
'CONDITIONALS', // ex: 'v-if', 'v-else-if', 'v-else', 'v-show', 'v-cloak'
'LIST_RENDERING', // ex: 'v-for item in items'
'RENDER_MODIFIERS', // ex: 'v-once', 'v-pre'
'GLOBAL', // ex: 'id'
'DEFINITION', // ex: 'is'
'UNIQUE', // ex: 'ref', 'key', 'slot'
'BINDING', // ex: 'v-model', 'v-bind', ':property="foo"'
'OTHER_ATTR', // ex: 'customProp="foo"'
'EVENTS', // ex: '@click="functionCall"', 'v-on="event"'
'CONTENT' // ex: 'v-text', 'v-html'
]
}],
//
//
// add Uncategorized rules
//
//
'vue/html-closing-bracket-newline': 'off',
'vue/html-closing-bracket-spacing': ['error', {
selfClosingTag: 'never' // disallow spaces
}],
'vue/prop-name-casing': ['error', 'snake_case'],
'vue/script-indent': 'off', // on ne met pas de javascript dans les .vue, le linting normal s'applique
// upgrade eslint plugin vue 6.x
'vue/no-v-html': 'off',
'vue/no-use-v-if-with-v-for': 'off',
'vue/multiline-html-element-content-newline': 'off',
'vue/singleline-html-element-content-newline': 'off'
}
};
|
"use strict";
const init = require("..");
const amqpBehaviour = {
url: "amqp://localhost",
exchange: "my-excchange",
ack: "true",
prefetch: 10
};
const broker = init(amqpBehaviour);
broker.on("connected", () => {
console.log("Connected to amqp server");
});
broker.on("subscribed", (subscription) => {
console.log("Subscription started:", subscription);
});
// Simplest way to deal with errors: abort the process.
// Assuming of course that you have a scheduler or process manager (kubernetes,
// pm2, forever etc) in place to restart your process.
//
// NOTE: See the "subcribe-reconnect" example on how to handle errors without
// restarting the process.
broker.on("error", (error) => {
console.error("Amqp error", error, ", aborting process.");
process.exit(1);
});
function handleMessage(message, meta, notify) {
console.log("Got message", message, "with routing key", meta.fields.routingKey);
notify.ack();
}
broker.subscribe("some-routing-key", "some-queue", handleMessage);
setInterval(() => {
broker.publish("some-routing-key", `Hello ${new Date()}`);
}, 1000);
|
'use strict';
module.exports = {
db: 'mongodb://localhost/worldcup',
app: {
name: 'MEAN - FullStack JS - Development'
},
facebook: {
clientID: 'APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/facebook/callback'
},
twitter: {
clientID: 'CONSUMER_KEY',
clientSecret: 'CONSUMER_SECRET',
callbackURL: 'http://localhost:3000/auth/twitter/callback'
},
github: {
clientID: 'APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/github/callback'
},
google: {
clientID: 'APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/google/callback'
},
linkedin: {
clientID: 'API_KEY',
clientSecret: 'SECRET_KEY',
callbackURL: 'http://localhost:3000/auth/linkedin/callback'
}
};
|
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v0.11.0-master-1a99821
*/
(function( window, angular, undefined ){
"use strict";
/**
* @private
* @ngdoc module
* @name material.components.switch
*/
angular.module('material.components.switch', [
'material.core',
'material.components.checkbox'
])
.directive('mdSwitch', MdSwitch);
/**
* @private
* @ngdoc directive
* @module material.components.switch
* @name mdSwitch
* @restrict E
*
* The switch directive is used very much like the normal [angular checkbox](https://docs.angularjs.org/api/ng/input/input%5Bcheckbox%5D).
*
* As per the [material design spec](http://www.google.com/design/spec/style/color.html#color-ui-color-application)
* the switch is in the accent color by default. The primary color palette may be used with
* the `md-primary` class.
*
* @param {string} ng-model Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {expression=} ng-true-value The value to which the expression should be set when selected.
* @param {expression=} ng-false-value The value to which the expression should be set when not selected.
* @param {string=} ng-change Angular expression to be executed when input changes due to user interaction with the input element.
* @param {boolean=} md-no-ink Use of attribute indicates use of ripple ink effects.
* @param {string=} aria-label Publish the button label used by screen-readers for accessibility. Defaults to the switch's text.
*
* @usage
* <hljs lang="html">
* <md-switch ng-model="isActive" aria-label="Finished?">
* Finished ?
* </md-switch>
*
* <md-switch md-no-ink ng-model="hasInk" aria-label="No Ink Effects">
* No Ink Effects
* </md-switch>
*
* <md-switch ng-disabled="true" ng-model="isDisabled" aria-label="Disabled">
* Disabled
* </md-switch>
*
* </hljs>
*/
function MdSwitch(mdCheckboxDirective, $mdUtil, $mdConstant, $parse, $$rAF, $mdGesture) {
var checkboxDirective = mdCheckboxDirective[0];
return {
restrict: 'E',
priority: 210, // Run before ngAria
transclude: true,
template:
'<div class="md-container">' +
'<div class="md-bar"></div>' +
'<div class="md-thumb-container">' +
'<div class="md-thumb" md-ink-ripple md-ink-ripple-checkbox></div>' +
'</div>'+
'</div>' +
'<div ng-transclude class="md-label"></div>',
require: '?ngModel',
compile: mdSwitchCompile
};
function mdSwitchCompile(element, attr) {
var checkboxLink = checkboxDirective.compile(element, attr);
// No transition on initial load.
element.addClass('md-dragging');
return function (scope, element, attr, ngModel) {
ngModel = ngModel || $mdUtil.fakeNgModel();
var disabledGetter = null;
if (attr.disabled != null) {
disabledGetter = function() { return true; };
} else if (attr.ngDisabled) {
disabledGetter = $parse(attr.ngDisabled);
}
var thumbContainer = angular.element(element[0].querySelector('.md-thumb-container'));
var switchContainer = angular.element(element[0].querySelector('.md-container'));
// no transition on initial load
$$rAF(function() {
element.removeClass('md-dragging');
});
checkboxLink(scope, element, attr, ngModel);
if (disabledGetter) {
scope.$watch(disabledGetter, function(isDisabled) {
element.attr('tabindex', isDisabled ? -1 : 0);
});
}
// These events are triggered by setup drag
$mdGesture.register(switchContainer, 'drag');
switchContainer
.on('$md.dragstart', onDragStart)
.on('$md.drag', onDrag)
.on('$md.dragend', onDragEnd);
var drag;
function onDragStart(ev) {
// Don't go if the switch is disabled.
if (disabledGetter && disabledGetter(scope)) return;
ev.stopPropagation();
element.addClass('md-dragging');
drag = {width: thumbContainer.prop('offsetWidth')};
element.removeClass('transition');
}
function onDrag(ev) {
if (!drag) return;
ev.stopPropagation();
ev.srcEvent && ev.srcEvent.preventDefault();
var percent = ev.pointer.distanceX / drag.width;
//if checked, start from right. else, start from left
var translate = ngModel.$viewValue ? 1 + percent : percent;
// Make sure the switch stays inside its bounds, 0-1%
translate = Math.max(0, Math.min(1, translate));
thumbContainer.css($mdConstant.CSS.TRANSFORM, 'translate3d(' + (100*translate) + '%,0,0)');
drag.translate = translate;
}
function onDragEnd(ev) {
if (!drag) return;
ev.stopPropagation();
element.removeClass('md-dragging');
thumbContainer.css($mdConstant.CSS.TRANSFORM, '');
// We changed if there is no distance (this is a click a click),
// or if the drag distance is >50% of the total.
var isChanged = ngModel.$viewValue ? drag.translate > 0.5 : drag.translate < 0.5;
if (isChanged) {
applyModelValue(!ngModel.$viewValue);
}
drag = null;
}
function applyModelValue(newValue) {
scope.$apply(function() {
ngModel.$setViewValue(newValue);
ngModel.$render();
});
}
};
}
}
MdSwitch.$inject = ["mdCheckboxDirective", "$mdUtil", "$mdConstant", "$parse", "$$rAF", "$mdGesture"];
})(window, window.angular); |
'use strict';
// this is the concatenated source from the video
// and includes the HTML partials as javascript objects.
(function ( window, angular, undefined ) {
(function(app) {
app.config([
'$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$stateProvider.state('app', {
url: '/',
views: {
'header': {
templateUrl: 'templates/header.tpl.html'
},
'sidebar': {
templateUrl: 'templates/sidebar.tpl.html'
},
'content': {
templateUrl: 'templates/content.tpl.html'
},
'footer': {
templateUrl: 'templates/footer.tpl.html'
}
}
});
$urlRouterProvider.otherwise('/');
}
]);
app.controller('AppController', ['$scope', '$rootScope', '$state',
function ($scope, $rootScope, $state) {
console.log('Global AppController - $state:', $state, '$rootScope: ', $rootScope);
$scope.$state = $state;
}
]);
}(angular.module('app', [
'app.namespace',
'app.config',
'app.services',
'app.alt-one',
'app.alt-two',
'app.alt-three',
'templates-app',
'templates-common',
'ui.router'
])));
angular.module('blink', []).directive('blink', [
'$timeout',
function ($timeout) {
return {
restrict: 'E',
transclude: true,
scope: {},
controller: [
'$scope',
'$element',
function ($scope, $element) {
var opacity = '0.0';
function toggleOpacity() {
opacity = (opacity === '1.0') ? '0.0' : '1.0';
$element.css('opacity', opacity);
$timeout(toggleOpacity, 400);
}
toggleOpacity();
}
],
template: '<span ng-transclude></span>',
replace: true
};
}
]);
})( window, window.angular );
|
const MnCheckbox = require('../checkbox/checkbox.class.js')
const evaluate = require('evaluate-string')
module.exports = class MnRadio extends MnCheckbox {
constructor(self) {
self = super(self)
return self
}
connectedCallback() {
this.innerHTML = ''
this._setStyle()
super._setLabel()
this._setInput()
this._setCustomInput()
this._setForm()
// this.checked = this.hasAttribute('checked')
this.disabled = this.hasAttribute('disabled')
this.readonly = this.hasAttribute('readonly')
this.name = this.hasAttribute('name')
this._setValidations()
}
_setStyle() {
this.classList.add('mn-radio')
this.classList.add('mn-option')
}
_setInput() {
this.input = document.createElement('input')
this.input.setAttribute('type', 'radio')
this.label.appendChild(this.input)
this.input.addEventListener('change', (event) => {
this.checked
? this.setAttribute('checked', '')
: this.removeAttribute('checked')
this.options.forEach(option => {
if (option !== event.target.closest('mn-radio')) {
option.removeAttribute('checked')
option.input.checked = false
}
option.form && option.form.classList && option.form.classList.contains('submitted')
? option.validate()
: null
})
})
}
_setCustomInput() {
const input = document.createElement('div')
input.classList.add('input')
this.label.appendChild(input)
}
_setValidations() {
this.validations = {
required: () => !this.value,
}
}
get options() {
const name = this.getAttribute('name')
? `[name="${this.getAttribute('name')}"]`
: ':not([name])'
return Array.from(this.form.querySelectorAll(`.mn-radio${name}`))
}
get value() {
const value = this
.options
.filter(option => option.checked)
.map(option => option.hasAttribute('value')
? evaluate(option.getAttribute('value'))
: option.getAttribute('placeholder')
)
return value[0]
}
set value(value) {
this.options.forEach(option => {
option.checked = false
})
const option = this.options.find(option => evaluate(option.getAttribute('value')) === value)
if (option) {
option.checked = true
}
}
}
|
(function (window, undefined) {
'use strict';
namespace('Lab');
function EmployeeCollection(json) {
/**
*
* @type {Array<Lab.Employee>}
*/
this.collection = [];
this.init(json);
}
EmployeeCollection.prototype = {
constructor : EmployeeCollection,
/**
*
* @param json {Array}
*/
init : function (json) {
this.json = json;
for (var i = 0, ii = json.length; i < ii; i++) {
this.collection.push(new Lab.Employee(json[i].properties));
}
},
getCollection : function () {
return this.collection;
},
getSize : function () {
return this.collection.length;
},
getMaxDistanceToWork : function () {
var collection = this.getCollection(),
item = _.max(collection, function (item) {
return parseFloat(item.getDistanceToWork());
});
return item.getDistanceToWork();
},
getMinDistanceToWork : function () {
var collection = this.getCollection(),
item = _.min(collection, function (item) {
return parseFloat(item.getDistanceToWork());
});
return item.getDistanceToWork();
}
};
Lab.EmployeeCollection = EmployeeCollection;
}(window)); |
/**
* @Author: Zhengfeng.Yao <yzf>
* @Date: 2017-07-03 14:20:48
* @Last modified by: yzf
* @Last modified time: 2017-07-03 14:20:51
*/
import React from 'react';
import { findDOMNode } from 'react-dom';
import BaseTable, { Column, ColumnGroup } from './base';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Pagination from '../pagination';
import Icon from '../icon';
import Loading from '../loading';
import warning from 'warning';
import FilterDropdown from './filterDropdown';
import createStore from './createStore';
import SelectionBox from './SelectionBox';
import SelectionCheckboxAll from './SelectionCheckboxAll';
import { flatArray, treeMap, flatFilter, normalizeColumns } from './util';
import s from './style';
function noop() {
}
function stopPropagation(e) {
e.stopPropagation();
if (e.nativeEvent.stopImmediatePropagation) {
e.nativeEvent.stopImmediatePropagation();
}
}
const defaultPagination = {
onChange: noop,
onShowSizeChange: noop
};
const defaultLocale = {
filterTitle: '筛选',
filterConfirm: '确定',
filterReset: '重置',
emptyText: <span><Icon type="frown-o" />暂无数据</span>,
selectAll: '全选当页',
selectInvert: '反选当页'
};
/**
* 避免生成新对象,这样父组件的shouldComponentUpdate可以更好的起作用
*/
const emptyObject = {};
export default class Table extends React.Component {
static Column = Column;
static ColumnGroup = ColumnGroup;
static propTypes = {
dataSource: PropTypes.array,
columns: PropTypes.array,
prefixCls: PropTypes.string,
useFixedHeader: PropTypes.bool,
rowSelection: PropTypes.object,
className: PropTypes.string,
size: PropTypes.string,
loading: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.object
]),
bordered: PropTypes.bool,
noborder: PropTypes.bool,
onChange: PropTypes.func,
locale: PropTypes.object,
dropdownPrefixCls: PropTypes.string
};
static defaultProps = {
dataSource: [],
prefixCls: s.tablePrefix,
useFixedHeader: false,
rowSelection: null,
className: '',
size: 'large',
loading: false,
bordered: false,
noborder: false,
indentSize: 20,
locale: {},
rowKey: 'key',
showHeader: true
};
constructor(props) {
super(props);
this.columns = props.columns || normalizeColumns(props.children);
this.state = Object.assign({}, this.getSortStateFromColumns(), {
// 减少状态
filters: this.getFiltersFromColumns(),
pagination: this.getDefaultPagination(props)
});
this.CheckboxPropsCache = {};
this.store = createStore({
selectedRowKeys: (props.rowSelection || {}).selectedRowKeys || [],
selectionDirty: false
});
}
getCheckboxPropsByItem = (item, index) => {
const { rowSelection = {} } = this.props;
if (!rowSelection.getCheckboxProps) {
return {};
}
const key = this.getRecordKey(item, index);
if (!this.CheckboxPropsCache[key]) {
this.CheckboxPropsCache[key] = rowSelection.getCheckboxProps(item);
}
return this.CheckboxPropsCache[key];
};
getDefaultSelection = () => {
const { rowSelection = {} } = this.props;
if (!rowSelection.getCheckboxProps) {
return [];
}
return this.getFlatData()
.filter((item, rowIndex) => this.getCheckboxPropsByItem(item, rowIndex).defaultChecked)
.map((record, rowIndex) => this.getRecordKey(record, rowIndex));
};
getDefaultPagination = props => {
const pagination = props.pagination || {};
return this.hasPagination(props) ? Object.assign(
{}, defaultPagination, pagination, {
current: pagination.defaultCurrent || pagination.current || 1,
pageSize: pagination.defaultPageSize || pagination.pageSize || 10
}) : {};
};
getLocale = () => {
return Object.assign({}, defaultLocale, this.props.locale);
};
componentWillReceiveProps(nextProps) {
this.columns = nextProps.columns || normalizeColumns(nextProps.children);
if ('pagination' in nextProps || 'pagination' in this.props) {
this.setState(previousState => {
const newPagination = Object.assign({}, defaultPagination, previousState.pagination);
newPagination.current = newPagination.current || 1;
newPagination.pageSize = newPagination.pageSize || 10;
return { pagination: nextProps.pagination !== false ? newPagination : emptyObject };
});
}
if (nextProps.rowSelection && 'selectedRowKeys' in nextProps.rowSelection) {
this.store.setState({
selectedRowKeys: nextProps.rowSelection.selectedRowKeys || []
});
const { rowSelection } = this.props;
if (rowSelection && (
nextProps.rowSelection.getCheckboxProps !== rowSelection.getCheckboxProps
)) {
this.CheckboxPropsCache = {};
}
}
if ('dataSource' in nextProps && nextProps.dataSource !== this.props.dataSource) {
this.store.setState({
selectionDirty: false
});
this.CheckboxPropsCache = {};
}
if (this.getSortOrderColumns(this.columns).length > 0) {
const sortState = this.getSortStateFromColumns(this.columns);
if (sortState.sortColumn !== this.state.sortColumn ||
sortState.sortOrder !== this.state.sortOrder) {
this.setState(sortState);
}
}
const filteredValueColumns = this.getFilteredValueColumns(this.columns);
if (filteredValueColumns.length > 0) {
const filtersFromColumns = this.getFiltersFromColumns(this.columns);
const newFilters = Object.assign({}, this.state.filters);
Object.keys(filtersFromColumns).forEach(key => {
newFilters[key] = filtersFromColumns[key];
});
if (this.isFiltersChanged(newFilters)) {
this.setState({ filters: newFilters });
}
}
}
setSelectedRowKeys = (selectedRowKeys, { selectWay, record, checked, changeRowKeys }) => {
const { rowSelection = {} } = this.props;
if (rowSelection && !('selectedRowKeys' in rowSelection)) {
this.store.setState({ selectedRowKeys });
}
if (!rowSelection.onChange && !rowSelection[selectWay]) {
return;
}
const data = this.getFlatData();
const selectedRows = data.filter(
(row, i) => selectedRowKeys.indexOf(this.getRecordKey(row, i)) >= 0
);
if (rowSelection.onChange) {
rowSelection.onChange(selectedRowKeys, selectedRows);
}
if (selectWay === 'onSelect' && rowSelection.onSelect) {
rowSelection.onSelect(record, checked, selectedRows);
} else if (selectWay === 'onSelectAll' && rowSelection.onSelectAll) {
const changeRows = data.filter(
(row, i) => changeRowKeys.indexOf(this.getRecordKey(row, i)) >= 0
);
rowSelection.onSelectAll(checked, selectedRows, changeRows);
} else if (selectWay === 'onSelectInvert' && rowSelection.onSelectInvert) {
rowSelection.onSelectInvert(selectedRowKeys);
}
};
hasPagination = props => (props || this.props).pagination !== false;
isFiltersChanged = filters => {
let filtersChanged = false;
if (Object.keys(filters).length !== Object.keys(this.state.filters).length) {
filtersChanged = true;
} else {
Object.keys(filters).forEach(columnKey => {
if (filters[columnKey] !== this.state.filters[columnKey]) {
filtersChanged = true;
}
});
}
return filtersChanged;
};
getSortOrderColumns = columns => flatFilter(columns || this.columns || [], column => 'sortOrder' in column);
getFilteredValueColumns = columns => (flatFilter(
columns || this.columns || [],
column => typeof column.filteredValue !== 'undefined'
));
getFiltersFromColumns = columns => {
let filters = {};
this.getFilteredValueColumns(columns).forEach(col => {
filters[this.getColumnKey(col)] = col.filteredValue;
});
return filters;
};
getSortStateFromColumns = columns => {
const sortedColumn = this.getSortOrderColumns(columns).filter(col => col.sortOrder)[0];
if (sortedColumn) {
return {
sortColumn: sortedColumn,
sortOrder: sortedColumn.sortOrder
};
}
return {
sortColumn: null,
sortOrder: null
};
};
getSorterFn = () => {
const { sortOrder, sortColumn } = this.state;
if (!sortOrder || !sortColumn || typeof sortColumn.sorter !== 'function') {
return;
}
return (a, b) => {
const result = sortColumn.sorter(a, b);
if (result !== 0) {
return (sortOrder === 'descend') ? -result : result;
}
return 0;
};
};
toggleSortOrder = (order, column) => {
let { sortColumn, sortOrder } = this.state;
// 只同时允许一列进行排序,否则会导致排序顺序的逻辑问题
let isSortColumn = this.isSortColumn(column);
if (!isSortColumn) { // 当前列未排序
sortOrder = order;
sortColumn = column;
} else { // 当前列已排序
if (sortOrder === order) { // 切换为未排序状态
sortOrder = '';
sortColumn = null;
} else { // 切换为排序状态
sortOrder = order;
}
}
const newState = {
sortOrder,
sortColumn
};
// Controlled
if (this.getSortOrderColumns().length === 0) {
this.setState(newState);
}
const onChange = this.props.onChange;
if (onChange) {
onChange.apply(null, this.prepareParamsArguments(Object.assign({}, this.state, newState)));
}
};
handleFilter = (column, nextFilters) => {
const props = this.props;
let pagination = Object.assign({}, this.state.pagination);
const filters = Object.assign({}, this.state.filters, {
[this.getColumnKey(column)]: nextFilters
});
// Remove filters not in current columns
const currentColumnKeys = [];
treeMap(this.columns, c => {
if (!c.children) {
currentColumnKeys.push(this.getColumnKey(c));
}
});
Object.keys(filters).forEach((columnKey) => {
if (currentColumnKeys.indexOf(columnKey) < 0) {
delete filters[columnKey];
}
});
if (props.pagination) {
// Reset current prop
pagination.current = 1;
pagination.onChange(pagination.current);
}
const newState = {
pagination,
filters: {}
};
const filtersToSetState = Object.assign({}, filters);
// Remove filters which is controlled
this.getFilteredValueColumns().forEach(col => {
const columnKey = this.getColumnKey(col);
if (columnKey) {
delete filtersToSetState[columnKey];
}
});
if (Object.keys(filtersToSetState).length > 0) {
newState.filters = filtersToSetState;
}
// Controlled current prop will not respond user interaction
if (typeof props.pagination === 'object' && 'current' in props.pagination) {
newState.pagination = Object.assign({}, pagination, {
current: this.state.pagination.current
});
}
this.setState(newState, () => {
this.store.setState({
selectionDirty: false
});
const onChange = this.props.onChange;
if (onChange) {
onChange.apply(null, this.prepareParamsArguments(Object.assign({}, this.state, {
selectionDirty: false,
filters,
pagination
})));
}
});
};
handleSelect = (record, rowIndex, e) => {
const checked = e.target.checked;
const defaultSelection = this.store.getState().selectionDirty ? [] : this.getDefaultSelection();
let selectedRowKeys = this.store.getState().selectedRowKeys.concat(defaultSelection);
let key = this.getRecordKey(record, rowIndex);
if (checked) {
selectedRowKeys.push(this.getRecordKey(record, rowIndex));
} else {
selectedRowKeys = selectedRowKeys.filter((i) => key !== i);
}
this.store.setState({
selectionDirty: true
});
this.setSelectedRowKeys(selectedRowKeys, {
selectWay: 'onSelect',
record,
checked
});
};
handleRadioSelect = (record, rowIndex, e) => {
const checked = e.target.checked;
const defaultSelection = this.store.getState().selectionDirty ? [] : this.getDefaultSelection();
let selectedRowKeys = this.store.getState().selectedRowKeys.concat(defaultSelection);
let key = this.getRecordKey(record, rowIndex);
selectedRowKeys = [key];
this.store.setState({
selectionDirty: true
});
this.setSelectedRowKeys(selectedRowKeys, {
selectWay: 'onSelect',
record,
checked
});
};
handleSelectRow = (selectionKey, index, onSelectFunc) => {
const data = this.getFlatCurrentPageData();
const defaultSelection = this.store.getState().selectionDirty ? [] : this.getDefaultSelection();
const selectedRowKeys = this.store.getState().selectedRowKeys.concat(defaultSelection);
const changeableRowKeys = data
.filter((item, i) => !this.getCheckboxPropsByItem(item, i).disabled)
.map((item, i) => this.getRecordKey(item, i));
let changeRowKeys = [];
let selectWay = '';
let checked;
switch (selectionKey) {
case 'all':
changeableRowKeys.forEach(key => {
if (selectedRowKeys.indexOf(key) < 0) {
selectedRowKeys.push(key);
changeRowKeys.push(key);
}
});
selectWay = 'onSelectAll';
checked = true;
break;
case 'removeAll':
changeableRowKeys.forEach(key => {
if (selectedRowKeys.indexOf(key) >= 0) {
selectedRowKeys.splice(selectedRowKeys.indexOf(key), 1);
changeRowKeys.push(key);
}
});
selectWay = 'onSelectAll';
checked = false;
break;
case 'invert':
changeableRowKeys.forEach(key => {
if (selectedRowKeys.indexOf(key) < 0) {
selectedRowKeys.push(key);
} else {
selectedRowKeys.splice(selectedRowKeys.indexOf(key), 1);
}
changeRowKeys.push(key);
selectWay = 'onSelectInvert';
});
break;
default:
break;
}
this.store.setState({
selectionDirty: true
});
// when select custom selection, callback selections[n].onSelect
if (index > 1 && typeof onSelectFunc === 'function') {
return onSelectFunc(changeableRowKeys);
}
this.setSelectedRowKeys(selectedRowKeys, {
selectWay: selectWay,
checked,
changeRowKeys
});
};
handlePageChange = (current, ...otherArguments) => {
const props = this.props;
let pagination = Object.assign({}, this.state.pagination);
if (current) {
pagination.current = current;
} else {
pagination.current = pagination.current || 1;
}
pagination.onChange(pagination.current, ...otherArguments);
const newState = {
pagination
};
if (props.pagination && typeof props.pagination === 'object' && 'current' in props.pagination) {
newState.pagination = Object.assign({}, pagination, {
current: this.state.pagination.current
});
}
this.setState(newState);
this.store.setState({
selectionDirty: false
});
const onChange = this.props.onChange;
if (onChange) {
onChange.apply(null, this.prepareParamsArguments(Object.assign({}, this.state, {
selectionDirty: false,
pagination
})));
}
};
renderSelectionBox = (type) => {
return (_, record, index) => {
let rowIndex = this.getRecordKey(record, index); // 从 1 开始
const props = this.getCheckboxPropsByItem(record, index);
const handleChange = (e) => {
type === 'radio' ? this.handleRadioSelect(record, rowIndex, e) : this.handleSelect(record, rowIndex, e);
};
return (
<span onClick={stopPropagation}>
<SelectionBox
type={type}
store={this.store}
rowIndex={rowIndex}
disabled={props.disabled}
onChange={handleChange}
defaultSelection={this.getDefaultSelection()}
/>
</span>
);
};
};
getRecordKey = (record, index) => {
const rowKey = this.props.rowKey;
const recordKey = (typeof rowKey === 'function') ? rowKey(record, index) : record[rowKey];
warning(
recordKey !== undefined,
'Each record in dataSource of table should have a unique `key` prop, or set `rowKey` to an unique primary key.'
);
return recordKey === undefined ? index : recordKey;
};
getPopupContainer = () => {
return findDOMNode(this);
};
renderRowSelection = () => {
const { prefixCls, rowSelection } = this.props;
const columns = this.columns.concat();
if (rowSelection) {
const data = this.getFlatCurrentPageData().filter((item, index) => {
if (rowSelection.getCheckboxProps) {
return !this.getCheckboxPropsByItem(item, index).disabled;
}
return true;
});
let selectionColumnClass = classNames(`${prefixCls}-selection-column`, {
[`${prefixCls}-selection-column-custom`]: rowSelection.selections
});
const selectionColumn = {
key: 'selection-column',
render: this.renderSelectionBox(rowSelection.type),
className: selectionColumnClass
};
if (rowSelection.type !== 'radio') {
const checkboxAllDisabled = data.every((item, index) => this.getCheckboxPropsByItem(item, index).disabled);
selectionColumn.title = (
<SelectionCheckboxAll
store={this.store}
locale={this.getLocale()}
data={data}
getCheckboxPropsByItem={this.getCheckboxPropsByItem}
getRecordKey={this.getRecordKey}
disabled={checkboxAllDisabled}
prefixCls={prefixCls}
onSelect={this.handleSelectRow}
selections={rowSelection.selections}
getPopupContainer={this.getPopupContainer}
/>
);
}
if (columns.some(column => column.fixed === 'left' || column.fixed === true)) {
selectionColumn.fixed = 'left';
}
if (columns[0] && columns[0].key === 'selection-column') {
columns[0] = selectionColumn;
} else {
columns.unshift(selectionColumn);
}
}
return columns;
};
getColumnKey = (column, index) => (column.key || column.dataIndex || index);
getMaxCurrent = total => {
const { current, pageSize } = this.state.pagination;
if ((current - 1) * pageSize >= total) {
return Math.floor((total - 1) / pageSize) + 1;
}
return current;
};
isSortColumn = column => {
const { sortColumn } = this.state;
if (!column || !sortColumn) {
return false;
}
return this.getColumnKey(sortColumn) === this.getColumnKey(column);
};
renderColumnsDropdown = columns => {
const { prefixCls, dropdownPrefixCls, bordered } = this.props;
const { sortOrder } = this.state;
const locale = this.getLocale();
return treeMap(columns, (originColumn, i) => {
let column = Object.assign({}, originColumn);
let key = this.getColumnKey(column, i);
let filterDropdown;
let sortButton;
if ((column.filters && column.filters.length > 0) || column.filterDropdown) {
let colFilters = this.state.filters[key] || [];
filterDropdown = (
<FilterDropdown
locale={locale}
column={column}
selectedKeys={colFilters}
confirmFilter={this.handleFilter}
prefixCls={`${prefixCls}-filter`}
dropdownPrefixCls={dropdownPrefixCls || 'td-dropdown'}
getPopupContainer={this.getPopupContainer}
/>
);
}
if (column.sorter) {
let isSortColumn = this.isSortColumn(column);
if (isSortColumn) {
column.className = column.className || '';
if (sortOrder) {
column.className += ` ${prefixCls}-column-sort`;
}
}
const isAscend = isSortColumn && sortOrder === 'ascend';
const isDescend = isSortColumn && sortOrder === 'descend';
sortButton = (
<div className={`${prefixCls}-column-sorter`}>
<span
className={`${prefixCls}-column-sorter-up ${isAscend ? 'on' : 'off'}`}
title="↑"
onClick={() => this.toggleSortOrder('ascend', column)}
>
<Icon type="triangle-up" />
</span>
<span
className={`${prefixCls}-column-sorter-down ${isDescend ? 'on' : 'off'}`}
title="↓"
onClick={() => this.toggleSortOrder('descend', column)}
>
<Icon type="triangle-down" />
</span>
</div>
);
}
column.title = (
<span>
{column.title}
{
(sortButton || filterDropdown) && (
<div style={{ display: 'inline-block', float: bordered ? 'right' : '' }}>
{sortButton}
{filterDropdown}
</div>
)
}
</span>
);
return column;
});
};
handleShowSizeChange = (current, pageSize) => {
const pagination = this.state.pagination;
pagination.onShowSizeChange(current, pageSize);
const nextPagination = Object.assign({}, pagination, { pageSize, current });
this.setState({ pagination: nextPagination });
const onChange = this.props.onChange;
if (onChange) {
onChange.apply(null, this.prepareParamsArguments(Object.assign({}, this.state, {
pagination: nextPagination
})));
}
}
renderPagination = () => {
// 强制不需要分页
if (!this.hasPagination()) {
return null;
}
let size = 'default';
const { pagination } = this.state;
if (pagination.size) {
size = pagination.size;
} else if (this.props.size === 'middle' || this.props.size === 'small') {
size = 'small';
}
let total = pagination.total || this.getLocalData().length;
return (total > 0) ? (
<Pagination
key="pagination"
{...pagination}
className={`${this.props.prefixCls}-pagination`}
onChange={this.handlePageChange}
total={total}
size={size}
current={this.getMaxCurrent(total)}
onShowSizeChange={this.handleShowSizeChange}
/>
) : null;
};
prepareParamsArguments = state => {
const pagination = { ...state.pagination };
// remove useless handle function in Table.onChange
delete pagination.onChange;
delete pagination.onShowSizeChange;
const filters = state.filters;
const sorter = {};
if (state.sortColumn && state.sortOrder) {
sorter.column = state.sortColumn;
sorter.order = state.sortOrder;
sorter.field = state.sortColumn.dataIndex;
sorter.columnKey = this.getColumnKey(state.sortColumn);
}
return [pagination, filters, sorter];
};
findColumn = myKey => {
let column;
treeMap(this.columns, c => {
if (this.getColumnKey(c) === myKey) {
column = c;
}
});
return column;
};
getCurrentPageData = () => {
let data = this.getLocalData();
let current;
let pageSize;
let state = this.state;
// 如果没有分页的话,默认全部展示
if (!this.hasPagination()) {
pageSize = Number.MAX_VALUE;
current = 1;
} else {
pageSize = state.pagination.pageSize;
current = this.getMaxCurrent(state.pagination.total || data.length);
}
// 分页
// ---
// 当数据量少于等于每页数量时,直接设置数据
// 否则进行读取分页数据
if (data.length > pageSize || pageSize === Number.MAX_VALUE) {
data = data.filter((_, i) => {
return i >= (current - 1) * pageSize && i < current * pageSize;
});
}
return data;
};
getFlatData = () => {
return flatArray(this.getLocalData());
};
getFlatCurrentPageData = () => {
return flatArray(this.getCurrentPageData());
};
recursiveSort = (data, sorterFn) => {
const { childrenColumnName = 'children' } = this.props;
return data.sort(sorterFn).map(item => (item[childrenColumnName] ? Object.assign(
{},
item, {
[childrenColumnName]: this.recursiveSort(item[childrenColumnName], sorterFn)
}
) : item));
};
getLocalData = () => {
const state = this.state;
const { dataSource } = this.props;
let data = dataSource || [];
// 优化本地排序
data = data.slice(0);
const sorterFn = this.getSorterFn();
if (sorterFn) {
data = this.recursiveSort(data, sorterFn);
}
// 筛选
if (state.filters) {
Object.keys(state.filters).forEach((columnKey) => {
let col = this.findColumn(columnKey);
if (!col) {
return;
}
let values = state.filters[columnKey] || [];
if (values.length === 0) {
return;
}
const onFilter = col.onFilter;
data = onFilter ? data.filter(record => {
return values.some(v => onFilter(v, record));
}) : data;
});
}
return data;
};
render() {
const { style, className, prefixCls, showHeader, ...restProps } = this.props;
const data = this.getCurrentPageData();
let columns = this.renderRowSelection();
const expandIconAsCell = this.props.expandedRowRender && this.props.expandIconAsCell !== false;
const locale = this.getLocale();
const classString = classNames({
[`${prefixCls}-${this.props.size}`]: true,
[`${prefixCls}-bordered`]: this.props.bordered,
[`${prefixCls}-noborder`]: this.props.noborder,
[`${prefixCls}-empty`]: !data.length,
[`${prefixCls}-without-column-header`]: !showHeader
});
columns = this.renderColumnsDropdown(columns);
columns = columns.map((column, i) => {
const newColumn = Object.assign({}, column);
newColumn.key = this.getColumnKey(newColumn, i);
return newColumn;
});
let expandIconColumnIndex = (columns[0] && columns[0].key === 'selection-column') ? 1 : 0;
if ('expandIconColumnIndex' in restProps) {
expandIconColumnIndex = restProps.expandIconColumnIndex;
}
const table = (
<BaseTable
key="table"
{...restProps}
prefixCls={prefixCls}
data={data}
columns={columns}
showHeader={showHeader}
className={classString}
expandIconColumnIndex={expandIconColumnIndex}
expandIconAsCell={expandIconAsCell}
emptyText={() => locale.emptyText}
/>
);
// if there is no pagination or no data,
// the height of loading should decrease by half of pagination
const paginationPatchClass = (this.hasPagination() && data && data.length !== 0)
? `${prefixCls}-with-pagination` : `${prefixCls}-without-pagination`;
let loading = this.props.loading;
return (
<div
className={classNames(`${prefixCls}-wrapper`, className)}
style={style}
>
<Loading
loading={loading}
className={loading ? `${paginationPatchClass} ${prefixCls}-spin-holder` : ''}
>
{table}
{this.renderPagination()}
</Loading>
</div>
);
}
}
|
import React from 'react';
import { Link } from 'react-router-dom';
import Main from '../layouts/Main';
import data from '../data/mooc';
const tableStyle = {
border: '1px solid black',
borderCollapse: 'collapse',
textAlign: 'center',
width: '100%'
}
const tdStyle = {
// border: '1px solid #85C1E9',
padding: '5px'
};
const thStyle = {
border: '1px solid #3498DB',
background: '#3498DB',
color: 'black',
padding: '5px',
'text-align':'center'
};
const students = [
{ "id": 177, "name": "Generative Adversarial Networks (GANs) Specialization by deeplearning.ai", "year": 2021, "platform": "Coursera", "href":"https://www.coursera.org/account/accomplishments/specialization/certificate/2W4NVMZQYKMV"},
];
const About = () => (
<Main
title="Certifications"
description="Learn more about Mooc"
>
<article className="post" id="mooc">
<header>
<div className="title">
<h2 data-testid="heading"><Link to="/mooc">Certifications & Courses</Link></h2>
</div>
</header>
<div>
<table style={tableStyle}>
<tbody>
<tr>
<th style={thStyle}>#</th>
<th style={thStyle}>Name</th>
<th style={thStyle}>Year</th>
<th style={thStyle}>Platform</th>
</tr>
{data.map(({ id, name, year, platform, href }) => (
<tr key={id}>
<td style={tdStyle}>{id}</td>
<td><a href={href} style={tdStyle}>{name}</a></td>
<td style={tdStyle}>{year}</td>
<td style={tdStyle}>{platform}</td>
</tr>
))}
</tbody>
</table>
</div>
</article>
</Main>
);
export default About;
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require jquery.mobile.custom.min
//= require waypoints/jquery.waypoints
//= require dataTables/jquery.dataTables
//= require dataTables/bootstrap/3/jquery.dataTables.bootstrap
//= require cocoon
//= require bootstrap
//= require Chart
//= require osem
//= require osem-dashboard
//= require ahoy
//= require jquery-smooth-scroll
//= require trianglify
//= require tinycolor
//= require bootstrap-markdown
//= require to-markdown
//= require markdown
//= require momentjs
//= require leaflet
//= require holderjs
//= require bootstrap-datetimepicker
//= require osem-datepickers
//= require osem-datatables
//= require osem-tickets
//= require bootstrap-switch
//= require osem-switch
//= require osem-bootstrap
//= require osem-commercials
//= require unobtrusive_flash
//= require unobtrusive_flash_bootstrap
$(document).ready(function() {
$('a[disabled=disabled]').click(function(event){
return false;
});
$('body').smoothScroll({
delegateSelector: 'a.smoothscroll'
});
});
|
'use strict';
//Setting up route
angular.module('accessrules').config(['$stateProvider',
function($stateProvider) {
// Accessrules state routing
$stateProvider.
state('listAccessrules', {
url: '/accessrules',
templateUrl: 'modules/accessrules/views/list-accessrules.client.view.html'
}).
state('createAccessrule', {
url: '/accessrules/create',
templateUrl: 'modules/accessrules/views/create-accessrule.client.view.html'
}).
state('viewAccessrule', {
url: '/accessrules/:accessruleId',
templateUrl: 'modules/accessrules/views/view-accessrule.client.view.html'
}).
state('editAccessrule', {
url: '/accessrules/:accessruleId/edit',
templateUrl: 'modules/accessrules/views/edit-accessrule.client.view.html'
});
}
]); |
"use strict";
var Resolver = require("enhanced-resolve/lib/Resolver");
var SyncNodeJsInputFileSystem = require("enhanced-resolve/lib/SyncNodeJsInputFileSystem");
var CachedInputFileSystem = require("enhanced-resolve/lib/CachedInputFileSystem");
var UnsafeCachePlugin = require("enhanced-resolve/lib/UnsafeCachePlugin");
var ModulesInDirectoriesPlugin = require("enhanced-resolve/lib/ModulesInDirectoriesPlugin");
var ModulesInRootPlugin = require("enhanced-resolve/lib/ModulesInRootPlugin");
var ModuleAsFilePlugin = require("enhanced-resolve/lib/ModuleAsFilePlugin");
var ModuleAsDirectoryPlugin = require("enhanced-resolve/lib/ModuleAsDirectoryPlugin");
var ModuleAliasPlugin = require("enhanced-resolve/lib/ModuleAliasPlugin");
var DirectoryDefaultFilePlugin = require("enhanced-resolve/lib/DirectoryDefaultFilePlugin");
var DirectoryDescriptionFilePlugin = require("enhanced-resolve/lib/DirectoryDescriptionFilePlugin");
var DirectoryDescriptionFileFieldAliasPlugin = require("enhanced-resolve/lib/DirectoryDescriptionFileFieldAliasPlugin");
var FileAppendPlugin = require("enhanced-resolve/lib/FileAppendPlugin");
var ResultSymlinkPlugin = require("enhanced-resolve/lib/ResultSymlinkPlugin");
function makeRootPlugin(name, root) {
if (typeof root === "string") {
return new ModulesInRootPlugin(name, root);
} else if (Array.isArray(root)) {
return function () {
root.forEach(function (root) {
this.apply(new ModulesInRootPlugin(name, root));
}, this);
};
}
return function () {};
}
function makeResolver(options) {
var fileSystem = new CachedInputFileSystem(new SyncNodeJsInputFileSystem(), 60000);
var resolver = new Resolver(fileSystem);
resolver.apply(new UnsafeCachePlugin(options.resolve.unsafeCache), options.resolve.packageAlias ? new DirectoryDescriptionFileFieldAliasPlugin("package.json", options.resolve.packageAlias) : function () {}, new ModuleAliasPlugin(options.resolve.alias), makeRootPlugin("module", options.resolve.root), new ModulesInDirectoriesPlugin("module", options.resolve.modulesDirectories), makeRootPlugin("module", options.resolve.fallback), new ModuleAsFilePlugin("module"), new ModuleAsDirectoryPlugin("module"), new DirectoryDescriptionFilePlugin("package.json", options.resolve.packageMains), new DirectoryDefaultFilePlugin(["index"]), new FileAppendPlugin(options.resolve.extensions), new ResultSymlinkPlugin());
return resolver;
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = makeResolver;
//# sourceMappingURL=resolver.js.map |
import Vue from 'vue';
import iView from 'iview';
import VueRouter from 'vue-router';
import {routers, otherRouter, appRouter} from './router';
import Vuex from 'vuex';
import Util from './libs/util';
import App from './app.vue';
import Cookies from 'js-cookie';
import 'iview/dist/styles/iview.css';
import VueI18n from 'vue-i18n';
import Locales from './locale';
import zhLocale from 'iview/src/locale/lang/zh-CN';
import enLocale from 'iview/src/locale/lang/en-US';
Vue.use(VueRouter);
Vue.use(Vuex);
Vue.use(VueI18n);
Vue.use(iView);
// 自动设置语言
const navLang = navigator.language;
const localLang = (navLang === 'zh-CN' || navLang === 'en-US') ? navLang : false;
const lang = window.localStorage.getItem('language') || localLang || 'zh-CN';
Vue.config.lang = lang;
// 多语言配置
const locales = Locales;
const mergeZH = Object.assign(zhLocale, locales['zh-CN']);
const mergeEN = Object.assign(enLocale, locales['en-US']);
Vue.locale('zh-CN', mergeZH);
Vue.locale('en-US', mergeEN);
// 路由配置
const RouterConfig = {
// mode: 'history',
routes: routers
};
const router = new VueRouter(RouterConfig);
router.beforeEach((to, from, next) => {
iView.LoadingBar.start();
Util.title(to.meta.title);
if (Cookies.get('locking') === '1' && to.name !== 'locking') { // 判断当前是否是锁定状态
next(false);
router.replace({
name: 'locking'
});
} else if (Cookies.get('locking') === '0' && to.name === 'locking') {
next(false);
} else {
if (!Cookies.get('user') && to.name !== 'login') { // 判断是否已经登录且前往的页面不是登录页
next({
name: 'login'
});
} else if (Cookies.get('user') && to.name === 'login') { // 判断是否已经登录且前往的是登录页
Util.title();
next({
name: 'home_index'
});
} else {
if (Util.getRouterObjByName([otherRouter, ...appRouter], to.name).access !== undefined) { // 判断用户是否有权限访问当前页
if (Util.getRouterObjByName([otherRouter, ...appRouter], to.name).access === parseInt(Cookies.get('access'))) {
next();
} else {
router.replace({
name: 'error_401'
});
next();
}
} else {
next();
}
}
}
iView.LoadingBar.finish();
});
router.afterEach(() => {
iView.LoadingBar.finish();
window.scrollTo(0, 0);
});
// 状态管理
const store = new Vuex.Store({
state: {
routers: [
otherRouter,
...appRouter
],
menuList: [],
tagsList: [...otherRouter.children],
pageOpenedList: [],
currentPageName: '',
currentPath: [
{
title: '首页',
path: '',
name: 'home_index'
}
], // 面包屑数组
openedSubmenuArr: [], // 要展开的菜单数组
menuTheme: '', // 主题
theme: '',
cachePage: []
},
getters: {
},
mutations: {
setTagsList (state, list) {
state.tagsList.push(...list);
},
closePage (state, name) {
state.cachePage.forEach((item, index) => {
if (item === name) {
state.cachePage.splice(index, 1);
}
});
},
increateTag (state, tagObj) {
state.cachePage.push(tagObj.name);
state.pageOpenedList.push(tagObj);
},
initCachepage (state) {
if (localStorage.pageOpenedList) {
state.cachePage = JSON.parse(localStorage.pageOpenedList).map(item => {
if (item.name !== 'home_index') {
return item.name;
}
});
}
},
removeTag (state, name) {
state.pageOpenedList.map((item, index) => {
if (item.name === name) {
state.pageOpenedList.splice(index, 1);
}
});
},
pageOpenedList (state, get) {
let openedPage = state.pageOpenedList[get.index];
if (get.argu) {
openedPage.argu = get.argu;
}
state.pageOpenedList.splice(get.index, 1, openedPage);
localStorage.pageOpenedList = JSON.stringify(state.pageOpenedList);
},
clearAllTags (state) {
state.pageOpenedList.splice(1);
router.push({
name: 'home_index'
});
state.cachePage = [];
localStorage.pageOpenedList = JSON.stringify(state.pageOpenedList);
},
clearOtherTags (state, vm) {
let currentName = vm.$route.name;
let currentIndex = 0;
state.pageOpenedList.forEach((item, index) => {
if (item.name === currentName) {
currentIndex = index;
}
});
if (currentIndex === 0) {
state.pageOpenedList.splice(1);
} else {
state.pageOpenedList.splice(currentIndex + 1);
state.pageOpenedList.splice(1, currentIndex - 1);
}
let newCachepage = state.cachePage.filter(item => {
return item === currentName;
});
state.cachePage = newCachepage;
localStorage.pageOpenedList = JSON.stringify(state.pageOpenedList);
},
setOpenedList (state) {
state.pageOpenedList = localStorage.pageOpenedList ? JSON.parse(localStorage.pageOpenedList) : [otherRouter.children[0]];
},
setCurrentPath (state, pathArr) {
state.currentPath = pathArr;
},
setCurrentPageName (state, name) {
state.currentPageName = name;
},
addOpenSubmenu (state, name) {
let hasThisName = false;
let isEmpty = false;
if (name.length === 0) {
isEmpty = true;
}
if (state.openedSubmenuArr.indexOf(name) > -1) {
hasThisName = true;
}
if (!hasThisName && !isEmpty) {
state.openedSubmenuArr.push(name);
}
},
clearOpenedSubmenu (state) {
state.openedSubmenuArr.length = 0;
},
changeMenuTheme (state, theme) {
state.menuTheme = theme;
},
changeMainTheme (state, mainTheme) {
state.theme = mainTheme;
},
lock (state) {
Cookies.set('locking', '1');
},
unlock (state) {
Cookies.set('locking', '0');
},
setMenuList (state, menulist) {
state.menuList = menulist;
},
updateMenulist (state) {
let accessCode = parseInt(Cookies.get('access'));
let menuList = [];
appRouter.forEach((item, index) => {
if (item.access !== undefined) {
if (Util.showThisRoute(item.access, accessCode)) {
if (item.children.length === 1) {
menuList.push(item);
} else {
let len = menuList.push(item);
let childrenArr = [];
childrenArr = item.children.filter(child => {
if (child.access !== undefined) {
if (child.access === accessCode) {
return child;
}
} else {
return child;
}
});
menuList[len - 1].children = childrenArr;
}
}
} else {
if (item.children.length === 1) {
menuList.push(item);
} else {
let len = menuList.push(item);
let childrenArr = [];
childrenArr = item.children.filter(child => {
if (child.access !== undefined) {
if (Util.showThisRoute(child.access, accessCode)) {
return child;
}
} else {
return child;
}
});
let handledItem = JSON.parse(JSON.stringify(menuList[len - 1]));
handledItem.children = childrenArr;
menuList.splice(len - 1, 1, handledItem);
}
}
});
state.menuList = menuList;
},
setAvator (state, path) {
localStorage.avatorImgPath = path;
}
},
actions: {
}
});
new Vue({
el: '#app',
router: router,
store: store,
render: h => h(App),
data: {
currentPageName: ''
},
mounted () {
this.currentPageName = this.$route.name;
this.$store.commit('initCachepage');
// 权限菜单过滤相关
this.$store.commit('updateMenulist');
},
created () {
let tagsList = [];
appRouter.map((item) => {
if (item.children.length <= 1) {
tagsList.push(item.children[0]);
} else {
tagsList.push(...item.children);
}
});
this.$store.commit('setTagsList', tagsList);
},
watch: {
'$route' (to) {
// if (Util.getRouterObjByName(this, to.name).access) {
// if (Util.getRouterObjByName(this, to.name).access === parseInt(Cookies.get('access'))) {
// }
// }
}
}
});
|
import Route from 'route-parser';
import { formatRoutes } from './formatRoutes';
export const matchRoute = (routeConfig, pathname) => {
const formattedRoutes = formatRoutes(routeConfig.routes);
const foundRoute = formattedRoutes.find(({ route }) => route.match(pathname));
return foundRoute
? { ...foundRoute, params: foundRoute.route.match(pathname) }
: { component: routeConfig.miss, params: {}, isMiss: true };
};
export const matchSingleRoute = (route, pathname) => {
const routeMatcher = new Route(route);
const matched = routeMatcher.match(pathname);
return matched ? { params: matched } : false;
};
|
//define(function(require) {
// 'use strict';
//
// var FormEntities = require('entities/forms');
// //var FormEntity = require('entities/form');
// var forms = new FormEntities();
//
// var FormEntitiesFixtures = {
// GET: {
// forms: [
// {
// templateId: 3,
// title: 'Personal Info',
// isComplete: false,
// totalQuestions: 10,
// totalCompletedQuestions: 3,
// formSchema: {
// title: {
// type: 'Select',
// options: ['', 'Mr', 'Mrs', 'Ms']
// },
// name: 'Text',
// email: {
// validators: ['required', 'email']
// }
// },
//
// fieldsets: [{
// legend: 'Member Information',
// fields: ['title', 'name', 'email', 'testHidden']
// }],
//
// data: {
// title: 'Mr',
// name: 'Bob Marley',
// email: 'b.marley@test.com'
// }
// }
// ]
// }
// };
//
// // Test that the Router exists.
// describe('Form Entities Collection', function() {
//
// it('should exist', function(){
// expect(FormEntities).toBeDefined();
// expect(FormEntities.prototype instanceof Backbone.Collection).toBe(true);
// });
//
// it('should have a url mapped to it', function(){
// expect(forms.url).toBeDefined();
// });
//
// it('calls url function', function() {
// spyOn(forms, 'url');
// forms.url();
// expect(forms.url).toHaveBeenCalled();
// });
//
// it('url function return string value', function() {
// expect(forms.url()).toEqual(jasmine.any(String));
// });
//
// it('should have a model', function(){
// expect(forms.model).toBe(FormEntity);
// });
//
// it('should be able to process a successful response from the server', function(){
// // set up the fake server
// var fakeServer = sinon.fakeServer.create();
// fakeServer.respondWith('GET',
// '/forms',
// [ 200,
// { 'Content-type': 'application/json' },
// JSON.stringify(FormEntitiesFixtures.GET.forms)
// ]);
//
// var forms = new FormEntities();
// forms.url = '/forms';
// forms.fetch();
// fakeServer.respond();
// expect(forms.length).toBe(1);
//
// // tear down the fake server
// fakeServer.restore();
// });
// });
//});
|
import { hyphen } from './utils';
/**
* 依赖
*/
export let devDependencies = [];
/**
* 添加依赖
* @param {array|string} dependencies 依赖
*/
export function addDependency(dependencies){
if ( !Array.isArray(dependencies) ){
dependencies = [dependencies];
};
dependencies.map(dependency => {
if ( devDependencies.indexOf(dependency) === -1 ){
devDependencies.push(dependency);
};
});
};
/**
* 移除依赖
* @param {array|string} dependencies 依赖
*/
export function removeDependency(dependencies){
if ( !Array.isArray(dependencies) ){
dependencies = [dependencies];
};
dependencies.map(dependency => {
devDependencies = devDependencies.filter(depend => depend !== dependency);
});
};
export function transformDependencyName(name){
name = name.replace(/_(?=[\d])/g, () => '-')
.replace(/_(?=[^\d])/g, () => '');
return hyphen(name);
}; |
import React from 'react'
import {Modal, Form, Input, notification, DatePicker} from 'antd'
import {connect} from 'dva'
import styles from './index.less'
import moment from 'moment'
import {routerRedux} from 'dva/router'
const FormItem = Form.Item;
const {RangePicker} = DatePicker;
class OrderModalForm extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: false,
}
}
showModal = () => {
if (!this.props.canOrder) {
notification.error({
message: "选好车空空如也",
description: "请选择点账号再来下单吧"
})
return;
}
this.setState({
visible: true
})
}
setOrderOk = () => {
this.props.form.validateFields((err, values) => {
if (!err) {
this.props.dispatch({
type: 'cart/createOrder',
payload: {
remark: values.remark,
name: values.orderName,
beginTime: moment(values.time[0]._d).format('YYYY-MM-DD'),
endTime: moment(values.time[1]._d).format('YYYY-MM-DD'),
}
})
this.setOrderCancel();
}
})
}
setOrderCancel = () => {
this.setState({
visible: false
})
}
disabledDate = (current) => {
return current && current.valueOf() + 86400000 < Date.now();
}
render() {
const {
props: {
dispatch,
loading,
isSuccess,
}
} = this
const {getFieldDecorator} = this.props.form;
return (
<div>
<span onClick={this.showModal}>
{this.props.children.props.children}
</span>
<Modal
//visible={visibleOrder}
//onOk={setOrderOk}
//onCancel={setOrderCancel}
visible={this.state.visible}
onOk={this.setOrderOk}
onCancel={this.setOrderCancel}
closable={false}
className={styles.orderModal}
okText="确认下单"
>
<Form>
<FormItem onSubmit={this.setOrderOk}>
<h3>订单名称</h3>
{
getFieldDecorator(
'orderName', {
rules: [{required: true, message: '请输入订单名称!'}]
}
)(
<Input placeholder="订单名称" className={styles.orderName}/>
)
}
</FormItem>
<FormItem>
<h3>投放时间</h3>
{
getFieldDecorator(
'time', {
rules: [{required: true, message: "请输入起止时间!"}]
}
)(
<RangePicker
format="YYYY-MM-DD"
disabledDate={this.disabledDate}
style={{width:"85%"}}
/>
)
}
<p style={{color:"#ccc"}}>依次选择开始时间、结束时间</p>
</FormItem>
<FormItem>
<h3>订单备注(选填)</h3>
{
getFieldDecorator('remark')(
<Input placeholder="请输入备注内容" className={styles.orderName}/>
)
}
</FormItem>
</Form>
<p className={styles.pText}>提醒:下单后投放不会立即生效,会有媒介人员与您联系沟通具体事宜。紧急投放建议<a href="#"
className={styles.aLink}>直接联系媒介</a>。
</p>
</Modal>
</div>
)
}
}
function mapStateToProps(state) {
const {
cart: {
isSuccess
},
} = state;
return {
loading: state.loading.effects,
isSuccess: state.cart.isSuccess,
}
}
export default connect(mapStateToProps)(Form.create()(OrderModalForm));
|
([])=>1;
|
/**
* remotelog.js
* Copyright (c) 2012 Christian Lobach <Christian.Lobach@gmail.com>
* MIT licensed
*/
var util = require('util');
var remotelog = {
_options: {
port: 1807,
replaceFunctions: true
},
// keep existing functionality
_oldlog: console.log,
_oldinfo: console.info,
_oldwarn: console.warn,
_olderror: console.error,
// remote logging functions
log: function() {
var d = new Date();
var t = d.getTime();
var clients = remotelog.io.sockets.clients();
for(var i = 0; i < clients.length; i++) {
clients[i].emit('log', {
type: 'log',
timestamp: t,
message: util.format.apply(this, arguments)
});
}
},
info: function() {
var d = new Date();
var t = d.getTime();
var clients = remotelog.io.sockets.clients();
for(var i = 0; i < clients.length; i++) {
clients[i].emit('info', {
type: 'info',
timestamp: t,
message: util.format.apply(this, arguments)
});
}
},
warn: function() {
var d = new Date();
var t = d.getTime();
var clients = remotelog.io.sockets.clients();
for(var i = 0; i < clients.length; i++) {
clients[i].emit('warn', {
type: 'warn',
timestamp: t,
message: util.format.apply(this, arguments)
});
}
},
error: function() {
var d = new Date();
var t = d.getTime();
var clients = remotelog.io.sockets.clients();
for(var i = 0; i < clients.length; i++) {
clients[i].emit('error', {
type: 'error',
timestamp: t,
message: util.format.apply(this, arguments)
});
}
},
// define console.log with new remote logging functionality
// and keep old behaviour
replaceOriginalFunctions: function() {
console.log = function() {
remotelog._oldlog.apply(this, arguments);
remotelog.log.apply(this, arguments);
};
console.info = function() {
remotelog._oldinfo.apply(this, arguments);
remotelog.info.apply(this, arguments);
};
console.warn = function() {
remotelog._oldwarn.apply(this, arguments);
remotelog.warn.apply(this, arguments);
};
console.error = function() {
remotelog._olderror.apply(this, arguments);
remotelog.error.apply(this, arguments);
};
},
createServer: function(options) {
if(options) {
if(typeof options.port !== 'undefined') {
remotelog._options.port = options.port;
}
if(typeof options.replaceFunctions !== 'undefined') {
remotelog._options.replaceFunctions = options.replaceFunctions;
}
}
remotelog.io = require('socket.io').listen(remotelog._options.port);
remotelog.io.set('log level', 0);
remotelog._oldlog("remotelog started");
remotelog.io.sockets.on('connection', function(socket) {
socket.emit('status', {
status: 'connected'
});
if(remotelog._options.replaceFunctions) {
remotelog.replaceOriginalFunctions();
}
});
}
};
module.exports = {
log: remotelog.log,
info: remotelog.info,
warn: remotelog.warn,
error: remotelog.error,
createServer: remotelog.createServer
} |
const rules = require( "../a11y" );
describe( "a11y", function() {
describe( "Extends", function() {
it( "should extend a11y rules", function() {
rules.extends.should.contain( "./rules/a11y.js" );
} );
} );
} );
|
// Synchronous highlighting with highlight.js
marked.setOptions({
highlight: function (code) {
return hljs.highlightAuto(code).value;
}
});
angular.module('plain', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
redirectTo: '/index'
})
.when('/:wikiId*', {
templateUrl: 'partials/page.html',
controller: 'PageCtrl'
});
}])
.controller('PageCtrl', ['$scope', '$routeParams', '$http', '$sce',
function ($scope, $routeParams, $http, $sce) {
console.log($routeParams.wikiId);
$http.get('wiki/' + $routeParams.wikiId + '.md')
.success(function (data) {
$scope.content = $sce.trustAsHtml(marked(data));
})
.error(function (data, status) {
$scope.content = $sce.trustAsHtml(data);
});
}]);
|
$('.message a').click(function(){
$('form').animate({height: "toggle", opacity: "toggle"}, "slow");
});
var name = document.getElementById('name1');
var pw = document.getElementById('pw');
function store() {
localStorage.setItem('name1', name.value);
localStorage.setItem('pw', pw.value);
}
function check() {
// stored data from the register-form
var storedName = localStorage.getItem('name1');
var storedPw = localStorage.getItem('pw');
// entered data from the login-form
var userName = document.getElementById('userName');
var userPw = document.getElementById('userPw');
// check if stored data from register-form is equal to data from login form
if(userName.value == storedName && userPw.value == storedPw) {
alert('You are loged in.');
}else {
alert('ERROR.');
}
}
var accounts = [];
var profile = [];
function finding(){
indexof(0) = username;
}
function login(){
var username = document.getElementById("usern").value;
var passwo = document.getElementById("passw").value;
while (username != accounts(profile[0])){
accounts.forEach(finding);
var found = username;
}
if (password != (profile[username,1])){
alert("YES");
}else{
alert("NO");
}
}
function create(){
profile["UserName"] = "username";
profile["PassWord"] = "passwo";
profile["email"] = "email";
document.getElementById("username").value;
document.getElementById("passwo").value;
document.getElementById("email").value;
profile.push("username");
profile.push("passwo");
profile.push("email");
accounts.push('profile')
window.location.href = "index.html";
}
|
import ko from 'knockout';
import template from 'text!./sl-date-picker.html';
import moment from 'moment';
import 'bootstrap-daterangepicker';
ko.bindingHandlers.SLDatePickerHandler = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var elem$ = this.myElem = $(element);
var span$ = elem$.find('span:first');
span$.html(moment.utc(viewModel.myDate()).format("MMM Do YY, h:mm"));
if (!viewModel.isViewMode()) {
elem$.daterangepicker({
format: 'MM/DD/YYYY',
startDate: moment(),
endDate: moment().add(365, 'days'),
singleDatePicker: true,
showDropdowns: true,
showWeekNumbers: true,
timePicker: false,
timePickerIncrement: 1,
timePicker12Hour: true,
opens: 'right',
drops: 'up',
buttonClasses: ['btn', 'btn-sm'],
applyClass: 'btn-primary',
cancelClass: 'btn-default',
separator: ' to ',
locale: {
applyLabel: 'Submit',
cancelLabel: 'Cancel',
fromLabel: 'From',
toLabel: 'To',
customRangeLabel: 'Custom',
daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
firstDay: 1
}
}, function (start, end, label) {
//console.log(start.toISOString(), end.toISOString(), label);
viewModel.myDate(start);
span$.html(moment.utc(viewModel.myDate()).format("MMM Do YY, h:mm"));
});
}
}
}
class SLDatePicker {
constructor(params) {
// params
this.isViewMode = params.isViewMode;
this.myDate = params.date;
this.myElem = undefined;
}
}
// This runs when the component is torn down. Put here any logic necessary to clean up,
// for example cancelling setTimeouts or disposing Knockout subscriptions/computeds.
SLDatePicker.prototype.dispose = function() { };
export default { viewModel: SLDatePicker, template: template };
|
/**
@module ember
@submodule ember-runtime
*/
import Ember from "ember-metal/core"; // Ember.assert
import {get} from "ember-metal/property_get";
import {set} from "ember-metal/property_set";
import {meta} from "ember-metal/utils";
import {addObserver, removeObserver, addBeforeObserver, removeBeforeObserver} from "ember-metal/observer";
import {propertyWillChange, propertyDidChange} from "ember-metal/property_events";
import {computed} from "ember-metal/computed";
import {defineProperty} from "ember-metal/properties";
import {observer} from "ember-metal/mixin";
import EmberStringUtils from "ember-runtime/system/string";
import EmberObject from "ember-runtime/system/object";
function contentPropertyWillChange(content, contentKey) {
var key = contentKey.slice(8); // remove "content."
if (key in this) { return; } // if shadowed in proxy
propertyWillChange(this, key);
}
function contentPropertyDidChange(content, contentKey) {
var key = contentKey.slice(8); // remove "content."
if (key in this) { return; } // if shadowed in proxy
propertyDidChange(this, key);
}
/**
`Ember.ObjectProxy` forwards all properties not defined by the proxy itself
to a proxied `content` object.
```javascript
object = Ember.Object.create({
name: 'Foo'
});
proxy = Ember.ObjectProxy.create({
content: object
});
// Access and change existing properties
proxy.get('name') // 'Foo'
proxy.set('name', 'Bar');
object.get('name') // 'Bar'
// Create new 'description' property on `object`
proxy.set('description', 'Foo is a whizboo baz');
object.get('description') // 'Foo is a whizboo baz'
```
While `content` is unset, setting a property to be delegated will throw an
Error.
```javascript
proxy = Ember.ObjectProxy.create({
content: null,
flag: null
});
proxy.set('flag', true);
proxy.get('flag'); // true
proxy.get('foo'); // undefined
proxy.set('foo', 'data'); // throws Error
```
Delegated properties can be bound to and will change when content is updated.
Computed properties on the proxy itself can depend on delegated properties.
```javascript
ProxyWithComputedProperty = Ember.ObjectProxy.extend({
fullName: function () {
var firstName = this.get('firstName'),
lastName = this.get('lastName');
if (firstName && lastName) {
return firstName + ' ' + lastName;
}
return firstName || lastName;
}.property('firstName', 'lastName')
});
proxy = ProxyWithComputedProperty.create();
proxy.get('fullName'); // undefined
proxy.set('content', {
firstName: 'Tom', lastName: 'Dale'
}); // triggers property change for fullName on proxy
proxy.get('fullName'); // 'Tom Dale'
```
@class ObjectProxy
@namespace Ember
@extends Ember.Object
*/
var ObjectProxy = EmberObject.extend({
/**
The object whose properties will be forwarded.
@property content
@type Ember.Object
@default null
*/
content: null,
_contentDidChange: observer('content', function() {
Ember.assert("Can't set ObjectProxy's content to itself", get(this, 'content') !== this);
}),
isTruthy: computed.bool('content'),
_debugContainerKey: null,
willWatchProperty: function (key) {
var contentKey = 'content.' + key;
addBeforeObserver(this, contentKey, null, contentPropertyWillChange);
addObserver(this, contentKey, null, contentPropertyDidChange);
},
didUnwatchProperty: function (key) {
var contentKey = 'content.' + key;
removeBeforeObserver(this, contentKey, null, contentPropertyWillChange);
removeObserver(this, contentKey, null, contentPropertyDidChange);
},
unknownProperty: function (key) {
var content = get(this, 'content');
if (content) {
return get(content, key);
}
},
setUnknownProperty: function (key, value) {
var m = meta(this);
if (m.proto === this) {
// if marked as prototype then just defineProperty
// rather than delegate
defineProperty(this, key, null, value);
return value;
}
var content = get(this, 'content');
Ember.assert(EmberStringUtils.fmt("Cannot delegate set('%@', %@) to the 'content' property of object proxy %@: its 'content' is undefined.", [key, value, this]), content);
return set(content, key, value);
}
});
export default ObjectProxy;
|
module.exports = (function(App,Connection,Package,privateMethods){
return function(){
App.frontPageLayout = require(App.Config.baseDir + App.Config.view.frontPageLayout);
}
}); |
/**
* This `decodeTx` decodes a bitcoin transaction. Its an example of how to use the composable helpers
* to make a decoder.
*/
const bitcoin = require('bitcoinjs-lib')
const bcrypto = bitcoin.crypto
const sha3_256 = require('js-sha3').sha3_256 // eslint-disable-line
const { compose, addProp } = require('./compose-read')
const {
readSlice,
readUInt32,
readInt32,
readUInt64,
readVarInt,
readVarSlice
} = require('./buffer-read')
/**
* Transaction's hash is a 256-bit integer, so we need to reverse bytes due to Little Endian byte order.
*/
// readHash :: Buffer -> [Hash, Buffer]
const readHash = buffer => {
const [res, bufferLeft] = readSlice(32)(buffer)
// Note: `buffer.reverse()` mutates the buffer, so make a copy:
const hash = Buffer.from(res).reverse().toString('hex')
return [hash, bufferLeft]
}
// readSig :: Buffer -> [ScriptSig, Buffer]
const readSig = buffer => {
const [ res, bufferLeft ] = readVarSlice(buffer)
const [ asmPart, asmBufferLeft ] = readVarSlice(res)
const asm = [ asmPart.toString('hex') ]
const hashType = asmPart.readUInt8(asmPart.length - 1) & ~0x80
if (hashType <= 0 || hashType >= 4) throw new Error('Invalid hashType ' + hashType)
const [ asmPart2 ] = readVarSlice(asmBufferLeft)
asm.push(asmPart2.toString('hex'))
return [{ asm: asm.join(' '), hex: res.toString('hex') }, bufferLeft]
}
// readInputs :: Fn -> Buffer -> (Res, Buffer)
const readInputs = readFn => buffer => {
const vins = []
let [vinLen, bufferLeft] = readVarInt(buffer)
let vin
for (let i = 0; i < vinLen; ++i) {
[vin, bufferLeft] = readFn(bufferLeft)
vins.push(vin)
}
return [vins, bufferLeft]
}
// readScript :: Buffer -> [ScriptPubKey, Buffer]
const readScript = buffer => {
const [ scriptBuffer, bufferLeft ] = readVarSlice(buffer)
return [ {
hex: scriptBuffer.toString('hex'),
type: scriptBuffer[0] === bitcoin.opcodes.OP_DUP && scriptBuffer[1] === bitcoin.opcodes.OP_HASH160 ? 'pubkeyhash' : 'nonstandard',
asm: bitcoin.script.toASM(scriptBuffer),
addresses: [ bitcoin.address.fromOutputScript(scriptBuffer) ]
}, bufferLeft ]
}
// decodeTx :: Buffer -> [Object, Buffer]
const decodeTx = buffer =>
(
compose([
addProp('version', readInt32), // 4 bytes
addProp('vin', readInputs(readInput)), // 1-9 bytes (VarInt), Input counter; Variable, Inputs
addProp('vout', readInputs(readOutput)), // 1-9 bytes (VarInt), Output counter; Variable, Outputs
addProp('locktime', readUInt32) // 4 bytes
])({}, buffer)
)
// readInput :: Buffer -> [Res, Buffer]
const readInput = buffer =>
(
compose([
addProp('txid', readHash), // 32 bytes, Transaction Hash
addProp('vout', readUInt32), // 4 bytes, Output Index
addProp('scriptSig', readSig), // 1-9 bytes (VarInt), Unlocking-Script Size; Variable, Unlocking-Script
addProp('sequence', readUInt32) // 4 bytes, Sequence Number
])({}, buffer)
)
// readOutput :: Buffer -> [Res, Buffer]
const readOutput = buffer =>
(
compose([
addProp('value', readUInt64), // 8 bytes, Amount in satoshis
addProp('scriptPubKey', readScript) // 1-9 bytes (VarInt), Locking-Script Size; Variable, Locking-Script
])({}, buffer)
)
// Single SHA3-256.
// hashSha3 :: Buffer -> Buffer
const hashSha3 = buffer => {
// Note: sha3_256 can accept either Buffer or String, and always outputs String.
const hashString = sha3_256(buffer)
return Buffer.from(hashString, 'hex')
}
// createHash :: Object -> Buffer -> Buffer
const createHash = options => data => {
let hashFn = bcrypto.hash256
if (options && options.sha === 'SHA3_256') {
hashFn = hashSha3
}
return hashFn(data)
}
// Since a hash is a 256-bit integer and is stored using Little Endian, we reverse it for showing to user (who reads BE).
// getTxId :: Buffer -> String
const getTxId = options => buffer => {
return createHash(options)(buffer).reverse().toString('hex')
}
module.exports = {
decodeTx,
readHash,
readInputs,
readInput,
readOutput,
createHash,
getTxId,
hashSha3
}
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import {GraphQLID, GraphQLList, GraphQLNonNull as NonNull,} from 'graphql';
import Runner from '../models/Runner';
import SuccessType from '../types/SuccessType';
const addRunnersToTeam = {
type: SuccessType,
args: {
team_id: { type: new NonNull(GraphQLID) },
runner_ids: { type: new GraphQLList(new NonNull(GraphQLID)) },
},
resolve(root, { team_id, runner_ids }) {
return Runner.update(
{ team_id },
{ where: { id: runner_ids } },
).then((affectedCount, affectedRows) => ({
success: true,
message: 'Runners updated',
}));
},
};
export default addRunnersToTeam;
|
define(function(require) {
'use strict';
var Promise = require('./Promise');
var forEachSeries = require('./forEachSeries');
/**
* Version of find which is guaranteed to process items in order
* @param {Array} list
* @param {Function} iterator
* @return {Promise<Any>}
*/
var findSeries = function(list, iterator) {
var found;
return forEachSeries(list, function(item, i) {
return Promise.fromAny(iterator(item, i, list))
.then(function(result) {
if (result) {
found = item;
throw 'break';
}
});
}).then(
function() {
return found;
},
function(err) {
if (err === 'break') {
return found;
}
throw err;
}
);
};
return findSeries;
});
|
var conn = require('../config/db').conn;
module.exports = {
getAllProdPorCliente: getAllProdPorCliente,
getAll: getAll,
getUltimo: getUltimo,
insertProd: insertProd,
getProdPorCodigoParaCadaCliente: getProdPorCodigoParaCadaCliente,
getProdPorNombreParaCadaCliente: getProdPorNombreParaCadaCliente,
getcdClientePorIdProducto: getcdClientePorIdProducto,
getProdPorId: getProdPorId,
updateProd: updateProd,
delProd: delProd,
getAllActivosPorCliente:getAllActivosPorCliente,
getAbLotePorIDProd:getAbLotePorIDProd,
verificacionCodigo: verificacionCodigo
}
function getAllProdPorCliente(cdcliente, cb){
conn("select * from Produc where cdcliente=" + cdcliente, cb);
}
function getAll(cb){
conn("select * from produc", cb);
}
function getUltimo(cdcliente, cb){
conn("select max(codigo) as max from Produc where cdcliente="+ cdcliente, cb)
}
function insertProd(codigo, cdcliente, lote, umed, nombre, idformulado, cantidad, cb){
conn("insert into Produc(codigo, cdcliente, AbLote, umed, nombre, activa, idFormulado, canFormulado) values('"+codigo+"',"+cdcliente+", '"+ lote +"', '"+umed+"', '"+nombre+"', 1, "+idformulado+", "+cantidad+"); ", cb);
}
function getProdPorCodigoParaCadaCliente(codigo, cdcliente, cb){
conn("select codigo from Produc where codigo ='"+codigo +"' AND cdcliente="+ cdcliente, cb);
}
function getProdPorNombreParaCadaCliente(nombre, cdcliente, cb){
conn("select nombre from Produc where nombre='"+nombre+"' AND cdcliente="+ cdcliente, cb);
}
function getcdClientePorIdProducto(id, cb){
conn("select cdcliente from produc where id="+id, cb);
}
function getProdPorId(id, cb){
conn("select * from Produc where id="+id, cb);
}
function updateProd(id, cdcliente, codigo, nombre, lote, umed, activo, idformulado, cantidad, cb){
conn("update Produc set cdcliente="+cdcliente+", codigo='"+codigo+"', nombre='"+nombre+"', AbLote='"+lote+"', umed='"+umed+"', activa="+activo+", idFormulado="+idformulado+", canFormulado="+cantidad+" where id="+id, cb);
}
function delProd(id, cb){
conn("DELETE from Produc where id="+id, cb);
}
function getAllActivosPorCliente(id, cb){
conn("SELECT * from produc where cdcliente="+ id +" and activa = 1 order by nombre", cb);
}
function getAbLotePorIDProd(id, cb){
conn("SELECT * from produc where id="+id, cb);
}
function verificacionCodigo(id, codigo, cb){
conn("select * from produc where codigo = '"+codigo+"' AND id <> "+id, cb)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.