text
stringlengths 2
6.14k
|
|---|
import JSONFile from 'loader/types/JSONFile.js';
let testFile = JSONFile('test', 'assets/folderTest.json');
testFile.load().then(
(file) => loadComplete(file)
);
function loadComplete (file) {
console.log('JSON File has loaded');
file.onProcess();
console.log(file.data);
}
|
import React from 'react'
import { ListGroupItem, FormCheck, Button } from 'react-bootstrap'
import { useCommand } from '@resolve-js/react-hooks'
const ShoppingListItem = ({ shoppingListId, item: { id, checked, text } }) => {
const toggleItem = useCommand({
type: 'toggleShoppingItem',
aggregateId: shoppingListId,
aggregateName: 'ShoppingList',
payload: {
id,
},
})
const removeItem = useCommand({
type: 'removeShoppingItem',
aggregateId: shoppingListId,
aggregateName: 'ShoppingList',
payload: {
id,
},
})
return (
<ListGroupItem key={id}>
<FormCheck
inline
type="checkbox"
label={text}
checked={checked}
onChange={toggleItem}
/>
<Button className="float-right" onClick={removeItem}>
Delete
</Button>
</ListGroupItem>
)
}
export default ShoppingListItem
|
var fs = require('fs');
module.exports = function (app) {
app.config([
'formioComponentsProvider',
function (formioComponentsProvider) {
formioComponentsProvider.register('well', {
title: 'Well',
template: 'formio/components/well.html',
group: 'layout',
settings: {
input: false,
components: []
}
});
}
]);
app.run([
'$templateCache',
function ($templateCache) {
$templateCache.put('formio/components/well.html',
fs.readFileSync(__dirname + '/../templates/components/well.html', 'utf8')
);
}
]);
};
|
'./quarterreview.html'
///// HELPERS /////
Template.quarterreviewPage.helpers({
quarterreviewEach() {
return DevTest.find( { spirit: {$exists: true}}, {sort: {createdAt: -1}}); },
});
////////* quarterreview Events *//////
|
'use strict';
/* global Connector, Util */
setupConnector();
function setupConnector() {
if (isRadioPlayer()) {
setupRadioPlayer();
} else if (isMusicPlayer()) {
setupMusicPlayer();
}
}
function isRadioPlayer() {
return $('.cur-blk').length > 0;
}
function isMusicPlayer() {
$('.cnt-song-lst').length > 0;
}
function setupMusicPlayer() {
Connector.playerSelector = '.cnt-song-lst';
Connector.getArtistTrack = function() {
let text = $('.playing .song').clone().children('.like-count').remove().end().text();
return Util.splitArtistTrack(text);
};
Connector.isPlaying = () => $('.playing .pause').length > 0;
Connector.getCurrentTime = () => $('.playing .p-btn').attr('sec');
Connector.getDuration = () => $('.playing .p-btn').attr('data-to_sec');
}
function setupRadioPlayer() {
Connector.playerSelector = '.cur-blk';
Connector.artistTrackSelector = '.cur-blk .name';
Connector.isPlaying = () => $('.cur-blk #play').hasClass('pause');
Connector.durationSelector = '.cur-blk .total-time';
}
|
import ControllerMixin from "ember-runtime/mixins/controller";
import ObjectProxy from "ember-runtime/system/object_proxy";
/**
@module ember
@submodule ember-runtime
*/
/**
`Ember.ObjectController` is part of Ember's Controller layer. It is intended
to wrap a single object, proxying unhandled attempts to `get` and `set` to the underlying
model object, and to forward unhandled action attempts to its `target`.
`Ember.ObjectController` derives this functionality from its superclass
`Ember.ObjectProxy` and the `Ember.ControllerMixin` mixin.
@class ObjectController
@namespace Ember
@extends Ember.ObjectProxy
@uses Ember.ControllerMixin
**/
export default ObjectProxy.extend(ControllerMixin);
|
module.exports = {
description: 'handles transforms that return stringified source maps (#377)',
options: {
plugins: [
{
transform: function ( code ) {
return {
code: code,
// just stringify an otherwise acceptable source map
map: JSON.stringify({ mappings: '' })
};
}
}
]
},
// ensure source maps are generated
bundleOptions: {
sourcemap: true
}
};
|
/**
* @summary Kick off the global namespace for Telescope.
* @namespace Telescope
*/
Telescope = {};
Telescope.VERSION = '0.27.1-nova';
// ------------------------------------- Config -------------------------------- //
/**
* @summary Telescope configuration namespace
* @namespace Telescope.config
*/
Telescope.config = {};
// ------------------------------------- Schemas -------------------------------- //
SimpleSchema.extendOptions({
private: Match.Optional(Boolean),
editable: Match.Optional(Boolean), // editable: true means the field can be edited by the document's owner
hidden: Match.Optional(Boolean), // hidden: true means the field is never shown in a form no matter what
required: Match.Optional(Boolean), // required: true means the field is required to have a complete profile
profile: Match.Optional(Boolean), // profile: true means the field is shown on user profiles
template: Match.Optional(String), // template used to display the field
autoform: Match.Optional(Object), // autoform placeholder
control: Match.Optional(Match.Any), // NovaForm control (String or React component)
order: Match.Optional(Number), // position in the form
group: Match.Optional(Object) // form fieldset group
});
// ------------------------------------- Components -------------------------------- //
Telescope.components = {};
Telescope.registerComponent = (name, component) => {
Telescope.components[name] = component;
};
Telescope.getComponent = (name) => {
return Telescope.components[name];
};
// ------------------------------------- Subscriptions -------------------------------- //
/**
* @summary Subscriptions namespace
* @namespace Telescope.subscriptions
*/
Telescope.subscriptions = [];
/**
* @summary Add a subscription to be preloaded
* @param {string} subscription - The name of the subscription
*/
Telescope.subscriptions.preload = function (subscription, args) {
Telescope.subscriptions.push({name: subscription, arguments: args});
};
// ------------------------------------- Strings -------------------------------- //
Telescope.strings = {};
// ------------------------------------- Routes -------------------------------- //
Telescope.routes = {
routes: [],
add(routeOrRouteArray) {
const addedRoutes = Array.isArray(routeOrRouteArray) ? routeOrRouteArray : [routeOrRouteArray];
this.routes = this.routes.concat(addedRoutes);
}
}
// ------------------------------------- Head Tags -------------------------------- //
Telescope.headtags = {
meta: [],
link: []
}
// ------------------------------------- Statuses -------------------------------- //
Telescope.statuses = [
{
value: 1,
label: 'pending'
},
{
value: 2,
label: 'approved'
},
{
value: 3,
label: 'rejected'
},
{
value: 4,
label: 'spam'
},
{
value: 5,
label: 'deleted'
}
];
export default Telescope;
|
// require(['jquery', 'jquery.inlinecomplete', 'boostrap', 'app.boostrap', 'events', 'configuration', 'application', 'index_page']);
require.config({
paths: {
'jquery': 'jquery.js',
}
});
require(['jquery'], function(jQuery) {
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:e027f9a86e8d83f34f323ce1856bbb9a68fe33019e6bcc028797c872f000deea
size 753
|
var controllers={};
try
{
controllers= require('require-all')({
dirname : require("path").resolve('./api/controllers'),
filter : /(.+Controller)\.js$/,
excludeDirs : /^\.(git|svn)$/,
recursive : true
});
}
catch(err)
{
throw(err);
}
module.exports= controllers;
|
{
"this": "is",
"a": "JavaScript",
"object": "yay!"
}
|
import Flickr from "@/flickr"
export default function add({ flickr = Flickr, photoId = `` } = {}) {
return flickr.fetchResource(`flickr.favorites.add`, { photoId }, {}, `write`)
}
|
import React from 'react';
const DisplayMessage = ({title, timestamp, user}) => {
let prettyTime = new Date(timestamp).toString().substring(0, 24);
return (
<p className="message">
<span className="pretty-time">{prettyTime} </span>
<span className="name-of-user">{user} </span><br/>
<span className="single-message">{title}</span>
</p>
)
}
export default DisplayMessage;
|
"use strict";
var setup = require("./setup");
var db = require("../index");
var expect = require("chai").expect;
var DbUtil = require("./db-util");
var util = require("./util");
var conti = require("conti");
var model = require("./model");
var initDb = util.createClearTableFun(["presc_example", "iyakuhin_master_arch"]);
describe("Testing search presc example", function(){
var conn = setup.getConnection();
beforeEach(initDb);
afterEach(initDb);
var old_valid_from = "2014-04-01";
var old_valid_upto = "2016-03-31";
var valid_from = "2016-04-01";
var at = "2016-06-26";
var valid_upto = "2018-03-31";
var future_valid_from = "2018-04-01";
var future_valid_upto = "2020-03-31";
it("empty", function(done){
db.searchPrescExample(conn, "テスト", function(err, result){
if( err ){
done(err);
return;
}
expect(result).eql([]);
done();
})
});
function makePrescExample(name, valid_from, valid_upto){
var master = model.iyakuhinMaster({
name: name,
valid_from: valid_from,
valid_upto: valid_upto
});
return model.prescExample({
m_master_valid_from: valid_from
}).setMaster(master);
}
it("case 1", function(done){
var ex = makePrescExample("あいう", valid_from, valid_upto);
conti.exec([
function(done){
ex.save(conn, done);
},
function(done){
db.searchPrescExample(conn, "い", function(err, result){
if( err ){
done(err);
return;
}
var ans = [ex.getFullData()];
expect(result).eql(ans);
done();
});
}
], done);
});
it("case 2", function(done){
var ex = makePrescExample("あいう", old_valid_from, old_valid_upto);
conti.exec([
function(done){
ex.save(conn, done);
},
function(done){
db.searchPrescExample(conn, "い", function(err, result){
if( err ){
done(err);
return;
}
var ans = [ex.getFullData()];
expect(result).eql(ans);
done();
});
}
], done);
});
it("case 3", function(done){
var ex = makePrescExample("あいう", future_valid_from, future_valid_upto);
conti.exec([
function(done){
ex.save(conn, done);
},
function(done){
db.searchPrescExample(conn, "い", function(err, result){
if( err ){
done(err);
return;
}
var ans = [ex.getFullData()];
expect(result).eql(ans);
done();
});
}
], done);
});
it("case 4", function(done){
var exlist = [
makePrescExample("あいう", valid_from, valid_upto),
makePrescExample("かきく", old_valid_from, old_valid_upto),
makePrescExample("さいす", future_valid_from, future_valid_upto),
makePrescExample("たちつ", valid_from, valid_upto),
];
conti.exec([
function(done){
model.batchSave(conn, exlist, done);
},
function(done){
db.searchPrescExample(conn, "い", function(err, result){
if( err ){
done(err);
return;
}
var ans = [0, 2].map(function(i){ return exlist[i].getFullData(); });
expect(result).eql(ans);
done();
});
}
], done);
})
});
|
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([
'chai',
'underscore',
'extendable-base'
], factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like enviroments that support module.exports,
// like Node.
module.exports = factory(require('chai'), require('underscore'), require('extendable-base'));
} else {
// Browser globals
this.extendable_base_specs = factory(chai, underscore, extendablebase);
}
}(function (__external_chai, __external_underscore, __external_extendablebase) {
var global = this, define;
function _require(id) {
var module = _require.cache[id];
if (!module) {
var exports = {};
module = _require.cache[id] = {
id: id,
exports: exports
};
_require.modules[id].call(exports, module, exports);
}
return module.exports;
}
_require.cache = [];
_require.modules = [
function (module, exports) {
module.exports = __external_chai;
},
function (module, exports) {
module.exports = __external_extendablebase;
},
function (module, exports) {
var Base = _require(1);
var expect = _require(0).expect;
describe('base class', function () {
function BaseClass() {
this.base_was_here = true;
}
var DerivedClass = Base.inherits(BaseClass, {
initialize: function () {
this.derived_was_here = true;
}
});
it('calls base class constructor', function () {
var d = new DerivedClass();
expect(d.base_was_here).to.equal(true);
expect(d.derived_was_here).to.equal(true);
});
});
}
];
return _require(2);
}));
|
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _functionalCurry = require('../functional/curry');
var hasIn = (0, _functionalCurry.curry)(function (property, obj) {
return property in obj;
});
exports.hasIn = hasIn;
|
/*
Math Kit
Copyright (c) 2014 - 2019 Cédric Ronvel
The MIT License (MIT)
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.
*/
"use strict" ;
const utils = require( './utils.js' ) ;
// A starting point/position and a vector, i.e. vector applied on a point/position.
function BoundingBox2D( xMin , yMin , xMax , yMax ) {
this.min = new Vector2D( xMin , yMin ) ;
this.max = new Vector2D( xMax , yMax ) ;
}
module.exports = BoundingBox2D ;
const Vector2D = require( './Vector2D.js' ) ;
BoundingBox2D.fromObject = object => new BoundingBox2D( object.min.x , object.min.y , object.max.x , object.max.y ) ;
BoundingBox2D.fromMinMaxVectors = ( min , max ) => new BoundingBox2D( min.x , min.y , max.x , max.y ) ;
// Create a new bound vector, starting from positional vector1 and pointing to the positional vector2
BoundingBox2D.fromTo = ( fromVector , toVector ) => new BoundingBox2D().setFromTo( fromVector , toVector ) ;
BoundingBox2D.fromPointCloud = points => {
var xMin = Infinity ,
yMin = Infinity ,
xMax = -Infinity ,
yMax = -Infinity ;
points.forEach( point => {
if ( point.x < xMin ) { xMin = point.x ; }
if ( point.x > xMax ) { xMax = point.x ; }
if ( point.y < yMin ) { yMin = point.y ; }
if ( point.y > yMax ) { yMax = point.y ; }
} ) ;
return new BoundingBox2D( xMin , yMin , xMax , yMax ) ;
} ;
BoundingBox2D.prototype.setMinMaxVectors = function( min , max ) {
this.min.setVector( min ) ;
this.max.setVector( max ) ;
return this ;
} ;
BoundingBox2D.prototype.setBoundingBox = function( boundingBox ) {
this.min.setVector( boundingBox.min ) ;
this.max.setVector( boundingBox.max ) ;
return this ;
} ;
// Create a new bound vector, starting from positional vector1 and pointing to the positional vector2
BoundingBox2D.prototype.setFromTo = function( fromVector , toVector ) {
if ( fromVector.x < toVector.x ) { this.min.x = fromVector.x ; this.max.x = toVector.x ; }
else { this.min.x = toVector.x ; this.max.x = fromVector.x ; }
if ( fromVector.y < toVector.y ) { this.min.y = fromVector.y ; this.max.y = toVector.y ; }
else { this.min.y = toVector.y ; this.max.y = fromVector.y ; }
return this ;
} ;
BoundingBox2D.prototype.dup = BoundingBox2D.prototype.clone = function() {
return new BoundingBox2D( this.min.x , this.min.y , this.max.x , this.max.y ) ;
} ;
BoundingBox2D.prototype.add = function( bbox ) {
this.min.add( bbox.min ) ;
this.max.add( bbox.max ) ;
return this ;
} ;
BoundingBox2D.prototype.boundingBoxIntersection = function( withBbox ) {
return (
utils.egte( this.max.x , withBbox.min.x ) &&
utils.elte( this.min.x , withBbox.max.x ) &&
utils.egte( this.max.y , withBbox.min.y ) &&
utils.elte( this.min.y , withBbox.max.y )
) ;
} ;
BoundingBox2D.prototype.translatedBoundingBoxesIntersection = function( position , withBbox , withBboxPosition ) {
return (
utils.egte( this.max.x + position.x , withBbox.min.x + withBboxPosition.x ) &&
utils.elte( this.min.x + position.x , withBbox.max.x + withBboxPosition.x ) &&
utils.egte( this.max.y + position.y , withBbox.min.y + withBboxPosition.y ) &&
utils.elte( this.min.y + position.y , withBbox.max.y + withBboxPosition.y )
) ;
} ;
// Same with moving (sweeping) BBoxes
BoundingBox2D.prototype.sweepingBoundingBoxesIntersection = function( boundVector , withBbox , withBboxBoundVector ) {
var dx = Math.abs( boundVector.vector.x - withBboxBoundVector.x ) ;
var dy = Math.abs( boundVector.vector.y - withBboxBoundVector.y ) ;
return (
utils.egte( this.max.x + boundVector.position.x + dx , withBbox.min.x + withBboxBoundVector.position.x ) &&
utils.elte( this.min.x + boundVector.position.x - dx , withBbox.max.x + withBboxBoundVector.position.x ) &&
utils.egte( this.max.y + boundVector.position.y + dy , withBbox.min.y + withBboxBoundVector.position.y ) &&
utils.elte( this.min.y + boundVector.position.y - dy , withBbox.max.y + withBboxBoundVector.position.y )
) ;
} ;
// Same with from/to position instead of boundVector
BoundingBox2D.prototype.sweepingBoundingBoxesFromToIntersection = function( from , to , withBbox , withBboxFrom , withBboxTo ) {
var dx = Math.abs( to.x - from.x + withBboxTo.x - withBboxFrom.x ) ;
var dy = Math.abs( to.y - from.y + withBboxTo.y - withBboxFrom.y ) ;
return (
utils.egte( this.max.x + from.x + dx , withBbox.min.x + withBboxFrom.x ) &&
utils.elte( this.min.x + from.x - dx , withBbox.max.x + withBboxFrom.x ) &&
utils.egte( this.max.y + from.y + dy , withBbox.min.y + withBboxFrom.y ) &&
utils.elte( this.min.y + from.y - dy , withBbox.max.y + withBboxFrom.y )
) ;
} ;
|
import { ActionTypes as types } from '../../src/constants';
import * as actions from '../../src/actions';
import expect from 'expect';
describe('GameActions', () => {
it('should create an action to turn a deck card', () => {
const expectedAction = { type: types.TURN_CARD };
expect(actions.turnCard()).toEqual(expectedAction);
});
it('should create an action to move cards', () => {
const where = { from: 'FOO', to: 'BAR'};
const cards = [];
const expectedAction = {
type: types.MOVE_CARD,
payload: {
where,
cards
}
};
expect(actions.moveCard(cards, where)).toEqual(expectedAction);
});
});
|
'use strict';
const metasync = require('..');
const metatests = require('metatests');
metatests.test('fifo / priority', test => {
const expectedResult = [1, 2, 3, 8, 6, 4, 5, 7, 9];
const result = [];
const q = metasync
.queue(3)
.priority()
.process((item, cb) => {
result.push(item.id);
setTimeout(cb, 100);
});
q.drain(() => {
test.strictSame(result, expectedResult);
test.end();
});
q.add({ id: 1 }, 0);
q.add({ id: 2 }, 0);
q.add({ id: 3 }, 1);
q.add({ id: 4 }, 0);
q.add({ id: 5 }, 0);
q.add({ id: 6 }, 10);
q.add({ id: 7 }, 0);
q.add({ id: 8 }, 100);
q.add({ id: 9 }, 0);
});
|
'use strict'
const MetaRole = require('roles_meta')
class Miner extends MetaRole {
constructor () {
super()
this.defaultEnergy = 950
}
getBuild (room, options) {
this.setBuildDefaults(room, options)
let base
if (options.remote) {
base = [MOVE, CARRY, WORK, WORK, WORK, WORK, WORK, WORK, MOVE, MOVE, MOVE, WORK]
if (options.energy >= 950) {
return base
}
} else {
base = [MOVE, CARRY, WORK, WORK, WORK, WORK, WORK, WORK, MOVE, MOVE]
if (options.energy >= 800) {
return base
}
}
return Creep.buildFromTemplate(base, options.energy)
}
}
module.exports = Miner
|
module.exports = (req) => {
if (req.file || req.files) {
const files = req.files ? req.files : [];
if (req.file) {
files.push(req.file);
}
return files;
}
};
|
/*global JSONFormatter */
jQuery( document ).ready(function( $ ) {
$('#form').submit(function(event){
event.preventDefault();
processForm();
});
var success = function(weather) {
console.log(weather);
var formatter = new JSONFormatter(weather);
$('#result').html(formatter.render());
$('.loading').addClass('hidden');
};
var processForm = function() {
$('.loading').removeClass('hidden');
$.simpleWeather({
location: $('input').val(),
unit: 'si',
success: success
});
};
});
|
"use strict";
var config = require('../config'),
nodemailer = require('nodemailer'),
//transporter = nodemailer.createTransport('smtps://'+config.mailsender.login+'%40gmail.com:'+config.mailsender.pwd+'@smtp.gmail.com');
transporter = nodemailer.createTransport('smtps://'+config.mailsender.login+'%40artbyacudj.xyz:'+config.mailsender.pwd+'@mail.gandi.net');
class Mail{
/**
*/
constructor() {
}
/**
* Send contact request to admin
*/
sendContact(infos){
// setup e-mail data with unicode symbols
var mailOptions = {
from: '"'+config.mailsender.name+'" <'+config.mailsender.email+'>', // sender address
replyTo: infos.email, // sender address
to: config.mailsender.email, // list of receivers
subject: '[contact] '+infos.subject, // Subject line
text: infos.message
//,html: '<b>Hello world ?</b>' // html body
};
return new Promise(
(resolve, reject)=>{
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
reject(error);
}
else{
resolve();
}
});
});
}
/**
* Send a new commission request to admin
*/
sendCommission(infos){
// setup e-mail data with unicode symbols
var mailOptions = {
from: '"'+config.mailsender.name+'" <'+config.mailsender.email+'>', // sender address
replyTo: infos.email, // sender address
to: config.mailsender.email, // list of receivers
subject: 'new commission ! ', // Subject line
text: 'the new commission comes from: '+infos.name +', '+infos.email + '\n\n Here is what they ask:\n\n'+infos.description
//,html: '<b>Hello world ?</b>' // html body
};
return new Promise(
(resolve, reject)=>{
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
reject(error);
}
else{
resolve();
}
});
});
}
/**
* send order summary to the admin so they can prepare the command
*/
sendNewOrderToProcess(infos){
// setup e-mail data with unicode symbols
var mailOptions = {
from: '"'+config.mailsender.name+'" <'+config.mailsender.email+'>', // sender address
replyTo: config.mailsender.email, // sender address
to: config.mailsender.email, // list of receivers
subject: '[new order] '+infos.nbItems+' items for '+infos.prices.totalPrice+'CAD', // Subject line
text: 'New order !\n\n Order\'s summary: \n'+infos.summary+'\n\n To be sent at \n'+infos.address+'\n\n Expected payment:\n '+infos.prices.totalPrice+'CAD \n\n Congrats !!! :D'
//,html: '<b>Hello world ?</b>' // html body
};
return new Promise(
(resolve, reject)=>{
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
reject(error)
}
else{
resolve();
}
})
});
}
/**
* send order summary to the admin so they can prepare the command
*/
sendNewOrderConfirmationToCustomer(infos){
// setup e-mail data with unicode symbols
var mailOptions = {
from: '"'+config.mailsender.name+'" <'+config.mailsender.email+'>', // sender address
replyTo: config.mailsender.email, // sender address
to: infos.email, // list of receivers
subject: '[new order] Summary of your order', // Subject line
text: 'Thank you for your order!\n\n Here is the summary: \n'+infos.summary+'\n\n Address of shipping: \n'+infos.address+'\n\n Price: '+infos.prices.totalPrice+'CAD. \n Two options of payment are available: \n - You can use Paypal easily on this page: http://paypal.me/artbyaudj \n - Or send me an e-transfer at this address: [email protected]. \n\n If you have any questions, please feel free to reply to this email directly. \n\n Art by ACUDJ'
//,html: '<b>Hello world ?</b>' // html body
};
return new Promise(
(resolve, reject)=>{
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
reject(error)
}
else{
resolve();
}
});
});
}
}
module.exports.mail = new Mail();
|
/**
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
;(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
app: 'app',
// angular bundles
'@angular/core': 'npm:@angular/core/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common/bundles/common.umd.js',
'@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router/bundles/router.umd.js',
'@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
// ng2-bootstrap
'moment': 'npm:moment/moment.js',
'ng2-bootstrap': 'npm:ng2-bootstrap/bundles/ng2-bootstrap.umd.js'
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
}
}
})
})(this)
|
var path = require('path');
var webpack = require('webpack');
var projectRootPath = path.resolve(__dirname, '../');
module.exports = {
devtool: process.env.NODE_ENV === 'production' ? false : 'inline-source-map',
output: {
path: path.join(projectRootPath, 'static/dist/dlls'),
filename: 'dll__[name].js',
library: 'DLL_[name]_[hash]'
},
performance: {
hints: false
},
entry: {
vendor: [
'babel-polyfill',
// <babel-runtime>
//
// Generate this list using the following command against the stdout of
// webpack running against the source bundle config (dev/prod.js):
//
// webpack --config webpack/dev.config.js --display-modules | egrep -o 'babel-runtime/\S+' | sed 's/\.js$//' | sort | uniq
'babel-runtime/core-js/array/from',
'babel-runtime/core-js/get-iterator',
'babel-runtime/core-js/is-iterable',
'babel-runtime/core-js/json/stringify',
'babel-runtime/core-js/number/is-integer',
'babel-runtime/core-js/number/is-safe-integer',
'babel-runtime/core-js/object/assign',
'babel-runtime/core-js/object/create',
'babel-runtime/core-js/object/define-property',
'babel-runtime/core-js/object/get-own-property-descriptor',
'babel-runtime/core-js/object/get-own-property-names',
'babel-runtime/core-js/object/get-prototype-of',
'babel-runtime/core-js/object/keys',
'babel-runtime/core-js/object/set-prototype-of',
'babel-runtime/core-js/promise',
'babel-runtime/core-js/symbol',
'babel-runtime/core-js/symbol/iterator',
'babel-runtime/helpers/class-call-check',
'babel-runtime/helpers/classCallCheck',
'babel-runtime/helpers/create-class',
'babel-runtime/helpers/createClass',
'babel-runtime/helpers/defineProperty',
'babel-runtime/helpers/extends',
'babel-runtime/helpers/get',
'babel-runtime/helpers/inherits',
'babel-runtime/helpers/interop-require-default',
'babel-runtime/helpers/interopRequireDefault',
'babel-runtime/helpers/object-without-properties',
'babel-runtime/helpers/objectWithoutProperties',
'babel-runtime/helpers/possibleConstructorReturn',
'babel-runtime/helpers/slicedToArray',
'babel-runtime/helpers/to-consumable-array',
'babel-runtime/helpers/toConsumableArray',
'babel-runtime/helpers/typeof',
// </babel-runtime>
'axios',
'multireducer',
'react',
'react-bootstrap',
'react-dom',
'react-helmet',
'react-hot-loader',
'react-redux',
'react-router',
'react-router-bootstrap',
'react-router-redux',
'react-router-scroll',
'redux',
'redux-connect',
'redux-form',
'serialize-javascript',
'socket.io-client'
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
}),
new webpack.DllPlugin({
path: path.join(projectRootPath, 'webpack/dlls/[name].json'),
name: 'DLL_[name]_[hash]'
})
]
};
|
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
var mssql = require('mssql'),
helpers = require('./helpers'),
promises = require('../../utilities/promises'),
log = require('../../logger'),
connection;
module.exports = function (config, statement) {
// for some reason, creating a new connection object for each request hangs on the second request when hosted
// not sure if this will have any effect on performance, i.e. does each request have to wait for the last to complete?
if(!connection) {
connection = new mssql.Connection(config)
return connection.connect()
.then(executeRequest)
.catch(function (err) {
connection = undefined;
throw err;
});
} else
return executeRequest();
function executeRequest() {
var request = new mssql.Request(connection);
request.multiple = statement.multiple;
if(statement.parameters) {
statement.parameters.forEach(function (parameter) {
var type = parameter.type || helpers.getMssqlType(parameter.value);
if(type)
request.input(parameter.name, type, parameter.value);
else
request.input(parameter.name, parameter.value);
});
}
log.verbose('Executing SQL statement ' + statement.sql + ' with parameters ' + JSON.stringify(statement.parameters));
return request.query(statement.sql).catch(function (err) {
log.debug('SQL statement failed - ' + err.message + ': ' + statement.sql + ' with parameters ' + JSON.stringify(statement.parameters));
if(err.number === 2627) {
var error = new Error('An item with the same ID already exists');
error.duplicate = true;
throw error;
}
return promises.rejected(err);
});
}
};
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/*!***********************************!*\
!*** ./parsing/evaluate/index.js ***!
\***********************************/
/***/ function(module, exports, __webpack_require__) {
it("should define DEBUG", function() {
(false).should.be.eql(false);
("boolean").should.be.eql("boolean");
var x = __webpack_require__(/*! ./a */ 1);
var y = false ? require("fail") : __webpack_require__(/*! ./a */ 1);
});
it("should short-circut evaluating", function() {
var expr;
var a = false ? require("fail") : __webpack_require__(/*! ./a */ 1);
var b = true ? __webpack_require__(/*! ./a */ 1) : require("fail");
});
it("should evaluate __dirname and __resourceQuery with replace and substr", function() {
var result = __webpack_require__(/*! ./resourceQuery/index?C:/Users/kop/Repos/~/webpack/test/cases/parsing/evaluate */ 2);
result.should.be.eql("?resourceQuery");
});
/***/ },
/* 1 */
/*!*******************************!*\
!*** ./parsing/evaluate/a.js ***!
\*******************************/
/***/ function(module, exports, __webpack_require__) {
module.exports = "a";
/***/ },
/* 2 */
/*!*************************************************************************************************!*\
!*** ./parsing/evaluate/resourceQuery?C:/Users/kop/Repos/~/webpack/test/cases/parsing/evaluate ***!
\*************************************************************************************************/
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(/*! ./parsing/evaluate/resourceQuery/returnRQ?resourceQuery */ 3);
/***/ },
/* 3 */
/*!******************************************************************!*\
!*** ./parsing/evaluate/resourceQuery/returnRQ.js?resourceQuery ***!
\******************************************************************/
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(__resourceQuery) {module.exports = __resourceQuery;
/* WEBPACK VAR INJECTION */}.call(exports, "?resourceQuery"))
/***/ }
/******/ ])
/*
//@ sourceMappingURL=bundle.js.map
//# sourceMappingURL=bundle.js.map
*/
|
/* jshint mocha: true */
'use strict';
describe('dir', function() {
it('should be requireable', function() {
require('../dir').should.be.a.Function;
});
});
|
'use strict';
describe('myApp.icons module', function() {
beforeEach(module('myApp.icons'));
describe('icons controller', function(){
it('should ....', inject(function($controller) {
//spec body
var iconsCtrl = $controller('iconsCtrl');
expect(iconsCtrl).toBeDefined();
}));
});
});
|
// General utility functions
var Utility = require( './lib/utility' );
// Pull in the app config
var config = require( './lib/config' );
// Set up app-wide logger
var logger = require( './lib/logger' );
// Attempt to create database connection - if we can't connect don't bother
// doing anything else
var dbConnect = require( './lib/db' );
var db;
// Build the Express app
var Express = require( 'express' );
var Compression = require( 'compression' );
var BodyParser = require( 'body-parser' );
var app = Express();
// Set the app up
app.use( Compression() );
app.use( BodyParser.json() );
// Pull in route controllers
var apiGet = require( './lib/routes/get' );
var apiSearch = require( './lib/routes/search' );
// First attempt database connection
dbConnect
.then( function ( _db ) {
db = _db;
///////////////////////////////////////////////////////////////////////////////
// Routes /////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Get object (Item, Vendor or Mob)
app.all( '/get/:type/:id', function( req, res ) {
var id = req.params.id;
var type = req.params.type;
// If type isn't valid, we out
if ( type !== 'item' && type !== 'mob' && type !== 'vendor' ) {
return res.status( 404 ).jsonp({ error: 'Nothin\' there, chief.', errorCode: 'pageNotFound' });
}
// Retrieve the specified item
apiGet( db, type, id )
.then( function ( result ) {
return res.jsonp({ success: true, result: result });
})
.catch( function ( err ) {
logger.error( 'Error fetching database object: ', err );
return res.jsonp({ error: 'Error fetching object', errorCode: 'databaseError' });
});
});
// Search the database
app.all( '/search/:type', function( req, res ) {
var type = req.params.type;
var query = Utility.getRequestValue( 'query', req );
// If type isn't valid, we out
if ( type !== 'item' && type !== 'mob' && type !== 'vendor' ) {
return res.status( 404 ).jsonp({ error: 'Nothin\' there, chief.', errorCode: 'pageNotFound' });
}
// If query wasn't passed, we also out
if ( ! query ) {
return res.jsonp({ error: 'Must pass valid search query to search.', errorCode: 'invalidParams' });
}
apiSearch( db, type, query )
.then( function ( result ) {
return res.jsonp({ success: true, result: result });
})
.catch( function ( err ) {
logger.error( 'Error fetching database object: ', err );
return res.jsonp({ error: 'Error fetching object', errorCode: 'databaseError' });
});
});
// FOUR OH FOUR
app.get( '*', function( req, res ) {
return res.status( 404 ).jsonp({ error: 'Nothin\' there, chief.', errorCode: 'pageNotFound' });
});
///////////////////////////////////////////////////////////////////////////////
// Away we go /////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Then if that went well, start the app
app.listen( config.port, function () {
logger.info( 'API server active.', { port: config.port } );
});
})
.catch( function ( err ) {
logger.error( 'Unable to establish database connection.', err );
});
///////////////////////////////////////////////////////////////////////////////
// Exit ///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Prevents node from existing instantly by starting to read stdInput
process.stdin.resume();
// Interrupt signal (Ctrl+C)
process.on( 'SIGINT', cleanup );
///////////////////////////////////////////////////////////////////////////////
// Internal functions /////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
function cleanup () {
// Close the database connection
if ( db && typeof( db.close ) === 'function' ) {
db.close();
}
logger.info( 'Exiting...' );
process.exit();
}
|
var jsConsole;
(function () {
var button = document.getElementById("check");
button.onclick = function () {
jsConsole.clearConsole();
var number = document.getElementById("number").value,
theLastDigitAsEnglishWord = getLastDigitAsEnglishWord(number);
console.log("Last digit as word: " + theLastDigitAsEnglishWord);
jsConsole.write("Last digit as word: " + theLastDigitAsEnglishWord);
};
function getLastDigitAsEnglishWord(number) {
number = parseFloat(number);
if (!(isNaN(number))) {
var digit = 0,
digitAsString = "";
digitAsWord = "not a number",
len = 0;
//default value
number = number || 0;
numberAsString = number.toString();
len = numberAsString.length;
//separates the last symbol and parses it as digit
digitAsString = numberAsString.slice(len - 1);
digit = parseInt(digitAsString);
switch (digit) {
case 0: {
digitAsWord = "zero";
break;
}
case 1: {
digitAsWord = "one";
} break;
case 2: {
digitAsWord = "two";
} break;
case 3: {
digitAsWord = "three";
} break;
case 4: {
digitAsWord = "four";
} break;
case 5: {
digitAsWord = "five";
} break;
case 6: {
digitAsWord = "six";
} break;
case 8: {
digitAsWord = "eight";
} break;
case 9: {
digitAsWord = "nine";
} break;
default: digitAsWord = "not a digit";
break;
}
return digitAsWord;
}
else {
return "not a number";
}
}
})();
|
(function () {
'use strict';
angular
.module('courses')
.directive('courseFormControlButtons', courseFormControlButtons);
function courseFormControlButtons() {
return {
scope: false,
templateUrl: 'modules/courses/directives/formControlButtons/formControlButtons.template.html'
};
}
}());
|
var memc = require("../lib/client");
var client = new memc.Connection();
client.parser.chunked = false;
client.parser.encoding = memc.constants.encodings.UTF8;
var key = "node-memcached-test";
var value = "12345";
var port = process.argv[2] || 11211;
var host = process.argv[3] || "127.0.0.1";
/*
{"method": "connect", "params":"port, host, cb"}
{"method": "get", "params":"key, cb"}
{"method": "getq", "params":"key, cb"}
{"method": "getk", "params":"key, cb"}
{"method": "getkq", "params":"key, cb"}
{"method": "set", "params":"key, value, flags, expiration, cb"}
{"method": "setq", "params":"key, value, flags, expiration, cb"}
{"method": "add", "params":"key, value, flags, expiration, cb"}
{"method": "addq", "params":"key, value, flags, expiration, cb"}
{"method": "replace", "params":"key, value, flags, expiration, cb"}
{"method": "replaceq", "params":"key, value, flags, expiration, cb"}
{"method": "inc", "params":"key, delta, initial, expiration, cb"}
{"method": "dec", "params":"key, delta, initial, expiration, cb"}
{"method": "incq", "params":"key, delta, initial, expiration, cb"}
{"method": "decq", "params":"key, delta, initial, expiration, cb"}
{"method": "delete", "params":"key, cb"}
{"method": "deleteq", "params":"key, cb"}
{"method": "append", "params":"key, value, cb"}
{"method": "prepend", "params":"key, value, cb"}
{"method": "appendq", "params":"key, value, cb"}
{"method": "prependq", "params":"key, value, cb"}
{"method": "quit", "params":"cb"}
{"method": "quitq", "params":"cb"}
{"method": "version", "params":"cb"}
{"method": "stat", "params":"key, cb"}
{"method": "noop", "params":"cb"}
{"method": "flush", "params":"expiration, cb"}
{"method": "flushq", "params":"expiration, cb"}
*/
client.connect(port, host, function() {
console.log("connected");
client.flush(null, function(message) {
console.log("FLUSH: " + (message.header.status == memc.constants.status.NO_ERROR?"OK":"FAIL"));
});
client.version(function(message) {
console.log("VERSION: " + message.body);
});
client.noop(function(message) {
console.log("NOOP: " + (message.header.status == memc.constants.status.NO_ERROR?"OK":"FAIL"));
});
client.set(key, value, 0x01, 3600, function(message) {
if(message.header.status == memc.constants.status.NO_ERROR) {
console.log("SET: OK");
client.get(key, function(message) {
console.log("GET: " + message.body);
var stat = {};
client.stat(null, function(message) {
if(message.header.bodylen > 0) {
stat[message.key] = message.body;
}
else {
console.log("STAT:\n" + JSON.stringify(stat, null, "\t"));
client.delete(key, function(message) {
console.log("DELETE: " + (message.header.status == memc.constants.status.NO_ERROR?"OK":"FAIL"));
client.quit(function(message) {
console.log("QUIT: " + (message.header.status == memc.constants.status.NO_ERROR?"OK":"FAIL"));
});
});
}
});
});
}
else {
console.log("SET: Error = " + message.header.status);
client.quit(function(message) {
console.log("QUIT: " + (message.header.status == memc.constants.status.NO_ERROR?"OK":"FAIL"));
});
}
});
});
client.on("error", function(err) {
console.log("client error\n" + JSON.stringify(err, null, "\t"));
});
client.on("close", function() {
console.log("client closed");
});
|
var Bmp180 = require('./bmp180');
// Instantiate and initialize.
var sensor = new Bmp180({ debug: true });
function testRead() {
sensor.read(function(data) {
console.log(data);
});
}
(function test() {
testRead();
})();
|
define(function(require, exports, module) {
var api = require('./api');
var $login = $('#login');
$login.on('submit', function(event) {
event.preventDefault();
var email = $login[0]["loginEmail"].value;
var password = $login[0]["loginPass"].value;
api.login(email, password);
});
//promise chain
//get roles for this director
api.getDirectorRoles().then(function(data){
console.log("My Roles")
console.dir(data)
}).then(function(){
//get details for a single role
return api.getRoleDetail(563)
}).then(function(data){
console.log("Role Detail:")
console.dir(data);
}).then(function(){
//get auditions for a role
return api.getRoleAuditions(563)
}).then(function(data){
console.log("Role Auditions:")
console.dir(data);
});
});
|
import React from "react";
import List from "./List";
export default React.createClass({
getInitialState: function(){
return {
skateparks: []
}
},
justDoIt: function(e) {
e.preventDefault();
console.log("just do ittt");
var path = "https://skate-life-backend.herokuapp.com/api/skateparks"
var request = $.ajax({
url: path,
method: 'get',
dataType: 'json'
})
request.done(function(response){
console.log("aye")
console.log(response)
this.setState({
skateparks: response
})
}.bind(this))
request.fail(function(response){
console.log("well fuckkk")
})
},
render: function() {
if(this.state.skateparks.length === 0){
console.log("i'm empty on the inside")
var Content = <button onClick={this.justDoIt} >Login</button>
}
else{
console.log("fullllll")
var Content = <List parks={this.state.skateparks} />
}
return (
<div>
{Content}
</div>
);
},
});
|
var $util = {};
$util.cleanInfo = function(tree) {
var r = [];
tree = tree.slice(1);
tree.forEach(function(e) {
r.push(Array.isArray(e) ? $util.cleanInfo(e) : e);
});
return r;
};
$util.treeToString = function(tree, level) {
var spaces = $util.dummySpaces(level),
level = level ? level : 0,
s = (level ? '\n' + spaces : '') + '[';
tree.forEach(function(e) {
s += (Array.isArray(e) ? $util.treeToString(e, level + 1) : e.f !== undefined ? $util.ircToString(e) : ('\'' + e.toString() + '\'')) + ', ';
});
return s.substr(0, s.length - 2) + ']';
};
$util.ircToString = function(o) {
return '{' + o.f + ',' + o.l + '}';
};
$util.dummySpaces = function(num) {
return ' '.substr(0, num * 2);
};
$util.printTree = function(tree) {
require('sys').print($util.treeToString(tree));
};
$util.statToString = function(stat) {
var s = '';
s += 'Total selector groups: ' + stat.totalSelectorGroups + '\n';
s += 'Total simple selectors: ' + stat.totalSimpleSelectors + '\n';
s += 'Total unique simple selectors: ' + stat.totalUniqueSimpleSelectors + '\n';
return s;
};
exports.cleanInfo = $util.cleanInfo;
exports.treeToString = $util.treeToString;
exports.printTree = $util.printTree;
exports.statToString = $util.statToString;
|
export function isEmpty(obj) {
return (
obj && // 👈 null and undefined check
Object.keys(obj).length === 0 &&
obj.constructor === Object
);
}
|
const ThermalPrinter = require("../node-thermal-printer").printer;
const Types = require("../node-thermal-printer").types;
let printer = new ThermalPrinter({
type: Types.EPSON,
interface: process.argv[2]
});
printer.println("MAXI CODE");
printer.maxiCode("4126565");
printer.newLine();
printer.newLine();
printer.println("CODE93");
printer.printBarcode("4126565");
printer.newLine();
printer.newLine();
printer.println("CODE128");
printer.code128("4126565", {
height: 50,
text: 1
});
printer.newLine();
printer.newLine();
printer.println("PDF417");
printer.pdf417("4126565");
printer.newLine();
printer.newLine();
printer.println("QR");
printer.printQR("4126565");
printer.cut();
printer.execute();
|
import get from 'lodash/get'
function rateLimit () {
return (req, res, next) => {
const timestamp = get(req, 'session.timestamp')
if (timestamp && Date.now() - timestamp < 3600000) {
res.status(429)
.send('Whoa, got a little excited there, did ya?')
return
}
next()
}
}
export default rateLimit
|
'use strict';
angular.module('reviews').controller('ReviewPaginationController', ['$scope', 'Reviews',
function ($scope, Reviews) {
$scope.searchIsCollapsed = true;
$scope.optionsItemsPage = [
{text : "15", value : "15"},
{text : "30", value : "30"},
{text : "45", value : "45"}
];
$scope.optionsOrder = [
{text : "Descendente", value : "asc"},
{text : "Ascendente", value : "desc"}
];
$scope.optionsStatus = [
{text : "Todos", value : ""},
{text : "Borrador", value : "draft"},
{text : "Publicado", value : "public"}
];
$scope.init = function(itemsPerPage){
$scope.pagedItems = [];
$scope.itemsPerPage = itemsPerPage;
$scope.currentPage = 1;
$scope.status = 'public';
$scope.order = 'desc';
$scope.find();
};
$scope.pageChanged = function () {
$scope.find();
};
$scope.find = function () {
var query = { page:$scope.currentPage,
itemsPerPage:$scope.itemsPerPage,
order:$scope.order,
status:$scope.status,
text:$scope.text
};
Reviews.query(query, function (data) {
$scope.pagedItems = data[0].reviews;
$scope.total = data[0].total;
});
};
}
]);
|
// Structured using the Object-Linked-To-Other-Objects (OLOO) principle
// describe by Kyle Simpson in his series 'You Don't Know JS
// 'this & Object Prototypes', Chaper 5
const stackNode = {
data: null,
next: null,
initialize( data ) {
this.data = data;
}
};
module.exports = stackNode;
|
'use strict';
angular.module('d3')
.controller('d3Controller',[]);
|
import url from 'url';
import sortedObject from './sortedObject';
const parseHref = href => {
const {query} = url.parse(href, true);
return {query, href: url.format({query})};
};
const merge = (oldParams, newParams) => {
const query = sortedObject({...oldParams.query, ...newParams.query});
const href = url.format({query});
return {query, href};
};
/**
* Naive implementation
* Just checks if url will be changed, if not, then this url is active.
* TODO: Optimize speed by not rendering href to compare
*
* @param {Object} oldParams Effectively, current URL state
* @param {Object} newParams What we will have if follow the link
* @returns {boolean} isActive
*/
const isActive = (oldParams, newParams) => {
const oldHref = url.format(oldParams);
const {href} = merge(oldParams, newParams);
return oldHref === href;
};
export default {parseHref, merge, isActive};
|
module.exports = {
name: "sync3",
ns: "group",
async: true,
description: "Synchronizes group items on 3 different ports",
phrases: {
active: "Synchronizing items"
},
ports: {
input: {
in1: {
title: "In 1",
type: "any",
fn: function __IN1__(data, source, state, input, $, output, chix_group) {
var r = function() {
state.sync.add('out1', $.get('in1'))
}.call(this);
return {
state: state,
return: r
};
}
},
in2: {
title: "In 2",
type: "any",
fn: function __IN2__(data, source, state, input, $, output, chix_group) {
var r = function() {
state.sync.add('out2', $.get('in2'))
}.call(this);
return {
state: state,
return: r
};
}
},
in3: {
title: "In 3",
type: "any",
fn: function __IN3__(data, source, state, input, $, output, chix_group) {
var r = function() {
state.sync.add('out3', $.get('in3'))
}.call(this);
return {
state: state,
return: r
};
}
},
xin: {
title: "In Group",
type: "object",
fn: function __XIN__(data, source, state, input, $, output, chix_group) {
var r = function() {
state.$ = $
state.sync.receive($.get('xin'))
}.call(this);
return {
state: state,
return: r
};
}
}
},
output: {
out1: {
title: "Out 1",
type: "any"
},
out2: {
title: "Out 2",
type: "any"
},
out3: {
title: "Out 3",
type: "any"
}
}
},
dependencies: {
npm: {
"chix-group": require('chix-group')
}
},
state: {},
on: {
start: function __ONSTART__(data, source, state, input, $, output, chix_group) {
var r = function() {
state.sync = chix_group.sync.create(['out1', 'out2', 'out3'])
state.sync.on('sync', function(itemId, set) {
var $ = state.$
var out = {}
Object.keys(set).forEach(function(port) {
out[port] = $.create(set[port])
})
output(out)
})
}.call(this);
return {
state: state,
return: r
};
}
}
}
|
/*
* Sequence class
*/
// create a new Sequence
function Sequence( ac, tempo, arr ) {
this.ac = ac || new AudioContext();
this.createFxNodes();
this.tempo = tempo || 120;
this.loop = true;
this.smoothing = 0;
this.staccato = 0;
this.notes = [];
this.push.apply( this, arr || [] );
}
// create gain and EQ nodes, then connect 'em
Sequence.prototype.createFxNodes = function() {
var eq = [ [ 'bass', 100 ], [ 'mid', 1000 ], [ 'treble', 2500 ] ],
prev = this.gain = this.ac.createGain();
eq.forEach(function( config, filter ) {
filter = this[ config[ 0 ] ] = this.ac.createBiquadFilter();
filter.type = 'peaking';
filter.frequency.value = config[ 1 ];
prev.connect( prev = filter );
}.bind( this ));
prev.connect( this.ac.destination );
return this;
};
// accepts Note instances or strings (e.g. 'A4 e')
Sequence.prototype.push = function() {
Array.prototype.forEach.call( arguments, function( note ) {
this.notes.push( note instanceof Note ? note : new Note( note ) );
}.bind( this ));
return this;
};
// create a custom waveform as opposed to "sawtooth", "triangle", etc
Sequence.prototype.createCustomWave = function( real, imag ) {
// Allow user to specify only one array and dupe it for imag.
if ( !imag ) {
imag = real;
}
// Wave type must be custom to apply period wave.
this.waveType = 'custom';
// Reset customWave
this.customWave = [ new Float32Array( real ), new Float32Array( imag ) ];
};
// recreate the oscillator node (happens on every play)
Sequence.prototype.createOscillator = function() {
this.stop();
this.osc = this.ac.createOscillator();
// customWave should be an array of Float32Arrays. The more elements in
// each Float32Array, the dirtier (saw-like) the wave is
if ( this.customWave ) {
this.osc.setPeriodicWave(
this.ac.createPeriodicWave.apply( this.ac, this.customWave )
);
} else {
this.osc.type = this.waveType || 'square';
}
this.osc.connect( this.gain );
return this;
};
// schedules this.notes[ index ] to play at the given time
// returns an AudioContext timestamp of when the note will *end*
Sequence.prototype.scheduleNote = function( index, when ) {
var duration = 60 / this.tempo * this.notes[ index ].duration,
cutoff = duration * ( 1 - ( this.staccato || 0 ) );
this.setFrequency( this.notes[ index ].frequency, when );
if ( this.smoothing && this.notes[ index ].frequency ) {
this.slide( index, when, cutoff );
}
this.setFrequency( 0, when + cutoff );
return when + duration;
};
// get the next note
Sequence.prototype.getNextNote = function( index ) {
return this.notes[ index < this.notes.length - 1 ? index + 1 : 0 ];
};
// how long do we wait before beginning the slide? (in seconds)
Sequence.prototype.getSlideStartDelay = function( duration ) {
return duration - Math.min( duration, 60 / this.tempo * this.smoothing );
};
// slide the note at <index> into the next note at the given time,
// and apply staccato effect if needed
Sequence.prototype.slide = function( index, when, cutoff ) {
var next = this.getNextNote( index ),
start = this.getSlideStartDelay( cutoff );
this.setFrequency( this.notes[ index ].frequency, when + start );
this.rampFrequency( next.frequency, when + cutoff );
return this;
};
// set frequency at time
Sequence.prototype.setFrequency = function( freq, when ) {
this.osc.frequency.setValueAtTime( freq, when );
return this;
};
// ramp to frequency at time
Sequence.prototype.rampFrequency = function( freq, when ) {
this.osc.frequency.linearRampToValueAtTime( freq, when );
return this;
};
// run through all notes in the sequence and schedule them
Sequence.prototype.play = function( when ) {
when = typeof when === 'number' ? when : this.ac.currentTime;
this.createOscillator();
this.osc.start( when );
this.notes.forEach(function( note, i ) {
when = this.scheduleNote( i, when );
}.bind( this ));
this.osc.stop( when );
this.osc.onended = this.loop ? this.play.bind( this, when ) : null;
return this;
};
// stop playback, null out the oscillator, cancel parameter automation
Sequence.prototype.stop = function() {
if ( this.osc ) {
this.osc.onended = null;
this.osc.disconnect();
this.osc = null;
}
return this;
};
|
/**
* OnObjectObserve
* @class OnObjectObserve
* @param {Object} o Observed object
* @return {OnObjectObserve}
*/
function OnObjectObserve(o){
var self = this;
var _observer = function(changes){
self._ee.emit.call(self._ee, 'change', changes);
}
Object.observe(o, _observer);
/**
* EventEmitter object
* @private
* @type {EventEmitter}
*/
this._ee = new EventEmitter();
/**
* observer
* @private
* @type {function}
*/
this._observer = _observer;
}
OnObjectObserve.prototype = {
deliverChangeRecords : deliverChangeRecords,
on : on,
off : off
}
/**
* excute Object.deliverChangeRecords(...)
* @method OnObjectObserve.prototype.deliverChangeRecords
* @example
* var o = { a: 'a' }
* var ooo = new OnObjectObserve(o);
* ooo.on(function(){
* console.log('change!!');
* });
* ooo.on(function(changes){
* console.log(JSON.stringify(changes));
* });
* o.a = 'b';
* ooo.deliverChangeRecords();
* console.log('set b')
* // return
* // [{"type":"update","object":{"a":"b"},"name":"a","oldValue":"a"}]
* // change!!
* // set b
*/
function deliverChangeRecords(){
Object.deliverChangeRecords(this._observer);
}
/**
* on
* @method OnObjectObserve.prototype.on
* @example
* var o = { a: 'a' }
* var ooo = new OnObjectObserve(o);
* ooo.on(function(){
* console.log('change!!');
* });
* ooo.on(function(changes){
* console.log(JSON.stringify(changes));
* });
* o.a = 'b';
* console.log('set b')
* // return
* // set b
* // [{"type":"update","object":{"a":"b"},"name":"a","oldValue":"a"}]
* // change!!
*/
function on(callback){
this._ee.on.call(this._ee, 'change', callback);
}
/**
* off
* @method OnObjectObserve.prototype.off
* @example
* var o = { a: 'a' }
* var ooo = new OnObjectObserve(o);
* ooo.on(function(){
* console.log('change!!');
* });
* ooo.on(function(changes){
* console.log(JSON.stringify(changes));
* });
* o.a = 'b';
* ooo.deliverChangeRecords();
* ooo.off();
* o.a = 'c';
* // return
* // [{"type":"update","object":{"a":"b"},"name":"a","oldValue":"a"}]
* // change!!
* @example
* var o = { a: 'a' }
* var ooo = new OnObjectObserve(o);
* ooo.on(function(){
* console.log('change!!');
* });
* ooo.on(function(changes){
* console.log(JSON.stringify(changes));
* });
* o.a = 'b';
* ooo.deliverChangeRecords();
* o.a = 'c';
* // return
* // [{"type":"update","object":{"a":"b"},"name":"a","oldValue":"a"}]
* // change!!
* // [{"type":"update","object":{"a":"c"},"name":"a","oldValue":"b"}]
* // change!!
*/
function off(){
this._ee.removeEvent.call(this._ee, 'change');
}
|
/*global VIS, view, d3 */
"use strict";
view.about = function (info) {
if (!VIS.ready.about) {
if (info.meta_info) {
d3.select("div#meta_info")
.html(info.meta_info);
}
VIS.ready.about = true;
}
return true;
};
|
'use strict';
module.exports = function (opts) {
opts = opts || {};
var regex = '(?:[A-Za-z0-9+\/]{4}\\n?)*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)';
return opts.exact ? new RegExp('(?:^' + regex + '$)') :
new RegExp(regex, 'g');
};
|
export const GET_INCIDENTS = 'GET_INCIDENTS';
export const APPROVE_INCIDENT = 'APPROVE_INCIDENT';
export const REJECT_INCIDENT = 'REJECT_INCIDENT';
export const INCIDENTS_LODADED = 'INCIDENTS_LODADED';
export const APPROVED_INCIDENTS_LODADED = 'APPROVED_INCIDENTS_LODADED';
export const REJECTED_INCIDENTS_LODADED = 'REJECTED_INCIDENTS_LODADED';
export const PENDING_INCIDENTS_LODADED = 'PENDING_INCIDENTS_LODADED';
export const SET_COUNTY = 'SET_COUNTY';
export const SET_ACTIVE_MAP = 'SET_ACTIVE_MAP';
export const FILTER = 'FILTER';
export const FILTERS_LODADED = 'FILTERS_LODADED';
export const SET_TYPE = 'SET_TYPE';
export const RESET_COUNTY = 'RESET_COUNTY';
export const RESET_FILTERS = 'RESET_FILTERS';
export const APPROVED = 'Approved';
export const REJECTED = 'Rejected';
export const PENDING = 'Pending';
|
// Dependencies
var gulp = require('gulp');
var gutil = require('gulp-util');
var jscs = require('gulp-jscs');
var jshint = require('gulp-jshint');
var runSequence = require('run-sequence');
var webpack = require('webpack');
var webpackStream = require('webpack-stream');
var WebpackDevServer = require('webpack-dev-server');
var webpackConfig = require('./webpack.config.js');
/**
* Lints the config files
*/
gulp.task('lint:config', function(){
return gulp.src('./gulpfile.js')
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(jshint.reporter('fail'));
});
/**
* Lints lib js
*/
gulp.task('lint:lib', function(){
return gulp.src([
'lib/*.js'
])
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(jshint.reporter('fail'));
});
/**
* Runs style check on config files
*/
gulp.task('jscs:config', function(){
return gulp.src('./gulpfile.js')
.pipe(jscs({
configPath : '.jscsrc',
fix : true
}))
.pipe(gulp.dest('./'));
});
/**
* Runs style check on lib js
*/
gulp.task('jscs:lib', function(){
return gulp.src([
'lib/*.js'
])
.pipe(jscs({
configPath : '.jscsrc',
fix : true
}))
.pipe(gulp.dest('lib'));
});
/**
* Builds the module
*/
gulp.task('webpack', function(){
return gulp.src('lib/spark.js')
.pipe(webpackStream(webpackConfig))
.pipe(gulp.dest('dist/'));
});
/**
* Runs the webpack dev server for live testing
*/
gulp.task('dev', function(){
var myConfig = Object.create(webpackConfig);
myConfig.devtool = 'eval';
myConfig.debug = true;
new WebpackDevServer(webpack(myConfig), {
contentBase : __dirname + '/lib',
stats : {
colors : true
}
}).listen(8889, 'localhost', function(err){
if (err) {
throw new gutil.PluginError('webpack-dev-server', err);
}
// Server listening
gutil.log('[webpack-dev-server]', 'http://localhost:8889/index.html');
});
});
/**
* Task to run all lint subtasks
*/
gulp.task('lint', ['lint:config', 'lint:lib', 'jscs:config', 'jscs:lib']);
/**
* Default gulp task
*/
gulp.task('default', function(callback){
runSequence('lint', 'webpack', callback);
});
|
import ThLarge from 'react-icons/lib/fa/th-large'
export default ThLarge
|
(function () {
'use strict';
angular.module('com.module.roles', []);
})();
|
/**
* @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config ) {
// Define changes to default configuration here.
// For complete reference see:
// http://docs.ckeditor.com/#!/api/CKEDITOR.config
// The toolbar groups arrangement, optimized for two toolbar rows.
config.toolbarGroups = [
{ name: 'styles' },
{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
{ name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
{ name: 'links' },
{ name: 'insert' }
];
config.skin = 'icy_orange';
// Remove some buttons provided by the standard plugins, which are
// not needed in the Standard(s) toolbar.
config.removeButtons = 'Anchor';
// Set the most common block elements.
config.format_tags = 'p;h1;h2;h3;h4;h5;h6;pre';
// Simplify the dialog windows.
config.removeDialogTabs = 'image:advanced;link:advanced';
// Iframe title text
config.title = false;
};
|
// Padd Trek specific extensions
define(function() {
return function() {
CanvasRenderingContext2D.prototype.drawPanel = function (x, y, width, height) {
this.fillStyle = "rgba(0,0,0,0.6)";
this.fillRect(x, y, width, height);
this.strokeStyle = "white";
this.strokeRect(
x + this.lineWidth/2,
y + this.lineWidth/2,
x + width - this.lineWidth,
y + height - this.lineWidth);
}
};
});
|
/**
*/
//
export class Pencil {
// create Pencil.js instance
// [[ CanvasRenderingContext2D ]]
constructor(context2d) {
this.ctx = context2d;
}
// clear whole frame
// [[ ]]
clear() {
this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
}
// draw image to the canvas
// [[ image, sx, sy, sw, sh, dx, dy, dw, dh, rad ]]
drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh, rad) {
this.ctx.globalAlpha = 1;
if (rad === 0) {
this.ctx.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh);
}
else {
this.ctx.save();
this.ctx.translate(dx + dw/2, dy + dh/2);
this.ctx.rotate(rad);
this.ctx.drawImage(image, sx, sy, sw, sh, -(dw/2), -(dh/2), dw, dh);
this.ctx.restore();
}
}
// complete path started with beginPath with a fill
// [[ color ]]
fill(c) {
if (c !== undefined)
this.ctx.fillStyle = c;
this.ctx.fill();
}
// complete path started with beginPath with a stroke
// [[ color ]]
stroke(c) {
if (c !== undefined)
this.ctx.strokeStyle = c;
this.ctx.stroke();
}
_getDrawMethod(m) {
switch (m) {
case 'stroke': return this.stroke.bind(this);
case 'fill': return this.fill.bind(this);
default: {
console.error(`'${m}' is not a valid Pencil drawing method`);
return this.fill;
}
}
}
draw(m, c, a=1) {
this.ctx.globalAlpha = a;
this._getDrawMethod(m)(c);
}
// integration for geometry.js
// [[ shape, mode, color ]]
drawShape(s, m, c) {
switch (s.__proto__.constructor.name) {
case 'Point': {
this.drawRect(s.x, s.y, 1, 1, c, m);
break;
}
case 'Circle': {
this.ctx.beginPath();
this.ctx.arc(s.x, s.y, s.r, 0, Math.PI * 2);
this.draw(m,c);
break;
}
case 'Line': {
this.ctx.beginPath();
this.ctx.moveTo(s.pt1.x, s.pt1.y);
this.ctx.lineTo(s.pt2.x, s.pt2.y);
this.draw(m,c);
break;
}
case 'Rectangle':
case 'Square': {
this.drawRect(s.x, s.y, s.width, s.height, m, c);
break;
}
case 'Polygon': {
this.drawPolygon(s.pts, m, c);
break;
}
}
}
// draw an array of Points
// [[ Array<Point>, mode, color ]]
drawPolygon(pts, m, c) {
this.ctx.beginPath();
this.ctx.moveTo(pts[0].x, pts[0].y);
pts.forEach((v) => {
this.ctx.lineTo(v.x, v.y);
});
this.ctx.lineTo(pts[0].x, pts[0].y);
this.draw(m,c);
}
// draw a rectangle
// [[ x, y, width, height, mode, color, alpha ]]
drawRect(x, y, w, h, m, c, a) {
this.ctx.beginPath();
this.ctx.rect(x,y,w,h);
this.draw(m,c,a);
}
// draw Text
// [[ x, y, mode, text, color, font ]]
drawText(x, y, m, t, c, f) {
if (c !== undefined)
this.ctx[`${m}Style`] = c;
if (f !== undefined)
this.ctx.font = f;
this.ctx[`${m}Text`](t, x, y);
}
}
|
import UIComponent from './UIComponent';
import { debounce, extend } from 'lib/util';
export default function DecoratorPanel(spec, def) {
let self = new UIComponent(spec, def);
let { game, debug, ui } = spec;
let { padding=UIComponent.DEFAULT_PADDING } = def;
let bgSprite = spec.game.add.image(0,0,'core','paneBackground');
self.add(bgSprite);
if (def.onClicked) {
self.inputEnabled=true;
self.onInputUp.add(debounce(def.onClicked,UIComponent.INPUTEVENT_DEBOUNCE_INTERVAL,true));
}
extend(self, {
reflowChildren() {
let target = self.childComponents[0];
if (target) target.reflow(getChildRect());
},
});
function updateSize() {
let target = self.childComponents[0];
if (!target) return;
if (def.stretchHorizontally) {
bgSprite.width = (self.fixedToCamera ? game.width : self.parentGroup.width);
} else {
bgSprite.width = target.width + 2*padding;
}
if (def.stretchVertically) {
bgSprite.height = (self.fixedToCamera ? game.height : self.parentGroup.height);
} else {
bgSprite.height = target.height + 2*padding;
}
self.onResized.dispatch();
}
function getChildRect() {
return new Phaser.Rectangle(padding,
padding,
self.width-2*padding,
self.height-2*padding);
}
if (def.stretchHorizontally || def.stretchVertically) {
ui.onResize.add(()=>updateSize());
}
self.onChildResized.add(()=> {
self.reflowChildren();
updateSize();
});
return self;
}
|
export default {
user: {
isAuthenticated : false,
},
contacts: [],
contact: {},
};
|
import React, {Component} from 'react'
import {DragDropContext} from 'react-dnd'
import HTML5Backend from 'react-dnd-html5-backend'
import Page from './Page'
import CustomDragLayer from './DragAndDropComponents/CustomDragLayer'
class Canvas extends Component {
constructor() {
super()
this.handleSnapToGridAfterDropChange = this.handleSnapToGridAfterDropChange.bind(this)
this.handleSnapToGridWhileDraggingChange = this.handleSnapToGridWhileDraggingChange.bind(this)
this.handleDeleteMode = this.handleDeleteMode.bind(this)
this.state = {
snapToGridAfterDrop: false,
snapToGridWhileDragging: false,
deleteMode: false,
}
}
handleSnapToGridAfterDropChange() {
this.setState({
snapToGridAfterDrop: !this.state.snapToGridAfterDrop,
})
}
handleSnapToGridWhileDraggingChange() {
this.setState({
snapToGridWhileDragging: !this.state.snapToGridWhileDragging,
})
}
handleDeleteMode () {
this.setState({
deleteMode: !this.state.deleteMode,
})
}
render() {
const { snapToGridAfterDrop, snapToGridWhileDragging, deleteMode } = this.state;
return (
<div>
<Page
snapToGrid={snapToGridAfterDrop}
selectElement={this.props.selectElement}
deleteMode={deleteMode}
editable={this.props.editable}
clearSelectedIfDeleted={this.props.clearSelectedIfDeleted}
/>
{this.props.editable ?
(<div id="drag-canvas">
<CustomDragLayer snapToGrid={snapToGridWhileDragging} />
<p>
<label htmlFor="snapToGridWhileDragging">
<input
id="snapToGridWhileDragging"
type="checkbox"
checked={snapToGridWhileDragging}
onChange={this.handleSnapToGridWhileDraggingChange}
/>
<small>Snap to grid while dragging</small>
</label>
<br />
<label htmlFor="snapToGridAfterDrop">
<input
id="snapToGridAfterDrop"
type="checkbox"
checked={snapToGridAfterDrop}
onChange={this.handleSnapToGridAfterDropChange}
/>
<small>Snap to grid after drop</small>
</label>
<br />
<label htmlFor="deleteMode">
<input
id="deleteMode"
type="checkbox"
checked={deleteMode}
onChange={this.handleDeleteMode}
/>
<small id="deleteCheckbox">Delete mode</small>
</label>
</p>
</div>)
: null}
</div>
);
}
}
export default DragDropContext(HTML5Backend)(Canvas)
|
Package.describe({
"summary": "meteor new relic integration",
"name": "alex509:newrelic",
"version": "1.0.5",
"author": "Alexey Kuznetsov (https://github.com/Alex509)",
"homepage": "https://github.com/Alex509/meteor-newrelic",
"git": "https://github.com/Alex509/meteor-newrelic.git"
});
Npm.depends({
"newrelic": "2.3.0",
"@newrelic/native-metrics": "2.1.2",
"cls-fibers": "1.1.1",
"fibers": "2.0.0"
});
Package.on_use(function(api) {
api.versionsFrom("[email protected]");
if (api.export)
api.export('newrelic', 'server');
api.add_files('lib/server.js', 'server');
});
|
//////////////////////////////////////////////////////////////////
//
// Fortune Cookie Generator
//
//////////////////////////////////////////
function generateFortuneCookie() {
var randomFortune = Math.floor(Math.random()*fortunesList.length);
document.getElementById("fortune-cookie-text").innerHTML = (fortunesList[randomFortune]);
var createNew = document.createElement("li");
createNew.innerHTML = (fortunesList[randomFortune]);
document.getElementById("previous-fortunes-container").appendChild(createNew);
}
// This is where your code for the Fortune Cookie generator goes.
// You will use the fortunesList variable defined lower in this file
// to supply your fortune cookies with text.
// TODO: Grab the paragraph with the ID
// `fortune-cookie-text` to be able to insert text into that element.
// TODO: Update the Previous Fortunes list with the current `innerHTML`
// value of `#fortune-cookie-text`. Follow these steps:
// 1. Create a new `li` element with the `document.createElement()` method.
// 2. Set the `innerHTML` of that element equal to the `innerHTML` of
// the `#fortune-cookie-text` element.
// 3. Select the `#previous-fortunes-container` container and use
// `appendChild()` to append the new `li` element you created above.
// 4. You should see the previous fortune cookie saying show up in the list.
// TODO: Select a new (random) fortune cookie saying from the data stored in the
// `fortunesList` variable. (HINT: You will use `Math.floor()` and
// `Math.random()` to accomplish this.) Use this data to update the
// `innerText` of the `#fortune-cookie-text` element.
// The following data list is provided for you to use in your code.
var fortunesList = Array(
"People are naturally attracted to you.",
"You learn from your mistakes... You will learn a lot today.",
"If you have something good in your life, don't let it go!",
"What ever you're goal is in life, embrace it visualize it, and for it will be yours.",
"Your shoes will make you happy today.",
"You cannot love life until you live the life you love.",
"Be on the lookout for coming events; They cast their shadows beforehand.",
"Land is always on the mind of a flying bird.",
"The man or woman you desire feels the same about you.",
"Meeting adversity well is the source of your strength.",
"A dream you have will come true.",
"Our deeds determine us, as much as we determine our deeds.",
"Never give up. You're not a failure if you don't give up.",
"You will become great if you believe in yourself.",
"There is no greater pleasure than seeing your loved ones prosper.",
"You will marry your lover.",
"The greatest love is self-love.",
"A very attractive person has a message for you.",
"You already know the answer to the questions lingering inside your head.",
"It is now, and in this world, that we must live.",
"You must try, or hate yourself for not trying.",
"You can make your own happiness.",
"The greatest risk is not taking one.",
"The love of your life is stepping into your planet this summer.",
"Love can last a lifetime, if you want it to.",
"Adversity is the parent of virtue.",
"Serious trouble will bypass you.",
"A short stranger will soon enter your life with blessings to share.",
"Now is the time to try something new.",
"Wealth awaits you very soon.",
"If you feel you are right, stand firmly by your convictions.",
"If winter comes, can spring be far behind?",
"Keep your eye out for someone special.",
"You are very talented in many ways.",
"A stranger, is a friend you have not spoken to yet.",
"A new voyage will fill your life with untold memories.",
"You will travel to many exotic places in your lifetime.",
"Your ability for accomplishment will follow with success.",
"Nothing astonishes men so much as common sense and plain dealing.",
"Its amazing how much good you can do if you dont care who gets the credit.",
"Everyone agrees. You are the best.",
"LIFE CONSISTS NOT IN HOLDING GOOD CARDS, BUT IN PLAYING THOSE YOU HOLD WELL.",
"Jealousy doesn't open doors, it closes them!",
"It's better to be alone sometimes.",
"When fear hurts you, conquer it and defeat it!",
"Let the deeds speak.",
"You will be called in to fulfill a position of high honor and responsibility.",
"The man on the top of the mountain did not fall there.",
"You will conquer obstacles to achieve success.",
"Joys are often the shadows, cast by sorrows.",
"Fortune favors the brave.");
|
import React from "react";
import ChangePasswordController from "./ChangePasswordController";
import user from "../../utilities/api-clients/user";
import { mount } from "enzyme";
jest.mock("../../utilities/notifications.js", () => {
return {
add: function () {
// do nothing
},
};
});
jest.mock("../../utilities/log.js", () => {
return {
add: function () {
// do nothing
},
};
});
jest.mock("../../utilities/api-clients/user", () => {
return {
updatePassword: jest
.fn(() => {
return Promise.resolve();
})
.mockImplementationOnce(() => {
return Promise.reject({ status: 500 });
}),
};
});
const formEvent = {
preventDefault: () => {},
};
const passwordToShort = {
value: "test",
errorMsg: "Passwords must contain four words, separated by spaces",
};
const notValidPassPhrase = {
value: "notaValidPassPhrase",
errorMsg: "Passwords must contain four words, separated by spaces",
};
const props = {
email: "[email protected]",
currentPassword: "testPassword",
handleSuccess: function () {},
handleCancel: function () {},
};
const mockEvent = {
target: {
id: "new-password",
value: "updated password",
},
};
test("handleSubmit checks length of new password and displays error", async () => {
const component = mount(<ChangePasswordController {...props} />);
component.setState({ newPassword: { value: "test", errorMsg: "" } });
await component.instance().handleSubmit(formEvent);
expect(component.state("newPassword")).toMatchObject(passwordToShort);
});
test("handleSubmit checks if new password is a valid pass phrase and displays error", async () => {
const component = mount(<ChangePasswordController {...props} />);
component.setState({ newPassword: { value: "notaValidPassPhrase", errorMsg: "" } });
await component.instance().handleSubmit(formEvent);
expect(component.state("newPassword")).toMatchObject(notValidPassPhrase);
});
test("handleSubmit posts if no validation errors", async () => {
const component = mount(<ChangePasswordController {...props} />);
component.setState({ newPassword: { value: "a valid pass phrase", errorMsg: "" } });
await component.instance().handleSubmit(formEvent);
expect(user.updatePassword.mock.calls.length).toBe(1);
});
test("handleInputChange updates state", async () => {
const component = mount(<ChangePasswordController {...props} />);
expect(component.state("newPassword")).toEqual({ value: "", errorMsg: "" });
await component.instance().handleInputChange(mockEvent);
expect(component.state("newPassword")).toEqual({ value: "updated password", errorMsg: "" });
});
|
import JInput from './JInput';
export default JInput;
|
// All code points in the Variation Selectors Supplement block as per Unicode v10.0.0:
[
0xE0100,
0xE0101,
0xE0102,
0xE0103,
0xE0104,
0xE0105,
0xE0106,
0xE0107,
0xE0108,
0xE0109,
0xE010A,
0xE010B,
0xE010C,
0xE010D,
0xE010E,
0xE010F,
0xE0110,
0xE0111,
0xE0112,
0xE0113,
0xE0114,
0xE0115,
0xE0116,
0xE0117,
0xE0118,
0xE0119,
0xE011A,
0xE011B,
0xE011C,
0xE011D,
0xE011E,
0xE011F,
0xE0120,
0xE0121,
0xE0122,
0xE0123,
0xE0124,
0xE0125,
0xE0126,
0xE0127,
0xE0128,
0xE0129,
0xE012A,
0xE012B,
0xE012C,
0xE012D,
0xE012E,
0xE012F,
0xE0130,
0xE0131,
0xE0132,
0xE0133,
0xE0134,
0xE0135,
0xE0136,
0xE0137,
0xE0138,
0xE0139,
0xE013A,
0xE013B,
0xE013C,
0xE013D,
0xE013E,
0xE013F,
0xE0140,
0xE0141,
0xE0142,
0xE0143,
0xE0144,
0xE0145,
0xE0146,
0xE0147,
0xE0148,
0xE0149,
0xE014A,
0xE014B,
0xE014C,
0xE014D,
0xE014E,
0xE014F,
0xE0150,
0xE0151,
0xE0152,
0xE0153,
0xE0154,
0xE0155,
0xE0156,
0xE0157,
0xE0158,
0xE0159,
0xE015A,
0xE015B,
0xE015C,
0xE015D,
0xE015E,
0xE015F,
0xE0160,
0xE0161,
0xE0162,
0xE0163,
0xE0164,
0xE0165,
0xE0166,
0xE0167,
0xE0168,
0xE0169,
0xE016A,
0xE016B,
0xE016C,
0xE016D,
0xE016E,
0xE016F,
0xE0170,
0xE0171,
0xE0172,
0xE0173,
0xE0174,
0xE0175,
0xE0176,
0xE0177,
0xE0178,
0xE0179,
0xE017A,
0xE017B,
0xE017C,
0xE017D,
0xE017E,
0xE017F,
0xE0180,
0xE0181,
0xE0182,
0xE0183,
0xE0184,
0xE0185,
0xE0186,
0xE0187,
0xE0188,
0xE0189,
0xE018A,
0xE018B,
0xE018C,
0xE018D,
0xE018E,
0xE018F,
0xE0190,
0xE0191,
0xE0192,
0xE0193,
0xE0194,
0xE0195,
0xE0196,
0xE0197,
0xE0198,
0xE0199,
0xE019A,
0xE019B,
0xE019C,
0xE019D,
0xE019E,
0xE019F,
0xE01A0,
0xE01A1,
0xE01A2,
0xE01A3,
0xE01A4,
0xE01A5,
0xE01A6,
0xE01A7,
0xE01A8,
0xE01A9,
0xE01AA,
0xE01AB,
0xE01AC,
0xE01AD,
0xE01AE,
0xE01AF,
0xE01B0,
0xE01B1,
0xE01B2,
0xE01B3,
0xE01B4,
0xE01B5,
0xE01B6,
0xE01B7,
0xE01B8,
0xE01B9,
0xE01BA,
0xE01BB,
0xE01BC,
0xE01BD,
0xE01BE,
0xE01BF,
0xE01C0,
0xE01C1,
0xE01C2,
0xE01C3,
0xE01C4,
0xE01C5,
0xE01C6,
0xE01C7,
0xE01C8,
0xE01C9,
0xE01CA,
0xE01CB,
0xE01CC,
0xE01CD,
0xE01CE,
0xE01CF,
0xE01D0,
0xE01D1,
0xE01D2,
0xE01D3,
0xE01D4,
0xE01D5,
0xE01D6,
0xE01D7,
0xE01D8,
0xE01D9,
0xE01DA,
0xE01DB,
0xE01DC,
0xE01DD,
0xE01DE,
0xE01DF,
0xE01E0,
0xE01E1,
0xE01E2,
0xE01E3,
0xE01E4,
0xE01E5,
0xE01E6,
0xE01E7,
0xE01E8,
0xE01E9,
0xE01EA,
0xE01EB,
0xE01EC,
0xE01ED,
0xE01EE,
0xE01EF
];
|
/**
* Created by yunzhou on 20/11/2016.
*/
import React from 'react';
const CheckboxInput = (props) => <input
id={props.id}
type="checkbox"
name={props.name}
placeholder={props.placeholder}
value={props.value}
onChange={props.onChange}
onBlur={props.onBlur}
>
</input>;
CheckboxInput.propTypes = {
id: React.PropTypes.any,
name: React.PropTypes.any,
placeholder: React.PropTypes.any,
value: React.PropTypes.any,
onChange: React.PropTypes.any,
onBlur: React.PropTypes.any,
};
export default CheckboxInput;
|
var ActorDBClient = require('./actordb_client');
var EventEmitter = require("events").EventEmitter;
var util = require('util');
function ActorDBPool( connect_params, pool_params ) {
var self = this;
EventEmitter.call(this);
self.config = connect_params;
self.pool_size = pool_params['pool_size'];
self.pool = [ ];
self.next_client = 0;
self.connected = false;
}
util.inherits(ActorDBPool, EventEmitter);
ActorDBPool.prototype.connect = function(callback) {
var self = this;
if(typeof callback != 'function') {
return new Promise(function(resolve, reject) {
self.connect(function(err,ok){
if(err) return reject(err);
resolve(ok);
})
});
}
if (self.connected) { callback({error:'Pool already connected'},null); return; }
self.connected = true;
for (i=0; i < self.pool_size; i++) {
var adbc = new ActorDBClient(self.config);
self.pool[i] = adbc;
adbc.connect();
}
callback(null,true);
}
ActorDBPool.prototype.db = function() {
var self = this;
if (!self.connected) return null;
self.next_client = (self.next_client + 1) % self.pool_size;
client = self.pool[self.next_client];
return client;
}
ActorDBPool.prototype.close = function() {
var self = this;
for (i=0; i<self.pool[i];i++) {
adbc = self.pool[i];
adbc.close();
}
self.connected = false;
}
module.exports = ActorDBPool;
|
var requiresRegex = /^(?:\s*)--(?:\s*)requires:(?:\s*)([^\s]+)/gmi;
export
default
function extractDepsFromSource(sqlSource) {
return new Promise((fulfill, reject) => {
var result = [];
try {
var m;
while ((m = requiresRegex.exec(sqlSource)) !== null) {
if (m.index === requiresRegex.lastIndex) {
requiresRegex.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
result.push(m[1]);
}
} catch (e) {
reject(e);
}
fulfill(result);
});
}
|
var isLuhn = require('../')
var test = require('tape')
test('should return true for a valid credit card number', function (t) {
var expected = true
var cc = isLuhn('4111111111111111')
t.equal(cc, expected)
t.end()
})
test('should return false for a invalid credit card number', function (t) {
var expected = false
var cc = isLuhn('1111111111111111')
t.equal(cc, expected)
t.end()
})
test('should return undefined if an empty string is provided as a param', function (t) {
var cc = isLuhn('')
t.equal(cc, undefined)
t.end()
})
test('should return undefined if no param is not provided', function (t) {
var cc = isLuhn()
t.equal(cc, undefined)
t.end()
})
|
module.exports = getAnswerDetail;
const saferman = require('saferman');
function getAnswerDetail(ID,callback){
let sql = saferman.format(
`SELECT QUESTION.title,QUESTION.description,ANSWER.answer,USER.username
FROM ANSWER,QUESTION,USER
WHERE ANSWER.ID=? AND
QUESTION.ID = ANSWER.questionID AND
USER.ID = ANSWER.authorID
LIMIT 1`,
[ID]);
saferman.sql(sql,function(results){
executeCallback(results[0]);
});
function executeCallback(argumentOfCallback){
if(callback!=undefined)
callback(argumentOfCallback);
}
}
|
var mapnik = require('mapnik');
var assert = require('assert');
var xtend = require('xtend');
var ShelfPack = require('shelf-pack');
var queue = require('queue-async');
var emptyPNG = new mapnik.Image(1, 1).encodeSync('png');
function heightAscThanNameComparator(a, b) {
return (b.height - a.height) || ((a.id === b.id) ? 0 : (a.id < b.id ? -1 : 1));
};
/**
* Pack a list of images with width and height into a sprite layout.
* Uses shelf-pack.
* @param {Array<Object>} imgs array of `{ buffer: Buffer, id: String }`
* @param {number} pixelRatio ratio of a 72dpi screen pixel to the destination
* pixel density
* @return {Object} layout
* @param {Function} callback
*/
function generateLayout(imgs, pixelRatio, format, callback) {
return generateLayoutInternal(imgs, pixelRatio, format, false, callback);
}
/**
* Same as generateLayout but can be used to dedupe identical SVGs
* and still preserve the reference.
* For example if A.svg and B.svg are identical, a single icon
* will be in the sprite image and both A and B will reference the same image
*/
function generateLayoutUnique(imgs, pixelRatio, format, callback) {
return generateLayoutInternal(imgs, pixelRatio, format, true, callback);
}
function generateLayoutInternal(imgs, pixelRatio, format, unique, callback) {
assert(typeof pixelRatio === 'number' && Array.isArray(imgs));
if (unique) {
/* If 2 items are pointing to identical buffers (svg icons)
* create a single image in the sprite but have all ids point to it
* Remove duplicates from imgs, but if format == true then when creating the
* resulting layout, make sure all item that had the same signature
* of an item are also updated with the same layout information.
*/
/* The svg signature of each item */
var svgPerItemId = {}
/* The items for each SVG signature */
var itemIdsPerSvg = {};
imgs.forEach(function(item) {
var svg = item.svg.toString('base64');
svgPerItemId[item.id] = svg;
if (svg in itemIdsPerSvg) {
itemIdsPerSvg[svg].push(item.id);
} else {
itemIdsPerSvg[svg] = [item.id];
}
});
/* Only keep 1 item per svg signature for packing */
imgs = imgs.filter(function(item) {
var svg = svgPerItemId[item.id];
return item.id === itemIdsPerSvg[svg][0]
});
}
function createImagesWithSize(img, callback) {
if (typeof(img.ext) !== 'undefined' && img.ext === 'png') {
createImageFromPng(img, callback);
} else {
createImageFromSvg(img, callback);
}
}
function createImageFromSvg(img, callback) {
mapnik.Image.fromSVGBytes(img.svg, { scale: pixelRatio }, function(err, image) {
if (err) return callback(err);
image.encode('png', function(err, buffer) {
if (err) return callback(err);
callback(null, xtend(img, {
width: image.width(),
height: image.height(),
buffer: buffer
}));
});
});
}
function createImageFromPng(img, callback) {
mapnik.Image.fromBytes(img.svg, function(err, image) {
if (err) return callback(err);
image.encode('png', function(err, buffer) {
if (err) return callback(err);
callback(null, xtend(img, {
width: image.width(),
height: image.height(),
buffer: buffer
}));
});
});
}
var q = new queue();
imgs.forEach(function(img) {
q.defer(createImagesWithSize, img);
});
q.awaitAll(function(err, imagesWithSizes){
if (err) return callback(err);
imagesWithSizes.sort(heightAscThanNameComparator);
var sprite = new ShelfPack(1, 1, { autoResize: true });
sprite.pack(imagesWithSizes, { inPlace: true });
if (format) {
var obj = {};
imagesWithSizes.forEach(function(item) {
var itemIdsToUpdate = [item.id];
if (unique) {
var svg = svgPerItemId[item.id];
itemIdsToUpdate = itemIdsPerSvg[svg];
}
itemIdsToUpdate.forEach(function(itemIdToUpdate) {
obj[itemIdToUpdate] = {
width: item.width,
height: item.height,
x: item.x,
y: item.y,
pixelRatio: pixelRatio
};
});
});
return callback(null, obj);
} else {
return callback(null, {
width: sprite.w,
height: sprite.h,
items: imagesWithSizes
});
}
});
}
module.exports.generateLayout = generateLayout;
module.exports.generateLayoutUnique = generateLayoutUnique;
/**
* Generate a PNG image with positioned icons on a sprite.
* @param {Object} packing
* @param {Function} callback
*/
function generateImage(packing, callback) {
assert(typeof packing === 'object' && typeof callback === 'function');
if (!packing.items.length) return callback(null, emptyPNG);
mapnik.blend(packing.items, {
width: packing.width,
height: packing.height
}, callback);
}
module.exports.generateImage = generateImage;
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.4.4.19-4-7
description: >
Array.prototype.map throws TypeError if callbackfn is Object
without Call internal method
includes: [runTestCase.js]
---*/
function testcase() {
var arr = new Array(10);
try {
arr.map(new Object());
}
catch(e) {
if(e instanceof TypeError)
return true;
}
}
runTestCase(testcase);
|
'use strict';
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const AppDirectory = require('appdirectory');
const dirs = new AppDirectory('miio');
const CHECK_TIME = 1000;
const MAX_STALE_TIME = 120000;
const debug = require('debug')('miio:tokens');
/**
* Shared storage for tokens of devices. Keeps a simple JSON file synced
* with tokens connected to device ids.
*/
class Tokens {
constructor() {
this._file = path.join(dirs.userData(), 'tokens.json');
this._data = {};
this._lastSync = 0;
}
get(deviceId) {
const now = Date.now();
const diff = now - this._lastSync;
if(diff > CHECK_TIME) {
return this._loadAndGet(deviceId);
}
return Promise.resolve(this._get(deviceId));
}
_get(deviceId) {
return this._data[deviceId];
}
_loadAndGet(deviceId) {
return this._load()
.then(() => this._get(deviceId))
.catch(() => null);
}
_load() {
if(this._loading) return this._loading;
return this._loading = new Promise((resolve, reject) => {
debug('Loading token storage from', this._file);
fs.stat(this._file, (err, stat) => {
if(err) {
delete this._loading;
if(err.code === 'ENOENT') {
debug('Token storage does not exist');
this._lastSync = Date.now();
resolve(this._data);
} else {
reject(err);
}
return;
}
if(! stat.isFile()) {
// tokens.json does not exist
delete this._loading;
reject(new Error('tokens.json exists but is not a file'));
} else if(Date.now() - this._lastSync > MAX_STALE_TIME || stat.mtime.getTime() > this._lastSync) {
debug('Loading tokens');
fs.readFile(this._file, (err, result) => {
this._data = JSON.parse(result.toString());
this._lastSync = Date.now();
delete this._loading;
resolve(this._data);
});
} else {
delete this._loading;
this._lastSync = Date.now();
resolve(this._data);
}
});
});
}
update(deviceId, token) {
return this._load()
.then(() => {
this._data[deviceId] = token;
if(this._saving) {
this._dirty = true;
return this._saving;
}
return this._saving = new Promise((resolve, reject) => {
const save = () => {
debug('About to save tokens');
fs.writeFile(this._file, JSON.stringify(this._data, null, 2), (err) => {
if(err) {
reject(err);
} else {
if(this._dirty) {
debug('Redoing save due to multiple updates');
this._dirty = false;
save();
} else {
delete this._saving;
resolve();
}
}
});
};
mkdirp(dirs.userData(), (err) => {
if(err) {
reject(err);
return;
}
save();
});
});
});
}
}
module.exports = new Tokens();
|
import { Schema, arrayOf, normalize } from 'normalizr';
import URLSearchParams from 'url-search-params';
import fetch from 'isomorphic-fetch';
import moment from 'moment-timezone';
import { deepMapValues } from 'lodash-deep';
function appendParamsToUrl(url, params) {
if (params !== null && typeof params === 'object') {
const qs = Object.keys(params)
.reduce((p, key) => {
p.append(key, params[key]);
return p;
}, new URLSearchParams())
.toString();
return `${url}?${qs}`;
}
return url;
}
function apiEndpoint(endpoint, params) {
const url = (endpoint.indexOf(__API_ROOT__) === -1)
? __API_ROOT__ + endpoint
: endpoint;
return appendParamsToUrl(url, params);
}
// Fetches an API response and normalizes the result JSON according to schema.
// This makes every API response have the same shape, regardless of how nested it was.
function callApi(endpoint, config, params = null, schema, transformations) {
const fullUrl = apiEndpoint(endpoint, params);
return fetch(fullUrl, config || {})
.then((response) =>
response.json().then((json) => ({ json, response }))
).then(({ json, response }) => {
if (!response.ok) {
return Promise.reject(json);
} else if (json.error) {
return Promise.reject(json.error);
}
const transformed = transformations ? transformations(json) : json;
const normalized = schema ? normalize(transformed, schema) : transformed;
return normalized;
}).then(
(response) => ({response}),
(error) => ({error: error.message || 'Something bad happened'})
);
}
function get(endpoint, params, schema, transformations) {
return callApi(endpoint, {}, params, schema, transformations);
}
function put(endpoint, data, schema, transformations) {
const config = {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
};
return callApi(endpoint, config, null, schema, transformations);
}
function post(endpoint, data, schema, transformations) {
const config = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
};
return callApi(endpoint, config, null, schema, transformations);
}
function del(endpoint, schema, transformations) {
const config = {
method: 'DELETE',
headers: {
'Accept': 'application/json'
}
};
return callApi(endpoint, config, null, schema, transformations);
}
const makeDates = (timezone) => (json) => {
return deepMapValues(json, (value, propertyPath) => {
if (propertyPath.join('.').endsWith('Date')) {
return moment.tz(value, timezone);
}
return value;
});
};
const eventSchema = new Schema('events', {idAttribute: 'id'});
const eventsSchema = { events: arrayOf(eventSchema) };
// all previous requests should be canceled to prevent
export function fetchEvents(params) {
const newParams = {
startDate: params.startDate.toISOString(),
endDate: params.endDate.toISOString(),
timezone: params.timezone
};
return get('/events', newParams, eventsSchema, makeDates(params.timezone));
}
export function updateEvent(event, timezone) {
const data = {...event, timezone: timezone};
return put(`/events/${event.id}`, data, null, makeDates(timezone));
}
export function insertEvent(event, timezone) {
const data = {...event, timezone: timezone};
return post('/events', data, null, makeDates(timezone));
}
export function deleteEvent(id) {
return del(`/events/${id}`);
}
|
/* globals it, describe */
var fs = require('fs')
var should = require('should')
var gutil = require('gulp-util')
var standard = require('../')
require('mocha')
var testFile1 = fs.readFileSync('test/fixtures/testFile1.js')
describe('gulp-standard', function () {
it('should lint files', function (done) {
var stream = standard()
var fakeFile = new gutil.File({
base: 'test/fixtures',
cwd: 'test/',
path: 'test/fixtures/testFile1.js',
contents: testFile1
})
stream.once('data', function (newFile) {
should.exist(newFile)
should.exist(newFile.standard)
should(newFile.standard.results[0].messages[0].message).equal("Expected '===' and instead saw '=='.")
done()
})
stream.write(fakeFile)
stream.end()
})
})
|
// 1. 定义(路由)组件。
// 可以从其他文件 import 进来
const Foo = {template: '<div>foo</div>'}
const Bar = {template: '<div>bar</div>'}
const routes = [
{path: '/foo', component: Foo},
{path: '/bar', component: Bar}
];
const router = new VueRouter({
routes // (缩写)相当于 routes: routes
});
new Vue({
router
}).$mount('#app');
|
/**
* This module activates on a Kitchen Sink page, and changes how code examples are rendered.
* The code example is hidden, and can be revealed with a toggle.
*/
!function() {
var $ks = $('#docs-kitchen-sink');
if (!$ks.length) return;
$ks.find('[data-ks-codepen]').each(function() {
var $codepen = $(this);
var $code = $codepen.next('[data-docs-code]');
$link = $('<a class="docs-code-toggle">Toggle Code</a>');
$link.on('click.docs', function() {
$codepen.slideToggle(250);
$code.slideToggle(250);
});
$link.insertBefore(this);
$code.addClass('kitchen-sink').hide(0);
$codepen.addClass('kitchen-sink').hide(0);
});
}();
|
'use strict';
//////////////////////////////
// Requires
//////////////////////////////
var jshint = require('gulp-jshint'),
stylish = require('jshint-stylish'),
paths = require('compass-options').paths(),
browserSync = require('browser-sync'),
reload = browserSync.reload;
//////////////////////////////
// Internal Vars
//////////////////////////////
var toLint = [
paths.js + '/**/*.js',
'!' + paths.js + '/**/*.min.js'
];
module.exports = function (gulp, lintPaths) {
gulp.task('jshint', function () {
lintPaths = lintPaths || toLint;
return gulp.src(lintPaths)
.pipe(jshint())
.pipe(jshint.reporter(stylish))
.pipe(reload({stream: true}));
});
gulp.task('jshint:watch', function () {
lintPaths = lintPaths || toLint;
gulp.watch(lintPaths, ['jshint']);
});
}
|
/**
* Created by tdoe on 5/10/14.
*/
|
gs.include('SnowLib.AWS.Requester.Request');
describe("SnowLib.AWS.Requester.Request", function() {
var mockProperties = {
'snowlib.aws.region' : 'us-east-1',
'snowlib.aws.secret_key' : 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY',
'snowlib.aws.access_key' : 'AKIDEXAMPLE'
};
var mockPropGetter = {
getProperty : function(name) {
return mockProperties[name];
}
};
describe("instance constructed with minimum GET params plus x-amz-date", function() {
var awsr = new SnowLib.AWS.Requester.Request({
// method : 'GET',
// region : 'us-east-1',
service : 'iam',
// path : '/',
query : {
'Action' : 'ListUsers',
'Version' : '2010-05-08'
},
headers : {
'Host' : 'iam.amazonaws.com',
// 'Content-Type' : 'application/x-www-form-urlencoded; charset=utf-8',
// X-Amz-Date is NOT a 'mimimum' parameter, but is supplied in order to pass test expectations
'X-Amz-Date' : '20150830T123600Z'
}
}, mockPropGetter);
var rmv2 = awsr.getSignedRestMessageV2();
it("has correct endpoint URL", function() {
expect(rmv2.getEndpoint()).toBe('https://iam.amazonaws.com/');
})
it("has correct headers", function() {
expect(rmv2.getRequestHeaders()).toEqual({
'Host' : 'iam.amazonaws.com',
'Content-Type' : 'application/x-www-form-urlencoded; charset=utf-8',
'X-Amz-Date' : '20150830T123600Z',
'Authorization' : 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/us-east-1/iam/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=5d672d79c15b13162d9279b0855cfba6789a8edb4c82c400e06b5924a6f2b5d7'
});
});
});
describe("instance created with minimum POST params plus x-amz-date", function() {
it("has correct HTTP body", function() {
var awsr = new SnowLib.AWS.Requester.Request({
method : 'POST',
service : 'iam',
headers : {
'Host' : 'iam.amazonaws.com',
// X-Amz-Date is NOT a 'mimimum' parameter, but is supplied in order to pass test expectations
'X-Amz-Date' : '20150830T123600Z'
},
payloadParams : {
'PlatformApplicationArn' : 'arn:aws:sns:us-west-2:025606354027:app/APNS_SANDBOX/AmazonMobilePush',
'Action' : 'CreatePlatformEndpoint',
'SignatureMethod' : 'HmacSHA256',
'CustomUserData' : 'UserId%3D27576823',
'AWSAccessKeyId' : 'AKIDEXAMPLE',
'Token' : '395a6f7bf0e87a3f26cbd2e817f12811cd10ca4593d0d9cc7a114c25241949d8'
}
}, mockPropGetter);
var rmv2 = awsr.getSignedRestMessageV2();
expect(rmv2.getRequestBody()).toEqual(
'AWSAccessKeyId=AKIDEXAMPLE' +
'&Action=CreatePlatformEndpoint' +
'&CustomUserData=UserId%253D27576823' +
'&PlatformApplicationArn=arn%3Aaws%3Asns%3Aus-west-2%3A025606354027%3Aapp%2FAPNS_SANDBOX%2FAmazonMobilePush' +
'&SignatureMethod=HmacSHA256' +
'&Token=395a6f7bf0e87a3f26cbd2e817f12811cd10ca4593d0d9cc7a114c25241949d8'
);
});
});
});
|
export {default as hmenu} from "./menu.vue";
export {default as msg} from "./msg.vue";
|
'use strict';
module.exports = function transform(fn) {
var _this = this;
if (Array.isArray(this.items)) {
this.items = this.items.map(fn);
} else {
var collection = {};
Object.keys(this.items).forEach(function (key) {
collection[key] = fn(_this.items[key], key);
});
this.items = collection;
}
};
|
// Define a `maxExtent` to include the "zoom to max extent" button
var panZoom = new olpz.control.PanZoom({
imgPath: './resources/ol2img',
maxExtent: [813079, 5929220, 848966, 5936863]
});
var map = new ol.Map({
controls: ol.control.defaults({
zoom: false
}).extend([
panZoom
]),
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map',
view: new ol.View({
center: ol.proj.transform([-70, 50], 'EPSG:4326', 'EPSG:3857'),
zoom: 5
})
});
|
import { getStrings } from '../../lib/helpers'
import express from 'express'
const router = express.Router()
router.get('/', (req, res) => {
if (req.isAuthenticated()) {
res.redirect('/apply')
} else {
const strings = getStrings().signin
strings.hideSignIn = true
res.render('signin', strings)
}
})
export default router
|
import bluebird from 'bluebird'
import decodeBinary from './utils/data3d/decode-binary.js'
import encodeBinary from './utils/data3d/encode-binary.js'
import loadData3d from './utils/data3d/load.js'
import traverseData3d from './utils/data3d/traverse.js'
import cloneData3d from './utils/data3d/clone.js'
import getData3dFromThreeJs from './utils/data3d/from-three.js'
import getData3dInspectorUrl from './utils/data3d/get-inspector-url.js'
import storeInCache from './utils/data3d/store-in-cache.js'
import removeFromCache from './utils/data3d/remove-from-cache.js'
import textureAttributes from './utils/data3d/texture-attributes.js'
import normalizeData3d from './utils/data3d/normalize.js'
import ui from './utils/ui.js'
import auth from './utils/auth.js'
import fetch from './utils/io/fetch.js'
import fetchScript from './utils/io/fetch-script.js'
import checkIfFileExists from './utils/io/check-if-file-exists.js'
import getBlobFromCanvas from './utils/image/get-blob-from-canvas.js'
import getImageFromFile from './utils/image/get-image-from-file.js'
import scaleDownImage from './utils/image/scale-down-image.js'
import md5 from './utils/math/md5.js'
import sha1 from './utils/math/sha1.js'
import getMimeTypeFromFilename from './utils/file/get-mime-type-from-filename.js'
import gzip from './utils/file/gzip.js'
import readFile from './utils/file/read.js'
import getMd5FileHash from './utils/file/get-md5-hash.js'
import uuid from './utils/uuid.js'
import getShortId from './utils/short-id.js'
import url from './utils/url.js'
import path from './utils/path.js'
import wait from './utils/wait.js'
import callService from './utils/services/call.js'
import whenDone from './utils/processing/when-done.js'
import whenHiResTexturesReady from './utils/processing/when-hi-res-textures-ready.js'
var utils = {
data3d: {
load: loadData3d,
encodeBinary: encodeBinary,
decodeBinary: decodeBinary,
fromThreeJs: getData3dFromThreeJs,
normalize: normalizeData3d,
clone: cloneData3d,
traverse: traverseData3d,
getInspectorUrl: getData3dInspectorUrl,
storeInCache: storeInCache,
removeFromCache: removeFromCache,
textureAttributes: textureAttributes
},
ui: ui,
auth: auth,
io: {
fetch: fetch,
fetchScript: fetchScript,
checkIfFileExists: checkIfFileExists
},
image: {
scaleDown: scaleDownImage,
getFromFile: getImageFromFile,
getBlobFromCanvas: getBlobFromCanvas
},
math: {
md5: md5,
sha1: sha1
},
services: {
call: callService
},
file: {
getMimeTypeFromFilename: getMimeTypeFromFilename,
gzip: gzip,
read: readFile,
getMd5Hash: getMd5FileHash
},
processing: {
whenDone: whenDone,
whenHiResTexturesReady: whenHiResTexturesReady
},
url: url,
uuid: uuid,
getShortId: getShortId,
path: path,
wait: wait,
bluebird: bluebird
}
export default utils
|
const UUID = require('uuid');
const { ParityDel, ParityRelock } = require('./scripts');
module.exports = function (redis) {
const warlock = {};
const parityDel = ParityDel(redis);
const parityRelock = ParityRelock(redis);
warlock.makeKey = function (key) {
return `${key}:lock`;
};
/**
* Set a lock key
* @param {string} key Name for the lock key. String please.
* @param {integer} ttl Time in milliseconds for the lock to live.
* @param {Function} cb
*/
warlock.lock = function (key, ttl, cb) {
cb = cb || function () {};
if (typeof key !== 'string') {
return cb(new Error('lock key must be string'));
}
let id;
UUID.v1(null, (id = new Buffer(16)));
id = id.toString('base64');
redis.set(
warlock.makeKey(key), id,
'PX', ttl, 'NX',
(err, lockSet) => {
if (err) return cb(err);
const unlock = lockSet ? warlock.unlock.bind(warlock, key, id) : false;
return cb(err, unlock, id);
},
);
return key;
};
warlock.unlock = async (key, id, cb) => {
cb = cb || function () {};
if (typeof key !== 'string') {
return cb(new Error('lock key must be string'));
}
const numKeys = 1;
const _key = warlock.makeKey(key);
try {
const result = await parityDel(numKeys, _key, id);
cb(null, result);
} catch (e) {
cb(e);
}
};
/**
* Set a lock optimistically (retries until reaching maxAttempts).
*/
warlock.optimistic = function (key, ttl, maxAttempts, wait, cb) {
let attempts = 0;
var tryLock = function () {
attempts += 1;
warlock.lock(key, ttl, (err, unlock) => {
if (err) return cb(err);
if (typeof unlock !== 'function') {
if (attempts >= maxAttempts) {
const e = new Error('unable to obtain lock');
e.maxAttempts = maxAttempts;
e.key = key;
e.ttl = ttl;
e.wait = wait;
return cb(e);
}
return setTimeout(tryLock, wait);
}
return cb(err, unlock);
});
};
tryLock();
};
warlock.touch = async (key, id, ttl, cb) => {
if (typeof key !== 'string') {
const e = new Error('lock key must be string');
e.id = id;
e.key = key;
e.ttl = ttl;
if (!cb) throw e;
return cb(e);
}
try {
const result = await parityRelock(3, warlock.makeKey(key), ttl, id);
return cb ? cb(null, result) : result;
} catch (e) {
if (!cb) throw e;
return cb(e);
}
};
return warlock;
};
|
/* eslint-disable */
import { createStore, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './application/modules/reducer';
import createLogger from 'redux-logger';
import request from './application/helpers/request';
const thunkMiddleware = thunk.withExtraArgument(request);
function configureStoreProd(initialState) {
const middlewares = [thunkMiddleware];
return createStore(
rootReducer,
initialState,
compose(applyMiddleware(...middlewares)),
);
}
const logger = createLogger();
const composeWithDevToolsExtension = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__;
function configureStoreDev(initialState) {
const middlewares = [thunkMiddleware, logger];
return createStore(
rootReducer,
initialState,
composeWithDevToolsExtension(
applyMiddleware(...middlewares),
),
);
}
const configureStore = process.env.NODE_ENV === 'production' ? configureStoreProd : configureStoreDev;
export default configureStore;
|
'use strict';
module.exports = {
app: {
title: 'DC - Developer Portfolio',
description: '',
keywords: 'cv, portfolio'
},
port: process.env.PORT || 3001,
templateEngine: 'swig',
// The secret should be set to a non-guessable string that
// is used to compute a session hash
sessionSecret: 'o9i8u7y6t5r4e',
// The name of the MongoDB collection to store sessions in
sessionCollection: 'sessions',
// The session cookie settings
sessionCookie: {
path: '/',
httpOnly: true,
// If secure is set to true then it will cause the cookie to be set
// only when SSL-enabled (HTTPS) is used, and otherwise it won't
// set a cookie. 'true' is recommended yet it requires the above
// mentioned pre-requisite.
secure: false,
// Only set the maxAge to null if the cookie shouldn't be expired
// at all. The cookie will expunge when the browser is closed.
maxAge: null,
// To set the cookie in a specific domain uncomment the following
// setting:
// domain: 'yourdomain.com'
},
// The session cookie name
sessionName: 'connect.sid',
log: {
// Can specify one of 'combined', 'common', 'dev', 'short', 'tiny'
format: 'combined',
// Stream defaults to process.stdout
// Uncomment to enable logging to a log on the file system
options: {
stream: 'access.log'
}
},
assets: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.css',
'public/lib/bootstrap/dist/css/bootstrap-theme.css',
'public/lib/font-awesome/css/font-awesome.css',
'//fonts.googleapis.com/css?family=Abel',
'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.8.0/styles/monokai_sublime.min.css'
],
js: [
'public/lib/jquery/dist/jquery.min.js',
'public/lib/angular/angular.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-ui-router/release/angular-ui-router.js',
'public/lib/angular-ui-utils/ui-utils.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
'//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.8.0/highlight.min.js'
]
},
css: [
'public/modules/**/css/*.css'
],
js: [
'public/config.js',
'public/application.js',
'public/modules/*/*.js',
'public/modules/*/*[!tests]*/*.js'
],
tests: [
'public/lib/angular-mocks/angular-mocks.js',
'public/modules/*/tests/*.js'
]
}
};
|
var app = app || {};
(function(){
var LoginWindow = app.LoginWindow;
var RegisterWindow = app.RegisterWindow;
var AccountPage = React.createClass({displayName: "AccountPage",
getInitialState:function(){
return {isRegister:false,username:'', password:'', repassword:''};
},
hanldeSwitch:function(){
this.setState({isRegister:!this.state.isRegister,username:'', password:'', repassword:''});
},
handleLogin:function(){
if(this.state.username.length == 0 || this.state.password.length == 0){
$('.login-area').shake(5,10,100);
app.showMsg('Please input username and password')
}else{
var post_data = {
'username':this.state.username,
'password':this.state.password
};
$.ajax({
url:'http://localhost:8000/account/login',
type:'POST',
data:JSON.stringify(post_data),
dataType:'json',
cache:false,
success:function(data){
if (data.isSuccessful){
$.cookie('fhir_token', data.token, { expires: 1, path: '/' });
window.location.href = '/dashboard.html';
}else{
$('.login-area').shake(5,10,100);
app.showMsg(data.error);
}
}
});
}
},
handleRegister:function(){
if(this.state.username.length == 0 || this.state.password.length == 0 || this.state.password != this.state.repassword){
$('.register-area').shake(5,10,100);
app.showMsg('Please input username and password');
}else{
var post_data = {
'username':this.state.username,
'password':this.state.password
};
console.log('re')
$.ajax({
url:'http://localhost:8000/account/register',
type:'POST',
data:JSON.stringify(post_data),
dataType:'json',
cache:false,
success:function(data){
if (data.isSuccessful){
app.showMsg('User created, please login');
}else{
$('.register-area').shake(5,10,100);
app.showMsg(data.error);
}
}
});
}
},
updateUsername:function(new_username){
this.setState({username:new_username});
},
updatePassword:function(new_password){
this.setState({password:new_password});
},
updateRepassword:function(new_repassword){
this.setState({repassword:new_repassword});
},
render:function(){
return (
React.createElement("div", {className: "index-content"},
React.createElement("h2", null, this.state.isRegister ? 'Create FHIR Tester Account' : 'Sign in to FHIR Tester'),
this.state.isRegister ? React.createElement(RegisterWindow, {register_action: this.handleRegister, updateUsername: this.updateUsername, updatePassword: this.updatePassword, updateRepassword: this.updateRepassword}) : React.createElement(LoginWindow, {login_action: this.handleLogin, updateUsername: this.updateUsername, updatePassword: this.updatePassword}),
React.createElement("a", {className: "action-link", href: "javascript:void()", onClick: this.hanldeSwitch},
this.state.isRegister ? 'Sign in with an exist account' : 'Create a new account'
),
React.createElement("a", {href: "/dashboard.html"}, "Continue without account")
)
);
}
});
function render() {
ReactDOM.render(
React.createElement(AccountPage, null),
document.getElementById('main')
);
}
render();
})();
|
/**
* Copyright (C) 2020 tt.bot dev team
*
* This file is part of tt.bot.
*
* tt.bot is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* tt.bot is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with tt.bot. If not, see <http://www.gnu.org/licenses/>.
*/
"use strict";
const { MessageListener } = require("sosamba");
const config = require("../config");
const PHONE = "\u260e";
class PhoneMessageListener extends MessageListener {
constructor(sosamba) {
super(sosamba);
this.channels = new Map();
}
async die(meta) {
meta.caller.createMessage("You have hung up.");
meta.otherSide.createMessage("The other side has hung up.");
this.channels.delete(meta.otherSide.id);
this.channels.delete(meta.caller.id);
}
async run(ctx) {
const channel = this.channels.get(ctx.channel.id);
if (ctx.msg.content.startsWith(`${config.prefix}hangup`)) {
this.die(channel);
return;
} else {
const content = ctx.msg.content.slice(1);
if (content || ctx.msg.attachments.length !== 0) {
channel.otherSide.createMessage({
content: `${PHONE} ${this.sosamba.getTag(ctx.author)}: ${content || ""}\n${
ctx.msg.attachments.length !== 0 ? ctx.msg.attachments.map(a => a.url).join("\n") : ""
}`,
allowedMentions: {}
});
}
}
}
addChannels(caller, otherSide, callData, otherSideCallData) {
this.channels.set(caller.id, {
otherSide,
caller,
callData,
otherSideCallData
});
this.channels.set(otherSide.id, {
otherSide: caller,
caller: otherSide,
callData: otherSideCallData,
otherSideCallData: callData
});
caller.createMessage({
content: `${PHONE} Connected to ${otherSideCallData.id} ${
!otherSideCallData.private ?
`(#${otherSide.name} at ${otherSide.guild.name})`
: ""}\n\nPrefix your messages with \`^\` to send them over.\nType \`${config.prefix}hangup\` to hang up`,
allowedMentions: {}
});
otherSide.createMessage({
content: `${PHONE} Connected to ${callData.id} ${
!callData.private ?
`(#${caller.name} at ${caller.guild.name})`
: ""}\n\nPrefix your messages with \`^\` to send them over.\nType \`${config.prefix}hangup\` to hang up`,
allowedMentions: {}
});
}
async prerequisites(ctx) {
return this.channels.has(ctx.channel.id)
&& (ctx.msg.content.startsWith("^")
|| ctx.msg.content.startsWith(`${config.prefix}hangup`));
}
}
module.exports = PhoneMessageListener;
|
describe('Natural Negotatior', function() {
integration(function() {
describe('Natural Negotatior\'s ability', function() {
beforeEach(function () {
this.setupTest({
phase: 'conflict',
player1: {
inPlay: ['ide-tadaji', 'moto-youth'],
hand: ['natural-negotiator'],
honor: 10
},
player2: {
inPlay: ['bayushi-shoju'],
honor: 10
}
});
this.ideTadaji = this.player1.findCardByName('ide-tadaji');
this.motoYouth = this.player1.findCardByName('moto-youth');
this.naturalNegotiator = this.player1.findCardByName('natural-negotiator');
this.bayushiShoju = this.player2.findCardByName('bayushi-shoju');
this.noMoreActions();
this.initiateConflict({
type: 'military',
attackers: [this.ideTadaji, this.motoYouth],
defenders: [this.bayushiShoju]
});
});
it('should only be able to be attached to a corutier you control', function () {
this.player2.pass();
this.player1.clickCard(this.naturalNegotiator);
expect(this.player1).toBeAbleToSelect(this.ideTadaji);
expect(this.player1).not.toBeAbleToSelect(this.motoYouth);
expect(this.player1).not.toBeAbleToSelect(this.bayushiShoju);
});
it('should give the opponent 1 honor and switch the attached character\'s base skills', function () {
this.player2.pass();
this.player1.clickCard(this.naturalNegotiator);
this.player1.clickCard(this.ideTadaji);
this.player2.pass();
this.player1.clickCard(this.naturalNegotiator);
expect(this.player1.honor).toBe(9);
expect(this.player2.honor).toBe(11);
expect(this.ideTadaji.getMilitarySkill()).toBe(4);
expect(this.ideTadaji.getPoliticalSkill()).toBe(1);
expect(this.getChatLogs(10)).toContain('player1 uses Natural Negotiator, giving 1 honor to player2 to switch Ide Tadaji\'s base military and political skill');
});
});
});
});
|
// test
import test from 'ava';
// src
import instanceOf from 'src/instanceOf';
test('if instanceOf returns false if object is falsy', (t) => {
const object = null;
t.false(instanceOf(Object)(object));
});
test('if instanceOf tests for direct constructor', (t) => {
class Foo {}
const object = new Foo();
t.true(instanceOf(Foo)(object));
});
test('if instanceOf tests up the ancestry tree', (t) => {
class Foo {}
const object = new Foo();
t.true(instanceOf(Object)(object));
});
|
function changeCasings(text) {
var array;
while (true) {
array = text.match(/<mixcase>(.*?)<\/mixcase>/);
if (array === null) {
break;
}
var initialString = array[1].toString();
var mixCased = new String();
for (var i = 0; i < array[1].length; i++) {
var random = Math.random();
if (random < 0.5) {
mixCased += initialString[i].toUpperCase()
}
else {
mixCased += initialString[i].toLowerCase();;
}
}
text = text.replace(array[0].toString(), mixCased);
}
while (true) {
array = text.match(/<upcase>(.*?)<\/upcase>/);
if (array === null) {
break;
}
text = text.replace(array[0].toString(), array[1].toString().toUpperCase());
}
while (true) {
array = text.match(/<lowcase>(.*?)<\/lowcase>/);
if (array === null) {
break;
}
text = text.replace(array[0].toString(), array[1].toString().toLowerCase());
}
return text;
}
var text = 'We are <mixcase>living</mixcase> in a <upcase>yellow submarine</upcase>. We <mixcase>don\'t</mixcase> have <lowcase>ANYTHING</lowcase> else.';
console.log(changeCasings(text));
|
const lazyRequire = require('import-lazy')(require);
const ClientFunctionBuilder = lazyRequire('../../client-functions/client-function-builder');
const SelectorBuilder = lazyRequire('../../client-functions/selectors/selector-builder');
const role = lazyRequire('../../role');
const createRequestLogger = lazyRequire('../request-hooks/request-logger');
const createRequestMock = lazyRequire('../request-hooks/request-mock');
// NOTE: We can't use lazy require for RequestHook, because it will break base class detection for inherited classes
let RequestHook = null;
// NOTE: We can't use lazy require for testControllerProxy, because it will break test controller detection
let testControllerProxy = null;
function Role (loginPage, initFn, options) {
return role.createRole(loginPage, initFn, options);
}
function RequestMock () {
return createRequestMock();
}
function RequestLogger (requestFilterRuleInit, logOptions) {
return createRequestLogger(requestFilterRuleInit, logOptions);
}
function ClientFunction (fn, options) {
const builder = new ClientFunctionBuilder(fn, options, { instantiation: 'ClientFunction' });
return builder.getFunction();
}
function Selector (fn, options) {
const builder = new SelectorBuilder(fn, options, { instantiation: 'Selector' });
return builder.getFunction();
}
Object.defineProperty(Role, 'anonymous', {
get: () => role.createAnonymousRole
});
export default {
Role,
ClientFunction,
Selector,
RequestLogger,
RequestMock,
get RequestHook () {
if (!RequestHook)
RequestHook = require('../request-hooks/hook');
return RequestHook;
},
get t () {
if (!testControllerProxy)
testControllerProxy = require('../test-controller/proxy');
return testControllerProxy;
}
};
|
var keyMirror = require('keymirror');
module.exports = keyMirror({
OPEN_DOCUMENT: null,
SET_FOCUS: null,
ADD_PARTNER: null,
ADD_CHILD: null,
ADD_PARENTS: null,
ADD_TWIN: null,
DELETE_INDIVIDUAL: null,
UPDATE_INDIVIDUAL_FIELDS: null,
ADD_CUSTOM_INDIVIDUAL_FIELD: null,
DELETE_CUSTOM_INDIVIDUAL_FIELD: null,
UNDO: null,
REDO: null
});
|
(function(){
"use strict";
_gaq.push(['_trackPageview']);
// Document ready
$(document).on("ready", function(){
// Load previously stored configs
ConfigManager.load();
KC3Meta.init("../../data/");
KC3Translation.execute();
// Set HTML language
$("html").attr("lang", ConfigManager.language);
var sectionBox;
// Add configurable settings
//$.getJSON("../../data/translations/"+ConfigManager.language+"/settings.json", function(response){
$.getTranslationJSON(ConfigManager.language, 'settings', function(response){
for(var sctr in response){
// Add section header
sectionBox = $("#factory .section").clone().appendTo("#wrapper .settings");
$(".title", sectionBox).text( response[sctr].section );
// Learn more button
if(response[sctr].help!=""){
$("a", sectionBox).attr("href", response[sctr].help );
}else{
$("a", sectionBox).hide();
}
// Add settings boxes under this section
for(var cctr in response[sctr].contents){
new SettingsBox( response[sctr].contents[cctr] );
}
}
});
});
// Show one of the developers
function addDeveloper( info ){
var devBox = $("#factory .devBox").clone().appendTo("#wrapper .developers");
$(".devAvatar img", devBox).attr("src", info.avatar);
$(".devName", devBox).text( info.name );
$(".devDesc", devBox).text( info.desc );
var linkBox;
for(var code in info.links){
linkBox = $("#factory .devLink").clone();
$("a", linkBox).attr("href", info.links[code] );
$("img", linkBox).attr("src", "../../assets/img/social/"+code+".png");
$(".devLinks", devBox).append(linkBox);
}
}
})();
|
'use strict';
exports.__esModule = true;
exports.default = normalize;
function normalize(brainKey) {
if (typeof brainKey !== 'string') {
throw new Error("string required for brainKey");
}
brainKey = brainKey.trim();
return brainKey.split(/[\t\n\v\f\r ]+/).join(' ');
}
module.exports = exports['default'];
|
/*jslint node: true */ /*eslint-env node*/
'use strict';
var mongoose = require('./mongoose_app').mongoose,
Schema = mongoose.Schema,
ModelNodeModule = require('./modelNode'),
ModelNode = ModelNodeModule.ModelNode,
utilsModule = require('../misc/utils'),
utilsIsValidModelPath = utilsModule.isValidModelPath,
utilsGetTemplate = utilsModule.getTemplate,
modelUtilsModule = require('./model_utils'),
getSchemaOptions = modelUtilsModule.getSchemaOptions,
OPT_TIMESTAMP = modelUtilsModule.OPT_TIMESTAMP,
populateSubDocsUtil = modelUtilsModule.populateSubDocs,
AnswerModule = require('./answer'),
answerPopulateOptions = AnswerModule.getSubDocPopulateOptions,
UserModule = require('./user'),
userPopulateOptions = UserModule.getSubDocPopulateOptions,
userPopulateProjection = UserModule.getPopulateProjection,
PersonModule = require('./person'),
personPopulateOptions = PersonModule.getSubDocPopulateOptions,
AddressModule = require('./addresses'),
addressPopulateOptions = AddressModule.getSubDocPopulateOptions;
var schema = new Schema({
available: {
type: Boolean,
default: true
},
dontCanvass: {
type: Boolean,
default: false
},
tryAgain: {
type: Boolean,
default: false
},
support: {
type: Number,
default: -1
},
date: {
type: Date,
default: Date.now
},
answers: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Answer'
}],
canvasser: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
voter: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Person'
},
address: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Address'
}
}, getSchemaOptions(OPT_TIMESTAMP));
// create a model using schema
var model = mongoose.model('CanvassResult', schema);
var modelNode = new ModelNode(model, { populateSubDocs: populateSubDocs });
var modelTree = modelNode.getTree();
/**
* Generates a canvass result template object from the specified source
* @param {object} source - object with properties to extract
* @param {string[]} exPaths - array of other paths to exclude
*/
function getTemplate (source, exPaths) {
// set defaults for arguments not passed
if (!exPaths) {
// exclude object ref fields by default
exPaths = ['canvass', 'answers', 'canvasser', 'voter', 'address'];
}
return utilsGetTemplate(source, model, exPaths);
}
/**
* Check if a path is valid for this model
* @param {string} path - path to check
* @param {string[]} exPaths - array of paths to exclude
* @param {boolean} checkSub - check sub documents flag
* @returns false or ModelNode if valid path
*/
function isValidModelPath (path, exPaths, checkSub) {
checkSub = checkSub || false;
var modelNodes;
if (checkSub) {
modelNodes = modelTree;
} else {
modelNodes = modelNode;
}
return utilsIsValidModelPath(modelNodes, path, exPaths);
}
/**
* Get the subdocument populate options
* @returns an array of populate objects of the form:
* @param {string} path - path to subdocument
* @param {string} model - name of subdocument model
* @param {function} populate - function to populate subdocument
*/
function getSubDocPopulateOptions () {
return [
{ path: 'answers', model: 'Answer', populate: answerPopulateOptions() },
{ path: 'canvasser', model: 'User', populate: userPopulateOptions(), select: userPopulateProjection() },
{ path: 'voter', model: 'Person', populate: personPopulateOptions() },
{ path: 'address', model: 'Address', populate: addressPopulateOptions() }
];
}
/**
* Get the root of the ModelNode tree for this model
* @returns {object} root of ModelNode tree
*/
function getModelNodeTree () {
return modelNode;
}
/**
* Populate the subdocuments in a result set
* @param {Array} docs - documents to populate
* @param {function} next - next function
*/
function populateSubDocs (docs, next) {
populateSubDocsUtil(model, docs, getSubDocPopulateOptions(), next);
}
module.exports = {
schema: schema,
model: model,
getTemplate: getTemplate,
isValidModelPath: isValidModelPath,
getSubDocPopulateOptions: getSubDocPopulateOptions,
getModelNodeTree: getModelNodeTree,
populateSubDocs: populateSubDocs
};
|
var through = require('through2');
var fs = require('fs');
var Handlebars = require('handlebars');
var PluginError = require('gulp-util').PluginError;
module.exports = function(options) {
var template = fs.readFileSync(options.template, options.encoding);
var templateFn = Handlebars.compile(template);
return through.obj(function(file, enc, cb) {
if (file.isStream()) {
this.emit('error', new PluginError('content.yaml',
'Streams not supported!'));
return cb();
}
if (file.isBuffer()) {
file.data.contents = file.contents;
file.contents = new Buffer(templateFn(file.data));
}
return cb(null, file);
});
};
|
var debug = require('debug')('botkit:channel_join');
module.exports = function(controller) {
controller.on('bot_channel_join', function(bot, message) {
controller.studio.run(bot, 'channel_join', message.user, message.channel).catch(function(err) {
debug('Error: encountered an error loading onboarding script from Botkit Studio:', err);
});
});
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.