text
stringlengths 2
6.14k
|
|---|
'use strict';
const FakeSocket = require('./fake-socket.js');
class FakeUser {
constructor() {
this.socket = new FakeSocket();
this.socket.user = this;
this.guestNum = -1;
this.name = 'CPU user';
this.generateId();
this.ips = ['0.0.0.0'];
this.currentIp = '0.0.0.0';
this.bacteriaPrototype = {owner: this};
this.defaultProto();
}
defaultProto() {
this.bacteriaPrototype.genetics = this.bacteriaPrototype.genetics || {fertility: 3, solitude: 1, overpopulation: 4, color: '#000'};
this.bacteriaPrototype.pattern = this.bacteriaPrototype.pattern || [{x: 2, y: 1}, {x: 2, y: 2}, {x: 2, y: 3}];
}
generateId() {
let text = '' + this.name;
this.id = text.toLowerCase().replace(/[^a-z0-9]+/g, '');
}
usePrototype(proto = {}) {
proto.owner = this;
this.bacteriaPrototype = proto;
this.defaultProto();
}
send(message) {
if (!message || !this.socket) return;
return this.socket.write(message);
}
destroy() {
delete this.socket.user;
this.socket.close();
delete this.socket;
}
}
module.exports = FakeUser;
|
// Generated by CoffeeScript 1.10.0
(function() {
_.mixin({
isNumeric: function(val) {
return !isNaN(parseFloat(val)) && isFinite(val);
},
inverse: function(object) {
var k, result, v;
result = {};
for (k in object) {
v = object[k];
result[v] = k;
}
return result;
},
twins: function(array) {
return _.uniq(array).length === 1;
},
surrounding: function(array, index, len) {
var after, alt, before, result;
before = _.first(array, index);
after = _.rest(array, index + 1);
result = [array[index]];
alt = true;
while (len > result.length && (before.length || after.length)) {
if (alt && before.length) {
result.unshift(before.pop());
} else if (after.length) {
result.push(after.shift());
}
alt = !alt;
}
return result;
}
});
}).call(this);
|
$('.search_friend_text').keydown(function (event) {
var keypressed = event.keyCode || event.which;
if (keypressed == 13) {
$(this).closest('form').submit();
}
});
|
const express = require('express')
const path = require('path')
const webpack = require('webpack')
const webpackDevMiddleware = require('webpack-dev-middleware')
const log = require('../core/log')
async function init (app) {
// https://webpack.js.org/api/node/
const webpackConfig = require('../webpack.' + app.get('env'))
const webpackCompiler = webpack(webpackConfig)
const promise = new Promise(function (resolve, reject) {
if (app.get('env') === 'development') {
app.use(webpackDevMiddleware(webpackCompiler, {
publicPath: webpackConfig.output.publicPath,
stats: webpackConfig.stats
}))
resolve()
} else {
log.info('Compiling static assets...')
webpackCompiler.run(function (err, stats) {
if (err) {
log.error(err.stack || err)
if (err.details) {
log.error(err.details)
}
reject(err)
return
}
const info = stats.toJson()
if (stats.hasErrors()) {
log.error(info.errors)
reject(info.errors)
return
}
if (stats.hasWarnings()) {
log.warn(info.warnings)
}
resolve()
})
}
})
return promise
}
module.exports = {
init: init,
static: express.static(path.join(__dirname, '..', 'static'))
}
|
export default function storageAvailable (type) {
try {
var storage = window[type];
var x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
} catch (e) {
return e instanceof DOMException && (
// everything except Firefox
e.code === 22 ||
// Firefox
e.code === 1014 ||
// test name field too, because code might not be present
// everything except Firefox
e.name === 'QuotaExceededError' ||
// Firefox
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
// acknowledge QuotaExceededError only if there's something already stored
storage.length !== 0;
}
}
|
'use strict';
angular.module('blog.friendship.controllers', [])
.controller('FollowingListCtrl', ['$scope', '$rootScope', '$http', '$location',
function($scope, $rootScope, $http, $location){
$rootScope.title = "关注我的好友";
$scope.editable = true;
$scope.url = '/api/following/';
$http.get($scope.url).success(function(data, status, header, config){
$scope.data = data;
}).error(function(data, status, header, config) {});
$scope.delete = function(friend) {
$http.delete($scope.url + friend.id + '/').success(function(data, status, header, config) {
$scope.data.results.splice($scope.data.results.indexOf(friend), 1);
}).error(function(data, status, header, config) {});
};
}])
.controller('FollowedListCtrl', ['$scope', '$rootScope', '$http', '$location',
function($scope, $rootScope, $http, $location){
$rootScope.title = "我关注的好友";
$scope.editable = false;
$scope.url = '/api/followed/';
$http.get($scope.url).success(function(data, status, header, config){
$scope.data = data;
}).error(function(data, status, header, config) {});
}]);
|
template={};
$(document).ready(function(){
template={
options:{
html:$('#hall-options').html(),
category:$('#hall-category').val()
}
};
$('#hall-tab a').click(function (e) {
e.preventDefault();
$(this).tab('show');
})
});
$('#hall-category').change(function(){
var category=$(this).val();
$.ajax({
url:'/category/options',
dataType:'json',
type:'GET',
data:{id:$(this).val()},
success:function(data){
var text='';
for(var i=0;i<data.length;i++){
text+="<label>\n"+
'<input type="checkbox" value="'+data[i].id+'" name="Hall[options][]"> '+data[i].name+
"</label>\n"
;
}
if(category==template.options.category){
$('#hall-options').html('').html(template.options.html);
}else{
$('#hall-options').html('').html(text);
}
}
})
});
|
// /public/js/custom.js
/*jQuery(function($) {
$("#create").on('click', function(event){
event.preventDefault();
var $stickynote = $(this);
$.post("stickynotes/add", null,
function(data){
if(data.response == true){
$stickynote.before("<div class=\"sticky-note\"><textarea id=\"stickynote-"+data.new_note_id+"\"></textarea><a href=\"#\" id=\"remove-"+data.new_note_id+"\"class=\"delete-sticky\">X</a></div>");
// print success message
} else {
// print error message
console.log('could not add');
}
}, 'json');
});
$('#sticky-notes').on('click', 'a.delete-sticky',function(event){
event.preventDefault();
var $stickynote = $(this);
var remove_id = $(this).attr('id');
remove_id = remove_id.replace("remove-","");
$.post("stickynotes/remove", {
id: remove_id
},
function(data){
if(data.response == true)
$stickynote.parent().remove();
else{
// print error message
console.log('could not remove ');
}
}, 'json');
});
$('#sticky-notes').on('keyup', 'textarea', function(event){
var $stickynote = $(this);
var update_id = $stickynote.attr('id'),
update_content = $stickynote.val();
update_id = update_id.replace("stickynote-","");
$.post("stickynotes/update", {
id: update_id,
content: update_content
},function(data){
if(data.response == false){
// print error message
console.log('could not update');
}
}, 'json');
});
});*/
// /public/js/custom.js
jQuery(function($) {
$("#create").on('click', function(event){
event.preventDefault();
var $amount = $(this);
$.post("amounts/add", null,
function(data){
if(data.response == true){
$amount.before("<div class=\"sticky-note\"><textarea id=\"stickynote-"+data.new_note_id+"\"></textarea><a href=\"#\" id=\"remove-"+data.new_note_id+"\"class=\"delete-sticky\">X</a></div>");
// print success message
} else {
// print error message
console.log('could not add');
}
}, 'json');
});
$('#sticky-notes').on('click', 'a.delete-sticky',function(event){
event.preventDefault();
var $amount = $(this);
var remove_id = $(this).attr('id');
remove_id = remove_id.replace("remove-","");
$.post("amounts/remove", {
id: remove_id
},
function(data){
if(data.response == true)
$amount.parent().remove();
else{
// print error message
console.log('could not remove ');
}
}, 'json');
});
$('#sticky-notes').on('keyup', 'textarea', function(event){
var $amount = $(this);
var update_id = $amount.attr('id'),
update_content = $amount.val();
update_id = update_id.replace("stickynote-","");
$.post("amounts/update", {
id: update_id,
content: update_content
},function(data){
if(data.response == false){
// print error message
console.log('could not update');
}
}, 'json');
});
});
|
var ex__put__loadbal__param__cc_8c =
[
[ "NC_INT64", "ex__put__loadbal__param__cc_8c.html#a8fe8ec701fdf28231954b552bd7c402c", null ],
[ "ex_put_loadbal_param_cc", "ex__put__loadbal__param__cc_8c.html#acac29bcc7ddf2b1c0538a6754c07c0c6", null ]
];
|
// var SGSAuth = require('../src/sgs-auth');
var SGSAuth = require('./coverage/instrument/src/sgs-auth');
var OAuthKeys = require('./fixtures/oauth-keys');
var Delegates = require('./fixtures/delegates');
var bodyParser = require('body-parser');
var passport = require('passport');
var express = require('express');
var localStrategyTests = require('./local-strategy-tests');
var oauthStrategyTests = require('./oauth-strategy-tests');
describe('Testing the auth. module:', function () {
'use strict';
before('Initialising the module', function () {
SGSAuth.init(Delegates, {
facebook: OAuthKeys.facebook,
google: OAuthKeys.google,
bearer: {},
local: {}
});
});
before('Initialising test server', function (callback) {
var app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(passport.initialize());
app.post(
'/auth/local/register',
SGSAuth.with('local', 'register'),
function (req, res) {
res.status(200).json({
token: req.auth.token
});
}
);
app.post(
'/auth/local/easy-register',
SGSAuth.with('local', 'easyRegister'),
function (req, res) {
res.status(200).json({
token: req.auth.token
});
}
);
app.post(
'/auth/local/verify_email',
SGSAuth.with('local', 'verifyEmail'),
function (req, res) {
res.status(200).json({
token: req.auth.token
});
}
);
app.get(
'/auth/bearer/authorize',
SGSAuth.with('bearer', 'authorize'),
function (req, res) {
res.status(200).end();
}
);
app.get(
'/auth/bearer/logout',
SGSAuth.with('bearer', 'logout'),
function (req, res) {
res.status(200).end();
}
);
app.post(
'/auth/local/login',
SGSAuth.with('local', 'login'),
function (req, res) {
res.status(200).json({
token: req.auth.token
});
}
);
app.post(
'/auth/local/change_password',
SGSAuth.with('bearer', 'authorize'),
SGSAuth.with('local', 'changePassword'),
function (req, res) {
res.status(200).json({
token: req.auth.token
});
}
);
app.post(
'/auth/local/forgot_password',
SGSAuth.with('local', 'forgotPassword'),
function (req, res) {
res.status(200).json({
token: req.auth.token
});
}
);
app.post(
'/auth/local/reset_password',
SGSAuth.with('local', 'resetPassword'),
function (req, res) {
res.status(200).json({
token: req.auth.token
});
}
);
app.get(
'/auth/facebook/login',
SGSAuth.with('facebook', 'login')
);
app.get(
'/auth/facebook/login_callback',
SGSAuth.with('facebook', 'login')
);
app.get(
'/auth/google/login',
SGSAuth.with('google', 'login')
);
app.get(
'/auth/google/login_callback',
SGSAuth.with('google', 'login')
);
app.listen(8000)
.on('error', callback)
.on('listening', callback);
});
describe('Local Strategy:', function () {
localStrategyTests();
});
describe('OAuth Strategy:', function () {
oauthStrategyTests();
});
});
|
import Quill from '../quill';
import clone from 'clone';
import equal from 'deep-equal';
import platform from '../lib/platform';
let Delta = Quill.require('delta');
class Keyboard {
// TODO allow passing in hotkeys in options
constructor(quill, options = {}) {
this.quill = quill;
this.hotkeys = {};
this.quill.root.addEventListener('keydown', (evt) => {
let which = evt.which || evt.keyCode;
let range = this.quill.getSelection();
let prevent = (this.hotkeys[which] || []).reduce(function(prevent, hotkey) {
let [key, callback] = hotkey;
if (!match(evt, key)) return prevent;
return callback(range, key, evt) || prevent;
}, false);
if (prevent) {
return evt.preventDefault();
}
});
}
addHotkey(hotkeys, callback) {
if (!Array.isArray(hotkeys)) {
hotkeys = [hotkeys];
}
hotkeys.forEach((hotkey) => {
hotkey = coerce(hotkey);
if (hotkey == null) {
return this.quill.emit(Quill.events.DEBUG, 'Attempted to add invalid hotkey', hotkey);
}
this.hotkeys[hotkey.key] = this.hotkeys[hotkey.key] || [];
this.hotkeys[hotkey.key].push([hotkey, callback]);
});
}
removeHotkey(hotkeys, callback) {
if (!Array.isArray(hotkeys)) {
hotkeys = [hotkeys];
}
return hotkeys.reduce((removed, query) => {
query = coerce(query);
if ((query != null) && (this.hotkeys[query.key] != null)) {
this.hotkeys[query.key] = this.hotkeys[query.key].filter(function(target) {
if (equal(target[0], query) && ((callback == null) || callback === target[1])) {
removed.push(target[1]);
return false;
}
return true;
});
}
return removed;
});
}
}
function corce(hotkey) {
switch (typeof hotkey) {
case 'string':
if (Keyboard.hotkeys[hotkey.toUpperCase()] != null) {
hotkey = clone(Keyboard.hotkeys[hotkey.toUpperCase()], false);
} else if (hotkey.length === 1) {
hotkey = { key: hotkey };
} else {
return null;
}
break;
case 'number':
hotkey = { key: hotkey };
break;
case 'object':
hotkey = clone(hotkey, false);
break;
default:
return null;
}
if (typeof hotkey.key === 'string') {
hotkey.key = hotkey.key.toUpperCase().charCodeAt(0);
}
return hotkey;
}
function match(evt, hotkey) {
let metaKey = platform.isMac() ? evt.metaKey : evt.metaKey || evt.ctrlKey;
if (hotkey.metaKey !== metaKey && hotkey.metaKey !== null) return false;
if (hotkey.shiftKey !== evt.shiftKey && hotkey.shiftKey !== null) return false;
if (hotkey.altKey !== evt.altKey && hotkey.altKey !== null) return false;
return true;
}
Quill.registerModule('keyboard', Keyboard);
export { Keyboard as default };
|
class HomePageService {
pageCards = [];
sorted = false;
registerCards(cards) {
cards.forEach(card => this.registerCard(card));
}
registerCard(card) {
this.pageCards.push(card);
}
getCards() {
if (this.sorted || this.pageCards.length == 0) {
return this.pageCards;
}
this.pageCards.sort((c1, c2) => c1.title.localeCompare(c2.title));
this.sorted = true;
return this.pageCards;
}
}
export default new HomePageService();
|
assert (/*: Num */ 1.0);
assert (/*: Int */ 1.0);
|
/**
* Makes "skip to content" link work correctly in IE9, Chrome, and Opera
* for better accessibility.
*
* @link http://www.nczonline.net/blog/2013/01/15/fixing-skip-to-content-links/
*/
( function() {
var is_webkit = navigator.userAgent.toLowerCase().indexOf( 'webkit' ) > -1,
is_opera = navigator.userAgent.toLowerCase().indexOf( 'opera' ) > -1,
is_ie = navigator.userAgent.toLowerCase().indexOf( 'msie' ) > -1;
if ( ( is_webkit || is_opera || is_ie ) && document.getElementById && window.addEventListener ) {
window.addEventListener( 'hashchange', function() {
var id = location.hash.substring( 1 ),
element;
if ( ! ( /^[A-z0-9_-]+$/.test( id ) ) ) {
return;
}
element = document.getElementById( id );
if ( element ) {
if ( ! ( /^(?:a|select|input|button|textarea)$/i.test( element.tagName ) ) ) {
element.tabIndex = -1;
}
element.focus();
}
}, false );
}
} )();
|
// map colours picked by Eskimo to match colour scheme
var mapStyle = [
{
featureType: "administrative",
stylers: [
{ visibility: "off" }
]
}
];
|
var async_exec = require('child_process').exec
async_exec('npm install shelljs', function (err, stdout, stderr) {
require('shelljs/global');
echo('About to setup Appgular environment');
echo('It works if it finishes with OK');
if(!which('bower')) {
echo('Bower is missing...taking care of that now.');
exec('npm install --global bower');
echo(exec('bower --version').output);
}
if(!which('grunt')) {
echo('Grunt is missing...taking care of that now.');
exec('npm install --global grunt-cli');
echo(exec('grunt --version').output);
}
if(!which('phantomjs')) {
echo('PhantomJS is missing...taking care of that now.');
exec('npm install --global phantomjs');
echo(exec('phantomjs --version').output);
}
if(!which('karma')) {
echo('Karma is missing...taking care of that now.');
exec('npm install --global karma');
echo(exec('karma --version').output);
}
echo('Installing devDependencies...');
exec('npm install');
echo('Installing components...');
exec('bower install');
echo('Downloading BrowserStackTunnel jar cli tool...');
exec('wget http://www.browserstack.com/BrowserStackTunnel.jar');
exec('mv BrowserStackTunnel.jar scripts/BrowserStackTunnel.jar');
echo('OK!');
});
|
System.register([], function($__export) {
"use strict";
var $__1;
var TestIterable;
return ($__1 = {}, Object.defineProperty($__1, "setters", {
value: [],
configurable: true,
enumerable: true,
writable: true
}), Object.defineProperty($__1, "execute", {
value: function() {
TestIterable = $__export("TestIterable", (function() {
var $__1;
var TestIterable = function TestIterable() {
this.list = [];
};
return ($traceurRuntime.createClass)(TestIterable, ($__1 = {}, Object.defineProperty($__1, Symbol.iterator, {
value: function() {
return this.list[Symbol.iterator]();
},
configurable: true,
enumerable: true,
writable: true
}), $__1), {});
}()));
},
configurable: true,
enumerable: true,
writable: true
}), $__1);
});
//# sourceMappingURL=angular2/test/change_detection/iterable.map
//# sourceMappingURL=../../../angular2/test/change_detection/iterable.js.map
|
angular.module('wakatime').controller('DashCtrl', function ($scope, SettingsService, $http, $log) {
$log.info("DashCtrl()");
var controller = this;
$scope.init = function () {
if (SettingsService.get() && SettingsService.get().apiKey) {
var apiKey = SettingsService.get().apiKey;
$http.get('https://wakatime.com/api/v1/users/current/?api_key=' + apiKey)
.then(function (response) {
$log.debug("Current user:", response.data);
});
$http.get('https://wakatime.com/api/v1/users/current/stats/last_7_days?api_key=' + apiKey)
.then(function (response) {
$log.debug("Stats:", response.data.data);
$scope.stats = response.data.data;
controller.initChart($scope.stats);
});
} else {
$log.warn("No API key yet");
$scope.noApiKey = true;
}
};
$scope.chartOptions = {
chart: {
type: 'pieChart',
height: 400,
donut: true,
x: function (d) {
return d.key;
},
y: function (d) {
return d.y;
},
showLabels: true,
//pie: {
// startAngle: function(d) { return d.startAngle/2 -Math.PI/2 },
// endAngle: function(d) { return d.endAngle/2 -Math.PI/2 }
//},
transitionDuration: 500,
legend: {
margin: {
top: 5,
right: 100,
bottom: 0,
left: 0
}
}
}
};
controller.initChart = function (stats) {
$scope.chartProjectData = [];
$scope.chartLanguageData = [];
$scope.chartEditorData = [];
for (var i = 0; i < stats.projects.length; i++) {
var project = stats.projects[i];
$scope.chartProjectData.push({key: project.name, y: project.total_seconds});
}
for (var i = 0; i < stats.languages.length; i++) {
var language = stats.languages[i];
$scope.chartLanguageData.push({key: language.name, y: language.total_seconds});
}
for (var i = 0; i < stats.editors.length; i++) {
var editor = stats.editors[i];
$scope.chartEditorData.push({key: editor.name, y: editor.total_seconds});
}
};
$scope.init();
});
|
/**
* 从一个 Color 对象转换出符合 {@link http://www.w3.org/TR/css3-color/|CSS Color Module Level 3} 标准定义的 CSS 语法描述格式。
* @see {@link Color#ieFilter}
* @see {@link Color#toJSON}
* @see {@link Color#toString}
* @see {@link Palette#css}
* @see {@link Gradient#css}
* @access public
* @func Color.prototype.css
* @param {number} [type] - 指定 CSS 语法描述的格式类型。
* @param {number} type.0 - \#RRGGBB 。
* @param {number} type.1 - rgb(R, G, B) || rgba(R, G, B, A) 。
* @param {number} type.2 - hsl(H, S, L) || hsla(H, S, L, A) 。
* @param {boolean} [alpha] - 是否输出为支持 `Alpha` 通道描述的格式。
* @param {boolean} alpha.false - rgb(R, G, B) || hsl(H, S, L) 。
* @param {boolean} alpha.true - rgba(R, G, B, A) || hsla(H, S, L, A) 。
* @returns {string}
* @example
* var color = new Color([ 0, 100, 100, 0 ], 'cmyk');
*
* console.log(color.css( )); // rgb(255,0,0)
*
* console.log(color.css(0)); // #FF0000
* console.log(color.css(0, true)); // #FF0000
*
* console.log(color.css(1)); // rgb(255,0,0)
* console.log(color.css(1, true)); // rgba(255,0,0,1)
*
* console.log(color.css(2)); // hsl(0,100%,50%)
* console.log(color.css(2, true)); // hsla(0,100%,50%,1)
*/
|
/* Wrapper for accessing strings through sequential reads */
function Stream(str) {
var position = 0;
function read(length) {
var result = str.substr(position, length);
position += length;
return result;
}
/* read a big-endian 32-bit integer */
function readInt32() {
var result = (
(str.charCodeAt(position) << 24)
+ (str.charCodeAt(position + 1) << 16)
+ (str.charCodeAt(position + 2) << 8)
+ str.charCodeAt(position + 3));
position += 4;
return result;
}
/* read a big-endian 16-bit integer */
function readInt16() {
var result = (
(str.charCodeAt(position) << 8)
+ str.charCodeAt(position + 1));
position += 2;
return result;
}
/* read an 8-bit integer */
function readInt8(signed) {
var result = str.charCodeAt(position);
if (signed && result > 127) result -= 256;
position += 1;
return result;
}
function eof() {
return position >= str.length;
}
/* read a MIDI-style variable-length integer
(big-endian value in groups of 7 bits,
with top bit set to signify that another byte follows)
*/
function readVarInt() {
var result = 0;
while (true) {
var b = readInt8();
if (b & 0x80) {
result += (b & 0x7f);
result <<= 7;
} else {
/* b is the last byte */
return result + b;
}
}
}
return {
'eof': eof,
'read': read,
'readInt32': readInt32,
'readInt16': readInt16,
'readInt8': readInt8,
'readVarInt': readVarInt
}
}
|
var searchData=
[
['tabularactionvalues_2ecpp',['tabularActionValues.cpp',['../tabularActionValues_8cpp.html',1,'']]],
['tabularactionvalues_2eh',['tabularActionValues.h',['../tabularActionValues_8h.html',1,'']]],
['taskdimensions_2ecpp',['taskDimensions.cpp',['../taskDimensions_8cpp.html',1,'']]],
['taskdimensions_2eh',['taskDimensions.h',['../taskDimensions_8h.html',1,'']]],
['taskscheduler_2ecpp',['taskScheduler.cpp',['../taskScheduler_8cpp.html',1,'']]],
['taskscheduler_2eh',['taskScheduler.h',['../taskScheduler_8h.html',1,'']]],
['taskschedulertest_2ecpp',['taskSchedulerTest.cpp',['../taskSchedulerTest_8cpp.html',1,'']]],
['tasksetgenerator_2ecpp',['taskSetGenerator.cpp',['../taskSetGenerator_8cpp.html',1,'']]],
['tasksetgenerator_2eh',['taskSetGenerator.h',['../taskSetGenerator_8h.html',1,'']]],
['temperature_2epy',['temperature.py',['../temperature_8py.html',1,'']]],
['temperatureandagingmodel_2ecpp',['temperatureAndAgingModel.cpp',['../temperatureAndAgingModel_8cpp.html',1,'']]],
['temperatureandagingmodel_2eh',['temperatureAndAgingModel.h',['../temperatureAndAgingModel_8h.html',1,'']]],
['temperaturedimension_2ecpp',['temperatureDimension.cpp',['../temperatureDimension_8cpp.html',1,'']]],
['temperaturedimension_2eh',['temperatureDimension.h',['../temperatureDimension_8h.html',1,'']]],
['temperaturemodel_2eh',['temperatureModel.h',['../temperatureModel_8h.html',1,'']]],
['terminates_2ecpp',['terminates.cpp',['../terminates_8cpp.html',1,'']]],
['terminates_2eh',['terminates.h',['../terminates_8h.html',1,'']]],
['testlinearprogrammingsolver_2ecpp',['testLinearProgrammingSolver.cpp',['../testLinearProgrammingSolver_8cpp.html',1,'']]],
['testrl_2ecpp',['testRL.cpp',['../testRL_8cpp.html',1,'']]],
['time_2ecpp',['time.cpp',['../time_8cpp.html',1,'']]],
['time_2eh',['time.h',['../time_8h.html',1,'']]],
['timedimension_2ecpp',['timeDimension.cpp',['../timeDimension_8cpp.html',1,'']]],
['timedimension_2eh',['timeDimension.h',['../timeDimension_8h.html',1,'']]],
['timeoutevent_2ecpp',['timeoutEvent.cpp',['../timeoutEvent_8cpp.html',1,'']]],
['timeoutevent_2eh',['timeoutEvent.h',['../timeoutEvent_8h.html',1,'']]],
['tinystr_2ecpp',['tinystr.cpp',['../tinystr_8cpp.html',1,'']]],
['tinystr_2eh',['tinystr.h',['../tinystr_8h.html',1,'']]],
['tinyxml_2ecpp',['tinyxml.cpp',['../tinyxml_8cpp.html',1,'']]],
['tinyxml_2eh',['tinyxml.h',['../tinyxml_8h.html',1,'']]],
['tinyxml2_2ecpp',['tinyxml2.cpp',['../tinyxml2_8cpp.html',1,'']]],
['tinyxml2_2eh',['tinyxml2.h',['../tinyxml2_8h.html',1,'']]],
['tinyxmlerror_2ecpp',['tinyxmlerror.cpp',['../tinyxmlerror_8cpp.html',1,'']]],
['tinyxmlparser_2ecpp',['tinyxmlparser.cpp',['../tinyxmlparser_8cpp.html',1,'']]],
['transitionmatrix_2ecpp',['transitionMatrix.cpp',['../transitionMatrix_8cpp.html',1,'']]],
['transitionmatrix_2eh',['transitionMatrix.h',['../transitionMatrix_8h.html',1,'']]],
['twophases_2ecpp',['twoPhases.cpp',['../twoPhases_8cpp.html',1,'']]],
['twophases_2eh',['twoPhases.h',['../twoPhases_8h.html',1,'']]]
];
|
INCLUDE('index.i18n');
var template = GETTEXT('template.ko');
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as Common from '../common/common.js';
import * as UI from '../ui/ui.js';
import {DataDisplayDelegate, Events as ProfileHeaderEvents, ProfileHeader} from './ProfileHeader.js'; // eslint-disable-line no-unused-vars
/**
* @unrestricted
*/
export class ProfileSidebarTreeElement extends UI.TreeOutline.TreeElement {
/**
* @param {!DataDisplayDelegate} dataDisplayDelegate
* @param {!ProfileHeader} profile
* @param {string} className
*/
constructor(dataDisplayDelegate, profile, className) {
super('', false);
this._iconElement = document.createElement('div');
this._iconElement.classList.add('icon');
this._titlesElement = document.createElement('div');
this._titlesElement.classList.add('titles');
this._titlesElement.classList.add('no-subtitle');
this._titleContainer = this._titlesElement.createChild('span', 'title-container');
this.titleElement = this._titleContainer.createChild('span', 'title');
this._subtitleElement = this._titlesElement.createChild('span', 'subtitle');
this.titleElement.textContent = profile.title;
this._className = className;
this._small = false;
this._dataDisplayDelegate = dataDisplayDelegate;
this.profile = profile;
profile.addEventListener(ProfileHeaderEvents.UpdateStatus, this._updateStatus, this);
if (profile.canSaveToFile()) {
this._createSaveLink();
} else {
profile.addEventListener(ProfileHeaderEvents.ProfileReceived, this._onProfileReceived, this);
}
}
_createSaveLink() {
this._saveLinkElement = this._titleContainer.createChild('span', 'save-link');
this._saveLinkElement.textContent = Common.UIString.UIString('Save');
this._saveLinkElement.addEventListener('click', this._saveProfile.bind(this), false);
}
_onProfileReceived(event) {
this._createSaveLink();
}
/**
* @param {!Common.EventTarget.EventTargetEvent} event
*/
_updateStatus(event) {
const statusUpdate = event.data;
if (statusUpdate.subtitle !== null) {
this._subtitleElement.textContent = statusUpdate.subtitle || '';
this._titlesElement.classList.toggle('no-subtitle', !statusUpdate.subtitle);
}
if (typeof statusUpdate.wait === 'boolean' && this.listItemElement) {
this.listItemElement.classList.toggle('wait', statusUpdate.wait);
}
}
/**
* @override
* @param {!Event} event
* @return {boolean}
*/
ondblclick(event) {
if (!this._editing) {
this._startEditing(/** @type {!Element} */ (event.target));
}
return false;
}
/**
* @param {!Element} eventTarget
*/
_startEditing(eventTarget) {
const container = eventTarget.enclosingNodeOrSelfWithClass('title');
if (!container) {
return;
}
const config = new UI.InplaceEditor.Config(this._editingCommitted.bind(this), this._editingCancelled.bind(this));
this._editing = UI.InplaceEditor.InplaceEditor.startEditing(container, config);
}
/**
* @param {!Element} container
* @param {string} newTitle
*/
_editingCommitted(container, newTitle) {
delete this._editing;
this.profile.setTitle(newTitle);
}
_editingCancelled() {
delete this._editing;
}
dispose() {
this.profile.removeEventListener(ProfileHeaderEvents.UpdateStatus, this._updateStatus, this);
this.profile.removeEventListener(ProfileHeaderEvents.ProfileReceived, this._onProfileReceived, this);
}
/**
* @override
* @return {boolean}
*/
onselect() {
this._dataDisplayDelegate.showProfile(this.profile);
return true;
}
/**
* @override
* @return {boolean}
*/
ondelete() {
this.profile.profileType().removeProfile(this.profile);
return true;
}
/**
* @override
*/
onattach() {
if (this._className) {
this.listItemElement.classList.add(this._className);
}
if (this._small) {
this.listItemElement.classList.add('small');
}
this.listItemElement.appendChildren(this._iconElement, this._titlesElement);
this.listItemElement.addEventListener('contextmenu', this._handleContextMenuEvent.bind(this), true);
UI.ARIAUtils.setDescription(this.listItemElement, ls`${this.profile.profileType().name}`);
}
/**
* @param {!Event} event
*/
_handleContextMenuEvent(event) {
const profile = this.profile;
const contextMenu = new UI.ContextMenu.ContextMenu(event);
// FIXME: use context menu provider
contextMenu.headerSection().appendItem(
Common.UIString.UIString('Load…'),
self.Profiler.ProfilesPanel._fileSelectorElement.click.bind(self.Profiler.ProfilesPanel._fileSelectorElement));
if (profile.canSaveToFile()) {
contextMenu.saveSection().appendItem(Common.UIString.UIString('Save…'), profile.saveToFile.bind(profile));
}
contextMenu.footerSection().appendItem(Common.UIString.UIString('Delete'), this.ondelete.bind(this));
contextMenu.show();
}
_saveProfile(event) {
this.profile.saveToFile();
}
/**
* @param {boolean} small
*/
setSmall(small) {
this._small = small;
if (this.listItemElement) {
this.listItemElement.classList.toggle('small', this._small);
}
}
/**
* @param {string} title
*/
setMainTitle(title) {
this.titleElement.textContent = title;
}
}
|
var searchData=
[
['wait_5fid',['WAIT_ID',['../globals_8h.html#a6a6a0bb02e515a094c3e7ea1bcb66fcc',1,'globals.h']]],
['wait_5flength',['WAIT_LENGTH',['../globals_8h.html#a235d2d0eac7e9af190ebafb84df37fd9',1,'globals.h']]],
['wait_5fstart',['WAIT_START',['../globals_8h.html#aea55597952638136c7c929b238904c82',1,'globals.h']]]
];
|
// TODO: write a single Dashboard kind that does:
// adds option as to wether to use seperate dashboards or layers (for webOS 3, possible for html notifications that work right?)
// webOS 3: open custom dashboard as we do now
// webOS 2: open stock dashboard, as we do now, but whenever a new layer is pushed, call openDashboard again
// playbook: opens an individual webkit notification for each layer
// chrome: see if we can use the existing dashboard in chrome somehow, assuming it's custom Html Notifications actually work unlike playbook
// android: call out to the notification plugin
// TODO: fix that damned android notification plugin
if(Platform.isWebOS() && Platform.platformVersion < 3.0) {
enyo.kind({ name: "gvoice.Dashboard", kind: "enyo.Dashboard" });
} else {
enyo.kind({
name: "gvoice.Dashboard",
kind: "enyo.Dashboard",
indexPath: "mainApp/dashboard/dashboard.html",
updateWindow: function() {
// Note that closed windows may get their js bindings snipped, so 'w.closed' may actually be undefined instead of true.
var windowValid = this.window && this.window.closed === false;
// If we have items to display, then create the window if we don't already have one.
if(this.layers.length) {
var params = {layers:this.layers, docPath:document.location.pathname, dashboardId:this.dashboardId};
if(!windowValid) {
var attributes = {
webosDragMode:"manual",
window:"dashboard",
doubleheightdash:true,
_enyoOpener:window,
};
if(this.smallIcon) {
attributes.icon = this.smallIcon;
}
this.window = enyo.windows.openDashboard(enyo.path.rewrite(this.indexPath), this.name, params, attributes);
} else {
enyo.windows.activate(undefined, this.name, params);
}
} else {
if(windowValid) {
this.window.close();
}
this.window = undefined;
}
},
});
}
|
const test = require('tape')
const isFunction = require('../core/isFunction')
const isMonoid = require('./isMonoid')
test('isMonoid predicate', t => {
t.ok(isFunction(isMonoid), 'is a function')
t.end()
})
|
var path = require('path');
var util = require('util');
var http = require('http');
// ошибки для выдачи посетителю
function HttpError(status, message) {
Error.apply(this, arguments);
Error.captureStackTrace(this, HttpError);
this.status = status;
this.message = message || http.STATUS_CODES[status] || "Error";
}
util.inherits(HttpError, Error);
HttpError.prototype.name = 'HttpError';
exports.HttpError = HttpError;
|
//------------------------------------------------------------------------------
/*
This file is part of Codius: https://github.com/codius
Copyright (c) 2014 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
var AbstractFilesystemNode = function () {
};
AbstractFilesystemNode.prototype.isDirectory = function () {
return false;
};
exports.AbstractFilesystemNode = AbstractFilesystemNode;
|
'use strict';
module.exports = function (T, a) {
var rules = new T(), x;
a.deep(rules.property, { '/': 2 }, "Property");
a(rules.value['/'] instanceof T, true, "Value");
a(rules.assignment['/'] instanceof T, true, "Assignment");
x = rules.value = {};
a(rules.value, x, "Editable");
};
|
'use strict';
const jwt = require('./jwt');
const providers = require('./providers');
const user = require('./user');
const role = require('./role');
const usersPermissions = require('./users-permissions');
module.exports = {
jwt,
providers,
role,
user,
'users-permissions': usersPermissions,
};
|
// @flow
import { NativeModules } from 'react-native';
const { ExponentImagePicker } = NativeModules;
type ImageInfo = {|
uri: string,
width: number,
height: number,
|};
type ImageResult = {| cancelled: true |} | ({| cancelled: false |} & ImageInfo);
type ImageLibraryOptions = {
allowsEditing?: boolean,
aspect?: [number, number],
quality?: number,
};
export async function launchImageLibraryAsync(
options?: ImageLibraryOptions
): Promise<ImageResult> {
if (!options || typeof options !== 'object') {
options = {};
}
return ExponentImagePicker.launchImageLibraryAsync(options);
}
type CameraOptions = {
allowsEditing?: boolean,
aspect?: [number, number],
quality?: number,
};
export async function launchCameraAsync(
options?: CameraOptions
): Promise<ImageResult> {
if (!options || typeof options !== 'object') {
options = {};
}
return ExponentImagePicker.launchCameraAsync(options);
}
|
// Generated by CoffeeScript 1.6.3
(function() {
var Stl, child_proc, fs, path, stl_parser, to_image;
fs = require('fs');
path = require('path');
child_proc = require('child_process');
stl_parser = require('./parser/stl_parser');
to_image = require('./to/image');
Stl = (function() {
function Stl() {}
return Stl;
})();
Stl.readFile = function(filePath, callback, progressCb) {
return stl_parser.parseFile(filePath, callback, progressCb);
};
Stl.imageify = function(filePath, options, callback, progressCb) {
if (options === null) {
options = {};
}
if (options.width === null || typeof options.width === 'undefined') {
options.width = 800;
}
if (options.height === null || typeof options.height === 'undefined') {
options.height = 600;
}
return to_image.convertFile(filePath, options, callback, progressCb);
};
Stl.writeFile = function(fileName, solidName, polygons, callback) {
var stream, writePolygon;
stream = fs.createWriteStream(fileName);
writePolygon = function(vertices, normal) {
var vertex, _i, _len;
stream.write(" facet normal " + normal.x + " " + normal.y + " " + normal.z + "\n");
stream.write(" outer loop\n");
for (_i = 0, _len = verticies.length; _i < _len; _i++) {
vertex = verticies[_i];
stream.write(" vertex " + vertex.pos.x + " " + vertex.pos.y + " " + vertex.pos.z + " \n");
}
stream.write(" endloop\n");
return stream.write(" endfacet\n");
};
return stream.once('open', function(fd) {
var normal, polygon, v, _i, _j, _len, _ref;
stream.write("solid " + solidName + "\n");
for (_i = 0, _len = polygons.length; _i < _len; _i++) {
polygon = polygons[_i];
normal = polygon.vertices[0].normal;
for (v = _j = 1, _ref = polygon.verticies.length - 1; 1 <= _ref ? _j < _ref : _j > _ref; v = 1 <= _ref ? ++_j : --_j) {
writePolygon([polygon.vertices[0], polygon.vertices[v], polygon.vertices[v + 1]], normal);
}
}
stream.write("endsolid " + solidName + "\n");
if (callback) {
return callback(null);
}
});
};
module.exports = Stl;
}).call(this);
|
'use strict';
/**
* Dime - app/report/form.js
*/
(function ($, Backbone, _, App) {
App.provide('Views.Report.Form', App.Views.Core.Form.Filter.extend({
reset: function(e) {
this.el.reset();
this.$(':input[name]').each(function (idx, input) {
$(input).trigger('change');
});
},
submit: function(e) {
if (e) {
e.preventDefault();
}
if (this.collection) {
var data = this.serialize(true);
if ("undefined" == typeof(data.limit)) {
// avoid limits
data.limit="";
}
// push show options to table
if (data.show && this.options.callback) {
var show = data.show;
this.options.callback(show);
delete data.show;
}
this.collection.removeFetchData('filter');
if (data) {
this.collection.addFetchData('filter', data);
}
this.collection.load();
}
},
save: function(e) {}
}));
})(jQuery, Backbone, _, Dime);
|
import 'babel-polyfill';
import './js/02-Block_Scope';
import './js/03-Functions';
import './js/04-Destructuring_and_Spread';
import './js/06-Promises';
import './js/07-async_functions';
import './js/08-Fetch';
import './js/09-Classes_and_OOP';
import './js/10-FP';
import './js/11-Observables';
import './js/12-Subjects';
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactIconBase = require('react-icon-base');
var _reactIconBase2 = _interopRequireDefault(_reactIconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var IoSocialWindows = function IoSocialWindows(props) {
return _react2.default.createElement(
_reactIconBase2.default,
_extends({ viewBox: '0 0 40 40' }, props),
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'm35 20.7v16.8l-19.4-2.8v-14h19.4z m-20.6 0v13.8l-14.4-2.1v-11.7h14.4z m20.6-18.2v17h-19.4v-14.3z m-20.6 3v14h-14.4v-12z' })
)
);
};
exports.default = IoSocialWindows;
module.exports = exports['default'];
|
/**
* @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
(function() {
'use strict';
CKEDITOR.plugins.add( 'stylescombo', {
requires: 'richcombo',
lang: 'af,ar,bg,bn,bs,ca,cs,cy,da,de,el,en,en-au,en-ca,en-gb,eo,es,et,eu,fa,fi,fo,fr,fr-ca,gl,gu,he,hi,hr,hu,id,is,it,ja,ka,km,ko,ku,lt,lv,mk,mn,ms,nb,nl,no,pl,pt,pt-br,ro,ru,si,sk,sl,sq,sr,sr-latn,sv,th,tr,ug,uk,vi,zh,zh-cn', // %REMOVE_LINE_CORE%
init: function( editor ) {
var config = editor.config,
lang = editor.lang.stylescombo,
styles = {},
stylesList = [],
combo,
allowedContent = [];
editor.on( 'stylesSet', function( evt ) {
var stylesDefinitions = evt.data.styles;
if ( !stylesDefinitions )
return;
var style, styleName;
// Put all styles into an Array.
for ( var i = 0, count = stylesDefinitions.length; i < count; i++ ) {
var styleDefinition = stylesDefinitions[ i ];
if ( editor.blockless && ( styleDefinition.element in CKEDITOR.dtd.$block ) )
continue;
styleName = styleDefinition.name;
style = new CKEDITOR.style( styleDefinition );
if ( !editor.filter.customConfig || editor.filter.check( style ) ) {
style._name = styleName;
style._.enterMode = config.enterMode;
// Weight is used to sort styles (#9029).
style._.weight = i + ( style.type == CKEDITOR.STYLE_OBJECT ? 1 : style.type == CKEDITOR.STYLE_BLOCK ? 2 : 3 ) * 1000;
styles[ styleName ] = style;
stylesList.push( style );
allowedContent.push( style );
}
}
// Sorts the Array, so the styles get grouped by type in proper order (#9029).
stylesList.sort( function( styleA, styleB ) { return styleA._.weight - styleB._.weight; } );
} );
editor.ui.addRichCombo( 'Styles', {
label: lang.label,
title: lang.panelTitle,
toolbar: 'styles,10',
allowedContent: allowedContent,
panel: {
css: [ CKEDITOR.skin.getPath( 'editor' ) ].concat( config.contentsCss ),
multiSelect: true,
attributes: { 'aria-label': lang.panelTitle }
},
init: function() {
var style, styleName, lastType, type, i, count;
// Loop over the Array, adding all items to the
// combo.
for ( i = 0, count = stylesList.length; i < count; i++ ) {
style = stylesList[ i ];
styleName = style._name;
type = style.type;
if ( type != lastType ) {
this.startGroup( lang[ 'panelTitle' + String( type ) ] );
lastType = type;
}
this.add( styleName, style.type == CKEDITOR.STYLE_OBJECT ? styleName : style.buildPreview(), styleName );
}
this.commit();
},
onClick: function( value ) {
editor.focus();
editor.fire( 'saveSnapshot' );
var style = styles[ value ],
elementPath = editor.elementPath();
editor[ style.checkActive( elementPath ) ? 'removeStyle' : 'applyStyle' ]( style );
editor.fire( 'saveSnapshot' );
},
onRender: function() {
editor.on( 'selectionChange', function( ev ) {
var currentValue = this.getValue(),
elementPath = ev.data.path,
elements = elementPath.elements;
// For each element into the elements path.
for ( var i = 0, count = elements.length, element; i < count; i++ ) {
element = elements[ i ];
// Check if the element is removable by any of
// the styles.
for ( var value in styles ) {
if ( styles[ value ].checkElementRemovable( element, true ) ) {
if ( value != currentValue )
this.setValue( value );
return;
}
}
}
// If no styles match, just empty it.
this.setValue( '' );
}, this );
},
onOpen: function() {
var selection = editor.getSelection(),
element = selection.getSelectedElement(),
elementPath = editor.elementPath( element ),
counter = [ 0, 0, 0, 0 ];
this.showAll();
this.unmarkAll();
for ( var name in styles ) {
var style = styles[ name ],
type = style.type;
// Check if block styles are applicable.
if ( type == CKEDITOR.STYLE_BLOCK && !elementPath.isContextFor( style.element ) ) {
this.hideItem( name );
continue;
}
if ( style.checkActive( elementPath ) )
this.mark( name );
else if ( type == CKEDITOR.STYLE_OBJECT && !style.checkApplicable( elementPath ) ) {
this.hideItem( name );
counter[ type ]--;
}
counter[ type ]++;
}
if ( !counter[ CKEDITOR.STYLE_BLOCK ] )
this.hideGroup( lang[ 'panelTitle' + String( CKEDITOR.STYLE_BLOCK ) ] );
if ( !counter[ CKEDITOR.STYLE_INLINE ] )
this.hideGroup( lang[ 'panelTitle' + String( CKEDITOR.STYLE_INLINE ) ] );
if ( !counter[ CKEDITOR.STYLE_OBJECT ] )
this.hideGroup( lang[ 'panelTitle' + String( CKEDITOR.STYLE_OBJECT ) ] );
},
// Force a reload of the data
reset: function() {
if ( combo ) {
delete combo._.panel;
delete combo._.list;
combo._.committed = 0;
combo._.items = {};
combo._.state = CKEDITOR.TRISTATE_OFF;
}
styles = {};
stylesList = [];
}
});
}
});
})();
|
/**
* @ngdoc Module
* @name app.components.avengers
* @description
* # module
* define module of the app
*/
(function() {
'use strict';
angular.module('app.components.avengers', []);
})();
|
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var plumber = require('gulp-plumber');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var gutil = require('gulp-util');
var exit = require('gulp-exit');
gulp.task('script', function() {
return gulp
.src(['routes/*','models/*'])
.pipe(plumber())
.pipe(jshint())
.pipe(jshint.reporter('default'))
;
})
gulp.task('test', function() {
return gulp
.src('test/*.js',{ read: false })
.pipe(mocha({ reporter: 'list' }))
.pipe(istanbul.writeReports())
.on('error', gutil.log)
.pipe(exit());
})
gulp.task('watch', function() {
gulp.watch(['routes/*','models/*'], ['script']);
// gulp.watch('test/*.js', ['test']);
})
gulp.task('default', [ 'script', 'watch']);
|
var url = require('url'),
common = require('../common');
var redirectRegex = /^201|30(1|2|7|8)$/;
/*!
* Array of passes.
*
* A `pass` is just a function that is executed on `req, res, options`
* so that you can easily add new checks while still keeping the base
* flexible.
*/
module.exports = { // <--
/**
* If is a HTTP 1.0 request, remove chunk headers
*
* @param {ClientRequest} Req Request object
* @param {IncomingMessage} Res Response object
* @param {proxyResponse} Res Response object from the proxy request
*
* @api private
*/
removeChunked: function removeChunked(req, res, proxyRes) {
if (req.httpVersion === '1.0') {
delete proxyRes.headers['transfer-encoding'];
}
},
/**
* If is a HTTP 1.0 request, set the correct connection header
* or if connection header not present, then use `keep-alive`
*
* @param {ClientRequest} Req Request object
* @param {IncomingMessage} Res Response object
* @param {proxyResponse} Res Response object from the proxy request
*
* @api private
*/
setConnection: function setConnection(req, res, proxyRes) {
if (req.httpVersion === '1.0') {
proxyRes.headers.connection = req.headers.connection || 'close';
} else if (req.httpVersion !== '2.0' && !proxyRes.headers.connection) {
proxyRes.headers.connection = req.headers.connection || 'keep-alive';
}
},
setRedirectHostRewrite: function setRedirectHostRewrite(req, res, proxyRes, options) {
if ((options.hostRewrite || options.autoRewrite || options.protocolRewrite)
&& proxyRes.headers['location']
&& redirectRegex.test(proxyRes.statusCode)) {
var target = url.parse(options.target);
var u = url.parse(proxyRes.headers['location']);
// make sure the redirected host matches the target host before rewriting
if (target.host != u.host) {
return;
}
if (options.hostRewrite) {
u.host = options.hostRewrite;
} else if (options.autoRewrite) {
u.host = req.headers['host'];
}
if (options.protocolRewrite) {
u.protocol = options.protocolRewrite;
}
proxyRes.headers['location'] = u.format();
}
},
/**
* Copy headers from proxyResponse to response
* set each header in response object.
*
* @param {ClientRequest} Req Request object
* @param {IncomingMessage} Res Response object
* @param {proxyResponse} Res Response object from the proxy request
* @param {Object} Options options.cookieDomainRewrite: Config to rewrite cookie domain
*
* @api private
*/
writeHeaders: function writeHeaders(req, res, proxyRes, options) {
var rewriteCookieDomainConfig = options.cookieDomainRewrite,
preserveHeaderKeyCase = options.preserveHeaderKeyCase,
rawHeaderKeyMap,
setHeader = function(key, header) {
if (header == undefined) return;
if (rewriteCookieDomainConfig && key.toLowerCase() === 'set-cookie') {
header = common.rewriteCookieDomain(header, rewriteCookieDomainConfig);
}
res.setHeader(String(key).trim(), header);
};
if (typeof rewriteCookieDomainConfig === 'string') { //also test for ''
rewriteCookieDomainConfig = { '*': rewriteCookieDomainConfig };
}
// message.rawHeaders is added in: v0.11.6
// https://nodejs.org/api/http.html#http_message_rawheaders
if (preserveHeaderKeyCase && proxyRes.rawHeaders != undefined) {
rawHeaderKeyMap = {};
for (var i = 0; i < proxyRes.rawHeaders.length; i += 2) {
var key = proxyRes.rawHeaders[i];
rawHeaderKeyMap[key.toLowerCase()] = key;
}
}
Object.keys(proxyRes.headers).forEach(function(key) {
var header = proxyRes.headers[key];
if (preserveHeaderKeyCase && rawHeaderKeyMap) {
key = rawHeaderKeyMap[key] || key;
}
setHeader(key, header);
});
},
/**
* Set the statusCode from the proxyResponse
*
* @param {ClientRequest} Req Request object
* @param {IncomingMessage} Res Response object
* @param {proxyResponse} Res Response object from the proxy request
*
* @api private
*/
writeStatusCode: function writeStatusCode(req, res, proxyRes) {
// From Node.js docs: response.writeHead(statusCode[, statusMessage][, headers])
if(proxyRes.statusMessage) {
res.statusCode = proxyRes.statusCode;
res.statusMessage = proxyRes.statusMessage;
} else {
res.statusCode = proxyRes.statusCode;
}
}
};
|
describe('DomEvent', function() {
var el;
function simulateClick(el) {
if (document.createEvent) {
var e = document.createEvent('MouseEvents');
e.initMouseEvent('click', true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
return el.dispatchEvent(e);
} else if (el.fireEvent) {
return el.fireEvent('onclick');
}
}
beforeEach(function() {
el = document.createElement('div');
el.style.position = 'absolute';
el.style.top = el.style.left = '-10000px';
document.body.appendChild(el);
});
afterEach(function() {
document.body.removeChild(el);
});
describe('#addListener', function() {
it('should add a listener and call it on event', function() {
var listener1 = jasmine.createSpy('listener1'),
listener2 = jasmine.createSpy('listener2');
L.DomEvent.addListener(el, 'click', listener1);
L.DomEvent.addListener(el, 'click', listener2);
simulateClick(el);
expect(listener1).toHaveBeenCalled();
expect(listener2).toHaveBeenCalled();
});
it('should have "this" keyword point to the given context', function() {
var obj = {foo: 'bar'},
result;
L.DomEvent.addListener(el, 'click', function() {
result = this;
}, obj);
simulateClick(el);
expect(result).toEqual(obj);
});
it('should pass an event object to the listener', function() {
var type;
L.DomEvent.addListener(el, 'click', function(e) {
type = e && e.type;
});
simulateClick(el);
expect(type).toEqual('click');
});
});
describe('#removeListener', function() {
it('should remove prevously added listener', function() {
var listener = jasmine.createSpy('listener');
L.DomEvent.addListener(el, 'click', listener);
L.DomEvent.removeListener(el, 'click', listener);
simulateClick(el);
expect(listener).not.toHaveBeenCalled();
});
});
describe('#stopPropagation', function() {
it('should stop propagation of the given event', function() {
var child = document.createElement('div'),
listener = jasmine.createSpy('listener');
el.appendChild(child);
L.DomEvent.addListener(child, 'click', L.DomEvent.stopPropagation);
L.DomEvent.addListener(el, 'click', listener);
simulateClick(child);
expect(listener).not.toHaveBeenCalled();
el.removeChild(child);
});
});
describe('#preventDefault', function() {
it('should prevent the default action of event', function() {
L.DomEvent.addListener(el, 'click', L.DomEvent.preventDefault);
expect(simulateClick(el)).toBe(false);
});
});
});
|
/* jshint asi:true*/
steal("can/map", "can/compute", "can/test", function (undefined) {
module('can/map')
test("Basic Map", 4, function () {
var state = new can.Map({
category: 5,
productType: 4
});
state.bind("change", function (ev, attr, how, val, old) {
equal(attr, "category", "correct change name")
equal(how, "set")
equal(val, 6, "correct")
equal(old, 5, "correct")
});
state.attr("category", 6);
state.unbind("change");
});
test("Nested Map", 5, function () {
var me = new can.Map({
name: {
first: "Justin",
last: "Meyer"
}
});
ok(me.attr("name") instanceof can.Map);
me.bind("change", function (ev, attr, how, val, old) {
equal(attr, "name.first", "correct change name")
equal(how, "set")
equal(val, "Brian", "correct")
equal(old, "Justin", "correct")
})
me.attr("name.first", "Brian");
me.unbind("change")
})
test("remove attr", function () {
var state = new can.Map({
category: 5,
productType: 4
});
state.removeAttr("category");
deepEqual(can.Map.keys(state), ["productType"], "one property");
});
test("nested event handlers are not run by changing the parent property (#280)", function () {
var person = new can.Map({
name: {
first: "Justin"
}
})
person.bind("name.first", function (ev, newName) {
ok(false, "name.first should never be called")
//equal(newName, "hank", "name.first handler called back with correct new name")
});
person.bind("name", function () {
ok(true, "name event triggered")
})
person.attr("name", {
first: "Hank"
});
});
test("cyclical objects (#521)", function () {
var foo = {};
foo.foo = foo;
var fooed = new can.Map(foo);
ok(true, "did not cause infinate recursion");
ok(fooed.attr('foo') === fooed, "map points to itself")
var me = {
name: "Justin"
}
var references = {
husband: me,
friend: me
}
var ref = new can.Map(references)
ok(ref.attr('husband') === ref.attr('friend'), "multiple properties point to the same thing")
})
test('Getting attribute that is a can.compute should return the compute and not the value of the compute (#530)', function () {
var compute = can.compute('before');
var map = new can.Map({
time: compute
});
equal(map.time, compute, 'dot notation call of time is compute');
equal(map.attr('time'), compute, '.attr() call of time is compute');
})
test('_cid add to original object', function () {
var map = new can.Map(),
obj = {
'name': 'thecountofzero'
};
map.attr('myObj', obj);
ok(!obj._cid, '_cid not added to original object');
})
test("can.each used with maps", function () {
can.each(new can.Map({
foo: "bar"
}), function (val, attr) {
if (attr === "foo") {
equal(val, "bar")
} else {
ok(false, "no properties other should be called " + attr)
}
})
})
test("can.Map serialize triggers reading (#626)", function () {
var old = can.__reading;
var attributesRead = [];
var readingTriggeredForKeys = false;
can.__reading = function (object, attribute) {
if (attribute === "__keys") {
readingTriggeredForKeys = true;
} else {
attributesRead.push(attribute);
}
};
var testMap = new can.Map({
cats: "meow",
dogs: "bark"
});
testMap.serialize();
ok(can.inArray("cats", attributesRead ) !== -1 && can.inArray( "dogs", attributesRead ) !== -1, "map serialization triggered __reading on all attributes");
ok(readingTriggeredForKeys, "map serialization triggered __reading for __keys");
can.__reading = old;
})
test("Test top level attributes", 7, function () {
var test = new can.Map({
'my.enable': false,
'my.item': true,
'my.count': 0,
'my.newCount': 1,
'my': {
'value': true,
'nested': {
'value': 100
}
}
});
equal(test.attr('my.value'), true, 'correct');
equal(test.attr('my.nested.value'), 100, 'correct');
ok(test.attr("my.nested") instanceof can.Map);
equal(test.attr('my.enable'), false, 'falsey (false) value accessed correctly');
equal(test.attr('my.item'), true, 'truthey (true) value accessed correctly');
equal(test.attr('my.count'), 0, 'falsey (0) value accessed correctly');
equal(test.attr('my.newCount'), 1, 'falsey (1) value accessed correctly');
});
});
|
import React, { Component, PropTypes } from 'react'
export default class Book extends Component {
// Validate the props flowing in
static propTypes = {
author: PropTypes.string.isRequired,
title: PropTypes.string.isRequired
};
constructor(props) {
super(props)
}
render() {
const { author, title } = this.props
return (
<div className="book">
<h2 className="title">
{ title }
</h2>
<p className="author">{ author }</p>
</div>
)
}
}
|
/**
A Plugin which provides fading Alert behaviors on a Node with compatible syntax
and markup from Twitter's Bootstrap project.
@module gallery-bootstrap-alert
**/
/**
A Plugin which provides fading Alert behaviors on a Node with compatible syntax
and markup from Twitter's Bootstrap project.
This makes it possible to have dynamic behaviors without incorporating any
JavaScript. However, it can be manually plugged into any node or node list.
var node = Y.one('.someNode');
// Duration is in seconds
node.plug( Y.Bootstrap.Alert, { duration : 5 } );
node.alert.close();
@class Bootstrap.Alert
**/
function AlertPlugin(config) {
AlertPlugin.superclass.constructor.apply(this, arguments);
this.config = Y.mix( config, this.defaults );
var selector = this.config.selector;
this._node = config.host;
/**
Fires when the close method is called, or when any close item has been
clicked
@event close
@preventable _dismissAlertFn
**/
this.publish('close', { preventable : true, defaultFn : this._dismissAlertFn });
this._node.delegate('click', function(e) { this.fire('close'); }, selector, this);
}
AlertPlugin.NAME = 'Bootstrap.Alert';
AlertPlugin.NS = 'alert';
Y.extend(AlertPlugin, Y.Plugin.Base, {
/**
@property defaults
@type Object
@default { duration : 0.5, selector : '.close', transition : true, destroy : true }
**/
defaults : {
duration : 0.5,
selector : '.close',
transition : true,
destroy : true
},
/**
@method close
@description Closes the alert target (the host) and removes the node.
**/
close: function() {
// Just a fake event facade.
this.fire('close', { currentTarget : this._node.one('.close') });
},
/**
@method _dismissAlertFn
@description Internal method to handle the transitions and fire the
closed event
@protected
**/
_dismissAlertFn: function(e) {
// This could be called from directly inside the plugin or just
// violating encapsulation entirely. I didn't want to go through
// instantiation overhead for what really will amount to a single and
// direct call.
var target = e.currentTarget,
alert,
config,
is_plugin,
destroy,
completed;
// If we have a node, use that. If not, find an ancestor that matches.
if ( Y.instanceOf( this, AlertPlugin ) ) {
alert = this._node;
config = this.config;
is_plugin = this;
} else {
alert = e.target.ancestor('div.' + ( target.getData('dismiss') || 'alert' ) );
config = AlertPlugin.prototype.defaults;
}
destroy = config.destroy ? true : false;
completed = function() {
if ( destroy ) { this.remove(); };
alert.fire('closed');
if ( is_plugin ) {
is_plugin.fire('closed');
}
};
if ( alert ) {
e.preventDefault();
if ( config.transition && alert.hasClass('fade') ) {
alert.transition(
{
duration : config.duration,
opacity : 0
},
completed
);
} else {
alert.hide();
completed.apply( alert );
}
}
}
});
Y.namespace('Bootstrap').Alert = AlertPlugin;
|
Meteor.startup(function () {
process.env.MAIL_URL = "smtp://postmaster%40sandboxfd8f5b7b227947e79f38766b0c7bbde7.mailgun.org:b04fd414757587940808adcf720cd7fe@smtp.mailgun.org:587";
});
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon([/*#__PURE__*/_jsx("path", {
d: "M8 8H6v9h11v-2H8z"
}, "0"), /*#__PURE__*/_jsx("path", {
d: "M22 3H10v10h12V3zm-2 8h-8V7h8v4zM4 12H2v9h11v-2H4z"
}, "1")], 'DynamicFeedSharp');
|
version https://git-lfs.github.com/spec/v1
oid sha256:95c9a9669619e3811ca38bc3b802e0647d91ffec7616c7f31a9d703050060bdd
size 27552
|
var searchData=
[
['phones_2epy',['phones.py',['../phones_8py.html',1,'']]],
['processor_2epy',['processor.py',['../processor_8py.html',1,'']]],
['processor_5ffactory_2epy',['processor_factory.py',['../processor__factory_8py.html',1,'']]]
];
|
var RestaurantView = React.createClass({
getInitialState: function() {
return {restaurant: null}
},
render: function() {
return (
<h4>Enter some text and hit <i>Go!</i> to do some sentiment analysis.</h4>
)
}
})
|
var _ = require('underscore');
var through = require('through');
var resolve = require( "resolve" );
var path = require( "path" );
module.exports = function( file, options ) {
var data = '';
return through( write, end );
function write( buf ) {
var _this = this;
var res = buf.toString( 'utf8' );
res = res.replace( /##asset_url\(\ *(['"])([^'"]*)\1\ *\)/g, function( wholeMatch, quote, assetSrcPath ) {
try {
assetSrcAbsPath = resolve.sync( assetSrcPath, { basedir : path.dirname( file ) } );
} catch( err ) {
return _this.emit( 'error', new Error( 'Could not resolve ##asset_url( "' + assetSrcPath + '" ) in file "' + file + '": ' + err ) );
}
var newFilePathRelativeToOutputDir = options.assetMap[ path.relative( options.appRootDir, assetSrcAbsPath ) ];
if( _.isUndefined( newFilePathRelativeToOutputDir ) ) {
throw new Error( 'There is no asset with the path "' + assetSrcPath + '". (If this is an image, has it been included in the package.json of its module with the "image" key?)' );
}
// urls are symmetric to paths
url = newFilePathRelativeToOutputDir; // ex: <packageId>/image/photo_<shasum>.png
if( options.outputDirUrl ) {
var baseUrl = options.outputDirUrl;
// outputDirUrl is normalized to always end is a forward slash, so drop the forward slash from the beginning of url
if( url[ 0 ] === path.sep ) url = url.slice( 1 );
url = baseUrl + url;
}
return url;
} );
this.queue( new Buffer( res, 'utf8' ) );
}
function end() {
this.queue( null );
}
};
|
/**
* Created by uzysjung on 2016. 10. 20..
*/
import React, { PropTypes } from 'react'
import Radium from 'radium'
const propTypes = {
children: PropTypes.node,
};
const style = {
minHeight: '100%',
backgroundColor: '#fafafa',
zIndex: 800
};
const pageWrapper = function ( { children } ) {
return (
<div style={style}>
{ children }
</div>
);
}
pageWrapper.propTypes = propTypes;
export default Radium(pageWrapper);
|
import { moduleFor, test } from 'ember-qunit';
moduleFor('adapter:github-member', 'Unit | Adapter | github member', {
needs: ['service:github-session']
});
test('it builds the organization\'s members URL correctly', function(assert) {
let adapter = this.subject();
const host = adapter.get('host');
const org = 'ember';
const query = {
org,
};
assert.equal(adapter.buildURL('github-member', null, null, 'query', query), `${host}/orgs/${org}/members`);
});
|
;
(function() {
window.require(["ace/snippets/mediawiki"], function(m) {
if (typeof module == "object" && typeof exports == "object" && module) {
module.exports = m;
}
});
})();
|
describe('device', function() {
var cookie = 'abc123',
host = 'localhost',
nock = require('nock'),
port = 8000;
it('sends a device status request', function(done) {
nock('https://' + host + ':' + port)
.post('/api/stat/device')
.reply(200, JSON.stringify({
"data" : [
{ "mac": "00:00", "name": "ap1" },
{ "mac": "00:01", "name": "ap2" }
],
"meta" : { "rc" : "ok"}
}));
var device = require('../../lib/status/device');
device(host, port, cookie)
.done(function(data) {
expect(data.length).toEqual(2);
expect(data[0].name).toBe("ap1");
done();
});
});
it('handles case where server returns unexpected value', function(done) {
nock('https://' + host + ':' + port)
.post('/api/stat/device')
.reply(500);
var device = require('../../lib/status/device');
device(host, port, cookie)
.done(function() {}, function(result) {
expect(result).toContain('error');
done();
});
});
});
|
import React from 'react';
import ReactDOM from 'react-dom';
import ParallaxContainer from './ParallaxContainer';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(
<ParallaxContainer><span /></ParallaxContainer>,
div
);
});
|
/**
* Dispatch command request
*
* 1. load modules
* 2. do some initialize stuffe
* 3. process command
*/
require("coffee-script");
var Module = require("../index");
global.Hub = require("hubjs")();
var SIGNALLIST = {
"SIG_START_SERVER": function(config) {
// Launch server
var localServer = require("./localServer");
localServer.create(config).listen(config.port, function() {
console.log("FED server listening on port " + config.port);
});
}
};
var msgHandler = function(msg) {
if(SIGNALLIST[msg.signal]) {
// Load modules
Module.init(msg.config);
Hub.emit("modules.load");
SIGNALLIST[msg.signal](msg.config);
} else {
// Signal not found
}
};
process.on("message", msgHandler);
exports.send = msgHandler;
|
// Generators example
// Read about generator functions and generators:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*
'use strict';
var log = require('./log');
var generatorFunction = function* (input1) {
log('Generator block #1');
var input2 = yield 'string from generator';
log('Generator block #2');
var input3 = yield ++input2;
log('Generator block #3');
return ++input3;
};
// Not a generator, just function
function delay (time) {
log('I\'m', time, 'ms sync delay...');
var end_time = (new Date()).valueOf() + time;
var now = new Date();
while (now.valueOf() < end_time) {
now = new Date();
}
}
// control code
try {
var generator = generatorFunction(0); // --> input1
log('Generator initialized', generator, '\n');
var r1 = generator.next();
log('\treturned', r1, '\n');
delay(2000);
var r2 = generator.next(1); // --> input2
// generator.throw('some error');
log('\treturned', r2, '\n');
var r3 = generator.next(2); // --> input3
log('\treturned', r3, '\n');
var r4 = generator.next();
log('\treturned', r4, '\n');
} catch (e) {
log('Catched! ' + e);
}
|
'use strict';
var createReduced = require('dbjs-reduce/create');
module.exports = function (mainDb) {
return createReduced(mainDb, 'statsBase');
};
|
/**
* Created by Liza on 13.08.2015.
*/
var pixi = require("pixi.js")
var spine = require('pixi-spine')
module.exports = function ($rootScope, $q) {
var promises = [];
function load() {
var loader = new pixi.loaders.Loader();
loader.add('back', 'assets/back2.png');
loader.add('wagon', 'assets/wagon_shadow15.png');
loader.add('loco', 'assets/loco_shadow15.png');
//mods here
loader.add('particle', 'assets/particle.png');
loader.add('delorean', 'assets/delorean2.png');
loader.add('river2', 'assets/river/river2.png');;
loader.add('riverbig1', 'assets/river/bigriver1.png');
loader.add('riverbig2', 'assets/river/bigriver2.png');
loader.add('riverbig3', 'assets/river/bigriver3.png');
loader.add('bridgeSE_top', 'assets/river/bridgeSE_top.png');
loader.add('bridgeSE_base', 'assets/river/bridgeSE_base.png');
loader.add('bridgeNE_top', 'assets/river/bridgeNE_top.png');
loader.add('bridgeNE_base', 'assets/river/bridgeNE_base.png');
loader.add('bridgeE_top', 'assets/river/bridgeE_top.png');
loader.add('bridgeE_base', 'assets/river/bridgeE_base.png');
loader.add('grav', 'assets/grav.png');
//obstacles
loader.add('shlagbaum', 'assets/spine/shlagbaum.json');
loader.add('horn', 'assets/spine/horn.json');
loader.add('alertbar', 'assets/spine/alertbar.json');
loader.add('sprites', 'assets/sprites.json');
loader.add('shapes', 'assets/shapes.json');
loader.load(function (loader, res) {
function removePngNames(obj) {
var o = {};
for (var key in obj)
o[key.replace(/\.png$/i, "")] = obj[key];
return o;
}
if (!res.sprites.data) {
//try again!!!
console.log("failed to load resources, trying again");
load();
return;
}
res.sprites.data.frames = removePngNames(res.sprites.data.frames);
res.sprites.textures = removePngNames(res.sprites.textures);
service.list = res;
for (var i = 0; i < promises.length; i++)
promises[i].resolve(res);
});
}
load();
var theme = document.getElementById("theme");
theme.loop = true;
theme.volume = 0.5;
var service = {
load: function() {
var q = $q.defer();
if (this.list) {
q.resolve(this.list);
} else promises.push(q);
return q.promise;
},
theme: theme
};
return service;
}
|
const chai = require('chai');
const assert = chai.assert;
const board = require('../lib/board/index');
const clearRows = require('../lib/board/index').clearRows;
const checkBoard = require('../lib/board/index').checkBoard;
const gameStatus = require('../lib/board/index').gameStatus;
describe('board', function () {
it('should be an array', function () {
assert(Array.isArray(board));
});
it('should be an array of arrays', function () {
assert(Array.isArray(board[0]));
});
it('should be an array with twenty arrays', function () {
assert.equal(board.length, 20);
});
it('should be an array with twenty arrays and 10 0s in each array', function () {
assert.equal(board[0].length, 10);
});
var board = [ [0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[1,1,1,1,1,1,1,1,1,1]
]
it('should be able to clear filled row', function () {
clearRows(board);
assert.equal(typeof(board[19]), typeof([0,0,0,0,0,0,0,0,0,0]));
// assert.deepEqual(board[19], [0,0,0,0,0,0,0,0,0,0]);
});
var board2 = [[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[1,1,1,1,1,1,1,1,1,1],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[1,1,1,1,1,1,1,1,1,1]
]
it('should be able to clear multiple filled row', function () {
clearRows(board);
assert.equal(typeof(board[15]), typeof([0,0,0,0,0,0,0,0,0,0]));
// assert.deepEqual(board[15], [0,0,0,0,0,0,0,0,0,0]);
});
var board3 = [[1,0,0,0,0,0,0,0,0,0],
[1,0,0,0,0,0,0,0,0,0],
[1,0,0,0,0,0,0,0,0,0],
[1,0,0,0,0,0,0,0,0,0],
[1,0,0,0,0,0,0,0,0,0],
[1,0,0,0,0,0,0,0,0,0],
[1,0,0,0,0,0,0,0,0,0],
[1,0,0,0,0,0,0,0,0,0],
[1,0,0,0,0,0,0,0,0,0],
[1,0,0,0,0,0,0,0,0,0],
[1,0,0,0,0,0,0,0,0,0],
[1,0,0,0,0,0,0,0,0,0],
[1,0,0,0,0,0,0,0,0,0],
[1,0,0,0,0,0,0,0,0,0],
[1,0,0,0,0,0,0,0,0,0],
[1,1,1,1,1,0,1,1,1,1],
[1,0,0,0,0,0,0,0,0,0],
[1,0,0,0,0,0,0,0,0,0],
[1,0,0,0,0,0,0,0,0,0],
[1,1,1,1,1,0,1,1,1,0]
]
xit('should end game if column fills up', function () {
result = gameStatus(board);
assert(result);
});
});
|
'use strict';
angular
.module('msMealPlannerApp')
.directive('recipeTable', recipeTableDirective);
recipeTableDirective.$inject = ['Recipe', 'growl'];
function recipeTableDirective(Recipe, growl) {
return {
templateUrl: 'app/recipe/recipeTable/recipeTable.html',
restrict: 'EA',
link: function (scope) {
function removeValue (array, id) {
return _.reject(array, function(item) {
console.info('Deleted recipe:', id);
return item._id === id;
});
}
function fetchData (){
return Recipe.getList()
.then(function(data){
scope.recipeCollection = data;
});
}
scope.deleteRecipe = function(recipe) {
if(window.confirm('Are you sure you want to remove this recipe?')){
recipe.remove().then(function(){
scope.recipeCollection = removeValue(scope.recipeCollection, recipe._id);
growl.success('Successfully deleted');
}, function() {
growl.error('Unable to delete. Try again later..');
});
}
};
var init = function(){
scope.recipeCollection = [];
fetchData();
};
init();
}
};
}
|
"use strict";
describe("separateDialCode:", function() {
beforeEach(function() {
intlSetup(true);
input = $("<input>");
});
afterEach(function() {
input.intlTelInput("destroy");
input = null;
});
// we test with "gb" because the ntl number is different to the intl number (aside from the dial code)
describe("init plugin with initialCountry=gb", function() {
beforeEach(function() {
input.intlTelInput({
separateDialCode: true,
initialCountry: "gb"
});
});
it("sets the classes properly", function() {
expect(getParentElement()).toHaveClass("separate-dial-code iti-sdc-3");
});
it("displays the dial code next to the selected flag", function() {
expect(getSelectedFlagContainer().find(".selected-dial-code").text()).toEqual("+44");
});
it("formats the placeholder correctly", function() {
// international format minus the dial code
expect(input.attr("placeholder")).toEqual("7400 123456");
});
describe("calling setNumber to a valid intl number", function() {
beforeEach(function() {
input.intlTelInput("setNumber", "+447400123456", intlTelInputUtils.numberFormat.INTERNATIONAL);
});
it("formats the number correctly", function() {
// international format minus the dial code
expect(getInputVal()).toEqual("7400 123456");
});
it("calling getNumber returns the full intl number", function() {
expect(input.intlTelInput("getNumber")).toEqual("+447400123456");
});
});
});
// we test with "ca" because we had some bugs with area codes
describe("init plugin with initialCountry=ca", function() {
beforeEach(function() {
input.intlTelInput({
separateDialCode: true,
initialCountry: "ca"
});
});
it("sets the placeholder correctly", function() {
// used to be '234-5678'
expect(input.attr("placeholder")).toEqual("204-234-5678");
});
it("calling setNumber will set the number correctly", function() {
input.intlTelInput("setNumber", "+15194971234", intlTelInputUtils.numberFormat.INTERNATIONAL);
// used to be '497-1234'
expect(getInputVal()).toEqual("519-497-1234");
});
});
// we test with "as" because we had a bug
describe("init plugin with initialCountry=as", function() {
beforeEach(function() {
input.intlTelInput({
separateDialCode: true,
initialCountry: "as"
});
});
it("sets the placeholder correctly", function() {
// used to be '4-733-1234'
expect(input.attr("placeholder")).toEqual("733-1234");
});
it("calling setNumber will set the number correctly", function() {
input.intlTelInput("setNumber", "+16847331234", intlTelInputUtils.numberFormat.INTERNATIONAL);
// used to be '4-733-1234'
expect(getInputVal()).toEqual("733-1234");
});
});
});
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4zM11 20v-5.5H9L13 7v5.5h2L11 20z" />
, 'BatteryChargingFull');
|
"use strict";
var gulp = require('gulp');
var connect = require('gulp-connect'); //Runs a local dev server
var open = require('gulp-open'); //Open a URL in a web browser
var browserify = require('browserify'); // Bundles JS
var reactify = require('reactify'); // Transforms React JSX to JS
var source = require('vinyl-source-stream'); // Use conventional text streams with Gulp
var concat = require('gulp-concat'); //Concatenates files
var lint = require('gulp-eslint'); //Lint JS files, including JSX
var config = {
port: 9005,
devBaseUrl: 'http://localhost',
paths: {
html: './src/*.html',
js: './src/**/*.js',
images: './src/images/*',
css: [
'node_modules/bootstrap/dist/css/bootstrap.min.css',
'node_modules/bootstrap/dist/css/bootstrap-theme.min.css'
],
dist: './dist',
mainJs: './src/main.js'
}
}
//Start a local development server
gulp.task('connect', function() {
connect.server({
root: ['dist'],
port: config.port,
base: config.devBaseUrl,
livereload: true
});
});
gulp.task('open', ['connect'], function() {
gulp.src('dist/index.html')
.pipe(open({ uri: config.devBaseUrl + ':' + config.port + '/'}));
});
gulp.task('html', function() {
gulp.src(config.paths.html)
.pipe(gulp.dest(config.paths.dist))
.pipe(connect.reload());
});
gulp.task('js', function() {
browserify(config.paths.mainJs)
.transform(reactify)
.bundle()
.on('error', console.error.bind(console))
.pipe(source('bundle.js'))
.pipe(gulp.dest(config.paths.dist + '/scripts'))
.pipe(connect.reload());
});
gulp.task('css', function() {
gulp.src(config.paths.css)
.pipe(concat('bundle.css'))
.pipe(gulp.dest(config.paths.dist + '/css'));
});
// Migrates images to dist folder
// Note that I could even optimize my images here
gulp.task('images', function () {
gulp.src(config.paths.images)
.pipe(gulp.dest(config.paths.dist + '/images'))
.pipe(connect.reload());
//publish favicon
gulp.src('./src/favicon.ico')
.pipe(gulp.dest(config.paths.dist));
});
gulp.task('lint', function() {
return gulp.src(config.paths.js)
.pipe(lint({config: 'eslint.config.json'}))
.pipe(lint.format());
});
gulp.task('watch', function() {
gulp.watch(config.paths.html, ['html']);
gulp.watch(config.paths.js, ['js', 'lint']);
});
gulp.task('default', ['html', 'js', 'css', 'images', 'lint', 'open', 'watch']);
|
module.exports = function(grunt) {
grunt.initConfig({
concat: {
dist: {
src: [
'src/toe.js',
'src/gestures/*.js'
],
dest: 'dist/toe.js'
}
},
jshint: {
options: {
curly: true,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
eqnull: true,
browser: true,
globals: {
jQuery: true
}
},
all: ['dist/toe.js', 'src/toe.js', 'src/gestures/*.js']
},
uglify: {
options: {
preserveComments: 'some'
},
jquery: {
src: ['dist/toe.js'],
dest: 'dist/toe.min.js'
},
zepto: {
src: ['dist/toe.zepto.js'],
dest: 'dist/toe.zepto.min.js'
}
},
replace: {
zepto: {
src: ['dist/toe.js'],
dest: 'dist/toe.zepto.js',
replacements: [{
from: 'jQuery',
to: 'Zepto'
}]
}
},
jsdoc : {
dist : {
src: ['src/toe.js', 'src/gestures/*.js'],
options: {
destination: 'dist/doc'
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-text-replace');
grunt.loadNpmTasks('grunt-jsdoc');
grunt.registerTask('default', ['concat', 'jshint', 'replace', 'uglify']);
};
|
var BaseGateway = require('42-cent-base').BaseGateway;
var P = require('bluebird');
var util = require('util');
var instance;
var methods = Object.keys(BaseGateway.prototype);
function MockGateway (options) {
this.stubs = [];
BaseGateway.call(this, options);
}
util.inherits(MockGateway, BaseGateway);
function factory (options) {
//forcing singleton
if (!instance) {
instance = new MockGateway(options);
}
return instance;
}
methods.forEach(function (meth) {
MockGateway.prototype[meth] = function () {
var args = [].slice.call(arguments);
var stub = this.stubs.filter(function (st) {
return meth === st.method;
});
if (stub.length === 0) {
throw new Error('Unexpected call of gateway ' + meth + ' with ' + JSON.stringify((args)));
}
stub = stub[0];
if (!stub.resolveValue && !stub.rejectValue) {
throw new Error('Unhandled call to the stub of ' + stub.method);
}
stub.calls.push(args);
return stub.resolveValue ? P.resolve(stub.resolveValue) : P.reject(stub.rejectValue);
}
});
exports.factory = factory;
exports.clean = function clean () {
factory().stubs = [];
};
function Stub (method) {
this.calls = [];
this.method = method;
}
Stub.prototype.rejectWith = function rejectWith (value) {
this.rejectValue = value;
return this;
};
Stub.prototype.resolveWith = function resolveWith (value) {
this.resolveValue = value;
return this;
};
exports.when = function when (method) {
var stub;
var matching;
if (method.indexOf(method) === -1) {
throw new Error(method, ' is not part of gateway implementation');
}
matching = factory().stubs.filter(function (st) {
return st.method === method;
});
while (matching.length > 0) {
factory().stubs.splice(factory().stubs.indexOf(matching.pop()), 1);
}
stub = new Stub(method);
factory().stubs.push(stub);
return stub;
};
|
define(['jquery', 'clipboard', 'views/dialog'], function($, Clipboard, DialogView) {
'use strict';
return Backbone.View.extend({
initialize: function(options) {
var _this = this;
$.post('/link/add.php', {
link: options.url
}, function(shortlink) {
_this.buildDialog(options.caption, shortlink);
});
},
dialogContent: function(data) {
return _.template($('#link-dialog').html())(data);
},
buildDialog: function(caption, shortlink) {
var dialog = new DialogView(),
$body = $(this.dialogContent({ href: shortlink }));
var $href = $body.find('.href');
this.activateClipboard($href);
dialog
.setCaption(caption)
.setContent($body)
.open();
},
activateClipboard: function($href) {
var clipboard = new Clipboard($href[0]);
clipboard.on('success', function() {
$href.addClass('used').text($href.data('copied'));
});
}
});
});
|
'use strict';
import mongoose from 'mongoose';
/**
* Mongoose schema of Konko core.
*
*/
const coreSchema = new mongoose.Schema({
basic: {
title: { type: String, unique: true, required: '{PATH} is required', default: 'Konko' },
description: { type: String, unique: true, default: 'MEAN stack based forum.' },
keywords: { type: String, unique: true, default: 'Konko,Konko Project' },
logo: { type: String, default: 'styles/core/images/brand.png' },
since: { type: Date, default: Date.now },
public: { type: Boolean, default: true },
},
admin: {
email: { type: String, unique: true, lowercase: true },
},
global: {
installed: { type: Boolean, default: true },
language: { type: String, lowercase: true, default: 'en-us' },
navbar: {
navs: [
{
name: { type: String, required: '{PATH} is required' },
url: { type: String, required: '{PATH} is required' },
order: { type: Number, min: 0 },
}
],
},
styles: [
{
name: { type: String, unique: true, required: '{PATH} is required' },
root: { type: String, unique: true, required: '{PATH} is required' },
},
],
},
mailer: {
method: { type: String, enum: ['sendmail', 'smtp', 'ses'], default: 'sendmail' },
from: { type: String, unique: true, lowercase: true, default: 'noreply@konko.project' },
host: { type: String, unique: true },
secure: { type: Boolean, default: true },
port: { type: Number, default: 465 },
user: { type: String, unique: true },
password: { type: String, unique: true },
ses_keyId: { type: String, unique: true },
ses_secret: { type: String, unique: true },
},
registration: {
public: { type: Boolean, default: true },
message: { type: String, default: 'Registration is closed by admin.' },
email: {
verification: { type: Boolean, default: false },
verificationSubject: { type: String, default: 'Welcome!' },
ttl: { type: Number, default: 12 * 60 },
welcome: { type: Boolean, default: false },
welcomeMessage: { type: String },
},
password: {
resetEmailSubject: { type: String, default: 'Reset your password' },
regex: { type: String, default: '(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\\!\\@\\#\\$\\%\\^\\&\\*\\_\\ ]).{8,32}' },
title: { type: String, default: 'Must contains 8 to 32 characters, including at least 1 digit, 1 lower case letter, 1 upper case letter, and 1 of the following special characters. (!, @, #, $, %, ^, &, *, _, )' },
min: { type: Number, default: 8 },
max: { type: Number, default: 32 },
capital: { type: Boolean, default: true },
lower: { type: Boolean, default: true },
digit: { type: Boolean, default: true },
special: { type: Boolean, default: true },
},
blacklist: [{ type: String, lowercase: true }],
},
profile: {
username: {
min: { type: Number, min: 1, default: 3 },
max: { type: Number, min: 1, default: 12 },
forbidden: [{ type: String }],
},
avatar: {
upload: { type: Boolean, default: true },
limit: { type: Number, default: 2046 },
},
banner: {
upload: { type: Boolean, default: true },
limit: { type: Number, default: 4096 },
},
tagline: {
min: { type: Number, min: 0, default: 0 },
max: { type: Number, min: 1, default: 20 },
},
},
panel: {
panel: {
name: {
min: { type: Number, min: 0, default: 1 },
max: { type: Number, min: 0, default: 60 },
},
description: {
min: { type: Number, min: 0, default: 0 },
max: { type: Number, min: 0, default: 200 },
},
},
category: {
name: {
min: { type: Number, min: 0, default: 1 },
max: { type: Number, min: 0, default: 60 },
},
},
},
post: {
topic: {
title: {
min: { type: Number, min: 0, default: 5 },
max: { type: Number, min: 0, default: 120 },
},
content: {
min: { type: Number, min: 0, default: 10 },
max: { type: Number, min: 0, default: 10000 },
},
lastReplyLength: { type: Number, min: 0, default: 3 },
},
comment: {
content: {
min: { type: Number, min: 0, default: 10 },
max: { type: Number, min: 0, default: 10000 },
},
short: {
max: { type: Number, min: 0, default: 15 },
},
},
},
});
mongoose.model('Core', coreSchema);
|
import _curry3 from './internal/_curry3';
import equals from './equals';
/**
* Reports whether two objects have the same value, in [`R.equals`](#equals)
* terms, for the specified property. Useful as a curried predicate.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Object
* @sig k -> {k: v} -> {k: v} -> Boolean
* @param {String} prop The name of the property to compare
* @param {Object} obj1
* @param {Object} obj2
* @return {Boolean}
*
* @example
*
* var o1 = { a: 1, b: 2, c: 3, d: 4 };
* var o2 = { a: 10, b: 20, c: 3, d: 40 };
* R.eqProps('a', o1, o2); //=> false
* R.eqProps('c', o1, o2); //=> true
*/
var eqProps = _curry3(function eqProps(prop, obj1, obj2) {
return equals(obj1[prop], obj2[prop]);
});
export default eqProps;
|
import { useTimezoneTime } from './useTimezoneTime';
export const useUTCClock = (utcOffset) => {
const time = useTimezoneTime(utcOffset, 10000);
return `${time} (UTC ${utcOffset})`;
};
|
import { expect } from 'chai';
import validator from '../../lib';
describe('Credit card validator', () => {
const validCardNumber = '4111111111111111';
const rules = {
cardNumber: ['creditCard']
};
it('should success', () => {
const result = validator.validate(rules, {cardNumber: validCardNumber});
const err = result.messages;
expect(result.success).to.equal(true);
expect(err).to.not.have.property('cardNumber');
});
it('should fail', () => {
const result = validator.validate(rules, {cardNumber: '4111111111111112'});
const err = result.messages;
expect(result.success).to.equal(false);
expect(err).to.have.property('cardNumber');
expect(err.cardNumber.creditCard).to.equal('Card Number is not a valid credit card number.');
});
});
|
$(function () {
$('#report-filter-contradicted').change(function () {
if (this.checked) {
$('.flag-contradicted').addClass('hidden')
} else {
$('.flag-contradicted').removeClass('hidden')
}
})
})
|
// The raw data to observe
var stats = [
{ label: 'A', value: 100 },
{ label: 'B', value: 100 },
{ label: 'C', value: 100 },
{ label: 'D', value: 100 },
{ label: 'E', value: 100 },
{ label: 'F', value: 100 }
]
// A resusable polygon graph component
Vue.component('polygraph', {
props: ['stats'],
template: '#polygraph-template',
computed: {
// a computed property for the polygon's points
points: function () {
var total = this.stats.length
return this.stats.map(function (stat, i) {
var point = valueToPoint(stat.value, i, total)
return point.x + ',' + point.y
}).join(' ')
}
},
components: {
// a sub component for the labels
'axis-label': {
props: {
stat: Object,
index: Number,
total: Number
},
template: '#axis-label-template',
computed: {
point: function () {
return valueToPoint(
+this.stat.value + 10,
this.index,
this.total
)
}
}
}
}
})
// math helper...
function valueToPoint (value, index, total) {
var x = 0
var y = -value * 0.8
var angle = Math.PI * 2 / total * index
var cos = Math.cos(angle)
var sin = Math.sin(angle)
var tx = x * cos - y * sin + 100
var ty = x * sin + y * cos + 100
return {
x: tx,
y: ty
}
}
// bootstrap the demo
new Vue({
el: '#demo',
data: {
newLabel: '',
stats: stats
},
methods: {
add: function (e) {
e.preventDefault()
if (!this.newLabel) return
this.stats.push({
label: this.newLabel,
value: 100
})
this.newLabel = ''
},
remove: function (stat) {
if (this.stats.length > 3) {
this.stats.splice(this.stats.indexOf(stat), 1)
} else {
alert('Can\'t delete more!')
}
}
}
})
|
(function () {
'use strict';
/**
* Izenda query service which provides filter specific queries
* this is singleton
*/
angular
.module('izendaFilters')
.factory('$izendaFiltersQuery', [
'$izendaRsQuery',
'$log',
function ($izendaRsQuery, $log) {
var _ = angular.element;
// PUBLIC API
return {
loadFiltersData: loadFiltersData,
loadAllFiltersData: loadAllFiltersData,
setFiltersData: setFiltersData,
refreshCascadingFilters: refreshCascadingFilters
};
function loadFiltersData() {
return $izendaRsQuery.query('getdashboardfiltersdata', [], {
dataType: 'json'
});
}
function loadAllFiltersData() {
return $izendaRsQuery.query('getallfiltersdata', [], {
dataType: 'json'
});
}
function setFiltersData(dashboardFilters) {
return $izendaRsQuery.query('setfiltersdata2', [JSON.stringify(dashboardFilters)], {
dataType: 'json'
});
}
function refreshCascadingFilters(dashboardFilters) {
return $izendaRsQuery.query('refreshcascadingfilters2', [JSON.stringify(dashboardFilters)], {
dataType: 'json'
});
}
/**
* Prepare filter to send (filter object changes)
*/
function convertFilterData(filter) {
switch (filter.ControlType) {
case 1:
case 11:
case 100:
case 3:
case 4:
case 6:
case 7:
case 9:
filter.Values = [filter.Value];
}
}
}]);
})();
|
import _extends from '@babel/runtime/helpers/esm/extends';
import { RuleList } from 'jss';
var at = '@global';
var atPrefix = '@global ';
var GlobalContainerRule =
/*#__PURE__*/
function () {
function GlobalContainerRule(key, styles, options) {
this.type = 'global';
this.at = at;
this.rules = void 0;
this.options = void 0;
this.key = void 0;
this.isProcessed = false;
this.key = key;
this.options = options;
this.rules = new RuleList(_extends({}, options, {
parent: this
}));
for (var selector in styles) {
this.rules.add(selector, styles[selector]);
}
this.rules.process();
}
/**
* Get a rule.
*/
var _proto = GlobalContainerRule.prototype;
_proto.getRule = function getRule(name) {
return this.rules.get(name);
}
/**
* Create and register rule, run plugins.
*/
;
_proto.addRule = function addRule(name, style, options) {
var rule = this.rules.add(name, style, options);
if (rule) this.options.jss.plugins.onProcessRule(rule);
return rule;
}
/**
* Get index of a rule.
*/
;
_proto.indexOf = function indexOf(rule) {
return this.rules.indexOf(rule);
}
/**
* Generates a CSS string.
*/
;
_proto.toString = function toString() {
return this.rules.toString();
};
return GlobalContainerRule;
}();
var GlobalPrefixedRule =
/*#__PURE__*/
function () {
function GlobalPrefixedRule(key, style, options) {
this.type = 'global';
this.at = at;
this.options = void 0;
this.rule = void 0;
this.isProcessed = false;
this.key = void 0;
this.key = key;
this.options = options;
var selector = key.substr(atPrefix.length);
this.rule = options.jss.createRule(selector, style, _extends({}, options, {
parent: this
}));
}
var _proto2 = GlobalPrefixedRule.prototype;
_proto2.toString = function toString(options) {
return this.rule ? this.rule.toString(options) : '';
};
return GlobalPrefixedRule;
}();
var separatorRegExp = /\s*,\s*/g;
function addScope(selector, scope) {
var parts = selector.split(separatorRegExp);
var scoped = '';
for (var i = 0; i < parts.length; i++) {
scoped += scope + " " + parts[i].trim();
if (parts[i + 1]) scoped += ', ';
}
return scoped;
}
function handleNestedGlobalContainerRule(rule, sheet) {
var options = rule.options,
style = rule.style;
var rules = style ? style[at] : null;
if (!rules) return;
for (var name in rules) {
sheet.addRule(name, rules[name], _extends({}, options, {
selector: addScope(name, rule.selector)
}));
}
delete style[at];
}
function handlePrefixedGlobalRule(rule, sheet) {
var options = rule.options,
style = rule.style;
for (var prop in style) {
if (prop[0] !== '@' || prop.substr(0, at.length) !== at) continue;
var selector = addScope(prop.substr(at.length), rule.selector);
sheet.addRule(selector, style[prop], _extends({}, options, {
selector: selector
}));
delete style[prop];
}
}
/**
* Convert nested rules to separate, remove them from original styles.
*
* @param {Rule} rule
* @api public
*/
function jssGlobal() {
function onCreateRule(name, styles, options) {
if (!name) return null;
if (name === at) {
return new GlobalContainerRule(name, styles, options);
}
if (name[0] === '@' && name.substr(0, atPrefix.length) === atPrefix) {
return new GlobalPrefixedRule(name, styles, options);
}
var parent = options.parent;
if (parent) {
if (parent.type === 'global' || parent.options.parent && parent.options.parent.type === 'global') {
options.scoped = false;
}
}
if (options.scoped === false) {
options.selector = name;
}
return null;
}
function onProcessRule(rule, sheet) {
if (rule.type !== 'style' || !sheet) return;
handleNestedGlobalContainerRule(rule, sheet);
handlePrefixedGlobalRule(rule, sheet);
}
return {
onCreateRule: onCreateRule,
onProcessRule: onProcessRule
};
}
export default jssGlobal;
|
// DATA_TEMPLATE: empty_table
oTest.fnStart("fnDrawCallback");
/* Fairly boring function compared to the others! */
$(document).ready(function () {
/* Check the default */
var oTable = $('#example').dataTable({
"sAjaxSource": "../../../examples/ajax/sources/arrays.txt",
"bDeferRender": true
});
var oSettings = oTable.fnSettings();
var mPass, bInit;
oTest.fnWaitTest(
"Default should be null",
null,
function () {
return oSettings.fnDrawCallback == null;
}
);
oTest.fnWaitTest(
"One argument passed",
function () {
oSession.fnRestore();
mPass = -1;
bInit = false;
$('#example').dataTable({
"sAjaxSource": "../../../examples/ajax/sources/arrays.txt",
"bDeferRender": true,
"fnDrawCallback": function () {
mPass = arguments.length;
},
"fnInitComplete": function () {
bInit = true;
}
});
},
function () {
return mPass == 1 && bInit;
}
);
oTest.fnWaitTest(
"That one argument is the settings object",
function () {
oSession.fnRestore();
bInit = false;
oTable = $('#example').dataTable({
"sAjaxSource": "../../../examples/ajax/sources/arrays.txt",
"bDeferRender": true,
"fnDrawCallback": function (oSettings) {
mPass = oSettings;
},
"fnInitComplete": function () {
bInit = true;
}
});
},
function () {
return oTable.fnSettings() == mPass && bInit;
}
);
/* The draw callback is called once for the init and then when the data is added */
oTest.fnWaitTest(
"fnRowCallback called once on first draw",
function () {
oSession.fnRestore();
mPass = 0;
bInit = false;
$('#example').dataTable({
"sAjaxSource": "../../../examples/ajax/sources/arrays.txt",
"bDeferRender": true,
"fnDrawCallback": function () {
mPass++;
},
"fnInitComplete": function () {
bInit = true;
}
});
},
function () {
return mPass == 2 && bInit;
}
);
oTest.fnWaitTest(
"fnRowCallback called once on each draw there after as well",
function () {
$('#example_next').click();
$('#example_next').click();
$('#example_next').click();
},
function () {
return mPass == 5;
}
);
oTest.fnComplete();
});
|
// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require jquery
//= require jquery_ujs
//= require jquery-migrate
//= require jquery-chosen
//= require bootstrap-dropdown
//= require bootstrap-typeahead
//= require_tree .
|
/*!
* tmplPlus.js: for jQuery Templates Plugin 1.0.0pre
* Additional templating features or support for more advanced/less common scenarios.
* Requires jquery.tmpl.js
* http://github.com/jquery/jquery-tmpl
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*/
(function (jQuery) {
var oldComplete = jQuery.tmpl.complete, oldManip = jQuery.fn.domManip;
// Override jQuery.tmpl.complete in order to provide rendered event.
jQuery.tmpl.complete = function(tmplItems) {
var tmplItem;
oldComplete(tmplItems);
for (tmplItem in tmplItems) {
tmplItem = tmplItems[tmplItem];
if (tmplItem.addedTmplItems && jQuery.inArray(tmplItem, tmplItem.addedTmplItems) === -1) {
tmplItem.addedTmplItems.push(tmplItem);
}
}
for (tmplItem in tmplItems) {
tmplItem = tmplItems[tmplItem];
// Raise rendered event
if (tmplItem.rendered) {
tmplItem.rendered(tmplItem);
}
}
};
jQuery.extend({
tmplCmd: function(command, data, tmplItems) {
var retTmplItems = [], before;
function find(data, tmplItems) {
var found = [], tmplItem, ti, tl = tmplItems.length, dataItem, di = 0, dl = data.length;
for (; di < dl;) {
dataItem = data[di++];
for (ti = 0; ti < tl;) {
tmplItem = tmplItems[ti++];
if (tmplItem.data === dataItem) {
found.push(tmplItem);
}
}
}
return found;
}
data = jQuery.isArray(data) ? data : [ data ];
switch (command) {
case "find":
return find(data, tmplItems);
case "replace":
data.reverse();
}
jQuery.each(tmplItems ? find(data, tmplItems) : data, function(i, tmplItem) {
coll = tmplItem.nodes;
switch (command) {
case "update":
tmplItem.update();
break;
case "remove":
jQuery(coll).remove();
if (tmplItems) {
tmplItems.splice(jQuery.inArray(tmplItem, tmplItems), 1);
}
break;
case "replace":
before = before ?
jQuery(coll).insertBefore(before)[0] :
jQuery(coll).appendTo(coll[0].parentNode)[0];
retTmplItems.unshift(tmplItem);
}
});
return retTmplItems;
}
});
jQuery.fn.extend({
domManip: function (args, table, callback, options) {
var data = args[1], tmpl = args[0], dmArgs;
if (args.length >= 2 && typeof data === "object" && !data.nodeType && !(data instanceof jQuery)) {
// args[1] is data, for a template.
dmArgs = jQuery.makeArray(arguments);
// Eval template to obtain fragment to clone and insert
dmArgs[0] = [ jQuery.tmpl(jQuery.template(tmpl), data, args[2], args[3]) ];
dmArgs[2] = function(fragClone) {
// Handler called by oldManip when rendered template has been inserted into DOM.
jQuery.tmpl.afterManip(this, fragClone, callback);
};
return oldManip.apply(this, dmArgs);
}
return oldManip.apply(this, arguments);
}
});
})(jQuery);
|
var _ = require('lodash');
var expect = require('chai').expect;
var monoxide = require('..');
var testSetup = require('./setup');
describe('monoxide indexes', function() {
before(testSetup.init);
after(testSetup.teardown);
var userIndexes;
before('get user indexes', function(finish) {
monoxide.models.users.getIndexes(function(err, res) {
if (err) return finish(err);
userIndexes = res;
finish();
});
});
it('should retrieve the indexes of a Mongo model', function(finish) {
monoxide.models.users.getIndexes(function(err, res) {
if (err) return finish(err);
expect(res).to.be.an('array');
expect(res).to.have.length(2);
expect(res[0]).to.have.property('name', '_id_');
expect(res[0]).to.have.property('ns');
expect(res[0].ns).to.match(/\.users$/);
finish();
});
});
it('should retrieve the ideal indexes of a declared schema', function(finish) {
monoxide.models.users.getSchemaIndexes(function(err, res) {
if (err) return finish(err);
expect(res).to.be.an('array');
expect(res).to.have.length(2);
expect(res[0]).to.have.property('name', '_id_');
finish();
});
});
it('should create multi-field indexes', function(finish) {
this.timeout(10 * 1000);
monoxide.models.widgets.index(['status', 'color'], function(err) {
if (err) return finish(err);
monoxide.models.widgets.checkIndexes([{key: {status: 1, color: 1}}], function(err, res) {
if (err) return finish(err);
finish();
});
});
});
it('should check the status of indexes when given an omitted index', function(finish) {
monoxide.models.users.checkIndexes([ // Glue a fake index to the list we are checking against
{key: {role: 1}, name: 'role', ns: userIndexes[0].ns.replace('_id', 'role')},
...userIndexes
], function(err, res) {
if (err) return finish(err);
res = _.sortBy(res, 'name');
expect(res[0]).to.have.property('name', '_id_');
expect(res[0]).to.have.property('status', 'ok');
expect(res[1]).to.have.property('name', 'role');
expect(res[1]).to.have.property('status', 'ok');
finish();
});
});
});
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2018 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* [description]
*
* @function Phaser.Utils.Object.HasValue
* @since 3.0.0
*
* @param {object} source - [description]
* @param {string} key - [description]
*
* @return {boolean} [description]
*/
var HasValue = function (source, key)
{
return (source.hasOwnProperty(key));
};
module.exports = HasValue;
|
/*global google */
/*jshint unused:true */
define([
'dojo/_base/declare',
'dijit/_WidgetBase',
'dijit/_TemplatedMixin'
],
function (
declare,
_WidgetBase,
_TemplatedMixin
) {
google.hello();
require(['test']);
return [declare, _WidgetBase, _TemplatedMixin];
});
|
// warning: This file is auto generated by `npm run build:tests`
// Do not edit by hand!
process.env.TZ = 'UTC'
var expect = require('chai').expect
var ini_set = require('../../../../src/php/info/ini_set') // eslint-disable-line no-unused-vars,camelcase
var ini_get = require('../../../../src/php/info/ini_get') // eslint-disable-line no-unused-vars,camelcase
var strnatcmp = require('../../../../src/php/strings/strnatcmp.js') // eslint-disable-line no-unused-vars,camelcase
describe('src/php/strings/strnatcmp.js (tested in test/languages/php/strings/test-strnatcmp.js)', function () {
it('should pass example 1', function (done) {
var expected = 0
var result = strnatcmp('abc', 'abc')
expect(result).to.deep.equal(expected)
done()
})
it('should pass example 2', function (done) {
var expected = -1
var result = strnatcmp('a', 'b')
expect(result).to.deep.equal(expected)
done()
})
it('should pass example 3', function (done) {
var expected = 1
var result = strnatcmp('10', '1')
expect(result).to.deep.equal(expected)
done()
})
it('should pass example 4', function (done) {
var expected = 0
var result = strnatcmp('0000abc', '0abc')
expect(result).to.deep.equal(expected)
done()
})
it('should pass example 5', function (done) {
var expected = -1
var result = strnatcmp('1239', '12345')
expect(result).to.deep.equal(expected)
done()
})
it('should pass example 6', function (done) {
var expected = 1
var result = strnatcmp('t01239', 't012345')
expect(result).to.deep.equal(expected)
done()
})
it('should pass example 7', function (done) {
var expected = -1
var result = strnatcmp('0A', '5N')
expect(result).to.deep.equal(expected)
done()
})
})
|
var supportSafariIOS = true;
if (!supportSafariIOS) {
var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
var isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
isIOS = true;
if (isSafari && isIOS) {
var errDis = document.getElementById('full-error-view');
if(errDis) {
errDis.style.display = 'block';
var btn = document.getElementById('full-error-view-button');
btn.onclick = function() {
errDis.style.display = 'none';
}
} else {
console.log('Err display not found!')
}
}
}
|
const webtorrent = module.exports = {
init,
send,
show,
toggleDevTools,
win: null
}
const { app, BrowserWindow } = require('electron')
const config = require('../../config')
function init () {
const win = webtorrent.win = new BrowserWindow({
backgroundColor: '#1E1E1E',
center: true,
fullscreen: false,
fullscreenable: false,
height: 150,
maximizable: false,
minimizable: false,
resizable: false,
show: false,
skipTaskbar: true,
title: 'webtorrent-hidden-window',
useContentSize: true,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
enableBlinkFeatures: 'AudioVideoTracks',
enableRemoteModule: true,
backgroundThrottling: false
},
width: 150
})
require('@electron/remote/main').enable(win.webContents)
win.loadURL(config.WINDOW_WEBTORRENT)
// Prevent killing the WebTorrent process
win.on('close', e => {
if (app.isQuitting) {
return
}
e.preventDefault()
win.hide()
})
}
function show () {
if (!webtorrent.win) return
webtorrent.win.show()
}
function send (...args) {
if (!webtorrent.win) return
webtorrent.win.send(...args)
}
function toggleDevTools () {
if (!webtorrent.win) return
if (webtorrent.win.webContents.isDevToolsOpened()) {
webtorrent.win.webContents.closeDevTools()
webtorrent.win.hide()
} else {
webtorrent.win.webContents.openDevTools({ mode: 'detach' })
}
}
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M10.01 21.01c0 1.1.89 1.99 1.99 1.99s1.99-.89 1.99-1.99h-3.98zM12 6c2.76 0 5 2.24 5 5v7H7v-7c0-2.76 2.24-5 5-5zm0-4.5c-.83 0-1.5.67-1.5 1.5v1.17C7.36 4.85 5 7.65 5 11v6l-2 2v1h18v-1l-2-2v-6c0-3.35-2.36-6.15-5.5-6.83V3c0-.83-.67-1.5-1.5-1.5z" /><path d="M13 8h-2v3H8v2h3v3h2v-3h3v-2h-3z" /></React.Fragment>
, 'AddAlertOutlined');
|
/**
* @file 标记类标签的行为父类,标记类标签将会通过引入而导致其父级元素(如果是shadowRoot 则穿透至其host)有一定特殊的行为
*
* @author Leo Wang(wangkemiao@baidu.com)
*/
define(function (require) {
/**
* 标记后面的兄弟元素为selectable的
* @class
*/
var overrides = {
/**
* 初始化,可用于调整 DOM 结构
*/
initialize: function () {
this.el.attr('hidden', '');
// 查询 host
var parent = this.el.parent()[0];
// 如果 parent 是 content,则向上一层
if (parent.tagName && parent.tagName.toLowerCase() === 'content') {
parent = parent.parentNode;
}
// 如果parent是shadowRoot,则穿透到其 host 上
var hasGoneThrough = false;
if (parent.host) {
parent = parent.host;
hasGoneThrough = true;
}
else if (parent.tagName.toLowerCase() === 'fake-shadow-root') {
parent = parent.parentNode;
}
/**
* @property {HTMLElement} host 宿主元素
*/
this.host = this.$(parent);
/**
* @property {Zepto} $host 用于绑定事件的宿主 Zepto 对象
*/
if (hasGoneThrough) { // support shadow root
this.$host = this.$(parent.shadowRoot);
}
else {
this.$host = this.host;
}
}
};
var MarkSelectable = require('eoo').create(require('k-component/Action'), overrides);
return MarkSelectable;
});
|
import { expect } from 'chai';
import server from '../../utils/server.mock';
import User from '../../../app/models/user';
import UserFactory from '../../factories/user.factory';
const ENDPOINT = '/users';
let savedUser;
describe(`GET ${ENDPOINT}/:username`, () => {
before(() => {
return User.remove({})
.then(() => User.create(UserFactory.generate()))
.then(u => savedUser = u);
});
describe('#200', () => {
it('should return the user profile', done => {
server.get(`${ENDPOINT}/${savedUser.username}`)
.end((err, res) => {
expect(res).to.have.status(200);
expect(res.body.username).to.equal(savedUser.username);
done();
});
});
});
describe('#404', () => {
it('return 404 if username does not exist', done => {
server.get(`${ENDPOINT}/doesnotexist`)
.end((err, res) => {
expect(res).to.have.status(404);
done();
});
});
});
});
describe(`GET ${ENDPOINT}/me`, () => {
before(() => {
return User.remove({})
.then(() => User.create(UserFactory.generate()))
.then(u => savedUser = u);
});
describe('#200', () => {
it('should return the current user\'s profile', done => {
server.get(`${ENDPOINT}/me`)
.set('Authorization', savedUser.generateToken())
.end((err, res) => {
expect(res).to.have.status(200);
expect(res.body.username).to.equal(savedUser.username);
done();
});
});
});
describe('#401', () => {
it('should return Unauthorized if wrong token is provided', done => {
server.get(`${ENDPOINT}/me`)
.set('Authorization', 'wrongtoken')
.end((err, res) => {
expect(res).to.have.status(401);
done();
});
});
});
});
|
import { Map, Set } from 'immutable'
import * as constants from './constants.js'
import {
addLogFilters,
removeLogFilters,
updateLogFilters,
parseLogs
} from './logparse.js'
const siadir = SiaAPI.config.siad.datadir
const defaultLogSize = 50000
const initialState = Map({
logFilters: Set(['consensus.log', 'gateway.log']),
logText: parseLogs(siadir, 50000, ['consensus.log', 'gateway.log']),
logSize: defaultLogSize,
scrolling: false
})
export default function loggingReducer (state = initialState, action) {
switch (action.type) {
case constants.INCREMENT_LOG_SIZE:
return updateLogFilters(
state,
state.get('logSize') + action.increment,
state.get('logFilters')
)
case constants.RELOAD_LOG:
return updateLogFilters(
state,
state.get('logSize'),
state.get('logFilters')
)
case constants.ADD_LOG_FILTERS:
return addLogFilters(state, action.filters)
case constants.REMOVE_LOG_FILTERS:
return removeLogFilters(state, action.filters)
case constants.SET_LOG_FILTERS:
return updateLogFilters(
state,
state.get('logSize'),
Set(action.filters)
).set('logSize', defaultLogSize)
case constants.SET_SCROLLING:
return state.set('scrolling', true)
case constants.SET_NOT_SCROLLING:
return state.set('scrolling', false)
default:
return state
}
}
|
import { FieldGroup, Box } from '@rocket.chat/fuselage';
import { useMutableCallback } from '@rocket.chat/fuselage-hooks';
import React, { useEffect, useState } from 'react';
import { useSubscription } from 'use-subscription';
import { businessHourManager } from '../../../../app/livechat/client/views/app/business-hours/BusinessHours';
import { useForm } from '../../../hooks/useForm';
import { useReactiveValue } from '../../../hooks/useReactiveValue';
import { formsSubscription } from '../additionalForms';
import BusinessHourForm from './BusinessHoursForm';
const useChangeHandler = (name, ref) =>
useMutableCallback((val) => {
ref.current[name] = { ...ref.current[name], ...val };
});
const getInitalData = ({ workHours }) => ({
daysOpen: workHours.filter(({ open }) => !!open).map(({ day }) => day),
daysTime: workHours.reduce((acc, { day, start: { time: start }, finish: { time: finish } }) => {
acc = { ...acc, [day]: { start, finish } };
return acc;
}, {}),
});
const cleanFunc = () => {};
const BusinessHoursFormContainer = ({ data, saveRef, onChange = () => {} }) => {
const forms = useSubscription(formsSubscription);
const [hasChangesMultiple, setHasChangesMultiple] = useState(false);
const [hasChangesTimeZone, setHasChangesTimeZone] = useState(false);
const { useBusinessHoursTimeZone = cleanFunc, useBusinessHoursMultiple = cleanFunc } = forms;
const TimezoneForm = useBusinessHoursTimeZone();
const MultipleBHForm = useBusinessHoursMultiple();
const showTimezone = useReactiveValue(
useMutableCallback(() => businessHourManager.showTimezoneTemplate()),
);
const showMultipleBHForm = useReactiveValue(
useMutableCallback(() => businessHourManager.showCustomTemplate(data)),
);
const onChangeTimezone = useChangeHandler('timezone', saveRef);
const onChangeMultipleBHForm = useChangeHandler('multiple', saveRef);
const { values, handlers, hasUnsavedChanges } = useForm(getInitalData(data));
saveRef.current.form = values;
useEffect(() => {
onChange(
hasUnsavedChanges ||
(showMultipleBHForm && hasChangesMultiple) ||
(showTimezone && hasChangesTimeZone),
);
});
return (
<Box maxWidth='600px' w='full' alignSelf='center'>
<FieldGroup>
{showMultipleBHForm && MultipleBHForm && (
<MultipleBHForm
onChange={onChangeMultipleBHForm}
data={data}
hasChangesAndIsValid={setHasChangesMultiple}
/>
)}
{showTimezone && TimezoneForm && (
<TimezoneForm
onChange={onChangeTimezone}
data={data?.timezone?.name ?? data?.timezoneName}
hasChanges={setHasChangesTimeZone}
/>
)}
<BusinessHourForm values={values} handlers={handlers} />
</FieldGroup>
</Box>
);
};
export default BusinessHoursFormContainer;
|
function Net(context) {
this.x = 545;
this.y = 600;
this.width = 10;
this.height = -80;
this.context = context;
this.color = '#33334d';
}
Net.prototype.render = function() {
this.context.fillStyle = this.color;
this.context.fillRect(this.x, this.y, this.width, this.height);
};
module.exports = Net;
|
const info = require("./package.json");
module.exports = {
author: info.author,
version: info.version,
description: info.description,
license: info.license,
name: "Kana Chart",
keywords: "japanese, hiragana, katakana, romanji, pronunciation, stroke order, how to write, interactive, chart, table",
locale: "en",
theme_color: "#c70025",
background_color: "#ffffff",
picture: "android-chrome-192x192.png",
url: "https://okku.site/japanese",
}
|
import Route from "@ember/routing/route";
import InfiniteScrollOffsetMixin from "ui/routes/-mixins/routes/infinite-scroll/offset";
import RefreshRouteMixin from "ui/routes/-mixins/routes/refresh";
export default Route.extend( InfiniteScrollOffsetMixin, RefreshRouteMixin, {
itemSelector: ".game-item-component",
modelName: "twitchGameTop",
modelPreload: "game.box.large"
});
|
var mongoose = require('mongoose');
var mySchema = mongoose.Schema({
key: String
});
module.exports = mongoose.model('myschema', mySchema);
|
// ------------------------------------
// Constants
// ------------------------------------
export const LOCATION_CHANGE = 'LOCATION_CHANGE'
// ------------------------------------
// Actions
// ------------------------------------
export function locationChange (location = '/') {
return {
type : LOCATION_CHANGE,
payload : location
}
}
// ------------------------------------
// Specialized Action Creator
// ------------------------------------
export const updateLocation = ({ dispatch }) => {
return (nextLocation) => dispatch(locationChange(nextLocation))
}
// ------------------------------------
// Reducer
// ------------------------------------
const initialState = null;
export default function locationReducer (state = initialState, action) {
return action.type === LOCATION_CHANGE
? action.payload
: state
}
|
import maxBy from 'lodash/maxBy';
import sortBy from 'lodash/sortBy';
import notificationsResource from '../../apiResources/notifications';
import { allNotifications, summarizedNotifications } from './getters';
export default {
namespaced: true,
state: {
currentClassroomId: null,
notifications: [],
},
mutations: {
SET_NOTIFICATIONS(state, notifications) {
state.notifications = [...notifications];
},
APPEND_NOTIFICATIONS(state, notifications) {
state.notifications = [...notifications, ...state.notifications];
},
INSERT_NOTIFICATIONS(state, notifications) {
state.notifications = sortBy([state.notifications, ...notifications], '-id');
},
SET_CURRENT_CLASSROOM_ID(state, classroomId) {
state.currentClassroomId = classroomId;
},
},
getters: {
allNotifications,
summarizedNotifications,
maxNotificationIndex(state) {
if (state.notifications.length > 0) {
// IDs are being converted to strings for some reason
return maxBy(state.notifications, n => Number(n.id)).id;
}
return 0;
},
},
actions: {
stopPolling(store) {
store.commit('SET_CURRENT_CLASSROOM_ID', '');
// Need to clear out 403 error in store to prevent auth message from showing
// in other places.
store.commit('CORE_SET_ERROR', '', { root: true });
},
fetchNotificationsForClass(store, classroomId) {
if (!store.state.currentClassroomId) {
store.commit('SET_CURRENT_CLASSROOM_ID', classroomId);
}
return notificationsResource
.fetchCollection({
getParams: {
classroom_id: classroomId,
},
})
.then(data => {
store.commit('SET_NOTIFICATIONS', data.results);
if (!store.state.poller) {
store.dispatch('startingPolling', { coachesPolling: data.coaches_polling });
}
})
.catch(() => {
if (!store.state.poller) {
store.dispatch('startingPolling', { coachesPolling: 0 });
}
});
},
updateNotificationsForClass(store, { classroomId, after }) {
// stop polling if not viewing a classroom anymore
if (!store.state.currentClassroomId) {
return;
}
return notificationsResource
.fetchCollection({
getParams: {
classroom_id: classroomId,
after,
},
force: true,
})
.then(data => {
if (data.results.length > 0) {
store.commit('APPEND_NOTIFICATIONS', data.results);
store.dispatch('classSummary/updateWithNotifications', data.results, { root: true });
}
store.dispatch('startingPolling', { coachesPolling: data.coaches_polling });
})
.catch(() => {
store.dispatch('startingPolling', { coachesPolling: 0 });
});
},
moreNotificationsForClass(store, params) {
const classroomId = store.state.currentClassroomId;
const lastNotification = store.state.notifications.slice(-1)[0];
// don't fetch if no current classroom
if (!classroomId || !lastNotification || lastNotification.id <= 1) {
return Promise.resolve(false);
}
const limit = 25;
return notificationsResource
.fetchCollection({
getParams: {
classroom_id: classroomId,
before: lastNotification.id,
limit,
...(params || {}),
},
force: true,
})
.then(data => {
if (data.results.length > 0) {
store.commit('INSERT_NOTIFICATIONS', data.results);
return data.more_results;
}
return false;
})
.catch(() => {
return false;
});
},
startingPolling(store, { coachesPolling }) {
const timeout = 2000 * Math.min(Math.max(coachesPolling, 1), 10);
setTimeout(() => {
store.dispatch('updateNotificationsForClass', {
classroomId: store.state.currentClassroomId,
after: store.getters.maxNotificationIndex,
});
}, timeout);
},
},
};
|
var player = document.getElementById("player")
function playORpause(){
if(player.paused){
player.play();
}else{
player.pause();
}
}
function fullScreen(){
if (player.requestFullscreen) {
player.requestFullscreen();
} else if (player.mozRequestFullScreen) {
player.mozRequestFullScreen();
} else if (player.webkitRequestFullscreen) {
player.webkitRequestFullscreen();
}
}
|
var stringUtil = require('ember-cli-string-utils');
var SilentError = require('silent-error');
var pathUtil = require('ember-cli-path-utils');
module.exports = {
description: 'Generates an ember-data adapter.',
availableOptions: [
{ name: 'base-class', type: String }
],
locals: function(options) {
var adapterName = options.entity.name;
var baseClass = 'JSONAPIAdapter';
var importStatement = 'import JSONAPIAdapter from \'ember-data/adapters/json-api\';';
var isAddon = options.inRepoAddon || options.project.isEmberCLIAddon();
var relativePath = pathUtil.getRelativePath(options.entity.name);
if (options.pod && options.podPath) {
relativePath = pathUtil.getRelativePath(options.podPath + options.entity.name);
}
if (!isAddon && !options.baseClass && adapterName !== 'application') {
options.baseClass = 'application';
}
if (options.baseClass === adapterName) {
throw new SilentError('Adapters cannot extend from themself. To resolve this, remove the `--base-class` option or change to a different base-class.');
}
if (options.baseClass) {
baseClass = stringUtil.classify(options.baseClass.replace('/', '-'));
baseClass = baseClass + 'Adapter';
importStatement = 'import ' + baseClass + ' from \'' + relativePath + options.baseClass + '\';';
}
return {
importStatement: importStatement,
baseClass: baseClass
};
}
};
|
/*!
* jquery.fancytree.gridnav.js
*
* Support keyboard navigation for trees with embedded input controls.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2017, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version @VERSION
* @date @DATE
*/
;(function($, window, document, undefined) {
"use strict";
/*******************************************************************************
* Private functions and variables
*/
// Allow these navigation keys even when input controls are focused
var KC = $.ui.keyCode,
// which keys are *not* handled by embedded control, but passed to tree
// navigation handler:
NAV_KEYS = {
"text": [KC.UP, KC.DOWN],
"checkbox": [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT],
"link": [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT],
"radiobutton": [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT],
"select-one": [KC.LEFT, KC.RIGHT],
"select-multiple": [KC.LEFT, KC.RIGHT]
};
/* Calculate TD column index (considering colspans).*/
function getColIdx($tr, $td) {
var colspan,
td = $td.get(0),
idx = 0;
$tr.children().each(function () {
if( this === td ) {
return false;
}
colspan = $(this).prop("colspan");
idx += colspan ? colspan : 1;
});
return idx;
}
/* Find TD at given column index (considering colspans).*/
function findTdAtColIdx($tr, colIdx) {
var colspan,
res = null,
idx = 0;
$tr.children().each(function () {
if( idx >= colIdx ) {
res = $(this);
return false;
}
colspan = $(this).prop("colspan");
idx += colspan ? colspan : 1;
});
return res;
}
/* Find adjacent cell for a given direction. Skip empty cells and consider merged cells */
function findNeighbourTd($target, keyCode){
var $tr, colIdx,
$td = $target.closest("td"),
$tdNext = null;
switch( keyCode ){
case KC.LEFT:
$tdNext = $td.prev();
break;
case KC.RIGHT:
$tdNext = $td.next();
break;
case KC.UP:
case KC.DOWN:
$tr = $td.parent();
colIdx = getColIdx($tr, $td);
while( true ) {
$tr = (keyCode === KC.UP) ? $tr.prev() : $tr.next();
if( !$tr.length ) {
break;
}
// Skip hidden rows
if( $tr.is(":hidden") ) {
continue;
}
// Find adjacent cell in the same column
$tdNext = findTdAtColIdx($tr, colIdx);
// Skip cells that don't conatain a focusable element
if( $tdNext && $tdNext.find(":input,a").length ) {
break;
}
}
break;
}
return $tdNext;
}
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "gridnav",
version: "@VERSION",
// Default options for this extension.
options: {
autofocusInput: false, // Focus first embedded input if node gets activated
handleCursorKeys: true // Allow UP/DOWN in inputs to move to prev/next node
},
treeInit: function(ctx){
// gridnav requires the table extension to be loaded before itself
this._requireExtension("table", true, true);
this._superApply(arguments);
this.$container.addClass("fancytree-ext-gridnav");
// Activate node if embedded input gets focus (due to a click)
this.$container.on("focusin", function(event){
var ctx2,
node = $.ui.fancytree.getNode(event.target);
if( node && !node.isActive() ){
// Call node.setActive(), but also pass the event
ctx2 = ctx.tree._makeHookContext(node, event);
ctx.tree._callHook("nodeSetActive", ctx2, true);
}
});
},
nodeSetActive: function(ctx, flag, callOpts) {
var $outer,
opts = ctx.options.gridnav,
node = ctx.node,
event = ctx.originalEvent || {},
triggeredByInput = $(event.target).is(":input");
flag = (flag !== false);
this._superApply(arguments);
if( flag ){
if( ctx.options.titlesTabbable ){
if( !triggeredByInput ) {
$(node.span).find("span.fancytree-title").focus();
node.setFocus();
}
// If one node is tabbable, the container no longer needs to be
ctx.tree.$container.attr("tabindex", "-1");
// ctx.tree.$container.removeAttr("tabindex");
} else if( opts.autofocusInput && !triggeredByInput ){
// Set focus to input sub input (if node was clicked, but not
// when TAB was pressed )
$outer = $(node.tr || node.span);
$outer.find(":input:enabled:first").focus();
}
}
},
nodeKeydown: function(ctx) {
var inputType, handleKeys, $td,
opts = ctx.options.gridnav,
event = ctx.originalEvent,
$target = $(event.target);
if( $target.is(":input:enabled") ) {
inputType = $target.prop("type");
} else if( $target.is("a") ) {
inputType = "link";
}
// ctx.tree.debug("ext-gridnav nodeKeydown", event, inputType);
if( inputType && opts.handleCursorKeys ){
handleKeys = NAV_KEYS[inputType];
if( handleKeys && $.inArray(event.which, handleKeys) >= 0 ){
$td = findNeighbourTd($target, event.which);
if( $td && $td.length ) {
// ctx.node.debug("ignore keydown in input", event.which, handleKeys);
$td.find(":input:enabled,a").focus();
// Prevent Fancytree default navigation
return false;
}
}
return true;
}
// ctx.tree.debug("ext-gridnav NOT HANDLED", event, inputType);
return this._superApply(arguments);
}
});
}(jQuery, window, document));
|
'use strict';
const fs = require('fs');
const path = require('path');
const LOG_DIR = path.join(__dirname, '../../logs/');
/**
* @param {string} pluginId
*/
function getPluginLogs(pluginId) {
return new Promise((resolve, reject) => {
var logFilename = path.join(LOG_DIR, pluginId + '.plugin.log');
fs.readFile(logFilename, 'utf8', (error, data) => {
if (error) {
reject(error);
} else {
resolve(data);
}
});
});
}
function getYakjsLogs() {
return new Promise((resolve, reject) => {
var logFilename = path.join(LOG_DIR, 'yakjs.log');
fs.readFile(logFilename, 'utf8', (error, data) => {
if (error) {
reject(error);
} else {
resolve(data);
}
});
});
}
module.exports = {
getPluginLogs,
getYakjsLogs
};
|
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var app = express();
// Specify the connection string for your mongodb database
// and the location to your Parse cloud code
var api = new ParseServer({
databaseURI: 'mongodb://localhost:27017/integration',
appId: 'integration',
masterKey: 'notsosecret',
serverURL: 'http://localhost:1337/parse' // Don't forget to change to https if needed
});
// Serve the Parse API on the /parse URL prefix
app.use('/parse', api);
const TestUtils = require('parse-server').TestUtils;
app.get('/clear', (req, res) => {
TestUtils.destroyAllDataPermanently().then(() => {
res.send('{}');
});
});
app.listen(1337, () => {
console.log('parse-server running on port 1337.');
});
|
import React from 'react';
import './Path'; // must import Path first, don`t know why. without this will throw an `Super expression must either be null or a function, not undefined`
import createReactNativeComponentClass from 'react/lib/createReactNativeComponentClass';
import {pathProps, numberProp} from '../lib/props';
import {RectAttributes} from '../lib/attributes';
import Shape from './Shape';
class Rect extends Shape {
static displayName = 'Rect';
static propTypes = {
...pathProps,
x: numberProp.isRequired,
y: numberProp.isRequired,
width: numberProp.isRequired,
height: numberProp.isRequired,
rx: numberProp,
ry: numberProp
};
static defaultProps = {
x: 0,
y: 0,
width: 0,
height: 0,
rx: 0,
ry: 0
};
setNativeProps = (...args) => {
this.root.setNativeProps(...args);
};
render() {
let props = this.props;
return <RNSVGRect
ref={ele => {this.root = ele;}}
{...this.extractProps({
...props,
x: null,
y: null
})}
x={props.x.toString()}
y={props.y.toString()}
width={props.width.toString()}
height={props.height.toString()}
rx={props.rx.toString()}
ry={props.ry.toString()}
/>;
}
}
const RNSVGRect = createReactNativeComponentClass({
validAttributes: RectAttributes,
uiViewClassName: 'RNSVGRect'
});
export default Rect;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.