text
stringlengths 2
6.14k
|
|---|
$(function () {
update()
$('input#send').click(send)
$('input#update').click(update)
})
function update(){
$.get('/get', function (result, status){
$('textarea').val(result.txt)
if(result.txt==undefined){
alert('Sth went wrong!')
}
})
}
function send(){
$.post('/', {txt:$('textarea').val()},function(result){
if(result.code!=0){
alert("Something went wrong!")
}
})
}
|
import {
assignNumber,
computeStyleFromItem,
CurrentLevel,
depthOf,
div, EventBus,
findLevel,
flattenAll, generateColour, getPalletXPosition,
mapDepths,
matchesRange,
RANGE_DISPLAY_LARGE,
RANGE_DISPLAY_NONE,
RANGE_DISPLAY_PREV_NEXT,
renderTemporal,
setStyle,
sortByKey
} from '../utils';
export default class DeepRange {
static CSS_ITEM = 'galway-timeline__item';
static CSS_ITEM_ACTIVE = 'galway-timeline__item--active';
static CSS_ITEM_REPRESENTATION = 'galway-timeline__representation';
static CSS_TEMPORAL = 'galway-timeline__temporal';
static CSS_ITEM_CHILDREN = 'galway-timeline__item--children';
constructor($el, model) {
this.$el = $el;
this.model = model;
this.bus = new EventBus('DeepRange');
// Initial DOM elements
this.renderInitial($el);
}
onClickRange(func) {
this.$elements.forEach(
$el => {
const key = this.$elements.indexOf($el);
const item = this.model.flatItems[key];
$el.addEventListener('click', e => {
return func(item, key, $el, e);
});
}
);
}
renderInitial($el) {
const $tooltip = document.querySelector('.galway-timeline__tooltip-float');
$el.addEventListener('mouseenter', (e) => {
$tooltip.classList.add('galway-timeline__tooltip-float--active');
});
$el.addEventListener('mouseleave', () => {
$tooltip.classList.remove('galway-timeline__tooltip-float--active');
});
$el.addEventListener('mousemove', (e) => {
const calc = getPalletXPosition($tooltip.getBoundingClientRect().width, e.clientX, window.innerWidth);
$tooltip.style.left = `${calc}px`;
});
this.$elements = this.model.flatItems.map(
(item) => {
// Only show top level, hide the rest.
const visibility = this.model.topKeys.indexOf(item.key) === -1 ? RANGE_DISPLAY_NONE : RANGE_DISPLAY_LARGE;
return (
div({
className: DeepRange.CSS_ITEM,
style: computeStyleFromItem(visibility, item),
onMouseEnter: () => {
$tooltip.innerText = item.label;
this.hoveredItem = item;
this.bus.dispatch('item:hover', item);
},
onMouseLeave: () => {
this.bus.dispatch('item:blur', item);
if (this.hoveredItem === item) {
this.hoveredItem = null;
}
},
}, [
div({
className: DeepRange.CSS_ITEM_REPRESENTATION, style: {
background: generateColour(item.level)
}
}),
div({className: DeepRange.CSS_TEMPORAL}, [
renderTemporal(item)
]),
])
);
}
);
$el.innerHTML = '';
this.$elements.forEach($element => {
$el.appendChild($element);
});
}
renderTopLevel(canvasIndex, model) {
this.$elements.forEach(($element, key) => {
const currentLevel = model.topKeys.indexOf(key);
const item = model.structure[currentLevel];
this.renderActive($element, item, canvasIndex);
if (currentLevel !== -1) {
setStyle($element, computeStyleFromItem(RANGE_DISPLAY_LARGE, item));
return;
}
setStyle($element, computeStyleFromItem(RANGE_DISPLAY_NONE, item));
});
}
renderActive($element, item, canvasIndex) {
if (matchesRange(item, canvasIndex)) {
$element.classList.add(DeepRange.CSS_ITEM_ACTIVE);
this.bus.dispatch('item:active', item);
if (item.children) {
$element.classList.add(DeepRange.CSS_ITEM_CHILDREN);
}
} else if ($element.classList.contains(DeepRange.CSS_ITEM_ACTIVE)) {
this.bus.dispatch('item:inactive', item);
$element.classList.remove(DeepRange.CSS_ITEM_ACTIVE);
$element.classList.remove(DeepRange.CSS_ITEM_CHILDREN);
}
}
render(canvasIndex, model) {
// If we are at the top level depth, we just render as normal.
if (model.depth === 0) {
return this.renderTopLevel(canvasIndex, model);
}
// Here we look for the current "view" which is the sub-sections expanded out.
if (model.currentViews.length === 0) {
// Default back to top level if we can't find a view.
return this.renderTopLevel(canvasIndex, model);
}
this.$elements.forEach(($element, key) => {
const item = model.current.findCurrent(key);
// Render the current item with class.
this.renderActive($element, item, canvasIndex);
if (model.current.isNext(key) || model.current.isPrevious(key)) {
setStyle($element, computeStyleFromItem(RANGE_DISPLAY_PREV_NEXT, item));
return;
}
if (item) {
setStyle($element, computeStyleFromItem(RANGE_DISPLAY_LARGE, item));
return;
}
setStyle($element, computeStyleFromItem(RANGE_DISPLAY_NONE, item));
});
}
}
|
/*!
Math.uuid.js (v1.4)
http://www.broofa.com
mailto:robert@broofa.com
Copyright (c) 2010 Robert Kieffer
Dual licensed under the MIT and GPL licenses.
*/
/*
* Generate a random uuid.
*
* USAGE: Math.uuid(length, radix)
* length - the desired number of characters
* radix - the number of allowable values for each character.
*
* EXAMPLES:
* // No arguments - returns RFC4122, version 4 ID
* >>> Math.uuid()
* "92329D39-6F5C-4520-ABFC-AAB64544E172"
*
* // One argument - returns ID of the specified length
* >>> Math.uuid(15) // 15 character ID (default base=62)
* "VcydxgltxrVZSTV"
*
* // Two arguments - returns ID of the specified length, and radix. (Radix must be <= 62)
* >>> Math.uuid(8, 2) // 8 character ID (base=2)
* "01001010"
* >>> Math.uuid(8, 10) // 8 character ID (base=10)
* "47473046"
* >>> Math.uuid(8, 16) // 8 character ID (base=16)
* "098F4D35"
*/
// Private array of chars to use
var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
var math = {
uuid: function (len, radix) {
var chars = CHARS, uuid = [], i;
radix = radix || chars.length;
if (len) {
// Compact form
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
} else {
// rfc4122, version 4 form
var r;
// rfc4122 requires these characters
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
// Fill in random data. At i==19 set the high bits of clock sequence as
// per rfc4122, sec. 4.1.5
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
},
uuidFast: function () {
var chars = CHARS, uuid = new Array(36), rnd = 0, r;
for (var i = 0; i < 36; i++) {
if (i == 8 || i == 13 || i == 18 || i == 23) {
uuid[i] = '-';
} else if (i == 14) {
uuid[i] = '4';
} else {
if (rnd <= 0x02) rnd = 0x2000000 + (Math.random() * 0x1000000) | 0;
r = rnd & 0xf;
rnd = rnd >> 4;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
return uuid.join('');
}, uuidCompact: function () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
};
function replaceSign(rs)
{
return rs.replace(/\-/g, '');
}
exports.get = math.uuid;
exports.getNoSign = function () {
return replaceSign(math.uuid.apply(this, arguments));
};
exports.getFast = math.uuidFast;
exports.getFastNoSign = function () {
return replaceSign(math.uuidFast.apply(this, arguments));
};
exports.getCompact = math.uuidCompact;
exports.getCompactNoSign = function () {
return replaceSign(math.uuidCompact.apply(this, arguments));
};
|
var ctrl = function ($scope, $q, $state, $stateParam, $anchorScroll, categoryService,
eventService, placeService, transactionService) {
$scope.isEditMode = $stateParam.publicId;
$scope.options = {
showWeeks: false
};
const applyToPromise = transactionService.getApplyToList();
$q.when(applyToPromise, function (data) {
$scope.applyToList = data;
});
const categoryPromise = categoryService.getList();
$q.when(categoryPromise, function (data) {
$scope.categoryList = data;
});
const eventPromise = eventService.defaultList()
$q.when(eventPromise, function (data) {
$scope.eventList = data;
});
const placePromise = placeService.defaultList()
$q.when(placePromise, function (data) {
$scope.placeList = data;
});
$scope.currentTx = {};
$q.all([
applyToPromise,
categoryPromise,
eventPromise,
placePromise
]).then(function () {
if ($scope.isEditMode) {
var request = { publicId: $stateParam.publicId };
transactionService.retrieve(request).then(function (data) {
data.calendar = new Date(data.calendar);
$scope.currentTx = data;
$scope.toExpense = data.category.toExpense;
});
} else {
$scope.currentTx.calendar = new Date();
}
});
$scope.filterByApplyTo = function (item) {
return item.toExpense === $scope.toExpense;
};
$scope.submit = function (data) {
$scope.submitted = true;
$anchorScroll();
transactionService.create(data).then(
function () {
if ($scope.isEditMode) {
$scope.cancel();
} else {
$scope.submitted = false;
$scope.toExpense = undefined;
$scope.currentTx.amount = null;
$scope.currentTx.category = null;
$scope.currentTx.description = null;
$scope.hasSaved = true;
$scope.hasError = false;
}
}, function (error) {
$scope.submitted = false;
$scope.hasSaved = false;
$scope.hasError = true;
console.error(error);
});
};
$scope.cancel = function () {
$state.go('accountTransactions');
};
};
ctrl.$inject = ['$scope', '$q', '$state', '$stateParams', '$anchorScroll', 'categoryService',
'eventService', 'placeService', 'transactionService'];
export default {
name: 'AddOrEditTransactionCtrl',
fn: ctrl
};
|
var assert = require('assert')
, svgfont2svgicons = require(__dirname + '/../src/index.js')
, Fs = require('fs')
, StringDecoder = require('string_decoder').StringDecoder
, Path = require("path")
;
// Tests
describe('Parsing fonts', function() {
it("should work for simple SVG fonts", function(done) {
var fontStream = Fs.createReadStream(__dirname + '/fixtures/cleanicons.svg');
var iconProvider = svgfont2svgicons();
var icons = [];
var bufferedIcons = 0;
var ended = false;
fontStream.pipe(iconProvider);
iconProvider.on('readable', function() {
var icon;
do {
icon = iconProvider.read();
if(icon) {
icon.content = '';
icons.push(icons);
icon.stream.on('readable', (function(icon) {
return function() {
var chunk;
do {
chunk = icon.stream.read();
if(chunk) {
icon.content += chunk.toString('utf-8');
}
} while(null !== chunk);
};
})(icon));
icon.stream.once('end', (function(icon) {
return function() {
assert.equal(
Fs.readFileSync(__dirname + '/expected/cleanicons/' + icon.name + '.svg'),
icon.content
);
bufferedIcons++;
if(ended && icons.length == bufferedIcons) {
done();
}
};
})(icon));
}
} while(null !== icon);
}).once('end',function() {
ended = true;
if(icons.length == bufferedIcons) {
done();
}
});
});
});
|
angular.module('demo').controller('ComponentsDemoCtrl',function($scope,$rootScope,$state){
});
|
import _ from 'lodash';
function registerMethod(vorpal, browser, property) {
vorpal
.command(`${property} [params...]`, 'Refer http://webdriver.io/api')
.parse(cmd => cmd
.split(' ')
.map(encodeURIComponent)
.join(' '))
.action(async ({ params = [] }) => {
const cleanedParams = params.map(decodeURIComponent);
const res = await browser[property](...cleanedParams);
if (res.value) {
vorpal.log(res.value);
} else {
vorpal.log(res);
}
});
}
module.exports = ({ vorpal, driver: { current: browser } }) => {
const methods = _.keysIn(browser);
methods.forEach((property) => {
registerMethod(vorpal, browser, property);
});
};
|
var dir_aa9befc4bdfa617079e96718d920d9d2 =
[
[ "Projects", "dir_9749fe1d1039c274ca5f4a0137bd5805.html", "dir_9749fe1d1039c274ca5f4a0137bd5805" ]
];
|
var items = require('../repositories/item');
var S = require('string');
var ObjectId = require('mongodb').ObjectID;
var extend = require('extend');
exports.fetchForTab = function(req, res) {
items.findByTabId(req.db,
req.params.tabId,
function(err, items) {
if (err) {
res.jsonError();
} else {
res.jsonSuccess(items);
}
}
);
};
exports.create = function(req, res) {
res.render('item/create', {
title: '',
content: '',
backUrl: '/tabs/' + req.params.tabId
});
};
exports.store = function(req, res) {
var err = validateItem(req);
if (err) {
req.flash('error', err);
res.render('item/create');
} else {
items.insert(req.db, {
tab_id: new ObjectId(req.params.tabId),
title: req.body.title,
content: req.body.content
}, function(err, result) {
if (err) {
throw err;
} else {
req.flash('success', 'New item has been successfully created.');
res.redirect('/tabs/' + req.params.tabId);
}
});
}
};
exports.edit = function(req, res) {
items.findById(req.db, req.params.id, function(err, item) {
if (err) {
throw err;
} else {
res.render('item/edit', extend(item, {
backUrl: '/tabs/' + req.params.tabId
})
);
}
});
};
exports.update = function(req, res) {
var err = validateItem(req);
if (err) {
req.flash('error', err);
res.render('item/edit', {
title: req.body.item,
content: req.body.content
});
return;
}
items.update(req.db,
{
id: req.params.id,
title: req.body.title,
content: req.body.content
},
function(err, result) {
if (err) {
throw err;
} else {
res.redirect('/tabs/' + req.params.tabId);
}
}
);
};
function validateItem(req) {
title = S(req.body.title).trim().s;
if (!title) {
return 'Title name cannot be empty.';
}
content = S(req.body.content).trim().s;
if (!content) {
return 'Content cannot be empty.';
}
return '';
}
exports.delete = function(req, res) {
items.delete(req.db, req.params.id, function(err, result) {
if (err) {
throw err;
} else {
res.redirect('/tabs/' + req.params.tabId);
}
});
};
|
var mongoose = require('mongoose');
var extend = require('mongoose-schema-extend');
var Schema = mongoose.Schema;
var ad_objects = require('./additionalModels.js');
var Element = require('mongoose').model('Element').schema;
var ElementVersion = require('mongoose').model('ElementVersion').schema;
var RecordVersion = require('mongoose').model('RecordVersion').schema;
var Territory = Element.extend({
territoryAtomized: {
extentOfOccurrence : String,
areaOfOccupancy : String
},
territoryUnstructured : String
},{ collection: 'territory', versionKey: false });
var TerritoryVersion = ElementVersion.extend({
territory : Territory
},{ collection: 'TerritoryVersion', versionKey: false });
module.exports = mongoose.model('TerritoryVersion', TerritoryVersion );
|
// All code points with the `Deprecated` property as per Unicode v9.0.0:
[
0x149,
0x673,
0xF77,
0xF79,
0x17A3,
0x17A4,
0x206A,
0x206B,
0x206C,
0x206D,
0x206E,
0x206F,
0x2329,
0x232A,
0xE0001
];
|
vows = require('vows');
assert = require('assert');
_ = require('lodash');
r = require('../');
vows.describe('Rhythmically merge').addBatch({
"merge sequences": function() {
s = r.merge(r.sequence('a b'), r.sequence('d e'));
assert.equal(s.length, 4);
assert.deepEqual(_.pluck(s, 'value'), ['a', 'd', 'b', 'e']);
assert.deepEqual(_.pluck(s, 'duration'), [1/4, 1/4, 1/4, 1/4]);
assert.deepEqual(_.pluck(s, 'position'), [0, 0, 0.25, 0.25]);
}
}).export(module);
|
'use strict';
module.exports = function(models) {
const OurServices = models.OurServices;
return {
createOurServicesData(ourServicesData) {
let ourServices = new OurServices(ourServicesData);
return new Promise((resolve, reject) => {
ourServices.save((error) => {
if (error) {
return reject(error);
}
return resolve(ourServices);
});
});
},
getAllOurServices() {
return new Promise((resolve, reject) => {
OurServices.find((err, details) => {
if (err) {
return reject(err);
}
return resolve(details);
});
});
}
}
}
|
/**
* config is the configuration wrapper object of the app
*/
var config = {
site : 'http://www.some.com',
domains : {
some : 'some.com'
},
el : {
productList : $('#product_list'),
productTemplate : $('#productTemplate'),
loader : $('#loader'),
err : $("#err")
},
imgPaths : {
logo : '../../img/logo.png'
},
urls : {
favouriteProducts : 'http://127.0.0.1/ajax/favorite_products',
fireabase : 'https://product-api.firebaseio.com'
},
errors : {
400 : '400',
500 : '500',
timeout : 'timeout'
},
errorMessages : {
serverConnectionFailed : 'Sunucuya bağlanılamıyor...',/*400*/
internalServerError : 'Sunucu taraflı bir hata oluştu...',/*500*/
timeout : 'Sayfa zaman aşımına uğradı. Lütfen tekrar deneyiniz...',
unidentifiedError : 'Beklenmeyen bir hata oluştu. Lütfen tekrar deneyiniz.'
},
stringBoundry : 16,
stringExtension : '...',
json : {
shortDesc : 'short_description',
name : 'name'
}
};
|
/*!
* Usher
* Copyright(c) 2014 meltmedia <mike@meltmedia.com>
*/
'use strict';
var async = require('async'),
winston = require('winston'),
STATUS = require('./tasks/status');
module.exports = WorkflowExecution;
function WorkflowExecution(tasks) {
if (!(this instanceof WorkflowExecution)) {
return new WorkflowExecution(tasks);
}
this.tasks = tasks;
}
WorkflowExecution.prototype.execute = function execute(context, done) {
done = done || function () {};
async.eachSeries(this.tasks, function (task, next) {
// Check to see if the task's dependencies have been resolved first
if (!context.isResolved(task)) {
var mask = STATUS.mask('pending');
context.setTaskStatus(task, mask);
return next(null, { name: task.name, mask: mask });
}
// Execute this task, updating the context for future tasks to utilize
task.execute(context, function (mask) {
winston.log('debug', 'Task %s completed with status: ', task.name, mask._value);
// Update the status
context.setTaskStatus(task, mask);
next(null, { name: task.name, mask: mask });
});
}, function (err, results) {
done(err, results);
});
};
|
(function() {
'use strict';
b3e.nodes.RestartBehaviorTree = b3e.node.create('RestartBehaviorTree', b3e.MODULATOR, {
group: 'behaviorTrees',
properties: [
['treeName', b3e.properties.String, {title: 'Tree name'}],
],
});
})();
|
/**
* Created by Wayne on 15/7/9.
*/
'use strict';
zhuzhuqs.directive('zzplacehold', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
var value;
var placehold = function () {
element.val(attr.zzplacehold)
};
var unplacehold = function () {
element.val('');
};
scope.$watch(attr.ngModel, function (val) {
value = val || '';
});
element.bind('focus', function () {
if(value == '') unplacehold();
});
element.bind('blur', function () {
if (element.val() == '') placehold();
});
ctrl.$formatters.unshift(function (val) {
if (!val) {
placehold();
value = '';
return attr.zzplacehold;
}
return val;
});
}
};
});
|
// Karma configuration
// Generated on Wed May 13 2015 17:38:34 GMT-0400 (EDT)
module.exports = function(config) {
config.set({
basePath: '',
browsers: ['Firefox', 'PhantomJS'],
frameworks: ['mocha', 'requirejs'],
files: [
'node_modules/mocha/mocha.js',
'node_modules/mocha/mocha.css',
'node_modules/chai/chai.js',
{pattern: 'bower_components/**/*.js', included: false},
{pattern: 'bower_components/**/*.css', included: false},
{pattern: 'lib/**/*.js', included: false},
{pattern: 'lib/**/*.spec.js', included: false},
'test-main.js',
'test/app.js'
],
exclude: [],
preprocessors: {},
reporters: ['progress'],
client: {
mocha: {
reporter: 'html'
}
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
singleRun: true
});
};
|
worldlyPosition = {
config: {
topLongitude: 10000
, leftLatitude: 20000
, bottomLongitude: 14000
, rightLatitude: 26000
}
, field: {}
, calcVars: function () {
var self = this
// Measured from left to right
self.field.width = self.config.rightLatitude - self.config.leftLatitude
self.field.latitudeConversionRate = self.field.width / 100
// Measured from top to bottom
self.field.height = self.config.bottomLongitude - self.config.topLongitude
self.field.longitudeConversionRate = self.field.height / 100
}
, longitudeToPercent: function (longitude) {
var self = this
self.calcVars()
, relativeLongitude = longitude - self.config.topLongitude
return relativeLongitude / self.field.longitudeConversionRate
}
, latitudeToPercent: function (latitude) {
var self = this
self.calcVars()
, relativeLatitude = latitude - self.config.leftLatitude
return relativeLatitude / self.field.latitudeConversionRate
}
}
Template.registerHelper('longitudeToPercent', function (longitude) {
return worldlyPosition.longitudeToPercent(longitude)
})
Template.registerHelper('latitudeToPercent', function (latitude) {
return worldlyPosition.latitudeToPercent(latitude)
})
|
'use strict'
const config = require('../config')
const pkg = require('../../package.json')
const winston = require('winston')
require('winston-papertrail').Papertrail // eslint-disable-line no-unused-expressions
function getPapertrail () {
return process.env.NODE_ENV !== 'production' ? {} : new winston.transports.Papertrail({
host: config.papertrailHost,
port: config.papertrailPort,
hostname: config.papertrailHostName,
logFormat: (level, message) => `${level.toUpperCase()} - ${message || ''}`
})
}
const winstonPapertrail = getPapertrail()
const winstonConsole = new winston.transports.Console({
formatter: options => `${new Date().toUTCString()} - ${options.level.toUpperCase()} - ${(options.message ? options.message : '')}`
})
const winstonTransports = process.env.NODE_ENV !== 'production' ? [winstonConsole] : [winstonConsole, winstonPapertrail]
const logger = new (winston.Logger)({
transports: winstonTransports
})
module.exports = (level, message) => {
const data = Array.isArray(message) ? message : [message]
const logMessage = `${pkg.name} - ${pkg.version}: ${data.join(' - ')}`
return logger.log(level, logMessage)
}
|
#!/usr/bin/env babel-node --harmony
// import firequeue from 'firequeue'
import firequeue from './src'
import { concat, throughSync } from 'stream-util'
import parallel from 'concurrent-transform'
const queue = firequeue.init('https://firequeue-test.firebaseio.com')
const logger = (fn) => throughSync(function(data) {
console.log(fn(data))
this.push(data)
})
// create some jobs
// in a real application you might want to use push to generate random job id instead
queue.incoming.child('job1').set({ task: 'task1', data: { name: 'job1' } })
queue.incoming.child('job2').set({ task: 'task1', data: { name: 'job2' } })
queue.incoming.child('job3').set({ task: 'task1', data: { name: 'job3' }, delayed: '20s' })
queue.incoming.child('job4').set({ task: 'task2', data: { name: 'job4' } })
queue.incoming.child('job5').set({ task: 'task3', data: { name: 'job5' } })
// listen to job updates
queue.jobs
.child('job1/state')
.on('value', (s) => console.log(`job1 changed state to ${s.val()}`))
// log 'queued'
// log 'activated'
// log 'completed'
// start queue engine
queue
.start()
.pipe(logger(({ task, key, state }) => `task: ${task}, job: ${key}, state: ${state}`))
// log task: task1, job: job1, state: queued
// log task: task1, job: job2, state: queued
// log task: task1, job: job3, state: delayed
// ...
// process task1
const task1 = queue
.read('task1')
.pipe(queue.process((job) => {
// do some work with job.key(), job.val()
return Promise.resolve()
}))
.pipe(logger(({ task, key, state }) => `task: ${task}, job: ${key}, state: ${state}`))
// log task: task1, job: job1, state: completed
// log task: task1, job: job2, state: completed
// ...
// process task2 with maxAttempts and backoff
const task2 = queue
.read('task2')
.pipe(queue.maxAttempts(2))
.pipe(queue.backoff('2s')) // wait 2s before retrying
.pipe(queue.process((job) => {
console.log('do some work with', job.key(), job.val())
const attempts = job.child('attempts').val() || 0
return attempts < 2
? Promise.reject()
: Promise.resolve()
}))
// process task3 with a concurrency of 10
const task3 = queue
.read('task3')
.pipe(parallel(queue.process((job) => {
console.log('do some work with', job.key(), job.val())
return Promise.resolve()
}), 10))
// remove completed jobs
concat(task1, task2, task3)
.pipe(queue.clean('completed'))
.pipe(logger(({ task, key, state }) => `task: ${task}, job: ${key}, state: ${state}`))
// log task: task1, job: job1, state: cleaned
// log task: task1, job: job2, state: cleaned
// ...
// 30sec later...
setTimeout(() => {
queue.stop().then(() => {
console.log('queue was stopped successfuly')
})
}, 30000)
|
exports = module.exports;
const request = require('request');
exports.answerJoke = function(sender, token) {
let messageData = {
"text":"Oh ho ho. My street name is \"the bot with the jokes\", FYI. Check out a few of them below."
+ " I love to share and make hoomans laugh!",
"quick_replies":[
{
"content_type":"text",
"title":"joke1",
"payload":"joke1"
},
{
"content_type":"text",
"title":"joke2",
"payload":"joke2"
},
{
"content_type":"text",
"title":"joke3",
"payload":"joke3"
},
{
"content_type":"text",
"title":"joke4",
"payload":"joke4"
},
{
"content_type":"text",
"title":"back",
"payload":"back"
}
]
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
messaging_type: "RESPONSE",
recipient: {id:sender},
message: messageData,
}
})
}
exports.answerJoke1 = function(sender, token) {
let messageData = {
"text":"What's Beethoven's favorite fruit?\nBA-NA-NA-NAAAAA!",
"quick_replies":[
{
"content_type":"text",
"title":"joke2",
"payload":"joke2"
},
{
"content_type":"text",
"title":"joke3",
"payload":"joke3"
},
{
"content_type":"text",
"title":"joke4",
"payload":"joke4"
},
{
"content_type":"text",
"title":"back",
"payload":"back"
}
]
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
messaging_type: "RESPONSE",
recipient: {id:sender},
message: messageData,
}
})
}
exports.answerJoke2 = function(sender, token) {
let messageData = {
"text":"Why was the musician arrested?\nHe was in TREBLE!",
"quick_replies":[
{
"content_type":"text",
"title":"joke1",
"payload":"joke1"
},
{
"content_type":"text",
"title":"joke3",
"payload":"joke3"
},
{
"content_type":"text",
"title":"joke4",
"payload":"joke4"
},
{
"content_type":"text",
"title":"back",
"payload":"back"
}
]
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
messaging_type: "RESPONSE",
recipient: {id:sender},
message: messageData,
}
})
}
exports.answerJoke3 = function(sender, token) {
let messageData = {
"text":"Why did Mozart kill his chickens?\nBecause they went BACH BACH BACH!",
"quick_replies":[
{
"content_type":"text",
"title":"joke1",
"payload":"joke1"
},
{
"content_type":"text",
"title":"joke2",
"payload":"joke2"
},
{
"content_type":"text",
"title":"joke4",
"payload":"joke4"
},
{
"content_type":"text",
"title":"back",
"payload":"back"
}
]
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
messaging_type: "RESPONSE",
recipient: {id:sender},
message: messageData,
}
})
}
exports.answerJoke4 = function(sender, token) {
let messageData = {
"text":"Why shouldn't you let your kids watch symphonies on the television?\nBecause there's too much VIOLINS and SAX on TV!",
"quick_replies":[
{
"content_type":"text",
"title":"joke1",
"payload":"joke1"
},
{
"content_type":"text",
"title":"joke2",
"payload":"joke2"
},
{
"content_type":"text",
"title":"joke3",
"payload":"joke3"
},
{
"content_type":"text",
"title":"back",
"payload":"back"
}
]
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
messaging_type: "RESPONSE",
recipient: {id:sender},
message: messageData,
}
})
}
|
const nconf = require('nconf');
nconf.argv()
.env()
.file({ file: './config.json' });
const task = require('./task');
const context = {
data: {
DOMAINS: nconf.get('DOMAINS'),
DAYS_THRESHOLD: nconf.get('DAYS_THRESHOLD'),
SLACK_INCOMING_WEBHOOK_URL: nconf.get('SLACK_INCOMING_WEBHOOK_URL')
}
};
task(context, (err) => {
if (err) {
console.log(JSON.stringify(err, null, 2));
return process.exit(1);
}
});
|
'use strict'
let models
class BlocksController {
constructor (projectModels) {
models = projectModels
}
async create (req, res) {
models.Blocks.create({
block: req.body.block
})
.then((block) => {
res.json({
error: false,
id: block.id
})
})
.catch((err) => {
res.json({
error: true,
message: err
})
})
}
get (req, res) {
models.Blocks.findById(req.params.id)
.then((block) => {
if (block === null) {
res.json({
error: true,
message: `Block ${req.params.id} not found`,
})
} else {
res.json({
error: false,
block,
})
}
})
.catch((err) => {
res.json({
error: true,
message: err,
})
})
}
listAll (req, res) {
models.Blocks.findAll({})
.then((blocks) => {
if(blocks.length === 0) {
res.json({
error: true,
message: "No blocks were found"
})
}else {
res.json({
error: false,
blocks
})
}
})
.catch((err) => {
res.json({
error: true,
message: err
})
})
}
update (req, res) {
models.Blocks.findById(req.params.id)
.then((block) => {
if (block === null) {
res.json({
error: true,
message: `Block ${req.params.id} not found`,
})
} else {
const block = req.body.block
block.block = block !== undefined ? block : block.block
block.save()
.then((block) => {
res.json({
error: false,
block,
})
})
}
})
.catch((err) => {
res.json({
error: true,
message: err,
})
})
}
}
module.exports = BlocksController
|
export { default } from './poop'
|
'use strict';
var EventDispatcher = createjs.EventDispatcher
, EaselEvent = createjs.Event;
var controls = {
37: 'moveleft',
39: 'moveright',
38: 'moveup',
40: 'movedown',
32: 'fire1'
};
var currentActions = {};
var actionService = module.exports = {
init: actions_init,
get: actions_get
}
var stage;
function actions_init(win, stage2) {
stage = stage2;
EventDispatcher.initialize(actionService);
win.addEventListener('keydown', onKeyDown);
win.addEventListener('keyup', onKeyUp);
win.addEventListener('mousemove', onMouseMove);
}
function actions_get() {
return currentActions;
}
function onKeyDown(event) {
var keyEvent = processEvent(event, 'down');
if (keyEvent)
currentActions[keyEvent.type] = keyEvent.data;
}
function onKeyUp(event) {
var keyEvent = processEvent(event, 'up');
if (keyEvent)
delete currentActions[keyEvent.type];
}
function onMouseMove(event) {
var canvasEl = stage && stage.canvas;
if (!canvasEl) return;
// May need to be more complex depending
var canvasXPos = canvasEl.offsetLeft;
var canvasYPos = canvasEl.offsetTop;
currentActions.mouse = {
winX: event.clientX,
winY: event.clientY,
stageX: event.clientX - canvasXPos,
stageY: event.clientY - canvasYPos,
target: event.target
};
}
function processEvent(event, phase) {
var generalEvent = prepareEvent(event, phase, 'key');
if (!generalEvent) return;
var specificEvent = prepareEvent(event, phase);
actionService.dispatchEvent(generalEvent);
actionService.dispatchEvent(specificEvent);
return specificEvent;
}
function prepareEvent(event, phase, type) {
var actionName = controls[event.keyCode];
if (!actionName) return;
type = type || actionName;
var eventData = {
name: actionName,
shiftKey: event.shiftKey,
metaKey: event.metaKey,
altKey: event.altKey,
ctrlKey: event.ctrlKey,
phase: phase
};
var keyEvent = new EaselEvent(type);
keyEvent.data = eventData;
keyEvent.nativeEvent = event;
return keyEvent;
}
|
/**
* Represents a student's response
*/
var StudentResponse = function (question, answeredCorrectly, abilityLevel) {
'use strict';
// TODO: Add some checking and error handling here.
// TODO: Possibly add a few more methods.
//console.log(question);
//console.log(answeredCorrectly);
//console.log(abilityLevel);
// The question that was asked.
this.question = question;
// Was the question properly answered?
this.answeredCorrectly = answeredCorrectly;
// The student's ability at the time it was answered.
this.abilityLevel = abilityLevel;
};
module.exports = StudentResponse;
|
var ebayTradingAPI = require('../index');
console.log(ebayTradingAPI.getUserToken());
ebayTradingAPI.setUserToken("adfsafdsaf");
console.log(ebayTradingAPI.getUserToken());
var config = require('./config.json');
ebayTradingAPI.setUserToken(config.eBayAuthToken);
console.log(ebayTradingAPI.getUserToken());
ebayTradingAPI.call(
"GetItem",
{
"ItemID" : 251636383648
},
function(result){
console.log(result);
}
);
|
import axios from 'axios';
import {Pet, PetList} from '../types/Pet';
/**
* @class PetService
*/
class PetService {
/**
* Get all pets the user has access to
* @return {Promise<Array<Pet>>} A promise that unwraps to an array of pets
*/
getAll() {
return axios.get('/pets')
.then(({data}) => new PetList(data))
.catch(e => {
console.error(e);
throw e;
});
}
/**
* [createPet description]
* @param {[type]} pet [description]
* @return {[type]} [description]
*/
createPet(pet) {
return axios.post('/pets', pet)
.then(({data}) => new Pet(data));
}
getPet(id) {
return axios.get(`/pets/${id}`)
.then(({data}) => new Pet(data));
}
deletePet(id) {
return axios.delete(`/pets/${id}`);
}
}
export default new PetService();
|
var underscore = require('./underscore.js');
var _executeBound = require('./_executeBound.js');
var restArguments = require('./restArguments.js');
// Partially apply a function by creating a version that has had some of its
// arguments pre-filled, without changing its dynamic `this` context. `_` acts
// as a placeholder by default, allowing any combination of arguments to be
// pre-filled. Set `_.partial.placeholder` for a custom placeholder argument.
var partial = restArguments(function(func, boundArgs) {
var placeholder = partial.placeholder;
var bound = function() {
var position = 0, length = boundArgs.length;
var args = Array(length);
for (var i = 0; i < length; i++) {
args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i];
}
while (position < arguments.length) args.push(arguments[position++]);
return _executeBound(func, bound, this, this, args);
};
return bound;
});
partial.placeholder = underscore;
module.exports = partial;
|
/**
* Renders graph with text symbols. Even though name says ASCII it supports
* unicode as well.
*
* @example
* var asciiGraphics = require('ngraph.ascii').graphics(graph);
* asciiGraphics.run(); // this will render graph with '*' symbols
*
* @param {ngraph.graph} graph - graph object to be rendered
*/
module.exports.graphics = require('./lib/graphics');
/**
* This primary serves as a mock for terminal, to test this package. But
* You can also use it if you want to graph as a text to somewhere else
* See `./lib/arrayScreen` for detailed information
*/
module.exports.arrayScreen = require('./lib/arrayScreen');
|
/*
* ToNumber() (E5 Section 9.3).
*
* Postfix increment changes its LHS, put returns ToNumber(oldValue) as the
* expression value. Use this get ToNumber() indirectly.
*/
function tonumber(x) {
var tmp = x;
return tmp++;
}
function zeroSign(x) {
if (x !== 0) {
return 'nz';
}
if (1 / x > 0) {
return 'pos';
} else {
return 'neg';
}
}
function test(x) {
var num = tonumber(x);
print(num, zeroSign(num));
}
/*===
NaN nz
0 pos
1 nz
0 pos
-1 nz
0 neg
0 pos
1 nz
NaN nz
Infinity nz
-Infinity nz
===*/
test(undefined);
test(null);
test(true);
test(false);
test(-1);
test(-0);
test(+0);
test(1);
test(NaN);
test(Number.POSITIVE_INFINITY);
test(Number.NEGATIVE_INFINITY);
/*===
-1 nz
-1 nz
0 neg
0 pos
0 pos
1 nz
17 nz
19 nz
-Infinity nz
Infinity nz
Infinity nz
3735928559 nz
3735928559 nz
3735928559 nz
NaN nz
===*/
/* String to number */
test('-1');
test(' -1 '); // whitespace is trimmed
test('-0');
test('+0');
test('0');
test('1');
test('000017'); // lead zeroes allowed, not interpreted as octal!
test('000019');
test(' -Infinity');
test(' +Infinity');
test(' Infinity');
test('0xdeadbeef');
test('0Xdeadbeef');
test(' \n0xdeadbeef\n');
test(' \n0xdeadbeefg\n'); // trailing garbage not allowed -> NaN
/*===
83 nz
83 nz
83 nz
83 nz
NaN nz
17 nz
17 nz
17 nz
17 nz
NaN nz
===*/
/* In ES6 0o123, and 0b10001 are recognized. Whitespace is also allowed.
* Note that whitespace is trimmed so these forms cannot be recognized
* by just peeking at the first few characters.
*/
test('0o123');
test('0O123');
test('\n0o123 \t');
test('\n0o000000123 \t');
test('\n0o000000123 x\t');
test('0b10001');
test('0B10001');
test('\t0b10001 \r\n');
test('\t0b0000010001 \r\n');
test('\t0b00000000000100012 \r\n'); // '2' is garbage to binary
/* XXX: object coercion */
|
module.exports = function (string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
|
/* eslint no-unused-expressions:0 */
import { createElement } from 'react';
import ReactDOM from 'react-dom';
import CheckboxGroup from './index';
import { $, $$, conformanceChecker } from '../boundless-utils-test-helpers/index';
import sinon from 'sinon';
describe('CheckboxGroup component', () => {
const mountNode = document.body.appendChild(document.createElement('div'));
const render = (vdom) => ReactDOM.render(vdom, mountNode);
const sandbox = sinon.sandbox.create();
const items = [ {
inputProps: {
name: 'gender-male',
checked: false,
},
label: 'Male',
}, {
inputProps: {
name: 'gender-female',
checked: false,
},
label: 'Female',
}, {
inputProps: {
name: 'gender-other',
checked: false,
},
label: 'Other',
} ];
const checkedItems = items.map((item) => {
return { ...item, inputProps: { ...item.inputProps, checked: true } };
});
const mixedItems = items.map((item, index) => {
return { ...item, inputProps: { ...item.inputProps, checked: !!(index % 2) } };
});
afterEach(() => {
ReactDOM.unmountComponentAtNode(mountNode);
sandbox.restore();
});
it('conforms to the Boundless prop interface standards', () => conformanceChecker(render, CheckboxGroup));
it('accepts an alternate wrapper HTML element type', () => {
render(<CheckboxGroup component='section' items={items} />);
expect($('section.b-checkbox-group')).not.toBeNull();
});
it('accepts an array of properly structured items', () => {
render(<CheckboxGroup items={items} />);
expect($$('.b-checkbox-wrapper:not(.b-checkbox-group-all) .b-checkbox').length).toBe(items.length);
});
it('accepts arbitrary React-supported HTML attributes via prop.selectAllProps', () => {
render(<CheckboxGroup selectAllProps={{ 'data-id': 'foo' }} />);
expect($('.b-checkbox-group-all[data-id="foo"]')).not.toBeNull();
});
describe('"select all" checkbox', () => {
it('will not render if `selectAll` is `CheckboxGroup.selectAll.NONE`', () => {
render(<CheckboxGroup items={items} selectAll={CheckboxGroup.selectAll.NONE} />);
expect($('.b-checkbox-group-all')).toBeNull();
});
it('renders as the first child if `selectAll` is `CheckboxGroup.selectAll.BEFORE`', () => {
render(<CheckboxGroup items={items} selectAll={CheckboxGroup.selectAll.BEFORE} />);
expect($('.b-checkbox-group > *:first-child')).toBe($('.b-checkbox-group-all'));
});
it('renders in the last position if `selectAll` is `CheckboxGroup.selectAll.AFTER`', () => {
render(<CheckboxGroup items={items} selectAll={CheckboxGroup.selectAll.AFTER} />);
expect($('.b-checkbox-group > *:last-child')).toBe($('.b-checkbox-group-all'));
});
it('accepts a name passed by `selectAllProps.className`', () => {
render(<CheckboxGroup items={items} selectAllProps={{ className: 'foo' }} />);
expect($('.b-checkbox-group-all.foo')).not.toBeNull();
});
it('accepts a name passed by `selectAllProps.inputProps.name`', () => {
render(<CheckboxGroup items={items} selectAllProps={{ inputProps: { name: 'foo' } }} />);
expect($('.b-checkbox-group-all .b-checkbox[name="foo"]')).not.toBeNull();
});
it('checks all children', () => {
const stub = sandbox.stub();
render(<CheckboxGroup items={items} onAllChecked={stub} />);
$('.b-checkbox-group-all .b-checkbox-unchecked').click();
expect(stub.calledOnce).toBe(true);
});
it('unchecks all children', () => {
const stub = sandbox.stub();
render(<CheckboxGroup items={checkedItems} onAllUnchecked={stub} />);
$('.b-checkbox-group-all .b-checkbox-checked').click();
expect(stub.calledOnce).toBe(true);
});
it('is indeterminate if children are in different checked states', () => {
render(<CheckboxGroup items={mixedItems} />);
expect($('.b-checkbox-group-all .b-checkbox-mixed')).not.toBeNull();
});
it('makes all children checked if clicked in indeterminate state', () => {
const stub = sandbox.stub();
render(<CheckboxGroup items={mixedItems} onAllChecked={stub} />);
$('.b-checkbox-group-all .b-checkbox-mixed').click();
expect(stub.calledOnce).toBe(true);
});
it('renders a custom label if given', () => {
render(<CheckboxGroup items={mixedItems} selectAllProps={{ label: 'foo' }} />);
expect($('.b-checkbox-group-all .b-checkbox-label')).not.toBeNull();
expect($('.b-checkbox-group-all .b-checkbox-label').textContent).toBe('foo');
});
});
});
|
// Config params for the Angular App
var
contentLoaded = false,
template_ext = '.html',
host = (function () {
return '//' + location.host + '/';
})(),
firstLoad = true;
jQuery(window).scroll(function (event) {
if (jQuery(this).scrollTop() > 200) {
jQuery('.static-share-header').css({
transform: 'translateX(0px) translateY(0px)',
transition: 'transform 500ms'
});
} else {
jQuery('.static-share-header').css({
transform: 'translateX(0px) translateY(-71px)',
transition: 'transform 500ms'
});
}
});
function isMobile() {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
}
function refreshAdsense() {
(adsbygoogle = window.adsbygoogle || []).push({});
}
function addUnits() {
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "ca-pub-3833845702235676",
enable_page_level_ads: true
});
console.log('units added');
}
$(document).on('click', 'a.google_vignette_inst', function (e) {
console.log(this);
e.preventDefault();
return false;
});
|
var sh = require('../');
sh.log.on('message', function (level, message) {
console.log(level, message);
})
sh.log.mode = 'event';
sh.config.setAlias('lsHidden', 'ls', ['-a']);
sh.config.setAlias('lsFull', sh.cmd('ls', ['-l']));
sh('lsHidden').on('success', function (output) {
console.assert(output.indexOf('..') !== -1);
});
sh('lsHidden', ['-l']).on('success', function (output) {
console.assert(output.indexOf('..') !== -1);
});
sh('lsFull').on('success', function (output) {
console.assert(output.indexOf('LICENSE.md') !== -1);
});
|
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M3 2l2.21 20H18.8L21 2H3zm9 17c-1.66 0-3-1.34-3-3 0-2 3-5.4 3-5.4s3 3.4 3 5.4c0 1.66-1.34 3-3 3zm6.33-11H5.67l-.44-4h13.53l-.43 4z"
}), 'LocalDrinkSharp');
|
function parseAngular(arr) {
let modules = new Map();
let elements = new Map();
let appPattern = /^\$app='([^']+)'$/;
let controllerPattern = /^\$controller='([^']+)'&app='([^']+)'$/;
let modelPattern = /^\$model='([^']+)'&app='([^']+)'$/;
let viewPattern = /^\$view='([^']+)'&app='([^']+)'$/;
arr = arr.filter(e => e !== '');
function newMapEntry(map, match) {
map.set(match, new Map());
map.get(match).set('controllers', new Set());
map.get(match).set('models', new Set());
map.get(match).set('views', new Set());
}
function addToMaps(match, type) {
if (modules.has(match[2])) {
modules.get(match[2]).get(type).add(match[1]);
} else {
if (elements.has(match[2])) {
elements.get(match[2]).get(type).add(match[1]);
} else {
newMapEntry(elements, match[2]);
elements.get(match[2]).get(type).add(match[1]);
}
}
}
for (let str of arr) {
if (str.startsWith('$app')) {
let match = appPattern.exec(str);
newMapEntry(modules, match[1]);
if (elements.has(match[1])) {
modules.get(match[1]).set('controllers', elements.get(match[1]).get('controllers'));
modules.get(match[1]).set('models', elements.get(match[1]).get('models'));
modules.get(match[1]).set('views', elements.get(match[1]).get('views'));
elements.delete(match[1]);
}
appPattern.lastIndex = 0;
}
if (str.startsWith('$controller')) {
let match = controllerPattern.exec(str);
addToMaps(match, 'controllers');
controllerPattern.lastIndex = 0;
}
if (str.startsWith('$model')) {
let match = modelPattern.exec(str);
addToMaps(match, 'models');
modelPattern.lastIndex = 0;
}
if (str.startsWith('$view')) {
let match = viewPattern.exec(str);
addToMaps(match, 'views');
viewPattern.lastIndex = 0;
}
}
let sortedModules = Array.from(modules.keys()).sort((a, b) => {
if (modules.get(b).get('controllers').size !== modules.get(a).get('controllers').size) {
return modules.get(b).get('controllers').size - modules.get(a).get('controllers').size;
}
if (modules.get(a).get('models').size !== modules.get(b).get('models').size) {
return modules.get(a).get('models').size - modules.get(b).get('models').size;
}
return 0;
});
let output = '{';
for (let module of sortedModules) {
output += `"${module}":{"controllers":`;
output += JSON.stringify(Array.from(modules.get(module).get('controllers').keys()).sort((a, b) => a.localeCompare(b)));
output += ',"models":';
output += JSON.stringify(Array.from(modules.get(module).get('models').keys()).sort((a, b) => a.localeCompare(b)));
output += ',"views":';
output += JSON.stringify(Array.from(modules.get(module).get('views').keys()).sort((a, b) => a.localeCompare(b)));
output += '},';
}
output = output.substr(0, output.length - 1);
output += '}';
console.log(output);
}
parseAngular(['$app=\'MyApp\'',
'$controller=\'My Controller\'&app=\'MyApp\'',
'$model=\'My Model\'&app=\'MyApp\'',
'$view=\'My View\'&app=\'MyApp\'']);
parseAngular(['$controller=\'PHPController\'&app=\'Language Parser\'',
'$controller=\'JavaController\'&app=\'Language Parser\'',
'$controller=\'C#Controller\'&app=\'Language Parser\'',
'$controller=\'C++Controller\'&app=\'Language Parser\'',
'$app=\'Garbage Collector\'',
'$controller=\'GarbageController\'&app=\'Garbage Collector\'',
'$controller=\'SpamController\'&app=\'Garbage Collector\'',
'$app=\'Language Parser\'']);
|
"use strict";
const utils = require('../utils/utils');
const ruleRegexp = /^S?([0-9]*)\/B?([0-9]*)\/C?([1-9][0-9]*)([MV]?)([0-9]*)$/i;
function getNeighbourMethod (methodId) {
if (methodId === 'V' || methodId === 'v' || methodId === 'von-neumann') {
return 'von-neumann';
} else {
return 'moore';
}
}
function generationsFunction (currentValue, neighbours) {
let sum = 0;
let result = 0;
for (let index = 0; index < neighbours.length; index++) {
sum = sum + (neighbours[index] === 1 ? 1 : 0);
}
if (currentValue === 0 && this.birth.indexOf(sum) > -1) {
result = 1;
} else if (currentValue === 1 && this.survival.indexOf(sum) > -1) {
result = 1;
} else if (currentValue > 0) {
result = (currentValue + 1) % this.stateCount;
}
return result;
}
module.exports = function parseRuleString (ruleString) {
const extractedRule = ruleRegexp.exec(utils.stripWhitespaces(ruleString));
return extractedRule ? {
process: generationsFunction,
ruleFormat: 'generations',
ruleString: ruleString,
survival: utils.splitStringInNumberArray(extractedRule[1]),
birth: utils.splitStringInNumberArray(extractedRule[2]),
stateCount: parseInt(extractedRule[3], 10) || 1,
neighbourhoodType: getNeighbourMethod(extractedRule[4]),
neighbourhoodRange: parseInt(extractedRule[5], 10) || 1
} : null;
};
|
function expandLeft() {
document.getElementById("sectionLeft").style.left = "0";
document.getElementById("sectionMiddle").style.left = "80%";
document.getElementById("sectionRight").style.left = "90%";
document.getElementById("titleLeft").style.left = "40%";
document.getElementById("titleMiddle").style.left = "0";
document.getElementById("titleRight").style.left = "0";
}
function expandMiddle() {
document.getElementById("sectionLeft").style.left = "0";
document.getElementById("sectionMiddle").style.left = "10%";
document.getElementById("sectionRight").style.left = "90%";
document.getElementById("titleLeft").style.left = "0";
document.getElementById("titleMiddle").style.left = "40%";
document.getElementById("titleRight").style.left = "0";
}
function expandRight() {
document.getElementById("sectionLeft").style.left = "0";
document.getElementById("sectionMiddle").style.left = "10%";
document.getElementById("sectionRight").style.left = "20%";
document.getElementById("titleLeft").style.left = "0";
document.getElementById("titleMiddle").style.left = "0";
document.getElementById("titleRight").style.left = "40%";
}
|
$(function() {
var toc = $('.toc-link'),
sidebar = $('#sidebar'),
main = $('#main'),
menu = $('#menu'),
x1, y1;
// run this function after pjax load.
var afterPjax = function() {
// open links in new tab.
$('#main').find('a').filter(function() {
return this.hostname != window.location.hostname;
}).attr('target', '_blank');
// discus comment.
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//devwayne' + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
// your scripts
};
afterPjax();
// NProgress
NProgress.configure({ showSpinner: false });
// Pjax
$(document).pjax('#sidebar-avatar, .toc-link', '#main', {
fragment: '#main',
timeout: 3000
});
$(document).on({
'pjax:click': function() {
NProgress.start();
main.removeClass('fadeIn');
},
'pjax:end': function() {
afterPjax();
NProgress.done();
main.scrollTop(0).addClass('fadeIn');
menu.add(sidebar).removeClass('open');
}
});
// Tags Filter
$('#sidebar-tags').on('click', '.sidebar-tag', function() {
var filter = $(this).data('filter');
if (filter === 'all') {
toc.fadeIn(350);
} else {
toc.hide();
$('.toc-link[data-tags~=' + filter + ']').fadeIn(350);
}
$(this).addClass('active').siblings().removeClass('active');
});
// Menu
menu.on('click', function() {
$(this).add(sidebar).toggleClass('open');
});
});
|
// @flow
import SRStudyTaskEditor from '../js/components/screens/SRStudyTaskEditor'
test('input title label visibility', () => {
// hidden at launch when not readonly
// hidden when place text input placeholder is still visible
})
test('Added SRSpacedRepetition properties', () => {
// expect(.easinessFactor).toBeCloseTo(2.5)
// expect(.interval).toBe(1)
// expect(.repetition).toBe(0)
})
test('Check default edit UI elements properties', () => {
// when editable: default selected date, intesity
// when readonly: not editable, edit button, delete button, visible rating history
})
test('Custom selected date', () => {
})
test('', () => {
})
|
this.NesDb = this.NesDb || {};
NesDb[ '7974126FFE8C5C064D6A0BDDA14646F874FA7109' ] = {
"$": {
"name": "Dokuganryuu Masamune",
"altname": "独眼竜政宗",
"class": "Licensed",
"subclass": "3rd-Party",
"catalog": "NAM-DG-5500",
"publisher": "Namco",
"developer": "Namco",
"region": "Japan",
"players": "1",
"date": "1988-04-05"
},
"cartridge": [
{
"$": {
"system": "Famicom",
"crc": "10C8F2FA",
"sha1": "7974126FFE8C5C064D6A0BDDA14646F874FA7109",
"dump": "ok",
"dumper": "bootgod",
"datedumped": "2007-05-20"
},
"board": [
{
"$": {
"type": "NAMCOT-163",
"pcb": "60-12",
"mapper": "19"
},
"prg": [
{
"$": {
"size": "128k",
"crc": "96533999",
"sha1": "1FA339A59832562A3ACD1B524F6E41ED125486BF"
}
}
],
"chr": [
{
"$": {
"size": "128k",
"crc": "C73DD1AA",
"sha1": "6A841634C15AD5EA3562572224F662D1C910CF88"
}
}
],
"wram": [
{
"$": {
"size": "8k",
"battery": "1"
}
}
],
"chip": [
{
"$": {
"type": "<163>"
}
}
]
}
]
}
]
};
|
'use strict';
/*
* Module dependencies
*/
export default class Index{
//Constructor de la clase
constructor(){
}
}
|
'use strict';
const _ = require('lodash');
const Bluebird = require('bluebird');
const request = Bluebird.promisifyAll(require('request'));
const BASE_URL = 'https://api.test.rb.is/v1/';
function createClaim(token, phoneNumber) {
return request.getAsync({
url: `${BASE_URL}/accounts/identifier?identifierId=${phoneNumber}`,
json: true,
headers: {
Authorization: `Bearer ${token}`
}
})
.then(res => {
if (res.statusCode === 404) {
return null;
}
return res.body;
});
}
module.exports = {
createClaim
};
|
"use strict";
var flatMap = function (arr, fn) {
return Array.prototype.concat.apply([], arr.map(fn));
};
var xmlQuery = function (ast) {
var nodes = Array.isArray(ast) ? ast : (ast ? [ast] : []);
var length = nodes.length;
var get = function (index) { return nodes[index]; };
var children = function () {
return xmlQuery(flatMap(nodes, function (node) { return node.children; }));
};
var findInNode = function (node, sel) {
var res = (node.name === sel) ? [node] : [];
return res.concat(flatMap(node.children, function (node) { return findInNode(node, sel); }));
};
var find = function (sel) {
return xmlQuery(flatMap(nodes, function (node) { return findInNode(node, sel); }));
};
var has = function (sel) {
if (nodes.length === 0) {
return false;
}
if (nodes.some(function (node) { return node.name === sel; })) {
return true;
}
return children().has(sel);
};
var attr = function (name) {
if (length) {
var attrs = nodes[0].attributes;
return name ? attrs[name] : attrs;
}
};
var eq = function (index) { return xmlQuery(nodes[index]); };
var first = function () { return eq(0); };
var last = function () { return eq(length - 1); };
var map = function (fn) { return nodes.map(fn); };
var each = function (fn) { return nodes.forEach(fn); };
var size = function () { return length; };
var prop = function (name) {
var node = get(0);
if (node) {
return node[name];
}
};
var text = function () {
var res = '';
each(function (node) {
if (node.type === 'text') {
res += node.value;
}
else {
res += xmlQuery(node).children().text();
}
});
return res;
};
return {
attr: attr,
children: children,
each: each,
eq: eq,
find: find,
has: has,
first: first,
get: get,
last: last,
length: length,
map: map,
prop: prop,
size: size,
text: text,
ast: ast,
};
};
module.exports = xmlQuery;
|
define({
"module-appland": {
"projectName": 'Project Name'
}
});
|
/*
| Ast minus assignment ( -= )
*/
/*
| The jion definition.
*/
if( JION )
{
throw{
id : 'jion$ast_minusAssign',
attributes :
{
left :
{
comment : 'left-hand side',
type : require( '../typemaps/astExpression' )
},
right :
{
comment : 'right-hand side',
type : require( '../typemaps/astExpression' )
}
}
};
}
/*
| Capsule
*/
(function() {
'use strict';
var
ast_minusAssign,
prototype;
ast_minusAssign = require( '../this' )( module, 'ouroboros' );
prototype = ast_minusAssign.prototype;
/**/if( CHECK )
/**/{
/**/ var
/**/ util;
/**/
/**/ util = require( 'util' );
/**/
/*** /
**** | Custom inspect
**** /
***/ prototype.inspect =
/**/ function(
/**/ depth,
/**/ opts
/**/ )
/**/ {
/**/ var
/**/ postfix,
/**/ result;
/**/
/**/ if( !opts.ast )
/**/ {
/**/ result = 'ast{ ';
/**/
/**/ postfix = ' }';
/**/ }
/**/ else
/**/ {
/**/ result = postfix = '';
/**/ }
/**/
/**/ opts.ast = true;
/**/
/**/ result += '( ' + util.inspect( this.left, opts ) + ' )';
/**/
/**/ result += ' -= ';
/**/
/**/ result += '( ' + util.inspect( this.right, opts ) + ' )';
/**/
/**/ return result + postfix;
/**/ };
/**/}
} )( );
|
/*
* poeditor_htmid
*
* This is an adaptation of a plugin found https://github.com/Philoozushi/grunt-poeditor-pz . This plugin will download the localizations for a particular project ID and then get all of the string associated with the project. This plugin is to be used in combination with the other htmid plugins.
*
* Copyright (c) 2016 Codin Pangell
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'<%= nodeunit.tests %>'
],
options: {
jshintrc: '.jshintrc'
}
},
// Before generating any new files, remove any previously-created files.
clean: {
tests: ['tmp']
},
// Configuration to be run (and then tested).
poeditor_htmid: {
},
// Unit tests.
nodeunit: {
tests: ['test/*_test.js']
}
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
// Whenever the "test" task is run, first clean the "tmp" dir, then run this
// plugin's task(s), then test the result.
grunt.registerTask('test', ['clean', poeditor_htmid, 'nodeunit']);
// By default, lint and run all tests.
grunt.registerTask('default', ['jshint', 'test']);
};
|
var assign = require('object-assign');
var number = require('as-number');
module.exports = function (THREE) {
return function (opt) {
opt = opt || {};
var ret = assign({
transparent: true,
uniforms: {
thickness: { type: 'f', value: number(opt.thickness, 0.1) },
opacity: { type: 'f', value: number(opt.opacity, 1.0) },
diffuse: { type: 'c', value: new THREE.Color(opt.diffuse) },
time: { type: 'f', value: 0 }
},
vertexShader: [
'uniform float thickness;',
'attribute float lineMiter;',
'attribute vec2 lineNormal;',
'attribute float lineDistance;',
'varying float edge;',
'varying float lineU;',
'uniform float time;',
'void main() {',
'edge = sign(lineMiter);',
'lineU = lineDistance;',
'vec3 pointPos = position.xyz + vec3(lineNormal * thickness/2.0 * lineMiter, 0.0);',
'gl_Position = projectionMatrix * modelViewMatrix * vec4( pointPos, 1.0 );',
'}'
].join('\n'),
fragmentShader: [
'varying float edge;',
'varying float lineU;',
'uniform float opacity;',
'uniform float time;',
'uniform vec3 diffuse;',
'void main() {',
'float lineV = 1.0 - abs(edge);',
'lineV = smoothstep(0.0, 0.8, lineV);',
'float radial = lineU * sin(time + lineU*2.0);',
'gl_FragColor = vec4(vec3(lineV), 1.0);',
'gl_FragColor.a *= opacity * radial * lineV;',
'}'
].join('\n')
}, opt);
// remove to satisfy r73
delete ret.thickness;
delete ret.opacity;
delete ret.diffuse;
var threeVers = (parseInt(THREE.REVISION, 10) || 0) | 0;
if (threeVers < 72) {
// Old versions need to specify shader attributes
ret.attributes = {
lineMiter: { type: 'f', value: 0 },
lineDistance: { type: 'f', value: 0 },
lineNormal: { type: 'v2', value: new THREE.Vector2() }
};
}
return ret;
};
};
|
var through = require('through2'),
falafel = require('falafel'),
fs = require('fs')
module.exports = lintroller
function lintroller(_checks) {
var count = 0,
files = [],
stream = through(add_files, noop),
checks = _checks || []
checks.forEach(resolve_check)
checks = checks.filter(Boolean)
return stream
function add_files(chunk, enc, next) {
files.push(chunk.toString())
if (!count) {
count++
read_file(files.shift())
}
next()
}
function read_file(filename) {
fs.readFile(filename, 'utf8', process_file)
function process_file(err, data) {
if (err) process.stdout.write('whoopsie goldberg') && process.exit(1)
falafel('' + data, check_node)
if (!files.length) return finish()
count++
read_file(files.shift())
}
}
function check_node(node) {
checks.forEach(run_check)
function run_check(check) {
if (check.selectors.some(match_selector)) {
check.rules.forEach(compare_and_count)
}
function match_selector(selector) {
return selector(node)
}
function compare_and_count(rule) {
if (rule.test(node)) rule.count++
}
}
}
function finish() {
process.stdout.write('processed ' + count + ' files\n')
console.dir(checks)
}
}
function resolve_check(check) {
if (typeof check === 'string') {
try {
check = require(check)
} catch(e) {
check = false
return
}
}
if (!check.rules || !check.rules.length) {
check = false
return
}
check.rules.forEach(validate_rules)
check.rules = check.rules.filter(Boolean)
function validate_rules(rule) {
if (!rule.name || !rule.test || typeof rule.test !== 'function') {
rule = false
return
}
rule.description = rule.description || rule.name
rule.count = rule.count || 0
}
}
function noop() {}
|
const _ = require("lodash");
const logger = require("../util/logger");
const MANDATORY_ENV_VARS = [
"PORT",
"FB_PAGE_ACCESS_TOKEN",
"FB_VERIFICATION_TOKEN",
"VIRTUAL_ASSISTANT_NAME",
"SOCIALMINER_HOST",
"SOCIALMINER_CHAT_FEED_ID",
"CCX_QUEUE_ID",
];
module.exports = {
/**
* Validates the deployed environment to ensure
* all required variables are defined. If not, it
* aborts the entire application.
*/
validateEnvironment: () => {
_.each(MANDATORY_ENV_VARS, (variable) => {
if (_.isUndefined(process.env[variable]) ||
_.isEmpty(_.trim(process.env[variable]))) {
throw new ReferenceError(`SEVERE ERROR: MISSING/INVALID environment variable value: ${variable}`);
}
});
},
/**
* Logs an error with its stack trace
*
* @param {*} err
* @param {String} msg
*/
logErrorWithStackTrace: (err, msg) => {
logger.error("Something went wrong.", err, new Error(msg).stack);
},
/**
* Properly decode a URLEncoded string
*
* @param {String} str
*/
decodeString: (str) => {
let decodedStr = decodeURIComponent(str.replace(/\+/g, " "));
decodedStr = decodedStr.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """)
.replace(/'/g, "'")
.replace(/\//g, "/");
return decodedStr;
},
};
|
import Inflector from 'ember-inflector';
const { inflector } = Inflector;
inflector.uncountable('knowledge');
inflector.uncountable('account-access');
export default { };
|
'use strict';
var build = "build"; // ビルド結果が出力されるディレクトリ
var tmp = ".tmp"; // Sassコンパイルで作成されるcssのテンポラリーファイルの場所
var src = 'src'; // ソースコードの場所
module.exports = {
build: build,
tmp: tmp,
src: src,
sf: {
//Salesforceのビルド結果が出力されるディレクトリ
sfbuild: build + "/sf",
// デプロイする静的リソースの名前
resourceName: "vfResource",
// apex:pageタグの属性値
apexPageOption: {
// デフォルト値、すべてのページに適用されます
'default': {
"docType": "html-5.0",
"showHeader": false,
"standardStyleSheets": false
},
// ページごとの設定、デフォルト値より優先されます
'topPage': {
controller: 'RemoteActionTestController'
}
},
// 開発環境の認証情報
development: {
user: '<Your salesforce email address>',
pass: '<Your salesforce password>',
token: '<Your salesforce access token>',
apiVersion: '30.0'
},
// SandBox環境の認証情報
sandbox: {
user: '<Your salesforce email address>',
pass: '<Your salesforce password>',
token: '<Your salesforce access token>',
apiVersion: '30.0'
},
// Visualforceページと静的リソースの取得先
retrieve: {
user: '<Your salesforce email address>',
pass: '<Your salesforce password>',
token: '<Your salesforce access token>',
apiVersion: '30.0'
}
},
script: {
// JavaScriptの結合順序を指定します
src: [
src + '/js/main.js',
src + '/js/chart/*.js',
src + '/js/controller/*.js'
]
},
css: {
// CSSの結合順序を指定します Sassはコンパイル後のcssを指定します
src: [
src + "/css/normalize.css",
tmp + "/css/main.css"
]
}
}
|
/**
* Created by 文琪 on 2015/3/3.
* 用于读取云大主页上的通知,并在数据库中保存发送标识。
*/
var MongoClient = require('mongodb').MongoClient,
ObjectID = require('mongodb').ObjectID;
var array = require('array');
var uuid = require('node-uuid');
var date = require('date-extended');
var sa = require('superagent');
var cheer = require('cheerio');
module.exports = function(connString){
return {
/**
* 从数据库中读取尚未发送的通知
* @param options
* @param callback
*/
getNotSendNotices: function (options, callback) {
MongoClient.connect(connString, function (err, db) {
var notice = db.collection('ynu_notices');
at.find({
'sended': false
}).toArray(function (err, notices) {
db.close();
callback(err, notices);
});
});
},
/**
* 从网页抓取通知,并标记为未发送
* @param callback
*/
catchNotices: function (callback) {
sa.get('http://www.ynu.edu.cn/xwzx/xygg/index.html').end(function(res2){
if(res2.ok){
var $ = cheer.load(res2.text);
var articles = [];
$('dl.right ul li').each(function(i, li){
if(i > 5) return;
var a = $(li).find('a');
articles.push({
title: a.text().trim(),
picurl: '',
'sended': false,
url: a.attr('href')
});
});
MongoClient.connect(connString, function (err, db) {
var notices = db.collection('ynu_notices');
var count = 0;
array(articles).each(function(article){
notices.update({
url: article
}, article, {upsert: true}, function (err, doc) {
if(++count === articles.length){
db.close();
callback(err, articles);
}
});
});
});
}
});
}
};
}
|
const { ALCore } = require('./lib/AurelionCore');
ALCore.startApp();
|
define([
"dojo/_base/declare", // declare
"dojo/dom-construct", // domConstruct.create
"dojo/has",
"dojo/_base/lang", // lang.hitch
"dojo/on",
"dojo/_base/window", // win.body
"../Viewport"
], function(declare, domConstruct, has, lang, on, win, Viewport){
// module:
// dijit/form/_ExpandingTextAreaMixin
// feature detection, true for mozilla and webkit
has.add("textarea-needs-help-shrinking", function(){
var body = win.body(), // note: if multiple documents exist, doesn't matter which one we use
te = domConstruct.create('textarea', {
rows:"5",
cols:"20",
value: ' ',
style: {zoom:1, fontSize:"12px", height:"96px", overflow:'hidden', visibility:'hidden', position:'absolute', border:"5px solid white", margin:"0", padding:"0", boxSizing: 'border-box', MsBoxSizing: 'border-box', WebkitBoxSizing: 'border-box', MozBoxSizing: 'border-box' }
}, body, "last");
var needsHelpShrinking = te.scrollHeight >= te.clientHeight;
body.removeChild(te);
return needsHelpShrinking;
});
return declare("dijit.form._ExpandingTextAreaMixin", null, {
// summary:
// Mixin for textarea widgets to add auto-expanding capability
_setValueAttr: function(){
this.inherited(arguments);
this.resize();
},
postCreate: function(){
this.inherited(arguments);
var textarea = this.textbox;
textarea.style.overflowY = "hidden";
this.own(on(textarea, "focus, resize", lang.hitch(this, "_resizeLater")));
},
startup: function(){
this.inherited(arguments);
this.own(Viewport.on("resize", lang.hitch(this, "_resizeLater")));
this._resizeLater();
},
_onInput: function(e){
this.inherited(arguments);
this.resize();
},
_estimateHeight: function(){
// summary:
// Approximate the height when the textarea is invisible with the number of lines in the text.
// Fails when someone calls setValue with a long wrapping line, but the layout fixes itself when the user clicks inside so . . .
// In IE, the resize event is supposed to fire when the textarea becomes visible again and that will correct the size automatically.
//
var textarea = this.textbox;
// #rows = #newlines+1
textarea.rows = (textarea.value.match(/\n/g) || []).length + 1;
},
_resizeLater: function(){
this.defer("resize");
},
resize: function(){
// summary:
// Resizes the textarea vertically (should be called after a style/value change)
var textarea = this.textbox;
function textareaScrollHeight(){
var empty = false;
if(textarea.value === ''){
textarea.value = ' ';
empty = true;
}
var sh = textarea.scrollHeight;
if(empty){ textarea.value = ''; }
return sh;
}
if(textarea.style.overflowY == "hidden"){ textarea.scrollTop = 0; }
if(this.busyResizing){ return; }
this.busyResizing = true;
if(textareaScrollHeight() || textarea.offsetHeight){
var newH = textareaScrollHeight() + Math.max(textarea.offsetHeight - textarea.clientHeight, 0);
var newHpx = newH + "px";
if(newHpx != textarea.style.height){
textarea.style.height = newHpx;
textarea.rows = 1; // rows can act like a minHeight if not cleared
}
if(has("textarea-needs-help-shrinking")){
var origScrollHeight = textareaScrollHeight(),
newScrollHeight = origScrollHeight,
origMinHeight = textarea.style.minHeight,
decrement = 4, // not too fast, not too slow
thisScrollHeight,
origScrollTop = textarea.scrollTop;
textarea.style.minHeight = newHpx; // maintain current height
textarea.style.height = "auto"; // allow scrollHeight to change
while(newH > 0){
textarea.style.minHeight = Math.max(newH - decrement, 4) + "px";
thisScrollHeight = textareaScrollHeight();
var change = newScrollHeight - thisScrollHeight;
newH -= change;
if(change < decrement){
break; // scrollHeight didn't shrink
}
newScrollHeight = thisScrollHeight;
decrement <<= 1;
}
textarea.style.height = newH + "px";
textarea.style.minHeight = origMinHeight;
textarea.scrollTop = origScrollTop;
}
textarea.style.overflowY = textareaScrollHeight() > textarea.clientHeight ? "auto" : "hidden";
if(textarea.style.overflowY == "hidden"){ textarea.scrollTop = 0; }
}else{
// hidden content of unknown size
this._estimateHeight();
}
this.busyResizing = false;
}
});
});
|
describe('Reinforced Plate', function() {
integration(function() {
describe('Reinforced Plate\'s constant ability', function() {
beforeEach(function() {
this.setupTest({
phase: 'conflict',
player1: {
inPlay: ['brash-samurai', 'doji-whisperer'],
hand: ['reinforced-plate', 'way-of-the-scorpion']
},
player2: {
inPlay: ['doomed-shugenja'],
hand: ['kirei-ko', 'way-of-the-scorpion', 'assassination']
}
});
this.brash = this.player1.findCardByName('brash-samurai');
this.whisperer = this.player1.findCardByName('doji-whisperer');
this.p1scorpion = this.player1.findCardByName('way-of-the-scorpion');
this.p2scorpion = this.player2.findCardByName('way-of-the-scorpion');
this.kireiko = this.player2.findCardByName('kirei-ko');
this.reinforcedPlate = this.player1.playAttachment('reinforced-plate', this.brash);
this.assassination = this.player2.findCardByName('assassination');
this.noMoreActions();
});
it('should make its wearer immune to opponent events during a military conflict', function() {
this.initiateConflict({
type: 'military',
attackers: [this.brash],
defenders: []
});
expect(this.player2).toHavePrompt('Conflict Action Window');
this.player2.clickCard(this.p2scorpion);
expect(this.player2).toHavePrompt('Conflict Action Window');
this.player2.pass();
this.player1.clickCard(this.brash);
expect(this.player2).not.toBeAbleToSelect(this.kireiko);
});
it('should not make its wearer immune to own events during a military conflict', function() {
this.initiateConflict({
type: 'military',
attackers: [this.brash],
defenders: []
});
this.player2.pass();
this.player1.clickCard(this.p1scorpion);
expect(this.player1).toBeAbleToSelect(this.brash);
this.player1.clickCard(this.brash);
expect(this.brash.isDishonored).toBe(true);
});
it('should not make its wearer immune to opponent events during a political conflict', function() {
this.initiateConflict({
type: 'political',
attackers: [this.brash],
defenders: []
});
expect(this.player2).toHavePrompt('Conflict Action Window');
this.player2.clickCard(this.p2scorpion);
expect(this.player2).toBeAbleToSelect(this.brash);
this.player2.clickCard(this.brash);
expect(this.brash.isDishonored).toBe(true);
this.player1.clickCard(this.brash);
expect(this.player2).toBeAbleToSelect(this.kireiko);
this.player2.clickCard(this.kireiko);
expect(this.brash.bowed).toBe(true);
});
it('should not make its wearer immune to opponent events if not participating', function() {
this.initiateConflict({
type: 'military',
attackers: [this.whisperer],
defenders: []
});
expect(this.player2).toHavePrompt('Conflict Action Window');
this.player2.clickCard(this.assassination);
expect(this.player2).toBeAbleToSelect(this.brash);
this.player2.clickCard(this.brash);
expect(this.brash.location).toBe('dynasty discard pile');
});
});
});
});
|
'use strict'
const path = require('path')
const execa = require('execa')
const merge = require('merge-options')
const { pkg } = require('./utils')
/**
* @typedef {import("execa").Options} ExecaOptions
* @typedef {import("./types").GlobalOptions} GlobalOptions
* @typedef {import("./types").DependencyCheckOptions} DependencyCheckOptions
*/
/**
* @param {any} arr1
* @param {any} arr2
*/
const isDefaultInput = (arr1, arr2) =>
JSON.stringify(arr1) === JSON.stringify(arr2)
/**
* Check dependencies
*
* @param {GlobalOptions & DependencyCheckOptions} argv - Command line arguments passed to the process.
* @param {ExecaOptions} [execaOptions] - execa options.
*/
const check = (argv, execaOptions) => {
const forwardOptions = argv['--'] ? argv['--'] : []
const input =
argv.productionOnly &&
isDefaultInput(argv.fileConfig.dependencyCheck.input, argv.input)
? argv.fileConfig.dependencyCheck.productionInput
: argv.input
const noDev = argv.productionOnly ? ['--no-dev'] : []
const ignore = argv.ignore
.concat(argv.fileConfig.dependencyCheck.ignore)
.reduce((acc, i) => acc.concat('-i', i), /** @type {string[]} */ ([]))
const args = [...input, '--missing', ...noDev, ...ignore]
if (pkg.type === 'module') {
// use detective-es6 for js, regular detective for cjs
args.push(
'--extensions', 'cjs:detective',
'--extensions', 'js:detective-es6'
)
}
return execa(
'dependency-check',
[...args, ...forwardOptions],
merge(
{
localDir: path.join(__dirname, '..'),
preferLocal: true
},
execaOptions
)
)
}
module.exports = {
check
}
|
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
import organSiteCategories from './organSiteCategories';
import riskEstimateSchema from './riskEstimateSchema';
import { isNumericishString } from '/imports/api/validators';
export default {
organSiteCategory: {
label: 'Organ site',
type: String,
popoverText: 'Organ site (controlled vocabulary - select one from list)',
allowedValues: organSiteCategories.options,
forceRequiredSymbol: true,
typeaheadMethod: 'searchOrganSiteCategories',
},
organSite: {
label: 'Organ site details',
type: String,
optional: true,
popoverText: 'Optional to further specify details, e.g ICD code, subtype',
typeaheadMethod: 'searchOrganSite',
},
effectMeasure: {
label: 'Measure of effect',
type: String,
min: 1,
popoverText: 'Risk metric used to display results (SMR, RR, etc.)',
typeaheadMethod: 'searchEffectMeasure',
},
effectUnits: {
label: 'Units of effect measurement',
type: String,
optional: true,
popoverText: 'Units, if relevant (e.g., risk per 10 μg/m3)',
typeaheadMethod: 'searchEffectUnits',
},
stratum: {
label: 'Stratum (if relevant)',
type: String,
optional: true,
popoverText: 'e.g.: men only, women only',
typeaheadMethod: 'searchStratum',
},
trendTest: {
label: 'Trend p-value',
type: String,
optional: true,
custom: isNumericishString,
popoverText: 'Provide p-value for trend-test when reported',
},
riskEstimates: {
type: [riskEstimateSchema],
minCount: 1,
},
covariates: {
label: 'Covariates controlled',
type: [String],
minCount: 1,
popoverText: 'List all covariates which were controlled by matching or adjustment in the analysis reported. Enter each covariate individually, and then press <enter> to add it to the list. If no covariates were specified, add \'not-specified\'',
typeaheadMethod: 'searchCovariates',
},
covariatesControlledText: {
label: 'Covariates controlled notes',
type: String,
optional: true,
popoverText: 'Further describe how covariates were controlled, if needed, such as details on matching methodology or adjustments made',
textAreaRows: 4,
},
notes: {
label: 'General notes',
type: String,
optional: true,
popoverText: 'Note issues related to appropriateness of comparison groups, potential for uncontrolled confounding, etc. (e.g. matching criteria for case-control studies)',
textAreaRows: 4,
},
parent_id: {
type: SimpleSchema.RegEx.Id,
denyUpdate: true,
},
};
|
var Util = {
addClass: function(cl, el){
if( el.className.trim() == '' || el.className.indexOf(cl) == -1 ){
el.className += ' '+ cl;
}
},
hasClass: function(cl, el){
return el.className.split(' ').indexOf( cl.replace('.', '') ) > -1;
},
removeClass: function(cl, el){
if( el.className.trim() != '' && el.className.indexOf(cl) > -1 ){
el.className = el.className.replace( new RegExp('\\s?'+ cl), '' );
}
},
closest: function(cl, el){
cl = cl.replace('.', '');
while( el.parentNode ){
el = el.parentNode;
if( Util.hasClass(cl, el) ){
return el;
break;
}
}
return false;
},
newDomElement: function(str){
var wrapper = document.createElement('div');
wrapper.innerHTML = str;
return wrapper.childNodes;
},
replaceElement: function(oldEl, newEl){
if( newEl && newEl.length && newEl.length === 1 ) newEl = newEl[0];
if( newEl && newEl.length ){
for( var i=0; i<newEl.length; i++ ){
oldEl.parentNode.insertBefore(newEl[i], oldEl.nextSibling);
}
}else{
oldEl.parentNode.insertBefore(newEl, oldEl.nextSibling);
}
oldEl.parentNode.removeChild(oldEl);
return newEl;
},
ajax: function(opts){
var req = new XMLHttpRequest();
var reqType = (opts.type || opts.form.method).toUpperCase();
var reqURL = opts.url || opts.form.action;
var reqData = buildFormData();
if( reqType == 'GET' ){
reqURL += (( reqURL.indexOf('?') > -1 ) ? '&' : '?') + reqData;
}
function addObjectData(data, formData){
var buildStr = !formData;
if( buildStr ) formData = [];
for( var key in data ){
if( data.hasOwnProperty(key) ){
var dat = data[key];
if( dat instanceof Array ){
for( var i=0; i<dat.length; i++ ){
var item = ( dat[i] instanceof Object || dat[i] instanceof Array ) ? JSON.stringify(dat[i]) : dat[i];
if( buildStr ) formData.push( key +'[]='+ item );
else formData.append( key+'[]', item );
}
}else if( dat instanceof Object ){
if( buildStr ) formData.push( key +'='+ JSON.stringify(dat) );
else formData.append( key, JSON.stringify(dat) );
}else{
if( buildStr ) formData.push( key +'='+ dat );
else formData.append( key, dat );
}
}
}
if( buildStr ){
return formData.join('&');
}
}
function buildFormData(){
var formData;
if( reqType == 'GET' ){
formData = '';
}else{
if( opts.form && !opts.formData ){
formData = new FormData( opts.form );
}else if( opts.formData ){
formData = opts.formData;
}else{
formData = new FormData();
}
}
if( opts.data ){
if( typeof formData == 'string' ) formData = addObjectData(opts.data);
else addObjectData(opts.data, formData);
}
return formData;
}
var promise = new Promise(function(resolve, reject){
req.open( reqType, reqURL, true );
if( opts.onProgress ){
req.upload.addEventListener('progress', function(ev){
var uploadProgress = (ev.loaded / ev.total) * 100;
opts.onProgress( uploadProgress );
if( uploadProgress == 100 ){
if( opts.onProgressComplete ) opts.onProgressComplete();
}
}, false);
}
req.onreadystatechange = function(){
if( req.readyState == 4 ){
var resp;
if( req.status == 200 ){
try{
resp = JSON.parse(req.responseText);
}catch( error ){
resp = req.responseText;
}
resolve( resp );
if( opts.onSuccess ) opts.onSuccess( resp );
}else{
try{
resp = JSON.parse(req.responseText);
}catch( error ){
resp = req.responseText;
}
reject( resp );
if( opts.onError ) opts.onError( resp, req.status, req.statusText );
}
}
};
if( reqType == 'GET' ) req.send();
else req.send( reqData );
});
return promise;
}
};
|
// Pluralize
export function pluralize(length, singular, plural) {
if (length == 1) {
return singular
} else {
return plural
}
}
// Get a single dom node by selector
export function getDOMNode(selector) {
const node = document.querySelectorAll(selector)[0]
return node
}
// Create array from DOM elements list
export function createDOMArray(list) {
const arr = [];
for (let i = 0; i < list.length; i++) {
arr.push(list[i]);
}
return arr
}
// Look for parent with id
export function hasParentId(target, id) {
let node = target
while (node !== null) {
if (node.id === id) {
return true
}
node = node.parentNode;
}
return false
}
// Pluralize
export function calculateSidebarDimensions() {
const sidebar = document.getElementById('sidebar')
const filters = document.getElementById('filters')
if (filters !== undefined) {
const viewportHeight = window.innerHeight - (2 * 48)
const filtersHeight = filters.scrollHeight
if (filtersHeight > viewportHeight) {
sidebar.classList.add('scroll-overflow')
} else {
sidebar.classList.remove('scroll-overflow')
}
}
}
// Visually focus element (via className)
export function visuallyFocusElem(elem) {
elem.classList.add('focus')
}
// Visually blur element (via className)
export function visuallyBlurElem(elem) {
elem.classList.remove('focus')
}
// Create fieldset id
export function createFieldSetId(...args) {
const id = `fieldset_${args.join('_')}`
return id
}
// Create inlines-item id
export function createInlinesItemId(...args) {
const id = `inlines_item_${args.join('_')}`
return id
}
// Get the [data-field-display-values] of a dom node with [data-field-display-name="fieldDisplayName"]
export function getFieldDisplayValues(fieldDisplayName) {
const node = getDOMNode(`[data-field-display-name="${fieldDisplayName}"]`)
if (node !== undefined) {
const fieldDisplayValues = node.getAttribute('data-field-display-values')
return fieldDisplayValues
}
return undefined
}
// Toggle expanded
export function toggleExpanded(id) {
const handler = getDOMNode(`[aria-controls="${id}"]`)
const region = document.getElementById(id)
const display = handler.getAttribute('aria-expanded') === 'false'
handler.setAttribute('aria-expanded', display)
region.setAttribute('aria-hidden', !display)
}
// Close expanded
export function closeExpanded(id) {
const handler = getDOMNode(`[aria-controls="${id}"]`)
const region = document.getElementById(id)
handler.setAttribute('aria-expanded', false)
region.setAttribute('aria-hidden', true)
}
// Show expanded
export function showExpanded(id) {
const handler = getDOMNode(`[aria-controls="${id}"]`)
const region = document.getElementById(id)
handler.setAttribute('aria-expanded', true)
region.setAttribute('aria-hidden', false)
}
// Close all expanded
export function closeAllExpanded(container) {
const expandables = container.querySelectorAll('[aria-expanded]')
expandables.forEach((element) => {
element.setAttribute('aria-expanded', false)
const region = document.getElementById(element.getAttribute('aria-controls'))
region.setAttribute('aria-hidden', true)
})
}
// Show all expanded
export function showAllExpanded(container) {
const expandables = container.querySelectorAll('[aria-expanded]')
expandables.forEach((element) => {
element.setAttribute('aria-expanded', true)
const region = document.getElementById(element.getAttribute('aria-controls'))
region.setAttribute('aria-hidden', false)
})
}
// Format date YYYY-MM-DD
export function formatDate(date) {
return date.toJSON().slice(0, 10)
}
// Format time HH:MM:SS
export function formatTime(date) {
return date.toJSON().slice(11, 19)
}
export function formatDateTime(date) {
const d = formatDate(date)
const t = formatTime(date)
return `${d}, ${t}`
}
|
'use strict';
var MongoBox = require('mongobox').MongoBox,
mongobox = new MongoBox();
before(function (done) {
mongobox.start(function (error) {
if (error) {
return done(error);
}
global.MONGOBIRD_TEST_PORT = mongobox.options.port;
done();
});
});
after(function (done) {
mongobox.stop(done);
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:577cc71f3d670e7c7a12e65b775a4e4e1c92a3552bb6b5ad94a69c4bec582b61
size 67957
|
version https://git-lfs.github.com/spec/v1
oid sha256:344627044ea2b88e1bc840b18e4a63a9eea81e6dc19bfd280e321a47f8a9c78a
size 412114
|
// 引入 node 的 fms 模块
var fms = require('fms')
fms.run({
// Server 启动在 3000 端口
port: 3100,
read: ['/demo/']
})
fms.ajax({
type: 'POST',
title: '获取颜值节目列表',
url: '/get_face/',
request: {
cid: 1
},
res: {
ok: {
list:[
{
url: "test.html",
_url: "该节目跳转链接",
image: "ex/head1.jpg",
_image: "节目头像",
author: "桐桐宝宝",
_author: "主播妮称",
number: "16.7万",
_number: "在线人数",
webname: "虎牙",
_webname: "直播平台名称拼音"
},
{
url: "http://www.qq.com",
_url: "该节目跳转链接",
image: "ex/head2.jpg",
_image: "节目头像",
author: "萱儿",
_author: "主播妮称",
number: "5633",
_number: "在线人数",
webname: "美拍",
_webname: "直播平台名称拼音"
},
{
url: "http://www.baidu.com",
_url: "该节目跳转链接",
image: "ex/head1.jpg",
_image: "节目头像",
author: "桐桐宝宝",
_author: "主播妮称",
number: "16.7万",
_number: "在线人数",
webname: "虎牙",
_webname: "直播平台名称拼音"
},
{
url: "http://www.qq.com",
_url: "该节目跳转链接",
image: "ex/head2.jpg",
_image: "节目头像",
author: "萱儿",
_author: "主播妮称",
number: "5633",
_number: "在线人数",
webname: "美拍",
_webname: "直播平台名称拼音"
},
{
url: "http://www.baidu.com",
_url: "该节目跳转链接",
image: "ex/head1.jpg",
_image: "节目头像",
author: "桐桐宝宝",
_author: "主播妮称",
number: "16.7万",
_number: "在线人数",
webname: "虎牙",
_webname: "直播平台名称拼音"
},
{
url: "http://www.qq.com",
_url: "该节目跳转链接",
image: "ex/head2.jpg",
_image: "节目头像",
author: "萱儿",
_author: "主播妮称",
number: "5633",
_number: "在线人数",
webname: "美拍",
_webname: "直播平台名称拼音"
}
],
status: 1,
page: 1,
pagetotal: 5
},
err: {
status: "error",
msg: "请先登录"
}
}
})
fms.ajax({
type: 'POST',
title: '获取游戏节目列表',
url: '/get_game/',
request: {
cid: 2
},
res: {
ok: {
list:[
{
url: "http://www.baidu.com",
_url: "该节目跳转链接",
image: "ex/head1.jpg",
_image: "节目头像",
author: "桐桐宝宝",
_author: "主播妮称",
number: "16.7万",
_number: "在线人数",
title: "Sli群星联赛NB.Y vs EHOME",
_title: "节目名称",
webname: "zhanqi",
_webname: "直播平台名称拼音"
}
],
status: 1,
_status: "请求状态,1成功,0失败",
page: 1,
_page: "当前页码",
pagetotal: 1,
_pagetotal: "总页码数"
},
err: {
status: "error",
msg: "请先登录"
}
},
timeout: 1000
})
|
/**
* @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'filetools', 'nl', {
loadError: 'Fout tijdens lezen van bestand.',
networkError: 'Netwerkfout tijdens uploaden van bestand.',
httpError404: 'HTTP fout tijdens uploaden van bestand (404: Bestand niet gevonden).',
httpError403: 'HTTP fout tijdens uploaden van bestand (403: Verboden).',
httpError: 'HTTP fout tijdens uploaden van bestand (fout status: %1).',
noUrlError: 'Upload URL is niet gedefinieerd.',
responseError: 'Ongeldig antwoord van server.'
} );
|
"use strict";
var Sequence = require('../models/sequence.model');
// Create a sequence
exports.sequenceGenerator = function(name){
return {
next: function(callback){
Sequence.find({"name":name},function(err, data){
if(err){ throw(err); }
if(data.length < 1){
// create if doesn't exist create and return first
Sequence.create({name:name,nextSeqNumber:1}, function(err, seq){
if(err) { throw(err); }
callback(seq.nextSeqNumber);
});
} else {
// update sequence and return next
Sequence.findOneAndUpdate({"name": name}, { $inc: { nextSeqNumber: 1 } }, {new: true}, function(err, seq){
if(err) { throw(err); }
callback(seq.nextSeqNumber);
});
}
});
}
};
}
|
var Mongoose = require('mongoose');
var personSchema = Mongoose.Schema({
family:String,
gen1:String,
gen2:String,
firstName:String,
maidenName:String,
familyName:String,
birtDate:Date,
weddingDate:Date,
phone:Array,
street:String,
city:String,
zip:String,
email:Array,
social:Array
});
var person = Mongoose.model('Person', personSchema);
module.exports = {
Person: person
};
|
(function() {
var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
templates['items-stored'] = template({"1":function(container,depth0,helpers,partials,data) {
var helper, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
return "<tr>\n <td><i class=\"icon-"
+ alias4(((helper = (helper = helpers.smiling || (depth0 != null ? depth0.smiling : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"smiling","hash":{},"data":data}) : helper)))
+ "\"></i></td>\n <td>\n <div class=\"table-results-imc\">"
+ alias4(((helper = (helper = helpers.imc || (depth0 != null ? depth0.imc : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"imc","hash":{},"data":data}) : helper)))
+ "</div>\n </td>\n <td>\n <div class=\"table-results-info\">\n <div class=\"table-results-name\">"
+ alias4(((helper = (helper = helpers.name || (depth0 != null ? depth0.name : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"name","hash":{},"data":data}) : helper)))
+ "</div>\n <div class=\"table-results-data\">"
+ alias4(((helper = (helper = helpers.date || (depth0 != null ? depth0.date : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"date","hash":{},"data":data}) : helper)))
+ "</div>\n <div class=\"table-results-time\">"
+ alias4(((helper = (helper = helpers.hours || (depth0 != null ? depth0.hours : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"hours","hash":{},"data":data}) : helper)))
+ "</div>\n </div>\n </td>\n</tr>\n";
},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
var stack1;
return ((stack1 = helpers.each.call(depth0 != null ? depth0 : {},depth0,{"name":"each","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
},"useData":true});
})();
|
// Karma configuration
// Generated on Thu Jul 03 2014 13:23:26 GMT+0530 (India Standard Time)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'dist/gainda.js',
'test/spec/*.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
|
export default {
SHOW_WEB3_CONFIRM_MODAL: 'showWeb3Wallet',
SHOW_TX_CONFIRM_MODAL: 'showTxConfirmModal',
SHOW_MSG_CONFIRM_MODAL: 'showMessageConfirmModal',
SHOW_TX_SIGN_MODAL: 'showTxSignModal',
CONFIRMED_TX: 'confirmedTx',
SHOW_BATCH_TX_MODAL: 'showTxCollectionConfirmModal',
SHOW_SWAP_TX_MODAL: 'showSwapTxConfirmModal'
};
|
"use strict";
angular.module("homeuiApp")
.factory("getTime", function () {
return function getTime () {
return new Date().getTime();
};
});
|
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'blockquote', 'ku', {
toolbar: 'بەربەستکردنی ووتەی وەرگیراو'
} );
|
$(document).ready(function() {
$.validator.setDefaults({
highlight: function (element) {
$(element)
.closest('.input-group')
.addClass('has-danger')
.removeClass('has-success')
},
unhighlight: function (element) {
$(element)
.closest('.input-group')
.removeClass('has-danger')
.addClass('has-success')
},
errorElement: 'div',
errorClass: 'form-text',
errorPlacement: function(error, element) {
error.insertAfter(element.parent('div'));
}
});
$("#add-driver-form").validate({
rules: {
"email": {
required: true,
email: true
},
"password": {
required: true,
minlength: 6
},
"full-name": {
required: true,
pattern: "^[A-ZА-Я][a-zа-я]+ [A-ZА-Я][a-zа-я]+$"
},
"passport-serial-numbers": {
required: true,
pattern: "^([А-Я]{2} \\d{6})|(\\d{10})$"
},
"phone-number": {
required: true,
pattern: "^(\\+?\\d{12})|(\\d{10})$"
},
"age": {
required: true,
pattern: "^(1[89]|[2-9][0-9])$"
}
},
messages: {
"email": {
required: "Please, enter an email address.",
email: "Please, enter a valid email address."
},
"password": {
required: "Please, enter your password.",
minlength: "Password must contain at least 6 characters."
},
"full-name": {
pattern: "Please, enter a valid full name(ex. John Smith)."
},
"passport-serial-numbers": {
pattern: "Please, enter valid passport serial numbers(ex. ВТ 123456)."
},
"phone-number": {
required: "Please, enter a phone number.",
pattern: "Please, enter a valid phone number(ex. +380664039952)."
},
"age": {
required: "Please, enter driver's age.",
pattern: "Please, enter a valid age(>18 & <99)."
}
}
});
});
|
/*let calculator = (function () {
let result = 0;
function add(x) {
result += x;
return this;
}
function subtract(x) {
result -= x;
return this;
}
function getResult() {
return result;
}
return{
add, subtract, getResult
}
})();*/
// our lasted obj starts as empty
let calculator = {};
// private iffe with every private functionality
(function (module) {
let result = 0;
function add(x) {
result += x;
return this;
}
function subtract(x) {
result -= x;
return this;
}
function getResult() {
return result;
}
module.add = add;
module.subtract = subtract;
module.getResult = getResult;
}(calculator));
// calling it with our obj
(function (module) {
module.add42 = function () {
this.add(42);
};
}(calculator));
calculator.add42();
console.log(calculator.add(5).getResult());
|
"use strict";
const {toPromise} = require("./promise");
const {interceptNode, registerGlobalInterceptor} = require("./interceptor");
// pipeline interceptor
registerGlobalInterceptor(node => node instanceof Pipeline ? (payload => node.dispatch(payload)) : null);
class Pipeline {
constructor() {
this.firstNode = null;
this.lastNode = null;
this.eagerNodes = [];
this.innerNodes = [];
this.deferedNodes = [];
this.errorHandler = null;
this.interceptors = [];
// Soon to be deprecated functions (renamed)
// Polyfill for backwards compatibility with 0.1
this.pipe = this.through;
this.capture = this.to;
}
from(node) {
if (arguments.length === 0) {
return this.firstNode;
}
this.firstNode = node;
return this;
}
to(node) {
if (arguments.length === 0) {
return this.lastNode;
}
this.lastNode = node;
return this;
}
through(...nodes) {
if (arguments.length === 0) {
return [].concat(this.innerNodes);
}
this.innerNodes = this.innerNodes.concat(nodes);
return this;
}
eager(...nodes) {
if (arguments.length === 0) {
return [].concat(this.eagerNodes);
}
this.eagerNodes = this.eagerNodes.concat(nodes);
return this;
}
defer(...nodes) {
if (arguments.length === 0) {
return [].concat(this.deferedNodes);
}
this.deferedNodes = this.deferedNodes.concat(nodes);
return this;
}
intercept(...interceptors) {
this.interceptors = this.interceptors.concat(interceptors);
return this;
}
get nodes() {
const nodes = [].concat(this.eagerNodes, this.innerNodes, this.deferedNodes);
if (this.firstNode != undefined) {
nodes.unshift(this.firstNode);
}
if (this.lastNode != undefined) {
nodes.push(this.lastNode);
}
return nodes;
}
report(errorHandler) {
this.errorHandler = errorHandler;
return this;
}
dispatch(payload = {}) {
let response = toPromise(payload);
this.nodes.forEach(node => {
const callback = interceptNode(node, [].concat(this.interceptors));
if (typeof callback === "function") {
response = response.then(
currentPayload => toPromise(currentPayload != undefined ? currentPayload : payload).then(callback)
);
}
});
if (this.errorHandler) {
const callback = interceptNode(this.errorHandler, [].concat(this.interceptors));
if (typeof callback === "function") {
response = response.catch(callback);
}
}
return response;
}
}
// generator
const createPipeline = () => new Pipeline();
module.exports = {
Pipeline,
createPipeline
};
|
import {connect } from 'react-redux'
import React,{Component} from 'react'
import {Nav, Navbar, NavItem} from 'react-bootstrap'
import {pushState} from 'redux-router'
import Alert from '../components/alert'
import Loader from 'react-loader-advanced';
@connect((state) => ( {loading: state.common.loading}))
export default class App extends Component {
constructor(props){
super(props);
}
render () {
let topRoutes = this.props.route.childRoutes;
let activeRoute = topRoutes.filter(route => this.props.history.isActive(route.path))[0]
return (<div>
<Navbar>
<Navbar.Header>
<Navbar.Brand><a href="#">ToolboxSite</a></Navbar.Brand>
</Navbar.Header>
<Nav pullRight>
{topRoutes.map(route =><NavItem key={route.path} href={'#'+ route.path}>{route.name}</NavItem>)}
<NavItem href="https://github.com/Jishun/ToolboxSite" target="_blank">GitHub</NavItem>
</Nav>
</Navbar>
<div id="content_area" className="container">
<Nav bsStyle="tabs">
{activeRoute && activeRoute.childRoutes? activeRoute.childRoutes.map((route, i) => <NavItem key={i} active={this.props.history.isActive(route.path)} href={'#' +route.path}>{route.name}</NavItem>) : null}
</Nav>
<Alert></Alert>
<div>{this.props.children}</div>
</div>
</div>);
}
}
|
'use strict';
//Emails service used to communicate Emails REST endpoints
angular.module('emails').factory('Emails', ['$resource',
function($resource) {
return $resource('api/emails/:emailId', { emailId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
]);
|
var assert = require('assert');
var util = require('util');
var auth0OidcStrategy = require('../lib/passport-auth0-openidconnect');
describe('passport-auth0-openidconnect', function(){
it('should report a version', function () {
assert.ok(auth0OidcStrategy.version);
assert.equal(typeof(auth0OidcStrategy.version),'string');
assert.ok(auth0OidcStrategy.version.length > 0);
});
});
|
var Omegle = require('omegle').Omegle;
var omegleSessions = [];
function init() {
if(Omegle) {
this.on('command', function(context, command) {
if(command == 'omegle') {
if(command.arguments.length == 0) {
context.reply('Omegle Plugin commands: pair, stop');
}else {
if(command.arguments[0] == 'pair') {
var session = {}
session.sideA = new Omegle();
session.sideB = new Omegle();
session.sideA.on('error', function(err) {
console.log(err);
console.log(err.stack);
context.reply('Error occured on Side A. Disconnecting');
session.sideA.disconnect();
session.sideB.disconnect();
});
session.sideB.on('error', function(err) {
console.log(err);
console.log(err.stack);
context.reply('Error occured on Side B. Disconnecting');
session.sideA.disconnect();
session.sideB.disconnect();
});
session.sideA.start(function(err) {
if(err) {
context.reply('Failed to create first side. Terminating connection');
session.sideA.disconnect();
session.sideB.disconnect();
return;
}else{
context.reply('Person 1 connected');
/* Start side B */
session.sideB.start(function(err) {
if(err) {
context.reply('Failed to create second side. Terminating connection');
session.sideA.disconnect();
session.sideB.disconnect();
return;
}else{
context.reply('Person 2 connected');
session.sideA.on('strangerDisconnected', function() {
context.reply('First person disconnected. Closing connection');
session.sideA.disconnect();
session.sideB.disconnect();
});
session.sideB.on('strangerDisconnected', function() {
context.reply('Second person disconnected. Closing connection');
session.sideA.disconnect();
session.sideB.disconnect();
});
session.sideA.on('typing', function() {
console.log('Omegle SideA Typing');
session.sideB.startTyping();
});
session.sideA.on('stoppedTyping', function() {
console.log('Omegle SideA Stop Typing');
session.sideB.stopTyping();
});
session.sideB.on('typing', function() {
console.log('Omegle SideB Typing');
session.sideA.startTyping();
});
session.sideB.on('stoppedTyping', function() {
console.log('Omegle SideB Stop Typing');
session.sideA.stopTyping();
});
session.sideA.on('gotMessage', function(msg) {
session.sideB.send(msg, function(err) {
if(err) {
context.reply('Error sending to sideB, abandoning!');
session.sideA.disconnect();
session.sideB.disconnect();
}else{
context.reply('P1 > P2: ' + msg);
}
});
});
session.sideB.on('gotMessage', function(msg) {
session.sideA.send(msg, function(err) {
if(err) {
context.reply('Error sending to sideA, abandoning');
session.sideA.disconnect();
session.sideB.disconnect();
}else{
context.reply('P2 > P1: ' + msg);
}
});
});
session.sideA.on('recaptchaRequired', function(key) {
context.reply('Side A requested a captcha. Bugging out! Woop!');
session.sideA.disconnect();
session.sideB.disconnect();
});
session.sideB.on('recaptchaRequired', function(key) {
context.reply('Side B requested a captcha. No thankies!');
session.sideA.disconnect();
session.sideB.disconnect();
});
}
});
}
});
}
}
}
});
} else {
console.log('Omegle API unavailable. Not attaching plugin');
}
}
function unload() {
}
module.exports = {
'init': init,
'unload': unload
};
|
var temp;
var weather;
function setTemp(tempKelvin) {
temp = tempKelvin - 273.15;
$("#temp").html(Math.floor(temp));
}
function getWeather(geolocation) {
$("#city").html(geolocation.city + ", " + geolocation.regionName);
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + geolocation.lat + "&lon=" + geolocation.lon + "&APPID=3d46ddc5857d31d05cb855f315723e84", function(openApiJson) {
$("#neighborhood").html(openApiJson.name + " Neighborhood");
weather = openApiJson.weather[0].main;
setIcon();
$("#weather").html(weather);
$("#humidity").html("Humidity: " + openApiJson.main.humidity + "%");
$("#wind").html("Wind speed: " + openApiJson.wind.speed + "m/s");
setTemp(openApiJson.main.temp);
});
}
function getLocation() {
$.getJSON("http://ip-api.com/json", getWeather);
}
function setIcon() {
var weatherIcon = "ion-home";
console.log(weather);
switch (weather) {
case "Thunderstorm":
weatherIcon = "ion-ios-thunderstorm";
break;
case "Drizzle":
case "Rain":
weatherIcon = "ion-ios-rainy";
break;
case "Snow":
weatherIcon = "ion-ios-snowy";
break;
case "Atmosphere":
weatherIcon = "ion-ios-partlysunny";
break;
case "Clear":
weatherIcon = "ion-ios-sunny";
break;
case "Clouds":
weatherIcon = "ion-ios-cloudy";
break;
case "Extreme":
weatherIcon = "ion-ios-thunderstorm";
break;
case "Additional":
weatherIcon = "ion-ios-cloudy-night";
break;
default:
weatherIcon = "ion-ios-moon";
break;
}
$("#weatherIcon").addClass(weatherIcon);
}
$(document).ready(function() {
var today = new Date();
$("#date").html(today.toDateString());
getLocation();
$(".unit").click(function() {
if (!$(this).is(".active")) {
$(".unit.active").removeClass("active");
$(this).addClass("active");
if ($(this).is("#far")) {
temp = temp * 9 / 5 + 32;
} else {
temp = (temp - 32) * 5 / 9;
}
$("#temp").html(Math.floor(temp));
}
});
});
|
var Login = function() {};
Login.prototype = {
preload: function() {
console.log('STATE : Login - Preload');
},
create: function() {
console.log('STATE : Login - Create');
this.state.start('Setup');
}
};
module.exports = Login;
|
const loadAll = true
const defaultLanguage = 'en'
const otherLang = [ 'vi']
const supportLanguage = [defaultLanguage, ...otherLang]
const defaultAndActive = [defaultLanguage, 'active']
module.exports = { supportLanguage, defaultLanguage, loadAll, defaultAndActive, otherLang }
|
$( document ).ready( function( ) {
setTimeout( function( ) {
$( ".alert.alert-overhead" ).css({
"opacity": 0
});
}, 1500 )
});
|
const path = require('path');
const { resolve, join } = path;
const OfflinePlugin = require(process.env.OFFLINE_PLUGIN_ROOT);
const CopyWebpackPlugin = require('copy-webpack-plugin');
const DefinePlugin = require('webpack').DefinePlugin;
module.exports = {
entry: {
main: join(__dirname, 'src/main.js'),
},
output: {
path: join(__dirname, 'www'),
filename: '[name].js',
chunkFilename: '[name].js',
publicPath: '/'
},
plugins: [
new CopyWebpackPlugin([
{ from: join(__dirname, 'src/index.html') },
{ from: join(__dirname, 'src/app-shell.html') }
]),
new DefinePlugin({
'process.env.OFFLINE_PLUGIN_ROOT': JSON.stringify(process.env.OFFLINE_PLUGIN_ROOT)
}),
new OfflinePlugin({
appShell: '/app-shell.html',
ServiceWorker: {
navigationPreload: {
map: (url) => {
if (url.pathname === '/') {
return '/api/index.json';
}
if (url.pathname === '/not-found') {
return '/api/not-found.json';
}
},
test: (url) => {
if (url.pathname.indexOf('/api/') === 0) {
return true;
}
}
},
},
AppCache: false,
})
]
};
|
'use strict';
var path = require('path');
var gulp = require('gulp');
var gutil = require('gulp-util');
var _ = require('lodash');
var notify = require('gulp-notify');
var plumber = require('gulp-plumber');
var livereload = require('gulp-livereload');
var config = require('./config');
var loaded = [];
var ns = function (name) {
return ['luminous-gulp', name].join(':');
};
/**
* Get the task name with the namespace after loading.
*
* @param {string} name
* @return {string}
*/
var LuminousGulp = function (name) {
var file = name.split(':')[0];
if (!_.includes(loaded, file)) {
loaded.push(file);
require(path.join(__dirname, 'tasks', file))(LuminousGulp);
}
return ns(name);
};
/**
* Get configuration.
*
* @param {string} path
* @return {Object}
*/
LuminousGulp.config = function (path) {
var paths = _.isString(path) ? path.split('.') : _.toArray(arguments),
value = config;
while (paths.length > 0) {
value = value[paths.shift()];
}
return value;
};
/**
* The wrapper for "gulp.task()".
*
* @param {string} name
* @param {array} deps
* @param {function} fn
* @return {undefined}
*/
LuminousGulp.task = function (name, deps, fn) {
if (!fn && typeof deps === 'function') {
fn = deps;
deps = [];
}
gulp.task(ns(name), deps.map(LuminousGulp), fn);
};
// Report file paths in the stream pipeline.
LuminousGulp.report = require('./report');
// https://www.npmjs.com/package/gulp-notify
LuminousGulp.notify = function (message) {
return notify({title: 'luminous-gulp', message: message});
};
LuminousGulp.onError = function () {
return notify.onError({title: 'luminous-gulp', message: "Error: <%= error.message %>"});
};
// https://www.npmjs.com/package/gulp-plumber
LuminousGulp.plumber = function () {
return plumber({ errorHandler: LuminousGulp.onError() });
};
// https://www.npmjs.com/package/gulp-livereload
LuminousGulp.listen = function (options) {
livereload.listen(options);
};
LuminousGulp.reload = function (file) {
if (file && file.path) {
gutil.log(gutil.colors.magenta('./' + path.relative(process.cwd(), file.path)) + ' is changed.');
}
livereload.reload('/');
};
module.exports = LuminousGulp;
|
import { someValue } from './index.js';
assert.equal( someValue, 10 );
|
Options.set('collectionsDefaultUpdateTemplate', 'orionHeartbeatCollectionsUpdate');
ReactiveTemplates.set('pages.update', 'orionHeartbeatPagesUpdate');
|
// COPYRIGHT © 2017 Esri
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// This material is licensed for use under the Esri Master License
// Agreement (MLA), and is bound by the terms of that agreement.
// You may redistribute and use this code without modification,
// provided you adhere to the terms of the MLA and include this
// copyright notice.
//
// See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english
//
// For additional information, contact:
// Environmental Systems Research Institute, Inc.
// Attn: Contracts and Legal Services Department
// 380 New York Street
// Redlands, California, USA 92373
// USA
//
// email: contracts@esri.com
//
// See http://js.arcgis.com/4.4/esri/copyright.txt for details.
define(["require","exports","./decorators","./jsxFactory","./widgetUtils"],function(e,r,o,t,i){function n(e){for(var o in e)r.hasOwnProperty(o)||(r[o]=e[o])}Object.defineProperty(r,"__esModule",{value:!0}),n(o),n(t),n(i)});
|
'use strict';
(function() {
// Employer profile view Controller Spec
describe('Employer profile view Controller Tests', function() {
// Initialize global variables
var EmployerProfileViewController,
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 Employer profile view controller.
EmployerProfileViewController = $controller('EmployerProfileViewController', {
$scope: scope
});
}));
it('Should do some controller test', inject(function() {
// The test logic
// ...
}));
});
}());
|
version https://git-lfs.github.com/spec/v1
oid sha256:8935846d723ae549df268eb54eaa120003319b3e26aca089dfd2fc3b0f146a7e
size 14667
|
(function($, $$) {
var _ = Mavo.UI.Popup = $.Class({
constructor: function(primitive) {
this.primitive = primitive;
// Need to be defined here so that this is what expected
this.position = evt => {
var bounds = this.primitive.element.getBoundingClientRect();
var x = bounds.left;
var y = bounds.bottom;
var pointDown = false;
if (this.element.offsetHeight) {
// Is in the DOM, check if it fits
this.height = this.element.getBoundingClientRect().height || this.height;
}
if (this.height + y + 20 > innerHeight) {
// Normal positioning means the popup would be cut off or too close to the edge, adjust
// Perhaps placing it above is better
if (bounds.top - this.height > 20) {
var pointDown = true;
y = bounds.top - this.height - 20;
}
else {
// Nah, just raise it a bit
y = innerHeight - this.height - 20;
}
}
this.element.classList.toggle("mv-point-down", pointDown);
$.style(this.element, { top: `${y}px`, left: `${x}px` });
};
this.element = $.create("div", {
className: "mv-popup",
hidden: true,
contents: {
tag: "fieldset",
contents: [
{
tag: "legend",
textContent: this.primitive.label + ":"
},
this.editor
]
},
events: {
keyup: evt => {
if (evt.keyCode == 13 || evt.keyCode == 27) {
if (this.element.contains(document.activeElement)) {
this.primitive.element.focus();
}
evt.stopPropagation();
this.hide();
}
},
transitionend: this.position
}
});
// No point in having a dropdown in a popup
if (this.editor.matches("select")) {
this.editor.size = Math.min(10, this.editor.children.length);
}
this.hideCallback = evt => {
if (!this.element.contains(evt.target) && !this.primitive.element.contains(evt.target)) {
this.hide();
}
};
},
show: function() {
$.unbind([this.primitive.element, this.element], ".mavo:showpopup");
this.shown = true;
this.element.style.transition = "none";
this.element.removeAttribute("hidden");
this.position();
this.element.setAttribute("hidden", "");
this.element.style.transition = "";
document.body.appendChild(this.element);
setTimeout(() => {
this.element.removeAttribute("hidden");
}, 100); // trigger transition. rAF or timeouts < 100 don't seem to, oddly.
$.bind(document, "focus click", this.hideCallback, true);
window.addEventListener("scroll", this.position, {passive: true});
},
hide: function() {
$.unbind(document, "focus click", this.hideCallback, true);
window.removeEventListener("scroll", this.position, {passive: true});
this.element.setAttribute("hidden", ""); // trigger transition
this.shown = false;
setTimeout(() => {
$.remove(this.element);
}, parseFloat(getComputedStyle(this.element).transitionDuration) * 1000 || 400); // TODO transition-duration could override this
},
prepare: function() {
$.bind(this.primitive.element, {
"click.mavo:edit": evt => {
this.show();
},
"keyup.mavo:edit": evt => {
if ([13, 113].indexOf(evt.keyCode) > -1) { // Enter or F2
this.show();
this.editor.focus();
}
}
});
if (!this.element.contains(this.editor)) {
// This can happen if edit type changes from popup to inline
this.element.append(this.editor);
}
},
close: function() {
this.hide();
$.unbind(this.primitive.element, ".mavo:edit .mavo:preedit .mavo:showpopup");
},
proxy: {
"editor": "primitive"
}
});
})(Bliss, Bliss.$);
|
module.exports = isLabelIdentifier;
function isLabelIdentifier(path) {
const { node } = path;
return (
path.parentPath.isLabeledStatement({ label: node }) ||
path.parentPath.isBreakStatement({ label: node }) ||
path.parentPath.isContinueStatement({ label: node })
);
}
|
import gulp from 'gulp';
import es from 'event-stream';
import nugetRestore from 'gulp-nuget-restore';
export default {
/**
* Task name
* @type {String}
*/
name: 'sitecore:nuget-restore',
/**
* Task description
* @type {String}
*/
description: 'Restore all nuget packages for solution.',
/**
* Task default configuration
* @type {Object}
*/
config: {
deps: [],
},
/**
* Task help options
* @type {Object}
*/
help: {
'solution, -s': 'Solution file path',
},
/**
* Task function
* @param {object} config
* @param {Function} end
* @param {Function} error
*/
fn(config, end, error) {
if (!config.solution) {
error('A solution file path was not set.');
return;
}
gulp.src(config.solution)
.pipe(nugetRestore())
.pipe(es.through(() => {}))
.on('end', end);
},
};
|
$(document).ready(function () {
var $sliderSlick = $('.latest-posts__list');
var $destroyed = true;
var $documentSize = $(document).innerWidth();
var $sliderOptions = {
arrows: false,
dots: true,
dotsClass: 'latest-posts__dots',
infinite: true,
vertical: true,
verticalSwiping: true
};
if ($documentSize > 600) {
$sliderSlick.slick($sliderOptions);
$sliderSlick.slick('init', function () {
$(this).equalize({
target: '.latest-post__item',
property: 'height'
});
});
$destroyed = !$destroyed;
}
$(window).on('resize', function (e) {
var documentSize = $(document).innerWidth();
if (documentSize < 600 && !$destroyed) {
$sliderSlick.slick('unslick');
$destroyed = !$destroyed;
} else if (documentSize >= 600 && $destroyed) {
$sliderSlick.slick($sliderOptions);
$destroyed = !$destroyed;
}
});
});
|
import QItem from './QItem'
import QItemMain from './QItemMain'
import QItemSide from './QItemSide'
function push (child, h, name, slot, replace, conf) {
const defaultProps = { props: { right: conf.right } }
if (slot && replace) {
child.push(h(name, defaultProps, slot))
return
}
let props, v = false
if (!slot) {
for (let p in conf) {
if (conf.hasOwnProperty(p)) {
v = conf[p]
if (v !== void 0 && v !== true) {
props = true
break
}
}
}
}
if (props || slot) {
child.push(h(name, props ? {props: conf} : defaultProps, slot))
}
}
export default {
name: 'q-item-wrapper',
functional: true,
props: {
cfg: {
type: Object,
default: () => ({})
},
slotReplace: Boolean
},
render (h, ctx) {
const
cfg = ctx.props.cfg,
replace = ctx.props.slotReplace,
slot = ctx.slots(),
child = []
push(child, h, QItemSide, slot.left, replace, {
icon: cfg.icon,
color: cfg.leftColor,
avatar: cfg.avatar,
letter: cfg.letter,
image: cfg.image
})
push(child, h, QItemMain, slot.main, replace, {
label: cfg.label,
sublabel: cfg.sublabel,
labelLines: cfg.labelLines,
sublabelLines: cfg.sublabelLines,
inset: cfg.inset
})
push(child, h, QItemSide, slot.right, replace, {
right: true,
icon: cfg.rightIcon,
color: cfg.rightColor,
avatar: cfg.rightAvatar,
letter: cfg.rightLetter,
image: cfg.rightImage,
stamp: cfg.stamp
})
if (slot.default) {
child.push(slot.default)
}
ctx.data.props = cfg
return h(QItem, ctx.data, child)
}
}
|
// Component: QuestionsPage
import React from 'react';
import { Redirect } from 'react-router-dom';
import { Header, SubTitle } from 'styles/Layout';
import { QuestionCard, UnansweredList } from 'Questions/ui/dynamicRoutes';
const QuestionListCard = question => <QuestionCard {...question} />;
const QuestionsPage = ({ list, questionnaire, ...props }) => {
const unanswered = list.filter(o => !o.answered);
const completed = list.length > 0 && unanswered.length === 0;
if (completed) {
return <Redirect to="/results" />;
}
return (
<>
<Header>
<h1>
Paitent Health Questionnaire <small>(PHQ-9)</small>
</h1>
</Header>
{!completed && <UnansweredList unanswered={unanswered} />}
<SubTitle className="subtitle">{questionnaire.subtitle}</SubTitle>
<ul className="questions-list">
{list.map(question => (
<QuestionListCard key={question.id} {...question} />
))}
</ul>
</>
);
};
export default QuestionsPage;
|
$(document).ready(function() {
clickReg();
clickCancel();
logOut();
scheduleThings();
makeAppointments();
});
|
'use strict';
var pi = require( './../lib' );
console.log( pi );
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.