code stringlengths 2 1.05M |
|---|
// @flow
import React from 'react';
import './styles/awesome.css';
const Awesome = ({onClick}: {onClick?: Function}): React.Element<any> => (
<a onClick={onClick} className="awesome">
Click on this Awesome Component
</a>
);
export default Awesome;
|
const fs = require('fs').promises;
const http = require('http');
const mime = require('mime-types');
const { URL } = require('url');
const { format } = require('util');
const Sentry = require('@sentry/node');
Sentry.init({
dsn: 'https://a7fa45b215ae4cf68bb9320a075234d7@sentry.io/1263950',
});
const engine = require('./lyric_engine_js');
function do_not_found(response) {
response.writeHead(404);
response.end();
}
const port = process.env.PORT || 8866;
console.log(`Listen to http://localhost:${port}`);
const outputJson = (response, out) => {
const json_string = JSON.stringify(out);
response.writeHead(200, {
'Content-Length': Buffer.byteLength(json_string, 'utf8'),
'Content-Type': 'application/json',
});
response.end(json_string);
};
const handleError = (request, response, error, lyric_url) => {
console.error('err:', error);
const out = {
lyric: `Failed to find lyric of ${lyric_url}`,
};
let level = 'error';
let domain = '';
if (error instanceof engine.SiteNotSupportError) {
level = 'warning';
out.lyric = error.message;
domain = error.domain;
}
if (error instanceof engine.BlockedError) {
level = 'warning';
out.lyric = `Failed to get lyric of ${lyric_url}. Blocked by vendor.`;
}
Sentry.withScope((scope) => {
scope.setLevel(level);
scope.addEventProcessor(async (event) =>
Sentry.Handlers.parseRequest(event, request)
);
if (domain) {
scope.setFingerprint(['site-not-support-error', domain]);
}
Sentry.captureException(error);
});
outputJson(response, out);
};
http
.createServer(async (request, response) => {
const request_object = new URL(
request.url,
`https://${request.headers.host}`
);
let { pathname } = request_object;
if (pathname === '/') {
pathname = '/index.html';
} else if (pathname === '/former/') {
pathname = '/former/index.html';
}
if (pathname === '/info') {
const info = {
headers: request.headers,
rawHeaders: request.rawHeaders,
};
return outputJson(response, info);
}
if (pathname === '/self') {
}
if (pathname === '/app' || pathname === '/json') {
const { searchParams } = request_object;
if (!searchParams || !searchParams.has('url')) {
console.warn('in app, but no query');
return do_not_found(response);
}
const url = searchParams.get('url');
let out = {
lyric: `Failed to find lyric of ${url}`,
};
if (pathname === '/app') {
try {
const lyric = await engine.get_full(url);
out.lyric = lyric;
} catch (error) {
return handleError(request, response, error, url);
}
} else if (pathname === '/json') {
try {
const json = await engine.get_json(url);
if (json) {
out = json;
}
} catch (error) {
return handleError(request, response, error, url);
}
}
return outputJson(response, out);
}
const source = format('%s%s', 'public', pathname);
fs.readFile(source)
.then((data) => {
response.writeHead(200, {
'Content-Length': data.length,
'Content-Type': mime.lookup(pathname) || 'application/octet-stream',
});
response.end(data);
})
.catch(() => do_not_found(response));
return '';
})
.listen(port);
|
'use strict';
module.exports = {
db: 'mongodb://localhost/diversityinmotion-dev',
app: {
title: 'diversityinmotion - Development Environment'
},
facebook: {
clientID: process.env.FACEBOOK_ID || '1634984180057018',
clientSecret: process.env.FACEBOOK_SECRET || '967e97c2d8286b527e9b5bf42bd8d84e',
callbackURL: '/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: '/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: '/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: '/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: '/auth/github/callback'
},
mailer: {
from: process.env.MAILER_FROM || 'MAILER_FROM',
options: {
service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
auth: {
user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
}
}
}
};
|
var stringUtil = require('ember-cli-string-utils');
var SilentError = require('silent-error');
var pathUtil = require('ember-cli-path-utils');
var existsSync = require('exists-sync');
var path = require('path');
module.exports = function(type, baseClass, packagePath, options) {
var entityName = options.entity.name;
var isAddon = options.inRepoAddon || options.project.isEmberCLIAddon();
var relativePath = pathUtil.getRelativePath(options.entity.name);
if (options.pod && options.podPath) {
relativePath = pathUtil.getRelativePath(options.podPath + options.entity.name);
}
var entityDirectory = type + 's';
var applicationEntityPath = path.join(options.project.root, 'app', entityDirectory, 'application.js');
var hasApplicationEntity = existsSync(applicationEntityPath);
if (!isAddon && !options.baseClass && entityName !== 'application' && hasApplicationEntity) {
options.baseClass = 'application';
packagePath = './application';
}
if (options.baseClass === entityName) {
throw new SilentError(stringUtil.classify(type) + 's cannot extend from themself. To resolve this, remove the `--base-class` option or change to a different base-class.');
}
var importStatement = 'import ' + baseClass + ' from \'' + packagePath + '\';';
if (options.baseClass) {
baseClass = stringUtil.classify(options.baseClass.replace('\/', '-'));
baseClass = baseClass + stringUtil.classify(type);
importStatement = 'import ' + baseClass + ' from \'' + relativePath + options.baseClass + '\';';
}
return {
importStatement: importStatement,
baseClass: baseClass
};
};
|
'use strict';
const blacklist = [
'freelist',
'sys'
];
module.exports = Object.keys(process.binding('natives'))
.filter(x => !/^_|^internal|\//.test(x) && blacklist.indexOf(x) === -1)
.sort();
|
/**
* Created by leo on 7/4/16.
*/
Date.prototype.Format = function (fmt) { //author: meizz
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
$(document).ready(function () {
$("#cusIDCard").click(function () {
$('#error_info').html("");
});
var cus = {
"cusNumber":0,
"cusName":"",
"cusID": null,
"deliverTime":null,
"property":null,
"unitName":null,
"telephone":null,
"mobile":null,
"address":null,
"postCode":0,
"contacts":null,
"email":null,
"maintainDevice":null
};
var newadd = true;
if (sessionStorage['edit'] == "true"){
newadd = false;
sessionStorage['edit'] = "false";
cus = $.parseJSON(sessionStorage["cus_info"]);
$("#cusName").val(cus.cusName );
$("#cusIDCard").val(cus.cusID);
if(cus.property > 0)
{
$('input:radio[name="cusProperty"]').eq(cus.property - 1).attr("checked", true);
}
$("#cusUnit").val(cus.unitName);
$("#cusTel").val(cus.telephone);
$("#cusMobile").val(cus.mobile);
$("#cusAddr").val(cus.address);
$("#cusPostCode").val(cus.postCode);
$("#cuscontact").val(cus.contacts);
$("#cusEmail").val(cus.email);
$("#cusContact").val(cus.contacts);
$("#cusDeliverTime").html(new Date(cus.deliverTime).Format("yyyy-MM-dd hh:mm:ss").toLocaleString());
}
$("#confirm_edit").click(function () {
cus.cusName = $("#cusName").val();
cus.cusID = $("#cusIDCard").val();
cus.property = parseInt($("input[name='cusProperty']:checked").val());
cus.unitName = $("#cusUnit").val();
cus.telephone = $("#cusTel").val();
cus.mobile = $("#cusMobile").val();
cus.address = $("#cusAddr").val();
cus.postCode = parseInt($("#cusPostCode").val());
cus.contacts = $("#cuscontact").val();
cus.email = $("#cusEmail").val();
cus.contacts=$("#cusContact").val();
if(cus.cusID == '')
{
$('#error_info').html("身份证号为必填项,请务必填写再确认!");
return;
}
if(newadd == true)
{
$.ajax({
type:"POST",
url:"customer/add",
dataType:"text",
contentType:"application/json; charset=utf-8",
data:JSON.stringify(cus),
success:function(data){
if (data == "failed"){
alert("添加失败");
}
else {
alert("添加成功");
}
cus.cusNumber = parseInt(data);
sessionStorage["cus_info"] = JSON.stringify(cus);
window.location.href="cus_info.html";
}
});
}else {
$.ajax({
type:"POST",
url:"customer/update",
dataType:"text",
contentType:"application/json; charset=utf-8",
data:JSON.stringify(cus),
success:function(data){
if (data == "failed"){
alert("修改失败");
}
else {
alert("修改成功");
}
sessionStorage["cus_info"] = JSON.stringify(cus);
window.location.href="cus_info.html";
}
})
}
})
}) |
version https://git-lfs.github.com/spec/v1
oid sha256:dc9c7d88b2e70188371d34d3e79787fe9bd0db0213ee33ab7b4b0527d673e443
size 7816
|
version https://git-lfs.github.com/spec/v1
oid sha256:8245e7c87cb5065eeea47c3d575e9482b98a644c35c1b8c6d1e70fb1b09e7980
size 5986
|
const Promise = require('bluebird');
const path = require('path');
const _ = require('lodash');
const Config = require('./config');
const Category = require('./category');
const CategoryUploader = require('./zendesk-uploader/category-uploader');
const ZendeskDeleter = require('./zendesk-uploader/deleter');
const logger = require('./logger');
const chalk = require('chalk');
/**
* Docpub represents interface to utility. It is used as entry point for all operations.
* It's interface methods represent a command utility support.
* Must be initialised with args received from user.
*/
module.exports = class Docpub {
/**
* Creates DocpubPipeline instance
* Options, received from user, must be passed to this constructor
* If path passed, it would be resolved relatively to process.cwd()
*
* @param {Object} opts - options received from user.
*/
constructor(opts) {
opts = _.defaults(opts || {}, {
path: process.cwd(),
verbose: false
});
logger.setup(opts);
this._path = path.resolve(opts.path);
this._config = this._loadConfig(opts);
}
/**
* Performs upload to Zendesk action for all available documents
* First reads the directory for all availblae items.
* If read was correct, performs upload of this items.
* If read or upload were rejected, rejects promise.
* If everything was successful, resolves the promise
*
* @returns Promise - promise to be resolved when uploading finished
*/
uploadCategory() {
logger.info(`Start uploading.`);
logger.info(`Category path: ${this._path}`);
const category = new Category(this._path, this._config);
return category.read()
.then(() => {
const categoryUploader = new CategoryUploader(category, this._config);
const zendeskDeleter = new ZendeskDeleter(category, this._config);
return categoryUploader.upload()
.then(() => zendeskDeleter.delete());
})
.then(() => {
logger.info(
chalk.green(`Successfully uploaded all entities for category ${this._path}`)
);
})
.catch(e => {
this._logError(e);
return Promise.reject(e);
});
}
_loadConfig(opts) {
try {
return new Config(opts.configPath, this._path);
} catch (e) {
this._logError(e);
throw e;
}
}
_logError(error) {
logger.error(`Upload failed!`);
logger.error(error.message);
logger.error(error.stack);
}
};
|
/**
* ProjectController
* @namespace crowdsource.project.controllers
* @author dmorina neilthemathguy
*/
(function () {
'use strict';
angular
.module('crowdsource.project.controllers')
.controller('ProjectController', ProjectController);
ProjectController.$inject = ['$window', '$location', '$scope', 'Project', '$filter', '$mdSidenav', '$routeParams', 'Skill'];
/**
* @namespace ProjectController
*/
function ProjectController($window, $location, $scope, Project, $filter, $mdSidenav, $routeParams) {
var self = this;
self.startDate = $filter('date')(new Date(), 'yyyy-MM-ddTHH:mmZ');
self.addProject = addProject;
self.endDate = $filter('date')(new Date(), 'yyyy-MM-ddTHH:mmZ');
self.name = null;
self.description = null;
self.saveCategories = saveCategories;
self.getReferenceData = getReferenceData;
self.categories = [];
self.getSelectedCategories = getSelectedCategories;
self.showTemplates = showTemplates;
self.closeSideNav = closeSideNav;
self.finishModules = finishModules;
self.activateTemplate = activateTemplate;
self.addTemplate = addTemplate;
self.addModule = addModule;
self.getStepId = getStepId;
self.getStepName = getStepName;
self.getPrevious = getPrevious;
self.getNext = getNext;
self.form = {
category: {is_expanded: false, is_done:false},
general_info: {is_expanded: false, is_done:false},
modules: {is_expanded: false, is_done:false},
templates: {is_expanded: false, is_done:false},
review: {is_expanded: false, is_done:false}
};
self.currentProject = Project.retrieve();
self.currentProject.payment = self.currentProject.payment || {};
self.toggle = toggle;
self.selectedItems = [];
self.isSelected = isSelected;
self.sort = sort;
self.config = {
order_by: "",
order: ""
};
self.myProjects = [];
Project.getProjects().then(function(data) {
self.myProjects = data[0];
});
self.getStatusName = getStatusName;
self.monitor = monitor;
self.other = false;
self.otherIndex = 7;
self.getPath = function(){
return $location.path();
};
self.toggle = function (item) {
self.currentProject.categories = [item];
if (item == self.otherIndex) self.other = true;
else self.other = false;
};
self.exists = function (item) {
var list = self.currentProject.categories || [];
return list.indexOf(item) > -1;
};
activate();
function activate(){
Project.getCategories().then(
function success(resp) {
var data = resp[0];
self.categories = data;
},
function error(resp) {
var data = resp[0];
self.error = data.detail;
}).finally(function () {});
}
function getReferenceData() {
Project.getReferenceData().success(function(data) {
$scope.referenceData = data[0];
});
}
/**
* @name addProject
* @desc Create new project
* @memberOf crowdsource.project.controllers.ProjectController
*/
function addProject() {
Project.addProject(self.currentProject).then(
function success(resp) {
var data = resp[0];
self.form.general_info.is_done = true;
self.form.general_info.is_expanded = false;
self.form.modules.is_expanded=true;
Project.clean();
$location.path('/monitor');
},
function error(resp) {
var data = resp[0];
self.error = data.detail;
}).finally(function () {
});
}
function saveCategories() {
self.form.category.is_expanded = false;
self.form.category.is_done=true;
self.form.general_info.is_expanded = true;
}
function getSelectedCategories(){
return Project.selectedCategories;
}
function showTemplates(){
if (self.getSelectedCategories().indexOf(3) < 0) {
} else {
return true;
}
}
function closeSideNav(){
$mdSidenav('right').close()
.then(function () {
});
}
function finishModules(){
self.form.modules.is_done = true;
self.form.modules.is_expanded = false;
if (!self.showTemplates()) {
self.form.review.is_expanded = true;
} else {
self.form.templates.is_expanded = true;
}
}
function activateTemplate(template){
self.selectedTemplate = template;
}
function addTemplate(){
self.form.templates.is_done = true;
self.form.templates.is_expanded = false;
self.form.review.is_expanded = true;
}
function addModule(){
var module = {
name: self.module.name,
description: self.module.description,
repetition: self.module.repetition,
dataSource: self.module.datasource,
startDate: self.module.startDate,
endDate: self.module.endDate,
workerHelloTimeout: self.module.workerHelloTimeout,
minNumOfWorkers: self.module.minNumOfWorkers,
maxNumOfWorkers: self.module.maxNumOfWorkers,
tasksDuration: self.module.tasksDuration,
milestone0: {
name: self.module.milestone0.name,
description: self.module.milestone0.description,
allowRevision: self.module.milestone0.allowRevision,
allowNoQualifications: self.module.milestone0.allowNoQualifications,
startDate: self.module.milestone0.startDate,
endDate: self.module.milestone0.endDate
},
milestone1: {
name: self.module.milestone1.name,
description: self.module.milestone1.description,
startDate: self.module.milestone1.startDate,
endDate: self.module.milestone1.endDate
},
numberOfTasks: self.module.numberOfTasks,
taskPrice: self.module.taskPrice
};
self.modules.push(module);
}
function getStepId(){
return $routeParams.projectStepId;
}
function getStepName(stepId){
if(stepId==1){
return '1. Category';
}
else if(stepId==2){
return '2. Description';
}
else if(stepId==3){
return '3. Prototype Task';
}
else if(stepId==4){
return '4. Design';
}
else if(stepId==5){
return '5. Payment';
}
else if(stepId==6){
return '6. Summary';
}
}
function getPrevious(){
return parseInt(self.getStepId())-1;
}
function getNext(){
return parseInt(self.getStepId())+1;
}
function computeTotal(payment) {
var total = ((payment.number_of_hits*payment.wage_per_hit)+(payment.charges*1));
total = total ? total.toFixed(2) : 'Error';
return total;
}
$scope.$watch('project.currentProject.payment', function (newVal, oldVal) {
if (!angular.equals(newVal, oldVal)) {
self.currentProject.payment.total = computeTotal(self.currentProject.payment);
}
}, true);
$scope.$on("$destroy", function() {
Project.syncLocally(self.currentProject);
});
function toggle(item) {
var idx = self.selectedItems.indexOf(item);
if (idx > -1) self.selectedItems.splice(idx, 1);
else self.selectedItems.push(item);
}
function isSelected(item){
return !(self.selectedItems.indexOf(item) < 0);
}
function sort(header){
var sortedData = $filter('orderBy')(self.myProjects, header, self.config.order==='descending');
self.config.order = (self.config.order==='descending')?'ascending':'descending';
self.config.order_by = header;
self.myProjects = sortedData;
}
function loadMyProjects() {
Projects.getMyProjects()
.then(function success(data, status) {
self.myProjects = data.data;
},
function error(data, status) {
}).finally(function () {
}
);
}
function getStatusName (status) {
return status == 1 ? 'created' : (status == 2 ? 'in review' : (status == 3 ? 'in progress' : 'completed'));
}
function monitor(project) {
window.location = 'monitor/' + project.id;
}
}
})(); |
var app = null;
Ext.define('CustomApp', {
extend: 'Rally.app.App',
componentCls: 'app',
launch: function() {
app = this;
app.numberSprints = app.getSetting("numberSprints");
app.queryIterations();
},
getSettingsFields: function() {
var values = [
{
name: 'numberSprints',
xtype: 'rallytextfield',
label : "Number of sprints to report on."
},
{
name: 'showOnlyTeams',
xtype: 'rallycheckboxfield',
label : "Only show projects with at least one team member."
},
{
name: 'showTeamMembers',
xtype: 'rallycheckboxfield',
label : "Show team members column."
},
{
name: 'showAcceptanceRateMetric',
xtype: 'rallycheckboxfield',
label : "Show Accepted .v. Commit %"
},
{
name: 'showImprovementRateMetric',
xtype: 'rallycheckboxfield',
label : "Show Improvement work as % of Scope"
},
{
name: 'showChurnRateMetric',
xtype: 'rallycheckboxfield',
label : "Show Churn Ratio (std dev of scope divided by average daily scope)"
},
{
name: 'showPercentEstimatedMetric',
xtype: 'rallycheckboxfield',
label : "Show Percentage of stories with a plan estimate metric"
},
{
name: 'showTaskChurnRateMetric',
xtype: 'rallycheckboxfield',
label : "Show Task Churn Ratio (std dev of task scope divided by average daily scope)"
},
{
name: 'showDailyInProgressMetric',
xtype: 'rallycheckboxfield',
label : "Show average daily percentage of work that is In-Progress"
},
{
name: 'showBurnDownResiduals',
xtype: 'rallycheckboxfield',
label : "Show burn down residuals (values closer to 1 indicate burndown closer to ideal)"
},
{
name: 'useLateAcceptanceRate',
xtype: 'rallycheckboxfield',
label : "use Late Accepted value for Acceptance Ratio"
},
{
name: 'commitAcceptRatio',
xtype: 'rallytextfield',
label : "Target accepted .v. committed percent"
},
{
name: 'continuousImprovementRangeMin',
xtype: 'rallytextfield',
label: 'Continuous Improvement Range Min'
},
{
name: 'continuousImprovementRangeMax',
xtype: 'rallytextfield',
label: 'Continuous Improvement Range Max'
}
];
_.each(values,function(value){
value.labelWidth = 250;
value.labelAlign = 'left';
});
return values;
},
config: {
defaultSettings : {
numberSprints : 4,
showOnlyTeams : false,
showTeamMembers : true,
showAcceptanceRateMetric : true,
showImprovementRateMetric : false,
showChurnRateMetric : true,
showPercentEstimatedMetric : true,
showTaskChurnRateMetric : true,
showDailyInProgressMetric : true,
showBurnDownResiduals : true,
commitAcceptRatio : 75,
continuousImprovementRangeMin : 5,
continuousImprovementRangeMax : 10,
useLateAcceptanceRate : true
}
},
/*
queryIteration retrieves all iterations in scope that ended before today and after one
year ago.
*/
queryIterations : function() {
var today = new Date();
var lastYear = new Date();
lastYear.setDate(today.getDate()-365);
var todayISO = Rally.util.DateTime.toIsoString(today, false);
var lastYearISO = Rally.util.DateTime.toIsoString(lastYear, false);
var configs = [
{
model : "Iteration",
fetch : ['Name', 'ObjectID', 'Project', 'StartDate', 'EndDate' ],
filters: [
{ property : 'EndDate', operator: "<=", value: todayISO },
{ property : 'EndDate', operator: ">=", value: lastYearISO }
],
sorters: [
{
property: 'EndDate',
direction: 'ASC'
}
]
}
];
async.map( configs, app.wsapiQuery, function(error,results) {
/*
We group the iterations by project (team), and then get metrics for the last four iterations
for each team.
*/
var iterationsRaw = results[0];
var prjRefs = _.map(results[0],function(iter)
{
return iter.get("Project").ObjectID;
});
var uniqPrjRefs = _.uniq(prjRefs);
var querConfigs = _.map(uniqPrjRefs,function(p) {
return{
model:"Project",
fetch: ["TeamMembers","Name"],
filters: [{property:"ObjectID",value:p}]
};
});
async.map(querConfigs, app.wsapiQuery, function(err, results) {
var flatTM = _.flatten(results);
var flatNotEmptyTM = _.filter(flatTM, function(prj) { return app.getSetting("showOnlyTeams") === false || prj.get("TeamMembers").Count > 0; });
var uniqPrjIdTM = _.map(flatNotEmptyTM, function(val) {
return val.get("ObjectID");
});
var inerNoEmptyTM = _.filter(iterationsRaw, function(iter) { return _.contains(uniqPrjIdTM, iter.get("Project").ObjectID );});
// var groupedByProject = _.groupBy(inerNoEmptyTM,function(r) { return r.get("Project").Name;});
var groupedByProject = _.groupBy(inerNoEmptyTM,function(r) { return r.get("Project").ObjectID;});
var teams = _.map(_.keys(groupedByProject),function(pid) {
return _.find(flatNotEmptyTM,function(p) {
return p.get("ObjectID")==pid;
});
});
var teamLastIterations = _.map( _.values(groupedByProject), function(gbp) {
return _.last(gbp,app.numberSprints);
});
/*
Get the iteration data for each set of up to 4 iterations.
*/
async.map( teamLastIterations, app.teamData, function(error,results) {
app.teamResults = _.map(results, function(result,i) {
return {
team : teams[i].get("Name"),
summary : _.merge(results[i][0],results[i][1],results[i][2])
};
});
// get list of team members,
async.map(teams,
function(proj,callback) {
proj.getCollection("TeamMembers").load({
fetch:true,
callback : function(recs,operation,success) {
callback(null,recs);
}
});
},
function(err,teamMemberships) {
_.each(app.teamResults,function(t,x) {
t.teamMembers = teamMemberships[x];
});
app.addTable(app.teamResults);
}
);
// create the table with the summary data.
});
});
});
},
/*
Called for each team to return the iteration and improvements data records
*/
teamData : function( iterations, callback) {
app.iterationsData( iterations, function(x,iterationResults) {
app.improvementsData( iterations,function(err,improvementResults) {
app.allIterationItems( iterations, function(err,allIterationItems) {
callback(null,[iterationResults,improvementResults,allIterationItems]);
});
});
});
},
allIterationItems : function( iterations, callback) {
var storyConfigs = _.map( iterations, function(iteration) {
return {
model : "HierarchicalRequirement",
fetch : ['ObjectID','PlanEstimate','Name','FormattedID','Project','ScheduleState'],
filters: [ {
property : 'Iteration.ObjectID',
operator: "=",
value: iteration.get("ObjectID")
}
]
};
});
var defectConfigs = _.map( iterations, function(iteration) {
return {
model : "Defect",
fetch : ['ObjectID','PlanEstimate','Name','FormattedID','Project','ScheduleState'],
filters: [ {
property : 'Iteration.ObjectID',
operator: "=",
value: iteration.get("ObjectID")
}
]
};
});
async.map( storyConfigs, app.wsapiQuery, function(error,storyResults) {
async.map( defectConfigs, app.wsapiQuery, function(error,defectResults) {
var allData = [];
_.each(iterations,function(iteration,x) {
var iterationArtifacts = storyResults[x].concat(defectResults[x]);
// total individual values for each artifact in iteration.
var allIterationData = {
totalScope : _.reduce(iterationArtifacts, function(memo,r) {
return memo + (r.get("PlanEstimate")!==null ? r.get("PlanEstimate") : 0);
},0),
lateAccepted : _.reduce(iterationArtifacts, function(memo,r) {
return memo + app.acceptedValue(r);
},0),
percentEstimated : iterationArtifacts.length > 0 ?
( _.filter(iterationArtifacts,function(artifact) {
return (artifact.get("PlanEstimate") !== null && artifact.get("PlanEstimate") > 0);
}).length / iterationArtifacts.length * 100) : 0
};
allData.push(allIterationData);
});
callback(null,allData);
});
});
},
improvementsData : function( iterations, callback) {
var configs = _.map( iterations, function(iteration) {
return {
model : "HierarchicalRequirement",
fetch : ['ObjectID','PlanEstimate','Name','FormattedID','Project','ScheduleState'],
filters: [ {
property : 'Feature.Name',
operator: "contains",
value: 'Continuous Improvement'
},
{
property : 'Iteration.ObjectID',
operator: "=",
value: iteration.get("ObjectID")
},
{
property : 'ScheduleState',
operator: "=",
value: "Accepted"
}
]
};
});
async.map( configs, app.wsapiQuery, function(error,results) {
var allData = [];
_.each(results,function(result){
var improvementRec = {
totalImprovementPoints : _.reduce(result,function(memo,r){
return memo + app.acceptedValue(r);
},0)
};
allData.push(improvementRec);
});
callback(null,allData);
});
},
acceptedValue : function(story) {
var accepted = story.get("ScheduleState") === "Accepted" || story.get("ScheduleState") == "Released";
var val = accepted && (story.get("PlanEstimate")!==null) ? story.get("PlanEstimate") : 0;
return val;
},
/*
Retrieves the iteration metrics (iterationcumulativeflowdata) for each set of iterations
*/
iterationsData : function( iterations, callback) {
// create a set of wsapi query configs from the iterations
var configs = _.map( iterations, function(iteration) {
return {
model : "IterationCumulativeFlowData",
fetch : ['CardEstimateTotal','CardState','CreationDate','TaskEstimateTotal','CardToDoTotal'],
filters: [ Ext.create('Rally.data.wsapi.Filter', {
property : 'IterationObjectID',
operator: "=",
value: iteration.get("ObjectID")
})]
};
});
// once we have the metrics data we do some gymnastics to calculate the committed and accepted values
async.map( configs, app.wsapiQuery, function(error,results) {
var summaries = [];
_.each(results,function(iterationRecords, index) {
if(iterationRecords.length >0) {
// group the metrics by date,
var groupedByDate = _.groupBy(iterationRecords,function(ir) { return ir.get("CreationDate");});
var churnRatio = app.churnRatio(_.values(groupedByDate));
var taskChurnRatio = app.taskChurnRatio(_.values(groupedByDate));
var stdResiduals = app.burnDownResiduals(_.values(groupedByDate));
var iterationDates = _.keys(groupedByDate);
var dailyInProgressRate = app.dailyInProgressRate(_.values(groupedByDate));
iterationDates = _.sortBy(iterationDates,function(d) {
return Rally.util.DateTime.fromIsoString(d);
});
var firstDayRecs = groupedByDate[_.first(iterationDates)];
var lastDayRecs = groupedByDate[_.last(iterationDates)];
if((firstDayRecs.length>0) && (lastDayRecs.length>0))
{
var committed = _.reduce( firstDayRecs, function(memo,val) {
return memo + (val.get("CardEstimateTotal") !== null ? val.get("CardEstimateTotal") : 0);
}, 0 );
var accepted = _.reduce( lastDayRecs, function(memo,val) {
var estimate = val.get("CardEstimateTotal");
var done = val.get("CardState") === "Accepted" || val.get("CardState") === "Released";
return memo + (( done && !_.isNull(estimate) ) ? estimate : 0);
}, 0 );
summaries.push( {
project : iterations[index].get("Project"),
iteration : iterations[index].get("Name"),
iteration_rec : iterations[index],
id : firstDayRecs[0].get("IterationObjectID"),
committed : Math.round(committed),
accepted : Math.round(accepted),
churnRatio : churnRatio,
taskChurnRatio : taskChurnRatio,
dailyInProgressRate : dailyInProgressRate,
stdResiduals : stdResiduals
});
}
}
});
callback(null,summaries);
});
},
// Returns the std dev when passed an array of arrays of daily cumulative flow recs
churnRatio : function ( arrDailyRecs ) {
var dailyTotals = _.map( arrDailyRecs, function(recs) {
return _.reduce(recs,function(memo,r) { return memo + r.get("CardEstimateTotal");},0);
});
var dailyAverage = _.mean(dailyTotals);
var stdDev = _.stdDeviation(dailyTotals);
return dailyAverage > 0 ? Math.round((stdDev / dailyAverage) *100) : 0;
},
// Returns the std dev when passed an array of arrays of daily cumulative flow recs
taskChurnRatio : function ( arrDailyRecs ) {
var dailyTotals = _.map( arrDailyRecs, function(recs) {
return _.reduce(recs,function(memo,r) { return memo + r.get("TaskEstimateTotal");},0);
});
var dailyAverage = _.mean(dailyTotals);
var stdDev = _.stdDeviation(dailyTotals);
return dailyAverage > 0 ? Math.round((stdDev / dailyAverage) *100) : 0;
},
burnDownResiduals : function ( arrDailyRecs ) {
var keys = _.keys(arrDailyRecs);
var firstDayEstimate = _.reduce( arrDailyRecs[_.first(keys)], function(memo,rec) {
return memo + rec.get("TaskEstimateTotal");
},0);
var ideal = _.map(keys,function(k,i) {
return Math.round(firstDayEstimate - (i*(firstDayEstimate/(keys.length-1))));
});
var todo = _.map(keys,function(k,i) {
return Math.round(_.reduce( arrDailyRecs[k], function(memo,rec) {
return memo + rec.get("CardToDoTotal");
},0));
});
var estimate = _.map(keys,function(k,i) {
return Math.round(_.reduce( arrDailyRecs[k], function(memo,rec) {
return memo + rec.get("TaskEstimateTotal");
},0));
});
var rec = { ideal : ideal, todo : todo, estimate : estimate };
var rs = app.rSquared(rec);
return rs;
},
rSquared : function(burndown) {
var squaredError = _.map( burndown.ideal, function(ideal,i) {
var diff = ideal - burndown.todo[i];
return diff * diff;
});
var mean = _.average(burndown.todo);
var diffFromMean = _.map( burndown.todo, function(todo,i) {
var diff = todo - mean;
return diff * diff;
});
var sse = _.sum(squaredError);
var sst = _.sum(diffFromMean);
var rs = sst !== 0 ? 1 - (Math.round( (sse/sst) *100 ) / 100) : 0;
return rs;
},
// average daily in progress rate (based on points)
dailyInProgressRate : function( arrDailyRecs ) {
var dailyInProgressRates = _.map( arrDailyRecs, function(recs) {
var dailyTotal = _.reduce(recs,function(memo,r) { return memo + r.get("CardEstimateTotal");},0);
var dailyInProgress = _.reduce(recs,function(memo,r) {
return memo + (r.get("CardState") === "In-Progress" ? r.get("CardEstimateTotal") : 0);
},0);
return (dailyTotal > 0 ? (( dailyInProgress / dailyTotal ) * 100 ) : 0);
});
return _.mean(dailyInProgressRates);
},
defineChartColumns : function() {
app.teamMembersColumn = {
text: 'Team Members',
dataIndex: 'teamMembers',
renderer : app.renderTeamMembers,
width : 150,
align : "left",
tdCls: 'wrap'
};
app.acceptanceRateColumn = {
text: '% Accepted Chart',
dataIndex: 'summary',
renderer : app.renderAcceptedChart,
width : 150,
align : "center"
};
app.improvementRateColumn = {
text: '% Improvement Chart',
dataIndex: 'summary',
renderer : app.renderImprovementChart,
width : 150,
align : "center"
};
app.churnRateColumn = {
text: 'Churn Ratio Chart',
dataIndex: 'summary',
renderer : app.renderChurnChart,
width : 150,
align : "center"
};
app.percentEstimatedColumn = {
text: 'Percent Estimated Chart',
dataIndex: 'summary',
renderer : app.renderPercentEstimatedChart,
width : 150,
align : "center"
};
app.taskChurnRateColumn = {
text: 'Task Churn Rate',
dataIndex: 'summary',
renderer : app.renderTaskChurnRateChart,
width : 150,
align : "center"
};
app.dailyInProgressColumn = {
text: 'Average Daily In-Progress % Rate',
dataIndex: 'summary',
renderer : app.renderDailyInProgressChart,
width : 150,
align : "center"
};
app.burnDownResiduals = {
text: 'Task Burndown Residuals',
dataIndex: 'summary',
renderer : app.renderBurnDownResiduals,
width : 150,
align : "center"
};
},
addTable : function(teamResults) {
app.defineChartColumns();
var columnCfgs = [
{ text: 'Team', dataIndex: 'team', renderer : app.renderTeamName },
{ text: 'Last 4 Sprints', dataIndex: 'summary', renderer : app.renderSummaries, width : 250 }
];
if (app.getSetting("showTeamMembers")===true)
columnCfgs.push(app.teamMembersColumn);
if (app.getSetting("showAcceptanceRateMetric")===true)
columnCfgs.push(app.acceptanceRateColumn);
if (app.getSetting("showImprovementRateMetric")===true)
columnCfgs.push(app.improvementRateColumn);
if (app.getSetting("showChurnRateMetric")===true)
columnCfgs.push(app.churnRateColumn);
if (app.getSetting("showPercentEstimatedMetric")===true)
columnCfgs.push(app.percentEstimatedColumn);
if (app.getSetting("showTaskChurnRateMetric")===true)
columnCfgs.push(app.taskChurnRateColumn);
if (app.getSetting("showDailyInProgressMetric")===true)
columnCfgs.push(app.dailyInProgressColumn);
if (app.getSetting("showBurnDownResiduals")===true)
columnCfgs.push(app.burnDownResiduals);
var grid = Ext.create('Rally.ui.grid.Grid', {
store: Ext.create('Rally.data.custom.Store', {
data: teamResults
}),
columnCfgs: columnCfgs
});
app.add(grid);
},
renderTeamName: function(value, metaData, record, rowIdx, colIdx, store, view) {
// return "Team " + rowIdx;
return value;
},
renderTeamMembers: function(value, metaData, record, rowIdx, colIdx, store, view) {
// return "Team " + rowIdx;
var userValue = function(m) {
var d = m.get("DisplayName");
return ((d!==null&&d!=="") ? d : m.get("UserName"));
};
if (value.length > 7)
return value.length + " Team Members";
return _.map(value,function(teamMember,i) {
return userValue(teamMember);
}).join("<br/>");
// + ( i < (value.length-1) ? "<br/>" : "")
},
renderAcceptedChart: function(value, metaData, record, rowIdx, colIdx, store, view) {
var acceptedToken = app.getSetting('useLateAcceptanceRate') === true ? 'lateAccepted' : 'accepted';
var data = _.map( value, function (v,i) {
var drec = {
acceptedPercent : v.committed > 0 ? Math.round((v[acceptedToken] / v.committed) * 100) : 0,
targetPercent : app.getSetting("commitAcceptRatio"),
index : i+1
};
return drec;
});
var id = app.renderChart(record,data,['index','acceptedPercent','targetPercent'],'AcceptedPercent');
var prj = value[0].project.ObjectID;
var iteration = _.last(value).id;
var href = "https://rally1.rallydev.com/#/"+prj+"/oiterationstatus?iterationKey="+iteration;
return "<a id='" + id + "'href="+href+" target=_blank></a>";
},
renderImprovementChart: function(value, metaData, record, rowIdx, colIdx, store, view) {
var id = app.renderChart(record,value,['index','improvementPercent'],'ImprovementRatio');
return "<div id='"+id+"'></div>";
},
renderChurnChart: function(value, metaData, record, rowIdx, colIdx, store, view) {
var id = app.renderChart(record,value,['index','churnRatio'],'ChurnRatio');
return "<div id='"+id+"'></div>";
},
renderTaskChurnRateChart: function(value, metaData, record, rowIdx, colIdx, store, view) {
var id = app.renderChart(record,value,['index','taskChurnRatio'],'TaskChurnRatio');
return "<div id='"+id+"'></div>";
},
renderPercentEstimatedChart: function(value, metaData, record, rowIdx, colIdx, store, view) {
var id = app.renderChart(record,value,['index','percentEstimated'],'PercentEstimated');
return "<div id='"+id+"'></div>";
},
renderDailyInProgressChart: function(value, metaData, record, rowIdx, colIdx, store, view) {
var id = app.renderChart(record,value,['index','dailyInProgressRate'],'DailyInProgressRate');
return "<div id='"+id+"'></div>";
},
renderBurnDownResiduals: function(value, metaData, record, rowIdx, colIdx, store, view) {
var id = app.renderChart(record,value,['index','stdResiduals'],'stdResiduals');
return "<div id='"+id+"'></div>";
},
renderChart : function( record, value, fields, chartName ) {
var data = _.map( value, function (v,i) {
var d = {
index : i+1
};
_.each(fields,function(f) {
if (f!=="index")
d[f] = _.isUndefined(v[f]) ? 0 : v[f];
});
return d;
});
var chartStore = Ext.create('Ext.data.JsonStore', {
fields: fields,
data: data
});
var chartConfig = app.createChartConfig(fields);
var id = Ext.id();
Ext.defer(function (id,chartStore,chartConfig,record) {
record.chartConfig = _.isUndefined(record.chartConfig) ? {} : record.chartConfig;
record.chart = _.isUndefined(record.chart) ? {} : record.chart;
record.chartConfig[chartName] = chartConfig;
record.chartConfig[chartName].renderTo = id;
record.chartConfig[chartName].store = chartStore;
if (record.chart[chartName]===undefined)
record.chart[chartName] = Ext.create('Ext.chart.Chart', chartConfig);
}, 50, undefined, [id,chartStore,chartConfig,record]);
return id;
},
// assumes the category series is the first element eg. ['index','acceptedPercent'] etc.
createChartConfig : function(series) {
return {
style : {
// backgroundColor : 'red'
},
width: 100,
height: 100,
axes: [{
type: 'Numeric',
position: 'left',
fields: [series[1]],
label: {
renderer: Ext.util.Format.numberRenderer('0,0')
},
grid: true
}, {
type: 'Category',
position: 'bottom',
fields: [series[0]]
}],
series: _.map(_.rest(series),function(s,x) {
var config = {
type: 'line',
highlight: {
size: 2,
radius: 2
},
axis: 'left',
xField: series[0],
yField: s
};
if (x>0) {
config.markerConfig = {
type: 'circle',
size: 1,
radius: 0
};
}
return config;
})
};
},
LinkRenderer: function(value, metaData, record, rowIdx, colIdx, store, view) {
var workspace=app.getContext().getProject().ObjectID;
var lastSprintId= _.last(value).id;
return "<a href='https://rally1.rallydev.com/#/"+workspace+"/oiterationstatus?iterationKey="+lastSprintId+"' target='_blank'>Last one</a>";
},
renderSummaries: function(value, metaData, record, rowIdx, colIdx, store, view) {
var endDateF = function(iteration) {
var d = Rally.util.DateTime.fromIsoString(iteration.iteration_rec.raw.EndDate);
return Ext.Date.format(d, 'm/d');
};
var s =
"<table class='iteration-summary'>" +
"<th>" +
_.map(value,function(v){ return '<td><i>'+endDateF(v)+'</i></td>';}).join('') +
"</th>"+
"<tr><td><i>Committed</i></td>" +
_.map(value,function(v){ return '<td>'+Math.round(v.committed)+'</td>'; }).join('') +
"</tr>"+
// "<tr><td><i>Accepted</i></td>" +
"<tr><td><i>Accepted In Sprint</i></td>" +
_.map(value,function(v){ return '<td>'+Math.round(v.accepted)+'</td>'; }).join('') +
"</tr>" +
// "<tr><td><i>Late Accepted</i></td>" +
"<tr><td><i>Total Accepted</i></td>" +
_.map(value,function(v){ return '<td>'+Math.round(v.lateAccepted)+'</td>'; }).join('') +
"</tr></table>";
return s;
},
wsapiQuery : function( config , callback ) {
Ext.create('Rally.data.WsapiDataStore', {
autoLoad : true,
limit : "Infinity",
model : config.model,
fetch : config.fetch,
filters : config.filters,
sorters : config.sorters,
listeners : {
scope : this,
load : function(store, data) {
callback(null,data);
}
}
});
}
}); |
module.exports = {
api: "/api",
port: 4000,
db: "mongodb://127.0.0.1/sudosu",
logLevel: "dev",
secret: "nmcvxljq9uweinsdgfälöaskdpj"
};
|
var mongoose = require('mongoose');
var Schema = require('mongoose').Schema;
var Persona = require('./Persona.js');
//Ingreso: {|Persona|, Cantidad, Fecha}
var pagoSchema = new Schema({
_creador : { type: Schema.ObjectId, ref: 'Persona' },
fecha: { type: Date, default: Date.now },
cantidad: Number
});
pagoSchema.post('save', function(next){
var pago = this;
Persona.findById(this._creador, function(err, persona){
persona.pagos.push(pago);
persona.NPagado += 1;
persona.save();
});
});
module.exports = mongoose.model('Pago', pagoSchema);
|
(function(){reas = new Meteor.Collection("RegisteredEmailAddresses");
/*checks to see if the current user making the request to update is
the admin user */
function adminUser(userId) {
var adminUser = Meteor.users.findOne({username:"admin"});
return (userId && adminUser && userId === adminUser._id);
}
reas.allow({
insert: function(userId, doc){
return adminUser(userId);
},
update: function(userId, docs, fields, modifier){
return adminUser(userId);
},
remove: function (userId, docs){
return adminUser(userId);
}
});
})();
|
class Band {
constructor(socket) {
this.socket = socket;
this.members = {};
}
watchInstrument(callback) {
this.instrumentChanged = callback;
}
process(frame) {
if (this.myId) {
this.members[this.myId].process(frame);
}
}
initialize(members, myId) {
this.myId = myId;
for (let memberId in members) {
let memberData = {
id: memberId,
data: members[memberId]
};
this.updateMember(memberData);
}
}
play(data) {
// Play music with any of the clients' instruments
// Note: This data comes from the server
this.members[data.id].play(data.data);
}
updateMember(memberData) {
// console.log('updateMember()');
// console.log(memberData);
if (!(memberData.id in this.members)) {
this.members[memberData.id] = new Member(socket, memberData.data);
// console.log('Adding new member');
}
let changed = this.members[memberData.id].update(memberData.data);
if (changed && memberData.id == this.myId && this.instrumentChanged) {
this.instrumentChanged(this.members[memberData.id].getInstrumentName());
}
// console.log(this.members);
}
removeMember(memberData) {
delete this.members[memberData.id];
}
}
|
/* global __ */
/* eslint-disable
func-style,
no-param-reassign,
object-shorthand
*/
/**
* A stored procedure for Azure DocumentDB which gets a count of the session documents
* @function
* @param {String} filterOn = 'type' The key to filter documents on for deletion.
* @param {String} filterValue = 'session' The value that a document's filter key must have to be counted
* @param {String} [continuationToken] The previous continuation token, if any was passed
* @return {responseBody}
*/
function length(filterOn, filterValue, continuationToken) {
// set default filter key and value
filterOn = filterOn || 'type';
filterValue = filterValue || 'session';
const response = __.response; // get the response object
let documentsFound = 0;
/**
* The response body returned by the stored procedure
* @const
* @typedef {Object} responseBody
* @type {Object} responseBody
* @prop {Number} documentsFound The number of documents found so far.
* @prop {Boolean} continuation Whether there are still more documents to find.
*/
const responseBody = {
documentsFound: documentsFound,
continuation: false,
};
/**
* Filters for session documents based on the provider filter key {@link filterOn} and value {@link filterValue}, and adds the number of results to the running count
* @function
* @param {String} continuationToken The continuation token, if one was received from the previous request
*/
function getSessions(continuationToken) {
/**
* The filter function that returns a doc only if it has the given filter {@link filterOn} and {@link filterValue}
* @function
* @param {Object} doc The DocumentDB document to test against
* @return {Boolean} Whether the document has the given filter key and value
*/
const filter = function filter(doc) {
return doc[filterOn] === filterValue;
};
/**
* Handler for the filter request.
* @function
* @param {Object} err The error object, if any was thrown
* @param {Number} err.number The error code
* @param {String} err.body The body of the error message
* @param {Array} sessions An array of the retrieved sessions
* @param {Object} info Info about the request, including a continuation token
* @param {String} info.continuation The continuation token, if any was passed
* @return {responseBody}
*/
const handler = function handler(err, sessions, info) {
if (err) throw err;
// if sessions were found, add them to the running documents total
documentsFound += sessions.length;
if (info.continuation) {
// if there was a continuation token, get the next set of results
getSessions(info.continuation);
} else {
// otherwise, return the response body, including the count of the results
response.setBody(responseBody);
}
};
// filter the collection for sessions using the filter function
const accepted = __.filter(filter, { continuation: continuationToken }, handler);
// if the filter request is not accepted due to timeout, return the response with a continuation
if (!accepted) {
responseBody.continuation = continuationToken;
response.setBody(responseBody);
}
}
getSessions(continuationToken);
}
module.exports = length;
|
'use strict';
angular.module('mean.mean-admin').config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('manage', {
url: '/admin/manage',
templateUrl: 'mean-admin/views/manage.html'
});
}
]).config(['ngClipProvider',
function(ngClipProvider) {
ngClipProvider.setPath('../mean-admin/assets/lib/zeroclipboard/ZeroClipboard.swf');
}
]); |
class rectangleD {
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.left = 0;
this.right = 0;
this.top = 0;
this.bottom = 0;
this._computeProperties();
}
_computeProperties() {
this.left = this.x;
this.right = this.x + this.width;
this.top = this.y;
this.bottom = this.y + this.height;
}
contains(rect) {
return (rect.x > this.left && rect.x < this.right && rect.y > this.top && rect.y < this.bottom);
}
intersects(rect) {
return (this.left < rect.right && this.right > rect.left && this.top < rect.bottom && this.bottom > rect.top);
}
clone() {
return new rectangleD(this.x, this.y, this.width, this.height)
}
}
export default rectangleD; |
function insert_list(contents)
{
if (contents) {
contents = contents.trimRight("\n");
var colls = contents.split("\n");
colls = colls.map(function(coll) {
return "<li><a href=\"/" + coll + "/\">" + coll + "</a></li>";
});
contents = colls.join("\n");
}
document.body.innerHTML += "<p>Available Collections: <ul>" + contents + "</ul></p>";
}
function run()
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == XMLHttpRequest.DONE) {
if (ajax.status == 200) {
insert_list(ajax.responseText);
}
}
}
ajax.open("GET", "/cdx$?listColls=true", true);
ajax.send();
}
run();
|
import React from 'react'
import PropTypes from 'prop-types'
import SVGDeviconInline from '../../_base/SVGDeviconInline'
import iconSVG from './KrakenjsPlainWordmark.svg'
/** KrakenjsPlainWordmark */
function KrakenjsPlainWordmark({ width, height, className }) {
return (
<SVGDeviconInline
className={'KrakenjsPlainWordmark' + ' ' + className}
iconSVG={iconSVG}
width={width}
height={height}
/>
)
}
KrakenjsPlainWordmark.propTypes = {
className: PropTypes.string,
width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
}
export default KrakenjsPlainWordmark
|
var linkNav=document.querySelectorAll('[href^=\"#nav\"]'),V=0.2;
for(var i=0;i<linkNav.length;i++){
linkNav[i].onclick=function(){
var w=window.pageYOffset,hash=this.href.replace(/[^#]*(.*)/,'$1');
t=document.querySelector(hash).getBoundingClientRect().top,start=null;
requestAnimationFrame(step);
function step(time){
if(start===null) start=time;
var progress= time - start, r=(t<0?Math.max(w-progress/V,w+t):Math.min(w+progress/V,w+t));
window.scrollTo(0,r);
if(r!=w+t){
requestAnimationFrame(step)
}else{
location.hash=hash
}
}
return false;
}
} |
#!/usr/bin/env node
/*******************************************************************************
* vim: tabstop=4:shiftwidth=4:expandtab:
******************************************************************************/
'use strict';
const expandTilde = require('expand-tilde');
const fs = require('fs-extra');
const path = require('path');
function mvToMovedSync(filepath) {
const dest = (l) => expandTilde('~/tmp/moved/') + path.basename(l);
if(fs.pathExistsSync(filepath)) {
//console.log('Link Name exists', answer.linkName);
fs.moveSync(
filepath,
dest(filepath),
{'overwrite': true}
);
} else {
console.warn('Filepath "%"s does not exist. Cannot copy.', filepath);
}
}
module.exports = mvToMovedSync;
|
import loopback from 'ember-cli-loopback-adapter/serializers/loopback';
export default loopback;
|
import _ from 'underscore';
import s from 'underscore.string';
import { Meteor } from 'meteor/meteor';
import { Tracker } from 'meteor/tracker';
import { Template } from 'meteor/templating';
import { Session } from 'meteor/session';
import { TAPi18n } from 'meteor/rocketchat:tap-i18n';
import { timeAgo, formatDateAndTime } from '../../lib/client/lib/formatDate';
import { DateFormat } from '../../lib/client';
import { renderMessageBody, MessageTypes, MessageAction, call, normalizeThreadMessage } from '../../ui-utils/client';
import { RoomRoles, UserRoles, Roles, Messages } from '../../models/client';
import { callbacks } from '../../callbacks/client';
import { Markdown } from '../../markdown/client';
import { t, roomTypes } from '../../utils';
import { upsertMessage } from '../../ui-utils/client/lib/RoomHistoryManager';
import './message.html';
import './messageThread.html';
import { AutoTranslate } from '../../autotranslate/client';
const renderBody = (msg, settings) => {
const searchedText = msg.searchedText ? msg.searchedText : '';
const isSystemMessage = MessageTypes.isSystemMessage(msg);
const messageType = MessageTypes.getType(msg) || {};
if (messageType.render) {
msg = messageType.render(msg);
} else if (messageType.template) {
// render template
} else if (messageType.message) {
msg.msg = s.escapeHTML(msg.msg);
msg = TAPi18n.__(messageType.message, { ...typeof messageType.data === 'function' && messageType.data(msg) });
} else if (msg.u && msg.u.username === settings.Chatops_Username) {
msg.html = msg.msg;
msg = callbacks.run('renderMentions', msg);
msg = msg.html;
} else {
msg = renderMessageBody(msg);
}
if (isSystemMessage) {
msg.html = Markdown.parse(msg.html);
}
if (searchedText) {
msg = msg.replace(new RegExp(searchedText, 'gi'), (str) => `<mark>${ str }</mark>`);
}
return msg;
};
Template.message.helpers({
body() {
const { msg, settings } = this;
return Tracker.nonreactive(() => renderBody(msg, settings));
},
i18nReplyCounter() {
const { msg } = this;
return `<span class='reply-counter'>${ msg.tcount }</span>`;
},
i18nDiscussionCounter() {
const { msg } = this;
return `<span class='reply-counter'>${ msg.dcount }</span>`;
},
formatDateAndTime,
encodeURI(text) {
return encodeURI(text);
},
broadcast() {
const { msg, room = {}, u } = this;
return !msg.private && !msg.t && msg.u._id !== u._id && room && room.broadcast;
},
isIgnored() {
const { ignored, msg } = this;
const isIgnored = typeof ignored !== 'undefined' ? ignored : msg.ignored;
return isIgnored;
},
ignoredClass() {
const { ignored, msg } = this;
const isIgnored = typeof ignored !== 'undefined' ? ignored : msg.ignored;
return isIgnored ? 'message--ignored' : '';
},
isDecrypting() {
const { msg } = this;
return msg.e2e === 'pending';
},
isBot() {
const { msg } = this;
return msg.bot && 'bot';
},
roleTags() {
const { msg, hideRoles, settings } = this;
if (settings.hideRoles || hideRoles) {
return [];
}
if (!msg.u || !msg.u._id) {
return [];
}
const userRoles = UserRoles.findOne(msg.u._id);
const roomRoles = RoomRoles.findOne({
'u._id': msg.u._id,
rid: msg.rid,
});
const roles = [...(userRoles && userRoles.roles) || [], ...(roomRoles && roomRoles.roles) || []];
return Roles.find({
_id: {
$in: roles,
},
description: {
$exists: 1,
$ne: '',
},
}, {
fields: {
description: 1,
},
});
},
isGroupable() {
const { msg, room = {}, settings, groupable } = this;
if (groupable === false || settings.allowGroup === false || room.broadcast || msg.groupable === false || (MessageTypes.isSystemMessage(msg) && !msg.tmid)) {
return 'false';
}
},
avatarFromUsername() {
const { msg } = this;
if (msg.avatar != null && msg.avatar[0] === '@') {
return msg.avatar.replace(/^@/, '');
}
},
getStatus() {
const { msg } = this;
return Session.get(`user_${ msg.u.username }_status_text`);
},
getName() {
const { msg, settings } = this;
if (msg.alias) {
return msg.alias;
}
if (!msg.u) {
return '';
}
return (settings.UI_Use_Real_Name && msg.u.name) || msg.u.username;
},
showUsername() {
const { msg, settings } = this;
return msg.alias || (settings.UI_Use_Real_Name && msg.u && msg.u.name);
},
own() {
const { msg, u } = this;
if (msg.u && msg.u._id === u._id) {
return 'own';
}
},
t() {
const { msg } = this;
return msg.t;
},
timestamp() {
const { msg } = this;
return +msg.ts;
},
chatops() {
const { msg, settings } = this;
if (msg.u && msg.u.username === settings.Chatops_Username) {
return 'chatops-message';
}
},
time() {
const { msg, timeAgo: useTimeAgo } = this;
return useTimeAgo ? timeAgo(msg.ts) : DateFormat.formatTime(msg.ts);
},
date() {
const { msg } = this;
return DateFormat.formatDate(msg.ts);
},
isTemp() {
const { msg } = this;
if (msg.temp === true) {
return 'temp';
}
},
threadMessage() {
const { msg } = this;
return normalizeThreadMessage(msg);
},
bodyClass() {
const { msg } = this;
return MessageTypes.isSystemMessage(msg) ? 'color-info-font-color' : 'color-primary-font-color';
},
system(returnClass) {
const { msg } = this;
if (MessageTypes.isSystemMessage(msg)) {
if (returnClass) {
return 'color-info-font-color';
}
return 'system';
}
},
showTranslated() {
const { msg, subscription, settings, u } = this;
if (settings.AutoTranslate_Enabled && msg.u && msg.u._id !== u._id && !MessageTypes.isSystemMessage(msg)) {
const autoTranslate = subscription && subscription.autoTranslate;
return msg.autoTranslateFetching || (!!autoTranslate !== !!msg.autoTranslateShowInverse && msg.translations && msg.translations[settings.translateLanguage]);
}
},
translationProvider() {
const instance = Template.instance();
const { translationProvider } = instance.data.msg;
return translationProvider && AutoTranslate.providersMetadata[translationProvider].displayName;
},
edited() {
const { msg } = this;
return msg.editedAt && !MessageTypes.isSystemMessage(msg);
},
editTime() {
const { msg } = this;
return msg.editedAt ? DateFormat.formatDateAndTime(msg.editedAt) : '';
},
editedBy() {
const { msg } = this;
if (!msg.editedAt) {
return '';
}
// try to return the username of the editor,
// otherwise a special "?" character that will be
// rendered as a special avatar
return (msg.editedBy && msg.editedBy.username) || '?';
},
label() {
const { msg } = this;
if (msg.i18nLabel) {
return t(msg.i18nLabel);
} if (msg.label) {
return msg.label;
}
},
hasOembed() {
const { msg, settings } = this;
// there is no URLs, there is no template to show the oembed (oembed package removed) or oembed is not enable
if (!(msg.urls && msg.urls.length > 0) || !Template.oembedBaseWidget || !settings.API_Embed) {
return false;
}
// check if oembed is disabled for message's sender
if ((settings.API_EmbedDisabledFor || '').split(',').map((username) => username.trim()).includes(msg.u && msg.u.username)) {
return false;
}
return true;
},
reactions() {
const { msg: { reactions = {} }, u: { username: myUsername, name: myName } } = this;
return Object.entries(reactions)
.map(([emoji, reaction]) => {
const myDisplayName = reaction.names ? myName : `@${ myUsername }`;
const displayNames = reaction.names || reaction.usernames.map((username) => `@${ username }`);
const selectedDisplayNames = displayNames.slice(0, 15).filter((displayName) => displayName !== myDisplayName);
if (displayNames.some((displayName) => displayName === myDisplayName)) {
selectedDisplayNames.unshift(t('You'));
}
let usernames;
if (displayNames.length > 15) {
usernames = `${ selectedDisplayNames.join(', ') } ${ t('And_more', { length: displayNames.length - 15 }).toLowerCase() }`;
} else if (displayNames.length > 1) {
usernames = `${ selectedDisplayNames.slice(0, -1).join(', ') } ${ t('and') } ${ selectedDisplayNames[selectedDisplayNames.length - 1] }`;
} else {
usernames = selectedDisplayNames[0];
}
return {
emoji,
count: displayNames.length,
usernames,
reaction: ` ${ t('Reacted_with').toLowerCase() } ${ emoji }`,
userReacted: displayNames.indexOf(myDisplayName) > -1,
};
});
},
markUserReaction(reaction) {
if (reaction.userReacted) {
return {
class: 'selected',
};
}
},
hideReactions() {
const { msg } = this;
if (_.isEmpty(msg.reactions)) {
return 'hidden';
}
},
hideMessageActions() {
const { msg } = this;
return msg.private || MessageTypes.isSystemMessage(msg);
},
actionLinks() {
const { msg } = this;
// remove 'method_id' and 'params' properties
return _.map(msg.actionLinks, function(actionLink, key) {
return _.extend({
id: key,
}, _.omit(actionLink, 'method_id', 'params'));
});
},
hideActionLinks() {
const { msg } = this;
if (_.isEmpty(msg.actionLinks)) {
return 'hidden';
}
},
injectMessage(data, { _id, rid }) {
data.msg = { _id, rid };
},
injectIndex(data, index) {
data.index = index;
},
injectSettings(data, settings) {
data.settings = settings;
},
channelName() {
const { subscription } = this;
// const subscription = Subscriptions.findOne({ rid: this.rid });
return subscription && subscription.name;
},
roomIcon() {
const { room } = this;
if (room && room.t === 'd') {
return 'at';
}
return roomTypes.getIcon(room);
},
customClass() {
const { customClass, msg } = this;
return customClass || msg.customClass;
},
fromSearch() {
const { customClass, msg } = this;
return [msg.customClass, customClass].includes('search');
},
actionContext() {
const { msg } = this;
return msg.actionContext;
},
messageActions(group) {
const { msg, context: ctx } = this;
let messageGroup = group;
let context = ctx || msg.actionContext;
if (!group) {
messageGroup = 'message';
}
if (!context) {
context = 'message';
}
return MessageAction.getButtons(this, context, messageGroup);
},
isSnippet() {
const { msg } = this;
return msg.actionContext === 'snippeted';
},
isThreadReply() {
const { groupable, msg: { tmid, t, groupable: _groupable }, settings: { showreply } } = this;
return !(groupable === true || _groupable === true) && !!(tmid && showreply && (!t || t === 'e2e'));
},
collapsed() {
const { msg: { tmid, collapsed }, settings: { showreply }, shouldCollapseReplies } = this;
const isCollapsedThreadReply = shouldCollapseReplies && tmid && showreply && collapsed !== false;
if (isCollapsedThreadReply) {
return 'collapsed';
}
},
collapseSwitchClass() {
const { msg: { collapsed = true } } = this;
return collapsed ? 'icon-right-dir' : 'icon-down-dir';
},
parentMessage() {
const { msg: { threadMsg } } = this;
return threadMsg;
},
showStar() {
const { msg } = this;
return msg.starred && !(msg.actionContext === 'starred' || this.context === 'starred');
},
});
const findParentMessage = (() => {
const waiting = [];
const uid = Tracker.nonreactive(() => Meteor.userId());
const getMessages = _.debounce(async function() {
const _tmp = [...waiting];
waiting.length = 0;
(await call('getMessages', _tmp)).map((msg) => Messages.findOne({ _id: msg._id }) || upsertMessage({ msg: { ...msg, _hidden: true }, uid }));
}, 500);
return (tmid) => {
if (waiting.indexOf(tmid) > -1) {
return;
}
const message = Messages.findOne({ _id: tmid });
if (!message) {
waiting.push(tmid);
return getMessages();
}
return Messages.update(
{ tmid, repliesCount: { $exists: 0 } },
{
$set: {
following: message.replies && message.replies.indexOf(uid) > -1,
threadMsg: normalizeThreadMessage(message),
repliesCount: message.tcount,
},
},
{ multi: true },
);
};
})();
Template.message.onCreated(function() {
const { msg, shouldCollapseReplies } = Template.currentData();
if (shouldCollapseReplies && msg.tmid && !msg.threadMsg) {
findParentMessage(msg.tmid);
}
});
const hasTempClass = (node) => node.classList.contains('temp');
const getPreviousSentMessage = (currentNode) => {
if (hasTempClass(currentNode)) {
return currentNode.previousElementSibling;
}
if (currentNode.previousElementSibling != null) {
let previousValid = currentNode.previousElementSibling;
while (previousValid != null && (hasTempClass(previousValid) || !previousValid.classList.contains('message'))) {
previousValid = previousValid.previousElementSibling;
}
return previousValid;
}
};
const isNewDay = (currentNode, previousNode, forceDate, showDateSeparator) => {
if (!showDateSeparator) {
return false;
}
if (forceDate || !previousNode) {
return true;
}
const { dataset: currentDataset } = currentNode;
const { dataset: previousDataset } = previousNode;
const previousMessageDate = new Date(parseInt(previousDataset.timestamp));
const currentMessageDate = new Date(parseInt(currentDataset.timestamp));
if (previousMessageDate.toDateString() !== currentMessageDate.toDateString()) {
return true;
}
return false;
};
const isSequential = (currentNode, previousNode, forceDate, period, showDateSeparator, shouldCollapseReplies) => {
if (!previousNode) {
return false;
}
if (showDateSeparator && forceDate) {
return false;
}
const { dataset: currentDataset } = currentNode;
const { dataset: previousDataset } = previousNode;
const previousMessageDate = new Date(parseInt(previousDataset.timestamp));
const currentMessageDate = new Date(parseInt(currentDataset.timestamp));
if (showDateSeparator && previousMessageDate.toDateString() !== currentMessageDate.toDateString()) {
return false;
}
if (shouldCollapseReplies && currentDataset.tmid) {
return previousDataset.id === currentDataset.tmid || previousDataset.tmid === currentDataset.tmid;
}
if (previousDataset.tmid && !currentDataset.tmid) {
return false;
}
if ([previousDataset.groupable, currentDataset.groupable].includes('false')) {
return false;
}
if (previousDataset.username !== currentDataset.username) {
return false;
}
if (previousDataset.alias !== currentDataset.alias) {
return false;
}
if (parseInt(currentDataset.timestamp) - parseInt(previousDataset.timestamp) <= period) {
return true;
}
return false;
};
const processSequentials = ({ index, currentNode, settings, forceDate, showDateSeparator = true, groupable, shouldCollapseReplies }) => {
if (!showDateSeparator && !groupable) {
return;
}
// const currentDataset = currentNode.dataset;
const previousNode = (index === undefined || index > 0) && getPreviousSentMessage(currentNode);
const nextNode = currentNode.nextElementSibling;
if (isSequential(currentNode, previousNode, forceDate, settings.Message_GroupingPeriod, showDateSeparator, shouldCollapseReplies)) {
currentNode.classList.add('sequential');
} else {
currentNode.classList.remove('sequential');
}
if (isNewDay(currentNode, previousNode, forceDate, showDateSeparator)) {
currentNode.classList.add('new-day');
} else {
currentNode.classList.remove('new-day');
}
if (nextNode && nextNode.dataset) {
if (isSequential(nextNode, currentNode, forceDate, settings.Message_GroupingPeriod, showDateSeparator, shouldCollapseReplies)) {
nextNode.classList.add('sequential');
} else {
nextNode.classList.remove('sequential');
}
if (isNewDay(nextNode, currentNode, forceDate, showDateSeparator)) {
nextNode.classList.add('new-day');
} else {
nextNode.classList.remove('new-day');
}
}
};
Template.message.onRendered(function() {
const currentNode = this.firstNode;
this.autorun(() => processSequentials({ currentNode, ...Template.currentData() }));
});
|
/**
* Game.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/#!documentation/models
*/
module.exports = {
autoWatch: false,
autosubscribe: ['message', 'update', 'destroy'],
attributes: {
active: {type: 'boolean',
required: true,
defaultsTo: false},
name: {type: 'string',
required: true},
rooms: {collection: 'room',
via: 'game'},
startingRoom: {model: 'room',
required: false},
players: {collection: 'player',
via: 'game'},
traitor: {model: 'player',
required: false},
haunt: {type: 'string',
required: false},
},
checkWin: function(gameID, roomID) {
Game.findOne(gameID).populate('players')
.then(function(game) {
if (game === undefined) {
throw new Error('Game could not be found.');
}
if (game.haunt === undefined) {
return;
}
for (var i = 0; i < game.players.length; i++) {
var p = game.players[i];
if (!p.isTraitor && p.room !== roomID) {
return;
}
}
/* If we made it through, then the heroes won. */
Game.message(game.id, {verb: 'heroesWon'});
})
.catch(function(err) {
sails.log.error(err);
});
},
startHaunt: function(gameID) {
var game;
Game.findOne(gameID).populate('players').populate('rooms')
.then(function(found) {
if (found === undefined) {
throw new Error("Game could not be found.");
}
game = found;
if (game.haunt !== undefined) {
sails.log.info("Haunt already started.");
throw new sails.promise.CancellationError();
}
var traitor = game.players[Math.floor(Math.random()
* game.players.length)];
var allHaunts = _.keys(Game.haunts);
var haunt;
if (process.env.haunt != undefined) {
haunt = process.env.haunt;
} else {
haunt = allHaunts[Math.floor(Math.random() * allHaunts.length)];
}
sails.log.info("Haunt is " + haunt);
return Game.update(game.id, {traitor: traitor, haunt: haunt});
})
.then(function(updatedGames) {
var updatedGame = updatedGames[0];
Game.publishUpdate(updatedGame.id, {traitor: updatedGame.traitor, haunt: updatedGame.haunt});
var itemsToCreate = [];
var numKeysToPlace = 2 * (game.players.length - 1);
var allRooms = game.rooms.slice(0);
var exithallwaysToCreate = [];
_.times(numKeysToPlace - 2, function(i) {
exithallwaysToCreate.push({ game: updatedGame.id,
name: 'exithallway',
background: Room.layouts.exithallway.floor,
wallSprite: Room.layouts.exithallway.wallSprite });
});
while (numKeysToPlace > 0) {
var chosenRoom = allRooms[Math.floor(Math.random() * allRooms.length)];
var possibleLocs = Room.layouts[chosenRoom.name].itemLocs;
if (possibleLocs.length == 0) {
continue;
}
var loc = possibleLocs[Math.floor(Math.random() * possibleLocs.length)];
itemsToCreate.push({ type: 'key',
stat: 'keys',
amount: 1,
gridX: loc.x,
gridY: loc.y,
room: chosenRoom,
game: game.id,
heroesOnly: true});
numKeysToPlace--;
}
sails.log.info('exit hallways to create');
sails.log.info(exithallwaysToCreate);
return [Item.create(itemsToCreate),
Room.findOne({ game: game.id, name: 'exithallway' }),
exithallwaysToCreate];
}).spread(function(items, firstExit, exitHallwaysToCreate) {
_.each(items, function(item) {
Item.publishCreate(item);
});
var exit = {game: game.id, name: 'exit', background: Room.layouts.exit.floor,
wallSprite: Room.layouts.exit.wallSprite};
return [firstExit, Room.create(exitHallwaysToCreate), Room.create(exit)];
})
.spread(function(firstExit, exitHallways, exit) {
var gatewaysToCreate = [];
var prevRoomID = firstExit.id;
_.each(exitHallways, function (room) {
gatewaysToCreate.push({ roomFrom: prevRoomID,
roomTo: room.id,
direction: 'south',
locked: true });
gatewaysToCreate.push({ roomFrom: room.id,
roomTo: prevRoomID,
direction: 'north',
locked: true });
prevRoomID = room.id;
});
gatewaysToCreate.push({ roomFrom: prevRoomID,
roomTo: exit.id,
direction: 'south',
locked: true });
gatewaysToCreate.push({ roomFrom: exit.id,
roomTo: prevRoomID,
direction: 'north',
locked: true });
sails.log.info('about to create gateways');
sails.log.info(gatewaysToCreate);
return Gateway.create(gatewaysToCreate);
})
.then(function(gateways) {
sails.log.info('gateways created');
sails.log.info(gateways);
})
.catch(sails.promise.CancellationError, function(err) {
sails.log.warn("Haunt already started.");
})
.catch(function(err) {
sails.log.error(err);
});
},
generateHouse: function(game, cb) {
var roomsToCreate = [];
var gatewaysToCreate = [];
var openGridLocs = [];
/* Put all rooms except the entryway, exit into allRooms and shuffle. */
var allRooms = _.keys(_.omit(Room.layouts, ['entryway', 'exithallway', 'exit', 'dummy']));
allRooms = _.shuffle(allRooms);
/* Sums the total abundance to make percentages of items relative. */
var totalAbundance = 0;
_.each(_.values(Item.kinds), function(i) {
totalAbundance += i.abundance;
});
sails.log.info(allRooms);
/* Add 2 items per room per the abundance specifications. */
var itemBank = [];
for (i in Item.kinds) {
_.times(Math.round(Item.kinds[i].abundance / totalAbundance
* allRooms.length * 2), function(n) {
itemBank.push(i);
});
}
/* Randomly order the items. */
itemBank = _.shuffle(itemBank);
var houseGrid = new Array(14);
for (var i = 0; i < houseGrid.length; i++) {
houseGrid[i] = new Array(16);
}
var entrywayLayout = Room.layouts.entryway;
var exitLayout = Room.layouts.exithallway;
var i = 7;
var j = 6;
houseGrid[i][j] = 'entryway';
openGridLocs.push([6,6], [7,5], [7,7]);
roomsToCreate.push({ game: game.id,
name: 'entryway',
background: entrywayLayout.floor,
wallSprite:
entrywayLayout.wallSprite });
houseGrid[i + 1][j] = 'exithallway';
roomsToCreate.push({ game: game.id,
name: 'exithallway',
background: exitLayout.floor,
wallSprite: entrywayLayout.wallSprite });
for (var k = i + 2; k < houseGrid.length; k++) {
houseGrid[k][j] = 'dummy';
}
gatewaysToCreate.push({roomFrom: 'entryway',
roomTo: 'exithallway',
direction: 'south',
locked: true});
gatewaysToCreate.push({roomFrom: 'exithallway',
roomTo: 'entryway',
direction: 'north',
locked: true});
var roomID;
var room;
while (allRooms.length > 0) {
var randLoc = Math.floor(Math.random() * openGridLocs.length);
var itemsToCreate = [];
i = openGridLocs[randLoc][0];
j = openGridLocs[randLoc][1];
roomID = allRooms.shift();
room = Room.layouts[roomID];
var fits = false;
var roomNorthID = (i == 0 ? null : houseGrid[i - 1][j]);
var roomEastID = (j == houseGrid[0].length - 1
? null : houseGrid[i][j + 1]);
var roomSouthID = (i == houseGrid.length - 1
? null : houseGrid[i + 1][j]);
var roomWestID = (j == 0 ? null : houseGrid[i][j - 1]);
var roomNorth = Room.layouts[roomNorthID];
var roomEast = Room.layouts[roomEastID];
var roomSouth = Room.layouts[roomSouthID];
var roomWest = Room.layouts[roomWestID];
if (roomNorth != null && room.gateways.north
&& roomNorth.gateways.south) {
fits = true;
}
if (roomEast != null && room.gateways.east
&& roomEast.gateways.west) {
fits = true;
}
if (roomSouth != null && room.gateways.south
&& roomSouth.gateways.north) {
fits = true;
}
if (roomWest != null && room.gateways.west
&& roomWest.gateways.east) {
fits = true;
}
if (!fits) {
allRooms.push(roomID);
continue;
}
houseGrid[i][j] = roomID;
openGridLocs = _.filter(openGridLocs, function(loc) {
return !(_.isEqual(loc, [i, j]));
});
var possibleLocs = Room.layouts[roomID].itemLocs.slice(0);
_.times(Math.min(1, possibleLocs.length), function(n) {
var item = itemBank.pop();
var index = Math.floor(Math.random() * possibleLocs.length);
var loc = possibleLocs[index];
possibleLocs.splice(index, 1);
itemsToCreate.push({type: item,
stat: Item.kinds[item].stat,
amount: Item.kinds[item].amount,
gridX: loc.x,
gridY: loc.y,
game: game.id});
});
roomsToCreate.push({game: game.id,
name: roomID,
background: room.floor,
wallSprite: room.wallSprite,
items: itemsToCreate});
if (room.gateways.north && houseGrid[i - 1][j] == undefined) {
openGridLocs.push([i - 1, j]);
}
if (room.gateways.east && houseGrid[i][j + 1] == undefined) {
openGridLocs.push([i, j + 1]);
}
if (room.gateways.south && houseGrid[i + 1][j] == undefined) {
openGridLocs.push([i + 1, j]);
}
if (room.gateways.west && houseGrid[i][j - 1] == undefined) {
openGridLocs.push([i, j - 1]);
}
}
var interactableObjects = [];
for (var i = 0; i < houseGrid.length; i++) {
for (var j = 0; j < houseGrid[0].length; j++) {
var thisRoomID = houseGrid[i][j];
if (thisRoomID === undefined) {
continue;
}
var thisRoom = Room.layouts[thisRoomID];
_.each(_.keys(thisRoom.objects), function(k) {
var id = k;
var o = thisRoom.objects[k];
if (_.has(Room.interactable, o.type)) {
interactableObjects.push({room: thisRoomID,
container: id});
}
});
var roomNorthID = (i == 0 ? null : houseGrid[i - 1][j]);
var roomEastID = (j == houseGrid[0].length - 1
? null : houseGrid[i][j + 1]);
var roomSouthID = (i == houseGrid.length - 1
? null : houseGrid[i + 1][j]);
var roomWestID = (j == 0 ? null : houseGrid[i][j - 1]);
var roomNorth = Room.layouts[roomNorthID];
var roomEast = Room.layouts[roomEastID];
var roomSouth = Room.layouts[roomSouthID];
var roomWest = Room.layouts[roomWestID];
if (roomNorth != null && thisRoom.gateways.north
&& roomNorth.gateways.south) {
gatewaysToCreate.push({roomFrom: thisRoomID,
roomTo: roomNorthID,
direction: 'north'})
}
if (roomEast != null && thisRoom.gateways.east
&& roomEast.gateways.west) {
gatewaysToCreate.push({roomFrom: thisRoomID,
roomTo: roomEastID,
direction: 'east'})
}
if (roomSouth != null && thisRoom.gateways.south
&& roomSouth.gateways.north) {
gatewaysToCreate.push({roomFrom: thisRoomID,
roomTo: roomSouthID,
direction: 'south'})
}
if (roomWest != null && thisRoom.gateways.west
&& roomWest.gateways.east) {
gatewaysToCreate.push({roomFrom: thisRoomID,
roomTo: roomWestID,
direction: 'west'})
}
}
}
var eventsToCreate = [];
var databaseID = {};
Room.create(roomsToCreate)
.then(function(rooms) {
rooms.forEach(function(v, i, a) {
databaseID[v.name] = v.id;
});
gatewaysToCreate.forEach(function(v, i, a) {
v.roomFrom = databaseID[v.roomFrom];
v.roomTo = databaseID[v.roomTo];
});
return Gateway.create(gatewaysToCreate);
})
.then(function(gateways) {
/* Shuffle the interactable objects. */
interactableObjects = _.shuffle(interactableObjects);
/* Randomly select objects to put events in. */
_.each(_.keys(Game.cards), function(c) {
var object = interactableObjects.pop();
var event = {
room: databaseID[object.room],
container: object.container,
card: c,
game: game
};
eventsToCreate.push(event);
});
sails.log.info(eventsToCreate);
return Event.create(eventsToCreate)
})
.catch(function(err) {
sails.log.error(err);
})
.done(function() {
cb(databaseID['entryway']);
});
},
hauntCutoff: function(relicsFound, maxRelics) {
return Math.pow(2, relicsFound) / Math.pow(2, maxRelics);
},
minPlayers: sails.config.gameconfig.minPlayers,
maxPlayers: sails.config.gameconfig.maxPlayers,
sprites: sails.config.gameconfig.sprites,
cards: sails.config.gameconfig.cards,
haunts: sails.config.gameconfig.haunts,
};
|
/*globals requireJS*/
/*jshint node:true*/
/**
* This class forwards function calls to the storage and in addition:
* - checks that input data is of correct format.
* - checks that users are authorized to access/change projects.
* - updates _users and _projects collections on delete/createProject.
*
* @module Server:SafeStorage
* @author pmeijer / https://github.com/pmeijer
*/
'use strict';
var Q = require('q'),
REGEXP = requireJS('common/regexp'),
ASSERT = requireJS('common/util/assert'),
Storage = require('./storage'),
UserProject = require('./userproject');
function check(cond, deferred, msg) {
var rejected = false;
if (!cond) {
deferred.reject(new Error('Invalid argument, ' + msg));
rejected = true;
}
return rejected;
}
function filterArray(arr) {
var i,
filtered = [];
for (i = 0; i < arr.length; i += 1) {
if (typeof arr[i] !== 'undefined') {
filtered.push(arr[i]);
}
}
return filtered;
}
/**
*
* @param mongo
* @param logger
* @param gmeConfig
* @param gmeAuth
* @constructor
*/
function SafeStorage(mongo, logger, gmeConfig, gmeAuth) {
ASSERT(gmeAuth !== null && typeof gmeAuth === 'object', 'gmeAuth is a mandatory parameter');
Storage.call(this, mongo, logger, gmeConfig);
this.gmeAuth = gmeAuth;
}
// Inherit from Storage
SafeStorage.prototype = Object.create(Storage.prototype);
SafeStorage.prototype.constructor = SafeStorage;
/**
* Returns and array of dictionaries for each project the user has at least read access to.
* If branches is set, the returned array will be filtered based on if the projects really do exist as
* collections on their own. If branches is not set, there is no guarantee that the returned projects
* really exist.
*
* Authorization level: read access for each returned project.
*
* @param {object} data - input parameters
* @param {boolean} [data.info] - include the info field from the _projects collection.
* @param {boolean} [data.rights] - include users' authorization information for each project.
* @param {boolean} [data.branches] - include a dictionary with all branches and their hash.
* @param {string} [data.username=gmeConfig.authentication.guestAccount]
* @param {function} [callback]
* @returns {promise} //TODO: jsdocify this
*/
SafeStorage.prototype.getProjects = function (data, callback) {
var deferred = Q.defer(),
self = this,
rejected = false;
rejected = check(data !== null && typeof data === 'object', deferred, 'data is not an object.') ||
check(typeof data.info === 'undefined' || typeof data.info === 'boolean', deferred,
'data.info is not a boolean.') ||
check(typeof data.rights === 'undefined' || typeof data.rights === 'boolean', deferred,
'data.rights is not a boolean.') ||
check(typeof data.branches === 'undefined' || typeof data.branches === 'boolean', deferred,
'data.branches is not a boolean.');
if (data.hasOwnProperty('username')) {
rejected = rejected || check(typeof data.username === 'string', deferred, 'data.username is not a string.');
} else {
data.username = this.gmeConfig.authentication.guestAccount;
}
if (rejected === false) {
this.gmeAuth.getProjectAuthorizationListByUserId(data.username)
.then(function (authorizedProjects) {
var projectIds = Object.keys(authorizedProjects);
self.logger.debug('user has rights to', projectIds);
function getProjectAppendRights(projectId) {
var projectDeferred = Q.defer();
self.gmeAuth.getProject(projectId)
.then(function (project) {
if (authorizedProjects[projectId].read === true) {
if (data.rights === true) {
project.rights = authorizedProjects[projectId];
}
if (!data.info) {
delete project.info;
}
projectDeferred.resolve(project);
} else {
projectDeferred.resolve();
}
})
.catch(function (err) {
if (err.message.indexOf('no such project') > -1) {
self.logger.error('Inconsistency: project exists in user "' + data.username +
'" but not in _projects: ', projectId);
projectDeferred.resolve();
} else {
projectDeferred.reject(err);
}
});
return projectDeferred.promise;
}
return Q.all(projectIds.map(getProjectAppendRights));
})
.then(function (projects) {
function getBranches(project) {
var branchesDeferred = Q.defer();
Storage.prototype.getBranches.call(self, {projectId: project._id})
.then(function (branches) {
project.branches = branches;
branchesDeferred.resolve(project);
})
.catch(function (err) {
if (err.message.indexOf('Project does not exist') > -1) {
//TODO: clean up in _projects and _users here too?
self.logger.error('Inconsistency: project exists in user "' + data.username +
'" and in _projects, but not as a collection on its own: ', project._id);
branchesDeferred.resolve();
} else {
branchesDeferred.reject(err);
}
});
return branchesDeferred.promise;
}
if (data.branches === true) {
return Q.all(filterArray(projects).map(getBranches));
} else {
deferred.resolve(filterArray(projects));
}
})
.then(function (projectsAndBranches) {
deferred.resolve(filterArray(projectsAndBranches));
})
.catch(function (err) {
deferred.reject(new Error(err));
});
}
return deferred.promise.nodeify(callback);
};
/**
* Deletes a project from the _projects collection, deletes the collection for the the project and removes
* the rights from all users.
*
* Authorization level: delete access for project
*
* @param {object} data - input parameters
* @param {string} data.projectId - identifier for project.
* @param {string} [data.username=gmeConfig.authentication.guestAccount]
* @param {function} [callback]
* @returns {promise} //TODO: jsdocify this
*/
SafeStorage.prototype.deleteProject = function (data, callback) {
var deferred = Q.defer(),
rejected = false,
didExist,
self = this;
rejected = check(data !== null && typeof data === 'object', deferred, 'data is not an object.') ||
check(typeof data.projectId === 'string', deferred, 'data.projectId is not a string.') ||
check(REGEXP.PROJECT.test(data.projectId), deferred, 'data.projectId failed regexp: ' + data.projectId);
if (data.hasOwnProperty('username')) {
rejected = rejected || check(typeof data.username === 'string', deferred, 'data.username is not a string.');
} else {
data.username = this.gmeConfig.authentication.guestAccount;
}
if (rejected === false) {
this.gmeAuth.getProjectAuthorizationByUserId(data.username, data.projectId)
.then(function (projectAccess) {
if (projectAccess.delete) {
return Storage.prototype.deleteProject.call(self, data);
} else {
throw new Error('Not authorized: cannot delete project. ' + data.projectId);
}
})
.then(function (didExist_) {
didExist = didExist_;
return self.gmeAuth.deleteProject(data.projectId);
})
.then(function () {
deferred.resolve(didExist);
})
.catch(function (err) {
deferred.reject(new Error(err));
});
}
return deferred.promise.nodeify(callback);
};
/**
* Creates a project and assigns a projectId by concatenating the username and the provided project name.
* The user with the given username becomes the owner of the project.
*
* Authorization level: canCreate
*
* @param {object} data - input parameters
* @param {string} data.projectName - name of new project.
* @param {string} [data.username=gmeConfig.authentication.guestAccount]
* @param {string} [data.ownerId=data.username]
* @param {function} [callback]
* @returns {promise} //TODO: jsdocify this
*/
SafeStorage.prototype.createProject = function (data, callback) {
var deferred = Q.defer(),
rejected = false,
self = this;
rejected = check(data !== null && typeof data === 'object', deferred, 'data is not an object.') ||
check(typeof data.projectName === 'string', deferred, 'data.projectName is not a string.') ||
check(REGEXP.PROJECT.test(data.projectName), deferred, 'data.projectName failed regexp: ' + data.projectName);
if (data.hasOwnProperty('username')) {
rejected = rejected || check(typeof data.username === 'string', deferred, 'data.username is not a string.');
} else {
data.username = this.gmeConfig.authentication.guestAccount;
}
if (data.ownerId) {
rejected = rejected || check(typeof data.ownerId === 'string', deferred, 'data.ownerId is not a string.');
} else {
data.ownerId = data.username;
}
if (rejected === false) {
this.gmeAuth.getUser(data.username)
.then(function (user) {
if (!user.canCreate) {
throw new Error('Not authorized to create a new project.');
} else if (data.ownerId === data.username) {
return data.ownerId;
} else {
return self.gmeAuth.getAdminsInOrganization(data.ownerId)
.then(function (admins) {
if (admins.indexOf(data.username) > -1) {
return data.ownerId;
} else {
throw new Error('Not authorized to create project in organization ' + data.ownerId);
}
});
}
})
.then(function (ownerId) {
var info = {
createdAt: (new Date()).toISOString()
};
return self.gmeAuth.addProject(ownerId, data.projectName, info);
})
.then(function (projectId) {
data.projectId = projectId;
return self.gmeAuth.authorizeByUserId(data.username, projectId, 'create', {
read: true,
write: true,
delete: true
});
})
.then(function () {
return Storage.prototype.createProject.call(self, data);
})
.then(function (dbProject) {
var project = new UserProject(dbProject, self, self.logger, self.gmeConfig);
deferred.resolve(project);
})
.catch(function (err) {
// TODO: Clean up appropriately when failure to add to model, user or projects database.
deferred.reject(new Error(err));
});
}
return deferred.promise.nodeify(callback);
};
/**
*
* @param data
* @param callback
* @returns {*}
*/
SafeStorage.prototype.transferProject = function (data, callback) {
var deferred = Q.defer(),
rejected = false,
self = this;
rejected = check(data !== null && typeof data === 'object', deferred, 'data is not an object.') ||
check(typeof data.projectId === 'string', deferred, 'data.projectId is not a string.') ||
check(REGEXP.PROJECT.test(data.projectId), deferred, 'data.projectId failed regexp: ' + data.projectId) ||
check(typeof data.newOwnerId === 'string', deferred, 'data.newOwnerId is not a string.');
if (data.hasOwnProperty('username')) {
rejected = rejected || check(typeof data.username === 'string', deferred, 'data.username is not a string.');
} else {
data.username = this.gmeConfig.authentication.guestAccount;
}
if (rejected === false) {
self.gmeAuth.getProjectAuthorizationByUserId(data.username, data.projectId)
.then(function (projectAccess) {
if (projectAccess.delete) {
return self.gmeAuth.getUserOrOrg(data.newOwnerId);
} else {
throw new Error('Not authorized to delete project: ' + data.projectId);
}
})
.then(function (newOwner) {
if (newOwner._id === data.username) {
} else if (newOwner.type === self.gmeAuth.CONSTANTS.ORGANIZATION) {
return self.gmeAuth.getAdminsInOrganization(newOwner._id)
.then(function (admins) {
if (admins.indexOf(data.username) === -1) {
throw new Error('Not authorized to transfer project to organization ' + newOwner._id);
}
});
} else {
throw new Error('Not authorized to transfer projects to other users ' + newOwner._id);
}
})
.then(function () {
return self.gmeAuth.transferProject(data.projectId, data.newOwnerId);
})
.then(function (newProjectId) {
data.newProjectId = newProjectId;
return Storage.prototype.renameProject.call(self, data);
})
.then(function (newProjectId) {
deferred.resolve(newProjectId);
})
.catch(function (err) {
deferred.reject(new Error(err));
});
}
return deferred.promise.nodeify(callback);
};
/**
* Returns a dictionary with all the branches and their hashes within a project.
* Example: {
* master: '#someHash',
* b1: '#someOtherHash'
* }
*
* Authorization level: read access for project
*
* @param {object} data - input parameters
* @param {string} data.projectId - identifier for project.
* @param {string} [data.username=gmeConfig.authentication.guestAccount]
* @param {function} [callback]
* @returns {promise} //TODO: jsdocify this
*/
SafeStorage.prototype.getBranches = function (data, callback) {
var deferred = Q.defer(),
rejected = false,
self = this;
rejected = check(data !== null && typeof data === 'object', deferred, 'data is not an object.') ||
check(typeof data.projectId === 'string', deferred, 'data.projectId is not a string.') ||
check(REGEXP.PROJECT.test(data.projectId), deferred, 'data.projectId failed regexp: ' + data.projectId);
if (data.hasOwnProperty('username')) {
rejected = rejected || check(typeof data.username === 'string', deferred, 'data.username is not a string.');
} else {
data.username = this.gmeConfig.authentication.guestAccount;
}
if (rejected === false) {
this.gmeAuth.getProjectAuthorizationByUserId(data.username, data.projectId)
.then(function (projectAccess) {
if (projectAccess.read) {
return Storage.prototype.getBranches.call(self, data);
} else {
throw new Error('Not authorized to read project: ' + data.projectId);
}
})
.then(function (result) {
deferred.resolve(result);
})
.catch(function (err) {
deferred.reject(new Error(err));
});
}
return deferred.promise.nodeify(callback);
};
/**
* Returns an array of commits for a project.
*
* Authorization level: read access for project
*
* @param {object} data - input parameters
* @param {string} data.projectId - identifier for project.
* @param {number} data.number - number of commits to load.
* @param {string|number} data.before - timestamp or commitHash to load history from. When number given it will load
* data.number of commits strictly before data.before, when commitHash is given it will return that commit too.
* @param {string} [data.username=gmeConfig.authentication.guestAccount]
* @param {function} [callback]
* @returns {promise} //TODO: jsdocify this
*/
SafeStorage.prototype.getCommits = function (data, callback) {
var deferred = Q.defer(),
rejected = false,
self = this;
rejected = check(data !== null && typeof data === 'object', deferred, 'data is not an object.') ||
check(typeof data.projectId === 'string', deferred, 'data.projectId is not a string.') ||
check(REGEXP.PROJECT.test(data.projectId), deferred, 'data.projectId failed regexp: ' + data.projectId) ||
check(typeof data.before === 'number' || typeof data.before === 'string', deferred,
'data.before is not a number nor string') ||
check(typeof data.number === 'number', deferred, 'data.number is not a number');
if (typeof data.before === 'string') {
rejected = rejected || check(REGEXP.HASH.test(data.before), deferred,
'data.before is not a number nor a valid hash.');
}
if (data.hasOwnProperty('username')) {
rejected = rejected || check(typeof data.username === 'string', deferred, 'data.username is not a string.');
} else {
data.username = this.gmeConfig.authentication.guestAccount;
}
if (rejected === false) {
this.gmeAuth.getProjectAuthorizationByUserId(data.username, data.projectId)
.then(function (projectAccess) {
if (projectAccess.read) {
return Storage.prototype.getCommits.call(self, data);
} else {
throw new Error('Not authorized to read project. ' + data.projectId);
}
})
.then(function (result) {
deferred.resolve(result);
})
.catch(function (err) {
deferred.reject(new Error(err));
});
}
return deferred.promise.nodeify(callback);
};
/**
* Returns the latest commit data for a branch within the project. (This is the same data that is provided during
* a BRANCH_UPDATE event.)
*
* Example: {
* projectId: 'guest+TestProject',
* branchName: 'master',
* commitObject: {
* _id: '#someCommitHash',
* root: '#someNodeHash',
* parents: ['#someOtherCommitHash'],
* update: ['guest'],
* time: 1430169614741,
* message: 'createChild(/1/2)',
* type: 'commit'
* },
* coreObject: [{coreObj}, ..., {coreObj}],
* }
*
* Authorization level: read access for project
*
* @param {object} data - input parameters
* @param {string} data.projectId - identifier for project.
* @param {string} data.branchName - name of the branch.
* @param {string} [data.username=gmeConfig.authentication.guestAccount]
* @param {function} [callback]
* @returns {promise} //TODO: jsdocify this
*/
SafeStorage.prototype.getLatestCommitData = function (data, callback) {
var deferred = Q.defer(),
rejected = false,
self = this;
rejected = check(data !== null && typeof data === 'object', deferred, 'data is not an object.') ||
check(typeof data.projectId === 'string', deferred, 'data.projectId is not a string.') ||
check(REGEXP.PROJECT.test(data.projectId), deferred, 'data.projectId failed regexp: ' + data.projectId) ||
check(typeof data.branchName === 'string', deferred, 'data.branchName is not a string.') ||
check(REGEXP.BRANCH.test(data.branchName), deferred, 'data.branchName failed regexp: ' + data.branchName);
if (data.hasOwnProperty('username')) {
rejected = rejected || check(typeof data.username === 'string', deferred, 'data.username is not a string.');
} else {
data.username = this.gmeConfig.authentication.guestAccount;
}
if (rejected === false) {
this.gmeAuth.getProjectAuthorizationByUserId(data.username, data.projectId)
.then(function (projectAccess) {
if (projectAccess.read) {
return Storage.prototype.getLatestCommitData.call(self, data);
} else {
throw new Error('Not authorized to read project. ' + data.projectId);
}
})
.then(function (result) {
deferred.resolve(result);
})
.catch(function (err) {
deferred.reject(new Error(err));
});
}
return deferred.promise.nodeify(callback);
};
/**
* Authorization: write access for data.projectId
* @param data
* @param callback
* @returns {*}
*/
SafeStorage.prototype.makeCommit = function (data, callback) {
var deferred = Q.defer(),
rejected = false,
self = this;
rejected = check(data !== null && typeof data === 'object', deferred, 'data is not an object.') ||
check(typeof data.projectId === 'string', deferred, 'data.projectId is not a string.') ||
check(REGEXP.PROJECT.test(data.projectId), deferred, 'data.projectId failed regexp: ' + data.projectId) ||
check(data.commitObject !== null && typeof data.commitObject === 'object', deferred,
'data.commitObject not an object.') ||
check(data.coreObjects !== null && typeof data.coreObjects === 'object', deferred,
'data.coreObjects not an object.');
// Checks when branchName is given and the branch will be updated
if (rejected === false && typeof data.branchName !== 'undefined') {
rejected = check(typeof data.branchName === 'string', deferred, 'data.branchName is not a string.') ||
check(REGEXP.BRANCH.test(data.branchName), deferred, 'data.branchName failed regexp: ' + data.branchName) ||
check(typeof data.commitObject._id === 'string', deferred, 'data.commitObject._id is not a string.') ||
check(typeof data.commitObject.root === 'string', deferred, 'data.commitObject.root is not a string.') ||
check(REGEXP.HASH.test(data.commitObject._id), deferred,
'data.commitObject._id is not a valid hash: ' + data.commitObject._id) ||
check(data.commitObject.parents instanceof Array, deferred,
'data.commitObject.parents is not an array.') ||
check(typeof data.commitObject.parents[0] === 'string', deferred,
'data.commitObject.parents[0] is not a string.') ||
check(data.commitObject.parents[0] === '' || REGEXP.HASH.test(data.commitObject.parents[0]), deferred,
'data.commitObject.parents[0] is not a valid hash: ' + data.commitObject.parents[0]) ||
check(REGEXP.HASH.test(data.commitObject.root), deferred,
'data.commitObject.root is not a valid hash: ' + data.commitObject.root);
// Commits without coreObjects is valid now (the assumption is that the rootObject does exist.
//check(typeof data.coreObjects[data.commitObject.root] === 'object', deferred,
// 'data.coreObjects[data.commitObject.root] is not an object');
if (typeof data.oldHash === 'string') {
// Provide the possibility to refer to an oldHash explicitly rather than from the commitObj,
// the is needed when e.g. undoing/redoing.
check(data.oldHash === '' || REGEXP.HASH.test(data.oldHash), deferred,
'data.oldHash is not a valid hash: ' + data.oldHash);
}
}
if (data.hasOwnProperty('username')) {
rejected = rejected || check(typeof data.username === 'string', deferred, 'data.username is not a string.');
} else {
data.username = this.gmeConfig.authentication.guestAccount;
}
if (rejected === false) {
this.gmeAuth.getProjectAuthorizationByUserId(data.username, data.projectId)
.then(function (projectAccess) {
if (projectAccess.write) {
return Storage.prototype.makeCommit.call(self, data);
} else {
throw new Error('Not authorized to write project. ' + data.projectId);
}
})
.then(function (result) {
deferred.resolve(result);
})
.catch(function (err) {
deferred.reject(new Error(err));
});
}
return deferred.promise.nodeify(callback);
};
/**
* Authorization: read access for data.projectId
* @param data
* @param callback
* @returns {*}
*/
SafeStorage.prototype.getBranchHash = function (data, callback) {
var deferred = Q.defer(),
rejected = false,
self = this;
rejected = check(data !== null && typeof data === 'object', deferred, 'data is not an object.') ||
check(typeof data.projectId === 'string', deferred, 'data.projectId is not a string.') ||
check(REGEXP.PROJECT.test(data.projectId), deferred, 'data.projectId failed regexp: ' + data.projectId) ||
check(typeof data.branchName === 'string', deferred, 'data.branchName is not a string.') ||
check(REGEXP.BRANCH.test(data.branchName), deferred, 'data.branchName failed regexp: ' + data.branchName);
if (data.hasOwnProperty('username')) {
rejected = rejected || check(typeof data.username === 'string', deferred, 'data.username is not a string.');
} else {
data.username = this.gmeConfig.authentication.guestAccount;
}
if (rejected === false) {
this.gmeAuth.getProjectAuthorizationByUserId(data.username, data.projectId)
.then(function (projectAccess) {
if (projectAccess.read) {
return Storage.prototype.getBranchHash.call(self, data);
} else {
throw new Error('Not authorized to read project. ' + data.projectId);
}
})
.then(function (result) {
deferred.resolve(result);
})
.catch(function (err) {
deferred.reject(new Error(err));
});
}
return deferred.promise.nodeify(callback);
};
/**
* Authorization: write access for data.projectId
* @param data
* @param callback
* @returns {*}
*/
SafeStorage.prototype.setBranchHash = function (data, callback) {
var deferred = Q.defer(),
rejected = false,
self = this;
rejected = check(data !== null && typeof data === 'object', deferred, 'data is not an object.') ||
check(typeof data.projectId === 'string', deferred, 'data.projectId is not a string.') ||
check(REGEXP.PROJECT.test(data.projectId), deferred, 'data.projectId failed regexp: ' + data.projectId) ||
check(typeof data.branchName === 'string', deferred, 'data.branchName is not a string.') ||
check(REGEXP.BRANCH.test(data.branchName), deferred, 'data.branchName failed regexp: ' + data.branchName) ||
check(typeof data.oldHash === 'string', deferred, 'data.oldHash is not a string.') ||
check(data.oldHash === '' || REGEXP.HASH.test(data.oldHash), deferred,
'data.oldHash is not a valid hash: ' + data.oldHash) ||
check(typeof data.newHash === 'string', deferred, 'data.newHash is not a string.') ||
check(data.newHash === '' || REGEXP.HASH.test(data.newHash), deferred,
'data.newHash is not a valid hash: ' + data.newHash);
if (data.hasOwnProperty('username')) {
rejected = rejected || check(typeof data.username === 'string', deferred, 'data.username is not a string.');
} else {
data.username = this.gmeConfig.authentication.guestAccount;
}
if (rejected === false) {
this.gmeAuth.getProjectAuthorizationByUserId(data.username, data.projectId)
.then(function (projectAccess) {
if (projectAccess.write) {
return Storage.prototype.setBranchHash.call(self, data);
} else {
throw new Error('Not authorized to write project. ' + data.projectId);
}
})
.then(function (result) {
deferred.resolve(result);
})
.catch(function (err) {
deferred.reject(new Error(err));
});
}
return deferred.promise.nodeify(callback);
};
/**
* Authorization: read access for data.projectId
* @param data
* @param callback
* @returns {*}
*/
SafeStorage.prototype.getCommonAncestorCommit = function (data, callback) {
var deferred = Q.defer(),
rejected = false,
self = this;
rejected = check(data !== null && typeof data === 'object', deferred, 'data is not an object.') ||
check(typeof data.projectId === 'string', deferred, 'data.projectId is not a string.') ||
check(REGEXP.PROJECT.test(data.projectId), deferred, 'data.projectId failed regexp: ' + data.projectId) ||
check(typeof data.commitA === 'string', deferred, 'data.commitA is not a string.') ||
check(data.commitA === '' || REGEXP.HASH.test(data.commitA), deferred,
'data.commitA is not a valid hash: ' + data.commitA) ||
check(typeof data.commitB === 'string', deferred, 'data.commitB is not a string.') ||
check(data.commitB === '' || REGEXP.HASH.test(data.commitB), deferred,
'data.commitB is not a valid hash: ' + data.commitB);
if (data.hasOwnProperty('username')) {
rejected = rejected || check(typeof data.username === 'string', deferred, 'data.username is not a string.');
} else {
data.username = this.gmeConfig.authentication.guestAccount;
}
if (rejected === false) {
this.gmeAuth.getProjectAuthorizationByUserId(data.username, data.projectId)
.then(function (projectAccess) {
if (projectAccess.read) {
return Storage.prototype.getCommonAncestorCommit.call(self, data);
} else {
throw new Error('Not authorized to read project. ' + data.projectId);
}
})
.then(function (commonHash) {
deferred.resolve(commonHash);
})
.catch(function (err) {
deferred.reject(new Error(err));
});
}
return deferred.promise.nodeify(callback);
};
/**
* Authorization: write access for data.projectId
* @param data
* @param callback
* @returns {*}
*/
SafeStorage.prototype.createBranch = function (data, callback) {
var deferred = Q.defer(),
rejected = false,
self = this;
rejected = check(data !== null && typeof data === 'object', deferred, 'data is not an object.') ||
check(typeof data.projectId === 'string', deferred, 'data.projectId is not a string.') ||
check(REGEXP.PROJECT.test(data.projectId), deferred, 'data.projectId failed regexp: ' + data.projectId) ||
check(typeof data.branchName === 'string', deferred, 'data.branchName is not a string.') ||
check(REGEXP.BRANCH.test(data.branchName), deferred, 'data.branchName failed regexp: ' + data.branchName) ||
check(typeof data.hash === 'string', deferred, 'data.hash is not a string.') ||
check(data.hash === '' || REGEXP.HASH.test(data.hash), deferred,
'data.hash is not a valid hash: ' + data.hash);
data.oldHash = '';
data.newHash = data.hash;
if (data.hasOwnProperty('username')) {
rejected = rejected || check(typeof data.username === 'string', deferred, 'data.username is not a string.');
} else {
data.username = this.gmeConfig.authentication.guestAccount;
}
if (rejected === false) {
this.gmeAuth.getProjectAuthorizationByUserId(data.username, data.projectId)
.then(function (projectAccess) {
if (projectAccess.write) {
return Storage.prototype.setBranchHash.call(self, data);
} else {
throw new Error('Not authorized to write project. ' + data.projectId);
}
})
.then(function (result) {
deferred.resolve(result);
})
.catch(function (err) {
deferred.reject(new Error(err));
});
}
return deferred.promise.nodeify(callback);
};
/**
* Authorization: write access for data.projectId
* @param data
* @param callback
* @returns {*}
*/
SafeStorage.prototype.deleteBranch = function (data, callback) {
var deferred = Q.defer(),
rejected = false,
self = this;
rejected = check(data !== null && typeof data === 'object', deferred, 'data is not an object.') ||
check(typeof data.projectId === 'string', deferred, 'data.projectId is not a string.') ||
check(REGEXP.PROJECT.test(data.projectId), deferred, 'data.projectId failed regexp: ' + data.projectId) ||
check(typeof data.branchName === 'string', deferred, 'data.branchName is not a string.') ||
check(REGEXP.BRANCH.test(data.branchName), deferred, 'data.branchName failed regexp: ' + data.branchName);
if (data.hasOwnProperty('username')) {
rejected = rejected || check(typeof data.username === 'string', deferred, 'data.username is not a string.');
} else {
data.username = this.gmeConfig.authentication.guestAccount;
}
if (rejected === false) {
this.gmeAuth.getProjectAuthorizationByUserId(data.username, data.projectId)
.then(function (projectAccess) {
if (projectAccess.write) {
return Storage.prototype.getBranchHash.call(self, data);
} else {
throw new Error('Not authorized to write project. ' + data.projectId);
}
})
.then(function (branchHash) {
data.oldHash = branchHash;
data.newHash = '';
return Storage.prototype.setBranchHash.call(self, data);
})
.then(function (result) {
deferred.resolve(result);
})
.catch(function (err) {
deferred.reject(new Error(err));
});
}
return deferred.promise.nodeify(callback);
};
/**
* Authorization: read access
* @param data
* @param callback
* @returns {*}
*/
SafeStorage.prototype.openProject = function (data, callback) {
var deferred = Q.defer(),
userProject,
self = this;
self._getProject(data)
.then(function (dbProject) {
userProject = new UserProject(dbProject, self, self.logger, self.gmeConfig);
deferred.resolve(userProject);
})
.catch(function (err) {
deferred.reject(new Error(err));
});
return deferred.promise.nodeify(callback);
};
/**
* Authorization: read access
* @param data
* @param callback
* @returns {*}
*/
SafeStorage.prototype._getProject = function (data, callback) {
var deferred = Q.defer(),
rejected = false,
self = this;
rejected = check(data !== null && typeof data === 'object', deferred, 'data is not an object.') ||
check(typeof data.projectId === 'string', deferred, 'data.projectId is not a string.') ||
check(REGEXP.PROJECT.test(data.projectId), deferred, 'data.projectId failed regexp: ' + data.projectId);
if (data.hasOwnProperty('username')) {
rejected = rejected || check(typeof data.username === 'string', deferred, 'data.username is not a string.');
} else {
data.username = this.gmeConfig.authentication.guestAccount;
}
if (rejected === false) {
this.gmeAuth.getProjectAuthorizationByUserId(data.username, data.projectId)
.then(function (projectAccess) {
if (projectAccess.read) {
return Storage.prototype.openProject.call(self, data);
} else {
throw new Error('Not authorized to read or write project: ' + data.projectId);
}
})
.then(function (dbProject) {
deferred.resolve(dbProject);
})
.catch(function (err) {
deferred.reject(new Error(err));
});
}
return deferred.promise.nodeify(callback);
};
/**
* Authorization: TODO: read access for data.projectId
* @param data
* @param callback
* @returns {*}
*/
SafeStorage.prototype.loadObjects = function (data, callback) {
var deferred = Q.defer(),
rejected = false,
self = this;
rejected = check(data !== null && typeof data === 'object', deferred, 'data is not an object.') ||
check(typeof data.projectId === 'string', deferred, 'data.projectId is not a string.') ||
check(REGEXP.PROJECT.test(data.projectId), deferred, 'data.projectId failed regexp: ' + data.projectId) ||
check(data.hashes instanceof Array, deferred, 'data.hashes is not an array: ' + JSON.stringify(data.hashes));
if (data.hasOwnProperty('username')) {
rejected = rejected || check(typeof data.username === 'string', deferred, 'data.username is not a string.');
} else {
data.username = this.gmeConfig.authentication.guestAccount;
}
self.logger.debug('loadObjects', {metadata: data});
if (rejected === false) {
this.gmeAuth.getProjectAuthorizationByUserId(data.username, data.projectId)
.then(function (projectAccess) {
if (projectAccess.read) {
return Storage.prototype.loadObjects.call(self, data);
} else {
throw new Error('Not authorized to read project. ' + data.projectId);
}
})
.then(function (project) {
deferred.resolve(project);
})
.catch(function (err) {
deferred.reject(new Error(err));
});
}
return deferred.promise.nodeify(callback);
};
module.exports = SafeStorage; |
/**
* grunt-nuget
* https://github.com/spatools/grunt-nuget
* Copyright (c) 2013 SPA Tools
* Code below is licensed under MIT License
*
* 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.
*/
var path = require('path');
var async = require('async');
var _ = require('lodash');
var nugetPathDefault = path.join(__dirname, 'nuget.exe');
module.exports = function(grunt) {
var useMono = (process.platform !== 'win32'),
executable = useMono ? 'mono' : nugetPathDefault,
logCommand = function(opts) {
grunt.verbose.writeln('Running NuGet.exe from [' + opts.cmd + '] with args [' + opts.args + ']');
},
// Check if a nugetExe option was supplied and configure tasks to run it rather
// than the default. If found, remove from args list so it isn't parsed into a
// NuGet CLI parameter.
establishNugetExe = function(args) {
if (args && args.nugetExe) {
if (grunt.file.exists(args.nugetExe)) {
executable = args.nugetExe;
} else {
grunt.log.warn('Unable to locate NuGet.exe at ', args.nugetExe);
grunt.log.warn('Falling back to default: ', executable);
}
delete args.nugetExe;
} else {
grunt.log.writeln('nugetExe option not supplied. Using default: ' + executable);
}
return args;
},
createArguments = function(command, path, args) {
var result = [];
if (useMono) {
result.push(nugetPathDefault);
}
result.push(command);
result.push(path);
for (var key in args) {
var argKey = '-' + key[0].toUpperCase() + key.slice(1);
result.push(argKey);
if (args[key] && args[key] !== true)
result.push(args[key]);
}
return result;
},
createSpawnCallback = function(path, args, callback) {
return function(error, result, code) {
if (error) {
var _error = 'Error while trying to execute NuGet Command Line on file ' + path + '\n' + error;
callback(error);
} else {
if ('verbose' in args || 'verbosity' in args) {
grunt.log.writeln(result);
}
grunt.log.ok();
callback();
}
}
},
isSpecFile = function(file) {
return path.extname(file) === '.nuspec' || path.extname(file) === '.csproj';
},
isPackageFile = function(file) {
return path.extname(file) === '.nupkg';
},
isSolutionFile = function(file) {
return path.extname(file) === '.sln';
},
isConfigFile = function(file) {
return path.basename(file) === 'packages.config';
},
pack = function(path, args, callback) {
if (!isSpecFile(path)) {
callback(path + '\' is not a NuGet specification (.nuspec) or project (.csproj) file');
return;
}
if (useMono) {
grunt.log
.warn('NuGet pack for .proj files is not currently supported by mono. More information: http://nuget.codeplex.com/workitem/2140');
}
args = establishNugetExe(args);
var opts = {
cmd: executable,
args: createArguments('Pack', path, args)
};
logCommand(opts);
grunt.log.writeln('Trying to create NuGet package from ' + path);
grunt.util.spawn(opts, createSpawnCallback(path, args, callback));
},
push = function(path, args, callback) {
if (!isPackageFile(path)) {
callback(path + '\' is not a NuGet package file (.nupkg)');
return;
}
args = establishNugetExe(args);
var opts = {
cmd: executable,
args: createArguments('Push', path, args)
};
logCommand(opts);
grunt.log.writeln('Trying to publish NuGet package ' + path);
grunt.util.spawn(opts, createSpawnCallback(path, args, callback));
},
restore = function(path, args, callback) {
if (!isSolutionFile(path) && !isConfigFile(path)) {
callback(path + '\' is not a valid solution file or packages.config');
return;
}
},
update = function(path, args, callback) {
if (!isSolutionFile(path)) {
callback("File path '" + path + "' is not a valid solution file!");
return;
}
args = establishNugetExe(args);
var opts = {
cmd: executable,
args: createArguments('Restore', path, args)
};
logCommand(opts);
grunt.log.writeln('Trying to restore NuGet packages for ' + path);
grunt.util.spawn(opts, createSpawnCallback(path, args, callback));
};
return {
isSpecFile: isSpecFile,
isPackageFile: isPackageFile,
pack: pack,
push: push,
update: update,
restore: restore
};
}; |
import React, { Component, PropTypes } from 'react'
import {
FIELD_BACKGROUND_EMPTY,
FIELD_BACKGROUND_TARGET,
FIELD_BACKGROUND_WALL,
FIELD_STEP_FINISH
} from '../constants/Sokoban'
export default class Field extends Component {
render() {
const { background, step } = this.props
var fieldTemplate = [];
for (let i=0; i<background.length; i++) {
fieldTemplate[i] = background[i].map(function(data, index) {
let isYou = step.you[0] == i && step.you[1] == index;
let isBox = false;
for (let j=0; j<step.boxes.length; j++) {
if (step.boxes[j][0] == i && step.boxes[j][1] == index) {
isBox = true;
}
}
if (data == '') {
let neighbors = [
[i-1, index-1], [i, index-1], [i+1, index-1],
[i-1, index ], [i+1, index-1],
[i-1, index+1], [i, index+1], [i+1, index+1],
]
for (let j=0; j<neighbors.length; j++) {
if (background[neighbors[j][0]]) {
if ([FIELD_BACKGROUND_EMPTY, FIELD_BACKGROUND_TARGET].indexOf(background[neighbors[j][0]][neighbors[j][1]]) > -1) {
data = FIELD_BACKGROUND_WALL
}
}
}
}
return (
<div key={index}
className={
'oneField '
+ (data == FIELD_BACKGROUND_EMPTY ? 'fieldEmpty' : ' ')
+ (data == FIELD_BACKGROUND_TARGET ? 'fieldTarget' : ' ')
+ (data == FIELD_BACKGROUND_WALL ? 'fieldWall' : ' ')
+ (isYou ? 'fieldYou' : '')
+ (isBox ? 'fieldBox' : '')
}
></div>
)
})
}
return <div className='fieldContainer'>
{step.direction == FIELD_STEP_FINISH ? <div className='fieldWinning'>You win!</div> : ''}
{fieldTemplate}
</div>
}
}
Field.propTypes = {
background: PropTypes.array.isRequired,
step: PropTypes.object.isRequired
} |
import DS from 'ember-data';
import DomainResource from 'ember-fhir/models/domain-resource';
const { attr, belongsTo, hasMany } = DS;
export default DomainResource.extend({
identifier: belongsTo('identifier', { async: false }),
status: attr('string'),
category: hasMany('codeable-concept', { async: true }),
patient: belongsTo('reference', { async: false }),
period: belongsTo('period', { async: false }),
dateTime: attr('date'),
consentingParty: hasMany('reference', { async: true }),
actor: hasMany('consent-actor', { async: true }),
action: hasMany('codeable-concept', { async: true }),
organization: hasMany('reference', { async: true }),
sourceAttachment: belongsTo('attachment', { async: false }),
sourceIdentifier: belongsTo('identifier', { async: false }),
sourceReference: belongsTo('reference', { async: false }),
policy: hasMany('consent-policy', { async: true }),
policyRule: attr('string'),
securityLabel: hasMany('coding', { async: true }),
purpose: hasMany('coding', { async: true }),
dataPeriod: belongsTo('period', { async: false }),
data_: hasMany('consent-data', { async: true }),
except: hasMany('consent-except', { async: true })
}); |
const fs = require("fs").promises;
const path = require("path");
const createDefineModules = require("./createDefineModules.js");
const createLibraryFiles = require("./createLibraryFiles.js");
const createWeekData = require("./createWeekData.js");
async function createEmptyDefineFolder(defineFolder) {
try {
const files = await fs.readdir(defineFolder);
// If we get this far, the folder already exists.
// Remove all existing files.
const removePromises = files.map(file => {
const filePath = path.join(defineFolder, file);
fs.unlink(filePath);
});
await Promise.all(removePromises);
} catch (e) {
if (e.code === "ENOENT") {
// Folder doesn't exist; create it.
await fs.mkdir(defineFolder);
} else {
throw e;
}
}
}
async function getSourceFiles(sourceFolder) {
/** @type {string[]} */ const files = await fs.readdir(sourceFolder);
const generatedFiles = ["elix.js", "weekData.js"];
// Source files have a .js extension. Also, ignore generated files.
const jsFiles = files.filter(
file => path.extname(file) === ".js" && !generatedFiles.includes(file)
);
// Sort source files into categories.
const sourceFiles = {
components: [],
helpers: [],
mixins: []
};
jsFiles.forEach(file => {
if (file.toLowerCase()[0] === file[0]) {
// Helpers start with lowercase letter.
sourceFiles.helpers.push(file);
} else if (path.basename(file, ".js").endsWith("Mixin")) {
// Mixin names end with "Mixin".
sourceFiles.mixins.push(file);
} else {
// Component
sourceFiles.components.push(file);
}
});
return sourceFiles;
}
(async () => {
try {
const sourceFolder = path.join(__dirname, "../src");
const defineFolder = path.join(__dirname, "../define");
// Preparation
const sourceFilesPromise = await getSourceFiles(sourceFolder);
await Promise.all([
sourceFilesPromise,
createEmptyDefineFolder(defineFolder)
]);
const sourceFiles = await sourceFilesPromise; // Resolves immediately
await Promise.all([
createDefineModules(defineFolder, sourceFiles.components),
createLibraryFiles(sourceFolder, defineFolder, sourceFiles),
createWeekData()
]);
} catch (e) {
// We have to deal with top-level exceptions.
console.error(e);
}
})();
|
(function(exporter) {
/**
* socket.io guaranteed delivery socket wrapper.
* if the socket gets disconnected at any point, it's up to the application to set a new socket to continue
* handling messages.
* calling 'setSocket' causes all messages that have not received an ack to be sent again.
* @constructor
*/
function SocketGD(socket, lastAcked) {
this._pending = [];
this._events = {};
this._id = 0;
this._enabled = true;
this._onAckCB = SocketGD.prototype._onAck.bind(this);
this._onReconnectCB = SocketGD.prototype._onReconnect.bind(this);
this.setLastAcked(lastAcked);
this.setSocket(socket);
}
/**
* set the id
* @param id
*/
SocketGD.prototype.setId = function (id) {
this._id = id >= 0 ? id : 0;
};
/**
* return the id
*/
SocketGD.prototype.id = function () {
return this._id;
};
/**
* set the last message id that an ack was sent for
* @param lastAcked
*/
SocketGD.prototype.setLastAcked = function(lastAcked) {
this._lastAcked = lastAcked >= 0 ? lastAcked : -1;
};
/**
* get the last acked message id
*/
SocketGD.prototype.lastAcked = function() {
return this._lastAcked;
};
/**
* replace the underlying socket.io socket with a new socket. useful in case of a socket getting
* disconnected and a new socket is used to continue with the communications
* @param socket
*/
SocketGD.prototype.setSocket = function(socket) {
this._cleanup();
this._socket = socket;
if (this._socket) {
this._socket.on('reconnect', this._onReconnectCB);
this._socket.on('socketgd_ack', this._onAckCB);
this.sendPending();
}
};
/**
* send all pending messages that have not received an ack
*/
SocketGD.prototype.sendPending = function() {
var _this = this;
// send all pending messages that haven't been acked yet
this._pending.forEach(function(message) {
_this._sendOnSocket(message);
});
};
/**
* clear out any pending messages
*/
SocketGD.prototype.clearPending = function() {
this._pending = [];
};
/**
* enable or disable sending message with gd. if disabled, then messages will be sent without guaranteeing delivery
* in case of socket disconnection/reconnection.
*/
SocketGD.prototype.enable = function(enabled) {
this._enabled = enabled;
};
/**
* get the underlying socket
*/
SocketGD.prototype.socket = function() {
return this._socket;
};
/**
* cleanup socket stuff
* @private
*/
SocketGD.prototype._cleanup = function() {
if (!this._socket) {
return;
}
this._socket.removeListener('reconnect', this._onReconnectCB);
this._socket.removeListener('socketgd_ack', this._onAckCB);
};
/**
* invoked when an ack arrives
* @param ack
* @private
*/
SocketGD.prototype._onAck = function(ack) {
// got an ack for a message, remove all messages pending an ack up to (and including) the acked message.
while (this._pending.length > 0 && this._pending[0].id <= ack.id) {
if (this._pending[0].id === ack.id && this._pending[0].ack) {
this._pending[0].ack.call(null, ack.data);
}
this._pending.shift();
}
};
/**
* invoked when an a reconnect event occurs on the underlying socket
* @private
*/
SocketGD.prototype._onReconnect = function() {
this.sendPending();
};
/**
* send an ack for a message
* @private
*/
SocketGD.prototype._sendAck = function(id, data) {
if (!this._socket) {
return;
}
this._lastAcked = id;
this._socket.emit('socketgd_ack', {id: id, data: data});
return this._lastAcked;
};
/**
* send a message on the underlying socket.io socket
* @param message
* @private
*/
SocketGD.prototype._sendOnSocket = function(message) {
if (this._enabled && message.id === undefined) {
message.id = this._id++;
message.gd = true;
this._pending.push(message);
}
if (!this._socket) {
return;
}
if (this._enabled) {
switch (message.type) {
case 'send':
this._socket.send('socketgd:' + message.id + ':' + message.msg);
break;
case 'emit':
this._socket.emit(message.event, {socketgd: message.id, msg: message.msg});
break;
}
} else {
switch (message.type) {
case 'send':
this._socket.send(message.msg, message.ack);
break;
case 'emit':
this._socket.emit(message.event, message.msg, message.ack);
break;
}
}
};
/**
* send a message with gd. this means that if an ack is not received and a new connection is established (by
* calling setSocket), the message will be sent again.
* @param message
* @param ack
*/
SocketGD.prototype.send = function(message, ack) {
this._sendOnSocket({type: 'send', msg: message, ack: ack});
};
/**
* emit an event with gd. this means that if an ack is not received and a new connection is established (by
* calling setSocket), the event will be emitted again.
* @param event
* @param message
* @param ack
*/
SocketGD.prototype.emit = function(event, message, ack) {
this._sendOnSocket({type: 'emit', event: event, msg: message, ack: ack});
};
/**
* disconnect the socket
*/
SocketGD.prototype.disconnect = function(close) {
this._socket && this._socket.disconnect(close);
this._cleanup();
this._socket = null;
};
/**
* disconnectSync the socket
*/
SocketGD.prototype.disconnectSync = function() {
this._socket && this._socket.disconnectSync();
this._cleanup();
this._socket = null;
};
/**
* close the socket
*/
SocketGD.prototype.close = function() {
this._socket && this._socket.disconnect(true);
this._cleanup();
this._socket = null;
};
/**
* listen for events on the socket. this replaces calling the 'on' method directly on the socket.io socket.
* here we take care of acking messages.
* @param event
* @param cb
*/
SocketGD.prototype.on = function(event, cb) {
this._events[event] = this._events[event] || [];
var _this = this;
var cbData = {
cb: cb,
wrapped: function(data, ack) {
if (data && event === 'message') {
// parse the message
if (data.indexOf('socketgd:') !== 0) {
cb(data, ack);
return;
}
// get the id (skipping the socketgd prefix)
var index = data.indexOf(':', 9);
if (index === -1) {
cb(data, ack);
return;
}
var id = parseInt(data.substring(9, index));
if (id <= _this._lastAcked) {
// discard the message since it was already handled and acked
return;
}
var message = data.substring(index + 1);
// the callback must call the 'ack' function so we can send an ack for the message
cb && cb(message, function(ackData) {
return _this._sendAck(id, ackData);
}, id);
} else if (data && typeof data === 'object' && data.socketgd !== undefined) {
if (data.socketgd <= _this._lastAcked) {
// discard the message since it was already handled and acked
return;
}
cb && cb(data.msg, function(ackData) {
return _this._sendAck(data.socketgd, ackData);
}, data.socketgd);
} else {
cb(data, ack);
}
}
};
this._events[event].push(cbData);
this._socket.on(event, cbData.wrapped);
};
/**
* remove a previously set callback for the specified event
*/
SocketGD.prototype.off =
SocketGD.prototype.removeListener = function(event, cb) {
if (!this._events[event]) {
return;
}
// find the callback to remove
for (var i = 0; i < this._events[event].length; ++i) {
if (this._events[event][i].cb === cb) {
this._socket && this._socket.removeListener(event, this._events[event][i].wrapped);
this._events[event].splice(i, 1);
}
}
};
exporter.SocketGD = SocketGD;
})(typeof module !== 'undefined' && typeof module.exports === 'object' ? module.exports : window);
|
/**
* View
*
* Manage application scopes and different views
*/
window.ls.container.set('view', function(http, container) {
let stock = {};
let execute = function(view, node, container) {
container.set('element', node, true, false);
container.resolve(view.controller);
if(true !== view.repeat) { // Remove view that should not repeat itself
node.removeAttribute(view.selector);
}
};
let parse = function (node, skip, callback) {
if(node.tagName === 'SCRIPT') {
return;
}
if(node.attributes && skip !== true) {
let attrs = [];
let attrsLen = node.attributes.length;
for (let x = 0; x < attrsLen; x++) {
attrs.push(node.attributes[x].nodeName);
}
if(1 !== node.nodeType) { // Skip text nodes
return;
}
//console.log('in DOM?', document.body.contains(node), node, node.nodeType);
if(attrs && attrsLen) { // Loop threw child attributes
// if(node && node.parentNode && node.parentNode.replaceChild) { // Remove previous refs
// console.info('Clean DOM Node (single)', node);
// let new_element = node.cloneNode(true);
// node.parentNode.replaceChild(new_element, node);
// node = new_element;
// console.info('empty node', node);
// }
for (let x = 0; x < attrsLen; x++) {
if (node.$lsSkip === true) { // Stop render if comp has set $lsSkip
break;
}
let pointer = (!/Edge/.test(navigator.userAgent)) ? x : (attrsLen -1) - x;
let length = attrsLen;
let attr = attrs[pointer];
if(!stock[attr]) {
continue; // No such view component
}
let comp = stock[attr];
if (typeof comp.template === "function") { // If template is function and not string resolve it first
comp.template = container.resolve(comp.template);
}
if(!comp.template) { // Execute with no template
(function (comp, node, container) {
execute(comp, node, container);
})(comp, node, container);
if(length !== attrsLen) {
x--;
}
if(callback) {
callback();
}
continue;
}
node.classList.remove('load-end');
node.classList.add('load-start');
node.$lsSkip = true;
// Load new view template
http.get(comp.template)
.then(function(node, comp) {
return function(data){
node.$lsSkip = false;
node.innerHTML = data;
node.classList.remove('load-start');
node.classList.add('load-end');
(function (comp, node, container) { // Execute after template has been loaded
execute(comp, node, container);
})(comp, node, container);
// re-render specific scope children after template is loaded
parse(node, true);
if(callback) {
callback();
}
}
}(node, comp),
function(error) {
throw new Error('Failed to load comp template: ' + error.message);
}
);
}
}
}
if(true === node.$lsSkip) { // ELEMENT told not to render child nodes
return;
}
let list = (node) ? node.childNodes : [];
if(node.$lsSkip === true) {
list = [];
}
// Run on tree
for (let i = 0; i < list.length; i++) { // Loop threw all DOM children
let child = list[i];
parse(child);
}
};
return {
stock: stock,
/**
* Add View
*
* Adds a new comp definition to application comp stack.
*
* @param object
* @returns {add}
*/
add: function(object) {
if(typeof object !== 'object') {
throw new Error('object must be of type object');
}
let defaults = {
'selector': '',
'controller': function () {},
'template': '',
'repeat': false,
'protected': false
};
for (let prop in defaults) {
if (!defaults.hasOwnProperty(prop)) {
continue;
}
if (prop in object) {
continue;
}
object[prop] = defaults[prop];
}
if(!object.selector) {
throw new Error('View component is missing a selector attribute');
}
stock[object.selector] = object;
return this;
},
/**
* Render
*
* Render all view components in a given scope.
*
* @param element
* @returns view
*/
render: function(element, callback) {
parse(element, false, callback);
element.dispatchEvent(new window.Event('rendered', {bubbles: false}));
}
}
}, true, false); |
/*************************************************************
* @author : Juan Francisco ( juan.maldonado.leon@gmail.com )
* @desc : Controlador de perfiles.
*************************************************************/
app.controller("ProfesionController", function($scope, $http)
{
$scope.profesiones = [];
/*************************************************************
* @author Juan Francisco ( juan.maldonado.leon@gmail.com )
* @desc
*************************************************************/
$scope.initialize = function()
{
NProgress.configure({ parent: '#main' });
NProgress.start();
$scope.obtener( function()
{
NProgress.done();
});
};
/*************************************************************
* @author Juan Francisco ( juan.maldonado.leon@gmail.com )
* @desc
*************************************************************/
$scope.obtener = function( callback )
{
var request = $http.get( CONSTANTS.contextPath + "/api/private/tipo/profesion" );
request.success( function( response )
{
$scope.profesiones = response;
callback();
} );
request.error( function( error )
{
console.log(error);
callback();
});
};
/*************************************************************
* @author Juan Francisco ( juan.maldonado.leon@gmail.com )
* @desc
*************************************************************/
$scope.nuevo = function()
{
var objeto = { codigo: $scope.codigo, nombre : $scope.nombre, descripcion : $scope.descripcion };
var request = $http.put( CONSTANTS.contextPath + "/api/private/tipo/profesion", objeto );
NProgress.configure({ parent: '.modal-body' });
NProgress.start();
request.success( function( response )
{
console.log( response );
NProgress.done();
$('#modal-create').modal('hide');
$scope.initialize();
} );
request.error( function( error )
{
console.log(error);
NProgress.done();
});
};
/*************************************************************
* @author Juan Francisco ( juan.maldonado.leon@gmail.com )
* @desc
*************************************************************/
$scope.selecionActualizar = function( objeto )
{
$scope.objUpdate = angular.copy(objeto);
$('#modal-update').modal('show');
};
/*************************************************************
* @author Juan Francisco ( juan.maldonado.leon@gmail.com )
* @desc
*************************************************************/
$scope.actualizar = function( objeto )
{
console.log( objeto );
var request = $http.post( CONSTANTS.contextPath + "/api/private/tipo/profesion" , $scope.objUpdate );
NProgress.configure({ parent: '.modal-body' });
NProgress.start();
request.success( function( response )
{
console.log( response );
NProgress.done();
$('#modal-update').modal('hide');
$scope.initialize();
} );
request.error( function( error )
{
console.log(error);
NProgress.done();
});
};
/*************************************************************
* @author Juan Francisco ( juan.maldonado.leon@gmail.com )
* @desc
*************************************************************/
$scope.eliminar = function( objeto )
{
var request = $http.delete( CONSTANTS.contextPath + "/api/private/tipo/profesion/"+objeto.oid );
NProgress.configure({ parent: '#main' });
NProgress.start();
request.success( function( response )
{
console.log( response );
NProgress.done();
$scope.initialize();
} );
request.error( function( error )
{
console.log(error);
NProgress.done();
});
};
$scope.clearform= function()
{
$scope.codigo = "";
$scope.nombre = "";
$scope.descripcion = "";
$scope.$apply;
};
$scope.initialize();
}); |
module.exports = {
framework: 'mocha',
test_page: 'tests/index.html?hidepassed',
disable_watching: true,
launch_in_ci: ['Chrome'],
launch_in_dev: ['Chrome'],
browser_args: {
Chrome: {
ci: [
// --no-sandbox is needed when running Chrome inside a container
process.env.CI ? '--no-sandbox' : null,
'--headless',
'--disable-gpu',
'--disable-dev-shm-usage',
'--disable-software-rasterizer',
'--mute-audio',
'--remote-debugging-port=0',
'--window-size=1440,900'
].filter(Boolean)
}
}
};
|
export const SUPPORTED_LOCALES = ['fr', 'en']
export const DEFAULT_LOCALE = 'fr'
export const COOKIE_NAMES = {
auth: 'KT-Auth',
csrfToken: 'KT-CSRF'
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:1591da34b70b2d2113e5f0c1a8acccb9fc0476678881ca91e87314ccdf241e2d
size 10496
|
version https://git-lfs.github.com/spec/v1
oid sha256:66ddd14e9d278283c80c90784d654ba0f3229481a17ddab76725fe94b819409b
size 88387
|
'use strict';
angular.module('users').controller('AuthenticationController', ['$scope', '$http', '$location', 'Authentication',
function($scope, $http, $location, Authentication) {
$scope.authentication = Authentication;
// If user is signed in then redirect back home
if ($scope.authentication.user) $location.path('/home');
$scope.signup = function() {
$http.post('/auth/signup', $scope.credentials).success(function(response) {
// If successful we assign the response to the global user model
$scope.authentication.user = response;
// And redirect to the index page
$location.path('/home');
}).error(function(response) {
$scope.error = response.message;
});
};
$scope.signin = function() {
$http.post('/auth/signin', $scope.credentials).success(function(response) {
// If successful we assign the response to the global user model
$scope.authentication.user = response;
// And redirect to the index page
$location.path('/home');
}).error(function(response) {
$scope.error = response.message;
});
};
}
]); |
// All code points in the `Pahawh_Hmong` script as per Unicode v9.0.0:
[
0x16B00,
0x16B01,
0x16B02,
0x16B03,
0x16B04,
0x16B05,
0x16B06,
0x16B07,
0x16B08,
0x16B09,
0x16B0A,
0x16B0B,
0x16B0C,
0x16B0D,
0x16B0E,
0x16B0F,
0x16B10,
0x16B11,
0x16B12,
0x16B13,
0x16B14,
0x16B15,
0x16B16,
0x16B17,
0x16B18,
0x16B19,
0x16B1A,
0x16B1B,
0x16B1C,
0x16B1D,
0x16B1E,
0x16B1F,
0x16B20,
0x16B21,
0x16B22,
0x16B23,
0x16B24,
0x16B25,
0x16B26,
0x16B27,
0x16B28,
0x16B29,
0x16B2A,
0x16B2B,
0x16B2C,
0x16B2D,
0x16B2E,
0x16B2F,
0x16B30,
0x16B31,
0x16B32,
0x16B33,
0x16B34,
0x16B35,
0x16B36,
0x16B37,
0x16B38,
0x16B39,
0x16B3A,
0x16B3B,
0x16B3C,
0x16B3D,
0x16B3E,
0x16B3F,
0x16B40,
0x16B41,
0x16B42,
0x16B43,
0x16B44,
0x16B45,
0x16B50,
0x16B51,
0x16B52,
0x16B53,
0x16B54,
0x16B55,
0x16B56,
0x16B57,
0x16B58,
0x16B59,
0x16B5B,
0x16B5C,
0x16B5D,
0x16B5E,
0x16B5F,
0x16B60,
0x16B61,
0x16B63,
0x16B64,
0x16B65,
0x16B66,
0x16B67,
0x16B68,
0x16B69,
0x16B6A,
0x16B6B,
0x16B6C,
0x16B6D,
0x16B6E,
0x16B6F,
0x16B70,
0x16B71,
0x16B72,
0x16B73,
0x16B74,
0x16B75,
0x16B76,
0x16B77,
0x16B7D,
0x16B7E,
0x16B7F,
0x16B80,
0x16B81,
0x16B82,
0x16B83,
0x16B84,
0x16B85,
0x16B86,
0x16B87,
0x16B88,
0x16B89,
0x16B8A,
0x16B8B,
0x16B8C,
0x16B8D,
0x16B8E,
0x16B8F
]; |
'use strict';
var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('')
, length = 64
, map = {}
, seed = 0
, i = 0
, prev;
/**
* Return a string representing the specified number.
*
* @param {Number} num The number to convert.
* @returns {String} The string representation of the number.
* @api public
*/
function encode(num) {
var encoded = '';
do {
encoded = alphabet[num % length] + encoded;
num = Math.floor(num / length);
} while (num > 0);
return encoded;
}
/**
* Return the integer value specified by the given string.
*
* @param {String} str The string to convert.
* @returns {Number} The integer value represented by the string.
* @api public
*/
function decode(str) {
var decoded = 0;
for (i = 0; i < str.length; i++) {
decoded = decoded * length + map[str.charAt(i)];
}
return decoded;
}
/**
* Yeast: A tiny growing id generator.
*
* @returns {String} A unique id.
* @api public
*/
function yeast() {
var now = encode(+new Date());
if (now !== prev) return seed = 0, prev = now;
return now + '.' + encode(seed++);
}
//
// Map each character to its index.
//
for (; i < length; i++) map[alphabet[i]] = i;
//
// Expose the `yeast`, `encode` and `decode` functions.
//
yeast.encode = encode;
yeast.decode = decode;
module.exports = yeast;
|
/*
* page.js: A single page (or set of pages) composed to content, metadata, and partials
*
* (C) 2011, Nodejitsu Inc.
*
*/
var events = require('events'),
fs = require('fs'),
path = require('path'),
plates = require('plates'),
Handlebars = require('handlebars'),
utile = require('flatiron').common,
async = utile.async,
inflect = utile.inflect,
content = require('./content'),
partial = require('./partial');
//
// ### function Page (options)
// #### @options {Object} Options for this Page.
//
// Constructor function for the Page object representing
// a single page (or set of pages).
//
var Page = module.exports = function Page(options) {
events.EventEmitter.call(this);
//
// Set all options for this instance
//
// TODO: Require all of this!
//
this.name = options.name;
this.plural = inflect.pluralize(this.name);
this.dir = options.dir;
this.layout = options.layout || 'default';
this.options = options.options;
//
// Represents all HTML and partially rendered content
// associate with the site.
//
this.html = options.html;
this.content = options.content;
this.references = options.references;
this.partials = options.partials || {};
};
//
// Inherit from `events.EventEmitter`.
//
utile.inherits(Page, events.EventEmitter);
//
// ### function renderAll ()
//
// Returns all fully rendered pages associated with this instance.
//
Page.prototype.renderAll = function (source, key) {
var rendered = {},
self = this;
source = source || this.content;
key = key || this.plural;
//
// Helper function to determine if we should continue to traverse
// this content tree
//
function hasChildren() {
return typeof source[key] === 'object' && Object.keys(source[key]).filter(function (childKey) {
return childKey[0] !== '_';
}).length;
}
if (typeof this.options === 'object' && this.options.type === 'compile') {
rendered[key] = {
_content: this.render(source[key] || source[this.name] || source || this.content)
}
}
else {
if (source[key] && source[key]._content) {
//
// If there is content on this node then render it.
//
rendered._content = this.render(source[key]);
}
if (typeof source[key] === 'object' && hasChildren()) {
//
// If the `content` has a pluralized key to the page `name`,
// render all pages in `content[plural]` e.g.:
//
// name = 'post'
// content = { posts: { ... } }
//
rendered[key] = Object.keys(source[key]).reduce(function (rendered, nextKey) {
if (nextKey[0] === '_') {
return rendered;
}
rendered[nextKey] = self.renderAll(source[key], nextKey);
return rendered;
}, {});
}
else if (!source[key] || !source[key]._content) {
//
// Conversely if no such convention exists just render a single page. e.g.
//
// name = 'index'
// content = { posts: { ... } }
//
rendered[key] = {
_content: this.render(source[key] || source[this.name] || source || this.content)
};
}
}
return !hasChildren() && arguments.length ? rendered : rendered[key];
};
//
// ### function render (key, source)
// #### @key {string} **Optional** Key of `source` within `this.content`.
// #### @source {Object} Content to render into this page.
//
// Returns a fully rendered page for the `source` content including layout,
// partials, content and metadata.
//
Page.prototype.render = function (source) {
//
// Create a map for HTML ids to use when rendering
// this page.
//
var rendered = { content: this.renderContent(source) },
map = plates.Map(),
self = this,
fullpage;
//
// Render all partials associated with this page.
//
if (this.options.partials) {
Object.keys(this.options.partials).forEach(function (id) {
//
// Always default to the partials being an Array.
//
self.options.partials[id] = !Array.isArray(self.options.partials[id])
? [self.options.partials[id]]
: self.options.partials[id];
rendered[id] = self.options.partials[id].reduce(function (fullHtml, name) {
if (typeof name !== 'string') {
return fullHtml + self.renderContent(self.content, name);
}
return fullHtml + partial.render({
metadata: source._content.metadata,
html: self.html.partials[name],
remove: self.partials[name] && self.partials[name].remove,
references: self.references
}) + '\n';
}, '\n');
});
}
fullpage = Handlebars.compile(this.html.layouts[this.layout] || this.html.layouts['default'])(rendered);
return {
html: fullpage,
date: source._content && new Date(source._content.metadata['page-details'].date),
dir: source._content && path.dirname(source._content.metadata['page-details'].source),
files: source._files
};
};
//
// ### function renderContent (source, contentOptions)
// #### @source {Object} Rendered markdown and metadata to render on the page
// #### @contentOptions {Object} Options to render this content
//
// Attempts to render the content section of a single page composed of:
//
// 1. A single content file
// 2. The composition of multiple content files.
//
Page.prototype.renderContent = function (source, contentOptions) {
if (!contentOptions) {
contentOptions = this.options.content;
}
var self = this,
partialName,
plural;
if (!contentOptions || typeof contentOptions === 'string') {
//
// If no "content" option (or if it is a string) is set default to using a
// partial with the same name as this page. If it is a string assume it
// is the name of a partial. If not found then just use the rendered
// markdown HTML.
//
partialName = contentOptions || this.options.partial || this.name;
if (this.html.partials[partialName]) {
return partial.render({
content: source._content.html,
metadata: source._content.metadata,
html: this.html.partials[partialName],
remove: this.partials[partialName] && self.partials[partialName].remove,
references: this.references
});
}
else {
return source._content.html;
}
}
else if (contentOptions.tree && contentOptions.partial) {
//
// Otherwise render list options such as:
//
// "content": {
// "tree": "posts"
// }
//
plural = inflect.pluralize(contentOptions.tree);
return source[plural]
? this.renderTree(source[plural], contentOptions)
: '';
}
else if (contentOptions.list) {
//
// Otherwise render list options such as:
//
// "content": {
// "list": "posts",
// "truncate": true,
// "limit": 20
// }
//
// If no "list" property is defined then throw an error.
// Remark: What are other kinds of content rendering are their?
//
//
// Always attempt to render multiple lists of content
//
contentOptions.list = !Array.isArray(contentOptions.list)
? [contentOptions.list]
: contentOptions.list;
return contentOptions.list.reduce(function (rendered, type) {
return rendered + self.renderList(source, utile.mixin(
utile.clone(contentOptions),
{ name: type }
)) + '\n';
}, '\n');
}
else if (contentOptions.compile) {
//
// If this is a compilation of pages then compile them
// from the `source`.
//
partialName = contentOptions.partial || this.name;
if (this.html.partials[partialName]) {
return partial.render({
content: source._content && source._content.content,
metadata: Object.keys(source).reduce(function (compiled, key) {
compiled[key] = (source[key] && source[key]._content
&& source[key]._content.html) || '';
return compiled;
}, (source._content && source._content.metadata) || {}),
html: this.html.partials[partialName],
remove: this.partials[partialName] && self.partials[partialName].remove,
references: this.references
});
}
else {
return source._content.html;
}
}
};
//
// ### function renderList (source, contentOptions)
// #### @source {Object} Rendered markdown and metadata to render the list
// #### @options {Object} Options to render this list.
//
// Attempts to render a list of content pages by concatenating rendered
// partials.
//
Page.prototype.renderList = function (source, options) {
var plural = inflect.pluralize(options.name),
self = this,
keys;
if (typeof source[plural] !== 'object') {
//
// Remark: Should this just fail silently?
//
throw new Error('Cannot render list for ' + options.name + ': No content found');
}
//
// TODO: Make sorting configurable by key and direction. For now default
// to a descending sorting by date.
//
keys = Object.keys(source[plural]).sort(function (lkey, rkey) {
var ldate = source[plural][lkey]._date,
rdate = source[plural][rkey]._date;
if (ldate > rdate) return -1;
if (ldate < rdate) return 1;
return 0;
});
if (options.limit) {
keys = keys.slice(0, options.limit);
}
return keys.reduce(function renderOn(rendered, key) {
var itemSource = source[plural][key],
itemDestination;
if (itemSource.index) {
itemSource = itemSource.index;
}
if (itemSource.content) itemSource._content = itemSource.content
if (options.truncate) {
//
// If we should truncate posts then do so by passing
// the HTML rendered from the truncated markdown.
//
itemDestination = {
_files: itemSource._files,
_content: {
metadata: itemSource._content.metadata,
html: itemSource._content.truncated && itemSource._content.truncated.html
? itemSource._content.truncated.html
: itemSource._content.html
}
};
}
return rendered + self.renderContent(itemDestination, options.partial || options.name) + '\n';
}, '\n');
};
//
// ### function renderTree (source, contentOptions)
// #### @source {Object} Rendered markdown and metadata to render the tree
// #### @options {Object} Options to render this list.
//
// Attempts to render a tree of content pages by concatenating rendered
// partials.
//
Page.prototype.renderTree = function (source, options) {
var self = this,
tree;
tree = Object.keys(source).reduce(function (fullTree, key) {
fullTree[key] = Object.keys(source[key])
.filter(function (childKey) {
return ['_date'].indexOf(childKey) === -1;
})
.map(function (childKey) {
if (childKey === '_content') {
return source[key]._content.metadata;
}
else if (!source[key][childKey] || (!source[key][childKey]._content
&& !source[key][childKey].index)) {
return;
}
else if (source[key][childKey]._content) {
return source[key][childKey]._content.metadata;
}
else if (source[key][childKey].index) {
return source[key][childKey].index._content &&
source[key][childKey].index._content.metadata;
}
})
.filter(Boolean);
return fullTree;
}, {});
//
// Helper function which sorts sub-keys based on
// metadata `source` values.
//
function sortMetadata(lval, rval) {
var ldetails = lval['page-details'],
rdetails = rval['page-details'];
if (/^index/.test(path.basename(ldetails.source))) {
return -1;
}
if (/^index/.test(path.basename(rdetails.source))) {
return 1;
}
if (ldetails.title > rdetails.title) return 1;
if (ldetails.title < rdetails.title) return -1;
return 0;
}
return Object.keys(tree).sort(function (lval, rval) {
var lindex, rindex;
if (options.sort) {
lindex = options.sort.indexOf(lval);
rindex = options.sort.indexOf(rval);
if (lindex > rindex) return 1;
if (lindex < rindex) return -1;
}
if (lval > rval) return 1;
if (lval < rval) return -1;
return 0;
}).reduce(function (rendered, key) {
return rendered + partial.render({
metadata: {
tree: tree[key].sort(sortMetadata)
},
html: self.html.partials[options.partial],
remove: self.partials[options.partial] && self.partials[options.partial].remove,
references: self.references
});
}, '');
};
|
/*
(c) Copyright 2016-2017 Hewlett Packard Enterprise Development LP
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.
*/
import Listener from './base-listener';
import MetricToPng from '../charting/chart';
const Conversation = require('hubot-conversation');
export default class ServerHardwareListener extends Listener {
constructor(robot, client, transform) {
super(robot, client, transform);
this.switchBoard = new Conversation(robot);
this.room = client.notificationsRoom;
this.title = "Server hardware (sh)";
this.capabilities = [];
this.respond(/(?:turn|power) on (?:\/rest\/server-hardware\/)(:<serverId>[a-zA-Z0-9_-]*?)\.$/i, ::this.PowerOn);
this.respond(/(?:turn|power) off (?:\/rest\/server-hardware\/)(:<serverId>[a-zA-Z0-9_-]*?)\.$/i, ::this.PowerOff);
this.capabilities.push(this.indent + "Power on/off a specific (server) hardware (e.g. turn on Encl1, bay 1).");
this.respond(/(?:get|list|show) all (?:server ){0,1}hardware\.$/i, ::this.ListServerHardware);
this.capabilities.push(this.indent + "List all (server) hardware (e.g. list all hardware).");
this.respond(/(?:get|list|show) (?:\/rest\/server-hardware\/)(:<serverId>[a-zA-Z0-9_-]*?) utilization\.$/i, ::this.ListServerHardwareUtilization);
this.capabilities.push(this.indent + "List server hardware utilization (e.g. list Encl1, bay 1 utilization).");
this.respond(/(?:get|list|show) (?!\/rest\/server-profiles\/)(?:\/rest\/server-hardware\/)(:<serverId>[a-zA-Z0-9_-]*?)\.$/i, ::this.ListServerHardwareById);
this.capabilities.push(this.indent + "List server hardware by name (e.g. list Encl1, bay 1).");
}
PowerOnHardware(id, msg, suppress) {
if(this.client.connection.isReadOnly()) {
return this.transform.text(msg, "Not so fast... You'll have to set readOnly mode to false in your config file first if you want to do that...");
}
let startMessage = false;
return this.client.ServerHardware.setPowerState(id, "On").feedback((res) => {
if (!suppress && !startMessage && res.associatedResource.resourceHyperlink) {
startMessage = true;
this.transform.text(msg, "I am powering on " + this.transform.hyperlink(res.associatedResource.resourceHyperlink, res.associatedResource.resourceName) + ", this may take some time.");
}
}).then((res) => {
if (!suppress) {
this.transform.send(msg, res, "Finished powering on " + res.name);
}
});
}
PowerOffHardware(id, msg, suppress) {
if(this.client.connection.isReadOnly()) {
return this.transform.text(msg, "Not so fast... You'll have to set readOnly mode to false in your config file first if you want to do that...");
}
let startMessage = false;
return this.client.ServerHardware.setPowerState(id, "Off", "MomentaryPress").feedback((res) => {
if (!suppress && !startMessage && res.associatedResource.resourceHyperlink) {
startMessage = true;
this.transform.text(msg, "Hey " + msg.message.user.name + " I am powering off " + this.transform.hyperlink(res.associatedResource.resourceHyperlink, res.associatedResource.resourceName) + ", this may take some time.");
}
}).then((res) => {
if (!suppress) {
this.transform.send(msg, res, "Finished powering off " + res.name);
}
});
}
PowerOn(msg) {
if(this.client.connection.isReadOnly()) {
return this.transform.text(msg, "Not so fast... You'll have to set readOnly mode to false in your config file first if you want to do that...");
}
let dialog = this.switchBoard.startDialog(msg);
this.transform.text(msg, "Ok " + msg.message.user.name + " I am going to power on the blade. Are you sure you want to do this? (yes/no)");
dialog.addChoice(/yes/i, () => {
this.PowerOnHardware(msg.serverId, msg).catch((err) => {
return this.transform.error(msg, err);
});
});
dialog.addChoice(/no/i, () => {
return this.transform.text(msg, "Ok " + msg.message.user.name + " I won't do that.");
});
}
PowerOff(msg) {
if(this.client.connection.isReadOnly()) {
return this.transform.text(msg, "I don't think I should be doing that if you are in readOnly mode... You'll have to set readOnly mode to false in your config file first if you want to do that...");
}
let dialog = this.switchBoard.startDialog(msg);
this.transform.text(msg, "Ok " + msg.message.user.name + " I am going to power off the blade. Are you sure you want to do this? (yes/no)");
dialog.addChoice(/yes/i, () => {
this.PowerOffHardware(msg.serverId, msg).catch((err) => {
return this.transform.error(msg, err);
});
});
dialog.addChoice(/no/i, () => {
return this.transform.text(msg, "Ok " + msg.message.user.name + " I won't do that.");
});
}
ListServerHardware(msg) {
this.client.ServerHardware.getAllServerHardware().then((res) => {
return this.transform.send(msg, res);
}).catch((err) => {
return this.transform.error(msg, err);
});
}
ListServerHardwareById(msg) {
this.client.ServerHardware.getServerHardware(msg.serverId).then((res) => {
return this.transform.send(msg, res);
}).catch((err) => {
return this.transform.error(msg, err);
});
}
ListServerHardwareUtilization(msg) {
let p = new Promise ((resolve) => {
this.client.ServerHardware.getServerUtilization(msg.serverId, {fields: 'AveragePower,PeakPower,PowerCap'}).then((res) => {
return MetricToPng(this.robot, 'Power', res.metricList, this.room);
}).then(() => {
this.robot.logger.debug('Finished creating Power chart.');
this.client.ServerHardware.getServerUtilization(msg.serverId, {fields: 'AmbientTemperature'}).then((res) => {
return MetricToPng(this.robot, 'Temperature', res.metricList, this.room);
}).then(() => {
this.robot.logger.debug('Finished creating Temperature chart.');
this.client.ServerHardware.getServerUtilization(msg.serverId, {fields: 'CpuUtilization,CpuAverageFreq'}).then((res) => {
return MetricToPng(this.robot, 'CPU', res.metricList, this.room);
}).then(() => {
this.robot.logger.debug('Finished creating CPU chart.');
resolve();
}).catch((err) => {
return this.transform.error(msg, err);
});
}).catch((err) => {
return this.transform.error(msg, err);
});
}).catch((err) => {
return this.transform.error(msg, err);
});
}); //end new promise
p.then(() => {
this.robot.logger.info('All charts finsihed.');
return this.transform.send(msg, "Ok " + msg.message.user.name + " I've finished creating all of the hardware utilization charts.");
});
}
}
|
console.log('This is a CLI!');
|
GITCE.overview = function (parameters) {
var options = $.extend({
refreshTime:5000
}, parameters);
var tplServer = $('<li class="server"><h2/><ul class="configs clearfix"></ul>');
var tplConfig = $('<li class="config"><h3 class="name"/>' +
'<ul class="branches branches-next"/>' +
'<ul class="branches branches-broken"/>' +
'<span style="display: none;">nothing pending / broken</span>' +
'</li>');
var tplBranch = $('<li class="branch"><a/>');
function branchHasStatus(states, status, branch) {
for (var index in states[status]) {
var branches = states[status];
for (var key in branches) {
if (branches[key].branch == branch) {
return true;
}
}
}
return false;
}
function branchHasAuthor(states, branch) {
for (var index in branch.authors) {
if (states.user == branch.authors[index].email) {
return true;
}
}
return false;
}
function isValidServer(server) {
if (server.title == "" || server.url == "") {
return false;
}
for(var index in that.serverList) {
if (that.serverList.hasOwnProperty(index)) {
if (server.url == that.serverList[index].url || server.title == that.serverList[index].title) {
return false;
}
}
}
return true;
}
var that = {
servers:null,
serverList:[
{title:'localhost', url:'/', deletable:false}
],
configIntervals:{},
update:function () {
that.servers.empty();
for (var index in that.serverList) {
that.initServer(that.serverList[index]);
}
},
updateConfig:function (config, configContainer, server) {
$.ajax({
url:server.url + "cgi-bin/status.cgi?" + config.config,
success:function (status) {
var index, branch, branchContainer;
var nothingToDo = configContainer.find('span').show();
// Pending Branches
var branchesPending = $('.branches-next', configContainer).empty();
for (index in status['next']) {
branch = status['next'][index];
branchContainer = tplBranch.clone().appendTo(branchesPending);
if (branchHasStatus(status, "running", branch.branch)) {
branchContainer.find('a').text(branch.branch);
branchContainer.find('a').attr('href', '/log.html?server=' + server.url + '&config=' + config.config + '/' + branch.branch + '/' + branch.number);
} else {
branchContainer.find('a').text(branch['branchContainer']);
branchContainer.find('a').remove();
}
}
if (branchesPending.children().size()) {
branchesPending.show();
nothingToDo.hide();
} else {
branchesPending.hide();
}
// Broken Branches
var branchesBroken = $('.branches-broken,', configContainer).empty();
var broken = false;
var responsible = false;
for (index in status['broken']) {
branch = status['broken'][index];
broken = true;
responsible = responsible || branchHasAuthor(status, branch);
branchContainer = tplBranch.clone().appendTo(branchesBroken);
branchContainer.find('a').text(branch.branch);
branchContainer.find('a').attr('href', '/log.html?server=' + server.url + '&config=' + config.config + '&branch=' + branch.branch + '&build=' + branch.number);
}
if (branchesBroken.children().size()) {
branchesBroken.show();
nothingToDo.hide();
} else {
branchesBroken.hide();
}
if (broken) {
configContainer.addClass('broken');
if (responsible) {
configContainer.addClass('you-broke-it');
}
}
}
});
},
initServer:function (server) {
var serverContainer = tplServer.clone().appendTo(that.servers);
if (server.deletable) {
serverContainer.find('h2').html(server.title + '<a href="#" class="delete-server">x</a>');
} else {
serverContainer.find('h2').html(server.title);
}
$.ajax({
url:server.url + 'cgi-bin/list.cgi',
success:function (configs) {
for (var index in configs) {
that.initConfig(configs[index], serverContainer, server);
}
}
});
},
addServer:function (server) {
if (!isValidServer(server)) return false;
that.serverList.push(server);
GITCE.cookieObject('serverList', that.serverList);
that.initServer(server);
return true;
},
deleteServer:function (serverContainer) {
var index, headline, serverName;
// find out the server-name
headline = serverContainer.find('h2');
headline.find('a').remove();
serverName = headline.html();
for(index in that.serverList) {
if (that.serverList[index].title == serverName && that.serverList[index].deletable) {
// remove from serverlist
that.serverList.splice(index, 1);
// clear all update-intervals
for(var key in that.configIntervals[serverName]) {
window.clearInterval(that.configIntervals[serverName][key]);
}
that.configIntervals[serverName] = new Array();
// remove from gui
serverContainer.remove();
break;
}
}
GITCE.cookieObject('serverList', that.serverList);
},
initConfig:function (config, serverContainer, server) {
var configContainer = tplConfig.clone().appendTo(serverContainer.find('.configs'));
configContainer.find('h3').html($('<a href="/detail.html?server=' + server.url + '&config='+config.config+'">'+config.config+'</a>'));
// initial and interval-driven update-process
that.updateConfig.call(that, config, configContainer, server);
var configInterval = window.setInterval(function () {
that.updateConfig.call(that, config, configContainer, server);
}, options.refreshTime);
// save config-Interval for clearing
if (that.configIntervals[server] === undefined) {
that.configIntervals[server] = new Array();
}
that.configIntervals[server].push(configInterval);
},
fetchVersion: function(serverUrl, callback){
$.ajax({
url: serverUrl + 'cgi-bin/version.cgi',
success: function(version) {
if (typeof(callback) == 'function') {
callback.call(that, version);
}
}
});
},
init:function () {
// restore configuration
var serverList = GITCE.cookieObject('serverList');
if (serverList !== null && serverList.length) {
that.serverList = serverList;
}
// initalize servers
that.servers = $('.servers');
for (var index in that.serverList) {
that.initServer(that.serverList[index]);
}
// bind add-server-event
$('#add-server').live('submit', function (e) {
e.preventDefault();
var server = {
title:$(this).find('#server-title').val(),
url:$(this).find('#server-location').val(),
deletable:true
};
that.addServer(server);
return false;
});
// bind delete-server-event
$('.delete-server').live('click', function (e) {
e.preventDefault();
that.deleteServer($(this).parents('.server'));
});
// display version
that.fetchVersion('/', function(version) {
console.log(version);
$('.version').text(version);
});
}
};
return that;
}; |
Package.describe({
summary: "Twitter API for Meteor"
});
Package.on_use(function (api, where) {
api.use('accounts-twitter', 'server');
api.use('oauth1', 'server');
api.use('http', 'server');
api.export && api.export('TwitterSpark', 'server');
api.add_files(['twitter-api.js'], 'server');
});
Package.on_test(function (api) {
});
|
import {
ruleTester,
warningFreeBasics,
} from "../../../testUtils"
import rule, { ruleName, messages } from ".."
const testRule = ruleTester(rule, ruleName)
testRule("always", tr => {
warningFreeBasics(tr)
tr.ok("/* comment */")
tr.ok("/* comment comment */")
tr.ok("/* comment\ncomment */")
tr.ok("/* comment\n\ncomment */")
tr.notOk("/*comment */", {
message: messages.expectedOpening,
line: 1,
column: 3,
})
tr.notOk("/* comment*/", {
message: messages.expectedClosing,
line: 1,
column: 10,
})
tr.notOk("/* comment */", {
message: messages.expectedOpening,
line: 1,
column: 3,
})
tr.notOk("/* comment */", {
message: messages.expectedClosing,
line: 1,
column: 12,
})
tr.notOk("/*comment comment */", {
message: messages.expectedOpening,
line: 1,
column: 3,
})
tr.notOk("/* comment comment*/", {
message: messages.expectedClosing,
line: 1,
column: 18,
})
tr.notOk("/*comment\n\ncomment */", {
message: messages.expectedOpening,
line: 1,
column: 3,
})
tr.notOk("/* comment\n\ncomment*/", {
message: messages.expectedClosing,
line: 3,
column: 7,
})
})
testRule("never", tr => {
warningFreeBasics(tr)
tr.ok("/*comment*/")
tr.ok("/*comment comment*/")
tr.ok("/*comment\ncomment*/")
tr.ok("/*comment\n\ncomment*/")
tr.notOk("/* comment*/", {
message: messages.rejectedOpening,
line: 1,
column: 3,
})
tr.notOk("/*comment */", {
message: messages.rejectedClosing,
line: 1,
column: 10,
})
tr.notOk("/* comment*/", {
message: messages.rejectedOpening,
line: 1,
column: 3,
})
tr.notOk("/*comment */", {
message: messages.rejectedClosing,
line: 1,
column: 11,
})
tr.notOk("/* comment comment*/", {
message: messages.rejectedOpening,
line: 1,
column: 3,
})
tr.notOk("/*comment comment */", {
message: messages.rejectedClosing,
line: 1,
column: 18,
})
tr.notOk("/* comment\n\ncomment*/", {
message: messages.rejectedOpening,
line: 1,
column: 3,
})
tr.notOk("/*comment\n\ncomment */", {
message: messages.rejectedClosing,
line: 3,
column: 8,
})
})
|
var fs = require('fs')
, p = require('path')
;
// how to know when you are done?
function recursiveReaddirSync(path) {
var list = []
, files = fs.readdirSync(path)
, stats
;
files.forEach(function (file) {
stats = fs.lstatSync(p.join(path, file));
if(stats.isDirectory()) {
list = list.concat(recursiveReaddirSync(p.join(path, file)));
} else {
list.push(p.join(path, file));
}
});
return list;
}
module.exports = recursiveReaddirSync;
|
'use strict';
// Komics controller
angular.module('komics').controller('KomicsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Komics', 'Reviews',
function($scope, $stateParams, $location, Authentication, Komics, Reviews ) {
$scope.authentication = Authentication;
$scope.review_state = false;
// Create new Komic
$scope.create = function() {
// Create new Komic object
var komic = new Komics ({
title: this.title,
description: this.description,
genres: this.genres
});
// Redirect after save
komic.$save(function(response) {
$location.path('komics/' + response._id);
// Clear form fields
$scope.title = '';
$scope.description = '';
$scope.genre = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Add Review to Komic
$scope.addReview = function() {
var review = new Reviews ({
komicId: $scope.komic._id,
review: this.review
});
console.log(review);
$scope.komic.reviews.push({review: this.review, user: Authentication.user.displayName, created: Date.now()});
review.$save(function(response) {
$scope.komic = response;
console.log(response);
},function(errorResponse) {
$scope.error =errorResponse.data.message;
});
$scope.review_state = false;
$scope.review = '';
};
// Remove Review from Komic
$scope.removeReview = function(rev) {
var review = new Reviews({
komicId: $scope.komic._id,
_id: rev._id
});
review.$remove(function(response) {
for (var i in $scope.komic.reviews) {
if ($scope.komic.reviews[i] === rev) {
$scope.komic.reviews.splice(i, 1);
}
}
},function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Remove existing Komic
$scope.remove = function( komic ) {
if ( komic ) { komic.$remove();
for (var i in $scope.komics ) {
if ($scope.komics [i] === komic ) {
$scope.komics.splice(i, 1);
}
}
} else {
$scope.komic.$remove(function() {
$location.path('komics');
});
}
};
// Update existing Komic
$scope.update = function() {
var komic = $scope.komic ;
komic.$update(function() {
$location.path('komics/' + komic._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Komics
$scope.find = function() {
$scope.komics = Komics.query();
};
// Find existing Komic
$scope.findOne = function() {
$scope.komic = Komics.get({
komicId: $stateParams.komicId
});
};
$scope.show_review = function() {
$scope.review_state = $scope.review_state === false ? true: false;
};
// $scope.show_review_list = function() {
// for (var i in $scope.komic.reviews)
// };
}
]); |
/*
* shape.js
*/
(function() {
// var tm = require("../../../libs/tmlib");
// var THREE = require("../../../libs/three");
// require("./mesh");
tm.define("tm.hybrid.PlaneMesh", {
superClass: "tm.hybrid.Mesh",
init: function(geometryParam, materialParam) {
geometryParam = {}.$extend(tm.hybrid.PlaneMesh.DEFAULT_GEOMETRY_PARAM, geometryParam);
materialParam = {}.$extend(tm.hybrid.PlaneMesh.DEFAULT_MATERIAL_PARAM, materialParam);
var geo = new THREE.PlaneGeometry(geometryParam.width, geometryParam.height, geometryParam.widthSegments, geometryParam.heightSegments);
var mat = new THREE.MeshPhongMaterial(materialParam);
this.superInit(new THREE.Mesh(geo, mat));
},
});
tm.hybrid.PlaneMesh.DEFAULT_GEOMETRY_PARAM = {
width: 1,
height: 1,
widthSegments: 1,
heightSegments: 1,
};
tm.hybrid.PlaneMesh.DEFAULT_MATERIAL_PARAM = {
color: 0xffffff,
};
tm.define("tm.hybrid.BoxMesh", {
superClass: "tm.hybrid.Mesh",
init: function(geometryParam, materialParam) {
geometryParam = {}.$extend(tm.hybrid.BoxMesh.DEFAULT_GEOMETRY_PARAM, geometryParam);
materialParam = {}.$extend(tm.hybrid.BoxMesh.DEFAULT_MATERIAL_PARAM, materialParam);
var geo = new THREE.BoxGeometry(geometryParam.width, geometryParam.height, geometryParam.depth, geometryParam.widthSegments, geometryParam.heightSegments, geometryParam.depthSegments);
var mat = new THREE.MeshPhongMaterial(materialParam);
this.superInit(new THREE.Mesh(geo, mat));
},
});
tm.hybrid.BoxMesh.DEFAULT_GEOMETRY_PARAM = {
width: 1,
height: 1,
depth: 1,
widthSegments: 1,
heightSegments: 1,
depthSegments: 1,
};
tm.hybrid.BoxMesh.DEFAULT_MATERIAL_PARAM = {
color: 0xffffff,
};
})();
|
'use strict';
let chai = require('chai');
let dirtyChai = require('dirty-chai');
chai.use(dirtyChai);
global.chai = chai;
global.expect = chai.expect;
global.assert = chai.assert;
global.should = chai.should();
process.on('uncaughtException', function(err) {
console.error('Uncaught Exception', err, err.stack);
throw err;
});
|
//
// 2020-12-25, jjuiddong
// packet class
// - binary data serialize
//
// 2021-08-24
// - refactoring
// - add array get, push
//
import TypeVariant from "./variant"
const VT_EMPTY = 0;
const VT_I2 = 2;
const VT_I4 = 3;
const VT_R4 = 4;
const VT_R8 = 5;
const VT_BSTR = 8;
const VT_BOOL = 11;
const VT_I1 = 16;
const VT_UI1 = 17;
const VT_UI2 = 18;
const VT_UI4 = 19;
const VT_I8 = 20;
const VT_UI8 = 21;
const VT_INT = 22;
const VT_UINT = 23;
const VT_ARRAY = 0x2000;
const VT_BYREF = 0x4000; // for array type
export default class Packet {
// size: buffer size (byte unit)
constructor(size = 0) {
this.buff = size == 0 ? null : new ArrayBuffer(size)
this.dv = (this.buff)? new DataView(this.buff) : null
this.offset = 0 // read/write offset
this.byteLength = size
}
//--------------------------------------------------------------------------------
// initialize read/write
init() {
this.offset = 0
}
//--------------------------------------------------------------------------------
// initialize with ArrayBuffer
// message: websocket receive message buffer
// offset: buffer offset (packet header size)
initWithArrayBuffer(message, offset = 0) {
this.dv = new DataView(message)
this.buff = message
this.offset = offset
this.byteLength = message.byteLength
}
//--------------------------------------------------------------------------------
// 4byte alignment
calc4ByteAlignment() {
if (this.offset % 4 != 0)
this.offset = this.offset + (4 - (this.offset % 4))
}
//--------------------------------------------------------------------------------
// boolean to arraybuffer
pushBool(val) {
if (!this.dv) return
if (this.offset + 1 > this.byteLength) return
this.dv.setUint8(this.offset, val ? 1 : 0)
this.offset += 1
}
//--------------------------------------------------------------------------------
// string to arraybuffer
pushStr(str) {
// let view = new Uint8Array(this.buff, this.offset)
// let ec = new TextEncoder().encode(str)
// for (let i = 0; i < ec.length; ++i) {
// view[i] = ec[i]
// }
// view[ec.length] = 0
// this.offset += ec.length + 1 // add null data
if (!this.dv) return
let ec = new TextEncoder().encode(str)
for (let i = 0; (i < ec.length) && (this.offset < this.byteLength); ++i) {
this.dv.setUint8(this.offset, ec[i])
this.offset++
}
if (this.offset < this.byteLength) {
this.dv.setUint8(this.offset, 0)
this.offset++
}
}
//--------------------------------------------------------------------------------
// string array to arraybuffer
pushStrArray(strArray) {
// this.pushInt(strArray.length) // array size
// let dst = 0
// let view = new Uint8Array(this.buff, this.offset)
// for (let i = 0; i < strArray.length; ++i) {
// let str = strArray[i]
// let ec = new TextEncoder().encode(str)
// for (let i = 0; i < ec.length; ++i) {
// view[dst++] = ec[i]
// }
// view[dst++] = 0
// }
// this.offset += dst
if (!this.dv) return
this.pushInt(strArray.length) // array size
for (let i = 0; i < strArray.length; ++i) {
const str = strArray[i]
let ec = new TextEncoder().encode(str)
for (let k = 0; (k < ec.length) && (this.offset < this.byteLength); ++k) {
this.dv.setUint8(this.offset++, ec[k])
}
if (this.offset < this.byteLength)
this.dv.setUint8(this.offset++, 0)
}
}
//--------------------------------------------------------------------------------
// number to arraybuffer
pushByte(num) {
// let view = new Uint8Array(this.buff, this.offset)
// view[0] = number
// this.offset += 1
if (!this.dv) return
if (this.offset >= this.byteLength) return
this.dv.setUint8(this.offset, num)
this.offset += 1
}
//--------------------------------------------------------------------------------
// number to arraybuffer
pushInt(num) {
// this.calc4ByteAlignment()
// let view = new Int32Array(this.buff, this.offset)
// view[0] = number
// this.offset += 4
if (!this.dv) return
if (this.offset + 4 > this.byteLength) return
this.dv.setInt32(this.offset, num, true)
this.offset += 4
}
//--------------------------------------------------------------------------------
// number to arraybuffer
pushFloat(num) {
// this.calc4ByteAlignment()
// let view = new Float32Array(this.buff, this.offset)
// view[0] = number
// this.offset += 4
if (!this.dv) return
this.calc4ByteAlignment()
if (this.offset + 4 > this.byteLength) return
this.dv.setFloat32(this.offset, num, true)
this.offset += 4
}
pushUint8(num) {
if (!this.dv) return
if (this.offset + 1 > this.byteLength) return
this.dv.setUint8(this.offset, num)
this.offset += 1
}
pushInt8(num) {
if (!this.dv) return
if (this.offset + 1 > this.byteLength) return
this.dv.setInt8(this.offset, num)
this.offset += 1
}
pushUint16(num) {
if (!this.dv) return
if (this.offset + 2 > this.byteLength) return
this.dv.setUint16(this.offset, num, true)
this.offset += 2
}
pushInt16(num) {
if (!this.dv) return
if (this.offset + 2 > this.byteLength) return
this.dv.setInt16(this.offset, num, true)
this.offset += 2
}
pushUint32(num) {
if (!this.dv) return
this.calc4ByteAlignment()
if (this.offset + 4 > this.byteLength) return
this.dv.setUint32(this.offset, num, true)
this.offset += 4
}
pushInt32(num) {
if (!this.dv) return
this.calc4ByteAlignment()
if (this.offset + 4 > this.byteLength) return
this.dv.setInt32(this.offset, num, true)
this.offset += 4
}
pushUint64(num) {
if (!this.dv) return
this.calc4ByteAlignment()
if (this.offset + 8 > this.byteLength) return
this.dv.setBigUint64(this.offset, num, true)
this.offset += 8
}
pushInt64(num) {
if (!this.dv) return
this.calc4ByteAlignment()
if (this.offset + 8 > this.byteLength) return
this.dv.setBigInt64(this.offset, num, true)
this.offset += 8
}
pushFloat32(num) {
if (!this.dv) return
this.calc4ByteAlignment()
if (this.offset + 4 > this.byteLength) return
this.dv.setFloat32(this.offset, num, true)
this.offset += 4
}
pushFloat64(num) {
if (!this.dv) return
this.calc4ByteAlignment()
if (this.offset + 8 > this.byteLength) return
this.dv.setFloat64(this.offset, num, true)
this.offset += 8
}
pushBoolArray(ar) {
if (!this.dv) return
this.pushUint32(ar.length)
for (let i = 0; (i < ar.length) && ((this.offset + 1) < this.byteLength); ++i) {
this.dv.setUint8(this.offset, ar[i] ? 1 : 0)
this.offset += 1
}
}
pushUint8Array(ar) {
if (!this.dv) return
this.pushUint32(ar.length)
for (let i = 0; (i < ar.length) && ((this.offset + 1) < this.byteLength); ++i) {
this.dv.setUint8(this.offset, ar[i])
this.offset += 1
}
}
pushInt8Array(ar) {
if (!this.dv) return
this.pushUint32(ar.length)
for (let i = 0; (i < ar.length) && ((this.offset + 1) < this.byteLength); ++i) {
this.dv.setInt8(this.offset, ar[i])
this.offset += 1
}
}
pushUint16Array(ar) {
if (!this.dv) return
this.pushUint32(ar.length)
for (let i = 0; (i < ar.length) && ((this.offset + 2) < this.byteLength); ++i) {
this.dv.setUint16(this.offset, ar[i], true)
this.offset += 2
}
}
pushInt16Array(ar) {
if (!this.dv) return
this.pushUint32(ar.length)
for (let i = 0; (i < ar.length) && ((this.offset + 2) < this.byteLength); ++i) {
this.dv.setInt16(this.offset, ar[i], true)
this.offset += 2
}
}
pushUint32Array(ar) {
if (!this.dv) return
this.pushUint32(ar.length)
for (let i = 0; (i < ar.length) && ((this.offset + 4) < this.byteLength); ++i) {
this.dv.setUint32(this.offset, ar[i], true)
this.offset += 4
}
}
pushInt32Array(ar) {
if (!this.dv) return
this.pushUint32(ar.length)
for (let i = 0; (i < ar.length) && ((this.offset + 4) < this.byteLength); ++i) {
this.dv.setInt32(this.offset, ar[i], true)
this.offset += 4
}
}
pushFloat32Array(ar) {
if (!this.dv) return
this.pushUint32(ar.length)
for (let i = 0; (i < ar.length) && ((this.offset + 4) < this.byteLength); ++i) {
this.dv.setFloat32(this.offset, ar[i], true)
this.offset += 4
}
}
pushFloat64Array(ar) {
if (!this.dv) return
this.pushUint32(ar.length)
for (let i = 0; (i < ar.length) && ((this.offset + 8) < this.byteLength); ++i) {
this.dv.setFloat64(this.offset, ar[i], true)
this.offset += 8
}
}
//--------------------------------------------------------------------------------
// parse string in dataView
// return string
// dataView: DataView
// offset: offset number
dv2str(dataView) {
let str = []
let i = this.offset
let c = dataView.getUint8(i)
while (c != 0) {
str.push(c)
c = dataView.getUint8(++i)
}
if (str.length == 0) return ''
return new TextDecoder().decode(new Uint8Array(str))
}
//--------------------------------------------------------------------------
// getBoolean
getBool() {
if (!this.dv) return false
const v = this.dv.getUint8(this.offset)
this.offset += 1
return v != 0
}
//--------------------------------------------------------------------------------
// getInt8
getInt8() {
if (this.dv) {
const v = this.dv.getInt8(this.offset)
this.offset += 1
return v
}
return 0
}
//--------------------------------------------------------------------------------
// getUint8
getUint8() {
if (this.dv) {
const v = this.dv.getUint8(this.offset)
this.offset += 1
return v
}
return 0
}
//--------------------------------------------------------------------------
// getInt16
getInt16() {
if (!this.dv) return 0
const v = this.dv.getInt16(this.offset, true)
this.offset += 2
return v
}
//--------------------------------------------------------------------------
// getUint16
getUint16() {
if (!this.dv) return 0
const v = this.dv.getUint16(this.offset, true)
this.offset += 2
return v
}
//--------------------------------------------------------------------------------
// getInt32
getInt32() {
if (this.dv) {
this.calc4ByteAlignment()
const v = this.dv.getInt32(this.offset, true)
this.offset += 4
return v
}
return 0
}
//--------------------------------------------------------------------------------
// getUint32
getUint32() {
if (this.dv) {
this.calc4ByteAlignment()
const v = this.dv.getUint32(this.offset, true)
this.offset += 4
return v
}
return 0
}
//--------------------------------------------------------------------------------
// getInt64
getInt64() {
if (this.dv) {
this.calc4ByteAlignment()
const v = this.dv.getBigInt64(this.offset, true)
this.offset += 8
return v
}
return 0
}
//--------------------------------------------------------------------------------
// getUint64
getUint64() {
if (this.dv) {
this.calc4ByteAlignment()
const v = this.dv.getBigUint64(this.offset, true)
this.offset += 8
return v
}
return 0
}
//--------------------------------------------------------------------------------
// getFloat32
getFloat32() {
if (this.dv) {
this.calc4ByteAlignment()
const v = this.dv.getFloat32(this.offset, true)
this.offset += 4
return v
}
return 0
}
//--------------------------------------------------------------------------------
// getFloat64
getFloat64() {
if (this.dv) {
this.calc4ByteAlignment()
const v = this.dv.getFloat64(this.offset, true)
this.offset += 8
return v
}
return 0
}
//--------------------------------------------------------------------------
// get array buffer
getArray( Alloc ) {
if (!this.buff) return null
const length = this.getUint32()
if (length == 0) return null
let out = Alloc(this.buff, this.offset, length)
return out
}
getInt8Array() {
return this.getArray((buff, offset, length) => {
let ar = new Int8Array(buff, offset, length)
this.offset += length
return ar
})
}
getUint8Array() {
return this.getArray((buff, offset, length) => {
let ar = new Uint8Array(buff, offset, length)
this.offset += length
return ar;
})
}
getInt16Array() {
return this.getArray((buff, offset, length) => {
let ar = new Int16Array(buff, offset, length)
this.offset += length * 2
return ar
})
}
getUint16Array() {
return this.getArray((buff, offset, length) => {
let ar = new Uint16Array(buff, offset, length)
this.offset += length * 2
return ar
})
}
getInt32Array() {
return this.getArray((buff, offset, length) => {
let ar = new Int32Array(buff, offset, length)
this.offset += length * 4
return ar
})
}
getUint32Array() {
return this.getArray((buff, offset, length) => {
let ar = new Uint32Array(buff, offset, length)
this.offset += length * 4
return ar
})
}
// getInt64Array() {
// return this.getArray((buff, offset, length) => {
// let ar = new BigInt64Array(buff, offset, length)
// this.offset += length * 8
// return ar
// })
// }
// getUint64Array() {
// return this.getArray((buff, offset, length) => {
// let ar = new BigUint64Array(buff, offset, length)
// this.offset += length * 8
// return ar
// })
// }
getFloat32Array() {
return this.getArray((buff, offset, length) => {
let ar = new Float32Array(buff, offset, length)
this.offset += length * 4
return ar
})
}
getFloat64Array() {
return this.getArray((buff, offset, length) => {
let ar = new Float64Array(buff, offset, length)
this.offset += length * 8
return ar
})
}
//--------------------------------------------------------------------------------
// getStr
getStr() {
if (this.dv && this.buff) {
// let str = []
// let c = this.dv.getUint8(this.offset++)
// while ((c != 0) && (this.offset < this.buff.byteLength)) {
// str.push(c)
// c = this.dv.getUint8(this.offset++)
// }
// if (str.length == 0) return ''
// return new TextDecoder().decode(new Uint8Array(str))
let str = []
while (this.offset < this.byteLength) {
const c = this.dv.getUint8(this.offset++)
if (c == 0)
break
str.push(c)
}
if (str.length == 0) return ''
return new TextDecoder().decode(new Uint8Array(str))
}
return ''
}
//--------------------------------------------------------------------------
// get string array
getStrArray() {
if (!this.dv || !this.buff)
return []
const size = this.getUint32()
let ar = []
for (let i = 0; i < size; ++i)
ar.push(this.getStr())
return ar
}
//--------------------------------------------------------------------------
// get TypeVariant
getTypeVariant() {
let out = new TypeVariant()
out.vt = this.getUint16();
switch (out.vt) {
case VT_EMPTY:
break; // nothing
case VT_I2:
out.value = this.getInt16();
break;
case VT_I4:
out.value = this.getInt32();
break;
case VT_R4:
out.value = this.getFloat32();
break;
case VT_R8:
out.value = this.getFloat64();
break;
case VT_BSTR:
out.value = this.getStr();
break;
case VT_BOOL:
out.value = this.getUint8() > 0 ? true : false;
break;
case VT_I1:
out.value = this.getInt8();
break;
case VT_UI1:
out.value = this.getUint8();
break;
case VT_UI2:
out.value = this.getUint16();
break;
case VT_UI4:
out.value = this.getUint32();
break;
case VT_I8:
out.value = this.getInt32();
break;
case VT_UI8:
out.value = this.getUint32();
break;
case VT_INT:
out.value = this.getInt32();
break;
case VT_UINT:
out.value = this.getUint32();
break;
default:
if (out.vt & VT_BYREF) {
out.value = this.getUint32();
} else {
console.log(`error parse Network.Packet-TypeVariant ${out.vt}`);
}
break;
}
return out
}
//--------------------------------------------------------------------------
// get TypeVariant Array
getTypeVariantArray(size) {
let ar = []
for (let i = 0; i < size; ++i)
ar.push(this.getTypeVariant())
return ar
}
//--------------------------------------------------------------------------
// get TypeVariant Vector
getTypeVariantVector() {
const size = this.getUint32()
return this.getTypeVariantArray(size)
}
}
|
define(['Graft'], function (Graft) {
describe('Tools', function () {
describe('#parseAttributeFromString', function () {
it('parses non-functions correctly', function () {
var parsed = Graft.Tools.parseAttributeFromString('something');
chai.expect(parsed.isFunction).to.be.false;
chai.expect(parsed.name).to.equal('something');
chai.expect(parsed.assertion).to.equal(true);
});
it('parses non-functions with reversal (!something)', function () {
var parsed = Graft.Tools.parseAttributeFromString('!something');
chai.expect(parsed.isFunction).to.be.false;
chai.expect(parsed.name).to.equal('something');
chai.expect(parsed.assertion).to.equal(false);
});
it('parses functions (something())', function () {
var parsed = Graft.Tools.parseAttributeFromString('something()');
chai.expect(parsed.isFunction).to.be.true;
chai.expect(parsed.name).to.equal('something');
chai.expect(parsed.assertion).to.equal(true);
});
it('parses functions with reversal (!something())', function () {
var parsed = Graft.Tools.parseAttributeFromString('!something()');
chai.expect(parsed.isFunction).to.be.true;
chai.expect(parsed.name).to.equal('something');
chai.expect(parsed.assertion).to.equal(false);
});
});
describe('#pluckAttributeWithStringFormat', function () {
it('plucks a simple attribute', function () {
var x = {a: 100};
chai.expect(Graft.Tools.pluckAttributeWithStringFormat(x, 'a')).to.equal(x.a);
});
it('plucks a simple attribute with white space, ignoring whitespace', function () {
var x = {a: 100};
chai.expect(Graft.Tools.pluckAttributeWithStringFormat(x, ' a ')).to.equal(x.a);
});
it('plucks format with parans (eg methodName()) and runs it, returning its value', function () {
var x = {
methodName: function () {
return 2;
}
};
chai.expect(Graft.Tools.pluckAttributeWithStringFormat(x, 'methodName()')).to.equal(2);
});
it('plucks format with parans and whitespace (eg methodName()) and runs it, returning its value', function () {
var x = {
methodName: function () {
return 2;
}
};
chai.expect(Graft.Tools.pluckAttributeWithStringFormat(x, ' methodName() ')).to.equal(2);
});
it('plucks format with parans and (eg methodName()) and wont run it when third parameter is true', function () {
var x = {
methodName: function () {
return 2;
}
};
chai.expect(Graft.Tools.pluckAttributeWithStringFormat(x, 'methodName()', true)).to.equal(x.methodName);
});
});
});
});
|
var nautical = require('nautical')
var util = require('../util')
module.exports = {
search: function (account, callback) {
var results = []
var client = nautical.getClient({ token: account.token })
var get_servers = function (page, done) {
client.droplets.list({ page: page }, function (error, reply) {
if (error) {
return done(error)
}
reply.body.droplets.forEach(function (server) {
var result = {
'id': server.id,
'name': server.name,
'region': server.region.slug,
'hostname': server.networks.v4[0].ip_address,
'account': account,
'image': server.image.id,
'ip': server.networks.v4[0].ip_address,
'private-ip': ((server.networks.v4.length > 1) ? server.networks.v4[1].ip_address : server.networks.v4[0].ip_address),
'type': server.size_slug
}
if (server.networks.v6 && server.networks.v6.length) {
result.ipv6 = server.networks.v6[0].ip_address
}
results.push(result)
})
if (typeof reply.next === 'function') {
return get_servers(page += 1, done)
}
return done()
})
}
get_servers(1, function (error) {
if (error) {
console.log('Something went wrong when searching DigitalOcean: %s'.red, error)
}
return callback(results)
})
},
ssh: function (server, options) {
util.ssh(server, options)
},
display: function (server, index) {
util.display(server, index)
},
regions: ['nyc1', 'ams1', 'sfo1', 'nyc2', 'ams2', 'sgp1', 'lon1', 'nyc3', 'ams3'],
keys: ['id', 'name', 'region', 'hostname', 'account', 'image', 'ip', 'private-ip', 'ipv6', 'type']
}
|
var request = require('request');
var Q = require('q');
// Request end-point. Fill this in when I know it.
var sensorsUrl = 'http://atthack2015-omt66.c9.io/api/users/user1/latest';
// Local magic variables
var temperatureThresh = 79; // Fahrenheit
var humidityThresh = 37.2; // Percentage
var brightnessThresh = 0; // 0: dark, 1: light
var altThresh = 1000; // Lat (degrees), Long (degrees), Alt (m)
var minVolume = 30;
// Test sets of sensor data
var sensorTestData = [
{ // 0
"temperature":temperatureThresh, // All at (but not above) threshold
"humidity":humidityThresh,
"brightness":brightnessThresh,
"gps":[28,160,altThresh],
"mood":0
},
{ // 1
"temperature":temperatureThresh+1, // Break temperature thresh
"humidity":humidityThresh,
"brightness":brightnessThresh,
"gps":[28,160,altThresh],
"mood":1
},
{ // 2
"temperature":temperatureThresh,
"humidity":humidityThresh+1, // Break humidity thresh
"brightness":brightnessThresh,
"gps":[28,160,altThresh],
"mood":2
},
{ // 3
"temperature":temperatureThresh+1, // Break temperature thresh
"humidity":humidityThresh+1, // Break humidity thresh
"brightness":brightnessThresh,
"gps":[28,160,altThresh],
"mood":2
},
{ // 4
"temperature":temperatureThresh,
"humidity":humidityThresh,
"brightness":brightnessThresh+1, // Break brightness thresh
"gps":[28,160,altThresh],
"mood":3
}
];
var testDataIdx = 0;
var songOrder = [0,1,2,3];
// Print sensors data
var printSensorsData = function printSensorsData(sensorsData) {
console.log('Temp: ' + sensorsData.temperature + ", Hum: " + sensorsData.humidity + ", Brightness: " + sensorsData.brightness + ", Mood: " + sensorsData.mood);
};
// Get the sensors data
var getSensorsData = function getSensorsData(liveDemo) {
var deferred = Q.defer();
var sensData;
if (liveDemo) {
request(sensorsUrl, function(err,res,body) {
if (!err && res.statusCode == 200) {
sensData = JSON.parse(body);
// console.log(sensData);
if (sensData.mood == undefined) sensData.mood = {level:3};
S = {
"temperature":Number(sensData.temperature.val),
"humidity":Number(sensData.humidity.replace(/%/g,'')), // mystring.replace(/r/g, '')
"brightness":(sensData.brightness == 'dark') ? 0 : 1,
"gps":[Number(sensData.gps.lat), Number(sensData.gps.lon), Number(sensData.gps.alt)],
"mood":sensData.mood.level || 0
};
printSensorsData(S);
deferred.resolve(S);
} else deferred.reject(err);
});
} else { // Debug data
sensData = sensorTestData[songOrder[testDataIdx]];
printSensorsData(sensData);
deferred.resolve(sensData);
testDataIdx = (testDataIdx+1)%4;
}
return deferred.promise;
};
// Function to select the song index
var getControlVars = function getControlVars(liveDemo) {
var deferred = Q.defer();
// Get the sensors data
getSensorsData(liveDemo).then(function(sensorData) {
songBin = ["0", "0", "0", "0"];
if (sensorData.temperature > temperatureThresh) songBin[0] = "1";
if (sensorData.humidity > humidityThresh) songBin[1] = "1";
if (sensorData.brightness > brightnessThresh) songBin[2] = "1";
if (sensorData.gps[3] > altThresh) songBin[3] = "1";
var songIdxFromSensors = parseInt(songBin.reverse().join(''),2);
var songIdxFromMood = sensorData.mood;
// Set volume based on something
vol = minVolume + Math.floor(sensorData.humidity/10);
var controlVars = {
songIdx:songIdxFromMood,
vol:vol
};
deferred.resolve(controlVars);
},function (err) {deferred.reject(err)});
return deferred.promise;
};
module.exports.getControlVars = getControlVars;
|
angular.module('synergyCity')
.directive('dragStart', function() {
return {
controller: function($scope, $element, $attrs, $parse) {
$element.attr('draggable', true);
$element.on('dragstart', function() {
$parse($attrs.dragStart)($scope);
});
}
}
})
.directive('dragOver', function() {
return {
controller: function($scope, $element, $attrs, $parse) {
$element.on('dragover', function(event) {
$parse($attrs.dragOver)($scope, { $event: event });
});
}
}
})
.directive('dragEnd', function() {
return {
controller: function($scope, $element, $attrs, $parse) {
$element.on('dragend', function(event) {
$parse($attrs.dragEnd)($scope, { $event: event });
});
}
}
})
.directive('drop', function() {
return {
controller: function($scope, $element, $attrs, $parse) {
$element.on('drop', function() {
$parse($attrs.drop)($scope);
$element.attr('draggable', false);
$scope.$apply();
});
}
}
})
|
(function(define) {
'use strict';
define(function(require) {
/**
* PanthR Language parser
*
* @module panthrLang
* @version 0.0.1
* @noPrefix
* @author Haris Skiadas <skiadas@hanover.edu>
*/
var panthrLang, Parser, parser, Node, Evaluate, Expression, Console;
Node = require('./panthrLang/node');
Console = require('./panthrLang/console');
Evaluate = require('./panthrLang/evaluate');
Expression = require('./panthrLang/expression');
parser = require('./panthrLang/parser').parser;
Parser = require('./panthrLang/parser').Parser;
Parser.prototype.parseError = function parseError(str, hash) {
function _parseError(msg, hash2) {
this.message = msg;
this.hash = hash2;
}
if (hash.recoverable) {
this.myError = { str: str, hash: hash };
this.trace(str);
} else {
_parseError.prototype = Error;
throw new _parseError(str, hash);
}
};
panthrLang = {
Node: Node,
Console: Console,
Evaluate: Evaluate,
Expression: Expression,
parse: function(str, action) {
if (action == null) { action = function(x) { console.log(x); }; }
// action is the function to call on each completed node
parser.yy.emit = function(node) { action(node); };
return parser.parse(str);
},
eval: function(str) {
return this.getInitializedEvaluate().parseAndEval(str);
},
getInitializedEvaluate: function() {
return (new Evaluate()).initialSetup();
}
};
Evaluate.addPackage('base', require('./packages/base'));
Evaluate.addPackage('stats', require('./packages/stats'));
return panthrLang;
});
}(typeof define === 'function' && define.amd ? define : function(factory) {
'use strict';
module.exports = factory(require);
}));
|
/*************************************************************
*
* MathJax/localization/ar/HTML-CSS.js
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
MathJax.Localization.addTranslation("ar","HTML-CSS",{
version: "2.7.3",
isLoaded: true,
strings: {
LoadWebFont: "\u062A\u062D\u0645\u064A\u0644 \u062E\u0637 \u0639\u0644\u0649 \u0634\u0628\u0643\u0629 \u0627\u0644\u0625\u0646\u062A\u0631\u0646\u062A %1",
CantLoadWebFont: "\u0644\u0627 \u064A\u0645\u0643\u0646 \u062A\u062D\u0645\u064A\u0644 \u062E\u0637 \u0639\u0644\u0649 \u0634\u0628\u0643\u0629 \u0627\u0644\u0625\u0646\u062A\u0631\u0646\u062A %1",
FirefoxCantLoadWebFont: "\u0641\u0627\u064A\u0631\u0641\u0648\u0643\u0633 \u0644\u0627 \u064A\u0645\u0643\u0646\u0647 \u062A\u062D\u0645\u064A\u0644 \u0627\u0644\u062E\u0637\u0648\u0637 \u0639\u0644\u0649 \u0634\u0628\u0643\u0629 \u0627\u0644\u0625\u0646\u062A\u0631\u0646\u062A \u0645\u0646 \u0645\u0636\u064A\u0641 \u0628\u0639\u064A\u062F",
CantFindFontUsing: "\u0644\u0627 \u064A\u0645\u0643\u0646 \u0627\u0644\u0639\u062B\u0648\u0631 \u0639\u0644\u0649 \u062E\u0637 \u0635\u0627\u0644\u062D \u0628\u0627\u0633\u062A\u062E\u062F\u0627\u0645 %1",
WebFontsNotAvailable: "\u062E\u0637\u0648\u0637 \u0627\u0644\u0648\u064A\u0628 \u063A\u064A\u0631 \u0645\u062A\u0648\u0641\u0631\u0629. \u0627\u0633\u062A\u062E\u062F\u0627\u0645 \u062E\u0637\u0648\u0637 \u0627\u0644\u0635\u0648\u0631\u0629 \u0628\u062F\u0644\u0627 \u0645\u0646 \u0630\u0644\u0643"
}
});
MathJax.Ajax.loadComplete("[MathJax]/localization/ar/HTML-CSS.js");
|
const _methodsNotToBeBound = {
constructor: true,
render: true,
};
export function bindMethodContext(object) {
Object
.getOwnPropertyNames(object.constructor.prototype)
.filter(name => !_methodsNotToBeBound[name])
.forEach(name => {
object[name] = object[name].bind(object);
});
}
|
//var paths = require('/Users/Vsilva/WebstormProjects/BlackBook_AutomationFramework/build/paths');
//var browserstack = require('browserstack-local');
//var paths = require('build/paths');
var dateFormat = require('dateformat');
var protractorConfig = require ('./e2e/features/Repository/BB_configuration.js');
exports.config = {
//specs: [
//'e2e/features/TestCases/*.feature'
// ],
//Turn off applitool
'ApplitoolsOn': protractorConfig.ApplitoolsOn,
//Running Test Cases in specific order.
specs: [
//Browserstack can only run for 2 hours long. Then it will stop
//add test cases here below:
'e2e/features/TestCases/Setup.feature'//,
],
// suites: {
// smoke: 'e2e/features/TestCases/OpenWebsite1.feature'//,
// },
//BrowserStack
'seleniumAddress': 'http://hub-cloud.browserstack.com/wd/hub',
//Settings for the local machine (Run "webdriver-manager start" from any directory + calls inside capabilities)
//Selenium
//seleniumAddress: 'http://localhost:4444/wd/hub',
//Appium
//seleniumAddress: 'http://localhost:4733/wd/hub',
////////////////////
// //windows XP and 7 lowest resolution
// 'width': 694,
// 'height': 494,
// Test 1 on this resolution (windows 8-10 and Mac lowest resolution)
// 'width': 918,
// 'height': 662,
// //this works on my mac computer
// 'width': 1024,
// 'height': 666,
////////////////////
// // //my MAC computer max resolution
// 'width': 1338,
// 'height': 666,
//Test 2 on this resolution (Mac max resolution)
'width': protractorConfig.width,
'height': protractorConfig.height,
// // //windows all version max resolution
// 'width': 1942,
// 'height': 1430,
'commonCapabilities': {
//Label
'build':''+protractorConfig.BuildTestNumber+'__________________ Run : Chrome_______________ Test : Setup_________________ ' + dateFormat(new Date(), "mmmm dS, yyyy, h:MM TT"),
'project': 'Black Book',
'name': 'Setup',
'browserstack.user': 'soltech2',
'browserstack.key': 'mnKfscqSMQ8C7jFfZR2Y',
//'browserstack.local' : 'true',
// 'acceptSslCerts': true,
'browserstack.selenium_version' : '3.3.1',
//Screenshot
'browserstack.debug': 'false',
//Video recording
'browserstack.video': 'true'//,
},
//Browserstack multiple browsers at a time testing
multiCapabilities: [
// {
// ////////////////////////////////////////////// Windows 10 IE 11.0 1920x1200 ///////////////////
// //Browser Type
// 'browserName' : 'IE',
// 'browser_version' : '11.0',
// 'os' : 'Windows',
// 'os_version' : '10',
// 'resolution' : '1920x1200'
// }
// ,
// {
// ////////////////////////////////////////////// Windows 10 Edge 13.0 1920x1200 ///////////////////
// //Browser Type
// 'os': 'Windows',
// 'os_version': '10',
// 'browserName': 'Edge',
// 'browser_version': '13.0',
// 'resolution': '1920x1200'
// }
// ,
{
////////////////////////////////////////////// Windows 10 Chrome 57.0 1920x1200 ///////////////////
// Browser Type
'os': 'Windows',
'os_version': '10',
'browserName': 'Chrome',
'browser_version': '57.0',
'resolution': '1920x1200',
'chromeOptions': {
'excludeSwitches': ["disable-popup-blocking"],
'args': [
'--disable-infobars'
],
'prefs': {
// disable chrome's annoying password manager
'profile.password_manager_enabled': false,
'credentials_enable_service': false,
'password_manager_enabled': false
}
}
// 'chromeOptions': {
// 'excludeSwitches': ["disable-popup-blocking"]
// }
// 'chromeOptions': {
// 'args': ["--disable-popup-blocking"]
// }
}
// ,
// {
// ////////////////////////////////////////////// Windows 10 Firefox 47.0 1920x1200 ///////////////////
// // Browser Type
// 'os': 'Windows',
// 'os_version': '10',
// 'browserName': 'Firefox',
// 'browser_version': '47.0',
// 'resolution': '1920x1200'
// }
// ,
// {
// ////////////////////////////////////////////// MAC SIERRA Safari 10.0 1920x1080 ///////////////////
// // Browser Type
// 'os': 'OS X',
// 'os_version': 'Sierra',
// 'browserName': 'Safari',
// 'browser_version': '10.0',
// 'resolution': '1920x1080' //,
// //'browserstack.safari.enablePopups': false
// }
/////////////NOT NEED FOR MOMENT/////
// ,
// {
// ////////////////////////////////////////////// DOES NOT WORK Windows 7 IE 10.0 1920x1200 ///////////////////
// // Browser Type
// 'os': 'Windows',
// 'os_version': '7',
// 'browserName': 'IE',
// 'browser_version': '10.0',
// 'resolution': '1920x1200'
// }
// ,
// {
// ////////////////////////////////////////////// Windows 7 IE 11.0 1920x1200 ///////////////////
// // Browser Type
// 'os': 'Windows',
// 'os_version': '7',
// 'browserName': 'IE',
// 'browser_version': '11.0',
// 'resolution': '1920x1200'
// }
// ,
// {
// ////////////////////////////////////////////// Windows 7 Chrome 54.0 1920x1200 ///////////////////
// // Browser Type
// 'os': 'Windows',
// 'os_version': '7',
// 'browserName': 'Chrome',
// 'browser_version': '54.0',
// 'resolution': '1920x1200'//,
//
// // 'chromeOptions': {
// // 'excludeSwitches': ["disable-popup-blocking"]
// // }
//
// // 'chromeOptions': {
// // 'args': ["--disable-popup-blocking"]
// // }
// }
// ,
// {
// ////////////////////////////////////////////// Windows 7 FireFox 46.0 1920x1200 ///////////////////
// //Browser Type
// 'os': 'Windows',
// 'os_version': '7',
// 'browserName': 'Firefox',
// 'browser_version': '46.0',
// 'resolution': '1920x1200'
// }
],
// capabilities: {
// //46.0b9
// //'browserName': 'firefox'
// //53.0.2785.89
// 'browserName': 'chrome'
// // 'browserName': 'safari'//,
// // 'acceptSslCerts': true,
// // 'mode' : 'proxy'
//
// },
//Then update config file and set the browserstack.local capability to true.
//Code to start browserstack local before start of test
// beforeLaunch: function(){
// console.log("Connecting local");
// return new Promise(function(resolve, reject){
// exports.bs_local = new browserstack.Local();
// exports.bs_local.start({'key': exports.config.capabilities['browserstack.key'] }, function(error) {
// if (error) return reject(error);
// console.log('Connected. Now testing...');
//
// resolve();
// });
// });
// },
//
// // Code to stop browserstack local after end of test
// afterLaunch: function(){
// return new Promise(function(resolve, reject){
// exports.bs_local.stop(resolve);
// });
// },
//directConnect: true, //Protractor can test directly against Chrome and Firefox without using a Selenium Server
//REAL // path relative to the current config file
frameworkPath: require.resolve('protractor-cucumber-framework'),
// framework: 'cucumber',
//set to "custom" instead of cucumber.
framework: 'custom',
//relevant cucumber command line options
cucumberOpts: {
keepAlive: true,
//format: "summary", //simple format
//require: [paths.distFiles, paths.support],
// require: ['/Users/Vsilva/WebstormProjects/BlackBook_AutomationFramework/support/JsonOutputHook.js'],
require: [protractorConfig.Path_mySteps.toString()],
// tags: false,
//tags: ' @TestCases_C-7',
//format: 'pretty',
//format: 'json' ,
format: 'json:./src/cucumber_report.json',
//format: 'progress',
//format: 'json',
//format: 'summary',
// profile: false, //false it still works on true
profile: false,
'no-source': true,
//require: ['TestAutomation/e2e/features/step_definitions/my_steps.js', paths.support],
//testing new stuff
// backtrace: true, // <boolean> show full bacwebdriver-manager updatektrace for errors
// dryRun: false, // <boolean> invoke formatters without executing steps
// failFast: false , // <boolean> abort the run on first failure
// colors: true, // <boolean> disable colors in formatter output
// snippets: true , // <boolean> hide step definition snippets for pending steps
// source: true, // <boolean> hide source URIs
// strict: true, // <boolean> fail if there are any undefined or pending steps
// ignoreUndefinedDefinitions: true // <boolean> Enable this config to treat undefined definitions as warnings.
},
// cucumberOpts: {
// // require:'/Users/Vsilva/Desktop/Black Book/TestAutomation/e2e/features/UserStoriesSteps_Cucumber/*_steps.js', // <string[]> (file/dir) require files before executing features
// backtrace: true, // <boolean> show full bacwebdriver-manager updatektrace for errors
// // compiler: [], // <string[]> ("extension:module") require files with the given EXTENSION after requiring MODULE (repeatable)
// dryRun: false, // <boolean> invoke formatters without executing steps
// failFast: false, // <boolean> abort the run on first failure
// format: 'pretty', // <string[]> (type[:path]) specify the output format, optionally supply PATH to redirect formatter output (repeatable)
// colors: true, // <boolean> disable colors in formatter output
// snippets: false, // <boolean> hide step definition snippets for pending steps
// source: false, // <boolean> hide source URIs
// // profile: [], // <string[]> (name) specify the profile to use
// strict: true, // <boolean> fail if there are any undefined or pending steps
// // tags: [], // <string[]> (expression) only execute the features or scenarios with tags matching the expression
// timeout: 20000, // <number> timeout for step definitions
// ignoreUndefinedDefinitions: false // <boolean> Enable this config to treat undefined definitions as warnings.
// }
// ,
//
getPageTimeout: 60000,
allScriptsTimeout: 60000,
useAllAngular2AppRoots: true
// rootElement: '.my-app'
};
// Code to support common capabilities
exports.config.multiCapabilities.forEach(function(caps){
for(var i in exports.config.commonCapabilities) caps[i] = caps[i] || exports.config.commonCapabilities[i];
}); |
var request = require('request');
var unzip = require('unzip');
//Settings
//var mainURL = 'https://api2.getpebble.com/v2/apps/collection/all/watchfaces?limit=100'; //watchfaces
var mainURL = 'https://api2.getpebble.com/v2/apps/collection/all/watchapps-and-companions?limit=100';
var hardware = 'basalt';
var filterhardware = true;
var MAX_QUEUE = 20;
//Vars
var offset = 0;
var pebbleJS = 0;
var error = 0;
var analyzed = 0;
var skipped = 0;
var someJS = 0;
function getAllPBWs(url, callback, pbws) {
if (!pbws) {
pbws = [];
}
request.get({
url: url,
json: true
}, function (error, response, body) {
if (body.data && body.data.length > 0) {
body.data.forEach(function (pbw) {
if (pbw.latest_release && pbw.latest_release.pbw_file) {
pbws.push(pbw.latest_release.pbw_file);
} else {
skipped++;
}
});
console.log('Now analyzing offset ' + offset++);
if (body.links.nextPage) {
getAllPBWs(body.links.nextPage, callback, pbws);
} else {
callback(pbws);
}
}
});
}
var queue = 0;
function printResults(pbw) {
var addToQueue = function () {
queue++;
var fetch = function (retry) {
if (retry < 5) {
var err = false;
request({
url: pbw,
timeout: 2500
}).on('error', function () {
if (!err) {
fetch(retry + 1);
err = true;
}
}).pipe(unzip.Parse().on('error', function () {
if (!err) {
fetch(retry + 1);
err = true;
}
})).on('entry', function (entry) {
if (!err) {
var fileName = entry.path;
if (fileName === "pebble-js-app.js") {
someJS++;
var result = '';
entry.on('error', function () {
console.log('entry error?');
}).on('readable', function () {
var chunk;
while ((chunk = entry.read()) != null) {
result += chunk;
}
}).on('end', function () {
if (result.indexOf('simply-pebble.js') > 0) {
pebbleJS++;
}
});
} else {
entry.autodrain();
}
} else {
entry.autodrain();
}
}).on('finish', function () {
if (!err) {
analyzed++;
queue--;
}
});
} else {
error++;
analyzed++;
queue--;
}
};
fetch(0);
};
var checkQueue = function () {
if (queue < MAX_QUEUE) {
addToQueue();
} else {
setTimeout(checkQueue, 500);
}
};
checkQueue();
}
getAllPBWs(mainURL + (filterhardware ? ('&filter_hardware=true&hardware=' + hardware) : ''), function (pbws) {
pbws = cleanArray(pbws);
pbws.forEach(function (pbw) {
printResults(pbw);
});
var done = function () {
setTimeout(function () {
if (analyzed >= pbws.length) {
displayResults();
process.exit(0);
} else {
console.log(analyzed + ' analyzed out of ' + pbws.length);
done();
}
}, 5000);
};
done();
});
function displayResults() {
console.log('There are ' + pebbleJS + ' PebbleJS pbws');
console.log('There are ' + someJS + ' pbws using some JS');
console.log('Out of ' + analyzed + ' pbws analyzed');
console.log();
console.log('Note: ' + error + ' pbws failed analysis');
console.log('Note: ' + skipped + ' apps were skipped because they do not have a PBW');
}
process.on('SIGINT', function () {
displayResults();
process.exit();
});
function cleanArray(actual) {
var newArray = [];
for (var i = 0; i < actual.length; i++) {
if (actual[i]) {
newArray.push(actual[i]);
}
}
return newArray;
} |
import {inject, bindable, customElement} from 'aurelia-framework';
@customElement('tab-wrapper')
@inject(Element)
export class TabsWrapper {
constructor(element) {
this.element = element;
}
attached() {
}
}
|
/**
* Created by lvliqi on 2017/5/2.
*/
const router = require('koa-router')();
const admin_menu = require('../../model/adminMenu');
const admin_user_right = require('../../model/adminUserRight');
const admin_right_group = require('../../model/adminRightGroup');
const admin_right_group_detail = require('../../model/adminRightGroupDetail');
const admin_right_base = require('../../model/adminRightBase');
const errcode = require('../../config/errcode');
router.post('/menu/list', async ctx => {
let user = ctx.session.user;
let userRight = await admin_user_right.getByUid(user.id);
if (!userRight) {
return ctx.error(errcode.NO_CONFIG_RIGHT);
}
let rgid = userRight.rgid;
let rightGroup = await admin_right_group.getById(rgid);
if (!rightGroup) {
return ctx.error(errcode.NO_RGID);
}
if (rightGroup.is_super == 1) {
let row = await admin_menu.menu();
ctx.success(row);
} else {
let rightDetail = await admin_right_group_detail.getFuncRight(rgid);
let rightMenu = await admin_right_group_detail.getMneuRight(rgid);
let rbIds = rightDetail.map(d => d.rbid);
let rightBase = [];
if (rbIds.length > 0) {
rightBase = await admin_right_base.getByIds(rbIds);
}
let row = await admin_menu.menu(rightMenu, rightBase);
ctx.success(row);
}
});
module.exports = router; |
// >>> WARNING THIS PAGE WAS AUTO-GENERATED - DO NOT EDIT!!! <<<
import QuestionPage from '../question.page'
class ExpenditureExisting2016Page extends QuestionPage {
constructor() {
super('expenditure-existing-2016')
}
setExpenditureExisting2016Answer(value) {
browser.setValue('[name="expenditure-existing-2016-answer"]', value)
return this
}
getExpenditureExisting2016Answer(value) {
return browser.element('[name="expenditure-existing-2016-answer"]').getValue()
}
}
export default new ExpenditureExisting2016Page()
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.goForward = exports.goBack = exports.jumpTo = undefined;
var _history = require('./history');
var _history2 = _interopRequireDefault(_history);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var jumpTo = exports.jumpTo = function jumpTo(to) {
return _history2.default.push(to);
};
var goBack = exports.goBack = function goBack() {
return _history2.default.goBack();
};
var goForward = exports.goForward = function goForward() {
return _history2.default.goForward();
};
exports.default = { jumpTo: jumpTo, goBack: goBack, goForward: goForward }; |
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { bindActionCreators } from 'redux'
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
import { Field,reduxForm } from 'redux-form'
import * as Actions from 'actions'
import SNSLogin from './snsLogin'
import { isLogin } from 'utils/authService'
const mapStateToProps = state =>{
return {
globalVal : state.globalVal.toJS(),
auth: state.auth.toJS(),
sns: state.sns.toJS()
}
}
const mapDispatchToProps = dispatch =>{
return {
actions: bindActionCreators(Actions, dispatch)
}
}
const validate = values => {
const errors = {}
if (!values.email) {
errors.email = 'Required'
} else if (!/^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/.test(values.email)) {
errors.email = '无效电子邮件地址'
}
if (!values.password) {
errors.password = 'Required'
} else if (values.password.length > 30) {
errors.password = '密码长度不超过30'
}
if (!values.captcha) {
errors.captcha = 'Required'
} else if (values.captcha.length !== 6) {
errors.captcha = '验证码是6位'
}
return errors
}
const validatorCalss = field => {
let initClass = 'form-control'
if(field.invalid){
initClass += ' ng-invalid'
}
if(field.dirty){
initClass += ' ng-dirty'
}
return initClass
}
const renderField = prs => (
<input className={validatorCalss(prs.meta)} name={prs.name} maxLength={prs.maxLength} {...prs.input} placeholder={prs.placeholder} type={prs.type} />
)
@withRouter
@connect(mapStateToProps,mapDispatchToProps)
@reduxForm({
form: 'signin',
validate
})
export default class Login extends Component {
constructor(props){
super(props)
this.submitForm = this.submitForm.bind(this)
this.changeCaptcha = this.changeCaptcha.bind(this)
}
static propTypes = {
actions: PropTypes.object.isRequired,
globalVal: PropTypes.object.isRequired,
auth: PropTypes.object.isRequired,
sns: PropTypes.object.isRequired,
handleSubmit: PropTypes.func,
dirty: PropTypes.bool,
invalid: PropTypes.bool,
history: PropTypes.object
}
componentWillMount(){
// const { auth } = this.props
if(isLogin()) {
this.props.history.replace('/')
}
}
static fetchData(params){
return [Actions.getSnsLogins()]
}
changeCaptcha(e){
e.preventDefault()
const { actions } = this.props
actions.getCaptchaUrl()
}
submitForm (values) {
const { actions } = this.props
actions.localLogin(values)
}
componentDidMount() {
const { actions,sns } = this.props
if(sns.logins.length < 1){
actions.getSnsLogins()
}
}
render() {
const { sns, globalVal: {captchaUrl}, dirty,invalid, handleSubmit} = this.props
return (
<div className="signin-box">
<div className="signin-container">
<h4 className="title">登 录</h4>
<form className="signin-form form-horizontal" onSubmit={handleSubmit(this.submitForm)} noValidate>
<div className="form-group">
<div className="input-group">
<div className="input-group-addon">
<i className="fa fa-envelope-o"></i>
</div>
<Field name="email" component={renderField} type="email" placeholder="邮箱" />
</div>
</div>
<div className="form-group">
<div className="input-group">
<div className="input-group-addon"><i className="fa fa-unlock-alt"></i></div>
<Field name="password" component={renderField} type="password" placeholder="密码" />
</div>
</div>
<div className="form-group" >
<div className="col-xs-6 captcha-code">
<Field name="captcha" component={renderField} type="text" maxLength="6" placeholder="验证码" />
</div>
<div className="col-xs-6 captcha-img">
<a href="javascript:;" onClick={this.changeCaptcha}>
<img src={captchaUrl} />
</a>
</div>
</div>
<div className="form-group">
<button disabled={ dirty && invalid } className="btn btn-primary btn-lg btn-block" type="submit">登 录</button>
</div>
</form>
<p className="text-center">您还可以通过以下方式直接登录</p>
<SNSLogin logins={sns.logins} />
</div>
</div>
)
}
} |
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
var common = require('../common');
var assert = require('assert');
var once = 0;
function onAsync0() { }
function onAsync1() { }
var results = [];
var handlers = {
before: function() {
throw 1;
},
error: function(stor, err) {
// Must catch error thrown in before callback.
assert.equal(err, 1);
once++;
return true;
}
}
var handlers1 = {
before: function() {
throw 2;
},
error: function(stor, err) {
// Must catch *other* handlers throw by error callback.
assert.equal(err, 1);
once++;
return true;
}
}
var listeners = [
process.addAsyncListener(onAsync0, handlers),
process.addAsyncListener(onAsync1, handlers1)
];
var uncaughtFired = false;
process.on('uncaughtException', function(err) {
uncaughtFired = true;
// Both error handlers must fire.
assert.equal(once, 2);
});
process.nextTick(function() { });
for (var i = 0; i < listeners.length; i++)
process.removeAsyncListener(listeners[i]);
process.on('exit', function(code) {
// If the exit code isn't ok then return early to throw the stack that
// caused the bad return code.
if (code !== 0)
return;
// Make sure uncaughtException actually fired.
assert.ok(uncaughtFired);
console.log('ok');
});
|
define( "RequireFile" , [ "Base" ] , function( Base ){
var RequireFile,
require = function( path , requireFile ){
if( typeof path != "string" ){
this.length--;
} else if( requireFile.__requireFileConfig.files[ path ] ){
this.done( path );
} else if( !path.replace( requireFile.__requireFileConfig.fileType.page , "" ) ){
requireHtml.call( this , path );
} else if( !path.replace( requireFile.__requireFileConfig.fileType.js , "" ) ){
requireJs.call( this , path );
} else if( !path.replace( requireFile.__requireFileConfig.fileType.css , "" ) ){
requireCss.call( this , path );
} else if( !path.replace( requireFile.__requireFileConfig.fileType.img , "" ) ){
requireImg.call( this , path );
}
} ,
requireJs = function( path ) {
var _script = document.createElement("script"),
_self = this;
_script.type = "text/javascript";
_script.src = path;
document.body.appendChild( _script );
if( $.browser && $.browser.msie ){
_script.onreadystatechange = function(){
if( _script.readyState == "complete" || _script.readyState == "loaded" ){
_self.done( path );
};
};
} else {
_script.onload = function(){
_self.done( path );
};
};
} ,
requireCss = function( path ){
var _link = document.createElement("link"),
_self = this ,
_head = document.head || document.getElementsByTagName("head")[ 0 ];
_link.rel = "stylesheet";
_link.href = path;
_head.appendChild( _link );
_link.onload = function(){
_self.done( path );
}
} ,
requireHtml = function( path ){
var _t = 0 ,
_state = "loading" ,
_self = this ,
x = function(){
_t += 50;
window.setTimeout( function(){
if( _state !== "ready" ){
try{
$.get( path , function( rtn ){
$( "body" ).append( rtn );
_self.done( path );
_state = "ready";
});
} catch( e ) {
x();
};
};
} , _t );
};
x();
} ,
requireImg = function( path ){
var _img = document.createElement("img") ,
_self = this;
_img.src = path;
_img.onload = function(){
_self.done( path );
};
};
/*!
* 获取对应的html css image文件
*/
RequireFile = Base.extend( function( filePath , callBack ){
this._requireFileConfig = {}
if ( !this.__requireFileConfig.files ) {
this.__requireFileConfig.files = {};
this.__initFiles();
}
this.getFile( filePath , callBack );
} , {
__requireFileConfig : {
files : false ,
fileType: {
page : /.*\.(html?|jsp|php|aspx?)$/i,
js : /.*\.js$/i,
img : /.*\.(jpe?g|png|bmp)$/i,
css : /.*\.css$/i
}
} ,
__initFiles : function(){
var _nodes = document.head,
_urls = [];
if( _nodes ){
_nodes = _nodes.childNodes;
for( var i = _nodes.length; i--; ){
if( _nodes[ i ].nodeName === "SCRIPT" && _nodes[ i ].src ){
_urls.push( _nodes[ i ].outerHTML.replace( /.*src\="(.*)".*/i , "$1" ) );
} else if( _nodes[ i ].nodeName === "LINK" ){
_urls.push( _nodes[ i ].outerHTML.replace( /.*href\="(.*)".*/i , "$1" ) );
}
}
}
_nodes = document.getElementsByTagName( "script" );
for( var i = _nodes.length; i--; ){
if( _nodes[ i ].nodeName === "SCRIPT" && _nodes[ i ].src ){
_urls.push( _nodes[ i ].outerHTML.replace( /.*src\="(.*)".*/i , "$1" ) );
}
}
this.filterRequireUrls( _urls );
return this;
} ,
/*!
* urls = ["../bin/aa.html" , "../bin/bbb.html"];
* 遇到以上的url请求时 直接执行callback命令
*/
filterRequireUrls : function( urls ){
for( var i = urls.length; i--; ){
this.__requireFileConfig.files[ urls[ i ] ] = true;
}
return this;
} ,
/*!
* 简写getFile 方便后续扩展开发
*/
get : function(){
return this.getFile.apply( this , arguments );
} ,
/*!
* 获取文件
* @filePath {string|array}
* @callBack {function}
* @isOrder {bool} 是否按照顺序加载
*/
getFile : function( filePath , callBack , isOrder ){
var _url,
_iterator,
_self = this;
if( isOrder ){
return this.getFileInOrder( filePath , callBack );
} else if( filePath ){
if ( typeof filePath === "string" ) {
filePath = [ filePath ];
}
if ( filePath instanceof Array && filePath.length ) {
_iterator = {
length : filePath.length ,
waitLength : filePath.length ,
doneUrl : 0 ,
done : function( path ){
_self.__requireFileConfig.files[ path ] = true;
if ( !--this.waitLength ) {
if( typeof callBack == "function" ){
callBack();
}
}
}
}
for( var i = filePath.length; i--; ){
_url = filePath[ i ];
require.call( _iterator , _url , this );
}
}
}
return this;
} ,
/*!
* 按顺序加载文件
* @filePath {string|array}
* @callBack {function}
*/
getFileInOrder : function( filePath , callBack ){
var _self = this;
if ( !filePath instanceof Array ) {
return this.getFile( filePath , callBack );
} else {
this.getFile( filePath[ 0 ] , function(){
filePath.splice( 0 , 1 );
if( filePath.length ){
_self.getFileInOrder( filePath , callBack );
} else {
callBack();
}
} );
}
return this;
}
} );
return RequireFile;
} );
|
import { connect } from 'react-redux';
import { fetchStatusesIfNeeded } from '../actions';
import List from '../components/list';
const mapStateToProps = state => {
return {
items: state.orderStatuses.items
};
};
const mapDispatchToProps = dispatch => {
return {
onLoad: () => {
dispatch(fetchStatusesIfNeeded());
}
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(List);
|
/**
* Created by Alex on 11/7/14.
*/
Template.welcomeIndex.helpers.canSignIn = function() {
return Accounts.loginServicesConfigured();
};
Template.welcomeIndex.events({
"click a#googleSignIn": function (e) {
e.preventDefault();
Meteor.loginWithGoogle({
requestPermissions: ["openid", "profile", "email"]
});
},
"click a#facebookSignIn": function (e) {
e.preventDefault();
Meteor.loginWithFacebook({
requestPermissions: ["email"]
});
}
}); |
define(function() {
return function randomInt(min,max, withZero) {
var rand = Math.random();
var randInt = Math.round(min + rand*(max-min));
if (withZero) {
return randInt;
}
else {
while (randInt === 0) {
rand = Math.random();
randInt = Math.round(min + rand*(max-min));
}
return randInt;
}
};
});
|
import loggerCreator from "app/utils/logger";
//noinspection JSUnresolvedVariable
var moduleLogger = loggerCreator("backend_lastfm_api");
export const API_KEY = "9e46560f972eb8300c78c0fc837d1c13";
export async function getArtistImage(artist) {
let logger = loggerCreator(getArtistImage.name, moduleLogger);
try {
const response = await fetch(
`http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=${encodeURIComponent(
artist
)}&autocorrect=1&api_key=${API_KEY}&format=json`
);
const responseJson = await response.json();
logger.info(`got response: ${responseJson}`);
return responseJson.artist.image[4]["#text"];
} catch (e) {
logger.warn(`failed to fetch song art`);
}
}
|
function deleteContent(collectionId, path, success, error) {
var safePath = checkPathSlashes(path);
// send ajax call
$.ajax({
url: "/zebedee/content/" + collectionId + "?uri=" + safePath,
type: 'DELETE',
success: function (response) {
if (success)
success(response);
},
error: function (response) {
if (error) {
error(response);
} else {
handleApiError(response);
}
}
});
}
|
'use strict'
const assert = require('assert')
const fs = require('fs')
const path = require('path')
const os = require('os')
const http = require('http')
const {closeWindow} = require('./window-helpers')
const remote = require('electron').remote
const screen = require('electron').screen
const app = remote.require('electron').app
const ipcMain = remote.require('electron').ipcMain
const ipcRenderer = require('electron').ipcRenderer
const BrowserWindow = remote.require('electron').BrowserWindow
const isCI = remote.getGlobal('isCi')
describe('browser-window module', function () {
var fixtures = path.resolve(__dirname, 'fixtures')
var w = null
var server
before(function (done) {
server = http.createServer(function (req, res) {
function respond () { res.end('') }
setTimeout(respond, req.url.includes('slow') ? 200 : 0)
})
server.listen(0, '127.0.0.1', function () {
server.url = 'http://127.0.0.1:' + server.address().port
done()
})
})
after(function () {
server.close()
server = null
})
beforeEach(function () {
w = new BrowserWindow({
show: false,
width: 400,
height: 400,
webPreferences: {
backgroundThrottling: false
}
})
})
afterEach(function () {
return closeWindow(w).then(function () { w = null })
})
describe('BrowserWindow.close()', function () {
it('should emit unload handler', function (done) {
w.webContents.on('did-finish-load', function () {
w.close()
})
w.once('closed', function () {
var test = path.join(fixtures, 'api', 'unload')
var content = fs.readFileSync(test)
fs.unlinkSync(test)
assert.equal(String(content), 'unload')
done()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'unload.html'))
})
it('should emit beforeunload handler', function (done) {
w.once('onbeforeunload', function () {
done()
})
w.webContents.on('did-finish-load', function () {
w.close()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'beforeunload-false.html'))
})
})
describe('window.close()', function () {
it('should emit unload handler', function (done) {
w.once('closed', function () {
var test = path.join(fixtures, 'api', 'close')
var content = fs.readFileSync(test)
fs.unlinkSync(test)
assert.equal(String(content), 'close')
done()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'close.html'))
})
it('should emit beforeunload handler', function (done) {
w.once('onbeforeunload', function () {
done()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'close-beforeunload-false.html'))
})
})
describe('BrowserWindow.destroy()', function () {
it('prevents users to access methods of webContents', function () {
var webContents = w.webContents
w.destroy()
assert.throws(function () {
webContents.getId()
}, /Object has been destroyed/)
})
})
describe('BrowserWindow.loadURL(url)', function () {
it('should emit did-start-loading event', function (done) {
w.webContents.on('did-start-loading', function () {
done()
})
w.loadURL('about:blank')
})
it('should emit did-get-response-details event', function (done) {
// expected {fileName: resourceType} pairs
var expectedResources = {
'did-get-response-details.html': 'mainFrame',
'logo.png': 'image'
}
var responses = 0
w.webContents.on('did-get-response-details', function (event, status, newUrl, oldUrl, responseCode, method, referrer, headers, resourceType) {
responses++
var fileName = newUrl.slice(newUrl.lastIndexOf('/') + 1)
var expectedType = expectedResources[fileName]
assert(!!expectedType, `Unexpected response details for ${newUrl}`)
assert(typeof status === 'boolean', 'status should be boolean')
assert.equal(responseCode, 200)
assert.equal(method, 'GET')
assert(typeof referrer === 'string', 'referrer should be string')
assert(!!headers, 'headers should be present')
assert(typeof headers === 'object', 'headers should be object')
assert.equal(resourceType, expectedType, 'Incorrect resourceType')
if (responses === Object.keys(expectedResources).length) {
done()
}
})
w.loadURL('file://' + path.join(fixtures, 'pages', 'did-get-response-details.html'))
})
it('should emit did-fail-load event for files that do not exist', function (done) {
w.webContents.on('did-fail-load', function (event, code, desc, url, isMainFrame) {
assert.equal(code, -6)
assert.equal(desc, 'ERR_FILE_NOT_FOUND')
assert.equal(isMainFrame, true)
done()
})
w.loadURL('file://a.txt')
})
it('should emit did-fail-load event for invalid URL', function (done) {
w.webContents.on('did-fail-load', function (event, code, desc, url, isMainFrame) {
assert.equal(desc, 'ERR_INVALID_URL')
assert.equal(code, -300)
assert.equal(isMainFrame, true)
done()
})
w.loadURL('http://example:port')
})
it('should set `mainFrame = false` on did-fail-load events in iframes', function (done) {
w.webContents.on('did-fail-load', function (event, code, desc, url, isMainFrame) {
assert.equal(isMainFrame, false)
done()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'did-fail-load-iframe.html'))
})
it('does not crash in did-fail-provisional-load handler', function (done) {
this.timeout(10000)
w.webContents.once('did-fail-provisional-load', function () {
w.loadURL('http://127.0.0.1:11111')
done()
})
w.loadURL('http://127.0.0.1:11111')
})
})
describe('BrowserWindow.show()', function () {
if (isCI) {
return
}
it('should focus on window', function () {
w.show()
assert(w.isFocused())
})
it('should make the window visible', function () {
w.show()
assert(w.isVisible())
})
it('emits when window is shown', function (done) {
this.timeout(10000)
w.once('show', function () {
assert.equal(w.isVisible(), true)
done()
})
w.show()
})
})
describe('BrowserWindow.hide()', function () {
if (isCI) {
return
}
it('should defocus on window', function () {
w.hide()
assert(!w.isFocused())
})
it('should make the window not visible', function () {
w.show()
w.hide()
assert(!w.isVisible())
})
it('emits when window is hidden', function (done) {
this.timeout(10000)
w.show()
w.once('hide', function () {
assert.equal(w.isVisible(), false)
done()
})
w.hide()
})
})
describe('BrowserWindow.showInactive()', function () {
it('should not focus on window', function () {
w.showInactive()
assert(!w.isFocused())
})
})
describe('BrowserWindow.focus()', function () {
it('does not make the window become visible', function () {
assert.equal(w.isVisible(), false)
w.focus()
assert.equal(w.isVisible(), false)
})
})
describe('BrowserWindow.blur()', function () {
it('removes focus from window', function () {
w.blur()
assert(!w.isFocused())
})
})
describe('BrowserWindow.capturePage(rect, callback)', function () {
it('calls the callback with a Buffer', function (done) {
w.capturePage({
x: 0,
y: 0,
width: 100,
height: 100
}, function (image) {
assert.equal(image.isEmpty(), true)
done()
})
})
})
describe('BrowserWindow.setSize(width, height)', function () {
it('sets the window size', function (done) {
var size = [300, 400]
w.once('resize', function () {
var newSize = w.getSize()
assert.equal(newSize[0], size[0])
assert.equal(newSize[1], size[1])
done()
})
w.setSize(size[0], size[1])
})
})
describe('BrowserWindow.setMinimum/MaximumSize(width, height)', function () {
it('sets the maximum and minimum size of the window', function () {
assert.deepEqual(w.getMinimumSize(), [0, 0])
assert.deepEqual(w.getMaximumSize(), [0, 0])
w.setMinimumSize(100, 100)
assert.deepEqual(w.getMinimumSize(), [100, 100])
assert.deepEqual(w.getMaximumSize(), [0, 0])
w.setMaximumSize(900, 600)
assert.deepEqual(w.getMinimumSize(), [100, 100])
assert.deepEqual(w.getMaximumSize(), [900, 600])
})
})
describe('BrowserWindow.setAspectRatio(ratio)', function () {
it('resets the behaviour when passing in 0', function (done) {
var size = [300, 400]
w.setAspectRatio(1 / 2)
w.setAspectRatio(0)
w.once('resize', function () {
var newSize = w.getSize()
assert.equal(newSize[0], size[0])
assert.equal(newSize[1], size[1])
done()
})
w.setSize(size[0], size[1])
})
})
describe('BrowserWindow.setPosition(x, y)', function () {
it('sets the window position', function (done) {
var pos = [10, 10]
w.once('move', function () {
var newPos = w.getPosition()
assert.equal(newPos[0], pos[0])
assert.equal(newPos[1], pos[1])
done()
})
w.setPosition(pos[0], pos[1])
})
})
describe('BrowserWindow.setContentSize(width, height)', function () {
it('sets the content size', function () {
var size = [400, 400]
w.setContentSize(size[0], size[1])
var after = w.getContentSize()
assert.equal(after[0], size[0])
assert.equal(after[1], size[1])
})
it('works for a frameless window', function () {
w.destroy()
w = new BrowserWindow({
show: false,
frame: false,
width: 400,
height: 400
})
var size = [400, 400]
w.setContentSize(size[0], size[1])
var after = w.getContentSize()
assert.equal(after[0], size[0])
assert.equal(after[1], size[1])
})
})
describe('BrowserWindow.setContentBounds(bounds)', function () {
it('sets the content size and position', function (done) {
var bounds = {x: 10, y: 10, width: 250, height: 250}
w.once('resize', function () {
assert.deepEqual(w.getContentBounds(), bounds)
done()
})
w.setContentBounds(bounds)
})
it('works for a frameless window', function (done) {
w.destroy()
w = new BrowserWindow({
show: false,
frame: false,
width: 300,
height: 300
})
var bounds = {x: 10, y: 10, width: 250, height: 250}
w.once('resize', function () {
assert.deepEqual(w.getContentBounds(), bounds)
done()
})
w.setContentBounds(bounds)
})
})
describe('BrowserWindow.setProgressBar(progress)', function () {
it('sets the progress', function () {
assert.doesNotThrow(function () {
if (process.platform === 'darwin') {
app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png'))
}
w.setProgressBar(0.5)
if (process.platform === 'darwin') {
app.dock.setIcon(null)
}
w.setProgressBar(-1)
})
})
})
describe('BrowserWindow.fromId(id)', function () {
it('returns the window with id', function () {
assert.equal(w.id, BrowserWindow.fromId(w.id).id)
})
})
describe('"useContentSize" option', function () {
it('make window created with content size when used', function () {
w.destroy()
w = new BrowserWindow({
show: false,
width: 400,
height: 400,
useContentSize: true
})
var contentSize = w.getContentSize()
assert.equal(contentSize[0], 400)
assert.equal(contentSize[1], 400)
})
it('make window created with window size when not used', function () {
var size = w.getSize()
assert.equal(size[0], 400)
assert.equal(size[1], 400)
})
it('works for a frameless window', function () {
w.destroy()
w = new BrowserWindow({
show: false,
frame: false,
width: 400,
height: 400,
useContentSize: true
})
var contentSize = w.getContentSize()
assert.equal(contentSize[0], 400)
assert.equal(contentSize[1], 400)
var size = w.getSize()
assert.equal(size[0], 400)
assert.equal(size[1], 400)
})
})
describe('"title-bar-style" option', function () {
if (process.platform !== 'darwin') {
return
}
if (parseInt(os.release().split('.')[0]) < 14) {
return
}
it('creates browser window with hidden title bar', function () {
w.destroy()
w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hidden'
})
var contentSize = w.getContentSize()
assert.equal(contentSize[1], 400)
})
it('creates browser window with hidden inset title bar', function () {
w.destroy()
w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hidden-inset'
})
var contentSize = w.getContentSize()
assert.equal(contentSize[1], 400)
})
})
describe('enableLargerThanScreen" option', function () {
if (process.platform === 'linux') {
return
}
beforeEach(function () {
w.destroy()
w = new BrowserWindow({
show: true,
width: 400,
height: 400,
enableLargerThanScreen: true
})
})
it('can move the window out of screen', function () {
w.setPosition(-10, -10)
var after = w.getPosition()
assert.equal(after[0], -10)
assert.equal(after[1], -10)
})
it('can set the window larger than screen', function () {
var size = screen.getPrimaryDisplay().size
size.width += 100
size.height += 100
w.setSize(size.width, size.height)
var after = w.getSize()
assert.equal(after[0], size.width)
assert.equal(after[1], size.height)
})
})
describe('"web-preferences" option', function () {
afterEach(function () {
ipcMain.removeAllListeners('answer')
})
describe('"preload" option', function () {
it('loads the script before other scripts in window', function (done) {
var preload = path.join(fixtures, 'module', 'set-global.js')
ipcMain.once('answer', function (event, test) {
assert.equal(test, 'preload')
done()
})
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
preload: preload
}
})
w.loadURL('file://' + path.join(fixtures, 'api', 'preload.html'))
})
})
describe('"node-integration" option', function () {
it('disables node integration when specified to false', function (done) {
var preload = path.join(fixtures, 'module', 'send-later.js')
ipcMain.once('answer', function (event, test) {
assert.equal(test, 'undefined')
done()
})
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
preload: preload,
nodeIntegration: false
}
})
w.loadURL('file://' + path.join(fixtures, 'api', 'blank.html'))
})
})
})
describe('beforeunload handler', function () {
it('returning undefined would not prevent close', function (done) {
w.once('closed', function () {
done()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'close-beforeunload-undefined.html'))
})
it('returning false would prevent close', function (done) {
w.once('onbeforeunload', function () {
done()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'close-beforeunload-false.html'))
})
it('returning empty string would prevent close', function (done) {
w.once('onbeforeunload', function () {
done()
})
w.loadURL('file://' + path.join(fixtures, 'api', 'close-beforeunload-empty-string.html'))
})
})
describe('new-window event', function () {
if (isCI && process.platform === 'darwin') {
return
}
it('emits when window.open is called', function (done) {
w.webContents.once('new-window', function (e, url, frameName) {
e.preventDefault()
assert.equal(url, 'http://host/')
assert.equal(frameName, 'host')
done()
})
w.loadURL('file://' + fixtures + '/pages/window-open.html')
})
it('emits when link with target is called', function (done) {
this.timeout(10000)
w.webContents.once('new-window', function (e, url, frameName) {
e.preventDefault()
assert.equal(url, 'http://host/')
assert.equal(frameName, 'target')
done()
})
w.loadURL('file://' + fixtures + '/pages/target-name.html')
})
})
describe('maximize event', function () {
if (isCI) {
return
}
it('emits when window is maximized', function (done) {
this.timeout(10000)
w.once('maximize', function () {
done()
})
w.show()
w.maximize()
})
})
describe('unmaximize event', function () {
if (isCI) {
return
}
it('emits when window is unmaximized', function (done) {
this.timeout(10000)
w.once('unmaximize', function () {
done()
})
w.show()
w.maximize()
w.unmaximize()
})
})
describe('minimize event', function () {
if (isCI) {
return
}
it('emits when window is minimized', function (done) {
this.timeout(10000)
w.once('minimize', function () {
done()
})
w.show()
w.minimize()
})
})
describe('beginFrameSubscription method', function () {
// This test is too slow, only test it on CI.
if (!isCI) return
this.timeout(20000)
it('subscribes to frame updates', function (done) {
let called = false
w.loadURL('file://' + fixtures + '/api/frame-subscriber.html')
w.webContents.on('dom-ready', function () {
w.webContents.beginFrameSubscription(function (data) {
// This callback might be called twice.
if (called) return
called = true
assert.notEqual(data.length, 0)
w.webContents.endFrameSubscription()
done()
})
})
})
it('subscribes to frame updates (only dirty rectangle)', function (done) {
let called = false
w.loadURL('file://' + fixtures + '/api/frame-subscriber.html')
w.webContents.on('dom-ready', function () {
w.webContents.beginFrameSubscription(true, function (data) {
// This callback might be called twice.
if (called) return
called = true
assert.notEqual(data.length, 0)
w.webContents.endFrameSubscription()
done()
})
})
})
it('throws error when subscriber is not well defined', function (done) {
w.loadURL('file://' + fixtures + '/api/frame-subscriber.html')
try {
w.webContents.beginFrameSubscription(true, true)
} catch (e) {
done()
}
})
})
describe('savePage method', function () {
const savePageDir = path.join(fixtures, 'save_page')
const savePageHtmlPath = path.join(savePageDir, 'save_page.html')
const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js')
const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css')
after(function () {
try {
fs.unlinkSync(savePageCssPath)
fs.unlinkSync(savePageJsPath)
fs.unlinkSync(savePageHtmlPath)
fs.rmdirSync(path.join(savePageDir, 'save_page_files'))
fs.rmdirSync(savePageDir)
} catch (e) {
// Ignore error
}
})
it('should save page to disk', function (done) {
w.webContents.on('did-finish-load', function () {
w.webContents.savePage(savePageHtmlPath, 'HTMLComplete', function (error) {
assert.equal(error, null)
assert(fs.existsSync(savePageHtmlPath))
assert(fs.existsSync(savePageJsPath))
assert(fs.existsSync(savePageCssPath))
done()
})
})
w.loadURL('file://' + fixtures + '/pages/save_page/index.html')
})
})
describe('BrowserWindow options argument is optional', function () {
it('should create a window with default size (800x600)', function () {
w.destroy()
w = new BrowserWindow()
var size = w.getSize()
assert.equal(size[0], 800)
assert.equal(size[1], 600)
})
})
describe('window states', function () {
describe('resizable state', function () {
it('can be changed with resizable option', function () {
w.destroy()
w = new BrowserWindow({show: false, resizable: false})
assert.equal(w.isResizable(), false)
if (process.platform === 'darwin') {
assert.equal(w.isMaximizable(), true)
}
})
it('can be changed with setResizable method', function () {
assert.equal(w.isResizable(), true)
w.setResizable(false)
assert.equal(w.isResizable(), false)
w.setResizable(true)
assert.equal(w.isResizable(), true)
})
})
describe('loading main frame state', function () {
it('is true when the main frame is loading', function (done) {
w.webContents.on('did-start-loading', function () {
assert.equal(w.webContents.isLoadingMainFrame(), true)
done()
})
w.webContents.loadURL(server.url)
})
it('is false when only a subframe is loading', function (done) {
w.webContents.once('did-finish-load', function () {
assert.equal(w.webContents.isLoadingMainFrame(), false)
w.webContents.on('did-start-loading', function () {
assert.equal(w.webContents.isLoadingMainFrame(), false)
done()
})
w.webContents.executeJavaScript(`
var iframe = document.createElement('iframe')
iframe.src = '${server.url}/page2'
document.body.appendChild(iframe)
`)
})
w.webContents.loadURL(server.url)
})
it('is true when navigating to pages from the same origin', function (done) {
w.webContents.once('did-finish-load', function () {
assert.equal(w.webContents.isLoadingMainFrame(), false)
w.webContents.on('did-start-loading', function () {
assert.equal(w.webContents.isLoadingMainFrame(), true)
done()
})
w.webContents.loadURL(`${server.url}/page2`)
})
w.webContents.loadURL(server.url)
})
})
})
describe('window states (excluding Linux)', function () {
// Not implemented on Linux.
if (process.platform === 'linux') return
describe('movable state', function () {
it('can be changed with movable option', function () {
w.destroy()
w = new BrowserWindow({show: false, movable: false})
assert.equal(w.isMovable(), false)
})
it('can be changed with setMovable method', function () {
assert.equal(w.isMovable(), true)
w.setMovable(false)
assert.equal(w.isMovable(), false)
w.setMovable(true)
assert.equal(w.isMovable(), true)
})
})
describe('minimizable state', function () {
it('can be changed with minimizable option', function () {
w.destroy()
w = new BrowserWindow({show: false, minimizable: false})
assert.equal(w.isMinimizable(), false)
})
it('can be changed with setMinimizable method', function () {
assert.equal(w.isMinimizable(), true)
w.setMinimizable(false)
assert.equal(w.isMinimizable(), false)
w.setMinimizable(true)
assert.equal(w.isMinimizable(), true)
})
})
describe('maximizable state', function () {
it('can be changed with maximizable option', function () {
w.destroy()
w = new BrowserWindow({show: false, maximizable: false})
assert.equal(w.isMaximizable(), false)
})
it('can be changed with setMaximizable method', function () {
assert.equal(w.isMaximizable(), true)
w.setMaximizable(false)
assert.equal(w.isMaximizable(), false)
w.setMaximizable(true)
assert.equal(w.isMaximizable(), true)
})
it('is not affected when changing other states', function () {
w.setMaximizable(false)
assert.equal(w.isMaximizable(), false)
w.setMinimizable(false)
assert.equal(w.isMaximizable(), false)
w.setClosable(false)
assert.equal(w.isMaximizable(), false)
w.setMaximizable(true)
assert.equal(w.isMaximizable(), true)
w.setClosable(true)
assert.equal(w.isMaximizable(), true)
w.setFullScreenable(false)
assert.equal(w.isMaximizable(), true)
w.setResizable(false)
assert.equal(w.isMaximizable(), true)
})
})
describe('fullscreenable state', function () {
// Only implemented on macOS.
if (process.platform !== 'darwin') return
it('can be changed with fullscreenable option', function () {
w.destroy()
w = new BrowserWindow({show: false, fullscreenable: false})
assert.equal(w.isFullScreenable(), false)
})
it('can be changed with setFullScreenable method', function () {
assert.equal(w.isFullScreenable(), true)
w.setFullScreenable(false)
assert.equal(w.isFullScreenable(), false)
w.setFullScreenable(true)
assert.equal(w.isFullScreenable(), true)
})
})
describe('closable state', function () {
it('can be changed with closable option', function () {
w.destroy()
w = new BrowserWindow({show: false, closable: false})
assert.equal(w.isClosable(), false)
})
it('can be changed with setClosable method', function () {
assert.equal(w.isClosable(), true)
w.setClosable(false)
assert.equal(w.isClosable(), false)
w.setClosable(true)
assert.equal(w.isClosable(), true)
})
})
describe('hasShadow state', function () {
// On Window there is no shadow by default and it can not be changed
// dynamically.
it('can be changed with hasShadow option', function () {
w.destroy()
let hasShadow = process.platform !== 'darwin'
w = new BrowserWindow({show: false, hasShadow: hasShadow})
assert.equal(w.hasShadow(), hasShadow)
})
it('can be changed with setHasShadow method', function () {
if (process.platform !== 'darwin') return
assert.equal(w.hasShadow(), true)
w.setHasShadow(false)
assert.equal(w.hasShadow(), false)
w.setHasShadow(true)
assert.equal(w.hasShadow(), true)
})
})
})
describe('parent window', function () {
let c = null
beforeEach(function () {
if (c != null) c.destroy()
c = new BrowserWindow({show: false, parent: w})
})
afterEach(function () {
if (c != null) c.destroy()
c = null
})
describe('parent option', function () {
it('sets parent window', function () {
assert.equal(c.getParentWindow(), w)
})
it('adds window to child windows of parent', function () {
assert.deepEqual(w.getChildWindows(), [c])
})
it('removes from child windows of parent when window is closed', function (done) {
c.once('closed', () => {
assert.deepEqual(w.getChildWindows(), [])
done()
})
c.close()
})
})
describe('win.setParentWindow(parent)', function () {
if (process.platform === 'win32') return
beforeEach(function () {
if (c != null) c.destroy()
c = new BrowserWindow({show: false})
})
it('sets parent window', function () {
assert.equal(w.getParentWindow(), null)
assert.equal(c.getParentWindow(), null)
c.setParentWindow(w)
assert.equal(c.getParentWindow(), w)
c.setParentWindow(null)
assert.equal(c.getParentWindow(), null)
})
it('adds window to child windows of parent', function () {
assert.deepEqual(w.getChildWindows(), [])
c.setParentWindow(w)
assert.deepEqual(w.getChildWindows(), [c])
c.setParentWindow(null)
assert.deepEqual(w.getChildWindows(), [])
})
it('removes from child windows of parent when window is closed', function (done) {
c.once('closed', () => {
assert.deepEqual(w.getChildWindows(), [])
done()
})
c.setParentWindow(w)
c.close()
})
})
describe('modal option', function () {
// The isEnabled API is not reliable on macOS.
if (process.platform === 'darwin') return
beforeEach(function () {
if (c != null) c.destroy()
c = new BrowserWindow({show: false, parent: w, modal: true})
})
it('disables parent window', function () {
assert.equal(w.isEnabled(), true)
c.show()
assert.equal(w.isEnabled(), false)
})
it('enables parent window when closed', function (done) {
c.once('closed', () => {
assert.equal(w.isEnabled(), true)
done()
})
c.show()
c.close()
})
it('disables parent window recursively', function () {
let c2 = new BrowserWindow({show: false, parent: w, modal: true})
c.show()
assert.equal(w.isEnabled(), false)
c2.show()
assert.equal(w.isEnabled(), false)
c.destroy()
assert.equal(w.isEnabled(), false)
c2.destroy()
assert.equal(w.isEnabled(), true)
})
})
})
describe('window.webContents.send(channel, args...)', function () {
it('throws an error when the channel is missing', function () {
assert.throws(function () {
w.webContents.send()
}, 'Missing required channel argument')
assert.throws(function () {
w.webContents.send(null)
}, 'Missing required channel argument')
})
})
describe('dev tool extensions', function () {
describe('BrowserWindow.addDevToolsExtension', function () {
let showPanelIntevalId
this.timeout(10000)
beforeEach(function () {
BrowserWindow.removeDevToolsExtension('foo')
assert.equal(BrowserWindow.getDevToolsExtensions().hasOwnProperty('foo'), false)
var extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'foo')
BrowserWindow.addDevToolsExtension(extensionPath)
assert.equal(BrowserWindow.getDevToolsExtensions().hasOwnProperty('foo'), true)
w.webContents.on('devtools-opened', function () {
showPanelIntevalId = setInterval(function () {
if (w && w.devToolsWebContents) {
var showLastPanel = function () {
var lastPanelId = WebInspector.inspectorView._tabbedPane._tabs.peekLast().id
WebInspector.inspectorView.showPanel(lastPanelId)
}
w.devToolsWebContents.executeJavaScript(`(${showLastPanel})()`)
} else {
clearInterval(showPanelIntevalId)
}
}, 100)
})
w.loadURL('about:blank')
})
afterEach(function () {
clearInterval(showPanelIntevalId)
})
it('throws errors for missing manifest.json files', function () {
assert.throws(function () {
BrowserWindow.addDevToolsExtension(path.join(__dirname, 'does-not-exist'))
}, /ENOENT: no such file or directory/)
})
it('throws errors for invalid manifest.json files', function () {
assert.throws(function () {
BrowserWindow.addDevToolsExtension(path.join(__dirname, 'fixtures', 'devtools-extensions', 'bad-manifest'))
}, /Unexpected token }/)
})
describe('when the devtools is docked', function () {
it('creates the extension', function (done) {
w.webContents.openDevTools({mode: 'bottom'})
ipcMain.once('answer', function (event, message) {
assert.equal(message.runtimeId, 'foo')
assert.equal(message.tabId, w.webContents.id)
assert.equal(message.i18nString, 'foo - bar (baz)')
assert.deepEqual(message.storageItems, {
local: {hello: 'world'},
sync: {foo: 'bar'}
})
done()
})
})
})
describe('when the devtools is undocked', function () {
it('creates the extension', function (done) {
w.webContents.openDevTools({mode: 'undocked'})
ipcMain.once('answer', function (event, message, extensionId) {
assert.equal(message.runtimeId, 'foo')
assert.equal(message.tabId, w.webContents.id)
done()
})
})
})
})
it('works when used with partitions', function (done) {
this.timeout(10000)
if (w != null) {
w.destroy()
}
w = new BrowserWindow({
show: false,
webPreferences: {
partition: 'temp'
}
})
var extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'foo')
BrowserWindow.removeDevToolsExtension('foo')
BrowserWindow.addDevToolsExtension(extensionPath)
w.webContents.on('devtools-opened', function () {
var showPanelIntevalId = setInterval(function () {
if (w && w.devToolsWebContents) {
var showLastPanel = function () {
var lastPanelId = WebInspector.inspectorView._tabbedPane._tabs.peekLast().id
WebInspector.inspectorView.showPanel(lastPanelId)
}
w.devToolsWebContents.executeJavaScript(`(${showLastPanel})()`)
} else {
clearInterval(showPanelIntevalId)
}
}, 100)
})
w.loadURL('about:blank')
w.webContents.openDevTools({mode: 'bottom'})
ipcMain.once('answer', function (event, message) {
assert.equal(message.runtimeId, 'foo')
done()
})
})
it('serializes the registered extensions on quit', function () {
var extensionName = 'foo'
var extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', extensionName)
var serializedPath = path.join(app.getPath('userData'), 'DevTools Extensions')
BrowserWindow.addDevToolsExtension(extensionPath)
app.emit('will-quit')
assert.deepEqual(JSON.parse(fs.readFileSync(serializedPath)), [extensionPath])
BrowserWindow.removeDevToolsExtension(extensionName)
app.emit('will-quit')
assert.equal(fs.existsSync(serializedPath), false)
})
})
describe('window.webContents.executeJavaScript', function () {
var expected = 'hello, world!'
var code = '(() => "' + expected + '")()'
it('doesnt throw when no calback is provided', function () {
const result = ipcRenderer.sendSync('executeJavaScript', code, false)
assert.equal(result, 'success')
})
it('returns result when calback is provided', function (done) {
ipcRenderer.send('executeJavaScript', code, true)
ipcRenderer.once('executeJavaScript-response', function (event, result) {
assert.equal(result, expected)
done()
})
})
it('works after page load and during subframe load', function (done) {
w.webContents.once('did-finish-load', function () {
// initiate a sub-frame load, then try and execute script during it
w.webContents.executeJavaScript(`
var iframe = document.createElement('iframe')
iframe.src = '${server.url}/slow'
document.body.appendChild(iframe)
`, function () {
w.webContents.executeJavaScript('console.log(\'hello\')', function () {
done()
})
})
})
w.loadURL(server.url)
})
it('executes after page load', function (done) {
w.webContents.executeJavaScript(code, function (result) {
assert.equal(result, expected)
done()
})
w.loadURL(server.url)
})
})
describe('offscreen rendering', function () {
this.timeout(10000)
beforeEach(function () {
if (w != null) w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
backgroundThrottling: false,
offscreen: true
}
})
})
it('creates offscreen window', function (done) {
w.webContents.once('paint', function (event, rect, data, size) {
assert.notEqual(data.length, 0)
done()
})
w.loadURL('file://' + fixtures + '/api/offscreen-rendering.html')
})
describe('window.webContents.isOffscreen()', function () {
it('is true for offscreen type', function () {
w.loadURL('file://' + fixtures + '/api/offscreen-rendering.html')
assert.equal(w.webContents.isOffscreen(), true)
})
it('is false for regular window', function () {
let c = new BrowserWindow({show: false})
assert.equal(c.webContents.isOffscreen(), false)
c.destroy()
})
})
describe('window.webContents.isPainting()', function () {
it('returns whether is currently painting', function (done) {
w.webContents.once('paint', function (event, rect, data, size) {
assert.equal(w.webContents.isPainting(), true)
done()
})
w.loadURL('file://' + fixtures + '/api/offscreen-rendering.html')
})
})
describe('window.webContents.stopPainting()', function () {
it('stops painting', function (done) {
w.webContents.on('dom-ready', function () {
w.webContents.stopPainting()
assert.equal(w.webContents.isPainting(), false)
done()
})
w.loadURL('file://' + fixtures + '/api/offscreen-rendering.html')
})
})
describe('window.webContents.startPainting()', function () {
it('starts painting', function (done) {
w.webContents.on('dom-ready', function () {
w.webContents.stopPainting()
w.webContents.startPainting()
w.webContents.once('paint', function (event, rect, data, size) {
assert.equal(w.webContents.isPainting(), true)
done()
})
})
w.loadURL('file://' + fixtures + '/api/offscreen-rendering.html')
})
})
describe('window.webContents.getFrameRate()', function () {
it('has default frame rate', function (done) {
w.webContents.once('paint', function (event, rect, data, size) {
assert.equal(w.webContents.getFrameRate(), 60)
done()
})
w.loadURL('file://' + fixtures + '/api/offscreen-rendering.html')
})
})
describe('window.webContents.setFrameRate(frameRate)', function () {
it('sets custom frame rate', function (done) {
w.webContents.on('dom-ready', function () {
w.webContents.setFrameRate(30)
w.webContents.once('paint', function (event, rect, data, size) {
assert.equal(w.webContents.getFrameRate(), 30)
done()
})
})
w.loadURL('file://' + fixtures + '/api/offscreen-rendering.html')
})
})
})
})
|
var terms;
var categories;
var series;
function parseQueryString() {
var query = (location.search || '?').substr(1),
map = {};
query.replace(/([^&=]+)=?([^&]*)(?:&+|$)/g, function(match, key, value) {
if (key.match(/compare[1-4]/gi)) {
(map[key] = map[key] || []).push(decodeURIComponent(value.replace( /\+/g, '%20' )));
}
});
return map;
}
var highChartConverter = (function ( $ ) {
return {
convertCategories: function () {
// initialize xaxis categories (months)
var months = [];
$.map(data, function ( datapoint, i ) {
months.push(datapoint["month"]);
});
return months;
},
convertSeries: function () {
// initialize series data
var series = [];
$.map(terms, function ( term, i ) {
var term_data = { "name": term, "data": [], "total_mentions": 0 }
// build data
$.map(data, function ( datapoint, i ) {
term_data["data"].push( datapoint["terms"][term]["percentage"] );
term_data["total_mentions"] += datapoint["terms"][term]["count"];
});
// calculate YOY change
var first = term_data["data"][term_data["data"].length-13];
var last = term_data["data"][term_data["data"].length-1]
// assign a floor to have more meaningful change calculation
if (first == 0) {
first = 1;
}
if (last == 0) {
last = 1;
}
term_data["change"] = (last - first) / first;
term_data["latest_mentions"] = last;
series.push(term_data);
});
return series;
}
}
}) ( jQuery );
var chartBuilder = (function ( $ ) {
function render( seriesData ) {
$('#chart').highcharts({
chart: {
type: 'line'
},
title: {
text: ''
},
xAxis: {
categories: categories,
labels: {
step: 3,
staggerLines: 1
}
},
yAxis: {
title: {
text: 'Percentage of posts'
},
min: 0
},
tooltip: {
},
series: seriesData
});
}
return {
renderTopTerms: function( numTerms ) {
render( series.slice( 0, numTerms ) );
},
renderComparison: function() {
var compareTerms = [];
var compareSeries = [];
$(".term-compare").each ( function ( i, val ) {
compareTerms.push( val.value.toLowerCase() );
});
$.each(series, function ( i, val) {
if ( $.inArray(val.name.toLowerCase(), compareTerms) > -1 ) {
compareSeries.push( val );
}
});
render( compareSeries );
}
}
}) ( jQuery );
$(function () {
data.reverse();
terms = Object.keys( data[0]["terms"] );
// transform raw data in to format consumable by highcharts
categories = highChartConverter.convertCategories();
series = highChartConverter.convertSeries();
// sort by cumulative popularity
series.sort(function(a,b){ return b.latest_mentions - a.latest_mentions });
// wire up top terms filter
$( "#topfilter" ).on( "change", function ( e ) {
chartBuilder.renderTopTerms( parseInt($(this).val()) );
});
// process url parameters if present
var urlParams = parseQueryString();
if ( Object.keys( urlParams ).length > 0 ) {
for (var term in urlParams) {
$("input[name=" + term + "]").val( urlParams[term] );
}
chartBuilder.renderComparison();
} else {
chartBuilder.renderTopTerms( 5 );
}
// populate rising/falling tables
// tableBuilder.renderTopTerms();
// tableBuilder.renderRising();
// tableBuilder.renderFalling();
// wire up autocomplete
$( ".term-compare" ).autocomplete({
source: terms
});
});
|
export default function(fn) {
return 'foo ' + fn();
}
|
$(document).ready(function(){
$("#room_black_bar").on("mouseover", function() {
$("#room_black_bar").animate({"padding-top": "-10em"},600);
$("#room_black_bar").animate({"margin-top": "12em"},600);
})
$("#room_black_bar").on("mouseleave", function() {
$("#room_black_bar").animate({"padding-top": "10em"},600);
$("#room_black_bar").animate({"margin-top": "23em"},600);
})
})
|
/**
* @file SpinningShapes.js
* @brief Makes spining shapes
*
* Creates a canvas with spinning Shapes inside a container div.
*/
/**
* @Class SpinningShapes
* @brief Some brief description.
*
*
*
*/
function SpinningShapes() {
'use strict';
//Holds the canvas element that the shapes are displayed on
this.canvas;
//Holds the 2D context of the canvas element
this.context;
//This array holds all the shapes
this.shapes = [];
//Stores the number of x and y shapes
this.xShapes = 0;
this.yShapes = 0;
//size of the grids that the shapes are drawn in
this.gridSize = 0;
//Store the pattern of shapes
this.pattern = [];
//Store Shape types with their draw functions
this.shapeType = {};
}
SpinningShapes.prototype.init = function init(target, xShapes, yShapes, pattern) {
'use strict';
//initialize canvas element and append it to targeted element
this.canvas = document.createElement('canvas');
this.canvas.width = target.offsetWidth;
this.canvas.height = target.offsetHeight;
this.context = this.canvas.getContext('2d');
target.appendChild(this.canvas);
this.xShapes = xShapes;
this.yShapes = yShapes;
this.gridSize = this.calculateGridSize();
this.pattern = pattern;
this.createDefaultshapeTypes();
this.createShapes();
window.requestAnimationFrame(this.mainLoop.bind(this));
}
SpinningShapes.prototype.addshapeType = function addshapeType(objectName, drawFunction) {
'use strict';
this.shapeType[objectName] = {
draw: drawFunction,
drawCache: 'uninitialized',
drawCacheContext: 'uninitialized',
gridSize: 0
};
}
SpinningShapes.prototype.createDefaultshapeTypes = function createDefaultshapeTypes() {
'use strict';
this.addshapeType('circle', function drawCircle(context, gridSize, x, y, rotation, color) {
if(this.drawCache === 'uninitialized') {
this.drawCache = document.createElement('canvas');
this.drawCacheContext = this.drawCache.getContext('2d');
}
if(this.gridSize !== gridSize) {
this.gridSize = this.drawCache.width = this.drawCache.height = gridSize;
this.drawCacheContext.clearRect(0, 0, gridSize, gridSize);
this.drawCacheContext.save();
this.drawCacheContext.translate(gridSize/2, gridSize/2);
this.drawCacheContext.beginPath();
this.drawCacheContext.fillStyle = color;
this.drawCacheContext.arc(0, 0, gridSize/10, 0, 2 * Math.PI);
this.drawCacheContext.closePath();
this.drawCacheContext.fill();
this.drawCacheContext.restore();
}
context.drawImage(this.drawCache, x * gridSize, y * gridSize)
});
this.addshapeType('diamond', function drawDiamond(context, gridSize, x, y, rotation, color) {
if(this.drawCache === 'uninitialized') {
this.drawCache = document.createElement('canvas');
this.drawCacheContext = this.drawCache.getContext('2d');
}
if(this.gridSize !== gridSize) {
this.gridSize = this.drawCache.width = this.drawCache.height = gridSize;
this.drawCacheContext.clearRect(0, 0, gridSize, gridSize);
this.drawCacheContext.save();
this.drawCacheContext.translate(gridSize/2, gridSize/2);
this.drawCacheContext.beginPath();
this.drawCacheContext.fillStyle = color;
this.drawCacheContext.moveTo(0, -gridSize/15);
this.drawCacheContext.lineTo(gridSize/4, 0);
this.drawCacheContext.lineTo(0, gridSize/15);
this.drawCacheContext.lineTo(-gridSize/4, 0);
this.drawCacheContext.closePath();
this.drawCacheContext.fill();
this.drawCacheContext.restore();
}
context.save();
context.translate(x * gridSize + gridSize/2, y * gridSize + gridSize/2);
context.rotate(rotation * Math.PI / 180);
context.drawImage(this.drawCache, -gridSize/2, -gridSize/2)
context.restore();
});
}
SpinningShapes.prototype.createShapes = function createShapes() {
'use strict';
for(var y=0; y-2 < this.yShapes; ++y) {
for(var x=0; x-2 < this.xShapes; ++x) {
this.createShape(this.selectShapeType(x, y), x, y);
}
}
}
SpinningShapes.prototype.createShape = function createShape(shapeType, posX, posY) {
'use strict';
this.shapes.push({
shapeType: shapeType,
x: posX,
y: posY,
angle: 0,
rotationSpeed: ((Math.random() * 0.125) - 0.0625) + ((Math.random() * 0.125) - 0.0625)
});
}
SpinningShapes.prototype.selectShapeType = function selectShapeType(x, y) {
'use strict';
return this.pattern[((x + y) % this.pattern.length)];
}
SpinningShapes.prototype.updateShapes = function updateShapes() {
'use strict';
for(var i=0; i < this.shapes.length; ++i){
this.shapes[i].angle = (this.shapes[i].angle + this.shapes[i].rotationSpeed) % 360;
}
}
SpinningShapes.prototype.drawShapes = function drawShapes() {
'use strict';
for(var i=0; i < this.shapes.length; ++i){
this.shapeType[this.shapes[i].shapeType].draw(this.context,
this.gridSize,
this.shapes[i].x,
this.shapes[i].y,
this.shapes[i].angle,
'#222'
);
}
}
SpinningShapes.prototype.calculateGridSize = function calculateGridSize() {
'use strict';
return this.canvas.offsetWidth / this.xShapes;
}
SpinningShapes.prototype.render = function render() {
'use strict';
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.context.save();
this.context.translate(-this.gridSize, -this.gridSize);
this.drawShapes();
this.context.restore();
}
SpinningShapes.prototype.mainLoop = function mainLoop() {
'use strict';
//
this.updateShapes();
this.render();
//begin loop each frame
window.requestAnimationFrame(this.mainLoop.bind(this));
}
|
/**
* @author Charlie Calvert
* Developed in class, Prog 272, Feb 14, 2013
*/
function changer() {
var divId = $('#select01 option:selected').attr("data-divIndex");
$("#data01").load("data.html #" + divId);
}
$(document).ready(function() {"use strict";
$("#test01").html("It works");
$("#data01").load("data.html #div01");
$("#select01").on("change", changer);
}); |
"use strict";
/**
* @param {String} [stores[].action=*] - A user specified store action or all actions.
*/
module.exports = {
"actions": {
"onCollectionRefreshIfChanged": {
"path": [
"collection"
],
"handler": {
"lib": "queryHandlers",
"actions": {
"query": "getQuery"
}
}
},
"onCollectionRefresh": {
"path": [
"collection"
],
"handler": {
"lib": "queryHandlers",
"actions": {
"query": "getQuery"
}
}
},
"onCollectionPropChange": {
"path": [
"collection"
],
"handler": {
"lib": "queryHandlers",
"actions": {
"query": "query"
}
}
},
"onCollectionFilterChange": {
"path": [
"collection"
],
"handler": {
"lib": "queryHandlers",
"actions": {
"query": "query"
}
}
},
"onCollectionEditableTableFilterChange": {
"path": [
"collection"
],
"handler": {
"lib": "queryHandlers",
"actions": {
"query": "query"
}
}
},
"getQuery": {
"preRequestHandlers": [
{
"lib": "queryHandlers",
"fn": "preRequestHandler"
}
],
"progressFlag": [
"collection",
"loading"
],
"handlerRequest": {
"serverModel": "QueryTableModel",
"property": "query",
"data": {
"tableModelIds": [
"collection",
"tableModelIds"
],
"filterName": [
"collection",
"filterName"
],
"serviceRole": [
"collection",
"serviceRole"
],
"page": [
"collection",
"page"
],
"pageSize": [
"collection",
"pageSize"
],
"userModelId": [
"stores",
"userModelUI-upsert-user",
"props",
"id"
],
"subFilterId": [
"collection",
"subFilterId"
]
}
},
"handlerResponse": {
},
"postResponseHandlers": [
{
"lib": "queryHandlers",
"fn": "postResponseHandler"
}
]
},
"getQueryPage": {
"preRequestHandlers": [
{
"lib": "queryHandlers",
"fn": "preRequestHandler"
}
],
"progressFlag": [
"collection",
"loading"
],
"handlerRequest": {
"serverModel": "QueryTableModel",
"property": "query",
"data": {
"tableModelIds": [
"collection",
"tableModelIds"
],
"filterName": [
"collection",
"filterName"
],
"serviceRole": [
"collection",
"serviceRole"
],
"page": [
"collection",
"page"
],
"pageSize": [
"collection",
"pageSize"
],
"view": [
"collection",
"view"
],
"userModelId": [
"stores",
"userModelUI-upsert-user",
"props",
"id"
],
"subFilterId": [
"collection",
"subFilterId"
]
}
},
"handlerResponse": {
},
"postResponseHandlers": [
{
"lib": "queryHandlers",
"fn": "postResponseHandler"
}
]
},
"query": {
"preRequestHandlers": [
{
"lib": "queryHandlers",
"fn": "preRequestHandler"
}
],
"progressFlag": [
"collection",
"loading"
],
"handlerRequest": {
"serverModel": "QueryTableModel",
"property": "query",
"data": {
"tableModelIds": [
"collection",
"tableModelIds"
],
"filterName": [
"collection",
"filterName"
],
"filter": [
"collection",
"filter"
],
"account": [
"collection",
"account"
],
"serviceRole": [
"collection",
"serviceRole"
],
"chart": [
"collection",
"chart"
],
"locked": [
"collection",
"locked"
],
"pageSize": [
"collection",
"pageSize"
],
"page": [
"collection",
"page"
],
"view": [
"collection",
"view"
],
"userModelId": [
"stores",
"userModelUI-upsert-user",
"props",
"id"
],
"subFilterId": [
"collection",
"subFilterId"
]
}
},
"handlerResponse": {
},
"postResponseHandlers": [
{
"lib": "queryHandlers",
"fn": "postResponseHandler"
}
]
},
"csvExportAll": {
"handlerRequest": {
"serverModel": "QueryTableModel",
"property": "postExportQuery",
"data": {
"tableModelIds": [
"collection",
"tableModelIds"
],
"filterName": [
"collection",
"filterName"
],
"serviceRole": [
"collection",
"serviceRole"
],
"exportType": "CSV_ALL",
"page": [
"collection",
"page"
],
"exportOptions": [
"collection",
"exportOptions"
],
"subFilterId": [
"collection",
"subFilterId"
]
}
},
"handlerResponse": {
"responseMessages": {
"200": "Successfully started export. You will receive an email when the export is ready for download.",
"400": "There was a problem starting the export. Please try again.",
"401": "You are not authorised to schedule the export.",
"403": []
}
}
},
"pdfExportAll": {
"handlerRequest": {
"serverModel": "QueryTableModel",
"property": "postExportQuery",
"data": {
"tableModelIds": [
"collection",
"tableModelIds"
],
"filterName": [
"collection",
"filterName"
],
"serviceRole": [
"collection",
"serviceRole"
],
"exportType": "PDF_ALL",
"page": [
"collection",
"page"
],
"exportOptions": [
"collection",
"exportOptions"
],
"subFilterId": [
"collection",
"subFilterId"
]
}
},
"handlerResponse": {
"responseMessages": {
"200": "Successfully started export. You will receive an email when the export is ready for download.",
"400": "There was a problem starting the export. Please try again.",
"401": "You are not authorised to schedule the export.",
"403": []
}
}
},
"deleteQuery": {
"progressFlag": [
"collection",
"loading"
],
"handlerRequest": {
"serverModel": "QueryTableModel",
"property": "deleteQuery",
"data": {
"tableModelIds": [
"collection",
"tableModelIds"
],
"filterName": [
"collection",
"filterName"
],
"account": [
"collection",
"account"
],
"serviceRole": [
"collection",
"serviceRole"
],
"userModelId": [
"stores",
"userModelUI-upsert-user",
"props",
"id"
]
}
},
"handlerResponse": {
},
"postResponseHandlers": [
{
"lib": "queryHandlers",
"fn": "postResponseHandler"
}
]
}
},
"collection": {
"addFilterFlag": false,
"editFilterFlag": false,
"editableFilter": false,
"editableAccountFilter": false,
"customisable": null,
"exportable": null,
"views": null,
"view": null,
"chart": {},
"labelColumnSpec": null,
"pictureColumnSpec": null,
"name": null,
"icon": null,
"label": null,
"activeFilter": null,
"filterModel": {
"_modelTemplate": {
"name": null,
"value": [],
"label": "",
"help": "",
"description": "",
"validation": {},
"error": "",
"showValidating": false,
"asyncValidationError": false,
"showError": false,
"touched": false,
"hide": false,
"disabled": false,
"relation": false
},
"_filterName": {
"name": "_filterName",
"value": null,
"label": "Filter name",
"help": "Enter filter name",
"description": "The filter name",
"validation": {},
"error": "",
"showValidating": false,
"asyncValidationError": false,
"showError": false,
"touched": false,
"hide": false,
"disabled": false,
"relation": false
},
"_account": {
"name": "_account",
"value": null,
"label": "Set as default tab for all users",
"help": "Set as default tab for all users",
"description": "Set as default tab for all users",
"validation": {},
"error": "",
"showValidating": false,
"asyncValidationError": false,
"showError": false,
"touched": false,
"hide": false,
"disabled": false,
"relation": false
},
"_locked": {
"name": "_locked",
"value": null,
"label": "Prevent users editing filter",
"help": "Lock the filter from editing by users without the Administrator role",
"description": "Lock the filter from editing by users without the Administrator role",
"validation": {},
"error": "",
"showValidating": false,
"asyncValidationError": false,
"showError": false,
"touched": false,
"hide": false,
"disabled": false,
"relation": false
},
"_updatedFilter": {
"name": "_updatedFilter",
"value": [],
"label": "Column selector",
"help": "Column selector",
"description": "Column selector",
"validation": {
"type": "object",
"required": false
},
"groups": [],
"records": [],
"error": "",
"showValidating": false,
"asyncValidationError": false,
"showError": false,
"touched": false,
"hide": false,
"disabled": false,
"relation": false
}
},
"tableModelIds": null,
"querySpecs": null,
"filterName": "",
"filterUpdate": null,
"filter": null,
"subFilterId": null,
"account": false,
"serviceRole": null,
"locked": false,
"records": null,
"recordCount": 0,
"selectedAll": false,
"page": null,
"pageSize": null,
"exportCounter": 0,
"refreshCounter": 0,
"displayMode": "query",
"syncWithRecords": false
}
};
|
/*
* pull page to other one (project qdplus)
* Date:2014-02-25
*/
;(function($) {
$.fn.mobileScroll = function(options) {
$.fn.mobileScroll.defaults = {
autohide : true,
wheelctl : true,
mousectl : true
};
var opts = $.extend({}, $.fn.mobileScroll.defaults, options);
var scrollbar = $(this);
var handle = scrollbar.children(".handle");
var _content = $("body");
var _container = $(window);
var bar_width = scrollbar.width();
// check position
var checkPos = function(dom, _y){
var pos_top = handle.position().top;
if(pos_top <= 0 && (_y === undefined || _y < 0)) {
handle.css("top", 0);
return false;
}
var maxTop = scrollbar.height() - handle.height();
if(pos_top >= maxTop && (_y === undefined || _y > 0)) {
handle.css("top", maxTop);
return false;
}
return true;
}
// click, record mouse position
if (opts.mousectl) {
handle.mousedown(function(event) {
handle.data("_drag", 1);
handle.data("_offset", handle.position());
handle.data("_mouseY", event.pageY - _container.scrollTop());
})
// release
.mouseup(function() {
handle.data("_drag", 0);
checkPos();
})
// moveout
.mouseout(function() {
handle.data("_drag", 0);
checkPos();
})
// move
.mousemove(function(event) {
if (handle.data("_drag") == 1) {
var old_offset = handle.data("_offset");
var mousemoveY = event.pageY - handle.data("_mouseY") - _container.scrollTop();
var top = old_offset.top + mousemoveY;
if (!checkPos(this, mousemoveY)) return;
// get value
var contentH = Math.max(window.document.documentElement.scrollHeight, window.document.body.scrollHeight);
var paneH = _container.height();
var handleH = handle.height();
var rangeH = scrollbar.height() - handleH;
// move
handle.css({top:top});
var pos_top = handle.position().top;
if (pos_top <= 0) pos_top = 0;
else if(pos_top >= rangeH) pos_top = rangeH;
var content_top = pos_top * (contentH - paneH) / rangeH;
// record value
handle.data("_offset", handle.position());
handle.data("_mouseY", event.pageY - _container.scrollTop());
_container.scrollTop(content_top);
handle.focus();
}
});
}
// auto show/hide
if (opts.autohide) {
handle.delay(2000).animate({left:bar_width+"px"}, 100);
scrollbar.mouseover(function(){
handle.stop(true).animate({left:"0px"}, 100);
});
scrollbar.mouseout(function(){
handle.delay(2000).animate({left:bar_width+"px"}, 100);
});
}
// scroll by wheel
if (opts.wheelctl) {
var wheel = function(event){
var delta = 0;
if (!event) /* For IE. */
event = window.event;
if (event.wheelDelta) { /* IE/Opera. */
delta = event.wheelDelta / 120;
} else if (event.detail) {
delta = -event.detail / 3;
}
//Scroll dom
if (delta){
//Scroll to
var t = $(window).scrollTop();
t -= delta * 100;
$(window).scrollTop(t);
}
scrollbar.get(0).reloadScrollHeight();
if (opts.autohide)
handle.stop(true).animate({left:"0px"}, 100).delay(2000).animate({left:bar_width+"px"}, 100);
if (event.preventDefault)
event.preventDefault();
event.returnValue = false;
}
if (window.addEventListener) {
/* DOMMouseScroll is for mozilla. */
window.addEventListener('DOMMouseScroll', wheel, false);
}
/* IE/Opera. */
if(window.onmousewheel)
window.onmousewheel = wheel;
else
document.onmousewheel = wheel;
}
// add listener
this[0].reloadScrollHeight = function() {
var h = Math.max(window.document.documentElement.scrollHeight, window.document.body.scrollHeight);
if( h == _container.height() ) {
scrollbar.hide();
return;
}
scrollbar.show();
// size;
scrollbar.height(_container.height());
handle.height(_container.height() * _container.height() / h);
// top;
var paneH = _container.height();
var handleH = handle.height();
var rangeH = scrollbar.height() - handleH;
var top = _content.scrollTop() * rangeH / (h - paneH);
handle.css("top", top);
}
this[0].reloadScrollHeight();
return this;
}
})(jQuery);
|
/*
* This file can be used for general library features of gom.
*
* The library features can be made available as CommonJS modules that the
* components in this project utilize.
*/
if (typeof process !== 'undefined' && process.execPath && process.execPath.indexOf('node') !== -1) {
require('coffee-script/register');
}
module.exports = require('./lib/GOM');
|
app.view.Viewport = class extends app.toolkit.three.R {
config() {
return {
planetSpecs: [
{type: app.view.milkyway.Planet, size: 1 / 2.54, distance: 0.4, period: 0.24, map: metadata.urls.mercury.surfaceMaterial },
{type: app.view.milkyway.Planet, size: 1 / 1.05, distance: 0.7, period: 0.62, map: metadata.urls.venus.surfaceMaterial },
{type: app.view.milkyway.earth.Earth, size: 1, distance: 1, period: 1, map: metadata.urls.earth.surfaceMaterial },
{type: app.view.milkyway.Planet, size: 1 / 1.88, distance: 1.6, period: 1.88, map: metadata.urls.mars.surfaceMaterial},
{type: app.view.milkyway.Planet, size: 2.7, distance: 2.6, period: 2, map: metadata.urls.jupiter.surfaceMaterial},
{type: app.view.milkyway.saturn.Saturn, size: 2.14, distance: 5, period: 3, map: metadata.urls.saturn.surfaceMaterial},
{type: app.view.milkyway.Planet, size: 1, distance: 9.8, period: 4, map: metadata.urls.uranus.surfaceMaterial},
{type: app.view.milkyway.Planet, size: 1.94, distance: 19.4, period: 5, map: metadata.urls.neptune.surfaceMaterial},
{type: app.view.milkyway.Planet,size: 10 / 5.55, distance: 38.6, period: 6, map: metadata.urls.pluto.surfaceMaterial }
],
mouseDown: function (x, y) {
this.lastX = x;
this.lastY = y;
this.mouseDown = true;
},
mouseUp: function (x, y) {
this.lastX = x;
this.lastY = y;
this.mouseDown = false;
},
mouseMove: function (x, y) {
if (this.mouseDown) {
let dx = x - this.lastX;
if (Math.abs(dx) > metadata.constants.MOUSE_MOVE_TOLERANCE) {
this.root.rotation.y -= (dx * 0.01);
}
this.lastX = x;
}
},
mouseScroll: function (delta) {
let dx = delta;
this.camera.position.z -= dx;
if (this.camera.position.z < metadata.constants.MIN_CAMERA_Z)
this.camera.position.z = metadata.constants.MIN_CAMERA_Z;
if (this.camera.position.z > metadata.constants.MAX_CAMERA_Z)
this.camera.position.z = metadata.constants.MAX_CAMERA_Z;
}
}
}
constructor(config) {
super(config);
this._planetSpecs = config && config.hasOwnProperty('planetSpecs') ? config.planets : this.config().planetSpecs;
this._lastX = config && config.hasOwnProperty('lastX') ? config.lastX : this.config().lastX;
this._lastY = config && config.hasOwnProperty('lastY') ? config.lastY : this.config().lastY;
this._planets = [];
this._orbits = [];
this._mouseDown = false;
}
get planetSpecs() {
return this._planetSpecs;
}
get planets() {
return this._planets;
}
get sun() {
return this._sun;
}
get orbits() {
return this._orbits;
}
get lastX() {
return this._lastX;
}
set lastX(x) {
this._lastX = x;
}
get lastY() {
return this._lastY;
}
set lastY(y) {
this._lastY = y;
}
get mouseDown() {
return this._mouseDown;
}
set mouseDown(val) {
this._mouseDown = val;
}
addOrbits() {
let me = this;
this.orbits.forEach(function(orbit){
me.addObject(orbit);
});
this._orbits = [];
}
updateCamera() {
let newposZ = this.camera.position.z - 1;
new TWEEN.Tween(this.camera.position)
.to({
z: newposZ
}, 10).start();
}
isCameraPositionFinal() {
return this.camera.position.z <= (metadata.constants.SUN_SIZE_IN_EARTHS * 10);
}
rotateRoot() {
let deltaX = (Math.PI / 8) / 4,
newRotationX = this.root.rotation.x + deltaX;
new TWEEN.Tween(this.root.rotation)
.to({
x: newRotationX
}, 100).start();
}
isRootRotationFinal() {
return this.root.rotation.x >= (Math.PI / 8);
}
update() {
TWEEN.update();
let hiddenPlanets = this.planets.filter(function(planet) {
return planet.planetGroup.position.y > 0;
});
if(this.sun.object3D.position.y <= 0) {
if(hiddenPlanets.length) {
hiddenPlanets[0].animate();
} else if(this.orbits.length) {
this.addOrbits();
} else if(!this.isCameraPositionFinal()) {
this.updateCamera();
} else if(!this.isRootRotationFinal()) {
this.rotateRoot();
}
}
this.planets.forEach(function(planet) {
planet.update();
});
this.sun.animate();
}
createPlanets() {
this.planetSpecs.forEach(function(spec) {
let planet = new spec.type({
animateOrbit: true, animateRotation: true, showOrbit: true,
distance: spec.distance * metadata.constants.EARTH_DISTANCE + metadata.constants.SUN_SIZE_IN_EARTHS,
size: spec.size * metadata.constants.EXAGGERATED_PLANET_SCALE,
period: spec.period,
revolutionSpeed: 0.002,
map: spec.map,
autoInit: true
}),
orbitDistance = spec.distance * metadata.constants.EARTH_DISTANCE + metadata.constants.SUN_SIZE_IN_EARTHS,
orbit = new app.view.milkyway.Orbit({
distance: orbitDistance,
autoInit: true
});
this.addObject(planet);
this.planets.push(planet);
this.orbits.push(orbit);
}, this);
}
render() {
let sun = new app.view.milkyway.Sun({autoInit: true}),
starDistance = metadata.constants.SUN_SIZE_IN_EARTHS +
metadata.constants.EARTH_DISTANCE *
metadata.constants.PLUTO_DISTANCE_IN_EARTHS,
stars = new app.view.milkyway.Stars({autoInit: true, distance: starDistance}),
ambientLight = new THREE.AmbientLight(0x676767);
this._sun = sun;
this.root.rotation.y = -0.81;
this.addObject(sun);
this.addObject(stars);
this.createPlanets();
this.camera.position.set(0, 0, 500);
this.scene.add(ambientLight);
}
}
|
const Promise = require('bluebird'),
domain = require('domain'),
fs = require('fs'),
AWS = require('aws-sdk'),
s3 = new AWS.S3({region: 'us-east-1'});
console.info("LOADING FUNCTIONS");
function json_print(value) {
return JSON.stringify(value, null, 2);
}
function handler(event, context, callback) {
var d = domain.create();
d.on('error', (er) => { console.error('error', er.stack); });
d.run(() => {
return Promise.all(event.Records.map(record =>
handlePayload(new Buffer(record.kinesis.data, 'base64').toString('utf8'))
))
.then((values) => {
var str = "Successfully processed " + event.Records.length + " records.";
console.log(str);
context.succeed(str);
})
.catch((err) => {
// We need to properly retry this batch: https://docs.aws.amazon.com/lambda/latest/dg/retries-on-errors.html
var str = "Error processing " + event.Records.length + " records: " + err;
console.error(str);
console.error(err);
context.fail(str);
})
});
}
function handlePayload(payloadStr) {
// No need to always check bucket. Trust me, they are there.
return parseJSON(payloadStr)
//.then(_checkIfBucketExists)
//.then(_createBucket)
.then(_sendToS3);
}
function _checkIfBucketExists(payload) {
return new Promise((fulfill, reject) => {
var params = { Bucket: getBucketName(payload) };
console.log(json_print(payload));
s3.headBucket(params, function(err, data) {
var bucketExists = false;
if (!err) {
bucketExists = true;
}
return fulfill(payload, bucketExists);
});
});
}
function _createBucket(payload, bucketExists) {
return new Promise((fulfill, reject) => {
if (bucketExists) {
return fulfill(payload);
}
var params = { Bucket: getBucketName(payload) };
s3.createBucket(params, function(err, data) {
if (err) {
return reject(err);
} else {
return fulfill(payload);
}
});
});
}
function _sendToS3(payload) {
console.log(json_print(payload));
return new Promise((fulfill, reject) => {
var params = { ContentType: 'text/plain', Bucket: getBucketName(payload), Key: buildPath(payload), Body: json_print(payload) },
options = { partSize: 10 * 1024 * 1024, queueSize: 1 };
s3.upload(params, options, function(err, data) {
if (err) {
return reject(err);
} else {
return fulfill();
}
});
});
}
function buildPath(payload) {
var idString = ("000000000" + payload.id).slice(-9);
var idArray = idString.match(/.{1,3}/g).join("/");
return payload.table_name + '/' + idArray + '/' + payload.uuid + '.json';
}
function getBucketName(payload) {
return payload.bucket_name;
}
function parseJSON(json) {
const parsePromise = new Promise((resolve, reject) => {
try {
resolve(JSON.parse(json));
} catch (e) {
reject(new Error(`Invalid JSON: ${json}`));
}
});
return parsePromise;
}
exports.handler = handler;
|
/*
* This file is part of the serializerjs package.
*
* (c) HAIRCVT <tfidry@haircvt.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* eslint-env mocha */
import { assert } from 'chai';
import SerializerError from './../../src/Error/SerializerError';
/** @test {SerializationError} */
describe('SerializationError', () => {
it('It is an Error', () => {
const error = new SerializerError();
assert.isTrue(error instanceof Error);
});
it('It captures the error message', () => {
const message = 'My message';
const error = new SerializerError(message);
assert.strictEqual(error.message, message);
});
it('An error without any message has an empty message', () => {
const error = new SerializerError();
assert.strictEqual(error.message, '');
});
it('It captures the error name', () => {
const error = new SerializerError();
assert.strictEqual(error.name, 'SerializerError');
});
});
|
import { createBinding } from "creators";
/**
* Flag will be set on missing initial state of store
* @type {String}
*/
export const ABSTRACT_STATE_FLAG = "$$isAbstractInitialStoreState";
/**
* @class Store
* @author Jan Biasi <biasijan@gmail.com>
*/
export default class Store {
/**
* Save internal set bindings inside Store
* @type {Array<String>}
*/
$$boundActions = [];
/**
* Prevent direct instanciation of the Store class
*/
constructor() {
if (new.target === Store) {
throw new TypeError(
"Store.constructor(...): Cannot construct Stores instances directly."
);
}
}
/**
* Provide an initial state for each store,
* will display warnings when a custom store does not
* override the initialState which can lead to issues.
* @abstract
*/
get initialState() {
return {
[ABSTRACT_STATE_FLAG]: true
};
}
/**
* Provide initialize method for each store
* @abstract
*/
initialize() {}
/**
* Listen to an action inside the app and run a state
* mutation handler on call.
* @param {String} action
* @param {Function} stateMutation
*/
on(action, stateMutation) {
this.$$boundActions.push(action);
createBinding(this, action, stateMutation);
}
/**
* Check if a value is a store instance,
* will be used internally atm.
* @param {Store?} optimisticStoreInstance
* @return {Boolean}
*/
static isStore(optimisticStoreInstance) {
if (!optimisticStoreInstance) {
return false;
}
if (optimisticStoreInstance.on && optimisticStoreInstance.initialState) {
return true;
}
return false;
}
}
|
'use strict';
var test = require('tap').test;
var async = require('async');
var cp = require('child_process');
/*
var Node = require('../../lib/node.js');
var RiakClient = require('../../lib/client.js');
var nodes = [{
host: '127.0.0.1',
port: 8087
}];
*/
function exec(cmd, callback) {
cp.exec(cmd, function (err, stdout, stderr) {
if (err) return callback(err, null);
if (stderr) return callback(new Error('stderr: ' + stderr));
callback(null, stdout);
});
}
test('enable security', function (t) {
async.series([
exec.bind(null, 'riak-admin security enable'),
exec.bind(null, 'riak-admin security add-user riakdb password=testing'),
exec.bind(null, 'riak-admin security grant riak_kv.put,riak_kv.get,riak_kv.delete on any to riakdb'),
exec.bind(null, 'riak-admin security add-source riakdb 127.0.0.1/32 password')
], function (err, stdouts) {
t.equal(err || null, null);
t.ok(true, stdouts.join('; '));
t.end();
});
});
/*
test('simple', function (t) {
var node = new Node(nodes[0], {
user: new Buffer('riakdb'),
password: new Buffer('testing')
});
node.connect();
node.once('connect', function () {
t.end();
});
});
test('not authorized, error though callback', function (t) {
var client = new RiakClient({ 'nodes': nodes });
client.once('error', function (err) {
console.log(err);
// t.end();
});
client.ping(function (err, response) {
console.log(err);
// t.end();
});
});
test('not authorized, error only though event', function (t) {
var client = new RiakClient({ 'nodes': nodes, 'minConnections': 1 });
client.once('error', function (err) {
console.log(err);
// t.end();
});
});
*/
test('disable security', function (t) {
exec('riak-admin security disable', function (err, stdout) {
t.equal(err || null, null);
t.ok(true, stdout);
t.end();
});
});
|
//= require ./underscore
EquivalentXml = (function(){
var compare_documents = function(node_1, node_2, opts){
return is_equivalent(node_1.childNodes,node_2.childNodes,opts);
};
var compare_elements = function(node_1, node_2, opts){
return node_1.nodeName == node_2.nodeName && compare_children(node_1, node_2, opts);
};
var compare_attributes = function(node_1, node_2, opts){
return node_1.name == node_2.name && node_1.value == node_2.value;
};
var compare_cdata = function(node_1, node_2, opts){
return node_1.nodeValue == node_2.nodeValue;
};
var compare_text = function(node_1, node_2, opts){
if(opts.normalize_whitespace){
return strip(node_1.textContent).replace(/\s+/g,' ') == strip(node_2.textContent).replace(/\s+/g,' ');
} else {
return node_1.nodeValue == node_2.nodeValue;
}
};
var attribute_is_namespace = function(attribute){
return attribute.prefix == "xmlns";
};
var compare_children = function(node_1, node_2, opts){
var nodelist_1 = as_nodelist(node_1.childNodes, opts);
var nodelist_2 = as_nodelist(node_2.childNodes, opts);
var result = compare_nodelists(nodelist_1, nodelist_2, opts);
if(node_1.attributes instanceof NamedNodeMap){
var attributes_1 = _.reject(node_1.attributes, attribute_is_namespace);
var attributes_2 = _.reject(node_2.attributes, attribute_is_namespace);
result = result && compare_nodelists(attributes_1, attributes_2,opts);
}
return result;
};
var node_index = function(node, set){
var index = -1;
_.find(set, function(element, i){
var result = node === element;
if(result){ index = i; }
return result;
});
return index;
};
var as_nodelist = function(data, opts){
return _.reject(data, function(child){
return child instanceof Comment ||
(opts.normalize_whitespace && child instanceof Text && _.isEmpty(strip(child.textContent)));
});
};
// Based on jQuery implementation
var xml = function(data){
if(typeof data != "string"){ return undefined; }
var xml, tmp;
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
// Nasty hack to detect errors generated by DOMParser
if( xml.documentElement.childNodes[0] && xml.documentElement.childNodes[0].nodeName == "parsererror" ||
xml.querySelector("html > body > parsererror") ){
xml = undefined;
}
return xml;
};
var compare_nodelists = function(nodelist_1, nodelist_2, opts){
if( nodelist_1.length != nodelist_2.length ){
return false;
}
var nodelist_2_found = [];
var all_found = _.all(nodelist_1, function(node_1, node_1_index){
var found_node = _.find(nodelist_2, function(node_2){
var node_2_index = node_index(node_2,nodelist_2);
var result = false;
// Only look at nodes we haven't already ticked off
if(!_.include(nodelist_2_found, node_2_index)){
result = is_equivalent(node_1, node_2, opts);
if(result){ nodelist_2_found.push(node_2_index); }
}
return result;
});
return !!found_node && (!opts.element_order || opts.element_order && node_1_index == node_index(found_node,nodelist_2));
});
// Make sure all nodelist_1 elements are found, and there are no extra in nodelist_2
return all_found && nodelist_2_found.length == nodelist_2.length;
};
var compare_nodes = function(node_1, node_2, opts){
var result;
if( _.any([node_1,node_2], isNotNode) ){
result = toString(node_1) == toString(node_2);
} else {
switch(node_1.constructor){
case Document:
result = compare_documents(node_1, node_2, opts);
break;
case Element:
result = compare_elements(node_1, node_2, opts);
break;
case Attr:
result = compare_attributes(node_1, node_2, opts);
break;
case Text:
result = compare_text(node_1, node_2, opts);
break;
case CDATASection:
result = compare_cdata(node_1, node_2, opts);
break;
default:
result = compare_children(node_1, node_2, opts);
}
}
return result;
};
var isNode = function(node){
return typeof node == "object" && node !== null && typeof node.nodeType == "number";
};
var isNotNode = function(node){
return !isNode(node);
};
var isNodelist = function(node){
return node instanceof NodeList || node instanceof NamedNodeMap;
};
var strip = function(string){
return string.replace(/(^\s+)|(\s+$)/g,'');
};
var toString = function(object){
if(object === null){
return "";
}else if(object instanceof Document){
return new XMLSerializer().serializeToString(object);
}
else{
return object.toString();
}
};
var is_equivalent = function(node_1, node_2, opts){
if(_.any([node_1,node_2],isNodelist)){
return compare_nodelists(node_1, node_2, opts);
} else {
return compare_nodes(node_1, node_2, opts);
}
};
return {
isEquivalent: function(node_1, node_2, options){
var opts = _.clone(this.defaults);
_.extend(opts,options);
return is_equivalent(node_1, node_2, opts);
},
xml: xml,
defaults: {
element_order: false,
normalize_whitespace: true
},
jasmine: {
beEquivalentTo: function(expected, options){
var actual = this.actual;
this.message = function () {
return "Expected " + toString(actual) + " to be equivalent to " + toString(expected);
};
return EquivalentXml.isEquivalent(actual,expected,options);
}
},
};
})(); |
import React from "react";
const VideoListItem = ({ video, onVideoSelect }) => {
// const video = props.video;
const imgUrl = video.snippet.thumbnails.default.url;
return (
<li onClick={() => onVideoSelect(video)} className="list-group-item">
<div className="video-list media">
<div className="media-left">
<img className="media-object" src={imgUrl} />
</div>
<div className="media-body">
<div className="media-heading">{video.snippet.title}</div>
</div>
</div>
</li>
);
};
export default VideoListItem;
|
/**
* Represents the highscore list
*
* @copyright Nikolay V. Nemshilov aka St.
*/
Sudoku.Highscore = new Class({
LENGTH: 7,
initialize: function() {
this.element = $E('div', {
id: 'rs-highscore',
html: '<label>Highscore</label><ul id="rs-highscore-list"></ul></label>'
});
this.list = this.element.first("#rs-highscore-list");
this.read();
},
load: function(level) {
this.levels[level] = this.levels[level] || [];
this.results = this.levels[level];
this.render();
return this;
},
add: function(time) {
this.results.push({time: time, name: '<input type="text" />'});
this.results.sort(function(a,b) { return a.time > b.time ? 1 : a.time < b.time ? -1 : 0; });
this.results.splice(this.LENGTH, this.results.length);
return this.render();
},
// protected
// reads the saved results out of the cookies
read: function() {
var levels = Cookie.get('rs-result') || '';
this.levels = {};
levels.split('%').each(function(level) {
var els = level.split('#');
if (els.length == 2) {
this.levels[els.first()] = els.last().split(';').map(function(result) {
var els = result.split('|');
return els.length == 2 ? {
time: els.first().toInt(),
name: unescape(els.last())
} : null;
}).compact();
}
}, this);
return this;
},
render: function() {
this.list.update(
this.results.map(function(result) {
var minutes = (result.time/60).floor();
var seconds = result.time % 60;
minutes = (minutes < 10 ? '0' : '') + minutes;
seconds = (seconds < 10 ? '0' : '') + seconds;
return '<li>'+minutes+':'+seconds+' '+result.name+'</li>';
}).join('') || 'Empty'
);
var input = this.list.first('input');
if (input) {
input.value = this.lastName || '';
input.on('keydown', (function(event) {
if (event.keyCode == 13) { // <- the enter is pressed
event.stop();
this.acceptName(input.value);
}
}).bind(this)).focus();
}
return this;
},
acceptName: function(name) {
var result = this.results.any(function(result) { return result.name == '<input type="text" />'; });
if (result) {
this.lastName = name;
result.name = name.replace('<', '<').replace('>', '>');
}
return this.render().save();
},
// saves the current results to the cookies
save: function() {
Cookie.set('rs-result',
Object.keys(this.levels).map(function(level) {
return level+"#"+this.levels[level].map(function(result) {
return result.time+"|"+escape(result.name)
}).join(';')
}, this).join('%'),
{duration: 999}
);
return this;
}
}); |
git://github.com/chilijung/form.js.git
|
describe('Modules.ExpensesDataTable.js', function () {
const module = moj.Modules.ExpensesDataTable
const options = module.options
it('...should exist', function () {
expect(moj.Modules.ExpensesDataTable).toBeDefined()
})
describe('...Options', function () {
it('...should have `info` disabled', function () {
expect(options.info).toEqual(false)
})
it('...should have `paging` disabled', function () {
expect(options.paging).toEqual(false)
})
it('...should have `searching` disabled', function () {
expect(options.searching).toEqual(false)
})
it('...should have `order`', function () {
expect(options.order).toEqual([
[0, 'asc'],
[3, 'asc']
])
})
describe('...options.columnDefs', function () {
const columnDefs = options.columnDefs
const getColsDefs = function (idx, prop) {
prop = prop || ''
return $.map([columnDefs[idx]], function (item) {
return item[prop]
})
}
const getColsDefsByTarget = function (target) {
return $.map(columnDefs, function (item) {
if (item.targets === target || 0) {
return item
}
})[0]
}
it('...should have `targets` defined', function () {
expect(getColsDefs(0, 'targets')).toEqual([0])
expect(getColsDefs(1, 'targets')).toEqual([1])
expect(getColsDefs(2, 'targets')).toEqual([2])
expect(getColsDefs(3, 'targets')).toEqual([3])
expect(getColsDefs(4, 'targets')).toEqual([4])
expect(getColsDefs(5, 'targets')).toEqual([5])
})
it('...should have orderable disabled for the details column', function () {
expect(getColsDefsByTarget(0)).toEqual({
targets: 0,
width: '1%'
})
expect(getColsDefsByTarget(1)).toEqual({
targets: 1,
width: '20%'
})
expect(getColsDefsByTarget(2)).toEqual({
targets: 2,
orderable: false,
width: '20%'
})
expect(getColsDefsByTarget(3)).toEqual({
targets: 3,
width: '1%'
})
expect(getColsDefsByTarget(4)).toEqual({
targets: 4,
width: '1%'
})
expect(getColsDefsByTarget(5)).toEqual({
targets: 5,
orderable: false,
width: '1%'
})
})
})
})
})
|
/**
* hilojs 2.0.2 for cmd
* Copyright 2016 alibaba.com
* Licensed under the MIT License
*/
define(function(n,e,o){var t=n("hilo/core/Class"),r=n("hilo/util/util"),c=t.create({constructor:function(n){n=n||{},r.copy(this,n,!0)},renderType:null,canvas:null,stage:null,blendMode:"source-over",startDraw:function(n){},draw:function(n){},endDraw:function(n){},transform:function(){},hide:function(){},remove:function(n){},clear:function(n,e,o,t){},resize:function(n,e){}});return c}); |
KB.onClick('.accordion-toggle', function(e) {
var section = KB.dom(e.target).parent('.accordion-section');
if (section) {
KB.dom(section).toggleClass('accordion-collapsed');
KB.dom(KB.dom(section).find('.accordion-content')).toggle();
}
});
|
/*
Copyright (c) 2015, SerGIS Project Contributors. All rights reserved.
Use of this source code is governed by the MIT License, which can be found
in the LICENSE.txt file.
*/
// node modules
var crypto = require("crypto");
// our modules
var config = require("../../config");
// The length of the random parts of our auth tokens
var TOKEN_LENGTH = 14;
// The AuthToken model (created in the `module.exports` function below)
var AuthToken;
// Create the AuthToken model
module.exports = function (mongoose, extend) {
var Schema = mongoose.Schema;
// AuthToken schema
var authTokenSchema = new Schema({
// The token
token: {
type: String,
unique: true
},
// Any old tokens for this session
oldTokens: [{
type: String
}],
// The user associated with this token (if any)
user: {
type: Schema.Types.ObjectId,
ref: "User"
},
// Whether the session associated with this token is a super-admin
// session (see config.js for details)
superAdmin: {
type: Boolean,
default: false
},
// Data about games played with this session (only used if no user is
// logged in)
// keys: game IDs, values: objects
playedGames: Schema.Types.Mixed,
// The date that the session was created
sessionCreated: {
type: Date,
default: Date.now
},
// The date that the current token was created
tokenCreated: {
type: Date
},
// The date that the session/token was last accessed
lastAccessed: {
type: Date,
default: Date.now
}
});
// AuthToken model instance method
authTokenSchema.methods.generateToken = function () {
if (this.token) {
this.oldTokens.push(this.token);
}
this.tokenCreated = Date.now();
return (this.token = generateToken());
};
// AuthToken model static method
authTokenSchema.statics.checkTokenFromReq = checkTokenFromReq;
// AuthToken model
return (AuthToken = mongoose.model("AuthToken", authTokenSchema));
};
/**
* Generate a random, pretty guaranteed unique auth token.
*/
function generateToken() {
return crypto.randomBytes(TOKEN_LENGTH)
.toString("base64")
.substring(0, TOKEN_LENGTH)
// Turn obscure base64 characters into less obscure characters
.replace(/\+/g, ".")
.replace(/\//g, ",")
// Add the current time for more uniqueness
+ (new Date()).getTime().toString(36);
}
/**
* Check for the presence of an auth token in an Express request. If one doesn't
* exist (or is invalid), generate a new one.
*
* @param req - The Express request object.
* @param {boolean} regenerateToken - Whether to regenerate the token if it
* already exists.
*
* @return {Promise.<AuthToken>} The AuthToken instance.
*/
function checkTokenFromReq(req, regenerateToken) {
return new Promise(function (resolve, reject) {
var generateNewToken = function () {
var authToken = new AuthToken();
authToken.generateToken();
authToken.save(function (err) {
if (err) {
reject(err);
return;
}
resolve(authToken);
});
};
if (req.signedCookies.t) {
// Check the token
AuthToken.findOne({token: req.signedCookies.t}).populate("user").exec(function (err, authToken) {
if (authToken) {
// We're good!
// Should we regenerate token?
if (regenerateToken) {
// Generate a new token (practically just for fun)
authToken.generateToken();
}
// Set the last accessed date
authToken.lastAccessed = Date.now();
// Save everything
authToken.save(function (err) {
if (err) {
reject(err);
return;
}
resolve(authToken);
});
} else {
// No good; generate a new one
generateNewToken();
}
});
} else {
generateNewToken();
}
});
} |
define( [ "shared", "mid.broadcaster" ],
function( shared, broadcaster )
{
/***
* Simple Method executed when a socket ends
*/
function closeSocket( socket )
{
console.log( ( socket.nick || "guest" ) + " left" );
var i = shared.telnetSockets.indexOf( socket );
if ( i != -1 )
shared.telnetSockets.splice( i, 1 );
i = shared.rooms[ socket.room ].indexOf( socket );
if ( i != -1 )
shared.rooms[ socket.room ].splice( i, 1 );
if ( socket.nick )
delete shared.socketsByNick[ socket.nick ];
broadcaster( { room: socket.room || "main", msg: ( socket.nick || "guest " ) + " disconnected" } );
}
return closeSocket;
} ); |
var nest = require('unofficial-nest-api'),
querystring = require('querystring'),
http = require('http'),
username = process.env.NEST_USERNAME,
password = process.env.NEST_PASSWORD,
device = process.env.NEST_DEVICE_ID,
influxHost = process.env.INFLUX_HOST,
influxPort = process.env.INFLUX_PORT,
influxDb = process.env.INFLUX_DB,
influxUser = process.env.INFLUX_USER,
influxPassword = process.env.INFLUX_PASSWORD,
tempCelsius = process.env.TEMP_CELSIUS,
wundergroundData = process.env.WUNDERGROUND_DATA,
wundergroundKey = process.env.WUNDERGROUND_KEY,
wundergroundStation = process.env.WUNDERGROUND_STATION
var influxReqOptions = {
host: influxHost,
port: influxPort,
path: '/write?db=' + influxDb + '&' + querystring.stringify({ u: influxUser, p: influxPassword }),
method: 'POST'
},
wundergroundReqOptions = {
host: 'api.wunderground.com',
path: '/api/' + wundergroundKey + '/conditions/q/pws:' + wundergroundStation + '.json',
method: 'GET'
}
nest.login(username, password, function (err, data) {
if (err) {
console.error('There was some weird error')
console.error(err)
process.exit(1)
}
nest.fetchStatus(function (data) {
var influxData = []
if (!data.hasOwnProperty('device') || !data.device.hasOwnProperty(device)) {
console.error('Could not find device with the id "' + device + '"')
process.exit(1)
}
if (!data.hasOwnProperty('shared') || !data.shared.hasOwnProperty(device)) {
console.error('Could not find shared device with the id "' + device + '"')
process.exit(1)
}
addInfluxPoint(data.device[device], 'battery_level', null, influxData)
addInfluxPoint(data.device[device], 'current_humidity', null, influxData)
addInfluxPoint(data.device[device], 'target_humidity', null, influxData)
addInfluxPoint(data.device[device], 'learning_days_completed_heat', null, influxData)
addInfluxPoint(data.shared[device], 'target_temperature', null, influxData, fToC)
addInfluxPoint(data.shared[device], 'current_temperature', null, influxData, fToC)
addInfluxPoint(data.shared[device], 'auto_away', 'auto_away_on', influxData)
addInfluxPoint(data.shared[device], 'hvac_heater_state', 'heater_on', influxData, function (value) {
if (value) {
return 1
}
return 0
})
console.log(JSON.stringify(influxData))
postInfluxData(influxData, function () {
console.log('NEST DONE!')
if(wundergroundData == 'true'){
wunderground()
}
})
})
})
/**
* Helper function to get weather information from Weather Underground and insert into Influx
*/
var wunderground = function () {
http.get(wundergroundReqOptions, function (response) {
var data = ''
response.on('data', function (body) {
data += body.toString()
})
response.on('end', function () {
try {
var wundergroundData = JSON.parse(data)
} catch (error) {
console.error('Failed to parse wunderground data')
console.error(data)
process.exit(1)
}
if (!wundergroundData.hasOwnProperty('current_observation')) {
console.error('Did not find the weather info we need!')
console.error(data)
process.exit(1)
}
var influxData = []
addInfluxPoint(wundergroundData['current_observation'], 'temp_f', 'outside_temperature', influxData)
addInfluxPoint(wundergroundData['current_observation'], 'relative_humidity', 'outside_humidity', influxData, parseInt)
postInfluxData(influxData, function () {
console.log('WUNDERGROUND DONE!')
process.exit(0)
})
})
}).on('error', function (error) {
console.error('Wunderground error')
console.error(error)
process.exit(1)
})
}
/**
* Handles posting an Influx data structure to Influx
* If this fails to insert into Influx the program is terminated
*
* @param {Object} data The Influx data structure to submit
* @param {Function} callback A function that is called on success
*/
var postInfluxData = function (data, callback) {
var resBody = ''
var req = http.request(influxReqOptions, function (res) {
res.setEncoding('binary')
res.on('data', function (data) {
resBody += data.toString()
})
res.on('end', function () {
if (res.statusCode != '204') {
console.error('Something bad happened with influx!')
console.error(resBody)
process.exit(1)
}
callback()
})
})
req.on('error', function (error) {
console.error('Influx did not like us')
console.error(error)
process.exit(1)
})
var bindata = ''
for (var i = 0, len = data.length; i < len; i++) {
bindata += data[i].name + ",deviceID=" + device + " value=" + data[i].points[0][0]+"\n"
}
req.write(bindata, 'binary')
req.end(null,'binary')
}
/**
* Add a data point to an Influx data structure for import into Influx
*
* @param {Object} source The object to search for the point to add into destination
* @param {String} point The property in source to add into destination
* @param {String} [name=point] Overrides the point name in the Influx data structure
* @param {Object} destination The object to insert the data from source into (this is what will be given to Influx)
* @param {Function} [convertFunc] Optional function to convert a found point value
*/
var addInfluxPoint = function (source, point, name, destination, convertFunc) {
if (source.hasOwnProperty(point)) {
var useName = (name == void 0) ? point : name
, useFunc = convertFunc || function (value) { return value }
destination.push({
name: 'nest.' + useName,
columns: [ 'value' ],
points: [[ useFunc(source[point]) ]]
})
}
}
/**
* Convert Celsius to Fahrenheit
*
* @param {Number} temp The temperature in Celsius
*
* @returns {Number} The temperature in Fahrenheit
*/
var fToC = function (temp) {
if(tempCelsius == 'true'){
return temp
}
return ((temp * (9 / 5)) + 32)
}
|
require('angular-ui-mask/dist/mask');
require('ui-select/dist/select');
require('angular-moment');
require('angular-sanitize');
require('angular-file-saver');
require('ng-file-upload');
require('bootstrap');
require('angular-ui-bootstrap');
require('angular-ckeditor');
require('bootstrap-ui-datetime-picker/dist/datetime-picker');
require('ng-dialog');
require('angular-ui-ace/src/ui-ace');
require('./formio');
|
const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const { AngularCompilerPlugin } = require('@ngtools/webpack')
const { ProgressPlugin, NormalModuleReplacementPlugin } = webpack
module.exports = (env, options) => {
const devMode = options.mode !== 'production'
return {
entry: {
app: './src/app/main.ts',
polyfills: './src/app/polyfills.ts'
},
output: {
path: path.resolve('dist', 'app'),
filename: '[name].js',
chunkFilename: '[id].chunk.js'
},
mode: 'development',
target: 'electron-renderer',
resolve: {
extensions: ['.ts', '.js', '.json']
},
externals: {
keytar: "require('keytar')"
},
devtool: devMode ? 'inline-source-map' : 'source-map',
watchOptions: {
aggregateTimeout: 1000,
ignored: ['node_modules', 'dist', '.git']
},
optimization: {
splitChunks: {
chunks: 'all'
}
},
module: {
rules: [
// html files
{
test: /\.html$/,
loader: 'html-loader'
},
// asset files
{
test: /\.(png|jpe?g|gif|svg|woff2?|[to]tf|eot|ico)$/,
loaders: [
{
loader: 'file-loader',
options: { name: 'assets/[name].[hash:8].[ext]' }
}
]
},
// page css
{
test: /\.css$/,
include: path.resolve('src', 'app', 'style'),
loaders: [
devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: { sourceMap: true, importLoaders: 1 }
},
{
loader: 'postcss-loader',
options: { sourceMap: 'inline' }
}
]
},
// angular component css
{
test: /\.css$/,
exclude: path.resolve('src', 'app', 'style'),
loaders: [
'to-string-loader',
{
loader: 'css-loader',
options: { sourceMap: true, importLoaders: 1 }
},
{
loader: 'postcss-loader',
options: { sourceMap: 'inline' }
}
]
},
// angular files
{
test: /\.ngfactory\.js|\.ngstyle\.js|\.ts$/,
loader: '@ngtools/webpack'
}
]
},
plugins: [
new ProgressPlugin(),
new NormalModuleReplacementPlugin(
/environments\/environment$/,
resource => {
if (options.mode === 'production') resource.request += '.prod'
}
),
new CopyWebpackPlugin([
// electron-level icons
{ from: './monux.*', context: './src', to: '../' },
// app icons
{ from: './assets/', context: './src/app', to: './assets' }
]),
new AngularCompilerPlugin({
tsConfigPath: './tsconfig.webpack.json',
mainPath: './src/app/main.ts',
sourceMap: true,
skipCodeGeneration: devMode,
compilerOptions: {
debug: devMode
}
}),
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[id].chunk.css'
}),
new HtmlWebpackPlugin({
template: './src/app/index.html',
// baseHref: devMode ? '/' : './',
chunksSortMode: (chunk1, chunk2) => {
const orders = ['polyfills', 'vendor', 'app']
return (
orders.indexOf(chunk1.names[0]) - orders.indexOf(chunk2.names[0])
)
}
})
]
}
}
|
//import React from 'react';
//import ReactDOM from 'react-dom';
import AtCoderCutomStandings from './app.js'
import injectCustomCSS from './css.js'
$('div.table-responsive').hide();
$('#pagination-standings').hide();
$('#standings-csv-link').after('<div id="content"></div>');
//$('head').append('<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">');
injectCustomCSS();
try{
ReactDOM.render(
<AtCoderCutomStandings />,
document.getElementById('content')
);
}catch(e){
console.log( "some error occurred" );
console.log( e );
$('div.table-responsive').show();
$('#pagination-standings').show();
}
|
'use strict';
module.exports = {
db: 'mongodb://localhost/selectora-test',
port: 3001,
app: {
title: 'selectora - Test Environment'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: '/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: '/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: '/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: '/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: '/auth/github/callback'
},
mailer: {
from: process.env.MAILER_FROM || 'MAILER_FROM',
options: {
service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
auth: {
user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
}
}
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.