text
stringlengths 2
6.14k
|
|---|
/*
var jsonfile = require('jsonfile');
var file = '../data1.json';
var tasksController = require('../public/js/tasks.js');
jsonfile.writeFile(file,data1);
*/
// var User = require('../public/js/mongoUser.js');
var Task = require('../public/js/mongoTasks.js');
var MongoClient = require('mongodb').MongoClient, format = require('util').format;
var dJ = require('../data1.json');
var tasksCount, taskList, groupList;
exports.viewTasks = function(req, res){
MongoClient.connect('mongodb://heroku_2s7m53vj:lqb9p32ov0u6akts4hoekc7h5l@ds153677.mlab.com:53677/heroku_2s7m53vj', function(err, db) {
if(err) throw err;
var collection = db.collection('tasks');
var collection2 = db.collection('groups');
// collection.count(function(err, count) {
// //console.log(format("count = %s", count));
// tasksCount = count;
// });
// Locate all the entries using find
collection.find().toArray(function(err, results) {
taskList = results;
});
collection2.find().toArray(function(err,results) {
groupList = results;
// console.dir(groupList);
});
db.close();
})
res.render('tasks', {
dataJson: dJ,
tasks: taskList,
groups: groupList
});
};
exports.updateTasks = function(req,res) {
var name = req.body.name;
var reward = req.body.reward;
var description = req.body.description;
var userSelected = "";
var newTask = new Task({
name: name,
reward: reward,
description: description,
userSelected: userSelected
});
Task.createTask(newTask, function(err,task) {
if(err) throw err;
//console.log(task);
});
res.redirect(req.get('referer'));
// res.redirect('/index');
}
exports.editTasks = function(req,res) {
MongoClient.connect('mongodb://heroku_2s7m53vj:lqb9p32ov0u6akts4hoekc7h5l@ds153677.mlab.com:53677/heroku_2s7m53vj', function(err, db) {
if(err) throw err;
var collection = db.collection('tasks');
var oldName = req.body.oldName || req.query.oldName;
var oldReward = req.body.oldReward || req.query.oldReward;
var oldDescription = req.body.oldDescription || req.query.oldDescription;
var taskName = req.body.taskName || req.query.taskName;
var taskReward = req.body.taskReward || req.query.taskReward;
var taskDescription = req.body.taskDescription || req.query.taskDescription;
//console.dir(taskName);
//collection.remove({"name": memberName});
collection.update({'name': oldName},{$set:{'name':taskName}});
collection.update({'reward': parseInt(oldReward)},{$set:{'reward': parseInt(taskReward)}});
collection.update({'description': oldDescription},{$set:{'description':taskDescription}});
db.close()
// Group.removeMember(memberName, function(err,group){
// if(err) throw err;
// console.log(group);
// })
})
res.redirect(req.get('referer'));
}
exports.removeTasks = function(req,res){
MongoClient.connect('mongodb://heroku_2s7m53vj:lqb9p32ov0u6akts4hoekc7h5l@ds153677.mlab.com:53677/heroku_2s7m53vj', function(err, db) {
if(err) throw err;
var collection = db.collection('tasks');
var taskName = req.body.taskID || req.query.taskID;
//console.dir(taskName);
collection.remove({ $or: [{"name": taskName}, {"name": ''}] });
db.close()
// Group.removeMember(memberName, function(err,group){
// if(err) throw err;
// console.log(group);
// })
})
res.redirect(req.get('referer'));
}
exports.selectUser = function(req,res){
MongoClient.connect('mongodb://heroku_2s7m53vj:lqb9p32ov0u6akts4hoekc7h5l@ds153677.mlab.com:53677/heroku_2s7m53vj', function(err, db) {
if(err) throw err;
var collection = db.collection('tasks');
var selectedUser = req.body.selectedUser || req.query.selectedUser;
var taskName = req.body.taskName || req.query.taskName;
// console.dir(selectedUser);
collection.update({'name': taskName},{$set:{'userSelected': selectedUser}});
db.close()
})
}
|
module.exports = {
flyers: {
testRail: {
projectId: 6,
},
confluence: {
space: '~adam.petrie'
}
}
}
|
'use strict';
const Joi = require('joi');
const uuid = require('uuid');
const reqUtils = require('../utils/requestUtils');
const R = require('ramda');
//fixme: allow unknown fields and just require absolutely mandatory ones
const cucumberSchema = Joi.array().items(Joi.object().keys({
id: Joi.string().required(),
name: Joi.string().required(),
description: Joi.string(),
line: Joi.number().integer(),
keyword: Joi.string(),
uri: Joi.string(),
elements: Joi.array().items(Joi.object().keys({
name: Joi.string().required(),
id: Joi.string().required(),
line: Joi.number().integer(),
keyword: Joi.string(),
description: Joi.string(),
type: Joi.string().required(),
steps: Joi.array().items(Joi.object().keys({
name: Joi.string(),
line: Joi.number().integer(),
keyword: Joi.string(),
result: Joi.object().keys({
status: Joi.string(),
duration: Joi.number().integer()
}),
match: Joi.object().keys({
location: Joi.string()
})
}))
}))
}));
module.exports = function (server, emitter) {
server.route({
method: 'POST',
path: '/upload/cucumber',
config: {
tags: ['upload'],
payload: {
//allow: ['multipart/form-data'],
parse: true,
output: 'stream'
},
validate: {
query: {
evaluation: Joi.string().min(1).required(),
evaluationTag: Joi.string().min(1).required(),
subject: Joi.string().min(1).required()
}
}
},
handler: function(request, reply) {
return reqUtils.getObject(request, 'cucumber')
.then(o => reqUtils.validateObject(o, cucumberSchema))
.then(report => {
emitter.emit(
'uploads/cucumber',
R.assoc('report', report, R.pick(['subject', 'evaluation', 'evaluationTag'], request.query))
);
return reply().code(202);
})
// fixme: this will resolve even internal errors as 429's
// break the initial processing (which returns 429 codes)
// from the final one (which returns 5xx codes)
.catch(e => {
return reply(e.message).code(400);
});
}
});
};
|
'use strict';
/**
* @ngdoc service
* @name publicApp.AuthInterceptor
* @description
* # AuthInterceptor
* Factory in the publicApp.
*/
angular.module('publicApp')
.factory('AuthInterceptor', function(JwtFactory) {
// Public API here
return {
request: function(config) {
config.headers.Authorization = JwtFactory.getJwt();
return config;
}
};
});
|
var accessToken="i7LM4k7JcSKs4ucCpxpgNPcs3i1kRbNKyUE8aPGKZzZWASagz9uZiuLgmgDgBJzY";
$(window).load(function() {
$('#pseudo_submit').click(function() {
NProgress.start();
$.ajax({
type: "POST",
url: "../db-app/signdown.php",
dataType: 'text',
data: {
password: $("#basic_pass").val()
},
complete: function(xhr, statusText){
NProgress.done();
},
success: function (res) {
console.log(res);
if(res.indexOf("ERR")==-1) {
delete_schedule(res);
}
else {
new PNotify({
title: 'Error :(',
text: "Something went wrong",
type: 'error',
styling: 'bootstrap3'
});
}
}
});
});
});
function delete_schedule(id) {
NProgress.start();
var del_url = "https://api.whenhub.com/api/schedules/"+id+"?access_token="+accessToken;
$.ajax({
type: "DELETE",
url: del_url,
complete: function(xhr, statusText){
NProgress.done();
console.log(xhr.status+" "+statusText);
},
success: function (data) {
console.log(data);
window.location.href = "account_deleted.php";
},
error: function(xhr, statusText, err){
console.log(xhr);
console.log(statusText);
console.log(err);
}
});
}
|
import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdFlashOn(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<polygon points="14 4 14 26 20 26 20 44 34 20 26 20 34 4" />
</IconBase>
);
}
export default MdFlashOn;
|
var UI = require('ui');
var ajax = require('ajax');
var Vector2 = require('vector2');
var webserver = decodeURIComponent(localStorage.getItem('webserver') ? localStorage.getItem('webserver') : 'webserver');
var qvserver = localStorage.getItem('qvserver') ? localStorage.getItem('qvserver') : 'qvserver';
var files = localStorage.getItem('files') ? localStorage.getItem('files') : 'files';
// Show splash screen while waiting for data
var splashWindow = new UI.Window();
// Text element to inform user
var text = new UI.Text({
position: new Vector2(0, 0),
size: new Vector2(144, 168),
text:'Downloading data...',
font:'GOTHIC_28_BOLD',
color:'black',
textOverflow:'wrap',
textAlign:'center',
backgroundColor:'white'
});
// Add to splashWindow and show
splashWindow.add(text);
splashWindow.show();
// Make request to the nodejs app //, webserver: test
ajax(
{
url: webserver + '/getdata',
method: 'post',
data: {server: qvserver, files: files, webserver: webserver},
crossDomain: true
},
function(data) {
try {
var items = [];
data = JSON.parse(data);
var areas = data.data;
for(var i = 0; i < areas.length; i++) {
items.push({
title:areas[i].name //,subtitle:time
});
}
var resultsMenu = new UI.Menu({
sections: [{
title: 'Areas',
items: items
}]
});
resultsMenu.on('select', function(e) {
var innerData = data.data[e.itemIndex].areadata;
var title = data.data[e.itemIndex].name;
var details = [];
for(var d = 0; d < innerData.length; d++) {
details.push({
title: innerData[d].category,
subtitle: innerData[d].value
});
}
var detailsMenu = new UI.Menu({
sections: [{
title: title,
items: details}]
});
detailsMenu.show();
});
// Show the Menu, hide the splash
resultsMenu.show();
splashWindow.hide();
} catch (err) {
var text = new UI.Text({
position: new Vector2(0, 0),
size: new Vector2(144, 168),
text:'Error parsing the data',
font:'GOTHIC_28_BOLD',
color:'black',
textOverflow:'wrap',
textAlign:'center',
backgroundColor:'white'
});
// Add to splashWindow and show
splashWindow.add(text);
splashWindow.show();
}
},
function(error) {
var text = new UI.Text({
position: new Vector2(0, 0),
size: new Vector2(144, 168),
text:'Download failed :(',
font:'GOTHIC_28_BOLD',
color:'black',
textOverflow:'wrap',
textAlign:'center',
backgroundColor:'white'
});
// Add to splashWindow and show
splashWindow.add(text);
splashWindow.show();
});
Pebble.addEventListener('showConfiguration', function(e) {
console.log("Showing configuration");
Pebble.openURL('https://googledrive.com/host/0BxjGsOE_3VoOU2RPQ3BjTlBfX0E');
});
Pebble.addEventListener('webviewclosed', function(e) {
var options = JSON.parse(decodeURIComponent(e.response));
qvserver = encodeURIComponent(options.qvserver);
webserver = encodeURIComponent(options.webserver);
files = encodeURIComponent(options.files);
if(qvserver == 'undefined') {
qvserver = 'http://localhost:4799/QMS/Service';
}
localStorage.setItem('qvserver', qvserver);
localStorage.setItem('webserver', webserver);
localStorage.setItem('files', files);
//console.log("Configuration window returned: ", JSON.stringify(options));
});
//Send a string to Pebble
var dict = {
QVSERVER : qvserver,
WEBSERVER: webserver,
FILES: files
};
Pebble.sendAppMessage(dict, function(e) {
console.log("Send successful.");
}, function(e) {
console.log("Send failed!");
});
|
import Ember from 'ember';
var PluginsPopularRoute = Ember.Route.extend({
titleToken: 'Popular'
});
export default PluginsPopularRoute;
|
/**
* Created by Hernandes on 21/04/2016.
*/
function PessoaModel(m){
var self = this;
var base = new BaseModel();
ko.utils.extend(self,base);
self.PessoaID = ko.observable().defaultValue(0).extend({required:true});
self.Nome = ko.observable('').extend({required:true,editable:true});
self.Email = ko.observable('').extend({required:true,editable:true});
self.Enderecos = ko.observableArray([]).typeOf(EnderecoBaseModel);
self.assignProperties(m);
}
define('pessoa-model',function() {
return PessoaModel;
});
|
var send = require("./index")
module.exports = sendJson
/* sendJson := (HttpRequest, HttpResponse, Value | {
body: Value,
headers?: Object<String, String>,
statusCode?: Number
})
*/
function sendJson(req, res, value, replacer, space) {
if (!value || (!value.statusCode && !value.headers)) {
value = { body: value }
}
value.headers = value.headers || {}
value.body = JSON.stringify(value.body, replacer, space)
value.headers["Content-Type"] = "application/json"
send(req, res, value)
}
|
process.env.NODE_ENV = 'production'
var ora = require('ora')
var rm = require('rimraf')
var path = require('path')
var chalk = require('chalk')
var webpack = require('webpack')
var config = require('../config')
var webpackConfig = require('./webpack.prod.conf')
var spinner = ora('building for production...')
spinner.start()
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
if (err) throw err
webpack(webpackConfig, function (err, stats) {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n\n')
console.log(chalk.cyan(' Build complete.\n'))
console.log(chalk.yellow(
' Tip: built files are meant to be served over an HTTP server.\n' +
' Opening index.html over file:// won\'t work.\n'
))
})
})
|
var duplex = require('duplexer')
var through = require('through')
module.exports = function (counter) {
var countries = {}
function count(input) {
countries[input.country] = (countries[input.country] || 0) + 1
}
function end() {
counter.setCounts(countries)
}
return duplex(through(count, end), counter)
}
|
export default function() {
let directive = {
restrict: 'E',
replace: true,
scope: {
ad: '='
},
templateUrl: './directives/adCard/template.html',
controller: ['$scope', ($scope) => {
if ($scope.ad.thumbnail) {
$scope.ad.previewImg = `${$scope.ad.thumbnail.base_url}/card/${$scope.ad.thumbnail.path}`;
}
else {
$scope.ad.previewImg = '/src/images/car2.png';
}
if (120 <= $scope.ad.body.length) {
$scope.ad.shortBody = `${$scope.ad.body.slice(0, 119).trim()}...`;
}
else {
$scope.ad.shortBody = $scope.ad.body;
}
}]
};
return directive;
}
|
var app = require('app'); // Module to control application life.
var BrowserWindow = require('browser-window'); // Module to create native browser window.
// Report crashes to our server.
require('crash-reporter').start();
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow = null;
// Quit when all windows are closed.
app.on('window-all-closed', function() {
'use strict';
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit();
}
});
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
'use strict';
// Create the browser window.
mainWindow = new BrowserWindow({
width: 1024,
height: 768,
title: 'Build & Deploy',
'auto-hide-menu-bar': true
});
// and load the index.html of the app.
mainWindow.loadUrl('file://' + __dirname + '/index.html');
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
});
|
import React from 'react';
import styled from 'styled-components';
import Item from './Item';
import parchment from '../assets/parchment.png';
import chest from '../assets/chest.png';
const Container = styled.div`
background: url(${parchment});
position: relative;
height: 286px;
width: 303px;
align-self: center;
margin: 10px;
`;
const Items = styled.div`
position: absolute;
display: flex;
flex-direction: row;
flex-wrap: wrap;
align-items: center;
top: 78px;
left: 130px;
width: 108px;
`;
const Chest = styled.div`
position: absolute;
background: url(${chest});
image-rendering: pixelated;
width: 92px;
height: 92px;
top: 138px;
left: 34px;
`;
const Clue = ({ rewards, className, style }) => (
<Container className={className} style={style}>
<Items>
{rewards.map(reward => (
<Item key={reward.id} id={reward.id} amount={reward.amount} />
))}
</Items>
<Chest />
</Container>
);
export default Clue;
|
var config = this.window ? {} : module.exports;
config.Rjs = {
environment: "browser",
rootPath: "../",
sources: [
"build/Reality.combined.replaced.js",
],
tests: [
"test/**/*.js"
]
};
|
/*
cryptr is a simple aes-256-gcm encrypt and decrypt module for node.js
Copyright (c) 2014 Maurice Butler
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
const crypto = require("crypto");
const algorithm = "aes-256-gcm";
const ivLength = 16;
const saltLength = 64;
const tagLength = 16;
const tagPosition = saltLength + ivLength;
const encryptedPosition = tagPosition + tagLength;
function Cryptr(secret) {
if (!secret || typeof secret !== "string") {
throw new Error("Cryptr: secret must be a non-0-length string");
}
function getKey(salt) {
return crypto.pbkdf2Sync(secret, salt, 100000, 32, "sha512");
}
this.encrypt = function encrypt(value) {
if (value == null) {
throw new Error("value must not be null or undefined");
}
const iv = crypto.randomBytes(ivLength);
const salt = crypto.randomBytes(saltLength);
const key = getKey(salt);
const cipher = crypto.createCipheriv(algorithm, key, iv);
const encrypted = Buffer.concat([cipher.update(String(value), "utf8"), cipher.final()]);
const tag = cipher.getAuthTag();
return Buffer.concat([salt, iv, tag, encrypted]).toString("hex");
};
this.decrypt = function decrypt(value) {
if (value == null) {
throw new Error("value must not be null or undefined");
}
const stringValue = Buffer.from(String(value), "hex");
const salt = stringValue.slice(0, saltLength);
const iv = stringValue.slice(saltLength, tagPosition);
const tag = stringValue.slice(tagPosition, encryptedPosition);
const encrypted = stringValue.slice(encryptedPosition);
const key = getKey(salt);
const decipher = crypto.createDecipheriv(algorithm, key, iv);
decipher.setAuthTag(tag);
return decipher.update(encrypted) + decipher.final("utf8");
};
}
module.exports = Cryptr;
|
'use strict';
/* global Parse */
angular.module('main').factory('ParseFile', function ($q) {
return {
upload: function (base64) {
var defer = $q.defer();
var parseFile = new Parse.File('image.jpg', { base64: base64 });
parseFile.save({
success: function (savedFile) {
defer.resolve(savedFile);
},
error: function (error) {
defer.reject(error);
}
});
return defer.promise;
},
uploadFile: function (file) {
var defer = $q.defer();
var parseFile = new Parse.File('image.jpg', file);
parseFile.save({
success: function (savedFile) {
defer.resolve(savedFile);
},
error: function (error) {
defer.reject(error);
}
});
return defer.promise;
},
};
});
|
var Counter = require('./counterEvented.js');
var c = new Counter(1);
c.increment();
c.on('even', function(){
console.log('even! ' + c.count);
return;
});
|
//数据的视觉映射
// 数据可视化是 数据 到 视觉元素 的映射过程(这个过程也可称为视觉编码,视觉元素也可称为视觉通道)。
// data ----> graph
//使用visualmap提供通用的视觉映射 visualmap 属性有 1.图形类别symbol 2.图像大小symbolSize 3.颜色color 4.透明度opacity 5.颜色透明度 colorAlpha
// 6.颜色明暗度colorLightness 7.颜色饱和度colorSturaction 8.色调colorHue
//数据和维度
// 引入 ECharts 主模块
var echarts = require('echarts/lib/echarts');
require('echarts/lib/chart/line');
require('echarts/lib/component/graphic');
require('echarts/lib/component/tooltip');
var symbolSize = 20;
// 这个 data 变量在这里单独声明,在后面也会用到。
var data = [[15, 0], [-50, 10], [-56.5, 20], [-46.5, 30], [-22.1, 40]];
var myChart = echarts.init(document.getElementById('root'));
myChart.setOption({
tooltip: {
// 表示不使用默认的『显示』『隐藏』触发规则。
triggerOn: 'none',
formatter: function (params) {
return 'X: ' + params.data[0].toFixed(2) + '<br>Y: ' + params.data[1].toFixed(2);
}
},
xAxis: {
min: -100,
max: 80,
type: 'value',
axisLine: { onZero: false }
},
yAxis: {
min: -30,
max: 60,
type: 'value',
axisLine: { onZero: false }
},
series: [
{
id: 'a',
type: 'line',
smooth: true,
symbolSize: symbolSize, // 为了方便拖拽,把 symbolSize 尺寸设大了。
data: data
}
]
});
myChart.setOption({
// 声明一个 graphic component,里面有若干个 type 为 'circle' 的 graphic elements。
// 这里使用了 echarts.util.map 这个帮助方法,其行为和 Array.prototype.map 一样,但是兼容 es5 以下的环境。
// 用 map 方法遍历 data 的每项,为每项生成一个圆点。
graphic: echarts.util.map(data, function (dataItem, dataIndex) {
return {
// 'circle' 表示这个 graphic element 的类型是圆点。
type: 'circle',
shape: {
// 圆点的半径。
r: symbolSize / 2
},
// 用 transform 的方式对圆点进行定位。position: [x, y] 表示将圆点平移到 [x, y] 位置。
// 这里使用了 convertToPixel 这个 API 来得到每个圆点的位置,下面介绍。
position: myChart.convertToPixel('grid', dataItem),
// 这个属性让圆点不可见(但是不影响他响应鼠标事件)。
invisible: true,
// 这个属性让圆点可以被拖拽。
draggable: true,
// 把 z 值设得比较大,表示这个圆点在最上方,能覆盖住已有的折线图的圆点。
z: 100,
// 在 mouseover 的时候显示,在 mouseout 的时候隐藏。
onmousemove: echarts.util.curry(showTooltip, dataIndex),
onmouseout: echarts.util.curry(hideTooltip, dataIndex),
// 此圆点的拖拽的响应事件,在拖拽过程中会不断被触发。下面介绍详情。
// 这里使用了 echarts.util.curry 这个帮助方法,意思是生成一个与 onPointDragging
// 功能一样的新的函数,只不过第一个参数永远为此时传入的 dataIndex 的值。
ondrag: echarts.util.curry(onPointDragging, dataIndex)
};
})
});
// 拖拽某个圆点的过程中会不断调用此函数。
// 此函数中会根据拖拽后的新位置,改变 data 中的值,并用新的 data 值,重绘折线图,从而使折线图同步于被拖拽的隐藏圆点。
function onPointDragging(dataIndex) {
// 这里的 data 就是本文最初的代码块中声明的 data,在这里会被更新。
// 这里的 this 就是被拖拽的圆点。this.position 就是圆点当前的位置。
data[dataIndex] = myChart.convertFromPixel('grid', this.position);
// 用更新后的 data,重绘折线图。
myChart.setOption({
series: [{
id: 'a',
data: data
}]
});
}
window.addEventListener('resize', function () {
// 对每个拖拽圆点重新计算位置,并用 setOption 更新。
myChart.setOption({
graphic: echarts.util.map(data, function (item, dataIndex) {
return {
position: myChart.convertToPixel('grid', item)
};
})
});
});
function showTooltip(dataIndex) {
myChart.dispatchAction({
type: 'showTip',
seriesIndex: 0,
dataIndex: dataIndex
});
}
function hideTooltip(dataIndex) {
myChart.dispatchAction({
type: 'hideTip'
});
}
|
'use strict';
var React = require('react');
var mui = require('material-ui');
var SvgIcon = mui.SvgIcon;
var DeviceSignalCellularConnectedNoInternet2Bar = React.createClass({
displayName: 'DeviceSignalCellularConnectedNoInternet2Bar',
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { 'fillOpacity': '.3', d: 'M22 8V2L2 22h16V8z' }),
React.createElement('path', { d: 'M14 22V10L2 22h12zm6-12v8h2v-8h-2zm0 12h2v-2h-2v2z' })
);
}
});
module.exports = DeviceSignalCellularConnectedNoInternet2Bar;
|
/**
* Created by tkachenko on 14.04.15.
*/
ATF.invoke(['$directiveProvider', 'utils', 'jQuery'], function ($directiveProvider, utils, $) {
$directiveProvider.register('$On', {
link: function (name, $el, scope, args, vars) {
var __vars = vars||{};
if (!args[0] || !args[1]) {
return $el;
}
var eventName = args[0];
var expr = utils.eval(args[1]);
var apply = args[2];
if (eventName.toLowerCase() === 'transitionend') {
eventName = 'webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend';
}
$($el).on(eventName, function ($event) {
__vars.$event = $event;
if (args[2] || eventName === 'click') {
$event.preventDefault();
}
expr.call(this, scope, __vars);
if (apply) {
scope.$apply();
}
});
return $el;
}
});
});
|
import Constants from '../constants';
import LinkDrawable from './link';
import SphericalPortalLinkMesh from '../mesh/spherical-portal-link';
/**
* Represents a portal link that follows the surface of a sphere.
*
* Hooray for custom shaders, etc!
*/
class SphericalPortalLinkDrawable extends LinkDrawable {
/**
* Construct a spherical portal link
* @param {Number} sphereRadius Radius of the sphere
* @param {vec2} start Lat,lng of the origin portal
* @param {vec2} end Lat,lng of the destination portal
* @param {vec4} color Color of the link
* @param {Number} startPercent Percent health of the origin portal
* @param {Number} endPercent Percent health of the destination portal
*/
constructor(sphereRadius, start, end, color, startPercent, endPercent) {
super(Constants.Program.SphericalLink, Constants.Texture.PortalLink);
this.radius = sphereRadius;
this.start = start;
this.end = end;
this.color = color;
this.startPercent = startPercent;
this.endPercent = endPercent;
}
/**
* Constructs a mesh for the link, then initializes the remaining assets.
* @param {AssetManager} manager AssetManager containing the program/texture
* @return {Boolean} Success/failure
*/
init(manager) {
this.mesh = new SphericalPortalLinkMesh(
manager._gl,
this.radius,
this.start,
this.end,
this.color,
this.startPercent,
this.endPercent
);
return super.init(manager);
}
updateView(viewProject, view, project) {
super.updateView(viewProject, view, project);
this.uniforms.u_model = this.model;
}
}
export default SphericalPortalLinkDrawable;
|
var models = require('../models');
var Message = models.Message;
var User = require('../proxy').User;
var messageProxy = require('../proxy/message');
var mail = require('./mail');
exports.sendReplyMessage = function (master_id, author_id, topic_id, reply_id) {
var message = new Message();
message.type = 'reply';
message.master_id = master_id;
message.author_id = author_id;
message.topic_id = topic_id;
message.reply_id = reply_id;
message.save(function (err) {
// TODO: 异常处理
User.getUserById(master_id, function (err, master) {
// TODO: 异常处理
if (master && master.receive_reply_mail) {
message.has_read = true;
message.save();
messageProxy.getMessageById(message._id, function (err, msg) {
msg.reply_id = reply_id;
// TODO: 异常处理
mail.sendReplyMail(master.email, msg);
});
}
});
});
};
exports.sendReply2Message = function (master_id, author_id, topic_id, reply_id) {
var message = new Message();
message.type = 'reply2';
message.master_id = master_id;
message.author_id = author_id;
message.topic_id = topic_id;
message.reply_id = reply_id;
message.save(function (err) {
// TODO: 异常处理
User.getUserById(master_id, function (err, master) {
// TODO: 异常处理
if (master && master.receive_reply_mail) {
message.has_read = true;
message.save();
messageProxy.getMessageById(message._id, function (err, msg) {
msg.reply_id = reply_id;
// TODO: 异常处理
mail.sendReplyMail(master.email, msg);
});
}
});
});
};
exports.sendAtMessage = function (master_id, author_id, topic_id, reply_id, callback) {
var message = new Message();
message.type = 'at';
message.master_id = master_id;
message.author_id = author_id;
message.topic_id = topic_id;
message.reply_id = reply_id;
message.save(function (err) {
// TODO: 异常处理
User.getUserById(master_id, function (err, master) {
// TODO: 异常处理
if (master && master.receive_at_mail) {
message.has_read = true;
message.save();
messageProxy.getMessageById(message._id, function (err, msg) {
// TODO: 异常处理
mail.sendAtMail(master.email, msg);
});
}
});
callback(err);
});
};
//author_id is the follower, so the message of the master is master_id
exports.sendFollowMessage = function (follow_id, author_id) {
var message = new Message();
message.type = 'follow';
message.master_id = follow_id;
message.author_id = author_id;
message.save();
};
//author_id is the attendee
exports.sendAttendMessage = function (master_id, topic_id, author_id) {
var message = new Message();
message.type = 'attend';
message.master_id = master_id;
message.author_id = author_id;
message.topic_id= topic_id;
message.save();
};
|
import Services from '../src/lib/services';
const _ = require('lodash');
require('db-migrate-mysql');
const expect = require('unexpected');
const request = require('./request.func');
let rds;
class Email {
// eslint-disable-next-line
sendHtml() {
return Promise.resolve();
}
}
class Slack {
// eslint-disable-next-line
sendAppUpdate() {
return Promise.resolve();
}
}
export default class FuncTestServices extends Services {
// eslint-disable-next-line class-methods-use-this
getEmail() {
return new Email();
}
// eslint-disable-next-line class-methods-use-this
getSlack() {
return new Slack();
}
getMysql() {
if (!rds) {
// eslint-disable-next-line global-require
rds = require('serverless-mysql')({
config: {
host: this.getEnv('RDS_HOST'),
user: this.getEnv('RDS_USER'),
password: this.getEnv('RDS_PASSWORD'),
database: this.getEnv('RDS_DATABASE'),
ssl: this.getEnv('RDS_SSL'),
port: this.getEnv('RDS_PORT'),
multipleStatements: true,
},
});
}
return rds;
}
static async initDb() {
await rds.query(
'INSERT IGNORE INTO vendors SET id=?, name=?, address=?, email=?, isPublic=?',
[process.env.FUNC_VENDOR, 'test', 'test', process.env.FUNC_USER_EMAIL, 0],
);
await rds.query('DELETE FROM appVersions WHERE vendor=?', [process.env.FUNC_VENDOR]);
}
static async login() {
const res = await expect(request({
method: 'post',
url: `${_.get(process.env, 'API_ENDPOINT')}/auth/login`,
responseType: 'json',
data: {
email: process.env.FUNC_USER_EMAIL,
password: process.env.FUNC_USER_PASSWORD,
},
}), 'to be fulfilled');
expect(_.get(res, 'status'), 'to be', 200);
expect(_.get(res, 'data'), 'to have key', 'token');
return _.get(res, 'data.token');
}
static async cleanIconsFromS3(appId) {
const s3 = Services.getS3();
const data = await s3.listObjects({ Bucket: process.env.S3_BUCKET, Prefix: `${appId}/` }).promise();
if (data && _.has(data, 'Contents')) {
const promises = [];
_.each(data.Contents, (file) => {
promises.push(s3.deleteObject({ Bucket: process.env.S3_BUCKET, Key: file.Key }).promise());
});
return Promise.all(promises);
}
return Promise.resolve();
}
}
|
#!/usr/bin/env node
var JavaScriptBuffer = require('../type-inference'),
fs = require('fs'),
clc = require('cli-color');
var filename = process.argv[2];
var text = fs.readFileSync(filename, {encoding:"utf8"});
var lines = text.split(/\r?\n|\r/);
var buffer = new JavaScriptBuffer;
buffer.add(filename, text);
var groups = buffer.renamePropertyName(process.argv[3] || "add");
groups.forEach(function(group) {
console.log(clc.green("---------------- (" + group.length + ")"));
group.forEach(function (item,index) {
if (index > 0) console.log(clc.blackBright("--"));
var idx = item.start.line - 1;
var line = lines[idx];
line = clc.black(line.substring(0,item.start.column)) +
clc.red(line.substring(item.start.column, item.end.column)) +
clc.black(line.substring(item.end.column));
console.log(clc.black(lines[idx-1]) || '');
console.log(line);
console.log(clc.black(lines[idx+1]) || '');
});
});
console.log(clc.green("----------------"));
|
var espeak = require('node-espeak');
espeak.initialize();
espeak.onVoice(function(wav, samples, samplerate) {
});
espeak.speak("hello world!");
|
'use strict';
/**
* Module dependencies.
*/
var express = require('express'),
consolidate = require('consolidate'),
mongoStore = require('connect-mongo')(express),
flash = require('connect-flash'),
helpers = require('view-helpers'),
assetmanager = require('assetmanager'),
config = require('../config/config');
var console = require('../utils/easy-logger')('express.js');
module.exports = function(app, passport, db) {
app.set('showStackError', true);
// Prettify HTML
app.locals.pretty = true;
// cache=memory or swig dies in NODE_ENV=production
app.locals.cache = 'memory';
// Should be placed before express.static
// To ensure that all assets and data are compressed (utilize bandwidth)
app.use(express.compress({
filter: function(req, res) {
return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
},
// Levels are specified in a range of 0 to 9, where-as 0 is
// no compression and 9 is best compression, but slowest
level: 9
}));
// Only use logger for development environment
if (process.env.NODE_ENV === 'development') {
app.use(express.logger('dev'));
}
// assign the template engine to .html files
app.engine('html', consolidate[config.templateEngine]);
// set .html as the default extension
app.set('view engine', 'html');
// Set views path, template engine and default layout
app.set('views', config.root + '/odin-front/app/views');
// Enable jsonp
app.enable('jsonp callback');
app.configure(function() {
// The cookieParser should be above session
app.use(express.cookieParser());
// Request body parsing middleware should be above methodOverride
app.use(express.urlencoded());
app.use(express.json());
app.use(express.methodOverride());
// Import your asset file
var assets = require('./../config/assets.json');
assetmanager.init({
js: assets.js,
css: assets.css,
debug: (process.env.NODE_ENV !== 'production'),
webroot: 'odin-front/public'
});
// Add assets to local variables
app.use(function (req, res, next) {
res.locals({
assets: assetmanager.assets
});
next();
});
// Express/Mongo session storage
app.use(express.session({
secret: config.sessionSecret,
store: new mongoStore({
db: db.connection.db,
collection: config.sessionCollection
})
}));
// Dynamic helpers
app.use(helpers(config.app.name));
// Use passport session
app.use(passport.initialize());
app.use(passport.session());
// Connect flash for flash messages
app.use(flash());
// Routes should be at the last
app.use(app.router);
// Setting the fav icon and static folder
app.use(express.favicon());
app.use(express.static(config.root + '/odin-front/public'));
// Assume "not found" in the error msgs is a 404. this is somewhat
// silly, but valid, you can do whatever you like, set properties,
// use instanceof etc.
app.use(function(err, req, res, next) {
// Treat as 404
if (~err.message.indexOf('not found')) return next();
// Log it
console.error(err.stack);
// Error page
res.status(500).render('500', {
error: err.stack
});
});
// Assume 404 since no middleware responded
app.use(function(req, res) {
res.status(404).render('404', {
url: req.originalUrl,
error: 'Not found'
});
});
});
};
|
// @flow
import { transformFileSync, type babel } from 'babel-core';
import pluginReactIntl from 'babel-plugin-react-intl';
import pluginReactIntlAuto from 'babel-plugin-react-intl-auto';
import pathOr from 'ramda/src/pathOr';
import compose from 'ramda/src/compose';
import type { AbsolutePath } from '../../../../types';
import type { Config } from '../../../config';
import log from '../../../log';
import type { MessageDescriptorsFromFile } from './extract';
const outputBabelFromFabs = (fabs: AbsolutePath, config: Config): babel.BabelFileResult => {
const plugins = [pluginReactIntl];
if (config.reactIntlAutoConfig) {
plugins.unshift([pluginReactIntlAuto, config.reactIntlAutoConfig]);
}
try {
return transformFileSync(fabs, { plugins });
} catch (err) {
log.error(err);
throw err;
}
};
const armdFromFabs: MessageDescriptorsFromFile = compose(
pathOr([], ['metadata', 'react-intl', 'messages']),
outputBabelFromFabs,
);
export default armdFromFabs;
|
// @flow
import getKeys from "./getKeys";
import type {Composite} from "./types";
/**
* Returns true if composite has no own enumerable keys (is empty) or false
* otherwise
*/
const isEmpty = (composite: Composite): boolean =>
getKeys(composite).length === 0;
export default isEmpty;
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.2.3.6-3-29
description: >
Object.defineProperty - 'enumerable' property in 'Attributes' is
own accessor property that overrides an inherited accessor
property (8.10.5 step 3.a)
includes: [runTestCase.js]
---*/
function testcase() {
var obj = {};
var accessed = false;
var proto = {};
Object.defineProperty(proto, "enumerable", {
get: function () {
return false;
}
});
var ConstructFun = function () { };
ConstructFun.prototype = proto;
var child = new ConstructFun();
Object.defineProperty(child, "enumerable", {
get: function () {
return true;
}
});
Object.defineProperty(obj, "property", child);
for (var prop in obj) {
if (prop === "property") {
accessed = true;
}
}
return accessed;
}
runTestCase(testcase);
|
this.NesDb = this.NesDb || {};
NesDb[ 'EFA19C34C9DC95F7511AF979CAD72884A6746A3B' ] = {
"$": {
"name": "Arkanoid",
"altname": "アルカノイド",
"class": "Licensed",
"subclass": "3rd-Party",
"catalog": "TFC-AN-5400-10",
"publisher": "Taito",
"developer": "Taito",
"region": "Japan",
"players": "1",
"date": "1986-12-26"
},
"peripherals": [
{
"device": [
{
"$": {
"type": "arkanoid",
"name": "Vaus Controller"
}
}
]
}
],
"cartridge": [
{
"$": {
"system": "Famicom",
"crc": "D89E5A67",
"sha1": "EFA19C34C9DC95F7511AF979CAD72884A6746A3B",
"dump": "ok",
"dumper": "bootgod",
"datedumped": "2007-06-29"
},
"board": [
{
"$": {
"type": "TAITO-CNROM",
"pcb": "FC-010",
"mapper": "3"
},
"prg": [
{
"$": {
"size": "32k",
"crc": "35893B67",
"sha1": "7BB46BD1070F09DBBBA3AA9A05E6265FCF9A3376"
}
}
],
"chr": [
{
"$": {
"size": "16k",
"crc": "C5789B20",
"sha1": "58551085A755781030EAFA8C0E9238C9B1A50F5B"
}
}
],
"chip": [
{
"$": {
"type": "74xx161"
}
}
],
"pad": [
{
"$": {
"h": "0",
"v": "1"
}
}
]
}
]
}
],
"gameGenieCodes": [
{
"name": "Player 1 start with 1 life",
"codes": [
[
"PAOPUGLA"
]
]
},
{
"name": "Player 1 start with 6 lives",
"codes": [
[
"TAOPUGLA"
]
]
},
{
"name": "Player 1 start with 9 lives",
"codes": [
[
"PAOPUGLE"
]
]
},
{
"name": "Infinite lives, players 1 & 2",
"codes": [
[
"OZNEATVK"
]
]
},
{
"name": "Player 1 start at level 5",
"codes": [
[
"IAOONGPA"
]
]
},
{
"name": "Player 1 start at level 10",
"codes": [
[
"ZAOONGPE"
]
]
},
{
"name": "Player 1 start at level 15",
"codes": [
[
"YAOONGPE"
]
]
},
{
"name": "Player 1 start at level 20",
"codes": [
[
"GPOONGPA"
]
]
},
{
"name": "Player 1 start at level 25",
"codes": [
[
"PPOONGPE"
]
]
},
{
"name": "Player 1 start at level 30",
"codes": [
[
"TPOONGPE"
]
]
},
{
"name": "No bat enhancement capsules",
"codes": [
[
"SXNAIAAX"
]
]
},
{
"name": "No lasers",
"codes": [
[
"SXVATAAX"
]
]
}
]
};
|
// Karma configuration
// Generated on Tue Jan 06 2015 16:30:03 GMT-0800 (PST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: 'browser',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha'],
// list of files / patterns to load in the browser
files: [
{pattern: 'fullnode.js', watched: true, included: false, served: true},
{pattern: 'fullnode-worker.js', watched: true, included: false, served: true},
'tests.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_DEBUG,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Firefox', 'Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true
});
};
|
var searchData=
[
['screeningsolver',['ScreeningSolver',['../classhdim_1_1internal_1_1_screening_solver.html',1,'hdim::internal']]],
['sgd',['SGD',['../classhdim_1_1hdim_1_1_s_g_d.html',1,'hdim::hdim']]],
['sgd_5fsr',['SGD_SR',['../classhdim_1_1hdim_1_1_s_g_d___s_r.html',1,'hdim::hdim']]],
['softthres',['SoftThres',['../structhdim_1_1_soft_thres.html',1,'hdim']]],
['solver',['Solver',['../classhdim_1_1internal_1_1_solver.html',1,'hdim::internal']]],
['solver',['Solver',['../classocl_1_1internal_1_1_solver.html',1,'ocl::internal']]],
['solver',['Solver',['../classhdim_1_1vcl_1_1internal_1_1_solver.html',1,'hdim::vcl::internal']]],
['solver_5fd',['Solver_d',['../classhdim_1_1hdim_1_1_solver__d.html',1,'hdim::hdim']]],
['solver_5ff',['Solver_f',['../classhdim_1_1hdim_1_1_solver__f.html',1,'hdim::hdim']]],
['srsolver_5fd',['SRSolver_d',['../classhdim_1_1hdim_1_1_s_r_solver__d.html',1,'hdim::hdim']]],
['srsolver_5ff',['SRSolver_f',['../classhdim_1_1hdim_1_1_s_r_solver__f.html',1,'hdim::hdim']]],
['subgradientsolver',['SubGradientSolver',['../classhdim_1_1vcl_1_1internal_1_1_sub_gradient_solver.html',1,'hdim::vcl::internal']]],
['subgradientsolver',['SubGradientSolver',['../classhdim_1_1internal_1_1_sub_gradient_solver.html',1,'hdim::internal']]],
['subgradientsolver',['SubGradientSolver',['../classhdim_1_1ocl_1_1internal_1_1_sub_gradient_solver.html',1,'hdim::ocl::internal']]],
['supportsift',['SupportSift',['../structhdim_1_1_support_sift.html',1,'hdim']]],
['swig_5fcast_5finfo',['swig_cast_info',['../structswig__cast__info.html',1,'']]],
['swig_5fconst_5finfo',['swig_const_info',['../structswig__const__info.html',1,'']]],
['swig_5fglobalvar',['swig_globalvar',['../structswig__globalvar.html',1,'']]],
['swig_5fmodule_5finfo',['swig_module_info',['../structswig__module__info.html',1,'']]],
['swig_5ftype_5finfo',['swig_type_info',['../structswig__type__info.html',1,'']]],
['swig_5fvarlinkobject',['swig_varlinkobject',['../structswig__varlinkobject.html',1,'']]],
['swigptr_5fpyobject',['SwigPtr_PyObject',['../classswig_1_1_swig_ptr___py_object.html',1,'swig']]],
['swigpyclientdata',['SwigPyClientData',['../struct_swig_py_client_data.html',1,'']]],
['swigpyobject',['SwigPyObject',['../struct_swig_py_object.html',1,'']]],
['swigpypacked',['SwigPyPacked',['../struct_swig_py_packed.html',1,'']]],
['swigvar_5fpyobject',['SwigVar_PyObject',['../structswig_1_1_swig_var___py_object.html',1,'swig']]]
];
|
(function () {
'use strict';
angular
.module('openSenseMapApp')
.controller('EditBoxLocationController', EditBoxLocationController);
EditBoxLocationController.$inject = ['$scope', 'boxData', 'notifications', 'AccountService', 'Box'];
function EditBoxLocationController ($scope, boxData, notifications, AccountService, Box) {
var vm = this;
vm.editMarkerInput = {};
vm.originalPosition = {};
vm.save = save;
vm.resetPosition = resetPosition;
activate();
////
function activate () {
var icon = '';
var color = '';
if (boxData.exposure === 'indoor' || boxData.exposure === 'outdoor') {
icon = 'cube';
color = 'green';
}
if (boxData.exposure === 'mobile') {
icon = 'rocket';
color = 'blue';
}
var marker = L.AwesomeMarkers.icon({
type: 'awesomeMarker',
prefix: 'fa',
icon: icon,
markerColor: color
});
var lat = parseFloat(boxData.currentLocation.coordinates[1].toFixed(6));
var lng = parseFloat(boxData.currentLocation.coordinates[0].toFixed(6));
vm.boxPosition = {
layerName: 'registration',
lng: lng,
lat: lat,
latLng: [lat, lng],
height: boxData.currentLocation.coordinates[2],
draggable: true,
zoom: 17,
icon: marker
};
angular.copy(vm.boxPosition, vm.originalPosition);
vm.editMarker = {
m1: angular.copy(vm.boxPosition)
};
angular.copy(vm.boxPosition, vm.editMarkerInput);
}
function save () {
return AccountService.updateBox(boxData._id, { location: vm.editMarker.m1 })
.then(function (response) {
angular.copy(new Box(response.data), boxData);
notifications.addAlert('info', 'NOTIFICATION_BOX_UPDATE_SUCCESS');
})
.catch(function () {
notifications.addAlert('danger', 'NOTIFICATION_BOX_UPDATE_FAILED');
});
}
function resetPosition () {
vm.editMarker = { m1: angular.copy(vm.originalPosition) };
vm.editMarkerInput = angular.copy(vm.originalPosition);
vm.editMarker.m1.draggable = true;
}
function setCoordinates (coords) {
vm.editMarker = {
m1: angular.copy(vm.originalPosition)
};
var lng = parseFloat(coords.lng.toFixed(6));
var lat = parseFloat(coords.lat.toFixed(6));
vm.editMarker.m1.lng = lng;
vm.editMarker.m1.lat = lat;
vm.editMarker.m1.latLng = [lat, lng];
vm.editMarker.m1.height = coords.height;
vm.editMarkerInput.lng = vm.editMarker.m1.lng;
vm.editMarkerInput.lat = vm.editMarker.m1.lat;
}
////
$scope.$on('osemMapClick.map_edit', function (e, args) {
setCoordinates(args.latlng);
});
$scope.$on('osemMarkerDragend.map_edit', function (e, args) {
setCoordinates(args.target._latlng);
});
$scope.$watchCollection('location.editMarkerInput', function (newValue) {
if (newValue && newValue.lat && newValue.lng) {
setCoordinates({
lng: newValue.lng,
lat: newValue.lat,
height: newValue.height,
});
}
});
}
})();
|
function foo<T = string>() {}
|
/**
* For proper JSON escaping for use as JS object literal in a <script> tag
* For your education: http://timelessrepo.com/json-isnt-a-javascript-subset
*
* Javascript implementation of http://golang.org/pkg/encoding/json/#HTMLEscape
*/
'use strict';
var ESCAPE_LOOKUP = {
'&': '\\u0026',
'>': '\\u003e',
'<': '\\u003c',
'\u2028': '\\u2028',
'\u2029': '\\u2029'
};
var ESCAPE_REGEX = /[&><\u2028\u2029]/g;
function escaper(match) {
return ESCAPE_LOOKUP[match];
}
module.exports = function(obj) {
return JSON.stringify(obj).replace(ESCAPE_REGEX, escaper);
};
|
import styled from 'styled-components';
import Stones from '../Stones';
const StyledStones = styled(Stones)`
display: inline-block;
width: 100%;
min-height: 30px;
div {
display: inline-block;
width: 20px;
height: 20px;
border: 1px solid #000000;
border-radius: 50%;
margin: 0 1px 0 0;
padding: 0;
text-align: center;
font-size: 16px;
line-height: 20px;
}
${props => typeof props.stoneClick == 'function' ? 'div:hover { cursor: pointer; }' : ''}
div.black {
color: white;
background: black;
}
div.red {
color: white;
background: red;
}
div.blue {
color: white;
background: blue;
}
div.white {
color: black;
background: white;
}
div.disabled {
color: #AAA;
background: #666;
}
div.plus,
div.and,
div.equals {
color: black;
background: white;
border: none;
}
`;
export default StyledStones;
|
var plain = require('./workers/plain.js');
var NodeMover = require('./modules/NodeMover').NodeMover;
var PixiGraphics = require('./modules/PixiGraphics').PixiGraphics;
module.exports.main = function () {
var _layoutIterations = 1000;
var _layoutStepsPerMessage = 25;
//--simple frame-rate display for renders vs layouts
var _counts = {renders: 0, layouts: 0, renderRate: 0, layoutRate: 0};
var $info = $('<div>').appendTo('body');
var startTime = new Date();
var _updateInfo = function () {
var endTime = new Date();
var timeDiff = (endTime - startTime) / 1000;
if (_counts.layouts < _layoutIterations) {
_counts.layoutRate = _counts.layouts / timeDiff;
}
_counts.renderRate = _counts.renders / timeDiff;
$info.text('Renders: ' + _counts.renders + ' (' + Math.round(_counts.renderRate) + ') | Layouts: ' + _counts.layouts + ' (' + Math.round(_counts.layoutRate) + ')');
};
var _nodeMovers = {};
$.getJSON('data/graph.json', function (jsonData) {
jsonData.nodes.forEach(function (node, i) {
var nodeMover = new NodeMover();
nodeMover.data('id', node.id);
_nodeMovers[node.id] = nodeMover;
});
var _layoutPositions = {};
function updatePos(ev) {
_layoutPositions = ev.data;
_counts.layouts = _layoutPositions.i;
};
plain(jsonData);
var graphics = new PixiGraphics(0.75, jsonData, function () {
$.each(_nodeMovers, function (id, nodeMover) {
if (_layoutPositions.nodePositions) {
nodeMover.position(_layoutPositions.nodePositions[id]);
nodeMover.animate();
}
});
return _nodeMovers;
});
function renderFrame() {
plain.step(updatePos);
graphics.renderFrame();
_counts.renders++;
_updateInfo();
requestAnimFrame(renderFrame);
}
// begin animation loop:
renderFrame();
});
};
|
function SignupController()
{
// redirect to homepage when cancel button is clicked //
$('#account-form-btn1').click(function(){ window.location.href = '/#section-3';});
// redirect to homepage on new account creation, add short delay so user can read alert window //
$('.modal-alert #ok').click(function(){ setTimeout(function(){window.location.href = '/#';}, 300)});
}
|
'use strict';
function posix(path) {
return path.charAt(0) === '/';
};
function win32(path) {
// https://github.com/joyent/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
var result = splitDeviceRe.exec(path);
var device = result[1] || '';
var isUnc = !!device && device.charAt(1) !== ':';
// UNC paths are always absolute
return !!result[2] || isUnc;
};
module.exports = process.platform === 'win32' ? win32 : posix;
module.exports.posix = posix;
module.exports.win32 = win32;
//# sourceMappingURL=index-compiled.js.map
|
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import uiBoostrap from 'angular-ui-bootstrap';
import angularJwt from 'angular-jwt';
let librariesModules = angular.module('app.libraries', [
uiRouter,
uiBoostrap,
angularJwt
]);
export default librariesModules;
|
ar_menu=new Array('downloaded','featured','popular','new','free','random');
str=1;
id_component=0;
ctype_component="";
flag_auto=true;
res="";
function zcomponent(id,ctype,page)
{
if(id!=id_component)
{
document.getElementById('home_boxes').innerHTML = "";
}
str=page;
var req = new JsHttpRequest();
// Code automatically called on load finishing.
req.onreadystatechange = function() {
if (req.readyState == 4) {
for(i=0;i<ar_menu.length;i++)
{
if(ar_menu[i]==ctype)
{
document.getElementById('menu_'+ctype).className="tact";
}
else
{
document.getElementById('menu_'+ar_menu[i]).className="tact2";
}
}
if(page==1)
{
document.getElementById('home_boxes').innerHTML =req.responseText;
res=req.responseText;
check_carts('');
}
else
{
document.getElementById('home_boxes').innerHTML = document.getElementById('home_boxes').innerHTML + req.responseText;
res=req.responseText;
check_carts('');
}
$('#home_boxes').masonry({
itemSelector: '.home_box'
});
$('#home_boxes').masonry('reload') ;
$('.home_preview').each(function(){
$(this).animate({opacity:'1.0'},1);
$(this).mouseover(function(){
$(this).stop().animate({opacity:'0.6'},600);
});
$(this).mouseout(function(){
$(this).stop().animate({opacity:'1.0'},300);
});
$(".hb_cart").mouseover(function(){
$(this).stop().animate({ opacity: 1}, 600);
});
$(".hb_cart").mouseout(function(){
$(this).stop().animate({ opacity: 0.5}, 600);
});
$(".hb_lightbox").mouseover(function(){
$(this).stop().animate({ opacity: 1}, 600);
});
$(".hb_lightbox").mouseout(function(){
$(this).stop().animate({ opacity: 0.5}, 600);
});
$(".hb_free").mouseover(function(){
$(this).stop().animate({ opacity: 1}, 600);
});
$(".hb_free").mouseout(function(){
$(this).stop().animate({ opacity: 0.5}, 600);
});
});
}
}
req.open(null, 'members/component_light2.php', true);
req.send( {id: id, ctype: ctype,str: str} );
str++;
id_component=id;
ctype_component=ctype;
}
$(document).ready(function(){
$(window).scroll(function(){
if($(document).height() - $(window).height() - $(window).scrollTop() <150)
{
if(str!=1 && flag_auto)
{
flag_auto=false;
if(res!="")
{
//zcomponent(id_component,ctype_component,str);
}
}
}
else
{
flag_auto=true;
}
});
$('#slides').superslides({
slide_easing: 'easeInOutCubic',
slide_speed: 800,
pagination: false,
hashchange: true,
scrollable: false,
inherit_width_from: '#wrapper_slideshow',
inherit_height_from: '#wrapper_slideshow',
animation:'fade',
play:5000
});
$(".prev1").css({ opacity: 0.5});
$(".next1").css({ opacity: 0.5});
$(".next1").mouseover(function(){
$(this).stop().animate({ opacity: 1}, 600);
});
$(".next1").mouseout(function(){
$(this).stop().animate({ opacity: 0.5}, 600);
});
$(".prev1").mouseover(function(){
$(this).stop().animate({ opacity: 1}, 600);
});
$(".prev1").mouseout(function(){
$(this).stop().animate({ opacity: 0.5}, 600);
});
});
|
import Ember from 'ember';
import config from './config/environment';
import googlePageview from './mixins/google-pageview';
const Router = Ember.Router.extend(googlePageview, {
location: config.locationType
});
Router.map(function() {
this.route('routes', function(){
this.route('route', { path: "/:route-id" });
this.route('loading');
});
this.route('stops', function(){
this.route('by-frequency');
this.route('walkshed');
this.route('transitshed');
this.route('stop', { path: "/:stop-id" });
});
this.route('operators', function(){
this.route('service-areas');
this.route('operator', { path: "/:operator-id" });
});
this.route('route-stop-patterns', function(){
});
this.route('error', { path: "*path" });
this.route('isochrones');
this.route('map-matching');
});
export default Router;
|
import assert from 'assert'
import { planetposition, julian, sexagesimal as sexa } from '../src/index.js'
import data from '../data/index.js'
describe('#planetposition', function () {
describe('position2000', function () {
it('Mars at 2415020.0', function () {
// Mars 1899 spherical data from vsop87.chk.
const jd = 2415020.0
const planet = new planetposition.Planet(data.mars)
const res = planet.position2000(jd)
assert.strictEqual(res.lon, 5.018579265623366)
assert.strictEqual(res.lat, -0.02740734998738619)
assert.strictEqual(res.range, 1.421877771845356)
})
it('Mars at 2415020.0 VSOP D', function () {
// Mars 1899 spherical data from vsop87.chk.
const jd = 2415020.0
const planet = new planetposition.Planet(data.vsop87Dmars)
const res = planet.position2000(jd)
assert.strictEqual(res.lon, 5.01857925809491)
assert.strictEqual(res.lat, -0.02740737901167283)
assert.strictEqual(res.range, 1.4218777705060395)
})
it('Venus at 1992-12-20', function () {
// Example 32.a, p. 219
const jd = julian.CalendarGregorianToJD(1992, 12, 20)
const planet = new planetposition.Planet(data.venus)
const res = planet.position2000(jd)
assert.strictEqual(res.lon, 0.45749253478276586) // rad
assert.strictEqual(res.lat, -0.045729822980889484) // rad
assert.strictEqual(res.range, 0.7246016739689574) // AU
})
})
describe('position', function () {
it('Venus at 1992-12-20', function () {
// Example 32.a, p. 219
const jd = julian.CalendarGregorianToJD(1992, 12, 20)
const planet = new planetposition.Planet(data.venus)
const res = planet.position(jd)
assert.strictEqual(new sexa.Angle(res.lon).toDegString(5), '26°.11412')
assert.strictEqual(new sexa.Angle(res.lat).toDegString(5), '-2°.6206')
assert.strictEqual(res.range, 0.7246016739689574)
})
it('Venus at 1992-12-20 VSOPD', function () {
// Example 32.a, p. 219
const jd = julian.CalendarGregorianToJD(1992, 12, 20)
const planet = new planetposition.Planet(data.vsop87Dvenus)
const res = planet.position(jd)
assert.strictEqual(new sexa.Angle(res.lon).toDegString(5), '26°.11412')
assert.strictEqual(new sexa.Angle(res.lat).toDegString(5), '-2°.6206')
assert.strictEqual(res.range, 0.7246016759555222)
})
})
describe('toFK5', function () {
it('Venus at 1992-12-20', function () {
// Meeus provides no worked example for the FK5 conversion given by
// formula 32.3, p. 219. This at least displays the result when applied
// to the position of Example 32.a on that page.
const jd = julian.CalendarGregorianToJD(1992, 12, 20)
const planet = new planetposition.Planet(data.venus)
const pos = planet.position(jd)
const fk5 = planetposition.toFK5(pos.lon, pos.lat, jd)
assert.strictEqual(new sexa.Angle(fk5.lon).toDegString(5), '26°.11409')
assert.strictEqual(new sexa.Angle(fk5.lat).toDegString(5), '-2°.6206')
})
})
})
|
//Pathway model
var FormModel = function () {
var self = this;
self.id = undefined;
self.name = undefined;
self.dataElements = []
ko.track(self);
self.previewForm = function(){
console.log('need to add form preview here')
window.location = '../../formDesign/show/' + self.id
}
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:3e0c436bb4be5a94bea0b2ce84121c3a8c6fbe226e7559f80cd0db5b4b93fdb0
size 17334
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
//Core
require('../../rxjs-extensions');
var core_1 = require('@angular/core');
var platform_browser_1 = require('@angular/platform-browser');
var forms_1 = require('@angular/forms');
var http_1 = require('@angular/http');
var app_routing_1 = require('./app.routing');
//Services
//Common Components
var page_footer_component_1 = require('../userinterface/page-footer.component');
var page_header_component_1 = require('../userinterface/page-header.component');
//Module Components
var app_component_1 = require('./app.component');
var home_content_component_1 = require('./home-content.component');
var AppModule = (function () {
function AppModule() {
}
AppModule = __decorate([
core_1.NgModule({
imports: [
platform_browser_1.BrowserModule,
forms_1.FormsModule,
forms_1.ReactiveFormsModule,
http_1.HttpModule,
app_routing_1.routing
],
declarations: [
app_component_1.AppComponent,
page_footer_component_1.PageFooterComponent,
page_header_component_1.PageHeaderComponent,
home_content_component_1.HomeContentComponent
],
bootstrap: [app_component_1.AppComponent]
}),
__metadata('design:paramtypes', [])
], AppModule);
return AppModule;
}());
exports.AppModule = AppModule;
//# sourceMappingURL=app.module.js.map
|
/**
* MIT License
*
* Copyright (c) 2017 ITGorillaz
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
'use strict';
const HttpException = require('./http-exception');
const HttpStatus = require('http-status-codes');
/**
* The GoneException class.
*
* This is a concrete class of the the HttpException class.
* It represents a gone http response.
*
* @author tommelo
*/
class GoneException extends HttpException {
/**
* The class constructor
*
* @param {Object} entity The object to be serialized as response body
* @param {Error} cause The error cause
*/
constructor(entity, cause) {
cause = cause || new Error('GoneException');
super(entity, HttpStatus.GONE, cause);
}
}
module.exports = GoneException;
|
(function($){
DashboardModel = Backbone.Model.extend({
url: "/sync"
});
SyncStatusModel = Backbone.Model.extend({
url: "/sync/status"
});
DeleteModel = Backbone.Model.extend();
DashboardView = Backbone.View.extend({
el: $("#form_block"),
events: {
"click .sync-now": "syncNow",
"click .delete-now": "deleteNow",
"deleteMessage": "showDeleteMessage",
},
showMessage: function(message) {
$("#message").animate({height: 90}, 5000);
$("#message span").text(message);
$("#message").animate({height: 0}, 1000);
},
showDeleteMessage: function(e, message) {
this.showMessage(message);
},
syncNow: function(e) {
var id = $(e.currentTarget).attr("data-id");
prepareAjaxCall();
this.syncmodel = new SyncStatusModel({
"idAttribute": id
});
this.model = new DashboardModel({
"idAttribute": id
});
this.model.save({}, {
success: function(model, response) {
$(e.currentTarget).text("Importing ...").show();
$("#progress").animate({height: 90}, 1000);
},
});
var syncmodel = this.syncmodel;
var self = this;
syncStatusInterval = setInterval(function(){
syncmodel.save({}, {
success: function(model, response) {
if (response.status != "error") {
$("#status").animate({width: response.progress + "%"}, 1000);
if (response.status === "running")
{
var insertedRows = response.inserted_rows;
var rowsToBeInserted = response.rows_to_be_inserted;
$("#progress span").text("Syncing: " + insertedRows + " out of " + rowsToBeInserted);
}
else if (response.status === "completed") {
clearInterval(syncStatusInterval);
var parent = $(e.currentTarget).parent();
parent.prev().text("0");
parent.prev().prev().text(response.last_synced);
parent.find(".all_synced").show();
$(e.currentTarget).hide();
$("#progress span").text(response.message);
$("#progress").animate({height: 0}, 1000);
}
}
else { // error
clearInterval(syncStatusInterval);
$(e.currentTarget).text("Sync Now");
self.showMessage(response.message);
$("#progress").animate({height: 0}, 1000);
}
}});
}, 5000);
},
deleteNow: function(e) {
if (confirm("Are you sure?")) {
var id = $(e.currentTarget).attr("data-id");
prepareAjaxCall();
this.model = new DeleteModel({
"id": id
});
this.model.url = "/sync/delete/" + id;
this.model.destroy();
$(e.currentTarget).parent().parent().remove();
this.$el.trigger("deleteMessage", ["Sync successfully removed."]);
}
}
});
window.view = new DashboardView;
// Dashboard functions
$(".tooltip").tooltip({ position: "top center", offset: [-3, 0]});
})(jQuery);
|
const Homeassistant = require('./../index')
// Connect to home-assistant
let ha = new Homeassistant({
host: '192.168.1.166'
})
ha.connect()
.then(() => {
// subscribe to state changes
ha.on('state:media_player.spotify', data => {
console.log(data)
})
// access current state
console.log(ha.state('sun.sun'))
// call a service
return ha.call({
domain: 'light',
service: 'turn_on'
})
})
.catch(console.error)
ha.on('connection', info => {
console.log('connection changed', info)
})
|
import config from './config';
describe('config', function(){
it('should exist', function(){
expect(config).to.be.an('object');
});
it('should contain the required keys', function(){
expect(config.ngxDirective).to.be.an('object');
expect(config.ngxDirective.name).to.be.a('string');
});
});
|
/**
* Created by tushar.mathur on 26/01/16.
*/
'use strict'
import test from 'ava'
import splitRange from '../src/splitRange'
test((t) => {
t.same(splitRange(100, 2), [[0, 49], [50, 100]])
t.same(splitRange(100, 3), [[0, 32], [33, 65], [66, 100]])
})
|
"use strict";
var Q = require("q");
var winston = require("winston");
var check = require('validator').check;
var Rule = function() {};
Rule.prototype.initializeFromJson = function(json) {
var self = this;
return Q.fcall(function() {
if(!json) throw new Error("JSON was not provided.");
if(!json.url) throw new Error("URL was not provided.");
check(json.url).isUrl();
if(!json.headers && !json.body) throw new Error("Either headers or a body must be present.");
self.rules = json;
winston.info("Set Rule: " + self.toString());
return self;
});
};
Rule.prototype.getUrl = function() {
return this.rules.url;
};
Rule.prototype.getHeaders = function() {
return this.rules.headers;
};
Rule.prototype.getBody = function() {
return this.rules.body;
};
Rule.prototype.getUrlReplacement = function() {
return this.rules.replaceUrls;
};
Rule.prototype.toString = function() {
return JSON.stringify(this.rules);
};
module.exports = Rule;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Tevent_1 = require("../../../events/Tevent");
class TagentEvent extends Tevent_1.Tevent {
constructor(type, eventData = null, cancelable = true) {
super(type, eventData, cancelable);
}
}
TagentEvent.FAILURE = "FAILURE";
exports.TagentEvent = TagentEvent;
//# sourceMappingURL=TagentEvent.js.map
|
var http = require("http");
var server = http.createServer(function(request, response) {
response.writeHead(200, { "Grip-Hold": "response",
"Grip-Channel": "mychannel",
"Grip-Timeout": "60"});
response.write('<b>Hello {{name}}</b>!');
response.end();
});
server.listen(8080);
console.log("Server is listening");
|
// ./index.js contains imports to redisClient, which should be mocked in unit tests.
jest.mock('src/lib/redisClient');
// Avoid loading src/lib/queue, which really connects to redis
jest.mock('src/lib/queues', () => ({}));
import { graphql } from 'graphql';
import { schema } from './';
/**
* Executes graphql query against the current GraphQL schema.
*
* Usage:
* const result = await gql`query{...}`(variable)
*
* @returns {(variable: Object, context: Object) => Promise<GraphQLResult>}
*/
function gql(query, ...substitutes) {
return (variables, context = {}) =>
graphql(
schema,
String.raw(query, ...substitutes),
null,
context,
variables
);
}
export { gql };
|
'use strict';
const fs = require('fs');
const path = require('path');
const test = require('ava');
const mockFs = require('mock-fs');
// const writeArtifacts = require('../../../lib/artifacts').writeArtifact;
const writeArtifacts = require('../../../lib');
test.afterEach(() => mockFs.restore());
test('should include symlink to file by default', async t => {
mockFs({
'file.txt': 'Hi!',
'source-dir': {
'symlink.txt': mockFs.symlink({
path: path.join('..', 'file.txt')
})
}
});
await writeArtifacts({ name: 'artifact-dir', patterns: 'source-dir/**' });
const link = fs.readlinkSync(path.join('artifact-dir', 'source-dir', 'symlink.txt'));
t.is(link, path.join('..', 'file.txt'));
});
test('should include symlink to dir by default', async t => {
mockFs({
'dir': {
'file.txt': 'Hi!'
},
'source-dir': {
'symdir': mockFs.symlink({
path: path.join('..', 'dir')
})
}
});
await writeArtifacts({ name: 'artifact-dir', patterns: 'source-dir/**' });
const link = fs.readlinkSync(path.join('artifact-dir', 'source-dir', 'symdir'));
t.is(link, path.join('..', 'dir'));
});
test('should follow symlink to file', async t => {
mockFs({
'file.txt': 'Hi!',
'source-dir': {
'symlink.txt': mockFs.symlink({
path: path.join('..', 'file.txt')
})
}
});
await writeArtifacts({ name: 'artifact-dir', patterns: 'source-dir/**' }, { followSymlinks: true });
const contents = fs.readFileSync(path.join('artifact-dir', 'source-dir', 'symlink.txt'), 'utf-8');
t.is(contents, 'Hi!');
});
test('should follow symlink to dir', async t => {
mockFs({
'dir': {
'file.txt': 'Hi!'
},
'source-dir': {
'symdir': mockFs.symlink({
path: path.join('..', 'dir')
})
}
});
await writeArtifacts({ name: 'artifact-dir', patterns: 'source-dir/**' }, { followSymlinks: true });
const contents = fs.readFileSync(path.join('artifact-dir', 'source-dir', 'symdir', 'file.txt'), 'utf-8');
t.is(contents, 'Hi!');
});
|
//filters.js eventsApp.filter('durations'
'use strict';
describe('durations', function(){
beforeEach(module("eventsApp"));
it('should return "Half Hour" when given a 1', inject(function(durationFilter){
expect(durationFilter(1)).toEqual('Half Hour');
}))
it('should return "1 Hour" when given a 2', inject(function(durationFilter){
expect(durationFilter(2)).toEqual('1 Hour');
}))
it('should return "Half Day" when given a 3', inject(function(durationFilter){
expect(durationFilter(3)).toEqual('Half Day');
}))
it('should return " Hour" when given a 4', inject(function(durationFilter){
expect(durationFilter(4)).toEqual('Full Day');
}))
})
|
function SeamCarver(ctx) {
var w = ctx.canvas.width;
var h = ctx.canvas.height;
var imgd = ctx.getImageData(0, 0, w, h);
var pix = imgd.data;
var img = [];
for (var i = 0; i < h; i++) {
img.push(new Uint32Array(w));
for (var j = 0; j < w; j++) {
img[i][j] = (pix[4 * i * w + 4 * j] << 16) + (pix[4 * i * w + 4 * j + 1] << 8) + pix[4 * i * w + 4 * j + 2];
}
}
this._img = img;
this._w = w;
this._h = h;
this._removedSeams = []
}
SeamCarver.prototype.energy = function (x, y) {
return this._energyInternal(x, y);
}
SeamCarver.prototype.imageData = function (ctx) {
var w = this._w;
var h = this._h;
var id = ctx.createImageData(w, h);
for (var i = 0; i < h; i++) {
for (var j = 0; j < w; j++) {
var color = this._img[i][j];
var r = color >> 16 & 0xFF;
var g = color >> 8 & 0xFF;
var b = color & 0xFF;
var index = 4 * w * i + 4 * j;
id.data[index] = r;
id.data[index + 1] = g;
id.data[index + 2] = b;
id.data[index + 3] = 255;
}
}
return id;
}
SeamCarver.prototype.findVerticalSeam = function () {
var w = this._w;
var h = this._h;
var edgeTo = [];
var distTo = [];
distTo.push(new Float32Array(w));
edgeTo.push(new Int16Array(w).fill(-1));
for (var i = 1; i < h; i++) {
distTo[i] = new Float32Array(w);
edgeTo[i] = new Int16Array(w).fill(-1);
for (var j = 0; j < w; j++) {
distTo[i][j] = Number.MAX_VALUE;
}
}
for (var i = 1; i < h; i++) {
var prevRow = distTo[i - 1];
for (var j = 1; j < w - 1; j++) {
var energy = this._energyInternal(j, i);
var dleft = prevRow[j - 1];
var dcenter = prevRow[j];
var dright = prevRow[j + 1];
if (dleft < dcenter && dleft < dright) {
distTo[i][j] = dleft + energy;
edgeTo[i][j] = j - 1;
}
else if (dcenter < dright) {
distTo[i][j] = dcenter + energy;
edgeTo[i][j] = j;
}
else {
distTo[i][j] = dright + energy;
edgeTo[i][j] = j + 1;
}
}
}
var min = Number.MAX_VALUE;
var minIndex = -1;
for (var i = 0; i < w; i++) {
if (distTo[h - 1][i] < min) {
min = distTo[h - 1][i];
minIndex = i;
}
}
distTo[h - 1][minIndex] = Number.MAX_VALUE;
var path = [minIndex];
var curIndex = minIndex;
for (var i = h - 1; i > 0; i--) {
var curIndex = edgeTo[i][curIndex];
path.push(curIndex);
}
return path;
}
SeamCarver.prototype.removeVerticalSeam = function () {
var seam = this.findVerticalSeam();
var h = this._h;
var res = [];
for (var i = 0; i < seam.length; i++) {
var col = seam[i];
res.push({ col: col, color: this._img[h - i - 1][col] });
for (var j = col; j < this._w - 1; j++) {
this._img[h - i - 1][j] = this._img[h - i - 1][j + 1];
}
}
this._w--;
this._removedSeams.push(res);
}
SeamCarver.prototype.restoreVerticalSeam = function () {
var w = this._w;
var h = this._h;
if (this._removedSeams.length == 0) {
return;
}
var seam = this._removedSeams.pop();
for (var i = 0; i < seam.length; i++) {
var row = this._img[h - i - 1];
var col = seam[i].col;
var color = seam[i].color;
for (var j = w - 1; j >= col; j--) {
row[j + 1] = row[j];
}
row[col] = color;
}
this._w++;
}
SeamCarver.prototype.width = function () {
return this._w;
}
SeamCarver.prototype._energyInternal = function (col, row) {
if (col == 0 || row == 0 || col == this._w - 1 || row == this._h - 1) {
return 1000;
}
var x1 = this._img[row][col - 1];
var x1r = x1 >> 16 & 0xFF;
var x1g = x1 >> 8 & 0xFF;
var x1b = x1 & 0xFF;
var x2 = this._img[row][col + 1];
var x2r = x2 >> 16 & 0xFF;
var x2g = x2 >> 8 & 0xFF;
var x2b = x2 & 0xFF;
var y1 = this._img[row - 1][col];
var y1r = y1 >> 16 & 0xFF;
var y1g = y1 >> 8 & 0xFF;
var y1b = y1 & 0xFF;
var y2 = this._img[row + 1][col];
var y2r = y2 >> 16 & 0xFF;
var y2g = y2 >> 8 & 0xFF;
var y2b = y2 & 0xFF;
var dx = (x1r - x2r) * (x1r - x2r) + (x1g - x2g) * (x1g - x2g) + (x1b - x2b) * (x1b - x2b);
var dy = (y1r - y2r) * (y1r - y2r) + (y1g - y2g) * (y1g - y2g) + (y1b - y2b) * (y1b - y2b);
return Math.sqrt(dx + dy);
}
|
import Ember from 'ember';
export default Ember.Mixin.create({
getMailsFromMailThreadByThreadId: function getMailsFromMailThreadByThreadId(mailThreadId) {
return this.store.find('mail-thread').then(function(mailThreads) {
return mailThreads.filterBy('id', mailThreadId)[0];
}).then(function(mailThread) {
return mailThread.get('mails');
});
},
getMailByIdFromMailThreads: function getMailByIdFromMailThreads(mailId){
return this.store.find('mail-thread').then(function(mailThreads){
var filteredMailToReturn;
mailThreads.forEach(function(mailThread){
var filteredMail = mailThread.get('mails').filterBy('id', +mailId)[0];
if( filteredMail ) {
filteredMailToReturn = filteredMail;
}
});
return filteredMailToReturn;
});
}
});
|
var express = require('express'),
logger = require('morgan'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
passport = require('passport');
module.exports = function (app, config) {
app.set('views', config.rootPath, '/server/views');
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({
secret: 'interval trainer unicorns',
name: 'jab-ita',
//store: sessionStore, // connect-mongo session store
proxy: true,
resave: true,
saveUninitialized: true
}));
//app.use(session({secret: 'interval trainer unicorns'}));
app.use(passport.initialize());
app.use(passport.session());
//app.use(express.static(config.rootPath, '/public'));
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
};
|
var assert = require('assert'),
cascade = require('../index');
var TestComplete = function(){}
TestComplete.prototype = new Error();
TestComplete.prototype.constructor = TestComplete;
var test = module.exports = {
// generates a macro context
"context" : function( initialVal, result ){
var funcs = Array.prototype.slice.call( arguments, 2 );
return {
topic : function(){
cascade.call(
{
stack : funcs.concat( test.done( this.callback ) ),
stackPosition : 0,
data : {}
},
initialVal
);
},
"ok" : function( topic ){
assert.deepEqual( topic, result );
}
};
},
"create" : function( initialArgs, resultArgs ){
var stack = Array.prototype.slice.call( arguments, 2 );
// if resultArgs is an array, add a final comparison function
if( resultArgs instanceof Array ){
stack.push( test.compareResult( resultArgs ) );
}
stack.push( test.complete );
return function(){
assert.throws( function(){
cascade.apply(
{
stack : stack,
stackPosition : 0,
data : {}
},
initialArgs
);
}, TestComplete );
}
},
"complete" : function(){
throw new TestComplete();
},
"passthrough" : function(){
arguments[ arguments.length - 1 ].apply(
this,
Array.prototype.slice.call( arguments, 0, arguments.length - 1 )
);
},
"increment" : function( by ){
return function( item, callback ){
callback( item + by );
};
},
"addData" : function( data ){
return function( item, next ){
//callback( item, data );
for( var prop in data ){
this.data[prop] = data[prop];
}
arguments[ arguments.length - 1 ].apply(
this,
Array.prototype.slice.call( arguments, 0, arguments.length - 1 )
);
}
},
"returnData" : function( item, next ){
arguments[ arguments.length - 1 ]( this.data );
},
"delay" : function( ms ){
return function( item, callback ){
setTimeout( function(){
callback( item );
}, ms );
}
},
"randomDelay" : function( min, max ){
return function( item, callback ){
setTimeout( function(){
callback( item );
}, Math.floor( Math.random() * (max - min) + min ) );
};
},
"log" : function( item, callback ){
var args = Array.prototype.slice.call( arguments, 0, arguments.length - 1 );
console.log( "Arguments:", args );
arguments[ arguments.length - 1 ].apply( this, args );
},
"tap" : function( func ){
return function(){
var args = Array.prototype.slice.call( arguments, 0, arguments.length - 1 ),
next = arguments[ arguments.length - 1 ];
func.apply( this, args );
next.apply( this, args );
}
},
"done" : function( cb ){
return function( item, callback ){
cb( null, item );
}
},
/**
* Asynchronous-compatible assertion
*/
"assertEqual" : function( value ){
return function( item, callback ){
assert.equal( item, value );
callback( item );
}
},
"assertDeepEqual" : function( obj ){
return function( item, callback ){
assert.deepEqual( item, obj );
callback( item );
}
},
"compareResult" : function( compareTo ){
return function(){
assert.deepEqual(
Array.prototype.slice.call( arguments, 0, arguments.length - 1 ),
compareTo
);
arguments[ arguments.length - 1 ].call(
this,
Array.prototype.slice.call( arguments, 0, arguments.length - 1 )
);
};
}
};
|
/**
* Super-Cache for Browser
*
* @author Zongmin Lei <leizongmin@gmail.com>
*/
var CacheManager = require('./lib/manager');
var MemoryStore = require('./lib/store/memory');
var LocalStore = require('./lib/store/local');
module.exports = exports = CacheManager;
exports.MemoryStore = MemoryStore;
exports.LocalStore = LocalStore;
exports.create = function (options) {
return new CacheManager(options);
};
// ADM mode
if (typeof define === 'function' && define.amd) {
define(function () {
return module.exports;
});
}
// Shim mode
if (typeof window !== 'undefined') {
window.SuperCache = module.exports;
}
|
module.exports = {
light: {
background1: 'rgba(227,227,227,.95)',
background2: 'rgba(204,204,204,.95)',
background2hover: 'rgba(208,208,208,.95)',
foreground1: 'rgba(105,105,105,.95)',
text1: 'rgba(36,36,36,.95)',
text2: 'rgba(87,87,87,.95)'
},
dark: {
background1: 'rgba(35,35,35,.95)',
background2: 'rgba(54,54,54,.95)',
background2hover: 'rgba(58,58,58,.95)',
foreground1: 'rgba(112,112,112,.95)',
text1: 'rgba(235,235,235,.95)',
text2: 'rgba(161,161,161,.95)'
}
}
|
class MetaProperty {
constructor (options) {
this.type = 'MetaProperty'
Object.assign(this, options)
}
}
module.exports = MetaProperty
|
"use strict";
var _getSert = require("../getsert");
var generateCode = require("../../../src/utils/code-generator");
class StorageDataUtil {
getSert(input) {
var ManagerType = require("../../../src/managers/master/storage-manager");
return _getSert(input, ManagerType, (data) => {
return {
code: data.code
};
});
}
getNewData() {
var Model = require('bateeq-models').master.Storage;
var data = new Model();
var code = generateCode();
data.code = code;
data.name = `name[${code}]`;
data.description = `storage description [${code}]`;
return Promise.resolve(data);
}
getRandomTestData() {
return this.getNewData()
.then((data) => {
return this.getSert(data);
});
}
getTestData() {
var data = {
code: 'UT/STO/01',
name: 'Storage Unit Test',
description: ''
};
return this.getSert(data);
}
getPackingTestData() {
var data = {
code: 'GDG.07',
name: 'Gudang Accesories',
description: ''
};
return this.getSert(data);
}
}
module.exports = new StorageDataUtil();
|
/*
Copyright 2008-2009 University of Cambridge
Copyright 2008-2009 University of Toronto
Licensed under the Educational Community License (ECL), Version 2.0 or the New
BSD license. You may not use this file except in compliance with one these
Licenses.
You may obtain a copy of the ECL 2.0 License and BSD License at
https://source.fluidproject.org/svn/LICENSE.txt
*/
/*global jQuery*/
var fluid = fluid || {};
(function ($) {
var selectOnFocus = false;
// Private functions.
var makeTabsSelectable = function (tablist) {
var tabs = tablist.children("li");
// Put the tablist in the tab focus order. Take each tab *out* of the tab order
// so that they can be navigated with the arrow keys instead of the tab key.
fluid.tabbable(tablist);
// When we're using the Windows style interaction, select the tab as soon as it's focused.
var selectTab = function (tabToSelect) {
if (selectOnFocus) {
tablist.tabs('select', tabs.index(tabToSelect));
}
};
// Make the tab list selectable with the arrow keys:
// * Pass in the items you want to make selectable.
// * Register your onSelect callback to make the tab actually selected.
// * Specify the orientation of the tabs (the default is vertical)
fluid.selectable(tablist, {
selectableElements: tabs,
onSelect: selectTab,
direction: fluid.a11y.orientation.HORIZONTAL
});
// Use an activation handler if we are using the "Mac OS" style tab interaction.
// In this case, we shouldn't actually select the tab until the Enter or Space key is pressed.
fluid.activatable(tablist, function (tabToSelect) {
if (!selectOnFocus) {
tablist.tabs('select', tabs.index(tabToSelect));
}
});
};
var addARIA = function (tablist, panelsId) {
var tabs = tablist.children("li");
var panels = $("#" + "panels" + " > div");
// Give the container a role of tablist
tablist.attr("role", "tablist");
// Each tab should have a role of Tab,
// and a "position in set" property describing its order within the tab list.
tabs.each (function(i, tab) {
$(tab).attr("role", "tab");
});
// Give each panel a role of tabpanel
panels.attr("role", "tabpanel");
// And associate each panel with its tab using the labelledby relation.
panels.each (function (i, panel) {
$(panel).attr("aria-labelledby", panel.id.split("Panel")[0] + "Tab");
});
};
// Public API.
fluid.accessibletabs = function (tabsId, panelsId) {
var tablist = $("#" + tabsId);
// Remove the anchors in the list from the tab order.
fluid.tabindex(tablist.find("a"), -1);
// Turn the list into a jQuery UI tabs widget.
tablist.tabs();
// Make them accessible.
makeTabsSelectable(tablist);
addARIA(tablist, panelsId);
};
// When the document is loaded, initialize our tabs.
$(function () {
selectOnFocus = false;
// Instantiate the tabs widget.
fluid.accessibletabs("tabs", "panels");
// Bind the select on focus link.
$("#selectOnFocusLink").click(function (evt) {
selectOnFocus = !selectOnFocus;
if (selectOnFocus) {
$(evt.target).text("Enabled");
} else {
$(evt.target).text("Disabled");
}
return false;
});
});
}) (jQuery);
|
import React from 'react';
import Examples from './Examples';
var node = document.getElementById('main');
window.render = function(){
React.render(<Examples />, node);
};
window.unmount = function() {
React.unmountComponentAtNode(node);
};
window.render();
|
;(function() {
'use strict';
var listOfProgrammingLanguages = {
restrict: 'E',
templateUrl: '/directives/tpl/cd-programming-languages-list',
bindings: {
programmingLanguages: '<'
},
controller: ['cdProgrammingLanguagesService', function (cdProgrammingLanguagesService) {
var ctrl = this;
cdProgrammingLanguagesService.get().then(function (data) {
var programmingLanguagesJSON = data.data;
_.each(ctrl.programmingLanguages, function (language, index) {
var lLanguage = _.find(programmingLanguagesJSON, {text: language.text});
if (!_.isUndefined(lLanguage)) {
ctrl.programmingLanguages[index].picture = lLanguage.image;
ctrl.programmingLanguages[index].caption = lLanguage.text;
ctrl.programmingLanguages[index].href = lLanguage.href;
}
});
});
}]
};
angular
.module('cpZenPlatform')
.component('programmingLanguagesList', listOfProgrammingLanguages);
}());
|
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || "Component";
}
export default getDisplayName;
|
// Ember Extensions
Ember.ArrayProxy.prototype.flatten = Array.prototype.flatten = function() {
var r = [];
this.forEach(function(el) {
r.push.apply(r, Ember.isArray(el) ? el.flatten() : [el]);
});
return r;
};
// jQuery Additions
jQuery.fn.exists = function() { return this.length > 0; };
|
/**
* Created by wangqi on 16/6/3.
*/
function ServiceValidationError(code, message, field) {
Error.captureStackTrace(this, this.constructor);
this.type = 'UserLevelServiceRequestError';
this.name = 'ServiceValidationError';
this.message = message || 'Unauthenticated Access Token';
this.code = code || 409;
this.field = field || 'unknown_field';
this.status = 409;
}
ServiceValidationError.prototype = Object.create(Error.prototype);
ServiceValidationError.prototype.constructor = ServiceValidationError;
module.exports = ServiceValidationError;
|
var _ = require('underscore')
, path = require('path')
, passport = require('passport')
, AuthCtrl = require('./controllers/auth')
, UserCtrl = require('./controllers/user')
, User = require('./models/User.js')
, userRoles = require('../client/scripts/routingConfig').userRoles
, accessLevels = require('../client/scripts/routingConfig').accessLevels;
var routes = [
// Views
{
path: '/partials/*',
httpMethod: 'GET',
middleware: [function (req, res) {
var requestedView = path.join('./', req.url);
res.render(requestedView);
}]
},
// Auth
{
path: '/api/v1/register',
httpMethod: 'POST',
middleware: [AuthCtrl.register]
},
{
path: '/api/v1/login',
httpMethod: 'POST',
middleware: [AuthCtrl.login]
},
{
path: '/api/v1/logout',
httpMethod: 'POST',
middleware: [AuthCtrl.logout]
},
// User resource
{
path: '/api/v1/users',
httpMethod: 'GET',
middleware: [UserCtrl.index],
accessLevel: accessLevels.admin_level
},
// All other get requests should be handled by AngularJS's client-side routing system
{
path: '/*',
httpMethod: 'GET',
middleware: [function(req, res) {
var role = userRoles.guest_role
, username = '';
if(req.user) {
role = req.user.role;
username = req.user.username;
}
res.cookie('user', JSON.stringify({
'username': username,
'role': role
}));
res.render('index');
}]
}
];
module.exports = function(app) {
_.each(routes, function(route) {
route.middleware.unshift(ensureAuthorized);
var args = _.flatten([route.path, route.middleware]);
switch(route.httpMethod.toUpperCase()) {
case 'GET':
app.get.apply(app, args);
break;
case 'POST':
app.post.apply(app, args);
break;
case 'PUT':
app.put.apply(app, args);
break;
case 'DELETE':
app.delete.apply(app, args);
break;
default:
throw new Error('Invalid HTTP method specified for route ' + route.path);
break;
}
});
}
function ensureAuthorized(req, res, next) {
var role;
if(!req.user) {
role = userRoles.guest_role;
} else {
role = req.user.role;
}
var accessLevel = _.findWhere(routes, { path: req.route.path, httpMethod: req.route.stack[0].method.toUpperCase() }).accessLevel || accessLevels.public_level;
if(!(accessLevel === "*") && !(accessLevel.indexOf(role) !== -1)) {
return res.send(403);
}
return next();
}
|
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = {
moduleType: 'locale',
name: 'gu',
dictionary: {},
format: {
days: ['રવિવાર', 'સોમવાર', 'મંગળવાર', 'બુધવાર', 'ગુરુવાર', 'શુક્રવાર', 'શનિવાર'],
shortDays: ['રવિ', 'સોમ', 'મંગળ', 'બુધ', 'ગુરુ', 'શુક્ર', 'શનિ'],
months: [
'જાન્યુઆરી', 'ફેબ્રુઆરી', 'માર્ચ', 'એપ્રિલ', 'મે', 'જૂન',
'જુલાઈ', 'ઑગસ્ટ', 'સપ્ટેમ્બર', 'ઑક્ટોબર', 'નવેમ્બર', 'ડિસેમ્બર'
],
shortMonths: [
'જાન્યુ', 'ફેબ્રુ', 'માર્ચ', 'એપ્રિલ', 'મે', 'જૂન',
'જુલાઈ', 'ઑગસ્ટ', 'સપ્ટે', 'ઑક્ટો', 'નવે', 'ડિસે'
],
date: '%d-%b-%Y'
}
};
|
import {TOGGLE_IS_VAT_PAYER} from '../actions';
export function isVATPayer(state = false, action) {
switch (action.type) {
case TOGGLE_IS_VAT_PAYER:
return !state;
default:
return state;
}
}
|
var gulp = require('gulp');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var eslint = require('gulp-eslint');
var coveralls = require('gulp-coveralls');
gulp.task('pre-test', function () {
return gulp.src(['lib/**/*.js', '!lib/micro-whalla.js', '!lib/helpers.js'])
.pipe(istanbul({ includeUntested: true }))
.pipe(istanbul.hookRequire());
});
gulp.task('test', ['lint', 'pre-test'], function () {
return gulp.src('test/*.test.js')
.pipe(mocha())
.pipe(istanbul.writeReports());
});
gulp.task('lint', function () {
return gulp.src(['**/*.js', '!node_modules/**', '!coverage/**'])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
gulp.task('coveralls', function () {
return gulp.src('coverage/**/lcov.info')
.pipe(coveralls());
});
gulp.task('default', ['test'], function () {
});
|
class TeaKnowledgeController {
constructor ($scope, $state, $compile, DTOptionsBuilder, DTColumnBuilder, API) {
'ngInject'
this.API = API
this.$state = $state
// let TeaKnowledges = this.API.service('teakns', this.API.all('users'))
let TeaKnowledges = this.API.service('teaknowledges', this.API.all('informs'))
TeaKnowledges.getList()
.then((response) => {
let dataSet = response.plain()
this.dtOptions = DTOptionsBuilder.newOptions()
.withOption('data', dataSet)
.withOption('createdRow', createdRow)
.withOption('responsive', true)
.withBootstrap()
this.dtColumns = [
DTColumnBuilder.newColumn('id').withTitle('ID'),
DTColumnBuilder.newColumn('title').withTitle('Title'),
// DTColumnBuilder.newColumn('content').withTitle('Content'),
DTColumnBuilder.newColumn(null).withTitle('Actions').notSortable()
.renderWith(actionsHtml)
]
this.displayTable = true
})
let createdRow = (row) => {
$compile(angular.element(row).contents())($scope)
}
let actionsHtml = (data) => {
return `
<a class="btn btn-xs btn-warning" ui-sref="app.teaknowledgeedit({teaknowledgeId: ${data.id}})">
<i class="fa fa-edit"></i>
</a>
 
<button class="btn btn-xs btn-danger" ng-click="vm.delete(${data.id})">
<i class="fa fa-trash-o"></i>
</button>`
}
}
delete (teaknowledgeId) {
let API = this.API
let $state = this.$state
swal({
title: '确认是否删除?',
text: '删除后将无法恢复!',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: '删除!',
closeOnConfirm: false,
showLoaderOnConfirm: true,
html: false
}, function () {
API.one('informs').one('teaknowledges', teaknowledgeId).remove()
.then(() => {
swal({
title: '删除!',
text: '好了,你已经删除掉TA了.',
type: 'success',
confirmButtonText: 'OK',
closeOnConfirm: true
}, function () {
$state.reload()
})
})
})
}
$onInit () {}
}
export const TeaKnowledgeComponent = {
templateUrl: './views/app/components/tea-knowledge/tea-knowledge.component.html',
controller: TeaKnowledgeController,
controllerAs: 'vm',
bindings: {}
}
|
'use strict';
/**
* @ngdoc function
* @name liteAppManagesystemApp.controller:AboutCtrl
* @description
* # AboutCtrl
* Controller of the liteAppManagesystemApp
*/
angular.module('liteAppManagesystemApp')
.controller('AboutCtrl', function ($scope) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
});
|
export const generateGuid = () => {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return `${s4() + s4()}-${s4()}${s4()}`;
};
export default {
generateGuid,
};
|
module.exports = require('./lib/Redback');
|
import React, { Component } from 'react';
import CatagoryBox1 from '../CatagoryBox1';
import { BgBox } from './style';
function BackgroundBox (props) {
const {bcolor} = props;
const {data} = props;
const cata = data.map((d,i) => <CatagoryBox1 data={d} key={i} />);
return (
<BgBox bcolor={bcolor}>
{cata}
</BgBox>
);
};
export default BackgroundBox;
|
var playState = {
create: function(){
var background = game.add.sprite(0, 0, 'cidade');
background.width = 1300;
background.height = 650;
graphics = game.add.graphics(0, 0);
groupCidade = game.add.group();
groupCidade.inputEnableChildren = true;
var x = 100;
for (var i = 0; i < 3; i++){
// Gera os retangulos que ficarão atras das imagens
graphics.beginFill(0xFFFFFF);
graphics.lineStyle(3, 0x05005e, 1);
graphics.drawRoundedRect(x, 200, 315, 190, 10);
graphics.endFill();
var button = groupCidade.create(x, 200, graphics.generateTexture());
button.tint = 0xff8800;
button.name = 'groupCidade-child-' + i;
x = x + 400;
}
graphics.destroy();
var cachorro = game.add.sprite(110, 210, 'cachorro');
cachorro.width = 300;
cachorro.height = 170;
// Desenha o gato e a borda da box
var gato = game.add.sprite(510, 210, 'gato');
gato.width = 300;
gato.height = 170;
// Desenha o passaro e a borda da box
var passaro = game.add.sprite(910, 210, 'passaro');
passaro.width = 300;
passaro.height = 170;
start();
// groupCidade.onChildInputDown.add(onDown, this);
// groupCidade.onChildInputOver.add(onOver, this);
// groupCidade.onChildInputOut.add(onOut, this);
function start(){
}
function onDown (sprite) {
sprite.tint = 0x00ff00;
}
function onOver (sprite) {
sprite.tint = 0xffff00;
}
function onOut (sprite) {
sprite.tint = 0xff8800;
// sprite.tint = Math.random() * 0xffffff;
}
},
update: function(){
},
start: function(int: id){
groupCidade.children[1].tint = 0x000000;
groupCidade.children[2].tint = 0x000000;
gato.tint = 0x000000;
passaro.tint = 0x000000;
background.tint = 0x888888;
},
Win: function(){
game.state.start('win');
}
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:d33a38aa03c6c04c3b54d84dbf40da10270e517a1f2ca5ed32486bd757d16cd0
size 455
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Exam Schema
*/
var GroupSchema = new Schema({
group_name: {//分组名称
type: String,
default: ''
},
group_type: { //分组类型
type: String,
default: '',
trim: true
},
group_created:{//分组数据入库时间(时间戳)
type: Date,
default: Date.now
},
group_desc:{//分组的描述
type: String,
default: '',
trim: true
}
});
mongoose.model('Group', GroupSchema);
|
/**
* Example
* @version 0.0.1
*/
var MetaReponse = require('./MetaResponse');
var MetaData = require('./MetaData');
var MetaError = require('./MetaError');
var data1 = new MetaData();
var mr = new MetaReponse();
data1.setId(3);
data1.setType('recipe');
data1.addAttribute('title', 'Risotto al funghi');
data1.addAttribute('time', '45mins');
data1.addLink('self', 'http://www.monsite.com/recipe/3');
data1.addLink('next', 'http://www.monsite.com/recipe/4');
data1.addLink('prev', 'http://www.monsite.com/recipe/2');
mr.addLink('self', 'http://www.monsite.com/');
mr.addLink('next', 'http://www.monsite.com/next');
mr.addData(data1.getResponse());
mr.addData(data1);
console.log(data1.getResponse());
console.log(mr.getResponse());
var error = new MetaError();
error
.setStatusCode(401)
.setStatus("401 Unauthorized");
var response = new MetaReponse();
response.addError(error);
console.log(response.getResponse().errors);
|
import { Class as Model } from 'meteor/jagi:astronomy';
import * as Errors from './errors.js';
export function init(config) {
config.collection = new Mongo.Collection(config.collectionName);
config.model = Model.create({
name: config.modelName,
collection: config.collection,
fields: config.modelFields,
});
config.saveMethod = 'save' + config.modelName;
config.removeMethod = 'remove' + config.modelName;
var methods = {};
methods[config.saveMethod] = saveDoc;
methods[config.removeMethod] = removeDoc;
Meteor.methods(methods);
let colFieldsFunc = function () {
result = [];
for (var i = 0; i < config.formFields.length; i++) {
if (config.formFields[i].colClass) {
result[i] = config.formFields[i];
}
}
return result;
}
config.colFields = colFieldsFunc();
}
export function saveDoc (doc) {
if ( !Meteor.userId() ) {
return;
}
try {
doc.save();
} catch (e) {
Errors.handle(e);
}
}
export function removeDoc (doc) {
if ( !Meteor.userId() ) {
return;
}
doc.remove();
}
|
"use strict";
/* tslint:disable */
var load_themed_styles_1 = require("@microsoft/load-themed-styles");
var styles = {};
load_themed_styles_1.loadStyles([{ "rawString": ".ms-FocusTrapZoneBoxExample{border:dashed 1px #ababab}.ms-FocusTrapComponent{border:#000 2px solid;padding:5px}" }]);
module.exports = styles;
/* tslint:enable */
//# sourceMappingURL=FocusTrapZone.Box.Example.scss.js.map
|
export default function VuxTableColumnDefinition (options) {
return {
...{
key: 'id',
label: 'Id',
isDisabled: false,
isHidden: false,
isSortable: false,
isSorting: false,
sortDirection: 'desc',
isFilterable: false,
displayComponent: null,
editComponent: null,
span: 1
},
...options
}
}
|
'use strict'
const MongoClient = require('mongodb').MongoClient
const muri = require('muri')
const chai = require('chai')
const expect = chai.expect
const assert = chai.assert
const chaiSubset = require('chai-subset')
chai.use(chaiSubset)
chai.should()
const stringConnection = 'mongodb://localhost:27017/lambda-mongo-crud-test'
const tableName = 'posts'
const Crud = require('./../lib/crud')
const PERMISSION = {
list: 'posts:list',
get: 'posts:get',
save: 'posts:save',
delete: 'posts:delete'
}
const ROLES = {
admin: {
can: [PERMISSION.save, PERMISSION.delete, PERMISSION.list, PERMISSION.get]
}
}
describe('MANY', () => {
before(async () => {
const { db: dbName } = muri(stringConnection)
const client = await MongoClient.connect(stringConnection, { useUnifiedTopology: true })
const collection = client.db(dbName).collection(tableName)
await collection.insertMany([{ title: "Title 1", code: 1 }, { title: "Title 2", code: 2 }, { title: "Title 3", code: 3 }])
await client.close()
})
after(async () => {
const { db: dbName } = muri(stringConnection)
const client = await MongoClient.connect(stringConnection, { useUnifiedTopology: true })
const collection = client.db(dbName).collection(tableName)
await collection.deleteMany()
await client.close()
})
const crud = new Crud(stringConnection, tableName, { role: 'admin', _id: 123 }, ROLES)
describe('list()', () => {
it('should return an array', (done) => {
crud.list({}, PERMISSION.list, {}, (err, docs) => {
expect(docs.length).to.be.equal(3)
done()
})
})
it('should return an array', (done) => {
const data = [
{ title: "Title 2", code: 2 },
{ title: "Title 3bis", code: 3 },
{ title: "Title 4", code: 4 },
{ title: "Title 5", code: 5 }
]
crud.upsertMany(data, "code", PERMISSION.save, {}, (err, result) => {
expect(result.nMatched).to.be.equal(2)
expect(result.nUpserted).to.be.equal(2)
crud.list({}, PERMISSION.list, {}, (err, docs) => {
expect(docs.length).to.be.equal(5)
done()
})
})
})
})
})
|
//= require ./src/module
//= require_tree ./src/services
//= require_tree ./src/controllers
//= require_tree ./src/directives
|
(function($){
$.applyBulkSelectTable = function(obj, settings) {
var lastClickedElement = null,
lastClickedChecked = false,
lastClickedIndex = null;
var applyClass = function(obj, className, checked) {
if(checked)
obj.addClass(className);
else
obj.removeClass(className);
};
obj.on('click', '.'+settings.selectAllClass, function(e) {
var checked = $(this).is(':checked'),
items = obj.find('.'+settings.checkboxClass);
items.prop('checked', checked);
if(checked)
items.parents(settings.parentTag).addClass(settings.selectedClass);
else
items.parents(settings.parentTag).removeClass(settings.selectedClass);
});
obj.on('click', '.'+settings.checkboxClass, function(e) {
var o = $(e.target);
clickingElement = o;
clickingChecked = o.is(':checked');
clickingIndex = o.parents(settings.parentTag).index();
applyClass(clickingElement.parents(settings.parentTag), settings.selectedClass, clickingChecked);
if(e.shiftKey && lastClickedElement!==null) {
var list,
start,
end;
if(lastClickedIndex < clickingIndex) {
start = lastClickedElement.parents(settings.parentTag);
end = clickingElement.parents(settings.parentTag);
list = start.nextUntil(end);
}
else if(lastClickedIndex > clickingIndex) {
start = lastClickedElement.parents(settings.parentTag);
end = clickingElement.parents(settings.parentTag);
list = start.prevUntil(end);
}
lastClickedElement.prop('checked', clickingChecked);
applyClass(start, settings.selectedClass, clickingChecked);
list.find('.'+settings.checkboxClass).prop('checked', clickingChecked);
applyClass(list, settings.selectedClass, clickingChecked);
obj.trigger(clickingChecked ? 'bulk-select' : 'bulk-deselect', {
'start': start,
'end': end,
'list': list,
'applied': Math.abs(clickingIndex-lastClickedIndex+1)
});
}
lastClickedElement = clickingElement;
lastClickedChecked = clickingChecked;
lastClickedIndex = clickingIndex;
});
};
$.fn.bulkSelectTable = function(options) {
var settings = $.extend({
selectAllClass: 'selectall',
checkboxClass: 'selectable',
selectedClass: 'selected',
parentTag: 'tr'
}, options);
return this.each(function(){
$.applyBulkSelectTable($(this), settings);
});
};
}(jQuery));
|
/**
* IconElement is often mixed into other classes to generate an icon.
* Icons are graphics, about the size of normal text. They are used to aid the user
* in locating a control or to convey information in a space-efficient way. See the
* [OOUI documentation on MediaWiki] [1] for a list of icons
* included in the library.
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
* the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
* the icon element be set to an existing icon instead of the one generated by this class, set a
* value using a jQuery selection. For example:
*
* // Use a <div> tag instead of a <span>
* $icon: $( '<div>' )
* // Use an existing icon element instead of the one generated by the class
* $icon: this.$element
* // Use an icon element from a child widget
* $icon: this.childwidget.$element
* @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a
* map of symbolic names. A map is used for i18n purposes and contains a `default` icon
* name and additional names keyed by language code. The `default` name is used when no icon is
* keyed by the user's language.
*
* Example of an i18n map:
*
* { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
* See the [OOUI documentation on MediaWiki] [2] for a list of icons included in the library.
* [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
*/
OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.$icon = null;
this.icon = null;
// Initialization
this.setIcon( config.icon || this.constructor.static.icon );
this.setIconElement( config.$icon || $( '<span>' ) );
};
/* Setup */
OO.initClass( OO.ui.mixin.IconElement );
/* Static Properties */
/**
* The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map
* is used for i18n purposes and contains a `default` icon name and additional names keyed by
* language code. The `default` name is used when no icon is keyed by the user's language.
*
* Example of an i18n map:
*
* { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
*
* Note: the static property will be overridden if the #icon configuration is used.
*
* @static
* @inheritable
* @property {Object|string}
*/
OO.ui.mixin.IconElement.static.icon = null;
/**
* The icon title, displayed when users move the mouse over the icon. The value can be text, a
* function that returns title text, or `null` for no title.
*
* The static property will be overridden if the #iconTitle configuration is used.
*
* @static
* @inheritable
* @property {string|Function|null}
*/
OO.ui.mixin.IconElement.static.iconTitle = null;
/* Methods */
/**
* Set the icon element. This method is used to retarget an icon mixin so that its functionality
* applies to the specified icon element instead of the one created by the class. If an icon
* element is already set, the mixin’s effect on that element is removed. Generated CSS classes
* and mixin methods will no longer affect the element.
*
* @param {jQuery} $icon Element to use as icon
*/
OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
if ( this.$icon ) {
this.$icon
.removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
.removeAttr( 'title' );
}
this.$icon = $icon
.addClass( 'oo-ui-iconElement-icon' )
.toggleClass( 'oo-ui-iconElement-noIcon', !this.icon )
.toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
if ( this.iconTitle !== null ) {
this.$icon.attr( 'title', this.iconTitle );
}
this.updateThemeClasses();
};
/**
* Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
* The icon parameter can also be set to a map of icon names. See the #icon config setting
* for an example.
*
* @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
* by language code, or `null` to remove the icon.
* @chainable
* @return {OO.ui.Element} The element, for chaining
*/
OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
if ( icon && typeof icon !== 'string' ) {
icon = OO.ui.getLocalValue( icon, null, 'default' );
}
if ( this.icon === icon ) {
return this;
}
this.$element.toggleClass( 'oo-ui-iconElement', !!icon );
if ( this.$icon ) {
if ( this.icon ) {
this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
}
if ( icon ) {
this.$icon.addClass( 'oo-ui-icon-' + icon );
}
this.$icon.toggleClass( 'oo-ui-iconElement-noIcon', !icon );
}
this.icon = icon;
this.updateThemeClasses();
return this;
};
/**
* Get the symbolic name of the icon.
*
* @return {string} Icon name
*/
OO.ui.mixin.IconElement.prototype.getIcon = function () {
return this.icon;
};
|
/**
* Created by Yang on 2/11/16.
*/
import { createSelector } from 'reselect';
const selectForgetPasswordPage = () => (state) => state.get('forgetpassword');
const selectEmail = () => createSelector(
selectForgetPasswordPage(),
(forgetPasswordState) => forgetPasswordState.get('email')
);
const selectError = () => createSelector(
selectForgetPasswordPage(),
(forgetPasswordState) => forgetPasswordState.get('error')
);
const selectResetEmailSent = () => createSelector(
selectForgetPasswordPage(),
(forgetPasswordState) => forgetPasswordState.get('resetEmailSent')
);
export {
selectForgetPasswordPage,
selectEmail,
selectError,
selectResetEmailSent,
};
|
import {assert} from 'chai'
import {toConsole} from '../src/destinations'
import {Message} from '../src/message'
import {addDestination} from '../src/output'
import {assertContainsFields} from '../src/testing'
describe('toConsole', function() {
/** @test {toConsole} */
it('performs a noop if no suitable method is found', function() {
const messages = [],
remove = addDestination(toConsole({}))
Message.create({x: 123}).write()
remove()
assert.deepEqual(messages, [])
})
/** @test {toConsole} */
it('falls back to `console.log`', function() {
const messages = [],
console = {log: x => messages.push(x)},
remove = addDestination(toConsole(console))
Message.create({x: 123}).write()
remove()
assertContainsFields(
messages[0],
{x: 123})
})
/** @test {toConsole} */
it('logs to `console.info`', function() {
const messages = [],
console = {info: x => messages.push(x)},
remove = addDestination(toConsole(console))
Message.create({x: 123}).write()
remove()
assertContainsFields(
messages[0],
{x: 123})
})
})
|
import isNil from "lodash/isNil";
import isArray from "lodash/isArray";
import isFunction from "lodash/isFunction";
import isObject from "lodash/isObject";
import mergeWith from "lodash/mergeWith";
import Fakerator from "lib/fakerator";
module.exports = function() {
let locale = require("lib/locales/sv-SE");
let fbLocale = require("lib/locales/default");
// Merge locale and fallback
locale = mergeWith(locale, fbLocale, (objValue) => {
// DON'T MERGE ARRAYS
if (isArray(objValue) || isFunction(objValue))
return objValue;
if (!isNil(objValue) && !isObject(objValue))
return objValue;
});
return new Fakerator(locale);
};
|
module.exports = {
'tokens': [
{
'type': 'category',
'name': 'Colors',
'tokens': [
{
'variable': '--app-accent-color',
'name': 'App Accent Color',
'type': 'color',
'themes': {
'plain': {
'value': 'black',
'variable': '--plain-black-color'
},
'funky': {
'value': 'orange',
'variable': '--funky-orange-color'
}
},
'description': 'Accent color'
},
{
'variable': '--app-call-to-action-color',
'name': 'App Call To Action Color',
'type': 'color',
'themes': {
'plain': {
'value': 'red',
'variable': '--plain-red-color'
},
'funky': {
'value': 'orange',
'variable': '--funky-orange-color'
}
},
'description': 'Primary interaction color'
}
]
},
{
'type': 'category',
'name': 'Shadows',
'tokens': [
{
'variable': '--app-box-shadow',
'name': 'App Box Shadow',
'type': 'shadow',
'themes': {
'plain': {
'value': '0 0 8px 2px rgba(92,43,54,0.2)'
},
'funky': {
'value': '0 0 8px 2px rgba(0,0,0,0.2)'
}
}
}
]
},
{
'type': 'category',
'name': 'Borders',
'tokens': [
{
'variable': '--app-border-radius',
'name': 'App Border Radius',
'type': 'border-radius',
'themes': {
'plain': {
'value': '20rem'
},
'funky': {
'value': '3px'
}
}
},
{
'variable': '--app-border-width',
'name': 'App Border Width',
'type': 'border-width',
'themes': {
'plain': {
'value': '2px'
},
'funky': {
'value': '7px'
}
}
},
{
'variable': '--app-border-style',
'name': 'App Border Style',
'type': 'border-style',
'themes': {
'plain': {
'value': 'dashed'
},
'funky': {
'value': 'dotted'
}
}
}
]
},
{
'type': 'category',
'name': 'Opacity',
'tokens': [
{
'variable': '--app-opacity-30',
'name': 'Opacity 30%',
'type': 'opacity',
'themes': {
'plain': {
'value': '0.3'
},
'funky': {
'value': '0.3'
}
}
},
{
'variable': '--app-opacity-60',
'name': 'Opacity 60%',
'type': 'opacity',
'themes': {
'plain': {
'value': '0.6'
},
'funky': {
'value': '0.6'
}
}
},
{
'variable': '--app-opacity-90',
'name': 'Opacity 90%',
'type': 'opacity',
'themes': {
'plain': {
'value': '0.9'
},
'funky': {
'value': '0.9'
}
}
}
]
},
{
'type': 'category',
'name': 'Spaces',
'tokens': [
{
'variable': '--app-space-xs',
'name': 'App Space XS',
'type': 'size',
'themes': {
'plain': {
'value': '0.25rem'
},
'funky': {
'value': '0.25rem'
}
}
},
{
'variable': '--app-space-s',
'name': 'App Space S',
'type': 'size',
'themes': {
'plain': {
'value': '0.5rem'
},
'funky': {
'value': '0.5rem'
}
}
},
{
'variable': '--app-space-m',
'name': 'App Space M',
'type': 'size',
'themes': {
'plain': {
'value': '1rem'
},
'funky': {
'value': '1rem'
}
}
},
{
'variable': '--app-space-l',
'name': 'App Space L',
'type': 'size',
'themes': {
'plain': {
'value': '1.5rem'
},
'funky': {
'value': '1.5rem'
}
}
},
{
'variable': '--app-space-xl',
'name': 'App Space XL',
'type': 'size',
'themes': {
'plain': {
'value': '2rem'
},
'funky': {
'value': '2rem'
}
}
},
{
'variable': '--app-space-xxl',
'name': 'App Space XXL',
'type': 'size',
'themes': {
'plain': {
'value': '4rem'
},
'funky': {
'value': '4rem'
}
}
}
]
}
]
}
|
console.log('Hello!');
var thermostat = new Thermostat();
var updateTemperature = function() {
$('#temperature_display').text(thermostat.temperature);
$('#temperature_display').css('color', thermostat.colour);
};
$(document).ready(function() {
updateTemperature();
$('#increase-button').on('click', function() {
thermostat.increaseTemp();
updateTemperature();
});
$('#decrease-button').on('click', function() {
thermostat.decreaseTemp();
updateTemperature();
});
$('#reset-button').on('click', function() {
thermostat.reset();
updateTemperature();
});
$('#power-saving-mode').on('change', function() {
if (this.checked) {
thermostat.powerSavingOn();
} else {
thermostat.powerSavingOff();
}
updateTemperature();
});
$('#weather-status-form').submit(function(event){
event.preventDefault();
captureCity = $('#weather-city').val();
console.log(captureCity);
processForm();
updateTemperature();
});
});
function processForm() {
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q=' + captureCity,
jsonp: 'callback',
dataType: 'jsonp',
cache: false,
data: {
q: $('#weather-city').val(),
},
success: function (response) {
$('#current-city').text(response.name);
$('#weather-description').text(response.weather[0].description);
$('#weather-temp').text((response.main.temp -273.15).toFixed(1));
$('#weather-wind').text(response.wind.speed);
},
});
}
|
var Observer = require('../../../../src/observer')
var config = require('../../../../src/config')
var _ = require('../../../../src/util')
describe('Observer', function () {
it('create on non-observables', function () {
// skip primitive value
var ob = Observer.create(1)
expect(ob).toBeUndefined()
// avoid vue instance
ob = Observer.create(new _.Vue())
expect(ob).toBeUndefined()
// avoid frozen objects
ob = Observer.create(Object.freeze({}))
expect(ob).toBeUndefined()
})
it('create on object', function () {
// on object
var obj = {
a: {},
b: {}
}
var ob = Observer.create(obj)
expect(ob instanceof Observer).toBe(true)
expect(ob.value).toBe(obj)
expect(obj.__ob__).toBe(ob)
// should've walked children
expect(obj.a.__ob__ instanceof Observer).toBe(true)
expect(obj.b.__ob__ instanceof Observer).toBe(true)
// should return existing ob on already observed objects
var ob2 = Observer.create(obj)
expect(ob2).toBe(ob)
})
it('create on array', function () {
// on object
var arr = [{}, {}]
var ob = Observer.create(arr)
expect(ob instanceof Observer).toBe(true)
expect(ob.value).toBe(arr)
expect(arr.__ob__).toBe(ob)
// should've walked children
expect(arr[0].__ob__ instanceof Observer).toBe(true)
expect(arr[1].__ob__ instanceof Observer).toBe(true)
})
it('observing object prop change', function () {
var obj = { a: { b: 2 } }
Observer.create(obj)
// mock a watcher!
var watcher = {
deps: [],
addDep: function (dep) {
this.deps.push(dep)
dep.addSub(this)
},
update: jasmine.createSpy()
}
// collect dep
Observer.setTarget(watcher)
obj.a.b
Observer.setTarget(null)
expect(watcher.deps.length).toBe(3) // obj.a + a.b + b
obj.a.b = 3
expect(watcher.update.calls.count()).toBe(1)
// swap object
obj.a = { b: 4 }
expect(watcher.update.calls.count()).toBe(2)
watcher.deps = []
Observer.setTarget(watcher)
obj.a.b
Observer.setTarget(null)
expect(watcher.deps.length).toBe(3)
// set on the swapped object
obj.a.b = 5
expect(watcher.update.calls.count()).toBe(3)
})
it('observing $add/$set/$delete', function () {
var obj = { a: 1 }
var ob = Observer.create(obj)
var dep = ob.dep
spyOn(dep, 'notify')
obj.$add('b', 2)
expect(obj.b).toBe(2)
expect(dep.notify.calls.count()).toBe(1)
obj.$delete('a')
expect(obj.hasOwnProperty('a')).toBe(false)
expect(dep.notify.calls.count()).toBe(2)
// should ignore adding an existing key
obj.$add('b', 3)
expect(obj.b).toBe(2)
expect(dep.notify.calls.count()).toBe(2)
// set existing key, should be a plain set and not
// trigger own ob's notify
obj.$set('b', 3)
expect(obj.b).toBe(3)
expect(dep.notify.calls.count()).toBe(2)
// set non-existing key
obj.$set('c', 1)
expect(obj.c).toBe(1)
expect(dep.notify.calls.count()).toBe(3)
// should ignore deleting non-existing key
obj.$delete('a')
expect(dep.notify.calls.count()).toBe(3)
// should work on non-observed objects
var obj2 = { a: 1 }
obj2.$delete('a')
expect(obj2.hasOwnProperty('a')).toBe(false)
})
it('observing array mutation', function () {
var arr = []
var ob = Observer.create(arr)
var dep = ob.dep
spyOn(dep, 'notify')
var objs = [{}, {}, {}]
arr.push(objs[0])
arr.pop()
arr.unshift(objs[1])
arr.shift()
arr.splice(0, 0, objs[2])
arr.sort()
arr.reverse()
expect(dep.notify.calls.count()).toBe(7)
// inserted elements should be observed
objs.forEach(function (obj) {
expect(obj.__ob__ instanceof Observer).toBe(true)
})
})
it('array $set', function () {
var arr = [1]
var ob = Observer.create(arr)
var dep = ob.dep
spyOn(dep, 'notify')
arr.$set(0, 2)
expect(arr[0]).toBe(2)
expect(dep.notify.calls.count()).toBe(1)
// setting out of bound index
arr.$set(2, 3)
expect(arr[2]).toBe(3)
expect(dep.notify.calls.count()).toBe(2)
})
it('array $remove', function () {
var arr = [{}, {}]
var obj1 = arr[0]
var obj2 = arr[1]
var ob = Observer.create(arr)
var dep = ob.dep
spyOn(dep, 'notify')
// remove by index
arr.$remove(0)
expect(arr.length).toBe(1)
expect(arr[0]).toBe(obj2)
expect(dep.notify.calls.count()).toBe(1)
// remove by identity, not in array
arr.$remove(obj1)
expect(arr.length).toBe(1)
expect(arr[0]).toBe(obj2)
expect(dep.notify.calls.count()).toBe(1)
// remove by identity, in array
arr.$remove(obj2)
expect(arr.length).toBe(0)
expect(dep.notify.calls.count()).toBe(2)
})
it('no proto', function () {
config.proto = false
// object
var obj = {a: 1}
var ob = Observer.create(obj)
expect(obj.$add).toBeTruthy()
expect(obj.$delete).toBeTruthy()
var dep = ob.dep
spyOn(dep, 'notify')
obj.$add('b', 2)
expect(dep.notify).toHaveBeenCalled()
// array
var arr = [1, 2, 3]
var ob2 = Observer.create(arr)
expect(arr.$set).toBeTruthy()
expect(arr.$remove).toBeTruthy()
expect(arr.push).not.toBe([].push)
var dep2 = ob2.dep
spyOn(dep2, 'notify')
arr.push(1)
expect(dep2.notify).toHaveBeenCalled()
config.proto = true
})
})
|
const { BrowserWindow } = require('electron');
const path = require('path');
class RecorderWindow {
constructor() {
let htmlPath = 'file://' + path.join(__dirname, '..') + '/pages/recorder_window.html'
this.window = new BrowserWindow({
show: false,
height: 400,
width: 600,
minHeight: 200,
minWidth: 200,
frame: false,
hasShadow: false,
alwaysOnTop: true,
transparent: true,
resizable: true
});
this.window.loadURL(htmlPath);
}
disable() {
this.window.setResizable(false);
this.window.setIgnoreMouseEvents(true);
}
enable() {
this.window.setResizable(true);
this.window.setIgnoreMouseEvents(false);
}
}
module.exports = RecorderWindow;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.