text:
"use strict";

$(function () {
  function n() {
    var n = function () {
      try {
        return document.createEvent("TouchEvent"), !0;
      } catch (n) {
        return !1;
      }
    }(),
        t = $.fn.on;$.fn.on = function () {
      if (/click/.test(arguments[0]) && "function" == typeof arguments[1] && n) {
        var e,
            i = arguments[1];t.apply(this, ["touchstart", function (n) {
          e = n.changedTouches[0].clientY;
        }]), t.apply(this, ["touchend", function (n) {
          Math.abs(n.changedTouches[0].clientY - e) > 10 || (n.preventDefault(), i.apply(this, [n]));
        }]);
      } else t.apply(this, arguments);return this;
    };
  }function t() {
    $(window).on("load", function () {
      for (var n = ["./images/layers/content.png", "./images/layers/navigation.png", "./images/layers/popout.png", "./images/layers/transparent.gif"], t = 0, e = n.length; t < e; ++t) {
        new Image().src = n[t];
      }
    });
  }function e() {
    /Android/gi.test(navigator.userAgent) && window.addEventListener("resize", function () {
      "INPUT" != document.activeElement.tagName && "TEXTAREA" != document.activeElement.tagName || window.setTimeout(function () {
        document.activeElement.scrollIntoViewIfNeeded();
      }, 0);
    });
  }function i() {
    var n = { title: "WeUI, 为微信 Web 服务量身设计", desc: "WeUI, 为微信 Web 服务量身设计", link: "https://weui.io", imgUrl: "https://mmbiz.qpic.cn/mmemoticon/ajNVdqHZLLA16apETUPXh9Q5GLpSic7lGuiaic0jqMt4UY8P4KHSBpEWgM7uMlbxxnVR7596b3NPjUfwg7cFbfCtA/0" };$.getJSON("https://weui.io/api/sign?url=" + encodeURIComponent(location.href.split("#")[0]), function (t) {
      wx.config({ beta: !0, debug: !1, appId: t.appid, timestamp: t.timestamp, nonceStr: t.nonceStr, signature: t.signature, jsApiList: ["onMenuShareTimeline", "onMenuShareAppMessage", "onMenuShareQQ", "onMenuShareWeibo", "onMenuShareQZone", "setBounceBackground"] }), wx.ready(function () {
        wx.invoke("setBounceBackground", { backgroundColor: "#F8F8F8", footerBounceColor: "#F8F8F8" }), wx.onMenuShareTimeline(n), wx.onMenuShareQQ(n), wx.onMenuShareAppMessage({ title: "WeUI", desc: "为微信 Web 服务量身设计", link: location.href, imgUrl: "https://mmbiz.qpic.cn/mmemoticon/ajNVdqHZLLA16apETUPXh9Q5GLpSic7lGuiaic0jqMt4UY8P4KHSBpEWgM7uMlbxxnVR7596b3NPjUfwg7cFbfCtA/0" });
      });
    });
  }function a() {
    for (var n = {}, t = $('script[type="text/html"]'), e = $(window).height(), i = 0, a = t.length; i < a; ++i) {
      var o = t[i],
          c = o.id.replace(/tpl_/, "");n[c] = { name: c, url: "#" + c, template: "#" + o.id };
    }n.home.url = "#";for (var r in n) {
      s.push(n[r]);
    }s.setPageAppend(function (n) {
      var t = n.find(".page__ft");t.length < 1 || (t.position().top + t.height() < e ? t.addClass("j_bottom") : t.removeClass("j_bottom"));
    }).setDefault("home").init();
  }function o() {
    t(), n(), e(), i(), a(), window.pageManager = s, window.home = function () {
      location.hash = "";
    };
  }var s = { $container: $("#container"), _pageStack: [], _configs: [], _pageAppend: function _pageAppend() {}, _defaultPage: null, _pageIndex: 1, setDefault: function setDefault(n) {
      return this._defaultPage = this._find("name", n), this;
    }, setPageAppend: function setPageAppend(n) {
      return this._pageAppend = n, this;
    }, init: function init() {
      var n = this;$(window).on("hashchange", function () {
        var t = history.state || {},
            e = 0 === location.hash.indexOf("#") ? location.hash : "#",
            i = n._find("url", e) || n._defaultPage;t._pageIndex <= n._pageIndex || n._findInStack(e) ? n._back(i) : n._go(i);
      }), history.state && history.state._pageIndex && (this._pageIndex = history.state._pageIndex), this._pageIndex--;var t = 0 === location.hash.indexOf("#") ? location.hash : "#",
          e = n._find("url", t) || n._defaultPage;return this._go(e), this;
    }, push: function push(n) {
      return this._configs.push(n), this;
    }, go: function go(n) {
      var t = this._find("name", n);t && (location.hash = t.url);
    }, _go: function _go(n) {
      this._pageIndex++, history.replaceState && history.replaceState({ _pageIndex: this._pageIndex }, "", location.href);var t = $(n.template).html(),
          e = $(t).addClass("slideIn").addClass(n.name);return e.on("animationend webkitAnimationEnd", function () {
        e.removeClass("slideIn").addClass("js_show");
      }), this.$container.append(e), this._pageAppend.call(this, e), this._pageStack.push({ config: n, dom: e }), n.isBind || this._bind(n), this;
    }, back: function back() {
      history.back();
    }, _back: function _back(n) {
      this._pageIndex--;var t = this._pageStack.pop();if (t) {
        var e = 0 === location.hash.indexOf("#") ? location.hash : "#",
            i = this._findInStack(e);if (!i) {
          var a = $(n.template).html(),
              o = $(a).addClass("js_show").addClass(n.name);o.insertBefore(t.dom), n.isBind || this._bind(n), this._pageStack.push({ config: n, dom: o });
        }return t.dom.addClass("slideOut").on("animationend webkitAnimationEnd", function () {
          t.dom.remove();
        }), this;
      }
    }, _findInStack: function _findInStack(n) {
      for (var t = null, e = 0, i = this._pageStack.length; e < i; e++) {
        var a = this._pageStack[e];if (a.config.url === n) {
          t = a;break;
        }
      }return t;
    }, _find: function _find(n, t) {
      for (var e = null, i = 0, a = this._configs.length; i < a; i++) {
        if (this._configs[i][n] === t) {
          e = this._configs[i];break;
        }
      }return e;
    }, _bind: function _bind(n) {
      var t = n.events || {};for (var e in t) {
        for (var i in t[e]) {
          this.$container.on(i, e, t[e][i]);
        }
      }n.isBind = !0;
    } };o();
});

//# sourceMappingURL=page-compiled.js.map

//# sourceMappingURL=page-compiled-compiled.js.map


text:
package pcommon

import (
	"go.opentelemetry.io/collector/pdata/internal"
	otlpresource "go.opentelemetry.io/collector/pdata/internal/data/protogen/resource/v1"
)

// Resource is a message representing the resource information.
//
// This is a reference type, if passed by value and callee modifies it the
// caller will see the modification.
//
// Must use NewResource function to create new instances.
// Important: zero-initialized instance is not valid for use.

type Resource internal.Resource

func newResource(orig *otlpresource.Resource) Resource {
	return Resource(internal.NewResource(orig))
}

func (ms Resource) getOrig() *otlpresource.Resource {
	return internal.GetOrigResource(internal.Resource(ms))
}

// NewResource creates a new empty Resource.
//
// This must be used only in testing code. Users should use "AppendEmpty" when part of a Slice,
// OR directly access the member if this is embedded in another struct.
func NewResource() Resource {
	return newResource(&otlpresource.Resource{})
}

// MoveTo moves all properties from the current struct overriding the destination and
// resetting the current instance to its zero value
func (ms Resource) MoveTo(dest Resource) {
	*dest.getOrig() = *ms.getOrig()
	*ms.getOrig() = otlpresource.Resource{}
}

// Attributes returns the Attributes associated with this Resource.
func (ms Resource) Attributes() Map {
	return Map(internal.NewMap(&ms.getOrig().Attributes))
}

// DroppedAttributesCount returns the droppedattributescount associated with this Resource.
func (ms Resource) DroppedAttributesCount() uint32 {
	return ms.getOrig().DroppedAttributesCount
}

// SetDroppedAttributesCount replaces the droppedattributescount associated with this Resource.
func (ms Resource) SetDroppedAttributesCount(v uint32) {
	ms.getOrig().DroppedAttributesCount = v
}

// CopyTo copies all properties from the current struct overriding the destination.
func (ms Resource) CopyTo(dest Resource) {
	ms.Attributes().CopyTo(dest.Attributes())
	dest.SetDroppedAttributesCount(ms.DroppedAttributesCount())
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package d88.core.object;

import d88.core.common.D88Constants;
import d88.core.common.D88SCommon;
import d88.core.common.D88SGzip;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashMap;
import java.util.zip.DataFormatException;
import org.json.JSONArray;
import org.json.JSONObject;
import d88.core.common.D88Constants.OBJTYPE;
import d88.core.common.D88Constants.OBJFORM;

/**
 *
 * @author dung.nt
 */

//                 DATA SEND AND RECEIVE
//                 +---------+--------+----------+----------+------------+
//                 |  TYPE   | DEVICE |   APPID  |   VER    |    DATA    |
//                 +---------+--------+----------+----------+------------+
//                 |    2    |   2    |    12    |    8     |   x - 24   | bit
//                 +---------+--------+----------+----------+------------+

//                 +----------+-------------------------------------------+
//                 |   TYPE   |                DESCRIPTION                |
//                 +----------+-------------------------------------------+
//                 |    0     | user                                      |
//                 +----------+-------------------------------------------+
//                 |    1     | request                                   |
//                 +----------+-------------------------------------------+
//                 |    2     | Chat                                      |
//                 +----------+-------------------------------------------+
//                 |    3     | OTHER                                     |
//                 +----------+-------------------------------------------+
//                 |  DEVICE  | Mã ngôn ngữ tạo ra model này              |
//                 +----------+-------------------------------------------+
//                 |    0     |   Create by Server                        |
//                 +----------+-------------------------------------------+
//                 |    1     |   JAVA                                    |
//                 +----------+-------------------------------------------+
//                 |    2     |   SWIFT , OBJECTIVE C                     |
//                 +----------+-------------------------------------------+
//                 |    3     |   .NET                                    |
//                 +----------+-------------------------------------------+
//                 +----------+-------------------------------------------+
//                 |  APPID   | ID Của App Giao Tiếp Với Server           |
//                 +----------+-------------------------------------------+
//                 |   VER    | VER Của OBJ để quản lý hàm theo version   |
//                 +----------+-------------------------------------------+
//                 |   DATA   | Quản lý dữ liệu của obj theo gzip         |
//                 +----------+-------------------------------------------+
//                 DATA OF OBJECT
//                 +------------------+------------------------------------------------------------------------------+
//                 |       BOOL       | Boolean value                                      |            o_           |
//                 +------------------+------------------------------------------------------------------------------+
//                 |    ARRAY BOOL    | Array Boolean value                                |            o_           |
//                 +------------------+------------------------------------------------------------------------------+
//                 |      DOUBLE      | Double  value                                      |            d_           |
//                 +------------------+------------------------------------------------------------------------------+
//                 |   ARRAY DOUBLE   | Array Double value                                 |            d_           |
//                 +------------------+------------------------------------------------------------------------------+
//                 |      STRING      | String  value                                      |            s_           |
//                 +------------------+------------------------------------------------------------------------------+
//                 |   ARRAY STRING   | Array String value                                 |            s_           |
//                 +------------------+------------------------------------------------------------------------------+
//                 |     Interger     | int  value                                         |            i_           |
//                 +------------------+------------------------------------------------------------------------------+
//                 |   ARRAY Interer  | Array Interger value                               |            i_           |
//                 +------------------+------------------------------------------------------------------------------+

public class D88SObject {

    private String cmd = null;
    private OBJTYPE objType = OBJTYPE.USER;
    private OBJFORM objForm = OBJFORM.SERVER; // SERVER CREATE
    private int objAppID = 0;
    private int objVer = 1;

    private HashMap<String, Object> properties = null;

    // CONSTRUCTOR

    public D88SObject(String _cmd) { // init default with CMD
        this.cmd = _cmd;
        if (this.properties == null) {
            this.properties = new HashMap<>();
            this.properties.put(D88Constants.CMD_STRING, _cmd);
        }
    }

    public D88SObject(OBJTYPE _objType,int _objAppID,int _objVer,String _cmd) {
        this.cmd = _cmd;
        this.objType = _objType;
        this.objAppID = _objAppID;
        this.objVer = _objVer;

        if (this.properties == null) {
            this.properties = new HashMap<>();
            this.properties.put(D88Constants.CMD_STRING, _cmd);
        }
    }

    public D88SObject(byte[] d88Message) throws IOException, DataFormatException, Exception {
        if (this.properties == null) {
            this.properties = new HashMap<>();
        }
        // kiểm tra xem message có hơp lệ không > 3  byte
        if (d88Message.length >= 3) {
            // lấy ra 3 byte cuối để xác định info
            // những file còn lại là file rawdata cần unzip
            byte[] dataInfo = Arrays.copyOfRange(d88Message, d88Message.length - 3, d88Message.length);
            this.onRetoreInfo(dataInfo);
            byte[] rawData = Arrays.copyOfRange(d88Message, 0, d88Message.length - 3);
            String d88Decompress = D88SGzip.d88Decompress(rawData);
            JSONObject jsonModel = new JSONObject(d88Decompress);
            this.properties = this.toHashMap(jsonModel);
        }
    }

    private void onRetoreInfo(byte[] info){
        String toBinary = D88SCommon.toBinary(info);
        int inttype = Integer.parseInt(toBinary.substring(toBinary.length() - 2, toBinary.length()), 2);
        if(inttype == 0){
            this.objType = OBJTYPE.USER;
        }else if(inttype == 1){
            this.objType = OBJTYPE.REQUEST;
        }
        else if(inttype == 2){
            this.objType = OBJTYPE.CHAT;
        }
        else if(inttype == 3){
            this.objType = OBJTYPE.OTHER;
        }

        int objFormINT = Integer.parseInt(toBinary.substring(toBinary.length() - 4, toBinary.length() - 2), 2);
        if(objFormINT == 0){
            this.objForm = OBJFORM.SERVER;
        }else if(objFormINT == 1){
            this.objForm = OBJFORM.IOS;
        }
        else if(objFormINT == 2){
            this.objForm = OBJFORM.JAVA;
        }
        else if(objFormINT == 3){
            this.objForm = OBJFORM.OTHER;
        }
        this.objAppID = Integer.parseInt(toBinary.substring(toBinary.length() - 16, toBinary.length() - 4), 2);
        this.objVer = Integer.parseInt(toBinary.substring(toBinary.length() - 24, toBinary.length() - 16), 2);
    }
    private HashMap<String, Object> toHashMap(JSONObject json) {
        HashMap<String, Object> maptemp = new HashMap<>();

        for (String key : json.keySet()) {
            if (key.startsWith(D88Constants.prefix_String)) {
                if (json.get(key) instanceof JSONArray) {
                    JSONArray jsonArray = json.getJSONArray(key);
                    String[] list = new String[jsonArray.length()];
                    for (int i = 0; i < jsonArray.length(); i++) {
                        list[i] = jsonArray.getString(i);
                    }
                    maptemp.put(key, list);
                } else {
                    maptemp.put(key, json.getString(key));
                }
            } else if (key.startsWith(D88Constants.prefix_Integer)) {
                if (json.get(key) instanceof JSONArray) {
                    JSONArray jsonArray = json.getJSONArray(key);
                    int[] list = new int[jsonArray.length()];
                    for (int i = 0; i < jsonArray.length(); i++) {
                        list[i] = jsonArray.getInt(i);

                    }
                    maptemp.put(key, list);
                } else {
                    maptemp.put(key, json.getInt(key));
                }
            } else if (key.startsWith(D88Constants.prefix_Double)) {
                if (json.get(key) instanceof JSONArray) {
                    JSONArray jsonArray = json.getJSONArray(key);
                    double[] list = new double[jsonArray.length()];
                    for (int i = 0; i < jsonArray.length(); i++) {
                        list[i] = jsonArray.getDouble(i);
                    }
                    maptemp.put(key, list);
                } else {
                    maptemp.put(key, json.getDouble(key));
                }
            } else if (key.startsWith(D88Constants.prefix_Boolean)) {
                if (json.get(key) instanceof JSONArray) {
                    JSONArray jsonArray = json.getJSONArray(key);
                    boolean[] list = new boolean[jsonArray.length()];
                    for (int i = 0; i < jsonArray.length(); i++) {
                        list[i] = jsonArray.getBoolean(i);
                    }
                    maptemp.put(key, list);
                } else {
                    maptemp.put(key, json.getBoolean(key));
                }
            } else if (D88Constants.CMD_STRING.equals(key)) {
                maptemp.put(key, json.getString(key));
                this.cmd = json.getString(key);
            }

        }
        return maptemp;
    }

    private byte[] onCreateObjectInfo() {
        String objTypeString = String.format("%2s", Integer.toBinaryString(this.objType.getValue())).replace(' ', '0');
        String objFormString = String.format("%2s", Integer.toBinaryString(this.objForm.getValue())).replace(' ', '0');
        String objAppIDString = String.format("%12s", Integer.toBinaryString(this.objAppID)).replace(' ', '0');
        String objVerString = String.format("%8s", Integer.toBinaryString(this.objVer)).replace(' ', '0');
        String info = objVerString + objAppIDString + objFormString + objTypeString;
        return new BigInteger(info, 2).toByteArray();
    }

    public byte[] getMessage() throws Exception {
        JSONObject jsonOBJ = new JSONObject(this.properties);
        byte[] zip = D88SGzip.d88Compress(jsonOBJ.toString());
        return D88SCommon.concatenateByteArrays(zip, onCreateObjectInfo());
    }

    // OBJECT ACTION
    public boolean containsKey(String key) {
        if (this.properties.containsKey(D88Constants.prefix_String + key)) {
            return true;
        } else if (this.properties.containsKey(D88Constants.prefix_Integer + key)) {
            return true;
        } else if (this.properties.containsKey(D88Constants.prefix_Double + key)) {
            return true;
        } else {
            return this.properties.containsKey(D88Constants.prefix_Boolean + key);
        }
    }

    public String[] getKeys() {
        String[] keys = new String[this.properties.keySet().size()];
        int t = 0;
        for (String key : this.properties.keySet()) {
            keys[t] = key.replace(D88Constants.prefix_String, "").replace(D88Constants.prefix_Integer, "").replace(D88Constants.prefix_Double, "").replace(D88Constants.prefix_Boolean, "");
            t += 1;
        }
        return keys;
    }

    public boolean removeObjectForKey(String key){
        if(D88Constants.CMD_STRING.equals(key)){
            return false;
        }
        if(this.containsKey(key)){
            if (this.properties.containsKey(D88Constants.prefix_String + key)) {
                this.properties.remove(D88Constants.prefix_String + key);
            }
            else if (this.properties.containsKey(D88Constants.prefix_Integer + key)) {
                this.properties.remove(D88Constants.prefix_Integer + key);
            }
            else if (this.properties.containsKey(D88Constants.prefix_Double + key)) {
                this.properties.remove(D88Constants.prefix_Double + key);
            }
            else{
                this.properties.remove(D88Constants.prefix_Boolean + key);
            }
            return true;
        }
        return false;
    }

    // SET GET
    public String getCmd() {
        return (String) this.properties.get("cmd");
    }

    public void setCmd(String cmd) {
        this.cmd = cmd;
        this.properties.put(D88Constants.CMD_STRING, cmd);
    }
    public void setStringForKey(String value, String key) {
        this.properties.put(D88Constants.prefix_String + key, value);
    }

    public String getStringForKey(String key) {
        return (String) this.properties.get(D88Constants.prefix_String + key);
    }

    public void setStringsForKey(String[] value, String key) {
        this.properties.put(D88Constants.prefix_String + key, value);
    }

    public String[] getStringsForKey(String key) {
        return (String[]) this.properties.get(D88Constants.prefix_String + key);
    }

    //Integer
    public void setIntegerForKey(int value, String key) {
        this.properties.put(D88Constants.prefix_Integer + key, value);
    }

    public int getIntegerForKey(String key) {
        return (int) this.properties.get(D88Constants.prefix_Integer + key);
    }

    public void setIntegersForKey(int[] value, String key) {
        this.properties.put(D88Constants.prefix_Integer + key, value);
    }

    public int[] getIntegersForKey(String key) {
        return (int[]) this.properties.get(D88Constants.prefix_Integer + key);
    }

    //Double
    public void setDoubleForKey(double value, String key) {
        this.properties.put(D88Constants.prefix_Double + key, value);

    }

    public double getDoubleForKey(String key) {
        return (double) this.properties.get(D88Constants.prefix_Double + key);
    }

    public void setDoublesForKey(double[] value, String key) {
        this.properties.put(D88Constants.prefix_Double + key, value);
    }

    public double[] getDoublesForKey(String key) {
        return (double[]) this.properties.get(D88Constants.prefix_Double + key);
    }

    //bool
    public void setBooleanForKey(boolean value, String key) {
        this.properties.put(D88Constants.prefix_Boolean + key, value);
    }

    public boolean getBooleanForKey(String key) {
        return (boolean) this.properties.get(D88Constants.prefix_Boolean + key);
    }

    public void setBooleansForKey(boolean[] value, String key) {
        this.properties.put(D88Constants.prefix_Boolean + key, value);
    }

    public boolean[] getBooleansForKey(String key) {
        return (boolean[]) this.properties.get(D88Constants.prefix_Boolean + key);
    }

    // obj param

    public OBJTYPE getObjType() {
        return objType;
    }

    public OBJFORM getObjForm() {
        return objForm;
    }

    public int getObjAppID() {
        return objAppID;
    }

    public int getObjVer() {
        return objVer;
    }

    public void setObjType(OBJTYPE objType) {
        this.objType = objType;
    }

    public void setObjForm(OBJFORM objForm) {
        this.objForm = objForm;
    }

    public void setObjAppID(int objAppID) {
        this.objAppID = objAppID;
    }

    public void setObjVer(int objVer) {
        this.objVer = objVer;
    }

}


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Returns "enabled" or "disabled" based on permissions in an array.
 *
 * @param array $array
 */
if ( ! function_exists('is_enabled')) {
    function is_enabled($permission, $array) {
        if (in_array($permission, $array)) {
            return "enabled";
        }
        return "disabled";
    }
}

/**
 *  Return a boolean indicating if the user has the indicated permission.
 */
if ( ! function_exists('has_perm')) {
    function has_perm($permission, $user) {
        return in_array($permission, $user["permissions"]);
    }
}

/**
 * Outputs an array in a user-readable JSON format
 *
 * @param array $array
 */
if ( ! function_exists('display_json'))
{
    function display_json($array)
    {
        $data = json_indent($array);

        header('Cache-Control: no-cache, must-revalidate');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Content-type: application/json');

        echo $data;
    }
}

if (!function_exists("current_full_url")) {
    function current_full_url() {
        $CI =& get_instance();

        $url = $CI->config->site_url($CI->uri->uri_string());
        return $_SERVER['QUERY_STRING'] ? $url.'?'.$_SERVER['QUERY_STRING'] : $url;
    }
}

/**
 * Convert an array to a user-readable JSON string
 *
 * @param array $array - The original array to convert to JSON
 * @return string - Friendly formatted JSON string
 */
if ( ! function_exists('json_indent'))
{
    function json_indent($array = array())
    {
        // make sure array is provided
        if (empty($array))
            return NULL;

        //Encode the string
        $json = json_encode($array);

        $result        = '';
        $pos           = 0;
        $str_len       = strlen($json);
        $indent_str    = '  ';
        $new_line      = "\n";
        $prev_char     = '';
        $out_of_quotes = true;

        for ($i = 0; $i <= $str_len; $i++)
        {
            // grab the next character in the string
            $char = substr($json, $i, 1);

            // are we inside a quoted string?
            if ($char == '"' && $prev_char != '\\')
            {
                $out_of_quotes = !$out_of_quotes;
            }
            // if this character is the end of an element, output a new line and indent the next line
            elseif (($char == '}' OR $char == ']') && $out_of_quotes)
            {
                $result .= $new_line;
                $pos--;

                for ($j = 0; $j < $pos; $j++)
                {
                    $result .= $indent_str;
                }
            }

            // add the character to the result string
            $result .= $char;

            // if the last character was the beginning of an element, output a new line and indent the next line
            if (($char == ',' OR $char == '{' OR $char == '[') && $out_of_quotes)
            {
                $result .= $new_line;

                if ($char == '{' OR $char == '[')
                {
                    $pos++;
                }

                for ($j = 0; $j < $pos; $j++)
                {
                    $result .= $indent_str;
                }
            }

            $prev_char = $char;
        }

        // return result
        return $result . $new_line;
    }
}

/**
 * Save data to a CSV file
 *
 * @param array $array
 * @param string $filename
 * @return bool
 */
if ( ! function_exists('array_to_csv'))
{
    function array_to_csv($array = array(), $filename = "export.csv")
    {
        $CI = get_instance();

        // disable the profiler otherwise header errors will occur
        $CI->output->enable_profiler(FALSE);

        if ( ! empty($array))
        {
            // ensure proper file extension is used
            if ( ! substr(strrchr($filename, '.csv'), 1))
            {
                $filename .= '.csv';
            }

            try
            {
                // set the headers for file download
                header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
                header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
                header("Cache-Control: no-cache, must-revalidate");
                header("Pragma: no-cache");
                header("Content-type: text/csv");
                header("Content-Description: File Transfer");
                header("Content-Disposition: attachment; filename={$filename}");

                $output = @fopen('php://output', 'w');

                // used to determine header row
                $header_displayed = FALSE;

                foreach ($array as $row)
                {
                    if ( ! $header_displayed)
                    {
                        // use the array keys as the header row
                        fputcsv($output, array_keys($row));
                        $header_displayed = TRUE;
                    }

                    // clean the data
                    $allowed = '/[^a-zA-Z0-9_ %\|\[\]\.\(\)%&-]/s';
                    foreach ($row as $key => $value)
                    {
                        $row[$key] = preg_replace($allowed, '', $value);
                    }

                    // insert the data
                    fputcsv($output, $row);
                }

                fclose($output);

            }
            catch (Exception $e) {}
        }

        exit;
    }
}

/**
 * Generates a random password
 *
 * @return string
 */
if ( ! function_exists('generate_random_password'))
{
    function generate_random_password()
    {
        $characters = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
        $pass = array();
        $alpha_length = strlen($characters) - 1;

        for ($i = 0; $i < 8; $i++)
        {
            $n = rand(0, $alpha_length);
            $pass[] = $characters[$n];
        }

        return implode($pass);
    }
}

/**
 * Retrieves list of language folders
 *
 * @return array
 */
if ( ! function_exists('get_languages'))
{
    function get_languages()
    {
        $CI = get_instance();

        if ($CI->session->languages)
        {
            return $CI->session->languages;
        }

        $CI->load->helper('directory');

        $language_directories = directory_map(APPPATH . '/language/', 1);
        if ( ! $language_directories)
        {
            $language_directories = directory_map(BASEPATH . '/language/', 1);
        }

        $languages = array();
        foreach ($language_directories as $language)
        {
            if (substr($language, -1) == "/" || substr($language, -1) == "\\")
            {
                $languages[substr($language, 0, -1)] = ucwords(str_replace(array('-', '_'), ' ', substr($language, 0, -1)));
            }
        }

        $CI->session->languages = $languages;

        return $languages;
    }
}

if (!function_exists("active_if_url_contains")) {
    function active_if_url_contains($text) {
        return (uri_string() == $text) ? 'active' : '';
    }
}


text:
'use babel';

import { Range } from 'atom';
import { allowUnsafeEval } from 'loophole';
const _ = require('lodash');
//const MDTKitParser = require('C:/git/mdtkit-parser'); //TODO: use real path after testing / publishing!!!
const MDTKitParser = require('mdtkit-parser');
const fs = require('fs');
function traceResolvedValues(tests) {

  const traces = [];

  const pushTrace = (valueElement) => {
    traces.push({
      type: 'Info',
      text: JSON.stringify(valueElement.value, null, 2),
      filePath: valueElement.path,
      range: new Range(
          [valueElement.location.start.line-1, valueElement.location.start.column-1],
          [valueElement.location.end.line-1, valueElement.location.end.column-1]
      ),
      severity: "info"
    });
  };

  const pushConstantsTraces = (prePostConstants) => {
    _.each(prePostConstants , prePostConstant => {
      if((prePostConstant.arithmeticallyResolved !== undefined && !!prePostConstant.arithmeticallyResolved === true) ||
          (prePostConstant.expression.replaced !== undefined && !!prePostConstant.expression.replaced === true)) {
        pushTrace(prePostConstant.expression);
      }
    });
  };

  const pushTableValuetrace = (tableContent) => {
    _.each(tableContent , row => {
      _.each(row, cell => {
        if((cell.arithmeticallyResolved !== undefined && !!cell.arithmeticallyResolved === true) ||
            (cell.replaced !== undefined && !!cell.replaced === true)) {
          pushTrace(cell);
        }
      });
    });
  };

  _.each(tests, test => {
    pushConstantsTraces(test.preConstants);
    pushConstantsTraces(test.postConstants);
    pushTableValuetrace(test.table.content)
  });

  return traces;
}

function shouldLint(filepath){
  const folderList = atom.config.get('mdtkit-lint').folderList;
  const isBlacklist = atom.config.get('mdtkit-lint').treatAsBlacklist;

  if(_.indexOf(folderList, '*') !== -1){
    if(isBlacklist){
      return false;
    }
    return true;
  }

  try{
    const resolvedPath = fs.realpathSync(filepath);
    const resolvedFolders = _.map(folderList, it => fs.realpathSync(_.trim(it, '"\'')));

    if(_.some(resolvedFolders, it => resolvedPath.indexOf(it) === 0)){
      if(isBlacklist){
        return false;
      }
      return true;
    }

  }catch(e){
    atom.notifications.addWarning('mdtkit-lint: bad folder check list', {detail: "the provided folder list causes some troubles. Please check given paths under settings. Exception:\n" + e.message});
  }
  if(isBlacklist){
    return true;
  }
  return false;
}

module.exports = {
  config: {
    showTooltipForResolvedValues: {
      title: 'Show tooltip for resolved values',
      type: 'boolean',
      default: true
    },
    ignoreImportOnlyFiles: {
      title: 'Disable direct parsing of import only files by labels',
      description: 'Provide a comma separated list of labels which will force the parser to ignore files staring with such a label.',
      type: 'array',
      default: ['$IMPORT_ONLY$'],
      item: {
        type: "string"
      }
    },
    folderList: {
      title: 'Folders to be checked by the linter',
      description: 'Provide a comma separated list of directories which should be checked by the linter.',
      type: 'array',
      default: ['*'],
      item: {
        type: "string"
      }
    },
    treatAsBlacklist: {
      description: 'treat folder list as blacklist',
      type: 'boolean',
      default: false
    }
  },
  activate() {
    require('atom-package-deps').install('mdtkit-lint');
  },
  provideLinter() {
    return {
      name: 'MDTKit Lint',
      grammarScopes: ['source.gfm', 'source.pfm'],
      scope: 'file',
      lintOnFly: true,
      lint: editor => {
        return new Promise((resolve, reject) => {
          let returnValue = [];

          const text = editor.getText();
          const path = editor.getPath();

          if(!shouldLint(path)){
            return resolve(returnValue);
          }

          if(_.some(atom.config.get("mdtkit-lint").ignoreImportOnlyFiles, ignoreLabel => text.startsWith(ignoreLabel))){
            return resolve(returnValue);
          }

          try{
            const result = allowUnsafeEval(() => MDTKitParser.instance.parseText(text, path));
            if(atom.config.get("mdtkit-lint").showTooltipForResolvedValues){
              returnValue = returnValue.concat(traceResolvedValues(result.tests));
            }
            _.each(result.linter.errors, error => {
              returnValue.push({
                type: 'Error',
                text: error.message,
                filePath: error.path,
                range: new Range(
                    [error.location.start.line-1, error.location.start.column-1],
                    [error.location.end.line-1, error.location.end.column-1]
                )
              });
            });

            _.each(result.linter.stack, stackElem => {
              returnValue.push({

                type: 'Error',
                text: `Parsing failed on \'${_.first(stackElem.blockName.split('_'))}\'`,
                filePath: stackElem.path,
                range: new Range(
                  [stackElem.location.start.line-1, stackElem.location.start.column-1],
                  [stackElem.location.end.line-1, stackElem.location.end.column-1]
                )
              });
            });
            return resolve(returnValue);
          }catch(e){
            returnValue.push({
              type: 'Error',
              text: "A critical error occurred: " + e.message
            });
          }
          return resolve(returnValue);
        });
      }
    };
  }
};


text:
package uk.nhs.hdn.crds.registry.domain.metadata;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import uk.nhs.hdn.common.MillisecondsSince1970;
import uk.nhs.hdn.common.hazelcast.hazelcastDataWriters.HazelcastDataWriter;
import uk.nhs.hdn.common.reflection.toString.AbstractToString;
import uk.nhs.hdn.common.serialisers.*;
import uk.nhs.hdn.crds.registry.domain.identifiers.Identifier;

import java.io.DataOutput;
import java.io.IOException;

public abstract class AbstractMetadataRecord<I extends Identifier> extends AbstractToString implements HazelcastDataWriter, Serialisable, MapSerialisable
{
	@SuppressWarnings({"PublicField", "ClassEscapesDefinedScope"}) @NotNull public final I identifier;
	@MillisecondsSince1970 public final long lastModified;

	protected AbstractMetadataRecord(@NotNull final I identifier, @MillisecondsSince1970 final long lastModified)
	{
		this.identifier = identifier;
		this.lastModified = lastModified;
	}

	@Override
	public void writeData(@NotNull final DataOutput out) throws IOException
	{
		identifier.writeData(out);
		out.writeLong(lastModified);
	}

	@Override
	public void serialise(@NotNull final Serialiser serialiser) throws CouldNotSerialiseException
	{
		try
		{
			serialiseMap(serialiser);
		}
		catch (CouldNotSerialiseMapException e)
		{
			throw new CouldNotSerialiseException(this, e);
		}
	}

	@Override
	public void serialiseMap(@NotNull final MapSerialiser mapSerialiser) throws CouldNotSerialiseMapException
	{
		try
		{
			mapSerialiser.writeProperty("identifier", identifier);
			mapSerialiser.writeProperty("lastModified", lastModified);
		}
		catch (CouldNotWritePropertyException e)
		{
			throw new CouldNotSerialiseMapException(this, e);
		}
	}

	@Override
	public boolean equals(@Nullable final Object obj)
	{
		if (this == obj)
		{
			return true;
		}
		if (obj == null || getClass() != obj.getClass())
		{
			return false;
		}

		final AbstractMetadataRecord<?> that = (AbstractMetadataRecord<?>) obj;

		if (lastModified != that.lastModified)
		{
			return false;
		}
		if (!identifier.equals(that.identifier))
		{
			return false;
		}

		return true;
	}

	@Override
	public int hashCode()
	{
		int result = identifier.hashCode();
		result = 31 * result + (int) (lastModified ^ (lastModified >>> 32));
		return result;
	}
}


text:
export default function getImageParameters(image) {
  return {
    width: image.width,
    height: image.height,
    components: image.components,
    alpha: image.alpha,
    colorModel: image.colorModel,
    bitDepth: image.bitDepth,
  };
}


text:
namespace content {
class WebContents;
}

// The delegate for a HandoffActiveURLObserver.
class HandoffActiveURLObserverDelegate {
 public:
  // Called when:
  //   1. The most recently focused browser changes.
  //   2. The active tab of the browser changes.
  //   3. After a navigation of the web contents of the active tab.
  // |web_contents| is the WebContents whose VisibleURL is considered the
  // "Active URL" of Chrome.
  virtual void HandoffActiveURLChanged(content::WebContents* web_contents) = 0;

 protected:
  virtual ~HandoffActiveURLObserverDelegate(){};
};

#endif  // CHROME_BROWSER_UI_COCOA_HANDOFF_ACTIVE_URL_OBSERVER_DELEGATE_H_


text:
package com.inepex.ineForm.shared.dispatch;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import net.customware.gwt.dispatch.shared.Action;

import com.inepex.ineom.shared.assistedobject.AssistedObject;
import com.inepex.ineom.shared.assistedobject.KeyValueObject;
import com.inepex.ineom.shared.dispatch.interfaces.RelationList;

/**
 * General action for searching when a {@link List} of {@link KeyValueObject} is
 * returned. Especially useful in {@link ServerSideTableModel}
 *
 * @author István Szoboszlai
 *
 */
public class RelationListAction extends AbstractSearchAction
        implements Action<RelationListActionResult>, RelationList {
    /**
     *
     */
    private static final long serialVersionUID = -8669603502664601792L;
    private List<String> propGroups = new ArrayList<String>();

    public RelationListAction() {}

    public RelationListAction(
        String descriptorName,
        AssistedObject searchParameters,
        int firstResult,
        int numMaxResult,
        boolean queryResultCount) {
        super(descriptorName, searchParameters, firstResult, numMaxResult, queryResultCount);
    }

    @Override
    public void setPropGroups(String... propGroups) {
        this.propGroups = Arrays.asList(propGroups);
    }

    @Override
    public List<String> getPropGroups() {
        return propGroups;
    }

}


text:
require 'spec_helper'

describe 'sample-go-cm::nginx' do
  describe command('nginx -t') do
    its(:exit_status) { should eq 0 }
  end
end


text:
from sys import version_info
if version_info >= (2, 6, 0):
    def swig_import_helper():
        from os.path import dirname
        import imp
        fp = None
        try:
            fp, pathname, description = imp.find_module('_SimTemplateZoneLoads_ZoneLoads_Default', [dirname(__file__)])
        except ImportError:
            import _SimTemplateZoneLoads_ZoneLoads_Default
            return _SimTemplateZoneLoads_ZoneLoads_Default
        if fp is not None:
            try:
                _mod = imp.load_module('_SimTemplateZoneLoads_ZoneLoads_Default', fp, pathname, description)
            finally:
                fp.close()
            return _mod
    _SimTemplateZoneLoads_ZoneLoads_Default = swig_import_helper()
    del swig_import_helper
else:
    import _SimTemplateZoneLoads_ZoneLoads_Default
del version_info
try:
    _swig_property = property
except NameError:
    pass  # Python < 2.2 doesn't have 'property'.

def _swig_setattr_nondynamic(self, class_type, name, value, static=1):
    if (name == "thisown"):
        return self.this.own(value)
    if (name == "this"):
        if type(value).__name__ == 'SwigPyObject':
            self.__dict__[name] = value
            return
    method = class_type.__swig_setmethods__.get(name, None)
    if method:
        return method(self, value)
    if (not static):
        if _newclass:
            object.__setattr__(self, name, value)
        else:
            self.__dict__[name] = value
    else:
        raise AttributeError("You cannot add attributes to %s" % self)

def _swig_setattr(self, class_type, name, value):
    return _swig_setattr_nondynamic(self, class_type, name, value, 0)

def _swig_getattr_nondynamic(self, class_type, name, static=1):
    if (name == "thisown"):
        return self.this.own()
    method = class_type.__swig_getmethods__.get(name, None)
    if method:
        return method(self)
    if (not static):
        return object.__getattr__(self, name)
    else:
        raise AttributeError(name)

def _swig_getattr(self, class_type, name):
    return _swig_getattr_nondynamic(self, class_type, name, 0)

def _swig_repr(self):
    try:
        strthis = "proxy of " + self.this.__repr__()
    except:
        strthis = ""
    return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)

try:
    _object = object
    _newclass = 1
except AttributeError:
    class _object:
        pass
    _newclass = 0

try:
    import weakref
    weakref_proxy = weakref.proxy
except:
    weakref_proxy = lambda x: x

import base
class SimTemplateZoneLoads(base.SimTemplate):
    __swig_setmethods__ = {}
    for _s in [base.SimTemplate]:
        __swig_setmethods__.update(getattr(_s, '__swig_setmethods__', {}))
    __setattr__ = lambda self, name, value: _swig_setattr(self, SimTemplateZoneLoads, name, value)
    __swig_getmethods__ = {}
    for _s in [base.SimTemplate]:
        __swig_getmethods__.update(getattr(_s, '__swig_getmethods__', {}))
    __getattr__ = lambda self, name: _swig_getattr(self, SimTemplateZoneLoads, name)
    __repr__ = _swig_repr

    def TemplateElectricalEquipment(self, *args):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_TemplateElectricalEquipment(self, *args)

    def TemplateElecEqmt_Elevators(self, *args):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_TemplateElecEqmt_Elevators(self, *args)

    def TemplateElecEqmt_Escalators(self, *args):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_TemplateElecEqmt_Escalators(self, *args)

    def TemplateElecEqmt_Process(self, *args):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_TemplateElecEqmt_Process(self, *args)

    def TemplateGasEquipment(self, *args):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_TemplateGasEquipment(self, *args)

    def TemplateGasEqmt_Process(self, *args):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_TemplateGasEqmt_Process(self, *args)

    def TemplateHotWaterEquipment(self, *args):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_TemplateHotWaterEquipment(self, *args)

    def TemplateSteamEquipment(self, *args):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_TemplateSteamEquipment(self, *args)

    def TemplateOtherEquipment(self, *args):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_TemplateOtherEquipment(self, *args)

    def TemplatePeopleLoads(self, *args):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_TemplatePeopleLoads(self, *args)

    def TemplateLightingLoads(self, *args):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_TemplateLightingLoads(self, *args)

    def __init__(self, *args):
        this = _SimTemplateZoneLoads_ZoneLoads_Default.new_SimTemplateZoneLoads(*args)
        try:
            self.this.append(this)
        except:
            self.this = this

    def _clone(self, f=0, c=None):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads__clone(self, f, c)
    __swig_destroy__ = _SimTemplateZoneLoads_ZoneLoads_Default.delete_SimTemplateZoneLoads
    __del__ = lambda self: None
SimTemplateZoneLoads_swigregister = _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_swigregister
SimTemplateZoneLoads_swigregister(SimTemplateZoneLoads)

class SimTemplateZoneLoads_ZoneLoads(SimTemplateZoneLoads):
    __swig_setmethods__ = {}
    for _s in [SimTemplateZoneLoads]:
        __swig_setmethods__.update(getattr(_s, '__swig_setmethods__', {}))
    __setattr__ = lambda self, name, value: _swig_setattr(self, SimTemplateZoneLoads_ZoneLoads, name, value)
    __swig_getmethods__ = {}
    for _s in [SimTemplateZoneLoads]:
        __swig_getmethods__.update(getattr(_s, '__swig_getmethods__', {}))
    __getattr__ = lambda self, name: _swig_getattr(self, SimTemplateZoneLoads_ZoneLoads, name)
    __repr__ = _swig_repr

    def __init__(self, *args):
        this = _SimTemplateZoneLoads_ZoneLoads_Default.new_SimTemplateZoneLoads_ZoneLoads(*args)
        try:
            self.this.append(this)
        except:
            self.this = this

    def _clone(self, f=0, c=None):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_ZoneLoads__clone(self, f, c)
    __swig_destroy__ = _SimTemplateZoneLoads_ZoneLoads_Default.delete_SimTemplateZoneLoads_ZoneLoads
    __del__ = lambda self: None
SimTemplateZoneLoads_ZoneLoads_swigregister = _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_ZoneLoads_swigregister
SimTemplateZoneLoads_ZoneLoads_swigregister(SimTemplateZoneLoads_ZoneLoads)

class SimTemplateZoneLoads_ZoneLoads_Default(SimTemplateZoneLoads_ZoneLoads):
    __swig_setmethods__ = {}
    for _s in [SimTemplateZoneLoads_ZoneLoads]:
        __swig_setmethods__.update(getattr(_s, '__swig_setmethods__', {}))
    __setattr__ = lambda self, name, value: _swig_setattr(self, SimTemplateZoneLoads_ZoneLoads_Default, name, value)
    __swig_getmethods__ = {}
    for _s in [SimTemplateZoneLoads_ZoneLoads]:
        __swig_getmethods__.update(getattr(_s, '__swig_getmethods__', {}))
    __getattr__ = lambda self, name: _swig_getattr(self, SimTemplateZoneLoads_ZoneLoads_Default, name)
    __repr__ = _swig_repr

    def __init__(self, *args):
        this = _SimTemplateZoneLoads_ZoneLoads_Default.new_SimTemplateZoneLoads_ZoneLoads_Default(*args)
        try:
            self.this.append(this)
        except:
            self.this = this

    def _clone(self, f=0, c=None):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_ZoneLoads_Default__clone(self, f, c)
    __swig_destroy__ = _SimTemplateZoneLoads_ZoneLoads_Default.delete_SimTemplateZoneLoads_ZoneLoads_Default
    __del__ = lambda self: None
SimTemplateZoneLoads_ZoneLoads_Default_swigregister = _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_ZoneLoads_Default_swigregister
SimTemplateZoneLoads_ZoneLoads_Default_swigregister(SimTemplateZoneLoads_ZoneLoads_Default)

class SimTemplateZoneLoads_ZoneLoads_Default_sequence(base.sequence_common):
    __swig_setmethods__ = {}
    for _s in [base.sequence_common]:
        __swig_setmethods__.update(getattr(_s, '__swig_setmethods__', {}))
    __setattr__ = lambda self, name, value: _swig_setattr(self, SimTemplateZoneLoads_ZoneLoads_Default_sequence, name, value)
    __swig_getmethods__ = {}
    for _s in [base.sequence_common]:
        __swig_getmethods__.update(getattr(_s, '__swig_getmethods__', {}))
    __getattr__ = lambda self, name: _swig_getattr(self, SimTemplateZoneLoads_ZoneLoads_Default_sequence, name)
    __repr__ = _swig_repr

    def __init__(self, *args):
        this = _SimTemplateZoneLoads_ZoneLoads_Default.new_SimTemplateZoneLoads_ZoneLoads_Default_sequence(*args)
        try:
            self.this.append(this)
        except:
            self.this = this

    def assign(self, n, x):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_ZoneLoads_Default_sequence_assign(self, n, x)

    def begin(self, *args):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_ZoneLoads_Default_sequence_begin(self, *args)

    def end(self, *args):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_ZoneLoads_Default_sequence_end(self, *args)

    def rbegin(self, *args):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_ZoneLoads_Default_sequence_rbegin(self, *args)

    def rend(self, *args):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_ZoneLoads_Default_sequence_rend(self, *args)

    def at(self, *args):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_ZoneLoads_Default_sequence_at(self, *args)

    def front(self, *args):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_ZoneLoads_Default_sequence_front(self, *args)

    def back(self, *args):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_ZoneLoads_Default_sequence_back(self, *args)

    def push_back(self, *args):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_ZoneLoads_Default_sequence_push_back(self, *args)

    def pop_back(self):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_ZoneLoads_Default_sequence_pop_back(self)

    def detach_back(self, pop=True):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_ZoneLoads_Default_sequence_detach_back(self, pop)

    def insert(self, *args):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_ZoneLoads_Default_sequence_insert(self, *args)

    def erase(self, *args):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_ZoneLoads_Default_sequence_erase(self, *args)

    def detach(self, position, r, erase=True):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_ZoneLoads_Default_sequence_detach(self, position, r, erase)

    def swap(self, x):
        return _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_ZoneLoads_Default_sequence_swap(self, x)
    __swig_destroy__ = _SimTemplateZoneLoads_ZoneLoads_Default.delete_SimTemplateZoneLoads_ZoneLoads_Default_sequence
    __del__ = lambda self: None
SimTemplateZoneLoads_ZoneLoads_Default_sequence_swigregister = _SimTemplateZoneLoads_ZoneLoads_Default.SimTemplateZoneLoads_ZoneLoads_Default_sequence_swigregister
SimTemplateZoneLoads_ZoneLoads_Default_sequence_swigregister(SimTemplateZoneLoads_ZoneLoads_Default_sequence)

# This file is compatible with both classic and new-style classes.


text:
<?php

namespace App\Services\HubSync;

use Illuminate\Contracts\Filesystem\Filesystem;
use Symfony\Component\Process\Process;

/**
 * Class Repository.
 *
 * This is a git repository container able to sync itself with any remote.
 * Syncing is done using the actual git binaries thus the process running
 * this command should be allowed to use these.
 */
class Repository
{
    use SynchronousProcess;

    /**
     * @var string
     */
    protected $path = '';

    /**
     * @var string
     */
    protected $absolutePath = '';

    /**
     * @var string
     */
    protected $localName = '';

    /**
     * @var string
     */
    protected $remoteURI = '';

    protected $fs = null;

    /**
     * Repository constructor.
     *
     * @param Filesystem $fs
     * @param string     $localName
     * @param string     $remoteURI
     */
    public function __construct(Filesystem $fs, $localName, $remoteURI)
    {
        $this->fs = $fs;

        $this->localName = $localName;
        $this->remoteURI = $remoteURI;

        $this->path = "hub_sync/{$this->localName}";
        $this->absolutePath = storage_path("app/{$this->path}");

        if (!$fs->exists('hub_sync')) {
            $fs->makeDirectory('hub_sync');
        }
    }

    /**
     * @return bool was the update succesful?
     */
    public function update()
    {
        if (!$this->exists()) {
            $cmd = sprintf(
                'git clone -q --recursive --recurse-submodules %s %s',
                $this->remoteURI,
                $this->absolutePath
            );
        } else {
            $cmd = sprintf('git -C %s pull -q', $this->absolutePath);
        }

        $process = new Process($cmd);

        $process->setTimeout(900);
        $process->start();
        $process->wait();

        return $process->getExitCode() == 0;
    }

    /**
     * Removes the repository.
     */
    public function remove()
    {
        $this->fs->deleteDirectory($this->path);
        $this->fs->delete($this->path);
    }

    public function clean()
    {
        return $this->synchronousProcess(sprintf('git -C %s clean -xf', $this->getAbsolutePath()));
    }

    /**
     * Get the path to a file inside the repository.
     *
     * Will return the repository's root path if no
     * filename was given.
     *
     * @param string $file path/to/a/file
     *
     * @return string
     */
    public function getPath($file = '')
    {
        return (strlen($file) === 0) ? $this->path : $this->path.'/'.$file;
    }

    /**
     * Get the repository name.
     *
     * i.e. the name of the repository's root directory
     *
     * @return string
     */
    public function getLocalName()
    {
        return $this->localName;
    }

    /**
     * Get the remote URI used for updates.
     *
     * @return string
     */
    public function getRemoteURI()
    {
        return $this->remoteURI;
    }

    /**
     * Get the current repo treeish.
     *
     * Aside from the canonical revision hash, there are
     * also other ways to uniquely address a git commit.
     *
     * This method will return the shortest possible
     * string that uniquely identifies the current HEAD.
     * Typically, that should be the name of a branch or
     * a checked-out non-HEAD tag.
     *
     * @return string
     */
    public function getCurrentTreeish()
    {
        $revParseCmd = sprintf('git -C %s rev-parse --abbrev-ref HEAD', $this->getAbsolutePath());

        return $this->synchronousProcess($revParseCmd);
    }

    /**
     * Returns the absolute path to the repository.
     *
     * @return string
     */
    public function getAbsolutePath()
    {
        return $this->absolutePath;
    }

    /**
     * @return string unique shortened commit hash for HEAD
     */
    public function getCurrentHead()
    {
        return $this->getUniqueRevision('HEAD');
    }

    /**
     * Get the unique shortened commit hash for any revision.
     *
     * In contrast to `getCurrentTreeish` this does not
     * return a symbolic name but the familiar git commit sha1
     * hash in it's shortened version.
     *
     * @param string $revision revision can be any tree-ish
     *
     * @return string
     */
    public function getUniqueRevision($revision)
    {
        $revParseCmd = sprintf('git -C %s rev-parse --short %s', $this->getAbsolutePath(), $revision);

        return $this->synchronousProcess($revParseCmd);
    }

    /**
     * @return bool
     */
    public function exists(): bool
    {
        return $this->fs->exists("{$this->path}/.git/HEAD");
    }
}


text:
import Backbone from 'backbone';
import Marionette from 'backbone.marionette';
import 'jquery-lazyload';

import template from './SearchResultListView.hbs';
import './SearchResultListView.css';
import SearchResultItemView from './SearchResultItemView';
import { setSlice } from '../utils';

// eslint-disable-next-line max-len
const SearchResultListView = Marionette.CompositeView.extend(/** @lends search/views/layers.SearchResultListView# */{
  template,
  templateHelpers() {
    const hasMore = this.hasMore();
    return {
      layerName: this.model.get('layerModel').get('displayName'),
      layerId: this.model.cid,
      isClosed: this.isClosed,
      hasMore,
      countLoadMore: hasMore ? Math.min(this.model.get('totalResults') - this.model.get('hasLoaded'), this.model.get('loadMore')) : 0,
      hasMoreOrIsSearching: hasMore || this.model.get('isSearching'),
    };
  },
  tagName: 'ul',
  className: 'search-result-list list-unstyled list-inline',

  childView: SearchResultItemView,
  childViewContainer: 'ul.result-list',

  buildChildView(child, ChildViewClass) {
    return new ChildViewClass({
      model: child,
      searchModel: this.model,
      highlightModel: this.highlightModel,
      fallbackThumbnailUrl: this.fallbackThumbnailUrl,
    });
  },

  events: {
    'click .btn-load-more': 'onLoadMoreClicked',
    'shown.bs.collapse': 'onShown',
    'hidden.bs.collapse': 'onHidden'
  },

  childEvents: {
    'item:clicked': 'onItemClicked',
    'item:info': 'onItemInfo',
    'item:hover': 'onItemHover',
    'item:hover:end': 'onItemHoverEnd',
  },

  constructor(options) {
    const collection = new Backbone.Collection();
    collection.searchModel = options.searchModel;
    Marionette.CompositeView.prototype.constructor.call(this, Object.assign({}, options, {
      collection
    }));
  },

  initialize(options) {
    this.searchModel = options.searchModel;
    this.highlightModel = options.highlightModel;
    this.downloadSelectionCollection = options.downloadSelectionCollection;
    this.fallbackThumbnailUrl = options.fallbackThumbnailUrl;
    this.isClosed = false;

    this.setSlice = setSlice;
    this.referenceCollection = options.referenceCollection;

    this.listenTo(this.model, 'change', this.render, this);
  },

  onLoadMoreClicked() {
    this.model.searchMore();
  },

  onShown() {
    this.isClosed = false;
    this.triggerMethod('collapse:change');
  },

  onHidden() {
    this.isClosed = true;
    this.triggerMethod('collapse:change');
  },

  onItemClicked(childView) {
    this.trigger('item:clicked', childView.model);
  },

  onItemInfo(childView) {
    this.trigger('item:info', {
      record: childView.model, searchModel: this.searchModel,
    });
  },

  onItemHover(childView) {
    this.highlightModel.highlight(childView.model.attributes);
  },

  onItemHoverEnd(childView) {
    this.highlightModel.unHighlight(childView.model.attributes);
  },

  hasMore() {
    if (this.model.get('hasError')) {
      return false;
    }
    const totalResults = this.model.get('totalResults');
    const hasLoaded = this.model.get('hasLoaded');
    return (
      typeof totalResults !== 'undefined'
      && typeof hasLoaded !== 'undefined' ? totalResults > hasLoaded : false
    );
  }
});

export default SearchResultListView;


text:
package org.motechproject.mds.jdo;

import static org.motechproject.mds.util.Constants.Util.MODIFIED_BY_FIELD_NAME;

/**
 * The ModifiedByValueGenerator class is responsible for generating value for
 * {@link org.motechproject.mds.util.Constants.Util#MODIFIED_BY_FIELD_NAME} field.
 */
public class ModifiedByValueGenerator extends UsernameValueGenerator {

    @Override
    protected String getPropertName() {
        return MODIFIED_BY_FIELD_NAME;
    }

}


text:
package com.navercorp.pinpoint.batch.dao;

import com.navercorp.pinpoint.batch.alarm.vo.CheckerResult;

import java.util.List;

/**
 * @author minwoo.jung
 */
public interface AlarmDao {

    List<CheckerResult> selectBeforeCheckerResultList(String applicationId);

    void deleteCheckerResult(String ruleId);

    void insertCheckerResult(CheckerResult checkerResult);
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Coryne starbaeckii P. Karst.

### Remarks
null


text:
(function () {
    "use strict";

    /** Product detail view controller */
    angular.module('app')
        .controller('DetailController', ['$scope', '$location', '$routeParams', 'catalogService', 'ProductUtils',
            function ($scope, $location, $routeParams, catalogService, ProductUtils) {

            $scope.product = {};

            catalogService.getProduct($routeParams.id).success(function (result) {
                $scope.product = result;
            });

            $scope.quantity = 1;

            $scope.getImage = ProductUtils.getImage;

		    /** Returns the CSS class for the average rating of a given product. */
		    $scope.getCSSRating = ProductUtils.getRatingCss;

}]);
})();


text:
FactoryGirl.define do
  factory :activity_member do
    activity_id 1
member_id 1
  end

end


text:
Versi
=====

Versi is a clone of the Reversi game.

The goal of the game is to capture more tiles than your enemy. You can capture the enemy's tiles
by placing a new piece on the blank tile so that one or more of enemy pieces are enclosed on a
line between your placed piece and one of your existing pieces.

https://github.com/pythonbyexample/PBE/tree/master/code/versi.py

To run Versi, you will also need to download 'board.py' and 'utils.py':

https://github.com/pythonbyexample/PBE/tree/master/code/

PlayerBase
----------

In order to compare Tiles and Player instances, I'll need a class that handles this logic:

.. sourcecode:: python

    class PlayerBase(object):
        def __eq__(self, other):
            return self.char == getattr(other, "char", None)

        def __ne__(self, other):
            return not self==other

Tiles
-----

The two kinds of tiles I'll use are blank tiles and player pieces which will have the `flip()`
method to let the piece be captured by the enemy:

.. sourcecode:: python

    class Tile(BaseTile, PlayerBase):
        blank = piece = False

        def __repr__(self): return self.char

    class Blank(Tile): char = blank

    class Piece(Tile):
        def __init__(self, loc=None, char=None):
            super(Piece, self).__init__(loc)
            self.char = char
            if loc: board[loc] = self

        def flip(self):
            self.char = nextval(player_chars, self.char)

VersiBoard
----------

There are a few small methods in the `Board` class: `valid_move()` returns `True` if the move captures
any pieces, `get_valid_moves()` returns all possible moves, `is_corner()` checks if the location is in
a corner, `status()` prints the score of each player:

.. sourcecode:: python

    class VersiBoard(Board):
        scores_msg = "%s  score: %3s    %s  score: %3s"

        def get_valid_moves(self, player):
            return [loc for loc in self.locations() if self.valid_move(player, loc)]

        def valid_move(self, player, loc):
            return bool(self.get_captured(player, loc))

        def is_corner(self, loc):
            return loc.x in (0, self.width-1) and loc.y in (0, self.height-1)

        def status(self):
            print(self.scores_msg % (player1, player1.score(), player2, player2.score()))

        def middle(self):
            return iround(self.width/2) - 1, iround(self.height/2) - 1

The logic of the `get_captured()` method is as follows: starting from the newly placed tile, go in
each of eight directions and check if any pieces can be captured; return the list of captures
(which may be empty).

Note that `dirlist2` is a list of eight major directions while `dirlist` is a list of four
directions.

.. sourcecode:: python

    def get_captured(self, player, start_loc):
        """If `start_loc` is a valid move, returns a list of locations of captured pieces."""
        if not self[start_loc].blank:
            return []

        getdir = self.capture_direction
        return flatten( [getdir(player, start_loc, dir) for dir in self.dirlist2] )

    def capture_direction(self, player, start, dir):
        """Return the list of enemy tiles to capture in the `dir` direction from `start` location."""
        groups = groupby(self.ray(start, dir))
        group1, group2 = nextgroup(groups), nextgroup(groups)
        if group1 and group2 and (group1.key == player.enemy() and group2.key == player):
            return group1.group
        else:
            return []

Player
------

There are a couple of tiny methods in the `Player` class: `score()` calculates the player's score
by adding up all of his tiles, `enemy()` returns Player's enemy.

.. sourcecode:: python

    def __init__(self, char):
        self.char = char
        self.ai   = char in ai_players

    def __repr__(self) : return self.char

    def score(self)    : return sum(tile==self for tile in board)
    def enemy(self)    : return nextval(players, self)

    def make_move(self, loc):
        for tile in board.get_captured(self, loc):
            tile.flip()
        Piece(loc, self.char)

The `get_random_move()` method is used by the AI and is a little tricky in the way it uses sorting:
we need to sort all moves so that corner locations are preferred, because they are protected from
capture, but in the absence of corner moves, we need to get the move that captures the most
pieces.

In the default Python sorting, `True` values come first and numeric values are sorted in ascending
order, so I need to negate the number of captured pieces to have the best moves sorted near the top:

.. sourcecode:: python

    def get_random_move(self):
        """Return location of best move."""
        def by_corner_score(loc):
            return board.is_corner(loc), -len(board.get_captured(self, loc))

        moves = board.get_valid_moves(self)
        shuffle(moves)
        return first(sorted(moves, key=by_corner_score))

Versi
-----

The Versi class is quite simple: I'm initializing a few pieces that go in the middle of the board,
checking if the game is finished and printing win/lose/draw messages.

.. sourcecode:: python

    class Versi(object):
        winmsg     = "%s wins!"
        tiemsg     = "The game was a tie!"

        def __init__(self):
            x, y = board.middle()
            Piece(Loc(x,y), player1.char)
            Piece(Loc(x+1, y+1), player1.char)
            Piece(Loc(x+1, y), player2.char)
            Piece(Loc(x, y+1), player2.char)

        def game_end(self):
            board.draw()
            winner = cmp(player1.score(), player2.score())
            if not winner : print(nl, self.tiemsg)
            else          : print(nl, self.winmsg % (player1 if winner>0 else player2))
            sys.exit()

BasicInterface
--------------

Player's input is simply the location of the new piece; the logic of the main loop is complicated
a bit by the fact that a player may have no valid moves available, in which case the other player
continues to make moves until the first player can either move again or the game ends; for this
reason, the transfer of turns needs to be handled explicitly.

The Player can always quit the game by entering the 'q' command.

.. sourcecode:: python

    def run(self):
        moves          = board.get_valid_moves
        player         = rndchoice(players)
        player         = first(players)
        self.textinput = TextInput(board=board)

        while True:
            board.draw()
            move = player.get_random_move() if player.ai else self.get_move(player)
            player.make_move(move)

            # give next turn to enemy OR end game if no turns left, FALLTHRU: current player keeps the turn
            if moves(player.enemy()) : player = player.enemy()
            elif not moves(player)   : versi.game_end()

    def get_move(self, player):
        while True:
            loc = self.textinput.getloc()
            if board.valid_move(player, loc) : return loc
            else                             : print(self.textinput.invalid_move)

Configuration
-------------

You can play human vs. human by setting `ai_players` empty, AI vs AI by setting it to include all AI
players, and human vs AI by omitting one player.

.. sourcecode:: python

    size         = 5, 5
    player_chars = '⎔▣'
    ai_players   = '⎔▣'

Screenshots
-----------

I'm playing square pieces, here is the initial layout::

          1     2     3     4     5     6

    1     .     .     .     .     .     .

    2     .     .     .     .     .     .

    3     .     .     ▣     ⎔     .     .

    4     .     .     ⎔     ▣     .     .

    5     .     .     .     .     .     .

    6     .     .     .     .     .     .

    ▣  score:   2    ⎔  score:   2
    >

This screenshot shows the board after two moves: my move to 5,3 and the AI move to 5,2; as you can
see, our scores changed accordingly::

          1     2     3     4     5     6

    1     .     .     .     .     .     .

    2     .     .     .     .     ⎔     .

    3     .     .     ▣     ⎔     ▣     .

    4     .     .     ⎔     ▣     .     .

    5     .     .     .     .     .     .

    6     .     .     .     .     .     .

    ▣  score:   3    ⎔  score:   3
    >


text:
package net.java.sipmack.common.scheduler;

import java.util.Date;

public class Timer {
    /**
     * The timer task queue. This data structure is shared with the timer
     * thread. The timer produces tasks, via its various schedule calls, and the
     * timer thread consumes, executing timer tasks as appropriate, and removing
     * them from the queue when they're obsolete.
     */
    private TaskQueue queue = new TaskQueue();

    /**
     * The timer thread.
     */
    private TimerThread thread = new TimerThread(queue);

    /**
     * ReSchedules the specified task to perform after "delay" milliseconds
     *
     * @param task the task to reschedule
     * @param date the time/date this task is scheduled for
     */
    public void reschedule(TimerTask task, java.util.Date date) {
        queue.reschedule(task, date.getTime());
    }

    /**
     * ReSchedules the specified task to perform after "delay" milliseconds
     *
     * @param task  the task to reschedule
     * @param delay delay in milliseconds before task is to be executed.
     */
    public void reschedule(TimerTask task, long delay) {
        queue.reschedule(task, delay);
    }

    /**
     * This object causes the timer's task execution thread to exit gracefully
     * when there are no live references to the Timer object and no tasks in the
     * timer queue. It is used in preference to a finalizer on Timer as such a
     * finalizer would be susceptible to a subclass's finalizer forgetting to
     * call it.
     */
    //TODO REMOVE
    @SuppressWarnings("unused")
    private Object threadReaper = new Object() {
        protected void finalize() throws Throwable {
            synchronized (queue) {
                thread.newTasksMayBeScheduled = false;
                queue.notify(); // In case queue is empty.
            }
        }
    };

    /**
     * Creates a new timer. The associated thread does not run as a
     * daemon.
     *
     * @see Thread
     * @see #cancel()
     */
    public Timer() {
        thread.start();
    }

    /**
     * Creates a new timer whose associated thread may be specified to run as a
     * daemon. A deamon thread is called for if the timer will be used to
     * schedule repeating "maintenance activities", which must be performed as
     * long as the application is running, but should not prolong the lifetime
     * of the application.
     *
     * @param isDaemon true if the associated thread should run as a daemon.
     * @see Thread
     * @see #cancel()
     */
    public Timer(boolean isDaemon) {
        thread.setDaemon(isDaemon);
        thread.start();
    }

    /**
     * Schedules the specified task for execution after the specified delay.
     *
     * @param task  task to be scheduled.
     * @param delay delay in milliseconds before task is to be executed.
     * @throws IllegalArgumentException if <tt>delay</tt> is negative, or
     *                                  <tt>delay + System.currentTimeMillis()</tt> is negative.
     * @throws IllegalStateException    if task was already scheduled or cancelled, or timer was
     *                                  cancelled.
     */
    public void schedule(TimerTask task, long delay) {
        if (delay < 0)
            throw new IllegalArgumentException("Negative delay.");
        sched(task, System.currentTimeMillis() + delay, 0);
    }

    /**
     * Schedules the specified task for execution at the specified time. If the
     * time is in the past, the task is scheduled for immediate execution.
     *
     * @param task task to be scheduled.
     * @param time time at which task is to be executed.
     * @throws IllegalArgumentException if <tt>time.getTime()</tt> is negative.
     * @throws IllegalStateException    if task was already scheduled or cancelled, timer was
     *                                  cancelled, or timer thread terminated.
     */
    public void schedule(TimerTask task, Date time) {
        sched(task, time.getTime(), 0);
    }

    /**
     * Schedules the specified task for repeated fixed-delay execution,
     * beginning after the specified delay. Subsequent executions take place at
     * approximately regular intervals separated by the specified period.
     *

     *

     * In fixed-delay execution, each execution is scheduled relative to the
     * actual execution time of the previous execution. If an execution is
     * delayed for any reason (such as garbage collection or other background
     * activity), subsequent executions will be delayed as well. In the long
     * run, the frequency of execution will generally be slightly lower than the
     * reciprocal of the specified period (assuming the system clock underlying
     * <tt>Object.wait(long)</tt> is accurate).
     *

     *

     * Fixed-delay execution is appropriate for recurring activities that
     * require "smoothness." In other words, it is appropriate for activities
     * where it is more important to keep the frequency accurate in the short
     * run than in the long run. This includes most animation tasks, such as
     * blinking a cursor at regular intervals. It also includes tasks wherein
     * regular activity is performed in response to human input, such as
     * automatically repeating a character as long as a key is held down.
     *
     * @param task   task to be scheduled.
     * @param delay  delay in milliseconds before task is to be executed.
     * @param period time in milliseconds between successive task executions.
     * @throws IllegalArgumentException if <tt>delay</tt> is negative, or
     *                                  <tt>delay + System.currentTimeMillis()</tt> is negative.
     * @throws IllegalStateException    if task was already scheduled or cancelled, timer was
     *                                  cancelled, or timer thread terminated.
     */
    public void schedule(TimerTask task, long delay, long period) {
        if (delay < 0)
            throw new IllegalArgumentException("Negative delay.");
        if (period <= 0)
            throw new IllegalArgumentException("Non-positive period.");
        sched(task, System.currentTimeMillis() + delay, -period);
    }

    /**
     * Schedules the specified task for repeated fixed-delay execution,
     * beginning at the specified time. Subsequent executions take place at
     * approximately regular intervals, separated by the specified period.
     *

     *

     * In fixed-delay execution, each execution is scheduled relative to the
     * actual execution time of the previous execution. If an execution is
     * delayed for any reason (such as garbage collection or other background
     * activity), subsequent executions will be delayed as well. In the long
     * run, the frequency of execution will generally be slightly lower than the
     * reciprocal of the specified period (assuming the system clock underlying
     * <tt>Object.wait(long)</tt> is accurate).
     *

     *

     * Fixed-delay execution is appropriate for recurring activities that
     * require "smoothness." In other words, it is appropriate for activities
     * where it is more important to keep the frequency accurate in the short
     * run than in the long run. This includes most animation tasks, such as
     * blinking a cursor at regular intervals. It also includes tasks wherein
     * regular activity is performed in response to human input, such as
     * automatically repeating a character as long as a key is held down.
     *
     * @param task      task to be scheduled.
     * @param firstTime First time at which task is to be executed.
     * @param period    time in milliseconds between successive task executions.
     * @throws IllegalArgumentException if <tt>time.getTime()</tt> is negative.
     * @throws IllegalStateException    if task was already scheduled or cancelled, timer was
     *                                  cancelled, or timer thread terminated.
     */
    public void schedule(TimerTask task, Date firstTime, long period) {
        if (period <= 0)
            throw new IllegalArgumentException("Non-positive period.");
        sched(task, firstTime.getTime(), -period);
    }

    /**
     * Schedules the specified task for repeated fixed-rate execution,
     * beginning after the specified delay. Subsequent executions take place at
     * approximately regular intervals, separated by the specified period.
     *

     *

     * In fixed-rate execution, each execution is scheduled relative to the
     * scheduled execution time of the initial execution. If an execution is
     * delayed for any reason (such as garbage collection or other background
     * activity), two or more executions will occur in rapid succession to
     * "catch up." In the long run, the frequency of execution will be exactly
     * the reciprocal of the specified period (assuming the system clock
     * underlying <tt>Object.wait(long)</tt> is accurate).
     *

     *

     * Fixed-rate execution is appropriate for recurring activities that are
     * sensitive to absolute time, such as ringing a chime every hour on
     * the hour, or running scheduled maintenance every day at a particular
     * time. It is also appropriate for for recurring activities where the total
     * time to perform a fixed number of executions is important, such as a
     * countdown timer that ticks once every second for ten seconds. Finally,
     * fixed-rate execution is appropriate for scheduling multiple repeating
     * timer tasks that must remain synchronized with respect to one another.
     *
     * @param task   task to be scheduled.
     * @param delay  delay in milliseconds before task is to be executed.
     * @param period time in milliseconds between successive task executions.
     * @throws IllegalArgumentException if <tt>delay</tt> is negative, or
     *                                  <tt>delay + System.currentTimeMillis()</tt> is negative.
     * @throws IllegalStateException    if task was already scheduled or cancelled, timer was
     *                                  cancelled, or timer thread terminated.
     */
    public void scheduleAtFixedRate(TimerTask task, long delay, long period) {
        if (delay < 0)
            throw new IllegalArgumentException("Negative delay.");
        if (period <= 0)
            throw new IllegalArgumentException("Non-positive period.");
        sched(task, System.currentTimeMillis() + delay, period);
    }

    /**
     * Schedules the specified task for repeated fixed-rate execution,
     * beginning at the specified time. Subsequent executions take place at
     * approximately regular intervals, separated by the specified period.
     *

     *

     * In fixed-rate execution, each execution is scheduled relative to the
     * scheduled execution time of the initial execution. If an execution is
     * delayed for any reason (such as garbage collection or other background
     * activity), two or more executions will occur in rapid succession to
     * "catch up." In the long run, the frequency of execution will be exactly
     * the reciprocal of the specified period (assuming the system clock
     * underlying <tt>Object.wait(long)</tt> is accurate).
     *

     *

     * Fixed-rate execution is appropriate for recurring activities that are
     * sensitive to absolute time, such as ringing a chime every hour on
     * the hour, or running scheduled maintenance every day at a particular
     * time. It is also appropriate for for recurring activities where the total
     * time to perform a fixed number of executions is important, such as a
     * countdown timer that ticks once every second for ten seconds. Finally,
     * fixed-rate execution is appropriate for scheduling multiple repeating
     * timer tasks that must remain synchronized with respect to one another.
     *
     * @param task      task to be scheduled.
     * @param firstTime First time at which task is to be executed.
     * @param period    time in milliseconds between successive task executions.
     * @throws IllegalArgumentException if <tt>time.getTime()</tt> is negative.
     * @throws IllegalStateException    if task was already scheduled or cancelled, timer was
     *                                  cancelled, or timer thread terminated.
     */
    public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) {
        if (period <= 0)
            throw new IllegalArgumentException("Non-positive period.");
        sched(task, firstTime.getTime(), period);
    }

    /**
     * Schedule the specifed timer task for execution at the specified time with
     * the specified period, in milliseconds. If period is positive, the task is
     * scheduled for repeated execution; if period is zero, the task is
     * scheduled for one-time execution. Time is specified in Date.getTime()
     * format. This method checks timer state, task state, and initial execution
     * time, but not period.
     *
     * @throws IllegalArgumentException if <tt>time()</tt> is negative.
     * @throws IllegalStateException    if task was already scheduled or cancelled, timer was
     *                                  cancelled, or timer thread terminated.
     */
    private void sched(TimerTask task, long time, long period) {
        if (time < 0)
            throw new IllegalArgumentException("Illegal execution time.");

        synchronized (queue) {
            if (!thread.newTasksMayBeScheduled)
                throw new IllegalStateException("Timer already cancelled.");

            synchronized (task.lock) {
                if (task.state != TimerTask.VIRGIN)
                    throw new IllegalStateException(
                            "Task already scheduled or cancelled");
                task.nextExecutionTime = time;
                task.period = period;
                task.state = TimerTask.SCHEDULED;
            }

            queue.add(task);
            if (queue.getMin() == task)
                queue.notify();
        }
    }

    /**
     * Terminates this timer, discarding any currently scheduled tasks. Does not
     * interfere with a currently executing task (if it exists). Once a timer
     * has been terminated, its execution thread terminates gracefully, and no
     * more tasks may be scheduled on it.
     *

     *

     * Note that calling this method from within the run method of a timer task
     * that was invoked by this timer absolutely guarantees that the ongoing
     * task execution is the last task execution that will ever be performed by
     * this timer.
     *

     *

     * This method may be called repeatedly; the second and subsequent calls
     * have no effect.
     */
    public void cancel() {
        synchronized (queue) {
            thread.newTasksMayBeScheduled = false;
            queue.clear();
            queue.notify(); // In case queue was already empty.
        }
    }
}

/**
 * This "helper class" implements the timer's task execution thread, which waits
 * for tasks on the timer queue, executions them when they fire, reschedules
 * repeating tasks, and removes cancelled tasks and spent non-repeating tasks
 * from the queue.
 */
class TimerThread extends Thread {
    /**
     * This flag is set to false by the reaper to inform us that there are no
     * more live references to our Timer object. Once this flag is true and
     * there are no more tasks in our queue, there is no work left for us to do,
     * so we terminate gracefully. Note that this field is protected by queue's
     * monitor!
     */
    boolean newTasksMayBeScheduled = true;

    /**
     * Our Timer's queue. We store this reference in preference to a reference
     * to the Timer so the reference graph remains acyclic. Otherwise, the Timer
     * would never be garbage-collected and this thread would never go away.
     */
    private TaskQueue queue;

    TimerThread(TaskQueue queue) {
        this.queue = queue;
    }

    public void run() {
        try {
            mainLoop();
        }
        finally {
            // Somone killed this Thread, behave as if Timer cancelled
            synchronized (queue) {
                newTasksMayBeScheduled = false;
                queue.clear(); // Eliminate obsolete references
            }
        }
    }

    /**
     * The main timer loop. (See class comment.)
     */
    private void mainLoop() {
        while (true) {
            try {
                TimerTask task;
                boolean taskFired;
                synchronized (queue) {
                    // Wait for queue to become non-empty
                    while (queue.isEmpty() && newTasksMayBeScheduled) queue.wait();
                    if (queue.isEmpty())
                        break; // Queue is empty and will forever remain; die

                    // Queue nonempty; look at first evt and do the right thing
                    long currentTime, executionTime;
                    task = queue.getMin();
                    synchronized (task.lock) {
                        if (task.state == TimerTask.CANCELLED) {
                            queue.removeMin();
                            continue; // No action required, poll queue again
                        }
                        currentTime = System.currentTimeMillis();
                        executionTime = task.nextExecutionTime;
                        if (taskFired = (executionTime <= currentTime)) {
                            if (task.period == 0) { // Non-repeating, remove
                                queue.removeMin();
                                task.state = TimerTask.EXECUTED;
                            }
                            else { // Repeating task, reschedule
                                queue
                                        .rescheduleMin(task.period < 0 ? currentTime
                                                - task.period
                                                : executionTime + task.period);
                            }
                        }
                    }
                    if (!taskFired) // Task hasn't yet fired; wait
                        queue.wait(executionTime - currentTime);
                }
                if (taskFired) // Task fired; run it, holding no locks
                    task.run();
            }
            catch (InterruptedException e) {
            }
        }
    }
}

/**
 * This class represents a timer task queue: a priority queue of TimerTasks,
 * ordered on nextExecutionTime. Each Timer object has one of these, which it
 * shares with its TimerThread. Internally this class uses a heap, which offers
 * log(n) performance for the add, removeMin and rescheduleMin operations, and
 * constant time performance for the the getMin operation.
 */
class TaskQueue {
    /**
     * Priority queue represented as a balanced binary heap: the two children of
     * queue[n] are queue[2*n] and queue[2*n+1]. The priority queue is ordered
     * on the nextExecutionTime field: The TimerTask with the lowest
     * nextExecutionTime is in queue[1] (assuming the queue is nonempty). For
     * each node n in the heap, and each descendant of n, d, n.nextExecutionTime <=
     * d.nextExecutionTime.
     *
     * @uml.property name="queue"
     * @uml.associationEnd multiplicity="(0 -1)"
     */
    private TimerTask[] queue = new TimerTask[128];

    /**
     * The number of tasks in the priority queue. (The tasks are stored in
     * queue[1] up to queue[size]).
     */
    private int size = 0;

    /**
     * Adds a new task to the priority queue.
     */
    void add(TimerTask task) {
        // Grow backing store if necessary
        if (++size == queue.length) {
            TimerTask[] newQueue = new TimerTask[2 * queue.length];
            System.arraycopy(queue, 0, newQueue, 0, size);
            queue = newQueue;
        }

        queue[size] = task;
        fixUp(size);
    }

    /**
     * Return the "head task" of the priority queue. (The head task is an task
     * with the lowest nextExecutionTime.)
     */
    TimerTask getMin() {
        return queue[1];
    }

    /**
     * Remove the head task from the priority queue.
     */
    void removeMin() {
        queue[1] = queue[size];
        queue[size--] = null; // Drop extra reference to prevent memory leak
        fixDown(1);
    }

    /**
     * Sets the nextExecutionTime associated with the head task to the specified
     * value, and adjusts priority queue accordingly.
     */
    void rescheduleMin(long newTime) {
        queue[1].nextExecutionTime = newTime;
        fixDown(1);
    }

    /**
     * Returns true if the priority queue contains no elements.
     */
    boolean isEmpty() {
        return size == 0;
    }

    /**
     * Removes all elements from the priority queue.
     */
    void clear() {
        // Null out task references to prevent memory leak
        for (int i = 1; i <= size; i++)
            queue[i] = null;

        size = 0;
    }

    /**
     * Establishes the heap invariant (described above) assuming the heap
     * satisfies the invariant except possibly for the leaf-node indexed by k
     * (which may have a nextExecutionTime less than its parent's).
     *

     * This method functions by "promoting" queue[k] up the hierarchy (by
     * swapping it with its parent) repeatedly until queue[k]'s
     * nextExecutionTime is greater than or equal to that of its parent.
     */
    private void fixUp(int k) {
        while (k > 1) {
            int j = k >> 1;
            if (queue[j].nextExecutionTime <= queue[k].nextExecutionTime)
                break;
            TimerTask tmp = queue[j];
            queue[j] = queue[k];
            queue[k] = tmp;
            k = j;
        }
    }

    /**
     * Establishes the heap invariant (described above) in the subtree rooted at
     * k, which is assumed to satisfy the heap invariant except possibly for
     * node k itself (which may have a nextExecutionTime greater than its
     * children's).
     *

     * This method functions by "demoting" queue[k] down the hierarchy (by
     * swapping it with its smaller child) repeatedly until queue[k]'s
     * nextExecutionTime is less than or equal to those of its children.
     */
    private void fixDown(int k) {
        int j;
        while ((j = k << 1) <= size) {
            if (j < size
                    && queue[j].nextExecutionTime > queue[j + 1].nextExecutionTime)
                j++; // j indexes smallest kid
            if (queue[k].nextExecutionTime <= queue[j].nextExecutionTime)
                break;
            TimerTask tmp = queue[j];
            queue[j] = queue[k];
            queue[k] = tmp;
            k = j;
        }
    }

    int findTask(TimerTask task) {
        for (int i = 1; i <= size; i++)
            if (queue[i] == task)
                return i;
        return -1;
    }

    void reschedule(TimerTask task, long time) {
        int i = findTask(task);
        if (i == -1)
            return;
        long oldTime = queue[i].nextExecutionTime;
        queue[i].nextExecutionTime = time;
        if (oldTime < time)
			fixDown(i);
		else
			fixUp(i);
	}

}