text
stringlengths 2
6.14k
|
|---|
// @flow
import type { Targets } from "@babel/helper-compilation-targets";
export const defaultWebIncludes = [
"web.timers",
"web.immediate",
"web.dom.iterable",
];
export default function(targets: Targets): null | string[] {
const targetNames = Object.keys(targets);
const isAnyTarget = !targetNames.length;
const isWebTarget = targetNames.some(name => name !== "node");
return isAnyTarget || isWebTarget ? defaultWebIncludes : null;
}
|
'use strict';
import config from '../../config';
import gulp from 'gulp';
import eslint from 'gulp-eslint';
import getSrcFiles from '../util/getSrcFiles';
export default function (src = config.scripts.src, options = {}, files = ['**/*.js', '!**/*.min.js']) {
return function() {
let srcFiles = getSrcFiles(src, files);
options = Object.assign({
fix: true
}, options);
return gulp.src(srcFiles, {
base: './'
})
.pipe(eslint(options))
.pipe(eslint.format())
.pipe(eslint.failAfterError())
.pipe(gulp.dest('.'));
};
}
|
// 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: 7.8.4-16-s
description: An OctalEscapeSequence is not allowed in a String under Strict Mode
flags: [onlyStrict]
includes: [runTestCase.js]
---*/
function testcase()
{
try
{
eval('"use strict"; var x = "\\400";');
return false;
}
catch (e) {
return (e instanceof SyntaxError);
}
}
runTestCase(testcase);
|
var path = require('path');
module.exports = function(config) {
config.set({
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// list of files / patterns to exclude
exclude: [],
browsers: ['PhantomJS'],
files: ['tests/**/*.spec.js'],
frameworks: ['jasmine'],
preprocessors: {
'tests/**/*.spec.js': ['webpack']
},
reporters: ['progress', 'coverage'],
coverageReporter: {
dir: 'coverage',
reporters: [
// reporters not supporting the `file` property
// { type: 'html', subdir: 'report-html' }, // fro dev
{ type: 'lcov', subdir: 'report-lcov' } // for coveralls
]
},
webpack: {
cache: true,
module: {
loaders: [
{
test: /(\.js)$/,
loader: 'babel-loader',
exclude: /(node_modules)/,
query: {
presets: ['env']
}
},
{
test: /\.spec.js$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
query: {
cacheDirectory: true,
presets: ['env']
}
},
{
// transpile and instrument only testing sources with isparta
test: /\.js$/,
include: path.resolve('src/'),
exclude: /(src\/vendor\/)/,
loader: 'isparta-loader'
}
]
}
},
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: true,
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
browserNoActivityTimeout: 200000,
browserDisconnectTolerance: 5
});
};
|
/**
* Serializes an HTML form into an application/x-www-form-urlencoded string.
*
* Example:
*
* var form = document.getElementById('update_product_1');
*
* var params = new Serializer();
* params.serialize(form);
* params.append('_method', 'put');
*
* var xhr = new XMLHttpRequest();
* xhr.open('POST', form);
* xhr.send(params.toString());
*
* IMPROVE: use selectedOptions for <select multiple/>
*/
Alpha.Serializer = function() {
this.data = '';
}
Alpha.Serializer.prototype.serialize = function(form)
{
var inputs = form.querySelectorAll('input,select,textarea');
Array.prototype.forEach.call(inputs, function(input)
{
if (!input.name
|| input.disabled
|| input.type == 'file'
|| (input.type == 'checkbox' && !input.checked)
|| (input.type == 'submit' && !input.hasAttribute('submitted')))
{
return;
}
if (input.type == 'select' && input.multiple)
{
for (var i=0, len=this.selectedOptions.length; i<len; i++) {
this.append(input.name, this.selectedOptions[i].value);
}
}
else {
this.append(input.name, input.value);
}
}, this);
}
Alpha.Serializer.prototype.append = function(key, value)
{
if (value !== null) {
this.data += (this.data ? '&' : '') + encodeURIComponent(key) + '=' + encodeURIComponent(value);
}
}
Alpha.Serializer.prototype.toString = function() {
return this.data;
}
|
/* eslint-disable class-methods-use-this */
const util = require('util');
const validator = require('express-validator');
const { APIError } = require('./error');
const ValidatorAPI = require('./validators');
class BaseCtrl {
/**
* Derived class must implement this one
* static get CLASSINFO() {}
*
* The following fields are supported:
*
* METHOD: HTTP method for the API. If not present, default method (POST) is used.
* INFO: Class description.
* VERSION: API version, optional.
* NAME: URL for the API, unless URL exists. This field can be used
* at the client side to resolve backend URLs.
* URL: URL for the API, if not present NAME field is used.
* URLPREFIX: URL prefix for the API.
* AUTHENTICATE: Set to true if API requires authentication.
*/
static get url() {
const info = this.CLASSINFO;
const version = (info.VERSION) ? util.format('/v%s', info.VERSION) : '';
return util.format('/%s%s/%s', info.URLPREFIX, version, info.URL || info.NAME);
}
constructor(req, res, next) {
this.req = req;
this.res = res;
this.next = next;
}
/**
* Execute controller action. The derived class is expected to provide the
* implementation for the action. The action method is expected to return
* a promise object. Promise resolve method must return Response instance whereas
* promise reject method must return error either as APIError instance or some
* Error instance.
*
* Before the actual action is executed, input parameter related errors are validated
* to make sure that all relevant data is available.
*/
execute() {
const obj = new Promise((resolve, reject) => {
// First validate input parameters
const errors = validator.validationResult(this.req);
if (!errors.isEmpty()) {
// Errors found, report back
return reject(new APIError(ValidatorAPI.getErrors(errors.mapped())));
}
// Execute the API action
this.action()
.then(resolve)
.catch(reject)
.finally(() => {
if (this.destroy) {
this.destroy();
}
});
});
// On success, render the action response
// On failure, call the error handler
obj
.then(response => this.renderResponse(response))
.catch(err => this.next(err));
return obj;
}
renderResponse(response) {
if (!response) {
this.res.json({});
this.res.end();
return;
}
if (!response.hasFile) {
if (response.statusCode) {
this.res.status(response.statusCode);
}
this.res.json(response.jsonResponse);
this.res.end();
return;
}
this.res[this.hasDownloadQuery ? 'download' : 'sendFile'](response.fileResponse);
}
get hasDownloadQuery() {
return this.getQueryParam('download');
}
hasQueryParam(param) {
return Object.prototype.hasOwnProperty.call(this.req.query, param);
}
getQueryParam(param) {
return decodeURIComponent(this.req.query[param]);
}
getParam(param) {
return this.req.params[param];
}
getPostParam(param) {
return this.req.body[param];
}
error(error) {
throw new APIError(error);
}
static apiEntry() {
const Cls = this;
return (req, res, next) => new Cls(req, res, next).execute();
}
static serialize(urlPrefix, defaultMethod = 'post') {
const info = this.CLASSINFO;
const data = {
url: util.format('%s%s', urlPrefix, this.url),
method: info.METHOD || defaultMethod,
info: info.INFO,
authenticate: info.AUTHENTICATE || false,
name: info.NAME
};
if (info.VERSION) {
data.version = info.VERSION;
}
return data;
}
}
module.exports = BaseCtrl;
|
{
"version": 1558978229,
"fileList": [
"data.js",
"c2runtime.js",
"jquery-2.1.1.min.js",
"offlineClient.js",
"images/tiledbackground.png",
"images/sprite-sheet0.png",
"images/sprite2-sheet0.png",
"images/rope-sheet0.png",
"images/sprite5-sheet0.png",
"images/tiledbackground2.png",
"images/sprite6-sheet0.png",
"images/sprite3-sheet0.png",
"images/sprite4-sheet0.png",
"images/sprite8-sheet0.png",
"images/tiledbackground3.png",
"images/sprite10-sheet0.png",
"images/sprite11-sheet0.png",
"images/spritefont.png",
"images/sprite12-sheet0.png",
"images/sprite9-sheet0.png",
"images/sprite13-sheet0.png",
"images/sprite14-sheet0.png",
"images/sprite15-sheet0.png",
"images/sprite17-sheet0.png",
"images/sprite7-sheet0.png",
"images/sprite7-sheet1.png",
"images/sprite7-sheet2.png",
"images/sprite16-sheet0.png",
"media/guncockbubble.m4a",
"media/guncockbubble.ogg",
"media/clang.m4a",
"media/clang.ogg",
"media/jump0.m4a",
"media/jump0.ogg",
"media/jump1.m4a",
"media/jump1.ogg",
"media/jump2.m4a",
"media/jump2.ogg",
"icon-16.png",
"icon-32.png",
"icon-114.png",
"icon-128.png",
"icon-256.png",
"loading-logo.png",
"patreonmark.png",
"twitter.png",
"facebook.png",
"instagram.png",
"youtube.png",
"rawdeflate.js",
"rawinflate.js",
"base64-1.7.js",
"GameAnalytics.js"
]
}
|
var ARC_SIZE = 2 * Math.PI;
module.exports = (ctx, position, radius, color) => {
ctx.beginPath();
ctx.arc(position.x, position.y, radius, 0, ARC_SIZE, false);
ctx.strokeStyle = color;
ctx.fillStyle = color;
ctx.fill();
ctx.stroke();
};
|
import api from '../../api'
let model = 'flowz'
// import store from '@/store'
export default {
get: (id = null, params = null, headers = null) => {
if (id === null) {
return api.request('get', '/' + model, null, params, headers)
} else {
return api.request('get', '/' + model + '/' + id, null, params, headers)
}
},
getCustom: (string) => {
return api.request('get', '/' + model + string)
},
post: (data) => {
return api.request('post', '/' + model, data)
},
put: (id, data) => {
return api.request('put', '/' + model + '/' + id, data)
},
patch: (id, data) => {
return api.request('patch', '/' + model + '/' + id, data)
},
delete: (id) => {
return api.request('delete', '/' + model + '/' + id)
}
}
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
const propTypes = {
clsfix:PropTypes.string,
onChange:PropTypes.func,
value:PropTypes.string
};
const defaultProps = {
clsfix:'u-search-tabs',
onChange:()=>{},
};
class SearchTabs extends Component {
constructor(props){
super(props);
this.state={
activeValue:props.value
}
}
componentWillReceiveProps(nextProps){
if('value' in nextProps && nextProps.value!=this.state.activeValue){
this.setState({
activeValue:nextProps.value
})
}
}
getChildren=()=>{
let { children,clsfix } = this.props;
let childs = [];
if(children.length>1){
React.Children.map(children,(child,index)=>{
childs.push(
React.cloneElement(child,{
tabClick:this.childClick,
active:child.props.value==this.state.activeValue,
clsfix:clsfix
})
)
if(index < children.length-1){
childs.push(
<span className={`${clsfix}-split`} key={`split-${index}`}>|</span>
)
}
})
}else{
childs.push(
React.cloneElement(children,{
tabClick:this.childClick,
active:children.props.value==this.state.activeValue,
clsfix:clsfix
})
)
}
return childs;
}
childClick=(activeValue)=>{
this.setState({
activeValue
})
this.props.onChange(activeValue)
}
render(){
let { clsfix,children, onChange, value, ...others } = this.props;
return(
<div className={`${clsfix}`} {...others}>
{
this.getChildren()
}
</div>
)
}
};
SearchTabs.propTypes = propTypes;
SearchTabs.defaultProps = defaultProps;
export default SearchTabs;
|
'use strict';
var grunt = require('grunt');
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
exports.kooshy_core = {
setUp: function(done) {
// setup here if necessary
done();
},
default_options: function(test) {
test.expect(1);
var actual = grunt.file.read('tmp/default_options');
var expected = grunt.file.read('test/expected/default_options');
test.equal(actual, expected, 'should describe what the default behavior is.');
test.done();
},
custom_options: function(test) {
test.expect(1);
var actual = grunt.file.read('tmp/custom_options');
var expected = grunt.file.read('test/expected/custom_options');
test.equal(actual, expected, 'should describe what the custom option(s) behavior is.');
test.done();
},
};
|
jQuery(function($){
$('.portfolio-item-thumbnail-wrap').tooltip();
$("a[rel^='prettyPhoto']").prettyPhoto();
$("img").lazyload({
effect: "fadeIn"
});
});
|
'use strict';
angular.module('zsoltiii.angular-cipher-filters')
.filter('scytaleCipher', function() {
return function(str, dimensions, decode) {
if (angular.isUndefined(str)) {
return null;
}
if (angular.isUndefined(dimensions)) {
dimensions = 1;
}
var i, j;
var returnArray = [];
var message = str.replace(/\s/g, '').toUpperCase();
var rows = message.length / dimensions;
var messageArray = message.split('');
if (decode === true) {
for(j = 0; j < dimensions; j++) {
for(i = 0; i < rows; i++) {
returnArray.push(messageArray[j+i*dimensions]);
}
}
return returnArray.join('');
} else {
for(i = 0; i < rows; i++) {
for(j = 0; j < dimensions; j++) {
returnArray.push(messageArray[i+j*rows]);
}
}
return returnArray.join('');
}
};
});
|
/// <reference path="typings/gulp/gulp.d.ts" />
/// <reference path="typings/gulp-typescript/gulp-typescript.d.ts" />
/// <reference path="typings/gulp-less/gulp-less.d.ts" />
var gulp = require('gulp');
var ts = require('gulp-typescript');
var less = require('gulp-less');
// config
var path = {
src : {
html: "src/html/**/*.html",
ts: "src/ts/**/*.ts",
less: "src/less/**/*.less",
img: "src/img/**/*.*",
test: "test/**/*.ts",
},
dest : {
root: "dest/",
html: "dest/html/",
js: "dest/js/",
css: "dest/css/",
img: "dest/img/",
vendor: {
root: "dest/vendor/",
},
test: "compiledTest/",
},
};
var tsProject = ts.createProject('src/tsconfig.json', {out: "app.js", sortOutput: true});
var testProject = ts.createProject('test/tsconfig.json');
// main tasks
gulp.task('build', [
'build:html',
'build:ts',
'build:less',
'build:img',
'build:vendor',
]);
gulp.task('watch', [
'watch:html',
'watch:ts',
'watch:less',
'watch:img',
]);
gulp.task('testBuild', [
'build',
'build:test'
]);
// sub tasks
gulp.task('build:html', function(){
gulp.src(path.src.html)
.pipe(gulp.dest(path.dest.html));
});
gulp.task('build:ts', function(){
var tsResult = gulp.src(path.src.ts)
.pipe(ts(tsProject));
tsResult.js.pipe(gulp.dest(path.dest.js));
});
gulp.task('build:less', function(){
gulp.src(path.src.less)
.pipe(less())
.pipe(gulp.dest(path.dest.css));
});
gulp.task('build:img', function(){
gulp.src(path.src.img)
.pipe(gulp.dest(path.dest.img));
});
gulp.task('build:vendor', function (){
});
gulp.task('build:test', function(){
var tsResult = gulp.src(path.src.test)
.pipe(ts(testProject));
tsResult.js.pipe(gulp.dest(path.dest.test));
});
gulp.task('watch:html', function(){
gulp.watch(path.src.html, ['build:html']);
});
gulp.task('watch:ts', function(){
gulp.watch(path.src.ts, ['build:ts']);
});
gulp.task('watch:less', function(){
gulp.watch(path.src.less, ['build:less']);
});
gulp.task('watch:img', function(){
gulp.watch(path.src.img, ['build:img']);
});
|
"use strict";
var EmailAddress_1 = require("../ComplexProperties/EmailAddress");
var ExtensionMethods_1 = require("../ExtensionMethods");
var XmlAttributeNames_1 = require("../Core/XmlAttributeNames");
var XmlElementNames_1 = require("../Core/XmlElementNames");
var EwsServiceJsonReader_1 = require("../Core/EwsServiceJsonReader");
var ExpandGroupResults = (function () {
function ExpandGroupResults() {
this.includesAllMembers = false;
this.members = [];
}
Object.defineProperty(ExpandGroupResults.prototype, "Count", {
get: function () {
return this.members.length;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ExpandGroupResults.prototype, "IncludesAllMembers", {
get: function () {
return this.includesAllMembers;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ExpandGroupResults.prototype, "Members", {
get: function () {
return this.members;
},
enumerable: true,
configurable: true
});
//GetEnumerator(): EmailAddress[] /*System.Collections.Generic.IEnumerator<EmailAddress>*/ { throw new Error("ExpandGroupResults.ts - GetEnumerator : Not implemented."); }
ExpandGroupResults.prototype.LoadFromXmlJsObject = function (responseObject, service) {
var dlResponse = responseObject[XmlElementNames_1.XmlElementNames.DLExpansion];
var mailboxes = EwsServiceJsonReader_1.EwsServiceJsonReader.ReadAsArray(dlResponse, XmlElementNames_1.XmlElementNames.Mailbox);
this.includesAllMembers = ExtensionMethods_1.Convert.toBool(dlResponse[XmlAttributeNames_1.XmlAttributeNames.IncludesLastItemInRange]);
var mailboxCount = ExtensionMethods_1.Convert.toNumber(dlResponse[XmlAttributeNames_1.XmlAttributeNames.TotalItemsInView]);
for (var _i = 0, mailboxes_1 = mailboxes; _i < mailboxes_1.length; _i++) {
var mailbox = mailboxes_1[_i];
var emailAddress = new EmailAddress_1.EmailAddress();
emailAddress.LoadFromXmlJsObject(mailbox, service);
this.members.push(emailAddress);
}
};
return ExpandGroupResults;
}());
exports.ExpandGroupResults = ExpandGroupResults;
|
/**
* Copyright 2012-2020, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var Registry = require('../../registry');
var hover = require('./hover').hover;
module.exports = function click(gd, evt, subplot) {
var annotationsDone = Registry.getComponentMethod('annotations', 'onClick')(gd, gd._hoverdata);
// fallback to fail-safe in case the plot type's hover method doesn't pass the subplot.
// Ternary, for example, didn't, but it was caught because tested.
if(subplot !== undefined) {
// The true flag at the end causes it to re-run the hover computation to figure out *which*
// point is being clicked. Without this, clicking is somewhat unreliable.
hover(gd, evt, subplot, true);
}
function emitClick() { gd.emit('plotly_click', {points: gd._hoverdata, event: evt}); }
if(gd._hoverdata && evt && evt.target) {
if(annotationsDone && annotationsDone.then) {
annotationsDone.then(emitClick);
} else emitClick();
// why do we get a double event without this???
if(evt.stopImmediatePropagation) evt.stopImmediatePropagation();
}
};
|
'use strict';
angular.module('myApp.dashboard', [])
.controller('sidebarController', ['$scope', '$rootScope','$location', function($scope, $rootScope,$location) {
$scope.state = true;
$scope.togglestate = function($event) {
$scope.state = !$scope.state;
$scope.showme = true;
$event.preventDefault();
};
$scope.logout = function($event) {
/*$scope.state = !$scope.state;
$scope.showme = true;*/
/*var oldTodos = $scope.todos;
*/
$scope.todos = [{}];
/*
angular.forEach(oldTodos, function(todo){
if(todo.email != '')
$scope.todos.push(todo);
});*/
localStorage.setItem('todos', JSON.stringify($scope.todos));
$rootScope.showSlidebar = false;
$event.preventDefault();
$location.path('/users/sign_in');
};
}])
.directive('sidebarDirective', function() {
return {
link: function(scope, element, attr) {
scope.$watch(attr.sidebarDirective, function() {
var iconElement = angular.element(document.getElementById("justify-icon"));
var iconParent = iconElement.parent();
var leftPanel = angular.element(document.getElementById("leftPanel"));
var rightPanel = angular.element(document.getElementById("rightPanel"));
if (iconParent.hasClass("sidebar-menu-collapsed")) {
iconParent.removeClass("sidebar-menu-collapsed");
iconParent.addClass("sidebar-menu-expanded");
leftPanel.removeClass("left-bar-full");
leftPanel.addClass("left-bar");
rightPanel.removeClass("right-bar");
rightPanel.addClass("right-bar-full");
scope.showme = "true";
return;
} else if (iconParent.hasClass("sidebar-menu-expanded")) {
iconParent.removeClass("sidebar-menu-expanded");
iconParent.addClass("sidebar-menu-collapsed");
leftPanel.removeClass("left-bar");
leftPanel.addClass("left-bar-full");
rightPanel.removeClass("right-bar-full");
rightPanel.addClass("right-bar");
scope.showme = false;
return;
}
});
}
};
});
|
/**
* Created by Nicolas on 6/22/15.
*/
(function (Controller) {
'use strict';
var async = require('async'),
postal = require('postal'),
constants = require('./constants'),
database = require('./database'),
logger = require('./logger'),
settings = require('./settings'),
streamManager = require('./streammanager'),
twitch = require('./twitch');
var channelsSubscription = null;
Controller.addChannel = function (channelName, callback) {
async.waterfall([
async.apply(twitch.api.getChannel, channelName),
function (response, next) {
if (response.statusCode === 200) {
database.createChannel(response.data, next);
} else {
next(new Error(response.data.message));
}
},
function (channel, next) {
streamManager.addChannel(channel, next);
}
], callback);
};
Controller.disposeIfNeeded = function () {
if (channelsSubscription) {
channelsSubscription.unsubscribe();
channelsSubscription = null;
}
streamManager.disposeAll();
};
Controller.getAllChannels = function (callback) {
database.getChannels(callback);
};
Controller.getAllStreams = function (callback) {
streamManager.getStreams(false, callback);
};
Controller.getAllStreamsWithPayload = function (callback) {
streamManager.getStreams(true, callback);
};
Controller.removeChannel = function (cid, callback) {
var channelName = null;
async.waterfall([
async.apply(database.getChannel, cid),
function (channel, next) {
if (channel == null) {
return next(new Error('Something went wrong, can not delete channel'));
}
channelName = channel.name;
database.deleteChannel(cid, next);
},
function (next) {
streamManager.removeChannelByName(channelName, next);
},
function (next) {
next(null, cid);
}
], callback);
};
Controller.saveClientId = function (clientId, callback) {
if (!clientId) {
return callback(new Error('Client ID is empty.'));
}
settings.save({clientId: clientId}, function (error, settingsData) {
if (error) {
return callback(error);
}
callback(null);
});
};
Controller.start = function (callback) {
async.waterfall([
function (next) {
channelsSubscription = postal.subscribe({
channel : constants.CHANNELS,
topic : constants.CHANNEL_DID_UPDATE,
callback: function (data) {
database.updateChannel(data.id, data.payload, function (error) {
if (error) {
return logger.log('error', 'Persisting channel. Error has occurred, message: %s', error.message);
}
});
}
});
next();
},
async.apply(settings.get),
function (settingsData, next) {
streamManager.initWidthDelay(settingsData.updateTime, next);
}
], callback);
};
/**
* Validates client id as requested by Twitch
*
* @param {string} clientId twitch application client id
* @param {function} callback should carry boolean status
*/
Controller.validateClientId = function (clientId, callback) {
//Invalid: empty client id
if (!clientId) {
return callback(null, false);
}
async.waterfall([
async.apply(twitch.api.validateClientId, clientId),
function (response, next) {
next(null, response.statusCode === 200 && response.body.identified === true);
}
], callback);
};
})(module.exports);
|
angular.module('demoScopeApp', [])
.controller('demoScopeController', function($scope) {
$scope.message = "Use Parent Scope";
})
.directive('scopeIsFalse', function() {
return {
restrict: 'E',
scope: false,
link: function(scope){
// scope.message = '我是爸爸、爸爸是我';
},
template: "<div>{{message}}</div>"
};
})
.directive('scopeIsTrue', function() {
return {
restrict: 'E',
scope: true,
link: function(scope){
// scope.message = '繼承爸爸,但我是獨立的';
},
template: "<div>{{message}}</div>"
}
})
.directive('scopeIsObject', function() {
return {
restrict: 'E',
scope: {},
link: function(scope){
// scope.message = "不繼承爸爸,我是獨立的!";
},
template: "<div>{{message}}</div>"
};
});
|
const redis = require('./lib/redis')
const lru = require('./lib/lru-cache')
const debug = require('debug')('koa-wxsession')
const getSessionKey = require('./lib/sessionkey')
const sha1 = require('./lib/sha1')
const ERRORS = require('./constants').errors
const wrapError = require('./lib/warpError')
const aesDecrypt = require('./lib/aes')
module.exports = wxsession
function wxsession ({
appID,
appSecret,
store,
prefix = 'wx-session:',
ttl = 2 * 60 * 60 * 1000,
redisConfig,
stateKey = 'wxinfo',
generator = code => sha1(code),
useEncryptedData = false,
errors = {
[ERRORS.ERR_HEADER_MISSED]: wrapError(400, ERRORS.ERR_HEADER_MISSED),
[ERRORS.ERR_SESSION_KEY_EXCHANGE_FAILED]: wrapError(400, ERRORS.ERR_SESSION_KEY_EXCHANGE_FAILED),
[ERRORS.ERR_UNTRUSTED_DATA]: wrapError(400, ERRORS.ERR_UNTRUSTED_DATA),
[ERRORS.ERR_SESSION_INVALID]: wrapError(401, ERRORS.ERR_SESSION_INVALID),
[ERRORS.ERR_OTHERS]: wrapError(500, ERRORS.ERR_OTHERS)
}
}) {
store = store || (redisConfig ? redis(ttl, redisConfig) : lru(ttl))
return {
authorization: async (ctx, next) => {
const {
'x-wechat-code': code,
'x-wechat-data': data,
'x-wechat-signature': signature,
'x-wechat-encrypted': encryptedData,
'x-wechat-iv': iv
} = ctx.headers
const rawData = decodeURIComponent(data || '')
// header check
if (useEncryptedData) {
if ([code, encryptedData, iv].some(v => !v)) {
debug(ERRORS.ERR_HEADER_MISSED)
return errors[ERRORS.ERR_HEADER_MISSED](ctx)
}
} else {
if ([code, rawData, signature].some(v => !v)) {
debug(ERRORS.ERR_HEADER_MISSED)
return errors[ERRORS.ERR_HEADER_MISSED](ctx)
}
}
// session exchange
debug('code: %s', code)
try {
var {openid, session_key} = await getSessionKey(appID, appSecret, code)
debug('openid: %s, session_key: %s', openid, session_key)
} catch (e) {
debug('%s: %s', ERRORS.ERR_SESSION_KEY_EXCHANGE_FAILED, e.message)
return errors[ERRORS.ERR_SESSION_KEY_EXCHANGE_FAILED](ctx)
}
// decrypt or signature check
let decryptedData
if (useEncryptedData) {
try {
decryptedData = aesDecrypt(session_key, iv, encryptedData)
} catch (e) {
debug(ERRORS.ERR_UNTRUSTED_DATA)
return errors[ERRORS.ERR_UNTRUSTED_DATA](ctx)
}
} else {
if (sha1(rawData + session_key) !== signature) {
debug(ERRORS.ERR_UNTRUSTED_DATA)
return errors[ERRORS.ERR_UNTRUSTED_DATA](ctx)
}
}
// store session
try {
const session = generator(code)
const key = prefix + session
const info = {
openid,
info: useEncryptedData ? JSON.parse(decryptedData) : JSON.parse(rawData),
session
}
await store.set(key, info)
ctx.state[stateKey] = info
} catch (e) {
debug('%s: %s', ERRORS.ERR_OTHERS, e.message)
return errors[ERRORS.ERR_OTHERS](ctx)
}
return next()
},
validation: async (ctx, next) => {
// check session
const session = ctx.headers['x-wechat-session']
if (!session) {
debug(ERRORS.ERR_SESSION_INVALID)
return errors[ERRORS.ERR_SESSION_INVALID](ctx)
}
const key = prefix + session
try {
const ret = await store.get(key)
if (ret == null) {
debug(ERRORS.ERR_SESSION_INVALID)
return errors[ERRORS.ERR_SESSION_INVALID](ctx)
}
ctx.state[stateKey] = ret
} catch (e) {
debug('%s: %s', ERRORS.ERR_OTHERS, e.message)
return errors[ERRORS.ERR_OTHERS](ctx)
}
return next()
}
}
}
|
'use strict';
var Q = require('q');
var progres = require('./index.js');
var connectionString = 'postgres://localhost';
[
// Errors in the job should propagate.
function () {
return progres.connect(connectionString, function (client) {
// Exception in the job.
throw 'passed';
}).then(function () {
// This should never execute.
throw new Error('Errors in the job should propagate.');
}, function (error) {
// Is it the error thrown in the job?
if (error !== 'passed') {
// Unexpected error.
throw error;
}
});
},
// postgresClient.end() should be called after the job is done.
function () {
var calledEnd = false;
return progres.connect(connectionString, function (client) {
// Attach a hook directly to the postgres client.
var oldEnd = client.postgresClient.end;
client.postgresClient.end = function () {
oldEnd.call(client.postgresClient);
calledEnd = true;
};
return Q();
}).then(function () {
if (!calledEnd) {
throw new Error('postgresClient.end() should be called after the job is done.');
}
});
},
// Queries should return the resulting rows.
function () {
return progres.connect(connectionString, function (client) {
// Run a query.
return client.query("SELECT 'passed' AS column_name;").then(function (rows) {
// Ensure we get the expected result back.
if (rows[0].column_name !== 'passed') {
throw new Error('Queries should return the resulting rows.');
}
});
});
},
// Broken SQL should propagate the error.
function () {
return progres.connect(connectionString, function (client) {
var brokenSql = 'broken sql';
// Run a broken query.
return client.query(brokenSql).then(function () {
// This should never execute.
throw new Error('Broken SQL should propagate the error.');
}, function (error) {
// The broken SQL should be part of the thrown error.
if (error.SQL !== brokenSql) {
throw new Error('Queries should return the resulting rows.');
}
});
});
},
// An exception should be thrown if the job doesn't return a promise.
// (Or the client might be ended prematurely - dangerous.)
function () {
return progres.connect(connectionString, function (client) {
// Break the rule about returning promises.
return 'not a promise';
}).then(function () {
// This should never execute.
throw new Error('An exception should be thrown if the job doesn\'t return a promise.');
}, function (error) {
// Passed the test.
});
}
]
// Run in sequence.
.reduce(function (soFar, next) { return soFar.then(next); }, Q())
.done(function () {
console.log('Everything OK.');
}, function (error) {
console.error(error);
process.exit(1);
});
|
// TWITTER_CONSUMER_KEY=EosSWKFz1kCRCa8ytMDWW6PwK
// TWITTER_CONSUMER_SECRET=sGFbOddr7PWnoChJ4fGV7TWDRuuCMzSwUJqfl6ufFGtPgMZoAG
// TWITTER_ACCESS_TOKEN=2457920262-5QtbA39tb3NbmlxJe4TA82k4WLFHvXiaflEO5Ec
// TWITTER_ACCESS_SECRET=NtmVlBqarVkCtVEQPj3EeihWfCOM9VjjrNtXuB8zLjQor
//HEROKU CONFIG SETUP
//heroku config:add TWITTER_CONSUMER_KEY=EosSWKFz1kCRCa8ytMDWW6PwK TWITTER_CONSUMER_SECRET=sGFbOddr7PWnoChJ4fGV7TWDRuuCMzSwUJqfl6ufFGtPgMZoAG TWITTER_ACCESS_TOKEN=2457920262-5QtbA39tb3NbmlxJe4TA82k4WLFHvXiaflEO5Ec TWITTER_ACCESS_SECRET=NtmVlBqarVkCtVEQPj3EeihWfCOM9VjjrNtXuB8zLjQor
//AND OUR FALLBACK FOR LOCAL
module.exports = {
local : {
consumer_key: 'EosSWKFz1kCRCa8ytMDWW6PwK',
consumer_secret: 'sGFbOddr7PWnoChJ4fGV7TWDRuuCMzSwUJqfl6ufFGtPgMZoAG',
access_token_key: '2457920262-5QtbA39tb3NbmlxJe4TA82k4WLFHvXiaflEO5Ec',
access_token_secret: 'NtmVlBqarVkCtVEQPj3EeihWfCOM9VjjrNtXuB8zLjQor'
},
dev : {
consumer_key: '',
consumer_secret: '',
access_token_key: '',
access_token_secret: ''
},
prod : {
consumer_key: '',
consumer_secret: '',
access_token_key: '',
access_token_secret: ''
}
}
|
console.log("my name is brian i am the bot");
Settings = require("./settings.json")
Responses = require("./Responses.json")
VoiceResponses = require("./VoiceResponses.json")
Discord = require('discord.js');
twitter = require("./twitter.js")
Steam = require("./steam.js");
Memes = require("./memes.json")
client = new Discord.Client();
client.login(Settings.token);
function getAMeme(){
return Memes.memes[Math.random(5)]
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/ global chat channel
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
var channel;
var voiceChannel;
var voiceChannelConnection;
var isJazzing = false;
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/ When client inits. set game and global channel
/ Sends few mesages to tell everboy brain
/ halls in the house.
/
/ Also send the channel object to twitter.js .
/ so it can send message when it recieves tweets
//*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
client.on("ready", function(){
client.user.setGame("Diablo 3");
channel = client.channels.find("name", "general");
channel.sendMessage("Rebooting",{"tts": true });
channel.sendCode("C", "return 'DOCTOR B.HALL'");
voiceChannel = client.channels.get('164382040215650304');
twitter.handlerForOnSteamTweet(channel);
})
AttachmentFunctions = {
"grade" : attachment => {
attachment.message.reply("F");
}
}
client.on('message', message => {
if (message.attachments.size === 0 && client.user.id === message.mentions.users.firstKey()){
var messageSplit = message.content.match(/("[^"]*")|[^ ]+/g);
if(messageSplit[0] === '<@' + client.user.id + '>' && messageSplit.length >= 2){
var response = Responses[messageSplit[1].toLowerCase()];
if(response === undefined){
message.reply(Responses._annoying);
} else if(response!="noresponse"){
message.reply(response);
}
var filename = VoiceResponses[messageSplit[1].toLowerCase()];
if(filename != undefined)
{
voiceChannel.join().then(connection => {
voiceChannelConnection = connection;
const dispatcher = connection.playFile("sfx/" + filename);
isJazzing = true;
});
}
else if(messageSplit[1].toLowerCase() == "stoptalking")
{
voiceChannel.leave();
}
}else{
message.reply(Responses._annoying);
}
}else if (client.user.id === message.mentions.users.firstKey()){
var messageSplit = message.content.match(/("[^"]*")|[^ ]+/g);
var attachment = Array.from(message.attachments.values())[0];
if(messageSplit[0] === '<@' + client.user.id + '>' && attachment.width !== undefined && messageSplit.length >= 2){
var response = AttachmentFunctions[messageSplit[1].toLowerCase()];
if(response === undefined){
message.reply(Responses._annoyingimage);
} else{
response(attachment);
}
}else if (messageSplit.length >= 2){
message.reply(getAMeme());
}else {
message.reply(Responses._imagesonly);
}
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/ if nobody's sent a message in the last minite
/ or so send a message. If your receiving
/ lots of messages then restart the timer.
//*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
clearTimeout()
});
function intervalCheck()
{
if(isJazzing)
{
if(!voiceChannelConnection.speaking)
{
voiceChannel.leave();
}
}
}
setInterval(intervalCheck, 1000);
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/ fires a events when somebody presence changes.
/ So if they start a new game or log off.
/ https://discord.js.org/#/docs/main/stable/class/Client?scrollTo=presenceUpdate
/ info on presence
/ https://discord.js.org/#/docs/main/stable/class/Presence?scrollTo=game
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
client.on('presenceUpdate', (oldPresence, newPresence) => {
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/ get the old presence
/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
//console.log(oldPresence.frozenPresence.status)
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/ get a user and then with a promise get the
/ presence so you can get the game idea
/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
client.fetchUser(newPresence.id).then((user) =>{
//console.log(user.presence)
if(user.presence.game != null){
game = user.presence.game.name.replace(".x86_64","").replace(".x64","")
console.log(game)
Steam.numberOfUsers(game).then((numberofUsers)=>{
console.log("got through")
if(numberofUsers < 100){
channel.sendMessage("what a indie darling")
}
});
Steam.getTags(user.presence.game.name).then((info)=>{
for(var i= 0; i < info.length; i++){
if(info[i] = "anime"){
channel.sendMessage("We can not tolerate this kind of behavior.")
}
}
});
Steam.appDetails(user.presence.game.name).then((info)=>{
if(info["metacritic"] < 50){
channel.sendMessage("It pains me to see you hurt yourself like this.")
}
});
}
})
});
|
'use strict';
(function() {
// Recipt Controller Spec
describe('Recipt Controller Tests', function() {
// Initialize global variables
var ReciptController,
$scope,
$httpBackend,
$stateParams,
$location;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function () {
jasmine.addMatchers({
toEqualData: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
// Set a new global scope
$scope = $rootScope.$new();
// Point global variables to injected services
$stateParams = _$stateParams_;
$httpBackend = _$httpBackend_;
$location = _$location_;
// Initialize the Recipt controller.
ReciptController = $controller('ReciptController', {
$scope: $scope
});
}));
it('Should do some controller test', inject(function () {
// The test logic
// ...
}));
});
}());
|
var jsdom = require('mocha-jsdom');
var fs = require("fs");
var chai = require('chai');
var expect = chai.expect;
var polydom = fs.readFileSync('./dist/polydom.js', 'utf-8');
var toArray = Function.prototype.call.bind(Array.prototype.slice);
var toString = Function.prototype.call.bind(Object.prototype.toString);
// Camelize strings
function camelize(string) {
return string.replace(reCamelize, function (c) {
return c ? c.toUpperCase() : '';
});
}
function getStyle(el, prop) {
if (el.currentStyle) {
return el.currentStyle[camelize(prop)];
}
else if (document.defaultView && document.defaultView.getComputedStyle) {
return document.defaultView.getComputedStyle(el, null).getPropertyValue(prop);
}
else {
return el.style[camelize(prop)];
}
}
|
import spawn from '../src/spawn'
import {childPrinted} from 'async-child-process'
import {expect} from 'chai'
describe('killOnExit', () => {
it('kills child when parent process exits', async function () {
this.timeout(60000)
const proc = spawn('babel-node', [require.resolve('./util/killOnExitParent')], {silent: true})
const parentOutput = await childPrinted(proc, /parent pid: \d+/)
const parentPid = parentOutput.substring("parent pid: ".length)
const childOutput = await childPrinted(proc, /child pid: \d+/)
const childPid = childOutput.substring("child pid: ".length)
// wait for parent to exit
await new Promise(resolve => setTimeout(resolve, 2000))
expect(() => process.kill(parentPid, 0)).to.throw
expect(() => process.kill(childPid, 0)).to.throw
})
it('kills child when parent process is killed with SIGINT', async function () {
this.timeout(60000)
const proc = spawn('babel-node', [require.resolve('./util/killOnExitParent')], {silent: true})
const parentOutput = await childPrinted(proc, /parent pid: \d+/)
const parentPid = parentOutput.substring("parent pid: ".length)
const childOutput = await childPrinted(proc, /child pid: \d+/)
const childPid = childOutput.substring("child pid: ".length)
proc.kill('SIGINT')
expect(() => process.kill(parentPid, 0)).to.throw
expect(() => process.kill(childPid, 0)).to.throw
})
it('kills child when parent process is killed with SIGTERM', async function () {
this.timeout(60000)
const proc = spawn('babel-node', [require.resolve('./util/killOnExitParent')], {silent: true})
const parentOutput = await childPrinted(proc, /parent pid: \d+/)
const parentPid = parentOutput.substring("parent pid: ".length)
const childOutput = await childPrinted(proc, /child pid: \d+/)
const childPid = childOutput.substring("child pid: ".length)
proc.kill('SIGTERM')
expect(() => process.kill(parentPid, 0)).to.throw
expect(() => process.kill(childPid, 0)).to.throw
})
it('works when child process exits by itself', async function () {
this.timeout(60000)
const proc = spawn('babel-node', [require.resolve('./util/killOnExitParent2')], {silent: true})
const parentOutput = await childPrinted(proc, /parent pid: \d+/)
const parentPid = parentOutput.substring("parent pid: ".length)
const childOutput = await childPrinted(proc, /child pid: \d+/)
const childPid = childOutput.substring("child pid: ".length)
// wait for parent to exit
await new Promise(resolve => setTimeout(resolve, 2000))
expect(() => process.kill(parentPid, 0)).to.throw
expect(() => process.kill(childPid, 0)).to.throw
})
})
|
import Immutable from 'immutable';
export default class State {
constructor() {
this.state = Immutable.fromJS({});
}
set state(state) {
if (this._state === state) {
return;
}
this._state = state;
}
get state() {
return this._state;
}
cursor(path, defaultValue) {
if (!this.state.getIn(path)) {
this.state = this.state.updateIn(path, () => Immutable.fromJS(defaultValue));
}
return (update) => {
if (update) {
this.state = this.state.updateIn(path, update);
}
return this.state.getIn(path);
};
}
}
|
import mongoose, { Schema } from 'mongoose'
const schema = new Schema({
_tournament: {
type: Schema.Types.ObjectId,
required: true
},
rank: {
type: Number,
required: true
},
breakRound: {
type: Schema.Types.ObjectId,
ref: 'breakRounds',
required: true
},
venue: {
type: Schema.Types.ObjectId,
ref: 'venues',
required: true
},
chair: {
type: Schema.Types.ObjectId,
ref: 'breakAdjudicators',
required: true
},
panels: [{ type: Schema.Types.ObjectId, ref: 'breakAdjudicators', default: [] }],
gov: {
type: Schema.Types.ObjectId,
ref: 'breakTeams',
required: true
},
opp: {
type: Schema.Types.ObjectId,
ref: 'breakTeams',
required: true
},
pm: {
type: Schema.Types.ObjectId,
ref: 'debaters'
},
dpm: {
type: Schema.Types.ObjectId,
ref: 'debaters'
},
gw: {
type: Schema.Types.ObjectId,
ref: 'debaters'
},
gr: {
type: Schema.Types.ObjectId,
ref: 'debaters'
},
lo: {
type: Schema.Types.ObjectId,
ref: 'debaters'
},
dlo: {
type: Schema.Types.ObjectId,
ref: 'debaters'
},
ow: {
type: Schema.Types.ObjectId,
ref: 'debaters'
},
or: {
type: Schema.Types.ObjectId,
ref: 'debaters'
},
motion: {
type: Schema.Types.ObjectId,
ref: 'motions'
},
createdAt: {
type: Date,
required: true,
default: Date.now
}
})
module.exports = mongoose.model('breakRooms', schema)
|
import { shortestRoute } from '../utils';
const { start, end, grid } = generateGrid(10, 10);
const initialState = {
rowCount: 10,
colCount: 10,
rows: 10,
cols: 10,
grid,
start,
end,
path: {},
};
export function checkRoute(state) {
const { grid, start, end } = state;
const path = shortestRoute(grid, start, end);
return { ...state, path };
}
export function generateCoords(rows, cols, min) {
return {
row: Math.floor(Math.random() * rows),
col: Math.floor(Math.random() * (cols - min) + min),
};
}
export function generateGrid(rows, cols) {
// divide by two to make sure start is always on the left
const start = generateCoords(rows, (cols / 2), 0);
// Pass min value to ensure end is always on the right
const end = generateCoords(rows, cols, (cols / 2));
// return grid, plus start & end values to save having to find them later on
return {
grid: [...Array(rows).keys()].map(row => [...Array(cols).keys()].map(col => {
return {
start: row === start.row && col === start.col,
end: row === end.row && col === end.col,
active: false,
visited: false,
}
})),
start,
end
}
}
export default function gridster(state = initialState, action) {
if (action.type === 'UPDATE_ROW_COUNT') {
return checkRoute({ ...state, rowCount: action.rowCount });
}
if (action.type === 'UPDATE_COLUMN_COUNT') {
return checkRoute({ ...state, colCount: action.colCount });
}
if (action.type === 'GENERATE_GRID') {
const { rowCount, colCount } = state;
const { start, end, grid } = generateGrid(rowCount, colCount);
return checkRoute({ ...state, start, end, grid, rows: rowCount, cols: colCount });
}
if (action.type === 'TOGGLE_SQUARE') {
const { grid } = state;
const square = grid[action.row][action.col];
square.active = !square.active;
return checkRoute({ ...state, grid });
} else {
return checkRoute(state);
}
}
|
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import MuseUI from 'muse-ui'
import 'muse-ui/dist/muse-ui.css'
import store from './store/store'
import axios from './http/index'
Vue.use(MuseUI)
Vue.config.productionTip = false
Vue.prototype.axios = axios
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
axios,
template: '<App/>',
components: { App }
})
|
const configuration = require("src/config/configuration").getInstance();
const TMDB = require("src/tmdb/tmdb");
const Plex = require("src/plex/plex");
const tmdb = new TMDB(configuration.get("tmdb", "apiKey"));
const plex = new Plex(configuration.get("plex", "ip"));
function handleError(error, res) {
const { status, message } = error;
if (status && message) {
res.status(status).send({ success: false, message });
} else {
console.log("caught movieinfo controller error", error);
res.status(500).send({
message: "An unexpected error occured while requesting movie info"
});
}
}
/**
* Controller: Retrieve information for a movie
* @param {Request} req http request variable
* @param {Response} res
* @returns {Callback}
*/
async function movieInfoController(req, res) {
const movieId = req.params.id;
let { credits, release_dates, check_existance } = req.query;
credits && credits.toLowerCase() === "true"
? (credits = true)
: (credits = false);
release_dates && release_dates.toLowerCase() === "true"
? (release_dates = true)
: (release_dates = false);
check_existance && check_existance.toLowerCase() === "true"
? (check_existance = true)
: (check_existance = false);
let tmdbQueue = [tmdb.movieInfo(movieId)];
if (credits) tmdbQueue.push(tmdb.movieCredits(movieId));
if (release_dates) tmdbQueue.push(tmdb.movieReleaseDates(movieId));
try {
const [Movie, Credits, ReleaseDates] = await Promise.all(tmdbQueue);
const movie = Movie.createJsonResponse();
if (Credits) movie.credits = Credits.createJsonResponse();
if (ReleaseDates)
movie.release_dates = ReleaseDates.createJsonResponse().results;
if (check_existance) {
try {
movie.exists_in_plex = await plex.existsInPlex(movie);
} catch (error) {
if (error.status === 401) {
console.log("Unathorized request, check plex server LAN settings");
} else {
console.log("Unkown error from plex!");
}
console.log(error);
}
}
res.send(movie);
} catch (error) {
handleError(error, res);
}
}
module.exports = movieInfoController;
|
/**
* 默认基于时间,返回指定范围内的随机数
* 当seed不固定时速度比较慢,仅用于减少重复率
* http://indiegamr.com/generate-repeatable-random-numbers-in-js/
*/
function seededRandom(max, min, seed) {
var seed = seed || new Date().getTime(),
rnd;
max = max || 1;
min = min || 0;
seed = (seed * 9301 + 49297) % 233280;
rnd = seed / 233280;
return min + rnd * (max - min);
}
module.exports = seededRandom;
|
'use strict';
var directivesModule = require('./_index.js');
/**
* @ngInject
*/
function slideable() {
return {
restrict:'C',
compile: function (element, attr) {
// wrap tag
var contents = element.html();
element.html('<div class="slideable_content" style="margin:0 !important; padding:0 !important" >' + contents + '</div>');
return function postLink(scope, element, attrs) {
// default properties
attrs.duration = (!attrs.duration) ? '1s' : attrs.duration;
attrs.easing = (!attrs.easing) ? 'ease-in-out' : attrs.easing;
element.css({
'overflow': 'hidden',
'height': '0px',
'transitionProperty': 'height',
'transitionDuration': attrs.duration,
'transitionTimingFunction': attrs.easing
});
};
}
};
}
directivesModule.directive('slideable', slideable);
|
var router = require("express").Router(),
ml = require("../db");
var deleteCampaign = function(req, res) {
var nosql = {
"collection": "campaigns",
"selector" : {"_id" : ml.ObjectID(req.param("campaignID"))}
};
console.log("Deleting campaign: ", nosql.selector._id);
ml.deleteData(nosql, function(err, result) {
if (err) {
console.log("error:" + nosql);
res.send(403, {
"error": "Something is wrong with your query" + err.message
});
} else {
res.send(200, {
"result": result
});
}
});
};
router.delete("/:campaignID", deleteCampaign);
module.exports = router;
|
var request = require ('request');
var url = require ('url');
var db = require (__dirname + '/../server/database.js');
var async = require ('async');
function getTableName (req) {
// Determine if it's primary or secondary
var pathname = url.parse (req.url).pathname;
pathname = pathname.split('/');
var tableName = pathname[4];
return tableName;
}
// =============================================================================
// Get a user's keywords
// =============================================================================
exports.getUserKeywords = function (req, res) {
// Verify valid api parameters
if (req.params.userID < 0) {
res.statusCode = 400;
return res.send ('Invalid userID.');
}
var tableName = getTableName (req);
var userID = req.params.userID;
var query = 'SELECT DISTINCT * FROM ' + tableName +
' INNER JOIN keywords ON keywords.id = ' +
tableName + '.keyID ' +
'WHERE ' + tableName + '.userID = ' + userID;
db.queryDB (query, function (err, rows) {
if (err) {
res.statusCode = 500;
return res.send (err);
}
return res.json (rows);
});
};
// =============================================================================
// Remove a user's keyword
// =============================================================================
exports.removeUserKeyword = function (req, res) {
// Verify valid api parameters
if (req.params.userID < 0) {
res.statusCode = 400;
return res.send ('Invalid userID');
}
if (req.params.keyword === '') {
res.statusCode = 400;
return res.send ('Keyword must not be null');
}
// Determine if it's primary or secondary
var tableName = getTableName (req);
var userID = req.params.userID;
var keyword = req.params.keyword;
var query = 'DELETE ' + tableName + ' FROM ' + tableName +
' INNER JOIN keywords ON keywords.id = ' + tableName + '.keyID ' +
'WHERE ' + tableName + '.userID = ' + userID + ' ' +
'AND keywords.name = "' + keyword + '"';
db.queryDB (query, function (err) {
if (err) {
res.statusCode = 500;
return res.send (err);
}
return res.json (true);
});
};
// =============================================================================
// Add a keyword to a user
// =============================================================================
exports.addKeywordToUser = function (req, res) {
if (req.params.userID < 0) {
res.statusCode = 400;
return res.send ('Invalid userID');
}
if (req.params.keyword === '') {
res.statusCode = 400;
return res.send ('Keyword must not be null');
}
// Determine if it's primary or secondary
var tableName = getTableName (req);
var userID = req.params.userID;
// TODO: Sanitize keyword
var keyword = req.params.keyword;
async.series ([
function (callback) {
addKeyword (keyword, function (err) {
return callback (err);
});
},
function (callback) {
assignToUser (userID, keyword, tableName, callback);
}
],
function (err) {
if (err) {
res.statusCode = 500;
return res.send (err);
}
return res.json (true);
});
};
function assignToUser (userID, keyword, tableName, callback) {
var query = 'INSERT INTO ' + tableName + ' (userID, keyID) ' +
'SELECT ' + userID + ', id ' +
'FROM keywords WHERE name = "' + keyword + '" ' +
'ON DUPLICATE KEY UPDATE userID=userID';
db.queryDB (query, function (err, result) {
if (err) {
callback(err);
return;
}
// Connection successful.
callback(null);
});
}
function addKeyword (keyword, callback) {
// Verify Valid api parameters
if (keyword === '') {
res.statusCode = 400;
return res.send ('Keyword must not be null');
}
var query = 'INSERT INTO keywords (name, popularity) ' +
'VALUES ("' + keyword + '", 0)' +
'ON DUPLICATE KEY UPDATE name = name';
db.queryDB (query, function (err, result) {
return callback (err);
});
}
// =============================================================================
// Get a user's articles
// =============================================================================
exports.getArticles = function (req, res) {
// Verify valid api parameters
if (req.params.userID < 0) {
res.status = 400;
return res.send ("Error 400: Invalid userID");
}
var query = 'SELECT DISTINCT articles.title, articles.url FROM userKey ' +
'INNER JOIN keyArt ON userKey.keyID = keyArt.keyID ' +
'INNER JOIN articles ON keyArt.artID = articles.id ' +
'WHERE userKey.userID = ' + userID;
db.queryDB (query, function (err, rows) {
if (err) {
res.status = 499;
return res.send ("Error 499: " + err);
}
return res.json (rows);
});
};
|
/*
@@@@@@@@@@@@@> @@@@@@@@@@>
@> @@@> @> @>
@> @> @> @@@@@@@@@@>
@> @> @>
@> @> @>
@> @> @@@@@@@@@>
(c) Scott Persinger 2011. See LICENSE.txt for license.
M5 support
*/
M5.require('jQuery');
/* System class additions */
Storage.prototype.setObject = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObject = function(key, demarshal) {
var result = JSON.parse(this.getItem(key));
if (demarshal && result && typeof(result.length) != "undefined") {
result = $.map(result, demarshal);
}
return result;
}
Date.prototype.datesEqual = function(other) {
if (other && typeof(other) == 'object') {
return this.toDateString() == other.toDateString();
} else {
return false;
}
}
String.prototype.trim = function() {
return jQuery.trim(this);
}
/** M5.util defines a set of utility functions.
*/
M5.util = (function() {
var benchmarks = [];
return {
benchmark: benchmark,
bench_start: bench_start,
bench_end: bench_end,
function_source: function_source,
get_cookie: get_cookie,
hash: hash,
inspect: inspect,
set_cookie: set_cookie,
stacktrace: stacktrace
}
/**#@+
@public
@memberOf M5.util#
*/
/** Retrieve the body of a function as text */
function function_source(f) {
var lines = f.toString().split("\n");
return lines.splice(1, lines.length-2).join("\n");
}
/** Set a cookie value. */
function set_cookie(name, value) {
document.cookie = name + "=" + escape(value + '');
}
/** Get a cookie value, or null. */
function get_cookie(name) {
parts = document.cookie.split("; ");
var m;
var res = null;
$.each(parts, function(index, val) {
if (m = val.match(new RegExp("^" + name + "=(.*)"))) {
res = m[1];
}
});
return res ? unescape(res) : null;
}
function delete_cookie(name) {
document.cookie = name + "=";
}
/** Mark the time that event 'key' starts. */
function bench_start(key) {
benchmarks[key] = new Date();
}
/** Report the time since bench_start(key) was called. */
function bench_end(key) {
var start;
if (start = benchmarks[key]) {
console.log("Benchmark == " + key + " == " + ((new Date() - start)/1000) );
}
}
/** Report the time required to execute function f. */
function benchmark(label, f) {
var start = new Date();
f();
console.log("Benchmark == " + label + " == " + ((new Date() - start)/1000) );
}
/** Return a hash generated from 'key' */
function hash(key, tableSize) {
tableSize = tableSize || 99999999;
var s = key;
var b = 27183, h = 0, a = 31415;
if (tableSize > 1) {
for (i = 0; i < s.length; i++) {
h = (a * h + s[i].charCodeAt()) % tableSize;
a = ((a % tableSize) * (b % tableSize)) % (tableSize);
}
}
return h;
}
function inspect(obj, level) {
level = level || 0;
if (level > 1) {
return '';
}
if (obj instanceof jQuery || jQuery.isArray(obj)) {
var res = [];
for (var i = 0; i < obj.length; i++) {
res.push(inspect(obj[i], level+1));
}
return "[" + res.join(", ") + "]";
} else if (obj instanceof Element) {
var res = "<" + obj.tagName;
for (var i = 0; i < obj.attributes.length; i++) {
res = res + " " + obj.attributes[i].name + '="' + obj.attributes[i].value + '" ';
}
res = res + " />";
return res;
}
if (!obj) {
return 'null';
} else if (typeof(obj) == "object") {
var res = [];
for (k in obj) {
res.push(k + ": " + inspect(obj[k], level+1));
}
return "{" + res.join(", ") + "}";
} else {
return obj + "";
}
}
function stacktrace()
{
re = /function\W+([\w-]+)/i;
var f = arguments.callee;
var s = "";
while (f)
{
s += (re.exec(f))[1] + '(';
for (i = 0; i < f.arguments.length - 1; i++)
{
s += "'" + f.arguments[i] + "', ";
}
if (arguments.length > 0)
{
s += "'" + f.arguments[i] + "'";
}
s += ")\n\n";
f = f.arguments.callee.caller;
}
return s;
}
})();
/** Interpolates the first argument string looking for {{identifier}} and %@ patterns. Values
* can be provided either as a hash, like:
* M5.format("Hello {{first_name}} {{last_name}}", {first_name: 'scott', last_name: 'persinger'})
* or by position, like:
* M5.format("Hello %@ %@", 'scott', 'persinger')
*/
M5.format = function(fmt) {
var result = fmt;
if ($.isPlainObject(arguments[1])) {
$.each(arguments[1], function(key, val) {
result = result.replace(new RegExp("{{\s*" + key + "\s*}}"), val);
});
} else {
for (var i = 1; i < arguments.length; i++) {
result = result.replace(/%@/, arguments[i]).replace(/{{\s*\w+\s*}}/,arguments[i]);
};
}
return result;
}
|
define([
'preact',
'htm',
// for effect
'bootstrap',
'css!./styles.css'
], (
preact,
htm
) => {
const {h, Component} = preact;
const html = htm.bind(h);
class HamburgerMenu extends Component {
renderSection(menuItems) {
return menuItems.map((menuItem) => {
let icon = null;
if (menuItem.icon) {
icon = html`
<div className="navbar-icon">
<span className=${`fa fa-${menuItem.icon}`}></span>
</div>
`;
}
return html`
<li>
<a href=${menuItem.uri ? menuItem.uri : `/#${ menuItem.path}`}
target=${menuItem.newWindow ? '_blank' : null}>
${icon}
<span>${menuItem.label}</span>
</a>
</li>
`;
});
}
renderSectionWithDivider(menuItems) {
if (menuItems.length === 0) {
return null;
}
return html`
${this.renderSection(menuItems)}
<li role="presentation" className="divider"></li>
`;
}
renderDivider() {
return html`
<li role="presentation" className="divider"></li>
`;
}
renderSections() {
return this.props.menu.section.map((section) => {
return this.renderSection(section);
});
}
render() {
const menuContent = [];
let hasContent = false;
[
this.props.menu.main,
this.props.menu.developer,
this.props.menu.help
].forEach((menu) => {
if (menu.length > 0) {
if (hasContent) {
menuContent.push(this.renderDivider());
}
menuContent.push(this.renderSection(menu));
hasContent = true;
} else {
hasContent = false;
}
});
return html`
<div className="navbar HamburgerMenu">
<button id="kb-nav-menu"
className="btn btn-default navbar-btn kb-nav-btn"
data-toggle="dropdown"
aria-haspopup="true">
<span className="fa fa-navicon"></>
</button>
<ul className="dropdown-menu"
role="menu"
aria-labeledby="kb-nav-menu">
${menuContent}
</ul>
</div>
`;
}
}
return HamburgerMenu;
});
|
import SagaRef from './SagaRef'
export default SagaRef
|
/**
* rollup-demo v1.0.0
* rollup技术分享
* author :
* homepage : https://github.com/HuYuee/rollup-demo#readme
* bugs : https://github.com/HuYuee/rollup-demo/issues
*/
(function (exports) {
'use strict';
var xx = function xx() {
console.log('its test is xx !');
};
exports.xx = xx;
}((this.bar = this.bar || {})));
|
'use strict';
var _express = require('express');
var _express2 = _interopRequireDefault(_express);
var _bodyParser = require('body-parser');
var _bodyParser2 = _interopRequireDefault(_bodyParser);
var _webpack = require('webpack');
var _webpack2 = _interopRequireDefault(_webpack);
var _mongodbUri = require('mongodb-uri');
var _mongodbUri2 = _interopRequireDefault(_mongodbUri);
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
var _webpackConfig = require('../webpack.config.dev');
var _webpackConfig2 = _interopRequireDefault(_webpackConfig);
var _open = require('open');
var _open2 = _interopRequireDefault(_open);
var _mongoose = require('mongoose');
var _mongoose2 = _interopRequireDefault(_mongoose);
var _routes = require('../src/routes/routes');
var _routes2 = _interopRequireDefault(_routes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var app = (0, _express2.default)();
/* eslint-disable no-console */
_mongoose2.default.Promise = global.Promise;
var mongodbUri = process.env.MONGODB_URI || 'mongodb://localhost/swapple';
var mongooseUri = _mongodbUri2.default.formatMongoose(mongodbUri);
var options = {
server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } },
replset: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } }
};
_mongoose2.default.connect(mongooseUri, options);
var port = process.env.PORT || 3000;
var PROD = process.env.NODE_ENV === 'production';
app.use(_bodyParser2.default.urlencoded({ extended: false }));
app.use(_bodyParser2.default.json());
app.use(_express2.default.static('public'));
if (PROD) {
app.use('/', _express2.default.static('dist'));
} else {
// When not in production, enable hot reloading
var compiler = (0, _webpack2.default)(_webpackConfig2.default);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: _webpackConfig2.default.output.publicPath
}));
app.use(require('webpack-hot-middleware')(compiler));
}
app.use('/', _routes2.default);
app.get('/', function (req, res) {
res.sendFile(_path2.default.join(__dirname, '../public/index.html'));
});
app.listen(port, function (err) {
if (err) {
console.log(err);
} else if (!PROD) {
console.log(('Starting app in dev mode, listening on port ' + port).green);
(0, _open2.default)('http://localhost:' + port);
} else {
console.log('Starting app in production mode, listening on port ' + port);
}
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:4e0bb78b5321b4c7593af74c6d78ed63a20b5f0f1cb53f5999b8d4df21ac58d5
size 64957
|
version https://git-lfs.github.com/spec/v1
oid sha256:bd007d14e85c7bd1f88ed952a39d9547396c6cddef6249e4b6113dfbceb6b91a
size 3094
|
var dispatcher = require('../dispatcher')
var constants = require('../constants/ChatConstants')
var ChatActionCreator = {
receiveIncomingMessage: function (fromId, message) {
dispatcher.handleViewAction(
this._getIncomingMessageAction(fromId, message)
)
},
viewMessages: function (fromId) {
dispatcher.handleViewAction(
this._getViewMessagesAction(fromId)
)
},
/**
* Action object creators. These are exposed for unit
* testing purposes, but should not be accessed from
* outside the module, hence the _ prefix.
*/
_getIncomingMessageAction: function (fromId, message) {
return {
actionType: constants.INCOMING_MESSAGE,
fromId: fromId,
message: message
}
},
_getViewMessagesAction: function (fromId) {
return {
actionType: constants.VIEW_MESSAGES,
fromId: fromId
}
}
}
module.exports = ChatActionCreator
|
/* global Rembrandt, describe, it, beforeEach */
import path from 'path'
describe('Rembrandt', () => {
describe('#compare', () => {
describe('two transparent images', () => {
let imageA, imageB, rembrandt
beforeEach(() => {
imageA = path.resolve(__dirname, 'fixtures/transparency.png')
imageB = path.resolve(__dirname, 'fixtures/transparency.png')
rembrandt = new Rembrandt({
imageA: imageA,
imageB: imageB,
renderComposition: true,
maxOffset: 0,
maxThreshold: 0
})
})
it('should be fulfilled with passed = true', function (done) {
this.timeout(10000)
rembrandt.compare()
.then((result) => {
result.passed.should.be.true
result.differences.should.equal(0)
done()
})
.catch((e) => done(e))
})
})
})
})
|
import React from 'react'
const RecursiveDiv = ({ length, width }) => {
if (length <= 0) return <span>I am a leaf. </span>
let children = []
for (let i = 0; i < width; i++) {
children.push(<RecursiveDiv key={i} length={length - 1} width={width} />)
}
return <div>{children}</div>
}
export default RecursiveDiv
|
var APP = APP || {};
APP.STATE_MACHINE = (function () {
// 'constants'
var STATES = ['WELCOME', 'SHOWBALL', 'HIDEBALL', 'SHUFFLE', 'GUESS', 'GUESSWASWRONG', 'GUESSWRONGAGAIN', 'GUESSWASRIGHT', 'PLAYAGAIN'];
var currentState;
var init = function () {
currentState = STATES[0];
callStateAction(currentState);
}
function transitionToNextState () {
var newState;
if (currentState == STATES[STATES.length - 1]) { // last state, start with the first one again
newState = STATES[1];
}
else if (currentState == 'GUESS') {
var errorString = "Cannot automatically transition to next state from state 'GUESS'."
+ " Transition has to be made explicitely depending on right or wrong guess.";
throw new Error(errorString);
}
else {
STATES.forEach(function (state, stateIndex) {
if (currentState == state) {
newState = STATES[stateIndex + 1];
}
});
}
currentState = newState;
callStateAction(newState);
}
function callStateAction (state) {
if (typeof state != "string") {
throw new Error("callStateAction must be called with a string as argument");
}
else {
APP.STATE_ACTIONS[state.toLowerCase() + "Action"](transitionToNextState);
}
}
var actionButtonClickHandler = function () {
transitionToNextState();
};
// pass true to this handler if the user made the right guess, false otherwise
var shellContainerClickHandler = function (wasRightGuess) {
var newState;
if (currentState == 'GUESSWASWRONG' && !wasRightGuess) {
newState = 'GUESSWRONGAGAIN';
}
else {
newState = wasRightGuess ? 'GUESSWASRIGHT' : 'GUESSWASWRONG'
}
currentState = newState;
callStateAction(newState);
};
var getCurrentState = function () {
return currentState;
};
var module = {};
module.init = init;
module.actionButtonClickHandler = actionButtonClickHandler;
module.shellContainerClickHandler = shellContainerClickHandler;
module.getCurrentState = getCurrentState;
return module;
})();
|
require('babel-polyfill');
import fs from 'fs';
import path from 'path';
import webpack from 'webpack';
import HardSourceWebpackPlugin from 'hard-source-webpack-plugin';
import StatsPlugin from 'stats-webpack-plugin';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import WebpackIsomorphicToolsConfig from './webpack-isomorphic-tools';
import CleanPlugin from 'clean-webpack-plugin';
import ResourceHintWebpackPlugin from 'resource-hints-webpack-plugin';
import WebpackIsomorphicToolsPlugin from 'webpack-isomorphic-tools/plugin';
import strip from 'strip-loader';
const projectRootPath = path.resolve(__dirname, '../');
const context = path.resolve(__dirname, '../');
const assetsPath = path.resolve(projectRootPath, './static/dist');
const webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(
WebpackIsomorphicToolsConfig
);
const babelrc = fs.readFileSync('./.babelrc');
let babelLoaderQuery = {};
try {
babelLoaderQuery = JSON.parse(babelrc);
} catch (err) {
console.error('==> ERROR: Error parsing your .babelrc.');
console.error(err);
}
babelLoaderQuery.plugins = [
[
'react-css-modules',
{
context,
webpackHotModuleReloading: false,
generateScopedName: '[hash:base64]'
}
],
...babelLoaderQuery.plugins
];
export default {
context,
devtool: 'source-map',
entry: { main: ['./app/client.js'] },
output: {
path: assetsPath,
filename: '[name]-[chunkhash].js',
chunkFilename: '[name]-[chunkhash].js',
publicPath: '/'
},
module: {
rules: [
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader:
'url-loader?limit=10000&mimetype=image/svg+xml!image-webpack-loader?bypassOnDebug&optimizationLevel=7&interlaced=false'
},
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: JSON.stringify(babelLoaderQuery)
}
]
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
sourceMap: true,
importLoaders: 1,
modules: true
}
},
{
loader: 'postcss-loader',
options: {
config: {
path: path.resolve(__dirname, './postcss.config.js')
}
}
}
]
// publicPath: "/assets" // Overrides output.publicPath
})
}
]
},
resolve: {
modules: ['src', 'node_modules'],
extensions: ['*', '.json', '.js', '.jsx'],
alias: {
react: path.resolve(__dirname, '../node_modules/react'),
'react-dom': path.resolve(__dirname, '../node_modules/react-dom'),
}
},
plugins: [
new HardSourceWebpackPlugin({
cacheDirectory: path.resolve(__dirname, '../node_modules/.cache/hard-source/prod/[confighash]'),
recordsPath: path.resolve(__dirname, '../node_modules/.cache/hard-source/prod/[confighash]/records.json'),
configHash: require('node-object-hash')({ sort: false }).hash
}),
new webpack.LoaderOptionsPlugin({
minimize: true,
debug: false,
options: { context }
}),
new CleanPlugin([assetsPath], { root: projectRootPath }),
new ExtractTextPlugin({
filename: '[name]-[chunkhash].css',
allChunks: true,
ignoreOrder: true
}),
new webpack.DefinePlugin({
'process.env': { NODE_ENV: '"production"' },
__CLIENT__: true,
__SERVER__: false,
__DEVELOPMENT__: false,
__DEVTOOLS__: false
}),
// ignore dev config
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.IgnorePlugin(/\.\/dev/, /\/config$/),
new webpack.ProvidePlugin({ React: 'react' }),
// optimizations
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
parallel: {
cache: true,
workers: 2
}
}),
new HtmlWebpackPlugin({
inject: 'body',
favicon: path.resolve(__dirname, '..', 'static', 'favicon.ico'),
filename: 'index.html',
template: path.resolve(__dirname, '..', 'static', 'template.html'),
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
removeAttributeQuotes: true,
collapseBooleanAttributes: true
}
}),
new ResourceHintWebpackPlugin(),
webpackIsomorphicToolsPlugin
]
};
|
var mout = require('mout');
var Q = require('q');
var endpointParser = require('apella-endpoint-parser');
var PackageRepository = require('../core/PackageRepository');
var defaultConfig = require('../config');
function info(logger, endpoint, property, config) {
if (!endpoint) {
return;
}
// handle @ as version divider
endpoint = endpoint.replace('@', '#');
var repository;
var decEndpoint;
config = defaultConfig(config);
repository = new PackageRepository(config, logger);
decEndpoint = endpointParser.decompose(endpoint);
return Q.all([
getPkgMeta(repository, decEndpoint, property),
decEndpoint.target === '*' && !property ? repository.versions(decEndpoint.source) : null
])
.spread(function (pkgMeta, versions) {
if (versions) {
return {
name: decEndpoint.source,
versions: versions,
latest: pkgMeta
};
}
return pkgMeta;
});
}
function getPkgMeta(repository, decEndpoint, property) {
return repository.fetch(decEndpoint)
.spread(function (canonicalDir, pkgMeta) {
pkgMeta = mout.object.filter(pkgMeta, function (value, key) {
return key.charAt(0) !== '_';
});
// Retrieve specific property
if (property) {
pkgMeta = mout.object.get(pkgMeta, property);
}
return pkgMeta;
});
}
// -------------------
info.readOptions = function (argv) {
var cli = require('../util/cli');
var options = cli.readOptions(argv);
var pkg = options.argv.remain[1];
var property = options.argv.remain[2];
return [pkg, property];
};
module.exports = info;
|
var CompletableFuture = require('./CompletableFuture');
function reduce(context) {
return new CompletableFuture(context);
}
function parallel(context) {
return new CompletableFuture(context, {
parallel : true
});
}
module.exports = {
reduce : reduce,
parallel : parallel,
CompletableFuture : CompletableFuture,
};
|
var onRun = function(context) {
var ga = require("../modules/Google_Analytics");
ga("Development");
var doc = context.document;
if (!doc.fileURL()) {
NSWorkspace.sharedWorkspace().openFile_withApplication_(nil, "Terminal");
} else {
var fileFolder = doc.fileURL().path().stringByDeletingLastPathComponent();
NSWorkspace.sharedWorkspace().openFile_withApplication_(fileFolder, "Terminal");
}
};
|
(function(){
angular
.module('VideoclubApp', ['ngMaterial', 'chart.js', 'routes', 'users', 'income', 'dashboard'])
.config(function($mdThemingProvider, $mdIconProvider){
$mdIconProvider
.defaultIconSet("./assets/svg/avatars.svg", 128)
.icon("menu" , "./assets/svg/menu.svg" , 24)
.icon("share" , "./assets/svg/share.svg" , 24)
.icon("google_plus", "./assets/svg/google_plus.svg" , 512)
.icon("hangouts" , "./assets/svg/hangouts.svg" , 512)
.icon("twitter" , "./assets/svg/twitter.svg" , 512)
.icon("phone" , "./assets/svg/phone.svg" , 512);
$mdThemingProvider.theme('default');
});
})();
|
"use strict";
var test = "should green";
|
import React from 'react';
import styled from 'styled-components';
var background = 'url(../static/title.png)';
const T = styled.h1`
font-size: 1rem;
height: 37px;
width: 150px;
background-image: ${background};
top: 70px;
position: relative;
`;
function Title (props) {
return(
<T>
{ props.name }
</T>
)
}
export default Title;
|
(function() {
'use strict';
/* var app = angular.module('examples', ['chart.js', 'ui.bootstrap']);*/
app.config(function(ChartJsProvider) {
// Configure all charts
ChartJsProvider.setOptions({
colours: ['#FF6E40', '#FBC02E', '#673AB7', '#66bd78', '#f05050'],
responsive: true
});
// Configure all doughnut charts
ChartJsProvider.setOptions('Doughnut', {
animateScale: true
});
});
app.controller('MenuCtrl', function($scope) {
$scope.isCollapsed = true;
$scope.charts = ['Line', 'Bar', 'Doughnut', 'Pie', 'Polar Area', 'Radar', 'Base'];
});
app.controller('SalePassingCtrl', ['$scope', '$timeout', function($scope, $timeout) {
$scope.options = {
scaleShowVerticalLines: false
};
$scope.labels = ['2009', '2010', '2011', '2012', '2013', '2014', '2015'];
$scope.series = ['Series A', 'Series B'];
$scope.data = [
[4500, 5100, 5000, 6100, 1600, 3500, 4500],
[7800, 8800, 3000, 4900, 5600, 6000, 3000]
];
$scope.colours = [{ // grey
fillColor: "#54bc97",
strokeColor: "#54bc97",
highlightFill: "#54bc97",
highlightStroke: "#54bc97"
}, { // dark grey
fillColor: "#00797c",
strokeColor: "#00797c",
highlightFill: "#00797c",
highlightStroke: "#00797c"
}];
$timeout(function() {
$scope.options = {
scaleShowVerticalLines: true
};
}, 3000);
}]);
app.controller('SaleSurveyCtrl', ['$scope', '$timeout', function($scope, $timeout) {
$scope.labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];
$scope.series = ['Quality of Products', 'Quality of Vendors','Quality of Delivery'];
$scope.data = [
[78, 88, 90, 79, 86, 97, 90],
[85, 89, 80, 81, 76, 75, 80],
[88, 90, 90, 69, 76, 57, 80]
];
$scope.onClick = function(points, evt) {
console.log(points, evt);
};
$scope.onHover = function(points) {
if (points.length > 0) {
console.log('Point', points[0].value);
} else {
console.log('No point');
}
};
$scope.colours = [{ // grey
fillColor: "rgba(84,188,151,0.5)",
strokeColor: "#54bc97",
pointColor: "#54bc97",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "#54bc97"
}, { // dark grey
fillColor: "rgba(0,121,124,0.5)",
strokeColor: "#00797c",
pointColor: "#00797c",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "#00797c"
}, { // dark grey
fillColor: "rgba(253,180,93,0.5)",
strokeColor: "#fdb45d",
pointColor: "#fdb45d",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "#fdb45d"
}];
}]);
app.controller('SaleSatisfactionCtrl', ['$scope', '$timeout', function($scope, $timeout) {
$scope.options = {
scaleShowVerticalLines: false
};
$scope.labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];
$scope.series = ['Series A', 'Series B','Series C'];
$scope.data = [
[81, 80, 81, 86, 75],
[88, 90, 99, 56, 77],
[91, 70, 61, 66, 55],
];
$scope.colours = [{ // grey
fillColor: "#54bc97",
strokeColor: "#54bc97",
highlightFill: "#54bc97",
highlightStroke: "#54bc97"
}, { // dark grey
fillColor: "#00797c",
strokeColor: "#00797c",
highlightFill: "#00797c",
highlightStroke: "#00797c"
}, { // dark grey
fillColor: "#fdb45d",
strokeColor: "#fdb45d",
highlightFill: "#fdb45d",
highlightStroke: "#fdb45d"
}];
$timeout(function() {
$scope.options = {
scaleShowVerticalLines: true
};
}, 3000);
}]);
app.controller('SaleTestScoreCtrl', ['$scope', '$timeout', function($scope, $timeout) {
$scope.labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];
$scope.series = ['Buyers', 'Sellers'];
$scope.data = [
[165, 169, 170, 181, 76, 45, 150],
[168, 160, 190, 189, 76, 157, 70]
];
$scope.onClick = function(points, evt) {
console.log(points, evt);
};
$scope.onHover = function(points) {
if (points.length > 0) {
console.log('Point', points[0].value);
} else {
console.log('No point');
}
};
$scope.colours = [{ // grey
fillColor: "rgba(84,188,151,0)",
strokeColor: "#54bc97",
pointColor: "#54bc97",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "#54bc97"
}, { // dark grey
fillColor: "rgba(0,121,124,0)",
strokeColor: "#00797c",
pointColor: "#00797c",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "#00797c"
}];
}]);
function getRandomValue(data) {
var l = data.length,
previous = l ? data[l - 1] : 50;
var y = previous + Math.random() * 10 - 5;
return y < 0 ? 0 : y > 100 ? 100 : y;
}
})();
|
module.exports = {
"env": {
"mocha": true
}
};
|
export default (mongoose) => {
mongoose.Query.prototype.field = function (options) {
let query = this;
if (options && options.filters && options.filters.field) {
if (typeof options.filters.field === 'string' && /\,/g.test(options.filters.field)) {
options.filters.field = options.filters.field.split(/\,/g);
}
if (Array.isArray(options.filters.field) && options.filters.field.length) {
options.filters.field.forEach((field) => {
if (query.model.schema.path(field)) {
query.select(field.trim());
}
});
} else if (query.model.schema.path(options.filters.field)) {
query.select(options.filters.field.trim());
}
}
return query;
};
};
|
import { uiModel, dataModel } from '../model'
export async function loadProps() {
const pageInfo = uiModel.get('articleList.pageInfo')
const { pageNum, pageSize } = pageInfo
const articles = await dataModel.get('articles')
return {
articles: articles.slice((pageNum - 1) * pageSize, pageNum * pageSize),
pageInfo,
totalSize: articles.length,
}
}
export function changePageInfo(newPageInfo) {
const pageInfo = uiModel.get('articleList.pageInfo')
uiModel.set('articleList.pageInfo', { ...pageInfo, ...newPageInfo })
}
|
const modulesWrappers = require('../models/modelWrappers');
// number of parties in a chunk
const partiesPerBatch = 4;
function Chunker(computation_id) {
this.computation_id = computation_id;
}
// initialize
Chunker.prototype.init = async function (jiff) {
// submitters
this.submitters = await jiff._wrapper.getTrackerParties(this.computation_id);
// linearize order of parties in an order matching the computation order
this.parties = this.submitters['none'].slice();
for (var cohort of this.submitters['cohorts']) {
this.parties = this.parties.concat(this.submitters[cohort]);
}
this.parties.push('s1');
// index into parties array
this.index = 0;
this.serverSlice = 2; // number of messages to slice from server
this.lastServerBatchSize = 0;
};
// get 'public_keys' and 'custom' messages!
Chunker.prototype.initMessages = async function () {
return await modulesWrappers.Mailbox.query(this.computation_id, 1, 0, 2, { from_id: 's1' });
};
// chunk: create a chunk of messages and return it
Chunker.prototype.chunk = async function () {
// in case done
if (this.index >= this.parties.length) {
return [];
}
// not done yet!
var messages = [];
if (this.index === this.parties.length - 1) { // keep all messages from 's1' in one chunk!
messages = await modulesWrappers.Mailbox.query(this.computation_id, 1, this.serverSlice, null, { from_id: 's1' });
this.lastServerBatchSize = messages.length;
} else {
var count = Math.min(this.parties.length - 1, this.index + partiesPerBatch);
for (var i = this.index; i < count; i++) {
var party_id = this.parties[i];
var data = await modulesWrappers.Mailbox.query(this.computation_id, 1, null, null, { from_id: party_id });
messages = messages.concat(data);
}
}
if (this.index === 0) {
messages = (await this.initMessages()).concat(messages);
}
return messages;
};
// Slice: move marker up so that the next call to chunk returns the next chunk
Chunker.prototype.slice = function () {
if (this.index >= this.parties.length - 1) {
this.index = this.parties.length - 1;
this.serverSlice += this.lastServerBatchSize;
this.lastServerBatchSize = 0;
} else {
this.index = Math.min(this.index + partiesPerBatch, this.parties.length - 1);
}
};
module.exports = Chunker;
|
const {expect} = require('chai');
const {Spacedoc} = require('..');
const mockVinyl = require('./util/mock-vinyl');
const TEST_FILE = mockVinyl('test/fixtures/example.md');
const TEST_FILE_ALT = mockVinyl('test/fixtures/example-alt-layout.md');
describe('Spacedoc.build()', () => {
it('builds an HTML file from the data of a page', () => {
const s = new Spacedoc().config({
theme: 'test/fixtures/theme'
});
const output = s.build({kittens: 'kittens', meta: {}});
expect(output).to.be.a('string');
expect(output).to.contain('<p>kittens');
});
it('throws Pug errors', () => {
const s = new Spacedoc().config({
theme: 'test/fixtures/theme-broken'
});
expect(s.build).to.throw(Error);
});
it('allows Front Matter to be retained on the page', () => {
const s = new Spacedoc().config({
theme: 'test/fixtures/theme',
keepFm: true
});
return expect(s.parse(TEST_FILE).then(data => s.build(data))).to.eventually.contain('---');
});
it('allows an alternate layout to be used', () => {
const s = new Spacedoc().config({
theme: 'test/fixtures/theme'
});
return expect(s.parse(TEST_FILE_ALT).then(data => s.build(data))).to.eventually.contain('<p>Puppies');
});
});
|
var connect = require('connect');
connect.createServer(
connect.static('public')
).listen(8000);
|
/*global $*/
(function happyJS($) {
function trim(el) {
return (''.trim) ? el.val().trim() : $.trim(el.val());
}
$.fn.isHappy = function isHappy(config) {
var fields = [], item;
var pauseMessages = false;
function isFunction(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
}
function defaultError(error) { //Default error template
var msgErrorClass = config.classes && config.classes.message || 'unhappyMessage';
return $('<span id="' + error.id + '" class="' + msgErrorClass + '" role="alert">' + error.message + '</span>');
}
function getError(error) { //Generate error html from either config or default
if (isFunction(config.errorTemplate)) {
return config.errorTemplate(error);
}
return defaultError(error);
}
function handleSubmit() {
var i, l;
var errors = false;
for (i = 0, l = fields.length; i < l; i += 1) {
if (!fields[i].testValid(true)) {
errors = true;
}
}
if (errors) {
if (isFunction(config.unHappy)) config.unHappy();
return false;
} else if (config.testMode) {
if (isFunction(config.happy)) return config.happy();
if (window.console) console.warn('would have submitted');
return false;
}
if (isFunction(config.happy)) return config.happy();
}
function handleMouseUp() {
pauseMessages = false;
}
function handleMouseDown() {
pauseMessages = true;
$(window).bind('mouseup', handleMouseUp);
}
function processField(opts, selector) {
var field = $(selector);
var error = {
message: opts.message || '',
id: selector.slice(1) + '_unhappy'
};
var errorEl = $(error.id).length > 0 ? $(error.id) : getError(error);
var handleBlur = function handleBlur() {
if (!pauseMessages) {
field.testValid();
} else {
$(window).bind('mouseup', field.testValid.bind(this));
}
};
fields.push(field);
field.testValid = function testValid(submit) {
var val, gotFunc, temp;
var el = $(this);
var errorTarget = (opts.errorTarget && $(opts.errorTarget)) || el;
var error = false;
var required = !!el.get(0).attributes.getNamedItem('required') || opts.required;
var password = (field.attr('type') === 'password');
var arg = isFunction(opts.arg) ? opts.arg() : opts.arg;
var fieldErrorClass = config.classes && config.classes.field || 'unhappy';
// handle control groups (checkboxes, radio)
if (el.length > 1) {
val = [];
el.each(function(i,obj) {
val.push($(obj).val());
});
val = val.join(',');
} else {
// clean it or trim it
if (isFunction(opts.clean)) {
val = opts.clean(el.val());
} else if (!password && typeof opts.trim === 'undefined' || opts.trim) {
val = trim(el);
} else {
val = el.val();
}
// write it back to the field
el.val(val);
}
// get the value
gotFunc = ((val.length > 0 || required === 'sometimes') && isFunction(opts.test));
// check if we've got an error on our hands
if (submit === true && required === true && val.length === 0) {
error = true;
} else if (gotFunc) {
error = !opts.test(val, arg);
}
if (error) {
errorTarget.addClass(fieldErrorClass).after(errorEl);
return false;
} else {
temp = errorEl.get(0);
// this is for zepto
if (temp.parentNode) {
temp.parentNode.removeChild(temp);
}
errorTarget.removeClass(fieldErrorClass);
return true;
}
};
field.bind(opts.when || config.when || 'blur', handleBlur);
}
for (item in config.fields) {
processField(config.fields[item], item);
}
$(config.submitButton || this).bind('mousedown', handleMouseDown);
if (config.submitButton) {
$(config.submitButton).click(handleSubmit);
} else {
this.bind('submit', handleSubmit);
}
return this;
};
})(this.jQuery || this.Zepto);
var happy = {
USPhone: function (val) {
return /^\(?(\d{3})\)?[\- ]?\d{3}[\- ]?\d{4}$/.test(val);
},
// matches mm/dd/yyyy (requires leading 0's (which may be a bit silly, what do you think?)
date: function (val) {
return /^(?:0[1-9]|1[0-2])\/(?:0[1-9]|[12][0-9]|3[01])\/(?:\d{4})/.test(val);
},
email: function (val) {
return /^(?:\w+\.?\+?)*\w+@(?:\w+\.)+\w+$/.test(val);
},
minLength: function (val, length) {
return val.length >= length;
},
maxLength: function (val, length) {
return val.length <= length;
},
equal: function (val1, val2) {
return (val1 == val2);
}
};
|
import { CLEAR_ERROR } from '../actions/Error'
import { REJECT_ACCOUNTS } from '../actions/Accounts'
import { REJECT_TRANSACTIONS } from '../actions/Transactions'
const error = (state = {
type: null,
description: null
}, action) => {
switch (action.type) {
case REJECT_ACCOUNTS:
case REJECT_TRANSACTIONS:
return {
...state,
type: action.error.code,
description: action.error.message
}
case CLEAR_ERROR:
return {
...state,
type: null,
description: null
}
default:
return state
}
}
export default error
|
angular.module('app.main.agent', ['app.main.agent.route', 'app.main.agent.sidebar', 'app.main.agent.bwl'])
.controller('AgentCtrl', function($scope, $state, AgentState) {
$scope.$on('$stateChangeSuccess', function(e, toState) {
$scope.currentState = toState;
// TODO reload data
});
$state.go(AgentState.BWL);
});
|
/* main collection class - handles all filtering and searching */
bbGrid.Collection = Backbone.Collection.extend({
initialize: function(models, options) {
console.log('bbGrid.Collection.initialize()');
/* if (!_.isEmpty(models)) {
this.parse(models);
} */
console.info(this);
},
filtered: [],
fullJson: [],
refreshCollection: function(e) {
this.filtered = this.fullJson = this.toJSON();
console.info(this);
},
filters: {},
// should not be aware of columns and stuff
applyFilter: function (key, text, customFilter) {
if (text == '') delete this.filters[key];
else this.filters[key] = text;
this.reset(this.fullJson,{silent:true}); // reset it to start off
if (!_.isEmpty(this.filters)) {
// how to reset it each time
_.each(_.keys(this.filters), function(key) {
var match = this.filters[key];
this.filtered = _.filter(this.models, function (model) {
if (customFilter) return customFilter(model,match);
var val = model.get(key);
if (val) {
return ("" + val).toLowerCase().indexOf(match.toLowerCase()) >= 0;
} else {
return false;
}
});
this.reset(this.filtered,{silent:true});
},this);
}
if (this.searchText != '') {
this.filtered = _.filter(this.models, function (model) {
var matches = false;
var log = '** searching model '+model.get('nameFirst')+' ' +model.get('nameLast')+' for '+this.searchText;
_.each(this.searchCriteria, function (criteria) {
if (matches === false) {
if (criteria.search !== false) {
matches = criteria.search(model,this.searchText);
} else { // default search
origVal = model.get(criteria.property);
if( _.isUndefined(origVal) ) {
matches = false;
} else {
if( !_.isString(origVal) ) {
origVal = '' + origVal; // convert to string
}
var val = origVal.toLowerCase().trim();
matches = val && ( val.indexOf(this.searchText.toLowerCase().trim(), 0) >= 0 );
}
}
}
},this);
return matches;
},this);
this.reset(this.filtered,{silent:true});
}
this.trigger('reset');
},
searchText: '',
searchCriteria: [],
search: function(text) {
// apply filters to the full list first, then search within
if (this.searchText != text) {
this.searchText = text;
this.applyFilter('bogus','');
}
}
});
|
function bindInitialFunctions() {
$("#alert-div").bs3Alert();
$(".generateBingoCard").click(createBingoCard);
bindBingoCellFunctions();
$("#export-nav-item").click(function (event){
$("#inputExport").val(settings.exportString());
});
$("#import-bingo-card").click(function (event){
importBingoCard($("#inputImport").val());
});
}
function bindBingoCellFunctions() {
$(".clickable").click(function (event){
toggleBingoCellState($(this));
updateAndPublishStats(settings, stats);
});
}
function toggleBingoCellState(cell) {
if (cell.css("text-decoration") !== "line-through") {
cell.css("text-decoration", "line-through");
} else {
cell.css("text-decoration", "none");
}
}
function publishStats(settings, stats) {
var progress = 0;
if (settings.properties.size > 0 ) {
progress = ((stats.checkedCells / Math.pow(settings.properties.size, 2)) * 100).toFixed(2);
}
$("#completion-bar").attr("aria-valuenow", progress*100);
$("#completion-bar").css("width", progress+"%");
$("#completion-bar").html(progress+"%");
$("#cells-stats").html(stats.checkedCells + "/" + Math.pow(settings.properties.size, 2));
$("#lines-stats").html(stats.completedLines + "/" + stats.possibleLines.length);
if(stats.isFullHouse()) {
$("#full-house-stats").html("Full House!");
} else {
$("#full-house-stats").html("No.");
}
}
|
require('babel-register')();
/*
|--------------------------------------------------------------------------
| generators/index.js
|--------------------------------------------------------------------------
|
| Exports the generators so plop knows them
|
*/
const fs = require('fs');
const componentGenerator = require('./component/index.js');
const containerGenerator = require('./container/index.js');
const routeGenerator = require('./route/index.js');
const languageGenerator = require('./language/index.js');
module.exports = (plop) => {
plop.setGenerator('component', componentGenerator);
plop.setGenerator('container', containerGenerator);
plop.setGenerator('route', routeGenerator);
plop.setGenerator('language', languageGenerator);
plop.addHelper('directory', (comp) => {
try {
fs.accessSync(`app/containers/${comp}`, fs.F_OK);
return `containers/${comp}`;
} catch (e) {
return `components/${comp}`;
}
});
plop.addHelper('curly', (object, open) => (open ? '{' : '}'));
};
|
import { action, get, set } from '@ember/object';
import { inject as service } from '@ember/service';
import { Promise } from 'rsvp';
import TabRoute from 'ember-inspector/routes/tab';
export default class RenderTreeRoute extends TabRoute {
@service port;
model() {
const port = this.port;
return new Promise(function (resolve) {
port.one('render:profilesAdded', function (message) {
resolve(message.profiles);
});
port.send('render:watchProfiles');
});
}
setupController(controller, model) {
super.setupController(...arguments);
if (model.length === 0) {
controller.set('initialEmpty', true);
}
const port = this.port;
port.on('render:profilesUpdated', this, this.profilesUpdated);
port.on('render:profilesAdded', this, this.profilesAdded);
}
deactivate() {
const port = this.port;
port.off('render:profilesUpdated', this, this.profilesUpdated);
port.off('render:profilesAdded', this, this.profilesAdded);
port.send('render:releaseProfiles');
}
profilesUpdated(message) {
set(this, 'controller.model', message.profiles);
}
profilesAdded(message) {
const model = get(this, 'controller.model');
const profiles = message.profiles;
model.pushObjects(profiles);
if (model.length > 100) {
set(this, 'controller.model', model.slice(0, 100));
}
}
@action
clearProfiles() {
this.port.send('render:clear');
}
}
|
/**
* This file is part of Wizkers.io
*
* The MIT License (MIT)
* Copyright (c) 2016 Edouard Lafargue, ed@wizkers.io
*
* 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.
*/
/**
* A Fluke 287/289 series instrument. This
* object implements a standard API shared by all instrument
* objects:
*
* @author Edouard Lafargue, ed@lafargue.name
*/
define(function(require) {
"use strict";
var driver_frontend = require('app/instruments/fluke28x/driver_frontend');
return function() {
// Helper function: get driver capabilites.
// returns a simple array of capabilities
this.getCaps = function() {
return ["LiveDisplay", "LogManagementView", "NumDisplay", "DiagDisplay", "LogView"];
};
// Return the type of data reading that this instrument generates. Can be used
// by output plugins to accept data from this instrument or not.
this.getDataType = function() {
return [ "voltage", "current", "capacity", "resistance", "temperature" ];
}
// This has to be a Backbone view
this.getLiveDisplay = function(arg, callback) {
require(['app/instruments/fluke28x/display_live'], function(view) {
callback(new view(arg));
});
};
// This is a Backbone view
// This is a numeric display
this.getNumDisplay = function(arg, callback) {
require(['app/instruments/fluke28x/display_numeric'], function(view) {
callback(new view(arg));
});
};
// A diagnostics/device setup screen
this.getDiagDisplay = function(arg, callback) {
require(['app/instruments/fluke28x/display_diag'], function(view) {
callback(new view(arg));
});
};
// This has to be a link manager
this.getDriver = function() {
return new driver_frontend();
};
// This is a browser implementation of the backend driver, when we
// run the app fully in-browser on as a Cordova native app.
this.getBackendDriver = function(arg, callback) {
require(['app/instruments/fluke28x/driver_backend'], function(driver) {
callback(new driver(arg));
});
};
// Return a Backbone view which is a mini graph
this.getMiniLogview = function(arg, callback) {
return null;
};
// Return a device log management view
this.getLogManagementView = function(arg, callback) {
require(['app/instruments/fluke28x/display_logmanager'], function(view) {
callback(new view(arg));
});
}
// Render a log (or list of logs) for the device.
this.getLogView = function(arg, callback) {
require(['app/instruments/fluke28x/display_log'], function(view) {
callback(new view(arg));
});
}
};
});
|
// Including and starting all inclusions
var express = require("express")
, app = express()
, bodyParser = require('body-parser')
, path = require('path')
, request = require('request')
, program = require('commander')
.version('0.0.1')
.option('-p, --port [value]', 'port')
.parse(process.argv)
, serverPort = program.port || 5446
, server = require('http').createServer(app).listen(serverPort)
app.use(express.static(__dirname + '/app'));
app.use(bodyParser.json({limit: '2mb'})); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({extended: true,limit: '2mb'})); // to support URL-encoded bodies
app.use(function(req,res,next){
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT");
next();
});
// ======================= START INITIALIZATION PROCESS ======================= //
console.log("######################################");
console.log("# SmartHome - Version : 0.5");
console.log("# Bayit Project");
console.log("# By @cyberwarfighte1 (Samuel LESPES CARDILLO)");
console.log("######################################");
console.log("[I] SmartHome started on port " + serverPort + " ...");
var core = require('./core/main');
core.initiate();
// ======================= START EXPRESS.JS API ======================= //
app.post('/',function(req,res){
var response = {
request: null,
answer : {
image: null,
voice: null,
text: null
}
}
console.log("[I] New command : " + req.body.order);
core.sendCommand(req.body, function(output) {
response = {
request: req.body.order,
answer: output
}
res.end(JSON.stringify(response));
});
})
|
const UserStore = require('app/alt/UserStore');
module.exports = {
path: 'users',
onEnter() {
console.log('ok');
UserStore.loadUsers(20);
},
onLeave() {
UserStore.flush();
},
getComponent(location, cb) {
require.ensure([], (require) => {
cb(null, require('app/pages/UsersPage'));
});
}
};
|
import React, { Component } from 'react'
import { StaticRouter as Router } from 'react-router'
import { connect } from 'react-redux'
import { push, replace } from './actions'
function mapStateToProps(state) {
return {
location: state.routing.location,
action: state.routing.action,
}
}
const mapDispatchToProps = {
onPush: push,
onReplace: replace,
}
const Wrapper = (props, context) => {
return (
<Router
location={props.location}
action={props.action}
onPush={props.onPush}
onReplace={props.onReplace}
>
{props.children}
</Router>
)
}
Wrapper.propTypes = {
location: React.PropTypes.object.isRequired,
action: React.PropTypes.string.isRequired,
onPush: React.PropTypes.func.isRequired,
onReplace: React.PropTypes.func.isRequired,
}
export default connect(mapStateToProps, mapDispatchToProps)(Wrapper)
|
import axios from 'axios';
import { reducer as notifReducer, actions as notifActions, Notifs } from 're-notif';
const { notifSend } = notifActions;
import notification from './notification';
import {hackathons} from './hackathons';
export const HACK = 'HACK';
export const UPDATE = 'UPDATE_HACK';
export const COMMENTS = 'COMMENTS';
// ------------------------------------
// Actions
// ------------------------------------
export function hack (value: Object): Action {
return {
type: HACK,
payload: value
};
}
export function update (value: Object): Action {
return {
type: UPDATE,
payload: value
};
}
export const fetchFromServer = (id) => (dispatch) => {
// TODO use config path instead
axios.get('/api/hacks/' + id)
.then((res) => {
dispatch(hack(res.data));
});
};
export const join = (hackEntity) => (dispatch) => {
axios.post('/api/hacks/' + hackEntity._id + "/join")
.then((res) => {
axios.get('/api/hacks/' + hackEntity._id)
.then((ress) => {
dispatch(hack(ress.data));
});
});
};
export const leave = (hackEntity) => (dispatch) => {
axios.post('/api/hacks/' + hackEntity._id + "/leave")
.then((res) => {
axios.get('/api/hacks/' + hackEntity._id)
.then((ress) => {
dispatch(hack(ress.data));
});
});
};
export const nominate = (hackEntity) => (dispatch) => {
axios.post('/api/hacks/' + hackEntity._id + "/nominate")
.then((res) => {
axios.get('/api/hacks/' + hackEntity._id)
.then((ress) => {
dispatch(hack(ress.data));
});
});
};
export const fetchHackathonsFromServer = () => (dispatch) => {
// TODO use config path instead
axios.get('/api/hackathons/')
.then((res) => {
dispatch(hackathons(res.data));
});
};
export const reset = () => (dispatch) => {
dispatch(hack({}));
};
export const updateToSever = (id, req) => (dispatch) => {
// TODO use config path instead
if(id) {
axios.put('/api/hacks/' + id, req)
.catch((res) => {
dispatch(notifSend(notification('Could not update', 'warning')));
})
.then((res) => {
if(res) {
dispatch(update(res.data));
dispatch(notifSend(notification(res.data.title + ' is now updated', 'success')));
}
});
} else {
axios.post('/api/hacks/', req)
.catch((res) => {
dispatch(notifSend(notification('Could not create hack', 'warning')));
})
.then((res) => {
if(res) {
dispatch(update(res.data));
dispatch(notifSend(notification(res.data.title + ' is now created', 'success')));
}
});
}
};
export const actions = {
fetchFromServer,
join,
leave,
nominate,
fetchHackathonsFromServer,
updateToSever,
reset
};
// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
[HACK]: (state: Object, action: {payload: Object}): Object => action.payload,
[UPDATE]: (state: Object, action: {payload: Object}) : Object => action.payload
};
// ------------------------------------
// Reducer
// ------------------------------------
const initialState = new Object();
export default function hackReducer (state: Object = initialState, action: Action): Object {
const handler = ACTION_HANDLERS[action.type];
return handler ? handler(state, action) : state;
}
|
$(document).ready(function () {
$('.PanelNotificationBox').css({ opacity: 0 });
$('.PanelNotificationBox').fadeTo("slow", 1.0);
setTimeout(function () {
$('.AutoHide').fadeOut('slow', function () {
$('.AutoHide').remove();
});
}, 3000);
});
|
'use strict';
module.exports = function(app) {
var users = require('../../app/controllers/users');
var owners = require('../../app/controllers/owners');
// Owners Routes
app.route('/owners')
.get(owners.list)
.post(users.requiresLogin, owners.create);
app.route('/owners/:ownerId')
.get(owners.read)
.put(users.requiresLogin, owners.hasAuthorization, owners.update)
.delete(users.requiresLogin, owners.hasAuthorization, owners.delete);
app.route('/ownerUpdate')
.put(owners.update);
app.route('/alterRoster/:ownerId')
.put(owners.alterRoster);
app.route('/spotChange/:ownerId')
.put(owners.spotChange);
app.route('/changePlayer')
.put(owners.changePlayer);
app.route('/ownerName/:ownerId')
.get(owners.getName);
app.route('/addCutPlayer')
.put(owners.addCutPlayer);
app.route('/executeTrade')
.put(owners.executeTrade);
app.route('/draftList')
.get(owners.draftList);
// Finish by binding the Owner middleware
app.param('ownerId', owners.ownerByID);
};
|
const initialize = require('./input');
const Compiler = require('./compile');
const Assembler = require('./assemble');
const bean = module.exports = {
Compiler, Assembler,
compile(source) {
return new bean.Compiler(source).binary;
},
assemble(binary) {
return new bean.Assembler(binary).tokens.join('');
},
program(binary) {
return (stdin = '') => {
const init = initialize(stdin);
const exec = bean.assemble(binary);
const body = (init + exec).replace(/["\\]/g, '\\$&').replace(/\r?\n/g, '\\n');
return new Function('', 'return eval("' + body + '")')();
};
},
};
|
Template.iframeDrive.helpers({
getIframeUri: function () {
return RocketChat.settings.get('MyDrive_IframeUrl');
}
});
|
export const API_BASE_URL = process.env.API_ROOT;
export const API_REQUEST = Symbol('API_REQUEST');
|
import chai from 'chai'
import path from 'path'
import sinonChai from'sinon-chai'
chai.use(sinonChai)
import sinon from 'sinon'
import {
coreUtils,
abeExtend,
cmsData,
config
} from '../../../../src/cli'
config.set({root: path.join(process.cwd(), 'tests', 'unit', 'fixtures')})
describe('coreUtils.array', function() {
var arr = [{'test': 'val'}, {'test2': 'val2'}];
var arrFacet = [{'a': 'vala', 'b': {'ba':'other'}}, {'a': 'valaprime', 'b': {'ba':'otherprime'}}];
it('coreUtils.array.find()', function() {
var result = coreUtils.array.find(arr, 'test', 'val');
chai.expect(result).to.be.a('array')
chai.expect(result.length).to.equal(1)
chai.expect(result[0]).to.equal(0)
var result2 = coreUtils.array.find(arr, 'test2', 'val2');
chai.expect(result2).to.be.a('array')
chai.expect(result2.length).to.equal(1)
chai.expect(result2[0]).to.equal(1)
});
it('coreUtils.array.facet()', function() {
var result = coreUtils.array.facet(arrFacet, ['a'], 'val');
chai.expect(result).to.be.a('array')
chai.expect(result.length).to.equal(2)
chai.expect(result[0]['a']).to.equal('vala')
result = coreUtils.array.facet(arrFacet, ['a', 'b.ba'], 'otherprime');
chai.expect(result).to.be.a('array')
chai.expect(result.length).to.equal(1)
chai.expect(result[0]['a']).to.equal('valaprime')
});
it('coreUtils.array.filter()', function() {
var result = coreUtils.array.filter(arr, 'test', 'val');
chai.expect(result).to.be.a('array')
chai.expect(result.length).to.equal(1)
chai.expect(result[0]).to.have.property('test')
chai.expect(result[0].test).to.equal('val')
});
it('coreUtils.array.removeByAttr()', function() {
var result = coreUtils.array.removeByAttr(arr, 'test2', 'val2');
chai.expect(result).to.be.a('array')
chai.expect(result.length).to.equal(1)
chai.expect(result[0]).to.have.property('test')
chai.expect(result[0].test).to.equal('val')
});
it('coreUtils.array.contains()', function() {
var testArray = ["test0", "test1", "test2"];
var result = coreUtils.array.contains(testArray, 'test1');
chai.expect(result).to.be.true
var result2 = coreUtils.array.contains(testArray, 'test3');
chai.expect(result2).to.be.false
});
});
|
import toInteger from '../_lib/toInteger/index.js'
import addQuarters from '../addQuarters/index.js'
/**
* @name subQuarters
* @category Quarter Helpers
* @summary Subtract the specified number of year quarters from the given date.
*
* @description
* Subtract the specified number of year quarters from the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of quarters to be subtracted
* @returns {Date} the new date with the quarters subtracted
* @throws {TypeError} 2 arguments required
*
* @example
* // Subtract 3 quarters from 1 September 2014:
* var result = subQuarters(new Date(2014, 8, 1), 3)
* //=> Sun Dec 01 2013 00:00:00
*/
export default function subQuarters(dirtyDate, dirtyAmount) {
if (arguments.length < 2) {
throw new TypeError(
'2 arguments required, but only ' + arguments.length + ' present'
)
}
var amount = toInteger(dirtyAmount)
return addQuarters(dirtyDate, -amount)
}
|
/// <reference types="mocha" />
const pkcs11 = require("pkcs11js");
const p11_crypto = require("node-webcrypto-p11");
const { Crypto } = require("@peculiar/webcrypto");
const assert = require("assert");
const config = require("./config");
context("EC", () => {
let mod = new pkcs11.PKCS11();;
let slot, session;
before(() => {
mod.load(config.lib);
mod.C_Initialize();
const slots = mod.C_GetSlotList();
slot = slots[0];
session = mod.C_OpenSession(slot, pkcs11.CKF_RW_SESSION | pkcs11.CKF_SERIAL_SESSION);
});
after(() => {
mod.C_CloseAllSessions(slot);
mod.C_Finalize();
});
context("GenerateKeyPair", () => {
it("#1", () => {
const privateTemplate = [
{ type: pkcs11.CKA_ID, value: new Buffer("1234567890") },
{ type: pkcs11.CKA_SIGN, value: true },
{ type: pkcs11.CKA_DERIVE, value: true },
];
const publicTemplate = [
{ type: pkcs11.CKA_ID, value: new Buffer("1234567890") },
{ type: pkcs11.CKA_EC_PARAMS, value: new Buffer("06082A8648CE3D030107", "hex") },
{ type: pkcs11.CKA_VERIFY, value: true },
{ type: pkcs11.CKA_DERIVE, value: true },
];
const keys = mod.C_GenerateKeyPair(session, { mechanism: pkcs11.CKM_ECDSA_KEY_PAIR_GEN, parameter: null }, publicTemplate, privateTemplate);
let attrs = mod.C_GetAttributeValue(session, keys.privateKey, [
{ type: pkcs11.CKA_TOKEN }
]);
});
});
context("Sign/Verify", () => {
let privateKey, publicKey;
before(() => {
const privateTemplate = [
{ type: pkcs11.CKA_ID, value: new Buffer("1234567890") },
{ type: pkcs11.CKA_SIGN, value: true },
];
const publicTemplate = [
{ type: pkcs11.CKA_ID, value: new Buffer("1234567890") },
{ type: pkcs11.CKA_EC_PARAMS, value: new Buffer("06082A8648CE3D030107", "hex") },
{ type: pkcs11.CKA_VERIFY, value: true },
];
const keys = mod.C_GenerateKeyPair(session, { mechanism: pkcs11.CKM_ECDSA_KEY_PAIR_GEN, parameter: null }, publicTemplate, privateTemplate);
privateKey = keys.privateKey;
publicKey = keys.publicKey;
});
context("ECDSA", () => {
[
"CKM_ECDSA_SHA1",
"CKM_ECDSA_SHA256",
"CKM_ECDSA_SHA384",
"CKM_ECDSA_SHA512",
]
.forEach((mech) => {
it(mech, () => {
const mechanism = { mechanism: pkcs11[mech], parameter: null };
mod.C_SignInit(session, mechanism, privateKey);
mod.C_SignUpdate(session, new Buffer("first"));
mod.C_SignUpdate(session, new Buffer("second"));
const signature = mod.C_SignFinal(session, new Buffer(1024));
mod.C_VerifyInit(session, mechanism, publicKey);
mod.C_VerifyUpdate(session, new Buffer("first"));
mod.C_VerifyUpdate(session, new Buffer("second"));
const res = mod.C_VerifyFinal(session, signature);
assert.strictEqual(res, true);
});
});
});
});
context("ossl vectors", () => {
let p11, ossl;
before(() => {
p11 = new p11_crypto.WebCrypto({
library: config.lib,
slot: 0,
});
ossl = new Crypto();
})
context("sign/verify", () => {
context("ECDSA", () => {
[
"SHA-1",
"SHA-256",
"SHA-384",
"SHA-512",
].forEach((hash) => {
it(hash, (done) => {
const alg = {
name: "ECDSA",
namedCurve: "P-256",
hash
};
const data = new Buffer("Test data");
p11.subtle.generateKey(alg, true, ["sign", "verify"])
.then((keys) => {
return p11.subtle.exportKey("jwk", keys.publicKey)
.then((jwk) => {
// console.log(jwk);
return ossl.subtle.importKey("jwk", jwk, alg, true, ["verify"])
})
.then((publicKey) => {
return p11.subtle.sign(alg, keys.privateKey, data)
.then((signature) => {
return ossl.subtle.verify(alg, publicKey, signature, data);
})
.then((ok) => {
assert.strictEqual(ok, true);
})
})
})
.then(done, done);
})
});
});
});
});
});
|
async function logger(ctx, next) {
console.log(`--> ${ctx.method} ${ctx.url}`);
const start = new Date();
await next();
const ms = Math.ceil(Date.now() - start);
ctx.set('X-Response-Time', `${ms}ms`);
console.log(`<-- ${ctx.method} ${ctx.url} ${ctx.status} (${ms}ms)`);
}
module.exports = () => logger;
|
import { CALL_API, apiMiddleware } from '../src/redux-api-middleware-native';
it('Exports const', () => {
return expect(CALL_API).toEqual('API_REQUEST');
});
it('Exports middleware', () => {
return expect(typeof apiMiddleware).toEqual('function');
});
|
import PropTypes from 'prop-types';
export default PropTypes.shape({
id: PropTypes.number,
name: PropTypes.string,
type: PropTypes.string,
infoAlertText: PropTypes.string,
ignoreQuestionText: PropTypes.string,
options: PropTypes.arrayOf(PropTypes.shape({
value: PropTypes.number,
label: PropTypes.string,
exclusive: PropTypes.bool
}))
});
|
'use strict';
// Configuring the Articles module
/* angular.module('articles').run(['Menus',
function (Menus) {
// Add the articles dropdown item
Menus.addMenuItem('topbar', {
title: 'Articles',
state: 'articles',
type: 'dropdown',
roles: ['*']
});
// Add the dropdown list item
Menus.addSubMenuItem('topbar', 'articles', {
title: 'List Articles',
state: 'articles.list'
});
// Add the dropdown create item
Menus.addSubMenuItem('topbar', 'articles', {
title: 'Create Articles',
state: 'articles.create',
roles: ['user']
});
}
]); */
|
/*
* index.js: Top-level include for the drone module.
*
* (C) 2010, Nodejitsu Inc.
*
*/
var fs = require('fs'),
path = require('path'),
http = require('http'),
flatiron = require('flatiron'),
haibu = require('../../haibu'),
async = haibu.common.async;
//
// ### Include Exports
// Export other components in the module
//
exports.Drone = require('./drone').Drone;
exports.Client = require('haibu-api').Client;
exports.started = false;
//
// ### function autostart (server, callback)
// #### @server {http.Server} Haibu drone server to autostart drones with.
// #### @callback {function} Continuation to respond to when complete
// Autostarts drones for all applications persisted to
// `haibu.config.get('directories:autostart')`.
//
exports.autostart = function (server, callback) {
var autostartDir = haibu.config.get('directories:autostart');
//
// Helper function which starts multiple drones
// a given application.
//
function startDrones (pkg, done) {
if (pkg.drones == 0) {
return done();
}
var started = 0;
async.whilst(function () {
return started < pkg.drones;
}, function (next) {
started++;
server.drone.start(pkg, next);
}, done);
}
//
// Find all drones in directory:
// %dir/%sanitized_name.json
//
fs.readdir(autostartDir, function (err, files) {
if (err) {
return callback(err);
}
async.map(files, function (file, next) {
//
// Read each `package.json` manifest file and start
// the appropriate drones in this `haibu` instance.
//
fs.readFile(path.join(autostartDir, file), function (err, pkg) {
if (err) {
return callback(err);
}
//
// Read the contents of the package.json manifest,
// which should be JSON
//
try {
pkg = JSON.parse(pkg.toString());
}
catch (ex) {
return callback(ex);
}
startDrones(pkg, next);
});
}, callback);
});
}
//
// ### function start (options, callback)
// #### @options {Object} Options to use when starting this module.
// #### @callback {function} Continuation to respond to when complete.
// Starts the haibu `drone` webservice with the specified options.
//
exports.start = function (options, callback) {
if (exports.started) {
return callback(null, haibu.running.server);
}
function tryAutostart (server) {
exports.autostart(server, function (err) {
//
// Ignore errors from autostart and continue
// bringing up the haibu `drone` server.
//
// Remark: We should report the `err` somewhere
//
haibu.emit('start');
callback(null, server);
});
}
function startServer (err) {
if (err) {
return callback(err);
}
//
// Create the server and add the new `http.Server`
// and `haibu.drone.Drone` instance into the `haibu.running`
// namespace.
//
var drone = new haibu.drone.Drone(options);
//
// Setup the `union` server through `flatiron.plugins.http`
// and then add routes.
//
haibu.use(flatiron.plugins.http, options.http || {});
require('./service').createRouter(drone);
if (options.port) {
haibu.listen(options.port);
}
haibu.running.server = haibu.server;
haibu.running.drone = haibu.server.drone = drone;
haibu.running.ports = {};
//
// There is a current bug in node that throws here:
//
// https://github.com/joyent/node/blob/v0.4.12/lib/net.js#L159
//
// It will throw a broken pipe error (EPIPE) when a child process that you
// are piping to unexpectedly exits. The write function on line 159 is
// defined here:
//
// https://github.com/joyent/node/blob/v0.4.12/lib/net.js#L62
//
// This uncaughtExceptionHandler will catch that error,
// and since it originated with in another sync context,
// this section will still respond to the request.
//
haibu.plugins.exceptions.logger.exitOnError = function (err) {
if (err.code === 'EPIPE') {
console.log('expected error:');
console.log('EPIPE -- probabaly caused by someone pushing a non gzip file.');
console.log('"net" throws on a broken pipe, current node bug, not haibu.');
return false;
}
return true;
};
//
// Attempt to autostart any applications and respond.
//
tryAutostart(haibu.server);
}
//
// Indicate that `haibu.drone` has started
//
exports.started = true;
return haibu.initialized
? startServer()
: haibu.init(options, startServer);
};
//
// ### function stop (callback)
// #### @cleanup {bool} (optional) Remove all autostart files (default=true).
// #### @callback {function} Continuation to respond to when complete.
// Gracefully stops `drone` instance
//
exports.stop = function (cleanup, callback) {
if (!callback && typeof cleanup === 'function') {
callback = cleanup;
cleanup = true;
}
if (!exports.started) {
return callback ? callback() : null;
}
exports.started = false;
haibu.running.server.close();
// Terminate drones
haibu.running.drone.destroy(cleanup, callback || function () {});
haibu.running = {};
};
|
const BaseComponent = require('ascesis').BaseComponent;
class QueryFilter extends BaseComponent {
filter(query){
if(query === false){
this.innerHTML = ``;
} else {
this.innerHTML = `#taglist li:not([data-search${this.getAttribute('operator') || '*'}="${query}"]){
display: none;
}`;
}
}
}
QueryFilter.extends = 'style';
module.exports = customElements.define('query-filter', QueryFilter);
|
import User from '../models/user';
import cuid from 'cuid';
import sanitizeHtml from 'sanitize-html';
/**
* Get all users
* @param req
* @param res
* @returns void
*/
export function getUsers(req, res) {
User.find().sort('-dateAdded')
.then(users => res.json({ users }))
.catch(err => res.status(500).send(err));
}
/**
* Save a user
* @param req
* @param res
* @returns void
*/
export function addUser(req, res) {
if (!req.body.email) {
res.status(403).end();
}
const newUser = new User(req.body);
// Let's sanitize inputs
//newUser.name = sanitizeHtml(newUser.name);
newUser.save()
.then(user => res.json({ user }))
.catch(err => res.status(500).send(err));
}
/**
* Get a single user
* @param req
* @param res
* @returns void
*/
export function getUser(req, res) {
User.findOne({ _id: req.params.id })
.then(user => res.json({ user }))
.catch(err => res.status(500).send(err));
}
/**
* Delete a user
* @param req
* @param res
* @returns void
*/
export function deleteUser(req, res) {
User.remove({ _id: req.params.id })
.then(user => res.json({ user }))
.catch(err => res.status(500).send(err));
}
/**
* Save a user
* @param req
* @param res
* @returns void
*/
export function updateUser(req, res) {
const id = req.params.id;
const updatedUser = req.body;
// Let's sanitize inputs
//updatedUser.name = sanitizeHtml(updatedUser.name);
User.findByIdAndUpdate(id, updatedUser, { runValidators: true })
.then(user => res.json({ user }))
.catch(err => res.status(500).send(err));
}
|
'use strict';
module.exports = function(grunt) {
//--------------------------------------------------------------------------
// SETUP CONFIG
//--------------------------------------------------------------------------
// setup task config
var config = {
// Arrays of relevant code classified by type
files: {
js: {
src: [
'*.js',
'lib/*.js'
]
}
},
// This handles automatic version bumping in travis
bump: {
options: {
files: ['package.json'],
updateConfigs: [],
commit: true,
commitMessage: 'Release v%VERSION%',
commitFiles: ['package.json', 'bower.json'],
createTag: true,
tagName: 'v%VERSION%',
tagMessage: 'Version %VERSION%',
push: false
}
},
// Some linting and code standards
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: ['Gruntfile.js', '<%= files.js.src %>']
},
jscs: {
src: ['Gruntfile.js', '<%= files.js.src %>'],
options: {
config: '.jscsrc'
}
}
};
//--------------------------------------------------------------------------
// LOAD TASKS
//--------------------------------------------------------------------------
// load task config
grunt.initConfig(config);
// load external tasks
//grunt.loadTasks('tasks');
// load grunt-* tasks from package.json dependencies
require('matchdep').filterAll('grunt-*').forEach(grunt.loadNpmTasks);
//--------------------------------------------------------------------------
// SETUP WORKFLOWS
//--------------------------------------------------------------------------
grunt.registerTask('bump-patch', [
'bump-only:patch'
]);
grunt.registerTask('test', [
'jshint',
'jscs'
]);
};
|
var Router = Ember.Router.extend(); // ensure we don't share routes between all Router instances
// Router.map(function() {
// this.route('component-test');
// this.route('helper-test');
// // this.resource('posts', function() {
// // this.route('new');
// // });
// });
Router.map(function () {
// Inicio
this.route('index', { path: '/' });
//Directorio transportistas
this.resource('directorio');
// Registro de usuario
this.resource('registro', function(){
this.route('gracias');
});
// Cotizar
this.resource('cotizar', function(){
this.resource('importacion');
this.resource('exportacion');
this.resource('domestica');
this.resource('contenedor');
this.resource('exito');
});
// Como funciona
this.resource('como_funciona', function(){
this.resource('cargador');
this.resource('transportista');
});
// Nosotros
this.resource('nosotros', function(){
this.resource('contacto');
this.resource('ayuda');
});
});
export default Router;
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Layout from '../../components/Layout';
import Contact from './Contact';
const title = 'Refres';
function action() {
return {
chunks: ['contact'],
title,
component: (
<Layout>
<Contact title={title} />
</Layout>
),
};
}
export default action;
|
/*jshint jasmine: true, node: true */
'use strict';
const logger = require('winston');
const mock = require('mock-require');
describe('server utils', () => {
let closeCalled = false;
let onErrorCB;
let customServerError;
let customPortError;
let customPortNumber;
beforeEach(() => {
spyOn(logger, 'info');
});
afterEach(() => {
closeCalled = false;
onErrorCB = undefined;
customServerError = undefined;
customPortError = undefined;
customPortNumber = undefined;
mock.stopAll();
});
function bind() {
mock('https', {
createServer: () => ({
on: (err, cb) => onErrorCB = cb,
close: () => closeCalled = true,
listen: (port, host, cb) => {
if (customServerError) {
onErrorCB(customServerError);
}
cb(port);
}
})
});
mock('portfinder', {
getPortPromise: () => {
if (customPortError) {
return Promise.reject(customPortError);
} else {
return Promise.resolve(customPortNumber);
}
}
});
return mock.reRequire('../cli/utils/server');
}
it('should expose start and stop methods', () => {
const server = bind();
expect(server.start).toBeDefined();
expect(server.stop).toBeDefined();
});
it('should accept a root', () => {
const server = bind();
const root = 'custom-root';
server.start(root).then(() =>{
});
});
it('should close the http server if it exists', (done) => {
const server = bind();
server.stop();
expect(closeCalled).toBe(false);
server.start().then(() => {
logger.info.calls.reset();
server.stop();
expect(closeCalled).toBe(true);
expect(logger.info).toHaveBeenCalledWith(`Stopping http server`);
done();
});
});
it('should catch http server failures', (done) => {
customServerError = 'custom-error';
const server = bind();
server.start().catch(err => {
expect(err).toBe(customServerError);
done();
});
});
it('should resolve the portfinder port', (done) => {
customPortNumber = 1234;
const server = bind();
server.start().then(port => {
expect(port).toBe(customPortNumber);
done();
});
});
it('should catch portfinder failures', (done) => {
customPortError = 'custom-portfinder-error';
const server = bind();
server.start().catch(err => {
expect(err).toBe(customPortError);
done();
});
});
});
|
'use strict';
class ConnectCore {
constructor(SuiteAPI, global) {
this.SuiteAPI = SuiteAPI;
this.global = global;
}
save(integrationInstanceId) {
let saveButton = document.getElementById('content-save-button');
if (saveButton.classList.contains('e-btn-disabled')) {
return;
}
saveButton.classList.add('e-btn-disabled');
this.global.Emarsys.integration.messageToService('save', {}, integrationInstanceId);
}
feedback(integrationInstanceId) {
this.global.Emarsys.integration.messageToService('feedback', {}, integrationInstanceId);
}
static create(SuiteAPI, global) {
return new ConnectCore(SuiteAPI, global);
}
}
module.exports = ConnectCore;
|
module.exports = (gulp) => {
gulp.task('archive', gulp.series('pre_archive'));
};
|
var redeyed = require('redeyed')
, theme = require('../themes/default')
, colors = require('ansicolors')
, colorSurround = colors.brightBlack
, surroundClose = '\u001b[39m'
;
/**
* Description
* @method trimEmptyLines
* @param {} lines
* @return
*/
function trimEmptyLines(lines) {
// remove lines from the end until we find a non-empy one
var line = lines.pop();
while(!line || !line.length)
line = lines.pop();
// put the non-empty line back
if (line) lines.push(line);
}
/**
* Description
* @method addLinenos
* @param {} highlightedCode
* @param {} firstline
* @return CallExpression
*/
function addLinenos (highlightedCode, firstline) {
var highlightedLines = highlightedCode.split('\n');
trimEmptyLines(highlightedLines);
var linesLen = highlightedLines.length
, lines = []
, totalDigits
, lineno
;
/**
* Description
* @method getDigits
* @param {} n
* @return Literal
*/
function getDigits (n) {
if (n < 10) return 1;
if (n < 100) return 2;
if (n < 1000) return 3;
if (n < 10000) return 4;
// this works for up to 99,999 lines - any questions?
return 5;
}
/**
* Description
* @method pad
* @param {} n
* @param {} totalDigits
* @return
*/
function pad (n, totalDigits) {
// not pretty, but simple and should perform quite well
var padDigits= totalDigits - getDigits(n);
switch(padDigits) {
case 0: return '' + n;
case 1: return ' ' + n;
case 2: return ' ' + n;
case 3: return ' ' + n;
case 4: return ' ' + n;
case 5: return ' ' + n;
}
}
totalDigits = getDigits(linesLen + firstline - 1);
for (var i = 0; i < linesLen; i++) {
// Don't close the escape sequence here in order to not break multi line code highlights like block comments
lineno = colorSurround(pad(i + firstline, totalDigits) + ': ').replace(surroundClose, '');
lines.push(lineno + highlightedLines[i]);
}
return lines.join('\n');
}
/**
* Description
* @method exports
* @param {} code
* @param {} opts
* @return
*/
module.exports = function highlight (code, opts) {
opts = opts || { };
if (opts.json) {
code = '!\n' + code;
}
try {
var result = redeyed(code, opts.theme || theme)
, firstline = opts.firstline && !isNaN(opts.firstline) ? opts.firstline : 1;
if (opts.json) {
result.code = result.code.split('\n').slice(1).join('\n');
}
return opts.linenos ? addLinenos(result.code, firstline) : result.code;
} catch (e) {
e.message = 'Unable to perform highlight. The code contained syntax errors: ' + e.message;
throw e;
}
};
|
/**
* =========== tesla-tpl =============
* @Author zhou_xg
* @Version 1.0.0-beta
* @Licence MIT License
* @Email zhou84034339@sina.com
*
*/
!function (undefined) {
var $tpl = function (tpl, data, options) {
options = options || {};
for (var property in defaults) {
if (!options[property]) {
options[property] = defaults[property];
}
}
return compile(tpl, options).render(data);
},
cache = $tpl.cache = {},
events = {},
defaults = {
openTag: "@{",
closeTag: "}",
cache: true
};
$tpl.on = function (name, callback) {
var callbacks = events[name] || (events[name] = []);
callbacks.push(callback);
};
$tpl.off = function (name, callback) {
if (!name) {
events = {};
return;
}
if (!callback) {
events[name] = [];
return;
}
var arr = events[name];
if (arr) {
for (var i = 0, item; (item = arr[i]) != null; i++) {
if (item === callback) {
arr.splice(i, 1);
return;
}
}
}
};
$tpl.emit = function (name) {
var data = undefined,
callbacks = events[name] || [];
if (arguments.length > 1) {
data = Array.prototype.slice.call(arguments, 1);
}
for (var callback in callbacks) {
callback.apply(undefined, callbacks);
}
};
//TODO 实现模板引擎的代码实现
function Engine(tpl, options) {
this.code = "";
this.tpl = tpl;
this.options = options;
this.render = function () {
};
(function () {
})();
}
//模板逻辑处理,字符转义等方法实现通过原型实现以降低内存占用
Engine.prototype = {
_langAnalyze: function () {
var _reg = new RegExp(this.options.openTag + "("
+ "[^" + this.options.closeTag + "]*" + ")" + this.options.closeTag, "igm");
this.tpl.replace(_reg, function (pattern, str) {
return parse(str);
});
}
};
function parse(str) {
var arr = str.split(/\s+/);
switch (arr.shift()) {
case "each" :
break;
case "if" :
break;
case "else" :
break;
case "html" :
break;
default :
break;
}
;
}
function compile(tpl, options) {
try {
var engine = cache[tpl] ? cache[tpl] : new Engine(tpl, options);
if (options.cache) {
cache[tpl] = engine;
}
return engine;
} catch (e) {
$tpl.on("error", e);
return {render: function () {
}};
}
}
if (typeof define === "function") {
define(function () {
return $tpl;
});
} else if (typeof module !== "undefined" && module.exports) {
module.exports = $tpl;
} else {
this.$tpl = $tpl;
}
}();
|
import { call } from 'redux-saga/effects'
import storageModule, { getRef } from './storage'
describe('storage', () => {
let app, context, ref, storage, task
task = 'qlsdmlqmd'
beforeEach(() => {
ref = {
delete: jest.fn(),
getDownloadURL: jest.fn(),
getMetadata: jest.fn(),
put: jest.fn(() => task),
putString: jest.fn(() => task),
updateMetadata: jest.fn(),
}
storage = {
ref: jest.fn(() => ref),
}
app = {
storage: jest.fn(() => storage),
}
context = {
app,
}
})
afterEach(() => {
expect.hasAssertions()
})
describe('uploadFile(path, file, metadata)', () => {
it('works', () => {
const path = 'skddksl'
const file = 'qdmlqssdklq'
const metadata = 'qpsdksql'
const result = storageModule.uploadFile.call(context, path, file, metadata)
expect(app.storage.mock.calls.length).toBe(1)
expect(app.storage.mock.calls[0]).toEqual([])
expect(storage.ref.mock.calls.length).toBe(1)
expect(storage.ref.mock.calls[0]).toEqual([path])
expect(ref.put.mock.calls.length).toBe(1)
expect(ref.put.mock.calls[0]).toEqual([file, metadata])
expect(result).toEqual(task)
})
})
describe('uploadString(path, string, format, metadata)', () => {
it('works', () => {
const path = 'skddksl'
const string = 'qdmlqssdklq'
const format = 'qp^zpq'
const metadata = 'qpsdksql'
const result = storageModule.uploadString.call(
context,
path,
string,
format,
metadata,
)
expect(app.storage.mock.calls.length).toBe(1)
expect(app.storage.mock.calls[0]).toEqual([])
expect(storage.ref.mock.calls.length).toBe(1)
expect(storage.ref.mock.calls[0]).toEqual([path])
expect(ref.putString.mock.calls.length).toBe(1)
expect(ref.putString.mock.calls[0]).toEqual([string, format, metadata])
expect(result).toEqual(task)
})
})
describe('getDownloadURL(path)', () => {
it('works', () => {
const path = 'skddksl'
const url = 'nkqkds'
const iterator = storageModule.getDownloadURL.call(context, path)
expect(iterator.next().value).toEqual(call([ref, ref.getDownloadURL]))
expect(app.storage.mock.calls.length).toBe(1)
expect(app.storage.mock.calls[0]).toEqual([])
expect(storage.ref.mock.calls.length).toBe(1)
expect(storage.ref.mock.calls[0]).toEqual([path])
expect(iterator.next(url)).toEqual({
done: true,
value: url,
})
})
})
describe('getFileMetadata(path)', () => {
it('works', () => {
const path = 'skddksl'
const metadata = 'nkqkds'
const iterator = storageModule.getFileMetadata.call(context, path)
expect(iterator.next().value).toEqual(call([ref, ref.getMetadata]))
expect(app.storage.mock.calls.length).toBe(1)
expect(app.storage.mock.calls[0]).toEqual([])
expect(storage.ref.mock.calls.length).toBe(1)
expect(storage.ref.mock.calls[0]).toEqual([path])
expect(iterator.next(metadata)).toEqual({
done: true,
value: metadata,
})
})
})
describe('updateFileMetadata(path, newMetadata)', () => {
it('works', () => {
const path = 'skddksl'
const newMetadata = 'nkqkds'
const metadata = 'qsdmqdmql'
const iterator = storageModule.updateFileMetadata.call(context, path, newMetadata)
expect(iterator.next().value).toEqual(call([ref, ref.updateMetadata], newMetadata))
expect(app.storage.mock.calls.length).toBe(1)
expect(app.storage.mock.calls[0]).toEqual([])
expect(storage.ref.mock.calls.length).toBe(1)
expect(storage.ref.mock.calls[0]).toEqual([path])
expect(iterator.next(metadata)).toEqual({
done: true,
value: metadata,
})
})
})
describe('deleteFile(path)', () => {
it('works', () => {
const path = 'skddksl'
const iterator = storageModule.deleteFile.call(context, path)
expect(iterator.next().value).toEqual(call([ref, ref.delete]))
expect(app.storage.mock.calls.length).toBe(1)
expect(app.storage.mock.calls[0]).toEqual([])
expect(storage.ref.mock.calls.length).toBe(1)
expect(storage.ref.mock.calls[0]).toEqual([path])
expect(iterator.next()).toEqual({
done: true,
value: undefined,
})
})
})
describe('getRef(rsf, pathOrRef)', () => {
let storageRef, storage, app, rsf
beforeEach(() => {
storageRef = {
bucket: 'bucket',
}
storage = {
ref: jest.fn(() => storageRef),
}
app = {
storage: jest.fn(() => storage),
}
rsf = { app }
})
it('returns a storage ref from path string', () => {
const path = 'path'
const ref = getRef(rsf, path)
expect(app.storage.mock.calls.length).toBe(1)
expect(app.storage.mock.calls[0]).toEqual([])
expect(storage.ref.mock.calls.length).toBe(1)
expect(storage.ref.mock.calls[0]).toEqual([path])
expect(ref).toEqual(storageRef)
})
it('returns the storage ref that was passed to it', () => {
const ref = getRef(rsf, storageRef)
expect(app.storage.mock.calls.length).toBe(0)
expect(storage.ref.mock.calls.length).toBe(0)
expect(ref).toEqual(storageRef)
})
})
})
|
describe('Inventory Controller', () => {
var expect = chai.expect;
beforeEach(function () {
angular.mock.module('app.inventory');
bard.inject(this, '$controller', '$rootScope', '$timeout');
controller = $controller('InventoryController', { $timeout: $timeout });
$rootScope.$apply();
});
bard.verifyNoOutstandingHttpRequests();
it('should exist', function () {
expect(controller).to.be.ok;
});
it('should have a non null gridOptions property', () => {
console.log("should have a non null gridOptions property");
expect(controller.gridOptions).to.be.ok;
});
});
|
const TABLE_LIST = 'TABLE_LIST'
export const getList = (type) => {
return (dispatch, getState) => {
if (type == 1) {
return new Promise((resolve) => {
setTimeout(() => {
dispatch({
type: TABLE_LIST,
payload: [{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York Park',
}, {
key: '2',
name: 'Jim Green',
age: 40,
address: 'London Park',
}]
})
resolve()
}, 200)
})
}
return new Promise((resolve) => {
setTimeout(() => {
dispatch({
type: TABLE_LIST,
payload: [{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York Park',
}, {
key: '2',
name: 'Jim Green',
age: 40,
address: 'London Park',
}, {
key: '3',
name: 'John Brown',
age: 32,
address: 'New York Park',
}, {
key: '4',
name: 'Jim Green',
age: 40,
address: 'London Park',
}, {
key: '5',
name: 'John Brown',
age: 32,
address: 'New York Park',
}, {
key: '6',
name: 'Jim Green',
age: 40,
address: 'London Park',
}, {
key: '7',
name: 'John Brown',
age: 32,
address: 'New York Park',
}, {
key: '8',
name: 'Jim Green',
age: 40,
address: 'London Park',
}, {
key: '9',
name: 'John Brown',
age: 32,
address: 'New York Park',
}, {
key: '10',
name: 'Jim Green',
age: 40,
address: 'London Park',
}, {
key: '11',
name: 'John Brown',
age: 32,
address: 'New York Park',
}, {
key: '12',
name: 'Jim Green',
age: 40,
address: 'London Park',
}
]
})
resolve()
}, 200)
})
}
}
const ACTION_HANDLERS = {
[TABLE_LIST]: (state, action) => {
state.list = action.payload;
return state;
}
}
const initialState = {
list: []
};
export default function tableReducer(state = initialState, action) {
const handler = ACTION_HANDLERS[action.type]
let nextState = Object.assign({}, state);
return handler ? handler(nextState, action) : nextState
}
|
/*jshint boss:true, expr:true, onevar:false */
var DataTable,
CSS_PREFIX_MODULE = 'rednose-datatable',
CSS_BOOTSTRAP_TABLE = 'table',
CSS_BOOTSTRAP_TABLE_CONDENSED = 'table-condensed';
DataTable = Y.Base.create('dataTable', Y.DataTable.Base, [ Y.DataTable.Scrollable, Y.DataTable.Sortable, Y.DataTable.ColumnWidths ], {
initializer: function () {
var boundingBox = this.get('boundingBox'),
condensed = this.get('condensed');
this.after('render', function() {
boundingBox.one('table').addClass(CSS_BOOTSTRAP_TABLE);
if (condensed === true) {
boundingBox.one('table').addClass(CSS_BOOTSTRAP_TABLE_CONDENSED);
}
});
}
}, {
ATTRS: {
condensed: {
value: false
}
}
});
DataTable.CSS_PREFIX = CSS_PREFIX_MODULE;
// -- Namespace ----------------------------------------------------------------
Y.namespace('Rednose').DataTable = DataTable;
|
'use strict';
const _ = require('lodash');
const {BaseStats} = require('gemini-core');
const RunnerEvents = require('./constants/runner-events');
const statNames = {
TOTAL: 'total',
PASSED: 'passed',
FAILED: 'failed',
SKIPPED: 'skipped',
RETRIES: 'retries'
};
module.exports = class Stats extends BaseStats {
constructor(runner) {
super(statNames);
this._statsByBrowsers = {};
this._testsByBrowsers = {};
runner && runner
.on(RunnerEvents.TEST_PASS, (test) => this.addPassed(test))
.on(RunnerEvents.TEST_FAIL, (test) => this.addFailed(test))
.on(RunnerEvents.RETRY, (test) => this.addRetries(test))
.on(RunnerEvents.TEST_PENDING, (test) => this.addSkipped(test));
}
addRetries(test) {
super.addRetries();
const bro = this._getBrowser(test.browserId);
bro.retries++;
}
getResult() {
const data = super.getResult();
Object.keys(this._statsByBrowsers).forEach((broName) => {
this._statsByBrowsers[broName].total = this._testsByBrowsers[broName].size;
});
return _.extend(data, {perBrowser: this._statsByBrowsers});
}
_addStat(stat, test) {
super._addStat(stat, test);
this._addBrowserStat(stat, test);
}
_addBrowserStat(stat, test) {
const browserId = test.browserId;
super._addStat(stat, test, this._getBrowser(browserId), this._testsByBrowsers[browserId]);
}
_getBrowser(browserId) {
return this._statsByBrowsers[browserId] || this._fillEmptyBrowser(browserId);
}
_fillEmptyBrowser(browserId) {
this._statsByBrowsers[browserId] = this._fillEmptyStats();
this._testsByBrowsers[browserId] = new Set();
return this._statsByBrowsers[browserId];
}
_buildStateKey(test) {
return test.title;
}
_buildSuiteKey(test) {
return `${test.parent.fullTitle()} ${test.browserId}`;
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.