text:
/*
 * @author Valentin Simonov / http://va.lent.in/
 */

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using TouchScript.Devices.Display;
using TouchScript.Hit;
using TouchScript.InputSources;
using TouchScript.Layers;
using TouchScript.Utils;
using UnityEngine;

namespace TouchScript
{
    /// <summary>
    /// Default implementation of <see cref="ITouchManager"/>.
    /// </summary>
    internal sealed class TouchManagerInstance : MonoBehaviour, ITouchManager
    {
        #region Events

        /// <inheritdoc />
        public event EventHandler FrameStarted
        {
            add { frameStartedInvoker += value; }
            remove { frameStartedInvoker -= value; }
        }

        /// <inheritdoc />
        public event EventHandler FrameFinished
        {
            add { frameFinishedInvoker += value; }
            remove { frameFinishedInvoker -= value; }
        }

        /// <inheritdoc />
        public event EventHandler<TouchEventArgs> TouchesBegan
        {
            add { touchesBeganInvoker += value; }
            remove { touchesBeganInvoker -= value; }
        }

        /// <inheritdoc />
        public event EventHandler<TouchEventArgs> TouchesMoved
        {
            add { touchesMovedInvoker += value; }
            remove { touchesMovedInvoker -= value; }
        }

        /// <inheritdoc />
        public event EventHandler<TouchEventArgs> TouchesEnded
        {
            add { touchesEndedInvoker += value; }
            remove { touchesEndedInvoker -= value; }
        }

        /// <inheritdoc />
        public event EventHandler<TouchEventArgs> TouchesCancelled
        {
            add { touchesCancelledInvoker += value; }
            remove { touchesCancelledInvoker -= value; }
        }

        // iOS Events AOT hack
        private EventHandler<TouchEventArgs> touchesBeganInvoker, touchesMovedInvoker,
            touchesEndedInvoker, touchesCancelledInvoker;

        private EventHandler frameStartedInvoker, frameFinishedInvoker;

        #endregion

        #region Public properties

        public static TouchManagerInstance Instance
        {
            get
            {
                if (shuttingDown) return null;
                if (instance == null)
                {
                    if (!Application.isPlaying) return null;
                    var objects = FindObjectsOfType<TouchManagerInstance>();
                    if (objects.Length == 0)
                    {
                        var go = new GameObject("TouchManager Instance");
                        instance = go.AddComponent<TouchManagerInstance>();
                    }
                    else if (objects.Length >= 1)
                    {
                        instance = objects[0];
                    }
                }
                return instance;
            }
        }

        /// <inheritdoc />
        public IDisplayDevice DisplayDevice
        {
            get
            {
                if (displayDevice == null)
                {
                    displayDevice = ScriptableObject.CreateInstance<GenericDisplayDevice>();
                }
                return displayDevice;
            }
            set
            {
                if (value == null)
                {
                    displayDevice = ScriptableObject.CreateInstance<GenericDisplayDevice>();
                }
                else
                {
                    displayDevice = value;
                }
                updateDPI();
            }
        }

        /// <inheritdoc />
        public float DPI
        {
            get { return dpi; }
        }

        /// <inheritdoc />
        public bool ShouldCreateCameraLayer
        {
            get { return shouldCreateCameraLayer; }
            set { shouldCreateCameraLayer = value; }
        }

        /// <inheritdoc />
        public IList<TouchLayer> Layers
        {
            get { return new ReadOnlyCollection<TouchLayer>(layers); }
        }

        /// <inheritdoc />
        public float DotsPerCentimeter
        {
            get { return dotsPerCentimeter; }
        }

        /// <inheritdoc />
        public int NumberOfTouches
        {
            get { return touches.Count; }
        }

        /// <inheritdoc />
        public IList<ITouch> ActiveTouches
        {
            get { return touches.Cast<ITouch>().ToList(); }
        }

        #endregion

        #region Private variables

        private static bool shuttingDown = false;
        private static TouchManagerInstance instance;
        private Boolean shouldCreateCameraLayer = true;

        private IDisplayDevice displayDevice;
        private float dpi = 96;
        private float dotsPerCentimeter = TouchManager.CM_TO_INCH * 96;

        private List<TouchLayer> layers = new List<TouchLayer>(10);
        private List<TouchPoint> touches = new List<TouchPoint>(30);
        private Dictionary<int, TouchPoint> idToTouch = new Dictionary<int, TouchPoint>(30);

        // Upcoming changes
        private List<TouchPoint> touchesBegan = new List<TouchPoint>(30);
        private HashSet<int> touchesUpdated = new HashSet<int>();
        private HashSet<int> touchesEnded = new HashSet<int>();
        private HashSet<int> touchesCancelled = new HashSet<int>();

        private int nextTouchId = 0;

        #endregion

        #region Public methods

        /// <inheritdoc />
        public bool AddLayer(TouchLayer layer)
        {
            if (layer == null) return false;
            if (layers.Contains(layer)) return true;
            layers.Add(layer);
            return true;
        }

        /// <inheritdoc />
        public bool AddLayer(TouchLayer layer, int index)
        {
            if (layer == null) return false;
            if (index >= layers.Count) return AddLayer(layer);
            var i = layers.IndexOf(layer);
            if (i == -1)
            {
                layers.Insert(index, layer);
            }
            else
            {
                if (index == i || i == index - 1) return true;
                layers.RemoveAt(i);
                if (index < i) layers.Insert(index, layer);
                else layers.Insert(index - 1, layer);
            }
            return true;
        }

        /// <inheritdoc />
        public bool RemoveLayer(TouchLayer layer)
        {
            if (layer == null) return false;
            var result = layers.Remove(layer);
            return result;
        }

        /// <inheritdoc />
        public void ChangeLayerIndex(int at, int to)
        {
            if (at < 0 || at >= layers.Count) return;
            if (to < 0 || to >= layers.Count) return;
            var data = layers[at];
            layers.RemoveAt(at);
            layers.Insert(to, data);
        }

        /// <inheritdoc />
        public Transform GetHitTarget(Vector2 position)
        {
            ITouchHit hit;
            TouchLayer layer;
            if (GetHitTarget(position, out hit, out layer)) return hit.Transform;
            return null;
        }

        /// <inheritdoc />
        public bool GetHitTarget(Vector2 position, out ITouchHit hit)
        {
            TouchLayer layer;
            return GetHitTarget(position, out hit, out layer);
        }

        /// <inheritdoc />
        public bool GetHitTarget(Vector2 position, out ITouchHit hit, out TouchLayer layer)
        {
            hit = null;
            layer = null;

            foreach (var touchLayer in layers)
            {
                if (touchLayer == null) continue;
                ITouchHit _hit;
                if (touchLayer.Hit(position, out _hit) == TouchLayer.LayerHitResult.Hit)
                {
                    hit = _hit;
                    layer = touchLayer;
                    return true;
                }
            }

            return false;
        }

        #endregion

        #region Internal methods

        internal ITouch BeginTouch(Vector2 position)
        {
            return BeginTouch(position, null);
        }

        internal ITouch BeginTouch(Vector2 position, Tags tags)
        {
            TouchPoint touch;
            lock (touchesBegan)
            {
                touch = new TouchPoint(nextTouchId++, position, tags);
                touchesBegan.Add(touch);
            }
            return touch;
        }

        internal void UpdateTouch(int id)
        {
            lock (touchesUpdated)
            {
                if (idToTouch.ContainsKey(id)) touchesUpdated.Add(id);
            }
        }

        internal void MoveTouch(int id, Vector2 position)
        {
            lock (touchesUpdated)
            {
                TouchPoint touch;
                if (idToTouch.TryGetValue(id, out touch))
                {
                    touch.SetPosition(position);
                    touchesUpdated.Add(id);
                }
            }
        }

        /// <inheritdoc />
        internal void EndTouch(int id)
        {
            lock (touchesEnded)
            {
                TouchPoint touch;
                if (!idToTouch.TryGetValue(id, out touch))
                {
                    // This touch was added this frame
                    touch = touchesBegan.Find((t) => t.Id == id);
                    // No touch with such id
                    if (touch == null) return;
                }
                touchesEnded.Add(touch.Id);
            }
        }

        /// <inheritdoc />
        internal void CancelTouch(int id)
        {
            lock (touchesCancelled)
            {
                TouchPoint touch;
                if (!idToTouch.TryGetValue(id, out touch))
                {
                    // This touch was added this frame
                    touch = touchesBegan.Find((t) => t.Id == id);
                    // No touch with such id
                    if (touch == null) return;
                }
                touchesCancelled.Add(touch.Id);
            }
        }

        #endregion

        #region Unity

        private void Awake()
        {
            if (instance == null)
            {
                instance = this;
            }
            else if (instance != this)
            {
                Destroy(this);
                return;
            }

            gameObject.hideFlags = HideFlags.HideInHierarchy;
            DontDestroyOnLoad(gameObject);

            updateDPI();

            StopAllCoroutines();
            StartCoroutine("lateAwake");
        }

        private void OnLevelWasLoaded(int value)
        {
            StopAllCoroutines();
            StartCoroutine("lateAwake");
        }

        private IEnumerator lateAwake()
        {
            yield return null;

            updateLayers();
            createCameraLayer();
            createTouchInput();
        }

        private void Update()
        {
            updateTouches();
        }

        private void OnApplicationQuit()
        {
            shuttingDown = true;
        }

        #endregion

        #region Private functions

        private void updateDPI()
        {
            dpi = DisplayDevice == null ? 96 : DisplayDevice.DPI;
            dotsPerCentimeter = TouchManager.CM_TO_INCH * dpi;
        }

        private void updateLayers()
        {
            // filter empty layers
            layers = layers.FindAll(l => l != null);
        }

        private void createCameraLayer()
        {
            if (layers.Count == 0 && shouldCreateCameraLayer)
            {
                Debug.LogWarning("No camera layers, adding CameraLayer for the main camera. (this message is harmless)");
                if (Camera.main != null)
                {
                    var layer = Camera.main.GetComponent<TouchLayer>();
                    if (layer == null) layer = Camera.main.gameObject.AddComponent<CameraLayer>();
                    AddLayer(layer);
                }
            }
        }

        private void createTouchInput()
        {
            var inputs = FindObjectsOfType(typeof(InputSource));
            if (inputs.Length == 0)
            {
                GameObject obj = null;
                var objects = FindObjectsOfType<TouchManager>();
                if (objects.Length == 0)
                {
                    obj = GameObject.Find("TouchScript");
                    if (obj == null) obj = new GameObject("TouchScript");
                }
                else
                {
                    obj = objects[0].gameObject;
                }

                switch (Application.platform)
                {
                    case RuntimePlatform.IPhonePlayer:
                    case RuntimePlatform.Android:
                    case RuntimePlatform.BlackBerryPlayer:
                    case RuntimePlatform.MetroPlayerARM:
                    case RuntimePlatform.MetroPlayerX64:
                    case RuntimePlatform.MetroPlayerX86:
                    case RuntimePlatform.WP8Player:
                        obj.AddComponent<MobileInput>();
                        break;
                    default:
                        obj.AddComponent<MouseInput>();
                        break;
                }
            }
        }

        private void updateBegan()
        {
            if (touchesBegan.Count > 0)
            {
                var touchesList = new List<ITouch>(touchesBegan.Count);
                foreach (var touch in touchesBegan)
                {
                    touchesList.Add(touch);
                    touches.Add(touch);
                    idToTouch.Add(touch.Id, touch);
                    foreach (var touchLayer in layers)
                    {
                        if (touchLayer == null) continue;
                        if (touchLayer.BeginTouch(touch)) break;
                    }
                }

                touchesBeganInvoker.InvokeHandleExceptions(this, new TouchEventArgs(touchesList));
                touchesBegan.Clear();
            }
        }

        private void updateUpdated()
        {
            if (touchesUpdated.Count > 0)
            {
                var updated = new List<ITouch>(touchesUpdated.Count);
                // Need to loop through all touches to reset those which did not move
                foreach (var touch in touches)
                {
                    touch.ResetPosition();
                    if (touchesUpdated.Contains(touch.Id))
                    {
                        updated.Add(touch);
                        if (touch.Layer != null) touch.Layer.UpdateTouch(touch);
                    }
                }

                touchesMovedInvoker.InvokeHandleExceptions(this, new TouchEventArgs(updated));
                touchesUpdated.Clear();
            }
        }

        private void updateEnded()
        {
            if (touchesEnded.Count > 0)
            {
                var updated = new List<ITouch>(touchesEnded.Count);
                foreach (var id in touchesEnded)
                {
                    var touch = idToTouch[id];
                    idToTouch.Remove(touch.Id);
                    touches.Remove(touch);
                    updated.Add(touch);
                    if (touch.Layer != null) touch.Layer.EndTouch(touch);
                }

                touchesEndedInvoker.InvokeHandleExceptions(this, new TouchEventArgs(updated));
                touchesEnded.Clear();
            }
        }

        private void updateCancelled()
        {
            if (touchesCancelled.Count > 0)
            {
                var updated = new List<ITouch>(touchesCancelled.Count);
                foreach (var id in touchesCancelled)
                {
                    var touch = idToTouch[id];
                    idToTouch.Remove(touch.Id);
                    touches.Remove(touch);
                    updated.Add(touch);
                    if (touch.Layer != null) touch.Layer.CancelTouch(touch);
                }

                touchesCancelledInvoker.InvokeHandleExceptions(this, new TouchEventArgs(updated));
                touchesCancelled.Clear();
            }
        }

        private void updateTouches()
        {
            frameStartedInvoker.InvokeHandleExceptions(this, EventArgs.Empty);

            lock (touchesBegan) updateBegan();
            lock (touchesUpdated) updateUpdated();
            lock (touchesEnded) updateEnded();
            lock (touchesCancelled) updateCancelled();

            frameFinishedInvoker.InvokeHandleExceptions(this, EventArgs.Empty);
        }

        #endregion
    }
}


text:
(function() {
    var Dom = YAHOO.util.Dom,
        Event = YAHOO.util.Event,
        Layout = YAHOO.widget.Layout,
        Lang = YAHOO.lang,
        LayoutUnit = YAHOO.widget.LayoutUnit;

        YAHOO.widget.LayoutUnit.prototype.initAttributes = function(attr) {
            YAHOO.widget.LayoutUnit.superclass.initAttributes.call(this, attr);

            /**
            * @private
            * @attribute wrap
            * @description A reference to the wrap element
            * @type HTMLElement
            */
            this.setAttributeConfig('wrap', {
                value: attr.wrap || null,
                method: function(w) {
                    if (w) {
                        var id = Dom.generateId(w);
                        LayoutUnit._instances[id] = this;
                    }
                }
            });
            /**
            * @attribute grids
            * @description Set this option to true if you want the LayoutUnit to fix the first layer of YUI CSS Grids (margins)
            * @type Boolean
            */
            this.setAttributeConfig('grids', {
                value: attr.grids || false
            });
            /**
            * @private
            * @attribute top
            * @description The current top positioning of the Unit
            * @type Number
            */
            this.setAttributeConfig('top', {
                value: attr.top || 0,
                validator: Lang.isNumber,
                method: function(t) {
                    if (!this._collapsing) {
                        this.setStyle('top', t + 'px');
                    }
                }
            });
            /**
            * @private
            * @attribute left
            * @description The current left position of the Unit
            * @type Number
            */
            this.setAttributeConfig('left', {
                value: attr.left || 0,
                validator: Lang.isNumber,
                method: function(l) {
                    if (!this._collapsing) {
                        this.setStyle('left', l + 'px');
                    }
                }
            });

            /**
            * @attribute minWidth
            * @description The minWidth parameter passed to the Resize Utility
            * @type Number
            */
            this.setAttributeConfig('minWidth', {
                value: attr.minWidth || false,
                validator: YAHOO.lang.isNumber
            });

            /**
            * @attribute maxWidth
            * @description The maxWidth parameter passed to the Resize Utility
            * @type Number
            */
            this.setAttributeConfig('maxWidth', {
                value: attr.maxWidth || false,
                validator: YAHOO.lang.isNumber
            });

            /**
            * @attribute minHeight
            * @description The minHeight parameter passed to the Resize Utility
            * @type Number
            */
            this.setAttributeConfig('minHeight', {
                value: attr.minHeight || false,
                validator: YAHOO.lang.isNumber
            });

            /**
            * @attribute maxHeight
            * @description The maxHeight parameter passed to the Resize Utility
            * @type Number
            */
            this.setAttributeConfig('maxHeight', {
                value: attr.maxHeight || false,
                validator: YAHOO.lang.isNumber
            });

            /**
            * @attribute height
            * @description The height of the Unit
            * @type Number
            */
            this.setAttributeConfig('height', {
                value: attr.height,
                validator: Lang.isNumber,
                method: function(h) {
                    if (!this._collapsing) {
                        this.setStyle('height', h + 'px');
                    }
                }
            });

            /**
            * @attribute width
            * @description The width of the Unit
            * @type Number
            */
            this.setAttributeConfig('width', {
                value: attr.width,
                validator: Lang.isNumber,
                method: function(w) {
                    if (!this._collapsing) {
                        this.setStyle('width', w + 'px');
                    }
                }
            });
            /**
            * @attribute position
            * @description The position (top, right, bottom, left or center) of the Unit in the Layout
            * @type {String}
            */
            this.setAttributeConfig('position', {
                value: attr.position
            });
            /**
            * @attribute gutter
            * @description The gutter that we should apply to the parent Layout around this Unit. Supports standard CSS markup: (2 4 0 5) or (2) or (2 5)
            * @type String
            */
            this.setAttributeConfig('gutter', {
                value: attr.gutter || 0,
                validator: YAHOO.lang.isString,
                method: function(gutter) {
                    var p = gutter.split(' ');
                    if (p.length) {
                        this._gutter.top = parseInt(p[0], 10);
                        if (p[1]) {
                            this._gutter.right = parseInt(p[1], 10);
                        } else {
                            this._gutter.right = this._gutter.top;
                        }
                        if (p[2]) {
                            this._gutter.bottom = parseInt(p[2], 10);
                        } else {
                            this._gutter.bottom = this._gutter.top;
                        }
                        if (p[3]) {
                            this._gutter.left = parseInt(p[3], 10);
                        } else if (p[1]) {
                            this._gutter.left = this._gutter.right;
                        } else {
                            this._gutter.left = this._gutter.top;
                        }
                    }
                }
            });
            /**
            * @attribute parent
            * @description The parent Layout that we are assigned to
            * @type {Object} YAHOO.widget.Layout
            */
            this.setAttributeConfig('parent', {
                writeOnce: true,
                value: attr.parent || false,
                method: function(p) {
                    if (p) {
                        p.on('resize', this.resize, this, true);
                    }

                }
            });
            /**
            * @attribute collapseSize
            * @description The pixel size of the Clip that we will collapse to
            * @type Number
            */
            this.setAttributeConfig('collapseSize', {
                value: attr.collapseSize || 25,
                validator: YAHOO.lang.isNumber
            });
            /**
            * @attribute duration
            * @description The duration to give the Animation Utility when animating the opening and closing of Units
            */
            this.setAttributeConfig('duration', {
                value: attr.duration || 0.5
            });
            /**
            * @attribute easing
            * @description The Animation Easing to apply to the Animation instance for this unit.
            */
            this.setAttributeConfig('easing', {
                value: attr.easing || ((YAHOO.util && YAHOO.util.Easing) ? YAHOO.util.Easing.BounceIn : 'false')
            });
            /**
            * @attribute animate
            * @description Use animation to collapse/expand the unit
            * @type Boolean
            */
            this.setAttributeConfig('animate', {
                value: ((attr.animate === false) ? false : true),
                validator: function() {
                    var anim = false;
                    if (YAHOO.util.Anim) {
                        anim = true;
                    }
                    return anim;
                },
                method: function(anim) {
                    if (anim) {
                        this._anim = new YAHOO.util.Anim(this.get('element'), {}, this.get('duration'), this.get('easing'));
                    } else {
                        this._anim = false;
                    }
                }
            });
            /**
            * @attribute header
            * @description The text to use as the Header of the Unit
            */
            this.setAttributeConfig('header', {
                value: attr.header || false,
                method: function(txt) {
                    if (txt === false) {
                        //Remove the footer
                        if (this.header) {
                            Dom.addClass(this.body, 'yui-layout-bd-nohd');
                            this.header.parentNode.removeChild(this.header);
                            this.header = null;
                        }
                    } else {
                        if (!this.header) {
                            var header = this.getElementsByClassName('yui-layout-hd', 'div')[0];
                            if (!header) {
                                header = this._createHeader();
                            }
                            this.header = header;
                        }
                        var h = this.header.getElementsByTagName('h2')[0];
                        if (!h) {
                            h = document.createElement('h2');
                            this.header.appendChild(h);
                        }
                        h.innerHTML = txt;
                        if (this.body) {
                            Dom.removeClass(this.body, 'yui-layout-bd-nohd');
                        }
                    }
                    this.fireEvent('contentChange', { target: 'header' });
                }
            });
            /**
            * @attribute proxy
            * @description Use the proxy config setting for the Resize Utility
            * @type Boolean
            */
            this.setAttributeConfig('proxy', {
                writeOnce: true,
                value: ((attr.proxy === false) ? false : true)
            });
            /**
            * @attribute body
            * @description The content for the body. If we find an element in the page with an id that matches the passed option we will move that element into the body of this unit.
            */
            this.setAttributeConfig('body', {
                value: attr.body || false,
                method: function(content) {
                    if (!this.body) {
                        var body = this.getElementsByClassName('yui-layout-bd', 'div')[0];
                        if (body) {
                            this.body = body;
                        } else {
                            body = document.createElement('div');
                            body.className = 'yui-layout-bd';
                            this.body = body;
                            this.get('wrap').appendChild(body);
                        }
                    }
                    if (!this.header) {
                        Dom.addClass(this.body, 'yui-layout-bd-nohd');
                    }
                    Dom.addClass(this.body, 'yui-layout-bd-noft');

                    var el = null;
                    if (Lang.isString(content)) {
                        el = Dom.get(content);
                    } else if (content && content.tagName) {
                        el = content;
                    }
                    if (el) {
                        var id = Dom.generateId(el);
                        LayoutUnit._instances[id] = this;
                        this.body.appendChild(el);
                    } else {
                        this.body.innerHTML = content;
                    }

                    this._cleanGrids();

                    this.fireEvent('contentChange', { target: 'body' });
                }
            });

            /**
            * @attribute footer
            * @description The content for the footer. If we find an element in the page with an id that matches the passed option we will move that element into the footer of this unit.
            */
            this.setAttributeConfig('footer', {
                value: attr.footer || false,
                method: function(content) {
                    if (content === false) {
                        //Remove the footer
                        if (this.footer) {
                            Dom.addClass(this.body, 'yui-layout-bd-noft');
                            this.footer.parentNode.removeChild(this.footer);
                            this.footer = null;
                        }
                    } else {
                        if (!this.footer) {
                            var ft = this.getElementsByClassName('yui-layout-ft', 'div')[0];
                            if (!ft) {
                                ft = document.createElement('div');
                                ft.className = 'yui-layout-ft';
                                this.footer = ft;
                                this.get('wrap').appendChild(ft);
                            } else {
                                this.footer = ft;
                            }
                        }
                        var el = null;
                        if (Lang.isString(content)) {
                            el = Dom.get(content);
                        } else if (content && content.tagName) {
                            el = content;
                        }
                        if (el) {
                            this.footer.appendChild(el);
                        } else {
                            this.footer.innerHTML = content;
                        }
                        Dom.removeClass(this.body, 'yui-layout-bd-noft');
                    }
                    this.fireEvent('contentChange', { target: 'footer' });
                }
            });
            /**
            * @attribute close
            * @description Adds a close icon to the unit
            */
            this.setAttributeConfig('close', {
                value: attr.close || false,
                method: function(close) {
                    //Position Center doesn't get this
                    if (this.get('position') == 'center') {
                        return false;
                    }
                    if (!this.header) {
                        this._createHeader();
                    }
                    var c = Dom.getElementsByClassName('close', 'div', this.header)[0];
                    if (close) {
                        if (!c) {
                            c = document.createElement('div');
                            c.className = 'close';
                            this.header.appendChild(c);
                            Event.on(c, 'click', this.close, this, true);
                        }
                        c.title = this.STR_CLOSE;
                    } else if (c) {
                        Event.purgeElement(c);
                        c.parentNode.removeChild(c);
                    }
                    this._configs.close.value = close;
                    this.set('collapse', this.get('collapse')); //Reset so we get the right classnames
                }
            });

            /**
            * @attribute collapse
            * @description Adds a collapse icon to the unit
            */
            this.setAttributeConfig('collapse', {
                value: attr.collapse || false,
                method: function(collapse) {
                    //Position Center doesn't get this
                    if (this.get('position') == 'center') {
                        return false;
                    }
                    if (!this.header) {
                        this._createHeader();
                    }
                    var c = Dom.getElementsByClassName('collapse', 'div', this.header)[0];
                    if (collapse) {
                        if (!c) {
                            c = document.createElement('div');
                            this.header.appendChild(c);
                            Event.on(c, 'click', this.collapse, this, true);
                        }
                        c.title = this.STR_COLLAPSE;
                        c.className = 'collapse' + ((this.get('close')) ? ' collapse-close' : '');
                    } else if (c) {
                        Event.purgeElement(c);
                        c.parentNode.removeChild(c);
                    }
                }
            });
            /**
            * @attribute scroll
            * @description Adds a class to the unit to allow for overflow: auto, default is overflow: hidden
            */

            this.setAttributeConfig('scroll', {
                value: attr.scroll || false,
                method: function(scroll) {
                    if ((scroll === false) && !this._collapsed) { //Removing scroll bar
                        if (this.body) {
                            if (this.body.scrollTop > 0) {
                                this._lastScrollTop = this.body.scrollTop;
                            }
                        }
                    }

                    if (scroll) {
                        this.addClass('yui-layout-scroll');
                        if (this._lastScrollTop > 0) {
                            if (this.body) {
                                this.body.scrollTop = this._lastScrollTop;
                            }
                        }
                    } else {
                        this.removeClass('yui-layout-scroll');
                    }
                }
            });
            /**
            * @attribute hover
            * @description Config option to pass to the Resize Utility
            */
            this.setAttributeConfig('hover', {
                writeOnce: true,
                value: attr.hover || false,
                validator: YAHOO.lang.isBoolean
            });
            /**
            * @attribute resize
            * @description Should a Resize instance be added to this unit
            */

            this.setAttributeConfig('resize', {
                value: attr.resize || false,
                validator: function(r) {
                    if (YAHOO.util && YAHOO.util.Resize) {
                        return true;
                    }
                    return false;
                },
                method: function(resize) {
                    if (resize && !this._resize) {
                        //Position Center doesn't get this
                        if (this.get('position') == 'center') {
                            return false;
                        }
                        var handle = false; //To catch center
                        switch (this.get('position')) {
                            case 'top':
                                handle = 'b';
                                break;
                            case 'bottom':
                                handle = 't';
                                break;
                            case 'right':
                                handle = 'l';
                                break;
                            case 'left':
                                handle = 'r';
                                break;
                        }

                        this.setStyle('position', 'absolute'); //Make sure Resize get's a position

                        if (handle) {
                            this._resize = new YAHOO.util.Resize(this.get('element'), {
                                proxy: this.get('proxy'),
                                hover: this.get('hover'),
                                status: false,
                                autoRatio: false,
                                handles: [handle],
                                minWidth: this.get('minWidth'),
                                maxWidth: this.get('maxWidth'),
                                minHeight: this.get('minHeight'),
                                maxHeight: this.get('maxHeight'),
                                height: this.get('height'),
                                width: this.get('width'),
                                setSize: false,
                                wrap: false
                            });

                            this._resize._handles[handle].innerHTML = '<div class="yui-layout-resize-knob"></div>';

                            if (this.get('proxy')) {
                                var proxy = this._resize.getProxyEl();
                                proxy.innerHTML = '<div class="yui-layout-handle-' + handle + '"></div>';
                            }
                            this._resize.on('startResize', function(ev) {
                                this._lastScroll = this.get('scroll');
                                this.set('scroll', false);
                                if (this.get('parent')) {
                                    this.get('parent').fireEvent('startResize');
                                    var c = this.get('parent').getUnitByPosition('center');
                                    this._lastCenterScroll = c.get('scroll');
                                    c.set('scroll', false);
                                }
                                this.fireEvent('startResize');
                            }, this, true);
                            this._resize.on('resize', function(ev) {
                                this.set('height', ev.height);
                                this.set('width', ev.width);
                                this.set('scroll', this._lastScroll);
                                if (this.get('parent')) {
                                    var c = this.get('parent').getUnitByPosition('center');
                                    c.set('scroll', this._lastCenterScroll);
                                }
                            }, this, true);
                        }
                    } else {
                        if (this._resize) {
                            this._resize.destroy();
                        }
                    }
                }
            });

        };
})();

redpajama_set_name: RedPajamaGithub


text:
using System.Web;
using System.Web.Optimization;

namespace SlimOperations
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));

            bundles.Add(new ScriptBundle("~/bundles/jquery-signalr").Include(
                        "~/Scripts/jquery.signalR-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/SlimOperationsJs").Include(
                        "~/Scripts/SlimOperationsJs.js"));

            bundles.Add(new ScriptBundle("~/bundles/md5").Include(
                        "~/Scripts/md5.js"));

#if DEBUG
            BundleTable.EnableOptimizations = false;
#else
            BundleTable.EnableOptimizations = true;
#endif

        }
    }
}


text:
namespace ContentSecurityPolicy
{
    public class FrameAncestorsDirective : Directive
    {
        public FrameAncestorsDirective()
            : this(Constants.SelfKeyword)
        {
        }

        public FrameAncestorsDirective(params string[] values)
            : base(Constants.FrameAncestorsDirectiveKey)
        {
            AddValues(values);
        }
    }
}


text:
package eyecandy

import (
	"fmt"
	"math"
	"regexp"
	"strings"

	"golang.org/x/image/font"

	"github.com/Alquimista/eyecandy/asstime"
	"github.com/Alquimista/eyecandy/reader"
	"github.com/Alquimista/eyecandy/utils"

	// "github.com/Alquimista/eyecandy/writer"
	writer "github.com/Alquimista/eyecandy/writer2"
)

const (
	// AlignBottomLeft Bottom Left SSA numbered Alignment
	AlignBottomLeft int = 1 + iota
	// AlignBottomCenter Bottom Center SSA numbered Alignment
	AlignBottomCenter
	// AlignBottomRight Bottom Right SSA numbered Alignment
	AlignBottomRight

	// AlignMiddleLeft Middle Left SSA numbered Alignment
	AlignMiddleLeft
	// AlignMiddleCenter Middle Center SSA numbered Alignment
	AlignMiddleCenter
	// AlignMiddleRight Middle Right SSA numbered Alignment
	AlignMiddleRight

	// AlignTopLeft Top Left SSA numbered Alignment
	AlignTopLeft
	// AlignTopCenter Top Left SSA numbered Alignment
	AlignTopCenter
	// AlignTopRight Top Right SSA numbered Alignment
	AlignTopRight
)

var reStripTags = regexp.MustCompile(`({[\s\w\d\\-]+})*`)
var reStripTags2 = regexp.MustCompile(`({[^k]+})*`)
var reKara = regexp.MustCompile(
	`{\\k[of]?(?P<duration>\d+)` + // k duration in centiseconds
		`(?:\-)*(?P<inline>[\w\d]+)*` + // inline
		`}(?P<text>[^\{\}]*)`) //text

func StripSSATags(text string) string {
	return strings.TrimSpace(reStripTags.ReplaceAllString(text, ""))
}

func StripSSATagsNotKDur(text string) string {
	return strings.TrimSpace(reStripTags2.ReplaceAllString(text, ""))
}

func GetSyls(text string) [][]string {
	return reKara.FindAllStringSubmatch(StripSSATagsNotKDur(text), -1)
}

type Dialog struct {
	Layer     int
	StartTime int
	EndTime   int
	StyleName string
	Actor     string
	Effect    string
	Text      string
	Tags      string
	Duration  int
	MidTime   int
	Style     *reader.Style
	Comment   bool
	Width     float64
	Height    float64
	Size      [2]float64
	XFix      float64
	X         float64
	Y         float64
	Top       float64
	Middle    float64
	Bottom    float64
	Left      float64
	Center    float64
	Right     float64
}

// Line Represent the subtitle"s lines.
type Line struct {
	Dialog
	Kara       string
	SylN       int
	CharN      int
	syls       [][]string
	fontFace   font.Face
	resolution [2]int
}

// Syl Represent the subtitle"s lines.
type Syl struct {
	Dialog
	Inline string
}

// Char Represent the subtitle"s lines.
type Char struct {
	Dialog
	Inline        string
	SylStartTime  int
	SylEndTime    int
	SylMidEndTime int
	SylDuration   int
}

// Chars list all characters in a Line
func (d *Line) Chars() (chars []*Char) {

	start, end, x, dur := 0, 0, 0.0, 0
	for _, s := range d.Syls() {

		curX := float64(s.Left)
		lineStart := s.StartTime
		lineEnd := s.EndTime

		charN := utils.LenString(s.Text)

		// For syls of one char
		if charN == 1 || charN == 0 {
			dur = s.Duration
		} else {
			dur = int(s.Duration / charN)
		}

		for i, c := range s.Text {
			text := string(c)

			start = lineStart
			lineStart += dur

			width, _ := utils.MeasureString(d.fontFace, text)
			width *= d.Style.Scale[0] / 100.0
			// width += 2.0*s.Style.Bord + s.Style.Shadow
			middlewidth := float64(width) / 2.0

			cleft := float64(curX)
			ccenter := cleft + float64(middlewidth)
			cright := cleft + float64(width)

			align := d.Style.Alignment

			switch align {
			case 1, 4, 7: // left
				x = cleft
			case 2, 5, 8: // center
				x = ccenter
			case 3, 6, 9: // right
				x = cright
			}

			if i == charN-1 {
				// Ensure that the end time and the width of the last char
				// is the same that the end time and width of the syl
				end = lineEnd
			} else {
				end = lineStart
			}

			c := &Char{
				Dialog: Dialog{
					Layer:     d.Layer,
					Style:     d.Style,
					StyleName: d.StyleName,
					Actor:     d.Actor,
					Effect:    d.Effect,
					Tags:      d.Tags,
					Comment:   d.Comment,
					StartTime: start,
					EndTime:   end,
					Duration:  dur,
					MidTime:   end - start,
					Text:      text,
					Width:     float64(width),
					Height:    d.Height, //+ 2.0*d.Style.Bord + d.Style.Shadow,
					Size:      [2]float64{float64(width), d.Height},
					X:         float64(x),
					Y:         float64(d.Y),
					Top:       float64(d.Top),
					Middle:    float64(d.Middle),
					Bottom:    float64(d.Bottom),
					Left:      float64(cleft),
					Center:    float64(ccenter),
					Right:     float64(cright),
				},
				Inline:        s.Inline,
				SylStartTime:  s.StartTime,
				SylEndTime:    s.EndTime,
				SylMidEndTime: s.MidTime,
				SylDuration:   s.Duration,
			}

			chars = append(chars, c)

			curX += width
		}
	}
	return chars

}

// Syls list all syllables in a Line
func (d *Line) Syls() (syls []*Syl) {

	lineStart := d.StartTime
	lineEnd := d.EndTime
	end := 0
	fontFace := d.fontFace

	spaceWidth, _ := utils.MeasureString(fontFace, " ")
	spaceWidth *= d.Style.Scale[0] / 100.0
	//spaceWidth += 2*d.Style.Bord + d.Style.Shadow

	curX := d.Left + float64(d.SylN)*-d.XFix/2.0
	maxWidth := 0.0
	sumHeight := 0.0
	resx, resy := float64(d.resolution[0]), float64(d.resolution[1])

	for i, dlg := range d.syls {
		duration, inline, text := dlg[1], dlg[2], dlg[3]
		dur := utils.Str2int(duration) * 10 // cs to ms

		// Absolute times
		start := lineStart
		lineStart += dur
		if i == d.SylN-1 {
			// Ensure that the end time and the width of the last syl
			// is the same that the end time and width of the line
			end = lineEnd
		} else {
			end = lineStart
		}

		strippedText, preSpace, postSpace := utils.TrimSpaceCount(text)

		width, _ := utils.MeasureString(fontFace, strippedText)
		width *= d.Style.Scale[0] / 100.0
		//width += 2.0*d.Style.Bord + d.Style.Shadow
		height := d.Height

		middleheight := float64(height) / 2.0
		middlewidth := float64(width) / 2.0
		align := d.Style.Alignment

		curX += float64(preSpace) * spaceWidth
		sleft := float64(curX)
		scenter := sleft + middlewidth
		sright := sleft + width
		x := 0.0
		y := 0.0
		stop := 0.0
		smid := 0.0
		sbot := 0.0

		maxWidth = math.Max(maxWidth, width)
		sumHeight += height

		// line x
		if align > 6 || align < 4 {
			switch align {
			case 1, 7: // left
				x = sleft
			case 2, 8: // center
				x = scenter
			case 3, 9: // right
				x = sright
			}
			curX += width + float64(postSpace)*spaceWidth +
				float64(d.Style.Spacing) + d.XFix

		} else { // vertical alignment
			xFix := (maxWidth - width) / 2.0
			switch align {
			case 4: // left
				sleft = d.Left + xFix
				scenter = sleft + middlewidth
				sright = sleft + width
				x = sleft
			case 5: // center
				sleft = resx/2.0 - middlewidth
				scenter = sleft + middlewidth
				sright = sleft + width
				x = scenter
			case 6: // right
				sleft = d.Right - width - xFix
				scenter = sleft + middlewidth
				sright = sleft + width
				x = sright
			}
		}

		curY := resy/2.0 - sumHeight/2.0 + float64(d.Style.Spacing)

		// line y
		if align > 6 || align < 4 {
			stop = d.Top
			smid = d.Middle
			sbot = d.Bottom
			y = d.Y
		} else { // vertical alignment
			stop = curY
			smid = stop + middleheight
			sbot = stop + height
			y = smid
			// curY += height
		}

		if text != "" {
			s := &Syl{
				Dialog: Dialog{
					Layer:     d.Layer,
					Style:     d.Style,
					StyleName: d.StyleName,
					Actor:     d.Actor,
					Effect:    d.Effect,
					Tags:      d.Tags,
					Comment:   d.Comment,
					StartTime: start,
					EndTime:   end,
					Duration:  dur,
					MidTime:   end - start,
					Text:      strippedText,
					Width:     float64(width),
					Height:    float64(height),
					Size:      [2]float64{float64(width), float64(height)},
					X:         float64(x),
					Y:         float64(y),
					Top:       float64(stop),
					Middle:    float64(smid),
					Bottom:    float64(sbot),
					Left:      float64(sleft),
					Center:    float64(scenter),
					Right:     float64(sright),
				},
				Inline: inline,
			}

			syls = append(syls, s)
		}
	}
	return syls
}

// Script represent the SSA Script
type Script struct {
	Resolution         [2]int // WIDTH, HEIGHT
	VideoPath          string
	VideoZoom          float64
	VideoPosition      int
	VideoAR            float64
	MetaFilename       string
	MetaTitle          string
	MetaOriginalScript string
	MetaTranslation    string
	MetaTiming         string
	Audio              string
	LineN              int
	Shift              int
	XFix               float64
	scriptIn           *reader.Script
	scriptOut          *writer.Script
	fontFace           map[string]font.Face
}

// Lines List all the lines in a Script
func (fx *Script) Lines() (dialogs []*Line) {

	resx, resy := float64(fx.Resolution[0]), float64(fx.Resolution[1])

	for _, dlg := range fx.scriptIn.Dialog.NotCommented() {

		end := asstime.SSAtoMS(dlg.EndTime)
		start := asstime.SSAtoMS(dlg.StartTime)
		duration := end - start
		text := StripSSATags(dlg.Text)
		fontFace := fx.fontFace[dlg.StyleName]
		width, height := utils.MeasureString(fontFace, text)
		width *= dlg.Style.Scale[0] / 100.0
		//width += 2*dlg.Style.Bord + dlg.Style.Shadow
		height *= dlg.Style.Scale[1] / 100.0

		align := dlg.Style.Alignment
		ml, mr, mv := float64(dlg.Style.Margin[0]),
			float64(dlg.Style.Margin[1]),
			float64(dlg.Style.Margin[2])

		// Alignment
		middleheight := float64(height) / 2.0
		middlewidth := float64(width) / 2.0

		x := 0.0
		y := 0.0
		ltop := 0.0
		lmid := 0.0
		lbot := 0.0
		lleft := 0.0
		lcenter := 0.0
		lright := 0.0

		// line x
		switch align {
		case 1, 4, 7: // left
			lleft = ml
			lcenter = lleft + middlewidth
			lright = lleft + width
			x = lleft
		case 2, 5, 8: // center
			lleft = resx/2.0 - middlewidth
			lcenter = lleft + middlewidth
			lright = lleft + width
			x = lcenter
		case 3, 6, 9: // right
			lleft = resx - mr - width
			lcenter = lleft + middlewidth
			lright = lleft + width
			x = lright
		}

		// line y
		switch align {
		case 7, 8, 9: // top
			ltop = mv
			lmid = ltop + middleheight
			lbot = ltop + height
			y = ltop
		case 4, 5, 6: // middle
			lmid = resy / 2
			ltop = lmid - middleheight
			lbot = lmid + middleheight
			y = lmid
		case 1, 2, 3: // bottom
			lbot = resy - mv
			lmid = lbot - middleheight
			ltop = lbot - height
			y = lbot
		}

		syls := GetSyls(dlg.Text)

		charN := 0
		for _, s := range syls {
			syltext := strings.TrimSpace(s[3])
			if syltext != "" {
				for range syltext {
					charN++
				}
			}
		}

		d := &Line{
			Dialog: Dialog{
				Layer:     dlg.Layer,
				StartTime: start,
				EndTime:   end,
				Duration:  duration,
				MidTime:   start + int(duration/2),
				Style:     dlg.Style,
				StyleName: dlg.StyleName,
				Actor:     dlg.Actor,
				Effect:    dlg.Effect,
				Text:      text,
				Tags:      dlg.Tags,
				Comment:   dlg.Comment,
				Width:     float64(width),
				Height:    float64(height),
				Size:      [2]float64{float64(width), float64(height)},
				XFix:      fx.XFix,
				X:         float64(x),
				Y:         float64(y),
				Top:       float64(ltop),
				Middle:    float64(lmid),
				Bottom:    float64(lbot),
				Left:      float64(lleft),
				Center:    float64(lcenter),
				Right:     float64(lright),
			},
			Kara:       dlg.Text,
			SylN:       len(syls),
			CharN:      charN,
			syls:       syls,
			fontFace:   fontFace,
			resolution: fx.Resolution,
		}
		dialogs = append(dialogs, d)
	}
	return dialogs
}

// GetStyle get a style corresponding to name provided
func (fx *Script) GetStyle(name string) (*reader.Style, bool) {
	style, ok := fx.Styles()[name]
	return style, ok
}

// Styles list styles use the Script
func (fx *Script) Styles() map[string]*reader.Style {
	return fx.scriptIn.StyleUsed
}

// AddStyle append a Style to Script
func (fx *Script) AddStyle(sty *writer.Style) {
	fx.scriptIn.StyleUsed[sty.Name] = reader.NewStyle(sty.Name)
	fx.scriptOut.AddStyle(sty)
}

// CopyLine create a copy of the current Line
func (fx *Script) CopyLine(dialog *Line) Line {
	return *dialog
}

// CopySyl create a copy of the current Syl
func (fx *Script) CopySyl(dialog *Syl) Syl {
	return *dialog
}

// CopyChar create a copy of the current Char
func (fx *Script) CopyChar(dialog *Char) Char {
	return *dialog
}

// Add append a Dialog (Syl, Char, Line) to Script
func (fx *Script) Add(dialog interface{}) {

	switch dlg := dialog.(type) {
	case Line:
		d := NewDialog(dlg.Text)
		d.Layer = dlg.Layer
		d.Start = asstime.MStoSSA(dlg.StartTime + fx.Shift)
		d.End = asstime.MStoSSA(dlg.EndTime + fx.Shift)
		d.StyleName = dlg.StyleName
		d.Actor = dlg.Actor
		d.Effect = dlg.Effect
		d.Tags = dlg.Tags
		d.Comment = dlg.Comment
		fx.scriptOut.AddDialog(d)
	case Syl:
		d := NewDialog(dlg.Text)
		d.Layer = dlg.Layer
		d.Start = asstime.MStoSSA(dlg.StartTime + fx.Shift)
		d.End = asstime.MStoSSA(dlg.EndTime + fx.Shift)
		d.StyleName = dlg.StyleName
		d.Actor = dlg.Actor
		d.Effect = dlg.Effect
		d.Tags = dlg.Tags
		d.Comment = dlg.Comment
		fx.scriptOut.AddDialog(d)
	case Char:
		d := NewDialog(dlg.Text)
		d.Layer = dlg.Layer
		d.Start = asstime.MStoSSA(dlg.StartTime + fx.Shift)
		d.End = asstime.MStoSSA(dlg.EndTime + fx.Shift)
		d.StyleName = dlg.StyleName
		d.Actor = dlg.Actor
		d.Effect = dlg.Effect
		d.Tags = dlg.Tags
		d.Comment = dlg.Comment
		fx.scriptOut.AddDialog(d)
	default:
		fmt.Println("Not admitted object")
	}

}

// Save create the final script file (.ass)
func (fx *Script) Save(fn string) {
	fx.scriptOut.Resolution = fx.Resolution
	fx.scriptOut.VideoPath = fx.VideoPath
	fx.scriptOut.VideoZoom = fx.VideoZoom
	fx.scriptOut.VideoPosition = fx.VideoPosition
	fx.scriptOut.VideoAR = fx.VideoAR
	fx.scriptOut.MetaFilename = fx.MetaFilename
	fx.scriptOut.MetaTitle = fx.MetaTitle
	fx.scriptOut.MetaOriginalScript = fx.MetaOriginalScript
	fx.scriptOut.MetaTranslation = fx.MetaTranslation
	fx.scriptOut.MetaTiming = fx.MetaTiming
	fx.scriptOut.Audio = fx.Audio
	fx.scriptOut.Save(fn)
}

// NewEffect create a new script
func NewEffect(inFN string) *Script {
	input := reader.Read(inFN)
	output := writer.NewScript()

	fontFace := make(map[string]font.Face)

	ssampling := 1

	for _, style := range input.StyleUsed {
		s := NewStyle(style.Name)
		s.Name = style.Name
		s.FontName = style.FontName
		s.FontSize = style.FontSize
		s.Color = style.Color
		s.Bold = style.Bold
		s.Italic = style.Italic
		s.Scale = style.Scale
		s.Angle = style.Angle
		s.Bord = style.Bord
		s.Shadow = style.Shadow
		s.Alignment = style.Alignment
		s.Margin = style.Margin
		output.AddStyle(s)

		ff, err := utils.LoadFont(s.FontName, s.FontSize*ssampling)
		if err != nil {
			panic(err)
		}
		fontFace[s.Name] = ff
	}

	// Add the original karaoke commented by default in the script
	// This help to jump to the wanted line in the preview in Aegisub,
	// and/or keep a backup of the timed subs
	dok := NewDialog("### Original Karaoke ###")
	dok.Comment = true
	output.AddDialog(dok)
	LineN := 0
	for _, dlg := range input.Dialog {
		d := writer.NewDialog(dlg.Text)
		d.Layer = dlg.Layer
		d.Start = dlg.StartTime
		d.End = dlg.EndTime
		d.StyleName = dlg.StyleName
		d.Actor = dlg.Actor
		d.Effect = dlg.Effect
		d.Comment = true
		output.AddDialog(d)
		LineN++
	}
	dke := NewDialog("### Karaoke Effect ###")
	dke.Comment = true
	output.AddDialog(dke)

	return &Script{
		Resolution:         input.Resolution,
		VideoPath:          input.VideoPath,
		VideoZoom:          input.VideoZoom,
		VideoPosition:      input.VideoPosition,
		VideoAR:            input.VideoAR,
		MetaFilename:       input.MetaFilename,
		MetaTitle:          input.MetaTitle,
		MetaOriginalScript: input.MetaOriginalScript,
		MetaTranslation:    input.MetaTranslation,
		MetaTiming:         input.MetaTiming,
		Audio:              input.Audio,
		LineN:              LineN,
		fontFace:           fontFace,
		scriptIn:           input,
		scriptOut:          output,
	}
}

// NewStyle create a new Style
func NewStyle(name string) *writer.Style {
	return writer.NewStyle(name)
}

// NewDialog create a new Dialog
func NewDialog(text string) *writer.Dialog {
	return writer.NewDialog(text)
}


text:
require 'test_helper'

class SiteControllerTest < ActionController::TestCase
  include Devise::TestHelpers
  def setup
    @request.env["devise.mapping"] = Devise.mappings[:admin]
    user = FactoryGirl.create(:admin)
    user.confirm!
    sign_in user
  end

  test "should get index" do
    get :index
    assert_response :success
  end

end


text:
namespace sim
{

TeamResult::TeamResult()
{
	for (size_t i = 0; i < StatisticalDataKeys::_LastKey; ++i)
		statisticalData[i] = 0;
	for (size_t i = 0; i < MAXPLACES; ++i)
		placeHistogram[i] = 0;
	teamID = 0;
}

TeamResult::~TeamResult()
{

}

double TeamResult::getAvgPlace()
{
	int totalPlaces = 0;
	int weightedPlaces = 0;

	for (int i = 0; i < Tournament::NoPlace; ++i)
	{
		totalPlaces += placeHistogram[i];
		weightedPlaces += i * placeHistogram[i];
	}

	if (totalPlaces == 0) return 0.0;
	return (double)(weightedPlaces) / (double)(totalPlaces);
}

int TeamResult::getTotalPlaceCount()
{
	int counter = 0;
	for (size_t i = 0; i < MAXPLACES; ++i)
		counter += placeHistogram[i];
	return counter;
}

void TeamResult::merge(TeamResult &other)
{
	for (size_t i = 0; i < StatisticalDataKeys::_LastKey; ++i)
		statisticalData[i] += other.statisticalData[i];
	for (size_t i = 0; i < MAXPLACES; ++i)
		placeHistogram[i] += other.placeHistogram[i];
}

json_spirit::Object TeamResult::toJSONObject()
{
	json_spirit::Object object;
	object.push_back(json_spirit::Pair("wins", statisticalData[StatisticalDataKeys::TotalWins]));
	object.push_back(json_spirit::Pair("losses", statisticalData[StatisticalDataKeys::TotalLosses]));
	object.push_back(json_spirit::Pair("draws", statisticalData[StatisticalDataKeys::TotalDraws]));
	object.push_back(json_spirit::Pair("matches", statisticalData[StatisticalDataKeys::TotalMatches]));
	assert(statisticalData[StatisticalDataKeys::TotalMatches] == (statisticalData[StatisticalDataKeys::TotalWins] + statisticalData[StatisticalDataKeys::TotalLosses] + statisticalData[StatisticalDataKeys::TotalDraws]));
	return object;
}

json_spirit::Array TeamResult::rankDataToJSONArray(std::vector<RankData> &rankData)
{
	json_spirit::Array ranks;
	// calculate number of total ranked games first - this is not necessarily ==TotalMatches
	int totalRankedGames = 0;
	for (size_t i = 1; i < MAXPLACES; ++i)
		totalRankedGames += placeHistogram[i];
	// match all ranks
	for (RankData &rank : rankData)
	{
		json_spirit::Object object;
		int count = 0;
		for (int i = rank.placeBegin; i <= rank.placeEnd; ++i)
			count += placeHistogram[i];
		// safety
		float value = 0.0f;
		if (totalRankedGames != 0)
			value = (float)count / (float)totalRankedGames;
		assert(value <= 1.0f);
		object.push_back(json_spirit::Pair("percentage", value));
		ranks.push_back(object);
	}
	return ranks;
}

Team::Team(json_spirit::Object &data, int index)
{
	this->index = index;

	for (json_spirit::Pair &pair : data)
	{
		std::string key = pair.name_;
		if (key == "id") id = pair.value_.get_int();
		else if (key == "scores") setupScores(pair.value_.get_obj());
		else
			std::cerr << "sim::Team: invalid property \"" << key << "\"" << std::endl;
	}
}

void Team::setupScores(json_spirit::Object &scoreData)
{
	for (json_spirit::Pair &pair : scoreData)
	{
		scores[pair.name_] = pair.value_.get_real();
	}
}

Team::~Team()
{
}

RankData::RankData(std::string name, int placeBegin, int placeEnd)
{
	this->name = name;
	this->placeBegin = placeBegin;
	this->placeEnd = placeEnd;
}

json_spirit::Object RankData::toJSONObject()
{
	json_spirit::Object object;
	object.push_back(json_spirit::Pair("name", name));
	return object;
}

} // namespace sim


text:
"""
A module to write the output in different formats
"""

import os
import gzip

from argparse import Namespace
from Bio import SeqIO
from Bio.SeqFeature import SeqFeature, FeatureLocation
from collections import OrderedDict
from BCBio import GFF  # bcbio-gff package

import PhiSpyModules.version as version
from .log_and_message import log_and_message
from .helper_functions import is_gzip_file
from .evaluation import check_pp

__author__ = 'Rob Edwards'

def genome_gff3(self):
    """
    Write GFF3 format output using BCBios format
    :param self: the data object
    :return: None
    """
    log_and_message("Writing Genomic GFF3 output file", c="GREEN", stderr=True, quiet=self.quiet)
    # GFF output
    out_gff = os.path.join(self.output_dir, self.file_prefix + "genome.gff3")
    with open(out_gff, 'w') as outf:
        GFF.write(self.record, outf, True)

def write_gff3(self):
    """
    Write GFF3 code. This was adapted from code contribued by [Jose Francisco Sanchez-Herrero]
    (https://github.com/JFsanchezherrero/)
    :param self: the data object
    :return: None
    """

    log_and_message("Writing GFF3 output file", c="GREEN", stderr=True, quiet=self.quiet)
    # GFF output
    out_gff = open(os.path.join(self.output_dir, self.file_prefix + "prophage.gff3"), "w")
    out_gff.write("##gff-version 3")
    out_gff.write("\n")

    # loop through pp results
    for i in self.pp:
        # GFF
        # strand is not known...
        out_gff.write(str(self.pp[i]['contig']) +
                      '\tPhiSpy\tprophage_region\t' +
                      str(self.pp[i]['start']) + '\t' +
                      str(self.pp[i]['stop']) + '\t.\t.' +
                      ' \t.\tID=pp' + str(i))
        out_gff.write('\n')

        if 'att' not in self.pp[i]:
            self.pp[i]['att'] = ""
        else:
            # attL
            out_gff.write(str(self.pp[i]['contig']) +
                          '\tPhiSpy\tattL\t' +
                          str(self.pp[i]['att'][0]) + '\t' +
                          str(self.pp[i]['att'][1]) + '\t.\t.' +
                          ' \t.\tID=pp' + str(i))
            out_gff.write('\n')

            # attR
            out_gff.write(str(self.pp[i]['contig']) +
                          '\tPhiSpy\tattR\t' +
                          str(self.pp[i]['att'][2]) + '\t' +
                          str(self.pp[i]['att'][3]) + '\t.\t.' +
                          ' \t.\tID=pp' + str(i))
            out_gff.write('\n')

    out_gff.close()

def write_genbank(self):
    """
    Write prophages and their potential attachment sites in updated input GenBank file.
    :param self: the data object
    :return: None
    """

    log_and_message("Writing GenBank output file", c="GREEN", stderr=True, quiet=self.quiet)
    outfile = os.path.join(self.output_dir, self.file_prefix + os.path.basename(self.infile))

    # are we writing a gzip file
    if is_gzip_file(self.infile):
        handle = gzip.open(outfile, 'wt')
    else:
        handle = open(outfile, 'w')

    SeqIO.write(self.record, handle, 'genbank')

def write_phage_and_bact(self):
    """
    Separate out the phage and bacterial fractions into fasta and GenBank files
    :param self: the data object
    :return: None
    """
    log_and_message('Writing bacterial and phage DNA as fasta', c="GREEN", stderr=True, quiet=self.quiet)
    phage_out = open(os.path.join(self.output_dir, self.file_prefix + "phage.fasta"), "w")
    phage_genbank = open(os.path.join(self.output_dir, self.file_prefix + "phage.gbk"), "w")
    bacteria_out = open(os.path.join(self.output_dir, self.file_prefix + "bacteria.fasta"), "w")
    bacteria_genbank = open(os.path.join(self.output_dir, self.file_prefix + "bacteria.gbk"), "w")

    dna = {entry.id: str(entry.seq) for entry in self.record}

    contig_to_phage = {}
    for i in self.pp:
        contig = self.pp[i]['contig']  # contig name
        if contig not in contig_to_phage:
            contig_to_phage[contig] = set()
        contig_to_phage[contig].add(i)

    for contig in dna:
        if contig not in contig_to_phage:
            bacteria_out.write(f">{contig}\n{dna[contig]}\n")
            SeqIO.write(self.record.get_entry(contig), bacteria_genbank, "genbank")
            continue
        pps1 = list(contig_to_phage[contig])
        pps = sorted(pps1, key=lambda k: self.pp[k]['start'])
        bactstart = 0
        dnaseq = ""
        hostcounter = 0
        for ppnum in pps:
            pphagestart = self.pp[ppnum]['start']
            pphagestop = self.pp[ppnum]['stop']

            phageseq = dna[contig][pphagestart:pphagestop]
            phage_out.write(f">{contig}_{pphagestart}_{pphagestop} [pp {ppnum}]\n{phageseq}\n")
            pp_gbk = self.record.get_entry(contig)[pphagestart:pphagestop]
            # set the locus tag
            pp_gbk.name += f"_PP{ppnum}"
            # set the Accession
            pp_gbk.id += f"_PP{ppnum}"
            # set the definition line
            pp_gbk.description += f" prophage PP{ppnum} on {contig} from {pphagestart} to {pphagestop}"
            # set the molecule type; required for Biopython v1.78 and above - https://biopython.org/wiki/Alphabet
            pp_gbk.annotations = {"molecule_type": "DNA"}
            SeqIO.write(pp_gbk, phage_genbank, "genbank")

            dnaseq += dna[contig][bactstart:pphagestart - 1]
            dnaseq += "N" * len(phageseq)
            host_gbk = self.record.get_entry(contig)[bactstart:pphagestart - 1]
            hostcounter += 1
            host_gbk.name += f"_region_{hostcounter}"
            host_gbk.id += f"_region_{hostcounter}"
            host_gbk.description += f" region {hostcounter} on {contig} from {bactstart} to {pphagestart - 1}"
            # set the molecule type; required for Biopython v1.78 and above - https://biopython.org/wiki/Alphabet
            host_gbk.annotations = {"molecule_type": "DNA"}
            SeqIO.write(host_gbk, bacteria_genbank, "genbank")
            bactstart = pphagestop + 1

        dnaseq += dna[contig][bactstart:]
        host_gbk = self.record.get_entry(contig)[bactstart:]
        hostcounter += 1
        host_gbk.name += f"_region_{hostcounter}"
        host_gbk.id += f"_region_{hostcounter}"
        host_gbk.description += f" region {hostcounter} on {contig} from {bactstart} onwards"
        # set the molecule type; required for Biopython v1.78 and above - https://biopython.org/wiki/Alphabet
        host_gbk.annotations = {"molecule_type": "DNA"}
        bacteria_out.write(f">{contig} [phage regions replaced with N]\n{dnaseq}\n")
        SeqIO.write(host_gbk, bacteria_genbank, "genbank")

    phage_out.close()
    phage_genbank.close()
    bacteria_out.close()
    bacteria_genbank.close()

def write_prophage_coordinates(self):
    """
    Write the coordinates and other details about the prophages
    :param self: the data object
    :return: None
    """

    log_and_message("Writing prophage_coordinates output file", c="GREEN", stderr=True, quiet=self.quiet)
    with open(os.path.join(self.output_dir, self.file_prefix + 'prophage_coordinates.tsv'), 'w') as out:
        for i in self.pp:
            if 'atts' not in self.pp[i]:
                self.pp[i]['atts'] = ""
            locs = [
                "pp" + str(i),
                self.pp[i]['contig'],
                self.pp[i]['start'],
                self.pp[i]['stop'],
                self.pp[i]['atts']
            ]
            out.write("\t".join(map(str, locs)) + "\n")

def write_prophage_tbl(self):
    """
    Create a prophage_tbl file from our pp dictionary
    :param self: the data object
    :return: None
    """

    log_and_message("Writing prophage.tbl output file", c="GREEN", stderr=True, quiet=self.quiet)
    with open(os.path.join(self.output_dir, self.file_prefix + "prophage.tbl"), 'w') as out:
        for i in self.pp:
            locs = [
                "pp_" + str(i),
                self.pp[i]['contig'],
                self.pp[i]['start'],
                self.pp[i]['stop']
            ]
            out.write(locs[0] + "\t" + "_".join(map(str, locs[1:])) + "\n")

def write_prophage_information(self):
    """
    Write the full ORF table
    :param self: the data object
    :return:
    """

    log_and_message("Writing prophage_information.tsv output file", c="GREEN", stderr=True, quiet=self.quiet)
    with open(os.path.join(self.output_dir, self.file_prefix + "prophage_information.tsv"), 'w') as out:
        out.write("identifier\tfunction\tcontig\tstart\tstop\tposition\trank\tmy_status\tpp\tFinal_status\t")
        out.write("start of attL\tend of attL\tstart of attR\tend of attR\tsequence of attL\tsequence of attR\t")
        out.write("Reason for att site\n")

        written_atts = set()
        for this_pp in self.initial_tbl:
            ppnum = check_pp(this_pp[2], int(this_pp[3]), int(this_pp[4]), self.pp)
            out.write("\t".join(map(str, this_pp + [ppnum])))
            if ppnum > 0 and 'atts' in self.pp[ppnum] and ppnum not in written_atts:
                out.write("\t" + self.pp[ppnum]['atts'] + "\n")
                written_atts.add(ppnum)
            else:
                out.write("\n")

def write_prophage_tsv(self):
    """
    Create a tsv with headers for this data. Issue #28 item 2
    :param self: the data object
    :return: None
    """

    log_and_message("Writing prophage.tsv output file", c="GREEN", stderr=True, quiet=self.quiet)
    with open(os.path.join(self.output_dir, self.file_prefix + "prophage.tsv"), 'w') as out:
        out.write("Prophage number\tContig\tStart\tStop\n")
        for i in self.pp:
            locs = [
                "pp_" + str(i),
                self.pp[i]['contig'],
                self.pp[i]['start'],
                self.pp[i]['stop']
            ]
            out.write("\t".join(map(str, locs)) + "\n")

def write_test_data(self):
    """
    Write the testing measurements
    :param self: the data object
    :return: None
    """
    log_and_message("Writing test_data output file", c="GREEN", stderr=True, quiet=self.quiet)
    with open(os.path.join(self.output_dir, self.file_prefix + "test_data.tsv"), 'w') as out:
        if self.phmms:
            out.write('identifier\torf_length_med\tshannon_slope\tat_skew\tgc_skew\tmax_direction\tphmms\tstatus\n')
        else:
            out.write('identifier\torf_length_med\tshannon_slope\tat_skew\tgc_skew\tmax_direction\tstatus\n')

        for i, d in enumerate(self.test_data):
            out.write("\t".join(map(str, [self.initial_tbl[i][0]] + d)) + "\n")

def prophage_measurements_to_tbl(inputf, outputf):
    try:
        f = open(inputf, 'r')
        fw = open(outputf, 'w')
    except IOError as e:
        log_and_message(f"There was an error trying to convert the measurements to a tbl: {e}", c="RED", stderr=True)
        return
    pp = {}
    ppindx = 0
    prev_contig = None
    inphage = False
    header = f.readline()
    for line in f:
        temp = line.strip().split("\t")
        if int(temp[9]) > 0:
            newphage = False
            if temp[2] != prev_contig:
                newphage = True
            if not inphage:
                newphage = True
            if newphage:
                ppindx += 1
                pp[ppindx] = {}
                pp[ppindx]['contig'] = temp[2]
                pp[ppindx]['start'] = min(int(temp[3]), int(temp[4]))
                pp[ppindx]['stop'] = max(int(temp[3]), int(temp[4]))
            else:
                pp[ppindx]['stop'] = max(int(temp[3]), int(temp[4]))
            inphage = True
            prev_contig = temp[2]
        else:
            inphage = False
    for i in pp:
        fw.write("pp_" + str(i) + "\t" + pp[i]['contig'] + "_" + str(pp[i]['start']) + "_" + str(pp[i]['stop']) + "\n")
    f.close()
    fw.close()

def write_all_outputs(**kwargs):
    self = Namespace(**kwargs)
    # make all predicted pp list
    log_and_message("Creating output files", c="GREEN", stderr=True, quiet=self.quiet)
    prophage_feature_type = 'misc_feature'  # / prophage_region

    for i in self.pp:
        self.record.get_entry(self.pp[i]['contig']).append_feature(SeqFeature(
            location=FeatureLocation(self.pp[i]['start'] - 1, self.pp[i]['stop'] - 1),
            type=prophage_feature_type,
            strand=1,
            qualifiers=OrderedDict(
                {'note': f'prophage region pp{i} identified with PhiSpy v{version.__version__}'}
            )))
        if 'atts' in self.pp[i]:
            self.record.get_entry(self.pp[i]['contig']).append_feature(SeqFeature(
                location=FeatureLocation(int(self.pp[i]['att'][0]), int(self.pp[i]['att'][1])) +
                         FeatureLocation(int(self.pp[i]['att'][2]), int(self.pp[i]['att'][3])),
                type='repeat_region',
                strand=1,
                qualifiers=OrderedDict({'note': f'prophage region pp{i} potential attachment sites'})))

    if self.keep_dropped_predictions:
        for i in self.droppedpp:
            self.record.get_entry(self.droppedpp[i]['contig']).append_feature(SeqFeature(
                location=FeatureLocation(self.droppedpp[i]['start'] - 1, self.droppedpp[i]['stop'] - 1),
                type=prophage_feature_type,
                strand=-1,
                qualifiers=OrderedDict(
                    {'note': f'Putative prophage region identified with PhiSpy v{version.__version__} but not' +
                     f'kept because: {self.droppedpp[i]["dropped_reason"]}'}
                )))

    """
    now we need to decide which files to keep
    It is based on this code:
        Code | File
        --- | ---
        1 | prophage_coordinates.tsv
        2 | GenBank format output
        4 | prophage and bacterial sequences
        8 | prophage_information.tsv
        16 | prophage.tsv
        32 | GFF3 format of the prophages
        64 | prophage.tbl
        128 | test data used in the random forest
        256 | GFF3 format of the genomes
    As explained in the README.
    """

    oc = self.output_choice

    if oc >= 256:
        # write the genomic GFF3 format
        genome_gff3(self)
        oc -= 256
    if oc >= 128:
        # write the calculated data
        write_test_data(self)
        oc -= 128
    if oc >= 64:
        # write the prophage location table
        write_prophage_tbl(self)
        oc -= 64
    if oc >= 32:
        # write the prophage in GFF3 format
        write_gff3(self)
        oc -= 32
    if oc >= 16:
        # write a tsv file of this data
        write_prophage_tsv(self)
        oc -= 16
    if oc >= 8:
        # write prophage_information.tsv
        write_prophage_information(self)
        oc -= 8
    if oc >= 4:
        # separate out the bacteria and phage as fasta files
        write_phage_and_bact(self)
        oc -= 4
    if oc >= 2:
        # update input GenBank file and incorporate prophage regions
        write_genbank(self)
        oc -= 2
    if oc >= 1:
        # print the prophage coordinates:
        write_prophage_coordinates(self)


text:
<?php
/**
 * @Author: Leandro Henrique Reis <emtudo@gmail.com>
 * @Date:   2016-03-30 09:02:31
 * @Last Modified by:   Leandro Henrique Reis
 * @Last Modified time: 2016-06-04 19:50:26
 */
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreatePasswordResetsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('password_resets', function (Blueprint $table) {
            $table->string('email')->index();
            $table->string('token')->index();
            $table->timestamp('created_at');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('password_resets');
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Parerga lichenol. (Breslau) 339 (1863)

#### Original name
Polyblastia guestphalica J. Lahm ex Körb.

### Remarks
null


text:
<?php

namespace Frontend\Modules\Search\Ajax;

use Symfony\Component\Filesystem\Filesystem;

use Frontend\Core\Engine\Base\AjaxAction as FrontendBaseAJAXAction;
use Frontend\Core\Engine\Language as FL;
use Frontend\Core\Engine\Model as FrontendModel;
use Frontend\Core\Engine\Navigation as FrontendNavigation;
use Frontend\Modules\Search\Engine\Model as FrontendSearchModel;

/**
 * This is the auto suggest-action, it will output a list of results for a certain search
 *
 * @author Matthias Mullie <forkcms@mullie.eu>
 */
class Autosuggest extends FrontendBaseAJAXAction
{
    /**
     * Name of the cache file
     *
     * @var    string
     */
    private $cacheFile;

    /**
     * The items
     *
     * @var    array
     */
    private $items;

    /**
     * Limit of data to fetch
     *
     * @var    int
     */
    private $limit;

    /**
     * Offset of data to fetch
     *
     * @var    int
     */
    private $offset;

    /**
     * The pagination array
     * It will hold all needed parameters, some of them need initialization.
     *
     * @var    array
     */
    protected $pagination = array(
        'limit' => 20,
        'offset' => 0,
        'requested_page' => 1,
        'num_items' => null,
        'num_pages' => null
    );

    /**
     * The requested page
     *
     * @var    int
     */
    private $requestedPage;

    /**
     * The search term
     *
     * @var string
     */
    private $term = '';

    /**
     * Display
     */
    private function display()
    {
        // set variables
        $this->requestedPage = 1;
        $this->limit = (int) FrontendModel::getModuleSetting('Search', 'autosuggest_num_items', 10);
        $this->offset = ($this->requestedPage * $this->limit) - $this->limit;
        $this->cacheFile = FRONTEND_CACHE_PATH . '/' . $this->getModule() . '/' .
                           FRONTEND_LANGUAGE . '_' . md5($this->term) . '_' .
                           $this->offset . '_' . $this->limit . '.php';

        // load the cached data
        if (!$this->getCachedData()) {
            // ... or load the real data
            $this->getRealData();
        }

        // parse
        $this->parse();
    }

    /**
     * Execute the action
     */
    public function execute()
    {
        parent::execute();
        $this->validateForm();
        $this->display();
    }

    /**
     * Load the cached data
     *
     * @return bool
     */
    private function getCachedData()
    {
        // no search term = no search
        if (!$this->term) {
            return false;
        }

        // debug mode = no cache
        if (SPOON_DEBUG) {
            return false;
        }

        // check if cache file exists
        if (!is_file($this->cacheFile)) {
            return false;
        }

        // get cache file modification time
        $cacheInfo = @filemtime($this->cacheFile);

        // check if cache file is recent enough (1 hour)
        if (!$cacheInfo || $cacheInfo < strtotime('-1 hour')) {
            return false;
        }

        // include cache file
        require_once $this->cacheFile;

        // set info
        $this->pagination = $pagination;
        $this->items = $items;

        return true;
    }

    /**
     * Load the data
     */
    private function getRealData()
    {
        // no search term = no search
        if (!$this->term) {
            return;
        }

        // set url
        $this->pagination['url'] = FrontendNavigation::getURLForBlock('Search') . '?form=search&q=' . $this->term;
        $this->pagination['limit'] = FrontendModel::getModuleSetting('Search', 'overview_num_items', 20);

        // populate calculated fields in pagination
        $this->pagination['requested_page'] = $this->requestedPage;
        $this->pagination['offset'] = ($this->pagination['requested_page'] * $this->pagination['limit']) - $this->pagination['limit'];

        // get items
        $this->items = FrontendSearchModel::search(
            $this->term,
            $this->pagination['limit'],
            $this->pagination['offset']
        );

        // populate count fields in pagination
        // this is done after actual search because some items might be
        // activated/deactivated (getTotal only does rough checking)
        $this->pagination['num_items'] = FrontendSearchModel::getTotal($this->term);
        $this->pagination['num_pages'] = (int) ceil($this->pagination['num_items'] / $this->pagination['limit']);

        // num pages is always equal to at least 1
        if ($this->pagination['num_pages'] == 0) {
            $this->pagination['num_pages'] = 1;
        }

        // redirect if the request page doesn't exist
        if ($this->requestedPage > $this->pagination['num_pages'] || $this->requestedPage < 1) {
            $this->redirect(
                FrontendNavigation::getURL(404)
            );
        }

        // debug mode = no cache
        if (!SPOON_DEBUG) {
            // set cache content
            $fs = new Filesystem();
            $fs->dumpFile(
                $this->cacheFile,
                "<?php\n" . '$pagination = ' . var_export($this->pagination, true) . ";\n" . '$items = ' . var_export(
                    $this->items,
                    true
                ) . ";\n?>"
            );
        }
    }

    public function parse()
    {
        // more matches to be found than?
        if ($this->pagination['num_items'] > count($this->items)) {
            // remove last result (to add this reference)
            array_pop($this->items);

            // add reference to full search results page
            $this->items[] = array(
                'title' => FL::lbl('More'),
                'text' => FL::msg('MoreResults'),
                'full_url' => FrontendNavigation::getURLForBlock('Search') . '?form=search&q=' . $this->term
            );
        }

        // format data
        foreach ($this->items as &$item) {
            // format description
            $item['text'] = !empty($item['text']) ? (mb_strlen($item['text']) > $this->length ? mb_substr(strip_tags($item['text']), 0, $this->length, SPOON_CHARSET) . '…' : $item['text']) : '';
        }

        // output
        $this->output(self::OK, $this->items);
    }

    /**
     * Validate the form
     */
    private function validateForm()
    {
        // set values
        $searchTerm = \SpoonFilter::getPostValue('term', null, '');
        $this->term = (SPOON_CHARSET == 'utf-8') ? \SpoonFilter::htmlspecialchars(
            $searchTerm
        ) : \SpoonFilter::htmlentities($searchTerm);
        $this->length = (int) \SpoonFilter::getPostValue('length', null, 50);

        // validate
        if ($this->term == '') {
            $this->output(self::BAD_REQUEST, null, 'term-parameter is missing.');
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/settings_button_pressed" />
    <item android:drawable="@drawable/settings_button_normal" />
</selector>


text:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TestSchema = new Schema({
    type: {type: String, default:"test"},
    date: {type: Date, default: Date.now},
    normal: String,
    attack: String,
    status: String,
    engine: String,
    model: String,
    windowSize: String,
    step: String,
    threshold: String,
    trainModelId: String,
    batchSize: Number,
    accurary: Number,
    auc: Number,
    score: Number

});
//model's method: find findByld findOne where
var Test = mongoose.model('Test', TestSchema);
module.exports = {
    Test: Test
};


text:
<?php

declare(strict_types=1);

namespace hipanel\modules\finance\grid;

use hipanel\grid\BoxedGridView;
use hipanel\grid\DataColumn;
use hipanel\modules\client\grid\ClientColumn;
use hipanel\modules\finance\helpers\ConsumptionConfigurator;
use hipanel\modules\finance\helpers\ResourceHelper;
use hipanel\modules\finance\models\Consumption;
use Yii;
use yii\db\ActiveRecordInterface;
use yii\helpers\Html;

class ConsumptionGridView extends BoxedGridView
{
    public ConsumptionConfigurator $configurator;

    public $resizableColumns = false;

    public function init()
    {
        $this->columns = $this->getColumns();
        parent::init();
    }

    public function getColumns(): array
    {
        $columns = [];
        $columns['object'] = [
            'format' => 'raw',
            'attribute' => 'name',
            'label' => Yii::t('hipanel', 'Object'),
            'contentOptions' => ['style' => 'display: flex; flex-direction: row; justify-content: space-between; flex-wrap: nowrap;'],
            'footerOptions' => ['colspan' => Yii::$app->user->can('access-subclients') ? 2 : 1, 'rowspan' => 2],
            'value' => function (ActiveRecordInterface $model): string {
                $objectLabel = Html::tag('span', '-', ['class' => 'text-danger']);
                if ($model->name) {
                    $objectLabel = Html::tag('span', Html::encode($model->name) ?: ' ', ['class' => 'text-bold']);
                }

                return $objectLabel . Html::a(Yii::t('hipanel', 'Detail view'), ['view', 'id' => $model->id], ['class' => 'btn btn-default btn-xs']);
            },
        ];
        foreach ($this->filterModel->getColumnsWithLabels() as $type => $label) {
            $columns[$type] = [
                'attribute' => $type,
                'label' => $label,
                'enableSorting' => true,
                'filter' => false,
                'format' => 'raw',
                'headerOptions' => ['class' => 'text-right'],
                'contentOptions' => ['class' => 'text-right', 'data-type' => $type, 'style' => 'white-space:nowrap;'],
                'value' => function (Consumption $consumption) use ($type) {
                    $resources = array_filter($consumption->resources, static fn($resource) => $resource->type === $type);
                    if (!empty($resources)) {
                        $unit = reset($resources)->buildResourceModel()->decorator()->displayUnit();

                        return sprintf("%s %s", $this->summarize($resources), $unit);
                    }
                },
                'footer' => 'test_footer',
                'footerOptions' => ['class' => $type . ' text-right', 'data-type' => true, 'style' => 'white-space: nowrap;'],
            ];
        }

        return $columns;
    }

    private function summarize(array $resources): string
    {
        return ResourceHelper::summarize($resources);
    }
}


text:
'use strict';

const express = require('express');
const app = express();
const hbs = require('express-handlebars');

//Aqui van configuradas las rutas, el view engine, los headers

app.engine('.hbs', hbs({
    defaultLayout: 'default',
    extname: '.hbs'
}));

app.use(express.static('views/images'));

app.set('view engine', '.hbs');

app.get('/', function(req, res){
    res.render('juego')
});

module.exports = app;


text:
using System;
using SharpDX;
using System.Collections.Generic;
using System.Linq;

#if !NETFX_CORE
namespace HelixToolkit.Wpf.SharpDX
#else
#if CORE
namespace HelixToolkit.SharpDX.Core
#else
namespace HelixToolkit.UWP
#endif
#endif
{
    namespace Model.Scene
    {
        using Core;
        using Animations;

        /// <summary>
        ///
        /// </summary>
        public class BoneSkinMeshNode : MeshNode, Animations.IBoneMatricesNode
        {
            /// <summary>
            /// Gets or sets the bone matrices.
            /// </summary>
            /// <value>
            /// The bone matrices.
            /// </value>
            public Matrix[] BoneMatrices
            {
                set
                {
                    (RenderCore as BoneSkinRenderCore).BoneMatrices = value;
                }
                get
                {
                    return (RenderCore as BoneSkinRenderCore).BoneMatrices;
                }
            }

            public float[] MorphTargetWeights
            {
                get
                {
                    return (RenderCore as BoneSkinRenderCore).MorphTargetWeights;
                }
                set
                {
                    (RenderCore as BoneSkinRenderCore).MorphTargetWeights = value;
                }
            }

            /// <summary>
            /// Gets or sets the bones.
            /// </summary>
            /// <value>
            /// The bones.
            /// </value>
            public Animations.Bone[] Bones
            {
                set; get;
            }
            /// <summary>
            /// Gets or sets a value indicating whether this node is used to show skeleton. Only used as an indication.
            /// </summary>
            /// <value>
            ///   <c>true</c> if this node is used to show skeleton; otherwise, <c>false</c>.
            /// </value>
            public bool IsSkeletonNode
            {
                set; get;
            }
            /// <summary>
            /// Gets or sets a value indicating whether this node has bone group.
            /// <see cref="BoneGroupNode"/> shares bones with multiple <see cref="BoneSkinMeshNode"/>
            /// </summary>
            /// <value>
            ///   <c>true</c> if this instance has bone group; otherwise, <c>false</c>.
            /// </value>
            public bool HasBoneGroup
            {
                internal set; get;
            }

            private Vector3[] skinnedVerticesCache = new Vector3[0];
            /// <summary>
            /// Called when [create render core].
            /// </summary>
            /// <returns></returns>
            protected override RenderCore OnCreateRenderCore()
            {
                return new BoneSkinRenderCore();
            }

            protected override IAttachableBufferModel OnCreateBufferModel(Guid modelGuid, Geometry3D geometry)
            {
                return !(EffectsManager.GeometryBufferManager.Register<BoneSkinnedMeshBufferModel>(modelGuid, geometry) is IBoneSkinMeshBufferModel buffer) ?
                    EmptyGeometryBufferModel.Empty : new BoneSkinPreComputeBufferModel(buffer, buffer.VertexStructSize.FirstOrDefault()) as IAttachableBufferModel;
            }

            public override bool TestViewFrustum(ref BoundingFrustum viewFrustum)
            {
                return BoneMatrices.Length == 0 ? base.TestViewFrustum(ref viewFrustum) : true;
            }

            protected override bool PreHitTestOnBounds(HitTestContext context)
            {
                return BoneMatrices.Length == 0 ? base.PreHitTestOnBounds(context) : true;
            }
            /// <summary>
            /// Creates the skeleton node.
            /// </summary>
            /// <param name="material">The material.</param>
            /// <param name="effectName">Name of the effect.</param>
            /// <param name="scale">The scale.</param>
            /// <returns></returns>
            public BoneSkinMeshNode CreateSkeletonNode(MaterialCore material, string effectName, float scale = 0.1f)
            {
                return CreateSkeletonNode(this, material, effectName, scale);
            }
            /// <summary>
            /// Creates the skeleton node.
            /// </summary>
            /// <param name="node">The node.</param>
            /// <param name="material">The material.</param>
            /// <param name="effectName">Name of the effect.</param>
            /// <param name="scale">The scale.</param>
            /// <returns></returns>
            public static BoneSkinMeshNode CreateSkeletonNode(BoneSkinMeshNode node, MaterialCore material, string effectName, float scale)
            {
                var skNode = new BoneSkinMeshNode()
                {
                    Material = material,
                    IsSkeletonNode = true,
                };
                skNode.Geometry = BoneSkinnedMeshGeometry3D.CreateSkeletonMesh(node.Bones, scale);
                skNode.PostEffects = effectName;
                skNode.Bones = node.Bones;
                return skNode;
            }
            /// <summary>
            /// Try to get skinned vertices. Skinned vertices are copied from GPU.
            /// </summary>
            /// <param name="manager"></param>
            /// <returns>New array with vertex positions</returns>
            public Vector3[] TryGetSkinnedVertices(IEffectsManager manager)
            {
                if (Geometry is BoneSkinnedMeshGeometry3D skGeometry)
                {
                    if (RenderCore is BoneSkinRenderCore skCore)
                    {
#if DX11_1
                        var proxy = new Render.DeviceContextProxy(manager.Device.ImmediateContext1, manager.Device);
#else
                        var proxy = new Render.DeviceContextProxy(manager.Device.ImmediateContext, manager.Device);
#endif
                        var array = new Vector3[skGeometry.Positions.Count];
                        if (skCore.CopySkinnedToArray(proxy, array) > 0)
                        {
                            return array;
                        }
                    }
                }
                return null;
            }
            /// <summary>
            /// Try to get skinned vertices. Skinned vertices are copied from GPU.
            /// </summary>
            /// <param name="manager"></param>
            /// <param name="array">Vertex positions will be copied into this array</param>
            /// <returns></returns>
            public int TryGetSkinnedVertices(IEffectsManager manager, Vector3[] array)
            {
                if (Geometry is BoneSkinnedMeshGeometry3D skGeometry)
                {
                    if (RenderCore is BoneSkinRenderCore skCore)
                    {
#if DX11_1
                        var proxy = new Render.DeviceContextProxy(manager.Device.ImmediateContext1, manager.Device);
#else
                        var proxy = new Render.DeviceContextProxy(manager.Device.ImmediateContext, manager.Device);
#endif
                        return skCore.CopySkinnedToArray(proxy, array);
                    }
                }
                return 0;
            }
            /// <summary>
            /// Get the skinned vertices cache used for hit test.
            /// This cache will only be updated after each hit test.
            /// To get latest skinned vertices, please use <see cref="TryGetSkinnedVertices(IEffectsManager)"/>.
            /// </summary>
            /// <returns></returns>
            public Vector3[] TryGetSkinnedVerticesCache()
            {
                return skinnedVerticesCache;
            }

            /// <summary>
            /// Make sure to use SetWeight so that the mutation of elements can be seen
            /// </summary>
            /// <param name="i">index</param>
            /// <param name="w">weight, typically 0-1</param>
            public void SetWeight(int i, float w)
            {
                (RenderCore as BoneSkinRenderCore).SetWeight(i, w);
            }

            /// <summary>
            /// Tells the render core to update it's morph target weight buffer
            /// </summary>
            public void WeightUpdated()
            {
                (RenderCore as BoneSkinRenderCore).SetWeight(0, MorphTargetWeights[0]);
                InvalidateRender();
            }

            public void SetupIdentitySkeleton()
            {
                BoneMatrices = new Matrix[] { Matrix.Identity };
                Bones = new Bone[] { new Bone() { Name = "Identity", BindPose = Matrix.Identity, InvBindPose = Matrix.Identity, BoneLocalTransform = Matrix.Identity } };

                var geom = Geometry as BoneSkinnedMeshGeometry3D;
                geom.VertexBoneIds = new BoneIds[geom.Positions.Count];
                for (var i = 0; i < geom.VertexBoneIds.Count; i++)
                    geom.VertexBoneIds[i] = new BoneIds() { Bone1 = 0, Weights = new Vector4(1, 0, 0, 0) };
            }

            public void UpdateBoneMatrices()
            {
                BoneMatrices = new Matrix[Bones.Length];
                BoneMatrices = BoneMatrices.Select((m, i) => Bones[i].Node.TotalModelMatrixInternal).ToArray();
            }

            public void InvalidateBoneMatrices()
            {
                (RenderCore as BoneSkinRenderCore).InvalidateBoneMatrices();
            }

            public void InvalidateMorphTargetWeights()
            {
                (RenderCore as BoneSkinRenderCore).InvalidateMorphTargetWeights();
            }

            public bool InitializeMorphTargets(MorphTargetVertex[] mtv, int pitch)
                => (RenderCore as BoneSkinRenderCore).InitializeMorphTargets(mtv, pitch);

            protected override bool OnHitTest(HitTestContext context, Matrix totalModelMatrix, ref List<HitTestResult> hits)
            {
                if (BoneMatrices.Length > 0 && Geometry is BoneSkinnedMeshGeometry3D skGeometry)
                {
                    if (RenderCore is BoneSkinRenderCore skCore)
                    {
                        if (skinnedVerticesCache.Length < skGeometry.Positions.Count)
                        {
                            skinnedVerticesCache = new Vector3[skGeometry.Positions.Count];
                        }
                        if (skCore.CopySkinnedToArray(context.RenderMatrices.RenderHost.ImmediateDeviceContext, skinnedVerticesCache) > 0)
                        {
                            return skGeometry.HitTestWithSkinnedVertices(context, skinnedVerticesCache,
                                totalModelMatrix, ref hits, WrapperSource);
                        }
                    }
                }
                return base.OnHitTest(context, totalModelMatrix, ref hits);
            }
        }
    }
}


text:
// This file is automatically generated.

package adila.db;

/*
 * Huawei M2
 *
 * DEVICE: HWMozart
 * MODEL: HUAWEI M2-803L
 */
final class hwmozart_huawei20m22d803l {
    public static final String DATA = "Huawei|M2|";
}


text:
'use strict';

module.exports = {
  database: 'gameofdrones',
  routing: {
    apiBaseUrl: '/api',
    staticPath: '../build/'
  }
};


text:
<?php

trait SchemaBuilder
{
    /**
     * @var \Illuminate\Database\Schema\Builder
     */
    protected $schema;

    /**
     * @var \Illuminate\Database\Connection
     */
    protected $db;

    public function __construct()
    {
        $this->db = app('db');
        $this->schema = $this->db->getSchemaBuilder();
    }
}