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

#if !UNITY_WEBPLAYER
using System.Reflection;
using System.IO;

#endif
using Engine.Events;
// using Engine.Data.Json;

public enum DataObjectsStorage {
    RESOURCES,
    PERSISTENT,
    PREFERENCES,
    SERVER
}

public enum DataObjectsType {
    LIST,
    OBJECT
}

public class DataObjectsMessages {
    public static string dataObjectLoaded = "data-object-loaded";
}

public class DataObjects<T> where T : DataObject, new() {

    public List<T> _items;
    public Dictionary<string, int> _lookupCode;

    //private static object syncRoot = new System.Object();

    public string pathKey = "";
    public string path = "";

    public string currentStateCode = null;

    public List<string> packPaths;
    public List<string> packPathsVersioned;
    public DataObjectsStorage dataStorage = DataObjectsStorage.PERSISTENT;
    public DataObjectsType dataType = DataObjectsType.LIST;
    public List<string> historyLevelItems = new List<string>();

    // If data is stored as a list json dataset

    public List<T> items {
        get {
            if(_items == null) {
                _items = new List<T>();
            }
            return _items;
        }
        set {
            _items = value;
        }
    }

    // If data is stored as a list json dataset

    public Dictionary<string, int> lookupCode {
        get {
            if(_lookupCode == null) {
                _lookupCode = new Dictionary<string, int>();
            }
            return _lookupCode;
        }
        set {
            _lookupCode = value;
        }
    }

    //private static volatile U current;
    //private static volatile U instance;
    //private static object syncRoot = new System.Object();

    /*
     *
    public static string DATA_KEY = "data-object";

    public static T Current {
        get  {
            if (current == null) {
                lock (syncRoot)  {
                    if (current == null)
                        current = new T();
                }
            }

            return current;
        }
        set {
            current = value;
        }
    }

    public static AppContentActions Instance {
        get  {
            if (instance == null) {
                lock (syncRoot)  {
                    if (instance == null)
                        instance = new AppContentActions(true);
                }
            }

            return instance;
        }
        set {
            instance = value;
        }
    }

    */

    public DataObjects() {
        Reset();

        //Messenger<string>.AddListener(DataObjectsMessages.dataObjectLoaded, OnDataLoaded);
    }

    public virtual void LoadData() {

        dataStorage = AppConfigs.dataStorage;

        switch(dataStorage) {

            case DataObjectsStorage.SERVER:
                LogUtil.Log("LoadData:LoadDataFromServer:" + path + " " + pathKey);
                LoadDataFromServer();
                break;

            case DataObjectsStorage.RESOURCES:
                Debug.Log("LoadData:LoadDataFromResources:" + path + " " + pathKey);
                LoadDataFromResources();
                break;

            case DataObjectsStorage.PREFERENCES:
                LogUtil.Log("LoadData:LoadDataFromPrefs:" + path + " " + pathKey);
                LoadDataFromPrefs();
                break;

            default:
                LogUtil.Log("LoadData:LoadDataFromPersistent:" + path + " " + pathKey);
                LoadDataFromPersistent();
                break;

        }

        //BroadcastDataLoaded();
    }

    public virtual void BroadcastDataLoaded() {

        Messenger<string>.Broadcast(DataObjectsMessages.dataObjectLoaded, pathKey);
    }

    public void OnDataLoaded(string key) {

        if(key.IsEqualLowercase(pathKey)) {
            LoadState();
        }
    }

    public virtual void LoadState() {

        string val = GetStateCode();

        if(val.IsNullOrEmpty()) {
            return;
        }

        SetStateCode(val);
    }

    public virtual string GetStateCode() {

        string val = GameProfiles.Current.GetGameDataState(pathKey);

        if(val.IsNullOrEmpty()
            || val.IsEqualLowercase(BaseDataObjectKeys.defaultKey)) {
            return null;
        }

        return val;
    }

    public virtual void SetStateCode(string val) {

        if(val.IsNullOrEmpty()
            || val.IsEqualLowercase(BaseDataObjectKeys.defaultKey)) {
            return;
        }

        GameProfiles.Current.SetGameDataState(pathKey, val);

        currentStateCode = val;
    }

    public virtual void ChangeCurrent(string codeTo) {
        SetStateCode(codeTo);
    }

    public virtual void LoadDataFromPersistent() {
        LoadDataFromPersistent(path);
    }

    public virtual void LoadDataFromResources() {

        string pathResources = path;

        if(!path.Contains(ContentsConfig.contentAppFolder)) {

            //Debug.Log("LoadDataFromResources:pathResources:" + pathResources);
            //Debug.Log("LoadDataFromResources:ContentsConfig.contentRootFolder:" + ContentsConfig.contentRootFolder);
            //Debug.Log("LoadDataFromResources:ContentsConfig.contentAppFolder:" + ContentsConfig.contentAppFolder);
            //Debug.Log("LoadDataFromResources:Application.persistentDataPath:" + Application.persistentDataPath);
            //Debug.Log("LoadDataFromResources:Application.dataPath:" + Application.dataPath);

            /*
            if (Application.isWebPlayer) {

                System.Text.StringBuilder sbPath = new System.Text.StringBuilder();

                sbPath.Append(ContentsConfig.contentRootFolder);
                sbPath.Append("/");
                sbPath.Append(ContentsConfig.contentAppFolder);
                sbPath.Append("/version/");
                sbPath.Append(pathResources);

                pathResources = sbPath.ToString();

                Debug.Log("LoadDataFromResources:web:pathResources:" + pathResources);
            }
            else {

                sbPath.Append(ContentsConfig.contentRootFolder);
                sbPath.Append("/");
                sbPath.Append(ContentsConfig.contentAppFolder);
                sbPath.Append("/version/");
                sbPath.Append(pathResources);

                pathResources = sbPath.ToString();
                pathResources = pathResources.Replace("data/", "");

                pathResources =
                 PathUtil.Combine(ContentPaths.appCachePathData, pathResources)
                     .Replace(Application.persistentDataPath, "")
                     .Replace(Application.dataPath, "");

                if (pathResources.EndsWith(".json")) {
                    //pathResources += ".txt";
                }

                if (pathResources.StartsWith("/")) {
                    pathResources = pathResources.TrimStart('/');
                }

                if (pathResources.Contains("/" + ContentsConfig.contentVersion + "/")) {
                    pathResources = pathResources.Replace("/" + ContentsConfig.contentVersion + "/", "/version/");
                }

            }
            */

            System.Text.StringBuilder sbPath = new System.Text.StringBuilder();

            sbPath.Append(ContentsConfig.contentRootFolder);
            sbPath.Append("/");
            sbPath.Append(ContentsConfig.contentAppFolder);
            sbPath.Append("/version/");
            sbPath.Append(pathResources);

            pathResources = sbPath.ToString();
        }

        Debug.Log("LoadDataFromResources:pathResources:" + pathResources);

        string data = LoadDataFromResources(pathResources);
        LoadDataFromString(data);
    }

    public virtual string DataToJson() {

        if(_items != null) {
            return items.ToJson();
        }

        return null;
    }

    public virtual bool SaveDataItemsToResources() {
        return SaveDataItemsToResources(path);
    }

    public virtual bool SaveDataItemsToResources(string path) {
        bool saved = false;
        string fileData = "";
        //string pathPart = path;

        path =
            Path.Combine(
            Application.dataPath,
            path);

        Debug.Log("SaveDataItemsToResources:path:" + path);

        if(_items != null) {
            fileData = items.ToJson();
        }

        if(path.EndsWith(".json")) {
            path = path + ".txt";
        }

        FileSystemUtil.WriteString(path, fileData);

        Debug.Log("SaveDataItemsToResources:fileData:" + fileData + " " + pathKey);

        saved = true;

        return saved;
    }

    //

    public virtual void LoadDataFromPrefs() {
        string data = LoadDataFromPrefs(pathKey);

        LoadDataFromString(data);
    }

    public void LoadDataFromServer() {
        // TODO
        LoadDataFromServer(path);
    }

    public void LoadDataFromServer(string key) {
        // TODO
    }

    public string LoadDataFromPrefs(string key) {
        string data = "";

        if(!SystemPrefUtil.HasLocalSetting(key)) {
            data = SystemPrefUtil.GetLocalSettingString(key);
        }
        return data;
    }

    public string LoadDataFromPersistent(string path) {
        return LoadDataFromPersistent(path, true);
    }

    public string LoadDataFromPersistent(string path, bool versioned) {
        string fileData = "";

        fileData = Contents.GetFileDataFromPersistentCache(path, versioned, false);

        LoadDataFromString(fileData);

        //if(!string.IsNullOrEmpty(fileData)) {
        //string log = fileData;
        //if(fileData.Length > 1000) {
        //      log = fileData.Substring(0, 990);
        //}
        ////LogUtil.Log("LoadDataFromPersistent:fileData:" + log + " " + pathKey);
        //}

        ////LogUtil.Log(">>>LoadDataFromPersistentPacks:" + path);
        LoadDataFromPersistentPacks(path);

        return fileData;
    }

    public bool SaveDataItemsToPersistent(string path) {
        bool saved = false;
        string fileData = "";
        string pathPart = path;

        path = PathUtil.Combine(ContentPaths.appCacheVersionPath, path.TrimStart('/'));
        string pathVersioned = Contents.GetFileVersioned(path);

        //LogUtil.Log("LoadDataFromPersistent:path:" + path);
        //LogUtil.Log("LoadDataFromPersistent:pathVersioned:" + pathVersioned + " " + pathKey);

        bool prepared = PreparePersistentFile(pathPart, pathVersioned);

        if(!prepared)
            return false;

        fileData = DataToJson();

        FileSystemUtil.WriteString(pathVersioned, fileData);

        //LogUtil.Log("SaveDataItemsToPersistent:fileData:" + fileData + " " + pathKey);

        saved = true;

        return saved;
    }

    public bool SaveDataItemToPersistent(T obj, string path) {
        bool saved = false;
        string fileData = "";
        string pathPart = path;

        path = PathUtil.Combine(ContentPaths.appCacheVersionPath, path.TrimStart('/'));
        string pathVersioned = Contents.GetFileVersioned(path);

        //LogUtil.Log("LoadDataFromPersistent:path:" + path);
        //LogUtil.Log("LoadDataFromPersistent:pathVersioned:" + pathVersioned + " " + pathKey);

        bool prepared = PreparePersistentFile(pathPart, pathVersioned);

        if(!prepared)
            return false;

        fileData = obj.ToJson();

        FileSystemUtil.WriteString(pathVersioned, fileData);

        //LogUtil.Log("SaveDataItemsToPersistent:fileData:" + fileData + " " + pathKey);

        saved = true;

        return saved;
    }

    public bool PreparePersistentFile(string pathPart, string pathVersioned) {
        bool prepared = true;

        if(!FileSystemUtil.CheckFileExists(pathVersioned)) {
            prepared = false;

            //LogUtil.Log("LoadDataFromPersistent:pathVersioned not exist:" + pathVersioned + " " + pathKey);

            // copy from streaming assets
            string pathToCopy = PathUtil.Combine(ContentPaths.appCacheVersionPath, pathPart.TrimStart('/'));
            //LogUtil.Log("LoadDataFromPersistent:pathToCopy:" + pathToCopy + " " + pathKey);
            if(FileSystemUtil.CheckFileExists(pathToCopy)) {
                FileSystemUtil.MoveFile(pathToCopy, pathVersioned);
                //LogUtil.Log("LoadDataFromPersistent:file moved:" + pathToCopy + " " + pathKey);
                prepared = true;
            }
            else {
                //LogUtil.Log("LoadDataFromPersistent:move not exist:" + pathToCopy + " " + pathKey);
                prepared = false;
            }
        }
        return prepared;
    }

    public void LoadDataFromPersistentPacks(string path) {

        // Append data from additional pack data files

        List<T> appendList = new List<T>();
        List<T> appendItemList = new List<T>();

        foreach(string packPath in ContentPaths.GetPackPathsVersioned()) {
            string data = "";
            string pathData = PathUtil.Combine(packPath, path.TrimStart('/'));
            FileSystemUtil.EnsureDirectory(pathData);

            string[] packDirs = packPath.TrimEnd('/').Replace("data", "").TrimEnd('/').Split('/');
            string packDirName = packDirs[packDirs.Length - 1];

            string fileVersioned = Contents.GetFullPathVersioned(pathData);

            FileSystemUtil.EnsureDirectory(fileVersioned);

            if(FileSystemUtil.CheckFileExists(fileVersioned)) {
                data = Contents.GetFileDataFromPersistentCache(pathData, true, true);
            }

            if(!string.IsNullOrEmpty(data)) {
                List<T> objs = new List<T>();

                objs = LoadDataFromString(appendItemList, data);

                int i = 0;

                for(int j = 0; j < objs.Count; j++) {
                    SetFieldValue(objs[j], "pack_code", packDirName);
                    SetFieldValue(objs[j], "pack_sort", i++);
                }

                if(objs != null && objs.Count > 0) {
                    appendList.AddRange(objs);
                }
            }
        }

        ////LogUtil.Log("!!!!!! PackPathsVersionShared:" + Contents.GetPackPathsVersionedShared().Count);

        foreach(string packPath in ContentPaths.GetPackPathsVersionedShared()) {
            string data = "";
            string pathData = PathUtil.Combine(packPath, path.TrimStart('/'));
            FileSystemUtil.EnsureDirectory(pathData);

            string[] packDirs = packPath.TrimEnd('/').Replace("data", "").TrimEnd('/').Split('/');
            string packDirName = packDirs[packDirs.Length - 1];

            string fileVersioned = Contents.GetFullPathVersioned(pathData);
            FileSystemUtil.EnsureDirectory(fileVersioned);

            if(FileSystemUtil.CheckFileExists(fileVersioned)) {
                data = Contents.GetFileDataFromPersistentCache(pathData, true, true);
            }

            if(!string.IsNullOrEmpty(data)) {
                List<T> objs = new List<T>();

                objs = LoadDataFromString(appendItemList, data);

                int i = 0;

                for(int j = 0; j < objs.Count; j++) {
                    SetFieldValue(objs[j], "pack_code", packDirName);
                    SetFieldValue(objs[j], "pack_sort", i++);
                }

                if(objs != null && objs.Count > 0) {
                    appendList.AddRange(objs);
                }
            }
        }

        foreach(string packPath in ContentPaths.GetPackPathsNonVersioned()) {
            string data = "";
            string pathData = PathUtil.Combine(packPath, path.TrimStart('/'));
            FileSystemUtil.EnsureDirectory(pathData);

            string[] packDirs = packPath.TrimEnd('/').Replace("data", "").TrimEnd('/').Split('/');
            string packDirName = packDirs[packDirs.Length - 1];

            if(string.IsNullOrEmpty(packDirName)) {
                packDirName = "";
            }

            string fileVersioned = Contents.GetFullPathVersioned(pathData);
            FileSystemUtil.EnsureDirectory(fileVersioned);

            if(FileSystemUtil.CheckFileExists(fileVersioned)) {
                ////LogUtil.Log(">> PACK FILE EXISTS: " + pathData);
                data = Contents.GetFileDataFromPersistentCache(pathData, true, true);
                ////LogUtil.Log(">> PACK FILE DATA: " + data);
            }

            if(!string.IsNullOrEmpty(data)) {
                if(!string.IsNullOrEmpty(data)) {
                    List<T> objs = new List<T>();

                    objs = LoadDataFromString(appendItemList, data);

                    int i = 0;

                    for(int j = 0; j < objs.Count; j++) {
                        SetFieldValue(objs[j], "pack_code", packDirName);
                        SetFieldValue(objs[j], "pack_sort", i++);
                    }

                    if(objs != null && objs.Count > 0) {
                        appendList.AddRange(objs);
                    }
                }
            }
        }

        // TODO update dict lookups

        items.AddRange(appendList);

    }

    public string LoadDataFromResources(string resourcesPath) {
        string fileData = "";

        //Debug.Log("LoadDataFromResources:string:resourcesPath:" + resourcesPath + " " + pathKey);

        TextAsset textData = Resources.Load(resourcesPath, typeof(TextAsset)) as TextAsset;

        if(textData != null) {
            //Debug.Log("LoadDataFromResources:textData.text:" + textData.text);
            fileData = textData.text;

            //using(StreamReader sr = new StreamReader(new MemoryStream(level.bytes))) {
            //
            //}
        }

        //Debug.Log("LoadDataFromResources:fileData:" + fileData + " " + pathKey);

        return fileData;
    }

    public virtual void LoadDataFromString(string data) {

        //Debug.Log("LoadDataFromString:hasData:" + !data.IsNullOrEmpty());

        if(!string.IsNullOrEmpty(data)) {

            items.Clear();
            items = LoadDataFromString(items, data);

            //Debug.Log("LoadDataFromString:items.Count:" + items.Count);

            UpdateLookups();
        }
    }

    public virtual Dictionary<string, T> LoadDataFromString(Dictionary<string, T> objs, string data) {

        if(!string.IsNullOrEmpty(data)) {

            try {
                objs = data.FromJson<Dictionary<string, T>>();
            }
            catch(Exception e) {
                Debug.Log("LoadDataFromString:" + " e:" + e.Message + " data:" + data + " objs:" + objs.ToJson());
            }

            Debug.Log(objs.GetType().ToString() + " T loaded:" + objs.Count);

            //for (int j = 0; j < objs.Count; j++) {
            //    SetFieldValue(objs[j], "pack_code", "default");
            //}
        }

        return objs;
    }

    public virtual List<T> LoadDataFromString(List<T> objs, string data) {

        if(!string.IsNullOrEmpty(data)) {

            try {
                objs = data.FromJson<List<T>>();
            }
            catch(Exception e) {
                Debug.Log("LoadDataFromString:" + " e:" + e.Message + " data:" + data + " objs:" + objs.ToJson());
            }

            Debug.Log(objs.GetType().ToString() + " T loaded:" + objs.Count);

            for(int j = 0; j < objs.Count; j++) {
                SetFieldValue(objs[j], "pack_code", "default");
            }
        }
        return objs;
    }

    public T GetByCode(string code) {
        return GetByStringKey("code", code);
    }

    public T GetById(string id) {
        return GetByStringKey("code", id);
    }

    public T GetByPackCode(string packCode) {
        return GetByStringKey("pack_code", packCode);
    }

    public bool CheckById(string id) {
        return CheckByStringKey("code", id);
    }

    public bool CheckByCode(string code) {
        return CheckByStringKey("code", code);
    }

    public T GetByUuid(string id) {
        return GetByStringKey("uuid", id);
    }

    public bool CheckByUuid(string id) {
        return CheckByStringKey("uuid", id);
    }

    public T GetByName(string id) {
        return GetByStringKey("name", id);
    }

    public bool CheckByName(string id) {
        return CheckByStringKey("name", id);
    }

    public Dictionary<string, string> attributes;

    public void Inspect<U>(U obj) where U : BaseDataObject {

        // harvest the properties, fields and keys if not already done.

        if(attributes == null) {

            attributes = new Dictionary<string, string>();

            if(typeof(BaseDataObject).IsAssignableFrom(obj.GetType())) {

                foreach(string key in ((BaseDataObject)obj).Keys) {

                    if(attributes.ContainsKey(key)) {
                        attributes[key] = "dict";
                    }
                    else {
                        attributes.Add(key, "dict");
                    }
                }
            }

            // add fields
            foreach(System.Reflection.FieldInfo fieldInfo in obj.GetType().GetFields()) {

                string key = fieldInfo.Name;

                if(attributes.ContainsKey(key)) {
                    attributes[key] = "field";
                }
                else {
                    attributes.Add(key, "field");
                }
            }

            // add properties
            foreach(System.Reflection.PropertyInfo propInfo in obj.GetType().GetProperties()) {

                string key = propInfo.Name;

                if(attributes.ContainsKey(key)) {
                    attributes[key] = "property";
                }
                else {
                    attributes.Add(key, "property");
                }
            }

            // TODO dictionary keys...
        }
    }

    public T GetByStringKey(string key, string keyValue) {

        if(keyValue.IsNullOrEmpty()) {
            return default(T);
        }

        LoadAll();

        if(key == "code") {

            if(lookupCode.ContainsKey(keyValue)) {

                int index = lookupCode.Get<int>(keyValue);
                T t = GetAll()[index];
                if(t != default(T)) {
                    return t;
                }
            }
            else {
                return default(T);
            }
        }

        foreach(T obj in GetAll()) {

            if(Has(obj, key)) {

                if(keyValue == GetFieldValue<string>(obj, key)) {
                    return obj;
                }
            }
            else {
                return default(T);
            }
        }

        return default(T);
    }

    public bool Has(T obj, string key) {

        Inspect<T>(obj);
        if(attributes.ContainsKey(key)) {
            return true;
        }
        return false;
    }

    public U GetFieldValue<U>(T obj, string fieldName) {

        object val = null;

        if(Has(obj, fieldName)) {

            string type = attributes[fieldName];

            if(type == "dict") {
                if(typeof(BaseDataObject).IsAssignableFrom(obj.GetType())) {
                    if(((BaseDataObject)obj).ContainsKey(fieldName)) {
                        val = ((BaseDataObject)obj)[fieldName];
                    }
                }
            }
            else if(type == "field") {
                System.Reflection.FieldInfo field = obj.GetType().GetField(fieldName);
                if(field != null) {
                    val = field.GetValue(obj);
                }
            }
            else if(type == "property") {
                System.Reflection.PropertyInfo prop = obj.GetType().GetProperty(fieldName);
                if(prop != null) {
                    if(prop.Name == fieldName) {
                        val = prop.GetValue(obj, null);
                    }
                }
            }
        }

        try {
            return (U)val;
        }
        catch(Exception e) {
            LogUtil.Log(e);
            return default(U);
        }
    }

    public void SetFieldValue(T obj, string fieldName, object fieldValue) {
        //bool hasSet = false;

        if(Has(obj, fieldName)) {
            string type = attributes[fieldName];
            if(type == "dict") {
                if(typeof(BaseDataObject).IsAssignableFrom(obj.GetType())) {
                    if(((BaseDataObject)obj).ContainsKey(fieldName)) {
                        ((BaseDataObject)obj)[fieldName] = fieldValue;
                    }
                }
            }
            else if(type == "field") {
                System.Reflection.FieldInfo field = obj.GetType().GetField(fieldName);
                if(field != null) {
                    field.SetValue(obj, fieldValue);
                }
            }
            else if(type == "property") {
                System.Reflection.PropertyInfo prop = obj.GetType().GetProperty(fieldName);
                if(prop != null) {
                    if(prop.Name == fieldName) {
                        prop.SetValue(obj, fieldValue, null);
                    }
                }
            }
        }
    }

    public bool CheckByStringKey(string key, string keyValue) {

        foreach(T obj in GetAll()) {

            Inspect<T>(obj);

            if(attributes.ContainsKey(key)) {
                string val = GetFieldValue<string>(obj, key);
                if(val != keyValue && !string.IsNullOrEmpty(val)) {
                    return true;
                }
            }
        }

        return false;
    }

    public List<T> GetList(string key, object val) {
        //LogUtil.Log("GetList:" + " key:" + key + " val:" + val);
        List<T> list = new List<T>();
        foreach(T t in GetAll()) {
            object obj = GetFieldValue<object>(t, key);
            //LogUtil.Log("GetList:" + " obj:" + obj);
            if(obj != null) {
                if(obj.Equals(val)) {
                    //LogUtil.Log("GetList: adding t:" + t);
                    list.Add(t);
                }
            }
        }
        return list;
    }

    public List<T> GetListLike(string key, object val) {
        //LogUtil.Log("GetList:" + " key:" + key + " val:" + val);
        List<T> list = new List<T>();
        foreach (T t in GetAll()) {
            object obj = GetFieldValue<object>(t, key);
            //LogUtil.Log("GetList:" + " obj:" + obj);
            if (obj != null) {
                if(obj.GetType() == typeof(string)) {
                    string objString = Convert.ToString(obj);
                    string valString = Convert.ToString(val);
                    if (objString.Contains(valString)) {
                        //LogUtil.Log("GetList: adding t:" + t);
                        list.Add(t);
                    }
                }
            }
        }
        return list;
    }

    public List<T> GetListPack(string key, object val, bool all) {
        //LogUtil.Log("GetList:" + " key:" + key + " val:" + val);
        List<T> list = new List<T>();
        foreach(T t in GetAll()) {
            object obj = GetFieldValue<object>(t, key);
            string strObj = "";
            if(obj != null) {
                strObj = obj.ToString();
                if(strObj != null) {
                    strObj = strObj.ToLower();
                }
            }
            string strVal = "";
            if(val != null) {
                strVal = val.ToString();
                if(strVal != null) {
                    strVal = strVal.ToLower();
                }
            }
            //LogUtil.Log("GetList:" + " obj:" + obj);
            if(obj != null) {
                if((obj.Equals(val)
                    || strObj == strVal)
                    || (all
                    && (
                     obj.Equals("*")
                    || obj.Equals("all")
                    || obj.Equals("default")
                    || obj.Equals("app-state-all")
                    || obj.Equals("app-pack-all")
                     )
                 )) {

                    //LogUtil.Log("GetList: adding t:" + t);
                    list.Add(t);
                }
            }
        }
        return list;
    }

    public List<T> GetListByUuid(string val) {
        return GetList("uuid", val);
    }

    public List<T> GetListByCode(string val) {
        return GetList("code", val);
    }

    public List<T> GetListByPack(string val) {
        return GetListPack(val, true);
    }

    public List<T> GetListByParentCode(string val) {
        return GetList("parent_code", val);
    }

    public List<T> GetListPack(object val, bool all) {
        return GetListPack("pack_code", val, all);
    }

    public List<T> GetListByPackExplicit(string val) {
        return GetListPack(val, false);
    }

    public List<T> GetListByType(string val) {
        return GetList("type", val);
    }

    //
    //

    public List<T> GetList(Predicate<T> match) {
        return items.FindAll(match);
    }

    public List<T> GetList(List<T> fromList, Predicate<T> match) {
        return fromList.FindAll(match);
    }

    //

    public List<T> SortList() {
        return SortList(items);
    }

    public List<T> SortList(List<T> listItems) {

        if(listItems == null) {
            return null;
        }

        listItems.Sort(
            delegate (T c1, T c2) {
                //LogUtil.Log("sorting:c1:", c1);
                //LogUtil.Log("sorting:c2:", c2);
                if(GetFieldValue<object>(c1, "sort_order") != null) {
                    int sort1 = (int)GetFieldValue<int>(c1, "sort_order");
                    int sort2 = (int)GetFieldValue<int>(c2, "sort_order");
                    //LogUtil.Log("sorting:sort1:", sort1);
                    //LogUtil.Log("sorting:sort2:", sort2);
                    return sort1.CompareTo(sort2);
                }
                else {
                    return -1;
                }
            }
        );

        return listItems;
    }

    public void UpdateLookups() {

        lookupCode.Clear();

        for(int i = 0; i < items.Count(); i++) {
            string _code = GetFieldValue<string>(items[i], "code");
            lookupCode.Set<int>(_code, i);
        }
    }

    public void LoadAll() {

        //LogUtil.Log("GetAll:IsLoaded:", IsLoaded);

        if(!IsLoaded) {

            LoadData();

            List<T> itemsActive = new List<T>();

            foreach(T t in items) {
                bool active = GetFieldValue<bool>(t, "active");
                if(active) {
                    itemsActive.Add(t);
                }
            }

            items.Clear();

            foreach(T t in itemsActive) {
                items.Add(t);
            }

            items = SortList(items);

            itemsActive.Clear();
            itemsActive = null;

            UpdateLookups();
        }

        if(lookupCode.Count != items.Count) {
            UpdateLookups();
        }
    }

    public List<T> GetAll() {

        //LogUtil.Log("GetAll:IsLoaded:", IsLoaded);

        LoadAll();

        return items;
    }

    public int CountAll() {

        LoadAll();

        if(_items != null) {

            return items.Count;
        }

        return 0;
    }

    public virtual bool IsLoaded {
        get {
            //if (list == null && dict == null) {
            //    return false;
            //}

            if(_items != null) {
                return items.Count > 0 ? true : false;
            }

            return false;
        }
    }

    public virtual bool HasData {
        get {
            return CountAll() > 0 ? true : false;
        }
    }

    public virtual void Reset() {

        if(_lookupCode != null) {

            lookupCode.Clear();
        }

        if(_items != null) {

            items.Clear();
        }

        packPaths = new List<string>();
    }

    public string GetPathItem(string key, string code, string folder) {
        string path = PathUtil.Combine(ContentPaths.appCachePathData, folder.TrimStart('/'));
        return GetPathItem(key, code, folder, path);
    }

    public string GetPathItem(string key, string code, string folder, string fullPath) {
        string pathCode = key + "-" + code + ".json";

        FileSystemUtil.CreateDirectoryIfNeededAndAllowed(fullPath);

        fullPath = PathUtil.Combine(fullPath, pathCode.TrimStart('/'));
        return fullPath;
    }

    //public T LoadItem<U>(string key, string code) {
    public T LoadItem(string key, string code) {
        // Load from file individually not a list

        string path = GetPathItem(key, code, "items");
        path = Contents.GetFileVersioned(path);

        DataObject item = new DataObject();

        if(!FileSystemUtil.CheckFileExists(path)) {
            SaveItem(key, code, item);
        }

        historyLevelItems.Clear();

        string jsonData = item.LoadData(path);
        T itemReturn = jsonData.FromJson<T>();
        if(itemReturn != null) {
            return itemReturn;
        }
        else {
            return default(T);
        }
    }

    public void SaveItem(string key, string code, DataObject obj) {
        // Load from file individually not a list

        string path = GetPathItem(key, code, "items");
        path = Contents.GetFileVersioned(path);

        string jsonData = obj.ToJson();

        historyLevelItems.Insert(0, jsonData);
        if(historyLevelItems.Count > 20) {
            historyLevelItems.RemoveAt(historyLevelItems.Count);
        }

        obj.SaveData(path, jsonData);

    }
}


text:
package es.bsc.mobile.runtime;

import java.io.IOException;
import java.net.URISyntaxException;

import es.bsc.mobile.annotations.Parameter.Direction;
import es.bsc.mobile.annotations.Parameter.Type;
import es.bsc.mobile.runtime.types.Task;
import es.bsc.mobile.runtime.types.data.RegisteredObject;
import es.bsc.mobile.runtime.types.data.access.DataAccess;
import es.bsc.mobile.runtime.types.data.parameter.BasicTypeParameter;
import es.bsc.mobile.runtime.types.data.parameter.FileParameter;
import es.bsc.mobile.runtime.types.data.parameter.RegisteredParameter;
import es.bsc.mobile.runtime.types.data.parameter.Parameter;
import es.bsc.mobile.runtime.utils.DataRegistry;

import es.bsc.comm.CommException;
import es.bsc.comm.Connection;
import es.bsc.comm.MessageHandler;
import es.bsc.comm.TransferManager;
import es.bsc.comm.nio.NIOConnection;
import es.bsc.comm.nio.NIONode;
import es.bsc.comm.stage.Transfer;
import es.bsc.mobile.runtime.service.RuntimeServiceItf;
import es.bsc.mobile.runtime.types.CEI;
import es.bsc.mobile.types.comm.Node;

import es.bsc.mobile.runtime.types.data.DataInfo;
import es.bsc.mobile.runtime.types.data.DataInstance;
import es.bsc.mobile.runtime.types.data.access.ReadAccess;
import es.bsc.mobile.runtime.types.data.access.ReadWriteAccess;
import es.bsc.mobile.runtime.utils.CoreManager;
import es.bsc.mobile.types.messages.runtime.DataExistenceNotification;
import es.bsc.mobile.types.messages.runtime.DataSourceResponse;
import es.bsc.mobile.types.messages.runtime.DataTransferRequest;
import java.util.HashMap;
import java.util.LinkedList;
import org.apache.log4j.Logger;

public class Runtime implements MessageHandler {

    public static final int ARGUMENTS_PER_PARAMETER = 3;
    public static final int ARGUMENT_TYPE_OFFSET = 0;
    public static final int ARGUMENT_DIRECTION_OFFSET = 1;
    public static final int ARGUMENT_VALUE_OFFSET = 2;

    private static final Logger LOGGER = Logger.getLogger("Runtime");
    private static final Node me = new Node(null, 28000);
    private static CEI cei;
    private static final RuntimeServiceItf runtimeService = RuntimeServiceItf.Stub.asInterface();

    private static final DataRegistry<Integer> privateReg = new DataRegistry<Integer>();
    private static final HashMap<Integer, Object> idToRep = new HashMap<Integer, Object>();
    private static final HashMap<String, LinkedList<Operation>> pendingOperations = new HashMap<String, LinkedList<Operation>>();
    private static final HashMap<Connection, String> requestedData = new HashMap<Connection, String>();

    private Runtime() {
    }

    /**
     * *********************************************************************
     * *********************************************************************
     * **************** ---------------------------------- *****************
     * **************** | INVOCATIONS FROM THE MAIN CODE | *****************
     * **************** ---------------------------------- *****************
     * *********************************************************************
     * *********************************************************************
     */
    /**
     * Initializes all the runtime structures and launches the threads.
     *
     */
    public static void startRuntime() {
        (new Thread() {
            public void run() {
                TransferManager.init("NIO", System.getProperty("nio.config"), new Runtime());
            }
        }).start();
        try {
            if (cei == null) {
                cei = new CEI(Class.forName("CEI"));
                if (!CoreManager.isInitialized()) {
                    runtimeService.start(cei);
                    String[] signatures = cei.getAllSignatures();
                    int[] ids = runtimeService.getCoreIds(signatures);
                    for (int i = 0; i < ids.length; i++) {
                        CoreManager.registerSignature(signatures[i], ids[i]);
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            LOGGER.error("Core Element Interface not found. " + e.getMessage());
        }
    }

    public static void unbindRuntime() {
        //No need to do anything for the Java runtime
    }

    /**
     * Registers an object access from the main code of the application.
     *
     * Should be invoked when any object is accessed.
     *
     * @param o Accessed representative object
     * @param isWritter {true} if the access modifies the content of the object
     * @return The current object value
     */
    public static <T> T newObjectAccess(T o, boolean isWritter) {
        if (o == null) {
            return null;
        }
        int dataId = getDataId(o);
        DataInfo data = privateReg.findData(dataId);
        if (data == null) {
            // Data is not in the system return same value
            return o;
        }
        DataAccess da = null;
        try {
            da = privateReg.registerLocalDataAccess(isWritter ? Direction.INOUT : Direction.IN, data);
        } catch (IOException e) {
            LOGGER.fatal("Error obtaining object");
            System.exit(1);
        }
        RegisteredObject<T> rd = (RegisteredObject<T>) data.getCurrentVersion().getValue();
        synchronized (rd) {
            if (!rd.isLocal()) {
                // We bring it
                String inRenaming;
                String outRenaming = "";
                if (isWritter) {
                    DataInstance inInstance = ((ReadWriteAccess) da).getReadDataInstance();
                    DataInstance outInstance = ((ReadWriteAccess) da).getWrittenDataInstance();
                    inRenaming = inInstance.getRenaming();
                    outRenaming = outInstance.getRenaming();
                    if (inInstance != outInstance) {
                        runtimeService.notifyDataCreation(outRenaming, me);
                    }

                } else {
                    inRenaming = ((ReadAccess) da).getReadDataInstance().getRenaming();
                    outRenaming = inRenaming;
                }
                Operation op = new Operation(dataId, outRenaming, false);
                LinkedList<Operation> ops = pendingOperations.get(inRenaming);
                if (ops == null) {
                    ops = new LinkedList<Operation>();
                    pendingOperations.put(inRenaming, ops);
                }
                ops.add(op);
                // We ask for it
                runtimeService.requestDataExistence(inRenaming, me);
            }
        }
        try {
            return rd.getValue();
        } catch (Exception e) {
            LOGGER.fatal("Error obtaining object");
            System.exit(1);
        }
        return null;
    }

    /**
     * Registers an object access from the main code, obtains its value and
     * removes any data stored in the runtime related to it.
     *
     * This method should be called when a task returns a primitive value and
     * this value is recovered by the runtime.
     *
     * @param o Accessed representative object
     * @return final value of the primitive value
     * @throws InterruptedException Interruption while the value is computed or
     * brough back to the master.
     */
    public static <T> T getValueAndRemove(T o)
            throws InterruptedException {

        int dataId = getDataId(o);
        DataInfo data = privateReg.findData(dataId);
        if (data == null) {
            // Data is not in the system return same value
            return null;
        }
        RegisteredObject<T> rd = (RegisteredObject<T>) privateReg.getCurrentVersionValue(data);
        synchronized (rd) {
            if (!rd.isLocal()) {
                String inRenaming = data.getCurrentVersion().getDataInstance().getRenaming();
                Operation op = new Operation(dataId, inRenaming, true);
                LinkedList<Operation> ops = pendingOperations.get(inRenaming);
                if (ops == null) {
                    ops = new LinkedList<Operation>();
                    pendingOperations.put(inRenaming, ops);
                }
                ops.add(op);

                runtimeService.requestDataExistence(inRenaming, me);

            }
        }
        return rd.getValue();
    }

    /**
     * Generates a new task whose execution will be managed by the runtime.
     *
     * @param methodClass name of the class containing the method that has been
     * invoked
     * @param methodName name of the invoked method
     * @param hasTarget the method has been invoked on a callee object
     * @param parameters parameter values
     * @return a unique identifier for the task
     */
    public static int executeTask(String methodClass, String methodName,
            boolean hasTarget, Object... parameters) {
        Parameter[] params = null;
        try {
            params = processParameters(parameters);
        } catch (URISyntaxException | IOException ex) {
            LOGGER.error("Error preparing object parameters for remote execution.", ex);
            System.exit(1);
        }
        Task t = new Task(methodClass, methodName, hasTarget, params);
        runtimeService.executeTask(t);
        return t.getId();
    }

    private static Parameter[] processParameters(Object[] parameters)
            throws URISyntaxException, IOException {
        int parameterCount = parameters.length / ARGUMENTS_PER_PARAMETER;
        Parameter[] params = new Parameter[parameterCount];
        for (int paramIdx = 0; paramIdx < parameterCount; paramIdx++) {
            Type type = (Type) parameters[paramIdx * ARGUMENTS_PER_PARAMETER + ARGUMENT_TYPE_OFFSET];
            Direction direction = (Direction) parameters[paramIdx * ARGUMENTS_PER_PARAMETER + ARGUMENT_DIRECTION_OFFSET];
            switch (type) {
                case OBJECT:
                    Object object = parameters[paramIdx * ARGUMENTS_PER_PARAMETER + ARGUMENT_VALUE_OFFSET];
                    int dataId = getDataId(object);
                    RegisteredObject paramObject = new RegisteredObject(object);
                    DataInfo dataInfo = privateReg.findData(dataId);
                    if (dataInfo == null) {
                        idToRep.put(dataId, object);
                        dataInfo = privateReg.registerData(dataId, paramObject);
                        runtimeService.notifyDataCreation(dataInfo.getCurrentVersion().getDataInstance().getRenaming(), me);
                    }
                    DataAccess da = privateReg.registerRemoteDataAccess(direction, dataInfo, paramObject);
                    params[paramIdx] = new RegisteredParameter(Type.OBJECT, direction, da);
                    break;
                case FILE:
                    params[paramIdx] = new FileParameter(direction, (String) parameters[paramIdx * ARGUMENTS_PER_PARAMETER + ARGUMENT_VALUE_OFFSET]);
                    break;
                default:
                    // Basic Type
                    params[paramIdx] = new BasicTypeParameter(type, Direction.IN, parameters[paramIdx * ARGUMENTS_PER_PARAMETER + ARGUMENT_VALUE_OFFSET]);
            }
        }
        return params;
    }

    /**
     * Indicates that an app does not generate any more tasks thus, all the
     * internal objects can be deleted once all the tasks are done.
     *
     * @param appId Id of the application that ends.
     */
    public void noMoreTasks(long appId) {
        //Not implemented yet
    }

    /**
     * Indicates that a file has to be deleted from the whole system
     *
     * @param fileName name of the file to be rmeoved
     * @return
     */
    public boolean deleteFile(String fileName) {
        //Not implemented yet
        return true;
    }

    /**
     * *********************************************************************
     * *********************************************************************
     * ************* ---------------------------------------- **************
     * ************* | INVOCATIONS FROM OTHER RUNTIME PARTS | **************
     * ************* ---------------------------------------- **************
     * *********************************************************************
     * *********************************************************************
     */
    @Override
    public void init() {
        try {
            TransferManager.startServer(me);
        } catch (CommException e) {
            LOGGER.fatal("Error starting server socket on Application side.", e);
        }
    }

    public void commandReceived(Connection c, Transfer t) {
        try {
            if (t.getObject() instanceof DataTransferRequest) {
                DataTransferRequest dtr = (DataTransferRequest) t.getObject();
                String rData = dtr.getDataSource();
                RegisteredObject rd = (RegisteredObject) privateReg.getRegisteredData(rData);
                if (!rd.isSavedForTransfer()) {
                    rd.saveForTransfer();
                }
                byte[] array = rd.getSerialized();
                c.sendDataArray(array);
                c.finishConnection();
            }
            if (t.getObject() instanceof DataExistenceNotification) {
                c.finishConnection();
                DataExistenceNotification den = (DataExistenceNotification) t.getObject();
                String data = den.getData();
                runtimeService.requestDataLocations(data, me);
            }
            if (t.getObject() instanceof DataSourceResponse) {
                c.finishConnection();
                DataSourceResponse dsr = (DataSourceResponse) t.getObject();
                String data = dsr.getData();
                es.bsc.comm.Node source = dsr.getLocations().iterator().next();
                completeSource((NIONode) source, c);
                Connection cnctn = TransferManager.startConnection(source);
                DataTransferRequest dtr = new DataTransferRequest(data);
                requestedData.put(cnctn, data);
                cnctn.sendCommand(dtr);
                cnctn.receiveDataObject();
            }
        } catch (IOException e) {
            LOGGER.error("Error processing received command.", e);
        }
    }

    @Override
    public void errorHandler(Connection cnctn, Transfer trnsfr, CommException ce) {
        LOGGER.error("Error processing transfer " + trnsfr + " on connection " + cnctn, ce);
    }

    @Override
    public void dataReceived(Connection cnctn, Transfer trnsfr) {
        cnctn.finishConnection();
        String daId = requestedData.remove(cnctn);
        LinkedList<Operation> ops = pendingOperations.get(daId);
        for (Operation op : ops) {
            RegisteredObject rd = (RegisteredObject) privateReg.getRegisteredData(op.target);
            rd.setValue(trnsfr.getObject());
            if (op.destroy) {
                privateReg.deleteData(op.data);
            }
        }

    }

    @Override
    public void writeFinished(Connection cnctn, Transfer trnsfr) {
        //End of transfer submission do nothing
    }

    @Override
    public void connectionFinished(Connection cnctn) {
        //Closed connection
    }

    @Override
    public void shutdown() {
        //Nothing to do on shutdown
    }

    private void completeSource(NIONode node, Connection connection) {
        if (node.ip == null) {
            node.ip = ((NIONode) ((NIOConnection) connection).getNode()).ip;
        }
    }

    private static class Operation {

        private Integer data;
        private String target;
        private boolean destroy;

        public Operation(int data, String target, boolean destroy) {
            this.data = data;
            this.target = target;
            this.destroy = destroy;
        }

        public int getData() {
            return data;
        }

        public String getTarget() {
            return target;
        }

        public boolean isDestroy() {
            return destroy;
        }

        public String toString() {
            return "object " + data + " with renaming " + target + (destroy ? " must be removed" : " shall not be removed");
        }

    }

    private static Integer getDataId(Object o) {
        int hashCode = o.hashCode();
        while (true) {
            Object rep = idToRep.get(hashCode);
            if (rep == null || rep == o) {
                return hashCode;
            }
            hashCode++;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;

namespace dnlib.DotNet {
	///
	/// Method impl attributes, see CorHdr.h/CorMethodImpl
	///
	[Flags]
	public enum MethodImplAttributes : ushort {
		/// Flags about code type.
		CodeTypeMask		= 0x0003,
		/// Method impl is IL.
		IL					= 0x0000,
		/// Method impl is native.
		Native				= 0x0001,
		/// Method impl is OPTIL
		OPTIL				= 0x0002,
		/// Method impl is provided by the runtime.
		Runtime				= 0x0003,

		/// Flags specifying whether the code is managed or unmanaged.
		ManagedMask			= 0x0004,
		/// Method impl is unmanaged, otherwise managed.
		Unmanaged			= 0x0004,
		/// Method impl is managed.
		Managed				= 0x0000,

		/// Indicates method is defined; used primarily in merge scenarios.
		ForwardRef			= 0x0010,
		/// Indicates method sig is not to be mangled to do HRESULT conversion.
		PreserveSig			= 0x0080,

		/// Reserved for internal use.
		InternalCall		= 0x1000,

		/// Method is single threaded through the body.
		Synchronized		= 0x0020,
		/// Method may not be inlined.
		NoInlining			= 0x0008,
		/// Method should be inlined if possible.
		AggressiveInlining	= 0x0100,
		/// Method may not be optimized.
		NoOptimization		= 0x0040,
	}
}


text:
import socket
import asynchat

from barneymc.protocol import bound_buffer
from barneymc.protocol.packet import *

class Client(asynchat.async_chat):
    node = NODE_CLIENT
    stop_packet_loop = False
    connected2 = False

    settings = {
        'port': 25565,
        'debug_in': False,
        'debug_out': False}

    handlers = {}

    def __init__(self, **custom_settings):
        self.rbuff = bound_buffer.BoundBuffer()
        self.settings.update(custom_settings)

        asynchat.async_chat.__init__(self, sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM))
        self.set_terminator(None)

    def log(self, message):
        print '[DEBUG] %s' % (message.encode("ascii", "ignore"))

    #Start a new connection
    def connect2(self):
        self.close()
        self.set_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM))
        try:
            self.connect((self.settings['host'], self.settings['port']))
        except:
            self.handle_error()

    def send_packet(self, packet):
        packet.direction = self.node
        if self.settings['debug_out']:
            print packet
        data = packet.encode()
        self.push(data)

    def collect_incoming_data(self, data):
        self.connected2 = True
        if len(data) > 0:
            self.rbuff.append(data)
            self.rbuff.save()
            while len(self.rbuff.buff) and not self.stop_packet_loop:
                try:
                    p = read_packet(self.rbuff, other_node[self.node])
                    self.rbuff.save()
                    if self.settings['debug_in']:
                        print p

                    self.dispatch_packet(p)

                except bound_buffer.BufferUnderflowException:
                    self.rbuff.revert()
                    return

    def found_terminator(self):
        pass

    def default_handler(self, packet):
        pass

    def reflect(self, packet):
        self.send_packet(packet.clone())

    def print_packet(self, packet):
        print packet

    def handle_error(self):
        raise

    #Dispatch a packet to its handler
    def dispatch_packet(self, p):
        self.handlers.get(p.ident, self.default_handler)(p)


text:
package org.jetbrains.plugins.javaFX.fxml.refs;

import javax.annotation.Nonnull;

import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.PsiReferenceProvider;
import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.util.ProcessingContext;

/**
 * User: anna
 */
class JavaFxSourceReferenceProvider extends PsiReferenceProvider {
  @Nonnull
  @Override
  public PsiReference[] getReferencesByElement(@Nonnull final PsiElement element,
                                               @Nonnull ProcessingContext context) {
    final FileReferenceSet set = new FileReferenceSet(((XmlAttributeValue)element).getValue(), element, 1, null, true);
    return set.getAllReferences();
  }
}


text:
TEST_SUFFIX = $(shell date +%s | base64 | head -c 15)

.PHONY: build
build:
	GO_BUILD_FLAGS="-v" ./build
	./bin/etcd --version
	ETCDCTL_API=3 ./bin/etcdctl version

test:
	$(info log-file: test-$(TEST_SUFFIX).log)
	PASSES='fmt bom dep compile build unit' ./test 2>&1 | tee test-$(TEST_SUFFIX).log
	! grep FAIL -A10 -B50 test-$(TEST_SUFFIX).log

test-all:
	$(info log-file: test-all-$(TEST_SUFFIX).log)
	RELEASE_TEST=y INTEGRATION=y PASSES='build unit release integration_e2e functional' ./test 2>&1 | tee test-all-$(TEST_SUFFIX).log
	! grep FAIL -A10 -B50 test-all-$(TEST_SUFFIX).log

test-proxy:
	$(info log-file: test-proxy-$(TEST_SUFFIX).log)
	PASSES='build grpcproxy' ./test 2>&1 | tee test-proxy-$(TEST_SUFFIX).log
	! grep FAIL -A10 -B50 test-proxy-$(TEST_SUFFIX).log

test-coverage:
	$(info log-file: test-coverage-$(TEST_SUFFIX).log)
	COVERDIR=covdir PASSES='build build_cov cov' ./test 2>&1 | tee test-coverage-$(TEST_SUFFIX).log
	$(shell curl -s https://codecov.io/bash >codecov)
	chmod 700 ./codecov
	./codecov -h
	./codecov -t 6040de41-c073-4d6f-bbf8-d89256ef31e1

# clean up failed tests, logs, dependencies
clean:
	rm -f ./codecov
	rm -f ./*.log
	rm -f ./bin/Dockerfile-release
	rm -rf ./bin/*.etcd
	rm -rf ./gopath
	rm -rf ./release
	rm -f ./integration/127.0.0.1:* ./integration/localhost:*
	rm -f ./clientv3/integration/127.0.0.1:* ./clientv3/integration/localhost:*
	rm -f ./clientv3/ordering/127.0.0.1:* ./clientv3/ordering/localhost:*

# sync with Dockerfile-test, e2e/docker-dns/Dockerfile, e2e/docker-dns-srv/Dockerfile
_GO_VERSION = go1.9.1
ifdef GO_VERSION
	_GO_VERSION = $(GO_VERSION)
endif

# build base container image for testing on Linux
docker-test-build:
	docker build --tag gcr.io/etcd-development/etcd-test:$(_GO_VERSION) --file ./Dockerfile-test .

# e.g.
# gcloud docker -- login -u _json_key -p "$(cat /etc/gcp-key-etcd.json)" https://gcr.io
docker-test-push:
	gcloud docker -- push gcr.io/etcd-development/etcd-test:$(_GO_VERSION)

docker-test-pull:
	docker pull gcr.io/etcd-development/etcd-test:$(_GO_VERSION)

# compile etcd and etcdctl with Linux
docker-test-compile:
	docker run \
	  --rm \
	  --volume=`pwd`/:/etcd \
	  gcr.io/etcd-development/etcd-test:$(_GO_VERSION) \
	  /bin/bash -c "cd /etcd && GO_BUILD_FLAGS=-v ./build && ./bin/etcd --version"

# run tests inside container
docker-test:
	$(info log-file: docker-test-$(TEST_SUFFIX).log)
	docker run \
	  --rm \
	  --volume=`pwd`:/go/src/github.com/coreos/etcd \
	  gcr.io/etcd-development/etcd-test:$(_GO_VERSION) \
	  /bin/bash -c "RELEASE_TEST=y INTEGRATION=y PASSES='build unit release integration_e2e functional' ./test 2>&1 | tee docker-test-$(TEST_SUFFIX).log"
	! grep FAIL -A10 -B50 docker-test-$(TEST_SUFFIX).log

docker-test-386:
	$(info log-file: docker-test-386-$(TEST_SUFFIX).log)
	docker run \
	  --rm \
	  --volume=`pwd`:/go/src/github.com/coreos/etcd \
	  gcr.io/etcd-development/etcd-test:$(_GO_VERSION) \
	  /bin/bash -c "GOARCH=386 PASSES='build unit integration_e2e' ./test 2>&1 | tee docker-test-386-$(TEST_SUFFIX).log"
	! grep FAIL -A10 -B50 docker-test-386-$(TEST_SUFFIX).log

docker-test-proxy:
	$(info log-file: docker-test-proxy-$(TEST_SUFFIX).log)
	docker run \
	  --rm \
	  --volume=`pwd`:/go/src/github.com/coreos/etcd \
	  gcr.io/etcd-development/etcd-test:$(_GO_VERSION) \
	  /bin/bash -c "PASSES='build grpcproxy' ./test ./test 2>&1 | tee docker-test-proxy-$(TEST_SUFFIX).log"
	! grep FAIL -A10 -B50 docker-test-proxy-$(TEST_SUFFIX).log

# build release container image with Linux
_ETCD_VERSION ?= $(shell git rev-parse --short HEAD || echo "GitNotFound")
ifdef ETCD_VERSION
	_ETCD_VERSION = $(ETCD_VERSION)
endif

docker-release-master-build: docker-test-compile
	cp ./Dockerfile-release ./bin/Dockerfile-release
	docker build \
	  --tag gcr.io/etcd-development/etcd:$(_ETCD_VERSION) \
	  --file ./bin/Dockerfile-release \
	  ./bin
	rm -f ./bin/Dockerfile-release

	docker run \
	  --rm \
	  gcr.io/etcd-development/etcd:$(_ETCD_VERSION) \
	  /bin/sh -c "/usr/local/bin/etcd --version && ETCDCTL_API=3 /usr/local/bin/etcdctl version"

docker-release-master-push:
	gcloud docker -- push gcr.io/etcd-development/etcd:$(_ETCD_VERSION)

# build base container image for DNS testing
docker-dns-test-build:
	docker build \
	  --tag gcr.io/etcd-development/etcd-dns-test:$(_GO_VERSION) \
	  --file ./e2e/docker-dns/Dockerfile \
	  ./e2e/docker-dns

	docker run \
	  --rm \
	  --dns 127.0.0.1 \
	  gcr.io/etcd-development/etcd-dns-test:$(_GO_VERSION) \
	  /bin/bash -c "/etc/init.d/bind9 start && cat /dev/null >/etc/hosts && dig etcd.local"

docker-dns-test-push:
	gcloud docker -- push gcr.io/etcd-development/etcd-dns-test:$(_GO_VERSION)

docker-dns-test-pull:
	docker pull gcr.io/etcd-development/etcd-dns-test:$(_GO_VERSION)

# run DNS tests inside container
docker-dns-test-run:
	docker run \
	  --rm \
	  --tty \
	  --dns 127.0.0.1 \
	  --volume=`pwd`/bin:/etcd \
	  --volume=`pwd`/integration/fixtures:/certs \
	  gcr.io/etcd-development/etcd-dns-test:$(_GO_VERSION) \
	  /bin/bash -c "cd /etcd && /run.sh && rm -rf m*.etcd"

# build base container image for DNS/SRV testing
docker-dns-srv-test-build:
	docker build \
	  --tag gcr.io/etcd-development/etcd-dns-srv-test:$(_GO_VERSION) \
	  --file ./e2e/docker-dns-srv/Dockerfile \
	  ./e2e/docker-dns-srv

	docker run \
	  --rm \
	  --dns 127.0.0.1 \
	  gcr.io/etcd-development/etcd-dns-srv-test:$(_GO_VERSION) \
	  /bin/bash -c "/etc/init.d/bind9 start && cat /dev/null >/etc/hosts && dig +noall +answer SRV _etcd-client-ssl._tcp.etcd.local && dig +noall +answer SRV _etcd-server-ssl._tcp.etcd.local && dig +noall +answer m1.etcd.local m2.etcd.local m3.etcd.local"

docker-dns-srv-test-push:
	gcloud docker -- push gcr.io/etcd-development/etcd-dns-srv-test:$(_GO_VERSION)

docker-dns-srv-test-pull:
	docker pull gcr.io/etcd-development/etcd-dns-srv-test:$(_GO_VERSION)

# run DNS/SRV tests inside container
docker-dns-srv-test-run:
	docker run \
	  --rm \
	  --tty \
	  --dns 127.0.0.1 \
	  --volume=`pwd`/bin:/etcd \
	  --volume=`pwd`/integration/fixtures:/certs \
	  gcr.io/etcd-development/etcd-dns-srv-test:$(_GO_VERSION) \
	  /bin/bash -c "cd /etcd && /run.sh && rm -rf m*.etcd"

# TODO: add DNS integration tests


text:
import dom from 'jsx-render'
import JSXComponent from 'jsx-render/lib/JSXComponent'

import Pages from './pages'

class Header extends JSXComponent {
  static menuClick() {
    const menu = document.querySelector('.pages')

    menu.classList.toggle('show')
  }

  render() {
    return (

        <button className="menu-button" ref={super.ref} onClick={Header.menuClick}>

        </button>

            <Pages />

Josh Hoegen » )'( » ♫ » ♥ »

    )
  }
}

export default Header


text:
'use strict';
var inherits = require('util').inherits,
  EventEmitter = require('events').EventEmitter;

module.exports = PulledJob;

function PulledJob(id, state) {
  this.id = id;
  this.state = state;
  this.name = state.name;
  this.payload = state.payload;
}
inherits(PulledJob, EventEmitter);

PulledJob.prototype.complete = function (result) {
  var self = this;
  process.nextTick(function () {
    self.emit('complete', result);
    self.close();
  })
}

PulledJob.prototype.progress = function (completed, total) {
  var self = this;
  process.nextTick(function () {
    self.emit('progress', completed, total);
  })
}

PulledJob.prototype.fail = function (err) {
  var self = this;

  process.nextTick(function () {
    if (++self.state.attempts < self.state.maxAttempts) {
      var restartAt = new Date().getTime(),
        backoff = self.state.backoff;

      if (backoff === true)
        restartAt += self.state.delay || 0;
      else if (backoff && backoff.type == 'fixed' && backoff.delay)
        restartAt += backoff.delay;
      else if (backoff && backoff.type == 'exponential' && (backoff.delay || self.state.delay))
        restartAt += Math.round( (backoff.delay || self.state.delay) * 0.5 * ( Math.pow(2, self.state.attempts) - 1) );

      self.emit('failedAttempt', restartAt, err);
      return self.close();
    }

    self.emit('failed', err);
    self.close();
  })
}

PulledJob.prototype.close = function () {
  this.emit('close');
  this.removeAllListeners();
}


text:
class SomeBase {
    static GetNumber() {
        return 2;
    }
}
class P extends SomeBase {
    static SomeNumber = P.GetNumber();
}

//// [staticMemberAccessOffDerivedType1.js]
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var SomeBase = (function () {
    function SomeBase() {
    }
    SomeBase.GetNumber = function () {
        return 2;
    };
    return SomeBase;
}());
var P = (function (_super) {
    __extends(P, _super);
    function P() {
        _super.apply(this, arguments);
    }
    return P;
}(SomeBase));
P.SomeNumber = P.GetNumber();


text:
set -e

if [[ "$*" == "id" ]]; then
	# Have a way to determine the uid under which volume mounts get mounted
    stat -c "%u" /minishift-docs
elif [ "$(id -u)" = '0' ]; then
	echo "Image cannot be run as root. Use -u option of 'docker run' to specify a uid."
	exit -1
else
	BUNDLER_HOME="/tmp/bundler/home"
	mkdir -p $BUNDLER_HOME
    cd $DOCS_CONTENT && HOME="$BUNDLER_HOME" /usr/local/bin/rake "$@"
fi


text:
<?xml version="1.0" encoding="UTF-8" ?>
  <skin version="0" xmlns="http://xsml.org/ns/0/">
  <width>160</width>
  <height>210</height>
 <name>
LezAmp
</name>
<email>
contact@lacymorrow.com
</email>
 <objects>
  <background image="images/MiniAMPcast.png" shape="rectRounded" />
  <playlist x="6" y="57" width="130" height="85" selectedColor="ffffff" size="10" font="Arial" color="2871e9" />
  <object label="playButton" x="48" y="173" width="11" height="11" color="ffffff" hoverMessage="Play" />
  <object label="stopButton" x="73" y="175" width="8" height="8" color="ffffff" hoverMessage="Stop" />
  <object label="prevButton" x="19" y="175" width="10" height="8" color="ffffff" hoverMessage="Previous" />
  <object label="fwdButton" x="98" y="175" width="10" height="8" color="ffffff" hoverMessage="Forward" />
  <object label="shuffleButton" x="220" y="173" width="13" height="13" color="ffffff"  hoverMessage="Shuffle" />
  <object label="trackDisplay" x="10" y="25" width="137" height="12" size="10" font="Arial" color="ffffff" />
  <object label="loadBar" x="11" y="150" color="010101" width="138" height="5"  />
  <object label="timeBar" x="11" y="150" width="138" height="5" color="2871e9" />
  <object label="scrollButton" x="145" y="62" width="10" height="80" color="2871e9" alpha="" bgAlpha="0" />
  <object label="volumeDisplay" x="107" y="43" width="40" height="8" color="2871e9" />
  <object label="timeDisplay" x="18" y="40" size="10" font="Arial" color="ffffff" />
  <object label="startButton" width="160" height="210" alpha="0" />
  </objects>
  </skin>


text:
package heng.shi.service;

import heng.shi.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;

/**
 * @author Rob Winch
 */
@Service
public class UserRepositoryUserDetailsService implements UserDetailsService {
    @Autowired
    private UserService userService;

    /*
     * (non-Javadoc)
     *
     * @see
     * org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername
     * (java.lang.String)
     */
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        User user = this.userService.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("Could not find user " + username);
        }
        return new CustomUserDetails(user);
    }

    private final static class CustomUserDetails extends User implements UserDetails {
        private static final long serialVersionUID = 5639683223516504866L;

        private CustomUserDetails(User user) {
            super(user);
        }

        public Collection<? extends GrantedAuthority> getAuthorities() {
            return AuthorityUtils.createAuthorityList("ROLE_USER");
        }

        public boolean isAccountNonExpired() {
            return true;
        }

        public boolean isAccountNonLocked() {
            return true;
        }

        public boolean isCredentialsNonExpired() {
            return true;
        }

        public boolean isEnabled() {
            return true;
        }
    }
}


text:
#include <yatl/lite.h>
#include "tests/unit/common.h"

#include <libdrizzle-redux/libdrizzle.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const drizzle_column_type_t column_types[] = {
    DRIZZLE_COLUMN_TYPE_DECIMAL,     DRIZZLE_COLUMN_TYPE_TINY,
    DRIZZLE_COLUMN_TYPE_SHORT,       DRIZZLE_COLUMN_TYPE_LONG,
    DRIZZLE_COLUMN_TYPE_FLOAT,       DRIZZLE_COLUMN_TYPE_DOUBLE,
    DRIZZLE_COLUMN_TYPE_NULL,        DRIZZLE_COLUMN_TYPE_TIMESTAMP,
    DRIZZLE_COLUMN_TYPE_LONGLONG,    DRIZZLE_COLUMN_TYPE_INT24,
    DRIZZLE_COLUMN_TYPE_DATE,        DRIZZLE_COLUMN_TYPE_TIME,
    DRIZZLE_COLUMN_TYPE_DATETIME,    DRIZZLE_COLUMN_TYPE_YEAR,
    DRIZZLE_COLUMN_TYPE_NEWDATE,     DRIZZLE_COLUMN_TYPE_VARCHAR,
    DRIZZLE_COLUMN_TYPE_BIT,         DRIZZLE_COLUMN_TYPE_TIMESTAMP2,
    DRIZZLE_COLUMN_TYPE_DATETIME2,   DRIZZLE_COLUMN_TYPE_TIME2,
    DRIZZLE_COLUMN_TYPE_NEWDECIMAL,  DRIZZLE_COLUMN_TYPE_ENUM,
    DRIZZLE_COLUMN_TYPE_SET,         DRIZZLE_COLUMN_TYPE_TINY_BLOB,
    DRIZZLE_COLUMN_TYPE_MEDIUM_BLOB, DRIZZLE_COLUMN_TYPE_LONG_BLOB,
    DRIZZLE_COLUMN_TYPE_BLOB,        DRIZZLE_COLUMN_TYPE_VAR_STRING,
    DRIZZLE_COLUMN_TYPE_STRING,      DRIZZLE_COLUMN_TYPE_GEOMETRY
  };

const char *column_type_names[] = {
    "DECIMAL",    "TINY", "SHORT",      "LONG",      "FLOAT",
    "DOUBLE",     "NULL", "TIMESTAMP",  "LONGLONG",  "INT24",
    "DATE",       "TIME", "DATETIME",   "YEAR",      "NEWDATE",
    "VARCHAR",    "BIT",  "TIMESTAMP2", "DATETIME2", "TIME2",
    "NEWDECIMAL", "ENUM", "SET",        "TINY_BLOB", "MEDIUM_BLOB",
    "LONG_BLOB",  "BLOB", "VAR_STRING", "STRING",    "GEOMETRY"};

int main(int argc, char *argv[])
{
  (void)argc;
  (void)argv;
  drizzle_row_t row;
  int num_fields;
  drizzle_result_st *result;
  drizzle_return_t driz_ret;

  set_up_connection();
  CHECKED_QUERY("SET CHARACTER SET latin1"); /* Or any other one-byte-per-character
                                                character set */
  set_up_schema("test_column");

  CHECKED_QUERY("CREATE TABLE test_column.t1 (a INT PRIMARY KEY AUTO_INCREMENT, "
		"b VARCHAR(255), c TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");

  CHECKED_QUERY("INSERT INTO test_column.t1 (b) VALUES ('this'),('is'),('war')");

  CHECKED_QUERY("SELECT * FROM test_column.t1");

  drizzle_result_buffer(result);
  num_fields = drizzle_result_column_count(result);

  ASSERT_EQ_(num_fields, 3, "Retrieved bad number of fields");

  int i = 0;
  drizzle_column_st *column;
  while ((row = drizzle_row_next(result)))
  {
    drizzle_column_seek(result, 0);
    int cur_column = 0;
    i++;
    char buf[10];
    snprintf(buf, sizeof(buf), "%d", i);
    ASSERT_EQ_(strcmp(row[0], buf), 0, "Retrieved bad row value");
    while ((column= drizzle_column_next(result)))
    {
      cur_column++;
      ASSERT_EQ_(strcmp(drizzle_column_db(column), "test_column"), 0,
                 "Column has bad DB name");
      ASSERT_EQ_(strcmp(drizzle_column_table(column), "t1"), 0,
                 "Column had bad table name");
      switch (cur_column) {
      case 1:
        ASSERT_EQ_(drizzle_column_type(column), DRIZZLE_COLUMN_TYPE_LONG,
                   "Column type wrong");
        break;
      case 2:
        ASSERT_EQ_(drizzle_column_max_size(column), 255,
                   "Column max size wrong %lu != 255",
                   drizzle_column_max_size(column));

        ASSERT_EQ_(drizzle_column_charset(column), DRIZZLE_CHARSET_LATIN1_SWEDISH_CI,
                   "Column charset wrong, %d != %d", drizzle_column_charset(column),
                   DRIZZLE_CHARSET_LATIN1_SWEDISH_CI);
        break;
      case 3:
        ASSERT_EQ_(drizzle_column_type(column), DRIZZLE_COLUMN_TYPE_TIMESTAMP,
                   "Column type wrong");
        break;
      }
    }
    ASSERT_EQ_(cur_column, 3, "Wrong column count");
  }
  /* Should have had 3 rows */
  ASSERT_EQ_(i, 3, "Retrieved bad number of rows");

  drizzle_result_free(result);

  CHECKED_QUERY("DROP TABLE test_column.t1");

  tear_down_schema("test_column");

  /* Check that column type is resolved to the correct string representation */
  for (i = 0; i < 30; i++)
  {
    ASSERT_STREQ_(drizzle_column_type_str(column_types[i]), column_type_names[i],
                  "Column type 'DRIZZLE_COLUMN_TYPE_%s' resolved to wrong name: '%s'",
                  column_type_names[i], drizzle_column_type_str(column_types[i]));
  }

  return EXIT_SUCCESS;
}


text:
package ipmi.transport;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

/**
 * Handles the UDP connection.
 */
public class UdpMessenger extends Thread implements Messenger {

	private int port;

	private DatagramSocket socket;

	private List<UdpListener> listeners;

	private boolean closing = false;

	private static final String DEFAULT_ADDRESS = "0.0.0.0";

	/**
	 * Size of the message data buffer. Default
	 * {@link UdpMessenger#DEFAULTBUFFERSIZE}.
	 */
	private int bufferSize;

	private static final int DEFAULTBUFFERSIZE = 512;

	private static Logger logger = Logger.getLogger(UdpMessenger.class);

	public int getPort() {
		return port;
	}

	/**
	 * Initiates UdpMessenger, binds it to the specified port and starts
	 * listening. Wildcard IP address will be used.
	 *
	 * @param port
	 *            - port to bind socket to.
	 * @throws SocketException
	 *             if the socket could not be opened, or the socket could not
	 *             bind to the specified local port.
	 * @throws UnknownHostException
	 */
	public UdpMessenger(int port) throws SocketException, UnknownHostException {
		this(port, InetAddress.getByName(DEFAULT_ADDRESS));
	}

	/**
	 * Initiates UdpMessenger, binds it to the specified port and IP address and
	 * starts listening.
	 *
	 * @param port
	 *            - port to bind socket to.
	 * @param address
	 *            - IP address to bind socket to.
	 * @throws SocketException
	 *             if the socket could not be opened, or the socket could not
	 *             bind to the specified local port.
	 */
	public UdpMessenger(int port, InetAddress address) throws SocketException {
		sentPackets = 0;
		this.port = port;
		listeners = new ArrayList<UdpListener>();
		bufferSize = DEFAULTBUFFERSIZE;
		socket = new DatagramSocket(this.port, address);
		socket.setSoTimeout(0);
		this.start();
	}

	/**
	 * Sets message data buffer size to bufferSize.
	 */
	public void setBufferSize(int bufferSize) {
		this.bufferSize = bufferSize;
	}

	/**
	 * @return Size of the message data buffer
	 */
	public int getBufferSize() {
		return bufferSize;
	}

	@Override
	public void run() {
		super.run();

		boolean run = true;

		while (run) {
			DatagramPacket response = new DatagramPacket(new byte[512], 512);

			try {
				socket.receive(response);
				UdpMessage message = new UdpMessage();
				message.setAddress(response.getAddress());
				message.setPort(response.getPort());
				byte[] buffer = new byte[response.getLength()];
				System.arraycopy(response.getData(), 0, buffer, 0,
						buffer.length);
				message.setMessage(buffer);

				synchronized (listeners) {
					for (UdpListener listener : listeners) {
						if (listener != null) {
							listener.notifyMessage(message);
						}
					}
				}

			} catch (SocketException se) {
				if (closing) {
					run = false;
				} else {
					logger.error(se.getMessage(), se);
				}
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			} finally {
				if (socket.isClosed()) {
					run = false;
				}
			}
		}
	}

	/**
	 * Closes the socket and releases port.
	 */
	public void closeConnection() {
		closing = true;
		socket.close();
	}

	/**
	 * Registers listener in the UdpMessenger so it will be notified via
	 * {@link UdpListener#notifyMessage(UdpMessage)} when new message arrives.
	 *
	 * @param listener
	 *            - {@link UdpListener} to register.
	 */
	public void register(UdpListener listener) {
		synchronized (listeners) {
			listeners.add(listener);
		}
	}

	/**
	 * Unregisters listener from UdpMessenger so it no longer will be notified.
	 *
	 * @param listener
	 *            - {@link UdpListener} to unregister
	 */
	public void unregister(UdpListener listener) {
		synchronized (listeners) {
			listeners.remove(listener);
		}
	}

	private static int sentPackets = 0;

	/**
	 * Returns number of packets sent since last creation of the instance of
	 * {@link UdpMessenger}. For debug/testing purposes only.
	 */
	public static int getSentPackets() {
		return sentPackets;
	}

	/**
	 * Sends {@link UdpMessage}.
	 *
	 * @param message
	 *            - {@link UdpMessage} to send.
	 * @throws IOException
	 *             when sending of the message fails
	 */
	public synchronized void send(UdpMessage message) throws IOException {
		DatagramPacket packet = new DatagramPacket(message.getMessage(),
				message.getMessage().length, message.getAddress(),
				message.getPort());
		socket.send(packet);
		try {
			Thread.sleep(1);
		} catch (InterruptedException e) {
			// TODO: log
		}
		++sentPackets;
	}
}


text:
#include "cairoint.h"

/*
 * This structure, and accompanying table, is borrowed/modified from the
 * file xserver/render/glyph.c in the freedesktop.org x server, with
 * permission (and suggested modification of doubling sizes) by Keith
 * Packard.
 */

static const cairo_cache_arrangement_t cache_arrangements [] = {
    { 16,		43,		41        },
    { 32,		73,		71        },
    { 64,		151,		149       },
    { 128,		283,		281       },
    { 256,		571,		569       },
    { 512,		1153,		1151      },
    { 1024,		2269,		2267      },
    { 2048,		4519,		4517      },
    { 4096,		9013,		9011      },
    { 8192,		18043,		18041     },
    { 16384,		36109,		36107     },
    { 32768,		72091,		72089     },
    { 65536,		144409,		144407    },
    { 131072,		288361,		288359    },
    { 262144,		576883,		576881    },
    { 524288,		1153459,	1153457   },
    { 1048576,		2307163,	2307161   },
    { 2097152,		4613893,	4613891   },
    { 4194304,		9227641,	9227639   },
    { 8388608,		18455029,	18455027  },
    { 16777216,		36911011,	36911009  },
    { 33554432,		73819861,	73819859  },
    { 67108864,		147639589,	147639587 },
    { 134217728,	295279081,	295279079 },
    { 268435456,	590559793,	590559791 }
};

#define N_CACHE_SIZES (sizeof(cache_arrangements)/sizeof(cache_arrangements[0]))

/*
 * Entries 'e' are poiners, in one of 3 states:
 *
 * e == NULL: The entry has never had anything put in it
 * e != DEAD_ENTRY: The entry has an active value in it currently
 * e == DEAD_ENTRY: The entry *had* a value in it at some point, but the
 *                  entry has been killed. Lookups requesting free space can
 *                  reuse these entries; lookups requesting a precise match
 *                  should neither return these entries nor stop searching when
 *                  seeing these entries.
 *
 * We expect keys will not be destroyed frequently, so our table does not
 * contain any explicit shrinking code nor any chain-coalescing code for
 * entries randomly deleted by memory pressure (except during rehashing, of
 * course). These assumptions are potentially bad, but they make the
 * implementation straightforward.
 *
 * Revisit later if evidence appears that we're using excessive memory from
 * a mostly-dead table.
 *
 * Generally you do not need to worry about freeing cache entries; the
 * cache will expire entries randomly as it experiences memory pressure.
 * If max_memory is set, entries are not expired, and must be explicitely
 * removed.
 *
 * This table is open-addressed with double hashing. Each table size is a
 * prime chosen to be a little more than double the high water mark for a
 * given arrangement, so the tables should remain < 50% full. The table
 * size makes for the "first" hash modulus; a second prime (2 less than the
 * first prime) serves as the "second" hash modulus, which is co-prime and
 * thus guarantees a complete permutation of table indices.
 *
 */

#define DEAD_ENTRY ((cairo_cache_entry_base_t *) 1)
#define NULL_ENTRY_P(cache, i) ((cache)->entries[i] == NULL)
#define DEAD_ENTRY_P(cache, i) ((cache)->entries[i] == DEAD_ENTRY)
#define LIVE_ENTRY_P(cache, i) \
 (!((NULL_ENTRY_P((cache),(i))) || (DEAD_ENTRY_P((cache),(i)))))

#ifdef NDEBUG
#define _cache_sane_state(c)
#else
static void
_cache_sane_state (cairo_cache_t *cache)
{
    assert (cache != NULL);
    assert (cache->entries != NULL);
    assert (cache->backend != NULL);
    assert (cache->arrangement != NULL);
    /* Cannot check this, a single object may larger */
    /* assert (cache->used_memory <= cache->max_memory); */
    assert (cache->live_entries <= cache->arrangement->size);
}
#endif

static void
_entry_destroy (cairo_cache_t *cache, unsigned long i)
{
    _cache_sane_state (cache);

    if (LIVE_ENTRY_P(cache, i))
    {
	cairo_cache_entry_base_t *entry = cache->entries[i];
	assert(cache->live_entries > 0);
	assert(cache->used_memory >= entry->memory);

	cache->live_entries--;
 	cache->used_memory -= entry->memory;
	cache->backend->destroy_entry (cache, entry);
	cache->entries[i] = DEAD_ENTRY;
    }
}

static cairo_cache_entry_base_t **
_cache_lookup (cairo_cache_t *cache,
	       void *key,
	       int (*predicate)(void*,void*,void*))
{

    cairo_cache_entry_base_t **probe;
    unsigned long hash;
    unsigned long table_size, i, idx, step;

    _cache_sane_state (cache);
    assert (key != NULL);

    table_size = cache->arrangement->size;
    hash = cache->backend->hash (cache, key);
    idx = hash % table_size;
    step = 0;

    for (i = 0; i < table_size; ++i)
    {
#ifdef CAIRO_MEASURE_CACHE_PERFORMANCE
	cache->probes++;
#endif
	assert(idx < table_size);
	probe = cache->entries + idx;

	/*
	 * There are two lookup modes: searching for a free slot and searching
	 * for an exact entry.
	 */

	if (predicate != NULL)
	{
	    /* We are looking up an exact entry. */
	    if (*probe == NULL)
	    {
		/* Found an empty spot, there can't be a match */
		break;
	    }
	    else if (*probe != DEAD_ENTRY
		     && (*probe)->hashcode == hash
		     && predicate (cache, key, *probe))
	    {
		return probe;
	    }
	}
	else
	{
	    /* We are just looking for a free slot. */
	    if (*probe == NULL
		|| *probe == DEAD_ENTRY)
	    {
		return probe;
	    }
	}

	if (step == 0) {
	    step = hash % cache->arrangement->rehash;
	    if (step == 0)
		step = 1;
	}

	idx += step;
	if (idx >= table_size)
	    idx -= table_size;
    }

    /*
     * The table should not have permitted you to get here if you were just
     * looking for a free slot: there should have been room.
     */
    assert(predicate != NULL);
    return NULL;
}

static cairo_cache_entry_base_t **
_find_available_entry_for (cairo_cache_t *cache,
			   void *key)
{
    return _cache_lookup (cache, key, NULL);
}

static cairo_cache_entry_base_t **
_find_exact_live_entry_for (cairo_cache_t *cache,
			    void *key)
{
    return _cache_lookup (cache, key, cache->backend->keys_equal);
}

static const cairo_cache_arrangement_t *
_find_cache_arrangement (unsigned long proposed_size)
{
    unsigned long idx;

    for (idx = 0; idx < N_CACHE_SIZES; ++idx)
	if (cache_arrangements[idx].high_water_mark >= proposed_size)
	    return &cache_arrangements[idx];
    return NULL;
}

static cairo_status_t
_resize_cache (cairo_cache_t *cache, unsigned long proposed_size)
{
    cairo_cache_t tmp;
    cairo_cache_entry_base_t **e;
    unsigned long new_size, i;

    tmp = *cache;
    tmp.arrangement = _find_cache_arrangement (proposed_size);
    assert(tmp.arrangement != NULL);
    if (tmp.arrangement == cache->arrangement)
	return CAIRO_STATUS_SUCCESS;

    new_size = tmp.arrangement->size;
    tmp.entries = calloc (new_size, sizeof (cairo_cache_entry_base_t *));
    if (tmp.entries == NULL)
	return CAIRO_STATUS_NO_MEMORY;

    for (i = 0; i < cache->arrangement->size; ++i) {
	if (LIVE_ENTRY_P(cache, i)) {
	    e = _find_available_entry_for (&tmp, cache->entries[i]);
	    assert (e != NULL);
	    *e = cache->entries[i];
	}
    }
    free (cache->entries);
    cache->entries = tmp.entries;
    cache->arrangement = tmp.arrangement;
    return CAIRO_STATUS_SUCCESS;
}

#ifdef CAIRO_MEASURE_CACHE_PERFORMANCE
static double
_load_factor (cairo_cache_t *cache)
{
    return ((double) cache->live_entries)
	/ ((double) cache->arrangement->size);
}
#endif

/* Find a random in the cache matching the given predicate. We use the
 * same algorithm as the probing algorithm to walk over the entries in
 * the hash table in a pseudo-random order. Walking linearly would
 * favor entries following gaps in the hash table. We could also
 * call rand() repeatedly, which works well for almost-full tables,
 * but degrades when the table is almost empty, or predicate
 * returns false for most entries.
 */
static cairo_cache_entry_base_t **
_random_entry (cairo_cache_t *cache,
	       int (*predicate)(void*))
{
    cairo_cache_entry_base_t **probe;
    unsigned long hash;
    unsigned long table_size, i, idx, step;

    _cache_sane_state (cache);

    table_size = cache->arrangement->size;
    hash = rand ();
    idx = hash % table_size;
    step = 0;

    for (i = 0; i < table_size; ++i)
    {
	assert(idx < table_size);
	probe = cache->entries + idx;

	if (LIVE_ENTRY_P(cache, idx)
	    && (!predicate || predicate (*probe)))
	    return probe;

	if (step == 0) {
	    step = hash % cache->arrangement->rehash;
	    if (step == 0)
		step = 1;
	}

	idx += step;
	if (idx >= table_size)
	    idx -= table_size;
    }

    return NULL;
}

/* public API follows */

cairo_status_t
_cairo_cache_init (cairo_cache_t *cache,
		   const cairo_cache_backend_t *backend,
		   unsigned long max_memory)
{
    assert (backend != NULL);

    if (cache != NULL){
	cache->arrangement = &cache_arrangements[0];
	cache->max_memory = max_memory;
	cache->used_memory = 0;
	cache->live_entries = 0;

#ifdef CAIRO_MEASURE_CACHE_PERFORMANCE
	cache->hits = 0;
	cache->misses = 0;
	cache->probes = 0;
#endif

	cache->backend = backend;
	cache->entries = calloc (cache->arrangement->size,
				 sizeof(cairo_cache_entry_base_t *));

	if (cache->entries == NULL)
	    return CAIRO_STATUS_NO_MEMORY;
    }
    _cache_sane_state (cache);
    return CAIRO_STATUS_SUCCESS;
}

void
_cairo_cache_destroy (cairo_cache_t *cache)
{
    unsigned long i;
    if (cache == NULL)
	return;

    _cache_sane_state (cache);

    for (i = 0; i < cache->arrangement->size; ++i)
	_entry_destroy (cache, i);

    free (cache->entries);
    cache->entries = NULL;
    cache->backend->destroy_cache (cache);
}

void
_cairo_cache_shrink_to (cairo_cache_t *cache,
			unsigned long max_memory)
{
    unsigned long idx;
    /* Make some entries die if we're under memory pressure. */
    while (cache->live_entries > 0 && cache->used_memory > max_memory) {
	idx =  _random_entry (cache, NULL) - cache->entries;
	assert (idx < cache->arrangement->size);
	_entry_destroy (cache, idx);
    }
}

cairo_status_t
_cairo_cache_lookup (cairo_cache_t *cache,
		     void          *key,
		     void         **entry_return,
		     int           *created_entry)
{

    cairo_status_t status = CAIRO_STATUS_SUCCESS;
    cairo_cache_entry_base_t **slot = NULL, *new_entry;

    _cache_sane_state (cache);

#ifdef CAIRO_MEASURE_CACHE_PERFORMANCE
    if ((cache->hits + cache->misses) % 0xffff == 0)
	printf("cache %p stats: size %ld, live %ld, load %.2f\n"
	       "                      mem %ld/%ld, hit %ld, miss %ld\n"
	       "                      probe %ld, %.2f probe/access\n",
	       cache,
	       cache->arrangement->size,
	       cache->live_entries,
	       _load_factor (cache),
	       cache->used_memory,
	       cache->max_memory,
	       cache->hits,
	       cache->misses,
	       cache->probes,
	       ((double) cache->probes)
	       / ((double) (cache->hits +
			    cache->misses + 1)));
#endif

    /* See if we have an entry in the table already. */
    slot = _find_exact_live_entry_for (cache, key);
    if (slot != NULL) {
#ifdef CAIRO_MEASURE_CACHE_PERFORMANCE
	cache->hits++;
#endif
	*entry_return = *slot;
	if (created_entry)
	    *created_entry = 0;
	return status;
    }

#ifdef CAIRO_MEASURE_CACHE_PERFORMANCE
    cache->misses++;
#endif

    /* Build the new entry. */
    status = cache->backend->create_entry (cache, key,
					   (void **)&new_entry);
    if (status != CAIRO_STATUS_SUCCESS)
	return status;

    /* Store the hash value in case the backend forgot. */
    new_entry->hashcode = cache->backend->hash (cache, key);

    if (cache->live_entries && cache->max_memory)
        _cairo_cache_shrink_to (cache, cache->max_memory);

    /* Can't assert this; new_entry->memory may be larger than max_memory */
    /* assert(cache->max_memory >= (cache->used_memory + new_entry->memory)); */

    /* Make room in the table for a new slot. */
    status = _resize_cache (cache, cache->live_entries + 1);
    if (status != CAIRO_STATUS_SUCCESS) {
	cache->backend->destroy_entry (cache, new_entry);
	return status;
    }

    slot = _find_available_entry_for (cache, key);
    assert(slot != NULL);

    /* Store entry in slot and increment statistics. */
    *slot = new_entry;
    cache->live_entries++;
    cache->used_memory += new_entry->memory;

    _cache_sane_state (cache);

    *entry_return = new_entry;
    if (created_entry)
      *created_entry = 1;

    return status;
}

cairo_status_t
_cairo_cache_remove (cairo_cache_t *cache,
		     void          *key)
{
    cairo_cache_entry_base_t **slot;

    _cache_sane_state (cache);

    /* See if we have an entry in the table already. */
    slot = _find_exact_live_entry_for (cache, key);
    if (slot != NULL)
      	_entry_destroy (cache, slot - cache->entries);

    return CAIRO_STATUS_SUCCESS;
}

void *
_cairo_cache_random_entry (cairo_cache_t *cache,
			   int (*predicate)(void*))
{
    cairo_cache_entry_base_t **slot = _random_entry (cache, predicate);

    return slot ? *slot : NULL;
}

unsigned long
_cairo_hash_string (const char *c)
{
    /* This is the djb2 hash. */
    unsigned long hash = 5381;
    while (c && *c)
	hash = ((hash << 5) + hash) + *c++;
    return hash;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Installation of Jekyll on Mac is usually less problematic than on Windows. However, you may run into permissions issues with Ruby that you must overcome. You...">
<meta name="keywords" content="getting_startedtroubleshooting,  ">
<title>Install Jekyll on Mac  | Jekyll theme for designers</title>
<link rel="stylesheet" href="/documentation-theme-jekyll/css/syntax.css">

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

<link rel="stylesheet" href="/documentation-theme-jekyll/css/modern-business.css">
<link rel="stylesheet" href="/documentation-theme-jekyll/css/lavish-bootstrap.css">
<link rel="stylesheet" href="/documentation-theme-jekyll/css/customstyles.css">
<link rel="stylesheet" href="/documentation-theme-jekyll/css/theme-blue.css">

<link rel="shortcut icon" href="/documentation-theme-jekyll/images/favicon.ico">

<link rel="alternate" type="application/rss+xml" title="" href="http://idratherbewriting.com/documentation-theme-jekyll/feed.xml">

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                Toggle navigation

            </button>
              N3N Documentation

                    WIZEYE

WIZEYE1.5.4

Manual Download

                    INNOWATCH

INNOWATCH 3.0.4

Manual Download

 Feedback

                        <input type="text" id="search-input" placeholder="search...">

WIZEYE 1.5.4

        Operation

Quick Start

WIZEYE 시작

WIZEYE 접속 방법 및 로그인

화면 구성 및 운영

사용자 관리

VIEW 구성 및 운영

CELL 운영

Contents 생성

참조

        Installation

설치 전 준비

설치

Collector 설치

Uninstall

Install Jekyll on Mac

Installation of Jekyll on Mac is usually less problematic than on Windows. However, you may run into permissions issues with Ruby that you must overcome. You should also use Bundler to be sure that you have all the required gems and other utilities on your computer to make the project run.

     Edit me

Ruby and RubyGems

Ruby and RubyGems are usually installed by default on Macs. Open your Terminal and type which ruby and  which gem to confirm that you have Ruby and Rubygems. You should get a response indicating the location of Ruby and Rubygems.

If you get responses that look like this:

/usr/local/bin/ruby

and

/usr/local/bin/gem

Great! Skip down to the Bundler section.

However, if your location is something like /Users/MacBookPro/.rvm/rubies/ruby-2.2.1/bin/gem, which points to your system location of Rubygems, you will likely run into permissions errors when trying to get a gem. A sample permissions error (triggered when you try to install the jekyll gem such as gem install jekyll) might look like this for Rubygems:

 >ERROR:  While executing gem ... (Gem::FilePermissionError)
  You don't have write permissions for the /Library/Ruby/Gems/2.0.0 directory.

Instead of changing the write permissions on your operating system's version of Ruby and Rubygems (which could pose security issues), you can install another instance of Ruby (one that is writable) to get around this.

Install Homebrew

Homebrew is a package manager for the Mac, and you can use it to install an alternative instance of Ruby code. To install Homebrew, run this command:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

If you already had Homebrew installed on your computer, be sure to update it:

brew update

Install Ruby through Homebrew

Now use Homebrew to install Ruby:

brew install ruby

Log out of terminal, and then then log back in.

When you type which ruby and which gem, you should get responses like this:

/usr/local/bin/ruby

And this:

/usr/local/bin/gem

Now Ruby and Rubygems are installed under your username, so these directories are writeable.

Note that if you don't see these paths, try restarting your computer or try installing rbenv, which is a Ruby version management tool. If you still have issues getting a writeable version of Ruby, you need to resolve them before installing Bundler.

Install the Jekyll gem

At this point you should have a writeable version of Ruby and Rubygem on your machine.

Now use gem to install Jekyll:

gem install jekyll

You can now use Jekyll to create new Jekyll sites following the quick-start instructions on Jekyllrb.com.

Installing dependencies through Bundler

Some Jekyll themes will require certain Ruby gem dependencies. These dependencies are stored in something called a Gemfile, which is packaged with the Jekyll theme. You can install these dependencies through Bundler. (Although you don't need to install Bundler for this Documentation theme, it's a good idea to do so.)

Bundler is a package manager for RubyGems. You can use it to get all the gems (or Ruby plugins) that you need for your Jekyll project.

You install Bundler by using the gem command with RubyGems:

gem install bundler

If you're prompted to switch to superuser mode (sudo) to get the correct permissions to install Bundler in that directory, avoid doing this. All other applications that need to use Bundler will likely not have the needed permissions to run.

Bundler goes out and retreives all the gems that are specified in a Jekyll project's Gemfile. If you have a gem that depends on other gems to work, Bundler will go out and retrieve all of the dependencies as well. (To learn more about Bundler, see About Ruby, Gems, Bundler, etc..

The vanilla Jekyll site you create through jekyll new my-awesome-site doesn't have a Gemfile, but many other themes (including the Documentation theme for Jekyll) do have a Gemfile.

Serve the Jekyll Documentation theme

Browse to the directory where you downloaded the Documentation theme for Jekyll.

Type jekyll serve

Go to the preview address in the browser. (Make sure you include the / at the end.)

    Tags:

    getting_started

    troubleshooting

               ©2016 company. All rights reserved.

 Site last generated: Jun 27, 2016


text:
namespace Piranha.Extend.Blocks;

/// <summary>
/// Separator
/// </summary>
[BlockType(Name = "Separator", Category = "Content", Icon = "fas fa-divide", Component = "separator-block")]
public class SeparatorBlock : Block
{
    public override string GetTitle()
    {
        return "----";
    }
}


text:
extern void prog1(void);
extern void prog2(void);

int main(int argc, char *argv[])
{
  printf("Hello from program.c\n");
  prog1();
  prog2();
  return 0;
}


text:
package org.gradle.internal.execution.steps;

import org.gradle.internal.Try;
import org.gradle.internal.execution.ExecutionEngine.Execution;
import org.gradle.internal.execution.UnitOfWork;

import java.time.Duration;

public class Result {

    private final Duration duration;
    private final Try<Execution> execution;

    protected Result(Duration duration, Try<Execution> execution) {
        this.duration = duration;
        this.execution = execution;
    }

    protected Result(Result parent) {
        this(parent.getDuration(), parent.getExecution());
    }

    public static Result failed(Throwable t, Duration duration) {
        return new Result(duration, Try.failure(t));
    }

    public static Result success(Duration duration, Execution outcome) {
        return new Result(duration, Try.successful(outcome));
    }

    /**
     * The elapsed wall clock time of executing the actual work, i.e. the time it took to execute the
     * {@link UnitOfWork#execute(UnitOfWork.ExecutionRequest)} method.
     *
     * The execution time refers to when and where the work was executed: if a previous result was reused,
     * then this method will return the time it took to produce the previous result.
     *
     * Note that reused work times might be different to what it would actually take to execute the work
     * in the current build for a number of reasons:
     *
     *

     *
reused work could have happened on a remote machine with different hardware capabilities,

     *
there might have been more or less load on the machine producing the reused work,

     *
the work reused might have been executed incrementally,

     *
had there been no work to reuse, the local execution might have happened happen incrementally.

     *

     */
    public Duration getDuration() {
        return duration;
    }

    public Try<Execution> getExecution() {
        return execution;
    }
}