text:
var ClipWall;
(function (ClipWall) {
    // define global variables
    (function (g) {
        g.d = document;
        g.w = window;
        g.b = (g.d.body || g.gt('body')[0]);
        g.ie = !!g.w["ActiveXObject"];
        g.ie6 = g.ie && !g.w["XMLHttpRequest"];
        g.st = function (handler, time) {
            return g.w.setTimeout(handler, time);
        };
        g.ge = function (id) {
            return g.d.getElementById(id);
        };
        g.gt = function (tag) {
            return g.d.getElementsByTagName(tag);
        };
        g.ce = function (tag) {
            return g.d.createElement(tag);
        };
        g.gat = function (elem, name) {
            return elem.getAttribute(name);
        };
        g.sat = function (elem, name, val) {
            return elem.setAttribute(name, val);
        };

        //replace this with final domain when publish
        g.h = "http://localhost:919/";
    })(ClipWall.g || (ClipWall.g = {}));
    var g = ClipWall.g;

    // define events utility
    (function (e) {
        // private fields
        var cache = {};

        // c_evt.fire(event, arguments);
        function fire(e) {
            var args = [];
            for (var _i = 0; _i < (arguments.length - 1); _i++) {
                args[_i] = arguments[_i + 1];
            }
            var handlers = cache[e];
            if (handlers) {
                for (var i = 0; i < handlers.length; i++) {
                    handlers[i](args);
                }
            }
        }
        e.fire = fire;

        // c_evt.bind(event, handler);
        function bind(event, handler) {
            var handlers = cache[event];
            if (!handlers) {
                handlers = [];
            }

            handlers.push(handler);
            cache[event] = handlers;
        }
        e.bind = bind;

        // c_evt.unbind(pressEvent, press);
        function unbind(event, handler) {
            var handlers = cache[event];
            if (handlers) {
                for (var i = 0; i < handlers.length; i++) {
                    if (handlers[i] == handler) {
                        handlers.splice(i, 1);
                    }
                }
            }
        }
        e.unbind = unbind;

        function be(element, event, handler) {
            if (element.addEventListener) {
                element.addEventListener(event, handler);
                return;
            }

            if (element.attachEvent) {
                element.attachEvent("on" + event, handler);
                return;
            }

            element["on" + event] = handler;
        }
        e.be = be;

        function ue(element, event, handler) {
            if (element.removeEventListener) {
                element.removeEventListener(event, handler);
                return;
            }

            if (element.detachEvent) {
                element.detachEvent("on" + event, handler);
                return;
            }

            element["on" + event] = null;
        }
        e.ue = ue;

        function trigger(element, event) {
            if (element.dispatchEvent) {
                var e = g.d.createEvent("HTMLEvents");
                e.initEvent(event.type, true, false);
                element.dispatchEvent(e);
            } else if (element.fireEvent) {
                element.fireEvent("on" + event.type);
            }
        }
        e.trigger = trigger;
    })(ClipWall.e || (ClipWall.e = {}));
    var e = ClipWall.e;
})(ClipWall || (ClipWall = {}));
/// <reference path="page.ts" />
var ClipWall;
(function (ClipWall) {
    //define utlity
    (function (u) {
        function evt(e) {
            var event = e || ClipWall.g.w.event;
            if (!event.target) {
                event.target = event.srcElement;
            }

            return event;
        }
        u.evt = evt;

        function cord(e) {
            var event = (e || ClipWall.g.w.event);
            if (event) {
                return new ClipWall.Point(event.pageX, event.pageY);
            }

            return null;
        }
        u.cord = cord;

        function fullpath(rel) {
            return ClipWall.g.h + rel;
        }
        u.fullpath = fullpath;

        function contains(elem1, elem2) {
            if (elem1 && elem2) {
                while (elem2) {
                    if (elem1 == elem2) {
                        return true;
                    }

                    elem2 = elem2.parentElement;
                }
            }

            return false;
        }
        u.contains = contains;

        function stop(event) {
            event.stopImmediatePropagation();
            event.preventDefault();
        }
        u.stop = stop;

        function format(pattern) {
            var ps = [];
            for (var _i = 0; _i < (arguments.length - 1); _i++) {
                ps[_i] = arguments[_i + 1];
            }
            if (!valid(ps)) {
                return pattern;
            }

            if (empty(pattern)) {
                return ps.join("");
            }

            for (var i = 0; i < ps.length; ++i) {
                pattern = pattern.replace(new RegExp("\\{" + i + "\\}", "gm"), ps[i]);
            }

            return pattern;
        }
        u.format = format;

        function empty(str) {
            return (!valid(str) || str.length === 0);
        }
        u.empty = empty;

        function valid(obj) {
            return (obj !== null && typeof obj !== "undefined");
        }
        u.valid = valid;

        function textNode(node) {
            return valid(node) && node.nodeType === 3;
        }
        u.textNode = textNode;

        function eachKid(dom, exec) {
            if (u.valid(dom) && u.valid(exec)) {
                for (var i = 0; i < dom.children.length; ++i) {
                    var result = exec(dom.children.item(i));
                    if (result) {
                        return result;
                    }
                }
            }

            return false;
        }
        u.eachKid = eachKid;

        function mouseselect(target, disable) {
            if (typeof target.onselectstart != "undefined")
                target.onselectstart = disable ? function () {
                    return false;
                } : null;
else if (typeof target.style.MozUserSelect != "undefined")
                target.style.MozUserSelect = disable ? "none" : null;
        }
        u.mouseselect = mouseselect;

        function width(elem) {
            return elem.offsetWidth | elem.clientWidth | elem.scrollWidth;
        }
        u.width = width;

        function height(elem) {
            return elem.offsetHeight | elem.clientHeight | elem.scrollHeight;
        }
        u.height = height;

        (function (AjaxMethod) {
            AjaxMethod[AjaxMethod["GET"] = 0] = "GET";
            AjaxMethod[AjaxMethod["POST"] = 1] = "POST";
        })(u.AjaxMethod || (u.AjaxMethod = {}));
        var AjaxMethod = u.AjaxMethod;

        // data is a serialized json object
        function ajax(url, method, data, success, fail) {
            var req;
            if (ClipWall.g.ie6) {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } else {
                req = new XMLHttpRequest();
            }

            req.open(method == AjaxMethod.GET ? "GET" : "POST", url, true);
            if (method == AjaxMethod.POST) {
                //Send the proper header information along with the request
                req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                req.setRequestHeader("Content-length", data.length.toString());
                req.setRequestHeader("Connection", "close");
            }

            req.onreadystatechange = function () {
                if (req !== null && 4 == req.readyState) {
                    // due to a webkit issue on iPhone/ipad:
                    // the request completed state will invoke the callback more than one time
                    // we release this object to make sure it's only executed once.
                    var status = req.status;
                    var content = req.responseText;
                    req = null;

                    if (200 == status) {
                        if (content && success) {
                            success(content);
                        }
                    } else if (fail) {
                        fail(status);
                    }
                }
            };

            if (method == AjaxMethod.GET) {
                req.send();
            } else {
                req.send(data);
            }
        }
        u.ajax = ajax;
    })(ClipWall.u || (ClipWall.u = {}));
    var u = ClipWall.u;
})(ClipWall || (ClipWall = {}));
/// <reference path="page.ts" />
/// <reference path="utils.ts" />
// define CSS utility
var ClipWall;
(function (ClipWall) {
    (function (Css) {
        function load(path) {
            var s = ClipWall.g.ce('link');
            ClipWall.g.sat(s, 'type', 'text/css');
            ClipWall.g.sat(s, 'rel', 'stylesheet');
            ClipWall.g.sat(s, 'href', ClipWall.u.fullpath(path));
            ClipWall.g.gt('body')[0].appendChild(s);
        }
        Css.load = load;
        function add(elem, className) {
            if (contains(elem, className)) {
                return;
            }

            elem.className += ' ' + className;
        }
        Css.add = add;

        function remove(elem, className) {
            if (!contains(elem, className)) {
                return;
            }

            var classList = elem.className.split(' ');
            var classId = classList.indexOf(className);
            if (classId >= 0) {
                classList.splice(classId, 1);
            }

            elem.className = classList.join(' ');
        }
        Css.remove = remove;

        function toggle(elem, className) {
            if (contains(elem, className)) {
                remove(elem, className);
            } else {
                add(elem, className);
            }
        }
        Css.toggle = toggle;

        function contains(elem, className) {
            var classList = elem.className.split(' ');
            return classList.indexOf(className) >= 0;
        }
        Css.contains = contains;

        function show(elem, show) {
            if (typeof show === "undefined") { show = true; }
            elem.style.display = show ? "block" : "none";
        }
        Css.show = show;
    })(ClipWall.Css || (ClipWall.Css = {}));
    var Css = ClipWall.Css;
})(ClipWall || (ClipWall = {}));
var ClipWall;
(function (ClipWall) {
    var Content = (function () {
        function Content(text, dom) {
            if (typeof text === "undefined") { text = null; }
            if (typeof dom === "undefined") { dom = null; }
            this.text = text;
            this.dom = dom;
            this.id = Content.IdGen++;
            if (ClipWall.u.valid(dom)) {
                this.imgRatio(dom);
                this.dom = dom.cloneNode(true);
            }
        }
        Content.prototype.toString = function () {
            if (!ClipWall.u.empty(this.text)) {
                return this.text;
            }

            if (ClipWall.u.valid(this.dom)) {
                // strip styles to make it consistent display
                // before stripping, clone it to a new node
                this.strip(this.dom);

                if (this.dom.tagName == "IMG") {
                    return this.dom.outerHTML;
                } else {
                    return this.dom.innerHTML;
                }
            }

            return "";
        };

        Content.prototype.strip = function (elem) {
            if (!ClipWall.u.valid(elem)) {
                return false;
            }

            elem.className = "";
            if (elem.style) {
                ClipWall.g.sat(elem, "style", "");
            }

            if (elem.tagName == "IMG") {
                var ratio = ClipWall.g.gat(elem, "data-ratio");
                if (ClipWall.u.valid(ratio)) {
                    ClipWall.g.sat(elem, "width", "250px");
                    ClipWall.g.sat(elem, "height", parseFloat(ratio) * 250 + "px");
                }

                return false;
            }

            ClipWall.u.eachKid(elem, this.strip);
            return false;
        };

        Content.prototype.imgRatio = function (elem) {
            if (!ClipWall.u.valid(elem)) {
                return false;
            }

            if (elem.tagName == "IMG") {
                var width = elem.clientWidth || elem.offsetWidth || elem.scrollWidth;
                var height = elem.clientHeight || elem.offsetHeight || elem.scrollHeight;
                if (width > 250) {
                    ClipWall.g.sat(elem, "data-ratio", "" + (height / width));
                }

                return false;
            }

            ClipWall.u.eachKid(elem, this.imgRatio);
            return false;
        };

        Content.prototype.fireAdd = function () {
            ClipWall.e.fire(Content.CADD, this);
        };

        Content.prototype.fireDel = function () {
            ClipWall.e.fire(Content.CDEL, this.id);
        };
        Content.CADD = "addcontent";
        Content.CDEL = "removecontent";

        Content.IdGen = 0;
        return Content;
    })();
    ClipWall.Content = Content;
})(ClipWall || (ClipWall = {}));
/// <reference path="content.ts" />
var ClipWall;
(function (ClipWall) {
    var Panel = (function () {
        function Panel() {
            var _this = this;
            this.modes = [];
            this.mLeft = ['0', '-300px'];
            this.mIndex = 0;
            this.panel = ClipWall.g.ce('div');
            ClipWall.g.sat(this.panel, 'class', 'panel');
            this.panel.innerHTML = "

" + "
" + "
" + "
" + "
" + "
" + "
" + "
" + "
" + "
";

            ClipWall.g.b.insertBefore(this.panel, ClipWall.g.b.firstChild);

            //set menu item click handling
            var items = this.panel.querySelectorAll("li");
            for (var i = 0; i < items.length; ++i) {
                ClipWall.g.sat(items[i], "onclick", "panel.mc(this);");
            }

            ClipWall.e.bind(ClipWall.Content.CADD, function (args) {
                _this.newNode(args[0]);
            });

            // create default mode
            this.createMode();
        }
        Panel.CreatePanel = function () {
            return new Panel();
        };

        Panel.prototype.newNode = function (content) {
            if (!ClipWall.u.valid(content)) {
                return;
            }

            var div = ClipWall.g.ce("div");
            div.innerHTML = content.toString();
            ClipWall.g.ge("cnt").appendChild(div);
        };

        Panel.prototype.createMode = function () {
            this.modes.push(new ClipWall.SelectMode(this.panel));
            this.modes.push(new ClipWall.ClickMode(this.panel));

            // use one clip mode for default
            this.modes[0].apply();
        };

        Panel.prototype.mc = function (item) {
            switch (item.className) {
                case "b_expand":
                    this.clickExpand();
                    break;
                case "b_pick":
                    this.clickPickMode();
                    break;
                case "b_select":
                    this.clickSelectMode();
                    break;
                case "b_login":
                    this.clickLogin();
                    break;
                case "b_submit":
                    this.clickSubmit();
                    break;
            }
        };

        Panel.prototype.clickExpand = function () {
            this.panel.style.marginLeft = this.mLeft[this.mIndex];
            this.mIndex = (this.mIndex + 1) % this.mLeft.length;
        };

        Panel.prototype.clickPickMode = function () {
            var mode = this.getMode(ClipWall.ClickMode.Name);
            if (mode == null) {
                throw new Error('this mode is not supported');
            }

            this.disposeAll();
            mode.apply();
        };

        Panel.prototype.clickSelectMode = function () {
            var mode = this.getMode(ClipWall.SelectMode.Name);
            if (mode == null) {
                throw new Error('this mode is not supported');
            }

            this.disposeAll();
            mode.apply();
        };

        Panel.prototype.clickLogin = function () {
        };

        // submit the data to server
        Panel.prototype.clickSubmit = function () {
            var cnt = ClipWall.g.ge("cnt");
            var data = {
                ID: new Date().getTime(),
                Title: ClipWall.g.d.title,
                URL: ClipWall.g.w.location.href,
                Sections: [],
                Images: [],
                Style: null
            };

            // put all content
            ClipWall.u.eachKid(cnt, function (kid) {
                data.Sections.push(kid.innerHTML);
            });

            // to-do: put all captured images here
            // to-do: analyze all style and put it here
            var postUri = ClipWall.g.h + "api/clip/post";
            ClipWall.u.ajax(postUri, ClipWall.u.AjaxMethod.POST, JSON.stringify(data), function (res) {
                alert(res);
            }, function (fail) {
                alert("fail status:" + fail);
            });
        };

        Panel.prototype.getMode = function (name) {
            for (var i = 0; i < this.modes.length; ++i) {
                if (this.modes[i].name === name) {
                    return this.modes[i];
                }
            }

            return null;
        };

        Panel.prototype.disposeAll = function () {
            for (var i = 0; i < this.modes.length; ++i) {
                this.modes[i].dispose();
            }
        };
        return Panel;
    })();
    ClipWall.Panel = Panel;
})(ClipWall || (ClipWall = {}));
var ClipWall;
(function (ClipWall) {
    // pointer-events:none;
    var greyoutPattern = 'top:{0}px;left:{1}px;width:{2}px;height:{3}px';

    // if parameter is empty, create full screen to cover document
    function createOverlay(under) {
        var s = ClipWall.g.ce('div');
        if (under === ClipWall.g.b) {
            ClipWall.g.sat(s, 'class', 'greyout');
        } else {
            ClipWall.g.sat(s, 'class', 'overlay');
            cover(s, under);
            //s.innerHTML = "
drag to expand it...
";
        }

        // add identifier to it
        ClipWall.g.sat(s, "data-cw", "1");
        ClipWall.g.b.appendChild(s);
        return s;
    }
    ClipWall.createOverlay = createOverlay;

    function cover(overlay, under) {
        var rect = { top: 0, left: 0, width: 0, height: 0 };
        if (ClipWall.u.valid(under)) {
            rect = under.getBoundingClientRect();
        }

        ClipWall.g.sat(overlay, 'style', ClipWall.u.format(greyoutPattern, rect.top.toString(), rect.left.toString(), rect.width.toString(), rect.height.toString()));
    }
    ClipWall.cover = cover;

    function isOverlay(elem) {
        if (elem) {
            return ClipWall.g.gat(elem, "data-cw") === "1";
        }

        return false;
    }
    ClipWall.isOverlay = isOverlay;

    function updateOverlay(elem, x, y, w, h) {
        if (y !== 0)
            elem.style.top = (parseInt(elem.style.top) + y) + 'px';
        if (x !== 0)
            elem.style.left = (parseInt(elem.style.left) + x) + 'px';
        if (w !== 0)
            elem.style.width = (parseInt(elem.style.width) + w) + 'px';
        if (h !== 0)
            elem.style.height = (parseInt(elem.style.height) + h) + 'px';
    }
    ClipWall.updateOverlay = updateOverlay;
})(ClipWall || (ClipWall = {}));
// define some basic collections
var ClipWall;
(function (ClipWall) {
    (function (c) {
        var KeyValuePair = (function () {
            function KeyValuePair(key, value) {
                this.key = key;
                this.value = value;
            }
            return KeyValuePair;
        })();
        c.KeyValuePair = KeyValuePair;

        var List = (function () {
            function List() {
                this.data = [];
            }
            List.prototype.add = function (elem) {
                if (ClipWall.u.valid(elem)) {
                    this.data.push(elem);
                }
            };

            List.prototype.remove = function (elem) {
                var found = this.indexOf(elem);
                if (found != -1) {
                    this.removeAt(found);
                }
            };

            List.prototype.removeAt = function (i) {
                if (i >= 0 && i < this.count) {
                    this.data.splice(i, 1);
                }
            };

            List.prototype.item = function (i) {
                if (i >= 0 && i < this.count) {
                    return this.data[i];
                }

                return null;
            };

            List.prototype.indexOf = function (elem) {
                var found = -1;
                for (var i = 0; i < this.count; i++) {
                    if (elem === this.data[i]) {
                        found = i;
                        break;
                    }
                }

                return found;
            };

            Object.defineProperty(List.prototype, "count", {
                get: function () {
                    return this.data.length;
                },
                enumerable: true,
                configurable: true
            });
            return List;
        })();
        c.List = List;

        var Dictionary = (function () {
            function Dictionary() {
                this.keys = new List();
                this.values = new List();
            }
            Dictionary.prototype.add = function (key, value) {
                if (ClipWall.u.valid(key) && ClipWall.u.valid(value) && !this.containsKey(key)) {
                    this.keys.add(key);
                    this.values.add(value);
                }
            };

            Dictionary.prototype.containsKey = function (key) {
                if (ClipWall.u.valid(key)) {
                    return this.keys.indexOf(key) != -1;
                }

                return false;
            };

            Dictionary.prototype.containsValue = function (value) {
                if (ClipWall.u.valid(value)) {
                    return this.values.indexOf(value) != -1;
                }

                return false;
            };

            Dictionary.prototype.remove = function (key) {
                this.removeAt(this.keys.indexOf(key));
            };

            Dictionary.prototype.removeAt = function (index) {
                if (index >= 0 && index < this.count) {
                    this.keys.removeAt(index);
                    this.values.removeAt(index);
                }
            };

            Dictionary.prototype.pair = function (i) {
                if (i >= 0 && i < this.count) {
                    return new KeyValuePair(this.keys.item(i), this.values.item(i));
                }

                return null;
            };

            Object.defineProperty(Dictionary.prototype, "count", {
                get: function () {
                    return this.keys.count;
                },
                enumerable: true,
                configurable: true
            });
            return Dictionary;
        })();
        c.Dictionary = Dictionary;
    })(ClipWall.c || (ClipWall.c = {}));
    var c = ClipWall.c;
})(ClipWall || (ClipWall = {}));
var ClipWall;
(function (ClipWall) {
    var Point = (function () {
        function Point(x, y) {
            if (typeof x === "undefined") { x = 0; }
            if (typeof y === "undefined") { y = 0; }
            this.x = x;
            this.y = y;
        }
        Point.from = function (me) {
            return new Point(me.clientX, me.clientY);
        };
        Point.prototype.substract = function (p) {
            return new Point(this.x - p.x, this.y - p.y);
        };

        Point.prototype.dist = function (p) {
            var gap = this.substract(p);
            return Math.sqrt(gap.x * gap.x + gap.y * gap.y);
        };
        return Point;
    })();
    ClipWall.Point = Point;
})(ClipWall || (ClipWall = {}));
/// <reference path="clip.ts" />
/// <reference path="mode.share.ts" />
/// <reference path="../lib/page.ts" />
/// <reference path="../lib/utils.ts" />
/// <reference path="../lib/coll.ts" />
/// <reference path="../lib/point.ts" />
var ClipWall;
(function (ClipWall) {
    var ClickMode = (function () {
        function ClickMode(panel) {
            var _this = this;
            this.panel = panel;
            this.selections = new ClipWall.c.Dictionary();
            this.overlays = new ClipWall.c.List();
            this.moflag = true;
            this.mouseOver = function (e) {
                if (!_this.moflag) {
                    console.log('is this useful?');
                    return;
                }

                _this.moflag = false;
                ClipWall.g.st(function () {
                    _this.moflag = true;
                }, 200);

                _this.overTarget(ClipWall.u.evt(e).target);
                ClipWall.u.stop(e);
            };

            this.mouseClick = function (e) {
                _this.clickOverlay(e);
                ClipWall.u.stop(e);
            };

            this.scroll = function () {
                _this.updateSelections();
            };
        }
        Object.defineProperty(ClickMode.prototype, "name", {
            get: function () {
                return ClickMode.Name;
            },
            enumerable: true,
            configurable: true
        });

        ClickMode.prototype.apply = function () {
            this.initOffset = new ClipWall.Point(ClipWall.g.w.pageXOffset, ClipWall.g.w.pageYOffset);
            this.hook(true);
            ClipWall.e.be(ClipWall.g.w, "scroll", this.scroll);
        };

        ClickMode.prototype.dispose = function () {
            this.hook(false);
        };

        ClickMode.prototype.hook = function (bind) {
            var handle = bind ? ClipWall.e.be : ClipWall.e.ue;
            handle(ClipWall.g.b, "mouseover", this.mouseOver);
            handle(ClipWall.g.b, "contextmenu", this.mouseClick);

            // handle(g.b, "mousemove", this.mouseMove);
            ClipWall.u.mouseselect(ClipWall.g.b, bind);
        };

        ClickMode.prototype.overTarget = function (target) {
            console.log('over: ' + target.tagName + '|x:' + target.offsetLeft + '|y:' + target.offsetTop);

            if (this.lastFocus && ClipWall.u.contains(this.lastFocus.value, target)) {
                return;
            }

            if (this.excludeNode(target)) {
                this.removeLastIfNotSelected();
                return;
            }

            if (!ClipWall.u.valid(this.lastFocus)) {
                this.lastFocus = new ClipWall.c.KeyValuePair(this.greyout(target), target);
                return;
            }

            if (target != this.lastFocus.value && !this.selections.containsValue(target)) {
                ClipWall.cover(this.lastFocus.key, target);
                this.lastFocus.value = target;
            }
        };

        ClickMode.prototype.greyout = function (target) {
            var s = ClipWall.createOverlay(target);
            this.overlays.add(s);
            ClipWall.e.be(s, "click", this.mouseClick);

            //e.be(s, "mouseout", this.removeLastIfNotSelected);
            return s;
        };

        ClickMode.prototype.clickOverlay = function (event) {
            if (!ClipWall.u.valid(event)) {
                return;
            }

            var overlay = ClipWall.u.evt(event).target;
            if (event.button === 2) {
                var lastTarget = ClipWall.u.valid(this.lastFocus) ? this.lastFocus.value : null;
                if (ClipWall.u.valid(overlay) && overlay !== lastTarget) {
                    this.overTarget(overlay);
                }
            }

            if (!ClipWall.isOverlay(overlay)) {
                return;
            }

            if (!this.selections.containsKey(overlay)) {
                if (this.lastFocus && this.lastFocus.key == overlay) {
                    if (event.button === 0) {
                        this.removeChildren(this.lastFocus.value);
                        this.selections.add(this.lastFocus.key, this.lastFocus.value);
                        new ClipWall.Content(null, this.lastFocus.value).fireAdd();
                        this.lastFocus = null;
                    }
                }
            } else {
                this.removeSelection(overlay);
            }
        };

        ClickMode.prototype.removeLastIfNotSelected = function () {
            if (ClipWall.u.valid(this.lastFocus) && !this.selections.containsKey(this.lastFocus.key)) {
                this.removeElement(this.lastFocus.key);
                this.lastFocus = null;
            }
        };

        ClickMode.prototype.removeChildren = function (elem) {
            for (var i = this.selections.count - 1; i >= 0; i--) {
                var pair = this.selections.pair(i);
                if (ClipWall.u.contains(elem, pair.value)) {
                    this.removeSelection(pair.key);
                }
            }
        };

        ClickMode.prototype.removeSelection = function (elem) {
            this.selections.remove(elem);
            this.removeElement(elem);
        };

        ClickMode.prototype.removeElement = function (elem) {
            var idx = this.overlays.indexOf(elem);
            if (idx !== -1) {
                this.overlays.removeAt(idx);
                ClipWall.g.b.removeChild(elem);
            }
        };

        ClickMode.prototype.updateSelections = function () {
            this.removeLastIfNotSelected();
            var newPoint = new ClipWall.Point(pageXOffset, pageYOffset);
            var gap = newPoint.substract(this.initOffset);
            this.initOffset = newPoint;

            for (var i = 0; i < this.selections.count; i++) {
                ClipWall.updateOverlay(this.selections.pair(i).key, -gap.x, -gap.y, 0, 0);
            }
        };

        ClickMode.prototype.excludeNode = function (elem) {
            if (!ClipWall.u.valid(elem) || ClipWall.isOverlay(elem) || elem.tagName === "IFRAME" || elem.tagName === "FORM" || elem.tagName === "INPUT" || elem.tagName === "SELECT" || elem.tagName === "TEXTAREA") {
                return true;
            }

            if (ClipWall.u.eachKid(elem, this.excludeNode)) {
                return true;
            }

            if (elem.tagName === "IMG" || ClipWall.u.textNode(elem)) {
                return false;
            }

            // maybe if the element's client height/width is too big, we should exclude
            return ClipWall.u.width(ClipWall.g.b) <= ClipWall.u.width(elem) * 2 || ClipWall.u.height(ClipWall.g.b) <= ClipWall.u.height(elem) * 2;
        };
        ClickMode.Name = "m_clk";
        return ClickMode;
    })();
    ClipWall.ClickMode = ClickMode;
})(ClipWall || (ClipWall = {}));
/// <reference path="utils.ts" />
var ClipWall;
(function (ClipWall) {
    var Scrape = (function () {
        function Scrape(start, selecting, selected) {
            var _this = this;
            this._flag = 0;
            this.onstart = start;
            this.onselecting = selecting;
            this.onselected = selected;

            this.mouseDown = function (e) {
                _this._target = ClipWall.u.evt(e).target;
                _this._position = ClipWall.Point.from(e);
                if (_this._flag === 0) {
                    _this._flag = 1;
                }

                if (ClipWall.u.valid(_this.onstart)) {
                    if (_this.onstart(_this)) {
                        ClipWall.u.stop(e);
                    }
                }
            };

            this.mouseMove = function (e) {
                if (_this._flag == 0) {
                    return;
                }

                _this._position = ClipWall.Point.from(e);
                if (_this._flag == 1) {
                    _this._flag = 2;
                }

                if (ClipWall.u.valid(_this.onselecting)) {
                    if (_this.onselecting(_this)) {
                        ClipWall.u.stop(e);
                    }
                }
            };

            this.mouseUp = function (e) {
                if (_this._flag != 2) {
                    return;
                }

                _this._flag = 0;
                if (ClipWall.u.valid(_this.onselected)) {
                    if (_this.onselected(_this)) {
                        ClipWall.u.stop(e);
                    }
                }

                _this._target = null;
            };
        }
        Object.defineProperty(Scrape.prototype, "target", {
            get: function () {
                return this._target;
            },
            enumerable: true,
            configurable: true
        });

        Object.defineProperty(Scrape.prototype, "position", {
            get: function () {
                return this._position;
            },
            enumerable: true,
            configurable: true
        });

        Scrape.prototype.enable = function (bind) {
            var handle = bind ? ClipWall.e.be : ClipWall.e.ue;
            handle(ClipWall.g.b, "mousedown", this.mouseDown);
            handle(ClipWall.g.b, "mousemove", this.mouseMove);
            handle(ClipWall.g.b, "mouseup", this.mouseUp);
        };
        return Scrape;
    })();
    ClipWall.Scrape = Scrape;
})(ClipWall || (ClipWall = {}));
/// <reference path="mode.share.ts" />
/// <reference path="../lib/page.ts" />
/// <reference path="../lib/scrape.ts" />
/// <reference path="../lib/utils.ts" />
var ClipWall;
(function (ClipWall) {
    var DragMode = (function () {
        function DragMode() {
            var _this = this;
            this.overlays = new ClipWall.c.List();
            this.selection = new ClipWall.Scrape(function (selection) {
                _this.lastPosition = selection.position;
                return true;
            }, function (selection) {
                var newP = selection.position;
                if (!ClipWall.u.valid(_this.lastPosition)) {
                    _this.lastPosition = newP;
                    return true;
                }

                var gap = newP.substract(_this.lastPosition);
                if (!ClipWall.u.valid(_this.dragTarget)) {
                    _this.dragTarget = ClipWall.createOverlay(null);
                    ClipWall.updateOverlay(_this.dragTarget, _this.lastPosition.x, _this.lastPosition.y, gap.x, gap.y);
                } else {
                    ClipWall.updateOverlay(_this.dragTarget, 0, 0, gap.x, gap.y);
                }

                _this.lastPosition = newP;
                return true;
            }, function () {
                if (ClipWall.u.valid(_this.dragTarget)) {
                    _this.clearOverlap(_this.dragTarget.getBoundingClientRect());
                    _this.overlays.add(_this.dragTarget);
                    _this.dragTarget = null;
                }

                return true;
            });
        }
        Object.defineProperty(DragMode.prototype, "name", {
            get: function () {
                return DragMode.Name;
            },
            enumerable: true,
            configurable: true
        });

        DragMode.prototype.apply = function () {
            this.selection.enable(true);
            ClipWall.u.mouseselect(ClipWall.g.b, true);
        };

        DragMode.prototype.dispose = function () {
            this.selection.enable(false);
            ClipWall.u.mouseselect(ClipWall.g.b, false);
        };

        DragMode.prototype.clearOverlap = function (rect) {
            for (var i = this.overlays.count - 1; i >= 0; i--) {
                if (this.overlap(rect, this.overlays.item(i).getBoundingClientRect())) {
                    ClipWall.g.b.removeChild(this.overlays.item(i));
                    this.overlays.removeAt(i);
                }
            }
        };

        DragMode.prototype.overlap = function (rect1, rect2) {
            return true;
        };
        DragMode.Name = "m_drg";
        return DragMode;
    })();
    ClipWall.DragMode = DragMode;
})(ClipWall || (ClipWall = {}));
/// <reference path="clip.ts" />
/// <reference path="../lib/scrape.ts" />
var ClipWall;
(function (ClipWall) {
    var SelectMode = (function () {
        function SelectMode(panel) {
            var _this = this;
            this.panel = panel;
            this.scrape = new ClipWall.Scrape(function (scrape) {
                return false;
            }, function (scrape) {
                return false;
            }, function () {
                _this.detectSelection();
                return false;
            });
        }
        Object.defineProperty(SelectMode.prototype, "name", {
            get: function () {
                return SelectMode.Name;
            },
            enumerable: true,
            configurable: true
        });

        SelectMode.prototype.apply = function () {
            this.scrape.enable(true);
        };

        SelectMode.prototype.dispose = function () {
            this.scrape.enable(false);
        };

        SelectMode.prototype.detectSelection = function () {
            if (!ClipWall.u.contains(this.panel, this.scrape.target)) {
                var text = this.selectedText();
                if (!ClipWall.u.empty(text)) {
                    new ClipWall.Content(text, null).fireAdd();
                    this.highlight('yellow');
                }
            }
        };

        SelectMode.prototype.makeEditableAndHighlight = function (color) {
            var sel = ClipWall.g.w.getSelection();
            ClipWall.g.d.designMode = "on";
            if (sel.rangeCount && sel.getRangeAt) {
                var range = sel.getRangeAt(0);
                sel.removeAllRanges();
                sel.addRange(range);
            }

            if (!ClipWall.g.d.execCommand("HiliteColor", false, color)) {
                ClipWall.g.d.execCommand("BackColor", false, color);
            }
            ClipWall.g.d.designMode = "off";
        };

        SelectMode.prototype.highlight = function (color) {
            if (ClipWall.g.w.getSelection) {
                try  {
                    if (!document.execCommand("BackColor", false, color)) {
                        this.makeEditableAndHighlight(color);
                    }
                } catch (ex) {
                    this.makeEditableAndHighlight(color);
                }
            } else if (ClipWall.g.d.selection && ClipWall.g.d.selection.createRange) {
                // IE <= 8 case
                var range = ClipWall.g.d.selection.createRange();
                range.execCommand("BackColor", false, color);
            }
        };

        SelectMode.prototype.selectedText = function () {
            if (ClipWall.g.w.getSelection) {
                var sel = ClipWall.g.w.getSelection();
                if (sel.rangeCount && sel.getRangeAt) {
                    var r = sel.getRangeAt(0);
                    var bounding = r.getBoundingClientRect();
                    if (bounding.height * 2 < ClipWall.u.height(ClipWall.g.b) && bounding.width * 2 < ClipWall.u.width(ClipWall.g.b)) {
                        return sel.getRangeAt(0).toString();
                    }
                }
            } else if (ClipWall.g.d.selection.createRange) {
                var tr = ClipWall.g.d.selection.createRange();
                if (tr.boundingHeight * 2 < ClipWall.u.height(ClipWall.g.b) && tr.boundingWidth * 2 < ClipWall.u.width(ClipWall.g.b)) {
                    return tr.text;
                }
            }

            return '';
        };
        SelectMode.Name = "m_sel";
        return SelectMode;
    })();
    ClipWall.SelectMode = SelectMode;
})(ClipWall || (ClipWall = {}));
/// <reference path="../lib/page.ts" />
/// <reference path="../lib/utils.ts" />
/// <reference path="../lib/css.ts" />
/// <reference path="panel.ts" />
/// <reference path="mode.click.ts" />
/// <reference path="mode.drag.ts" />
/// <reference path="mode.select.ts" />
var loaded;
var panel = {};

if (!loaded) {
    loaded = true;

    // load css file we need
    ClipWall.Css.load("clip");

    // create a panel
    panel = ClipWall.Panel.CreatePanel();
}


text:
package com.saasovation.agilepm.domain.model.product;

import com.saasovation.agilepm.domain.model.DomainRegistry;
import com.saasovation.agilepm.domain.model.product.backlogitem.BacklogItem;
import com.saasovation.agilepm.domain.model.tenant.Tenant;
import com.saasovation.agilepm.domain.model.tenant.TenantId;

import java.util.Collection;

public class BusinessPriorityCalculator {

	public BusinessPriorityTotals businessPriorityTotals(TenantId aTenantId,ProductId aProductId){
		int totalBenefit = 0;
		int totalPenalty = 0;
		int totalCost    = 0;
		int totalRisk    = 0;
		Tenant tenant = DomainRegistry.tenantRepository()
				.tenantOfId(aTenantId);
		Collection<BacklogItem> outstandingBacklogItems =
				DomainRegistry.backlogItemRepository()
				.allOutstandingBacklogItems(tenant,aProductId);
		for(BacklogItem backlogItem:outstandingBacklogItems){
			BusinessPriorityRating rating = backlogItem.businessPriority().rating();
			totalBenefit +=rating.benefit();
			totalPenalty +=rating.penalty();
			totalCost    +=rating.cost();
			totalRisk	 +=rating.risk();
		}
		BusinessPriorityTotals businessPriorityTotals =
				new BusinessPriorityTotals(
						totalBenefit,
						totalPenalty,
						totalBenefit+totalPenalty,
						totalCost,
						totalRisk);

		return businessPriorityTotals;
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.gmail.socraticphoenix.randores.waila;

import com.gmail.socraticphoenix.randores.IRandoresItem;
import com.gmail.socraticphoenix.randores.block.RandoresTileEntity;
import com.gmail.socraticphoenix.randores.crafting.forge.CraftiniumForge;
import com.gmail.socraticphoenix.randores.crafting.forge.CraftiniumForgeTileEntity;
import com.gmail.socraticphoenix.randores.RandoresKeys;
import mcp.mobius.waila.api.IWailaConfigHandler;
import mcp.mobius.waila.api.IWailaDataAccessor;
import mcp.mobius.waila.api.IWailaDataProvider;
import mcp.mobius.waila.api.IWailaRegistrar;
import mcp.mobius.waila.api.SpecialChars;
import net.minecraft.block.Block;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.items.ItemStackHandler;

import java.util.List;

public class RandoresWailaHandler implements IWailaDataProvider {
    private boolean forgeMode;

    public RandoresWailaHandler(boolean forgeMode) {
        this.forgeMode = forgeMode;
    }

    public static void callbackRegister(IWailaRegistrar registrar) {
        registrar.registerStackProvider(new RandoresWailaHandler(false), IRandoresItem.class);
        registrar.registerBodyProvider(new RandoresWailaHandler(false), IRandoresItem.class);
        registrar.registerBodyProvider(new RandoresWailaHandler(true), CraftiniumForgeTileEntity.class);
        registrar.registerNBTProvider(new RandoresWailaHandler(true), CraftiniumForgeTileEntity.class);
    }

    @Override
    public ItemStack getWailaStack(IWailaDataAccessor iWailaDataAccessor, IWailaConfigHandler iWailaConfigHandler) {
        if (!this.forgeMode && iWailaDataAccessor.getBlock() instanceof IRandoresItem) {
            ItemStack stack = new ItemStack(((IRandoresItem) iWailaDataAccessor.getBlock()).getThis());
            TileEntity entity = iWailaDataAccessor.getTileEntity();
            if (entity != null && entity instanceof RandoresTileEntity) {
                ((RandoresTileEntity) entity).getData().applyTo(stack);
            }
            return stack;
        }

        return ItemStack.EMPTY;
    }

    @Override
    public List<String> getWailaHead(ItemStack itemStack, List<String> list, IWailaDataAccessor iWailaDataAccessor, IWailaConfigHandler iWailaConfigHandler) {
        return list;
    }

    @Override
    public List<String> getWailaBody(ItemStack itemStack, List<String> list, IWailaDataAccessor iWailaDataAccessor, IWailaConfigHandler iWailaConfigHandler) {
        Block block = iWailaDataAccessor.getBlock();
        if (this.forgeMode && block instanceof CraftiniumForge) {
            NBTTagCompound randores = iWailaDataAccessor.getNBTData().getCompoundTag("randores");
            int cookTime = randores.getInteger("cook_time");
            int totalCookTime = randores.getInteger("cook_time_total");
            int burnTime = randores.getInteger("burn_time");
            if (burnTime > 0) {
                ItemStackHandler input = new ItemStackHandler();
                ItemStackHandler output = new ItemStackHandler();
                ItemStackHandler fuel = new ItemStackHandler();
                input.deserializeNBT(randores.getCompoundTag("input"));
                fuel.deserializeNBT(randores.getCompoundTag("fuel"));
                output.deserializeNBT(randores.getCompoundTag("output"));

                ItemStack[] inventory = new ItemStack[3];
                inventory[0] = input.getStackInSlot(0);
                inventory[1] = fuel.getStackInSlot(0);
                inventory[2] = output.getStackInSlot(0);
                for (int i = 0; i < inventory.length; i++) {
                    if (inventory[i] == ItemStack.EMPTY) {
                        inventory[i] = null;
                    }
                }

                String renderStr = "";

                if (inventory[0] != null) {
                    String name = inventory[0].getItem().getRegistryName().toString();
                    renderStr += SpecialChars.getRenderString("waila.stack", "1", name, String.valueOf(inventory[0].getCount()), String.valueOf(inventory[0].getItemDamage()));
                } else {
                    renderStr += SpecialChars.getRenderString("waila.stack", "2");
                }

                if (inventory[1] != null) {
                    String name = inventory[1].getItem().getRegistryName().toString();
                    renderStr += SpecialChars.getRenderString("waila.stack", "1", name, String.valueOf(inventory[1].getCount()), String.valueOf(inventory[1].getItemDamage()));
                } else {
                    renderStr += SpecialChars.getRenderString("waila.stack", "2");
                }

                renderStr += SpecialChars.getRenderString("waila.progress", String.valueOf(cookTime), String.valueOf(totalCookTime));

                if (inventory[2] != null) {
                    String name = inventory[2].getItem().getRegistryName().toString();
                    renderStr += SpecialChars.getRenderString("waila.stack", "1", name, String.valueOf(inventory[2].getCount()), String.valueOf(inventory[2].getItemDamage()));
                } else {
                    renderStr += SpecialChars.getRenderString("waila.stack", "2");
                }
                list.add(renderStr);
                list.add(I18n.format(RandoresKeys.FORGE_POWER) + ": " + randores.getInteger("furnace_speed"));
            }
        }

        return list;
    }

    @Override
    public List<String> getWailaTail(ItemStack itemStack, List<String> list, IWailaDataAccessor iWailaDataAccessor, IWailaConfigHandler iWailaConfigHandler) {
        return list;
    }

    @Override
    public NBTTagCompound getNBTData(EntityPlayerMP entityPlayerMP, TileEntity te, NBTTagCompound tag, World world, BlockPos blockPos) {
        if (this.forgeMode && te != null) {
            te.writeToNBT(tag);
        }
        return tag;
    }

}


text:
class Money
  # Provides classes that aid in the ability of exchange one currency with
  # another.
  module Bank

    # The lowest Money::Bank error class.
    # All Money::Bank errors should inherit from it.
    class Error < StandardError
    end

    # Raised when the bank doesn't know about the conversion rate
    # for specified currencies.
    class UnknownRate < Error
    end

    # Money::Bank::Base is the basic interface for creating a money exchange
    # object, also called Bank.
    #
    # A Bank is responsible for storing exchange rates, take a Money object as
    # input and returns the corresponding Money object converted into an other
    # currency.
    #
    # This class exists for aiding in the creating of other classes to exchange
    # money between different currencies. When creating a subclass you will
    # need to implement the following methods to exchange money between
    # currencies:
    #
    # - #exchange_with(Money) #=> Money
    #
    # See Money::Bank::VariableExchange for a real example.
    #
    # Also, you can extend +Money::Bank::VariableExchange+ instead of
    # +Money::Bank::Base+ if your bank implementation needs to store rates
    # internally.
    #
    # @abstract Subclass and override +#exchange_with+ to implement a custom
    #  +Money::Bank+ class. You can also override +#setup+ instead of
    #  +#initialize+ to setup initial variables, etc.
    class Base

      # Returns the singleton instance of the Base bank.
      #
      # @return [Money::Bank::Base]
      def self.instance
        @singleton ||= new
      end

      # The rounding method to use when exchanging rates.
      attr_accessor :rounding_method

      # Initializes a new +Money::Bank::Base+ object. An optional block can be
      # passed to dictate the rounding method that +#exchange_with+ can use.
      #
      # @yield [n, currency] Optional block to round value after exchanging.
      # @yieldparam [BigDecimal, Money::Currency] The resulting amount and
      #  target currency.
      # @yieldreturn [Numeric]
      #
      # @return [Money::Bank::Base]
      #
      # @example
      #   Money::Bank::Base.new #=> #<Money::Bank::Base @rounding_method=nil>
      #   Money::Bank::Base.new {|n|
      #     n.floor
      #   } #=> #<Money::Bank::Base @round_method=#<Proc>>
      def initialize(&block)
        @rounding_method = block
        setup
      end

      # Called after initialize. Subclasses can use this method to setup
      # variables, etc that they normally would in +#initialize+.
      #
      # @abstract Subclass and override +#setup+ to implement a custom
      #  +Money::Bank+ class.
      #
      # @return [self]
      def setup
      end

      # Exchanges the given +Money+ object to a new +Money+ object in
      # +to_currency+.
      #
      # @abstract Subclass and override +#exchange_with+ to implement a custom
      #  +Money::Bank+ class.
      #
      # @raise NotImplementedError
      #
      # @param [Money] from The +Money+ object to exchange from.
      # @param [Money::Currency, String, Symbol] to_currency The currency
      #  string or object to exchange to.
      # @param  [Symbol] round_mode
      #         BigDecimal's rounding mode, to round result using target
      #         currency's decimal_places.
      # @yield [n, currency] Optional block to round value after exchanging.
      # @yieldparam [BigDecimal, Money::Currency] The resulting amount and
      #  target currency.
      # @yieldreturn [Numeric]
      #
      # @return [Money]
      def exchange_with(from, to_currency, rounding_mode = nil, &block)
        raise NotImplementedError, "#exchange_with must be implemented"
      end

      # Given two currency strings or object, checks whether they're both the
      # same currency. Return +true+ if the currencies are the same, +false+
      # otherwise.
      #
      # @param [Money::Currency, String, Symbol] currency1 The first currency
      #  to compare.
      # @param [Money::Currency, String, Symbol] currency2 The second currency
      #  to compare.
      #
      # @return [Boolean]
      #
      # @example
      #   same_currency?("usd", "USD")                #=> true
      #   same_currency?("usd", "EUR")                #=> false
      #   same_currency?("usd", Currency.new("USD"))   #=> true
      #   same_currency?("usd", "USD")                #=> true
      def same_currency?(currency1, currency2)
        Currency.wrap(currency1) == Currency.wrap(currency2)
      end

      # Rounds value with a given block or rounding_method.
      def round(value, currency, mode = nil, &block)
        method = block || mode || rounding_method
        return value unless method
        if method.is_a?(Symbol)
          value.round(currency.decimal_places, method)
        else
          method.call(value, currency)
        end
      end
    end
  end
end


text:
Contact Us

    <form name="contactForm" class="form-horizontal" ng-submit="contact(contactForm.$valid)" novalidate>

            Your Name
            <input type="text" name="name" ng-model="name" id="name" class="form-control" placeholder="Your name" required>

Your name is required.

            Your Email Address
            <input type="email" name="email" ng-model="email" id="email" class="form-control" placeholder="Your email address" required>

Your email address is required.

Your email address is invalid.

            Your subject
            <select name="subject" ng-model="subject" id="subject" class="form-control" required>
              <option value="Option 1">Option 1</option>
              <option value="Option 2">Option 2</option>
              <option value="Option 3">Option 3</option>
            </select>

Your message is required.

            Your Message
            <textarea type="text" name="message" ng-model="message" id="message" class="form-control" placeholder="Your message" cols="3" rows="4" required></textarea>

Your message is required.

            <button type="submit" class="btn btn-default" ng-disabled="submitButtonDisabled">
              {{submitButton || 'Send'}}
            </button>

    </form>


text:
class CreateFollows < ActiveRecord::Migration
  def change
    create_table :follows do |t|
      t.integer :followee_id, null: false
      t.integer :follower_id, null: false

      t.timestamps
    end

    add_index :follows, :followee_id
    add_index :follows, :follower_id
    add_index :follows, [:followee_id, :follower_id], unique: true
  end
end


text:
/*
 * A dummy Socket implementation which just holds an error message.
 */

#include <stdio.h>
#include <assert.h>

#define DEFINE_PLUG_METHOD_MACROS
#include "tree234.h"
#include "putty.h"
#include "network.h"

typedef struct Socket_error_tag *Error_Socket;

struct Socket_error_tag {
    const struct socket_function_table *fn;
    /* the above variable absolutely *must* be the first in this structure */

    char *error;
    Plug plug;
};

static Plug sk_error_plug(Socket s, Plug p)
{
    Error_Socket ps = (Error_Socket) s;
    Plug ret = ps->plug;
    if (p)
    ps->plug = p;
    return ret;
}

static void sk_error_close(Socket s)
{
    Error_Socket ps = (Error_Socket) s;

    sfree(ps->error);
    sfree(ps);
}

static const char *sk_error_socket_error(Socket s)
{
    Error_Socket ps = (Error_Socket) s;
    return ps->error;
}

static char *sk_error_peer_info(Socket s)
{
    return NULL;
}

Socket new_error_socket(const char *errmsg, Plug plug)
{
    static const struct socket_function_table socket_fn_table = {
    sk_error_plug,
    sk_error_close,
    NULL /* write */,
    NULL /* write_oob */,
    NULL /* write_eof */,
    NULL /* flush */,
    NULL /* set_frozen */,
    sk_error_socket_error,
    sk_error_peer_info,
    };

    Error_Socket ret;

    ret = snew(struct Socket_error_tag);
    ret->fn = &socket_fn_table;
    ret->plug = plug;
    ret->error = dupstr(errmsg);

    return (Socket) ret;
}


text:
require "spec_helper"

describe Mongoid::Persistence::Operations::Remove do

  before do
  end

end


text:
module UserAuthenticationConcern
  extend ActiveSupport::Concern
  include Devise::SignInCallbacks

  included do
    # Include default devise modules. Others available are:
    # :validatable, :confirmable, :lockable, :timeoutable and :omniauthable
    devise :database_authenticatable, :registerable,
           :recoverable, :rememberable, :trackable

    before_sign_in :create_instance_user
    after_create :create_instance_user

    validates :email, presence: true, if: :email_required?
    validates :password, presence: true, if: :password_required?
    validates :password, confirmation: true, if: :password_required?
    validates :password, length: { within: Devise.password_length, allow_blank: true }

    extend ReplacementClassMethods
    include UserOmniauthConcern
  end

  private

  # Checks whether a password is needed or not. For validations only.
  # Passwords are always required if it's a new record, or if the password or confirmation are
  # being set somewhere.
  def password_required?
    !persisted? || !password.nil? || !password_confirmation.nil?
  end

  def email_required?
    true
  end

  def create_instance_user
    instance_users.create if persisted? && instance_users.empty?
  end

  module ReplacementClassMethods
    # Overrides Devise::Models::Authenticatable::ClassMethods#find_first_by_auth_conditions
    # This will check the user's various emails instead of just one email per user.
    #
    # @return [User|nil] The user matching the given conditions.
    def find_first_by_auth_conditions(tainted_conditions, opts = {})
      email = tainted_conditions.delete(:email)
      if email && email.is_a?(String)
        conditions = devise_parameter_filter.filter(tainted_conditions).merge(opts).
                     reverse_merge(emails: { email: email })

        joins(:emails).where { users.id != User::SYSTEM_USER_ID }.find_by(conditions)
      else
        super(tainted_conditions, opts)
      end
    end
  end
end


text:
"""
def generate_function(arrow_array):
    arrow_dict={}
    rows=len(arrow_array)
    columns=len(arrow_array[0])
    for i in range(rows):
        for j in range(columns):
            if arrow_array[i][j]=='<':
                incr=(0,-1)
            elif arrow_array[i][j]=='>':
                incr=(0,1)
            elif arrow_array[i][j]=='v':
                incr=(1,0)
            elif arrow_array[i][j]=='^':
                incr=(-1,0)
            arrow_dict[(i,j)]=((i+incr[0])%rows,(j+incr[1])%columns)
    return arrow_dict
"""

def parse_file(filename):
    arrow_array=[]
    for line in open(filename):
        arrow_array.append([])
        for char in line.strip():
            arrow_array[-1].append(char)
    return arrow_array

def get_next(position, arrow_array):
    rows=len(arrow_array)
    columns=len(arrow_array[0])
    i,j=position
    if arrow_array[i][j]=='<':
        incr=(0,-1)
    elif arrow_array[i][j]=='>':
        incr=(0,1)
    elif arrow_array[i][j]=='v':
        incr=(1,0)
    elif arrow_array[i][j]=='^':
        incr=(-1,0)
    return ((i+incr[0])%rows,(j+incr[1])%columns)

def get_longest_cycle(arrow_array):
    rows=len(arrow_array)
    columns=len(arrow_array[0])
    max_cycle_length=0
    start=(0, 0)
    path=[]
    auxillary_array=[[None for j in range(columns)] for i in range(rows)]
    for i in range(rows):
        for j in range(columns):
            if auxillary_array[i][j] is None:
                path_taken={}
                current=(i,j)
                path_length=1
                while not current in path_taken:
                    path_taken[current]=path_length
                    current=get_next(current, arrow_array)
                    path_length+=1
                cycle_length=path_length-path_taken[current]
                for position in path_taken:
                    if path_taken[position]>=path_taken[current]:
                        auxillary_array[position[0]][position[1]]=cycle_length
                    else:
                        auxillary_array[position[0]][position[1]]=-1
                if cycle_length>max_cycle_length:
                    max_cycle_length=cycle_length
                    start=current
    #path.append(start)
    #start=get_next(start, arrow_array)
    #while start!=path[0]:
    #    path.append(start)
    #    start=get_next(start, arrow_array)
    return max_cycle_length,start


text:
module MissCleo
  module TestSelector
    module_function

    def predict(coverage_map, lines_changed)
      tests_to_run = []
      lines_changed.each do |file, line|
        tests_to_run |= coverage_map.tests_for_lines(file, line)
      end

      tests_to_run.sort.reverse
    end
  end
end


text:
<?php

namespace Irazasyed\Telegram\Objects;

class Sticker extends BaseObject
{
    /**
     * @inheritdoc
     */
    public function relations()
    {
        return [
            'thumb' => PhotoSize::class,
        ];
    }
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Card Pure CSS</title>
  <link rel="stylesheet" href="style.css">

Card Pure CSS

Card Titulo

              <input type="checkbox" id="click-card"/>

                  Lorem ipsum dolor sit amet, consectetur adipisicing elit.


text:
$(function(){
	$('.sensorSuggessions').on("click",function() {

		var email = localStorage.getItem("email");
		var roomno = localStorage.getItem("roomno");
		$("#roomno").empty().append(roomno);
		//$("#roomno").append(roomno);
		if(roomno == null){
			alert("please select your device location...");
		}else {
			$.get("/ecoAPI/dev/api/ecomappersapi.php?roomno="+roomno+"&email="+email+"&method=showSuggessions&format=json ")
			.done(function (response){
				$.each(response.showSuggessionsResponse, function(i,suggessions){
					var nameOfSensor = suggessions.sensor_name;
					var suggession1 = suggessions.sug1_sensitive_groups;
					var suggession2 = suggessions.sug2_health_effects;
					var suggession3 = suggessions.sug3_cautionary;

					$("#SenitiveGroup"+nameOfSensor).empty();
					$("#HeathEffect"+nameOfSensor).empty();
					$("#Cautionary"+nameOfSensor).empty();

					$("#SenitiveGroup"+nameOfSensor).append(suggession1);
					$("#HeathEffect"+nameOfSensor).append(suggession2);
					$("#Cautionary"+nameOfSensor).append(suggession3);

					/*if(suggession2=="N/A"){
						$("#HeathEffect"+nameOfSensor).hide();
						$(".healthEffects").hide();
					}
					if(suggession3=="N/A"){
						$("#Cautionary"+nameOfSensor).hide();
						$(".cautionarys").hide();
					}else {
						$(".healthEffects").show();
						$(".cautionarys").show();
						$("#Cautionary"+nameOfSensor).show();
						$("#HeathEffect"+nameOfSensor).show();

					}*/
				});

			});
		}
	});
});


text:
package org.apache.ignite.internal.processors.cache.index;

import java.util.ArrayList;
import java.util.List;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteException;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.cluster.ClusterState;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.configuration.NearCacheConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.util.typedef.G;
import org.apache.ignite.testframework.GridTestUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;

/**
 * Tests basic functionality of enabling indexing.
 */
@RunWith(Parameterized.class)
public class DynamicEnableIndexingBasicSelfTest extends DynamicEnableIndexingAbstractTest {
    /** Test parameters. */
    @Parameters(name = "hasNear={0},nodeIdx={1},cacheMode={2},atomicityMode={3}")
    public static Iterable<Object[]> params() {
        int[] opNodes = new int[] {IDX_CLI, IDX_SRV_CRD, IDX_SRV_NON_CRD, IDX_SRV_FILTERED};

        CacheMode[] cacheModes = new CacheMode[] {CacheMode.PARTITIONED, CacheMode.REPLICATED};

        CacheAtomicityMode[] atomicityModes = new CacheAtomicityMode[] {
            CacheAtomicityMode.ATOMIC,
            CacheAtomicityMode.TRANSACTIONAL,
            CacheAtomicityMode.TRANSACTIONAL_SNAPSHOT
        };

        List<Object[]> res = new ArrayList<>();

        for (int node : opNodes) {
            for (CacheMode cacheMode : cacheModes) {
                for (CacheAtomicityMode atomicityMode : atomicityModes) {
                    res.add(new Object[] {true, node, cacheMode, atomicityMode});

                    // For TRANSACTIONAL_SNAPSHOT near caches is forbidden.
                    if (atomicityMode != CacheAtomicityMode.TRANSACTIONAL_SNAPSHOT)
                        res.add(new Object[] {false, node, cacheMode, atomicityMode});

                }
            }
        }

        return res;
    }

    /** */
    @Parameter(0)
    public Boolean hasNear;

    /** */
    @Parameter(1)
    public int nodeIdx;

    /** */
    @Parameter(2)
    public CacheMode cacheMode;

    /** */
    @Parameter(3)
    public CacheAtomicityMode atomicityMode;

    /** {@inheritDoc} */
    @Override protected void beforeTestsStarted() throws Exception {
        super.beforeTestsStarted();

        for (IgniteConfiguration cfg : configurations())
            startGrid(cfg);

        node().cluster().state(ClusterState.ACTIVE);
    }

    /** {@inheritDoc} */
    @Override protected void beforeTest() throws Exception {
        super.beforeTest();

        CacheConfiguration<?, ?> ccfg = testCacheConfiguration(POI_CACHE_NAME, cacheMode, atomicityMode);

        if (hasNear && atomicityMode != CacheAtomicityMode.TRANSACTIONAL_SNAPSHOT)
            ccfg.setNearConfiguration(new NearCacheConfiguration<>());

        node().getOrCreateCache(ccfg);

        awaitCacheOnClient(grid(IDX_CLI_NEAR_ONLY), POI_CACHE_NAME);

        if (atomicityMode != CacheAtomicityMode.TRANSACTIONAL_SNAPSHOT)
            grid(IDX_CLI_NEAR_ONLY).getOrCreateNearCache(POI_CACHE_NAME, new NearCacheConfiguration<>());
    }

    /** {@inheritDoc} */
    @Override protected void afterTest() throws Exception {
        node().destroyCache(POI_CACHE_NAME);

        super.afterTest();
    }

    /** */
    @Test
    public void testEnableDynamicIndexing() throws Exception {
        loadData(node(), 0, NUM_ENTRIES / 2);

        createTable();

        grid(IDX_SRV_CRD).cache(POI_CACHE_NAME).indexReadyFuture().get();

        loadData(node(), NUM_ENTRIES / 2, NUM_ENTRIES);

        for (Ignite ig : G.allGrids()) {
            assertEquals(NUM_ENTRIES, query(ig, SELECT_ALL_QUERY).size());

            performQueryingIntegrityCheck(ig);

            checkQueryParallelism((IgniteEx)ig, cacheMode);
        }
    }

    /** */
    @SuppressWarnings("ThrowableNotThrown")
    private void createTable() {
        if (cacheMode == CacheMode.REPLICATED) {
            GridTestUtils.assertThrows(log, () -> createTable(node().cache(POI_CACHE_NAME), QUERY_PARALLELISM),
                IgniteException.class, "Segmented indices are supported for PARTITIONED mode only.");

            createTable(node().cache(POI_CACHE_NAME), 1);
        }
        else
            createTable(node().cache(POI_CACHE_NAME), QUERY_PARALLELISM);
    }

    /** */
    private IgniteEx node() {
        return grid(nodeIdx);
    }
}


text:
#ifndef JOYSTICK_EVENT_LISTENER_H
#define JOYSTICK_EVENT_LISTENER_H

class JoyStickEvent;

class JoyStickEventListener
{
public:
    virtual bool onJoyStickEvent(const JoyStickEvent& event) = 0;
};

#endif


text:
namespace stan {

STAN_ADD_REQUIRE_BINARY(same, std::is_same, require_std);
STAN_ADD_REQUIRE_BINARY_INNER(same, std::is_same, require_std);

STAN_ADD_REQUIRE_BINARY(convertible, std::is_convertible, require_std);
STAN_ADD_REQUIRE_BINARY_INNER(convertible, std::is_convertible, require_std);
STAN_ADD_REQUIRE_BINARY(assignable, std::is_assignable, require_std);
STAN_ADD_REQUIRE_BINARY_INNER(assignable, std::is_assignable, require_std);

STAN_ADD_REQUIRE_BINARY(constructible, std::is_constructible, require_std);
STAN_ADD_REQUIRE_BINARY_INNER(constructible, std::is_constructible,
                              require_std);

STAN_ADD_REQUIRE_UNARY(arithmetic, std::is_arithmetic,
                       require_stan_scalar_real);
STAN_ADD_REQUIRE_UNARY_INNER(arithmetic, std::is_arithmetic,
                             require_stan_scalar_real);
STAN_ADD_REQUIRE_UNARY(floating_point, std::is_floating_point,
                       require_stan_scalar_real);
STAN_ADD_REQUIRE_UNARY_INNER(floating_point, std::is_floating_point,
                             require_stan_scalar_real);
STAN_ADD_REQUIRE_UNARY(integral, std::is_integral, require_stan_scalar_real);
STAN_ADD_REQUIRE_UNARY_INNER(integral, std::is_integral,
                             require_stan_scalar_real);

}  // namespace stan
#endif


text:
package net.frog.vo.diners.photo;

public class DinersPhotopathVO {
public DinersPhotopathVO (){

	}
	protected int no;
	protected int diners_photo_no;
	protected String stored_file_path;
	public int getNo() {
		return no;
	}
	public void setNo(int no) {
		this.no = no;
	}
	public int getDiners_photo_no() {
		return diners_photo_no;
	}
	public void setDiners_photo_no(int diners_photo_no) {
		this.diners_photo_no = diners_photo_no;
	}
	public String getStored_file_path() {
		return stored_file_path;
	}
	public void setStored_file_path(String stored_file_path) {
		this.stored_file_path = stored_file_path;
	}

}


text:
import logging

from sqlalchemy.orm.exc import NoResultFound
import bleach

from aetherguild.listener_service.tables import NewsItem
from aetherguild.listener_service.user_session import LEVEL_ADMIN
from .basehandler import BaseHandler, validate_message_schema, has_level, ErrorList
from aetherguild.listener_service.schemas.news import *
from .utils import validate_str_length

log = logging.getLogger(__name__)

class NewsHandler(BaseHandler):
    @has_level(LEVEL_ADMIN)
    @validate_message_schema(get_news_posts)
    def get_news_posts(self, track_route, message):
        start = message['data'].get('start')
        count = message['data'].get('count')

        # Form the query
        query = self.db.query(NewsItem).filter(NewsItem.deleted == False)
        news_count = query.count()
        query = query.order_by(NewsItem.id.desc())
        if start:
            query = query.offset(start)
        if count:
            query = query.limit(count)

        # Serialize objects
        out_list = []
        for post in query:
            out_list.append(post.serialize())

        # Dump out the object list
        self.send_message({
            'news_count': news_count,
            'posts': out_list
        })

    @has_level(LEVEL_ADMIN)
    @validate_message_schema(get_news_post)
    def get_news_post(self, track_route, message):
        post_id = message['data']['post']

        # Find the news post, error out if not found
        try:
            post = NewsItem.get_one(self.db, id=post_id, deleted=False)
        except NoResultFound:
            self.send_error(404, u"News item not found")
            return

        # Serialize and send the news post
        self.send_message({
            'post': post.serialize()
        })

    @has_level(LEVEL_ADMIN)
    @validate_message_schema(insert_news_posts_request)
    def insert_news_post(self, track_route, message):
        msg = bleach.clean(message['data']['message'])
        header = bleach.clean(message['data']['header'])
        err_list = ErrorList()

        # Make sure the message and header has at least some content
        validate_str_length('message', msg, err_list, 1)
        validate_str_length('header', header, err_list, 1, 32)

        # Send errors if any
        if err_list.get_list():
            self.send_error(450, err_list)
            return

        # Create the new post
        post = NewsItem()
        post.nickname = self.session.user.nickname
        post.message = msg
        post.header = header
        self.db.add(post)
        self.db.flush()

        # Send the new post as a response
        self.send_message({
            'post': post.serialize()
        })

    @has_level(LEVEL_ADMIN)
    @validate_message_schema(delete_news_post_request)
    def delete_news_post(self, track_route, message):
        post_id = message['data']['post']

        # Make sure the user exists and get the reference
        try:
            post = NewsItem.get_one(self.db, id=post_id, deleted=False)
        except NoResultFound:
            self.send_error(404, u"News item not found")
            return

        # Set deleted flag
        post.deleted = True
        self.db.add(post)

        # Just send an empty notification
        self.send_message({})

    @has_level(LEVEL_ADMIN)
    @validate_message_schema(update_news_post_request)
    def update_news_post(self, track_route, message):
        post_id = message['data']['post']
        msg = bleach.clean(message['data']['message'])
        header = bleach.clean(message['data']['header'])
        err_list = ErrorList()

        # Make sure the message and header has at least some content
        validate_str_length('message', msg, err_list, 1)
        validate_str_length('header', header, err_list, 1, 64)

        # Send errors if any
        if err_list.get_list():
            self.send_error(450, err_list)
            return

        # Find the news post, error out if not found
        try:
            post = NewsItem.get_one(self.db, id=post_id, deleted=False)
        except NoResultFound:
            self.send_error(404, u"News item not found")
            return

        # Update content
        post.message = msg
        post.header = header
        self.db.add(post)

        # Serialize and send the news post
        self.send_message({
            'post': post.serialize()
        })

    def get_routes(self):
        return {
            'get_news_posts': self.get_news_posts,
            'get_news_post': self.get_news_post,
            'insert_news_post': self.insert_news_post,
            'delete_news_post': self.delete_news_post,
            'update_news_post': self.update_news_post,
        }


text:
"""Tests of manual clustering GUI."""

#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------

from pytest import mark
import numpy as np
from numpy.testing import assert_allclose as ac
from numpy.testing import assert_array_equal as ae

from ..gui import ClusterManualGUI
from ....utils.settings import _load_default_settings
from ....utils.logging import set_level
from ....utils.array import _spikes_in_clusters
from ....io.mock import MockModel
from ....io.kwik.store_items import create_store

# Skip these tests in "make test-quick".
pytestmark = mark.long()

#------------------------------------------------------------------------------
# Kwik tests
#------------------------------------------------------------------------------

def setup():
    set_level('debug')

def _start_manual_clustering(config='none', shortcuts=None):
    if config is 'none':
        config = []
    model = MockModel()
    spc = model.spikes_per_cluster
    store = create_store(model, spikes_per_cluster=spc)
    gui = ClusterManualGUI(model=model, store=store,
                           config=config, shortcuts=shortcuts)
    return gui

def test_gui_clustering(qtbot):

    gui = _start_manual_clustering()
    gui.show()
    qtbot.addWidget(gui.main_window)

    cs = gui.store
    spike_clusters = gui.model.spike_clusters.copy()

    f = gui.model.features
    m = gui.model.masks

    def _check_arrays(cluster, clusters_for_sc=None, spikes=None):
        """Check the features and masks in the cluster store
        of a given custer."""
        if spikes is None:
            if clusters_for_sc is None:
                clusters_for_sc = [cluster]
            spikes = _spikes_in_clusters(spike_clusters, clusters_for_sc)
        shape = (len(spikes),
                 len(gui.model.channel_order),
                 gui.model.n_features_per_channel)
        ac(cs.features(cluster), f[spikes, :].reshape(shape))
        ac(cs.masks(cluster), m[spikes])

    _check_arrays(0)
    _check_arrays(2)

    # Merge two clusters.
    clusters = [0, 2]
    up = gui.merge(clusters)
    new = up.added[0]
    _check_arrays(new, clusters)

    # Split some spikes.
    spikes = [2, 3, 5, 7, 11, 13]
    # clusters = np.unique(spike_clusters[spikes])
    up = gui.split(spikes)
    _check_arrays(new + 1, spikes=spikes)

    # Undo.
    gui.undo()
    _check_arrays(new, clusters)

    # Undo.
    gui.undo()
    _check_arrays(0)
    _check_arrays(2)

    # Redo.
    gui.redo()
    _check_arrays(new, clusters)

    # Split some spikes.
    spikes = [5, 7, 11, 13, 17, 19]
    # clusters = np.unique(spike_clusters[spikes])
    gui.split(spikes)
    _check_arrays(new + 1, spikes=spikes)

    # Test merge-undo-different-merge combo.
    spc = gui.clustering.spikes_per_cluster.copy()
    clusters = gui.cluster_ids[:3]
    up = gui.merge(clusters)
    _check_arrays(up.added[0], spikes=up.spike_ids)
    # Undo.
    gui.undo()
    for cluster in clusters:
        _check_arrays(cluster, spikes=spc[cluster])
    # Another merge.
    clusters = gui.cluster_ids[1:5]
    up = gui.merge(clusters)
    _check_arrays(up.added[0], spikes=up.spike_ids)

    # Move a cluster to a group.
    cluster = gui.cluster_ids[0]
    gui.move([cluster], 2)
    assert len(gui.store.mean_probe_position(cluster)) == 2

    spike_clusters_new = gui.model.spike_clusters.copy()
    # Check that the spike clusters have changed.
    assert not np.all(spike_clusters_new == spike_clusters)
    ac(gui.model.spike_clusters, gui.clustering.spike_clusters)

    gui.close()

def test_gui_wizard(qtbot):
    gui = _start_manual_clustering()
    n = gui.n_clusters
    qtbot.addWidget(gui.main_window)
    gui.show()

    clusters = np.arange(gui.n_clusters)
    best_clusters = gui.wizard.best_clusters()

    # assert gui.wizard.best_clusters(1)[0] == best_clusters[0]
    ae(np.unique(best_clusters), clusters)
    assert len(gui.wizard.most_similar_clusters()) == n - 1

    assert len(gui.wizard.most_similar_clusters(0, n_max=3)) == 3

    clusters = gui.cluster_ids[:2]
    up = gui.merge(clusters)
    new = up.added[0]
    assert np.all(np.in1d(gui.wizard.best_clusters(),
                  np.arange(clusters[-1] + 1, new + 1)))
    assert np.all(np.in1d(gui.wizard.most_similar_clusters(new),
                  np.arange(clusters[-1] + 1, new)))

    gui.close()

@mark.long
def test_gui_history(qtbot):

    gui = _start_manual_clustering()
    qtbot.addWidget(gui.main_window)
    gui.show()

    gui.wizard.start()

    spikes = _spikes_in_clusters(gui.model.spike_clusters,
                                 gui.wizard.selection)
    gui.split(spikes[::3])
    gui.undo()
    gui.wizard.next()
    gui.redo()
    gui.undo()

    for _ in range(10):
        gui.merge(gui.wizard.selection)
        gui.wizard.next()
        gui.undo()
        gui.wizard.next()
        gui.redo()
        gui.wizard.next()

        spikes = _spikes_in_clusters(gui.model.spike_clusters,
                                     gui.wizard.selection)
        if len(spikes):
            gui.split(spikes[::10])
            gui.wizard.next()
            gui.undo()
        gui.merge(gui.wizard.selection)
        gui.wizard.next()
        gui.wizard.next()

        gui.wizard.next_best()
        ae(gui.model.spike_clusters, gui.clustering.spike_clusters)

    gui.close()

@mark.long
def test_gui_gui(qtbot):
    settings = _load_default_settings()
    config = settings['cluster_manual_config']
    shortcuts = settings['cluster_manual_shortcuts']

    gui = _start_manual_clustering(config=config,
                                   shortcuts=shortcuts,
                                   )
    qtbot.addWidget(gui.main_window)
    gui.show()
    gui.close()


text:
<?php
/**
 * Description of VerifType
 *
 * @author Anthony
 */
namespace Lam\MdlBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Lam\MdlBundle\Entity\Organisme;

class VerifType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options){
        $builder

     ->add('nom_organisme', 'entity', array(
    'class' => 'LamMdlBundle:Organisme'))
     ->add('mdpOrganisme','password',array('label'=>"mdp :"));

    }

    public function getName(){
        return 'Lam_MdlBundle_VerifType';
    }
}

?>


text:
AliAnalysisTaskStrangenessLifetimes *AddTaskStrangenessLifetimes(bool isMC = false,bool V0s=false,
    TString tskname = "LifetimesFiltering", TString suffix = "std") {
  // Get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskStrangenessLifetimes", "No analysis manager found.");
    return 0x0;
  }

  // Check the analysis type using the event handlers connected to the analysis
  // manager.
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskStrangenessLifetimes",
            "This task requires an input event handler");
    return 0x0;
  }

  tskname.Append(suffix.Data());
  AliAnalysisTaskStrangenessLifetimes *task =
      new AliAnalysisTaskStrangenessLifetimes(isMC, tskname.Data(),1,true,V0s);

  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(
      Form("%s_summary", tskname.Data()), TList::Class(),
      AliAnalysisManager::kOutputContainer, "AnalysisResults.root");

  AliAnalysisDataContainer *coutput2 =
      mgr->CreateContainer(Form("V0tree%s", suffix.Data()), TTree::Class(),
                           AliAnalysisManager::kOutputContainer, Form("V0tree.root:%s",suffix.Data()));
  coutput2->SetSpecialOutput();

  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 1, coutput1);
  mgr->ConnectOutput(task, 2, coutput2);
  return task;
}


text:
package org.gluu.oxauth.ping;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PPMRequestBroker {

    private static Logger logger = LoggerFactory.getLogger(RequestToken.class);

    private int expiration;
    private String nonce;
    private byte secretKey[];
    private RequestToken rt;
    private JSONObject b;

    public PPMRequestBroker(String orgAlias, String token, String sender,
            String returnUrl, String idpAccountId, byte secretKey[], int expiration) {

        nonce = UUID.randomUUID().toString();
        this.secretKey = secretKey;
        this.expiration = expiration;

        b = new JSONObject();
        b.put("idpAccountId", idpAccountId);
        b.put("iss", sender);
        b.put("aud", "pingidauthenticator");
        b.put("returnUrl", returnUrl);
        b.put("nonce", nonce);
        //b.put("confVersion", 1);

        rt = new RequestToken(false, orgAlias, token);

    }

    public String getNonce() {
        return nonce;
    }

    public void populate(String username, JSONObject... attributes) {

        b.put("sub", username);
        if (attributes != null) {

            List<JSONObject> attrs = Arrays.asList(attributes);
            if (attrs.size() > 0) {
                b.put("attributes", attrs);
            }
        }

    }

    public String getSignedRequest() throws TokenProcessingException {
        long now = System.currentTimeMillis();
        b.put("iat", now);
        b.put("exp", now + expiration * 1000);

        rt.setPayload(b);
        return rt.getSignedToken(secretKey);

    }

}


text:
package com.amazonaws.services.simpleemail.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *

 * Contains the topic ARN associated with an Amazon Simple Notification Service (Amazon SNS) event destination.
 *

 *

 * Event destinations, such as Amazon SNS, are associated with configuration sets, which enable you to publish email
 * sending events. For information about using configuration sets, see the Amazon SES Developer
 * Guide.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SNSDestination implements Serializable, Cloneable {

    /**
     *

     * The ARN of the Amazon SNS topic that email sending events will be published to. An example of an Amazon SNS topic
     * ARN is arn:aws:sns:us-west-2:123456789012:MyTopic. For more information about Amazon SNS topics, see
     * the Amazon SNS Developer Guide.
     *

     */
    private String topicARN;

    /**
     *

     * The ARN of the Amazon SNS topic that email sending events will be published to. An example of an Amazon SNS topic
     * ARN is arn:aws:sns:us-west-2:123456789012:MyTopic. For more information about Amazon SNS topics, see
     * the Amazon SNS Developer Guide.
     *

     *
     * @param topicARN
     *        The ARN of the Amazon SNS topic that email sending events will be published to. An example of an Amazon
     *        SNS topic ARN is arn:aws:sns:us-west-2:123456789012:MyTopic. For more information about
     *        Amazon SNS topics, see the Amazon SNS
     *        Developer Guide.
     */

    public void setTopicARN(String topicARN) {
        this.topicARN = topicARN;
    }

    /**
     *

     * The ARN of the Amazon SNS topic that email sending events will be published to. An example of an Amazon SNS topic
     * ARN is arn:aws:sns:us-west-2:123456789012:MyTopic. For more information about Amazon SNS topics, see
     * the Amazon SNS Developer Guide.
     *

     *
     * @return The ARN of the Amazon SNS topic that email sending events will be published to. An example of an Amazon
     *         SNS topic ARN is arn:aws:sns:us-west-2:123456789012:MyTopic. For more information about
     *         Amazon SNS topics, see the Amazon
     *         SNS Developer Guide.
     */

    public String getTopicARN() {
        return this.topicARN;
    }

    /**
     *

     * The ARN of the Amazon SNS topic that email sending events will be published to. An example of an Amazon SNS topic
     * ARN is arn:aws:sns:us-west-2:123456789012:MyTopic. For more information about Amazon SNS topics, see
     * the Amazon SNS Developer Guide.
     *

     *
     * @param topicARN
     *        The ARN of the Amazon SNS topic that email sending events will be published to. An example of an Amazon
     *        SNS topic ARN is arn:aws:sns:us-west-2:123456789012:MyTopic. For more information about
     *        Amazon SNS topics, see the Amazon SNS
     *        Developer Guide.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SNSDestination withTopicARN(String topicARN) {
        setTopicARN(topicARN);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getTopicARN() != null)
            sb.append("TopicARN: ").append(getTopicARN());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof SNSDestination == false)
            return false;
        SNSDestination other = (SNSDestination) obj;
        if (other.getTopicARN() == null ^ this.getTopicARN() == null)
            return false;
        if (other.getTopicARN() != null && other.getTopicARN().equals(this.getTopicARN()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getTopicARN() == null) ? 0 : getTopicARN().hashCode());
        return hashCode;
    }

    @Override
    public SNSDestination clone() {
        try {
            return (SNSDestination) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
//
//  ZKRFunCategoryController.m
//  Zaker-C
//
//  Created by GuangliChan on 16/2/26.
//  Copyright © 2016年 GLChen. All rights reserved.
//

#import "ZKRFunCategoryController.h"
#import "ZKRCategoryButton.h"
#import "AFHTTPSessionManager.h"
#import "ZKRFunCategoryItem.h"
#import "MJExtension.h"
#import "ZKRFunLocationController.h"

@interface ZKRFunCategoryController ()

@property (weak, nonatomic) IBOutlet ZKRCategoryButton *firCateButton;
@property (weak, nonatomic) IBOutlet ZKRCategoryButton *secCateButton;
@property (weak, nonatomic) IBOutlet ZKRCategoryButton *thrCateButton;
@property (weak, nonatomic) IBOutlet ZKRCategoryButton *fourCateButton;
@property (weak, nonatomic) IBOutlet ZKRCategoryButton *fifCateButton;
@property (weak, nonatomic) IBOutlet ZKRCategoryButton *sixCateButton;

@property (weak, nonatomic) IBOutlet UIButton *locationButton;

@property (nonatomic, strong) NSMutableArray *buttons;

@property (nonatomic, strong) AFHTTPSessionManager *manager;
@property (nonatomic, strong) NSArray *itemsArray;
@end

@implementation ZKRFunCategoryController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.title = @"分类";

    [self loadData];

    [self.buttons enumerateObjectsUsingBlock:^(ZKRCategoryButton *button, NSUInteger idx, BOOL * _Nonnull stop) {
        [button addTarget:self action:@selector(categorySelected:) forControlEvents:UIControlEventTouchUpInside];
    }];
}
/**
 *  http://wl.myzaker.com/?_appid=iphone&_v=6.4.7&_version=6.46&c=category_list&city=%E5%B9%BF%E5%B7%9E
 */

- (void)loadData
{
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"funCategory" ofType:@"plist"];
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];

    /** 通过字典数组来创建一个模型数组 */
    self.itemsArray = [ZKRFunCategoryItem mj_objectArrayWithKeyValuesArray:data[@"data"][@"list"]];

    [self.itemsArray enumerateObjectsUsingBlock:^(ZKRFunCategoryItem  *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        ZKRCategoryButton *button = self.buttons[idx];
        button.item = obj;
        self.buttons[idx] = button;
//        NSLog(@"%@ %zd", obj.icon, idx);
    }];

}

- (void)categorySelected:(ZKRCategoryButton *)button
{
    ZKRFunCategoryItem *item = button.item;
    NSLog(@"%@", item.category);
}

- (IBAction)locationButtonClick:(UIButton *)sender {
    ZKRFunLocationController *vc = [[ZKRFunLocationController alloc] init];
    vc.navigationItem.title = @"选择你所在的城市";
    [self.navigationController pushViewController:vc animated:YES];

}

- (NSMutableArray *)buttons
{
    if (!_buttons) {
        NSArray *array = @[self.firCateButton,
                     self.secCateButton,
                     self.thrCateButton,
                     self.fourCateButton,
                     self.fifCateButton,
                     self.sixCateButton];
        _buttons = [NSMutableArray arrayWithCapacity:array.count];
        [_buttons addObjectsFromArray:array];
    }
    return _buttons;
}

@end


text:
*   Challenges of AEM Configuration
*   CONGA Sling Plugin
*   CONGA AEM Plugin
*   CONGA AEM Definitions
*   Bringing it together

### Training Material

Presentation: [DATM-58_AEM-Configuration-with-CONGA.pdf](slides/DATM-58_AEM-Configuration-with-CONGA.pdf)

Exercises: [DATM-59 CONGA exercises](DATM-59-CONGA-exercises.html)

### Further links

*   [CONGA Sling Plugin](https://devops.wcm.io/conga/plugins/sling/)
*   [CONGA AEM Plugin](https://devops.wcm.io/conga/plugins/aem/)
*   [CONGA AEM Definitions](https://devops.wcm.io/conga/definitions/aem/)


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**partition** | **int** | Partition indicates the ordinal at which the StatefulSet should be partitioned. Default value is 0. | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>integration-tests</artifactId>
    <name>Simulator Integration tests</name>
    <packaging>pom</packaging>

    <parent>
        <groupId>com.hazelcast.simulator</groupId>
        <artifactId>simulator-root</artifactId>
        <version>2.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <prerequisites>
        <maven>${maven.version}</maven>
    </prerequisites>

    <properties>
        <main.basedir>${project.parent.basedir}</main.basedir>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.hazelcast.simulator</groupId>
            <artifactId>simulator</artifactId>
            <version>${project.parent.version}</version>
        </dependency>
        <dependency>
            <groupId>com.hazelcast.simulator</groupId>
            <artifactId>driver-hazelcast4plus</artifactId>
            <version>${project.parent.version}</version>
        </dependency>

        <dependency>
            <groupId>com.hazelcast.simulator</groupId>
            <artifactId>simulator</artifactId>
            <version>${project.parent.version}</version>
            <scope>test</scope>
            <classifier>tests</classifier>
        </dependency>
    </dependencies>

</project>


text:
(function() {
  function shadowSelector(v) {
    return 'html /deep/ ' + selector(v);
  }
  function selector(v) {
    return '[touch-action="' + v + '"]';
  }
  function rule(v) {
    return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + ';}';
  }
  var attrib2css = [
    'none',
    'auto',
    'pan-x',
    'pan-y',
    {
      rule: 'pan-x pan-y',
      selectors: [
        'pan-x pan-y',
        'pan-y pan-x'
      ]
    },
    'manipulation'
  ];
  var styles = '';
  // only install stylesheet if the browser has touch action support
  var hasTouchAction = typeof document.head.style.touchAction === 'string';
  // only add shadow selectors if shadowdom is supported
  var hasShadowRoot = !window.ShadowDOMPolyfill && document.head.createShadowRoot;

  if (hasTouchAction) {
    attrib2css.forEach(function(r) {
      if (String(r) === r) {
        styles += selector(r) + rule(r) + '\n';
        if (hasShadowRoot) {
          styles += shadowSelector(r) + rule(r) + '\n';
        }
      } else {
        styles += r.selectors.map(selector) + rule(r.rule) + '\n';
        if (hasShadowRoot) {
          styles += r.selectors.map(shadowSelector) + rule(r.rule) + '\n';
        }
      }
    });

    var el = document.createElement('style');
    el.textContent = styles;
    document.head.appendChild(el);
  }
})();