code stringlengths 2 1.05M |
|---|
import React from 'react';
import {connect} from 'react-redux'
import {browserHistory} from 'react-router'
import myStore from '../../AppStore'
const chooseQuote = function (quoteId) {
myStore.dispatch({
'type': 'QUOTES-SELECT'
, 'selected': quoteId
});
browserHistory.push('/information')
}
const Quotes = ({quotes}) => {
let quotesJsx = [];
if (quotes.fetched) {
quotesJsx = quotes.fetched.map(
(quote) => {
const coveragesJsx = quote.coverages.map((coverage) => <li key={quote.id + '-' + coverage}>coverage</li>);
return (
<div className="panel panel-primary" key={quote.id}>
<div className="panel-heading">{quote.title}</div>
<div className="panel-body">
<ul>
{coveragesJsx}
</ul>
</div>
<div className="panel-footer">
<button className="btn btn-primary col-xs-12"
onClick={() => chooseQuote(quote.id)}>
Choose this quote
</button>
<div className="clearfix"></div>
</div>
</div>
);
}
)
}
return (
<div>
<div className="row">
<div className="col-xs-12">
<div className="panel panel-primary">
<div className="panel-heading">
<h3 className="panel-title">Quotes</h3>
</div>
<div className="panel-body">
{quotesJsx}
</div>
</div>
</div>
</div>
</div>
);
}
export default connect(
state => {
return {quotes: state.quotes}
}
)(Quotes) |
require('mocha');
var assert = require('assert');
var Scaffold = require('scaffold');
var isScaffold = require('./');
describe('isScaffold', function () {
it('should return false if the value is not a Scaffold:', function () {
assert(isScaffold('a') === false);
assert(isScaffold({}) === false);
assert(isScaffold({ files: [] }) === false);
});
it('should return true if the value is a Scaffold:', function () {
assert(isScaffold(new Scaffold({ files: [] })) === true);
});
});
|
"use strict";
/**
* Gives us some nice debug convenience functions
*
* @namespace Debug
*/
Log = (function() {
/**
* true if info mode is on, otherwise false
*/
var INFO = true;
var enableInfo = function() {
INFO = true;
};
/**
* true if error mode is on, otherwise false
*/
var ERROR = true;
var enableError = function() {
ERROR = true;
};
/**
* true if debug mode is on, otherwise false
*/
var DEBUG = false;
var enableDebug = function() {
DEBUG = true;
};
/**
* Logs an info message to the console if debug mode is on
*
* @param {string} message the message to log
*
* @memberof Log
*/
var info = function(message) {
if (INFO) console.log("[INFO]\t" + _getDateString() + " -- " + message);
};
/**
* Logs an error message to the console if debug mode is on
*
* @param {string} message the message to log
*
* @memberof Log
*/
var error = function(message) {
if (ERROR) console.error("[ERROR]\t" + _getDateString() + " -- " + message);
};
/**
* Logs an debug message to the console if debug mode is on
*
* @param {string} message the message to log
*
* @memberof Log
*/
var debug = function(message) {
if (DEBUG) console.log("[DEBUG]\t" + _getDateString() + " -- " + message);
};
/**
* Gets a nicely formatted string of the given date
*
* @param {Date} date the date to format into a string. Defaults to the current date.
* @returns {string} a string describing the date
*
* @memberof Log
*/
var _getDateString = function(date) {
if (date === undefined) date = new Date();
var hours = date.getHours();
hours = (hours.length === 1) ? "0" + hours : hours;
var minutes = date.getMinutes();
minutes = (minutes.length === 1) ? "0" + minutes : minutes;
var seconds = date.getSeconds();
seconds = (seconds.length === 1) ? "0" + seconds : seconds;
var milliseconds = date.getMilliseconds();
milliseconds = (milliseconds.length === 1) ? "00" + milliseconds : milliseconds;
milliseconds = (milliseconds.length === 2) ? "0" + milliseconds : milliseconds;
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
};
return {
enableDebug: enableDebug,
info: info,
error: error,
debug: debug
};
})();
|
import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class IosNutritionOutline extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g>
<path d="M358,233.855l0.413-0.039c-0.137-0.137-0.046-0.101-0.185-0.237L279.798,155h-0.004c-5.833-6-14.193-10.154-23.485-10.154
c-11.811,0-22.115,6.154-27.635,16.154h-0.007c0,0-7.09,10.994-18.27,28.874l32.531,39.637c2.939,3.769,3.296,7.801,1.411,9.689
l-0.114,0.071c-0.909,0.909-2.021,1.33-3.274,1.33c-1.908,0-4.142-0.99-6.485-2.768l-35.872-29.418
c-23.546,37.655-56.677,90.634-83.45,133.451l19.072,23.337c2.939,3.77,3.296,7.884,1.41,9.772l-0.114,0.114
c-0.911,0.913-2.028,1.342-3.287,1.342c-1.905,0-4.136-0.981-6.472-2.755l-21.067-16.533C84.734,389.051,70,412.464,68,414.366
v0.003c-3,5.062-4.085,11.132-4.085,17.664c0,17.655,14.657,31.967,32.285,31.967c7.821,0,14.57-3.395,20.799-7.5l114.651-84.109
l-28.838-35.358c-2.94-3.769-3.268-7.887-1.382-9.775l0.128-0.114c0.912-0.912,2.034-1.341,3.294-1.341
c1.905,0,4.14,0.981,6.476,2.755l37.864,31.59C304.03,319.902,355.082,283,355.082,283h0.005c7.839-6,12.473-15.711,12.473-26.238
c0-8.704-3.56-17.14-9.56-22.904V233.855z M345.531,269.834c-2.664,1.934-46.692,33.932-95.764,69.899l-28.272-23.483l-0.26-0.223
l-0.274-0.211c-5.245-3.981-10.663-5.998-16.108-5.998c-5.465,0-10.592,2.097-14.458,5.909l-0.064,0.062l-0.083,0.082l-0.083,0.083
c-7.808,7.821-7.761,20.823,0.111,30.917l0.11,0.143l0.113,0.138l18.223,22.312l-100.656,73.896
c-5.066,3.304-8.427,4.657-11.542,4.657c-8.822,0-16-7.171-16-15.983c0-3.086,0.694-6.045,2.017-8.623
c2.391-3.161,6.6-9.876,18.655-29.351c2.543-4.108,5.252-8.487,8.134-13.129l6.39,5.176l0.195,0.156l0.2,0.152
c5.245,3.981,10.665,6,16.111,6c5.517,0,10.692-2.139,14.571-6.023l0.114-0.113c7.806-7.817,7.756-20.82-0.118-30.916l-0.113-0.144
l-0.115-0.142l-11.814-14.455l43.693-69.872l24.059-38.474l21.855,17.922l0.231,0.19l0.24,0.181
c5.254,3.988,10.678,6.01,16.123,6.01c4.954,0,9.631-1.725,13.339-4.89l0.461-0.337l0.871-0.874
c7.79-7.803,7.74-20.778-0.118-30.854l-0.12-0.153l-0.124-0.15l-25.239-30.539c2.957-4.703,5.457-8.491,7.405-11.488l5.209-8.494
c2.777-5.025,7.761-8.157,13.673-8.157c4.367,0,8.76,2.042,12.057,5.43l4.701,4.928h0.122L342,240.286v0.376l5.186,4.716
c2.793,2.69,4.539,6.782,4.539,11.227C351.725,261.801,349.467,266.728,345.531,269.834z"></path>
<polygon points="439.994,115.175 435.216,117.938 343.578,170.93 407.313,60.358 409.83,55.992 396.011,48 393.523,52.313
322.748,175.098 339.418,191.794 443.38,131.674 447.974,129.018 "></polygon>
</g>
</g>;
} return <IconBase>
<g>
<path d="M358,233.855l0.413-0.039c-0.137-0.137-0.046-0.101-0.185-0.237L279.798,155h-0.004c-5.833-6-14.193-10.154-23.485-10.154
c-11.811,0-22.115,6.154-27.635,16.154h-0.007c0,0-7.09,10.994-18.27,28.874l32.531,39.637c2.939,3.769,3.296,7.801,1.411,9.689
l-0.114,0.071c-0.909,0.909-2.021,1.33-3.274,1.33c-1.908,0-4.142-0.99-6.485-2.768l-35.872-29.418
c-23.546,37.655-56.677,90.634-83.45,133.451l19.072,23.337c2.939,3.77,3.296,7.884,1.41,9.772l-0.114,0.114
c-0.911,0.913-2.028,1.342-3.287,1.342c-1.905,0-4.136-0.981-6.472-2.755l-21.067-16.533C84.734,389.051,70,412.464,68,414.366
v0.003c-3,5.062-4.085,11.132-4.085,17.664c0,17.655,14.657,31.967,32.285,31.967c7.821,0,14.57-3.395,20.799-7.5l114.651-84.109
l-28.838-35.358c-2.94-3.769-3.268-7.887-1.382-9.775l0.128-0.114c0.912-0.912,2.034-1.341,3.294-1.341
c1.905,0,4.14,0.981,6.476,2.755l37.864,31.59C304.03,319.902,355.082,283,355.082,283h0.005c7.839-6,12.473-15.711,12.473-26.238
c0-8.704-3.56-17.14-9.56-22.904V233.855z M345.531,269.834c-2.664,1.934-46.692,33.932-95.764,69.899l-28.272-23.483l-0.26-0.223
l-0.274-0.211c-5.245-3.981-10.663-5.998-16.108-5.998c-5.465,0-10.592,2.097-14.458,5.909l-0.064,0.062l-0.083,0.082l-0.083,0.083
c-7.808,7.821-7.761,20.823,0.111,30.917l0.11,0.143l0.113,0.138l18.223,22.312l-100.656,73.896
c-5.066,3.304-8.427,4.657-11.542,4.657c-8.822,0-16-7.171-16-15.983c0-3.086,0.694-6.045,2.017-8.623
c2.391-3.161,6.6-9.876,18.655-29.351c2.543-4.108,5.252-8.487,8.134-13.129l6.39,5.176l0.195,0.156l0.2,0.152
c5.245,3.981,10.665,6,16.111,6c5.517,0,10.692-2.139,14.571-6.023l0.114-0.113c7.806-7.817,7.756-20.82-0.118-30.916l-0.113-0.144
l-0.115-0.142l-11.814-14.455l43.693-69.872l24.059-38.474l21.855,17.922l0.231,0.19l0.24,0.181
c5.254,3.988,10.678,6.01,16.123,6.01c4.954,0,9.631-1.725,13.339-4.89l0.461-0.337l0.871-0.874
c7.79-7.803,7.74-20.778-0.118-30.854l-0.12-0.153l-0.124-0.15l-25.239-30.539c2.957-4.703,5.457-8.491,7.405-11.488l5.209-8.494
c2.777-5.025,7.761-8.157,13.673-8.157c4.367,0,8.76,2.042,12.057,5.43l4.701,4.928h0.122L342,240.286v0.376l5.186,4.716
c2.793,2.69,4.539,6.782,4.539,11.227C351.725,261.801,349.467,266.728,345.531,269.834z"></path>
<polygon points="439.994,115.175 435.216,117.938 343.578,170.93 407.313,60.358 409.83,55.992 396.011,48 393.523,52.313
322.748,175.098 339.418,191.794 443.38,131.674 447.974,129.018 "></polygon>
</g>
</IconBase>;
}
};IosNutritionOutline.defaultProps = {bare: false} |
'use strict';
var shell = require('electron').shell;
var desktop_daemon = require('electron').remote;
angular.module('update', ['ngMaterial', 'remote']).controller('downloadController', ['$scope', 'rest', function($scope, rest)
{
this.check_for_update = function()
{
rest.get_desktop_version().then(function(response)
{
var remote_desktop_version = response.data;
if(desktop_daemon.getGlobal('desktop_version') !== remote_desktop_version)
$scope.update_available = true;
else
$scope.update_available = false;
$scope.ready = true;
});
};
$scope.ready = false;
$scope.download = function()
{
shell.openExternal('https://rain.vg/download.html');
window.close();
};
setTimeout(this.check_for_update, 1500);
}]);
|
var common = require('../../common');
var connection = common.createConnection({port: common.fakeServerPort});
var assert = require('assert');
var closeErr;
connection.on('close', function(err) {
assert.ok(!closeErr);
closeErr = err;
});
var queryErr;
var server = common.createFakeServer();
server.listen(common.fakeServerPort, function(err) {
if (err) throw err;
connection.query('SELECT 1', function(err) {
assert.ok(!queryErr);
queryErr = err;
});
});
server.on('connection', function(connection) {
connection.handshake();
connection.on('query', function(packet) {
server.destroy();
});
});
process.on('exit', function() {
assert.strictEqual(queryErr.code, 'PROTOCOL_CONNECTION_LOST');
assert.strictEqual(queryErr.fatal, true);
assert.strictEqual(closeErr, queryErr);
});
|
describe('view-specific options', function() {
var options
beforeEach(function() {
options = {
header: {
left: 'prev,next',
center: 'title',
right: 'month,basicWeek,basicDay,agendaWeek,agendaDay'
},
defaultView: 'month',
titleFormat: '[default]',
views: { }
}
affix('#cal')
})
function testEachView(viewsAndVals) {
$('#cal').fullCalendar(options)
$.each(viewsAndVals, function(view, val) {
$('#cal').fullCalendar('changeView', view)
expect($('h2')).toHaveText(val)
})
}
it('can target a specific view (month)', function() {
options.views.month = {
titleFormat: '[special!!!]'
}
testEachView({
month: 'special!!!',
basicWeek: 'default',
basicDay: 'default',
agendaWeek: 'default',
agendaDay: 'default'
})
})
it('can target a specific view (agendaWeek)', function() {
options.views.agendaWeek = {
titleFormat: '[special!!!]'
}
testEachView({
month: 'default',
basicWeek: 'default',
basicDay: 'default',
agendaWeek: 'special!!!',
agendaDay: 'default'
})
})
it('can target basic views', function() {
options.views.basic = {
titleFormat: '[special!!!]'
}
testEachView({
month: 'default', // will NOT target month view
basicWeek: 'special!!!',
basicDay: 'special!!!',
agendaWeek: 'default',
agendaDay: 'default'
})
})
it('can target agenda views', function() {
options.views.agenda = {
titleFormat: '[special!!!]'
}
testEachView({
month: 'default',
basicWeek: 'default',
basicDay: 'default',
agendaWeek: 'special!!!',
agendaDay: 'special!!!'
})
})
it('can target week views', function() {
options.views.week = {
titleFormat: '[special!!!]'
}
testEachView({
month: 'default',
basicWeek: 'special!!!',
basicDay: 'default',
agendaWeek: 'special!!!',
agendaDay: 'default'
})
})
it('can target day views', function() {
options.views.day = {
titleFormat: '[special!!!]'
}
testEachView({
month: 'default',
basicWeek: 'default',
basicDay: 'special!!!',
agendaWeek: 'default',
agendaDay: 'special!!!'
})
})
})
|
/**
*
* @author : Mei XinLin
* @version : 1.0
*/
export function validateEmail(email) {
const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/;
return reg.test(email);
}
export function validatePsd(password,secondPsd){
return password === secondPsd;
}
|
autowatch=1;
outlets=3;
// outlet 0 = jit_matrix / jit_gl_texture
// outlet 1 = movie attributes
// outlet 2 = special messages
const cachemode_static = 0;
const cachemode_auto = 1;
var cachemode = cachemode_static;
declareattribute("cachemode");
var cache_size = 0.5;
declareattribute("cache_size");
var cache_sizeauto = 5;
declareattribute("cache_sizeauto");
var drawto = "";
declareattribute("drawto", null, "setdrawto");
var verbose = 0;
declareattribute("verbose", null, null);
var target = 0;
declareattribute("target", null, "settarget");
var curmov=-1;
var isstopped=false;
var saveargs=true;
var readcount = 0;
var loopmode = 1;
var targets = [];
// viddll supports all these, first 3 are supported by avf
var filetypes = ["MPEG", "mpg4","MooV", "WVC1", "WMVA", "WMV3", "WMV2", "M4V ", "VfW "];
var moviedict = new Dict();
var movies = new Object();
// "movie" : jit.movie object,
// "index" : movie index,
// "listener" : movie listener,
var movnames = [];
var curmovob = null;
var movct = 0;
var savedargs = new Array();
var dummymatrix = new JitterMatrix(4,"char",320,240);
var swaplisten=null;
const outtex = "jit_gl_texture";
const outmat = "jit_matrix";
function postln(arg) {
if(verbose)
post(arg+"\n");
}
postln.local = 1;
const is820 = (max.version >= 820);
var tmp = JitterObject("jit.movie");
const engine = tmp.engine;
tmp.freepeer();
const isviddll = (engine === "viddll");
if(isviddll) {
postln("polymovie using viddll engine");
}
else {
postln("polymovie using avf engine");
}
// bug in viddll engine asyncread if version is < 8.2
const useasync = (is820 || !isviddll);
// force override here if asyncread is causing issues
//const useasync = false;
function bang() {
if(!drawtexture())
drawmovies();
}
function swapcallback(event){
//post("callback: " + event.subjectname + " sent "+ event.eventname + " with (" + event.args + ")\n");
// if context is root we use swap, if jit.gl.node use draw
if ((event.eventname=="swap" || event.eventname=="draw")) {
drawmovies();
}
}
swapcallback.local = 1;
function movcallback(event){
if(event.eventname==="read") {
var m = movies[event.subjectname];
finalizemovie(m);
if(readcount == movnames.length) {
finalizeread();
}
}
else if(event.eventname==="seeknotify") {
outlet(2, "seeknotify", target);
}
else if(event.eventname==="loopreport") {
outlet(2, "loopnotify", target);
}
//post("callback: " + event.subjectname + " sent "+ event.eventname + " with (" + event.args + ")\n");
}
movcallback.local = 1;
function drawmovies() {
if(!targets.length) {
drawmovie();
}
else {
outtype = outtex;
outnames = [];
outpositions = [];
for(i = 0; i < targets.length; i++) {
var o = targets[i];
if(!o)
continue;
if(drawtexture()) {
o.matrixcalc(dummymatrix,dummymatrix);
outnames.push(o.texture_name);
}
else {
outtype = outmat;
var movdim = o.movie_dim;
var matdim = dummymatrix.dim;
if(movdim[0]!=matdim[0] || movdim[1]!=matdim[1])
dummymatrix.dim=movdim;
o.matrixcalc(dummymatrix,dummymatrix);
outnames.push(dummymatrix.name);
}
outpositions.push(o.position);
}
outlet(0, outtype, outnames);
outlet(2, "position", outpositions);
}
}
drawmovies.local = 1;
function drawmovie() {
if(!curmovob)
return;
var o = curmovob;
if(drawtexture()) {
o.matrixcalc(dummymatrix,dummymatrix);
outlet(0,outtex,o.texture_name);
}
else {
var movdim = o.movie_dim;
var matdim = dummymatrix.dim;
if(movdim[0]!=matdim[0] || movdim[1]!=matdim[1])
dummymatrix.dim=movdim;
o.matrixcalc(dummymatrix,dummymatrix);
outlet(0,outmat,dummymatrix.name);
}
outlet(2, "position", o.position);
}
drawmovie.local = 1;
function drawtexture() {
return !(drawto==="");
}
drawtexture.local = 1;
function getmovie_index(i) {
if(i>=0 && i<movnames.length)
return movies[movnames[i]]["movie"];
return null;
}
getmovie_index.local = 1;
function getmovie_name(n) {
return movies[n]["movie"];
}
getmovie_name.local = 1;
/////////////////////////////////////////////
// #mark Read and Init
/////////////////////////////////////////////
function setdrawto(arg) {
if(arg === drawto || !arg) {
// bounce
return;
}
postln("setdrawto " + arg);
drawto=arg;
setmovieattr("drawto",drawto);
setmovieattr("output_texture",1);
if(swaplisten)
swaplisten.subjectname = "";
swaplisten = new JitterListener(drawto,swapcallback);
}
function clear() {
settarget(0);
readcount = 0;
curmovob = null;
for(n in movies) {
getmovie_name(n).freepeer();
}
movnames.splice(0,movnames.length);
movies = new Object();
moviedict.clear();
movct = 0;
outlet(2, "movielist", "clear");
}
function readfolder(path) {
clear();
appendfolder(path);
}
function appendfolder(path) {
var f = new Folder(path);
var fpath = f.pathname;
var fcount = f.count;
f.reset();
while (!f.end) {
if(ismovie(f.filetype)) {
postln(fpath + f.filename);
addmovie(fpath + f.filename);
}
f.next();
}
doargattrs();
if(!useasync) {
finalizeread();
}
}
function appendmovie(path) {
addmovie(path)
doargattrs();
}
function dictionary(dname) {
postln("reading dictionary " + dname);
var d = new Dict(dname);
var keys = d.getkeys();
if(!keys)
return;
clear();
// convert single value to array
if(typeof(keys) === "string") {
keys = [keys];
}
keys.forEach(function (key, i) {
var m = d.get(key);
addmovie(m.get("path"));
});
// apply arg attrs first...
doargattrs();
// then apply dictionary attrs
keys.forEach(function (key, i) {
var m = d.get(key)
var attrs = m.get("attributes");
if(attrs) {
var akeys = attrs.getkeys();
var movie = getmovie_index(i);
// convert single value to array
if(typeof(akeys) === "string") {
akeys = [akeys];
}
akeys.forEach(function (akey, j) {
//postln("attribute: " + akey + ", vals: " + attrs.get(akey));
if(movie) {
sendmovie(movie, akey, attrs.get(akey));
}
});
}
});
if(!useasync) {
finalizeread();
}
}
function writedict() {
writeloopstatetodict(curmovob);
if(arguments.length) {
moviedict.export_json(arguments[0]);
}
else {
moviedict.export_json();
}
}
function readdict() {
var d = new Dict();
if(arguments.length) {
d.import_json(arguments[0]);
}
else {
d.import_json();
}
dictionary(d.name);
}
function getdict() {
writeloopstatetodict(curmovob);
outlet(2, "dictionary", moviedict.name);
}
// from patcherargs
function done() {
saveargs=false;
}
function addmovie(path) {
var o = new JitterObject("jit.movie");
o.autostart=0;
o.automatic=0;
if(!swaplisten) {
postln("disable output_texture")
o.output_texture=0;
}
else {
postln("enable output_texture")
o.output_texture=1;
o.drawto=drawto;
}
// engine specific stuff goes here...
if(isviddll) {
o.cache_size = cache_size;
}
var idx = movct++;
var regname = o.getregisteredname();
movnames.push(regname);
var m = new Object();
movies[regname] = m;
m.movie = o;
m.index = idx;
m.listener = new JitterListener(regname, movcallback);
// placeholder values, will overwrite in finalizemovie
moviedict.setparse(m.index, '{ "name" : "'+m.movie.moviename+'", "path" : "' + m.movie.moviepath + '"}' );
// placeholder for proper umenu ordering
outlet(2, "movielist", "append", m.path);
if(useasync) {
o.asyncread(path);
}
else {
o.read(path);
finalizemovie(m);
}
}
addmovie.local = 1;
function ismovie(t) {
for(f in filetypes) {
if(filetypes[f]===t)
return true;
}
return false;
}
ismovie.local = 1;
function finalizeread() {
outlet(2, "readfolder", "done", readcount);
outlet(2, "dictionary", moviedict.name);
}
finalizeread.local = 1;
function finalizemovie(m) {
readcount++;
moviedict.replace(m.index+"::name", m.movie.moviename);
moviedict.replace(m.index+"::path", m.movie.moviepath);
// overwrite full path with filename
outlet(2, "movielist", "setitem", m.index, m.movie.moviename);
postln("movie info for movie index: "+m.index);
postln("name: "+m.movie.moviename);
}
finalizemovie.local = 1;
// maybe not an issue, but only write looppoints on movie changes or dictionary writes
function writeloopstatetodict(ob) {
if(ob) {
var idx = movies[ob.getregisteredname()].index;
moviedict.replace(idx + "::attributes::looppoints_secs", ob.looppoints_secs);
}
}
writeloopstatetodict.local = 1;
// loop state is reset on file read, so grab it from the dictionary when playback triggered
function readloopstatefromdict(ob) {
if(ob) {
var idx = movies[ob.getregisteredname()].index;
if(moviedict.contains(idx + "::attributes::looppoints_secs")) {
ob.looppoints_secs = moviedict.get(idx + "::attributes::looppoints_secs");
}
}
}
readloopstatefromdict.local = 1;
/////////////////////////////////////////////
// #mark Playback
/////////////////////////////////////////////
function settarget(t) {
postln("setting target " + t);
target = t;
if(target === 0 && targets.length) {
curmovob = targets[0];
targets.splice(0, targets.length);
postln("target length is: " + targets.length);
}
else if(target > 0) {
if(target <= targets.length)
curmovob = targets[target - 1];
else
curmovob = null;
}
}
function play() {
var i=0;
if(arguments.length)
var i=arguments[0];
if(movieindexvalid(i)) {
endmovie();
curmov = i;
curmovob = getmovie_index(curmov);
postln("playing movie: " + curmov + " " + curmovob.moviefile);
if(!isstopped || target > 0)
doplay();
curmovob.loop = loopmode;
readloopstatefromdict(curmovob);
var loopi = curmovob.looppoints_secs[0] / curmovob.seconds;
var loopo = curmovob.looppoints_secs[1] / curmovob.seconds;
// output normalized looppoints for GUI
outlet(2, "looppoints", loopi, loopo);
if(isviddll && cachemode == cachemode_auto) {
postln("autosizing cache: "+cache_sizeauto);
curmovob.cache_size = cache_sizeauto;
}
}
if(target > 0) {
targets[target-1] = curmovob;
postln("added target, length is: " + targets.length);
}
}
function start() {
doplay();
}
function stop() {
if(curmovob)
curmovob.stop();
isstopped = true;
}
function scrub(pos) {
if(curmovob) {
curmovob.position = pos;
}
}
function doplay() {
if(curmovob) {
curmovob.start();
}
isstopped = false;
}
doplay.local = 1;
function endmovie() {
if(curmovob) {
curmovob.stop();
writeloopstatetodict(curmovob);
if(isviddll && curmovob && cachemode == cachemode_auto) {
postln("zeroing cache");
curmovob.cache_size = 0;
}
}
}
endmovie.local = 1;
function movieindexvalid(idx) {
return (idx < movnames.length && idx >= 0);
}
movieindexvalid.local = 1;
/////////////////////////////////////////////
// #mark Args Attrs and Messages
/////////////////////////////////////////////
function anything() {
if(saveargs) {
var a = arrayfromargs(arguments);
var e = messagename+","+a.join();
savedargs.push(e);
}
if(curmovob) {
var a = arrayfromargs(arguments);
sendmovie(curmovob, messagename, a);
}
}
function sendmovies() {
var a = arrayfromargs(arguments);
var mess = a[0];
if(a.length>1)
a.splice(0,1)
for(n in movies) {
sendmovie(getmovie_name(n),mess, a);
}
}
// special case handlers for position and loop attrs
function position(p) {
if(curmovob) {
curmovob.position = p;
}
}
function loop(state) {
loopmode = state;
if(curmovob) {
curmovob.loop = loopmode;
}
}
function looppoints(loopi, loopo) {
if(curmovob) {
if(loopi <= 1. && loopo <= 1.) {
// special polymovie normalized looppoints
var loopsecin = (loopi < loopo ? loopi : loopo) * curmovob.seconds;
var loopsecout = (loopi < loopo ? loopo : loopi) * curmovob.seconds;
curmovob.looppoints_secs = [loopsecin, loopsecout];
}
else {
// conventional looppoints
curmovob.looppoints = [loopi, loopo];
}
}
}
function automatic(v) {
post("modifying automatic unsupported\n");
}
function autostart(v) {
post("modifying autostart unsupported\n");
}
function output_texture(v) {
post("modifying output_texture unsupported\n");
}
function sendmovie(movie, mess, args) {
if (Function.prototype.isPrototypeOf(movie[mess])) {
postln("sending message " + mess + " with args " + args);
movie[mess](args);
}
else if(mess.search("get")==0) {
var attr=mess.substr(3, mess.length);
postln("getting attr " + attr);
outlet(1, attr, movie[attr]);
}
else {
postln("setting attr " + mess + " with args " + args);
movie[mess] = args;
var regname = movie.getregisteredname();
var idx = movies[regname].index;
moviedict.replace(idx + "::attributes::" + mess, args);
}
}
sendmovie.local = 1;
function doargattrs() {
for(n in movies) {
var m = getmovie_name(n);
for(i in savedargs) {
var str = savedargs[i];
var ary = str.split(",");
sendmovie(m, ary[0], ary.slice(1,ary.length));
}
}
}
doargattrs.local = 1;
function setmovieattr(arg, val) {
for(n in movies)
getmovie_name(n)[arg] = val;
}
setmovieattr.local = 1; |
'use strict';
const _ = require('lodash');
const assert = require('assert');
const Bluebird = require('bluebird');
const __ = require('../../..');
describe('IsFulfilled', () => {
it('should provide a better readable alias', () => {
__.assertThat(__.isFulfilledWith, __.is(__.fulfilled));
});
describe('fulfilled', () => {
describe('without argument', () => {
let sut;
beforeEach(() => {
sut = __.fulfilled();
});
it('should return a promise', () => {
const aFulfilledPromise = Bluebird.resolve('a value');
const result = sut.matches(aFulfilledPromise);
assert.ok(result);
assert.ok(_.isFunction(result.then));
});
it('should match fulfilled promises', () => {
const aFulfilledPromise = Bluebird.resolve('a value');
return sut.matches(aFulfilledPromise).then((value) => {
assert.ok(value);
});
});
it('should not match rejected promises', () => {
const aRejectedPromise = Bluebird.reject(new Error('rejected for a reason'));
return sut.matches(aRejectedPromise).then((value) => {
assert.equal(value, false);
});
});
it('should wait for pending promises', (done) => {
let resolveFn;
const deferred = new Bluebird((resolve) => {
resolveFn = resolve;
});
sut.matches(deferred).then((value) => {
assert.ok(value);
})
.nodeify(done);
resolveFn();
});
it('should describe nicely', () => {
const description = new __.Description();
sut.describeTo(description);
__.assertThat(description.get(), __.equalTo('a fulfilled promise'));
});
});
describe('with a value', () => {
let sut;
beforeEach(() => {
sut = __.fulfilled('a value');
});
it('should return a promise', () => {
const aFulfilledPromise = Bluebird.resolve('a value');
const result = sut.matches(aFulfilledPromise);
assert.ok(result);
assert.ok(_.isFunction(result.then));
});
it('should match fulfilled promise with equivalent value', () => {
const aFulfilledPromise = Bluebird.resolve('a value');
return sut.matches(aFulfilledPromise).then((value) => {
assert.ok(value);
});
});
it('should not match fulfilled promise with different value', () => {
const aFulfilledPromise = Bluebird.resolve('another value');
return sut.matches(aFulfilledPromise).then((value) => {
assert.equal(value, false);
});
});
it('should not match rejected promise', () => {
const aRejectedPromise = Bluebird.reject(new Error('a value'));
return sut.matches(aRejectedPromise).then((value) => {
assert.equal(value, false);
});
});
it('should wait for pending promises', (done) => {
let resolveFn;
const deferred = new Bluebird((resolve) => {
resolveFn = resolve;
});
sut.matches(deferred).then((value) => {
assert.ok(value);
})
.nodeify(done);
resolveFn('a value');
});
describe('description', () => {
let description;
beforeEach(() => {
description = new __.Description();
});
it('should contain value', () => {
sut.describeTo(description);
__.assertThat(description.get(), __.equalTo('a promise fulfilled with "a value"'));
});
it('should contain mismatched value', () => {
const actual = Bluebird.resolve('another value');
return sut.describeMismatch(actual, description).then(() => {
__.assertThat(description.get(), __.equalTo('fulfillment value: was "another value"'));
});
});
it('should contain rejected reason', () => {
const actual = Bluebird.reject(new Error('for a reason'));
return sut.describeMismatch(actual, description).then(() => {
__.assertThat(description.get(), __.allOf(__.containsString('was'), __.containsString('rejected'), __.containsString('"for a reason"')));
});
});
});
});
describe('with a matcher', () => {
let sut;
beforeEach(() => {
sut = __.fulfilled(__.containsString('expected'));
});
it('should match fulfilled promise with matching values', () => {
const aFulfilledPromise = Bluebird.resolve('expected value');
return sut.matches(aFulfilledPromise).then((value) => {
assert.ok(value);
});
});
it('should not match fulfilled promise with nonmatching value', () => {
const aFulfilledPromise = Bluebird.resolve('another value');
return sut.matches(aFulfilledPromise).then((value) => {
assert.equal(value, false);
});
});
it('should not match rejected promise', () => {
const aRejectedPromise = Bluebird.reject(new Error('rejected for expected reason'));
return sut.matches(aRejectedPromise).then((value) => {
assert.equal(value, false);
});
});
it('should wait for pending promises', (done) => {
let resolveFn;
const deferred = new Bluebird((resolve) => {
resolveFn = resolve;
});
sut.matches(deferred).then((value) => {
assert.ok(value);
})
.nodeify(done);
resolveFn('expected value');
});
describe('description', () => {
let description;
beforeEach(() => {
description = new __.Description();
});
it('should contain matcher description', () => {
sut.describeTo(description);
__.assertThat(description.get(), __.equalTo('a promise fulfilled with a string containing "expected"'));
});
it('should contain mismatched value', () => {
const actual = Bluebird.resolve('another value');
return sut.describeMismatch(actual, description).then(() => {
__.assertThat(description.get(), __.equalTo('fulfillment value: was "another value"'));
});
});
it('should contain mismatch description', () => {
sut = __.fulfilled(__.hasProperties({
expected: 'value',
other: 'property'
}));
const actual = Bluebird.resolve({expected: 'another value', other: 'property'});
return sut.describeMismatch(actual, description).then(() => {
__.assertThat(description.get(), __.equalTo('fulfillment value: expected was "another value"'));
});
});
it('should contain rejected reason', () => {
const actual = Bluebird.reject(new Error('for a reason'));
return sut.describeMismatch(actual, description).then(() => {
__.assertThat(description.get(), __.allOf(__.containsString('was'), __.containsString('rejected'), __.containsString('"for a reason"')));
});
});
});
});
describe('with a promising matcher', () => {
let sut;
beforeEach(() => {
sut = __.fulfilled(__.contains(__.willBe('expected')));
});
it('should match fulfilled promise with matching values', () => {
const aFulfilledPromise = Bluebird.resolve([
Bluebird.resolve('expected')
]);
return sut.matches(aFulfilledPromise).then((value) => {
assert.ok(value);
});
});
it('should not match fulfilled promise with nonmatching value', () => {
const aFulfilledPromise = Bluebird.resolve([
Bluebird.resolve('another value')
]);
return sut.matches(aFulfilledPromise).then((value) => {
assert.equal(value, false);
});
});
it('should wait for pending promises', (done) => {
let resolveFn;
const deferred = new Bluebird((resolve) => {
resolveFn = resolve;
});
const aFulfilledPromiseContainingAPendingPromise = Bluebird.resolve([deferred]);
sut.matches(aFulfilledPromiseContainingAPendingPromise).then((value) => {
assert.ok(value);
})
.nodeify(done);
resolveFn('expected');
});
describe('description', () => {
let description;
beforeEach(() => {
description = new __.Description();
});
it('should contain matcher description', () => {
sut.describeTo(description);
__.assertThat(description.get(), __.equalTo('a promise fulfilled with [a promise fulfilled with "expected"]'));
});
it('should contain mismatch description', () => {
const actual = Bluebird.resolve([Bluebird.resolve('another value')]);
return sut.describeMismatch(actual, description).then(() => {
__.assertThat(description.get(), __.equalTo('fulfillment value: item 0: fulfillment value: was "another value"\n'));
});
});
});
});
});
});
|
Package.describe({
name: 'zurb:foundation-sites',
summary: 'Foundation 6 - The most advanced responsive front-end framework in the world.',
version: '6.3.0',
git: 'https://github.com/zurb/foundation-sites.git',
documentation: 'meteor-README.md'
});
Package.onUse(function(api) {
api.versionsFrom('1.2.1');
api.imply('fourseven:scss@3.4.1');
api.use(['ecmascript', 'jquery', 'fourseven:scss@3.4.1'], 'client');
api.addFiles('dist/js/foundation.js', 'client');
api.addFiles([
'scss/foundation.scss',
'scss/_global.scss',
'scss/settings/_settings.scss',
'scss/components/_accordion-menu.scss',
'scss/components/_accordion.scss',
'scss/components/_badge.scss',
'scss/components/_breadcrumbs.scss',
'scss/components/_button-group.scss',
'scss/components/_button.scss',
'scss/components/_callout.scss',
'scss/components/_close-button.scss',
'scss/components/_drilldown.scss',
'scss/components/_dropdown-menu.scss',
'scss/components/_dropdown.scss',
'scss/components/_flex.scss',
'scss/components/_float.scss',
'scss/components/_label.scss',
'scss/components/_media-object.scss',
'scss/components/_menu-icon.scss',
'scss/components/_menu.scss',
'scss/components/_off-canvas.scss',
'scss/components/_orbit.scss',
'scss/components/_pagination.scss',
'scss/components/_progress-bar.scss',
'scss/components/_responsive-embed.scss',
'scss/components/_reveal.scss',
'scss/components/_slider.scss',
'scss/components/_sticky.scss',
'scss/components/_switch.scss',
'scss/components/_table.scss',
'scss/components/_tabs.scss',
'scss/components/_thumbnail.scss',
'scss/components/_title-bar.scss',
'scss/components/_tooltip.scss',
'scss/components/_top-bar.scss',
'scss/components/_visibility.scss',
'scss/forms/_checkbox.scss',
'scss/forms/_error.scss',
'scss/forms/_fieldset.scss',
'scss/forms/_forms.scss',
'scss/forms/_help-text.scss',
'scss/forms/_input-group.scss',
'scss/forms/_label.scss',
'scss/forms/_meter.scss',
'scss/forms/_progress.scss',
'scss/forms/_range.scss',
'scss/forms/_select.scss',
'scss/forms/_text.scss',
'scss/grid/_classes.scss',
'scss/grid/_column.scss',
'scss/grid/_flex-grid.scss',
'scss/grid/_grid.scss',
'scss/grid/_gutter.scss',
'scss/grid/_layout.scss',
'scss/grid/_position.scss',
'scss/grid/_row.scss',
'scss/grid/_size.scss',
'scss/typography/_alignment.scss',
'scss/typography/_base.scss',
'scss/typography/_helpers.scss',
'scss/typography/_print.scss',
'scss/typography/_typography.scss',
'scss/util/_breakpoint.scss',
'scss/util/_color.scss',
'scss/util/_flex.scss',
'scss/util/_mixins.scss',
'scss/util/_selector.scss',
'scss/util/_unit.scss',
'scss/util/_util.scss',
'scss/util/_value.scss'
], 'client', {isImport: true});
});
|
var ischool = ischool || {}; //namespace : ischool
ischool.WindowResizeHandler = {}; //播放筆劃的物件,只負責播放筆劃
/*
在拖拉更改視窗大小的過程會一直觸發 window.resize 事件,造成效能慢,
這段程式碼偵測使用者改變視窗大小的動作已結束之後,才觸發事件。
*/
ischool.WindowResizeHandler.handle = function(afterWindowResize) {
/* 檢查 resize 是否結束了 */
var rtime = new Date(1, 1, 2000, 12,00,00);
var timeout = false;
var delta = 200;
/*
idea : 當window 經過 200 millisecond 都沒有觸發 resize 事件,
就認定其已經完成調整視窗大小的動作。
*/
$(window).resize(function() {
rtime = new Date();
if (timeout === false) {
timeout = true;
setTimeout(resizeend, delta);
}
});
var resizeend = function() {
if (new Date() - rtime < delta) {
setTimeout(resizeend, delta);
} else {
timeout = false;
if (afterWindowResize)
afterWindowResize();
}
};
}
var ischool = ischool || {}; //namespace : ischool
ischool.CanvasResizer = {}; //播放筆劃的物件,只負責播放筆劃
ischool.CanvasResizer.handle = function(options) {
//containerID, widthDiff, heightDiff, afterResizedHandler
var targetContainerID = options.containerID ;
var targetCanvasID ='myCanvas';
var widthDiff = (options.widthDiff) ? options.widthDiff : 0;
var heightDiff = (options.heightDiff) ? options.heightDiff : 0;
var afterResizedHandler = options.afterResizedHandler;
var canvasWidth = 0;
var canvasHeight = 0;
/* 處理 Window Resize 事件,確定 Window Resize 後才會觸發事件,而不會在 Window Resize 過程中一直觸發,影響效能 */
ischool.WindowResizeHandler.handle(function() {
resizeUI();
});
var resizeUI = function(){
canvasWidth = $('#' + targetContainerID ).width() - 3;
canvasHeight = $('#' + targetContainerID ).height() - 3;
/* 若還沒有 Canvas */
resetCanvas(canvasWidth, canvasHeight, targetCanvasID);
if (afterResizedHandler) {
afterResizedHandler();
}
};
var resetCanvas = function(canvasWidth, canvasHeight, canvasID) {
$('#' + targetContainerID).html('');
var canvasString = "<canvas id='" + canvasID + "' width='" + canvasWidth + "' height='" + canvasHeight + "' style='padding: 0px; margin: 0px; border: 0px; overflow: hidden;'></canvas>";
$(canvasString).appendTo('#' + targetContainerID);
};
resizeUI();
}
var ischool = ischool || {}; //namespace : ischool
ischool.StrokePlayer = {}; //播放筆劃的物件,只負責播放筆劃
/* 宣告一個『建立播放筆劃物件』的方法 */
ischool.StrokePlayer.create = function(containerID) {
var aryStrokes = []; //記錄所有筆劃
var canvasID = "myCanvas"; //預設建立的 canvas 的 ID
var playerQueue = []; //放置 Painter 的集合。一筆劃(stroke)由一個 Painter 物件處理。
var playInterval = 100; //millisecond, 每隔多少時間取一次筆劃的點資料來畫圖。
var speed = 1 ; //播放速度,浮點數。
var afterCanvasResize ; //將 Canvas Resize 事件廣播出去。因為 window resize 時會把 Canvas 重設,所以把。
ischool.CanvasResizer.handle({
containerID : containerID,
widthDiff : 0,
heightDiff : 0,
afterResizedHandler : function() {
//重劃所有的筆劃
if (drawAllPoints)
drawAllPoints();
//將 Canvas Resize 事件廣播出去。
if (afterCanvasResize)
afterCanvasResize();
}
});
/* 此函數要確保這些 painter 物件可以按照順序執行,
一個 stroke 執行完畢後才可以執行下一個 stroke 。
*/
var playByOrder = function() {
var isProcessing = false
var i=0;
for(i=0; i<playerQueue.length; i++) {
item = playerQueue[i] ;
if (item.getStatus() == 1){ //處理中
isProcessing = true ;
break ;
}
}
if (!isProcessing) {
for(i=0; i<playerQueue.length; i++) {
item = playerQueue[i] ;
if (item.getStatus() == 0){ //尚未處理
item.draw( speed, playInterval );
break ;
}
}
}
};
var drawAllPoints = function() {
//再重劃所有點
$(aryStrokes).each(function(index, stroke) {
if (stroke) {
if (stroke.points.length > 0) {
var ctx = document.getElementById(canvasID).getContext('2d');
ctx.beginPath(); //若不加此行則全部會變成最後的顏色及粗細
ctx.lineWidth = stroke.pen;
ctx.strokeStyle = stroke.color ;
var initPt = stroke.points[0]
ctx.moveTo(initPt.x, initPt.y);
$(stroke.points).each(function(index, pt) {
ctx.lineTo(pt.x, pt.y);
//console.log("color:" + _lineColor); //為什麼設定幾次就會有幾個值?
ctx.stroke();
});
}
}
});
}
return {
/*
播放所有筆劃,按照順序與時間。
strokes : 所有筆劃資料
drawSpeed : 播放速度, float number
drawInterval : 取得點資料的時間間隔,值越小畫面越順暢(不會 lag)。 millisecond。
*/
play : function(strokes, drawSpeed, drawInterval) {
this.clean(); //清空畫面
this.stop(); //停止目前所有播放動作
if (strokes) {
aryStrokes = strokes;
playerQueue = [];
$(aryStrokes).each(function(index, stroke) {
/* 傳入要畫的點集合,以及畫完後要呼叫的函數 */
var painter = StrokePainter(canvasID, stroke, playByOrder) ;
if (painter) {
playerQueue.push(painter);
}
});
if (drawInterval)
playInterval = drawInterval ; //重設取點資料畫出的時間間隔
if (drawSpeed)
speed = drawSpeed ;
playByOrder();
}
},
/* 清除畫面成為空白 */
clean : function() {
//alert(data);
var el = document.getElementById(canvasID);
var ctx = el.getContext("2d");
ctx.clearRect(0,0,el.width,el.height);
},
/*
全部立刻重劃,不需要按時間重劃。
若傳入筆劃(strokes),就畫出傳入的筆劃。否則畫出內部儲存的筆劃 (aryStrokes)。
*/
drawNow : function(strokes) {
this.clean();
aryStrokes = strokes ;
drawAllPoints();
},
/* 立刻停止 */
stop : function() {
for(i=0; i<playerQueue.length; i++) {
item = playerQueue[i] ;
if (item.getStatus() != 2){ //尚未完成
item.stop();
}
}
},
/* 取得有多少筆劃 */
getStrokeCount : function() {
return aryStrokes.length ;
},
/* 播放單一筆劃。 */
addStroke : function(stroke) {
aryStrokes.push(stroke);
if (stroke.points.length ==0)
return ;
/* 傳入要畫的點集合,以及畫完後要呼叫的函數 */
var painter = StrokePainter(canvasID,stroke, playByOrder) ;
if (painter) {
playerQueue.push(painter);
}
playByOrder();
},
/* 取得系統建立的 CanvasID */
getCanvasID : function() {
return canvasID;
},
setCanvasResizeHandler : function(afterCanvasResizedHandler) {
afterCanvasResize = afterCanvasResizedHandler
},
setBackgroundImage : function(bgOptions) {
var $container = $('#' + containerID) ;
if (bgOptions.color)
$container.css("background-color", bgOptions.color);
if (bgOptions.imageUrl)
$container.css("background-image", "url(" + bgOptions.imageUrl + ")" );
if (bgOptions.repeat)
$container.css("background-repeat", bgOptions.repeat);
if (bgOptions.position)
$container.css("background-position", bgOptions.position);
if (bgOptions.size)
$container.css("background-size", bgOptions.size);
$('#' + containerID).css("background-image","url(" + bg_url + ") ").css("background-size", "100% 100%");
if (!is_repeated)
$('#' + containerID).css("background-repeat", "no-repeat");
}
};
}
/* factory function to create a player object for replay points */
var StrokePainter = function(canvasID, stroke, finishHandler) {
if (! stroke)
return null;
if (stroke.points.length ==0)
return null ;
var status = 0 ; //0: 尚未開始 , 1: 處理中 , 2: 已處理完成
var ctx ;
var pts = stroke.points ;
var currentIndex = 0;
var lineColor = stroke.color;
var lineWidth = stroke.pen;
var initPt = pts[0];
var initTime = initPt.time ; //第一個點的時間
var beginPlayTime ; //開始play 的時間
var speed = 1; //播放速度
var playInterval =100; //取樣時間
var isInterrupted = false ; //是否中斷。當執行 stop 時,會將此變數設為 true。
var beginDraw = function() {
status = 1;
/* 這筆劃開始畫點時的時間 */
if (!beginPlayTime)
beginPlayTime = (new Date()).getTime();
/* ctx : 因為這段程式碼速度慢,如果放在上面,到執行 beginDraw 會太慢,
導致兩個 Painter 同時執行,會造成贅連線的狀況,所以放在這裡判斷,讓前面的程式執行快一點,好更改 status 的狀態。 */
if (!ctx) {
var el = document.getElementById(canvasID)
ctx = el.getContext("2d");
ctx.beginPath();
ctx.lineWidth = lineWidth;
ctx.strokeStyle = lineColor ;
ctx.moveTo(initPt.x, initPt.y);
console.log( " move to (" + initPt.x + "," + initPt.y + ")");
}
console.log(' == beginDraw == currentIndex : ' + currentIndex );
if (pts.length ==0)
return ;
if (currentIndex > pts.length -1)
return ;
var firstPt = pts[currentIndex];
var i = currentIndex;
var currentPlayTime = (new Date()).getTime(); //這一輪 play 的時間,因為每 playInterval 長度就 play 一輪。
var currentTimeDiff = (currentPlayTime - beginPlayTime) * speed ; //這一輪距離開始 play已經過了多少時間?
for (i=currentIndex; i<pts.length; i++) {
//判斷是否中斷
if (isInterrupted) {
status = 2;
console.log(' == isInterrupted == currentIndex : ' + currentIndex );
if (finishHandler)
finishHandler();
return ;
}
var pt = pts[i];
var timeDiff = pt.time - initTime; //計算這個點的時間距離第一個點過了多少時間
if (timeDiff < currentTimeDiff) {
//ctx.lineWidth = pt.lw ;
ctx.lineTo(pt.x, pt.y);
ctx.stroke();
console.log(i + " : (" + pt.x + "," + pt.y + ") , count :" + pts.length + "," + timeDiff + "," + currentTimeDiff);
}
else
break;
}
if (i >= pts.length) {
status = 2 ;
if (finishHandler)
finishHandler();
}
else {
currentIndex = i;
window.setTimeout(beginDraw, playInterval); //每隔多少時間取一次筆劃的點資料畫圖
}
}
return {
draw : function(drawSpeed, drawInterval) {
speed =drawSpeed ;
playInterval = drawInterval ;
isInterrupted = false ;
beginDraw();
},
//0: 尚未開始 , 1: 處理中 , 2: 已處理完成
getStatus : function() {
return status;
},
stop : function() {
isInterrupted = true ;
}
}
};
//定義 Touch drawing 行為的 jquery plugin
//var defineTouchDrawing = function() {
$.fn.drawTouch = function(option) {
var defaults = {
onDrawing : null,
onStart : null,
onEnd : null,
lineWidth : 4,
lineColor : "#000000"
};
var _lineColor = (option.lineColor) ? (option.lineColor) : "#000000";
var options = $.extend(defaults, option) ;
return this.each(function(){
var raiseDrawingCallback = function(x, y, color) {
if (options.onDrawing) {
options.onDrawing({time: (new Date()).getTime(), x: x, y: y }); //, lw: options.lineWidth, c: color});
}
};
var el = this;
var ctx = el.getContext("2d");
ctx.lineWidth = options.lineWidth;
var canvasX = $(el).offset().left;
var canvasY = $(el).offset().top;
var start = function(e) {
var touchEvent = e.originalEvent.changedTouches[0];
ctx.beginPath();
ctx.lineJoin = 'round';
ctx.lineCap = "round";
//var x = touchEvent.pageX;
//var y = touchEvent.pageY;
var x = Math.floor(touchEvent.pageX - canvasX );
var y = Math.floor(touchEvent.pageY - canvasY );
ctx.moveTo(x, y);
if (options.onStart){
options.onStart();
}
raiseDrawingCallback(x, y, _lineColor);
};
var move = function(e) {
var touchEvent = e.originalEvent.changedTouches[0];
e.preventDefault();
var x = Math.floor(touchEvent.pageX - canvasX );
var y = Math.floor(touchEvent.pageY - canvasY );
ctx.lineTo(x, y);
ctx.strokeStyle = options.lineColor ;
ctx.stroke();
raiseDrawingCallback(x, y, _lineColor);
//console.log(options);
};
var end = function(e) {
if (options.onEnd)
options.onEnd();
}
$(this).touchstart(start);
$(this).touchmove(move);
$(this).touchend(end);
});
};
//};
//定義 mouse drawing 行為的 jquery plugin
//var defineMouseDrawing = function() {
$.fn.drawMouse = function(option) {
var defaults = {
onDrawing : null,
onStart : null,
onEnd : null,
lineWidth : 4,
lineColor : "#000000"
};
var options = $.extend(defaults, option) ;
var _lineColor = (option.lineColor) ? (option.lineColor) : "#000000";
return this.each(function(){
var raiseDrawingCallback = function(x, y, color) {
if (options.onDrawing){
options.onDrawing({time: (new Date()).getTime(), x: x, y: y }); //, lw: options.lineWidth, c:color});
}
};
var el = this;
var ctx = el.getContext("2d");
ctx.lineWidth = options.lineWidth ;
var canvasX = $(el).offset().left;
var canvasY = $(el).offset().top;
var clicked = 0;
var previousX ;
var previousY;
var start = function(e) {
clicked = 1;
ctx.beginPath();
ctx.lineJoin = 'round';
ctx.lineCap = "round";
//var x = e.pageX - el.offsetX;
//var y = e.pageY - el.offsetY ;
var x = Math.floor(e.pageX - canvasX );
var y = Math.floor(e.pageY - canvasY );
previousX = x;
previousY = y;
ctx.moveTo(x, y);
if (options.onStart)
options.onStart();
raiseDrawingCallback(x, y, options.lineColor);
};
var move = function(e) {
if(clicked){
//var x = e.pageX;
//var y = e.pageY;
var x = Math.floor(e.pageX - canvasX );
var y = Math.floor(e.pageY - canvasY );
ctx.lineTo(x, y);
//ctx.arcTo(previousX, previousY, x, y , 5);
ctx.strokeStyle = options.lineColor ;
//console.log("color:" + _lineColor); //為什麼設定幾次就會有幾個值?
ctx.stroke();
previousX = x;
previousY = y;
//console.log(x + "," + y);
raiseDrawingCallback(x, y, _lineColor);
}
};
var stop = function(e) {
clicked = 0;
if (options.onEnd)
options.onEnd();
};
$(this).mousedown(start);
$(this).mousemove(move);
$(this).mouseup(stop);
});
};
var ischool = ischool || {}; //namespace : ischool
ischool.Painter = {}; //類似小畫家的物件,負責讓使用者書寫畫面,並收集筆劃資料,可 play, undo, redo, clean 等。
/* 宣告一個『建立小畫家物件』的方法 */
ischool.Painter.create = function(options) {
var containerID = options.containerID;
var penSize = options.penSize;
var penColor = options.penColor ;
var afterStrokeHandler = options.afterStroke; //每一筆劃完成後就會觸發此事件
//會建立 Canvas,並套用 resize,以及 play 的功能
var strokePlayer = ischool.StrokePlayer.create(containerID);
//處理 window.resize 事件
strokePlayer.setCanvasResizeHandler(function() {
initCanvasBehavior();
strokePlayer.drawNow(strokes);
});
var canvasID = strokePlayer.getCanvasID();
var strokes = []; //暫存所有的筆劃
var undoStrokes = []; //所有後悔的步驟
var points =[]; //暫存一筆劃的所有點資訊(x,y,time)
//套用 Mouse 畫圖行為 (適用 PC)
var registerMouseDrawing = function() {
$('#' + canvasID).drawMouse({
lineWidth : penSize ,
lineColor : penColor,
onStart : function(evt) {
points=[];
},
onDrawing : function(evt) {
points.push(evt);
},
onEnd : function() {
var stroke = { color: penColor , pen: penSize, points:points};
strokes.push(stroke);
undoStrokes =[];
if (afterStrokeHandler)
afterStrokeHandler(stroke);
}
});
};
//套用 Touch 畫圖行為(適用 行動裝置)
var registerTouchDrawing = function() {
$('#' + canvasID).drawTouch({
lineWidth : penSize ,
lineColor : penColor,
onStart : function(evt) {
points=[]; //reset
},
onDrawing : function(evt) {
points.push(evt);
},
onEnd : function() {
var stroke = { color: penColor , pen: penSize, points:points};
strokes.push(stroke);
undoStrokes =[];
if (afterStrokeHandler)
afterStrokeHandler(stroke);
}
});
};
var initCanvasBehavior = function() {
//1. 套用滑鼠繪圖的邏輯
registerMouseDrawing();
//2. 套用手指繪圖的邏輯 (適用平板)
registerTouchDrawing();
}
/* 改變畫布的顏色和畫筆粗細 */
var changeColorPen = function() {
$('#' + canvasID).drawMouse({ lineWidth : penSize, lineColor : penColor });
$('#' + canvasID).drawTouch({ lineWidth : penSize, lineColor : penColor });
};
return {
replay : function(speed) {
var theSpeed = (speed) ? speed : 1 ;
strokePlayer.play( strokes, speed, 10);
},
undo : function() {
strokePlayer.clean(); //清除畫面
var s = strokes.pop();
if (s)
undoStrokes.push(s);
strokePlayer.drawNow(strokes);
},
redo : function() {
strokePlayer.clean(); //清除畫面
var s = undoStrokes.pop();
if (s)
strokes.push(s);
strokePlayer.drawNow(strokes);
},
clean : function() {
strokePlayer.clean(); //清除畫面
strokes =[]; //清除所有筆畫資料
undoStrokes = [];
},
getStrokes : function() {
return strokes;
},
setStrokes : function(theStrokes) {
strokes = theStrokes ;
},
setPenColor : function(color) {
penColor = color ;
changeColorPen();
},
setPenSize : function(size) {
penSize = size ;
changeColorPen();
},
getStrokePlayer : function() {
return strokePlayer ;
},
setBackgroundImage : function( bgOptions ) {
strokePlayer.setBackgroundImage(bgOptions);
}
}
}
|
'use strict';
var angular = require('angular');
angular
.module('mwl.calendar')
.constant('calendarConfig', {
allDateFormats: {
angular: {
date: {
hour: 'ha',
day: 'd MMM',
month: 'MMMM',
weekDay: 'EEEE',
time: 'HH:mm',
datetime: 'MMM d, h:mm a'
},
title: {
day: 'EEEE d MMMM, yyyy',
week: 'Week {week} of {year}',
month: 'MMMM yyyy',
year: 'yyyy'
}
},
moment: {
date: {
hour: 'ha',
day: 'D MMM',
month: 'MMMM',
weekDay: 'dddd',
time: 'HH:mm',
datetime: 'MMM D, h:mm a'
},
title: {
day: 'dddd D MMMM, YYYY',
week: 'Semana {week} de {year}',
month: 'MMMM YYYY',
year: 'YYYY'
}
}
},
get dateFormats() {
return this.allDateFormats[this.dateFormatter].date;
},
get titleFormats() {
return this.allDateFormats[this.dateFormatter].title;
},
dateFormatter: 'angular',
showTimesOnWeekView: false,
displayAllMonthEvents: false,
i18nStrings: {
weekNumber: 'Semana {week}'
},
templates: {},
colorTypes: {
info: {
primary: '#1e90ff',
secondary: '#d1e8ff'
},
important: {
primary: '#ad2121',
secondary: '#fae3e3'
},
warning: {
primary: '#e3bc08',
secondary: '#fdf1ba'
},
inverse: {
primary: '#1b1b1b',
secondary: '#c1c1c1'
},
special: {
primary: '#800080',
secondary: '#ffe6ff'
},
success: {
primary: '#006400',
secondary: '#caffca'
}
}
});
|
import './progressDialog.html';
import './progressDialog.styl';
import './progressDialog.js';
|
describe("Time left", function() {
beforeEach(function () {
settings = new Settings();
settings.blocklist = ['www.zombo.com'];
settings.show_badge = true;
settings.time_limits = {'www.zombo.com': 10};
settings.elapsed_times = {'www.zombo.com': 6};
settings.temp_blocklist = ['canabusmart.info'];
settings.default_time_limit = 12;
settings.timerbutton_elapsed_times = {'canabusmart.info': 9};
var check_interval = 1000;
var tab = {id: 1234, url: 'http://www.zombo.com/anything'};
chrome = {
extension: {
getURL: function(){}},
tabs: {
update: function(){}},
browserAction: {
setBadgeText: function(){},
setBadgeBackgroundColor: function(){},
setIcon: function(){}
}
}
spyOn(chrome.extension, 'getURL');
spyOn(chrome.browserAction, 'setBadgeText');
spyOn(chrome.browserAction, 'setBadgeBackgroundColor');
update_times(tab, 'www.zombo.com');
var tab = {id: 1234, url: 'http://canabusmart.info/news'};
update_times(tab, 'canabusmart.info');
});
it("Calculates time left if the hostname is in the blocklist", function() {
expect(settings.elapsed_times['www.zombo.com']).toEqual(7);
});
it("Calculates time left if the hostname is in the temporary blocklist", function() {
expect(settings.timerbutton_elapsed_times['canabusmart.info']).toEqual(10);
});
});
|
import React from 'react';
import classNames from 'classnames';
import { makeStyles, useTheme } from '@material-ui/styles';
import Drawer from '@material-ui/core/Drawer';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import CssBaseline from '@material-ui/core/CssBaseline';
import List from '@material-ui/core/List';
import Typography from '@material-ui/core/Typography';
import Divider from '@material-ui/core/Divider';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';
import ChevronLeftIcon from '@material-ui/icons/ChevronLeft';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import InboxIcon from '@material-ui/icons/MoveToInbox';
import MailIcon from '@material-ui/icons/Mail';
const drawerWidth = 240;
const useStyles = makeStyles(theme => ({
root: {
display: 'flex',
},
appBar: {
transition: theme.transitions.create(['margin', 'width'], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
},
appBarShift: {
width: `calc(100% - ${drawerWidth}px)`,
transition: theme.transitions.create(['margin', 'width'], {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen,
}),
marginRight: drawerWidth,
},
menuButton: {
marginLeft: 12,
marginRight: 20,
},
hide: {
display: 'none',
},
drawer: {
width: drawerWidth,
flexShrink: 0,
},
drawerPaper: {
width: drawerWidth,
},
drawerHeader: {
display: 'flex',
alignItems: 'center',
padding: '0 8px',
...theme.mixins.toolbar,
justifyContent: 'flex-start',
},
content: {
flexGrow: 1,
padding: theme.spacing.unit * 3,
transition: theme.transitions.create('margin', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
marginRight: -drawerWidth,
},
contentShift: {
transition: theme.transitions.create('margin', {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen,
}),
marginRight: 0,
},
}));
function PersistentDrawerRight() {
const classes = useStyles();
const theme = useTheme();
const [open, setOpen] = React.useState(false);
function handleDrawerOpen() {
setOpen(true);
}
function handleDrawerClose() {
setOpen(false);
}
return (
<div className={classes.root}>
<CssBaseline />
<AppBar
position="fixed"
className={classNames(classes.appBar, {
[classes.appBarShift]: open,
})}
>
<Toolbar disableGutters={!open}>
<IconButton
color="inherit"
aria-label="Open drawer"
onClick={handleDrawerOpen}
className={classNames(classes.menuButton, open && classes.hide)}
>
<MenuIcon />
</IconButton>
<Typography variant="h6" color="inherit" noWrap>
Persistent drawer
</Typography>
</Toolbar>
</AppBar>
<main
className={classNames(classes.content, {
[classes.contentShift]: open,
})}
>
<div className={classes.drawerHeader} />
<Typography paragraph>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua. Rhoncus dolor purus non enim praesent elementum
facilisis leo vel. Risus at ultrices mi tempus imperdiet. Semper risus in hendrerit
gravida rutrum quisque non tellus. Convallis convallis tellus id interdum velit laoreet id
donec ultrices. Odio morbi quis commodo odio aenean sed adipiscing. Amet nisl suscipit
adipiscing bibendum est ultricies integer quis. Cursus euismod quis viverra nibh cras.
Metus vulputate eu scelerisque felis imperdiet proin fermentum leo. Mauris commodo quis
imperdiet massa tincidunt. Cras tincidunt lobortis feugiat vivamus at augue. At augue eget
arcu dictum varius duis at consectetur lorem. Velit sed ullamcorper morbi tincidunt. Lorem
donec massa sapien faucibus et molestie ac.
</Typography>
<Typography paragraph>
Consequat mauris nunc congue nisi vitae suscipit. Fringilla est ullamcorper eget nulla
facilisi etiam dignissim diam. Pulvinar elementum integer enim neque volutpat ac
tincidunt. Ornare suspendisse sed nisi lacus sed viverra tellus. Purus sit amet volutpat
consequat mauris. Elementum eu facilisis sed odio morbi. Euismod lacinia at quis risus sed
vulputate odio. Morbi tincidunt ornare massa eget egestas purus viverra accumsan in. In
hendrerit gravida rutrum quisque non tellus orci ac. Pellentesque nec nam aliquam sem et
tortor. Habitant morbi tristique senectus et. Adipiscing elit duis tristique sollicitudin
nibh sit. Ornare aenean euismod elementum nisi quis eleifend. Commodo viverra maecenas
accumsan lacus vel facilisis. Nulla posuere sollicitudin aliquam ultrices sagittis orci a.
</Typography>
</main>
<Drawer
className={classes.drawer}
variant="persistent"
anchor="right"
open={open}
classes={{
paper: classes.drawerPaper,
}}
>
<div className={classes.drawerHeader}>
<IconButton onClick={handleDrawerClose}>
{theme.direction === 'rtl' ? <ChevronLeftIcon /> : <ChevronRightIcon />}
</IconButton>
</div>
<Divider />
<List>
{['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => (
<ListItem button key={text}>
<ListItemIcon>{index % 2 === 0 ? <InboxIcon /> : <MailIcon />}</ListItemIcon>
<ListItemText primary={text} />
</ListItem>
))}
</List>
<Divider />
<List>
{['All mail', 'Trash', 'Spam'].map((text, index) => (
<ListItem button key={text}>
<ListItemIcon>{index % 2 === 0 ? <InboxIcon /> : <MailIcon />}</ListItemIcon>
<ListItemText primary={text} />
</ListItem>
))}
</List>
</Drawer>
</div>
);
}
export default PersistentDrawerRight;
|
define(['exports', 'aurelia-framework', '../utils/bootstrap-options'], function (exports, _aureliaFramework, _bootstrapOptions) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.AubsBtnLoadingCustomAttribute = undefined;
function _initDefineProp(target, property, descriptor, context) {
if (!descriptor) return;
Object.defineProperty(target, property, {
enumerable: descriptor.enumerable,
configurable: descriptor.configurable,
writable: descriptor.writable,
value: descriptor.initializer ? descriptor.initializer.call(context) : void 0
});
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
var desc = {};
Object['ke' + 'ys'](descriptor).forEach(function (key) {
desc[key] = descriptor[key];
});
desc.enumerable = !!desc.enumerable;
desc.configurable = !!desc.configurable;
if ('value' in desc || desc.initializer) {
desc.writable = true;
}
desc = decorators.slice().reverse().reduce(function (desc, decorator) {
return decorator(target, property, desc) || desc;
}, desc);
if (context && desc.initializer !== void 0) {
desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
desc.initializer = undefined;
}
if (desc.initializer === void 0) {
Object['define' + 'Property'](target, property, desc);
desc = null;
}
return desc;
}
function _initializerWarningHelper(descriptor, context) {
throw new Error('Decorating class property failed. Please ensure that transform-class-properties is enabled.');
}
var _dec, _class, _desc, _value, _class2, _descriptor, _descriptor2, _descriptor3;
var AubsBtnLoadingCustomAttribute = exports.AubsBtnLoadingCustomAttribute = (_dec = (0, _aureliaFramework.inject)(Element), _dec(_class = (_class2 = function () {
function AubsBtnLoadingCustomAttribute(element) {
_classCallCheck(this, AubsBtnLoadingCustomAttribute);
_initDefineProp(this, 'loading', _descriptor, this);
_initDefineProp(this, 'text', _descriptor2, this);
_initDefineProp(this, 'disabled', _descriptor3, this);
this.element = element;
if (this.element.tagName !== 'BUTTON' && this.element.tagName !== 'A') {
throw new Error("The aubs-btn-loading attribute can only be used in button and anchor elements");
}
}
AubsBtnLoadingCustomAttribute.prototype.attached = function attached() {
this.isAttached = true;
this.innerHTML = this.element.innerHTML;
this.setClass();
this.disabledChanged();
};
AubsBtnLoadingCustomAttribute.prototype.loadingChanged = function loadingChanged() {
if (this.isAttached) {
this.setClass();
}
};
AubsBtnLoadingCustomAttribute.prototype.disabledChanged = function disabledChanged() {
if (!this.isAttached) {
return;
}
if (this.disabled) {
if (!this.loading) {
this.element.classList.add("disabled");
this.element.disabled = true;
}
} else {
if (!this.loading) {
this.element.classList.remove("disabled");
this.element.disabled = false;
}
}
};
AubsBtnLoadingCustomAttribute.prototype.setClass = function setClass() {
if (this.loading) {
this.innerHTML = this.element.innerHTML;
this.element.innerHTML = this.text;
this.element.classList.add("disabled");
this.element.disabled = true;
} else {
this.element.innerHTML = this.innerHTML;
if (!this.disabled) {
this.element.classList.remove("disabled");
this.element.disabled = false;
}
}
};
return AubsBtnLoadingCustomAttribute;
}(), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, 'loading', [_aureliaFramework.bindable], {
enumerable: true,
initializer: null
}), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, 'text', [_aureliaFramework.bindable], {
enumerable: true,
initializer: function initializer() {
return _bootstrapOptions.bootstrapOptions.btnLoadingText;
}
}), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, 'disabled', [_aureliaFramework.bindable], {
enumerable: true,
initializer: function initializer() {
return false;
}
})), _class2)) || _class);
}); |
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
StatusBar,
TextInput,
ActivityIndicator,
Platform
} from 'react-native';
import { connect } from 'react-redux';
import t from 'tcomb-form-native';
const Form = t.form.Form;
import Button from '../common/Button';
import ServicesForm from './ServicesForm';
import Toolbar from '../common/Toolbar';
import { createAddress, loadZipcode, getAddress, updateAddress } from '../actions/address';
class AddressForm extends Component {
_createAddress() {
let value = this.refs.form.getValue();
// if are any validation errors, value will be null
if (value !== null) {
if (this.props.edit) {
this.props.dispatch(updateAddress(value));
} else {
this.props.dispatch(createAddress(value));
}
}
}
componentDidMount() {
if (this.props.edit) {
this.props.dispatch(getAddress());
}
}
componentDidUpdate() {
if (this.props.form.success) {
if (this.props.edit) {
this.props.navigator.pop();
} else {
const route = {
component: ServicesForm,
title: 'Barber Hour'
};
Platform.OS === 'ios' ? requestAnimationFrame(() => this.props.navigator.resetTo(route)) : this.props.navigator.resetTo(route);
}
}
}
getFormValue() {
return {
zipcode: this.props.form.zipcode,
street: this.props.form.street,
district: this.props.form.district,
number: this.props.form.number,
city: this.props.form.city,
state: this.props.form.state
};
}
loadZipcode() {
var zipcode = this.refs.form.getComponent('zipcode').props.value
if (zipcode) {
this.props.dispatch(loadZipcode(zipcode));
}
}
_getButtonLabel() {
if (this.props.edit) {
return this.props.isLoading ? 'Alterando...' : 'Alterar';
} else {
return this.props.isLoading ? 'Cadastrando...' : 'Avançar';
}
}
render() {
const Address = t.struct({
zipcode: t.String,
street: t.String,
district: t.String,
number: t.Number,
city: t.String,
state: t.String,
});
var formOptions = this.props.form;
formOptions.fields.zipcode.onBlur = this.loadZipcode.bind(this);
var infoPrefix = this.props.edit ? 'Altere' : 'Cadastre';
var content;
if (this.props.form.isRequestingInfo) {
content = <ActivityIndicator size='small' />;
}
return(
<View style={styles.container}>
<StatusBar backgroundColor='#C5C5C5' networkActivityIndicatorVisible={this.props.form.isLoading || this.props.form.isRequestingInfo} />
<Toolbar backIcon navigator={this.props.navigator} />
<View style={styles.innerContainer}>
<Text style={styles.title}>Endereço</Text>
<Text style={styles.info}>{infoPrefix} o endereço da barbearia:</Text>
{content}
<View style={styles.formContainer}>
<Form ref='form' type={Address} options={formOptions} value={this.getFormValue()} />
</View>
<Button
containerStyle={styles.button}
text={this._getButtonLabel()}
disabled={this.props.form.isLoading || this.props.form.isRequestingInfo}
onPress={this._createAddress.bind(this)} />
</View>
</View>
);
}
}
function select(store) {
return {
form: store.address
};
}
export default connect(select)(AddressForm);
var styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
backgroundColor: 'white',
marginTop: Platform.OS === 'ios' ? 55 : 0
},
innerContainer: {
padding: 20,
},
title: {
fontSize: 24,
textAlign: 'center'
},
info: {
fontSize: 16,
textAlign: 'center'
},
button: {
marginTop: 20
},
formContainer: {
marginTop: 10
}
});
|
/**
* Filters an array by the given filter function(s), may provide a function or an array or an object with filtering
* functions.
*/
module.exports = function(value, filterFunc, testValue) {
if (!Array.isArray(value)) {
return [];
} else if (!filterFunc) {
return value;
}
if (typeof filterFunc === 'string' && arguments.length > 2) {
var key = filterFunc;
filterFunc = function(item) {
return item && item[key] === testValue;
};
}
if (typeof filterFunc === 'function') {
value = value.filter(filterFunc, this);
} else if (Array.isArray(filterFunc)) {
filterFunc.forEach(function(func) {
value = value.filter(func, this);
});
} else if (typeof filterFunc === 'object') {
Object.keys(filterFunc).forEach(function(key) {
var func = filterFunc[key];
if (typeof func === 'function') {
value = value.filter(func, this);
}
});
}
return value;
};
|
import Router from './routers/Router';
import OctobusRouter from './routers/Octobus';
import MongoResourceRouter from './routers/MongoResourceRouter';
import { route } from './libs/decorators';
import * as mongoHelpers from './libs/mongo-helpers';
export { Router, MongoResourceRouter, route, mongoHelpers, OctobusRouter };
|
'use strict'
var postcss = require('postcss')
var isCssRoot = require('is-css-root')
var cssVariable = require('css-variable')
module.exports = postcss.plugin('get-variables', function (callback) {
return function (root, postcssResult) {
var variables = {}
root.walkRules(function (rule) {
if (rule.selectors.length === 1 && isCssRoot(rule.selectors[0]) && rule.parent.type === 'root') {
rule.each(function (declaration) {
if (declaration.type === 'decl' && declaration.prop) {
var variable = cssVariable(declaration.prop)
variables[variable.base()] = declaration.value
}
})
}
})
callback(variables)
}
})
|
function panel_arkud_update(KaTZPit_data){
// Variable ARKUD contient
// 1=Selecteur de Mode, 2-3=Switch Sensitivity, 4=Selecteur de Channel, 5=Volume, 6-8 Voyants
// Switch Sensotivity et UHF/VHF
if (dataread_posit(KaTZPit_data["ARKUD"],2) ==1) {$("#ARKUD-SW-Sens").attr('src','images/Switch-Metal-U3.gif')} else {$("#ARKUD-SW-Sens").attr('src','images/Switch-Metal-D3.gif')}
if (dataread_posit(KaTZPit_data["ARKUD"],3) ==1) {$("#ARKUD-SW-VHF").attr('src','images/Switch-Metal-U3.gif')} else {$("#ARKUD-SW-VHF").attr('src','images/Switch-Metal-D3.gif')}
// Alarme Low Alti (deuxième digit des
if (dataread_posit(KaTZPit_data["ARKUD"],6) ==1) {$("#ARKUD-V1").fadeIn()} else {$("#ARKUD-V1").fadeOut()}
if (dataread_posit(KaTZPit_data["ARKUD"],7) ==1) {$("#ARKUD-V2").fadeIn()} else {$("#ARKUD-V2").fadeOut()}
if (dataread_posit(KaTZPit_data["ARKUD"],8) ==1) {$("#ARKUD-V3").fadeIn()} else {$("#ARKUD-V3").fadeOut()}
// Switch Off/Narrow/Wide/Pulse Translation
Translate_ArkUDOff(dataread_posit(KaTZPit_data["ARKUD"],1))
// Channel Selection Rotation
Arkchan = dataread_posit(KaTZPit_data["ARKUD"],4) + 5 // les valeurs ont été envoyé avec un décalage de 5
if (Arkchan > 2 ){Arkchan = Arkchan + 1} // decallage pour passer la position milieu
Rotate_Chanselect(Arkchan)
// Volume Rotation
Rotate_Volume(dataread_posit(KaTZPit_data["ARKUD"],5)+ 5 ) // les valeurs ont été envoyé avec un décalage de 5
}
function panel_ark9_update(KaTZPit_data){
// Affichage des Frequences Main Stby
var ARK9_frequence = dataread_split_2(KaTZPit_data["ARK9_F"])
document.getElementById('ARK9-Main').innerHTML = (ARK9_frequence[0]/1000).toFixed(3)
document.getElementById('ARK9-Stby').innerHTML = (ARK9_frequence[1]/1000).toFixed(3)
// Switch Main/Stby et TLF/TLG
if (dataread_posit(KaTZPit_data["ARK9_SW"],1) ==1) {$("#ARK9-SW-MAIN").attr('src','images/Switch-Metal-R3.gif')} else {$("#ARK9-SW-MAIN").attr('src','images/Switch-Metal-L3.gif')}
if (dataread_posit(KaTZPit_data["ARK9_SW"],2) ==1) {$("#ARK9-SW-TLF").attr('src','images/Switch-Metal-U3.gif')} else {$("#ARK9-SW-TLF").attr('src','images/Switch-Metal-D3.gif')}
// Switch Off/Comp/ANT/Loop Translation
Translate_ArkOff(dataread_posit(KaTZPit_data["ARK9_SW"],3))
// Tune Main Rotation
Rotate_TuneMain(dataread_posit(KaTZPit_data["ARK9_SW"],4))
// Tune Stby Rotation
Rotate_TuneStby(dataread_posit(KaTZPit_data["ARK9_SW"],5))
// Gain et Signal Rotation
ARK9_signal = dataread_split_2(KaTZPit_data["ARK9_Data"])
Rotate_ArkGain(ARK9_signal[1])
Rotate_ArkSignal(ARK9_signal[0])
}
// Translation bouton selection Ark_UD
function Translate_ArkUDOff(val){
var u_origine = 0
var u_gain = 75
// valat : positif = Translation vers la droite
$("#ARKUD-SW-OFF").css({
'-moz-transform':'translate('+(u_origine + u_gain * val)+'px,0px)',
'-webkit-transform':'translate('+(u_origine + u_gain * val)+'px,0px)',
'-ms-transform':'translate('+(u_origine + u_gain * val)+'px,0px)',
})
}
// Translation bouton selection Ark_9
function Translate_ArkOff(valat){
var a_origine = 0
var a_gain = 45
// valat : positif = Translation vers la droite
$("#ARK9-SW-OFF").css({
'-moz-transform':'translate('+(a_origine + a_gain * valat)+'px,0px)',
'-webkit-transform':'translate('+(a_origine + a_gain * valat)+'px,0px)',
'-ms-transform':'translate('+(a_origine + a_gain * valat)+'px,0px)',
})
}
function Rotate_Chanselect(chan){
var c_origine = -80
var c_gain = 26.6
$("#ARKUD-Chan").css({
'-moz-transform':'rotate('+(c_origine+c_gain*chan)+'deg)',
'-webkit-transform':'rotate('+(c_origine+c_gain*chan)+'deg)',
'-ms-transform':'rotate('+(c_origine+c_gain*chan)+'deg)',
})
}
function Rotate_Volume(vol){
var v_origine = -70
var v_gain = 12
$("#ARKUD-Vol").css({
'-moz-transform':'rotate('+(v_origine+v_gain*vol)+'deg)',
'-webkit-transform':'rotate('+(v_origine+v_gain*vol)+'deg)',
'-ms-transform':'rotate('+(v_origine+v_gain*vol)+'deg)',
})
}
function Rotate_TuneMain(val){
var a_origine = 0
var l_gain = 45
$("#ARK9-Tune-MAIN").css({
'-moz-transform':'rotate('+(a_origine+l_gain*val)+'deg)',
'-webkit-transform':'rotate('+(a_origine+l_gain*val)+'deg)',
'-ms-transform':'rotate('+(a_origine+l_gain*val)+'deg)',
})
}
function Rotate_TuneStby(val){
var a_origine = 0
var l_gain = 45
$("#ARK9-Tune-STBY").css({
'-moz-transform':'rotate('+(a_origine+l_gain*val)+'deg)',
'-webkit-transform':'rotate('+(a_origine+l_gain*val)+'deg)',
'-ms-transform':'rotate('+(a_origine+l_gain*val)+'deg)',
})
}
function Rotate_ArkGain(val){
var a_origine = 22.5
var l_gain = -0.35
$("#ARK9-Gain").css({
'-moz-transform':'rotate('+(a_origine+l_gain*val)+'deg)',
'-webkit-transform':'rotate('+(a_origine+l_gain*val)+'deg)',
'-ms-transform':'rotate('+(a_origine+l_gain*val)+'deg)',
})
}
function Rotate_ArkSignal(val){
var a_origine = -45
var l_gain = 0.09
$("#ARK9-Signal").css({
'-moz-transform':'rotate('+(a_origine+l_gain*val)+'deg)',
'-webkit-transform':'rotate('+(a_origine+l_gain*val)+'deg)',
'-ms-transform':'rotate('+(a_origine+l_gain*val)+'deg)',
})
}
function Increment_ARK_Freq(canal,pas,signe){
// Passage des fréquence en mode édition (chiffres rouges)
// On remplace l'affichage #ARK9-Main par #ARK9-temp-Main
document.getElementById("ARK9-temp-Main").style.display = "block"
document.getElementById("ARK9-temp-Stby").style.display = "block"
document.getElementById('ARK9-temp-Main').innerHTML = (KaTZPit_data["ARK9_T_Main"]/1000).toFixed(3)
document.getElementById('ARK9-temp-Stby').innerHTML = (KaTZPit_data["ARK9_T_Stby"]/1000).toFixed(3)
// Incrémentation des fréquences en fonciton du canal, pas et signe
// Main Frequence = canal 1
if (canal == 0) {
KaTZPit_data["ARK9_T_Main"] = KaTZPit_data["ARK9_T_Main"] + signe * pas
if (KaTZPit_data["ARK9_T_Main"] > 1290) {KaTZPit_data["ARK9_T_Main"] = 1290}
if (KaTZPit_data["ARK9_T_Main"] < 150) {KaTZPit_data["ARK9_T_Main"] = 150}
}
// Stby Frequence = canal 0
if (canal == 1) {
KaTZPit_data["ARK9_T_Stby"] = KaTZPit_data["ARK9_T_Stby"] + signe * pas
if (KaTZPit_data["ARK9_T_Stby"] > 1290) {KaTZPit_data["ARK9_T_Stby"] = 1290}
if (KaTZPit_data["ARK9_T_Stby"] < 150) {KaTZPit_data["ARK9_T_Stby"] = 150}
}
// mise à jour de l'affichage
document.getElementById('ARK9-temp-Main').innerHTML = (KaTZPit_data["ARK9_T_Main"]/1000).toFixed(3)
document.getElementById('ARK9-temp-Stby').innerHTML = (KaTZPit_data["ARK9_T_Stby"]/1000).toFixed(3)
}
function Send_ARK_Freq(){
// Envoi de la fréquence temporaire à DCS
var main1 = Math.floor(KaTZPit_data["ARK9_T_Main"] / 100)
var main0 = (KaTZPit_data["ARK9_T_Main"] % 100 ) / 10
var stby1 = Math.floor(KaTZPit_data["ARK9_T_Stby"] / 100)
var stby0 = (KaTZPit_data["ARK9_T_Stby"] % 100) / 10
console.log("main = ",main1, " ",main0)
console.log("stby = ",stby1, " ",stby0)
var cmdm1 = 44000900 + Math.abs(main0)
var cmdm2 = 74000800 + Math.abs((main1 - 1 )/ 0.2 )
var cmds1 = 44000600 + Math.abs(stby0)
var cmds2 = 74000500 + Math.abs((stby1 - 1 )/ 0.2 )
console.log("Commande = ",cmdm1, " ", cmdm2," ",cmds1, " ", cmds2 )
CmdDCSRaw(cmdm1)
CmdDCSRaw(cmdm2)
CmdDCSRaw(cmds1)
CmdDCSRaw(cmds2)
// On remplace desactive l'affichage #ARK9-temp-Main
document.getElementById("ARK9-temp-Main").style.display = "none"
document.getElementById("ARK9-temp-Stby").style.display = "none"
}
function panel_doppler_update(KaTZPit_data) {
var Doppler_dat1 = dataread_split_2(KaTZPit_data["Doppler_d1"])
var Doppler_dat2 = dataread_split_2(KaTZPit_data["Doppler_d2"])
document.getElementById('Dop_Drift').innerHTML = (Doppler_dat1[0]/10).toFixed(1)
document.getElementById('Dop_Flight').innerHTML = (Doppler_dat1[1]/10).toFixed(1)
// Ajout d'un zero significatif aux minutes
var Doppler_min = (Doppler_dat2[0]).toString()
if (Doppler_dat2[0]<10) { Doppler_min = "0" + (Doppler_dat2[0]).toString() }
document.getElementById('Dop_Map').innerHTML = (Doppler_dat2[1]/10).toString()+"°"+ Doppler_min
if (dataread_posit(KaTZPit_data["Doppler_f"],2) ==0) {document.getElementById('Dop_DFlag').innerHTML = "Left"}
else {document.getElementById('Dop_DFlag').innerHTML = "Right"}
if (dataread_posit(KaTZPit_data["Doppler_f"],3) ==0) {document.getElementById('Dop_FFlag').innerHTML = "Forward"}
else {document.getElementById('Dop_FFlag').innerHTML = "Back"}
if (dataread_posit(KaTZPit_data["Doppler_f"],1) ==0) {$("#Doppler-Enable").fadeIn()} else {$("#Doppler-Enable").fadeOut()}
}
|
import Ember from 'ember';
import DS from 'ember-data';
import ENV from '../config/environment';
export default DS.Model.reopenClass({
random: function(proposal_id) {
var path = "/proposals/next";
if(proposal_id) {
path += "?proposal_id=" + proposal_id;
}
return (new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.getJSON(ENV.api + path).then(
function(data) {
resolve(data);
}, reject);
}));
},
}).extend({
type: DS.attr("string"),
user: DS.belongsTo("user"),
lang: DS.belongsTo("lang"),
wordset: DS.belongsTo("wordset", {async: true}),
project: DS.belongsTo("project", {inverse: null}),
wordName: DS.attr("string"),
reason: DS.attr("string"),
state: DS.attr("string"),
createdAt: DS.attr("date"),
tally: DS.attr("number"),
votes: DS.hasMany("vote"),
activities: DS.hasMany("activity"),
flagged: DS.attr("boolean"),
// NewWord
meanings: DS.attr(),
// MeaningLike
def: DS.attr("string"),
example: DS.attr("string"),
labels: DS.hasMany("labels", {serialize: true}),
// ChangeMeaning
meaning: DS.belongsTo("meaning", {inverse: null}),
original: DS.attr(),
parentId: DS.attr(),
// NewMeaning
pos: DS.attr("string"),
typeName: function() {
if(this.get("type") === "NewWordset") {
return "New Word";
} else if(this.get("type") === "NewMeaning") {
return "New Meaning";
} else if(this.get("type") === "MeaningChange") {
return "Change";
} else if(this.get("type") === "MeaningRemoval") {
return "Removal";
}
}.property("type"),
isRemoval: function() {
return (this.get("type") === "MeaningRemoval");
}.property("type"),
isEditableType: function() {
return (this.get("type") !== "MeaningRemoval");
}.property("typeName"),
positiveTally: function() {
if(this.get("tally") > 0 ) {
return "width: " + this.get("tally") + "%;";
} else {
return "";
}
}.property("tally"),
negativeTally: function() {
if(this.get("tally") < 0 ) {
return "width: " + (this.get("tally") * -1) + "%;";
} else {
return "";
}
}.property("tally"),
originalLabels: function() {
var _this = this;
if(Ember.isEmpty(this.get("original.labels"))) { return []; }
return this.store.filter("label", function(label) {
return _this.get("original.labels").contains("" + label.id);
});
}.property("original.labels"),
});
|
import React from "react";
const MdnLink = ({ children }) =>
<a href={`https://mdn.io/${children}`}>
<code>
{children}
</code>
</a>;
export default MdnLink;
|
#!/usr/bin/env node
'use strict';
const Argv = require('yargs')
.demand('env')
.argv;
Argv.env === 'dev' && require('babel-register');
const appDir = `./${Argv.env === 'dev' ? 'app' : 'dist'}`;
const Config = require(`${appDir}/config`);
const initApp = require(`./${appDir}/init`);
Config.getConfig(Argv.env)
.then(initApp)
.catch(err=> {
console.error(err);
});
|
$(document).ready(function() {
if (!(navigator.userAgent.toLowerCase().indexOf('chrome') > -1)) {
$('body').html('<p id="disclaimer">We are sorry, this experiment only works under the latest version of Google Chrome</p>');
return;
}
App.run();
}); |
/**
* @author Bloody
*/
var Scene_RenderTarget_Viewport = new Class({
rootElement: null,
canvas: null,
context: null,
sceneGraph: null,
initialize : function(element, sceneGraph) {
this.rootElement = element;
this.sceneGraph = sceneGraph;
var size = element.width();
var canvas = $(document.createElement('canvas'));
canvas.attr('width', element.width());
canvas.attr('height', element.height());
canvas.css('top', 0);
canvas.addClass('viewport absolute');
element.append(canvas);
this.canvas = canvas;
this.context = canvas[0].getContext('2d');
},
update: function() {
var size = element.getSize();
this.canvas.set('width', size.x).set('height', size.y);
},
render: function() {
var batch = this.sceneGraph.draw();
batch.sort(function(A, B) {
return A.z - B.z;
});
this.context.clearRect(0, 0, this.canvas.attr('width'), this.canvas.attr('height'));
for(var i = 0; i < batch.length; i++) {
batch[i].render(this.context);
}
},
}); |
var nconf = require('nconf');
// load config from args, env vars or local.json
nconf.argv().env().file({
file: 'local.json',
dir: __dirname,
search: true
});
// defaults
nconf.defaults({
url: 'https://omgvamp-hearthstone-v1.p.mashape.com',
key: '',
sets: ['Classic', 'The Grand Tournament', 'Goblins vs Gnomes']
});
module.exports = nconf;
|
'use strict';
var app = app || {};
(function(module) {
const generalController = {};
const f = $('form')[0];
// take the area, start, and end dates from the url to make an object for the request parameters
generalController.createFilter = function(ctx, next) {
let area = ctx.params.area.split(', ');
let start = ctx.params.start.split('-');
let end = ctx.params.end.split('-');
ctx.filter = {
city: area[0],
stateCode: area[1],
startDateTime: new Date(start[0], parseInt(start[1]) - 1, start[2], 0).toISOString().replace(/\.\d\d\d/, ''),
endDateTime: new Date(end[0], parseInt(end[1]) - 1, end[2], 23, 59).toISOString().replace(/\.\d\d\d/, ''),
classificationName: 'Music',
sort: 'date,asc',
}
next();
};
// uses the filter in ctx to load concerts from the TM API
generalController.loadFromFilter = function(ctx, next) {
app.Concert.fetchAll(ctx.filter, next);
}
module.generalController = generalController;
})(app);
|
var authController = (models, _validate, _h, jwt, co) => {
var Authenticate = (req, res) => {
_validate.validateAuthParams(req, function (err) {
co(function* () {
if (err) return res.status(400).json(err);
// Authenticate a user
// find the user
var user = yield models.User.findOne({
email: req.body.email
}).populate({
path: 'role',
select: 'title'
});
if (!user) {
res.status(404).json({
success: false,
message: 'Authentication failed. User not found.'
});
} else {
if (user.google.id || user.facebook.id) {
return res.status(401).json({
success: false,
message: 'Hello, Looks like you logged in using the social ' +
'authentication. You cannot use the feature.'
});
}
// check if password matches
user.comparePassword(req.body.password, (err, isMatch) => {
if (err) throw err;
if (isMatch) {
// if user is found and password is right
// create a token
var options = {
expiresIn: '24h' // expires in 24 hours from creation.
};
jwt.sign(user,
process.env.WEB_TOKEN_SECRET, options, (token) => {
// return the information including token as JSON
res.json({
success: true,
message: 'Authentication successful!',
user: user,
token: token
});
});
} else {
res.status(401).json({
success: false,
message: 'Authentication failed. Wrong password.'
});
}
});
}
});
});
};
return Authenticate;
};
module.exports = authController;
|
;(function ($, window, document, undefined) {
'use strict';
var noop = function() {};
var Orbit = function(el, settings) {
// Don't reinitialize plugin
if (el.hasClass(settings.slides_container_class)) {
return this;
}
var self = this,
container,
slides_container = el,
number_container,
bullets_container,
timer_container,
idx = 0,
animate,
adjust_height_after = false,
has_init_active = slides_container.find("." + settings.active_slide_class).length > 0;
self.cache = {};
self.slides = function() {
return slides_container.children(settings.slide_selector);
};
if (!has_init_active) {self.slides().first().addClass(settings.active_slide_class)};
self.update_slide_number = function(index) {
if (settings.slide_number) {
number_container.find('span:first').text(parseInt(index)+1);
number_container.find('span:last').text(self.slides().length);
}
if (settings.bullets) {
bullets_container.children().removeClass(settings.bullets_active_class);
$(bullets_container.children().get(index)).addClass(settings.bullets_active_class);
}
};
self.update_active_link = function(index) {
var link = $('[data-orbit-link="'+self.slides().eq(index).attr('data-orbit-slide')+'"]');
link.siblings().removeClass(settings.bullets_active_class);
link.addClass(settings.bullets_active_class);
};
self.build_markup = function() {
slides_container.wrap('<div class="'+settings.container_class+'"></div>');
container = slides_container.parent();
slides_container.addClass(settings.slides_container_class);
slides_container.addClass(settings.animation);
if (settings.stack_on_small) {
container.addClass(settings.stack_on_small_class);
}
if (settings.navigation_arrows) {
container.append($('<a href="#"><span></span></a>').addClass(settings.prev_class));
container.append($('<a href="#"><span></span></a>').addClass(settings.next_class));
}
if (settings.timer) {
timer_container = $('<div>').addClass(settings.timer_container_class);
timer_container.append('<span>');
if (settings.timer_show_progress_bar) {
timer_container.append($('<div>').addClass(settings.timer_progress_class));
}
timer_container.addClass(settings.timer_paused_class);
container.append(timer_container);
}
if (settings.slide_number) {
number_container = $('<div>').addClass(settings.slide_number_class);
number_container.append('<span></span> ' + settings.slide_number_text + ' <span></span>');
container.append(number_container);
}
if (settings.bullets) {
bullets_container = $('<ol>').addClass(settings.bullets_container_class);
container.append(bullets_container);
bullets_container.wrap('<div class="orbit-bullets-container"></div>');
self.slides().each(function(idx, el) {
var bullet = $('<li>').attr('data-orbit-slide', idx);
bullets_container.append(bullet);
});
}
};
self._prepare_direction = function(next_idx, current_direction) {
var dir = 'next';
if (next_idx <= idx) { dir = 'prev'; }
if (settings.animation === 'slide') {
setTimeout(function(){
slides_container.removeClass("swipe-prev swipe-next");
if (dir === 'next') {slides_container.addClass("swipe-next");}
else if (dir === 'prev') {slides_container.addClass("swipe-prev");}
},0);
}
var slides = self.slides();
if (next_idx >= slides.length) {
if (!settings.circular) return false;
next_idx = 0;
} else if (next_idx < 0) {
if (!settings.circular) return false;
next_idx = slides.length - 1;
}
var current = $(slides.get(idx))
, next = $(slides.get(next_idx));
return [dir, current, next, next_idx];
};
self._goto = function(next_idx, start_timer) {
if (next_idx === null) {return false;}
if (self.cache.animating) {return false;}
if (next_idx === idx) {return false;}
if (typeof self.cache.timer === 'object') {self.cache.timer.restart();}
var slides = self.slides();
self.cache.animating = true;
var res = self._prepare_direction(next_idx)
, dir = res[0]
, current = res[1]
, next = res[2]
, next_idx = res[3];
// This means that circular is disabled and we most likely reached the last slide.
if (res === false) return false;
slides_container.trigger('before-slide-change.fndtn.orbit');
settings.before_slide_change();
idx = next_idx;
current.css("transitionDuration", settings.animation_speed+"ms");
next.css("transitionDuration", settings.animation_speed+"ms");
var callback = function() {
var unlock = function() {
if (start_timer === true) {self.cache.timer.restart();}
self.update_slide_number(idx);
// Remove "animate-in" class as late as possible to avoid "flickering" (especially with variable_height).
next.removeClass("animate-in");
next.addClass(settings.active_slide_class);
self.update_active_link(next_idx);
slides_container.trigger('after-slide-change.fndtn.orbit',[{slide_number: idx, total_slides: slides.length}]);
settings.after_slide_change(idx, slides.length);
setTimeout(function(){
self.cache.animating = false;
}, 100);
};
if (slides_container.height() != next.height() && settings.variable_height) {
slides_container.animate({'min-height': next.height()}, 250, 'linear', unlock);
} else {
unlock();
}
};
if (slides.length === 1) {callback(); return false;}
var start_animation = function() {
if (dir === 'next') {animate.next(current, next, callback);}
if (dir === 'prev') {animate.prev(current, next, callback);}
};
if (next.height() > slides_container.height() && settings.variable_height) {
slides_container.animate({'min-height': next.height()}, 250, 'linear', start_animation);
} else {
start_animation();
}
};
self.next = function(e) {
e.stopImmediatePropagation();
e.preventDefault();
self._prepare_direction(idx + 1);
setTimeout(function(){
self._goto(idx + 1);
}, 100);
};
self.prev = function(e) {
e.stopImmediatePropagation();
e.preventDefault();
self._prepare_direction(idx - 1);
setTimeout(function(){
self._goto(idx - 1)
}, 100);
};
self.link_custom = function(e) {
e.preventDefault();
var link = $(this).attr('data-orbit-link');
if ((typeof link === 'string') && (link = $.trim(link)) != "") {
var slide = container.find('[data-orbit-slide='+link+']');
if (slide.index() != -1) {
setTimeout(function(){
self._goto(slide.index());
},100);
}
}
};
self.link_bullet = function(e) {
var index = $(this).attr('data-orbit-slide');
if ((typeof index === 'string') && (index = $.trim(index)) != "") {
if(isNaN(parseInt(index)))
{
var slide = container.find('[data-orbit-slide='+index+']');
if (slide.index() != -1) {
setTimeout(function(){
self._goto(slide.index() + 1);
},100);
}
}
else
{
setTimeout(function(){
self._goto(parseInt(index));
},100);
}
}
}
self.timer_callback = function() {
self._goto(idx + 1, true);
}
self.compute_dimensions = function() {
var current = $(self.slides().get(idx));
var h = current.height();
if (!settings.variable_height) {
self.slides().each(function(){
if ($(this).height() > h) { h = $(this).height(); }
});
}
slides_container.css('minHeight', String(h)+'px');
};
self.create_timer = function() {
var t = new Timer(
container.find('.'+settings.timer_container_class),
settings,
self.timer_callback
);
return t;
};
self.stop_timer = function() {
if (typeof self.cache.timer === 'object') self.cache.timer.stop();
};
self.toggle_timer = function() {
var t = container.find('.'+settings.timer_container_class);
if (t.hasClass(settings.timer_paused_class)) {
if (typeof self.cache.timer === 'undefined') {self.cache.timer = self.create_timer();}
self.cache.timer.start();
}
else {
if (typeof self.cache.timer === 'object') {self.cache.timer.stop();}
}
};
self.init = function() {
self.build_markup();
if (settings.timer) {
self.cache.timer = self.create_timer();
Foundation.utils.image_loaded(this.slides().children('img'), self.cache.timer.start);
}
animate = new CSSAnimation(settings, slides_container);
if (has_init_active) {
var $init_target = slides_container.find("." + settings.active_slide_class),
animation_speed = settings.animation_speed;
settings.animation_speed = 1;
$init_target.removeClass('active');
self._goto($init_target.index());
settings.animation_speed = animation_speed;
}
container.on('click', '.'+settings.next_class, self.next);
container.on('click', '.'+settings.prev_class, self.prev);
if (settings.next_on_click) {
container.on('click', '[data-orbit-slide]', self.link_bullet);
}
container.on('click', self.toggle_timer);
if (settings.swipe) {
slides_container.on('touchstart.fndtn.orbit',function(e) {
if (self.cache.animating) {return;}
if (!e.touches) {e = e.originalEvent;}
e.preventDefault();
e.stopPropagation();
self.cache.start_page_x = e.touches[0].pageX;
self.cache.start_page_y = e.touches[0].pageY;
self.cache.start_time = (new Date()).getTime();
self.cache.delta_x = 0;
self.cache.is_scrolling = null;
self.cache.direction = null;
self.stop_timer(); // does not appear to prevent callback from occurring
})
.on('touchmove.fndtn.orbit',function(e) {
if (Math.abs(self.cache.delta_x) > 5) {
e.preventDefault();
e.stopPropagation();
}
if (self.cache.animating) {return;}
requestAnimationFrame(function(){
if (!e.touches) { e = e.originalEvent; }
// Ignore pinch/zoom events
if(e.touches.length > 1 || e.scale && e.scale !== 1) return;
self.cache.delta_x = e.touches[0].pageX - self.cache.start_page_x;
if (self.cache.is_scrolling === null) {
self.cache.is_scrolling = !!( self.cache.is_scrolling || Math.abs(self.cache.delta_x) < Math.abs(e.touches[0].pageY - self.cache.start_page_y) );
}
if (self.cache.is_scrolling) {
return;
}
var direction = (self.cache.delta_x < 0) ? (idx+1) : (idx-1);
if (self.cache.direction !== direction) {
var res = self._prepare_direction(direction);
self.cache.direction = direction;
self.cache.dir = res[0];
self.cache.current = res[1];
self.cache.next = res[2];
}
if (settings.animation === 'slide') {
var offset, next_offset;
offset = (self.cache.delta_x / container.width()) * 100;
if (offset >= 0) {next_offset = -(100 - offset);}
else {next_offset = 100 + offset;}
self.cache.current.css("transform","translate3d("+offset+"%,0,0)");
self.cache.next.css("transform","translate3d("+next_offset+"%,0,0)");
}
});
})
.on('touchend.fndtn.orbit', function(e) {
if (self.cache.animating) {return;}
e.preventDefault();
e.stopPropagation();
setTimeout(function(){
self._goto(self.cache.direction);
}, 50);
});
}
container.on('mouseenter.fndtn.orbit', function(e) {
if (settings.timer && settings.pause_on_hover) {
self.stop_timer();
}
})
.on('mouseleave.fndtn.orbit', function(e) {
if (settings.timer && settings.resume_on_mouseout) {
self.cache.timer.start();
}
});
$(document).on('click', '[data-orbit-link]', self.link_custom);
$(window).on('load resize', self.compute_dimensions);
var children = this.slides().find('img');
Foundation.utils.image_loaded(children, self.compute_dimensions);
Foundation.utils.image_loaded(children, function() {
container.prev('.'+settings.preloader_class).css('display', 'none');
self.update_slide_number(idx);
self.update_active_link(idx);
slides_container.trigger('ready.fndtn.orbit');
});
};
self.init();
};
var Timer = function(el, settings, callback) {
var self = this,
duration = settings.timer_speed,
progress = el.find('.'+settings.timer_progress_class),
do_progress = progress && progress.css('display') != 'none',
start,
timeout,
left = -1;
this.update_progress = function(w) {
var new_progress = progress.clone();
new_progress.attr('style', '');
new_progress.css('width', w+'%');
progress.replaceWith(new_progress);
progress = new_progress;
};
this.restart = function() {
clearTimeout(timeout);
el.addClass(settings.timer_paused_class);
left = -1;
if (do_progress) {self.update_progress(0);}
self.start();
};
this.start = function() {
if (!el.hasClass(settings.timer_paused_class)) {return true;}
left = (left === -1) ? duration : left;
el.removeClass(settings.timer_paused_class);
if (do_progress) {
start = new Date().getTime();
progress.animate({'width': '100%'}, left, 'linear');
}
timeout = setTimeout(function() {
self.restart();
callback();
}, left);
el.trigger('timer-started.fndtn.orbit')
};
this.stop = function() {
if (el.hasClass(settings.timer_paused_class)) {return true;}
clearTimeout(timeout);
el.addClass(settings.timer_paused_class);
if (do_progress) {
var end = new Date().getTime();
left = left - (end - start);
var w = 100 - ((left / duration) * 100);
self.update_progress(w);
}
el.trigger('timer-stopped.fndtn.orbit');
};
};
var CSSAnimation = function(settings, container) {
var animation_end = "webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend";
this.next = function(current, next, callback) {
if (Modernizr.csstransitions) {
next.on(animation_end, function(e){
next.unbind(animation_end);
current.removeClass("active animate-out");
container.children().css({
"transform":"",
"-ms-transform":"",
"-webkit-transition-duration":"",
"-moz-transition-duration": "",
"-o-transition-duration": "",
"transition-duration":""
});
callback();
});
} else {
setTimeout(function(){
current.removeClass("active animate-out");
container.children().css({
"transform":"",
"-ms-transform":"",
"-webkit-transition-duration":"",
"-moz-transition-duration": "",
"-o-transition-duration": "",
"transition-duration":""
});
callback();
}, settings.animation_speed);
}
container.children().css({
"transform":"",
"-ms-transform":"",
"-webkit-transition-duration":"",
"-moz-transition-duration": "",
"-o-transition-duration": "",
"transition-duration":""
});
current.addClass("animate-out");
next.addClass("animate-in");
};
this.prev = function(current, prev, callback) {
if (Modernizr.csstransitions) {
prev.on(animation_end, function(e){
prev.unbind(animation_end);
current.removeClass("active animate-out");
container.children().css({
"transform":"",
"-ms-transform":"",
"-webkit-transition-duration":"",
"-moz-transition-duration": "",
"-o-transition-duration": "",
"transition-duration":""
});
callback();
});
} else {
setTimeout(function(){
current.removeClass("active animate-out");
container.children().css({
"transform":"",
"-ms-transform":"",
"-webkit-transition-duration":"",
"-moz-transition-duration": "",
"-o-transition-duration": "",
"transition-duration":""
});
callback();
}, settings.animation_speed);
}
container.children().css({
"transform":"",
"-ms-transform":"",
"-webkit-transition-duration":"",
"-moz-transition-duration": "",
"-o-transition-duration": "",
"transition-duration":""
});
current.addClass("animate-out");
prev.addClass("animate-in");
};
};
Foundation.libs = Foundation.libs || {};
Foundation.libs.orbit = {
name: 'orbit',
version: '5.2.2',
settings: {
animation: 'slide',
timer_speed: 10000,
pause_on_hover: true,
resume_on_mouseout: false,
next_on_click: true,
animation_speed: 500,
stack_on_small: false,
navigation_arrows: true,
slide_number: true,
slide_number_text: 'of',
container_class: 'orbit-container',
stack_on_small_class: 'orbit-stack-on-small',
next_class: 'orbit-next',
prev_class: 'orbit-prev',
timer_container_class: 'orbit-timer',
timer_paused_class: 'paused',
timer_progress_class: 'orbit-progress',
timer_show_progress_bar: true,
slides_container_class: 'orbit-slides-container',
preloader_class: 'preloader',
slide_selector: '*',
bullets_container_class: 'orbit-bullets',
bullets_active_class: 'active',
slide_number_class: 'orbit-slide-number',
caption_class: 'orbit-caption',
active_slide_class: 'active',
orbit_transition_class: 'orbit-transitioning',
bullets: true,
circular: true,
timer: true,
variable_height: false,
swipe: true,
before_slide_change: noop,
after_slide_change: noop
},
init : function (scope, method, options) {
var self = this;
this.bindings(method, options);
},
events : function (instance) {
var self = this;
var orbit_instance = new Orbit(this.S(instance), this.S(instance).data('orbit-init'));
this.S(instance).data(self.name + '-instance', orbit_instance);
},
reflow : function () {
var self = this;
if (self.S(self.scope).is('[data-orbit]')) {
var $el = self.S(self.scope);
var instance = $el.data(self.name + '-instance');
instance.compute_dimensions();
} else {
self.S('[data-orbit]', self.scope).each(function(idx, el) {
var $el = self.S(el);
var opts = self.data_options($el);
var instance = $el.data(self.name + '-instance');
instance.compute_dimensions();
});
}
}
};
}(jQuery, this, this.document));
|
git://github.com/dmjs/dm.js.git
|
demoApp.controller('main', [ "$scope", function($scope) {
$scope.name = "test";
}]);
demoApp.controller('SimpleController', [ "$scope", function($scope) {
$scope.name = "test";
}]); |
describe('The specs from the ruby source project', function(){
var cut;
beforeEach(function(){
cut = require('../js/htmldiff');
});
it('should diff text', function(){
var diff = cut('a word is here', 'a nother word is there');
expect(diff).equal('a<ins data-operation-index="1"> nother</ins> word is ' +
'<del data-operation-index="3">here</del><ins data-operation-index="3">' +
'there</ins>');
});
it('should insert a letter and a space', function(){
var diff = cut('a c', 'a b c');
expect(diff).equal('a <ins data-operation-index="1">b </ins>c');
});
it('should remove a letter and a space', function(){
var diff = cut('a b c', 'a c');
diff.should == 'a <del data-operation-index="1">b </del>c';
});
it('should change a letter', function(){
var diff = cut('a b c', 'a d c');
expect(diff).equal('a <del data-operation-index="1">b</del>' +
'<ins data-operation-index="1">d</ins> c');
});
});
|
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import myProfileComponent from './my-profile.component';
let myProfileModule = angular.module('my-profile', [
uiRouter
])
.config(($stateProvider) => {
$stateProvider
.state('my-profile', {
url: '/my-profile',
template: '<my-profile></my-profile>'
});
})
.directive('myProfile', myProfileComponent);
export default myProfileModule; |
/* eslint-disable no-param-reassign, consistent-return */
import { useEffect, useRef } from "react";
export const useESCKey = ({ condition, element, listener }) =>
useEffect(() => {
if (condition) {
const handleKeyDown = (event) => {
if (event.key === "Escape") listener?.(event);
};
element.addEventListener("keydown", handleKeyDown);
return () => {
element.removeEventListener("keydown", handleKeyDown);
};
}
}, [condition]);
export const useChangeCallback = ({ currentValue, initialValue, onChange }) => {
const lastValue = useRef(initialValue);
useEffect(() => {
if (currentValue !== lastValue.current) onChange?.();
lastValue.current = currentValue;
}, [currentValue]);
};
|
var hub = require('mag-hub');
var format = require('mag-format-message');
var colored = require('../');
hub.pipe(format())
.pipe(colored())
.pipe(process.stdout);
var logger = require('mag')('colored-output');
logger.info('examle of %s', 'mag-format-message');
logger.debug('mag methods:\n ', logger);
var secondLogger = require('mag')('second-logger');
secondLogger.info('i am in a different color');
secondLogger.panic('panic =)');
secondLogger.alert('alert!');
secondLogger.crit('critical...');
secondLogger.err('just error');
secondLogger.warn('dangerous');
secondLogger.notice('less dangerous');
secondLogger.info('some information');
secondLogger.debug('for debugging');
|
import Ember from 'ember';
export default Ember.Component.extend({
// filteredCollection: Ember.computed.oneWay('collection'),
// _filter(query) {
// return Ember.RSVP.resolve(this.get('collection').filter((object) => {
// return object.get('title').toLowerCase().indexOf(query.toLowerCase()) >= 0;
// }));
// },
actions: {
onSelect: function (value, sb) {
const selected = this.get('collection').findBy('id', value);
this.set('value', selected);
sb.close();
},
// filter(query) {
// return this._filter(query).then((filtered) => {
// this.set('filteredCollection', filtered);
// return filtered;
// });
// },
close(e, sb) {
sb.close();
},
pressedUp(e, sb) {
sb.navigateOptionsUp();
},
pressedDown(e, sb) {
sb.navigateOptionsDown();
},
},
});
|
'use strict';
/*global Faye: true, document: true*/
var client = new Faye.Client('http://localhost:8000');
var containerDiv = document.getElementById('containerDiv');
function zeroPadding(number, len) {
if (!len && len !== 0) {
len = 2;
}
var str = String(number);
while (str.length < len) {
str = '0' + str;
}
return str;
}
// 2014-04-03 12:56:00.805
function formatDate(dateStr) {
var date = new Date(dateStr);
return date.getFullYear() + '-' +
zeroPadding(date.getMonth() + 1) + '-' +
zeroPadding(date.getDate()) + ' ' +
date.getHours() + ':' +
zeroPadding(date.getMinutes()) + ':' +
zeroPadding(date.getSeconds()) + '.' +
zeroPadding(date.getMilliseconds(), 3);
}
function localLog(str) {
var newSpan = document.createElement('p');
newSpan.innerHTML = '<span style="color:grey">' +
'[' + formatDate(new Date()) +
'] - ' + '</span>' + str;
return newSpan;
}
client.on('transport:up', function () {
containerDiv.appendChild(localLog('Connected to log server'));
document.body.scrollTop = containerDiv.scrollHeight;
});
client.on('transport:down', function () {
containerDiv.appendChild(localLog('Disconnected from log server'));
document.body.scrollTop = containerDiv.scrollHeight;
});
var colors = {
ALL: 'grey',
TRACE: 'blue',
DEBUG: '#00C0C0', //'cyan',
INFO: 'green',
WARN: '#D3A900', //'yellow',
ERROR: 'red',
FATAL: 'magenta',
OFF: 'grey'
};
function logLevelToColor(level) {
return colors[level.levelStr] || 'grey';
}
function formatLog(loggingEvent) {
var i,
result = '<span style="color:' + logLevelToColor(loggingEvent.level) + '">' +
'[' + formatDate(loggingEvent.startTime) +
'] [' + loggingEvent.level.levelStr +
'] ' + loggingEvent.categoryName +
' - ' + '</span>' + loggingEvent.data[0];
if (loggingEvent.data && loggingEvent.data.length > 1) {
for (i = 1; i < loggingEvent.data.length; i += 1) {
result += '<br>' + loggingEvent.data[i];
}
}
return result;
}
function messageToSpan(message) {
var newSpan = document.createElement('p');
newSpan.innerHTML = formatLog(message);
return newSpan;
}
client.subscribe('/testchannel', function (message) {
containerDiv.appendChild(messageToSpan(message));
document.body.scrollTop = containerDiv.scrollHeight;
});
client.disable('autodisconnect'); |
import { CHANGE_SHARED_TITLE } from './constants';
export function changeSharedTitle(newTitle) {
return {
type: CHANGE_SHARED_TITLE,
payload: newTitle
}
}
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import Chart from '../components/chart';
class WeatherList extends Component {
renderWeather(cityData) {
const name = cityData.city.name;
const temps = cityData.list.map(weather => 9/5 * (weather.main.temp - 273) + 32);
const pressures = cityData.list.map(weather => weather.main.pressure / 68.94757293168);
const humidities = cityData.list.map(weather => weather.main.humidity);
return (
<tr key={name}>
<td>{name}</td>
<td><Chart data={temps} color="orange" /></td>
<td><Chart data={pressures} color="green" /></td>
<td><Chart data={humidities} color="black" /></td>
</tr>
);
}
render() {
return (
<table className="table table-hover">
<thead>
<tr>
<th>City</th>
<th>Temperature (°F)</th>
<th>Pressure (psi)</th>
<th>Humidity (%)</th>
</tr>
</thead>
<tbody>
{this.props.weather.map(this.renderWeather)}
</tbody>
</table>
);
}
}
function mapStateToProps({ weather }) {
return { weather };
}
export default connect(mapStateToProps)(WeatherList); |
'use strict';
var config = require('./config/gulp.config');
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var $$ = $.loadUtils(['colors', 'env', 'log', 'pipeline']);
var _ = require('lodash');
require('require-dir')('./tasks');
gulp.task('default', ['dev']);
|
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
*/
var utils = require('cordova/utils');
function each (objects, func, context) {
for (var prop in objects) {
if (objects.hasOwnProperty(prop)) {
func.apply(context, [objects[prop], prop]);
}
}
}
function clobber (obj, key, value) {
exports.replaceHookForTesting(obj, key);
var needsProperty = false;
try {
obj[key] = value;
} catch (e) {
needsProperty = true;
}
// Getters can only be overridden by getters.
if (needsProperty || obj[key] !== value) {
utils.defineGetter(obj, key, function () {
return value;
});
}
}
function assignOrWrapInDeprecateGetter (obj, key, value, message) {
if (message) {
utils.defineGetter(obj, key, function () {
console.log(message);
delete obj[key];
clobber(obj, key, value);
return value;
});
} else {
clobber(obj, key, value);
}
}
function include (parent, objects, clobber, merge) {
each(objects, function (obj, key) {
try {
var result = obj.path ? require(obj.path) : {};
if (clobber) {
// Clobber if it doesn't exist.
if (typeof parent[key] === 'undefined') {
assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
} else if (typeof obj.path !== 'undefined') {
// If merging, merge properties onto parent, otherwise, clobber.
if (merge) {
recursiveMerge(parent[key], result);
} else {
assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
}
}
result = parent[key];
} else {
// Overwrite if not currently defined.
if (typeof parent[key] === 'undefined') {
assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
} else {
// Set result to what already exists, so we can build children into it if they exist.
result = parent[key];
}
}
if (obj.children) {
include(result, obj.children, clobber, merge);
}
} catch (e) {
utils.alert('Exception building Cordova JS globals: ' + e + ' for key "' + key + '"');
}
});
}
/**
* Merge properties from one object onto another recursively. Properties from
* the src object will overwrite existing target property.
*
* @param target Object to merge properties into.
* @param src Object to merge properties from.
*/
function recursiveMerge (target, src) {
for (var prop in src) {
if (src.hasOwnProperty(prop)) {
if (target.prototype && target.prototype.constructor === target) {
// If the target object is a constructor override off prototype.
clobber(target.prototype, prop, src[prop]);
} else {
if (typeof src[prop] === 'object' && typeof target[prop] === 'object') {
recursiveMerge(target[prop], src[prop]);
} else {
clobber(target, prop, src[prop]);
}
}
}
}
}
exports.buildIntoButDoNotClobber = function (objects, target) {
include(target, objects, false, false);
};
exports.buildIntoAndClobber = function (objects, target) {
include(target, objects, true, false);
};
exports.buildIntoAndMerge = function (objects, target) {
include(target, objects, true, true);
};
exports.recursiveMerge = recursiveMerge;
exports.assignOrWrapInDeprecateGetter = assignOrWrapInDeprecateGetter;
exports.replaceHookForTesting = function () {};
|
'use strict'
const path = require('path')
module.exports = {
environment: 'development',
db_url: 'sqlite://' + path.join(__dirname, '../', 'db.sqlite'),
port: 3000
}
|
var gulp = require('gulp');
var styleguide = require('sc5-styleguide');
var sass = require('gulp-sass');
var concat = require('gulp-concat');
var babel = require("gulp-babel");
var uglify = require("gulp-uglify");
var outputPath = 'styleguide';
gulp.task('styleguide:generate', function () {
return gulp.src('src/stylesheets/**/*.scss')
.pipe(styleguide.generate({
title: 'SmartCampus Styleguide',
server: true,
disableEncapsulation: true,
extraHead: [
'<script src="../bower_components/jquery/dist/jquery.min.js"></script>',
'<script src="../dist/smartcampus-ui.js"></script>'],
rootPath: outputPath,
overviewPath: 'overview.md'
}))
.pipe(gulp.dest(outputPath));
});
gulp.task('styleguide:applystyles', function () {
return gulp.src('dist/smartcampus-ui.css')
.pipe(sass({
errLogToConsole: true
}))
.pipe(styleguide.applyStyles())
.pipe(gulp.dest(outputPath));
});
gulp.task('styleguide', ['styleguide:generate', 'styleguide:applystyles']);
gulp.task('watch', ['styleguide'], function () {
// Styleguide automatically detects existing server instance
gulp.watch(['*.scss'], ['styleguide']);
});
gulp.task('build', function () {
gulp.src(['src/javascripts/components/tooltip.js',
'src/javascripts/components/collapse.js',
'src/javascripts/components/affix.js',
'src/javascripts/components/alert.js',
'src/javascripts/components/button.js',
'src/javascripts/components/modal.js',
'src/javascripts/components/transition.js',
'src/javascripts/components/tab.js',
'src/javascripts/components/scrollspy.js',
'src/javascripts/components/popover.js',
'src/javascripts/components/dropdown.js',
])
.pipe(babel())
.pipe(concat('smartcampus-ui.js'))
.pipe(gulp.dest('dist/'))
.pipe(uglify())
.pipe(concat('smartcampus-ui.min.js'));
gulp
.src('src/stylesheets/smartcampus-ui.css')
.pipe(gulp.dest('dist'));
}); |
'use strict';
const electron = require('electron');
const menubar = require('menubar');
const electronDebug = require('electron-debug');
const electronDetach = require('electron-detach');
if (electronDetach({ requireCmdlineArg: false })) {
electronDebug();
const mb = menubar({
dir: __dirname + '/src/',
preloadWindow: true,
'window-position': 'trayBottomLeft'
});
mb.on('ready', () => {
mb.tray.setContextMenu(
electron.Menu.buildFromTemplate([{
label: 'Edit tunnels',
click: () => mb.showWindow()
}, {
label: 'Exit',
click: () => electron.app.quit()
}])
);
mb.window.setSkipTaskbar(true);
mb.window.webContents.executeJavaScript('require("./app.js");');
});
}
|
'use strict';
// Use applicaion configuration module to register a new module
ApplicationConfiguration.registerModule('soluznodes'); |
define(function () {
return 'dependency';
});
|
import { APP_NAME, APP_URL, LANDING_PAGE_URL, SUPPORT_EMAIL, LIQUID_TOKEN, DEBT_TOKEN, DEBT_TOKEN_SHORT, CURRENCY_SIGN, VESTING_TOKEN, LIQUID_TICKER } from 'config/client_config';
/**
* see: app/locales/README.md
*/
export const ua = {
// this variables mainly used in navigation section
about: "Про проект",
explore: "Досліджувати",
APP_NAME_whitepaper: "Папір про " + APP_NAME,
buy_LIQUID_TOKEN: 'Купити ' + LIQUID_TOKEN,
sell_LIQUID_TOKEN: 'Продати ' + LIQUID_TOKEN,
market: "Біржа",
stolen_account_recovery: "Повернення вкраденого акаунта",
change_account_password: "Змінити пароль акаунта",
APP_NAME_chat: APP_NAME + " чат",
witnesses: "Делегати",
privacy_policy: "Політика Конфіденційності",
terms_of_service: "Умови користування",
sign_up: "Реєстрація",
/* end navigation */
buy: 'Купити',
sell: 'Продати',
buy_INVEST_TOKEN: 'Купити ' + VESTING_TOKEN,
transaction_history: 'Історія транзакцій',
submit_a_story: 'Додати пост',
nothing_yet: 'Поки нічого немає',
close: 'Закрити',
// next 5 strings were supposed to be sinngle block of text, but due large size,
// code erros they were splitted.
authors_get_paid_when_people_like_you_upvote_their_post: 'В мережі Голос автори отримують винагороду, коли користувачі голосують за їх пости.',
if_you_enjoyed_what_you_read_earn_amount: "Читачі, які проголосували, також отримують винагороду. Якщо вам сподобався цей пост Ви можете нагородити автора.",
when_you: "Для цього",
when_you_link_text: 'зареєструйтесь',
and_vote_for_it: 'та проголосуйте за пост',
// post_promo_text: "Автори отримують винагороду, коли користувачі голосують за їх пости<br />Люди, які проголосували, також отримать винагороду. Якщо вам сподобалось те, що ви прочитали тут, заробіть{amount} в " + VESTING_TOKEN + "<br />. Для цього {link} і проголосуєте за пост.",
read_only_mode: 'Через технічне обслуговування сервера ми працюємо в режимі читання. Вибачте за незручність.',
membership_invitation_only: 'Стати користувачем Голоса зараз можливо тільки по запрошенню. Зверніться до ваших знайомих про запрошення.', // бажаючих зареєструватися ?
submit_email_to_get_on_waiting_list: 'Додайте адресу вашої електронної пошти, щоб потрапити в список очікування',
login: 'Увійти',
logout: 'Вийти',
show_less_low_value_posts: "Показати менше повідомлень низької вартості",
show_more_low_value_posts: "Показати більше повідомлень низької вартості",
select_topic: 'Вибрати топік',
tags_and_topics: "Теги і топіки",
filter: "Фільтр",
show_more_topics: "Показати більше топікив",
we_require_social_account: APP_NAME + ' спонсує кожен акаунт на суму близько {signup_bonus} в ' + VESTING_TOKEN + '; щоб запобігти зловживання, ми просимо нових користувачів реєструватися використовуючи соціальні мережі.',
personal_info_will_be_private: 'Ваша персональна інформація буде залишатися',
personal_info_will_be_private_link: 'приватною',
continue_with_facebook: 'Продовжити з Facebook',
continue_with_reddit: 'Продовжити з Reddit',
continue_with_vk: 'Продовжити з Vk',
requires_positive_karma: 'необхідна позитивна карма Reddit коментуваня',
dont_have_facebook: 'Нема Facebook чи Reddit акаунта?',
subscribe_to_get_sms_confirm: 'Підпишіться щоб отримати СМС коли підтвердження буде доступно',
by_verifying_you_agree: 'Підтверджуючи ваш акаунт ви погоджуєтеся з умовами проекту ' + APP_NAME,
by_verifying_you_agree_terms_and_conditions: 'умовами та угодами',
terms_and_conditions: 'Умови та Угоди',
// this is from top-right dropdown menu
hot: 'Актуальне',
trending: 'Популярне',
payout_time: 'час виплати',
active: 'Обговорення',
responses: 'відповіді',
popular: 'популярне',
/* end dropdown menu */
loading: 'Завантаження',
cryptography_test_failed: 'Криптографічний тест провалений',
unable_to_log_you_in: 'У нас не вийде авторизувати вас в цьому браузері',
// next 3 blocks will be used in conjunction
/* this is how it will look like:
'The latest versions of <a href="https://www.google.com/chrome/">Chrome</a> and <a href="https://www.mozilla.org/en-US/firefox/new/">Firefox</a> are well tested and known to work with steemit.com.' */
the_latest_versions_of: 'Останні версії',
and: 'і',
are_well_tested_and_known_to_work_with: 'добре тестовані і працюють з ' + APP_URL + '.',
account_creation_succes: 'Ваш акаунт успішно створений!',
account_recovery_succes: 'Ваш акаунт успішно відновлено!',
password_update_succes: 'Пароль для {accountName} був успішно оновлений',
password_is_bound_to_your_accounts_owner_key: "Цей пароль прив'язаний до головного ключу акаунта і не може бути використаний для авторизації на сайті",
however_you_can_use_it_to: "Проте його можна використовувати щоб",
to_obtaion_a_more_secure_set_of_keys: "для отримання більш безпечного набору ключів",
update_your_password: 'оновити свій пароль',
enter_username: 'Введіть своє ім\'я користувача',
password_or_wif: 'Пароль чи WIF',
requires_auth_key: 'Ця операція вимагає ваш {authType} ключ (або використайте головний пароль)',
keep_me_logged_in: 'Залишати мене авторизованим',
// this are used mainly in "submit a story" form
title: "Заголовок",
write_your_story: 'Написати свою історію',
editor: 'Редактор',
reply: 'Відповісти',
edit: 'Редагувати',
delete: 'Видалити',
cancel: 'Відміна',
clear: 'Очистити',
save: 'Зберегти',
upvote_post: 'Проголосувати за пост',
update_post: 'Оновити пост',
markdown_is_supported: 'підтримується стилізація с Markdown',
preview: 'Попередній перегляд',
markdown_not_supported: 'Markdown тут не підтримується',
welcome_to_the_blockchain: 'Ласкаво просимо в Blockchain!',
your_voice_is_worth_something: 'Твій голос чогось вартий',
learn_more: 'Дізнатися більше',
get_INVEST_TOKEN_when_sign_up: 'Отримай {signupBonus} ' + VESTING_TOKEN + ' підписавшись сьогодні.',
all_accounts_refunded: 'Всі втрати по відновленним акаунтам були повністью компенсовані',
APP_URL_is_now_open_source: APP_URL + ' тепер Open Source',
// this is mainly from ReplyEditor
tag_your_story: 'Додай теги (до 5 штук), перший тег стане основною категорією.',
select_a_tag: 'Вибрати тег',
required: 'Обов\'язково',
shorten_title: 'Скоротити заголовок',
exceeds_maximum_length: 'Перевищує максимальну довжину ({maxKb}KB)',
including_the_category: "(включаючи категорію '{rootCategory}')",
use_limited_amount_of_tags: 'У вас {tagsLength} тегів, включаючи {includingCategory}. Будь ласка, використовуйте не більше 5 в пості і категорії.',
// this is mainly used in CategorySelector
maximum_tag_length_is_24_characters: 'Максимальна довжина категорії 24 знака',
use_limitied_amount_of_categories: 'Будь ласка, використовуйте не більше {amount} категорій',
use_only_lowercase_letters: 'Використовуйте тільки символи нижнього регістра',
use_one_dash: 'Використовуйте тільки одне тире',
use_spaces_to_separate_tags: 'Використовуйте пробіл щоб розділити теги',
use_only_allowed_characters: 'Використовуйте тільки малі літери, цифри і одне тире',
must_start_with_a_letter: 'Має починатися з літери',
must_end_with_a_letter_or_number: 'Має закінчуватися з букви або номера',
// tags page
tag: 'Тег',
replies: 'Відповіді',
payouts: 'Виплати',
need_password_or_key: 'Вам потрібен приватний пароль або ключ (не публічний ключ)',
// BlocktradesDeposit
change_deposit_address: 'Змінити адресу депозиту',
get_deposit_address: 'Отримати адресу депозиту',
// for example 'powered by Blocktrades'
powered_by: 'Powered by', // NOTE this might be deleted in future
send_amount_of_coins_to: 'Надіслати {value} {coinName} до',
amount_is_in_form: 'Сума повинна бути в форматі 99999.999',
insufficent_funds: 'Недостатньо коштів',
update_estimate: 'Оновити оцінку',
get_estimate: 'Отримати оцінку',
memo: 'Замітка',
must_include_memo: 'Необхідно увімкнути замітку',
estimate_using: 'Підрахувати використовуючи',
amount_to_send: 'Сума до відправки {estimateInputCoin}',
deposit_using: 'Поповнити через', // example: 'deposit using Steem Power' // TODO: is this example right?
suggested_limit: 'Передбачуваний ліміт {depositLimit}',
internal_server_error: 'Внутрішня помилка сервера',
enter_amount: 'Ввести кількість',
processing: 'Обробляється',
broadcasted: 'Транслюється',
confirmed: 'Підтверджено',
remove: 'Видалити',
collapse_or_expand: "Згорнути/Розгорнути",
reveal_comment: 'Показати коментар',
are_you_sure: 'Ви впевнені?',
// PostFull.jsx
by: ' ', // тут спеціально нічого немає, приклад: "posted by 'Vitya'" > "додав 'Vitya'"
in: 'у',
share: 'Поділитися',
in_reply_to: 'у відповідь на',
replied_to: 'відповів', // теж що і 'by'
transfer_amount_to_INVEST_TOKEN: "Перекласти {amount} у " + VESTING_TOKEN,
transfer_amount_INVEST_TOKEN_to: "Переклад {amount} " + VESTING_TOKEN + " у",
recieve_amount_INVEST_TOKEN_from: "Отримання {amount} " + VESTING_TOKEN + " від",
transfer_amount_INVEST_TOKEN_from_to: "Передати{amount} " + VESTING_TOKEN + " від {from} до",
transfer_amount_to: "Переклад {amount} на рахунок",
recieve_amount_from: "Отримано {amount} від",
transfer_amount_from: "Переклад {amount} з рахунку",
transfer_amount_steem_power_to: "Переклад {amount} " + LIQUID_TICKER + " в Силу Голосу",
stop_power_down: "Ослаблення Сили Голосу зупинено",
start_power_down_of: "Ослаблення Сили Голосу розпочато з",
curation_reward_of_INVEST_TOKEN_for: 'Кураторські винагороди {reward} ' + VESTING_TOKEN + ' за',
author_reward_of_INVEST_TOKEN_for: 'Авторські винагороди {payout} і {reward} ' + VESTING_TOKEN + ' за',
recieve_interest_of: 'Отримано відсотки в розмірі {interest}',
// TODO find where this is used and write an example
from: 'ві',
to: 'до',
account_not_found: 'Акаунт не знайдено',
this_is_wrong_password: 'Це неправильний пароль',
do_you_need_to: 'Вам потрібно',
recover_your_account: 'відновити ваш аккаунт', // this probably will end with question mark
reset_usernames_password: "Скинути пароль користувача {username}",
this_will_update_usernames_authtype_key: 'Це оновить {username} {authType} ключ',
the_rules_of_APP_NAME: "Перше правило мережі " + APP_NAME + ": не втрачайте свій пароль. <br /> Друге правило " + APP_NAME + ": <strong>Не</strong> втрачайте свій пароль. <br /> Третє правило " + APP_NAME + ": ми не можемо відновити ваш пароль. <br /> Четверте правило: якщо ви можете запам'ятати свій пароль, значить він не безпечний. <br /> П'яте правило: використовуйте тільки згенеровані випадковим чином паролі. <br /> Шосте правило: Нікому не кажіть свій пароль. <br /> Сьоме правило: Завжди надійно зберігайте свій пароль.",
account_name: 'Ім\'я облікового запису',
recover_password: 'Відновити акаунт',
current_password: 'Поточний пароль',
recent_password: 'Недавній пароль',
generated_password: 'Згенерований пароль',
recover_account: 'Відновити акаунт',
new: 'Нове', // ex. 'Generated Password (new)', but not exclusively
backup_password_by_storing_it: 'Зробіть резервну копію в менеджері паролів або текстовому файлі',
click_to_generate_password: 'Натисніть щоб згенерувати пароль',
re_enter_generate_password: 'Повторно введіть пароль',
understand_that_APP_NAME_cannot_recover_password: 'Я розумію що ' + APP_NAME + ' не зможе відновити втрачений пароль',
i_saved_password: 'Я надійно зберіг згенерований пароль',
update_password: 'Оновити пароль',
password_must_be_characters_or_more: 'Пароль повинен бути {amount} символів або більше',
passwords_do_not_match: 'Паролі не співпадають',
you_need_private_password_or_key_not_a_public_key: 'Вам потрібен приватний пароль або ключ (не публічний ключ)',
account_updated: 'Акаунт оновлений',
warning: 'увага',
your_password_permissions_were_reduced: 'Ваш дозвіл паролю був знижен',
if_you_did_not_make_this_change: 'Якщо ви не робили цих змін, будь ласка',
owhership_changed_on: 'Власність змінена на',
deadline_for_recovery_is: 'Крайнім терміном для відновлення є',
i_understand_dont_show_again: "Розумію, більше не показувати",
ok: 'Ок', // Краще використовувати "добре" або "гаразд"?
convert_to_INVEST_TOKEN: 'Перевести в ' + VESTING_TOKEN,
DEBT_TOKEN_will_be_unavailable: 'Ця операція буде проходити через тиждень від справжнього моменту і її не можна скасувати. Ці ' + DEBT_TOKEN + ' миттєво стануть недоступні',
amount: 'Кількість',
convert: 'Конвертувати',
invalid_amount: 'Неправильна кількість',
insufficent_balance: 'Недостатній баланс',
in_week_convert_DEBT_TOKEN_to_LIQUID_TOKEN: 'За тиждень перевести {amount} ' + DEBT_TOKEN + ' в ' + LIQUID_TOKEN,
order_placed: 'Замовлення розміщенно', // ex.: "Order placed: Sell {someamount_to_sell} for atleast {min_to_receive}"
follow: 'Підписатися',
unfollow: 'Відписатися',
mute: 'Блокувати',
unmute: 'Розблокувати',
confirm_password: 'Підтвердити пароль',
login_to_see_memo: 'увійти щоб побачити замітку',
post: 'Пост', // places used: tooltip in MediumEditor
unknown: 'Невідомий', // exp.: 'unknown error'
account_name_is_not_available: 'Ім\'я облікового запису недоступно',
type: 'Тип',
price: 'Ціна',
// Market.jsx
last_price: 'Остання ціна',
'24h_volume': 'Обсяг за 24 години',
bid: 'Покупка',
ask: 'Продаж',
spread: 'Різниця',
total: 'Разом',
available: 'Доступно',
lowest_ask: 'Краща ціна продажу',
highest_bid: 'Краща ціна покупки',
buy_orders: 'Замовлення на покупку',
sell_orders: 'Замовлення на продаж',
trade_history: 'Історія угод',
open_orders: 'Відкриті угоди',
sell_amount_for_atleast: 'Продати {amount_to_sell} за {min_to_receive} за ціною ({effectivePrice})',
buy_atleast_amount_for: 'Купити {min_to_receive} за {amount_to_sell} ({effectivePrice})',
higher: 'Дорожче', // context is about prices
lower: 'Дешевше', // context is about prices
total_DEBT_TOKEN_SHORT_CURRENCY_SIGN: "Сума " + DEBT_TOKEN_SHORT + ' (' + CURRENCY_SIGN + ')',
// RecoverAccountStep1.jsx // recover account stuff
not_valid: 'Недійсне',
account_name_is_not_found: 'Ім\'я облікового запису не знайдено',
unable_to_recover_account_not_change_ownership_recently: 'У нас не вийшло відновити цей акаунт, тому що він не змінював власника в недавні часи.',
password_not_used_in_last_days: 'Цей пароль не використовувався в цьому акаунті за останні 30 днів.',
request_already_submitted_contact_support: 'Ваш запит був відправлений, і ми працюємо над цим. Будь ласка, зв`яжіться з ' + SUPPORT_EMAIL + ' для отримання статусу вашого запиту.',
recover_account_intro: "Іноді буває що ключ власника може бути скомпрометований. Відновлення вкраденого акаунта дає законному власнику 30 днів щоб повернути аккаунт з моменту зміни власного ключа шахраєм. Відновлення вкраденого акаунта в " + APP_URL + " можливо тільки якщо власник акаунта раніше вказав '" + APP_NAME + "' як довірена особа і погодився з Умовами Використання сайту " + APP_NAME + ".",
login_with_facebook_or_reddit_media_to_verify_identity: 'Будь ласка, увійдіть використовуючи Facebook або Reddit щоб підтвердити вашу особистість',
login_with_social_media_to_verify_identity: 'Будь ласка, зайдіть за допомогою {show_social_login} щоб підтвердити вашу особистість',
enter_email_toverify_identity: 'Нам потрібно підтвердити вашу особистість. Будь ласка вкажіть вашу електронну пошту нижче, щоб почати перевірку.',
email: 'Електронна пошта',
continue_with_email: "Продовжити",
thanks_for_submitting_request_for_account_recovery: '<p>Дякуємо Вам за відправку запиту на відновлення акаунта використовуючи засновану на блокчейне мультифакторна аутентифікацію ' + APP_NAME + '’a.</p> <p>Ми відповімо Вам якнайшвидше, проте, будь ласка, очікуйте що може бути деяка затримка через великий обсяг листів.</p> <p>Будь ласка, будьте готові підтвердити свою особистість.</p>',
recovering_account: 'Відновлюємо аккаунт',
checking_account_owner: 'Перевіряємо власника акаунта',
sending_recovery_request: 'Відправляємо запит відновлення',
cant_confirm_account_ownership: 'Ми не можемо підтвердити володіння акаунтом. Перевірте ваш пароль.',
account_recovery_request_not_confirmed: "Запит відновлення акаунта ще не підтверджений, будь ласка перевірте пізніше. Дякуємо за ваше терпіння.",
vote: 'Проголосувати', // context: to vote? (title attribute on voting button)
witness: 'Делегати',
top_witnesses: 'Топ делегатів',
// user's navigational menu
feed: 'Стрічка',
wallet: 'Гаманець',
blog: 'Блог',
change_password: 'Змінити пароль',
// UserProfile
unknown_account: 'Невідомий акаунт',
user_hasnt_made_any_posts_yet: "Схоже що {name} ще не написав постів!",
user_hasnt_started_bloggin_yet: "Схоже що {name} ще не завів блог!",
user_hasnt_followed_anything_yet: "Схоже що {name} ще ні на кого не підписаний !",
user_hasnt_had_any_replies_yet: "{name} ще не отримав відповідей",
users_blog: "блог {name}",
users_posts: "пости {name}",
users_wallet: "гаманець {name}",
users_curation_rewards: "Кураторські винагороди {name}",
users_author_rewards: "Авторські винагороди {name}",
users_permissions: "Дозволи {name}",
recent_replies_to_users_posts: "Недавні відповіді до постів користувача {name}",
print: 'Роздрукувати',
curation_rewards: "Кураторські винагороди",
author_rewards: 'Авторські винагороди',
feeds: 'Стрічка',
rewards: 'Нагороди',
permissions: 'Дозволи',
password: 'Пароль',
posts: 'Пости',
// PLURALS
// see locales/README.md on how to properly use them
// context usually is about profile stats: 'User has: 3 posts, 2 followers, 5 followed'
post_count: `{postCount, plural,
zero {0 постів}
one {# пост}
few {# поста}
many {# постів}
}`,
follower_count: `{followerCount, plural,
zero {0 підписників}
one {# підписник}
few {# підписника}
many {# підписників}
}`,
followed_count: `{followingCount, plural,
zero {0 підписок}
one {# підписка}
few {# підписки}
many {# підписок}
}`,
vote_count: `{voteCount, plural,
zero {0 голосів}
one {# голос}
few {# голоса}
many {# голосів}
}`,
response_count: `{responseCount, plural,
zero {0 відповідей}
one {# відповідь}
few {# відповіді}
many {# відповідей}
}`,
reply_count: `{replyCount, plural,
zero {0 відповідей}
one {# відповідь}
few {# відповіді}
many {# відповідей}
}`,
this_is_users_reputations_score_it_is_based_on_history_of_votes: "Це кількість очок репутації користувача {name}.\n\nКількість очок підраховується на основі історії отриманих голосів і на його голосах проти контенту.",
newer: 'Новіше',
older: 'Старіше',
author_rewards_last_24_hours: 'Авторські винагороди за останні 24 години',
daily_average_author_rewards: 'Середньодобові авторські винагороди',
author_rewards_history: 'Історія авторських нагород',
balance: 'Баланс',
balances: 'Баланси',
estimate_account_value: 'Оцінка вартості акаунта',
next_power_down_is_scheduled_to_happen_at: 'Наступне зниження Сили Голосу заплановано на',
transfers_are_temporary_disabled: 'Переклади тимчасово відключені',
history: 'Історія',
// CurationRewards.jsx
curation_rewards_last_24_hours: 'Кураторські нагороди за останні 24 години',
daily_average_curation_rewards: 'Середньодобові кураторські нагороди',
estimated_curation_rewards_last_week: "Оціночні кураторські нагороди за останній тиждень",
curation_rewards_last_week: "Кураторські нагороди за останній тиждень",
curation_rewards_history: 'Історія кураторських нагород',
// Post.jsx
now_showing_comments_with_low_ratings: 'Відобразити коментарі з низьким рейтингом',
hide: 'Приховати',
show: 'Показати',
sort_order: 'Порядок сортування',
comments_were_hidden_due_to_low_ratings: 'Коментарі були закриті через низький рейтинг',
we_will_be_unable_to_create_account_with_this_browser: 'У нас не виходить створити акаунт використовуючи цей браузер',
you_need_to_logout_before_creating_account: 'Вам потрібно {logoutLink} перш ніж ви можете створити інший акаунт',
APP_NAME_can_only_register_one_account_per_verified_user: 'Будь ласка, майте на увазі що ' + APP_NAME + ' може реєструвати тільки один акаунт для кожного підтвердженого користувача',
username: 'Ім\'я користувача',
couldnt_create_account_server_returned_error: "Не вийшло створити акаунт. Сервер повернув цю помилку",
form_requires_javascript_to_be_enabled: 'Ця форма вимагає активований в браузері javascript',
our_records_indicate_you_already_have_account: 'Наші записи показують що у вас вже є ' + APP_NAME + ' акаунт',
// TODO
to_prevent_abuse_APP_NAME_can_only_register_one_account_per_user: 'Щоб запобігти зловживанню (кожен зареєстрований акаунт варто{amount} в ' + LIQUID_TOKEN + ') ' + APP_NAME + ' може реєструвати тільки один акаунт для кожного підтвердженого користувача.',
// next 3 blocks are meant to be used together
you_can_either: 'Ви можете або', // context 'you can either login'
to_your_existing_account_or: 'в ваш існуючий акаунт або', // context: 'to your existing account or send us email'
if_you_need_a_new_account: 'якщо вам потрібен новий акаунт',
send_us_email: 'надішліть нам електронну пошту',
connection_lost_reconnecting: 'Зв\'язок втрачений, перепідключитися',
// Voting.jsx
stop_seeing_content_from_this_user: 'Перестати бачити контент від цього користувача',
flagging_post_can_remove_rewards_the_flag_should_be_used_for_the_following: 'Голос проти може зняти винагороди і зробити пост менш видимим. Голосування проти повинно ґрунтуватися на',
fraud_or_plagiarism: 'Шахрайство або плагіат',
hate_speech_or_internet_trolling: 'Розпалювання ненависті або інтернет тролінг',
intentional_miss_categorized_content_or_spam: 'Навмисна неправильна категоризація контенту або спам',
downvote: 'голосувати проти',
pending_payout: 'Очікувана виплата',
past_payouts: 'Минулі виплати',
more: 'більше',
remove_vote: 'Прибрати голос',
upvote: 'Голосувати за',
we_will_reset_curation_rewards_for_this_post: 'скине ваші кураторські винагороди за цей пост',
removing_your_vote: 'Видалення голосу',
changing_to_an_upvote: 'Зміна на голос за',
changing_to_a_downvote: 'Зміна на голос проти',
confirm_flag: 'Підтвердити голос проти',
date_created: 'Дата створення',
search: 'Пошук',
begin_recovery: 'Почати відновлення',
post_as: 'Запостить як', // 'Post as Misha'
action: 'Дія',
APP_NAME_app_center: 'Центр додатків ' + APP_NAME,
witness_thread: 'пост делегата',
you_have_votes_remaining: 'У вас залишилося {votesCount} голосів',
you_can_vote_for_maximum_of_witnesses: 'Ви можете голосувати максимум за 30 делегатів',
information: 'Інформація',
if_you_want_to_vote_outside_of_top_enter_account_name: 'Якщо ви хочете проголосувати за делегата поза top 50, введіть ім\'я облікового запису нижче',
view_the_direct_parent: 'Перегляд прямого батька',
you_are_viewing_single_comments_thread_from: 'Ви читаєте одну нитку коментарів від',
view_the_full_context: 'Показати повний контекст',
this_is_a_price_feed_conversion: 'Це котування ціни. Тиждень відстрочки необхідна щоб запобігти зловживанню від гри на середньої цінової катировки.',
your_existing_DEBT_TOKEN_are_liquid_and_transferable: 'Ваші існуючі ' + DEBT_TOKEN + ' ліквідні і переміщувані. Можливо, ви хочете торгувати' + DEBT_TOKEN + ' безпосередньо на цьому сайті в розділі {link} або перевести на зовнішній ринок.',
buy_or_sell: 'Купити або Продати',
trending_30_day: 'Популярне (30 дней)',
promoted: 'Прогресивне',
comments: 'Коментарі',
topics: 'Топіки',
this_password_is_bound_to_your_accounts_private_key: 'Цей пароль прив\'язаний до активного ключу вашого облікового запису і не може бути використаний для входу на цю сторінку. Ви можете використовувати його для входу на інші більш захищені сторінки як "гаманець" або "маркет".',
potential_payout: 'Потенційна виплата',
boost_payments: 'Платіж за просування',
authors: 'Автори',
curators: 'Куратори',
date: 'Дата',
no_responses_yet_click_to_respond: 'Відповідей поки немає. Натисніть щоб відповісти.',
click_to_respond: 'Натисніть щоб відповісти',
new_password: 'Новий пароль',
paste_a_youtube_or_vimeo_and_press_enter: 'Вставте YouTube или Vimeo посилання та натисніть Enter',
there_was_an_error_uploading_your_image: 'Виникла помилка під час завантаження зображення',
raw_html: 'HTML код',
please_remove_following_html_elements: 'Будь ласка видаліть ці HTML елементи з вашого поста:',
reputation: "Репутація",
remember_voting_and_posting_key: "Запам'ятати голос і постинг ключ",
// example usage: 'Autologin? yes/no'
auto_login_question_mark: 'Входити автоматично?',
yes: 'Так',
no: 'Ні',
hide_private_key: 'Приховати приватний ключ',
show_private_key: 'Показати приватний ключ',
login_to_show: 'Увійти щоб показати',
APP_NAME_cannot_recover_passwords_keep_this_page_in_a_secure_location: APP_NAME + ' не може відновити паролі. Збережіть цю сторінку в безпечному місці, наприклад, в вогнестійкому сейфі або в депозитарному сховищі.',
APP_NAME_password_backup: APP_NAME + ' резервне копіювання пароля',
APP_NAME_password_backup_required: APP_NAME + ' резервне копіювання пароля (обов\'язково)',
after_printing_write_down_your_user_name: 'Після друку напишіть ваше ім\'я користувача',
public: 'Публічне',
private: 'Приватне',
public_something_key: 'Публічний {key} ключ',
private_something_key: 'Приватний {key} ключ',
// UserProfile > Permissions
posting_key_is_required_it_should_be_different: 'Постинг ключ використовується для постінгу і голосування. Він повинен відрізнятися від активного і ключа власника.',
the_active_key_is_used_to_make_transfers_and_place_orders: 'Активний ключ використовується для переказів і розміщення замовлень на внутрішньому ринку.',
the_owner_key_is_required_to_change_other_keys: 'Ключ власника це головний ключ до всього акаунта, він необхідний для зміни інших ключів.',
the_private_key_or_password_should_be_kept_offline: 'Приватний ключ або пароль повинен зберігатися в офлайні так швидко наскільки можливо.',
the_memo_key_is_used_to_create_and_read_memos: 'Ключ заміток використовується для створення та читання заміток.',
previous: 'Попередній',
next: 'Наступний',
browse: 'Подивитися',
not_valid_email: 'Недійсна адреса',
thank_you_for_being_an_early_visitor_to_APP_NAME: 'Дякуємо вам за те що є раннім відвідувачем ' + APP_NAME + '. Ми зв\'яжемося з вами при першій же можливості.',
estimated_author_rewards_last_week: "Оціночні авторські винагороди за минулий тиждень",
author_rewards_last_week: "Оціночні авторські винагороди за минулий тиждень",
confirm: 'Підтвердити',
asset: 'Актив',
this_memo_is_private: 'Ця замітка є приватною',
this_memo_is_public: 'Ця замітка є публічною',
power_up: 'Посилити силу голосу',
power_down: 'Зменшити силу голосу',
cancel_power_down: 'Скасувати зниження сили голосу',
transfer: 'Передати',
deposit: 'Купити',
basic: 'Базовий',
advanced: 'Високий рівень',
convert_to_LIQUID_TOKEN: 'Перевести в ' + LIQUID_TOKEN,
transfer_to_account: 'Передати користувачу',
buy_LIQUID_TOKEN_or_INVEST_TOKEN: 'Купити ' + LIQUID_TOKEN + ' чи ' + VESTING_TOKEN,
version: 'Версія',
about_APP_NAME: 'О ' + APP_NAME,
APP_NAME_is_a_social_media_platform_where_everyone_gets_paid_for_creating_and_curating_content: APP_NAME + ' це соціальна медіа платформа в якій<strong>всі</strong> отримують <strong>гроші</strong> за створення і курирування контенту',
APP_NAME_is_a_social_media_platform_where_everyone_gets_paid: APP_NAME + ' це соціальна медіа платформа в якій кожен заробляє за створення і курирування контенту. Він використовує надійну систему цифрових очок під назвою' + LIQUID_TOKEN + ', який підтримує реальну цінність для цифрових нагород через виявлення ринкової ціни і ліквідності.',
learn_more_at_LANDING_PAGE_URL: 'Дізнатись більше в ' + LANDING_PAGE_URL,
resources: 'Ресурси',
join_our_slack: 'Приєднуйтесь до нашого Slack',
APP_NAME_support: APP_NAME + ' підтримка',
please_email_questions_to: 'Будь ласка, надішліть ваші запитання на електронну пошту',
sorry_your_reddit_account_doesnt_have_enough_karma: "Вибачте, у вашого Reddit акаунта недостатньо Reddit карми щоб мати можливість безкоштовної реєстрації. Будь ласка, додайте вашу електронну пошту щоб записатися в лист очікування",
register_with_facebook: 'Реєстрація з Facebook',
or_click_the_button_below_to_register_with_facebook: 'Або натисніть кнопку, щоб зареєструватися з Facebook',
trending_24_hour: 'популярне (24 години)',
home: 'Стрічка',
'24_hour': '24 години',
'30_day': '30 днів',
flag: "Голосувати проти",
promote: 'Просунути',
// Tips.js
tradeable_tokens_that_may_be_transferred_anywhere_at_anytime: 'Переміщувані цифрові токени, які можуть бути передані куди завгодно в будь-який момент.',
LIQUID_TOKEN_can_be_converted_to_INVEST_TOKEN_in_a_process_called_powering_up: LIQUID_TOKEN + ' може бути конвертований в ' + VESTING_TOKEN + ', цей процес називається "посилення голосу".',
tokens_worth_about_AMOUNT_of_LIQUID_TOKEN: 'Переміщувані цифрові токени, ціна яких завжди дорівнює ~1 мг золота в ' + LIQUID_TOKEN + '.',
influence_tokens_which_earn_more_power_by_holding_long_term: 'Непереміщуваними цифрові токени, їх кількість збільшується при довгостроковому зберіганні.',
the_more_you_hold_the_more_you_influence_post_rewards: 'Чим їх більше, тим сильніше ви впливаєте на винагороди за пост і тим більше заробляєте за голосування.',
the_estimated_value_is_based_on_a_7_day_average_value_of_LIQUID_TOKEN_in_currency: 'Оціночна вартість розраховується з 7-ми денної середньої вартості ' + LIQUID_TOKEN + '.',
INVEST_TOKEN_is_non_transferrable_and_will_require_2_years_and_104_payments_to_convert_back_to_LIQUID_TOKEN: VESTING_TOKEN + ' не можна передавати і буде потрібно 2 роки і 104 виплати щоб перевести назад в ' + LIQUID_TOKEN + '.',
// TODO
converted_INVEST_TOKEN_can_be_sent_to_yourself_but_can_not_transfer_again: 'Конвертированная ' + VESTING_TOKEN + ' може бути відправлена собі або комусь ще, але не може бути передана знову без конвертації назад в ' + LIQUID_TOKEN + '.',
profile: 'Профіль',
send_to_account: 'Надіслати акаунту',
confirm_email: 'Підтвердити електронну пошту',
authenticate_for_this_transaction: 'Авторизуйтесь для цієї транзакції',
login_to_your_APP_NAME_account: 'Зайдіть в ваш ' + APP_NAME + ' акаунт',
// UserProfile > Permissions
posting: 'Постинг',
owner: 'Власник',
active_or_owner: 'активний або власника',
sign: 'Увійти',
dismiss: 'Приховати',
// next 3 strings are used conditionally together
show_more: 'Показати більше',
show_less: 'Показати менше',
value_posts: 'повідомлень низької вартості',
// PormotePost.jsx
leave_this_unchecked_to_receive_half_your_reward: 'не намагайтеся покинути Омськ',
promote_post: 'Просунути пост',
spend_your_DEBT_TOKEN_to_advertise_this_post: 'Використовуйте ваші ' + DEBT_TOKEN + ' щоб прорекламувати цей пост в секції просуваємого контенту',
you_successdully_promoted_this_post: 'Ви успішно просунули цей пост',
pay_me_100_in_INVEST_TOKEN: 'Заплатіть мені 100% в ' + VESTING_TOKEN,
requires_5_or_more_reddit_comment_karma: 'необхідно 5 або більше Reddit карми коментування',
this_post_was_hidden_due_to_low_ratings: 'Цей пост був закритий через низький рейтинг',
reblogged_by: 'Поділився',
reblog: 'Поділитися',
updated: 'Оновлене',
created: 'Нове',
settings: 'Налаштування',
incorrect_password: 'Неправильний пароль',
username_does_not_exist: 'Такого імені не існує',
// string with a '.'(dot) is returned from the server, so you should add it too, despite rules
account_name_should_be_longer: 'Ім\'я облікового запису має бути довшим.',
account_name_should_be_shorter: 'Ім\'я облікового запису має бути коротше.',
account_name_should_start_with_a_letter: 'Ім\'я облікового запису має починатися з літери.',
account_name_should_have_only_letters_digits_or_dashes: 'Имя акаунта должно должно состоять только из букв, цифр или дефисов.',
choose_language: 'Виберіть мову',
choose_currency: 'Виберіть валюту',
crowdsale: 'Краудсейл',
followers: 'Подписчики',
// errors
cannot_increase_reward_of_post_within_the_last_minute_before_payout: 'Нагорода за пост не може бути збільшена після закінчення 24 годин з моменту публікації',
vote_currently_exists_user_must_be_indicate_a_to_reject_witness: 'Голос вже існує, користувач повинен позначити бажання прибрати делегата',
only_one_APP_NAME_account_allowed_per_ip_address_every_10_minutes: 'Тільки один Голос аккаунт дозволений з одного IP адресу кожні десять хвилин ',
// enter_confirm_email.jsx
thank_you_for_providing_your_email_address: 'Дякуємо вам за надання вашої електронної пошти ',
to_continue_please_click_on_the_link_in_the_email_weve_sent_you: 'Для продовження, натисніть на заслання в листі, яке ми вам надіслали',
user_not_found: 'користувач не знайдений',
please_provide_your_email_address_to_continue_the_registration_process: 'Будь ласка, вкажіть адресу вашої електронної пошти, щоб продовжити процес реєстрації',
this_information_allows_steemit_to_assist_with_account_recovery_in_case_your_account_is_ever_compormised: 'Ця інформація дозволяє Голосу допомогти вам відновити акаунт, якщо він коли-небудь буде вкрадений ',
email_address_cannot_be_changed_at_this_moment_sorry_for_inconvenience: 'Адреса електронної пошти на данний момент не може бути змінена, вибачте за незручності',
continue: 'продовжити',
email_address: 'Адреса електронної пошти',
please_prove_an_email_address: 'Будь ласка вкажіть адресу електронної пошти',
failed_captcha_verification_please_try_again: 'Помилка перевірки капчі, спробуйте ще раз',
re_send_email: 'Повторна відправка електронної пошти',
email_confirmation: 'Підтвердження електронної пошти',
add_image_url: 'Додайте URL вашого зображення',
like: 'Подобатися',
}
|
import React, { useEffect, useReducer, useCallback } from 'react'
import { ActivityIndicator, StyleSheet, Text, View } from 'react-native'
import { getList } from './api/picsum'
import { actionCreators, initialState, reducer } from './reducers/photos'
import PhotoGrid from './components/PhotoGrid'
export default function App() {
return (
<View style={styles.container}>
<Text>Open up App.js to start working on your app!</Text>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
})
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+relay
*/
'use strict';
const RelayFeatureFlags = require('../../util/RelayFeatureFlags');
const RelayInMemoryRecordSource = require('../RelayInMemoryRecordSource');
const RelayModernRecord = require('../RelayModernRecord');
const RelayModernTestUtils = require('relay-test-utils-internal');
const defaultGetDataID = require('../defaultGetDataID');
const {normalize} = require('../RelayResponseNormalizer');
const {ROOT_ID, ROOT_TYPE} = require('../RelayStoreUtils');
describe('RelayResponseNormalizer', () => {
const {
generateAndCompile,
generateWithTransforms,
matchers,
} = RelayModernTestUtils;
const defaultOptions = {
getDataID: defaultGetDataID,
};
beforeEach(() => {
jest.resetModules();
expect.extend(matchers);
});
it('normalizes queries', () => {
const {FooQuery} = generateWithTransforms(
`
query FooQuery($id: ID, $size: [Int]) {
node(id: $id) {
id
__typename
... on User {
firstName
friends(first: 3) {
edges {
cursor
node {
id
firstName
}
}
}
profilePicture(size: $size) {
uri
}
}
}
}
`,
);
const payload = {
node: {
id: '1',
__typename: 'User',
firstName: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:2',
node: {
id: '2',
firstName: 'Bob',
},
},
null,
{
cursor: 'cursor:3',
node: {
id: '3',
firstName: 'Claire',
},
},
],
},
profilePicture: {
uri: 'https://...',
},
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
normalize(
recordSource,
{
dataID: ROOT_ID,
node: FooQuery.operation,
variables: {id: '1', size: 32},
},
payload,
defaultOptions,
);
const friendsID = 'client:1:friends(first:3)';
const edgeID1 = `${friendsID}:edges:0`;
const edgeID2 = `${friendsID}:edges:2`;
const pictureID = 'client:1:profilePicture(size:32)';
expect(recordSource.toJSON()).toEqual({
'1': {
__id: '1',
id: '1',
__typename: 'User',
firstName: 'Alice',
'friends(first:3)': {__ref: friendsID},
'profilePicture(size:32)': {__ref: pictureID},
},
'2': {
__id: '2',
__typename: 'User',
id: '2',
firstName: 'Bob',
},
'3': {
__id: '3',
__typename: 'User',
id: '3',
firstName: 'Claire',
},
[friendsID]: {
__id: friendsID,
__typename: 'FriendsConnection',
edges: {
__refs: [edgeID1, null, edgeID2],
},
},
[edgeID1]: {
__id: edgeID1,
__typename: 'FriendsEdge',
cursor: 'cursor:2',
node: {__ref: '2'},
},
[edgeID2]: {
__id: edgeID2,
__typename: 'FriendsEdge',
cursor: 'cursor:3',
node: {__ref: '3'},
},
[pictureID]: {
__id: pictureID,
__typename: 'Image',
uri: 'https://...',
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
});
});
it('normalizes queries with "handle" fields', () => {
const {UserFriends} = generateAndCompile(`
query UserFriends($id: ID!) {
node(id: $id) {
id
__typename
... on User {
friends(first: 1) @__clientField(handle: "bestFriends") {
edges {
cursor
node {
id
name @__clientField(handle: "friendsName")
}
}
}
}
}
}
`);
const payload = {
node: {
id: '4',
__typename: 'User',
friends: {
edges: [
{
cursor: 'cursor:bestFriends',
node: {
id: 'pet',
name: 'Beast',
},
},
],
},
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
const {fieldPayloads} = normalize(
recordSource,
{
dataID: ROOT_ID,
node: UserFriends.operation,
variables: {id: '1'},
},
payload,
defaultOptions,
);
expect(recordSource.toJSON()).toMatchSnapshot();
expect(fieldPayloads.length).toBe(2);
expect(fieldPayloads[0]).toEqual({
args: {},
dataID: 'pet',
fieldKey: 'name',
handle: 'friendsName',
handleKey: '__name_friendsName',
});
expect(fieldPayloads[1]).toEqual({
args: {first: 1},
dataID: '4',
fieldKey: 'friends(first:1)',
handle: 'bestFriends',
handleKey: '__friends_bestFriends',
});
});
it('normalizes queries with "filters"', () => {
const {UserFriends} = generateAndCompile(`
query UserFriends(
$id: ID!,
$orderBy: [String],
$isViewerFriend: Boolean,
) {
node(id: $id) {
id
__typename
... on User {
friends(first: 1, orderby: $orderBy, isViewerFriend: $isViewerFriend)@__clientField(
handle: "bestFriends",
key: "UserFriends_friends",
filters: ["orderby", "isViewerFriend"]
){
edges {
cursor
node {
id
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
}
}
`);
const payload1 = {
node: {
id: '4',
__typename: 'User',
friends: {
edges: [
{
cursor: 'cursor:bestFriends',
node: {
id: 'pet',
name: 'Beast',
},
},
],
},
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
let {fieldPayloads} = normalize(
recordSource,
{
dataID: ROOT_ID,
node: UserFriends.operation,
variables: {id: '1', orderBy: ['last name'], isViewerFriend: true},
},
payload1,
defaultOptions,
);
expect(recordSource.toJSON()).toMatchSnapshot();
expect(fieldPayloads.length).toBe(1);
expect(fieldPayloads[0]).toEqual({
args: {first: 1, orderby: ['last name'], isViewerFriend: true},
dataID: '4',
fieldKey: 'friends(first:1,isViewerFriend:true,orderby:["last name"])',
handle: 'bestFriends',
handleKey:
'__UserFriends_friends_bestFriends(isViewerFriend:true,orderby:["last name"])',
});
const payload2 = {
node: {
id: '4',
__typename: 'User',
friends: {
edges: [
{
cursor: 'cursor:bestFriends:2',
node: {
id: 'cat',
name: 'Betty',
},
},
],
},
},
};
fieldPayloads = normalize(
recordSource,
{
dataID: ROOT_ID,
node: UserFriends.operation,
variables: {id: '1', orderBy: ['first name'], isViewerFriend: true},
},
payload2,
defaultOptions,
).fieldPayloads;
expect(recordSource.toJSON()).toMatchSnapshot();
expect(fieldPayloads.length).toBe(1);
expect(fieldPayloads[0]).toEqual({
args: {first: 1, orderby: ['first name'], isViewerFriend: true},
dataID: '4',
fieldKey: 'friends(first:1,isViewerFriend:true,orderby:["first name"])',
handle: 'bestFriends',
handleKey:
'__UserFriends_friends_bestFriends(isViewerFriend:true,orderby:["first name"])',
});
});
describe('@match', () => {
let BarQuery;
beforeEach(() => {
const nodes = generateAndCompile(`
fragment PlainUserNameRenderer_name on PlainUserNameRenderer {
plaintext
data {
text
}
}
fragment MarkdownUserNameRenderer_name on MarkdownUserNameRenderer {
markdown
data {
markup
}
}
fragment BarFragment on User {
id
nameRenderer @match {
...PlainUserNameRenderer_name
@module(name: "PlainUserNameRenderer.react")
...MarkdownUserNameRenderer_name
@module(name: "MarkdownUserNameRenderer.react")
}
}
query BarQuery($id: ID!) {
node(id: $id) {
...BarFragment
}
}
`);
BarQuery = nodes.BarQuery;
});
it('normalizes queries correctly', () => {
const payload = {
node: {
id: '1',
__typename: 'User',
nameRenderer: {
__typename: 'MarkdownUserNameRenderer',
__module_component_BarFragment: 'MarkdownUserNameRenderer.react',
__module_operation_BarFragment:
'MarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
markup: '<markup/>',
},
},
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
const {moduleImportPayloads} = normalize(
recordSource,
{
dataID: ROOT_ID,
node: BarQuery.operation,
variables: {id: '1'},
},
payload,
defaultOptions,
);
expect(recordSource.toJSON()).toEqual({
'1': {
__id: '1',
id: '1',
__typename: 'User',
'nameRenderer(supported:["PlainUserNameRenderer","MarkdownUserNameRenderer"])': {
__ref:
'client:1:nameRenderer(supported:["PlainUserNameRenderer","MarkdownUserNameRenderer"])',
},
},
'client:1:nameRenderer(supported:["PlainUserNameRenderer","MarkdownUserNameRenderer"])': {
__id:
'client:1:nameRenderer(supported:["PlainUserNameRenderer","MarkdownUserNameRenderer"])',
__typename: 'MarkdownUserNameRenderer',
__module_component_BarFragment: 'MarkdownUserNameRenderer.react',
__module_operation_BarFragment:
'MarkdownUserNameRenderer_name$normalization.graphql',
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
});
expect(moduleImportPayloads).toEqual([
{
operationReference:
'MarkdownUserNameRenderer_name$normalization.graphql',
dataID:
'client:1:nameRenderer(supported:["PlainUserNameRenderer","MarkdownUserNameRenderer"])',
data: {
__typename: 'MarkdownUserNameRenderer',
__module_component_BarFragment: 'MarkdownUserNameRenderer.react',
__module_operation_BarFragment:
'MarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
markup: '<markup/>',
},
},
variables: {id: '1'},
typeName: 'MarkdownUserNameRenderer',
path: ['node', 'nameRenderer'],
},
]);
});
it('returns metadata with prefixed path', () => {
const payload = {
node: {
id: '1',
__typename: 'User',
nameRenderer: {
__typename: 'MarkdownUserNameRenderer',
__module_component_BarFragment: 'MarkdownUserNameRenderer.react',
__module_operation_BarFragment:
'MarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
markup: '<markup/>',
},
},
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
const {moduleImportPayloads} = normalize(
recordSource,
{
dataID: ROOT_ID,
node: BarQuery.operation,
variables: {id: '1'},
},
payload,
// simulate a nested @match that appeared, validate that nested payload
// path is prefixed with this parent path:
{...defaultOptions, path: ['abc', '0', 'xyz']},
);
expect(recordSource.toJSON()).toEqual({
'1': {
__id: '1',
id: '1',
__typename: 'User',
'nameRenderer(supported:["PlainUserNameRenderer","MarkdownUserNameRenderer"])': {
__ref:
'client:1:nameRenderer(supported:["PlainUserNameRenderer","MarkdownUserNameRenderer"])',
},
},
'client:1:nameRenderer(supported:["PlainUserNameRenderer","MarkdownUserNameRenderer"])': {
__id:
'client:1:nameRenderer(supported:["PlainUserNameRenderer","MarkdownUserNameRenderer"])',
__typename: 'MarkdownUserNameRenderer',
__module_component_BarFragment: 'MarkdownUserNameRenderer.react',
__module_operation_BarFragment:
'MarkdownUserNameRenderer_name$normalization.graphql',
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
});
expect(moduleImportPayloads).toEqual([
{
operationReference:
'MarkdownUserNameRenderer_name$normalization.graphql',
dataID:
'client:1:nameRenderer(supported:["PlainUserNameRenderer","MarkdownUserNameRenderer"])',
data: {
__typename: 'MarkdownUserNameRenderer',
__module_component_BarFragment: 'MarkdownUserNameRenderer.react',
__module_operation_BarFragment:
'MarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
markup: '<markup/>',
},
},
variables: {id: '1'},
typeName: 'MarkdownUserNameRenderer',
// parent path followed by local path to @match
path: ['abc', '0', 'xyz', 'node', 'nameRenderer'],
},
]);
});
it('normalizes queries correctly when the resolved type does not match any of the specified cases', () => {
const payload = {
node: {
id: '1',
__typename: 'User',
nameRenderer: {
__typename: 'CustomNameRenderer',
customField: 'this is ignored!',
},
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
normalize(
recordSource,
{
dataID: ROOT_ID,
node: BarQuery.operation,
variables: {id: '1'},
},
payload,
defaultOptions,
);
expect(recordSource.toJSON()).toEqual({
'1': {
__id: '1',
id: '1',
__typename: 'User',
'nameRenderer(supported:["PlainUserNameRenderer","MarkdownUserNameRenderer"])': {
__ref:
'client:1:nameRenderer(supported:["PlainUserNameRenderer","MarkdownUserNameRenderer"])',
},
},
'client:1:nameRenderer(supported:["PlainUserNameRenderer","MarkdownUserNameRenderer"])': {
__id:
'client:1:nameRenderer(supported:["PlainUserNameRenderer","MarkdownUserNameRenderer"])',
__typename: 'CustomNameRenderer',
// note: 'customField' data not processed, there is no selection on this type
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
});
});
it('normalizes queries correctly when the @match field is null', () => {
const payload = {
node: {
id: '1',
__typename: 'User',
nameRenderer: null,
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
normalize(
recordSource,
{
dataID: ROOT_ID,
node: BarQuery.operation,
variables: {id: '1'},
},
payload,
defaultOptions,
);
expect(recordSource.toJSON()).toEqual({
'1': {
__id: '1',
id: '1',
__typename: 'User',
'nameRenderer(supported:["PlainUserNameRenderer","MarkdownUserNameRenderer"])': null,
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
});
});
});
describe('@module', () => {
let BarQuery;
beforeEach(() => {
const nodes = generateAndCompile(`
fragment PlainUserNameRenderer_name on PlainUserNameRenderer {
plaintext
data {
text
}
}
fragment MarkdownUserNameRenderer_name on MarkdownUserNameRenderer {
markdown
data {
markup
}
}
fragment BarFragment on User {
id
nameRenderer { # intentionally does not use @match
...PlainUserNameRenderer_name
@module(name: "PlainUserNameRenderer.react")
...MarkdownUserNameRenderer_name
@module(name: "MarkdownUserNameRenderer.react")
}
}
query BarQuery($id: ID!) {
node(id: $id) {
...BarFragment
}
}
`);
BarQuery = nodes.BarQuery;
});
it('normalizes queries and returns metadata when the type matches an @module selection', () => {
const payload = {
node: {
id: '1',
__typename: 'User',
nameRenderer: {
__typename: 'MarkdownUserNameRenderer',
__module_component_BarFragment: 'MarkdownUserNameRenderer.react',
__module_operation_BarFragment:
'MarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
markup: '<markup/>',
},
},
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
const {moduleImportPayloads} = normalize(
recordSource,
{
dataID: ROOT_ID,
node: BarQuery.operation,
variables: {id: '1'},
},
payload,
defaultOptions,
);
expect(recordSource.toJSON()).toEqual({
'1': {
__id: '1',
id: '1',
__typename: 'User',
nameRenderer: {
__ref: 'client:1:nameRenderer',
},
},
'client:1:nameRenderer': {
__id: 'client:1:nameRenderer',
__typename: 'MarkdownUserNameRenderer',
__module_component_BarFragment: 'MarkdownUserNameRenderer.react',
__module_operation_BarFragment:
'MarkdownUserNameRenderer_name$normalization.graphql',
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
});
expect(moduleImportPayloads).toEqual([
{
operationReference:
'MarkdownUserNameRenderer_name$normalization.graphql',
dataID: 'client:1:nameRenderer',
data: {
__typename: 'MarkdownUserNameRenderer',
__module_component_BarFragment: 'MarkdownUserNameRenderer.react',
__module_operation_BarFragment:
'MarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
markup: '<markup/>',
},
},
variables: {id: '1'},
typeName: 'MarkdownUserNameRenderer',
path: ['node', 'nameRenderer'],
},
]);
});
it('returns metadata with prefixed path', () => {
const payload = {
node: {
id: '1',
__typename: 'User',
nameRenderer: {
__typename: 'MarkdownUserNameRenderer',
__module_component_BarFragment: 'MarkdownUserNameRenderer.react',
__module_operation_BarFragment:
'MarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
markup: '<markup/>',
},
},
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
const {moduleImportPayloads} = normalize(
recordSource,
{
dataID: ROOT_ID,
node: BarQuery.operation,
variables: {id: '1'},
},
payload,
// simulate a nested @match that appeared, validate that nested payload
// path is prefixed with this parent path:
{...defaultOptions, path: ['abc', '0', 'xyz']},
);
expect(recordSource.toJSON()).toEqual({
'1': {
__id: '1',
id: '1',
__typename: 'User',
nameRenderer: {
__ref: 'client:1:nameRenderer',
},
},
'client:1:nameRenderer': {
__id: 'client:1:nameRenderer',
__typename: 'MarkdownUserNameRenderer',
__module_component_BarFragment: 'MarkdownUserNameRenderer.react',
__module_operation_BarFragment:
'MarkdownUserNameRenderer_name$normalization.graphql',
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
});
expect(moduleImportPayloads).toEqual([
{
operationReference:
'MarkdownUserNameRenderer_name$normalization.graphql',
dataID: 'client:1:nameRenderer',
data: {
__typename: 'MarkdownUserNameRenderer',
__module_component_BarFragment: 'MarkdownUserNameRenderer.react',
__module_operation_BarFragment:
'MarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
markup: '<markup/>',
},
},
variables: {id: '1'},
typeName: 'MarkdownUserNameRenderer',
// parent path followed by local path to @match
path: ['abc', '0', 'xyz', 'node', 'nameRenderer'],
},
]);
});
it('normalizes queries correctly when the resolved type does not match any @module selections', () => {
const payload = {
node: {
id: '1',
__typename: 'User',
nameRenderer: {
__typename: 'CustomNameRenderer',
customField: 'this is ignored!',
},
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
normalize(
recordSource,
{
dataID: ROOT_ID,
node: BarQuery.operation,
variables: {id: '1'},
},
payload,
defaultOptions,
);
expect(recordSource.toJSON()).toEqual({
'1': {
__id: '1',
id: '1',
__typename: 'User',
nameRenderer: {
__ref: 'client:1:nameRenderer',
},
},
'client:1:nameRenderer': {
__id: 'client:1:nameRenderer',
__typename: 'CustomNameRenderer',
// note: 'customField' data not processed, there is no selection on this type
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
});
});
});
describe('@defer', () => {
it('normalizes when if condition is false', () => {
const {Query} = generateAndCompile(
`
fragment TestFragment on User {
id
name
}
query Query($id: ID!, $enableDefer: Boolean!) {
node(id: $id) {
...TestFragment @defer(label: "TestFragment", if: $enableDefer)
}
}`,
);
const payload = {
node: {
id: '1',
__typename: 'User',
name: 'Alice',
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
const {incrementalPlaceholders} = normalize(
recordSource,
{
dataID: ROOT_ID,
node: Query.operation,
variables: {id: '1', enableDefer: false},
},
payload,
defaultOptions,
);
expect(incrementalPlaceholders).toEqual([]);
expect(recordSource.toJSON()).toEqual({
'1': {
__id: '1',
__typename: 'User',
id: '1',
name: 'Alice',
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
});
});
it('returns metadata when `if` is true (literal value)', () => {
const {Query} = generateAndCompile(
`
fragment TestFragment on User {
id
name
}
query Query($id: ID!) {
node(id: $id) {
...TestFragment @defer(label: "TestFragment", if: true)
}
}`,
);
const payload = {
node: {
id: '1',
__typename: 'User',
name: 'Alice',
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
const {incrementalPlaceholders} = normalize(
recordSource,
{
dataID: ROOT_ID,
node: Query.operation,
variables: {id: '1'},
},
payload,
defaultOptions,
);
expect(incrementalPlaceholders).toEqual([
{
kind: 'defer',
label: 'Query$defer$TestFragment',
path: ['node'],
selector: {
dataID: '1',
variables: {id: '1'},
node: expect.objectContaining({kind: 'Defer'}),
},
typeName: 'User',
},
]);
expect(recordSource.toJSON()).toEqual({
'1': {
__id: '1',
__typename: 'User',
id: '1',
// 'name' not normalized even though its present in the payload
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
});
});
it('returns metadata when `if` is true (variable value)', () => {
const {Query} = generateAndCompile(
`
fragment TestFragment on User {
id
name
}
query Query($id: ID!, $enableDefer: Boolean!) {
node(id: $id) {
...TestFragment @defer(label: "TestFragment", if: $enableDefer)
}
}`,
);
const payload = {
node: {
id: '1',
__typename: 'User',
name: 'Alice',
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
const {incrementalPlaceholders} = normalize(
recordSource,
{
dataID: ROOT_ID,
node: Query.operation,
variables: {id: '1', enableDefer: true},
},
payload,
defaultOptions,
);
expect(incrementalPlaceholders).toEqual([
{
kind: 'defer',
label: 'Query$defer$TestFragment',
path: ['node'],
selector: {
dataID: '1',
variables: {id: '1', enableDefer: true},
node: expect.objectContaining({kind: 'Defer'}),
},
typeName: 'User',
},
]);
expect(recordSource.toJSON()).toEqual({
'1': {
__id: '1',
__typename: 'User',
id: '1',
// 'name' not normalized even though its present in the payload
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
});
});
it('returns metadata for @defer within a plural', () => {
const {Query} = generateAndCompile(
`
fragment TestFragment on User {
name
}
query Query($id: ID!) {
node(id: $id) {
... on Feedback {
actors {
...TestFragment @defer(label: "TestFragment", if: true)
}
}
}
}`,
);
const payload = {
node: {
id: '1',
__typename: 'Feedback',
actors: [
{__typename: 'User', id: '2', name: 'Alice'},
{__typename: 'User', id: '3', name: 'Bob'},
],
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
const {incrementalPlaceholders} = normalize(
recordSource,
{
dataID: ROOT_ID,
node: Query.operation,
variables: {id: '1'},
},
payload,
defaultOptions,
);
expect(incrementalPlaceholders).toEqual([
{
kind: 'defer',
label: 'Query$defer$TestFragment',
path: ['node', 'actors', '0'],
selector: {
dataID: '2',
variables: {id: '1'},
node: expect.objectContaining({kind: 'Defer'}),
},
typeName: 'User',
},
{
kind: 'defer',
label: 'Query$defer$TestFragment',
path: ['node', 'actors', '1'],
selector: {
dataID: '3',
variables: {id: '1'},
node: expect.objectContaining({kind: 'Defer'}),
},
typeName: 'User',
},
]);
expect(recordSource.toJSON()).toEqual({
'1': {
__id: '1',
__typename: 'Feedback',
id: '1',
actors: {__refs: ['2', '3']},
},
'2': {
__id: '2',
__typename: 'User',
id: '2',
// name deferred
},
'3': {
__id: '3',
__typename: 'User',
id: '3',
// name deferred
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
});
});
it('returns metadata with prefixed path', () => {
const {Query} = generateAndCompile(
`
fragment TestFragment on User {
id
name
}
query Query($id: ID!) {
node(id: $id) {
...TestFragment @defer(label: "TestFragment")
}
}`,
);
const payload = {
node: {
id: '1',
__typename: 'User',
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
const {incrementalPlaceholders} = normalize(
recordSource,
{
dataID: ROOT_ID,
node: Query.operation,
variables: {id: '1'},
},
payload,
// simulate a nested defer payload, verify that the incrementalPlaceholders
// paths are prefixed with this parent path
{...defaultOptions, path: ['abc', '0', 'xyz']},
);
expect(incrementalPlaceholders).toEqual([
{
kind: 'defer',
label: 'Query$defer$TestFragment',
path: ['abc', '0', 'xyz', 'node'],
selector: {
dataID: '1',
variables: {id: '1'},
node: expect.objectContaining({kind: 'Defer'}),
},
typeName: 'User',
},
]);
});
});
describe('@stream', () => {
it('normalizes when if condition is false', () => {
const {Query} = generateAndCompile(
`
fragment TestFragment on Feedback {
id
actors @stream(label: "actors", if: $enableStream, initial_count: 0) {
name
}
}
query Query($id: ID!, $enableStream: Boolean!) {
node(id: $id) {
...TestFragment
}
}`,
);
const payload = {
node: {
id: '1',
__typename: 'Feedback',
actors: [{__typename: 'User', id: '2', name: 'Alice'}],
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
const {incrementalPlaceholders} = normalize(
recordSource,
{
dataID: ROOT_ID,
node: Query.operation,
variables: {id: '1', enableStream: false},
},
payload,
defaultOptions,
);
expect(incrementalPlaceholders).toEqual([]);
expect(recordSource.toJSON()).toEqual({
'1': {
__id: '1',
__typename: 'Feedback',
id: '1',
actors: {__refs: ['2']},
},
'2': {
__id: '2',
__typename: 'User',
id: '2',
name: 'Alice',
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
});
});
it('normalizes and returns metadata when `if` is true (literal value)', () => {
const {Query} = generateAndCompile(
`
fragment TestFragment on Feedback {
id
actors @stream(label: "actors", if: true, initial_count: 0) {
name
}
}
query Query($id: ID!) {
node(id: $id) {
...TestFragment
}
}`,
);
const payload = {
node: {
id: '1',
__typename: 'Feedback',
actors: [{__typename: 'User', id: '2', name: 'Alice'}],
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
const {incrementalPlaceholders} = normalize(
recordSource,
{
dataID: ROOT_ID,
node: Query.operation,
variables: {id: '1'},
},
payload,
defaultOptions,
);
expect(incrementalPlaceholders).toEqual([
{
kind: 'stream',
label: 'TestFragment$stream$actors',
path: ['node'],
parentID: '1',
node: expect.objectContaining({kind: 'Stream'}),
variables: {id: '1'},
},
]);
expect(recordSource.toJSON()).toEqual({
'1': {
__id: '1',
__typename: 'Feedback',
id: '1',
actors: {__refs: ['2']},
},
'2': {
__id: '2',
__typename: 'User',
id: '2',
name: 'Alice',
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
});
});
it('normalizes and returns metadata when `if` is true (variable value)', () => {
const {Query} = generateAndCompile(
`
fragment TestFragment on Feedback {
id
actors @stream(label: "actors", if: $enableStream, initial_count: 0) {
name
}
}
query Query($id: ID!, $enableStream: Boolean!) {
node(id: $id) {
...TestFragment
}
}`,
);
const payload = {
node: {
id: '1',
__typename: 'Feedback',
actors: [{__typename: 'User', id: '2', name: 'Alice'}],
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
const {incrementalPlaceholders} = normalize(
recordSource,
{
dataID: ROOT_ID,
node: Query.operation,
variables: {id: '1', enableStream: true},
},
payload,
defaultOptions,
);
expect(incrementalPlaceholders).toEqual([
{
kind: 'stream',
label: 'TestFragment$stream$actors',
path: ['node'],
parentID: '1',
node: expect.objectContaining({kind: 'Stream'}),
variables: {id: '1', enableStream: true},
},
]);
expect(recordSource.toJSON()).toEqual({
'1': {
__id: '1',
__typename: 'Feedback',
id: '1',
actors: {__refs: ['2']},
},
'2': {
__id: '2',
__typename: 'User',
id: '2',
name: 'Alice',
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
});
});
it('normalizes and returns metadata for @stream within a plural', () => {
const {Query} = generateAndCompile(
`
fragment TestFragment on Feedback {
id
actors {
... on User {
name
actors @stream(label: "actors", if: true, initial_count: 0) {
name
}
}
}
}
query Query($id: ID!) {
node(id: $id) {
...TestFragment
}
}`,
);
const payload = {
node: {
id: '1',
__typename: 'Feedback',
actors: [
{__typename: 'User', id: '2', name: 'Alice', actors: []},
{__typename: 'User', id: '3', name: 'Bob', actors: []},
],
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
const {incrementalPlaceholders} = normalize(
recordSource,
{
dataID: ROOT_ID,
node: Query.operation,
variables: {id: '1'},
},
payload,
defaultOptions,
);
expect(incrementalPlaceholders).toEqual([
{
kind: 'stream',
label: 'TestFragment$stream$actors',
path: ['node', 'actors', '0'],
parentID: '2',
variables: {id: '1'},
node: expect.objectContaining({kind: 'Stream'}),
},
{
kind: 'stream',
label: 'TestFragment$stream$actors',
path: ['node', 'actors', '1'],
parentID: '3',
variables: {id: '1'},
node: expect.objectContaining({kind: 'Stream'}),
},
]);
expect(recordSource.toJSON()).toEqual({
'1': {
__id: '1',
__typename: 'Feedback',
id: '1',
actors: {__refs: ['2', '3']},
},
'2': {
__id: '2',
__typename: 'User',
id: '2',
name: 'Alice',
actors: {__refs: []},
},
'3': {
__id: '3',
__typename: 'User',
id: '3',
name: 'Bob',
actors: {__refs: []},
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
});
});
it('returns metadata with prefixed path', () => {
const {Query} = generateAndCompile(
`
fragment TestFragment on Feedback {
id
actors @stream(label: "actors", initial_count: 0) {
name
}
}
query Query($id: ID!) {
node(id: $id) {
...TestFragment
}
}`,
);
const payload = {
node: {
id: '1',
__typename: 'Feedback',
actors: [{__typename: 'User', id: '2', name: 'Alice'}],
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
const {incrementalPlaceholders} = normalize(
recordSource,
{
dataID: ROOT_ID,
node: Query.operation,
variables: {id: '1'},
},
payload,
// simulate a nested @match that appeared, validate that nested payload
// path is prefixed with this parent path:
{...defaultOptions, path: ['abc', '0', 'xyz']},
);
expect(incrementalPlaceholders).toEqual([
{
kind: 'stream',
label: 'TestFragment$stream$actors',
path: ['abc', '0', 'xyz', 'node'],
parentID: '1',
variables: {id: '1'},
node: expect.objectContaining({kind: 'Stream'}),
},
]);
});
});
describe('Client Extensions', () => {
const {StrippedQuery} = generateAndCompile(
`
query StrippedQuery($id: ID, $size: [Int]) {
node(id: $id) {
id
__typename
... on User {
firstName
nickname
foo {
bar {
content
}
}
}
}
}
extend type User {
nickname: String
foo: Foo
}
type Foo {
bar: Bar
}
type Bar {
content: String
}
`,
);
const payload = {
node: {
id: '1',
__typename: 'User',
firstName: 'Bob',
},
};
it('skips client fields not present in the payload but present in the store', () => {
const recordSource = new RelayInMemoryRecordSource({
'1': {
__id: '1',
__typename: 'User',
id: '1',
firstName: 'Alice',
nickname: 'ecilA',
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
});
normalize(
recordSource,
{
dataID: ROOT_ID,
node: StrippedQuery.operation,
variables: {id: '1', size: 32},
},
payload,
{...defaultOptions, handleStrippedNulls: true},
);
const result = {
'1': {
__id: '1',
__typename: 'User',
id: '1',
firstName: 'Bob',
nickname: 'ecilA',
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
};
expect(recordSource.toJSON()).toEqual(result);
normalize(
recordSource,
{
dataID: ROOT_ID,
node: StrippedQuery.operation,
variables: {id: '1', size: 32},
},
payload,
{...defaultOptions, handleStrippedNulls: false},
);
expect(recordSource.toJSON()).toEqual(result);
});
it('skips client fields not present in the payload or store', () => {
const recordSource = new RelayInMemoryRecordSource({
'1': {
__id: '1',
__typename: 'User',
id: '1',
firstName: 'Alice',
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
});
normalize(
recordSource,
{
dataID: ROOT_ID,
node: StrippedQuery.operation,
variables: {id: '1', size: 32},
},
payload,
{...defaultOptions, handleStrippedNulls: true},
);
const result = {
'1': {
__id: '1',
__typename: 'User',
id: '1',
firstName: 'Bob',
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
};
expect(recordSource.toJSON()).toEqual(result);
normalize(
recordSource,
{
dataID: ROOT_ID,
node: StrippedQuery.operation,
variables: {id: '1', size: 32},
},
payload,
{...defaultOptions, handleStrippedNulls: false},
);
expect(recordSource.toJSON()).toEqual(result);
});
it('ignores linked client fields not present in the payload', () => {
const recordSource = new RelayInMemoryRecordSource({
'1': {
__id: '1',
__typename: 'User',
id: '1',
firstName: 'Alice',
foo: {
__ref: '2',
},
},
'2': {
__id: '2',
__typename: 'Foo',
bar: {
__ref: '3',
},
},
'3': {
__id: '3',
__typename: 'Bar',
content: 'bar',
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
});
normalize(
recordSource,
{
dataID: ROOT_ID,
node: StrippedQuery.operation,
variables: {id: '1', size: 32},
},
payload,
{...defaultOptions, handleStrippedNulls: true},
);
const result = {
'1': {
__id: '1',
__typename: 'User',
id: '1',
firstName: 'Bob',
foo: {
__ref: '2',
},
},
'2': {
__id: '2',
__typename: 'Foo',
bar: {
__ref: '3',
},
},
'3': {
__id: '3',
__typename: 'Bar',
content: 'bar',
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
};
expect(recordSource.toJSON()).toEqual(result);
normalize(
recordSource,
{
dataID: ROOT_ID,
node: StrippedQuery.operation,
variables: {id: '1', size: 32},
},
payload,
{...defaultOptions, handleStrippedNulls: false},
);
expect(recordSource.toJSON()).toEqual(result);
});
it('ignores linked client fields not present in the payload or store', () => {
const recordSource = new RelayInMemoryRecordSource({
'1': {
__id: '1',
__typename: 'User',
id: '1',
firstName: 'Alice',
foo: {
__ref: '2',
},
},
'2': {
__id: '2',
__typename: 'Foo',
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
});
normalize(
recordSource,
{
dataID: ROOT_ID,
node: StrippedQuery.operation,
variables: {id: '1', size: 32},
},
payload,
{...defaultOptions, handleStrippedNulls: true},
);
const result = {
'1': {
__id: '1',
__typename: 'User',
id: '1',
firstName: 'Bob',
foo: {
__ref: '2',
},
},
'2': {
__id: '2',
__typename: 'Foo',
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {__ref: '1'},
},
};
expect(recordSource.toJSON()).toEqual(result);
normalize(
recordSource,
{
dataID: ROOT_ID,
node: StrippedQuery.operation,
variables: {id: '1', size: 32},
},
payload,
{...defaultOptions, handleStrippedNulls: false},
);
expect(recordSource.toJSON()).toEqual(result);
});
});
describe('User-defined getDataID', () => {
let recordSource;
const getDataID = jest.fn((fieldValue, typename) => {
return `${fieldValue.id}:${typename}`;
});
const getNullAsDataID = jest.fn((fieldValue, typename) => {
return null;
});
beforeEach(() => {
recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
});
afterEach(() => {
jest.clearAllMocks();
});
describe('single field', () => {
const {BarQuery} = generateAndCompile(
`
query BarQuery($id: ID) {
node(id: $id) {
id
__typename
... on User {
actor {
id
__typename
}
author {
id
__typename
}
}
}
}
`,
);
const payload = {
node: {
id: '1',
__typename: 'User',
actor: {
id: '1',
__typename: 'Page',
},
author: {
id: '1',
__typename: 'User',
},
},
};
it('Overwrite fields in same position but with different data', () => {
const {Foo} = generateAndCompile(
`query Foo {
me {
author {
id
name
}
}
meAgain: me {
author {
id
name
}
}
}
`,
);
const fooPayload = {
me: {
__typename: 'User',
id: 'me',
author: {
id: 'friend1',
name: 'First Friend',
},
},
meAgain: {
__typename: 'User',
id: 'me',
author: {
id: 'friend2',
name: 'Second Friend',
},
},
};
normalize(
recordSource,
{
dataID: ROOT_ID,
node: Foo.operation,
variables: {id: '1'},
},
fooPayload,
{getDataID},
);
expect(recordSource.toJSON()).toEqual({
'client:root': {
__id: 'client:root',
__typename: '__Root',
me: {
__ref: 'me:User',
},
},
'friend1:User': {
__id: 'friend1:User',
__typename: 'User',
id: 'friend1',
name: 'First Friend',
},
'friend2:User': {
__id: 'friend2:User',
__typename: 'User',
id: 'friend2',
name: 'Second Friend',
},
'me:User': {
__id: 'me:User',
__typename: 'User',
author: {
__ref: 'friend2:User', // Should be the second one
},
id: 'me',
},
});
});
it('Overwrite fields in same position but with different data in second normalization', () => {
const {Foo} = generateAndCompile(
`query Foo {
me {
author {
id
name
}
}
}
`,
);
const fooPayload0 = {
me: {
__typename: 'User',
id: 'me',
author: {
id: 'friend0',
name: 'First Friend',
},
},
};
const fooPayload1 = {
me: {
__typename: 'User',
id: 'me',
author: {
id: 'friend1',
name: 'Second Friend',
},
},
};
normalize(
recordSource,
{
dataID: ROOT_ID,
node: Foo.operation,
variables: {id: '1'},
},
fooPayload0,
{getDataID},
);
normalize(
recordSource,
{
dataID: ROOT_ID,
node: Foo.operation,
variables: {id: '1'},
},
fooPayload1,
{getDataID},
);
expect(recordSource.toJSON()).toEqual({
'client:root': {
__id: 'client:root',
__typename: '__Root',
me: {
__ref: 'me:User',
},
},
'friend0:User': {
__id: 'friend0:User',
__typename: 'User',
id: 'friend0',
name: 'First Friend',
},
'friend1:User': {
__id: 'friend1:User',
__typename: 'User',
id: 'friend1',
name: 'Second Friend',
},
'me:User': {
__id: 'me:User',
__typename: 'User',
author: {
__ref: 'friend1:User', // Should be the second one
},
id: 'me',
},
});
});
it('stores user-defined id when function returns an string', () => {
normalize(
recordSource,
{
dataID: ROOT_ID,
node: BarQuery.operation,
variables: {id: '1'},
},
payload,
{getDataID},
);
expect(recordSource.toJSON()).toEqual({
'1:Page': {
__id: '1:Page',
__typename: 'Page',
id: '1',
},
'1:User': {
__id: '1:User',
__typename: 'User',
actor: {
__ref: '1:Page',
},
author: {
__ref: '1:User',
},
id: '1',
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {
__ref: '1:User',
},
},
});
expect(getDataID).toBeCalledTimes(3);
});
it('falls through to previously generated ID if function returns null ', () => {
const previousData = {
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {
__ref: 'test:root:node(id:"1")',
},
},
'test:root:node(id:"1")': {
__id: 'test:root:node(id:"1")',
__typename: 'User',
actor: {
__ref: 'test:root:node(id:"1"):actor',
},
author: {
__ref: 'test:root:node(id:"1"):author',
},
id: '1',
},
'test:root:node(id:"1"):actor': {
__id: 'test:root:node(id:"1"):actor',
__typename: 'Page',
id: '1',
},
'test:root:node(id:"1"):author': {
__id: 'test:root:node(id:"1"):author',
__typename: 'User',
id: '1',
},
};
const expectedData = JSON.parse(JSON.stringify(previousData));
recordSource = new RelayInMemoryRecordSource(previousData);
normalize(
recordSource,
{
dataID: ROOT_ID,
node: BarQuery.operation,
variables: {id: '1'},
},
payload,
{getDataID: getNullAsDataID},
);
expect(recordSource.toJSON()).toEqual(expectedData);
expect(getNullAsDataID).toBeCalledTimes(3);
});
it('falls through to generateClientID when the function returns null, and no previously generated ID', () => {
normalize(
recordSource,
{
dataID: ROOT_ID,
node: BarQuery.operation,
variables: {id: '1'},
},
payload,
{getDataID: getNullAsDataID},
);
expect(recordSource.toJSON()).toEqual({
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {
__ref: 'client:root:node(id:"1")',
},
},
'client:root:node(id:"1")': {
__id: 'client:root:node(id:"1")',
__typename: 'User',
actor: {
__ref: 'client:root:node(id:"1"):actor',
},
author: {
__ref: 'client:root:node(id:"1"):author',
},
id: '1',
},
'client:root:node(id:"1"):actor': {
__id: 'client:root:node(id:"1"):actor',
__typename: 'Page',
id: '1',
},
'client:root:node(id:"1"):author': {
__id: 'client:root:node(id:"1"):author',
__typename: 'User',
id: '1',
},
});
expect(getNullAsDataID).toBeCalledTimes(3);
});
});
describe('plural fileds', () => {
const {BarQuery} = generateWithTransforms(
`
query BarQuery($id: ID) {
node(id: $id) {
id
__typename
... on User {
actors {
id
__typename
}
}
}
}
`,
);
const payload = {
node: {
id: '1',
__typename: 'User',
actors: [
{
id: '1',
__typename: 'Page',
},
{
id: '2',
__typename: 'Page',
},
],
},
};
it('stores user-defined ids when function returns an string', () => {
normalize(
recordSource,
{
dataID: ROOT_ID,
node: BarQuery.operation,
variables: {id: '1'},
},
payload,
{getDataID},
);
expect(recordSource.toJSON()).toEqual({
'1:Page': {
__id: '1:Page',
__typename: 'Page',
id: '1',
},
'2:Page': {
__id: '2:Page',
__typename: 'Page',
id: '2',
},
'1:User': {
__id: '1:User',
__typename: 'User',
actors: {
__refs: ['1:Page', '2:Page'],
},
id: '1',
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {
__ref: '1:User',
},
},
});
expect(getDataID).toBeCalledTimes(3);
});
it('uses cached IDs if they were generated before and the function returns null', () => {
const previousData = {
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {
__ref: 'test:root:node(id:"1")',
},
},
'test:root:node(id:"1")': {
__id: 'test:root:node(id:"1")',
__typename: 'User',
actors: {
__refs: [
'test:root:node(id:"1"):actor:0',
'test:root:node(id:"1"):actor:1',
],
},
id: '1',
},
'test:root:node(id:"1"):actor:0': {
__id: 'test:root:node(id:"1"):actor:0',
__typename: 'Page',
id: '1',
},
'test:root:node(id:"1"):actor:1': {
__id: 'test:root:node(id:"1"):actor:1',
__typename: 'Page',
id: '2',
},
};
recordSource = new RelayInMemoryRecordSource(previousData);
const expectedData = JSON.parse(JSON.stringify(previousData));
normalize(
recordSource,
{
dataID: ROOT_ID,
node: BarQuery.operation,
variables: {id: '1'},
},
payload,
{getDataID: getNullAsDataID},
);
expect(recordSource.toJSON()).toEqual(expectedData);
expect(getNullAsDataID).toBeCalledTimes(3);
});
it('falls through to generateClientID when the function returns null and there is one new field in stored plural links', () => {
const data = {
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {
__ref: 'test:root:node(id:"1")',
},
},
'test:root:node(id:"1")': {
__id: 'test:root:node(id:"1")',
__typename: 'User',
actors: {
__refs: ['test:root:node(id:"1"):actor:0'],
},
id: '1',
},
'test:root:node(id:"1"):actor:0': {
__id: 'test:root:node(id:"1"):actor:0',
__typename: 'Page',
id: '1',
},
};
recordSource = new RelayInMemoryRecordSource(data);
normalize(
recordSource,
{
dataID: ROOT_ID,
node: BarQuery.operation,
variables: {id: '1'},
},
payload,
{getDataID: getNullAsDataID},
);
expect(data['test:root:node(id:"1")']).toEqual({
__id: 'test:root:node(id:"1")',
__typename: 'User',
actors: {
__refs: [
'test:root:node(id:"1"):actor:0',
'client:test:root:node(id:"1"):actors:1',
],
},
id: '1',
});
expect(data['client:test:root:node(id:"1"):actors:1']).toEqual({
__id: 'client:test:root:node(id:"1"):actors:1',
__typename: 'Page',
id: '2',
});
expect(getNullAsDataID).toBeCalledTimes(3);
});
it('falls through to generateClientID when the function returns null and no preiously generated IDs', () => {
normalize(
recordSource,
{
dataID: ROOT_ID,
node: BarQuery.operation,
variables: {id: '1'},
},
payload,
{getDataID: getNullAsDataID},
);
expect(recordSource.toJSON()).toEqual({
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {
__ref: 'client:root:node(id:"1")',
},
},
'client:root:node(id:"1")': {
__id: 'client:root:node(id:"1")',
__typename: 'User',
actors: {
__refs: [
'client:root:node(id:"1"):actors:0',
'client:root:node(id:"1"):actors:1',
],
},
id: '1',
},
'client:root:node(id:"1"):actors:0': {
__id: 'client:root:node(id:"1"):actors:0',
__typename: 'Page',
id: '1',
},
'client:root:node(id:"1"):actors:1': {
__id: 'client:root:node(id:"1"):actors:1',
__typename: 'Page',
id: '2',
},
});
expect(getNullAsDataID).toBeCalledTimes(3);
});
it('Overwrite fields in same position but with different data in second normalization', () => {
const {Foo} = generateWithTransforms(
`
query Foo($id: ID) {
node(id: $id) {
id
__typename
... on User {
actors {
id
name
__typename
}
}
}
}
`,
);
const payload0 = {
node: {
id: '1',
__typename: 'User',
actors: [
{
id: '1',
__typename: 'Page',
name: 'Page0',
},
],
},
};
const payload1 = {
node: {
id: '1',
__typename: 'User',
actors: [
{
id: '2',
__typename: 'Page',
name: 'Page1',
},
],
},
};
normalize(
recordSource,
{
dataID: ROOT_ID,
node: Foo.operation,
variables: {id: '1'},
},
payload0,
{getDataID},
);
normalize(
recordSource,
{
dataID: ROOT_ID,
node: Foo.operation,
variables: {id: '1'},
},
payload1,
{getDataID},
);
expect(recordSource.toJSON()).toEqual({
'1:Page': {
__id: '1:Page',
__typename: 'Page',
id: '1',
name: 'Page0',
},
'2:Page': {
__id: '2:Page',
__typename: 'Page',
id: '2',
name: 'Page1',
},
'1:User': {
__id: '1:User',
__typename: 'User',
actors: {
__refs: ['2:Page'], // Should be the second one
},
id: '1',
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {
__ref: '1:User',
},
},
});
});
});
});
it('warns in __DEV__ if payload data is missing an expected field', () => {
jest.mock('warning');
const {BarQuery} = generateWithTransforms(
`
query BarQuery($id: ID) {
node(id: $id) {
id
__typename
... on User {
firstName
profilePicture(size: 100) {
uri
}
}
}
}
`,
);
const payload = {
node: {
id: '1',
__typename: 'User',
profilePicture: {
uri: 'https://...',
},
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
expect(() => {
normalize(
recordSource,
{
dataID: ROOT_ID,
node: BarQuery.operation,
variables: {id: '1'},
},
payload,
{...defaultOptions, handleStrippedNulls: true},
);
}).toWarn([
'RelayResponseNormalizer(): Payload did not contain a value for ' +
'field `%s: %s`. Check that you are parsing with the same query that ' +
'was used to fetch the payload.',
'firstName',
'firstName',
]);
});
it('does not warn in __DEV__ if payload data is missing for an abstract field', () => {
jest.mock('warning');
const {BarQuery} = generateAndCompile(`
query BarQuery {
named {
name
... on Node {
id
}
}
}
`);
const payload = {
named: {
__typename: 'SimpleNamed',
name: 'Alice',
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
expect(() => {
normalize(
recordSource,
{
dataID: ROOT_ID,
node: BarQuery.operation,
variables: {},
},
payload,
{...defaultOptions, handleStrippedNulls: true},
);
}).not.toWarn([
'RelayResponseNormalizer(): Payload did not contain a value for ' +
'field `%s: %s`. Check that you are parsing with the same query that ' +
'was used to fetch the payload.',
'name',
'name',
]);
});
it('warns in __DEV__ if payload contains inconsistent types for a record', () => {
jest.mock('warning');
const {BarQuery} = generateWithTransforms(
`
query BarQuery($id: ID) {
node(id: $id) {
id
__typename
... on User {
actor {
id
__typename
}
actors {
id
__typename
}
}
}
}
`,
);
const payload = {
node: {
id: '1',
__typename: 'User',
actor: {
id: '1',
__typename: 'Actor', // <- invalid
},
actors: [
{
id: '1',
__typename: 'Actors', // <- invalid
},
],
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
expect(() => {
normalize(
recordSource,
{
dataID: ROOT_ID,
node: BarQuery.operation,
variables: {id: '1'},
},
payload,
{...defaultOptions, handleStrippedNulls: true},
);
}).toWarn([
'RelayResponseNormalizer: Invalid record `%s`. Expected %s to be ' +
'be consistent, but the record was assigned conflicting types `%s` ' +
'and `%s`. The GraphQL server likely violated the globally unique ' +
'id requirement by returning the same id for different objects.',
'1',
'__typename',
'User',
'Actor',
]);
expect(() => {
normalize(
recordSource,
{
dataID: ROOT_ID,
node: BarQuery.operation,
variables: {id: '1'},
},
payload,
{...defaultOptions, handleStrippedNulls: true},
);
}).toWarn([
'RelayResponseNormalizer: Invalid record `%s`. Expected %s to be ' +
'be consistent, but the record was assigned conflicting types `%s` ' +
'and `%s`. The GraphQL server likely violated the globally unique ' +
'id requirement by returning the same id for different objects.',
'1',
'__typename',
'Actor', // `User` is already overwritten when the plural field is reached
'Actors',
]);
});
it('does not warn in __DEV__ on inconsistent types for a client record', () => {
jest.mock('warning');
const {BarQuery} = generateWithTransforms(
`
query BarQuery($id: ID) {
node(id: $id) {
id
__typename
... on User {
actor {
id
__typename
}
actors {
id
__typename
}
}
}
}
`,
);
const payload = {
node: {
id: 'client:1',
__typename: 'User',
actor: {
id: 'client:1',
__typename: 'Actor', // <- invalid
},
actors: [
{
id: 'client:1',
__typename: 'Actors', // <- invalid
},
],
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
expect(() => {
normalize(
recordSource,
{
dataID: ROOT_ID,
node: BarQuery.operation,
variables: {id: '1'},
},
payload,
{...defaultOptions, handleStrippedNulls: true},
);
}).not.toWarn();
expect(() => {
normalize(
recordSource,
{
dataID: ROOT_ID,
node: BarQuery.operation,
variables: {id: '1'},
},
payload,
{...defaultOptions, handleStrippedNulls: true},
);
}).not.toWarn();
});
it('leaves undefined fields unset, as handleStrippedNulls == false', () => {
const {StrippedQuery} = generateWithTransforms(
`
query StrippedQuery($id: ID, $size: [Int]) {
node(id: $id) {
id
__typename
... on User {
firstName
profilePicture(size: $size) {
uri
}
}
}
}
`,
);
const payload = {
node: {
id: '1',
__typename: 'User',
firstName: 'Alice',
},
};
const recordSource = new RelayInMemoryRecordSource();
recordSource.set(ROOT_ID, RelayModernRecord.create(ROOT_ID, ROOT_TYPE));
normalize(
recordSource,
{
dataID: ROOT_ID,
node: StrippedQuery.operation,
variables: {id: '1', size: 32},
},
payload,
{...defaultOptions, handleStrippedNulls: false},
);
expect(recordSource.toJSON()).toEqual({
'1': {
__id: '1',
__typename: 'User',
id: '1',
firstName: 'Alice',
// `profilePicture` is excluded
},
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"1")': {
__ref: '1',
},
},
});
});
});
|
/**
* Created by xreztento@vip.sina.com on 2016/12/29.
*/
define(function (require, exports, module) {
require("jquery");
require("style");
var Class = require("class");
var Element = require("./Element");
var ButtonElement = require("buttonElement");
var AlertElement = Class("AlertElement", {
Extends : Element,
STATIC: {
MODULE_NAME : "AlertElement"
},
initialize : function(width, height, topic, message, style) {
AlertElement.Super.call(this, width, height);
this.topic = topic;
this.message = message;
this.style = style;
},
init : function(where){
var statement = "<div role='alert'><div>";
var topic = this.topic || "Alert!";
var message = this.message || "";
var style = this.style || StyleType.danger;
this.element = AlertElement.Super.prototype.init.call(this, where, statement);
this.element
.addClass("alert alert-" + style)
.html("<strong>" + topic + "</strong>" + message);
return this;
},
setClosable : function(){
this.element.prepend("<button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>×</span></button>");
return this;
},
setContent : function(content){
var p = $("<p></p>").css({
"margin-top" : "10px"
}).text(content);
this.element.append(p);
return this;
},
setToolBar : function(submitCallback, cancelCallback){
var submitButton = new ButtonElement(null, null, StyleType.danger);
var cancelButton = new ButtonElement(null, null, StyleType.default);
var p = $("<p></p>").css({
"margin-top" : "10px"
});
this.element.append(p);
submitButton.init(p);
submitButton.setText("确认").click(submitCallback).css("margin-right", "10px");
cancelButton.init(p);
cancelButton.setText("取消").click(cancelCallback);
return this;
},
getModuleName : function(){
return AlertElement.MODULE_NAME;
}
});
module.exports = AlertElement;
}); |
const fs = require('fs');
const path = require('path');
const data = require('./data');
const TinyColor = require('@ctrl/tinycolor').default;
data.forEach(category => {
const l = element => new TinyColor([].concat(element)[0].color).toHsl().l;
const h = element => new TinyColor([].concat(element)[0].color).toHsl().h;
category.data = Object.fromEntries(
Object.entries(category.data)
.sort((a, b) => a[0] < b[0] ? -1 : a[0] === b[0] ? 0 : 1) // sort by name
.sort((a, b) => l(a[1]) - l(b[1])) // sort by lightness
.sort((a, b) => h(a[1]) - h(b[1])) // sort by hue
)
});
const date = new Date();
const [y, m, d] = [
date.getFullYear(),
date.getMonth(),
`${date.getDate()}`,
];
fs.writeFileSync(path.resolve(__dirname, './data.js'), `/***********************************************************************
* _
* _____ _ ____ _ |_|
* | _ |/ \\ ____ ____ __ ___ / ___\\/ \\ __ _ ____ _
* | |_| || | / __ \\/ __ \\\\ '_ \\ _ / / | |___\\ \\ | |/ __ \\| |
* | _ || |__. ___/. ___/| | | ||_|\\ \\___ | _ | |_| |. ___/| |
* |_/ \\_|\\___/\\____|\\____||_| |_| \\____/|_| |_|_____|\\____||_|
*
* ================================================================
* More than a coder, More than a designer
* ================================================================
*
*
* - Document: data.js
* - Author: aleen42
* - Description: data for building badges
* - Create Time: Apr 20th, 2017
* - Update Time: ${[
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
][m]} ${d + (/1$/.test(d) ? 'st' : /2$/.test(d) ? 'nd' : /3$/.test(d) ? 'rd' : 'th')}, ${y}
*
*
**********************************************************************/
module.exports = ${
JSON.stringify(data, (k, v) => v.color
? JSON.stringify(v, null, 1)
.replace(/^[\t ]*"[^:\n\r]+(?<!\\)":/gm, match => match.replace(/"/g, ''))
.replace(/{\n\s/g, '{ ')
.replace(/\n}/g, ' }')
.replace(/\n/g, '')
: v, 4)
.replace(/\\"/g, '"')
.replace(/"{/g, '{')
.replace(/}"/g, '}')
.replace(/"/g, '\'')
};
`, {encoding: 'utf8'});
module.exports = data;
|
// Variables
var user,
timer,
socket,
oldname,
username,
typeTimer,
clients = [],
usersTyping = [],
nmr = 0,
dev = true,
unread = 0,
focus = true,
typing = false,
connected = false,
version = VERSION,
blop = new Audio('sounds/blop.wav');
emojione.ascii = true;
emojione.imageType = 'png';
emojione.unicodeAlt = false;
document.getElementById('version').innerHTML = version;
var regex = /(‍| )/g;
var settings = {
'name': null,
'emoji': true,
'greentext': true,
'sound': true,
'desktop': false,
'synthesis': false,
'recognition': false
};
// Connection
var connect = function() {
socket = new WebSocket('ws://'+ window.location.host +'/socket/websocket');
socket.onopen = function() {
var ping = setInterval(function(){
socket.send(JSON.stringify({type: 'ping'}));
}, 50 * 1000);
console.info('Connection established.');
updateInfo();
};
socket.onclose = function() {
clearTimeout(typeTimer);
$('#admin').hide();
typing = false;
clients = [];
if(connected) {
updateBar('mdi-action-autorenew spin', 'Connection lost, reconnecting...', true);
timer = setTimeout(function() {
console.warn('Connection lost, reconnecting...');
connect();
}, 1500);
}
};
socket.onmessage = function(e) {
var data = JSON.parse(e.data);
if(dev) console.log(data);
if(data.type == 'delete')
return $('div[data-mid="' + data.message + '"]').remove();
if(data.type == 'typing') {
var string;
if(data.user != username) {
if(data.typing)
usersTyping.push(data.user);
else
usersTyping.splice(usersTyping.indexOf(data.user), 1);
}
if(usersTyping.length == 1) {
string = usersTyping + ' is writing...';
} else if(usersTyping.length > 4) {
string = 'Several people are writing...';
} else if(usersTyping.length > 1) {
var lastUser = usersTyping.pop();
string = usersTyping.join(', ') + ' and ' + lastUser + ' are writing...';
usersTyping.push(lastUser);
} else {
string = '<br>';
}
return document.getElementById('typing').innerHTML = string;
}
if(data.type == 'server') {
switch(data.info) {
case 'rejected':
var message;
if(data.reason == 'length') message = 'Your username must have at least 3 characters and no more than 16 characters';
if(data.reason == 'format') message = 'Your username must only contain alphanumeric characters (numbers, letters and underscores)';
if(data.reason == 'taken') message = 'This username is already taken';
if(data.reason == 'banned') message = 'You have been banned from the server for ' + data.time / 60 / 1000 + ' minutes. You have to wait until you get unbanned to be able to connect again';
showChat('light', null, message);
if(!data.keep) {
username = undefined;
connected = false;
} else {
username = oldname;
}
break;
case 'success':
document.getElementById('send').childNodes[0].nodeValue = 'Send';
updateBar('mdi-content-send', 'Enter your message here', false);
connected = true;
settings.name = username;
localStorage.settings = JSON.stringify(settings);
break;
case 'update':
showChat('info', null, data.user.oldun + ' changed its name to ' + data.user.un);
clients[data.user.id] = data.user;
break;
case 'connection':
showChat('info', null, data.user.un + ' connected to the server');
clients[data.user.id] = data.user;
document.getElementById('users').innerHTML = Object.keys(clients).length + ' USERS';
break;
case 'disconnection':
if(data.user.un != null)
showChat('info', null, data.user.un + ' disconnected from the server');
delete clients[data.user.id];
document.getElementById('users').innerHTML = Object.keys(clients).length + ' USERS';
break;
case 'spam':
showChat('global', null, 'You have to wait 1 second between messages. Continuing on spamming the servers may get you banned. Warning ' + data.warn + ' of 5');
break;
case 'clients':
clients = data.clients;
document.getElementById('users').innerHTML = Object.keys(clients).length + ' USERS';
break;
case 'user':
user = data.client.id;
break;
}
} else if((data.type == 'kick' || data.type == 'ban') && data.extra == username) {
location.reload();
} else {
if(data.message.indexOf('@' + username) > -1)
data.type = 'mention';
if(settings.synthesis) {
textToSpeech.text = data.message;
speechSynthesis.speak(textToSpeech);
}
showChat(data.type, data.user, data.message, data.subtxt, data.mid);
}
if(data.type == 'role') {
if(getUserByName(data.extra) != undefined) {
if(data.extra == username && data.role > 0) {
$('#admin').show();
$('#menu-admin').show();
}
if(data.extra == username && data.role == 0) {
$('#admin').hide();
$('#menu-admin').hide();
}
clients[getUserByName(data.extra).id].role = data.role;
}
}
if(data.type == 'global' || data.type == 'pm' || data.type == 'mention') {
if(!focus) {
unread++;
document.title = '(' + unread + ') Node.JS Chat';
if(settings.sound)
blop.play();
if(settings.desktop)
desktopNotif(data.user + ': ' + data.message);
}
}
}
};
function sendSocket(value, method, other, txt) {
socket.send(JSON.stringify({
type: method,
message: value,
subtxt: txt,
extra: other
}));
}
function updateInfo() {
socket.send(JSON.stringify({
user: username,
type: 'update'
}));
}
// Utilities
function getUserByName(name) {
for(client in clients)
if(clients[client].un == name)
return clients[client];
}
function updateBar(icon, placeholder, disable) {
document.getElementById('icon').className = 'mdi ' + icon;
$('#message').attr('placeholder', placeholder);
$('#message').prop('disabled', disable);
$('#send').prop('disabled', disable);
}
function showChat(type, user, message, subtxt, mid) {
if(type == 'global' || type == 'kick' || type == 'ban' || type == 'info' || type == 'light' || type == 'help' || type == 'role') user = 'System';
if(type == 'me' || type == 'em') type = 'emote';
if(!mid) mid == 'system';
var nameclass = '';
if(type == 'emote' || type == 'message') {
if(user == username && getUserByName(user).role == 0) nameclass = 'self';
else {
if(getUserByName(user).role == 1) nameclass = 'helper';
if(getUserByName(user).role == 2) nameclass = 'moderator';
if(getUserByName(user).role == 3) nameclass = 'administrator';
}
}
if(!subtxt)
$('#panel').append('<div data-mid="' + mid + '" class="' + type + '""><span class="name ' + nameclass + '"><b><a class="namelink" href="javascript:void(0)">' + user + '</a></b></span><span class="delete"><a href="javascript:void(0)">DELETE</a></span><span class="timestamp">' + getTime() + '</span><span class="msg">' + message + '</span></div>');
else
$('#panel').append('<div data-mid="' + mid + '" class="' + type + '""><span class="name ' + nameclass + '"><b><a class="namelink" href="javascript:void(0)">' + user + '</a></b></span><span class="timestamp">(' + subtxt + ') ' + getTime() + '</span><span class="msg">' + message + '</span></div>');
$('#panel').animate({scrollTop: $('#panel').prop('scrollHeight')}, 500);
updateStyle();
nmr++;
}
function handleInput() {
var value = $('#message').val().replace(regex, ' ').trim();
if(value.length > 0) {
if(username === undefined) {
username = value;
connect();
} else if(value.charAt(0) == '/') {
var command = value.substring(1).split(' ');
switch(command[0].toLowerCase()) {
case 'pm': case 'msg': case 'role': case 'kick': case 'ban': case 'name': case 'alert': case 'me': case 'em':
if(value.substring(command[0].length).length > 1) {
if((command[0] == 'pm' || command[0] == 'msg') && value.substring(command[0].concat(command[1]).length).length > 2)
sendSocket(value.substring(command[0].concat(command[1]).length + 2), 'pm', command[1], 'PM');
else if(command[0] == 'pm' || command[0] == 'msg')
showChat('light', 'Error', 'Use /' + command[0] + ' [user] [message]');
if(command[0] == 'ban' && value.substring(command[0].concat(command[1]).length).length > 2)
sendSocket(command[1], 'ban', command[2]);
else if(command[0] == 'ban')
showChat('light', 'Error', 'Use /ban [user] [minutes]');
if(command[0] == 'alert')
sendSocket(value.substring(command[0].length + 2), 'global', null, username);
if((command[0] == 'role') && value.substring(command[0].concat(command[1]).length).length > 3)
sendSocket(command[1], 'role', value.substring(command[0].concat(command[1]).length + 3));
else if(command[0] == 'role')
showChat('light', 'Error', 'Use /' + command[0] + ' [user] [0-3]');
if(command[0] == 'kick' || command[0] == 'me' || command[0] == 'em')
sendSocket(value.substring(command[0].length + 2), command[0]);
if(command[0] == 'name') {
oldname = username;
username = value.substring(command[0].length + 2);
updateInfo();
}
} else {
var variables;
if(command[0] == 'alert' || command[0] == 'me' || command[0] == 'em')
variables = ' [message]';
if(command[0] == 'role')
variables = ' [user] [0-3]';
if(command[0] == 'ban')
variables = ' [user] [minutes]';
if(command[0] == 'pm')
variables = ' [user] [message]';
if(command[0] == 'kick')
variables = ' [user]';
if(command[0] == 'name')
variables = ' [name]';
showChat('light', 'Error', 'Use /' + command[0] + variables);
}
break;
case 'clear':
nmr = 0;
document.getElementById('panel').innerHTML = '';
showChat('light', 'System', 'Messages cleared');
break;
case 'shrug':
sendSocket(value.substring(6) + ' ¯\\_(ツ)_/¯', 'message');
break;
case 'help':
$('#help-dialog').modal('show');
$('#message').val('');
break;
case 'reconnect':
socket.close();
break;
default:
showChat('light', 'Error', 'Unknown command, use /help to get a list of the available commands');
break;
}
} else {
sendSocket(value, 'message');
}
$('#message').val('');
}
}
function getTime() {
var now = new Date(),
time = [now.getHours(), now.getMinutes(), now.getSeconds()];
for(var i = 0; i < 3; i++) {
if(time[i] < 10)
time[i] = '0' + time[i];
}
return time.join(':');
}
function updateStyle() {
$('#panel').linkify();
var element = document.getElementsByClassName('msg')[nmr];
if(element.innerHTML != undefined) {
if(settings.greentext && element.innerHTML.indexOf('>') == 0)
element.style.color = '#689f38';
if(settings.emoji) {
var input = element.innerHTML;
var output = emojione.shortnameToImage(element.innerHTML);
element.innerHTML = output;
}
}
}
// Triggers
$(document).ready(function() {
$('#user').bind('click', function() {
var content = '',
admin;
for(var i in clients) {
if(clients[i] != undefined) {
if(clients[i].role == 0) admin = '</li>'
if(clients[i].role == 1) admin = ' - <b>Helper</b></li>';
if(clients[i].role == 2) admin = ' - <b>Moderator</b></li>';
if(clients[i].role == 3) admin = ' - <b>Administrator</b></li>';
content += '<li><b>ID:</b> ' + clients[i].id + ' - <b>Name:</b> ' + clients[i].un + admin;
}
}
document.getElementById('users-content').innerHTML = content;
$('#users-dialog').modal('show');
});
$('#panel').on('mouseenter', '.message', function() {
if(clients[user].role > 0) {
$(this).find('span:eq(1)').show();
$(this).find('span:eq(2)').hide();
}
});
$('#panel').on('mouseleave', '.message',function() {
if(clients[user].role > 0) {
$(this).find('span:eq(1)').hide();
$(this).find('span:eq(2)').show();
}
});
$('#panel').on('mouseenter', '.emote', function() {
if(clients[user].role > 0) {
$(this).find('span:eq(1)').show();
$(this).find('span:eq(2)').hide();
}
});
$('#panel').on('mouseleave', '.emote', function() {
if(clients[user].role > 0) {
$(this).find('span:eq(1)').hide();
$(this).find('span:eq(2)').show();
}
});
$('#panel').on('click', '.delete', function(e) {
var value = $(this)[0].parentElement.attributes[0].value;
sendSocket(value, 'delete');
});
$('#panel').on('click', '.name', function(e) {
$('#message').val('@' + $(this)[0].children[0].children[0].innerHTML + ' ');
$('#message').focus();
});
$('#send').bind('click', function() {
handleInput();
});
$('#menu-admin').bind('click', function() {
$('#admin-help-dialog').modal('show');
});
$('#help').bind('click', function() {
$('#help-dialog').modal('show');
});
$('#options').bind('click', function() {
$('#options-dialog').modal('show');
});
$('#menu-options').bind('click', function() {
$('#options-dialog').modal('show');
});
$('#audio').bind('click', function() {
speechToText.start();
updateBar('mdi-av-mic', 'Start speaking', true);
});
$('#emoji').bind('change', function() {
settings.emoji = document.getElementById('emoji').checked;
localStorage.settings = JSON.stringify(settings);
});
$('#greentext').bind('change', function() {
settings.greentext = document.getElementById('greentext').checked;
localStorage.settings = JSON.stringify(settings);
});
$('#sound').bind('change', function() {
settings.sound = document.getElementById('sound').checked;
localStorage.settings = JSON.stringify(settings);
});
$('#synthesis').bind('change', function() {
settings.synthesis = document.getElementById('synthesis').checked;
localStorage.settings = JSON.stringify(settings);
});
$('#desktop').bind('change', function() {
settings.desktop = document.getElementById('desktop').checked;
localStorage.settings = JSON.stringify(settings);
if(Notification.permission !== 'granted')
Notification.requestPermission();
});
$('#recognition').bind('change', function() {
settings.recognition = document.getElementById('recognition').checked;
localStorage.settings = JSON.stringify(settings);
if(settings.recognition)
$('#audio').show();
else {
$('#audio').hide();
}
});
$('#message').keypress(function(e) {
if(e.which == 13) {
if(connected && typing) {
typing = false;
clearTimeout(typeTimer);
socket.send(JSON.stringify({type:'typing', typing:false}));
}
handleInput();
} else if(connected) {
if(!typing) {
typing = true;
socket.send(JSON.stringify({type:'typing', typing:true}));
}
clearTimeout(typeTimer);
typeTimer = setTimeout(function() {
typing = false;
socket.send(JSON.stringify({type:'typing', typing:false}));
}, 2000);
}
});
});
// Intern
if(Notification) {
$('#toggle-desktop').show();
}
if('speechSynthesis' in window) {
$('#toggle-synthesis').show();
textToSpeech = new SpeechSynthesisUtterance();
textToSpeech.lang = 'en';
}
if('SpeechRecognition' in window || 'webkitSpeechRecognition' in window) {
$('#toggle-recognition').show();
var speechToText = new webkitSpeechRecognition();
speechToText.interimResults = true;
speechToText.continuous = true;
speechToText.lang = 'en-US';
}
speechToText.onresult = function(event) {
$('#message').val('');
for (var i = event.resultIndex; i < event.results.length; ++i) {
if (event.results[i].isFinal) {
$('#message').val(event.results[i][0].transcript);
updateBar('mdi-content-send', 'Enter your message here', false);
speechToText.stop();
handleInput();
} else {
var oldval = $('#message').val();
$('#message').val(oldval + event.results[i][0].transcript);
}
}
}
speechToText.onerror = function(event) {
updateBar('mdi-content-send', 'Enter your message here', false);
}
function desktopNotif(message) {
if(!Notification)
return;
var notification = new Notification('You\'ve got a new message', {
icon: 'http://i.imgur.com/ehB0QcM.png',
body: message
});
}
if(typeof(Storage) !== 'undefined') {
if(!localStorage.settings) {
localStorage.settings = JSON.stringify(settings);
} else {
settings = JSON.parse(localStorage.settings);
document.getElementById('emoji').checked = settings.emoji;
document.getElementById('greentext').checked = settings.greentext;
document.getElementById('sound').checked = settings.sound;
document.getElementById('desktop').checked = settings.desktop;
document.getElementById('synthesis').checked = settings.synthesis;
document.getElementById('recognition').checked = settings.recognition;
if(settings.recognition)
$('#audio').show();
}
}
window.onfocus = function() {
document.title = 'Node.JS Chat';
focus = true;
unread = 0;
};
window.onblur = function() {
focus = false;
}; |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: >
The production QuantifierPrefix :: ? evaluates by returning the two
results 0 and 1
es5id: 15.10.2.7_A5_T8
description: Execute /x?ay?bz?c/.exec("abcd") and check results
---*/
__executed = /x?ay?bz?c/.exec("abcd");
__expected = ["abc"];
__expected.index = 0;
__expected.input = "abcd";
//CHECK#1
if (__executed.length !== __expected.length) {
$ERROR('#1: __executed = /x?ay?bz?c/.exec("abcd"); __executed.length === ' + __expected.length + '. Actual: ' + __executed.length);
}
//CHECK#2
if (__executed.index !== __expected.index) {
$ERROR('#2: __executed = /x?ay?bz?c/.exec("abcd"); __executed.index === ' + __expected.index + '. Actual: ' + __executed.index);
}
//CHECK#3
if (__executed.input !== __expected.input) {
$ERROR('#3: __executed = /x?ay?bz?c/.exec("abcd"); __executed.input === ' + __expected.input + '. Actual: ' + __executed.input);
}
//CHECK#4
for(var index=0; index<__expected.length; index++) {
if (__executed[index] !== __expected[index]) {
$ERROR('#4: __executed = /x?ay?bz?c/.exec("abcd"); __executed[' + index + '] === ' + __expected[index] + '. Actual: ' + __executed[index]);
}
}
|
import React from 'react';
import SingleDatePicker from 'react-dates/lib/components/SingleDatePicker';
class SingleDatePickerWrapper extends React.Component {
constructor(props) {
super(props);
this.state = {
focused: false,
date: null,
};
this.onDateChange = this.onDateChange.bind(this);
this.onFocusChange = this.onFocusChange.bind(this);
}
onDateChange(date) {
this.setState({ date });
}
onFocusChange({ focused }) {
this.setState({ focused });
}
render() {
const { focused, date } = this.state;
return (
<SingleDatePicker
{...this.props}
id="date_input"
date={date}
focused={focused}
onDateChange={this.onDateChange}
onFocusChange={this.onFocusChange}
/>
);
}
}
export default SingleDatePickerWrapper;
|
(function(angular) {
'use strict';
angular.module('gravatarImageExample', ['bgn.GravatarImage'])
.controller('GravatarImageController', ['$scope', function($scope) {
$scope.email = 'deerawan@gmail.com';
}]);
})(window.angular); |
/**
* bearerAuth Policy
*
* Policy for authorizing API requests. The request is authenticated if the
* it contains the accessToken in header, body or as a query param.
* Unlike other strategies bearer doesn't require a session.
* Add this policy (in config/policies.js) to controller actions which are not
* accessed through a session. For example: API request from another client
*
* @param {Object} req
* @param {Object} res
* @param {Function} next
*/
module.exports = function (req, res, next) {
return passport.authenticate('bearer', { session: false })(req, res, next);
};
|
module.exports = {
db: process.env.DB_CONN_STRING || 'postgres://test@localhost:5432/test',
secretHash: 'thecakeisalie',
env: 'test'
};
|
{
'welcome':"Bienvenue sur le web en français",
'hello':"Quoi de neuf",
'paths': {
'greeting' : "/salutation"
}
} |
if(typeof exports === 'object') {
var assert = require("assert");
var alasql = require('..');
var _ = require('lodash');
} else {
__dirname = '.';
};
describe('Test 287 SET NOCOUNT OFF/ON', function() {
it('1. CREATE TABLE and FIRST INSERT',function(done){
alasql('CREATE DATABASE test287;USE test287');
done();
});
it('2. SET',function(done){
assert(!alasql.options.nocount);
var res = alasql('SET NOCOUNT ON');
assert(alasql.options.nocount);
var res = alasql('SET NOCOUNT OFF');
assert(!alasql.options.nocount);
done();
});
it('3. CREATE TABLE',function(done){
alasql('SET NOCOUNT OFF');
var res = alasql('CREATE TABLE one');
assert(res == 1);
alasql('SET NOCOUNT ON');
var res = alasql('CREATE TABLE two');
assert(typeof res == 'undefined');
done();
});
it('4. INSERT',function(done){
alasql('SET NOCOUNT OFF');
var res = alasql('INSERT INTO one VALUES {a:1},{a:2}');
assert(res == 2);
alasql('SET NOCOUNT ON');
var res = alasql('INSERT INTO two VALUES {b:10},{b:20}');
assert(typeof res == 'undefined');
done();
});
// TODO: Add other operators
it('3. DROP DATABASE',function(done){
var res = alasql('DROP DATABASE test287');
done();
});
});
|
{
"metadata" :
{
"formatVersion" : 3.1,
"sourceFile" : "dice.obj",
"generatedBy" : "OBJConverter",
"vertices" : 8,
"faces" : 6,
"normals" : 6,
"uvs" : 22,
"materials" : 1
},
"materials": [ {
"DbgColor" : 15658734,
"DbgIndex" : 0,
"DbgName" : "Material",
"colorAmbient" : [0.207916, 0.207916, 0.207916],
"colorDiffuse" : [0.8, 0.8, 0.8],
"colorSpecular" : [1.0, 1.0, 1.0],
"illumination" : 0,
"mapDiffuse" : "dice.png",
"opticalDensity" : 1.0,
"specularCoef" : 96.078431,
"transparency" : 1.0
}],
"buffers": "dice_bin.bin"
}
|
'use strict';
/**
* @ngdoc overview
* @name knobyApp
* @description
* # knobyApp
*
* Main module of the application.
*/
angular
.module('knobyApp', [
'knoby.hammer',
'knoby.lodash',
'knoby.d3',
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch'
])
.config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl'
})
.otherwise({
redirectTo: '/'
});
}]);
|
import Sequelize from 'sequelize';
import config from '../config/config';
import User from './User';
import Permissionlevel from './Permissionlevel';
import Project from './Project';
import Users_have_Projects from './Users_have_Projects';
let model = {};
let sequelize = new Sequelize(config.postgresql.connectionString, {
logging: false,
timestamps: false,
freezeTableName: true
});
sequelize
.authenticate()
.catch(err => {
console.error('Unable to connect to the database:', err);
});
model.User = new User(sequelize);
model.Permissionlevel = new Permissionlevel(sequelize);
model.Project = new Project(sequelize);
model.Users_have_Projects = new Users_have_Projects(sequelize);
module.exports = model; |
import React from 'react'
export default () => <h2>I'm a Basic Literasee Component</h2>
|
import Button from './Button.js';// eslint-disable-line no-unused-vars
|
module.exports = {
"key": "pichu",
"moves": [
{
"learn_type": "tutor",
"name": "covet"
},
{
"learn_type": "machine",
"name": "wild-charge"
},
{
"learn_type": "machine",
"name": "volt-switch"
},
{
"learn_type": "egg move",
"name": "bestow"
},
{
"learn_type": "machine",
"name": "echoed-voice"
},
{
"learn_type": "machine",
"name": "round"
},
{
"learn_type": "egg move",
"name": "lucky-chant"
},
{
"learn_type": "egg move",
"name": "flail"
},
{
"learn_type": "tutor",
"name": "magnet-rise"
},
{
"learn_type": "tutor",
"name": "signal-beam"
},
{
"learn_type": "tutor",
"name": "helping-hand"
},
{
"learn_type": "tutor",
"name": "uproar"
},
{
"learn_type": "machine",
"name": "charge-beam"
},
{
"learn_type": "machine",
"name": "grass-knot"
},
{
"learn_type": "machine",
"name": "captivate"
},
{
"learn_type": "level up",
"level": 18,
"name": "nasty-plot"
},
{
"learn_type": "machine",
"name": "fling"
},
{
"learn_type": "machine",
"name": "natural-gift"
},
{
"learn_type": "egg move",
"name": "tickle"
},
{
"learn_type": "egg move",
"name": "fake-out"
},
{
"learn_type": "egg move",
"name": "thunderpunch"
},
{
"learn_type": "other",
"name": "volt-tackle"
},
{
"learn_type": "tutor",
"name": "substitute"
},
{
"learn_type": "tutor",
"name": "mimic"
},
{
"learn_type": "tutor",
"name": "seismic-toss"
},
{
"learn_type": "tutor",
"name": "counter"
},
{
"learn_type": "tutor",
"name": "double-edge"
},
{
"learn_type": "tutor",
"name": "body-slam"
},
{
"learn_type": "tutor",
"name": "mega-kick"
},
{
"learn_type": "tutor",
"name": "mega-punch"
},
{
"learn_type": "machine",
"name": "shock-wave"
},
{
"learn_type": "machine",
"name": "secret-power"
},
{
"learn_type": "egg move",
"name": "wish"
},
{
"learn_type": "egg move",
"name": "charge"
},
{
"learn_type": "machine",
"name": "facade"
},
{
"learn_type": "machine",
"name": "light-screen"
},
{
"learn_type": "tutor",
"name": "thunderbolt"
},
{
"learn_type": "machine",
"name": "rain-dance"
},
{
"learn_type": "machine",
"name": "hidden-power"
},
{
"learn_type": "machine",
"name": "iron-tail"
},
{
"learn_type": "egg move",
"name": "encore"
},
{
"learn_type": "machine",
"name": "frustration"
},
{
"learn_type": "egg move",
"name": "present"
},
{
"learn_type": "machine",
"name": "return"
},
{
"learn_type": "machine",
"name": "sleep-talk"
},
{
"learn_type": "machine",
"name": "attract"
},
{
"learn_type": "machine",
"name": "swagger"
},
{
"learn_type": "machine",
"name": "rollout"
},
{
"learn_type": "level up",
"level": 1,
"name": "charm"
},
{
"learn_type": "machine",
"name": "endure"
},
{
"learn_type": "machine",
"name": "detect"
},
{
"learn_type": "machine",
"name": "zap-cannon"
},
{
"learn_type": "machine",
"name": "mud-slap"
},
{
"learn_type": "level up",
"level": 11,
"name": "sweet-kiss"
},
{
"learn_type": "machine",
"name": "protect"
},
{
"learn_type": "egg move",
"name": "reversal"
},
{
"learn_type": "machine",
"name": "curse"
},
{
"learn_type": "machine",
"name": "snore"
},
{
"learn_type": "machine",
"name": "rest"
},
{
"learn_type": "machine",
"name": "flash"
},
{
"learn_type": "machine",
"name": "swift"
},
{
"learn_type": "egg move",
"name": "bide"
},
{
"learn_type": "machine",
"name": "defense-curl"
},
{
"learn_type": "machine",
"name": "double-team"
},
{
"learn_type": "machine",
"name": "toxic"
},
{
"learn_type": "machine",
"name": "thunder"
},
{
"learn_type": "level up",
"level": 8,
"name": "thunder-wave"
},
{
"learn_type": "level up",
"level": 1,
"name": "thundershock"
},
{
"learn_type": "level up",
"level": 6,
"name": "tail-whip"
},
{
"learn_type": "machine",
"name": "headbutt"
},
{
"learn_type": "egg move",
"name": "doubleslap"
}
]
}; |
/*jslint indent:2*/
/**
* Snow main class
*/
var Snow = function(config) {
this.init(config);
this.create();
};
Snow.prototype = {
// public
start: function() {
this.render();
},
stop: function() {
// this.create();
},
// View constructor
init: function(config) {
this.config(config);
// AnimationFrame Polyfill
var lastTime = 0;
var vendors = ['webkit', 'moz'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if(!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}
this._createCanvas();
// $(window).scroll($.proxy(this.onScroll, this));
// $(window).on('resize', $.proxy(this.onResize, this));
},
// public
config: function(config) {
// Storing the View context
var self = this;
//————————————————————— C U S T O M V A L U E S
// Debug
this.debug = true;
this.stats = null;
// Snow behavior
this.intro = true; // If true, the snowflakes will appear from the top left hand corner, instead of directly filling the screen.
this.fade = true; // If true, the snowflakes will appear using opacity
// Snow Look
this.snowAmount = config.amount; // The number of snowflakes
this.snowSize = 1;// Scale of individual snowflakes. 1 is normal, 2 is double, 0.5 is half
this.sizeMin = config.sizeMin;
this.sizeMax = config.sizeMax;
this.windMin = config.windMin;
this.windMax = config.windMax;
// Snow distance
this.snowZmin = config.sizeMin; // The min snowflake distance : 0 is close, 1 is far
this.snowZmax = config.sizeMax; // The max snowflake distance : 0 is close, 1 is far
// Snow Opacity
this.snowAlphaMin = 1; // The minimum alpha value
this.snowAlphaMax = 1; // The maximum alpha value
// Snow Rotation
this.snowRotation = 0; // Rotation animation. 0.5 is half, 2 is double.
// Gravity
this.gravity = config.gravity; // Speed of fall. 100 is the normal speed. 0 to float, -100 to inverse the direction.
// Wind Force
this.windBegin = 10; // The inital wind when the snow starts, then it smoothly changes to the normal values
this.windForceMin = 2; // The minimum force of the wind
this.windForceMax = 10; // The maximum force of the wind
// Wind Direction
this.windDirection = "both"; // You can chose between "left", "right", and "both"
// Wind duration
this.windTimeMin = 1; // Minimum time between two winds
this.windTimeMax = 20; // Maximum time between two winds
this.activeFlakes = [];
// this.gravity = Math.random() * 40 - 20;
this.wind = {force: 1};
// scrolling
this.previousScroll = 0;
},
create: function() {
// this._randomgravity();
this._randomWind();
this._createSnow();
if(this.debug) {
this._createStats();
}
},
destroy: function() {
for (var i = 0; i < this.activeFlakes.length; i++) {
delete(this.activeFlakes[i]);
}
this.activeFlakes = [];
},
render: function() {
if(this.debug) {
this.stats.begin();
}
// clear the canvas
this._clear();
// render the flakes
for (var i = 0; i < this.activeFlakes.length; i++) {
this.activeFlakes[i].gravity = this.gravity;
this.activeFlakes[i].wind = this.wind;
this.activeFlakes[i].update();
this.activeFlakes[i].render();
}
this._loop(this.render);
if(this.debug) {
this.stats.end();
}
},
// private
_clear: function() {
this.context.clearRect(0, 0, $(window).width(), $(window).height());
},
_loop: function(handler) {
window.requestAnimationFrame($.proxy(handler, this));
},
_createStats: function() {
this.stats = new Stats();
this.stats.setMode(0);
// Align top-left
this.stats.domElement.style.position = 'fixed';
this.stats.domElement.style.left = '0px';
this.stats.domElement.style.top = '0px';
this.stats.domElement.style.zIndex = '20000';
document.body.appendChild( this.stats.domElement );
},
// canvas
_createCanvas: function() {
var canvas = $('<canvas/>',{'class':'flares', 'id':'flares'});
$('body > #container').after(canvas);
this.context = canvas[0].getContext('2d');
this._resizeCanvas();
},
_resizeCanvas: function() {
$('#flares').attr('width', $(window).width()).attr('height', $(window).height());
},
// snow
_createSnow: function() {
for (var i=0; i < this.snowAmount; i++) {
this._createFlake(i);
}
this._distributeFlakes();
for (var i = 0; i < this.activeFlakes.length; i++) {
this.activeFlakes[i].gravity = this.gravity;
this.activeFlakes[i].wind = this.wind;
this.activeFlakes[i].startAnimation();
}
},
_distributeFlakes: function() {
for (var i = 0; i < this.activeFlakes.length; i++) {
this.activeFlakes[i].x = Math.random() * $(window).width();
this.activeFlakes[i].y = Math.random() * $(window).height();
}
// var iterationsWidth = 1;
// var iterationsHeight = 1;
// for (var i = 0; i < this.activeFlakes.length; i++) {
// var x = 0;
// for (var j = 0; j < iterationsWidth; j++) {
// x += Math.random() * $(window).width() *1.2;
// };
// this.activeFlakes[i].x = x / iterationsWidth + $(window).width() * 0.5 - 50;
// if(this.activeFlakes[i].x > $(window).width()) {
// this.activeFlakes[i].x = $(window).width() - (this.activeFlakes[i].x - $(window).width());
// }
// var y = 0;
// for (var j = 0; j < iterationsHeight; j++) {
// y += Math.random() * $(window).height();
// };
// this.activeFlakes[i].y = y / (iterationsHeight);
// }
},
_createFlake: function() {
var m = new Snowflake({
sizeMin: this.sizeMin,
sizeMax: this.sizeMax
});
m.context = this.context;
this.activeFlakes.push(m);
},
_randomgravity: function() {
TweenLite.to(this, Math.random() * 5 + 1, {
gravity: this.gravity + Math.random() * this.gravity - this.gravity * 0.5,
onComplete: $.proxy(this._randomgravity, this)
});
},
_randomWind: function() {
var nWind;
var wind = new Object;
wind.min = this.windMin;
wind.max = this.windMax;
wind.dir = "left";
// Wind duration
var windTimeMin = 3; // Minimum time between two winds
var windTimeMax = 10; // Maximum time between two winds
if(wind.dir == "right") {
nWind = Math.random() * (wind.max - wind.min) + wind.min;
} else if(wind.dir == "left") {
nWind = -Math.random()*(wind.max-wind.min)-wind.min;
} else {
nWind = Math.random()*(wind.max*2-wind.min)-wind.min-wind.max;
}
if(this.debug == true) {
console.log("SNOW : next wind : "+nWind)
}
TweenLite.to(this.wind, Math.random()*3+1, {
force: nWind,
delay: Math.random() * ( windTimeMax - windTimeMin) + windTimeMin,
onComplete:$.proxy(this._randomWind, this)
});
},
// eventhandler
onScroll: function(event) {
// var currentScroll = $(window).scrollTop();
// var gravity;
// if (currentScroll > this.previousScroll){
// gravity = -50;
// } else {
// gravity = 50;
// }
// this.previousScroll = currentScroll;
// var perc = $(document).scrollTop() / ($(document).height() - $(window).height());
// TweenLite.killTweensOf($('#background'));
// TweenLite.killTweensOf($(this));
// TweenLite.to($('#background'), 0.4, {css:{top:(perc*-100)}});
// TweenLite.to($(this), 0.4, {
// gravity: gravity,
// onComplete: $.proxy(this._randomgravity, this),
// ease: Linear.easeInOut,
// overwrite: true
// });
var perc = $(document).scrollTop() / ($(document).height() - $(window).height());
$('#background').css({'top': (perc * -2000)});
// TweenLite.to($('#background'), 0.4, {
// css:{
// top:(perc * -2000)
// },
// overwrite: true
// });
},
onResize: function() {
this._resizeBackground();
}
} |
var path = require('path');
var basic = require('../functions/basic.js');
var consoleLogger = require('../functions/basic.js').consoleLogger;
var userDB = require('../db/user_db.js');
var receivedLogger = function (module) {
var rL = require('../functions/basic.js').receivedLogger;
rL('router', module);
};
var successLogger = function (module, text) {
var sL = require('../functions/basic.js').successLogger;
return sL('router', module, text);
};
var errorLogger = function (module, text, err) {
var eL = require('../functions/basic.js').errorLogger;
return eL('router', module, text, err);
};
function getTheUser(req) {
return req.customData.theUser;
}
function getTheCurrentGrillStatus(req) {
return req.customData.currentGrillStatus;
}
module.exports = {
index_Html: function (req, res) {
var module = 'indexHtml';
receivedLogger(module);
if (req.user) {
res.redirect("clientHome.html");
} else {
res.render('index', {
errorCode: 0,
errorMessage: "No errors"
})
}
},
clientHome_Html: function (req, res) {
var module = 'clientHome_Html';
receivedLogger(module);
var theUser = getTheUser(req);
if (theUser.customLoggedInStatus == 1 && theUser.isAdmin == 'yes') {
res.redirect('admin.html');
} else if (theUser.customLoggedInStatus == 1 && theUser.isAdmin == 'no') {
res.redirect('client.html');
} else {
if (theUser.isAdmin == 'yes') {
res.redirect('adminHome.html');
} else {
var gaUserId = "ga('set', '&uid', " + "'" + theUser.uniqueCuid + "');";
res.render('client/client_home', {
gAnalyticsUserId: gaUserId
})
}
}
},
adminHome_Html: function (req, res) {
var module = 'admin_home_Html';
receivedLogger(module);
var theUser = getTheUser(req);
if (theUser.customLoggedInStatus == 1 && theUser.isAdmin == 'yes') {
res.redirect('admin.html');
} else if (theUser.customLoggedInStatus == 1 && theUser.isAdmin == 'no') {
res.redirect('client.html');
} else {
if (theUser.isAdmin == 'yes') {
var gaUserId = "ga('set', '&uid', " + "'" + theUser.uniqueCuid + "');";
res.render('admin/admin_home', {
gAnalyticsUserId: gaUserId
})
} else {
res.redirect('clientHome.html')
}
}
},
client_Html: function (req, res) {
var module = 'client_Html';
receivedLogger(module);
var theUser = getTheUser(req);
if (theUser.isAdmin == 'yes') {
res.redirect('admin.html');
} else if (theUser.isAdmin == 'no') {
var gaUserId = "ga('set', '&uid', " + "'" + theUser.uniqueCuid + "');";
res.render('client/client.ejs', {
gAnalyticsUserId: gaUserId
});
}
},
client_profile_Html: function (req, res) {
var module = 'client_profile_Html';
receivedLogger(module);
var theUser = getTheUser(req);
if (theUser.isAdmin == 'yes') {
res.redirect('adminProfile.html');
} else if (theUser.isAdmin == 'no') {
var gaUserId = "ga('set', '&uid', " + "'" + theUser.uniqueCuid + "');";
res.render('client/client_profile.ejs', {
gAnalyticsUserId: gaUserId,
fullName: theUser.fullName
});
}
},
admin_Html: function (req, res) {
var module = 'admin_Html';
receivedLogger(module);
var theUser = getTheUser(req);
if (theUser.isAdmin == 'yes') {
var gaUserId = "ga('set', '&uid', " + "'" + theUser.uniqueCuid + "');";
res.render('admin/admin.ejs', {
gAnalyticsUserId: gaUserId
});
} else if (theUser.isAdmin == 'no') {
res.redirect('client.html');
}
},
admin_profile_Html: function (req, res) {
var module = 'admin_profile_Html';
receivedLogger(module);
var theUser = getTheUser(req);
if (theUser.isAdmin == 'yes') {
var gaUserId = "ga('set', '&uid', " + "'" + theUser.uniqueCuid + "');";
res.render('admin/admin_profile.ejs', {
gAnalyticsUserId: gaUserId,
fullName: theUser.fullName
});
} else if (theUser.isAdmin == 'no') {
res.redirect('clientProfile.html');
}
}
}; |
/**
* Create display state chunk type for draw render of lights projection
*/
SceneJS_ChunkFactory.createChunkType({
type:"lights",
build:function () {
this._uAmbientColor = this._uAmbientColor || [];
this._uLightColor = this._uLightColor || [];
this._uLightDir = this._uLightDir || [];
this._uLightPos = this._uLightPos || [];
this._uLightCutOff = this._uLightCutOff || [];
this._uLightSpotExp = this._uLightSpotExp || [];
this._uLightAttenuation = this._uLightAttenuation || [];
var lights = this.core.lights;
var program = this.program;
for (var i = 0, len = lights.length; i < len; i++) {
switch (lights[i].mode) {
case "ambient":
this._uAmbientColor[i] = (program.draw.getUniform("SCENEJS_uAmbientColor"));
break;
case "dir":
this._uLightColor[i] = program.draw.getUniform("SCENEJS_uLightColor" + i);
this._uLightPos[i] = null;
this._uLightDir[i] = program.draw.getUniform("SCENEJS_uLightDir" + i);
break;
case "point":
this._uLightColor[i] = program.draw.getUniform("SCENEJS_uLightColor" + i);
this._uLightPos[i] = program.draw.getUniform("SCENEJS_uLightPos" + i);
this._uLightDir[i] = null;
this._uLightAttenuation[i] = program.draw.getUniform("SCENEJS_uLightAttenuation" + i);
break;
}
}
},
draw:function (frameCtx) {
if (frameCtx.dirty) {
this.build();
}
var lights = this.core.lights;
var light;
var gl = this.program.gl;
for (var i = 0, len = lights.length; i < len; i++) {
light = lights[i];
if (this._uAmbientColor[i]) {
this._uAmbientColor[i].setValue(light.color);
} else {
if (this._uLightColor[i]) {
this._uLightColor[i].setValue(light.color);
}
if (this._uLightPos[i]) {
this._uLightPos[i].setValue(light.pos);
if (this._uLightAttenuation[i]) {
this._uLightAttenuation[i].setValue(light.attenuation);
}
}
if (this._uLightDir[i]) {
this._uLightDir[i].setValue(light.dir);
}
}
}
}
}); |
import getViewportSize from '../../util/dom/getViewportSize';
import createPlacement from './create';
import BottomLeft from './bottom-left';
import BottomRight from './bottom-right';
import BottomCenter from './bottom-center';
import TopLeft from './top-left';
import TopRight from './top-right';
import TopCenter from './top-center';
const positionMap = {
BottomLeft,
BottomRight,
BottomCenter,
TopLeft,
TopRight,
TopCenter,
};
function locate(anchorBoundingBox, containerBoundingBox, contentDimension, options) {
const viewport = getViewportSize();
const { anchorBoundingBoxViewport, cushion } = options;
let horizontal;
let vertical;
const mid = (anchorBoundingBoxViewport.left + anchorBoundingBoxViewport.right) / 2;
const halfWidth = contentDimension.width / 2;
// Only when the right does not fit, and the left can be put down when the move to the left
if (
mid + halfWidth > viewport.width &&
anchorBoundingBoxViewport.right - contentDimension.width > 0
) {
horizontal = 'Right';
} else if (
mid - halfWidth < 0 &&
anchorBoundingBoxViewport.left + contentDimension.width < viewport.width
) {
horizontal = 'Left';
} else {
horizontal = 'Center';
}
// Only when the following can not fit, and the above can be put down to move to the top
if (
anchorBoundingBoxViewport.top - cushion - contentDimension.height < 0 &&
anchorBoundingBoxViewport.bottom + cushion + contentDimension.height < viewport.height
) {
vertical = 'Bottom';
} else {
vertical = 'Top';
}
const key = `${vertical}${horizontal}`;
return positionMap[key].locate(
anchorBoundingBox,
containerBoundingBox,
contentDimension,
options,
);
}
const AutoBottomCenter = createPlacement(locate);
export default AutoBottomCenter;
|
/*
* routes for config page
*/
var db = require('./db')
, config = require('./config');
// Get all DB entries and render the config.jade file
exports.list = function(req, res){
db.query(function(pclist){
res.render('config',{title: 'Wol', pclist: pclist});
});
};
// add one entrie from the database and render config.jade again
exports.add = function(req, res){
db.add(req, res, function(){
config.list(req,res);
});
};
// remove one entrie from the database and render config.jade again
exports.remove = function(req, res){
db.remove(req, res, function(){
config.list(req,res);
});
};
|
// All symbols in the Shorthand Format Controls block as per Unicode v9.0.0:
[
'\uD82F\uDCA0',
'\uD82F\uDCA1',
'\uD82F\uDCA2',
'\uD82F\uDCA3',
'\uD82F\uDCA4',
'\uD82F\uDCA5',
'\uD82F\uDCA6',
'\uD82F\uDCA7',
'\uD82F\uDCA8',
'\uD82F\uDCA9',
'\uD82F\uDCAA',
'\uD82F\uDCAB',
'\uD82F\uDCAC',
'\uD82F\uDCAD',
'\uD82F\uDCAE',
'\uD82F\uDCAF'
]; |
/*
* Copyright 2017 Bennett Somerville
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
const https = require('https'),
zlib = require('zlib');
/**
* A project with a set of client IDs.
*/
class Project {
/**
* Creates a Google sign in project.
* @param {string[]} clientIds A list of valid client IDs.
*/
constructor(...clientIds) {
this.clientIds = clientIds;
}
/**
* Verifies a token generated by the client.
* @param {string} idToken The token to verify.
* @return {Promise<object>} A promise that resolves with the JSON returned by the API (see https://developers.google.com/identity/sign-in/web/backend-auth#calling-the-tokeninfo-endpoint) if the token is valid and rejects if it is invalid or if an error occured. 'aud' and 'exp' claims are automatically verified.
*/
verifyToken(idToken) {
// Declare the promise to return
const promise = new Promise((resolve, reject) => {
// Construct a get request
https.get({
'hostname' : 'www.googleapis.com',
'path' : '/oauth2/v3/tokeninfo?id_token=' + idToken,
'headers' : {
'Accept' : 'application/json',
'Accept-Encoding' : 'gzip, deflate'
}
}, (res) => { // Callback function
// Create a function to return the new data
const returnData = (err, newData) => {
// Check for an error
if (err) {
reject(err);
} else {
// Try - catch for a parse error
try {
// Parse data
const jsonData = JSON.parse(newData);
// Check for errors
if (jsonData.hasOwnProperty('error_description')) { // Check for an error returned by Gogle
reject(new Error(jsonData.error_description));
} else if (this.clientIds.indexOf(jsonData.aud) === -1) { // Verify that the token is for the correct project
reject(new Error('The \'aud\' claim does not match a client ID.'));
} else if (new Date(jsonData.exp) < new Date()) { // Verify that the token is not expired
reject(new Error('The \'exp\' claim has expired.'));
} else { // Resolve with data if all goes well
resolve(jsonData);
}
} catch (parseError) {
reject(parseError);
}
}
};
// Check the copression method used
const compressionMethod = res.headers['content-encoding'];
// Create a stream
var stream = res;
if (compressionMethod === 'gzip') {
stream = res.pipe(zlib.createGunzip());
} else if (compressionMethod === 'deflate') {
stream = res.pipe(zlib.createDeflate());
}
// Gather the data, parse, and return
var data = new Buffer([]);
stream.on('data', (chunk) => {
data = Buffer.concat([data, chunk]);
});
stream.on('end', () => {
returnData(null, data);
});
}).on('error', (error) => {
reject(error); // Reject in case of request error
});
});
return promise; // Return the promise
}
}
module.exports = { Project }; |
version https://git-lfs.github.com/spec/v1
oid sha256:bc7d1eb1b09ca463642b46225f6b96ce28401f54e6c925df216686427c74e922
size 23900
|
version https://git-lfs.github.com/spec/v1
oid sha256:26cd19b47656e784cda9f0d9d58a8b57edf007b6e9820b4a663a32cacb0a7352
size 5461
|
'use strict';
var TestHelpers = require('./test-helpers');
var Logfire = require('../lib/logfire-client');
var client, server;
client = new Logfire('http://localhost:8088');
describe('client.query', function() {
before(function() {
return TestHelpers.runServer()
.then(function (_server) {
server = _server;
});
});
beforeEach(function () {
return server.store.reset();
});
var id;
beforeEach(function() {
return client.events.create({
event: 'cache.hit'
}).then(function (response) {
id = response.$id;
});
});
describe('#query', function() {
it('successfully runs the query and returns the result', function() {
return client.query.query({
events: ['cache.hit']
}).then(function(response) {
response[0].$id.should.equal(id);
});
});
it('should return an error if it fails to run the query', function() {
return client.query.query({
events: ['foo.bar']
}).catch(function(err) {
err.message.should.equal('The event \"foo.bar\" does not exist.');
});
});
});
});
|
const findParent = (target, el={}) => target === el
? true
: !!el.parentElement && findParent(target, el.parentElement)
export default {
name: 'dropdown-menu',
props: {
options: {
type: Array,
default: () => []
},
tag: {
type: String,
default: 'a'
},
title: String
},
data() {
return {
visible: false
}
},
methods: {
_renderLink(h, item) {
const on = {}
if (item.click) on.click = !item.disabled
? item.click
: (ev) => ev.preventDefault()
const className = {
'dropdown-item': true,
disabled: item.disabled
}
return <a
href={item.href || '#'}
class={className}
{ ...{ on } }>
{ item.text }
</a>
},
_renderDivider(h) {
// return simple separator
return <div class="dropdown-divider"></div>
},
_renderTitle(h) {
// return h6 element
return <h6 class="dropdown-header">
{ this.title }
</h6>
},
_generateListener() {
return ({target}) => {
!findParent(this.$el, target) && this.toggle()
}
},
toggle() {
// visible became not visible
this.visible = !this.visible;
}
},
created() {
this.__body__ = this.$root.$el
this.$on('show', () => {
// ensure listener
if (!this.__ev_listener__) this.__ev_listener__ = this._generateListener()
// add event listener
setTimeout(() => {
this.__body__.addEventListener('click', this.__ev_listener__)
}, 100)
})
this.$on('hide', () => {
// ensure body
if (!(this.__body__ && this.__ev_listener__)) return
// remove event listener and delete __ev_listener__
this.__body__.removeEventListener('click', this.__ev_listener__)
delete this.__ev_listener__
})
},
destroyed() {
this.$off('show')
this.$off('hide')
},
render(h) {
const children = [];
// add title when present title
if (this.title) children.push(
this._renderTitle(h)
)
// for each element in options,
// create a link/button or a divider
for (let item of this.options) children.push(
item.divider
? this._renderDivider(h)
: this._renderLink(h, item)
)
// return the elment when visible
// otherwise return nothing
return <div
v-show={this.visible}
aria-label={this.id}
style={{ display: 'block' }}
class="dropdown-menu">
{ children }
</div>
},
watch: {
visible(val, oldVal) {
// when val is same as oldVal
// just exit the listener
if (val === oldVal) return;
// emit show or hide,
// depending on `$data.visible` new value
this.$emit(val
? 'show'
: 'hide'
)
}
},
// XXX: wait for a fix
events: {
show() {
// ensure body
if (!this.__body__) this.__body__ = this.$root.$el
// ensure listener
if (!this.__ev_listener__) this.__ev_listener__ = this._generateListener()
// add event listener
this.__body__.addEventLisener('click', this.__ev_listener__)
},
hide() {
// ensure body
if (!(this.__body__ && this.__ev_listener__)) return
// remove event listener and delete __ev_listener__
this.__body__.removeEventLisener('click', this.__ev_listener__)
delete this.__ev_listener__
}
}
}
|
var tests = [];
exports.test = function(code, ast, options, pluginOptions) {
tests.push({code, ast, options, pluginOptions});
};
exports.testFail = function(code, message, options, pluginOptions) {
tests.push({code, error: message, options, pluginOptions});
};
exports.testAssert = function(code, assert, options) {
tests.push({code, assert, options});
};
exports.runTests = function(config, callback) {
var parse = config.parse;
for (var i = 0; i < tests.length; ++i) {
var test = tests[i];
if (config.filter && !config.filter(test)) continue;
try {
var testOpts = Object.assign({ecmaVersion: 11}, test.options || {locations: true});
var expected = {};
if (expected.onComment = testOpts.onComment) {
testOpts.onComment = []
}
if (expected.onToken = testOpts.onToken) {
testOpts.onToken = [];
}
var ast = parse(test.code, testOpts, test.pluginOptions);
if (test.error) {
if (config.loose) {
callback("ok", test.code);
} else {
callback("fail", test.code, "Expected error message: " + test.error + "\nBut parsing succeeded.");
}
}
else if (test.assert) {
var error = test.assert(ast);
if (error) callback("fail", test.code,
"\n Assertion failed:\n " + error);
else callback("ok", test.code);
} else {
var mis = misMatch(test.ast, ast);
for (var name in expected) {
if (mis) break;
if (expected[name]) {
mis = misMatch(expected[name], testOpts[name]);
testOpts[name] = expected[name];
}
}
if (mis) callback("fail", test.code, mis);
else callback("ok", test.code);
}
} catch(e) {
if (!(e instanceof SyntaxError)) {
throw e;
}
if (test.error) {
if (e.message == test.error) callback("ok", test.code);
else callback("fail", test.code,
"Expected error message: " + test.error + "\nGot error message: " + e.message);
} else {
callback("error", test.code, e.stack || e.toString());
}
}
}
};
function ppJSON(v) { return v instanceof RegExp ? v.toString() : JSON.stringify(v, null, 2); }
function addPath(str, pt) {
if (str.charAt(str.length-1) == ")")
return str.slice(0, str.length-1) + "/" + pt + ")";
return str + " (" + pt + ")";
}
var misMatch = exports.misMatch = function(exp, act) {
if (!exp || !act || (typeof exp != "object") || (typeof act != "object")) {
if (exp !== act) return ppJSON(exp) + " !== " + ppJSON(act);
} else if (exp instanceof RegExp || act instanceof RegExp) {
var left = ppJSON(exp), right = ppJSON(act);
if (left !== right) return left + " !== " + right;
} else if (exp.splice) {
if (!act.slice) return ppJSON(exp) + " != " + ppJSON(act);
if (act.length != exp.length) return "array length mismatch " + exp.length + " != " + act.length;
for (var i = 0; i < act.length; ++i) {
var mis = misMatch(exp[i], act[i]);
if (mis) return addPath(mis, i);
}
} else {
for (var prop in exp) {
var mis = misMatch(exp[prop], act[prop]);
if (mis) return addPath(mis, prop);
}
}
};
function mangle(ast) {
if (typeof ast != "object" || !ast) return;
if (ast.slice) {
for (var i = 0; i < ast.length; ++i) mangle(ast[i]);
} else {
var loc = ast.start && ast.end && {start: ast.start, end: ast.end};
if (loc) { delete ast.start; delete ast.end; }
for (var name in ast) if (ast.hasOwnProperty(name)) mangle(ast[name]);
if (loc) ast.loc = loc;
}
}
|
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var particle={x:-50, y:-50, v:0, d:0};
canvas.width = canvas.parentElement.offsetWidth;
canvas.height = canvas.parentElement.offsetHeight;
var centre = {x: canvas.width/2, y: canvas.height/2};
function isRFromCentre(x, y, r){
return Math.sqrt( (centre.x - x)*(centre.x -x) + (centre.y - y)*(centre.y - y) ) < r;
}
var cols = ["rgba(180,180,255,0.7)", "rgba(160,160,255,0.8)", "rgba(170,170,250,0.7)"]
var colSwitch = 0;
var strokeCount = 0;
function draw(){
if(!isRFromCentre(particle.x, particle.y, 160)){
strokeCount++;
if(strokeCount > 50){
strokeCount = 0;
colSwitch = (colSwitch + 1)%cols.length;
}
particle.x = centre.x + 200 * Math.random() - 100;
particle.y = centre.y + 200 * Math.random() - 100;
particle.v = 10 + 5 * Math.random();
particle.d = 2 * Math.PI * Math.random();
}
ctx.beginPath();
particle.x += particle.v * Math.sin(particle.d);
particle.y += particle.v * Math.cos(particle.d);
ctx.fillStyle=cols[colSwitch];
ctx.arc(particle.x, particle.y, 8 + 2 * Math.random(), 0, 2*Math.PI);
ctx.fill();
window.requestAnimationFrame(draw);
}
draw(); |
import EmberRouter from '@ember/routing/router';
import config from './config/environment';
const Router = EmberRouter.extend({
location: config.locationType,
rootURL: config.rootURL
});
Router.map(function() {
this.route('people', function() {
this.route('show', { path: ":person_id" });
})
});
export default Router;
|
// Copyright IBM Corp. 2015. All Rights Reserved.
// Node module: strong-arc-filesystem
// US Government Users Restricted Rights - Use, duplication or disclosure
// restricted by GSA ADP Schedule Contract with IBM Corp.
module.exports = function mountLoopBackExplorer(server) {
var explorer;
try {
explorer = require('loopback-explorer');
} catch (err) {
// Print the message only when the app was started via `server.listen()`.
// Do not print any message when the project is used as a component.
server.once('started', function(baseUrl) {
console.log(
'Run `npm install loopback-explorer` to enable the LoopBack explorer'
);
});
return;
}
var restApiRoot = server.get('restApiRoot');
var explorerApp = explorer(server, {basePath: restApiRoot});
server.use('/explorer', explorerApp);
server.once('started', function() {
var baseUrl = server.get('url').replace(/\/$/, '');
// express 4.x (loopback 2.x) uses `mountpath`
// express 3.x (loopback 1.x) uses `route`
var explorerPath = explorerApp.mountpath || explorerApp.route;
console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
});
};
|
import { entity, ignore, id, rules } from 'walas';
import { required, period, length } from 'rules';
@rules([period, start, end])
@entity
export class Task {
@id
id;
@rules(required, [length, 50])
name;
@rules(required)
start;
@rules(required)
end;
@ignore
timestamp;
}
|
const renderer = require('./renderer');
class Tree {
/**
* @param {Object} tree PostHTML tree
* @see https://github.com/posthtml/posthtml/blob/master/docs/tree.md#json
*/
constructor(tree) {
this.tree = tree;
}
toString() {
return renderer(this.tree, this.tree.options);
}
}
module.exports = Tree; |
module.exports = { prefix: 'far', iconName: 'desktop-alt', icon: [576, 512, [], "f390", "M528 0H48C21.5 0 0 21.5 0 48v288c0 26.5 21.5 48 48 48h480c26.5 0 48-21.5 48-48V48c0-26.5-21.5-48-48-48zM48 54c0-3.3 2.7-6 6-6h468c3.3 0 6 2.7 6 6v234H48V54zm432 434c0 13.3-10.7 24-24 24H120c-13.3 0-24-10.7-24-24s10.7-24 24-24h98.7l18.6-55.8c1.6-4.9 6.2-8.2 11.4-8.2h78.7c5.2 0 9.8 3.3 11.4 8.2l18.6 55.8H456c13.3 0 24 10.7 24 24z"] }; |
/**
* Created by sheldon on 2016/5/18.
*/
var mongoose = require('mongoose');
var AgentSchema = require('../schemas/agent');
var Agent = mongoose.model('Agent',AgentSchema);
module.exports = Agent;
|
/**
* @fileoverview Externs for createjs
* @externs
*/
/**
* @constructor
*/
createjs.EventDispatcher = function() {};
/**
* @param {string} type
* @param {Function|Object} listener
* @param {boolean=} useCapture
* @return {Function|Object}
*/
createjs.EventDispatcher.prototype.addEventListener = function(type, listener, useCapture) {};
/**
* @param {Object|string|createjs.Event} eventObj
* @param {boolean=} bubbles
* @param {boolean=} cancelable
* @return {boolean}
*/
createjs.EventDispatcher.prototype.dispatchEvent = function(eventObj, bubbles, cancelable) {};
/**
* @param {string} type
* @return {boolean}
*/
createjs.EventDispatcher.prototype.hasEventListener = function(type) {};
/**
* @param {string} type
* @return {boolean}
*/
createjs.EventDispatcher.prototype.willTrigger = function(type) {};
/**
* @param {Object} target
*/
createjs.EventDispatcher.initialize = function(target) {};
/**
* @param {string} type
* @param {Function|Object} listener
* @param {boolean=} useCapture
*/
createjs.EventDispatcher.prototype.off = function(type, listener, useCapture) {};
/**
* @param {string} type
* @param {Function|Object} listener
* @param {Object=} scope
* @param {boolean=} once
* @param {*=} data
* @param {boolean=} useCapture
* @return {Function}
*/
createjs.EventDispatcher.prototype.on = function(type, listener, scope, once, data, useCapture) {};
/**
* @param {string=} type
*/
createjs.EventDispatcher.prototype.removeAllEventListeners = function(type) {};
/**
* @param {string} type
* @param {Function|Object} listener
* @param {boolean=} useCapture
*/
createjs.EventDispatcher.prototype.removeEventListener = function(type, listener, useCapture) {};
/**
* @return {string}
*/
createjs.EventDispatcher.prototype.toString = function() {}; |
// All symbols in the `Limbu` script as per Unicode v5.0.0:
[
'\u1900',
'\u1901',
'\u1902',
'\u1903',
'\u1904',
'\u1905',
'\u1906',
'\u1907',
'\u1908',
'\u1909',
'\u190A',
'\u190B',
'\u190C',
'\u190D',
'\u190E',
'\u190F',
'\u1910',
'\u1911',
'\u1912',
'\u1913',
'\u1914',
'\u1915',
'\u1916',
'\u1917',
'\u1918',
'\u1919',
'\u191A',
'\u191B',
'\u191C',
'\u1920',
'\u1921',
'\u1922',
'\u1923',
'\u1924',
'\u1925',
'\u1926',
'\u1927',
'\u1928',
'\u1929',
'\u192A',
'\u192B',
'\u1930',
'\u1931',
'\u1932',
'\u1933',
'\u1934',
'\u1935',
'\u1936',
'\u1937',
'\u1938',
'\u1939',
'\u193A',
'\u193B',
'\u1940',
'\u1944',
'\u1945',
'\u1946',
'\u1947',
'\u1948',
'\u1949',
'\u194A',
'\u194B',
'\u194C',
'\u194D',
'\u194E',
'\u194F'
]; |
import Ember from 'ember';
export default Ember.Component.extend({
classNames: ["admin-nav-item", "collection-item"]
});
|
// Convert html into markdown
//
'use strict';
/* eslint-disable-next-line no-redeclare */
const $ = require('nodeca.core/lib/parser/cheequery');
class MarkdownWriter {
constructor() {
this.tag_handlers = {};
Object.assign(this.tag_handlers, {
a: this.tag_handler_anchor,
blockquote: this.tag_handler_blockquote,
br: this.tag_handler_line_break,
code: this.tag_handler_code,
div: this.tag_handler_paragraph,
em: this.tag_handler_em,
h1: this.tag_handler_heading,
h2: this.tag_handler_heading,
h3: this.tag_handler_heading,
h4: this.tag_handler_heading,
h5: this.tag_handler_heading,
h6: this.tag_handler_heading,
hr: this.tag_handler_hr,
img: this.tag_handler_img,
li: this.tag_handler_list_item,
ol: this.tag_handler_paragraph,
p: this.tag_handler_paragraph,
pre: this.tag_handler_pre,
s: this.tag_handler_del,
strong: this.tag_handler_strong,
sub: this.tag_handler_sub,
sup: this.tag_handler_sup,
td: this.tag_handler_td,
tr: this.tag_handler_tr,
ul: this.tag_handler_paragraph
});
}
tag_handler_del(el) { return this.format_pair('~~', this.contents(el)); }
tag_handler_em(el) { return this.format_pair('_', this.contents(el)); }
tag_handler_hr() { return this.format_block('---'); }
tag_handler_line_break() { return '\\\n'; }
tag_handler_strong(el) { return this.format_pair('__', this.contents(el)); }
tag_handler_sub(el) { return this.format_pair('~', this.contents(el)); }
tag_handler_sup(el) { return this.format_pair('^', this.contents(el)); }
tag_handler_default(el) { return this.contents(el); }
tag_handler_code(el) { return this.format_code($(el).text()); }
tag_handler_tr(el) { return this.contents(el) + '\n'; }
tag_handler_td(el) { return '| ' + this.contents(el) + ' '; }
tag_handler_heading(el) {
return this.format_block('#'.repeat(el.tagName[1]) + ' ' + this.contents(el).replace(/#/g, '\\#'));
}
tag_handler_blockquote(el) {
let contents = this.contents(el);
return this.format_quote(
contents.startsWith('\n\n') ? contents.slice(2) : this.escape_block(contents),
$(el).attr('cite')
);
}
tag_handler_list_item(el) {
let contents = this.contents(el);
contents = contents.startsWith('\n\n') ? contents.slice(2) : this.escape_block(contents);
return this.format_block(contents.replace(/^(?!$)/mg, ' ').replace(/^ /, ' - '));
}
tag_handler_paragraph(el) {
let contents = this.contents(el);
return contents.startsWith('\n\n') ? contents : this.format_block(this.escape_block(contents));
}
tag_handler_anchor(el) {
let $el = $(el);
if ($el.find('a').length) return this.tag_handler_default(el);
let dest = $el.attr('href') || '';
let title = $el.attr('title') || '';
if ($el.children().length === 0 && $el.text() === dest && dest && !title) {
if (/^https?:\/\/(?!-)([a-z0-9-]|[a-z0-9]\.[a-z0-9])+(?=[\/?]|$)(?:[a-z0-9]|[\/\-&=?](?:[a-z0-9]|$))*$/i
.test(dest)) return this.format_linkify(dest);
if (/^[a-z][a-z0-9+.\-]{1,31}:/.test(dest)) return this.format_autolink(dest);
return this.format_link(dest, dest);
}
return this.format_link(this.contents(el), dest, title);
}
tag_handler_img(el) {
let $el = $(el);
let text = $el.attr('alt') || '';
let dest = $el.attr('src') || '';
let title = $el.attr('title') || '';
return this.format_image(text, dest, title);
}
tag_handler_pre(el) {
let language = ($(el).attr('class') || '').split(/\s+/)
.map(x => x.match(/^language-(.*)$/)).filter(Boolean).map(x => x[1])[0];
return this.format_fence($(el).text(), language);
}
format_pair(markers, text) {
if (!text) return ''; // empty tags can't be represented in markdown
return `${markers}${text}${markers}`;
}
format_linkify(dest) {
return dest;
}
format_autolink(dest) {
// eslint-disable-next-line no-control-regex
return '<' + dest.replace(/[<>\x00-\x20\x7f]/g, encodeURI) + '>';
}
format_link(text, dest, title = '') {
dest = dest.replace(/[\r\n]/g, encodeURI);
if (!dest && !title) {
// nothing to do, return []()
// eslint-disable-next-line no-control-regex
} else if (!dest || /[<>\s()\x00-\x1f\x7f]/.test(dest)) {
dest = '<' + dest.replace(/([\\<>])/g, '\\$1') + '>';
} else {
dest = dest.replace(/\\/g, '\\\\');
}
title = title.replace(/[\r\n]+/g, '\n').replace(/"/g, '\\"');
return `[${text}](${dest}${title ? ` "${title}"` : ''})`;
}
format_image(text, dest, title) {
return '!' + this.format_link(this.escape_inline(text), dest, title);
}
format_quote(text, cite) {
return this.format_block((cite ? `${cite}\n` : '') + text.replace(/^(>*) ?/mg, '>$1 ')).replace(/^(>+) $/mg, '$1');
}
format_code(text) {
// collapse newlines
text = text.replace(/(\r\n|\r|\n)+/g, ' ');
// calculate minimum backtick length for `code`, so it would encapsulate
// original content (longest backtick sequence plus 1)
let backtick_sequences = new Set(((text).match(/`+/g) ?? [ '' ]).map(s => s.length)); //`
let backtick_seq_len = 1;
while (backtick_sequences.has(backtick_seq_len)) backtick_seq_len++;
if (/^`|`$/.test(text)) text = ` ${text} `;
let markers = '`'.repeat(backtick_seq_len);
return this.format_pair(markers, text);
}
// make "```type params" block (code or quote)
//
format_fence(text, infostring = '') {
// calculate minimum backtick length for ````quote, so it would encapsulate
// original content (longest backtick sequence plus 1, but at least 3)
let backtick_seq_len = Math.max.apply(
null,
('`` ' + text)
.match(/`+/g) //`
.map(s => s.length)
) + 1;
let markers = '`'.repeat(backtick_seq_len);
// can represent "`" infostring with ~~~ markers, but we don't support it yet
infostring = String(infostring).replace(/[\r\n`]/g, ''); //`
return this.format_block(`
${markers}${infostring}
${text.replace(/\n$/, '')}
${markers}
`.replace(/^\n|\n$/g, ''));
}
format_block(md) {
return md.startsWith('\n\n') ? md : ('\n\n' + md);
}
// Concatenate many markdown texts into a single document
//
// This method is required because we can't safely concatenate two markdown parts
// (e.g. `*abc**def*` isn't the same as `*abc*` + `*def*`).
//
// Texts starting with '\n\n' are considered block tags, the rest are inline.
//
concat(texts) {
let blocks = [];
let inlines = [];
for (let text of texts) {
if (!text.startsWith('\n\n')) {
inlines.push(text);
continue;
}
if (inlines.length) {
blocks.push(this.format_block(this.escape_block(this.concat_inline(inlines))));
inlines = [];
}
blocks.push(text);
}
if (inlines.length) {
// all inline tags, join into single inline tag
if (!blocks.length) return this.concat_inline(inlines);
blocks.push(this.format_block(this.escape_block(this.concat_inline(inlines))));
}
return blocks.filter(block => block.match(/\S/)).join('');
}
concat_inline(texts) {
// This is not implemented (needs object tokens instead of strings):
// `_em_` + `_em_` == `_em_ _em_`
// `foo` + `http://` == `foo http://`
// `http://google.com` + `foo` == `http://google.com foo`
return texts.join('');
}
contents(el) {
if (!el) return '';
let texts = [];
el.childNodes.forEach(child => {
texts.push(this._write_node(child));
});
return this.concat(texts);
}
// Convert any node with ELEMENT_NODE type to markdown
//
_write_element_node(el) {
let tag = el.tagName.toLowerCase();
if (Object.prototype.hasOwnProperty.call(this.tag_handlers, tag)) {
return this.tag_handlers[tag].call(this, el);
}
return this.tag_handler_default(el);
}
// Convert any node to markdown
//
_write_node(node) {
if (!node) return '';
switch (node.nodeType) {
case 1 /* Node.ELEMENT_NODE */:
return this._write_element_node(node);
case 3 /* Node.TEXT_NODE */:
return this.escape_inline(node.data.replace(/\s+/g, ' '));
default:
return '';
}
}
// Convert any DOM Node or Cheerio Node to markdown
//
// Input:
// - node: Node - either DOM Node or Cheerio Node
//
convert(node) {
let result = this._write_node(node);
if (!result.startsWith('\n\n')) result = this.escape_block(result);
return result.replace(/^\n+|\n+$/g, '') + '\n';
}
escape_inline(text = '') {
// * - emphasis
// _ - emphasis
// ~ - strikethrough, sub, fence
// ^ - sup
// ++ - ins
// -- - heading
// == - mark, heading
// ` - code, fence
// [] - links
// \ - escape
return String(text)
.replace(/([*_~^`\\\[\]])/g, '\\$1') //`
.replace(/(:(?!\s))/ig, '\\$1') // emoji
.replace(/(<(?!\s))/ig, '\\$1') // autolinks
.replace(/(?:\r\n|\r|\n)/g, '\\\n') // newlines
.replace(/(\+{2,}|\={2,})/g, m => Array.from(m).map(x => `\\${x}`).join(''))
.replace(/(&([a-z0-9]+|#[0-9]+|#x[0-9a-f]+);)/ig, '\\$1'); // entities
}
escape_block(text = '') {
return String(text)
.replace(/^\s+|\s+$/mg, '') // remove leading and trailing spaces
.replace(/^(#+\s)/mg, '\\$1') // atx headings
.replace(/^((?!\s)([*\s]+|[-\s]+|[_\s+]))$/mg, '\\$1') // hr
.replace(/^([-+*]\s)/mg, '\\$1') // lists
.replace(/^(\d+)(\.)/mg, '$1\\$2') // ordered lists
.replace(/^(>)/mg, '\\$1'); // blockquote
}
}
class NodecaMarkdownWriter extends MarkdownWriter {
constructor() {
super();
Object.assign(this.tag_handlers, {
span: this.tag_handler_span
});
}
_write_element_node(el) {
let $el = $(el);
if ($el.data('nd-link-orig')) return this.nd_link_handler(el);
if ($el.data('nd-image-orig')) return this.nd_image_handler(el);
return super._write_element_node(el);
}
nd_link_handler(el) {
let $el = $(el);
let orig = $el.data('nd-link-orig');
let type = $el.data('nd-link-type');
let result;
if (type === 'linkify') {
result = this.format_linkify(orig) ??
this.format_link(orig, orig);
} else if (type === 'autolink') {
result = this.format_autolink(orig) ??
this.format_link(orig, orig);
} else {
result = this.format_link(this.contents(el), orig, $el.attr('title') || '');
}
let tag = el.tagName.toLowerCase();
if (tag === 'div' || tag === 'blockquote') result = this.format_block(this.escape_block(result));
return result;
}
nd_image_handler(el) {
let $el = $(el);
let $img = el.tagName.toLowerCase() === 'img' ? $el : $el.children('img');
let orig = $el.data('nd-image-orig');
let size = $el.data('nd-image-size') || 'sm';
let alt = $img.attr('alt') || '';
let title = $img.attr('title') || '';
let desc = [ alt, size === 'sm' ? '' : size ].filter(Boolean).join('|');
return this.format_image(desc, orig, title);
}
// `<em data-nd-pair-src="*">abc</em>` -> `*abc*`
tag_handler_em(el) {
let markers = $(el).data('nd-pair-src');
if (markers) return this.format_pair(markers, this.contents(el));
return super.tag_handler_em(el);
}
// `<strong data-nd-pair-src="**">abc</strong>` -> `**abc**`
tag_handler_strong(el) {
let markers = $(el).data('nd-pair-src');
if (markers) return this.format_pair(markers, this.contents(el));
return super.tag_handler_strong(el);
}
// `<hr data-nd-hr-src="*****">` -> `*****`
tag_handler_hr(el) {
let src = $(el).data('nd-hr-src');
if (src) return this.format_block(src);
return super.tag_handler_hr(el);
}
// `<span class="emoji emoji-xxx" data-nd-emoji-src=":xxx:"></span>` -> `:xxx:`
tag_handler_span(el) {
let src = $(el).data('nd-emoji-src');
if (src) return src;
return this.tag_handler_default(el);
}
tag_handler_blockquote(el) {
if (!$(el).hasClass('quote')) return super.tag_handler_blockquote(el);
let contents = this.contents($(el).children('.quote__content')[0]);
return this.format_quote(
contents.startsWith('\n\n') ? contents.slice(2) : this.escape_block(contents),
$(el).attr('cite')
);
}
format_quote(text, cite) {
return this.format_fence(text, 'quote' + (cite ? ` ${cite}` : ''));
}
}
module.exports = {
MarkdownWriter,
NodecaMarkdownWriter
};
|
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* globals PDFJS, expect, it, describe, Promise, combineUrl, waitsFor, runs */
'use strict';
describe('api', function() {
// TODO run with worker enabled
var basicApiUrl = combineUrl(window.location.href, '../pdfs/basicapi.pdf');
function waitsForPromise(promise, successCallback) {
var data;
promise.then(function(val) {
data = val;
successCallback(data);
},
function(error) {
// Shouldn't get here.
expect(false).toEqual(true);
});
waitsFor(function() {
return data !== undefined;
}, 20000);
}
describe('PDFJS', function() {
describe('getDocument', function() {
it('creates pdf doc from URL', function() {
var promise = PDFJS.getDocument(basicApiUrl);
waitsForPromise(promise, function(data) {
expect(true).toEqual(true);
});
});
/*
it('creates pdf doc from typed array', function() {
// TODO
});
*/
});
});
describe('PDFDocument', function() {
var promise = PDFJS.getDocument(basicApiUrl);
var doc;
waitsForPromise(promise, function(data) {
doc = data;
});
it('gets number of pages', function() {
expect(doc.numPages).toEqual(3);
});
it('gets fingerprint', function() {
expect(typeof doc.fingerprint).toEqual('string');
});
it('gets page', function() {
var promise = doc.getPage(1);
waitsForPromise(promise, function(data) {
expect(true).toEqual(true);
});
});
it('gets destinations', function() {
var promise = doc.getDestinations();
waitsForPromise(promise, function(data) {
// TODO this seems to be broken for the test pdf
});
});
it('gets outline', function() {
var promise = doc.getOutline();
waitsForPromise(promise, function(outline) {
// Two top level entries.
expect(outline.length).toEqual(2);
// Make sure some basic attributes are set.
expect(outline[1].title).toEqual('Chapter 1');
expect(outline[1].items.length).toEqual(1);
expect(outline[1].items[0].title).toEqual('Paragraph 1.1');
});
});
it('gets metadata', function() {
var promise = doc.getMetadata();
waitsForPromise(promise, function(metadata) {
expect(metadata.info['Title']).toEqual('Basic API Test');
expect(metadata.metadata.get('dc:title')).toEqual('Basic API Test');
});
});
});
describe('Page', function() {
var resolvePromise;
var promise = new Promise(function (resolve) {
resolvePromise = resolve;
});
PDFJS.getDocument(basicApiUrl).then(function(doc) {
doc.getPage(1).then(function(data) {
resolvePromise(data);
});
});
var page;
waitsForPromise(promise, function(data) {
page = data;
});
it('gets ref', function() {
expect(page.ref).toEqual({num: 15, gen: 0});
});
// TODO rotate
// TODO viewport
// TODO annotaions
// TOOD text content
// TODO operation list
});
});
|
angular.module('app')
.config(() => (
firebase.initializeApp({
apiKey: "AIzaSyCptyoC-x5hm4Ut5Nu2a_CqHdCkH21A458",
authDomain: "flavorize-front-end-capstone.firebaseapp.com",
databaseURL: "https://flavorize-front-end-capstone.firebaseio.com",
storageBucket: "flavorize-front-end-capstone.appspot.com",
})));
|
// @flow
const ClauseActionTypes = {
// add/edit UI
ON_CLICK_ADD_CLAUSE: 'ON_CLICK_ADD_CLAUSE',
ON_CLICK_CANCEL: 'ON_CLICK_CANCEL',
ON_CLICK_DELETE_CLAUSE: 'ON_CLICK_DELETE_CLAUSE',
ON_CLICK_EDIT_CLAUSE: 'ON_CLICK_EDIT_CLAUSE',
ON_CLICK_SAVE_CLAUSE: 'ON_CLICK_SAVE_CLAUSE',
ON_CHANGE_SELECTED_NP: 'ON_CHANGE_SELECTED_NP',
ON_CHANGE_SELECTED_VP: 'ON_CHANGE_SELECTED_VP',
// Pump a new Clause directly into the db w/o dealing with any UI.
INSERT_CLAUSE: 'INSERT_CLAUSE'
}
export default ClauseActionTypes
|
'use strict';
var Immutable = require('immutable');
Immutable.Iterable.noLengthWarning = true;
module.exports = {
topics: new Immutable.List(),
title: 'Word Cloud',
width: 800,
height: 300,
fontSizes: [12, 16, 20, 24, 30, 40],
random: false,
initialHighlight: true
};
|
'use strict';
/**
* A callback function that fires after the left arrow is clicked
* @callback CarouselArrows~onLeftArrowClick
*/
/**
* A callback function that fires after the right arrow is clicked
* @callback CarouselArrows~onRightArrowClick
*/
/**
* Adds functionality for carousel's left and right arrows.
* @constructor CarouselArrows
*/
export default class CarouselArrows {
/**
* When the carousel is instantiated.
* @param {object} options - Options passed into instance
* @param {HTMLElement} options.leftArrow - The html element to use as the left arrow
* @param {HTMLElement} options.rightArrow - The html element to use as the right arrow
* @param {HTMLCollection} options.panels - The carousel panel elements that to be associated with the arrows
* @param {string} [options.arrowDisabledClass] - The CSS class that gets added to an arrow when it becomes disabled
* @param {CarouselArrows~onLeftArrowClick} [options.onLeftArrowClick] - When the left arrow is clicked
* @param {CarouselArrows~onRightArrowClick} [options.onRightArrowClick] - When the right arrow is clicked
*/
constructor (options) {
options = Object.assign({
leftArrow: null,
rightArrow: null,
panels: [],
arrowDisabledClass: 'carousel-arrow-disabled',
onLeftArrowClick: null,
onRightArrowClick: null,
initialIndex: 0
}, options);
if (!options.leftArrow && !options.rightArrow) {
console.error('Carousel Arrows Error: no left and right arrows were passed into constructor');
}
this.options = options;
this.arrows = [];
// setup listeners
if (options.leftArrow) {
this.arrows.push(options.leftArrow);
this._leftArrowEventListener = e => this.onLeftArrowClick(e);
options.leftArrow.addEventListener('click', this._leftArrowEventListener);
}
if (options.rightArrow) {
this.arrows.push(options.rightArrow);
this._rightArrowEventListener = e => this.onRightArrowClick(e);
options.rightArrow.addEventListener('click', this._rightArrowEventListener);
}
}
/**
* Updates the arrow based on the supplied panel index.
* @param {Number} panelIndex - The new panel index
*/
update (panelIndex) {
var currentItemNum = panelIndex + 1,
maxItems = this.options.panels.length,
minItems = 1;
if (currentItemNum < maxItems && currentItemNum > minItems) {
// not on first or last item
this.enable();
} else if (currentItemNum === maxItems && currentItemNum === minItems) {
// on the only panel available
this.disable();
} else if (currentItemNum === maxItems) {
// on last item
this.disableRightArrow();
this.enableLeftArrow();
} else if (currentItemNum === minItems) {
// on first item
this.disableLeftArrow();
this.enableRightArrow();
}
}
/**
* Disables all arrows
*/
disable () {
this.disableLeftArrow();
this.disableRightArrow();
}
/**
* Disables left arrow.
*/
disableLeftArrow () {
if (this.options.leftArrow) {
this.options.leftArrow.classList.add(this.options.arrowDisabledClass);
}
}
/**
* Disables right arrow.
*/
disableRightArrow () {
if (this.options.rightArrow) {
this.options.rightArrow.classList.add(this.options.arrowDisabledClass);
}
}
/**
* Re-enables all arrows.
*/
enable () {
this.enableLeftArrow();
this.enableRightArrow();
}
/**
* Re-enables left arrow.
*/
enableLeftArrow () {
if (this.options.leftArrow) {
this.options.leftArrow.classList.remove(this.options.arrowDisabledClass);
}
}
/**
* Re-enables right arrow.
*/
enableRightArrow () {
if (this.options.rightArrow) {
this.options.rightArrow.classList.remove(this.options.arrowDisabledClass);
}
}
/**
* When the left arrow is clicked.
* @param {Event} e
*/
onLeftArrowClick (e) {
var isDisabled = this.options.leftArrow.classList.contains(this.options.arrowDisabledClass);
if (this.options.onLeftArrowClick && !isDisabled) {
this.options.onLeftArrowClick(e);
}
}
/**
* When the right arrow is clicked.
* @param {Event} e
*/
onRightArrowClick (e) {
var isDisabled = this.options.rightArrow.classList.contains(this.options.arrowDisabledClass);
if (this.options.onRightArrowClick && !isDisabled) {
this.options.onRightArrowClick(e);
}
}
/**
* Final cleanup of instance.
* @memberOf CarouselArrows
*/
destroy () {
if (this.options.leftArrow) {
this.options.leftArrow.removeEventListener('click', this._leftArrowEventListener);
}
if (this.options.rightArrow) {
this.options.rightArrow.removeEventListener('click', this._rightArrowEventListener);
}
}
}
|
/*
*
* Wijmo Library 0.6.1
* http://wijmo.com/
*
* Copyright(c) ComponentOne, LLC. All rights reserved.
*
* Dual licensed under the MIT or GPL Version 2 licenses.
* licensing@wijmo.com
* http://www.wijmo.com/license
*
* * Wijmo Popup widget.
*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.ui.wijpopup.js
*
*/
(function ($) {
$.fn.extend({
getBounds: function () {
return $.extend({}, $(this).offset(), { width: $(this).outerWidth(true), height: $(this).outerHeight(true) });
},
setBounds: function (bounds) {
$(this).css({'left': bounds.left, 'top': bounds.top})
.width(bounds.width)
.height(bounds.height);
return this;
},
getMaxZIndex: function () {
var max = (($(this).css('z-index') == 'auto') ? 0 : $(this).css('z-index')) * 1;
$(this).siblings().each(function (i, e) {
max = Math.max(max, (($(e).css('z-index') == 'auto') ? 0 : $(e).css('z-index')) * 1);
});
return max;
}
});
$.widget("ui.wijpopup", {
options: {
/// <summary>
/// Determines if the element's parent element is the outermost element.
/// If true, the element's parent element will be changed to the body or outermost form element.
/// </summary>
ensureOutermost: false,
/// <summary>
/// Specifies the effect to be used when the popup is shown.
/// Possible values: 'blind', 'clip', 'drop', 'fade', 'fold', 'slide', 'pulsate'.
/// </summary>
showEffect: 'show',
/// <summary>
/// Specified the object/hash including specific options for the show effect.
/// </summary>
showOptions: {},
/// <summary>
/// Defines how long (in milliseconds) the animation duration for showing the popup will last.
/// </summary>
showDuration: 300,
/// <summary>
/// Specifies the effect to be used when the popup is hidden.
/// Possible values: 'blind', 'clip', 'drop', 'fade', 'fold', 'slide', 'pulsate'.
/// </summary>
hideEffect: 'hide',
/// <summary>
/// Specified the object/hash including specific options for the hide effect.
/// </summary>
hideOptions: {},
/// <summary>
/// Defines how long (in milliseconds) the animation duration for hiding the popup will last.
/// </summary>
hideDuration: 100,
/// <summary>
/// Determines whether to automatically hide the popup when clicking outside the element.
/// </summary>
autoHide: false,
/// <summary>
/// Options for positioning the element, please see jquery.ui.position for possible options.
/// </summary>
position:{
at: 'left bottom',
my: 'left top'
}
},
_create: function () {
},
_init: function () {
if (!!this.options.ensureOutermost) {
var root = $('form');
if (root.length === 0) root = $(document.body);
this.element.appendTo(root);
}
this.element.data('visible.wijpopup', false);
this.element.css('position', "absolute");
this.element.position({
of: $(document.body)
});
this.element.hide();
},
_setOption: function (key, value) {
$.Widget.prototype._setOption.apply(this, arguments);
switch (key) {
case "autoHide":
var visible = this.isVisible();
this.hide();
if (visible) this.show();
break;
}
},
destroy: function () {
$.Widget.prototype.destroy.apply(this, arguments);
if (this.isVisible()) this.hide();
if ($.browser.msie && ($.browser.version < 7)) {
jFrame = this.element.data('backframe.wijpopup');
if (!jFrame) jFrame.remove();
}
var self = this;
this.element.unbind('.wijpopup');
$.each( [ "visible", "backframe", "animating", "width" ], function( i, prefix ) {
self.element.removeData( prefix + ".wijpopup" );
});
},
isVisible: function () {
/// <summary>Determines whether the element is visible.</summary>
return (!!this.element.data('visible.wijpopup') && this.element.is(':visible'));
},
isAnimating: function(){
return !!this.element.data("animating.wijpopup");
},
show: function (position) {
/// <summary>Popups the element. Position is an optional argument, it is the options object used in jquery.ui.position.</summary>
this._setPosition(position);
if (this.isVisible()) return;
var data = {cancel: false};
this._trigger('showing', data);
if (data.cancel) return;
if (this.options.autoHide) {
$(document.body).bind('mouseup.wijpopup', $.proxy(this._onDocMouseUp, this));
}
var effect = this.options.showEffect || "show";
var duration = this.options.showDuration || 300;
var ops = this.options.showOptions || {};
this.element.data("animating.wijpopup", true);
if ($.effects && $.effects[effect])
this.element.show(effect, ops, duration, $.proxy(this._showCompleted, this));
else
this.element[effect]((effect === 'show' ? null : duration), $.proxy(this._showCompleted, this));
if (!effect || !duration || effect === 'show' || duration <= 0)
this._showCompleted();
},
_showCompleted: function () {
this.element.removeData("animating.wijpopup");
this.element.data('visible.wijpopup', true);
this._trigger('shown');
},
showAt: function (x, y) {
/// <summary>Popups the element at specified absolute position related to document.</summary>
this.show({
my: 'left top',
at: 'left top',
of: document.body,
offset: '' + x + ' ' + y
});
},
hide: function () {
/// <summary>Hides the element.</summary>
if (!this.isVisible()) return;
var data = {cancel: false};
this._trigger('hidding', data);
if (data.cancel) return;
$(document.body).unbind('mouseup.wijpopup');
var effect = this.options.hideEffect || "hide";
var duration = this.options.hideDuration || 300;
var ops = this.options.hideOptions || {};
this.element.data("animating.wijpopup", true);
if ($.effects && $.effects[effect])
this.element.hide(effect, ops, duration, $.proxy(this._hideCompleted, this));
else
this.element[effect]((effect === 'hide' ? null : duration), $.proxy(this._hideCompleted, this));
if (!effect || !duration || effect === 'hide' || duration <= 0)
this._hideCompleted();
},
_hideCompleted: function () {
if (this.element.data('width.wijpopup') !== undefined) {
this.element.width(this.element.data('width.wijpopup'));
this.element.removeData('width.wijpopup');
}
this.element.unbind('move.wijpopup');
this.element.removeData("animating.wijpopup");
if ($.browser.msie && ($.browser.version < 7)) {
var jFrame = this.element.data('backframe.wijpopup');
if (jFrame) { jFrame.hide(); }
}
this._trigger('hidden');
},
_onDocMouseUp: function (e) {
var srcElement = e.target ? e.target : e.srcElement;
if (this.isVisible() && !!this.options.autoHide) {
if (srcElement != this.element.get(0) && $(srcElement).parents().index(this.element) < 0) this.hide();
}
},
_onMove: function (e) {
var jFrame = this.element.data('backframe.wijpopup');
if (jFrame) {
this.element.before(jFrame);
jFrame.css({'top': this.element.css('top'),
'left': this.element.css('left')
});
}
},
_addBackgroundIFrame: function () {
if ($.browser.msie && ($.browser.version < 7)) {
var jFrame = this.element.data('backframe.wijpopup');
if (!jFrame) {
jFrame = jQuery('<iframe/>')
.css({'position': 'absolute',
'display': 'none',
'filter': 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)'
}).attr({'src': 'javascript:\'<html></html>\';',
'scrolling': 'no',
'frameborder': '0',
'tabIndex ': -1
});
this.element.before(jFrame);
this.element.data('backframe.wijpopup', jFrame);
this.element.bind('move.wijpopup', $.proxy(this._onMove, this));
}
jFrame.setBounds(this.element.getBounds());
document.title = this.element.css('display');
jFrame.css({'display': 'block',
'left': this.element.css('left'),
'top': this.element.css('top'),
'z-index': this.element.css('z-index') - 1
});
}
},
_setZIndex: function (index) {
this.element.css('z-index', index);
var jFrame = this.element.data('backframe.wijpopup');
if (jFrame) {
jFrame.css('z-index', (this.element.css('z-index')) - 1);
}
},
_setPosition: function (position) {
var visible = this.element.is(':visible');
this.element.show();
this.element.position($.extend({}, this.options.position, position ? position : {}));
if (!visible) this.element.hide();
this._addBackgroundIFrame();
var zIndex = 1000;
if (this.options.position.of) {
zIndex = Math.max(zIndex, $(this.options.position.of).getMaxZIndex());
}
this._setZIndex(zIndex + 10);
this._trigger('posChanged');
}
});
})(jQuery); |
defineClass('Consoloid.OS.Process', 'Consoloid.Base.Object',
{
__constructor: function(options)
{
this.__base($.extend({
args: [],
spawnOptions: {},
readStdout: this.__defaultStdoutCallback.bind(this),
readStderr: this.__defaultStderrCallback.bind(this),
onClose: this.__defaultOnCloseCallback.bind(this),
onError: this.__defaultOnErrorCallback.bind(this),
killTimeOut: 5000,
outputBufferSize: 1048576
}, options));
this.requireProperty('command');
this.spawn = require('child_process').spawn;
this.childProcess = undefined;
this.isRunning = false;
this.stdout = '';
this.stderr = '';
},
__defaultStdoutCallback: function(data)
{
this.stdout += this.__getBufferToAppend(this.stdout.length, data);
this.get('logger').log('debug', 'Process stdout', {pid: this.childProcess.pid, out: data.toString() });
},
__getBufferToAppend: function(length, data)
{
if (length + data.length > this.outputBufferSize) {
data = data.slice(0, this.outputBufferSize - (length + data.length));
}
return data.toString();
},
__defaultStderrCallback: function(data)
{
this.stderr += this.__getBufferToAppend(this.stderr.length, data);
this.get('logger').log('debug', 'Process stderr', {pid: this.childProcess.pid, error: data.toString() });
},
__defaultOnCloseCallback: function(code)
{
this.get('logger').log('info', 'Process closed', {pid: this.childProcess.pid, code: code });
},
__defaultOnErrorCallback: function(error)
{
this.get('logger').log('error', 'Process error', {pid: this.childProcess.pid, error: error.message });
},
getStdout: function()
{
return this.stdout;
},
getStderr: function()
{
return this.stderr;
},
start: function()
{
if (this.isRunning) {
throw new Error('Process is already running, pid: ' + this.childProcess.pid);
}
this.childProcess = this.spawn(this.command, this.args, this.spawnOptions);
this.isRunning = true;
this.__bindEventCallbacks();
},
__bindEventCallbacks: function()
{
var $this = this;
this.childProcess.stdout.on('data', function (data) {
$this.readStdout(data);
});
this.childProcess.stderr.on('data', function (data) {
$this.readStderr(data);
});
this.childProcess.on('close', function (code) {
$this.isRunning = false;
$this.onClose(code);
});
this.childProcess.on('error', function (error) {
if (error.message == 'spawn ENOENT') {
$this.isRunning = false;
}
$this.onError(error);
});
},
writeStdin: function(data)
{
if (!this.isRunning) {
throw new Error('Cannot write stdin since process is not running.');
}
this.childProcess.stdin.write(data);
},
forceQuit: function()
{
this.kill('SIGTERM');
setTimeout(this.__sendKillSignal.bind(this), this.killTimeOut);
},
kill: function(signal)
{
if (!this.isRunning) {
throw new Error('Cannot kill process since it is not running.');
}
this.childProcess.kill(signal);
},
__sendKillSignal: function()
{
if (this.isRunning) {
this.kill('SIGKILL');
}
}
}
); |
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import loginComponent from './login.component';
let loginModule = angular.module('login', [
uiRouter
])
.config($stateProvider => {
'ngInject';
$stateProvider.state('login', {
url : '/login',
template : '<login></login>'
});
})
.component('login', loginComponent);
export default loginModule;
|
//os analyzer
//I use the redis server to publish the os status informations.
var net = require('net');
var path = require('path');
var log4js = require("log4js");
var cjson = require('cjson');
var config = cjson.load('./config/config.json');
var snmp = require('snmp-native');
var _ = require('underscore');
var util = require('util');
var async = require('async');
//
var logfile = path.join(__dirname, '/logs/snmp_analyzer.log');
var host = 'localhost';
var community = 'kesix';
log4js.addAppender(require('log4js/lib/appenders/file').appender(logfile), 'snmp_analyzer');
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file(logfile), 'os.analyzer');
var logger = log4js.getLogger('os.analyzer');
logger.setLevel(config.OS_ANALYZER_LOG_LEVEL);
var redis = require("redis");
var redisClient = redis.createClient(config.redis_port, config.redis_host);
/*var session2 = new snmp.Session({
host: host,
community: community
});
session2.getSubtree({
oid: oid
}, function(err, varbinds) {
if(err) {
console.log("session 2 " + err);
} else {
_.each(varbinds, function(vb) {
console.log('Name of interface ' + _.last(vb.oid) + ' is "' + vb.value + '"');
});
}
session2.close();
});*/
/*var oidAstStr = '.1.3.6.1.4.1.22736.1';
oidAst = _.map(_.compact(oidAstStr.split('.')), function (x) { return parseInt(x, 10); });
var session3= new snmp.Session({ host: host, community: community });
session3.getSubtree({ oid: oidAst }, function (err, varbinds) {
if (err) {
console.log(err);
} else {
_.each(varbinds, function (vb) {
console.log('Name of asterisk ' + _.last(vb.oid) + ' is "' + vb.value + '"');
});
}
session3.close();
});*/
function snmpSystemJob(){
var sysOids = [];
//.1.3.6.1.2.1.1.3.0
var oidSysUpTime = [1 ,3 ,6 ,1 ,2 ,1 ,1 ,3 ,0]; //[1 ,3 ,6 ,1 ,2 ,1 ,25 ,1,1,0]; //
var oidSysCPULoad5 = [1 , 3, 6 ,1 ,4 , 1, 2021,10 ,1 ,3 ,2];
var oidSysTotalRamInMachine=[1,3,6,1,4,1,2021,4,5,0];
var oidSysTotalRamUsed = [1,3,6,1,4,1,2021,4,6,0];
var oidSysTotalRamFree = [1,3,6,1,4,1,2021,4,11,0];
var oidSysTotalRamShared = [1,3,6,1,4,1,2021,4,13,0];
var oidSysTotalSwap= [1,3,6,1,4,1,2021,4,4,0];
//
var oidSysDiskTotalSize = [1,3,6,1,4,1,2021,9,1,6,1];
var oidSysDiskAvailableSize=[1,3,6,1,4,1,2021,9,1,7,1];
var oidSysDiskUsedSpace = [1,3,6,1,4,1,2021,9,1,8,1];
var oidSysDiskPercSpaceUsed = [1,3,6,1,4,1,2021,9,1,9,1];
//
sysOids.push(oidSysUpTime);
sysOids.push(oidSysCPULoad5);
//
sysOids.push(oidSysTotalRamInMachine);
sysOids.push(oidSysTotalRamUsed);
sysOids.push(oidSysTotalRamFree);
sysOids.push(oidSysTotalRamShared);
sysOids.push(oidSysTotalSwap);
//
sysOids.push(oidSysDiskTotalSize);
sysOids.push(oidSysDiskAvailableSize);
sysOids.push(oidSysDiskUsedSpace);
sysOids.push(oidSysDiskPercSpaceUsed);
//
var session = new snmp.Session({
host: host,
community: community
});
//
session.getAll({
oids: sysOids
}, function(err, varbinds) {
var msg = {id: 'info:system', upTime: '0', cpuLoad: '0',
totalRamInMachine: '0', totalRamUsed: '0', totalRamFree: '0', totalRamShared: '0',
totalSwap: '0', totalDiskSize: '0', totalDiskAvailableSize: '0', totalDiskUsedSpace: '0',
totalDiskPercSpaceUsed: '0'};
//
_.each(varbinds, function(vb) {
if(snmp.compareOids(vb.oid, oidSysUpTime) == 0) {
//logger.debug("ods system uptime " + vb.oid + ' = ' + vb.value);
msg.upTime = vb.value;
}else if(snmp.compareOids(vb.oid, oidSysCPULoad5) == 0) {
//logger.debug("ods system cpu load " + vb.oid + ' = ' + vb.value);
msg.cpuLoad = vb.value;
}else if(snmp.compareOids(vb.oid, oidSysTotalRamInMachine) == 0) {
msg.totalRamInMachine = vb.value * 1024;
}else if(snmp.compareOids(vb.oid, oidSysTotalRamUsed) == 0) {
msg.totalRamUsed = vb.value;
}else if(snmp.compareOids(vb.oid, oidSysTotalRamFree) == 0) {
msg.totalRamFree = vb.value * 1024;
}else if(snmp.compareOids(vb.oid, oidSysTotalRamShared) == 0) {
msg.totalRamShared = vb.value * 1024;
}else if(snmp.compareOids(vb.oid, oidSysTotalSwap) == 0) {
msg.totalSwap = vb.value * 1024;
}else if(snmp.compareOids(vb.oid, oidSysDiskTotalSize) == 0) {
msg.totalDiskSize = vb.value * 1024;
}else if(snmp.compareOids(vb.oid, oidSysDiskAvailableSize) == 0) {
msg.totalDiskAvailableSize = vb.value * 1024;
}else if(snmp.compareOids(vb.oid, oidSysDiskUsedSpace) == 0) {
msg.totalDiskUsedSpace = vb.value * 1024;
}else if(snmp.compareOids(vb.oid, oidSysDiskPercSpaceUsed) == 0) {
msg.totalDiskPercSpaceUsed = vb.value;
}else {
logger.debug("ods " + vb.oid + ' = ' + vb.value);
}
});
redisClient.publish( 'odin_snmp_channel', JSON.stringify(msg));
session.close();
});
//
}
function snmpAsteriskJob() {
//fetching asterisk infos
var asteriskOids = [];
var oidAstVersion = [1, 3, 6, 1, 4, 1, 22736, 1, 1, 1, 0];
var oidAstUpTime = [1, 3, 6, 1, 4, 1, 22736, 1, 2, 1, 0];
var oidAstReloadTime = [1, 3, 6, 1, 4, 1, 22736, 1, 2, 2, 0];
var oidAstChannelsInUse = [1, 3, 6, 1, 4, 1, 22736, 1, 5, 1, 0];
var oidAstConfigCallsActive = [1, 3, 6, 1, 4, 1, 22736, 1, 2, 5, 0];
var oidAstConfigCallsProcessed = [1, 3, 6, 1, 4, 1, 22736, 1, 2, 6, 0];
//
asteriskOids.push(oidAstVersion);
asteriskOids.push(oidAstUpTime);
asteriskOids.push(oidAstReloadTime);
asteriskOids.push(oidAstChannelsInUse);
asteriskOids.push(oidAstConfigCallsActive);
asteriskOids.push(oidAstConfigCallsProcessed);
var session = new snmp.Session({
host: host,
community: community
});
//fetch asterisk infos
session.getAll({
oids: asteriskOids
}, function(err, varbinds) {
var msg = {id: 'info:asterisk', version: '', upTime: '0', reloadTime: '0', channelsInUse: '0',
callsActive:'0', callsProcessed: '0'};
//
_.each(varbinds, function(vb) {
if(snmp.compareOids(vb.oid, oidAstVersion) == 0) {
msg.version = vb.value;
} else if(snmp.compareOids(vb.oid, oidAstUpTime) == 0) {
msg.upTime = vb.value;
} else if(snmp.compareOids(vb.oid, oidAstReloadTime) == 0) {
msg.reloadTime = vb.value;
} else if(snmp.compareOids(vb.oid, oidAstChannelsInUse) == 0) {
msg.channelsInUse = vb.value;
} else if(snmp.compareOids(vb.oid, oidAstConfigCallsActive) == 0){
msg.callsActive = vb.value;
}else if(snmp.compareOids(vb.oid, oidAstConfigCallsProcessed) == 0){
msg.callsProcessed = vb.value;
} else {
logger.debug("ods " + vb.oid + ' = ' + vb.value);
}
});
redisClient.publish( 'odin_snmp_channel', JSON.stringify(msg));
session.close();
});
}
function snmpPacemaker() {
//fetching asterisk infos
var pacemakerOids = [];
var oidCrmNode = [1, 3, 6, 1, 4, 1, 32723.1];
var oidCrmRsc = [1, 3, 6, 1, 4, 1, 32723.2];
//
asteriskOids.push(oidAstVersion);
asteriskOids.push(oidAstUpTime);
asteriskOids.push(oidAstReloadTime);
asteriskOids.push(oidAstChannelsInUse);
asteriskOids.push(oidAstConfigCallsActive);
asteriskOids.push(oidAstConfigCallsProcessed);
var session = new snmp.Session({
host: host,
community: community
});
//fetch asterisk infos
session.getAll({
oids: asteriskOids
}, function(err, varbinds) {
var msg = {id: 'info:asterisk', version: '', upTime: '0', reloadTime: '0', channelsInUse: '0',
callsActive:'0', callsProcessed: '0'};
//
_.each(varbinds, function(vb) {
if(snmp.compareOids(vb.oid, oidAstVersion) == 0) {
msg.version = vb.value;
} else if(snmp.compareOids(vb.oid, oidAstUpTime) == 0) {
msg.upTime = vb.value;
} else if(snmp.compareOids(vb.oid, oidAstReloadTime) == 0) {
msg.reloadTime = vb.value;
} else if(snmp.compareOids(vb.oid, oidAstChannelsInUse) == 0) {
msg.channelsInUse = vb.value;
} else if(snmp.compareOids(vb.oid, oidAstConfigCallsActive) == 0){
msg.callsActive = vb.value;
}else if(snmp.compareOids(vb.oid, oidAstConfigCallsProcessed) == 0){
msg.callsProcessed = vb.value;
} else {
logger.debug("ods " + vb.oid + ' = ' + vb.value);
}
});
redisClient.publish( 'odin_snmp_channel', JSON.stringify(msg));
session.close();
});
}
var snmpJobInterval = 2000;
(function shedule() {
setTimeout(function doIt() {
async.series([
function(next) {
snmpAsteriskJob();
next();
},
function(next) {
snmpSystemJob();
next();
},
function(next) {
console.log("placeholder");
next();
}, ], function(err, results) {
if(err) {
logger.error('I got error : ' + err + ' and re-try reschedule job.');
} else {
logger.debug('I did the jobs with success.');
}
shedule();
});
}, snmpJobInterval);
}()); |
import React from 'react';
import PropTypes from 'prop-types';
import { Checkbox } from 'office-ui-fabric-react/lib/Checkbox';
import styled from 'styled-components';
import { Label } from 'office-ui-fabric-react/lib/Label';
import { metaProp, inputProp, optionsProp } from 'utils/propTypes';
import { isEmptyChecks } from 'utils/validate';
import theme from 'utils/theme';
import Field from './Field';
import FieldError from './FieldError';
export const Check = styled(Checkbox)`
margin: 5px 0;
.ms-Checkbox-checkbox {
border-color: ${theme.neutralTertiary};
${(props) => props.errorMessage && `border-color: ${theme.redDark};`}
}
`;
export class FieldChecks extends React.Component {
static format = (value) => value || [];
constructor(props) {
super(props);
this.state = {
options: this.props.options,
};
}
componentWillReceiveProps(nextProps) {
const { input, options } = nextProps;
// when redux form resets, reset the options to not checked
if (isEmptyChecks(input.value)) {
const newOptions = options.map((option) => ({ ...option, checked: false }));
this.setState({ options: newOptions });
}
}
handleChange = (event, isChecked, key) => {
const { input } = this.props;
const { options } = this.state;
const newOptions = [...options];
// set the selected checkbox to checked (or not checked if false)
newOptions.find((option) => option.key === key).checked = isChecked;
// get just keys that are checked for redux store
const checked = newOptions
.filter((option) => option.checked)
.map((option) => option.key);
// update in redux store and state
input.onChange(checked);
this.setState({ options: newOptions });
}
render() {
const {
meta,
input,
label,
required,
...props
} = this.props;
const { options } = this.state;
const { touched, error } = meta;
const errorMessage = touched && error ? error : '';
const labelProps = {
label,
required,
};
const checkBoxProps = {
...props,
errorMessage,
};
return (
<div>
{label && <Label {...labelProps}>{label}</Label>}
{
options.map((option) => (
<Check
{...option}
{...checkBoxProps}
label={option.text}
onChange={(event, checked) => this.handleChange(event, checked, option.key)}
/>
))
}
{errorMessage && <FieldError>{errorMessage}</FieldError>}
</div>
);
}
}
const { bool, string, array } = PropTypes;
FieldChecks.propTypes = {
meta: metaProp.isRequired,
input: inputProp(array).isRequired,
label: string,
required: bool,
options: optionsProp.isRequired,
};
export default Field(FieldChecks, isEmptyChecks);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.