text
stringlengths 2
6.14k
|
|---|
define([
"src/extender",
"src/events",
"src/hash.route",
"src/model",
"src/fetch",
"src/style",
"src/tmpl",
"src/view",
"src/resources",
"src/spromise",
"src/module"
], function(Extender, Events, Hash, Model, Fetch, Style, Tmpl, View, Resources, Promise, Module) {
return {
Extender: Extender,
Events: Events,
Hash: Hash,
Model: Model,
Fetch: Fetch,
Style: Style,
Tmpl: Tmpl,
View: View,
Resources: Resources,
Promise: Promise,
Module: Module
};
});
|
'use strict';
// From: https://github.com/w3c/web-platform-tests/blob/fa9436d12c/encoding/api-surrogates-utf8.html
require('../common');
const assert = require('assert');
const {
TextDecoder,
TextEncoder
} = require('util');
const badStrings = [
{
input: 'abc123',
expected: [0x61, 0x62, 0x63, 0x31, 0x32, 0x33],
decoded: 'abc123',
name: 'Sanity check'
},
{
input: '\uD800',
expected: [0xef, 0xbf, 0xbd],
decoded: '\uFFFD',
name: 'Surrogate half (low)'
},
{
input: '\uDC00',
expected: [0xef, 0xbf, 0xbd],
decoded: '\uFFFD',
name: 'Surrogate half (high)'
},
{
input: 'abc\uD800123',
expected: [0x61, 0x62, 0x63, 0xef, 0xbf, 0xbd, 0x31, 0x32, 0x33],
decoded: 'abc\uFFFD123',
name: 'Surrogate half (low), in a string'
},
{
input: 'abc\uDC00123',
expected: [0x61, 0x62, 0x63, 0xef, 0xbf, 0xbd, 0x31, 0x32, 0x33],
decoded: 'abc\uFFFD123',
name: 'Surrogate half (high), in a string'
},
{
input: '\uDC00\uD800',
expected: [0xef, 0xbf, 0xbd, 0xef, 0xbf, 0xbd],
decoded: '\uFFFD\uFFFD',
name: 'Wrong order'
}
];
badStrings.forEach((t) => {
const encoded = new TextEncoder().encode(t.input);
assert.deepStrictEqual([].slice.call(encoded), t.expected);
assert.strictEqual(new TextDecoder('utf-8').decode(encoded), t.decoded);
});
|
'use strict'
const React = require('react')
// import _ from 'lodash'
//
// import hashHistory from 'react-router'
// import initStore from '../../src/front-end/js/store'
// import initRouter from '../../src/front-end/js/router'
const _ = require('lodash')
const { hashHistory } = require('react-router')
const initStore = require('../../src/front-end/js/store')
const initRouter = require('../../src/front-end/js/router')
const pkg = require(process.cwd() + '/package.json')
function reduxHandler (req, res, next) {
let initialState = {
application: {
token: null,
user: null,
nextTransitionPath: req.query.targetPath || ''
},
cv: {}
}
if (_.result(req, 'session.user')) {
initialState.application = _.merge(initialState.application, {
token: req.cookies.token,
user: req.session.user
})
}
global.INITIAL_STATE = JSON.stringify(initialState)
let store = initStore()
global.RESPONSE = res
initRouter(hashHistory, store)
.then(({content}) => {
const html = React.renderToString(content)
var opts = {
title: pkg.name,
author: pkg.author,
description: pkg.description,
version: pkg.version,
keywords: pkg.keywords.join(', '),
html: html,
initialState: JSON.stringify(initialState)
}
if (!res.headersSent) {
res.render('index', opts)
}
})
.catch((err) => {
console.error(err)
next(err)
})
}
module.exports = (app) => app.get('/app*', reduxHandler)
|
JalaliDate = {
g_days_in_month : [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
j_days_in_month : [31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29]
};
JalaliDate.jalaliToGregorian = function (j_y, j_m, j_d) {
j_y = parseInt(j_y);
j_m = parseInt(j_m);
j_d = parseInt(j_d);
var jy = j_y - 979;
var jm = j_m - 1;
var jd = j_d - 1;
var j_day_no = 365 * jy + parseInt(jy / 33) * 8 + parseInt((jy % 33 + 3) / 4);
for (var i = 0; i < jm; ++i)
j_day_no += JalaliDate.j_days_in_month[i];
j_day_no += jd;
var g_day_no = j_day_no + 79;
var gy = 1600 + 400 * parseInt(g_day_no / 146097);
g_day_no = g_day_no % 146097;
var leap = true;
if (g_day_no >= 36525) {
g_day_no--;
gy += 100 * parseInt(g_day_no / 36524);
g_day_no = g_day_no % 36524;
if (g_day_no >= 365)
g_day_no++;
else
leap = false;
}
gy += 4 * parseInt(g_day_no / 1461);
g_day_no %= 1461;
if (g_day_no >= 366) {
leap = false;
g_day_no--;
gy += parseInt(g_day_no / 365);
g_day_no = g_day_no % 365;
}
for (var i = 0; g_day_no >= JalaliDate.g_days_in_month[i] + (i == 1 && leap); i++)
g_day_no -= JalaliDate.g_days_in_month[i] + (i == 1 && leap);
var gm = i + 1;
var gd = g_day_no + 1;
return [gy, gm, gd];
}
JalaliDate.checkDate = function (j_y, j_m, j_d) {
return !(j_y < 0 || j_y > 32767 || j_m < 1 || j_m > 12 || j_d < 1 || j_d >
(JalaliDate.j_days_in_month[j_m - 1] + (j_m == 12 && !((j_y - 979) % 33 % 4))));
}
module.exports = JalaliDate;
JalaliDate.gregorianToJalali = function (g_y, g_m, g_d) {
g_y = parseInt(g_y);
g_m = parseInt(g_m);
g_d = parseInt(g_d);
var gy = g_y - 1600;
var gm = g_m - 1;
var gd = g_d - 1;
var g_day_no = 365 * gy + parseInt((gy + 3) / 4) - parseInt((gy + 99) / 100) + parseInt((gy + 399) / 400);
for (var i = 0; i < gm; ++i)
g_day_no += JalaliDate.g_days_in_month[i];
if (gm > 1 && ((gy % 4 == 0 && gy % 100 != 0) || (gy % 400 == 0)))
/* leap and after Feb */
++g_day_no;
g_day_no += gd;
var j_day_no = g_day_no - 79;
var j_np = parseInt(j_day_no / 12053);
j_day_no %= 12053;
var jy = 979 + 33 * j_np + 4 * parseInt(j_day_no / 1461);
j_day_no %= 1461;
if (j_day_no >= 366) {
jy += parseInt((j_day_no - 1) / 365);
j_day_no = (j_day_no - 1) % 365;
}
for (var i = 0; i < 11 && j_day_no >= JalaliDate.j_days_in_month[i]; ++i) {
j_day_no -= JalaliDate.j_days_in_month[i];
}
var jm = i + 1;
var jd = j_day_no + 1;
return [jy, jm, jd];
}
|
'use strict';
const fs = require('fs');
const sharedData = require('@render/shared_data.js');
const Config = require('@render/config.js');
const { getKeyFromConfig, get } = require('@aux/aux_global.js');
const Logger = require('@render/logger.js');
const aux_webManager = require('@render/aux_web_manager.js');
const aux_viewer = require('@render/aux_viewer.js');
const { promisify } = require('util');
const path = require('path');
module.exports = context => {
return {
config: {
maxTxtFileSize: 100 * 1024,
minTxtFileSize: 10,
disableExtensions: [],
userExtensions: [],
viewer: true,
},
viewer: false,
init() {
this.viewer = this.config.viewer;
if (this.config.viewer === 'auto') {
this.viewer = false;
const onKey = event => {
let lastRule = context.getLastRuleSelected();
let isTab = event && event.code === 'Tab';
let isFile = context.get(lastRule, 'params.drive_path');
if (isTab && isFile) {
if (event && event.preventDefault) event.preventDefault();
this.viewer = !this.viewer;
if (context.forceRefreshRules) context.forceRefreshRules();
}
};
if (document && document.addEventListener) document.addEventListener('keydown', onKey);
}
},
defineTypeViewers() {
if (!this.config.viewer) return;
const disableExtensions = this.config.disableExtensions || [];
const userExtensions = this.config.userExtensions || [];
const getRuleExtension = rule => {
const drive_path = context.get(rule, 'params.drive_path');
if (!drive_path) return null;
let drive_path_ext = path.extname(drive_path);
drive_path_ext = drive_path_ext.length > 0 ? drive_path_ext.substr(1) : drive_path_ext;
return drive_path_ext;
};
const isValidTxt = rule => {
const drive_path = context.get(rule, 'params.drive_path');
if (!drive_path === null) return null;
const drive_path_ext = getRuleExtension(rule);
const textextensions = context.require('textextensions');
const isText =
drive_path &&
!disableExtensions.includes(drive_path_ext) &&
(drive_path_ext === '' || textextensions.includes(drive_path_ext) || userExtensions.includes(drive_path_ext));
if (!isText) return false;
let stats = null;
try {
stats = fs.statSync(drive_path);
} catch (e) {
Logger.warn(e);
}
if (!stats) return false;
let fileSizeInBytes = stats['size'];
let big = fileSizeInBytes > this.config.maxTxtFileSize;
let small = fileSizeInBytes < this.config.minTxtFileSize;
if (big || small) return false;
return true;
};
const viewerTxtComp = context.createViewerHtml({}, async (resolve, reject, rule) => {
const fileName = context.get(rule, 'params.drive_path');
const data = await promisify(fs.readFile)(fileName, 'utf8');
const drive_path_ext = getRuleExtension(rule);
const isCode = drive_path_ext !== 'txt' && drive_path_ext !== '' && drive_path_ext !== 'doc';
resolve({ component: context.createComponentFromHtml(aux_viewer.string2HtmlCode(data, isCode)) });
});
return [
{
type: 'file',
title: 'File String Viewer',
enabled: rule => {
return this.viewer && isValidTxt(rule);
},
viewerComp: viewerTxtComp,
},
];
},
};
};
|
/* globals describe, it */
var assert = require('assert');
var t = require('../index');
var util = require('./util');
describe('t.intersection(types, [name])', function () {
var Min = t.subtype(t.String, function (s) { return s.length > 2; }, 'Min');
var Max = t.subtype(t.String, function (s) { return s.length < 5; }, 'Max');
var MinMax = t.intersection([Min, Max], 'MinMax');
describe('combinator', function () {
it('should throw if used with wrong arguments', function () {
util.throwsWithMessage(function () {
t.intersection();
}, '[tcomb] Invalid argument types undefined supplied to intersection(types, [name]) combinator (expected an array of at least 2 types)');
util.throwsWithMessage(function () {
t.intersection([]);
}, '[tcomb] Invalid argument types [] supplied to intersection(types, [name]) combinator (expected an array of at least 2 types)');
util.throwsWithMessage(function () {
t.intersection([1]);
}, '[tcomb] Invalid argument types [\n 1\n] supplied to intersection(types, [name]) combinator (expected an array of at least 2 types)');
util.throwsWithMessage(function () {
t.intersection([Min, Max], 1);
}, '[tcomb] Invalid argument name 1 supplied to intersection(types, [name]) combinator (expected a string)');
});
});
describe('ctor', function () {
it('should throw with a contextual error message if used with wrong arguments', function () {
util.throwsWithMessage(function () {
MinMax('a');
}, '[tcomb] Invalid value "a" supplied to MinMax');
util.throwsWithMessage(function () {
MinMax('a', ['root']);
}, '[tcomb] Invalid value "a" supplied to root');
});
});
describe('is(x)', function () {
it('should return true when x is an instance of the intersection', function () {
assert.strictEqual(MinMax.is('123'), true);
assert.strictEqual(MinMax.is('12'), false);
assert.strictEqual(MinMax.is('12345'), false);
});
});
});
|
---
layout: null
---
$(document).ready(function () {
$('a.blog-button').click(function (e) {
if ($('.panel-cover').hasClass('panel-cover--collapsed')){
return;
}
currentWidth = $('.panel-cover').width();
if (currentWidth < 960) {
$('.panel-cover').addClass('panel-cover--collapsed');
$('.content-wrapper').addClass('animated slideInRight');
}
else {
$('.panel-cover').css('max-width', currentWidth);
$('.panel-cover').animate({'max-width': '530px', 'width': '40%'}, 400, swing = 'swing', function () {});
}
});
if (window.location.hash && window.location.hash == '#blog') {
$('.panel-cover').addClass('panel-cover--collapsed');
}
if(window.location.pathname !== "/" || window.location.hash !== ""){
$('.panel-cover').addClass('panel-cover--collapsed');
}
// if (window.location.pathname !== '{{ site.baseurl }}' && window.location.pathname !== '{{ site.baseurl }}index.html') {
// $('.panel-cover').addClass('panel-cover--collapsed');
// }
$('.btn-mobile-menu').click(function () {
$('.navigation-wrapper').toggleClass('visible animated bounceInDown');
$('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn');
});
$('.navigation-wrapper .blog-button').click(function () {
$('.navigation-wrapper').toggleClass('visible');
$('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn');
});
});
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../actions';
class CommentBox extends Component {
constructor(props) {
super(props);
this.state = {
comment: ''
}
}
handleChange(e) {
this.setState({ comment: e.target.value })
}
handleSubmit(e) {
e.preventDefault();
this.props.saveComment(this.state.comment);
this.setState({ comment: '' })
}
render() {
return (
<form onSubmit={this.handleSubmit.bind(this)} className='comment-box'>
<h4>Add a Comment</h4>
<textarea value={this.state.comment} onChange={this.handleChange.bind(this)} />
<div>
<button action='submit'>Submit Comment</button>
</div>
</form>
)
}
}
export default connect(null, actions)(CommentBox);
|
#!/usr/bin/env node
'use strict';
var getStdin = require('get-stdin');
var meow = require('meow');
var detectNewline = require('./');
var cli = meow({
help: [
'Usage',
' $ detect-newline <string>',
' $ cat unicorn.txt | detect-newline',
'',
'Example',
' $ detect-newline "$(printf \'Unicorns\\nRainbows\')"',
' \\n'
]
});
function init(data) {
process.stdout.write(detectNewline(data) || '');
}
if (process.stdin.isTTY) {
if (!cli.input[0]) {
console.error('Expected a string');
process.exit(1);
}
init(cli.input[0]);
} else {
getStdin(init);
}
|
import React from 'react';
import { connect } from 'react-redux';
import Colors from './../../constants/PolygonColors.js';
import Operations from './../../constants/Operations.js';
import { LOCALE } from './../../constants/Config';
import './Range.css';
const scaleFactor = 2;
let Range = ({min, max, operationType}) => {
let style = {
background: `linear-gradient(${Colors})`
};
let values = [];
if(min && max){
let step = ((max - min) / Colors.length) * scaleFactor;
for(let i = 0; i < Colors.length / scaleFactor + 1; i ++){
values.push(min + step * i);
}
}
return (
<div className="Range">
<h3>Leyenda</h3>
<div className="Gradient" style={style}> </div>
<div className="Values">{values.map(v => <div key={v}>{Operations[operationType].unit}{Math.floor(v).toLocaleString(LOCALE)}</div>)}</div>
</div>
);
};
Range = connect((state) => ({
min: state.map.range.min,
max: state.map.range.max,
operationType: state.filters.operationType
}))(Range);
export default Range;
|
// Stwórz dwie funkcje, jedną nazwij range - powinna tworzyć tablicę
// zawierającą wszystkie liczby całkowite ze wskazanego przedziału,
// a jako dodatkowy argument przyjmować wielkość "kroku"
// np range(1, 10, 2) powinno stworzyć tablicę [1,3,5,7,9]
// druga funkcja o nazwie sum powinna sumować elementy tablicy
|
"use strict";
var Promise = require('bluebird');
var twilio = require('twilio');
var xoauth2 = require('xoauth2');
var crypto = require('crypto');
var crypto_pbkdf2 = Promise.promisify(crypto.pbkdf2);
var phone_regex = /\b[0-9]{10}\b/;
module.exports = function(api){
var client;
return {
phone: {
settings: {
accountSid: '',
authToken: '',
number: ''
},
configure: function(){
if (!api.phone.settings.accountSid || !api.phone.settings.authToken || !api.phone.settings.number) {
console.log("Twilio phone client has not been configured.");
return;
}
client = twilio(api.phone.settings.accountSid, api.phone.settings.authToken);
},
state: { // this is what will be stored in the database specific to each resource
independent: { // what can be set directly
number: String,
signin: Boolean // should this phone be used as a step in signing in.
},
dependent: { // what is set indirectly according to the api
verified: Boolean,
verifySalt: String,
verifyCodeHash: String
},
index: { },
},
static: {
view: {
},
action:{
root: {
handler: function(req) {
if (!phone_regex.test(this.number)){
throw new api.phone.Error('invalidphone',
'The phone number must be 10 digits with no spaces or puncuation.', [],
400);
}
// this will actually return the default return value
return Promise.resolve();
}
}
}
},
view: {
root: {
secure: true
},
'verified': {
parameter: ':code',
handler: function(req, res) {
var phone = this;
res.render('verified', {
_id: phone._id,
number: phone.number,
code: req.params.code
});
}
}
},
action: {
root: {
secure: true,
handler: function(req) {
if (!phone_regex.test(this.number)){
throw new api.phone.Error('invalidphone',
'The phone address is not a valid format.', [],
400);
}
this.verified = false;
}
},
'send-code-link': {
secure: true,
handler: function(req, res){
var phone = this;
phone.verifySalt = crypto.randomBytes(16).toString('hex');
var code = crypto.randomBytes(16).toString('hex');
return crypto_pbkdf2(code, phone.verifySalt, 1000, 64, 'sha256')
.then(function(codeHash) {
phone.verifyCodeHash = codeHash.toString('hex');
return phone.save();
})
.then(function(phone){
return phone.sendSms({
text: 'http://localhost:3000/api/phone/' + phone._id + '/verified/' + code
});
});
}
},
verify: {
secure: false,
handler: function(req, res) {
var phone = this;
if (phone.verified) {
return {
verified: true
};
}
return crypto_pbkdf2(req.body.code, phone.verifySalt, 1000, 64, 'sha256')
.then(function(codeHash) {
if (phone.verifyCodeHash === codeHash.toString('hex')){
phone.verified = true;
return phone.save();
}
return phone;
})
.then(function(phone) {
return {
verified: phone.verified
};
});
}
}
},
internal: {
sendSms: function(data) {
var phone = this;
return new Promise(function(resolve, reject){
try{
//https://www.twilio.com/blog/2013/03/introducing-the-twilio-module-for-node-js.html
client.sendSms({
to: phone.number,
from: api.phone.settings.number,
body: data.text
}, function(error, message) {
if (error) {
reject(error);
}else{
resolve(message);
}
});
}catch(error){
reject(error);
}
});
}
}
}
};
};
|
define([], function () {
var parser = (function(){
function parseMessage(message){
var parsedMessage = '',
laughingEmoticon = '<img src=\\"../server/media/emoticons/laughing.png\\"/>',
likeEmoticon = '<img src="../server/media/emoticons/like.png"/>',
sadEmoticon = '<img src="../server/media/emoticons/sad.png"/>',
smileEmoticon = '<img src="../server/media/emoticons/smile.png"/>',
winkEmoticon = '<img src="../server/media/emoticons/wink.png"/>',
dislikeEmoticon = '<img src="../server/media/emoticons/dislike.png"/>',
awesomeEmoticon = '<img src="../server/media/emoticons/awesome.png"/>'
poopEmoticon = '<img src="../server/media/emoticons/poop.png"/>',
tongueEmoticon = '<img src="../server/media/emoticons/tongue.png"/>',
wtfEmoticon = '<img src="../server/media/emoticons/wtf.png"/>',
kissEmoticon = '<img src="../server/media/emoticons/kiss.png"/>';
for (var i = 0; i < message.length; i++){
if (message[i] === ':' && (message[i + 1] === 'D' || message[i + 1] === 'd')) {
parsedMessage += laughingEmoticon;
i += 1;
} else if (message[i] === ':' && message[i + 1] === ')') {
parsedMessage += smileEmoticon;
i += 1;
} else if (message[i] === ':' && message[i + 1] === '(') {
parsedMessage += sadEmoticon;
i += 1;
} else if (message[i] === ';' && message[i + 1] === ')') {
parsedMessage += winkEmoticon;
i += 1;
} else if (message[i] === '(' && (message[i + 1] === 'y' || message[i + 1] === 'Y') && message[i + 2] === ')') {
parsedMessage += likeEmoticon;
i += 2;
} else if (message[i] === '(' && (message[i + 1] === 'n' || message[i + 1] === 'N') && message[i + 2] === ')') {
parsedMessage += dislikeEmoticon;
i += 2;
} else if (message[i] === ':' && message[i + 1] === '3'){
parsedMessage += awesomeEmoticon;
i += 1;
} else if (message[i] === ':' && message[i + 1] === '*'){
parsedMessage += kissEmoticon;
i += 1;
} else if (message[i] === 'o' && message[i + 1] === '.' && message[i + 2] === 'O'){
parsedMessage += wtfEmoticon;
i += 2;
} else if (message[i] === ':' && message[i + 4] === 'p' && message[i + 5] === ':'){
parsedMessage += poopEmoticon;
i += 5;
} else if (message[i] === ':' && (message[i + 1] === 'P' || message[i + 1] === 'p')){
parsedMessage += tongueEmoticon;
i += 1;
} else {
parsedMessage += message[i];
}
}
console.log(parsedMessage);
return parsedMessage;
}
return {
parseMessage: parseMessage
};
}());
return parser;
});
|
import { createIterable } from '../helpers/helpers';
import from from 'core-js-pure/es/array/from';
import Set from 'core-js-pure/features/set';
QUnit.test('Set#symmetricDifference', assert => {
const { symmetricDifference } = Set.prototype;
assert.isFunction(symmetricDifference);
assert.arity(symmetricDifference, 1);
assert.name(symmetricDifference, 'symmetricDifference');
assert.nonEnumerable(Set.prototype, 'symmetricDifference');
const set = new Set([1]);
assert.notSame(set.symmetricDifference([2]), set);
assert.deepEqual(from(new Set([1, 2, 3]).symmetricDifference([4, 5])), [1, 2, 3, 4, 5]);
assert.deepEqual(from(new Set([1, 2, 3]).symmetricDifference([3, 4])), [1, 2, 4]);
assert.deepEqual(from(new Set([1, 2, 3]).symmetricDifference(createIterable([3, 4]))), [1, 2, 4]);
assert.throws(() => new Set([1, 2, 3]).symmetricDifference(), TypeError);
assert.throws(() => symmetricDifference.call({}, [1, 2, 3]), TypeError);
assert.throws(() => symmetricDifference.call(undefined, [1, 2, 3]), TypeError);
assert.throws(() => symmetricDifference.call(null, [1, 2, 3]), TypeError);
});
|
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin')
var TARGET = process.env.TARGET;
var config = {
devtool: 'eval-source-map',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./app/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'App/Views/template.html'
})
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
include: path.join(__dirname, 'app')
}]
},
resolve: {
root: [
path.resolve(__dirname)
]
}
};
if (TARGET === 'prod') {
var config = {
devtool: 'source-map',
entry: [
'./app/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/ui/'
},
plugins: [
new webpack.NoErrorsPlugin(),
new webpack.optimize.UglifyJsPlugin({
compressor: { warnings: false },
sourceMap: false
}),
new webpack.DefinePlugin({
'process.env': { NODE_ENV: JSON.stringify('production') }
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'App/Views/template.html'
})
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
include: path.join(__dirname, 'app')
}]
},
resolve: {
root: [
path.resolve(__dirname)
]
}
};
}
module.exports = config;
|
const { each } = require('async')
const executeInitializers = async (ready, params) =>
new Promise(async (resolve, reject) => {
const $ = Object.keys(ready).filter(r => r[0] === '$')
try { resolve(await each($, async i => await ready[i](params))) }
catch (e) { reject(e) }
})
module.exports = executeInitializers
|
module.exports = {
"env": {
"es6": true,
"node": true,
"mocha": true,
},
"extends": "eslint:recommended",
"parserOptions": {
"sourceType": "module",
},
"parser": "babel-eslint",
"rules": {
"indent": [
"error",
2
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
]
}
};
|
var button = document.getElementById('create-event-button');
button.addEventListener('click', function(e) {
e.preventDefault();
// Submit data to DB.
db.collection('events')
.add({
title: document.getElementById('event-title').value,
date: document.getElementById('event-date').value,
location: document.getElementById('event-location').value,
description: document.getElementById('event-description').value,
})
// Show success alert upon completion.
.then(function() {
activateSuccessAlert();
document.getElementById('create-event-form').reset();
})
// Show fail Alert if error.
.catch(function(error) {
activateFailedAlert();
console.log(error);
});
});
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.4.4.16-7-b-11
description: >
Array.prototype.every - deleting property of prototype causes
prototype index property not to be visited on an Array
includes: [runTestCase.js]
---*/
function testcase() {
var accessed = false;
function callbackfn(val, idx, obj) {
accessed = true;
return idx !== 1;
}
var arr = [0, , 2];
Object.defineProperty(arr, "0", {
get: function () {
delete Array.prototype[1];
return 0;
},
configurable: true
});
try {
Array.prototype[1] = 1;
return arr.every(callbackfn) && accessed;
} finally {
delete Array.prototype[1];
}
}
runTestCase(testcase);
|
'use strict';
// virtual-dom
var h = require('virtual-dom/h');
// lodash
var difference = require('lodash/difference');
// bpmn-questionnaire
var BpmnQuestionnaire = require('../../../../lib/BpmnQuestionnaire');
var interactive = BpmnQuestionnaire.createType({
renderQuestion: function() {
var html =
h('div', [
h('p', this.options.text),
this.diagram.render(this.state)
]);
return html;
},
renderResult: function() {
var html;
if (this.state.rightAnswer) {
html =
h('div.panel.panel-success', [
h('div.panel-heading',
h('h3.panel-title', 'Glückwunsch!')
),
h('div.panel-body', 'Sie haben diese Frage richtig beantwortet!')
]);
} else {
html = [
h('div.panel.panel-danger', [
h('div.panel-heading',
h('h3.panel-title', 'Oh nein!')
),
h('div.panel-body', 'Ihre Antwort war leider falsch! Die richtige Antwort lautet:')
]),
this.diagram.render(this.state)
]
}
return html;
},
checkIfValidAnswer: function() {
return this.diagram.state.selected.length > 0;
},
checkIfRightAnswer: function() {
return difference(this.options.diagram.rightAnswers, this.diagram.state.selected).length < 1;
}
});
module.exports = interactive;
|
(function () {
var default_item_width = 120;
var last_list_num = 0;
function getInt16String() {
return parseInt(Math.random()*200+56).toString(16);
}
let Random = {
color: function () {
return '#' + getInt16String() + getInt16String() + getInt16String() ;
},
size: function (min, max) {
return parseInt(min + Math.random() * (max - min));
},
el: function (min = 100, max = 300) {
var size = this.size(min, max);
return `<div class="preview-item" style="background-color: ${this.color()};height: ${size}px;line-height: ${size}px;top: 0;left: 0;">${default_item_width} X ${size}</div>`
}
}
var _preview = document.getElementsByClassName('preview')[0];
var _main = document.getElementsByClassName('main')[0];
function init () {
for (var i = 0; i < 50; i++) {
_preview.innerHTML += Random.el(100, 200);
}
}
function relayout () {
_preview.style.height = '';
var list_num = Math.floor(_main.offsetWidth / default_item_width);
if (list_num === last_list_num) {
return;
}
_preview.style.width = `${list_num * default_item_width}px`;
var lists = [];
for (var i = 0; i < list_num; i++) {
lists.push({top: 0,left: i*default_item_width});
}
items = document.getElementsByClassName('preview-item');
for (var i = 0; i < items.length; i++) {
var min_height_list, min_height = Number.MAX_VALUE;
for (var j = 0; j < lists.length; j++) {
if (lists[j].top < min_height) {
min_height_list = j;
min_height = lists[j].top;
}
}
items[i].style.width = default_item_width - 20 + 'px';
items[i].style.transitionDelay = (list_num > last_list_num ? i : (items.length - i)) * 0.2 + 's';
items[i].style.left = lists[min_height_list].left + 'px';
items[i].style.top = lists[min_height_list].top + 10 + 'px';
lists[min_height_list].top += items[i].offsetHeight + 20;
}
var total_height = 0;
for (var i = 0; i < list_num; i++) {
if (total_height < lists[i].top) {
total_height = lists[i].top;
}
}
setTimeout(() => {
_preview.style.height = `${total_height + 20}px`;
}, items.length * 0.2);
last_list_num = list_num;
}
window.onload = function () {
init();
relayout();
}
window.onresize = relayout;
})();
|
var express = require('express');
var nodemailer = require('nodemailer');
var williamJHitchcock = express();
//default port to 8000 for dev
var PORT = process.env.PORT || 8000;
console.log(__dirname);
//serve static files
williamJHitchcock.use(express.static(__dirname + '/public/'));
//send email
williamJHitchcock.get('/contact', function(req, res) {
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport('smtps://william.hitchcock1%40gmail.com:omusofgnvqpvezqd@smtp.gmail.com');
console.log(req.query);
// setup e-mail data
var mailOptions = {
from: '"' + req.query.name + '" <contact@willhitchcock.me>',
replyTo: req.query.email,
to: 'hi@willhitchcock.me',
subject: req.query.sub,
text: req.query.msg
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
setTimeout(function() {
res.send('{' +
'"status":"error",' +
'"message":"An error occured, your message may not have been sent!",' +
'"icon":"error"' +
'}');
}, 3000);
return console.log(error);
}
setTimeout(function() {
res.send('{' +
'"status":"success",' +
'"message":"Message sent!",' +
'"icon":"check_circle"' +
'}');
}, 3000);
console.log('Message sent: ' + info.response);
});
});
var server = williamJHitchcock.listen(PORT, function() {
console.log('Listening on port ' + PORT)
});
|
describe("hapi-rest-methods", function() {
var testMethods = ['any', 'get', 'post', 'put', 'patch', 'delete', 'options'];
var hapi = require('hapi');
var request = require('request');
var restMethods = require('../lib/index')
var server;
beforeEach(function() {
server = new hapi.Server();
server.connection({ port: 8080 });
server.register(restMethods);
});
afterEach(function() {
server.stop();
server = null;
});
function it_for(specName, methodName, callback) {
it(specName + " for " + methodName + "()", callback);
}
describe("when configuring server", function() {
testMethods.forEach(function(methodName) {
it_for("should decorate hapi.server and make it respond", methodName, function() {
expect(typeof server[methodName]).toBe("function");
});
});
});
describe("when running server", function() {
function testServer(methodName, path) {
server.start(function(err) {
if(err) throw err;
if(methodName === 'any') methodName = 'patch'; // this can be anything, choosing patch for convenience
request({ uri: server.info.uri + path, method: methodName }, function(error, response, body) {
expect(response.statusCode).toBe(200);
expect(body).toBe('test');
});
});
}
function routeHandler(done) {
return function(response, reply) {
reply('test');
done();
}
}
testMethods.forEach(function(methodName) {
it_for("should create route path and handler", methodName, function(done) {
var path = '/test/' + methodName;
server[methodName](path, routeHandler(done));
testServer(methodName, path);
});
it_for("should create route path, config and handler", methodName, function(done) {
var path = '/test/' + methodName;
server[methodName](path, {}, routeHandler(done));
testServer(methodName, path);
});
});
});
});
|
import {VelocityAnimator} from '../src/animator';
import {initialize} from 'aurelia-pal-browser';
jasmine.getFixtures().fixturesPath = 'base/test/fixtures/';
describe('stop function', () => {
let animator;
let container;
beforeAll(() => initialize());
beforeEach(() => {
let elem = $('#test-simple').eq(0)[0];
//stop all animations running on the test element
if (animator) animator.stop(elem, true);
loadFixtures('animation.html');
container = $('#animation').eq(0)[0];
animator = new VelocityAnimator(container);
let elems = container.querySelectorAll('.group1');
animator.stop(elem, true);
animator.stop(elems, true);
});
it('returns the animator instance for a fluent api', () => {
let elem = $('#test-simple').eq(0)[0];
let result = animator.stop(elem);
expect(result).toBe(animator);
});
it('stops the animation without resetting it', (done) => {
let elem = $('#test-simple').eq(0)[0];
animator.animate(elem, 'fadeIn', {duration: 100});
//the fixture does not have an opacity at the begining
expect(elem.style.opacity).toBe('');
//stop the animation halfway through
setTimeout(()=> {
//get current opacity value
let opacity = elem.style.opacity;
//check if opacity was being animated
expect(opacity > 0, opacity < 1).toBe(true);
//stop animation
animator.stop(elem);
//check if opacity hasn't been reset or changed because of the stop
expect(opacity === elem.style.opacity).toBe(true);
//make sure the animation didn't continue afterwards
setTimeout(()=> {
expect(opacity === elem.style.opacity).toBe(true);
done();
}, 10);
}, 50);
});
it('stops multiple elements', (done) => {
let elems = container.querySelectorAll('.group1');
animator.stop(elems, true);
expect(elems[0].style.opacity).toBe('');
animator.animate(elems, 'fadeIn', {duration: 100});
//stop the animation halfway through
setTimeout(()=> {
//get current opacity value
let opacity0 = elems[0].style.opacity;
let opacity1 = elems[1].style.opacity;
//stop animations
animator.stop(elems);
//check if opacity was being animated
expect(opacity0 > 0, opacity0 < 1).toBe(true);
//check if opacity hasn't been reset or changed because of the stop
expect(opacity0 === elems[0].style.opacity).toBe(true);
//check if opacity was being animated
expect(opacity1 > 0, opacity1 < 1).toBe(true);
//check if opacity hasn't been reset or changed because of the stop
expect(opacity1 === elems[0].style.opacity).toBe(true);
done();
}, 50);
});
it('sets isAnimating to false', () => {
let elem = $('#test-simple').eq(0)[0];
animator.animate(elem, 'fadeIn', {duration: 100});
expect(animator.isAnimating).toBe(true);
animator.stop(elem);
expect(animator.isAnimating).toBe(false);
});
});
|
var MERU = {};
MERU.options = {
requestGet: {
host: 'mobileapp.merucabs.com',
port: 80,
method: 'GET',
path: ''
},
requestPost: {
host: 'merucabapp.com',
port: 80,
method: 'POST',
path: '',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': 0,
'Host': 'merucabapp.com',
}
}
};
MERU.Taxi_Name_Map = {
genie: 'Genie',
meru: 'Meru',
}
module.exports = MERU;
|
version https://git-lfs.github.com/spec/v1
oid sha256:8dab13cd84b3c528037755762df99084451664baa1c87b6b0c9cd81d547fac00
size 39149
|
version https://git-lfs.github.com/spec/v1
oid sha256:cc9206eb96354984cfaaece07ee4ce59c3d753ea120208abe0ee5626ad8621fe
size 2958
|
version https://git-lfs.github.com/spec/v1
oid sha256:d332f13e7f0b16ef6915ebf6faeb3c55a9fa54c5828092777166a289835bcd2a
size 846
|
var TouchendBtn = require('../../../lib/touch/default/touchend-button'),
Q = require('q'),
expect = require('expect.js'),
initElement = function () {
var el = document.createElement('div');
el.style.width = '100px';
el.style.height = '100px';
el.style.position = 'absolute';
el.style.zIndex = '100';
el.style.top = 0;
el.style.left = 0;
window.document.body.appendChild(el);
return el;
};
describe('default/TouchendButton', function () {
it('must be an function', function () {
expect(TouchendBtn).to.be.an('function');
});
describe('instance', function () {
it('should raise an Error when calling .bind() if already binded', function () {
var btn = new TouchendBtn({
el : initElement(),
f : function () { }
});
expect(function () { btn.bind(); }).to.throwException("Can't bind an already binded button.");
});
it('should raise an Error when calling .unbind() if unbinded', function () {
var btn = new TouchendBtn({
el : initElement(),
f : function () { }
});
btn.unbind();
expect(function () { btn.unbind(); }).to.throwException("Can't unbind a unbinded button.");
});
it('should have a setActiveBorder method', function () {
var btn = new TouchendBtn({
el : initElement(),
f : function () { }
});
expect(btn.setActiveBorder).to.be.an('function');
});
it('can not be activated if already activated', function (done) {
var i = 0,
btn = new TouchendBtn({
el : initElement(),
f : function () { i = i+1; return Q.delay(200); }
});
// first fake activation
btn.onTouchstart({ changedTouches:[{ identifier : 0 }] });
btn.onTouchend({ changedTouches:[{ identifier : 0 }] });
setTimeout(function () {
// second activation while the first is not done
btn.onTouchstart({ changedTouches:[{ identifier : 1 }] });
btn.onTouchend({ changedTouches:[{ identifier : 1 }] });
},50);
setTimeout(function () {
expect(i).to.be(1);
done();
},300);
});
it('should add the `.active` css class on the underlying DOM element when touched', function (done) {
var btn = new TouchendBtn({
el : initElement(),
f : function () { return Q.delay(200); }
});
// fake activation
btn.onTouchstart({ changedTouches:[{ identifier : 0 }] });
expect(btn.el.classList.contains('active')).to.be(true);
btn.onTouchend({ changedTouches:[{ identifier : 0 }] });
done();
});
it('should remove the `.active` css class on the underlying DOM element after being touched', function (done) {
var btn = new TouchendBtn({
el : initElement(),
f : function () { return Q.delay(100); }
});
// fake activation
btn.onTouchstart({ changedTouches:[{ identifier : 0 }] });
btn.onTouchend({ changedTouches:[{ identifier : 0 }] });
expect(btn.el.classList.contains('active')).to.be(false);
done();
});
it('.bind should return the button', function () {
var btn = new TouchendBtn({
el : initElement(),
f : function () { },
autobind: false
});
expect(btn.bind()).to.be.equal(btn);
});
it('.unbind should return the button', function () {
var btn = new TouchendBtn({
el : initElement(),
f : function () { },
autobind: false
});
expect(btn.bind().unbind()).to.be.equal(btn);
});
});
});
|
// Generated by CoffeeScript 1.8.0
var BITSTR, DERNULL, INTERGER, OID, PRTSTR, SEQUENCE, SET, TAG, UTF8STR, asn1Util, cryptoUtil, generateCSR, generateKeyPair, j, keyUtil, onmessage;
postMessage({
type: 'status',
message: 'Importing JSRSASign library ...'
});
importScripts('jsrsasign-4.7.0-all-min.js');
j = KJUR;
keyUtil = KEYUTIL;
asn1Util = j.asn1.ASN1Util;
cryptoUtil = j.crypto.Util;
SEQUENCE = function(arr) {
return new j.asn1.DERSequence({
'array': arr
});
};
SET = function(arr) {
return new j.asn1.DERSet({
'array': arr
});
};
INTERGER = function(num) {
return new j.asn1.DERInteger({
'int': num
});
};
PRTSTR = function(str) {
return new j.asn1.DERPrintableString({
'str': str
});
};
UTF8STR = function(str) {
return new j.asn1.DERUTF8String({
'str': str
});
};
BITSTR = function(hex) {
return new j.asn1.DERBitString({
'hex': hex
});
};
OID = function(oid) {
return j.asn1.x509.OID.name2obj(oid);
};
TAG = function(tag) {
return new j.asn1.DERTaggedObject({
'tag': tag || 'a0'
});
};
DERNULL = function() {
return new j.asn1.DERNull();
};
generateKeyPair = function(len) {
var keyPair, privateKeyHex, privateKeyObj, privateKeyPEM, publicKeyHex, publicKeyObj, publicKeyPEM, ret, tbl;
ret = {};
tbl = [324, 588];
keyPair = keyUtil.generateKeypair("RSA", len);
privateKeyObj = ret.privateKeyObj = keyPair.prvKeyObj;
publicKeyObj = ret.publicKeyObj = keyPair.pubKeyObj;
privateKeyObj.isPrivate = true;
privateKeyPEM = ret.privateKeyPEM = keyUtil.getPEM(privateKeyObj, "PKCS8PRV");
privateKeyHex = ret.privateKeyHex = keyUtil.getHexFromPEM(privateKeyPEM, "PRIVATE KEY");
publicKeyPEM = ret.publicKeyPEM = keyUtil.getPEM(publicKeyObj);
publicKeyHex = ret.publicKeyHex = keyUtil.getHexFromPEM(publicKeyPEM, "PUBLIC KEY");
if (tbl.indexOf(ret.publicKeyHex.length) === -1) {
return false;
}
return ret;
};
generateCSR = function(data, keyPair, alg) {
var certificateRequestInfo, sig;
alg = alg || 'SHA256withRSA';
certificateRequestInfo = SEQUENCE([INTERGER(0), SEQUENCE([SET([SEQUENCE([OID("countryName"), PRTSTR(data.countryName)])]), SET([SEQUENCE([OID("stateOrProvinceName"), UTF8STR(data.stateOrProvinceName)])]), SET([SEQUENCE([OID("locality"), UTF8STR(data.locality)])]), SET([SEQUENCE([OID("organization"), UTF8STR(data.organization)])]), SET([SEQUENCE([OID("commonName"), UTF8STR(data.commonName)])])]), new j.asn1.x509.SubjectPublicKeyInfo(keyPair.publicKeyObj), TAG()]);
sig = new j.crypto.Signature({
alg: alg
});
sig.init(keyPair.privateKeyPEM);
sig.updateHex(certificateRequestInfo.getEncodedHex());
return SEQUENCE([certificateRequestInfo, SEQUENCE([OID(alg), DERNULL()]), BITSTR('00' + sig.sign())]);
};
onmessage = function(e) {
var CSR, CSRPEM, data, keyPair;
data = e.data.workload;
postMessage({
type: 'status',
message: 'Generating private key ...'
});
keyPair = false;
while (1) {
keyPair = generateKeyPair(parseInt(data.keySize));
if (keyPair === false) {
postMessage({
type: 'status',
message: 'Regenerating private key ...'
});
} else {
break;
}
}
postMessage({
type: 'status',
message: 'Generating CSR ...'
});
CSR = generateCSR(data, keyPair, "SHA256withRSA");
postMessage({
type: 'status',
message: 'Converting CSR to PEM format ...'
});
CSRPEM = asn1Util.getPEMStringFromHex(CSR.getEncodedHex(), "CERTIFICATE REQUEST");
postMessage({
type: 'private',
pem: keyPair.privateKeyPEM
});
postMessage({
type: 'csr',
pem: CSRPEM
});
return postMessage({
type: 'done'
});
};
|
$(document).ready(function () {
$(document).on('click', '.loading', function () {
var btn = $(this);
btn.button('loading');
setTimeout(function () {
btn.button('reset')
}, 5000);
});
});
|
// Generated by CoffeeScript 1.6.3
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
define(['backbone', 'underscore', 'jquery', 'leaflet'], function(Backbone, _, $) {
var RouteMapDetailView, _ref;
RouteMapDetailView = (function(_super) {
__extends(RouteMapDetailView, _super);
function RouteMapDetailView() {
_ref = RouteMapDetailView.__super__.constructor.apply(this, arguments);
return _ref;
}
RouteMapDetailView.prototype.el = '.map-block';
RouteMapDetailView.prototype.initialize = function() {
return this.render();
};
RouteMapDetailView.prototype.render = function() {
var layer, map, vectorData, vectorLayer;
this.$el.html('<div id="map"></div>');
map = new L.Map('map');
layer = L.tileLayer('http://{s}.tile.cloudmade.com/9d0b97ba4e6d403aad532091aaafbc0b/997/256/{z}/{x}/{y}.png', {
attribution: 'Cloudmade',
maxZoom: 18
});
layer.addTo(map);
vectorData = {
type: 'Feature',
geometry: this.model.get('st_asgeojson')
};
vectorLayer = L.geoJson();
vectorLayer.addTo(map);
vectorLayer.addData(vectorData);
console.log(vectorLayer.getBounds());
return map.fitBounds(vectorLayer.getBounds());
};
return RouteMapDetailView;
})(Backbone.View);
return RouteMapDetailView;
});
}).call(this);
|
'use strict';
// TODO: best name? Better to call it Helpers? Utils is already taken
var Core = function () {};
Core.prototype.reserved = function (name) {
return (name && name.length >= 1 && name.charAt(0) === '$') ? true : false;
};
module.exports = new Core();
|
/**
* @ngdoc directive
* @name ui.controls.uiIcon
* @description
*
* uiIcon is used to render font icons. When uiIcon is placed inside a uiButton or uiToolbar it adjusts it's size to
* match it's parent size.
*
* @param {string} name The name of the font icon.
*
* @restrict E
* @example
<example module="ui">
<file name="index.html">
<ui-icon name="fa-home"></ui-icon>
</file>
</example>
*/
(function (app) {
app.directive('uiIcon', [
'$uiSize',
function (/** UI.Size */$uiSize) {
/**
* @param {angular.IScope} scope
* @param {Array.<Element>} el
* @param {$compile.directive.Attributes} attr
* @param {ui.components.uiHeight.Controller} $uiHeight
*/
function _link(scope, el, attr, $uiHeight) {
var $el = angular.element(el);
$el.addClass('ui-icon');
scope.$watch('name', function (value) {
// using font-awesome
if (_.startsWith(value, 'fa-')) {
$el.addClass('fa');
$el.addClass(value);
return;
}
// using Material Icons
el.addClass('material-icons');
el.text(value);
});
if(!$uiHeight) {
$el.addClass('ui-height-md');
return;
}
$uiHeight.setHeight($el);
if($uiHeight.getHeight() === 'sd' && $uiHeight.getParentHeight() === 'md') {
$el.addClass('ui-fit-md');
}
}
return {
restrict: 'E',
require: '?^uiHeight',
scope: {
name: '@'
},
link: _link,
controller: '$uiSizeController'
}
}]);
})(angular.module('thinkingmedia.ui.controls'));
|
var ViewAbstract = function () {
this.initialited = false;
this.$viewContainer = null;
};
ViewAbstract.prototype.setViewContainer = function($viewContainer) {
this.$viewContainer = $viewContainer;
return this;
};
ViewAbstract.prototype.getViewContainer = function() {
return this.$viewContainer;
};
ViewAbstract.prototype.setController = function(controller) {
this.controller = controller;
return this;
};
ViewAbstract.prototype.getController = function() {
return this.controller;
};
ViewAbstract.prototype.setInitialized = function(state) {
this.initialited = state;
return this;
};
ViewAbstract.prototype.getInitialized = function() {
return this.initialited;
};
/**
* Called, when contructed
*/
ViewAbstract.prototype.onInit = function() {
console.log('INIT');
};
/**
* called when view is open
*/
ViewAbstract.prototype.onOpen = function() {
console.log('OPENED');
};
/**
* called when view is closed
*/
ViewAbstract.prototype.onClose = function() {
console.log('CLOSED');
};
console.log('ViewAbstract', ViewAbstract);
|
//= require jquery/jquery
//= require raphael
//= require_tree .
$(document).ready(function(){
function arcs(id,n,type,mod,size){
var top = $(id).position().top;
var height = $(id).height();
var width = $(id).width();
var center = width/2;
var R = 100;
var paper = Raphael(0, top, width, height);
xmod = 0;
for (i = 0; i < n; i++) {
var xmod = xmod + mod;
switch(type) {
case 1:
var startx = center+xmod;
var starty = height+xmod;
var spin = -90;
var angle = 90;
var elx = size-(xmod*4);
var ely = size+(size*0.25)-(xmod*4);
var dir = 1;
var quad = 1;
break;
case 2:
var startx = 0;
var starty = height/2+xmod;
var spin = -90;
var angle = 90;
var elx = size-xmod*4;
var ely = size+(size*0.25)-(xmod*4);
var dir = 0;
var quad = 1;
break;
case 3:
var startx = center+xmod;
var starty = height+xmod;
var spin = 90;
var angle = 90;
var elx = size-(xmod*4);
var ely = size+(size*0.25)-(xmod*4);
var dir = 0;
var quad = 1;
break;
case 4:
var startx = center+xmod;
var starty = -(height/2);
var spin = 90;
var angle = 180;
var elx = size-xmod*4;
var ely = size+(size*0.25)-(xmod*4);
var dir = 1;
var quad = 1;
break;
default:
var startx = center+xmod;
var starty = height+xmod;
break;
}
var path_string = ['m', startx, starty, 'a', elx, ely, 3, quad, dir, spin, angle];
var arcs = paper.path(path_string);
arcs.attr("stroke", "#4babe0");
arcs.toBack();
};
};
// ElementID , number of arcs, arctype, offset, size
// TODO: ADD RESIZE EVENT
var a = arcs('#overview',5,1,15,1500);
var a = arcs('#overview',5,2,30,2500);
var a = arcs('#overview',5,3,15,2000);
var a = arcs('#overview',5,4,15,1000);
});
|
angular.module('ps.core.service')
.service('dataTranslationService', function(i18n) {
'use strict';
var s = this;
s.translate = translate;
s.setStorageDataLabels = setStorageDataLabels;
function translate(data) {
angular.forEach(data, function(value, key) {
switch (key) {
case 'widgets':
value = translateWidgets(value);
break;
case 'layout':
value = translateLayout(value);
break;
default:
}
});
return data;
}
function translateLayout(data) {
angular.forEach(data, function(value) {
value.title = i18n.get('c_l_' + value.label);
});
return data;
}
function translateWidgets(data) {
angular.forEach(data, function(value, key) {
value.title = i18n.get('w_' + key);
value.help = i18n.get('w_' + key + '_help');
});
return data;
}
function setStorageDataLabels(data) {
var i = 0;
angular.forEach(data, function(value, key) {
switch (key) {
case 'layout':
case 'badgeLayout':
case 'styles':
value.title = i18n.get('c_o_' + key);
value.order = -1;
i++;
break;
default:
if (i18n.get('w_' + key) !== '') {
value.title = i18n.get('w_' + key);
value.order = +1;
i++;
}
}
});
return data;
}
});
|
var expect = require('chai').expect;
var errors = require('../lib/Errors');
describe('Errors', function() {
it('maps status codes to custom errors', function() {
var unauthorized = errors('401');
expect(unauthorized.name).to.eq('Error');
expect(unauthorized.type).to.eq('AuthenticationError');
expect(unauthorized.message).to.eq(undefined);
expect(unauthorized.stack).to.be.a('string');
var unacceptable = errors('406', 'foo');
expect(unauthorized.name).to.eq('Error');
expect(unacceptable.type).to.eq('UnsupportedFormatRequestedError');
expect(unacceptable.message).to.eq('foo');
expect(unauthorized.stack).to.be.a('string');
var rateLimited = errors('429', 'foo', { retryAfter: 5 });
expect(rateLimited.name).to.eq('Error');
expect(rateLimited.type).to.eq('TooManyRequestsError');
expect(rateLimited.message).to.eq('foo');
expect(rateLimited.stack).to.be.a('string');
expect(rateLimited.retryAfter).to.eq(5);
});
});
|
'use strict';
describe('Unit Test', function() {
beforeEach(module('appServices', 'serviceMocks'));
describe('Services', function(){
var Github;
var httpBackend;
var scope;
beforeEach(inject(function(_Github_, $httpBackend, $rootScope) {
Github = _Github_;
scope = $rootScope.$new();
httpBackend = $httpBackend;
}));
afterEach(function() {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
it('should have all the required methods', function(){
expect(angular.isFunction(Github.getUser)).toBe(true);
expect(angular.isFunction(Github.getRepos)).toBe(true);
expect(angular.isFunction(Github.getIssues)).toBe(true);
expect(angular.isFunction(Github.getWatchers)).toBe(true);
});
describe('getUser', function() {
var userResponse;
beforeEach(inject(function(userMock) {
userResponse = userMock;
httpBackend.whenJSONP('https://api.github.com/users/angular?callback=JSON_CALLBACK').respond(userResponse);
}));
afterEach(function(){
httpBackend.flush();
scope.$root.$digest();
});
it('should return angular', function(){
Github.getUser('angular').$promise.then(function(response) {
expect(response.data.login).toEqual('angular');
});
});
it('should return a number of public repos', function(){
Github.getUser('angular').$promise.then(function(response) {
expect(response.data.public_repos).toBeGreaterThan(50);
});
});
});
describe('getRepos', function(){
var reposResponse;
beforeEach(inject(function(reposMock) {
reposResponse = reposMock;
httpBackend.whenJSONP('https://api.github.com/users/angular/repos?callback=JSON_CALLBACK').respond(reposResponse);
}));
afterEach(function(){
httpBackend.flush();
});
it('should return multiple repos', function(){
Github.getRepos('angular').$promise.then(function(response) {
expect(response.data).not.toBeNull();
});
});
it('should return angular/angular for sure', function(){
Github.getRepos('angular').$promise.then(function(response) {
expect(response.data[0].id).toEqual(24195339);
expect(response.data[0].full_name).toEqual('angular/angular');
});
});
});
describe('getIssues', function(){
var issuesResponse;
beforeEach(inject(function(issuesMock) {
issuesResponse = issuesMock;
httpBackend.whenJSONP('https://api.github.com/repos/angular/angular/issues?callback=JSON_CALLBACK').respond(issuesResponse);
}));
afterEach(function(){
httpBackend.flush();
});
it('should return multiple issues', function(){
Github.getIssues('angular', 'angular').$promise.then(function(response) {
expect(response.data).not.toBeNull();
});
});
it('should return issue 492', function(){
Github.getIssues('angular', 'angular').$promise.then(function(response) {
expect(response.data[0].number).toEqual(492);
expect(response.data[0].title).toEqual(jasmine.any(String));
});
});
});
describe('getWatcherss', function(){
var watchersResponse;
beforeEach(inject(function(watchersMock) {
watchersResponse = watchersMock;
httpBackend.whenJSONP('https://api.github.com/repos/angular/angular/subscribers?callback=JSON_CALLBACK').respond(watchersResponse);
}));
afterEach(function(){
httpBackend.flush();
});
it('should return multiple watchers', function(){
Github.getWatchers('angular', 'angular').$promise.then(function(response) {
expect(response.data).not.toBeNull();
});
});
it('should return watcher chirayuk', function(){
Github.getWatchers('angular', 'angular').$promise.then(function(response) {
expect(response.data[0].login).toEqual('chirayuk');
});
});
});
});
});
|
var cron = require('./lib/cron');
cron.aliases(require('./lib/aliases.json'));
/**
* I have always hated these little individual files, literally taking one file and re-exporting it
* Turns out, in this situation it's needed, due to the way node require's modules
*
* Take two files: "cronfile" and "./lib/cron.js"
* With package.json, "cronfile" => "./lib/cron.js", easy
* But then referring it internally, "../lib/cron", doesn't work since "cronfile" has been cached somewhere else
* So to get around that, we have to force node to cache our actual cron lib as a file, not a module
*/
module.exports = cron;
|
window.onload = function() {
var prod_img = document.getElementById("prod_img");
// Set an interval o keep rotating the image every 256 milliseconds
setInterval(function(){
prod_img.src = getImageSrc();
},1000);
var imgIndex = 1;
function getImageSrc() {
imgIndex = (imgIndex + 1) > 5? 1 : imgIndex + 1;
return imgIndex + ".jpeg";
}
var home = document.getElementById("pic");
var details = document.getElementById("inf");
var review = document.getElementById("rev");
document.getElementById("home").onclick = function() {
home.style.display = "block";
details.style.display = "none";
review.style.display = "none";
}
document.getElementById("details").onclick = function() {
home.style.display = "none";
details.style.display = "block";
review.style.display = "none";
}
document.getElementById("review").onclick = function() {
home.style.display = "none";
details.style.display = "none";
review.style.display = "block";
}
}
|
/* globals window, _, VIZI, THREE */
(function() {
"use strict";
/**
* Blueprint debug circles output
* @author Robin Hawkes - vizicities.com
* @author Edward Oliver Greer - eogreer.me
*/
// output: {
// type: "BlueprintOutputDebugCircles",
// options: {}
// }
VIZI.BlueprintOutputDebugCircles = function(options) {
var self = this;
VIZI.BlueprintOutput.call(self, options);
_.defaults(self.options, {});
// Triggers and actions reference
self.triggers = [
{name: "initialised", arguments: []}
];
self.actions = [
{name: "outputCircles", arguments: ["data"]}
];
self.world;
};
VIZI.BlueprintOutputDebugCircles.prototype = Object.create( VIZI.BlueprintOutput.prototype );
// Initialise instance and start automated processes
VIZI.BlueprintOutputDebugCircles.prototype.init = function() {
var self = this;
self.emit("initialised");
};
// {
// coordinates: [lon, lat],
// distance: 123
// }
VIZI.BlueprintOutputDebugCircles.prototype.outputCircles = function(data) {
var self = this;
var material = new THREE.MeshBasicMaterial({
color: 0xff0000,
});
if (self.options.opacity) {
material.opacity = self.options.opacity;
material.transparent = true;
}
var geom; // = new THREE.CircleGeometry();
// Local pixels per meter - set once per tile
var pixelsPerMeter;
_.each(data, function(point) {
var latLon = new VIZI.LatLon(point.coordinates[1], point.coordinates[0]);
var geoCoord = self.world.project(latLon);
// Set local pixels per meter if not set
if (pixelsPerMeter === undefined) {
pixelsPerMeter = self.world.pixelsPerMeter(latLon);
}
// TODO: Get this from options
var height = 50;
var radius = 100;
var segments = 32;
// Multiply height in meters by pixels per meter ratio at latitude
height *= pixelsPerMeter.y;
geom = new THREE.CircleGeometry(radius, segments);
geom.vertices.push(new THREE.Vector3( geoCoord.x, height, geoCoord.y ));
});
var circle = new THREE.Mesh( geom, material );
circle.rotateX(-90*(Math.PI/180));
circle.position.y = 100;
self.add(circle);
};
VIZI.BlueprintOutputDebugCircles.prototype.onAdd = function(world) {
var self = this;
self.world = world;
self.init();
};
}());
|
"use strict";
var gulp = require("gulp");
var cfg = require("../../../gulp.config");
function serve() {
try {
var browserSync = require("browser-sync").create();
gulp.task("build:sync", ["build"], browserSync.reload);
gulp.task("serve", function (done) {
browserSync.init({
server: "./"
});
var opts = {
interval: 100,
debounceDelay: 500,
mode: 'auto',
cwd: process.cwd()
};
// When emails, styles or components are compiled we reload the browser
gulp.watch([
cfg.src.emails.base + "/**/*.js",
cfg.styles + "/**/*.*",
cfg.src.components.base + "/**/*.js"], opts, ["build:sync"]);
});
} catch (error) {
console.warn([
"WARN: browser-sync not insalled.",
"Run 'npm install browser-sync --save-dev' to activate the 'serve' gulp task.",
"Windows see http://www.browsersync.io/docs/#windows-users"].join("\n"));
}
}
module.exports = serve;
|
/*global jQuery,alert*/
this.mytodo = (function (mytodo) {
mytodo.MyTodoView = function () {
var self, newTodoItemView, todoListView, eventBus, myTodoService;
self = this;
eventBus = new mytodo.EventBus();
myTodoService = new mytodo.MyTodoService();
todoListView = new mytodo.TodoListView(eventBus, myTodoService);
newTodoItemView = new mytodo.NewTodoItemView(eventBus, myTodoService);
eventBus.onError(function (message) {
alert(message);
});
self.init = function () {
todoListView.init();
newTodoItemView.init();
};
};
return mytodo;
}(this.mytodo || {}));
|
window.Mobi = window.Mobi || {};
window.Mobi.View = Backbone.View.extend({
delegateEvents: function(events) {
var key, newKey, oldValue;
this.events = this.events || events;
for (key in this.events) {
if (key.indexOf('click') === 0) {
if (window.Modernizr.touch) {
newKey = key.replace('click', 'touchend');
oldValue = this.events[key];
this.events[newKey] = oldValue;
delete this.events[key];
}
}
}
return Backbone.View.prototype.delegateEvents.call(this, this.events);
}
});
|
'use strict';
/**
* @ngdoc function
* @name uniappApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the uniappApp
*/
angular.module('uniappApp')
.controller('MainCtrl', function ($scope) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
});
|
import React from 'react'
import PropTypes from 'prop-types'
import ReactDisqusComments from 'react-disqus-comments'
import * as S from './styled'
const Comments = ({ url, title }) => {
const completeURL = `https://muniz95.com.br${url}`
return (
<S.CommentsWrapper>
<S.CommentsTitle>Comentários</S.CommentsTitle>
<ReactDisqusComments
shortname="muniz95"
identifier={completeURL}
title={title}
url={completeURL}
/>
</S.CommentsWrapper>
)
}
Comments.propTypes = {
url: PropTypes.string.isRequired,
title: PropTypes.string.isRequired
}
export default Comments
|
(function( $ ){
var multiSelectId=-1;
$.fn.multiSelect=function(options){
multiSelectId++;
var settings = {
'createCallback':false,
'createText':false,
'title':this.attr('title'),
'checked':[],
'oncheck':false,
'onuncheck':false,
};
$.extend(settings,options);
var button=$('<div class="multiselect button"><span>'+settings.title+'</span><span>▾</span></div>');
if(settings.checked.length>0){
button.children('span').first().text(settings.checked.join(', '));
}
var span=$('<span/>');
span.append(button);
button.data('id',multiSelectId);
button.selectedItems=[];
this.hide();
this.before(span);
settings.minWidth=button.width();
button.css('min-width',settings.minWidth);
settings.minOuterWidth=button.outerWidth()-2;
button.data('settings',settings);
button.click(function(event){
var button=$(this);
if(button.parent().children('ul').length>0){
button.parent().children('ul').slideUp(400,function(){
button.parent().children('ul').remove();
button.removeClass('active');
});
return;
}
var lists=$('ul.multiselectoptions');
lists.slideUp(400,function(){
lists.remove();
$('div.multiselect').removeClass('active');
button.addClass('active');
});
button.addClass('active');
event.stopPropagation();
var options=$(this).parent().next().children().map(function(){return $(this).val();});
var list=$('<ul class="multiselectoptions"/>').hide().appendTo($(this).parent());
function createItem(item,checked){
var id='ms'+multiSelectId+'-option-'+item;
var input=$('<input id="'+id+'" type="checkbox"/>');
var label=$('<label for="'+id+'">'+item+'</label>');
if(settings.checked.indexOf(item)!=-1 || checked){
input.attr('checked',true);
}
if(checked){
settings.checked.push(item);
}
input.change(function(){
var groupname=$(this).next().text();
if($(this).is(':checked')){
settings.checked.push(groupname);
if(settings.oncheck){
if(settings.oncheck(groupname)===false){
$(this).attr('checked', false);
return;
}
}
}else{
var index=settings.checked.indexOf(groupname);
settings.checked.splice(index,1);
if(settings.onuncheck){
if(settings.onuncheck(groupname)===false){
$(this).attr('checked',true);
return;
}
}
}
var oldWidth=button.width();
if(settings.checked.length>0){
button.children('span').first().text(settings.checked.join(', '));
}else{
button.children('span').first().text(settings.title);
}
var newOuterWidth=Math.max((button.outerWidth()-2),settings.minOuterWidth)+'px';
var newWidth=Math.max(button.width(),settings.minWidth);
button.css('height',button.height());
button.css('white-space','nowrap');
button.css('width',oldWidth);
button.animate({'width':newWidth},undefined,undefined,function(){
button.css('width','');
});
list.animate({'width':newOuterWidth});
});
var li=$('<li></li>');
li.append(input).append(label);
return li;
}
$.each(options,function(index,item){
list.append(createItem(item));
});
button.parent().data('preventHide',false);
if(settings.createText){
var li=$('<li>+ <em>'+settings.createText+'<em></li>');
li.click(function(event){
li.empty();
var input=$('<input class="new">');
li.append(input);
input.focus();
input.css('width',button.width());
button.parent().data('preventHide',true);
input.keypress(function(event) {
if(event.keyCode == 13) {
event.preventDefault();
event.stopPropagation();
var li=$(this).parent();
$(this).remove();
li.text('+ '+settings.createText);
li.before(createItem($(this).val()));
li.prev().children('input').trigger('click');
button.parent().data('preventHide',false);
var select=button.parent().next();
select.append($('<option value="'+$(this).val()+'">'+$(this).val()+'</option>'));
if(settings.createCallback){
settings.createCallback();
}
}
});
input.blur(function(){
event.preventDefault();
event.stopPropagation();
$(this).remove();
li.text('+ '+settings.createText);
setTimeout(function(){
button.parent().data('preventHide',false);
},100);
});
});
list.append(li);
}
var pos=button.position();
list.css('top',pos.top+button.outerHeight()-5);
list.css('left',pos.left+3);
list.css('width',(button.outerWidth()-2)+'px');
list.slideDown();
list.click(function(event){
event.stopPropagation();
});
});
$(window).click(function(){
if(!button.parent().data('preventHide')){
button.parent().children('ul').slideUp(400,function(){
button.parent().children('ul').remove();
button.removeClass('active');
});
}
});
return span;
};
})( jQuery );
|
var currentTagsArray = new Array();
var popularTagsArray = new Array();
var separatorArray = new Array();
var currIdArray = new Array();
$(document).ready(function(){
for (var currDivId in currentTagsArray)
for(var index in currentTagsArray[currDivId])
if(isInteger(index) && currentTagsArray[currDivId][index] != '')
addCurrentTag(currentTagsArray[currDivId][index], currIdArray[currDivId], true);
for (var popDivId in popularTagsArray)
for(var tag in popularTagsArray[popDivId])
if(isInteger(tag)) addPopularTag(popularTagsArray[popDivId][tag], popDivId);
$("div[id$='DTICurrTags'] > * > .DTICancelButton").live("click", function(){
var i = 0;
for(i=0;i<currentTagsArray.length;i++) {
if(currIdArray[i] == $(this).closest("div[id$='DTICurrTags']").attr("id")) {
currentTagsArray[i].remove($(this).next().text());
$(this).parent().remove();
break;
}
}
});
$("div[id$='DTIPopularTags'] > .DTIPopularTag").click(function(){
addCurrentTag($(this).text(), $(this).parent().parent().prev().attr("id"), false);
});
});
function addCurrentTag(tag, addToDivId, staticAdd){
if (staticAdd){
$("#" + addToDivId).append("<div class=\"DTICurrentTag\"><div class=\"DTICancelButton\">X</div><div class=\"DTITagText\">" + tag + "</div></div>");
}
else {
for (var index in currIdArray)
if (currIdArray[index] == addToDivId)
if(jQuery.inArray(tag, currentTagsArray[index]) < 0) {
currentTagsArray[index].push(tag);
$("#" + addToDivId).append("<div class=\"DTICurrentTag\"><div class=\"DTICancelButton\">X</div><div class=\"DTITagText\">" + tag + "</div></div>");
}
}
}
function addPopularTag(tag, addToDivId){
$("#" + addToDivId).append("<div class=\"DTIPopularTag\">" + tag + "</div>");
}
function isInteger(s) {
return (s.toString().search(/^-?[0-9]+$/) == 0);
}
function prepareCurrentTags(){
var currDivId = 0;
for (currDivId = 0; currDivId < currentTagsArray.length; currDivId++) {
var tags = '';
var index = 0;
for (index = 0; index < currentTagsArray[currDivId].length; index++) {
if(currentTagsArray[currDivId][index].toString().trim() != '') {
tags = tags + separatorArray[currIdArray[currDivId]] + currentTagsArray[currDivId][index];
}
}
$("#" + currIdArray[currDivId] + " input[id$='hfTags']").attr("value",tags.substring(1));
}
return true;
}
|
import {test} from 'zora';
import {body, TAB_PANEL_TAG_NAME} from '../util.js';
/**
* @test {TabPanel}
*/
test('TabPanel Component', ({test}) => {
test('TabPanel is connected', t => {
const el = document.createElement(TAB_PANEL_TAG_NAME);
body.appendChild(el);
t.eq(el.getAttribute('role'), 'tabpanel', 'should have the role tabpanel');
t.eq(el.getAttribute('slot'), 'tabpanels', 'should be put in the tabpanels slot');
});
/**
* @test {Tab#active}
*/
test('active getter should follow the `hidden` attribute', t => {
const el = document.createElement(TAB_PANEL_TAG_NAME);
t.eq(el.active, true);
el.setAttribute('hidden', '');
t.eq(el.active, false);
});
});
|
(function (exports) {
exports.SkyBoxActor = SkyBoxActor;
// The instance of this class is sent throght network.
function SkyBoxActor(actorInfo, actorManager) {
exports.Actor.call(this, actorInfo, actorManager);
var cShape = new Ammo.btSphereShape(1);
var inertia = new Ammo.btVector3();
cShape.calculateLocalInertia(0, inertia);
this.physicsState = new exports.PhysicsState(actorManager.physics);
this.physicsState.rigidBody = new Ammo.btRigidBody(0, this, cShape, inertia);
};
SkyBoxActor.prototype = Object.create(exports.Actor.prototype);
SkyBoxActor.prototype.constructor = exports.Actor;
exports.ActorManager.setCreator(
exports.SkyBoxActorInfo.prototype.type,
function(actorInfo, actorManager){
return new exports.SkyBoxActor(actorInfo, actorManager);
}
);
})(typeof teien === 'undefined' ? module.exports : teien);
|
import * as React from "react";
import PropTypes from "prop-types";
import { withWrapper } from "../Icon";
const Vector = React.forwardRef(({ size, color, ...props }, ref) => (
<svg
width={size}
height={size}
viewBox="4 4 32 32"
xmlns="http://www.w3.org/2000/svg"
ref={ref}
aria-hidden={!props["aria-label"]}
{...props}
>
<path
d="M32.727 25.639A5 5 0 0 1 28.319 33H11.681a5 5 0 0 1-4.408-7.361l8.32-15.53a5 5 0 0 1 8.814 0l8.32 15.53ZM20 26.019c-1.119 0-1.948.828-1.948 1.903v.044c0 1.074.83 1.903 1.948 1.903 1.119 0 1.948-.829 1.948-1.903v-.044c0-1.075-.83-1.903-1.948-1.903ZM18.008 15.14l.962 8.416c.068.605.47.986 1.03.986s.962-.38 1.03-.986l.962-8.416c.067-.648-.292-1.14-.894-1.14h-2.195c-.603 0-.962.492-.895 1.14Z"
fill={color}
fillRule="nonzero"
/>
</svg>
));
Vector.propTypes = {
color: PropTypes.string,
size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
"aria-label": PropTypes.string,
};
Vector.defaultProps = {
color: "currentColor",
size: "1em",
};
const MdCautionFilled = withWrapper(Vector);
MdCautionFilled.groupName = "States";
export default MdCautionFilled;
|
var options;
chrome.runtime.sendMessage({method: "getSettings"}, function(response) {
options = response;
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
WireUp();
clearInterval(readyStateCheckInterval);
}
}, 10);
});
function WireUp(){
if (fitadd.fitnessepage.IsFitnesse()){
if (fitadd.fitnessepage.AreAdding()){
if (options.cloneShortcut){
fitadd.fitnesseui.LoadClonedContentIfNeeded();
}
}
if (options.spEnabled){
fitadd.fixtures.search.RegisterHandlers(options);
}
if (fitadd.fitnessepage.AreEditing()){
if (options.saveShortcut){
fitadd.fitnesseui.RegisterSaveShortcut();
}
if (options.autoFormat){
fitadd.fitnesseui.RegisterAutoFormatOnSave();
}
}else{
if (options.editShortcut){
fitadd.fitnesseui.RegisterEditShortcut();
if (options.cloneShortcut){
fitadd.fitnesseui.RegisterCloneLink();
}
}
}
}
}
|
/**
* @file TwinkleAnimation.js
*
*
* @author Jonathan Lee Marcus
*
*
* @license Licensed under the MIT license.
**/
(function () {
"use strict";
var StarAnimation = require("./StarAnimation.js");
/**
* @class TwinkleAnimation
*
* @classdesc Twlinky animation that Jonathan made.
**/
this.TwinkleAnimation = function (params) {
StarAnimation.apply(this, arguments);
var numberOfTwinkles = 20;
Object.defineProperties(this, {
twink: {
enumerable: false,
writable: false,
value: new Array(numberOfTwinkles)
}
});
for (var i=0; i<this.twink.length; i++)
{
//for each twinkle, set a random location and initialize the birthtime to a random time within the last 1000 millisieconds
this.twink[i] = {"pixLoc":Math.floor(Math.random()*80),
"birthTime":(new Date().getTime() - (Math.random()*2000)),
"aliveTime":2000.0};
// for future potential twinkle rotation! <3
// twink[i] = {"pixLoc":Math.floor(Math.random()*80),
// "birthTime":(new Date().getTime() - (Math.random()*2000)),
// "aliveTime":2000.0,
// "rotationSpeed":Math.floor((Math.random()*60)-30)};
}
};
this.TwinkleAnimation.prototype = Object.create(StarAnimation.prototype, {
tick: {
enumerable: true,
writable: false,
value: function (timeNow) {
StarAnimation.prototype.tick.apply(this, arguments);
//zero the pixels before each draw!
for (var i=0; i<80; i++)
{
this.pixels.set_rgb(i, 0, 0, 0);
}
//var timeNow = new Date().getTime();
for (var i=0; i<this.twink.length; i++)
{
var age = timeNow - this.twink[i].birthTime;
var luminosity = 255 * Math.sin((age/this.twink[i].aliveTime)*2*Math.PI);
// future potential twinkle rotation! <3
//var shift = parseInt((age/twink[i].aliveTime)*twink[i].rotationSpeed);
//console.log(shift);
this.pixels.set_rgb(this.twink[i].pixLoc, luminosity, luminosity, luminosity);
//client.setPixel(twink[i].pixLoc, luminosity, luminosity, luminosity);
// future potential twinkle rotation! <3
// client.setPixel((twink[i].pixLoc+shift+80)%80, luminosity, luminosity, luminosity);
if(age>=this.twink[i].aliveTime)
{
this.twink[i].pixLoc = Math.floor(Math.random()*80);
this.twink[i].birthTime = timeNow;
this.twink[i].aliveTime = Math.random()*2000+3000;
}
}
}
}
});
module.exports = this.TwinkleAnimation;
}).call(this);
|
'use strict';
angular.module('registryUiApp').controller('DashboardController', function($scope, $interval, _,LogsService,wsService){
var vm = this;
$scope.sysinfo = wsService.collection;
vm.totalCpu = '100';
vm.label = ['CPU', '内存', '磁盘'];
LogsService.query({num: 7}).$promise.then(function(value, responseHeaders){
vm.logs = value;
},function(httpResponse){});
});
|
/**
* ListItemState allows a list item to track its state between sessions
* @param {hash} options - hash of required parameters.
* @param {string} options.identifier - the identifier for the list item
* @returns {ListItemState}
*
*/
function ListItemState(options) {
var settings = {
identifier: "unknown"
};
$.extend(settings, options);
/**
* readLocalStorage
* reads local storage and returns a hash of all item states
* @returns the hash of all item states in local storage
*/
function readLocalStorage() {
var item_states_string = localStorage.getItem('item_states') || "{}";
var item_states = JSON.parse(item_states_string);
return item_states;
}
/**
* writeLocalStorage
* Takes a hash of all item_states and writes it to local storage
* @param {hash} item_states
*/
function writeLocalStorage(item_states) {
item_states_string = JSON.stringify(item_states);
localStorage.setItem('item_states', item_states_string);
}
/**
* set
* Sets the item's current state in local storage
* @param {type} state
*/
this.set = function(state) {
var item_states = readLocalStorage();
var item_state = {
id: settings.identifier,
state: state
};
item_states[settings.identifier] = item_state;
writeLocalStorage(item_states);
};
/**
* get
* Retreives the item's last know state from local storage
* @param {type} state
*/
this.get = function() {
var item_states = readLocalStorage();
if (item_states) {
var current_state = item_states[settings.identifier];
if (current_state) {
return current_state.state;
}
}
return "0";
};
this.state = this.get();
}
|
import AuthActions from 'actions/AuthActions';
import AuthService from 'services/AuthService';
import BaseStore from 'stores/BaseStore';
import jwt_decode from 'jwt-decode';
import { LOGIN_USER, LOGOUT_USER } from 'constants';
class AuthStore extends BaseStore {
constructor() {
super();
this.subscribe(() => this._registerToActions);
this._user = null;
this._jwt = '';
}
_registerToActions = (actions) => {
switch(actions.actionType) {
case LOGIN_USER:
this._jwt = actions.jwt;
this._user = jwt_decode(this._jwt);
this.emitChange();
break;
case LOGOUT_USER:
this._user = null;
this.emitChange();
break;
default:
break;
}
}
get user() {
return this._user;
}
get jwt() {
return this._jwt;
}
isLoggedIn() {
if (!!this._user) {
AuthService.validateToken();
}
return !!this._user;
}
}
export default new AuthStore();
|
var boot = require('../').boot,
shutdown = require('../').shutdown,
connectDB = require('../').connectDB,
disconnectDB = require('../').disconnectDB,
port = require('../').port,
superagent = require('superagent'),
expect = require('expect.js');
describe('server', function() {
before(function(done) {
boot();
done();
// connectDB("testCollection", done);
});
describe('homepage', function() {
it('should respond to GET', function(done) {
superagent
.get('http://localhost:' + port)
.end(function(err, res) {
expect(res.statusCode).to.equal(200);
// Calling the end function will send the request
done();
});
})
});
after(function(done) {
shutdown();
done();
// disconnectDB(done);
});
});
|
module.exports = {
// App Configuration
debug: true,
mongo: {
host: 'localhost',
port: 27017,
database: 'meteor',
collection: 'your_collection_name'
},
dbSocket: function () {
return 'mongodb://' + this.mongo.host + ':' + this.mongo.port + '/' + this.mongo.database;
},
prefix: '',
// Spreadsheet
spreadsheet: {
spreadsheetId: '',
spreadsheetName: '',
worksheets: [
{
worksheetName: '',
worksheetId: ''
}
]
},
username: '',
password: ''
};
|
define([
'main/home/HomeApp',
'main/home/controllers/HomeController',
'main/home/controllers/GaugeController',
'main/home/controllers/DonutController',
'main/home/controllers/PieChartController',
'main/home/controllers/MultiController'
], function(){
});
|
import styled from 'styled-components';
const Form = styled.form``;
export default Form;
|
$.ready( function(){
});
|
/*global window:false */
( function ( $, mw ) {
'use strict';
// note: class=media-link-preMW125-core-hack kept for compatibility prior to MW 1.25
// you must edit the $IP/includes/Linker.php file, method makeMediaLinkFile()
// and change this line:
// $class = 'internal';
// to:
// $class = 'internal media-link-preMW125-core-hack'; // MW CORE HACK required until MW 1.25
// When you upgrade to MW 1.25 this hack is no longer needed.
$('.media-link, .media-link-preMW125-core-hack').each(function(i,e) {
var $e = $(e);
var href = $e.attr( 'href' );
// if a ? not present, add one to the end of the href
// (e.g. start query string)
if ( href.indexOf( '?' ) === -1 ) {
href += '?';
}
// else query string already exists, add to it
else {
href += '&';
}
// add random number to query string
href += 'rand=' + Math.random();
// modify href
$e.attr( 'href', href );
});
} )( jQuery, mediaWiki );
|
var typeis = require('type-is');
function typeIs(types) {
if (!Array.isArray(types)) types = [].slice.call(arguments);
return typeis(this, types);
};
module.exports = function() {
return function(req) {
return typeIs.bind(req);
};
};
|
'use strict';
var assert = require('chai').assert;
var rule = require('../../../lib/rules/extension.js');
describe('extension', function () {
it('should have a message', function () {
assert.equal(rule.message, 'file extension is not supported');
});
it('should pass filenames with a valid extension', function () {
assert.isTrue(rule('image.jpg', ['jpg', 'gif', 'png']));
});
it('should fail filenames without a valid extension', function () {
assert.isFalse(rule('image.doc', ['jpg', 'gif', 'png']));
});
});
|
var gulp = require('gulp');
var exec = require('child_process').exec;
var mkdirs = require('mkdirs');
var browserify = require('gulp-browserify');
var rename = require('gulp-rename');
var autoprefixer = require('gulp-autoprefixer');
var sass = require('gulp-sass');
var nodemon = require('gulp-nodemon')
function runCommand(command) {
return function (cb) {
exec(command, function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
cb(err);
});
}
}
gulp.task('create-data-folder', function() {
mkdirs('./mongodb/data');
});
//https://stackoverflow.com/questions/28665395/using-gulp-to-manage-opening-and-closing-mongodb
gulp.task('start-mongo', runCommand('mongod --dbpath ./mongodb/data/'));
gulp.task('stop-mongo', runCommand('mongo --eval "use admin; db.shutdownServer();"'));
gulp.task('create-db', runCommand('mongo tauw --eval "db.getCollectionNames()"'));
gulp.task('import-data', runCommand('mongoimport --db tauw --collection sensors --drop --file ./sensorseed.json'));
gulp.task('import-data2', runCommand('mongoimport --db tauw --collection settings --drop --file ./settingsseed.json'));
gulp.task('drop-collection', runCommand('mongo tauw --eval "db.sensors.drop()"'));
gulp.task('import-data-live', runCommand('mongoimport --host "tauw-shard-00-00-rkjng.mongodb.net:27017,tauw-shard-00-01-rkjng.mongodb.net:27017,tauw-shard-00-02-rkjng.mongodb.net:27017" --authenticationDatabase admin --ssl --username jaimie2 --password tauw22 --db tauw --collection sensors --drop --jsonArray --file "./generated.json"'));
gulp.task('import-settings-live', runCommand('mongoimport --host "tauw-shard-00-00-rkjng.mongodb.net:27017,tauw-shard-00-01-rkjng.mongodb.net:27017,tauw-shard-00-02-rkjng.mongodb.net:27017" --authenticationDatabase admin --ssl --username jaimie2 --password tauw22 --db tauw --collection settings --drop --file "./settingsseed.json"'));
gulp.task('setup-db',['create-data-folder','start-mongo','create-db','import-data', 'import-data2']);
gulp.task('sass', function() {
return gulp.src('public/stylesheets/*.scss')
.pipe(sass())
.pipe(autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(gulp.dest('public/build/css'));
});
gulp.task('scripts', function() {
gulp.src('public/javascripts/main.js')
.pipe(browserify({
insertGlobals : true,
debug : !gulp.env.production
}))
.pipe(rename('build.js'))
.pipe(gulp.dest('public/build/js/'))
});
gulp.task('watch', function() {
gulp.watch('public/stylesheets/*.scss', ['sass']);
gulp.watch('public/javascripts/*.js', ['scripts']);
});
gulp.task('start', function () {
nodemon({
script: 'bin/www'
, ext: 'js html ejs'
, env: { 'NODE_ENV': 'development' }
})
})
gulp.task('start-live', function () {
nodemon({
script: 'bin/www'
, ext: 'js html ejs'
, env: { 'NODE_ENV': 'development' }
})
})
gulp.task('live',['start-live']);
gulp.task('default', ['sass','scripts','start-mongo', 'watch','start']);
|
var path = require( 'path' );
module.exports = {
pkgJSONPath: path.resolve( __dirname, '../package.json' ),
configFile: {
//defaultName: 'package.json',
//pathToLocalConfig: path.resolve( __dirname, '../configs/bundly.json' ),
description: 'Path to your `ico-mixins` config. This can be used to specify the options and targets instead of passing them on the command line'
},
//useDefaultOptions: true,
optionator: {
prepend: '===============================================================\nUsage: ico-mixins -c my.conf.js\n ico-mixins ./font/selection.json -o ./dest/outfile.less \n===============================================================',
options: [
{
heading: 'Options'
},
{
option: 'output',
alias: 'o',
type: 'String',
description: 'The path to the output less file. A mixins file will also be created in the same directory'
},
{
option: 'target',
alias: 't',
type: 'String',
dependsOn: 'config',
description: 'The name of the target to execute from all the posible targets'
}
]
}
};
|
/**
*
* Empty Values
*
* @author: Corey Hart <http://www.codenothing.com>
* @description: Removes properties that don't have values
*
* @before:
* .example {
* color: red;
* font-size:;
* }
*
*
* @after:
* .example {
* color: red;
* }
*
*/
var CSSCompressor = global.CSSCompressor;
CSSCompressor.rule({
name: 'Empty Values',
type: CSSCompressor.RULE_TYPE_BLOCK,
group: 'Trim',
description: "Removes properties that don't have values",
priority: CSSCompressor.PRIORITY_LOWEST,
callback: function( branch, compressor ) {
if ( ! branch.rules || ! branch.rules.length ) {
return;
}
for ( var i = -1, rule; ++i < branch.rules.length; ) {
rule = branch.rules[ i ];
if ( ! rule.parts.length || rule.parts.join( '' ).trim().length < 1 ) {
compressor.log(
"Removing empty value with property key '" + rule.property + "'",
[ rule.position ]
);
CSSCompressor.removeItem( branch.rules, rule );
i--;
}
}
}
});
|
/* @flow */
export interface Story {
data: {
author: string,
id: string,
score: number,
title: string,
url: string,
};
kind: 't3';
}
export interface Subreddit {
data: {
display_name: string,
id: string,
subscribers: number,
title: string,
url: string,
};
kind: 't5';
}
export interface ResponseStories {
data: {
children: Array<Story>,
};
kind: 'Listing';
}
export interface ResponseSubreddits {
data: {
children: Array<Subreddit>,
};
kind: 'Listing';
}
|
/** @constructor */
ScalaJS.c.scala_collection_mutable_ObservableMap$$anon$2 = (function() {
ScalaJS.c.scala_collection_script_Update.call(this);
this.$$outer$2 = null;
this.key$1$2 = null;
this.old$1$2 = null
});
ScalaJS.c.scala_collection_mutable_ObservableMap$$anon$2.prototype = new ScalaJS.inheritable.scala_collection_script_Update();
ScalaJS.c.scala_collection_mutable_ObservableMap$$anon$2.prototype.constructor = ScalaJS.c.scala_collection_mutable_ObservableMap$$anon$2;
ScalaJS.c.scala_collection_mutable_ObservableMap$$anon$2.prototype.undo__V = (function() {
this.$$outer$2.$$plus$eq__Lscala_Tuple2__Lscala_collection_mutable_ObservableMap(new ScalaJS.c.scala_Tuple2().init___O__O(this.key$1$2, this.old$1$2))
});
ScalaJS.c.scala_collection_mutable_ObservableMap$$anon$2.prototype.init___Lscala_collection_mutable_ObservableMap__O__O__O = (function($$outer, key$1, value$1, old$1) {
if (($$outer === null)) {
throw new ScalaJS.c.java_lang_NullPointerException().init___()
} else {
this.$$outer$2 = $$outer
};
this.key$1$2 = key$1;
this.old$1$2 = old$1;
ScalaJS.c.scala_collection_script_Update.prototype.init___O.call(this, new ScalaJS.c.scala_Tuple2().init___O__O(key$1, value$1));
return this
});
ScalaJS.c.scala_collection_mutable_ObservableMap$$anon$2.prototype.undo__ = (function() {
return ScalaJS.bV(this.undo__V())
});
/** @constructor */
ScalaJS.inheritable.scala_collection_mutable_ObservableMap$$anon$2 = (function() {
/*<skip>*/
});
ScalaJS.inheritable.scala_collection_mutable_ObservableMap$$anon$2.prototype = ScalaJS.c.scala_collection_mutable_ObservableMap$$anon$2.prototype;
ScalaJS.is.scala_collection_mutable_ObservableMap$$anon$2 = (function(obj) {
return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_collection_mutable_ObservableMap$$anon$2)))
});
ScalaJS.as.scala_collection_mutable_ObservableMap$$anon$2 = (function(obj) {
if ((ScalaJS.is.scala_collection_mutable_ObservableMap$$anon$2(obj) || (obj === null))) {
return obj
} else {
ScalaJS.throwClassCastException(obj, "scala.collection.mutable.ObservableMap$$anon$2")
}
});
ScalaJS.isArrayOf.scala_collection_mutable_ObservableMap$$anon$2 = (function(obj, depth) {
return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_collection_mutable_ObservableMap$$anon$2)))
});
ScalaJS.asArrayOf.scala_collection_mutable_ObservableMap$$anon$2 = (function(obj, depth) {
if ((ScalaJS.isArrayOf.scala_collection_mutable_ObservableMap$$anon$2(obj, depth) || (obj === null))) {
return obj
} else {
ScalaJS.throwArrayCastException(obj, "Lscala.collection.mutable.ObservableMap$$anon$2;", depth)
}
});
ScalaJS.data.scala_collection_mutable_ObservableMap$$anon$2 = new ScalaJS.ClassTypeData({
scala_collection_mutable_ObservableMap$$anon$2: 0
}, false, "scala.collection.mutable.ObservableMap$$anon$2", ScalaJS.data.scala_collection_script_Update, {
scala_collection_mutable_ObservableMap$$anon$2: 1,
scala_collection_mutable_Undoable: 1,
scala_collection_script_Update: 1,
scala_Serializable: 1,
java_io_Serializable: 1,
scala_Product: 1,
scala_Equals: 1,
scala_collection_script_Message: 1,
java_lang_Object: 1
});
ScalaJS.c.scala_collection_mutable_ObservableMap$$anon$2.prototype.$classData = ScalaJS.data.scala_collection_mutable_ObservableMap$$anon$2;
//@ sourceMappingURL=ObservableMap$$anon$2.js.map
|
// Generated by CoffeeScript 1.8.0
var Account, CONSTANTS, Contact, Scheduler, Settings, async, cozydb, log, ramStore;
Scheduler = require('../processes/_scheduler');
Account = require('../models/account');
Contact = require('../models/contact');
Settings = require('../models/settings');
CONSTANTS = require('../utils/constants');
async = require('async');
cozydb = require('cozy-db-pouchdb');
log = require('../utils/logging')({
prefix: 'controllers:index'
});
ramStore = require('../models/store_account_and_boxes');
module.exports.main = function(req, res, next) {
if (Scheduler.applicationStartupRunning()) {
return res.render('reindexing');
}
return async.series([
function(cb) {
return Settings.getDefault(cb);
}, function(cb) {
return cozydb.api.getCozyLocale(cb);
}, function(cb) {
return cb(null, ramStore.clientList());
}, function(cb) {
return Contact.list(cb);
}
], function(err, results) {
var accounts, contacts, imports, locale, refreshes, settings;
refreshes = Scheduler.clientSummary();
if (err) {
log.error("err on index", err.stack);
imports = "console.log(\"" + err + "\");\nwindow.locale = \"en\"\nwindow.refreshes = []\nwindow.accounts = []\nwindow.contacts = []";
} else {
settings = results[0], locale = results[1], accounts = results[2], contacts = results[3];
imports = "window.settings = " + (JSON.stringify(settings)) + "\nwindow.refreshes = " + (JSON.stringify(refreshes)) + ";\nwindow.locale = \"" + locale + "\";\nwindow.accounts = " + (JSON.stringify(accounts)) + ";\nwindow.contacts = " + (JSON.stringify(contacts)) + ";\nwindow.app_env = \"" + process.env.NODE_ENV + "\";";
}
return res.render('index', {
imports: imports
});
});
};
module.exports.refresh = function(req, res, next) {
var limitByBox, onlyFavorites, _ref;
if ((_ref = req.query) != null ? _ref.all : void 0) {
limitByBox = null;
onlyFavorites = false;
} else {
limitByBox = CONSTANTS.LIMIT_BY_BOX;
onlyFavorites = true;
}
return Scheduler.startAllRefresh(function(err) {
if (err) {
log.error("REFRESHING ACCOUNT FAILED", err);
}
if (err) {
return next(err);
}
return res.send({
refresh: 'done'
});
});
};
module.exports.refreshes = function(req, res, next) {
return res.send(Scheduler.clientSummary());
};
|
import {Vector3} from 'three';
import {Loop} from '@whs/core/Loop';
/**
* StarOrbitModule Class
*/
export class StarOrbitModule {
/**
* Stable angular velocity
* @type {boolean}
*/
stableAngularVelocity = false;
/**
* Default constructor
*
* @param {Star} parent_star
* @param {Planet} planet
* @return {ShaderMaterial}
*/
constructor(parent_star, planet) {
const g = 6.67384e-11;
const av_min = 0.00000000001;
Object.assign(this, {
G: g,
SPR: planet.params.physics.fixedTimeStep, // Second Per Step
MPU: 1.0, // Meters Per Unit
star: parent_star,
planet: planet
});
Object.assign(this, {
minAngularVelocity: av_min
});
Object.assign(planet, {
starAccelerationLoop: new Loop(clock => {
this.adjustToStar(parent_star, planet);
})
});
}
/**
* Get acceleration by distance and mass to/of star
* this is a re-implementation of https://lord.io/blog/2014/kepler/ by Robert Lord, thanks!
*
* @param planet_star_distance
* @param star_mass
* @return {number}
*/
getStarAcceleration(planet_star_distance, star_mass) {
return this.G * star_mass / (Math.pow(planet_star_distance, 2));
}
/**
* Adjust linear velocity to star
*/
adjustToStar(star, planet) {
const distance_to_star = star.position.distanceTo(planet.position);
const acceleration = this.getStarAcceleration(distance_to_star, star.getRealMass());
const d_velocity = acceleration * this.SPR;
let l_velocity = planet.getLinearVelocity().clone();
l_velocity.subVectors(star.position, planet.position).setLength(d_velocity / this.MPU);
l_velocity.add(planet.getLinearVelocity());
let av = planet.getAngularVelocity();
let av_min = this.minAngularVelocity;
planet.setLinearVelocity(l_velocity);
if (Math.abs(av.x) < av_min && Math.abs(av.y) < av_min && Math.abs(av.z) < av_min && this.stableAngularVelocity === false) {
// Angular
planet.setAngularVelocity(planet.aVelocity);
// Linear
planet.setLinearVelocity(new Vector3(29861, 0, 0));
// console.log(planet.getLinearVelocity());
// planet.applyForce(
// {x: 29861*100000000, y: 0.0, z: 0.0},
// {x: 0, y: 0, z: 0}
// );
if(Math.abs(av.x) >= av_min || Math.abs(av.y) >= av_min | Math.abs(av.z) >= av_min) {
this.stableAngularVelocity = true;
console.log(`[${planet.name}] reached ~stable star orbit @ (angular velocity):`, planet.getAngularVelocity(), planet);
}
}
// console.log(`[${planet.name}|av]: ( ${planet._physijs.linearVelocity.x} +${l_velocity.x}, ${planet._physijs.linearVelocity.z} +${l_velocity.x} )`);
}
}
|
import {
watch,
unwatch
} from './watching';
import {
addListener,
removeListener
} from './events';
/**
@module @ember/object
*/
const AFTER_OBSERVERS = ':change';
export function changeEvent(keyName) {
return keyName + AFTER_OBSERVERS;
}
/**
@method addObserver
@static
@for @ember/object/observers
@param obj
@param {String} path
@param {Object|Function} target
@param {Function|String} [method]
@public
*/
export function addObserver(obj, path, target, method) {
addListener(obj, changeEvent(path), target, method);
watch(obj, path);
}
/**
@method removeObserver
@static
@for @ember/object/observers
@param obj
@param {String} path
@param {Object|Function} target
@param {Function|String} [method]
@public
*/
export function removeObserver(obj, path, target, method) {
unwatch(obj, path);
removeListener(obj, changeEvent(path), target, method);
}
|
"use strict"
var shsapi = {
shs: 'https://mighty-shelf-9974.herokuapp.com',
//shs: 'http://localhost:3000',
ajax: function(config, cb) {
$.ajax(config).done(function(data, textStatus, jqxhr) {
cb(null, data);
}).fail(function(jqxhr, status, error) {
cb({jqxher: jqxhr, status: status, error: error});
});
},
register: function (credentials, callback) {
this.ajax({
method: 'POST',
// url: 'http://httpbin.org/post',
url: this.shs + '/register',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(credentials),
dataType: 'json'
}, callback);
},
login: function (credentials, callback) {
this.ajax({
method: 'POST',
// url: 'http://httpbin.org/post',
url: this.shs + '/login',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(credentials),
dataType: 'json'
}, callback);
},
logout: function(callback) {
this.ajax({
method: 'DELETE',
url: this.shs + '/logout/' + user.userID,
headers: {
Authorization: 'Token token=' + user.currentToken
}
}, callback);
},
//Authenticated api actions
getCallerId: function (params, callback) {
this.ajax({
method: 'GET',
url: this.shs + '/callers' + params,
headers: {
"Content-Type": "application/json"
},
dataType: 'json'
}, callback);
},
getSongId: function (params, callback) {
this.ajax({
method: 'GET',
url: this.shs + '/songs' + params,
headers: {
"Content-Type": "application/json"
},
dataType: 'json'
}, callback);
},
getSingingsByName: function (params, callback) {
this.ajax({
method: 'GET',
url: this.shs + '/singings' + params,
headers: {
"Content-Type": "application/json"
},
dataType: 'json'
}, callback);
},
getCalls: function(route, callback){
this.ajax({
method: 'GET',
url: this.shs + route + '/calls/',
dataType: 'json'
}, callback);
},
getCallers: function(callback){
this.ajax({
method: 'GET',
url: this.shs + '/callers/',
dataType: 'json'
}, callback);
},
createSinging: function (data, callback) {
var json_string = JSON.stringify(data);
this.ajax({
method: 'POST',
url: this.shs + '/singings',
headers: {
Authorization: 'Token token=' + user.currentToken
},
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
dataType: 'json',
}, callback);
},
editSinging: function (id, data, token, callback) {
this.ajax({
method: 'PATCH',
url: this.shs + '/singings/' + id,
headers: {
Authorization: 'Token token=' + token
},
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
dataType: 'json'
}, callback);
},
deleteSinging: function(id, token, callback){
this.ajax({
method: 'DELETE',
url: this.shs + '/singings/' + id,
headers: {
Authorization: 'Token token=' + token
},
contentType: 'application/json; charset=utf-8',
dataType: 'json'
}, callback);
}
};
|
/*
* API covering the free interfaces
*/
function freeIntApi(db) {
var colDevices = db.collection('devices');
var colLinks = db.collection('links');
var colIous = db.collection('ious');
function iouInterfaces(deviceId, cb) {
colDevices.findOne({
id : parseInt(deviceId)
}, function(err, devObj) {
if (!(devObj && devObj.type)) {
if (cb) return cb({ serial: {}, ethernet: {} });
return;
}
colIous.findOne({
id : parseInt(devObj.type)
}, function(err, devQ) {
var i, j = 0;
var intf = { serial : {}, ethernet : {} };
var eNum = (devQ.ethernet > 0) ? parseInt(0.9999 + (devQ.ethernet) / 4) : 0;
var sNum = (devQ.serial > 0) ? parseInt(0.9999 + (devQ.serial) / 4) : 0;
// console.log('eNum',eNum,' sNum',sNum);
for (i = 0; i < eNum; i++, j++) {
intf.ethernet['e' + j + '/0'] = 1;
intf.ethernet['e' + j + '/1'] = 1;
intf.ethernet['e' + j + '/2'] = 1;
intf.ethernet['e' + j + '/3'] = 1;
}
for (i = 0; i < sNum; i++, j++) {
intf.serial['s' + j + '/0'] = 1;
intf.serial['s' + j + '/1'] = 1;
intf.serial['s' + j + '/2'] = 1;
intf.serial['s' + j + '/3'] = 1;
}
if (cb) return cb(intf);
});
});
}
function iouFreeInterfaces(deviceId, cb) { // Return array with all the free interfaces
iouInterfaces(deviceId,function(intf) {
colLinks.find({
$or : [
{
"source.id" : parseInt(deviceId)
},
{
"source.id" : deviceId.toString()
},
{
"target.id" : parseInt(deviceId)
},
{
"target.id" : deviceId.toString()
}
]
}).toArray(function(err, q) {
console.log('We got q',q,q.forEach,err);
q.forEach(function(n) {
if (n.source.id == parseInt(deviceId)) {
delete (intf.ethernet[n.source.name]);
delete (intf.serial[n.source.name]);
}
if (n.target.id == parseInt(deviceId)) {
delete (intf.ethernet[n.target.name]);
delete (intf.serial[n.target.name]);
}
});
if (cb)
cb(intf); // return the free interfaces
});
});
}
function iouFreeEthInts(deviceId, cb) { // Return object with all the free eth interfaces
console.log(arguments.callee);
iouFreeInterfaces(deviceId, function(intf) {
delete intf.serial;
if (cb)
cb(intf);
});
}
function iouFreeSerInts(deviceId, cb) { // Return object with all the free ser interfaces
console.log(arguments.callee);
iouFreeInterfaces(deviceId, function(intf) {
delete intf.ethernet;
if (cb)
cb(intf);
});
}
function iouFreeEthernet(deviceId, cb) { // Return the first free ethernet interface
console.log(arguments.callee);
iouFreeEthInts(deviceId, function(q) {
cb(Object.keys(q.ethernet).sort()[0]);
});
}
function iouFreeSerial(deviceId, cb) { // Return the first free serial interface
console.log(arguments.callee);
iouFreeSerInts(deviceId, function(q) {
cb(Object.keys(q.serial).sort()[0]);
});
}
return {
iouInterfaces: iouInterfaces,
iouFreeInterfaces: iouFreeInterfaces,
iouFreeEthInts: iouFreeEthInts,
iouFreeSerInts: iouFreeSerInts,
iouFreeEthernet: iouFreeEthernet,
iouFreeSerial: iouFreeSerial
}
}
exports = freeIntApi;
module.exports = exports;
|
/*
* grunt-awot
* https://github.com/lasselukkari/grunt-awot
*
* Copyright (c) 2015 Lasse Lukkari
* Licensed under the MIT license.
*/
'use strict';
var ejs = require('ejs');
var path = require('path');
var mime = require('mime');
var zlib = require('zlib');
module.exports = function (grunt) {
grunt.registerMultiTask('awot', 'Generate aWOT payloads.', function () {
var done = this.async();
var options = this.options({
rootPath: 'index.html',
needle: '// asset router',
appName: 'app',
gzip: true
});
if (!grunt.file.exists(options.sketch)) {
grunt.fail.fatal('Sketch ' + options.sketch + ' not found');
}
var sketch = grunt.file.read(options.sketch);
var sketchDir = options.sketch.substring(0, options.sketch.lastIndexOf(path.sep));
var assetsRouter = sketchDir + path.sep + 'asset.router.ino';
var assetsController = sketchDir + path.sep + 'asset.controller.ino';
var commandTemplate = grunt.file.read(__dirname + path.sep + 'templates/command.ejs');
var routesTemplate = grunt.file.read(__dirname + path.sep + 'templates/router.ejs');
var commands = [];
grunt.file.write(assetsController, '');
this.files.forEach(function (f) {
f.src.filter(function (filepath) {
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
}).forEach(function (filepath) {
var shortPath = filepath.replace(f.orig.cwd + '/', '');
var nameParts = path.basename(shortPath).split('.');
var camelCaseName = nameParts[0];
for (var i = 1; i < nameParts.length; i++) {
camelCaseName += nameParts[i].charAt(0).toUpperCase() + nameParts[i].slice(1);
}
if (shortPath === options.rootPath) {
shortPath = '';
}
var fileContent = grunt.file.read(filepath, {
encoding: null
});
if (options.gzip) {
fileContent = zlib.gzipSync(fileContent);
}
var contentLength = fileContent.length;
if (contentLength) {
var hexArray = fileContent.toString('hex').match(/.{1,2}/g).map(function (hex) {
return '0x' + hex;
}).toString().replace(/,/g, ', ').match(/.{1,66}/g).map(function (line) {
return line + '\n';
}).join('').split('\n').join('\n ');
var command = {
name: camelCaseName,
mime: mime.lookup(filepath),
path: shortPath,
size: contentLength
};
grunt.file.write(assetsController, grunt.file.read(assetsController) + ejs.render(commandTemplate, {command: command, data: hexArray}));
grunt.log.writeln(['Asset for route /' + command.path, 'created', '(' + command.size + ' bytes)'].join(' '));
commands.push(command);
}
});
});
var generatedRoutes = ejs.render(routesTemplate, {commands: commands});
if (sketch.indexOf('AssetRouter(' + options.appName + ');') < 0) {
sketch = sketch.replace(options.needle, options.needle + '\n' + ' AssetRouter(' + options.appName + ');');
}
grunt.file.write(options.sketch, sketch);
grunt.file.write(assetsRouter, generatedRoutes);
var combinedSize = 0;
commands.forEach(function (command) {
combinedSize += command.size;
});
grunt.log.writeln('Combined size of assets: ' + combinedSize + ' bytes');
done();
});
};
|
{ port : 8080
, verifyUrl : 'http://localhost:8080/verify'
, authUrl : 'http://localhost:8080/auth'
}
|
import React from 'react';
import {Paper} from 'material-ui';
import CallView from 'components/CallView';
import ConnectionStore from 'stores/ConnectionStore';
class CallList extends React.Component {
constructor(props) {
super(props);
this.state = {
calls: ConnectionStore.getCallList()
};
}
componentDidMount() {
ConnectionStore.addListener('callsChange', this._onChange.bind(this));
}
componentWillUnmount() {
ConnectionStore.removeListener('callsChange', this._onChange.bind(this));
}
_onChange() {
this.setState({
calls: ConnectionStore.getCallList()
});
}
render() {
var peerItems = this.state.calls.map(renderPeerItem);
return (
<div className="callList row">
{peerItems}
</div>
);
}
}
function renderPeerItem(call) {
return (
<div className="col-xs-4" key={call.peer}>
<Paper zDepth={3}>
<CallView peerCall={call} />
</Paper>
</div>
);
}
export default CallList;
|
'use strict';
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
import isFunction from 'lodash.isfunction';
import isObject from 'lodash.isobject';
import { save as actionSave } from './actions';
import { LOAD, SAVE } from './constants';
function swallow() {}
function warnAboutConfusingFiltering(blacklist, whitelist) {
blacklist.filter(function (item) {
return whitelist.indexOf(item) !== -1;
}).forEach(function (item) {
console.warn( // eslint-disable-line no-console
'[redux-storage] Action ' + item + ' is on BOTH black- and whitelist.' + ' This is most likely a mistake!');
});
}
function isValidAction(action) {
var isFunc = isFunction(action);
var isObj = isObject(action);
var hasType = isObj && action.hasOwnProperty('type');
if (!isFunc && isObj && hasType) {
return true;
}
if (process.env.NODE_ENV !== 'production') {
if (isFunc) {
console.warn( // eslint-disable-line no-console
'[redux-storage] ACTION IGNORED! Actions should be objects' + ' with a type property but received a function! Your' + ' function resolving middleware (e.g. redux-thunk) must be' + ' placed BEFORE redux-storage!');
} else if (!isObj) {
console.warn( // eslint-disable-line no-console
'[redux-storage] ACTION IGNORED! Actions should be objects' + (' with a type property but received: ' + action));
} else if (!hasType) {
console.warn( // eslint-disable-line no-console
'[redux-storage] ACTION IGNORED! Action objects should have' + ' a type property.');
}
}
return false;
}
function handleWhitelist(action, actionWhitelist) {
if (Array.isArray(actionWhitelist)) {
return actionWhitelist.length === 0 ? true // Don't filter if the whitelist is empty
: actionWhitelist.indexOf(action.type) !== -1;
}
// actionWhitelist is a function that returns true or false
return actionWhitelist(action);
}
export default (function (engine) {
var actionBlacklist = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var actionWhitelist = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var opts = Object.assign({ disableDispatchSaveAction: false }, options);
// Also don't save if we process our own actions
var blacklistedActions = [].concat(_toConsumableArray(actionBlacklist), [LOAD, SAVE]);
if (process.env.NODE_ENV !== 'production' && Array.isArray(actionWhitelist)) {
warnAboutConfusingFiltering(actionBlacklist, actionWhitelist);
}
return function (_ref) {
var dispatch = _ref.dispatch,
getState = _ref.getState;
return function (next) {
return function (action) {
var result = next(action);
if (!isValidAction(action)) {
return result;
}
var isOnBlacklist = blacklistedActions.indexOf(action.type) !== -1;
var isOnWhitelist = handleWhitelist(action, actionWhitelist);
// Skip blacklisted actions
if (!isOnBlacklist && isOnWhitelist) {
var saveState = getState();
var saveAction = actionSave(saveState);
if (process.env.NODE_ENV !== 'production') {
if (!saveAction.meta) {
saveAction.meta = {};
}
saveAction.meta.origin = action;
}
var dispatchSave = function dispatchSave() {
return dispatch(saveAction);
};
engine.save(saveState).then(function () {
if (opts.disableDispatchSaveAction === false) {
return dispatchSave();
}
})['catch'](swallow);
}
return result;
};
};
};
});
|
const express = require('express'),
router = express.Router(),
SRTV = require('../lib/srtv.js'),
moment = require('moment-timezone'),
db = require('../db');
router.get('/', (req, res) => {
res.render('srtv/index');
});
module.exports = router;
|
/*
* Stateful things in runtime
*/
export default {
component: null,
driver: null,
mountID: 1,
// Roots
rootComponents: {},
rootInstances: {},
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:468600a2ba782c16f9edb62431bd778f814dba1c61f444c46afcf1f9c2b5c359
size 1606
|
export default function Fragment$detach () {
var docFrag;
if ( this.items.length === 1 ) {
return this.items[0].detach();
}
docFrag = document.createDocumentFragment();
this.items.forEach( item => {
docFrag.appendChild( item.detach() );
});
return docFrag;
}
|
import './main.css'
import '../style/style.css'
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App.jsx'
main()
function main() {
const app = document.getElementsByClassName('demonstration')[0]
ReactDOM.render(<App />, app)
}
|
/*!--------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
/*---------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
define("vs/workbench/parts/debug/electron-browser/repl.nls", {
"vs/workbench/parts/debug/electron-browser/repl": [
"Read Eval Print Loop Panel"
],
"vs/workbench/parts/debug/electron-browser/replViewer": [
"Object state is captured from first evaluation",
"Click to follow (Cmd + click opens to the side)",
"Click to follow (Ctrl + click opens to the side)",
"Variable {0} has value {1}, read eval print loop, debug",
"Expression {0} has value {1}, read eval print loop, debug",
"{0}, read eval print loop, debug",
"Output variable {0} has value {1}, read eval print loop, debug"
]
});
|
(function (window) {
var Muuri = window.Muuri;
QUnit.module('Grid events');
QUnit.test('synchronize: should be triggered after grid.synchronize()', function (assert) {
assert.expect(1);
var container = utils.createGridElements();
var grid = new Muuri(container);
var teardown = function () {
grid.destroy();
container.parentNode.removeChild(container);
};
grid.on('synchronize', function () {
assert.strictEqual(arguments.length, 0, 'callback: should have no arguments');
});
grid.synchronize();
teardown();
});
})(this);
|
var fs = require('fs'),
exec = require('child_process').exec;
var modules = process.argv.slice(2)[0];
modules = modules ? modules.split('=')[1].split(',') : [ ];
var minifier = process.argv.slice(3)[0];
var mininfierCmd;
minifier = minifier ? minifier.split('=')[1] : 'yui';
if (minifier === 'yui') {
mininfierCmd = 'java -jar lib/yuicompressor-2.4.2.jar dist/all.js -o dist/all.min.js';
}
else if (minifier === 'closure') {
mininfierCmd = 'java -jar lib/google_closure_compiler.jar --js dist/all.js --js_output_file dist/all.min.js';
}
var includeAllModules = modules.length === 1 && modules[0] === 'ALL';
var distFileContents = '';
function appendFileContents(fileNames, callback) {
(function readNextFile() {
if (fileNames.length <= 0) {
return callback();
}
var fileName = fileNames.shift();
if (!fileName) {
return readNextFile();
}
fs.readFile(__dirname + '/' + fileName, function (err, data) {
if (err) throw err;
distFileContents += (data + '\n');
readNextFile();
});
})();
}
function ifSpecifiedInclude(moduleName, fileName) {
return (modules.indexOf(moduleName) > -1 || includeAllModules) ? fileName : '';
}
var filesToInclude = [
'HEADER.js',
ifSpecifiedInclude('serialization', 'lib/json2.js'),
ifSpecifiedInclude('text', 'lib/cufon.js'),
'src/log.js',
'src/observable.js',
'src/util/misc.js',
'src/util/lang_array.js',
'src/util/lang_object.js',
'src/util/lang_string.js',
'src/util/lang_function.js',
'src/util/lang_class.js',
'src/util/dom_event.js',
'src/util/dom_style.js',
'src/util/dom_misc.js',
'src/util/dom_request.js',
ifSpecifiedInclude('parser', 'src/parser.js'),
'src/gradient.js',
'src/point.class.js',
'src/intersection.class.js',
'src/color.class.js',
'src/static_canvas.class.js',
ifSpecifiedInclude('interaction', 'src/canvas.class.js'),
'src/canvas.animation.js',
ifSpecifiedInclude('serialization', 'src/canvas.serialization.js'),
'src/object.class.js',
'src/line.class.js',
'src/circle.class.js',
'src/triangle.class.js',
'src/ellipse.class.js',
'src/rect.class.js',
'src/polyline.class.js',
'src/polygon.class.js',
'src/path.class.js',
'src/path_group.class.js',
'src/group.class.js',
'src/image.class.js',
ifSpecifiedInclude('image_filters', 'src/image_filters.js'),
ifSpecifiedInclude('text', 'src/text.class.js'),
ifSpecifiedInclude('node', 'src/fabric_node.js')
];
appendFileContents(filesToInclude, function() {
fs.writeFile('dist/all.js', distFileContents, function (err) {
if (err) {
console.log(err);
throw err;
}
console.log('Built distribution to dist/all.js');
exec(mininfierCmd, function (error, output) {
if (!error) {
console.log('Minified using', minifier, 'to dist/all.min.js');
}
exec('gzip -c dist/all.min.js > dist/all.min.js.gz', function (error, output) {
console.log('Gzipped to dist/all.min.js.gz');
exec('ls -l dist', function (error, output) {
console.log(output.replace(/^.*/, ''));
});
});
});
});
});
|
import React from "react"
import gray from "gray-percentage"
import { StyleSheet, css } from "aphrodite"
const styles = StyleSheet.create({
editor: {
":active": {
borderColor: gray(75, 0, true),
},
":hover": {
borderColor: gray(75, 0, true),
},
":focus": {
borderColor: gray(75, 0, true),
},
},
})
const Select = ({ options, style = {}, value, onChange }) => {
const optionsEls = options.map((text, i) => (
<option key={i} value={i}>
{text}
</option>
))
return (
<select
className={css(styles.editor)}
style={{
background:
"url(\"data:image/svg+xml;utf8,<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='18' height='18' viewBox='0 0 24 24'><path fill='rgb(153, 153, 153)' d='M7.406 7.828l4.594 4.594 4.594-4.594 1.406 1.406-6 6-6-6z'></path></svg>\")",
backgroundColor: gray(20),
backgroundPosition: "100% 50%",
backgroundRepeat: "no-repeat",
border: "1px solid",
borderColor: gray(50, 0, true),
borderRadius: 3,
color: gray(90, 0, true),
fontSize: 12,
width: 80,
padding: "2px 8px",
height: 24,
outline: "none",
apperance: "none",
mozAppearance: "none",
webkitAppearance: "none",
...style,
}}
value={value}
onChange={(e) => onChange(e.target.value)}
onKeyDown={(e) => {
const valueInt = parseInt(value, 10)
let change = false
let newValue
if (e.which === 40 || e.which === 38) {
e.preventDefault()
}
if (e.which === 40) {
// arrow down
change = true
// At end?
if (valueInt === options.length - 1) {
newValue = 0
} else {
newValue = valueInt + 1
}
}
if (e.which === 38) {
// arrow up
change = true
// At beginning?
if (valueInt === 0) {
newValue = options.length - 1
} else {
newValue = valueInt - 1
}
}
// If keyboard press was up or down then change.
if (change) {
onChange(newValue.toString())
}
return false
}}
>
{optionsEls}
</select>
)
}
export default Select
|
'use strict';
const path = require('path');
const getMimeType = require('./get-mime-type');
module.exports = function(filePath) {
let ext = path.extname(filePath).toLowerCase(),
isGzipped = false;
if (ext === '.gz') {
isGzipped = true;
ext = path.extname(filePath.slice(0, -3)).toLowerCase();
}
return {
gzip: isGzipped,
extname: ext,
mimeType: getMimeType(ext)
};
};
|
import React from 'react';
const Cell = ({ value, columnKey }) => (
<td>{'' + value}</td>
);
export default Cell;
|
var request = require('request')
var static = require('../')
var levelup = require('level-test')()
var http = require('http')
var tape = require('tape')
var fs = require('fs')
var db = levelup('level-static-test')
var port = ~~(Math.random()*60000) + 1024
function url() {
return 'http://localhost:'+port+'/'+[].slice.call(arguments).join('/')
}
tape('simple test', function (t) {
var server = http.createServer(static(db)).listen(port, function () {
var put = request.put(url('foo'))
put.write('hello\n')
put.end()
put.on('end', function () {
request(url('foo'), function (err, _, body) {
t.equal(body, 'hello\n')
server.close()
t.end()
})
})
})
})
tape('large file', function (t) {
var server = http.createServer(static(db)).listen(port, function () {
var d3 = '', l = 0
var put = request.put(url('d3.v2.js'))
fs.createReadStream(__dirname + '/fixtures/d3.v2.js', 'utf-8')
.on('data', function (data) {
d3 += data.toString()
l += data.length
})
.pipe(put)
put.on('end', function () {
request(url('d3.v2.js'), function (err, _, body) {
if(err) throw err
t.equal(body, d3)
server.close()
t.end()
})
})
})
})
tape('url parser option', function (t) {
var opt = {};
opt.urlparser = function(url){
return url.split('?')[0]
}
var server = http.createServer(static(db, opt)).listen(port, function () {
var d3 = '', l = 0
var put = request.put(url('urlparser.js?aparam=hello'))
fs.createReadStream(__dirname + '/fixtures/d3.v2.js', 'utf-8')
.on('data', function (data) {
d3 += data.toString()
l += data.length
})
.pipe(put)
put.on('end', function () {
request(url('urlparser.js'), function (err, _, body) {
if(err) throw err
t.equal(body, d3)
server.close()
t.end()
})
})
})
})
|
'use strict';
var React = require('react');
var mui = require('material-ui'),
RaisedButton = mui.RaisedButton,
Paper = mui.Paper,
Dialog = mui.Dialog,
TextField = mui.TextField;
var util = require('utils/util');
var toastr = require('toastr');
var api = require('utils/api');
var bootstrap = require('bootstrap');
var UserActions = require('actions/UserActions');
var UserStore = require('stores/UserStore');
import connectToStores from 'alt-utils/lib/connectToStores';
import {changeHandler} from 'utils/component-utils';
@connectToStores
@changeHandler
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
loginForm: {},
forgotForm: {},
forgot_dialog: false
};
}
static getStores() {
return [UserStore];
}
static getPropsFromStores() {
return UserStore.getState();
}
login() {
UserActions.login(this.state.loginForm)
}
toggle_forgot() {
this.setState({forgot_dialog: !this.state.forgot_dialog});
}
forgot() {
var that = this;
var email = this.state.forgotForm.email;
if (email) {
api.post(`/api/public/forgot_password/${email}`, {}, function(res) {
if (res.message) toastr.info(res.message);
if (res.success) that.toggle_forgot();
});
}
}
render() {
return (
<div className="row">
<Paper className="col-sm-6 col-sm-offset-3" zDepth="3" style={{marginTop: "30px", padding: "10px"}} rounded={true}>
<div className="row">
<div className="col-sm-4 text-center">
<img src="/images/logos/echosense_512.png" style={{marginTop: "25px"}} width="100" />
</div>
<div className="col-sm-8">
<div className="alert alert-danger" hidden={!this.props.error}>{ this.props.error }</div>
<TextField
type='text'
hintText="Enter email"
floatingLabelText="Email"
value={this.state.loginForm._login}
onChange={this.changeHandler.bind(this, 'loginForm', '_login')} />
<TextField
type='password'
hintText="Enter password"
floatingLabelText="Password"
value={this.state.loginForm._pw}
onChange={this.changeHandler.bind(this, 'loginForm', '_pw')} />
<br/>
<RaisedButton onClick={this.login.bind(this)} label="Sign In" secondary={true} style={{ marginBottom: "15px" }} />
<p><small>
<a href="javascript:void(0)" onClick={this.toggle_forgot.bind(this)}>Forgot password</a>
</small></p>
</div>
</div>
</Paper>
<Dialog title="Forgot Password?" open={this.state.forgot_dialog} onRequestClose={this.toggle_forgot.bind(this)}>
<TextField
type='text'
hintText="Enter Email"
floatingLabelText="Email"
value={this.state.forgotForm.email}
onChange={this.changeHandler.bind(this, 'forgotForm', 'email')} />
<RaisedButton onClick={this.forgot.bind(this)} label="Reset Password"
secondary={true} />
</Dialog>
</div>
)
}
};
module.exports = Login;
|
var a, b;
a = b;
if (a) {
console.log("a");
}
//可以合併成為這樣(Bad)
if (a = b) {
console.log("a=b");
}
//但我們常常會看成這樣
if (a == b) {
console.log("a==b");
}
|
(function() {
'use strict';
require('structure/iterator');
var Set = require('structure/set'),
Map = require('structure/map');
describe('set', function() {
it('should be defined if required', function() {
(Set != null).should.be.true;
});
it('should instantiate correctly, and without error', function() {
var set = new Set();
(set != null).should.be.true;
set.size.should.equal(0);
});
it('should accept an array as a construction parameter', function() {
var set = new Set([1]);
set.size.should.equal(1);
set.has(0).should.be.false;
set.has(1).should.be.true;
set.has(2).should.be.false;
var set = new Set([1, 2, 3]);
set.size.should.equal(3);
set.has(0).should.be.false;
set.has(1).should.be.true;
set.has(2).should.be.true;
set.has(3).should.be.true;
set.has(4).should.be.false;
var set = new Set([]);
set.size.should.equal(0);
set.has(0).should.be.false;
});
it('should accept another Set as a construction parameter', function() {
var set = new Set([1]);
var copy = new Set(set);
copy.size.should.equal(1);
copy.has(0).should.be.false;
copy.has(1).should.be.true;
copy.has(2).should.be.false;
var set = new Set([1, 2, 3]);
var copy = new Set(set);
copy.size.should.equal(3);
copy.has(0).should.be.false;
copy.has(1).should.be.true;
copy.has(2).should.be.true;
copy.has(3).should.be.true;
copy.has(4).should.be.false;
});
it('should add() elements specified', function() {
var set = new Set([1]);
set.size.should.equal(1);
set.has(0).should.be.false;
set.has(1).should.be.true;
set.has(2).should.be.false;
set.has(NaN).should.be.false;
set.has('test').should.be.false;
set.add(NaN);
set.add('test');
set.has(NaN).should.be.true;
set.has('test').should.be.true;
});
it('should be able to create an array of contained values', function() {
var source = [2, 1, {}, 'test', false],
index = 0,
set = new Set(source),
values = set.toArray();
for(var index = 0, length = values.length; index < length; index++) {
values[index].should.be.exactly(source[index]);
}
});
});
})();
|
'use strict';
let gulp = require('gulp');
let config = require('../config');
let $ = require('gulp-load-plugins')();
let _ = require('lodash');
let path = require('path');
let prefix = 'js';
let taskName = function(bundle) {
return prefix + '-' + bundle.name;
};
let bundles = config.js;
gulp.task(prefix, _.map(bundles, function(bundle) {
return taskName(bundle);
}));
_.forEach(bundles, function(bundle, key) {
gulp.task(taskName(bundle), function() {
return gulp.src(bundle.src)
.pipe($.newer(path.resolve(bundle.dest, bundle.name)))
.pipe($.if(config.debug, $.debug()))
.pipe($.if(bundle.sourcemaps, $.sourcemaps.init()))
.pipe($.concat(bundle.name))
.pipe($.if(config.production, $.uglify()))
.pipe($.if(bundle.sourcemaps, $.sourcemaps.write('.')))
.pipe(gulp.dest(bundle.dest));
});
});
module.exports = {
taskName: taskName,
};
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var plugin_1 = require('./plugin');
/**
* @name Media Capture
* @description
* @usage
* ```typescript
* import { MediaCapture, MediaFile, CaptureError, CaptureImageOptions } from 'ionic-native';
*
*
* let options: CaptureImageOptions = { limit: 3 };
* MediaCapture.captureImage(options)
* .then(
* (data: MediaFile[]) => console.log(data),
* (err: CaptureError) => console.error(err)
* );
*
* ```
* @interfaces
* MediaFile
* MediaFileData
* CaptureError
* CaptureAudioOptions
* CaptureImageOptions
* CaptureVideoOptions
* ConfigurationData
*/
var MediaCapture = (function () {
function MediaCapture() {
}
/**
* Start the audio recorder application and return information about captured audio clip files.
* @param options
* @returns {Promise<MediaFile[]>}
*/
MediaCapture.captureAudio = function (options) { return; };
/**
* Start the camera application and return information about captured image files.
* @param options
* @returns {Promise<MediaFile[]>}
*/
MediaCapture.captureImage = function (options) { return; };
/**
* Start the video recorder application and return information about captured video clip files.
* @param options
* @returns {Promise<MediaFile[]>}
*/
MediaCapture.captureVideo = function (options) { return; };
/**
* is fired if the capture call is successful
* @returns {Observable<MediaFile[]>}
*/
MediaCapture.onPendingCaptureResult = function () { return; };
/**
* is fired if the capture call is unsuccessful
* @returns {Observable<CaptureError>}
*/
MediaCapture.onPendingCaptureError = function () { return; };
__decorate([
plugin_1.CordovaProperty
], MediaCapture, "supportedImageModes", void 0);
__decorate([
plugin_1.CordovaProperty
], MediaCapture, "supportedAudioModes", void 0);
__decorate([
plugin_1.CordovaProperty
], MediaCapture, "supportedVideoModes", void 0);
__decorate([
plugin_1.Cordova({
callbackOrder: 'reverse'
})
], MediaCapture, "captureAudio", null);
__decorate([
plugin_1.Cordova({
callbackOrder: 'reverse'
})
], MediaCapture, "captureImage", null);
__decorate([
plugin_1.Cordova({
callbackOrder: 'reverse'
})
], MediaCapture, "captureVideo", null);
__decorate([
plugin_1.Cordova({
eventObservable: true,
event: 'pendingcaptureresult'
})
], MediaCapture, "onPendingCaptureResult", null);
__decorate([
plugin_1.Cordova({
eventObservable: true,
event: 'pendingcaptureerror'
})
], MediaCapture, "onPendingCaptureError", null);
MediaCapture = __decorate([
plugin_1.Plugin({
pluginName: 'MediaCapture',
plugin: 'cordova-plugin-media-capture',
pluginRef: 'navigator.device.capture',
repo: 'https://github.com/apache/cordova-plugin-media-capture'
})
], MediaCapture);
return MediaCapture;
}());
exports.MediaCapture = MediaCapture;
//# sourceMappingURL=media-capture.js.map
|
try { require('mongoose').connect(process.env.MONGODB_URI); } catch (e) {}
const model = require('mongoose').model('User', { object: Object });
model._find = (args, exec) => {
args.skip = args.skip - 0;
args.limit = args.limit - 0;
const _id = args._id || false;
const sort = args.sort || {};
const where = args.where || {};
const limit = args.limit > 0 && args.limit < 24 ? args.limit : 24;
const skip = args.skip > 0 ? args.skip : 0;
const select = args.select || {};
if (_id) {
model.findById(_id, exec);
} else {
model.find(where).
select(select).
limit(limit).
skip(skip).
sort(sort).
exec(exec);
}
};
module.exports = model;
|
(function () {
"use strict";
function initController($scope, $rootScope, $timeout, $state, authenticationFactory, fpmUtilities) {
var vm = this;
function activateController() {
authenticationFactory.logout(true);
$timeout(function () {
$rootScope.$broadcast("$fpm:onLoginViewLoaded", { fromLogout: true });
$state.go("login");
}, 200);
}
$scope.$on("$ionicView.beforeEnter", function (e, data) {
activateController();
});
}
initController.$inject = ["$scope", "$rootScope", "$timeout", "$state", "authenticationFactory", "fpm-utilities-factory"];
angular.module("fpm").controller("logout-controller", initController);
})();
|
Router.route('/', {
name: 'home',
data: {meteor: 'Meteor'}
})
|
var fs = require ('fs');
var path = require('path');
var _ = require('underscore');
var apiGen = require('../src/apiGen');
var objectifyTree = require('../src/objectifyTree');
module.exports = function (grunt) {
grunt.registerMultiTask ('api', 'Generates api docs', function () {
grunt.log.writeln ("Starting RazorDoc...");
var configDir = process.cwd ();
var options = this.options ({});
var apiMeta = options.src;
var tocPath = path.resolve (configDir, options.toc);
var toc = fs.readFileSync (tocPath, 'utf-8');
var outPath = options.outPath;
var templateDir = options.apiTemplates;
var ext = options.suffix;
var outputPath = path.resolve(configDir, options.outPath);
var tree = JSON.parse(fs.readFileSync (apiMeta, 'utf-8'));
var constantsPath = path.resolve (configDir, options.constantsPath);
var constantsObj = JSON.parse (fs.readFileSync (constantsPath, 'utf-8'));
tree = objectifyTree(tree);
apiGen.generate(tree, templateDir, outPath, ext, true, {}, {}, constantsObj, '', options, toc);
});
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.