text
stringlengths 2
6.14k
|
|---|
'use strict';
const SETTINGS = require(__dirname + '/config');
// Behaviour
const Behaviour = require('./components/behaviour');
Behaviour.start(SETTINGS);
// Web server
const express = require('express');
const app = express();
const server = require('http').Server(app);
// Middleware
app.use(require('logfmt').requestLogger());
app.use(require('body-parser').urlencoded({extended: true}));
// Work with reverse proxies
app.set('trust proxy', SETTINGS.reverseProxyMode);
// Static files
app.use(express.static(SETTINGS.dir.client));
// Routes
const rest = require('./components/rest');
rest.start(app, SETTINGS);
// Socket.IO
const io = require('./components/comms');
io.start(server, SETTINGS);
// Slack bot
const bot = require('./components/slack');
bot.start(app, SETTINGS);
// Error Handler
const errorHandler = require('./errorHandler');
app.use(errorHandler);
app.use(errorHandler.notFound);
// Run the server
server.listen(SETTINGS.port, function onServerStarted() {
console.log("Server listening on port %d", SETTINGS.port);
});
|
exports.notEmpty = name => {
return v => {
if (!v || v.trim === '') {
return `${name} is required`
} else {
return true
}
}
}
|
/****************************************
* 协同云 项目状态统计
*
****************************************/
var CC = CC || {};
(function (u, undefined) {
var taskStatusReport = {
//作用:搜索所有任务
//参数:vault
searchAllTasks: function (vault) {
var sConditons = MFiles.CreateInstance("SearchConditions");
var condition = MFiles.CreateInstance("SearchCondition");
condition.ConditionType = MFConditionTypeEqual;
condition.Expression.DataPropertyValuePropertyDef = MFBuiltInPropertyDefClass;
condition.TypedValue.SetValue(MFDatatypeLookup, -100);
sConditons.Add(-1, condition);
return MF.ObjectOps.SearchObjects(vault, MFBuiltInObjectTypeAssignment, sConditons);
},
//作用:判断任务是否完成
//参数:vault;任务对象版本
isTaskCompleted: function (vault, objVer) {
var props = vault.ObjectPropertyOperations.GetProperties(objVer, false);
var pIdAssignTop = MF.alias.propertyDef(vault, md.genericTask.propDefs.AssignedTo);
//指派给
var assignToLen = 0;
var assignToTvalue = props.SearchForProperty(pIdAssignTop).Value;
if (assignToTvalue.IsNULL() == false) {
var ups1 = assignToTvalue.GetValueAsLookups();
assignToLen = ups1.Count;
}
if (assignToLen !== 0 ) {
return false;
}
return true;
},
//作用:根据时间过滤任务
//参数:vault;任务对象列表;开始日期;结束日期
filterTaskFromDate: function (vault, tasks, startDate, endDate) {
var taskData = [];
for (var i = 1; i <= tasks.Count; i++) {
var task = tasks.Item(i);
var props = vault.ObjectPropertyOperations.GetProperties(task.ObjVer, false);
var starId = MF.alias.propertyDef(vault, md.genericTask.propDefs.StartDate);
var start = props.SearchForProperty(starId).Value.DisplayValue;
var endId = MF.alias.propertyDef(vault, md.genericTask.propDefs.Deadline);
var end = props.SearchForProperty(endId).Value.DisplayValue;
if (this._compareDate(startDate, start) && this._compareDate(end, endDate)) {
taskData.push(task);
}
}
return taskData;
},
//作用:时间比较tagDate >= srcDate : true
//参数:开始时间;结束时间
_compareDate: function (srcDate, tagDate) {
if (srcDate == null || tagDate == null) {
return false;
}
srcDate = srcDate.replace(/\-/g, "/");
tagDate = tagDate.replace(/\-/g, "/");
var startDate = new Date(srcDate);
var endDate = new Date(tagDate);
if (startDate > endDate) {
return false;
} else {
return true;
}
}
};
u.taskStatusReport = taskStatusReport;
})(CC);
|
var express = require('../');
function req(ret) {
return {
get: function(){ return ret }
, __proto__: express.request
};
}
describe('req', function(){
describe('.host', function(){
it('should return hostname', function(){
req('example.com:3000').host.should.equal('example.com');
req('example.com').host.should.equal('example.com');
})
})
})
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M4 4v13.17l.59-.59.58-.58H20V4H4zm9 11h-2v-2h2v2zm0-4h-2V5h2v6z" opacity=".3" /><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H5.17l-.59.59-.58.58V4h16v12zM11 5h2v6h-2zm0 8h2v2h-2z" /></React.Fragment>
, 'AnnouncementTwoTone');
|
'use strict';
const app = require('app');
var repository = require('./js/backEnd/itemsRepository');
const BrowserWindow = require('browser-window');
var ipc = require('ipc');
let mainWindow = null;
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit();
}
});
ipc.on('saveItems', function(event, arg) {
repository.saveItems(arg);
});
ipc.on('getItems', function(event) {
event.returnValue = repository.loadItems();
});
app.on('ready', function () {
mainWindow = new BrowserWindow({
width: 600,
height: 1000,
resizable: false
});
mainWindow.loadUrl(`file://${__dirname}/index.html`);
mainWindow.on('closed', function () {
// deref the window
// for multiple windows store them in an array
mainWindow = null;
});
});
|
import Ember from 'ember';
var KiwiPhoneComponent = Ember.Component.extend({
classNames: 'form-group',
inputElementId: function(){
return 'input-' + this.get('elementId');
}.property('elementId'),
translatedLabel: function(){
return translate(this.get('label'));
}.property('label'),
actions: {
savePhoneNumber: function(phoneNumber){
this.sendAction('action', phoneNumber);
}
}
});
export default KiwiPhoneComponent;
|
var searchData=
[
['max_5fverbosity',['max_verbosity',['../class_test.html#aad3dc21628f5210b9ebdf843eb2b2ae0',1,'Test']]],
['min_5fverbosity',['min_verbosity',['../class_test.html#a1ff0e4cf27254c988233880fff9e6c6d',1,'Test']]]
];
|
require.config({
baseUrl: '../public/assets/scripts/lib',
paths: {
app: '../app',
routes: '../app/routes',
models: '../app/models',
views: '../app/views',
controllers: '../app/controllers',
mixins: '../app/mixins',
templates: '../../templates',
ember: 'ember/ember',
jquery: 'jquery/dist/jquery',
requirejs: 'requirejs/require',
handlebars: 'handlebars/handlebars',
bootstrap: 'bootstrap-sass-official/assets/javascripts/bootstrap',
'ember-data': 'ember-data/ember-data',
'ember-qunit': 'ember-qunit/dist/globals/main'
},
shim: {
ember: {
deps: [
'handlebars',
'jquery'
],
exports: 'Ember'
},
'ember-data': {
deps: [
'ember'
],
exports: 'DS'
},
'bootstrap/transition': {
deps: [
'jquery'
]
},
'bootstrap/collapse': {
deps: [
'jquery',
'bootstrap/transition'
]
},
'ember-qunit': {
deps: ['ember']
}
}
});
|
describe('destroy', function() {
beforeEach(function() {
affix('#cal');
});
describe('when calendar is LTR', function() {
it('cleans up all classNames on the root element', function() {
$('#cal').fullCalendar({
isRTL: false
});
$('#cal').fullCalendar('destroy');
expect($('#cal')[0].className).toBe('');
});
});
describe('when calendar is RTL', function() {
it('cleans up all classNames on the root element', function() {
$('#cal').fullCalendar({
isRTL: true
});
$('#cal').fullCalendar('destroy');
expect($('#cal')[0].className).toBe('');
});
});
[ 'month', 'basicWeek', 'agendaWeek' ].forEach(function(viewName) {
describe('when in ' + viewName + ' view', function() {
var options;
beforeEach(function() {
options = {
defaultView: viewName,
defaultDate: '2014-12-01',
droppable: true, // likely to attach document handler
editable: true, // same
events: [
{ title: 'event1', start: '2014-12-01' }
]
};
});
it('leaves no handlers attached to DOM', function(done) {
var origDocCnt = countHandlers(document);
var origElCnt = countHandlers('#cal');
$('#cal').fullCalendar(options);
setTimeout(function() { // in case there are delayed attached handlers
$('#cal').fullCalendar('destroy');
expect(countHandlers(document)).toBe(origDocCnt);
expect(countHandlers('#cal')).toBe(origElCnt);
done();
}, 0);
});
// Issue 2432
it('preserves existing window handlers when handleWindowResize is off', function() {
var resizeHandler = function() { };
var handlerCnt0 = countHandlers(window);
var handlerCnt1;
var handlerCnt2;
$(window).on('resize', resizeHandler);
handlerCnt1 = countHandlers(window);
expect(handlerCnt1).toBe(handlerCnt0 + 1);
$('#cal').fullCalendar({
handleWindowResize: false
});
$('#cal').fullCalendar('destroy');
handlerCnt2 = countHandlers(window);
expect(handlerCnt2).toBe(handlerCnt1);
});
});
});
});
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M7.82 16H15v-1c0-2.21 1.79-4 4-4h.74l-1.9-8.44C17.63 1.65 16.82 1 15.89 1H12v2h3.89l1.4 6.25h-.01c-2.16.65-3.81 2.48-4.19 4.75H7.82c-.48-1.34-1.86-2.24-3.42-1.94-1.18.23-2.13 1.2-2.35 2.38C1.7 16.34 3.16 18 5 18c1.3 0 2.4-.84 2.82-2zM5 16c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z"
}, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M19 12c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3zm0 4c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm-8 4H7l6 3v-2h4l-6-3z"
}, "1")], 'ElectricScooterTwoTone');
exports.default = _default;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const assert = require("assert");
const fs_macchiato_1 = require("../../../fs.macchiato");
const util = require("./fs");
describe('Utils → FS', () => {
describe('.createDirentFromStats', () => {
it('should convert fs.Stats to fs.Dirent', () => {
const actual = util.createDirentFromStats('name', new fs_macchiato_1.Stats());
assert.strictEqual(actual.name, 'name');
assert.ok(!actual.isBlockDevice());
assert.ok(!actual.isCharacterDevice());
assert.ok(!actual.isDirectory());
assert.ok(!actual.isFIFO());
assert.ok(actual.isFile());
assert.ok(!actual.isSocket());
assert.ok(!actual.isSymbolicLink());
});
});
});
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 13.1-37-s
description: >
StrictMode - SyntaxError is thrown if 'eval' occurs as the
Identifier of a FunctionExpression in strict eval code
flags: [onlyStrict]
includes: [runTestCase.js]
---*/
function testcase() {
var _13_1_37_s = {};
try {
eval("'use strict'; _13_1_37_s.x = function eval() {};");
return false;
} catch (e) {
return e instanceof SyntaxError;
}
}
runTestCase(testcase);
|
'use strict';
exports.box = function (stdlib, foreign, heap) {
'use asm';
function uniqueCols (ptr) {
ptr = ptr >>> 0;
var u32 = new stdlib.Uint32Array(heap);
return;
}
function uniqueRows (ptr) {
ptr = ptr >>> 0;
var data = new stdlib.Uint32Array(heap);
return;
}
return {
uniqueCols: uniqueCols,
uniqueRows: uniqueRows
};
}
exports.write = function (heap, offset, data) {
var u32 = new Uint32Array(heap);
var arr = data.split(' ').reduce(function (a, e) {
if (e !== '') {
a.push(e.split(''));
}
return a;
}, []);
var cols = arr[0].length;
var rows = arr.length;
arr.forEach(function (row, y) {
row.forEach(function (e, x) {
var num = isNaN(e) ? 0 : Number(e);
u32[(x + y * cols) + 4] = num;
});
});
// descriptor
u32[0] = 1; // type
u32[1] = cols;
u32[2] = rows;
};
exports.read = function (heap, offset) {
var u32 = new Uint32Array(heap);
var data = '';
var cols = u32[1];
var rows = u32[2];
var x, y;
for (y = 0; y < rows; y++) {
for (x = 0; x < cols; x++) {
data += u32[(x + y * cols) + 4] || '.';
}
data += '\n';
}
return data;
};
|
import React, { Component, PropTypes } from 'react';
import { IndexLink, Link } from 'react-router';
import { connect } from 'react-redux';
import DocumentMeta from 'react-document-meta';
import { isLoaded as isInfoLoaded, load as loadInfo } from 'redux/modules/info';
import { isLoaded as isAuthLoaded, load as loadAuth, logout } from 'redux/modules/auth';
import { InfoBar } from 'components';
import { pushState } from 'redux-router';
const title = 'React Redux Example';
const description = 'All the modern best practices in one example.';
const image = 'https://react-redux.herokuapp.com/logo.jpg';
const meta = {
title,
description,
meta: {
charSet: 'utf-8',
property: {
'og:site_name': title,
'og:image': image,
'og:locale': 'en_US',
'og:title': title,
'og:description': description,
'twitter:card': 'summary',
'twitter:site': '@erikras',
'twitter:creator': '@erikras',
'twitter:title': title,
'twitter:description': description,
'twitter:image': image,
'twitter:image:width': '200',
'twitter:image:height': '200'
}
}
};
const NavbarLink = ({to, className, component, children}) => {
const Comp = component || Link;
return (
<Comp to={to} className={className} activeStyle={{
color: '#33e0ff'
}}>
{children}
</Comp>
);
};
@connect(
state => ({user: state.auth.user}),
{logout, pushState})
export default class App extends Component {
static propTypes = {
children: PropTypes.object.isRequired,
user: PropTypes.object,
logout: PropTypes.func.isRequired,
pushState: PropTypes.func.isRequired
};
static contextTypes = {
store: PropTypes.object.isRequired
};
componentWillReceiveProps(nextProps) {
if (!this.props.user && nextProps.user) {
// login
this.props.pushState(null, '/loginSuccess');
} else if (this.props.user && !nextProps.user) {
// logout
this.props.pushState(null, '/');
}
}
static fetchData(getState, dispatch) {
const promises = [];
if (!isInfoLoaded(getState())) {
promises.push(dispatch(loadInfo()));
}
if (!isAuthLoaded(getState())) {
promises.push(dispatch(loadAuth()));
}
return Promise.all(promises);
}
handleLogout(event) {
event.preventDefault();
this.props.logout();
}
render() {
const {user} = this.props;
const styles = require('./App.scss');
return (
<div className={styles.app}>
<DocumentMeta {...meta}/>
<nav className="navbar navbar-default navbar-fixed-top">
<div className="container">
<NavbarLink to="/" className="navbar-brand" component={IndexLink}>
<div className={styles.brand}/>
React Redux Example
</NavbarLink>
<ul className="nav navbar-nav">
{user && <li><NavbarLink to="/chat">Chat</NavbarLink></li>}
<li><NavbarLink to="/widgets">Widgets</NavbarLink></li>
<li><NavbarLink to="/survey">Survey</NavbarLink></li>
<li><NavbarLink to="/about">About Us</NavbarLink></li>
{!user && <li><NavbarLink to="/login">Login</NavbarLink></li>}
{user && <li className="logout-link"><a href="/logout" onClick={::this.handleLogout}>Logout</a></li>}
</ul>
{user &&
<p className={styles.loggedInMessage + ' navbar-text'}>Logged in as <strong>{user.name}</strong>.</p>}
<ul className="nav navbar-nav navbar-right">
<li>
<a href="https://github.com/erikras/react-redux-universal-hot-example"
target="_blank" title="View on Github"><i className="fa fa-github"/></a>
</li>
</ul>
</div>
</nav>
<div className={styles.appContent}>
{this.props.children}
</div>
<InfoBar/>
<div className="well text-center">
Have questions? Ask for help <a
href="https://github.com/erikras/react-redux-universal-hot-example/issues"
target="_blank">on Github</a> or in the <a
href="http://www.reactiflux.com/" target="_blank">#react-redux-universal</a> Slack channel.
</div>
</div>
);
}
}
|
var expect = require('chai').expect,
es = require('event-stream'),
File = require('vinyl'),
render = require('../');
describe('gulp-handlebars-render', function() {
it('should render a template with data', function(done){
var fakeFile = new File({
contents: new Buffer('<h1>{{test}}</h1>'),
path: '/some/path'
});
var myRender = render({test: "test data"});
myRender.once('data', function(file){
var result = file.contents.toString();
expect(result).to.equal('<h1>test data</h1>');
done();
});
myRender.write(fakeFile);
});
it('return error with stream', function(done){
var fakeFile = new File({
contents: es.readArray(['stream', 'with', 'those', 'contents']),
path: '/some/path'
});
var myRender = render({test: "test data"});
myRender.on('error', function(err){
expect(err.message).to.equal("Streaming not supported");
done();
});
myRender.write(fakeFile);
});
});
|
test("toString", function() {
assert_equal((123).toString(), "123");
assert_equal((123.0).toString(), "123");
assert_equal((123.456).toString(), "123.456");
assert_equal(Number.POSITIVE_INFINITY.toString(), "Infinity");
assert_equal(Number.NEGATIVE_INFINITY.toString(), "-Infinity");
assert_equal(Number.NaN.toString(), "NaN");
});
test("toString throws on non-number", function() {
try {
Number.prototype.toString.call("");
assert(false);
} catch(e) {
assert(true);
}
});
test("toExponential", function() {
assert_equal((1).toExponential(), "1.0e+0");
assert_equal((1.0).toExponential(), "1.0e+0");
assert_equal((123).toExponential(), "1.23e+2");
assert_equal((0.00123).toExponential(), "1.23e-3");
assert_equal("Infinity", Infinity.toExponential());
assert_equal("-Infinity", (-Infinity).toExponential());
assert_equal("NaN", NaN.toExponential());
assert_equal(123456789..toExponential(3), "1.235e+8");
assert_equal(123456789..toExponential(NaN), "1e+8");
assert_equal(123456789..toExponential(Infinity), "1e+8");
assert_equal(123456789..toExponential(-Infinity), "1e+8");
});
test("toFixed", function() {
assert_equal("1235", 1234.5.toFixed());
assert_equal("12.35", 12.345678.toFixed(2));
assert_equal("1235", 1234.56789.toFixed(NaN));
assert_equal("1235", 1234.56789.toFixed(Infinity));
assert_equal("1235", 1234.56789.toFixed(-Infinity));
});
test("toPrecision", function() {
assert_equal("5.123456", 5.123456.toPrecision());
assert_equal("5.1235", 5.123456.toPrecision(5));
assert_equal("5.1", 5.123456.toPrecision(2));
assert_equal("5", 5.123456.toPrecision(1));
try {
123..toPrecision(NaN);
assert(false, "did not throw");
} catch(e) {
assert(e instanceof RangeError);
}
});
test("typeof", function() {
assert_equal(typeof 1, "number");
assert_equal(typeof 1.0, "number");
assert_equal(typeof Number(1), "number");
assert_equal(typeof Number(1.0), "number");
assert_equal(typeof new Number(1), "object");
assert_equal(typeof new Number(1.0), "object");
});
test("Number", function() {
assert(isNaN(Number(undefined)));
assert_equal(0, Number(null));
assert_equal(0, Number(false));
assert_equal(1, Number(true));
assert_equal(0, Number(""));
assert_equal(0, Number(" "));
assert_equal(123, Number("123"));
assert_equal(123.456, Number("123.456"));
assert_equal(5, Number({ toString: function() { return "5"; } }));
});
test("int32", function() {
assert_equal(5, 5 >> NaN);
assert_equal(5, 5 << NaN);
assert_equal(5, 5 | NaN);
assert_equal(4, 5 & 4);
assert_equal(4, 5.5 & 4.7816516);
assert_equal(-8, ~7);
assert_equal(-9, ~8.9923456789123456789123456789);
});
test("==", function() {
assert("5" == 5);
assert(5 == "5");
});
test("^", function() {
assert_equal(6, 3 ^ 5);
});
test(">>>", function() {
assert_equal(32589925, -123456789 >>> 7);
assert_equal(964506, 123456789 >>> 7);
});
test(">>", function() {
assert_equal(-964507, -123456789 >> 7);
assert_equal(964506, 123456789 >> 7);
});
|
import { Meteor } from 'meteor/meteor';
import { Match, check } from 'meteor/check';
import { LivechatVisitors } from '../../../models';
import { Livechat } from '../lib/Livechat';
Meteor.methods({
sendMessageLivechat({ token, _id, rid, msg, attachments }, agent) {
check(token, String);
check(_id, String);
check(rid, String);
check(msg, String);
check(agent, Match.Maybe({
agentId: String,
username: String,
}));
const guest = LivechatVisitors.getVisitorByToken(token, {
fields: {
name: 1,
username: 1,
department: 1,
token: 1,
},
});
if (!guest) {
throw new Meteor.Error('invalid-token');
}
return Livechat.sendMessage({
guest,
message: {
_id,
rid,
msg,
token,
attachments,
},
agent,
});
},
});
|
"use strict";
var Ember = require("ember")["default"] || require("ember");
var alias = Ember.computed.alias;
exports["default"] = Ember.Component.extend({
tagName: 'ic-autocomplete-list',
attributeBindings: [
'role',
'aria-expanded'
],
/**
* Tells the screenreader how to deal with this element.
* http://www.w3.org/TR/wai-aria/roles#listbox
*
* @property role
* @private
*/
role: 'listbox',
/**
* Tells the screenreader when this element is expanded or not.
*
* @property aria-expanded
* @private
*/
'aria-expanded': function() {
return this.get('parentView.isOpen')+'';
}.property('parentView.isOpen'),
/**
* @method registerWithParent
* @private
*/
registerWithParent: function() {
this.get('parentView').registerList(this);
}.on('didInsertElement')
});
|
var util = require('./util')
var filepath = process.argv[2]
var section = process.argv[3]
if (!filepath) {
util.fail('File path argument required')
}
if (!section) {
util.fail('Section argument required')
}
util.echo(
util.generateBatch(
util.generateVars(
util.parseIni(filepath)[section],
'user' + '_' + section
)
)
)
util.exit(0)
|
/*
* grunt-riot
*
*
* Copyright (c) 2015
* Licensed under the MIT license.
*/
'use strict';
module.exports = function (grunt) {
// load all npm grunt tasks
require('load-grunt-tasks')(grunt);
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'<%= nodeunit.tests %>'
],
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
}
},
// Before generating any new files, remove any previously-created files.
clean: {
test: ['test/tmp/**']
},
// Configuration to be run (and then tested).
riot: {
compile: {
options: {
concat: true
},
src: ['test/fixtures/test.tag','test/fixtures/todo.tag'],
dest: 'test/tmp/concatFile.js'
},
es6: {
options: {
concat: true
},
src: 'test/fixtures/es6.tag',
dest: 'test/tmp/es6.js'
}
},
// Unit tests.
nodeunit: {
tests: ['test/*_test.js']
}
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// Whenever the "test" task is run, first clean the "tmp" dir, then run this
// plugin's task(s), then test the result.
grunt.registerTask('test', ['clean', 'riot', 'nodeunit']);
grunt.registerTask('compile', ['riot']);
// By default, lint and run all tests.
grunt.registerTask('default', ['jshint', 'test', 'clean']);
};
|
import React from 'react'
import Icon from 'react-icon-base'
const TiPlus = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m30 16.7h-6.7v-6.7c0-1.8-1.5-3.3-3.3-3.3s-3.3 1.5-3.3 3.3l0.1 6.7h-6.8c-1.8 0-3.3 1.5-3.3 3.3s1.5 3.3 3.3 3.3l6.8-0.1-0.1 6.8c0 1.8 1.5 3.3 3.3 3.3s3.3-1.5 3.3-3.3v-6.8l6.7 0.1c1.8 0 3.3-1.5 3.3-3.3s-1.5-3.3-3.3-3.3z"/></g>
</Icon>
)
export default TiPlus
|
angular.module('ajoslin.promise-tracker')
.config(['$httpProvider', function($httpProvider) {
if ($httpProvider.interceptors) {
//Support angularJS 1.1+: interceptors
$httpProvider.interceptors.push(TrackerHttpInterceptor);
} else {
//Support angularJS pre 1.0.x: responseInterceptors
$httpProvider.responseInterceptors.push(TrackerResponseInterceptor);
}
}]);
/*
* Intercept all http requests that have a `tracker` option in their config,
* and add that http promise to the specified `tracker`
*/
//angular-1.1.4+ format
function TrackerResponseInterceptor($q, promiseTracker, $injector) {
//We use $injector get around circular dependency problem for $http
var $http;
return function trackerResponse(promise) {
if (!$http) {
$http = $injector.get('$http'); //lazy-load http
}
//We know the latest request is always going to be last in the list
var config = $http.pendingRequests[$http.pendingRequests.length-1];
if (config.tracker) {
if (!angular.isArray(config.tracker)) {
config.tracker = [config.tracker];
}
angular.forEach(config.tracker, function(trackerName) {
promiseTracker(trackerName).addPromise(promise, config);
});
}
return promise;
};
}
TrackerResponseInterceptor.$inject = ['$q', 'promiseTracker', '$injector'];
//angular-1.0.x format
function TrackerHttpInterceptor($q, promiseTracker) {
return {
request: function(config) {
if (config.tracker) {
if (!angular.isArray(config.tracker)) {
config.tracker = [config.tracker];
}
config.$promiseTrackerDeferred = config.$promiseTrackerDeferred || [];
angular.forEach(config.tracker, function(trackerName) {
var deferred = promiseTracker(trackerName).createPromise(config);
config.$promiseTrackerDeferred.push(deferred);
});
}
return $q.when(config);
},
response: function(response) {
if (response.config && response.config.$promiseTrackerDeferred) {
angular.forEach(response.config.$promiseTrackerDeferred, function(deferred) {
deferred.resolve(response);
});
}
return $q.when(response);
},
responseError: function(response) {
if (response.config && response.config.$promiseTrackerDeferred) {
angular.forEach(response.config.$promiseTrackerDeferred, function(deferred) {
deferred.reject(response);
});
}
return $q.reject(response);
}
};
}
TrackerHttpInterceptor.$inject = ['$q', 'promiseTracker'];
|
var Gigasecond = require('./gigasecond');
describe('Gigasecond', function() {
it('test 1', function() {
var gs = new Gigasecond(new Date(2011, 3, 25));
var expectedDate = new Date(2043, 0, 1);
expect(gs.date()).toEqual(expectedDate);
});
xit('test 2', function() {
var gs = new Gigasecond(new Date(1977, 5, 13));
var expectedDate = new Date(2009, 1, 19);
expect(gs.date()).toEqual(expectedDate);
});
xit('test 3', function() {
var gs = new Gigasecond(new Date(1959, 6, 19));
var expectedDate = new Date(1991, 2, 27);
expect(gs.date()).toEqual(expectedDate);
});
});
|
(function(){
'use strict';
function ResultController (quizData) {
var self = this;
init(self);
quizData.resultResponse
.then(function(response) {
if (!response.title) {
throw new Error('There is no solved quiz to display');
}
self.result = response;
self.pageTitle = 'Result for "' + response.title + '"';
});
self.getScore = function getScore () {
if (!self.result.totalQuestions) {
return;
}
var score = ((self.result.totalQuestions - self.result.wrongAnswers.length) /
self.result.totalQuestions) * 100;
return Math.round(score);
};
}
function init(self) {
self.pageRoute = "Home » Quizzes » <strong class='sub-title'>Result</strong>";
self.mainContentTemplate = "views/quiz/solve-quiz.html";
self.sidebarTemplate = 'views/templates/side-content/recent.html';
self.result = {};
}
angular.module('quizProjectApp.controllers')
.controller('ResultController', ['QuizDataService', ResultController]);
}());
|
require("node-opcua-service-filter");
require("./HistoryReadDetails_schema");
// < BaseType="ua:">
const ReadEventDetails_Schema = {
name: "ReadEventDetails",
baseType: "HistoryReadDetails",
fields: [
{ name: "numValuesPerNode", fieldType: "UInt32" },
{ name: "startTime", fieldType: "DateTime" },
{ name: "endTime", fieldType: "DateTime" },
{ name: "filter", fieldType: "EventFilter" }
]
};
exports.ReadEventDetails_Schema = ReadEventDetails_Schema;
|
/*
* jQuery Simply Countable plugin
* Provides a character counter for any text input or textarea
*
* @version 0.3
* @homepage http://github.com/aaronrussell/jquery-simply-countable/
* @author Aaron Russell (http://www.aaronrussell.co.uk)
*
* Copyright (c) 2009-2010 Aaron Russell (aaron@gc4.co.uk)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*/
(function($){$.fn.simplyCountable=function(options){options=$.extend({counter:'#counter',countType:'characters',maxCount:140,strictMax:false,countDirection:'down',safeClass:'safe',overClass:'over',thousandSeparator:','},options);var countable=this;var countCheck=function(){var count;if(options.countType==='words'){count=options.maxCount-countable.val().split(/[\s]+/).length;if(countable.val()===''){count+=1;}}
else{count=options.maxCount-countable.val().length;}
if(options.strictMax&&count<=0){var content=countable.val();if(options.countType==='words'){countable.val(content.split(/[\s]+/).slice(0,options.maxCount).join(' '));}
else{countable.val(content.substring(0,options.maxCount));}
count=0;}
if(!$(options.counter).hasClass(options.safeClass)&&!$(options.counter).hasClass(options.overClass)){if(count<0){$(options.counter).addClass(options.overClass);}
else{$(options.counter).addClass(options.safeClass);}}
else if(count<0&&$(options.counter).hasClass(options.safeClass)){$(options.counter).removeClass(options.safeClass).addClass(options.overClass);}
else if(count>=0&&$(options.counter).hasClass(options.overClass)){$(options.counter).removeClass(options.overClass).addClass(options.safeClass);}
if(options.countDirection==='up'){count=count-(count*2)+options.maxCount;}
if(options.thousandSeparator){count=count.toString();for(var i=count.length-3;i>0;i-=3){count=count.substr(0,i)+options.thousandSeparator+count.substr(i);}}
$(options.counter).text(count);};countCheck();countable.keyup(countCheck);};})(jQuery);
|
module.exports = function (registry) {
registry.block(function () {
var self = this
self.named('shout')
self.onContext('paragraph')
self.process(function (parent, reader) {
var lines = reader.getLines().map(function (l) { return l.toUpperCase() })
return self.createBlock(parent, 'paragraph', lines)
})
})
}
|
/**
* Webpack config for development
*/
module.exports = require('./webpack.make')({
BUILD: false,
TEST: true
})
|
// Use this file to change prototype configuration.
// Note: prototype config can be overridden using environment variables (eg on heroku)
module.exports = {
// Service name used in header. Eg: 'Renew your passport'
serviceName: "Industrial Injuries Disablement Benefit",
// Default port that prototype runs on
port: '3000',
// Enable or disable password protection on production
useAuth: 'true',
// Force HTTP to redirect to HTTPs on production
useHttps: 'true',
// Cookie warning - update link to service's cookie page.
cookieText: 'GOV.UK uses cookies to make the site simpler. <a href="#" title="Find out more about cookies">Find out more about cookies</a>',
// this could be accessed from a variety of required js modules so placed here in config
protoPaths: {
version: '/:phase/:version*', // e.g '/alpha/alpha-01/'
step: '/:phase/:version*/app/:step', // e.g '/alpha/alpha-01/app/address'
appsGlob: [
__dirname + '/views/**/index.html',
'!' + __dirname + '/views/index.html',
'!' + __dirname + '/views/**/app/index.html',
'!' + __dirname + 'views/includes/**/.*'
],
routesGlob: [
__dirname + '/views/**/version_routes.js'
]
}
};
|
var mysql = require("mysql");
function MySqlStore(opts) {
this.opts = opts || {};
if (!this.opts.hasOwnProperty("table")) {
this.opts.table = "sessions";
}
this.db = mysql.createClient(this.opts);
}
MySqlStore.prototype.add = function (uid) {
var meta = null, data = {}, cb = null, success = false;
for (var i = 1; i < arguments.length; i++) {
switch (typeof arguments[i]) {
case "function":
cb = arguments[i];
break;
case "object":
if (meta === null) {
meta = arguments[i];
} else {
data = arguments[i];
}
break;
}
}
if (meta === null) {
meta = {};
}
this.db.query("INSERT INTO `" + this.opts.table + "` (uid, meta, data) VALUES (?, ?, ?)",
[ uid, JSON.stringify(meta), JSON.stringify(data) ], function (err) {
if (err) {
return cb(err);
}
return cb(null, meta, data);
});
return this;
};
MySqlStore.prototype.uids = function (cb) {
this.db.query("SELECT uid FROM `" + this.opts.table + "`", function (err, items) {
if (err) {
return cb(err);
}
var keys = [];
for (var i = 0; i < items.length; i++) {
keys.push(items[i].uid);
}
return cb(null, keys);
});
return this;
};
MySqlStore.prototype.set = function (uid, meta, data, cb) {
var db = this.db, t = this.opts.table;
db.query("SELECT * FROM `" + t + "` WHERE uid=?", [ uid ], function (err, sessions) {
if (err || !sessions.length) {
typeof cb == "function" && cb(new Error("uid not found"));
return;
}
try {
sessions[0].meta = JSON.parse(sessions[0].meta);
} catch (e) {
sessions[0].meta = {};
}
try {
sessions[0].data = JSON.parse(sessions[0].data);
} catch (e) {
sessions[0].data = {};
}
for (k in meta) {
sessions[0].meta[k] = meta[k];
}
for (k in data) {
sessions[0].data[k] = data[k];
}
db.query("UPDATE `" + t + "` SET data = ?, meta = ? WHERE uid = ?",
[ JSON.stringify(sessions[0].data), JSON.stringify(sessions[0].meta), uid ], function (err) {
if (err) {
typeof cb == "function" && cb(new Error("Could not save new meta/data"));
return;
}
typeof cb == "function" && cb(null);
});
});
return this;
};
MySqlStore.prototype.get = function (uid) {
var key = null, cb = null;
for (var i = 1; i < arguments.length; i++) {
switch (typeof arguments[i]) {
case "string":
key = arguments[i];
break;
case "function":
cb = arguments[i];
break;
}
}
if (cb === null) {
throw new Error("missing callback");
}
this.db.query("SELECT * FROM `" + this.opts.table + "` WHERE uid = ?", [ uid ], function (err, sessions) {
if (err || !sessions.length) {
return cb(new Error("uid not found"));
}
try {
sessions[0].meta = JSON.parse(sessions[0].meta);
} catch (e) {
sessions[0].meta = {};
}
try {
sessions[0].data = JSON.parse(sessions[0].data);
} catch (e) {
sessions[0].data = {};
}
if (key === null) {
return cb(null, sessions[0].meta, sessions[0].data);
}
return cb(null, sessions[0].data.hasOwnProperty(key) ? sessions[0].data[key] : null);
});
return this;
};
MySqlStore.prototype.remove = function () {
var items = Array.prototype.slice.apply(arguments),
uid = items.shift(), cb = items.pop(),
db = this.db, t = this.opts.table;
if (items.length == 0) {
db.query("DELETE FROM `" + t + "` WHERE uid = ?", [ uid ], function () {
typeof cb == "function" && cb(null);
});
return this;
}
db.query("SELECT * FROM `" + t + "` WHERE uid = ?", [ uid ], function (err, sessions) {
if (err || !sessions.length) {
typeof cb == "function" && cb(new Error("uid not found"));
return this;
}
try {
sessions[0].data = JSON.parse(sessions[0].data);
} catch (e) {
sessions[0].data = {};
}
for (k in items) {
delete sessions[0].data[items[k]];
}
db.query("UPDATE `" + t + "` SET data = ? WHERE uid = ?",
[ JSON.stringify(sessions[0].data), uid ], function (err) {
if (err) {
typeof cb == "function" && cb(new Error("Could not remove data"));
return;
}
typeof cb == "function" && cb(null);
});
});
return this;
};
module.exports = MySqlStore;
|
import { _ } from 'meteor/underscore';
import { Meteor } from 'meteor/meteor';
import { check, Match } from 'meteor/check';
import { resourceManager } from '/server/imports/threading/resourceManager';
import { dbCompanies, getPriceLimits } from '/db/dbCompanies';
import { dbOrders } from '/db/dbOrders';
import { limitMethod } from '/server/imports/utils/rateLimit';
import { createOrder } from '/server/imports/createOrder';
import { debug } from '/server/imports/utils/debug';
Meteor.methods({
createBuyOrder(orderData) {
check(this.userId, String);
check(orderData, {
companyId: String,
unitPrice: Match.Integer,
amount: Match.Integer
});
createBuyOrder(Meteor.user(), orderData);
return true;
}
});
export function createBuyOrder(user, orderData) {
debug.log('createBuyOrder', { user, orderData });
if (user.profile.isInVacation) {
throw new Meteor.Error(403, '您現在正在渡假中,請好好放鬆!');
}
if (user.profile.notPayTax) {
throw new Meteor.Error(403, '您現在有稅單逾期未繳!');
}
if (_.contains(user.profile.ban, 'deal')) {
throw new Meteor.Error(403, '您現在被金融管理會禁止了所有投資下單行為!');
}
if (orderData.unitPrice < 1) {
throw new Meteor.Error(403, '購買單價不可小於1!');
}
if (orderData.amount < 1) {
throw new Meteor.Error(403, '購買數量不可小於1!');
}
const totalCost = orderData.unitPrice * orderData.amount;
if (user.profile.money < totalCost) {
throw new Meteor.Error(403, '剩餘金錢不足,訂單無法成立!');
}
const companyId = orderData.companyId;
const userId = user._id;
const existsSellOrderCursor = dbOrders.find({
companyId: companyId,
userId: userId,
orderType: '賣出'
});
if (existsSellOrderCursor.count() > 0) {
throw new Meteor.Error(403, '有賣出該公司股票的訂單正在執行中,無法同時下達購買的訂單!');
}
const companyData = dbCompanies.findOne(companyId, {
fields: {
_id: 1,
companyName: 1,
listPrice: 1,
lastPrice: 1,
isSeal: 1,
capital: 1,
totalValue: 1,
createdAt: 1
}
});
if (! companyData) {
throw new Meteor.Error(404, '不存在的公司股票,訂單無法成立!');
}
if (companyData.isSeal) {
throw new Meteor.Error(403, `「${companyData.companyName}」公司已被金融管理委員會查封關停了!`);
}
checkPriceError(orderData, companyData);
resourceManager.throwErrorIsResourceIsLock(['season', 'allCompanyOrders', `companyOrder${companyId}`, `user${userId}`]);
// 先鎖定資源,再重新讀取一次資料進行運算
resourceManager.request('createBuyOrder', [`companyOrder${companyId}`, `user${userId}`], (release) => {
const user = Meteor.users.findOne(userId, {
fields: {
profile: 1
}
});
const totalCost = orderData.unitPrice * orderData.amount;
if (user.profile.money < totalCost) {
throw new Meteor.Error(403, '剩餘金錢不足,訂單無法成立!');
}
const existsSellOrderCursor = dbOrders.find({
companyId: companyId,
userId: userId,
orderType: '賣出'
});
if (existsSellOrderCursor.count() > 0) {
throw new Meteor.Error(403, '有賣出該公司股票的訂單正在執行中,無法同時下達購買的訂單!');
}
const companyData = dbCompanies.findOne(companyId, {
fields: {
_id: 1,
listPrice: 1,
lastPrice: 1,
capital: 1,
totalValue: 1,
createdAt: 1
}
});
if (! companyData) {
throw new Meteor.Error(404, '不存在的公司股票,訂單無法成立!');
}
checkPriceError(orderData, companyData);
createOrder({
userId: userId,
companyId: companyId,
orderType: '購入',
unitPrice: orderData.unitPrice,
amount: orderData.amount
});
release();
});
}
function checkPriceError(orderData, companyData) {
const priceLimits = getPriceLimits(companyData);
if (orderData.unitPrice < priceLimits.lower) {
throw new Meteor.Error(403, '每股單價不可低於該股票的跌停價格!');
}
if (orderData.unitPrice > priceLimits.upper) {
throw new Meteor.Error(403, '每股單價不可大於該股票的漲停價格!');
}
}
// 兩秒鐘最多一次
limitMethod('createBuyOrder', 1, 2000);
|
window.toggleTag = function (id, tag) {
let isTurningOnFilter = true;
Array.prototype.forEach.call(
document.querySelectorAll(`#${id} [data-tag]`),
function (el, i) {
let itemTags = el.getAttribute("data-tag");
if (itemTags === tag) {
isTurningOnFilter = !el.classList.contains("is-primary");
if(isTurningOnFilter) {
el.classList.remove("is-light");
el.classList.add("is-primary");
}
else {
el.classList.add("is-light");
el.classList.remove("is-primary");
}
} else {
el.classList.add("is-light");
el.classList.remove("is-primary");
}
});
Array.prototype.forEach.call(
document.querySelectorAll(`#${id} [data-tags]`),
function (el, i) {
let itemTags = el.getAttribute("data-tags").split(",");
if(isTurningOnFilter) {
if (itemTags.includes(tag)) {
el.classList.remove("is-gone")
} else {
el.classList.add("is-gone")
}
}
else {
el.classList.remove("is-gone")
}
});
};
|
QuizEngine.module('QuizList', function(QuizList) {
// QuizList Module Must be Manually Started
QuizList.startWithParent = false;
// Router needs to be created immediately, regardless of whether or not the module is started
QuizList.controller = new QuizList.Controller();
QuizList.router = new QuizList.Router({controller: QuizList.controller});
QuizList.addInitializer(function(){
QuizList.controller.show();
});
QuizList.addFinalizer(function(){
QuizList.controller.hide();
QuizList.stopListening();
});
});
|
//testing
//test 2
//test 3
//test 4
|
beforeAll(function(){
ItemDescriberMock = function(){
//TO-DO: Implement opts to build custom describers
return [
{
type: 'user',
wrapperClass: '.w-col.w-col-4'
},
{
type: 'project',
wrapperClass: '.w-col.w-col-4'
},
{
type: 'contribution',
wrapperClass: '.w-col.w-col-2'
},
{
type: 'payment',
wrapperClass: '.w-col.w-col-2'
}
];
};
});
|
const APIError = require('../rest').APIError;
const Sort = require('../model/articleSort')
const Result = require('../model/result.js')
const Tool = require('../tool/tool')
const Check = require('../tool/check')
const DB = require('../sqlhelp/mysql')
module.exports = {
'POST /api/sort/:userId/:token': async (ctx, next) => {
let tokenResult = await Check.checkToken(ctx)
if(tokenResult.code != 0){
ctx.rest(tokenResult)
return
}
var id = ctx.params.userId,
token = ctx.params.token,
t = ctx.request.body,
m;
if (!t.sort || !t.sort.trim()) {
ctx.rest(Result.create(10,{msg:'miss sort'}))
return
}
m = new Sort(id,t.sort)
let sortResult =await Sort.save(m)
ctx.rest(sortResult)
},
'GET /api/sort/userid/:userId': async (ctx, next) => {
let paraCheckResult = Check.checkNum(ctx.params,'userId')
if(paraCheckResult){
ctx.rest(paraCheckResult)
return
}
let id = ctx.params.userId
let sortsResult = await Sort.sorts(id)
ctx.rest(sortsResult)
},
'DELETE /api/sort/:id/:userId/:token': async (ctx, next) => {
let tokenResult = await Check.checkToken(ctx)
if(tokenResult.code != 0){
ctx.rest(tokenResult)
return
}
let id = ctx.params.id
let user_id = ctx.params.userId
let token = ctx.params.token
let deleteResult =await Sort.deleteSort(id)
let sql = `update article set article_sort_id = 0 where article_sort_id = ` + id
await DB.exec(sql)
ctx.rest(deleteResult)
},
}
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M5 19h14V5H5v14zm13-5.5V16c0 .55-.45 1-1 1h-2v1.5h-1.5v-6H17c.55 0 1 .45 1 1zm-6-8h1.5v3H15v-3h1.5v3h1V10h-1v1.5H15V10h-3V5.5zm-5 0h3v6H8.5V7H7V5.5zm-1 8c0-.55.45-1 1-1h4.5c.55 0 1 .45 1 1v5H11V14h-1v3H8.5v-3h-1v4.5H6v-5z",
opacity: ".3"
}, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M15 14h1.5v1.5H15z",
opacity: ".3"
}, "1"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M7.5 14h1v3H10v-3h1v4.5h1.5v-5c0-.55-.45-1-1-1H7c-.55 0-1 .45-1 1v5h1.5V14zm6-1.5v6H15V17h2c.55 0 1-.45 1-1v-2.5c0-.55-.45-1-1-1h-3.5zm3 3H15V14h1.5v1.5z"
}, "2"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V5h14v14z"
}, "3"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M8.5 11.5H10v-6H7V7h1.5zm6.5 0h1.5V10h1V8.5h-1v-3H15v3h-1.5v-3H12V10h3z"
}, "4")], 'FourteenMpTwoTone');
exports.default = _default;
|
/**
* Copyright (c) 2008-2011 The Open Planning Project
*
* Published under the GPL license.
* See https://github.com/opengeo/gxp/raw/master/license.txt for the full text
* of the license.
*/
/**
* @requires data/WFSProtocolProxy.js
* requires GeoExt/data/FeatureStore.js
*/
/** api: (define)
* module = gxp.data
* class = WFSFeatureStore
* base_link = `Ext.data.Store <http://extjs.com/deploy/dev/docs/?class=Ext.data.Store>`_
*/
Ext.namespace("gxp.data");
gxp.data.WFSFeatureStore = Ext.extend(GeoExt.data.FeatureStore, {
/** api: config[maxFeatures]
* ``Number``
* Optional limit for number of features requested in a read. No limit
* set by default.
*/
/** api: config[ogcFilter]
* ``OpenLayers.Filter``
* Optional filter to set on the WFSProtocolProxy.
*/
/** api: config[multi]
* ``Boolean`` If set to true, geometries will be casted to Multi
* geometries before writing. No casting will be done for reading.
*/
/** api: method[setOgcFilter]
* :arg ogcFilter: ``OpenLayers.Filter`` Update the filter used by the
* protocol proxy. You must manually call load or reload to trigger
* loading.
*/
setOgcFilter: function(ogcFilter) {
this.proxy.setFilter(ogcFilter);
},
/** private */
constructor: function(config) {
if(!(config.proxy && config.proxy instanceof GeoExt.data.ProtocolProxy)) {
config.proxy = new gxp.data.WFSProtocolProxy(Ext.apply({
srsName: config.srsName,
url: config.url,
featureType: config.featureType,
featureNS: config.featureNS,
geometryName: config.geometryName,
schema: config.schema,
filter: config.ogcFilter,
maxFeatures: config.maxFeatures,
multi: config.multi
}, config.proxy));
}
if(!config.writer) {
// a writer is not used, but is required by store.save
config.writer = new Ext.data.DataWriter({
write: Ext.emptyFn
});
}
gxp.data.WFSFeatureStore.superclass.constructor.apply(this, arguments);
/**
* TODO: Determine what needs to be done to the feature reader to
* properly fit the 3.0 DataReader inteface.
*
* This method gets called with the data that goes to the reader.realize
* method. This method requires that the data has a property with the
* same name as reader.meta.idProperty. The WFSProtocolProxy prepares
* a data object for each feature, with a fid and feature property. The
* return from this method will be applied to record.data. So it makes
* sense that it looks very much like what reader.readRecords does.
*/
this.reader.extractValues = (function(data, items, length) {
var obj = this.readRecords([data.feature]);
return obj.records[0].data;
}).createDelegate(this.reader);
/**
* TODO: Determine the appropriate meta.idProperty value.
* If this is set to fid, then we can't use store.getById given a feature
* until after the feature has been saved. If this is set to id, then
* we better never have to create a new feature that represents the
* same record.
*/
this.reader.meta.idProperty = "id";
/**
* TODO: Same as above, but it seems that the getId method is responsible
* for determining the id in Ext > 3.0. This is crucial after changes
* are committed (see WFSProtocolProxy::onProtocolCommit), because the
* callback there does an isData check, which involves an attempt to get
* the id through this method.
*/
this.reader.getId = function(data) {
return data.id;
};
}
});
|
(function () {
'use strict';
angular
.module('app.dashboard')
.controller('Dashboard', Dashboard);
Dashboard.$inject = ['$state', 'dataservice', 'logger'];
function Dashboard($state, dataservice, logger) {
var vm = this;
vm.customers = [];
vm.gotoCustomer = gotoCustomer;
vm.title = 'Dashboard';
activate();
function activate() {
return getCustomers().then(function () {
logger.info('Activated Dashboard');
});
}
function getCustomers() {
return dataservice.getCustomers().then(function (data) {
vm.customers = data;
return vm.customers;
});
}
function gotoCustomer(c) {
$state.go('customer.detail', {
id: c.id
});
}
}
})();
|
var m = require('mithril');
var partial = require('chessground').util.partial;
var util = require('./util');
var arena = require('./arena');
var pairings = require('./pairings');
var playerInfo = require('./playerInfo');
var pagination = require('../pagination');
var myCurrentGameId = require('../tournament').myCurrentGameId;
module.exports = {
main: function(ctrl) {
var gameId = myCurrentGameId(ctrl);
var pag = pagination.players(ctrl);
return [
m('div.tournament_clock.title_tag', {
config: util.clock(ctrl.data.secondsToFinish)
},
m('div.time')),
util.title(ctrl),
gameId ? m('a.is.is-after.pov.button.glowed', {
href: '/' + gameId
}, [
'You are playing!',
m('span.text[data-icon=G]', ctrl.trans('joinTheGame'))
]) : null,
arena.standing(ctrl, pag),
util.games(ctrl.data.lastGames)
];
},
side: function(ctrl) {
return ctrl.vm.playerInfo.id ? playerInfo(ctrl) : pairings(ctrl);
}
};
|
describe('Audiobridge tests', function() {
var janusConnection;
var janusSession;
var audiobridgePlugin;
function randomRoomId() {
return Math.floor(Math.random() * 1000 + 1);
}
before(function() {
this.timeout(4000);
$('body').append('<audio id="audio" autoplay="true"></audio>');
return jQuery.getJSON('./config.json')
.then(function(config) {
var janus = new Janus.Client(config.url, config);
return janus.createConnection('client');
})
.then(function(connection) {
janusConnection = connection;
return connection.createSession();
})
.then(function(session) {
janusSession = session;
});
});
after(function() {
$('#audio').remove();
return janusSession.destroy()
.then(function() {
return janusConnection.close();
});
});
beforeEach(function() {
return janusSession.attachPlugin(Janus.AudiobridgePlugin.NAME)
.then(function(plugin) {
audiobridgePlugin = plugin;
});
});
afterEach(function() {
return audiobridgePlugin.detach();
});
it('creates, connects, lists', function() {
var roomId = randomRoomId();
return audiobridgePlugin.create(roomId)
.then(function(response) {
assert.equal(response.getResultText(), 'created');
return audiobridgePlugin.join(roomId);
})
.then(function(response) {
assert.equal(response.getResultText(), 'joined');
return audiobridgePlugin.list();
})
.then(function(response) {
var rooms = response.getPluginData('list');
var createdRoom = jQuery.grep(rooms, function(room) {
return room.room == roomId;
});
assert.equal(createdRoom.length, 1);
});
});
it('lists participants', function() {
var roomId = randomRoomId();
return audiobridgePlugin.create(roomId)
.then(function() {
return audiobridgePlugin.connect(roomId);
})
.then(function() {
return audiobridgePlugin.listParticipants(roomId);
})
.then(function(response) {
var participants = response.getPluginData('participants');
assert.equal(participants.length, 1);
});
});
it('changes room when connect', function() {
var roomId1 = randomRoomId();
var roomId2 = randomRoomId();
return audiobridgePlugin.create(roomId1)
.then(function() {
return audiobridgePlugin.create(roomId2);
})
.then(function() {
return audiobridgePlugin.connect(roomId1);
})
.then(function() {
return audiobridgePlugin.connect(roomId2);
})
.then(function(response) {
assert.equal(response.getResultText(), 'roomchanged');
});
});
it('starts media streaming', function(done) {
var roomId = randomRoomId();
var audio = document.getElementById('audio');
audio.addEventListener('playing', function() {
done();
});
audiobridgePlugin.on('pc:track:remote', function(event) {
assert(event.streams[0]);
adapter.browserShim.attachMediaStream(audio, event.streams[0]);
});
audiobridgePlugin.create(roomId)
.then(function() {
return audiobridgePlugin.connect(roomId);
})
.then(function() {
return audiobridgePlugin.getUserMedia({audio: true, video: false});
})
.then(function(stream) {
return audiobridgePlugin.offerStream(stream, null, {muted: false});
});
});
it.skip('stops media on detach', function() {
var roomId = randomRoomId();
var audio = document.getElementById('audio');
return audiobridgePlugin.create(roomId)
.then(function() {
return audiobridgePlugin.connect(roomId);
})
.then(function() {
return audiobridgePlugin.getUserMedia({audio: true, video: false});
})
.then(function(stream) {
return audiobridgePlugin.offerStream(stream, null, {muted: false});
})
.delay(1000)
.then(function() {
assert.strictEqual(audio.paused, false);
return audiobridgePlugin.detach();
})
.delay(300)
.then(function() {
assert.strictEqual(audio.paused, true);
});
});
});
|
/**
* @author Richard Davey @photonstorm
* @copyright 2015 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
PhaserNano.Cache = function (game) {
this.game = game;
this._cache = {
image: {}
};
};
PhaserNano.Cache.prototype = {
addImage: function (key, url, img, frameWidth, frameHeight, frameMax, margin, spacing) {
var frameData = new PhaserNano.FrameData();
if (frameWidth !== undefined)
{
this.buildSheet(frameData, img, frameWidth, frameHeight, frameMax, margin, spacing);
}
else
{
frameData.addFrame(0, 0, img.width, img.height, key);
}
this.addImageEntry(key, url, img, frameData);
},
// Private
addImageEntry: function (key, url, img, frames) {
var obj = {
key: key,
url: url,
data: img,
base: new PhaserNano.BaseTexture(img, frames)
};
if (this.game.pixelArt)
{
obj.base.scaleMode = 1;
}
// WebGL only
this.game.renderer.loadTexture(obj.base);
this._cache.image[key] = obj;
},
addTextureAtlas: function (key, url, img, json) {
if (!json['frames'])
{
console.warn("Invalid Atlas JSON");
return;
}
var width = img.width;
var height = img.height;
var frameData = new PhaserNano.FrameData();
if (Array.isArray(json.frames))
{
for (var i = 0; i < json.frames.length; i++)
{
frameData.add(json.frames[i], width, height, json.frames[i].filename);
}
}
else
{
for (var name in json.frames)
{
frameData.add(json.frames[name], width, height, name);
}
}
this.addImageEntry(key, url, img, frameData);
},
buildSheet: function (frameData, img, frameWidth, frameHeight, frameMax, margin, spacing) {
var width = img.width;
var height = img.height;
if (frameWidth <= 0)
{
frameWidth = Math.floor(-width / Math.min(-1, frameWidth));
}
if (frameHeight <= 0)
{
frameHeight = Math.floor(-height / Math.min(-1, frameHeight));
}
var row = Math.floor((width - margin) / (frameWidth + spacing));
var column = Math.floor((height - margin) / (frameHeight + spacing));
var total = row * column;
if (frameMax !== -1)
{
total = frameMax;
}
// Zero or smaller than frame sizes?
if (width === 0 || height === 0 || width < frameWidth || height < frameHeight || total === 0)
{
return;
}
var x = margin;
var y = margin;
for (var i = 0; i < total; i++)
{
frameData.addFrame(x, y, frameWidth, frameHeight);
x += frameWidth + spacing;
if (x + frameWidth > width)
{
x = margin;
y += frameHeight + spacing;
}
}
},
getTexture: function (key) {
if (this._cache.image[key])
{
return this._cache.image[key].base;
}
else
{
console.warn('No texture found matching key', key);
}
},
getImage: function (key, full) {
var img = this._cache.image[key];
if (full)
{
return img;
}
else
{
return img.data;
}
}
};
|
adblock = false;
|
const path = require('path');
module.exports = {
module: {
loaders: [
{
test: /\.css/,
exclude: /node_modules/,
loaders: ['style', 'css?modules&importLoaders=1', 'postcss-loader'],
},
{
test: /.(png|gif|jpe?g)(\?[a-z0-9=\.]+)?$/,
loader: 'url',
query: {
limit: 10240,
name: '[name]-[hash:6].[ext]',
},
},
],
},
resolve: {
alias: {
vclub: path.resolve('./src'),
},
},
};
|
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
nodeunit: {
files: ['test/**/*_test.js'],
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
gruntfile: {
src: 'Gruntfile.js'
},
lib: {
src: ['lib/**/*.js']
},
test: {
src: ['test/**/*.js']
},
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
lib: {
files: '<%= jshint.lib.src %>',
tasks: ['jshint:lib']
},
test: {
files: '<%= jshint.test.src %>',
tasks: ['jshint:test']
},
},
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
// Default task.
grunt.registerTask('default', ['jshint', 'nodeunit']);
};
|
module.exports = function (math) {
var util = require('../../util/index.js'),
Complex = require('../../type/Complex.js'),
Unit = require('../../type/Unit.js'),
collection = require('../../type/collection.js'),
isNumBool = util.number.isNumBool,
isComplex = Complex.isComplex,
isUnit = Unit.isUnit,
isCollection = collection.isCollection;
/**
* Calculate the cotangent of a value. cot(x) is defined as 1 / tan(x)
*
* cot(x)
*
* For matrices, the function is evaluated element wise.
*
* @param {Number | Boolean | Complex | Unit | Array | Matrix} x
* @return {Number | Complex | Array | Matrix} res
*/
math.cot = function cot(x) {
if (arguments.length != 1) {
throw new util.error.ArgumentsError('cot', arguments.length, 1);
}
if (isNumBool(x)) {
return 1 / Math.tan(x);
}
if (isComplex(x)) {
var den = Math.exp(-4.0 * x.im) -
2.0 * Math.exp(-2.0 * x.im) * Math.cos(2.0 * x.re) + 1.0;
return new Complex(
2.0 * Math.exp(-2.0 * x.im) * Math.sin(2.0 * x.re) / den,
(Math.exp(-4.0 * x.im) - 1.0) / den
);
}
if (isUnit(x)) {
if (!x.hasBase(Unit.BASE_UNITS.ANGLE)) {
throw new TypeError ('Unit in function cot is no angle');
}
return 1 / Math.tan(x.value);
}
if (isCollection(x)) {
return collection.map(x, cot);
}
if (x.valueOf() !== x) {
// fallback on the objects primitive value
return cot(x.valueOf());
}
throw new util.error.UnsupportedTypeError('cot', x);
};
};
|
var wifilocation = require('../');
var should = require('should');
require('mocha');
var towers = [
{ mac: 'bc:ae:c5:c3:dd:56',
ssid: 'Arconet Camp',
signal_level: '-75' },
{ mac: '5c:d9:98:5a:93:72',
ssid: 'Arconet',
signal_level: '-73' },
{ mac: '1c:af:f7:ce:fb:f9',
ssid: 'Arconet',
signal_level: '-62' },
{ mac: '00:24:a5:15:d2:c2',
ssid: 'Arconet Amphitheatre',
signal_level: '-69' }
];
var arcosanti = {
accuracy: 26,
latitude: 34.3427953,
longitude: -112.1003188
};
describe('wifi-location', function() {
describe('getTowers()', function() {
it('should work', function(done) {
this.timeout(10000);
wifilocation.getTowers(function(err, towers){
should.not.exist(err);
should.exist(towers);
done();
});
});
});
describe('getLocation()', function() {
it('should work', function(done) {
this.timeout(10000);
wifilocation.getLocation(towers, function(err, loc){
should.not.exist(err);
should.exist(loc);
loc.should.eql(arcosanti);
done();
});
});
});
});
|
define(['exports'], function (exports) { 'use strict';
const a = 1;
const b = 2;
exports.a = a;
exports.b = b;
});
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2020 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
var GetFastValue = require('../utils/object/GetFastValue');
var UppercaseFirst = require('../utils/string/UppercaseFirst');
/**
* Builds an array of which physics plugins should be activated for the given Scene.
*
* @function Phaser.Scenes.GetPhysicsPlugins
* @since 3.0.0
*
* @param {Phaser.Scenes.Systems} sys - The scene system to get the physics systems of.
*
* @return {array} An array of Physics systems to start for this Scene.
*/
var GetPhysicsPlugins = function (sys)
{
var defaultSystem = sys.game.config.defaultPhysicsSystem;
var sceneSystems = GetFastValue(sys.settings, 'physics', false);
if (!defaultSystem && !sceneSystems)
{
// No default physics system or systems in this scene
return;
}
// Let's build the systems array
var output = [];
if (defaultSystem)
{
output.push(UppercaseFirst(defaultSystem + 'Physics'));
}
if (sceneSystems)
{
for (var key in sceneSystems)
{
key = UppercaseFirst(key.concat('Physics'));
if (output.indexOf(key) === -1)
{
output.push(key);
}
}
}
// An array of Physics systems to start for this Scene
return output;
};
module.exports = GetPhysicsPlugins;
|
version https://git-lfs.github.com/spec/v1
oid sha256:1d68d7bd871ab59346264fb1d50addc56c1ea780e7878f34baddde5346dcf58e
size 2347
|
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import { syncHistoryWithStore, routerMiddleware } from 'react-router-redux';
import App from './components/App';
import MainRecipe from './components/MainRecipe';
import Profile from './components/Profile';
import Dashboard from './components/Dashboard';
import Discover from './components/Discover';
import SearchResults from './components/SearchResults';
import ImageUpload from './components/ImageUpload.js';
import CreateRecipe from './components/CreateRecipe';
import Landing from './components/Landing';
import rootReducer from './reducers';
const middleware = routerMiddleware(browserHistory);
// createStore accepts a single reducer or a collection of reducers
const store = createStore(rootReducer, applyMiddleware(middleware));
const history = syncHistoryWithStore(browserHistory, store);
const render = function () {
ReactDOM.render(
<Provider store={store}>
<div>
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={Landing} />
<Route path="/dashboard" component={Dashboard} />
<Route path="/landing" component={Landing} />
<Route path="/discover" component={Discover} />
<Route path="/profile/:user_id" component={Profile} />
<Route path="/recipe/:id" component={MainRecipe} />
<Route path="/create" component={CreateRecipe} />
<Route path="/search" component={SearchResults} />
<Route path="/*" component={Dashboard} />
</Route>
</Router>
</div>
</Provider>,
document.getElementById('app')
);
};
render();
store.subscribe(render);
|
/* global process: true */
module.exports = function(config) { 'use strict';
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
frameworks: ['jasmine', 'commonjs'],
// list of files / patterns to load in the browser
files: [
'Library/jquery-1.10.2.js',
'Library/angular.js',
'Library/angular-mocks.js',
'TestSearch.js'
],
// list of files to exclude
exclude: [
],
preprocessors: {
'client/*.js': ['commonjs'],
'test/client/*.js': ['commonjs']
},
// use dots reporter, as travis terminal does not support escaping sequences
// possible values: 'dots', 'progress'
// CLI --reporters progress
reporters: ['progress', 'junit'],
junitReporter: {
// will be resolved to basePath (in the same way as files/exclude patterns)
outputFile: 'test-results.xml'
},
// web server port
// CLI --port 9876
port: 9876,
// enable / disable colors in the output (reporters and logs)
// CLI --colors --no-colors
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
// CLI --log-level debug
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
// CLI --auto-watch --no-auto-watch
autoWatch: true,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
// CLI --browsers Chrome,Firefox,Safari
browsers: [process.env.TRAVIS ? 'Firefox' : 'Chrome'],
// browsers: ['PhantomJS'],
// If browser does not capture in given timeout [ms], kill it
// CLI --capture-timeout 5000
captureTimeout: 20000,
// Auto run tests on start (when browsers are captured) and exit
// CLI --single-run --no-single-run
singleRun: false,
// report which specs are slower than 500ms
// CLI --report-slower-than 500
reportSlowerThan: 500,
plugins: [
'karma-jasmine',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-junit-reporter',
'karma-commonjs'
]
});
};
|
/**
* Copyright © 2016-present Kriasoft.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
/* eslint-env jest */
import Context from '../Context';
describe('Context', () => {
test('ensureIsAuthenticated()', () => {
const ctx1 = new Context({ user: null });
const ctx2 = new Context({ user: {} });
expect(() => ctx1.ensureIsAuthenticated()).toThrow();
expect(() => ctx2.ensureIsAuthenticated()).not.toThrow();
});
});
|
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {Fiber} from 'react-reconciler/src/ReactFiber';
import {
REACT_ASYNC_MODE_TYPE,
REACT_CONTEXT_TYPE,
REACT_FORWARD_REF_TYPE,
REACT_FRAGMENT_TYPE,
REACT_PORTAL_TYPE,
REACT_PROFILER_TYPE,
REACT_PROVIDER_TYPE,
REACT_STRICT_MODE_TYPE,
REACT_TIMEOUT_TYPE,
} from 'shared/ReactSymbols';
function getComponentName(fiber: Fiber): string | null {
const {type} = fiber;
if (typeof type === 'function') {
return type.displayName || type.name;
}
if (typeof type === 'string') {
return type;
}
switch (type) {
case REACT_ASYNC_MODE_TYPE:
return 'AsyncMode';
case REACT_CONTEXT_TYPE:
return 'Context.Consumer';
case REACT_FRAGMENT_TYPE:
return 'ReactFragment';
case REACT_PORTAL_TYPE:
return 'ReactPortal';
case REACT_PROFILER_TYPE:
return `Profiler(${fiber.pendingProps.id})`;
case REACT_PROVIDER_TYPE:
return 'Context.Provider';
case REACT_STRICT_MODE_TYPE:
return 'StrictMode';
case REACT_TIMEOUT_TYPE:
return 'Timeout';
}
if (typeof type === 'object' && type !== null) {
switch (type.$$typeof) {
case REACT_FORWARD_REF_TYPE:
const functionName = type.render.displayName || type.render.name || '';
return functionName !== ''
? `ForwardRef(${functionName})`
: 'ForwardRef';
}
}
return null;
}
export default getComponentName;
|
var Person = function (fn, ln, ag, gen) {
this.firstName = "" || fn;
this.lastName = "" || ln;
this.age = 0 || ag;
this.gender = "" || gen;
};
|
import React from 'react'
import Icon from 'react-icon-base'
const GoRuby = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m30 5h-20l-10 10 20 20 20-20-10-10z m-25 10l7.5-7.5h15l7.5 7.5-15 15-15-15z m22.5-5h-7.5v17.5l12.5-12.5-5-5z"/></g>
</Icon>
)
export default GoRuby
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
const concat = require('concat-stream');
const debug = require('debug')('RNP:Symbolication');
const net = require('net');
const temp = require('temp');
const xpipe = require('xpipe');var _require =
require('./util');const LazyPromise = _require.LazyPromise,LockingPromise = _require.LockingPromise;var _require2 =
require('child_process');const fork = _require2.fork;
const affixes = { prefix: 'metro-bundler-symbolicate', suffix: '.sock' };
const childPath = require.resolve('./worker');
exports.createWorker = () => {
// There are issues with named sockets on windows that cause the connection to
// close too early so run the symbolicate server on a random localhost port.
const socket = process.platform === 'win32' ?
34712 :
xpipe.eq(temp.path(affixes));
const child = new LockingPromise(new LazyPromise(() => startupChild(socket)));
return (stack, sourceMaps) =>
child.
then(() => connectAndSendJob(socket, message(stack, sourceMaps))).
then(JSON.parse).
then(response =>
'error' in response ?
Promise.reject(new Error(response.error)) :
response.result);
};
function startupChild(socket) {
const child = fork(childPath);
return new Promise((resolve, reject) => {
child.
once('error', reject).
once('message', () => {
child.removeAllListeners();
resolve(child);
});
// $FlowFixMe ChildProcess.send should accept any type.
child.send(socket);
});
}
function connectAndSendJob(socket, data) {
const job = new Promise((resolve, reject) => {
debug('Connecting to worker');
const connection = net.createConnection(socket);
connection.setEncoding('utf8');
connection.on('error', reject);
connection.pipe(concat(resolve));
debug('Sending data to worker');
connection.end(data);
});
job.then(() => debug('Received response from worker'));
return job;
}
function message(stack, sourceMaps) {
return JSON.stringify({ maps: Array.from(sourceMaps), stack });
}
|
import { h, computed } from 'vue'
import QIcon from '../icon/QIcon.js'
import { createComponent } from '../../utils/private/create.js'
import { hMergeSlot } from '../../utils/private/render.js'
import useRouterLink, { useRouterLinkProps } from '../../composables/private/use-router-link.js'
export default createComponent({
name: 'QBreadcrumbsEl',
props: {
...useRouterLinkProps,
label: String,
icon: String,
tag: {
type: String,
default: 'span'
}
},
setup (props, { slots }) {
const { linkTag, linkProps, linkClass, hasRouterLink, navigateToRouterLink } = useRouterLink()
const data = computed(() => {
const acc = {
class: 'q-breadcrumbs__el q-link '
+ 'flex inline items-center relative-position '
+ (props.disable !== true ? 'q-link--focusable' + linkClass.value : 'q-breadcrumbs__el--disable'),
...linkProps.value
}
if (hasRouterLink.value === true) {
acc.onClick = navigateToRouterLink
}
return acc
})
const iconClass = computed(() =>
'q-breadcrumbs__el-icon'
+ (props.label !== void 0 ? ' q-breadcrumbs__el-icon--with-label' : '')
)
return () => {
const child = []
props.icon !== void 0 && child.push(
h(QIcon, {
class: iconClass.value,
name: props.icon
})
)
props.label !== void 0 && child.push(props.label)
return h(
linkTag.value,
{ ...data.value },
hMergeSlot(slots.default, child)
)
}
}
})
|
import React from 'react';
import PropTypes from 'prop-types';
import { Box } from '@strapi/design-system/Box';
import { Flex } from '@strapi/design-system/Flex';
import { PaginationURLQuery, PageSizeURLQuery } from '@strapi/helper-plugin';
export const PaginationFooter = ({ pagination }) => {
return (
<Box paddingTop={6}>
<Flex alignItems="flex-end" justifyContent="space-between">
<PageSizeURLQuery />
<PaginationURLQuery pagination={pagination} />
</Flex>
</Box>
);
};
PaginationFooter.defaultProps = {
pagination: {
pageCount: 0,
pageSize: 10,
total: 0,
},
};
PaginationFooter.propTypes = {
pagination: PropTypes.shape({
page: PropTypes.number,
pageCount: PropTypes.number,
pageSize: PropTypes.number,
total: PropTypes.number,
}),
};
|
// Generated by CoffeeScript 1.7.0
(function() {
module.exports = {
hygienist: require('hygienist-middleware'),
escapist: require('escapist-middleware'),
archivist: require('archivist-middleware'),
alchemist: require('alchemist-middleware'),
apologist: require('apology-middleware'),
publicist: require('publicist-middleware'),
columnist: require('morgan'),
pathologist: require('pathologist-middleware'),
journalist: require('infestor'),
minimist: require('compression')
};
}).call(this);
|
version https://git-lfs.github.com/spec/v1
oid sha256:068786890121429e2842abf7fd11c372a76064ca662fdc4e1a66da82c565927d
size 260571
|
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
// https://github.com/Microsoft/ChakraCore/issues/5492
const blah = {"\0":"hi","\0\0":"hello"};
for (var i in new Proxy(blah, {})) console.log(blah[i]);
|
import {Resource} from '../resource';
export class ValidationModel {
constructor() {
this.resource = new Resource();
this.rules = [];
}
}
|
function registerSubmitHandler(formId){
$("form#" + formId + " button#submitProfile").click(function(){
$("form#" + formId).find("input, select").each(function (){
var id = $(this).attr("id");
var value;
console.log(id);
if ($(this).prop("tagName").toLowerCase() == "select")
{
value = $(this).find("option:selected").text();
}
else
{
value = $(this).val();
}
$("#confirmDetails #acme_bscenebundle_account_" + id).text(value);
});
});
};
|
/**
* @module helpers/x/renderer3d
*/
import ControlsTrackball from '../../controls/controls.trackball';
export default class {
constructor(containerId='r3d') {
this._container = null;
this._renderer = null;
this._camera = null;
this._controls = null;
this._scene = null;
this._initRenderer(containerId);
this._initCamera();
this._initScene();
this._initControls();
// setup event listeners
this._onWindowResize = this._onWindowResize.bind(this);
this.addEventListeners();
}
set container(container) {
this._container = container;
}
get container() {
return this._container;
}
add(obj) {
this._scene.add(obj);
}
addEventListeners() {
window.addEventListener('resize', this._onWindowResize, false);
}
removeEventListeners() {
window.removeEventListener('resize', this._onWindowResize, false);
}
center(worldPosition) {
// update camrea's and control's target
this._camera.lookAt(worldPosition.x, worldPosition.y, worldPosition.z);
this._camera.updateProjectionMatrix();
this._controls.target.set(worldPosition.x, worldPosition.y,
worldPosition.z);
}
animate() {
this._controls.update();
this._renderer.render(this._scene, this._camera);
// request new frame
requestAnimationFrame(this.animate.bind(this));
}
// private methods
_onWindowResize() {
this._camera.aspect =
this._container.clientWidth / this._container.clientHeight;
this._camera.updateProjectionMatrix();
this._renderer.setSize(this._container.clientWidth,
this._container.clientHeight);
}
_initRenderer(containerId) {
// renderer
this._container = document.getElementById(containerId);
this._renderer = new THREE.WebGLRenderer({
antialias: true,
});
this._renderer.setSize(this._container.clientWidth,
this._container.clientHeight);
this._renderer.setClearColor(0x424242, 1);
this._renderer.setPixelRatio(window.devicePixelRatio);
this._container.appendChild(this._renderer.domElement);
}
_initCamera() {
this._camera = new THREE.PerspectiveCamera(45,
this._container.clientWidth / this._container.clientHeight, 1, 10000000);
this._camera.position.x = 250;
this._camera.position.y = 250;
this._camera.position.z = 250;
}
_initScene() {
// add some lights to the scene by default
this._scene = new THREE.Scene();
// ambient
this._scene.add(new THREE.AmbientLight(0x353535));
// directional 1
let directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(200, 200, 1000).normalize();
this._scene.add(directionalLight);
// directional 2
let directionalLight2 = new THREE.DirectionalLight(0xffffff, 1);
directionalLight2.position.set(-200, -200, -1000).normalize();
this._scene.add(directionalLight2);
}
_initControls() {
// controls
this._controls = new ControlsTrackball(this._camera, this._container);
this._controls.rotateSpeed = 1.4;
this._controls.zoomSpeed = 1.2;
this._controls.panSpeed = 0.8;
}
}
|
declare module 'fbt' {
declare opaque type GC$NOT_A_PERSON: number;
declare opaque type GC$FEMALE_SINGULAR: number;
declare opaque type GC$MALE_SINGULAR: number;
declare opaque type GC$FEMALE_SINGULAR_GUESS: number;
declare opaque type GC$MALE_SINGULAR_GUESS: number;
declare opaque type GC$MIXED_SINGULAR: number;
declare opaque type GC$MIXED_PLURAL: number;
declare opaque type GC$NEUTER_SINGULAR: number;
declare opaque type GC$UNKNOWN_SINGULAR: number;
declare opaque type GC$FEMALE_PLURAL: number;
declare opaque type GC$MALE_PLURAL: number;
declare opaque type GC$NEUTER_PLURAL: number;
declare opaque type GC$UNKNOWN_PLURAL: number;
declare export var GenderConst: {|
NOT_A_PERSON: GC$NOT_A_PERSON,
FEMALE_SINGULAR: GC$FEMALE_SINGULAR,
MALE_SINGULAR: GC$MALE_SINGULAR,
FEMALE_SINGULAR_GUESS: GC$FEMALE_SINGULAR_GUESS,
MALE_SINGULAR_GUESS: GC$MALE_SINGULAR_GUESS,
MIXED_SINGULAR: GC$MIXED_SINGULAR,
MIXED_PLURAL: GC$MIXED_PLURAL,
NEUTER_SINGULAR: GC$NEUTER_SINGULAR,
UNKNOWN_SINGULAR: GC$UNKNOWN_SINGULAR,
FEMALE_PLURAL: GC$FEMALE_PLURAL,
MALE_PLURAL: GC$MALE_PLURAL,
NEUTER_PLURAL: GC$NEUTER_PLURAL,
UNKNOWN_PLURAL: GC$UNKNOWN_PLURAL,
|};
declare opaque type IV$BITMASK_NUMBER: number;
declare opaque type IV$BITMASK_GENDER: number;
declare opaque type IV$NUMBER_ZERO: number;
declare opaque type IV$NUMBER_ONE: number;
declare opaque type IV$NUMBER_TWO: number;
declare opaque type IV$NUMBER_FEW: number;
declare opaque type IV$NUMBER_MANY: number;
declare opaque type IV$NUMBER_OTHER: number;
declare opaque type IV$GENDER_MALE: number;
declare opaque type IV$GENDER_FEMALE: number;
declare opaque type IV$GENDER_UNKNOWN: number;
declare type IntlGenderVariations = {|
GENDER_MALE: IV$GENDER_MALE,
GENDER_FEMALE: IV$GENDER_FEMALE,
GENDER_UNKNOWN: IV$GENDER_UNKNOWN,
|};
declare export var IntlVariations: {|
...IntlGenderVariations,
BITMASK_NUMBER: IV$BITMASK_NUMBER,
BITMASK_GENDER: IV$BITMASK_GENDER,
NUMBER_ZERO: IV$NUMBER_ZERO,
NUMBER_ONE: IV$NUMBER_ONE,
NUMBER_TWO: IV$NUMBER_TWO,
NUMBER_FEW: IV$NUMBER_FEW,
NUMBER_MANY: IV$NUMBER_MANY,
NUMBER_OTHER: IV$NUMBER_OTHER,
|};
declare export type IntlVariationsValues = $Values<typeof IntlVariations>;
declare export var IntlViewerContext: {|
GENDER: IntlVariationsValues,
locale: string,
|};
declare export type Translations = {
[locale: string]: {
[key: string]: string,
},
};
declare export var init: ({|
translations: Translations,
|}) => void;
declare export type Options = {|
author?: string,
project?: string,
preserveWhitespace?: boolean,
subject?: IntlVariationsValues,
common?: boolean,
doNotExtract?: boolean,
|};
declare export var FbtTranslations: {
getTranslatedPayload<T>(
hashKey: string,
enumHashKey?: string,
args?: T
): ?{|
table: string,
args: T,
|},
isComponentScript(): boolean,
registerTranslations(Translations): void,
};
declare export type PluralOptions = {|
many?: string,
showCount?: 'yes' | 'no' | 'ifMany',
name?: string,
value?: mixed,
|};
declare export type ParamOptions = {|
gender?: $Values<IntlGenderVariations>,
number?: number | true,
|};
declare export type EnumValue = string | number;
// https://github.com/facebookincubator/fbt/blob/c2d363a40b622d5aaf80ff1d249b38604fd869f6/transform/babel-plugin-fbt/FbtConstants.js#L22-L27 ===> https://github.com/facebookincubator/fbt/blob/ffadd5fadd68179a2f0c3cde36ed080a49804203/runtime/shared/fbt.js#L64-L70
declare export type PronounType =
| 'object'
| 'possessive'
| 'reflexive'
| 'subject';
declare export type PronounOptions = {|
human?: boolean,
capitalize?: boolean,
|};
declare export type FbtResult = string;
declare export interface Fbt {
(source: string, desc: string, options?: Options): FbtResult;
param(paramName: string, value: mixed, options?: ParamOptions): FbtResult;
sameParam(paramName: string): FbtResult;
name(name: string, gender: $Values<IntlGenderVariations>): FbtResult;
plural(
singularPhrase: string,
count: number,
options?: PluralOptions
): FbtResult;
enum<Range: { [enumKey: string]: EnumValue }, RangeKeys: $Keys<Range>>(
enumKey: RangeKeys,
enumRange: Range
): FbtResult;
enum(index: number, enumRange: Array<EnumValue>): FbtResult;
pronoun(
type: PronounType,
gender: $Values<typeof GenderConst>,
options: PronounOptions
): FbtResult;
}
declare export var fbt: Fbt;
declare export default Fbt;
}
|
import Ember from 'ember';
import AnimationSupportMixin from 'ember-magma/mixins/animation-support';
import { module, test } from 'qunit';
module('Unit | Mixin | animation support');
// Replace this with your real tests.
test('it works', function (assert) {
var AnimationSupportObject = Ember.Object.extend(AnimationSupportMixin);
var subject = AnimationSupportObject.create();
assert.ok(subject);
});
test('animate', function (assert) {
let AnimationSupportObject = Ember.Object.extend(AnimationSupportMixin);
let subject = AnimationSupportObject.create();
subject.$ = $;
Ember.run(() => {
subject.animate('fadeIn');
});
let animation1 = subject.get('animations').objectAt(0);
assert.ok(animation1.animation === 'fadeIn', 'Animation is loaded');
assert.ok(animation1.target === '', 'Target is valid');
Ember.run(() => {
subject.animate('fadeOut', '.target');
});
let animation2 = subject.get('animations').objectAt(1);
assert.ok(animation2.animation === 'fadeOut', 'Animation is loaded');
assert.ok(animation2.target === '.target', 'Target is valid');
});
test('stopAnimation', function (assert) {
var AnimationSupportObject = Ember.Object.extend(AnimationSupportMixin);
var subject = AnimationSupportObject.create();
subject.$ = $;
Ember.run(() => {
subject.animate('fadeIn');
subject.stopAnimation();
});
assert.ok(subject.get('animations.length') === 0, 'Animation has been removed');
});
|
/*jslint node: true */
module.exports = function(grunt) {
var apigee_conf = require('./apigee-config.js')
var helper = require('./libs/helper-functions.js');
var searchNReplace = require('./conf/search-and-replace-files.js');
//var apigee_common = require('./libs/apigee-grunt-common.js');
require('load-grunt-tasks')(grunt);
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
apigee_profiles : apigee_conf.profiles(grunt),//{
clean: ["target"],
mkdir: {
all: {
options: {
create: ['target']
},
},
},
copy: {
main: {
files : [{
src: 'apiproxy/**',
dest: 'target/',
},
{
expand : true,
src: './node/*',
dest: './target/apiproxy/resources/node/', filter: 'isFile', flatten: true
},
]
}
},
// make a zipfile
compress: {
node_modules: helper.setNodeResources({
mode : 'zip',
archive: './target/apiproxy/resources/node/node_modules.zip'
}, [
{expand: true, cwd: './node/node_modules/', src: ['**'], dest: 'node_modules/' } // makes all src relative to cwd
]),
node_public: helper.setNodeResources({
mode : 'zip',
archive: './target/apiproxy/resources/node/public.zip'
},[
{expand: true, cwd: './node/public/', src: ['**'], dest: 'public/' }, // makes all src relative to cwd
]),
node_resources: helper.setNodeResources({
mode : 'zip',
archive: './target/apiproxy/resources/node/resources.zip'
},[
{expand: true, cwd: './node/resources/', src: ['**'], dest: 'resources/' }, // makes all src relative to cwd
]),
main: {
options: {
mode : 'zip',
archive: function(){
var ap = grunt.config.get("apigee_profiles")
return 'target/' + ap[ap.env].apiproxy + ".zip"
}
},
files: [
{expand: true, cwd: 'target/apiproxy/', src: ['**'], dest: 'apiproxy/' }, // makes all src relative to cwd
]
}
},
// task for configuration management: search and replace elements within XML files
xmlpoke: apigee_conf.config(apigee_conf.profiles(grunt).env),
// Configure a mochaTest task
mochaTest: {
test: {
options: {
reporter: 'spec',
timeout : 5000
},
src: ['tests/**.js']
}
},
jshint: {
options: { //see options reference http://www.jshint.com/docs/options/
curly: true,
eqeqeq: true,
eqnull: true,
browser: true,
asi : true,
debug : true,
undef : true,
unused : true,
maxcomplexity : 5,
reporter: require('jshint-stylish')
},
all: ['Gruntfile.js', 'apiproxy/**/*.js', 'tests/**/*.js', 'tasks/*.js']
},
eslint: { // task
options: {
config: 'conf/eslint.json', // custom config
rulesdir: ['conf/rules'] // custom rules
},
target: ['Gruntfile.js', 'apiproxy/**/*.js', 'tests/**/*.js', 'tasks/*.js'] // array of files
},
'string-replace': {
dist : searchNReplace.searchAndReplaceFiles(apigee_conf.profiles(grunt).env)
},
})
grunt.registerTask('buildApiBundle', 'Build zip without importing it to Edge', ['jshint', 'eslint', 'clean', 'mkdir','copy', 'xmlpoke', 'string-replace','compress']);
// Default task(s).
//delete and then import revision keeping same id
grunt.registerTask('default', [ 'buildApiBundle', 'getDeployedApiRevisions', 'undeployApiRevision',
'deleteApiRevision', 'importApiBundle', 'deployApiRevision', 'executeTests']);
grunt.loadTasks('tasks');
if(grunt.option.flags().indexOf('--help') === -1 && !apigee_conf.profiles(grunt).env) {
grunt.fail.fatal('Invalid environment flag --env={env}. Provide environment as argument, see apigee_profiles in Grunfile.js.')
}
};
|
/**
* The map center objects specifies a map location where the map can be centered on
*
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* MapCenter Schema
*/
var FeatureStyleSchema = new Schema({
name: {
type: String,
trim: true,
default: '',
required:true,
form: {label:'Name'},
list:true
},
weight: {
type: Number,
trim: true,
default: 2,
required:true,
form: {label:'Font weight'},
},
color: {
type: String,
trim: true,
default: 'white',
required:true,
form: {label:'Font color'},
},
opacity: {
type: Number,
trim: true,
default: 1.0,
required:true,
form: {label:'Font opacity'},
},
dashArray: {
type: String,
trim: true,
default: '3',
required:true,
form: {label:'Distance between dashes'},
},
fillColor: {
type: String,
trim: true,
default: '#666666',
required:true,
form: {label:'Background color'},
},
fillOpacity: {
type: Number,
trim: true,
default: 0.3,
required:true,
form: {label:'Background opacity'},
}
});
var FeatureStyle;
try {
FeatureStyle = mongoose.model('FeatureStyle');
} catch (e) {
FeatureStyle = mongoose.model('FeatureStyle', FeatureStyleSchema);
}
|
import moment from "moment";
import defaultRegex from "../regex/defaults";
const creditCard = value => {
const replaceValue = value.replace(/-/g, "");
if (defaultRegex.startOfVisa.test(replaceValue)) {
const regex = /^4[0-9]{12}(?:[0-9]{3})?$/;
return regex.test(replaceValue);
} else if (defaultRegex.startOfMastercard.test(replaceValue)) {
const regex = /^5[1-5][0-9]{14}$/;
return regex.test(replaceValue);
} else if (defaultRegex.startOfAmEx.test(replaceValue)) {
const regex = /^3[47][0-9]{13}$/;
return regex.test(replaceValue);
} else if (defaultRegex.startOfDiscover.test(replaceValue)) {
const regex = /^6(?:011|5[0-9]{2})[0-9]{12}$/;
return regex.test(replaceValue);
}
return false;
};
const creditExpiry = value => {
let d;
if (value.length <= 3) {
d = value.replace(/\D/g, "");
d = moment(value, "MM");
} else {
d = moment(value, "MM/YY");
if (d.isBefore(moment().subtract(1, "month")) || d.isAfter(moment().add(15, "years"))) {
return false;
}
}
if (d == null || !d.isValid()) return false;
return true;
};
const creditCVV = value => {
const regex = /^[0-9]{3,4}$/;
return regex.test(value);
};
export { creditCard, creditExpiry, creditCVV };
|
angular.module('formControllers', [])
.controller('FormController', function ($scope) {
$scope.register = {};
$scope.submitted = false;
$scope.submit = function (myForm) {
if (myForm.$valid) {
// Challenge B
$scope.submitted = false;
// continue with form processing
alert("Form Valid: " + $scope.register.username + " " + $scope.register.email);
$scope.register = {}; //reset the form
return; // return from function
} else {
alert("form is invalid");
}
$scope.submitted = true;
};
})
.controller('SelectionController', function ($scope) {
$scope.items = [{
name: 'one',
age: 30
},
{
name: 'two',
age: 27
},
{
name: 'three',
age: 50
}];
$scope.cars = ['mini', 'ferrari', 'bmw', 'VW'];
$scope.wasSubmitted = false;
$scope.selectedItem = $scope.items[0];
$scope.selectedCar = $scope.cars[1];
// for check box
$scope.checkboxModel = {
fishing: true,
golf: true,
sailing: false,
vote: 'down'
};
// for radio button
$scope.color = {
name: 'blue'
};
$scope.specialValue = {
"id": "12345",
"value": "green"
};
$scope.submit = function () {
if ($scope.selectionForm.$valid) {
$scope.wasSubmitted = true;
alert("selected car: " + $scope.selectedCar);
alert("selected item: " + $scope.selectedItem.name + " " + $scope.selectedItem.age);
} else {
alert("form is invalid");
}
};
})
.controller('RegisterController', function ($scope) {
$scope.register = {};
$scope.submitted = false;
$scope.uniqueusername = true;
$scope.uniqueemail = true;
$scope.registerForm = function (registerForm) {
if (registerForm.$valid) {
$scope.submitted = true;
// continue with form processing
// use a service to check for validity of username
$scope.uniqueusername = false;
// use a service to check for validity of email
$scope.uniqueemail = true;
if ($scope.uniqueusername && $scope.uniqueemail) {
// proceed to process form via backend service
// if successful route to next page
}
} else {
console.log("form is invalid");
$scope.submitted = true;
}
};
});
|
var searchData=
[
['unsubscribe',['unsubscribe',['../classpsychic__ui_1_1_signal.html#ae5d22cf074ab2a826c120b787f9deead',1,'psychic_ui::Signal']]],
['updatelayout',['updateLayout',['../classpsychic__ui_1_1_div.html#aa46418f04f7997d19aaca778ba41e3d9',1,'psychic_ui::Div']]],
['updateruntimestyles',['updateRuntimeStyles',['../classpsychic__ui_1_1_div.html#aa17180151ecead9c43179a0b23ce74c5',1,'psychic_ui::Div']]],
['updatestyle',['updateStyle',['../classpsychic__ui_1_1_div.html#ab6d50fd9a1f1ddd80dd0e59a1a54c5bd',1,'psychic_ui::Div']]]
];
|
describe('validate-commit-msg.js', function() {
var m = require('./validate-commit-msg');
var errors = [];
var logs = [];
var VALID = true;
var INVALID = false;
beforeEach(function() {
errors.length = 0;
logs.length = 0;
spyOn(console, 'error').andCallFake(function(msg) {
errors.push(msg.replace(/\x1B\[\d+m/g, '')); // uncolor
});
spyOn(console, 'log').andCallFake(function(msg) {
logs.push(msg.replace(/\x1B\[\d+m/g, '')); // uncolor
});
});
describe('validateMessage', function() {
it('should be valid', function() {
expect(m.validateMessage('fix($compile): something')).toBe(VALID);
expect(m.validateMessage('feat($location): something')).toBe(VALID);
expect(m.validateMessage('docs($filter): something')).toBe(VALID);
expect(m.validateMessage('style($http): something')).toBe(VALID);
expect(m.validateMessage('refactor($httpBackend): something')).toBe(VALID);
expect(m.validateMessage('test($resource): something')).toBe(VALID);
expect(m.validateMessage('chore($controller): something')).toBe(VALID);
expect(m.validateMessage('chore(foo-bar): something')).toBe(VALID);
expect(m.validateMessage('chore(*): something')).toBe(VALID);
expect(m.validateMessage('chore(guide/location): something')).toBe(VALID);
expect(m.validateMessage('revert(foo): something')).toBe(VALID);
expect(errors).toEqual([]);
});
it('should validate 70 characters length', function() {
var msg = 'fix($compile): something super mega extra giga tera long, maybe even longer... ' +
'way over 80 characters';
expect(m.validateMessage(msg)).toBe(INVALID);
expect(errors).toEqual(['INVALID COMMIT MSG: is longer than 70 characters !']);
});
it('should validate "<type>(<scope>): <subject>" format', function() {
var msg = 'not correct format';
expect(m.validateMessage(msg)).toBe(INVALID);
expect(errors).toEqual(['INVALID COMMIT MSG: does not match "<type>(<scope>): <subject>" !']);
});
it('should validate type', function() {
expect(m.validateMessage('weird($filter): something')).toBe(INVALID);
expect(errors).toEqual(['INVALID COMMIT MSG: "weird" is not allowed type !']);
});
it('should allow empty scope', function() {
expect(m.validateMessage('fix: blablabla')).toBe(VALID);
});
it('should allow dot in scope', function() {
expect(m.validateMessage('chore(mocks.$httpBackend): something')).toBe(VALID);
});
it('should ignore msg prefixed with "WIP: "', function() {
expect(m.validateMessage('WIP: bullshit')).toBe(VALID);
});
});
});
|
/**
* Developer: Stepan Burguchev
* Date: 7/17/2014
* Copyright: 2009-2016 Comindware®
* All Rights Reserved
* Published under the MIT license
*/
"use strict";
import { Handlebars } from 'lib';
import template from '../templates/emptyGrid.hbs';
import LocalizationService from '../../services/LocalizationService';
/**
* Some description for initializer
* @name EmptyGridView
* @memberof module:core.list.views
* @class EmptyGridView
* @constructor
* @description View для отображения списка без колонок
* @extends Marionette.ItemView
* @param {Object} options Constructor options
* @param {string} [options.text=Список пуст] отображаемый текст
* */
export default Marionette.ItemView.extend({
initialize: function (options) {
this.model = new Backbone.Model({
text: options.text || LocalizationService.get('CORE.GRID.EMPTYVIEW.EMPTY')
});
},
template: Handlebars.compile(template),
className: 'empty-view'
});
|
/**
* Created by jan on 16.05.15.
*
* https://raw.githubusercontent.com/klughammer/node-randomstring/master/lib/randomstring.js
*/
"use strict";
var charsNumbers = '0123456789';
var charsLower = 'abcdefghijklmnopqrstuvwxyz';
var charsUpper = charsLower.toUpperCase();
var chars = charsNumbers + charsLower + charsUpper;
exports.generate = function (length) {
if (!length)
length = 32;
var string = '';
for (var i = 0; i < length; i++) {
var randomNumber = Math.floor(Math.random() * chars.length);
string += chars.substring(randomNumber, randomNumber + 1);
}
return string;
};
|
import Ember from 'ember';
const eq = (params) => params[0] !== params[1];
export default Ember.Helper.helper(eq);
|
import React from 'react';
import { Router, Route, IndexRoute, useRouterHistory } from 'react-router';
import { createHashHistory } from 'history';
import useScroll from 'scroll-behavior/lib/useStandardScroll';
import App from '../components/App';
import HomePage from '../components/Pages/HomePage';
import ChartPage from '../components/Pages/ChartPage';
import TablePage from '../components/Pages/TablePage';
import MapPage from '../components/Pages/MapPage';
import AboutPage from '../components/Pages/AboutPage';
import AuthPage from '../components/Pages/AuthPage';
import ProfilePage from '../components/Pages/ProfilePage';
import ManagePetPage from '../components/Pages/ManagePetPage';
import CreatePetPage from '../components/Pages/CreatePetPage';
const history = useScroll(createHashHistory);
const appHistory = useRouterHistory(history)({ queryKey: false });
export const Routes = () => {
return (
<Router history={appHistory}>
<Route path='/' components={App} >
<IndexRoute component={HomePage} />
<Route path='home' component={HomePage} />
<Route path='chart' component={ChartPage} />
<Route path='table' component={TablePage} />
<Route path='map' component={MapPage} />
<Route path='about' component={AboutPage} />
<Route path='auth' component={AuthPage} />
<Route path='profile' component={ProfilePage} />
<Route path='pet/:_id' component={ManagePetPage} />
<Route path='createpet' component={CreatePetPage} />
</Route>
</Router>
);
};
export default Routes;
|
// This is an interface.
export class Heater {}
|
"use strict";
var Dispatch = require('./dispatch');
module.exports = Router;
var resp = require('./response');
function Router() {
this.routes = { //Holds route and middleware
GET: {},
POST: {},
PUT: {},
PATCH: {},
DELETE: {}
};
this.tasks = [{func: resp, pararms: null}]; //Processqueue
}
//handles default route (no matched url)
Router.prototype.default = function def(callback) {
this.default = callback;
};
//Adds middleware to all undefined routes, or to specifc route
// Route and method are optional, but method must be included if route is
Router.prototype.use = function use(middleware, params, route, method) {
if(route && method){
this.routes[method][route] = this.routes[method][route] || {};
this.routes[method][route].tasks = this.routes[method][route] || [];
this.routes[method][route].tasks.
push({func: middleware, params: params});
} else {
this.tasks.push({func: middleware, params: params});
}
};
//Assign route to GET handler
Router.prototype.get = function get(route, callback) {
this.assignRoute('GET', route, callback);
};
//Assign route to POST handler
Router.prototype.post = function post(route, callback) {
this.assignRoute('POST', route, callback);
};
//Assign route to PUT handler
Router.prototype.put = function put(route, callback) {
this.assignRoute('PUT', route, callback);
};
//Assign route to PATCH handler
Router.prototype.patch = function patch(route, callback) {
this.assignRoute('PATCH', route, callback);
};
//Assign route to DELETE handler
Router.prototype.del = function del(route, callback) {
this.assignRoute('DELETE', route, callback);
};
//Assign middleware and route
Router.prototype.assignRoute = function (method, route, callback){
this.routes[method][route] = this.routes[method][route] || {};
this.routes[method][route].callback = callback;
if (this.routes[method][route].tasks) {
this.routes[method][route].tasks =
this.tasks.concat(this.routes[method][route].tasks);
} else {
this.routes[method][route].tasks = this.tasks.slice();
}
};
//Route request to specified callback with middleware
Router.prototype.route = function (req, res) {
var path = this.routes
[req.method]
[req.url.slice(0, req.url.lastIndexOf('/') || req.url.length)];
if (path) {
var dispatch = new Dispatch();
var tasks = path.tasks.slice();
tasks.push({func: path.callback});
dispatch.exec(res, res, tasks);
} else {
if(this.default){
this.default(req, res);
}
}
};
|
module.exports = function (grunt) {
'use strict';
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
options: {
jshintrc: '.jshintrc'
},
all: [
'Gruntfile.js',
'./scripts/{,*/}*.js',
'test/spec/{,*/}*.js'
]
},
jsdoc : {
dist : {
src: ['./scripts/*.js'],
options: {
destination: 'doc'
}
}
},
connect: {
test: {
options: {
port: 8000,
base: '.'
}
}
},
browserify: {
options : {
transform : ['hbsfy']
},
test: {
src : ['test/test.js'],
dest : '.tmp/index.js',
options : {
debug : true
}
}
},
bump: {
options: {
files : ['package.json'],
updateConfigs : [],
commit : true,
commitMessage : 'Release v%VERSION%',
commitFiles : ['-a'],
createTag : true,
tagName : 'v%VERSION%',
tagMessage : 'Version %VERSION%',
push : true,
pushTo : '<%= pkg.repository.url %>',
gitDescribeOptions : '--tags --always --abbrev=1 --dirty=-d'
}
},
open : {
test : {
path: 'http://localhost:8000/test',
app: 'Google Chrome'
}
},
watch: {
scripts: {
files: ['scripts/*.*', 'test/*.*'],
tasks: ['browserify:test']
}
}
});
grunt.registerTask('test', [
'browserify',
'connect:test',
'open:test',
'watch'
]);
grunt.registerTask('default', [
'jshint',
'browserify'
]);
grunt.registerTask('release', [
'jshint',
'bump'
]);
};
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M12.97 7h-1.94c-2.75.08-3.62.58-3.9 1h9.74c-.28-.42-1.15-.92-3.9-1zM7 16v1c0 .45.3.84.74.95h3.11c-.22-.26-.35-.59-.35-.95 0-.39.15-.73.39-1H7zm6.5 1c0 .36-.13.69-.35.95h3.11c.44-.11.74-.5.74-.95v-1h-3.89c.24.27.39.61.39 1z",
opacity: ".3"
}, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "m13 5 .75-1.5H17V2H7v1.5h4.75L11 5c-3.13.09-6 .73-6 3.5V17c0 1.5 1.11 2.73 2.55 2.95L6 21.5v.5h2l2-2h4l2 2h2v-.5l-1.55-1.55h-.01.01C17.89 19.73 19 18.5 19 17V8.5c0-2.77-2.87-3.41-6-3.5zm-1.97 2h1.94c2.75.08 3.62.58 3.9 1H7.13c.28-.42 1.15-.92 3.9-1zm-.18 10.95H7.74C7.3 17.84 7 17.45 7 17v-1h3.89c-.24.27-.39.61-.39 1 0 .36.13.69.35.95zM17 17c0 .45-.3.84-.74.95h-3.11c.22-.26.35-.59.35-.95 0-.39-.15-.73-.39-1H17v1zm0-3H7v-4h10v4z"
}, "1")], 'TramTwoTone');
exports.default = _default;
|
/**
* Module dependencies
*/
var _ = require('@sailshq/lodash'),
util = require('sails-util');
/**
* default locals
*
* Always share some basic metadata with views.
* Roughly analogous to `app.locals` in Express.
*
* > Application local variables are provided to all templates rendered
* > within the application. This is useful for providing helper functions
* > to templates, as well as app-level data.
* >
* > http://expressjs.com/api.html#app.locals
*
* @param {Request} req
* @param {Response} res
* @api private
*/
module.exports = function _mixinLocals(req, res) {
// TODO:
// Actually take advantage of `app.locals`
// for this logic.
// TODO:
// we might look at pruning the stuff being
// passed in here, to improve the optimizations
// of Express's production view cache.
_.extend(res.locals, {
_: _,
util: util,
session: req.session,
req: req,
res: res,
sails: req._sails
});
// May be deprecated in an upcoming release:
res.locals.title = req._sails.config.appName;
if (req.options.action) {
' | ' + util.str.capitalize(req.param('action'));
}
};
|
import Vuex from 'vuex';
import Vue from 'vue';
import modules from './modules';
Vue.use(Vuex);
const store = new Vuex.Store({
modules,
strict: process.env.NODE_ENV !== 'production',
});
export default store;
|
// all variable are defined in 'global' variable even with var statement
// this behaviour is similar to the browser window, please be aware not to override them
var phantomcss = require('./../node_modules/phantomcss/phantomcss.js');
var system = require('system');
var args = Array.prototype.slice.call(system.args).join(' ');
var blockName = args.match(/blockName=([^\s]+)/)[1];
var scenario = args.match(/scenario=([^\s]+)/)[1];
var util = require('./util')(casper, phantomcss);
phantomcss.init({
libraryRoot: "./../node_modules/phantomcss",
screenshotRoot: './screenshots/',
fileNameGetter: function (root, filename) {
if (!(new RegExp('^' + blockName + '\\.')).test(filename))
filename = filename.replace(blockName, blockName + '.');
var name = root + filename + '.png';
// console.log(filename);
// if the file exists - write .diff file
if (fs.isFile(name)) return root + filename + '.diff.png'
else return name;
}
});
casper.start('http://localhost:3000/regression-tests/index.html');
util.shotCurrent('body', 'default')();
if (scenario !== 'null')
require(scenario); //executing scenario
casper.then( function () {
casper.test.done(); //ending casper
});
casper.run(function() {
phantom.exit(phantomcss.getExitStatus());
});
|
var result;
console.log('Divided by 7 and 5?');
result = 3 % 5 === 0 && 3 % 7 === 0 ? 'true' : 'false';
console.log(' 3 - ' + result);
result = 0 % 5 === 0 && 0 % 7 === 0 ? 'true' : 'false';
console.log(' 0 - ' + result);
result = 5 % 5 === 0 && 5 % 7 === 0 ? 'true' : 'false';
console.log(' 5 - ' + result);
result = 7 % 5 === 0 && 7 % 7 === 0 ? 'true' : 'false';
console.log(' 7 - ' + result);
result = 35 % 5 === 0 && 35 % 7 === 0 ? 'true' : 'false';
console.log(' 35 - ' + result);
result = 140 % 5 === 0 && 140 % 7 === 0 ? 'true' : 'false';
console.log('140 - ' + result);
|
'use strict';
exports.get = require('./get');
|
import _ from 'lodash';
export default function(source,panelSize) {
var bg = source;
var bgStyle = {};
if (bg === undefined) return bgStyle;
//size
if (!!bg.size) {
if (panelSize !== undefined && (bg.size === "leftHalf" || bg.size === "rightHalf")) {
bgStyle.backgroundSize = `${panelSize.width * 2}px ${panelSize.height}px`;
bgStyle.backgroundPosition = bg.size === "leftHalf" ? '0% 0%' : '100% 0%';
//console.log(bgStyle);
}
else{
bgStyle.backgroundSize = bg.size;
if (!!bg.position) bgStyle.backgroundPosition = bg.position;
}
}
//gradient
var bgGradient = bg.gradient;
if (bgGradient !== undefined) {
//gradient
if (bgGradient.stops !== undefined) {
var gradientStops = _.reduce(bgGradient.stops, function (memo, stop) {
return memo + ', ' + stop.color + ' ' + (stop.offset * 100) + '%'
}, '');
var orientation = bgGradient.orientation || 'top';
var grandientType = bgGradient.orientation === 'center, ellipse cover' ? '-webkit-radial-gradient' : '-webkit-linear-gradient';
bgStyle.background = grandientType + '(' + orientation + gradientStops + ')';
}
}
//color
var bgColor = bg.color;
if (bgColor !== undefined) {
if (!!bgColor.color) bgStyle.backgroundColor = bgColor.color;
if (!!bgColor.alpha) bgStyle.opacity = bgColor.alpha / 100;
}
if (!!bg.image) bgStyle.backgroundImage = 'url(' + bg.image + ')';
if (!!bg.repeat) bgStyle.backgroundRepeat = bg.repeat;
if (!!bg.attachment) bgStyle.backgroundAttachment = bg.attachment;
var filter = bg.filter || {};
var cssFilter = "";
if (!!filter.blur) cssFilter += ' blur(' + filter.blur + 'px)';
if (!!filter.brightness) cssFilter += ' brightness(' + filter.brightness + '%)';
if (!!filter.contrast) cssFilter += ' contrast(' + filter.contrast + '%)';
if (!!filter.grayscale) cssFilter += ' grayscale(' + filter.grayscale + '%)';
if (!!filter.hueRotate) cssFilter += ' hue-rotate(' + filter.hueRotate + 'deg)';
if (!!filter.invert) cssFilter += ' invert(' + filter.invert + '%)';
if (!!filter.opacity) cssFilter += ' opacity(' + filter.opacity + '%)';
if (!!filter.saturate) cssFilter += ' saturate(' + filter.saturate + '%)';
if (!!filter.sepia) cssFilter += ' sepia(' + filter.sepia + '%)';
if (!!cssFilter) {
bgStyle.WebkitFilter = cssFilter;
bgStyle.filter = cssFilter;
}
//bgStyle.position = 'absolute';
return bgStyle;
}
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "m12 8.89.94 3.11h2.82l-2.27 1.62.93 3.01L12 14.79l-2.42 1.84.93-3.01L8.24 12h2.82L12 8.89M12 2l-2.42 8H2l6.17 4.41L5.83 22 12 17.31 18.18 22l-2.35-7.59L22 10h-7.58L12 2z"
}), 'StarPurple500TwoTone');
exports.default = _default;
|
'use strict';
/**
* @example
* @code
* const sass = new TypedPlugin('gulp-sass', {
* errLogToConsole: true,
* outputStyle: 'expanded'
* });
*
* sass.Invoke()
*
* sass.outputStyle === 'expanded' // true
* @endcode
*
* @example
* An example above is the same as:
*
* @code
* const sass = require('gulp-sass');
*
* sass({
* errLogToConsole: true,
* outputStyle: 'expanded'
* });
*
* sass.outputStyle === undefined // true
* @endcode
*/
export default class TypedPlugin {
/**
* @constructor
*
* @param {String} module
* The name of module.
* @param {String} [method]
* The name of method to initialize the module.
* @param {Object} [options]
* A set of options for module invocation.
*/
constructor(module, method, options = {}) {
this.module = module ? require(module) : {};
this.options = options;
if (method in this.module) {
this.module[method](this.options);
}
// Copy methods into this object.
for (const item in this.module) {
this[item] = this.module[item];
}
// Copy options into this object.
for (const item in this.options) {
this[item] = this.options[item];
}
}
Invoke() {
return this.module instanceof Function ? this.module(this.options) : {};
}
}
|
import {Map, fromJS} from 'immutable';
import {expect} from 'chai';
import reducer from '../../../../views/src/reducer';
describe('reducer', () => {
it('handles SET_ENTRIES', () => {
const initialState = Map();
const action = {type: 'SET_ENTRIES', entries: ['Trainspotting']};
const nextState = reducer(initialState, action);
expect(nextState).to.equal(fromJS({
entries: ['Trainspotting'],
initialEntries: ['Trainspotting']
}));
});
it('handles NEXT', () => {
const initialState = fromJS({
entries: ['Trainspotting', '28 Days Later']
});
const action = {type: 'NEXT'};
const nextState = reducer(initialState, action);
expect(nextState).to.equal(fromJS({
vote: {
round: 1,
pair: ['Trainspotting', '28 Days Later']
},
entries: []
}));
});
it('handles VOTE', () => {
const initialState = fromJS({
vote: {
round: 1,
pair: ['Trainspotting', '28 Days Later']
},
entries: []
});
const action = {type: 'VOTE', entry: 'Trainspotting', clientId: 'voter1'};
const nextState = reducer(initialState, action);
expect(nextState).to.equal(fromJS({
vote: {
round: 1,
pair: ['Trainspotting', '28 Days Later'],
tally: {Trainspotting: 1},
votes: {
voter1: 'Trainspotting'
}
},
entries: []
}));
});
it('has an initial state', () => {
const action = {type: 'SET_ENTRIES', entries: ['Trainspotting']};
const nextState = reducer(undefined, action);
expect(nextState).to.equal(fromJS({
entries: ['Trainspotting'],
initialEntries: ['Trainspotting']
}));
});
it('can be used with reduce', () => {
const actions = [
{type: 'SET_ENTRIES', entries: ['Trainspotting', '28 Days Later']},
{type: 'NEXT'},
{type: 'VOTE', entry: 'Trainspotting', clientId: 'voter1'},
{type: 'VOTE', entry: '28 Days Later', clientId: 'voter2'},
{type: 'VOTE', entry: 'Trainspotting', clientId: 'voter3'},
{type: 'NEXT'}
];
const finalState = actions.reduce(reducer, Map());
expect(finalState).to.equal(fromJS({
winner: 'Trainspotting',
initialEntries: ['Trainspotting', '28 Days Later']
}));
});
});
|
'use strict'
/*global */
var disque = require('../index')
var client = disque.createClient([7711, 7712, 7713])
client.info()(function (err, info) {
console.log(err, info)
return this.addjob('queueA', 'Hello', 0)
})(function (err, res) {
console.log(err, res)
// null
// 'DI81250b3ccbac68e6625e79c8e7c5b286b1dcd2ac05a0SQ'
return this.show(res)
})(function (err, res) {
console.log(err, res)
// null
// {
// id: 'DI81250b3ccbac68e6625e79c8e7c5b286b1dcd2ac05a0SQ',
// queue: 'queueA',
// state: 'queued',
// repl: 3,
// ttl: 86400,
// ctime: 1430579357544000000,
// delay: 0,
// retry: 8640,
// 'nodes-delivered':
// [ 'f0e652056250c887ed294a53fa9386ea05abb0be',
// '2067c69f914c619ed9f348f5ce6e7532ec26e9a8',
// '81250b3c4318f0b6463da3742c7cf7069a46b6f6' ],
// 'nodes-confirmed': [],
// 'next-requeue-within': 8639835,
// 'next-awake-within': 8639335,
// body: 'Hello'
// }
})
|
/**
* @author Mat Groves
*
* Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/
* for creating the original pixi version!
* Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now share 4 bytes on the vertex buffer
*
* Heavily inspired by LibGDX's ParticleBuffer:
* https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java
*/
/**
*
* @class
* @private
* @memberof PIXI
* @param renderer {WebGLRenderer} The renderer this sprite batch works for.
*/
function ParticleBuffer(gl, properties, size)
{
/**
* the current WebGL drawing context
* @member {WebGLRenderingContext}
*/
this.gl = gl;
/**
*
*
* @member {number}
*/
this.vertSize = 2;
/**
*
*
* @member {number}
*/
this.vertByteSize = this.vertSize * 4;
/**
* The number of images in the SpriteBatch before it flushes.
*
* @member {number}
*/
this.size = size;
/**
*
*
* @member {Array}
*/
this.dynamicProperties = [];
/**
*
*
* @member {Array}
*/
this.staticProperties = [];
for (var i = 0; i < properties.length; i++)
{
var property = properties[i];
if(property.dynamic)
{
this.dynamicProperties.push(property);
}
else
{
this.staticProperties.push(property);
}
}
this.staticStride = 0;
this.staticBuffer = null;
this.staticData = null;
this.dynamicStride = 0;
this.dynamicBuffer = null;
this.dynamicData = null;
this.initBuffers();
}
ParticleBuffer.prototype.constructor = ParticleBuffer;
module.exports = ParticleBuffer;
/**
* Sets up the renderer context and necessary buffers.
*
* @private
* @param gl {WebGLRenderingContext} the current WebGL drawing context
*/
ParticleBuffer.prototype.initBuffers = function ()
{
var gl = this.gl;
var i;
var property;
var dynamicOffset = 0;
this.dynamicStride = 0;
for (i = 0; i < this.dynamicProperties.length; i++)
{
property = this.dynamicProperties[i];
property.offset = dynamicOffset;
dynamicOffset += property.size;
this.dynamicStride += property.size;
}
this.dynamicData = new Float32Array( this.size * this.dynamicStride * 4);
this.dynamicBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.dynamicBuffer);
gl.bufferData(gl.ARRAY_BUFFER, this.dynamicData, gl.DYNAMIC_DRAW);
// static //
var staticOffset = 0;
this.staticStride = 0;
for (i = 0; i < this.staticProperties.length; i++)
{
property = this.staticProperties[i];
property.offset = staticOffset;
staticOffset += property.size;
this.staticStride += property.size;
}
this.staticData = new Float32Array( this.size * this.staticStride * 4);
this.staticBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.staticBuffer);
gl.bufferData(gl.ARRAY_BUFFER, this.staticData, gl.DYNAMIC_DRAW);
};
ParticleBuffer.prototype.uploadDynamic = function(children, startIndex, amount)
{
var gl = this.gl;
for (var i = 0; i < this.dynamicProperties.length; i++)
{
var property = this.dynamicProperties[i];
property.uploadFunction(children, startIndex, amount, this.dynamicData, this.dynamicStride, property.offset);
}
gl.bindBuffer(gl.ARRAY_BUFFER, this.dynamicBuffer);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.dynamicData);
};
ParticleBuffer.prototype.uploadStatic = function(children, startIndex, amount)
{
var gl = this.gl;
for (var i = 0; i < this.staticProperties.length; i++)
{
var property = this.staticProperties[i];
property.uploadFunction(children, startIndex, amount, this.staticData, this.staticStride, property.offset);
}
gl.bindBuffer(gl.ARRAY_BUFFER, this.staticBuffer);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.staticData);
};
/**
* Starts a new sprite batch.
*
*/
ParticleBuffer.prototype.bind = function ()
{
var gl = this.gl;
var i, property;
gl.bindBuffer(gl.ARRAY_BUFFER, this.dynamicBuffer);
for (i = 0; i < this.dynamicProperties.length; i++)
{
property = this.dynamicProperties[i];
gl.vertexAttribPointer(property.attribute, property.size, gl.FLOAT, false, this.dynamicStride * 4, property.offset * 4);
}
gl.bindBuffer(gl.ARRAY_BUFFER, this.staticBuffer);
for (i = 0; i < this.staticProperties.length; i++)
{
property = this.staticProperties[i];
gl.vertexAttribPointer(property.attribute, property.size, gl.FLOAT, false, this.staticStride * 4, property.offset * 4);
}
};
/**
* Destroys the SpriteBatch.
*
*/
ParticleBuffer.prototype.destroy = function ()
{
//TODO implement this :) to busy making the fun bits..
};
|
/*eslint-disable*/
module.exports = {
'test': {
'files': [{
"src": ['test/jsftp/Test.txt'],
"orig": {
"expand": true,
"cwd": 'test',
"src": ['**/*']
},
"dest": 'jsftp/Test.txt'
}, {
"src": ['test/jsftp/jsftpSpec.js'],
"orig": {
"expand": true,
"cwd": 'test',
"src": ['**/*']
},
"dest": 'jsftp/jsftpSpec.js'
}, {
"src": ['test/nested/another/sample.js'],
"orig": {
"expand": true,
"cwd": 'test',
"src": ['**/*']
},
"dest": 'nested/another/sample.js'
}, {
"src": ['tasks/ftp_push.js'],
"dest": 'tasks/ftp_push.js',
"orig": {
"expand": true,
"cwd": 'tasks',
"src": ['**/*'],
"dest": 'test/'
}
}, {
"src": ['tasks/utils.js'],
"dest": 'tasks/utils.js',
"orig": {
"expand": true,
"cwd": 'tasks',
"src": ['**/*'],
"dest": 'test/'
}
}],
'paths': [{
'src': 'test/jsftp/Test.txt',
'dest': '/html/test/jsftp/Test.txt'
}, {
'src': 'test/jsftp/jsftpSpec.js',
'dest': '/html/test/jsftp/jsftpSpec.js'
}, {
'src': 'test/nested/another/sample.js',
'dest': '/html/test/nested/another/sample.js'
}, {
'src': 'tasks/ftp_push.js',
'dest': '/html/test/test/ftp_push.js'
}, {
'src': 'tasks/utils.js',
'dest': '/html/test/test/utils.js',
// This wont normally be in the results, but will use this to test to make sure the path is correct
'badPath': '/html/test/tasks/utils.js'
}],
'base': '/html/test/'
}
};
|
export default function levenshtein(a, b){
let m = []
for(let i = 0; i <= b.length; i++) {
m[i] = [i]
if(i === 0) continue;
let ib = i-1
for(let j = 0; j <= a.length; j++){
m[0][j] = j
if(j === 0) continue;
let jb = j-1
m[i][j] = b.charAt(ib) === a.charAt(jb) ? m[ib][jb] : Math.min(
m[ib][jb]+1,
m[i][jb]+1,
m[ib][j]+1
)
}
}
return m
}
|
var express = require('express');
var router = express.Router();
var handler = require('../modules/handler.js');
/* GET home page. */
router.get('/', function(req, res, next)
{
handler.provideList('data/data.json',{'Content-Type': 'application/json'}, res);
});
router.get('/:type', function(request, response, next)
{
console.log('Type: ' + request.params.type);
console.log('Image: ' + request.query.image);
console.log(request.query);
var img = request.query.image;
var type = request.params.type;
if(img != null && (type != '' && type != null))
{
console.log('Image requested');
console.log(img);
handler.provideData('images/' + type + '.jpg', {'Content-Type': 'image/jpeg'}, response);
}
else if(type != '' && type != null)
{
console.log('Data requested');
handler.queryData('data/data.json',{'Content-Type': 'application/json'}, request.params.type, response);
}
else
{
handler.provideList('data/data.json',{'Content-Type': 'application/json'}, response);
}
});
module.exports = router;
|
(function(w) {
w.RocketChat = w.RocketChat || { _: [] };
var config = {};
var widget;
var iframe;
var hookQueue = [];
var ready = false;
var widgetWidth = '320px';
var widgetHeightOpened = '350px';
var widgetHeightClosed = '30px';
// hooks
var callHook = function(action, params) {
if (!ready) {
return hookQueue.push(arguments);
}
var data = {
src: 'rocketchat',
fn: action,
args: params
};
iframe.contentWindow.postMessage(data, '*');
};
var closeWidget = function() {
widget.dataset.state = 'closed';
widget.style.height = widgetHeightClosed;
callHook('widgetClosed');
};
var openWidget = function() {
widget.dataset.state = 'opened';
widget.style.height = widgetHeightOpened;
callHook('widgetOpened');
document.querySelector('.rocketchat-widget iframe').focus();
};
var api = {
ready: function() {
ready = true;
if (hookQueue.length > 0) {
hookQueue.forEach(function(hookParams) {
callHook.apply(this, hookParams);
});
hookQueue = [];
}
},
toggleWindow: function(/*forceClose*/) {
if (widget.dataset.state === 'closed') {
openWidget();
} else {
closeWidget();
}
},
openPopout: function() {
closeWidget();
var popup = window.open(config.url + '?mode=popout', 'livechat-popout', 'width=400, height=450, toolbars=no');
popup.focus();
},
openWidget: function() {
openWidget();
},
removeWidget: function() {
document.getElementsByTagName('body')[0].removeChild(widget);
}
};
var pageVisited = function(change) {
callHook('pageVisited', {
change: change,
location: JSON.parse(JSON.stringify(document.location)),
title: document.title
});
};
var setCustomField = function(key, value, overwrite) {
if (typeof overwrite === 'undefined') {
overwrite = true;
}
callHook('setCustomField', [ key, value, overwrite ]);
};
var setTheme = function(theme) {
callHook('setTheme', theme);
};
var setDepartment = function(department) {
callHook('setDepartment', department);
};
var clearDepartment = function() {
callHook('clearDepartment');
};
var currentPage = {
href: null,
title: null
};
var trackNavigation = function() {
setInterval(function() {
if (document.location.href !== currentPage.href) {
pageVisited('url');
currentPage.href = document.location.href;
}
if (document.title !== currentPage.title) {
pageVisited('title');
currentPage.title = document.title;
}
}, 800);
};
var init = function(url) {
if (!url) {
return;
}
config.url = url;
var chatWidget = document.createElement('div');
chatWidget.dataset.state = 'closed';
chatWidget.className = 'rocketchat-widget';
chatWidget.innerHTML = '<div class="rocketchat-container" style="width:100%;height:100%">' +
'<iframe id="rocketchat-iframe" src="' + url + '" style="width:100%;height:100%;border:none;background-color:transparent" allowTransparency="true"></iframe> '+
'</div><div class="rocketchat-overlay"></div>';
chatWidget.style.position = 'fixed';
chatWidget.style.width = widgetWidth;
chatWidget.style.height = widgetHeightClosed;
chatWidget.style.borderTopLeftRadius = '5px';
chatWidget.style.borderTopRightRadius = '5px';
chatWidget.style.bottom = '0';
chatWidget.style.right = '50px';
chatWidget.style.zIndex = '12345';
document.getElementsByTagName('body')[0].appendChild(chatWidget);
widget = document.querySelector('.rocketchat-widget');
iframe = document.getElementById('rocketchat-iframe');
w.addEventListener('message', function(msg) {
if (typeof msg.data === 'object' && msg.data.src !== undefined && msg.data.src === 'rocketchat') {
if (api[msg.data.fn] !== undefined && typeof api[msg.data.fn] === 'function') {
var args = [].concat(msg.data.args || []);
api[msg.data.fn].apply(null, args);
}
}
}, false);
var mediaqueryresponse = function(mql) {
if (mql.matches) {
chatWidget.style.left = '0';
chatWidget.style.right = '0';
chatWidget.style.width = '100%';
} else {
chatWidget.style.left = 'auto';
chatWidget.style.right = '50px';
chatWidget.style.width = widgetWidth;
}
};
var mql = window.matchMedia('screen and (max-device-width: 480px) and (orientation: portrait)');
mediaqueryresponse(mql);
mql.addListener(mediaqueryresponse);
// track user navigation
trackNavigation();
};
if (typeof w.initRocket !== 'undefined') {
console.warn('initRocket is now deprecated. Please update the livechat code.');
init(w.initRocket[0]);
}
if (typeof w.RocketChat.url !== 'undefined') {
init(w.RocketChat.url);
}
var queue = w.RocketChat._;
w.RocketChat = w.RocketChat._.push = function(c) {
c.call(w.RocketChat.livechat);
};
// exports
w.RocketChat.livechat = {
pageVisited: pageVisited,
setCustomField: setCustomField,
setTheme: setTheme,
setDepartment: setDepartment,
clearDepartment: clearDepartment
};
// proccess queue
queue.forEach(function(c) {
c.call(w.RocketChat.livechat);
});
}(window));
|
/*!
* Start Bootstrap - Freelancer Bootstrap Theme (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
$(document).ready( function() {
// Next/prev buttons
$('.btnNext').click(function(){
$('.nav-tabs > .active').next('li').find('a').trigger('click');
});
$('.btnPrevious').click(function(){
$('.nav-tabs > .active').prev('li').find('a').trigger('click');
});
// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
$('body').on('click', '.page-scroll a', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1000, 'easeInOutExpo');
event.preventDefault();
});
});
// Floating label headings for the contact form
$(function() {
$("body").on("input propertychange", ".floating-label-form-group", function(e) {
$(this).toggleClass("floating-label-form-group-with-value", !! $(e.target).val());
}).on("focus", ".floating-label-form-group", function() {
$(this).addClass("floating-label-form-group-with-focus");
}).on("blur", ".floating-label-form-group", function() {
$(this).removeClass("floating-label-form-group-with-focus");
});
});
// Highlight the top nav as scrolling occurs
$('body').scrollspy({
target: '.navbar-fixed-top'
})
// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
$('.navbar-toggle:visible').click();
});
// Embiggen carousels on click
$(".carousel-inner").click(function(){
$(this).parent().toggleClass("col-sm-6");
$(this).parent().toggleClass("col-sm-12");
});
}); // All code inside this
|
(function () {
var emptyFn = function () { };
TimerStateManager = function () {
};
TimerStateManager.prototype.playingState = {
play: emptyFn,
pause: function (timer) {
var lastDuration = timer.currentDuration();
timer.durations.push(lastDuration);
timer.state = this.pausedState;
},
now: function (timer) {
return timer.durations.reduce(function (accumlatedValue, next) {
return accumlatedValue += next;
}, 0) + timer.currentDuration();
},
setTimeScale: function (timer, scale) {
timer.pause();
timer.timeScale = scale;
timer.play();
}
};
TimerStateManager.prototype.pausedState = {
play: function (timer) {
timer.lastStartTime = performance.now();
timer.state = this.playingState;
},
pause: emptyFn,
now: function (timer) {
return timer.durations.reduce(function (accumlatedValue, next) {
return accumlatedValue += next;
}, 0);
},
setTimeScale: function (timer, scale) {
timer.timeScale = scale;
}
};
var stateManager = new TimerStateManager();
Timer = function () {
this.performance = performance;
this.timeScale = 1;
this.lastStartTime = 0;
this.durations = [];
this.stateManager = stateManager;
this.state = stateManager.pausedState;
};
Timer.prototype.currentDuration = function () {
return (this.performance.now() - this.lastStartTime) * this.timeScale;
};
Timer.prototype.play = function () {
this.state.play.call(this.stateManager, this);
};
Timer.prototype.pause = function () {
this.state.pause.call(this.stateManager, this);
};
Timer.prototype.now = function () {
return this.state.now.call(this.stateManager, this);
};
Timer.prototype.setTimeScale = function (value) {
if (typeof value !== "number" || value < 0) {
throw new Error("value needs to be a number and greater than 0.");
}
this.state.setTimeScale.call(this.stateManager, this, value);
};
BASE.namespace("BASE.canvas");
BASE.canvas.Timer = Timer;
}());
|
// disconnect any meteor server
if(location.host !== 'localhost:3000' && location.host !== '127.0.0.1:3000')
Meteor.disconnect();
Meteor.startup(function() {
// SET default language
if(Cookie.get('TAPi18next')) {
TAPi18n.setLanguage(Cookie.get('TAPi18next'));
} else {
var userLang = navigator.language || navigator.userLanguage,
availLang = TAPi18n.getLanguages();
// set default language
if (_.isObject(availLang) && availLang[userLang]) {
TAPi18n.setLanguage(userLang);
// lang = userLang;
} else if (_.isObject(availLang) && availLang[userLang.substr(0,2)]) {
TAPi18n.setLanguage(userLang.substr(0,2));
// lang = userLang.substr(0,2);
} else {
TAPi18n.setLanguage('en');
// lang = 'en';
}
}
// change moment and numeral language, when language changes
Tracker.autorun(function(){
if(_.isString(TAPi18n.getLanguage())) {
moment.locale(TAPi18n.getLanguage().substr(0,2));
numeral.language(TAPi18n.getLanguage().substr(0,2));
}
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.