code
stringlengths
2
1.05M
AngularApp.factory('s1', [ '$log', function ($log) { 'use strict'; $log.info('s1 service loaded'); var s1 = { init: function () { } /* getGroups: function () { $log.debug('getGroups', g.groups); return g.groups; }, getGroup: function (groupId) { return g.groups[groupId]; }, addGroup: function (group) { var gk = Object.keys(g.groups); var id = Number(gk[gk.length - 1]) + 1; g.groups[id] = { name: group.name, members: [] }; $log.debug('addGroup', group, gk, id, g); }, deleteGroup: function (groupKey) { var m = g.groups[groupKey].members; if (!m || m.length === 0) { delete g.groups[groupKey]; } } */ }; s1.init(); return s1; } ]);
import React from 'react'; import NewsList from './NewsList'; class Stream extends React.Component { constructor(props) { super(props); this.state = { data: null }; } componentDidMount() { const URL = 'http://feeds.dzone.com/home'; let streamComponent = this; feednami.load(URL, function(result) { if (result.error) { //console.log(result.error) } let entriesData = result.feed.entries; streamComponent.setState({ data: entriesData }); }); } render() { return ( <NewsList listOfNews={this.state.data} /> ) } } export default Stream;
/* jshint unused: true, laxcomma: true, freeze: true, strict: true */ (function (win, doc, xhr) { 'use strict'; var Sherlog = { /** * Sets the resolution units and initializes the framework. * * @return void */ init: function() { this.environment(); this.error(); this.xhr(); }, /** * Sets the environment from the "data-environment" attribute of corresponding script tag. * NOTE: It will only find the attribute when the framework's source contains 'sherlog' keyword. * * @return void */ environment: function() { var s = doc.getElementsByTagName('script') , env; for( var i = 0, l = s.length; i < l; i++) { if (s[i].src.indexOf('sherlog') > -1) { env = s[i].getAttribute('data-environment'); break; } } this.environment = env || ''; }, /** * Listens for the error events, fires the pixel as soon as catches one. * * @return void */ error: function() { var _this = this; win.onerror = function (m, u, l, c, e) { // TODO: Stack trace param (e) will not work in old browsers. var s = e ? e.stack : null; _this.format([m,u,l,c,s], 0); _this.inject(); }; }, /** * Fires custom tracking events. * * @return void */ event: function(data) { this.format(data, 1); this.inject(); }, /** * Fires xhr error event once request returns 4xx or 5xx response. * * @return void */ xhr: function() { var _self = this , _open = xhr.prototype.open , _send = xhr.prototype.send , _method, _url, _timestamp; xhr.prototype.open = function(method, url) { _timestamp = new Date(); _method = method; _url = url; _open.apply(this, arguments); }; xhr.prototype.send = function() { var self = this; var cb = function(response) { if (self.readyState == 4) { try { var res , status = response.target.status.toString() , timeSpan = new Date() - _timestamp , isError = /^[45]/.test(status.slice(0, -2)); if (!isError) { return; } try { res = JSON.parse(response.target.response); } catch(e) { res = response.target.response.substring(0, 100); } _self.format([_method, status, res, _url, timeSpan], 2); _self.inject(); } catch(e){} } }; this.addEventListener('readystatechange', cb, false); _send.apply(this, arguments); }; }, /** * Formats data to be sent to server according to tracking type. * * @param data obj * @param type number * @return void */ format: function(data, type) { this.type = type; switch (this.type) { case 0: this.data = { message : data[0], source : data[1], line : data[2], column : data[3], stack : data[4] }; break; case 1: this.data = (typeof data !== 'object') ? { _event : data } : data; break; case 2: this.data = { method : data[0], status : data[1], response : data[2], url : data[3], response_time : data[4] }; break; } }, /** * Returns the structured url with params. * * @return string */ url: function() { var params = '&t=' + this.type + '&d=' + encodeURIComponent(JSON.stringify(this.data)) + '&cw=' + screen.width + '&ch=' + screen.height + '&e=' + encodeURIComponent(this.environment); return (win.location.protocol+'//{{sherlog_url}}/{{pixel_name}}?ts='+(new Date().getTime())+params); }, /** * Injects the pixel into DOM. * * @return void */ inject: function() { var img = document.createElement('img'); img.style.visibility = 'hidden'; img.src = this.url(); doc.getElementsByTagName('body')[0].appendChild(img); img.parentNode.removeChild(img); } }; var Public = { /** * Public method for event tracker, sends callback when the process is done. * * @param data obj * @param cb function * @return void */ push: function (data, cb) { if (typeof data === 'undefined') { return; } try { Sherlog.event(data); // Uses the default context for this. // We don't have anything to expose to the user, so we don't pass `this` as the callback context cb.call(null); } catch(e) {} } }; Sherlog.init(); win.Sherlog = win.Sherlog || Public; }(window, document, XMLHttpRequest));
(function(global) { var farProblemCauseViewModel, app = global.app = global.app || {}; farProblemCauseViewModel = kendo.data.ObservableObject.extend({ _isLoading: true, userId: function() { var cache = localStorage.getItem("profileData"); if (cache == null || cache == undefined) { return null; } else { return JSON.parse(cache).userId; } }, //=========================================================================================== initFaMProblemCauseMaster: function() { var that = this; $("#lvFProblemCauseM").kendoMobileListView({ dataSource: { transport: { read: function(operation) { //operation.success(JSON.parse(localStorage.getItem("favoriteProblemCausesData"))); if (app.configService.isMorkupData) { var response = { "favoriteProblemCauses": [{ "userId": "7478", "favProblemCauseId": "6", "problemCauseMainId": "02", "problemCauseDesc": "Transmission", "problemCauseSubId": "016", "problemCauseSubDesc": "Connector/Patch cord" }, { "userId": "7478", "favProblemCauseId": "2", "problemCauseMainId": "08", "problemCauseDesc": "AC MAIN FAILED", "problemCauseSubId": "042", "problemCauseSubDesc": "MEA/PEA Failed" }, { "userId": "7478", "favProblemCauseId": "1", "problemCauseMainId": "08", "problemCauseDesc": "AC MAIN FAILED", "problemCauseSubId": "050", "problemCauseSubDesc": "Phase Error / Loss of Phase" }], "version": "1", "userId": "7478", "jobId": "" }; localStorage.setItem("favoriteProblemCausesMultiData", JSON.stringify(response)); } else { $.ajax({ //using jsfiddle's echo service to simulate remote data loading type: "POST", timeout: 180000, url: app.configService.serviceUrl + 'post-json.service?s=master-service&o=getFavoriteProblemCauseMultiTTSME.json', data: JSON.stringify({ "token": localStorage.getItem("token"), "userId": JSON.parse(localStorage.getItem("profileData")).userId, "statusId": "", "version": "2" }), dataType: "json", contentType: 'application/json', success: function(response) { localStorage.setItem("favoriteProblemCausesMultiData", JSON.stringify(response)); operation.success(response); //that.hideLoading(); ////console.log("fetch Reason Over Due Data : Complete"); ////console.log("Reason Over Due Data :" + JSON.stringify(response)); }, error: function(xhr, error) { if (!app.ajaxHandlerService.error(xhr, error)) { var cache = localStorage.getItem("favoriteProblemCausesMultiData"); if (cache == null || cache == undefined) { ////console.log("Get Reason Over Due failed"); ////console.log(xhr); ////console.log(error); navigator.notification.alert(xhr.status + error, function() {}, "Get Favorite Problem Causes failed", 'OK'); } } return; }, complete: function() { that.hideLoading(); } }); } } }, schema: { data: "favoriteProblemCauses" } }, template: $("#favorite-problem-cause-multi-template").html(), databound: function() { that.hideLoading(); }, filterable: { field: "multiCauseDesc", ignoreCase: true }, click: function(e) { that.selectPbCM(e); } //virtualViewSize: 30, //endlessScroll: true, }); ////console.log('lv Problemcause Master Loaded'); }, showFaProblemCauseMaster: function() { var that = this; // app.masterService.viewModel.loadFavoriteProblemCauses(); // var aa = JSON.parse(localStorage.getItem("favoriteProblemCausesData")); var lvFProblemCauseM = $("#lvFProblemCauseM").data("kendoMobileListView"); lvFProblemCauseM.dataSource.read(); lvFProblemCauseM.refresh(); // $("#lvFProblemCauseM").kendoMobileListView({ // dataSource: { // transport: { // read: function(operation) { // operation.success(JSON.parse(localStorage.getItem("favoriteProblemCausesData"))); // } // }, // schema: { // data: "favoriteProblemCauses" // } // }, // template: $("#Fproblem-cause-template").html(), // databound: function() { // that.hideLoading(); // }, // filterable: { // field: "problemCauseDesc", // ignoreCase: true // }, // click: function(e) { // that.selectPbC(e); // } // //virtualViewSize: 30, // //endlessScroll: true, // }); ////console.log('lv Problemcause Master Loaded'); }, loadFaProblemCauseMaster: function() { var that = this; var lvProblemCauseMaster = $("#lvFProblemCauseM").data("kendoMobileListView"); //lvProblemCauseMaster.reset(); app.application.view().scroller.reset(); //$("#lvProblemCauseMaster").kendoMobileListView({ // dataSource: problemCauseData // }, // schema: { // data: "problemCauses" // }, // // }), // template: $("#problem-cause-template").html(), //}); ////console.log('lv Problemcause Master Loaded'); }, selectPbCM: function(e) { //console.log("###### selectPbC #########"); var that = app.jobService.viewModel; var selectItem = that.get("selectItem"); var selectProblemCM = that.get("selectProblemCM"); var flag = true; if (selectProblemCM != null && selectProblemCM != undefined) { var data = selectProblemCM.data(); for (var i = 0; i < data.length; i++) { // var multiID = data[i].multiCauseId.split("|"); // var level = multiID.length-1; if (data[i].multiCauseIds == e.dataItem.multiCauseId) { flag = false; e.preventDefault(); navigator.notification.alert("Duplicate problem cause.", function() {}, "Error", 'OK'); i = data.length; } } } else { selectProblemCM = new kendo.data.DataSource(); } if (flag) { selectItem.cntProblemCause++; var pbcm = { //"ids": e.dataItem.id, "jobId": selectItem.jobId, "seqId": null, "multiCauseIds": e.dataItem.multiCauseId, "multiCauseLevels": e.dataItem.multiCauseLevel, "maxLevel": e.dataItem.maxLevel, "multiCauseDescs": e.dataItem.multiCauseDesc }; selectProblemCM.pushCreate(pbcm); selectProblemCM.fetch(function() { that.set("selectProblemCM", selectProblemCM); }); // app.favoriteProblemCauseMService.viewModel.setFarProblemSolveRadio(); //SUBPRO_CAUSE_ID //SUBPRO_CAUSE_DESCRIPTION //SUBPRO_CAUSE_STATUS //SUBPRO_CAUSE_PRO_CAUSE_ID //PROBLEM_CAUSE_ID //PROBLEM_CAUSE_DESCRIPTION that.set("selectItem", selectItem); //that.set("selectPage", 2); app.application.navigate( '#job-problem-cause-multi' ); } else { // navigator.notification.alert("Problem cause duplicate", // function() {}, "Error", 'OK'); } }, setFarProblemSolveRadio: function() { var that = app.jobService.viewModel; var selectItem = that.get("selectItem"); var problemSolveRadioData = null; var selectProblemCM = that.get("selectProblemCM"); var selectProblemSP = that.get("selectProblemSP"); var problemSolveData = new kendo.data.DataSource({ transport: { read: function(operation) { operation.success(JSON.parse(localStorage.getItem("favoriteProblemCausesMultiData"))); } }, schema: { data: "favoriteProblemCauses" } }); var filter = { logic: "or", filters: [] } if (selectProblemCM != undefined && selectProblemCM != null) { var data = selectProblemCM.data(); for (var i = 0; i < data.length; i++) { var filters = { field: "subproblemCauseId", operator: "eq", value: data[i].problemCauseSubId }; filter.filters.push(filters); } problemSolveData.filter(filter); problemSolveData.fetch(function() { problemSolveRadioData = new kendo.data.DataSource({ transport: { read: function(operation) { operation.success(problemSolveData.view()); } }, filter: [{ field: "description", operator: "eq", value: "Temporary" }] }); ////console.log(JSON.stringify(problemSolveData)); problemSolveRadioData.fetch(function() { data = problemSolveRadioData.view(); if (data.length > 0) { var a = data.length; for (var i = 0; i < a; i++) { if (selectProblemS != undefined && selectProblemS != null) { selectProblemS.fetch(function() { dataS = selectProblemS.data(); if (dataS.length > 0) { var flagDup = false; var b = dataS.length; for (var j = 0; j < b; j++) { if (data[i].subproblemCauseId == dataS[j].subProblemCauseId) { var flagDup = true; //return false; j = dataS.length; } } if (!flagDup) { var pbs = { "jobId": selectItem.jobId, "problemSolveId": data[i].id, "problemSolveDesc": data[i].subProblemCauseDesc + "-" + data[i].description, "processDesc": "", "subProblemCauseId": data[i].subproblemCauseId, "process": "N" }; selectProblemS.pushCreate(pbs); } } else { var pbs = [{ "jobId": selectItem.jobId, "problemSolveId": data[i].id, "problemSolveDesc": data[i].subProblemCauseDesc + "-" + data[i].description, "processDesc": "", "subProblemCauseId": data[i].subproblemCauseId, "process": "N" }]; selectProblemS = new kendo.data.DataSource({ data: pbs }); } }) } else { var pbs = [{ "jobId": selectItem.jobId, "problemSolveId": data[i].id, "problemSolveDesc": data[i].subProblemCauseDesc + "-" + data[i].description, "processDesc": "", "subProblemCauseId": data[i].subproblemCauseId, "process": "N" }]; selectProblemS = new kendo.data.DataSource({ data: pbs }); } } } if (selectProblemS != null && selectProblemS != undefined) { selectProblemS.fetch(function() { that.set("selectProblemS", selectProblemS); }); } else { that.set("selectProblemS", new kendo.data.DataSource()); } }); }); } // }, showLoading: function() { //if (this._isLoading) { app.application.showLoading(); //} }, hideLoading: function() { app.application.hideLoading(); }, }); app.favoriteProblemCauseMService = { init: function() { ////console.log("myteam init start"); app.favoriteProblemCauseMService.viewModel.initFaMProblemCauseMaster(); ////console.log("myteam init end"); }, show: function() { //app.faProblemCauseService.viewModel.showFaProblemCauseMaster(); //app.faProblemCauseService.viewModel.initFaProblemCauseMaster(); ////console.log("myteam show start"); //app.problemCauseService.viewModel.showLoading(); //app.problemCauseService.viewModel.loadProblemCauseMaster(); //app.myService.viewModel.hideLoading(////console.logle.debug("myteam hide hide"); }, hide: function() { ////console.log("myteam hide start"); //app.myService.viewModel.hideLoading(); ////console.log("myteam hide hide"); }, viewModel: new farProblemCauseViewModel() } })(window);
'use strict'; // Declare app level module which depends on views, and components angular.module('myContacts', [ 'ngRoute', 'firebase', 'myContacts.contacts' ]).config(['$routeProvider', function ($routeProvider) { $routeProvider.otherwise({redirectTo: '/contacts'}); }]);
import { ADV_TOP_REQUEST_DATA , ADV_LEFT_REQUEST_DATA , SAMPLES_REQUEST_DATA , PRINGLES_REQUEST_DATA , SUITES_REQUEST_DATA } from '../actions/homeAction' const initState = { params : {}, req_counter : 0, sliderTopData : [], sliderLeftData : [], samplesData : [], pringlesData : [], suitesData : [], } export default function all( home = initState, action) { switch (action.type) { case ADV_TOP_REQUEST_DATA: return Object.assign({}, home, { req_counter : home.req_counter + 1, sliderTopData : action.data, }) case ADV_LEFT_REQUEST_DATA: return Object.assign({}, home, { req_counter : home.req_counter + 1, sliderLeftData : action.data, }) case SAMPLES_REQUEST_DATA: return Object.assign({}, home, { req_counter : home.req_counter + 1, samplesData : action.data, }) case PRINGLES_REQUEST_DATA: return Object.assign({}, home, { req_counter : home.req_counter + 1, pringlesData : action.data, }) case SUITES_REQUEST_DATA: return Object.assign({}, home, { req_counter : home.req_counter + 1, suitesData : action.data, }) default: return home } }
import { XMLSchema } from 'substance' import JATSArchivingData from '../../tmp/JATS-archiving.data' const JATSArchiving = XMLSchema.fromJSON(JATSArchivingData) // TODO: this should come from compilation JATSArchiving.getName = function() { return 'jats' } JATSArchiving.getVersion = function() { return '1.1' } JATSArchiving.getDocTypeParams = function() { return [ 'article', '-//NLM//DTD JATS (Z39.96) Journal Archiving DTD v1.0 20120330//EN', 'JATS-journalarchiving.dtd' ] } export default JATSArchiving
// Copyright 2018 by caixw, All rights reserved. // Use of this source code is governed by a MIT // license that can be found in the LICENSE file. 'use strict'; const versions = new Map(); {{VERSIONS}} self.addEventListener('install', (event)=>{ console.info('sw install'); event.waitUntil(onInstall()); }); self.addEventListener('fetch', (event)=>{ console.info('sw fetch'); event.respondWith(onFetch(event)); }); self.addEventListener('activate', (event)=>{ console.info('sw activate'); event.waitUntil(onActivate()); }) function onInstall() { const ps = []; for (let [key, vals] of versions) { const p = caches.open(key).then((cache)=>{ return cache.addAll(vals); }) ps.push(p); } return Promise.all(ps); } function onFetch(event) { return caches.match(event.request).then((resp)=>{ return resp || fetch(event.request); }).catch((err)=>{ console.error('sw fetch error:', err); return fetch(event.request); }) } function onActivate() { return caches.keys().then((cachesName)=>{ const ps = []; cachesName.forEach((name)=>{ if (!cacheExists(name)) { const p = caches.delete(name); ps.push(p); } }) return Promise.all(ps); }); } function cacheExists(name) { for(let [key, val] of versions) { if (key == name) { return true; } } return false; }
var theCanvas; var frames = 0; var showCapture = true; var screenWidth = 360; var screenHeight = 270; var totalParticles = 100; var pixelsPerFrame1; var oldX1 = 0; var oldY1 = 0; var sumPPF1 = 0; var averagePPF1; // video capture object var capture; // colors we want to track var r1 = 0; var g1 = 0; var b1 = 0; var xPos1; var yPos1; var runRadius = 30; var frameCheck = 40; var currentColor = 1; // low numbers means more color sensitivity, high numbers mean less sensitivity (aka false positives) var threshold = 20; var marker; var hand; var bg1; var bg2; var bg3; var bg4; var particle1; var particle2; var particle3; var particle4; var transitionSound; var aura1Sound; var aura2Sound; var aura3Sound; var aura4Sound; var oldAura = 0; var currentAura = 0; var auraChanged = false; function preload() { transitionSound = loadSound("../sounds/transition.mp3"); aura1Sound = loadSound("../sounds/aura1.mp3"); aura2Sound = loadSound("../sounds/aura2.m4a"); aura3Sound = loadSound("../sounds/aura3.m4a"); aura4Sound = loadSound("../sounds/aura4.m4a"); marker = loadImage("../img/marker.png"); bg1 = loadImage("../backgrounds/1-01.png"); bg2 = loadImage("../backgrounds/2-02.png"); bg3 = loadImage("../backgrounds/3-03.png"); bg4 = loadImage("../backgrounds/4-04.png"); particle1 = loadImage("../particles/1.png"); particle2 = loadImage("../particles/2.png"); particle3 = loadImage("../particles/3.png"); particle4 = loadImage("../particles/4-02.png"); hand = loadImage("../particles/hand.png"); } function setup() { // container.style('width', '100%'); // container.style('height', '100%'); // start up our web cam capture = createCapture({ video: { mandatory: { minWidth: screenWidth, minHeight: screenHeight, maxWidth: screenWidth, maxHeight: screenHeight } } }); capture.hide(); noStroke(); noFill(); rectMode(CENTER); imageMode(CENTER); // request a detailed noise landscape noiseDetail(24); // create our walker array walkerArray = []; // create particle system for (var i = 0; i < totalParticles; i++) { var tempWalker = new NoiseWalker( random(screenWidth), random(screenHeight) ); walkerArray.push( tempWalker ); } theCanvas = createCanvas(screenWidth, screenHeight); var canvasNode = document.getElementById("defaultCanvas0"); var parent = canvasNode.parentNode; var wrapper = document.createElement('div'); parent.replaceChild(wrapper, canvasNode); var theVideo = document.getElementsByTagName("video")[0]; console.log(theVideo); wrapper.appendChild(canvasNode); wrapper.appendChild(theVideo); wrapper.id = "container" // canvasNode.style.width = "100%"; // canvasNode.style.height = "100%"; // // videoNode.style.width = "100%"; // videoNode.style.height = "100%"; // // wrapper.style.width = "100%"; // wrapper.style.height = "100%"; } function draw() { capture.loadPixels(); mirrorVideo(); if (capture.pixels.length > 0) { var bestLocations1 = []; for (var i = 0; i < capture.pixels.length; i += 8) { var match1 = dist(r1, g1, b1, capture.pixels[i], capture.pixels[i + 1], capture.pixels[i + 2]); if (match1 < threshold) { bestLocations1.push(i); } } // draw the video only if we still need it! if (showCapture){ image(capture, screenWidth/2, screenHeight/2); } else { animateBackground(); } // do we have a best match? it's possible that no pixels met our threshold if (bestLocations1.length > 0) { var xSum = 0; var ySum = 0; for (var i = 0; i < bestLocations1.length; i++) { xSum += (bestLocations1[i] / 4) % screenWidth; ySum += (bestLocations1[i] / 4) / screenWidth; } // average our sums to get our 'centroid' point xPos1 = xSum / bestLocations1.length; yPos1 = ySum / bestLocations1.length; // now we know the best match! draw a box around it // stroke(0,255,0); // rect(xPos1, yPos1, 25, 25); image(hand, xPos1, yPos1, 40, 40); } pixelsPerFrame1 = dist(oldX1, oldY1, xPos1, yPos1); oldX1 = xPos1; oldY1 = yPos1; sumPPF1 += pixelsPerFrame1; if (frames % frameCheck == 0){ averagePPF1 = sumPPF1 / 30; sumPPF1 = 0; console.log(averagePPF1); } frames++; } } function mousePressed() { // memorize the color the user is clicking on var loc = int( (mouseX + mouseY * capture.width) * 4); if (currentColor == 1) { r1 = capture.pixels[loc]; g1 = capture.pixels[loc + 1]; b1 = capture.pixels[loc + 2]; console.log("Color 1 - Looking for: R=" + r1 + "; G=" + g1 + "; B=" + b1); currentColor = 2; } if (r1 != 0 && g1 != 0 && b1 != 0){ showCapture = false; } } function keyPressed() { if (key == 'A') { threshold--; console.log("Threshold is now: " + threshold); } if (key == 'D') { threshold++; console.log("Threshold is now: " + threshold); } } // mirror our video function mirrorVideo() { // iterate over 1/2 of the width of the image & the full height of the image for (var x = 0; x < capture.width/2; x++) { for (var y = 0; y < capture.height; y++) { // compute location here var loc1 = (x + y*capture.width) * 4; var loc2 = (capture.width-x + y*capture.width) * 4; // swap pixels from left to right var tR = capture.pixels[loc1]; var tG = capture.pixels[loc1+1]; var tB = capture.pixels[loc1+2]; capture.pixels[loc1] = capture.pixels[loc2]; capture.pixels[loc1+1] = capture.pixels[loc2+1]; capture.pixels[loc1+2] = capture.pixels[loc2+2]; capture.pixels[loc2] = tR; capture.pixels[loc2+1] = tG; capture.pixels[loc2+2] = tB; } } capture.updatePixels(); } function animateBackground(){ if (averagePPF1 < 2){ oldAura = currentAura; currentAura = 1; if (oldAura != currentAura){ auraChanged = true; } runRadius = 30; animation1(); } else if (averagePPF1 < 6){ oldAura = currentAura; currentAura = 2; if (oldAura != currentAura){ auraChanged = true; } runRadius = 80; animation2(); } else if (averagePPF1 < 10){ oldAura = currentAura; currentAura = 3; if (oldAura != currentAura){ auraChanged = true; } runRadius = 55; animation3(); } else { oldAura = currentAura; currentAura = 4; if (oldAura != currentAura){ auraChanged = true; } runRadius = 65; animation4(); } if (auraChanged){ transitionSound.play(); if (currentAura == 1){ aura1Sound.play(); aura2Sound.stop(); aura3Sound.stop(); aura4Sound.stop(); } else if (currentAura == 2){ aura1Sound.stop(); aura2Sound.play(); aura3Sound.stop(); aura4Sound.stop(); } else if (currentAura == 3){ aura1Sound.stop(); aura2Sound.stop(); aura3Sound.play(); aura4Sound.stop(); } else if (currentAura == 4){ aura1Sound.stop(); aura2Sound.stop(); aura3Sound.stop(); aura4Sound.play(); } auraChanged = false; } } function animation1(){ image(bg1, screenWidth/2 , screenHeight/2, width, height); for (var i = 0; i < walkerArray.length; i++) { walkerArray[i].move1(); walkerArray[i].display1(); } } function animation2(){ image(bg2, screenWidth/2 , screenHeight/2, width, height); for (var i = 0; i < walkerArray.length; i++) { walkerArray[i].move2(); walkerArray[i].display2(); } } function animation3(){ image(bg3, screenWidth/2 , screenHeight/2, width, height); for (var i = 0; i < walkerArray.length; i++) { walkerArray[i].move3(); walkerArray[i].display3(); } } function animation4(){ image(bg4, screenWidth/2 , screenHeight/2, width, height); for (var i = 0; i < walkerArray.length; i++) { walkerArray[i].move4(); walkerArray[i].display4(); } } // our NoiseWalker class function NoiseWalker(x, y) { // store our position this.x = x; this.y = y; this.scale = random(.5, 1.5); // store our color this.r = random(100,255); this.g = this.r; this.b = this.r; // store our size this.s = 5; // create a "noise offset" to keep track of our position in Perlin Noise space this.xNoiseOffset = random(0,1000); this.yNoiseOffset = random(1000,2000); // display mechanics this.display1 = function() { image(particle1, this.x, this.y, 80*map(this.scale, .3, 1.5, .2, 2), 80*map(this.scale, .5, 1.5, .2, 1.5)); } this.display2 = function() { image(particle2, this.x, this.y, 70*this.scale, 70*this.scale); } this.display3 = function() { image(particle3, this.x, this.y, 50*this.scale, 50*this.scale); } this.display4 = function() { image(particle4, this.x, this.y, 30, 30); } // movement mechanics this.move1 = function() { // compute how much we should move var xMovement = map( noise(this.xNoiseOffset), 0, 1, -1, 1 ); var yMovement = map( noise(this.yNoiseOffset), 0, 1, -1, 1 ); // update our position this.x += xMovement*1; this.y += yMovement*1; // are we close to the mouse? if so, run away! if (dist(this.x, this.y, xPos1, yPos1) < 25) { var speed = 1; if (xPos1 < this.x) { this.x += speed; } else { this.x -= speed; } if (yPos1 < this.y) { this.y += speed; } else { this.y -= speed; } } // handle wrap-around if (this.x > width) { this.x = 0; } else if (this.x < 0) { this.x = width; } if (this.y > height) { this.y = 0; } else if (this.y < 0) { this.y = height; } this.xNoiseOffset += 0.01; this.yNoiseOffset += 0.01; } this.move2 = function() { // compute how much we should move var xMovement = map( noise(this.xNoiseOffset), 0, 1, -1, 1 ); var yMovement = map( noise(this.yNoiseOffset), 0, 1, -1, 1 ); // update our position this.x += xMovement*2; this.y += yMovement*2; // are we close to the mouse? if so, run away! if (dist(this.x, this.y, xPos1, yPos1) < 25) { var speed = 2; if (xPos1 < this.x) { this.x += speed; } else { this.x -= speed; } if (yPos1 < this.y) { this.y += speed; } else { this.y -= speed; } } // handle wrap-around if (this.x > width) { this.x = 0; } else if (this.x < 0) { this.x = width; } if (this.y > height) { this.y = 0; } else if (this.y < 0) { this.y = height; } this.xNoiseOffset += 0.01; this.yNoiseOffset += 0.01; } this.move3 = function() { // compute how much we should move var xMovement = map( noise(this.xNoiseOffset), 0, 1, -1, 1 ); var yMovement = map( noise(this.yNoiseOffset), 0, 1, -1, 1 ); // update our position this.x += xMovement*3; this.y += yMovement*3; // are we close to the mouse? if so, run away! if (dist(this.x, this.y, xPos1, yPos1) < runRadius) { var speed = 3; if (xPos1 < this.x) { this.x += speed; } else { this.x -= speed; } if (yPos1 < this.y) { this.y += speed; } else { this.y -= speed; } } // handle wrap-around if (this.x > width) { this.x = 0; } else if (this.x < 0) { this.x = width; } if (this.y > height) { this.y = 0; } else if (this.y < 0) { this.y = height; } this.xNoiseOffset += 0.01; this.yNoiseOffset += 0.01; } this.move4 = function() { // compute how much we should move var xMovement = map( noise(this.xNoiseOffset), 0, 1, -1, 1 ); var yMovement = map( noise(this.yNoiseOffset), 0, 1, -1, 1 ); // update our position this.x += xMovement*8; this.y += yMovement*8; // are we close to the mouse? if so, run away! if (dist(this.x, this.y, xPos1, yPos1) < runRadius) { var speed = 8; if (xPos1 < this.x) { this.x += speed; } else { this.x -= speed; } if (yPos1 < this.y) { this.y += speed; } else { this.y -= speed; } } // handle wrap-around if (this.x > width) { this.x = 0; } else if (this.x < 0) { this.x = width; } if (this.y > height) { this.y = 0; } else if (this.y < 0) { this.y = height; } this.xNoiseOffset += 0.01; this.yNoiseOffset += 0.01; } }
var getByClass = require('get-by-class'); var Templater = function(list) { var itemSource = getItemSource(list.item), templater = this; function getItemSource(item) { if (item === undefined) { var nodes = list.list.childNodes, items = []; for (var i = 0, il = nodes.length; i < il; i++) { // Only textnodes have a data attribute if (nodes[i].data === undefined) { return nodes[i]; } } return null; } else if (item.indexOf("<") !== -1) { // Try create html element of list, do not work for tables!! var div = document.createElement('div'); div.innerHTML = item; return div.firstChild; } else { return document.getElementById(list.item); } } /* Get values from element */ this.get = function(item, valueNames) { templater.create(item); var values = {}; for(var i = 0, il = valueNames.length; i < il; i++) { var elm = getByClass(item.elm, valueNames[i], true); values[valueNames[i]] = elm ? elm.innerHTML : ""; } return values; }; /* Sets values at element */ this.set = function(item, values) { if (!templater.create(item)) { for(var v in values) { if (values.hasOwnProperty(v)) { // TODO speed up if possible var elm = getByClass(item.elm, v, true); if (elm) { /* src attribute for image tag & text for other tags */ if (elm.tagName === "IMG" && values[v] !== "") { elm.src = values[v]; } else if(elm.tagName === "INPUT" && values[v] !== "") { if(elm.type === 'checkbox') { if(values[v] === true) { elm.setAttribute('checked', true); } else { elm.removeAttribute('checked'); } } else { elm.value = values[v]; } } else { elm.innerHTML = values[v]; } } } } } }; this.create = function(item) { if (item.elm !== undefined) { return false; } /* If item source does not exists, use the first item in list as source for new items */ var newItem = itemSource.cloneNode(true); newItem.removeAttribute('id'); item.elm = newItem; templater.set(item, item.values()); return true; }; this.remove = function(item) { if (item.elm.parentNode === list.list) { list.list.removeChild(item.elm); } }; this.show = function(item) { templater.create(item); list.list.appendChild(item.elm); }; this.hide = function(item) { if (item.elm !== undefined && item.elm.parentNode === list.list) { list.list.removeChild(item.elm); } }; this.clear = function() { /* .innerHTML = ''; fucks up IE */ if (list.list.hasChildNodes()) { while (list.list.childNodes.length >= 1) { list.list.removeChild(list.list.firstChild); } } }; }; module.exports = function(list) { return new Templater(list); };
'use strict'; var gulp = require('../'); var Q = require('q'); var should = require('should'); require('mocha'); describe('jsrun start', function() { it('should run multiple tasks', function(done) { var a, fn, fn2; a = 0; fn = function() { this.should.equal(gulp); ++a; }; fn2 = function() { this.should.equal(gulp); ++a; }; gulp.task('test', fn); gulp.task('test2', fn2); gulp.start(['test', 'test2']); a.should.equal(2); gulp.reset(); done(); }); it('should run all tasks when call start() multiple times', function(done) { var a, fn, fn2; a = 0; fn = function() { this.should.equal(gulp); ++a; }; fn2 = function() { this.should.equal(gulp); ++a; }; gulp.task('test', fn); gulp.task('test2', fn2); gulp.start('test'); gulp.start('test2'); a.should.equal(2); gulp.reset(); done(); }); it('should run all async promise tasks', function(done) { var a, fn, fn2; a = 0; fn = function() { var deferred = Q.defer(); setTimeout(function() { ++a; deferred.resolve(); }, 1); return deferred.promise; }; fn2 = function() { var deferred = Q.defer(); setTimeout(function() { ++a; deferred.resolve(); }, 1); return deferred.promise; }; gulp.task('test', fn); gulp.task('test2', fn2); gulp.start('test'); gulp.start('test2', function() { gulp.isRunning.should.equal(false); a.should.equal(2); gulp.reset(); done(); }); gulp.isRunning.should.equal(true); }); it('should run all async callback tasks', function(done) { var a, fn, fn2; a = 0; fn = function(cb) { setTimeout(function() { ++a; cb(null); }, 1); }; fn2 = function(cb) { setTimeout(function() { ++a; cb(null); }, 1); }; gulp.task('test', fn); gulp.task('test2', fn2); gulp.start('test'); gulp.start('test2', function() { gulp.isRunning.should.equal(false); a.should.equal(2); gulp.reset(); done(); }); gulp.isRunning.should.equal(true); }); it('should emit task_not_found and throw an error when task is not defined', function(done) { gulp.on('task_not_found', function(err) { should.exist(err); should.exist(err.task); err.task.should.equal('test'); gulp.reset(); done(); }); try { gulp.start('test'); } catch (err) { should.exist(err); } }); it('should run task scoped to gulp', function(done) { var a, fn; a = 0; fn = function() { this.should.equal(gulp); ++a; }; gulp.task('test', fn); gulp.start('test'); a.should.equal(1); gulp.isRunning.should.equal(false); gulp.reset(); done(); }); it('should run default task scoped to gulp', function(done) { var a, fn; a = 0; fn = function() { this.should.equal(gulp); ++a; }; gulp.task('default', fn); gulp.start(); a.should.equal(1); gulp.isRunning.should.equal(false); gulp.reset(); done(); }); });
import React, {Component, PropTypes} from 'react'; import formatCurrency from '../lib/format_currency'; import { resizeImage, getGroupCustomStyles } from '../lib/utils'; const DEFAULT_LOGOS = [ '/public/images/code.svg', '/public/images/rocket.svg', '/public/images/repo.svg', ]; export default class SponsoredCard extends Component { render() { const { index, group, tier, className, width, target } = this.props; const formattedAmount = formatCurrency(group.myTotalDonations, group.currency, { compact: true, precision: 0 }); const defaultLogo = DEFAULT_LOGOS[index || Math.floor(Math.random() * DEFAULT_LOGOS.length)]; group.settings = group.settings || {}; group.settings.style = getGroupCustomStyles(group); if (group.backgroundImage && !group.backgroundImage.match(/^\//)) { group.settings.style.hero.cover.backgroundImage = `url(${resizeImage(group.backgroundImage, { width: width * 2 || 320 })})`; } return ( <div className={`SponsoredCard ${className}`}> <a href={group.publicUrl} target={target}> <div> <div className='SponsoredCard-head'> <div className='SponsoredCard-background' style={group.settings.style.hero.cover}></div> <div className='SponsoredCard-image' style={{backgroundImage: `url(${group.logo || defaultLogo})`}}></div> </div> <div className='SponsoredCard-body'> <div className='SponsoredCard-name'>{ group.name }</div> </div> <div className='SponsoredCard-footer'> {tier && <div className='SponsoredCard-type'>{ tier }</div> } {group.myTotalDonations > 0 && <div className='SponsoredCard-amount'>{`${formattedAmount}`}</div>} </div> </div> </a> </div> ); } } SponsoredCard.propTypes = { group: PropTypes.object.isRequired, interval: PropTypes.string.isRequired, tier: PropTypes.string, target: PropTypes.string, index: PropTypes.number }; SponsoredCard.defaultProps = { target: '_top', group: { amount: 0, currency: 'USD', interval: '', tier: '' } };
/* * Copyright 2014-2015 MarkLogic Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var exutil = require('./example-util.js'); //a real application would require without the 'exutil.' namespace var marklogic = exutil.require('marklogic'); var pb = marklogic.patchBuilder; var dbAdmin = marklogic.createDatabaseClient(exutil.restAdminConnection); var db = marklogic.createDatabaseClient(exutil.restWriterConnection); var timestamp = (new Date()).toISOString(); var uri = '/countries/uv.json'; var operations = [ pb.pathLanguage('jsonpath'), pb.replaceInsert('$.timestamp', '$.name', 'after', timestamp) ]; console.log('configure the server to enforce optimistic locking'); // a one-time administrative action dbAdmin.config.serverprops.write({ 'update-policy': 'version-required' }) .result(function(response) { console.log( 'try to update a value in the content to '+ timestamp+'\n without passing the document version id'); db.documents.patch({ uri: uri, operations: operations // versionId not specified }) .result(function(success) { console.log('should never execute'); }) .catch(function(failure) { console.log('expected failure for the update without the version id'); console.log('get the current version id for the document'); db.documents.probe(uri) .result(function(document){ console.log( 'try to update the document passing the version id '+document.versionId); return db.documents.patch({ uri: uri, operations: operations, versionId: document.versionId }).result(); }) .then(function(response){ console.log('update succeeded with the version id'); console.log('get the new version id for the updated document'); return db.documents.read(uri).result(); }) .then(function(documents) { var document = documents[0]; console.log( 'the document has the new version id '+document.versionId+ '\n and the content has an updated value of '+ document.content.timestamp ); // reconfigure the server to turn off optimistic locking return dbAdmin.config.serverprops.write({ 'update-policy': 'merge-metadata' }).result(); }) .then(function(response) { console.log('done'); exutil.succeeded(); }) .catch(function(error) { console.log(JSON.stringify(error)); exutil.failed(); }); }); }) .catch(function(error) { console.log(JSON.stringify(error)); exutil.failed(); });
var React = require('react'); var $ = require('jquery'); var Link = require('react-router').Link; var AppointmentWhen = React.createClass({ handleAppointmentWhen:function(){ this.props.appointmentDetailInputWhen(this.refs.date.value); this.props.handleAppointmentStep(1); }, handleAppointmentPrevious: function(){ this.props.handleAppointmentStep(-1); }, handleDatePicker: function(){ console.log("handleDatePicker"); $('#sandbox-container input').on('show', function(e){ console.debug('show', e.date, $(this).data('stickyDate')); if ( e.date ) { $(this).data('stickyDate', e.date); } else { $(this).data('stickyDate', null); } }); $('#sandbox-container input').on('hide', function(e){ console.debug('hide', e.date, $(this).data('stickyDate')); var stickyDate = $(this).data('stickyDate'); if ( !e.date && stickyDate ) { console.debug('restore stickyDate', stickyDate); $(this).datepicker('setDate', stickyDate); $(this).data('stickyDate', null); } }); }, componentDidMount: function() { $('#sandbox-container input').datepicker({ autoclose: true }); }, render: function(){ return( <form className="form"> <div className="form-group"> <div className="form-group"> <div id="sandbox-container"> <Link to="Appointment/AppointmentWhere" className="btn btn_default" onClick={this.handleAppointmentPrevious}>Previous</Link> <input type="input" id="datepickerInput" type="text" ref="date" placeholder="Date app." className="form-control" onClick={this.handleDatePicker}/> <Link to="Appointment/AppointmentCompleted" className="btn btn_default" onClick={this.handleAppointmentWhen}>Next</Link> </div> </div> </div> </form> ); } }); module.exports = AppointmentWhen;
"use strict";define("directives/todoItem_13e72c1317b3931cc1017f2ec2f08ef0",["tpl/todoItem_a1bc63a51282e9c56b21202e096cb7cd"],function(){var moduleName="TodoItemDirective";return angular.module(moduleName,[]).directive("todoItem",function($timeout){return{restrict:"A",templateUrl:"todo-item",link:function($scope,$element,$attr){$scope.editTodo=function(todo){$scope.editedTodo=todo,$scope.originalTodo=angular.copy(todo)},$scope.doneEditing=function(todo){$scope.editedTodo=null,todo.title=todo.title.trim(),todo.title||$scope.removeTodo(todo)}}}}),moduleName}),define("tpl/todoItem_a1bc63a51282e9c56b21202e096cb7cd",function(){utils.loadTtpl(function(){eval("var a='a'"),/*loadText*<!--target:todo-item--> <div class="view"> <input class="toggle" type="checkbox" ng-model="todo.completed"> <label ng-dblclick="editTodo(todo)">{{todo.title}}</label> <button class="destroy" ng-click="removeTodo(todo)"></button> </div> <form ng-submit="doneEditing(todo)"> <input class="edit" ng-trim="false" ng-model="todo.title" ng-blur="doneEditing(todo)" todo-escape="revertEditing(todo)" todo-focus="todo == editedTodo"> </form>loadTextEnd*/ eval("var a='a'")})});
'use strict'; const _ = require('lodash'); const util = require('../../util'); // 終了時刻(Minute)の登録 const editEndMinute = ({ act, model, workflow }) => { return ({ res, msg }) => { const domainId = util.res.getDomainId({ res }); const roomId = util.res.getRoomId({ res }); // 入力文字列を改行区切り・トリム・空行除外 const minute = msg.split('\n').map(_.trim).filter(m => m); const minuteNum = Number(_.head(minute)); // 1行の入力でない場合 if (minute.length !== 1) { workflow.message.notAllowManyInput({ roomId }); return; } // 数値でない場合 if (!minuteNum && (minuteNum !== 0)) { workflow.message.notAllowStringAllowNumeric({ roomId }); return; } // 終了分を上書登録 model.timers.saveItems({ domainId, end_minute: minuteNum }); // 現在の設定情報をメッセージ送信 workflow.message.settingInfo({ domainId, roomId }); // アクション設定 model.admin.saveAction({ domainId, action: 'SETTING' }); // 設定メッセージ送信 workflow.question.whatSetting({ roomId }); }; } module.exports = editEndMinute;
/** * Created by Taywan_ka on 25/02/2016. */ app.factory("RailtypeFactory", ['$resource', function ($resource) { return $resource("api/railtypes/:id/", {id: '@ID'}, { update: { method: 'PUT' } }); }]); app.service('RailtypeService', ['RailtypeFactory', '$rootScope', '$q', '$timeout', 'ngToast', function (RailtypeFactory, $rootScope, $q, $timeout, ngToast) { var self = { 'page': 1, 'hasMore': true, 'isLoading': false, 'isSaving': false, 'selectedRailType': null, 'list': [], 'search': null, 'ordering': 'ID', 'getRailType': function (id) { for (var i = 0; i < self.list.length; i++) { var obj = self.list[i]; if (parseInt(obj.ID) == id) return obj; } }, 'doSearch': function () { self.hasMore = true; self.page = 1; self.list = []; self.loadRailtypes(); }, 'doOrder': function () { self.hasMore = true; self.page = 1; self.list = []; self.loadRailtypes(); }, 'loadRailtypes': function () { if (self.hasMore && !self.isLoading) { self.isLoading = true; var params = { 'page': self.page, 'search': self.search, 'ordering': self.ordering }; RailtypeFactory.get(params, function (data) { angular.forEach(data.results, function (item) { self.list.push(new RailtypeFactory(item)); }); if (!data.next) self.hasMore = false; self.isLoading = false; }); } }, 'loadMore': function () { if (self.hasMore && !self.isLoading) { self.page += 1; self.loadRailtypes(); } }, 'getRailTypeById': function (_id) { var params = { 'id': _id }; RailtypeFactory.get(params, function (data) { self.selectedRailType = new RailtypeFactory(data); }); }, 'createRailType': function (railtypeItem) { var d = $q.defer(); self.isSaving = true; RailtypeFactory.save(railtypeItem).$promise.then(function () { self.isSaving = false; self.selectedRailType = null; self.hasMore = true; self.page = 1; self.list = []; self.doSearch(); ngToast.success({ content: 'ทำรายการสำเร็จ' }); d.resolve(); }, function (error) { ngToast.error({ content: error.message }); d.resolve(); }); return d.promise; }, 'updateRailType': function (railtypeItem) { var d = $q.defer(); self.isSaving = true; railtypeItem.$update() .then(function (data) { self.isSaving = false; ngToast.success({ content: 'อัพเดทรายการสำเร็จ' }); self.doSearch(); d.resolve(); }, function (error) { ngToast.error({ content: error.message }); d.resolve(); }); return d.promise; }, 'removeRailType': function (railtypeItem) { console.log(railtypeItem); var d = $q.defer(); self.isDeleting = true; railtypeItem.$remove().then(function () { ngToast.success({ content: 'ลบรายการสำเร็จ' }); self.isDeleting = false; var index = self.list.indexOf(railtypeItem); self.list.splice(index, 1); self.selectedRailType = null; d.resolve() }, function (error) { ngToast.error({ content: error.message }); d.resolve(); }); return d.promise; } }; self.loadRailtypes(); return self; }]);
#!/usr/bin/env node var dotenv = require('dotenv'); dotenv.load(); var fb = require('../app/firebatch'), summarize = require('../app/summarize.js'); fb.authenticate() .then(function() { return fb.run(process.env.BATCH_SIZE*1, summarize.item); } ) .then(function() { process.exit(0); }) .done();
'use strict'; describe('Controller: MainCtrl', function () { // load the controller's module beforeEach(module('binowPlayingApp')); var MainCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); MainCtrl = $controller('MainCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings.length).toBe(3); }); });
/** * 项目里的Controller基类 * 这里做一些通用的处理逻辑,其他Controller继承该类 * @param {[type]} * @return {[type]} [description] */ module.exports = Controller(function(){ 'use strict'; return { init: function(http){ var self= this; self.super("init", http); // var deferred = new Promise(sessionController(self, function(){ // sessionController(self, function(){ console.log('user base') // }) // return self.initComplete = deferred; }, } })
export function initialize(appInstance) { // appInstance.inject('route', 'foo', 'service:foo'); console.log(appInstance.lookup('service:service-ambienx')); let serviceAmbienx = appInstance.lookup('service:service-ambienx'); let newAmbienx = new Ambienx({ audioSrc: 'music.mp3', audioLoop: true, autoPlay: false, enabledLoseFocus: true }); serviceAmbienx.newAmbienx = newAmbienx; } export default { name: 'audio', initialize };
define(['./module'], function (services) { 'use strict'; /** * - addVoteToDbAndToCookie * - addCommentToDB * - deleteCommentFromDB * * * * */ services.factory('ActivityService', function ($http, ipCookie) { return{ addVoteToDbAndToCookie: function (problemID,userID,userName,userSurname) { return $http.post('/api/vote', {idProblem: problemID, userId: userID, userName: userName,userSurname:userSurname}) .success(function (data, status, headers, config) { ipCookie('vote' + problemID, true); }) .error(function (data, status, headers, config) { throw error; }); }, addCommentToDB:function(userID,userName,userSurname,problemID,comment,updateScope) { if(comment==""|| comment == undefined){ alert("Неможливо відправити пусте повідомлення"); return; } var data = {data: {userId: userID, userName: userName,userSurname:userSurname, Content: comment}}; return $http.post('/api/comment/' + problemID, JSON.stringify(data)) .success(function (data, status, headers, config) { updateScope(data); }) .error(function (data, status, headers, config) { throw error; }); }, deleteCommentFromDB:function(id){ return $http.delete('/api/activity/' + id) .success(function (data, status, headers, config) { }) .error(function (data, status, headers, config) { throw error; }); } } }); });
const express = require('express'), router = express.Router() router.all('*', function (req, res) { res.send('The database connection could not be made. All API routes are inactive.'); }) module.exports = router;
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict * @format */ 'use strict'; const RelayTestSchemaPath = require('./RelayTestSchemaPath'); const fs = require('fs'); const { GraphQLEnumType, GraphQLScalarType, GraphQLSchema, Kind, extendSchema, parse, } = require('graphql'); function buildSchema() { const CropPosition = new GraphQLEnumType({ name: 'CropPosition', values: { TOP: {value: 1}, CENTER: {value: 2}, BOTTOM: {value: 3}, LEFT: {value: 4}, RIGHT: {value: 5}, }, }); const FileExtension = new GraphQLEnumType({ name: 'FileExtension', values: { JPG: {value: 'jpg'}, PNG: {value: 'png'}, }, }); let schema = new GraphQLSchema({ types: [CropPosition, FileExtension, GraphQLJSONType], }); schema = extendSchema( schema, parse(fs.readFileSync(RelayTestSchemaPath, 'utf8')), ); // AST Builder doesn't allow things undefined in AST to be argument types it // seems return extendSchema( schema, parse(` input ProfilePictureOptions { newName: String } extend type User { profilePicture2( size: [Int], preset: PhotoSize cropPosition: CropPosition fileExtension: FileExtension additionalParameters: JSON options: ProfilePictureOptions ): Image } `), ); } function identity(value) { return value; } function parseLiteral(ast, variables) { switch (ast.kind) { case Kind.STRING: case Kind.BOOLEAN: return ast.value; case Kind.INT: case Kind.FLOAT: return parseFloat(ast.value); case Kind.OBJECT: { const value = Object.create(null); ast.fields.forEach(field => { value[field.name.value] = parseLiteral(field.value, variables); }); return value; } case Kind.LIST: return ast.values.map(n => parseLiteral(n, variables)); case Kind.NULL: return null; case Kind.VARIABLE: { const name = ast.name.value; return variables ? variables[name] : undefined; } default: return undefined; } } const GraphQLJSONType = new GraphQLScalarType({ name: 'JSON', description: 'The `JSON` scalar type represents JSON values as specified by ' + '[ECMA-404](http://www.ecma-international.org/' + 'publications/files/ECMA-ST/ECMA-404.pdf).', serialize: identity, parseValue: identity, parseLiteral, }); module.exports = (buildSchema(): GraphQLSchema);
var Q = require('q'); var events = require('events'); var util = require('util'); var debug = require('debug')('home-controller:insteon:iolinc'); function IOLinc(id, insteon) { this.id = id; this.insteon = insteon; this.emitOnAck = true; } util.inherits(IOLinc, events.EventEmitter); IOLinc.prototype.relayOn = function (next) { var id = this.id; return this.insteon.directCommand(id, '11', 'FF', next); }; IOLinc.prototype.relayOff = function (next) { var id = this.id; return this.insteon.directCommand(id, '13', next); }; IOLinc.prototype.status = function(next) { var insteon = this.insteon; var id = this.id; var deferred = Q.defer(); var stat = {}; deferred.resolve( insteon.directCommand(id, '19', '00') // Relay status .then(function (status) { if(!status || !status.response || !status.response.standard) { debug('No response for IO Linc Relay request for device %s', id); } else { var relayStatus = parseInt(status.response.standard.command2, 16); stat.relay = relayStatus === 0 ? 'off' : 'on'; } return insteon.directCommand(id, '19', '01'); // Sensor status }) .then(function (status) { if(!status || !status.response || !status.response.standard) { debug('No response for IO Linc Sensor request for device %s', id); } else { var sensorStatus = parseInt(status.response.standard.command2, 16); stat.sensor = sensorStatus === 0 ? 'off' : 'on'; } return stat; }) ); return deferred.promise.nodeify(next); }; IOLinc.prototype.handleAllLinkBroadcast = function (group, cmd1, cmd2) { debug('Emitting BC command for device (%s) - group: %s, cmd1: %s, cmd2: %s', this.id, group, cmd1, cmd2); this.emit('command', group, cmd1, cmd2); switch (cmd1 + group) { case '110': this.emit('relayOn', group); break; case '111': this.emit('sensorOn', group); break; case '130': this.emit('relayOff', group); break; case '131': this.emit('sensorOff', group); break; default: debug('No event for command - %s', cmd1); } }; IOLinc.prototype.handleAck = function (cmd1, cmd2) { if(!this.emitOnAck) { return; } debug('Emitting ACK command for device (%s) - cmd1: %s, cmd2: %s', this.id, cmd1, cmd2); this.emit('command', null, cmd1, cmd2); switch (cmd1) { case '11': // turnOn this.emit('relayOn'); break; case '13': // turnOff this.emit('relayOff'); break; default: debug('No event for command - %s', cmd1); } }; IOLinc.prototype.cancelPending = function() { this.insteon.cancelPending(this.id); }; module.exports = IOLinc;
define("view/tip", ["require", "exports", "module", "hbs!template/pop-tip"], function(require, exports) { exports.View = Backbone.View.extend({ className: "outer-tip", template: require("hbs!template/pop-tip"), events: { "click .action": "undoAction", "click .close": "_closeAction" }, initialize: function(e) { this.initData(e); this.beforeRender(); this.render(); this.autoClose() }, /** * @desc 将参数中的className转变成当前实例的attachClass,并将className删除掉 * */ initData: function(e) { if(e && e.className){ this.attachClass = e.className; e.className = null } _.extend(this, e); }, render: function() { var e = this.template({ text: this.text, actionText: this.action ? this.actionText : false, closeAction: this.closeAction ? true : false }); this.$el.html(e).appendTo($("body")).addClass(this.attachClass); this.setAnimation() }, /** * @desc 首先检测是否有其余的提示,有就删除 * */ beforeRender: function() { var hasOtherTip = this.hasOtherTip(); if(hasOtherTip){ $ot = $(".pop-tip"); $ot.addClass("fast-close-animation"); setTimeout(function() { $ot.parent().remove() }, 200); } }, hasOtherTip: function() { return $(".pop-tip").length ? true : false }, setAnimation: function() { var e = this; setTimeout(function() { e.$(".pop-tip").removeClass("before-animation") }) }, setCloseAnimation: function() { this.$(".pop-tip").addClass("before-animation") }, autoClose: function() { var e = this; this.delayTime = this.delayTime || 3e3; this.timer = setTimeout(function() { e.setCloseAnimation(), setTimeout(function() { e.onClose() }, 200) }, this.delayTime) }, undoAction: function() { this.action && this.action(), this.onClose() }, _closeAction: function() { this.closeAction && this.closeAction(), this.onClose() }, onClose: function() { _.isUndefined(this.timer) || clearTimeout(this.timer), this.remove() } }) })
function logMessage(number, message) { const lines = message.split(/\n/); console.error(`#${number} in ${lines[0].bold}`); console.error(lines.splice(1).map(line => `> ${line}`).join('\n')); console.log(''); } export default function(stats) { const info = stats.toJson(); if (stats.hasErrors()) { console.log(`${' ERROR '.bgRed.black}`); info.errors.forEach((message, index) => { logMessage(index + 1, message); }); } else if (stats.hasWarnings()) { console.log(`${' WARN '.bgYellow.black}`); info.warnings.forEach((message, index) => { logMessage(index + 1, message); }); } else { return true; } return false; }
var demo = demo || {}; demo.Controller = (function ($) { // HTML Imports support feature test var supportsHTMLImports = Boolean('import' in document.createElement('link')); // Test to see if the browser supports the HTML template element by checking // for the presence of the template element's content attribute. var supportsHTMLTemplate = Boolean('content' in document.createElement('template')); // history.replaceState support feature test var supportsHistoryReplaceState = Boolean('replaceState' in history); // Replace location hash without new history entry var replaceHash = function (newhash) { newhash = '#' + newhash.replace(/^#/, ''); // ensure hash starts with # if (supportsHistoryReplaceState) { history.replaceState('', '', newhash); // replace history entry } else { location.replace(newhash); // this works in all known browsers, even old IE } } var mainPage, mainPageId; var scanForHTMLImports = function () { // Use jQuery.load() if we don't have native HTML Imports support if (!supportsHTMLImports) { var imports = $('link[rel=import]'); for (var i = 0, len = imports.length; i < len; i++) { // Don't import already imported links if (imports[i].dataset.imported) { continue; } // Mark the import imports[i].dataset.imported = true; $('<template/>').appendTo(document.body).load( $(imports[i]).attr('href'), function (link, response, status, xhr) { if (link) { if (status === 'error') { if (link.onerror) { link.onerror({ target: link }); } } else { if (link.onload) { link.onload({ target: link }); } } } }.bind(this, imports[i]) ); } } }; var init = function (config) { // Always redirect to main page $(window).bind('hashchange', function () { var hash = location.hash.replace(/^#/, ''); if (hash === '') { replaceHash(mainPageId); } }); scanForHTMLImports(); }; var injectTemplate = function (options) { var callback = function (options) { // Use an empty page for main page placeholder // and prevent jQuery Mobile to inject a blank page if (!mainPage) { mainPage = $('div[data-main-page]'); mainPageId = mainPage.attr('data-main-page'); } var templateDoc = document; if (supportsHTMLImports) { // templateDoc refers to the "importee", which is template.html var templateDoc = options.context.ownerDocument; } // Grab the contents of the template from templateDoc // and append it to the importing document. var template = templateDoc.querySelector('template[data-template-id="' + options.templateId + '"]'); if (!template) { throw 'template with data-template-id="' + options.templateId + '"] not found'; } var component; // If the browser supports HTML Template, we have to import the page Element // otherwise we will get the HTML Element already injected by jQuery.load() if (supportsHTMLTemplate) { component = document.importNode(template.content, true); } else { component = template.querySelector('#' + options.templateId); // remove component from the DOM $(component).remove(); } // If component is main page, replace it, if not, append // component maybe DOM Element or DocumentFragment if (options.templateId === mainPageId) { mainPage.replaceWith(component); } else { $(document.body).append(component); } component = $('#' + options.templateId); // Get injected DOM Element if (!component.hasClass('ui-' + component.attr('data-role'))) { // If not already enhanced component[component.attr('data-role')](); // enhance ;) } // If this template is the main page, show it instantly if (options.templateId === mainPageId) { $.mobile.changePage(component, { transition: 'none', changeHash: false }); replaceHash(mainPageId); } }; // maybe we have to wait until the DOM is ready if (!document.body) { $(document).ready(function () { callback(options); }, false); } else { callback(options); } }; var reset = function () { mainPage = null; mainPageId = null; }; var public = { init: init, injectTemplate: injectTemplate, reset: reset }; return public; })(jQuery);
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var microphone = exports.microphone = { "viewBox": "0 0 24 24", "children": [{ "name": "path", "attribs": { "d": "M12 16c2.206 0 4-1.795 4-4v-6c0-2.206-1.794-4-4-4s-4 1.794-4 4v6c0 2.205 1.794 4 4 4zM19 12v-2c0-.552-.447-1-1-1s-1 .448-1 1v2c0 2.757-2.243 5-5 5s-5-2.243-5-5v-2c0-.552-.447-1-1-1s-1 .448-1 1v2c0 3.52 2.613 6.432 6 6.92v1.08h-3c-.553 0-1 .447-1 1s.447 1 1 1h8c.553 0 1-.447 1-1s-.447-1-1-1h-3v-1.08c3.387-.488 6-3.4 6-6.92z" }, "children": [] }] };
var assert = require("assert"); var dirLib = require("../Library/Dirs"); describe("Test01", function() { it ("Is 3 equal to 3", function() { assert.equal(3, 3); }); it ("so", function() { assert.equal(2, 2); }); it("Dirs", function() { }); });
// @flow import type { FloatPosition, FloatAlign } from '../components/floats'; import type { Choice } from '../gral/types'; // -- Props: // -- START_DOCS export type SelectProps = { // Both SelectCustom and SelectNative // ---------------------------------- className?: string, id?: string, type: SelectPickerType, // see below (default: 'native') // Items with the following attributes: // - **value** *any*: any value that can be converted to JSON. Values should be unique // - **label** *string*: descriptive string that will be shown to the user // - **keys** *array(string)?*: keyboard shortcuts for this option, e.g. // `mod+a` (= `cmd+a` in OS X, `ctrl+a` in Windows), `alt+backspace`, `shift+up`... // **Only supported in non-native Selects** items: Array<Choice>, lang?: string, // current language (used just for force-render). // Apart from its use for [validation](#input-validation), // enabling this flag disables the addition of a `null` option to the `items` list required?: boolean, disabled?: boolean, // SelectCustom only // ----------------- children?: any, onClickItem?: Function, onCloseFloat?: Function, floatPosition?: FloatPosition, floatAlign?: FloatAlign, // When enabled, two different visual styles are applied // to an item depending on whether it is just *hovered* or also *selected*. If disabled, // a single style is used to highlight the selected or the hovered item twoStageStyle?: boolean, }; export type SelectPickerType = 'native' | 'inlinePicker' | 'dropDownPicker'; // -- END_DOCS /* -- You can also include a separator between `items` by including the special `LIST_SEPARATOR` item (**only in non-native Selects**): ```js import { Select, LIST_SEPARATOR } from 'giu'; <Select required items={[ { value: 'apples', label: 'Apples', keys: 'alt+a' }, { value: 'cherries', label: 'Cherries', keys: ['alt+h', 'alt+e'] }, LIST_SEPARATOR, { value: 'peaches', label: 'Peaches', keys: 'alt+p' }, { value: 'blueberries', label: 'Blueberries', keys: 'alt+b' }, ]} /> ``` -- */
"use strict"; const getFirstIndex = require("../../lib/time/getFirstIndex"); describe("getFirstIndex", () => { it("should be exported", () => { expect(typeof getFirstIndex).toEqual("function"); }); it("expects a list as input", () => { let a; const doTest = () => { a = getFirstIndex(); }; expect(doTest).toThrowError(); expect(a).not.toBeDefined(); }); it("returns 0 on an empty list", () => { const a = getFirstIndex([]); expect(a).toBe(0); }); it("should return the index of the lowest value in a list", () => { const a = getFirstIndex([1, 2, 3, 4, 5]); const b = getFirstIndex([5, 1, 2, 3, 4]); const c = getFirstIndex([4, 5, 1, 2, 3]); const d = getFirstIndex([3, 4, 5, 1, 2]); const e = getFirstIndex([2, 3, 4, 5, 1]); expect(a).toBe(0); expect(b).toBe(1); expect(c).toBe(2); expect(d).toBe(3); expect(e).toBe(4); }); it("should return the lowest index when multiple values are the lowest", () => { const a = getFirstIndex([1, 1, 2, 2, 2]); const b = getFirstIndex([2, 1, 1, 1, 1]); const c = getFirstIndex([4, 5, 1, 1, 1]); const d = getFirstIndex([3, 4, 5, 1, 1]); const e = getFirstIndex([1, 1, 1, 1, 1]); expect(a).toBe(0); expect(b).toBe(1); expect(c).toBe(2); expect(d).toBe(3); expect(e).toBe(0); }); });
var hotController = require('../renderer/hot.js'); const {remote} = require('electron'); const {Menu, MenuItem} = remote; var menu = new Menu(); var rowAbove = new MenuItem({ label: 'Insert row above', click: function() { hotController.insertRowAbove(true); } }); var rowBelow = new MenuItem({ label: 'Insert row below', click: function() { hotController.insertRowBelow(true); } }); var columnLeft = new MenuItem({ label: 'Insert column left', click: function() { hotController.insertColumnLeft(true); } }); var columnRight = new MenuItem({ label: 'Insert column right', click: function() { hotController.insertColumnRight(true); } }); var removeRow = new MenuItem({ label: 'Remove row(s)', click: function() { hotController.removeRows(); } }); var removeCol = new MenuItem({ label: 'Remove column(s)', click: function() { hotController.removeColumns(); } }); var freezeRow = new MenuItem({ label: 'Freeze header row', click: function(){ hotController.freeze(); } }); var unfreezeRow = new MenuItem({ label: 'Unfreeze header row', click: function(){ hotController.unfreeze(); } }); menu.append(freezeRow); menu.append(unfreezeRow); menu.append(new MenuItem({ type: 'separator' })); menu.append(rowAbove); menu.append(rowBelow); menu.append(new MenuItem({ type: 'separator' })); menu.append(columnLeft); menu.append(columnRight); menu.append(new MenuItem({ type: 'separator' })); menu.append(removeRow); menu.append(removeCol);
(function($) { "use strict"; // Start of use strict // Configure tooltips for collapsed side navigation $('.navbar-sidenav [data-toggle="tooltip"]').tooltip({ template: '<div class="tooltip navbar-sidenav-tooltip" role="tooltip"><div class="arrow"></div><div class="tooltip-inner"></div></div>' }) // Toggle the side navigation $("#sidenavToggler").click(function(e) { e.preventDefault(); $("body").toggleClass("sidenav-toggle"); $(".navbar-sidenav .nav-link-collapse").addClass("collapsed"); $(".navbar-sidenav .sidenav-second-level, .navbar-sidenav .sidenav-third-level").removeClass("show"); }); // Force the toggled class to be removed when a collapsible nav link is clicked $(".navbar-sidenav .nav-link-collapse").click(function(e) { e.preventDefault(); $("body").removeClass("sidenav-toggled"); }); // Prevent the content wrapper from scrolling when the fixed side navigation hovered over $('body.fixed-nav .navbar-sidenav, body.fixed-nav .sidenav-toggler, body.fixed-nav .navbar-collapse').on('mousewheel DOMMouseScroll', function(e) { var e0 = e.originalEvent, delta = e0.wheelDelta || -e0.detail; this.scrollTop += (delta < 0 ? 1 : -1) * 30; e.preventDefault(); }); // Scroll to top button appear $(document).scroll(function() { var scrollDistance = $(this).scrollTop(); if (scrollDistance > 100) { $('.scroll-to-top').fadeIn(); } else { $('.scroll-to-top').fadeOut(); } }); // Configure tooltips globally $('[data-toggle="tooltip"]').tooltip() // Smooth scrolling using jQuery easing $(document).on('click', 'a.scroll-to-top', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: ($($anchor.attr('href')).offset().top) }, 1000, 'easeInOutExpo'); event.preventDefault(); }); // Call the dataTables jQuery plugin $(document).ready(function() { $('#dataTable').DataTable(); }); })(jQuery); // End of use strict // Chart.js scripts // -- Set new default font family and font color to mimic Bootstrap's default styling Chart.defaults.global.defaultFontFamily = '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif'; Chart.defaults.global.defaultFontColor = '#292b2c'; // -- Area Chart Example var ctx = document.getElementById("myAreaChart"); var myLineChart = new Chart(ctx, { type: 'line', data: { labels: ["Mar 1", "Mar 2", "Mar 3", "Mar 4", "Mar 5", "Mar 6", "Mar 7", "Mar 8", "Mar 9", "Mar 10", "Mar 11", "Mar 12", "Mar 13"], datasets: [{ label: "Sessions", lineTension: 0.3, backgroundColor: "rgba(2,117,216,0.2)", borderColor: "rgba(2,117,216,1)", pointRadius: 5, pointBackgroundColor: "rgba(2,117,216,1)", pointBorderColor: "rgba(255,255,255,0.8)", pointHoverRadius: 5, pointHoverBackgroundColor: "rgba(2,117,216,1)", pointHitRadius: 20, pointBorderWidth: 2, data: [10000, 30162, 26263, 18394, 18287, 28682, 31274, 33259, 25849, 24159, 32651, 31984, 38451], }], }, options: { scales: { xAxes: [{ time: { unit: 'date' }, gridLines: { display: false }, ticks: { maxTicksLimit: 7 } }], yAxes: [{ ticks: { min: 0, max: 40000, maxTicksLimit: 5 }, gridLines: { color: "rgba(0, 0, 0, .125)", } }], }, legend: { display: false } } }); // -- Bar Chart Example var ctx = document.getElementById("myBarChart"); var myLineChart = new Chart(ctx, { type: 'bar', data: { labels: ["January", "February", "March", "April", "May", "June"], datasets: [{ label: "Revenue", backgroundColor: "rgba(2,117,216,1)", borderColor: "rgba(2,117,216,1)", data: [4215, 5312, 6251, 7841, 9821, 14984], }], }, options: { scales: { xAxes: [{ time: { unit: 'month' }, gridLines: { display: false }, ticks: { maxTicksLimit: 6 } }], yAxes: [{ ticks: { min: 0, max: 15000, maxTicksLimit: 5 }, gridLines: { display: true } }], }, legend: { display: false } } }); // -- Pie Chart Example var ctx = document.getElementById("myPieChart"); var myPieChart = new Chart(ctx, { type: 'pie', data: { labels: ["Blue", "Red", "Yellow", "Green"], datasets: [{ data: [12.21, 15.58, 11.25, 8.32], backgroundColor: ['#007bff', '#dc3545', '#ffc107', '#28a745'], }], }, });
// inspired by https://github.com/commitizen/cz-cli/blob/master/src/configLoader/loader.js /** * The MIT License (MIT) * * Copyright 2013 Dulin Marat and other contributors * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * Command line config helpers */ import * as fs from 'fs'; import * as path from 'path'; import * as stripJSONComments from 'strip-json-comments'; import * as glob from 'glob'; // Configuration sources in priority order. var configs = ['package.json', '.codeweight', '.codeweight.json']; // Before, "findup-sync" package was used, // but it does not provide filter callback function findup(patterns, options, fn) { /* jshint -W083 */ var lastpath; var file; options = Object.create(options); options.maxDepth = 1; options.cwd = path.resolve(options.cwd); do { file = patterns.filter(function(pattern) { var configPath = glob.sync(pattern, options)[0]; if (configPath) { return fn(path.join(options.cwd, configPath)); } })[0]; if (file) { return path.join(options.cwd, file); } lastpath = options.cwd; options.cwd = path.resolve(options.cwd, '..'); } while (options.cwd !== lastpath); } function getNormalizedConfig(config, content) { if (content && (config == 'package.json')) { // PACKAGE.JSON // use npm config key if (content.config && content.config.codeweight) { return content.config.codeweight; } } else { // .checksize or .checksize.json return content; } } /** * Get content of the configuration file. * * @param {String} config - partial path to configuration file * @param {String} directory - directory path which will be joined with config argument * @return {Object} */ function getContent(config, directory) { if (!config) { return; } var configPath = path.resolve(directory, config); var ext; var content; config = path.basename(config); if (fs.existsSync(configPath)) { ext = path.extname(configPath); if (ext === '.js' || ext === '.json') { content = JSON.parse(fs.readFileSync(configPath, 'utf8')); } else { content = JSON.parse( stripJSONComments( fs.readFileSync(configPath, 'utf8') ) ); } // Adding property via Object.defineProperty makes it // non-enumerable and avoids warning for unsupported rules Object.defineProperty(content, 'configPath', { value: configPath }); } return getNormalizedConfig(config, content); } /** * Get content of the configuration file. * * @param {String} config - partial path to configuration file * @return {Object|undefined} */ export default function load(config) { var content; var directory = process.cwd(); // If config option is given, attempt to load it if (config) { return getContent(config, directory); } content = getContent( findup(configs, { nocase: true, cwd: directory }, function(configPath) { if (path.basename(configPath) === 'package.json') { // return !!getContent(configPath); } return true; }) ); if (content) { return content; } // Try to load standard configs from home dir var directoryArr = [process.env.USERPROFILE, process.env.HOMEPATH, process.env.HOME]; for (var i = 0, dirLen = directoryArr.length; i < dirLen; i++) { if (!directoryArr[i]) { continue; } for (var j = 0, len = configs.length; j < len; j++) { content = getContent(configs[j], directoryArr[i]); if (content) { return content; } } } }
import React, { Component } from 'react' import Alert from '../../src/components/Alert' class AlertDemo extends Component { render() { return( <div> <Alert type="warning"> <h4>Heading</h4> <strong>Error:</strong> You need to take action, something has gone terribly wrong! </Alert> </div> ) } } module.exports = AlertDemo
// MODULES // var // Expectation library: chai = require( 'chai' ), // Module to be tested: plugin = require( './../lib' ); // VARIABLES // var expect = chai.expect, assert = chai.assert; // TESTS // describe( 'monitor-os-plugin', function tests() { 'use strict'; // SETUP // var monitor; beforeEach( function() { monitor = {}; }); // TESTS // it( 'should export a function', function test() { expect( plugin ).to.be.a( 'function' ); }); it( 'should have an arity of 2', function test() { assert.strictEqual( plugin.length, 2 ); }); it( 'should append to the monitor object', function test( done ) { plugin( monitor, next ); function next() { expect( monitor.system ).to.be.an( 'object' ); done(); } }); });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = undefined; var _jsx2 = require('babel-runtime/helpers/jsx'); var _jsx3 = _interopRequireDefault(_jsx2); 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; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _base = require('../utils/base'); var _radium = require('radium'); var _radium2 = _interopRequireDefault(_radium); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Cite = (0, _radium2.default)(_class = function (_Component) { (0, _inherits3.default)(Cite, _Component); function Cite() { (0, _classCallCheck3.default)(this, Cite); return (0, _possibleConstructorReturn3.default)(this, _Component.apply(this, arguments)); } Cite.prototype.render = function render() { var typefaceStyle = this.context.typeface || {}; return (0, _jsx3.default)('cite', { className: this.props.className, style: [this.context.styles.components.cite, _base.getStyles.call(this), this.props.style, typefaceStyle] }, void 0, '- ', this.props.children); }; return Cite; }(_react.Component)) || _class; exports.default = Cite; Cite.contextTypes = { styles: _propTypes2.default.object, store: _propTypes2.default.object, typeface: _propTypes2.default.object };
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' import { Message } from 'shengnian-ui-react' const HeaderVariationsExamples = () => ( <ExampleSection title='Variations'> <ComponentExample title='Dividing' description='A header can be formatted to divide itself from the content below it.' examplePath='elements/Header/Variations/HeaderExampleDividing' /> <ComponentExample title='Block' description='A header can be formatted to appear inside a content block.' examplePath='elements/Header/Variations/HeaderExampleBlock' /> <ComponentExample title='Attached' description='A header can be attached to other content, like a segment.' examplePath='elements/Header/Variations/HeaderExampleAttached' /> <ComponentExample title='Floating' description='A header can sit to the left or right of other content.' examplePath='elements/Header/Variations/HeaderExampleFloating' /> <ComponentExample title='Text Alignment' description='A header can have its text aligned to a side.' examplePath='elements/Header/Variations/HeaderExampleTextAlignment' /> <ComponentExample title='Colored' description='A header can be formatted with different colors.' examplePath='elements/Header/Variations/HeaderExampleColored' /> <ComponentExample title='Inverted' description='A header can have its colors inverted for contrast.' examplePath='elements/Header/Variations/HeaderExampleInverted' > <Message warning> Inverted headers use modified light versions of the site color scheme. </Message> </ComponentExample> </ExampleSection> ) export default HeaderVariationsExamples
lucid.ruleset = { 'form':{}, 'handlers':{}, 'mode':'single-list', 'formAlert':'<div class="alert alert-danger clearfix" id=":id" style="display:none;"><strong>Form Errors</strong><p>test</p></div>' }; /* START COMPAT FUNCTIONS: These functions allows the exact same php code to run as javascript */ function strlen(str){ return strval(str).length; } function strval(str){ return String(str); } /* END COMPAT FUNCTIONS */ lucid.ruleset.add=function(name,rules){ lucid.ruleset.form[name] = rules; }; lucid.ruleset.process=function(name, data){ if(typeof(lucid.ruleset.form[name]) == 'object'){ var errorList = {}; var errorCount = 0; var rules = lucid.ruleset.form[name]; for(var i=0; i < rules.length; i++){ if(typeof(lucid.ruleset.handlers[rules[i].type]) == 'function'){ if( lucid.ruleset.handlers[rules[i].type](rules[i],data) === false){ if(typeof(errorList[rules[i]['label']]) != 'object'){ errorList[rules[i]['label']] = []; } errorList[rules[i]['label']].push(rules[i].message); errorCount++; } }else{ console.log('Unknown validation rule: ' + rules[i].type); } } if(errorCount > 0){ lucid.ruleset.showErrors(name, errorList); return false; } return true; }else{ console.log('no rules found'); return true; } } lucid.ruleset.showErrors=function(name,errors){ var form = document.forms[name]; var data = lucid.getFormValues(form); var formErrorId = window.jQuery(form).attr('name')+'-errors'; if (jQuery('#'+formErrorId).length ==0){ jQuery(form).prepend(lucid.ruleset.formAlert.replace(':id',formErrorId)); } jQuery('#'+formErrorId +' > p').html(lucid.ruleset.buildErrorHtml(errors)); jQuery('#'+formErrorId).fadeIn(300); }; lucid.ruleset.clearErrors=function(form){ var formErrorId = jQuery(form).attr('name')+'-errors'; var errorArea = jQuery('#'+formErrorId); if (errorArea){ errorArea.hide(); } }; lucid.ruleset.buildErrorHtml =function(errors){ if(lucid.ruleset.mode == 'single-categorized'){ var html = '<dl class="dl-horizontal">'; for(var field in errors){ html += '<dt class="col-sm-3">' + field + '</dt>'; for(var i=0; i<errors[field].length; i++){ html += '<dd class="col-sm-9' +((i == 0)?'':' col-sm-offset-3')+ '">'; html += errors[field][i] + '</dd>'; } } html += '</dl>'; } if(lucid.ruleset.mode == 'single-list') { var html = '<ul class="list-unstyled">'; for(var field in errors){ for(var i=0; i<errors[field].length; i++){ html += '<li>'+errors[field][i]+'</li>'; } } html += '</ul>'; } return html; } lucid.ruleset.handlers.lengthRange = function($rule, $data){ $rule.last_value = strval($data[$rule.field]); return (strlen($rule['last_value']) >= $rule['min'] && strlen($rule['last_value']) < $rule['max']); }; lucid.ruleset.handlers.integerValue = function($rule, $data){ $rule.last_value = parseInt($data[$rule.field]); if(isNaN($rule.last_value)){ return false; } return true; }; lucid.ruleset.handlers.integerValueMin = function($rule, $data){ $rule.last_value = parseInt($data[$rule.field]); if(isNaN($rule.last_value)){ return false; } if('min' in $rule && $rule.last_value < $rule.min){ return false; } return true; }; lucid.ruleset.handlers.integerValueMax = function($rule, $data){ $rule.last_value = parseInt($data[$rule.field]); if(isNaN($rule.last_value)){ return false; } if('max' in $rule && $rule.last_value > $rule.max){ return false; } return true; }; lucid.ruleset.handlers.integerValueMinMax = function($rule, $data){ $rule.last_value = parseInt($data[$rule.field]); if(isNaN($rule.last_value)){ return false; } if('min' in $rule && $rule.last_value < $rule.min){ return false; } if('max' in $rule && $rule.last_value > $rule.max){ return false; } return true; }; lucid.ruleset.handlers.checked = function($rule, $data){ $rule.last_value = $data[$rule.field]; return ($rule.last_value === true); }; lucid.ruleset.handlers.anyValue = function($rule, $data){ $rule.last_value = strval($data[$rule.field]); return ($rule.last_value !== '' && $rule.last_value+'' != 'undefined'); }; lucid.ruleset.handlers.floatValue = function($rule, $data){ $rule.last_value = parseInt($data[$rule.field]); if(isNaN($rule.last_value)){ return false; } return true; }; lucid.ruleset.handlers.validDate = function($rule, $data){ console.log('validDate rule not implemented yet :('); return true; };
// ChopJS scope database BDD test // ================================ /* jshint multistr:true */ /* global describe, it, chai, $ch */ // Make a shorthand for chai.expect. var expect = chai.expect; // Testing body // ----------- describe('ChopJS Scope Module', function () { 'use strict'; it('should retrieve all ch-scope and ch-name annotations from DOM.', function () { var info = 'ChopJS'; var details = 'Scope module'; $ch.scope('information', function ($$) { expect($$.message.content()).to.equal(info); }); $ch.scope('footer-information', function ($$) { expect($$.details.content()).to.equal(details); }); }); it('should support data placeholder.', function () { var msg = 'This is a scope-data.'; var scp; $ch.scope('myScope', function($$) { scp = $$; $$.message.set(msg); }); expect($ch.find('#my-scope-message').content()).to.equal(msg); }); it('should allow nested scopes.', function () { $ch.scope('Main', function ($$) { $$.timeOfDay.set('morning'); $$.name.set('Nikki'); }); $ch.scope('Child', function ($$) { $$.timeOfDay.set('afternoon'); $$.name.set('Mattie'); }); $ch.scope('GrandChild', function ($$) { $$.timeOfDay.set('evening'); $$.name.set('Gingerbread Baby'); }); var main = $ch.scope('Main').msg.content(); var child = $ch.scope('Child').msg.content(); var grandchild = $ch.scope('GrandChild').msg.content(); expect(main).to.not.equal(child); expect(main).to.not.equal(grandchild); expect(child).to.not.equal(grandchild); }); it('should support ch-data binding.', function () { var name = 'ChopJS'; $ch.scope('bindingScope', function ($$) { $$.username.set(name); }); $ch.scope('nestedbindingScope', function ($$) { $$.username.set('Nested'); }); }); it('should support events pub/sub.', function () { var eventName = 'update'; var data1 = 100; var data2 = 'Hello world'; $ch.scope('eventScope', function ($scope, $event) { $scope.message.set('Event Scope'); $event.listen(eventName, function (time, msg) { console.log(time, msg); expect(time).to.equal(data1); expect(msg).to.equal(data2); }); $event.emit(eventName, data1, data2); }); }); it('should handle events in nested scopes.', function () { var eventName = 'update'; var data1 = 100100; var data2 = 'Hello nested world'; $ch.scope('nestedEventScope', function ($scope, $event) { $scope.message.set('Nested Event Scope'); $event.listen(eventName, function (time, msg) { console.log(time, msg); expect(time).to.equal(data1); expect(msg).to.equal(data2); }); $event.emit(eventName, data1, data2); }); }); it('should support object property ch-data placeholder.', function () { var person = { firstname: 'Bruce', lastname: 'Wayne', product: { batwing: { speed: 'fast' }, chopjs: { 'test-mode': 'BDD', version: 'Edge' } } }; $ch.scope('objScope', function ($scope) { $scope.person.set(person); expect($scope.first.content()).to.equal(person.firstname); expect($scope.last.content()).to.equal(person.lastname); expect($scope.ver.content()).to.equal(person.product.chopjs.version); }); }); it('should load scopes from updated HTML.', function () { $ch.scope('loadScope', function ($scope) { var load = function () { $ch.scope('dataScope', function (scp) { scp.data.set({ name: 'ChopJS', author: 'ChopJS Author' }); }); }; $scope.template = $ch.find('#template').html(); $scope.loadBtn.on('click', function () { $scope.container.html($scope.template); load(); }); }); }); // $ch.scope // --------- describe('$ch.scope', function () { it('should define and retrieve ChopJS scopes.', function () { var scopeName = 'mochaTest'; var message = 'Mocha BDD'; // Use `$ch.scope(name, callback)` to define a scope. $ch.scope(scopeName, function (scp) { scp.name = message; scp.getName = function () { return scp.name; }; }); // Now use `$ch.scope(name)` to retrieve a scope. var scope = $ch.scope(scopeName); expect(scope.getName()).to.equal(message); }); }); });
'use strict' function index (req, res) { res.render('index', { title: 'welcome to jemo\'s page' }) } module.exports = { index: index }
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Annonce Schema */ var AnnonceSchema = new Schema({ idbuilding: { type: String, required: '', trim: true }, name: { type: String, required: '', trim: true }, surface: { type: Number, required: '', trim: true }, prix: { type: Number, required: '', trim: true }, nombre: { type: Number, required: '', trim: true }, email: { type: String, required: '', trim: true }, contact: { type: String, required: '', trim: true }, info: { type: String, required: '', trim: true }, created: { type: Date, default: Date.now }, user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('Annonce', AnnonceSchema);
/* *初始化部分页面数据 */ var viewHeight;//浏览器窗口可视高度 var viewWidth;//浏览器窗口可视宽度 var pageHeight;//文档页面高度 var pageWidth;//文档页面宽度 $(document).ready(function () { // DOM绘制完毕即开始运行,不等到,图片,文字的元素的加载 //window是在所有元素均加载完成后才开始运行,注意区别 //alert(viewWidth+'/'+viewHeight+'/'+pageWidth+'/'+pageHeight) }) window.onload = function(){ //window是在所有元素均加载完成后才开始运行,注意区别 //延迟加载,用于处理部分因DOM加载耗时较长引起的BUG var t_load = setTimeout(function(){ //刷新部分全局数据 getValue(); //进行页面调整 pageAdjust(); },300);//delayTime } $(window).resize(function(){ //刷新部分全局数据 getValue(); //进行页面调整 pageAdjust(); }) function getValue() { /*全局变量 * 浏览器窗口可视高度 */ viewHeight = $(window).height(); /*全局变量 * 浏览器窗口可视宽度 */ viewWidth = $(window).width(); //获取部分全局变量 /*全局变量 * 文档高度 */ pageHeight = $(document).height(); /*全局变量 * 文档宽度 */ pageWidth = $(document).width(); } function pageAdjust() { //页面样式的调整 //在初始化和页面尺寸变化时,从getValue()调用 /* *nav_list的调整 */ var width_header_menu_list = $('#header').width() - 416; $('#header_menu_list').width(width_header_menu_list); var left_header_menu_list = (width_header_menu_list*0.28-12)/2+208; $('#header_menu_list').css('marginLeft', left_header_menu_list); //section_button_list位置调整 console.log(viewHeight/2-50) $("#section_button").css('top', viewHeight/2-50 + "px"); for (var i = 0; i <6; i++) { $('.header_detail_container').eq(i).css('left', 1000*i+'px'); } //调整背景 $('#bg').height(viewHeight); $('.bg').height(viewHeight); } /* *header_nav_list上移动menu_detail移动特效 * */ (function(){ var open_status = false;//true表示打开状态 var run_status =false;//动画运行状态,true表示正在运行 var run1_status = false;//nav的动画状态 $('.header_menu_list').on('mouseenter',function(){ /*移动到header_nav_list上时, *先判断menu_detail有没有打开,如果打开就直接进行左右切换,如果没有打开则先进行左右切换再打开 * */ if(open_status) { //打开状态 if(!run_status) { run_status = true;//正在运行 var index = $(this).index(); $('#header_menu_details_mask').animate({ left: -1000*index+'px'}, 300,function(){ run_status = false;//结束运行状态 }) } } else { //关闭状态 var index = $(this).index(); $('#header_menu_details_mask').css('left', -1000*index+'px'); if(!run1_status) { $('#header_menu_details').slideDown(); run1_status = true; //打开完毕,标记状态 open_status = true; } } }) $('#header_nav').on('mouseleave',function(){ //鼠标离开nav区域,关闭header_menu_details $('#header_menu_details').slideUp(300,function(){ run1_status = false; }); //关闭完毕,标记状态 open_status = false; }) })();//不会自动提升 /* *搜索框效果 * */ $('#header_search_text').on('focus',function(){ $(this).css('color', 'black'); var value = $(this).val(); console.log(value); if( value == '输入搜索内容') { $(this).val(''); } }).on('blur',function(){ $(this).css('color', '#8e8e8e'); var value = $(this).val(); if( value == '') { $(this).val('输入搜索内容'); } }) /* *背景切换 */ var val = { fa_id:"bg", son_class:"bg", speed:7000, interval:10000, }; banner(val); function banner(opts) { //输入值为父级的ID以及最大子元素的类名 console.log(opts); console.log(opts.fa_id); var banner = document.getElementById(opts.fa_id);//获取当前banner的对象 var banner_img = $("#"+opts.fa_id).children("."+opts.son_class);//获取所有子元素的对象 var img_num = banner_img.length;//获取当前banner的图片张数 var speed = opts.speed;//渐变持续时间,单位:毫秒 var interval = opts.interval;//间隔时间 var currentImg = 0;//当前显示的图片,初始化时保留显示第一张图片。 init();//调用初始化函数; function init() { //初始化 console.log(img_num); //部分变量默认值初始化 if(!speed){speed = 1000; console.log(speed);} if(!interval){interval = 3000; console.log(interval);} if(speed<50){speed = 50; alert("速度时间间隔不得小于50ms");} if(speed>interval){interval = 2*speed;alert('变化时间不得大于变化间隔');} for(i=1; i<img_num;i++) { //隐藏多余的图片 banner_img.eq(i).hide(); } t1 = setTimeout(function(){picChange();},3000); } function picChange() { //自动轮换 banner_img.eq(currentImg).fadeOut(speed); banner_img.eq((currentImg + 1)%img_num).fadeIn(speed); currentImg = (currentImg + 1)%img_num; t2 = setTimeout(function(){picChange();},interval); } }
/** * @author a.demeshko * created on 28.12.2015 */ (function () { 'use strict'; angular.module('BrainPal.pages.components.mail') .controller('MailDetailCtrl', MailDetailCtrl); /** @ngInject */ function MailDetailCtrl($stateParams, mailMessages) { var vm = this; vm.mail = mailMessages.getMessageById($stateParams.id); vm.label = $stateParams.label; } })();
const assert = require('assert'); const feathers = require('@feathersjs/feathers'); const { join } = require('path'); const plugin = require('../lib'); describe('@feathersjs/configuration', () => { const app = feathers().configure(plugin()); it('exports default', () => assert.equal(plugin, plugin.default) ); it('initialized app with default data', () => assert.equal(app.get('port'), 3030) ); it('initialized with <env>', () => assert.equal(app.get('from'), 'testing') ); it('initialized with <env> derived data module', () => assert.equal(app.get('derived'), 'Hello World') ); it('initialized property with environment variable', () => assert.equal(app.get('environment'), 'testing') ); it('initialized property with environment variable from <env>', () => assert.equal(app.get('testEnvironment'), 'testing') ); it('initialized property with derived environment variable from <env> module', () => assert.equal(app.get('derivedEnvironment'), 'testing') ); it('uses an escape character', () => assert.equal(app.get('unescaped'), 'NODE_ENV') ); it('normalizes relative path names', () => assert.equal(app.get('path'), join(__dirname, 'something')) ); it('converts environment variables recursively', () => assert.equal(app.get('deeply').nested.env, 'testing') ); it('converts arrays as actual arrays', () => assert.ok(Array.isArray(app.get('array'))) ); it('works when called directly', () => { const fn = plugin(); assert.equal(fn().port, '3030'); }); it('deep merges properties', () => assert.deepEqual(app.get('deep'), { base: false, merge: true }) ); it('supports null value', () => { assert.strictEqual(app.get('nullish'), null); }); });
/* AbsolutelySuperList version 0.1. http://github.com/AvocadoCorp/absolutely-super-list (c) 2012 Avocado Software, Inc. AbsolutelySuperList is freely distributable under the MIT license. */ (function(){function c(a){if(1<a.length||!a.is("ol")&&!a.is("ul"))throw"Selector should only contain one <ul> or <ol>.";this.$list=a;a=a[0];a.style.position="relative";$.browser.webkit&&!/chrome/i.test(window.navigator.userAgent)&&(a.style.WebkitPerspective="1000",a.style.WebkitBackfaceVisibility="hidden");this.$list.delegate(h,c.SUPER_LIST_RESIZED_EVENT,g(this.onChildListResized_,this));this.$list.delegate(n,"mousedown",g(this.onDraggableMousedown_,this));this.reload()}var h=".absolutely-super-item", n=".absolutely-super-draggable",f=function(){};$.browser.webkit?f=function(a,b){a.style.WebkitTransition=b}:$.browser.mozilla?f=function(a,b){a.style.MozTransition=b}:$.browser.msie&&10<=parseInt($.browser.version,10)&&(f=function(a,b){a.style.msTransition=b});var g=function(a,b){return function(){return a.apply(b,arguments)}},j=function(a){if(a.is(h))return a;var b=$('<div class="absolutely-super-item"/>');b.insertBefore(a);a.appendTo(b);a=b[0];a.style.position="absolute";a.style.left="0px";a.style.right= "0px";a.style.overflow="hidden";return b},k=function(a){var b=a[0],e=b.style.height;e&&(f(b,"top 0.2s ease"),b.style.height="");var d=a.height();e?(b.style.height=e,setTimeout(function(){f(b,"top 0.2s ease, height 0.2s ease");b.style.height=d+"px"},0)):(b.style.height=d+"px",setTimeout(function(){f(b,"top 0.2s ease, height 0.2s ease")},0));return d};c.ITEM_DRAGGED_EVENT="absolutely-super-dragged";c.SUPER_LIST_RESIZED_EVENT="super-list-resized";c.prototype.getItemPositions_=function(){var a=0,b=[]; this.$list.children().each(function(e,d){var c=$(d);c.find(".absolutely-super-drag-boundary").length?b.push(NaN):b.push(a);a+=c.data("height")});return b};c.prototype.onDraggableMousedown_=function(a){a.preventDefault();a.stopPropagation();var b=$(a.currentTarget).closest(h);this.$list.addClass("absolutely-super-dragging");b.children().addClass("absolutely-super-dragging-item");var e=b[0];e.style.zIndex="100000";e.style.overflow="visible";f(e,"height 0.2s ease");b.data("dragging",!0);var e=b.index(), d=b.position().top,c=this.getItemPositions_();this.dragInfo_={item:b,boundDrag:g(this.onDrag_,this),boundMouseup:g(this.onDraggableMouseup_,this),currentTop:d,offsetY:a.pageY-d,startIndex:e,currentIndex:e,boundaries:c};$(document.body).bind("mousemove",this.dragInfo_.boundDrag).bind("mouseup",this.dragInfo_.boundMouseup)};c.prototype.onDrag_=function(a){var b=a.pageY-this.dragInfo_.offsetY;this.dragInfo_.item[0].style.top=b+"px";for(var a=this.dragInfo_.boundaries,e=this.dragInfo_.currentIndex,d= 0,c=e+1,f=a.length;!isNaN(a[c])&&c<f&&b>a[c];c++)d++;for(c=e-1;!isNaN(a[c])&&0<=c&&b<a[c];c--)d--;0!=d&&(b=e+d,this.moveItem(e,b),this.dragInfo_.currentIndex=b,this.dragInfo_.currentTop=a[b],this.dragInfo_.boundaries=this.getItemPositions_())};c.prototype.onDraggableMouseup_=function(){$(document.body).unbind("mousemove",this.dragInfo_.boundDrag).unbind("mouseup",this.dragInfo_.boundMouseup);var a=this.dragInfo_.item,b=this.dragInfo_.startIndex,e=this.dragInfo_.currentIndex;delete this.dragInfo_; this.$list.removeClass("absolutely-super-dragging");a.children().removeClass("absolutely-super-dragging-item");a.data("dragging",null);var d=a[0];f(d,"top 0.2s ease, height 0.2s ease");d.style.overflow="hidden";setTimeout(function(){d.style.zIndex=""},250);this.repositionElements_();b!=e&&this.$list.trigger(c.ITEM_DRAGGED_EVENT,[b,e])};c.prototype.onChildListResized_=function(a,b){var e=$(a.currentTarget),d=e.data("height")-b;e.data("height",d);e[0].style.height=d+"px";this.repositionElements_()}; c.prototype.reload=function(){for(var a=this.$list.children(),b=0,e=a.length;b<e;b++){var d=a.eq(b),d=j(d),c=k(d);d.data("height",c)}this.repositionElements_()};c.prototype.repositionElements_=function(){for(var a=0,b=this.$list.children(),e=0;e<b.length;e++){var d=b.eq(e);d.data("dragging")||(d[0].style.top=a+"px");a+=d.data("height")}this.$list[0].style.height=a+"px";b=parseInt(this.$list.data("height"),10);!isNaN(b)&&b!=a&&this.$list.parent().trigger(c.SUPER_LIST_RESIZED_EVENT,b-a);this.$list.data("height", a)};c.prototype.length=function(){return this.$list.children().length};c.prototype.isEmpty=function(){return 0==this.length()};c.prototype.html=function(a){this.$list.html(a);this.reload()};c.prototype.insertAtIndex=function(a,b){var c=j($(a)),d=this.$list.children().eq(b);d.length?c.insertBefore(d):c.appendTo(this.$list);this.reload()};c.prototype.indexBySelector=function(a){return this.find(a).closest(h).index()};c.prototype.removeAtIndex=function(a){this.$list.children().eq(a).remove();this.repositionElements_()}; c.prototype.removeBySelector=function(a){this.removeAtIndex(this.indexBySelector(a))};c.prototype.moveItem=function(a,b){var c=this.$list.children(),d=c.length;a==b||(a>=d||b>=d)||(d=c.eq(a),c=c.eq(b),d.detach(),a>b?d.insertBefore(c):d.insertAfter(c),setTimeout(g(function(){this.repositionElements_()},this),50))};c.prototype.sort=function(a){for(var b=this.$list.children(),c=b.length,d=[],f=0;f<c;f++)d.push(b.eq(f).children());d.sort(a||function(a,b){return a.text().localeCompare(b.text())});for(f= 0;f<c;f++)a=d[f].parent(),a.detach(),a.appendTo(this.$list);setTimeout(g(function(){this.repositionElements_()},this),50)};c.prototype.refreshAtIndex=function(a){var a=this.$list.children().eq(a),b=k(a);a.data("height")!=b&&(a.data("height",b),this.repositionElements_())};c.prototype.refreshBySelector=function(a){this.refreshAtIndex(this.indexBySelector(a))};for(var l="empty addClass removeClass toggleClass find bind unbind delegate".split(" "),i=0;i<l.length;i++){var m=l[i];c.prototype[m]=function(a){return function(){return this.$list[a].apply(this.$list, arguments)}}(m)}window.require&&window.define?define([],function(){return c}):window.AbsolutelySuperList=c})();
import React, { Component } from 'react' import styles from './TeamLogo.scss' export default class TeamLogo extends Component { render() { return ( <div> <span className={styles.logo}></span> <h2>Rasensprenger</h2> </div> ) } }
'use strict'; var assert = require('assert'), makeService = require('../make_service'), constants = require('../constants'); var Tilestats = module.exports = makeService('MapboxTilestats'); /** * To create an empty set of tileset statistics. * * @private * @param {String} tileset - the id for the tileset * @param {Array<string>} layers - an array of layer names in the tileset * @param {Function} callback called with (err, tilestats) * @returns {undefined} nothing, calls callback */ Tilestats.prototype.createTilestats = function(tileset, layers, callback) { assert(typeof tileset === 'string', 'tileset must be a string'); assert(typeof callback === 'function', 'callback must be a function'); assert(Array.isArray(layers), 'layers must be an array'); assert(layers.every(function(layer) { return typeof layer === 'string'; }), 'layers must be an array of strings'); var owner = tileset.split('.')[0]; if (owner === tileset) owner = this.owner; this.client({ path: constants.API_TILESTATS_STATISTICS, params: { owner: owner, tileset: tileset }, entity: { layers: layers }, method: 'post', callback: callback }); }; /** * To delete a set of tileset statistics. * * @private * @param {String} tileset - the id for the tileset * @param {Function} callback called with (err) * @returns {undefined} nothing, calls callback */ Tilestats.prototype.deleteTilestats = function(tileset, callback) { assert(typeof tileset === 'string', 'tileset must be a string'); assert(typeof callback === 'function', 'callback must be a function'); var owner = tileset.split('.')[0]; if (owner === tileset) owner = this.owner; this.client({ path: constants.API_TILESTATS_STATISTICS, params: { owner: owner, tileset: tileset }, method: 'delete', callback: callback }); }; /** * To retrieve statistics about a specific tileset. * * @param {String} tileset - the id for the tileset * @param {Function} callback called with (err, tilestats) * @returns {undefined} nothing, calls callback * @example * var client = new MapboxClient('ACCESSTOKEN'); * client.getTilestats('tileset-id', function(err, info) { * console.log(info); * // { * // "account": {account}, * // "tilesetid": "tileset-id", * // "layers": [ * // { * // "account": {account}, * // "tilesetid": "tileset-id", * // "layer": {layername}, * // "count": 10, * // "attributes": [ * // { * // "attribute": {attributename}, * // "min": 0, * // "max": 10, * // "values": [0, 10] * // } * // ] * // } * // ] * // } * }); */ Tilestats.prototype.getTilestats = function(tileset, callback) { assert(typeof tileset === 'string', 'tileset must be a string'); assert(typeof callback === 'function', 'callback must be a function'); var owner = tileset.split('.')[0]; if (owner === tileset) owner = this.owner; this.client({ path: constants.API_TILESTATS_STATISTICS, params: { owner: owner, tileset: tileset }, callback: callback }); }; /** * Add or update information about geometry types present in a tileset layer. * This request may be made multiple times against a single layer, in order to * update the total geometry counts across a set of parallel tileset reads. * * @private * @param {String} tileset - the id for the tileset * @param {String} layer - the name of the layer in the tileset * @param {Object} geometries - an object indicating the number of features present * in the layer of various geometry types. * @param {Number} [geometries.point] - number of Point features * @param {Number} [geometries.multipoint] - number of MultiPoint features * @param {Number} [geometries.linestring] - number of LineString features * @param {Number} [geometries.multilinestring] - number of MultiLineString features * @param {Number} [geometries.polygon] - number of Polygon features * @param {Number} [geometries.multipolygon] - number of MultiPolygon features * @param {Number} [geometries.geometrycollection] - number of GeometryCollection features * @param {Function} callback called with (err) * @returns {undefined} nothing, calls callback */ Tilestats.prototype.updateTilestatsLayer = function(tileset, layer, geometries, callback) { assert(typeof tileset === 'string', 'tileset must be a string'); assert(typeof callback === 'function', 'callback must be a function'); assert(typeof layer === 'string', 'layer must be a string'); assert(typeof geometries === 'object', 'geometries must be an object'); var owner = tileset.split('.')[0]; if (owner === tileset) owner = this.owner; this.client({ path: constants.API_TILESTATS_LAYER, params: { owner: owner, tileset: tileset, layer: layer }, entity: geometries, method: 'post', callback: callback }); }; /** * To add or update statistics about the values of a particular attribute in * a layer. This request may be made multiple times against a single attribute, * in order to update the statistics across a set of parallel tileset reads. * * @private * @param {String} tileset - the id for the tileset * @param {String} layer - the name of the layer in the tileset * @param {String} attribute - the name of the attribute in the layer * @param {Object} stats - statistics about attribute values in the layer * @param {Number|String} stats.min - the minimum attribute value * @param {Number|String} stats.max - the maximum attribute value * @param {Array<Number|String>} stats.values - an array of unique values for the attribute * @param {Function} callback called with (err) * @returns {undefined} nothing, calls callback */ Tilestats.prototype.updateTilestatsAttribute = function(tileset, layer, attribute, stats, callback) { assert(typeof tileset === 'string', 'tileset must be a string'); assert(typeof callback === 'function', 'callback must be a function'); assert(typeof layer === 'string', 'layer must be a string'); assert(typeof attribute === 'string', 'attribute must be a string'); assert(typeof stats === 'object', 'stats must be an object'); var owner = tileset.split('.')[0]; if (owner === tileset) owner = this.owner; this.client({ path: constants.API_TILESTATS_ATTRIBUTE, params: { owner: owner, tileset: tileset, layer: layer, attribute: attribute }, entity: stats, method: 'post', callback: callback }); }; /** * To retrieve statistics about the attribute values of a particular attribute * within a tileset layer. * * @param {String} tileset - the id for the tileset * @param {String} layer - the name of the layer in the tileset * @param {String} attribute - the name of the attribute in the layer * @param {Function} callback called with (err) * @returns {undefined} nothing, calls callback * @example * var client = new MapboxClient('ACCESSTOKEN'); * client.getTilestatsAttribute('tileset-id', 'layer-name', 'attr-name', function(err, info) { * console.log(info); * // { * // "account": {account}, * // "tilesetid": "tileset-id", * // "layer": "layer-name", * // "attribute": "attr-name", * // "type": "Number", * // "min": 0, * // "max": 10, * // "values": [ * // 0, * // 10 * // ] * // } * }); */ Tilestats.prototype.getTilestatsAttribute = function(tileset, layer, attribute, callback) { assert(typeof tileset === 'string', 'tileset must be a string'); assert(typeof callback === 'function', 'callback must be a function'); assert(typeof layer === 'string', 'layer must be a string'); assert(typeof attribute === 'string', 'attribute must be a string'); var owner = tileset.split('.')[0]; if (owner === tileset) owner = this.owner; this.client({ path: constants.API_TILESTATS_ATTRIBUTE, params: { owner: owner, tileset: tileset, layer: layer, attribute: attribute }, callback: callback }); };
const net = require('net'); const constants = require('./constants.js'); const client = new net.Socket(); const { HOST, PORT } = constants; client.connect(PORT, HOST, () => { console.log(`client connected to ${HOST}:${PORT}`); client.write('1'); }); client.on('data', (data) => { console.log(`server sent back -> ${data}`); client.destroy(); }); client.on('close', () => { console.log('connection was closed.'); });
import React from 'react'; import ReactDOM from 'react-dom'; import './styles/index.css'; import App from './containers/App'; import registerServiceWorker from './utils/registerServiceWorker'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
$(document).ready(function() { $("a.comment-action").attr("href", "#").css("opacity", "1"); $("span.date").each(function(index, value) { $(value).attr("title", $(value).text()) .text(moment($(value).text()).fromNow()); }); if(typeof(data) !== "undefined") { $("table.sorted").DataTable({ data: data }); } $("a.admin-action").on("click", function(e) { e.preventDefault(); var confirmation = confirm("Sure? This action cannot be undone. Clicking OK will " + $(this).data("desc") + "."); if(confirmation) { $.ajax({ type: $(this).data("request-type"), url: $(this).data("url"), data: { id: $(this).data("id") || -1 }, success: function(data) { if(data === "success") { alert("Action completed successfully."); } else { alert("Action failed to complete."); } }, error: function(data) { alert("Action failed to complete."); } }); } }); $("a.comment-action").on("click", function(e) { e.preventDefault(); var action = $(this).data("action"); var baseUrl = "/posts/comments"; if(action === "get") { // action.get: retrieve comments and display var parentId = $("div#article-container").data("post-id"); fetchComments(baseUrl, parseInt(parentId, 10)); } else if(action === "add") { // action.add: create a new comment and save it $("#add-comment-input").css("display", "block"); } else { console.log("element = ANCHOR_ELEMENT {class = 'comment-action'}"); console.log("element.userAction('click').action !== 'get' && element.userAction('click').action !== 'add'"); console.error("Could not complete action: unknown action method."); } }); $("button#comment-submit").on("click", function() { var baseUrl = "/posts/comments"; var parentId = $("div#article-container").data("post-id"); addComment(baseUrl, parentId); }); function addComment(baseUrl, parentId) { var commentText = $("#comment-input").val(); var request = baseUrl + "/add"; $.post(request, { "text": commentText, "parent": parentId }) .done(function(data) { if(data == "ok") { $("#comment-container").html(""); fetchComments(baseUrl, parentId); } else { $("#comment-status").text("There was an error adding your comment."); } $("#comment-input").val(""); $("#add-comment-input").css("display", "none"); }) .fail(function(jqXHR, textStatus, errorThrown) { $("#comment-status").text("There was an error adding your comment: " + jqXHR.responseText); }); } function fetchComments(baseUrl, parentId) { var request = baseUrl + "/get"; $.post(request, {"parent": parentId}) .done(function(data) { var json; try { json = JSON.parse(data); } catch(e) { $("#comment-status").text("There was an error fetching comments."); console.error("Error fetching comments: exception thrown at JSON.parse. Exception follows."); console.log(e); json = {}; // so that the next load of processing doesn't also throw } if(json.length == 0) { $("#comment-status").text("There are no comments to display."); return; } var templates = { "text": $("div.comment-templates > #comment-text-template").text(), "author": $("div.comment-templates > #comment-author-template").text() }; for(var i = 0; i < json.length; i++) { var commentContainer = $("<div></div>", { "class": "comment" }); $("<div></div>").text(templates["text"].replace("{{text}}", json[i]["text"])).appendTo(commentContainer); $("<div></div>").text(templates["author"].replace("{{author}}", json[i]["author"]) .replace("{{date}}", moment(json[i]["date"]).fromNow())) .attr("title", json[i]["date"]) .addClass("post-details") .appendTo(commentContainer); $("div#comment-container").append(commentContainer); } }) .fail(function(jqXHR, textStatus, errorThrown) { console.error("Error fetching comments: $.post(request) failed. Logs: request \\n jqXHR, textStatus, errorThrown."); console.log(request); console.log(jqXHR, textStatus, errorThrown); $("#comment-status").text("There was an error fetching comments: " + jqXHR.responseText); }); } });
import css from './index/index.css'
var assert = require('assert'); var flyd = require('../../../flyd'); var stream = flyd.stream; var flatMap = require('../index.js'); describe('flatMap', function() { it('applies function to values in stream', function() { var result = []; function f(v) { result.push(v); return stream(); } var s = stream(); flatMap(f, s); s(1)(2)(3)(4)(5); assert.deepEqual(result, [1, 2, 3, 4, 5]); }); it('returns stream with result from all streams created by function', function() { var result = []; function f(v) { var s = stream(); setImmediate(function() { s(v + 1)(v + 2)(v + 3); }); return s; } var s = stream(); flyd.map(function(v) { result.push(v); }, flatMap(f, s)); s(1)(3)(5); setImmediate(function() { assert.deepEqual(result, [2, 3, 4, 4, 5, 6, 6, 7, 8]); }); }); it('passed bug outlined in https://github.com/paldepind/flyd/issues/31', function(done) { function delay(val, ms) { var outStream = flyd.stream(); setTimeout(function() { outStream(val); outStream.end(true); }, ms); return outStream; } var main = delay(1, 500); var merged = flatMap(function(v) { return delay(v, 1000) }, main); flyd.on(function() { assert(main() === 1); assert(merged() === 1); done(); }, merged.end); }); });
/* global module, process */ module.exports = function(grunt) { 'use strict'; var ff = grunt.config('shared.firefox'); return { 'firefox-release': { auth: { host: 'ftp.mailfred.de', port: 21, authKey: 'firefox', authPath: process.env.FTP_DEPLOY_AUTH_PATH // may be undefined, uses the .ftppass file instead }, src: ff.path, dest: '/firefox', forceVerbose: true, exclusions: [ '**/*.xpi!' + ff.file // upload only the current xpi file ] } }; };
const errorReducer = (state = {}, action) => { const {type, payload} = action; const matches = (/(.*)_(REQUEST|FAILURE|CLEAR_ERROR)/).exec(type); if (!matches) return state; const [, requestName, requestState] = matches; return { ...state, [requestName]: requestState === 'FAILURE' ? payload.message : '', }; }; export default errorReducer;
import React from 'react'; const codespan = (props) => { const { children } = props; return ( <code className="w3-codespan">{ children }</code> ); }; export default codespan;
require('proof')(2, async okay => { await require('./harness')(okay, 'idbdatabase_createObjectStore5') await harness(async function () { var t = async_test(), open_rq = createdb(t) open_rq.onupgradeneeded = function(e) { var db = e.target.result db.createObjectStore("My cool object store name") assert_true( db.objectStoreNames.contains("My cool object store name"), 'objectStoreNames.contains') } open_rq.onsuccess = function(e) { var db = e.target.result assert_true( db.objectStoreNames.contains("My cool object store name"), 'objectStoreNames.contains (in success)') t.done() } }) })
/* * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ /* * Everything that isn't used by Strophe has been stripped here! */ /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ const safe_add = function (x, y) { const lsw = (x & 0xFFFF) + (y & 0xFFFF); const msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); }; /* * Bitwise rotate a 32-bit number to the left. */ const bit_rol = function (num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); }; /* * Convert a string to an array of little-endian words */ const str2binl = function (str) { if (typeof str !== "string") { throw new Error("str2binl was passed a non-string"); } const bin = []; for(let i = 0; i < str.length * 8; i += 8) { bin[i>>5] |= (str.charCodeAt(i / 8) & 255) << (i%32); } return bin; }; /* * Convert an array of little-endian words to a string */ const binl2str = function (bin) { let str = ""; for(let i = 0; i < bin.length * 32; i += 8) { str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & 255); } return str; }; /* * Convert an array of little-endian words to a hex string. */ const binl2hex = function (binarray) { const hex_tab = "0123456789abcdef"; let str = ""; for(let i = 0; i < binarray.length * 4; i++) { str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) + hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF); } return str; }; /* * These functions implement the four basic operations the algorithm uses. */ const md5_cmn = function (q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q),safe_add(x, t)), s),b); }; const md5_ff = function (a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); }; const md5_gg = function (a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); }; const md5_hh = function (a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); }; const md5_ii = function (a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); }; /* * Calculate the MD5 of an array of little-endian words, and a bit length */ const core_md5 = function (x, len) { /* append padding */ x[len >> 5] |= 0x80 << ((len) % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; let a = 1732584193; let b = -271733879; let c = -1732584194; let d = 271733878; let olda, oldb, oldc, oldd; for (let i = 0; i < x.length; i += 16) { olda = a; oldb = b; oldc = c; oldd = d; a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i+10], 17, -42063); b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return [a, b, c, d]; }; /* * These are the functions you'll usually want to call. * They take string arguments and return either hex or base-64 encoded * strings. */ const MD5 = { hexdigest: function (s) { return binl2hex(core_md5(str2binl(s), s.length * 8)); }, hash: function (s) { return binl2str(core_md5(str2binl(s), s.length * 8)); } }; export { MD5 as default };
'use babel' /* global atom */ import fs from 'fs-plus' const getIndexContent = function (name) { return `import {Meteor} from 'meteor/meteor' import Schema from './Schema' const ${name} = new Meteor.Collection('${name.toLowerCase()}') ${name}.attachSchema(Schema) global.${name} = ${name} export default ${name} ` } const getSchemaContent = function (name) { return `import SimpleSchema from 'simpl-schema' export default new SimpleSchema({ }) ` } const create = function (path, name) { const indexPath = `${path}/${name}/index.js` const schemaPath = `${path}/${name}/Schema.js` if (fs.existsSync(indexPath) || fs.existsSync(schemaPath)) { return atom.confirm({ message: `Collection ${name} already exists` }) } fs.writeFileSync(indexPath, getIndexContent(name)) fs.writeFileSync(schemaPath, getSchemaContent(name)) atom.workspace.open(indexPath) atom.workspace.open(schemaPath) } export default function (event) { const path = event.currentTarget.querySelector('.selected [data-path]').getAttribute('data-path') const QuestionDialog = require('../dialogs/question') const dialog = new QuestionDialog(path, 'Enter the name of the Collection') dialog.on('answer', (event, name) => { create(path, name) }) dialog.attach() }
'use strict'; //Autors service used to communicate Autors REST endpoints angular.module('autors').factory('Autors', ['$resource', function($resource) { return $resource('autors/:autorId', { autorId: '@_id' }, { update: { method: 'PUT' } }); } ]);
/* eslint-disable no-unused-vars */ /* eslint-disable no-async-promise-executor */ const express = require('express'); const bcrypt = require('bcryptjs'); const mongoose = require('mongoose'); const router = express.Router(); const request = require('request-promise'); const email = require('../lib/email'); const debugLib = require('debug')('rt-signup'); const logERR = require('debug')('ERROR:rt-signup'); const logWARN = require('debug')('WARN:rt-signup'); const logINFO = require('debug')('INFO:rt-signup'); const User = mongoose.models.User; module.exports = router; router.get('/', async function (req, res, next) { const debug = debugLib.extend('public-get/'); const captchaSiteKey = process.env.CAPTCHA_SITEKEY; const email = req.query.email; if (req.user) { debug('User already logged in: %s', req.user.username); return res.redirect('/profile'); } else if (email) { const user = await User.findOneActive({ username: email }); debug('User %s %s found.', email, user ? '' : 'not'); res.json({ result: 'ok', found: user ? 1 : 0, username: email }); res.end(); } else return res.render('signup', { captchaSiteKey: captchaSiteKey }); }); router.post('/', async function (req, res, next) { const debug = debugLib.extend('public-post/'); const siteUrl = req.protocol + '://' + req.get('host'); //const uv = new mongoose.model('UserVerify'); //const username = req.body.email; const captcha_res = req.body['g-recaptcha-response']; const recapUrl = 'https://www.google.com/recaptcha/api/siteverify?' + 'secret=' + process.env.CAPTCHA_SECRET + '&response=' + captcha_res + '&remoteip=' + req.connection.remoteAddress; // Configure the request var options = { url: recapUrl, method: 'POST', body: {}, json: true, }; // Start the request const resp = await request(options); debug('CAPTCHA RESPONSE', resp); if (!resp.success) { logWARN('CAPTCHA ERROR %s', resp['error-codes']); return res.render('message', { title: 'Nie ste človek?', error: { message: 'Pravdepodobne ste neodpovedali správne na otázky, ktorými systém overuje, či ste skutočne človek. Skúste znovu.', }, }); } try { const s = await bcrypt.genSalt(5); const h = await bcrypt.hash(req.body.password, s); const u = await User.findOneActive({ username: req.body.userName }); if (u) return res.render('message', { title: "Užívateľ '" + req.body.userName + "' už existuje", error: {}, }); const nu = { username: req.body.userName, passwordHash: h, salt: s, fullName: req.body.fullName, email: req.body.email, }; debug('Going to create user: %O', nu); const user = await User.create(nu); logINFO('User created: username=%s id=%s', user.username, user.id); email.sendSignupConfirmation(user, siteUrl); return res.render('message', { title: 'Vytvorenie účtu bolo úspešné', message: 'Pri prihlasovaní použite údaje vložené na predchádzajúcej stránke..', link: { description: 'Pre pokračovanie kliknite na', url: '/login', text: 'tento link', }, }); } catch (err) { debug('Error: %O', err); return res.render('message', { title: 'Nepodarilo sa vytvoriť účet', error: err }); } });
const exec = require("util").promisify(require("child_process").exec); exports.run = async (client, msg, [input]) => { const result = await exec(input).catch((err) => { throw err; }); const output = result.stdout ? `**\`OUTPUT\`**${"```sh"}\n${result.stdout}\n${"```"}` : ""; const outerr = result.stderr ? `**\`ERROR\`**${"```sh"}\n${result.stderr}\n${"```"}` : ""; return msg.channel.send([output, outerr].join("\n")); }; exports.conf = { enabled: true, selfbot: false, runIn: ["text", "dm", "group"], aliases: [], permLevel: 10, botPerms: [], requiredFuncs: [], requiredModules: [], }; exports.help = { name: "exec", description: "Execute commands in the terminal, use with EXTREME CAUTION.", usage: "<expression:str>", usageDelim: "", extendedHelp: "", type: "commands", };
/* Search Result Area */ $('.content .results-cover').click(function(event) { event.preventDefault(); $('.search .field').addClass('required'); $('.search .field').focus(); }); /* /Search Result Area */ /* If search field is empty */ $('.search .submit').click(function(){ if( !$('.search .field').val() ) { $('.search .field').addClass('required'); $('.search .field').focus(); } else { $('.search .field').removeClass('required'); } }); /* /If search field is empty */ /* Add to Favorite */ $('.favorite').click(function(event) { event.preventDefault(); $(this).toggleClass('active'); }); /* /Add to Favorite */ // not work $('#cover-favorite-coverrrrr').click(function(e) { e.preventDefault(); });
/** * @file Data zoom model */ var zrUtil = require('zrender/lib/core/util'); var env = require('zrender/lib/core/env'); var echarts = require('../../echarts'); var modelUtil = require('../../util/model'); var AxisProxy = require('./AxisProxy'); var each = zrUtil.each; var eachAxisDim = modelUtil.eachAxisDim; var DataZoomModel = echarts.extendComponentModel({ type: 'dataZoom', dependencies: [ 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'series' ], /** * @protected */ defaultOption: { zlevel: 0, z: 4, // Higher than normal component (z: 2). orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'. xAxisIndex: null, // Default the first horizontal category axis. yAxisIndex: null, // Default the first vertical category axis. angleAxisIndex: null, radiusAxisIndex: null, filterMode: 'filter', // Possible values: 'filter' or 'empty'. // 'filter': data items which are out of window will be removed. // This option is applicable when filtering outliers. // 'empty': data items which are out of window will be set to empty. // This option is applicable when user should not neglect // that there are some data items out of window. // Taking line chart as an example, line will be broken in // the filtered points when filterModel is set to 'empty', but // be connected when set to 'filter'. throttle: null, // Dispatch action by the fixed rate, avoid frequency. // default 100. Do not throttle when use null/undefined. // If animation === true and animationDurationUpdate > 0, // default value is 100, otherwise 20. start: 0, // Start percent. 0 ~ 100 end: 100, // End percent. 0 ~ 100 startValue: null, // Start value. If startValue specified, start is ignored. endValue: null // End value. If endValue specified, end is ignored. }, /** * @override */ init: function (option, parentModel, ecModel) { /** * key like x_0, y_1 * @private * @type {Object} */ this._dataIntervalByAxis = {}; /** * @private */ this._dataInfo = {}; /** * key like x_0, y_1 * @private */ this._axisProxies = {}; /** * @readOnly */ this.textStyleModel; /** * @private */ this._autoThrottle = true; var rawOption = retrieveRaw(option); this.mergeDefaultAndTheme(option, ecModel); this.doInit(rawOption); }, /** * @override */ mergeOption: function (newOption) { var rawOption = retrieveRaw(newOption); //FIX #2591 zrUtil.merge(this.option, newOption, true); this.doInit(rawOption); }, /** * @protected */ doInit: function (rawOption) { var thisOption = this.option; // Disable realtime view update if canvas is not supported. if (!env.canvasSupported) { thisOption.realtime = false; } this._setDefaultThrottle(rawOption); processRangeProp('start', 'startValue', rawOption, thisOption); processRangeProp('end', 'endValue', rawOption, thisOption); this.textStyleModel = this.getModel('textStyle'); this._resetTarget(); this._giveAxisProxies(); }, /** * @private */ _giveAxisProxies: function () { var axisProxies = this._axisProxies; this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) { var axisModel = this.dependentModels[dimNames.axis][axisIndex]; // If exists, share axisProxy with other dataZoomModels. var axisProxy = axisModel.__dzAxisProxy || ( // Use the first dataZoomModel as the main model of axisProxy. axisModel.__dzAxisProxy = new AxisProxy( dimNames.name, axisIndex, this, ecModel ) ); // FIXME // dispose __dzAxisProxy axisProxies[dimNames.name + '_' + axisIndex] = axisProxy; }, this); }, /** * @private */ _resetTarget: function () { var thisOption = this.option; var autoMode = this._judgeAutoMode(); eachAxisDim(function (dimNames) { var axisIndexName = dimNames.axisIndex; thisOption[axisIndexName] = modelUtil.normalizeToArray( thisOption[axisIndexName] ); }, this); if (autoMode === 'axisIndex') { this._autoSetAxisIndex(); } else if (autoMode === 'orient') { this._autoSetOrient(); } }, /** * @private */ _judgeAutoMode: function () { // Auto set only works for setOption at the first time. // The following is user's reponsibility. So using merged // option is OK. var thisOption = this.option; var hasIndexSpecified = false; eachAxisDim(function (dimNames) { // When user set axisIndex as a empty array, we think that user specify axisIndex // but do not want use auto mode. Because empty array may be encountered when // some error occured. if (thisOption[dimNames.axisIndex] != null) { hasIndexSpecified = true; } }, this); var orient = thisOption.orient; if (orient == null && hasIndexSpecified) { return 'orient'; } else if (!hasIndexSpecified) { if (orient == null) { thisOption.orient = 'horizontal'; } return 'axisIndex'; } }, /** * @private */ _autoSetAxisIndex: function () { var autoAxisIndex = true; var orient = this.get('orient', true); var thisOption = this.option; if (autoAxisIndex) { // Find axis that parallel to dataZoom as default. var dimNames = orient === 'vertical' ? {dim: 'y', axisIndex: 'yAxisIndex', axis: 'yAxis'} : {dim: 'x', axisIndex: 'xAxisIndex', axis: 'xAxis'}; if (this.dependentModels[dimNames.axis].length) { thisOption[dimNames.axisIndex] = [0]; autoAxisIndex = false; } } if (autoAxisIndex) { // Find the first category axis as default. (consider polar) eachAxisDim(function (dimNames) { if (!autoAxisIndex) { return; } var axisIndices = []; var axisModels = this.dependentModels[dimNames.axis]; if (axisModels.length && !axisIndices.length) { for (var i = 0, len = axisModels.length; i < len; i++) { if (axisModels[i].get('type') === 'category') { axisIndices.push(i); } } } thisOption[dimNames.axisIndex] = axisIndices; if (axisIndices.length) { autoAxisIndex = false; } }, this); } if (autoAxisIndex) { // FIXME // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制), // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)? // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified, // dataZoom component auto adopts series that reference to // both xAxis and yAxis which type is 'value'. this.ecModel.eachSeries(function (seriesModel) { if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) { eachAxisDim(function (dimNames) { var axisIndices = thisOption[dimNames.axisIndex]; var axisIndex = seriesModel.get(dimNames.axisIndex); if (zrUtil.indexOf(axisIndices, axisIndex) < 0) { axisIndices.push(axisIndex); } }); } }, this); } }, /** * @private */ _autoSetOrient: function () { var dim; // Find the first axis this.eachTargetAxis(function (dimNames) { !dim && (dim = dimNames.name); }, this); this.option.orient = dim === 'y' ? 'vertical' : 'horizontal'; }, /** * @private */ _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) { // FIXME // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。 // 例如series.type === scatter时。 var is = true; eachAxisDim(function (dimNames) { var seriesAxisIndex = seriesModel.get(dimNames.axisIndex); var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex]; if (!axisModel || axisModel.get('type') !== axisType) { is = false; } }, this); return is; }, /** * @private */ _setDefaultThrottle: function (rawOption) { // When first time user set throttle, auto throttle ends. if (rawOption.hasOwnProperty('throttle')) { this._autoThrottle = false; } if (this._autoThrottle) { var globalOption = this.ecModel.option; this.option.throttle = (globalOption.animation && globalOption.animationDurationUpdate > 0) ? 100 : 20; } }, /** * @public */ getFirstTargetAxisModel: function () { var firstAxisModel; eachAxisDim(function (dimNames) { if (firstAxisModel == null) { var indices = this.get(dimNames.axisIndex); if (indices.length) { firstAxisModel = this.dependentModels[dimNames.axis][indices[0]]; } } }, this); return firstAxisModel; }, /** * @public * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel */ eachTargetAxis: function (callback, context) { var ecModel = this.ecModel; eachAxisDim(function (dimNames) { each( this.get(dimNames.axisIndex), function (axisIndex) { callback.call(context, dimNames, axisIndex, this, ecModel); }, this ); }, this); }, getAxisProxy: function (dimName, axisIndex) { return this._axisProxies[dimName + '_' + axisIndex]; }, /** * If not specified, set to undefined. * * @public * @param {Object} opt * @param {number} [opt.start] * @param {number} [opt.end] * @param {number} [opt.startValue] * @param {number} [opt.endValue] */ setRawRange: function (opt) { each(['start', 'end', 'startValue', 'endValue'], function (name) { // If any of those prop is null/undefined, we should alos set // them, because only one pair between start/end and // startValue/endValue can work. this.option[name] = opt[name]; }, this); }, /** * @public * @return {Array.<number>} [startPercent, endPercent] */ getPercentRange: function () { var axisProxy = this.findRepresentativeAxisProxy(); if (axisProxy) { return axisProxy.getDataPercentWindow(); } }, /** * @public * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0); * * @param {string} [axisDimName] * @param {number} [axisIndex] * @return {Array.<number>} [startValue, endValue] */ getValueRange: function (axisDimName, axisIndex) { if (axisDimName == null && axisIndex == null) { var axisProxy = this.findRepresentativeAxisProxy(); if (axisProxy) { return axisProxy.getDataValueWindow(); } } else { return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow(); } }, /** * @public * @return {module:echarts/component/dataZoom/AxisProxy} */ findRepresentativeAxisProxy: function () { // Find the first hosted axisProxy var axisProxies = this._axisProxies; for (var key in axisProxies) { if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) { return axisProxies[key]; } } // If no hosted axis find not hosted axisProxy. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis, // and the option.start or option.end settings are different. The percentRange // should follow axisProxy. // (We encounter this problem in toolbox data zoom.) for (var key in axisProxies) { if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) { return axisProxies[key]; } } } }); function retrieveRaw(option) { var ret = {}; each( ['start', 'end', 'startValue', 'endValue', 'throttle'], function (name) { option.hasOwnProperty(name) && (ret[name] = option[name]); } ); return ret; } function processRangeProp(percentProp, valueProp, rawOption, thisOption) { // start/end has higher priority over startValue/endValue, // but we should make chart.setOption({endValue: 1000}) effective, // rather than chart.setOption({endValue: 1000, end: null}). if (rawOption[valueProp] != null && rawOption[percentProp] == null) { thisOption[percentProp] = null; } // Otherwise do nothing and use the merge result. } module.exports = DataZoomModel;
/* * THIS FILE IS AUTO GENERATED from 'lib/position.kep' * DO NOT EDIT */define(["require", "exports"], (function(require, exports) { "use strict"; var SourcePosition, SourceLocation; (SourcePosition = (function(line, column, file) { var self = this; (self.line = line); (self.column = column); (self.file = file); })); (SourcePosition.initial = new(SourcePosition)(1, 0, null)); (SourcePosition.prototype.increment = (function(tok) { var self = this; return ((tok === "\n") ? new(SourcePosition)((self.line + 1), 0, self.file) : new( SourcePosition)(self.line, (self.column + 1), self.file)); })); (SourcePosition.prototype.toString = (function() { var self = this; return (((("{line:" + self.line) + " col:") + self.column) + "}"); })); (SourcePosition.prototype.compare = (function(pos) { var self = this; return ((self.line === pos.line) ? (self.column - pos.column) : (self.line - pos.line)); })); (SourceLocation = (function(start, end, file) { var self = this; (self.start = start); (self.end = end); (self.file = file); })); (SourceLocation.prototype.toString = (function() { var self = this; return (((((("{" + self.file) + " start:") + self.start) + " end:") + self.end) + "}"); })); (SourceLocation.merge = (function(s1, s2) { return new(SourceLocation)(((s1.start.compare(s2.start) > 0) ? s2.start : s1.start), ((s1.end.compare( s2.end) > 0) ? s1.end : s2.end), (s1.file || s2.file)); })); (exports["SourcePosition"] = SourcePosition); (exports["SourceLocation"] = SourceLocation); }));
'use strict'; var fs = require( 'fs' ); var path = require( 'path' ); var logger = require( './../utilities/logger.js' ); /** * Reads all controls, including engine's predefined controls. * @param {string} controlPath - The path of the controls directory. * @param {FilingCabinet} filingCabinet - The file manager object. */ function readControls( controlPath, filingCabinet ) { logger.showInfo( '*** Reading controls...' ); // Initialize the store - engine controls. logger.showInfo( 'Engine controls:' ); getControls( '/node_modules/md-site-engine/controls', '', filingCabinet.controls ); // Initialize the store - user controls. logger.showInfo( 'Site controls:' ); getControls( controlPath, '', filingCabinet.controls ); } /** * Reads all controls from a sub-directory. * @param {string} controlPath - The path of the control sub-directory. * @param {string} levelPath - The base URL of the sub-directory. * @param {ControlDrawer} controlDrawer - The control storage. */ function getControls( controlPath, levelPath, controlDrawer ) { var typeName = 'Control'; // Read directory items. var directoryPath = path.join( process.cwd(), controlPath ); var items = fs.readdirSync( directoryPath ); items.forEach( function ( item ) { var itemPath = path.join( controlPath, item ); var filePath = path.join( process.cwd(), itemPath ); // Get item info. var stats = fs.statSync( filePath ); if (stats.isDirectory()) { // Get sub level controls. getControls( itemPath, path.join( levelPath, item ), controlDrawer ); } else if (stats.isFile() && path.extname( item ) === '.js') { // Read and store the JavaScript file. var controlKey = path.join( levelPath, path.basename( item, '.js' ) ); controlDrawer.add( controlKey, require( filePath ) ); logger.fileProcessed( typeName, itemPath ); } else logger.fileSkipped( typeName, itemPath ); } ) } module.exports = readControls;
export default class TabNames { static get overview() { return 'overview'; } static get pois() { return 'pois'; } static get hotels() { return 'hotels'; } static get villas() { return 'villas'; } }
'use strict'; /* jshint -W110 */ var Utils = require('../../utils') , hstore = require('./hstore') , range = require('./range') , util = require('util') , DataTypes = require('../../data-types') , SqlString = require('../../sql-string') , AbstractQueryGenerator = require('../abstract/query-generator') , primaryKeys = {} , _ = require('lodash'); var QueryGenerator = { options: {}, dialect: 'postgres', createSchema: function(schema) { var query = 'CREATE SCHEMA <%= schema%>;'; return Utils._.template(query)({schema: schema}); }, dropSchema: function(schema) { var query = 'DROP SCHEMA <%= schema%> CASCADE;'; return Utils._.template(query)({schema: schema}); }, showSchemasQuery: function() { return "SELECT schema_name FROM information_schema.schemata WHERE schema_name <> 'information_schema' AND schema_name != 'public' AND schema_name !~ E'^pg_';"; }, versionQuery: function() { return 'SHOW SERVER_VERSION'; }, createTableQuery: function(tableName, attributes, options) { var self = this; options = Utils._.extend({ }, options || {}); primaryKeys[tableName] = []; var query = 'CREATE TABLE IF NOT EXISTS <%= table %> (<%= attributes%>)<%= comments %>' , comments = '' , attrStr = [] , i; if (options.comment && Utils._.isString(options.comment)) { comments += '; COMMENT ON TABLE <%= table %> IS ' + this.escape(options.comment); } for (var attr in attributes) { if ((i = attributes[attr].indexOf('COMMENT')) !== -1) { // Move comment to a seperate query comments += '; ' + attributes[attr].substring(i); attributes[attr] = attributes[attr].substring(0, i); } var dataType = this.pgDataTypeMapping(tableName, attr, attributes[attr]); attrStr.push(this.quoteIdentifier(attr) + ' ' + dataType); } var values = { table: this.quoteTable(tableName), attributes: attrStr.join(', '), comments: Utils._.template(comments)({ table: this.quoteTable(tableName)}) }; if (!!options.uniqueKeys) { Utils._.each(options.uniqueKeys, function(columns) { if (!columns.singleField) { // If it's a single field its handled in column def, not as an index values.attributes += ', UNIQUE (' + columns.fields.map(function(f) { return self.quoteIdentifiers(f); }).join(', ') + ')'; } }); } var pks = primaryKeys[tableName].map(function(pk) { return this.quoteIdentifier(pk); }.bind(this)).join(','); if (pks.length > 0) { values.attributes += ', PRIMARY KEY (' + pks + ')'; } return Utils._.template(query)(values).trim() + ';'; }, dropTableQuery: function(tableName, options) { options = options || {}; var query = 'DROP TABLE IF EXISTS <%= table %><%= cascade %>;'; return Utils._.template(query)({ table: this.quoteTable(tableName), cascade: options.cascade ? ' CASCADE' : '' }); }, showTablesQuery: function() { return "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type LIKE '%TABLE' AND table_name != 'spatial_ref_sys';"; }, describeTableQuery: function(tableName, schema) { if (!schema) { schema = 'public'; } var query = 'SELECT tc.constraint_type as "Constraint", c.column_name as "Field", c.column_default as "Default", c.is_nullable as "Null", ' + "CASE WHEN c.udt_name = 'hstore' " + 'THEN c.udt_name ELSE c.data_type END as "Type", (SELECT array_agg(e.enumlabel) ' + 'FROM pg_catalog.pg_type t JOIN pg_catalog.pg_enum e ON t.oid=e.enumtypid WHERE t.typname=c.udt_name) AS "special" ' + 'FROM information_schema.columns c ' + 'LEFT JOIN information_schema.key_column_usage cu ON c.table_name = cu.table_name AND cu.column_name = c.column_name ' + 'LEFT JOIN information_schema.table_constraints tc ON c.table_name = tc.table_name AND cu.column_name = c.column_name AND tc.constraint_type = \'PRIMARY KEY\' ' + ' WHERE c.table_name = <%= table %> AND c.table_schema = <%= schema %> '; return Utils._.template(query)({ table: this.escape(tableName), schema: this.escape(schema) }); }, // A recursive parser for nested where conditions parseConditionObject: function(_conditions, path) { var self = this; path = path || []; return Utils._.reduce(_conditions, function (r, v, k) { // result, key, value if (Utils._.isObject(v)) { r = r.concat(self.parseConditionObject(v, path.concat(k))); // Recursively parse objects } else { r.push({ path: path.concat(k), value: v }); } return r; }, []); }, handleSequelizeMethod: function (smth, tableName, factory, options, prepend) { var _ = Utils._; if (smth instanceof Utils.json) { // Parse nested object if (smth.conditions) { var conditions = _.map(this.parseConditionObject(smth.conditions), function generateSql(condition) { return util.format("%s#>>'{%s}' = '%s'", _.first(condition.path), _.rest(condition.path).join(','), condition.value); }); return conditions.join(' and '); } else if (smth.path) { var str; // Allow specifying conditions using the postgres json syntax if (_.any(['->', '->>', '#>'], _.partial(_.contains, smth.path))) { str = smth.path; } else { // Also support json dot notation var path = smth.path.split('.'); str = util.format("%s#>>'{%s}'", _.first(path), _.rest(path).join(',')); } if (smth.value) { str += util.format(' = %s', this.escape(smth.value)); } return str; } } else { return AbstractQueryGenerator.handleSequelizeMethod.call(this, smth, tableName, factory, options, prepend); } }, addColumnQuery: function(table, key, dataType) { var query = 'ALTER TABLE <%= table %> ADD COLUMN <%= attribute %>;' , dbDataType = this.attributeToSQL(dataType, {context: 'addColumn'}) , attribute; if (dataType.type && dataType.type instanceof DataTypes.ENUM || dataType instanceof DataTypes.ENUM) { query = this.pgEnum(table, key, dataType) + query; } attribute = Utils._.template('<%= key %> <%= definition %>')({ key: this.quoteIdentifier(key), definition: this.pgDataTypeMapping(table, key, dbDataType) }); return Utils._.template(query)({ table: this.quoteTable(table), attribute: attribute }); }, removeColumnQuery: function(tableName, attributeName) { var query = 'ALTER TABLE <%= tableName %> DROP COLUMN <%= attributeName %>;'; return Utils._.template(query)({ tableName: this.quoteTable(tableName), attributeName: this.quoteIdentifier(attributeName) }); }, changeColumnQuery: function(tableName, attributes) { var query = 'ALTER TABLE <%= tableName %> ALTER COLUMN <%= query %>;' , sql = []; for (var attributeName in attributes) { var definition = this.pgDataTypeMapping(tableName, attributeName, attributes[attributeName]); var attrSql = ''; if (definition.indexOf('NOT NULL') > 0) { attrSql += Utils._.template(query)({ tableName: this.quoteTable(tableName), query: this.quoteIdentifier(attributeName) + ' SET NOT NULL' }); definition = definition.replace('NOT NULL', '').trim(); } else { attrSql += Utils._.template(query)({ tableName: this.quoteTable(tableName), query: this.quoteIdentifier(attributeName) + ' DROP NOT NULL' }); } if (definition.indexOf('DEFAULT') > 0) { attrSql += Utils._.template(query)({ tableName: this.quoteTable(tableName), query: this.quoteIdentifier(attributeName) + ' SET DEFAULT ' + definition.match(/DEFAULT ([^;]+)/)[1] }); definition = definition.replace(/(DEFAULT[^;]+)/, '').trim(); } else { attrSql += Utils._.template(query)({ tableName: this.quoteTable(tableName), query: this.quoteIdentifier(attributeName) + ' DROP DEFAULT' }); } if (attributes[attributeName].match(/^ENUM\(/)) { query = this.pgEnum(tableName, attributeName, attributes[attributeName]) + query; definition = definition.replace(/^ENUM\(.+\)/, this.quoteIdentifier('enum_' + tableName + '_' + attributeName)); definition += ' USING (' + this.quoteIdentifier(attributeName) + '::' + this.quoteIdentifier(definition) + ')'; } if (definition.match(/UNIQUE;*$/)) { definition = definition.replace(/UNIQUE;*$/, ''); attrSql += Utils._.template(query.replace('ALTER COLUMN', ''))({ tableName: this.quoteTable(tableName), query: 'ADD CONSTRAINT ' + this.quoteIdentifier(attributeName + '_unique_idx') + ' UNIQUE (' + this.quoteIdentifier(attributeName) + ')' }); } attrSql += Utils._.template(query)({ tableName: this.quoteTable(tableName), query: this.quoteIdentifier(attributeName) + ' TYPE ' + definition }); sql.push(attrSql); } return sql.join(''); }, renameColumnQuery: function(tableName, attrBefore, attributes) { var query = 'ALTER TABLE <%= tableName %> RENAME COLUMN <%= attributes %>;'; var attrString = []; for (var attributeName in attributes) { attrString.push(Utils._.template('<%= before %> TO <%= after %>')({ before: this.quoteIdentifier(attrBefore), after: this.quoteIdentifier(attributeName) })); } return Utils._.template(query)({ tableName: this.quoteTable(tableName), attributes: attrString.join(', ') }); }, fn: function(fnName, tableName, body, returns, language) { fnName = fnName || 'testfunc'; language = language || 'plpgsql'; returns = returns || 'SETOF ' + this.quoteTable(tableName); var query = 'CREATE OR REPLACE FUNCTION pg_temp.<%= fnName %>() RETURNS <%= returns %> AS $func$ BEGIN <%= body %> END; $func$ LANGUAGE <%= language %>; SELECT * FROM pg_temp.<%= fnName %>();'; return Utils._.template(query)({ fnName: fnName, returns: returns, language: language, body: body }); }, exceptionFn: function(fnName, tableName, main, then, when, returns, language) { when = when || 'unique_violation'; var body = '<%= main %> EXCEPTION WHEN <%= when %> THEN <%= then %>;'; body = Utils._.template(body)({ main: main, when: when, then: then }); return this.fn(fnName, tableName, body, returns, language); }, // http://www.maori.geek.nz/post/postgres_upsert_update_or_insert_in_ger_using_knex_js upsertQuery: function (tableName, insertValues, updateValues, where, rawAttributes, options) { var insert = this.insertQuery(tableName, insertValues, rawAttributes, options); var update = this.updateQuery(tableName, updateValues, where, options, rawAttributes); // The numbers here are selected to match the number of affected rows returned by MySQL return this.exceptionFn( 'sequelize_upsert', tableName, insert + ' RETURN 1;', update + '; RETURN 2', 'unique_violation', 'integer' ); }, bulkInsertQuery: function(tableName, attrValueHashes, options, modelAttributes) { options = options || {}; var query = 'INSERT INTO <%= table %> (<%= attributes %>) VALUES <%= tuples %>' , tuples = [] , serials = [] , allAttributes = []; if (options.returning) { query += ' RETURNING *'; } Utils._.forEach(attrValueHashes, function(attrValueHash) { Utils._.forOwn(attrValueHash, function(value, key) { if (allAttributes.indexOf(key) === -1) { allAttributes.push(key); } if (modelAttributes && modelAttributes[key] && modelAttributes[key].autoIncrement === true) { serials.push(key); } }); }); Utils._.forEach(attrValueHashes, function(attrValueHash) { tuples.push('(' + allAttributes.map(function(key) { if (serials.indexOf(key) !== -1) { return attrValueHash[key] || 'DEFAULT'; } return this.escape(attrValueHash[key], modelAttributes && modelAttributes[key]); }.bind(this)).join(',') + ')'); }.bind(this)); var replacements = { table: this.quoteTable(tableName) , attributes: allAttributes.map(function(attr) { return this.quoteIdentifier(attr); }.bind(this)).join(',') , tuples: tuples.join(',') }; query = query + ';'; return Utils._.template(query)(replacements); }, deleteQuery: function(tableName, where, options, model) { var query; options = options || {}; tableName = Utils.removeTicks(this.quoteTable(tableName), '"'); if (options.truncate === true) { query = 'TRUNCATE ' + QueryGenerator.quoteIdentifier(tableName); if (options.cascade) { query += ' CASCADE'; } return query; } if (Utils._.isUndefined(options.limit)) { options.limit = 1; } primaryKeys[tableName] = primaryKeys[tableName] || []; if (!!model && primaryKeys[tableName].length < 1) { primaryKeys[tableName] = Utils._.map(Object.keys(model.primaryKeys), function(k){ return model.primaryKeys[k].field; }); } if (options.limit) { query = 'DELETE FROM <%= table %> WHERE <%= primaryKeys %> IN (SELECT <%= primaryKeysSelection %> FROM <%= table %><%= where %><%= limit %>)'; } else { query = 'DELETE FROM <%= table %><%= where %>'; } var pks; if (primaryKeys[tableName] && primaryKeys[tableName].length > 0) { pks = primaryKeys[tableName].map(function(pk) { return this.quoteIdentifier(pk); }.bind(this)).join(','); } else { pks = this.quoteIdentifier('id'); } var replacements = { table: this.quoteIdentifiers(tableName), where: this.getWhereConditions(where), limit: !!options.limit ? ' LIMIT ' + this.escape(options.limit) : '', primaryKeys: primaryKeys[tableName].length > 1 ? '(' + pks + ')' : pks, primaryKeysSelection: pks }; if (replacements.where) { replacements.where = ' WHERE ' + replacements.where; } return Utils._.template(query)(replacements); }, showIndexesQuery: function(tableName) { if (!Utils._.isString(tableName)) { tableName = tableName.tableName; } // This is ARCANE! var query = 'SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, ' + 'array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) ' + 'AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a ' + 'WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND '+ "t.relkind = 'r' and t.relname = '<%= tableName %>' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;"; return Utils._.template(query)({ tableName: tableName }); }, removeIndexQuery: function(tableName, indexNameOrAttributes) { var sql = 'DROP INDEX IF EXISTS <%= indexName %>' , indexName = indexNameOrAttributes; if (typeof indexName !== 'string') { indexName = Utils.inflection.underscore(tableName + '_' + indexNameOrAttributes.join('_')); } return Utils._.template(sql)({ tableName: this.quoteIdentifiers(tableName), indexName: this.quoteIdentifiers(indexName) }); }, addLimitAndOffset: function(options) { var fragment = ''; if (options.limit) fragment += ' LIMIT ' + options.limit; if (options.offset) fragment += ' OFFSET ' + options.offset; return fragment; }, attributeToSQL: function(attribute) { if (!Utils._.isPlainObject(attribute)) { attribute = { type: attribute }; } var template = '<%= type %>' , replacements = {}; if (attribute.type instanceof DataTypes.ENUM) { if (attribute.type.values && !attribute.values) attribute.values = attribute.type.values; if (Array.isArray(attribute.values) && (attribute.values.length > 0)) { replacements.type = 'ENUM(' + Utils._.map(attribute.values, function(value) { return this.escape(value); }.bind(this)).join(', ') + ')'; } else { throw new Error("Values for ENUM haven't been defined."); } } if (!replacements.type) { replacements.type = attribute.type; } if (attribute.hasOwnProperty('allowNull') && (!attribute.allowNull)) { template += ' NOT NULL'; } if (attribute.autoIncrement) { template += ' SERIAL'; } if (Utils.defaultValueSchemable(attribute.defaultValue)) { template += ' DEFAULT <%= defaultValue %>'; replacements.defaultValue = this.escape(attribute.defaultValue, attribute); } if (attribute.unique === true) { template += ' UNIQUE'; } if (attribute.primaryKey) { template += ' PRIMARY KEY'; } if (attribute.references) { attribute = Utils.formatReferences(attribute); template += ' REFERENCES <%= referencesTable %> (<%= referencesKey %>)'; replacements.referencesTable = this.quoteTable(attribute.references.model); if (attribute.references.key) { replacements.referencesKey = this.quoteIdentifiers(attribute.references.key); } else { replacements.referencesKey = this.quoteIdentifier('id'); } if (attribute.onDelete) { template += ' ON DELETE <%= onDeleteAction %>'; replacements.onDeleteAction = attribute.onDelete.toUpperCase(); } if (attribute.onUpdate) { template += ' ON UPDATE <%= onUpdateAction %>'; replacements.onUpdateAction = attribute.onUpdate.toUpperCase(); } if (attribute.references.deferrable) { template += ' <%= deferrable %>'; replacements.deferrable = attribute.references.deferrable.toString(this); } } return Utils._.template(template)(replacements); }, deferConstraintsQuery: function (options) { return options.deferrable.toString(this); }, setConstraintQuery: function (columns, type) { var columnFragment = 'ALL'; if (columns) { columnFragment = columns.map(function (column) { return this.quoteIdentifier(column); }.bind(this)).join(', '); } return 'SET CONSTRAINTS ' + columnFragment + ' ' + type; }, setDeferredQuery: function (columns) { return this.setConstraintQuery(columns, 'DEFERRED'); }, setImmediateQuery: function (columns) { return this.setConstraintQuery(columns, 'IMMEDIATE'); }, attributesToSQL: function(attributes, options) { var result = {} , key , attribute; for (key in attributes) { attribute = attributes[key]; result[attribute.field || key] = this.attributeToSQL(attribute, options); } return result; }, findAutoIncrementField: function(factory) { var fields = []; for (var name in factory.attributes) { var definition = factory.attributes[name]; if (definition && definition.autoIncrement) { fields.push(name); } } return fields; }, createTrigger: function(tableName, triggerName, eventType, fireOnSpec, functionName, functionParams, optionsArray) { var sql = [ 'CREATE <%= constraintVal %>TRIGGER <%= triggerName %>' , '<%= eventType %> <%= eventSpec %>' , 'ON <%= tableName %>' , '<%= optionsSpec %>' , 'EXECUTE PROCEDURE <%= functionName %>(<%= paramList %>);' ].join('\n\t'); return Utils._.template(sql)({ constraintVal: this.triggerEventTypeIsConstraint(eventType), triggerName: triggerName, eventType: this.decodeTriggerEventType(eventType), eventSpec: this.expandTriggerEventSpec(fireOnSpec), tableName: tableName, optionsSpec: this.expandOptions(optionsArray), functionName: functionName, paramList: this.expandFunctionParamList(functionParams) }); }, dropTrigger: function(tableName, triggerName) { var sql = 'DROP TRIGGER <%= triggerName %> ON <%= tableName %> RESTRICT;'; return Utils._.template(sql)({ triggerName: triggerName, tableName: tableName }); }, renameTrigger: function(tableName, oldTriggerName, newTriggerName) { var sql = 'ALTER TRIGGER <%= oldTriggerName %> ON <%= tableName %> RENAME TO <%= newTriggerName%>;'; return Utils._.template(sql)({ tableName: tableName, oldTriggerName: oldTriggerName, newTriggerName: newTriggerName }); }, createFunction: function(functionName, params, returnType, language, body, options) { var sql = ['CREATE FUNCTION <%= functionName %>(<%= paramList %>)' , 'RETURNS <%= returnType %> AS $func$' , 'BEGIN' , '\t<%= body %>' , 'END;' , "$func$ language '<%= language %>'<%= options %>;" ].join('\n'); return Utils._.template(sql)({ functionName: functionName, paramList: this.expandFunctionParamList(params), returnType: returnType, body: body.replace('\n', '\n\t'), language: language, options: this.expandOptions(options) }); }, dropFunction: function(functionName, params) { // RESTRICT is (currently, as of 9.2) default but we'll be explicit var sql = 'DROP FUNCTION <%= functionName %>(<%= paramList %>) RESTRICT;'; return Utils._.template(sql)({ functionName: functionName, paramList: this.expandFunctionParamList(params) }); }, renameFunction: function(oldFunctionName, params, newFunctionName) { var sql = 'ALTER FUNCTION <%= oldFunctionName %>(<%= paramList %>) RENAME TO <%= newFunctionName %>;'; return Utils._.template(sql)({ oldFunctionName: oldFunctionName, paramList: this.expandFunctionParamList(params), newFunctionName: newFunctionName }); }, databaseConnectionUri: function(config) { var template = '<%= protocol %>://<%= user %>:<%= password %>@<%= host %><% if(port) { %>:<%= port %><% } %>/<%= database %><% if(ssl) { %>?ssl=<%= ssl %><% } %>'; return Utils._.template(template)({ user: config.username, password: config.password, database: config.database, host: config.host, port: config.port, protocol: config.protocol, ssl: true }); }, pgEscapeAndQuote: function(val) { return this.quoteIdentifier(Utils.removeTicks(this.escape(val), "'")); }, expandFunctionParamList: function expandFunctionParamList(params) { if (Utils._.isUndefined(params) || !Utils._.isArray(params)) { throw new Error('expandFunctionParamList: function parameters array required, including an empty one for no arguments'); } var paramList = Utils._.each(params, function expandParam(curParam) { var paramDef = []; if (Utils._.has(curParam, 'type')) { if (Utils._.has(curParam, 'direction')) { paramDef.push(curParam.direction); } if (Utils._.has(curParam, 'name')) { paramDef.push(curParam.name); } paramDef.push(curParam.type); } else { throw new Error('createFunction called with a parameter with no type'); } return paramDef.join(' '); }); return paramList.join(', '); }, expandOptions: function expandOptions(options) { return Utils._.isUndefined(options) || Utils._.isEmpty(options) ? '' : '\n\t' + options.join('\n\t'); }, decodeTriggerEventType: function decodeTriggerEventType(eventSpecifier) { var EVENT_DECODER = { 'after': 'AFTER', 'before': 'BEFORE', 'instead_of': 'INSTEAD OF', 'after_constraint': 'AFTER' }; if (!Utils._.has(EVENT_DECODER, eventSpecifier)) { throw new Error('Invalid trigger event specified: ' + eventSpecifier); } return EVENT_DECODER[eventSpecifier]; }, triggerEventTypeIsConstraint: function triggerEventTypeIsConstraint(eventSpecifier) { return eventSpecifier === 'after_constrain' ? 'CONSTRAINT ' : ''; }, expandTriggerEventSpec: function expandTriggerEventSpec(fireOnSpec) { if (Utils._.isEmpty(fireOnSpec)) { throw new Error('no table change events specified to trigger on'); } return Utils._.map(fireOnSpec, function parseTriggerEventSpec(fireValue, fireKey) { var EVENT_MAP = { 'insert': 'INSERT', 'update': 'UPDATE', 'delete': 'DELETE', 'truncate': 'TRUNCATE' }; if (!Utils._.has(EVENT_MAP, fireKey)) { throw new Error('parseTriggerEventSpec: undefined trigger event ' + fireKey); } var eventSpec = EVENT_MAP[fireKey]; if (eventSpec === 'UPDATE') { if (Utils._.isArray(fireValue) && fireValue.length > 0) { eventSpec += ' OF ' + fireValue.join(', '); } } return eventSpec; }).join(' OR '); }, pgEnumName: function (tableName, attr, options) { options = options || {}; var enumName = '"enum_' + (_.isPlainObject(tableName) ? tableName.table : tableName) + '_' + attr + '"'; if (options.schema !== false && tableName && tableName.schema) { enumName = '"' + tableName.schema + '"' + tableName.delimiter + enumName; } return enumName; }, pgListEnums: function(tableName, attrName) { var enumName = '' , schema = tableName && tableName.schema ? tableName.schema : 'public'; if (!!tableName && !!attrName) { enumName = ' AND t.typname=' + this.pgEnumName(tableName, attrName, { schema: false }).replace(/"/g, "'"); } var query = 'SELECT t.typname enum_name, array_agg(e.enumlabel) enum_value FROM pg_type t ' + 'JOIN pg_enum e ON t.oid = e.enumtypid ' + 'JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace ' + "WHERE n.nspname = '" + schema + "'" + enumName + ' GROUP BY 1'; return query; }, pgEnum: function(tableName, attr, dataType, options) { var enumName = this.pgEnumName(tableName, attr) , values; if (dataType.values) { values = "ENUM('" + dataType.values.join("', '") + "')"; } else { values = dataType.toString().match(/^ENUM\(.+\)/)[0]; } var sql = 'CREATE TYPE ' + enumName + ' AS ' + values + ';'; if (!!options && options.force === true) { sql = this.pgEnumDrop(tableName, attr) + sql; } return sql; }, pgEnumAdd: function(tableName, attr, value, options) { var enumName = this.pgEnumName(tableName, attr) , sql = 'ALTER TYPE ' + enumName + ' ADD VALUE ' + this.escape(value); if (!!options.before) { sql += ' BEFORE ' + this.escape(options.before); } else if (!!options.after) { sql += ' AFTER ' + this.escape(options.after); } return sql; }, pgEnumDrop: function(tableName, attr, enumName) { enumName = enumName || this.pgEnumName(tableName, attr); return 'DROP TYPE IF EXISTS ' + enumName + '; '; }, fromArray: function(text) { text = text.replace(/^{/, '').replace(/}$/, ''); var matches = text.match(/("(?:\\.|[^"\\\\])*"|[^,]*)(?:\s*,\s*|\s*$)/ig); if (matches.length < 1) { return []; } matches = matches.map(function(m) { return m.replace(/",$/, '').replace(/,$/, '').replace(/(^"|"$)/, ''); }); return matches.slice(0, -1); }, padInt: function(i) { return (i < 10) ? '0' + i.toString() : i.toString(); }, pgDataTypeMapping: function(tableName, attr, dataType) { return this.dataTypeMapping(tableName, attr, dataType); }, dataTypeMapping: function(tableName, attr, dataType) { if (Utils._.includes(dataType, 'PRIMARY KEY')) { primaryKeys[tableName].push(attr); dataType = dataType.replace(/PRIMARY KEY/, ''); } if (Utils._.includes(dataType, 'SERIAL')) { if (Utils._.includes(dataType, 'BIGINT')) { dataType = dataType.replace(/SERIAL/, 'BIGSERIAL'); dataType = dataType.replace(/BIGINT/, ''); } else { dataType = dataType.replace(/INTEGER/, ''); } dataType = dataType.replace(/NOT NULL/, ''); } if (dataType.match(/^ENUM\(/)) { dataType = dataType.replace(/^ENUM\(.+\)/, this.pgEnumName(tableName, attr)); } return dataType; }, quoteIdentifier: function(identifier, force) { if (identifier === '*') return identifier; if (!force && this.options && this.options.quoteIdentifiers === false) { // default is `true` // In Postgres, if tables or attributes are created double-quoted, // they are also case sensitive. If they contain any uppercase // characters, they must always be double-quoted. This makes it // impossible to write queries in portable SQL if tables are created in // this way. Hence, we strip quotes if we don't want case sensitivity. return Utils.removeTicks(identifier, '"'); } else { return Utils.addTicks(identifier, '"'); } }, /* Escape a value (e.g. a string, number or date) */ escape: function(value, field) { if (value && value._isSequelizeMethod) { return this.handleSequelizeMethod(value); } if (field && field.type && value) { if (field.type.validate) { field.type.validate(value); } } if (Utils._.isObject(value) && field && (field.type instanceof DataTypes.HSTORE || DataTypes.ARRAY.is(field.type, DataTypes.HSTORE))) { if (field.type instanceof DataTypes.HSTORE){ return "'" + hstore.stringify(value) + "'"; } else if (DataTypes.ARRAY.is(field.type, DataTypes.HSTORE)) { return 'ARRAY[' + Utils._.map(value, function(v){return "'" + hstore.stringify(v) + "'::hstore";}).join(',') + ']::HSTORE[]'; } } else if(Utils._.isArray(value) && field && (field.type instanceof DataTypes.RANGE || DataTypes.ARRAY.is(field.type, DataTypes.RANGE))) { if(field.type instanceof DataTypes.RANGE) { // escape single value return "'" + range.stringify(value) + "'"; } else if (DataTypes.ARRAY.is(field.type, DataTypes.RANGE)) { // escape array of ranges return 'ARRAY[' + Utils._.map(value, function(v){return "'" + range.stringify(v) + "'";}).join(',') + ']::' + field.type.toString(); } } else if (value!==null && field && field.type instanceof DataTypes.JSON) { value = JSON.stringify(value); } else if (Array.isArray(value) && field && DataTypes.ARRAY.is(field.type, DataTypes.JSON)) { var jsonType = field.type.type; // type may be JSON or JSONB return 'ARRAY[' + value.map(function (v) { return SqlString.escape(JSON.stringify(v), false, this.options.timezone, this.dialect, field); }, this).join(',') + ']::' + jsonType.key + '[]'; } else if (value && field && field.type instanceof DataTypes.GEOMETRY) { return "ST_GeomFromGeoJSON('" + JSON.stringify(value) + "')"; } return SqlString.escape(value, false, this.options.timezone, this.dialect, field); }, /** * Generates an SQL query that returns all foreign keys of a table. * * @param {String} tableName The name of the table. * @param {String} schemaName The name of the schema. * @return {String} The generated sql query. */ getForeignKeysQuery: function(tableName, schemaName) { return 'SELECT conname as constraint_name, pg_catalog.pg_get_constraintdef(r.oid, true) as condef FROM pg_catalog.pg_constraint r ' + "WHERE r.conrelid = (SELECT oid FROM pg_class WHERE relname = '" + tableName + "' LIMIT 1) AND r.contype = 'f' ORDER BY 1;"; }, /** * Generates an SQL query that removes a foreign key from a table. * * @param {String} tableName The name of the table. * @param {String} foreignKey The name of the foreign key constraint. * @return {String} The generated sql query. */ dropForeignKeyQuery: function(tableName, foreignKey) { return 'ALTER TABLE ' + this.quoteTable(tableName) + ' DROP CONSTRAINT ' + this.quoteIdentifier(foreignKey) + ';'; }, setAutocommitQuery: function(value, options) { if (options.parent) { return; } // POSTGRES does not support setting AUTOCOMMIT = OFF if (!value) { return; } return AbstractQueryGenerator.setAutocommitQuery.call(this, value, options); }, geometrySelect: function(column) { return this.quoteIdentifiers(column); } }; module.exports = Utils._.extend(Utils._.clone(AbstractQueryGenerator), QueryGenerator);
module.exports = { "@id": "/files/ENCFF001REQ/", "@type": ["File", "Item"], "accession": "ENCFF001REQ", "alternate_accessions": [], "dataset": "/experiments/ENCSR999NOF/", "date_created": "2013-06-13", "download_path": "2013/6/14/ENCFF001REQ.fastq.gz", "file_format": "fastq", "href": "/files/ENCFF001REQ/@@download/ENCFF001REQ.fastq.gz", "md5sum": "de9e05ad88fea5664f1c5d90815df360", "output_type": "reads", "platform": require('../platform'), "replicate": "/replicates/ec1ed4db-de5f-481b-a686-261bda0319cb/", "schema_version": "2", "status": "in progress", "submitted_by": "/users/f5b7857d-208e-4acc-ac4d-4c2520814fe1/", "submitted_file_name": "SID38822_AC1HYAACXX_5.txt.gz", "uuid": "e984ec73-0db4-4d30-934d-4cfc49096236" };
/*jslint white: true */ import { templates } from '../templates.js'; var scrollFixedHelper = (function() { /* use strict */ var switchToFixed = function() { $('#backgroundContainer').css('display', 'block'); $('#container').removeClass('searchResultsContainer'); $('#container').addClass('cover'); }; var switchToScroll = function() { $('#backgroundContainer').css('display', 'none'); $('#container').removeClass('cover'); $('#container').addClass('searchResultsContainer'); }; var switchToUserFixed = function() { $('#backgroundContainer').css('display', 'none'); $('#container').removeClass('searchResultsContainer'); $('#container').addClass('cover'); }; return { switchToFixed, switchToScroll, switchToUserFixed }; }()); export { scrollFixedHelper };
import React from 'react'; const HomePage = () => ( <div> <div className='col dm-hero sv-bg-color--blue-800'/> <div className='dm-home-content'> <div className='sv-row'> <div className='sv-column sv-text-center sv-padd-50'> <img height='auto' src='hermes.png' width='220' /> <h6>Hermes for notifications</h6> </div> <div className='sv-column sv-text-center sv-padd-50'> <img height='auto' src='window.png' width='220' /> <h6>Launch Window.</h6> </div> <div className='sv-column sv-text-center sv-padd-50'> <img height='auto' src='all-components.png' width='220' /> <h6>View all components!</h6> </div> </div> </div> <div className='sv-row sv-bg-color--steel-200 sv-no-margins'> <div className='dm-home-synchro'> <div className='sv-row'> <div className='sv-column sv-text-center sv-padd-25'> <a href='https://github.com/Synchro-TEC' rel='noopen' target='_blank'> <img height='auto' src='logo-synchro.png' width='120'/> </a> </div> <div className='sv-column sv-text-center sv-padd-25'> <a href='https://github.com/Synchro-TEC' rel='noopen' target='_blank'> <img height='50' src='syntec.svg' width='auto'/> </a> </div> </div> </div> </div> <div className='dm-credits sv-row sv-bg-color--steel-100 sv-no-margins'> <div className='sv-column sv-padd-10 sv-text-center'> Icons made by <a href='http://www.flaticon.com/authors/freepik' title='Freepik'>Freepik</a> from <a href='http://www.flaticon.com' title='Flaticon'>www.flaticon.com</a> is licensed by <a href='http://creativecommons.org/licenses/by/3.0/' target='_blank' title='Creative Commons BY 3.0'>CC 3.0 BY</a> <br /> <a href='http://www.freepik.com/free-vector/outer-space_797691.htm'>Designed by Freepik</a> </div> </div> </div> ); HomePage.displayName = 'HomePage'; export default HomePage;
'use strict'; var util = require('./lib/util'); exports = module.exports = {}; /* ### Herror ```js function Herror(String message) ``` `Error` class with paths on its stack trace as `<module>@<version>` instead of `node_modules/<module>`. Inherits from the Error class. _arguments_ - `message` type string message for the error _returns_ - a new `error` instance #### usage ```js var Herror = require('herro').Herror; if('something broke'){ throw new Herror('oh, no, you did not!'); } ``` */ exports.Herror = function Herror(message){ if(!(this instanceof Herror)){ return new Herror(message); } this.message = message; Error.captureStackTrace(this, Herror); this.stack = util.formatStack(this.stack); }; util.inherits(exports.Herror, Error); /* ### global ```js function global([Boolean flag]) ``` If `flag` is truthy or `undefined`, it will make all stack traces have `<module>@<version>` instead of `node_modules/<module>`. If `flag` is falsy it will revert stacktraces to their default format. #### usage ```js var herro = require('herro'); herro.global(); // make it global herro.global(false); // go back to the normal stack format ``` */ var prepare = Error.prepareStackTrace; exports.global = function(flag){ if(flag === void 0 || Boolean(flag)){ Error.prepareStackTrace = function(err, stack){ return ( 'Error:' + err.message + '\n' + util.formatStack(stack.join('\n at ')) ); }; } else { Error.prepareStackTrace = prepare; } };
import React from 'react'; import {expect} from 'chai'; import {shallow} from 'enzyme'; import Task from '../../../app/components/Task'; describe('<Task/>', function() { it('renders html with subject and content', () => { const taskJson = {'subject' : 'first task', 'content': 'sample content', 'id': '321'}; const task = shallow(<Task task={taskJson}/>); expect(task.contains('first task')).to.equal(true); expect(task.contains('sample content')).to.equal(true) }); });
YUI.add('event-delegate', function (Y, NAME) { /** * Adds event delegation support to the library. * * @module event * @submodule event-delegate */ var toArray = Y.Array, YLang = Y.Lang, isString = YLang.isString, isObject = YLang.isObject, isArray = YLang.isArray, selectorTest = Y.Selector.test, detachCategories = Y.Env.evt.handles; /** * <p>Sets up event delegation on a container element. The delegated event * will use a supplied selector or filtering function to test if the event * references at least one node that should trigger the subscription * callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {String|node} the element that is the delegation container * @param filter {string|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @static * @for Event */ function delegate(type, fn, el, filter) { var args = toArray(arguments, 0, true), query = isString(el) ? el : null, typeBits, synth, container, categories, cat, i, len, handles, handle; // Support Y.delegate({ click: fnA, key: fnB }, el, filter, ...); // and Y.delegate(['click', 'key'], fn, el, filter, ...); if (isObject(type)) { handles = []; if (isArray(type)) { for (i = 0, len = type.length; i < len; ++i) { args[0] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } else { // Y.delegate({'click', fn}, el, filter) => // Y.delegate('click', fn, el, filter) args.unshift(null); // one arg becomes two; need to make space for (i in type) { if (type.hasOwnProperty(i)) { args[0] = i; args[1] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } } return new Y.EventHandle(handles); } typeBits = type.split(/\|/); if (typeBits.length > 1) { cat = typeBits.shift(); args[0] = type = typeBits.shift(); } synth = Y.Node.DOM_EVENTS[type]; if (isObject(synth) && synth.delegate) { handle = synth.delegate.apply(synth, arguments); } if (!handle) { if (!type || !fn || !el || !filter) { Y.log("delegate requires type, callback, parent, & filter", "warn"); return; } container = (query) ? Y.Selector.query(query, null, true) : el; if (!container && isString(el)) { handle = Y.on('available', function () { Y.mix(handle, Y.delegate.apply(Y, args), true); }, el); } if (!handle && container) { args.splice(2, 2, container); // remove the filter handle = Y.Event._attach(args, { facade: false }); handle.sub.filter = filter; handle.sub._notify = delegate.notifySub; } } if (handle && cat) { categories = detachCategories[cat] || (detachCategories[cat] = {}); categories = categories[type] || (categories[type] = []); categories.push(handle); } return handle; } /** Overrides the <code>_notify</code> method on the normal DOM subscription to inject the filtering logic and only proceed in the case of a match. This method is hosted as a private property of the `delegate` method (e.g. `Y.delegate.notifySub`) @method notifySub @param thisObj {Object} default 'this' object for the callback @param args {Array} arguments passed to the event's <code>fire()</code> @param ce {CustomEvent} the custom event managing the DOM subscriptions for the subscribed event on the subscribing node. @return {Boolean} false if the event was stopped @private @static @since 3.2.0 **/ delegate.notifySub = function (thisObj, args, ce) { // Preserve args for other subscribers args = args.slice(); if (this.args) { args.push.apply(args, this.args); } // Only notify subs if the event occurred on a targeted element var currentTarget = delegate._applyFilter(this.filter, args, ce), //container = e.currentTarget, e, i, len, ret; if (currentTarget) { // Support multiple matches up the the container subtree currentTarget = toArray(currentTarget); // The second arg is the currentTarget, but we'll be reusing this // facade, replacing the currentTarget for each use, so it doesn't // matter what element we seed it with. e = args[0] = new Y.DOMEventFacade(args[0], ce.el, ce); e.container = Y.one(ce.el); for (i = 0, len = currentTarget.length; i < len && !e.stopped; ++i) { e.currentTarget = Y.one(currentTarget[i]); ret = this.fn.apply(this.context || e.currentTarget, args); if (ret === false) { // stop further notifications break; } } return ret; } }; /** Compiles a selector string into a filter function to identify whether Nodes along the parent axis of an event's target should trigger event notification. This function is memoized, so previously compiled filter functions are returned if the same selector string is provided. This function may be useful when defining synthetic events for delegate handling. Hosted as a property of the `delegate` method (e.g. `Y.delegate.compileFilter`). @method compileFilter @param selector {String} the selector string to base the filtration on @return {Function} @since 3.2.0 @static **/ delegate.compileFilter = Y.cached(function (selector) { return function (target, e) { return selectorTest(target._node, selector, (e.currentTarget === e.target) ? null : e.currentTarget._node); }; }); /** Regex to test for disabled elements during filtering. This is only relevant to IE to normalize behavior with other browsers, which swallow events that occur to disabled elements. IE fires the event from the parent element instead of the original target, though it does preserve `event.srcElement` as the disabled element. IE also supports disabled on `<a>`, but the event still bubbles, so it acts more like `e.preventDefault()` plus styling. That issue is not handled here because other browsers fire the event on the `<a>`, so delegate is supported in both cases. @property _disabledRE @type {RegExp} @protected @since 3.8.1 **/ delegate._disabledRE = /^(?:button|input|select|textarea)$/i; /** Walks up the parent axis of an event's target, and tests each element against a supplied filter function. If any Nodes, including the container, satisfy the filter, the delegated callback will be triggered for each. Hosted as a protected property of the `delegate` method (e.g. `Y.delegate._applyFilter`). @method _applyFilter @param filter {Function} boolean function to test for inclusion in event notification @param args {Array} the arguments that would be passed to subscribers @param ce {CustomEvent} the DOM event wrapper @return {Node|Node[]|undefined} The Node or Nodes that satisfy the filter @protected **/ delegate._applyFilter = function (filter, args, ce) { var e = args[0], container = ce.el, // facadeless events in IE, have no e.currentTarget target = e.target || e.srcElement, match = [], isContainer = false; // Resolve text nodes to their containing element if (target.nodeType === 3) { target = target.parentNode; } // For IE. IE propagates events from the parent element of disabled // elements, where other browsers swallow the event entirely. To normalize // this in IE, filtering for matching elements should abort if the target // is a disabled form control. if (target.disabled && delegate._disabledRE.test(target.nodeName)) { return match; } // passing target as the first arg rather than leaving well enough alone // making 'this' in the filter function refer to the target. This is to // support bound filter functions. args.unshift(target); if (isString(filter)) { while (target) { isContainer = (target === container); if (selectorTest(target, filter, (isContainer ? null: container))) { match.push(target); } if (isContainer) { break; } target = target.parentNode; } } else { // filter functions are implementer code and should receive wrappers args[0] = Y.one(target); args[1] = new Y.DOMEventFacade(e, container, ce); while (target) { // filter(target, e, extra args...) - this === target if (filter.apply(args[0], args)) { match.push(target); } if (target === container) { break; } target = target.parentNode; args[0] = Y.one(target); } args[1] = e; // restore the raw DOM event } if (match.length <= 1) { match = match[0]; // single match or undefined } // remove the target args.shift(); return match; }; /** * Sets up event delegation on a container element. The delegated event * will use a supplied filter to test if the callback should be executed. * This filter can be either a selector string or a function that returns * a Node to use as the currentTarget for the event. * * The event object for the delegated event is supplied to the callback * function. It is modified slightly in order to support all properties * that may be needed for event delegation. 'currentTarget' is set to * the element that matched the selector string filter or the Node returned * from the filter function. 'container' is set to the element that the * listener is delegated from (this normally would be the 'currentTarget'). * * Filter functions will be called with the arguments that would be passed to * the callback function, including the event object as the first parameter. * The function should return false (or a falsey value) if the success criteria * aren't met, and the Node to use as the event's currentTarget and 'this' * object if they are. * * @method delegate * @param type {string} the event type to delegate * @param fn {function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {string|node} the element that is the delegation container * @param filter {string|function} a selector that must match the target of the * event or a function that returns a Node or false. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.delegate = Y.Event.delegate = delegate; }, '3.10.3', {"requires": ["node-base"]});
version https://git-lfs.github.com/spec/v1 oid sha256:f27e59b0bfe421134163f7323ca346e4fcada41db0dbbadc3576cd562f8ebca4 size 181947
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiR2V0U3dpbW1lckJ5UG9vbFJlc3BvbnNlLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vc3JjL21vZGVscy9HZXRTd2ltbWVyQnlQb29sUmVzcG9uc2UudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9
import React, { Component, PropTypes } from 'react'; import Button from 'remotedev-app/lib/components/Button'; import MdHelp from 'react-icons/lib/md/help'; import FindReplace from 'react-icons/lib/md/find-replace'; import RefreshIcon from 'react-icons/lib/md/refresh'; import styles from 'remotedev-app/lib/styles'; const headerStyles = { refreshButton: { position: 'absolute', top: 0, left: 0, }, select: { background: 'none', border: 'none', color: 'white', outline: 'none', }, }; class NumberButton extends Component { static propTypes = { defaultValue: PropTypes.number, onClick: PropTypes.func, numbers: PropTypes.array.isRequired, } constructor(props) { super(props); const value = props.defaultValue === undefined ? 1 : props.defaultValue; this.state = { value: value.toString() }; this.onNumberChange = this.onNumberChange.bind(this); this.onClickWithNumber = this.onClickWithNumber.bind(this); } onNumberChange(e) { this.setState({ value: e.target.value.toString() }); e.stopPropagation(); } onClickWithNumber(e) { this.props.onClick(parseInt(this.state.value, 10)); } stopPropagation(e) { e.stopPropagation(); } render() { const { numbers, children, ...other } = this.props; const { value } = this.state; const options = numbers.map(n => <option value={n} key={n}>{n}</option>); return ( <Button {...other} onClick={this.onClickWithNumber} > {children[0]} &nbsp; <select style={headerStyles.select} onClick={(e) => e.stopPropagation()} value={value} onChange={this.onNumberChange} > {options} </select> &nbsp; {children[1]} </Button> ); } } export default function Header({ onRefresh, onHelp, onPaintWorst }) { return ( <header style={styles.buttonBar}> <Button style={headerStyles.refreshButton} Icon={RefreshIcon} onClick={onRefresh} >Refresh Selector Graph</Button> <Button Icon={MdHelp} onClick={onHelp} >Help</Button> <NumberButton Icon={FindReplace} onClick={onPaintWorst} numbers={[1, 2, 3, 5, 10]} > <span>Select</span> <span>Most Recomputed</span> </NumberButton> </header> ); } Header.propTypes = { onRefresh: PropTypes.func, onHelp: PropTypes.func, onPaintWorst: PropTypes.func, };
/*! * Copyright (c) 2015-2019 Cisco Systems, Inc. See LICENSE file. */ /* eslint-disable no-underscore-dangle */ import {assert} from '@webex/test-helper-chai'; import MockWebex from '@webex/test-helper-mock-webex'; import sinon from '@webex/test-helper-sinon'; import Conversation from '@webex/internal-plugin-conversation'; describe('plugin-conversation', () => { describe('Conversation', () => { let webex; const convoUrl = 'https://conv-test.wbx2.com/conversation'; beforeEach(() => { webex = new MockWebex({ children: { conversation: Conversation } }); webex.internal.device.getServiceUrl = sinon.stub().returns(Promise.resolve(convoUrl)); }); describe('#_inferConversationUrl', () => { const testConvo = {test: 'convo'}; it('Returns given convo if no id', () => webex.internal.conversation._inferConversationUrl(testConvo) .then((convo) => { assert.notCalled(webex.internal.feature.getFeature); assert.notCalled(webex.internal.device.getServiceUrl); assert.equal(convo.test, 'convo'); })); describe('HA is disabled', () => { beforeEach(() => { webex.internal.feature.getFeature = sinon.stub().returns(Promise.resolve(false)); testConvo.id = 'id1'; }); it('returns unmodified convo if URL is defined', () => { testConvo.url = 'http://example.com'; return webex.internal.conversation._inferConversationUrl(testConvo) .then((convo) => { assert.called(webex.internal.feature.getFeature); assert.notCalled(webex.internal.device.getServiceUrl); assert.equal(convo.url, 'http://example.com'); }); }); it('builds URL if not defined', () => { delete testConvo.url; return webex.internal.conversation._inferConversationUrl(testConvo) .then((convo) => { assert.called(webex.internal.feature.getFeature); assert.called(webex.internal.device.getServiceUrl); assert.equal(convo.url, `${convoUrl}/conversations/id1`); }); }); }); describe('HA is enabled', () => { beforeEach(() => { webex.internal.feature.getFeature = sinon.stub().returns(Promise.resolve(true)); testConvo.id = 'id1'; }); it('builds URL if already defined', () => { testConvo.url = 'https://example.com'; return webex.internal.conversation._inferConversationUrl(testConvo) .then((convo) => { assert.called(webex.internal.feature.getFeature); assert.called(webex.internal.device.getServiceUrl); assert.equal(convo.url, `${convoUrl}/conversations/id1`); }); }); it('builds URL if not defined', () => { delete testConvo.url; return webex.internal.conversation._inferConversationUrl(testConvo) .then((convo) => { assert.called(webex.internal.feature.getFeature); assert.called(webex.internal.device.getServiceUrl); assert.equal(convo.url, `${convoUrl}/conversations/id1`); }); }); }); }); }); });
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Web Client * Copyright (C) 2008, 2009, 2010 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ ZmDocsEditView = function(parent, className, posStyle, controller, deferred) { className = className || "ZmDocsEditView"; DwtComposite.call(this, {parent:parent, className:className, posStyle:DwtControl.ABSOLUTE_STYLE}); this._buttons = {}; this._controller = controller; this._docMgr = new ZmDocletMgr(); this._initialize(); this.getHtmlElement().style.overflow = "auto"; }; ZmDocsEditView.prototype = new DwtComposite; ZmDocsEditView.prototype.construction = ZmDocsEditView; ZmDocsEditView.ZD_VALUE = "ZD"; ZmDocsEditView.APP_ZIMBRA_DOC = "application/x-zimbra-doc"; ZmDocsEditView.prototype.getController = function() { return this._controller; }; ZmDocsEditView.prototype._focusPageInput = function() { if (this.warngDlg) { this.warngDlg.popdown(); } this._buttons.fileName.focus(); }; ZmDocsEditView.prototype._showVersionDescDialog = function(callback){ if(!this._descDialog){ var dlg = this._descDialog = new DwtDialog({parent:appCtxt.getShell()}); var id = Dwt.getNextId(); dlg.setContent(AjxTemplate.expand("briefcase.Briefcase#VersionNotes", {id: id})); dlg.setTitle(ZmMsg.addVersionNotes); this._versionNotes = document.getElementById(id+"_notes"); } ZmDocsEditApp.fileInfo.desc = ""; this._versionNotes.value = ""; this._descDialog.setButtonListener(DwtDialog.OK_BUTTON, new AjxListener(this, this._okCallback, callback)); this._descDialog.popup(); this._versionNotes.focus(); }; ZmDocsEditView.prototype._okCallback = function(callback){ ZmDocsEditApp.fileInfo.desc = this._versionNotes.value; if(callback){ callback.run(); } this._descDialog.popdown(); }; ZmDocsEditView.prototype.save = function(force){ var fileName = this._buttons.fileName.getValue(); var message = this._docMgr.checkInvalidDocName(fileName); // Ignore save if document is not dirty var _docModified = ZmDocsEditApp._controller._isDirty(); var _docNameModified = fileName && (fileName != ZmDocsEditApp.fileInfo.name); if(!_docModified && !_docNameModified) { if(this._saveClose){ window.close(); } else { return; } } ZmDocsEditApp.fileInfo.descEnabled = this._getVersionNotesChk().checked; if (message) { var style = DwtMessageDialog.WARNING_STYLE; var dialog = this.warngDlg = appCtxt.getMsgDialog(); dialog.setMessage(message, style); dialog.popup(); dialog.registerCallback(DwtDialog.OK_BUTTON, this._focusPageInput, this); return false; } if(!force && this._getVersionNotesChk().checked){ this._showVersionDescDialog(new AjxCallback(this, this.save, true)); return false; } ZmDocsEditApp.fileInfo.name = fileName; ZmDocsEditApp.fileInfo.content = this._editor.getContent(); ZmDocsEditController.savedDoc = ZmDocsEditApp.fileInfo.content; ZmDocsEditApp.fileInfo.contentType = ZmDocsEditApp.APP_ZIMBRA_DOC; this._docMgr.setSaveCallback(new AjxCallback(this, this._saveHandler)); this._docMgr.saveDocument(ZmDocsEditApp.fileInfo); }; ZmDocsEditView.prototype._saveHandler = function(files, conflicts) { if(conflicts){ var formatter = new AjxMessageFormat(ZmMsg.saveConflictDoc); appCtxt.setStatusMsg(formatter.format(files[0].name), ZmStatusView.LEVEL_WARNING); } else { if (files && files.length > 0) { ZmDocsEditApp.fileInfo.id = files[0].id; ZmDocsEditApp.fileInfo.version = files[0].ver; var item = this.loadData(ZmDocsEditApp.fileInfo.id); if(item && !item.rest){ //TODO: Change this code to construct a rest url item.rest = ZmDocsEditApp.restUrl; } if(item != null) { ZmDocsEditApp.fileInfo = item; this.setFooterInfo(item); } var wAppCtxt = null; if(window.isRestView) { wAppCtxt = top.appCtxt; } else { wAppCtxt = window.opener && window.opener.appCtxt; } appCtxt.setStatusMsg(ZmMsg.savedDoc, ZmStatusView.LEVEL_INFO); if(this._saveClose){ window.close(); } } } }; ZmDocsEditView.prototype.setFooterInfo = function(item){ if(!this._locationEl) return; var content; var rootId = ZmOrganizer.getSystemId(ZmOrganizer.ID_ROOT); if (item.folderId == rootId) { content = appCtxt.getById(item.folderId).name; }else { var separator = "&nbsp;&raquo;&nbsp;"; var a = [ ]; var folderId = item.folderId; while ((folderId != null) && (folderId != rootId)) { var wAppCtxt = null; if(window.isRestView) { wAppCtxt = top.appCtxt; } else { wAppCtxt = window.opener && window.opener.appCtxt; } var docs = wAppCtxt && wAppCtxt.getById(folderId); if(!docs) { break; } a.unshift(docs.name); if(!docs.parent) { break; } folderId = docs.parent.id; if (folderId != rootId) { a.unshift(separator); } } content = a.join(""); } this._locationEl.innerHTML = content; this._versionEl.innerHTML = (item.version ? item.version : ""); this._authorEl.innerHTML = (item.creator ? item.creator : ""); this._modifiedEl.innerHTML = (item.createDate ? item.createDate : ""); }; ZmDocsEditView.prototype.loadData = function(id) { return this._docMgr.getItemInfo({id:id}); }; ZmDocsEditView.prototype.loadDoc = function(item) { var content = this._docMgr.fetchDocumentContent(item); if(this._editor) { this._editor.setEditorHTML(content ? content : "<br/>"); } }; ZmDocsEditView.prototype.setPendingContent = function(content) { this._pendingContent = content; }; ZmDocsEditView.prototype.getPendingContent = function() { return this._pendingContent; }; ZmDocsEditView.prototype.onLoadContent = function(ed) { var pendingContent = this.getPendingContent(); if (pendingContent != null) { ed.setContent(pendingContent, {format: "raw"}); this.setPendingContent(null); } }; ZmDocsEditView.prototype._initialize = function() { var toolbar = this._toolbar = new DwtToolBar({parent:this, className:"ZDToolBar", cellSpacing:2, posStyle:DwtControl.RELATIVE_STYLE}); this._createToolbar(toolbar); /* commented for bug:40022 var toolbar2 = this._toolbar2 = new DwtToolBar({parent:this, className:"ZDUtilToolBar",cellSpacing:0,posStyle:DwtControl.RELATIVE_STYLE}); toolbar2.getHtmlElement().setAttribute("align","center"); this._createToolbar2(toolbar2); */ var obj = this; function handleContentLoad(ed) { obj.onLoadContent(ed); }; var iFrame = this._iframe = document.createElement("iframe"); iFrame.id = Dwt.getNextId(); iFrame.className = "ZDEditor"; iFrame.setAttribute("border", "0", false); iFrame.setAttribute("frameborder", "0", false); iFrame.setAttribute("vspace", "0", false); iFrame.setAttribute("autocomplete", "off", false); iFrame.setAttribute("allowtransparency", "true", false); iFrame.onload = AjxCallback.simpleClosure(this._stealFocus, this, iFrame.id); //if(window.isTinyMCE) { //temp check if(false) { var htmlEl = this.getHtmlElement(); var divEl = document.createElement("div"); divEl.setAttribute("style","padding:3px; height:98%"); var textEl = document.createElement("textarea"); textEl.setAttribute("id", "tiny_mce_content"); textEl.setAttribute("name","tiny_mce_content"); textEl.setAttribute("rows", "100"); //textEl.setAttribute("cols", "99"); textEl.setAttribute("style", "width:99.5%; height:97%;"); divEl.appendChild(textEl); htmlEl.appendChild(divEl); var urlParts = AjxStringUtil.parseURL(location.href); //important: tinymce doesn't handle url parsing well when loaded from REST URL - override baseURL/baseURI //to fix this tinymce.baseURL = window.contextPath + "/tiny_mce/3.2.6/"; if(tinymce.EditorManager) tinymce.EditorManager.baseURI = new tinymce.util.URI(urlParts.protocol + "://" + urlParts.authority + tinymce.baseURL); tinyMCE.init({ // General options mode : "exact", elements: "tiny_mce_content", theme : "advanced", relative_urls: false, remove_script_host : false, plugins : "pagebreak,ztable,safari,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template", // Theme options theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect,|,cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor", theme_advanced_buttons2 : "ztablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen,|,insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak", theme_advanced_buttons3 : "", theme_advanced_toolbar_location : "top", theme_advanced_toolbar_align : "left", theme_advanced_statusbar_location : "none", theme_advanced_resizing : true, force_br_newlines : true, forced_root_block : '', force_p_newlines : false, // Example content CSS (should be your site CSS) content_css : "css/content.css", //enabling browser spell check gecko_spellcheck : true, // Drop lists for link/image/media/template dialogs template_external_list_url : "lists/template_list.js", external_link_list_url : "lists/link_list.js", external_image_list_url : "lists/image_list.js", media_external_list_url : "lists/media_list.js", setup : function(ed) { ed.onLoadContent.add(handleContentLoad); } }); } else { var editor = this._editor = new ZmDocsEditor({parent:this, iframe: this._iframe, controller: this._controller, className:"ZDEditDiv"}); this._editorTb = editor._createToolbar(this); editor.getHtmlElement().appendChild(iFrame); editor._initIframe(); var iContentWindow = this._iframe.contentWindow; this._doc = iContentWindow ? iContentWindow.document : null; this._pushIframeContent(this._iframe); editor._enableDesignMode(editor._getIframeDoc()); this.addFooter(); } }; ZmDocsEditView.prototype._stealFocus = function(iFrameId) { if(AjxEnv.isFirefox3up) { var iframe = document.getElementById(iFrameId); if (iframe) { iframe.blur(); iframe.focus(); } } } ZmDocsEditView.prototype.addFooter = function() { var el = this.getHtmlElement(); var div = this._footerEl = document.createElement("div"); var locationId = Dwt.getNextId(); var versionId = Dwt.getNextId(); var authorId = Dwt.getNextId(); var modifiedId = Dwt.getNextId(); var footer = [ '<table cellpadding="0" cellspacing="0" class="ZmHtmlEditorFooter">', '<tr>', '<td>',ZmMsg.locationLabel,' <span id="',locationId,'"></span></td>', '<td>',ZmMsg.versionLabel,' <span id="',versionId,'"></span></td>', '<td>',ZmMsg.authorLabel,' <span id="',authorId,'"></span></td>', '<td>',ZmMsg.modifiedOnLabel,' <span id="',modifiedId,'"></span></td>', '</tr>', '</table>' ]; div.innerHTML = footer.join(""); el.appendChild(div); this._locationEl = document.getElementById(locationId); this._versionEl = document.getElementById(versionId); this._authorEl = document.getElementById(authorId); this._modifiedEl = document.getElementById(modifiedId); }; ZmDocsEditView.prototype._saveButtonListener = function(ev) { this._saveClose = false; this.save(); }; ZmDocsEditView.prototype._saveCloseButtonListener = function(ev) { this._saveClose = true; this.save(); }; ZmDocsEditView.prototype._tbActionListener = function(ev) { var action = ev.item.getData(ZmDocsEditView.ZD_VALUE); if(action == "NewDocument") { var fileInfo = ZmDocsEditApp.fileInfo; var url = ZmDocletMgr.getEditURLForContentType(fileInfo.contentType) + "?l="+fileInfo.folderId + (window.isTinyMCE ? "&editor=tinymce" : "") + (window.skin ? "&skin="+window.skin : "") + "&localeId=" + AjxEnv.DEFAULT_LOCALE; var winName = (new Date()).getTime().toString(); window.open(url, winName); } else if(action = "OpenDocument") { /*if(!this._openDocDlg) { this._openDocDlg = new ZmOpenDocDialog(appCtxt.getShell()); } this._openDocDlg.popup();*/ } }; ZmDocsEditView.prototype._createToolbar2 = function(toolbar) { var params = {parent:toolbar,style:DwtButton.TOGGLE_STYLE}; var listener = new AjxListener(this, this._quickTbActionListener); var b = this._buttons.docElTb = new DwtToolBarButton(params); b.setText(ZmMsg.zd_docElements); b.setData(ZmDocsEditView.ZD_VALUE, "DocElements"); b.addSelectionListener(listener); b.setToolTipContent(ZmMsg.zd_docElementsTT); new DwtControl({parent:toolbar, className:"vertSep"}); b = this._buttons.quickTb = new DwtToolBarButton(params); b.setText(ZmMsg.zd_docQuickTables); b.setData(ZmDocsEditView.ZD_VALUE, "QuickTables"); b.addSelectionListener(listener); b.setToolTipContent(ZmMsg.zd_docQuickTablesTT); /*new DwtControl({parent:toolbar, className:"vertSep"}); b = this._buttons.chartTb = new DwtToolBarButton(params); b.setText(ZmMsg.zd_docCharts); b.setData(ZmDocsEditView.ZD_VALUE, "QuickCharts"); b.addSelectionListener(listener); b.setToolTipContent(ZmMsg.zd_docChartsTT); new DwtControl({parent:toolbar, className:"vertSep"}); b = this._buttons.smartTb = new DwtToolBarButton(params); b.setText(ZmMsg.zd_docSmartArt); b.setData(ZmDocsEditView.ZD_VALUE, "SmartArt"); b.addSelectionListener(listener); b.setToolTipContent(ZmMsg.zd_docSmartArtTT);*/ this._createQuickTables(); this._createDocElements(); }; ZmDocsEditView.prototype._quickTbActionListener = function(ev) { var action = ev.item.getData(ZmDocsEditView.ZD_VALUE); if(action == "QuickTables") { if(this._toolbar3.getVisible()) { this._toolbar3.setVisible(false); } else { this._toolbar3.setVisible(true); } this._toolbar4.setVisible(false); } else if(action == "DocElements") { if(this._toolbar4.getVisible()) { this._toolbar4.setVisible(false); } else { this._toolbar4.setVisible(true); } this._toolbar3.setVisible(false); } else { this._toolbar4.setVisible(false); this._toolbar3.setVisible(false); } }; ZmDocsEditView.prototype._insertQuickTables = function(ev) { var action = ev.item.getData(ZmDocsEditView.ZD_VALUE); var doc = this._editor._getIframeDoc(); var spanEl = doc.createElement("span"); if(action == "QuickTable1") { var tableHtml = []; tableHtml.push('<table width="90%" cellspacing="1" cellpadding="3" align="center"><tbody><tr><th style="width:33%; background-color:rgb(237,37,37);"></br></th><th style="width:33%; background-color:rgb(237,37,37);" ></br></th><th style="width:33%; background-color:rgb(237,37,37);"></br></td></tr>' + '<tr><td style="background-color:rgb(255,197,197);"></br></td><td style="background-color:rgb(255,197,197);"></br></td><td style="background-color:rgb(255,197,197);"></br></td></tr>' + '<tr><td></br></td><td></br></td><td></br></td></tr>' + '<tr><td style="background-color:rgb(255,197,197);"></br></td><td style="background-color:rgb(255,197,197);"></br></td><td style="background-color:rgb(255,197,197);"></br></td></tr>' + '<tr><td></br></td><td></br></td><td></br></td></tr>' + '<tr><td style="background-color:rgb(255,197,197);"></br></td><td style="background-color:rgb(255,197,197);"></br></td><td style="background-color:rgb(255,197,197);"></br></td></tr>' + '<tr><td></br></td><td></br></td><td></br></td></tr></tbody></table>'); spanEl.innerHTML = tableHtml.join(""); } else if(action == "QuickTable2") { var tableHtml = []; tableHtml.push('<table width="90%" cellspacing="1" cellpadding="3" align="center"><tbody><tr><th style="background-color:rgb(115,170,270);"></br></th></tr>' + '<tr><td style="background-color:rgb(198,220,238);"></br></td></tr>' + '<tr><td></br></td></tr>' + '<tr><td style="background-color:rgb(198,220,238);"></br></td></tr>' + '<tr><td></br></td></tr>' + '<tr><td style="background-color:rgb(198,220,238);"></br></td></tr>' + '<tr><td></br></td></tr></tbody></table>'); spanEl.innerHTML = tableHtml.join("");; } else if(action == "QuickTable3") { var tableHtml = []; tableHtml.push('<table width="90%" cellspacing="1" cellpadding="3" align="center"><tbody><tr><th style="width:33%; background-color:rgb(128,128,128);"></br></th><th style="width:33%; background-color:rgb(128,128,128);" ></br></th><th style="width:33%; background-color:rgb(128,128,128);"></br></td></tr>' + '<tr><td colspan="1" rowspan="5" style="background-color:rgb(196,196,196);"></br></td><td style="background-color:rgb(234,234,234);"></br></td><td style="background-color:rgb(234,234,234);"></br></td></tr>' + '<tr><td style="background-color:rgb(234,234,234);"></br></td><td style="background-color:rgb(234,234,234);"></br></td></tr>' + '<tr><td style="background-color:rgb(234,234,234);"></br></td><td style="background-color:rgb(234,234,234);"></br></td></tr>' + '<tr><td style="background-color:rgb(234,234,234);"></br></td><td style="background-color:rgb(234,234,234);"></br></td></tr>' + '<tr><td style="background-color:rgb(234,234,234);"></br></td><td style="background-color:rgb(234,234,234);"></br></td></tr>' + '<tr><td style="background-color:rgb(234,234,234);"></br></td><td style="background-color:rgb(234,234,234);"></br></td><td style="background-color:rgb(234,234,234);"></br></td></tr></tbody></table>'); spanEl.innerHTML = tableHtml.join(""); } else if(action == "QuickTable4") { var tableHtml = []; tableHtml.push('<table width="90%" cellspacing="1" cellpadding="3" align="center"><tbody><tr><th style="width:33%; background-color:rgb(1,171,37);"></br></th><th style="width:33%; background-color:rgb(1,171,37);" ></br></th><th style="width:33%; background-color:rgb(1,171,37);"></br></td></tr>' + '<tr><td style="background-color:rgb(216,255,225);"></br></td><td style="background-color:rgb(216,255,225);"></br></td><td style="background-color:rgb(216,255,225);"></br></td></tr>' + '<tr><td style="background-color:rgb(216,255,225);"></br></td><td style="background-color:rgb(216,255,225);"></br></td><td style="background-color:rgb(216,255,225);"></br></td></tr>' + '<tr><td style="background-color:rgb(216,255,225);"></br></td><td style="background-color:rgb(216,255,225);"></br></td><td style="background-color:rgb(216,255,225);"></br></td></tr>' + '<tr><td style="background-color:rgb(216,255,225);"></br></td><td style="background-color:rgb(216,255,225);"></br></td><td style="background-color:rgb(216,255,225);"></br></td></tr>' + '<tr><td style="background-color:rgb(216,255,225);"></br></td><td style="background-color:rgb(216,255,225);"></br></td><td style="background-color:rgb(216,255,225);"></br></td></tr>' + '<tr><td style="background-color:rgb(216,255,225);"></br></td><td style="background-color:rgb(216,255,225);"></br></td><td style="background-color:rgb(216,255,225);"></br></td></tr></tbody></table>'); spanEl.innerHTML = tableHtml.join(""); } var p = doc.createElement("br"); var df = doc.createDocumentFragment(); df.appendChild(p); df.appendChild(spanEl.getElementsByTagName("table")[0]); df.appendChild(p.cloneNode(true)); this._editor._insertNodeAtSelection(df); }; ZmDocsEditView.prototype._insertDocElements = function(ev) { var action = ev.item.getData(ZmDocsEditView.ZD_VALUE); var doc = this._editor._getIframeDoc(); var spanEl = doc.createElement("span"); if(action == "DocElement2") { spanEl.innerHTML = '<table width="90%" cellspacing="1" cellpadding="3" align="center" style="border:1px solid rgb(0,0,0);"><tbody><tr height="40"><td style="background-color: rgb(204, 0, 0);"><br/></td></tr><tr><td><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/>' + '<br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><div _moz_dirty="" style="margin-left: 80px;">' + '<font size="7" _moz_dirty="">[ Document Title ]</font><br _moz_dirty=""/><font size="3" _moz_dirty="" style="color: rgb(192, 192, 192);">&nbsp;[ Sub Title]</font><br _moz_dirty=""/></div><br _moz_dirty=""/>' + '<br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/>' + '<br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><div _moz_dirty="" style="margin-left: 76%;">&nbsp;' + '<img src="http://www.zimbra.com/_media/logos/zimbra_logo.gif" alt="http://www.zimbra.com/_media/logos/zimbra_logo.gif" _moz_dirty="" style="width: 211px; height: 101px;"/>' + '<br _moz_dirty=""/></div><br _moz_dirty=""/><br _moz_dirty=""/></td></tr></tbody></table>'; } else if(action == "DocElement3") { spanEl.innerHTML = '<table width="90%" cellspacing="1" cellpadding="3" align="center"><tbody><tr><td style="border: 1px solid rgb(0, 0, 0);"><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/>' + '<br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><div _moz_dirty="" style="margin-left: 80px;">' + '<font size="7" _moz_dirty="">[ Document Title ]</font><br _moz_dirty=""/><font size="3" _moz_dirty="" style="color: rgb(192, 192, 192);">&nbsp;[ Sub Title]</font><br _moz_dirty=""/></div><br _moz_dirty=""/>' + '<br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/>' + '<br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><br _moz_dirty=""/><div _moz_dirty="" style="margin-left: 80%;">&nbsp;' + '<img src="http://yhoo.client.shareholder.com/press/images/yahoobang-small.gif" alt="http://yhoo.client.shareholder.com/press/images/yahoobang-small.gif" _moz_dirty="" style="width: 156px; height: 91px;"/>' + '<br _moz_dirty=""/></div><br _moz_dirty=""/><br _moz_dirty=""/></td></tr></tbody></table>'; } var p = doc.createElement("br"); var df = doc.createDocumentFragment(); df.appendChild(p); df.appendChild(spanEl.getElementsByTagName("table")[0]); df.appendChild(p.cloneNode(true)); this._editor._insertNodeAtSelection(df); }; ZmDocsEditView.prototype._createDocElements = function() { var toolbar4 = this._toolbar4 = new DwtToolBar({parent:this, className:"ZDQtbToolBar",cellSpacing:0,posStyle:DwtControl.RELATIVE_STYLE}); var params = {parent:toolbar4,style:DwtButton.ALWAYS_FLAT}; var listener = new AjxListener(this, this._insertDocElements); var b = new DwtToolBarButton(params); b.setImage("DocElement2"); b.setData(ZmDocsEditView.ZD_VALUE, "DocElement2"); b.addSelectionListener(listener); b.setToolTipContent(ZmMsg.zd_docQuickInsert); b = new DwtToolBarButton(params); b.setImage("DocElement3"); b.setData(ZmDocsEditView.ZD_VALUE, "DocElement3"); b.addSelectionListener(listener); b.setToolTipContent(ZmMsg.zd_docQuickInsert); this._toolbar4.setVisible(false); }; ZmDocsEditView.prototype._createQuickTables = function() { var toolbar3 = this._toolbar3 = new DwtToolBar({parent:this, className:"ZDQtbToolBar",cellSpacing:0,posStyle:DwtControl.RELATIVE_STYLE}); var params = {parent:toolbar3,style:DwtButton.ALWAYS_FLAT}; var listener = new AjxListener(this, this._insertQuickTables); var b = new DwtToolBarButton(params); b.setImage("QuickTable1"); b.setData(ZmDocsEditView.ZD_VALUE, "QuickTable1"); b.addSelectionListener(listener); b.setToolTipContent(ZmMsg.zd_docQuickInsert); b.getHtmlElement().style.padding = "6px"; b = new DwtToolBarButton(params); b.setImage("QuickTable2"); b.setData(ZmDocsEditView.ZD_VALUE, "QuickTable2"); b.addSelectionListener(listener); b.setToolTipContent(ZmMsg.zd_docQuickInsert); b.getHtmlElement().style.padding = "6px"; b = new DwtToolBarButton(params); b.setImage("QuickTable3"); b.setData(ZmDocsEditView.ZD_VALUE, "QuickTable3"); b.addSelectionListener(listener); b.setToolTipContent(ZmMsg.zd_docQuickInsert); b.getHtmlElement().style.padding = "6px"; b = new DwtToolBarButton(params); b.setImage("QuickTable4"); b.setData(ZmDocsEditView.ZD_VALUE, "QuickTable4"); b.addSelectionListener(listener); b.setToolTipContent(ZmMsg.zd_docQuickInsert); b.getHtmlElement().style.padding = "6px"; this._toolbar3.setVisible(false); }; ZmDocsEditView.prototype._createToolbar = function(toolbar) { var params = {parent:toolbar}; b = this._buttons.fileName = new DwtInputField({parent:toolbar, size:20}); var b = this._buttons.saveFile = new DwtToolBarButton(params); b.setImage("Save"); b.setText(ZmMsg.save); b.setData(ZmDocsEditView.ZD_VALUE, "Save"); b.addSelectionListener(new AjxListener(this, this._saveButtonListener)); b.setToolTipContent(ZmMsg.save); new DwtControl({parent:toolbar, className:"vertSep"}); var b = this._buttons.saveAndCloseFile = new DwtToolBarButton(params); b.setImage("Save"); b.setText(ZmMsg.saveClose); b.setData(ZmDocsEditView.ZD_VALUE, "Save&Close"); b.addSelectionListener(new AjxListener(this, this._saveCloseButtonListener)); b.setToolTipContent(ZmMsg.saveClose); toolbar.addFiller(); b = new DwtComposite({parent:toolbar}); b.setContent([ "<div style='white-space: nowrap; padding-right:10px;'>", "<input type='checkbox' name='enableDesc' id='enableDesc' value='enableVersions'>", "&nbsp; <label for='enableDesc'>", ZmMsg.enableVersionNotes, "</label>", "</div>" ].join('')); /* var listener = new AjxListener(this, this._tbActionListener); new DwtControl({parent:toolbar, className:"vertSep"}); b = this._buttons.clipboardCopy = new DwtToolBarButton(params); b.setImage("Copy"); b.setData(ZmDocsEditView.ZD_VALUE, "ClipboardCopy"); b.addSelectionListener(listener); b.setToolTipContent(ZmMsg.copy); b = this._buttons.clipboardCut = new DwtToolBarButton(params); b.setImage("Cut"); b.setData(ZmDocsEditView.ZD_VALUE, "ClipboardCut"); b.addSelectionListener(listener); b.setToolTipContent(ZmMsg.cut); b = this._buttons.clipboardPaste = new DwtToolBarButton(params); b.setImage("Paste"); b.setData(ZmDocsEditView.ZD_VALUE, "ClipboardPaste"); b.addSelectionListener(listener); b.setToolTipContent(ZmMsg.paste); new DwtControl({parent:toolbar, className:"vertSep"}); b = this._buttons.newDocument = new DwtToolBarButton(params); b.setText(ZmMsg.newDocument); b.setImage("Doc"); b.setData(ZmDocsEditView.ZD_VALUE, "NewDocument"); b.addSelectionListener(listener); b.setToolTipContent(ZmMsg.briefcaseCreateNewDocument); b = this._buttons.clipboardPaste = new DwtToolBarButton(params); b.setText("Open Document"); b.setData(ZmDocsEditView.ZD_VALUE, "OpenDocument"); b.addSelectionListener(listener); b.setToolTipContent(ZmMsg.paste); */ }; ZmDocsEditView.prototype._getVersionNotesChk = function(){ if(!this._verNotesChk){ this._verNotesChk = document.getElementById('enableDesc'); } return this._verNotesChk; } ZmDocsEditView.prototype.enableVersionNotes = function(enable){ this._getVersionNotesChk().checked = !!enable; }; ZmDocsEditView.prototype._pushIframeContent = function(iframeN) { if(!iframeN) return; var iContentWindow = iframeN.contentWindow; var doc = iContentWindow ? iContentWindow.document : null; if(doc) { doc.open(); var html = []; html.push('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">'); html.push('<html>'); //html.push('<link href="' + window.appContextPath + '/css/skin,slides.css?locale=' + AjxEnv.DEFAULT_LOCALE + '" rel="stylesheet" type="text/css" />'); html.push('<body><br _moz_dirty=""/></body>'); html.push('</html>'); doc.write(html.join("")); doc.close(); iContentWindow.focus(); } };
import Player from './player'; import Darts501Game from './games/501'; export default { Player, games: { Darts501Game } };
define(['jquery','datepicker'], function (jQuery) { /* Serbian i18n for the jQuery UI date picker plugin. */ /* Written by Dejan Dimić. */ jQuery(function($){ $.datepicker.regional['sr-SR'] = { closeText: 'Zatvori', prevText: '&#x3C;', nextText: '&#x3E;', currentText: 'Danas', monthNames: ['Januar','Februar','Mart','April','Maj','Jun', 'Jul','Avgust','Septembar','Oktobar','Novembar','Decembar'], monthNamesShort: ['Jan','Feb','Mar','Apr','Maj','Jun', 'Jul','Avg','Sep','Okt','Nov','Dec'], dayNames: ['Nedelja','Ponedeljak','Utorak','Sreda','Četvrtak','Petak','Subota'], dayNamesShort: ['Ned','Pon','Uto','Sre','Čet','Pet','Sub'], dayNamesMin: ['Ne','Po','Ut','Sr','Če','Pe','Su'], weekHeader: 'Sed', dateFormat: 'dd/mm/yy', firstDay: 1, isRTL: false, showMonthAfterYear: false, yearSuffix: ''}; $.datepicker.setDefaults($.datepicker.regional['sr-SR']); }); });
class Room { constructor() { this.remotes = [] } addRemote(remote) { this.remotes.push(remote) } removeRemote(remote) { this.remotes.splice(this.remotes.indexOf(remote), 1) } broadcast(data) { this.remotes.forEach((remote) => { remote.send(data) }) } broadcastExcept(exceptRemote, data) { this.remotes.forEach((remote) => { if (remote == exceptRemote) return remote.send(data) }) } } module.exports = Room
'use strict'; module.exports = { set: function (v) { this.setProperty('shape-rendering', v); }, get: function () { return this.getPropertyValue('shape-rendering'); }, enumerable: true };
import { Extension } from "@tiptap/core"; import { Plugin } from 'prosemirror-state'; import { DOMParser, Schema } from 'prosemirror-model'; export const Paste = Extension.create({ name: 'paste', addOptions: () => ({ schema: null, }), addProseMirrorPlugins() { const schema = getNormalizedSchema( this.options.schema, this.editor.schema ); const parser = DOMParser.fromSchema(schema); return [ new Plugin({ props: { clipboardParser: parser, }, }) ] } }); // needed to keep same references of node/mark types function getNormalizedSchema(target, source) { const schema = new Schema(target.spec); schema.nodes = Object.fromEntries( Object.entries(source.nodes).filter(([key]) => !!target.nodes[key]) ); schema.marks = Object.fromEntries( Object.entries(source.marks).filter(([key]) => !!target.marks[key]) ); return schema; }
module.exports={A:{A:{"2":"L H G E A B jB"},B:{"1":"BB","2":"C D d K I N J"},C:{"1":"0 1 6 7 8 9 f g h i j k l m n o M q r s t u v w x y z AB CB DB EB O GB HB","2":"2 3 5 gB IB F L H G E A B C D d K I N J P Q R S T U V W X Y Z a b c e aB ZB"},D:{"1":"6 9 AB CB DB EB O GB HB TB PB NB mB OB LB BB QB RB","2":"0 1 2 3 5 7 8 F L H G E A B C D d K I N J P Q R S T U V W X Y Z a b c e f g h i j k l m n o M q r s t u v w x y z"},E:{"2":"2 F L H G E SB KB UB VB WB XB","132":"4 A B C D YB p bB"},F:{"1":"0 1 r s t u v w x y z","2":"3 4 5 E B C K I N J P Q R S T U V W X Y Z a b c e f g h i j k l m n o M q cB dB eB fB p FB hB"},G:{"2":"G KB iB JB kB lB MB nB oB pB","132":"D qB rB sB tB uB vB"},H:{"2":"wB"},I:{"1":"O","2":"IB F xB yB zB 0B JB 1B 2B"},J:{"2":"H A"},K:{"1":"M","2":"4 A B C p FB"},L:{"1":"LB"},M:{"1":"O"},N:{"2":"A B"},O:{"1":"3B"},P:{"1":"7B 8B","2":"F 4B 5B 6B"},Q:{"2":"9B"},R:{"2":"AC"},S:{"1":"BC"}},B:5,C:"Scroll methods on elements (scroll, scrollTo, scrollBy)"};
var graph = require("fbgraph"); var memory = []; var READY = false; var fbtoken = "{facebook-token}"; var yoobro_pageid = "1039852779358258"; graph.setAccessToken(fbtoken); function getPhotos(url) { url = url || (yoobro_pageid + "/photos/uploaded?fields=source&limit=500"); console.log("getting..."); graph.get(url, function (err, res) { if (err) return console.error(err); memory = memory.concat(res.data); if (res.paging && res.paging.next) { getPhotos(res.paging.next); } else { memory = _.uniq(memory); READY = true; console.log("done"); } }); } getPhotos(); module.exports = { getRandom: function () { if (!READY) { return false; } return _.sample(memory).source; } };
var fs = require('fs'); var config = JSON.parse(fs.readFileSync('config.json')); var speakers = JSON.parse(fs.readFileSync('sprekers.json')); var mongoose = require('mongoose'); var User = require('./models/User'); var Ticket = require('./models/Ticket'); mongoose.connect(config.mongodb.url); for (var i = speakers.length - 1; i >= 0; i--) { var speaker = speakers[i]; console.log(speaker); var user = new User({ firstname: speaker.firstname, surname: speaker.surname, vereniging: 'partner', email: speaker.email, vegetarian: false, ticket: speaker.ticketcode, }); console.log(user); user.save(); Ticket.findById(speaker.ticketcode).then(ticket =>{ ticket.ownedBy = user; ticket.save(); }) }
import { connect } from 'react-redux' import { setTabBarState,setTabBarIsShow,setScreenHeight } from './../../../reducers/ReactTabBar_reducer' import { setNetworkData } from './../../../reducers/Common_reducer' import NetworkView from '../components/NetworkView' const mapDispatchtoProps = { setTabBarState, setTabBarIsShow, setScreenHeight, setNetworkData } const mapStateToProps = (state) => ({ tabBarState: state.ReactTabBar.tabBarState, tabBarIsShow: state.ReactTabBar.tabBarIsShow, screenHeight: state.ReactTabBar.screenHeight, networkData: state.CommonReducer.networkData }) export default connect(mapStateToProps, mapDispatchtoProps)(NetworkView)
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M22 2H2v20l4-4h16V2zM5 14l3.5-4.5 2.5 3.01L14.5 8l4.5 6H5z" }), 'MmsSharp');
/** * @module color/mixer */ /** The name of the module. */ export const name = 'mixer'; /** The most recent blended color. */ export var lastColor = null; /** * Blend two colors together. * @param {string} color1 - The first color, in hexidecimal format. * @param {string} color2 - The second color, in hexidecimal format. * @return {string} The blended color. */ export function blend(color1, color2) {} // convert color to array of RGB values (0-255) function rgbify(color) {} export { /** * Get the red, green, and blue values of a color. * @function * @param {string} color - A color, in hexidecimal format. * @returns {Array} An array of the red, green, and blue values, * each ranging from 0 to 255. */ rgbify as toRgb }
var firebaseModule = require('../routes/firebase'); var firebase = firebaseModule.firebase; var user_data = []; var chore_data = []; var home_data = []; var ref = firebase.database().ref('users'); ref.on("value", function (snapshot) { user_data = snapshot.val(); }); var ref2 = firebase.database().ref('defaultChores'); ref2.on('value', function (snapshot) { chore_data = snapshot.val(); }); var homeRef = firebase.database().ref('homes'); homeRef.on('value', function (snapshot) { home_data = snapshot.val(); }); exports.saveCustomChores = function (req, res) { var current_user = req.session.current_user; var data = req.body.saveinput; console.log(data); var newString = data.split('-').join(' '); var fin = newString.split(','); var uname = current_user['email'].replace(".", ""); var prevData = []; for (home in home_data) { if (home == user_data[uname]['homeName']) { console.log(home); console.log(user_data[uname]['homeName']); prevData = home_data[home]; } } var home = user_data[uname]['homeName']; console.log(prevData); console.log(fin); var storeRef = firebase.database().ref('chores/' + home).set(prevData.concat(fin)); if (current_user != null) { var email = current_user['email']; email = email.replace(".", ""); if (user_data[email] != null) res.render('home', user_data[email]); else res.render("login"); } };
'use strict'; const events = require('events'); const url = require('url'); const debug = require('debug')('sockjs:server'); const listener = require('./listener'); const webjs = require('./webjs'); const pkg = require('../package.json'); class Server extends events.EventEmitter { constructor(user_options) { super(); this.options = Object.assign( { prefix: '', transports: [ 'eventsource', 'htmlfile', 'jsonp-polling', 'websocket', 'websocket-raw', 'xhr-polling', 'xhr-streaming' ], response_limit: 128 * 1024, faye_server_options: null, jsessionid: false, heartbeat_delay: 25000, disconnect_delay: 5000, log() {}, sockjs_url: 'https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js' }, user_options ); // support old options.websocket setting if (user_options.websocket === false) { const trs = new Set(this.options.transports); trs.delete('websocket'); trs.delete('websocket-raw'); this.options.transports = Array.from(trs.values()); } this._prefixMatches = () => true; if (this.options.prefix) { // remove trailing slash, but not leading this.options.prefix = this.options.prefix.replace(/\/$/, ''); this._prefixMatches = (requrl) => url.parse(requrl).pathname.startsWith(this.options.prefix); } this.options.log( 'debug', `SockJS v${pkg.version} bound to ${JSON.stringify(this.options.prefix)}` ); this.handler = webjs.generateHandler(this, listener.generateDispatcher(this.options)); } attach(server) { this._rlisteners = this._installListener(server, 'request'); this._ulisteners = this._installListener(server, 'upgrade'); } detach(server) { if (this._rlisteners) { this._removeListener(server, 'request', this._rlisteners); this._rlisteners = null; } if (this._ulisteners) { this._removeListener(server, 'upgrade', this._ulisteners); this._ulisteners = null; } } _removeListener(server, eventName, listeners) { server.removeListener(eventName, this.handler); listeners.forEach((l) => server.on(eventName, l)); } _installListener(server, eventName) { const listeners = server.listeners(eventName).filter((x) => x !== this.handler); server.removeAllListeners(eventName); server.on(eventName, (req, res, head) => { if (this._prefixMatches(req.url)) { debug('prefix match', eventName, req.url, this.options.prefix); this.handler(req, res, head); } else { listeners.forEach((l) => l.call(server, req, res, head)); } }); return listeners; } } module.exports = Server;
var mongoose = require('mongoose'); var mongoosastic = require('mongoosastic'); var Schema = mongoose.Schema; var shortid = require('shortid'); var ListSchema = new Schema({ _id: {type: String, index: { unique: true } ,'default': shortid.generate, es_indexed:true}, name: {type: String, es_indexed:true}, creator: {type: String, index: true, required: true, es_indexed:true}, contributors: { type : Array , "default" : [], es_type:'string', es_indexed:true }, info: {type: String, es_indexed:true}, tags: String, created: {type: Date, default: Date.now}, upvotes: Number, public: {type: Boolean, default: true, es_indexed:true} }); ListSchema.plugin(mongoosastic); var List = mongoose.model('List', ListSchema); List.createMapping(function(err, mapping){ if(err){ console.log('error creating mapping (you can safely ignore this)'); console.log(err); }else{ console.log('elasticsearch Lists connected.'); console.log(mapping); } }); module.exports = { List: List };
import React from 'react'; import Icon from '../Icon'; export default class PowerSettingsNewIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M26 6h-4v20h4V6zm9.67 4.33l-2.83 2.83C35.98 15.73 38 19.62 38 24c0 7.73-6.27 14-14 14s-14-6.27-14-14c0-4.38 2.02-8.27 5.16-10.84l-2.83-2.83C8.47 13.63 6 18.52 6 24c0 9.94 8.06 18 18 18s18-8.06 18-18c0-5.48-2.47-10.37-6.33-13.67z"/></svg>;} };
var update = { map: function(map){ var createPattern, start; if (map == 'Loopy') { canvas.drawImage(backgroundImage1, 0, 0, 800, 500); map = game.map.slice(1); start = game.map[0]; canvas.beginPath(); canvas.moveTo(start.x, start.y); map.forEach(function(cur, i) { canvas.lineTo(cur.x, cur.y); }); canvas.stroke(); canvas.lineWidth = 50; createPattern = canvas.createPattern(floorPatternMap1, "repeat"); canvas.strokeStyle = createPattern; } else if (map == 'Backtrack') { canvas.drawImage(backgroundImage2, 0, 0, 800, 500); map = game.map.slice(1); start = game.map[0]; canvas.beginPath(); canvas.moveTo(start.x, start.y); map.forEach(function(cur, i) { canvas.lineTo(cur.x, cur.y); }); canvas.stroke(); canvas.lineWidth = 50; createPattern = canvas.createPattern(floorPatternMap2, "repeat"); canvas.strokeStyle = createPattern; } else if (map == 'Dash') { canvas.drawImage(backgroundImage3, 0, 0, 800, 500); map = game.map.slice(1); start = game.map[0]; canvas.beginPath(); canvas.moveTo(start.x, start.y); map.forEach(function(cur, i) { canvas.lineTo(cur.x, cur.y); }); canvas.stroke(); canvas.lineWidth = 50; createPattern = canvas.createPattern(floorPatternMap3, "repeat"); canvas.strokeStyle = createPattern; } canvas.beginPath(); canvas.moveTo(start.x, start.y); map.forEach(function(cur, i) { canvas.lineTo(cur.x, cur.y); }); canvas.stroke(); } } function IsInRange(targetPoint, sourcePoint, radius) { var distance = (sourcePoint.x - targetPoint.x) * (sourcePoint.x - targetPoint.x) + (sourcePoint.y - targetPoint.y) * (sourcePoint.y - targetPoint.y); return distance < radius * radius; } function MoveObject(object, target, speed) { var distancex = target.x - object.x, distancey = target.y - object.y, angle = Math.atan2(distancey, distancex); object.x += speed * Math.cos(angle); object.y += speed * Math.sin(angle); return Math.abs(distancex) + Math.abs(distancey) < 2; } function GetRandom(maxNumber){ return Math.floor(Math.random() * (maxNumber + 1)); } /////////////////////////////////////////////////////////////////////////////// // Elements /////////////////////////////////////////////////////////////////////////////// function Element(id){ return document.getElementById(id); } window.ui = { timer: document.getElementById("control-timer"), cash: document.getElementById("control-cash"), lives: document.getElementById("control-lives"), wave: document.getElementById("control-wave"), fps: document.getElementById("control-fps"), nav: ["start"], action: {}, bind: function(evt, elems, fn) { Array.prototype.slice.call(elems).forEach(function(elem) { elem.addEventListener(evt, fn, false); }); }, page: function(name) { if (name) { ui.nav.unshift(name); } else { ui.page(ui.nav[1]); return; } Array.prototype.slice.call(document.getElementById("pages").children).forEach(function(elem) { if (elem.id !== "pages-overlay") { elem.style.display = "none"; } }); document.getElementById("pages-" + name).style.display = "block"; }, panel: function(name) { Array.prototype.slice.call(document.getElementById("control-left").children).forEach(function(elem) { elem.style.display = "none"; }); document.getElementById("control-" + name).style.display = "block"; } }; $('#loopy').click(function () { $(this).parents('html').addClass('loopy'); }); $('#backtrack').click(function () { $(this).parents('html').addClass('backtrack'); }); $('#dash').click(function () { $(this).parents('html').addClass('dash'); }); var about = document.getElementById("about"), aboutRecipient = document.getElementById("about-text"), hotkeys = document.getElementById("hotkeys"), hotkeysRecipient = document.getElementById("hotkeys-text"), authors = document.getElementById("authors"), authorsRecipient = document.getElementById("authors-text"), credits = document.getElementById("credits"), creditsRecipient = document.getElementById("credits-text"), instructions = document.getElementById("instructions"), instructionsRecipient = document.getElementById("instructions-text"); about.addEventListener("click",function(){ aboutRecipient.style.display = 'block'; hotkeysRecipient.style.display = 'none'; authorsRecipient.style.display = 'none'; creditsRecipient.style.display = 'none'; instructionsRecipient.style.display = 'none'; },false ); aboutRecipient.addEventListener("click",function(){ aboutRecipient.style.display = 'none'; },false ); hotkeys.addEventListener("click",function(){ hotkeysRecipient.style.display = 'block'; aboutRecipient.style.display = 'none'; authorsRecipient.style.display = 'none'; creditsRecipient.style.display = 'none'; instructionsRecipient.style.display = 'none'; },false ); hotkeysRecipient.addEventListener("click",function(){ hotkeysRecipient.style.display = 'none'; },false ); authors.addEventListener("click",function(){ var recipient = document.getElementById("authors-text"); authorsRecipient.style.display = 'block'; aboutRecipient.style.display = 'none'; hotkeysRecipient.style.display = 'none'; creditsRecipient.style.display = 'none'; instructionsRecipient.style.display = 'none'; },false ); authorsRecipient.addEventListener("click",function(){ authorsRecipient.style.display = 'none'; },false ); credits.addEventListener("click",function(){ var recipient = document.getElementById("credits-text"); creditsRecipient.style.display = 'block'; aboutRecipient.style.display = 'none'; authorsRecipient.style.display = 'none'; hotkeysRecipient.style.display = 'none'; instructionsRecipient.style.display = 'none'; },false ); creditsRecipient.addEventListener("click",function(){ creditsRecipient.style.display = 'none'; },false ); instructions.addEventListener("click",function(){ var recipient = document.getElementById("instructions-text"); instructionsRecipient.style.display = 'block'; aboutRecipient.style.display = 'none'; authorsRecipient.style.display = 'none'; creditsRecipient.style.display = 'none'; hotkeysRecipient.style.display = 'none'; },false ); instructionsRecipient.addEventListener("click",function(){ instructionsRecipient.style.display = 'none'; },false );
// Sprite is just a static namespace of generally useful functions relating to sprites. Sprite = {}; Sprite.fixPositionAnchor = function(sprite) { sprite.x = sprite.x + (sprite.width / 2); sprite.y = sprite.y + (sprite.height / 2); } // This function will check all three conditions of being on the ground (since for some reason Phaser does this, no idea why) and returns // true or false. The sprite has to have body enabled for this to work. Sprite.checkGround = function(sprite) { if(sprite.body.onFloor()) return true; if(sprite.body.blocked.down) return true; if(sprite.body.touching.down) return true; return false }
// @flow import * as t from "@babel/types"; import type { TraversalAncestors, TraversalHandler } from "@babel/types"; import { parse } from "@babel/parser"; import { codeFrameColumns } from "@babel/code-frame"; import type { TemplateOpts, ParserOpts } from "./options"; import type { Formatter } from "./formatters"; export type Metadata = { ast: BabelNodeFile, placeholders: Array<Placeholder>, placeholderNames: Set<string>, }; type PlaceholderType = "string" | "param" | "statement" | "other"; export type Placeholder = {| name: string, resolve: BabelNodeFile => { parent: BabelNode, key: string, index?: number }, type: PlaceholderType, isDuplicate: boolean, |}; const PATTERN = /^[_$A-Z0-9]+$/; export default function parseAndBuildMetadata<T>( formatter: Formatter<T>, code: string, opts: TemplateOpts, ): Metadata { const { placeholderWhitelist, placeholderPattern, preserveComments, syntacticPlaceholders, } = opts; const ast = parseWithCodeFrame(code, opts.parser, syntacticPlaceholders); t.removePropertiesDeep(ast, { preserveComments, }); formatter.validate(ast); const syntactic = { placeholders: [], placeholderNames: new Set(), }; const legacy = { placeholders: [], placeholderNames: new Set(), }; const isLegacyRef = { value: undefined }; t.traverse(ast, (placeholderVisitorHandler: TraversalHandler<*>), { syntactic, legacy, isLegacyRef, placeholderWhitelist, placeholderPattern, syntacticPlaceholders, }); return { ast, ...(isLegacyRef.value ? legacy : syntactic), }; } function placeholderVisitorHandler( node: BabelNode, ancestors: TraversalAncestors, state: MetadataState, ) { let name; if (t.isPlaceholder(node)) { if (state.syntacticPlaceholders === false) { throw new Error( "%%foo%%-style placeholders can't be used when " + "'.syntacticPlaceholders' is false.", ); } else { name = ((node: any).name: BabelNodeIdentifier).name; state.isLegacyRef.value = false; } } else if (state.isLegacyRef.value === false || state.syntacticPlaceholders) { return; } else if (t.isIdentifier(node) || t.isJSXIdentifier(node)) { name = ((node: any): BabelNodeIdentifier).name; state.isLegacyRef.value = true; } else if (t.isStringLiteral(node)) { name = ((node: any): BabelNodeStringLiteral).value; state.isLegacyRef.value = true; } else { return; } if ( !state.isLegacyRef.value && (state.placeholderPattern != null || state.placeholderWhitelist != null) ) { // This check is also in options.js. We need it there to handle the default // .syntacticPlaceholders behavior. throw new Error( "'.placeholderWhitelist' and '.placeholderPattern' aren't compatible" + " with '.syntacticPlaceholders: true'", ); } if ( state.isLegacyRef.value && (state.placeholderPattern === false || !(state.placeholderPattern || PATTERN).test(name)) && !state.placeholderWhitelist?.has(name) ) { return; } // Keep our own copy of the ancestors so we can use it in .resolve(). ancestors = ancestors.slice(); const { node: parent, key } = ancestors[ancestors.length - 1]; let type: PlaceholderType; if ( t.isStringLiteral(node) || t.isPlaceholder(node, { expectedNode: "StringLiteral" }) ) { type = "string"; } else if ( (t.isNewExpression(parent) && key === "arguments") || (t.isCallExpression(parent) && key === "arguments") || (t.isFunction(parent) && key === "params") ) { type = "param"; } else if (t.isExpressionStatement(parent) && !t.isPlaceholder(node)) { type = "statement"; ancestors = ancestors.slice(0, -1); } else if (t.isStatement(node) && t.isPlaceholder(node)) { type = "statement"; } else { type = "other"; } const { placeholders, placeholderNames } = state.isLegacyRef.value ? state.legacy : state.syntactic; placeholders.push({ name, type, resolve: ast => resolveAncestors(ast, ancestors), isDuplicate: placeholderNames.has(name), }); placeholderNames.add(name); } function resolveAncestors(ast: BabelNodeFile, ancestors: TraversalAncestors) { let parent: BabelNode = ast; for (let i = 0; i < ancestors.length - 1; i++) { const { key, index } = ancestors[i]; if (index === undefined) { parent = (parent: any)[key]; } else { parent = (parent: any)[key][index]; } } const { key, index } = ancestors[ancestors.length - 1]; return { parent, key, index }; } type MetadataState = { syntactic: { placeholders: Array<Placeholder>, placeholderNames: Set<string>, }, legacy: { placeholders: Array<Placeholder>, placeholderNames: Set<string>, }, isLegacyRef: { value: boolean | void }, placeholderWhitelist: Set<string> | void, placeholderPattern: RegExp | false | void, syntacticPlaceholders: boolean | void, }; function parseWithCodeFrame( code: string, parserOpts: ParserOpts, syntacticPlaceholders?: boolean, ): BabelNodeFile { const plugins = (parserOpts.plugins || []).slice(); if (syntacticPlaceholders !== false) { plugins.push("placeholders"); } parserOpts = { allowReturnOutsideFunction: true, allowSuperOutsideMethod: true, sourceType: "module", ...parserOpts, plugins, }; try { // $FlowFixMe - The parser AST is not the same type as the babel-types type. return parse(code, parserOpts); } catch (err) { const loc = err.loc; if (loc) { err.message += "\n" + codeFrameColumns(code, { start: loc }); err.code = "BABEL_TEMPLATE_PARSE_ERROR"; } throw err; } }
import get from 'lodash.get'; import { PROJECT_LIST_LOCK, PROJECT_LIST_OK, PROJECT_LIST_FAIL, } from './_actions'; const initialState = { error : '', locked: false, data : {}, }; export default (state = initialState, action) => { switch (action.type) { case PROJECT_LIST_LOCK: return { ...state, error : false, save_error : false, locked : true }; case PROJECT_LIST_OK: let data = get(action, "data.data", {}); return { save_error : false, error : false, locked : false, data : data, }; case PROJECT_LIST_FAIL: return { ...state, save_error : false, error : action.error, locked : false }; default: return state; } }
const assert = require('assert'); const modulePath = './../src/index'; const logtify = require('./../src/index'); const ConsoleSubscriber = require('./../src/subscribers/console-link'); const WinstonAdapter = require('./../src/adapters/winston'); describe('Logger stream ', () => { beforeEach(() => { delete require.cache[require.resolve(modulePath)]; }); afterEach(() => { delete require.cache[require.resolve(modulePath)]; const { streamBuffer } = logtify; streamBuffer.adapters = {}; streamBuffer.subscribers = []; }); before(() => { assert.equal(typeof logtify, 'function'); this.NODE_ENV = process.env.NODE_ENV; this.CONSOLE_LOGGING = process.env.CONSOLE_LOGGING; this.BUGSNAG_LOGGING = process.env.BUGSNAG_LOGGING; this.LOGENTRIES_LOGGING = process.env.LOGENTRIES_LOGGING; }); after(() => { process.env.NODE_ENV = this.NODE_ENV; process.env.CONSOLE_LOGGING = this.CONSOLE_LOGGING; process.env.BUGSNAG_LOGGING = this.BUGSNAG_LOGGING; process.env.LOGENTRIES_LOGGING = this.LOGENTRIES_LOGGING; }); it('should initialize when undefined config is given ', () => { const logtifyInstance = logtify(undefined); assert(logtifyInstance); const { stream } = logtifyInstance; assert.equal(typeof stream, 'object'); assert.equal(typeof stream.settings, 'object'); assert.equal(typeof stream.Message, 'function'); assert.equal(typeof stream.Subscriber, 'function'); assert.equal(typeof stream.log, 'function'); assert.equal(typeof stream.subscribe, 'function'); }); it('should initialize when null config is given ', () => { const logtifyInstance = logtify(null); assert(logtifyInstance); const { stream } = logtifyInstance; assert.equal(typeof stream, 'object'); assert.equal(typeof stream.settings, 'object'); assert.equal(typeof stream.Message, 'function'); assert.equal(typeof stream.Subscriber, 'function'); assert.equal(typeof stream.log, 'function'); assert.equal(typeof stream.subscribe, 'function'); }); it('should initialize when empty config is given', () => { const logtifyInstance = logtify({}); const { stream } = logtifyInstance; assert.equal(typeof stream, 'object'); assert.equal(typeof stream.settings, 'object'); assert.equal(typeof stream.Message, 'function'); assert.equal(typeof stream.Subscriber, 'function'); assert.equal(typeof stream.log, 'function'); assert.equal(typeof stream.subscribe, 'function'); }); it('should allow user to reconfigure the module', () => { let logtifyInstance = logtify({ hello: 'world' }); assert(logtifyInstance); assert.equal(logtifyInstance.stream.settings.hello, 'world'); logtifyInstance = logtify({ hello: 'everyone' }); assert.equal(logtifyInstance.stream.settings.hello, 'everyone'); }); it('should behave as a singleton if config was not provided', () => { let logtifyInstance = logtify({ hello: 'world' }); assert(logtifyInstance); assert.equal(logtifyInstance.stream.settings.hello, 'world'); logtifyInstance = logtify(); assert(logtifyInstance); assert.equal(logtifyInstance.stream.settings.hello, 'world'); }); it('should support custom subscribers', () => { const { streamBuffer } = logtify; streamBuffer.addAdapter({ name: 'unicorn', class: WinstonAdapter }); streamBuffer.addSubscriber(ConsoleSubscriber); streamBuffer.addSubscriber(ConsoleSubscriber); streamBuffer.addSubscriber(ConsoleSubscriber); const { stream, logger, unicorn } = logtify({}); assert(stream); assert(logger); assert(unicorn); assert.equal(stream.subscribersCount, 4); }); it('should not let adapters override existing ones', () => { const { streamBuffer } = logtify; streamBuffer.addAdapter({ name: 'stream', class: WinstonAdapter }); streamBuffer.addAdapter({ name: 'unicorn', class: WinstonAdapter }); const { stream, logger, unicorn } = logtify({}); assert(stream); assert(logger); assert(unicorn); }); it('should be able to unbind adapter', () => { const { streamBuffer } = logtify; streamBuffer.addAdapter({ name: 'stream', class: WinstonAdapter }); streamBuffer.addAdapter({ name: 'unicorn', class: WinstonAdapter }); let { stream, unicorn } = logtify({}); assert(stream); assert(unicorn); stream.unbindAdapter('unicorn'); unicorn = logtify().unicorn; // eslint-disable-line stream = logtify().stream; // eslint-disable-line assert.equal(unicorn, undefined); assert.notEqual(stream, undefined); }); it('should not be able to unbind non adapter object', () => { const { stream } = logtify({}); assert(stream); stream.unbindAdapter('stream'); assert(stream); }); it('should skip null undefined or empty object subscriber', () => { const { streamBuffer } = logtify; streamBuffer.addSubscriber(null); streamBuffer.addSubscriber(undefined); const { stream } = logtify({}); assert.equal(stream.subscribersCount, 1); }); it('should throw if subscriber is not valid', () => { try { const { streamBuffer } = logtify; streamBuffer.addSubscriber({ handle: () => {} }); logtify({}); } catch (e) { assert(e instanceof Error); } }); it('should change prototype of pre-configured subscribers', () => { class MySubscriber { constructor(settings, utility) { this.settings = settings; this.utility = utility; } handle(message) { this.next(message); } next() {} link(next) { this.nextLink = next; } } const settings = { SOME_SECRET: 'powerpuffgirls' }; const { streamBuffer } = logtify; streamBuffer.addSubscriber({ config: settings, class: MySubscriber }); const { stream } = logtify({}); assert.equal(stream.subscribersCount, 2); }); it('should not break down if null is logged (console logging is on)', () => { const { stream, logger } = logtify({}); stream.log(null, null); assert(logger); }); it('should be configured according to the preset', () => { const stream1 = logtify({ presets: ['dial-once'] }).stream; assert.equal(stream1.settings.CONSOLE_LOGGING, true); assert.equal(stream1.settings.BUGSNAG_LOGGING, false); assert.equal(stream1.settings.LOGENTRIES_LOGGING, false); process.env.NODE_ENV = 'staging'; const { stream, logger } = logtify({ presets: ['dial-once'] }); assert.equal(stream.settings.CONSOLE_LOGGING, false); assert.equal(stream.settings.BUGSNAG_LOGGING, true); assert.equal(stream.settings.LOGENTRIES_LOGGING, true); assert.equal(stream.subscribersCount, 1); assert(logger); assert(logger.info); stream.log(null, null); }); });