How to use settings method in fMBT

Best Python code snippet using fMBT_python

jquery.joyride-2.1.js

Source:jquery.joyride-2.1.js Github

copy

Full Screen

1 /*2 * jQuery Foundation Joyride Plugin 2.13 * http://foundation.zurb.com4 * Copyright 2013, ZURB5 * Free to use under the MIT license.6 * http://www.opensource.org/licenses/mit-license.php7*/8/*jslint unparam: true, browser: true, indent: 2 */9;(function ($, window, undefined) {10 'use strict';11 var defaults = {12 'version' : '2.1',13 'tipLocation' : 'bottom', // 'top' or 'bottom' in relation to parent14 'nubPosition' : 'auto', // override on a per tooltip bases15 'scroll' : true, // whether to scroll to tips16 'scrollSpeed' : 300, // Page scrolling speed in milliseconds17 'timer' : 0, // 0 = no timer , all other numbers = timer in milliseconds18 'autoStart' : false, // true or false - false tour starts when restart called19 'startTimerOnClick' : true, // true or false - true requires clicking the first button start the timer20 'startOffset' : 0, // the index of the tooltip you want to start on (index of the li)21 'nextButton' : true, // true or false to control whether a next button is used22 'tipAnimation' : 'fade', // 'pop' or 'fade' in each tip23 'pauseAfter' : [], // array of indexes where to pause the tour after24 'tipAnimationFadeSpeed': 300, // when tipAnimation = 'fade' this is speed in milliseconds for the transition25 'cookieMonster' : false, // true or false to control whether cookies are used26 'cookieName' : 'joyride', // Name the cookie you'll use27 'cookieDomain' : false, // Will this cookie be attached to a domain, ie. '.notableapp.com'28 'cookiePath' : false, // Set to '/' if you want the cookie for the whole website29 'localStorage' : false, // true or false to control whether localstorage is used30 'localStorageKey' : 'joyride', // Keyname in localstorage31 'tipContainer' : 'body', // Where will the tip be attached32 'modal' : false, // Whether to cover page with modal during the tour33 'expose' : false, // Whether to expose the elements at each step in the tour (requires modal:true)34 'postExposeCallback' : $.noop, // A method to call after an element has been exposed35 'preRideCallback' : $.noop, // A method to call before the tour starts (passed index, tip, and cloned exposed element)36 'postRideCallback' : $.noop, // A method to call once the tour closes (canceled or complete)37 'preStepCallback' : $.noop, // A method to call before each step38 'postStepCallback' : $.noop, // A method to call after each step39 'template' : { // HTML segments for tip layout40 'link' : '<a href="#close" class="joyride-close-tip">X</a>',41 'timer' : '<div class="joyride-timer-indicator-wrap"><span class="joyride-timer-indicator"></span></div>',42 'tip' : '<div class="joyride-tip-guide"><span class="joyride-nub"></span></div>',43 'wrapper' : '<div class="joyride-content-wrapper" role="dialog"></div>',44 'button' : '<a href="#" class="joyride-next-tip"></a>',45 'modal' : '<div class="joyride-modal-bg"></div>',46 'expose' : '<div class="joyride-expose-wrapper"></div>',47 'exposeCover': '<div class="joyride-expose-cover"></div>'48 }49 },50 Modernizr = Modernizr || false,51 settings = {},52 methods = {53 init : function (opts) {54 return this.each(function () {55 if ($.isEmptyObject(settings)) {56 settings = $.extend(true, defaults, opts);57 // non configurable settings58 settings.document = window.document;59 settings.$document = $(settings.document);60 settings.$window = $(window);61 settings.$content_el = $(this);62 settings.$body = $(settings.tipContainer);63 settings.body_offset = $(settings.tipContainer).position();64 settings.$tip_content = $('> li', settings.$content_el);65 settings.paused = false;66 settings.attempts = 0;67 settings.tipLocationPatterns = {68 top: ['bottom'],69 bottom: [], // bottom should not need to be repositioned70 left: ['right', 'top', 'bottom'],71 right: ['left', 'top', 'bottom']72 };73 // are we using jQuery 1.7+74 methods.jquery_check();75 // can we create cookies?76 if (!$.isFunction($.cookie)) {77 settings.cookieMonster = false;78 }79 // generate the tips and insert into dom.80 if ( (!settings.cookieMonster || !$.cookie(settings.cookieName) ) &&81 (!settings.localStorage || !methods.support_localstorage() || !localStorage.getItem(settings.localStorageKey) ) ) {82 settings.$tip_content.each(function (index) {83 methods.create({$li : $(this), index : index});84 });85 // show first tip86 if(settings.autoStart)87 {88 if (!settings.startTimerOnClick && settings.timer > 0) {89 methods.show('init');90 methods.startTimer();91 } else {92 methods.show('init');93 }94 }95 }96 settings.$document.on('click.joyride', '.joyride-next-tip, .joyride-modal-bg', function (e) {97 e.preventDefault();98 if (settings.$li.next().length < 1) {99 methods.end();100 } else if (settings.timer > 0) {101 clearTimeout(settings.automate);102 methods.hide();103 methods.show();104 methods.startTimer();105 } else {106 methods.hide();107 methods.show();108 }109 });110 settings.$document.on('click.joyride', '.joyride-close-tip', function (e) {111 e.preventDefault();112 methods.end(true /* isAborted */);113 });114 settings.$window.on('resize.joyride', function (e) {115 if(settings.$li){116 if(settings.exposed && settings.exposed.length>0){117 var $els = $(settings.exposed);118 $els.each(function(){119 var $this = $(this);120 methods.un_expose($this);121 methods.expose($this);122 });123 }124 if (methods.is_phone()) {125 methods.pos_phone();126 } else {127 methods.pos_default();128 }129 }130 });131 } else {132 methods.restart();133 }134 });135 },136 // call this method when you want to resume the tour137 resume : function () {138 methods.set_li();139 methods.show();140 },141 nextTip: function(){142 if (settings.$li.next().length < 1) {143 methods.end();144 } else if (settings.timer > 0) {145 clearTimeout(settings.automate);146 methods.hide();147 methods.show();148 methods.startTimer();149 } else {150 methods.hide();151 methods.show();152 }153 },154 tip_template : function (opts) {155 var $blank, content, $wrapper;156 opts.tip_class = opts.tip_class || '';157 $blank = $(settings.template.tip).addClass(opts.tip_class);158 content = $.trim($(opts.li).html()) +159 methods.button_text(opts.button_text) +160 settings.template.link +161 methods.timer_instance(opts.index);162 $wrapper = $(settings.template.wrapper);163 if (opts.li.attr('data-aria-labelledby')) {164 $wrapper.attr('aria-labelledby', opts.li.attr('data-aria-labelledby'))165 }166 if (opts.li.attr('data-aria-describedby')) {167 $wrapper.attr('aria-describedby', opts.li.attr('data-aria-describedby'))168 }169 $blank.append($wrapper);170 $blank.first().attr('data-index', opts.index);171 $('.joyride-content-wrapper', $blank).append(content);172 return $blank[0];173 },174 timer_instance : function (index) {175 var txt;176 if ((index === 0 && settings.startTimerOnClick && settings.timer > 0) || settings.timer === 0) {177 txt = '';178 } else {179 txt = methods.outerHTML($(settings.template.timer)[0]);180 }181 return txt;182 },183 button_text : function (txt) {184 if (settings.nextButton) {185 txt = $.trim(txt) || 'Next';186 txt = methods.outerHTML($(settings.template.button).append(txt)[0]);187 } else {188 txt = '';189 }190 return txt;191 },192 create : function (opts) {193 // backwards compatibility with data-text attribute194 var buttonText = opts.$li.attr('data-button') || opts.$li.attr('data-text'),195 tipClass = opts.$li.attr('class'),196 $tip_content = $(methods.tip_template({197 tip_class : tipClass,198 index : opts.index,199 button_text : buttonText,200 li : opts.$li201 }));202 $(settings.tipContainer).append($tip_content);203 },204 show : function (init) {205 var opts = {}, ii, opts_arr = [], opts_len = 0, p,206 $timer = null;207 // are we paused?208 if (settings.$li === undefined || ($.inArray(settings.$li.index(), settings.pauseAfter) === -1)) {209 // don't go to the next li if the tour was paused210 if (settings.paused) {211 settings.paused = false;212 } else {213 methods.set_li(init);214 }215 settings.attempts = 0;216 if (settings.$li.length && settings.$target.length > 0) {217 if(init){ //run when we first start218 settings.preRideCallback(settings.$li.index(), settings.$next_tip );219 if(settings.modal){220 methods.show_modal();221 }222 }223 settings.preStepCallback(settings.$li.index(), settings.$next_tip );224 // parse options225 opts_arr = (settings.$li.data('options') || ':').split(';');226 opts_len = opts_arr.length;227 for (ii = opts_len - 1; ii >= 0; ii--) {228 p = opts_arr[ii].split(':');229 if (p.length === 2) {230 opts[$.trim(p[0])] = $.trim(p[1]);231 }232 }233 settings.tipSettings = $.extend({}, settings, opts);234 settings.tipSettings.tipLocationPattern = settings.tipLocationPatterns[settings.tipSettings.tipLocation];235 if(settings.modal && settings.expose){236 methods.expose();237 }238 // scroll if not modal239 if (!settings.$target.is("body") && settings.scroll) {240 methods.scroll_to();241 }242 if (methods.is_phone()) {243 methods.pos_phone(true);244 } else {245 methods.pos_default(true);246 }247 $timer = $('.joyride-timer-indicator', settings.$next_tip);248 if (/pop/i.test(settings.tipAnimation)) {249 $timer.outerWidth(0);250 if (settings.timer > 0) {251 settings.$next_tip.show();252 $timer.animate({253 width: $('.joyride-timer-indicator-wrap', settings.$next_tip).outerWidth()254 }, settings.timer);255 } else {256 settings.$next_tip.show();257 }258 } else if (/fade/i.test(settings.tipAnimation)) {259 $timer.outerWidth(0);260 if (settings.timer > 0) {261 settings.$next_tip.fadeIn(settings.tipAnimationFadeSpeed);262 settings.$next_tip.show();263 $timer.animate({264 width: $('.joyride-timer-indicator-wrap', settings.$next_tip).outerWidth()265 }, settings.timer);266 } else {267 settings.$next_tip.fadeIn(settings.tipAnimationFadeSpeed);268 }269 }270 settings.$current_tip = settings.$next_tip;271 // Focus next button for keyboard users.272 $('.joyride-next-tip', settings.$current_tip).focus();273 methods.tabbable(settings.$current_tip);274 // skip non-existent targets275 } else if (settings.$li && settings.$target.length < 1) {276 methods.show();277 } else {278 methods.end();279 }280 } else {281 settings.paused = true;282 }283 },284 // detect phones with media queries if supported.285 is_phone : function () {286 if (Modernizr) {287 return Modernizr.mq('only screen and (max-width: 767px)');288 }289 return (settings.$window.width() < 767) ? true : false;290 },291 support_localstorage : function () {292 if (Modernizr) {293 return Modernizr.localstorage;294 } else {295 return !!window.localStorage;296 }297 },298 hide : function () {299 if(settings.modal && settings.expose){300 methods.un_expose();301 }302 if(!settings.modal){303 $('.joyride-modal-bg').hide();304 }305 settings.$current_tip.hide();306 settings.postStepCallback(settings.$li.index(), settings.$current_tip);307 },308 set_li : function (init) {309 if (init) {310 settings.$li = settings.$tip_content.eq(settings.startOffset);311 methods.set_next_tip();312 settings.$current_tip = settings.$next_tip;313 } else {314 settings.$li = settings.$li.next();315 methods.set_next_tip();316 }317 methods.set_target();318 },319 set_next_tip : function () {320 settings.$next_tip = $('.joyride-tip-guide[data-index=' + settings.$li.index() + ']');321 },322 set_target : function () {323 var cl = settings.$li.attr('data-class'),324 id = settings.$li.attr('data-id'),325 $sel = function () {326 if (id) {327 return $(settings.document.getElementById(id));328 } else if (cl) {329 return $('.' + cl).filter(":visible").first();330 } else {331 return $('body');332 }333 };334 settings.$target = $sel();335 },336 scroll_to : function () {337 var window_half, tipOffset;338 window_half = settings.$window.height() / 2;339 tipOffset = Math.ceil(settings.$target.offset().top - window_half + settings.$next_tip.outerHeight());340 $("html, body").stop().animate({341 scrollTop: tipOffset342 }, settings.scrollSpeed);343 },344 paused : function () {345 if (($.inArray((settings.$li.index() + 1), settings.pauseAfter) === -1)) {346 return true;347 }348 return false;349 },350 destroy : function () {351 if(!$.isEmptyObject(settings)){352 settings.$document.off('.joyride');353 }354 $(window).off('.joyride');355 $('.joyride-close-tip, .joyride-next-tip, .joyride-modal-bg').off('.joyride');356 $('.joyride-tip-guide, .joyride-modal-bg').remove();357 clearTimeout(settings.automate);358 settings = {};359 },360 restart : function () {361 if(!settings.autoStart)362 {363 if (!settings.startTimerOnClick && settings.timer > 0) {364 methods.show('init');365 methods.startTimer();366 } else {367 methods.show('init');368 }369 settings.autoStart = true;370 }371 else372 {373 methods.hide();374 settings.$li = undefined;375 methods.show('init');376 }377 },378 pos_default : function (init) {379 var half_fold = Math.ceil(settings.$window.height() / 2),380 tip_position = settings.$next_tip.offset(),381 $nub = $('.joyride-nub', settings.$next_tip),382 nub_width = Math.ceil($nub.outerWidth() / 2),383 nub_height = Math.ceil($nub.outerHeight() / 2),384 toggle = init || false;385 // tip must not be "display: none" to calculate position386 if (toggle) {387 settings.$next_tip.css('visibility', 'hidden');388 settings.$next_tip.show();389 }390 if (!settings.$target.is("body")) {391 var392 topAdjustment = settings.tipSettings.tipAdjustmentY ? parseInt(settings.tipSettings.tipAdjustmentY) : 0,393 leftAdjustment = settings.tipSettings.tipAdjustmentX ? parseInt(settings.tipSettings.tipAdjustmentX) : 0;394 if (methods.bottom()) {395 settings.$next_tip.css({396 top: (settings.$target.offset().top + nub_height + settings.$target.outerHeight() + topAdjustment),397 left: settings.$target.offset().left + leftAdjustment});398 if (/right/i.test(settings.tipSettings.nubPosition)) {399 settings.$next_tip.css('left', settings.$target.offset().left - settings.$next_tip.outerWidth() + settings.$target.outerWidth());400 }401 methods.nub_position($nub, settings.tipSettings.nubPosition, 'top');402 } else if (methods.top()) {403 settings.$next_tip.css({404 top: (settings.$target.offset().top - settings.$next_tip.outerHeight() - nub_height + topAdjustment),405 left: settings.$target.offset().left + leftAdjustment});406 methods.nub_position($nub, settings.tipSettings.nubPosition, 'bottom');407 } else if (methods.right()) {408 settings.$next_tip.css({409 top: settings.$target.offset().top + topAdjustment,410 left: (settings.$target.outerWidth() + settings.$target.offset().left + nub_width) + leftAdjustment});411 methods.nub_position($nub, settings.tipSettings.nubPosition, 'left');412 } else if (methods.left()) {413 settings.$next_tip.css({414 top: settings.$target.offset().top + topAdjustment,415 left: (settings.$target.offset().left - settings.$next_tip.outerWidth() - nub_width) + leftAdjustment});416 methods.nub_position($nub, settings.tipSettings.nubPosition, 'right');417 }418 if (!methods.visible(methods.corners(settings.$next_tip)) && settings.attempts < settings.tipSettings.tipLocationPattern.length) {419 $nub.removeClass('bottom')420 .removeClass('top')421 .removeClass('right')422 .removeClass('left');423 settings.tipSettings.tipLocation = settings.tipSettings.tipLocationPattern[settings.attempts];424 settings.attempts++;425 methods.pos_default(true);426 }427 } else if (settings.$li.length) {428 methods.pos_modal($nub);429 }430 if (toggle) {431 settings.$next_tip.hide();432 settings.$next_tip.css('visibility', 'visible');433 }434 },435 pos_phone : function (init) {436 var tip_height = settings.$next_tip.outerHeight(),437 tip_offset = settings.$next_tip.offset(),438 target_height = settings.$target.outerHeight(),439 $nub = $('.joyride-nub', settings.$next_tip),440 nub_height = Math.ceil($nub.outerHeight() / 2),441 toggle = init || false;442 $nub.removeClass('bottom')443 .removeClass('top')444 .removeClass('right')445 .removeClass('left');446 if (toggle) {447 settings.$next_tip.css('visibility', 'hidden');448 settings.$next_tip.show();449 }450 if (!settings.$target.is("body")) {451 if (methods.top()) {452 settings.$next_tip.offset({top: settings.$target.offset().top - tip_height - nub_height});453 $nub.addClass('bottom');454 } else {455 settings.$next_tip.offset({top: settings.$target.offset().top + target_height + nub_height});456 $nub.addClass('top');457 }458 } else if (settings.$li.length) {459 methods.pos_modal($nub);460 }461 if (toggle) {462 settings.$next_tip.hide();463 settings.$next_tip.css('visibility', 'visible');464 }465 },466 pos_modal : function ($nub) {467 methods.center();468 $nub.hide();469 methods.show_modal();470 },471 show_modal : function() {472 if ($('.joyride-modal-bg').length < 1) {473 $('body').append(settings.template.modal).show();474 }475 if (/pop/i.test(settings.tipAnimation)) {476 $('.joyride-modal-bg').show();477 } else {478 $('.joyride-modal-bg').fadeIn(settings.tipAnimationFadeSpeed);479 }480 },481 expose: function(){482 var expose,483 exposeCover,484 el,485 origCSS,486 randId = 'expose-'+Math.floor(Math.random()*10000);487 if (arguments.length>0 && arguments[0] instanceof $){488 el = arguments[0];489 } else if(settings.$target && !settings.$target.is("body")){490 el = settings.$target;491 } else {492 return false;493 }494 if(el.length < 1){495 if(window.console){496 console.error('element not valid', el);497 }498 return false;499 }500 expose = $(settings.template.expose);501 settings.$body.append(expose);502 expose.css({503 top: el.offset().top,504 left: el.offset().left,505 width: el.outerWidth(true),506 height: el.outerHeight(true)507 });508 exposeCover = $(settings.template.exposeCover);509 origCSS = {510 zIndex: el.css('z-index'),511 position: el.css('position')512 };513 el.css('z-index',expose.css('z-index')*1+1);514 if(origCSS.position == 'static'){515 el.css('position','relative');516 }517 el.data('expose-css',origCSS);518 exposeCover.css({519 top: el.offset().top,520 left: el.offset().left,521 width: el.outerWidth(true),522 height: el.outerHeight(true)523 });524 settings.$body.append(exposeCover);525 expose.addClass(randId);526 exposeCover.addClass(randId);527 if(settings.tipSettings['exposeClass']){528 expose.addClass(settings.tipSettings['exposeClass']);529 exposeCover.addClass(settings.tipSettings['exposeClass']);530 }531 el.data('expose', randId);532 settings.postExposeCallback(settings.$li.index(), settings.$next_tip, el);533 methods.add_exposed(el);534 },535 un_expose: function(){536 var exposeId,537 el,538 expose ,539 origCSS,540 clearAll = false;541 if (arguments.length>0 && arguments[0] instanceof $){542 el = arguments[0];543 } else if(settings.$target && !settings.$target.is("body")){544 el = settings.$target;545 } else {546 return false;547 }548 if(el.length < 1){549 if(window.console){550 console.error('element not valid', el);551 }552 return false;553 }554 exposeId = el.data('expose');555 expose = $('.'+exposeId);556 if(arguments.length>1){557 clearAll = arguments[1];558 }559 if(clearAll === true){560 $('.joyride-expose-wrapper,.joyride-expose-cover').remove();561 } else {562 expose.remove();563 }564 origCSS = el.data('expose-css');565 if(origCSS.zIndex == 'auto'){566 el.css('z-index', '');567 } else {568 el.css('z-index',origCSS.zIndex);569 }570 if(origCSS.position != el.css('position')){571 if(origCSS.position == 'static'){// this is default, no need to set it.572 el.css('position', '');573 } else {574 el.css('position',origCSS.position);575 }576 }577 el.removeData('expose');578 el.removeData('expose-z-index');579 methods.remove_exposed(el);580 },581 add_exposed: function(el){582 settings.exposed = settings.exposed || [];583 if(el instanceof $){584 settings.exposed.push(el[0]);585 } else if(typeof el == 'string'){586 settings.exposed.push(el);587 }588 },589 remove_exposed: function(el){590 var search;591 if(el instanceof $){592 search = el[0]593 } else if (typeof el == 'string'){594 search = el;595 }596 settings.exposed = settings.exposed || [];597 for(var i=0; i<settings.exposed.length; i++){598 if(settings.exposed[i] == search){599 settings.exposed.splice(i,1);600 return;601 }602 }603 },604 center : function () {605 var $w = settings.$window;606 settings.$next_tip.css({607 top : ((($w.height() - settings.$next_tip.outerHeight()) / 2) + $w.scrollTop()),608 left : ((($w.width() - settings.$next_tip.outerWidth()) / 2) + $w.scrollLeft())609 });610 return true;611 },612 bottom : function () {613 return /bottom/i.test(settings.tipSettings.tipLocation);614 },615 top : function () {616 return /top/i.test(settings.tipSettings.tipLocation);617 },618 right : function () {619 return /right/i.test(settings.tipSettings.tipLocation);620 },621 left : function () {622 return /left/i.test(settings.tipSettings.tipLocation);623 },624 corners : function (el) {625 var w = settings.$window,626 window_half = w.height() / 2,627 tipOffset = Math.ceil(settings.$target.offset().top - window_half + settings.$next_tip.outerHeight()),//using this to calculate since scroll may not have finished yet.628 right = w.width() + w.scrollLeft(),629 offsetBottom = w.height() + tipOffset,630 bottom = w.height() + w.scrollTop(),631 top = w.scrollTop();632 if(tipOffset < top){633 if (tipOffset <0 ){634 top = 0;635 } else {636 top = tipOffset;637 }638 }639 if(offsetBottom > bottom){640 bottom = offsetBottom;641 }642 return [643 el.offset().top < top,644 right < el.offset().left + el.outerWidth(),645 bottom < el.offset().top + el.outerHeight(),646 w.scrollLeft() > el.offset().left647 ];648 },649 visible : function (hidden_corners) {650 var i = hidden_corners.length;651 while (i--) {652 if (hidden_corners[i]) return false;653 }654 return true;655 },656 nub_position : function (nub, pos, def) {657 if (pos === 'auto') {658 nub.addClass(def);659 } else {660 nub.addClass(pos);661 }662 },663 startTimer : function () {664 if (settings.$li.length) {665 settings.automate = setTimeout(function () {666 methods.hide();667 methods.show();668 methods.startTimer();669 }, settings.timer);670 } else {671 clearTimeout(settings.automate);672 }673 },674 end : function (isAborted) {675 isAborted = isAborted || false;676 // Unbind resize events.677 if (isAborted) {678 settings.$window.off('resize.joyride');679 }680 if (settings.cookieMonster) {681 $.cookie(settings.cookieName, 'ridden', { expires: 365, domain: settings.cookieDomain, path: settings.cookiePath });682 }683 if (settings.localStorage) {684 localStorage.setItem(settings.localStorageKey, true);685 }686 if (settings.timer > 0) {687 clearTimeout(settings.automate);688 }689 if(settings.modal && settings.expose){690 methods.un_expose();691 }692 if (settings.$current_tip) {693 settings.$current_tip.hide();694 }695 if (settings.$li) {696 settings.postStepCallback(settings.$li.index(), settings.$current_tip, isAborted);697 settings.postRideCallback(settings.$li.index(), settings.$current_tip, isAborted);698 }699 $('.joyride-modal-bg').hide();700 },701 jquery_check : function () {702 // define on() and off() for older jQuery703 if (!$.isFunction($.fn.on)) {704 $.fn.on = function (types, sel, fn) {705 return this.delegate(sel, types, fn);706 };707 $.fn.off = function (types, sel, fn) {708 return this.undelegate(sel, types, fn);709 };710 return false;711 }712 return true;713 },714 outerHTML : function (el) {715 // support FireFox < 11716 return el.outerHTML || new XMLSerializer().serializeToString(el);717 },718 version : function () {719 return settings.version;720 },721 tabbable : function (el) {722 $(el).on('keydown', function( event ) {723 if (!event.isDefaultPrevented() && event.keyCode &&724 // Escape key.725 event.keyCode === 27 ) {726 event.preventDefault();727 methods.end(true /* isAborted */);728 return;729 }730 // Prevent tabbing out of tour items.731 if ( event.keyCode !== 9 ) {732 return;733 }734 var tabbables = $(el).find(":tabbable"),735 first = tabbables.filter(":first"),736 last = tabbables.filter(":last");737 if ( event.target === last[0] && !event.shiftKey ) {738 first.focus( 1 );739 event.preventDefault();740 } else if ( event.target === first[0] && event.shiftKey ) {741 last.focus( 1 );742 event.preventDefault();743 }744 });745 }746 };747 $.fn.joyride = function (method) {748 if (methods[method]) {749 return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));750 } else if (typeof method === 'object' || !method) {751 return methods.init.apply(this, arguments);752 } else {753 $.error('Method ' + method + ' does not exist on jQuery.joyride');754 }755 };...

Full Screen

Full Screen

ors-settings-service.js

Source:ors-settings-service.js Github

copy

Full Screen

1angular.module("orsApp.settings-service", []).factory("orsSettingsFactory", [2 "$timeout",3 "orsObjectsFactory",4 "orsUtilsService",5 "orsRequestService",6 "orsRouteService",7 "orsAaService",8 "orsMessagingService",9 "lists",10 "weathercheck",11 "orsFuelService",12 (13 $timeout,14 orsObjectsFactory,15 orsUtilsService,16 orsRequestService,17 orsRouteService,18 orsAaService,19 orsMessagingService,20 lists,21 weathercheck,22 orsFuelService23 ) => {24 let orsSettingsFactory = {};25 /** Behaviour subjects routing. */26 orsSettingsFactory.routingWaypointsSubject = new Rx.BehaviorSubject({});27 orsSettingsFactory.routingSettingsSubject = new Rx.BehaviorSubject({28 waypoints: []29 });30 /** Behaviour subjects accessibility analysis. */31 orsSettingsFactory.aaWaypointsSubject = new Rx.BehaviorSubject({});32 orsSettingsFactory.aaSettingsSubject = new Rx.BehaviorSubject({33 waypoints: []34 });35 /** Behaviour subject for user options, language and units */36 orsSettingsFactory.userOptionsSubject = new Rx.BehaviorSubject({});37 /** Behaviour subject for map options */38 orsSettingsFactory.mapOptionsInitSubject = new Rx.ReplaySubject(1);39 /** Behaviour subject routing. */40 orsSettingsFactory.ngRouteSubject = new Rx.BehaviorSubject(undefined);41 orsSettingsFactory.requestSubject = new Rx.Subject();42 /** Global reference settings, these are switched when panels are changed - default is routing.*/43 let currentSettingsObj, currentWaypointsObj;44 orsSettingsFactory.isInitialized = false;45 orsSettingsFactory.focusIdx = true;46 /**47 * Sets the settings from permalink48 * @param {Object} set - The settings object.49 * @param {boolean} focus - If only one waypoint is set zoom to it.50 */51 orsSettingsFactory.setSettings = set => {52 /** Fire request */53 orsSettingsFactory[currentSettingsObj].onNext(set);54 };55 /**56 * Sets user specific options in settings (language, routinglang and units). Can be used for any key-value pair. Is used by both permalink and Cookies57 * @param {Object} options- Consists of routing instruction language and units km/mi58 */59 orsSettingsFactory.setUserOptions = params => {60 if (params === undefined) return;61 //get current settings and add new params/replace existing params62 let set = orsSettingsFactory.userOptionsSubject.getValue();63 for (var k in params) {64 set[k] = params[k];65 }66 orsSettingsFactory.userOptionsSubject.onNext(set);67 orsSettingsFactory.mapOptionsInitSubject.onNext(set);68 };69 /**70 * Gets user specific options in settings (language and units)71 * @return {Object} The user settings72 */73 orsSettingsFactory.getUserOptions = () => {74 return orsSettingsFactory.userOptionsSubject.getValue();75 };76 /**;77 * Returns active profile.78 * @return {Object} The profile object.79 */80 orsSettingsFactory.getActiveProfile = () => {81 return orsSettingsFactory[currentSettingsObj].getValue().profile;82 };83 /**84 * Returns current options.85 * @return {Object} The options object, may contain both profile options and aa options.86 */87 orsSettingsFactory.getActiveOptions = () => {88 return orsSettingsFactory[currentSettingsObj].getValue().profile.options;89 };90 orsSettingsFactory.setActiveOptions = (options, fireRequest) => {91 orsSettingsFactory[92 currentSettingsObj93 ].getValue().profile.options = options;94 if (fireRequest)95 orsSettingsFactory[currentSettingsObj].onNext(96 orsSettingsFactory[currentSettingsObj].getValue()97 );98 if (orsSettingsFactory.isInitialized) {99 orsUtilsService.parseSettingsToPermalink(100 orsSettingsFactory[currentSettingsObj].getValue(),101 orsSettingsFactory.getUserOptions()102 );103 }104 };105 /**106 * Returns current settings.107 * @return {Object} The settings object, may contain both profile options and aa options.108 */109 orsSettingsFactory.getSettings = () => {110 return orsSettingsFactory[currentSettingsObj].getValue();111 };112 /** Subscription function to current waypoints object, used in map. */113 orsSettingsFactory.subscribeToWaypoints = o => {114 return orsSettingsFactory.routingWaypointsSubject.subscribe(o);115 };116 /** Subscription function to current aa waypoints object, used in map. */117 orsSettingsFactory.subscribeToAaWaypoints = o => {118 return orsSettingsFactory.aaWaypointsSubject.subscribe(o);119 };120 /** Subscription function to current route object. */121 orsSettingsFactory.subscribeToNgRoute = o => {122 return orsSettingsFactory.ngRouteSubject.subscribe(o);123 };124 /** Subscription function to current route object. */125 orsSettingsFactory.subscribeToRouteRequest = o => {126 return orsSettingsFactory.requestSubject.subscribe(o);127 };128 /** Returns waypoints in settings. If none are set then returns empty list. */129 orsSettingsFactory.getWaypoints = () => {130 return orsSettingsFactory[currentSettingsObj].getValue().waypoints;131 };132 /**133 * Intializes empty waypoints without coordinates.134 * @param {number} n - Specifices the amount of waypoints to be added135 */136 orsSettingsFactory.initWaypoints = n => {137 orsSettingsFactory[currentSettingsObj].getValue().waypoints = [];138 var wp;139 for (var i = 1; i <= n; i++) {140 wp = orsObjectsFactory.createWaypoint("", new L.latLng());141 orsSettingsFactory[currentSettingsObj].getValue().waypoints.push(wp);142 }143 orsSettingsFactory[currentSettingsObj].onNext(144 orsSettingsFactory[currentSettingsObj].getValue()145 );146 return orsSettingsFactory[currentSettingsObj].getValue().waypoints;147 };148 /**149 * Updates waypoint address and position in settings.150 * @param {number} idx - Which is the index of the to be updated wp.151 * @param {string} address - Which is the string of the address.152 * @param {Object} pos - Which is the latlng object.153 */154 orsSettingsFactory.updateWaypoint = (155 idx,156 address,157 pos,158 fireRequest = true159 ) => {160 orsSettingsFactory.focusIdx = false;161 orsSettingsFactory[currentSettingsObj].getValue().waypoints[162 idx163 ]._latlng = pos;164 orsSettingsFactory[currentSettingsObj].getValue().waypoints[165 idx166 ]._address = address;167 /** Fire a new request. */168 if (fireRequest)169 orsSettingsFactory[currentSettingsObj].onNext(170 orsSettingsFactory[currentSettingsObj].getValue()171 );172 //orsSettingsFactory.panelWaypoints.onNext(orsSettingsFactory.panelSettings.getValue().waypoints);173 };174 /** Used for map update */175 orsSettingsFactory.updateWaypoints = () => {176 orsSettingsFactory[currentWaypointsObj].onNext(177 orsSettingsFactory[currentSettingsObj].getValue().waypoints178 );179 };180 /** Sets avoidable regions in settings object */181 orsSettingsFactory.setAvoidableAreas = avoidablePolygons => {182 orsSettingsFactory[183 currentSettingsObj184 ].getValue().avoidable_polygons = avoidablePolygons;185 orsSettingsFactory[currentSettingsObj].onNext(186 orsSettingsFactory[currentSettingsObj].getValue()187 );188 };189 /**190 * This is basically the heart of navigation. If the panels are switched between191 * routing and accessibility analysis the subject references are updated.192 * @param {string} newRoute - Path of current location.193 */194 orsSettingsFactory.updateNgRoute = newRoute => {195 currentSettingsObj = orsSettingsFactory.getCurrentSettings(newRoute);196 currentWaypointsObj = orsSettingsFactory.getCurrentWaypoints(newRoute);197 /** panels switched, clear the map */198 /** Cancel outstanding requests */199 orsAaService.aaRequests.clear();200 orsRouteService.routingRequests.clear();201 orsRequestService.geocodeRequests.clear();202 orsSettingsFactory.ngRouteSubject.onNext(newRoute);203 };204 /**205 * Checks if two waypoints are set206 * @param {Object} settings - route settings object207 * @return {boolean} routePresent - whether route is present208 */209 orsSettingsFactory.handleRoutePresent = (settings, num) => {210 let sum = 0,211 routePresent = false;212 angular.forEach(settings.waypoints, waypoint => {213 sum += waypoint._set;214 if (sum == num) {215 routePresent = true;216 return;217 }218 });219 return routePresent;220 };221 /** Subscription function to current routing settings */222 orsSettingsFactory.routingSettingsSubject.subscribe(settings => {223 const isRoutePresent = orsSettingsFactory.handleRoutePresent(settings, 2);224 if (isRoutePresent) {225 orsSettingsFactory.requestSubject.onNext(true);226 /** Cancel outstanding requests */227 orsRouteService.routingRequests.clear();228 orsRouteService.resetRoute();229 const userOptions = orsSettingsFactory.getUserOptions();230 const payload = orsUtilsService.routingPayload(settings, userOptions);231 const request = orsRouteService.fetchRoute(payload);232 orsRouteService.routingRequests.requests.push(request);233 request.promise.then(234 function(response) {235 orsSettingsFactory.requestSubject.onNext(false);236 const profile = settings.profile.type;237 orsRouteService.processResponse(238 response,239 profile,240 orsSettingsFactory.focusIdx,241 settings.profile.options.landmarks242 );243 let ofsSettings = profile === "Car" ? settings.profile.options.ofs : undefined;244 if (ofsSettings) {245 orsFuelService.getConsumption(ofsSettings);246 }247 },248 function(response) {249 orsSettingsFactory.requestSubject.onNext(false);250 }251 );252 }253 });254 /** Subscription function to current accessibility settings */255 orsSettingsFactory.aaSettingsSubject.subscribe(settings => {256 /** get user options */257 const isAaPresent = orsSettingsFactory.handleRoutePresent(settings, 1);258 if (isAaPresent) {259 orsSettingsFactory.requestSubject.onNext(true);260 /** Cancel outstanding requests */261 orsAaService.aaRequests.clear();262 const payload = orsUtilsService.isochronesPayload(settings);263 const request = orsAaService.getIsochrones(payload);264 orsAaService.aaRequests.requests.push(request);265 request.promise.then(266 function(response) {267 orsAaService.processResponse(response, settings);268 orsSettingsFactory.requestSubject.onNext(false);269 // orsAaService.parseResultsToBounds(response);270 // orsAaService.parseResponseToPolygonJSON(response);271 },272 function(response) {273 orsSettingsFactory.requestSubject.onNext(false);274 }275 );276 }277 });278 /** Fetches address279 * @param {Object} pos - latLng Object280 * @param {number} idx - Index of waypoint281 * @param {boolean} init - Init is true when the service is loaded over permalink with the correct indices of waypoints282 */283 orsSettingsFactory.getAddress = (pos, idx, init, fromHover = false) => {284 // if this function is called from a popup we have to translate the index285 if (!fromHover) {286 if (!init) {287 const set = orsSettingsFactory[currentSettingsObj].getValue();288 if (idx === 0) {289 idx = 0;290 } else if (idx == 2) {291 idx = set.waypoints.length - 1;292 } else if (idx == 1) {293 idx = set.waypoints.length - 2;294 }295 }296 }297 const latLngString = orsUtilsService.parseLatLngString(pos);298 const lngLatString = orsUtilsService.parseLngLatString(pos);299 orsSettingsFactory.updateWaypointAddress(idx, latLngString, init);300 const payload = orsUtilsService.geocodingPayload(lngLatString, true);301 const request = orsRequestService.geocode(payload, true);302 const requestsQue =303 orsSettingsFactory.ngRouteSubject.getValue() == "directions"304 ? "routeRequests"305 : "aaRequests";306 orsRequestService.geocodeRequests.updateRequest(307 request,308 idx,309 requestsQue310 );311 request.promise.then(312 data => {313 if (data.features.length > 0) {314 const addressData = orsUtilsService.addShortAddresses(315 data.features316 )[0];317 let addressStrings = [318 addressData.processed.primary,319 addressData.processed.secondary320 ];321 addressStrings = addressStrings.join(", ");322 orsSettingsFactory.updateWaypointAddress(idx, addressStrings, init);323 } else {324 orsMessagingService.messageSubject.onNext(lists.errors.GEOCODE);325 }326 },327 response => {328 //orsMessagingService.messageSubject.onNext(lists.errors.GEOCODE);329 }330 );331 };332 /**333 * Updates waypoint address. No need to fire subscription for settings.334 * This is done already when updated latlng.335 * @param {number} idx - Index of waypoint.336 * @param {string} address - Address as string.337 * @param {boolean} init - When this is true, the index is loaded from the loop (idx is correct) and not from the popup (0, 1 or 2)338 */339 orsSettingsFactory.updateWaypointAddress = (idx, address, init) => {340 let set = orsSettingsFactory[currentSettingsObj].getValue();341 set.waypoints[idx]._address = address;342 };343 /**344 * Sets waypoints into settings.345 * @param {waypoints.<Object>} List of waypoint objects.346 */347 orsSettingsFactory.setWaypoints = (waypoints, fireRequest = true) => {348 orsSettingsFactory[currentSettingsObj].getValue().waypoints = waypoints;349 /** fire a new request */350 if (fireRequest)351 orsSettingsFactory[currentSettingsObj].onNext(352 orsSettingsFactory[currentSettingsObj].getValue()353 );354 orsSettingsFactory[currentWaypointsObj].onNext(waypoints);355 orsUtilsService.parseSettingsToPermalink(356 orsSettingsFactory[currentSettingsObj].getValue(),357 orsSettingsFactory.getUserOptions()358 );359 };360 /**361 * Sets waypoint into settings.362 * @param {waypoints.<Object>} List of waypoint objects.363 */364 orsSettingsFactory.setWaypoint = (waypoint, idx, fireRequest = true) => {365 orsSettingsFactory[currentSettingsObj].getValue().waypoints[366 idx367 ] = waypoint;368 /** fire a new request */369 if (fireRequest)370 orsSettingsFactory[currentSettingsObj].onNext(371 orsSettingsFactory[currentSettingsObj].getValue()372 );373 orsSettingsFactory[currentWaypointsObj].onNext(374 orsSettingsFactory[currentSettingsObj].getValue().waypoints375 );376 orsUtilsService.parseSettingsToPermalink(377 orsSettingsFactory[currentSettingsObj].getValue(),378 orsSettingsFactory.getUserOptions()379 );380 };381 /**382 * Inserts waypoint to settings waypoints when added on map. This can383 * either be a start, via or end384 * @param {number} idx - Type of wp which should be added: start, via or end.385 * @param {Object} wp - The waypoint object to be inserted to wp list.386 */387 orsSettingsFactory.insertWaypointFromMap = (388 idx,389 wp,390 fireRequest = true,391 fromHover = false392 ) => {393 if (fromHover) {394 orsSettingsFactory[currentSettingsObj].value.waypoints.splice(395 idx,396 0,397 wp398 );399 orsSettingsFactory.focusIdx = false;400 } else {401 if (idx === 0) {402 orsSettingsFactory[currentSettingsObj].value.waypoints[idx] = wp;403 } else if (idx == 2) {404 orsSettingsFactory[currentSettingsObj].value.waypoints[405 orsSettingsFactory[currentSettingsObj].value.waypoints.length - 1406 ] = wp;407 } else if (idx == 1) {408 orsSettingsFactory[currentSettingsObj].value.waypoints.splice(409 orsSettingsFactory[currentSettingsObj].value.waypoints.length - 1,410 0,411 wp412 );413 orsSettingsFactory.focusIdx = false;414 }415 }416 /** Update Map. */417 orsSettingsFactory[currentWaypointsObj].onNext(418 orsSettingsFactory[currentSettingsObj].getValue().waypoints419 );420 /** Fire a new request. */421 if (fireRequest)422 orsSettingsFactory[currentSettingsObj].onNext(423 orsSettingsFactory[currentSettingsObj].getValue()424 );425 };426 /**427 * Returns the current settings depending on the route428 */429 orsSettingsFactory.getCurrentSettings = path => {430 let settingsObject;431 if (path == "directions") {432 settingsObject = "routingSettingsSubject";433 } else if (path == "reach") {434 settingsObject = "aaSettingsSubject";435 }436 return settingsObject;437 };438 /**439 * Returns the current waypoints depending on the route440 */441 orsSettingsFactory.getCurrentWaypoints = path => {442 let waypointsObject;443 if (path == "directions") {444 waypointsObject = "routingWaypointsSubject";445 } else if (path == "reach") {446 waypointsObject = "aaWaypointsSubject";447 }448 return waypointsObject;449 };450 /**451 * Determines which icon should be returned.452 * @param {number} idx - Type of wp which should be added: start, via or end.453 * @return {number} iconIdx - 0, 1 or 2.454 */455 orsSettingsFactory.getIconIdx = idx => {456 let iconIdx;457 if (idx === 0) {458 iconIdx = 0;459 } else if (460 idx ==461 orsSettingsFactory[currentSettingsObj].getValue().waypoints.length - 1462 ) {463 iconIdx = 2;464 } else {465 iconIdx = 1;466 }467 return iconIdx;468 };469 /**470 * Sets the profile of selected in settings.471 * @param {Object} currentProfile - current profile.472 */473 orsSettingsFactory.setProfile = currentProfile => {474 orsUtilsService.parseSettingsToPermalink(475 orsSettingsFactory[currentSettingsObj].getValue(),476 orsSettingsFactory.getUserOptions()477 );478 let set = orsSettingsFactory[currentSettingsObj].getValue();479 set.profile.type = currentProfile.type;480 /** Fire a new request if on route. */481 const isAaPanel =482 orsSettingsFactory.ngRouteSubject.getValue() == "reach" ? true : false;483 if (!isAaPanel) orsSettingsFactory[currentSettingsObj].onNext(set);484 };485 /**486 * Retrieves API Key487 * @return {string} weathercheck - current api key488 */489 orsUtilsService.getApiKey = () => {490 return weathercheck;491 };492 return orsSettingsFactory;493 }...

Full Screen

Full Screen

setup_util.py

Source:setup_util.py Github

copy

Full Screen

...5'''6Usage Examples:7setup_util = Setup_Util(uri, session_key)8setup_util.get_log_level()9setup_util.get_proxy_settings()10setup_util.get_credential_account("my_account_name")11setup_util.get_customized_setting("my_customized_field_name")12'''13'''14setting object structure.15It is stored in self.__cached_global_settings16Note, this structure is only maintained in this util.17setup_util transforms global settings in os environment or from ucc into this structure.18{19 "proxy_settings": {20 "proxy_enabled": False/True,21 "proxy_url": "example.com",22 "proxy_port": "1234",23 "proxy_username": "",24 "proxy_password": "",25 "proxy_type": "http",26 "proxy_rdns": False/True27 },28 "log_settings": {29 "loglevel": "DEBUG"30 },31 "credential_settings": [{32 "name": "account_id",33 "username": "example_account",34 "password": "example_password"35 }, { # supported by ucc, not seen any usage in AoB36 "api_key": "admin",37 "api_uuid": "admin",38 "endpoint": "some url",39 "name": "account1"40 }],41 "customized_settings": {42 "text_name": "content",43 "pass_name": "password",44 "checkbox": 0/145 }46}47'''48GLOBAL_SETTING_KEY = "global_settings"49AOB_TEST_FLAG = 'AOB_TEST'50PROXY_SETTINGS = "proxy_settings"51LOG_SETTINGS = "log_settings"52CREDENTIAL_SETTINGS = "credential_settings"53CUSTOMIZED_SETTINGS = "customized_settings"54UCC_PROXY = "proxy"55UCC_LOGGING = "logging"56UCC_CUSTOMIZED = "additional_parameters"57UCC_CREDENTIAL = "account"58CONFIGS = [CREDENTIAL_SETTINGS]59SETTINGS = [PROXY_SETTINGS, LOG_SETTINGS, CUSTOMIZED_SETTINGS]60PROXY_ENABLE_KEY = 'proxy_enabled'61PROXY_RDNS_KEY = 'proxy_rdns'62LOG_LEVEL_KEY = 'loglevel'63LOG_LEVEL_KEY_ENV = 'log_level'64TYPE_CHECKBOX = "checkbox"65ALL_SETTING_TYPES = ['text', 'password', 'checkbox', 'dropdownlist', 'multi_dropdownlist', 'radiogroup']66def get_schema_path():67 dirname = os.path.dirname68 basedir = dirname(dirname(dirname((dirname(__file__)))))69 return os.path.join(basedir, 'appserver', 'static', 'js', 'build', 'globalConfig.json')70class Setup_Util(object):71 def __init__(self, uri, session_key, logger=None):72 self.__uri = uri73 self.__session_key = session_key74 self.__logger = logger75 self.scheme, self.host, self.port = utils.extract_http_scheme_host_port(76 self.__uri)77 self.__cached_global_settings = {}78 self.__global_config = None79 def init_global_config(self):80 if self.__global_config is not None:81 return82 schema_file = get_schema_path()83 if not os.path.isfile(schema_file):84 self.log_error("Global config JSON file not found!")85 self.__global_config = None86 else:87 with open(get_schema_path()) as f:88 json_schema = ''.join([l for l in f])89 self.__global_config = GlobalConfig(self.__uri, self.__session_key,90 GlobalConfigSchema(json.loads(json_schema)))91 def log_error(self, msg):92 if self.__logger:93 self.__logger.error(msg)94 def log_info(self, msg):95 if self.__logger:96 self.__logger.info(msg)97 def log_debug(self, msg):98 if self.__logger:99 self.__logger.debug(msg)100 def _parse_conf(self, key):101 if os.environ.get(AOB_TEST_FLAG, 'false') == 'true':102 global_settings = self._parse_conf_from_env(json.loads(os.environ.get(GLOBAL_SETTING_KEY, '{}')))103 return global_settings.get(key)104 else:105 return self._parse_conf_from_global_config(key)106 def _parse_conf_from_env(self, global_settings):107 '''108 this is run in test env109 '''110 if not self.__cached_global_settings:111 # format the settings, the setting from env is from global_setting112 # meta113 self.__cached_global_settings = {}114 for s_k, s_v in global_settings.iteritems():115 if s_k == PROXY_SETTINGS:116 proxy_enabled = s_v.get(PROXY_ENABLE_KEY)117 proxy_rdns = s_v.get(PROXY_RDNS_KEY)118 if type(proxy_enabled) != bool:119 s_v[PROXY_ENABLE_KEY] = utils.is_true(proxy_enabled)120 if type(proxy_rdns) != bool:121 s_v[PROXY_RDNS_KEY] = utils.is_true(proxy_rdns)122 self.__cached_global_settings[PROXY_SETTINGS] = s_v123 elif s_k == LOG_SETTINGS:124 self.__cached_global_settings[LOG_SETTINGS] = {125 LOG_LEVEL_KEY: s_v.get(LOG_LEVEL_KEY_ENV)126 }127 elif s_k == CREDENTIAL_SETTINGS:128 # add account id to accounts129 for i in range(0, len(s_v)):130 s_v[i]['name'] = 'account' + str(i)131 self.__cached_global_settings[CREDENTIAL_SETTINGS] = s_v132 else: # should be customized settings133 self.__cached_global_settings[CUSTOMIZED_SETTINGS] = {}134 for s in s_v:135 field_type = s.get('type')136 if not field_type:137 self.log_error(138 'unknown type for customized var:{}'.format(s))139 continue140 self.__cached_global_settings['customized_settings'][s.get('name', '')] = self._transform(141 s.get("value", ""), field_type)142 return self.__cached_global_settings143 def _parse_conf_from_global_config(self, key):144 if self.__cached_global_settings and key in self.__cached_global_settings:145 return self.__cached_global_settings.get(key)146 self.init_global_config()147 if self.__global_config is None:148 return None149 if key in CONFIGS:150 accounts = self.__global_config.configs.load().get(UCC_CREDENTIAL, [])151 if accounts:152 for account in accounts:153 if 'disabled' in account:154 del account['disabled']155 self.__cached_global_settings[CREDENTIAL_SETTINGS] = accounts156 elif key in SETTINGS:157 settings = self.__global_config.settings.load()158 self.__cached_global_settings.update({UCC_PROXY: None, UCC_LOGGING: None, UCC_CUSTOMIZED: None})159 customized_setting = {}160 for setting in settings.get('settings', []):161 # filter out disabled setting page and 'disabled' field162 if setting.get('disabled', False):163 continue164 if setting['name'] == UCC_LOGGING:165 self.__cached_global_settings[LOG_SETTINGS] = {166 LOG_LEVEL_KEY: setting.get(LOG_LEVEL_KEY)167 }168 elif setting['name'] == UCC_PROXY:169 if 'disabled' in setting:170 del setting['disabled']171 setting[PROXY_ENABLE_KEY] = utils.is_true(setting.get(PROXY_ENABLE_KEY, '0'))172 setting[PROXY_RDNS_KEY] = utils.is_true(setting.get(PROXY_RDNS_KEY, '0'))173 self.__cached_global_settings[PROXY_SETTINGS] = setting174 else: # should be customized settings175 if 'disabled' in setting:176 del setting['disabled']177 customized_setting.update(setting)178 self.__cached_global_settings[CUSTOMIZED_SETTINGS] = customized_setting179 return self.__cached_global_settings.get(key)180 def get_log_level(self):181 log_level = "INFO"182 log_settings = self._parse_conf(LOG_SETTINGS)183 if log_settings is None:184 self.log_info("Log level is not set, use default INFO")185 else:186 log_level = log_settings.get(LOG_LEVEL_KEY, None)187 if not log_level:188 self.log_info("Log level is not set, use default INFO")189 log_level = "INFO"190 return log_level191 def get_proxy_settings(self):192 proxy_settings = self._parse_conf(PROXY_SETTINGS)193 if proxy_settings is None:194 self.log_info("Proxy is not set!")195 return {}196 proxy_enabled = proxy_settings.get(PROXY_ENABLE_KEY)197 if not proxy_enabled:198 self.log_info("Proxy is not enabled!")199 return {}200 proxy_settings = {201 "proxy_url": proxy_settings.get("proxy_url", ""),202 "proxy_port": proxy_settings.get("proxy_port", None),203 "proxy_username": proxy_settings.get("proxy_username", ""),204 "proxy_password": proxy_settings.get("proxy_password", ""),205 "proxy_type": proxy_settings.get("proxy_type", ""),206 "proxy_rdns": proxy_settings.get("proxy_rdns")207 }208 self._validate_proxy_settings(proxy_settings)209 return proxy_settings210 def get_credential_by_id(self, account_id):211 credential_settings = self._parse_conf(CREDENTIAL_SETTINGS)212 for account in credential_settings:213 if account.get('name', None) == account_id:214 return account215 self.log_error("Credential account with account id {} can not be found".format(account_id))216 return None217 def get_credential_by_username(self, username):218 credential_settings = self._parse_conf(CREDENTIAL_SETTINGS)219 for account in credential_settings:220 if account.get('username', None) == username:221 return account222 self.log_error("Credential account with username {} can not be found".format(username))223 return None224 def get_customized_setting(self, key):225 customized_settings = self._parse_conf(CUSTOMIZED_SETTINGS)226 if customized_settings is None:227 self.log_info("Customized setting is not set")228 return None229 if key not in customized_settings:230 self.log_info("Customized key can not be found")231 return None232 customized_setting = customized_settings.get(key, None)233 if customized_setting is None:234 self.log_error("Cannot find customized setting with key %s" % key)235 return customized_setting236 def _validate_proxy_settings(self, proxy_settings):237 if proxy_settings:238 if proxy_settings.get('proxy_url') == "":239 raise Exception("Proxy host must not be empty!")240 proxy_port = proxy_settings.get('proxy_port')241 if proxy_port is None or not proxy_port.isdigit():242 raise Exception("Proxy port must be a number!")243 def _transform(self, value, field_type):244 '''245 This is method is only used when parsing customized global params from env.246 Only checkbox type needs transform. Other types will be extracted automatically when apply json.loads.247 :param value:248 :param field_type: can be checkbox, text, password, dropdownlist, multi_dropdownlist, radiogroup249 :return:250 '''251 if field_type == TYPE_CHECKBOX:252 return utils.is_true(value)253 elif field_type in ALL_SETTING_TYPES:254 return value255 else:256 raise Exception("Type of this customized setting is corrupted. Value: {}, type: {}"257 .format(value, field_type))258 '''259 # the following methods is used by AoB internally260 # user should not use this261 # These methods returns the similiar structure like ucc libs262 the output of config is like263{264 "account": [265 {266 "username": "admin",267 "credential": "a",268 "name": "ddddd",269 "disabled": false270 }271 ]272}273 the output of settings is like274{275 "settings": [276 {277 "additional_parameters": {278 "checkbox": "1",279 "text": "msn",280 "disabled": false281 }282 },283 {284 "proxy": {285 "proxy_type": "http",286 "proxy_port": "9999",287 "proxy_url": "localhost",288 "proxy_rdns": "1",289 "disabled": false,290 "proxy_password": "a",291 "proxy_username": "admin",292 "proxy_enabled": "1"293 }294 },295 {296 "logging": {297 "loglevel": "ERROR",298 "disabled": false299 }300 }301 ]302}303 '''304 def get_ucc_log_setting(self):305 return {UCC_LOGGING: self._parse_conf(LOG_SETTINGS)}306 def get_ucc_proxy_setting(self):307 p = dict(self.get_proxy_settings())308 p[PROXY_ENABLE_KEY] = True if p else False309 return {310 UCC_PROXY: p311 }312 def get_ucc_customized_setting(self):313 customized_settings = self._parse_conf(CUSTOMIZED_SETTINGS)314 if customized_settings:315 return {316 UCC_CUSTOMIZED: customized_settings317 }318 else:319 return {}320 # account belongs to the configs321 def get_ucc_account_config(self):...

Full Screen

Full Screen

widgets.py

Source:widgets.py Github

copy

Full Screen

1# coding:utf-82from django import forms3from django.conf import settings4from django.contrib.admin.widgets import AdminTextareaWidget5from django.template.loader import render_to_string6from django.utils.safestring import mark_safe7from django.utils.http import urlencode8from . import settings as USettings9from .commands import *10from django.utils.six import string_types11# 修正输入的文件路径,输入路径的标准格式:abc,不需要前后置的路径符号12# 如果输入的路径参数是一个函数则执行,否则可以拉接受时间格式化,用来生成如file20121208.bmp的重命名格式13def calc_path(OutputPath, instance=None):14 if callable(OutputPath):15 try:16 OutputPath = OutputPath(instance)17 except:18 OutputPath = ""19 else:20 try:21 import datetime22 OutputPath = datetime.datetime.now().strftime(OutputPath)23 except:24 pass25 return OutputPath26# width=600, height=300, toolbars="full", imagePath="", filePath="", upload_settings={},27 # settings={},command=None,event_handler=None28class UEditorWidget(forms.Textarea):29 def __init__(self, attrs=None):30 params = attrs.copy()31 width = params.pop("width")32 height = params.pop("height")33 toolbars = params.pop("toolbars", "full")34 imagePath = params.pop("imagePath", "")35 filePath = params.pop("filePath", "")36 upload_settings = params.pop("upload_settings", {})37 settings = params.pop("settings", {})38 command = params.pop("command", None)39 event_handler = params.pop("event_handler", None)40 # 扩展命令41 self.command = command42 self.event_handler = event_handler43 # 上传路径44 self.upload_settings = upload_settings.copy()45 self.upload_settings.update({46 "imagePathFormat": imagePath,47 "filePathFormat": filePath48 })49 # 保存50 self._upload_settings = self.upload_settings.copy()51 self.recalc_path(None)52 self.ueditor_settings = {53 'toolbars': toolbars,54 'initialFrameWidth': width,55 'initialFrameHeight': height56 }57 # 以下处理工具栏设置,将normal,mini等模式名称转化为工具栏配置值58 if toolbars == "full":59 del self.ueditor_settings['toolbars']60 elif isinstance(toolbars, string_types) and toolbars in USettings.TOOLBARS_SETTINGS:61 self.ueditor_settings[62 "toolbars"] = USettings.TOOLBARS_SETTINGS[toolbars]63 else:64 self.ueditor_settings["toolbars"] = toolbars65 # raise ValueError('toolbars should be a string defined in DjangoUeditor.settings.TOOLBARS_SETTINGS, options are full(default), besttome, mini and normal!')66 self.ueditor_settings.update(settings)67 super(UEditorWidget, self).__init__(attrs)68 def recalc_path(self, model_inst):69 """计算上传路径,允许是function"""70 try:71 uSettings = self.upload_settings72 if 'filePathFormat' in self._upload_settings:73 uSettings['filePathFormat'] = calc_path(74 self._upload_settings['filePathFormat'], model_inst)75 if 'imagePathFormat' in self._upload_settings:76 uSettings['imagePathFormat'] = calc_path(77 self._upload_settings['imagePathFormat'], model_inst)78 if 'scrawlPathFormat' in self._upload_settings:79 uSettings['scrawlPathFormat'] = calc_path(80 self._upload_settings['scrawlPathFormat'], model_inst)81 if 'videoPathFormat' in self._upload_settings:82 uSettings['videoPathFormat'] = calc_path(83 self._upload_settings['videoPathFormat'], model_inst),84 if 'snapscreenPathFormat' in self._upload_settings:85 uSettings['snapscreenPathFormat'] = calc_path(86 self._upload_settings['snapscreenPathFormat'], model_inst)87 if 'catcherPathFormat' in self._upload_settings:88 uSettings['catcherPathFormat'] = calc_path(89 self._upload_settings['catcherPathFormat'], model_inst)90 if 'imageManagerListPath' in self._upload_settings:91 uSettings['imageManagerListPath'] = calc_path(92 self._upload_settings['imageManagerListPath'], model_inst)93 if 'fileManagerListPath' in self._upload_settings:94 uSettings['fileManagerListPath'] = calc_path(95 self._upload_settings['fileManagerListPath'], model_inst)96 # 设置默认值,未指定涂鸦、截图、远程抓图、图片目录时,默认均等于imagePath97 if uSettings['imagePathFormat'] != "":98 default_path = uSettings['imagePathFormat']99 uSettings['scrawlPathFormat'] = uSettings.get(100 'scrawlPathFormat', default_path)101 uSettings['videoPathFormat'] = uSettings.get(102 'videoPathFormat', default_path)103 uSettings['snapscreenPathFormat'] = uSettings.get(104 'snapscreenPathFormat', default_path)105 uSettings['catcherPathFormat'] = uSettings.get(106 'catcherPathFormat', default_path)107 uSettings['imageManagerListPath'] = uSettings.get(108 'imageManagerListPath', default_path)109 if uSettings['filePathFormat'] != "":110 uSettings['fileManagerListPath'] = uSettings.get(111 'fileManagerListPath', uSettings['filePathFormat'])112 except:113 pass114 def render(self, name, value, attrs=None):115 if value is None:116 value = ''117 # 传入模板的参数118 editor_id = "id_%s" % name.replace("-", "_")119 uSettings = {120 "name": name,121 "id": editor_id,122 "value": value123 }124 if isinstance(self.command, list):125 cmdjs = ""126 if isinstance(self.command, list):127 for cmd in self.command:128 cmdjs = cmdjs + cmd.render(editor_id)129 else:130 cmdjs = self.command.render(editor_id)131 uSettings["commands"] = cmdjs132 uSettings["settings"] = self.ueditor_settings.copy()133 uSettings["settings"].update({134 "serverUrl": "/ueditor/controller/?%s" % urlencode(self._upload_settings)135 })136 # 生成事件侦听137 if self.event_handler:138 uSettings["bindEvents"] = self.event_handler.render(editor_id)139 context = {140 'UEditor': uSettings,141 'STATIC_URL': settings.STATIC_URL,142 'STATIC_ROOT': settings.STATIC_ROOT,143 'MEDIA_URL': settings.MEDIA_URL,144 'MEDIA_ROOT': settings.MEDIA_ROOT145 }146 return mark_safe(render_to_string('ueditor.html', context))147 class Media:148 js = ("ueditor/ueditor.config.js",149 "ueditor/ueditor.all.min.js")150class AdminUEditorWidget(AdminTextareaWidget, UEditorWidget):151 def __init__(self, **kwargs):...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run fMBT automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful