code
stringlengths 1
5.19M
| package
stringlengths 1
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
/**
* Galleria - v1.5.6 2017-04-08
* https://galleria.io
*
* Copyright (c) 2010 - 2017 worse is better UG
* Licensed under the MIT License.
* https://raw.github.com/worseisbetter/galleria/master/LICENSE
*
*/
!function(a,b){Galleria.requires(1.25,"The History Plugin requires Galleria version 1.2.5 or later."),Galleria.History=function(){var c,d=[],e=!1,f=b.location,g=b.document,h=Galleria.IE,i="onhashchange"in b&&(void 0===g.mode||g.mode>7),j=function(a){return a=c&&!i&&Galleria.IE?a||c.location:f,parseInt(a.hash.substr(2),10)},k=j(f),l=[],m=function(){a.each(l,function(a,c){c.call(b,j())})},n=function(){a.each(d,function(a,b){b()}),e=!0},o=function(a){return"/"+a};return i&&h<8&&(i=!1),i?n():a(function(){b.setInterval(function(){var a=j();isNaN(a)||a==k||(k=a,f.hash=o(a),m())},50);h?a('<iframe tabindex="-1" title="empty">').hide().attr("src","about:blank").one("load",function(){c=this.contentWindow,n()}).insertAfter(g.body):n()}),{change:function(a){l.push(a),i&&(b.onhashchange=m)},set:function(a){isNaN(a)||(!i&&h&&this.ready(function(){var b=c.document;b.open(),b.close(),c.location.hash=o(a)}),f.hash=o(a))},ready:function(a){e?a():d.push(a)}}}()}(jQuery,this); | 153957-theme | /153957-theme-2.tar.gz/153957-theme-2/153957_theme/static/js/galleria.history.min.js | galleria.history.min.js |
/**
* Galleria - v1.5.6 2017-04-08
* https://galleria.io
*
* Copyright (c) 2010 - 2017 worse is better UG
* Licensed under the MIT License.
* https://raw.github.com/worseisbetter/galleria/master/LICENSE
*
*/
!function(a){Galleria.addTheme({name:"classic",version:1.5,author:"Galleria",css:"galleria.classic.css",defaults:{transition:"slide",thumbCrop:"height",_toggleInfo:!0},init:function(b){Galleria.requires(1.4,"This version of Classic theme requires Galleria 1.4 or later"),this.addElement("info-link","info-close"),this.append({info:["info-link","info-close"]});var c=this.$("info-link,info-close,info-text"),d=Galleria.TOUCH;this.$("loader,counter").show().css("opacity",.4),d||(this.addIdleState(this.get("image-nav-left"),{left:-50}),this.addIdleState(this.get("image-nav-right"),{right:-50}),this.addIdleState(this.get("counter"),{opacity:0})),b._toggleInfo===!0?c.bind("click:fast",function(){c.toggle()}):(c.show(),this.$("info-link, info-close").hide()),this.bind("thumbnail",function(b){d?a(b.thumbTarget).css("opacity",this.getIndex()?1:.6).bind("click:fast",function(){a(this).css("opacity",1).parent().siblings().children().css("opacity",.6)}):(a(b.thumbTarget).css("opacity",.6).parent().hover(function(){a(this).not(".active").children().stop().fadeTo(100,1)},function(){a(this).not(".active").children().stop().fadeTo(400,.6)}),b.index===this.getIndex()&&a(b.thumbTarget).css("opacity",1))});var e=function(b){a(b.thumbTarget).css("opacity",1).parent().siblings().children().css("opacity",.6)};this.bind("loadstart",function(a){a.cached||this.$("loader").show().fadeTo(200,.4),window.setTimeout(function(){e(a)},d?300:0),this.$("info").toggle(this.hasInfo())}),this.bind("loadfinish",function(a){this.$("loader").fadeOut(200)})}})}(jQuery); | 153957-theme | /153957-theme-2.tar.gz/153957-theme-2/153957_theme/static/js/galleria.classic.min.js | galleria.classic.min.js |
/**
* Galleria - v1.5.6 2017-04-08
* https://galleria.io
*
* Copyright (c) 2010 - 2017 worse is better UG
* Licensed under the MIT License.
* https://raw.github.com/worseisbetter/galleria/master/LICENSE
*
*/
!function(a,b,c,d){var e=b.document,f=a(e),g=a(b),h=Array.prototype,i=1.56,j=!0,k=3e4,l=!1,m=navigator.userAgent.toLowerCase(),n=b.location.hash.replace(/#\//,""),o="file:"==b.location.protocol?"http:":b.location.protocol,p=Math,q=function(){},r=function(){return!1},s=function(){var a=3,b=e.createElement("div"),c=b.getElementsByTagName("i");do b.innerHTML="<!--[if gt IE "+ ++a+"]><i></i><![endif]-->";while(c[0]);return a>4?a:e.documentMode||d}(),t=function(){return{html:e.documentElement,body:e.body,head:e.getElementsByTagName("head")[0],title:e.title}},u=b.parent!==b.self,v="data ready thumbnail loadstart loadfinish image play pause progress fullscreen_enter fullscreen_exit idle_enter idle_exit rescale lightbox_open lightbox_close lightbox_image",w=function(){var b=[];return a.each(v.split(" "),function(a,c){b.push(c),/_/.test(c)&&b.push(c.replace(/_/g,""))}),b}(),x=function(b){var c;return"object"!=typeof b?b:(a.each(b,function(d,e){/^[a-z]+_/.test(d)&&(c="",a.each(d.split("_"),function(a,b){c+=a>0?b.substr(0,1).toUpperCase()+b.substr(1):b}),b[c]=e,delete b[d])}),b)},y=function(b){return a.inArray(b,w)>-1?c[b.toUpperCase()]:b},z={youtube:{reg:/https?:\/\/(?:[a-zA_Z]{2,3}.)?(?:youtube\.com\/watch\?)((?:[\w\d\-\_\=]+&(?:amp;)?)*v(?:<[A-Z]+>)?=([0-9a-zA-Z\-\_]+))/i,embed:function(){return o+"//www.youtube.com/embed/"+this.id},get_thumb:function(a){return o+"//img.youtube.com/vi/"+this.id+"/default.jpg"},get_image:function(a){return o+"//img.youtube.com/vi/"+this.id+"/hqdefault.jpg"}},vimeo:{reg:/https?:\/\/(?:www\.)?(vimeo\.com)\/(?:hd#)?([0-9]+)/i,embed:function(){return o+"//player.vimeo.com/video/"+this.id},getUrl:function(){return o+"//vimeo.com/api/v2/video/"+this.id+".json?callback=?"},get_thumb:function(a){return a[0].thumbnail_medium},get_image:function(a){return a[0].thumbnail_large}},dailymotion:{reg:/https?:\/\/(?:www\.)?(dailymotion\.com)\/video\/([^_]+)/,embed:function(){return o+"//www.dailymotion.com/embed/video/"+this.id},getUrl:function(){return"https://api.dailymotion.com/video/"+this.id+"?fields=thumbnail_240_url,thumbnail_720_url&callback=?"},get_thumb:function(a){return a.thumbnail_240_url},get_image:function(a){return a.thumbnail_720_url}},_inst:[]},A=function(c,d){for(var e=0;e<z._inst.length;e++)if(z._inst[e].id===d&&z._inst[e].type==c)return z._inst[e];this.type=c,this.id=d,this.readys=[],z._inst.push(this);var f=this;a.extend(this,z[c]),_videoThumbs=function(b){f.data=b,a.each(f.readys,function(a,b){b(f.data)}),f.readys=[]},this.hasOwnProperty("getUrl")?a.getJSON(this.getUrl(),_videoThumbs):b.setTimeout(_videoThumbs,400),this.getMedia=function(a,b,c){c=c||q;var d=this,e=function(c){b(d["get_"+a](c))};try{d.data?e(d.data):d.readys.push(e)}catch(a){c()}}},B=function(a){var b;for(var c in z)if(b=a&&z[c].reg&&a.match(z[c].reg),b&&b.length)return{id:b[2],provider:c};return!1},C={support:function(){var a=t().html;return!u&&(a.requestFullscreen||a.msRequestFullscreen||a.mozRequestFullScreen||a.webkitRequestFullScreen)}(),callback:q,enter:function(a,b,c){this.instance=a,this.callback=b||q,c=c||t().html,c.requestFullscreen?c.requestFullscreen():c.msRequestFullscreen?c.msRequestFullscreen():c.mozRequestFullScreen?c.mozRequestFullScreen():c.webkitRequestFullScreen&&c.webkitRequestFullScreen()},exit:function(a){this.callback=a||q,e.exitFullscreen?e.exitFullscreen():e.msExitFullscreen?e.msExitFullscreen():e.mozCancelFullScreen?e.mozCancelFullScreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()},instance:null,listen:function(){if(this.support){var a=function(){if(C.instance){var a=C.instance._fullscreen;e.fullscreen||e.mozFullScreen||e.webkitIsFullScreen||e.msFullscreenElement&&null!==e.msFullscreenElement?a._enter(C.callback):a._exit(C.callback)}};e.addEventListener("fullscreenchange",a,!1),e.addEventListener("MSFullscreenChange",a,!1),e.addEventListener("mozfullscreenchange",a,!1),e.addEventListener("webkitfullscreenchange",a,!1)}}},D=[],E=[],F=!1,G=!1,H=[],I=[],J=function(b){I.push(b),a.each(H,function(a,c){c._options.theme!=b.name&&(c._initialized||c._options.theme)||(c.theme=b,c._init.call(c))})},K=function(){return{clearTimer:function(b){a.each(c.get(),function(){this.clearTimer(b)})},addTimer:function(b){a.each(c.get(),function(){this.addTimer(b)})},array:function(a){return h.slice.call(a,0)},create:function(a,b){b=b||"div";var c=e.createElement(b);return c.className=a,c},removeFromArray:function(b,c){return a.each(b,function(a,d){if(d==c)return b.splice(a,1),!1}),b},getScriptPath:function(b){b=b||a("script:last").attr("src");var c=b.split("/");return 1==c.length?"":(c.pop(),c.join("/")+"/")},animate:function(){var d,f,g,h,i,j,k,l=function(a){var c,d="transition WebkitTransition MozTransition OTransition".split(" ");if(b.opera)return!1;for(c=0;d[c];c++)if("undefined"!=typeof a[d[c]])return d[c];return!1}((e.body||e.documentElement).style),m={MozTransition:"transitionend",OTransition:"oTransitionEnd",WebkitTransition:"webkitTransitionEnd",transition:"transitionend"}[l],n={_default:[.25,.1,.25,1],galleria:[.645,.045,.355,1],galleriaIn:[.55,.085,.68,.53],galleriaOut:[.25,.46,.45,.94],ease:[.25,0,.25,1],linear:[.25,.25,.75,.75],"ease-in":[.42,0,1,1],"ease-out":[0,0,.58,1],"ease-in-out":[.42,0,.58,1]},o=function(b,c,d){var e={};d=d||"transition",a.each("webkit moz ms o".split(" "),function(){e["-"+this+"-"+d]=c}),b.css(e)},p=function(a){o(a,"none","transition"),c.WEBKIT&&c.TOUCH&&(o(a,"translate3d(0,0,0)","transform"),a.data("revert")&&(a.css(a.data("revert")),a.data("revert",null)))};return function(e,r,s){return s=a.extend({duration:400,complete:q,stop:!1},s),e=a(e),s.duration?l?(s.stop&&(e.off(m),p(e)),d=!1,a.each(r,function(a,b){k=e.css(a),K.parseValue(k)!=K.parseValue(b)&&(d=!0),e.css(a,k)}),d?(f=[],g=s.easing in n?n[s.easing]:n._default,h=" "+s.duration+"ms cubic-bezier("+g.join(",")+")",void b.setTimeout(function(b,d,e,g){return function(){b.one(d,function(a){return function(){p(a),s.complete.call(a[0])}}(b)),c.WEBKIT&&c.TOUCH&&(i={},j=[0,0,0],a.each(["left","top"],function(a,c){c in e&&(j[a]=K.parseValue(e[c])-K.parseValue(b.css(c))+"px",i[c]=e[c],delete e[c])}),(j[0]||j[1])&&(b.data("revert",i),f.push("-webkit-transform"+g),o(b,"translate3d("+j.join(",")+")","transform"))),a.each(e,function(a,b){f.push(a+g)}),o(b,f.join(",")),b.css(e)}}(e,m,r,h),2)):void b.setTimeout(function(){s.complete.call(e[0])},s.duration)):void e.animate(r,s):(e.css(r),void s.complete.call(e[0]))}}(),removeAlpha:function(a){if(a instanceof jQuery&&(a=a[0]),s<9&&a){var b=a.style,c=a.currentStyle,d=c&&c.filter||b.filter||"";/alpha/.test(d)&&(b.filter=d.replace(/alpha\([^)]*\)/i,""))}},forceStyles:function(b,c){b=a(b),b.attr("style")&&b.data("styles",b.attr("style")).removeAttr("style"),b.css(c)},revertStyles:function(){a.each(K.array(arguments),function(b,c){c=a(c),c.removeAttr("style"),c.attr("style",""),c.data("styles")&&c.attr("style",c.data("styles")).data("styles",null)})},moveOut:function(a){K.forceStyles(a,{position:"absolute",left:-1e4})},moveIn:function(){K.revertStyles.apply(K,K.array(arguments))},hide:function(b,c,d){d=d||q;var e=a(b);b=e[0],e.data("opacity")||e.data("opacity",e.css("opacity"));var f={opacity:0};if(c){var g=s<9&&b?function(){K.removeAlpha(b),b.style.visibility="hidden",d.call(b)}:d;K.animate(b,f,{duration:c,complete:g,stop:!0})}else s<9&&b?(K.removeAlpha(b),b.style.visibility="hidden"):e.css(f)},show:function(b,c,d){d=d||q;var e=a(b);b=e[0];var f=parseFloat(e.data("opacity"))||1,g={opacity:f};if(c){s<9&&(e.css("opacity",0),b.style.visibility="visible");var h=s<9&&b?function(){1==g.opacity&&K.removeAlpha(b),d.call(b)}:d;K.animate(b,g,{duration:c,complete:h,stop:!0})}else s<9&&1==g.opacity&&b?(K.removeAlpha(b),b.style.visibility="visible"):e.css(g)},wait:function(d){c._waiters=c._waiters||[],d=a.extend({until:r,success:q,error:function(){c.raise("Could not complete wait function.")},timeout:3e3},d);var e,f,g,h=K.timestamp(),i=function(){return f=K.timestamp(),e=f-h,K.removeFromArray(c._waiters,g),d.until(e)?(d.success(),!1):"number"==typeof d.timeout&&f>=h+d.timeout?(d.error(),!1):void c._waiters.push(g=b.setTimeout(i,10))};c._waiters.push(g=b.setTimeout(i,10))},toggleQuality:function(a,b){7!==s&&8!==s||!a||"IMG"!=a.nodeName.toUpperCase()||("undefined"==typeof b&&(b="nearest-neighbor"===a.style.msInterpolationMode),a.style.msInterpolationMode=b?"bicubic":"nearest-neighbor")},insertStyleTag:function(b,c){if(!c||!a("#"+c).length){var d=e.createElement("style");if(c&&(d.id=c),t().head.appendChild(d),d.styleSheet)d.styleSheet.cssText=b;else{var f=e.createTextNode(b);d.appendChild(f)}}},loadScript:function(b,c){var d=!1,e=a("<script>").attr({src:b,async:!0}).get(0);e.onload=e.onreadystatechange=function(){d||this.readyState&&"loaded"!==this.readyState&&"complete"!==this.readyState||(d=!0,e.onload=e.onreadystatechange=null,"function"==typeof c&&c.call(this,this))},t().head.appendChild(e)},parseValue:function(a){if("number"==typeof a)return a;if("string"==typeof a){var b=a.match(/\-?\d|\./g);return b&&b.constructor===Array?1*b.join(""):0}return 0},timestamp:function(){return(new Date).getTime()},loadCSS:function(b,f,g){var h,i;if(a("link[rel=stylesheet]").each(function(){if(new RegExp(b).test(this.href))return h=this,!1}),"function"==typeof f&&(g=f,f=d),g=g||q,h)return g.call(h,h),h;if(i=e.styleSheets.length,a("#"+f).length)a("#"+f).attr("href",b),i--;else{h=a("<link>").attr({rel:"stylesheet",href:b,id:f}).get(0);var j=a('link[rel="stylesheet"], style');if(j.length?j.get(0).parentNode.insertBefore(h,j[0]):t().head.appendChild(h),s&&i>=31)return void c.raise("You have reached the browser stylesheet limit (31)",!0)}if("function"==typeof g){var k=a("<s>").attr("id","galleria-loader").hide().appendTo(t().body);K.wait({until:function(){return k.height()>0},success:function(){k.remove(),g.call(h,h)},error:function(){k.remove(),c.raise("Theme CSS could not load after 20 sec. "+(c.QUIRK?"Your browser is in Quirks Mode, please add a correct doctype.":"Please download the latest theme at http://galleria.io/customer/."),!0)},timeout:5e3})}return h}}}(),L=function(b){var c=".galleria-videoicon{width:60px;height:60px;position:absolute;top:50%;left:50%;z-index:1;margin:-30px 0 0 -30px;cursor:pointer;background:#000;background:rgba(0,0,0,.8);border-radius:3px;-webkit-transition:all 150ms}.galleria-videoicon i{width:0px;height:0px;border-style:solid;border-width:10px 0 10px 16px;display:block;border-color:transparent transparent transparent #ffffff;margin:20px 0 0 22px}.galleria-image:hover .galleria-videoicon{background:#000}";return K.insertStyleTag(c,"galleria-videoicon"),a(K.create("galleria-videoicon")).html("<i></i>").appendTo(b).click(function(){a(this).siblings("img").mouseup()})},M=function(){var b=function(b,c,d,e){var f=this.getOptions("easing"),g=this.getStageWidth(),h={left:g*(b.rewind?-1:1)},i={left:0};d?(h.opacity=0,i.opacity=1):h.opacity=1,a(b.next).css(h),K.animate(b.next,i,{duration:b.speed,complete:function(a){return function(){c(),a.css({left:0})}}(a(b.next).add(b.prev)),queue:!1,easing:f}),e&&(b.rewind=!b.rewind),b.prev&&(h={left:0},i={left:g*(b.rewind?1:-1)},d&&(h.opacity=1,i.opacity=0),a(b.prev).css(h),K.animate(b.prev,i,{duration:b.speed,queue:!1,easing:f,complete:function(){a(this).css("opacity",0)}}))};return{active:!1,init:function(a,b,c){M.effects.hasOwnProperty(a)&&M.effects[a].call(this,b,c)},effects:{fade:function(b,c){a(b.next).css({opacity:0,left:0}),K.animate(b.next,{opacity:1},{duration:b.speed,complete:c}),b.prev&&(a(b.prev).css("opacity",1).show(),K.animate(b.prev,{opacity:0},{duration:b.speed}))},flash:function(b,c){a(b.next).css({opacity:0,left:0}),b.prev?K.animate(b.prev,{opacity:0},{duration:b.speed/2,complete:function(){K.animate(b.next,{opacity:1},{duration:b.speed,complete:c})}}):K.animate(b.next,{opacity:1},{duration:b.speed,complete:c})},pulse:function(b,c){b.prev&&a(b.prev).hide(),a(b.next).css({opacity:0,left:0}).show(),K.animate(b.next,{opacity:1},{duration:b.speed,complete:c})},slide:function(a,c){b.apply(this,K.array(arguments))},fadeslide:function(a,c){b.apply(this,K.array(arguments).concat([!0]))},doorslide:function(a,c){b.apply(this,K.array(arguments).concat([!1,!0]))}}}}();C.listen(),a.event.special["click:fast"]={propagate:!0,add:function(c){var d=function(a){if(a.touches&&a.touches.length){var b=a.touches[0];return{x:b.pageX,y:b.pageY}}},e={touched:!1,touchdown:!1,coords:{x:0,y:0},evObj:{}};a(this).data({clickstate:e,timer:0}).on("touchstart.fast",function(c){b.clearTimeout(a(this).data("timer")),a(this).data("clickstate",{touched:!0,touchdown:!0,coords:d(c.originalEvent),evObj:c})}).on("touchmove.fast",function(b){var c=d(b.originalEvent),e=a(this).data("clickstate"),f=Math.max(Math.abs(e.coords.x-c.x),Math.abs(e.coords.y-c.y));f>6&&a(this).data("clickstate",a.extend(e,{touchdown:!1}))}).on("touchend.fast",function(d){var f=a(this),g=f.data("clickstate");g.touchdown&&c.handler.call(this,d),f.data("timer",b.setTimeout(function(){f.data("clickstate",e)},400))}).on("click.fast",function(b){var d=a(this).data("clickstate");return!d.touched&&(a(this).data("clickstate",e),void c.handler.call(this,b))})},remove:function(){a(this).off("touchstart.fast touchmove.fast touchend.fast click.fast")}},g.on("orientationchange",function(){a(this).resize()}),c=function(){var h=this;this._options={},this._playing=!1,this._playtime=5e3,this._active=null,this._queue={length:0},this._data=[],this._dom={},this._thumbnails=[],this._layers=[],this._initialized=!1,this._firstrun=!1,this._stageWidth=0,this._stageHeight=0,this._target=d,this._binds=[],this._id=parseInt(1e4*p.random(),10);var i="container stage images image-nav image-nav-left image-nav-right info info-text info-title info-description thumbnails thumbnails-list thumbnails-container thumb-nav-left thumb-nav-right loader counter tooltip",j="current total";a.each(i.split(" "),function(a,b){h._dom[b]=K.create("galleria-"+b)}),a.each(j.split(" "),function(a,b){h._dom[b]=K.create("galleria-"+b,"span")});var k=this._keyboard={keys:{UP:38,DOWN:40,LEFT:37,RIGHT:39,RETURN:13,ESCAPE:27,BACKSPACE:8,SPACE:32},map:{},bound:!1,press:function(a){var b=a.keyCode||a.which;b in k.map&&"function"==typeof k.map[b]&&k.map[b].call(h,a)},attach:function(a){var b,c;for(b in a)a.hasOwnProperty(b)&&(c=b.toUpperCase(),c in k.keys?k.map[k.keys[c]]=a[b]:k.map[c]=a[b]);k.bound||(k.bound=!0,f.on("keydown",k.press))},detach:function(){k.bound=!1,k.map={},f.off("keydown",k.press)}},l=this._controls={0:d,1:d,active:0,swap:function(){l.active=l.active?0:1},getActive:function(){return h._options.swipe?l.slides[h._active]:l[l.active]},getNext:function(){return h._options.swipe?l.slides[h.getNext(h._active)]:l[1-l.active]},slides:[],frames:[],layers:[]},n=this._carousel={next:h.$("thumb-nav-right"),prev:h.$("thumb-nav-left"),width:0,current:0,max:0,hooks:[],update:function(){var b=0,c=0,d=[0];a.each(h._thumbnails,function(e,f){if(f.ready){b+=f.outerWidth||a(f.container).outerWidth(!0);var g=a(f.container).width();b+=g-p.floor(g),d[e+1]=b,c=p.max(c,f.outerHeight||a(f.container).outerHeight(!0))}}),h.$("thumbnails").css({width:b,height:c}),n.max=b,n.hooks=d,n.width=h.$("thumbnails-list").width(),n.setClasses(),h.$("thumbnails-container").toggleClass("galleria-carousel",b>n.width),n.width=h.$("thumbnails-list").width()},bindControls:function(){var a;n.next.on("click:fast",function(b){if(b.preventDefault(),"auto"===h._options.carouselSteps){for(a=n.current;a<n.hooks.length;a++)if(n.hooks[a]-n.hooks[n.current]>n.width){n.set(a-2);break}}else n.set(n.current+h._options.carouselSteps)}),n.prev.on("click:fast",function(b){if(b.preventDefault(),"auto"===h._options.carouselSteps)for(a=n.current;a>=0;a--){if(n.hooks[n.current]-n.hooks[a]>n.width){n.set(a+2);break}if(0===a){n.set(0);break}}else n.set(n.current-h._options.carouselSteps)})},set:function(a){for(a=p.max(a,0);n.hooks[a-1]+n.width>=n.max&&a>=0;)a--;n.current=a,n.animate()},getLast:function(a){return(a||n.current)-1},follow:function(a){if(0===a||a===n.hooks.length-2)return void n.set(a);for(var b=n.current;n.hooks[b]-n.hooks[n.current]<n.width&&b<=n.hooks.length;)b++;a-1<n.current?n.set(a-1):a+2>b&&n.set(a-b+n.current+2)},setClasses:function(){n.prev.toggleClass("disabled",!n.current),n.next.toggleClass("disabled",n.hooks[n.current]+n.width>=n.max)},animate:function(b){n.setClasses();var c=n.hooks[n.current]*-1;isNaN(c)||(h.$("thumbnails").css("left",function(){return a(this).css("left")}),K.animate(h.get("thumbnails"),{left:c},{duration:h._options.carouselSpeed,easing:h._options.easing,queue:!1}))}},o=this._tooltip={initialized:!1,open:!1,timer:"tooltip"+h._id,swapTimer:"swap"+h._id,init:function(){o.initialized=!0;var a=".galleria-tooltip{padding:3px 8px;max-width:50%;background:#ffe;color:#000;z-index:3;position:absolute;font-size:11px;line-height:1.3;opacity:0;box-shadow:0 0 2px rgba(0,0,0,.4);-moz-box-shadow:0 0 2px rgba(0,0,0,.4);-webkit-box-shadow:0 0 2px rgba(0,0,0,.4);}";K.insertStyleTag(a,"galleria-tooltip"),h.$("tooltip").css({opacity:.8,visibility:"visible",display:"none"})},move:function(a){var b=h.getMousePosition(a).x,c=h.getMousePosition(a).y,d=h.$("tooltip"),e=b,f=c,g=d.outerHeight(!0)+1,i=d.outerWidth(!0),j=g+15,k=h.$("container").width()-i-2,l=h.$("container").height()-g-2;isNaN(e)||isNaN(f)||(e+=10,f-=g+8,e=p.max(0,p.min(k,e)),f=p.max(0,p.min(l,f)),c<j&&(f=j),d.css({left:e,top:f}))},bind:function(b,d){if(!c.TOUCH){o.initialized||o.init();var e=function(){h.$("container").off("mousemove",o.move),h.clearTimer(o.timer),h.$("tooltip").stop().animate({opacity:0},200,function(){h.$("tooltip").hide(),h.addTimer(o.swapTimer,function(){o.open=!1},1e3)})},f=function(b,c){o.define(b,c),a(b).hover(function(){h.clearTimer(o.swapTimer),h.$("container").off("mousemove",o.move).on("mousemove",o.move).trigger("mousemove"),o.show(b),h.addTimer(o.timer,function(){h.$("tooltip").stop().show().animate({opacity:1}),o.open=!0},o.open?0:500)},e).click(e)};"string"==typeof d?f(b in h._dom?h.get(b):b,d):a.each(b,function(a,b){f(h.get(a),b)})}},show:function(c){c=a(c in h._dom?h.get(c):c);var d=c.data("tt"),e=function(a){b.setTimeout(function(a){return function(){o.move(a)}}(a),10),c.off("mouseup",e)};d="function"==typeof d?d():d,d&&(h.$("tooltip").html(d.replace(/\s/," ")),c.on("mouseup",e))},define:function(b,c){if("function"!=typeof c){var d=c;c=function(){return d}}b=a(b in h._dom?h.get(b):b).data("tt",c),o.show(b)}},q=this._fullscreen={scrolled:0,crop:d,active:!1,prev:a(),beforeEnter:function(a){a()},beforeExit:function(a){a()},keymap:h._keyboard.map,parseCallback:function(b,c){return M.active?function(){"function"==typeof b&&b.call(h);var d=h._controls.getActive(),e=h._controls.getNext();h._scaleImage(e),h._scaleImage(d),c&&h._options.trueFullscreen&&a(d.container).add(e.container).trigger("transitionend")}:b},enter:function(a){q.beforeEnter(function(){a=q.parseCallback(a,!0),h._options.trueFullscreen&&C.support?(q.active=!0,K.forceStyles(h.get("container"),{width:"100%",height:"100%"}),h.rescale(),c.MAC?c.SAFARI&&/version\/[1-5]/.test(m)?(h.$("stage").css("opacity",0),b.setTimeout(function(){q.scale(),h.$("stage").css("opacity",1)},4)):(h.$("container").css("opacity",0).addClass("fullscreen"),b.setTimeout(function(){q.scale(),h.$("container").css("opacity",1)},50)):h.$("container").addClass("fullscreen"),g.resize(q.scale),C.enter(h,a,h.get("container"))):(q.scrolled=g.scrollTop(),c.TOUCH||b.scrollTo(0,0),q._enter(a))})},_enter:function(f){q.active=!0,u&&(q.iframe=function(){var d,f=e.referrer,g=e.createElement("a"),h=b.location;return g.href=f,g.protocol!=h.protocol||g.hostname!=h.hostname||g.port!=h.port?(c.raise("Parent fullscreen not available. Iframe protocol, domains and ports must match."),!1):(q.pd=b.parent.document,a(q.pd).find("iframe").each(function(){var a=this.contentDocument||this.contentWindow.document;if(a===e)return d=this,!1}),d)}()),K.hide(h.getActiveImage()),u&&q.iframe&&(q.iframe.scrolled=a(b.parent).scrollTop(),b.parent.scrollTo(0,0));var i=h.getData(),j=h._options,k=!h._options.trueFullscreen||!C.support,l={height:"100%",overflow:"hidden",margin:0,padding:0};if(k&&(h.$("container").addClass("fullscreen"),q.prev=h.$("container").prev(),q.prev.length||(q.parent=h.$("container").parent()),h.$("container").appendTo("body"),K.forceStyles(h.get("container"),{position:c.TOUCH?"absolute":"fixed",top:0,left:0,width:"100%",height:"100%",zIndex:1e4}),K.forceStyles(t().html,l),K.forceStyles(t().body,l)),u&&q.iframe&&(K.forceStyles(q.pd.documentElement,l),K.forceStyles(q.pd.body,l),K.forceStyles(q.iframe,a.extend(l,{width:"100%",height:"100%",top:0,left:0,position:"fixed",zIndex:1e4,border:"none"}))),q.keymap=a.extend({},h._keyboard.map),h.attachKeyboard({escape:h.exitFullscreen,right:h.next,left:h.prev}),q.crop=j.imageCrop,j.fullscreenCrop!=d&&(j.imageCrop=j.fullscreenCrop),i&&i.big&&i.image!==i.big){var m=new c.Picture,n=m.isCached(i.big),o=h.getIndex(),p=h._thumbnails[o];h.trigger({type:c.LOADSTART,cached:n,rewind:!1,index:o,imageTarget:h.getActiveImage(),thumbTarget:p,galleriaData:i}),m.load(i.big,function(b){h._scaleImage(b,{complete:function(b){h.trigger({type:c.LOADFINISH,cached:n,index:o,rewind:!1,imageTarget:b.image,thumbTarget:p});var d=h._controls.getActive().image;d&&a(d).width(b.image.width).height(b.image.height).attr("style",a(b.image).attr("style")).attr("src",b.image.src)}})});var r=h.getNext(o),s=new c.Picture,v=h.getData(r);s.preload(h.isFullscreen()&&v.big?v.big:v.image)}h.rescale(function(){h.addTimer(!1,function(){k&&K.show(h.getActiveImage()),"function"==typeof f&&f.call(h),h.rescale()},100),h.trigger(c.FULLSCREEN_ENTER)}),k?g.resize(q.scale):K.show(h.getActiveImage())},scale:function(){h.rescale()},exit:function(a){q.beforeExit(function(){a=q.parseCallback(a),h._options.trueFullscreen&&C.support?C.exit(a):q._exit(a)})},_exit:function(a){q.active=!1;var d=!h._options.trueFullscreen||!C.support,e=h.$("container").removeClass("fullscreen");if(q.parent?q.parent.prepend(e):e.insertAfter(q.prev),d){K.hide(h.getActiveImage()),K.revertStyles(h.get("container"),t().html,t().body),c.TOUCH||b.scrollTo(0,q.scrolled);var f=h._controls.frames[h._controls.active];f&&f.image&&(f.image.src=f.image.src)}u&&q.iframe&&(K.revertStyles(q.pd.documentElement,q.pd.body,q.iframe),q.iframe.scrolled&&b.parent.scrollTo(0,q.iframe.scrolled)),h.detachKeyboard(),h.attachKeyboard(q.keymap),h._options.imageCrop=q.crop;var i=h.getData().big,j=h._controls.getActive().image;!h.getData().iframe&&j&&i&&i==j.src&&b.setTimeout(function(a){return function(){j.src=a}}(h.getData().image),1),h.rescale(function(){h.addTimer(!1,function(){d&&K.show(h.getActiveImage()),"function"==typeof a&&a.call(h),g.trigger("resize")},50),h.trigger(c.FULLSCREEN_EXIT)}),g.off("resize",q.scale)}},r=this._idle={trunk:[],bound:!1,active:!1,add:function(b,d,e,f){if(b&&!c.TOUCH){r.bound||r.addEvent(),b=a(b),"boolean"==typeof e&&(f=e,e={}),e=e||{};var g,h={};for(g in d)d.hasOwnProperty(g)&&(h[g]=b.css(g));b.data("idle",{from:a.extend(h,e),to:d,complete:!0,busy:!1}),f?b.css(d):r.addTimer(),r.trunk.push(b)}},remove:function(b){b=a(b),a.each(r.trunk,function(a,c){c&&c.length&&!c.not(b).length&&(b.css(b.data("idle").from),r.trunk.splice(a,1))}),r.trunk.length||(r.removeEvent(),h.clearTimer(r.timer))},addEvent:function(){r.bound=!0,h.$("container").on("mousemove click",r.showAll),"hover"==h._options.idleMode&&h.$("container").on("mouseleave",r.hide)},removeEvent:function(){r.bound=!1,h.$("container").on("mousemove click",r.showAll),"hover"==h._options.idleMode&&h.$("container").off("mouseleave",r.hide)},addTimer:function(){"hover"!=h._options.idleMode&&h.addTimer("idle",function(){r.hide()},h._options.idleTime)},hide:function(){if(h._options.idleMode&&h.getIndex()!==!1){h.trigger(c.IDLE_ENTER);var b=r.trunk.length;a.each(r.trunk,function(a,c){var d=c.data("idle");d&&(c.data("idle").complete=!1,K.animate(c,d.to,{duration:h._options.idleSpeed,complete:function(){a==b-1&&(r.active=!1)}}))})}},showAll:function(){h.clearTimer("idle"),a.each(r.trunk,function(a,b){r.show(b)})},show:function(b){var d=b.data("idle");r.active&&(d.busy||d.complete)||(d.busy=!0,h.trigger(c.IDLE_EXIT),h.clearTimer("idle"),K.animate(b,d.from,{duration:h._options.idleSpeed/2,complete:function(){r.active=!0,a(b).data("idle").busy=!1,a(b).data("idle").complete=!0}})),r.addTimer()}},v=this._lightbox={width:0,height:0,initialized:!1,active:null,image:null,elems:{},keymap:!1,init:function(){if(!v.initialized){v.initialized=!0;var b="overlay box content shadow title info close prevholder prev nextholder next counter image",d={},e=h._options,f="",g="position:absolute;",i="lightbox-",j={overlay:"position:fixed;display:none;opacity:"+e.overlayOpacity+";filter:alpha(opacity="+100*e.overlayOpacity+");top:0;left:0;width:100%;height:100%;background:"+e.overlayBackground+";z-index:99990",box:"position:fixed;display:none;width:400px;height:400px;top:50%;left:50%;margin-top:-200px;margin-left:-200px;z-index:99991",shadow:g+"background:#000;width:100%;height:100%;",content:g+"background-color:#fff;top:10px;left:10px;right:10px;bottom:10px;overflow:hidden",info:g+"bottom:10px;left:10px;right:10px;color:#444;font:11px/13px arial,sans-serif;height:13px",close:g+"top:10px;right:10px;height:20px;width:20px;background:#fff;text-align:center;cursor:pointer;color:#444;font:16px/22px arial,sans-serif;z-index:99999",image:g+"top:10px;left:10px;right:10px;bottom:30px;overflow:hidden;display:block;",prevholder:g+"width:50%;top:0;bottom:40px;cursor:pointer;",nextholder:g+"width:50%;top:0;bottom:40px;right:-1px;cursor:pointer;",prev:g+"top:50%;margin-top:-20px;height:40px;width:30px;background:#fff;left:20px;display:none;text-align:center;color:#000;font:bold 16px/36px arial,sans-serif",next:g+"top:50%;margin-top:-20px;height:40px;width:30px;background:#fff;right:20px;left:auto;display:none;font:bold 16px/36px arial,sans-serif;text-align:center;color:#000",title:"float:left",counter:"float:right;margin-left:8px;"},k=function(b){return b.hover(function(){a(this).css("color","#bbb")},function(){a(this).css("color","#444")})},l={},m="";m=s>7?s<9?"background:#000;filter:alpha(opacity=0);":"background:rgba(0,0,0,0);":"z-index:99999",j.nextholder+=m,j.prevholder+=m,a.each(j,function(a,b){f+=".galleria-"+i+a+"{"+b+"}"}),f+=".galleria-"+i+"box.iframe .galleria-"+i+"prevholder,.galleria-"+i+"box.iframe .galleria-"+i+"nextholder{width:100px;height:100px;top:50%;margin-top:-70px}",K.insertStyleTag(f,"galleria-lightbox"),a.each(b.split(" "),function(a,b){h.addElement("lightbox-"+b),d[b]=v.elems[b]=h.get("lightbox-"+b)}),v.image=new c.Picture,a.each({box:"shadow content close prevholder nextholder",info:"title counter",content:"info image",prevholder:"prev",nextholder:"next"},function(b,c){var d=[];a.each(c.split(" "),function(a,b){d.push(i+b)}),l[i+b]=d}),h.append(l),a(d.image).append(v.image.container),a(t().body).append(d.overlay,d.box),k(a(d.close).on("click:fast",v.hide).html("×")),a.each(["Prev","Next"],function(b,e){var f=a(d[e.toLowerCase()]).html(/v/.test(e)?"‹ ":" ›"),g=a(d[e.toLowerCase()+"holder"]);return g.on("click:fast",function(){v["show"+e]()}),s<8||c.TOUCH?void f.show():void g.hover(function(){f.show()},function(a){f.stop().fadeOut(200)})}),a(d.overlay).on("click:fast",v.hide),c.IPAD&&(h._options.lightboxTransitionSpeed=0)}},rescale:function(b){var d=p.min(g.width()-40,v.width),e=p.min(g.height()-60,v.height),f=p.min(d/v.width,e/v.height),i=p.round(v.width*f)+40,j=p.round(v.height*f)+60,k={width:i,height:j,"margin-top":p.ceil(j/2)*-1,"margin-left":p.ceil(i/2)*-1};b?a(v.elems.box).css(k):a(v.elems.box).animate(k,{duration:h._options.lightboxTransitionSpeed,easing:h._options.easing,complete:function(){var b=v.image,d=h._options.lightboxFadeSpeed;h.trigger({type:c.LIGHTBOX_IMAGE,imageTarget:b.image}),a(b.container).show(),a(b.image).animate({opacity:1},d),K.show(v.elems.info,d)}})},hide:function(){v.image.image=null,g.off("resize",v.rescale),a(v.elems.box).hide().find("iframe").remove(),K.hide(v.elems.info),h.detachKeyboard(),h.attachKeyboard(v.keymap),v.keymap=!1,K.hide(v.elems.overlay,200,function(){a(this).hide().css("opacity",h._options.overlayOpacity),h.trigger(c.LIGHTBOX_CLOSE)})},showNext:function(){v.show(h.getNext(v.active))},showPrev:function(){v.show(h.getPrev(v.active))},show:function(d){v.active=d="number"==typeof d?d:h.getIndex()||0,v.initialized||v.init(),h.trigger(c.LIGHTBOX_OPEN),v.keymap||(v.keymap=a.extend({},h._keyboard.map),h.attachKeyboard({escape:v.hide,right:v.showNext,left:v.showPrev})),g.off("resize",v.rescale);var e,f,i,j=h.getData(d),k=h.getDataLength(),l=h.getNext(d);K.hide(v.elems.info);try{for(i=h._options.preload;i>0;i--)f=new c.Picture,e=h.getData(l),f.preload(e.big?e.big:e.image),l=h.getNext(l)}catch(a){}v.image.isIframe=j.iframe&&!j.image,a(v.elems.box).toggleClass("iframe",v.image.isIframe),a(v.image.container).find(".galleria-videoicon").remove(),v.image.load(j.big||j.image||j.iframe,function(c){if(c.isIframe){var e=a(b).width(),f=a(b).height();if(c.video&&h._options.maxVideoSize){var i=p.min(h._options.maxVideoSize/e,h._options.maxVideoSize/f);i<1&&(e*=i,f*=i)}v.width=e,v.height=f}else v.width=c.original.width,v.height=c.original.height;if(a(c.image).css({width:c.isIframe?"100%":"100.1%",height:c.isIframe?"100%":"100.1%",top:0,bottom:0,zIndex:99998,opacity:0,visibility:"visible"}).parent().height("100%"),v.elems.title.innerHTML=j.title||"",v.elems.counter.innerHTML=d+1+" / "+k,g.resize(v.rescale),v.rescale(),j.image&&j.iframe){if(a(v.elems.box).addClass("iframe"),j.video){var l=L(c.container).hide();b.setTimeout(function(){l.fadeIn(200)},200)}a(c.image).css("cursor","pointer").mouseup(function(b,c){return function(d){a(v.image.container).find(".galleria-videoicon").remove(),d.preventDefault(),c.isIframe=!0,c.load(b.iframe+(b.video?"&autoplay=1":""),{width:"100%",height:s<8?a(v.image.container).height():"100%"})}}(j,c))}}),a(v.elems.overlay).show().css("visibility","visible"),a(v.elems.box).show()}},w=this._timer={trunk:{},add:function(a,c,d,e){if(a=a||(new Date).getTime(),e=e||!1,this.clear(a),e){var f=c;c=function(){f(),w.add(a,c,d)}}this.trunk[a]=b.setTimeout(c,d)},clear:function(a){var c,d=function(a){b.clearTimeout(this.trunk[a]),delete this.trunk[a]};if(a&&a in this.trunk)d.call(this,a);else if("undefined"==typeof a)for(c in this.trunk)this.trunk.hasOwnProperty(c)&&d.call(this,c)}};return this},c.prototype={constructor:c,init:function(b,e){if(e=x(e),this._original={target:b,options:e,data:null},this._target=this._dom.target=b.nodeName?b:a(b).get(0),this._original.html=this._target.innerHTML,E.push(this),!this._target)return void c.raise("Target not found",!0);if(this._options={autoplay:!1,carousel:!0,carouselFollow:!0,carouselSpeed:400,carouselSteps:"auto",clicknext:!1,dailymotion:{foreground:"%23EEEEEE",highlight:"%235BCEC5",background:"%23222222",logo:0,hideInfos:1},dataConfig:function(a){return{}},dataSelector:"img",dataSort:!1,dataSource:this._target,debug:d,dummy:d,easing:"galleria",extend:function(a){},fullscreenCrop:d,fullscreenDoubleTap:!0,fullscreenTransition:d,height:0,idleMode:!0,idleTime:3e3,idleSpeed:200,imageCrop:!1,imageMargin:0,imagePan:!1,imagePanSmoothness:12,imagePosition:"50%",imageTimeout:d,initialTransition:d,keepSource:!1,layerFollow:!0,lightbox:!1,lightboxFadeSpeed:200,lightboxTransitionSpeed:200,linkSourceImages:!0,maxScaleRatio:d,maxVideoSize:d,minScaleRatio:d,overlayOpacity:.85,overlayBackground:"#0b0b0b",pauseOnInteraction:!0,popupLinks:!1,preload:2,queue:!0,responsive:!0,show:0,showInfo:!0,showCounter:!0,showImagenav:!0,swipe:"auto",theme:null,thumbCrop:!0,thumbEventType:"click:fast",thumbMargin:0,thumbQuality:"auto",thumbDisplayOrder:!0,thumbPosition:"50%",thumbnails:!0,touchTransition:d,transition:"fade",transitionInitial:d,transitionSpeed:400,trueFullscreen:!0,useCanvas:!1,variation:"",videoPoster:!0,vimeo:{title:0,byline:0,portrait:0,color:"aaaaaa"},wait:5e3,width:"auto",youtube:{modestbranding:1,autohide:1,color:"white",hd:1,rel:0,showinfo:0}},this._options.initialTransition=this._options.initialTransition||this._options.transitionInitial,
e&&(e.debug===!1&&(j=!1),"number"==typeof e.imageTimeout&&(k=e.imageTimeout),"string"==typeof e.dummy&&(l=e.dummy),"string"==typeof e.theme&&(this._options.theme=e.theme)),a(this._target).children().hide(),c.QUIRK&&c.raise("Your page is in Quirks mode, Galleria may not render correctly. Please validate your HTML and add a correct doctype."),I.length)if(this._options.theme){for(var f=0;f<I.length;f++)if(this._options.theme===I[f].name){this.theme=I[f];break}}else this.theme=I[0];return"object"==typeof this.theme?this._init():H.push(this),this},_init:function(){var f=this,h=this._options;if(this._initialized)return c.raise("Init failed: Gallery instance already initialized."),this;if(this._initialized=!0,!this.theme)return c.raise("Init failed: No theme found.",!0),this;if(a.extend(!0,h,this.theme.defaults,this._original.options,c.configure.options),h.swipe=function(a){return"enforced"==a||a!==!1&&"disabled"!=a&&!!c.TOUCH}(h.swipe),h.swipe&&(h.clicknext=!1,h.imagePan=!1),function(a){return"getContext"in a?void(G=G||{elem:a,context:a.getContext("2d"),cache:{},length:0}):void(a=null)}(e.createElement("canvas")),this.bind(c.DATA,function(){b.screen&&b.screen.width&&Array.prototype.forEach&&this._data.forEach(function(a){var c="devicePixelRatio"in b?b.devicePixelRatio:1,d=p.max(b.screen.width,b.screen.height);d*c<1024&&(a.big=a.image)}),this._original.data=this._data,this.get("total").innerHTML=this.getDataLength();var a=this.$("container");f._options.height<2&&(f._userRatio=f._ratio=f._options.height);var d={width:0,height:0},e=function(){return f.$("stage").height()};K.wait({until:function(){return d=f._getWH(),a.width(d.width).height(d.height),e()&&d.width&&d.height>50},success:function(){f._width=d.width,f._height=d.height,f._ratio=f._ratio||d.height/d.width,c.WEBKIT?b.setTimeout(function(){f._run()},1):f._run()},error:function(){e()?c.raise("Could not extract sufficient width/height of the gallery container. Traced measures: width:"+d.width+"px, height: "+d.height+"px.",!0):c.raise("Could not extract a stage height from the CSS. Traced height: "+e()+"px.",!0)},timeout:"number"==typeof this._options.wait&&this._options.wait})}),this.append({"info-text":["info-title","info-description"],info:["info-text"],"image-nav":["image-nav-right","image-nav-left"],stage:["images","loader","counter","image-nav"],"thumbnails-list":["thumbnails"],"thumbnails-container":["thumb-nav-left","thumbnails-list","thumb-nav-right"],container:["stage","thumbnails-container","info","tooltip"]}),K.hide(this.$("counter").append(this.get("current"),e.createTextNode(" / "),this.get("total"))),this.setCounter("–"),K.hide(f.get("tooltip")),this.$("container").addClass([c.TOUCH?"touch":"notouch",this._options.variation,"galleria-theme-"+this.theme.name].join(" ")),this._options.swipe||a.each(new Array(2),function(b){var d=new c.Picture;a(d.container).css({position:"absolute",top:0,left:0}).prepend(f._layers[b]=a(K.create("galleria-layer")).css({position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:2})[0]),f.$("images").append(d.container),f._controls[b]=d;var e=new c.Picture;e.isIframe=!0,a(e.container).attr("class","galleria-frame").css({position:"absolute",top:0,left:0,zIndex:4,background:"#000",display:"none"}).appendTo(d.container),f._controls.frames[b]=e}),this.$("images").css({position:"relative",top:0,left:0,width:"100%",height:"100%"}),h.swipe&&(this.$("images").css({position:"absolute",top:0,left:0,width:0,height:"100%"}),this.finger=new c.Finger(this.get("stage"),{onchange:function(a){f.pause().show(a)},oncomplete:function(b){var c=p.max(0,p.min(parseInt(b,10),f.getDataLength()-1)),d=f.getData(c);a(f._thumbnails[c].container).addClass("active").siblings(".active").removeClass("active"),d&&(f.$("images").find(".galleria-frame").css("opacity",0).hide().find("iframe").remove(),f._options.carousel&&f._options.carouselFollow&&f._carousel.follow(c))}}),this.bind(c.RESCALE,function(){this.finger.setup()}),this.$("stage").on("click",function(c){var e=f.getData();if(e){if(e.iframe){f.isPlaying()&&f.pause();var g=f._controls.frames[f._active],h=f._stageWidth,i=f._stageHeight;if(a(g.container).find("iframe").length)return;return a(g.container).css({width:h,height:i,opacity:0}).show().animate({opacity:1},200),void b.setTimeout(function(){g.load(e.iframe+(e.video?"&autoplay=1":""),{width:h,height:i},function(a){f.$("container").addClass("videoplay"),a.scale({width:f._stageWidth,height:f._stageHeight,iframelimit:e.video?f._options.maxVideoSize:d})})},100)}if(e.link)if(f._options.popupLinks){b.open(e.link,"_blank")}else b.location.href=e.link;else;}}),this.bind(c.IMAGE,function(b){f.setCounter(b.index),f.setInfo(b.index);var c=this.getNext(),d=this.getPrev(),e=[d,c];e.push(this.getNext(c),this.getPrev(d),f._controls.slides.length-1);var g=[];a.each(e,function(b,c){a.inArray(c,g)==-1&&g.push(c)}),a.each(g,function(b,c){var d=f.getData(c),e=f._controls.slides[c],g=f.isFullscreen()&&d.big?d.big:d.image||d.iframe;d.iframe&&!d.image&&(e.isIframe=!0),e.ready||f._controls.slides[c].load(g,function(b){b.isIframe||a(b.image).css("visibility","hidden"),f._scaleImage(b,{complete:function(b){b.isIframe||a(b.image).css({opacity:0,visibility:"visible"}).animate({opacity:1},200)}})})})})),this.$("thumbnails, thumbnails-list").css({overflow:"hidden",position:"relative"}),this.$("image-nav-right, image-nav-left").on("click:fast",function(a){h.pauseOnInteraction&&f.pause();var b=/right/.test(this.className)?"next":"prev";f[b]()}).on("click",function(a){a.preventDefault(),(h.clicknext||h.swipe)&&a.stopPropagation()}),a.each(["info","counter","image-nav"],function(a,b){h["show"+b.substr(0,1).toUpperCase()+b.substr(1).replace(/-/,"")]===!1&&K.moveOut(f.get(b.toLowerCase()))}),this.load(),h.keepSource||s||(this._target.innerHTML=""),this.get("errors")&&this.appendChild("target","errors"),this.appendChild("target","container"),h.carousel){var i=0,j=h.show;this.bind(c.THUMBNAIL,function(){this.updateCarousel(),++i==this.getDataLength()&&"number"==typeof j&&j>0&&this._carousel.follow(j)})}return h.responsive&&g.on("resize",function(){f.isFullscreen()||f.resize()}),h.fullscreenDoubleTap&&this.$("stage").on("touchstart",function(){var a,b,c,d,e,g,h=function(a){return a.originalEvent.touches?a.originalEvent.touches[0]:a};return f.$("stage").on("touchmove",function(){a=0}),function(i){if(!/(-left|-right)/.test(i.target.className)){if(g=K.timestamp(),b=h(i).pageX,c=h(i).pageY,i.originalEvent.touches.length<2&&g-a<300&&b-d<20&&c-e<20)return f.toggleFullscreen(),void i.preventDefault();a=g,d=b,e=c}}}()),a.each(c.on.binds,function(b,c){a.inArray(c.hash,f._binds)==-1&&f.bind(c.type,c.callback)}),this},addTimer:function(){return this._timer.add.apply(this._timer,K.array(arguments)),this},clearTimer:function(){return this._timer.clear.apply(this._timer,K.array(arguments)),this},_getWH:function(){var b,c=this.$("container"),d=this.$("target"),e=this,f={};return a.each(["width","height"],function(a,g){e._options[g]&&"number"==typeof e._options[g]?f[g]=e._options[g]:(b=[K.parseValue(c.css(g)),K.parseValue(d.css(g)),c[g](),d[g]()],e["_"+g]||b.splice(b.length,K.parseValue(c.css("min-"+g)),K.parseValue(d.css("min-"+g))),f[g]=p.max.apply(p,b))}),e._userRatio&&(f.height=f.width*e._userRatio),f},_createThumbnails:function(d){this.get("total").innerHTML=this.getDataLength();var f,g,h,i,j=this,k=this._options,l=d?this._data.length-d.length:0,m=l,n=[],o=0,p=s<8?"http://upload.wikimedia.org/wikipedia/commons/c/c0/Blank.gif":"data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw%3D%3D",q=function(){var a=j.$("thumbnails").find(".active");return!!a.length&&a.find("img").attr("src")}(),r="string"==typeof k.thumbnails?k.thumbnails.toLowerCase():null,t=function(a){return e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g.container,null)[a]:i.css(a)},u=function(b,d,e){return function(){a(e).append(b),j.trigger({type:c.THUMBNAIL,thumbTarget:b,index:d,galleriaData:j.getData(d)})}},v=function(b){k.pauseOnInteraction&&j.pause();var c=a(b.currentTarget).data("index");j.getIndex()!==c&&j.show(c),b.preventDefault()},w=function(b,d){a(b.container).css("visibility","visible"),j.trigger({type:c.THUMBNAIL,thumbTarget:b.image,index:b.data.order,galleriaData:j.getData(b.data.order)}),"function"==typeof d&&d.call(j,b)},x=function(b,c){b.scale({width:b.data.width,height:b.data.height,crop:k.thumbCrop,margin:k.thumbMargin,canvas:k.useCanvas,position:k.thumbPosition,complete:function(b){var d,e,f=["left","top"],g=["Width","Height"];j.getData(b.index);a.each(g,function(c,g){d=g.toLowerCase(),k.thumbCrop===!0&&k.thumbCrop!==d||(e={},e[d]=b[d],a(b.container).css(e),e={},e[f[c]]=0,a(b.image).css(e)),b["outer"+g]=a(b.container)["outer"+g](!0)}),K.toggleQuality(b.image,k.thumbQuality===!0||"auto"===k.thumbQuality&&b.original.width<3*b.width),k.thumbDisplayOrder&&!b.lazy?a.each(n,function(a,b){if(a===o&&b.ready&&!b.displayed)return o++,b.displayed=!0,void w(b,c)}):w(b,c)}})};for(d||(this._thumbnails=[],this.$("thumbnails").empty());this._data[l];l++)h=this._data[l],f=h.thumb||h.image,k.thumbnails!==!0&&"lazy"!=r||!h.thumb&&!h.image?h.iframe&&null!==r||"empty"===r||"numbers"===r?(g={container:K.create("galleria-image"),image:K.create("img","span"),ready:!0,data:{order:l}},"numbers"===r&&a(g.image).text(l+1),h.iframe&&a(g.image).addClass("iframe"),this.$("thumbnails").append(g.container),b.setTimeout(u(g.image,l,g.container),50+20*l)):g={container:null,image:null}:(g=new c.Picture(l),g.index=l,g.displayed=!1,g.lazy=!1,g.video=!1,this.$("thumbnails").append(g.container),i=a(g.container),i.css("visibility","hidden"),g.data={width:K.parseValue(t("width")),height:K.parseValue(t("height")),order:l,src:f},k.thumbCrop!==!0?i.css({width:"auto",height:"auto"}):i.css({width:g.data.width,height:g.data.height}),"lazy"==r?(i.addClass("lazy"),g.lazy=!0,g.load(p,{height:g.data.height,width:g.data.width})):g.load(f,x),"all"===k.preload&&g.preload(h.image)),a(g.container).add(k.keepSource&&k.linkSourceImages?h.original:null).data("index",l).on(k.thumbEventType,v).data("thumbload",x),q===f&&a(g.container).addClass("active"),this._thumbnails.push(g);return n=this._thumbnails.slice(m),this},lazyLoad:function(b,c){var d=b.constructor==Array?b:[b],e=this,f=0;return a.each(d,function(b,g){if(!(g>e._thumbnails.length-1)){var h=e._thumbnails[g],i=h.data,j=function(){++f==d.length&&"function"==typeof c&&c.call(e)},k=a(h.container).data("thumbload");h.video?k.call(e,h,j):h.load(i.src,function(a){k.call(e,a,j)})}}),this},lazyLoadChunks:function(a,c){var d=this.getDataLength(),e=0,f=0,g=[],h=[],i=this;for(c=c||0;e<d;e++)h.push(e),++f!=a&&e!=d-1||(g.push(h),f=0,h=[]);var j=function(a){var d=g.shift();d&&b.setTimeout(function(){i.lazyLoad(d,function(){j(!0)})},c&&a?c:0)};return j(!1),this},_run:function(){var e=this;e._createThumbnails(),K.wait({timeout:1e4,until:function(){return c.OPERA&&e.$("stage").css("display","inline-block"),e._stageWidth=e.$("stage").width(),e._stageHeight=e.$("stage").height(),e._stageWidth&&e._stageHeight>50},success:function(){if(D.push(e),e._options.swipe){var f=e.$("images").width(e.getDataLength()*e._stageWidth);a.each(new Array(e.getDataLength()),function(b){var d=new c.Picture,g=e.getData(b);a(d.container).css({position:"absolute",top:0,left:e._stageWidth*b}).prepend(e._layers[b]=a(K.create("galleria-layer")).css({position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:2})[0]).appendTo(f),g.video&&L(d.container),e._controls.slides.push(d);var h=new c.Picture;h.isIframe=!0,a(h.container).attr("class","galleria-frame").css({position:"absolute",top:0,left:0,zIndex:4,background:"#000",display:"none"}).appendTo(d.container),e._controls.frames.push(h)}),e.finger.setup()}return K.show(e.get("counter")),e._options.carousel&&e._carousel.bindControls(),e._options.autoplay&&(e.pause(),"number"==typeof e._options.autoplay&&(e._playtime=e._options.autoplay),e._playing=!0),e._firstrun?(e._options.autoplay&&e.trigger(c.PLAY),void("number"==typeof e._options.show&&e.show(e._options.show))):(e._firstrun=!0,c.History&&c.History.change(function(a){isNaN(a)?b.history.go(-1):e.show(a,d,!0)}),e.trigger(c.READY),e.theme.init.call(e,e._options),a.each(c.ready.callbacks,function(a,b){"function"==typeof b&&b.call(e,e._options)}),e._options.extend.call(e,e._options),/^[0-9]{1,4}$/.test(n)&&c.History?e.show(n,d,!0):e._data[e._options.show]&&e.show(e._options.show),void(e._options.autoplay&&e.trigger(c.PLAY)))},error:function(){c.raise("Stage width or height is too small to show the gallery. Traced measures: width:"+e._stageWidth+"px, height: "+e._stageHeight+"px.",!0)}})},load:function(b,d,e){var f=this,g=this._options;return this._data=[],this._thumbnails=[],this.$("thumbnails").empty(),"function"==typeof d&&(e=d,d=null),b=b||g.dataSource,d=d||g.dataSelector,e=e||g.dataConfig,a.isPlainObject(b)&&(b=[b]),a.isArray(b)?this.validate(b)?this._data=b:c.raise("Load failed: JSON Array not valid."):(d+=",.video,.iframe",a(b).find(d).each(function(b,c){c=a(c);var d={},g=c.parent(),h=g.attr("href"),i=g.attr("rel");h&&("IMG"==c[0].nodeName||c.hasClass("video"))&&B(h)?d.video=h:h&&c.hasClass("iframe")?d.iframe=h:d.image=d.big=h,i&&(d.big=i),a.each("big title description link layer image".split(" "),function(a,b){c.data(b)&&(d[b]=c.data(b).toString())}),d.big||(d.big=d.image),f._data.push(a.extend({title:c.attr("title")||"",thumb:c.attr("src"),image:c.attr("src"),big:c.attr("src"),description:c.attr("alt")||"",link:c.attr("longdesc"),original:c.get(0)},d,e(c)))})),"function"==typeof g.dataSort?h.sort.call(this._data,g.dataSort):"random"==g.dataSort&&this._data.sort(function(){return p.round(p.random())-.5}),this.getDataLength()&&this._parseData(function(){this.trigger(c.DATA)}),this},_parseData:function(b){var c,e=this,f=!1,g=function(){var c=!0;a.each(e._data,function(a,b){if(b.loading)return c=!1,!1}),c&&!f&&(f=!0,b.call(e))};return a.each(this._data,function(b,f){if(c=e._data[b],"thumb"in f==!1&&(c.thumb=f.image),f.big||(c.big=f.image),"video"in f){var h=B(f.video);h&&(c.iframe=new A(h.provider,h.id).embed()+function(){if("object"==typeof e._options[h.provider]){var b="?",c=[];return a.each(e._options[h.provider],function(a,b){c.push(a+"="+b)}),"youtube"==h.provider&&(c=["wmode=opaque"].concat(c)),b+c.join("&")}return""}(),c.thumb&&c.image||a.each(["thumb","image"],function(a,b){if("image"==b&&!e._options.videoPoster)return void(c.image=d);var f=new A(h.provider,h.id);c[b]||(c.loading=!0,f.getMedia(b,function(a,b){return function(c){a[b]=c,"image"!=b||a.big||(a.big=a.image),delete a.loading,g()}}(c,b)))}))}}),g(),this},destroy:function(){return this.$("target").data("galleria",null),this.$("container").off("galleria"),this.get("target").innerHTML=this._original.html,this.clearTimer(),K.removeFromArray(E,this),K.removeFromArray(D,this),c._waiters.length&&a.each(c._waiters,function(a,c){c&&b.clearTimeout(c)}),this},splice:function(){var a=this,c=K.array(arguments);return b.setTimeout(function(){h.splice.apply(a._data,c),a._parseData(function(){a._createThumbnails()})},2),a},push:function(){var a=this,c=K.array(arguments);return 1==c.length&&c[0].constructor==Array&&(c=c[0]),b.setTimeout(function(){h.push.apply(a._data,c),a._parseData(function(){a._createThumbnails(c)})},2),a},_getActive:function(){return this._controls.getActive()},validate:function(a){return!0},bind:function(a,b){return a=y(a),this.$("container").on(a,this.proxy(b)),this},unbind:function(a){return a=y(a),this.$("container").off(a),this},trigger:function(b){return b="object"==typeof b?a.extend(b,{scope:this}):{type:y(b),scope:this},this.$("container").trigger(b),this},addIdleState:function(a,b,c,d){return this._idle.add.apply(this._idle,K.array(arguments)),this},removeIdleState:function(a){return this._idle.remove.apply(this._idle,K.array(arguments)),this},enterIdleMode:function(){return this._idle.hide(),this},exitIdleMode:function(){return this._idle.showAll(),this},enterFullscreen:function(a){return this._fullscreen.enter.apply(this,K.array(arguments)),this},exitFullscreen:function(a){return this._fullscreen.exit.apply(this,K.array(arguments)),this},toggleFullscreen:function(a){return this._fullscreen[this.isFullscreen()?"exit":"enter"].apply(this,K.array(arguments)),this},bindTooltip:function(a,b){return this._tooltip.bind.apply(this._tooltip,K.array(arguments)),this},defineTooltip:function(a,b){return this._tooltip.define.apply(this._tooltip,K.array(arguments)),this},refreshTooltip:function(a){return this._tooltip.show.apply(this._tooltip,K.array(arguments)),this},openLightbox:function(){return this._lightbox.show.apply(this._lightbox,K.array(arguments)),this},closeLightbox:function(){return this._lightbox.hide.apply(this._lightbox,K.array(arguments)),this},hasVariation:function(b){return a.inArray(b,this._options.variation.split(/\s+/))>-1},getActiveImage:function(){var a=this._getActive();return a?a.image:d},getActiveThumb:function(){return this._thumbnails[this._active].image||d},getMousePosition:function(a){return{x:a.pageX-this.$("container").offset().left,y:a.pageY-this.$("container").offset().top}},addPan:function(b){if(this._options.imageCrop!==!1){b=a(b||this.getActiveImage());var c=this,d=b.width()/2,e=b.height()/2,f=parseInt(b.css("left"),10),g=parseInt(b.css("top"),10),h=f||0,i=g||0,j=0,k=0,l=!1,m=K.timestamp(),n=0,o=0,q=function(a,c,d){if(a>0&&(o=p.round(p.max(a*-1,p.min(0,c))),n!==o))if(n=o,8===s)b.parent()["scroll"+d](o*-1);else{var e={};e[d.toLowerCase()]=o,b.css(e)}},r=function(a){K.timestamp()-m<50||(l=!0,d=c.getMousePosition(a).x,e=c.getMousePosition(a).y)},t=function(a){l&&(j=b.width()-c._stageWidth,k=b.height()-c._stageHeight,f=d/c._stageWidth*j*-1,g=e/c._stageHeight*k*-1,h+=(f-h)/c._options.imagePanSmoothness,i+=(g-i)/c._options.imagePanSmoothness,q(k,i,"Top"),q(j,h,"Left"))};return 8===s&&(b.parent().scrollTop(i*-1).scrollLeft(h*-1),b.css({top:0,left:0})),this.$("stage").off("mousemove",r).on("mousemove",r),this.addTimer("pan"+c._id,t,50,!0),this}},proxy:function(a,b){return"function"!=typeof a?q:(b=b||this,function(){return a.apply(b,K.array(arguments))})},getThemeName:function(){return this.theme.name},removePan:function(){return this.$("stage").off("mousemove"),this.clearTimer("pan"+this._id),this},addElement:function(b){var c=this._dom;return a.each(K.array(arguments),function(a,b){c[b]=K.create("galleria-"+b)}),this},attachKeyboard:function(a){return this._keyboard.attach.apply(this._keyboard,K.array(arguments)),this},detachKeyboard:function(){return this._keyboard.detach.apply(this._keyboard,K.array(arguments)),this},appendChild:function(a,b){return this.$(a).append(this.get(b)||b),this},prependChild:function(a,b){return this.$(a).prepend(this.get(b)||b),this},remove:function(a){return this.$(K.array(arguments).join(",")).remove(),this},append:function(a){var b,c;for(b in a)if(a.hasOwnProperty(b))if(a[b].constructor===Array)for(c=0;a[b][c];c++)this.appendChild(b,a[b][c]);else this.appendChild(b,a[b]);return this},_scaleImage:function(b,c){if(b=b||this._controls.getActive()){var d,e=function(b){a(b.container).children(":first").css({top:p.max(0,K.parseValue(b.image.style.top)),left:p.max(0,K.parseValue(b.image.style.left)),width:K.parseValue(b.image.width),height:K.parseValue(b.image.height)})};return c=a.extend({width:this._stageWidth,height:this._stageHeight,crop:this._options.imageCrop,max:this._options.maxScaleRatio,min:this._options.minScaleRatio,margin:this._options.imageMargin,position:this._options.imagePosition,iframelimit:this._options.maxVideoSize},c),this._options.layerFollow&&this._options.imageCrop!==!0?"function"==typeof c.complete?(d=c.complete,c.complete=function(){d.call(b,b),e(b)}):c.complete=e:a(b.container).children(":first").css({top:0,left:0}),b.scale(c),this}},updateCarousel:function(){return this._carousel.update(),this},resize:function(b,c){"function"==typeof b&&(c=b,b=d),b=a.extend({width:0,height:0},b);var e=this,f=this.$("container");return a.each(b,function(a,c){c||(f[a]("auto"),b[a]=e._getWH()[a])}),a.each(b,function(a,b){f[a](b)}),this.rescale(c)},rescale:function(b,e,f){var g=this;"function"==typeof b&&(f=b,b=d);var h=function(){g._stageWidth=b||g.$("stage").width(),g._stageHeight=e||g.$("stage").height(),g._options.swipe?(a.each(g._controls.slides,function(b,c){g._scaleImage(c),a(c.container).css("left",g._stageWidth*b)}),g.$("images").css("width",g._stageWidth*g.getDataLength())):g._scaleImage(),g._options.carousel&&g.updateCarousel();var d=g._controls.frames[g._controls.active];d&&g._controls.frames[g._controls.active].scale({width:g._stageWidth,height:g._stageHeight,iframelimit:g._options.maxVideoSize}),g.trigger(c.RESCALE),"function"==typeof f&&f.call(g)};return h.call(g),this},refreshImage:function(){return this._scaleImage(),this._options.imagePan&&this.addPan(),this},_preload:function(){if(this._options.preload){var a,b,d,e=this.getNext();try{for(b=this._options.preload;b>0;b--)a=new c.Picture,d=this.getData(e),a.preload(this.isFullscreen()&&d.big?d.big:d.image),e=this.getNext(e)}catch(a){}}},show:function(d,e,f){var g=this._options.swipe;if(g||!(this._queue.length>3||d===!1||!this._options.queue&&this._queue.stalled)){if(d=p.max(0,p.min(parseInt(d,10),this.getDataLength()-1)),e="undefined"!=typeof e?!!e:d<this.getIndex(),f=f||!1,!f&&c.History)return void c.History.set(d.toString());if(this.finger&&d!==this._active&&(this.finger.to=-(d*this.finger.width),this.finger.index=d),this._active=d,g){var i=this.getData(d),j=this;if(!i)return;var k=this.isFullscreen()&&i.big?i.big:i.image||i.iframe,l=this._controls.slides[d],m=l.isCached(k),n=this._thumbnails[d],o={cached:m,index:d,rewind:e,imageTarget:l.image,thumbTarget:n.image,galleriaData:i};this.trigger(a.extend(o,{type:c.LOADSTART})),j.$("container").removeClass("videoplay");var q=function(){j._layers[d].innerHTML=j.getData().layer||"",j.trigger(a.extend(o,{type:c.LOADFINISH})),j._playCheck()};j._preload(),b.setTimeout(function(){l.ready&&a(l.image).attr("src")==k?(j.trigger(a.extend(o,{type:c.IMAGE})),q()):(i.iframe&&!i.image&&(l.isIframe=!0),l.load(k,function(b){o.imageTarget=b.image,j._scaleImage(b,q).trigger(a.extend(o,{type:c.IMAGE})),q()}))},100)}else h.push.call(this._queue,{index:d,rewind:e}),this._queue.stalled||this._show();return this}},_show:function(){var e=this,f=this._queue[0],g=this.getData(f.index);if(g){var i=this.isFullscreen()&&g.big?g.big:g.image||g.iframe,j=this._controls.getActive(),k=this._controls.getNext(),l=k.isCached(i),m=this._thumbnails[f.index],n=function(){a(k.image).trigger("mouseup")};e.$("container").toggleClass("iframe",!!g.isIframe).removeClass("videoplay");var o=function(f,g,i,j,k){return function(){var l;M.active=!1,K.toggleQuality(g.image,e._options.imageQuality),e._layers[e._controls.active].innerHTML="",a(i.container).css({zIndex:0,opacity:0}).show(),a(i.container).find("iframe, .galleria-videoicon").remove(),a(e._controls.frames[e._controls.active].container).hide(),a(g.container).css({zIndex:1,left:0,top:0}).show(),e._controls.swap(),e._options.imagePan&&e.addPan(g.image),(f.iframe&&f.image||f.link||e._options.lightbox||e._options.clicknext)&&a(g.image).css({cursor:"pointer"}).on("mouseup",function(g){if(!("number"==typeof g.which&&g.which>1)){if(f.iframe){e.isPlaying()&&e.pause();var h=e._controls.frames[e._controls.active],i=e._stageWidth,j=e._stageHeight;return a(h.container).css({width:i,height:j,opacity:0}).show().animate({opacity:1},200),void b.setTimeout(function(){h.load(f.iframe+(f.video?"&autoplay=1":""),{width:i,height:j},function(a){e.$("container").addClass("videoplay"),a.scale({width:e._stageWidth,height:e._stageHeight,iframelimit:f.video?e._options.maxVideoSize:d})})},100)}return e._options.clicknext&&!c.TOUCH?(e._options.pauseOnInteraction&&e.pause(),void e.next()):f.link?void(e._options.popupLinks?l=b.open(f.link,"_blank"):b.location.href=f.link):void(e._options.lightbox&&e.openLightbox())}}),e._playCheck(),e.trigger({type:c.IMAGE,index:j.index,imageTarget:g.image,thumbTarget:k.image,galleriaData:f}),h.shift.call(e._queue),e._queue.stalled=!1,e._queue.length&&e._show()}}(g,k,j,f,m);this._options.carousel&&this._options.carouselFollow&&this._carousel.follow(f.index),e._preload(),K.show(k.container),k.isIframe=g.iframe&&!g.image,a(e._thumbnails[f.index].container).addClass("active").siblings(".active").removeClass("active"),e.trigger({type:c.LOADSTART,cached:l,index:f.index,rewind:f.rewind,imageTarget:k.image,thumbTarget:m.image,galleriaData:g}),e._queue.stalled=!0,k.load(i,function(b){var h=a(e._layers[1-e._controls.active]).html(g.layer||"").hide();e._scaleImage(b,{complete:function(b){"image"in j&&K.toggleQuality(j.image,!1),K.toggleQuality(b.image,!1),e.removePan(),e.setInfo(f.index),e.setCounter(f.index),g.layer&&(h.show(),(g.iframe&&g.image||g.link||e._options.lightbox||e._options.clicknext)&&h.css("cursor","pointer").off("mouseup").mouseup(n)),g.video&&g.image&&L(b.container);var i=e._options.transition;if(a.each({initial:null===j.image,touch:c.TOUCH,fullscreen:e.isFullscreen()},function(a,b){if(b&&e._options[a+"Transition"]!==d)return i=e._options[a+"Transition"],!1}),i in M.effects==!1)o();else{var k={prev:j.container,next:b.container,rewind:f.rewind,speed:e._options.transitionSpeed||400};M.active=!0,M.init.call(e,i,k,o)}e.trigger({type:c.LOADFINISH,cached:l,index:f.index,rewind:f.rewind,imageTarget:b.image,thumbTarget:e._thumbnails[f.index].image,galleriaData:e.getData(f.index)})}})})}},getNext:function(a){return a="number"==typeof a?a:this.getIndex(),a===this.getDataLength()-1?0:a+1},getPrev:function(a){return a="number"==typeof a?a:this.getIndex(),0===a?this.getDataLength()-1:a-1},next:function(){return this.getDataLength()>1&&this.show(this.getNext(),!1),this},prev:function(){return this.getDataLength()>1&&this.show(this.getPrev(),!0),this},get:function(a){return a in this._dom?this._dom[a]:null},getData:function(a){return a in this._data?this._data[a]:this._data[this._active]},getDataLength:function(){return this._data.length},getIndex:function(){return"number"==typeof this._active&&this._active},getStageHeight:function(){return this._stageHeight},getStageWidth:function(){return this._stageWidth},getOptions:function(a){return"undefined"==typeof a?this._options:this._options[a]},setOptions:function(b,c){return"object"==typeof b?a.extend(this._options,b):this._options[b]=c,this},play:function(a){return this._playing=!0,this._playtime=a||this._playtime,this._playCheck(),this.trigger(c.PLAY),this},pause:function(){return this._playing=!1,this.trigger(c.PAUSE),this},playToggle:function(a){return this._playing?this.pause():this.play(a)},isPlaying:function(){return this._playing},isFullscreen:function(){return this._fullscreen.active},_playCheck:function(){var a=this,b=0,d=20,e=K.timestamp(),f="play"+this._id;if(this._playing){this.clearTimer(f);var g=function(){return b=K.timestamp()-e,b>=a._playtime&&a._playing?(a.clearTimer(f),void a.next()):void(a._playing&&(a.trigger({type:c.PROGRESS,percent:p.ceil(b/a._playtime*100),seconds:p.floor(b/1e3),milliseconds:b}),a.addTimer(f,g,d)))};a.addTimer(f,g,d)}},setPlaytime:function(a){return this._playtime=a,this},setIndex:function(a){return this._active=a,this},setCounter:function(a){if("number"==typeof a?a++:"undefined"==typeof a&&(a=this.getIndex()+1),this.get("current").innerHTML=a,s){var b=this.$("counter"),c=b.css("opacity");1===parseInt(c,10)?K.removeAlpha(b[0]):this.$("counter").css("opacity",c)}return this},setInfo:function(b){var c=this,d=this.getData(b);return a.each(["title","description"],function(a,b){var e=c.$("info-"+b);d[b]?e[d[b].length?"show":"hide"]().html(d[b]):e.empty().hide()}),this},hasInfo:function(a){var b,c="title description".split(" ");for(b=0;c[b];b++)if(this.getData(a)[c[b]])return!0;return!1},jQuery:function(b){var c=this,d=[];a.each(b.split(","),function(b,e){e=a.trim(e),c.get(e)&&d.push(e)});var e=a(c.get(d.shift()));return a.each(d,function(a,b){e=e.add(c.get(b))}),e},$:function(a){return this.jQuery.apply(this,K.array(arguments))}},a.each(w,function(a,b){var d=/_/.test(b)?b.replace(/_/g,""):b;c[b.toUpperCase()]="galleria."+d}),a.extend(c,{IE9:9===s,IE8:8===s,IE7:7===s,IE6:6===s,IE:s,WEBKIT:/webkit/.test(m),CHROME:/chrome/.test(m),SAFARI:/safari/.test(m)&&!/chrome/.test(m),QUIRK:s&&e.compatMode&&"BackCompat"===e.compatMode,MAC:/mac/.test(navigator.platform.toLowerCase()),OPERA:!!b.opera,IPHONE:/iphone/.test(m),IPAD:/ipad/.test(m),ANDROID:/android/.test(m),TOUCH:"ontouchstart"in e}),c.addTheme=function(d){d.name||c.raise("No theme name specified"),(!d.version||parseInt(10*c.version)>parseInt(10*d.version))&&c.raise("This version of Galleria requires "+d.name+" theme version "+parseInt(10*c.version)/10+" or later",!0),"object"!=typeof d.defaults?d.defaults={}:d.defaults=x(d.defaults);var e,f,g=!1;return"string"==typeof d.css?(a("link").each(function(a,b){if(e=new RegExp(d.css),e.test(b.href))return g=!0,J(d),!1}),g||a(function(){var h=0,i=function(){a("script").each(function(a,c){e=new RegExp("galleria\\."+d.name.toLowerCase()+"\\."),f=new RegExp("galleria\\.io\\/theme\\/"+d.name.toLowerCase()+"\\/(\\d*\\.*)?(\\d*\\.*)?(\\d*\\/)?js"),(e.test(c.src)||f.test(c.src))&&(g=c.src.replace(/[^\/]*$/,"")+d.css,b.setTimeout(function(){K.loadCSS(g,"galleria-theme-"+d.name,function(){J(d)})},1))}),g||(h++>5?c.raise("No theme CSS loaded"):b.setTimeout(i,500))};i()})):J(d),d},c.loadTheme=function(d,e){if(!a("script").filter(function(){return a(this).attr("src")==d}).length){var f,g=!1;return a(b).on("load",function(){g||(f=b.setTimeout(function(){g||c.raise("Galleria had problems loading theme at "+d+". Please check theme path or load manually.",!0)},2e4))}),K.loadScript(d,function(){g=!0,b.clearTimeout(f)}),c}},c.get=function(a){return E[a]?E[a]:"number"!=typeof a?E:void c.raise("Gallery index "+a+" not found")},c.configure=function(b,d){var e={};return"string"==typeof b&&d?(e[b]=d,b=e):a.extend(e,b),c.configure.options=e,a.each(c.get(),function(a,b){b.setOptions(e)}),c},c.configure.options={},c.on=function(b,d){if(b){d=d||q;var e=b+d.toString().replace(/\s/g,"")+K.timestamp();return a.each(c.get(),function(a,c){c._binds.push(e),c.bind(b,d)}),c.on.binds.push({type:b,callback:d,hash:e}),c}},c.on.binds=[],c.run=function(b,d){return a.isFunction(d)&&(d={extend:d}),a(b||"#galleria").galleria(d),c},c.addTransition=function(a,b){return M.effects[a]=b,c},c.utils=K,c.log=function(){var c=K.array(arguments);if(!("console"in b&&"log"in b.console))return b.alert(c.join("<br>"));try{return b.console.log.apply(b.console,c)}catch(d){a.each(c,function(){b.console.log(this)})}},c.ready=function(b){return"function"!=typeof b?c:(a.each(D,function(a,c){b.call(c,c._options)}),c.ready.callbacks.push(b),c)},c.ready.callbacks=[],c.raise=function(b,c){var d=c?"Fatal error":"Error",e={color:"#fff",position:"absolute",top:0,left:0,zIndex:1e5},f=function(b){var f='<div style="padding:4px;margin:0 0 2px;background:#'+(c?"811":"222")+';">'+(c?"<strong>"+d+": </strong>":"")+b+"</div>";a.each(E,function(){var a=this.$("errors"),b=this.$("target");a.length||(b.css("position","relative"),a=this.addElement("errors").appendChild("target","errors").$("errors").css(e)),a.append(f)}),E.length||a("<div>").css(a.extend(e,{position:"fixed"})).append(f).appendTo(t().body)};if(j){if(f(b),c)throw new Error(d+": "+b)}else if(c){if(F)return;F=!0,c=!1,f("Gallery could not load.")}},c.version=i,c.getLoadedThemes=function(){return a.map(I,function(a){return a.name})},c.requires=function(a,b){return b=b||"You need to upgrade Galleria to version "+a+" to use one or more components.",c.version<a&&c.raise(b,!0),c},c.Picture=function(b){this.id=b||null,this.image=null,this.container=K.create("galleria-image"),a(this.container).css({overflow:"hidden",position:"relative"}),this.original={width:0,height:0},this.ready=!1,this.isIframe=!1},c.Picture.prototype={cache:{},show:function(){K.show(this.image)},hide:function(){K.moveOut(this.image)},clear:function(){this.image=null},isCached:function(a){return!!this.cache[a];
},preload:function(b){a(new Image).on("load",function(a,b){return function(){b[a]=a}}(b,this.cache)).attr("src",b)},load:function(d,e,f){if("function"==typeof e&&(f=e,e=null),this.isIframe){var g="if"+(new Date).getTime(),h=this.image=a("<iframe>",{src:d,frameborder:0,id:g,allowfullscreen:!0,css:{visibility:"hidden"}})[0];return e&&a(h).css(e),a(this.container).find("iframe,img").remove(),this.container.appendChild(this.image),a("#"+g).on("load",function(c,d){return function(){b.setTimeout(function(){a(c.image).css("visibility","visible"),"function"==typeof d&&d.call(c,c)},10)}}(this,f)),this.container}this.image=new Image,c.IE8&&a(this.image).css("filter","inherit"),c.IE||c.CHROME||c.SAFARI||a(this.image).css("image-rendering","optimizequality");var i=!1,j=!1,k=a(this.container),m=a(this.image),n=function(){i?l?a(this).attr("src",l):c.raise("Image not found: "+d):(i=!0,b.setTimeout(function(a,b){return function(){a.attr("src",b+(b.indexOf("?")>-1?"&":"?")+K.timestamp())}}(a(this),d),50))},o=function(d,f,g){return function(){var h=function(){a(this).off("load"),d.original=e||{height:this.height,width:this.width},c.HAS3D&&(this.style.MozTransform=this.style.webkitTransform="translate3d(0,0,0)"),k.append(this),d.cache[g]=g,"function"==typeof f&&b.setTimeout(function(){f.call(d,d)},1)};this.width&&this.height?h.call(this):!function(b){K.wait({until:function(){return b.width&&b.height},success:function(){h.call(b)},error:function(){j?c.raise("Could not extract width/height from image: "+b.src+". Traced measures: width:"+b.width+"px, height: "+b.height+"px."):(a(new Image).on("load",o).attr("src",b.src),j=!0)},timeout:100})}(this)}}(this,f,d);return k.find("iframe,img").remove(),m.css("display","block"),K.hide(this.image),a.each("minWidth minHeight maxWidth maxHeight".split(" "),function(a,b){m.css(b,/min/.test(b)?"0":"none")}),m.on("load",o).on("error",n).attr("src",d),this.container},scale:function(b){var e=this;if(b=a.extend({width:0,height:0,min:d,max:d,margin:0,complete:q,position:"center",crop:!1,canvas:!1,iframelimit:d},b),this.isIframe){var f,g,h=b.width,i=b.height;if(b.iframelimit){var j=p.min(b.iframelimit/h,b.iframelimit/i);j<1?(f=h*j,g=i*j,a(this.image).css({top:i/2-g/2,left:h/2-f/2,position:"absolute"})):a(this.image).css({top:0,left:0})}a(this.image).width(f||h).height(g||i).removeAttr("width").removeAttr("height"),a(this.container).width(h).height(i),b.complete.call(e,e);try{this.image.contentWindow&&a(this.image.contentWindow).trigger("resize")}catch(a){}return this.container}if(!this.image)return this.container;var k,l,m,n=a(e.container);return K.wait({until:function(){return k=b.width||n.width()||K.parseValue(n.css("width")),l=b.height||n.height()||K.parseValue(n.css("height")),k&&l},success:function(){var c=(k-2*b.margin)/e.original.width,d=(l-2*b.margin)/e.original.height,f=p.min(c,d),g=p.max(c,d),h={true:g,width:c,height:d,false:f,landscape:e.original.width>e.original.height?g:f,portrait:e.original.width<e.original.height?g:f},i=h[b.crop.toString()],j="";b.max&&(i=p.min(b.max,i)),b.min&&(i=p.max(b.min,i)),a.each(["width","height"],function(b,c){a(e.image)[c](e[c]=e.image[c]=p.round(e.original[c]*i))}),a(e.container).width(k).height(l),b.canvas&&G&&(G.elem.width=e.width,G.elem.height=e.height,j=e.image.src+":"+e.width+"x"+e.height,e.image.src=G.cache[j]||function(a){G.context.drawImage(e.image,0,0,e.original.width*i,e.original.height*i);try{return m=G.elem.toDataURL(),G.length+=m.length,G.cache[a]=m,m}catch(a){return e.image.src}}(j));var n={},o={},q=function(b,c,d){var f=0;if(/\%/.test(b)){var g=parseInt(b,10)/100,h=e.image[c]||a(e.image)[c]();f=p.ceil(h*-1*g+d*g)}else f=K.parseValue(b);return f},r={top:{top:0},left:{left:0},right:{left:"100%"},bottom:{top:"100%"}};a.each(b.position.toLowerCase().split(" "),function(a,b){"center"===b&&(b="50%"),n[a?"top":"left"]=b}),a.each(n,function(b,c){r.hasOwnProperty(c)&&a.extend(o,r[c])}),n=n.top?a.extend(n,o):o,n=a.extend({top:"50%",left:"50%"},n),a(e.image).css({position:"absolute",top:q(n.top,"height",l),left:q(n.left,"width",k)}),e.show(),e.ready=!0,b.complete.call(e,e)},error:function(){c.raise("Could not scale image: "+e.image.src)},timeout:1e3}),this}},a.extend(a.easing,{galleria:function(a,b,c,d,e){return(b/=e/2)<1?d/2*b*b*b+c:d/2*((b-=2)*b*b+2)+c},galleriaIn:function(a,b,c,d,e){return d*(b/=e)*b+c},galleriaOut:function(a,b,c,d,e){return-d*(b/=e)*(b-2)+c}}),c.Finger=function(){var d=(p.abs,c.HAS3D=function(){var b,c,d=e.createElement("p"),f=["webkit","O","ms","Moz",""],g=0,h="transform";for(t().html.insertBefore(d,null);f[g];g++)c=f[g]?f[g]+"Transform":h,void 0!==d.style[c]&&(d.style[c]="translate3d(1px,1px,1px)",b=a(d).css(f[g]?"-"+f[g].toLowerCase()+"-"+h:h));return t().html.removeChild(d),void 0!==b&&b.length>0&&"none"!==b}()),g=function(){var a="RequestAnimationFrame";return b.requestAnimationFrame||b["webkit"+a]||b["moz"+a]||b["o"+a]||b["ms"+a]||function(a){b.setTimeout(a,1e3/60)}}(),h=function(c,e){if(this.config={start:0,duration:500,onchange:function(){},oncomplete:function(){},easing:function(a,b,c,d,e){return-d*((b=b/e-1)*b*b*b-1)+c}},this.easeout=function(a,b,c,d,e){return d*((b=b/e-1)*b*b*b*b+1)+c},c.children.length){var f=this;a.extend(this.config,e),this.elem=c,this.child=c.children[0],this.to=this.pos=0,this.touching=!1,this.start={},this.index=this.config.start,this.anim=0,this.easing=this.config.easing,d||(this.child.style.position="absolute",this.elem.style.position="relative"),a.each(["ontouchstart","ontouchmove","ontouchend","setup"],function(a,b){f[b]=function(a){return function(){a.apply(f,arguments)}}(f[b])}),this.setX=function(){var a=f.child.style;return d?void(a.MozTransform=a.webkitTransform=a.transform="translate3d("+f.pos+"px,0,0)"):void(a.left=f.pos+"px")},a(c).on("touchstart",this.ontouchstart),a(b).on("resize",this.setup),a(b).on("orientationchange",this.setup),this.setup(),function a(){g(a),f.loop.call(f)}()}};return h.prototype={constructor:h,setup:function(){this.width=a(this.elem).width(),this.length=p.ceil(a(this.child).width()/this.width),0!==this.index&&(this.index=p.max(0,p.min(this.index,this.length-1)),this.pos=this.to=-this.width*this.index)},setPosition:function(a){this.pos=a,this.to=a},ontouchstart:function(a){var b=a.originalEvent.touches;this.start={pageX:b[0].pageX,pageY:b[0].pageY,time:+new Date},this.isScrolling=null,this.touching=!0,this.deltaX=0,f.on("touchmove",this.ontouchmove),f.on("touchend",this.ontouchend)},ontouchmove:function(a){var b=a.originalEvent.touches;b&&b.length>1||a.scale&&1!==a.scale||(this.deltaX=b[0].pageX-this.start.pageX,null===this.isScrolling&&(this.isScrolling=!!(this.isScrolling||p.abs(this.deltaX)<p.abs(b[0].pageY-this.start.pageY))),this.isScrolling||(a.preventDefault(),this.deltaX/=!this.index&&this.deltaX>0||this.index==this.length-1&&this.deltaX<0?p.abs(this.deltaX)/this.width+1.8:1,this.to=this.deltaX-this.index*this.width),a.stopPropagation())},ontouchend:function(a){this.touching=!1;var b=+new Date-this.start.time<250&&p.abs(this.deltaX)>40||p.abs(this.deltaX)>this.width/2,c=!this.index&&this.deltaX>0||this.index==this.length-1&&this.deltaX<0;this.isScrolling||this.show(this.index+(b&&!c?this.deltaX<0?1:-1:0)),f.off("touchmove",this.ontouchmove),f.off("touchend",this.ontouchend)},show:function(a){a!=this.index?this.config.onchange.call(this,a):this.to=-(a*this.width)},moveTo:function(a){a!=this.index&&(this.pos=this.to=-(a*this.width),this.index=a)},loop:function(){var a=this.to-this.pos,b=1;if(this.width&&a&&(b=p.max(.5,p.min(1.5,p.abs(a/this.width)))),this.touching||p.abs(a)<=1)this.pos=this.to,a=0,this.anim&&!this.touching&&this.config.oncomplete(this.index),this.anim=0,this.easing=this.config.easing;else{this.anim||(this.anim={start:this.pos,time:+new Date,distance:a,factor:b,destination:this.to});var c=+new Date-this.anim.time,d=this.config.duration*this.anim.factor;if(c>d||this.anim.destination!=this.to)return this.anim=0,void(this.easing=this.easeout);this.pos=this.easing(null,c,this.anim.start,this.anim.distance,d)}this.setX()}},h}(),a.fn.galleria=function(b){var d=this.selector;return a(this).length?this.each(function(){a.data(this,"galleria")&&(a.data(this,"galleria").destroy(),a(this).find("*").hide()),a.data(this,"galleria",(new c).init(this,b))}):(a(function(){a(d).length?a(d).galleria(b):c.utils.wait({until:function(){return a(d).length},success:function(){a(d).galleria(b)},error:function(){c.raise('Init failed: Galleria could not find the element "'+d+'".')},timeout:5e3})}),this)},"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=c:(b.Galleria=c,"function"==typeof define&&define.amd&&define("galleria",["jquery"],function(){return c}))}(jQuery,this); | 153957-theme | /153957-theme-2.tar.gz/153957-theme-2/153957_theme/static/js/galleria.min.js | galleria.min.js |
Edit `ForeignKey`, `ManyToManyField` and `CharField` in Django Admin using jQuery UI AutoComplete.
[](https://travis-ci.org/crucialfelix/django-ajax-selects) [](https://badge.fury.io/py/django-ajax-selects)
---


Documentation
------------------
http://django-ajax-selects.readthedocs.org/en/latest/
Quick Usage
-----------
Define a lookup channel:
```python
# yourapp/lookups.py
from ajax_select import register, LookupChannel
from .models import Tag
@register('tags')
class TagsLookup(LookupChannel):
model = Tag
def get_query(self, q, request):
return self.model.objects.filter(name__icontains=q).order_by('name')[:50]
def format_item_display(self, item):
return u"<span class='tag'>%s</span>" % item.name
```
Add field to a form:
```python
# yourapp/forms.py
class DocumentForm(ModelForm):
class Meta:
model = Document
tags = AutoCompleteSelectMultipleField('tags')
```
Fully customizable
------------------
- Customize search query
- Query other resources besides Django ORM
- Format results with HTML
- Customize styling
- Customize security policy
- Add additional custom UI alongside widget
- Integrate with other UI elements elsewhere on the page using the javascript API
- Works in Admin as well as in normal views
Assets included by default
-------------------
- //ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
- //code.jquery.com/ui/1.10.3/jquery-ui.js
- //code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css
Compatibility
-------------
- Django >=1.6, <=1.10
- Python >=2.7, 3.3-3.5
Contributors
------------
Many thanks to all contributors and pull requesters !
https://github.com/crucialfelix/django-ajax-selects/graphs/contributors
License
-------
Dual licensed under the MIT and GPL licenses:
- http://www.opensource.org/licenses/mit-license.php
- http://www.gnu.org/licenses/gpl.html
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/README.md | README.md |
#!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
setup(
name='15five-django-ajax-selects',
version='1.5.2.155',
description='Edit ForeignKey, ManyToManyField and CharField in Django Admin using jQuery UI AutoComplete.',
author='Chris Sattinger',
author_email='crucialfelix@gmail.com',
url='https://github.com/crucialfelix/django-ajax-selects/',
packages=['ajax_select'],
package_data={'ajax_select':
[
'*.py',
'*.txt',
'*.md',
'static/ajax_select/css/*',
'static/ajax_select/images/*',
'static/ajax_select/js/*',
'templates/ajax_select/*.html'
]
},
include_package_data=True,
zip_safe=False,
license="MIT",
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Development Status :: 5 - Production/Stable",
'Environment :: Web Environment',
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Software Development :: User Interfaces",
"Framework :: Django",
],
long_description="""\
Edit ForeignKey, ManyToManyField and CharField in Django Admin using jQuery UI AutoComplete.
- Customize search query
- Query other resources besides Django ORM
- Format results with HTML
- Customize styling
- Customize security policy
- Add additional custom UI alongside widget
- Integrate with other UI elements elsewhere on the page using the javascript API
- Works in Admin as well as in normal views
- Django >=1.6, <=1.10
- Python >=2.7, <=3.5
"""
)
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/setup.py | setup.py |
# Change Log
## [1.5.2](https://github.com/crucialfelix/django-ajax-selects/tree/1.5.2) (2016-10-19)
[Full Changelog](https://github.com/crucialfelix/django-ajax-selects/compare/1.5.1...1.5.2)
**Fixed bugs:**
- Occasionally: $.ui.autocomplete is undefined [\#188](https://github.com/crucialfelix/django-ajax-selects/issues/188)
**Closed issues:**
- No cache management headers in HTTP response [\#187](https://github.com/crucialfelix/django-ajax-selects/issues/187)
## [1.5.1](https://github.com/crucialfelix/django-ajax-selects/tree/1.5.1) (2016-10-13)
[Full Changelog](https://github.com/crucialfelix/django-ajax-selects/compare/1.5.0...1.5.1)
**Implemented enhancements:**
- Prefer document.createElement to document.write [\#182](https://github.com/crucialfelix/django-ajax-selects/issues/182)
**Fixed bugs:**
- fix: add related for multiple select [\#184](https://github.com/crucialfelix/django-ajax-selects/pull/184) ([crucialfelix](https://github.com/crucialfelix))
## [1.5.0](https://github.com/crucialfelix/django-ajax-selects/tree/1.5.0) (2016-09-05)
[Full Changelog](https://github.com/crucialfelix/django-ajax-selects/compare/1.4.3...1.5.0)
- Added Support for Django 1.10
- Dropped Django 1.5
**Fixed bugs:**
- Initial fields are duplicated when new row added. [\#94](https://github.com/crucialfelix/django-ajax-selects/issues/94)
**Closed issues:**
- ValueError in Django 1.10 [\#177](https://github.com/crucialfelix/django-ajax-selects/issues/177)
- Django 1.10 did add popup [\#174](https://github.com/crucialfelix/django-ajax-selects/issues/174)
- Example not Working [\#161](https://github.com/crucialfelix/django-ajax-selects/issues/161)
**Merged pull requests:**
- Fix documentation to format code properly [\#165](https://github.com/crucialfelix/django-ajax-selects/pull/165) ([joshblum](https://github.com/joshblum))
- install.sh not working [\#162](https://github.com/crucialfelix/django-ajax-selects/pull/162) ([hdzierz](https://github.com/hdzierz))
## [1.4.3](https://github.com/crucialfelix/django-ajax-selects/tree/1.4.3) (2016-03-13)
[Full Changelog](https://github.com/crucialfelix/django-ajax-selects/compare/1.4.2...1.4.3)
**Closed issues:**
- Additional stacked inlines clear un-saved autocomplete fields [\#156](https://github.com/crucialfelix/django-ajax-selects/issues/156)
- support request: ManyToOneRel doesn't have expected attributes [\#154](https://github.com/crucialfelix/django-ajax-selects/issues/154)
**Merged pull requests:**
- Stop using deprecated \_meta api. [\#160](https://github.com/crucialfelix/django-ajax-selects/pull/160) ([kramarz](https://github.com/kramarz))
- Fixed file name in documentation for custom templates. [\#158](https://github.com/crucialfelix/django-ajax-selects/pull/158) ([sebslomski](https://github.com/sebslomski))
- Fixes re-initialization upon adding inlines [\#157](https://github.com/crucialfelix/django-ajax-selects/pull/157) ([funkyfuture](https://github.com/funkyfuture))
## [1.4.2](https://github.com/crucialfelix/django-ajax-selects/tree/1.4.2) (2016-01-18)
[Full Changelog](https://github.com/crucialfelix/django-ajax-selects/compare/1.4.1...1.4.2)
**Fixed bugs:**
- Selected data lost when adding new rows via ajax [\#145](https://github.com/crucialfelix/django-ajax-selects/issues/145)
- Inline forms raise TypeError when not filled in [\#142](https://github.com/crucialfelix/django-ajax-selects/issues/142)
**Merged pull requests:**
- Fix incorrect has\_changed result for AutoCompleteSelectField that has not been filled in. [\#152](https://github.com/crucialfelix/django-ajax-selects/pull/152) ([unklphil](https://github.com/unklphil))
- Only trigger reset\(\) initially if data hasn't changed. [\#146](https://github.com/crucialfelix/django-ajax-selects/pull/146) ([jmfederico](https://github.com/jmfederico))
## [1.4.1](https://github.com/crucialfelix/django-ajax-selects/tree/1.4.1) (2015-11-18)
[Full Changelog](https://github.com/crucialfelix/django-ajax-selects/compare/1.4.0...1.4.1)
**Closed issues:**
- Templates not included in pypi1.4.0 package [\#141](https://github.com/crucialfelix/django-ajax-selects/issues/141)
- Documentation seems to be broken on RTD [\#140](https://github.com/crucialfelix/django-ajax-selects/issues/140)
## [1.4.0](https://github.com/crucialfelix/django-ajax-selects/tree/1.4.0) (2015-11-07)
[Full Changelog](https://github.com/crucialfelix/django-ajax-selects/compare/1.3.6...1.4.0)
**Implemented enhancements:**
- Pass `request` to `LookupChannel` methods, make overriding easier [\#40](https://github.com/crucialfelix/django-ajax-selects/issues/40)
**Fixed bugs:**
- AttributeError on invalid form data [\#135](https://github.com/crucialfelix/django-ajax-selects/issues/135)
- Doesn't work with readonly\_fields [\#120](https://github.com/crucialfelix/django-ajax-selects/issues/120)
- Add another popup doesn't add `?\_popup=1` to url in Django 1.8 [\#118](https://github.com/crucialfelix/django-ajax-selects/issues/118)
- Field appers duplicated when marked as readonly in admin [\#84](https://github.com/crucialfelix/django-ajax-selects/issues/84)
**Closed issues:**
- can't import register module [\#139](https://github.com/crucialfelix/django-ajax-selects/issues/139)
- How to fire lookup for value in text field using javascript [\#137](https://github.com/crucialfelix/django-ajax-selects/issues/137)
- tests not included in MANIFEST.in [\#136](https://github.com/crucialfelix/django-ajax-selects/issues/136)
- Content of input not included in field, only dropdown choices for make\_ajax\_field [\#134](https://github.com/crucialfelix/django-ajax-selects/issues/134)
- documentation for add link on ajax fields for django admin inlines [\#127](https://github.com/crucialfelix/django-ajax-selects/issues/127)
- Can't specify widget for AutoCompleteSelectMultipleField [\#126](https://github.com/crucialfelix/django-ajax-selects/issues/126)
- RemovedInDjango19Warning in ajax\_select [\#125](https://github.com/crucialfelix/django-ajax-selects/issues/125)
- Django's form change\_data always include autocomplete fields [\#123](https://github.com/crucialfelix/django-ajax-selects/issues/123)
- AttributeError: 'int' object has no attribute 'isnumeric' [\#117](https://github.com/crucialfelix/django-ajax-selects/issues/117)
- Error with TheForm in Django 1.8 [\#115](https://github.com/crucialfelix/django-ajax-selects/issues/115)
- Not Secure. invalid literal for long\(\) with base 10 [\#114](https://github.com/crucialfelix/django-ajax-selects/issues/114)
- ImportError: No module named ajax\_select [\#112](https://github.com/crucialfelix/django-ajax-selects/issues/112)
- 'AutoCompleteSelectWidget' object has no attribute 'choices' [\#111](https://github.com/crucialfelix/django-ajax-selects/issues/111)
- "Uncaught TypeError: Cannot read property 'autocomplete' of undefined" [\#107](https://github.com/crucialfelix/django-ajax-selects/issues/107)
- Regression? Or UUID PK not supported [\#103](https://github.com/crucialfelix/django-ajax-selects/issues/103)
- Support lookup channels from third-party apps [\#98](https://github.com/crucialfelix/django-ajax-selects/issues/98)
- callbacks for select doesn't work [\#97](https://github.com/crucialfelix/django-ajax-selects/issues/97)
- DeprecationWarning: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is deprecated [\#96](https://github.com/crucialfelix/django-ajax-selects/issues/96)
- AutoCompleteSelectField has no attribute 'limit\_choices\_to' in Django 1.7 [\#83](https://github.com/crucialfelix/django-ajax-selects/issues/83)
- Custom form [\#81](https://github.com/crucialfelix/django-ajax-selects/issues/81)
- avoid warning when installing via pip [\#53](https://github.com/crucialfelix/django-ajax-selects/issues/53)
- search\_fields like in ModelAdmin [\#21](https://github.com/crucialfelix/django-ajax-selects/issues/21)
- Issues when using django-admin-sortable [\#12](https://github.com/crucialfelix/django-ajax-selects/issues/12)
**Merged pull requests:**
- Get rid of terrible `\_as\_pk` function \(fixes \#117, \#120, and \#135\) [\#138](https://github.com/crucialfelix/django-ajax-selects/pull/138) ([hwkns](https://github.com/hwkns))
- Reset button handling [\#132](https://github.com/crucialfelix/django-ajax-selects/pull/132) ([jmerdich](https://github.com/jmerdich))
- Remove unnecessary backquotes in README.md [\#131](https://github.com/crucialfelix/django-ajax-selects/pull/131) ([zablotski](https://github.com/zablotski))
- Feature autodiscover [\#129](https://github.com/crucialfelix/django-ajax-selects/pull/129) ([morr0350](https://github.com/morr0350))
- Example for get\_formset on inline admin [\#128](https://github.com/crucialfelix/django-ajax-selects/pull/128) ([rlskoeser](https://github.com/rlskoeser))
- ajax\_lookup should respond with content type `application/json` [\#119](https://github.com/crucialfelix/django-ajax-selects/pull/119) ([unklphil](https://github.com/unklphil))
- Add AjaxSelectAdminStackedInline to work similarly to AjaxSelectAdminTabularInline [\#89](https://github.com/crucialfelix/django-ajax-selects/pull/89) ([unklphil](https://github.com/unklphil))
## [1.3.6](https://github.com/crucialfelix/django-ajax-selects/tree/1.3.6) (2015-04-06)
[Full Changelog](https://github.com/crucialfelix/django-ajax-selects/compare/1.3.5...1.3.6)
**Closed issues:**
- 'AutoCompleteSelectWidget' object has no attribute 'choices' [\#110](https://github.com/crucialfelix/django-ajax-selects/issues/110)
- \_\_init\_\_\(\) got an unexpected keyword argument 'mimetype' [\#108](https://github.com/crucialfelix/django-ajax-selects/issues/108)
- Limit number of results returned by lookup and auto load additional results when user scrolls to bottom of list [\#105](https://github.com/crucialfelix/django-ajax-selects/issues/105)
- Support reverse relationships [\#99](https://github.com/crucialfelix/django-ajax-selects/issues/99)
- 'set' object does not support indexing [\#93](https://github.com/crucialfelix/django-ajax-selects/issues/93)
- deck area [\#92](https://github.com/crucialfelix/django-ajax-selects/issues/92)
- Inline won't work with new lines \(SOLVED\) [\#87](https://github.com/crucialfelix/django-ajax-selects/issues/87)
- Bug in ajax\_selects.js \(addKiller function call\) [\#79](https://github.com/crucialfelix/django-ajax-selects/issues/79)
- AutoCompleteSelectField breaks when using localization and long ids [\#68](https://github.com/crucialfelix/django-ajax-selects/issues/68)
- format\_match did not work with django-ajax-select 1.3.3 [\#58](https://github.com/crucialfelix/django-ajax-selects/issues/58)
- Support Non-integer Primary Keys \(mongodb etc\) [\#34](https://github.com/crucialfelix/django-ajax-selects/issues/34)
- non operation with mongodb [\#3](https://github.com/crucialfelix/django-ajax-selects/issues/3)
**Merged pull requests:**
- Change order for running script by .sh \#112 \(NOTICE\) [\#113](https://github.com/crucialfelix/django-ajax-selects/pull/113) ([skrzypek](https://github.com/skrzypek))
- Update README.md [\#101](https://github.com/crucialfelix/django-ajax-selects/pull/101) ([cormier](https://github.com/cormier))
- Added option for fields in TheForm superclass [\#91](https://github.com/crucialfelix/django-ajax-selects/pull/91) ([onyekaa](https://github.com/onyekaa))
## [1.3.5](https://github.com/crucialfelix/django-ajax-selects/tree/1.3.5) (2014-08-02)
[Full Changelog](https://github.com/crucialfelix/django-ajax-selects/compare/1.3.4...1.3.5)
**Closed issues:**
- ajax-selects/fields.py simplejson is deprecated [\#74](https://github.com/crucialfelix/django-ajax-selects/issues/74)
- Document the use in template for 'quick installation' [\#71](https://github.com/crucialfelix/django-ajax-selects/issues/71)
- Document how to use an ajax field in a ListFilter in admin [\#70](https://github.com/crucialfelix/django-ajax-selects/issues/70)
- Issue with Ajax-Search on Media-Fields [\#60](https://github.com/crucialfelix/django-ajax-selects/issues/60)
- Set width of jquery autocomplete widget [\#30](https://github.com/crucialfelix/django-ajax-selects/issues/30)
**Merged pull requests:**
- Fix issue 58 and pull request 76 [\#85](https://github.com/crucialfelix/django-ajax-selects/pull/85) ([camillobruni](https://github.com/camillobruni))
- Django's HttpResponse object has deprecated the mimetype kwarg in 1.7 [\#82](https://github.com/crucialfelix/django-ajax-selects/pull/82) ([squidsoup](https://github.com/squidsoup))
- Support non-int primary keys [\#78](https://github.com/crucialfelix/django-ajax-selects/pull/78) ([AlexHill](https://github.com/AlexHill))
- correct import deprecated since Django 1.4 [\#77](https://github.com/crucialfelix/django-ajax-selects/pull/77) ([gertingold](https://github.com/gertingold))
- maintain compatibility with Python 2.6 [\#75](https://github.com/crucialfelix/django-ajax-selects/pull/75) ([gertingold](https://github.com/gertingold))
## [1.3.4](https://github.com/crucialfelix/django-ajax-selects/tree/1.3.4) (2014-03-30)
[Full Changelog](https://github.com/crucialfelix/django-ajax-selects/compare/1.3.3...1.3.4)
**Closed issues:**
- Custom validation with django-ajax-selects [\#73](https://github.com/crucialfelix/django-ajax-selects/issues/73)
- DeprecationWarning django.utils.simplejson [\#63](https://github.com/crucialfelix/django-ajax-selects/issues/63)
- When create select list always show \(in bottom list\) add new object. [\#62](https://github.com/crucialfelix/django-ajax-selects/issues/62)
**Merged pull requests:**
- Trivial typo fix \(chanel\_name\) [\#69](https://github.com/crucialfelix/django-ajax-selects/pull/69) ([gthb](https://github.com/gthb))
- Fixes \#18 - AJAX Selector and dynamic inlines [\#67](https://github.com/crucialfelix/django-ajax-selects/pull/67) ([peterfarrell](https://github.com/peterfarrell))
- Using json as opposed to simplejson \(depreciated\) [\#65](https://github.com/crucialfelix/django-ajax-selects/pull/65) ([krzysztof](https://github.com/krzysztof))
## [1.3.3](https://github.com/crucialfelix/django-ajax-selects/tree/1.3.3) (2013-11-13)
[Full Changelog](https://github.com/crucialfelix/django-ajax-selects/compare/1.3.2...1.3.3)
**Merged pull requests:**
- Remove protocol from dynamically loaded urls. [\#54](https://github.com/crucialfelix/django-ajax-selects/pull/54) ([jellonek](https://github.com/jellonek))
## [1.3.2](https://github.com/crucialfelix/django-ajax-selects/tree/1.3.2) (2013-11-09)
[Full Changelog](https://github.com/crucialfelix/django-ajax-selects/compare/1.3.1...1.3.2)
## [1.3.1](https://github.com/crucialfelix/django-ajax-selects/tree/1.3.1) (2013-10-09)
[Full Changelog](https://github.com/crucialfelix/django-ajax-selects/compare/1.3.0...1.3.1)
**Closed issues:**
- parameters to triggers [\#43](https://github.com/crucialfelix/django-ajax-selects/issues/43)
- django.conf.urls.defaults depreciated [\#38](https://github.com/crucialfelix/django-ajax-selects/issues/38)
- How do you pass a class name for the addKiller [\#37](https://github.com/crucialfelix/django-ajax-selects/issues/37)
- AutoComplete and AutoCompleteSelect renders fine but AutoCompleteMultipleSelect isnt working [\#31](https://github.com/crucialfelix/django-ajax-selects/issues/31)
- django inline formset [\#18](https://github.com/crucialfelix/django-ajax-selects/issues/18)
## [1.3.0](https://github.com/crucialfelix/django-ajax-selects/tree/1.3.0) (2013-10-08)
[Full Changelog](https://github.com/crucialfelix/django-ajax-selects/compare/1.2.5...1.3.0)
**Closed issues:**
- ContentNotRenderedError [\#39](https://github.com/crucialfelix/django-ajax-selects/issues/39)
- Please add a change trigger to the target. [\#35](https://github.com/crucialfelix/django-ajax-selects/issues/35)
- can\_add isn't working in lookups [\#23](https://github.com/crucialfelix/django-ajax-selects/issues/23)
**Merged pull requests:**
- Follow the Meta definition of the original modelform [\#49](https://github.com/crucialfelix/django-ajax-selects/pull/49) ([artscoop](https://github.com/artscoop))
## [1.2.5](https://github.com/crucialfelix/django-ajax-selects/tree/1.2.5) (2012-08-22)
[Full Changelog](https://github.com/crucialfelix/django-ajax-selects/compare/1.2.4...1.2.5)
**Closed issues:**
- dj1.4 Error importing template source loader django.template.loaders.filesystem.load\_template\_source: [\#15](https://github.com/crucialfelix/django-ajax-selects/issues/15)
- fixed bug: AutoCompleteSelectMultipleField does not honor 'widget' parameter [\#14](https://github.com/crucialfelix/django-ajax-selects/issues/14)
- error 'this.data\("autocomplete"\) is undefined' [\#10](https://github.com/crucialfelix/django-ajax-selects/issues/10)
- Fire the change event on selection [\#8](https://github.com/crucialfelix/django-ajax-selects/issues/8)
- ValueError: translation table must be 256 characters long [\#5](https://github.com/crucialfelix/django-ajax-selects/issues/5)
- Error on Pop-Up [\#19](https://github.com/crucialfelix/django-ajax-selects/issues/19)
**Merged pull requests:**
- Small fix in CSS [\#2](https://github.com/crucialfelix/django-ajax-selects/pull/2) ([karlmoritz](https://github.com/karlmoritz))
## [1.2.4](https://github.com/crucialfelix/django-ajax-selects/tree/1.2.4) (2012-01-15)
[Full Changelog](https://github.com/crucialfelix/django-ajax-selects/compare/1.2.3...1.2.4)
## [1.2.3](https://github.com/crucialfelix/django-ajax-selects/tree/1.2.3) (2011-11-29)
[Full Changelog](https://github.com/crucialfelix/django-ajax-selects/compare/1.2.1...1.2.3)
## [1.2.1](https://github.com/crucialfelix/django-ajax-selects/tree/1.2.1) (2011-10-19)
[Full Changelog](https://github.com/crucialfelix/django-ajax-selects/compare/1.1.5...1.2.1)
## [1.1.5](https://github.com/crucialfelix/django-ajax-selects/tree/1.1.5) (2011-08-24)
[Full Changelog](https://github.com/crucialfelix/django-ajax-selects/compare/1.1.3...1.1.5)
## [1.1.3](https://github.com/crucialfelix/django-ajax-selects/tree/1.1.3) (2010-06-06)
[Full Changelog](https://github.com/crucialfelix/django-ajax-selects/compare/1.1.1...1.1.3)
## [1.1.1](https://github.com/crucialfelix/django-ajax-selects/tree/1.1.1) (2010-06-03)
[Full Changelog](https://github.com/crucialfelix/django-ajax-selects/compare/1.1.0...1.1.1)
## [1.1.0](https://github.com/crucialfelix/django-ajax-selects/tree/1.1.0) (2010-03-06)
\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)*
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/CHANGELOG.md | CHANGELOG.md |
"""
Testing the register and autoloading.
Should not be used by other tests.
"""
from django.utils.html import escape
from django.contrib.auth.models import User
from tests.models import Person, Author
import ajax_select
@ajax_select.register('person')
class PersonLookup(ajax_select.LookupChannel):
model = Person
def get_query(self, q, request):
return self.model.objects.filter(name__icontains=q)
def get_result(self, obj):
return obj.name
def format_match(self, obj):
return "%s<div><i>%s</i></div>" % (escape(obj.name), escape(obj.email))
def format_item_display(self, obj):
return "%s<div><i>%s</i></div>" % (escape(obj.name), escape(obj.email))
@ajax_select.register('user')
class UserLookup(ajax_select.LookupChannel):
"""
Test if you can unset a lookup provided by a third-party application.
In this case it exposes User without any auth checking
and somebody could manually check the ajax URL and find out
if a user email exists.
So you might want to turn this channel off
by settings.AJAX_LOOKUP_CHANNELS['user'] = None
"""
model = User
def get_query(self, q, request):
return self.model.objects.filter(email=q)
@ajax_select.register('name')
class NameLookup(ajax_select.LookupChannel):
def get_query(self, q, request):
return ['Joseph Simmons', 'Darryl McDaniels', 'Jam Master Jay']
@ajax_select.register('author')
class AuthorLookup(ajax_select.LookupChannel):
model = Author
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/tests/lookups.py | lookups.py |
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin
from django.conf import settings
from ajax_select import urls as ajax_select_urls
admin.autodiscover()
urlpatterns = [
url(r'^ajax_lookups/', include(ajax_select_urls)),
url(r'^admin/', include(admin.site.urls)),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/tests/urls.py | urls.py |
DEBUG = True
USE_TZ = True
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
}
ROOT_URLCONF = "tests.urls"
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
'django.contrib.messages',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.staticfiles',
"ajax_select",
"tests"
]
SITE_ID = 1
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware'
)
STATIC_URL = '/static/'
SECRET_KEY = 'inyd5fc5pymlsv@hwoc5+3_6*cm0erlxzv6i-wl0jm_kt-6rp9'
AJAX_LOOKUP_CHANNELS = {
# tuple points to a module and class to load
'book': ('tests.other_lookups', 'BookLookup'),
# dict specifies an automatically constructed LookupChannel
'author': {'model': 'tests.Author', 'search_field': 'name'},
# unset a channel that a third-party app specified
'user': None,
'was-never-a-channel': None
# LookupChannels in lookups.py are auto-loaded
}
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
# insert your TEMPLATE_DIRS here
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
# Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
# list if you haven't customized them:
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
],
},
},
]
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/tests/settings.py | settings.py |
from django.contrib import admin
from ajax_select.admin import AjaxSelectAdmin, AjaxSelectAdminTabularInline
from tests.models import Author, Book, Person
from tests.test_integration import BookForm
class BookAdmin(AjaxSelectAdmin):
form = BookForm
admin.site.register(Book, BookAdmin)
class BookInline(AjaxSelectAdminTabularInline):
model = Book
form = BookForm
extra = 2
class AuthorAdmin(AjaxSelectAdmin):
inlines = [
BookInline
]
admin.site.register(Author, AuthorAdmin)
class PersonAdmin(admin.ModelAdmin):
pass
admin.site.register(Person, PersonAdmin)
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/tests/admin.py | admin.py |
from django.test import TestCase
from ajax_select import fields
from tests.models import Book
class TestAutoCompleteSelectWidget(TestCase):
def test_render(self):
channel = 'book'
widget = fields.AutoCompleteSelectWidget(channel)
out = widget.render('book', None)
self.assertTrue('autocompleteselect' in out)
def test_render_with_value(self):
channel = 'book'
widget = fields.AutoCompleteSelectWidget(channel)
book = Book.objects.create(name='book')
out = widget.render('book', book.pk)
self.assertTrue('autocompleteselect' in out)
class TestAutoCompleteSelectMultipleWidget(TestCase):
def test_render(self):
channel = 'book'
widget = fields.AutoCompleteSelectMultipleWidget(channel)
out = widget.render('book', None)
self.assertTrue('autocompleteselectmultiple' in out)
def test_render_with_query_set(self):
channel = 'book'
widget = fields.AutoCompleteSelectMultipleWidget(channel)
Book.objects.create(name='book')
out = widget.render('book', Book.objects.all())
self.assertTrue('autocompleteselectmultiple' in out)
class TestAutoCompleteWidget(TestCase):
def test_render(self):
channel = 'book'
widget = fields.AutoCompleteWidget(channel)
out = widget.render('book', None)
self.assertTrue('autocomplete' in out)
class TestAutoCompleteSelectField(TestCase):
def test_has_changed(self):
field = fields.AutoCompleteSelectField('book')
self.assertFalse(field.has_changed(1, '1'))
self.assertFalse(field.has_changed('abc', 'abc'))
self.assertTrue(field.has_changed(1, '2'))
self.assertFalse(field.has_changed(None, ''))
self.assertFalse(field.has_changed(None, None))
self.assertFalse(field.has_changed('', None))
class TestAutoCompleteSelectMultipleField(TestCase):
def test_has_changed(self):
field = fields.AutoCompleteSelectMultipleField('book')
self.assertFalse(field.has_changed([1], ['1']))
self.assertFalse(field.has_changed(['abc'], ['abc']))
self.assertTrue(field.has_changed([1], ['2']))
def test_has_changed_blank_input(self):
field = fields.AutoCompleteSelectMultipleField('book')
self.assertTrue(field.has_changed(None, ['1']))
self.assertFalse(field.has_changed(None, []))
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/tests/test_fields.py | test_fields.py |
"""Testing if lookups that are not in a file named lookups.py can be loaded correctly."""
import ajax_select
from tests.models import Book
class BookLookup(ajax_select.LookupChannel):
model = Book
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/tests/other_lookups.py | other_lookups.py |
from django.test import TestCase
from django.contrib.auth.models import User
from django.test import Client
class TestViews(TestCase):
def setUp(self):
self.user = User.objects.create_superuser(username='admin',
email='email@example.com',
password='password')
self.client = Client()
self.client.login(username='admin', password='password')
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/tests/test_views.py | test_views.py |
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField(null=True, blank=True)
class Meta:
app_label = 'tests'
class Author(models.Model):
name = models.CharField(max_length=50)
class Meta:
app_label = 'tests'
class Book(models.Model):
""" Book has no admin, its an inline in the Author admin"""
author = models.ForeignKey(Author, null=True)
name = models.CharField(max_length=50)
mentions_persons = models.ManyToManyField(Person, help_text="MENTIONS PERSONS HELP TEXT")
class Meta:
app_label = 'tests'
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/tests/models.py | models.py |
from django.test import TestCase
import ajax_select
from ajax_select.registry import can_autodiscover
class TestRegistry(TestCase):
def test_lookup_py_is_autoloaded(self):
"""Django >= 1.7 autoloads tests/lookups.py"""
is_registered = ajax_select.registry.is_registered('person')
if can_autodiscover():
self.assertTrue(is_registered)
else:
# person is not in settings and this django will not autoload lookups.py
# self.assertFalse(is_registered)
# test_integration is more important and requires that lookup.py be loaded
# Will drop support for 1.6 soon anyway and we know that it does work
pass
def test_back_compatible_loads_by_settings(self):
"""a module and class specified in settings"""
self.assertTrue(ajax_select.registry.is_registered('book'))
def test_autoconstruct_from_spec(self):
"""a dict in settings specifying model and lookup fields"""
self.assertTrue(ajax_select.registry.is_registered('author'))
def test_unsetting_a_channel(self):
"""settings can unset a channel that was specified in a lookups.py"""
# self.assertFalse(ajax_select.registry.is_registered('user'))
self.assertFalse(ajax_select.registry.is_registered('was-never-a-channel'))
# def test_reimporting_lookup(self):
# """
# Importing a lookup should not re-register it after app launch is completed.
# """
# # importing this file will cause the @register to be called
# from tests import lookups # noqa
# # should not have over-ridden what is in settings
# # registry is already frozen
# self.assertFalse(ajax_select.registry.is_registered('user'))
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/tests/test_registry.py | test_registry.py |
"""
Test render and submit from the highest Django API level
so we are testing with exactly what Django gives.
Specific errors that are discovered through these tests
should be unit tested in test_fields.py
"""
from __future__ import unicode_literals
import django
from django.forms.models import ModelForm
from django.test import TestCase, Client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from tests.models import Book, Author, Person
from ajax_select import fields
# Other versions will autoload
if django.VERSION[1] < 7:
from tests import lookups # noqa
# --------------- setup ----------------------------------- #
class BookForm(ModelForm):
class Meta:
model = Book
fields = ['name', 'author', 'mentions_persons']
name = fields.AutoCompleteField('name')
author = fields.AutoCompleteSelectField('author')
mentions_persons = fields.AutoCompleteSelectMultipleField('person')
# --------------- tests ----------------------------------- #
class TestBookForm(TestCase):
def test_render_no_data(self):
form = BookForm()
out = form.as_p()
# print(out)
self.assertTrue('autocomplete' in out)
self.assertTrue('autocompleteselect' in out)
self.assertTrue('autocompleteselectmultiple' in out)
def _make_instance(self):
author = Author.objects.create(name="author")
book = Book.objects.create(name="book", author=author)
book.mentions_persons = [Person.objects.create(name='person')]
return book
def _book_data(self, book):
persons_pks = [person.pk for person in book.mentions_persons.all()]
mentions_persons = fields.pack_ids(persons_pks)
return {
'author': str(book.author.pk),
'name': book.name,
'mentions_persons': mentions_persons
}
def test_render_instance(self):
book = self._make_instance()
form = BookForm(instance=book)
out = form.as_p()
# print(out)
self.assertTrue('autocomplete' in out)
self.assertTrue('autocompleteselect' in out)
self.assertTrue('autocompleteselectmultiple' in out)
def test_render_with_data(self):
"""
Rendering a form with data already in it
because it is pre-filled or had errors and is redisplaying.
"""
book = self._make_instance()
form = BookForm(data=self._book_data(book))
out = form.as_p()
# print(out)
# should have the values in there somewhere
self.assertTrue('autocomplete' in out)
self.assertTrue('autocompleteselect' in out)
self.assertTrue('autocompleteselectmultiple' in out)
def test_render_with_initial(self):
book = self._make_instance()
# this is data for the form submit
data = self._book_data(book)
# initial wants the pks
data['mentions_persons'] = [p.pk for p in book.mentions_persons.all()]
form = BookForm(initial=data)
out = form.as_p()
# print(out)
# should have the values in there somewhere
self.assertTrue('autocomplete' in out)
self.assertTrue('autocompleteselect' in out)
self.assertTrue('autocompleteselectmultiple' in out)
def test_is_valid(self):
book = self._make_instance()
form = BookForm(data=self._book_data(book))
self.assertTrue(form.is_valid())
def test_full_clean(self):
book = self._make_instance()
form = BookForm(data=self._book_data(book))
form.full_clean()
data = form.cleaned_data
# {u'author': <Author: Author object>, u'name': u'book', u'mentions_persons': [u'1']}
self.assertEqual(data['author'], book.author)
self.assertEqual(data['name'], book.name)
# why aren't they instances ?
self.assertEqual(data['mentions_persons'], [str(p.pk) for p in book.mentions_persons.all()])
def test_save(self):
book = self._make_instance()
form = BookForm(data=self._book_data(book))
saved = form.save()
self.assertTrue(saved.pk is not None)
# def test_save_instance(self):
# book = self._make_instance()
# form = BookForm(instance=book)
# import pdb; pdb.set_trace()
# if form.is_valid():
# saved = form.save()
# else:
# print(form.errors)
# saved = None
# self.assertTrue(saved is not None)
# self.assertEqual(saved.pk, book.pk)
class TestAdmin(TestCase):
def setUp(self):
self.user = User.objects.create_superuser('admin', 'admin@example.com', 'password')
self.client = Client()
ok = self.client.login(username='admin', password='password')
if not ok:
raise Exception("Failed to log in")
class TestBookAdmin(TestAdmin):
"""
Test the admins in tests/admin.py
"""
def test_get_blank(self):
app_label = 'tests'
model = 'book'
response = self.client.get(reverse('admin:%s_%s_add' % (app_label, model)))
content = str(response.content)
# print(content)
self.assertEqual(response.status_code, 200)
self.assertTrue('/static/ajax_select/js/ajax_select.js' in content)
self.assertTrue('autocompleteselectmultiple' in content)
self.assertTrue('autocompleteselect' in content)
self.assertTrue('autocomplete' in content)
self.assertTrue('/admin/tests/author/add/?_popup=1' in content)
self.assertTrue('/admin/tests/person/add/?_popup=1' in content)
class TestAuthorAdmin(TestAdmin):
"""
Test an admin with inlines
"""
def test_get_blank(self):
app_label = 'tests'
model = 'author'
response = self.client.get(reverse('admin:%s_%s_add' % (app_label, model)))
content = str(response.content)
# print(content)
self.assertEqual(response.status_code, 200)
self.assertTrue('book_set-1-mentions_persons' in content)
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/tests/test_integration.py | test_integration.py |
from django.core.exceptions import PermissionDenied
from django.utils.encoding import force_text
from django.utils.html import escape
class LookupChannel(object):
"""
Subclass this, setting the model and implementing methods to taste.
Attributes:
model (Model): The Django Model that this lookup channel will search for.
plugin_options (dict): Options passed to jQuery UI plugin that are specific to this channel.
min_length (int): Minimum number of characters user types before a search is initiated.
This is passed to the jQuery plugin_options.
It is used in jQuery's UI when filtering results from its own cache.
It is also used in the django view to prevent expensive database queries.
Large datasets can choke if they search too often with small queries.
Better to demand at least 2 or 3 characters.
"""
model = None
plugin_options = {}
min_length = 1
def get_query(self, q, request):
"""
Return a QuerySet searching for the query string `q`.
Note that you may return any iterable so you can return a list or even use yield and turn this
method into a generator.
Args:
q (str, unicode): The query string to search for.
request (Request): This can be used to customize the search by User or to use additional GET variables.
Returns:
(QuerySet, list, generator): iterable of related_models
"""
kwargs = {"%s__icontains" % self.search_field: q}
return self.model.objects.filter(**kwargs).order_by(self.search_field)
def get_result(self, obj):
"""The text result of autocompleting the entered query.
For a partial string that the user typed in, each matched result is here converted to the fully completed text.
This is currently displayed only for a moment in the text field after the user has selected the item.
Then the item is displayed in the item_display deck and the text field is cleared.
Args:
obj (Model):
Returns:
str: The object as string
"""
return escape(force_text(obj))
def format_match(self, obj):
"""(HTML) Format item for displaying in the dropdown.
Args:
obj (Model):
Returns:
str: formatted string, may contain HTML.
"""
return escape(force_text(obj))
def format_item_display(self, obj):
""" (HTML) format item for displaying item in the selected deck area.
Args:
obj (Model):
Returns:
str: formatted string, may contain HTML.
"""
return escape(force_text(obj))
def get_objects(self, ids):
"""This is used to retrieve the currently selected objects for either ManyToMany or ForeignKey.
Note that the order of the ids supplied for ManyToMany fields is dependent on how the
objects manager fetches it.
ie. what is returned by `YourModel.{fieldname}_set.all()`
In most situations (especially postgres) this order is indeterminate -- not the order that you originally
added them in the interface.
See :doc:`/Ordered-ManyToMany` for a solution to this.
Args:
ids (list): list of primary keys
Returns:
list: list of Model objects
"""
# return objects in the same order as passed in here
pk_type = self.model._meta.pk.to_python
ids = [pk_type(pk) for pk in ids]
things = self.model.objects.in_bulk(ids)
return [things[aid] for aid in ids if aid in things]
def can_add(self, user, other_model):
"""Check if the user has permission to add a ForeignKey or M2M model.
This enables the green popup + on the widget.
Default implentation is the standard django permission check.
Args:
user (User)
other_model (Model): the ForeignKey or M2M model to check if the User can add.
Returns:
bool
"""
from django.contrib.contenttypes.models import ContentType
ctype = ContentType.objects.get_for_model(other_model)
return user.has_perm("%s.add_%s" % (ctype.app_label, ctype.model))
def check_auth(self, request):
"""By default only request.user.is_staff have access.
This ensures that nobody can get your data by simply knowing the lookup URL.
This is called from the ajax_lookup view.
Public facing forms (outside of the Admin) should implement this to allow
non-staff to use this LookupChannel.
Args:
request (Request)
Raises:
PermissionDenied
"""
if not request.user.is_staff:
raise PermissionDenied
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/ajax_select/lookup_channel.py | lookup_channel.py |
from django.apps import AppConfig
class AjaxSelectConfig(AppConfig):
"""
Django 1.7+ enables initializing installed applications
and autodiscovering modules
On startup, search for and import any modules called `lookups.py` in all installed apps.
Your LookupClass subclass may register itself.
"""
name = 'ajax_select'
verbose_name = 'Ajax Selects'
def ready(self):
from ajax_select.registry import registry
registry.load_channels()
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/ajax_select/apps.py | apps.py |
from django.conf.urls import url
from ajax_select import views
urlpatterns = [
url(r'^ajax_lookup/(?P<channel>[-\w]+)$',
views.ajax_lookup,
name='ajax_lookup')
]
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/ajax_select/urls.py | urls.py |
from django.core.exceptions import ImproperlyConfigured
from django.conf import settings
class LookupChannelRegistry(object):
"""
Registry for LookupChannels activated for your django project.
This includes any installed apps that contain lookup.py modules (django 1.7+)
and any lookups that are explicitly declared in `settings.AJAX_LOOKUP_CHANNELS`
"""
_registry = {}
def load_channels(self):
"""
Called when loading the application. Cannot be called a second time,
(eg. for testing) as Django will not re-import and re-register anything.
"""
self._registry = {}
try:
from django.utils.module_loading import autodiscover_modules
except ImportError:
pass
else:
autodiscover_modules('lookups')
if hasattr(settings, 'AJAX_LOOKUP_CHANNELS'):
self.register(settings.AJAX_LOOKUP_CHANNELS)
def register(self, lookup_specs):
"""Register a set of lookup definitions.
Args:
lookup_specs (dict): One or more LookupChannel specifications
- `{'channel': LookupChannelSubclass}`
- `{'channel': ('module.of.lookups', 'MyLookupClass')}`
- `{'channel': {'model': 'MyModelToBeLookedUp', 'search_field': 'field_to_search'}}`
"""
for channel, spec in lookup_specs.items():
if spec is None: # unset
if channel in self._registry:
del self._registry[channel]
else:
self._registry[channel] = spec
def get(self, channel):
"""Find the LookupChannel class for the named channel and instantiate it.
Args:
channel (string): - name that the lookup channel was registered at
Returns:
LookupChannel
Raises:
ImproperlyConfigured - if channel is not found.
Exception - invalid lookup_spec was stored in registery
"""
from ajax_select import LookupChannel
try:
lookup_spec = self._registry[channel]
except KeyError:
raise ImproperlyConfigured(
"No ajax_select LookupChannel named %(channel)r is registered." % {'channel': channel})
if (type(lookup_spec) is type) and issubclass(lookup_spec, LookupChannel):
return lookup_spec()
# damnit python.
# ideally this would match regardless of how you imported the parent class
# but these are different classes:
# from ajax_select.lookup_channel import LookupChannel
# from ajax_select import LookupChannel
elif isinstance(lookup_spec, dict):
# 'channel' : dict(model='app.model', search_field='title' )
# generate a simple channel dynamically
return self.make_channel(lookup_spec['model'], lookup_spec['search_field'])
elif isinstance(lookup_spec, tuple):
# a tuple
# 'channel' : ('app.module','LookupClass')
# from app.module load LookupClass and instantiate
lookup_module = __import__(lookup_spec[0], {}, {}, [''])
lookup_class = getattr(lookup_module, lookup_spec[1])
return lookup_class()
else:
raise Exception("Invalid lookup spec: %s" % lookup_spec)
def is_registered(self, channel):
return channel in self._registry
def make_channel(self, app_model, arg_search_field):
"""Automatically make a LookupChannel.
Args:
app_model (str): app_name.ModelName
arg_search_field (str): the field to search against and to display in search results
Returns:
LookupChannel
"""
from ajax_select import LookupChannel
app_label, model_name = app_model.split(".")
class MadeLookupChannel(LookupChannel):
model = get_model(app_label, model_name)
search_field = arg_search_field
return MadeLookupChannel()
registry = LookupChannelRegistry()
def get_model(app_label, model_name):
"""Loads the model given an 'app_label' 'ModelName'"""
try:
# django >= 1.7
from django.apps import apps
except ImportError:
# django < 1.7
from django.db import models
return models.get_model(app_label, model_name)
else:
return apps.get_model(app_label, model_name)
def can_autodiscover():
try:
from django.apps import AppConfig # noqa
except ImportError:
return False
return True
def register(channel):
"""Decorator to register a LookupClass.
Example::
from ajax_select import LookupChannel, register
@register('agent')
class AgentLookup(LookupClass):
def get_query(self):
...
def format_item(self):
...
"""
def _wrapper(lookup_class):
if not channel:
raise ValueError('Lookup Channel must have a channel name')
registry.register({channel: lookup_class})
return lookup_class
return _wrapper
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/ajax_select/registry.py | registry.py |
from django.contrib import admin
from ajax_select.fields import autoselect_fields_check_can_add
class AjaxSelectAdmin(admin.ModelAdmin):
""" in order to get + popup functions subclass this or do the same hook inside of your get_form """
def get_form(self, request, obj=None, **kwargs):
form = super(AjaxSelectAdmin, self).get_form(request, obj, **kwargs)
autoselect_fields_check_can_add(form, self.model, request.user)
return form
class AjaxSelectAdminInlineFormsetMixin(object):
def get_formset(self, request, obj=None, **kwargs):
fs = super(AjaxSelectAdminInlineFormsetMixin, self).get_formset(request, obj, **kwargs)
autoselect_fields_check_can_add(fs.form, self.model, request.user)
return fs
class AjaxSelectAdminTabularInline(AjaxSelectAdminInlineFormsetMixin, admin.TabularInline):
pass
class AjaxSelectAdminStackedInline(AjaxSelectAdminInlineFormsetMixin, admin.StackedInline):
pass
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/ajax_select/admin.py | admin.py |
import json
from django.http import HttpResponse
from django.utils.encoding import force_text
from ajax_select import registry
def ajax_lookup(request, channel):
"""Load the named lookup channel and lookup matching models.
GET or POST should contain 'term'
Returns:
HttpResponse - JSON: `[{pk: value: match: repr:}, ...]`
Raises:
PermissionDenied - depending on the LookupChannel's implementation of check_auth
"""
# it should come in as GET unless global $.ajaxSetup({type:"POST"}) has been set
# in which case we'll support POST
if request.method == "GET":
# we could also insist on an ajax request
if 'term' not in request.GET:
return HttpResponse('')
query = request.GET['term']
else:
if 'term' not in request.POST:
return HttpResponse('') # suspicious
query = request.POST['term']
lookup = registry.get(channel)
if hasattr(lookup, 'check_auth'):
lookup.check_auth(request)
if len(query) >= getattr(lookup, 'min_length', 1):
instances = lookup.get_query(query, request)
else:
instances = []
results = json.dumps([
{
'pk': force_text(getattr(item, 'pk', None)),
'value': lookup.get_result(item),
'match': lookup.format_match(item),
'repr': lookup.format_item_display(item)
} for item in instances
])
response = HttpResponse(results, content_type='application/json')
response['Cache-Control'] = 'max-age=0, must-revalidate, no-store, no-cache;'
return response
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/ajax_select/views.py | views.py |
from django.db.models.fields.related import ForeignKey, ManyToManyField
from django.forms.models import ModelForm
from django.utils.text import capfirst
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
def make_ajax_form(model, fieldlist, superclass=ModelForm, show_help_text=False, **kwargs):
"""Creates a ModelForm subclass with AutoComplete fields.
Args:
model (type): Model class for which you are making the ModelForm
fieldlist (dict): {field_name -> channel_name, ...}
superclass (type): optional ModelForm superclass
show_help_text (bool): suppress or show the widget help text
Returns:
ModelForm: a ModelForm suitable for use in an Admin
Usage::
from django.contrib import admin
from ajax_select import make_ajax_form
from yourapp.models import YourModel
@admin.register(YourModel)
class YourModelAdmin(Admin):
form = make_ajax_form(YourModel, {
'contacts': 'contact', # ManyToManyField
'author':'contact' # ForeignKeyField
})
Where 'contacts' is a ManyToManyField specifying to use the lookup channel 'contact'
and 'author' is a ForeignKeyField specifying here to also use the same lookup channel 'contact'
"""
# will support previous arg name for several versions before deprecating
# TODO: time to go
if 'show_m2m_help' in kwargs:
show_help_text = kwargs.pop('show_m2m_help')
class TheForm(superclass):
class Meta:
exclude = []
setattr(Meta, 'model', model)
if hasattr(superclass, 'Meta'):
if hasattr(superclass.Meta, 'fields'):
setattr(Meta, 'fields', superclass.Meta.fields)
if hasattr(superclass.Meta, 'exclude'):
setattr(Meta, 'exclude', superclass.Meta.exclude)
if hasattr(superclass.Meta, 'widgets'):
setattr(Meta, 'widgets', superclass.Meta.widgets)
for model_fieldname, channel in fieldlist.items():
f = make_ajax_field(model, model_fieldname, channel, show_help_text)
TheForm.declared_fields[model_fieldname] = f
TheForm.base_fields[model_fieldname] = f
return TheForm
def make_ajax_field(related_model, fieldname_on_model, channel, show_help_text=False, **kwargs):
"""Makes an AutoComplete field for use in a Form.
Args:
related_model (Model): model of the related object
fieldname_on_model (str): field name on the model being edited
channel (str): channel name of a registered LookupChannel
show_help_text (bool): show or supress help text below the widget
Django admin will show help text below the widget, but not for ManyToMany inside of admin inlines
This setting will show the help text inside the widget itself.
kwargs: optional args
- help_text: default is the model db field's help_text.
None will disable all help text
- label: default is the model db field's verbose name
- required: default is the model db field's (not) blank
Returns:
(AutoCompleteField, AutoCompleteSelectField, AutoCompleteSelectMultipleField): field
"""
from ajax_select.fields import AutoCompleteField, \
AutoCompleteSelectMultipleField, \
AutoCompleteSelectField
field = related_model._meta.get_field(fieldname_on_model)
if 'label' not in kwargs:
kwargs['label'] = _(capfirst(force_text(field.verbose_name)))
if ('help_text' not in kwargs) and field.help_text:
kwargs['help_text'] = field.help_text
if 'required' not in kwargs:
kwargs['required'] = not field.blank
kwargs['show_help_text'] = show_help_text
if isinstance(field, ManyToManyField):
f = AutoCompleteSelectMultipleField(
channel,
**kwargs)
elif isinstance(field, ForeignKey):
f = AutoCompleteSelectField(
channel,
**kwargs)
else:
f = AutoCompleteField(
channel,
**kwargs)
return f
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/ajax_select/helpers.py | helpers.py |
"""JQuery-Ajax Autocomplete fields for Django Forms."""
__version__ = "1.5.2"
__author__ = "crucialfelix"
__contact__ = "crucialfelix@gmail.com"
__homepage__ = "https://github.com/crucialfelix/django-ajax-selects/"
from ajax_select.registry import registry, register # noqa
from ajax_select.helpers import make_ajax_form, make_ajax_field # noqa
from ajax_select.lookup_channel import LookupChannel # noqa
try:
# django 1.7+ will use the new AppConfig api
# It will load all your lookups.py modules
# and any specified in settings.AJAX_LOOKUP_CHANNELS
# It will do this after all apps are imported.
from django.apps import AppConfig # noqa
default_app_config = 'ajax_select.apps.AjaxSelectConfig'
except ImportError:
# Previous django versions should load now
# using settings.AJAX_LOOKUP_CHANNELS
registry.load_channels()
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/ajax_select/__init__.py | __init__.py |
"""
Blank file so that Django recognizes the app.
This is only required for Django < 1.7
"""
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/ajax_select/models.py | models.py |
from __future__ import unicode_literals
import json
from ajax_select.registry import registry
from django import forms
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.db.models.query import QuerySet
try:
from django.forms.utils import flatatt
except ImportError:
# < django 1.7
from django.forms.util import flatatt
from django.template.loader import render_to_string
from django.template.defaultfilters import force_escape
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe
from django.utils.six import text_type
from django.utils.translation import ugettext as _
as_default_help = 'Enter text to search.'
def _media(self):
# unless AJAX_SELECT_BOOTSTRAP == False
# then load jquery and jquery ui + default css
# where needed
js = ('ajax_select/js/bootstrap.js', 'ajax_select/js/ajax_select.js')
try:
if not settings.AJAX_SELECT_BOOTSTRAP:
js = ('ajax_select/js/ajax_select.js',)
except AttributeError:
pass
return forms.Media(css={'all': ('ajax_select/css/ajax_select.css',)}, js=js)
####################################################################################
class AutoCompleteSelectWidget(forms.widgets.TextInput):
"""Widget to search for a model and return it as text for use in a CharField."""
media = property(_media)
add_link = None
def __init__(self,
channel,
help_text='',
show_help_text=True,
plugin_options=None,
*args,
**kwargs):
self.plugin_options = plugin_options or {}
super(forms.widgets.TextInput, self).__init__(*args, **kwargs)
self.channel = channel
self.help_text = help_text
self.show_help_text = show_help_text
def render(self, name, value, attrs=None):
value = value or ''
# Always ignore required attribute when rendering HTML fields
attrs.pop('required', None)
final_attrs = self.build_attrs(attrs)
self.html_id = final_attrs.pop('id', name)
current_repr = ''
initial = None
lookup = registry.get(self.channel)
if value:
objs = lookup.get_objects([value])
try:
obj = objs[0]
except IndexError:
raise Exception("%s cannot find object:%s" % (lookup, value))
current_repr = lookup.format_item_display(obj)
initial = [current_repr, obj.pk]
if self.show_help_text:
help_text = self.help_text
else:
help_text = ''
context = {
'name': name,
'html_id': self.html_id,
'current_id': value,
'current_repr': current_repr,
'help_text': help_text,
'extra_attrs': mark_safe(flatatt(final_attrs)),
'func_slug': self.html_id.replace("-", ""),
'add_link': self.add_link,
}
context.update(make_plugin_options(lookup, self.channel, self.plugin_options, initial))
templates = (
'ajax_select/autocompleteselect_%s.html' % self.channel,
'ajax_select/autocompleteselect.html')
out = render_to_string(templates, context)
return mark_safe(out)
def value_from_datadict(self, data, files, name):
return data.get(name, None)
def id_for_label(self, id_):
return '%s_text' % id_
class AutoCompleteSelectField(forms.fields.CharField):
"""Form field to select a Model for a ForeignKey db field."""
channel = None
def __init__(self, channel, *args, **kwargs):
self.channel = channel
widget_kwargs = dict(
channel=channel,
help_text=kwargs.get('help_text', _(as_default_help)),
show_help_text=kwargs.pop('show_help_text', True),
plugin_options=kwargs.pop('plugin_options', {})
)
widget_kwargs.update(kwargs.pop('widget_options', {}))
kwargs["widget"] = AutoCompleteSelectWidget(**widget_kwargs)
super(AutoCompleteSelectField, self).__init__(max_length=255, *args, **kwargs)
def clean(self, value):
if value:
lookup = registry.get(self.channel)
objs = lookup.get_objects([value])
if len(objs) != 1:
# someone else might have deleted it while you were editing
# or your channel is faulty
# out of the scope of this field to do anything more than tell you it doesn't exist
raise forms.ValidationError("%s cannot find object: %s" % (lookup, value))
return objs[0]
else:
if self.required:
raise forms.ValidationError(self.error_messages['required'])
return None
def check_can_add(self, user, model):
_check_can_add(self, user, model)
def has_changed(self, initial, data):
# 1 vs u'1'
initial_value = initial if initial is not None else ''
data_value = data if data is not None else ''
return text_type(initial_value) != text_type(data_value)
####################################################################################
class AutoCompleteSelectMultipleWidget(forms.widgets.SelectMultiple):
"""Widget to select multiple models for a ManyToMany db field."""
media = property(_media)
add_link = None
def __init__(self,
channel,
help_text='',
show_help_text=True,
plugin_options=None,
*args,
**kwargs):
super(AutoCompleteSelectMultipleWidget, self).__init__(*args, **kwargs)
self.channel = channel
self.help_text = help_text
self.show_help_text = show_help_text
self.plugin_options = plugin_options or {}
def render(self, name, value, attrs=None):
if value is None:
value = []
final_attrs = self.build_attrs(attrs)
self.html_id = final_attrs.pop('id', name)
lookup = registry.get(self.channel)
if isinstance(value, QuerySet):
objects = value
else:
objects = lookup.get_objects(value)
current_ids = pack_ids([obj.pk for obj in objects])
# text repr of currently selected items
initial = [
[lookup.format_item_display(obj), obj.pk]
for obj in objects
]
if self.show_help_text:
help_text = self.help_text
else:
help_text = ''
context = {
'name': name,
'html_id': self.html_id,
'current': value,
'current_ids': current_ids,
'current_reprs': mark_safe(json.dumps(initial)),
'help_text': help_text,
'extra_attrs': mark_safe(flatatt(final_attrs)),
'func_slug': self.html_id.replace("-", ""),
'add_link': self.add_link,
}
context.update(make_plugin_options(lookup, self.channel, self.plugin_options, initial))
templates = ('ajax_select/autocompleteselectmultiple_%s.html' % self.channel,
'ajax_select/autocompleteselectmultiple.html')
out = render_to_string(templates, context)
return mark_safe(out)
def value_from_datadict(self, data, files, name):
# eg. 'members': ['|229|4688|190|']
return [val for val in data.get(name, '').split('|') if val]
def id_for_label(self, id_):
return '%s_text' % id_
class AutoCompleteSelectMultipleField(forms.fields.CharField):
""" form field to select multiple models for a ManyToMany db field """
channel = None
def __init__(self, channel, *args, **kwargs):
self.channel = channel
help_text = kwargs.get('help_text')
show_help_text = kwargs.pop('show_help_text', False)
if not (help_text is None):
# '' will cause translation to fail
# should be ''
if isinstance(help_text, str):
help_text = force_text(help_text)
# django admin appends "Hold down "Control",..." to the help text
# regardless of which widget is used. so even when you specify an explicit
# help text it appends this other default text onto the end.
# This monkey patches the help text to remove that
if help_text != '':
if not isinstance(help_text, text_type):
# ideally this could check request.LANGUAGE_CODE
translated = help_text.translate(settings.LANGUAGE_CODE)
else:
translated = help_text
dh = 'Hold down "Control", or "Command" on a Mac, to select more than one.'
django_default_help = _(dh).translate(settings.LANGUAGE_CODE)
if django_default_help in translated:
cleaned_help = translated.replace(django_default_help, '').strip()
# probably will not show up in translations
if cleaned_help:
help_text = cleaned_help
else:
help_text = ""
show_help_text = False
else:
help_text = _(as_default_help)
# django admin will also show help text outside of the display
# area of the widget. this results in duplicated help.
# it should just let the widget do the rendering
# so by default do not show it in widget
# if using in a normal form then set to True when creating the field
widget_kwargs = {
'channel': channel,
'help_text': help_text,
'show_help_text': show_help_text,
'plugin_options': kwargs.pop('plugin_options', {})
}
widget_kwargs.update(kwargs.pop('widget_options', {}))
kwargs['widget'] = AutoCompleteSelectMultipleWidget(**widget_kwargs)
kwargs['help_text'] = help_text
super(AutoCompleteSelectMultipleField, self).__init__(*args, **kwargs)
def clean(self, value):
if not value and self.required:
raise forms.ValidationError(self.error_messages['required'])
return value # a list of primary keys from widget value_from_datadict
def check_can_add(self, user, model):
_check_can_add(self, user, model)
def has_changed(self, initial_value, data_value):
# [1, 2] vs [u'1', u'2']
ivs = [text_type(v) for v in (initial_value or [])]
dvs = [text_type(v) for v in (data_value or [])]
return ivs != dvs
####################################################################################
class AutoCompleteWidget(forms.TextInput):
"""
Widget to select a search result and enter the result as raw text in the text input field.
the user may also simply enter text and ignore any auto complete suggestions.
"""
media = property(_media)
channel = None
help_text = ''
html_id = ''
def __init__(self, channel, *args, **kwargs):
self.channel = channel
self.help_text = kwargs.pop('help_text', '')
self.show_help_text = kwargs.pop('show_help_text', True)
self.plugin_options = kwargs.pop('plugin_options', {})
super(AutoCompleteWidget, self).__init__(*args, **kwargs)
def render(self, name, value, attrs=None):
initial = value or ''
final_attrs = self.build_attrs(attrs)
self.html_id = final_attrs.pop('id', name)
lookup = registry.get(self.channel)
if self.show_help_text:
help_text = self.help_text
else:
help_text = ''
context = {
'current_repr': initial,
'current_id': initial,
'help_text': help_text,
'html_id': self.html_id,
'name': name,
'extra_attrs': mark_safe(flatatt(final_attrs)),
'func_slug': self.html_id.replace("-", ""),
}
context.update(make_plugin_options(lookup, self.channel, self.plugin_options, initial))
templates = ('ajax_select/autocomplete_%s.html' % self.channel,
'ajax_select/autocomplete.html')
return mark_safe(render_to_string(templates, context))
class AutoCompleteField(forms.CharField):
"""
A CharField that uses an AutoCompleteWidget to lookup matching and stores the result as plain text.
"""
channel = None
def __init__(self, channel, *args, **kwargs):
self.channel = channel
widget_kwargs = dict(
help_text=kwargs.get('help_text', _(as_default_help)),
show_help_text=kwargs.pop('show_help_text', True),
plugin_options=kwargs.pop('plugin_options', {})
)
widget_kwargs.update(kwargs.pop('widget_options', {}))
if 'attrs' in kwargs:
widget_kwargs['attrs'] = kwargs.pop('attrs')
widget = AutoCompleteWidget(channel, **widget_kwargs)
defaults = {'max_length': 255, 'widget': widget}
defaults.update(kwargs)
super(AutoCompleteField, self).__init__(*args, **defaults)
####################################################################################
def _check_can_add(self, user, related_model):
"""
Check if the User can create a related_model.
If the LookupChannel implements check_can_add() then use this.
Else uses Django's default permission system.
If it can add, then enable the widget to show the green + link
"""
lookup = registry.get(self.channel)
if hasattr(lookup, 'can_add'):
can_add = lookup.can_add(user, related_model)
else:
ctype = ContentType.objects.get_for_model(related_model)
can_add = user.has_perm("%s.add_%s" % (ctype.app_label, ctype.model))
if can_add:
app_label = related_model._meta.app_label
model = related_model._meta.object_name.lower()
self.widget.add_link = reverse('admin:%s_%s_add' % (app_label, model)) + '?_popup=1'
def autoselect_fields_check_can_add(form, model, user):
"""
Check the form's fields for any autoselect fields and enable their
widgets with green + button if permissions allow then to create the related_model.
"""
for name, form_field in form.declared_fields.items():
if isinstance(form_field, (AutoCompleteSelectMultipleField, AutoCompleteSelectField)):
db_field = model._meta.get_field(name)
form_field.check_can_add(user, db_field.rel.to)
def make_plugin_options(lookup, channel_name, widget_plugin_options, initial):
""" Make a JSON dumped dict of all options for the jQuery ui plugin."""
po = {}
if initial:
po['initial'] = initial
po.update(getattr(lookup, 'plugin_options', {}))
po.update(widget_plugin_options)
if not po.get('source'):
po['source'] = reverse('ajax_lookup', kwargs={'channel': channel_name})
# allow html unless explicitly set
if po.get('html') is None:
po['html'] = True
return {
'plugin_options': mark_safe(json.dumps(po)),
'data_plugin_options': force_escape(json.dumps(po))
}
def pack_ids(ids):
if ids:
# |pk|pk| of current
return "|" + "|".join(str(pk) for pk in ids) + "|"
else:
return "|"
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/ajax_select/fields.py | fields.py |
(function() {
var $ = window.jQuery;
$.fn.autocompleteselect = function(options) {
return this.each(function() {
var id = this.id,
$this = $(this),
$text = $('#' + id + '_text'),
$deck = $('#' + id + '_on_deck');
function receiveResult(event, ui) {
if ($this.val()) {
kill();
}
$this.val(ui.item.pk);
$text.val('');
addKiller(ui.item.repr, ui.item.pk);
$deck.trigger('added', [ui.item.pk, ui.item]);
$this.trigger('change');
return false;
}
function addKiller(repr, pk) {
var killId = 'kill_' + pk + id,
killButton = '<span class="ui-icon ui-icon-trash" id="' + killId + '">X</span> ';
if (repr) {
$deck.empty();
$deck.append('<div>' + killButton + repr + '</div>');
} else {
$('#' + id + '_on_deck > div').prepend(killButton);
}
$('#' + killId).click(function() {
kill();
$deck.trigger('killed', [pk]);
});
}
function kill() {
$this.val('');
$deck.children().fadeOut(1.0).remove();
}
options.select = receiveResult;
$text.autocomplete(options);
function reset() {
if (options.initial) {
addKiller(options.initial[0], options.initial[1]);
$this.val(options.initial[1]);
} else {
kill();
}
}
if (!$this.attr('data-changed')) {
reset();
$this.attr('data-changed', true);
}
$this.closest('form').on('reset', reset);
$this.bind('didAddPopup', function(event, pk, repr) {
receiveResult(null, {item: {pk: pk, repr: repr}});
});
});
};
$.fn.autocompleteselectmultiple = function(options) {
return this.each(function() {
var id = this.id,
$this = $(this),
$text = $('#' + id + '_text'),
$deck = $('#' + id + '_on_deck');
function receiveResult(event, ui) {
var pk = ui.item.pk,
prev = $this.val();
if (prev.indexOf('|' + pk + '|') === -1) {
$this.val((prev ? prev : '|') + pk + '|');
addKiller(ui.item.repr, pk);
$text.val('');
$deck.trigger('added', [ui.item.pk, ui.item]);
$this.trigger('change');
}
return false;
}
function addKiller(repr, pk) {
var killId = 'kill_' + pk + id,
killButton = '<span class="ui-icon ui-icon-trash" id="' + killId + '">X</span> ';
$deck.append('<div id="' + id + '_on_deck_' + pk + '">' + killButton + repr + ' </div>');
$('#' + killId).click(function() {
kill(pk);
$deck.trigger('killed', [pk]);
});
}
function kill(pk) {
$this.val($this.val().replace('|' + pk + '|', '|'));
$('#' + id + '_on_deck_' + pk).fadeOut().remove();
}
options.select = receiveResult;
$text.autocomplete(options);
function reset() {
$deck.empty();
var query = '|';
if (options.initial) {
$.each(options.initial, function(i, its) {
addKiller(its[0], its[1]);
query += its[1] + '|';
});
}
$this.val(query);
}
if (!$this.attr('data-changed')) {
reset();
$this.attr('data-changed', true);
}
$this.closest('form').on('reset', reset);
$this.bind('didAddPopup', function(event, pk, repr) {
receiveResult(null, {item: {pk: pk, repr: repr}});
});
});
};
function addAutoComplete (inp, callback) {
var $inp = $(inp),
opts = JSON.parse($inp.attr('data-plugin-options'));
// Do not activate empty-form inline rows.
// These are cloned into the form when adding another row and will be activated at that time.
if ($inp.attr('id').indexOf('__prefix__') !== -1) {
// console.log('skipping __prefix__ row', $inp);
return;
}
if ($inp.data('_ajax_select_inited_')) {
// console.log('skipping already activated row', $inp);
return;
}
// console.log('activating', $inp);
callback($inp, opts);
$inp.data('_ajax_select_inited_', true);
}
// allow html in the results menu
// https://github.com/scottgonzalez/jquery-ui-extensions
var proto = $.ui.autocomplete.prototype,
initSource = proto._initSource;
function filter(array, term) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(term), 'i');
return $.grep(array, function(value) {
return matcher.test($('<div>').html(value.label || value.value || value).text());
});
}
$.extend(proto, {
_initSource: function() {
if (this.options.html && $.isArray(this.options.source)) {
this.source = function(request, response) {
response(filter(this.options.source, request.term));
};
} else {
initSource.call(this);
}
},
_renderItem: function(ul, item) {
var body = this.options.html ? item.match: item.label;
return $('<li></li>')
.data('item.autocomplete', item)
.append($('<a></a>')[this.options.html ? 'html' : 'text' ](body))
.appendTo(ul);
}
});
/* Called by the popup create object when it closes.
* For the popup this is opener.dismissAddRelatedObjectPopup
* Django implements this in RelatedObjectLookups.js
* In django >= 1.10 we can rely on input.trigger('change')
* and avoid this hijacking.
*/
var djangoDismissAddRelatedObjectPopup = window.dismissAddRelatedObjectPopup || window.dismissAddAnotherPopup;
window.dismissAddRelatedObjectPopup = function(win, newId, newRepr) {
// Iff this is an ajax-select input then close the window and
// trigger didAddPopup
var name = window.windowname_to_id(win.name);
var input = $('#' + name);
if (input.data('ajax-select')) {
win.close();
// newRepr is django's repr of object
// not the Lookup's formatting of it.
input.trigger('didAddPopup', [newId, newRepr]);
} else {
// Call the normal django set and close function.
djangoDismissAddRelatedObjectPopup(win, newId, newRepr);
}
}
// Django renamed this function in 1.8
window.dismissAddAnotherPopup = window.dismissAddRelatedObjectPopup;
// activate any on page
$(window).bind('init-autocomplete', function() {
$('input[data-ajax-select=autocomplete]').each(function(i, inp) {
addAutoComplete(inp, function($inp, opts) {
opts.select =
function(event, ui) {
$inp.val(ui.item.value).trigger('added', [ui.item.pk, ui.item]);
return false;
};
$inp.autocomplete(opts);
});
});
$('input[data-ajax-select=autocompleteselect]').each(function(i, inp) {
addAutoComplete(inp, function($inp, opts) {
$inp.autocompleteselect(opts);
});
});
$('input[data-ajax-select=autocompleteselectmultiple]').each(function(i, inp) {
addAutoComplete(inp, function($inp, opts) {
$inp.autocompleteselectmultiple(opts);
});
});
});
$(document).ready(function() {
// if dynamically injecting forms onto a page
// you can trigger them to be ajax-selects-ified:
$(window).trigger('init-autocomplete');
// When adding new rows in inline forms, reinitialize and activate newly added rows.
$(document)
.on('click', '.inline-group ul.tools a.add, .inline-group div.add-row a, .inline-group .tabular tr.add-row td a', function() {
$(window).trigger('init-autocomplete');
});
});
})();
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/ajax_select/static/ajax_select/js/ajax_select.js | ajax_select.js |
(function(w) {
/**
* load jquery and jquery-ui if needed
*/
function not(thing) {
return typeof thing === 'undefined';
}
function loadJS(src) {
document.write('<script type="text/javascript" src="' + src + '"><\/script>');
}
function loadCSS(href) {
var script = document.createElement('link');
script.href = href;
script.type = 'text/css';
script.rel = 'stylesheet';
document.head.appendChild(script);
}
if (not(w.jQuery)) {
loadJS('//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js');
}
if (not(w.jQuery) || not(w.jQuery.ui) || not(w.jQuery.ui.autocomplete)) {
loadJS('//code.jquery.com/ui/1.10.3/jquery-ui.js');
loadCSS('//code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css');
}
})(window);
| 15five-django-ajax-selects | /15five-django-ajax-selects-1.5.2.155.tar.gz/15five-django-ajax-selects-1.5.2.155/ajax_select/static/ajax_select/js/bootstrap.js | bootstrap.js |
======================================================
Python Analytics for Snowplow
======================================================
.. image:: https://travis-ci.org/snowplow/snowplow-python-tracker.png?branch=master
:alt: Build Status
:target: https://travis-ci.org/snowplow/snowplow-python-tracker
.. image:: https://badge.fury.io/py/snowplow-tracker.png
:target: http://badge.fury.io/py/snowplow-tracker
.. image:: https://coveralls.io/repos/snowplow/snowplow-python-tracker/badge.png
:target: https://coveralls.io/r/snowplow/snowplow-python-tracker
.. image:: http://img.shields.io/badge/license-Apache--2-blue.svg?style=flat
:target: http://www.apache.org/licenses/LICENSE-2.0
Overview
########
Add analytics to your Python apps and Python games with the Snowplow_ event tracker for Python_.
.. _Snowplow: http://snowplowanalytics.com
.. _Python: http://python.org
With this tracker you can collect event data from your Python-based applications, games or Python web servers/frameworks.
Find out more
#############
+---------------------------------+---------------------------+-------------------------+-----------------------------------+
| Technical Docs | Setup Guide | Roadmap | Contributing |
+=================================+===========================+=========================+===================================+
| |techdocs|_ | |setup|_ | |roadmap| | |contributing| |
+---------------------------------+---------------------------+-------------------------+-----------------------------------+
| `Technical Docs`_ | `Setup Guide`_ | `Roadmap`_ | `Contributing`_ |
+---------------------------------+---------------------------+-------------------------+-----------------------------------+
.. |techdocs| image:: https://d3i6fms1cm1j0i.cloudfront.net/github/images/techdocs.png
.. |setup| image:: https://d3i6fms1cm1j0i.cloudfront.net/github/images/setup.png
.. |roadmap| image:: https://d3i6fms1cm1j0i.cloudfront.net/github/images/roadmap.png
.. |contributing| image:: https://d3i6fms1cm1j0i.cloudfront.net/github/images/contributing.png
.. _techdocs: https://github.com/snowplow/snowplow/wiki/Python-Tracker
.. _setup: https://github.com/snowplow/snowplow/wiki/Python-Tracker-Setup
.. _`Technical Docs`: https://github.com/snowplow/snowplow/wiki/Python-Tracker
.. _`Setup Guide`: https://github.com/snowplow/snowplow/wiki/Python-Tracker-Setup
.. _`Roadmap`: https://github.com/snowplow/snowplow/wiki/Python-Tracker-Roadmap
.. _`Contributing`: https://github.com/snowplow/snowplow/wiki/Python-Tracker-Contributing
Contributing quickstart
#######################
Assuming Git, Vagrant_ and VirtualBox_ are installed:
::
host$ git clone git@github.com:snowplow/snowplow-python-tracker.git
host$ vagrant up && vagrant ssh
guest$ cd /vagrant
guest$ ./run-tests.sh deploy
guest$ ./run-tests.sh test
.. _Vagrant: http://docs.vagrantup.com/v2/installation/index.html
.. _VirtualBox: https://www.virtualbox.org/wiki/Downloads
Publishing
##########
::
host$ vagrant push
Copyright and license
#####################
The Snowplow Python Tracker is copyright 2013-2014 Snowplow Analytics Ltd.
Licensed under the `Apache License, Version 2.0`_ (the "License");
you may not use this software except in compliance with the License.
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.
.. _Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
| 15five-snowplow-tracker | /15five-snowplow-tracker-0.8.156.tar.gz/15five-snowplow-tracker-0.8.156/README.rst | README.rst |
"""
setup.py
Copyright (c) 2013-2014 Snowplow Analytics Ltd. All rights reserved.
This program is licensed to you under the Apache License Version 2.0,
and you may not use this file except in compliance with the Apache License
Version 2.0. You may obtain a copy of the Apache License Version 2.0 at
http://www.apache.org/licenses/LICENSE-2.0.
Unless required by applicable law or agreed to in writing,
software distributed under the Apache License Version 2.0 is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the Apache License Version 2.0 for the specific
language governing permissions and limitations there under.
Authors: Anuj More, Alex Dean, Fred Blundun
Copyright: Copyright (c) 2013-2014 Snowplow Analytics Ltd
License: Apache License Version 2.0
!!!MODIFIED BY 15FIVE!!!
Modifiers: Andrii Pleskach, Paul Logston
"""
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import os
version_file_path = os.path.join(
os.path.dirname(__file__),
'snowplow_tracker',
'_version.py'
)
exec(open(version_file_path).read(), {}, locals())
authors_list = [
'Anuj More',
'Alexander Dean',
'Fred Blundun'
]
authors_str = ', '.join(authors_list)
authors_email_list = [
'support@snowplowanalytics.com',
]
authors_email_str = ', '.join(authors_email_list)
setup(
name='15five-snowplow-tracker',
version='0.8.156',
author=authors_str,
author_email=authors_email_str,
packages=['snowplow_tracker', 'snowplow_tracker.test'],
url='http://snowplowanalytics.com',
license='Apache License 2.0',
description='Snowplow event tracker for Python. Add analytics to your Python and Django apps, webapps and games',
long_description=open('README.rst').read(),
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Operating System :: OS Independent",
],
install_requires=[
"greenlet>=0.4.15",
"requests>=2.19.1",
"pycontracts>=1.7.6",
"celery>=4.2.0",
"gevent>=1.3.3",
"redis>=2.10.6",
"six>=1.11.0"
],
)
| 15five-snowplow-tracker | /15five-snowplow-tracker-0.8.156.tar.gz/15five-snowplow-tracker-0.8.156/setup.py | setup.py |
"""
tracker.py
Copyright (c) 2013-2014 Snowplow Analytics Ltd. All rights reserved.
This program is licensed to you under the Apache License Version 2.0,
and you may not use this file except in compliance with the Apache License
Version 2.0. You may obtain a copy of the Apache License Version 2.0 at
http://www.apache.org/licenses/LICENSE-2.0.
Unless required by applicable law or agreed to in writing,
software distributed under the Apache License Version 2.0 is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the Apache License Version 2.0 for the specific
language governing permissions and limitations there under.
Authors: Anuj More, Alex Dean, Fred Blundun
Copyright: Copyright (c) 2013-2014 Snowplow Analytics Ltd
License: Apache License Version 2.0
!!!MODIFIED BY 15FIVE!!!
Modifiers: Andrii Pleskach, Paul Logston
"""
import time
import uuid
import six
from contracts import contract, new_contract
from snowplow_tracker import payload, _version, SelfDescribingJson
from snowplow_tracker import subject as _subject
from snowplow_tracker.timestamp import Timestamp, TrueTimestamp, DeviceTimestamp
"""
Constants & config
"""
VERSION = "py-%s" % _version.__version__
DEFAULT_ENCODE_BASE64 = True
BASE_SCHEMA_PATH = "iglu:com.snowplowanalytics.snowplow"
SCHEMA_TAG = "jsonschema"
CONTEXT_SCHEMA = "%s/contexts/%s/1-0-1" % (BASE_SCHEMA_PATH, SCHEMA_TAG)
UNSTRUCT_EVENT_SCHEMA = "%s/unstruct_event/%s/1-0-0" % (BASE_SCHEMA_PATH, SCHEMA_TAG)
FORM_NODE_NAMES = ("INPUT", "TEXTAREA", "SELECT")
FORM_TYPES = (
"button", "checkbox", "color", "date", "datetime",
"datetime-local", "email", "file", "hidden", "image", "month",
"number", "password", "radio", "range", "reset", "search",
"submit", "tel", "text", "time", "url", "week"
)
"""
Tracker class
"""
class Tracker:
new_contract("not_none", lambda s: s is not None)
new_contract("non_empty_string", lambda s: isinstance(s, six.string_types)
and len(s) > 0)
new_contract("string_or_none", lambda s: (isinstance(s, six.string_types)
and len(s) > 0) or s is None)
new_contract("payload", lambda s: isinstance(s, payload.Payload))
new_contract("tracker", lambda s: isinstance(s, Tracker))
new_contract("emitter", lambda s: hasattr(s, "input"))
new_contract("self_describing_json", lambda s: isinstance(s, SelfDescribingJson))
new_contract("context_array", "list(self_describing_json)")
new_contract("form_node_name", lambda s: s in FORM_NODE_NAMES)
new_contract("form_type", lambda s: s.lower() in FORM_TYPES)
new_contract("timestamp", lambda x: (isinstance(x, Timestamp)))
new_contract("form_element", lambda x: Tracker.check_form_element(x))
@contract
def __init__(self, emitters, subject=None,
namespace=None, app_id=None, encode_base64=DEFAULT_ENCODE_BASE64):
"""
:param emitters: Emitters to which events will be sent
:type emitters: list[>0](emitter) | emitter
:param subject: Subject to be tracked
:type subject: subject | None
:param namespace: Identifier for the Tracker instance
:type namespace: string_or_none
:param app_id: Application ID
:type app_id: string_or_none
:param encode_base64: Whether JSONs in the payload should be base-64 encoded
:type encode_base64: bool
"""
if subject is None:
subject = _subject.Subject()
if type(emitters) is list:
self.emitters = emitters
else:
self.emitters = [emitters]
self.subject = subject
self.encode_base64 = encode_base64
self.standard_nv_pairs = {
"tv": VERSION,
"tna": namespace,
"aid": app_id
}
self.timer = None
@staticmethod
@contract
def get_uuid():
"""
Set transaction ID for the payload once during the lifetime of the
event.
:rtype: string
"""
return str(uuid.uuid4())
@staticmethod
@contract
def get_timestamp(tstamp=None):
"""
:param tstamp: User-input timestamp or None
:type tstamp: int | float | None
:rtype: int
"""
if tstamp is None:
return int(time.time() * 1000)
elif isinstance(tstamp, (int, float, )):
return int(tstamp)
"""
Tracking methods
"""
@contract
def track(self, pb):
"""
Send the payload to a emitter
:param pb: Payload builder
:type pb: payload
:rtype: tracker
"""
for emitter in self.emitters:
emitter.input(pb.nv_pairs)
return self
@contract
def complete_payload(self, pb, context, tstamp):
"""
Called by all tracking events to add the standard name-value pairs
to the Payload object irrespective of the tracked event.
:param pb: Payload builder
:type pb: payload
:param context: Custom context for the event
:type context: context_array | None
:param tstamp: Optional user-provided timestamp for the event
:type tstamp: timestamp | int | float | None
:rtype: tracker
"""
pb.add("eid", Tracker.get_uuid())
if isinstance(tstamp, TrueTimestamp):
pb.add("ttm", tstamp.value)
if isinstance(tstamp, DeviceTimestamp):
pb.add("dtm", Tracker.get_timestamp(tstamp.value))
elif isinstance(tstamp, (int, float, type(None))):
pb.add("dtm", Tracker.get_timestamp(tstamp))
if context is not None:
context_jsons = list(map(lambda c: c.to_json(), context))
context_envelope = SelfDescribingJson(CONTEXT_SCHEMA, context_jsons).to_json()
pb.add_json(context_envelope, self.encode_base64, "cx", "co")
pb.add_dict(self.standard_nv_pairs)
pb.add_dict(self.subject.standard_nv_pairs)
return self.track(pb)
@contract
def track_page_view(self, page_url, page_title=None, referrer=None, context=None, tstamp=None):
"""
:param page_url: URL of the viewed page
:type page_url: non_empty_string
:param page_title: Title of the viewed page
:type page_title: string_or_none
:param referrer: Referrer of the page
:type referrer: string_or_none
:param context: Custom context for the event
:type context: context_array | None
:param tstamp: Optional user-provided timestamp for the event
:type tstamp: timestamp | int | float | None
:rtype: tracker
"""
pb = payload.Payload()
pb.add("e", "pv") # pv: page view
pb.add("url", page_url)
pb.add("page", page_title)
pb.add("refr", referrer)
return self.complete_payload(pb, context, tstamp)
@contract
def track_page_ping(self, page_url, page_title=None, referrer=None, min_x=None, max_x=None, min_y=None, max_y=None, context=None, tstamp=None):
"""
:param page_url: URL of the viewed page
:type page_url: non_empty_string
:param page_title: Title of the viewed page
:type page_title: string_or_none
:param referrer: Referrer of the page
:type referrer: string_or_none
:param min_x: Minimum page x offset seen in the last ping period
:type min_x: int | None
:param max_x: Maximum page x offset seen in the last ping period
:type max_x: int | None
:param min_y: Minimum page y offset seen in the last ping period
:type min_y: int | None
:param max_y: Maximum page y offset seen in the last ping period
:type max_y: int | None
:param context: Custom context for the event
:type context: context_array | None
:param tstamp: Optional user-provided timestamp for the event
:type tstamp: timestamp | int | float | None
:rtype: tracker
"""
pb = payload.Payload()
pb.add("e", "pp") # pp: page ping
pb.add("url", page_url)
pb.add("page", page_title)
pb.add("refr", referrer)
pb.add("pp_mix", min_x)
pb.add("pp_max", max_x)
pb.add("pp_miy", min_y)
pb.add("pp_may", max_y)
return self.complete_payload(pb, context, tstamp)
@contract
def track_link_click(self, target_url, element_id=None,
element_classes=None, element_target=None,
element_content=None, context=None, tstamp=None):
"""
:param target_url: Target URL of the link
:type target_url: non_empty_string
:param element_id: ID attribute of the HTML element
:type element_id: string_or_none
:param element_classes: Classes of the HTML element
:type element_classes: list(str) | tuple(str,*) | None
:param element_content: The content of the HTML element
:type element_content: string_or_none
:param context: Custom context for the event
:type context: context_array | None
:param tstamp: Optional user-provided timestamp for the event
:type tstamp: timestamp | int | float | None
:rtype: tracker
"""
properties = {}
properties["targetUrl"] = target_url
if element_id is not None:
properties["elementId"] = element_id
if element_classes is not None:
properties["elementClasses"] = element_classes
if element_target is not None:
properties["elementTarget"] = element_target
if element_content is not None:
properties["elementContent"] = element_content
event_json = SelfDescribingJson("%s/link_click/%s/1-0-1" % (BASE_SCHEMA_PATH, SCHEMA_TAG), properties)
return self.track_unstruct_event(event_json, context, tstamp)
@contract
def track_add_to_cart(self, sku, quantity, name=None, category=None,
unit_price=None, currency=None, context=None,
tstamp=None):
"""
:param sku: Item SKU or ID
:type sku: non_empty_string
:param quantity: Number added to cart
:type quantity: int
:param name: Item's name
:type name: string_or_none
:param category: Item's category
:type category: string_or_none
:param unit_price: Item's price
:type unit_price: int | float | None
:param currency: Type of currency the price is in
:type currency: string_or_none
:param context: Custom context for the event
:type context: context_array | None
:param tstamp: Optional user-provided timestamp for the event
:type tstamp: timestamp | int | float | None
:rtype: tracker
"""
properties = {}
properties["sku"] = sku
properties["quantity"] = quantity
if name is not None:
properties["name"] = name
if category is not None:
properties["category"] = category
if unit_price is not None:
properties["unitPrice"] = unit_price
if currency is not None:
properties["currency"] = currency
event_json = SelfDescribingJson("%s/add_to_cart/%s/1-0-0" % (BASE_SCHEMA_PATH, SCHEMA_TAG), properties)
return self.track_unstruct_event(event_json, context, tstamp)
@contract
def track_remove_from_cart(self, sku, quantity, name=None, category=None,
unit_price=None, currency=None, context=None,
tstamp=None):
"""
:param sku: Item SKU or ID
:type sku: non_empty_string
:param quantity: Number added to cart
:type quantity: int
:param name: Item's name
:type name: string_or_none
:param category: Item's category
:type category: string_or_none
:param unit_price: Item's price
:type unit_price: int | float | None
:param currency: Type of currency the price is in
:type currency: string_or_none
:param context: Custom context for the event
:type context: context_array | None
:param tstamp: Optional user-provided timestamp for the event
:type tstamp: timestamp | int | float | None
:rtype: tracker
"""
properties = {}
properties["sku"] = sku
properties["quantity"] = quantity
if name is not None:
properties["name"] = name
if category is not None:
properties["category"] = category
if unit_price is not None:
properties["unitPrice"] = unit_price
if currency is not None:
properties["currency"] = currency
event_json = SelfDescribingJson("%s/remove_from_cart/%s/1-0-0" % (BASE_SCHEMA_PATH, SCHEMA_TAG), properties)
return self.track_unstruct_event(event_json, context, tstamp)
@contract
def track_form_change(self, form_id, element_id, node_name, value, type_=None,
element_classes=None, context=None, tstamp=None):
"""
:param form_id: ID attribute of the HTML form
:type form_id: non_empty_string
:param element_id: ID attribute of the HTML element
:type element_id: string_or_none
:param node_name: Type of input element
:type node_name: form_node_name
:param value: Value of the input element
:type value: string_or_none
:param type_: Type of data the element represents
:type type_: non_empty_string, form_type
:param element_classes: Classes of the HTML element
:type element_classes: list(str) | tuple(str,*) | None
:param context: Custom context for the event
:type context: context_array | None
:param tstamp: Optional user-provided timestamp for the event
:type tstamp: timestamp | int | float | None
:rtype: tracker
"""
properties = dict()
properties["formId"] = form_id
properties["elementId"] = element_id
properties["nodeName"] = node_name
properties["value"] = value
if type_ is not None:
properties["type"] = type_
if element_classes is not None:
properties["elementClasses"] = element_classes
event_json = SelfDescribingJson("%s/change_form/%s/1-0-0" % (BASE_SCHEMA_PATH, SCHEMA_TAG), properties)
return self.track_unstruct_event(event_json, context, tstamp)
@contract
def track_form_submit(self, form_id, form_classes=None, elements=None,
context=None, tstamp=None):
"""
:param form_id: ID attribute of the HTML form
:type form_id: non_empty_string
:param form_classes: Classes of the HTML form
:type form_classes: list(str) | tuple(str,*) | None
:param elements: Classes of the HTML form
:type elements: list(form_element) | None
:param context: Custom context for the event
:type context: context_array | None
:param tstamp: Optional user-provided timestamp for the event
:type tstamp: timestamp | int | float | None
:rtype: tracker
"""
properties = dict()
properties['formId'] = form_id
if form_classes is not None:
properties['formClasses'] = form_classes
if elements is not None and len(elements) > 0:
properties['elements'] = elements
event_json = SelfDescribingJson("%s/submit_form/%s/1-0-0" % (BASE_SCHEMA_PATH, SCHEMA_TAG), properties)
return self.track_unstruct_event(event_json, context, tstamp)
@contract
def track_site_search(self, terms, filters=None, total_results=None,
page_results=None, context=None, tstamp=None):
"""
:param terms: Search terms
:type terms: seq[>=1](str)
:param filters: Filters applied to the search
:type filters: dict(str:str|bool) | None
:param total_results: Total number of results returned
:type total_results: int | None
:param page_results: Total number of pages of results
:type page_results: int | None
:param context: Custom context for the event
:type context: context_array | None
:param tstamp: Optional user-provided timestamp for the event
:type tstamp: timestamp | int | float | None
:rtype: tracker
"""
properties = {}
properties["terms"] = terms
if filters is not None:
properties["filters"] = filters
if total_results is not None:
properties["totalResults"] = total_results
if page_results is not None:
properties["pageResults"] = page_results
event_json = SelfDescribingJson("%s/site_search/%s/1-0-0" % (BASE_SCHEMA_PATH, SCHEMA_TAG), properties)
return self.track_unstruct_event(event_json, context, tstamp)
@contract
def track_ecommerce_transaction_item(self, order_id, sku, price, quantity,
name=None, category=None, currency=None,
context=None,
tstamp=None):
"""
This is an internal method called by track_ecommerce_transaction.
It is not for public use.
:param order_id: Order ID
:type order_id: non_empty_string
:param sku: Item SKU
:type sku: non_empty_string
:param price: Item price
:type price: int | float
:param quantity: Item quantity
:type quantity: int
:param name: Item name
:type name: string_or_none
:param category: Item category
:type category: string_or_none
:param currency: The currency the price is expressed in
:type currency: string_or_none
:param context: Custom context for the event
:type context: context_array | None
:rtype: tracker
"""
pb = payload.Payload()
pb.add("e", "ti")
pb.add("ti_id", order_id)
pb.add("ti_sk", sku)
pb.add("ti_nm", name)
pb.add("ti_ca", category)
pb.add("ti_pr", price)
pb.add("ti_qu", quantity)
pb.add("ti_cu", currency)
return self.complete_payload(pb, context, tstamp)
@contract
def track_ecommerce_transaction(self, order_id, total_value,
affiliation=None, tax_value=None, shipping=None,
city=None, state=None, country=None, currency=None,
items=None,
context=None, tstamp=None):
"""
:param order_id: ID of the eCommerce transaction
:type order_id: non_empty_string
:param total_value: Total transaction value
:type total_value: int | float
:param affiliation: Transaction affiliation
:type affiliation: string_or_none
:param tax_value: Transaction tax value
:type tax_value: int | float | None
:param shipping: Delivery cost charged
:type shipping: int | float | None
:param city: Delivery address city
:type city: string_or_none
:param state: Delivery address state
:type state: string_or_none
:param country: Delivery address country
:type country: string_or_none
:param currency: The currency the price is expressed in
:type currency: string_or_none
:param items: The items in the transaction
:type items: list(dict(str:*))
:param context: Custom context for the event
:type context: context_array | None
:rtype: tracker
"""
pb = payload.Payload()
pb.add("e", "tr")
pb.add("tr_id", order_id)
pb.add("tr_tt", total_value)
pb.add("tr_af", affiliation)
pb.add("tr_tx", tax_value)
pb.add("tr_sh", shipping)
pb.add("tr_ci", city)
pb.add("tr_st", state)
pb.add("tr_co", country)
pb.add("tr_cu", currency)
tstamp = Tracker.get_timestamp(tstamp)
self.complete_payload(pb, context, tstamp)
for item in items:
item["tstamp"] = tstamp
item["order_id"] = order_id
item["currency"] = currency
self.track_ecommerce_transaction_item(**item)
return self
@contract
def track_screen_view(self, name=None, id_=None, context=None, tstamp=None):
"""
:param name: The name of the screen view event
:type name: string_or_none
:param id_: Screen view ID
:type id_: string_or_none
:param context: Custom context for the event
:type context: context_array | None
:rtype: tracker
"""
screen_view_properties = {}
if name is not None:
screen_view_properties["name"] = name
if id_ is not None:
screen_view_properties["id"] = id_
event_json = SelfDescribingJson("%s/screen_view/%s/1-0-0" % (BASE_SCHEMA_PATH, SCHEMA_TAG), screen_view_properties)
return self.track_unstruct_event(event_json, context, tstamp)
@contract
def track_struct_event(self, category, action, label=None, property_=None, value=None,
context=None,
tstamp=None):
"""
:param category: Category of the event
:type category: non_empty_string
:param action: The event itself
:type action: non_empty_string
:param label: Refer to the object the action is
performed on
:type label: string_or_none
:param property_: Property associated with either the action
or the object
:type property_: string_or_none
:param value: A value associated with the user action
:type value: int | float | None
:param context: Custom context for the event
:type context: context_array | None
:rtype: tracker
"""
pb = payload.Payload()
pb.add("e", "se")
pb.add("se_ca", category)
pb.add("se_ac", action)
pb.add("se_la", label)
pb.add("se_pr", property_)
pb.add("se_va", value)
return self.complete_payload(pb, context, tstamp)
@contract
def track_unstruct_event(self, event_json, context=None, tstamp=None):
"""
:param event_json: The properties of the event. Has two field:
A "data" field containing the event properties and
A "schema" field identifying the schema against which the data is validated
:type event_json: self_describing_json
:param context: Custom context for the event
:type context: context_array | None
:param tstamp: User-set timestamp
:type tstamp: timestamp | int | None
:rtype: tracker
"""
envelope = SelfDescribingJson(UNSTRUCT_EVENT_SCHEMA, event_json.to_json()).to_json()
pb = payload.Payload()
pb.add("e", "ue")
pb.add_json(envelope, self.encode_base64, "ue_px", "ue_pr")
return self.complete_payload(pb, context, tstamp)
# Alias
track_self_describing_event = track_unstruct_event
@contract
def flush(self, is_async=False):
"""
Flush the emitter
:param is_async: Whether the flush is done asynchronously. Default is False
:type is_async: bool
:rtype: tracker
"""
for emitter in self.emitters:
if is_async:
emitter.flush()
else:
emitter.sync_flush()
return self
@contract
def set_subject(self, subject):
"""
Set the subject of the events fired by the tracker
:param subject: Subject to be tracked
:type subject: subject | None
:rtype: tracker
"""
self.subject = subject
return self
@contract
def add_emitter(self, emitter):
"""
Add a new emitter to which events should be passed
:param emitter: New emitter
:type emitter: emitter
:rtype: tracker
"""
self.emitters.append(emitter)
return self
@staticmethod
def check_form_element(element):
"""
PyContracts helper method to check that dictionary conforms element
in sumbit_form and change_form schemas
"""
all_present = isinstance(element, dict) and 'name' in element and 'value' in element and 'nodeName' in element
try:
if element['type'] in FORM_TYPES:
type_valid = True
else:
type_valid = False
except KeyError:
type_valid = True
return all_present and element['nodeName'] in FORM_NODE_NAMES and type_valid
| 15five-snowplow-tracker | /15five-snowplow-tracker-0.8.156.tar.gz/15five-snowplow-tracker-0.8.156/snowplow_tracker/tracker.py | tracker.py |
"""
_version.py
Copyright (c) 2013-2014 Snowplow Analytics Ltd. All rights reserved.
This program is licensed to you under the Apache License Version 2.0,
and you may not use this file except in compliance with the Apache License
Version 2.0. You may obtain a copy of the Apache License Version 2.0 at
http://www.apache.org/licenses/LICENSE-2.0.
Unless required by applicable law or agreed to in writing,
software distributed under the Apache License Version 2.0 is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the Apache License Version 2.0 for the specific
language governing permissions and limitations there under.
Authors: Anuj More, Alex Dean, Fred Blundun
Copyright: Copyright (c) 2013-2016 Snowplow Analytics Ltd
License: Apache License Version 2.0
"""
__version_info__ = (0, 8, 1)
__version__ = ".".join(str(x) for x in __version_info__)
__build_version__ = __version__ + ''
| 15five-snowplow-tracker | /15five-snowplow-tracker-0.8.156.tar.gz/15five-snowplow-tracker-0.8.156/snowplow_tracker/_version.py | _version.py |
"""
self_describing_json.py
Copyright (c) 2013-2016 Snowplow Analytics Ltd. All rights reserved.
This program is licensed to you under the Apache License Version 2.0,
and you may not use this file except in compliance with the Apache License
Version 2.0. You may obtain a copy of the Apache License Version 2.0 at
http://www.apache.org/licenses/LICENSE-2.0.
Unless required by applicable law or agreed to in writing,
software distributed under the Apache License Version 2.0 is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the Apache License Version 2.0 for the specific
language governing permissions and limitations there under.
Authors: Anuj More, Alex Dean, Fred Blundun, Anton Parkhomenko
Copyright: Copyright (c) 2013-2014 Snowplow Analytics Ltd
License: Apache License Version 2.0
"""
from contracts import contract, new_contract
new_contract("ts_type", lambda x: x == "ttm" or x == "dtm")
class Timestamp(object):
@contract
def __init__(self, ts_type, value):
"""
Construct base timestamp type
:param ts_type: one of possible timestamp types, according to
tracker protocol
:type ts_type: ts_type
:param value: timestamp value in milliseconds
:type value: int
"""
self.ts_type = ts_type
self.value = value
class TrueTimestamp(Timestamp):
@contract
def __init__(self, value):
"""
Construct true_timestamp (ttm)
:param value: timestamp value in milliseconds
:type value: int
"""
super(TrueTimestamp, self).__init__("ttm", value)
class DeviceTimestamp(Timestamp):
@contract
def __init__(self, value):
"""
Construct device_timestamp (dtm)
:param value: timestamp value in milliseconds
:type value: int
"""
super(DeviceTimestamp, self).__init__("dtm", value)
| 15five-snowplow-tracker | /15five-snowplow-tracker-0.8.156.tar.gz/15five-snowplow-tracker-0.8.156/snowplow_tracker/timestamp.py | timestamp.py |
"""
redis_worker.py
Copyright (c) 2013-2014 Snowplow Analytics Ltd. All rights reserved.
This program is licensed to you under the Apache License Version 2.0,
and you may not use this file except in compliance with the Apache License
Version 2.0. You may obtain a copy of the Apache License Version 2.0 at
http://www.apache.org/licenses/LICENSE-2.0.
Unless required by applicable law or agreed to in writing,
software distributed under the Apache License Version 2.0 is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the Apache License Version 2.0 for the specific
language governing permissions and limitations there under.
Authors: Anuj More, Alex Dean, Fred Blundun
Copyright: Copyright (c) 2013-2014 Snowplow Analytics Ltd
License: Apache License Version 2.0
"""
import redis
import gevent
from gevent.pool import Pool
import json
import signal
DEFAULT_KEY = "snowplow"
class RedisWorker(object):
"""
Asynchronously take events from redis and send them to an emitter
"""
def __init__(self, emitter, rdb=None, key=DEFAULT_KEY):
self.emitter = emitter
self.key = key
if rdb is None:
rdb = redis.StrictRedis()
self.rdb = rdb
self.pool = Pool(5)
signal.signal(signal.SIGTERM, self.request_shutdown)
signal.signal(signal.SIGINT, self.request_shutdown)
signal.signal(signal.SIGQUIT, self.request_shutdown)
def send(self, payload):
"""
Send an event to an emitter
"""
self.emitter.input(payload)
def pop_payload(self):
"""
Get a single event from Redis and send it
If the Redis queue is empty, sleep to avoid making continual requests
"""
payload = self.rdb.lpop(self.key)
if payload:
self.pool.spawn(self.send, json.loads(payload.decode("utf-8")))
else:
gevent.sleep(5)
def run(self):
"""
Run indefinitely
"""
self._shutdown = False
while not self._shutdown:
self.pop_payload()
self.pool.join(timeout=20)
def request_shutdown(self, *args):
"""
Halt the worker
"""
self._shutdown = True
| 15five-snowplow-tracker | /15five-snowplow-tracker-0.8.156.tar.gz/15five-snowplow-tracker-0.8.156/snowplow_tracker/redis_worker.py | redis_worker.py |
"""
subject.py
Copyright (c) 2013-2014 Snowplow Analytics Ltd. All rights reserved.
This program is licensed to you under the Apache License Version 2.0,
and you may not use this file except in compliance with the Apache License
Version 2.0. You may obtain a copy of the Apache License Version 2.0 at
http://www.apache.org/licenses/LICENSE-2.0.
Unless required by applicable law or agreed to in writing,
software distributed under the Apache License Version 2.0 is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the Apache License Version 2.0 for the specific
language governing permissions and limitations there under.
Authors: Anuj More, Alex Dean, Fred Blundun
Copyright: Copyright (c) 2013-2014 Snowplow Analytics Ltd
License: Apache License Version 2.0
!!!MODIFIED BY 15FIVE!!!
Modifiers: Andrii Pleskach, Paul Logston
"""
from contracts import contract, new_contract
SUPPORTED_PLATFORMS = set(["pc", "tv", "mob", "cnsl", "iot", "web", "srv", "app"])
DEFAULT_PLATFORM = "pc"
new_contract("subject", lambda x: isinstance(x, Subject))
new_contract("supported_platform", lambda x: x in SUPPORTED_PLATFORMS)
class Subject(object):
"""
Class for an event subject, where we view events as of the form
(Subject) -> (Verb) -> (Object)
"""
def __init__(self):
self.standard_nv_pairs = {"p": DEFAULT_PLATFORM}
@contract
def set_platform(self, value):
"""
:param value: One of ["pc", "tv", "mob", "cnsl", "iot", "web", "srv", "app"]
:type value: supported_platform
:rtype: subject
"""
self.standard_nv_pairs["p"] = value
return self
@contract
def set_user_id(self, user_id):
"""
:param user_id: User ID
:type user_id: string
:rtype: subject
"""
self.standard_nv_pairs["uid"] = user_id
return self
@contract
def set_screen_resolution(self, width, height):
"""
:param width: Width of the screen
:param height: Height of the screen
:type width: int,>0
:type height: int,>0
:rtype: subject
"""
self.standard_nv_pairs["res"] = "".join([str(width), "x", str(height)])
return self
@contract
def set_viewport(self, width, height):
"""
:param width: Width of the viewport
:param height: Height of the viewport
:type width: int,>0
:type height: int,>0
:rtype: subject
"""
self.standard_nv_pairs["vp"] = "".join([str(width), "x", str(height)])
return self
@contract
def set_color_depth(self, depth):
"""
:param depth: Depth of the color on the screen
:type depth: int
:rtype: subject
"""
self.standard_nv_pairs["cd"] = depth
return self
@contract
def set_timezone(self, timezone):
"""
:param timezone: Timezone as a string
:type timezone: string
:rtype: subject
"""
self.standard_nv_pairs["tz"] = timezone
return self
@contract
def set_lang(self, lang):
"""
Set language.
:param lang: Language the application is set to
:type lang: string
:rtype: subject
"""
self.standard_nv_pairs["lang"] = lang
return self
@contract
def set_domain_user_id(self, duid):
"""
Set the domain user ID
:param duid: Domain user ID
:type duid: string
:rtype: subject
"""
self.standard_nv_pairs["duid"] = duid
return self
@contract
def set_ip_address(self, ip):
"""
Set the domain user ID
:param ip: IP address
:type ip: string
:rtype: subject
"""
self.standard_nv_pairs["ip"] = ip
return self
@contract
def set_useragent(self, ua):
"""
Set the user agent
:param ua: User agent
:type ua: string
:rtype: subject
"""
self.standard_nv_pairs["ua"] = ua
return self
@contract
def set_network_user_id(self, nuid):
"""
Set the network user ID field
This overwrites the nuid field set by the collector
:param nuid: Network user ID
:type nuid: string
:rtype: subject
"""
self.standard_nv_pairs["tnuid"] = nuid
return self
def set_custom(self, field, value):
"""
Set custom field
:param field: Field name
:param value: Value for a field
"""
self.standard_nv_pairs[field] = value
return self
def set_custom_by_name(self, field, value):
"""
Set custom field by getting field name from SNOWPLOW_REVERTED_TRANSFORM_MAP
:param field: Field name
:param value: Value for a field
"""
self.standard_nv_pairs[SNOWPLOW_REVERTED_TRANSFORM_MAP.get(field, field)] = value
return self
SNOWPLOW_REVERTED_TRANSFORM_MAP = {
"event": "e",
"user_ipaddress": "ip",
"app_id": "aid",
"platform": "p",
"txn_id": "tid",
"user_id": "uid",
"domain_userid": "duid",
"network_userid": "nuid",
"useragent": "ua",
"user_fingerprint": "fp",
"domain_sessionidx": "vid",
"domain_sessionid": "sid",
"dvce_created_tstamp": "dtm",
"true_tstamp": "ttm",
"dvce_sent_tstamp": "stm",
"name_tracker": "tna",
"v_tracker": "tv",
"v_collector": "cv",
"br_lang": "lang",
"br_features_pdf": "f_pdf",
"br_features_flash": "f_fla",
"br_features_java": "f_java",
"br_features_director": "f_dir",
"br_features_quicktime": "f_qt",
"br_features_realplayer": "f_realp",
"br_features_windowsmedia": "f_wma",
"br_features_gears": "f_gears",
"br_features_silverlight": "f_ag",
"br_cookies": "cookie",
"br_colordepth": "cd",
"os_timezone": "tz",
"page_referrer": "refr",
"page_url": "url",
"page_title": "page",
"doc_charset": "cs",
"event_id": "eid",
"contexts": "cx",
"se_category": "se_ca",
"se_action": "se_ac",
"se_label": "se_la",
"se_property": "se_pr",
"se_value": "se_va",
"unstruct_event": "ue_pr",
"tr_orderid": "tr_id",
"tr_affiliation": "tr_af",
"tr_total": "tr_tt",
"tr_tax": "tr_tx",
"tr_shipping": "tr_sh",
"tr_city": "tr_ci",
"tr_state": "tr_st",
"tr_country": "tr_co",
"ti_orderid": "ti_id",
"ti_sku": "ti_sk",
"ti_name": "ti_nm",
"ti_category": "ti_ca",
"ti_price": "ti_pr",
"ti_quantity": "ti_qu",
"pp_xoffset_min": "pp_mix",
"pp_xoffset_max": "pp_max",
"pp_yoffset_min": "pp_miy",
"pp_yoffset_max": "pp_may",
"tr_currency": "tr_cu",
"ti_currency": "ti_cu",
}
| 15five-snowplow-tracker | /15five-snowplow-tracker-0.8.156.tar.gz/15five-snowplow-tracker-0.8.156/snowplow_tracker/subject.py | subject.py |
"""
!!!MODIFIED BY 15FIVE!!!
Modifiers: Andrii Pleskach, Paul Logston
"""
import logging
import requests
logger = logging.getLogger(__name__)
def http_post(endpoint, data):
"""
:param endpoint: endpoint URL
:param data: The array of JSONs to be sent
:type endpoint: string
:type data: string
"""
logger.info("Sending POST request to %s..." % endpoint)
logger.debug("Payload: %s" % data)
r = requests.post(endpoint, data=data, headers={'content-type': 'application/json; charset=utf-8'})
getattr(logger, "info" if is_good_status_code(r.status_code) else "warn")(
"POST request finished with status code: " + str(r.status_code))
return r
def http_get(endpoint, payload):
"""
:param endpoint: endpoint URL
:param payload: The event properties
:type endpoint: string
:type payload: dict(string:*)
"""
logger.info("Sending GET request to %s..." % endpoint)
logger.debug("Payload: %s" % payload)
r = requests.get(endpoint, params=payload)
getattr(logger, "info" if is_good_status_code(r.status_code) else "warn")(
"GET request finished with status code: " + str(r.status_code))
return r
def is_good_status_code(status_code):
"""
:param status_code: HTTP status code
:type status_code: int
:rtype: bool
"""
return 200 <= status_code < 400
| 15five-snowplow-tracker | /15five-snowplow-tracker-0.8.156.tar.gz/15five-snowplow-tracker-0.8.156/snowplow_tracker/utils.py | utils.py |
"""
emitters.py
Copyright (c) 2013-2014 Snowplow Analytics Ltd. All rights reserved.
This program is licensed to you under the Apache License Version 2.0,
and you may not use this file except in compliance with the Apache License
Version 2.0. You may obtain a copy of the Apache License Version 2.0 at
http://www.apache.org/licenses/LICENSE-2.0.
Unless required by applicable law or agreed to in writing,
software distributed under the Apache License Version 2.0 is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the Apache License Version 2.0 for the specific
language governing permissions and limitations there under.
Authors: Anuj More, Alex Dean, Fred Blundun
Copyright: Copyright (c) 2013-2014 Snowplow Analytics Ltd
License: Apache License Version 2.0
!!!MODIFIED BY 15FIVE!!!
Modifiers: Andrii Pleskach, Paul Logston
"""
import json
import logging
import time
import threading
try:
# Python 2
from Queue import Queue
except ImportError:
# Python 3
from queue import Queue
from celery import shared_task
import redis
import requests
from contracts import contract, new_contract
from snowplow_tracker.utils import http_get, http_post, is_good_status_code
from snowplow_tracker.self_describing_json import SelfDescribingJson
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
DEFAULT_MAX_LENGTH = 10
PAYLOAD_DATA_SCHEMA = "iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-4"
new_contract("protocol", lambda x: x == "http" or x == "https")
new_contract("method", lambda x: x == "get" or x == "post")
new_contract("function", lambda x: hasattr(x, "__call__"))
new_contract("redis", lambda x: isinstance(x, (redis.Redis, redis.StrictRedis)))
class Emitter(object):
"""
Synchronously send Snowplow events to a Snowplow collector
Supports both GET and POST requests
"""
@contract
def __init__(self, endpoint, protocol="http", port=None, method="get", buffer_size=None, on_success=None, on_failure=None, byte_limit=None):
"""
:param endpoint: The collector URL. Don't include "http://" - this is done automatically.
:type endpoint: string
:param protocol: The protocol to use - http or https. Defaults to http.
:type protocol: protocol
:param port: The collector port to connect to
:type port: int | None
:param method: The HTTP request method
:type method: method
:param buffer_size: The maximum number of queued events before the buffer is flushed. Default is 10.
:type buffer_size: int | None
:param on_success: Callback executed after every HTTP request in a flush has status code 200
Gets passed the number of events flushed.
:type on_success: function | None
:param on_failure: Callback executed if at least one HTTP request in a flush has status code 200
Gets passed two arguments:
1) The number of events which were successfully sent
2) If method is "post": The unsent data in string form;
If method is "get": An array of dictionaries corresponding to the unsent events' payloads
:type on_failure: function | None
:param byte_limit: The size event list after reaching which queued events will be flushed
:type byte_limit: int | None
"""
self.endpoint = Emitter.as_collector_uri(endpoint, protocol, port, method)
self.method = method
if buffer_size is None:
if method == "post":
buffer_size = DEFAULT_MAX_LENGTH
else:
buffer_size = 1
self.buffer_size = buffer_size
self.buffer = []
self.byte_limit = byte_limit
self.bytes_queued = None if byte_limit is None else 0
self.on_success = on_success
self.on_failure = on_failure
self.lock = threading.RLock()
self.timer = None
logger.info("Emitter initialized with endpoint " + self.endpoint)
@staticmethod
@contract
def as_collector_uri(endpoint, protocol="http", port=None, method="get"):
"""
:param endpoint: The raw endpoint provided by the user
:type endpoint: string
:param protocol: The protocol to use - http or https
:type protocol: protocol
:param port: The collector port to connect to
:type port: int | None
:param method: Either `get` or `post` HTTP method
:type method: method
:rtype: string
"""
if method == "get":
path = "/i"
else:
path = "/com.snowplowanalytics.snowplow/tp2"
if port is None:
return protocol + "://" + endpoint + path
else:
return protocol + "://" + endpoint + ":" + str(port) + path
@contract
def input(self, payload):
"""
Adds an event to the buffer.
If the maximum size has been reached, flushes the buffer.
:param payload: The name-value pairs for the event
:type payload: dict(string:*)
"""
with self.lock:
if self.bytes_queued is not None:
self.bytes_queued += len(str(payload))
if self.method == "post":
self.buffer.append({key: str(payload[key]) for key in payload})
else:
self.buffer.append(payload)
if self.reached_limit():
self.flush()
def reached_limit(self):
"""
Checks if event-size or bytes limit are reached
:rtype: bool
"""
if self.byte_limit is None:
return len(self.buffer) >= self.buffer_size
else:
return self.bytes_queued >= self.byte_limit or len(self.buffer) >= self.buffer_size
def flush(self):
"""
Sends all events in the buffer to the collector.
"""
with self.lock:
self.send_events(self.buffer)
self.buffer = []
if self.bytes_queued is not None:
self.bytes_queued = 0
@contract
def http_post(self, data):
"""
:param data: The array of JSONs to be sent
:type data: string
"""
logger.info("Sending POST request to %s..." % self.endpoint)
logger.debug("Payload: %s" % data)
r = requests.post(self.endpoint, data=data, headers={'content-type': 'application/json; charset=utf-8'})
getattr(logger, "info" if self.is_good_status_code(r.status_code) else "warn")("POST request finished with status code: " + str(r.status_code))
return r
@contract
def http_get(self, payload):
"""
:param payload: The event properties
:type payload: dict(string:*)
"""
logger.info("Sending GET request to %s..." % self.endpoint)
logger.debug("Payload: %s" % payload)
r = requests.get(self.endpoint, params=payload)
getattr(logger, "info" if self.is_good_status_code(r.status_code) else "warn")("GET request finished with status code: " + str(r.status_code))
return r
def sync_flush(self):
"""
Calls the flush method of the base Emitter class.
This is guaranteed to be blocking, not asynchronous.
"""
logger.debug("Starting synchronous flush...")
Emitter.flush(self)
logger.info("Finished synchrous flush")
@staticmethod
@contract
def is_good_status_code(status_code):
"""
:param status_code: HTTP status code
:type status_code: int
:rtype: bool
"""
return 200 <= status_code < 400
@contract
def send_events(self, evts):
"""
:param evts: Array of events to be sent
:type evts: list(dict(string:*))
"""
send_events(self.endpoint, evts, self.method)
@contract
def set_flush_timer(self, timeout, flush_now=False):
"""
Set an interval at which the buffer will be flushed
:param timeout: interval in seconds
:type timeout: int | float
:param flush_now: immediately flush buffer
:type flush_now: bool
"""
# Repeatable create new timer
if flush_now:
self.flush()
self.timer = threading.Timer(timeout, self.set_flush_timer, [timeout, True])
self.timer.daemon = True
self.timer.start()
def cancel_flush_timer(self):
"""
Abort automatic async flushing
"""
if self.timer is not None:
self.timer.cancel()
@staticmethod
def attach_sent_timestamp(events):
"""
Attach (by mutating in-place) current timestamp in milliseconds
as `stm` param
:param events: Array of events to be sent
:type events: list(dict(string:*))
:rtype: None
"""
def update(e):
e.update({'stm': str(int(time.time()) * 1000)})
[update(event) for event in events]
class AsyncEmitter(Emitter):
"""
Uses threads to send HTTP requests asynchronously
"""
@contract
def __init__(
self,
endpoint,
protocol="http",
port=None,
method="get",
buffer_size=None,
on_success=None,
on_failure=None,
thread_count=1,
byte_limit=None):
"""
:param endpoint: The collector URL. Don't include "http://" - this is done automatically.
:type endpoint: string
:param protocol: The protocol to use - http or https. Defaults to http.
:type protocol: protocol
:param port: The collector port to connect to
:type port: int | None
:param method: The HTTP request method
:type method: method
:param buffer_size: The maximum number of queued events before the buffer is flushed. Default is 10.
:type buffer_size: int | None
:param on_success: Callback executed after every HTTP request in a flush has status code 200
Gets passed the number of events flushed.
:type on_success: function | None
:param on_failure: Callback executed if at least one HTTP request in a flush has status code 200
Gets passed two arguments:
1) The number of events which were successfully sent
2) If method is "post": The unsent data in string form;
If method is "get": An array of dictionaries corresponding to the unsent events' payloads
:type on_failure: function | None
:param thread_count: Number of worker threads to use for HTTP requests
:type thread_count: int
:param byte_limit: The size event list after reaching which queued events will be flushed
:type byte_limit: int | None
"""
super(AsyncEmitter, self).__init__(endpoint, protocol, port, method, buffer_size, on_success, on_failure, byte_limit)
self.queue = Queue()
for i in range(thread_count):
t = threading.Thread(target=self.consume)
t.daemon = True
t.start()
def sync_flush(self):
while True:
self.flush()
self.queue.join()
if len(self.buffer) < 1:
break
def flush(self):
"""
Removes all dead threads, then creates a new thread which
executes the flush method of the base Emitter class
"""
with self.lock:
self.queue.put(self.buffer)
self.buffer = []
if self.bytes_queued is not None:
self.bytes_queued = 0
def consume(self):
while True:
evts = self.queue.get()
self.send_events(evts)
self.queue.task_done()
class CeleryEmitter(Emitter):
"""
Uses a Celery worker to send HTTP requests asynchronously.
Works like the base Emitter class,
but on_success and on_failure callbacks cannot be set.
"""
celery_app = None
def __init__(self, endpoint, protocol="http", port=None, method="get", buffer_size=None, byte_limit=None):
super(CeleryEmitter, self).__init__(endpoint, protocol, port, method, buffer_size, None, None, byte_limit)
def send_events(self, evts):
"""
Schedules a flush task
"""
send_events.delay(self.endpoint, evts, self.method)
logger.info("Scheduled a Celery task to flush the event queue")
class RedisEmitter(object):
"""
Sends Snowplow events to a Redis database
"""
@contract
def __init__(self, rdb=None, key="snowplow"):
"""
:param rdb: Optional custom Redis database
:type rdb: redis | None
:param key: The Redis key for the list of events
:type key: string
"""
if rdb is None:
rdb = redis.StrictRedis()
self.rdb = rdb
self.key = key
@contract
def input(self, payload):
"""
:param payload: The event properties
:type payload: dict(string:*)
"""
logger.debug("Pushing event to Redis queue...")
self.rdb.rpush(self.key, json.dumps(payload))
logger.info("Finished sending event to Redis.")
def flush(self):
logger.warn("The RedisEmitter class does not need to be flushed")
def sync_flush(self):
self.flush()
@shared_task
def send_events(endpoint, evts, method):
if len(evts) > 0:
logger.info("Attempting to send %s requests" % len(evts))
Emitter.attach_sent_timestamp(evts)
if method == 'post':
data = SelfDescribingJson(PAYLOAD_DATA_SCHEMA, evts).to_string()
post_succeeded = False
try:
status_code = http_post(endpoint, data).status_code
post_succeeded = is_good_status_code(status_code)
except requests.RequestException as e:
logger.warn(e)
if post_succeeded:
logger.info("Success")
else:
logger.info("Fail")
elif method == 'get':
success_count = 0
unsent_requests = []
for evt in evts:
get_succeeded = False
try:
status_code = http_get(endpoint, evt).status_code
get_succeeded = is_good_status_code(status_code)
except requests.RequestException as e:
logger.warn(e)
if get_succeeded:
success_count += 1
else:
unsent_requests.append(evt)
else:
logger.info("Skipping flush since buffer is empty")
| 15five-snowplow-tracker | /15five-snowplow-tracker-0.8.156.tar.gz/15five-snowplow-tracker-0.8.156/snowplow_tracker/emitters.py | emitters.py |
from snowplow_tracker._version import __version__
from snowplow_tracker.subject import Subject
from snowplow_tracker.emitters import logger, Emitter, AsyncEmitter, CeleryEmitter, RedisEmitter
from snowplow_tracker.self_describing_json import SelfDescribingJson
from snowplow_tracker.tracker import Tracker
from contracts import disable_all as disable_contracts, enable_all as enable_contracts
| 15five-snowplow-tracker | /15five-snowplow-tracker-0.8.156.tar.gz/15five-snowplow-tracker-0.8.156/snowplow_tracker/__init__.py | __init__.py |
"""
self_describing_json.py
Copyright (c) 2013-2014 Snowplow Analytics Ltd. All rights reserved.
This program is licensed to you under the Apache License Version 2.0,
and you may not use this file except in compliance with the Apache License
Version 2.0. You may obtain a copy of the Apache License Version 2.0 at
http://www.apache.org/licenses/LICENSE-2.0.
Unless required by applicable law or agreed to in writing,
software distributed under the Apache License Version 2.0 is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the Apache License Version 2.0 for the specific
language governing permissions and limitations there under.
Authors: Anuj More, Alex Dean, Fred Blundun
Copyright: Copyright (c) 2013-2014 Snowplow Analytics Ltd
License: Apache License Version 2.0
"""
import json
class SelfDescribingJson(object):
def __init__(self, schema, data):
self.schema = schema
self.data = data
def to_json(self):
return {
"schema": self.schema,
"data": self.data
}
def to_string(self):
return json.dumps(self.to_json())
| 15five-snowplow-tracker | /15five-snowplow-tracker-0.8.156.tar.gz/15five-snowplow-tracker-0.8.156/snowplow_tracker/self_describing_json.py | self_describing_json.py |
"""
payload.py
Copyright (c) 2013-2014 Snowplow Analytics Ltd. All rights reserved.
This program is licensed to you under the Apache License Version 2.0,
and you may not use this file except in compliance with the Apache License
Version 2.0. You may obtain a copy of the Apache License Version 2.0 at
http://www.apache.org/licenses/LICENSE-2.0.
Unless required by applicable law or agreed to in writing,
software distributed under the Apache License Version 2.0 is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the Apache License Version 2.0 for the specific
language governing permissions and limitations there under.
Authors: Anuj More, Alex Dean, Fred Blundun
Copyright: Copyright (c) 2013-2014 Snowplow Analytics Ltd
License: Apache License Version 2.0
"""
import random
import time
import json
import base64
from contracts import contract
class Payload:
def __init__(self, dict_=None):
"""
Constructor
"""
self.nv_pairs = {}
if dict_ is not None:
for f in dict_:
self.nv_pairs[f] = dict_[f]
"""
Methods to add to the payload
"""
def add(self, name, value):
"""
Add a name value pair to the Payload object
"""
if not (value == "" or value is None):
self.nv_pairs[name] = value
@contract
def add_dict(self, dict_, base64=False):
"""
Add a dict of name value pairs to the Payload object
:param dict_: Dictionary to be added to the Payload
:type dict_: dict(string:*)
"""
for f in dict_:
self.add(f, dict_[f])
@contract
def add_json(self, dict_, encode_base64, type_when_encoded, type_when_not_encoded):
"""
Add an encoded or unencoded JSON to the payload
:param dict_: Custom context for the event
:type dict_: dict(string:*) | None
:param encode_base64: If the payload is base64 encoded
:type encode_base64: bool
:param type_when_encoded: Name of the field when encode_base64 is set
:type type_when_encoded: string
:param type_when_not_encoded: Name of the field when encode_base64 is not set
:type type_when_not_encoded: string
"""
if dict_ is not None and dict_ != {}:
json_dict = json.dumps(dict_, ensure_ascii=False)
if encode_base64:
encoded_dict = base64.urlsafe_b64encode(json_dict.encode("ascii"))
if not isinstance(encoded_dict, str):
encoded_dict = encoded_dict.decode("utf-8")
self.add(type_when_encoded, encoded_dict)
else:
self.add(type_when_not_encoded, json_dict)
def get(self):
"""
Returns the context dictionary from the Payload object
"""
return self.nv_pairs
| 15five-snowplow-tracker | /15five-snowplow-tracker-0.8.156.tar.gz/15five-snowplow-tracker-0.8.156/snowplow_tracker/payload.py | payload.py |
# Resumo do funcionamento
A biblioteca desenvolvida auxilia desenvolvedores a explorar os dados com funções essenciais para a identificação de outliers e anomalias e uma interface que auxilia a visualizar as informações de acordo com o arquivo de configuração.
A biblioteca recebe um arquivo yaml com as configurações de cada etapa do pipeline de dados, e do endereço do banco de dados.
Após a execução do banco de dados, o banco de dados de dados é atualizado com os resultados da análise e os resultados podem ser visualizados por meio de dashboards no metabase.
| 170051277-trab-final-gces | /170051277_trab_final_gces-0.5.0-py3-none-any.whl/170051277_trab_final_gces/README.md | README.md |
import os
from parser.YAML_parser import YAMLParser
from parser.feature_engineering_parser import FeatureEngineeringParser
from parser.model_parser import ModelParser
if __name__ != "__main__":
exit()
def get_config():
initialParser = YAMLParser
featureEngineringParser = FeatureEngineeringParser
modelParser = ModelParser
for file in os.listdir('src/yamls'):
filepath = os.path.join('src/yamls', file)
config = initialParser(filepath).parse()
features_configs, columns_set_alias = featureEngineringParser(filepath).parse(config['feature_engineering'])
del config['feature_engineering']
model_configs = modelParser(columns_set_alias).parse(config['model'])
del config['model']
print("FEATURES")
print(features_configs)
print(3 * '\n')
print(20 * '-')
print(3 * '\n')
print(model_configs)
get_config()
| 170051277-trab-final-gces | /170051277_trab_final_gces-0.5.0-py3-none-any.whl/170051277_trab_final_gces/src/main.py | main.py |
from whatlies.language import BytePairLanguage
import numpy as np
class WordEmbedding:
def __init__(self, lang, dimensions):
"""Initialize a word embedding object using the BytePairLanguage model.
Parameters
----------
lang: str
The language to use for the word embedding (default is "es")
dimensions: str
The number of dimensions for the word embedding vectors (default is 25)
"""
self.bpl = BytePairLanguage(lang=lang, dim=dimensions)
def get_embedding(self, text):
"""Get the word embedding vector for a given text.
Parameters
----------
text: str
The string to be processed
Returns
----------
arr[float]
A word embedding vector for the given text
Examples
--------
>>> get_embedding("This is a text", "es", 25)
[ 0.06799883 0.17547965 0.47599664 0.16108984 -0.1360625 -0.10632467
-0.10654568 -0.09805 -0.33004168 -0.33528003 -0.23304085 0.36661038
-0.5797167 0.53252834 0.30276018 -0.01584417 0.85087484 0.14121284
0.74862367 -0.33011952 0.015432 0.02694534 0.10118082 -0.34017918
-0.14560167]
"""
return self.bpl[text].vector | 170051277-trab-final-gces | /170051277_trab_final_gces-0.5.0-py3-none-any.whl/170051277_trab_final_gces/src/data_pipeline/feature_engineering/word_embedding.py | word_embedding.py |
from statistics import mean
class KeySmash:
"""A class for calculating metrics to indicate key smashing behavior in a text.
Key smashing is the act of typing on a keyboard in a rapid and uncontrolled manner,
often resulting in a series of random characters being entered into a document or text field.
"""
def __init__(self):
self.char_sets = {
"vowels": 'aeiouáéíóúãõ',
"consonants": 'bcdfghjklmnñpqrstvwxyz',
"special_characters": '!@#$%^¨|\'\"&*()_+:;~`´]}{[}ºª=-.¿¡'
}
def calculate_char_frequency_metric(self, text):
"""
Calculate the Char Frequency Metric.
Parameters
----------
text : str
The text to use for the calculation.
Returns
-------
float
Char Frequency Metric.
Examples
--------
>>> calculate_char_frequency_metric("PUENTECILLA KM. 1.7")
1.121212121212121
>>> calculate_char_frequency_metric("ASDASD XXXX")
3.0
"""
word_results = []
for w in text.split(' '):
char_count = []
if w and len(w) > 0:
for e in set(w):
char_count.append(w.count(e)**2)
word_results.append(sum(char_count)/len(w))
if word_results == 0 or len(word_results) == 0:
return 0
else:
return mean(word_results)
def calculate_irregular_sequence_metric(self, text, opt):
"""
Calculate the Irregular Sequence Metric.
Parameters
----------
text : str
The text to use for the calculation.
opt : str
The type of characters to consider for the calculation,
can be one of 'vowels', 'consonants', or 'special_characters'.
Returns
-------
float
Irregular Sequence Metric.
Examples
--------
>>> calculate_irregular_sequence_metric("PUENTECILLA KM. 1.7", "vowels")
0.21052631578947367
>>> calculate_irregular_sequence_metric("ASDASD XXXX", "consonants")
2.1818181818181817
>>> calculate_irregular_sequence_metric("!@#$% ASDFGHJKL", "special_characters")
1.5625
"""
count_sequence = 1
sequence_regex = []
text = str(text).lower()
opt = self.char_sets[opt]
for i in range(len(text) - 1):
if text[i] in opt and text[i + 1] in opt:
count_sequence = count_sequence + 1
else:
if (count_sequence != 1):
sequence_regex.append(count_sequence**2)
count_sequence = 1
if (count_sequence != 1):
sequence_regex.append(count_sequence**2)
return sum(sequence_regex)/len(text)
def calculate_number_count_metric(self, text):
"""
Calculate the Number Count Metric.
Parameters
----------
text : str
The text field to use for the calculation.
Returns
-------
float
Number Count Metric.
Examples
--------
>>> calculate_number_count_metric("ABC 123 !@#")
0.0
>>> calculate_number_count_metric("ABC123 !@#")
0.9
"""
text_list = text.split()
calc_num_line = 0
if text_list:
for word in text_list:
if any(char.isdigit() for char in word) and any(not char.isdigit() for char in word):
num = len([char for char in word if char.isdigit()])
calc_num = num**2
calc_num_line += calc_num
return calc_num_line / len(' '.join(text_list))
return 0 | 170051277-trab-final-gces | /170051277_trab_final_gces-0.5.0-py3-none-any.whl/170051277_trab_final_gces/src/data_pipeline/feature_engineering/key_smash.py | key_smash.py |
from pandas import DataFrame
def get_concatenated_column(csv, columns, column_name):
if(type(columns) == str):
csv[column_name] = csv[columns]
return DataFrame(csv[column_name])
for value in columns:
if(not(column_name in csv)):
csv[column_name] = csv[value].astype(str)
continue
csv[column_name] = csv[column_name] + ' ' + csv[value].astype(str)
return DataFrame(csv[column_name])
| 170051277-trab-final-gces | /170051277_trab_final_gces-0.5.0-py3-none-any.whl/170051277_trab_final_gces/src/data_pipeline/pre_processing/concatenate_columns.py | concatenate_columns.py |
from src.parser.parser_base import ParserBase
class FeatureEngineeringParser(ParserBase):
def parse(self, data: list):
return self._parse_feature_engineering_configs(data)
def _parse_feature_engineering_configs(self, data: list):
if(not data): return
configs = []
columns_set_alias = []
for inputs in data:
input = self._try_get(inputs, 'input')
# columns
columns_set, columns_alias = self._get_dataframe(self._try_get(input, 'columns'))
columns_set_alias = columns_alias + columns_set_alias
# features
word_embedding, keyboard_smash = self._get_features_details(self._try_get(input, 'features'))
data_lang, dimensions = self._get_word_embedding_config(word_embedding, columns_set_alias)
# Enabled features
enabled_features = keyboard_smash
if(not dimensions): enabled_features['word_embedding'] = False
else: enabled_features['word_embedding'] = True
configs.append({
'columns_alias': columns_alias,
'columns_set': columns_set,
'data_lang': data_lang,
'dimensions': dimensions,
'enabled_features': enabled_features
})
return configs, columns_set_alias
def _get_dataframe(self, columns: dict):
if(not columns): return
columns_alias = []
for column in columns:
for key in column.keys():
columns_alias.append(key)
return columns, columns_alias
def _get_features_details(self, features: dict):
if(not features): return
word_embedding = self._try_get(features, 'word_embedding')
if (word_embedding == 'off'): word_embedding = False
keyboard_smash = self._get_keyboard_smash_config(features)
return word_embedding, keyboard_smash
def _get_word_embedding_config(self, feature: dict, columns_alias: list):
if(not feature): return 'es', None
data_lang = self._get(feature, 'data_lang', 'es')
if ('data_lang' in feature): del feature['data_lang']
dimensions = {}
dimensions_default_value = 25
for key, item in feature.items():
if(not(key in columns_alias)):
error_msg = f'Label {key} not match'
raise ValueError(error_msg)
dimensions[key] = self._get(item, 'dimensions', dimensions_default_value)
for name in columns_alias:
if(not(name in dimensions)): dimensions[name] = dimensions_default_value
return data_lang, dimensions
def _get_keyboard_smash_config(self, features: dict):
keyboard_smash_default_value = {
'ksmash_sequence_vowels': True,
'ksmash_sequence_consonants': True,
'ksmash_sequence_special_characters': True,
'ksmash_numbers': True,
'ksmash_char_frequence': True
}
keyboard_smash = self._get(features, 'keyboard_smash', keyboard_smash_default_value)
if (keyboard_smash == keyboard_smash_default_value): return keyboard_smash
for key in keyboard_smash.keys():
if(key in keyboard_smash_default_value and keyboard_smash[key] == 'off'):
keyboard_smash_default_value[key] = False
return keyboard_smash_default_value
| 170051277-trab-final-gces | /170051277_trab_final_gces-0.5.0-py3-none-any.whl/170051277_trab_final_gces/src/parser/feature_engineering_parser.py | feature_engineering_parser.py |
model_type = {
'ADDRESS': 'address'
} | 170051277-trab-final-gces | /170051277_trab_final_gces-0.5.0-py3-none-any.whl/170051277_trab_final_gces/src/parser/const.py | const.py |
import os
class ParserBase():
def __init__(self, filepath = 'src/yamls/config.yaml'):
self.filepath = filepath
def _try_get(self, variable: dict, field, error_msg=None):
try:
return variable[field]
except KeyError:
if not error_msg:
error_msg = f'the field `{field}` is required.'
file_name = self.filepath.split('/')[-1]
error_msg = f'Error in file {file_name}: {error_msg}'
raise ValueError(error_msg)
def _get(self, variable: dict, field, default_value):
try:
return variable[field]
except:
return default_value | 170051277-trab-final-gces | /170051277_trab_final_gces-0.5.0-py3-none-any.whl/170051277_trab_final_gces/src/parser/parser_base.py | parser_base.py |
import yaml
from src.parser.parser_base import ParserBase
class YAMLParser(ParserBase):
def parse(self):
return self._parse_yaml()
def _parse_yaml(self):
with open(self.filepath, 'r') as file:
dag_config_dict = yaml.safe_load(file)
dag = self._try_get(dag_config_dict, 'dag')
initial_parser = {
"dag_id": self._try_get(dag, 'id'),
"data_path": self._try_get(dag, 'data_path'),
"output_folder": self._try_get(dag, 'output_folder'),
"description": self._try_get(dag, 'description'),
"feature_engineering": self._try_get(dag, 'feature_engineering'),
"model": self._try_get(dag, 'model'),
}
return initial_parser
| 170051277-trab-final-gces | /170051277_trab_final_gces-0.5.0-py3-none-any.whl/170051277_trab_final_gces/src/parser/YAML_parser.py | YAML_parser.py |
from src.parser.parser_base import ParserBase
from src.parser.const import model_type
class ModelParser(ParserBase):
def __init__(self, columns_alias):
self.columns_alias = columns_alias
self.default_keyboard_smash_values = {
'ksmash_sequence_vowels': 1.00,
'ksmash_sequence_consonants': 1.999,
'ksmash_sequence_special_characters': 2.2499,
'ksmash_numbers': 2.9,
'ksmash_char_frequence': 2.78
}
def parse(self, data: list):
return self._parse_modal_configs(data)
def _parse_modal_configs(self, data: list):
if(not data): return
random_forest = data.get('random_forest')
if(random_forest):
return self.get_random_forest_address_config(random_forest)
def get_random_forest_address_config(self, model: list):
configs = []
for inputs in model:
input = self._try_get(inputs, 'input', 'The inputs should be specified')
type = self._try_get(input, 'type')
if (type == model_type['ADDRESS']):
columns_set_alias = self.get_columns(input)
keyboard_smash, n_estimators, test_size = self.get_thresholds(input, columns_set_alias)
configs.append({
'model': 'keyboard_smash',
'type': model_type['ADDRESS'],
'columns_set_alias': columns_set_alias,
'keyboard_smash': keyboard_smash,
'n_estimators': n_estimators,
'test_size': test_size
})
return configs
def get_columns(self, input):
columns_set_alias = self._try_get(input, 'columns')
for alias in columns_set_alias:
if(not(alias in self.columns_alias)):
raise ValueError(f'`{alias}` column not match with the available columns')
return columns_set_alias
def get_thresholds(self, input, columns_set_alias):
thresholds = self._try_get(input, 'thresholds')
test_size = self._get(thresholds, 'test_size', 0.3)
n_estimators = self._get(thresholds, 'n_estimators', 100)
keyboard_smash_default = self.get_keyboard_smash_default_thresholds(columns_set_alias)
keyboard_smash = self._get(thresholds, 'keyboard_smash', keyboard_smash_default)
for key in keyboard_smash.keys():
if(not(key in columns_set_alias)):
raise ValueError(f'`{key}` key not match with the available columns')
for alias in columns_set_alias:
if(not(alias in keyboard_smash.keys())):
keyboard_smash.append({alias: self.default_keyboard_smash_values})
return keyboard_smash, n_estimators, test_size
def get_keyboard_smash_default_thresholds(self, columns_set_alias):
default_config = []
for alias in columns_set_alias:
default_config.append({alias: self.default_keyboard_smash_values})
return default_config
| 170051277-trab-final-gces | /170051277_trab_final_gces-0.5.0-py3-none-any.whl/170051277_trab_final_gces/src/parser/model_parser.py | model_parser.py |
# Since there are no tests implemented, I create this dummy class that simulates them.
import pytest
def testGetGcesString():
result = getGcesString()
assert result == "GCES"
def getGcesString():
return "GCES"
| 170051277-trab-final-gces | /170051277_trab_final_gces-0.5.0-py3-none-any.whl/170051277_trab_final_gces/tests/test_init.py | test_init.py |
17MonIP Changelog
=================
Version 0.2.7
-------------
Released on Oct 14, 2015.
- update dat version to 20151001
Version 0.2.6
-------------
Released on April 21, 2015.
- support python wheel
Version 0.2.5
-------------
Released on April 21, 2015.
- update dat version to 20150401
- use binary search to replace line search for speed boost, via #7
.. _`#7`: https://github.com/lxyu/17monip/issues/7
Version 0.2.4
-------------
Released on November 18, 2014.
- update dat version to 20141001
- code rewrite via `#3`_ and `#5`_,
.. _`#3`: https://github.com/lxyu/17monip/issues/3
.. _`#5`: https://github.com/lxyu/17monip/issues/5
Version 0.2.3
-------------
Released on August 6, 2014.
- add support for py2.6, py3.2
Version 0.2.2
-------------
Released on August 5, 2014.
- update dat version to 20140804
- update tests and docs
Version 0.2.1
-------------
Released on July 4, 2014.
- update dat version to 20140701
- change bin script from 'ip' to 'iploc' via `#2`_.
.. _`#2`: https://github.com/lxyu/17monip/issues/2
Version 0.2.0
-------------
Released on June 4, 2014.
- update dat version to 20140601
- increased accuracy from province to city
- add command line utils
- add tests
Version 0.1.0
-------------
First release.
| 17MonIP | /17MonIP-0.2.7.tar.gz/17MonIP-0.2.7/CHANGES.rst | CHANGES.rst |
17MonIP Python Lib
==================
.. image:: http://img.shields.io/pypi/v/17MonIP.svg?style=flat
:target: https://pypi.python.org/pypi/17MonIP
.. image:: http://img.shields.io/travis/lxyu/17monip/master.svg?style=flat
:target: https://travis-ci.org/lxyu/17monip
.. image:: http://img.shields.io/pypi/dm/17MonIP.svg?style=flat
:target: https://pypi.python.org/pypi/17MonIP
IP search based on 17mon.cn, the best IP database for china.
Source: http://tool.17mon.cn
Install
-------
Supports python2.6 to python3.4 and pypy.
.. code:: bash
$ pip install 17monip
Usage
-----
.. code:: python
>>> import IP
>>> IP.find("www.baidu.com")
'中国\t浙江\t杭州'
>>> IP.find("127.0.0.1")
'本机地址\t本机地址'
CMD Util
--------
.. code:: bash
$ iploc ele.me
中国 北京 北京
$ iploc aliyun.com
中国 浙江 杭州
Changelog
---------
https://github.com/lxyu/17monip/blob/master/CHANGES.rst
| 17MonIP | /17MonIP-0.2.7.tar.gz/17MonIP-0.2.7/README.rst | README.rst |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
dev_requires = [
"flake8>=2.2.0",
"pytest>=2.6.0",
]
setup(
name="17MonIP",
version="0.2.7",
description="IP search based on 17mon.cn, the best IP database for China.",
author="Lx Yu",
author_email="github@lxyu.net",
packages=["IP", ],
package_data={'IP': ['17monipdb.dat'], },
entry_points={"console_scripts": ["iploc = IP.cmd:main", ]},
url="http://lxyu.github.io/17monip/",
license="MIT",
long_description=open("README.rst").read(),
extras_require={
"dev": dev_requires,
},
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: MIT License",
"Intended Audience :: Developers",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
]
)
| 17MonIP | /17MonIP-0.2.7.tar.gz/17MonIP-0.2.7/setup.py | setup.py |
# -*- coding: utf-8 -*-
import os
import socket
import struct
try:
import mmap
except ImportError:
mmap = None
__all__ = ['IPv4Database', 'find']
_unpack_V = lambda b: struct.unpack("<L", b)[0]
_unpack_N = lambda b: struct.unpack(">L", b)[0]
def _unpack_C(b):
if isinstance(b, int):
return b
return struct.unpack("B", b)[0]
datfile = os.path.join(os.path.dirname(__file__), "17monipdb.dat")
class IPv4Database(object):
"""Database for search IPv4 address.
The 17mon dat file format in bytes::
-----------
| 4 bytes | <- offset number
-----------------
| 256 * 4 bytes | <- first ip number index
-----------------------
| offset - 1028 bytes | <- ip index
-----------------------
| data storage |
-----------------------
"""
def __init__(self, filename=None, use_mmap=True):
if filename is None:
filename = datfile
with open(filename, 'rb') as f:
if use_mmap and mmap is not None:
buf = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
else:
buf = f.read()
use_mmap = False
self._use_mmap = use_mmap
self._buf = buf
self._offset = _unpack_N(buf[:4])
self._is_closed = False
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def close(self):
if self._use_mmap:
self._buf.close()
self._is_closed = True
def _lookup_ipv4(self, ip):
nip = socket.inet_aton(ip)
# first IP number
fip = bytearray(nip)[0]
# 4 + (fip - 1) * 4
fip_offset = fip * 4 + 4
# position in the index block
count = _unpack_V(self._buf[fip_offset:fip_offset + 4])
pos = count * 8
offset = pos + 1028
data_length = 0
data_pos = 0
lo, hi = 0, (self._offset - offset) // 8
while lo < hi:
mid = (lo + hi) // 2
mid_offset = pos + 1028 + 8 * mid
mid_val = self._buf[mid_offset: mid_offset+4]
if mid_val < nip:
lo = mid + 1
else:
hi = mid
offset = pos + 1028 + 8 * lo
if offset == self._offset:
return None
data_pos = _unpack_V(self._buf[offset + 4:offset + 7] + b'\0')
data_length = _unpack_C(self._buf[offset + 7])
offset = self._offset + data_pos - 1024
value = self._buf[offset:offset + data_length]
return value.decode('utf-8').strip()
def find(self, ip):
if self._is_closed:
raise ValueError('I/O operation on closed dat file')
return self._lookup_ipv4(ip)
def find(ip):
# keep find for compatibility
try:
ip = socket.gethostbyname(ip)
except socket.gaierror:
return
with IPv4Database() as db:
return db.find(ip)
| 17MonIP | /17MonIP-0.2.7.tar.gz/17MonIP-0.2.7/IP/ip.py | ip.py |
# -*- coding: utf-8 -*-
from .ip import find, IPv4Database
__all__ = ['IPv4Database', 'find']
| 17MonIP | /17MonIP-0.2.7.tar.gz/17MonIP-0.2.7/IP/__init__.py | __init__.py |
# -*- coding: utf-8 -*-
import argparse
from .ip import find
def main():
parser = argparse.ArgumentParser()
parser.add_argument("ip", help="ip or domain")
args = parser.parse_args()
if not args.ip:
return
print(find(args.ip))
if __name__ == '__main__':
main()
| 17MonIP | /17MonIP-0.2.7.tar.gz/17MonIP-0.2.7/IP/cmd.py | cmd.py |
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="19226331LalitAgrawal",
version="0.0.1",
author="Lalit Agrawal",
author_email="agrawal.lalit95@gmail.com",
description="A package to calculate total cart value",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/agrawallalit/Food_ordering_library",
packages=setuptools.find_packages(),
install_requires=[''],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires=">=3.6",
) | 19226331LalitAgrawal | /19226331LalitAgrawal-0.0.1.tar.gz/19226331LalitAgrawal-0.0.1/setup.py | setup.py |
class calcart:
def __init__(self, list):
self.list = []
#Function to add the price when a item is added is to the cart
def add_item_amount(self, cart):
total = 0
null = 0
if cart != null:
for item in self.list:
name, price = item # or price = item[1]
total = total + price
else:
print("Cart is Empty")
#function to substrate the price when a item is removed for the cart
def remove_item_amount(self,cart):
total = 0
null = 0
if cart == null:
print("The Cart is already empty")
else:
for item in self.list:
price = item
total = total - price
if __name__ == '__main__':
cal = calcart()
cal.add_item_amount(50)
cal.remove_item_amount(30) | 19226331LalitAgrawal | /19226331LalitAgrawal-0.0.1.tar.gz/19226331LalitAgrawal-0.0.1/addcart_properties_pkg/addcart.py | addcart.py |
import setuptools # 模块
# 让readme文件以只读的形式
with open("README.md", "rb") as f:
description = f.read().decode("utf-8")
setuptools.setup(
name="19434010112", # 当包名已经出现在pypi中已经被别人发布过,你再发布就会报403错误
version="1.0",
packages=setuptools.find_packages(),
aythor="laohu",
author_email="aaa@163.com",
description="一个打包案例",
long_description=description,
python_requires=">=3.7" # python的最低版本
) | 19434010112 | /19434010112-1.0.tar.gz/19434010112-1.0/setup.py | setup.py |
===============
199Fix
===============
199Fix provides a logging handler to push exceptions and other errors to https://199fix.com/.
Installation
============
Installation with ``pip``:
::
$ pip install 199fix
Get an API Key here https://199fix.com/signup/
Add ``'199fix.handlers.I99FixHandler'`` as a logging handler:
::
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'199fix': {
'level': 'ERROR',
'class': 'i99fix.handlers.I99FixHandler',
'filters': ['require_debug_false'],
'api_key': '[your-api-key]',
'env_name': 'production',
},
},
'loggers': {
'django': {
'handlers': ['199fix'],
'level': 'ERROR',
'propagate': True,
},
}
}
Settings
========
``level`` (built-in setting)
Change the ``level`` to ``'ERROR'`` to disable logging of 404 error messages.
``api_key`` (required)
API key , Get one here https://199fix.com/.
``env_name`` (required)
Name of the environment (e.g. production, development)
Contributing
============
* Fork the repository on GitHub and start hacking.
* Run the tests.
* Send a pull request with your changes.
| 199Fix | /199Fix-1.1.2.tar.gz/199Fix-1.1.2/README.rst | README.rst |
from distutils.core import setup
from setuptools import find_packages
import i99fix
setup(
name=i99fix.__app_name__,
packages=find_packages(exclude=('tests',)),
version=i99fix.__version__,
author='Madra David',
author_email='madra@199fix.com',
url=i99fix.__app_url__,
download_url='https://github.com/199fix/199fix/tarball/0.3',
description='199fix exception logger for Django',
license='MIT',
long_description=open('README.rst').read(),
install_requires=['Django>=1.4'],
keywords=['logging', 'uptime monitoring'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
],
)
| 199Fix | /199Fix-1.1.2.tar.gz/199Fix-1.1.2/setup.py | setup.py |
__version__ = '1.1.2'
__app_name__ = '199Fix'
__app_url__ = 'https://github.com/199fix/199fix'
| 199Fix | /199Fix-1.1.2.tar.gz/199Fix-1.1.2/i99fix/__init__.py | __init__.py |
import logging
import traceback
try:
from urllib.request import Request, urlopen
from urllib.error import HTTPError
except ImportError:
from urllib2 import Request, urlopen, HTTPError
import json
from i99fix import __version__
_DEFAULT_API_URL = 'https://199fix.com/api/logger/'
_DEFAULT_ENV_VARIABLES = ['DJANGO_SETTINGS_MODULE', ]
_DEFAULT_META_VARIABLES = ['HTTP_USER_AGENT', 'REMOTE_ADDR',
'SERVER_NAME', 'SERVER_SOFTWARE', ]
class I99FixHandler(logging.Handler):
'''
Error logger for 199fix.com
'''
def __init__(self, api_key, env_name, api_url=_DEFAULT_API_URL,
timeout=30, env_variables=_DEFAULT_ENV_VARIABLES,
meta_variables=_DEFAULT_META_VARIABLES):
logging.Handler.__init__(self)
self.api_key = api_key
self.api_url = api_url
self.env_name = env_name
self.env_variables = env_variables
self.meta_variables = meta_variables
self.timeout = timeout
def emit(self, record):
try:
message = self.generate_json(record)
self._sendMessage(message)
except Exception:
return None
def generate_json(self, record):
'''
generate json
from data
'''
exn = None
trace = None
data = {}
if record.exc_info:
_, exn, trace = record.exc_info
message = record.getMessage()
if exn:
message = "{0}: {1}".format(message, str(exn))
if hasattr(record, 'request'):
request = record.request
cgi_data = []
for key, value in request.META.items():
if key in self.meta_variables:
'''more data'''
cgi_data.append({key: value})
data['cgi_data'] = cgi_data
data['exception'] = exn.__class__.__name__ if exn else ''
data['message'] = message
data['level'] = record.levelname
trace_data = []
try:
if trace is None:
trace_data = {'file': record.pathname,
'number': str(record.lineno),
'method': record.funcName
}
else:
for pathname, lineno, funcName, text in traceback.extract_tb(trace):
trace_data = {'file': pathname,
'number': str(lineno),
'method': '%s: %s' % (funcName, text)
}
except Exception:
pass
try:
'''
request url
'''
data['url'] = request.build_absolute_uri()
except Exception:
pass
data['backtrace'] = trace_data
return data
def _sendHttpRequest(self, message={}):
'''
send json request to url
'''
try:
'''initial values'''
message['__version__'] = __version__
message['api-key'] = self.api_key
message['environment-name'] = self.env_name
req = Request(self.api_url)
req.add_header('Content-Type', 'application/json')
response = urlopen(req, json.dumps(message), timeout=self.timeout)
status = response.getcode()
except HTTPError as e:
status = e.code
return status
def _sendMessage(self, message):
'''
send message
'''
status = self._sendHttpRequest(message)
if status == 200:
return
if status == 403:
exceptionMessage = "Invalid API credentials"
elif status == 422:
exceptionMessage = "Invalid Json sent: {0}".format(message)
elif status == 500:
exceptionMessage = "Destination server is unavailable. " \
"Please check the remote server status."
elif status == 503:
exceptionMessage = "Service unavailable. You may be over your " \
"quota."
elif status == 303:
exceptionMessage = "Invalid Url for this application"
else:
exceptionMessage = "Unexpected status code {0}".format(str(status))
raise Exception('[199fix] %s' % exceptionMessage)
| 199Fix | /199Fix-1.1.2.tar.gz/199Fix-1.1.2/i99fix/handlers.py | handlers.py |
This is a simple package.
| 19CS30055-Q2 | /19CS30055_Q2-0.0.6.tar.gz/19CS30055_Q2-0.0.6/README.md | README.md |
import os
from setuptools import setup, find_packages
VERSION = '0.0.6'
DESCRIPTION = 'My package'
LONG_DESCRIPTION = 'My first Python package with a slightly longer description'
# Setting up
setup(
# the name must match the folder name 'verysimplemodule'
name="19CS30055_Q2",
version=VERSION,
author="Neha Dalmia",
author_email="<nehadalmia002@gmail.com>",
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
packages=find_packages(),
install_requires=['numpy','matplotlib','opencv-python'], # add any additional packages that
# needs to be installed along with your package. Eg: 'caer'
keywords=[],
classifiers= [
"Development Status :: 3 - Alpha",
"Intended Audience :: Education",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows",
]
)
| 19CS30055-Q2 | /19CS30055_Q2-0.0.6.tar.gz/19CS30055_Q2-0.0.6/setup.py | setup.py |
import torch
import torch.nn as nn
import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
# Class id to name mapping
COCO_INSTANCE_CATEGORY_NAMES = [
'__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', 'stop sign',
'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack', 'umbrella', 'N/A', 'N/A',
'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket',
'bottle', 'N/A', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',
'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'N/A', 'dining table',
'N/A', 'N/A', 'toilet', 'N/A', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A', 'book',
'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush'
]
# Class definition for the model
class ObjectDetectionModel(object):
'''
The blackbox object detection model (Faster RCNN for those who want to know).
Given an image as numpy array (3, H, W), it detects objects (generates their category ids and bounding boxes).
'''
# __init__ function
def __init__(self):
self.model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
self.model.eval()
# function for calling the faster-rcnn model
def __call__(self, input):
'''
Arguments:
input (numpy array): A (3, H, W) array of numbers in [0, 1] representing the image.
Returns:
pred_boxes (list): list of bounding boxes, [[x1 y1 x2 y2], ..] where (x1, y1) are the coordinates of the top left corner
and (x2, y2) are the coordinates of the bottom right corner.
pred_class (list): list of predicted classes
pred_score (list): list of the probability (confidence) of prediction of each of the bounding boxes
Tip:
You can print the outputs to get better clarity :)
'''
input_tensor = torch.from_numpy(input)
input_tensor = input_tensor.type(torch.FloatTensor)
input_tensor = input_tensor.unsqueeze(0)
predictions = self.model(input_tensor)
pred_class = [COCO_INSTANCE_CATEGORY_NAMES[i] for i in list(predictions[0]['labels'].numpy())] # Get the Prediction Score
pred_boxes = [[(i[0], i[1]), (i[2], i[3])] for i in list(predictions[0]['boxes'].detach().numpy())] # Bounding boxes
pred_score = list(predictions[0]['scores'].detach().numpy())
return pred_boxes, pred_class, pred_score
| 19CS30055-Q2 | /19CS30055_Q2-0.0.6.tar.gz/19CS30055_Q2-0.0.6/my_package/model.py | model.py |
from .model import ObjectDetectionModel
| 19CS30055-Q2 | /19CS30055_Q2-0.0.6.tar.gz/19CS30055_Q2-0.0.6/my_package/__init__.py | __init__.py |
#Imports
import numpy as np
import cv2
def plot_boxes(pred_class, pred_boxes,image, path, image_name, color = None):
arr = image.astype('float32')
arr = cv2.cvtColor(arr, cv2.COLOR_RGB2BGR)
colorsarr = []
if(color==None):
colorsarr =[(1.0,0,1.0),(0,1.0,1.0),(1.0,0,0),(0,0,1.0),(0,1.0,0)]
else:
colorsarr = [color,color,color,color,color]
for idx,box in enumerate(pred_boxes):
if(idx>=5):
break
arr = cv2.rectangle(arr, box[0], box[1], colorsarr[idx], 2)
cv2.putText(arr, pred_class[idx], (box[0][0], max(box[0][1],20)), cv2.FONT_HERSHEY_DUPLEX, 1, colorsarr[idx], 2)
cv2.imwrite(str(path+'/'+image_name+'.jpg'), 255*arr)
return cv2.cvtColor(arr, cv2.COLOR_BGR2RGB)
#cv2.imshow('Image',arr)
#cv2.waitKey(100)
# Write the required arguments
# The function should plot the predicted boxes on the images and save them.
# Tip: keep the dimensions of the output image less than 800 to avoid RAM crashes.
| 19CS30055-Q2 | /19CS30055_Q2-0.0.6.tar.gz/19CS30055_Q2-0.0.6/my_package/analysis/visualize.py | visualize.py |
from .visualize import plot_boxes
| 19CS30055-Q2 | /19CS30055_Q2-0.0.6.tar.gz/19CS30055_Q2-0.0.6/my_package/analysis/__init__.py | __init__.py |
#Imports
import numpy as np
import json
from matplotlib import image
from matplotlib import pyplot
from pathlib import Path
class Dataset(object):
'''
A class for the dataset that will return data items as per the given index
'''
def __init__(self, annotation_file, transforms = None):
self.annotation_file = annotation_file
self.transforms = transforms
self.datalist = []
with open(self.annotation_file) as f:
for line in f:
data = json.loads(line)
gt_bboxes = np.array([])
for box in data['bboxes']:
added = np.append(box['category_id'], box['bbox'])
if(len(gt_bboxes) == 0):
gt_bboxes = added
gt_bboxes = gt_bboxes.reshape(1,5)
else:
gt_bboxes = np.vstack((gt_bboxes,added))
p = Path(annotation_file)
dir_data = str(p.parent.absolute())
image1 = image.imread(dir_data + '\\' + data['img_fn'])
image1 = np.interp(image1, (image1.min(), image1.max()), (0, +1))
if(self.transforms is not None):
for t in self.transforms:
image1 = t(image1)
image1 = np.transpose(image1, (2,0,1))
self.datalist.append([image1, gt_bboxes])
'''
Arguments:
annotation_file: path to the annotation file
transforms: list of transforms (class instances)
For instance, [<class 'RandomCrop'>, <class 'Rotate'>]
'''
def __len__(self):
return(len(self.datalist))
'''
return the number of data points in the dataset
'''
def __getitem__(self, idx):
d= {}
d["annotations"] = self.datalist[idx][1]
d["image"] = self.datalist[idx][0]
return d
'''
return the dataset element for the index: "idx"
Arguments:
idx: index of the data element.
Returns: A dictionary with:
image: image (in the form of a numpy array) (shape: (3, H, W))
gt_bboxes: N X 5 array where N is the number of bounding boxes, each
consisting of [class, x1, y1, x2, y2]
x1 and x2 lie between 0 and width of the image,
y1 and y2 lie between 0 and height of the image.
You need to do the following,
1. Extract the correct annotation using the idx provided.
2. Read the image and convert it into a numpy array (wont be necessary
with some libraries). The shape of the array would be (3, H, W).
3. Scale the values in the array to be with [0, 1].
4. Create a dictonary with both the image and annotations
4. Perform the desired transformations.
5. Return the transformed image and annotations as specified. '''
| 19CS30055-Q2 | /19CS30055_Q2-0.0.6.tar.gz/19CS30055_Q2-0.0.6/my_package/data/dataset.py | dataset.py |
from .dataset import Dataset
| 19CS30055-Q2 | /19CS30055_Q2-0.0.6.tar.gz/19CS30055_Q2-0.0.6/my_package/data/__init__.py | __init__.py |
#Imports
import numpy as np
class FlipImage(object):
'''
Flips the image.
'''
def __init__(self, flip_type='horizontal'):
'''
Arguments:
flip_type: 'horizontal' or 'vertical' Default: 'horizontal'
'''
self.type = flip_type
# Write your code here
def __call__(self, image):
if(self.type == 'horizontal'):
return np.flip(image, axis = 0)
elif(self.type == 'vertical'):
return np.flip(image, axis = 1)
'''
Arguments:
image (numpy array or PIL image)
Returns:
image (numpy array or PIL image)
'''
| 19CS30055-Q2 | /19CS30055_Q2-0.0.6.tar.gz/19CS30055_Q2-0.0.6/my_package/data/transforms/flip.py | flip.py |
#Imports
import numpy as np
class CropImage(object):
'''
Performs either random cropping or center cropping.
'''
def __init__(self, shape, crop_type='center'):
self.crop_type = crop_type
self.shape = shape
'''
Arguments:
shape: output shape of the crop (h, w)
crop_type: center crop or random crop. Default: center
'''
def __call__(self, image):
'''
Arguments:
image (numpy array or PIL image)
Returns:
image (numpy array or PIL image)
'''
y,x,_ = image.shape
cropx = self.shape[1]
cropy = self.shape[0]
if(self.crop_type == 'center'):
startx = x//2-(cropx//2)
starty = y//2-(cropy//2)
return image[starty:starty+cropy,startx:startx+cropx]
elif(self.crop_type == 'random'):
startx = np.random.randint(0,x-cropx+1)
starty = np.random.randint(0,y-cropy+1)
return image[starty:starty+cropy,startx:startx+cropx]
| 19CS30055-Q2 | /19CS30055_Q2-0.0.6.tar.gz/19CS30055_Q2-0.0.6/my_package/data/transforms/crop.py | crop.py |
#Imports
import scipy
from scipy import ndimage
import numpy as np
class RotateImage(object):
'''
Rotates the image about the centre of the image.
'''
def __init__(self, degrees):
'''
Arguments:
degrees: rotation degree.
'''
self.degrees = degrees
# Write your code here
def __call__(self, sample):
'''
Arguments:
image (numpy array or PIL image)
Returns:
image (numpy array or PIL image)
'''
return scipy.ndimage.rotate(sample, self.degrees)
| 19CS30055-Q2 | /19CS30055_Q2-0.0.6.tar.gz/19CS30055_Q2-0.0.6/my_package/data/transforms/rotate.py | rotate.py |
#Imports
import numpy as np
from scipy.ndimage.filters import gaussian_filter
class BlurImage(object):
'''
Applies Gaussian Blur on the image.
'''
def __init__(self, radius):
self.radius = radius
'''
Arguments:
radius (int): radius to blur
'''
# Write your code here
def __call__(self, image):
'''
Arguments:
image (numpy array or PIL Image)
Returns:
image (numpy array or PIL Image)
'''
return (gaussian_filter(image, sigma=[self.radius, self.radius, 0]))
| 19CS30055-Q2 | /19CS30055_Q2-0.0.6.tar.gz/19CS30055_Q2-0.0.6/my_package/data/transforms/blur.py | blur.py |
#Imports
import numpy as np
from skimage.transform import resize
import cv2
import math
class RescaleImage(object):
'''
Rescales the image to a given size.
'''
def __init__(self, output_size):
self.output_size = output_size
''' Arguments:
output_size (tuple or int): Desired output size. If tuple, output is
matched to output_size. If int, smaller of image edges is matched
to output_size keeping aspect ratio the same.
'''
# Write your code here
def __call__(self, image):
'''
Arguments:
image (numpy array or PIL image)
Returns:
image (numpy array or PIL image)
Note: You do not need to resize the bounding boxes. ONLY RESIZE THE IMAGE.
'''
image_resized = np.array([])
if(isinstance(self.output_size, tuple)):
image_resized = resize(image, self.output_size)
return image_resized
elif(isinstance(self.output_size, int)):
h, w, ch = image.shape
if(w < h):
image_resized = resize(image, (math.floor(h*self.output_size/w), self.output_size), anti_aliasing = True)
return image_resized
else:
image_resized = resize(image, (self.output_size, math.floor(w*self.output_size/h)), anti_aliasing = True)
return image_resized | 19CS30055-Q2 | /19CS30055_Q2-0.0.6.tar.gz/19CS30055_Q2-0.0.6/my_package/data/transforms/rescale.py | rescale.py |
from .blur import BlurImage
from .crop import CropImage
from .flip import FlipImage
from .rotate import RotateImage
from .rescale import RescaleImage
| 19CS30055-Q2 | /19CS30055_Q2-0.0.6.tar.gz/19CS30055_Q2-0.0.6/my_package/data/transforms/__init__.py | __init__.py |
import torch
import torch.nn as nn
import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
# Class id to name mapping
COCO_INSTANCE_CATEGORY_NAMES = [
'__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', 'stop sign',
'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack', 'umbrella', 'N/A', 'N/A',
'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket',
'bottle', 'N/A', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',
'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'N/A', 'dining table',
'N/A', 'N/A', 'toilet', 'N/A', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A', 'book',
'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush'
]
# Class definition for the model
class ObjectDetectionModel(object):
'''
The blackbox object detection model (Faster RCNN for those who want to know).
Given an image as numpy array (3, H, W), it detects objects (generates their category ids and bounding boxes).
'''
# __init__ function
def __init__(self):
self.model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
self.model.eval()
# function for calling the faster-rcnn model
def __call__(self, input):
'''
Arguments:
input (numpy array): A (3, H, W) array of numbers in [0, 1] representing the image.
Returns:
pred_boxes (list): list of bounding boxes, [[x1 y1 x2 y2], ..] where (x1, y1) are the coordinates of the top left corner
and (x2, y2) are the coordinates of the bottom right corner.
pred_class (list): list of predicted classes
pred_score (list): list of the probability (confidence) of prediction of each of the bounding boxes
Tip:
You can print the outputs to get better clarity :)
'''
input_tensor = torch.from_numpy(input)
input_tensor = input_tensor.type(torch.FloatTensor)
input_tensor = input_tensor.unsqueeze(0)
predictions = self.model(input_tensor)
pred_class = [COCO_INSTANCE_CATEGORY_NAMES[i] for i in list(predictions[0]['labels'].numpy())] # Get the Prediction Score
pred_boxes = [[(i[0], i[1]), (i[2], i[3])] for i in list(predictions[0]['boxes'].detach().numpy())] # Bounding boxes
pred_score = list(predictions[0]['scores'].detach().numpy())
return pred_boxes, pred_class, pred_score
| 19CS30055-package | /19CS30055_package-0.0.6-py3-none-any.whl/my_package/model.py | model.py |
from .model import ObjectDetectionModel
| 19CS30055-package | /19CS30055_package-0.0.6-py3-none-any.whl/my_package/__init__.py | __init__.py |
#Imports
import numpy as np
import cv2
def plot_boxes(pred_class, pred_boxes,image, path, image_name, color = None):
arr = image.astype('float32')
arr = cv2.cvtColor(arr, cv2.COLOR_RGB2BGR)
colorsarr = []
if(color==None):
colorsarr =[(1.0,0,1.0),(0,1.0,1.0),(1.0,0,0),(0,0,1.0),(0,1.0,0)]
else:
colorsarr = [color,color,color,color,color]
for idx,box in enumerate(pred_boxes):
if(idx>=5):
break
arr = cv2.rectangle(arr, box[0], box[1], colorsarr[idx], 2)
cv2.putText(arr, pred_class[idx], (box[0][0], max(box[0][1],20)), cv2.FONT_HERSHEY_DUPLEX, 1, colorsarr[idx], 2)
cv2.imwrite(str(path+'/'+image_name+'.jpg'), 255*arr)
return cv2.cvtColor(arr, cv2.COLOR_BGR2RGB)
#cv2.imshow('Image',arr)
#cv2.waitKey(100)
# Write the required arguments
# The function should plot the predicted boxes on the images and save them.
# Tip: keep the dimensions of the output image less than 800 to avoid RAM crashes.
| 19CS30055-package | /19CS30055_package-0.0.6-py3-none-any.whl/my_package/analysis/visualize.py | visualize.py |
from .visualize import plot_boxes
| 19CS30055-package | /19CS30055_package-0.0.6-py3-none-any.whl/my_package/analysis/__init__.py | __init__.py |
#Imports
import numpy as np
import json
from matplotlib import image
from matplotlib import pyplot
from pathlib import Path
class Dataset(object):
'''
A class for the dataset that will return data items as per the given index
'''
def __init__(self, annotation_file, transforms = None):
self.annotation_file = annotation_file
self.transforms = transforms
self.datalist = []
with open(self.annotation_file) as f:
for line in f:
data = json.loads(line)
gt_bboxes = np.array([])
for box in data['bboxes']:
added = np.append(box['category_id'], box['bbox'])
if(len(gt_bboxes) == 0):
gt_bboxes = added
gt_bboxes = gt_bboxes.reshape(1,5)
else:
gt_bboxes = np.vstack((gt_bboxes,added))
p = Path(annotation_file)
dir_data = str(p.parent.absolute())
image1 = image.imread(dir_data + '\\' + data['img_fn'])
image1 = np.interp(image1, (image1.min(), image1.max()), (0, +1))
if(self.transforms is not None):
for t in self.transforms:
image1 = t(image1)
image1 = np.transpose(image1, (2,0,1))
self.datalist.append([image1, gt_bboxes])
'''
Arguments:
annotation_file: path to the annotation file
transforms: list of transforms (class instances)
For instance, [<class 'RandomCrop'>, <class 'Rotate'>]
'''
def __len__(self):
return(len(self.datalist))
'''
return the number of data points in the dataset
'''
def __getitem__(self, idx):
d= {}
d["annotations"] = self.datalist[idx][1]
d["image"] = self.datalist[idx][0]
return d
'''
return the dataset element for the index: "idx"
Arguments:
idx: index of the data element.
Returns: A dictionary with:
image: image (in the form of a numpy array) (shape: (3, H, W))
gt_bboxes: N X 5 array where N is the number of bounding boxes, each
consisting of [class, x1, y1, x2, y2]
x1 and x2 lie between 0 and width of the image,
y1 and y2 lie between 0 and height of the image.
You need to do the following,
1. Extract the correct annotation using the idx provided.
2. Read the image and convert it into a numpy array (wont be necessary
with some libraries). The shape of the array would be (3, H, W).
3. Scale the values in the array to be with [0, 1].
4. Create a dictonary with both the image and annotations
4. Perform the desired transformations.
5. Return the transformed image and annotations as specified. '''
| 19CS30055-package | /19CS30055_package-0.0.6-py3-none-any.whl/my_package/data/dataset.py | dataset.py |
from .dataset import Dataset
| 19CS30055-package | /19CS30055_package-0.0.6-py3-none-any.whl/my_package/data/__init__.py | __init__.py |
#Imports
import numpy as np
class FlipImage(object):
'''
Flips the image.
'''
def __init__(self, flip_type='horizontal'):
'''
Arguments:
flip_type: 'horizontal' or 'vertical' Default: 'horizontal'
'''
self.type = flip_type
# Write your code here
def __call__(self, image):
if(self.type == 'horizontal'):
return np.flip(image, axis = 0)
elif(self.type == 'vertical'):
return np.flip(image, axis = 1)
'''
Arguments:
image (numpy array or PIL image)
Returns:
image (numpy array or PIL image)
'''
| 19CS30055-package | /19CS30055_package-0.0.6-py3-none-any.whl/my_package/data/transforms/flip.py | flip.py |
#Imports
import numpy as np
class CropImage(object):
'''
Performs either random cropping or center cropping.
'''
def __init__(self, shape, crop_type='center'):
self.crop_type = crop_type
self.shape = shape
'''
Arguments:
shape: output shape of the crop (h, w)
crop_type: center crop or random crop. Default: center
'''
def __call__(self, image):
'''
Arguments:
image (numpy array or PIL image)
Returns:
image (numpy array or PIL image)
'''
y,x,_ = image.shape
cropx = self.shape[1]
cropy = self.shape[0]
if(self.crop_type == 'center'):
startx = x//2-(cropx//2)
starty = y//2-(cropy//2)
return image[starty:starty+cropy,startx:startx+cropx]
elif(self.crop_type == 'random'):
startx = np.random.randint(0,x-cropx+1)
starty = np.random.randint(0,y-cropy+1)
return image[starty:starty+cropy,startx:startx+cropx]
| 19CS30055-package | /19CS30055_package-0.0.6-py3-none-any.whl/my_package/data/transforms/crop.py | crop.py |
#Imports
import scipy
from scipy import ndimage
import numpy as np
class RotateImage(object):
'''
Rotates the image about the centre of the image.
'''
def __init__(self, degrees):
'''
Arguments:
degrees: rotation degree.
'''
self.degrees = degrees
# Write your code here
def __call__(self, sample):
'''
Arguments:
image (numpy array or PIL image)
Returns:
image (numpy array or PIL image)
'''
return scipy.ndimage.rotate(sample, self.degrees)
| 19CS30055-package | /19CS30055_package-0.0.6-py3-none-any.whl/my_package/data/transforms/rotate.py | rotate.py |
#Imports
import numpy as np
from scipy.ndimage.filters import gaussian_filter
class BlurImage(object):
'''
Applies Gaussian Blur on the image.
'''
def __init__(self, radius):
self.radius = radius
'''
Arguments:
radius (int): radius to blur
'''
# Write your code here
def __call__(self, image):
'''
Arguments:
image (numpy array or PIL Image)
Returns:
image (numpy array or PIL Image)
'''
return (gaussian_filter(image, sigma=[self.radius, self.radius, 0]))
| 19CS30055-package | /19CS30055_package-0.0.6-py3-none-any.whl/my_package/data/transforms/blur.py | blur.py |
#Imports
import numpy as np
from skimage.transform import resize
import cv2
import math
class RescaleImage(object):
'''
Rescales the image to a given size.
'''
def __init__(self, output_size):
self.output_size = output_size
''' Arguments:
output_size (tuple or int): Desired output size. If tuple, output is
matched to output_size. If int, smaller of image edges is matched
to output_size keeping aspect ratio the same.
'''
# Write your code here
def __call__(self, image):
'''
Arguments:
image (numpy array or PIL image)
Returns:
image (numpy array or PIL image)
Note: You do not need to resize the bounding boxes. ONLY RESIZE THE IMAGE.
'''
image_resized = np.array([])
if(isinstance(self.output_size, tuple)):
image_resized = resize(image, self.output_size)
return image_resized
elif(isinstance(self.output_size, int)):
h, w, ch = image.shape
if(w < h):
image_resized = resize(image, (math.floor(h*self.output_size/w), self.output_size), anti_aliasing = True)
return image_resized
else:
image_resized = resize(image, (self.output_size, math.floor(w*self.output_size/h)), anti_aliasing = True)
return image_resized | 19CS30055-package | /19CS30055_package-0.0.6-py3-none-any.whl/my_package/data/transforms/rescale.py | rescale.py |
from .blur import BlurImage
from .crop import CropImage
from .flip import FlipImage
from .rotate import RotateImage
from .rescale import RescaleImage
| 19CS30055-package | /19CS30055_package-0.0.6-py3-none-any.whl/my_package/data/transforms/__init__.py | __init__.py |
This is a simple package.
| 19CS30055-package1 | /19CS30055_package1-0.0.6.tar.gz/19CS30055_package1-0.0.6/README.md | README.md |
import os
from setuptools import setup, find_packages
VERSION = '0.0.6'
DESCRIPTION = 'My package'
LONG_DESCRIPTION = 'My first Python package with a slightly longer description'
# Setting up
setup(
# the name must match the folder name 'verysimplemodule'
name="19CS30055_package1",
version=VERSION,
author="Neha Dalmia",
author_email="<nehadalmia002@gmail.com>",
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
packages=find_packages(),
install_requires=['numpy','matplotlib','opencv'], # add any additional packages that
# needs to be installed along with your package. Eg: 'caer'
keywords=[],
classifiers= [
"Development Status :: 3 - Alpha",
"Intended Audience :: Education",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows",
]
)
| 19CS30055-package1 | /19CS30055_package1-0.0.6.tar.gz/19CS30055_package1-0.0.6/setup.py | setup.py |
import torch
import torch.nn as nn
import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
# Class id to name mapping
COCO_INSTANCE_CATEGORY_NAMES = [
'__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', 'stop sign',
'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack', 'umbrella', 'N/A', 'N/A',
'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket',
'bottle', 'N/A', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',
'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'N/A', 'dining table',
'N/A', 'N/A', 'toilet', 'N/A', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A', 'book',
'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush'
]
# Class definition for the model
class ObjectDetectionModel(object):
'''
The blackbox object detection model (Faster RCNN for those who want to know).
Given an image as numpy array (3, H, W), it detects objects (generates their category ids and bounding boxes).
'''
# __init__ function
def __init__(self):
self.model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
self.model.eval()
# function for calling the faster-rcnn model
def __call__(self, input):
'''
Arguments:
input (numpy array): A (3, H, W) array of numbers in [0, 1] representing the image.
Returns:
pred_boxes (list): list of bounding boxes, [[x1 y1 x2 y2], ..] where (x1, y1) are the coordinates of the top left corner
and (x2, y2) are the coordinates of the bottom right corner.
pred_class (list): list of predicted classes
pred_score (list): list of the probability (confidence) of prediction of each of the bounding boxes
Tip:
You can print the outputs to get better clarity :)
'''
input_tensor = torch.from_numpy(input)
input_tensor = input_tensor.type(torch.FloatTensor)
input_tensor = input_tensor.unsqueeze(0)
predictions = self.model(input_tensor)
pred_class = [COCO_INSTANCE_CATEGORY_NAMES[i] for i in list(predictions[0]['labels'].numpy())] # Get the Prediction Score
pred_boxes = [[(i[0], i[1]), (i[2], i[3])] for i in list(predictions[0]['boxes'].detach().numpy())] # Bounding boxes
pred_score = list(predictions[0]['scores'].detach().numpy())
return pred_boxes, pred_class, pred_score
| 19CS30055-package1 | /19CS30055_package1-0.0.6.tar.gz/19CS30055_package1-0.0.6/my_package/model.py | model.py |
from .model import ObjectDetectionModel
| 19CS30055-package1 | /19CS30055_package1-0.0.6.tar.gz/19CS30055_package1-0.0.6/my_package/__init__.py | __init__.py |
#Imports
import numpy as np
import cv2
def plot_boxes(pred_class, pred_boxes,image, path, image_name, color = None):
arr = image.astype('float32')
arr = cv2.cvtColor(arr, cv2.COLOR_RGB2BGR)
colorsarr = []
if(color==None):
colorsarr =[(1.0,0,1.0),(0,1.0,1.0),(1.0,0,0),(0,0,1.0),(0,1.0,0)]
else:
colorsarr = [color,color,color,color,color]
for idx,box in enumerate(pred_boxes):
if(idx>=5):
break
arr = cv2.rectangle(arr, box[0], box[1], colorsarr[idx], 2)
cv2.putText(arr, pred_class[idx], (box[0][0], max(box[0][1],20)), cv2.FONT_HERSHEY_DUPLEX, 1, colorsarr[idx], 2)
cv2.imwrite(str(path+'/'+image_name+'.jpg'), 255*arr)
return cv2.cvtColor(arr, cv2.COLOR_BGR2RGB)
#cv2.imshow('Image',arr)
#cv2.waitKey(100)
# Write the required arguments
# The function should plot the predicted boxes on the images and save them.
# Tip: keep the dimensions of the output image less than 800 to avoid RAM crashes.
| 19CS30055-package1 | /19CS30055_package1-0.0.6.tar.gz/19CS30055_package1-0.0.6/my_package/analysis/visualize.py | visualize.py |
from .visualize import plot_boxes
| 19CS30055-package1 | /19CS30055_package1-0.0.6.tar.gz/19CS30055_package1-0.0.6/my_package/analysis/__init__.py | __init__.py |
#Imports
import numpy as np
import json
from matplotlib import image
from matplotlib import pyplot
from pathlib import Path
class Dataset(object):
'''
A class for the dataset that will return data items as per the given index
'''
def __init__(self, annotation_file, transforms = None):
self.annotation_file = annotation_file
self.transforms = transforms
self.datalist = []
with open(self.annotation_file) as f:
for line in f:
data = json.loads(line)
gt_bboxes = np.array([])
for box in data['bboxes']:
added = np.append(box['category_id'], box['bbox'])
if(len(gt_bboxes) == 0):
gt_bboxes = added
gt_bboxes = gt_bboxes.reshape(1,5)
else:
gt_bboxes = np.vstack((gt_bboxes,added))
p = Path(annotation_file)
dir_data = str(p.parent.absolute())
image1 = image.imread(dir_data + '\\' + data['img_fn'])
image1 = np.interp(image1, (image1.min(), image1.max()), (0, +1))
if(self.transforms is not None):
for t in self.transforms:
image1 = t(image1)
image1 = np.transpose(image1, (2,0,1))
self.datalist.append([image1, gt_bboxes])
'''
Arguments:
annotation_file: path to the annotation file
transforms: list of transforms (class instances)
For instance, [<class 'RandomCrop'>, <class 'Rotate'>]
'''
def __len__(self):
return(len(self.datalist))
'''
return the number of data points in the dataset
'''
def __getitem__(self, idx):
d= {}
d["annotations"] = self.datalist[idx][1]
d["image"] = self.datalist[idx][0]
return d
'''
return the dataset element for the index: "idx"
Arguments:
idx: index of the data element.
Returns: A dictionary with:
image: image (in the form of a numpy array) (shape: (3, H, W))
gt_bboxes: N X 5 array where N is the number of bounding boxes, each
consisting of [class, x1, y1, x2, y2]
x1 and x2 lie between 0 and width of the image,
y1 and y2 lie between 0 and height of the image.
You need to do the following,
1. Extract the correct annotation using the idx provided.
2. Read the image and convert it into a numpy array (wont be necessary
with some libraries). The shape of the array would be (3, H, W).
3. Scale the values in the array to be with [0, 1].
4. Create a dictonary with both the image and annotations
4. Perform the desired transformations.
5. Return the transformed image and annotations as specified. '''
| 19CS30055-package1 | /19CS30055_package1-0.0.6.tar.gz/19CS30055_package1-0.0.6/my_package/data/dataset.py | dataset.py |
from .dataset import Dataset
| 19CS30055-package1 | /19CS30055_package1-0.0.6.tar.gz/19CS30055_package1-0.0.6/my_package/data/__init__.py | __init__.py |
#Imports
import numpy as np
class FlipImage(object):
'''
Flips the image.
'''
def __init__(self, flip_type='horizontal'):
'''
Arguments:
flip_type: 'horizontal' or 'vertical' Default: 'horizontal'
'''
self.type = flip_type
# Write your code here
def __call__(self, image):
if(self.type == 'horizontal'):
return np.flip(image, axis = 0)
elif(self.type == 'vertical'):
return np.flip(image, axis = 1)
'''
Arguments:
image (numpy array or PIL image)
Returns:
image (numpy array or PIL image)
'''
| 19CS30055-package1 | /19CS30055_package1-0.0.6.tar.gz/19CS30055_package1-0.0.6/my_package/data/transforms/flip.py | flip.py |
#Imports
import numpy as np
class CropImage(object):
'''
Performs either random cropping or center cropping.
'''
def __init__(self, shape, crop_type='center'):
self.crop_type = crop_type
self.shape = shape
'''
Arguments:
shape: output shape of the crop (h, w)
crop_type: center crop or random crop. Default: center
'''
def __call__(self, image):
'''
Arguments:
image (numpy array or PIL image)
Returns:
image (numpy array or PIL image)
'''
y,x,_ = image.shape
cropx = self.shape[1]
cropy = self.shape[0]
if(self.crop_type == 'center'):
startx = x//2-(cropx//2)
starty = y//2-(cropy//2)
return image[starty:starty+cropy,startx:startx+cropx]
elif(self.crop_type == 'random'):
startx = np.random.randint(0,x-cropx+1)
starty = np.random.randint(0,y-cropy+1)
return image[starty:starty+cropy,startx:startx+cropx]
| 19CS30055-package1 | /19CS30055_package1-0.0.6.tar.gz/19CS30055_package1-0.0.6/my_package/data/transforms/crop.py | crop.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.