<commit_before>requirejs(["JSZip","UI","FS","NewProjectDialog","Encoding","T1Map"],
        function (JSZip,UI,FS,NPD,Encoding,T1Map) {
    var dragMsg="ここにTonyu1プロジェクトフォルダのzipファイルをドラッグ＆ドロップ";
    var dragPoint=UI("div", {style:"margin:10px; padding:10px; border:solid blue 2px;",
        on:{dragover: s, dragenter: s, drop:dropAdd}},dragMsg
    ).appendTo("body");
    function s(e) {
        e.stopPropagation();
        e.preventDefault();

    }
    function fromSJIS(zipObj) {
        var sjisArray =zipObj.asUint8Array();
        //console.log("sjis",sjisArray);
        var res= Encoding.convert(sjisArray, {
            from: 'SJIS',
            to: 'Unicode',
            type:"string"
        });
        //console.log("sjsires",res);
        return res;
    }
    var zip;
    function dropAdd(e) {
        try {
            eo=e.originalEvent;
            var file = eo.dataTransfer.files[0];
            console.log(file);
            var rd = new FileReader();
            rd.onload = function(e){
                var ary = new Uint8Array(rd.result);
                zip=new JSZip(ary);
                start(file.name.replace(/\.zip$/i,""));
            };
            rd.readAsArrayBuffer(file);
        }catch (e) {
            console.log(e);
        }
        e.stopPropagation();
        e.preventDefault();
        return false;
    }
    var mem;
    function start(name) {
        var diag=$("<div>").appendTo("body");
        diag.
        append($("<h1>").text("インポート先のフォルダを入力してください")).
        append( NPD.embed(FS.get("/Tonyu/Projects/"), extract ,{defName:name} ) );
    }
    var convFiles;
    var dstDir;
    var rsrc;
    function extract(dir) {
        mem={};
        rsrc={
                images:[{name:"$pat_ball1",url:"images/Ball.png"}],
                sounds:[]
        };
        var base;
        dstDir=dir;
        for (var fn in zip.files) {
            var f=FS.get("/"+fn);
            if (f.name()=="default.tonyuprj") {
                base=f.up();
                break;
            }
        }
        convFiles={};
        for (var fn in zip.files) {
            var f=FS.get("/"+fn);
            var rp=f.relPath(base);
            var fb=zip.files[fn];
            convFiles[ dir.rel(rp).path()] = fb;
        }
        console.log(convFiles);
        for (var fn in convFiles) {
            var fb=convFiles[fn];
            var f=FS.get(fn);
            if (f.name()=="default.tonyuprj") {
                var tprj=$("<div>").html(fromSJIS( fb )).appendTo("body");
                parseTPRJ(tprj);
                break;
            }
        }
    }
    function parseTPRJ(tprj) {
        var classes=tprj.find("class");
        var pages=tprj.find("page");
        copyClasses(classes);
        copyPages(pages);
        mem[dstDir.rel("res.json")]=JSON.stringify(rsrc);
        //console.log(mem);
        cpTmp("SpriteChar");
        cpTmp("PlainChar");
        cpTmp("TextChar");
        cpTmp("SecretChar");
        cpTmp("DxChar");
        cpTmp("T1Text");
        cpTmp("T1Line");
        cpTmp("T1Map");
        cpTmp("T1Page");
        cpTmp("MediaPlayer");
        cpTmp("Boot");
        console.log(mem);
        //console.log(JSON.stringify(mem));
        for (var fn in mem) {
            FS.get(fn).text(mem[fn]);
        }
    }
    function cpTmp(fn) {
        mem[dstDir.rel(fn+".tonyu")]=FS.get("/Tonyu/Projects/Tonyu1/").
        rel(fn+".tonyu").text();
    }
    function copyClasses(classes) {
        classes.each(function () {
            var fn=$(this).attr("src");
            var f=dstDir.rel(fn);
            console.log(f.path());
            mem[f.path()]=fromSJIS( convFiles[f.path()]);//.asText();
        });
    }
    function copyPages(pages) {
        pages.each(function () {
            var fn=$(this).attr("src");
            copyPage(dstDir.rel(fn));
        });
    }
    function copyPage(pageF) {
        var cmmlSrc=fromSJIS( convFiles[pageF.path()]); //.asText();
        var pg=$("<div>").html(cmmlSrc).appendTo("body");
        var fn="Page_"+pageF.truncExt(".cmml")+".tonyu";
        console.log("Page", fn);
        var globals=pg.find("globalvalue");
        var buf="extends T1Page;\n";
        buf+="initGlobals();\n";
        globals.each(function () {
            buf+=$(this).attr("name")+"="+$(this).attr("value")+";\n";
        });
        buf+="$Screen.resize($screenWidth,$screenHeight);\n";
        var pats=pg.find("cpattern");
        copyImages(pats);

        var gens=pg.find("generator");
        gens.each(function () {
            var a=this.attributes;
            var klass=$(this).attr("classname");
            if (klass=="Map") {
                buf+=genMap( $(this) );
                return;
            }
            buf+=$(this).attr("name")+"= new "+klass+"{";
            var com="";
            for (var i=0 ; i<a.length; i++) {
                var n=a[i].name;
                var r=/inst_(.*)/.exec(n);
                if (r) {
                    buf+=com+r[1]+": "+val(a[i].value);
                    com=", ";
                }
            }
            buf+="};\n";
        });
        mem[dstDir.rel(fn).path()]=buf;
    }
    function val(v) {
        return v.replace(/%22/g,"\"");
    }
    function genMap(map) {
        console.log("map", map);
        var src=map.attr("src");
        var mapF=convFiles[dstDir.rel(src)];
        var ary=mapF.asUint8Array();
        var pwidth=map.attr("inst_pwidth");
        var pheight=map.attr("inst_pheight");
        var width=map.attr("inst_width");
        var height=map.attr("inst_height");
        console.log(pwidth, pheight, width, height,ary);
        var buf="";
        var mapFile=dstDir.rel("maps/").rel(dstDir.rel(src).name());
        buf+=T1Map(pwidth, pheight, width, height,ary,mapFile, mem);
        return buf;
    }
    function copyImages(pats) {
        pats.each(function () {
            var name=$(this).attr("name");
            //name=name.replace(/^\$/,"$pat_");
            var src=$(this).attr("src");
            var imgFile=dstDir.rel(src).path();
            var o=convFiles[imgFile];
            if (!o) {
                console.log(convFiles);
                throw "Image file not found :"+imgFile;
            }
            var fn=dstDir.rel(src).name();
            //console.log("pats", o);
            var buf="";
            var a=o.asUint8Array();
            var s=btoa(String.fromCharCode.apply(null, a));
            s="data:image/png;base64,"+s;
            //$("<img>").attr("src",s).appendTo("body");
            //console.log("patss", s);
            var url="images/"+fn;
            mem[dstDir.rel(url)]=s;
            rsrc.images.push({name:name , url:"ls:"+url });
        });

    }
});<commit_msg>import tonyu1<commit_after>requirejs(["JSZip","UI","FS","NewProjectDialog","Encoding","T1Map"],
        function (JSZip,UI,FS,NPD,Encoding,T1Map) {
    var dragMsg="ここにTonyu1プロジェクトフォルダのzipファイルをドラッグ＆ドロップ";
    var dragPoint=UI("div", {style:"margin:10px; padding:10px; border:solid blue 2px;",
        on:{dragover: s, dragenter: s, drop:dropAdd}},dragMsg
    ).appendTo("body");
    function s(e) {
        e.stopPropagation();
        e.preventDefault();

    }
    function fromSJIS(zipObj) {
        var sjisArray =zipObj.asUint8Array();
        //console.log("sjis",sjisArray);
        var res= Encoding.convert(sjisArray, {
            from: 'SJIS',
            to: 'Unicode',
            type:"string"
        });
        //console.log("sjsires",res);
        return res;
    }
    var zip;
    function dropAdd(e) {
        try {
            eo=e.originalEvent;
            var file = eo.dataTransfer.files[0];
            console.log(file);
            var rd = new FileReader();
            rd.onload = function(e){
                var ary = new Uint8Array(rd.result);
                zip=new JSZip(ary);
                start(file.name.replace(/\.zip$/i,""));
            };
            rd.readAsArrayBuffer(file);
        }catch (e) {
            console.log(e);
        }
        e.stopPropagation();
        e.preventDefault();
        return false;
    }
    var mem;
    function start(name) {
        var diag=$("<div>").appendTo("body");
        diag.
        append($("<h1>").text("インポート先のフォルダを入力してください")).
        append( NPD.embed(FS.get("/Tonyu/Projects/"), extract ,{defName:name} ) );
    }
    var convFiles;
    var dstDir;
    var rsrc;
    var kerDev=false;
    function extract(dir) {
        mem={};
        rsrc={
                images:[{name:"$pat_ball1",url:"images/Ball.png"}],
                sounds:[]
        };
        var base;
        dstDir=dir;
        for (var fn in zip.files) {
            var f=FS.get("/"+fn);
            if (f.name()=="default.tonyuprj") {
                base=f.up();
                break;
            }
        }
        convFiles={};
        for (var fn in zip.files) {
            var f=FS.get("/"+fn);
            var rp=f.relPath(base);
            var fb=zip.files[fn];
            convFiles[ dir.rel(rp).path()] = fb;
        }
        console.log(convFiles);
        for (var fn in convFiles) {
            var fb=convFiles[fn];
            var f=FS.get(fn);
            if (f.name()=="default.tonyuprj") {
                var tprj=$("<div>").html(fromSJIS( fb )).appendTo("body");
                parseTPRJ(tprj);
                break;
            }
        }
    }
    function parseTPRJ(tprj) {
        var classes=tprj.find("class");
        var pages=tprj.find("page");
        copyClasses(classes);
        copyPages(pages);
        mem[dstDir.rel("res.json")]=JSON.stringify(rsrc);
        //console.log(mem);
        cpTmp("SpriteChar");
        cpTmp("PlainChar");
        cpTmp("TextChar");
        cpTmp("SecretChar");
        cpTmp("DxChar");
        cpTmp("T1Text");
        cpTmp("T1Line");
        cpTmp("T1Map");
        cpTmp("T1Page");
        cpTmp("MediaPlayer");
        setOptions();
        //cpTmp("Boot");
        console.log(mem);
        //console.log(JSON.stringify(mem));
        for (var fn in mem) {
            FS.get(fn).text(mem[fn]);
        }
    }
    function setOptions(){
        convFiles[dstDir.rel("options.json")]=JSON.stringify({
            "compiler":{
                "defaultSuperClass":"kernel.Actor",
                //"commentLastPos":true,
                "diagnose":false
            },
            "run":{
                "mainClass":"user.Page_index",
                "bootClass":"kernel.Boot"
            },
            "kernelEditable":kerDev
        });
    }
    function cpTmp(fn) {
        //var ker=FS.get("/Tonyu/Kernel/");
        var t1=FS.get("/Tonyu/Projects/Tonyu1/");
        fn+=".tonyu";
        if (t1.rel(fn).exists()) {
            mem[dstDir.rel(fn)]=t1.rel(fn).text();
            kerDev=true;
        }
    }
    function copyClasses(classes) {
        classes.each(function () {
            var fn=$(this).attr("src");
            var f=dstDir.rel(fn);
            console.log(f.path());
            mem[f.path()]=fromSJIS( convFiles[f.path()]);//.asText();
        });
    }
    function copyPages(pages) {
        pages.each(function () {
            var fn=$(this).attr("src");
            copyPage(dstDir.rel(fn));
        });
    }
    function copyPage(pageF) {
        var cmmlSrc=fromSJIS( convFiles[pageF.path()]); //.asText();
        var pg=$("<div>").html(cmmlSrc).appendTo("body");
        var fn="Page_"+pageF.truncExt(".cmml")+".tonyu";
        console.log("Page", fn);
        var globals=pg.find("globalvalue");
        var buf="extends T1Page;\n";
        buf+="initGlobals();\n";
        globals.each(function () {
            buf+=$(this).attr("name")+"="+$(this).attr("value")+";\n";
        });
        buf+="$Screen.resize($screenWidth,$screenHeight);\n";
        var pats=pg.find("cpattern");
        copyImages(pats);

        var gens=pg.find("generator");
        gens.each(function () {
            var a=this.attributes;
            var klass=$(this).attr("classname");
            if (klass=="Map") {
                buf+=genMap( $(this) );
                return;
            }
            buf+=$(this).attr("name")+"= new "+klass+"{";
            var com="";
            for (var i=0 ; i<a.length; i++) {
                var n=a[i].name;
                var r=/inst_(.*)/.exec(n);
                if (r) {
                    buf+=com+r[1]+": "+val(a[i].value);
                    com=", ";
                }
            }
            buf+="};\n";
        });
        mem[dstDir.rel(fn).path()]=buf;
    }
    function val(v) {
        return v.replace(/%22/g,"\"");
    }
    function genMap(map) {
        console.log("map", map);
        var src=map.attr("src");
        var mapF=convFiles[dstDir.rel(src)];
        var ary=mapF.asUint8Array();
        var pwidth=map.attr("inst_pwidth");
        var pheight=map.attr("inst_pheight");
        var width=map.attr("inst_width");
        var height=map.attr("inst_height");
        console.log(pwidth, pheight, width, height,ary);
        var buf="";
        var mapFile=dstDir.rel("maps/").rel(dstDir.rel(src).name());
        buf+=T1Map(pwidth, pheight, width, height,ary,mapFile, mem);
        return buf;
    }
    function copyImages(pats) {
        pats.each(function () {
            var name=$(this).attr("name");
            //name=name.replace(/^\$/,"$pat_");
            var src=$(this).attr("src");
            var imgFile=dstDir.rel(src).path();
            var o=convFiles[imgFile];
            if (!o) {
                console.log(convFiles);
                throw "Image file not found :"+imgFile;
            }
            var fn=dstDir.rel(src).name();
            //console.log("pats", o);
            var buf="";
            var a=o.asUint8Array();
            var s=btoa(String.fromCharCode.apply(null, a));
            s="data:image/png;base64,"+s;
            //$("<img>").attr("src",s).appendTo("body");
            //console.log("patss", s);
            var url="images/"+fn;
            mem[dstDir.rel(url)]=s;
            rsrc.images.push({name:name , url:"ls:"+url });
        });

    }
});<|endoftext|>


<commit_before>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Enhances and consistently styles text inputs.
//>>label: Text Inputs & Textareas
//>>group: Forms
//>>css.structure: ../css/structure/jquery.mobile.forms.textinput.css
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css

define( [ "jquery", "../../jquery.mobile.core", "../../jquery.mobile.widget", "../../jquery.mobile.degradeInputs", "../../jquery.mobile.zoom" ], function( jQuery ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {

$.widget( "mobile.textinput", {
	initSelector: "input[type='text'], input[type='search'], :jqmData(type='search'), input[type='number'], :jqmData(type='number'), input[type='password'], input[type='email'], input[type='url'], input[type='tel'], textarea, input[type='time'], input[type='date'], input[type='month'], input[type='week'], input[type='datetime'], input[type='datetime-local'], input[type='color'], input:not([type]), input[type='file']",

	options: {
		theme: null,
		corners: true,
		mini: false,
		// This option defaults to true on iOS devices.
		preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1,
		wrapperClass: "",
		enhanced: false
	},

	_create: function() {

		var options = this.options,
			isSearch = this.element.is( "[type='search'], :jqmData(type='search')" ),
			isTextarea = this.element[ 0 ].tagName === "TEXTAREA",
			isRange = this.element.is( "[data-" + ( $.mobile.ns || "" ) + "type='range']" ),
			inputNeedsWrap = ( (this.element.is( "input" ) ||
				this.element.is( "[data-" + ( $.mobile.ns || "" ) + "type='search']" ) ) &&
					!isRange );

		$.extend( this, {
			classes: this._classesFromOptions(),
			isSearch: isSearch,
			isTextarea: isTextarea,
			isRange: isRange,
			inputNeedsWrap: inputNeedsWrap
		});

		this._autoCorrect();

		if ( this.element[ 0 ].disabled ) {
			options.disabled = true;
		}

		if ( !options.enhanced ) {
			this._enhance();
		}

		this._on( {
			"focus": "_handleFocus",
			"blur": "_handleBlur"
		});

	},

	refresh: function() {
		this.setOptions({
			"disabled" : this.element.is( ":disabled" )
		});
	},

	_enhance: function() {
		var elementClasses = [];

		if ( this.isTextarea ) {
			elementClasses.push( "ui-input-text" );
		}

		if ( this.isTextarea || this.isRange ) {
			elementClasses.push( "ui-shadow-inset" );
		}

		//"search" and "text" input widgets
		if ( this.inputNeedsWrap ) {
			this.element.wrap( this._wrap() );
		} else {
			elementClasses = elementClasses.concat( this.classes );
		}

		this.element.addClass( elementClasses.join( " " ) );
	},

	widget: function() {
		return ( this.inputNeedsWrap ) ? this.element.parent() : this.element;
	},

	_classesFromOptions: function() {
		var options = this.options,
			classes = [];

		classes.push( "ui-body-" + ( ( options.theme === null ) ? "inherit" : options.theme ) );
		if ( options.corners ) {
			classes.push( "ui-corner-all" );
		}
		if ( options.mini ) {
			classes.push( "ui-mini" );
		}
		if ( options.disabled ) {
			classes.push( "ui-state-disabled" );
		}
		if ( options.wrapperClass ) {
			classes.push( options.wrapperClass );
		}

		return classes;
	},

	_wrap: function() {
		return $( "

" );
	},

	_autoCorrect: function() {
		// XXX: Temporary workaround for issue 785 (Apple bug 8910589).
		//      Turn off autocorrect and autocomplete on non-iOS 5 devices
		//      since the popup they use can't be dismissed by the user. Note
		//      that we test for the presence of the feature by looking for
		//      the autocorrect property on the input element. We currently
		//      have no test for iOS 5 or newer so we're temporarily using
		//      the touchOverflow support flag for jQM 1.0. Yes, I feel dirty.
		//      - jblas
		if ( typeof this.element[0].autocorrect !== "undefined" &&
			!$.support.touchOverflow ) {

			// Set the attribute instead of the property just in case there
			// is code that attempts to make modifications via HTML.
			this.element[0].setAttribute( "autocorrect", "off" );
			this.element[0].setAttribute( "autocomplete", "off" );
		}
	},

	_handleBlur: function() {
		this.element.removeClass( $.mobile.focusClass );
		if ( this.options.preventFocusZoom ) {
			$.mobile.zoom.enable( true );
		}
	},

	_handleFocus: function() {
		// In many situations, iOS will zoom into the input upon tap, this
		// prevents that from happening
		if ( this.options.preventFocusZoom ) {
			$.mobile.zoom.disable( true );
		}
		this.element.addClass( $.mobile.focusClass );
	},

	_setOptions: function ( options ) {
		var outer = this.widget();

		this._super( options );

		if ( !( options.disabled === undefined &&
			options.mini === undefined &&
			options.corners === undefined &&
			options.theme === undefined &&
			options.wrapperClass === undefined ) ) {

			outer.removeClass( this.classes.join( " " ) );
			this.classes = this._classesFromOptions();
			outer.addClass( this.classes.join( " " ) );
		}

		if ( options.disabled !== undefined ) {
			this.element.prop( "disabled", !!options.disabled );
		}
	},

	_destroy: function() {
		if ( this.options.enhanced ) {
			return;
		}
		if ( this.inputNeedsWrap ) {
			this.element.unwrap();
		}
		this.element.removeClass( "ui-input-text " + this.classes.join( " " ) );
	}
});

})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<commit_msg>Textinput: Add focus class to and remove focus class from this.widget() to make sure we act on the wrapper when there is a wrapper. Fixes #6415.<commit_after>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Enhances and consistently styles text inputs.
//>>label: Text Inputs & Textareas
//>>group: Forms
//>>css.structure: ../css/structure/jquery.mobile.forms.textinput.css
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css

define( [ "jquery", "../../jquery.mobile.core", "../../jquery.mobile.widget", "../../jquery.mobile.degradeInputs", "../../jquery.mobile.zoom" ], function( jQuery ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {

$.widget( "mobile.textinput", {
	initSelector: "input[type='text'], input[type='search'], :jqmData(type='search'), input[type='number'], :jqmData(type='number'), input[type='password'], input[type='email'], input[type='url'], input[type='tel'], textarea, input[type='time'], input[type='date'], input[type='month'], input[type='week'], input[type='datetime'], input[type='datetime-local'], input[type='color'], input:not([type]), input[type='file']",

	options: {
		theme: null,
		corners: true,
		mini: false,
		// This option defaults to true on iOS devices.
		preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1,
		wrapperClass: "",
		enhanced: false
	},

	_create: function() {

		var options = this.options,
			isSearch = this.element.is( "[type='search'], :jqmData(type='search')" ),
			isTextarea = this.element[ 0 ].tagName === "TEXTAREA",
			isRange = this.element.is( "[data-" + ( $.mobile.ns || "" ) + "type='range']" ),
			inputNeedsWrap = ( (this.element.is( "input" ) ||
				this.element.is( "[data-" + ( $.mobile.ns || "" ) + "type='search']" ) ) &&
					!isRange );

		$.extend( this, {
			classes: this._classesFromOptions(),
			isSearch: isSearch,
			isTextarea: isTextarea,
			isRange: isRange,
			inputNeedsWrap: inputNeedsWrap
		});

		this._autoCorrect();

		if ( this.element[ 0 ].disabled ) {
			options.disabled = true;
		}

		if ( !options.enhanced ) {
			this._enhance();
		}

		this._on( {
			"focus": "_handleFocus",
			"blur": "_handleBlur"
		});

	},

	refresh: function() {
		this.setOptions({
			"disabled" : this.element.is( ":disabled" )
		});
	},

	_enhance: function() {
		var elementClasses = [];

		if ( this.isTextarea ) {
			elementClasses.push( "ui-input-text" );
		}

		if ( this.isTextarea || this.isRange ) {
			elementClasses.push( "ui-shadow-inset" );
		}

		//"search" and "text" input widgets
		if ( this.inputNeedsWrap ) {
			this.element.wrap( this._wrap() );
		} else {
			elementClasses = elementClasses.concat( this.classes );
		}

		this.element.addClass( elementClasses.join( " " ) );
	},

	widget: function() {
		return ( this.inputNeedsWrap ) ? this.element.parent() : this.element;
	},

	_classesFromOptions: function() {
		var options = this.options,
			classes = [];

		classes.push( "ui-body-" + ( ( options.theme === null ) ? "inherit" : options.theme ) );
		if ( options.corners ) {
			classes.push( "ui-corner-all" );
		}
		if ( options.mini ) {
			classes.push( "ui-mini" );
		}
		if ( options.disabled ) {
			classes.push( "ui-state-disabled" );
		}
		if ( options.wrapperClass ) {
			classes.push( options.wrapperClass );
		}

		return classes;
	},

	_wrap: function() {
		return $( "

" );
	},

	_autoCorrect: function() {
		// XXX: Temporary workaround for issue 785 (Apple bug 8910589).
		//      Turn off autocorrect and autocomplete on non-iOS 5 devices
		//      since the popup they use can't be dismissed by the user. Note
		//      that we test for the presence of the feature by looking for
		//      the autocorrect property on the input element. We currently
		//      have no test for iOS 5 or newer so we're temporarily using
		//      the touchOverflow support flag for jQM 1.0. Yes, I feel dirty.
		//      - jblas
		if ( typeof this.element[0].autocorrect !== "undefined" &&
			!$.support.touchOverflow ) {

			// Set the attribute instead of the property just in case there
			// is code that attempts to make modifications via HTML.
			this.element[0].setAttribute( "autocorrect", "off" );
			this.element[0].setAttribute( "autocomplete", "off" );
		}
	},

	_handleBlur: function() {
		this.widget().removeClass( $.mobile.focusClass );
		if ( this.options.preventFocusZoom ) {
			$.mobile.zoom.enable( true );
		}
	},

	_handleFocus: function() {
		// In many situations, iOS will zoom into the input upon tap, this
		// prevents that from happening
		if ( this.options.preventFocusZoom ) {
			$.mobile.zoom.disable( true );
		}
		this.widget().addClass( $.mobile.focusClass );
	},

	_setOptions: function ( options ) {
		var outer = this.widget();

		this._super( options );

		if ( !( options.disabled === undefined &&
			options.mini === undefined &&
			options.corners === undefined &&
			options.theme === undefined &&
			options.wrapperClass === undefined ) ) {

			outer.removeClass( this.classes.join( " " ) );
			this.classes = this._classesFromOptions();
			outer.addClass( this.classes.join( " " ) );
		}

		if ( options.disabled !== undefined ) {
			this.element.prop( "disabled", !!options.disabled );
		}
	},

	_destroy: function() {
		if ( this.options.enhanced ) {
			return;
		}
		if ( this.inputNeedsWrap ) {
			this.element.unwrap();
		}
		this.element.removeClass( "ui-input-text " + this.classes.join( " " ) );
	}
});

})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<|endoftext|>


<commit_before>/*
Copyright 2016 Mozilla

Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*/
/* eslint no-console: "off" */
/* eslint no-multi-str: "off" */

import { ipcRenderer, remote } from '../../../shared/electron';

const { systemPreferences } = remote;

// Check only on startup -- can handle changes in the future, but not
// something people are toggling in the OS while using this prototype.
// Only OSX has this function.
const SWIPE_ENABLED = systemPreferences.isSwipeTrackingFromScrollEventsEnabled ?
  systemPreferences.isSwipeTrackingFromScrollEventsEnabled() :
  false;

// The duration of the swipe must atleast be this value, in ms.
const SWIPE_TIME_THRESHOLD = 50;

// The Y movement of the swipe must be less than this, in pixels.
// This is to distinguish from scrolling up/down a page.
const SWIPE_DELTA_Y_THRESHOLD = 100;

// The X movement of the swipe must be greater than this, in pixels.
const SWIPE_DELTA_X_THRESHOLD = 100;

export const attachGestureListeners = () => {
  let moving = false;
  let startTime = 0;
  let time = 0;
  let deltaX = 0;
  let deltaY = 0;

  window.addEventListener('wheel', (e) => {
    if (moving) {
      deltaX += e.deltaX;
      deltaY += e.deltaY;
      time = Date.now() - startTime;
    }
  }, { passive: true });

  ipcRenderer.on('scroll-touch-begin', () => {
    if (SWIPE_ENABLED) {
      moving = true;
      startTime = Date.now();
    }
  });

  ipcRenderer.on('scroll-touch-end', () => {
    if (time > SWIPE_TIME_THRESHOLD &&
        moving &&
        Math.abs(deltaY) < SWIPE_DELTA_Y_THRESHOLD) {
      if (deltaX > SWIPE_DELTA_X_THRESHOLD && SWIPE_ENABLED) {
        ipcRenderer.emit('go-forward');
      } else if (deltaX < -SWIPE_DELTA_X_THRESHOLD && SWIPE_ENABLED) {
        ipcRenderer.emit('go-back');
      }
    }
    moving = false;
    deltaX = 0;
    deltaY = 0;
  });
};
<commit_msg>Remove useless eslint rules from gestures.js<commit_after>/*
Copyright 2016 Mozilla

Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*/

import { ipcRenderer, remote } from '../../../shared/electron';

const { systemPreferences } = remote;

// Check only on startup -- can handle changes in the future, but not
// something people are toggling in the OS while using this prototype.
// Only OSX has this function.
const SWIPE_ENABLED = systemPreferences.isSwipeTrackingFromScrollEventsEnabled ?
  systemPreferences.isSwipeTrackingFromScrollEventsEnabled() :
  false;

// The duration of the swipe must atleast be this value, in ms.
const SWIPE_TIME_THRESHOLD = 50;

// The Y movement of the swipe must be less than this, in pixels.
// This is to distinguish from scrolling up/down a page.
const SWIPE_DELTA_Y_THRESHOLD = 100;

// The X movement of the swipe must be greater than this, in pixels.
const SWIPE_DELTA_X_THRESHOLD = 100;

export const attachGestureListeners = () => {
  let moving = false;
  let startTime = 0;
  let time = 0;
  let deltaX = 0;
  let deltaY = 0;

  window.addEventListener('wheel', (e) => {
    if (moving) {
      deltaX += e.deltaX;
      deltaY += e.deltaY;
      time = Date.now() - startTime;
    }
  }, { passive: true });

  ipcRenderer.on('scroll-touch-begin', () => {
    if (SWIPE_ENABLED) {
      moving = true;
      startTime = Date.now();
    }
  });

  ipcRenderer.on('scroll-touch-end', () => {
    if (time > SWIPE_TIME_THRESHOLD &&
        moving &&
        Math.abs(deltaY) < SWIPE_DELTA_Y_THRESHOLD) {
      if (deltaX > SWIPE_DELTA_X_THRESHOLD && SWIPE_ENABLED) {
        ipcRenderer.emit('go-forward');
      } else if (deltaX < -SWIPE_DELTA_X_THRESHOLD && SWIPE_ENABLED) {
        ipcRenderer.emit('go-back');
      }
    }
    moving = false;
    deltaX = 0;
    deltaY = 0;
  });
};
<|endoftext|>


<commit_before>/**
 * Base functionality for relationships.
 * @module relationships
 */
var InternalSiestaError = require('./error').InternalSiestaError,
  util = require('./util'),
  Query = require('./Query'),
  log = require('./log'),
  cache = require('./cache'),
  events = require('./events'),
  wrapArrayForAttributes = events.wrapArray,
  ArrayObserver = require('../vendor/observe-js/src/observe').ArrayObserver,
  modelEvents = require('./modelEvents'),
  ModelEventType = modelEvents.ModelEventType;

/**
 * @class  [RelationshipProxy description]
 * @param {Object} opts
 * @constructor
 */
function RelationshipProxy(opts) {
  var self = this;
  opts = opts || {};

  util.extend(this, {
    object: null,
    related: null
  });

  Object.defineProperties(this, {
    isForward: {
      get: function() {
        return !self.isReverse;
      },
      set: function(v) {
        self.isReverse = !v;
      },
      enumerable: true
    }
  });

  util.extendFromOpts(this, opts, {
    reverseModel: null,
    forwardModel: null,
    forwardName: null,
    reverseName: null,
    isReverse: null,
    serialise: null
  }, false);

  this.cancelListens = {};
}

util.extend(RelationshipProxy, {});

util.extend(RelationshipProxy.prototype, {
  /**
   * Install this proxy on the given instance
   * @param {ModelInstance} modelInstance
   */
  install: function(modelInstance) {
    if (modelInstance) {
      if (!this.object) {
        this.object = modelInstance;
        var self = this;
        var name = this.getForwardName();
        Object.defineProperty(modelInstance, name, {
          get: function() {
            return self.related;
          },
          set: function(v) {
            self.set(v);
          },
          configurable: true,
          enumerable: true
        });
        if (!modelInstance.__proxies) modelInstance.__proxies = {};
        modelInstance.__proxies[name] = this;
        if (!modelInstance._proxies) {
          modelInstance._proxies = [];
        }
        modelInstance._proxies.push(this);
      } else {
        throw new InternalSiestaError('Already installed.');
      }
    } else {
      throw new InternalSiestaError('No object passed to relationship install');
    }
  }

});

//noinspection JSUnusedLocalSymbols
util.extend(RelationshipProxy.prototype, {
  set: function(obj, opts) {
    throw new InternalSiestaError('Must subclass RelationshipProxy');
  },
  get: function(callback) {
    throw new InternalSiestaError('Must subclass RelationshipProxy');
  }
});

util.extend(RelationshipProxy.prototype, {
  proxyForInstance: function(modelInstance, reverse) {
    var name = reverse ? this.getReverseName() : this.getForwardName(),
      model = reverse ? this.reverseModel : this.forwardModel;
    var ret;
    // This should never happen. Should g   et caught in the mapping operation?
    if (util.isArray(modelInstance)) {
      ret = modelInstance.map(function(o) {
        return o.__proxies[name];
      });
    } else {
      var proxies = modelInstance.__proxies;
      var proxy = proxies[name];
      if (!proxy) {
        var err = 'No proxy with name "' + name + '" on mapping ' + model.name;
        throw new InternalSiestaError(err);
      }
      ret = proxy;
    }
    return ret;
  },
  reverseProxyForInstance: function(modelInstance) {
    return this.proxyForInstance(modelInstance, true);
  },
  getReverseName: function() {
    return this.isForward ? this.reverseName : this.forwardName;
  },
  getForwardName: function() {
    return this.isForward ? this.forwardName : this.reverseName;
  },
  getForwardModel: function() {
    return this.isForward ? this.forwardModel : this.reverseModel;
  },
  clearRemovalListener: function(obj) {
    var localId = obj.localId;
    var cancelListen = this.cancelListens[localId];
    // TODO: Remove this check. cancelListen should always exist
    if (cancelListen) {
      cancelListen();
      this.cancelListens[localId] = null;
    }
  },
  listenForRemoval: function(obj) {
    this.cancelListens[obj.localId] = obj.on('*', function(e) {
      if (e.type == ModelEventType.Remove) {
        if (util.isArray(this.related)) {
          var idx = this.related.indexOf(obj);
          this.splice(idx, 1);
        }
        else {
          this.setIdAndRelated(null);
        }
        this.clearRemovalListener(obj);
      }
    }.bind(this));
  },
  /**
   * Configure _id and related with the new related object.
   * @param obj
   * @param {object} [opts]
   * @param {boolean} [opts.disableNotifications]
   * @returns {String|undefined} - Error message or undefined
   */
  setIdAndRelated: function(obj, opts) {
    opts = opts || {};
    if (!opts.disableevents) var oldValue = this._getOldValueForSetChangeEvent();
    var previouslyRelated = this.related;
    if (previouslyRelated) this.clearRemovalListener(previouslyRelated);
    if (obj) {
      if (util.isArray(obj)) {
        this.related = obj;
        obj.forEach(function(_obj) {
          this.listenForRemoval(_obj);
        }.bind(this));
      } else {
        this.related = obj;
        this.listenForRemoval(obj);
      }
    }
    else {
      this.related = null;
    }
    if (!opts.disableevents) this.registerSetChange(obj, oldValue);
  },
  checkInstalled: function() {
    if (!this.object) {
      throw new InternalSiestaError('Proxy must be installed on an object before can use it.');
    }
  },
  splicer: function(opts) {
    opts = opts || {};
    return function(idx, numRemove) {
      opts = opts || {};
      if (!opts.disableevents) {
        var added = this._getAddedForSpliceChangeEvent(arguments),
          removed = this._getRemovedForSpliceChangeEvent(idx, numRemove);
      }
      var add = Array.prototype.slice.call(arguments, 2);
      var res = this.related.splice.bind(this.related, idx, numRemove).apply(this.related, add);
      if (!opts.disableevents) this.registerSpliceChange(idx, added, removed);
      return res;
    }.bind(this);
  },
  clearReverseRelated: function(opts) {
    opts = opts || {};
    var self = this;
    if (this.related) {
      var reverseProxy = this.reverseProxyForInstance(this.related);
      var reverseProxies = util.isArray(reverseProxy) ? reverseProxy : [reverseProxy];
      reverseProxies.forEach(function(p) {
        if (util.isArray(p.related)) {
          var idx = p.related.indexOf(self.object);
          p.makeChangesToRelatedWithoutObservations(function() {
            p.splicer(opts)(idx, 1);
          });
        } else {
          p.setIdAndRelated(null, opts);
        }
      });
    }
  },
  setIdAndRelatedReverse: function(obj, opts) {
    var self = this;
    var reverseProxy = this.reverseProxyForInstance(obj);
    var reverseProxies = util.isArray(reverseProxy) ? reverseProxy : [reverseProxy];
    reverseProxies.forEach(function(p) {
      if (util.isArray(p.related)) {
        p.makeChangesToRelatedWithoutObservations(function() {
          p.splicer(opts)(p.related.length, 0, self.object);
        });
      } else {
        p.clearReverseRelated(opts);
        p.setIdAndRelated(self.object, opts);
      }
    });
  },
  makeChangesToRelatedWithoutObservations: function(f) {
    if (this.related) {
      this.related.arrayObserver.close();
      this.related.arrayObserver = null;
      f();
      this.wrapArray(this.related);
    } else {
      f();
    }
  },
  /**
   * Get old value that is sent out in emissions.
   * @returns {*}
   * @private
   */
  _getOldValueForSetChangeEvent: function() {
    var oldValue = this.related;
    if (util.isArray(oldValue) && !oldValue.length) {
      oldValue = null;
    }
    return oldValue;
  },
  registerSetChange: function(newValue, oldValue) {
    var proxyObject = this.object;
    if (!proxyObject) throw new InternalSiestaError('Proxy must have an object associated');
    var model = proxyObject.model.name;
    var collectionName = proxyObject.collectionName;
    // We take [] == null == undefined in the case of relationships.
    modelEvents.emit({
      collection: collectionName,
      model: model,
      localId: proxyObject.localId,
      field: this.getForwardName(),
      old: oldValue,
      new: newValue,
      type: ModelEventType.Set,
      obj: proxyObject
    });
  },

  _getRemovedForSpliceChangeEvent: function(idx, numRemove) {
    var removed = this.related ? this.related.slice(idx, idx + numRemove) : null;
    return removed;
  },

  _getAddedForSpliceChangeEvent: function(args) {
    var add = Array.prototype.slice.call(args, 2),
      added = add.length ? add : [];
    return added;
  },

  registerSpliceChange: function(idx, added, removed) {
    var model = this.object.model.name,
      coll = this.object.collectionName;
    modelEvents.emit({
      collection: coll,
      model: model,
      localId: this.object.localId,
      field: this.getForwardName(),
      index: idx,
      removed: removed,
      added: added,
      type: ModelEventType.Splice,
      obj: this.object
    });
  },
  wrapArray: function(arr) {
    var self = this;
    wrapArrayForAttributes(arr, this.reverseName, this.object);
    if (!arr.arrayObserver) {
      arr.arrayObserver = new ArrayObserver(arr);
      var observerFunction = function(splices) {
        splices.forEach(function(splice) {
          var added = splice.addedCount ? arr.slice(splice.index, splice.index + splice.addedCount) : [];
          var model = self.getForwardModel();
          modelEvents.emit({
            collection: model.collectionName,
            model: model.name,
            localId: self.object.localId,
            field: self.getForwardName(),
            removed: splice.removed,
            added: added,
            type: ModelEventType.Splice,
            obj: self.object
          });
        });
      };
      arr.arrayObserver.open(observerFunction);
    }
  },
  splice: function() {
    this.splicer({}).apply(this, arguments);
  }

});

module.exports = RelationshipProxy;<commit_msg>remove unneccessary listens<commit_after>/**
 * Base functionality for relationships.
 * @module relationships
 */
var InternalSiestaError = require('./error').InternalSiestaError,
  util = require('./util'),
  Query = require('./Query'),
  log = require('./log'),
  cache = require('./cache'),
  events = require('./events'),
  wrapArrayForAttributes = events.wrapArray,
  ArrayObserver = require('../vendor/observe-js/src/observe').ArrayObserver,
  modelEvents = require('./modelEvents'),
  ModelEventType = modelEvents.ModelEventType;

/**
 * @class  [RelationshipProxy description]
 * @param {Object} opts
 * @constructor
 */
function RelationshipProxy(opts) {
  var self = this;
  opts = opts || {};

  util.extend(this, {
    object: null,
    related: null
  });

  Object.defineProperties(this, {
    isForward: {
      get: function() {
        return !self.isReverse;
      },
      set: function(v) {
        self.isReverse = !v;
      },
      enumerable: true
    }
  });

  util.extendFromOpts(this, opts, {
    reverseModel: null,
    forwardModel: null,
    forwardName: null,
    reverseName: null,
    isReverse: null,
    serialise: null
  }, false);

  this.cancelListens = {};
}

util.extend(RelationshipProxy, {});

util.extend(RelationshipProxy.prototype, {
  /**
   * Install this proxy on the given instance
   * @param {ModelInstance} modelInstance
   */
  install: function(modelInstance) {
    if (modelInstance) {
      if (!this.object) {
        this.object = modelInstance;
        var self = this;
        var name = this.getForwardName();
        Object.defineProperty(modelInstance, name, {
          get: function() {
            return self.related;
          },
          set: function(v) {
            self.set(v);
          },
          configurable: true,
          enumerable: true
        });
        if (!modelInstance.__proxies) modelInstance.__proxies = {};
        modelInstance.__proxies[name] = this;
        if (!modelInstance._proxies) {
          modelInstance._proxies = [];
        }
        modelInstance._proxies.push(this);
      } else {
        throw new InternalSiestaError('Already installed.');
      }
    } else {
      throw new InternalSiestaError('No object passed to relationship install');
    }
  }

});

//noinspection JSUnusedLocalSymbols
util.extend(RelationshipProxy.prototype, {
  set: function(obj, opts) {
    throw new InternalSiestaError('Must subclass RelationshipProxy');
  },
  get: function(callback) {
    throw new InternalSiestaError('Must subclass RelationshipProxy');
  }
});

util.extend(RelationshipProxy.prototype, {
  proxyForInstance: function(modelInstance, reverse) {
    var name = reverse ? this.getReverseName() : this.getForwardName(),
      model = reverse ? this.reverseModel : this.forwardModel;
    var ret;
    // This should never happen. Should g   et caught in the mapping operation?
    if (util.isArray(modelInstance)) {
      ret = modelInstance.map(function(o) {
        return o.__proxies[name];
      });
    } else {
      var proxies = modelInstance.__proxies;
      var proxy = proxies[name];
      if (!proxy) {
        var err = 'No proxy with name "' + name + '" on mapping ' + model.name;
        throw new InternalSiestaError(err);
      }
      ret = proxy;
    }
    return ret;
  },
  reverseProxyForInstance: function(modelInstance) {
    return this.proxyForInstance(modelInstance, true);
  },
  getReverseName: function() {
    return this.isForward ? this.reverseName : this.forwardName;
  },
  getForwardName: function() {
    return this.isForward ? this.forwardName : this.reverseName;
  },
  getForwardModel: function() {
    return this.isForward ? this.forwardModel : this.reverseModel;
  },
  /**
   * Configure _id and related with the new related object.
   * @param obj
   * @param {object} [opts]
   * @param {boolean} [opts.disableNotifications]
   * @returns {String|undefined} - Error message or undefined
   */
  setIdAndRelated: function(obj, opts) {
    opts = opts || {};
    if (!opts.disableevents) var oldValue = this._getOldValueForSetChangeEvent();
    if (obj) {
      if (util.isArray(obj)) {
        this.related = obj;
      } else {
        this.related = obj;
      }
    }
    else {
      this.related = null;
    }
    if (!opts.disableevents) this.registerSetChange(obj, oldValue);
  },
  checkInstalled: function() {
    if (!this.object) {
      throw new InternalSiestaError('Proxy must be installed on an object before can use it.');
    }
  },
  splicer: function(opts) {
    opts = opts || {};
    return function(idx, numRemove) {
      opts = opts || {};
      if (!opts.disableevents) {
        var added = this._getAddedForSpliceChangeEvent(arguments),
          removed = this._getRemovedForSpliceChangeEvent(idx, numRemove);
      }
      var add = Array.prototype.slice.call(arguments, 2);
      var res = this.related.splice.bind(this.related, idx, numRemove).apply(this.related, add);
      if (!opts.disableevents) this.registerSpliceChange(idx, added, removed);
      return res;
    }.bind(this);
  },
  clearReverseRelated: function(opts) {
    opts = opts || {};
    var self = this;
    if (this.related) {
      var reverseProxy = this.reverseProxyForInstance(this.related);
      var reverseProxies = util.isArray(reverseProxy) ? reverseProxy : [reverseProxy];
      reverseProxies.forEach(function(p) {
        if (util.isArray(p.related)) {
          var idx = p.related.indexOf(self.object);
          p.makeChangesToRelatedWithoutObservations(function() {
            p.splicer(opts)(idx, 1);
          });
        } else {
          p.setIdAndRelated(null, opts);
        }
      });
    }
  },
  setIdAndRelatedReverse: function(obj, opts) {
    var self = this;
    var reverseProxy = this.reverseProxyForInstance(obj);
    var reverseProxies = util.isArray(reverseProxy) ? reverseProxy : [reverseProxy];
    reverseProxies.forEach(function(p) {
      if (util.isArray(p.related)) {
        p.makeChangesToRelatedWithoutObservations(function() {
          p.splicer(opts)(p.related.length, 0, self.object);
        });
      } else {
        p.clearReverseRelated(opts);
        p.setIdAndRelated(self.object, opts);
      }
    });
  },
  makeChangesToRelatedWithoutObservations: function(f) {
    if (this.related) {
      this.related.arrayObserver.close();
      this.related.arrayObserver = null;
      f();
      this.wrapArray(this.related);
    } else {
      f();
    }
  },
  /**
   * Get old value that is sent out in emissions.
   * @returns {*}
   * @private
   */
  _getOldValueForSetChangeEvent: function() {
    var oldValue = this.related;
    if (util.isArray(oldValue) && !oldValue.length) {
      oldValue = null;
    }
    return oldValue;
  },
  registerSetChange: function(newValue, oldValue) {
    var proxyObject = this.object;
    if (!proxyObject) throw new InternalSiestaError('Proxy must have an object associated');
    var model = proxyObject.model.name;
    var collectionName = proxyObject.collectionName;
    // We take [] == null == undefined in the case of relationships.
    modelEvents.emit({
      collection: collectionName,
      model: model,
      localId: proxyObject.localId,
      field: this.getForwardName(),
      old: oldValue,
      new: newValue,
      type: ModelEventType.Set,
      obj: proxyObject
    });
  },

  _getRemovedForSpliceChangeEvent: function(idx, numRemove) {
    var removed = this.related ? this.related.slice(idx, idx + numRemove) : null;
    return removed;
  },

  _getAddedForSpliceChangeEvent: function(args) {
    var add = Array.prototype.slice.call(args, 2),
      added = add.length ? add : [];
    return added;
  },

  registerSpliceChange: function(idx, added, removed) {
    var model = this.object.model.name,
      coll = this.object.collectionName;
    modelEvents.emit({
      collection: coll,
      model: model,
      localId: this.object.localId,
      field: this.getForwardName(),
      index: idx,
      removed: removed,
      added: added,
      type: ModelEventType.Splice,
      obj: this.object
    });
  },
  wrapArray: function(arr) {
    var self = this;
    wrapArrayForAttributes(arr, this.reverseName, this.object);
    if (!arr.arrayObserver) {
      arr.arrayObserver = new ArrayObserver(arr);
      var observerFunction = function(splices) {
        splices.forEach(function(splice) {
          var added = splice.addedCount ? arr.slice(splice.index, splice.index + splice.addedCount) : [];
          var model = self.getForwardModel();
          modelEvents.emit({
            collection: model.collectionName,
            model: model.name,
            localId: self.object.localId,
            field: self.getForwardName(),
            removed: splice.removed,
            added: added,
            type: ModelEventType.Splice,
            obj: self.object
          });
        });
      };
      arr.arrayObserver.open(observerFunction);
    }
  },
  splice: function() {
    this.splicer({}).apply(this, arguments);
  }

});

module.exports = RelationshipProxy;<|endoftext|>


<commit_before>const base = {
    appenders: {
        accessLogs: { type: 'Datefile', filename: '/tmp/log/access.log', pattern: '_yyyyMMdd.log', alwaysIncludePattern: true, category: 'access' },
        console: { type: 'console', category: 'console'}
    },
    categories: {
        access: { appenders: ['accessLogs'], level: 'info' },
        console: { appenders: ['console'], level: 'debug' },
        default: { appenders: ['console', 'accessLogs'], level: 'trace' }
    },
    replaceConsole: true,
}

const dev = {

}

const prod = {

}

module.exports = process.env === 'production' ? Object.assign({}, base, prod) : Object.assign({}, base, dev);<commit_msg>update<commit_after>
const os = require('os');
const _type = os.type();
const _path = _type === 'Windows_NT' ? './' : '/tmp/'

const base = {
    appenders: {
        accessLogs: { type: 'Datefile', filename: `${_path}log/access.log`, pattern: '_yyyyMMdd.log', alwaysIncludePattern: true, category: 'access' },
        console: { type: 'console', category: 'console'}
    },
    categories: {
        access: { appenders: ['accessLogs'], level: 'info' },
        console: { appenders: ['console'], level: 'debug' },
        default: { appenders: ['console', 'accessLogs'], level: 'trace' }
    },
    replaceConsole: true,
}

const dev = {

}

const prod = {

}

module.exports = process.env === 'production' ? Object.assign({}, base, prod) : Object.assign({}, base, dev);<|endoftext|>


<commit_before>import Ember from 'ember';
import helpers from 'ember-google-map/core/helpers';
import GoogleMapCoreView from './core';

var computed = Ember.computed;
var alias = computed.alias;
var oneWay = computed.oneWay;

/**
 * @class GoogleMapMarkerView
 * @extends GoogleMapCoreView
 */
export default GoogleMapCoreView.extend({
  googleFQCN: 'google.maps.Marker',

  googleProperties: {
    isClickable: {name: 'clickable', event: 'clickable_changed'},
    isVisible:   {name: 'visible', event: 'visible_changed'},
    isDraggable: {name: 'draggable', event: 'draggable_changed'},
    isOptimized: {name: 'optimized', readOnly: true},
    title:       {event: 'title_changed'},
    opacity:     {cast: helpers.cast.number},
    icon:        {event: 'icon_changed'},
    zIndex:      {event: 'zindex_changed', cast: helpers.cast.integer},
    map:         {readOnly: true},
    'lat,lng':   {
      name:       'position',
      event:      'position_changed',
      toGoogle:   helpers._latLngToGoogle,
      fromGoogle: helpers._latLngFromGoogle
    }
  },

  _coreGoogleEvents: ['click'],

  // aliased from controller so that if they are not defined they use the values from the controller
  title:       alias('controller.title'),
  opacity:     alias('controller.opacity'),
  zIndex:      alias('controller.zIndex'),
  isVisible:   alias('controller.isVisible'),
  isDraggable: alias('controller.isDraggable'),
  isClickable: alias('controller.isClickable'),
  isOptimized: alias('controller.isOptimized'),
  icon:        alias('controller.icon'),
  lat:         alias('controller.lat'),
  lng:         alias('controller.lng'),

  // get the info window template name from the component or own controller
  infoWindowTemplateName: computed.any('controller.infoWindowTemplateName', 'googleMapComponent.markerInfoWindowTemplateName'),

  infoWindowAnchor: oneWay('googleObject'),

  isInfoWindowVisible: alias('controller.isInfoWindowVisible'),

  hasInfoWindow: computed('googleMapComponent.markerHasInfoWindow', 'controller.hasInfoWindow', {
    get() {
      var fromCtrl = this.get('controller.hasInfoWindow');
      if (fromCtrl == null) {
        return Boolean(this.get('googleMapComponent.markerHasInfoWindow'));
      }
      return fromCtrl;
    }
  }),

  /**
   * @inheritDoc
   */
  _handleCoreEvent: function (name) {
    if (name === 'click') {
      this.set('isInfoWindowVisible', true);
    }
  }
});

<commit_msg>[FIX #78] Fixed optimized<commit_after>import Ember from 'ember';
import helpers from 'ember-google-map/core/helpers';
import GoogleMapCoreView from './core';

var computed = Ember.computed;
var alias = computed.alias;
var oneWay = computed.oneWay;

/**
 * @class GoogleMapMarkerView
 * @extends GoogleMapCoreView
 */
export default GoogleMapCoreView.extend({
  googleFQCN: 'google.maps.Marker',

  googleProperties: {
    isClickable: {name: 'clickable', event: 'clickable_changed'},
    isVisible:   {name: 'visible', event: 'visible_changed'},
    isDraggable: {name: 'draggable', event: 'draggable_changed'},
    isOptimized: {name: 'optimized', optionOnly: true},
    title:       {event: 'title_changed'},
    opacity:     {cast: helpers.cast.number},
    icon:        {event: 'icon_changed'},
    zIndex:      {event: 'zindex_changed', cast: helpers.cast.integer},
    map:         {readOnly: true},
    'lat,lng':   {
      name:       'position',
      event:      'position_changed',
      toGoogle:   helpers._latLngToGoogle,
      fromGoogle: helpers._latLngFromGoogle
    }
  },

  _coreGoogleEvents: ['click'],

  // aliased from controller so that if they are not defined they use the values from the controller
  title:       alias('controller.title'),
  opacity:     alias('controller.opacity'),
  zIndex:      alias('controller.zIndex'),
  isVisible:   alias('controller.isVisible'),
  isDraggable: alias('controller.isDraggable'),
  isClickable: alias('controller.isClickable'),
  isOptimized: alias('controller.isOptimized'),
  icon:        alias('controller.icon'),
  lat:         alias('controller.lat'),
  lng:         alias('controller.lng'),

  // get the info window template name from the component or own controller
  infoWindowTemplateName: computed.any('controller.infoWindowTemplateName', 'googleMapComponent.markerInfoWindowTemplateName'),

  infoWindowAnchor: oneWay('googleObject'),

  isInfoWindowVisible: alias('controller.isInfoWindowVisible'),

  hasInfoWindow: computed('googleMapComponent.markerHasInfoWindow', 'controller.hasInfoWindow', {
    get() {
      var fromCtrl = this.get('controller.hasInfoWindow');
      if (fromCtrl == null) {
        return Boolean(this.get('googleMapComponent.markerHasInfoWindow'));
      }
      return fromCtrl;
    }
  }),

  /**
   * @inheritDoc
   */
  _handleCoreEvent: function (name) {
    if (name === 'click') {
      this.set('isInfoWindowVisible', true);
    }
  }
});

<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2016, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

define(function(require) {

  var Locale = require('utils/locale');
  var Sunstone = require('sunstone');
  var Notifier = require('utils/notifier');

  //Escape doublequote in a string and return it
  function _escapeDoubleQuotes(string) {
    if (string != undefined && typeof(string) == "string") {
      // Recursive to deal with strings like: 'aa""b"'
      // The second " would not match

      var prev;
      var result = string;

      do {
        prev = result;
        result = prev.replace(/([^\\]|^)"/g, '$1\\"');
      } while (prev != result)

      return result;
    } else {
      return string;
    }
  }

  // Transforms text:
  //  input:      <b>bold</b> "text"
  //  output:     bold "text"
  function _htmlDecode(value) {
    return $('
').html(value).text();
  }

  // Transforms text:
  //  input:      bold "text"
  //  output:     <b>bold</b> "text"
  function _htmlEncode(value) {
    return $('
').text(value).html();
  }

  // Transforms an object to an opennebula template string
  function _convert_template_to_string(template_json, unshown_values) {
    if (unshown_values)
      template_json = $.extend({}, template_json, unshown_values);

    var template_str = "";
    $.each(template_json, function(key, value) {
      if (!value) {
        template_str += key + " = \"\"\n";
      } else {
        var values;

        if ($.isArray(value)){
          values = value;
        }else{
          values = [value];
        }

        $.each(values, function(index, element) {
          if (!element) return true;
          // current value can be an object
          if (typeof element == 'object') {
            template_str += key + " = [\n";

            template_str += Object.keys(element).map(function(k){
              return "  " + k + " = \"" + _escapeDoubleQuotes(element[k].toString()) + "\"";
            }).join(",\n")

            template_str += " ]\n";
          } else { // or a string
            template_str += key + " = \"" + _escapeDoubleQuotes(element.toString()) + "\"\n";
          }
        });
      }
    });

    return template_str;
  }

  function _merge_templates(template_master, template_slave, advanced){
    if(!advanced)
      template_slave = _convert_string_to_template(template_slave);
    else
      template_master = _convert_string_to_template(template_master);
    if((advanced && template_master) || (!advanced && template_slave)){
      var template_final = {};
      $.extend(true, template_final, template_slave, template_master);
      return template_final;
    }else{
      Notifier.notifyError(Locale.tr("Advanced template malformed"));
    }
    return template_master;
  }
  // Transforms an object to an opennebula template string
  function _convert_string_to_template(string_json, unshown_values) {
    string_json = string_json.split("\n").join(" ");
    string_json = string_json.split("   ").join(" ");
    string_json = string_json.split("  ").join(" ");
    var match_symbols = "=[,]"
    var template_json = {};
    var array_string = string_json.split(" ");
    var i = 0;
    var array = false;
    while(i < array_string.length-1){
      if(!array_string[i].match('"') && !array_string[i].match(match_symbols)){ //is key
        var key = array_string[i];
        if(template_json[key]){ //exists key, generate Array
          if(!Array.isArray(template_json[key])){
            var obj = template_json[key];
            template_json[key] = [];
            template_json[key].push(obj);
          }
          array = true;
        }
        else{
          array = false;
        }
        template_json[key];
        i+=1;
        if(array_string[i] == "="){
          i+=1;
          if(array_string[i] != "["){
            var value = "";
            if(key == "DESCRIPTION" && array_string[i][0] == '"' && array_string[i][array_string[i].length-1] != '"'){
              while (array_string[i][array_string[i].length-1] != '"' && i < array_string.length-1){
                value += array_string[i] + " ";
                i+=1;
              }
              if(!value.match("="))
                value = value.split('"').join("");
              else{
                value  = value .slice(0,-1);
                value = value .slice(1);
              }
              if(array){
                template_json[key].push(value);
              }else{
                template_json[key] = value;
              }
              i+=1;
            }
            else if(array_string[i].match('"')){
              value = array_string[i];
              if(!value.match("="))
                value = value.split('"').join("");
              else{
                value  = value .slice(0,-1);
                value = value .slice(1);
              }
              if(array){
                template_json[key].push(value);
              }else{
                template_json[key] = value;
              }
              i+=1;
            }
            else return false;
          }else{
            var obj = {}
            i+=1;
            while(array_string[i] != ']' && i < array_string.length-1){
              var sub_key;
              if(!array_string[i].match('"') && !array_string[i].match(match_symbols)){
                sub_key = array_string[i];
                i+=1;
                if(array_string[i] == "="){
                  i+=1;
                  if(array_string[i].match('"')){
                    if(array_string[i][array_string[i].length-1] == ","){
                      array_string[i] = array_string[i].slice(0,-1);
                    }
                    var value = array_string[i];
                    obj[sub_key] = value;
                    obj[sub_key] = obj[sub_key].split('"').join("");
                    i+=1;
                  }else return false;
                }else return false;
              }else return false;
            }
            if(array){
              template_json[key].push(obj);
            }else{
              template_json[key] = {};
              template_json[key] = obj;
            }
            i+=1;
          }
        }else return false;
      }else return false;
    }
    return template_json;
  }

  return {
    'mergeTemplates'  : _merge_templates,
    'stringToTemplate': _convert_string_to_template,
    'templateToString': _convert_template_to_string,
    'htmlDecode': _htmlDecode,
    'htmlEncode': _htmlEncode,
    'escapeDoubleQuotes': _escapeDoubleQuotes
  };
});

<commit_msg>TemplateUtils changed code of string_to_template<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2016, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

define(function(require) {

  var Locale = require('utils/locale');
  var Sunstone = require('sunstone');
  var Notifier = require('utils/notifier');

  //Escape doublequote in a string and return it
  function _escapeDoubleQuotes(string) {
    if (string != undefined && typeof(string) == "string") {
      // Recursive to deal with strings like: 'aa""b"'
      // The second " would not match

      var prev;
      var result = string;

      do {
        prev = result;
        result = prev.replace(/([^\\]|^)"/g, '$1\\"');
      } while (prev != result)

      return result;
    } else {
      return string;
    }
  }

  // Transforms text:
  //  input:      <b>bold</b> "text"
  //  output:     bold "text"
  function _htmlDecode(value) {
    return $('
').html(value).text();
  }

  // Transforms text:
  //  input:      bold "text"
  //  output:     <b>bold</b> "text"
  function _htmlEncode(value) {
    return $('
').text(value).html();
  }

  // Transforms an object to an opennebula template string
  function _convert_template_to_string(template_json, unshown_values) {
    if (unshown_values)
      template_json = $.extend({}, template_json, unshown_values);

    var template_str = "";
    $.each(template_json, function(key, value) {
      if (!value) {
        template_str += key + " = \"\"\n";
      } else {
        var values;

        if ($.isArray(value)){
          values = value;
        }else{
          values = [value];
        }

        $.each(values, function(index, element) {
          if (!element) return true;
          // current value can be an object
          if (typeof element == 'object') {
            template_str += key + " = [\n";

            template_str += Object.keys(element).map(function(k){
              return "  " + k + " = \"" + _escapeDoubleQuotes(element[k].toString()) + "\"";
            }).join(",\n")

            template_str += " ]\n";
          } else { // or a string
            template_str += key + " = \"" + _escapeDoubleQuotes(element.toString()) + "\"\n";
          }
        });
      }
    });

    return template_str;
  }

  function _merge_templates(template_master, template_slave, advanced){
    if(!advanced)
      template_slave = _convert_string_to_template(template_slave);
    else
      template_master = _convert_string_to_template(template_master);
    if((advanced && template_master) || (!advanced && template_slave)){
      var template_final = {};
      $.extend(true, template_final, template_slave, template_master);
      return template_final;
    }else{
      Notifier.notifyError(Locale.tr("Advanced template malformed"));
    }
    return template_master;
  }
  // Transforms an object to an opennebula template string
  function _convert_string_to_template(string_json, unshown_values) {
    var i = 0;
    var characters = [];
    var symbols = [];
    var key, sub_key, value;
    var template_json = {}, obj_aux = {};
    var array = false;
    while (i <= string_json.length-1){
      var symbol = symbols[symbols.length-1];
      if(string_json[i] != " " && string_json[i] != "," && string_json[i] != "\n" || symbol == '"'){
        if(string_json[i] == "=" && symbol != '"' && characters.length > 0 && (!symbol || (symbol && symbol == "["))){
          var key_aux = "";
          while(characters.length > 0){
            key_aux += characters.shift();
          }
          if(!symbol){
            key = key_aux;
            if(template_json[key]){ //exists key, generate Array
              if(!Array.isArray(template_json[key])){
                var obj = template_json[key];
                template_json[key] = [];
                template_json[key].push(obj);
              }
              array = true;
            }else{
              template_json[key] = {};
              array = false;
            }
          }else{
            sub_key = key_aux;
          }
        }
        else if(string_json[i] == '"' && symbol && symbol == '"' && characters[characters.length-1] != "\\"){
          symbols.pop();
          var value_aux = "";
          while(characters.length > 0){
            value_aux += characters.shift();
          }
          if(sub_key){
            if (array) {
              obj_aux[sub_key] = value_aux;
            }
            else{
              template_json[key][sub_key] = value_aux;
            }
            sub_key = undefined;
          }else{
            template_json[key] = value_aux;
          }
        }
        else if(string_json[i] == '[' && !symbol){
          symbols.push("[");
        }
        else if(string_json[i] == '"' && characters[characters.length-1] != "\\"){
          symbols.push('"');
        }
        else if(string_json[i] == ']' && symbol && symbol == '['){
          symbols.pop();
          if(array){
            template_json[key].push(obj_aux);
            obj_aux = {};
          }
        }
        else{
          if(JSON.stringify(template_json[key]) === '{}' && symbols.length <= 0){ //Empty
            return false;
          }
          else{
            characters.push(string_json[i]);
          }
        }
      }
      i+=1;
    }
    return template_json;
  }

  return {
    'mergeTemplates'  : _merge_templates,
    'stringToTemplate': _convert_string_to_template,
    'templateToString': _convert_template_to_string,
    'htmlDecode': _htmlDecode,
    'htmlEncode': _htmlEncode,
    'escapeDoubleQuotes': _escapeDoubleQuotes
  };
});

<|endoftext|>


<commit_before>/*    Copyright 2016 Firewalla LLC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
'use strict';
var express = require('express');
var router = express.Router();

var CloudWrapper = require('../lib/CloudWrapper');
var cloudWrapper = new CloudWrapper();

let log = require('../../net2/logger.js')(__filename, "info");

let sc = require('../lib/SystemCheck.js');

const jsonfile = require('jsonfile')

router.post('/message/:gid',

  sc.debugInfo,

  (req, res, next) => {

    const localIPs = ["127.0.0.1", "::ffff:127.0.0.1"];

    if(!localIPs.includes(req.connection.remoteAddress)) { // this api can only be used for local access
      res.status(404).send("");
      return;
    }

    let gid = req.params.gid;

    (async() =>{
      let controller = await cloudWrapper.getNetBotController(gid)
      let response = await controller.msgHandlerAsync(gid, req.body)
      res.body = JSON.stringify(response);
      next();
    })()
      .catch((err) => {
        // netbot controller is not ready yet, waiting for init complete
        log.error(err);
        res.status(503);
        res.json({error: 'Initializing Firewalla Device, please try later'});
      });
  },

  sc.compressPayloadIfRequired,

  (req, res, next) => {
    res.type('json');
    res.send(res.body);
  }
);

module.exports = router;
<commit_msg>update copyright<commit_after>/*    Copyright 2020 Firewalla LLC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
'use strict';
var express = require('express');
var router = express.Router();

var CloudWrapper = require('../lib/CloudWrapper');
var cloudWrapper = new CloudWrapper();

let log = require('../../net2/logger.js')(__filename, "info");

let sc = require('../lib/SystemCheck.js');

const jsonfile = require('jsonfile')

router.post('/message/:gid',

  sc.debugInfo,

  (req, res, next) => {

    const localIPs = ["127.0.0.1", "::ffff:127.0.0.1"];

    if(!localIPs.includes(req.connection.remoteAddress)) { // this api can only be used for local access
      res.status(404).send("");
      return;
    }

    let gid = req.params.gid;

    (async() =>{
      let controller = await cloudWrapper.getNetBotController(gid)
      let response = await controller.msgHandlerAsync(gid, req.body)
      res.body = JSON.stringify(response);
      next();
    })()
      .catch((err) => {
        // netbot controller is not ready yet, waiting for init complete
        log.error(err);
        res.status(503);
        res.json({error: 'Initializing Firewalla Device, please try later'});
      });
  },

  sc.compressPayloadIfRequired,

  (req, res, next) => {
    res.type('json');
    res.send(res.body);
  }
);

module.exports = router;
<|endoftext|>


<commit_before>var SPI = require('spi');
var median = require('median')
var average = [];
var lastAverage;
var averageCount =0;
var signalMax = 0;
var signalMin = 4096;
var peakToPeak;

var spi = new SPI.Spi('/dev/spidev0.1', {
    'mode': SPI.MODE['MODE_0'],  // always set mode as the first option
    'chipSelect': SPI.CS['none'] // 'none', 'high' - defaults to low
  }, function(s){
    s.maxSpeed(6000000);
    s.open();
  });

var txbuf = new Buffer([ 0x23, 0x48, 0xAF, 0x19, 0x19, 0x19 ]);
var rxbuf = new Buffer([ 0x00, 0x00, 0x00]);

setInterval(function(){
  spi.read(rxbuf, function(device, buf) {
    //console.log(buf.readUInt16BE(0));
    var sample = buf.readUInt16BE(0);
    if (sample > signalMax)
         {
            signalMax = sample;  // save just the max levels
         }
         else if (sample < signalMin)
         {
            signalMin = sample;  // save just the min levels
         }
  });
},1);

setInterval(function(){
 peakToPeak = 0;
 peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
 average.unshift(peakToPeak);
 if(average.length == 20){
   var first = average.pop();
 }
 var outString = "";
 for(var i = 0; i<peakToPeak/10;i++){
   outString += " ";
 }
 outString += "*";
 var averageToMedian = average;
 var value = median(averageToMedian);
 console.log("median value is " + value + " First was: "+ first + " Array: " + average.toString());
 //console.log(outString);
 signalMax = 0;
 signalMin = 4096;
},50);
<commit_msg>add median output<commit_after>var SPI = require('spi');
var median = require('median')
var average = [];
var lastAverage;
var averageCount =0;
var signalMax = 0;
var signalMin = 4096;
var peakToPeak;

var spi = new SPI.Spi('/dev/spidev0.1', {
    'mode': SPI.MODE['MODE_0'],  // always set mode as the first option
    'chipSelect': SPI.CS['none'] // 'none', 'high' - defaults to low
  }, function(s){
    s.maxSpeed(6000000);
    s.open();
  });

var txbuf = new Buffer([ 0x23, 0x48, 0xAF, 0x19, 0x19, 0x19 ]);
var rxbuf = new Buffer([ 0x00, 0x00, 0x00]);

setInterval(function(){
  spi.read(rxbuf, function(device, buf) {
    //console.log(buf.readUInt16BE(0));
    var sample = buf.readUInt16BE(0);
    if (sample > signalMax)
         {
            signalMax = sample;  // save just the max levels
         }
         else if (sample < signalMin)
         {
            signalMin = sample;  // save just the min levels
         }
  });
},1);

setInterval(function(){
 peakToPeak = 0;
 peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
 average.push(peakToPeak);
 if(average.length == 20){
   var first = average.shift();
 }
 var outString = "";
 for(var i = 0; i<peakToPeak/10;i++){
   outString += " ";
 }
 outString += "*";
 var averageToMedian = average;
 var value = median(averageToMedian);
 console.log("median value is " + value + " First was: "+ first + " Array: " + average.toString());
 //console.log(outString);
 signalMax = 0;
 signalMin = 4096;
},50);
<|endoftext|>


<commit_before>import React from 'react';
import Title from 'react-title-component';
import { FormattedMessage, FormattedHTMLMessage, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import Snackbar from 'material-ui/Snackbar';
// polyfill for Safari :-(
import intl from 'intl';  // eslint-disable-line
import intlEn from 'intl/locale-data/jsonp/en.js';  // eslint-disable-line
import { Row } from 'react-flexbox-grid/lib';
import AppHeader from './common/header/AppHeader';
import messages from '../resources/messages';
import { getVersion } from '../config';
import { getBrandColors } from '../styles/colors';
import { updateFeedback } from '../actions/appActions';
import { ErrorNotice } from './common/Notice';

const localMessages = {
  supportEmail: { id: 'app.supportEmail', defaultMessage: 'Problems? email support@mediacloud.org' },
  maintenance: { id: 'app.maintenance', defaultMessage: 'Sorry, we have taken our system down right now for maintenance' },
};

const AppContainer = (props) => {
  const { children, feedback, subHeader, handleSnackBarRequestClose, name, title, description, drawer, showLoginButton } = props;
  const { formatMessage } = props.intl;
  const brandColors = getBrandColors();

  let content = children;
  if (document.appConfig.online === false) {
    content = (

        <Row center="lg">
          <ErrorNotice>

            <FormattedMessage {...localMessages.maintenance} />

          </ErrorNotice>
        </Row>

    );
  }

  return (
    <div className={`app-${name}`}>
      <Title render={formatMessage(messages.suiteName)} />

        <AppHeader
          name={title}
          description={description}
          backgroundColor={brandColors.dark}
          lightColor={brandColors.light}
          showLoginButton={showLoginButton}
          drawer={drawer}
          subHeader={subHeader}
        />

        {content}

          {'Created by the '}

            <FormattedMessage {...messages.c4cmName} />

          {' and the '}

            <FormattedMessage {...messages.berkmanName} />
          .

          <FormattedHTMLMessage {...localMessages.supportEmail} />

          v{getVersion()}

      <Snackbar
        open={feedback.open}
        message={feedback.message}
        autoHideDuration={8000}
        onRequestClose={handleSnackBarRequestClose}
      />

  );
};

AppContainer.propTypes = {
  children: React.PropTypes.node,
  handleTouchTapLeftIconButton: React.PropTypes.func,
  intl: React.PropTypes.object.isRequired,
  // from state
  feedback: React.PropTypes.object.isRequired,
  // from dispatch
  handleSnackBarRequestClose: React.PropTypes.func.isRequired,
  // from parent
  name: React.PropTypes.string.isRequired,
  title: React.PropTypes.string.isRequired,
  description: React.PropTypes.string.isRequired,
  drawer: React.PropTypes.node,
  showLoginButton: React.PropTypes.bool,
  subHeader: React.PropTypes.node,
};

AppContainer.contextTypes = {
  router: React.PropTypes.object.isRequired,
  store: React.PropTypes.object.isRequired,
};

const mapStateToProps = state => ({
  feedback: state.app.feedback,
});

const mapDispatchToProps = dispatch => ({
  handleSnackBarRequestClose: () => {
    dispatch(updateFeedback({ open: false, message: '' }));
  },
});

export default
  injectIntl(
    connect(mapStateToProps, mapDispatchToProps)(
      AppContainer
    )
  );
<commit_msg>show link to group.io forum in footer<commit_after>import React from 'react';
import Title from 'react-title-component';
import { FormattedMessage, FormattedHTMLMessage, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import Snackbar from 'material-ui/Snackbar';
// polyfill for Safari :-(
import intl from 'intl';  // eslint-disable-line
import intlEn from 'intl/locale-data/jsonp/en.js';  // eslint-disable-line
import { Row } from 'react-flexbox-grid/lib';
import AppHeader from './common/header/AppHeader';
import messages from '../resources/messages';
import { getVersion } from '../config';
import { getBrandColors } from '../styles/colors';
import { updateFeedback } from '../actions/appActions';
import { ErrorNotice } from './common/Notice';

const localMessages = {
  supportOptions: { id: 'app.supportOptions', defaultMessage: 'Need help? Join our discussion group
or email support@mediacloud.org.' },
  maintenance: { id: 'app.maintenance', defaultMessage: 'Sorry, we have taken our system down right now for maintenance' },
};

const AppContainer = (props) => {
  const { children, feedback, subHeader, handleSnackBarRequestClose, name, title, description, drawer, showLoginButton } = props;
  const { formatMessage } = props.intl;
  const brandColors = getBrandColors();

  let content = children;
  if (document.appConfig.online === false) {
    content = (

        <Row center="lg">
          <ErrorNotice>

            <FormattedMessage {...localMessages.maintenance} />

          </ErrorNotice>
        </Row>

    );
  }

  return (
    <div className={`app-${name}`}>
      <Title render={formatMessage(messages.suiteName)} />

        <AppHeader
          name={title}
          description={description}
          backgroundColor={brandColors.dark}
          lightColor={brandColors.light}
          showLoginButton={showLoginButton}
          drawer={drawer}
          subHeader={subHeader}
        />

        {content}

          {'Created by the '}

            <FormattedMessage {...messages.c4cmName} />

          {' and the '}

            <FormattedMessage {...messages.berkmanName} />
          .

          <FormattedHTMLMessage {...localMessages.supportOptions} />

          v{getVersion()}

      <Snackbar
        open={feedback.open}
        message={feedback.message}
        autoHideDuration={8000}
        onRequestClose={handleSnackBarRequestClose}
      />

  );
};

AppContainer.propTypes = {
  children: React.PropTypes.node,
  handleTouchTapLeftIconButton: React.PropTypes.func,
  intl: React.PropTypes.object.isRequired,
  // from state
  feedback: React.PropTypes.object.isRequired,
  // from dispatch
  handleSnackBarRequestClose: React.PropTypes.func.isRequired,
  // from parent
  name: React.PropTypes.string.isRequired,
  title: React.PropTypes.string.isRequired,
  description: React.PropTypes.string.isRequired,
  drawer: React.PropTypes.node,
  showLoginButton: React.PropTypes.bool,
  subHeader: React.PropTypes.node,
};

AppContainer.contextTypes = {
  router: React.PropTypes.object.isRequired,
  store: React.PropTypes.object.isRequired,
};

const mapStateToProps = state => ({
  feedback: state.app.feedback,
});

const mapDispatchToProps = dispatch => ({
  handleSnackBarRequestClose: () => {
    dispatch(updateFeedback({ open: false, message: '' }));
  },
});

export default
  injectIntl(
    connect(mapStateToProps, mapDispatchToProps)(
      AppContainer
    )
  );
<|endoftext|>


<commit_before>import cx from 'classnames';
import * as React from 'react';

import Avatar from '../Avatar';
import Username from '../Username';

import Loader from '../Loader';
import compile from './Markup/compile';

const padZero = n => (n < 10 ? `0${n}` : n);
const formatTime = date => `${padZero(date.getHours())}:${padZero(date.getMinutes())}`;

const Message = ({
  user,
  text,
  parsedText,
  inFlight,
  isMention,
  timestamp,
  compileOptions
}) => {
  let avatar;
  if (inFlight) {
    avatar = (

        <Loader size="tiny" />

    );
  } else {
    avatar = (
      <Avatar
        className="ChatMessage-avatar"
        user={user}
      />
    );
  }

  const children = parsedText ? compile(parsedText, compileOptions) : text;

  const date = new Date(timestamp);

  const inFlightClass = inFlight ? 'ChatMessage--loading' : '';
  const mentionClass = isMention ? 'ChatMessage--mention' : '';
  return (

      {avatar}

        <time
          className="ChatMessage-timestamp"
          dateTime={date.toISOString()}
        >
          {formatTime(date)}
        </time>
        <Username className="ChatMessage-username" user={user} />
        {children}

  );
};

Message.propTypes = {
  user: React.PropTypes.object.isRequired,
  text: React.PropTypes.string.isRequired,
  parsedText: React.PropTypes.array.isRequired,
  inFlight: React.PropTypes.bool,
  timestamp: React.PropTypes.number.isRequired,
  isMention: React.PropTypes.bool.isRequired,
  compileOptions: React.PropTypes.shape({
    availableEmoji: React.PropTypes.array,
    emojiImages: React.PropTypes.object
  })
};

export default Message;
<commit_msg>chat: use localised timestamp<commit_after>import cx from 'classnames';
import * as React from 'react';

import Avatar from '../Avatar';
import Username from '../Username';

import Loader from '../Loader';
import compile from './Markup/compile';

const timeFormatOptions = { hour: 'numeric', minute: 'numeric' };

const Message = ({
  user,
  text,
  parsedText,
  inFlight,
  isMention,
  timestamp,
  compileOptions
}) => {
  let avatar;
  if (inFlight) {
    avatar = (

        <Loader size="tiny" />

    );
  } else {
    avatar = (
      <Avatar
        className="ChatMessage-avatar"
        user={user}
      />
    );
  }

  const children = parsedText ? compile(parsedText, compileOptions) : text;

  const date = new Date(timestamp);

  const inFlightClass = inFlight ? 'ChatMessage--loading' : '';
  const mentionClass = isMention ? 'ChatMessage--mention' : '';
  return (

      {avatar}

        <time
          className="ChatMessage-timestamp"
          dateTime={date.toISOString()}
        >
          {date.toLocaleTimeString([], timeFormatOptions)}
        </time>
        <Username className="ChatMessage-username" user={user} />
        {children}

  );
};

Message.propTypes = {
  user: React.PropTypes.object.isRequired,
  text: React.PropTypes.string.isRequired,
  parsedText: React.PropTypes.array.isRequired,
  inFlight: React.PropTypes.bool,
  timestamp: React.PropTypes.number.isRequired,
  isMention: React.PropTypes.bool.isRequired,
  compileOptions: React.PropTypes.shape({
    availableEmoji: React.PropTypes.array,
    emojiImages: React.PropTypes.object
  })
};

export default Message;
<|endoftext|>


<commit_before>import React, { Component } from 'react';

/* component styles */
import styles from './styles';

/* authors */
const AUTHORS = [
  {
    id: 1,
    name: 'anorudes'
  }, {
    id: 2,
    name: 'keske'
  }
];

export class Footer extends Component {
  render() {
    return (
      <footer className={`${ styles }`}>

               Star

              {AUTHORS.map(function(author) {
                return

                  <a className="github-button" href={`https://github.com/${author.name}`}
                    data-count-href={`/${author.name}/followers`}
                    data-count-api={`/users/${author.name}#followers`}
                    data-count-aria-label="# followers on GitHub"
                    aria-label={`Follow @${author.name} on GitHub`}>
                    @{author.name}

              })}

    );
  }
}
<commit_msg>Revert "Patch footer"<commit_after>import React, { Component } from 'react';

/* component styles */
import styles from './styles';

/* authors */
const AUTHORS = ['anorudes', 'keske'];

export class Footer extends Component {
  render() {
    function renderGitHubFollowButton(user) {
      return (
        <a className="github-button" href={`https://github.com/${user}`}
           data-count-href={`/${user}/followers`}
           data-count-api={`/users/${user}#followers`}
           data-count-aria-label="# followers on GitHub"
           aria-label={`Follow @${user} on GitHub`}>
          @{user}

      );
    }
    return (
      <footer className={`${ styles }`}>

               Star

              {
                AUTHORS.map((author) => renderGitHubFollowButton(author))
              }

    );
  }
}
<|endoftext|>


<commit_before>/*
Name      : passdock
Source    : https://github.com/fvdm/nodejs-passdock
Feedback  : https://github.com/fvdm/nodejs-passdock/issues
License   : Unlicense / Public Domain

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org/>
*/

var https = require ('https')
var querystring = require ('querystring')

var app = {
  api: {
    host: 'api.passdock.com',
    path: '/api/v1/',
    timeout: 30,
    token: ''
  }
}

// Communication error
app.buildError = function ( reason, response, requestBody ) {
  return {
    reason: reason,
    response: {
      headers: response.headers,
      statusCode: response.statusCode,
      complete: response.complete
    },
    request: {
      method: response.req.method,
      path: response.req.path,
      headers: response.req._headers,
      body: requestBody,
      finished: response.req.finished
    }
  }
}

// Communicate
app.talk = function ( method, path, fields, cb ) {
  if ( !cb && typeof fields == 'function' ){
    var cb = fields
    var fields = {}
  }

  // build request
  fields.api_token = app.api.token
  fields = querystring.stringify ( fields )

  var options = {
    host: app.api.host,
    port: 443,
    path: app.api.path + path + (method == 'GET' ? '?' + fields : ''),
    method: method,
    agent: false,
    headers: {
      Accept: 'application/json',
      'User-Agent': 'passdock.js (https://github.com/fvdm/nodejs-passdock)'
    }
  }

  if ( method != 'GET' ){
    options.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    options.headers['Content-Length'] = fields.length
  }

  // do request
  var req = https.request ( options, function ( response ) {
    var data = ''
    response.on ( 'data', function ( d ) { data += d })

    // process response
    response.on ( 'end', function () {
      data = data.toString ('utf8').trim ()

      if ( response.statusCode >= 500 ){

        // server trouble
        cb ( data, app.buildError ( 'server error', response, fields ))

      } else if ( response.statusCode >= 200 && response.statusCode < 300 ){

        // all good
        if ( data.match ( /^(\{.*\}|\[.*\])$/ ) ){
          cb ( JSON.parse ( data ), false )
        } else {
          cb ( data, app.buildError ( 'invalid data', response, fields ))
        }

      } else {

        // API error
        cb ( data, app.buildError ( 'error', response, fields ))

      }
    })

    // request cut off
    response.on ( 'close', function ( err ) {
      cb ( data.toString ('utf8'), app.buildError ( 'early disconnect', response, fields ))
    })
  })

  req.setTimeout ( app.api.timeout * 1000 )

  if ( method != 'GET' ){
    req.write ( fields )
  }

  req.end ()
}

// Templates
app.templates = {
  list: function ( cb ) { app.talk ( 'GET', 'templates', cb ) },
  show: function ( id, cb ) { app.talk ( 'GET', 'templates/' + id, cb ) },
  delete: function ( id, cb ) { app.talk ( 'DELETE', 'templates/' + id, cb ) }
}

// Passes
app.passes = {
  list: function ( tid, cb ) { app.talk ( 'GET', 'templates/' + tid +'/passes', cb ) },
  show: function ( tid, id, cb ) { app.talk ( 'GET', 'templates/' + tid +'/passes/' + id, cb ) },
  delete: function ( tid, id, cb ) { app.talk ( 'DELETE', 'templates/' + tid +'/passes/' + id, cb ) },
  create: function ( tid, pass, cb ) { app.talk ( 'POST', 'templates/' + tid +'/passes', { pass: pass }, cb ) },
  update: function ( tid, pid, pass, cb ) { app.talk ( 'PUT', 'template/' + tid +'/passes/' + pid, { pass: pass }, cb ) }
}

// module magic
module.exports = app
<commit_msg>Fix update route according to latest docs (#1)<commit_after>/*
Name      : passdock
Source    : https://github.com/fvdm/nodejs-passdock
Feedback  : https://github.com/fvdm/nodejs-passdock/issues
License   : Unlicense / Public Domain

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org/>
*/

var https = require ('https')
var querystring = require ('querystring')

var app = {
  api: {
    host: 'api.passdock.com',
    path: '/api/v1/',
    timeout: 30,
    token: ''
  }
}

// Communication error
app.buildError = function ( reason, response, requestBody ) {
  return {
    reason: reason,
    response: {
      headers: response.headers,
      statusCode: response.statusCode,
      complete: response.complete
    },
    request: {
      method: response.req.method,
      path: response.req.path,
      headers: response.req._headers,
      body: requestBody,
      finished: response.req.finished
    }
  }
}

// Communicate
app.talk = function ( method, path, fields, cb ) {
  if ( !cb && typeof fields == 'function' ){
    var cb = fields
    var fields = {}
  }

  // build request
  fields.api_token = app.api.token
  fields = querystring.stringify ( fields )

  var options = {
    host: app.api.host,
    port: 443,
    path: app.api.path + path + (method == 'GET' ? '?' + fields : ''),
    method: method,
    agent: false,
    headers: {
      Accept: 'application/json',
      'User-Agent': 'passdock.js (https://github.com/fvdm/nodejs-passdock)'
    }
  }

  if ( method != 'GET' ){
    options.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    options.headers['Content-Length'] = fields.length
  }

  // do request
  var req = https.request ( options, function ( response ) {
    var data = ''
    response.on ( 'data', function ( d ) { data += d })

    // process response
    response.on ( 'end', function () {
      data = data.toString ('utf8').trim ()

      if ( response.statusCode >= 500 ){

        // server trouble
        cb ( data, app.buildError ( 'server error', response, fields ))

      } else if ( response.statusCode >= 200 && response.statusCode < 300 ){

        // all good
        if ( data.match ( /^(\{.*\}|\[.*\])$/ ) ){
          cb ( JSON.parse ( data ), false )
        } else {
          cb ( data, app.buildError ( 'invalid data', response, fields ))
        }

      } else {

        // API error
        cb ( data, app.buildError ( 'error', response, fields ))

      }
    })

    // request cut off
    response.on ( 'close', function ( err ) {
      cb ( data.toString ('utf8'), app.buildError ( 'early disconnect', response, fields ))
    })
  })

  req.setTimeout ( app.api.timeout * 1000 )

  if ( method != 'GET' ){
    req.write ( fields )
  }

  req.end ()
}

// Templates
app.templates = {
  list: function ( cb ) { app.talk ( 'GET', 'templates', cb ) },
  show: function ( id, cb ) { app.talk ( 'GET', 'templates/' + id, cb ) },
  delete: function ( id, cb ) { app.talk ( 'DELETE', 'templates/' + id, cb ) }
}

// Passes
app.passes = {
  list: function ( tid, cb ) { app.talk ( 'GET', 'templates/' + tid +'/passes', cb ) },
  show: function ( tid, id, cb ) { app.talk ( 'GET', 'templates/' + tid +'/passes/' + id, cb ) },
  delete: function ( tid, id, cb ) { app.talk ( 'DELETE', 'templates/' + tid +'/passes/' + id, cb ) },
  create: function ( tid, pass, cb ) { app.talk ( 'POST', 'templates/' + tid +'/passes', { pass: pass }, cb ) },
  update: function ( tid, pid, pass, cb ) { app.talk ( 'PUT', 'templates/' + tid +'/passes/' + pid, { pass: pass }, cb ) }
}

// module magic
module.exports = app
<|endoftext|>