code stringlengths 2 1.05M |
|---|
// Get main modules
var telegram = require('../lib/telegram-bot.js');
var should = require('should');
var path = require('path');
/**
* NOTE1: Create test bot by yourself throught BotFather
* NOTE2: Your test bot can have any username (of course), but first_name should be equal to "Test Bot"
* NOTE3: Create chat with only 2 members: you and your bot
*/
// Get needed environment
var apiKey = process.env.telegramApiKey; // This is your bot token
var chatId = parseInt(process.env.telegramChatId); // This is your chatId
var forwardMessageId = parseInt(process.env.telegramForwardMessageId); // This is message_id inside the chatId that will be forwarded
var api = null; // this is main API shared variable
/**
* HOOK: Check needed environment
*/
before(function checkEnvironment()
{
var err = null;
if (!apiKey) err = new Error('telegramApiKey environment variable should be defined');
else if (!chatId) err = new Error('telegramChatId environment variable should be defined');
else if (!forwardMessageId) err = new Error('telegramForwardMessageId environment variable should be defined');
if (err)
{
console.log('===========================================================================');
console.log('= For testing you need to create dedicated bot through BotFather');
console.log('= Create chat and add only 2 members into it: you and your bot');
console.log('= Export following environment variables:');
console.log('= telegramApiKey: your bot auth token');
console.log('= telegramChatId: ID of created chat');
console.log('= telegramForwardMessageId: message_id of the message inside the chat');
console.log('= ');
console.log('= These environment variables are only needed for running tests');
console.log('===========================================================================');
throw err;
}
});
afterEach(function timeout(done)
{
setTimeout(done, 500);
});
describe('API', function()
{
describe('wrong configuration', function()
{
/**
* Function resets shared API instance
*/
afterEach(function unsetupAPI()
{
api = null;
});
it('unknown token', function(done)
{
api = new telegram({
token: '111111111:AAAAAAAAAAAAAAAAAAA-aaaaaaaaaaaaaaaa'
});
api.getMe()
.then(function(data)
{
throw new Error('Function should fail');
})
.catch(function(err)
{
err.should.have.property('statusCode', 401)
done();
});
});
});
describe('functions', function()
{
/**
* Function setups shared API instance
*/
before(function setupAPI()
{
// Create shared API for functions testing
api = new telegram({
token: apiKey
});
});
/**
* Function resets shared API instance
*/
after(function unsetupAPI()
{
api = null;
});
////////////////////////////////////////////////////////////////////////
//
// FUNCTION: getMe
//
////////////////////////////////////////////////////////////////////////
describe('getMe', function()
{
it('should return valid data with promise', function(done)
{
api.getMe()
.then(function(data)
{
should.exist(data);
data.should.property('first_name', 'Test Bot');
done();
})
.catch(function(err)
{
throw new Error(err);
});
});
it('should return valid data with callback', function(done)
{
api.getMe(function(err, data)
{
should.not.exist(err);
should.exist(data);
data.should.property('first_name', 'Test Bot');
done();
});
});
});
////////////////////////////////////////////////////////////////////////
//
// FUNCTION: sendMessage
//
////////////////////////////////////////////////////////////////////////
describe('sendMessage', function()
{
it('should succeed with promise', function(done)
{
api.sendMessage({
chat_id: chatId,
text: 'Test Message 1'
})
.then(function(data)
{
should.exist(data);
data.should.property('message_id');
data.should.property('text');
data.should.property('chat');
data.chat.should.property('id', chatId);
done();
})
.catch(function(err)
{
throw new Error(err);
});
});
it('should succeed with callback', function(done)
{
api.sendMessage({
chat_id: chatId,
text: 'Test Message 2'
}, function(err, data)
{
should.not.exist(err);
should.exist(data);
data.should.property('message_id');
data.should.property('text');
data.should.property('chat');
data.chat.should.property('id', chatId);
done();
});
});
// TO DO
it('verify parse_mode');
it('verify disable_web_page_preview');
it('verify disable_notification');
it('verify reply_to_message_id');
it('verify reply_markup');
});
////////////////////////////////////////////////////////////////////////
//
// FUNCTION: forwardMessage
//
////////////////////////////////////////////////////////////////////////
describe('forwardMessage', function()
{
it('should succeed with promise', function(done)
{
api.forwardMessage({
chat_id: chatId,
from_chat_id: chatId,
message_id: forwardMessageId
})
.then(function(data)
{
should.exist(data);
data.should.property('message_id');
data.should.property('text');
data.should.property('chat');
data.chat.should.property('id', chatId);
done();
})
.catch(function(err)
{
throw new Error(err);
});
});
it('should succeed with callback', function(done)
{
api.forwardMessage({
chat_id: chatId,
from_chat_id: chatId,
message_id: forwardMessageId
}, function(err, data)
{
should.not.exist(err);
should.exist(data);
data.should.property('message_id');
data.should.property('text');
data.should.property('chat');
data.chat.should.property('id', chatId);
done();
});
});
// TO DO
it('verify disable_notification');
});
////////////////////////////////////////////////////////////////////////
//
// FUNCTION: sendPhoto
//
////////////////////////////////////////////////////////////////////////
describe('sendPhoto', function()
{
it('should succeed with promise', function(done)
{
api.sendPhoto({
chat_id: chatId,
photo: path.join(__dirname, './assets/image.png'),
caption: 'My Linux photo'
})
.then(function(data)
{
should.exist(data);
data.should.property('message_id');
data.should.property('photo');
data.should.property('chat');
data.chat.should.property('id', chatId);
done();
})
.catch(function(err)
{
throw new Error(err);
});
});
it('should succeed with callback', function(done)
{
api.sendPhoto({
chat_id: chatId,
photo: path.join(__dirname, './assets/image.png'),
caption: 'My Linux photo'
}, function(err, data)
{
should.not.exist(err);
should.exist(data);
data.should.property('message_id');
data.should.property('photo');
data.should.property('chat');
data.chat.should.property('id', chatId);
done();
});
});
// TO DO
it('verify disable_notification');
it('verify reply_to_message_id');
it('verify reply_markup');
it('verify photo as file_id');
});
////////////////////////////////////////////////////////////////////////
//
// FUNCTION: sendAudio
//
////////////////////////////////////////////////////////////////////////
describe('sendAudio', function()
{
// TO DO
it('should succeed with promise');
it('should succeed with callback');
it('verify disable_notification');
it('verify reply_to_message_id');
it('verify reply_markup');
it('verify audio as file_id');
});
////////////////////////////////////////////////////////////////////////
//
// FUNCTION: sendDocument
//
////////////////////////////////////////////////////////////////////////
describe('sendDocument', function()
{
// TO DO
it('should succeed with promise');
it('should succeed with callback');
it('verify disable_notification');
it('verify reply_to_message_id');
it('verify reply_markup');
it('verify document as file_id');
});
////////////////////////////////////////////////////////////////////////
//
// FUNCTION: sendSticker
//
////////////////////////////////////////////////////////////////////////
describe('sendSticker', function()
{
// TO DO
it('should succeed with promise');
it('should succeed with callback');
it('verify disable_notification');
it('verify reply_to_message_id');
it('verify reply_markup');
it('verify sticker as file_id');
});
////////////////////////////////////////////////////////////////////////
//
// FUNCTION: sendVideo
//
////////////////////////////////////////////////////////////////////////
describe('sendVideo', function()
{
// TO DO
it('should succeed with promise');
it('should succeed with callback');
it('verify disable_notification');
it('verify reply_to_message_id');
it('verify reply_markup');
it('verify video as file_id');
});
////////////////////////////////////////////////////////////////////////
//
// FUNCTION: sendVoice
//
////////////////////////////////////////////////////////////////////////
describe('sendVoice', function()
{
// TO DO
it('should succeed with promise');
it('should succeed with callback');
it('verify disable_notification');
it('verify reply_to_message_id');
it('verify reply_markup');
it('verify voice as file_id');
});
////////////////////////////////////////////////////////////////////////
//
// FUNCTION: sendLocation
//
////////////////////////////////////////////////////////////////////////
describe('sendLocation', function()
{
it('should succeed with promise', function(done)
{
api.sendLocation({
chat_id: chatId,
latitude: 56.326206,
longitude: 44.005865
})
.then(function(data)
{
should.exist(data);
data.should.property('message_id');
data.should.property('location');
data.should.property('chat');
data.chat.should.property('id', chatId);
done();
})
.catch(function(err)
{
throw new Error(err);
});
});
it('should succeed with callback', function(done)
{
api.sendLocation({
chat_id: chatId,
latitude: 56.326206,
longitude: 44.005865
}, function(err, data)
{
should.not.exist(err);
should.exist(data);
data.should.property('message_id');
data.should.property('location');
data.should.property('chat');
data.chat.should.property('id', chatId);
done();
});
});
// TO DO
it('verify disable_notification');
it('verify reply_to_message_id');
it('verify reply_markup');
});
////////////////////////////////////////////////////////////////////////
//
// FUNCTION: sendVenue
//
////////////////////////////////////////////////////////////////////////
describe('sendVenue', function()
{
it('should succeed with promise', function(done)
{
api.sendVenue({
chat_id: chatId,
latitude: 56.326206,
longitude: 44.005865,
title: 'Фонтан',
address: 'Nizhniy Novgorod, Minina sq.'
})
.then(function(data)
{
should.exist(data);
data.should.property('message_id');
data.should.property('venue');
data.should.property('chat');
data.chat.should.property('id', chatId);
done();
})
.catch(function(err)
{
throw new Error(err);
});
});
it('should succeed with callback', function(done)
{
api.sendVenue({
chat_id: chatId,
latitude: 56.326206,
longitude: 44.005865,
title: 'Фонтан',
address: 'Nizhniy Novgorod, Minina sq.'
}, function(err, data)
{
should.not.exist(err);
should.exist(data);
data.should.property('message_id');
data.should.property('venue');
data.should.property('chat');
data.chat.should.property('id', chatId);
done();
});
});
// TO DO
it('verify disable_notification');
it('verify reply_to_message_id');
it('verify reply_markup');
});
////////////////////////////////////////////////////////////////////////
//
// FUNCTION: sendContact
//
////////////////////////////////////////////////////////////////////////
describe('sendContact', function()
{
it('should succeed with promise', function(done)
{
api.sendContact({
chat_id: chatId,
phone_number: '+70001234567',
first_name: 'Max',
last_name: 'Stepanov'
})
.then(function(data)
{
should.exist(data);
data.should.property('message_id');
data.should.property('contact');
data.should.property('chat');
data.chat.should.property('id', chatId);
done();
})
.catch(function(err)
{
throw new Error(err);
});
});
it('should succeed with callback', function(done)
{
api.sendContact({
chat_id: chatId,
phone_number: '+70001234567',
first_name: 'Max',
last_name: 'Stepanov'
}, function(err, data)
{
should.not.exist(err);
should.exist(data);
data.should.property('message_id');
data.should.property('contact');
data.should.property('chat');
data.chat.should.property('id', chatId);
done();
});
});
// TO DO
it('verify disable_notification');
it('verify reply_to_message_id');
it('verify reply_markup');
});
////////////////////////////////////////////////////////////////////////
//
// FUNCTION: sendChatAction
//
////////////////////////////////////////////////////////////////////////
describe('sendChatAction', function()
{
// Checking only one action
// It's enough for verifying bot API
it('should succeed with promise', function(done)
{
api.sendChatAction({
chat_id: chatId,
action: 'typing'
})
.then(function(data)
{
should.exist(data);
data.should.be.true();
done();
})
.catch(function(err)
{
throw new Error(err);
});
});
});
////////////////////////////////////////////////////////////////////////
//
// FUNCTION: getUserProfilePhotos
//
////////////////////////////////////////////////////////////////////////
describe('getUserProfilePhotos', function()
{
// TO DO
it('should succeed with promise');
});
////////////////////////////////////////////////////////////////////////
//
// FUNCTION: getFile
//
////////////////////////////////////////////////////////////////////////
describe('getFile', function()
{
// TO DO
it('should succeed with promise');
});
////////////////////////////////////////////////////////////////////////
//
// FUNCTION: kickChatMember
//
////////////////////////////////////////////////////////////////////////
describe('kickChatMember', function()
{
// TO DO
it('should succeed with promise');
});
////////////////////////////////////////////////////////////////////////
//
// FUNCTION: leaveChat
//
////////////////////////////////////////////////////////////////////////
describe('leaveChat', function()
{
// TO DO
it('should succeed with promise');
});
////////////////////////////////////////////////////////////////////////
//
// FUNCTION: unbanChatMember
//
////////////////////////////////////////////////////////////////////////
describe('unbanChatMember', function()
{
// TO DO
it('should succeed with promise');
});
////////////////////////////////////////////////////////////////////////
//
// FUNCTION: getChat
//
////////////////////////////////////////////////////////////////////////
describe('getChat', function()
{
it('should succeed with promise', function(done)
{
api.getChat({
chat_id: chatId
})
.then(function(data)
{
should.exist(data);
data.should.property('id', chatId);
done();
})
.catch(function(err)
{
throw new Error(err);
});
});
});
////////////////////////////////////////////////////////////////////////
//
// FUNCTION: getChatAdministrators
//
////////////////////////////////////////////////////////////////////////
describe('getChatAdministrators', function()
{
it('should succeed with promise', function(done)
{
api.getChatAdministrators({
chat_id: chatId
})
.then(function(data)
{
should.exist(data);
data.should.be.Array();
done();
})
.catch(function(err)
{
throw new Error(err);
});
});
});
////////////////////////////////////////////////////////////////////////
//
// FUNCTION: getChatMembersCount
//
////////////////////////////////////////////////////////////////////////
describe('getChatMembersCount', function()
{
it('should succeed with promise', function(done)
{
api.getChatMembersCount({
chat_id: chatId
})
.then(function(data)
{
should.exist(data);
data.should.be.equal(2);
done();
})
.catch(function(err)
{
throw new Error(err);
});
});
});
////////////////////////////////////////////////////////////////////////
//
// FUNCTION: getChatMember
//
////////////////////////////////////////////////////////////////////////
describe('getChatMember', function()
{
// TO DO
it('should succeed with promise');
});
////////////////////////////////////////////////////////////////////////
//
// FUNCTION: answerCallbackQuery
//
////////////////////////////////////////////////////////////////////////
describe('answerCallbackQuery', function()
{
// TO DO
it('should succeed with promise');
});
});
}); |
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('Docker container says hello!');
});
app.listen(8080);
|
/*
* Arctic-snowstorm
* (c) 2014-2015, Teempla Inc.
*
* MIT License
*/
"use strict";
define([
'abstractWorker',
'log',
'config',
'q',
'lodash'
], function(AbstractWorker, log, config, Q, _) {
/**
* This worker demonstrating to you the message processing workflow
*
* @class ExampleWorker
*/
return AbstractWorker.extend({
/**
* Use this method instead constructor
*/
setUp: function(){
this.timeout = 1000 * (60 * 2); // 2 minutes timeout for this work
},
/**
* This method will be called before execute event.
* In this method you able to reject the message before execution.
*
* You must return empty promise
*
* @param {Object} data
* @param {Boolean} redelivered
* @returns {Promise}
*/
beforeExecute: function(data, redelivered){
log.info('This method fire before every message');
if(data && data.rejectMe === true){
log.warn('You rejected this message, execute won`t be call');
this.reject();
}
return Q();
},
/**
* This method will be called for processing message,
* if beforeExecute not rejected this message before
*/
execute: function(data, redelivered){
// Start time
var startTime = new Date();
var self = this;
log.info('Start example worker', data);
// Do some hard work
Q.delay(1000)
.then(function(){
if(_.isEmpty(data)){
// This exception will be handled by catch
throw new Error('Worker needs some data');
}
log.info('Worker say: ', data.say);
// Success means that message was successful processed
self.success();
})
.catch(function(error){
log.error('Worker say error:', error);
// If we already repeated this message, probably we should reject this message
if(redelivered){
// If we call reject, message will be rejected from queue
self.reject();
}else{
// If we call repeat, message will be redelivered again
self.repeat();
}
})
.done(function(){
log.info('Worker done:', (new Date() - startTime) / 1000, 'sec');
});
}
});
});
|
'use strict'
var webpack = require('webpack')
var plugins = [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
__DEV__: process.env.NODE_ENV === 'development',
__TEST__: process.env.NODE_ENV === 'test'
})
]
if (process.env.NODE_ENV === 'production') {
plugins.push(new webpack.optimize.UglifyJsPlugin())
}
module.exports = {
output: {
library: 'jssPropsSort',
libraryTarget: 'umd'
},
plugins: plugins,
module: {
loaders: [
{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}
]
}
}
|
import React from 'react';
import { NavLink } from 'react-router-dom';
import PropTypes from 'prop-types';
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';
import IconButton from 'material-ui/IconButton';
import ContentClear from 'material-ui/svg-icons/content/clear';
export default class Menu extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<Drawer docked={true} open={this.props.openSideMenu} className='side-menu'>
<div className='close-container'>
<IconButton touch={true} onTouchTap={this.props.toggleSideMenu}>
<ContentClear />
</IconButton>
</div>
<NavLink to='/tabata'><MenuItem onTouchTap={this.props.toggleSideMenu} primaryText='Tabata Timer'/></NavLink>
<NavLink to='/weights'><MenuItem onTouchTap={this.props.toggleSideMenu} primaryText='Weight Tables'/></NavLink>
<NavLink to='/convert'><MenuItem onTouchTap={this.props.toggleSideMenu} primaryText='Weight Conversion'/></NavLink>
</Drawer>
);
}
}
Menu.propTypes = {
openSideMenu: PropTypes.bool.isRequired,
toggleSideMenu: PropTypes.func.isRequired
}
//Tabata Timer
//Weight Percentages, raw and nearest 5 pounds
//What should be on the bar
//Lbs to Kilo |
var ClassAttr = ClassAttr || require('../src/helpers/classattr.js')
/**
* cat constructor
*/
var Cat = function(name, weight){
this._name = name
this.weight = weight || 0
}
Cat.prototype.getName = function(){
return this._name
}
Cat = ClassAttr(cat)
//////////////////////////////////////////////////////////////////////////////////
// comment //
//////////////////////////////////////////////////////////////////////////////////
Cat = ClassAttr(Cat, {
arguments : [String],
privatize : true,
properties : {
name : String,
},
onAfter : function(instance, args){
console.log('onAfter')
}
})
var cat = new Cat('kitty')
console.assert(cat instanceof Cat)
console.assert(cat instanceof Animal)
console.assert(typeof(cat.name) === 'string')
// cat.name = 99
console.log('name', cat.name)
// cat.prout = 99
console.log('salute', cat.salute())
|
import React, { Component } from 'react'
import classnames from 'classnames'
import PropTypes from './utils/proptypes'
import { objectAssign } from './utils/objects'
import Enhance from './higherOrders/FormItem'
import _forms from './styles/_form.scss'
class FormBlock extends Component {
constructor (props) {
super(props)
this.state = {}
this.itemBind = this.itemBind.bind(this)
this.itemUnbind = this.itemUnbind.bind(this)
this.itemChange = this.itemChange.bind(this)
this.items = {}
this.initData = {}
}
getChildContext () {
const { columns, labelWidth, layout, hintType } = this.props
const np = {}
if (columns) np.columns = columns
if (labelWidth) np.labelWidth = labelWidth
if (layout) np.layout = layout
if (hintType) np.hintType = hintType
return {
formData: this.props.value,
itemBind: this.itemBind,
itemUnbind: this.itemUnbind,
itemChange: this.itemChange,
controlProps: objectAssign({}, this.context.controlProps, np)
}
}
componentDidMount () {
this.props.onChange(objectAssign({}, this.props.value, this.initData))
}
itemBind (item) {
const { name, value } = item
const data = { ...this.props.value }
this.items[name] = item
if (value !== undefined && !data[name]) {
this.initData[name] = value
}
}
itemUnbind (name) {
delete this.items[name]
const data = {...this.props.value}
delete data[name]
this.props.onChange(data)
}
itemChange (name, value) {
const data = objectAssign({}, this.props.value, {[name]: value})
this.props.onChange(data)
}
validate (data) {
return Object.keys(this.items).reduce((suc, key) => {
return suc && (this.items[key].validate(data[key], true) === true)
}, true)
}
render () {
const { className, children } = this.props
return (
<div className={classnames(className, _forms[this.props.layout])}>
{children}
</div>
)
}
}
FormBlock.isFormBlock = true
FormBlock.propTypes = {
children: PropTypes.any,
className: PropTypes.string,
columns: PropTypes.number,
hintType: PropTypes.oneOf(['block', 'none', 'pop', 'inline']),
labelWidth: PropTypes.number_string,
layout: PropTypes.oneOf(['aligned', 'stacked', 'inline']),
onChange: PropTypes.func.isRequired,
value: PropTypes.object
}
FormBlock.defaultProps = {
value: {}
}
FormBlock.contextTypes = {
controlProps: PropTypes.object
}
FormBlock.childContextTypes = {
formData: PropTypes.object,
itemBind: PropTypes.func,
itemChange: PropTypes.func,
itemUnbind: PropTypes.func,
controlProps: PropTypes.object
}
export default Enhance(FormBlock)
|
import ParseAuthenticator from '../authenticators/parse';
import LocalStorageWithIdStore from '../stores/local-storage-with-id';
export default {
name: 'authentication',
before: 'simple-auth',
after: 'store',
initialize: function(container, application) {
container.register('authenticator:parse', ParseAuthenticator);
application.inject('authenticator:parse', 'store', 'store:main');
container.register('simple-auth-session-store:local-storage-with-id', LocalStorageWithIdStore);
}
};
|
import { defineMessages } from 'react-intl';
const i18nUserCard = defineMessages({
language: {
id: 'userCard.language',
defaultMessage: 'Language'
},
korean: {
id: 'userCard.korean',
defaultMessage: 'Korean'
},
cancel: {
id: 'userCard.cancel',
defaultMessage: 'Cancel'
},
save: {
id: 'userCard.save',
defaultMessage: 'Save'
},
editButton: {
id: 'userCard.editButton',
defaultMessage: 'Edit'
}
});
export default i18nUserCard;
|
try {
var GPIO = require('onoff').Gpio;
var buttonYes = new GPIO(17, 'in', 'both'),
buttonNo = new GPIO(18, 'in', 'both');
// pass the callback function to the
// as the first argument to watch()
buttonYes.watch(sendYes);
buttonNo.watch(sendNo);
} catch (error) {
console.log("CLIENT: librairie GPIO introuvable");
}
var socket = require('socket.io-client')('http://localhost:1234', { query: "user=user1" });
function sendYes(err, state) {
if (state == 1) {
post(1);
}
}
function sendNo(err, state) {
if (state == 1) {
post(2);
}
}
function post(value) {
console.log("CLIENT: post value");
socket.emit("answer:add", value, function(err){
console.log("CLIENT: value sent");
});
}
socket.on('connected', function() {
post(1);
}); |
var su = require('stylus/lib/utils.js'),
n = require('stylus/lib/nodes'),
u = require('../common/utils.js');
module.exports = {};
var type;
(type = module.exports.vartype = function type(expr) {
expr = su.unwrap(expr);
if(expr.nodes.length > 1) return 'list';
if(typeof expr.first.vals == 'object') return 'hash';
return expr.first.nodeName;
}).raw = true;
var nodeTypes = [
'string',
'list',
'hash',
'ident',
'literal',
'block',
'function',
'boolean',
'rgba',
'null',
'unit',
'hsla',
];
for(var i = nodeTypes.length - 1; i >= 0; i--) {
module.exports['is-' + nodeTypes[i]] = (function(nodeType) {
var fnc;
(fnc = function(expr) {
if(type(expr) == nodeType) return true;
}).raw = true;
return fnc;
})(nodeTypes[i]);
}
(module.exports['is-color'] = function(expr) {
var tp = type(expr);
if(tp == 'rgba' || tp == 'hsla') return true;
}).raw = true;
|
var postcss = require('postcss');
var expect = require('chai').expect;
var size = require('../');
var test = function (input, output) {
expect(postcss(size).process(input).css).to.eql(output);
};
describe('postcss-size', function () {
it('sets width and height', function () {
test('a{ size: 1px 2px; }', 'a{ width: 1px; height: 2px; }');
});
it('sets width and height by one value', function () {
test('a{ size: 1px; }', 'a{ width: 1px; height: 1px; }');
});
it('splits values by brackets', function () {
test('a{ size: calc(4 * 2px) 2px; }',
'a{ width: calc(4 * 2px); height: 2px; }');
});
it('prefix value', function () {
test('a{ size: -webkit-fit-content auto; }',
'a{ width: -webkit-fit-content; height: auto; }');
});
it('auto value', function () {
test('a{ size: .98% auto; }',
'a{ width: .98%; height: auto; }');
});
});
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require rails-ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .
|
/*global module*/
var events = require('events')
, util = require('util')
, format = util.format
, dateUtil = require('./date-util');
const BARS = "▇▅▃▁".split('')
, SYMBOLS = "☀☁☂⚡".split('')
, VALID_MOODS = "sunny|cloudy|rainy|stormy".split('|');
function MoodEngine(client, options) {
events.EventEmitter.call(this);
this.client = client;
this.redisKey = options && options.redisKey || "moods";
}
util.inherits(MoodEngine, events.EventEmitter);
module.exports = MoodEngine;
MoodEngine.prototype.clear = function clear() {
this.emit('debug', format('clearing records in %s', this.redisKey));
this.client.del(this.redisKey);
this.emit('debug', format('deleted records in %s', this.redisKey));
};
MoodEngine.prototype.filter = function filter(moods, filters) {
if (!moods.length || !filters) {
return [];
}
return moods.filter(function(mood) {
var included = true;
if (filters.date) {
included = included && mood.date === filters.date;
}
if (~~filters.since > 0) {
included = included && mood.date >= dateUtil.daysBefore(~~filters.since - 1);
}
if (filters.user) {
included = included && mood.user === filters.user;
}
if (filters.mood) {
if (Array.isArray(filters.mood)) {
included = included && filters.mood.indexOf(mood.mood) !== -1;
} else {
included = included && mood.mood === filters.mood;
}
}
return included;
});
};
MoodEngine.prototype.query = function query() {
var filters = {}, cb;
if (arguments.length === 2 && typeof arguments[1] === "function") {
filters = typeof arguments[0] === "object" ? arguments[0] : {};
cb = arguments[1];
} else {
cb = arguments[0];
}
this.client.lrange(this.redisKey, 0, -1, function(err, reply) {
var moods = [];
if (err) return cb.call(this, err);
try {
moods = reply.map(function(entry) {
return Mood.parse(entry);
});
} catch (e) {
err = e;
}
return cb.call(this, err, this.filter(moods, filters));
}.bind(this));
};
MoodEngine.prototype.exists = function exists(filters, cb) {
this.query(filters, function(err, moods) {
if (err) return cb.call(this, err);
return cb.call(this, err, moods.length > 0);
});
};
MoodEngine.prototype.graph = function graph(filters, cb) {
if (!filters.user) return cb.call(this, new Error("a user is mandatory"));
if (!filters.since) return cb.call(this, new Error("a since filter is mandatory"));
this.query(filters, function(err, moods) {
var graph = "";
if (!moods || !moods.length) {
return cb.call(this, new Error(format('No mood entry for %s in the last %d days.',
filters.user, filters.since)));
}
return cb.call(this, null, moods.sort(function(a, b) {
return a.date > b.date;
}).map(function(mood) {
return mood.bar();
}).join(''));
});
};
MoodEngine.prototype.store = function store(data, cb) {
var mood;
try {
mood = new Mood(data);
} catch (err) {
return cb.call(this, err);
}
this.exists({ date: data.date, user: data.user }, function(err, exists) {
if (err) return cb.call(this, err);
if (exists) {
return cb.call(this, new Error(format('Mood already stored for %s on %s',
data.user, data.date)));
}
this.emit('info', format('storing mood entry for %s: %s', data.user, mood.serialize()));
this.client.rpush(this.redisKey, mood.serialize(), function(err) {
cb.call(this, err, mood);
}.bind(this));
}.bind(this));
};
function Mood(data) {
this.clean(data);
}
Mood.prototype.bar = function bar() {
return BARS[VALID_MOODS.indexOf(this.mood)];
};
Mood.prototype.clean = function clean(data) {
if (typeof data !== "object") {
throw new Error("mood data must be an object");
}
if (!data.date) {
data.date = dateUtil.today();
}
this.date = data.date;
if (!data.user) {
throw new Error('A user is required');
}
this.user = data.user;
if (VALID_MOODS.indexOf(data.mood) === -1) {
throw new Error(format('Invalid mood %s; valid values are %s',
data.mood, VALID_MOODS.join(', ')));
}
if (data.info) {
this.info = data.info.replace(/\s/g, ' ') || undefined;
}
this.mood = data.mood;
};
Mood.prototype.serialize = function serialize() {
return format('%s:%s:%s%s',
this.date,
this.user,
this.mood,
this.info ? format(":%s", this.info) : "");
};
Mood.prototype.symbol = function bar() {
return SYMBOLS[VALID_MOODS.indexOf(this.mood)];
};
Mood.prototype.toString = function toString() {
function formatDate(date) {
if (date === dateUtil.today()) {
return "Today";
} else if (date === dateUtil.yesterday()) {
return "Yesterday";
} else {
return "On " + date;
}
}
var formattedDate = formatDate(this.date);
return format("%s, %s %s in a %s mood %s%s",
formattedDate,
this.user,
formattedDate === "Today" ? "is" : "was",
this.mood,
this.symbol(),
this.info ? format(" (%s)", this.info) : "");
};
Mood.parse = function parse(string) {
var parts = string.split(':');
return new Mood({
date: parts[0]
, user: parts[1]
, mood: parts[2]
, info: parts[3]
});
};
MoodEngine.Mood = Mood;
|
version https://git-lfs.github.com/spec/v1
oid sha256:adcca6734a7ffabd7a41a3eea8f26a9ab11c63423d49c0f67e33ec7d36ca00bc
size 2464
|
version https://git-lfs.github.com/spec/v1
oid sha256:7dc76ca751fb4ecb8f823027323279acf5354496b11c972f5d437fa5a3b3668d
size 31205
|
/*
* grunt-sc-mustache-html
*
* Copyright (c) 2015 Optimal Software s.r.o.
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Requires
var fs = require('fs');
var hogan = require('hogan.js');
var _ = require('underscore');
// Private module
var privateModule = {
// Models
models: {
template: {
name: '',
vanilla: {},
data: {
render: {
layout: '',
},
page: {},
},
},
},
};
// Task module
var taskModule = {
// Properties
properties: {
globals: {},
options: {
src: '',
dist: '',
type: '',
},
},
// Templates
templates: {
layouts: [],
partials: [],
},
// Methods
init: function(globals, options) {
var self = this;
// Properties
self.properties.globals = _.extend({}, self.properties.options, globals);
self.properties.options = _.extend({}, self.properties.options, options);
var fileTypeMatcher = new RegExp('\\.' + self.properties.options.type + '$');
// Templates
self.templates.layouts = self.createTemplatesInFolder(self.properties.options.src + '/layouts', fileTypeMatcher);
grunt.log.ok(self.templates.layouts.length, 'layouts');
self.templates.partials = self.createTemplatesInFolder(self.properties.options.src + '/partials', fileTypeMatcher);
grunt.log.ok(self.templates.partials.length, 'partials');
// Pages
var pagesPath = (self.properties.options.src + '/pages');
var pages = self.createTemplatesInFolder(pagesPath, fileTypeMatcher);
if (pages.length < 1) { grunt.log.error('No page found in folder: ' + pagesPath); return null; }
self.processPageTemplates(pages);
grunt.log.ok(pages.length, 'pages');
},
processPageTemplates: function(value) {
var self = this;
if (!_.isArray(value) || value.length < 1) { return null; }
value.forEach(function(item, index) {
// Properties
var path = ''.concat(self.properties.options.dist, '/', item.name, '.', (item.data.render.extension || 'html'));
// Content
var content = self.createContentFromTemplate(item, path);
if (!_.isString(content) || (content === '')) { content = ''; }
// Process
grunt.file.write(path, content);
});
},
getProperTemplatePath: function(folderPath, name) {
var self = this;
if ((typeof(folderPath) !== 'string') || (folderPath === '')) { return null; }
if ((typeof(name) !== 'string') || (name === '')) { return null; }
var result = ''.concat(folderPath, '/', name, '.', self.properties.options.type);
// Process
return result;
},
createTemplatesInFolder: function(value, fileTypeMatcher) {
var self = this;
if ((typeof(value) !== 'string') || (value === '')) { return []; }
var result = [];
grunt.file.recurse(value, function (path, rootdir, subdir, filename) {
if (!filename.match(fileTypeMatcher)) { return null; }
// Properties
var name = (subdir? (subdir + '/') : '') + filename.replace(fileTypeMatcher, '');
var dataPath = path.replace(fileTypeMatcher, '.json');
// Result
result.push(_.extend({}, privateModule.models.template, {
name: name,
vanilla: hogan.compile(grunt.file.read(path), { sectionTags: [{o:'_i', c:'i'}] }),
data: grunt.file.exists(dataPath)? grunt.file.readJSON(dataPath) : null,
}));
});
// Process
return result;
},
getPathname: function(value) {
var result = value
result = !result.startsWith('build/') ? result : result.substr(5)
result = !result.endsWith('/index.html') ? result : result.substr(0, result.length - 10)
result = !result.endsWith('/index.aspx') ? result : result.substr(0, result.length - 11)
result = !result.endsWith('/index.htm') ? result : result.substr(0, result.length - 9)
result = !result.endsWith('/index.asp') ? result : result.substr(0, result.length - 9)
return result
},
createContentFromTemplate: function(value, path) {
var self = this;
var value = _.extend({}, privateModule.models.template, value);
value.data.page.pathname = self.getPathname(path)
// Case: layout
var layout = self.getLayoutTemplate(value.data.render.layout);
if (layout) {
var partials = self.getTemplatesAsVanilla(self.templates.partials);
partials['content'] = value.vanilla;
return layout.vanilla.render(
_.extend({}, self.properties.globals, value.data),
partials
);
}
// Other case
return value.vanilla.render(
_.extend({}, self.properties.globals, value.data),
self.getTemplatesAsVanilla(self.templates.partials)
);
},
getLayoutTemplate: function(value) {
var self = this;
if ((typeof(value) !== 'string') || (value === '')) { return null; }
// Results
var results = self.templates.layouts.filter(function (item) {
if (item.name === value) { return item; }
});
if (results.length < 1) { return null; }
// Process
return results[0];
},
getTemplatesAsVanilla: function(value) {
var self = this;
if (!_.isArray(value) || (value.length < 1)) { return []; }
// Result
var result = [];
for (var i = 0; i < value.length; i++) {
result[value[i].name] = value[i].vanilla;
}
// Process
return result;
},
};
// Process
grunt.registerMultiTask('sc_mustache_html', 'Compile mustache|hbs templates to HTML', function() {
try {
taskModule.init(this.data.globals, this.options({
src: 'src',
dist: 'dist',
type: 'mustache',
}));
} catch(e) {
grunt.log.error(e.stack);
}
});
};
|
import Request from 'utils/request';
import React from 'react';
export default class WetlandsLegend extends React.Component {
constructor(props) {
super(props);
//- Set legend Info to an empty array until data is returned
this.state = {
legendInfos: []
};
}
componentDidMount() {
Request.getLegendInfos(this.props.url, this.props.layerIds).then(legendInfos => {
this.setState({ legendInfos: legendInfos });
});
}
shouldComponentUpdate(nextProps, nextState) {
return nextState.legendInfos.length !== this.state.legendInfos.length;
}
render() {
return (
<div className='legend-container'>
{this.state.legendInfos.length === 0 ? <div className='legend-unavailable'>No Legend</div> :
<div className='wetlands-legend'>
{this.state.legendInfos.map(this.itemMapper, this)}
</div>
}
</div>
);
}
itemMapper (item, index) {
return <div className='legend-row' key={index}>
<img title={item.label} src={`data:image/png;base64,${item.imageData}`} />
<div className='legend-label'>{item.label}</div>
</div>;
}
}
WetlandsLegend.propTypes = {
url: React.PropTypes.string.isRequired,
layerIds: React.PropTypes.array.isRequired
};
|
var expect = require('chai').expect;
var Mocksy = require('mocksy');
var ask = require('../../index.js');
var server = new Mocksy({port: 9876});
var ORIGIN = 'http://localhost:9876';
describe('request instance', function () {
var request;
beforeEach(function (done) {
request = ask();
server.start(done);
});
afterEach(function (done) {
server.stop(done);
});
it('sets defaults in the contructor', function () {
request = ask({
origin: ORIGIN,
headers: {
'Authorization': 'Bearer 1234'
},
xhrOptions: {
'method': 'POST',
'withCredentials': true
}
});
expect(request.origin()).to.equal(ORIGIN);
expect(request.header('Authorization')).to.equal('Bearer 1234');
expect(request.xhrOption('method')).to.equal('POST');
});
it('sets the default origin for all http requests on the instance', function () {
request.origin(ORIGIN);
return request.get('test')().then(function (res) {
expect(res.body.url).to.equal('/test');
expect(res.body.method).to.equal('GET');
});
});
it('sets the default headers for all http requests on the instance', function () {
request
.origin(ORIGIN)
.header('Authorization', 'Bearer 1234');
return request.get('test')().then(function (res) {
expect(res.body.headers.authorization).to.equal('Bearer 1234');
});
});
it('sets multiple headers from an object', function () {
request
.origin(ORIGIN)
.header({
'Authorization': 'Bearer 1234',
'Content-Type': 'text/html'
});
return request.get('test')().then(function (res) {
expect(res.body.headers.authorization).to.equal('Bearer 1234');
expect(res.body.headers['content-type']).to.equal('text/html');
});
});
it('sets the default xhr options for all http requests on the instance', function () {
request
.origin(ORIGIN)
.xhrOption('method', 'POST');
return request.get('test')().then(function (res) {
expect(res.body.method).to.equal('POST');
});
});
});
describe('making bare requests', function () {
var request;
beforeEach(function (done) {
request = ask();
server.start(done);
});
afterEach(function (done) {
server.stop(done);
});
it('makes a request with a given http method', function () {
var apps = request.http('GET', ORIGIN, 'apps');
return apps().then(function (res) {
expect(res.body.method).to.equal('GET');
expect(res.body.url).to.equal('/apps');
});
});
// Helpers
ask.HTTP_METHODS.forEach(function (method) {
// EXAMPLE: request.get('url', 123)
it('makes a ' + method + ' request', function () {
var requester = request[method.toLowerCase()](ORIGIN, 'requester', 123);
return requester().then(function (res) {
expect(res.body.method).to.equal(method);
expect(res.body.url).to.equal('/requester/123');
});
});
});
it('passes body parameters to various methods', function () {
var create = request
.origin(ORIGIN)
.post('test');
return create({key: 'value'}).then(function (res) {
expect(res.body.body).to.eql({key: 'value'});
});
});
it('extends a resource', function () {
request
.origin(ORIGIN);
var tests = request
.get('tests')
.header('custom', 'header')
.query('test', 'ing');
var oneTest = tests
.extend('123')
.header('extended', 'header');
expect(oneTest.url()).to.equal(ORIGIN + '/tests/123?test=ing');
expect(oneTest.headers.custom).to.equal('header');
expect(oneTest.headers.extended).to.equal('header');
});
});
describe('setting options', function () {
var request;
var requester;
beforeEach(function (done) {
request = ask();
server.start(done);
});
afterEach(function (done) {
server.stop(done);
});
it('sets the request origin', function () {
var requester = request
.get('test')
.origin(ORIGIN);
return requester().then(function (res) {
expect(res.body.url).to.equal('/test');
});
});
it('sets the header for the request', function () {
var requester = request
.get('test')
.origin(ORIGIN)
.header('Authorization', 'Bearer 1234');
return requester().then(function (res) {
expect(res.body.headers.authorization).to.equal('Bearer 1234')
});
});
it('sets an xhr options for the request', function () {
var requester = request
.get('test')
.origin(ORIGIN)
.xhrOption('method', 'POST')
.xhrOption('form', {test: 'test'});
return requester().then(function (res) {
expect(res.body.method).to.equal('POST');
expect(res.body.body).to.eql({test: 'test'});
});
});
it('sets the default settings from the instance on the request', function () {
request
.origin(ORIGIN)
.header('Authorization', 'Bearer 1234');
var test = request.get('test');
expect(test.origin()).to.equal(request.origin());
expect(test.header('Authorization')).to.equal(request.header('Authorization'));
});
it('changing endpoint request settings does not modify the state of the instance', function () {
var TEST_ORIGIN = 'http://localhost:1234';
var TEST_ORIGIN2 = 'http://localhost:8888';
// Instance
request
.origin(ORIGIN)
.xhrOption('method', 'POST')
.header('Authorization', 'Bearer 1234');
// Endpoint
var test = request
.get('test')
.origin(TEST_ORIGIN)
.xhrOption('method', 'GET')
.header('Authorization', 'Session 1234');
var test2 = request
.get('test2')
.origin(TEST_ORIGIN2);
expect(request.xhrOption('method')).to.equal('POST');
expect(test.xhrOption('method')).to.equal('GET');
expect(request.header('Authorization')).to.equal('Bearer 1234');
expect(test.header('Authorization')).to.equal('Session 1234');
expect(request.origin()).to.equal(ORIGIN);
expect(test.origin()).to.equal(TEST_ORIGIN);
expect(test2.origin()).to.equal(TEST_ORIGIN2);
});
it('gets the url of a resource', function () {
var test = request
.origin(ORIGIN)
.get('test', 123);
expect(request.url()).to.equal(ORIGIN + '/');
expect(test.url()).to.equal(ORIGIN + '/test/123');
});
});
describe('query strings', function () {
var request;
beforeEach(function (done) {
request = ask();
server.start(done);
});
afterEach(function (done) {
server.stop(done);
});
it('returns a stringified version of query parameters', function () {
var test = request
.origin(ORIGIN)
.query('page', 1)
.query('name', 'name')
.get('test');
test.query('email', 'email');
expect(request.query()).to.equal('page=1&name=name');
expect(test.query()).to.equal('page=1&name=name&email=email');
});
it('adds query string parameters', function () {
request
.origin(ORIGIN)
.query('page', 1)
.query('limit', 10);
var withoutQuery = request.get('test');
var withQuery = request.get('test?name=name');
expect(withoutQuery.url()).to.equal(ORIGIN + '/test?page=1&limit=10');
expect(withQuery.url()).to.equal(ORIGIN + '/test?name=name&page=1&limit=10');
return withoutQuery().then(function (res) {
expect(res.body.url).to.equal('/test?page=1&limit=10');
});
});
it('only adds the query parameter to the string if it has a value', function () {
request
.origin(ORIGIN)
.query('page', 1)
.query('limit', null);
expect(request.url()).to.equal(ORIGIN + '/?page=1');
});
it('adds query parameters from an object', function () {
request
.origin(ORIGIN)
.query({
page: 1,
limit: 10
});
expect(request.url()).to.equal(ORIGIN + '/?page=1&limit=10');
});
});
|
angular.
module('core.dashboardPage').
factory('DashBoardFactory', ['$resource',
function ($resource) {
return $resource('http://api.localhost/reports/:methodType', {}, {
get: {
method: 'GET'
}
});
}
]); |
import React from 'react'
import { observer } from 'mobx-react'
import { Button, Glyphicon, FormGroup, FormControl } from 'react-bootstrap'
@observer
export class GlyphButton extends React.Component {
render() {
const { glyph, title, tooltip } = this.props
const attributes = Object.assign({}, this.props)
attributes.className = attributes.className || ''
delete attributes.glyph
delete attributes.title
delete attributes.tooltip
if (!title) {
attributes.className = attributes.className.concat(' tooltip-control icon')
}
return (
<Button {...attributes}>
<Glyphicon glyph={"glyphicon glyphicon-" + glyph} />
{title ? " " + title : ""}
{tooltip && <span className="tooltip-text">{tooltip}</span>}
</Button>
)
}
}
@observer
export class SimpleSelect extends React.Component {
render() {
const { className, name, onChange, options, placeholder, inputRef, value } = this.props
return (
<FormGroup className={className}>
<FormControl inputRef={inputRef} componentClass='select' defaultValue={value} name={name}
onChange={onChange} placeholder={placeholder}>
{options.map((o, i) => <option key={i} value={o.id}>{o.title}</option>)}
</FormControl>
</FormGroup>
)
}
}
@observer
export class SimpleInput extends React.Component {
render() {
var props = Object.assign({}, this.props)
const className = props.className
delete props.className
return (
<FormGroup className={className}>
<FormControl {...props} />
</FormGroup>
)
}
}
|
var CandidateAffix = React.createClass({
render: function() {
return (
<div className='col-md-offset-4 col-md-4 affix' data-spy="affix">
<JobDetail current_job={this.props.current_job}/>
<CandidateForm current_job={this.props.current_job} />
</div>
);
}
});
var JobDetail = React.createClass({
render: function() {
return (
<div>
<h4>{this.props.current_job.title}</h4>
<div className="panel panel-default">
<div className="panel-heading">
<h3 className="panel-title">Job Description</h3>
</div>
<div className="panel-body" style={{height: '200px', overflow: 'scroll'}}>
{this.props.current_job.description}
</div>
</div>
</div>
);
}
});
var CandidateForm = React.createClass({
handleSubmit: function(e) {
e.preventDefault();
var job_id = React.findDOMNode(this.refs.job_id).value.trim();
var name = React.findDOMNode(this.refs.name).value.trim();
var email = React.findDOMNode(this.refs.email).value.trim();
var form_data = new FormData($('#candidate_submit_form')[0]);
form_data.append('candidate_name', name);
form_data.append('candidate_email', email);
form_data.append('job_id', job_id);
var fileInput = document.getElementById('resume_file');
var file = fileInput.files[0];
form_data.append('file', file);
$.ajax({
type: 'POST',
url: '/submit',
data: form_data,
contentType: false,
processData: false,
success: function(data) {
console.log('Success!');
},
});
return;
},
render: function() {
return (
<form id='candidate_submit_form' name='candidate_submit_form' method="post" encType='multipart/form-data' onSubmit={this.handleSubmit}>
<input type="hidden" ref='job_id' className="form-control" id="candidate_name" placeholder="Name"
value={this.props.current_job.id} required></input>
<div className="form-group">
<label htmlFor="candidate_name">Candidate Name</label>
<input type="text" ref='name' className="form-control" id="candidate_name" placeholder="Name" required></input>
</div>
<div className="form-group">
<label htmlFor="candidate_email">Candidate Email</label>
<input type="email" ref='email' className="form-control" id="candidate_email" placeholder="your@email.com" required></input>
</div>
<div className="form-group">
<label htmlFor="candidate_resume">Candidate Resume</label>
<input id='resume_file' type="file" ref='resume' required ></input>
<p className="help-block">Upload the resume to use for this submission.</p>
</div>
<button type="submit" className="btn btn-default">
Submit
</button>
</form>
);
}
});
var Job = React.createClass({
jobClicked: function(e) {
this.props.onJobClick(this.props.data);
},
render: function() {
return (
<button data-job-id={this.props.data.id} type="button" className="list-group-item" onClick={this.jobClicked}>
<h4 className="list-group-item-heading">{this.props.data.title}</h4>
<div className='row'>
<label className="col-md-2">Salary</label>
<div className="col-md-4">
<span>{this.props.data.salary_min}-{this.props.data.salary_max}</span>
</div>
</div>
<div className='row'>
<label className="col-md-2">Fee</label>
<div className="col-md-4">
<span>{this.props.data.fee}%</span>
</div>
</div>
</button>
);
}
});
var JobList = React.createClass({
onJobClicked: function(job) {
this.props.onJobClicked(job);
},
render: function() {
var job_click = this.onJobClicked;
var jobNodes = this.props.data.map(function (job) {
return (
<Job data={job} onJobClick={job_click} />
);
});
return (
<div className="list-group">
{jobNodes}
</div>
);
}
});
var JobForm = React.createClass({
handleSubmit: function(e) {
e.preventDefault();
var text = React.findDOMNode(this.refs.req_search).value.trim();
console.info('search for', text);
this.props.onJobSearchSubmit({title: text});
return;
},
render: function() {
return (
<form className="form-inline" onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="req_search">Job Search</label>
<input type="text" className="form-control" ref="req_search" id="req_search"
placeholder="Software Engineer"></input>
</div>
<button type="submit" className="btn btn-default">Search</button>
</form>
);
}
});
var JobBox = React.createClass({
getInitialState: function() {
return {data: [{
title:'Select a Job',
description: 'Description will show up here'
}]};
},
componentDidMount: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
//console.log(data);
this.setState({data: data.data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
handleJobClick: function(job) {
this.props.onJobClicked(job);
},
handleJobSearchSubmit: function(data) {
// TODO: submit to the server and refresh the list
console.info('searching submit', data);
$.ajax({
url: this.props.url,
data: data,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data.data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
render: function() {
return (
<div className="jobBox col-md-6">
<JobForm onJobSearchSubmit={this.handleJobSearchSubmit} />
<JobList data={this.state.data} onJobClicked={this.handleJobClick}/>
</div>
);
}
});
var SearchPane = React.createClass({
getInitialState: function() {
return {current_job: {
title:'Select a Job',
description: 'Description will show up here'
}};
},
handleJobClick: function(job) {
this.setState({current_job: job});
},
render: function() {
return (
<div role="tabpanel" className="tab-pane active" id="search">
<CandidateAffix current_job={this.state.current_job} />
<JobBox url="/search" onJobClicked={this.handleJobClick} />
</div>
);
}
});
React.render(
<SearchPane />,
document.getElementById('tab_content_anchor')
);
|
/**
* @module base/ko-plugins/ko-content
* @description
* Knockout bindings which insert the html for an object.
* It is expected that the view text is located at the view property on the object.
*/
define(["ko"], function(ko){
"use strict";
/**
* @class ko.bindingHandlers.content
* @classdesc
* Knockout binding which inserts the html for an object.
* It is expected that the view text is located at the view property on the object.
*/
ko.bindingHandlers.content = {
/**
* @description Called when binding is initially applied to an element.
* @param {Object} element - The DOM element involved in this binding.
* @param {Function} valueAccessor - A JavaScript function that you can call to get the current model property that is involved in this binding.
* @param {Object} allBindingsAccessor - A JavaScript object that you can use to access all the model values bound to this DOM element.
* @param {Object} viewModel - Deprecated. Do not use.
* @param {Object} bindingContext - An object that holds the binding context available to this element’s bindings.
* @name ko.bindingHandlers.content#init
* @returns {{controlsDescendantBindings: boolean}}
* @function
*/
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
return { controlsDescendantBindings: true };
},
/**
* @description Called when binding is applied to an element and whenever a dependency changes.
* @param {Object} element - The DOM element involved in this binding.
* @param {Function} valueAccessor - A JavaScript function that you can call to get the current model property that is involved in this binding.
* @param {Object} allBindingsAccessor - A JavaScript object that you can use to access all the model values bound to this DOM element.
* @param {Object} viewModel - Deprecated. Do not use.
* @param {Object} bindingContext - An object that holds the binding context available to this element’s bindings.
* @name ko.bindingHandlers.content#update
* @function
*/
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext){
var parentProperty = ko.utils.unwrapObservable(valueAccessor());
ko.virtualElements.emptyNode(element);
if(parentProperty != null){
var content = parentProperty.view;
var temp = document.createElement('div');
temp.innerHTML = content;
var DOMControl = temp.firstChild;
temp = null;
ko.virtualElements.prepend(element, DOMControl);
ko.applyBindings(parentProperty, DOMControl);
}
}
};
/**
* @class ko.bindingHandlers.foreachcontent
* @classdesc
* Knockout binding which inserts the html for an object which is in a list.
* It is expected that the view text is located at the view property on the object.
*/
ko.bindingHandlers.foreachcontent = {
/**
* @description Called when binding is initially applied to an element.
* @param {Object} element - The DOM element involved in this binding.
* @param {Function} valueAccessor - A JavaScript function that you can call to get the current model property that is involved in this binding.
* @param {Object} allBindingsAccessor - A JavaScript object that you can use to access all the model values bound to this DOM element.
* @param {Object} viewModel - Deprecated. Do not use.
* @param {Object} bindingContext - An object that holds the binding context available to this element’s bindings.
* @name ko.bindingHandlers.foreachcontent#init
* @returns {{controlsDescendantBindings: boolean}}
* @function
*/
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
return { controlsDescendantBindings: true };
},
/**
* @description Called when binding is applied to an element and whenever a dependency changes.
* @param {Object} element - The DOM element involved in this binding.
* @param {Function} valueAccessor - A JavaScript function that you can call to get the current model property that is involved in this binding.
* @param {Object} allBindingsAccessor - A JavaScript object that you can use to access all the model values bound to this DOM element.
* @param {Object} viewModel - Deprecated. Do not use.
* @param {Object} bindingContext - An object that holds the binding context available to this element’s bindings.
* @name ko.bindingHandlers.foreachcontent#update
* @function
*/
update:function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var content = viewModel.view;
var temp = document.createElement('div');
temp.innerHTML = content;
var DOMControl = temp.firstChild;
temp = null;
ko.virtualElements.emptyNode(element);
ko.virtualElements.prepend(element, DOMControl);
ko.applyBindings(viewModel, DOMControl);
}
};
ko.virtualElements.allowedBindings.content = true;
ko.virtualElements.allowedBindings.foreachcontent = true;
return {};
}); |
'use strict';
module.exports = {
window:
{
title: 'Squid'
, toolbar: false
, width: 380
, height: 465
, resizable: false
, frame: false
, transparent: true
, show: false
}
, storage: { engine: 'localStorage' }
, logger: {
exitOnError: false
, output: 'File'
, transports: {
level: 'info'
, filename: '/logs.log'
, handleExceptions: true
, json: true
, maxsize: 5242880 //5MB
, maxFiles: 5
, colorize: false
}
}
, showDevTools: false
}
|
import { PwaUpdateAvailable } from './pwa-update-available/PwaUpdateAvailable.js';
customElements.define('pwa-update-available', PwaUpdateAvailable);
|
'use strict';
angular.module('myApp')
.directive('myModalentidad', function() {
return {
restrict : 'AE',
controller: [ "$scope","$window",'$http', function($scope,$window,$http) {
$scope.afirmaEliminar = function() {
var Codigo = $('#myModal').data('id').toString();
var datos ={
Accion:'D',
SQL:'DELETE FROM ESC_ENTI' +
" WHERE ENT_CODI = " + Codigo
}
$http.post("services/executesql.php",datos)
.success(function(data) {
$('#tableentidad').bootstrapTable('remove', {
field: 'ENT_CODI',
values: Codigo
});
$('#myModal').modal('hide');
})
.error(function(data) {
$('#myModal').modal('hide');
alert(data['msg']);
});
};
}],
template : '<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
'<div class="modal-dialog">' +
'<div class="modal-content">' +
'<div class="modal-header">' +
'<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>' +
'<h3 class="modal-title" id="myModalLabel">Advertencia!</h3> ' +
'</div>' +
'<div class="modal-body"> ' +
'<h4> Desea Borrar la entidad? </h4> ' +
'<div><label id="nombreentidad"></label>' +
'</div>' +
'<div class="modal-footer">' +
'<button ng-click= "afirmaEliminar();" class="btn btn-danger" id="btnYes" >Si</button>' +
'<button type="button" class="btn btn-default" data-dismiss="modal" >No</button>' +
'</div>' +
'</div>' +
'</div>' +
'</div>' +
'</div>',
}
})
.directive('initTablaentidad', ['$compile', function($compile) {
return {
restrict: 'A',
link: function(scope, el, attrs) {
var opts = scope.$eval(attrs.initTablaentidad);
opts.onLoadSuccess = function() {
$compile(el.contents())(scope);
};
el.bootstrapTable(opts);
scope.$watch(el, function (bstable) {
$compile(el.contents())(scope);
});
el.bind('body-changed.bs.table', function () {
var body = el.find('tbody')[0];
console.log('get here one more time');
$compile(body)(scope);
});
}
}
}])
.controller('entidadCtrl', ['$scope','$window','Execute', function($scope,$window,Execute) {
var datos ={
Accion:"S",
SQL:"SELECT ENT_CODI,ENT_NOMB FROM ESC_ENTI "
}
$scope.options = {
cache: false,
data:[{}],
height: 500,
striped: true,
pagination: true,
pageList: [10, 25, 50, 100, 200],
search: true,
showColumns: true,
showRefresh: true,
minimumCountColumns: 2,
clickToSelect: true,
idField:'CAR_CODI',
toolbar: '#custom-toolbarentidad',
columns: [{
field: 'ENT_CODI',
title: 'Código',
align: 'left',
valign: 'middle',
width: 100,
sortable: true,
visible:false,
switchable:false
}, {
field: 'ENT_NOMB',
title: 'NOMBRE',
align: 'left',
valign: 'middle',
width: 2000,
sortable: true
}, {
title: '',
width: 200,
switchable:false,
formatter: function(value, row, index) {
return '<a class="edit ml10 btn btn-default btn-xs" title="Editar"><span class="glyphicon glyphicon-pencil"></span></a> ' +
'<a class="remove ml10 btn btn-default btn-xs" title="Eliminar" ><span class="glyphicon glyphicon-trash"></span></a>';
},
events: window.operateEvents = {
'click .remove': function (e, value, row, index) {
$('#nombreentidad').text(row.ENT_NOMB);
$('#myModal').data('id', row.ENT_CODI).modal('show');
},
'click .edit': function (e, value, row, index) {
$window.location.href ="#/edit-entidad/" + row.ENT_CODI + "";
}
}
}]
};
Execute.SQL(datos).then(function(result) {
if (result.data[0]!=null)
$('#tableentidad').bootstrapTable('load',result.data);
else
$('#tableentidad').bootstrapTable('load',[]);
});
// $('#tableentidad').bootstrapTable('removeAll');
// $('#tableentidad').bootstrapTable('append',result.data);
// });
// // var json =[{'CAR_CODI':1,'CAR_NOMB':'Nombre1'}];
// var datos ={
// Accion:"S",
// SQL:"SELECT CAR_CODI,CAR_NOMB FROM CACAO.ESC_CARA "
// }
// Execute.SQL(datos).then(function(result) {
// $('#tableentidad').bootstrapTable('removeAll');
// $('#tableentidad').bootstrapTable('append',result.data);
// var datos = $scope.options;
// });
}])
.controller('ListControllerentidad', ['$window','$scope', function($window,$scope) {
this.btnNovoClick = function() {
$window.location.href = "#/edit-entidad/0";
};
}]);
|
'use strict';
/**
* @ngdoc service
* @name jodomaxApp.SalesDetailModel
* @description
* # SalesDetailModel
* Factory in the jodomaxApp.
*/
angular.module('jodomaxApp')
.factory('SalesDetailModel', [
'dbService',
'$mdToast',
'AppUtils',
'BaseModel',
'AttributeGroup',
function (
dbService,
$mdToast,
AppUtils,
BaseModel,
AttributeGroup
) {
// Service logic
var SalesDetailModel = (function(superClass) {
AppUtils.extend(SalesDetailModel, superClass);
function SalesDetailModel() {
return SalesDetailModel.__super__.constructor.apply(this, arguments);
}
SalesDetailModel.tableName = 'SalesDetail';
SalesDetailModel.prototype.afterExtendData = function() {
var _this = this;
var _oldAttr = _this.Attributes;
_this.Attributes = [];
this.deserializeAttribute(_oldAttr, function(res){
_this.Attributes = res;
});
};
SalesDetailModel.prototype.beforeSave = function() {
var _this = this;
var attributes = _this.Attributes;
attributes = _.map(attributes, function(attr){
return attr.Value;
});
attributes = _.reduce(attributes, function(start, el){
if (start=='') {
start = el.FK_group + ':' + el.Id;
} else {
start += ',' + el.FK_group + ':' + el.Id;
}
return start;
}, '');
this.saveData.Attributes = attributes;
};
SalesDetailModel.prototype.deserializeAttribute = function(attributes, cb) {
var _this = this;
if (_this.Id>0 && _this.FK_product>0) {
dbService.find('Product', _this.FK_product, function(prod){
var attributeArr = AppUtils.deserializeAttribute(attributes);
var prodAttributeArr = _this.deserializeProductAttribute(prod.Attributes);
var res = _.map(prodAttributeArr, function(el) {
var el_id = el.Id;
var foundAc = _.find(attributeArr, function(ac) {
return (ac.Id==el_id);
});
var attributes = el.Attributes;
_.each(attributes, function(elAttr){
if (foundAc!=undefined) {
var foundAttr = _.find(foundAc.AttributeId, function(attr_id){
return (elAttr.Id==attr_id);
});
if (foundAttr!=undefined){
el.Value = angular.copy(elAttr);
}
}
});
return el;
});
cb(res);
});
} else {
//cb([]);
}
};
SalesDetailModel.prototype.deserializeProductAttribute = function(attributes) {
var attributeArr = AppUtils.deserializeAttribute(attributes);
var attrCate = angular.copy(AttributeGroup.attributeGroup);
attrCate = AppUtils.reduceAttribute(attrCate, attributeArr);
return attrCate;
};
SalesDetailModel.prototype.applyProduct = function(prod, $scope) {
var _this = this;
var attributes = prod.Attributes;
var attributeArr = this.deserializeProductAttribute(attributes);
var FK_discount = prod.FK_discount;
if (FK_discount) {
dbService.find('Discount', FK_discount, function(disc){
var percent = disc.Percent;
$scope.$apply(function(){
_this.FK_product = prod.Id;
_this.Code = prod.Code;
_this.Title = prod.Title;
_this.Price = prod.Price;
_this.Disc = percent;
_this.Attributes = attributeArr;
});
});
} else {
$scope.$apply(function(){
_this.FK_product = prod.Id;
_this.Code = prod.Code;
_this.Title = prod.Title;
_this.Price = prod.Price;
_this.Disc = 0;
_this.Attributes = attributeArr;
});
}
};
SalesDetailModel.prototype.applyRoomCharge = function(prod) {
var _this = this;
_this.FK_product = prod.Id;
_this.Code = prod.Code;
_this.Title = prod.Title;
_this.Price = prod.Price;
_this.Disc = 0;
_this.Attributes = prod.Attributes;
};
SalesDetailModel.prototype.getPriceText = function() {
return AppUtils.formatMoney(this.Price, 0, ',', '.');
};
SalesDetailModel.prototype.getAmountText = function() {
return AppUtils.formatMoney(this.getAmount(), 0, ',', '.');
};
SalesDetailModel.prototype.getAmountCharged = function() {
return (this.Price * this.Qty);
};
SalesDetailModel.prototype.getAmount = function() {
return (this.Price * this.Qty)*(100-this.Disc)/100;
};
SalesDetailModel.prototype.getPromo = function() {
return (this.Price * this.Qty)*(this.Disc)/100;
};
SalesDetailModel.prototype.getAmountNotDisc = function() {
var res = 0;
if (this.Disc==0)
res = (this.Price * this.Qty);
return res;
};
return SalesDetailModel;
})(BaseModel);
return SalesDetailModel;
}]);
|
/**
* Created by piyushthapa on 11/5/14.
*/
Template.signup.events({
'submit #signupForm':function(e,t){
e.preventDefault();
var user={
username:t.find('#userName').value,
email:t.find('#userEmail').value,
password: t.find('#userPassword').value,
profile:{name:t.find('#userName').value,avatar:null}
};
Accounts.createUser(user,function(err,res){
if(err){
console.log(err);
} else{
Router.go('/');
}
});
}
}); |
export { default } from 'ui-list/components/ui-selection-aspect'; |
import { h } from 'preact'
const IconImport = ({ ...props }) => (
<div class='icon icon-import' title='Import' onClick={props.onClick}>
<svg viewBox='0 0 50 50' width='30' height='30'>
<path d='M24.9 2.97L24.8 3c-.46.1-.8.52-.78 1v28.56l-6.28-6.28c-.15-.14-.33-.24-.53-.28-.15-.03-.3-.03-.42 0-.37.07-.67.34-.78.7-.1.37 0 .76.28 1.02l7.88 7.84c.07.12.16.2.28.28l.56.57.56-.56.1-.06.06-.06v-.03l.06-.08 7.94-7.9c.4-.4.4-1.04 0-1.44-.4-.4-1.04-.4-1.44 0L26 32.56V4v-.1-.1c0-.06-.04-.14-.06-.2l-.07-.07c-.02-.07-.05-.13-.1-.2l-.05-.05-.1-.06c-.2-.18-.45-.27-.7-.25zM2 36v6c0 2.75 2.25 5 5 5h36c2.75 0 5-2.25 5-5v-6h-2v6c0 1.66-1.34 3-3 3H7c-1.66 0-3-1.34-3-3v-6z' />
</svg>
</div>
)
export { IconImport }
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M12.34 6V4H18v5.66h-2V7.41l-5 5V20H9v-7.58c0-.53.21-1.04.59-1.41l5-5h-2.25z"
}), 'TurnSlightRight');
exports.default = _default; |
/**
* @fileoverview Rule to flag unsafe statements in finally block
* @author Onur Temizkan
*/
"use strict";
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
let SENTINEL_NODE_TYPE_RETURN_THROW = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression)$/;
let SENTINEL_NODE_TYPE_BREAK = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|DoWhileStatement|WhileStatement|ForOfStatement|ForInStatement|ForStatement|SwitchStatement)$/;
let SENTINEL_NODE_TYPE_CONTINUE = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|DoWhileStatement|WhileStatement|ForOfStatement|ForInStatement|ForStatement)$/;
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: "disallow control flow statements in `finally` blocks",
category: "Possible Errors",
recommended: true
},
schema: []
},
create: function(context) {
/**
* Checks if the node is the finalizer of a TryStatement
*
* @param {ASTNode} node - node to check.
* @returns {boolean} - true if the node is the finalizer of a TryStatement
*/
function isFinallyBlock(node) {
return node.parent.type === "TryStatement" && node.parent.finalizer === node;
}
/**
* Climbs up the tree if the node is not a sentinel node
*
* @param {ASTNode} node - node to check.
* @param {string} label - label of the break or continue statement
* @returns {boolean} - return whether the node is a finally block or a sentinel node
*/
function isInFinallyBlock(node, label) {
let labelInside = false;
let sentinelNodeType;
if (node.type === "BreakStatement" && !node.label) {
sentinelNodeType = SENTINEL_NODE_TYPE_BREAK;
} else if (node.type === "ContinueStatement") {
sentinelNodeType = SENTINEL_NODE_TYPE_CONTINUE;
} else {
sentinelNodeType = SENTINEL_NODE_TYPE_RETURN_THROW;
}
while (node && !sentinelNodeType.test(node.type)) {
if (node.parent.label && label && (node.parent.label.name === label.name)) {
labelInside = true;
}
if (isFinallyBlock(node)) {
if (label && labelInside) {
return false;
}
return true;
}
node = node.parent;
}
return false;
}
/**
* Checks whether the possibly-unsafe statement is inside a finally block.
*
* @param {ASTNode} node - node to check.
* @returns {void}
*/
function check(node) {
if (isInFinallyBlock(node, node.label)) {
context.report({
message: "Unsafe usage of " + node.type + ".",
node: node,
line: node.loc.line,
column: node.loc.column
});
}
}
return {
ReturnStatement: check,
ThrowStatement: check,
BreakStatement: check,
ContinueStatement: check
};
}
};
|
var NeatoDemoApp = {
clientId: null,
scopes: null,
redirectUrl: null,
user: null,
initialize: function (options) {
this.clientId = options.clientId;
this.scopes = options.scopes;
this.redirectUrl = options.redirectUrl;
this.guiShowLoginPage();
this.guiHideDashboardPage();
this.guiInitializeEvents();
this.checkAuthenticationStatus();
},
// robot state
connect: function (robot) {
var self = this;
robot.onConnected = function () {
console.log(robot.serial + " got connected");
};
robot.onDisconnected = function (status, json) {
console.log(robot.serial + " got disconnected");
self.guiResetAll(robot.serial);
};
robot.onStateChange = function () {
console.log(robot.serial + " got new state:", robot.state);
self.onStateChange(robot.serial);
};
robot.connect();
},
disconnect: function (serial) {
this.user.getRobotBySerial(serial).disconnect();
},
onStateChange: function (serial) {
this.guiEnableRobotCommands(serial);
this.guiDisplayState(serial);
},
getAvailableCommands: function (serial) {
if (this.user.getRobotBySerial(serial).state) {
return this.user.getRobotBySerial(serial).state.availableCommands;
} else {
return null;
}
},
getAvailableServices: function (serial) {
if (this.user.getRobotBySerial(serial).state) {
return this.user.getRobotBySerial(serial).state.availableServices;
} else {
return null;
}
},
// robot commands
startOrResume: function (serial) {
var availableCommands = this.getAvailableCommands(serial);
if (!availableCommands) {
return;
}
if (availableCommands.start) {
this.startHouseCleaning(serial);
} else if (availableCommands.resume) {
this.resumeCleaning(serial);
}
},
startHouseCleaning: function (serial) {
this.user.getRobotBySerial(serial).startHouseCleaning({
mode: Neato.Constants.TURBO_MODE,
modifier: Neato.Constants.HOUSE_FREQUENCY_NORMAL,
navigationMode: Neato.Constants.EXTRA_CARE_OFF
});
},
pauseCleaning: function (serial) {
this.user.getRobotBySerial(serial).pauseCleaning();
},
resumeCleaning: function (serial) {
this.user.getRobotBySerial(serial).resumeCleaning();
},
stopCleaning: function (serial) {
this.user.getRobotBySerial(serial).stopCleaning();
},
sendToBase: function (serial) {
this.user.getRobotBySerial(serial).sendToBase();
},
findMe: function (serial) {
this.user.getRobotBySerial(serial).findMe();
},
maps: function (serial) {
var self = this;
self.user.getRobotBySerial(serial).maps().done(function (data) {
if(data["maps"] && data["maps"].length > 0) {
var mapId = data["maps"][0]["id"];
self.user.getRobotBySerial(serial).mapDetails(mapId).done(function (data) {
window.open(data["url"]);
}).fail(function (data) {
self.showErrorMessage("something went wrong getting map details....");
});
}else {
alert("No maps available yet. Complete at least one house cleaning to view maps.")
}
}).fail(function (data) {
self.showErrorMessage("something went wrong getting robots map....");
});
},
setScheduleEveryMonday: function(serial) {
this.user.getRobotBySerial(serial).setSchedule({
1: { mode: 1, startTime: "15:00" }
});
},
setScheduleEveryDay: function(serial) {
this.user.getRobotBySerial(serial).setSchedule({
0: { mode: 1, startTime: "15:00" },
1: { mode: 1, startTime: "15:00" },
2: { mode: 1, startTime: "15:00" },
3: { mode: 1, startTime: "15:00" },
4: { mode: 1, startTime: "15:00" },
5: { mode: 1, startTime: "15:00" },
6: { mode: 1, startTime: "15:00" }
});
},
checkAuthenticationStatus: function () {
var self = this;
this.user = new Neato.User();
this.user.isConnected()
.done(function () {
self.guiHideLoginPage();
self.guiShowDashboardPage();
self.getDashboard();
})
.fail(function () {
//show auth error only if the user attempt to login with a token
if(self.user.authenticationError()) {
self.guiShowAuthenticationErrorUI(self.user.authErrorDescription);
}else if(!self.user.connected && self.user.token != null) {
self.guiShowAuthenticationErrorUI("access denied");
}
});
},
// GUI
guiInitializeEvents: function () {
var self = this;
$("#cmd_login").click(function () {
self.user.login({
clientId: self.clientId,
scopes: self.scopes,
redirectUrl: self.redirectUrl
});
});
$("#cmd_logout").click(function () {
self.user.logout()
.done(function (data) {
self.guiHideDashboardPage();
self.guiShowLoginPage();
}).fail(function (data) {
self.showErrorMessage("something went wrong during logout...");
});
});
$(document).on("click", ".cmd_start", function () {
self.startOrResume($(this).parents(".robot").attr('data-serial'));
});
$(document).on("click", ".cmd_pause", function () {
self.pauseCleaning($(this).parents(".robot").attr('data-serial'));
});
$(document).on("click", ".cmd_stop", function () {
self.stopCleaning($(this).parents(".robot").attr('data-serial'));
});
$(document).on("click", ".cmd_send_to_base", function () {
self.sendToBase($(this).parents(".robot").attr('data-serial'));
});
$(document).on("click", ".cmd_find_me", function () {
self.findMe($(this).parents().attr('data-serial'));
});
$(document).on("click", ".cmd_maps", function () {
self.maps($(this).parents().attr('data-serial'));
});
$(document).on("click", ".cmd_schedule_monday", function () {
self.setScheduleEveryMonday($(this).parents().parents().attr('data-serial'));
});
$(document).on("click", ".cmd_schedule_every_day", function () {
self.setScheduleEveryDay($(this).parents().parents().attr('data-serial'));
});
},
guiShowLoginPage: function () {
this.hideErrorMessage();
$("#signin").show();
},
guiHideLoginPage: function () {
$("#signin").hide();
},
guiShowDashboardPage: function () {
$("#dashboard").show();
},
guiHideDashboardPage: function () {
$("#dashboard").hide();
},
getDashboard: function () {
var self = this;
//get user email if available
this.user.getUserInfo()
.done(function (data) {
$("#user_first_name").html(data.first_name || "");
}).fail(function (data) {
self.showErrorMessage("something went wrong accessing user info....");
});
//get user robots
this.user.getRobots()
.done(function (robotsArray) {
var html = "";
var robot;
//start polling robot state
for (var i = 0; i < robotsArray.length; i++) {
robot = robotsArray[i];
self.connect(robot);
html += self.guiRobotTemplate(robot);
}
$("#robot_list").html(html);
}).fail(function (data) {
self.showErrorMessage("something went wrong retrieving robot list....");
});
},
guiRobotTemplate: function(robot) {
return "<div class='robot grid-40 prefix-5 suffix-5' data-serial='"+robot.serial+"' data-secret_key='"+robot.secret_key+"'>" +
"<div class='model'><img src='img/"+this.getRobotImage(robot.model)+"'></div>" +
"<p class='name'>"+robot.name+"</p>" +
"<p class='robot_state'>NOT AVAILABLE</p>" +
"<a class='cmd_find_me' title='Find me'><i class='fa fa-search' aria-hidden='true'></i></a>" +
"<a class='cmd_maps' title='Maps'><i class='fa fa-map' aria-hidden='true'></i></a>" +
"<div class='cleaning-commands'>" +
"<a class='cmd_start disabled'><i class='fa fa-play' aria-hidden='true'></i></a>" +
"<a class='cmd_pause disabled'><i class='fa fa-pause' aria-hidden='true'></i></a>" +
"<a class='cmd_stop disabled'><i class='fa fa-stop' aria-hidden='true'></i></a>" +
"<a class='cmd_send_to_base disabled'><i class='fa fa-home' aria-hidden='true'></i></a>" +
"</div>" +
"<div class='other-commands'>" +
"<p>WIPE ALL EXISTING SCHEDULE AND SET IT TO:</p>" +
"<a class='btn cmd_schedule_every_day'>Everyday at 3:00 pm</a>" +
"<a class='btn cmd_schedule_monday'>Monday at 3:00 pm</a>" +
"</div>" +
"</div>";
},
getRobotImage: function(model) {
if(model.toLowerCase() == "botvacconnected") return "robot_image_botvacconnected.png";
else if(model.toLowerCase() == "botvacd3connected") return "robot_image_botvacd3connected.png";
else if(model.toLowerCase() == "botvacd5connected") return "robot_image_botvacd5connected.png";
else if(model.toLowerCase() == "botvacd7connected") return "robot_image_botvacd7connected.png";
else return "robot_empty.png";
},
guiShowAuthenticationErrorUI: function (message) {
this.guiShowLoginPage();
this.showErrorMessage(message);
},
guiEnableRobotCommands: function (serial) {
var availableCommands = this.getAvailableCommands(serial);
if (!availableCommands) {
return;
}
var $robotUI = $("[data-serial='" + serial + "']");
$robotUI.find(".cmd_start").first().removeClass('disabled');
$robotUI.find(".cmd_pause").first().removeClass('disabled');
$robotUI.find(".cmd_stop").first().removeClass('disabled');
$robotUI.find(".cmd_send_to_base").first().removeClass('disabled');
if(!(availableCommands.start || availableCommands.resume)) $robotUI.find(".cmd_start").first().addClass('disabled');
if(!availableCommands.pause) $robotUI.find(".cmd_pause").first().addClass('disabled');
if(!availableCommands.stop) $robotUI.find(".cmd_stop").first().addClass('disabled');
if(!availableCommands.goToBase) $robotUI.find(".cmd_send_to_base").first().addClass('disabled');
//check available services to enable robot features
var availableServices = this.getAvailableServices(serial);
if (!availableServices) {
return;
}
if(!availableServices["findMe"]) $robotUI.find(".cmd_find_me").first().hide();
else $robotUI.find(".cmd_find_me").first().show();
if(!availableServices["maps"]) $robotUI.find(".cmd_maps").first().hide();
else $robotUI.find(".cmd_maps").first().show();
},
guiDisableRobotCommands: function (serial) {
var $robotUI = $("[data-serial='" + serial + "']");
$robotUI.find(".cmd_start").first().addClass('disabled');
$robotUI.find(".cmd_pause").first().addClass('disabled');
$robotUI.find(".cmd_stop").first().addClass('disabled');
$robotUI.find(".cmd_send_to_base").first().addClass('disabled');
$robotUI.find(".cmd_find_me").first().hide();
$robotUI.find(".cmd_maps").first().hide();
},
guiDisplayState: function (serial) {
var $robotState = $("div[data-serial='" + serial + "']");
var prettyState = "NOT AVAILABLE";
var robot_state = this.user.getRobotBySerial(serial).state.state;
switch (robot_state) {
case 1:
prettyState = "IDLE";
break;
case 2:
prettyState = "BUSY";
break;
case 3:
prettyState = "PAUSED";
break;
case 4:
prettyState = "ERROR";
break;
default:
prettyState = "NOT AVAILABLE";
}
$robotState.find(".robot_state").html(prettyState);
},
guiResetState: function (serial) {
var $robotState = $("div[data-serial='" + serial + "']");
$robotState.find(".robot_state").html("NOT AVAILABLE");
},
guiResetAll: function (serial) {
this.guiResetState(serial);
this.guiDisableRobotCommands(serial);
},
showErrorMessage: function(message) {
$("div.error").html(message).show();
},
hideErrorMessage: function() {
$("div.error").hide();
}
};
|
const assert = require('assert');
const extract = require('extract-zip');
const fs = require('fs');
const tmp = require('tmp');
describe('extract-zip', function() {
var dir = null;
beforeEach(function() { dir = tmp.dirSync({unsafeCleanup: true}); });
afterEach(function() {
dir.removeCallback();
dir = null;
});
it('should not crash with intermediate directories', function(done) {
extract('./test/test.zip', {dir: dir.name}, function(err) {
assert.ifError(err);
assert.ok(fs.existsSync(dir.name + '/nested/file'));
done();
});
});
});
|
import React from 'react';
import _ from 'lodash';
import SectionHeader from '../components/section-header';
import token from 'otkit-borders/token.common';
const Borders = () => {
var tokens = _.toPairsIn(token);
tokens = tokens.map((token, index) => {
return (
<div key={index}>
{_.kebabCase(token[0])}: {token[1]}
</div>
);
});
return (
<section>
<SectionHeader text="Borders" />
{tokens}
</section>
);
};
export default Borders;
|
// Generated by CoffeeScript 1.9.1
var canvas, context, draw, findClosest, generate, image, imageData, img, points;
canvas = document.getElementsByTagName('canvas')[0];
context = canvas.getContext('2d');
points = [];
image = context.createImageData(canvas.width, canvas.height);
img = new Image;
imageData = null;
img.onload = function() {
var ctx, t;
t = document.createElement('canvas');
t.width = img.width;
t.height = img.height;
ctx = t.getContext('2d');
ctx.drawImage(img, 0, 0);
imageData = ctx.getImageData(0, 0, img.width, img.height);
generate();
return requestAnimationFrame(draw);
};
img.src = 'smile.png';
findClosest = function(x, y) {
var closest, closestDist, dist, i, len, point;
closest = {
r: 0,
g: 0,
b: 0
};
closestDist = canvas.width * canvas.height;
for (i = 0, len = points.length; i < len; i++) {
point = points[i];
dist = (x - point.x) * (x - point.x) + (y - point.y) * (y - point.y);
if (dist < closestDist) {
closestDist = dist;
closest = point;
}
}
return closest;
};
generate = function() {
var i, imgIndex, ix, iy, n, point, results, x, y;
points = [];
results = [];
for (n = i = 0; i <= 512; n = ++i) {
x = Math.random();
y = Math.random();
ix = Math.floor(img.width * x);
iy = Math.floor(img.height * y);
imgIndex = (ix + iy * img.width) * 4;
point = {
index: n,
x: canvas.width * x,
y: canvas.height * y,
r: imageData.data[imgIndex + 0],
g: imageData.data[imgIndex + 1],
b: imageData.data[imgIndex + 2],
a: imageData.data[imgIndex + 3]
};
results.push(points.push(point));
}
return results;
};
draw = function() {
var h, i, index, j, ms, point, ref, ref1, start, w, x, y;
start = Date.now();
w = canvas.width - 1;
h = canvas.height - 1;
for (x = i = 0, ref = w; 0 <= ref ? i <= ref : i >= ref; x = 0 <= ref ? ++i : --i) {
for (y = j = 0, ref1 = h; 0 <= ref1 ? j <= ref1 : j >= ref1; y = 0 <= ref1 ? ++j : --j) {
point = findClosest(x, y);
index = (x + y * canvas.width) * 4;
image.data[index + 0] = point.r;
image.data[index + 1] = point.g;
image.data[index + 2] = point.b;
image.data[index + 3] = point.a;
}
}
ms = Date.now() - start;
context.putImageData(image, 0, 0);
context.font = '18px consolas';
context.fillStyle = 'black';
context.fillText(ms + "ms", 20, 20);
context.fillText("R to regenerate", 20, 40);
return requestAnimationFrame(draw);
};
document.onkeyup = function(e) {
if (e.keyCode === 'R'.charCodeAt(0)) {
return generate();
}
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:af2327264ba777d44458efe551bf8a733b135ea5842e3614f06bb0a4e013e8f4
size 7240
|
var connect = require('connect')
var open = require("open")
var gulp = require('gulp')
var stylus = require('gulp-stylus')
var prefix = require('gulp-autoprefixer')
var plumber = require('gulp-plumber')
var rename = require("gulp-rename");
var minify = require('gulp-minify-css');
gulp.task('stylus', function() {
var stream = gulp.src('./source/ng-trans.styl')
.pipe(plumber())
.pipe(stylus())
.pipe(prefix("last 2 version", "> 1%", "ie 8"))
.pipe(gulp.dest('./'))
.pipe(gulp.dest('document/'));
return stream
});
gulp.task('minify', ['stylus'], function() {
var stream = gulp.src('./ng-trans.css')
.pipe(rename({suffix: ".min"}))
.pipe(minify(opts))
.pipe(gulp.dest('./'))
return stream
});
gulp.task('connect', function() {
connect.createServer(
connect.static('./document')
).listen(5000);
open("http://0.0.0.0:5000", "Google Chrome");
});
gulp.task('watch', function() {
var watcher = gulp.watch('./source/*.styl', function(){
gulp.start('stylus')
gulp.start('minify')
});
});
gulp.task('serve', ['connect', 'stylus', 'minify', 'watch'])
gulp.task('default', ['stylus', 'minify']); |
var background = (function(){
var background = {};
background.color = {
name: 'Background color',
id: 'background-color',
color: null,
data: null,
};
background.image = {
name: 'Background image',
id: 'background-image',
src: null,
data: null,
};
}()); |
'use strict';
var object = require('./object');
var style = require('./style');
var template = require('./template');
module.exports = {
applyAnsiStyles: style.applyAnsiStyles,
concatFirstStringElements: template.concatFirstStringElements,
customFormatterFactory: customFormatterFactory,
maxDepthFactory: object.maxDepthFactory,
removeStyles: style.removeStyles,
toJSON: object.toJSON,
toStringFactory: object.toStringFactory,
transform: transform,
};
function customFormatterFactory(customFormat, concatFirst, scopeOptions) {
if (typeof customFormat === 'string') {
return function customStringFormatter(data, message) {
return transform(message, [
template.templateVariables,
template.templateScopeFactory(scopeOptions),
template.templateDate,
template.templateText,
concatFirst && template.concatFirstStringElements,
], [customFormat].concat(data));
};
}
if (typeof customFormat === 'function') {
return function customFunctionFormatter(data, message) {
var modifiedMessage = Object.assign({}, message, { data: data });
var texts = customFormat(modifiedMessage, data);
return [].concat(texts);
};
}
return function (data) {
return [].concat(data);
};
}
function transform(message, transformers, initialData) {
return transformers.reduce(function (data, transformer) {
if (typeof transformer === 'function') {
return transformer(data, message);
}
return data;
}, initialData || message.data);
}
|
define(['altair/facades/declare',
'altair/plugins/node!path',
'altair/mixins/_DeferredMixin',
'lodash'
], function (declare,
pathUtil,
_DeferredMixin,
_) {
"use strict";
return declare([_DeferredMixin], {
_controllers: null, //cache of controllers to keep from double generating
_namespaces: null, //all the namespaces we have forged
constructor: function () {
this._controllers = {};
this._namespaces = {};
},
nameForRoute: function (vendor, route) {
var callbackParts = route.action.split('::'),
controllerName = callbackParts[0].indexOf(':') == -1 ? vendor + ':*/' + callbackParts[0] : callbackParts[0];
return controllerName;
},
hasController: function (named) {
return _.has(this._controllers, named);
},
controller: function (named) {
return this._controllers[named];
},
hasNamespace: function (named) {
return _.has(this._namespaces, named);
},
controllersInNamespace: function (named) {
return this._namespaces[named];
},
forgeForRoute: function (path, vendor, route, options, config) {
var callbackParts = route.action.split('::'),
controllerName = this.nameForRoute(vendor, route),
controller = controllerName == callbackParts[0] ? null : pathUtil.join(path, callbackParts[0]),
_config = config || {};
_config.path = controller;
_config.startup = false;
return this.forgeController(controllerName, options, _config)
},
forgeController: function (named, options, config) {
var dfd,
sitePath,
_config = config || {},
path = _config.path,
startup = _.has(_config, 'startup') ? _config.startup : true,
parent = _config.parent,
namespace = named.split('/').shift();
if (!path && named.search(':') === -1) {
path = this.nexus('Altair').resolvePath(named);
} else {
}
//are we starting up the controller?
if (_.isUndefined(startup)) {
startup = true;
}
//build sitePath
sitePath = this.nexus('Altair').resolvePath('.')
//track all the namespaces (1 per site)
if (!this._namespaces[namespace]) {
this._namespaces[namespace] = [];
}
//controller already ready
if (_.has(this._controllers, named)) {
dfd = this.when(this._controllers[named]);
} else {
var fullname = parent.name.split('/')[0] + '/' + named;
dfd = this.forge(path || named, options, { type: 'controller', startup: startup, parent: parent, name: fullname, foundry: this.hitch(function (Class, options, config) {
//override paths for things to be off the sitePath (vs relative to the controller)
Class.extendOnce({
sitePath: sitePath,
dir: sitePath
});
var controller = config.defaultFoundry(Class, options, config);
this._controllers[named] = controller;
this._namespaces[namespace].push(controller);
return controller;
})});
this._controllers[named] = dfd;
}
return dfd;
}
});
});
|
import styled from 'styled-components';
import { grayText } from 'global/styles';
export const ProConColumn = styled.div`
display: inline-block;
vertical-align: top;
width: 50%;
`;
export const ProConContainer = styled.div`
background-color: #f6f5f5;
padding: 1rem;
`;
export const ProConSubtitle = styled.div`
font-size: .75rem;
${grayText}
`;
export const ProConTitle = styled.div`
font-size: 1.125rem;
text-transform: uppercase;
`;
export const SummaryRow = styled.div`
align-items: baseline;
display: flex;
flex: 1 0 auto;
font-size: .9rem;
justify-content: space-between;
padding: 1rem;
`;
// Unfortunately the only way to style inside of ReactStars is by reaching in
export const SummaryStars = styled.div`
&:first-child {
display: inline-block;
margin-right: .5rem;
& span {
cursor: default !important; /*sigh*/
font-size: 1.875rem !important;
display: inline-block;
height: 1.5625rem;
line-height: 1.875rem;
}
}
`;
export const ViewAllLink = styled.span`
cursor: pointer;
font-weight: bold;
`;
|
// var app = angular.module ('restApiTester');
window.app.controller ('EnvironmentsController', ['$scope', '$rootScope', '$state', '$interval', '$translate', 'notificationsService', 'testsResultsService', 'environmentsService', 'testsService', '$stateParams',
function ($scope, $rootScope, $state, $interval, $translate, notificationsService, testsResultsService, environmentsService, testsService, $stateParams) {
var self = this;
self.formData = {};
self.overview = {};
self.addUser = {};
self.manageEnvironments = false;
$rootScope.enableLoadingDashboardTests = false;
$rootScope.dashboardTests = [];
$rootScope.failedDasboardTests = {};
/**
* Load list of dasboard tests.
*
* Currently using AJAX polling... :(
*/
$rootScope.loadDashboardTests = function () {
var projectId = $stateParams.projectId, test = {};
// turn off loading results for dashboard
if (!$rootScope.enableLoadingDashboardTests)
return;
// load results for past 7 days in current project
testsResultsService.getOverview (7 * 24, projectId).then (function (response) {
$rootScope.dashboardTests = response.data;
// separate failed tests from not-failed
$rootScope.failedDasboardTests = {};
for (i in $rootScope.dashboardTests) {
test = $rootScope.dashboardTests[i];
if (!$rootScope.failedDasboardTests.hasOwnProperty (test.environmentsId))
$rootScope.failedDasboardTests[test.environmentsId] = [];
if (test.status == 'failed')
$rootScope.failedDasboardTests[test.environmentsId].push (test);
}
});
};
$rootScope.loadDashboardTests ();
$interval ($rootScope.loadDashboardTests, 30 * 1000);
/**
* Add tests from given environment into queue for testing
*
* @param environmentId
*/
$rootScope.runEnvironmentTests = function (environmentId) {
$rootScope.testAddedOrInProgress = true;
testsService.runAll (environmentId).then (function (response) {
switch (response.status) {
case 200:
// becase of some time needed for preparing test we will display some "waiting" image before loading test list again
$timeout (function () {
$rootScope.loadTests (false);
}, 3 * 1000);
break;
case 403:
$translate ('Pro tuto akci nemáte dostatečná oprávnění').then (function (translation) {
notificationsService.push ('alert', translation);
});
break;
default:
$translate ('Nelze vykonat požadavek').then (function (translation) {
notificationsService.push ('alert', translation);
});
break;
}
});
};
/**
* List of all environments
*
* @param projectId
* @param selectedEnvironmentId
* @param loadDasboardTests
*/
self.initOverview = function (projectId, selectedEnvironmentId, loadDasboardTests) {
if (typeof loadDasboardTests == 'undefined')
loadDasboardTests = true;
if (typeof projectId == 'undefined')
projectId = $stateParams.projectId;
// turn ajax polling for loading tests on dasboard?
if (loadDasboardTests) {
$rootScope.enableLoadingDashboardTests = loadDasboardTests;
$rootScope.loadDashboardTests ();
}
// get all environments in given project
environmentsService.getOverview (projectId).then (function (response) {
switch (response.status) {
case 200:
self.overview = response.data;
$rootScope.setEnvironment (selectedEnvironmentId, projectId);
break;
case 403:
$translate ('Pro tuto akci nemáte dostatečná oprávnění').then (function (translation) {
notificationsService.push ('alert', translation);
$state.go ('projects');
});
break;
case 404:
$translate ('Požadované prostředí neexistuje. Vyberte prosím jiné.').then (function (translation) {
notificationsService.push ('alert', translation);
$state.go ('projects');
});
break;
default:
$translate ('Nelze vykonat požadavek').then (function (translation) {
notificationsService.push ('alert', translation);
$state.go ('projects');
});
break;
}
});
};
/**
* Load detail about curren environment.
*
* In response are included team members
*/
self.loadDetail = function (updateBreadcrumbs) {
if (typeof updateBreadcrumbs == 'undefined')
updateBreadcrumbs = true;
var environmentId = $stateParams.environmentId;
$rootScope.setEnvironment (environmentId);
// get detail
environmentsService.detail (environmentId).then (function (response) {
switch (response.status) {
case 200:
self.detail = response.data;
self.formData = angular.copy (response.data);
// update breadcrumbs
$translate ('Nastavení').then (function (settings) {
if (updateBreadcrumbs)
$rootScope.breadcrumbs = [{
label: settings,
href: $state.href ('environment_settings', {environmentId: response.data.id})
}];
});
break;
case 403:
$translate ('Pro tuto akci nemáte dostatečná oprávnění').then (function (translation) {
notificationsService.push ('alert', translation);
$state.go ('projects');
});
break;
case 404:
$translate ('Tento projekt neexistuje, nelze zobrazit přehled prostředí.').then (function (translation) {
notificationsService.push ('alert', translation);
$state.go ('projects');
});
break;
default:
$translate ('Nelze vykonat požadavek').then (function (translation) {
notificationsService.push ('alert', translation);
$state.go ('projects');
});
break;
}
});
};
/**
* Create new environment in current project
*/
self.create = function (options) {
var projectId = $stateParams.projectId;
if (typeof options == 'undefined')
options = {};
environmentsService.create (projectId, self.formData).then (function (response) {
self.formData = {};
$rootScope.refreshProjectOverview ();
$rootScope.reinitIdentity (function () {
if (!options.redirect) {
self.initOverview (projectId, undefined, false);
}
});
if (options.redirect) {
$state.go ('tests', {environmentId: response.data.id});
}
self.manageEnvironments = false;
}, function (response) {
switch (response.status) {
case 403:
$translate ('Pro tuto akci nemáte dostatečná oprávnění').then (function (translation) {
notificationsService.push ('alert', translation);
$state.go ('projects');
});
break;
default:
$translate ('Nelze vykonat požadavek').then (function (translation) {
notificationsService.push ('alert', translation);
$state.go ('projects');
});
break;
}
});
};
/**
* Edit current environment
*/
self.edit = function () {
var environmentId = $stateParams.environmentId;
// ignore not-changed form
if (self.formData.name == self.detail.name && self.formData.description == self.detail.description && self.formData.apiEndpoint == self.detail.apiEndpoint)
return;
environmentsService.edit (environmentId, self.formData).then (function (data) {
$rootScope.refreshProjectOverview ();
self.loadDetail ();
$translate ('Úspěšně uloženo.').then (function (translation) {
notificationsService.push ('success', translation);
});
}, function (response) {
switch (data.status) {
case 403:
$translate ('Pro tuto akci nemáte dostatečná oprávnění').then (function (translation) {
notificationsService.push ('alert', translation);
$state.go ('projects');
});
break;
default:
$translate ('Nelze vykonat požadavek').then (function (translation) {
notificationsService.push ('alert', translation);
$state.go ('projects');
});
break;
}
});
};
/**
* Delete given environment
* @param environmentId
*/
self.delete = function (environmentId) {
if (confirm ($translate.instant ('Opravdu?'))) {
environmentsService.delete (environmentId).then (function (response) {
$rootScope.refreshProjectOverview ();
$rootScope.reinitIdentity (function () {
self.initOverview (undefined, undefined, false);
});
}, function (response) {
switch (response.status) {
case 403:
$translate ('Pro tuto akci nemáte dostatečná oprávnění').then (function (translation) {
notificationsService.push ('alert', translation);
$state.go ('projects');
});
break;
default:
$translate ('Nelze vykonat požadavek').then (function (translation) {
notificationsService.push ('alert', translation);
$state.go ('projects');
});
break;
}
});
}
};
/**
* Assign user to current environment
*/
self.assignUser = function () {
var environmentId = $stateParams.environmentId;
environmentsService.addUser (environmentId, self.addUser).then (function (response) {
self.loadDetail ();
self.addUser = {};
self.manageUser = false;
}, function (response) {
switch (response.status) {
case 403:
$translate ('Pro tuto akci nemáte dostatečná oprávnění').then (function (translation) {
notificationsService.push ('alert', translation);
});
break;
case 400:
$translate ('Uživatel je k prostředí již přiřazen.').then (function (translation) {
notificationsService.push ('alert', translation);
});
break;
default:
$translate ('Nelze vykonat požadavek').then (function (translation) {
notificationsService.push ('alert', translation);
});
break;
}
});
};
/**
* Remove specified user from current environment
*
* @param userId
*/
self.removeUser = function (userId) {
var environmentId = $stateParams.environmentId;
if (confirm ($translate.instant ('Opravdu?'))) {
environmentsService.removeUser (environmentId, userId).then (function (response) {
self.loadDetail ();
}, function (response) {
switch (response.status) {
case 403:
$translate ('Pro tuto akci nemáte dostatečná oprávnění').then (function (translation) {
notificationsService.push ('alert', translation);
$state.go ('projects');
});
break;
default:
$translate ('Nelze vykonat požadavek').then (function (translation) {
notificationsService.push ('alert', translation);
$state.go ('projects');
});
break;
}
});
}
};
return self;
}]);
|
/**
* @file gasp 表
* 对于需要hinting的字号需要这个表,否则会导致错误
* @author mengke01(kekee000@gmail.com)
* reference: https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6gasp.html
*/
var table = require('./table');
var gasp = table.create(
'gasp',
[],
{
read: function (reader, ttf) {
var length = ttf.tables.gasp.length;
return reader.readBytes(this.offset, length);
},
write: function (writer, ttf) {
if (ttf.gasp) {
writer.writeBytes(ttf.gasp, ttf.gasp.length);
}
},
size: function (ttf) {
return ttf.gasp ? ttf.gasp.length : 0;
}
}
);
module.exports = gasp;
|
// All symbols in the `Cherokee` script as per Unicode v5.2.0:
[
'\u13A0',
'\u13A1',
'\u13A2',
'\u13A3',
'\u13A4',
'\u13A5',
'\u13A6',
'\u13A7',
'\u13A8',
'\u13A9',
'\u13AA',
'\u13AB',
'\u13AC',
'\u13AD',
'\u13AE',
'\u13AF',
'\u13B0',
'\u13B1',
'\u13B2',
'\u13B3',
'\u13B4',
'\u13B5',
'\u13B6',
'\u13B7',
'\u13B8',
'\u13B9',
'\u13BA',
'\u13BB',
'\u13BC',
'\u13BD',
'\u13BE',
'\u13BF',
'\u13C0',
'\u13C1',
'\u13C2',
'\u13C3',
'\u13C4',
'\u13C5',
'\u13C6',
'\u13C7',
'\u13C8',
'\u13C9',
'\u13CA',
'\u13CB',
'\u13CC',
'\u13CD',
'\u13CE',
'\u13CF',
'\u13D0',
'\u13D1',
'\u13D2',
'\u13D3',
'\u13D4',
'\u13D5',
'\u13D6',
'\u13D7',
'\u13D8',
'\u13D9',
'\u13DA',
'\u13DB',
'\u13DC',
'\u13DD',
'\u13DE',
'\u13DF',
'\u13E0',
'\u13E1',
'\u13E2',
'\u13E3',
'\u13E4',
'\u13E5',
'\u13E6',
'\u13E7',
'\u13E8',
'\u13E9',
'\u13EA',
'\u13EB',
'\u13EC',
'\u13ED',
'\u13EE',
'\u13EF',
'\u13F0',
'\u13F1',
'\u13F2',
'\u13F3',
'\u13F4'
]; |
'use strict';
describe('myApp.version module', function() {
beforeEach(module('cafe'));
describe('app-version directive', function() {
it('should print current version', function() {
module(function($provide) {
$provide.value('version', 'TEST_VER');
});
inject(function($compile, $rootScope) {
var element = $compile('<span app-version></span>')($rootScope);
expect(element.text()).toEqual('TEST_VER');
});
});
});
});
|
const debug = require('../debug').server
const fs = require('fs')
const util = require('../utils')
const Auth = require('../api/authn')
/**
* Serves as a last-stop error handler for all other middleware.
*
* @param err {Error}
* @param req {IncomingRequest}
* @param res {ServerResponse}
* @param next {Function}
*/
function handler (err, req, res, next) {
debug('Error page because of:', err)
const locals = req.app.locals
const authMethod = locals.authMethod
const ldp = locals.ldp
// If the user specifies this function,
// they can customize the error programmatically
if (ldp.errorHandler) {
debug('Using custom error handler')
return ldp.errorHandler(err, req, res, next)
}
const statusCode = statusCodeFor(err, req, authMethod)
switch (statusCode) {
case 401:
setAuthenticateHeader(req, res, err)
renderLoginRequired(req, res, err)
break
case 403:
renderNoPermission(req, res, err)
break
default:
if (ldp.noErrorPages) {
sendErrorResponse(statusCode, res, err)
} else {
sendErrorPage(statusCode, res, err, ldp)
}
}
}
/**
* Returns the HTTP status code for a given request error.
*
* @param err {Error}
* @param req {IncomingRequest}
* @param authMethod {string}
*
* @returns {number}
*/
function statusCodeFor (err, req, authMethod) {
let statusCode = err.status || err.statusCode || 500
if (authMethod === 'oidc') {
statusCode = Auth.oidc.statusCodeOverride(statusCode, req)
}
return statusCode
}
/**
* Dispatches the writing of the `WWW-Authenticate` response header (used for
* 401 Unauthorized responses).
*
* @param req {IncomingRequest}
* @param res {ServerResponse}
* @param err {Error}
*/
function setAuthenticateHeader (req, res, err) {
const locals = req.app.locals
const authMethod = locals.authMethod
switch (authMethod) {
case 'oidc':
Auth.oidc.setAuthenticateHeader(req, res, err)
break
case 'tls':
Auth.tls.setAuthenticateHeader(req, res)
break
default:
break
}
}
/**
* Sends the HTTP status code and error message in the response.
*
* @param statusCode {number}
* @param res {ServerResponse}
* @param err {Error}
*/
function sendErrorResponse (statusCode, res, err) {
res.status(statusCode)
res.header('Content-Type', 'text/plain;charset=utf-8')
res.send(err.message + '\n')
}
/**
* Sends the HTTP status code and error message as a custom error page.
*
* @param statusCode {number}
* @param res {ServerResponse}
* @param err {Error}
* @param ldp {LDP}
*/
function sendErrorPage (statusCode, res, err, ldp) {
const errorPage = ldp.errorPages + statusCode.toString() + '.html'
return new Promise((resolve) => {
fs.readFile(errorPage, 'utf8', (readErr, text) => {
if (readErr) {
// Fall back on plain error response
return resolve(sendErrorResponse(statusCode, res, err))
}
res.status(statusCode)
res.header('Content-Type', 'text/html')
res.send(text)
resolve()
})
})
}
/**
* Renders a 401 response explaining that a login is required.
*
* @param req {IncomingRequest}
* @param res {ServerResponse}
*/
function renderLoginRequired (req, res, err) {
const currentUrl = util.fullUrlForReq(req)
debug(`Display login-required for ${currentUrl}`)
res.statusMessage = err.message
res.status(401)
res.render('auth/login-required', { currentUrl })
}
/**
* Renders a 403 response explaining that the user has no permission.
*
* @param req {IncomingRequest}
* @param res {ServerResponse}
*/
function renderNoPermission (req, res, err) {
const currentUrl = util.fullUrlForReq(req)
const webId = req.session.userId
debug(`Display no-permission for ${currentUrl}`)
res.statusMessage = err.message
res.status(403)
res.render('auth/no-permission', { currentUrl, webId })
}
/**
* Returns a response body for redirecting browsers to a Select Provider /
* login workflow page. Uses either a JS location.href redirect or an
* http-equiv type html redirect for no-script conditions.
*
* @param url {string}
*
* @returns {string} Response body
*/
function redirectBody (url) {
return `<!DOCTYPE HTML>
<meta charset="UTF-8">
<script>
window.location.href = "${url}" + encodeURIComponent(window.location.hash)
</script>
<noscript>
<meta http-equiv="refresh" content="0; url=${url}">
</noscript>
<title>Redirecting...</title>
If you are not redirected automatically,
follow the <a href='${url}'>link to login</a>
`
}
module.exports = {
handler,
redirectBody,
sendErrorPage,
sendErrorResponse,
setAuthenticateHeader
}
|
/*global require module */
(function () {
"use strict";
var express = require('express');
var router = express.Router();
var clienteHandler = require('./clientesHandler.js');
router.get('/clientes', clienteHandler.getClientes);
router.post('/clientes', clienteHandler.createCliente);
router.put('/clientes/:clienteID', clienteHandler.modifyCliente);
router.delete ('/clientes/:clienteID', clienteHandler.delCliente);
module.exports = router;
}
());
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.DOK = global.DOK || {})));
}(this, (function (core) { 'use strict';
var spot = {x:0,y:0}, callbacks = [];
var touchSpotX = {}, touchSpotY = {};
var mdown = false;
/**
* HEADER
*/
core.requireScripts([
'setup.js',
]);
core.logScript();
/**
* FUNCTION DEFINITIONS
*/
function onDown(e)
{
if(e.target.attributes['tap']===undefined) {
var touches = e.changedTouches;
if(touches) {
for(var i=0;i<touches.length;i++) {
var touch = touches[i];
touchSpotX[touch.identifier] =touch.pageX;
touchSpotY[touch.identifier] =touch.pageY;
}
} else {
spot.x = e.pageX;
spot.y = e.pageY;
}
mdown = true;
for(var i=0;i<callbacks.length;i++) {
callbacks[i](null,null,true,e.pageX,e.pageY);
}
}
e.preventDefault();
}
function onUp(e) {
var hasTouch = false;
if(e.changedTouches) {
for(var i=0;i<e.changedTouches.length;i++) {
delete touchSpotX[touch.identifier];
delete touchSpotY[touch.identifier];
}
for(var i in touchSpotX) {
hasTouch = true;
}
}
for(var i=0;i<callbacks.length;i++) {
callbacks[i](null,null, hasTouch,e.pageX,e.pageY);
}
mdown = false;
e.preventDefault();
}
function onMove(e) {
var touches = e.changedTouches;
if(!touches) {
if(e.buttons & 1 && mdown) {
var newX = e.pageX;
var newY = e.pageY;
var dx = newX - spot.x;
var dy = newY - spot.y;
spot.x = newX;
spot.y = newY;
for(var i=0;i<callbacks.length;i++) {
callbacks[i](dx,dy,true,e.pageX,e.pageY);
}
} else {
mdown = false;
for(var i=0;i<callbacks.length;i++) {
callbacks[i](dx,dy,false,e.pageX,e.pageY);
}
}
} else if(mdown) {
var dx = 0, dy = 0;
for(var i=0;i<touches.length;i++) {
var touch = touches[i];
dx += touch.pageX - touchSpotX[touch.identifier];
dy += touch.pageY - touchSpotY[touch.identifier];
touchSpotX[touch.identifier] = touch.pageX;
touchSpotY[touch.identifier] = touch.pageY;
}
for(var i=0;i<callbacks.length;i++) {
callbacks[i](dx,dy,true,e.pageX,e.pageY);
}
}
e.preventDefault();
}
function setOnTouch(func) {
deactivateTouch();
activateTouch();
callbacks.push(func);
}
function activateTouch() {
document.addEventListener("mousedown", onDown);
document.addEventListener("touchstart", onDown);
document.addEventListener("mouseup", onUp);
document.addEventListener("touchend", onUp);
document.addEventListener("touchcancel", onUp);
document.addEventListener("mousemove", onMove);
document.addEventListener("touchmove", onMove);
}
function deactivateTouch() {
document.removeEventListener("mousedown", onDown);
document.removeEventListener("touchstart", onDown);
document.removeEventListener("mouseup", onUp);
document.removeEventListener("touchend", onUp);
document.removeEventListener("touchcancel", onUp);
document.removeEventListener("mousemove", onMove);
document.removeEventListener("touchmove", onMove);
}
function destroyEverything() {
callbacks = [];
deactivateTouch();
}
/**
* PUBLIC DECLARATIONS
*/
core.setOnTouch = setOnTouch;
core.destroyEverything = core.combineMethods(destroyEverything, core.destroyEverything);
/**
* PROCESSES
*/
}))); |
//= link_directory ../javascripts/twitter/bootstrap/components/rails .js
//= link_directory ../stylesheets/twitter/bootstrap/components/rails .css
|
import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
import Button from 'app/components/shared/Button';
import FormRadioGroup from 'app/components/shared/FormRadioGroup';
import Panel from 'app/components/shared/Panel';
import FlashesStore from 'app/stores/FlashesStore';
import OrganizationMemberUpdateMutation from 'app/mutations/OrganizationMemberUpdate';
import OrganizationMemberRoleConstants from 'app/constants/OrganizationMemberRoleConstants';
import OrganizationMemberSSOModeConstants from 'app/constants/OrganizationMemberSSOModeConstants';
class Form extends React.PureComponent {
static displayName = "Member.Edit.Form";
static propTypes = {
organizationMember: PropTypes.shape({
role: PropTypes.string.isRequired,
sso: PropTypes.shape({
mode: PropTypes.string
}).isRequired,
permissions: PropTypes.object.isRequired,
user: PropTypes.shape({
name: PropTypes.string.isRequired
}).isRequired,
organization: PropTypes.shape({
ssoProviders: PropTypes.shape({
count: PropTypes.number.isRequired
}).isRequired
}).isRequired
})
};
state = {
role: null,
ssoMode: null
};
UNSAFE_componentWillMount() {
this.setState({
role: this.props.organizationMember.role,
ssoMode: this.props.organizationMember.sso.mode
});
}
render() {
if (!this.props.organizationMember.permissions.organizationMemberUpdate.allowed) {
return (
<Panel>
<Panel.Section>
{this.props.organizationMember.permissions.organizationMemberUpdate.message}
</Panel.Section>
</Panel>
);
}
return (
<Panel>
<Panel.Section>
<FormRadioGroup
label="Role"
value={this.state.role}
onChange={this.handleRoleChange}
required={true}
options={[
{
label: "User",
value: OrganizationMemberRoleConstants.MEMBER,
help: "Can view, create and manage pipelines and builds."
},
{
label: "Administrator",
value: OrganizationMemberRoleConstants.ADMIN,
help: "Can view and edit everything in the organization."
}
]}
/>
</Panel.Section>
{this.renderSSOSection()}
<Panel.Section>
<Button
onClick={this.handleUpdateOrganizationMemberClick}
loading={this.state.updating && 'Saving User…'}
>
Save User
</Button>
</Panel.Section>
</Panel>
);
}
renderSSOSection() {
if (!this.isSSOEnabled()) {
return null;
}
return (
<Panel.Section>
<FormRadioGroup
label="Single Sign-On"
value={this.state.ssoMode}
onChange={this.handleSSOModeChange}
required={true}
options={[
{
label: "Required",
value: OrganizationMemberSSOModeConstants.REQUIRED,
help: "A verified SSO authorization is required before this user can access organization details.",
badge: "Recomended"
},
{
label: "Optional",
value: OrganizationMemberSSOModeConstants.OPTIONAL,
help: "The user can access organization details either via SSO, or with their Buildkite email and password."
}
]}
/>
</Panel.Section>
);
}
isSSOEnabled() {
return (
this.props.organizationMember.organization.ssoProviders.count > 0
);
}
handleRoleChange = (evt) => {
this.setState({
role: evt.target.value
});
}
handleSSOModeChange = (evt) => {
this.setState({
ssoMode: evt.target.value
});
}
handleUpdateOrganizationMemberClick = () => {
// Show the updating indicator
this.setState({ updating: true });
const variables = {
organizationMember: this.props.organizationMember,
role: this.state.role
};
if (this.isSSOEnabled()) {
variables.sso = {
mode: this.state.ssoMode
};
}
const mutation = new OrganizationMemberUpdateMutation(variables);
// Run the mutation
Relay.Store.commitUpdate(mutation, {
onSuccess: this.handleMutationSuccess,
onFailure: this.handleMutationFailure
});
}
handleMutationSuccess = ({ organizationMemberUpdate }) => {
this.setState({ updating: false });
FlashesStore.flash(
FlashesStore.SUCCESS,
`${organizationMemberUpdate.organizationMember.user.name}’s member details have been saved`
);
}
handleMutationFailure = (transaction) => {
this.setState({ updating: false });
FlashesStore.flash(FlashesStore.ERROR, transaction.getError());
}
}
export default Relay.createContainer(Form, {
fragments: {
organizationMember: () => Relay.QL`
fragment on OrganizationMember {
role
sso {
mode
}
user {
name
}
organization {
ssoProviders {
count
}
}
permissions {
organizationMemberUpdate {
allowed
message
}
}
${OrganizationMemberUpdateMutation.getFragment('organizationMember')}
}
`
}
});
|
'use strict';
function getValue(src, def) {
return typeof src === 'undefined' ? def : src;
}
exports.getValue = getValue;
function getKey(key, src, def) {
return getValue(src[key], def[key]);
}
exports.getKey = getKey;
function setKey(key, target, src, def) {
var val = target[key] = getValue(src[key], def[key]);
return val;
}
exports.setKey = setKey;
function createObject(src, factory) {
return factory(src);
}
exports.createObject = createObject;
function setObject(key, src, factory) {
var val = getValue(src[key], {});
src[key] = createObject.call(null, val, factory);
return src[key];
}
exports.setObject = setObject;
function getCollection(src, itemFactory) {
src = getValue(src, []);
return src.map(itemFactory);
}
exports.getCollection = getCollection;
function setCollection(key, src, itemFactory) {
var val = src[key] = getCollection(src[key], itemFactory);
return val;
}
exports.setCollection = setCollection;
|
var events = require('events');
var eventEmitter = new events.EventEmitter();
var request = require('request');
var _ = require('underscore');
var baseURL = 'https://api.vineapp.com';
var version = '1.3.2';
var userAgent = 'iphone/' + version + ' (iPhone; iOS 7.0; Scale/2.00)';
var vineClient = 'ios/' + version;
var self;
function Twine(args, callback){
self = this;
if(args && args.username && args.password){
self.auth(args.username, args.password, function(user){
self.setSession(user);
})
}
var key;
var userId;
}
Twine.prototype = new events.EventEmitter;
Twine.prototype.auth = function(username, password, callback){
request.post(baseURL + '/users/authenticate', {form:{"deviceToken":randomString(64), "username": username, "password": password}}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var data = JSON.parse(body).data;
callback(data);
}
})
}
Twine.prototype.setSession = function(args, callback){
this.key = args.key;
this.userId = args.userId;
self.emit('loggedIn');
if(callback){
callback(args);
}
}
Twine.prototype.getUser = function(userId, callback){
request({url : baseURL + '/users/profiles/' + userId, headers: headers: getHeaders() }, function (error, response, body) {
if (!error && response.statusCode == 200) {
callback(JSON.parse(body).data);
}
else {
console.log(response);
}
})
}
Twine.prototype.getMe = function(callback){
request({url : baseURL + '/users/me', headers: getHeaders() }, function (error, response, body) {
if (!error && response.statusCode == 200) {
callback(JSON.parse(body).data);
}
else {
console.log(response);
}
})
}
Twine.prototype.getTimeline = function(callback){
request({url : baseURL + '/timelines/graph', headers: getHeaders() }, function (error, response, body) {
if (!error && response.statusCode == 200) {
callback(JSON.parse(body).data);
}
else {
console.log(response);
}
})
}
Twine.prototype.getUserTimeline = function(userId, callback){
request({url : baseURL + '/timelines/users/' + userId , headers: getHeaders() }, function (error, response, body) {
if (!error && response.statusCode == 200) {
callback(JSON.parse(body).data);
}
else {
console.log(response);
}
})
}
Twine.prototype.searchUsers = function(query, callback){
request({url : baseURL + '/users/search/' + query , headers: getHeaders() }, function (error, response, body) {
if (!error && response.statusCode == 200) {
callback(JSON.parse(body).data);
}
else {
console.log(response);
}
})
}
module.exports = Twine;
// Helpers
function randomString(length){
var data = "";
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
_(length || 16).times(function(){ data += possible[_.random(possible.length-1)]; });
return data;
}
function getHeaders(){
// This is a stupid method. I know this. But there is a reason.
return {"vine-session-id" : this.key , "User-Agent" : userAgent, "X-Vine-Client" : vineClient};
} |
/**
* User.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/documentation/concepts/models-and-orm/models
*/
module.exports = {
autoPK: true,
autoCreatedAt: true,
autoUpdatedAt: true,
attributes: {
name: { type: 'string' },
email: { type: 'string' },
contacts: { collection: 'contact', via: 'user' }
},
// Add change to change log
beforeUpdate: function(newUser, cb) {
// Add change to change log
sails.log.info('updating', newUser);
cb();
}
};
|
function OnMessage(messageEvent)
{
if (messageEvent.data.action == "buy"){
console.log(messageEvent.data.action);
SendMessage("Canvas", "FillText");
window.removeEventListener("message", OnMessage, false);
}
}
function OpenRechargePopup()
{
window.parent.postMessage({'action':'chips'},'*');
window.addEventListener("message", OnMessage, false);
} |
import React from 'react';
import { luiClassName } from '../util';
const PopoverFooter = ({
className,
children,
nopad,
...extraProps
}) => {
const finalClassName = luiClassName('popover__footer', {
className,
states: { nopad },
});
return (
<div className={finalClassName} {...extraProps}>
{children}
</div>
);
};
export default PopoverFooter;
|
require([
'ijit/widgets/authentication/_LoginRegisterRequestPane',
'dojo/dom-construct',
'dojo/_base/window',
'dojo/dom-style'
],
function(
LoginRegisterRequestPane,
domConstruct,
win,
domStyle
) {
describe('ijit/widgets/authentication/_LoginRegisterRequestPane', function() {
var testWidget;
var destroy = function(widget) {
widget.destroyRecursive();
widget = null;
};
beforeEach(function() {
testWidget = new LoginRegisterRequestPane({
parentWidget: {
signInPane: {}
}
}, domConstruct.create('div', {}, win.body()));
testWidget.startup();
});
afterEach(function() {
destroy(testWidget);
});
it('create a valid object', function() {
expect(testWidget).toEqual(jasmine.any(LoginRegisterRequestPane));
});
describe('getData', function() {
var fName = 'blah1';
var lName = 'blah5';
var agency = 'blah2';
var email = 'blah3';
var password = 'blah4';
beforeEach(function() {
testWidget.fNameTxt.value = fName;
testWidget.lNameTxt.value = lName;
testWidget.agencyTxt.value = agency;
testWidget.emailTxt.value = email;
testWidget.emailConfirmTxt.value = email;
testWidget.passwordTxt.value = password;
testWidget.passwordConfirmTxt.value = password;
});
it('return the appopriate values', function() {
expect(testWidget.getData()).toEqual({
first: fName,
last: lName,
agency: agency,
email: email,
password: password
});
});
it('validates that the emails and passwords match', function() {
testWidget.emailConfirmTxt.value = 'different';
expect(function() {
testWidget.getData();
}).toThrow(testWidget.mismatchedEmailMsg);
testWidget.emailConfirmTxt.value = email;
testWidget.passwordConfirmTxt.value = 'different';
expect(function() {
testWidget.getData();
}).toThrow(testWidget.mismatchedPasswordMsg);
});
});
describe('onSubmitReturn', function() {
it('shows the success msg', function() {
spyOn(testWidget, 'showSuccessMsg');
testWidget.onSubmitReturn();
expect(testWidget.showSuccessMsg).toHaveBeenCalled();
});
it('hides the request button', function () {
testWidget.onSubmitReturn();
expect(domStyle.get(testWidget.submitBtn, 'display')).toEqual('none');
});
});
});
}); |
/* Game namespace */
var game = {
// an object where to store game information
data: {
// score
score: 0,
option1: "",
option2: "",
enemyBaseHealth: 1,
playerBasehealth: 1,
enemyCreepHealth: 6,
playerHealth: 10,
enemyCreepAttack: 1,
playerAttack: 1,
// orcBaseDamage: 10,
// orcBaseHealth: 10,
// orcBaseSpeed: 3,
// orcBaseDefense: 0,
playerAttackTimer: 1000,
enemyCreepAttackTimer: 1000,
playerMoveSpeed: 6,
creepMoveSpeed: 6,
gameTimerManager: "",
heroDeathManager: "",
spearTimer: 15,
player: "",
exp: 0,
gold: 0,
Upgrade1: 0,
Upgrade2: 0,
Upgrade3: 0,
Ability1: 0,
Ability2: 0,
Ability3: 0,
exp1: 0,
exp2: 0,
exp3: 0,
exp4: 0,
win: "",
pausePos: "",
buyscreen: "",
buytext: ""
},
// Run on page load.
"onload": function() {
// Initialize the video.
if (!me.video.init("screen", me.video.CANVAS, 1067, 600, true, '1.0')) {
alert("Your browser does not support HTML5 canvas.");
return;
}
// add "#debug" to the URL to enable the debug Panel
if (document.location.hash === "#debug") {
window.onReady(function() {
me.plugin.register.defer(this, debugPanel, "debug");
});
}
me.state.SPENDEXP = 112;
me.state.LOAD = 113;
me.state.NEW = 114;
// Initialize the audio.
me.audio.init("mp3,ogg");
// Set a callback to run when loading is complete.
me.loader.onload = this.loaded.bind(this);
// Load the resources.
me.loader.preload(game.resources);
// Initialize melonJS and display a loading screen.
me.state.change(me.state.LOADING);
},
// Run on game resources loaded.
"loaded": function() {
me.pool.register("player", game.PlayerEntity, true);
me.pool.register("Playerbase", game.PlayerBaseEntity, true);
me.pool.register("Enemybase", game.EnemyBaseEntity, true);
me.pool.register("EnemyCreep", game.EnemyCreep, true);
me.pool.register("GameTimerManager", game.GameTimerManager);
me.pool.register("HeroDeathManager", game.HeroDeathManager);
me.pool.register("ExperienceManager", game.ExperienceManager);
me.pool.register("SpendGold", game.SpendGold);
me.pool.register("spear", game.SpartanThrow);
me.state.set(me.state.MENU, new game.TitleScreen());
me.state.set(me.state.PLAY, new game.PlayScreen());
me.state.set(me.state.SPENDEXP, new game.SpendExp());
me.state.set(me.state.LOAD, new game.LoadProfile());
me.state.set(me.state.NEW, new game.NewProfile());
// Start the game.
me.state.change(me.state.MENU);
}
}; |
// JS Goes here - ES6 supported
import Velocity from 'velocity-animate';
var george = document.getElementById('george');
var lighthouse = document.getElementsByClassName('lighthouse-draw');
/* First animation */
Velocity(lighthouse, { strokeDashoffset: 0 }, {duration: 3000});
Velocity(lighthouse, { fill: "#145693" }, {delay: 1250, queue: false});
Velocity(george, "fadeIn", { delay: 1500, duration: 1000});
Velocity(george, { translateY: -75 }, { delay: 1500, duration: 1000, queue: false });
Velocity(george, { rotateZ: -5 }, { delay: 1500, duration: 2000, queue: false }); |
import {Meteor} from 'meteor/meteor';
import {Template} from 'meteor/templating';
import {Session} from 'meteor/session';
import {Random} from 'meteor/random';
import {FlowRouter} from 'meteor/kadira:flow-router';
import {moment} from 'meteor/momentjs:moment';
import {numeral} from 'meteor/numeral:numeral';
// Utils
import {Util} from '../../api/util.js';
import {DocTreeConfig} from '../../../client/ui/lib/doc_tree/doc_tree_config.js';
// Collections
import {Actions} from '../../api/actions/actions.js';
import {Datastores} from '../../api/datastores/datastores.js';
import {DatastoreDataTypes} from '../../api/datastores/datastore_data_types.js';
import {Nodes} from '../../api/nodes/nodes.js';
import {Projects} from '../../api/projects/projects.js';
import {ProjectVersions} from '../../api/projects/project_versions.js';
import {TestServers} from '../../api/test_servers/test_servers.js';
import {TestAgents} from '../../api/test_agents/test_agents.js';
import {TestSystems} from '../../api/test_systems/test_systems.js';
// Enums
import {AdventureStatus, AdventureStatusLookup} from '../../api/adventures/adventure_status.js';
import {AdventureStepStatus, AdventureStepStatusLookup} from '../../api/adventures/adventure_step_status.js';
import {ChangeTypes, ChangeTypesLookup} from '../../api/change_tracker/change_types.js';
import {DatastoreCategories, DatastoreCategoriesLookup} from '../../api/datastores/datastore_catagories.js';
import {FieldTypes, FieldTypesLookup} from '../../api/datastores/field_types.js';
import {FunctionParamTypes, FunctionParamTypesLookup} from '../../api/code_modules/function_param_types.js';
import {NodeTypes, NodeTypesLookup} from '../../api/nodes/node_types.js';
import {NodeComparisonDatumResult, NodeComparisonDatumResultLookup} from '../../api/platform_types/node_comparison_datum_result.js';
import {PlatformTypes, PlatformTypesLookup} from '../../api/platform_types/platform_types.js';
import {ProjectRoles, ProjectRolesLookup} from '../../api/projects/project_roles.js';
import {ReferenceTypes, ReferenceTypesLookup} from '../../api/reference_docs/reference_types.js';
import {TestAgentOS, TestAgentOSLookup} from '../../api/test_agents/test_agent_os.js';
import {TestAgentTypes, TestAgentTypesLookup} from '../../api/test_agents/test_agent_types.js';
import {TestCaseStepTypes, TestCaseStepTypesLookup} from '../../api/test_cases/test_case_step_types.js';
import {TestResultCodes, TestResultCodesLookup} from '../../api/test_results/test_result_codes.js';
import {TestResultStatus, TestResultStatusLookup} from '../../api/test_results/test_result_status.js';
import {TestRunItemTypes, TestRunItemTypesLookup} from '../../api/test_runs/test_run_item_types.js';
import {TestSystemStatus, TestSystemStatusLookup} from '../../api/test_systems/test_system_status.js';
/**
* Listen for page resize events
*/
Meteor.startup(function(){
var self = {};
// setup a resize event for redraw actions
Session.set("resize", { timestamp: Date.now(), width: window.innerWidth, height: window.innerHeight });
$(window).resize(function() {
if(this.resizeTimeout){
clearTimeout(this.resizeTimeout);
}
this.resizeTimeout = setTimeout(function(){
Session.set("resize", { timestamp: Date.now(), width: window.innerWidth, height: window.innerHeight });
}.bind(self), 250);
});
// set the default setup for x-editable
$.fn.editable.defaults.mode = "inline";
});
/**
* Enums
*/
Template.registerHelper("AdventureStatus", () => { return AdventureStatus });
Template.registerHelper("AdventureStatusLookup", () => { return AdventureStatusLookup });
Template.registerHelper("AdventureStepStatus", () => { return AdventureStepStatus });
Template.registerHelper("AdventureStepStatusLookup", () => { return AdventureStepStatusLookup });
Template.registerHelper("ChangeTypes", () => { return ChangeTypes });
Template.registerHelper("ChangeTypesLookup", () => { return ChangeTypesLookup });
Template.registerHelper("DatastoreCategories", () => { return DatastoreCategories });
Template.registerHelper("DatastoreCategoriesLookup", () => { return DatastoreCategoriesLookup });
Template.registerHelper("FieldTypes", () => { return FieldTypes });
Template.registerHelper("FieldTypesLookup", () => { return FieldTypesLookup });
Template.registerHelper("FunctionParamTypes", () => { return FunctionParamTypes });
Template.registerHelper("FunctionParamTypesLookup", () => { return FunctionParamTypesLookup });
Template.registerHelper("NodeTypes", () => { return NodeTypes });
Template.registerHelper("NodeTypesLookup", () => { return NodeTypesLookup });
Template.registerHelper("NodeComparisonDatumResult", () => { return NodeComparisonDatumResult });
Template.registerHelper("NodeComparisonDatumResultLookup", () => { return NodeComparisonDatumResultLookup });
Template.registerHelper("PlatformTypes", () => { return PlatformTypes });
Template.registerHelper("PlatformTypesLookup", () => { return PlatformTypesLookup });
Template.registerHelper("ProjectRoles", () => { return ProjectRoles });
Template.registerHelper("ProjectRolesLookup", () => { return ProjectRolesLookup });
Template.registerHelper("ReferenceTypes", () => { return ReferenceTypes });
Template.registerHelper("ReferenceTypesLookup", () => { return ReferenceTypesLookup });
Template.registerHelper("TestAgentOS", () => { return TestAgentOS });
Template.registerHelper("TestAgentOSLookup", () => { return TestAgentOSLookup });
Template.registerHelper("TestAgentTypes", () => { return TestAgentTypes });
Template.registerHelper("TestAgentTypesLookup", () => { return TestAgentTypesLookup });
Template.registerHelper("TestCaseStepTypes", () => { return TestCaseStepTypes });
Template.registerHelper("TestCaseStepTypesLookup", () => { return TestCaseStepTypesLookup });
Template.registerHelper("TestResultCodes", () => { return TestResultCodes });
Template.registerHelper("TestResultCodesLookup", () => { return TestResultCodesLookup });
Template.registerHelper("TestResultStatus", () => { return TestResultStatus });
Template.registerHelper("TestResultStatusLookup", () => { return TestResultStatusLookup });
Template.registerHelper("TestRunItemTypes", () => { return TestRunItemTypes });
Template.registerHelper("TestRunItemTypesLookup", () => { return TestRunItemTypesLookup });
Template.registerHelper("TestSystemStatus", () => { return TestSystemStatus });
Template.registerHelper("TestSystemStatusLookup", () => { return TestSystemStatusLookup });
/**
* Debug
*/
Template.registerHelper("debug", function(){
if(arguments.length){
var argv = _.toArray(arguments).slice(0, -1);
if(typeof argv[0] == "string"){
console.log(argv[0], argv.slice(1));
} else {
console.log("Debug: ", argv);
}
} else {
console.log("Debug: ", this);
}
});
/**
* Subscriptions ready
*/
Template.registerHelper("ready", function(){
return Template.instance().subscriptionsReady()
});
/**
* Simple pathFor helper
*/
Template.registerHelper("pathFor", function (routeName, routeParams) {
return FlowRouter.path(routeName, routeParams.hash);
});
/**
* Set the page title
*/
Template.registerHelper("setTitle", function () {
if(arguments.length){
document.title = _.toArray(arguments).slice(0, -1).join(" ");
}
});
/**
* Get the title displayed in the main nav menu
*/
Template.registerHelper("setNavTitle", function () {
if(arguments.length){
Session.set("navTitle", _.toArray(arguments).slice(0, -1).join(" "));
}
});
/**
* Not Null helper
*/
Template.registerHelper("notNull", function(value){
return value != null;
});
/**
* Variable and function name validation helper
*/
Template.registerHelper("variablePattern", function(){
return Util.variableInputPattern;
});
/**
* Get a screen size relative height value
*/
Template.registerHelper("relativeHeight", function(proportion){
if(proportion){
var screenSize = Session.get("resize");
if(screenSize.height){
return parseInt(parseFloat(proportion) * screenSize.height);
}
}
});
Template.registerHelper("relativeWidth", function(proportion){
if(proportion){
var screenSize = Session.get("resize");
if(screenSize.width){
return parseInt(parseFloat(proportion) * screenSize.width);
}
}
});
/**
* Determine if a field is custom
*/
Template.registerHelper("fieldIsCustom", function(field){
field = field || this;
return field && field.type == FieldTypes.custom;
});
/**
* Quick general field renderer
*/
Template.registerHelper("renderValueByType", function (value){
if(_.isBoolean(value)){
return value ? "true" : "false"
} else if(_.isDate(value)){
return moment(value).format("MMM Do, YY");
} else if(_.isObject(value)){
return JSON.stringify(value);
} else {
return value;
}
});
/**
* Render a lookup value
*/
Template.registerHelper("renderLookup", function (lookupName, key, style) {
if(lookupName && key !== undefined){
var lookup = eval(lookupName);
if(lookup){
var name = lookup[key];
if(name){
if(style && style == "dash"){
return Util.camelToDash(name);
} else {
return Util.camelToTitle(name);
}
} else {
console.error("renderLookup failed: no key [" + key + "] in " + lookupName);
}
} else {
console.error("renderLookup failed: lookup not found " + lookupName);
}
} else {
//console.error("renderLookup failed: insufficient data [" + lookupName + "," + key + "]");
}
});
/**
* Render a node title
*/
Template.registerHelper("renderNodeTitle", function (staticId, projectVersionId) {
check(staticId, String);
check(projectVersionId, String);
var node = Nodes.findOne({staticId: staticId, projectVersionId: projectVersionId});
return node ? node.title : "";
});
/**
* Render a user's name
*/
Template.registerHelper("renderUserDisplayName", function (userId) {
if(userId){
var user = Meteor.users.findOne(userId);
if(user){
return user.profile.name;
}
}
});
/**
* Render a camel case string as words
*/
Template.registerHelper("renderCamelCaseAsWords", function (message) {
if(message){
return Util.camelToTitle(message);
}
});
/**
* Render a formatted date
*/
Template.registerHelper("dateFormat", function (date, format) {
format = _.isString(format) ? format : "MMM Do, YY";
if(date){
return moment(date).format(format);
}
});
/**
* Render a formatted date
*/
Template.registerHelper("dateFromNow", function (date, hideSuffix) {
hideSuffix = hideSuffix === true;
if(date){
return moment(date).fromNow(hideSuffix);
}
});
/**
* Render a formatted number
*/
Template.registerHelper("numberFormat", function (value, format) {
return numeral(value).format(format);
});
/**
* Render a formatted number
*/
Template.registerHelper("renderLogTime", function (value) {
return numeral(value).format("0.000");
});
/**
* Get a list of projects for a user, including their role
*/
Template.registerHelper("userProjects", function () {
var user = Meteor.user();
if(user && user.projectList){
return Projects.find({_id: {$in: user.projectList}, active: true}, {sort: {title: 1}});
}
console.log("userProjects:", user);
});
/**
* Get the role for this user for a given project
*/
Template.registerHelper("userRole", function (projectId) {
projectId = (this ? this._id : this) || projectId;
var user = Meteor.user();
if(user && user.projects && user.projects[projectId] && user.projects[projectId].roles){
var role = _.min(user.projects[projectId].roles);
if(role != null){
return ProjectRolesLookup[role]
}
}
});
/**
* Check if a user has role permissions for a project
*/
Template.registerHelper("hasProjectAdminRole", function (projectId) {
if(projectId && Meteor.userId()) {
var user = Meteor.users.findOne(Meteor.userId());
return user.hasAdminAccess(projectId);
}
});
/**
* Check if a user has role permissions for a project
*/
Template.registerHelper("hasRole", function (roleName, projectId) {
if(roleName){
var roleType = ProjectRoles[roleName];
if(roleType){
var user = Meteor.user();
if(user && user.projects && user.projects[projectId] && user.projects[projectId].roles){
return _.contains(user.projects[projectId].roles, roleType)
}
}
}
return false
});
/**
* Get the list of versions for a project
*/
Template.registerHelper("projectVersions", function () {
var project = this;
if(project && project._id){
return ProjectVersions.find({projectId: project._id}, {sort: {version: -1}});
}
});
/**
* Render a change type to a string
*/
Template.registerHelper("renderDataTypeTitle", function (staticId, projectVersionId) {
if(staticId && projectVersionId){
var customType = DatastoreDataTypes.findOne({staticId: staticId, projectVersionId: projectVersionId});
if(customType){
return customType.title;
}
}
});
/**
* Render a test agent name
*/
Template.registerHelper("renderTestAgentName", function (testAgent) {
return Util.getTestAgentNameWithVersion(testAgent);
});
/**
* Render a test agent name from just the ID
*/
Template.registerHelper("renderTestAgentNameFromId", function (id) {
var testAgent = TestAgents.findOne({_id: id});
if(testAgent){
return Util.getTestAgentNameWithVersion(testAgent);
}
});
/**
* Render a test agent name from just the static ID and project version
*/
Template.registerHelper("renderTestAgentNameFromStaticId", function (staticId, projectVersionId) {
var testAgent = TestAgents.findOne({staticId: staticId, projectVersionId: projectVersionId});
if(testAgent) {
return Util.getTestAgentNameWithVersion(testAgent);
}
});
/**
* Render a server name
*/
Template.registerHelper("renderServerName", function (serverId) {
var server = TestServers.findOne(serverId);
if(server){
return server.title;
}
});
/**
* Render a server name from a server staticId
*/
Template.registerHelper("renderServerNameFromStaticId", function (staticId, projectVersionId) {
var server = TestServers.findOne({staticId: staticId, projectVersionId: projectVersionId});
if(server){
return server.title;
}
});
/**
* Render a test system name
*/
Template.registerHelper("renderTestSystemName", function (testSystemId) {
var testSystem = TestSystems.findOne(testSystemId);
if(testSystem){
return testSystem.title;
}
});
/**
* Render a test system name from a test system staticId
*/
Template.registerHelper("renderTestSystemNameFromStaticId", function (staticId, projectVersionId) {
var testSystem = TestSystems.findOne({staticId: staticId, projectVersionId: projectVersionId});
if(testSystem){
return testSystem.title;
}
});
/**
* Return or generate a unique ID for an element tied to a Template Instance
*/
Template.registerHelper("getElementId", function () {
var instance = Template.instance();
if(!instance.elementId){
instance.elementId = "Element_" + Random.id();
if(instance.elementIdReactor){
instance.elementIdReactor.set(instance.elementId);
}
}
return instance.elementId;
});
/**
* Return a data-key based on a title or a value
*/
Template.registerHelper("titleKey", function (value) {
let context = this;
if(value){
return Util.dataKey(value);
} else if (context && context.title) {
return Util.dataKey(context.title);
} else if (context && context.name) {
return Util.dataKey(context.name);
}
});
/**
* Get a version of a node
*/
Template.registerHelper("getNode", function (staticId, versionId) {
if(staticId && versionId) {
return Nodes.findOne({staticId: staticId, projectVersionId: versionId});
}
});
/**
* Get a version of an action
*/
Template.registerHelper("getAction", function (staticId, versionId) {
if(staticId && versionId) {
return Actions.findOne({staticId: staticId, projectVersionId: versionId});
}
});
/**
* Determine if an adventure is not in motion
*/
Template.registerHelper("adventureIsStill", function (context) {
var adventure = context || this.adventure;
return _.contains([
AdventureStatus.awaitingCommand,
AdventureStatus.paused,
AdventureStatus.complete,
AdventureStatus.error,
AdventureStatus.failed
], adventure.status);
});
/**
* Determine if an adventure is not in motion
*/
Template.registerHelper("adventureIsComplete", function (context) {
var adventure = context || this.adventure;
return adventure.status == AdventureStatus.complete || adventure.status == AdventureStatus.failed ;
});
/**
* Determine if an adventure is paused
*/
Template.registerHelper("adventureIsPaused", function (context) {
var adventure = context || this.adventure;
return adventure.status == AdventureStatus.paused;
});
/**
* Get the right data template for test result log data
*/
Template.registerHelper("LogMessageData", function (data) {
// accept the param or default to this
data = data || this;
if(_.isString(data)){
return "LogMessageDataString";
} else if(_.isDate(data)){
return "LogMessageDataString";
} else if(_.isNumber(data)){
return "LogMessageDataString";
} else if(_.isArray(data)){
return "LogMessageDataArray";
} else if(_.isObject(data)){
return "LogMessageDataObject";
} else {
return "LogMessageDataString";
}
});
/**
* Get an name of a test step type
*/
Template.registerHelper("testStepType", function (type) {
type = type || this.type;
if(type != null){
return TestCaseStepTypesLookup[type];
}
});
/**
* Get an icon for a test step type
*/
Template.registerHelper("testStepTypeIcon", function (type) {
type = type || this.type;
return Util.testStepTypeIcon(type);
});
Template.registerHelper("join", function (list, joint) {
joint = joint && _.isString(joint) ? joint : ", ";
if(list){
return _.filter(list, function (d) {return d != null;}).join(joint);
}
});
Template.registerHelper("scale", function (number, scale) {
if( number != null && scale != null){
return number * scale;
}
});
Template.registerHelper("stringify", function () {
return JSON.stringify(this);
});
Template.registerHelper("btoa", function (value) {
return btoa(value);
});
Template.registerHelper("atob", function (value) {
return btoa(value);
});
/**
* Helpers to return configuration
*/
Template.registerHelper("nodeConfig", function (key) {
return DocTreeConfig.nodes[key];
});
|
/**
* test.js
*
* @author <a href="https://github.com/pahund">Patrick Hund</a>
* @since 14 Jul 2016
*/
import { TEST } from "../actions";
export default (state = {}, action) => {
switch (action.type) {
case TEST:
console.log("test reducer:", action.message); // eslint-disable-line no-console
return action.message;
default:
}
return state;
};
|
const nodes = new Map
const add = (ref, source, inputs, outputs) =>
nodes.set(ref, {source, inputs, outputs})
add(1, 'a = Math.random()', ['Math'], ['a'])
add(2, 'b = a * 2', ['a'], ['b'])
add(3, 'c = 42', [], ['c'])
add(4, 'd = c * 2', ['c'], ['d'])
// add(5, 'e = a * b * c * d', ['a','b','c','d'], ['e'])
console.log(nodes)
// compute graph edges
const edges = (nodes) => {
// for each node, compute any other nodes it feeds into
const edges = new Set
nodes.forEach(({outputs}, ref) => {
nodes.forEach(({inputs}, ref2) => {
if(ref != ref2) {
const linked = !outputs.every(output =>
inputs.indexOf(output) == -1
)
if(linked) {
edges.add([ref, ref2])
}
}
})
})
return edges
}
console.log(edges(nodes))
/* option 1 */
const r1 = () => {
let a
const fn = () => {
a = Math.random()
console.log(`a is ${a}`)
return {a}
}
return fn()
}
const r2 = ({a}) => {
b = a * 2
console.log(`b is ${b}`)
return [b]
}
// This is how we could call it (though memoizes)
// r2(r1())
// r3(r4())
// console.log("---", a)
const r1b = (state) => {
let a
Promise.all([])
.then(() => {
a = Math.random()
})
.then(() => {
return Object.assign(state, {a})
})
}
const r2b = (state) => {
let b
Promise.all([state.a])
.then(([a]) => {
b = a * 2
})
.then(() => {
return Object.assign(state, {b})
})
}
// b += 2
const r2c = (a, b) => {
new Function('b = a * 2')()
return [b]
}
|
/**
* Shopware 4.0
* Copyright © 2012 shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*/
/**
* Shopware Accessory Group Store
*/
//{block name="backend/article/store/accessory/groups"}
Ext.define('Shopware.apps.Article.store.accessory.Groups', {
/**
* Extend for the standard ExtJS 4
* @string
*/
extend: 'Ext.data.Store',
/**
* Auto load the store after the component
* is initialized
* @boolean
*/
autoLoad: false,
/**
* Amount of data loaded at once
* @integer
*/
pageSize: 20,
remoteFilter: true,
remoteSort: true,
/**
* Define the used model for this store
* @string
*/
model : 'Shopware.apps.Article.model.accessory.Group'
});
//{/block} |
'use strict';
var CC = {};
// interpret url param as shared code.
CC.sharedCode = false;
if(document.location.search.length > 1){
CC.sharedCode = document.location.search.substring(1);
}
CC.canvas = document.getElementById('cas');
CC.context = CC.canvas.getContext('2d');
(function(){
var $canvas = $('#cas');
function resizeCanvas() {
CC.canvas.width = $canvas.width();
CC.canvas.height = $canvas.height();
}
$( window ).resize(resizeCanvas);
resizeCanvas();
})();
CC.loadCodeAndReset = function () {
this.activeLevel = new this.levels[this.activeLevelName].constructor();
$('#userscript').remove();
try {
var e = $("<script id='userscript'>\ncontrolFunction=undefined;controlFunction = (function(){\n 'use strict';\n "+this.editor.getValue()+"\n return controlFunction;\n})();\n</script>");
$('body').append(e);
}
catch(e) {
this.pause();
this.logError(e);
return false;
}
return true;
}
CC.loadLevel = function(name) {
if(!(name in CC.levels)) name = 'TutorialBlockWithFriction';
localStorage.setItem("lastLevel",name);
this.activeLevelName = name;
this.activeLevel = new this.levels[name].constructor();
$('#levelDescription').html(this.activeLevel.description);
$('#levelTitle').text(this.activeLevel.title);
document.title = this.activeLevel.title +': Control Challenges';
var savedCode = localStorage.getItem(this.activeLevel.name+"Code");
if(typeof savedCode == 'string' && savedCode.length > 10)
this.editor.setValue(savedCode);
else
this.editor.setValue(this.activeLevel.boilerPlateCode);
CC.loadCodeAndReset();
showPopup('#levelStartPopup');
};
CC.share_BLOB = function(){
return (""+window.location).split('?')[0] + "?" + btoa(JSON.stringify({code:CC.editor.getValue(), lvl_id:CC.activeLevelName}));
};
(function(){
var runSimulation = false;
CC.pause = function () {
this.pauseButton.hide();
this.playButton.show();
runSimulation = false;
};
CC.play = function () {
this.pauseButton.show();
this.playButton.hide();
runSimulation = true;
};
CC.running = function(){return runSimulation;};
})();
CC.editorSetCode_preserveOld = function(code) {
var lines = this.editor.getValue().split(/\r?\n/);
for (var i = 0; i < lines.length; i++) if(!lines[i].startsWith('//') && lines[i].length > 0) lines[i] = '//'+lines[i];
var oldCode = lines.join("\n");
this.editor.setValue(code + "\n\n"+oldCode+"\n");
}
CC.loadBoilerplate = function(){ this.editorSetCode_preserveOld(this.activeLevel.boilerPlateCode); };
CC.loadSampleSolution = function(){ this.editorSetCode_preserveOld(this.activeLevel.sampleSolution); };
CC.clearErrors = function (){ this.logText.text(''); };
CC.logError = function(s) {
var timeStamp = new Date().toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
CC.logText.text((CC.logText.text()+"\n["+timeStamp+"] "+s).trim());
CC.logText.scrollTop(CC.logText.prop("scrollHeight") - CC.logText.height());
};
function clearMonitor() {CC.variableInfo.text('');}
function monitor(name,val) {
if(typeof val == 'number') val = ""+round(val,4);
CC.variableInfo.text(CC.variableInfo.text()+name+" = "+val+"\n");
}
function showPopup(p) {
CC.popups.hide();
$(p).show();
if(p)CC.pause();
}
CC.gameLoop = (function() {
if(this.running()) {
clearMonitor();
try { this.activeLevel.simulate(0.02,controlFunction); }
catch(e) {
this.pause();
this.logError(e);
}
if(this.activeLevel.levelFailed())
this.pause();
if(this.activeLevel.levelComplete()) {
this.levelSolvedTime.text(round(this.activeLevel.getSimulationTime(),2));
showPopup('#levelCompletePopup');
}
this.variableInfo.text(this.variableInfo.text()+this.activeLevel.infoText());
}
this.activeLevel.draw(this.context,this.canvas);
if(this.running()) requestAnimationFrame(this.gameLoop);
else setTimeout( function() {requestAnimationFrame(CC.gameLoop);}, 200);
}).bind(CC);
CC.levels = {
TutorialBlockWithFriction: {constructor: Levels.TutorialBlockWithFriction, lineBreakAfter: false},
TutorialBlockWithoutFriction: {constructor: Levels.TutorialBlockWithoutFriction, lineBreakAfter: false},
TutorialBlockOnSlope: {constructor: Levels.TutorialBlockOnSlope, lineBreakAfter: true },
CruiseControlIntro: {constructor: Levels.CruiseControlIntro, lineBreakAfter: false},
CruiseControl2: {constructor: Levels.CruiseControl2, lineBreakAfter: true },
StabilizeSinglePendulum: {constructor: Levels.StabilizeSinglePendulum, lineBreakAfter: false},
SwingUpSinglePendulum: {constructor: Levels.SwingUpSinglePendulum, lineBreakAfter: false},
StabilizeDoublePendulum: {constructor: Levels.StabilizeDoublePendulum, lineBreakAfter: true },
RocketLandingNormal: {constructor: Levels.RocketLandingNormal, lineBreakAfter: false},
RocketLandingUpsideDown: {constructor: Levels.RocketLandingUpsideDown, lineBreakAfter: false},
RocketLandingMulti: {constructor: Levels.RocketLandingMulti, lineBreakAfter: false},
RocketLandingHoverslam: {constructor: Levels.RocketLandingHoverslam, lineBreakAfter: true },
VehicleSteeringSimple: {constructor: Levels.VehicleSteeringSimple, lineBreakAfter: false},
VehicleRacing: {constructor: Levels.VehicleRacing, lineBreakAfter: true },
MultirotorIntro: {constructor: Levels.MultirotorIntro, lineBreakAfter: false},
MultirotorObstacles: {constructor: Levels.MultirotorObstacles, lineBreakAfter: false},
MultirotorFlip: {constructor: Levels.MultirotorFlip, lineBreakAfter: false},
};
///////////////////// initialize ////////////////////////
// Cache DOM
CC.pauseButton = $('#pauseButton');
CC.playButton = $('#playButton');
CC.variableInfo = $('#variableInfo');
CC.popups = $('.popup');
CC.logText = $('#errorsBox pre');
CC.levelSolvedTime = $('#levelSolvedTime');
CC.variableInfo = $('#variableInfo');
CC.varInfoShowButton = $('#varInfoShowButton');
CC.varInfoHideButton = $('#varInfoHideButton');
CC.tipsButton = $('#tipsButton');
CC.boilerplateButton = $('#boilerplateButton');
CC.solutionButton = $('#solutionButton');
CC.levelmenuButton = $('#levelmenuButton');
CC.restartButton = $('#restartButton');
CC.errorsBoxUpButton = $('#errorsBoxUpButton');
CC.errorsBoxDownButton = $('#errorsBoxDownButton');
CC.shareButton = $('#shareButton');
CC.shareLink = $('#shareLink');
// button events
(function(){
function toggleVariableInfo() {
CC.variableInfo.toggle();
CC.varInfoShowButton.toggle();
CC.varInfoHideButton.toggle();
}
CC.varInfoShowButton.on('click', toggleVariableInfo.bind(CC));
CC.varInfoHideButton.on('click', toggleVariableInfo.bind(CC));
})();
(function () {
function makeErrorLogBig(){CC.errorsBoxUpButton.hide();CC.errorsBoxDownButton.show();$('.smallErrorBox').removeClass('smallErrorBox').addClass('bigErrorBox');}
function makeErrorLogSmall(){CC.errorsBoxUpButton.show();CC.errorsBoxDownButton.hide();$('.bigErrorBox').removeClass('bigErrorBox').addClass('smallErrorBox');}
makeErrorLogSmall();
CC.errorsBoxUpButton.on('click', makeErrorLogBig);
CC.errorsBoxDownButton.on('click', makeErrorLogSmall);
})();
CC.pauseButton.on('click', CC.pause.bind(CC));
CC.playButton.on('click', CC.play.bind(CC));
CC.tipsButton.on('click', function() {showPopup('#tipsPopup');});
CC.boilerplateButton.on('click', CC.loadBoilerplate.bind(CC));
CC.solutionButton.on('click', CC.loadSampleSolution.bind(CC));
CC.levelmenuButton.on('click', function() {showPopup('#levelMenuPopup');});
CC.restartButton.on('click', function() {if(CC.loadCodeAndReset()) CC.play();});
CC.shareButton.on('click', function() {showPopup('#sharePopup');CC.shareLink.val(CC.share_BLOB()).focus().select();});
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
$('#varInfoShowButton').hide();
if(CC.sharedCode === false){
CC.editor = CodeMirror.fromTextArea(document.getElementById("CodeMirrorEditor"), {lineNumbers: true, mode: "javascript", matchBrackets: true, lineWrapping:true});
CC.editor.on("change", function () {localStorage.setItem(CC.activeLevel.name+"Code", CC.editor.getValue());});
} else {
CC.editor = CodeMirror.fromTextArea(document.getElementById("CodeMirrorEditor"), {lineNumbers: true, mode: "javascript", matchBrackets: true, lineWrapping:true, readOnly: true});
}
shortcut.add("Alt+Enter",function() {if(CC.loadCodeAndReset())CC.play();}, {'type':'keydown','propagate':true,'target':document});
shortcut.add("Alt+P",function() {if(CC.running())CC.pause();else CC.play();}, {'type':'keydown','propagate':true,'target':document});
shortcut.add("Esc",function() {showPopup(null);}, {'type':'keydown','propagate':true,'target':document});
// popup close button
$('.popup').prepend($('<button type="button" class="btn btn-danger closeButton" onclick="showPopup(null);" data-toggle="tooltip" data-placement="bottom" title="Close [ESC]"><span class="glyphicon glyphicon-remove"> </span></button>'));
// level load buttons
for(var name in CC.levels) {
var level = new CC.levels[name].constructor();
var e = $('<button type="button" class="btn btn-primary" onclick="CC.loadLevel(\''+name+'\');">'+level.title+'</button>');
$('#levelList').append(e);
if(CC.levels[name].lineBreakAfter)
$('#levelList').append($('<br />'));
}
// make buttons pretty
$(document).ready(function() {$('[data-toggle="tooltip"]').tooltip();});
$('#buttons').cleanWhitespace();
$('.popup').cleanWhitespace();
$('button').attr('data-placement',"bottom");
$('button').attr('data-toggle',"tooltip");
$('button').each(function(index, element){if(element.className==='') element.className='btn btn-primary';});
CC.pause();
// normal mode
if(CC.sharedCode === false) {
try { CC.loadLevel(localStorage.getItem("lastLevel")); }
catch (e) { CC.logError(e); }
CC.loadCodeAndReset();
// show shared code
} else {
CC.boilerplateButton.remove();
CC.solutionButton.remove();
CC.levelmenuButton.remove();
CC.shareButton.remove();
$('.CodeMirror').css('background-color','#ddd');
try {
var share_params = JSON.parse(atob(CC.sharedCode));
CC.loadLevel(share_params.lvl_id);
CC.editor.setValue(share_params.code);
CC.loadCodeAndReset();
CC.play();
} catch (e) {
CC.logError("Error loading shared code.");
CC.logError(e);
}
showPopup(null);
}
CC.gameLoop(); |
import styled from 'styled-components';
const Container = styled.containter`
display: flex;
font-size: 12px;
padding: 10px 10px 0 0;
`
|
'use strict';
angular.module('eventmanagerApp')
.provider('AlertService', function () {
this.toast = false;
this.$get = ['$timeout', '$sce', '$translate', function($timeout, $sce,$translate) {
var exports = {
factory: factory,
isToast: isToast,
add: addAlert,
closeAlert: closeAlert,
closeAlertByIndex: closeAlertByIndex,
clear: clear,
get: get,
success: success,
error: error,
info: info,
warning : warning
},
toast = this.toast,
alertId = 0, // unique id for each alert. Starts from 0.
alerts = [],
timeout = 5000; // default timeout
function isToast() {
return toast;
}
function clear() {
alerts = [];
}
function get() {
return alerts;
}
function success(msg, params, position) {
return this.add({
type: "success",
msg: msg,
params: params,
timeout: timeout,
toast: toast,
position: position
});
}
function error(msg, params, position) {
return this.add({
type: "danger",
msg: msg,
params: params,
timeout: timeout,
toast: toast,
position: position
});
}
function warning(msg, params, position) {
return this.add({
type: "warning",
msg: msg,
params: params,
timeout: timeout,
toast: toast,
position: position
});
}
function info(msg, params, position) {
return this.add({
type: "info",
msg: msg,
params: params,
timeout: timeout,
toast: toast,
position: position
});
}
function factory(alertOptions) {
var alert = {
type: alertOptions.type,
msg: $sce.trustAsHtml(alertOptions.msg),
id: alertOptions.alertId,
timeout: alertOptions.timeout,
toast: alertOptions.toast,
position: alertOptions.position ? alertOptions.position : 'top right',
scoped: alertOptions.scoped,
close: function (alerts) {
return exports.closeAlert(this.id, alerts);
}
}
if(!alert.scoped) {
alerts.push(alert);
}
return alert;
}
function addAlert(alertOptions, extAlerts) {
alertOptions.alertId = alertId++;
alertOptions.msg = $translate.instant(alertOptions.msg, alertOptions.params);
var that = this;
var alert = this.factory(alertOptions);
if (alertOptions.timeout && alertOptions.timeout > 0) {
$timeout(function () {
that.closeAlert(alertOptions.alertId, extAlerts);
}, alertOptions.timeout);
}
return alert;
}
function closeAlert(id, extAlerts) {
var thisAlerts = extAlerts ? extAlerts : alerts;
return this.closeAlertByIndex(thisAlerts.map(function(e) { return e.id; }).indexOf(id), thisAlerts);
}
function closeAlertByIndex(index, thisAlerts) {
return thisAlerts.splice(index, 1);
}
return exports;
}];
this.showAsToast = function(isToast) {
this.toast = isToast;
};
});
|
var map;
var request;
var hasInit = false;
var markersArray = [];
google.maps.event.addDomListener(window, 'load', initialize);
//Generate map during initial map load
function initialize() {
if (!hasInit) {
var mapOptions = {
center: new google.maps.LatLng(40.714623,-74.006605 ),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
hasInit = true;
}
// Create the DIV to hold the control and call the ArticleControl() constructor
// passing in this DIV.
var articleControlDiv = document.createElement('div');
var articleControl = new ArticleControl(articleControlDiv, map);
articleControlDiv.index = 1;
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(articleControlDiv);
}
//The load article control will load article markers onto the map
function ArticleControl(controlDiv, map) {
// Set CSS styles for the DIV containing the control
// Setting padding to 5 px will offset the control
// from the edge of the map.
controlDiv.style.padding = '5px';
// Set CSS for the control border.
var controlUI = document.createElement('div');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Load articles when you click the button';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior.
var controlText = document.createElement('div');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '12px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.innerHTML = '<strong>Load Articles</strong>';
controlUI.appendChild(controlText);
// Setup the click event listeners: simply set the map to Chicago.
google.maps.event.addDomListener(controlUI, 'click', loadArticles);
}
// Adds marker to specfic lat lng
function addMarker(JSONObj) {
var myLatLng = (JSONObj.fields.lat && JSONObj.fields.lon) ? new google.maps.LatLng(JSONObj.fields.lat, JSONObj.fields.lon) : null;
if (myLatLng == null) {
console.log("Lat Lng for article was null. No marker made");
return;
}
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: JSONObj.headline,
url: JSONObj.fields.url
});
markersArray.push(marker);
var infowindow = new google.maps.InfoWindow({
content: JSONObj.fields.blurb
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.open(map,marker);
});
google.maps.event.addListener(marker, 'mouseout', function() {
infowindow.close();
});
google.maps.event.addListener(marker, 'click', function() {
window.open(this.url);
});
console.log("Plotting headline " + JSONObj.fields.headline + "at " + JSONObj.fields.lat + " " + JSONObj.fields.lon);
console.log("Plotting headline " + JSONObj.headline + "at " + JSONObj.lat + " " + JSONObj.lng);
}
// Passes in lat lng from center of map and returns relevant articles. We then build markers on the map.
function loadArticles() {
//clear map markers
clearMarkers();
//Get lat lng for center
var currentLatLng = map.getCenter();
var lat = currentLatLng.lat();
var lng = currentLatLng.lng();
//Get region radius
var bounds = map.getBounds();
var swPoint = bounds.getSouthWest();
var xOffset = Math.abs(swPoint.lng() - lng);
var yOffset = Math.abs(swPoint.lat() - lat);
//Retreive list of locations and stories from server
var JSONArr = getFromServer(lat, lng, xOffset, yOffset);
var JSONArrObj = JSON.parse(JSONArr);
//loop through relevant articles and get address
for(var i = 0; i < JSONArrObj.length; i++) {
addMarker(JSONArrObj[i]);
}
}
function clearMarkers() {
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
}
function getFromServer(lat, lng, xOffset, yOffset) {
var url = "/maploco/stories?lat=" + lat + "&long=" + lng + "&xoffset=" + xOffset + "&yoffset=" + yOffset;
console.log("getting from " + url);
createRequest();
request.open("GET", url, false);
request.send(null);
return request.responseText; // Will update this to be asynchronous
}
// Creates request based on browser used by user
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = null;
}
}
}
if (request == null) {
alert("Error creating XMLHttpRequest. Try switching browsers");
}
}
|
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'vendor/js/angular.js',
'vendor/js/angular-route.js',
'vendor/js/angular-animate.js',
'vendor/js/angular-mocks.js',
'app/app.module.js',
'app/*.js',
'app/**/*.html',
'test/*-spec.js'
],
reporters: ['mocha', 'coverage'],
preprocessors: {
'app/*.*.js': ['coverage'],
'app/partials/*.html': 'ng-html2js'
},
ngHtml2JsPreprocessor: {
moduleName: 'templates',
prependPrefix: '/'
},
coverageReporter: {
dir: '.',
reporters: [
{
type : 'lcovonly',
subdir: '.',
file: 'coverage.lcov'
}
]
},
plugins: [
'karma-jasmine',
'karma-coverage',
'karma-mocha-reporter',
'karma-phantomjs-launcher',
'karma-ng-html2js-preprocessor'
],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: true
});
};
|
require.config({
paths: {
"Namespace" : "external_libs/Namespace",
"jquery" : "external_libs/jquery-1.8.1.min",
"underscore": "external_libs/underscore-min",
"backbone" : "external_libs/backbone-min"
},
shim: {
'YourFramework': {
deps: ['backbone', 'jquery', 'Namespace']
},
'backbone': {
deps: ['jquery', 'underscore']
},
'DemoApp': {
deps: ['YourFramework']
}
}
});
require(["DemoApp"],
function() {
console.log('all libraries have been loaded.');
}
);
|
$(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 () {})
}
})
//auto change cover image
var count = 0;
var covers = ["url(https://cheaterhu.github.io/images/cover/bg-1.jpg)",
"url(https://cheaterhu.github.io/images/cover/bg-2.jpg)",
"url(https://cheaterhu.github.io/images/cover/bg-3.jpg)"];
var cover = $('.panel-cover ');
function changeCover(){
count++;
if (count > 2){ count = 0;}
var url = covers[count];
//alert(url)
cover[0].style.backgroundImage = url;
}
setInterval(changeCover,60*1000);
///////////////////
if (window.location.hash && window.location.hash == '#blog') {
$('.panel-cover').addClass('panel-cover--collapsed')
}
// if (window.location.pathname !== 'https://cheaterhu.github.io/' && window.location.pathname !== 'https://cheaterhu.github.io/index.html') {
// console.log(window.location.pathname + 'budengyu')
// $('.panel-cover').addClass('panel-cover--collapsed')
// }
// if (window.location.pathname == 'https://cheaterhu.github.io/' || window.location.pathname == 'https://cheaterhu.github.io/index.html') {
// console.log(window.location.pathname + 'dengyu')
// $('.panel-cover').removeClass('panel-cover--collapsed')
// }
if (window.location.href === 'https://cheaterhu.github.io/' || window.location.href === 'https://cheaterhu.github.io' || window.location.href === 'https://cheaterhu.github.io/index.html') {
$('.panel-cover').removeClass('panel-cover--collapsed')
} else {
$('.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')
})
})
|
// Ball Variables
var ballXmin = 150, // Ball Min X Position
ballXmax = 650, // Ball Max X Position
ballX = Math.floor(Math.random() * (ballXmax - ballXmin + 1)) + ballXmin; // Ball X Position
ballY = 150, // Ball Y Position
ballDXmin = -3; // Ball Min X Direction
ballDXmax = 3, // Ball Max X Direction
ballDX = Math.floor(Math.random() * (ballDXmax - ballDXmin + 1)) + ballDXmin; // Ball X Direction
ballDY = 6; // Ball Velocity
// Board Variables
var boardX = 800, // Board Width
boardY = 720; // Board Height
// Paddle Variables
var paddleX = 348, // Paddle Starting Position
paddleW = 120, // Paddle Width
paddleH = 10, // Paddle Height
paddleD = boardY - paddleH; // Paddle Depth
// Score Variables
var score = 0, // Player Score
highscore = 0; // Player Highscore
// Start Game
function drawGame() {
gameLoop = setInterval(drawBall, 16)
}
function drawBall() {
// Change Ball Position
ballX += ballDX
ballY += ballDY
ball.setAttribute("cx", ballX)
ball.setAttribute("cy", ballY)
// Bounce on Left or Right Edge
if (ballX + ballDX > boardX - 15 || ballX + ballDX < 15) {
ballDX = -ballDX
audio1.play()
}
// If Ball hits the Top, Bounce it
if (ballY + ballDY < 15) {
ballDY = -ballDY
audio1.play()
}
// If Ball hits the Bottom, Check if it hits the Paddle
else if (ballY + ballDY > boardY - 15) {
// If Ball hits the Paddle, Bounce it
if (ballX > paddleX && ballX < paddleX + paddleW) {
ballDY = -ballDY
ballDX = Math.floor(Math.random() * (ballDXmax - ballDXmin + 1)) + ballDXmin
audio2.play()
score = score += 1
drawScore()
drawHighscore()
}
// Otherwise Game Over
else {
lives = lives - 1
if (lives > -1) {
clearInterval(gameLoop)
ballDX = 0
ballX = 400
ballY = 150
paddleX = 348
document.getElementById("lives").innerHTML = lives
document.getElementById("paddle").setAttribute("x", 348)
document.getElementById("ball").setAttribute("cx", 348)
document.getElementById("ball").setAttribute("cy", 150)
drawGame()
} else {
clearInterval(gameLoop)
document.getElementById("loseHeader").innerHTML = "You lost! Press 'R' to try again."
}
}
}
}
// Score Counter
var goal = 50
var lives = 3
function drawScore() {
document.getElementById("score").innerHTML = score
if (score === 10) ballDY = 8
if (score === 20) ballDY = 10
if (score === 30) ballDY = 12
if (score === 40) ballDY = 14
if (score === 50) {
ballDY = 16
goal = 125
localStorage.setItem("chl0311", true)
document.getElementById("goal").innerHTML = goal
}
if (score === 60) ballDY = 18
if (score === 70) ballDY = 20
if (score === 80) ballDY = 22
if (score === 90) ballDY = 24
if (score === 100) ballDY = 26
if (score === 110) ballDY = 28
if (score === 120) ballDY = 30
if (score === 125) {
ballDY = 31
localStorage.setItem("chl0321", true)
document.getElementById("goal").style.color = "lightgreen"
}
}
// Highscore Counter
function drawHighscore() {
if (score > highscore) {
highscore = highscore += 1;
document.getElementById("highscore").innerHTML = highscore
}
}
// Game Restart
function Restart() {
// Stop Game
clearInterval(gameLoop)
// Reset Ball
ballXmin = 150
ballXmax = 650
ballX = Math.floor(Math.random() * (ballXmax - ballXmin + 1)) + ballXmin
ballY = 150
ballDXmin = -3
ballDXmax = 3
ballDX = Math.floor(Math.random() * (ballDXmax - ballDXmin + 1)) + ballDXmin
ballDY = 6
// Reset Paddle & Score
paddleX = 348
lives = 3
goal = 50
score = 0
// Reset Other Elements
document.getElementById("loseHeader").innerHTML = " "
document.getElementById("paddle").setAttribute("x", 348)
document.getElementById("lives").innerHTML = lives
document.getElementById("score").innerHTML = score
document.getElementById("goal").innerHTML = goal
document.getElementById("goal").style.color = "red"
// Start Game
drawGame()
}
// Audio Variables
var audio1 = new Audio('../../sound/impact_01.wav');
var audio2 = new Audio('../../sound/impact_02.wav');
// Game Mute
var mute = 1
function audioMute() {
mute += 1
if (mute % 2 === 0) {
document.getElementById("audio").innerHTML = "OFF"
audio1.muted = true
audio2.muted = true
} else {
document.getElementById("audio").innerHTML = "ON"
mute = 1
audio1.muted = false
audio2.muted = false
}
}
// Key Listener
function KeyboardController(keys, repeat) {
var timers = {};
document.onkeydown = function (event) {
var key = (event || window.event).keyCode;
if (!(key in keys))
return true;
if (!(key in timers)) {
timers[key] = null;
keys[key]();
if (repeat !== 0)
timers[key] = setInterval(keys[key], repeat);
}
return false;
};
document.onkeyup = function (event) {
var key = (event || window.event).keyCode;
if (key in timers) {
if (timers[key] !== null)
clearInterval(timers[key]);
delete timers[key]
}
};
window.onblur = function () {
for (key in timers)
if (timers[key] !== null)
clearInterval(timers[key]);
timers = {};
};
}
KeyboardController({
37: () => {
paddleX -= 2;
if (paddleX < 0) paddleX = 0;
paddle.setAttribute("x", paddleX);
},
39: () => {
paddleX += 2;
if (paddleX > boardX - paddleW) paddleX = boardX - paddleW;
paddle.setAttribute("x", paddleX);
},
82: () => {
Restart();
},
77: () => {
audioMute();
},
27: () => {
window.location.replace('../../index.html')
}
}, 1); |
import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
const getTitle = function(self) {
if (self.meta == null) {
return;
}
return self.meta.ogTitle || self.meta.twitterTitle || self.meta.title || self.meta.pageTitle;
};
Template.oembedVideoWidget.helpers({
url() {
if (this.meta && this.meta.twitterPlayerStream) {
return this.meta.twitterPlayerStream;
} else if (this.url) {
return this.url;
}
},
contentType() {
if (this.meta && this.meta.twitterPlayerStreamContentType) {
return this.meta.twitterPlayerStreamContentType;
} else if (this.headers && this.headers.contentType) {
return this.headers.contentType;
}
},
title() {
return getTitle(this);
},
collapsed() {
if (this.collapsed) {
return this.collapsed;
} else {
return RocketChat.getUserPreference(Meteor.userId(), 'collapseMediaByDefault') === true;
}
},
});
|
/**
* @module 布局容器[Container]
* @description 布局容器
*
* @date: 2013-11-07 下午1:36
*/
define(["core/js/CommonConstant",
"core/js/view/Layout",
"text!core/resources/tmpl/layout.html",
"core/js/base/AbstractView",
"core/js/utils/Utils",
"core/js/utils/ApplicationUtils"
], function ( CommonConstant,
Layout,
LayoutTemplate,
AbstractView,
Utils,
ApplicationUtils) {
var Container = Layout.extend(AbstractView).extend({
/**
* 布局模版
*/
template: LayoutTemplate,
/**
* 定义布局中的区域 ,必须为null,不然同时初始化多个对象会有问题
* 其中属性内容可以参考Region对象中的属性
* [
* {
* columnSize:"[栏位的大小]<可选>"
* region: "north",
* width: 200,
* height: 300,
* autoScroll: true, //设置当显示内容超出区域时是否要显示滚动条
* collapsible: true, //是否可收缩
* el: null, //此区域的元素
* flex: 1 //扣除已经指定了width或者height的区域,剩余的空间按各区域指定的flex进行分配
* }
* ]
*/
items: null,
/**
* 各区域间的间隔
*/
spacing: CommonConstant.Spacing.DEFAULT,
dataPre:"data",
/**
* 外边距
*/
margin: CommonConstant.Spacing.NONE,
/**
* 样式
*/
className: "container-fluid",
/**
* 布局调整后触发该事件
*/
onresize: null,
_registerEvent: false, //标识是否已经注册了事件
/**
* 存储可见视图的名称,用于仅显示某个区域,而隐藏其它区域时使用
*/
_visibleRegionNameArray: null,
/**
* 如果需要计算区域布局的,就需要添加该样式,基于绝对定位进行布局
*/
_defaultRegionClassName: null,
/**
* 已经渲染的子区域
*/
renderdRegion:null,
initialize: function (options, triggerEvent) {
this._firstRender = true;
//初始化本身属性信息
this.set(options, null);
this.initId();
//初始化的内容,需要close中清空
this.renderdRegion=[];
this.beforeInitializeHandle(options, triggerEvent);
this.initializeHandle(options, triggerEvent);
this.afterInitializeHandle(options, triggerEvent);
},
/**
* 初始化核心处理方法,由子类实现,主要是初始化数据,不包含渲染的内容
*/
initializeHandle:function(options,triggerEvent){
if (this.isDestroied) {
// a previously closed layout means we need to
// completely re-initialize the regions
this._initializeRegions();
}
if (this._firstRender) {
// if this is the first render, don't do anything to
// reset the regions
this._firstRender = false;
} else if (!this.isDestroied) {
// If this is not the first render call, then we need to
// re-initializing the `el` for each region
this._reInitializeRegions();
}
//初始化子区域信息
this.initItems();
//根据子区域信息初始化区域对象
this._initializeRegions();
},
/**
* DOM的渲染,初始化本身、挂载容器、初始化子区域
* 初始化过程:
* 1.初始化展示的页面内容
* 2.把要输出的区域初始化称Region对象
* @param triggerEvent
* @returns {Container}
*/
mountContent: function () {
//执行父类的渲染方法,容器的渲染,依赖区域的个数,所以,需要先初始化区域,还是继续渲染
this._super();
this.regionsRender();
},
/**
* 渲染区域的内容
*/
regionsRender:function(){
//父节点先渲染完后,子区域的才能渲染
//如果各区域有配置其内容的信息,那么就根据各区域内容的配置信息来渲染各区域的内容
// 容器是本组件渲染后,然后直接渲染区域的组件,而不是由渲染的事件来触发
var rName, region,
regions = this.getAllRegions();
if(regions){
//
this.childrenCount = _.keys(regions).length;
//设置parent的childrenCount也需要+1,因为是异步渲染
//如果父组件是Container,则不需要再+1
//如果有RegionParent则不需要+1,应为parent会根据Region的个数增加n
//如果没有Regionparent,则是非容器组件,则需要+1
if(this.getParent()&&!this.regionParent){
this.getParent().childrenCount++;
}
for (rName in regions) {
region = regions[rName];
region.render(); //根据区域的配置信息对区域进行渲染
this.renderdRegion.push(rName);
}
}
},
/**
* 根据区域id渲染区域对象
* @param regionId
*/
regionRender:function(regionId){
var region = this.getRegion(regionId);
if(region){
//直接包含内容的,不是region对象
region.render();
}
this.renderdRegion.push(regionId);
},
/**
* 初始化区域属性,此属性与Layout中的regions不一样,需要在进行转化
*/
initItems:function(){
if(this.items==null){
this.items = [];
}
},
/**
* 转换成是可以初始化化区域对象的属性对象
*/
_initializeRegions: function () {
var regions;
this._initRegionManager();
if (_.isFunction(this.regions)) {
regions = this.regions(this);
}else if(this.items!=null){
regions = this._getRegionsByItems(this.getItems()); //将items转换成regions
} else {
regions = this.regions || {};
}
this.addRegions(regions); //追加regions
//一个区域算一个子组件
//Todo处理异步线程渲染问题
},
/**
* 初始化容器的事件
*/
registerEvent:function(){
this.on("show", function () {
this.resizeLayout(); //计算各区域的布局
});
this.on("resize", function () {
this.resizeLayout(); //计算各区域的布局
});
//注册事件,页面渲染完后,计算各区域的布局
// this.on("render", function(){
// this.resizeLayout(); //计算各区域的布局
// });
},
/**
* 显示某个区域的内容
* @param regionName
* @param content
*/
showRegionContent: function (regionName, content) {
this.getRegion(regionName).show(content);
},
/**
* 向布局中动态追加区域
* @param items {Object|Array}待插入的区域项配置信息
* @return {*} 返回的是区域对象Region的数组
*/
appendItems: function (items) {
return this._insertItems(items, null, false, true);
},
/**
* 向布局中动态追加一个区域,并返回区域的对象
* @returns {*} 返回的是区域对象Region的对象
*/
appendItem:function(item){
var insertItems = this._insertItems([item], null, false, true);
if(insertItems!=null){
return insertItems[item.id];
}else{
return;
}
},
/**
* 向布局中指定的元素之前动态追加区域
* @param regionId {String|null}区域要插入到指定的元素的ID,为空的话,就添加到容器的最后
* @param items {Object|Array}待插入的区域项配置信息
* @return {*}
*/
insertItemsBefore: function (regionId, items) {
return this._insertItems(items, regionId, true, true);
},
/**
* 向布局中指定的元素之后动态追加区域
* @param regionId {String|null}区域要插入到指定的元素的ID,为空的话,就添加到容器的最后
* @param items {Object|Array}待插入的区域项配置信息
* @return {*}
*/
insertItemsAfter: function (regionId, items) {
return this._insertItems(items, regionId, false, true);
},
/**
* 还原原来容器中显示的区域
*/
restore: function () {
var visibleRegionNameArray = this._visibleRegionNameArray;
if (visibleRegionNameArray == null || visibleRegionNameArray.length == 0)
return;
this.showRegions(visibleRegionNameArray.join(","));
this._visibleRegionNameArray = null;
},
/**
* 最大化显示某个区域
* @param regionName
*/
maximizeRegion: function (regionName) {
var visibleRegionNameArray = this.initVisibleRegionNameArray(regionName);
this.hideRegions(visibleRegionNameArray.join(",")); //隐藏其它区域,使得指定的区域最大化
},
/**
* 初始化当前可见区域:排除掉参数中给定的区域名
* @param regionName
*/
initVisibleRegionNameArray: function (regionName) {
var rName, region,
regions = this.getAllRegions(),
result = [];
for (rName in regions) {
if (regionName == rName)
continue;
region = regions[rName];
if (!region.isVisible())
continue;
result.push(rName);
}
this._visibleRegionNameArray = result;
return result;
},
/**
* 根据给定的区域名来隐藏指定的区域
* @param regionNames {String}多个值用逗号分隔
*/
hideRegions: function (regionNames) {
this._setRegionsVisible(regionNames, false);
},
/**
* 根据给定的区域名来显示指定的区域
* @param regionNames {String}多个值用逗号分隔
*/
showRegions: function (regionNames) {
this._setRegionsVisible(regionNames, true);
},
setSpacing: function (spacing) {
this.spacing = spacing;
},
/**
* 覆写模版上下文的方法
* @override
* @return {{}}
*/
getTemplateContext: function () {
//如果指定了上下文data属性,那么就用指定的,没有就用系统默认的
var result = this._super();
if (result)
return result;
result = {regions: _.values(this.regions)};
return result;
},
/*------------------------------- 初始化及私有方法 ---------------------------------------------------*/
/**
* 向布局中动态添加区域
*
* @param items {Object|Array}待插入的区域项配置信息
* @param regionId {String|null}区域要插入到指定的元素的ID,为空的话,就添加到容器的最后
* @param isBefore {boolean|null}标识区域容器的内容是追加到指定元素之前还是之后
* @param triggerResizeLayout {boolean}是否要触发布局调整,默认是触发的
* @return {*}
* @private
*/
_insertItems: function (items, regionId, isBefore, triggerResizeLayout) {
this.items.push(items);
var regions = this._getRegionsByItems(items);
if (regions == null)
return null;
var regionObjs = this.insertRegions(regions, regionId, isBefore); //向区域的容器中追加新的区域
this._insertRegionContainer(regions, regionId, isBefore); //添加区域的容器
//触发布局调整
if (triggerResizeLayout == null || triggerResizeLayout)
this.resizeLayout();
return regionObjs;
},
/**
* 追加区域的容器
* @param regions {Object}待插入的区域配置信息
* @param regionId {String|null}区域要插入到指定的元素的ID,为空的话,就添加到容器的最后
* @param isBefore {boolean|null}标识区域容器的内容是追加到指定元素之前还是之后
* @private
*/
_insertRegionContainer: function (regions, regionId, isBefore) {
if (!regions || !this.$el)
return;
var context = {regions: _.values(regions)}
var regionContainer = _.template(this.template,{variable:this.dataPre})( context);
var $region = this.$el.find(["[id='", regionId, "']"].join(""));
if ($region.length == 0) {
this.$el.append(regionContainer);
return;
}
if (isBefore) {
$region.before(regionContainer);
} else
$region.after(regionContainer);
},
/**
* 设置指定区域的可见性
* @param regionNames {String}多个值用逗号分隔
* @param isVisible {boolean|null}是否可见
* @private
*/
_setRegionsVisible: function (regionNames, isVisible) {
regionNames = $.trim(regionNames);
if (regionNames === "")
return;
var regionNameArray = regionNames.split(","), region, i;
for (i = 0; i < regionNameArray.length; i++) {
region = this.getRegion(regionNameArray[i]);
region.setVisible(isVisible);
}
this.trigger("resize"); //触发重新计算布局(宽度、高度)的事件
},
_getRegionsByItems: function (items) {
if (items == null)
return null;
if ($.isPlainObject(items))
items = [items];
if (!$.isArray(items))
return null;
var i, region,
ln = items.length,
result = {};
for (i = 0; i < ln; i++) {
region = this._getRegionByItem(items[i]);
result[region.id] = region;
}
return result;
},
/**
* 根据item来生成region
* @param item
* @return {*}
*/
_getRegionByItem: function (item) {
var id = item["id"],
el = item["el"],
region = item["region"],
result = item;
if (!id || id === "") {
id = el && el.indexOf("#") == 0 ? el.substr(1) : null;
var preStr = region||"";
if(!id){
id = $.createId(preStr);
}
}
//此处不直接使用#id,是因为如果id是带有.的字符串(例如orderPanel.id_group)时,那么点后面的就被识别为className add by 2014.4.12
if (!el || el === "")
result["el"] = ["[id='", id, "']"].join("");
result["id"] = id;
/*var className = result["className"] || "";
className = this._defaultRegionClassName + className;*/
//this._defaultRegionClassName是容器默认的类型,item
this.initItemClassName(item,result);
//result["className"] =item.className||item.columnSize ||this._defaultRegionClassName;
return result;
},
/**
* 初始化子项的className,修改result中的className属性
* @param item 子项的配置信息
* @param result
*/
initItemClassName:function(item,result){
result["className"] =item.className||item.columnSize ||this._defaultRegionClassName;
},
/**
* 重新计算布局
*/
resizeLayout: function () {
var width = this.getWidth(),
height = this.getHeight();
this.calculateRegionLayout(width, height); //计算各区域的布局
},
/**
* 重置该容器的宽度和高度,并触发大小调整的事件
* @param width
* @param height
*/
resizeTo: function (width, height) {
//如果前后的宽度和高度一致,就不执行大小调整的动作 add by 2014.11.13
if(width == this.width && height == this.height)
return;
this.setWidth(width); //设置当前容器的宽度
this.setHeight(height); //设置当前容器的高度
this.trigger("resize"); //当容器布局调整后,触发该事件,使其重新计算各区域的布局
},
/**
* 计算各区域的布局
* @param width 容器的宽度
* @param height 容器的高度
*/
calculateRegionLayout: function (width, height) {
},
/**
* 初始化区域的布局
* @param region
* @param height
* @param width
* @param left
* @param top
* @param right
* @param bottom
*/
_initRegionLayout: function (region, height, width, left, top, right, bottom) {
if (region == null)
return;
region.ensureEl(); //先保证当前要显示区域的元素存在
region.setLeft(left);
region.setTop(top);
region.setRight(right);
region.setBottom(bottom);
region.resizeTo(width, height); //设置区域的宽度和高度,这里的高度、高度包含了补白padding和边框border
},
getItems: function () {
return this.items || [];
},
getRegionName: function (regionName) {
if(this.id)
return [this.id, regionName].join("-");
return regionName;
},
close:function(){
if (this.isDestroied) {
return;
}
this.items = null;
//this._firstRender = false;
this.renderdRegion = null;
ApplicationUtils.removeComponent(this.id);
this.unregisterEvent();
this._super();
}
});
Container.Region = Layout.Region;
Container.Spacing = CommonConstant.Spacing;
return Container;
}); |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const baseResource_1 = require("./baseResource");
/**
* Role
*
* @constructor Role
* @property {IConnector} connector the jira connector instance
*/
class Role extends baseResource_1.baseResource {
constructor(connector, Model, settings) {
super(connector, Model, settings);
/**
* Adds default actors to the given role. The request data should contain a list of usernames or a list of groups to add.
*
* @method addProjectRoleActorsToRole
* @memberOf Role#
* @param {Object} options An object containing options to pass to the Jira API.
* @param {string} options.id id
* @param {string} options.user user
* @param {string} options.group group
* @param {string} options.token token The token to use for authentication. This token is supplied on a sucessful login. If not supplied, the default token (if set) is used
* @param [callback] if supplied, called with result of api call
* @return {Promise.<any>} result of api call
*/
this.addProjectRoleActorsToRole = (...args) => {
if (args.length === 0) {
throw new Error("options must be passed");
}
let callback = ((typeof args[args.length - 1]) === 'function') ? args.pop() : null;
let options = ((typeof args[0]) === 'object') ? args[0] : {};
return this.makeRequest('addProjectRoleActorsToRole', 'POST', 'rest/api/2/role/:id/actors', options, callback);
};
/**
* Creates a new ProjectRole to be available in JIRA.
* The created role does not have any default actors assigned.
*
* @method createProjectRole
* @memberOf Role#
* @param {Object} options An object containing options to pass to the Jira API.
* @param {string} options.description description
* @param {string} options.name name
* @param {string} options.token token The token to use for authentication. This token is supplied on a sucessful login. If not supplied, the default token (if set) is used
* @param [callback] if supplied, called with result of api call
* @return {Promise.<any>} result of api call
*/
this.createProjectRole = (...args) => {
if (args.length === 0) {
throw new Error("options must be passed");
}
let callback = ((typeof args[args.length - 1]) === 'function') ? args.pop() : null;
let options = ((typeof args[0]) === 'object') ? args[0] : {};
return this.makeRequest('createProjectRole', 'POST', 'rest/api/2/role', options, callback);
};
/**
* Deletes a role. May return 403 in the futureif given, removes a role even if it is used in scheme by replacing the role with the given one
*
* @method deleteProjectRole
* @memberOf Role#
* @param {Object} options An object containing options to pass to the Jira API.
* @param {string} options.id id
* @param {string} options.swap swap if given, removes a role even if it is used in scheme by replacing the role with the given one
* @param {string} options.token token The token to use for authentication. This token is supplied on a sucessful login. If not supplied, the default token (if set) is used
* @param [callback] if supplied, called with result of api call
* @return {Promise.<any>} result of api call
*/
this.deleteProjectRole = (...args) => {
if (args.length === 0) {
throw new Error("options must be passed");
}
let callback = ((typeof args[args.length - 1]) === 'function') ? args.pop() : null;
let options = ((typeof args[0]) === 'object') ? args[0] : {};
return this.makeRequest('deleteProjectRole', 'DELETE', 'rest/api/2/role/:id', options, callback);
};
/**
* Removes default actor from the given role.if given, removes an actor from given roleif given, removes an actor from given role
*
* @method deleteProjectRoleActorsFromRole
* @memberOf Role#
* @param {Object} options An object containing options to pass to the Jira API.
* @param {string} options.id id
* @param {string} options.user user if given, removes an actor from given role
* @param {string} options.group group if given, removes an actor from given role
* @param {string} options.token token The token to use for authentication. This token is supplied on a sucessful login. If not supplied, the default token (if set) is used
* @param [callback] if supplied, called with result of api call
* @return {Promise.<any>} result of api call
*/
this.deleteProjectRoleActorsFromRole = (...args) => {
if (args.length === 0) {
throw new Error("options must be passed");
}
let callback = ((typeof args[args.length - 1]) === 'function') ? args.pop() : null;
let options = ((typeof args[0]) === 'object') ? args[0] : {};
return this.makeRequest('deleteProjectRoleActorsFromRole', 'DELETE', 'rest/api/2/role/:id/actors', options, callback);
};
/**
* Fully updates a roles. Both name and description must be given.
*
* @method fullyUpdateProjectRole
* @memberOf Role#
* @param {Object} options An object containing options to pass to the Jira API.
* @param {string} options.id id
* @param {string} options.description description
* @param {string} options.name name
* @param {string} options.token token The token to use for authentication. This token is supplied on a sucessful login. If not supplied, the default token (if set) is used
* @param [callback] if supplied, called with result of api call
* @return {Promise.<any>} result of api call
*/
this.fullyUpdateProjectRole = (...args) => {
if (args.length === 0) {
throw new Error("options must be passed");
}
let callback = ((typeof args[args.length - 1]) === 'function') ? args.pop() : null;
let options = ((typeof args[0]) === 'object') ? args[0] : {};
return this.makeRequest('fullyUpdateProjectRole', 'PUT', 'rest/api/2/role/:id', options, callback);
};
/**
* Gets default actors for the given role.
*
* @method getProjectRoleActorsForRole
* @memberOf Role#
* @param {Object} options An object containing options to pass to the Jira API.
* @param {string} options.id id
* @param {string} options.token token The token to use for authentication. This token is supplied on a sucessful login. If not supplied, the default token (if set) is used
* @param [callback] if supplied, called with result of api call
* @return {Promise.<any>} result of api call
*/
this.getProjectRoleActorsForRole = (...args) => {
if (args.length === 0) {
throw new Error("options must be passed");
}
let callback = ((typeof args[args.length - 1]) === 'function') ? args.pop() : null;
let options = ((typeof args[0]) === 'object') ? args[0] : {};
return this.makeRequest('getProjectRoleActorsForRole', 'GET', 'rest/api/2/role/:id/actors', options, callback);
};
/**
* Get all the ProjectRoles available in JIRA. Currently this list is global.
*
* @method getProjectRoles
* @memberOf Role#
* @param {Object} options An object containing options to pass to the Jira API.
* @param {string} options.token token The token to use for authentication. This token is supplied on a sucessful login. If not supplied, the default token (if set) is used
* @param [callback] if supplied, called with result of api call
* @return {Promise.<any>} result of api call
*/
this.getProjectRoles = (...args) => {
if (args.length === 0) {
throw new Error("options must be passed");
}
let callback = ((typeof args[args.length - 1]) === 'function') ? args.pop() : null;
let options = ((typeof args[0]) === 'object') ? args[0] : {};
return this.makeRequest('getProjectRoles', 'GET', 'rest/api/2/role', options, callback);
};
/**
* Get a specific ProjectRole available in JIRA.
*
* @method getProjectRolesById
* @memberOf Role#
* @param {Object} options An object containing options to pass to the Jira API.
* @param {string} options.id id
* @param {string} options.token token The token to use for authentication. This token is supplied on a sucessful login. If not supplied, the default token (if set) is used
* @param [callback] if supplied, called with result of api call
* @return {Promise.<any>} result of api call
*/
this.getProjectRolesById = (...args) => {
if (args.length === 0) {
throw new Error("options must be passed");
}
let callback = ((typeof args[args.length - 1]) === 'function') ? args.pop() : null;
let options = ((typeof args[0]) === 'object') ? args[0] : {};
return this.makeRequest('getProjectRolesById', 'GET', 'rest/api/2/role/:id', options, callback);
};
/**
* Partially updates a roles name or description.
*
* @method partialUpdateProjectRole
* @memberOf Role#
* @param {Object} options An object containing options to pass to the Jira API.
* @param {string} options.id id
* @param {string} options.description description
* @param {string} options.name name
* @param {string} options.token token The token to use for authentication. This token is supplied on a sucessful login. If not supplied, the default token (if set) is used
* @param [callback] if supplied, called with result of api call
* @return {Promise.<any>} result of api call
*/
this.partialUpdateProjectRole = (...args) => {
if (args.length === 0) {
throw new Error("options must be passed");
}
let callback = ((typeof args[args.length - 1]) === 'function') ? args.pop() : null;
let options = ((typeof args[0]) === 'object') ? args[0] : {};
return this.makeRequest('partialUpdateProjectRole', 'POST', 'rest/api/2/role/:id', options, callback);
};
this.methods = [];
this.register();
}
}
exports.Role = Role;
|
(function() {
'use strict';
var module = angular.module('core');
module.controller('wdTagChipsCtrl', function($scope,$q, Restangular,$log, $filter, wdCollections, wdTags) {
$log.debug("Init wdTagChipsCtrl")
$log.info("See whats in 'this'");
$log.info(this)
$log.info("See whats in '$scope'");
$log.info($scope)
var self = this;
self.tagSuggestions = function(name){
return wdTags.tagSuggestions(name);
}
self.someTags = []
// Adds new tags from list, is used as chip transform
self.tags = [];
self.newTag = function(name){
if (name.hasOwnProperty('name')) { return name }
var tags = wdTags.get_async(name).then(function(tags){
for (var i = 0; i < tags.length; i++) {
if (_.indexOf(self.tags,tags[i]) == -1){
self.tags.push(tags[i]);
}
}
});
return null
}
// Load more tags
self.nextCursor = ""
self.moreTags = true
self.moreTagsLoading = false
self.getSomeTags = function(){
self.moreTagsLoading = true
Restangular.all('tags').getList({count_greater:-1,size:10,cursor:self.nextCursor})
.then(function(tags) {
self.someTags = self.someTags.concat(tags)
self.nextCursor = tags.meta.nextCursor
self.moreTags = tags.meta.more
self.moreTagsLoading = false
});
}
self.getSomeTags();
self.addTags = function(){
wdTags.add_async(self.tags)
}
});
}());
|
'use strict';
import React from 'react';
import PlayerInfo from './PlayerInfo';
class Player extends React.Component {
constructor ( props ) {
super(props);
this.state = {};
}
render () {
return (
<div>
<h1>Player Name</h1>
<PlayerInfo/>
</div>
);
}
}
export default Player;
|
let law
module.exports = law = {
// Convenience method: wrap services in complete middleware stack
// accepts {serviceName: serviceDef}
// returns {serviceName: serviceDef} (wrapped)
create({services, jargon, policy, resolvers}) {
services = law.applyMiddleware(services, jargon)
services = law.applyPolicy(services, policy)
services = law.applyDependencies(services, resolvers)
return services
},
// loads services from the file system (assumed to be in separate files)
// accepts (serviceLocation)
// returns {serviceName: serviceDef}
load: require('./load'),
// processes service definitions into functions
// accepts (services, jargon)
// returns {serviceName: service}
applyMiddleware: require('./applyMiddleware'),
// wraps services with access/lookup policy
// accepts (services, policy)
// returns {serviceName: wrappedService}
applyPolicy: require('./applyPolicy'),
// looks up and requires dependencies according to
// the resolvers data structure.
// accepts (services, resolvers)
// returns {serviceName: wrappedService}
applyDependencies: require('./applyDependencies'),
// prints out the stack of filters applied to each service
// accepts (services)
// returns {serviceName: filterStack}
printFilters: require('./printFilters'),
// exposes the 'graph' submodule, which includes functions to
// take a set of services and return information about the graphs
// graphs induced by the various dependency types, especially
// the 'services' dependencyType.
graph: require('./graph'),
// Export 'errors' module for extensions to depend upon.
errors: require('./errors'),
}
|
/* eslint-env meteor, browser */
/* global Fetcher:true, Foursquare, Venues, Queries */
function getRadiusFromZoom(zoom) {
return Math.pow(2, 14 - zoom) * 1609.34 * 2; // the last "* 2" is a magic number for more results
}
Fetcher = {};
Fetcher.search = function(lat, lng, zoom, query) {
var radius = getRadiusFromZoom(zoom);
Queries.insert({
query: query,
lat: lat,
lng: lng,
radius: radius,
createdAt: new Date(),
owner: Meteor.userId()
});
Foursquare.find({
ll: '' + lat + ',' + lng,
radius: radius,
query: query,
limit: 50
}, function(err, result) {
if (err) return window.alert('failed to fetch venues [1]');
if (!result || !result.response || !result.response.venues) return window.alert('failed to fetch veneus [2]');
// better way to replace the whole collection?
Venues.find({}).fetch().forEach(function(item) {
Venues.remove(item._id);
});
result.response.venues.forEach(function(item) {
item.owner = Meteor.userId();
Venues.insert(item);
});
});
};
|
import {ActionTypes} from '@constants/';
export function showNotification(dispatch, message) {
dispatch({ type: ActionTypes.SHOW_NOTIFICATION , message });
}
|
/**
* @author Alex Acevedo
*/
//A Test Torrent
//magnet:?xt=urn:btih:d266b48a9e61435bd6f044f0a11bc12b6fc56f1d&dn=Nerf+Gun&tr=udp%3A%2F%2Ftracker.openbittorrent.com%3A80&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ftracker.istole.it%3A6969&tr=udp%3A%2F%2Ftracker.ccc.de%3A80&tr=udp%3A%2F%2Fopen.demonii.com%3A1337
var map = L.map('map').setView([0, 0], 2);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
maxZoom: 18
}).addTo(map);
markers = new L.FeatureGroup();
var btapp = new Btapp();
btapp.connect();
function removeTorrent(thisId) {
btapp.get('torrent').get(thisId).remove();
};
function submitTorrent(){
//var grabURI = document.getElementById('inputMagnet').value;
//alert(grabURI);
btapp.live('add', function(add) {
var grabURI = document.getElementById('inputMagnet').value;
add.torrent(grabURI);
});
};
function torrentInfo() {
$("#listEm tr").remove();
$('#listEm').append('<tr><td>Torrent Name</td><td>Percent Complete</td><td>Seed Count</td><td>Peer Count</td><td>Remove Torrent</td></tr>');
btapp.get('torrent').each(function(torrent) {
var torrentName = torrent.get('properties').get('name');
var torrentLink = torrent.get('properties').get('uri');
var torrentHash = torrent.get('properties').get('hash');
var seedNumber = torrent.get('properties').get('seeds_connected');
var peerNumber = torrent.get('properties').get('peers_connected');
var percentComplete = torrent.get('properties').get('progress')/10;
torrent.get('peer').each(function(peer) {
});
$('#listEm').append('<tr><td><a href="' + torrentLink + '">' + torrentName + '</a></td><td>' + percentComplete + '</td><td>' + seedNumber + '</td><td>' + peerNumber + '</td></td><td><button id="'+ torrentHash +'" onclick="removeTorrent(this.id)">Remove</button></td></tr>');
});
};
setInterval(function() {torrentInfo();}, 1000);
function seedMap() {
btapp.get('torrent').each(function(torrent) {
map.removeLayer(markers);
var torrentName = torrent.get('properties').get('name');
var torrentHash = torrent.get('properties').get('hash');
torrent.get('peer').each(function(peer) {
var ip = peer.get('properties').get('ip');
var peerClient = peer.get('properties').get('client');
$.ajax({url: 'http://www.telize.com/geoip/' + ip,
dataType: 'jsonp',
success: function(data) {
var lat = data.latitude;
var lon = data.longitude;
var city = data.city;
var region = data.region;
var country = data.country;
var marker = new L.marker([lat, lon]).addTo(markers)
.bindPopup('<p>I.P. Address: ' + ip + '</p><p>Location: ' + city + ', ' + region + ', ' + country + '</p><p>Client: ' + peerClient + '</p>');
map.addLayer(markers);
},
error: function() {
console.log('Failed to locate I.P. address. Bad JSON call.');
}
});
});
});
$.ajax({url: 'http://www.telize.com/geoip/',
dataType: 'jsonp',
success: function(data) {
var ip = data.ip;
var lat = data.latitude;
var lon = data.longitude;
var city = data.city;
var region = data.region;
var country = data.country;
btapp.live('settings' , function(settings) {
var yourClient = settings.get('clientname');
var marker = new L.marker([lat, lon]).addTo(markers)
.bindPopup('<p><b>You</b></p><p>I.P. Address: ' + ip + '</p><p>Location: ' + city + ', ' + region + ', ' + country + '</p><p>Client: ' + yourClient + '</p>');
map.addLayer(markers);
});
},
error: function() {
console.log('Failed to locate I.P. address. Bad JSON call.');
}
});
};
//Another Test Torrent:
//http://www.legittorrents.info/download.php?id=8fa84aae7a629b6346c1a881ce5fda929e0fd9ad&f=Pixelhive%20-%2014th%20April%202013%20-%20Best%20Minecraft%20Creations.torrent |
angular.module('mySite', ['ui.bootstrap', 'ui.utils', 'ui.router', 'ngAnimate', 'youtube-embed', 'home', 'about', 'contact', 'projects']);
angular.module('mySite').config(function($stateProvider, $urlRouterProvider) {
/* Add New States Above */
$urlRouterProvider.otherwise('/home');
});
angular.module('mySite').run(function($rootScope) {
$rootScope.safeApply = function(fn) {
var phase = $rootScope.$$phase;
if (phase === '$apply' || phase === '$digest') {
if (fn && (typeof(fn) === 'function')) {
fn();
}
} else {
this.$apply(fn);
}
};
$rootScope.$on('$stateChangeSuccess',function(event, current, previous){
$("html, body").animate({ scrollTop: 0 }, 0);
return $rootScope.pageTitle = current.data.pageTitle;
});
});
angular.module('mySite').controller('AppCtrl',function($scope, $window){
$scope.atTop = true;
$scope.nav = [
{route: "home", name: "Home"},
{route: "about", name: "About"},
{route: "projects", name: "Portfolio"},
{route: "contact", name: "Contact"},
];
$scope.socialLinks = {
facebook: "https://www.facebook.com/ryan.milstead.7",
twitter: "https://twitter.com/ryanmilstead",
email: "mailto:ryanmilstead1@gmail.com",
linkedin: "https://www.linkedin.com/in/ryanmilstead",
github: "https://github.com/RyanMilstead1",
youtube: "https://www.youtube.com/user/viperguy4123",
};
});
angular.module('mySite').directive("scroll", function ($window) {
return function(scope, element, attrs) {
angular.element($window).bind("scroll", function() {
if (this.pageYOffset >= 50) {
scope.atTop = false;
} else {
scope.atTop = true;
}
scope.$apply();
});
};
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:2e39f067c84ed9830e617b93ad24043ace31dc1bdcc8ff18413fa8d9771c6207
size 2904
|
version https://git-lfs.github.com/spec/v1
oid sha256:b953defcf9a84460e5beeb4ce8cdbe97d9c68f0356d7fb81b0aceb52f811d1ea
size 1135
|
import fetchMock from 'fetch-mock';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import {
authenticate,
logout,
setAuthenticating,
setPassword,
} from './session';
const mockStore = configureMockStore([thunk]);
const password = 'password';
test('setAuthenticating dispatches SET_AUTHENTICATING action', () => {
expect(setAuthenticating(true)).toEqual({
type: 'SET_AUTHENTICATING',
authenticating: true,
});
});
test('setPassword dispatches SET_PASSWORD action', () => {
expect(setPassword('password')).toEqual({
type: 'SET_PASSWORD',
password,
});
});
test('logout dispatches actions to clear the session', () => {
const expectedActions = [
{ type: 'SET_AUTHENTICATED', authenticated: false },
{ type: 'SET_PASSWORD', password: '' },
];
const store = mockStore({ session: { authenticated: true, password: 'password' } });
store.dispatch(logout());
expect(store.getActions()).toEqual(expectedActions);
});
describe('authenticate', () => {
afterEach(() => {
fetchMock.restore();
});
it('authenticates for the given password and dispatches a success event', () => {
fetchMock.postOnce({
matcher: (url, opts) => {
return (
url === '/session/validate' &&
opts && opts.body && JSON.parse(opts.body).password === password
)
},
headers: { 'accept': 'application/json', 'content-type': 'application/json' },
response: {},
});
const expectedActions = [
{ type: 'AUTHENTICATE_REQUEST' },
{ type: 'AUTHENTICATE_SUCCESS', password },
];
const store = mockStore({ session: { authenticating: true } });
return store.dispatch(authenticate('password')).then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
it('dispatches a failure event on unsuccessful response', () => {
fetchMock.postOnce({
matcher: '/session/validate',
headers: { 'accept': 'application/json', 'content-type': 'application/json' },
response: { status: 401 },
});
const err = new Error('Failed');
const expectedActions = [
{ type: 'AUTHENTICATE_REQUEST' },
{ type: 'AUTHENTICATE_FAILURE', password, err },
];
const store = mockStore({ session: { authenticating: true } });
return store.dispatch(authenticate('password')).then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
it('dispatches a failure event on request failure', () => {
const err = new Error('request failure');
fetchMock.getOnce({
matcher: '/session/validate',
headers: { 'accept': 'application/json', 'content-type': 'application/json' },
response: { throws: err },
});
const expectedActions = [
{ type: 'AUTHENTICATE_REQUEST' },
{ type: 'AUTHENTICATE_FAILURE', password, err },
];
const store = mockStore({ session: { authenticating: true } });
return store.dispatch(authenticate('password')).then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
});
|
'use strict';
const Config = require('./config');
const Shouts = require('./shouts');
const NodeBB = require('./nodebb');
const Sockets = module.exports;
Sockets.events = {
get: getShouts,
send: sendShout,
edit: editShout,
getPlain: getPlainShout,
remove: removeShout,
removeAll: removeAllShouts,
startTyping: startTyping,
stopTyping: stopTyping,
getSettings: Config.user.sockets.getSettings,
saveSetting: Config.user.sockets.saveSettings,
};
async function getShouts(socket, data) {
const shoutLimit = parseInt(Config.global.get('limits.shoutLimit'), 10);
const guestsAllowed = Boolean(Config.global.get('toggles.guestsAllowed'));
let start = (-shoutLimit);
let end = -1;
if (data && data.start) {
const parsedStart = parseInt(data.start, 10);
if (!isNaN(parsedStart)) {
start = parsedStart;
end = start + shoutLimit;
}
}
if (socket.uid <= 0 && !guestsAllowed) {
return [];
}
return await Shouts.getShouts(start, end);
}
async function sendShout(socket, data) {
if (!socket.uid || !data || !data.message || !data.message.length) {
throw new Error('[[error:invalid-data]]');
}
const msg = NodeBB.utils.stripHTMLTags(data.message, NodeBB.utils.stripTags);
if (msg.length) {
const shout = await Shouts.addShout(socket.uid, msg);
emitEvent('event:shoutbox.receive', shout);
return true;
}
}
async function editShout(socket, data) {
if (!socket.uid || !data || !data.sid || isNaN(parseInt(data.sid, 10)) || !data.edited || !data.edited.length) {
throw new Error('[[error:invalid-data]]');
}
const msg = NodeBB.utils.stripHTMLTags(data.edited, NodeBB.utils.stripTags);
if (msg.length) {
const result = await Shouts.editShout(data.sid, msg, socket.uid);
emitEvent('event:shoutbox.edit', result);
return true;
}
}
async function getPlainShout(socket, data) {
if (!socket.uid || !data || !data.sid || isNaN(parseInt(data.sid, 10))) {
throw new Error('[[error:invalid-data]]');
}
return await Shouts.getPlainShouts([data.sid]);
}
async function removeShout(socket, data) {
if (!socket.uid || !data || !data.sid || isNaN(parseInt(data.sid, 10))) {
throw new Error('[[error:invalid-data]]');
}
const result = await Shouts.removeShout(data.sid, socket.uid);
if (result === true) {
emitEvent('event:shoutbox.delete', { sid: data.sid });
}
return result;
}
async function removeAllShouts(socket, data) {
if (!socket.uid || !data || !data.which || !data.which.length) {
throw new Error('[[error:invalid-data]]');
}
if (data.which === 'all') {
return await Shouts.removeAll(socket.uid);
} else if (data.which === 'deleted') {
return await Shouts.pruneDeleted(socket.uid);
}
throw new Error('invalid-data');
}
function startTyping(socket, data, callback) {
if (!socket.uid) return callback(new Error('invalid-data'));
notifyStartTyping(socket.uid);
if (socket.listeners('disconnect').length === 0) {
socket.on('disconnect', () => {
notifyStopTyping(socket.uid);
});
}
callback();
}
function stopTyping(socket, data, callback) {
if (!socket.uid) return callback(new Error('invalid-data'));
notifyStopTyping(socket.uid);
callback();
}
function notifyStartTyping(uid) {
emitEvent('event:shoutbox.startTyping', { uid: uid });
}
function notifyStopTyping(uid) {
emitEvent('event:shoutbox.stopTyping', { uid: uid });
}
function emitEvent(event, data) {
NodeBB.SocketIndex.server.sockets.emit(event, data);
}
|
var API_SERVER = "/api/franz/";
var API_LIST = {
residence: "bank:model:residence",
credit_card_count: "bank:model:credit_card_count",
age_hist: "bank:model:age_hist",
avg_saving_all_time: "bank:model:avg_saving_all_time",
year_savings: "bank:model:year_savings",
years_registered: "bank:model:years_registered",
gender: "bank:model:gender",
deposit_withdraw: "bank:model:deposit_withdraw",
credit_card_consume: "bank:model:credit_card_consume",
investment: "bank:model:investment",
fund: "bank:model:fund",
credit_card_activate: "bank:model:credit_card_activate"
}; |
import React from 'react';
import PropTypes from 'prop-types';
const Bookmark = (props) => {
const color = props.color == 'inherit' ? undefined : props.color;
const aria = props.title ? 'svg-bookmark-title' : '' +
props.title && props.description ? ' ' : '' +
props.description ? 'svg-bookmark-desc' : '';
return (
<svg width={props.width} height={props.height} viewBox='0 0 24 24'
xmlns='http://www.w3.org/2000/svg' role='img'
aria-labelledby={aria}
>
{!props.title ? null :
<title id='svg-bookmark-title'>{props.title}</title>
}
{!props.description ? null :
<desc id='svg-bookmark-desc'>{props.description}</desc>
}
<path fill={color} d="M17 3H7c-1.1 0-1.99.9-1.99 2L5 21l7-3 7 3V5c0-1.1-.9-2-2-2z"/>
</svg>
);
};
Bookmark.defaultProps = {
color: 'inherit',
width: undefined,
height: undefined,
title: '',
description: ''
};
Bookmark.propTypes = {
color: PropTypes.string,
width: PropTypes.string,
height: PropTypes.string,
title: PropTypes.string,
description: PropTypes.string
};
export default Bookmark;
|
var vows = require('vows'),
assert = require('assert');
/*
* Don't require d3 in a var declaration so the name is available to
* d3-transform. This makes it global, which should probably be avoided but
* ???
*/
d3 = require('d3');
var transform = require("../src/d3-transform.js");
vows.describe('d3-transform').addBatch({
'the initial object' : {
topic : function() {
return d3.svg.transform();
},
'is an identity transform' : function(topic) {
assert.equal(topic(), "");
}
},
'calling translate' : {
'works for one argument' : function() {
var transform = d3.svg.transform()
.translate(1);
assert.equal(transform(), 'translate(1)');
},
'works for two arguments' : function() {
var transform = d3.svg.transform()
.translate(1, 2);
assert.equal(transform(), 'translate(1,2)');
},
'works for a function argument' : function() {
var transform = d3.svg.transform()
.translate(function() { return [3, 5]; });
assert.equal(transform(), 'translate(3,5)');
},
'works for a function argument, given arguments' : function() {
var transform = d3.svg.transform()
.translate(function(x) { return [x, 13]; });
assert.equal(transform(8), 'translate(8,13)');
},
'works for a function argument, as a method' : function() {
var transform = d3.svg.transform()
.translate(function() { return [this.x, 34]; });
var cxt = { 'x' : 21 };
assert.equal(transform.call(cxt), 'translate(21,34)');
}
},
'composing transforms' : {
'works' : function() {
var transform = d3.svg.transform()
.translate(1, 1)
.rotate(2);
assert.equal(transform(), 'translate(1,1) rotate(2)');
}
},
'composing multiple transform objects' : {
'works' : function() {
var t1 = d3.svg.transform()
.translate(1,1)
.rotate(2)
var t2 = d3.svg
.transform(t1)
.scale(3,3);
assert.equal(t2(),"translate(1,1) rotate(2) scale(3,3)");
},
'works with functions at any point' : function() {
var t1 = d3.svg.transform()
.translate(function(d) { return [d,1];})
.rotate(2)
var t2 = d3.svg
.transform(t1)
.scale(function(d) { return [d+1,4];});
assert.equal(t2(10),"translate(10,1) rotate(2) scale(11,4)");
}
}
}).export(module);
|
Ext.define('Ueaac.view.Navigation', {
extend: 'Ext.Container',
alias: 'widget.navigation',
initComponent: function () {
this.layout = {
type: 'vbox',
align: 'stretch',
pack: 'start'
};
this.items = [{
xtype: 'button',
flex: 1,
maxHeight: 35,
text: 'UEAAC域',
menu: {
xtype: 'menu',
width: 170,
items: [{
xtype: 'menuitem',
text: 'UEAAC'
},'-',{
xtype: 'menuitem',
text: '智能家居'
},{
xtype: 'menuitem',
text: 'MRP'
},'-',{
xtype: 'menuitem',
text: '管理'
}]
}
},{
xtype: 'tabpanel',
flex: 1,
activeTab: 0,
items: [{
xtype: 'buttongroup',
title: '配置',
layout: 'vbox',
defaults: {
flex: 1,
maxHeight: 35,
width: '100%'
},
items: [{
text: '组织架构'
},{
text: '角色'
},{
text: '用户'
},{
text: '资源'
}]
},{
xtype: 'panel',
title: '授权'
},{
xtype: 'panel',
title: '系统'
}]
}];
this.callParent();
}
}); |
/** @jsx React.DOM */
var apiKey = 'AIzaSyB0ydxHAKRpkuaKbIMRtt12XvuYjtMd2sA';
var TravellogMap = React.createClass({
render: function(){
var places = this.props.places;
if (!places || places.length < 2){
return <div></div>;
}
var origin = places.shift(),
destination = places.pop(),
waypoints = places.join('|');
var string = 'origin=' + origin + '&destination=' + destination + '&waypoints=' + waypoints;
var createItem = function() {
return <iframe
width="600"
height="450"
frameBorder="0"
src = {'https://www.google.com/maps/embed/v1/directions?' + string + '&key=' + apiKey}>
</iframe>
};
return <div>{ createItem() }</div>;
}
});
|
//---------------------------------------------------------------------------
// Agent-Admin protocol
// Attempt at event-based distributed processes
//---------------------------------------------------------------------------
"use strict";
(function() {
//-------------
// Dependencies
//-------------
var restify = require("restify");
// var async = require("async");
var _ = require("underscore");
//----------------------------
// Hidden (internal) functions
//----------------------------
//-------------------
// Protocol object
//-------------------
// Constructor. Initializes/Loads resources asynchronously
var Protocol = function(config, agentState, adminState) {
this.config = config;
this.agentState = agentState;
this.adminState = adminState;
// Subscribe to events from adminState
this.adminState.on("add", function onAdd(resource) {
if (resource.resourceType === "agent") {
this.handleAgentCreated(resource.agent);
}
else if (resource.resourceType === "transfer") {
this.handleTransferCreated(resource.transfer);
}
}.bind(this));
this.adminState.on("update", function onUpdate(resource, old) {
if (resource.resourceType === "agent") {
this.handleAgentUpdated(resource.agent, old);
}
else if (resource.resourceType === "transfer") {
this.handleTransferUpdated(resource.transfer, old);
}
}.bind(this));
this.adminState.on("delete", function onDelete(resource, old) {
if (resource.resourceType === "agent") {
this.handleAgentDeleted(old);
}
else if (resource.resourceType === "transfer") {
this.handleTransferDeleted(old);
}
}.bind(this));
};
//----------------------------
// Event handlers
//----------------------------
// Trigger: agent has started
// Action: Find our own id from adminState
// Action: Trigger handleAgentHandshake
Protocol.prototype.handleAgentStarted = function() {
console.log("handleAgentStarted");
this.adminState.agent.findResources(function matchOurself(agent) {
return this.config.host === agent.host && this.config.port === agent.port;
}.bind(this), function matchedOrNot(err, result) {
if (! err && result && result.length > 0) {
this.config.id = result[0].id;
this.config.version = result[0].version;
if (this.config.name !== result[0].name) {
console.log("WARN: Agent found itself in adminState, but with different name (" +
this.config.name + " != " + result[0].name + ")");
}
}
this.handleAgentHandshake();
}.bind(this));
};
// Trigger: on agent startup
// Action: If id exists - notify admin with agent.status = RUNNING
// Action: If id doesn't exists - notify admin with new agent
Protocol.prototype.handleAgentHandshake = function() {
console.log("handleAgentHandshake");
if (this.config.id) {
this.handleNotifyAdminAboutAgent();
}
else {
this.handleAgentDoesntExist();
}
};
// Trigger: Agent startup
// Action: Notify admin with agent status
Protocol.prototype.handleNotifyAdminAboutAgent = function() {
console.log("handleNotifyAdminAboutAgent");
var adminClient = restify.createJsonClient({
url: "http://" + this.config.adminHost + ":" + this.config.adminPort,
version: "*"
});
adminClient.put("/rest/v1/agents/" + this.config.id, {
id: this.config.id,
version: this.config.version,
state: "RUNNING"
}, function onResponse(err) {
if (! err) {
console.log("Notified admin about running state successfully");
}
else {
this.handleUnrecoverableError("Failed to notify admin about running state");
}
}.bind(this));
};
// Trigger: Admin doesn't know about me
// Action: Notify admin with new agent
Protocol.prototype.handleAgentDoesntExist = function() {
console.log("handleAgentDoesntExist");
var adminClient = restify.createJsonClient({
url: "http://" + this.config.adminHost + ":" + this.config.adminPort,
version: "*"
});
adminClient.post("/rest/v1/agents", {
name: this.config.name,
host: this.config.host,
port: this.config.port,
inboundDir: this.config.inboundDir,
outboundDir: this.config.outboundDir,
state: "RUNNING"
}, function onResponse(err, req, res, obj) {
if (! err) {
// Update our adminState with ourself
var adminAgent = obj.agent;
this.adminState.agent.addResource(adminAgent);
// Update our config with id and version and persist it
this.config.id = adminAgent.id;
this.config.version = adminAgent.version;
console.log("Registered agent successfully with administrator");
}
else {
this.handleUnrecoverableError("Failed to register agent with administrator");
}
}.bind(this));
};
// Trigger: A agent has been created on admin
// Action: ToDo
Protocol.prototype.handleAgentCreated = function(agent) {
console.log("handleAgentCreated (agentId: " + agent.id + ")");
// Not implemented
};
// Trigger: A agent has been updated on admin
// Action: ToDo
Protocol.prototype.handleAgentUpdated = function(agent) {
console.log("handleAgentUpdated (agentId: " + agent.id + ")");
// Not implemented
};
// Trigger: A agent has been deleted from admin
// Action: ToDo
Protocol.prototype.handleAgentDeleted = function(agent) {
console.log("handleAgentDeleted (agentId: " + agent.id + ")");
// Not implemented
};
// Trigger: A transfer has been created on admin
// Action: Verify (and possible fetch) that we know of the relevant agents
Protocol.prototype.handleTransferCreated = function(transfer) {
console.log("handleTransferCreated (transferId: " + transfer.id + ")");
this.handleFetchTransferAgents(transfer);
// ToDo: act on transfer...
};
// Trigger: A transfer has been updated on admin
// Action: Verify (and possible fetch) that we know of the relevant agents
Protocol.prototype.handleTransferUpdated = function(transfer) {
console.log("handleTransferUpdated (transferId: " + transfer.id + ")");
this.handleFetchTransferAgents(transfer);
// ToDo: act on transfer...
};
// Trigger: A transfer has been deleted from admin
// Action: ToDo
Protocol.prototype.handleTransferDeleted = function(transfer) {
console.log("handleTransferDeleted (transferId: " + transfer.id + ")");
// Not implemented
// ToDo: act on transfer...
};
// Trigger: A transfer has been modified
// Action: Verify (and possible fetch) that we know of the relevant agents
Protocol.prototype.handleFetchTransferAgents = function(transfer) {
console.log("handleFetchTransferAgents (transferId: " + transfer.id + ")");
// Get array of agent ids
var agentIds = _.uniq(_.union(
_.map(transfer.sources, function getAgentId(source) { return source.agentId; }),
_.map(transfer.targets, function getAgentId(target) { return target.agentId; })
));
// Get agents from state (the ones we have)
this.adminState.agent.findResources(function matchAgents(agent) {
return _.some(agentIds, function match(id) {
return agent.id === id;
});
}, function agentsThatWeHave(err, agents) {
if (! err) {
// Now, lets find out which ones we don't have knowledge about
_.each(agentIds, function inAgentIds(agentId) {
if (!_.find(agents, function inAgents(agent) { return agent.id === agentId; })) {
this.handleFetchAgent(agentId);
}
}.bind(this));
}
else {
console.log("handleFetchTransferAgents ERROR: Couldn't find matching agents");
console.log(err);
}
}.bind(this));
};
// Trigger: A transfer has been modified and an agent is currently not known
// Action: Get an agent from admin
Protocol.prototype.handleFetchAgent = function(agentId) {
console.log("handleFetchAgent (agentId: " + agentId + ")");
var adminClient = restify.createJsonClient({
url: "http://" + this.config.adminHost + ":" + this.config.adminPort,
version: "*"
});
adminClient.get("/rest/v1/agents/" + agentId, function onResponse(err, req, res, obj) {
if (! err) {
// Yeay, we got the agent, now let's store it internally
this.adminState.agent.addResource(obj.agent);
console.log("Fetched agent " + agentId + " successfully");
}
else {
console.log("Failed to fetch agent " + agentId);
console.log(err);
}
}.bind(this));
};
// Trigger: An unrecoverable error occurred
// Action: We should crash, but for now, lets just log it
Protocol.prototype.handleUnrecoverableError = function(message) {
console.log("handleUnrecoverableError: " + message);
};
//---------------
// Module exports
//---------------
module.exports.create = function(config, agentState, adminState) {
return new Protocol(config, agentState, adminState);
};
}()); |
ml.module('three.core.Vector3')
.requires('three.Three')
.defines(function(){
/**
* @author mrdoob / http://mrdoob.com/
* @author kile / http://kile.stravaganza.org/
* @author philogb / http://blog.thejit.org/
* @author mikael emtinger / http://gomo.se/
* @author egraether / http://egraether.com/
* @author WestLangley / http://github.com/WestLangley
*/
THREE.Vector3 = function ( x, y, z ) {
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
};
THREE.Vector3.prototype = {
constructor: THREE.Vector3,
set: function ( x, y, z ) {
this.x = x;
this.y = y;
this.z = z;
return this;
},
setX: function ( x ) {
this.x = x;
return this;
},
setY: function ( y ) {
this.y = y;
return this;
},
setZ: function ( z ) {
this.z = z;
return this;
},
copy: function ( v ) {
this.x = v.x;
this.y = v.y;
this.z = v.z;
return this;
},
add: function ( a, b ) {
this.x = a.x + b.x;
this.y = a.y + b.y;
this.z = a.z + b.z;
return this;
},
addSelf: function ( v ) {
this.x += v.x;
this.y += v.y;
this.z += v.z;
return this;
},
addScalar: function ( s ) {
this.x += s;
this.y += s;
this.z += s;
return this;
},
sub: function ( a, b ) {
this.x = a.x - b.x;
this.y = a.y - b.y;
this.z = a.z - b.z;
return this;
},
subSelf: function ( v ) {
this.x -= v.x;
this.y -= v.y;
this.z -= v.z;
return this;
},
multiply: function ( a, b ) {
this.x = a.x * b.x;
this.y = a.y * b.y;
this.z = a.z * b.z;
return this;
},
multiplySelf: function ( v ) {
this.x *= v.x;
this.y *= v.y;
this.z *= v.z;
return this;
},
multiplyScalar: function ( s ) {
this.x *= s;
this.y *= s;
this.z *= s;
return this;
},
divideSelf: function ( v ) {
this.x /= v.x;
this.y /= v.y;
this.z /= v.z;
return this;
},
divideScalar: function ( s ) {
if ( s ) {
this.x /= s;
this.y /= s;
this.z /= s;
} else {
this.x = 0;
this.y = 0;
this.z = 0;
}
return this;
},
negate: function() {
return this.multiplyScalar( - 1 );
},
dot: function ( v ) {
return this.x * v.x + this.y * v.y + this.z * v.z;
},
lengthSq: function () {
return this.x * this.x + this.y * this.y + this.z * this.z;
},
length: function () {
return Math.sqrt( this.lengthSq() );
},
lengthManhattan: function () {
return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
},
normalize: function () {
return this.divideScalar( this.length() );
},
setLength: function ( l ) {
return this.normalize().multiplyScalar( l );
},
lerpSelf: function ( v, alpha ) {
this.x += ( v.x - this.x ) * alpha;
this.y += ( v.y - this.y ) * alpha;
this.z += ( v.z - this.z ) * alpha;
return this;
},
cross: function ( a, b ) {
this.x = a.y * b.z - a.z * b.y;
this.y = a.z * b.x - a.x * b.z;
this.z = a.x * b.y - a.y * b.x;
return this;
},
crossSelf: function ( v ) {
var x = this.x, y = this.y, z = this.z;
this.x = y * v.z - z * v.y;
this.y = z * v.x - x * v.z;
this.z = x * v.y - y * v.x;
return this;
},
distanceTo: function ( v ) {
return Math.sqrt( this.distanceToSquared( v ) );
},
distanceToSquared: function ( v ) {
return new THREE.Vector3().sub( this, v ).lengthSq();
},
getPositionFromMatrix: function ( m ) {
this.x = m.elements[12];
this.y = m.elements[13];
this.z = m.elements[14];
return this;
},
setEulerFromRotationMatrix: function ( m, order ) {
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
// clamp, to handle numerical problems
function clamp( x ) {
return Math.min( Math.max( x, -1 ), 1 );
}
var te = m.elements;
var m11 = te[0], m12 = te[4], m13 = te[8];
var m21 = te[1], m22 = te[5], m23 = te[9];
var m31 = te[2], m32 = te[6], m33 = te[10];
if ( order === undefined || order === 'XYZ' ) {
this.y = Math.asin( clamp( m13 ) );
if ( Math.abs( m13 ) < 0.99999 ) {
this.x = Math.atan2( - m23, m33 );
this.z = Math.atan2( - m12, m11 );
} else {
this.x = Math.atan2( m32, m22 );
this.z = 0;
}
} else if ( order === 'YXZ' ) {
this.x = Math.asin( - clamp( m23 ) );
if ( Math.abs( m23 ) < 0.99999 ) {
this.y = Math.atan2( m13, m33 );
this.z = Math.atan2( m21, m22 );
} else {
this.y = Math.atan2( - m31, m11 );
this.z = 0;
}
} else if ( order === 'ZXY' ) {
this.x = Math.asin( clamp( m32 ) );
if ( Math.abs( m32 ) < 0.99999 ) {
this.y = Math.atan2( - m31, m33 );
this.z = Math.atan2( - m12, m22 );
} else {
this.y = 0;
this.z = Math.atan2( m21, m11 );
}
} else if ( order === 'ZYX' ) {
this.y = Math.asin( - clamp( m31 ) );
if ( Math.abs( m31 ) < 0.99999 ) {
this.x = Math.atan2( m32, m33 );
this.z = Math.atan2( m21, m11 );
} else {
this.x = 0;
this.z = Math.atan2( - m12, m22 );
}
} else if ( order === 'YZX' ) {
this.z = Math.asin( clamp( m21 ) );
if ( Math.abs( m21 ) < 0.99999 ) {
this.x = Math.atan2( - m23, m22 );
this.y = Math.atan2( - m31, m11 );
} else {
this.x = 0;
this.y = Math.atan2( m13, m33 );
}
} else if ( order === 'XZY' ) {
this.z = Math.asin( - clamp( m12 ) );
if ( Math.abs( m12 ) < 0.99999 ) {
this.x = Math.atan2( m32, m22 );
this.y = Math.atan2( m13, m11 );
} else {
this.x = Math.atan2( - m23, m33 );
this.y = 0;
}
}
return this;
},
setEulerFromQuaternion: function ( q, order ) {
// q is assumed to be normalized
// clamp, to handle numerical problems
function clamp( x ) {
return Math.min( Math.max( x, -1 ), 1 );
}
// http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
var sqx = q.x * q.x;
var sqy = q.y * q.y;
var sqz = q.z * q.z;
var sqw = q.w * q.w;
if ( order === undefined || order === 'XYZ' ) {
this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
} else if ( order === 'YXZ' ) {
this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
} else if ( order === 'ZXY' ) {
this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
} else if ( order === 'ZYX' ) {
this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
} else if ( order === 'YZX' ) {
this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
} else if ( order === 'XZY' ) {
this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
}
return this;
},
getScaleFromMatrix: function ( m ) {
var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
this.x = sx;
this.y = sy;
this.z = sz;
return this;
},
equals: function ( v ) {
return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
},
isZero: function () {
return ( this.lengthSq() < 0.0001 /* almostZero */ );
},
clone: function () {
return new THREE.Vector3( this.x, this.y, this.z );
}
};
}); |
import Vue from 'vue';
import DiffFileComponent from '~/diffs/components/diff_file.vue';
import { diffViewerModes, diffViewerErrors } from '~/ide/constants';
import store from 'ee_else_ce/mr_notes/stores';
import { createComponentWithStore } from 'spec/helpers/vue_mount_component_helper';
import diffFileMockData from '../mock_data/diff_file';
describe('DiffFile', () => {
let vm;
beforeEach(() => {
vm = createComponentWithStore(Vue.extend(DiffFileComponent), store, {
file: JSON.parse(JSON.stringify(diffFileMockData)),
canCurrentUserFork: false,
}).$mount();
});
describe('template', () => {
it('should render component with file header, file content components', () => {
const el = vm.$el;
const { file_hash, file_path } = vm.file;
expect(el.id).toEqual(file_hash);
expect(el.classList.contains('diff-file')).toEqual(true);
expect(el.querySelectorAll('.diff-content.hidden').length).toEqual(0);
expect(el.querySelector('.js-file-title')).toBeDefined();
expect(el.querySelector('.file-title-name').innerText.indexOf(file_path)).toBeGreaterThan(-1);
expect(el.querySelector('.js-syntax-highlight')).toBeDefined();
vm.file.renderIt = true;
vm.$nextTick(() => {
expect(el.querySelectorAll('.line_content').length).toBeGreaterThan(5);
});
});
describe('collapsed', () => {
it('should not have file content', done => {
expect(vm.$el.querySelectorAll('.diff-content').length).toEqual(1);
expect(vm.isCollapsed).toEqual(false);
vm.isCollapsed = true;
vm.file.renderIt = true;
vm.$nextTick(() => {
expect(vm.$el.querySelectorAll('.diff-content').length).toEqual(0);
done();
});
});
it('should have collapsed text and link', done => {
vm.renderIt = true;
vm.isCollapsed = true;
vm.$nextTick(() => {
expect(vm.$el.innerText).toContain('This diff is collapsed');
expect(vm.$el.querySelectorAll('.js-click-to-expand').length).toEqual(1);
done();
});
});
it('should have collapsed text and link even before rendered', done => {
vm.renderIt = false;
vm.isCollapsed = true;
vm.$nextTick(() => {
expect(vm.$el.innerText).toContain('This diff is collapsed');
expect(vm.$el.querySelectorAll('.js-click-to-expand').length).toEqual(1);
done();
});
});
it('should be collapsed for renamed files', done => {
vm.renderIt = true;
vm.isCollapsed = false;
vm.file.highlighted_diff_lines = null;
vm.file.viewer.name = diffViewerModes.renamed;
vm.$nextTick(() => {
expect(vm.$el.innerText).not.toContain('This diff is collapsed');
done();
});
});
it('should be collapsed for mode changed files', done => {
vm.renderIt = true;
vm.isCollapsed = false;
vm.file.highlighted_diff_lines = null;
vm.file.viewer.name = diffViewerModes.mode_changed;
vm.$nextTick(() => {
expect(vm.$el.innerText).not.toContain('This diff is collapsed');
done();
});
});
it('should have loading icon while loading a collapsed diffs', done => {
vm.isCollapsed = true;
vm.isLoadingCollapsedDiff = true;
vm.$nextTick(() => {
expect(vm.$el.querySelectorAll('.diff-content.loading').length).toEqual(1);
done();
});
});
it('should update store state', done => {
spyOn(vm.$store, 'dispatch');
vm.isCollapsed = true;
vm.$nextTick(() => {
expect(vm.$store.dispatch).toHaveBeenCalledWith('diffs/setFileCollapsed', {
filePath: vm.file.file_path,
collapsed: true,
});
done();
});
});
it('updates local state when changing file state', done => {
vm.file.viewer.collapsed = true;
vm.$nextTick(() => {
expect(vm.isCollapsed).toBe(true);
done();
});
});
});
});
describe('too large diff', () => {
it('should have too large warning and blob link', done => {
const BLOB_LINK = '/file/view/path';
vm.file.viewer.error = diffViewerErrors.too_large;
vm.file.viewer.error_message =
'This source diff could not be displayed because it is too large';
vm.file.view_path = BLOB_LINK;
vm.file.renderIt = true;
vm.$nextTick(() => {
expect(vm.$el.innerText).toContain(
'This source diff could not be displayed because it is too large',
);
done();
});
});
});
describe('watch collapsed', () => {
it('calls handleLoadCollapsedDiff if collapsed changed & file has no lines', done => {
spyOn(vm, 'handleLoadCollapsedDiff');
vm.file.highlighted_diff_lines = undefined;
vm.file.parallel_diff_lines = [];
vm.isCollapsed = true;
vm.$nextTick()
.then(() => {
vm.isCollapsed = false;
return vm.$nextTick();
})
.then(() => {
expect(vm.handleLoadCollapsedDiff).toHaveBeenCalled();
})
.then(done)
.catch(done.fail);
});
});
});
|
export { default } from 'ember-fhir/serializers/consent-actor-1'; |
'use strict';
var path = require('path');
var helpers = require('yeoman-test');
var assert = require('yeoman-assert');
describe('general', function () {
before(function(done) {
helpers.run(path.join(__dirname, '../app'))
.on('error', function(err) {
console.log('Hm, something went wrong.', err);
})
.withPrompts({ features: [] })
.withGenerators([
[helpers.createDummyGenerator(), 'mocha:app']
])
.on('end', done);
});
it('generator can be required without throwing', function() {
// not testing the actual run of generators yet
require('../app');
});
it('creates expected files', function() {
assert.file([
'.babelrc',
'.eslintrc',
'.gitignore',
'.bowerrc',
'bower.json',
'Gulpfile.js',
'karma.conf.js',
'nodemon.json',
'package.json',
'phantomas.json',
'yslow.js'
]);
});
it('does not create unexpected files', function() {
assert.noFile([
'Gruntfile.js'
]);
});
});
|
/**
* captcah util
* @type {exports|*}
*/
var tek = require('tek'),
copy = tek.meta.copy,
random = Math.random,
color = require('./u.color'),
rainbow = color.rainbow;
exports.defaultStyle = {
width: 250,
height: 120,
baseColor: '#DD3030',
backgroundColor: '#FFF',
lineWidth: 8,
fontSize: 80,
fontFamily: 'sans'
};
exports.newBuffer = function (text, style, callback) {
var Canvas = require('canvas');
switch
(arguments.length) {
case 2 :
callback = arguments[1];
style = {};
break;
}
copy.fallback(exports.defaultStyle, style);
var w = style.width,
h = style.height;
var canvas = new Canvas(w, h),
ctx = canvas.getContext('2d');
ctx.antialias = 'gray';
ctx.fillStyle = style.backgroundColor;
ctx.fillRect(0, 0, w, h);
var colors = rainbow(style.baseColor, text.length).sort(function () {
return random() - random();
});
ctx.font = [style.fontSize + 'px', style.fontFamily].join(' ');
ctx.fillStyle = style.baseColor;
var i;
for (i = 0; i < 2; i++) {
ctx.moveTo(20, random() * 150);
ctx.bezierCurveTo(80, random() * 150, 160, random() * 150, 230, random() * 150);
ctx.strokeStyle = colors[i % colors.length];
ctx.stroke();
}
for (i = 0; i < text.length; i++) {
ctx.fillStyle = colors[i];
ctx.setTransform(
random() * 0.5 + 1, random() * 0.4, random() * 0.4,
random() * 0.5 + 1,
style.fontSize * .5 * i + 5, 100);
ctx.fillText(text[i], 5, 0);
}
canvas.toBuffer(callback);
};
|
const logger = require('winston');
const electron = require('electron')
const app = electron.app
const jsonfile = require('jsonfile');
const path = require('path')
const fs = require('fs')
const _ = require('lodash');
const Migration = require('../migration')
class v071 extends Migration {
run() {
// TODO find default profile, get the SLI id and set this SLI profile as default
const profilesFile = path.resolve(app.getPath('userData'), 'profiles.json');
try {
fs.statSync(profilesFile)
} catch (err) {
return true;
}
let profiles = {}
try {
profiles = jsonfile.readFileSync(profilesFile);
} catch (err) {
logger.error(err);
return false;
}
let sli;
_.forIn(profiles, (profile, id) => {
// find first profile with an activated sli
if (!sli && profile.default && profile.sli) {
sli = profile.sli;
}
profiles[id].default = null;
delete profiles[id].default;
});
try {
jsonfile.writeFileSync(profilesFile, profiles);
} catch (err) {
logger.error(err);
return false;
}
if (sli) {
const shiftLightsFile = path.resolve(app.getPath('userData'), 'shift_lights.json');
try {
fs.statSync(shiftLightsFile)
} catch (err) {
return true;
}
let shiftLights = {};
try {
shiftLights = jsonfile.readFileSync(shiftLightsFile);
} catch (err) {
return true;
}
if (!shiftLights.default) {
shiftLights.default = sli;
try {
jsonfile.writeFileSync(shiftLightsFile, shiftLights);
} catch (err) {
console.error(err);
return false;
}
}
}
return true
}
}
module.exports = new v071()
|
import React from 'react';
import Exception from '../Exception/index';
import CheckPermissions from './CheckPermissions';
/**
* 默认不能访问任何页面
* default is "NULL"
*/
const Exception403 = () => (
<Exception type="403" style={{ minHeight: 500, height: '80%' }} />
);
/**
* 用于判断是否拥有权限访问此view权限
* authority 支持传入 string ,funtion:()=>boolean|Promise
* e.g. 'user' 只有user用户能访问
* e.g. 'user,admin' user和 admin 都能访问
* e.g. ()=>boolean 返回true能访问,返回false不能访问
* e.g. Promise then 能访问 catch不能访问
* e.g. authority support incoming string, funtion: () => boolean | Promise
* e.g. 'user' only user user can access
* e.g. 'user, admin' user and admin can access
* e.g. () => boolean true to be able to visit, return false can not be accessed
* e.g. Promise then can not access the visit to catch
* @param {string | function | Promise} authority
* @param {ReactNode} error 非必需参数
*/
const authorize = (authority, error) => {
/**
* conversion into a class
* 防止传入字符串时找不到staticContext造成报错
* String parameters can cause staticContext not found error
*/
let classError = false;
if (error) {
classError = () => error;
}
if (!authority) {
throw new Error('authority is required');
}
return function decideAuthority(targer) {
return () => CheckPermissions(authority, targer, classError || Exception403);
};
};
export default authorize;
|
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import { expect } from 'chai';
import {
init,
eventInstance,
getInnerHTML,
expectInputAttribute,
expectInputValue,
getSuggestionsContainer,
getSuggestion,
expectSuggestions,
expectFocusedSuggestion,
mouseEnterSuggestion,
mouseLeaveSuggestion,
clickSuggestion,
focusInput,
blurInput,
clickEscape,
clickEnter,
clickDown,
clickUp,
focusAndSetInputValue,
isInputFocused
} from '../helpers';
import AutosuggestApp, {
getSuggestionValue,
renderSuggestion,
onChange,
shouldRenderSuggestions,
onSuggestionSelected
} from './AutosuggestApp';
describe('Plain list Autosuggest', () => {
beforeEach(() => {
const app = TestUtils.renderIntoDocument(React.createElement(AutosuggestApp));
const container = TestUtils.findRenderedDOMComponentWithClass(app, 'react-autosuggest__container');
const input = TestUtils.findRenderedDOMComponentWithTag(app, 'input');
init({ app, container, input });
});
describe('initially', () => {
describe('should render an input and set its:', () => {
it('id', () => {
expectInputAttribute('id', 'my-awesome-autosuggest');
});
it('placeholder', () => {
expectInputAttribute('placeholder', 'Type a programming language');
});
it('type', () => {
expectInputAttribute('type', 'search');
});
it('value', () => {
expectInputValue('');
});
});
it('should not show suggestions', () => {
expectSuggestions([]);
});
});
describe('when typing and matches exist', () => {
beforeEach(() => {
focusAndSetInputValue('p');
});
it('should show suggestions', () => {
expectSuggestions(['Perl', 'PHP', 'Python']);
});
it('should not focus on any suggestion', () => {
expectFocusedSuggestion(null);
});
it('should hide suggestions when Escape is pressed', () => {
clickEscape();
expectSuggestions([]);
});
it('should not clear the input when Escape is pressed', () => {
clickEscape();
expectInputValue('p');
});
it('should clear the input when Escape is pressed again', () => {
clickEscape();
clickEscape();
expectInputValue('');
});
it('should hide suggestions when input is blurred', () => {
blurInput();
expectSuggestions([]);
});
it('should show suggestions when input is focused again', () => {
blurInput();
focusInput();
expectSuggestions(['Perl', 'PHP', 'Python']);
});
it('should revert input value when Escape is pressed after Up/Down interaction', () => {
clickDown();
clickEscape();
expectInputValue('p');
});
it('should update input value when suggestion is clicked', () => {
clickSuggestion(1);
expectInputValue('PHP');
});
it('should focus on suggestion when mouse enters it', () => {
mouseEnterSuggestion(2);
expectFocusedSuggestion('Python');
});
it('should not have focused suggestions when mouse leaves a suggestion', () => {
mouseEnterSuggestion(2);
mouseLeaveSuggestion(2);
expectFocusedSuggestion(null);
});
});
describe('when typing and matches do not exist', () => {
beforeEach(() => {
focusAndSetInputValue('z');
});
it('should not show suggestions', () => {
expectSuggestions([]);
});
it('should clear the input when Escape is pressed', () => {
clickEscape();
expectInputValue('');
});
});
describe('when pressing Down', () => {
beforeEach(() => {
focusAndSetInputValue('p');
});
it('should show suggestions with no focused suggestion, if they are hidden', () => {
clickEscape();
clickDown();
expectSuggestions(['Perl', 'PHP', 'Python']);
expectFocusedSuggestion(null);
});
it('should focus on the first suggestion', () => {
clickDown();
expectFocusedSuggestion('Perl');
});
it('should focus on the next suggestion', () => {
clickDown(2);
expectFocusedSuggestion('PHP');
});
it('should not focus on any suggestion after reaching the last suggestion', () => {
clickDown(4);
expectFocusedSuggestion(null);
});
it('should focus on the first suggestion again', () => {
clickDown(5);
expectFocusedSuggestion('Perl');
});
});
describe('when pressing Up', () => {
beforeEach(() => {
focusAndSetInputValue('p');
});
it('should show suggestions with no focused suggestion, if they are hidden', () => {
clickEscape();
clickUp();
expectSuggestions(['Perl', 'PHP', 'Python']);
expectFocusedSuggestion(null);
});
it('should focus on the last suggestion', () => {
clickUp();
expectFocusedSuggestion('Python');
});
it('should focus on the second last suggestion', () => {
clickUp(2);
expectFocusedSuggestion('PHP');
});
it('should not focus on any suggestion after reaching the first suggestion', () => {
clickUp(4);
expectFocusedSuggestion(null);
});
it('should focus on the last suggestion again', () => {
clickUp(5);
expectFocusedSuggestion('Python');
});
});
describe('when pressing Enter', () => {
beforeEach(() => {
focusAndSetInputValue('p');
});
it('should hide suggestions if there is a focused suggestion', () => {
clickDown();
clickEnter();
expectSuggestions([]);
});
it('should not hide suggestions if there is no focused suggestion', () => {
clickEnter();
expectSuggestions(['Perl', 'PHP', 'Python']);
});
});
describe('when pressing Escape', () => {
it('should clear the input if suggestions are hidden and never been shown before', () => {
focusAndSetInputValue('z');
clickEscape();
expectInputValue('');
});
it('should clear the input if suggestions are hidden but were shown before', () => {
focusAndSetInputValue('p');
focusAndSetInputValue('pz');
clickEscape();
expectInputValue('');
});
});
describe('when suggestion is clicked', () => {
beforeEach(() => {
focusAndSetInputValue('p');
clickSuggestion(1);
});
it('should hide suggestions', () => {
expectSuggestions([]);
});
it('should focus on input if focusInputOnSuggestionClick is true', () => {
expect(isInputFocused()).to.equal(true);
});
});
describe('getSuggestionValue', () => {
beforeEach(() => {
getSuggestionValue.reset();
focusAndSetInputValue('r');
});
it('should be called once with the right parameters when Up is pressed', () => {
clickUp();
expect(getSuggestionValue).to.have.been.calledOnce;
expect(getSuggestionValue).to.have.been.calledWithExactly({ name: 'Ruby', year: 1995 });
});
it('should be called once with the right parameters when Down is pressed', () => {
clickDown();
expect(getSuggestionValue).to.have.been.calledOnce;
expect(getSuggestionValue).to.have.been.calledWithExactly({ name: 'Ruby', year: 1995 });
});
it('should be called once with the right parameters when suggestion is clicked', () => {
clickSuggestion(0);
expect(getSuggestionValue).to.have.been.calledOnce;
expect(getSuggestionValue).to.have.been.calledWithExactly({ name: 'Ruby', year: 1995 });
});
});
describe('renderSuggestion', () => {
beforeEach(() => {
renderSuggestion.reset();
focusAndSetInputValue('r');
});
it('should be called with the right parameters', () => {
expect(renderSuggestion).to.have.been.calledWithExactly({ name: 'Ruby', year: 1995 }, { value: 'r', valueBeforeUpDown: null });
renderSuggestion.reset();
clickDown();
expect(renderSuggestion).to.have.been.calledWithExactly({ name: 'Ruby', year: 1995 }, { value: 'Ruby', valueBeforeUpDown: 'r' });
});
it('should be called once per suggestion', () => {
expect(renderSuggestion).to.have.been.calledOnce;
});
it('return value should be used to render suggestions', () => {
const firstSuggestion = getSuggestion(0);
expect(getInnerHTML(firstSuggestion)).to.equal('<strong>R</strong><span>uby</span>');
});
});
describe('inputProps.onChange', () => {
beforeEach(() => {
focusAndSetInputValue('c');
onChange.reset();
});
it('should be called once with the right parameters when user types', () => {
focusAndSetInputValue('c+');
expect(onChange).to.have.been.calledOnce;
expect(onChange).to.be.calledWithExactly(eventInstance, {
newValue: 'c+',
method: 'type'
});
});
it('should be called once with the right parameters when pressing Down focuses on a suggestion which differs from input value', () => {
clickDown();
expect(onChange).to.have.been.calledOnce;
expect(onChange).to.be.calledWithExactly(eventInstance, {
newValue: 'C',
method: 'down'
});
});
it('should be called once with the right parameters when pressing Up focuses on a suggestion which differs from input value', () => {
clickUp();
expect(onChange).to.have.been.calledOnce;
expect(onChange).to.be.calledWithExactly(eventInstance, {
newValue: 'Clojure',
method: 'up'
});
});
it('should be called once with the right parameters when Escape is pressed and suggestions are hidden', () => {
clickEscape();
clickEscape();
expect(onChange).to.have.been.calledOnce;
expect(onChange).to.be.calledWithExactly(eventInstance, {
newValue: '',
method: 'escape'
});
});
it('should be called once with the right parameters when suggestion which differs from input value is clicked', () => {
clickSuggestion(2);
expect(onChange).to.have.been.calledOnce;
expect(onChange).to.be.calledWithExactly(eventInstance, {
newValue: 'C++',
method: 'click'
});
});
it('should not be called when Down is pressed and suggestions are hidden', () => {
clickEscape();
clickDown();
expect(onChange).not.to.have.been.called;
});
it('should not be called when pressing Down focuses on suggestion which value equals to input value', () => {
focusAndSetInputValue('C++');
onChange.reset();
clickDown();
expect(onChange).not.to.have.been.called;
});
it('should not be called when Up is pressed and suggestions are hidden', () => {
clickEscape();
clickUp();
expect(onChange).not.to.have.been.called;
});
it('should not be called when pressing Up focuses on suggestion which value equals to input value', () => {
focusAndSetInputValue('C++');
onChange.reset();
clickUp();
expect(onChange).not.to.have.been.called;
});
it('should not be called when Escape is pressed and suggestions are shown', () => {
clickEscape();
expect(onChange).not.to.have.been.called;
});
it('should not be called when Escape is pressed, suggestions are hidden, and input is empty', () => {
focusAndSetInputValue('');
onChange.reset();
clickEscape();
expect(onChange).not.to.have.been.called;
});
it('should not be called when suggestion which value equals to input value is clicked', () => {
focusAndSetInputValue('C++');
onChange.reset();
clickSuggestion(0);
expect(onChange).not.to.have.been.called;
});
});
describe('shouldRenderSuggestions', () => {
beforeEach(() => {
shouldRenderSuggestions.reset();
});
it('should be called with the right parameters', () => {
focusAndSetInputValue('e');
expect(shouldRenderSuggestions).to.be.calledWithExactly('e');
});
it('should show suggestions when `true` is returned', () => {
focusAndSetInputValue('e');
expectSuggestions(['Elm']);
});
it('should hide suggestions when `false` is returned', () => {
focusAndSetInputValue(' e');
expectSuggestions([]);
});
});
describe('onSuggestionSelected', () => {
beforeEach(() => {
onSuggestionSelected.reset();
focusAndSetInputValue('j');
});
it('should be called once with the right parameters when suggestion is clicked', () => {
clickSuggestion(1);
expect(onSuggestionSelected).to.have.been.calledOnce;
expect(onSuggestionSelected).to.have.been.calledWithExactly(eventInstance, {
suggestion: { name: 'Javascript', year: 1995 },
suggestionValue: 'Javascript',
method: 'click'
});
});
it('should be called once with the right parameters when Enter is pressed and suggestion is focused', () => {
clickDown();
clickEnter();
expect(onSuggestionSelected).to.have.been.calledOnce;
expect(onSuggestionSelected).to.have.been.calledWithExactly(eventInstance, {
suggestion: { name: 'Java', year: 1995 },
suggestionValue: 'Java',
method: 'enter'
});
});
it('should not be called when Enter is pressed and there is no focused suggestion', () => {
clickEnter();
expect(onSuggestionSelected).not.to.have.been.called;
});
it('should not be called when Enter is pressed and there is no focused suggestion after Up/Down interaction', () => {
clickDown();
clickDown();
clickDown();
clickEnter();
expect(onSuggestionSelected).not.to.have.been.called;
});
});
describe('aria attributes', () => {
describe('initially', () => {
describe('should set input\'s', () => {
it('role to "combobox"', () => {
expectInputAttribute('role', 'combobox');
});
it('aria-autocomplete to "list"', () => {
expectInputAttribute('aria-autocomplete', 'list');
});
it('aria-expanded to "false"', () => {
expectInputAttribute('aria-expanded', 'false');
});
it('aria-owns', () => {
expectInputAttribute('aria-owns', 'react-whatever-1');
});
});
describe('should not set input\'s', () => {
it('aria-activedescendant', () => {
expectInputAttribute('aria-activedescendant', null);
});
});
});
describe('when suggestions are shown', () => {
beforeEach(() => {
focusAndSetInputValue('J');
});
it('input\'s aria-expanded should be "true"', () => {
expectInputAttribute('aria-expanded', 'true');
});
it('input\'s aria-owns should be equal to suggestions container id', () => {
expectInputAttribute('aria-owns', getSuggestionsContainer().id);
});
it('input\'s aria-activedescendant should be equal to the focused suggestion id when using keyboard', () => {
clickDown();
expectInputAttribute('aria-activedescendant', getSuggestion(0).id);
clickDown();
expectInputAttribute('aria-activedescendant', getSuggestion(1).id);
clickDown();
expectInputAttribute('aria-activedescendant', null);
});
it('input\'s aria-activedescendant should be equal to the focused suggestion id when using mouse', () => {
mouseEnterSuggestion(0);
expectInputAttribute('aria-activedescendant', getSuggestion(0).id);
mouseLeaveSuggestion(0);
expectInputAttribute('aria-activedescendant', null);
});
it('suggestions container role should be "listbox"', () => {
expect(getSuggestionsContainer().getAttribute('role')).to.equal('listbox');
});
it('suggestions\' role should be "option"', () => {
expect(getSuggestion(0).getAttribute('role')).to.equal('option');
expect(getSuggestion(1).getAttribute('role')).to.equal('option');
});
});
});
});
|
import process from 'node:process';
export const spinnerFrames = process.platform === 'win32'
? ['-', '\\', '|', '/']
: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
export default function elegantSpinner() {
let index = 0;
return () => {
index = ++index % spinnerFrames.length;
return spinnerFrames[index];
};
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.