code
stringlengths
2
1.05M
//Main Function var App = function () { // IE mode var isIE8 = false; var isIE9 = false; var isIE10 = false; var $pageArea; var currentPage = ''; // current page //main settings var HoldInit = function () { isIE8 = !! navigator.userAgent.match(/MSIE 8.0/); isIE9 = !! navigator.userAgent.match(/MSIE 9.0/); isIE10 = !! navigator.userAgent.match(/MSIE 10.0/); if (isIE10) { jQuery('html').addClass('ie10'); // detect IE10 version } if (isIE10 || isIE9 || isIE8) { jQuery('html').addClass('ie'); // detect IE10 version } } //Tooltips var HoldTooltips = function () { if ($(".tooltips").length) { $('.tooltips').tooltip(); } $("[data-toggle='tooltip']").tooltip(); }; //Popovers var HoldPopovers = function () { if ($(".popovers").length) { $('.popovers').popover(); } }; //The size of the sidebar menu var HoldNavigationToggler = function () { $('.navigation-toggler').bind('click', function () { if (!$('body').hasClass('small-nav')) { $('body').addClass('small-nav'); $('.icon-arrow').hide(); // $('.brand-wrap').hide(); } else { $('body').removeClass('small-nav'); $('.icon-arrow').hide(); // $('.brand-wrap').show(); }; }); }; //Panel tools var HoldModuleTools = function () { $('.panel-tools .panel-close').bind('click', function (e) { $(this).parents(".panel").fadeOut(500, function(){ $(this).remove(); }); e.preventDefault(); }); $('.panel-tools .panel-refresh').bind('click', function (e) { var el = $(this).parents(".panel"); el.block({ overlayCSS: { backgroundColor: '#fff' }, message: '<img src="assets/images/loading.gif" />', css: { border: 'none', color: '#333', background: 'none' } }); window.setTimeout(function () { el.unblock(); }, 1000); e.preventDefault(); }); $('.panel-tools .panel-collapse').bind('click', function (e) { e.preventDefault(); var el = jQuery(this).parent().closest(".panel").children(".panel-body"); if ($(this).hasClass("collapses")) { $(this).addClass("expand").removeClass("collapses"); el.slideUp(200); } else { $(this).addClass("collapses").removeClass("expand"); el.slideDown(200); } }); }; //Sidebar menus var HoldSidebarNav = function () { $('.sidebar-menu li.active').addClass('open'); $('.sidebar-menu > li a').bind('click', function () { if ($(this).parent().children('ul').hasClass('sub') && (!$('body').hasClass('small-nav') || !$(this).parent().parent().hasClass('main-navigation-menu'))) { if (!$(this).parent().hasClass('open')) { $(this).parent().addClass('open'); $(this).parent().parent().children('li.open').not($(this).parent()).not($('.main-navigation-menu > li.active')).removeClass('open').children('ul').slideUp(300); $(this).parent().children('ul').slideDown(300); } else { if (!$(this).parent().hasClass('active')) { $(this).parent().parent().children('li.open').not($('.main-navigation-menu > li.active')).removeClass('open').children('ul').slideUp(300); } else { $(this).parent().parent().children('li.open').removeClass('open').children('ul').slideUp(300); } } } }); }; //function scroll to top var HoldGoTop = function () { $('.go-to-top').click(function(e) { $("html, body").animate({ scrollTop: 0}, "slow"); e.preventDefault(); }); }; //Sparkline var HoldSparkline = function () { $('#visit_1').sparkline([67547], { type: "bar", barSpacing: 2, barColor: "#00bdaf", barWidth: "57", height: "42", chartRangeMin: "10" }); $('#visit_2').sparkline([30141], { type: "bar", barSpacing: 2, barColor: "#1c84c6", barWidth: "57", height: "20", chartRangeMin: "10" }); }; //Custom checkboxes & radios using jQuery Uniform plugin var HoldUniform = function () { if (!jQuery().uniform) { return; } var test = $("input[type=checkbox]:not(.toggle), input[type=radio]:not(.toggle, .star)"); if (test.size() > 0) { test.each(function () { if ($(this).parents(".checker").size() == 0) { $(this).show(); $(this).uniform(); } }); } } // range slider var HoldRangeSlider = function () { $("#slider-range").slider({ range: true, min: 0, max: 500, values: [75, 300], slide: function (event, ui) { $("#slider-range-amount").text("$" + ui.values[0] + " - $" + ui.values[1]); } }); } //iCheck plugin for login page var HoldCustomCheckbox = function () { $('input[type="checkbox"].grey, input[type="radio"].grey').iCheck({ checkboxClass: 'icheckbox_minimal-grey', radioClass: 'iradio_minimal-grey', increaseArea: '10%' // optional }); }; return { //main function to initiate template pages init: function () { // page level handlers if (App.isPage("index")) { HoldVisitorsChart(); // handles plot charts for main page HoldSparkline(); // handles sparklines HoldPieChart(); HoldCustomCheckbox(); } // page level holders if (App.isPage("product")) { HoldRangeSlider(); } HoldInit(); HoldNavigationToggler(); //Navigation Toggler HoldSidebarNav(); //Saide bar navigation HoldGoTop(); //Got to top button HoldModuleTools(); //Tools HoldTooltips(); //Tooltips HoldPopovers(); //Popovers HoldUniform(); //Uniform HoldCustomCheckbox(); }, // set map page setPage: function (name) { currentPage = name; }, // check current page isPage: function (name) { return currentPage == name ? true : false; } }; }();
/* * example (insert new div after first div) : * var new_elm = document.createElement('div'); * insertAfter( * document.getElementsByTagName('div')[0], * new_elm * ) */ function insertAfter(refNode, newNode) { refNode.parentNode.insertBefore(newNode, refNode.nextSibling); }
'use strict'; const AWS = require('aws-sdk'); module.exports = (config) => { if (config.profile) { let credentials = new AWS.SharedIniFileCredentials({ profile: config.profile }); AWS.config.update({ credentials: credentials }); } if (config.region) { AWS.config.update({ region: config.region }); } };
var test = require('tape'); var lasync = require('../'); function a (cb) { console.log('run function "a"'); setTimeout(function () { return cb(null); }, 3000); } function b (cb) { console.log('run function "b"'); setTimeout(function () { return cb(null, 'Hello World'); }, 2500); } function c (cb) { console.log('run function "c"'); return cb(null, 123); } lasync.series([ function (cb) { test('lasync - series', function (t) { t.plan(1); lasync.series([a, b, c], function (err, results) { if (err) t.fail(err); t.ok(results, '"' + results.join(', ') + '"'); cb(); }); }); }, function (cb) { test('lasync - parallel', function (t) { t.plan(1); setTimeout(function () { lasync.parallel([a, b, c], function (err, results) { if (err) t.fail(err); t.ok(results, '"' + results.join(', ') + '"'); cb(); }); }, 1500); }); }, function (cb) { test('lasync - series with error', function (t) { t.plan(2); setTimeout(function () { lasync.series([ function (callback) { return callback(null, 'ok'); }, function (callback) { // flow will end here return callback('this is a error!!!!'); }, function (callback) { return callback(null, 'will not execute'); } ], function (err, results) { if (err) t.ok(err, err); t.equal(results, undefined, 'will return "undefined"'); cb(); }); }, 1500); }); }], function (err, results) { //empty });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _assign = require('babel-runtime/core-js/object/assign'); var _assign2 = _interopRequireDefault(_assign); var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties'); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = require('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _class, _temp; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * BeforeAfterWrapper * An alternative for the ::before and ::after css pseudo-elements for * components whose styles are defined in javascript instead of css. * * Usage: For the element that we want to apply before and after elements to, * wrap its children with BeforeAfterWrapper. For example: * * <Paper> * <Paper> <div> // See notice * <BeforeAfterWrapper> renders <div/> // before element * [children of paper] ------> [children of paper] * </BeforeAfterWrapper> <div/> // after element * </Paper> </div> * </Paper> * * Notice: Notice that this div bundles together our elements. If the element * that we want to apply before and after elements is a HTML tag (i.e. a * div, p, or button tag), we can avoid this extra nesting by passing using * the BeforeAfterWrapper in place of said tag like so: * * <p> * <BeforeAfterWrapper> do this instead <BeforeAfterWrapper elementType='p'> * [children of p] ------> [children of p] * </BeforeAfterWrapper> </BeforeAfterWrapper> * </p> * * BeforeAfterWrapper features spread functionality. This means that we can * pass HTML tag properties directly into the BeforeAfterWrapper tag. * * When using BeforeAfterWrapper, ensure that the parent of the beforeElement * and afterElement have a defined style position. */ var styles = { box: { boxSizing: 'border-box' } }; var BeforeAfterWrapper = (_temp = _class = function (_Component) { (0, _inherits3.default)(BeforeAfterWrapper, _Component); function BeforeAfterWrapper() { (0, _classCallCheck3.default)(this, BeforeAfterWrapper); return (0, _possibleConstructorReturn3.default)(this, _Component.apply(this, arguments)); } BeforeAfterWrapper.prototype.render = function render() { var _props = this.props, beforeStyle = _props.beforeStyle, afterStyle = _props.afterStyle, beforeElementType = _props.beforeElementType, afterElementType = _props.afterElementType, elementType = _props.elementType, other = (0, _objectWithoutProperties3.default)(_props, ['beforeStyle', 'afterStyle', 'beforeElementType', 'afterElementType', 'elementType']); var prepareStyles = this.context.muiTheme.prepareStyles; var beforeElement = void 0; var afterElement = void 0; if (beforeStyle) { beforeElement = _react2.default.createElement(this.props.beforeElementType, { style: prepareStyles((0, _assign2.default)({}, styles.box, beforeStyle)), key: '::before' }); } if (afterStyle) { afterElement = _react2.default.createElement(this.props.afterElementType, { style: prepareStyles((0, _assign2.default)({}, styles.box, afterStyle)), key: '::after' }); } var children = [beforeElement, this.props.children, afterElement]; var props = other; props.style = prepareStyles((0, _assign2.default)({}, this.props.style)); return _react2.default.createElement(this.props.elementType, props, children); }; return BeforeAfterWrapper; }(_react.Component), _class.propTypes = { afterElementType: _propTypes2.default.string, afterStyle: _propTypes2.default.object, beforeElementType: _propTypes2.default.string, beforeStyle: _propTypes2.default.object, children: _propTypes2.default.node, elementType: _propTypes2.default.string, /** * Override the inline-styles of the root element. */ style: _propTypes2.default.object }, _class.defaultProps = { beforeElementType: 'div', afterElementType: 'div', elementType: 'div' }, _class.contextTypes = { muiTheme: _propTypes2.default.object.isRequired }, _temp); exports.default = BeforeAfterWrapper;
//funkcija za ispis Z0 function ispisiZl(){ var rl = document.getElementById("rl").value; var xl = document.getElementById("xl").value; //ako je xl pozitivan if (xl >= 0) document.getElementById("zl").innerHTML = "Z<sub>L</sub> = <span id='zlComplex'>" + rl + "+j" + xl + "</span> &Omega;"; else //negativan document.getElementById("zl").innerHTML = "Z<sub>L</sub> = <span id='zlComplex'>" + rl + "-j" + -xl + "</span> &Omega;"; } //funkcija za validaciju function validacija(){ //provjeri sve textboxove var z0 = parseFloat(document.getElementById("z0").value); var rl = parseFloat(document.getElementById("rl").value); var xl = parseFloat(document.getElementById("xl").value); var f = parseFloat(document.getElementById("f").value); //ako je barem jedna od vrijednost NaN vrati false if(isNaN(z0) || isNaN(rl) || isNaN(xl) || isNaN(z0) || isNaN(f)){ alert("Upisite sve BROJCANE vrijednosti"); return false; } odaberiKrug(); } //funkcija za odabir kruga function odaberiKrug(){ var rl = parseFloat(document.getElementById("rl").value); var z0 = parseFloat(document.getElementById("z0").value); //ako je rl > z0 unutar 1+jx kruga if(rl > z0) unutarKruga(); //inace izvan 1+jx kruga else izvanKruga(); } //unutar 1+jx kruga function unutarKruga(){ var z0 = parseFloat(document.getElementById("z0").value); var rl = parseFloat(document.getElementById("rl").value); var xl = parseFloat(document.getElementById("xl").value); var f = parseFloat(document.getElementById("f").value); //pretvori f u Hz iz MHz f = f * 1000000; //izracunaj w(omega) var w = 2*Math.PI * f; //izracunaj X i B with(Math){ var b1 = (xl + sqrt(rl/z0) * sqrt(pow(rl, 2) + pow(xl, 2) - z0 * rl)) / (pow(rl, 2) + pow(xl, 2)); var b2 = (xl - sqrt(rl/z0) * sqrt(pow(rl, 2) + pow(xl, 2) - z0 * rl)) / (pow(rl, 2) + pow(xl, 2)); var x1 = (1/b1) + ((xl*z0)/rl) - (z0/(b1*rl)); var x2 = (1/b2) + ((xl*z0)/rl) - (z0/(b2*rl)); } //prvo rjesenje if(b1 > 0 && x1 > 0) var r1 = LC(b1, x1, w); else if(b1 > 0 && x1 < 0) var r1 = CC(b1, x1, w); else if(b1 < 0 && x1 > 0) var r1 = LL(b1, x1, w); else if(b1 < 0 && x1 < 0) var r1 = CL(b1, x1, w); //drugo rjesenje if(b2 > 0 && x2 > 0) var r2 = LC(b2, x2, w); else if(b2 > 0 && x2 < 0) var r2 = CC(b2, x2, w); else if(b2 < 0 && x2 > 0) var r2 = LL(b2, x2, w); else if(b2 < 0 && x2 < 0) var r2 = CL(b2, x2, w); //postavi varijablu krug na unutar kako bi znali sto ispisati var krug = "unutar"; //ispisi rezultat ispisiRezultat(r1, r2, krug); //izracunaj koef. refleksije gamma var gamma = izracunajGamma(r1, r2, krug, z0); //iscrtaj gamma na grafu crtajGraf(gamma); } //izvan 1+jx kruga function izvanKruga(){ var z0 = parseFloat(document.getElementById("z0").value); var rl = parseFloat(document.getElementById("rl").value); var xl = parseFloat(document.getElementById("xl").value); var f = parseFloat(document.getElementById("f").value); //pretvori f u Hz iz MHz f = f * 1000000; //izracunaj w(omega) var w = 2*Math.PI * f; //izracunaj X i B with(Math){ var b1 = (sqrt((z0 - rl) / rl)) / z0; var x1 = sqrt(rl * (z0 - rl)) - xl; var b2 = - (sqrt((z0 - rl) / rl)) / z0; var x2 = - sqrt(rl * (z0 - rl)) - xl; } //prvo rjesenje if(b1 > 0 && x1 > 0) var r1 = LC(b1, x1, w); else if(b1 > 0 && x1 < 0) var r1 = CC(b1, x1, w); else if(b1 < 0 && x1 > 0) var r1 = LL(b1, x1, w); else if(b1 < 0 && x1 < 0) var r1 = CL(b1, x1, w); //drugo rjesenje if(b2 > 0 && x2 > 0) var r2 = LC(b2, x2, w); else if(b2 > 0 && x2 < 0) var r2 = CC(b2, x2, w); else if(b2 < 0 && x2 > 0) var r2 = LL(b2, x2, w); else if(b2 < 0 && x2 < 0) var r2 = CL(b2, x2, w); //postavi varijablu krug na izvan kako bi znali sto ispisati var krug = "izvan"; //ispisi rezultat ispisiRezultat(r1, r2, krug); //izracunaj koef. refleksije gamma var gamma = izracunajGamma(r1, r2, krug, z0); //iscrtaj gamma na grafu crtajGraf(gamma); } //izracuna za LC mrezu function LC(b, x, w){ var rez1 = Math.abs(x)/w; var rez2 = Math.abs(b)/w; var mreza = "LC"; return [rez1, rez2, mreza]; } //izracun za CC mrezu function CC(b, x, w){ var rez1 = 1/(w*Math.abs(x)); var rez2 = Math.abs(b)/w; var mreza = "CC"; return [rez1, rez2, mreza]; } //izracun za LL mrezu function LL(b, x, w){ var rez1 = Math.abs(x)/w; var rez2 = 1/(w*Math.abs(b)); var mreza = "LL"; return [rez1, rez2, mreza]; } //izracun za CL mrezu function CL(b, x, w){ var rez1 = 1/(w*Math.abs(x)); var rez2 = 1/(w*Math.abs(b)); var mreza = "CL"; return [rez1, rez2, mreza]; } //funkcija za ispis rezultata function ispisiRezultat(r1, r2, krug){ var mreza1 = r1[2]; var mreza2 = r2[2]; //provjeri je li izvan 1+jx kruga if (krug == "unutar"){ //prvo rijesenje //provjeri koja je mreza i ispisi sliku mreze te rezultat switch(mreza1){ case "LC": document.getElementById("prvaMreza").innerHTML = "1. rješenje: <br><img src='img/LC_unutar.png'><br> L1=" + (r1[0] * Math.pow(10,9)).toFixed(2) + " nH<br>C1=" + (r1[1] * Math.pow(10,12)).toFixed(2) + " pF"; break; case "CC": document.getElementById("prvaMreza").innerHTML = "1. rješenje: <br><img src='img/CC_unutar.png'><br> C1=" + (r1[0] * Math.pow(10,12)).toFixed(2) + " pF<br>C1'=" + (r1[1] * Math.pow(10,12)).toFixed(2) + " pF"; break; case "LL": document.getElementById("prvaMreza").innerHTML = "1. rješenje: <br><img src='img/LL_unutar.png'><br> L1=" + (r1[0] * Math.pow(10,9)).toFixed(2) + " nH<br>L1'=" + (r1[1] * Math.pow(10,9)).toFixed(2) + " nH"; break; case "CL": document.getElementById("prvaMreza").innerHTML = "1. rješenje: <br><img src='img/CL_unutar.png'><br> C1=" + (r1[0] * Math.pow(10,12)).toFixed(2) + " pF<br>L1=" + (r1[1] * Math.pow(10,9)).toFixed(2) + " nH"; break; } //drugo rijesenje //provjeri koja je mreza i ispisi sliku mreze te rezultat switch(mreza2){ case "LC": document.getElementById("drugaMreza").innerHTML = "2. rješenje: <br><img src='img/LC_unutar.png'><br> L2=" + (r2[0] * Math.pow(10,9)).toFixed(2) + " nH<br>C2=" + (r2[1] * Math.pow(10,12)).toFixed(2) + " pF"; break; case "CC": document.getElementById("drugaMreza").innerHTML = "2. rješenje: <br><img src='img/CC_unutar.png'><br> C2=" + (r2[0] * Math.pow(10,12)).toFixed(2) + " pF<br>C2'=" + (r2[1] * Math.pow(10,12)).toFixed(2) + " pF"; break; case "LL": document.getElementById("drugaMreza").innerHTML = "2. rješenje: <br><img src='img/LL_unutar.png'><br> L2=" + (r2[0] * Math.pow(10,9)).toFixed(2) + " nH<br>L2'=" + (r2[1] * Math.pow(10,9)).toFixed(2) + " nH"; break; case "CL": document.getElementById("drugaMreza").innerHTML = "2. rješenje: <br><img src='img/CL_unutar.png'><br> C2=" + (r2[0] * Math.pow(10,12)).toFixed(2) + " pF<br>L2=" + (r2[1] * Math.pow(10,9)).toFixed(2) + " nH"; break; } //prikazi mreze document.getElementById("tablicaMreza").style.visibility = "visible"; } //provjeri je li izvan 1+jx kruga else if(krug == "izvan"){ switch(mreza1){ //prvo rijesenje //provjeri koja je mreza i ispisi sliku mreze te rezultat case "LC": document.getElementById("prvaMreza").innerHTML = "1. rješenje: <br><img src='img/LC_izvan.png'><br> L1=" + (r1[0] * Math.pow(10,9)).toFixed(2) + " nH<br>C1=" + (r1[1] * Math.pow(10,12)).toFixed(2) + " pF"; break; case "CC": document.getElementById("prvaMreza").innerHTML = "1. rješenje: <br><img src='img/CC_izvan.png'><br> C1=" + (r1[0] * Math.pow(10,12)).toFixed(2) + " pF<br>C1'=" + (r1[1] * Math.pow(10,12)).toFixed(2) + " pF"; break; case "LL": document.getElementById("prvaMreza").innerHTML = "1. rješenje: <br><img src='img/LL_izvan.png'><br> L1=" + (r1[0] * Math.pow(10,9)).toFixed(2) + " nH<br>L1'=" + (r1[1] * Math.pow(10,9)).toFixed(2) + " nH"; break; case "CL": document.getElementById("prvaMreza").innerHTML = "1. rješenje: <br><img src='img/CL_izvan.png'><br> C1=" + (r1[0] * Math.pow(10,12)).toFixed(2) + " pF<br>L1=" + (r1[1] * Math.pow(10,9)).toFixed(2) + " nH"; break; } //drugo rijesenje //provjeri koja je mreza i ispisi sliku mreze te rezultat switch(mreza2){ case "LC": document.getElementById("drugaMreza").innerHTML = "2. rješenje: <br><img src='img/LC_izvan.png'><br> L2=" + (r2[0] * Math.pow(10,9)).toFixed(2) + " nH<br>C2=" + (r2[1] * Math.pow(10,12)).toFixed(2) + " pF"; break; case "CC": document.getElementById("drugaMreza").innerHTML = "2. rješenje: <br><img src='img/CC_izvan.png'><br> C2=" + (r2[0] * Math.pow(10,12)).toFixed(2) + " pF<br>C2'=" + (r2[1] * Math.pow(10,12)).toFixed(2) + " pF"; break; case "LL": document.getElementById("drugaMreza").innerHTML = "2. rješenje: <br><img src='img/LL_izvan.png'><br> L2=" + (r2[0] * Math.pow(10,9)).toFixed(2) + " nH<br>L2'=" + (r2[1] * Math.pow(10,9)).toFixed(2) + " nH"; break; case "CL": document.getElementById("drugaMreza").innerHTML = "2. rješenje: <br><img src='img/CL_izvan.png'><br> C2=" + (r2[0] * Math.pow(10,12)).toFixed(2) + " pF<br>L2=" + (r2[1] * Math.pow(10,9)).toFixed(2) + " nH"; break; } //prikazi mreze document.getElementById("tablicaMreza").style.visibility = "visible"; } } //funkcija za izracun gamma function izracunajGamma(r1, r2, krug, z0){ ////pretvori z0 i zl u kompleksne brojeve z0 = math.complex(z0, 0); var rl = parseFloat(document.getElementById("rl").value); var xl = parseFloat(document.getElementById("xl").value); var zl = math.complex(rl, xl); //dohvati rijesenja var r11 = r1[0]; var r12 = r1[1]; var mreza1 = r1[2]; var r21 = r2[0]; var r22 = r2[1]; var mreza2 = r2[2]; //stvori polja za spremanje rezultata var rez1 = []; var rez2 = []; //IZRACUN FREKVENCIJE DO 1500 MHz tj. 1500000000 Hz var frekGranica = 1500000000; //provjeri je li unutar 1+jx kruga if (krug == "unutar"){ //prvo rijesenje //izracun za frekvenciju od 1Hz do 1.5 GHz zl = math.pow(zl, -1); for(var frek=1; frek<=frekGranica; frek+=1000000){ var w = 2 * Math.PI * frek; //provjeri koja je mreza te recunaj jX i jB switch(mreza1){ case "LC" : var jX1 = r11 * w; jX1 = math.complex(0, jX1); var jB1 = r12 * w; jB1 = math.complex(0, jB1); break; case "CC" : var jX1 = -r11 * w; jX1 = math.pow(jX1, -1); jX1 = math.complex(0, jX1); var jB1 = r12 * w; jB1 = math.complex(0, jB1); break; case "LL" : var jX1 = r11 * w; jX1 = math.complex(0, jX1); var jB1 = -r12 * w; jB1 = math.pow(jB1, -1); jB1 = math.complex(0, jB1); break; case "CL" : var jX1 = -r11 * w; jX1 = math.pow(jX1, -1); jX1 = math.complex(0, jX1); var jB1 = -r12 * w; jB1 = math.pow(jB1, -1); jB1 = math.complex(0, jB1); break; } //izracunaj zul var jB1zl = math.add(jB1, zl); jB1zl = math.pow(jB1zl, -1); var zul = math.add(jX1, jB1zl); //izracunaj gamma var gammaBrojink = math.subtract(zul, z0); var gammaNazivnik = math.add(zul, z0); var gamma = math.divide(gammaBrojink, gammaNazivnik); var gammaAbs = math.abs(gamma); rez1.push(gammaAbs); } //drugo rijesenje //izracun za frekvenciju od 1Hz do 1.5 GHz for(var frek=1; frek<=frekGranica; frek+=1000000){ var w = 2 * Math.PI * frek; //provjeri koja je mreza te recunaj jX i jB switch(mreza2){ case "LC" : var jX2 = r21 * w; jX2 = math.complex(0, jX2); var jB2 = r22 * w; jB2 = math.complex(0, jB2); break; case "CC" : var jX2 = -r21 * w; jX2 = math.pow(jX2, -1); jX2 = math.complex(0, jX2); var jB2 = r22 * w; jB2 = math.complex(0, jB2); break; case "LL" : var jX2 = r21 * w; jX2 = math.complex(0, jX2); var jB2 = -r22 * w; jB2 = math.pow(jB2, -1); jB2 = math.complex(0, jB2); break; case "CL" : var jX2 = -r21 * w; jX2 = math.pow(jX2, -1); jX2 = math.complex(0, jX2); var jB2 = -r22 * w; jB2 = math.pow(jB2, -1); jB2 = math.complex(0, jB2); break; } //izracunaj zul var jB2zl = math.add(jB2, zl); jB2zl = math.pow(jB2zl, -1); var zul = math.add(jX2, jB2zl); //izracunaj gamma var gammaBrojink1 = math.subtract(zul, z0); var gammaNazivnik1 = math.add(zul, z0); var gamma1 = math.divide(gammaBrojink1, gammaNazivnik1); var gammaAbs1 = math.abs(gamma1); rez2.push(gammaAbs1); } } //provjeri je li izvan 1+jx kruga else if (krug == "izvan"){ //prvo rijesenje //izracun za frekvenciju od 1Hz do 1.5 GHz for(var frek=1; frek<=frekGranica; frek+=1000000){ var w = 2 * Math.PI * frek; //provjeri koja je mreza te recunaj jX i jB switch(mreza1){ case "LC" : var jX1 = r11 * w; jX1 = math.complex(0, jX1); var jB1 = r12 * w; jB1 = math.complex(0, jB1); break; case "CC" : var jX1 = -r11 * w; jX1 = math.pow(jX1, -1); jX1 = math.complex(0, jX1); var jB1 = r12 * w; jB1 = math.complex(0, jB1); break; case "LL" : var jX1 = r11 * w; jX1 = math.complex(0, jX1); var jB1 = -r12 * w; jB1 = math.pow(jB1, -1); jB1 = math.complex(0, jB1); break; case "CL" : var jX1 = -r11 * w; jX1 = math.pow(jX1, -1); jX1 = math.complex(0, jX1); var jB1 = -r12 * w; jB1 = math.pow(jB1, -1); jB1 = math.complex(0, jB1); break; } //izracunaj zul var jX1zl = math.add(jX1, zl); jX1zl = math.pow(jX1zl, -1); var zul = math.add(jB1, jX1zl); zul = math.pow(zul, -1); //izracunaj gamma var gammaBrojink = math.subtract(zul, z0); var gammaNazivnik = math.add(zul, z0); var gamma = math.divide(gammaBrojink, gammaNazivnik); var gammaAbs = math.abs(gamma); rez1.push(gammaAbs); } //drugo rijesenje //izracun za frekvenciju od 1Hz do 1.5 GHz for(var frek=1; frek<=frekGranica; frek+=1000000){ var w = 2 * Math.PI * frek; //provjeri koja je mreza te recunaj jX i jB switch(mreza2){ case "LC" : var jX2 = r21 * w; jX2 = math.complex(0, jX2); var jB2 = r22 * w; jB2 = math.complex(0, jB2); break; case "CC" : var jX2 = -r21 * w; jX2 = math.pow(jX2, -1); jX2 = math.complex(0, jX2); var jB2 = r22 * w; jB2 = math.complex(0, jB2); break; case "LL" : var jX2 = r21 * w; jX2 = math.complex(0, jX2); var jB2 = -r22 * w; jB2 = math.pow(jB2, -1); jB2 = math.complex(0, jB2); break; case "CL" : var jX2 = -r21 * w; jX2 = math.pow(jX2, -1); jX2 = math.complex(0, jX2); var jB2 = -r22 * w; jB2 = math.pow(jB2, -1); jB2 = math.complex(0, jB2); break; } //izracunaj zul var jX2zl = math.add(jX2, zl); jX2zl = math.pow(jX2zl, -1); var zul = math.add(jB2, jX2zl); zul = math.pow(zul, -1); //izracunaj gamma var gammaBrojink1 = math.subtract(zul, z0); var gammaNazivnik1 = math.add(zul, z0); var gamma1 = math.divide(gammaBrojink1, gammaNazivnik1); var gammaAbs1 = math.abs(gamma1); rez2.push(gammaAbs1); } } //vrati 2 rijesenja return [rez1, rez2]; } //funkcija za crtanje grafa function crtajGraf(data){ document.getElementById('graph').innerHTML = ""; //izbrisi graf ukuliko je nacrtan d3.select("svg") .remove(); //dohvati rijesenja Ydata1 = data[0]; Ydata2 = data[1]; var Xdata = d3.range(1500); var xy1 = []; for(var i=0;i<Xdata.length;i++){ xy1.push({x:Xdata[i],y:Ydata1[i]}); } var xy2 = []; for(var i=0;i<Xdata.length;i++){ xy2.push({x:Xdata[i],y:Ydata2[i]}); } // definiraj dimenzije grafa var m = [20, 20, 50, 80]; // margine var w = 745 - m[1] - m[3]; // width var h = 400 - m[0] - m[2]; // height // X skala za data1 polje od 0-w piksela xScale = d3.scale.linear().domain(d3.extent(xy1,function(d) {return d.x;})).range([0, w]); // Y skala od 0-1 od 0-h piksela yScale = d3.scale.linear().domain([0, 1]).range([h, 0]); // funkcija koja pretvara data u x i y tocke var line = d3.svg.line() .x(function(d,i) { return xScale(d.x);}) .y(function(d,i) { return yScale(d.y);}) // dodaj SVG element za zeljenim marginama var graph = d3.select("#graph").append("svg:svg") .attr("width", w + m[1] + m[3]) .attr("height", h + m[0] + m[2]) .append("svg:g") .attr("transform", "translate(" + m[3] + "," + m[0] + ")"); // stvori x os var xAxis = d3.svg.axis().scale(xScale).tickSize(-h).tickSubdivide(true); // dodaj x os graph.append("svg:g") .attr("class", "x axis") .attr("transform", "translate(0," + h + ")") .call(xAxis) //dodaj x labelu .append("text") .attr("x", w / 2) .attr("y", m[2] - 25) .attr("dy", ".45em") .style("text-anchor", "end") .text("f(MHz)"); // stvori y os var yAxisLeft = d3.svg.axis().scale(yScale).ticks(4).orient("left"); // dodaj y os graph.append("svg:g") .attr("class", "y axis") .attr("transform", "translate(-25,0)") .call(yAxisLeft) //dodaj y labelu .append("text") //.attr("transform", "rotate(-90)") .attr("x", -h/2) .attr("y", -m[2]) .attr("dx", "8em") .attr("dy", "14em") .style("text-anchor", "end") .text("|\u0393|"); //iscrtaj 2 linije za 2 rijsenja graph.append("svg:path") .attr("d", line(xy1)) .attr("id", "myPath1") .attr('stroke', '#47A3FF') //prikaz vrijednosti na grafu .on("mousemove", mMove1) .append("title"); graph.append("svg:path") .attr("d", line(xy2)) //.attr('stroke', 'red') //isprekidana linija .style("stroke-dasharray", ("7, 3")) .attr("id", "myPath2") .attr('stroke', '#FF4747') //prikaz vrijednosti na grafu .on("mousemove", mMove2) .append("title"); //prostor za legendu var legendSpace = w/xy1.length; //legenda prvog rijesenja graph.append("text") .attr("x", (legendSpace/2)+legendSpace + 135 ) .attr("y", h + (m[2]/2)+ 21) .attr("class", "legend") .style("fill", '#47A3FF') .text("1. rješenje \u2014"); //legenda drugog rjesenja graph.append("text") .attr("x", (legendSpace/2)+legendSpace + 390 ) .attr("y", h + (m[2]/2)+ 21) .attr("class", "legend") .style("fill", '#FF4747') .text("2. rješenje - - -"); //prikazi bandwidth document.getElementById("bandwidth").style.visibility = "visible"; //funkcije koje prikazuju vrijednosti na krivulji pomakom misa function mMove1(){ var title = d3.mouse(this); d3.select("#myPath1").select("title").text((yScale.invert(title[1])).toFixed(3)); } function mMove2(){ var title = d3.mouse(this); d3.select("#myPath2").select("title").text((yScale.invert(title[1])).toFixed(3)); } //ako je izracun bandwidtha prikazan -> refresh if ((typeof(isBandwidth) !== 'undefined') && (isBandwidth == true)){ izracunajBandwidth(); } } //funkcija za izracun bandwidtha function izracunajBandwidth(){ //varijable za spremanje frekvencije var f1 = []; var f2 = []; //pomocna varijabla var flag = false; //uzmi gamma var gamma = parseFloat(document.getElementById("bandwidthNum").value); //zaokruzi gamma na 2 decimale gamma = gamma.toFixed(2); //prođi kroz polje rjesenja i ako je jednako gamma i flag je false spremi rjesenje u polje i postavi flag na true for (var i=0; i<Ydata1.length; i++){ if(Ydata1[i].toFixed(2) == gamma && flag == false){ f1.push(i); flag = true; } //ukoliko nije jednako gamma postavi flag na false else if(Ydata1[i].toFixed(2) != gamma) { flag = false; } } //prođi kroz polje rjesenja i ako je jednako gamma i flag je false spremi rjesenje u polje i postavi flag na true for (var i=0; i<Ydata2.length; i++){ if(Ydata2[i].toFixed(2) == gamma && flag == false){ f2.push(i); flag = true; } //ukoliko nije jednako gamma postavi flag na false else if(Ydata2[i].toFixed(2) != gamma) { flag = false; } } //izracunaj bandwidth (f2-f1) var bw1 = f1[1] - f1[0]; var bw2 = f2[1] - f2[0]; //izracunaj fo (f1+f2 / 2) var fo1 = (f1[0] + f1[1]) / 2; //relativni bw var relBW1 = (bw1 / fo1 * 100).toFixed(2); var fo2 = (f2[0] + f2[1]) / 2; var relBW2 = (bw2 / fo2 * 100).toFixed(2); //ispisi rjesenja document.getElementById("bandwidth1rjesenje").innerHTML = "<font color='#47A3FF'>1. rješenje: f1 = " + f1[0] + " MHz; " + "f2 = " + f1[1] + " MHz<br> BW = " + bw1 + " MHz; BW<sub>rel</sub> = " + relBW1 + " %</font>"; document.getElementById("bandwidth2rjesenje").innerHTML = "<font color='#FF4747'>2. rješenje: f1 = " + f2[0] + " MHz; " + "f2 = " + f2[1] + " MHz<br> BW = " + bw2 + " MHz; BW<sub>rel</sub> = "+ relBW2 + " %</font>"; //iscrtavanje rijesenja na grafuNa //selektiraj graf var graph = d3.select("#graph").select("svg"); //ukoliko postoje neka od rijesenja izbrisi ih if ((typeof(horizontalLine) !== 'undefined')){ horizontalLine.remove() } if ((typeof(f11Line) !== 'undefined')){ f11Line.remove() } if ((typeof(f12Line) !== 'undefined')){ f12Line.remove() } if ((typeof(f21Line) !== 'undefined')){ f21Line.remove() } if ((typeof(f22Line) !== 'undefined')){ f22Line.remove() } //horizontalna linija za gamma vrijednost horizontalLine = graph.append("svg:line") .attr("x1", 0 + 80) .attr("y1", yScale(gamma) + 20) .attr("x2", 1500 + 25) .attr("y2", yScale(gamma) + 20) .style("stroke", "black") .style("stroke-width", 2); if(!isNaN(f1[0])){ //f1 linija prvog rjesenja f11Line = graph.append("svg:line") .attr("x1", xScale(f1[0]) + 80) .attr("y1", yScale(0) + 20) .attr("x2", xScale(f1[0]) + 80) .attr("y2", yScale(gamma) + 20) .style("stroke", "#47A3FF") .style("stroke-width", 2) .style("stroke-dasharray", ("2, 2")); } if(!isNaN(f1[1])){ //f2 linija prvog rjensenja f12Line = graph.append("svg:line") .attr("x1", xScale(f1[1]) + 80) .attr("y1", yScale(0) + 20) .attr("x2", xScale(f1[1]) + 80) .attr("y2", yScale(gamma) + 20) .style("stroke", "#47A3FF") .style("stroke-width", 2) .style("stroke-dasharray", ("2, 2")); } if(!isNaN(f2[0])){ //f1 linija drugog rjesenja f21Line = graph.append("svg:line") .attr("x1", xScale(f2[0]) + 80) .attr("y1", yScale(0) + 20) .attr("x2", xScale(f2[0]) + 80) .attr("y2", yScale(gamma) + 20) .style("stroke", "#FF4747") .style("stroke-width", 2) .style("stroke-dasharray", ("2, 2")); } if(!isNaN(f2[1])){ //f2 linija drugog rjesenja f22Line = graph.append("svg:line") .attr("x1", xScale(f2[1]) + 80) .attr("y1", yScale(0) + 20) .attr("x2", xScale(f2[1]) + 80) .attr("y2", yScale(gamma) + 20) .style("stroke", "#FF4747") .style("stroke-width", 2) .style("stroke-dasharray", ("2, 2")); } //bandwidth je ispisan isBandwidth = true; } //funkcija za spremanje datoteke function save(){ //uzmi vrijednosti za spremanje var z0 = document.getElementById("z0").value; var rl = document.getElementById("rl").value; var xl = document.getElementById("xl").value; var f = document.getElementById("f").value; //zapisi vrijednosti u varijablu (Windows formatiranje) var text = z0 + "\r\n" + rl + "\r\n" + xl + "\r\n" + f; //stvori blob i download link na buttonu var textFileAsBlob = new Blob([text], {type:'text/plain'}); var fileNameToSaveAs = document.getElementById("FileNameToSave").value; var downloadLink = document.createElement("a"); downloadLink.download = fileNameToSaveAs; downloadLink.innerHTML = "Download File"; if (window.webkitURL != null){ // Chrome allows the link to be clicked // without actually adding it to the DOM. downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob); } else{ // Firefox requires the link to be added to the DOM // before it can be clicked. downloadLink.href = window.URL.createObjectURL(textFileAsBlob); downloadLink.onclick = destroyClickedElement; downloadLink.style.display = "none"; document.body.appendChild(downloadLink); } downloadLink.click(); } //unisti kliknuti element ( potrebno kako bi radilo u Firefoxu) function destroyClickedElement(event){ document.body.removeChild(event.target); } //funkcija za ucitavanje datoteke function load(){ //file u koji ce se spremati var fileToLoad = document.getElementById("fileToLoad").files[0]; //stvori novi FileReader var fileReader = new FileReader(); fileReader.onload = function(fileLoadedEvent){ var text = fileLoadedEvent.target.result; //razdvoji string u polje var text = text.split("\r\n"); //spremi u određene textboxove i trigeraj onchange event za ispis zl document.getElementById("z0").value = text[0]; document.getElementById("rl").value = text[1]; document.getElementById("rl").onchange(); document.getElementById("xl").value = text[2]; document.getElementById("xl").onchange(); document.getElementById("f").value = text[3]; }; //utf-8 formatiranje fileReader.readAsText(fileToLoad, "UTF-8"); } //funkcija za prikaz opceg rjesenja function toggle_visibility(id){ var e = document.getElementById(id); if(e.style.display == 'block') e.style.display = 'none'; else e.style.display = 'block'; }
/* The MIT License (MIT) Original Library - Copyright (c) Marak Squires Additional functionality - Copyright (c) Sindre Sorhus <[email protected]> (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var colors = {}; module['exports'] = colors; colors.themes = {}; var ansiStyles = colors.styles = require('./styles'); var defineProps = Object.defineProperties; colors.supportsColor = require('./system/supports-colors'); if (typeof colors.enabled === "undefined") { colors.enabled = colors.supportsColor; } colors.stripColors = colors.strip = function(str){ return ("" + str).replace(/\x1B\[\d+m/g, ''); }; var stylize = colors.stylize = function stylize (str, style) { if (!colors.enabled) { return str+''; } return ansiStyles[style].open + str + ansiStyles[style].close; } var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; var escapeStringRegexp = function (str) { if (typeof str !== 'string') { throw new TypeError('Expected a string'); } return str.replace(matchOperatorsRe, '\\$&'); } function build(_styles) { var builder = function builder() { return applyStyle.apply(builder, arguments); }; builder._styles = _styles; // __proto__ is used because we must return a function, but there is // no way to create a function with a different prototype. builder.__proto__ = proto; return builder; } var styles = (function () { var ret = {}; ansiStyles.grey = ansiStyles.gray; Object.keys(ansiStyles).forEach(function (key) { ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); ret[key] = { get: function () { return build(this._styles.concat(key)); } }; }); return ret; })(); var proto = defineProps(function colors() {}, styles); function applyStyle() { var args = arguments; var argsLen = args.length; var str = argsLen !== 0 && String(arguments[0]); if (argsLen > 1) { for (var a = 1; a < argsLen; a++) { if(toString.call(args[a])==="[object Array]")args[a] = args[a].join('\r\n') str += ' ' + args[a]; } } if (!colors.enabled || !str) { return str; } var nestedStyles = this._styles; var i = nestedStyles.length; while (i--) { var code = ansiStyles[nestedStyles[i]]; str = code.open + str.replace(code.closeRe, code.open) + code.close; } return str; } function applyTheme (theme) { for (var style in theme) { (function(style){ colors[style] = function(str){ if (typeof theme[style] === 'object'){ var out = str; for (var i in theme[style]){ out = colors[theme[style][i]](out); } return out; } return colors[theme[style]](str); }; })(style) } } colors.setTheme = function (theme) { if (typeof theme === 'string') { try { colors.themes[theme] = require(theme); applyTheme(colors.themes[theme]); return colors.themes[theme]; } catch (err) { console.log(err); return err; } } else { applyTheme(theme); } }; function init() { var ret = {}; Object.keys(styles).forEach(function (name) { ret[name] = { get: function () { return build([name]); } }; }); return ret; } var sequencer = function sequencer (map, str) { var exploded = str.split(""), i = 0; exploded = exploded.map(map); return exploded.join(""); }; // custom formatter methods colors.trap = require('./custom/trap'); colors.zalgo = require('./custom/zalgo'); // maps colors.maps = {}; colors.maps.america = require('./maps/america'); colors.maps.zebra = require('./maps/zebra'); colors.maps.rainbow = require('./maps/rainbow'); colors.maps.random = require('./maps/random') for (var map in colors.maps) { (function(map){ colors[map] = function (str) { return sequencer(colors.maps[map], str); } })(map) } defineProps(colors, init());
/** * Returns the details of one P6 postcode. Instance of GET /postcodes. * @name getSinglePostcode * @method * @static * @since 1.0.0 * @param {Object} options - Options for performing the API call and influencing the callback. * @param {String} options.apiKey - The API-token to access the API. * @param {Boolean} [options.returnRateLimit] - If set to true, the callback will be invoked with an extra result containing an object with the limit and the remaining amount of API calls. * @param {String} postcode - The postcode to query, formatted in P6. * @param {Function} callback - A callback which is called when the API-request is finished. * @param {Error} callback.error - May contain an instance of Error, if no error occured null is responded. * @param {Object} callback.result - Contains the response as a json in exactly the same format as provided by the API. If no results are found, null is responded. * @param {Object} [callback.rateLimit] - If requested in options, an object with information about the API limits is returned. Otherwise, it will return undefined. * @example * const postcodeApi = require('postcode-nl'); * * let options = { * apiKey : 'abcdefghijklmnopQRSTUVWXYZ123' * }; * let postcode = '1234AB'; * * postcodeApi.getSinglePostcode(options, postcode, (error, result) => { * if (!error) { * console.log(result); // Shows the json-output of the API directy in the console * } * }); */ 'use strict'; const helpers = require('./helpers.js'); const api = require('./requestApi.js'); function getSinglePostcode(options, postcode, callback) { // Check if postcode is correctly formatted for this API-call if (!postcode || typeof(postcode) !== 'string' || !helpers.validatePostcodeP6(postcode)) { return callback(new Error('The postcode is required and must be in P6-formatted for this API-call'), null); } options.url = 'https://postcode-api.apiwise.nl/v2/postcodes/' + postcode; options.headers = { 'X-Api-Key' : options.apiKey }; // Executing API-request return api.get(options, callback); } module.exports = getSinglePostcode;
import React from 'react'; import SearchLayer from '../../src/components/SearchLayer/SearchLayer.js'; import renderer from 'react-test-renderer'; it('SearchLayer component renders correctly with no data', () => { const component = shallow(<SearchLayer/>); expect(component).toMatchSnapshot(); });
//検索ウィンドウの表示 function fnSearchSubWindow(Winname,Wwidth,Wheight){ var WIN; WIN = window.open("/admin/feature_products/product_search",Winname,"width="+Wwidth+",height="+Wheight+",scrollbars=yes,resizable=yes,toolbar=no,location=no,directories=no,status=no"); WIN.focus(); } //検索ウィンドウで決定した商品をメインウィンドウに反映 function fnProductSubmit(product_id, resource_id, product_name){ window.opener.document.getElementById("product_name").innerHTML = product_name; window.opener.document.getElementById("feature_product_product_id").value = product_id; window.opener.document.getElementById("feature_product_image_resource_id").value = resource_id; resource_old_id = window.opener.document.getElementById("feature_product_image_resource_old_id") if(resource_old_id != null && resource_old_id.value > 0){ window.opener.document.getElementById("feature_product_image_resource_old_id").value = 0; window.opener.document.getElementById("feature_product_image_resource_old_file").style.display = 'none'; } window.close(); return false; }
ccm.files[ "configs.js" ] = { "demo": { task: "<h4>1. Lesen Sie den Text und reflektieren Sie.</h4>" + "<p>Er hörte leise Schritte hinter sich. Das bedeutete nichts Gutes. Wer würde ihm schon folgen, spät in der " + "Nacht und dazu noch in dieser engen Gasse mitten im übel beleumundeten Hafenviertel? Gerade jetzt, wo er das Ding " + "seines Lebens gedreht hatte und mit der Beute verschwinden wollte! Hatte einer seiner zahllosen Kollegen dieselbe " + "Idee gehabt, ihn beobachtet und abgewartet, um ihn nun um die Früchte seiner Arbeit zu erleichtern? Oder gehörten " + "die Schritte hinter ihm zu einem der unzähligen Gesetzeshüter dieser Stadt, und die stählerne Acht um seine " + "Handgelenke würde gleich zuschnappen? Er konnte die Aufforderung stehen zu bleiben schon hören.</p>", "submit": true, "onfinish": { log: true } } };
'use strict'; const supertest = require('supertest'); const req = supertest(require('../../').app); describe('GET /page/about', function describe() { const url = '/page/about'; it('returns about page', function it(done) { req.get(url).expect(200, done); }); }); describe('GET /page/notfound', function describe() { const url = '/page/notfound'; it('returns 404 error', function it(done) { req.get(url).expect(404, done); }); });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.isNot = exports.isProvider = exports.iff = exports.softDelete = undefined; var _utils = require('./utils'); /* eslint-env es6, node */ /* eslint no-param-reassign: 0, no-var: 0 */ var errors = require('feathers-errors').errors; /** * Mark an item as deleted rather than removing it from the database. * * @param {string} field - Field for delete status. Supports dot notation. Default is 'deleted'. * * export.before = { <<<<<<< HEAD * remove: [ softDelete() ], // update item flagging it as deleted * find: [ softDelete() ] // ignore deleted items * }; */ var softDelete = exports.softDelete = function softDelete(field) { return function (hook) { (0, _utils.checkContext)(hook, 'before', ['remove', 'find'], 'softDelete'); if (hook.method === 'find') { hook.params.query = hook.params.query || {}; (0, _utils.setByDot)(hook.data, (field || 'deleted') + '.$ne', true); // include non-deleted items only return hook; } hook.data = hook.data || {}; (0, _utils.setByDot)(hook.data, field || 'deleted', true); // update the item as deleted return undefined.patch(hook.id, hook.data, hook.params).then(function (data) { hook.result = data; // Set the result from `patch` as the method call result return hook; // Always return the hook or `undefined` }); ======= * all: softDelete() * }; */ var softDelete = exports.softDelete = function softDelete(field) { var deleteField = field || 'deleted'; return function (hook) { var service = this; hook.data = hook.data || {}; hook.params.query = hook.params.query || {}; (0, _utils.checkContext)(hook, 'before', null, 'softDelete'); if (hook.params.query.$disableSoftDelete) { delete hook.params.query.$disableSoftDelete; return hook; } switch (hook.method) { case 'find': hook.params.query[deleteField] = { $ne: true }; return hook; case 'get': return throwIfItemDeleted(hook.id).then(function () { return hook; }); case 'create': return hook; case 'update': // fall through case 'patch': if (hook.id) { return throwIfItemDeleted(hook.id).then(function () { return hook; }); } hook.params.query[deleteField] = { $ne: true }; return hook; case 'remove': return Promise.resolve().then(function () { return hook.id ? throwIfItemDeleted(hook.id) : null; }).then(function () { hook.data[deleteField] = true; hook.params.query[deleteField] = { $ne: true }; hook.params.query.$disableSoftDelete = true; return service.patch(hook.id, hook.data, hook.params).then(function (result) { hook.result = result; return hook; }); }); } function throwIfItemDeleted(id) { return service.get(id, { query: { $disableSoftDelete: true } }).then(function (data) { if (data[deleteField]) { throw new errors.NotFound('Item has been soft deleted.'); } }).catch(function () { throw new errors.NotFound('Item not found.'); }); } >>>>>>> 529789d50613867eb4e9b77788dcf7a313297e4f }; }; /** * Hook to conditionally execute another hook. * * @param {Function|Promise|boolean} ifFcn - Predicate function(hook). * Execute hookFcn if result is truesy. * @param {Function|Promise} hookFcn - Hook function to execute. * @returns {Object} hook * * The predicate is called with hook as a param. * const isServer = hook => !hook.params.provider; * iff(isServer, hook.remove( ... )); * You can use a high order predicate to access other values. * const isProvider = provider => hook => hook.params.provider === provider; * iff(isProvider('socketio'), hook.remove( ... )); * * feathers-hooks will catch any errors from the predicate or hook Promises. */ var iff = exports.iff = function iff(ifFcn, hookFcn) { return function (hook) { var check = typeof ifFcn === 'function' ? ifFcn(hook) : !!ifFcn; if (!check) { return hook; } if (typeof check.then !== 'function') { return hookFcn(hook); // could be sync or async } return check.then(function (check1) { if (!check1) { return hook; } return hookFcn(hook); // could be sync or async }); }; }; /** * Predicate to check what called the service method. * * @param {string} [providers] - Providers permitted * 'server' = service method called from server, * 'external' = any external access, * string = that provider e.g. 'rest', * @returns {boolean} whether the service method was called by one of the [providers]. */ var isProvider = exports.isProvider = function isProvider() { for (var _len = arguments.length, providers = Array(_len), _key = 0; _key < _len; _key++) { providers[_key] = arguments[_key]; } if (!providers.length) { throw new errors.MethodNotAllowed('Calling iff() predicate incorrectly. (isProvider)'); } return function (hook) { // allow bind var hookProvider = (hook.params || {}).provider; return providers.some(function (provider) { return provider === hookProvider || provider === 'server' && !hookProvider || provider === 'external' && hookProvider; }); }; }; /** * Negate a predicate. * * @param {Function} predicate - returns a boolean or a promise resolving to a boolean. * @returns {boolean} the not of the predicate result. * * const hooks, { iff, isNot, isProvider } from 'feathers-hooks-common'; * iff(isNot(isProvider('rest')), hooks.remove( ... )); */ var isNot = exports.isNot = function isNot(predicate) { if (typeof predicate !== 'function') { throw new errors.MethodNotAllowed('Expected function as param. (isNot)'); } return function (hook) { var result = predicate(hook); // Should we pass a clone? (safety vs performance) if (!result || typeof result.then !== 'function') { return !result; } return result.then(function (result1) { return !result1; }); }; };
import React, { Component } from 'react' import { Card, CardActions, CardHeader, CardMedia, CardTitle, CardText } from 'material-ui/Card' import FlatButton from 'material-ui/FlatButton' import FloatingActionButton from 'material-ui/FloatingActionButton' import ContentAdd from 'material-ui/svg-icons/content/add' import moment from 'moment' import { connect } from 'react-redux' import { PROJECT, UI } from '../constants/actionTypes' import CreateTransactionModal from './CreateTransactionModal' import LinearProgress from 'material-ui/LinearProgress' class Project extends Component { constructor() { super() this.openTransactionModal = this.openTransactionModal.bind(this) } componentDidMount() { const { match: { params }, dispatch } = this.props dispatch({ type: PROJECT.REQUEST, payload: { id: params.id } }) } openTransactionModal() { const { dispatch, match: { params } } = this.props dispatch({ type: UI.CREATE_TRANSACTION_MODAL.SHOW, payload: { projectId: params.id } }) } render() { const { project } = this.props return ( <Card style={{ width: '400px', margin: '20px auto' }}> <CardMedia style={{ width: '100%', height: '400px', background: 'url("http://www.euneighbours.eu/sites/default/files/2017-01/placeholder.png") no-repeat 50% 50%', backgroundSize: '100% 100%' }} /> <CardTitle title={project.name} subtitle={moment(project.createdDate).format('DD/MM/YYYY')} /> <CardText> {project.description} <div style={{ margin: '10px 0' }}> Money Collected: {project.amount}/{project.limit} </div> <LinearProgress mode="determinate" value={(project.amount / project.limit) * 100} /> </CardText> <CreateTransactionModal /> <FloatingActionButton style={{ position: 'fixed', bottom: '20px', right: '20px' }} onClick={this.openTransactionModal} secondary={true} > <ContentAdd /> </FloatingActionButton> </Card> ) } } export default connect( state => ({ project: state.auth.currentProject }) )(Project)
(function(){ angular .module('ColumnStudy') .directive('csGraph', drawingDirectiveFactory); var GRAPH_LEFT = 0; var GRAPH_TOP = 0; var GRAPH_RIGHT = 200; var GRAPH_BOTTOM = 200; drawingDirectiveFactory.$inject = ['numberFilter','initialConditions','simulation']; function drawingDirectiveFactory(numberFilter,initialConditions,simulation){ return { scope: {}, link: link, templateUrl: 'script/directives/graph.html' }; function link(scope){ scope.time = { index: -1, value: null, count: 0 }; scope.aqueous = null; scope.sorbed = null; scope.$watch('time.index',onTimeIndexChanged); scope.$watch(function(){return simulation.data.length;},onResultsUpdated); scope.$on('valid-initial-conditions', onNewInitialConditions); onNewInitialConditions(); function onResultsUpdated(){ scope.time.count = simulation.data.length; if(scope.time.index===-1 && simulation.data.length > 0 ){ scope.time.index = 0; scope.time.value = simulation.data[scope.time.index].time; } else if (scope.time.index > simulation.data.length ) { scope.time.index = (simulation.data.length||0)-1; scope.time.value = scope.time.index > -1 ? simulation.data[scope.time.index].time : null; } } function onTimeIndexChanged(){ scope.time.value = scope.time.index > -1 ? simulation.data[scope.time.index].time : null; if(scope.time.index > -1){ var Caq = simulation.data[scope.time.index].Caq; var Cs = simulation.data[scope.time.index].Cs; var xOrigin = scope.layout.left; var yOrigin = scope.layout.bottom; var dxMult = scope.layout.xScale; var dyMult = scope.layout.yScale; var dx = scope.layout.xCell; var aq = []; for(var i=0;i<Caq.length;i++){ aq.push(xOrigin+dxMult*dx*i); aq.push(yOrigin+dyMult*[Caq[i]]); aq.push(xOrigin+dxMult*dx*(i+1)); aq.push(yOrigin+dyMult*[Caq[i]]); } var s = []; for(i=0;i<Cs.length;i++){ s.push(xOrigin+dxMult*dx*i); s.push(yOrigin+dyMult*[Cs[i]]); s.push(xOrigin+dxMult*dx*(i+1)); s.push(yOrigin+dyMult*[Cs[i]]); } scope.aqueous = 'M ' + xOrigin + ' ' + yOrigin + ' L ' + aq.join(' '); scope.sorbed = 'M ' + xOrigin + ' ' + yOrigin + ' L ' + s.join(' '); } else { scope.aqueous = null; scope.sorbed = null; } } function onNewInitialConditions(){ var ncx = Math.ceil(initialConditions.lenC / initialConditions.lenSoil) * 100; if(ncx === 0) { ncx = 1; } var dx = initialConditions.lenC / ncx ; var nx = Math.floor(initialConditions.lenSoil / dx) + 1; var dxMax = dx * nx; var maxCaq = (initialConditions.massC / initialConditions.lenC) / (initialConditions.rhoB * initialConditions.Kd + initialConditions.n); // (mg/l) var maxCs = initialConditions.Kd * maxCaq; // (mg/kg) var dyMax = maxCaq; // (mg/l) or (mg/kg) if( dyMax < maxCs ) { dyMax = maxCs; // (mg/l) or (mg/kg) } dyMax = 0.1*(Math.ceil(dyMax*10.0)); // (mg/l) or (mg/kg) var sz = calculateTextSize(numberFilter(dyMax,1)); var tm = calculateTextSize('M'); var textHeight = tm.height; var textWidth = tm.width; var xOrigin = GRAPH_LEFT + sz.width + textWidth; var yOrigin = GRAPH_BOTTOM - 3 * textHeight; var xTextOrigin = GRAPH_LEFT + sz.width + textWidth / 3; var yTextOrigin = GRAPH_BOTTOM - 7 * textHeight / 5; var graphWidth = (GRAPH_RIGHT - GRAPH_LEFT) - sz.width - 2 * textWidth; var graphHeight = (GRAPH_BOTTOM - GRAPH_TOP) - 4.8 * textHeight; var dxMult = graphWidth / dxMax; var dyMult = 0.0 - graphHeight / dyMax; var dyLabel = Math.max(0.1,dyMax/(2*Math.floor(graphHeight/(3*textHeight/2)/2))); var yLabels = []; for(var y = 0; y <= dyMax; y += dyLabel ) { yLabels.push({ x: xTextOrigin, y: yOrigin + (dyMult*y) + 0.3*textHeight, text: numberFilter(y,1) }); } var dxLabel = Math.max(0.1,dxMax/(2*Math.floor(graphWidth/(1.5*(calculateTextSize(numberFilter(dxMax,1)).width))/2))); var xLabels = []; for(var x = 0; x <= dxMax; x += dxLabel ) { xLabels.push({ x: xOrigin + dxMult*x, y: yTextOrigin, text: numberFilter(x,1) }); } var yTicks = []; var yTickLeft = xOrigin - textWidth / 3; var yTickRight = xOrigin; var dyTick = dyLabel / 4.0; for(y = 0; y <= dyMax; y += dyTick ){ yTicks.push(yOrigin+dyMult*y); } var xTicks = []; var xTickTop = yOrigin; var xTickBottom = yOrigin + textHeight/3; var dxTick = dxLabel / 2.0; for(x = 0; x <= dxMax; x += dxTick ){ xTicks.push(xOrigin+dxMult*x); } scope.layout = { top: yOrigin - graphHeight, bottom: yOrigin, left: xOrigin, right: xOrigin + graphWidth, xScale: dxMult, yScale: dyMult, xCell: dx, yAxisLabelX: GRAPH_LEFT, yAxisLabelY: 0.8 * textHeight, yLabels: yLabels, yTickLeft: yTickLeft, yTickRight: yTickRight, yTicks: yTicks, xAxisLabelX: xOrigin + 0.5 * graphWidth, xAxisLabelY: yOrigin + 2.6 * textHeight, xLabels: xLabels, xTickTop: xTickTop, xTickBottom: xTickBottom, xTicks: xTicks, soluteLabelX: GRAPH_RIGHT, soluteLabelY: GRAPH_TOP + textHeight, sorbedLabelX: GRAPH_RIGHT, sorbedLabelY: GRAPH_TOP + 2 * textHeight }; scope.time.index = -1; scope.time.value = null; scope.time.count = 0; } function calculateTextSize(value){ var text = document.createElementNS("http://www.w3.org/2000/svg", "text"); text.setAttributeNS(null,"x",0); text.setAttributeNS(null,"y",0); text.setAttributeNS(null,"font-size","8px"); text.appendChild(document.createTextNode(value)); var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); svg.appendChild(text); document.documentElement.appendChild(svg); var box = text.getBBox(); var size = { width: box.width, height: box.height }; document.documentElement.removeChild(svg); return size; } } } })();
/* * This file is part of the EcoLearnia platform. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * EcoLearnia v0.0.1 * * @fileoverview * This file includes definition of HapiResource. * * @author Young Suk Ahn Park * @date 2/15/15 */ var Sequelize = require('sequelize'); var logger = require('ecofyjs-logger-facade'); // Declararation of namespace for internal module use var internals = {}; internals.SequelizeUtils = {}; /** * connect * * @param {string} connSgtring 'mysql://user:[email protected]:9821/dbname' */ internals.SequelizeUtils.connect = function(connString) { //var sequelize = new Sequelize(connString); internals.sequelize = new Sequelize('eco_learnia', 'ecolearnia', 'eco', { dialect: "mysql", // or 'sqlite', 'postgres', 'mariadb' port: 3306, // or 5432 (for postgres) }); // Parameterize the path internals.models = require('../models/sequelize/index.js').loadModels(internals.sequelize); return internals.sequelize; } /** * returns the underlying connection * @return {Object} conection */ internals.SequelizeUtils.getConnection = function () { return internals.sequelize; } /** * getModel * @param {string} name - The name of the model. Not used in * @param {string} schema - The schema reference */ internals.SequelizeUtils.getModel = function (name, schema) { return internals.models[name]; } module.exports.SequelizeUtils = internals.SequelizeUtils;
'use strict'; // Production specific configuration // ================================= module.exports = { // Server IP ip: process.env.OPENSHIFT_NODEJS_IP || process.env.IP || undefined, // Server port port: process.env.OPENSHIFT_NODEJS_PORT || process.env.PORT || 8080, // MongoDB connection options mongo: { uri: process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || process.env.OPENSHIFT_MONGODB_DB_URL+process.env.OPENSHIFT_APP_NAME || 'mongodb://localhost/eventbrite' } };
/** @jsx React.DOM */ var Article = React.createClass({displayName: 'Article', getInitialState: function() { return { date: timeSince(this.props.data.date) } }, tick: function() { this.setState({ date: timeSince(this.props.data.date) }); }, componentDidMount: function() { this.interval = setInterval(this.tick, 1000); }, componentWillUnmount: function() { clearInterval(this.interval); }, render: function() { var articleStyle = { backgroundImage: 'url(' + this.props.data.image + ')' } console.log(this.props.data.image); return ( React.DOM.div({className: "article"}, React.DOM.h1({style: articleStyle }, this.props.data.title), React.DOM.p(null, this.props.data.author), React.DOM.p(null, this.state.date, " ago"), React.DOM.p(null, this.props.data.description) ) ); } });
angular.module( 'sample.login', [ 'auth0' ]) .controller( 'LoginCtrl', function HomeController( $scope, auth, $location ) { $scope.login = function() { auth.signin({ // Get the refresh token offline_mode: true }); } });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _libs = require('../../libs'); var _utils = require('../../libs/utils'); var _BasePicker2 = require('./BasePicker'); var _BasePicker3 = _interopRequireDefault(_BasePicker2); var _TimePanel = require('./panel/TimePanel'); var _TimePanel2 = _interopRequireDefault(_TimePanel); var _constants = require('./constants'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function converSelectRange(props) { var selectableRange = []; if (props.selectableRange) { var ranges = props.selectableRange; var parser = _constants.TYPE_VALUE_RESOLVER_MAP.datetimerange.parser; var format = _constants.DEFAULT_FORMATS.timerange; ranges = Array.isArray(ranges) ? ranges : [ranges]; selectableRange = ranges.map(function (range) { return parser(range, format); }); } return selectableRange; } var TimePicker = function (_BasePicker) { _inherits(TimePicker, _BasePicker); _createClass(TimePicker, null, [{ key: 'propTypes', // why this is used, goto: http://exploringjs.com/es6/ch_classes.html get: function get() { return Object.assign({ // '18:30:00 - 20:30:00' // or ['09:30:00 - 12:00:00', '14:30:00 - 18:30:00'] selectableRange: _libs.PropTypes.oneOfType([_libs.PropTypes.string, _libs.PropTypes.arrayOf(_libs.PropTypes.string)]) }, _BasePicker3.default.propTypes); } }, { key: 'defaultProps', get: function get() { return Object.assign({}, _BasePicker3.default.defaultProps); } }]); function TimePicker(props) { _classCallCheck(this, TimePicker); var _this = _possibleConstructorReturn(this, (TimePicker.__proto__ || Object.getPrototypeOf(TimePicker)).call(this, props, 'time', {})); _this._onSelectionChange = (0, _utils.debounce)(_this.onSelectionChange.bind(_this), 200); return _this; } _createClass(TimePicker, [{ key: 'onSelectionChange', value: function onSelectionChange(start, end) { this.refs.inputRoot.refs.input.setSelectionRange(start, end); this.refs.inputRoot.refs.input.focus(); } }, { key: 'pickerPanel', value: function pickerPanel(state, props) { var _this2 = this; return _react2.default.createElement(_TimePanel2.default, _extends({}, props, { currentDate: state.value, onCancel: function onCancel() { return _this2.setState({ pickerVisible: false }); }, onPicked: this.onPicked.bind(this), onSelectRangeChange: this._onSelectionChange, selectableRange: converSelectRange(props) })); } }]); return TimePicker; }(_BasePicker3.default); var _default = TimePicker; exports.default = _default; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(converSelectRange, 'converSelectRange', 'src/date-picker/TimePicker.jsx'); __REACT_HOT_LOADER__.register(TimePicker, 'TimePicker', 'src/date-picker/TimePicker.jsx'); __REACT_HOT_LOADER__.register(_default, 'default', 'src/date-picker/TimePicker.jsx'); }(); ;
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = undefined; var _defineProperty2 = require('babel-runtime/helpers/defineProperty'); var _defineProperty3 = _interopRequireDefault(_defineProperty2); var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = require('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); var _CardHeader = require('./CardHeader'); var _CardHeader2 = _interopRequireDefault(_CardHeader); var _CardBody = require('./CardBody'); var _CardBody2 = _interopRequireDefault(_CardBody); var _CardFooter = require('./CardFooter'); var _CardFooter2 = _interopRequireDefault(_CardFooter); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var Card = function (_React$Component) { (0, _inherits3["default"])(Card, _React$Component); function Card() { (0, _classCallCheck3["default"])(this, Card); return (0, _possibleConstructorReturn3["default"])(this, _React$Component.apply(this, arguments)); } Card.prototype.render = function render() { var _classNames; var _props = this.props, prefixCls = _props.prefixCls, full = _props.full, children = _props.children, className = _props.className; var wrapCls = (0, _classnames2["default"])((_classNames = {}, (0, _defineProperty3["default"])(_classNames, prefixCls, true), (0, _defineProperty3["default"])(_classNames, prefixCls + '-full', full), (0, _defineProperty3["default"])(_classNames, className, className), _classNames)); return _react2["default"].createElement("div", { className: wrapCls }, children); }; return Card; }(_react2["default"].Component); exports["default"] = Card; Card.defaultProps = { prefixCls: 'am-card', full: false }; Card.Header = _CardHeader2["default"]; Card.Body = _CardBody2["default"]; Card.Footer = _CardFooter2["default"]; module.exports = exports['default'];
var answer = prompt("Do you like waffles?!"); switch(answer) { case 'Yes I like waffles!': console.log("Let's be friends!"); break; case 'Yes': console.log("Right on! Have some waffles!"); break; case 'yes': console.log("Here's some syrup"); break; case 'y': console.log("Are you sure you like waffles?"); break; default: console.log("Then shoo! This is not for you."); }
// Load the http module to create an http server. var http = require('http'); var request = require('request'); // Configure our HTTP server to respond with Hello World to all requests. var res = "Inicializando"; var server = http.createServer(function (request, response) { res.setHeader('Access-Control-Allow-Headers', 'authorization, content-type'); getTemp("temperature"); response.writeHead(200, {"Content-Type": "text/plain"}); response.end("Hello World: " + res); }); // Listen on port 8000, IP defaults to 127.0.0.1 server.listen(8000); // Put a friendly message on the terminal console.log("Server running at http://127.0.0.1:8000/"); function getTemp(q){ request.post( 'http://test:[email protected]:15672/api/queues/martinMQT/temperature/get', { json: { encoding: 'auto', requeue: true, count: 1 } }, function (error, response, body) { if (!error && response.statusCode == 200) { let info = body[0]; if (info == null) { res = '{"err":"no info available"}'; } else { res = body[0]['payload']; } } } ); };
define([ 'underscore', 'chaplin', 'orosync/js/sync', 'oroui/js/mediator', 'oroui/js/messenger', 'orotranslation/js/translator' ], function(_, Chaplin, sync, mediator, messenger, __) { 'use strict'; /** * Content Management * * component: * - provides API of page content caching; * - stores content tags for pages; * - listing sever messages for content update; * - shows notification for outdated content; * * @export oronavigation/js/content-manager * @name oronavigation.contentManager * @type {Object} */ var contentManager; /** * Hash object with relation page URL -> its content * @type {Object.<string, Object>} */ var pagesCache = {}; /** * Information about current page (URL and tags for current page) * @type {Object} * { * tags: {Array}, * path: {string}, * query: {string}, * page: {Object.<string, *>}, // object with page content * state: {Object.<string, *>} // each page component can cache own state * } */ var current = { // collect tags and state, even if the page is not initialized tags: [], state: {} }; /** * User ID needed to check whenever update person is the same user * @type {String} */ var currentUser = null; /** * Notifier object * @type {{close: function()}} */ var notifier; /** * Pages that has been out dated * @type {Object} */ var outdatedPageHandlers = {}; /** * On URL changes clean up tags collection and set a new URL as current * * @param {string} path * @param {string} query */ function changeUrl(path, query) { var item; item = pagesCache[path] || {}; _.extend(item, { path: path, query: query, tags: [] }); // define default page and state _.defaults(item, { page: null, state: {} }); // there's no previous page, then collected tags and state belong to current page if (current.path === null || current.path === void 0) { _.extend(item.state, current.state); item.tags = current.tags; } current = item; } /** * Default callback on content outdated * * shows notification of outdated content * * @param {string} path */ function defaultCallback(path) { var page = contentManager.get(path); var title = page ? '<b>' + page.titleShort + '</b>' : 'the'; if (notifier) { notifier.close(); } notifier = messenger.notificationMessage( 'warning', __('navigation.message.content.outdated', {title: title}) ); } /** * Tags come from server in following structure * [ * { tagname: TAG, username: AUTHOR}, * ... * { tagname: TAG2, username: AUTHOR}, * ... * ] * * @param {string} tags * @return [] */ function prepareTags(tags) { tags = _.reject(JSON.parse(tags), function(tag) { return (tag.username || null) === currentUser; }); return _.pluck(tags, 'tagname'); } /** * Page refresh handler, check whenever * * @param {string} path * @param {Array} callbacks */ function refreshHandler(path, callbacks) { if (path === current.path) { _.each(callbacks, function(callback) { callback(path); }); } } /** * Handler of content update message from server * * @param {string} tags */ function onUpdate(tags) { var pages; tags = prepareTags(tags); pages = [current].concat(_.values(pagesCache)); _.each(pages, function(page) { var handler; var callbacks = []; var items = page.tags; var path = page.path; // collect callbacks for outdated contents _.each(items, function(options) { if (_.intersection(options.tags, tags).length) { callbacks.push(options.callback || defaultCallback); } }); if (!callbacks.length) { return false; } // filter only unique callbacks to protects notification duplication callbacks = _.uniq(callbacks); if (path === current.path) { // current page is outdated - execute all callbacks _.each(callbacks, function(callback) { callback(path); }); } else { if (!outdatedPageHandlers[path]) { handler = _.partial(refreshHandler, path, callbacks); outdatedPageHandlers[path] = handler; mediator.on('page:update', handler); } } mediator.trigger('content-manager:content-outdated', { path: path, isCurrentPage: path === current.path }); }); } // handles page request mediator.on('page:request', function(args) { var path = args.route.path !== null && args.route.path !== void 0 ? args.route.path : current.path; var query = args.route.query !== null && args.route.query !== void 0 ? args.route.query : current.query; changeUrl(path, query); if (notifier) { notifier.close(); } }); // handles page update mediator.on('page:update', function(page, args) { var options; current.page = page; options = args.options; // if it's forced page reload and page was in a cache, update it if (options.cache === true || (options.force === true && contentManager.get())) { contentManager.add(); } }); // subscribes to data update channel sync.subscribe('oro/data/update', onUpdate); /** * Takes url, picks out path and trims root part * * @param {string} url * @returns {*} */ function fetchPath(url) { var _ref; // it's anchor address inside current page if (url[0] === '#') { url = current.path; } _ref = url.split('#')[0].split('?'); return mediator.execute('retrievePath', _ref[0]); } contentManager = { /** * Setups content management component, sets initial URL * * @param {string} path * @param {string} query * @param {string} userName */ init: function(path, query, userName) { changeUrl(path, query); currentUser = userName; }, /** * Stores content related tags for current page * * @param {Array.<string>} tags list of tags * @param {function(string)=} callback is optional, * handler which will be executed on content by the tags gets outdated */ tagContent: function(tags, callback) { var obj = { tags: _.isArray(tags) ? tags : [tags] }; if (callback) { obj.callback = callback; } current.tags.push(obj); mediator.trigger('content-manager:content-tagged', {current: current.tags, added: obj}); }, /** * Clear cached data, by default for current url * * @param {string=} path part of URL */ remove: function(path) { if (_.isUndefined(path)) { path = current.path; } else { path = fetchPath(path); } delete pagesCache[path]; if (outdatedPageHandlers[path]) { mediator.off('page:update', outdatedPageHandlers[path]); delete outdatedPageHandlers[path]; } }, /** * Add current page to permanent cache */ add: function() { var path; path = current.path; pagesCache[path] = current; }, /** * Fetches cache data for url, by default for current url * * @param {string=} path part of URL * @return {Object|boolean} */ get: function(path) { path = _.isUndefined(path) ? current.path : fetchPath(path); return pagesCache[path] || undefined; }, /** * Return information about current page * * @return {Object} */ getCurrent: function() { return current; }, /** * Saves state of a page component in a cache * * @param {string} key * @param {*} value * @param {string=} hash */ saveState: function(key, value, hash) { if (value !== null && value !== void 0) { current.state[key] = value; } else { delete current.state[key]; } if (_.isUndefined(hash)) { // hash is not defined, there's nothing else to do return; } this.changeUrlParam(key, hash); mediator.trigger('pagestate:change'); }, /** * Changes url for current page * * @param {string} url * @param {Object} options */ changeUrl: function(url, options) { options = options || {}; var _ref = url.split('?'); current.path = _ref[0]; current.query = _ref[1] || ''; var route = _.pick(current, ['path', 'query']); mediator.execute('changeRoute', route, options); }, /** * Updates URL parameter for current page * * @param {string} param * @param {string} value */ changeUrlParam: function(param, value) { var route; var query = Chaplin.utils.queryParams.parse(current.query); if (query[param] === value || ( (query[param] === null || query[param] === void 0) && (value === null || value === void 0) )) { // there's nothing to change in query, skip query update and redirect return; } if (value !== null) { // if there's new value, update query query[param] = value; } else { // if there's no new value, delete query part delete query[param]; } query = Chaplin.utils.queryParams.stringify(query); current.query = query; route = _.pick(current, ['path', 'query']); mediator.execute('changeRoute', route, {replace: true}); }, /** * Fetches state of a page component from cached page * * @param {string} key * @return {*} */ fetchState: function(key) { return current.state[key]; }, /** * Check if state's GET parameter (pair key and hash) reflects current URL * * @param {string} key * @param {string} hash */ checkState: function(key, hash) { var query; query = Chaplin.utils.queryParams.parse(current.query); return query[key] === hash || query[key] === void 0 && hash === null; }, /** * Retrieve meaningful part of path from url and compares it with reference path * (assumes that URL contains only path and query) * * @param {string} url * @param {string=} refPath * @returns {boolean} */ compareUrl: function(url, refPath) { if (refPath === null || refPath === void 0) { refPath = current.path; } return fetchPath(refPath) === fetchPath(url); }, /** * Combines route URL for current page * * @returns {script} */ currentUrl: function() { var url; url = mediator.execute('combineRouteUrl', current); return url; }, /** * Prevents storing current page in cache */ cacheIgnore: function() { mediator.once('page:beforeChange', function(oldRoute) { contentManager.remove(oldRoute.path); }); } }; return contentManager; });
var xmlDoc = null; var xslDoc = null; var xslObj = null; var arrScriptFiles = ["includes/XML.js", "includes/sfwobjects.js", "includes/sfwmain.js", "includes/classes.js", "includes/Events.js", "includes/Dialog.js", "includes/Moveable.js" ]; window.onload = function mini_startup() { cache_document_parts(); var qstring = window.location.search; function make_sfw_tag(name) { return "sfw_" + name + "_match"; } function modify_xsldoc(xsldoc) { var ss = xsldoc.documentElement; var rootmatch = ss.selectSingleNode("xsl:template[@match='/']"); var nhtml = rootmatch.selectSingleNode("html:html"); function make_alias(name) { var node = nhtml.selectSingleNode("html:" + name); if (node) { var nl = node.selectNodes("*"); var newnode = add_namespace_el("template",nsXSL,ss,rootmatch,xsldoc); newnode.setAttribute("match", make_sfw_tag(name)); for (var i=0, stop=nl.length; i<stop; ++i) newnode.appendChild(nl[i]); alert(serialize(newnode.parentNode)); } } make_alias("head"); make_alias("body"); alert(serialize(rootmatch)); } function replace_html_part(name) { var docel = xmlDoc.documentElement; var target = document[name]; var node = xmlDoc.createElement(make_sfw_tag(name)); docel.appendChild(node); xslObj.transformReplace(target, node); } function translate_page() { console.log("Ready to translate the page."); replace_html_part("head"); replace_html_part("body"); cache_document_parts(); prepare_page(); } function got_xsldoc(xsldoc) { xslDoc = xsldoc; console.log("Got the XSL document"); modify_xsldoc(xsldoc); xslObj = new XSL(xsldoc, translate_page); } function got_xmldoc(xmldoc) { xmlDoc = xmldoc; var xsl = xmldoc.selectSingleNode("/processing-instruction('xml-stylesheet')"); if (xsl) { var m = /href=\"([^\"]+)\"/.exec(xsl.data); if (m) xhr_get(m[1], got_xsldoc); } } function scripts_loaded() { xhr_default_req_header("SFW_DATA_REQUEST", "true"); xhr_get(qstring, got_xmldoc); } load_scripts(arrScriptFiles, scripts_loaded); }; function cache_document_parts() { var nl; if (!"html" in document || !document.html) document.html = document.documentElement; if (!"head" in document || !document.head) document.head = ((nl=document.getElementsByTagName("head")) && nl.length) ? nl[0] : null; if (!"body" in document || !document.body) { var n = ((nl=document.getElementsByTagName("body")) && nl.length) ? nl[0] : null; document.body = n; } } function load_scripts(arrFiles, callback) { var host = document.head; // var arrScripts = ["includes/XML.js"]; var ndx = 0; function get_next() { if (ndx < arrScripts.length) { var s = document.createElement("script"); s.addEventListener("load", get_next, false); s.src = arrScripts[ndx++]; host.appendChild(s); } else { console.log("Finished with javascript adds."); if (callback) callback(); } } get_next(); }
(function (){ 'use strict'; angular.module('eliteApp').controller('locationMapCtrl', ['$stateParams', 'eliteApi', locationMapCtrl]); function locationMapCtrl($stateParams, eliteApi) { var vm = this; vm.locationId = Number($stateParams.id); eliteApi.getLeagueData().then(function(data) { vm.location = _.find(data.locations, { id: vm.locationId }); vm.locationName = vm.location.name; vm.marker = { id: 1, latitude: vm.location.latitude, longitude: vm.location.longitude, title: vm.location.name + '<br />(Toque para direções)', showWindow: true, options: { labelContent: vm.location.name + '<br />(Toque para direções)', labelAnchor: google.maps.Point(10, -8), labelClass: 'marker-labels' } }; vm.map = { center: { latitude: vm.location.latitude, longitude: vm.location.longitude }, zoom: 12 }; }); vm.locationClicked = function(marker) { console.log('clicked marker:', marker); window.location = 'geo:' + marker.latitude +','+ marker.longitude + ';u=35'; } }; })();
export class Declaration { constructor (name, ext, pairs) { this._name = name; this._options = {}; this._extension = ext; pairs.map((item) => this._options[item.key] = item.value); } get name () { return this._name; } get extension () { return this._extension; } option (key) { return this._options[key]; } }
/*eslint-env browser, phantomjs, es6, mocha, jasmine*/ /*eslint-disable no-unused-expressions*/ import React from 'react'; import ReactDOM from 'react-dom'; import ReactTestUtils from 'react-addons-test-utils'; import ProgressBarView from './ProgressBar'; describe('(view) ProgressBar', () => { it('Should render a progress bar component with default props using bootstrap classes', () => { const component = ReactTestUtils.renderIntoDocument(<ProgressBarView/>); expect(component.props).to.deep.equal({progress: 0, showText: false}); let node = ReactDOM.findDOMNode(component); node = node.getElementsByClassName('progress'); expect(node.length).to.equal(1); node = node[0].getElementsByClassName('progress-bar'); expect(node.length).to.equal(1); node = node[0]; expect(node.style.width).to.equal('0%'); expect(node.innerHTML).to.equal(''); }); it('Should render a progress bar at 50% width of component', () => { const component = ReactTestUtils.renderIntoDocument(<ProgressBarView progress={50}/>); expect(component.props.progress).to.equal(50); let node = ReactDOM.findDOMNode(component); node = node.getElementsByClassName('progress-bar')[0]; expect(node.style.width).to.equal('50%'); expect(node.innerHTML).to.equal(''); }); it('Should render progress bar at 80% width and include inner text', () => { const component = ReactTestUtils.renderIntoDocument(<ProgressBarView progress={80} showText/>); expect(component.props).to.deep.equal({progress: 80, showText: true}); let node = ReactDOM.findDOMNode(component); node = node.getElementsByClassName('progress-bar')[0]; expect(node.style.width).to.equal('80%'); expect(node.innerHTML).to.equal('80%'); }) });
import { moduleForModel, test } from 'ember-qunit'; moduleForModel('spacedog-schema', 'Unit | Serializer | spacedog schema', { // Specify the other units that are required for this test. needs: ['serializer:spacedog-schema', 'model:tsygan@spacedog-schemafield'] }); // Replace this with your real tests. test('it serializes records', function(assert) { let record = this.subject(); let serializedRecord = record.serialize(); assert.ok(serializedRecord); });
/* This notice must be untouched at all times. wz_tooltip.js v. 4.12 The latest version is available at http://www.walterzorn.com or http://www.devira.com or http://www.walterzorn.de Copyright (c) 2002-2007 Walter Zorn. All rights reserved. Created 1.12.2002 by Walter Zorn (Web: http://www.walterzorn.com ) Last modified: 13.7.2007 Easy-to-use cross-browser tooltips. Just include the script at the beginning of the <body> section, and invoke Tip('Tooltip text') from within the desired HTML onmouseover eventhandlers. No container DIV, no onmouseouts required. By default, width of tooltips is automatically adapted to content. Is even capable of dynamically converting arbitrary HTML elements to tooltips by calling TagToTip('ID_of_HTML_element_to_be_converted') instead of Tip(), which means you can put important, search-engine-relevant stuff into tooltips. Appearance of tooltips can be individually configured via commands passed to Tip() or TagToTip(). Tab Width: 4 LICENSE: LGPL This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For more details on the GNU Lesser General Public License, see http://www.gnu.org/copyleft/lesser.html */ var config = new Object(); //=================== GLOBAL TOOPTIP CONFIGURATION =========================// var tt_Debug = false // false or true - recommended: false once you release your page to the public var tt_Enabled = true // Allows to (temporarily) suppress tooltips, e.g. by providing the user with a button that sets this global variable to false var TagsToTip = false // false or true - if true, the script is capable of converting HTML elements to tooltips // For each of the following config variables there exists a command, which is // just the variablename in uppercase, to be passed to Tip() or TagToTip() to // configure tooltips individually. Individual commands override global // configuration. Order of commands is arbitrary. // Example: onmouseover="Tip('Tooltip text', LEFT, true, BGCOLOR, '#FF9900', FADEIN, 400)" config. Above = false // false or true - tooltip above mousepointer? config. BgColor = '#E4E7FF' // Background color config. BgImg = '' // Path to background image, none if empty string '' config. BorderColor = '#002299' config. BorderStyle = 'solid' // Any permitted CSS value, but I recommend 'solid', 'dotted' or 'dashed' config. BorderWidth = 1 config. CenterMouse = false // false or true - center the tip horizontally below (or above) the mousepointer config. ClickClose = false // false or true - close tooltip if the user clicks somewhere config. CloseBtn = false // false or true - closebutton in titlebar config. CloseBtnColors = ['#990000', '#FFFFFF', '#DD3333', '#FFFFFF'] // [Background, text, hovered background, hovered text] - use empty strings '' to inherit title colors config. CloseBtnText = '&nbsp;X&nbsp;' // Close button text (may also be an image tag) config. CopyContent = true // When converting a HTML element to a tooltip, copy only the element's content, rather than converting the element by its own config. Delay = 400 // Time span in ms until tooltip shows up config. Duration = 0 // Time span in ms after which the tooltip disappears; 0 for infinite duration config. FadeIn = 0 // Fade-in duration in ms, e.g. 400; 0 for no animation config. FadeOut = 0 config. FadeInterval = 30 // Duration of each fade step in ms (recommended: 30) - shorter is smoother but causes more CPU-load config. Fix = null // Fixated position - x- an y-oordinates in brackets, e.g. [210, 480], or null for no fixation config. FollowMouse = true // false or true - tooltip follows the mouse config. FontColor = '#000044' config. FontFace = 'Verdana,Geneva,sans-serif' config. FontSize = '8pt' // E.g. '9pt' or '12px' - unit is mandatory config. FontWeight = 'normal' // 'normal' or 'bold'; config. Left = false // false or true - tooltip on the left of the mouse config. OffsetX = 14 // Horizontal offset of left-top corner from mousepointer config. OffsetY = 8 // Vertical offset config. Opacity = 100 // Integer between 0 and 100 - opacity of tooltip in percent config. Padding = 3 // Spacing between border and content config. Shadow = false // false or true config. ShadowColor = '#C0C0C0' config. ShadowWidth = 5 config. Sticky = false // Do NOT hide tooltip on mouseout? false or true config. TextAlign = 'left' // 'left', 'right' or 'justify' config. Title = '' // Default title text applied to all tips (no default title: empty string '') config. TitleAlign = 'left' // 'left' or 'right' - text alignment inside the title bar config. TitleBgColor = '' // If empty string '', BorderColor will be used config. TitleFontColor = '#ffffff' // Color of title text - if '', BgColor (of tooltip body) will be used config. TitleFontFace = '' // If '' use FontFace (boldified) config. TitleFontSize = '' // If '' use FontSize config. Width = 0 // Tooltip width; 0 for automatic adaption to tooltip content //======= END OF TOOLTIP CONFIG, DO NOT CHANGE ANYTHING BELOW ==============// //====================== PUBLIC ============================================// function Tip() { var arg = arguments[0]; arg = arg.replace(/&lt;/g, "<"); arg = arg.replace(/&gt;/g, ">"); arguments[0] = arg; tt_Tip(arguments, null); } function TagToTip() { if(TagsToTip) { var t2t = tt_GetElt(arguments[0]); if(t2t) tt_Tip(arguments, t2t); } } //================== PUBLIC EXTENSION API ==================================// // Extension eventhandlers currently supported: // OnLoadConfig, OnCreateContentString, OnSubDivsCreated, OnShow, OnMoveBefore, // OnMoveAfter, OnHideInit, OnHide, OnKill var tt_aElt = new Array(10), // Container DIV, outer title & body DIVs, inner title & body TDs, closebutton SPAN, shadow DIVs, and IFRAME to cover windowed elements in IE tt_aV = new Array(), // Caches and enumerates config data for currently active tooltip tt_sContent, // Inner tooltip text or HTML tt_scrlX = 0, tt_scrlY = 0, tt_musX, tt_musY, tt_over, tt_x, tt_y, tt_w, tt_h; // Position, width and height of currently displayed tooltip function tt_Extension() { tt_ExtCmdEnum(); tt_aExt[tt_aExt.length] = this; return this; } function tt_SetTipPos(x, y) { var css = tt_aElt[0].style; tt_x = x; tt_y = y; css.left = x + "px"; css.top = y + "px"; if(tt_ie56) { var ifrm = tt_aElt[tt_aElt.length - 1]; if(ifrm) { ifrm.style.left = css.left; ifrm.style.top = css.top; } } } function tt_Hide() { if(tt_db && tt_iState) { if(tt_iState & 0x2) { tt_aElt[0].style.visibility = "hidden"; tt_ExtCallFncs(0, "Hide"); } tt_tShow.EndTimer(); tt_tHide.EndTimer(); tt_tDurt.EndTimer(); tt_tFade.EndTimer(); if(!tt_op && !tt_ie) { tt_tWaitMov.EndTimer(); tt_bWait = false; } if(tt_aV[CLICKCLOSE]) tt_RemEvtFnc(document, "mouseup", tt_HideInit); tt_AddRemOutFnc(false); tt_ExtCallFncs(0, "Kill"); // In case of a TagToTip tooltip, hide converted DOM node and // re-insert it into document if(tt_t2t && !tt_aV[COPYCONTENT]) { tt_t2t.style.display = "none"; tt_MovDomNode(tt_t2t, tt_aElt[6], tt_t2tDad); } tt_iState = 0; tt_over = null; tt_ResetMainDiv(); if(tt_aElt[tt_aElt.length - 1]) tt_aElt[tt_aElt.length - 1].style.display = "none"; } } function tt_GetElt(id) { return(document.getElementById ? document.getElementById(id) : document.all ? document.all[id] : null); } function tt_GetDivW(el) { return(el ? (el.offsetWidth || el.style.pixelWidth || 0) : 0); } function tt_GetDivH(el) { return(el ? (el.offsetHeight || el.style.pixelHeight || 0) : 0); } function tt_GetScrollX() { return(window.pageXOffset || (tt_db ? (tt_db.scrollLeft || 0) : 0)); } function tt_GetScrollY() { return(window.pageYOffset || (tt_db ? (tt_db.scrollTop || 0) : 0)); } function tt_GetClientW() { return(document.body && (typeof(document.body.clientWidth) != tt_u) ? document.body.clientWidth : (typeof(window.innerWidth) != tt_u) ? window.innerWidth : tt_db ? (tt_db.clientWidth || 0) : 0); } function tt_GetClientH() { // Exactly this order seems to yield correct values in all major browsers return(document.body && (typeof(document.body.clientHeight) != tt_u) ? document.body.clientHeight : (typeof(window.innerHeight) != tt_u) ? window.innerHeight : tt_db ? (tt_db.clientHeight || 0) : 0); } function tt_GetEvtX(e) { return (e ? ((typeof(e.pageX) != tt_u) ? e.pageX : (e.clientX + tt_scrlX)) : 0); } function tt_GetEvtY(e) { return (e ? ((typeof(e.pageY) != tt_u) ? e.pageY : (e.clientY + tt_scrlY)) : 0); } function tt_AddEvtFnc(el, sEvt, PFnc) { if(el) { if(el.addEventListener) el.addEventListener(sEvt, PFnc, false); else el.attachEvent("on" + sEvt, PFnc); } } function tt_RemEvtFnc(el, sEvt, PFnc) { if(el) { if(el.removeEventListener) el.removeEventListener(sEvt, PFnc, false); else el.detachEvent("on" + sEvt, PFnc); } } //====================== PRIVATE ===========================================// var tt_aExt = new Array(), // Array of extension objects tt_db, tt_op, tt_ie, tt_ie56, tt_bBoxOld, // Browser flags tt_body, tt_flagOpa, // Opacity support: 1=IE, 2=Khtml, 3=KHTML, 4=Moz, 5=W3C tt_maxPosX, tt_maxPosY, tt_iState = 0, // Tooltip active |= 1, shown |= 2, move with mouse |= 4 tt_opa, // Currently applied opacity tt_bJmpVert, // Tip above mouse (or ABOVE tip below mouse) tt_t2t, tt_t2tDad, // Tag converted to tip, and its parent element in the document tt_elDeHref, // The tag from which Opera has removed the href attribute // Timer tt_tShow = new Number(0), tt_tHide = new Number(0), tt_tDurt = new Number(0), tt_tFade = new Number(0), tt_tWaitMov = new Number(0), tt_bWait = false, tt_u = "undefined"; function tt_Init() { tt_MkCmdEnum(); // Send old browsers instantly to hell if(!tt_Browser() || !tt_MkMainDiv()) return; tt_IsW3cBox(); tt_OpaSupport(); tt_AddEvtFnc(document, "mousemove", tt_Move); // In Debug mode we search for TagToTip() calls in order to notify // the user if they've forgotten to set the TagsToTip config flag if(TagsToTip || tt_Debug) tt_SetOnloadFnc(); tt_AddEvtFnc(window, "scroll", function() { tt_scrlX = tt_GetScrollX(); tt_scrlY = tt_GetScrollY(); if(tt_iState && !(tt_aV[STICKY] && (tt_iState & 2))) tt_HideInit(); } ); // Ensure the tip be hidden when the page unloads tt_AddEvtFnc(window, "unload", tt_Hide); tt_Hide(); } // Creates command names by translating config variable names to upper case function tt_MkCmdEnum() { var n = 0; for(var i in config) eval("window." + i.toString().toUpperCase() + " = " + n++); tt_aV.length = n; } function tt_Browser() { var n, nv, n6, w3c; n = navigator.userAgent.toLowerCase(), nv = navigator.appVersion; tt_op = (document.defaultView && typeof(eval("w" + "indow" + "." + "o" + "p" + "er" + "a")) != tt_u); tt_ie = n.indexOf("msie") != -1 && document.all && !tt_op; if(tt_ie) { var ieOld = (!document.compatMode || document.compatMode == "BackCompat"); tt_db = !ieOld ? document.documentElement : (document.body || null); if(tt_db) tt_ie56 = parseFloat(nv.substring(nv.indexOf("MSIE") + 5)) >= 5.5 && typeof document.body.style.maxHeight == tt_u; } else { tt_db = document.documentElement || document.body || (document.getElementsByTagName ? document.getElementsByTagName("body")[0] : null); if(!tt_op) { n6 = document.defaultView && typeof document.defaultView.getComputedStyle != tt_u; w3c = !n6 && document.getElementById; } } tt_body = (document.getElementsByTagName ? document.getElementsByTagName("body")[0] : (document.body || null)); if(tt_ie || n6 || tt_op || w3c) { if(tt_body && tt_db) { if(document.attachEvent || document.addEventListener) return true; } else tt_Err("wz_tooltip.js must be included INSIDE the body section," + " immediately after the opening <body> tag."); } tt_db = null; return false; } function tt_MkMainDiv() { // Create the tooltip DIV if(tt_body.insertAdjacentHTML) tt_body.insertAdjacentHTML("afterBegin", tt_MkMainDivHtm()); else if(typeof tt_body.innerHTML != tt_u && document.createElement && tt_body.appendChild) tt_body.appendChild(tt_MkMainDivDom()); // FireFox Alzheimer bug if(window.tt_GetMainDivRefs && tt_GetMainDivRefs()) return true; tt_db = null; return false; } function tt_MkMainDivHtm() { return('<div id="WzTtDiV"></div>' + (tt_ie56 ? ('<iframe id="WzTtIfRm" src="javascript:false" scrolling="no" frameborder="0" style="filter:Alpha(opacity=0);position:absolute;top:0px;left:0px;display:none;"></iframe>') : '')); } function tt_MkMainDivDom() { var el = document.createElement("div"); if(el) el.id = "WzTtDiV"; return el; } function tt_GetMainDivRefs() { tt_aElt[0] = tt_GetElt("WzTtDiV"); if(tt_ie56 && tt_aElt[0]) { tt_aElt[tt_aElt.length - 1] = tt_GetElt("WzTtIfRm"); if(!tt_aElt[tt_aElt.length - 1]) tt_aElt[0] = null; } if(tt_aElt[0]) { var css = tt_aElt[0].style; css.visibility = "hidden"; css.position = "absolute"; css.overflow = "hidden"; return true; } return false; } function tt_ResetMainDiv() { var w = (window.screen && screen.width) ? screen.width : 10000; tt_SetTipPos(-w, 0); tt_aElt[0].innerHTML = ""; tt_aElt[0].style.width = (w - 1) + "px"; } function tt_IsW3cBox() { var css = tt_aElt[0].style; css.padding = "10px"; css.width = "40px"; tt_bBoxOld = (tt_GetDivW(tt_aElt[0]) == 40); css.padding = "0px"; tt_ResetMainDiv(); } function tt_OpaSupport() { var css = tt_body.style; tt_flagOpa = (typeof(css.filter) != tt_u) ? 1 : (typeof(css.KhtmlOpacity) != tt_u) ? 2 : (typeof(css.KHTMLOpacity) != tt_u) ? 3 : (typeof(css.MozOpacity) != tt_u) ? 4 : (typeof(css.opacity) != tt_u) ? 5 : 0; } // Ported from http://dean.edwards.name/weblog/2006/06/again/ // (Dean Edwards et al.) function tt_SetOnloadFnc() { tt_AddEvtFnc(document, "DOMContentLoaded", tt_HideSrcTags); tt_AddEvtFnc(window, "load", tt_HideSrcTags); if(tt_body.attachEvent) tt_body.attachEvent("onreadystatechange", function() { if(tt_body.readyState == "complete") tt_HideSrcTags(); } ); if(/WebKit|KHTML/i.test(navigator.userAgent)) { var t = setInterval(function() { if(/loaded|complete/.test(document.readyState)) { clearInterval(t); tt_HideSrcTags(); } }, 10); } } function tt_HideSrcTags() { if(!window.tt_HideSrcTags || window.tt_HideSrcTags.done) return; window.tt_HideSrcTags.done = true; if(!tt_HideSrcTagsRecurs(tt_body)) tt_Err("To enable the capability to convert HTML elements to tooltips," + " you must set TagsToTip in the global tooltip configuration" + " to true."); } function tt_HideSrcTagsRecurs(dad) { var a, ovr, asT2t; // Walk the DOM tree for tags that have an onmouseover attribute // containing a TagToTip('...') call. // (.childNodes first since .children is bugous in Safari) a = dad.childNodes || dad.children || null; for(var i = a ? a.length : 0; i;) {--i; if(!tt_HideSrcTagsRecurs(a[i])) return false; ovr = a[i].getAttribute ? a[i].getAttribute("onmouseover") : (typeof a[i].onmouseover == "function") ? a[i].onmouseover : null; if(ovr) { asT2t = ovr.toString().match(/TagToTip\s*\(\s*'[^'.]+'\s*[\),]/); if(asT2t && asT2t.length) { if(!tt_HideSrcTag(asT2t[0])) return false; } } } return true; } function tt_HideSrcTag(sT2t) { var id, el; // The ID passed to the found TagToTip() call identifies an HTML element // to be converted to a tooltip, so hide that element id = sT2t.replace(/.+'([^'.]+)'.+/, "$1"); el = tt_GetElt(id); if(el) { if(tt_Debug && !TagsToTip) return false; else el.style.display = "none"; } else tt_Err("Invalid ID\n'" + id + "'\npassed to TagToTip()." + " There exists no HTML element with that ID."); return true; } function tt_Tip(arg, t2t) { if(!tt_db) return; if(tt_iState) tt_Hide(); if(!tt_Enabled) return; tt_t2t = t2t; if(!tt_ReadCmds(arg)) return; tt_iState = 0x1 | 0x4; tt_AdaptConfig1(); tt_MkTipContent(arg); tt_MkTipSubDivs(); tt_FormatTip(); tt_bJmpVert = false; tt_maxPosX = tt_GetClientW() + tt_scrlX - tt_w - 1; tt_maxPosY = tt_GetClientH() + tt_scrlY - tt_h - 1; tt_AdaptConfig2(); // We must fake the first mousemove in order to ensure the tip // be immediately shown and positioned tt_Move(); tt_ShowInit(); } function tt_ReadCmds(a) { var i; // First load the global config values, to initialize also values // for which no command has been passed i = 0; for(var j in config) tt_aV[i++] = config[j]; // Then replace each cached config value for which a command has been // passed (ensure the # of command args plus value args be even) if(a.length & 1) { for(i = a.length - 1; i > 0; i -= 2) tt_aV[a[i - 1]] = a[i]; return true; } tt_Err("Incorrect call of Tip() or TagToTip().\n" + "Each command must be followed by a value."); return false; } function tt_AdaptConfig1() { tt_ExtCallFncs(0, "LoadConfig"); // Inherit unspecified title formattings from body if(!tt_aV[TITLEBGCOLOR].length) tt_aV[TITLEBGCOLOR] = tt_aV[BORDERCOLOR]; if(!tt_aV[TITLEFONTCOLOR].length) tt_aV[TITLEFONTCOLOR] = tt_aV[BGCOLOR]; if(!tt_aV[TITLEFONTFACE].length) tt_aV[TITLEFONTFACE] = tt_aV[FONTFACE]; if(!tt_aV[TITLEFONTSIZE].length) tt_aV[TITLEFONTSIZE] = tt_aV[FONTSIZE]; if(tt_aV[CLOSEBTN]) { // Use title colors for non-specified closebutton colors if(!tt_aV[CLOSEBTNCOLORS]) tt_aV[CLOSEBTNCOLORS] = new Array("", "", "", ""); for(var i = 4; i;) {--i; if(!tt_aV[CLOSEBTNCOLORS][i].length) tt_aV[CLOSEBTNCOLORS][i] = (i & 1) ? tt_aV[TITLEFONTCOLOR] : tt_aV[TITLEBGCOLOR]; } // Enforce titlebar be shown if(!tt_aV[TITLE].length) tt_aV[TITLE] = " "; } // Circumvents broken display of images and fade-in flicker in Geckos < 1.8 if(tt_aV[OPACITY] == 100 && typeof tt_aElt[0].style.MozOpacity != tt_u && !Array.every) tt_aV[OPACITY] = 99; // Smartly shorten the delay for fade-in tooltips if(tt_aV[FADEIN] && tt_flagOpa && tt_aV[DELAY] > 100) tt_aV[DELAY] = Math.max(tt_aV[DELAY] - tt_aV[FADEIN], 100); } function tt_AdaptConfig2() { if(tt_aV[CENTERMOUSE]) tt_aV[OFFSETX] -= ((tt_w - (tt_aV[SHADOW] ? tt_aV[SHADOWWIDTH] : 0)) >> 1); } // Expose content globally so extensions can modify it function tt_MkTipContent(a) { if(tt_t2t) { if(tt_aV[COPYCONTENT]) tt_sContent = tt_t2t.innerHTML; else tt_sContent = ""; } else tt_sContent = a[0]; tt_ExtCallFncs(0, "CreateContentString"); } function tt_MkTipSubDivs() { var sCss = 'position:relative;margin:0px;padding:0px;border-width:0px;left:0px;top:0px;line-height:normal;width:auto;', sTbTrTd = ' cellspacing=0 cellpadding=0 border=0 style="' + sCss + '"><tbody style="' + sCss + '"><tr><td '; tt_aElt[0].innerHTML = ('' + (tt_aV[TITLE].length ? ('<div id="WzTiTl" style="position:relative;z-index:1;">' + '<table id="WzTiTlTb"' + sTbTrTd + 'id="WzTiTlI" style="' + sCss + '">' + tt_aV[TITLE] + '</td>' + (tt_aV[CLOSEBTN] ? ('<td align="right" style="' + sCss + 'text-align:right;">' + '<span id="WzClOsE" style="padding-left:2px;padding-right:2px;' + 'cursor:' + (tt_ie ? 'hand' : 'pointer') + ';" onmouseover="tt_OnCloseBtnOver(1)" onmouseout="tt_OnCloseBtnOver(0)" onclick="tt_HideInit()">' + tt_aV[CLOSEBTNTEXT] + '</span></td>') : '') + '</tr></tbody></table></div>') : '') + '<div id="WzBoDy" style="position:relative;z-index:0;">' + '<table' + sTbTrTd + 'id="WzBoDyI" style="' + sCss + '">' + tt_sContent + '</td></tr></tbody></table></div>' + (tt_aV[SHADOW] ? ('<div id="WzTtShDwR" style="position:absolute;overflow:hidden;"></div>' + '<div id="WzTtShDwB" style="position:relative;overflow:hidden;"></div>') : '') ); tt_GetSubDivRefs(); // Convert DOM node to tip if(tt_t2t && !tt_aV[COPYCONTENT]) { // Store the tag's parent element so we can restore that DOM branch // once the tooltip is hidden tt_t2tDad = tt_t2t.parentNode || tt_t2t.parentElement || tt_t2t.offsetParent || null; if(tt_t2tDad) { tt_MovDomNode(tt_t2t, tt_t2tDad, tt_aElt[6]); tt_t2t.style.display = "block"; } } tt_ExtCallFncs(0, "SubDivsCreated"); } function tt_GetSubDivRefs() { var aId = new Array("WzTiTl", "WzTiTlTb", "WzTiTlI", "WzClOsE", "WzBoDy", "WzBoDyI", "WzTtShDwB", "WzTtShDwR"); for(var i = aId.length; i; --i) tt_aElt[i] = tt_GetElt(aId[i - 1]); } function tt_FormatTip() { var css, w, iOffY, iOffSh; //--------- Title DIV ---------- if(tt_aV[TITLE].length) { css = tt_aElt[1].style; css.background = tt_aV[TITLEBGCOLOR]; css.paddingTop = (tt_aV[CLOSEBTN] ? 2 : 0) + "px"; css.paddingBottom = "1px"; css.paddingLeft = css.paddingRight = tt_aV[PADDING] + "px"; css = tt_aElt[3].style; css.color = tt_aV[TITLEFONTCOLOR]; css.fontFamily = tt_aV[TITLEFONTFACE]; css.fontSize = tt_aV[TITLEFONTSIZE]; css.fontWeight = "bold"; css.textAlign = tt_aV[TITLEALIGN]; // Close button DIV if(tt_aElt[4]) { css.paddingRight = (tt_aV[PADDING] << 1) + "px"; css = tt_aElt[4].style; css.background = tt_aV[CLOSEBTNCOLORS][0]; css.color = tt_aV[CLOSEBTNCOLORS][1]; css.fontFamily = tt_aV[TITLEFONTFACE]; css.fontSize = tt_aV[TITLEFONTSIZE]; css.fontWeight = "bold"; } if(tt_aV[WIDTH] > 0) tt_w = tt_aV[WIDTH] + ((tt_aV[PADDING] + tt_aV[BORDERWIDTH]) << 1); else { tt_w = tt_GetDivW(tt_aElt[3]) + tt_GetDivW(tt_aElt[4]); // Some spacing between title DIV and closebutton if(tt_aElt[4]) tt_w += tt_aV[PADDING]; } // Ensure the top border of the body DIV be covered by the title DIV iOffY = -tt_aV[BORDERWIDTH]; } else { tt_w = 0; iOffY = 0; } //-------- Body DIV ------------ css = tt_aElt[5].style; css.top = iOffY + "px"; if(tt_aV[BORDERWIDTH]) { css.borderColor = tt_aV[BORDERCOLOR]; css.borderStyle = tt_aV[BORDERSTYLE]; css.borderWidth = tt_aV[BORDERWIDTH] + "px"; } if(tt_aV[BGCOLOR].length) css.background = tt_aV[BGCOLOR]; if(tt_aV[BGIMG].length) css.backgroundImage = "url(" + tt_aV[BGIMG] + ")"; css.padding = tt_aV[PADDING] + "px"; css.textAlign = tt_aV[TEXTALIGN]; // TD inside body DIV css = tt_aElt[6].style; css.color = tt_aV[FONTCOLOR]; css.fontFamily = tt_aV[FONTFACE]; css.fontSize = tt_aV[FONTSIZE]; css.fontWeight = tt_aV[FONTWEIGHT]; css.background = ""; css.textAlign = tt_aV[TEXTALIGN]; if(tt_aV[WIDTH] > 0) w = tt_aV[WIDTH] + ((tt_aV[PADDING] + tt_aV[BORDERWIDTH]) << 1); else // We measure the width of the body's inner TD, because some browsers // expand the width of the container and outer body DIV to 100% w = tt_GetDivW(tt_aElt[6]) + ((tt_aV[PADDING] + tt_aV[BORDERWIDTH]) << 1); if(w > tt_w) tt_w = w; //--------- Shadow DIVs ------------ if(tt_aV[SHADOW]) { tt_w += tt_aV[SHADOWWIDTH]; iOffSh = Math.floor((tt_aV[SHADOWWIDTH] * 4) / 3); // Bottom shadow css = tt_aElt[7].style; css.top = iOffY + "px"; css.left = iOffSh + "px"; css.width = (tt_w - iOffSh - tt_aV[SHADOWWIDTH]) + "px"; css.height = tt_aV[SHADOWWIDTH] + "px"; css.background = tt_aV[SHADOWCOLOR]; // Right shadow css = tt_aElt[8].style; css.top = iOffSh + "px"; css.left = (tt_w - tt_aV[SHADOWWIDTH]) + "px"; css.width = tt_aV[SHADOWWIDTH] + "px"; css.background = tt_aV[SHADOWCOLOR]; } else iOffSh = 0; //-------- Container DIV ------- tt_SetTipOpa(tt_aV[FADEIN] ? 0 : tt_aV[OPACITY]); tt_FixSize(iOffY, iOffSh); } // Fixate the size so it can't dynamically change while the tooltip is moving. function tt_FixSize(iOffY, iOffSh) { var wIn, wOut, i; tt_aElt[0].style.width = tt_w + "px"; tt_aElt[0].style.pixelWidth = tt_w; wOut = tt_w - ((tt_aV[SHADOW]) ? tt_aV[SHADOWWIDTH] : 0); // Body wIn = wOut; if(!tt_bBoxOld) wIn -= ((tt_aV[PADDING] + tt_aV[BORDERWIDTH]) << 1); tt_aElt[5].style.width = wIn + "px"; // Title if(tt_aElt[1]) { wIn = wOut - (tt_aV[PADDING] << 1); if(!tt_bBoxOld) wOut = wIn; tt_aElt[1].style.width = wOut + "px"; tt_aElt[2].style.width = wIn + "px"; } tt_h = tt_GetDivH(tt_aElt[0]) + iOffY; // Right shadow if(tt_aElt[8]) tt_aElt[8].style.height = (tt_h - iOffSh) + "px"; i = tt_aElt.length - 1; if(tt_aElt[i]) { tt_aElt[i].style.width = tt_w + "px"; tt_aElt[i].style.height = tt_h + "px"; } } function tt_DeAlt(el) { var aKid; if(el.alt) el.alt = ""; if(el.title) el.title = ""; aKid = el.childNodes || el.children || null; if(aKid) { for(var i = aKid.length; i;) tt_DeAlt(aKid[--i]); } } // This hack removes the annoying native tooltips over links in Opera function tt_OpDeHref(el) { if(!tt_op) return; if(tt_elDeHref) tt_OpReHref(); while(el) { if(el.hasAttribute("href")) { el.t_href = el.getAttribute("href"); el.t_stats = window.status; el.removeAttribute("href"); el.style.cursor = "hand"; tt_AddEvtFnc(el, "mousedown", tt_OpReHref); window.status = el.t_href; tt_elDeHref = el; break; } el = el.parentElement; } } function tt_ShowInit() { tt_tShow.Timer("tt_Show()", tt_aV[DELAY], true); if(tt_aV[CLICKCLOSE]) tt_AddEvtFnc(document, "mouseup", tt_HideInit); } function tt_OverInit(e) { tt_over = e.target || e.srcElement; tt_DeAlt(tt_over); tt_OpDeHref(tt_over); tt_AddRemOutFnc(true); } function tt_Show() { var css = tt_aElt[0].style; // Override the z-index of the topmost wz_dragdrop.js D&D item css.zIndex = Math.max((window.dd && dd.z) ? (dd.z + 2) : 0, 1010); if(tt_aV[STICKY] || !tt_aV[FOLLOWMOUSE]) tt_iState &= ~0x4; if(tt_aV[DURATION] > 0) tt_tDurt.Timer("tt_HideInit()", tt_aV[DURATION], true); tt_ExtCallFncs(0, "Show") css.visibility = "visible"; tt_iState |= 0x2; if(tt_aV[FADEIN]) tt_Fade(0, 0, tt_aV[OPACITY], Math.round(tt_aV[FADEIN] / tt_aV[FADEINTERVAL])); tt_ShowIfrm(); } function tt_ShowIfrm() { if(tt_ie56) { var ifrm = tt_aElt[tt_aElt.length - 1]; if(ifrm) { var css = ifrm.style; css.zIndex = tt_aElt[0].style.zIndex - 1; css.display = "block"; } } } function tt_Move(e) { e = window.event || e; if(e) { tt_musX = tt_GetEvtX(e); tt_musY = tt_GetEvtY(e); } if(tt_iState) { if(!tt_over && e) tt_OverInit(e); if(tt_iState & 0x4) { // Protect some browsers against jam of mousemove events if(!tt_op && !tt_ie) { if(tt_bWait) return; tt_bWait = true; tt_tWaitMov.Timer("tt_bWait = false;", 1, true); } if(tt_aV[FIX]) { tt_iState &= ~0x4; tt_SetTipPos(tt_aV[FIX][0], tt_aV[FIX][1]); } else if(!tt_ExtCallFncs(e, "MoveBefore")) tt_SetTipPos(tt_PosX(), tt_PosY()); tt_ExtCallFncs([tt_musX, tt_musY], "MoveAfter") } } } function tt_PosX() { var x; x = tt_musX; if(tt_aV[LEFT]) x -= tt_w + tt_aV[OFFSETX] - (tt_aV[SHADOW] ? tt_aV[SHADOWWIDTH] : 0); else x += tt_aV[OFFSETX]; // Prevent tip from extending past right/left clientarea boundary if(x > tt_maxPosX) x = tt_maxPosX; return((x < tt_scrlX) ? tt_scrlX : x); } function tt_PosY() { var y; // Apply some hysteresis after the tip has snapped to the other side of the // mouse. In case of insufficient space above and below the mouse, we place // the tip below. if(tt_aV[ABOVE] && (!tt_bJmpVert || tt_CalcPosYAbove() >= tt_scrlY + 16)) y = tt_DoPosYAbove(); else if(!tt_aV[ABOVE] && tt_bJmpVert && tt_CalcPosYBelow() > tt_maxPosY - 16) y = tt_DoPosYAbove(); else y = tt_DoPosYBelow(); // Snap to other side of mouse if tip would extend past window boundary if(y > tt_maxPosY) y = tt_DoPosYAbove(); if(y < tt_scrlY) y = tt_DoPosYBelow(); return y; } function tt_DoPosYBelow() { tt_bJmpVert = tt_aV[ABOVE]; return tt_CalcPosYBelow(); } function tt_DoPosYAbove() { tt_bJmpVert = !tt_aV[ABOVE]; return tt_CalcPosYAbove(); } function tt_CalcPosYBelow() { return(tt_musY + tt_aV[OFFSETY]); } function tt_CalcPosYAbove() { var dy = tt_aV[OFFSETY] - (tt_aV[SHADOW] ? tt_aV[SHADOWWIDTH] : 0); if(tt_aV[OFFSETY] > 0 && dy <= 0) dy = 1; return(tt_musY - tt_h - dy); } function tt_OnOut() { tt_AddRemOutFnc(false); if(!(tt_aV[STICKY] && (tt_iState & 0x2))) tt_HideInit(); } function tt_HideInit() { tt_ExtCallFncs(0, "HideInit"); tt_iState &= ~0x4; if(tt_flagOpa && tt_aV[FADEOUT]) { tt_tFade.EndTimer(); if(tt_opa) { var n = Math.round(tt_aV[FADEOUT] / (tt_aV[FADEINTERVAL] * (tt_aV[OPACITY] / tt_opa))); tt_Fade(tt_opa, tt_opa, 0, n); return; } } tt_tHide.Timer("tt_Hide();", 1, false); } function tt_OpReHref() { if(tt_elDeHref) { tt_elDeHref.setAttribute("href", tt_elDeHref.t_href); tt_RemEvtFnc(tt_elDeHref, "mousedown", tt_OpReHref); window.status = tt_elDeHref.t_stats; tt_elDeHref = null; } } function tt_Fade(a, now, z, n) { if(n) { now += Math.round((z - now) / n); if((z > a) ? (now >= z) : (now <= z)) now = z; else tt_tFade.Timer("tt_Fade(" + a + "," + now + "," + z + "," + (n - 1) + ")", tt_aV[FADEINTERVAL], true); } now ? tt_SetTipOpa(now) : tt_Hide(); } // To circumvent the opacity nesting flaws of IE, we set the opacity // for each sub-DIV separately, rather than for the container DIV. function tt_SetTipOpa(opa) { tt_SetOpa(tt_aElt[5].style, opa); if(tt_aElt[1]) tt_SetOpa(tt_aElt[1].style, opa); if(tt_aV[SHADOW]) { opa = Math.round(opa * 0.8); tt_SetOpa(tt_aElt[7].style, opa); tt_SetOpa(tt_aElt[8].style, opa); } } function tt_OnCloseBtnOver(iOver) { var css = tt_aElt[4].style; iOver <<= 1; css.background = tt_aV[CLOSEBTNCOLORS][iOver]; css.color = tt_aV[CLOSEBTNCOLORS][iOver + 1]; } function tt_Int(x) { var y; return(isNaN(y = parseInt(x)) ? 0 : y); } // Adds or removes the document.mousemove or HoveredElem.mouseout handler // conveniently. Keeps track of those handlers to prevent them from being // set or removed redundantly. function tt_AddRemOutFnc(bAdd) { var PSet = bAdd ? tt_AddEvtFnc : tt_RemEvtFnc; if(bAdd != tt_AddRemOutFnc.bOn) { PSet(tt_over, "mouseout", tt_OnOut); tt_AddRemOutFnc.bOn = bAdd; if(!bAdd) tt_OpReHref(); } } tt_AddRemOutFnc.bOn = false; Number.prototype.Timer = function(s, iT, bUrge) { if(!this.value || bUrge) this.value = window.setTimeout(s, iT); } Number.prototype.EndTimer = function() { if(this.value) { window.clearTimeout(this.value); this.value = 0; } } function tt_SetOpa(css, opa) { tt_opa = opa; if(tt_flagOpa == 1) { // Hack for bugs of IE: // A DIV cannot be made visible in a single step if an opacity < 100 // has been applied while the DIV was hidden. // Moreover, in IE6, applying an opacity < 100 has no effect if the // concerned element has no layout (position, size, zoom, ...). if(opa < 100) { var bVis = css.visibility != "hidden"; css.zoom = "100%"; if(!bVis) css.visibility = "visible"; css.filter = "alpha(opacity=" + opa + ")"; if(!bVis) css.visibility = "hidden"; } else css.filter = ""; } else { opa /= 100.0; switch(tt_flagOpa) { case 2: css.KhtmlOpacity = opa; break; case 3: css.KHTMLOpacity = opa; break; case 4: css.MozOpacity = opa; break; case 5: css.opacity = opa; break; } } } function tt_MovDomNode(el, dadFrom, dadTo) { if(dadFrom) dadFrom.removeChild(el); if(dadTo) dadTo.appendChild(el); } function tt_Err(sErr) { if(tt_Debug) alert("Tooltip Script Error Message:\n\n" + sErr); } //=========== DEALING WITH EXTENSIONS ==============// function tt_ExtCmdEnum() { var s; // Add new command(s) to the commands enum for(var i in config) { s = "window." + i.toString().toUpperCase(); if(eval("typeof(" + s + ") == tt_u")) { eval(s + " = " + tt_aV.length); tt_aV[tt_aV.length] = null; } } } function tt_ExtCallFncs(arg, sFnc) { var b = false; for(var i = tt_aExt.length; i;) {--i; var fnc = tt_aExt[i]["On" + sFnc]; // Call the method the extension has defined for this event if(fnc && fnc(arg)) b = true; } return b; } tt_Init();
var express = require('express'); var router = express.Router(); router.get('/go', function (req, res) { res.send('pretty damn deep'); }); module.exports = router;
import { IconContainer } from './' import { CheckedCircleIcon } from '../../../..' import renderer from 'react-test-renderer' import React from 'react' describe('<IconContainer/>', () => { it('should match snapshot with default behavior', () => { const component = renderer .create( <IconContainer icon={<CheckedCircleIcon />}>Foobar</IconContainer>, ) .toJSON() expect(component).toMatchSnapshot() }) it('should match snapshot when we change color', () => { const component = renderer .create( <IconContainer color="#fff" icon={<CheckedCircleIcon />}> Foobar </IconContainer>, ) .toJSON() expect(component).toMatchSnapshot() }) it('should match snapshot when we change position', () => { const component = renderer .create( <IconContainer position="bottom" icon={<CheckedCircleIcon />}> Foobar </IconContainer>, ) .toJSON() expect(component).toMatchSnapshot() }) it('should match snapshot when we change width and height', () => { const component = renderer .create( <IconContainer iconWidth={30} iconHeight={50} icon={<CheckedCircleIcon />} > Foobar </IconContainer>, ) .toJSON() expect(component).toMatchSnapshot() }) it('should match snapshot when we add an icon description', () => { const component = renderer .create( <IconContainer iconDescription="checked icon circle" icon={<CheckedCircleIcon />} > Foobar </IconContainer>, ) .toJSON() expect(component).toMatchSnapshot() }) })
import React, { PropTypes, } from 'react'; import { StyleSheet, Text, } from 'react-native'; import { xishengStyles, } from './styles'; const cs = StyleSheet.create(xishengStyles); const propTypes = { children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, ]), style: PropTypes.any, }; const defaultProps = {}; export default function Note(props) { return ( <Text {...props} style={[cs.note, props.style]} > {props.children} </Text> ); } Note.propTypes = propTypes; Note.defaultProps = defaultProps;
/* Removes button if you don't support GeoLocation*/ if ("geolocation" in navigator) { $('.js-geolocation').show(); } else { $('.js-geolocation').hide(); } /* Finds your Current Location */ $('.js-geolocation').on('click', function() { navigator.geolocation.getCurrentPosition(function(position) { loadWeather(position.coords.latitude + ',' + position.coords.longitude); //load weather using your lat/lng coordinates }); }); $(document).ready(function() { navigator.geolocation.getCurrentPosition(function(position) { loadWeather(position.coords.latitude + ',' + position.coords.longitude); //load weather using your lat/lng coordinates }); }); function loadWeather(location, woeid) { $.simpleWeather({ location: location, woeid: woeid, unit: 'f', success: function(weather) { html = '<h2><i class="icon-' + weather.code + '"></i> ' + weather.temp + '&deg;' + weather.units.temp + '</h2>'; html += '<ul><li>' + weather.city + ', ' + weather.region + '</li>'; html += '<li class="currently">' + weather.currently + '</li>'; html += '<li>' + weather.alt.temp + '&deg;C</li></ul>'; /*var heatIndex = if (weather.temp <= 40){ $('.progress').append('<div class="progress-bar progress-bar-info" role-"progressbar" aria-valuenow="') } */ //This is how the bar changes color based on temp var declare = '' var saying = '' if (weather.temp <= 55){ declare='info' saying= "Brr, better bundle up! It's cold out there!" } else if (weather.temp <= 70){ declare='success'; saying="It's a bit chilly, might I recommend a sweater?";; } else if (weather.temp <=80){ declare='warning'; saying="It's getting a bit warm outside, but not too bad."; } else{ declare='declare'; saying="It's gonna be a scorcher! Dress cool!" } var tempProg = '<div class="progress bar progress-bar-'+declare+'" role="progressbar" aria-valuenow="'+weather.temp+' "aria-valuemin="0" aria-valuemax="100" style="width:'+weather.temp+'%">'+saying+'It\'\s <b>' +weather.temp+'&deg;</b>F outside!</p></div>'; $('.progress').append(tempProg); //End Bar Creation //End Test Area if (weather.temp <= 30){ $('body').css("background", "url('http://www.psdgraphics.com/file/snow-background.jpg')"); } else if (weather.temp <= 60){ $('body').css("background", "url('http://dreamatico.com/data_images/autumn/autumn-5.jpg')"); } else if (weather.temp <= 80){ $('body').css("background-image", "url('https://s3.amazonaws.com/staticblog.virtualvocations.com/2014/06/Hot-Thermometer.jpg')") } $("#weather").html(html); }, error: function(error) { $("#weather").html('<p>' + error + '</p>'); } }); }
; (function (angular, undefined) { 'use strict'; angular.module('app.directives') .value('checkboxsCreated', (function () { var value = 0; return { get: function () { return value; }, add: function () { value += 1; } }; }())) .directive('materialCheckbox', ['$timeout', 'checkboxsCreated', materialCheckbox]); var template = [ '<div class="lista-options-group">', '<input type="{{::type}}" id="{{::id}}" name="{{::name}}">', '<label for="{{::id}}">', '<span></span>', '<span class="check"></span>', '<span class="box"></span>', '{{label}}', '</label>', '</div>' ].join(''); function materialCheckbox($timeout, checkboxsCreated) { return { priority: 99, restrict: 'AE', template: template, replace: true, transclude: true, scope: { type: '@', id: '@', name: '@', label: '@' // ngModel: '=', // ngValue: '=', // valueSelected: '=selected' }, link: linker }; function linker(scope, elem, attrs) { checkboxsCreated.add(); scope.id = 'material-checkbox-' + checkboxsCreated.get(); attrs.$observe('id', function (newValue) { scope.id = newValue; }); scope.type = scope.type || 'checkbox'; elem.on('click', 'input', animateSelection); console.log(elem.find('input')); var animationEvt = 'animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd'; function animateSelection(evt) { // var evtCopy = angular.copy(evt); console.log('checkbox', evt.target); var el = elem.find('label').children().eq(0); el.addClass('circle'); var newone = el.clone(true); el.before(newone); el.remove(); el = null; newone.on(animationEvt, removeCircleClass); return true; function removeCircleClass() { newone.removeClass('circle'); newone.off(animationEvt, removeCircleClass); } } } } }(window.angular));
const scopeCheckLimit = getScopeCheckLimit() module.exports = { evaluate(source, context = {}, restricted = {}) { runInSandbox(source, context, restricted, scopeCheckLimit) }, isolate(source, allowed = {}, context = {}) { runInIsolation(source, allowed, context, scopeCheckLimit) }, createTerminal() { let terminal = null return { reset() { terminal = null }, sendBatch(batch, context = {}, restricted = {}) { if (terminal === null) { terminal = runSandboxTerminal(batch, context, restricted) terminal.next(batch) return } terminal.next(batch) } } } } function runInSandbox(source, context, restricted, scopeCheckLimit) { const scope = new Proxy({ source, context, restricted, Proxy, eval }, { has(target, propName) { if (propName in target || propName in context) { return false } if (propName in restricted) { throw `ReferenceError: ${propName} is restricted` } return false }, }) with(scope) { function runInInnerSandbox(source, context) { const used = { eval: 0, source: scopeCheckLimit - 1 } const innerScope = new Proxy({ source: null, eval: null }, { has(target, propName) { if (propName in target) { if (used[propName] < scopeCheckLimit) { ++used[propName] return false } if (propName in restricted) { throw `ReferenceError: ${propName} is restricted` } return false } if (propName in context) { return true } return false }, set(target, propName, value) { if (context[propName]) { context[propName] = value } else { target[propName] = value } return true }, get(target, propName) { if (context[propName]) { return context[propName] } return target[propName] } }) with(innerScope) { eval(source) } } if ('this' in restricted) { runInInnerSandbox.call({}, source, context) return } runInInnerSandbox(source, context) } } function runInIsolation(source, allowed, context, scopeCheckLimit) { const scope = new Proxy({ source, context, allowed, scopeCheckLimit, Proxy, eval, }, { has(target, propName) { if (propName in target) { return false } if (!(propName in allowed)) { throw `ReferenceError: ${propName} is restricted` } return false }, }) with(scope) { function runInInnerIsolation(source, context) { const used = { eval: 0, source: scopeCheckLimit - 1, allowed: scopeCheckLimit, context : scopeCheckLimit, scopeCheckLimit: scopeCheckLimit } const innerScope = new Proxy({ source: null, eval: null, allowed, context, scopeCheckLimit }, { has(target, propName) { if (propName in target) { if (used[propName] < scopeCheckLimit) { ++used[propName] return false } if (!(propName in allowed) && !(propName in context)) { throw `ReferenceError: ${propName} is restricted` } return false } if (propName in context) { return true } return false }, set(target, propName, value) { if (context[propName]) { context[propName] = value } else { target[propName] = value } return true }, get(target, propName) { if (context[propName]) { return context[propName] } return target[propName] } }) with(innerScope) { eval(source) } } if ('this' in allowed) { return runInInnerIsolation(source, context) } return runInInnerIsolation.call({}, source, context) } } // todo: implement better isolation function* runSandboxTerminal(source, context, restricted) { const target = { source, eval } const scope = new Proxy(target, { has(target, propName) { if (propName in target) { return true } if (propName in context) { return true } if (propName in restricted) { throw `ReferenceError: ${propName} is restricted` } return false }, set(target, propName, value) { if (context[propName]) context[propName] = value else target[propName] = value return true }, get(target, propName) { if (context[propName]) return context[propName] return target[propName] } }) while (true) { with(scope) { eval(source) } target.source = yield } } function getScopeCheckLimit() { let scopeCheckLimit = 0 const scope = new Proxy({ }, { has: () => false }) with(scope) { const innerScope = new Proxy({ eval: null }, { has(_, propName) { if (propName === 'eval') { ++scopeCheckLimit } return false } }) with(innerScope) { eval('') } // runInInnerSandbox() return scopeCheckLimit } }
'use strict'; var repository = require('../lib/contactRepository'); module.exports = { /** * summary: * description: * parameters: * produces: application/json, text/json * responses: 200 */ get: function contacts_get(req, res) { res.json(repository.all()) } };
"use strict" var Role = require('./RoleService'); module.exports.findRoles = function findRoles(req, res, next) { Role.findRoles(req.swagger.params, res, next); }; module.exports.createRole = function createRole(req, res, next) { Role.createRole(req.swagger.params, res, next); }; module.exports.updateRoleById = function updateRoleById(req, res, next) { Role.updateRoleById(req.swagger.params, res, next); }; module.exports.deleteRoleById = function deleteRoleById(req, res, next) { Role.deleteRoleById(req.swagger.params, res, next); }; module.exports.getUsersForRole = function getUsersForRole(req, res, next) { Role.getUsersForRole(req.swagger.params, res, next); }; module.exports.addUserForRole = function addUserForRole(req, res, next) { Role.setUsersForRole(req.swagger.params, res, next); }; module.exports.removeUserForRole = function removeUserForRole(req, res, next) { Role.removeUserForRole(req.swagger.params, res, next); };
app.get('/problem', async (req, res) => { res.redirect('/problems'); }); app.get('/contest', async (req, res) => { res.redirect('/contests'); }); app.get('/judge_state', async (req, res) => { res.redirect('/submissions'); }); app.get('/judge_detail/:id', async (req, res) => { res.redirect('/submission/' + req.params.id); });
import Key from 'input/keyboard/Key.js'; export default function F9 () { return Key(120, 'F9'); }
let snake; let apples = []; let numApples = 130; let size = 10; function setup(){ createCanvas(800, 600); snake = new Snake(createVector(400, 300), size); for (let i = 0; i < numApples; i++){ let numX = width / size; let numY = height / size; let x = floor(random(numX - 2) + 1) * size; let y = floor(random(numY - 2) + 1) * size; apples.push(new Apple(createVector(x, y), size)); } frameRate(15); } function draw(){ background('black'); snake.move(); for (let i = 0; i < numApples; i++){ apples[i].checkSnake(snake); apples[i].show(); } snake.show(); } function keyPressed() { if (keyCode == LEFT_ARROW){ snake.turnLeft(); } else if (keyCode == RIGHT_ARROW){ snake.turnRight(); } }
'use strict'; exports.__esModule = true; exports.default = { el: { colorpicker: { confirm: 'Onayla', clear: 'Temizle' }, datepicker: { now: 'Şimdi', today: 'Bugün', cancel: 'İptal', clear: 'Temizle', confirm: 'Onayla', selectDate: 'Tarih seç', selectTime: 'Saat seç', startDate: 'Başlangıç Tarihi', startTime: 'Başlangıç Saati', endDate: 'Bitiş Tarihi', endTime: 'Bitiş Saati', prevYear: 'Önceki Yıl', nextYear: 'Sonraki Yıl', prevMonth: 'Önceki Ay', nextMonth: 'Sonraki Ay', year: '', month1: 'Ocak', month2: 'Şubat', month3: 'Mart', month4: 'Nisan', month5: 'Mayıs', month6: 'Haziran', month7: 'Temmuz', month8: 'Ağustos', month9: 'Eylül', month10: 'Ekim', month11: 'Kasım', month12: 'Aralık', // week: 'week', weeks: { sun: 'Paz', mon: 'Pzt', tue: 'Sal', wed: 'Çar', thu: 'Per', fri: 'Cum', sat: 'Cmt' }, months: { jan: 'Oca', feb: 'Şub', mar: 'Mar', apr: 'Nis', may: 'May', jun: 'Haz', jul: 'Tem', aug: 'Ağu', sep: 'Eyl', oct: 'Eki', nov: 'Kas', dec: 'Ara' } }, select: { loading: 'Yükleniyor', noMatch: 'Eşleşen veri bulunamadı', noData: 'Veri yok', placeholder: 'Seç' }, cascader: { noMatch: 'Eşleşen veri bulunamadı', loading: 'Yükleniyor', placeholder: 'Seç', noData: 'Veri yok' }, pagination: { goto: 'Git', pagesize: '/sayfa', total: 'Toplam {total}', pageClassifier: '' }, messagebox: { title: 'Mesaj', confirm: 'Onayla', cancel: 'İptal', error: 'İllegal giriş' }, upload: { deleteTip: 'kaldırmak için delete tuşuna bas', delete: 'Sil', preview: 'Görüntüle', continue: 'Devam' }, table: { emptyText: 'Veri yok', confirmFilter: 'Onayla', resetFilter: 'Sıfırla', clearFilter: 'Hepsi', sumText: 'Sum' }, tree: { emptyText: 'Veri yok' }, transfer: { noMatch: 'Eşleşen veri bulunamadı', noData: 'Veri yok', titles: ['Liste 1', 'Liste 2'], filterPlaceholder: 'Anahtar kelimeleri gir', noCheckedFormat: '{total} adet', hasCheckedFormat: '{checked}/{total} seçildi' }, image: { error: 'FAILED' // to be translated }, pageHeader: { title: 'Back' // to be translated }, popconfirm: { confirmButtonText: 'Yes', // to be translated cancelButtonText: 'No' // to be translated } } };
var Stream = require('stream').Stream; var util = require('util'); exports.BufferedNetstringStream = BufferedNetstringStream; function BufferedNetstringStream() { this.readable = true; this.writable = true; this.length = null; this.buffer = null; this.offset = 0; } util.inherits(BufferedNetstringStream, Stream); function readLength(buffer, offset) { var char = buffer[offset], value; if (char >= 48 && char <= 57) { value = char - 48; if (this.length == null) { this.length = value; return false; } else { this.length = (this.length * 10) + value; return false; } } else if (char == 58) { this.length += 1; return true; } else { throw Error('malformed payload length header'); } } function readData(buffer, offset) { var size = Math.min(buffer.length - offset, this.length - this.offset); buffer.copy(this.buffer, this.offset, offset, offset + size); return size; } BufferedNetstringStream.prototype.write = function(data) { var offset = 0; while (offset < data.length) { if (this.buffer == null) { try { if (readLength.call(this, data, offset)) { this.buffer = new Buffer(this.length); } offset += 1; } catch (error) { this.emit('error', error); return this.destroy(); } } else { var size = readData.call(this, data, offset); offset += size, this.offset += size; if (this.length == this.offset) { if (this.buffer[this.length - 1] != 44) { this.emit('error', Error('payload length mismatch')); return this.destroy(); } this.emit('data', this.buffer.slice(0, this.length - 1)); this.buffer = null; this.length = null; this.offset = 0; } } } } BufferedNetstringStream.prototype.end = function() { if (this.length != null || this.buffer != null) { this.emit('error', Error('unexpected end of stream')); return this.destroy(); } this.emit('end'); } BufferedNetstringStream.prototype.destroy = function() { this.emit('close'); }
'use strict'; module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), src: { // This will cover all JS files in 'js' and sub-folders js: ['app/js/**/*.js'], templates: ['app/partials/**/*.html'] }, clean: [ 'test-results', 'coverage' ], //JS Test files test: { karmaConfig: 'test/karma.conf.js', unit: ['test/unit/**/*.js'] }, // Configure Lint\JSHint Task jshint: { options: { jshintrc: '.jshintrc' }, files: { src: ['Gruntfile.js', '<%= src.js %>', '<%= test.unit %>'] } }, karma: { dev: { configFile: '<%= test.karmaConfig %>', singleRun: false }, ci: { configFile: '<%= test.karmaConfig %>', singleRun: true } }, // copy coverage results to static location copy: { coverage: { files: [ { expand: true, src: ['test-results/Phantom*/**/*'], dest: 'test-results/coverage/', rename: function (dest, src) { return dest + src.replace(/test-results\/Phantom[^\/]+\//, '/'); } } ] } }, sass: { dist: { files: { 'app/css/app.css': 'sass/main.scss' } } }, connect: { web: { options: { port: 9000, bases: '.', keepalive: true } } }, watch: { jshint: { files: ["<%= src.js %>", "<%= test.unit %>"], tasks: ['jshint'] }, sass: { files: ["**/.scss"], tasks: ['sass:dist'] }, karma: { files: ["<%= src.js %>", "<%= test.unit %>"], tasks: ['karma:dev'] } }, concurrent: { dev: { tasks: ['watch', 'watch-tests', 'web'], options: { logConcurrentOutput: true } } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-karma'); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-concurrent'); grunt.loadNpmTasks('grunt-sass'); grunt.registerTask('web', ['connect:web']); grunt.registerTask('watch-tests', ['karma:dev']); grunt.registerTask('default', ['clean', 'concurrent:dev']); grunt.registerTask('ci', ['clean', 'karma:ci', 'copy:coverage']); };
var gulp = require('gulp'); var concat = require('gulp-concat'); var sourcemaps = require('gulp-sourcemaps'); var runSequence = require('run-sequence'); var jshint = require('gulp-jshint'); var stylish = require('jshint-stylish'); var sass = require('gulp-sass'); var shell = require('gulp-shell'); var fs = require('fs'); // Settings var builds = ['designexplorer', 'main']; var buildDevNames = []; var allJsSrcFolder = 'js/src/**/*'; var allJsSrc = allJsSrcFolder + '.js'; var allCssSrcFolder = 'css/src/**/*'; var s3Config = JSON.parse(fs.readFileSync('.secrets/s3config.json')); var s3 = require('gulp-s3-upload')(s3Config); // Build node dependencies gulp.task('build-dependencies', function () { return gulp.src( [ './node_modules/lodash/lodash.min.js', './node_modules/angular/angular.min.js', './node_modules/angular-ui-router/release/angular-ui-router.min.js', './node_modules/promise-polyfill/promise.min.js', ] ) .pipe(concat('dependencies.js')) .pipe(gulp.dest('./js/builds')); }); // Init each build task builds.forEach(function (buildFolder) { var buildName = 'build-' + buildFolder; gulp.task(buildName, function () { return gulp.src( [ './js/src/' + buildFolder + '/header.js', './js/src/' + buildFolder + '/*dependencies/**/*.js', './js/src/' + buildFolder + '/*constructors/**/*.js', './js/src/' + buildFolder + '/**/*.js', './js/src/' + buildFolder + '/footer.js' ] ) .pipe(sourcemaps.init()) .pipe(concat(buildFolder + '.js')) .pipe(sourcemaps.write()) .pipe(gulp.dest('./js/builds')); }); buildDevNames.push(buildName); }); // Set up lint gulp.task('lint', function () { return gulp.src(allJsSrc) .pipe(jshint()) .pipe(jshint.reporter(stylish)); }); // Build All Dev gulp.task('build-dev', /*['clean'],*/ function () { runSequence(buildDevNames); }); // Sass gulp.task('sass', function () { return gulp.src('./css/src/style.scss') .pipe(sourcemaps.init()) .pipe(sass() .on('error', sass.logError)) .pipe(sourcemaps.write()) .pipe(gulp.dest('./css')); }); // documentation gulp.task('document', shell.task([ 'jsdoc ' + '-c node_modules/angular-jsdoc/common/conf.json ' + // config file // '-t docs/src/angular-template ' + // template file '-d docs/auto/ ' + // output directory './readme.md ' + // to include README.md as index contents '-r js/src/main' //+ // source code directory // '-u tutorials' // tutorials directory , // 'jsdoc -c docs/src/jsdocConf.json -d docs/auto/js' // 'jsdoc -c docs/src/jsdocConfInkDocstrap.json -d docs/auto/js -t ./node_modules/ink-docstrap/template' ])); // serve documentation folder gulp.task('view-documentation', shell.task([ 'http-server ./docs -p 8000' ])); // upload to s3 bucket gulp.task("upload-s3", function () { var bucketName = 'kpfui-de'; var aclValue = 'public-read'; gulp.src(['index.html']) .pipe(s3({ Bucket: bucketName, // Required ACL: aclValue, // Needs to be user-defined }, { // S3 Constructor Options, ie: maxRetries: 5 })); ['css', 'js/builds', 'js/src', 'lib'].forEach(function (folder) { var prefix = "./" + folder + "/**/*"; var srcFiles = [prefix + '.js', prefix + '.json', prefix + '.css']; if (folder === 'js/src') { srcFiles = [prefix + '.html']; } gulp.src(srcFiles) .pipe(s3({ Bucket: bucketName, // Required ACL: aclValue, // Needs to be user-defined keyTransform: function (relative_filename) { return folder + "/" + relative_filename; } }, { // S3 Constructor Options, ie: maxRetries: 5 })); }); }); // Default gulp task: build dev gulp.task('default', ['build-dependencies'], function () { var devBuildJsTasks = ['lint', 'build-dev']; var devBuildCssTasks = ['sass']; gulp.start(devBuildJsTasks); gulp.start(devBuildCssTasks); gulp.watch(allJsSrcFolder, devBuildJsTasks); gulp.watch(allCssSrcFolder, devBuildCssTasks); });
var express = require('express'); var app = express(); app.use(express.static('build')); var port = process.env.PORT || 3000; app.listen(port, function () { console.log('Example app listening on port '+port+' !') })
'use strict'; angular .module('app.controllers') .controller('ActionCtrl', function($scope, $stateParams, $state, apiDescriptor, pageProvider) { var resourceName = $stateParams.resourceName; $scope.action = $state.current.data.action; $scope.resourceName = resourceName; $scope.pp = pageProvider; apiDescriptor.then(function(apiDescription) { $scope.rdesc = apiDescription.resource(resourceName); }); });
angular.module('repository') .controller('repositoryController', ['$scope', 'subjects', 'semesters', 'files','FolderDataProvider', 'FileDataProvider', 'Authentication', 'FileUploader', '$sce', '$timeout',function($scope, subjects, semesters, files, FolderDataProvider, FileDataProvider , Authentication, FileUploader, $sce, $timeout) { $scope.subjects = subjects; $scope.semesters = semesters; $scope.files = files; $scope.displayFiles = $scope.files; $scope.filterOptions = {filterText: ''}; $scope.searchText = ''; $scope.newResource = {}; $scope.editFile = {}; $scope.error = {}; $scope.selectedIndex = 0; $scope.temp = {}; var me = Authentication.user; var subjectIds = _.map($scope.subjects, function(subject) {return subject._id}); var semesterIds = _.map($scope.semesters, function(semester) {return semester._id}); var types = ['pdf', 'doc', 'ebook', 'video', 'audio', 'image', 'other']; $scope.allSubjects = [{_id: subjectIds, name: '所有科目'}].concat($scope.subjects); $scope.allSemesters = [{_id: semesterIds, name: '所有年级'}].concat($scope.semesters); //console.log(me); $scope.selectedSubject = $scope.allSubjects[0]._id; $scope.selectedSemester = $scope.allSemesters[0]._id; $scope.$watchGroup(['selectedIndex', 'searchText'], function(newValue) { if(newValue) { if (newValue[0] === 0) { $scope.filterOptions.filterText = newValue[1]; }else { $scope.filterOptions.filterText = 'type:' + types[newValue[0]-1] + ';' + newValue[1]; } } }); $scope.filter = function() { $scope.displayFiles = _.filter($scope.files, function(file) { return ($scope.selectedSubject.indexOf(file.subject._id) > -1) && ($scope.selectedSemester.indexOf(file.semester._id) > -1) }); }; $scope.selectFileType = function(index) { $scope.selectedIndex = index; }; $scope.toEditFile = function(index) { $scope.index = index; $scope.theFile= $scope.uploader.queue[index].file; var dotIndex = $scope.theFile.name.lastIndexOf('.'); $scope.editFile.fileName = $scope.theFile.name.substr(0, dotIndex < 0 ? $scope.theFile.name.length : dotIndex); $scope.editFile.extension = $scope.theFile.name.substr(dotIndex < 0 ? $scope.theFile.name.length : dotIndex, $scope.theFile.name.length); $scope.editFile.description = $scope.theFile.description; $('#editFileInfoDialog').modal('show'); }; $scope.editFileInfo = function() { $scope.uploader.queue[$scope.index].file.name = $scope.editFile.fileName + $scope.editFile.extension; $scope.uploader.queue[$scope.index].file.description = $scope.editFile.description; $('#editFileInfoDialog').modal('hide'); }; $scope.showEditFileDialog = function(event, row) { event.stopPropagation(); $('#editFileDialog').modal('show'); console.log('clearing queue'); $scope.editFileUploader.clearQueue(); $scope.row = row; var dotIndex = $scope.row.entity.originalname.lastIndexOf('.'); $scope.temp.newFileName = $scope.row.entity.originalname.substr(0, dotIndex < 0 ? $scope.row.entity.originalname.length : dotIndex); $scope.temp.extension = $scope.row.entity.originalname.substr(dotIndex < 0 ? $scope.row.entity.originalname.length : dotIndex, $scope.row.entity.originalname.length); $scope.temp.newFileDescription = row.entity.description; }; $scope.editFile = function(row) { var info = {}; info._id = row.entity._id; info.name = $scope.temp.newFileName + $scope.temp.extension; info.description = $scope.temp.newFileDescription; if($scope.editFileUploader.queue.length) { $scope.editFileUploader.uploadAll(); $scope.editFileUploader.onErrorItem = function(item, response, status) { swal({title: " 修改文件内容失败", text: response.message,type: 'error', timer: 2000}); if (status == 406) { $scope.editFileUploader.clearQueue(); } }; $scope.editFileUploader.onSuccessItem = function(item, response) { swal({title: "修改文件成功", type: 'success', timer: 2000}); $('#editFileDialog').modal('hide'); $scope.row.entity.originalname = response.originalname; $scope.row.entity.description = response.description; $scope.row.entity.size = response.size; $scope.row.entity.mimetype = response.mimetype; $scope.row.entity.updated_at = Date.now(); $scope.editFileUploader.clearQueue(); }; }else { FileDataProvider.editFileNameAndDescription(info) .success(function(editedFile) { $scope.row.entity.originalname = editedFile.originalname; $scope.row.entity.description = editedFile.description; $scope.temp = {}; swal({title: '修改成功', type: 'success', timer: 2000}); $('#editFileDialog').modal('hide'); }) .error(function(err) { console.error(err); swal({title: '修改失败', text: '请重试', type: 'error'}); }) } }; $scope.toAddDescription = function(index) { $scope.index = index; $('#addDescriptionDialog').modal('show'); }; $scope.addDescription = function() { $scope.uploader.queue[$scope.index].file.description = $scope.newResource.description; $scope.newResource.description = null; $('#addDescriptionDialog').modal('hide'); }; $scope.uploader = new FileUploader({ url: "/repository", method: "POST", queueLimit: 10 }); $scope.uploader.filters.push({ name: 'queueLimit', fn: function () { $scope.error.limit = (this.queue.length > 10); return this.queue.length < 11; } }); $scope.uploader.onBeforeUploadItem = function(item) { //item.formData = [{description: item.file.description, createBy: 'admin'}]; var description = (typeof item.file.description === "undefined") ? "": item.file.description; item.formData = [{description: description, createBy: 'admin', semester: $scope.newResource.semester._id, subject: $scope.newResource.subject._id}]; }; $scope.uploader.onErrorItem = function(item, response, status) { swal({title: " 上传失败", text: response.message,type: 'error'}); if (status == 406) { $scope.uploader.clearQueue(); } }; $scope.uploader.onSuccessItem = function(item, response) { console.log(response.file); console.log(response); response.file.subject = $scope.newResource.subject; response.file.semester = $scope.newResource.semester; response.file.owner = me; response.file.school = response.school; $scope.displayFiles.push(response.file); //$rootScope.$broadcast('addFile', {folderId: folder._id, updated_at: Date.now()}); }; $scope.uploader.onCompleteAll = function() { $timeout(function() { swal({title: "上传成功", type: 'success', timer: 2000}); $('#addResourceDialog').modal('hide'); $scope.uploader.clearQueue(); }, 1200); }; $scope.editFileUploader = new FileUploader({ url: "/edit/file", method: "POST", queueLimit: 1 }); $scope.editFileUploader.onBeforeUploadItem = function(item) { var name = $scope.temp.newFileName; var description = (typeof $scope.temp.newFileDescription === "undefined") ? "": $scope.temp.newFileDescription; item.formData = [{fileId: $scope.row.entity._id,originalname: name,description: description}]; }; $scope.gridOptions = { data: 'displayFiles', multiSelect: false, enableFiltering: true, enableColumnResize: true, rowTemplate: '<div ng-mouseover="$parent.showedit=true" ng-mouseleave="$parent.showedit=false" ng-style="{\'cursor\': row.cursor, \'z-index\': col.zIndex() }" ' + 'ng-repeat="col in renderedColumns" ng-class="col.colIndex()" ' + 'class="ngCell {{col.cellClass}}" ng-cell></div>', columnDefs: [ {field: '_id', visible: false}, {field: 'type', displayName: '文件类型',cellTemplate: '<div><span ng-bind-html="row.entity.type | typeFilter"></span></div>'}, {field: 'originalname', displayName: '文件名称', cellTemplate: '<div><a ng-click="selectFile(row.entity)">{{row.entity.originalname}}</a></div>'}, {field: 'description', displayName: '描述', cellTemplate: '<div ng-show="row.entity.description">' + '<a title="文件描述:{{row.entity.description}}" id="info-tooltip" data-placement="right" data-toggle="tooltip" type="button"><i class="glyphicon glyphicon-info-sign text-success" ng-mouseover="tooltip()"></i></a>'+ ' {{row.entity.description}}</div><div ng-hide="row.entity.description"><button class="btn btn-xs btn-success" ng-click="toAddDescriptionOnRow(row)"><i class="fa fa-comments"></i> 添加</button></div>'}, {field: 'size', displayName: '大小', cellTemplate: '<div>{{row.entity.size | fileSizeFilter}}</div>'}, {filed: 'like', displayName: '点赞', cellTemplate: '<div>{{row.entity.like.length}}</div>'}, //{field: '', displayName: '分享'}, {field: 'subject.name', displayName: '科目'}, {field: 'semester.name', displayName: '年级'}, {field: 'owner', displayName: '创建人', cellTemplate: '<div ng-show="row.entity.createBy === \'root\' || row.entity.createBy === \'admin\'">{{row.entity.school.name}}</div><div ng-show="row.entity.createBy === \'teacher\'">{{row.entity.owner.name}}</div>'}, //{field: 'school.name', displayName: '学校'}, {field: 'created_at', displayName: '创建时间', cellTemplate: '<span class="label label-success" am-time-ago="row.entity.created_at"></span>'}, {field: 'name', displayName: '编辑', cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()" ng-show="showedit">' + '<a class="fa fa-edit text-success fa-2x" ng-click="showEditFileDialog($event, row)"></a> &nbsp;&nbsp;' + //'<a class="fui-cross text-danger" ng-click="removeStudent($event, row)"></a>' + //'<a class="fa fa-star-o text-success fa-2x" ng-click="removeStudent($event, row)"></a> &nbsp;&nbsp;' + '<a class="fa fa-close text-danger fa-2x " ng-click="deleteFile($event, row)"></a>' + '</div>'} //{field: 'loginDateLocal', displayName: '上次登录时间', width: 170} ], selectedItems: [], filterOptions: $scope.filterOptions }; $scope.deleteFile = function (event, row) { event.stopPropagation(); swal({ title: "删除文件", text: "您确定要删除"+row.entity.originalname+"吗?\n删除之后,文件信息将无法找回", type: "warning", showCancelButton: true, cancelButtonText: "取消", confirmButtonColor: "#DD6B55", confirmButtonText: "删除", closeOnConfirm: false }, function(){ FileDataProvider.deleteFile(row.entity._id) .success(function(file){ swal({title: "删除成功", type: "success", timer: 1000 }); $scope.files.splice($scope.files.indexOf(row.entity),1); }) .error(function(err){ console.error(err); swal({title: "删除失败", text: "请重试", type: 'error'}) }) }); }; $scope.clickLike = function(fileId) { if($scope.liked) { $('#likeButton').removeClass('fa-heart-o').addClass('text-danger fa-heart'); }else { $('#likeButton').removeClass('text-danger fa-heart').addClass('fa-heart-o'); } FileDataProvider.changeFileLike(fileId, me._id, $scope.liked) .success(function(editedFile) { $scope.file.like = editedFile.like; _.findWhere($scope.displayFiles, {_id: fileId}).like = editedFile.like; }) .error(function(err) { console.error(err); }); }; $scope.selectFile = function (file) { //event.stopPropagation(); $scope.file = null; $scope.file = file; $scope.liked = $scope.file.like.indexOf(me._id) > -1; console.log($scope.liked); if($scope.liked) { $('#likeButton').addClass('text-danger fa-heart').removeClass('fa-heart-o'); }else { $('#likeButton').removeClass('text-danger fa-heart').addClass('fa-heart-o'); } $scope.type = {}; console.log($scope.file.like); var mimetype = $scope.file.mimetype; if(mimetype.indexOf('pdf') > -1) { $scope.type.isPDF = true; }else if(mimetype.indexOf('video') > -1) { $scope.type.isVideo = true; }else if(mimetype.indexOf('audio') > -1) { $scope.type.isAudio = true; }else if(mimetype.indexOf('image') > -1) { $scope.type.isImage = true; }else if(mimetype.indexOf('text') > -1) { $scope.type.isText = true; }else { $scope.type.isOther = true; } $scope.fileUrl = $sce.trustAsResourceUrl('/sunpack/' + $scope.file._id); $scope.videoUrl = $sce.trustAsResourceUrl('/sunpack/' + $scope.file._id); console.log($scope.file.mimetype); $('#previewFileDialog').modal('show'); }; $scope.closePreview = function() { $scope.file = null; $scope.type = {}; $('#previewFileDialog').modal('hide'); }; $scope.tooltip = function() { $('[data-toggle="tooltip"]').tooltip(); // Add style class name to a tooltips $('.tooltip').addClass(function () { if ($(this).prev().attr('data-tooltip-style')) { return 'tooltip-' + $(this).prev().attr('data-tooltip-style'); } }); }; }]);
var EventEmitter = require('events').EventEmitter; var net = require('net'); var fs = require('fs'); var util = require('util'); util.inherits(MaxCube, EventEmitter); function padLeft(nr, n, str){ return Array(n-String(nr).length+1).join(str||'0')+nr; } function MaxCube(ip, port, heartbeatInterval) { this.ip = ip; this.port = port; this.interval = heartbeatInterval || 20000; this.connectionState = 'disconnected'; this.busy = false; this.callback = null; this.dutyCycle = 0; this.memorySlots = 0; this.rooms = []; this.devices = {}; this.deviceCount = 0; this.client = new net.Socket(); var self = this; this.client.on('error', function(err){ self.client.end(); self.connectionState = 'disconnected'; self.busy = false; self.emit('error', err); }); this.client.on('data', this.onData.bind(this)); this.connect(); } MaxCube.prototype.connect = function () { if (this.connectionState === 'disconnected') { this.connectionState = "connecting"; this.client.connect(this.port, this.ip, function() { this.connectionState = 'connected'; this.emit('connected'); }.bind(this)); } else if(this.connectionState === 'connected'){ this.send('l:\r\n', function(err){ if(err) { this.client.emit('error', err); } }.bind(this)); } setTimeout(this.connect.bind(this), this.interval); }; MaxCube.prototype.send = function (message, callback) { if (!this.busy) { //console.log('Sending command: ' + message.substr(0,1)); this.busy = true; this.client.write(message, 'utf-8', callback); } else { callback(new Error("The cube is busy")); } }; MaxCube.prototype.onData = function (data) { this.busy = false; data = data.toString('utf-8'); data = data.split('\r\n'); data.forEach(function (line) { if (line.length > 0) { var commandType = line.substr(0, 1); var payload = line.substring(2); //console.log('Data received: ' + commandType); var dataObj = this.parseCommand(commandType, payload); //console.log(dataObj); } }.bind(this)); this.emit('update', this.devices); }; MaxCube.prototype.getDeviceType = function (deviceId) { var type = null; switch (deviceId) { case 0: type = 'Cube'; break; case 1: type = 'Heating Thermostat'; break; case 2: type = 'Heating Thermostat Plus'; break; case 3: type = 'Wall mounted Thermostat'; break; case 4: type = 'Shutter Contact'; break; case 5: type = 'Push Button'; break; default: type = 'unknown'; break; } return type; }; MaxCube.prototype.parseCommand = function (type, payload) { var data = null; switch (type) { case 'H': data = this.parseCommandHello(payload); break; case 'M': data = this.parseCommandMetadata(payload); break; case 'C': data = this.parseCommandDeviceConfiguration(payload); break; case 'L': data = this.parseCommandDeviceList(payload); break; case 'S': data = this.parseCommandSendDevice(payload); break; default: console.log('Unknown command type: ' + type); break; } return data; }; MaxCube.prototype.parseCommandHello = function (payload) { var payloadArr = payload.split(","); var dataObj = { serial: payloadArr[0], address: payloadArr[1], firmware: payloadArr[2], connectionId: payloadArr[4], dutyCycle: parseInt(payloadArr[5], 16), freeMemorySlots: parseInt(payloadArr[6], 16), date: 2000 + parseInt(payloadArr[7].substr(0, 2), 16) + '-' + parseInt(payloadArr[7].substr(2, 2), 16) + '-' + parseInt(payloadArr[7].substr(4, 2), 16), time: parseInt(payloadArr[8].substr(0, 2), 16) + ':' + parseInt(payloadArr[8].substr(2, 2), 16) , stateTime: payloadArr[9], ntpCounter: payloadArr[10], }; this.dutyCycle = dataObj.dutyCycle; this.memorySlots = dataObj.freeMemorySlots; this.emit('status', { dutyCycle: this.dutyCycle, memorySlots: this.memorySlots }); return dataObj; }; MaxCube.prototype.parseCommandDeviceConfiguration = function (payload) { var payloadArr = payload.split(","); var decodedPayload = new Buffer(payloadArr[1], 'base64'); var address = decodedPayload.slice(1, 4).toString('hex'); var devicetype = this.getDeviceType(parseInt(decodedPayload[4].toString(10))); if ( (devicetype == 'Heating Thermostat' || devicetype == 'Heating Thermostat Plus') && this.devices[address]) { this.devices[address].comfortTemperature = parseInt(decodedPayload[18].toString(10)) / 2; this.devices[address].ecoTemperature = parseInt(decodedPayload[19].toString(10)) / 2; this.devices[address].maxTemperature = parseInt(decodedPayload[20].toString(10)) / 2; this.devices[address].minTemperature = parseInt(decodedPayload[21].toString(10)) / 2; this.devices[address].temperatureOffset = parseInt(decodedPayload[22].toString(10)) / 2; this.devices[address].windowOpenTemperature = parseInt(decodedPayload[23].toString(10)) / 2; return this.devices[address]; } return null; }; MaxCube.prototype.parseCommandMetadata = function (payload) { var payloadArr = payload.split(","); var decodedPayload = new Buffer(payloadArr[2], 'base64'); var room_count = parseInt(decodedPayload[2].toString(10)); var currentIndex = 3; // parse rooms for (var i = 0; i < room_count; i++) { var roomData = {}; roomData.roomId = parseInt(decodedPayload[currentIndex].toString(10)); var room_length = parseInt(decodedPayload[currentIndex + 1].toString(10)); roomData.name = decodedPayload.slice(currentIndex + 2, currentIndex + 2 + room_length).toString('utf-8'); roomData.groupAddress = decodedPayload.slice(currentIndex + 2 + room_length, currentIndex + room_length + 5).toString('hex'); this.rooms.push(roomData); currentIndex = currentIndex + room_length + 5; } if (currentIndex < decodedPayload.length) { this.deviceCount = parseInt(decodedPayload[currentIndex].toString(10)); for (var j = 0; j < this.deviceCount; j++) { var deviceData = {}; deviceData.type = this.getDeviceType(parseInt(decodedPayload[currentIndex + 1].toString(10))); deviceData.address = decodedPayload.slice(currentIndex + 2, currentIndex + 5).toString('hex'); deviceData.serial = decodedPayload.slice(currentIndex + 5, currentIndex + 13).toString(); device_length = parseInt(decodedPayload[currentIndex + 15].toString(10)); deviceData.name = decodedPayload.slice(currentIndex + 16, currentIndex + 16 + device_length).toString('utf-8'); deviceData.roomId = parseInt(decodedPayload[currentIndex + 16 + device_length].toString(10)); this.devices[deviceData.address] = deviceData; currentIndex = currentIndex + 16 + device_length; } } return { rooms: this.rooms, devices: this.devices }; }; MaxCube.prototype.parseCommandDeviceList = function (payload) { var decodedPayload = new Buffer(payload, 'base64'); var currentIndex = 1; var actualTemp = 0; for(var i = 0; i < this.deviceCount, currentIndex < decodedPayload.length; i++) { var data = ''; var length = parseInt(decodedPayload[currentIndex - 1].toString()); var address = decodedPayload.slice(currentIndex, currentIndex + 3).toString('hex'); if (this.devices[address] && (this.devices[address].type == 'Heating Thermostat' || this.devices[address].type == 'Heating Thermostat Plus') ) { this.devices[address].valve = decodedPayload[currentIndex + 6]; this.devices[address].setpoint = parseInt(decodedPayload[currentIndex + 7].toString(10)) / 2; /* byte 5 from http://www.domoticaforum.eu/viewtopic.php?f=66&t=6654 5 1 12 bit 4 Valid 0=invalid;1=information provided is valid bit 3 Error 0=no; 1=Error occurred bit 2 Answer 0=an answer to a command,1=not an answer to a command bit 1 Status initialized 0=not initialized, 1=yes 12 = 00010010b = Valid, Initialized */ this.devices[address].initialized = !!(decodedPayload[currentIndex + 4] & (1 << 1)); this.devices[address].fromCmd = !!(decodedPayload[currentIndex + 4] & (1 << 2)); this.devices[address].error = !!(decodedPayload[currentIndex + 4] & (1 << 3)); this.devices[address].valid = !!(decodedPayload[currentIndex + 4] & (1 << 4)); this.devices[address].dstActive = !!(decodedPayload[currentIndex + 5] & 8); this.devices[address].gatewayKnown = !!(decodedPayload[currentIndex + 5] & 16); this.devices[address].panelLocked = !!(decodedPayload[currentIndex + 5] & 32); this.devices[address].linkError = !!(decodedPayload[currentIndex + 5] & 64); data = padLeft(decodedPayload[currentIndex + 5].toString(2), 8); this.devices[address].battery = parseInt(data.substr(0, 1)) ? 'low' : 'ok'; switch (data.substr(6, 2)) { case '00': mode = "auto"; break; case '01': mode = "manu"; break; case '10': mode = "vacation"; break; case '11': mode = "boost"; break; } if(typeof mode == "string") { this.devices[address].mode = mode; } if(decodedPayload[currentIndex + 8] !== 0 || decodedPayload[currentIndex + 9] !== 0) { actualTemp = (decodedPayload[currentIndex + 8] * 256 + decodedPayload[currentIndex + 9]) / 10; } else { actualTemp = undefined; } this.devices[address].actualTemperature = actualTemp; } else if (this.devices[address] && this.devices[address].type === 'Wall mounted Thermostat') { actualTemp = (decodedPayload[currentIndex + 11] + (decodedPayload[currentIndex + 7] & 0x80) * 2) / 10; this.devices[address].actualTemperature = actualTemp; this.devices[address].battery = parseInt(data.substr(0, 1)) ? 'low' : 'ok'; } else if (this.devices[address] && this.devices[address].type === 'Shutter Contact') { data = padLeft(decodedPayload[currentIndex + 5].toString(2), 8); this.devices[address].state = parseInt(data.substr(6, 1)) ? 'open' : 'closed'; this.devices[address].battery = parseInt(data.substr(0, 1)) ? 'low' : 'ok'; } currentIndex = currentIndex + length + 1; } return this.devices; }; MaxCube.prototype.parseCommandSendDevice = function (payload) { var payloadArr = payload.split(","); var dataObj = { accepted: payloadArr[1] == '0', duty_cycle: parseInt(payloadArr[0], 16), free_memory_slots: parseInt(payloadArr[2], 16) }; this.dutyCycle = dataObj.duty_cycle; this.memorySlots = dataObj.free_memory_slots; this.emit('status', { dutyCycle: this.dutyCycle, memorySlots: this.memorySlots }); this.emit('response', dataObj); return dataObj; }; MaxCube.prototype.allWindowsClosed = function(roomId) { var self = this; if(!self.devices) { return; } // check if a window is open var isWindowOpen = false; Object.keys(self.devices).forEach(function(key) { var otherDevice = self.devices[key]; if(otherDevice.type === 'Shutter Contact' && otherDevice.roomId === roomId && otherDevice.state !== 'closed') { isWindowOpen = true; } }); return !isWindowOpen; }; MaxCube.prototype.setTemperature = function (rfAddress, mode, temperature, callback) { var reqTempHex, reqTempBinary, reqRoomHex; var self = this; if (this.connectionState !== 'connected') { callback(new Error("Not connected")); return; } var date_until = '0000'; var time_until = '00'; // 00 = Auto weekprog (no temp is needed, just make the whole byte 00) // 01 = Permanent // 10 = Temporarily var modeBin; switch (mode) { case 'auto': modeBin = '00'; break; case 'manu': modeBin = '01'; break; case 'boost': modeBin = '11'; break; default: callback(new Error('Unknown mode: ' + mode)); return false; } var device = this.devices[rfAddress]; if(!device) { callback(new Error("Could not find a device with this rfAddress!")); return; } var roomId = device.roomId; reqRoomHex = padLeft(roomId.toString(16), 2); if(mode == 'auto' && (typeof temperature === "undefined" || temperature === null)) { reqTempHex = '00'; } else { reqTempBinary = modeBin + ("000000" + (temperature * 2).toString(2)).substr(-6); reqTempHex = padLeft(parseInt(reqTempBinary, 2).toString(16), 2); } var payload = new Buffer('000440000000' + rfAddress + reqRoomHex + reqTempHex + date_until + time_until, 'hex').toString('base64'); var data = 's:' + payload + '\r\n'; this.send(data, function(err) { if(err) { this.connectionState = 'disconnected'; if(callback) { callback(err); callback = null; } else { this.client.emit('error', err); } } else { var timeoutTime = 10000; setTimeout(function(){ if(!callback) { return; } callback(new Error("No answer from cube after " + timeoutTime + "ms")); callback = null; }, timeoutTime) } }.bind(this)); this.once('response', function(res) { if(!callback) { return; } if(res.accepted) { callback(null); } else { var reason = ""; var reasonCode = "Unknown"; if(res.free_memory_slots === 0) { reason = ": Too many commands send, the cube has no memory slots left."; reasonCode = "NO_MEMORY"; } else { var isWindowOpen = !self.allWindowsClosed(roomId); if(isWindowOpen) { reason = ": A window in the room is open"; reasonCode = "WINDOW_OPEN"; } } var err = new Error('Command was rejected' + reason); err.code = reasonCode; callback(err); } callback = null; }); }; MaxCube.prototype.sendResetError = function (rfAddress, callback) { var payload = new Buffer(rfAddress).toString('base64'); var data = 'r:01,' + payload + '\r\n'; this.send(data, callback); }; module.exports = MaxCube;
'use strict'; module.exports = { port: 443, db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/davidjonesguru', assets: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.min.css', 'public/lib/bootstrap/dist/css/bootstrap-theme.min.css', ], js: [ 'public/lib/angular/angular.min.js', 'public/lib/angular-resource/angular-resource.min.js', 'public/lib/angular-animate/angular-animate.min.js', 'public/lib/angular-ui-router/release/angular-ui-router.min.js', 'public/lib/angular-ui-utils/ui-utils.min.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js' ] }, css: 'public/dist/application.min.css', js: 'public/dist/application.min.js' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: 'https://localhost:443/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
'use strict'; /** * module dependencies */ var path = require('path'); var Core = require('assemble-core'); var utils = require('./lib/utils'); var cli = require('./lib/cli'); /** * Create an `assemble` app. This is the main function exported * by the assemble module. * * ```js * var assemble = require('assemble'); * var app = assemble(); * ``` * @param {Object} `options` Optionally pass default options to use. * @api public */ function Assemble(options) { if (!(this instanceof Assemble)) { return new Assemble(options); } Core.apply(this, arguments); this.isAssemble = true; this.initAssemble(this); } /** * Inherit assemble-core */ Core.extend(Assemble); /** * Initialize Assemble defaults */ Assemble.prototype.initAssemble = function(app) { var opts = this.options; var exts = opts.exts || ['md', 'hbs', 'html']; var regex = utils.extRegex(exts); // ensure `name` is set for composer-runtimes if (!this.name) { this.name = opts.name || 'base'; } /** * Register plugins */ this.use(utils.pipeline(opts)) .use(utils.pipeline()) .use(utils.loader()) .use(utils.config()) .use(utils.store()) .use(utils.argv()) .use(utils.list()) .use(utils.cli()) .use(utils.ask()) .use(cli()); /** * Default engine */ this.engine(exts, require('engine-handlebars')); /** * Middleware for parsing front matter */ this.onLoad(regex, function(view, next) { // needs to be inside the middleware, to // account for options defined after init if (view.options.frontMatter !== false && app.options.frontMatter !== false) { utils.matter.parse(view, next); } else { next(); } }); /** * Built-in view collections * | partials * | layouts * | pages */ var engine = opts.defaultEngine || 'hbs'; this.create('partials', { engine: engine, viewType: 'partial', renameKey: function(fp) { return path.basename(fp, path.extname(fp)); } }); this.create('layouts', { engine: engine, viewType: 'layout', renameKey: function(fp) { return path.basename(fp, path.extname(fp)); } }); this.create('pages', { engine: engine, renameKey: function(fp) { return fp; } }); }; /** * Set a `base` instance that can be used for storing * additional instances. */ Object.defineProperty(Assemble.prototype, 'base', { configurable: true, get: function() { return this.parent ? this.parent.base : this; } }); /** * Expose `Assemble` */ module.exports = Assemble;
module.exports = { QueryCache : require('./src/QueryCache'), };
'use strict'; var factory = require('../octicon.js'); // This is an auto-generated ES2015 icon from the modularize script. Please do not modify this file. var foldUp = factory('fold-up', 14, 16, {"fill-rule":"evenodd","d":"M10 6L7 3 4 6h2v6h2V6h2zm4 0c0-.55-.45-1-1-1h-2.5l1 1h1l-2 2H9v1h1.5l2 2H9v1h4c.55 0 1-.45 1-1l-2.5-2.5L14 6zM3.5 8H5v1H3.5l-2 2H5v1H1c-.55 0-1-.45-1-1l2.5-2.5L0 6c0-.55.45-1 1-1h2.5l-1 1h-1l2 2z"}, ["unfold","hide","collapse","up"]); module.exports = foldUp;
angular.module('felt.color.service', []) // A RESTful factory for retrieving contacts from 'contacts.json' .factory('Color', ['$http', 'utils', function ($http, utils) { var colorPromise = null; var factory = {}; factory.getColorInfo = function(hexColor) { if (colorPromise == null) { console.log("Acquiring info for color " + hexColor + " ..."); colorPromise = $http.get("http://www.colorhexa.com/" + hexColor).then(function (resp) { return resp.data; }); } return colorPromise; } return factory; }]);
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Feathers = void 0; const version_1 = __importDefault(require("./version")); const dependencies_1 = require("./dependencies"); const events_1 = require("./events"); const index_1 = require("./hooks/index"); const service_1 = require("./service"); const regular_1 = require("./hooks/regular"); const debug = (0, dependencies_1.createDebug)('@feathersjs/feathers'); class Feathers extends dependencies_1.EventEmitter { constructor() { super(); this.services = {}; this.settings = {}; this.mixins = [index_1.hookMixin, events_1.eventMixin]; this.version = version_1.default; this._isSetup = false; this.appHooks = { [dependencies_1.HOOKS]: [events_1.eventHook] }; this.regularHooks = (0, regular_1.enableRegularHooks)(this); } get(name) { return this.settings[name]; } set(name, value) { this.settings[name] = value; return this; } configure(callback) { callback.call(this, this); return this; } defaultService(location) { throw new Error(`Can not find service '${location}'`); } service(location) { const path = ((0, dependencies_1.stripSlashes)(location) || '/'); const current = this.services[path]; if (typeof current === 'undefined') { this.use(path, this.defaultService(path)); return this.service(path); } return current; } use(path, service, options) { if (typeof path !== 'string') { throw new Error(`'${path}' is not a valid service path.`); } const location = ((0, dependencies_1.stripSlashes)(path) || '/'); const subApp = service; const isSubApp = typeof subApp.service === 'function' && subApp.services; if (isSubApp) { Object.keys(subApp.services).forEach(subPath => this.use(`${location}/${subPath}`, subApp.service(subPath))); return this; } const protoService = (0, service_1.wrapService)(location, service, options); const serviceOptions = (0, service_1.getServiceOptions)(service, options); for (const name of service_1.protectedMethods) { if (serviceOptions.methods.includes(name)) { throw new Error(`'${name}' on service '${location}' is not allowed as a custom method name`); } } debug(`Registering new service at \`${location}\``); // Add all the mixins this.mixins.forEach(fn => fn.call(this, protoService, location, serviceOptions)); // If we ran setup already, set this service up explicitly, this will not `await` if (this._isSetup && typeof protoService.setup === 'function') { debug(`Setting up service for \`${location}\``); protoService.setup(this, location); } this.services[location] = protoService; return this; } hooks(hookMap) { const regularMap = hookMap; if (regularMap.before || regularMap.after || regularMap.error) { return this.regularHooks(regularMap); } if (Array.isArray(hookMap)) { this.appHooks[dependencies_1.HOOKS].push(...hookMap); } else { const methodHookMap = hookMap; Object.keys(methodHookMap).forEach(key => { const methodHooks = this.appHooks[key] || []; this.appHooks[key] = methodHooks.concat(methodHookMap[key]); }); } return this; } setup() { let promise = Promise.resolve(); // Setup each service (pass the app so that they can look up other services etc.) for (const path of Object.keys(this.services)) { promise = promise.then(() => { const service = this.service(path); if (typeof service.setup === 'function') { debug(`Setting up service for \`${path}\``); return service.setup(this, path); } }); } return promise.then(() => { this._isSetup = true; return this; }); } } exports.Feathers = Feathers; //# sourceMappingURL=application.js.map
'use strict'; /** * @ngdoc function * @name typrApp.controller:ContactCtrl * @description * # ContactCtrl * Controller of the typrApp */ angular.module('typrApp') .controller('ContactCtrl', function ($scope) { $scope.awesomeThings = []; });
import Render, { component } from './render' const TICK = 'TICK' export default function run(App) { const canvas = document.createElement('canvas') const ctx = canvas.getContext('2d') canvas.id = 'game' canvas.width = window.innerWidth || 800 canvas.height = window.innerHeight || 600 document.body.appendChild(canvas) let state const dispatch = action => { if (App.update) state = App.update(state, action) } dispatch({ type: 'INIT' }) const tick = () => { try { dispatch({ type: TICK }) setTimeout(() => tick(), 1000 / 60) } catch(e) { console.error('Stopping game reason below!') throw e } } let stop = false const render = () => { try { if (!stop) requestAnimationFrame(render) Render(<App state={state} dispatch={dispatch} />, ctx) } catch(e) { stop = true console.error('Render stopping game reason below!') throw e } } tick() render() }
'use strict'; angular.module('myApp.carousel', [ 'myApp.carousel.carousel-service', 'myApp.carousel.carousel-directive' ]);
/** * Created by benseager on 16/07/2017. */ "use strict"; const factory = require('./factory'); const logger = require('./logger'); const keyMapping = { events: 'events.json' }; module.exports = { get: (key) => { logger.log(logger.logType.INFO, 'repository.get'); return new Promise((resolve, reject) => { if (!keyMapping[key]) reject(new Error(`Can't get ${key}`)); const s3 = factory.instance('s3'); const params = { Bucket: process.env.BUCKET_NAME || 'ncfsc', Key: keyMapping[key] }; s3.getObject(params, (err, response) => { if (err) { logger.log(logger.logType.ERR, 's3.getObject'); logger.log(logger.logType.ERR, err); reject (err); } let data; try { logger.log(logger.logType.INFO, 'repository.get - parsing data'); data = response.Body.toString('utf-8'); resolve(JSON.parse(data)); } catch(err) { logger.log(logger.logType.ERR, 'parsing'); logger.log(logger.logType.ERR, err); reject(err); } }); }); } };
M.BillsView = M.BaseView.extend({ className: 'bills', collection: new M.Bills(), templatePath: 'bills/index', events: { 'change #repeat-intervals': 'togglePaymentSourceSelection', 'click #toggle-create-bill-form': 'toggleForm', 'submit #create-bill-form': 'handleSubmit', 'click .show-payment-sources': 'showCards', 'click .show-profile': 'showProfile', 'click .show-bills': 'showBills', 'click .signout': 'signout' }, initialize: function() { this.listenTo(this.collection, 'add', this.addBill); this.listenTo(this.collection, 'error', this.handleError); this.listenTo(this.collection, 'invalid', this.handleInvalid); this.render(); this.collection.fetch(); }, render: function() { this.setPageTitle('bills'); this.$el.html(this.template()); $('#money').html(this.el); this.populateCategories(); this.populateRepeatIntervals(); this.populatePaymentSources(); return this; }, addBill: function(bill) { var condensedBillView = new M.CondensedBillView({ model: bill }); this.$('.condensed-bills').append(condensedBillView.render().el); }, // FIXME: this needs to be replaced with better error handling handleError: function(collection, response, options) { $('#money').text(response.status + ' ' + response.statusText); }, handleSubmit: function(e) { e.preventDefault(); var props = this.createAttributesObject(this.$('#create-bill-form').serializeArray()); props = this.formatParams(props); var newBill = this.collection.create(props, this.validationOptions()); newBill.on('sync', function(e) { this.resetForm(this.$('#create-bill-form')[0]); this.$('#repeat-intervals').trigger('change'); }, this); }, validationOptions: function() { return { wait: true, nonRecurringBill: this.isNonRecurringBill() }; }, isNonRecurringBill: function(e) { return ('one_time' == this.$('#repeat-intervals option:selected').data('interval')) }, populateCategories: function() { var categoriesView = new M.CategoriesView(); categoriesView.render(); }, populateRepeatIntervals: function() { var repeatIntervalsView = new M.RepeatIntervalsView(); repeatIntervalsView.render(); }, populatePaymentSources: function() { var paymentSourcesListView = new M.PaymentSourcesListView(); this.$('#payment-source-id').html(paymentSourcesListView.render().el); }, // format tags: "one, two, three" => ["one", "two", "three"] formatParams: function(props) { props.next_due_date = this.formatDate(props.next_due_date); props.tags = props.tags.split(','); return props; }, toggleForm: function(e) { e.preventDefault(); this.$('#create-bill-form').toggle('fast'); this.toggleText(this.$('#toggle-create-bill-form')); }, toggleText: function($link) { if ('+ create bill' == $link.text()) { $link.text('- create bill'); } else { $link.text('+ create bill'); } }, togglePaymentSourceSelection: function(e) { var $paymentSourceEl = $(e.target); var interval = $paymentSourceEl.find(':selected').data('interval'); if ('one_time' == interval) { this.$('.select-card-form-group').show('fast'); } else { this.$('.select-card-form-group').hide('fast'); } } });
// !LOCNS:galactic_war_credits define([], function () { return { name: 'Design', color: [[207,93,255], [192,192,192]], teams: [ { boss: { name: 'John Comes', description: [ '<div class="div_credits_title">', '!LOC:Design Director', '</div>' ], icon: 'coui://ui/main/game/galactic_war/shared/img/icon_faction_design.png', iconColor: [207,93,255], commander: '/pa/units/commanders/tank_aeson/tank_aeson.json', }, workers: [ { name: 'Tom Vinita', description: [ '<div class="div_credits_title">', '!LOC:Designer', '</div>' ], } ] } ], // teams minions: [ ] // minions }; });
/* eslint-env jest */ 'use strict' const assertErr = require('../') describe('assertErr', () => { test('if falsy, throws given error', () => { const fn = () => assertErr(false, ReferenceError, 'value does not exist') expect(fn).toThrowError(ReferenceError) expect(fn).toThrow('value does not exist') }) test('if truthy, does not throw error', () => { assertErr('truthy', Error, 'this should not throw') }) test('makes the stack strace start from assertion line', () => { const fn = () => assertErr(false, TypeError, 'my error') try { fn() } catch (err) { const stack = err.stack.split('\n') expect(stack[0]).toContain('TypeError: my error') expect(stack[1]).toContain(__filename) return } assertErr(false, Error, 'Error was not thrown') }) test('works with really custom error type', () => { class MyError extends Error { constructor (...args) { super(...args) delete this.stack } } const fn = () => assertErr(false, MyError) expect(fn).toThrowError(MyError) }) })
/*: * @plugindesc Applies pixi filter to the spriteset * @author Cristian Carlesso <kentaromiura> * Alpha, use at your risk * @help * ============================================================================ * Introduction * ============================================================================ * This plugin allows you to apply some predefined filters * to the spriteset. * The filters will only be visible in environment supporting a webGL context, * where this is not avaiable they will simply not show. * * ============================================================================ * Plugin Commands * ============================================================================ * * Plugin Command * RemoveSpriteSetFilter $filter Removes the specif filter if exists * RemoveAllSpriteSetFilters Removes any filter applied * AppendSpriteSetFilter $filter Adds a filter at the end of the list * PrependSpriteSetFilter $filter Adds a filter at the begin of the list * * where $filter can be any of the following: * Blur, BlurX, BlurY, ColorMatrix, ColorStep, CrossHatch, DotScreen, Gray, * Invert, Pixelate, RGBSplit, Sepia, Twist * ============================================================================ */ require('../../Common/Events/GameInterpreter/commandInvoked')() var filterList = [] function addToFilter(filter){ filterList.push(new PIXI[filter]) } global.addEventListener('commandInvoked', function(event){ var args = event.detail.args var command = args[0] var parameters = args[1] switch (command){ case 'RemoveSpriteSetFilter': var filterType = parameters[0] + 'Filter' if (filterType in PIXI){ var filterTypeToRemove = PIXI[filterType] filterList = filterList.filter(function(filter){ return ! (filter instanceof filterTypeToRemove) }) } break case 'RemoveAllSpriteSetFilters': filterList = [] break case 'AppendSpriteSetFilter': var filterType = parameters[0] + 'Filter' if (filterType in PIXI){ addToFilter(filterType) } break case 'PrependSpriteSetFilter': var filterType = parameters[0] + 'Filter' if (filterType in PIXI){ filterList.unshift(new PIXI[filterType]) } break } if (filterList.length > 0) { SceneManager._scene._spriteset.filters = filterList } else { SceneManager._scene._spriteset.filters = undefined delete SceneManager._scene._spriteset.filters //? } })
(function() { 'use strict'; angular .module('plagUiApp') .constant('paginationConstants', { 'itemsPerPage': 20 }); })();
module.exports = { nepq: `create test.product(name: "p1", price: 100) { }`, obj: { method: 'create', name: 'test.product', params: [{ name: 'p1', price: 100 }], retrieves: 0, $_: 1 } }
import SchemaSnapshot from '../../Schema/SchemaSnapshot'; export default class DynamicSnapshot extends SchemaSnapshot {}
// Functions that process dates given a certain set of frequency and formatting // settings // Node modules var d3 = require("d3"); require("sugar-date"); // Parse dates and return strings based on selected format var dateParsers = { "lmdy": function(d, i, o) { if(o) { d.addMinutes(o) } return d.format('{M}/{d}/{yy}'); }, "mmdd": function(d, i, o) { if(o) { d.addMinutes(o) } return d.format('{M}/{d}'); }, "Mdd": function(d, i, o) { if(o) { d.addMinutes(o) } var month = d.getMonth() + 1; if (month == 5) { return d.format('{Month} {d}'); } else { return d.format('{Mon}. {d}'); } }, "M1d": function(d,i,o) { if(o) { d.addMinutes(o) } var date = d.getDate(); if(date == 1) { return dateParsers.M(d); } else if (i === 0) { return dateParsers.M(d) + d.format(' {d}'); } else { return d.format('{d}'); } }, "ddM": function(d, i, o) { if(o) { d.addMinutes(o) } var month = d.getMonth() + 1; if (month == 5) { return d.format('{d} {Month}'); } else { return d.format('{d} {Mon}.'); } }, "mmyy": function(d, i, o) { if(o) { d.addMinutes(o) } return d.format('{M}/' + dateParsers.yyyy(d).slice(-2)); }, "yy": function(d, i, o) { if(o) { d.addMinutes(o) } return "’" + dateParsers.yyyy(d).slice(-2); }, "yyyy": function(d, i, o) { if(o) { d.addMinutes(o) } return "" + d.getFullYear(); }, "MM": function(d, i, o) { if(o) { d.addMinutes(o) } var month = d.getMonth() + 1; if (month == 1) { return "" + d.getFullYear(); } else { return d.format('{Month}'); } }, "M": function(d, i, o) { if(o) { d.addMinutes(o) } var month = d.getMonth() + 1; if (month == 1) { return "’" + dateParsers.yyyy(d).slice(-2); } else if (month == 5) { return d.format('{Mon}'); } else { return d.format('{Mon}.'); } }, "hmm": function(d, i, o) { if(o) { d.addMinutes(o) } return d.format("{h}:{mm}"); }, "h": function(d, i, o) { if(o) { d.addMinutes(o) } return d.format("{h}{tt}"); }, "QJan": function(d, i, o) { if(o) { d.addMinutes(o) } var year = d.getFullYear(); var month = d.getMonth() + 1; var day = d.getDate(); if (day == 1) { if (month == 1) { return year; } if (month == 4 || month == 7 || month == 10) { return "Q" + (((month - 1) / 3) + 1); } } return ""; }, "QJul": function(d, i, o) { if(o) { d.addMinutes(o) } var year = d.getFullYear(); var month = d.getMonth() + 1; var day = d.getDate(); if (day == 1) { if (month == 7) { return year; } if (month == 1) { return "Q3"; } if (month == 4) { return "Q4"; } if (month == 10) { return "Q2"; } } return ""; } }; // Define time intervals and number of steps for date frequency options var dateFrequencies = { "auto": { interval: null, steps: null }, "1h": function(minDate, maxDate) { var interval = d3.time.hour; return interval.range(minDate, maxDate, 1); }, "2h": function(minDate, maxDate) { var interval = d3.time.hour; return interval.range(minDate, maxDate, 2); }, "3h": function(minDate, maxDate) { var interval = d3.time.hour; return interval.range(minDate, maxDate, 3); }, "4h": function(minDate, maxDate) { var interval = d3.time.hour; return interval.range(minDate, maxDate, 4); }, "6h": function(minDate, maxDate) { var interval = d3.time.hour; return interval.range(minDate, maxDate, 6); }, "1d": function(minDate, maxDate) { var interval = d3.time.day; return interval.range(minDate, maxDate, 1); }, "1w": function(minDate, maxDate) { var interval = d3.time.week; return interval.range(minDate, maxDate, 1); }, "1m": function(minDate, maxDate) { var interval = d3.time.month; return interval.range(minDate, maxDate, 1); }, "3m": function(minDate, maxDate) { var interval = d3.time.month; return interval.range(minDate, maxDate, 3); }, "6m": function(minDate, maxDate) { var interval = d3.time.month; return interval.range(minDate, maxDate, 6); }, "1y": function(minDate, maxDate) { var interval = d3.time.year; maxDate = d3.time.day.offset(maxDate, 1); return interval.range(minDate, maxDate, 1); }, "2y": function(minDate, maxDate) { var interval = d3.time.year; maxDate = d3.time.day.offset(maxDate, 1); return interval.range(minDate, maxDate, 2); }, "4y": function(minDate, maxDate) { var interval = d3.time.year; maxDate = d3.time.day.offset(maxDate, 4); output = interval.range(minDate, maxDate, 4).map(function(d) { var fullYear = d.getFullYear() return new Date(fullYear - ((fullYear + 2) % 4), 1, 1) }); var last = output[output.length-1] output.push(new Date(last.getFullYear() + 4,1,1)) return output; }, "5y": function(minDate, maxDate) { var interval = d3.time.year; maxDate = d3.time.day.offset(maxDate, 1); return interval.range(minDate, maxDate, 5); }, "10y": function(minDate, maxDate) { var interval = d3.time.year; maxDate = d3.time.day.offset(maxDate, 1); return interval.range(minDate, maxDate, 10); }, "20y": function(minDate, maxDate) { var interval = d3.time.year; maxDate = d3.time.day.offset(maxDate, 1); return interval.range(minDate, maxDate, 20); }, "100y": function(minDate, maxDate) { var interval = d3.time.year; maxDate = d3.time.day.offset(maxDate, 1); return interval.range(minDate, maxDate, 100); }, "us-pe4": function(minDate, maxDate) { // only label US presidential election years var interval = d3.time.year; maxDate = d3.time.day.offset(maxDate, 4); var yearMod = minDate.getFullYear() % 4; minDate = new Date(minDate.getFullYear() - yearMod,1,1) return interval.range(minDate, maxDate, 4); }, "us-me4": function(minDate, maxDate) { // only label US midterm election years var interval = d3.time.year; maxDate = d3.time.day.offset(maxDate, 4); output = interval.range(minDate, maxDate, 4).map(function(d) { var fullYear = d.getFullYear() return new Date(fullYear - ((fullYear + 2) % 4),1,1) }); var last = output[output.length-1] output.push(new Date(last.getFullYear() + 4,1,1)) return output } }; function humanReadableNumber(n) { //turns a number into an int that is either 1, 2, 5, or a multiple of 10 var rounded = Math.round(n); if (rounded < 2) { return 1; } if (n < 3.5) { return 2; } if (n < 7) { return 5; } if (n <= 10) { return 10; } var magnitude = Math.floor((Math.log(n) / Math.LN10)) + 1; var factor = Math.pow(10,magnitude); return humanReadableNumber(n/factor) * factor; } // Automatically calculate date frequency if not selected function autoDateFormatAndFrequency(minDate, maxDate, dateFormat, availableWidth) { var timespan = Math.abs(maxDate - minDate); var years = timespan / 31536000000; var months = timespan / 2628000000; var days = timespan / 86400000; var yearGap; var hourGap; var interval; var targetPixelGap = 64; var maximum_ticks = Math.floor(availableWidth / targetPixelGap); var time_gap = timespan / maximum_ticks; if (dateFormat == "auto") { //lets go small to large if (days <= 2) { dateFormat = "h"; } else if (days <= 91) { dateFormat = "M1d"; } else if (months < 36) { dateFormat = "M"; } else { dateFormat = "yy"; } } var gapInYears = humanReadableNumber(Math.floor(time_gap / 31536000000)); var gapInMonths = Math.ceil(time_gap / 2628000000); var gapInDays = humanReadableNumber(time_gap / 86400000); var gapInHours = humanReadableNumber(time_gap / 3600000); //make sure that the interval include the maxDate in the interval list maxDate.addMilliseconds(0.1); switch (dateFormat) { case "yy": // Add a day to the max date for years to make inclusive of max date // irrespective of time zone / DST maxDate = d3.time.day.offset(maxDate, 1); interval = d3.time.year.range(minDate, maxDate, gapInYears); break; case "yyyy": // See above maxDate = d3.time.day.offset(maxDate, 1); interval = d3.time.year.range(minDate, maxDate, gapInYears); break; case "MM": interval = d3.time.month.range(minDate, maxDate, gapInMonths); break; case "M": interval = d3.time.month.range(minDate, maxDate, gapInMonths); break; case "Mdd": interval = d3.time.day.range(minDate, maxDate, gapInDays); break; case "M1d": interval = d3.time.day.range(minDate, maxDate, gapInDays); break; case "YY": interval = d3.time.year.range(minDate, maxDate, gapInYears); break; case "QJan": interval = d3.time.month.range(minDate, maxDate, 4); break; case "QJul": interval = d3.time.month.range(minDate, maxDate, 4); break; case "h": interval = d3.time.hour.range(minDate, maxDate, gapInHours); break; default: interval = d3.time.year.range(minDate, maxDate, 1); } interval = cleanInterval(interval); return {"format": dateFormat, "frequency": interval}; } function cleanInterval(interval) { return interval.reduce(function(out, currDate, i, arr) { if (i === 0) { return [currDate]; } var prevDate = out[out.length - 1].getDate(); var excludeRange = (prevDate >= 28 && prevDate <= 31); if(excludeRange && currDate.getDate() == 1) { out.pop(); return out.concat(currDate); } else { return out.concat(currDate); } }, []); } module.exports = { dateParsers: dateParsers, dateFrequencies: dateFrequencies, autoDateFormatAndFrequency: autoDateFormatAndFrequency };
import dom from '../utils/dom' import BaseElement from './base.element' const bodyAnimationClass = 'sidr-animating' const openAction = 'open' function isBody (element) { return element.tagName === 'BODY' } function openClasses (name) { let classes = 'sidr-open' if (name !== 'sidr') { classes += ' ' + name + '-open' } return classes } class Body extends BaseElement { constructor (settings, menuWidth) { super(dom.qs(settings.body)) this.name = settings.name this.side = settings.side this.speed = settings.speed this.timing = settings.timing this.displace = settings.displace this.menuWidth = menuWidth } prepare (action) { var prop = (action === openAction) ? 'hidden' : '' // Prepare page if container is body if (isBody(this.element)) { let html = new BaseElement(dom.qs('html')) let scrollTop = html.scrollTop() html.style('overflowX', prop) html.scrollTop(scrollTop) } } unprepare () { if (isBody(this.element)) { let html = new BaseElement(dom.qs('html')) html.style('overflowX', '') } } move (action) { this.addClass(bodyAnimationClass) if (action === openAction) { this.open() } else { this.close() } } open () { if (this.displace) { let transitions = dom.transitions let styles = { width: this.offsetWidth() + 'px', position: 'absolute' } this.style(this.side, '0') this.style(transitions.cssProperty, this.side + ' ' + (this.speed / 1000) + 's ' + this.timing) this.style(styles) setTimeout(() => this.style(this.side, this.menuWidth + 'px'), 1) } } onClose () { let transitions = dom.transitions let styles = { width: '', position: '', right: '', left: '' } styles[transitions.cssProperty] = '' this.style(styles) this.unbind(transitions.event, this.temporalCallback) } close () { if (this.displace) { let transitions = dom.transitions this.style(this.side, 0) let self = this this.temporalCallback = () => { self.onClose() } this.bind(transitions.event, this.temporalCallback) } } removeAnimationClass () { this.removeClass(bodyAnimationClass) } removeOpenClass () { this.removeClass(openClasses(this.name)) } addOpenClass () { this.addClass(openClasses(this.name)) } } export default Body
require("../../vendors/bootstrap/dist/css/bootstrap.min.css"); require("../../vendors/font-awesome/scss/font-awesome.scss"); require("../../vendors/nprogress/nprogress.css"); require("../../vendors/iCheck/skins/flat/green.css"); require("../../vendors/bootstrap-progressbar/css/bootstrap-progressbar-3.3.4.min.css"); require("../../vendors/google-code-prettify/bin/prettify.min.css"); require("../../vendors/select2/dist/css/select2.min.css"); require("../../vendors/switchery/dist/switchery.min.css"); require("../../vendors/starrr/dist/starrr.css"); require("../../vendors/normalize-css/normalize.css"); require("../../vendors/ion.rangeSlider/css/ion.rangeSlider.css"); require("../../vendors/ion.rangeSlider/css/ion.rangeSlider.skinFlat.css"); require("../../vendors/mjolnic-bootstrap-colorpicker/dist/css/bootstrap-colorpicker.min.css"); require("../../vendors/cropper/dist/cropper.min.css"); require("../../vendors/pnotify/dist/pnotify.css"); require("../../vendors/pnotify/dist/pnotify.buttons.css"); //require("../../vendors/pnotify/dist/pnotify.nonblock.css"); require("../../vendors/datatables.net-bs/css/dataTables.bootstrap.min.css"); require("../../vendors/datatables.net-buttons-bs/css/buttons.bootstrap.min.css"); require("../../vendors/datatables.net-fixedheader-bs/css/fixedHeader.bootstrap.min.css"); require("../../vendors/datatables.net-responsive-bs/css/responsive.bootstrap.min.css"); require("../../vendors/datatables.net-scroller-bs/css/scroller.bootstrap.min.css"); require('../../vendors/bootstrap-switch/dist/css/bootstrap3/bootstrap-switch.css'); require('../../vendors/sweetalert2/dist/sweetalert2.min.css');
'use strict'; define(['AnguRaptor', 'controllers/TrendingBoxCtrl'], function(AnguRaptor) { AnguRaptor.directive('trendingBox', function() { return { restrict: 'E', templateUrl: './views/trending-box.html', controller: 'TrendingBoxCtrl' }; }); });
// // PayPalMobilePGPlugin.js // function PayPalPayment(amount, currency, shortDescription) { this.amount = amount; this.currency = currency; this.shortDescription = shortDescription; } /** * This class exposes the PayPal iOS SDK functionality to javascript. * * @constructor */ function PayPalMobile() {} /** * Retrieve the version of the PayPal iOS SDK library. Useful when contacting support. * * @parameter callback: a callback function accepting a string */ PayPalMobile.prototype.version = function(callback) { var failureCallback = function() { console.log("Could not retrieve PayPal library version"); }; cordova.exec(callback, failureCallback, "PayPalMobile", "version", []); }; /** * Set the environment that the PayPal iOS SDK uses. * * @parameter environment: string * Choices are "PayPalEnvironmentNoNetwork", "PayPalEnvironmentSandbox", or "PayPalEnvironmentProduction" */ PayPalMobile.prototype.setEnvironment = function(environment) { var failureCallback = function(error) { console.log(error); }; cordova.exec(null, failureCallback, "PayPalMobile", "setEnvironment", [environment]); }; /** * Retrieve the current PayPal iOS SDK environment: mock, sandbox, or live. * * @parameter callback: a callback function accepting a string */ PayPalMobile.prototype.environment = function(callback) { var failureCallback = function() { console.log("Could not retrieve PayPal environment"); }; cordova.exec(callback, failureCallback, "PayPalMobile", "environment", []); }; /** * You SHOULD preconnect to PayPal to prepare the device for processing payments. * This improves the user experience, by making the presentation of the * UI faster. The preconnect is valid for a limited time, so * the recommended time to preconnect is on page load. * * @parameter clientID: your client id from developer.paypal.com * @parameter callback: a parameter-less success callback function (normally not used) */ PayPalMobile.prototype.prepareForPayment = function(clientId) { var failureCallback = function(message) { console.log("Could not perform prepareForPurchase " + message); }; cordova.exec(null, failureCallback, "PayPalMobile", "prepareForPayment", [clientId]); }; /** * Start PayPal UI to collect payment from the user. * See https://developer.paypal.com/webapps/developer/docs/integration/mobile/ios-integration-guide/ * for more documentation of the parameters. * * @parameter clientId: clientId from developer.paypal.com * @parameter email: receiver's email address * @parameter payerId: a string that uniquely identifies a user within the scope of your system, such as an email address or user ID * @parameter payment: PayPalPayment object * @parameter completionCallback: a callback function accepting a js object, called when the user has completed payment * @parameter cancelCallback: a callback function accepting a reason string, called when the user cancels the payment */ PayPalMobile.prototype.presentPaymentUI = function(clientId, email, payerId, payment, completionCallback, cancelCallback) { cordova.exec(completionCallback, cancelCallback, "PayPalMobile", "presentPaymentUI", [clientId, email, payerId, payment]); }; /** * Plugin setup boilerplate. */ cordova.addConstructor(function() { if (!window.plugins) { window.plugins = {}; } if (!window.plugins.PayPalMobile) { window.plugins.PayPalMobile = new PayPalMobile(); } });
export const USER_INPUT = 'USER_INPUT'; export const USER_AUTH = 'USER_AUTH'; export const USER_UNAUTH = 'USER_UNAUTH'; export const AUTH_ERROR = 'AUTH_ERROR'; export const CLEAR_ERROR = 'CLEAR_ERROR'; export const REQUEST_PENDING = 'REQUEST_PENDING'; export const REQUEST_RESOLVED = 'REQUEST_RESOLVED';
function loadUser() { // main content renderCategory('#target-fun','FUN 趣味','爆發心中的小宇宙,校園就是我的遊樂場!'); renderCategory('#target-campus','CAMPUS 校園','在清華最後的日子,怎能不做點新鮮的事!'); renderCategory('#target-issue','ISSUE 議題','回顧這幾年直到如今,原來發生過這麼多事情!'); // Missions Modal var template = $('#template').html(); Mustache.parse(template); // optional, speeds up future uses for(var index = 1 ; index<= missions_info.length ; index++){ var rendered = Mustache.render(template, missions_info[index-1] ); $('#target').append(rendered); } } function renderAll(){ var template = $('#template-all').html(); Mustache.parse(template); for(var index = 1 ; index<= missions_info.length ; index++){ var rendered = Mustache.render(template, missions_info[index-1] ); $('#target-list-all').append(rendered); } } function renderCategory(target_id,category, description){ var template_fun = $('#template-category').html(); Mustache.parse(template_fun); var missions_catogory = missions_info.filter( function(element){ return element.category == category; }); var rendered = Mustache.render(template_fun, { category : category, description : description }); $(target_id).html(rendered); var template_content = $('#template-content').html(); Mustache.parse(template_content); var buffer = []; for(var index = 1 ; index <= missions_catogory.length ; index++){ buffer.push(missions_catogory[index-1]); if(buffer.length>=4){ var wrapper = $('<div class= "row">'); for(var j=0 ; j < buffer.length ; j++ ){ var num = buffer[j].id.substring(6, 9); buffer[j].num = num; wrapper.append(Mustache.render(template_content, buffer[j])); } $(target_id).append(wrapper); buffer = []; } } var wrapper = $('<div class= "row">'); for(var j = 0; j < buffer.length ; j++){ var num = buffer[j].id.substring(6, 9); buffer[j].num = num; wrapper.append(Mustache.render(template_content, buffer[j])); } $(target_id).append(wrapper); buffer = []; }
doWhenPresent('#search-input', function searchBarIsReady() { typeaheadCache.whenReady(function setUpTypeahead(cacheData) { let directHits = new Bloodhound({ datumTokenizer: function datumTokenizer(datum) { return Bloodhound.tokenizers.whitespace(datum.searchString); }, queryTokenizer: Bloodhound.tokenizers.whitespace, local: cacheData.directHits, }); let searchStrings = new Bloodhound({ datumTokenizer: function datumTokenizer(datum) { return Bloodhound.tokenizers.whitespace(datum.searchString); }, queryTokenizer: Bloodhound.tokenizers.whitespace, local: cacheData.searchStrings, }); $('#search-input').typeahead({ highlight: true, hint: false, }, { name: 'directHits', source: directHits, templates: { suggestion: directHitRow }, display: function getDisplayForItem(item) { return item.name; }, identify: function getIdForItem(item) { return item.id; }, limit: 4, }, { name: 'searchStrings', source: searchStrings, templates: { suggestion: searchStringRow }, display: function getDisplayForItem(item) { return item.id; }, identify: function getIdForItem(item) { return item.id; }, limit: 3, } ); $('#search-input').bind('typeahead:select', typeaheadClick); $('#search-input').bind('keypress', typeaheadKeypress); }); function directHitRow(item) { return ` <div class="typeahead-row"> <div class="typeahead-content name">` + item.name + `</div> <div class="typeahead-content model">` + item.model + `</div> <div class="typeahead-content desc">` + item.desc + `</div> </div> `; } function searchStringRow(item) { return ` <div class="typeahead-row"> <div class="typeahead-content search-string"> Search for &quot;` + item.searchString + `&quot; </div> </div> `; } function typeaheadClick(ev, item) { window.location.href = item.url; } function typeaheadKeypress(ev) { if(ev.keyCode !== 13) { return; } // if($('body.n_search.index').length > 0) { do stuff on the search page } else let url = new URL('/search', window.location.origin); // hack for Microsoft Edge. because Microsoft just can't manage to comply with web standards. // even after junking IE and rebuilding from scratch. if(typeof url.searchParams !== 'undefined') { url.searchParams.set('search_string', $('#search-input').val()); window.location.href = url.href; } else { window.location.href = url.href + '?search_string=' + encodeURIComponent($('#search-input').val()); } return false; }; }); doWhenPresent('body.n_search.index', function searchPageIsReady() { let search = JSON.parse($('#search-results').attr('json')); let subjectAreas = {}; for(let area of JSON.parse($('#groupings-data').attr('subject_areas'))) { subjectAreas[area.name] = { styling: 'background-color: ' + area.back_color + '; color: ' + area.color + '; padding: 0 10px;', order: area.display_order, href: area.link_to, } } let collections = {}; for(let collection of JSON.parse($('#groupings-data').attr('collections'))) { collections[collection.name] = collection.link_to; } let models = {}; for(let model of JSON.parse($('#groupings-data').attr('models'))) { models[model.name] = model.link_to; } // This will be used to create the checkboxes for "233 terms," "14 reports," etc. // We create it outside of Vue so that it will be frozen; when one of these boxes // gets checked, it won't cause all the others to vanish. let modelToLabel = (model, count) => { if(model === "BusinessProcess") { return (count > 1) ? "business procs" : "business proc"; } return model.toLowerCase() + (count > 1 ? 's' : ''); } let modelLinkList = []; for(model in search.counts.model_tag) { let count = search.counts.model_tag[model] || 0; if(count) { modelLinkList.push({ label: modelToLabel(model, count), model: model }); } } let modelIcons = { Report: 'fa-bar-chart', Dataset: 'fa-database', Dataview: 'fa-list-alt', Diagram: 'fa-object-group', Table: 'fa-table', Column: 'fa-columns', Collection: 'fa-folder-o', Term: 'fa-book', BusinessProcess: 'fa-briefcase', Resource: 'fa-question-circle', Event: 'fa-calendar-star', }; let vm = new Vue({ el: '#search-results', data: { query: search.query, results: search.results, counts: search.counts, subjectAreas: subjectAreas, collections: collections, models: models, modelFilters: {}, modelLinkList: modelLinkList, modelIcons: modelIcons, pageMin: Math.ceil(search.query.page / 10) * 10 - 9, pageMax: Math.min(Math.ceil(search.query.page / 10) * 10, search.counts.pages), }, template: ` <div class="search-results"> <div class="pageheader with-breadcrumb" id="page-content" style="padding-top: 20px;"> <div class="row"> <div class="col-lg-12"> <div class="panel"> <ol class="breadcrumb"> <li> <a href="/"> <i class="pli-home"></i> </a> </li> <li class="active"></li> </ol> <div class="panel-body"> <div class="panel media middle"> <div class="media-body pad-lft"> <h2>Search Results</h2> <span>{{ counts.total_count }} results found for &quot;{{ query.search_string }}&quot;</span> </div> </div> </div> </div> </div> </div> </div> <div id="page-content" > <div class="panel"> <div class="panel-body"> <div class="search-detail-bar pad-top" style="display: flex; flex-wrap: wrap;"> <div style="flex: none; margin-right: 15px;"> Filter search results: </div> <div style="flex: auto; display: flex; flex-wrap: wrap;"> <div class="text-capitalize" style="flex: none; margin-right: 20px;" v-for="(modelLink, modelLinkInd) in modelLinkList" > <input type="checkbox" :id="'toggle-filter-' + modelLink.model" v-on:change="toggleModelFilter(modelLink.model)" :checked="modelFilters[modelLink.model]" >&nbsp; <span> <i :class="'fa ' + modelIcons[modelLink.model]"></i> </span> {{ modelLink.label }}</input> </div> </div> </div> <hr class="new-section-xs bord-no" /> <ul class="list-group search-result-list"> <li class="list-item" v-for="(item, item_ind) in results"> <a class="search-result-row" v-bind:href="item.url"> <div class="search-result-content name"> <h4> <span> <i :class="'fa ' + modelIcons[item.model_tag]"></i> </span> {{ item.name }} </h4> <div class="search-result-tag subject-area" v-for="(subject, subject_ind) in item.subject_areas"> <object> <a class="btn btn-xs btn-rounded dataset_info" :style="subjectAreas[subject].styling" :href="subjectAreas[subject].href"> {{ subject }} </a> </object> </div> <div class="search-result-tag collection" v-for="(collection, collection_ind) in item.collections"> <object> <a class="btn btn-xs btn-rounded bord-all dataset_info" style="padding: 0 10px; background-color: white;" :href="collections[collection]"> {{ collection }} </a> </object> </div> </div> <div class="search-result-content desc"> {{ item.shortdesc }} </div> </a> </li> </ul> <div class="search-pages-list-wrapper"> <ul v-if="counts.pages > 1" class="search-pages-list pagination"> <template v-if="query.page === 1"> <li class="footable-page-arrow disabled"><a>«</a></li> <li class="footable-page-arrow disabled"><a>‹</a></li> </template> <template v-else> <li class="footable-page-arrow"> <a v-on:click="updateQuery({ page: 1, restorePaginateScrollPos: true })">«</a> </li> <li class="footable-page-arrow"> <a v-on:click="updateQuery({ page: query.page - 1, restorePaginateScrollPos: true })">‹</a> </li> </template> <li v-if="pageMin > 1"> <a v-on:click="updateQuery({ page: Math.max(query.page - 10, 1), restorePaginateScrollPos: true })">…</a> </li> <template v-for="page in counts.pages"> <li v-if="page >= pageMin && page <= pageMax" :key="page" :class="'footable-page' + (page === query.page ? ' active' : '')" > <a v-on:click="updateQuery({ page: page, restorePaginateScrollPos: true })" v-bind:class="page === query.page ? 'this-page' : 'other-page'" >{{ page }}</a> </li> </template> <li v-if="pageMax < counts.pages"> <a v-on:click="updateQuery({ page: Math.min(query.page + 10, counts.pages), restorePaginateScrollPos: true })">…</a> </li> <template v-if="query.page === counts.pages"> <li class="footable-page-arrow disabled"><a>›</a></li> <li class="footable-page-arrow disabled"><a>»</a></li> </template> <template v-else> <li class="footable-page-arrow"> <a v-on:click="updateQuery({ page: query.page + 1, restorePaginateScrollPos: true })">›</a> </li> <li class="footable-page-arrow"> <a v-on:click="updateQuery({ page: counts.pages, restorePaginateScrollPos: true })">»</a> </li> </template> </ul> </div> </div> </div> </div> </div> `, methods: { toggleModelFilter(model) { this.modelFilters[model] = !this.modelFilters[model]; modelsToShow = []; for(model in this.modelFilters) { if(this.modelFilters[model]) { modelsToShow.push(model); } } // Always jump back to page 1 when changing model filters, since // we might end up on an invalid page otherwise (e.g., we're on // page 6 and we filter the results down to 2 pages). this.updateQuery({ models: modelsToShow, page: 1 }); }, updateQuery(params) { let changed = false; for(param in params) { if(param === 'restorePaginateScrollPos') { continue; } if(this.query[param] !== params[param]) { changed = true; this.query[param] = params[param] } } if(!changed) { return; } $.ajax({ url: '/search.json?' + $.param(this.query), type: 'GET', beforeSend: function beforeSend(xhr) { xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content')); }, }). then(function updateResults(data) { let paginateScrollPos = $(window).scrollTop() - $('.search-pages-list-wrapper').offset().top; this.query = data.query; this.results = data.results; this.counts = data.counts; if(this.query.page >= 1 && this.query.page <= this.counts.pages) { while(this.query.page > this.pageMax) { this.pageMax = Math.min(this.pageMax + 10, this.counts.pages); this.pageMin = Math.max(this.pageMax - 9, 1); } while(this.query.page < this.pageMin) { this.pageMin = Math.max(this.pageMin - 10, 1); this.pageMax = Math.min(this.pageMin + 9, this.counts.pages); } } if(params.restorePaginateScrollPos) { Vue.nextTick(function restorePaginateScrollPos() { $(window).scrollTop(paginateScrollPos + $('.search-pages-list-wrapper').offset().top); }); } }.bind(this)); }, }, }); });
import Playground from './Playground' import { bindActionCreators } from 'redux' import { connect } from 'react-redux' import { actions as activeTabActions } from '../../redux/modules/activeTab' import { actions as codeActions } from '../../redux/modules/code' import { actions as compilingActions } from '../../redux/modules/compiling' const mapStateToProps = (state) => ({ activeTab: state.activeTab, compiling: state.compiling, ...state.code }) const mapDispatchToProps = (dispatch) => { return bindActionCreators({ ...activeTabActions, ...codeActions, ...compilingActions }, dispatch) } const mergeProps = (stateProps, dispatchProps, ownProps) => { // If code was not synced into store // Use code from ownProps if (!stateProps.isSynced) { return { ...dispatchProps, ...stateProps, ...ownProps, ...{ css: { original: ownProps.css }, html: { original: ownProps.html }, javascript: { original: ownProps.javascript } } } } // Or use code from store return { ...dispatchProps, ...ownProps, ...stateProps } } export default connect( mapStateToProps, mapDispatchToProps, mergeProps )(Playground)
var Usuari = require('../models/usuari'); exports.actionList = function (req, res) { /*if (req.user.es_admin) { Usuari.find(req.query, function (err, usuaris) { if (err) { console.error(new Date().toISOString(), err); res.status(500).json({codError: 500, descError: 'LIST: Error intern al servidor. Veure log'}); } else res.json(usuaris); }); } else {*/ res.json([req.user]); //} }; exports.actionShow = function (req, res) { if (req.user.es_admin) { Usuari.findById(req.params.id, function (err, usuari) { if (err) { console.error(new Date().toISOString(), err); res.status(500).json({codError: 500, descError: 'SHOW: Error intern al servidor. Veure log'}); } else if (!usuari) res.status(404).json({ codError: 404, descError: "SHOW: No existeix l'usuari amb id=" + req.params.id }); else res.json(usuari); }); } else { if (req.user._id === req.params.id) res.json(req.user); else res.status(403).json({ codError: 403, descError: "SHOW: L'usuari no té permís per accedir a l'usuari amb id=" + req.params.id }); } }; exports.actionCreate = function (req, res) { if (!req.user.es_admin) res.status(403).json({codError: 403, descError: "CREATE: L'usuari no té permís per crear usuaris"}); else { var usuari = new Usuari(req.body); usuari.save(function (err) { if (err) { console.error(new Date().toISOString(), err); res.status(500).json({codError: 500, descError: 'CREATE: Error intern al servidor. Veure log'}); } else res.json({_id: usuari._id}); }); } }; exports.actionUpdate = function (req, res) { Usuari.findById(req.params.id, function (err, usuari) { if (err) { console.error(new Date().toISOString(), err); res.status(500).json({codError: 500, descError: 'UPDATE: Error intern al servidor. Veure log'}); } else if (!usuari) res.status(404).json({ codError: 404, descError: "UPDATE: No existeix l'usuari amb id=" + req.params.id }); else { if(req.body.oldPassword === usuari.contrasenya) { var obj = { contrasenya: req.body.newPassword }; if(obj.contrasenya.length >= 8) { usuari.set(obj); usuari.save(function (err) { if (err) { console.error(new Date().toISOString(), err); res.status(500).json({codError: 500, descError: 'UPDATE: Error intern al servidor. Veure log'}); } else res.json({_id: usuari._id}); }); } else { res.status(496).json({codError: 496, descError: 'UPDATE: Contrasenya minim 8 caràcters'}); } } else { res.status(495).json({codError: 495, descError: 'UPDATE: Contrasenya incorrecta'}); } } }); }; exports.actionDelete = function (req, res) { if (!req.user.es_admin) res.status(403).json({codError: 403, descError: "DELETE: L'usuari no té permís per esborrar usuaris"}); else { Usuari.findById(req.params.id, function (err, usuari) { if (err) { console.error(new Date().toISOString(), err); res.status(500).json({codError: 500, descError: 'DELETE: Error intern al servidor. Veure log'}); } else if (!usuari) res.status(404).json({ codError: 404, descError: "DELETE: No existeix l'usuari amb id=" + req.params.id }); else { usuari.remove(function (err) { if (err) { console.error(new Date().toISOString(), err); res.status(500).json({codError: 500, descError: 'DELETE: Error intern al servidor. Veure log'}); } else res.json({_id: usuari.id}); }); } }); } };
'use strict'; var test = require('tape'); var fn = require('..').isInt; test('isInt', function(t) { t.ok(fn('42')); t.notOk(fn('3.14')); t.notOk(fn('foo')); t.end(); });
'use strict'; angular.module('ngSelectionChange', []) .directive('selectionChange', function () { return { restrict: 'A', require: 'ngModel', link: function(scope, element, attr, ctrl) { element.on('keypress', function (event) { scope.$eval(attr.ngSelectionChange); }); } }; });
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Chart from '../components/chart'; import GoogleMap from '../components/google_map'; class WeatherList extends Component { renderWeather(cityData) { const name = cityData.city.name; const temps = cityData.list.map(weather => weather.main.temp); const pressures = cityData.list.map(weather => weather.main.pressure); const humidities = cityData.list.map(weather => weather.main.humidity); const { lon, lat } = cityData.city.coord; return ( <tr key={name}> <td><GoogleMap lon={lon} lat={lat} /></td> <td><Chart data={temps} color="orange" units="K" /></td> <td><Chart data={pressures} color="green" units="hPa" /></td> <td><Chart data={humidities} color="black" units="%" /></td> </tr> ) } render() { return ( <table className="table table-hover"> <thead> <tr> <th>City</th> <th>Temperature (K)</th> <th>Pressure (hPa)</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);
var module = require('./_module_init.js'); module.controller('ProjectHoursListController', function( $QJLocalSession, $QJCTimeCounter, $interval, $QJCCombobox, $QJCSelectkey, $QJCListview, $QJCFilter, $QJLogger, $QJHelperFunctions, $scope, $rootScope, $QJLoginModule, $QJApi, $timeout, $state, $QJLoginModule ) { $QJLogger.log("ProjectListController -> initialized"); $scope.breadcrumb = { name: 'Projects Hours', list: [{ name: 'Projects', state: 'module-project-list', //fa: 'fa-dashboard' }], active: "Projects Hours" }; g.ProjectListController = $scope; $scope.items = []; //holds projects from db $scope.itemsData = null; //holds projects divided per page //filter $QJCFilter.create({ name: 'projecthoursFilter', fields: [{ name: 'loginname', arrayName: 'items', bindTo: ['loginname'] }, { name: '_id_company', arrayName: 'items', bindTo: ['_id_company'] }, { name: '_id_project', arrayName: 'items', bindTo: ['_id_project'] }, { name: '_id_user', arrayName: 'items', bindTo: ['_id_user'] }] }, $scope); function loadControls() { //-------- //combobox $QJCCombobox.create({ name: 'hourscompanyCBO', label: "Company", code: $rootScope.session.projecthours_hourscompanyCBOCODE || -1, //$rootScope.currentUser._group_id, code_copyto: 'hoursprojectCBO.api.params._id_company', //description_copyto: 'current.company', api: { controller: 'company', params: { action: 'combobox_all' } }, }, $scope); //combobox $QJCCombobox.create({ name: 'hoursprojectCBO', label: "Project", code: $rootScope.session.projecthours_hoursprojectCBOCODE || -1, //$rootScope.currentUser._group_id, code_copyto: 'current.item._id_project', description_copyto: 'current.project', api: { controller: 'project', params: { action: 'combobox_all', _id_company: $scope.hourscompanyCBO.code || -1 } }, }, $scope) //-------- //combobox $QJCCombobox.create({ name: 'companyCBO', label: "Company", code: -1, //$rootScope.currentUser._group_id, code_copyto: 'projecthoursFilter.fields._id_company', api: { controller: 'company', params: { action: 'combobox_all' } }, }, $scope); //combobox $QJCCombobox.create({ name: 'projectCBO', label: "Project", code: -1, //$rootScope.currentUser._group_id, code_copyto: 'projecthoursFilter.fields._id_project', api: { controller: 'project', params: { action: 'combobox_all' } }, }, $scope); //combobox $QJCCombobox.create({ name: 'userCBO', label: "User", code: -1, //$rootScope.currentUser._group_id, code_copyto: 'projecthoursFilter.fields._id_user', api: { controller: 'user', params: { action: 'combobox_all' } }, }, $scope); //listview $QJCListview.create({ name: 'projectshoursLVW', dataArray: 'items', pagedDataArray: 'itemsData', api: { controller: 'project', params: { action: 'hours_all', _id_project: -1 } }, columns: [{ name: 'loginname', label: 'User' }, { name: 'differenceFormated', label: 'Tiempo (hms)' }, { name: 'startFormated', label: 'Start' }, { name: 'endFormated', label: 'End' }], itemClick: function(item) { $QJHelperFunctions.changeState('module-project-hours-edit', { id: item._id }); } }, $scope); $scope.$on("projectshoursLVW.update", function() { //console.info("projectshoursLVW.update"); $scope.items = _.each($scope.items, function(item) { var diff = item.difference; var duration = { hours: Math.round((diff / 1000 / 60 / 60) % 24), minutes: Math.round((diff / 1000 / 60) % 60), seconds: Math.round((diff / 1000) % 60) }; var str = ""; str += duration.hours + ":"; str += duration.minutes + ":"; str += duration.seconds + ""; item.differenceFormated = str; item.startFormated = moment(parseInt(item.start)).format("DD-MM-YY h:mm:ss a"); item.endFormated = moment(parseInt(item.end)).format("DD-MM-YY h:mm:ss a"); }); //$QJLogger.log("projectshoursLVW.update"); }); } $QJCTimeCounter.create({ name: 'current', api: { controller: 'project', params: { action: 'hours_current', _id_project: -1 } }, onInit: function(self) { if (_.isUndefined(self.resitem) || _.isNull(self.resitem)) { self.item = { _id: -1, _id_project: $scope.hoursprojectCBO.code, _id_user: null, //save current based on token. start: null, end: null, difference: null }; } else { self.item = self.resitem; self.resume(self.item.start); } }, onStartChange: function(newVal, self) { self.item.start = newVal; }, onStopChange: function(newVal, self) { self.item.end = newVal; }, onDiffChange: function(newVal, newValFormated, self) { self.item.difference = newVal; }, onValidateStart: function(self) { var val = !_.isUndefined(self.item) && !_.isUndefined(self.item._id_project) && self.item._id_project != null && self.item._id_project != ""; if (!val) { self.errors = []; self.addError("Project required"); } return val; }, onStartClick: function(self) { $scope.hourscompanyCBO.disabled = true; $scope.hoursprojectCBO.disabled = true; // $QJApi.getController("project").post({ action: 'hours_save' }, self.item, function(res) { $QJLogger.log("hours -> save -> success"); }); }, onStopClick: function(self) { $scope.hourscompanyCBO.disabled = false; $scope.hoursprojectCBO.disabled = false; // $QJApi.getController("project").post({ action: 'hours_save' }, self.item, function(res) { $QJLogger.log("hours -> save -> success"); self.addError("Duration: " + $QJHelperFunctions.getTimestampDuration(self.item.difference)); self.addError("Timestamp saved"); $scope.projectshoursLVW.update(); $scope.$emit('project.update', { initializeTimer: false }); }); // if ($scope.projectinfo) { $scope.projectinfo.show = false; } } }, $scope); //.init(); $scope.$on('hoursprojectCBO.change', function() { $scope.$emit('project.update', { initializeTimer: true }); }); $scope.$on('project.update', function(arg, params) { //stores company,project $rootScope.session.projecthours_hourscompanyCBOCODE = $scope.hourscompanyCBO.code; $rootScope.session.projecthours_hoursprojectCBOCODE = $scope.hoursprojectCBO.code; $QJLocalSession.save(); var _id_project = $scope.hoursprojectCBO.code; //UPDATE INFORMATION ABOUT PROJECT HOURS if (_id_project != -1) { updateProjectInfo(_id_project); if (params.initializeTimer) { $scope.current.api.params._id_project = _id_project; //ifa prj its selected. Update timer status $scope.current.init(); } } }); function updateProjectInfo(_id_project) { $QJApi.getController("project").get({ action: "hours_all", _id_project: _id_project.toString() }, function(res) { $QJLogger.log("project hours_all -> success"); var hours = []; _.each(res.items, function(item) { var exists = !_.isUndefined(_.find(hours, function(infoItem) { return infoItem.loginname == item.loginname; })); if (item.end == null) exists = true; // if (exists) return; var hoursfrom = _.filter(res.items, function(i) { return i.loginname == item.loginname; }); var diff = 0; _.each(hoursfrom, function(i) { diff += parseInt(i.difference); }); hours.push({ loginname: item.loginname, diff: diff, diffFormated: $QJHelperFunctions.getTimestampDuration(diff) }); }); //console.info(info); var hoursTotal = 0; _.each(hours, function(i) { hoursTotal += parseInt(i.diff); }); $scope.projectinfo = { hours: hours, hoursTotal: hoursTotal, hoursTotalFormated: $QJHelperFunctions.getTimestampDuration(hoursTotal), show: true }; //console.info($scope.projectinfo); }); } //Load controls when current user its avaliable. var controlsLoaded = false; $rootScope.$on('currentUser.change', function() { loadControls(); controlsLoaded = true; }); if (!controlsLoaded && !_.isUndefined($rootScope.currentUser)) { loadControls(); controlsLoaded = true; } //defaults $timeout(function() { $scope.projecthoursFilter.filter(); }, 2000); scope = $scope; }) module.controller('ProjectHoursEditController', function( $QJCCombobox, $QJCSelectkey, $QJCListview, $QJCFilter, $QJLogger, $QJHelperFunctions, $scope, $rootScope, $QJLoginModule, $QJApi, $timeout, $state, $QJLoginModule ) { $QJLogger.log("ProjectHoursEditController -> initialized"); $scope.breadcrumb = { name: 'Project Hours', list: [{ name: 'Projects Hours', state: 'module-project-hours-list', //fa: 'fa-dashboard' }], active: "Loading" }; var _id = $state.params.id; $scope.crud = { errors: [] } function showError(error) { $scope.crud.errors.push(error); return true; } function formHasErrors() { $scope.crud.errors = []; var hasErrors = false; if (_.isUndefined($scope.item.start) || $scope.item.start == '') { hasErrors = showError('Start required'); } if (_.isUndefined($scope.item.end) || $scope.item.end == '') { hasErrors = showError('End required'); } return hasErrors; } $scope.save = function() { if (!formHasErrors()) { $QJApi.getController('project').post({ action: 'hours_save' }, $scope.item, function(res) { $QJLogger.log("ProjectHoursEditController -> -> project hours_save -> success"); // showError('Cambios guardados'); }); }; }; $scope.cancel = function() { $QJHelperFunctions.changeState('module-project-hours-list'); }; $scope.delete = function() { var r = confirm("Delete [" + $scope.item.start + " - " + $scope.item.end + "] ?"); if (r == true) { $QJApi.getController('project').post({ action: 'hours_delete' }, $scope.item, function(res) { $QJLogger.log("ProjectHoursEditController -> project delete -> success"); // showError('Cambios guardados'); showError($scope.item.name + ' eliminado'); $timeout(function() { $QJHelperFunctions.changeState('module-project-hours-list'); }, 500); }); } else {} } function create() { $QJLogger.log("ProjectHoursEditController -> create new!"); $scope.item = { _id: -1, _id_project: '', _id_user: '', start: '', end: '', milliseconds: '', }; } function loadControls() { } if (_id == -1) { //CREATE //create(); loadControls(); } else { //UPDATE $QJApi.getController('project').get({ action: 'hours_single', id: _id }, function(res) { $QJLogger.log("ProjectHoursEditController -> project hours_single -> success"); //console.info(res.item); $scope.item = res.item; $scope.breadcrumb.active = $scope.item.userName + "'s Timestamp"; loadControls(); }); } });
var Todo = React.createClass({displayName: "Todo", getInitialState: function() { this.text = ""; return {text: ""}; }, componentWillUnmount: function() { this.ref.off(); }, componentWillMount: function() { this.ref = new Firebase("https://glaring-fire-5349.firebaseio.com/react_todos/" + this.props.todoKey); // Update the todo's text when it changes. this.ref.on("value", function(snap) { if (snap.val() !== null) { this.text = snap.val().text; this.setState({ text: this.text }); } else { this.ref.update({ text: "" }); } }.bind(this)); }, onTextBlur: function(event) { this.ref.update({ text: $(event.target).text() }); }, render: function() { return ( React.createElement("li", {id: this.props.todoKey, className: "list-group-item todo"}, React.createElement("a", {href: "#", className: "pull-left todo-check"}, React.createElement("span", { className: "todo-check-mark glyphicon glyphicon-ok", "aria-hidden": "true"} ) ), React.createElement("span", { onBlur: this.onTextBlur, contentEditable: "true", "data-ph": "Todo", className: "todo-text"}, this.state.text ) ) ); } }); var TodoList = React.createClass({displayName: "TodoList", getInitialState: function() { this.todos = []; return {todos: []}; }, componentWillMount: function() { this.ref = new Firebase("https://glaring-fire-5349.firebaseio.com/react_todos/"); // Add an empty todo if none currently exist. this.ref.on("value", function(snap) { if (snap.val() === null) { this.ref.push({ text: "", checked: false, }); } }.bind(this)); // Add an added child to this.todos. this.ref.on("child_added", function(childSnap) { this.todos.push({ k: childSnap.key(), val: childSnap.val() }); this.setState({ todos: this.todos }); }.bind(this)); this.ref.on("child_removed", function(childSnap) { var key = childSnap.key(); var i; for (i = 0; i < this.todos.length; i++) { if (this.todos[i].k == key) { break; } } this.todos.splice(i, 1); this.setState({ todos: this.todos }); }.bind(this)); }, componentWillUnmount: function() { this.ref.off(); }, render: function() { var todos = this.state.todos.map(function (todo) { return ( React.createElement(Todo, {todoKey: todo.k}) ); }); return ( React.createElement("div", null, React.createElement("h1", {id: "list_title"}, this.props.title), React.createElement("ul", {id: "todo-list", className: "list-group"}, todos ) ) ); } }); var ListPage = React.createClass({displayName: "ListPage", render: function() { return ( React.createElement("div", null, React.createElement("div", {id: "list_page"}, React.createElement("a", {href: "?", id: "lists_link", className: "btn btn-primary"}, "Back to Lists") ), React.createElement("div", {className: "page-header"}, this.props.children ) ) ); } }); var Nav = React.createClass({displayName: "Nav", render: function() { return ( React.createElement("nav", {className: "navbar navbar-default navbar-static-top"}, React.createElement("div", {className: "container"}, React.createElement("div", {className: "navbar-header"}, React.createElement("a", {className: "navbar-brand", href: "?"}, "Firebase Todo") ), React.createElement("ul", {className: "nav navbar-nav"}, React.createElement("li", null, React.createElement("a", {href: "?"}, "Lists")) ) ) ) ); }, }); var App = React.createClass({displayName: "App", getInitialState: function() { // TODO: route here. return { page: "LIST", todoListKey: "asdf" }; }, getPage: function() { if (this.state.page === "LIST") { return ( React.createElement(ListPage, null, React.createElement(TodoList, {todoListKey: this.state.todoListKey}) ) ); } else { console.log("Unknown page: " + this.state.page); } }, render: function() { React.createElement("div", null, React.createElement(Nav, {app: this}), this.getPage() ) } }); React.render( React.createElement(App, null), document.getElementById('content') );
'use strict'; var expect = require('chai').expect; var clean = require('../');
import * as types from './mutation-types' import { url } from 'src/Modules/Auth/resources' export function initPosts (store) { return url.get('posts').then(function (response) { store.commit(types.INIT_POSTS, response.data.posts) return response }, function (response) { return response }) }
import React, { Component } from 'react' import { Entity, AtomicBlockUtils } from 'draft-js' import { createPlugin, pluginUtils } from 'draft-extend' import { Button, Modal, message } from 'antd' import AudioSelect from '../../Resource/Audio/Select' const ENTITY_TYPE = 'AUDIO' const BLOCK_TYPE = 'atomic' class AudioButton extends Component { constructor() { super() this.state = { visible: false, record: null } } toggleVisible = () => this.setState({ visible: !this.state.visible }) okHandler = () => { const { record } = this.state if (record) { const { editorState, onChange } = this.props const newEditorState = AtomicBlockUtils.insertAtomicBlock( editorState, Entity.create( ENTITY_TYPE, 'IMMUTABLE', { src: record.path } ), ' ' ) onChange(newEditorState) this.toggleVisible() } else { message.warn('请选择一项!') } } render() { const { visible } = this.state return ( <div> <Modal visible={visible} title="选择音频" onOk={this.okHandler} onCancel={this.toggleVisible} maskClosable={false} > <AudioSelect onChange={val => this.setState({ record: val })}/> </Modal> <Button onClick={this.toggleVisible}>添加音频</Button> </div> ) } } const AudioDecorator = { strategy: pluginUtils.entityStrategy(ENTITY_TYPE), component: props => { const entity = Entity.get(props.entityKey) const { src } = entity.getData() return ( <audio src={src} controls /> ); } } const htmlToEntity = (nodeName, node) => { if (nodeName === 'audio') { return Entity.create( ENTITY_TYPE, 'IMMUTABLE', { src: node.getAttribute('src'), } ) } } const entityToHTML = (entity, originalText) => { if (entity.type === ENTITY_TYPE) { return `<audio src="${entity.data.src}" controls />` } return originalText } const blockRendererFn = (block) => { if (block.getType() === BLOCK_TYPE && block.size > 0 && Entity.get(block.getEntityAt(0)).getType() === ENTITY_TYPE) { return { component: ({block}) => { const {src} = Entity.get(block.getEntityAt(0)).getData(); return <audio src={src} controls /> }, editable: false } } } const AudioPlugin = createPlugin({ displayName: 'AudioPlugin', buttons: AudioButton, decorators: AudioDecorator, htmlToEntity, entityToHTML, blockRendererFn, htmlToBlock: (nodeName, node, lastList, inBlock) => { if (nodeName === 'figure' && node.firstChild.nodeName === 'AUDIO' || (nodeName === 'audio' && inBlock !== BLOCK_TYPE)) { return BLOCK_TYPE; } }, blockToHTML: { 'atomic': { start: '<figure>', end: '</figure>' } } }); export default AudioPlugin export { AudioButton, AudioDecorator }
var CLOCKWORKRT = CLOCKWORKRT || {}; CLOCKWORKRT.apps = {}; zip.workerScriptsPath = "/js/"; CLOCKWORKRT.apps.installAppFromLocalFile = function (callback) { CLOCKWORKRT.ui.showLoader("Select a .cw file",""); // Create the picker object and set options var openPicker = new Windows.Storage.Pickers.FileOpenPicker(); openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.list; openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.documentsLibrary; // Users expect to have a filtered view of their folders depending on the scenario. // For example, when choosing a documents folder, restrict the filetypes to documents for your application. openPicker.fileTypeFilter.replaceAll([".cw"]); openPicker.pickSingleFileAsync().then(function (file) { if (file) { return file.openAsync(Windows.Storage.FileAccessMode.read); } }).done(function (fileBuf) { if (fileBuf) { var blob = MSApp.createBlobFromRandomAccessStream('application/zip', fileBuf); CLOCKWORKRT.apps.installAppFromBlob(blob, callback); } else { callback(); } }); }; CLOCKWORKRT.apps.installAppFromURL = function (url, callback) { CLOCKWORKRT.ui.showLoader("Downloading the game package", ""); var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { CLOCKWORKRT.apps.installAppFromBlob(this.response, callback); } } xhr.open('GET', url); xhr.responseType = 'blob'; xhr.send(); }; CLOCKWORKRT.apps.installAppFromBlob = function (blob,callback) { zip.createReader(new zip.BlobReader(blob), function (reader) { // get all entries from the zip reader.getEntries(function (entries) { if (entries.length) { //var contents = {}; //entries.forEach(function (x) { // x.getData(new zip.TextWriter(), function (text) { // contents[x.filename] = text; // }) //}); var nentries = entries.length; function copyAppFiles(appname) { var currentfile = 1; entries.recursiveForEach(function (file, cb) { CLOCKWORKRT.ui.showLoader("Copying game files", currentfile+"/"+nentries); var localFolder = Windows.Storage.ApplicationData.current.localFolder; var path = "installedApps/" + appname + "/" + file.filename; var pathFolders = path.split("/"); var filename = pathFolders.pop(); navigatePath(localFolder, pathFolders, function (folder) { if (file.directory) { currentfile++; if (currentfile > nentries) { CLOCKWORKRT.ui.hideLoader(); callback(); } else { cb(); } return; } console.log("creating " + filename); file.getData(new zip.BlobWriter(), function (blob) { folder.createFileAsync(filename, Windows.Storage.CreationCollisionOption.replaceExisting).then(function (file) { // Open the returned file in order to copy the data file.openAsync(Windows.Storage.FileAccessMode.readWrite).then(function (output) { // Get the IInputStream stream from the blob object var input = blob.msDetachStream(); // Copy the stream from the blob to the File stream Windows.Storage.Streams.RandomAccessStream.copyAsync(input, output).then(function () { output.flushAsync().done(function () { input.close(); output.close(); currentfile++; if (currentfile > nentries) { CLOCKWORKRT.ui.hideLoader(); callback(); } else { cb(); } }); }); }); }); }); }); }); } var manifest = entries.filter(function (x) { return x.filename == "manifest.json" }); if (manifest.length == 0) { //TODO: ERROR, NO MANIFEST } manifest = manifest[0]; manifest.getData(new zip.TextWriter(), function (text) { // text contains the entry data as a String var manifestData = JSON.parse(text); console.log(manifestData); Promise.all(Object.keys(manifestData.dependencies).map(function (n,i) { return new Promise(function (resolve, fail) { CLOCKWORKRT.ui.showLoader("Downloading dependencies", i + "/" + Object.keys(manifestData.dependencies).length); CLOCKWORKRT.apps.installDependency(n, manifestData.dependencies[n], resolve); }) })).then(function () { CLOCKWORKRT.apps.addInstalledApp(manifestData); setTimeout(function () { copyAppFiles(manifestData.name); }, 100); }); // close the zip reader //reader.close(function () { // // onclose callback //}); }, function (current, total) { console.log(current,total); }); } }); }, function (error) { // onerror callback }); } CLOCKWORKRT.apps.getInstalledApps = function () { return JSON.parse(localStorage.installedApps || "[]"); } CLOCKWORKRT.apps.addInstalledApp = function (app) { var apps = CLOCKWORKRT.apps.getInstalledApps(); apps = apps.filter(function (x) { return x.name != app.name }); apps.push(app); localStorage.installedApps = JSON.stringify(apps); } CLOCKWORKRT.apps.launchApp = function (name) { var manifest=CLOCKWORKRT.apps.getInstalledApps().filter(x=>x.name == name)[0]; localStorage.currentAppName=manifest.name; localStorage.currentAppScope = manifest.scope; localStorage.currentAppManifest = JSON.stringify(manifest); localStorage.debugMode = false; window.location = "game.html"; } CLOCKWORKRT.apps.debugApp = function (name, debugFrontend,levelEditor) { var manifest = CLOCKWORKRT.apps.getInstalledApps().filter(x=>x.name == name)[0]; localStorage.currentAppName = manifest.name; localStorage.currentAppScope = manifest.scope; localStorage.currentAppManifest = JSON.stringify(manifest); localStorage.debugMode = true; localStorage.debugFrontend = debugFrontend; localStorage.levelEditor = levelEditor; window.location = "game.html"; } CLOCKWORKRT.apps.reset = function (name) { localStorage.clear(); var localFolder = Windows.Storage.ApplicationData.current.localFolder.getFoldersAsync().done(function (folders) { folders.forEach(function (f) { f.deleteAsync(); }); }); CLOCKWORKRT.API.loadMenu(); function emptyFolder(f) { Windows.Storage.ApplicationData.current.localFolder.getFoldersAsync().done(function (folders) { folders.forEach(function (f) { emptyFolder(f); f.deleteAsync() }); }); Windows.Storage.ApplicationData.current.localFolder.getFilesAsync().done(function (folders) { folders.forEach(function (f) { f.deleteAsync(); }); }); } } CLOCKWORKRT.apps.installDependency = function (name, version, callback) { var uri = new Windows.Foundation.Uri(`ms-appdata:///local/installedDependencies/${name}/${version}.js`); var file = Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri).done(function (file) { console.log(name + " is already installed"); callback(); }, function (x) { var localFolder = Windows.Storage.ApplicationData.current.localFolder; var path = `installedDependencies/${name}/${version}.js` var pathFolders = path.split("/"); var filename = pathFolders.pop(); var request = new XMLHttpRequest(); request.onreadystatechange = function () { if (this.readyState === 4) { var packageContent = this.responseText; if (packageContent == "") { CLOCKWORKRT.apps.installDependency(name, version, callback); } else { navigatePath(localFolder, pathFolders, function (folder) { folder.createFileAsync(filename, Windows.Storage.CreationCollisionOption.replaceExisting).then(function (file) { Windows.Storage.FileIO.writeTextAsync(file, packageContent).then(callback); }); }); } } }; request.open('GET', `https://clockworkdev.github.io/ClockworkPackages/packages/${name}/${version}/components.js`, true); request.send(); }); } CLOCKWORKRT.apps.getDependency = function (name, version, callback) { var uri = new Windows.Foundation.Uri(`ms-appdata:///local/installedDependencies/${name}/${version}.js`); var file = Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri).done(function (file) { Windows.Storage.FileIO.readTextAsync(file).done(function (x) { callback(x); }); }, function (x) { console.log(x); }); } Array.prototype.recursiveForEach = function (action, index) { var i = index || 0; if (i >= this.length) { return; } var that = this; action(this[i], function () { that.recursiveForEach(action, i + 1); }); } //File system helper functions function navigatePath(startFolder, path, callback) { if (path.length > 0) { var newName = path.shift(); console.log("trying to navigate to " + newName); startFolder.createFolderQuery().getFoldersAsync().done(function (f) { var r = f.filter(function (x) { return x.name == newName; }); if (r.length > 0) { console.log("navigated to" + newName); navigatePath(r[0], path, callback); } else { console.log("trying to create" + newName); startFolder.createFolderAsync(newName).done( function (f) { console.log("created" + newName); navigatePath(f, path, callback) } ); } }); } else { callback(startFolder); } }
export default function factorialize(num) { return num; }
import introduction from "./introduction" import usage from "./usage" import treeview from "./treeview" export default [ introduction, usage, treeview ]
import React from 'react'; import PropTypes from 'prop-types'; // import ons from 'onsenui'; import {Page, List, ListItem, ListHeader} from 'react-onsenui'; import PullToRefresh from '../components/PullToRefresh'; import InfiniteScroll from '../components/InfiniteScroll'; import SideMenu from '../containers/SideMenu'; import FloatingActionButton from '../components/FloatingActionButton'; import SpeedDials from '../components/SpeedDials'; // // const initialPlatform = ons.platform.isAndroid() // ? 'android' // : 'ios'; class Home extends React.Component { gotoComponent(component) { this.props.navigator.pushPage({comp: component}); } render() { return ( <Page> <p style={{padding: '0 15px'}}> This is a kitchen sink example that shows off the React extension for Onsen UI. </p> <p style={{padding: '0 15px'}}> <a href="https://onsen.io/v2/react.html" target="_blank" rel="noopener noreferrer"> <strong>Official site with docs</strong> </a> </p> <List renderHeader={() => <ListHeader>Components</ListHeader>} dataSource={[ { name: 'Pull to refresh', component: PullToRefresh }, { name: 'Infinite scroll', component: InfiniteScroll }, { name: 'Side menu', component: SideMenu }, { name: 'Floating action button', component: FloatingActionButton }, { name: 'Speed dials', component: SpeedDials } ]} renderRow={(row, i) => ( <ListItem key={i} tappable onClick={this.gotoComponent.bind(this, row.component)} > {row.name} </ListItem> )} /> </Page> ); } } Home.propTypes = { navigator: PropTypes.object, }; export default Home;
;(function() { var map = warped.map, randInt = warped.randInt, randVal = warped.randVal, repeat = warped.repeat, concat = warped.concat var headTypes = [ function() { return [ "vv('k ~ k s ~ ~, h*4')", " (motif, samples)" ] }, function() { return [ "vv('c, k, [t*3, t*2]*2')", " (motif, samples)" ] }, ] var modifierTypes = [ function() { return [ " (every, " + (randInt(1, 4) * 2) + ", function(beats) {", " return vv(beats)", " (slice, -(beats.length / 2))", " (repeat, randInt(1, 2) * 2)", " (concatValues)", " ()", " })" ] }, function() { return [ " (every, " + (randInt(1, 4) * 2) + ", function(beats) {", " var i = -randInt(1, 2) * 2", " return concat(slice(beats, 0, i), vv(beats)", " (slice, i)", " (repeat, randInt(1, 2) * 2)", " (concatValues)", " ())", " })" ] }, function() { var p = -randVal([0.2, 0.6, 1.2, 2, 2.3, 2.5]) var n = randInt(2, 3) return [" (every, " + n + ", deepMap, ctl, {pitch: " + p + "})"] }, function() { var p = randVal([0.3, 0.5, 1.5, 3.3]) var n = randInt(2, 6) return [" (every, " + n + ", deepMap, ctl, {pitch: " + p + "})"] } ] function intro() { var head = randVal(headTypes)() var modifiers = vv(null) (repeat, randInt(2, modifierTypes.length)) (map, function() { return randVal(modifierTypes)() }) (cat) () return cat([ head, " (sync)", " (loop)", " (result)", modifiers, " (to, s1)" ]).join('\n') } function cat(arr) { return arr.reduce(function(a, b) { return concat(a, b) }) } permutation.intro = intro })()
var resolve = require('path').resolve var webpack = require('webpack') var HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = function getBaseConfig (loader, isDev) { return { output: { path: resolve(__dirname, '../dist'), filename: '[name].' + (loader === 'vue' ? 'web' : loader) + '.js' }, externals: loader === 'weex' ? { 'vue': 'Vue', 'weex-vue-render': 'weexVueRenderer' } : {}, module: { rules: [ // You can use eslint here // Take eslint-plugin-vue as an example // 1. npm i babel-eslint babel-plugin-transform-runtime babel-runtime babel-preset-stage-2 eslint eslint-config-vue eslint-friendly-formatter eslint-loader eslint-plugin-html eslint-plugin-promise eslint-plugin-vue -D // 2. set the config below // { // test: /\.(js|vue)$/, // loader: 'eslint-loader', // enforce: 'pre', // include: [resolve(__dirname, '../src')], // options: { // formatter: require('eslint-friendly-formatter') // } // }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.vue$/, loader: loader + '-loader' } ] }, resolve: { alias: { 'vue$': 'vue/dist/vue.runtime.js' } }, plugins: [ new webpack.BannerPlugin({ banner: '// { "framework": "Vue" }\n', raw: true }), new webpack.LoaderOptionsPlugin({ vue: { // // You can use PostCSS now! // // Take cssnext for example: // // 1. npm install postcss-cssnext --save-dev // // 2. write `var cssnext = require('postcss-cssnext')` at the top // // 3. set the config below // postcss: [cssnext({ // features: { // autoprefixer: false // } // })] } }) ].concat(isDev ? [ new webpack.NamedModulesPlugin(), new webpack.DefinePlugin({ 'process.env': { IP: JSON.stringify(require('ip').address()) } }), new HtmlWebpackPlugin({ filename: 'web/qrcode.html', template: 'web/qrcode.tpl', chunks: [] }) ] : []) .concat(loader === 'vue' ? [ new HtmlWebpackPlugin({ template: 'web/index.tpl' }), new webpack.ProvidePlugin({ Vue: 'vue/dist/vue.runtime.js' }) ] : []) } }
"use strict"; const gulp = require('gulp'); const eslint = require('gulp-eslint'); const fs = require('fs'); const spawn = require('child_process').spawn; gulp.task('eslint', function () { return gulp.src('./src/**').pipe(eslint()); }); gulp.task('publish', function (cb) { const publish = spawn('npm', ['publish'], {stdio: 'inherit'}); publish.on('close', () => { cb(); }); publish.on('error', (err) => { cb(err) }); }); gulp.task('default', ['eslint']);
function sleep(t) { return new Promise(resolve => setTimeout( _ => { resolve(+new Date) }, t)) } async function run() { // 顺序 let a = await sleep(100) let b = await sleep(200) // 并发1 let c = await Promise.all([sleep(100), sleep(200), sleep(300)]) // 并发2 let d = await Promise.all([100, 200, 300].map(t => sleep(t))) // 并发3 let list = [sleep(100), sleep(200), sleep(300)] let e = [] for (let fn of list) { e.push(await fn) } console.log( '', 'a:', a, '\n', 'b:', b, '\n', 'c:', c, '\n', 'd:', d, '\n', 'e:', e, '\n' ) } run()
import childProcess from 'child_process'; import gulp from 'gulp'; import chalk from 'chalk'; import gulpLoadPlugins from 'gulp-load-plugins'; const $ = gulpLoadPlugins(); gulp.task('copy-publish', () => { return gulp .src(['README.md', 'sass/*']) .pipe($.copy('publish')) }); // 发布到 npm 中 gulp.task('publish', () => { const {exec} = childProcess; exec('cd publish && npm publish && cd ..', (error, stdout, stderr) => { if (error) { console.log(chalk.magenta(error)); return; } if (stdout) { console.log(chalk.magenta(`stdout: ${stdout}`)); } if (stderr) { console.log(chalk.magenta(`stderr: ${stderr}`)); } }); });
// >>> WARNING THIS PAGE WAS AUTO-GENERATED - DO NOT EDIT!!! <<< import QuestionPage from '../question.page' class TurnoverAndExportsCompletedPage extends QuestionPage { constructor() { super('turnover-and-exports-completed') } } export default new TurnoverAndExportsCompletedPage()
import utils from 'osg/utils'; import InputSource from 'osgViewer/input/source/InputSource'; import notify from 'osg/notify'; /** * WebVR Hmd device input handling. * @param canvas * @constructor */ var InputSourceWebVR = function(elem, options) { InputSource.call(this); this._supportedEvents = [ 'vrdisplayposechanged', 'vrdisplayconnected', 'vrdisplaynotfound', 'vrdisplaydisconnected' ]; this._callbacks = {}; this._events = {}; for (var i = 0; i < this._supportedEvents.length; i++) { var eventName = this._supportedEvents[i]; var event = new Event(eventName); this._events[eventName] = event; } this._nbCallbacks = 0; // We poll the device at regular interval, if ever a headset is plugged in. // 3 seconds default poll interval // If the pollInterval is set to 0 or less the polling is disabled and the user // will have to poll it manually with the pollHeadset method this._pollInterval = options && options.pollInterval !== undefined ? options.pollInterval : 3000; }; utils.createPrototypeObject( InputSourceWebVR, utils.objectInherit(InputSource.prototype, { getName: function() { return 'WebVR'; }, setEnable: function(name, callback, enable) { var callbacks = this._callbacks[name]; if (!callbacks) { callbacks = []; this._callbacks[name] = callbacks; } var index = callbacks.indexOf(callback); if (enable) { if (index < 0) { callbacks.push(callback); this._nbCallbacks++; // only poll for device if we have callbacks. this._schedulePolling(); } } else { if (index >= 0) { callbacks.splice(index, 1); this._nbCallbacks--; if (!this._nbCallbacks) { // no more callbacks let's stop polling this._cancelPolling(); } } } }, populateEvent: function(ev, customEvent) { if (ev.vrDisplay) { customEvent.vrDisplay = ev.vrDisplay; return; } customEvent.pose = ev.pose; customEvent.sitToStandMatrix = ev.sitToStandMatrix; customEvent.worldFactor = this._inputManager.getParam('worldFactor'); if (!customEvent.worldFactor) customEvent.worldFactor = 1.0; }, _schedulePolling: function() { if (this._pollInterval > 0 && this._pollingTimeout === undefined) { this._pollingTimeout = setInterval(this.pollHeadset.bind(this), this._pollInterval); } }, _cancelPolling: function() { if (this._pollingTimeout !== undefined) { clearInterval(this._pollingTimeout); } }, pollHeadset: function() { if (!navigator.getVRDisplays) { this._hmd = undefined; this._frameData = undefined; this.triggerNotFoundEvent(); return; } var self = this; navigator .getVRDisplays() .then( function(displays) { if (displays.length === 0) { this.triggerNotFoundEvent(); return; } if (self._hmd === displays[0]) { // still the same display nothing to do return; } notify.log('Found a VR display'); //fire the disconnect event var event = self._events['vrdisplaydisconnected']; event.vrDisplay = self._hmd; this._dispatchEvent(event, self._callbacks['vrdisplaydisconnected']); //fire the connect event event = self._events['vrdisplayconnected']; event.vrDisplay = displays[0]; this._dispatchEvent(event, self._callbacks['vrdisplayconnected']); self._hmd = displays[0]; self._frameData = new window.VRFrameData(); }.bind(this) ) .catch(function(ex) { this._hmd = undefined; this._frameData = undefined; this.triggerNotFoundEvent(); notify.warn(ex.message); }); }, triggerNotFoundEvent: function() { if (this._pollInterval > 0) { // we are in auto polling mode, don't trigger the event return; } // in case of manual polling we trigger an event when no display was found var event = this._events['vrdisplaynotfound']; this._dispatchEvent(event, this._callbacks['vrdisplaynotfound']); }, setPollInterval: function(interval) { this._pollInterval = interval; }, _dispatchEvent: function(event, callbacks) { if (!callbacks) return; for (var i = 0; i < callbacks.length; i++) { var callback = callbacks[i]; callback(event); } }, poll: function() { if (!this._hmd) { return; } var callbacks = this._callbacks['vrdisplayposechanged']; if (!callbacks || !callbacks.length) { return; } //hmd movement this._hmd.getFrameData(this._frameData); var pose = this._frameData.pose; if (!pose) return; // WebVR up vector is Y // OSGJS up vector is Z var sitToStand = this._hmd.stageParameters && this._hmd.stageParameters.sittingToStandingTransform; var event = this._events['vrdisplayposechanged']; event.pose = pose; event.sitToStandMatrix = sitToStand; this._dispatchEvent(event, callbacks); } }), 'osgViewer', 'InputSourceWebVR' ); export default InputSourceWebVR;
(function(Hammer){ var Curve = function(stage, multipliers, baseAngle, growth){ this.stage = stage; this.multipliers = multipliers; this.baseAngle = baseAngle; this.growth = growth; this.m = multipliers.length; } Curve.prototype.drawOn = function(context, options) { context.save(); for(var key in (options || {})) { context[key] = options[key]; } context.beginPath(); context.moveTo(0, 0); var unit = context.canvas.width/ Math.pow(this.growth, this.stage); for (var index = 0, total = Math.pow(this.m, this.stage); index < total; index++) { var phase = index; while (phase > 0 && phase % this.m == 0) { phase = phase / this.m; } var multiplier = this.multipliers[phase % this.m]; var angle = multiplier * this.baseAngle; context.rotate(angle) context.translate(unit, 0); context.lineTo(0, 0); } context.stroke(); context.restore(); } var curves = { koch : function(stage){ return new Curve(stage, [0, 1, -2, 1], Math.PI/3, 3); }, kochLike: function(stage, angle){ return new Curve(stage, [0, 1, -2, 1], angle, 2*(1 + Math.cos(angle))); } } var Paragraph = function(stage, messages, offsets){ this.stage = stage; this.messages = messages; this.offsets = offsets; } Paragraph.prototype.drawOn = function(context, options){ context.save(); context.fillStyle = 'black'; context.fillRect(0, 0, canvas.width, canvas.height); context.restore(); context.save(); for(var key in (options || {})) { context[key] = options[key]; } for (var index = 0; index < this.messages.length; index++){ context.fillText(this.messages[index], this.offsets.indent, (index + 1) * this.offsets.baseline); } context.restore(); context.save(); context.translate(0, canvas.height); context.scale(1, -1); context.translate(0, 10); var koch = new curves.koch(this.stage); koch.drawOn(context, options); context.restore(); }; var Story = function(paragraphs){ this.paragraphs = paragraphs; this.currentIndex = 0; this.reachedEnd = false; } Story.prototype.drawOn = function(context, options){ this.paragraphs[this.currentIndex].drawOn(context, options); }; Story.prototype.next = function(){ var targetIndex = this.currentIndex + 1; this.reachedEnd = (targetIndex === this.paragraphs.length); if (!this.reachedEnd) { this.currentIndex = Math.min(targetIndex, this.paragraphs.length - 1); } } Story.prototype.previous = function(){ if (!this.reachedEnd) { this.currentIndex = Math.max(0, this.currentIndex - 1); } } var body = document.getElementsByTagName('body')[0]; var left = document.createElement('button'); left.className = 'left'; left.textContent = '<'; body.appendChild(left); var canvas = document.createElement('canvas'); canvas.width = 640; canvas.height= 640; body.appendChild(canvas); var right = document.createElement('button'); right.className = 'right'; right.textContent = '>'; body.appendChild(right); context = canvas.getContext('2d'); var paragraphOptions = { 'indent': 10, 'baseline': 60 }; var story = new Story([ new Paragraph(1, ['Lieve Vrienden & Familie'], paragraphOptions), new Paragraph(2, ['Na een jaar', 'waarin gegeven', 'en genomen is'], paragraphOptions), new Paragraph(3, ['Willen wij stil staan', 'bij wat ons dierbaar is'], paragraphOptions), new Paragraph(4, ['Een leven rijk aan', 'waardevolle relaties', 'en warme contacten'], paragraphOptions), new Paragraph(3, ['Wij zijn jullie', 'hier enorm', 'dankbaar voor'], paragraphOptions), new Paragraph(2, ['Wij wensen jullie daarom', 'een warm, liefdevol', 'en dynamisch 2014!'], paragraphOptions), new Paragraph(1, ['Daan, Marlies & Sophie'], paragraphOptions), ]); function drawStory() { story.drawOn(context, { 'fillStyle': 'white', 'font': '50px sans-serif', 'strokeStyle': 'white', 'lineWidth': '1' }); } function advanceStory() { if (!story.reachedEnd) { story.next(); drawStory(); } if (story.reachedEnd && start == undefined) { start = (new Date()).getTime(); continuous(); } } function retreatStory() { if (!story.reachedEnd) { story.previous(); drawStory(); } } var start = undefined; drawCurve = (function(){ var period = 12 * 1000; var alpha0 = Math.acos(-13/27); var t0 = alpha0 * period / (2*Math.PI); function number(t) { return 1 + Math.floor((t - start + t0)/period) % 6 } return function drawCurve(t) { context.save(); context.fillRect(0, 0, canvas.width, canvas.height); var alpha = 2 * Math.PI * (t - start + t0) / period; context.translate(0, 640); context.scale(1, -1); context.translate(0, 10); var koch = new curves.kochLike(number(t), 9*Math.PI/40 * (1 - Math.cos(alpha))); koch.drawOn(context, { strokeStyle: 'white', lineWidth: 1 }); context.restore(); } })(); function continuous(){ drawCurve((new Date()).getTime()); requestAnimationFrame(continuous); } drawStory(); body.addEventListener('keydown', function(event){ if (event.keyCode == 39) { advanceStory(); } if (event.keyCode == 37) { retreatStory(); } }); left.addEventListener('click', retreatStory); right.addEventListener('click', advanceStory); Hammer(body).on('swipeleft', advanceStory); Hammer(body).on('swiperight', retreatStory); })(Hammer);
import Ember from 'ember'; export default Ember.Controller.extend({ actions: { create: function () { var bot = this.store.createRecord('bot', { name: this.get('name'), description: this.get('description'), type: 'stream' }); bot.save().then(function (bot) { this.notify.success('Bot created!'); this.set('name', ''); this.set('description', ''); this.transitionToRoute('bots.bot', bot); }.bind(this)); // TODO: error handling } } });
import { Meteor } from 'meteor/meteor'; // Read app version and log it const version = process.env.VERSION || ''; Meteor.settings.public.version = version; console.log(`Running SignMeUp ${version}`); // eslint-disable-line no-console // Set config import '../both/config.js'; // Register API import '../both/register-api.js'; // Run migrations import './migrations/migrations.js'; // Initialize test data import './fixtures.js'; // Run cron jobs import './cron-jobs.js';
Mariachi.Views.Parameters = Backbone.View.extend({ el: "div.parameters", template: _.template($(".parameter").html()), initialize: function(parameter) { this.render(parameter); }, render: function(parameter) { if(parameter) { this.$el.append(this.template({parameter: parameter})); } } }); /** * List servers */ Mariachi.Views.ListRecepies = Backbone.View.extend({ el: "#content", loading: new Mariachi.Views.Loading(), initialize: function() { this.render(); }, template: _.template($(".listRecepies").html()), render: function() { var self = this; var items = new Mariachi.Collections.Recepies(); items.fetch({ error: function(collection, response) { console.log(response); self.loading.hide(); }, success: function(collection, response) { // Table self.$el.html(self.template({items: response})); self.loading.hide(); } }); }, }); /** * View a server */ Mariachi.Views.ViewRecepie = Backbone.View.extend({ el: "#content", loading: new Mariachi.Views.Loading(), template: _.template($(".viewRecepie").html()), initialize: function(data) { this.render(data.id); }, render: function(id) { var self = this; var model = new Mariachi.Models.Recepie({id: id}); model.fetch({ success: function(model, response) { self.$el.html(self.template(model.toJSON())); self.loading.hide(); }, error: function(model, response) { console.log(response); self.loading.hide(); } }); } }); /** * Add server */ Mariachi.Views.AddRecepie = Backbone.View.extend({ el: "#content", loading: new Mariachi.Views.Loading(), events: { "click #submit": "submit" }, initialize: function() { this.render(); }, render: function() { var template = _.template($(".addRecepie").html()); this.$el.html(template); }, submit: function(e) { var self = this; e.preventDefault(); self.loading.show(); $("#submit").addClass("disabled"); var data = { name: $('input#name').val(), description: $('textarea#description').val(), parameters: $("input#parameters").val(), recepie: $('textarea#recepie').val() } var model = new Mariachi.Models.Recepie(data); model.save(data, { success: function(model, response) { var collection = new Mariachi.Collections.Recepies(); collection.add(model); Backbone.history.navigate("/", {trigger: true, replace: true}); new Mariachi.Views.MessageView({ message: "Recepie created.", type:"success" }); self.loading.hide(); }, error: function(model, error) { console.log(error); new Mariachi.Views.MessageView({ message: "Error: " + error.statusText + "(" + error.status + ")", type: "danger" }); self.loading.hide(); } }); } }); /** * Edit recepie */ Mariachi.Views.EditRecepie = Backbone.View.extend({ el: "#content", loading: new Mariachi.Views.Loading(), events: { "click #submit": "submit" }, initialize: function(data) { this.model = new Mariachi.Models.Recepie({id: data.id}); this.render(data.id); }, render: function(id) { var self = this; this.model.fetch({ success: function(model, response) { var template = _.template($(".editRecepie").html()); self.$el.html(template(model.toJSON())); self.loading.hide(); }, error: function(model, response) { self.loading.hide(); } }); }, submit: function(e) { var self = this; e.preventDefault(); self.loading.show(); $("#submit").addClass("disabled"); var data = { name: $('input#name').val(), description: $('textarea#description').val(), parameters: $("input#parameters").val(), recepie: $('textarea#recepie').val() } this.model.set(data); this.model.save(data, { success: function(model, response) { Backbone.history.navigate("/", {trigger: true, replace: true}); new Mariachi.Views.MessageView({ message: "Recepie updated.", type:"success" }); self.loading.hide(); }, error: function(model, error) { console.log(error); new Mariachi.Views.MessageView({ message: "Error: " + error.statusText + "(" + error.status + ")", type: "danger" }); self.loading.hide(); } }); } }); /** * Delete recepie */ Mariachi.Views.DeleteRecepie = Backbone.View.extend({ el: "#content", loading: new Mariachi.Views.Loading(), events: { "click #submit": "submit" }, initialize: function(data) { this.model = new Mariachi.Models.Recepie({id: data.id}); this.render(data.id); }, render: function(id) { var self = this; this.model.fetch({ success: function(model, response) { var template = _.template($(".deleteRecepie").html()); self.$el.html(template(model.toJSON())); self.loading.hide(); }, error: function(model, response) { self.loading.hide(); } }); }, submit: function(e) { e.preventDefault(); var self = this; this.model.destroy({ success: function(model, response) { var collection = new Mariachi.Collections.Recepies(); collection.remove(model); Backbone.history.navigate("/", {trigger: true, replace: true}); new Mariachi.Views.MessageView({ message: "Recepie deleted.", type:"success" }); self.loading.hide(); }, error: function(model, response) { new Mariachi.Views.MessageView({ message: "Error: " + response.statusText, type:"danger" }); self.loading.hide(); } }); } }); /** * Execute recepie */ Mariachi.Views.ExecuteRecepie = Backbone.View.extend({ el: "#content", loading: new Mariachi.Views.Loading(), events: { "click #execute": "execute" }, recepieId: null, template: _.template($(".executeRecepie").html()), initialize: function(data) { this.render(data.id); this.recepieId = data.id; }, render: function(id) { var self = this; var model = new Mariachi.Models.Recepie({id: id}); model.fetch({ success: function(model, response) { self.$el.html(self.template(model.toJSON())); self.loading.hide(); self.populateServers(); if(response.parameters) { self.addParamsForm(response); } else { $("div.parameters").text("This recepie accepts no extra parameters"); } }, error: function(model, response) { console.log(response); self.loading.hide(); } }); }, populateServers: function() { var self = this; self.loading.show(); var servers = new Mariachi.Collections.Servers(); servers.getWithStatus(1, function(err, response) { if(err) { console.log(err); new Mariachi.Views.MessageView({ message: "Error: " + err, type: "danger" }) } if(response.length) { var options = $("#servers"); _.each(response, function(item) { options.append(new Option(item.name, item.id)); }); } else { new Mariachi.Views.MessageView({ message: "You need to add servers before you can deploy a recepie", type: "danger" }) // Hide the execute button $("form").addClass("hidden"); } self.loading.hide(); }); }, addParamsForm: function(response) { // convert patterns to array var params = response.parameters.split(", "); // for each pattern, create a new view, this view will create // a new input element _.each(params, function(param, index) { new Mariachi.Views.Parameters({parameter: param}); }); }, execute: function(e) { // On execution, a task will be created e.preventDefault(); var self = this; var data = {} data.type = "recepie"; data.server = $("select#servers").val(); data.task = self.recepieId; var parameters = new Array(); _.each($(".parameter-input"), function(parameter, index) { var id = $(parameter).attr("id"); var value = $(parameter).val(); // Add every pattern to an array parameters.push({id: id, value: value}); }); data.parameters = JSON.stringify(parameters); var model = new Mariachi.Models.Task(data); model.save(data, { success: function(model, response) { var collection = new Mariachi.Collections.Tasks(); collection.add(model); }, error: function(model, error) { console.log(error); new Mariachi.Views.MessageView({ message: "Error: " + error.statusText + "(" + error.status + ")", type: "danger" }); self.loading.hide(); } }); self.loading.hide(); self.listen(); }, listen: function() { var self = this; $("form").fadeOut(); // Clean the well and show the div $(".results").removeClass("hidden"); $(".results").fadeIn(); $(".stdout").html(" "); $(".stderr").html(" "); Mariachi.io.on("tasks:start", function(data) { // Remove the form $("span#deployStatus").removeClass().addClass("label label-info").text("EXECUTING"); console.log("Started"); console.log(data.started); $("span#started").text("Started: " + data.started); if(!_.isNull(data.stderr)) { var stderr = data.stderr.replace(new RegExp('\r?\n', 'g'), '<br />'); $(".stderr").html(stderr); $("span#deployStatus").removeClass().addClass("label label-danger").text("ERROR"); } if(!_.isNull(data.stdout)) { var stdout = data.stdout.replace(new RegExp('\r?\n', 'g'), '<br />'); $(".stdout").html(stdout); } }); Mariachi.io.on("tasks:stream", function(data) { if(!_.isNull(data.stderr) && !_.isUndefined(data.stderr)) { var stderr = data.stderr.replace(new RegExp('\r?\n', 'g'), '<br />'); $(".stderr").html(stderr); } if(!_.isNull(data.stdout) && !_.isUndefined(data.stdout)) { var stdout = data.stdout.replace(new RegExp('\r?\n', 'g'), '<br />'); $(".stdout").html(stdout); } }); Mariachi.io.on("tasks:finished", function(data) { console.log(data.ended); $("span#ended").text("Ended: " + data.ended); if(data.status === "SUCCESS") { $("span#deployStatus").removeClass().addClass("label label-success").text(data.status); } if(data.status === "ERROR") { $("span#deployStatus").removeClass().addClass("label label-danger").text(data.status); } self.loading.hide(); }); } });
module.exports = { patternlab: { files: [ { expand: true, cwd: 'core/styleguide/', src: ['./**/*.*'], dest: '<%= globalConfig.public.public %>/styleguide/' } ] }, fontsPublic: { files: [ { expand: true, cwd: '<%= globalConfig.source.fonts %>/', src: ['./**/*.*'], dest: '<%= globalConfig.public.fonts %>/' } ] }, fontsDist: { files: [ { expand: true, cwd: '<%= globalConfig.source.fonts %>/', src: ['./**/*.*'], dest: '<%= globalConfig.dist.fonts %>/' } ] }, jsPublic: { files: [ { expand: true, cwd: '<%= globalConfig.source.js %>/', src: ['./**/*.*'], dest: '<%= globalConfig.public.js %>/' } ] }, jsDist: { files: [ { expand: true, cwd: '<%= globalConfig.source.js %>/standalone', src: ['*.js'], dest: '<%= globalConfig.dist.js %>/' } ] } };