text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
using System.Xml;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using LitJson;
using Mono.Addins;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OMEconomy.OMBase;

[assembly: Addin("OMCurrencyModule", OMEconomy.OMBase.OMBaseModule.MODULE_VERSION)]
[assembly: AddinDependency("OpenSim.Region.Framework", OpenSim.VersionInfo.VersionNumber)]

namespace OMEconomy.OMCurrency
{
    [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "OMCurrencyModule")]

    public class OMCurrencyModule : IMoneyModule, ISharedRegionModule
    {
        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private string MODULE_VERSION = OMBase.OMBaseModule.MODULE_VERSION;
        private string MODULE_NAME = "OMCURRENCY";

        Boolean Enabled = false;

        CommunicationHelpers m_communication = null;
        public SceneHandler m_sceneHandler = SceneHandler.getInstance();
        public Dictionary<UUID, int> m_KnownClientFunds = new Dictionary<UUID, int>();
        public OMBaseModule omBase = new OMBaseModule();

        public event ObjectPaid OnObjectPaid;

        #region ISharedRegion implementation
        public string Name { get { return "OMCURRENCY"; } }

        public void Initialise(IConfigSource config)
        {
            IConfig cfg = config.Configs["OpenMetaverseEconomy"];
            if (cfg == null)
                return;

            Enabled = cfg.GetBoolean("enabled", Enabled);

            if (!Enabled)
                return;
            m_communication = new CommunicationHelpers(config, MODULE_NAME, OMBase.OMBaseModule.MODULE_VERSION);
            MainServer.Instance.AddXmlRPCHandler("OMCurrencyNotification", currencyNotify, false);

            MainServer.Instance.AddXmlRPCHandler("getCurrencyQuote", getCurrencyQuote, false);
            MainServer.Instance.AddXmlRPCHandler("buyCurrency", buyCurrency, false);

            MainServer.Instance.AddXmlRPCHandler("preflightBuyLandPrep", preBuyLand);
            MainServer.Instance.AddXmlRPCHandler("buyLandPrep", buyLand);
        }

        public void PostInitialise()
        {
        }

        public void AddRegion(Scene scene)
        {
            if (!Enabled)
                return;

            scene.RegisterModuleInterface<IMoneyModule>(this);
        }

        public void RegionLoaded(Scene scene)
        {
            if (!Enabled)
                return;

            scene.EventManager.OnNewClient += OnNewClient;
            scene.EventManager.OnClientClosed += OnClientClosed;
            scene.EventManager.OnValidateLandBuy += OnValidateLandBuy;
            scene.EventManager.OnLandBuy += OnLandBuy;
            m_communication.RegisterService(MODULE_NAME, OMBase.OMBaseModule.MODULE_VERSION, scene.RegionInfo.RegionID);
        }

        public Type ReplaceableInterface
        {
            get { return null; }
        }

        public void RemoveRegion(Scene scene)
        {
            if (!Enabled)
                return;
            scene.EventManager.OnNewClient -= OnNewClient;
            scene.EventManager.OnClientClosed -= OnClientClosed;
            scene.EventManager.OnValidateLandBuy -= OnValidateLandBuy;
            scene.EventManager.OnLandBuy -= OnLandBuy;

            scene.UnregisterModuleInterface<IMoneyModule>(this);
        }

        public void Close() { }
        #endregion

        #region // Not implemented

        public bool GroupCreationCovered(IClientAPI client) { return true; }
        public bool AmountCovered(UUID agentID, int amount) { return true; }
        public bool UploadCovered(UUID agentID, int amount) { return true; }
        public int UploadCharge { get { return 13; } }
        public int GroupCreationCharge { get { return 12; } }
        public void ApplyUploadCharge(UUID agentID, int second, string third) { }
        public void ApplyGroupCreationCharge(UUID agentID) { }

        public bool MoveMoney(UUID fromAgentID, UUID toAgentID, int amount,MoneyTransactionType type, string text)
        {
		return false;
        }

        public void MoveMoney(UUID fromAgentID, UUID toAgentID, int amount, string text)
        {
        }

        //prior 0.7.6
        //public void ApplyCharge(UUID agentID, int amount, string text) { }

        //new since 0.7.6
        public void ApplyCharge(UUID agentID, int amount, MoneyTransactionType type) { }
        public void ApplyCharge(UUID agentID, int amount, MoneyTransactionType type, string extraData) { }

        public void updateClientFunds(UUID clientUUID)
        {
        }

        #endregion

        public bool ObjectGiveMoney(UUID objectID, UUID fromID, UUID toID, int amount, UUID txn, out string reason)
        {
            try
            {
                SceneObjectPart part = m_sceneHandler.FindPrim(objectID);
                if (part == null)
                {
                    throw new Exception("Could not find prim " + objectID);
                }

                Dictionary<string, string> additionalParameters = new Dictionary<string, string>();
                additionalParameters.Add("primUUID", part.UUID.ToString());
                additionalParameters.Add("primName", part.Name);
                additionalParameters.Add("primDescription", part.Description);

                additionalParameters.Add("primLocation", m_sceneHandler.GetObjectLocation(part));
                additionalParameters.Add("parentUUID", part.OwnerID.ToString());

                DoMoneyTransfer(fromID, toID, amount, (int)TransactionType.OBJECT_PAYS, additionalParameters);
                reason = String.Empty;
                return true;
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[{0}]: ObjectGiveMoney Exception: {1} - {2}", Name, e.Message, e.StackTrace);
                reason = e.Message;
                return false;
            }
        }

        public int GetBalance(UUID clientUUID)
        {
            lock (m_KnownClientFunds)
            {
                return m_KnownClientFunds.ContainsKey(clientUUID) ? m_KnownClientFunds[clientUUID] : 0;
            }
        }

        #region // Events
        private void OnNewClient(IClientAPI client)
        {
            client.OnMoneyBalanceRequest += SendMoneyBalance;
            client.OnMoneyTransferRequest += OnMoneyTransferRequest;
            client.OnRequestPayPrice += requestPayPrice;
            client.OnObjectBuy += ObjectBuy;
            client.OnLogout += OnLogout;
            client.OnScriptAnswer += OnScriptAnswer;
        }

        private void OnClientClosed(UUID agentUUID, Scene scene)
        {
            lock (m_KnownClientFunds)
            {
                if (m_KnownClientFunds.ContainsKey(agentUUID))
                {
                    m_KnownClientFunds.Remove(agentUUID);
                }
            }

            IClientAPI client = m_sceneHandler.LocateClientObject(agentUUID);

            if (client != null)
            {
                client.OnMoneyBalanceRequest -= SendMoneyBalance;
                client.OnRequestPayPrice -= requestPayPrice;
                client.OnScriptAnswer -= OnScriptAnswer;
                client.OnObjectBuy -= ObjectBuy;
                client.OnMoneyTransferRequest -= OnMoneyTransferRequest;
            }
        }

        private void OnLogout(IClientAPI client)
        {
            OnClientClosed(client.AgentId, null);
        }

        private void OnScriptAnswer(IClientAPI remoteClient, UUID objectID, UUID itemID, int answer)
        {
            try
            {
                SceneObjectPart part = m_sceneHandler.FindPrim(objectID);
                Dictionary<string, string> parameters = new Dictionary<string, string>();
                parameters.Add("primUUID", part.UUID.ToString());
                parameters.Add("primName", part.Name);
                parameters.Add("primDescription", part.Description);

                parameters.Add("primLocation", m_sceneHandler.GetObjectLocation(part));
                parameters.Add("parentUUID", part.OwnerID.ToString());
                parameters.Add("regionUUID", part.RegionID.ToString());
                //parameters.Add("m_gridURL", m_gridURL);

                if ((answer & 0x2) == 2)
                {
                    parameters.Add("method", "allowPrimDebit");
                }
                else
                {
                    parameters.Add("method", "removePrimDebit");
                }

                TaskInventoryItem item = null;
                part.TaskInventory.TryGetValue(itemID, out item);

                Dictionary<string, string[]> inventoryItems = new Dictionary<string, string[]>();
                inventoryItems.Add(item.ItemID.ToString(), new string[] { answer.ToString(), item.Name });
                parameters.Add("inventoryItems", JsonMapper.ToJson(inventoryItems));

                m_communication.DoRequestDictionary(parameters);
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[{0}]: ScriptChangedEvent Exception: {1} - {2}", Name, e.Message, e.StackTrace);
            }
        }

        private void OnMoneyTransferRequest(UUID sourceID, UUID destID, int amount, int transactionType, string description)
        {
            IClientAPI sender = m_sceneHandler.LocateClientObject(sourceID);
            if (sender == null)
            {
                m_log.ErrorFormat("[{0}]: MoneyTransferRequest(): Could not find Avatar {1}:({2})",
                    Name, sourceID.ToString(), sender.Name);

                return;
            }

            switch (transactionType)
            {
                case (int)TransactionType.PAY_OBJECT:
                    SceneObjectPart part = m_sceneHandler.FindPrim(destID);
                    if (part == null)
                    {
                        return;
                    }

                    string name = m_sceneHandler.ResolveAgentName(part.OwnerID);
                    if (String.IsNullOrEmpty(name))
                    {
                        name = m_sceneHandler.ResolveGroupName(part.OwnerID);
                    }

                    Dictionary<string, string> additionalParameters = new Dictionary<string, string>();
                    additionalParameters.Add("primUUID", part.UUID.ToString());
                    additionalParameters.Add("primName", part.Name);
                    additionalParameters.Add("primDescription", part.Description);
                    additionalParameters.Add("primLocation", m_sceneHandler.GetObjectLocation(part));

                    DoMoneyTransfer(sourceID, part.OwnerID, amount, transactionType, additionalParameters);
                    break;

                case (int)TransactionType.GIFT:
                    DoMoneyTransfer(sourceID, destID, amount, transactionType);
                    break;

                default:
                    m_log.ErrorFormat("[{0}]: TransactionType {1}  not specified.", Name, transactionType);
                    break;
            }
        }

        private void OnValidateLandBuy(Object osender, EventManager.LandBuyArgs e)
        {
            e.economyValidated = false;
        }

        private void OnLandBuy(Object osender, EventManager.LandBuyArgs e)
        {
            Scene s = m_sceneHandler.LocateSceneClientIn(e.agentId);
            if (e.economyValidated == false)
            {
                if (e.parcelPrice == 0)
                {
                    e.economyValidated = true;
                    s.EventManager.TriggerLandBuy(osender, e);
                }
                else
                {
                    ILandObject parcel = s.LandChannel.GetLandObject(e.parcelLocalID);

                    Dictionary<string, string> additionalParameters = new Dictionary<string, string>();
                    additionalParameters.Add("final", e.final == true ? "1" : "0");
                    additionalParameters.Add("removeContribution", e.removeContribution == true ? "1" : "0");
                    additionalParameters.Add("parcelLocalID", e.parcelLocalID.ToString());
                    additionalParameters.Add("parcelName", parcel.LandData.Name);
                    additionalParameters.Add("transactionID", e.transactionID.ToString());
                    additionalParameters.Add("amountDebited", e.amountDebited.ToString());
                    additionalParameters.Add("authenticated", e.authenticated == true ? "1" : "0");

                    DoMoneyTransfer(e.agentId, e.parcelOwnerID, e.parcelPrice, (int)TransactionType.BUY_LAND, additionalParameters);
                }
            }
        }

        #endregion Event Handler

        public void SendMoneyBalance(IClientAPI client, UUID agentID, UUID SessionID, UUID TransactionID)
        {
            if (client.AgentId == agentID && client.SessionId == SessionID)
            {
                int returnfunds = GetBalance(agentID);

                //new since 0.7.6
                client.SendMoneyBalance(
                TransactionID, true, new byte[0], returnfunds, 0, UUID.Zero, false, UUID.Zero, false, 0, String.Empty);

                //prior 0.7.6
                //client.SendMoneyBalance(TransactionID, true, new byte[0], returnfunds);

            }
        }

        public void DoMoneyTransfer(UUID sourceId, UUID destId, int amount, int transactiontype)
        {
            DoMoneyTransfer(sourceId, destId, amount, transactiontype, null);
        }

        public void DoMoneyTransfer(UUID sourceId, UUID destId, int amount,
            int transactiontype, Dictionary<string, string> additionalParameters)
        {
            System.Threading.ThreadPool.QueueUserWorkItem(delegate {
                IClientAPI recipient = m_sceneHandler.LocateClientObject(destId);
                string recipientName = recipient == null ? destId.ToString() : recipient.FirstName + " " + recipient.LastName;

                IClientAPI sender = m_sceneHandler.LocateClientObject(sourceId);
                string senderName = sender == null ? sourceId.ToString() : sender.FirstName + " " + sender.LastName;

                Dictionary<string, string> d = new Dictionary<string, string>();
                d.Add("method", "transferMoney");
                d.Add("senderUUID", sourceId.ToString());
                d.Add("senderName", senderName);
                d.Add("recipientUUID", destId.ToString());
                d.Add("recipientName", recipientName);
                d.Add("amount", amount.ToString());
                d.Add("transactionType", transactiontype.ToString());
                if (transactiontype == (int)TransactionType.OBJECT_PAYS)
                {
                    d.Add("regionUUID", m_sceneHandler.LocateSceneClientIn(destId).RegionInfo.RegionID.ToString());
                }
                else
                {
                    d.Add("regionUUID", m_sceneHandler.LocateSceneClientIn(sourceId).RegionInfo.RegionID.ToString());
                }
                //d.Add("m_gridURL", m_gridURL);

                if (additionalParameters != null)
                {
                    foreach (KeyValuePair<string, string> pair in additionalParameters)
                    {
                        d.Add(pair.Key, pair.Value);
                    }
                }

                if (m_communication.DoRequestDictionary(d) == null)
                {
                    serviceNotAvailable(sourceId);
                }
            }, null);
        }

        #region Local Fund Management

        private void SetBalance(UUID AgentID, Int32 balance)
        {
            lock (m_KnownClientFunds)
            {
                if (m_KnownClientFunds.ContainsKey(AgentID))
                {
                    m_KnownClientFunds[AgentID] = balance;
                }
                else
                {
                    m_KnownClientFunds.Add(AgentID, balance);
                }
            }
        }

        #endregion Local Fund Management

        public void requestPayPrice(IClientAPI client, UUID objectID)
        {
            SceneObjectPart prim = m_sceneHandler.FindPrim(objectID);
            if (prim != null)
            {
                SceneObjectPart root = prim.ParentGroup.RootPart;
                client.SendPayPrice(objectID, root.PayPrice);
            }
        }

        public void ObjectBuy(IClientAPI remoteClient, UUID agentID, UUID sessionID, UUID groupID, UUID categoryID, uint localID, byte saleType, int salePrice)
        {
            m_log.DebugFormat("User {0} buys object {1} for {2} OMC", agentID, localID, salePrice);
            Scene s = m_sceneHandler.LocateSceneClientIn(remoteClient.AgentId);
            SceneObjectPart part = s.GetSceneObjectPart(localID);
            if (part == null)
            {
                remoteClient.SendAgentAlertMessage("Unable to buy now. The object can not be found.", false);
                return;
            }

            if (salePrice == 0)
            {
                m_log.Debug ("Sale Price is 0");
                IBuySellModule buyModule = s.RequestModuleInterface<IBuySellModule>();
                if (buyModule != null)
                {
                    m_log.Debug ("Call BuyObject if sale price is 0");
                    buyModule.BuyObject(remoteClient, categoryID, localID, saleType, salePrice);
                }
                else
                {
                    throw new Exception("Could not find IBuySellModule");
                }
            }
            else
            {
                Dictionary<string, string> buyObject = new Dictionary<string, string>();
                buyObject.Add("categoryID", categoryID.ToString());
                buyObject.Add("localID", Convert.ToString(localID));
                buyObject.Add("saleType", saleType.ToString());
                buyObject.Add("objectUUID", part.UUID.ToString());
                buyObject.Add("objectName", part.Name);
                buyObject.Add("objectDescription", part.Description);
                buyObject.Add("objectLocation", m_sceneHandler.GetObjectLocation(part));

                DoMoneyTransfer(remoteClient.AgentId, part.OwnerID, salePrice, (int)TransactionType.BUY_OBJECT, buyObject);
            }
        }

        private void serviceNotAvailable(UUID avatarUUID)
        {
            string message = "The currency service is not available. Please try again later.";
            m_sceneHandler.LocateClientObject(avatarUUID).SendBlueBoxMessage(UUID.Zero, String.Empty, message);
        }

        #region XML NOTIFICATIONS

        public XmlRpcResponse currencyNotify(XmlRpcRequest request, IPEndPoint ep)
        {

            XmlRpcResponse r = new XmlRpcResponse ();
            Hashtable requestData = m_communication.ValidateRequest(request);
            if(requestData != null) {
                string method = (string)requestData["method"];
                switch (method)
                {
                    case "notifyDeliverObject": r.Value = deliverObject(requestData);
                        break;
                    case "notifyOnObjectPaid": r.Value = onObjectPaid(requestData);
                        break;
                    case "notifyLandBuy": r.Value = landBuy(requestData);
                        break;
                    case "notifyChangePrimPermission": r.Value = changePrimPermissions(requestData);
                        break;
                    case "notifyBalanceUpdate": r.Value = balanceUpdate(requestData);
                        break;
                    case "notifyGetVersion": r.Value = GetVersion(requestData);
                        break;
                    default: m_log.ErrorFormat("[{0}]: Method {1} is not supported", Name, method);
                        break;
                }
            } else {
                r.SetFault(-1, "Could not validate the request");
            }
            return r;
        }

        //   12 => {8, 4}     25 => {16, 8, 1}    127 => {64, 32, 16, 8, 4, 2, 1}
        private List<int> sliceBits(int permissions)
        {
            string binaryString = Convert.ToString(permissions, 2);
            List<int> returnValue = new List<int>();
            for (int i = binaryString.Length; i > 0; i--)
            {
                if (binaryString[i - 1] == '1')
                {
                    returnValue.Add((int)Math.Pow(2, binaryString.Length - i));
                }
            }
            return returnValue;
        }

        private Hashtable changePrimPermissions(Hashtable requestData)
        {
            Hashtable rparms = new Hashtable();

            try
            {
                UUID primUUID = UUID.Parse((string)requestData["primUUID"]);
                SceneObjectPart part = m_sceneHandler.FindPrim(primUUID);
                if (part == null)
                {
                    throw new Exception("Could not find the requested prim");
                }

                string inventoryItemsString = (string)requestData["inventoryItems"];
                Dictionary<string, string> inventoryItems = JsonMapper.ToObject<Dictionary<string, string>>(inventoryItemsString);
                foreach (KeyValuePair<string, string> inventoryItem in inventoryItems)
                {
                    if (inventoryItem.Value == "0")
                    {
                        part.RemoveScriptEvents(UUID.Parse(inventoryItem.Key));
                    }
                    else
                    {
                        part.SetScriptEvents(UUID.Parse(inventoryItem.Key), Convert.ToInt32(inventoryItem.Value));
                    }
                }

                rparms["success"] = true;
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[{0}]: changePrimPermissions() Exception: {1} - {2}", Name, e.Message, e.StackTrace);
                rparms["success"] = false;
            }
            return rparms;
        }

        private Hashtable balanceUpdate(Hashtable requestData)
        {
            Hashtable rparms = new Hashtable();
            try
            {
                UUID avatarUUID = UUID.Parse((string)requestData["avatarUUID"]);
                Int32 balance = Int32.Parse((string)requestData["balance"]);

                IClientAPI client = m_sceneHandler.LocateClientObject(avatarUUID);
                if (client == null)
                {
                    throw new Exception("Avatar " + avatarUUID.ToString() + " does not reside in this region");
                }

                SetBalance(client.AgentId, balance);
                SendMoneyBalance(client, client.AgentId, client.SessionId, UUID.Zero);
                rparms["success"] = true;
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[{0}]: balanceUpdate() Exception: {1} - {2}", Name, e.Message, e.StackTrace);
                rparms["success"] = false;
            }
            return rparms;
        }

        private Hashtable landBuy(Hashtable requestData)
        {
            Hashtable rparms = new Hashtable();
            rparms["success"] = false;
            try
            {
                Dictionary<string, string> d = new Dictionary<string, string>();
                d.Add("method", "buyLand");
                d.Add("id", (string)requestData["id"]);
                Dictionary<string, string> response = m_communication.DoRequestDictionary(d);
                if (response != null)
                {
                    UUID agentID = UUID.Parse((string)response["senderUUID"]);
                    int parcelLocalID = int.Parse((string)response["parcelLocalID"]);
                    int transactionID = int.Parse((string)response["transactionID"]);
                    int amountDebited = int.Parse((string)response["amountDebited"]);
                    bool final = (string)response["final"] == "1" ? true : false;
                    bool authenticated = (string)response["authenticated"] == "1" ? true : false;
                    bool removeContribution = (string)response["removeContribution"] == "1" ? true : false;

                    UUID regionUUID = UUID.Parse(response["regionUUID"]);
                    Scene s = m_sceneHandler.GetSceneByUUID(regionUUID);
                    ILandObject parcel = s.LandChannel.GetLandObject(parcelLocalID);

                    UUID groupID = parcel.LandData.GroupID;
                    int parcelArea = parcel.LandData.Area;
                    int parcelPrice = parcel.LandData.SalePrice;
                    bool groupOwned = parcel.LandData.IsGroupOwned;
                    UUID parcelOwnerUUID = parcel.LandData.OwnerID;

                    EventManager.LandBuyArgs landbuyArguments =
                        new EventManager.LandBuyArgs(agentID, groupID, final, groupOwned, removeContribution,
                                                     parcelLocalID, parcelArea, parcelPrice, authenticated);

                    IClientAPI sender = m_sceneHandler.LocateClientObject(agentID);
                    if (sender != null)
                    {
                        landbuyArguments.amountDebited = amountDebited;
                        landbuyArguments.parcelOwnerID = parcelOwnerUUID;
                        landbuyArguments.transactionID = transactionID;

                        s.EventManager.TriggerValidateLandBuy(sender, landbuyArguments);
                        landbuyArguments.economyValidated = true;

                        s.EventManager.TriggerLandBuy(sender, landbuyArguments);

                        rparms["success"] = true;
                    }
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[{0}]: landBuy(...) Exception: {1} - {2}", Name, e.Message, e.StackTrace);
            }

            return rparms;
        }

        private Hashtable deliverObject(Hashtable requestData)
        {
            Hashtable rparms = new Hashtable();
            rparms["success"] = false;
            try
            {
                Dictionary<string, string> d = new Dictionary<string, string>();
                d.Add("method", "deliverObject");
                d.Add("id", (string)requestData["id"]);

                Dictionary<string, string> response = m_communication.DoRequestDictionary(d);
                if (response != null && response["success"] == "TRUE" || response["success"] == "1")
                {
                    UInt32 localID = UInt32.Parse(response["localID"]);
                    UUID receiverUUID = UUID.Parse(response["receiverUUID"]);
                    UUID categoryID = UUID.Parse(response["categoryID"]);
                    byte saleType = byte.Parse(response["saleType"]);
                    int salePrice = response.ContainsKey("salePrice") ? Int32.Parse(response["salePrice"]) : 0;

                    IClientAPI sender = m_sceneHandler.LocateClientObject(receiverUUID);
                    if (sender == null)
                    {
                        throw new Exception("Avatar " + receiverUUID.ToString() + " does not reside in this region");
                    }

                    Scene s = m_sceneHandler.LocateSceneClientIn(receiverUUID);
                    if (s == null)
                    {
                        throw new Exception("Could not find the receiver's current scene");
                    }

                    IBuySellModule buyModule = s.RequestModuleInterface<IBuySellModule>();
                    if (buyModule != null)
                    {
                        m_log.Debug("Call BuyObject from delicerObject");
                        buyModule.BuyObject(sender, categoryID, localID, saleType, salePrice);
                    }
                    else
                    {
                        throw new Exception("Could not find IBuySellModule");
                    }
                    rparms["success"] = true;
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[{0}]: deliverObject() Exception: {1} - {2}", Name, e.Message, e.StackTrace);
            }
            return rparms;
        }

        private Hashtable GetVersion(Hashtable requestData)
        {
            Hashtable rparms = new Hashtable();
            rparms["version"] = MODULE_VERSION;
            return rparms;
        }

        private Hashtable onObjectPaid(Hashtable requestData)
        {
            Hashtable rparms = new Hashtable();
            rparms["success"] = false;
            try
            {
                Dictionary<string, string> d = new Dictionary<string, string>();
                d.Add("method", "objectPaid");
                d.Add("id", (string)requestData["id"]);

                Dictionary<string, string> response = m_communication.DoRequestDictionary(d);
                if (response != null)
                {
                    UUID primUUID = UUID.Parse(response["primUUID"]);
                    UUID senderUUID = UUID.Parse(response["senderUUID"]);
                    Int32 amount = Int32.Parse(response["amount"]);

                    IClientAPI depositor = m_sceneHandler.LocateClientObject(senderUUID);
                    if (depositor == null)
                    {
                        throw new Exception("Avatar " + senderUUID.ToString() + " does not reside in this Region");
                    }

                    ObjectPaid HandlerOnObjectPaid = OnObjectPaid;
                    if (HandlerOnObjectPaid != null)
                    {
                        m_log.Debug("Trigger Object Payed");
                        HandlerOnObjectPaid(primUUID, senderUUID, amount);
                    }
                    else
                    {
                        m_log.Debug("No Trigger Object Payed");
                    }

                    rparms["success"] = true;
                }
            }
            catch (Exception e)
            {
                m_log.Error("[OMCURRENCY]: onObjectPaid() " + e.Message);
            }
            return rparms;
        }

        public XmlRpcResponse buyCurrency(XmlRpcRequest request, IPEndPoint ep)
        {
            Hashtable requestData = (Hashtable)request.Params[0];
            Hashtable returnresp = new Hashtable();

            try
            {
                UUID avatarUUID = UUID.Parse((string)requestData["agentId"]);
                int amount = (Int32)requestData["currencyBuy"];

                Dictionary<string, string> d = new Dictionary<string, string>();
                d.Add("method", "buyCurrency");
                d.Add("avatarUUID", avatarUUID.ToString());
                d.Add("amount", amount.ToString());

                Dictionary<string, string> response = m_communication.DoRequestDictionary(d);

                if (response != null && response["success"] == "TRUE" || response["success"] == "1")
                {
                    returnresp.Add("success", true);
                }
                else
                {
                    throw new Exception();
                }

            }
            catch (Exception)
            {
                returnresp.Add("success", false);
                returnresp.Add("errorMessage", "Please visit virwox.com to transfer money");
                returnresp.Add("errorURI", "http://www.virwox.com");
            }

            XmlRpcResponse returnval = new XmlRpcResponse();
            returnval.Value = returnresp;
            return returnval;
        }

        public XmlRpcResponse getCurrencyQuote(XmlRpcRequest request, IPEndPoint ep)
        {
            Hashtable requestData = (Hashtable)request.Params[0];
            UUID agentId = UUID.Zero;
            int amount = 0;
            Hashtable quoteResponse = new Hashtable();

            try
            {
                UUID.TryParse((string)requestData["agentId"], out agentId);
                amount = (Int32)requestData["currencyBuy"];

                int realAmount = amount / getExchangeRate() + 1;
                amount = realAmount * getExchangeRate();

                Hashtable currencyResponse = new Hashtable();
                currencyResponse.Add("estimatedCost", realAmount * 100);
                currencyResponse.Add("currencyBuy", amount);

                quoteResponse.Add("success", true);
                quoteResponse.Add("currency", currencyResponse);
                quoteResponse.Add("confirm", "");

            }
            catch (Exception)
            {
                Dictionary<string, string> d = new Dictionary<string, string>();
                d.Add("method", "getString");
                d.Add("type", "chargeAccount");
                d.Add("avatarUUID", (string)requestData["agentId"]);

                Dictionary<string, string> response = m_communication.DoRequestDictionary(d);
                if (response != null)
                {
                    quoteResponse.Add ("success", false);
                    quoteResponse.Add ("errorMessage", response ["errorMessage"]);
                    quoteResponse.Add ("errorURI", response ["errorURI"]);
                }
                else
                {
                    quoteResponse.Add ("success", false);
                }
            }

            XmlRpcResponse returnval = new XmlRpcResponse();
            returnval.Value = quoteResponse;
            return returnval;
        }

        public XmlRpcResponse preBuyLand(XmlRpcRequest request, IPEndPoint ep)
        {
            m_log.Error("preBuyLand(XmlRpcRequest request, IPEndPoint ep)");
            XmlRpcResponse ret = new XmlRpcResponse();
            Hashtable retparam = new Hashtable();
            Hashtable membershiplevels = new Hashtable();
            ArrayList levels = new ArrayList();
            Hashtable level = new Hashtable();
            level.Add("id", "00000000-0000-0000-0000-000000000000");
            level.Add("description", "");
            levels.Add(level);

            Hashtable landuse = new Hashtable();
            landuse.Add("upgrade", true);
            landuse.Add("action", "");

            Hashtable currency = new Hashtable();
            currency.Add("estimatedCost", 0);

            Hashtable membership = new Hashtable();
            membershiplevels.Add("upgrade", true);
            membershiplevels.Add("action", "");
            membershiplevels.Add("levels", membershiplevels);

            retparam.Add("success", true); // Cannot buy now - overall message.
            retparam.Add("currency", currency);
            retparam.Add("membership", membership);
            retparam.Add("landuse", landuse);
            retparam.Add("confirm", "");

            ret.Value = retparam;
            return ret;
        }

        public XmlRpcResponse buyLand(XmlRpcRequest request, IPEndPoint ep)
        {
            m_log.Error("buyLand(XmlRpcRequest request, IPEndPoint ep)");
            XmlRpcResponse ret = new XmlRpcResponse();
            Hashtable retparam = new Hashtable();
            retparam.Add("success", true);
            ret.Value = retparam;
            return ret;
        }

        private int getExchangeRate()
        {
            Dictionary<string, string> d = new Dictionary<string, string>();
            d.Add("method", "getExchangeRate");
            Dictionary<string, string> response = m_communication.DoRequestDictionary(d);
            if (response != null)
            {
                return int.Parse((string)response["currentExchangeRate"]);
            }
            else
            {
                m_log.Error("buyLand(XmlRpcRequest request, IPEndPoint ep)");
            }
            return 0;
        }

        #endregion XML NOTIFICATIONS
    }

    public enum TransactionType : int
    {
        BUY_OBJECT = 5000,
        GIFT = 5001,
        PAY_OBJECT = 5008,
        OBJECT_PAYS = 5009,
        BUY_LAND = 5013,
    }
}


text:
  Barst est
       un village
       géographiquement positionné dans le département de Moselle en Lorraine. Elle totalisait 538 habitants en 2008.

Si vous pensez venir habiter à Barst, vous pourrez aisément trouver une maison à vendre.

Le nombre de logements, à Barst, était réparti en 2011 en 19 appartements et 210 maisons soit
 un marché relativement équilibré.

La commune offre quelques  équipements, elle propose entre autres une base nautique et une boucle de randonnée.

À coté de Barst sont localisées les villes de
Macheren à 5 km, 2 946 habitants,
Seingbouse située à 4 km, 1 863 habitants,
Hoste située à 3 km, 678 habitants,
Henriville située à 3 km, 755 habitants,
Leyviller située à 4 km, 503 habitants,
Guenviller située à 4 km, 659 habitants,
 entre autres. De plus, Barst est située à seulement treize km de Forbach.

À Barst, la valorisation moyenne à l'achat d'un appartement se situe à zero € du m² en vente. la valorisation moyenne d'une maison à l'achat se situe à 1 800 € du m². À la location la valorisation moyenne se situe à 0 € du m² mensuel.

redpajama_set_name: RedPajamaGithub


text:
package org.apache.isis.objectstore.jdo.metamodel.facets.prop.notpersistent;

import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PrimaryKey;

import org.apache.isis.core.metamodel.facetapi.FacetUtil;
import org.apache.isis.core.metamodel.facetapi.FeatureType;
import org.apache.isis.core.metamodel.facets.Annotations;
import org.apache.isis.core.metamodel.facets.FacetFactoryAbstract;
import org.apache.isis.core.metamodel.facets.FacetedMethod;

public class JdoNotPersistentAnnotationFacetFactory extends FacetFactoryAbstract {

    public JdoNotPersistentAnnotationFacetFactory() {
        super(FeatureType.PROPERTIES_ONLY);
    }

    @Override
    public void process(ProcessMethodContext processMethodContext) {
        final NotPersistent annotation = Annotations.getAnnotation(processMethodContext.getMethod(), NotPersistent.class);
        if (annotation == null) {
            return;
        }

        final FacetedMethod holder = processMethodContext.getFacetHolder();
        FacetUtil.addFacet(new JdoNotPersistentFacetAnnotation(holder));
        FacetUtil.addFacet(new NotPersistedFacetDerivedFromJdoNotPersistentAnnotation(holder));
    }
}


text:
'use strict';

/**
 * @ngdoc function
 * @name todoListApp.controller:AboutCtrl
 * @description
 * # AboutCtrl
 * Controller of the todoListApp
 */
angular.module('todoListApp')
  .controller('AboutCtrl', function () {
    this.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];
  });


text:
class EmailValidatorMock : public EmailValidator {
public:
    MOCK_CONST_METHOD1_T(isValid, bool (const String &email));
};


text:
require 'formula'

class Jpegoptim < Formula
  homepage 'https://github.com/tjko/jpegoptim'
  url 'https://github.com/tjko/jpegoptim/archive/RELEASE.1.3.1.tar.gz'
  sha1 'c7264e3a6c59cc4ee919ca6e4c9db02076da2476'
  head 'https://github.com/tjko/jpegoptim.git'

  depends_on 'jpeg'

  def install
    system "./configure", "--disable-debug", "--disable-dependency-tracking",
                          "--prefix=#{prefix}"
    ENV.j1 # Install is not parallel-safe
    system "make install"
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>GLCommon (libgdx API)</title>
<meta name="date" content="2013-11-03">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

				libgdx API

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.badlogic.gdx.graphics

Interface GLCommon

All Known Subinterfaces:

GL10, GL11, GL20

public interface GLCommon

This interface defines methods common to GL10, GL11 and GL20.

Author:

mzechner

Field Summary

Fields

Modifier and Type
Field and Description

static int
GL_GENERATE_MIPMAP

static int
GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT

static int
GL_TEXTURE_MAX_ANISOTROPY_EXT

Method Summary

Methods

Modifier and Type
Method and Description

void
glActiveTexture(int texture)

void
glBindTexture(int target,
             int texture)

void
glBlendFunc(int sfactor,
           int dfactor)

void
glClear(int mask)

void
glClearColor(float red,
            float green,
            float blue,
            float alpha)

void
glClearDepthf(float depth)

void
glClearStencil(int s)

void
glColorMask(boolean red,
           boolean green,
           boolean blue,
           boolean alpha)

void
glCompressedTexImage2D(int target,
                      int level,
                      int internalformat,
                      int width,
                      int height,
                      int border,
                      int imageSize,
                      java.nio.Buffer data)

void
glCompressedTexSubImage2D(int target,
                         int level,
                         int xoffset,
                         int yoffset,
                         int width,
                         int height,
                         int format,
                         int imageSize,
                         java.nio.Buffer data)

void
glCopyTexImage2D(int target,
                int level,
                int internalformat,
                int x,
                int y,
                int width,
                int height,
                int border)

void
glCopyTexSubImage2D(int target,
                   int level,
                   int xoffset,
                   int yoffset,
                   int x,
                   int y,
                   int width,
                   int height)

void
glCullFace(int mode)

void
glDeleteTextures(int n,
                java.nio.IntBuffer textures)

void
glDepthFunc(int func)

void
glDepthMask(boolean flag)

void
glDepthRangef(float zNear,
             float zFar)

void
glDisable(int cap)

void
glDrawArrays(int mode,
            int first,
            int count)

void
glDrawElements(int mode,
              int count,
              int type,
              java.nio.Buffer indices)

void
glEnable(int cap)

void
glFinish()

void
glFlush()

void
glFrontFace(int mode)

void
glGenTextures(int n,
             java.nio.IntBuffer textures)

int
glGetError()

void
glGetIntegerv(int pname,
             java.nio.IntBuffer params)

java.lang.String
glGetString(int name)

void
glHint(int target,
      int mode)

void
glLineWidth(float width)

void
glPixelStorei(int pname,
             int param)

void
glPolygonOffset(float factor,
               float units)

void
glReadPixels(int x,
            int y,
            int width,
            int height,
            int format,
            int type,
            java.nio.Buffer pixels)

void
glScissor(int x,
         int y,
         int width,
         int height)

void
glStencilFunc(int func,
             int ref,
             int mask)

void
glStencilMask(int mask)

void
glStencilOp(int fail,
           int zfail,
           int zpass)

void
glTexImage2D(int target,
            int level,
            int internalformat,
            int width,
            int height,
            int border,
            int format,
            int type,
            java.nio.Buffer pixels)

void
glTexParameterf(int target,
               int pname,
               float param)

void
glTexSubImage2D(int target,
               int level,
               int xoffset,
               int yoffset,
               int width,
               int height,
               int format,
               int type,
               java.nio.Buffer pixels)

void
glViewport(int x,
          int y,
          int width,
          int height)

Field Detail

GL_GENERATE_MIPMAP

static final int GL_GENERATE_MIPMAP

See Also:

Constant Field Values

GL_TEXTURE_MAX_ANISOTROPY_EXT

static final int GL_TEXTURE_MAX_ANISOTROPY_EXT

See Also:

Constant Field Values

GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT

static final int GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT

See Also:

Constant Field Values

Method Detail

glActiveTexture

void glActiveTexture(int texture)

glBindTexture

void glBindTexture(int target,
                 int texture)

glBlendFunc

void glBlendFunc(int sfactor,
               int dfactor)

glClear

void glClear(int mask)

glClearColor

void glClearColor(float red,
                float green,
                float blue,
                float alpha)

glClearDepthf

void glClearDepthf(float depth)

glClearStencil

void glClearStencil(int s)

glColorMask

void glColorMask(boolean red,
               boolean green,
               boolean blue,
               boolean alpha)

glCompressedTexImage2D

void glCompressedTexImage2D(int target,
                          int level,
                          int internalformat,
                          int width,
                          int height,
                          int border,
                          int imageSize,
                          java.nio.Buffer data)

glCompressedTexSubImage2D

void glCompressedTexSubImage2D(int target,
                             int level,
                             int xoffset,
                             int yoffset,
                             int width,
                             int height,
                             int format,
                             int imageSize,
                             java.nio.Buffer data)

glCopyTexImage2D

void glCopyTexImage2D(int target,
                    int level,
                    int internalformat,
                    int x,
                    int y,
                    int width,
                    int height,
                    int border)

glCopyTexSubImage2D

void glCopyTexSubImage2D(int target,
                       int level,
                       int xoffset,
                       int yoffset,
                       int x,
                       int y,
                       int width,
                       int height)

glCullFace

void glCullFace(int mode)

glDeleteTextures

void glDeleteTextures(int n,
                    java.nio.IntBuffer textures)

glDepthFunc

void glDepthFunc(int func)

glDepthMask

void glDepthMask(boolean flag)

glDepthRangef

void glDepthRangef(float zNear,
                 float zFar)

glDisable

void glDisable(int cap)

glDrawArrays

void glDrawArrays(int mode,
                int first,
                int count)

glDrawElements

void glDrawElements(int mode,
                  int count,
                  int type,
                  java.nio.Buffer indices)

glEnable

void glEnable(int cap)

glFinish

void glFinish()

glFlush

void glFlush()

glFrontFace

void glFrontFace(int mode)

glGenTextures

void glGenTextures(int n,
                 java.nio.IntBuffer textures)

glGetError

int glGetError()

glGetIntegerv

void glGetIntegerv(int pname,
                 java.nio.IntBuffer params)

glGetString

java.lang.String glGetString(int name)

glHint

void glHint(int target,
          int mode)

glLineWidth

void glLineWidth(float width)

glPixelStorei

void glPixelStorei(int pname,
                 int param)

glPolygonOffset

void glPolygonOffset(float factor,
                   float units)

glReadPixels

void glReadPixels(int x,
                int y,
                int width,
                int height,
                int format,
                int type,
                java.nio.Buffer pixels)

glScissor

void glScissor(int x,
             int y,
             int width,
             int height)

glStencilFunc

void glStencilFunc(int func,
                 int ref,
                 int mask)

glStencilMask

void glStencilMask(int mask)

glStencilOp

void glStencilOp(int fail,
               int zfail,
               int zpass)

glTexImage2D

void glTexImage2D(int target,
                int level,
                int internalformat,
                int width,
                int height,
                int border,
                int format,
                int type,
                java.nio.Buffer pixels)

glTexParameterf

void glTexParameterf(int target,
                   int pname,
                   float param)

glTexSubImage2D

void glTexSubImage2D(int target,
                   int level,
                   int xoffset,
                   int yoffset,
                   int width,
                   int height,
                   int format,
                   int type,
                   java.nio.Buffer pixels)

glViewport

void glViewport(int x,
              int y,
              int width,
              int height)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

libgdx API

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

				Copyright © 2010-2013 Mario Zechner (contact@badlogicgames.com), Nathan Sweet (admin@esotericsoftware.com)


text:
Stops YouTrack from notifying users about the changes performed by the commands executed on all commit commands executed
from this plugin.


text:
file(REMOVE_RECURSE
  "CMakeFiles/compile_PartialRedux_squaredNorm.dir/compile_PartialRedux_squaredNorm.cpp.o"
  "compile_PartialRedux_squaredNorm.pdb"
  "compile_PartialRedux_squaredNorm"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/compile_PartialRedux_squaredNorm.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


text:
package io.cattle.platform.docker.transform;

import static io.cattle.platform.core.constants.InstanceConstants.*;
import static io.cattle.platform.docker.constants.DockerInstanceConstants.*;
import static io.cattle.platform.docker.constants.DockerNetworkConstants.*;
import io.cattle.platform.core.addon.LogConfig;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.json.JsonMapper;
import io.cattle.platform.object.util.DataAccessor;
import io.cattle.platform.util.type.CollectionUtils;
import io.github.ibuildthecloud.gdapi.exception.ClientVisibleException;
import io.github.ibuildthecloud.gdapi.util.ResponseCodes;
import io.github.ibuildthecloud.gdapi.validation.ValidationErrorCodes;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;

import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.model.Capability;
import com.github.dockerjava.api.model.ContainerConfig;
import com.github.dockerjava.api.model.Device;
import com.github.dockerjava.api.model.ExposedPort;
import com.github.dockerjava.api.model.HostConfig;
import com.github.dockerjava.api.model.LxcConf;
import com.github.dockerjava.api.model.Ports;
import com.github.dockerjava.api.model.Ports.Binding;
import com.github.dockerjava.api.model.RestartPolicy;
import com.github.dockerjava.api.model.VolumeBind;

public class DockerTransformerImpl implements DockerTransformer {

    private static final String IMAGE_PREFIX = "docker:";
    private static final String IMAGE_KIND_PATTERN = "^(sim|docker):.*";
    private static final String READ_WRITE = "rw";
    private static final String READ_ONLY = "ro";

    @Inject
    JsonMapper jsonMapper;

    @SuppressWarnings("unchecked")
    public List<DockerInspectTransformVolume> transformVolumes(Map<String, Object> fromInspect) {
        InspectContainerResponse inspect = transformInspect(fromInspect);
        HostConfig hostConfig = inspect.getHostConfig();
        VolumeBind[] volumeBinds = null;
        try {
            volumeBinds = inspect.getVolumes();
        } catch (NullPointerException e) {
            // A bug in docker-java can cause this.
            volumeBinds = new VolumeBind[0];
        }
        Set<String> binds = bindSet(hostConfig.getBinds());
        Map<String, String> rw = rwMap((Map<String, Boolean>)fromInspect.get("VolumesRW"));
        List<DockerInspectTransformVolume> volumes = new ArrayList<DockerInspectTransformVolume>();
        for (VolumeBind vb : volumeBinds) {
            String am = rw.containsKey(vb.getContainerPath()) ? rw.get(vb.getContainerPath()) : READ_WRITE;
            boolean isBindMound = binds.contains(vb.getContainerPath());
            volumes.add(new DockerInspectTransformVolume(vb.getContainerPath(), vb.getHostPath(), am, isBindMound));
        }
        return volumes;
    }

    Map<String, String> rwMap(Map<String, Boolean> volumeRws) {
        // TODO When this bug is fixed, switch to using java-docker's volumesRW
        // https://github.com/docker-java/docker-java/issues/205
        Map<String, String> rwMap = new HashMap<String, String>();

        if (volumeRws == null) {
            return rwMap;
        }

        for (Map.Entry<String, Boolean> volume : volumeRws.entrySet()) {
            Boolean readWrite = volume.getValue();
            String perms = readWrite ? READ_WRITE : READ_ONLY;
            rwMap.put(volume.getKey(), perms);
        }

        return rwMap;
    }

    Set<String> bindSet(String[] binds) {
        Set<String> hostBindMounts = new HashSet<String>();
        if (binds == null)
            return hostBindMounts;

        for (String bindMount : binds) {
            String[] parts = bindMount.split(":");
            hostBindMounts.add(parts[1]);
        }
        return hostBindMounts;
    }

    @Override
    public void transform(Map<String, Object> fromInspect, Instance instance) {
        InspectContainerResponse inspect = transformInspect(fromInspect);
        ContainerConfig containerConfig = inspect.getConfig();
        HostConfig hostConfig = inspect.getHostConfig();

        instance.setExternalId(inspect.getId());
        instance.setKind(KIND_CONTAINER);
        setName(instance, inspect);

        if (containerConfig != null) {
            instance.setHostname((String) fixEmptyValue(containerConfig.getHostName()));
            setField(instance, FIELD_MEMORY, containerConfig.getMemoryLimit());
            setField(instance, FIELD_CPU_SET, containerConfig.getCpuset());
            setField(instance, FIELD_CPU_SHARES, containerConfig.getCpuShares());
            setField(instance, FIELD_MEMORY_SWAP, containerConfig.getMemorySwap());
            setField(instance, FIELD_DOMAIN_NAME, containerConfig.getDomainName());
            setField(instance, FIELD_USER, containerConfig.getUser());
            setField(instance, FIELD_TTY, containerConfig.isTty());
            setField(instance, FIELD_STDIN_OPEN, containerConfig.isStdinOpen());
            setImage(instance, containerConfig.getImage());
            setField(instance, FIELD_WORKING_DIR, containerConfig.getWorkingDir());
            setEnvironment(instance, containerConfig.getEnv());
            setCommand(instance, containerConfig.getCmd());
            setListField(instance, FIELD_ENTRY_POINT, containerConfig.getEntrypoint());
            setField(instance, FIELD_VOLUME_DRIVER, fromInspect, "Config", "VolumeDriver");
        }

        if (containerConfig != null && hostConfig != null) {
            setVolumes(instance, containerConfig.getVolumes(), hostConfig.getBinds());
            setPorts(instance, safeGetExposedPorts(containerConfig), hostConfig.getPortBindings());
        }

        if (hostConfig != null) {
            setField(instance, FIELD_PRIVILEGED, hostConfig.isPrivileged());
            setField(instance, FIELD_PUBLISH_ALL_PORTS, hostConfig.isPublishAllPorts());
            setLxcConf(instance, hostConfig.getLxcConf());
            setListField(instance, FIELD_DNS, hostConfig.getDns());
            setListField(instance, FIELD_DNS_SEARCH, hostConfig.getDnsSearch());
            setCapField(instance, FIELD_CAP_ADD, hostConfig.getCapAdd());
            setCapField(instance, FIELD_CAP_DROP, hostConfig.getCapDrop());
            setRestartPolicy(instance, hostConfig.getRestartPolicy());
            setDevices(instance, hostConfig.getDevices());
        }

        setNetworkMode(instance, containerConfig, hostConfig);
        setField(instance, FIELD_SECURITY_OPT, fromInspect, "HostConfig", "SecurityOpt");
        setField(instance, FIELD_PID_MODE, fromInspect, "HostConfig", "PidMode");
        setField(instance, FIELD_READ_ONLY, fromInspect, "HostConfig", "ReadonlyRootfs");
        setField(instance, FIELD_EXTRA_HOSTS, fromInspect, "HostConfig", "ExtraHosts");
        setFieldIfNotEmpty(instance, FIELD_CPU_SHARES, fromInspect, "HostConfig", "CpuShares");
        setFieldIfNotEmpty(instance, FIELD_CPU_SET, fromInspect, "HostConfig", "CpusetCpus");
        setFieldIfNotEmpty(instance, FIELD_MEMORY, fromInspect, "HostConfig", "Memory");
        setFieldIfNotEmpty(instance, FIELD_MEMORY_SWAP, fromInspect, "HostConfig", "MemorySwap");
        setLogConfig(instance, fromInspect);
        setLabels(instance, fromInspect);

        // Currently not implemented: VolumesFrom, Links,
        // Consider: AttachStdin, AttachStdout, AttachStderr, StdinOnce,
    }

    void setNetworkMode(Instance instance, ContainerConfig containerConfig, HostConfig hostConfig) {
        if(DataAccessor.fields(instance).withKey(FIELD_NETWORK_MODE).get() != null)
            return;

        String netMode = null;
        if (containerConfig != null && containerConfig.isNetworkDisabled()) {
            netMode = NETWORK_MODE_NONE;
        } else if (hostConfig != null) {
            String inspectNetMode = hostConfig.getNetworkMode();
            if (NETWORK_MODE_BRIDGE.equals(inspectNetMode) ||
                    NETWORK_MODE_HOST.equals(inspectNetMode) ||
                    NETWORK_MODE_NONE.equals(inspectNetMode)) {
                netMode = inspectNetMode;
            } else if (StringUtils.isBlank(inspectNetMode)) {
                netMode = NETWORK_MODE_BRIDGE;
            } else if (StringUtils.startsWith(inspectNetMode, NETWORK_MODE_CONTAINER)) {
                throw new ClientVisibleException(ResponseCodes.UNPROCESSABLE_ENTITY, ValidationErrorCodes.INVALID_OPTION,
                        "Transformer API does not support container network mode.", null);
            } else {
                throw new ClientVisibleException(ResponseCodes.UNPROCESSABLE_ENTITY, ValidationErrorCodes.INVALID_OPTION,
                        "Unrecognized network mode: " + inspectNetMode, null);
            }
        }

        setField(instance, FIELD_NETWORK_MODE, netMode);
    }

    void setField(Instance instance, String field, Map<String, Object> fromInspect, String... keys) {
        Object l = CollectionUtils.getNestedValue(fromInspect, keys);
        setField(instance, field, l);
    }

    void setFieldIfNotEmpty(Instance instance, String field, Map<String, Object> fromInspect, String... keys) {
        Object l = CollectionUtils.getNestedValue(fromInspect, keys);
        if (!isEmptyValue(l)) {
            setField(instance, field, l);
        }
    }

    @SuppressWarnings("unchecked")
    void setLogConfig(Instance instance, Map<String, Object> fromInspect) {
        Object type = CollectionUtils.getNestedValue(fromInspect, "HostConfig", "LogConfig", "Type");
        Object config = CollectionUtils.getNestedValue(fromInspect, "HostConfig", "LogConfig", "Config");

        if (type == null && config == null) {
            return;
        }

        LogConfig logConfig = new LogConfig();
        if (type != null) {
            logConfig.setDriver(type.toString());
        }
        if (config instanceof Map) {
            logConfig.setConfig((Map<String, String>)config);
        }

        setField(instance, FIELD_LOG_CONFIG, logConfig);
    }

    @SuppressWarnings({ "rawtypes" })
    void setLabels(Instance instance, Map<String, Object> fromInspect) {
        // Labels not yet implemented in docker-java. Need to use the raw map
        Object l = CollectionUtils.getNestedValue(fromInspect, "Config", "Labels");
        Map<String, String> cleanedLabels = new HashMap<String, String>();
        if (l instanceof Map) {
            Map labels = (Map)l;
            for (Object key : labels.keySet()) {
                if (key == null)
                    continue;
                Object value = labels.get(key);
                if (value == null)
                    value = "";
                cleanedLabels.put(key.toString(), value.toString());
            }
        }
        setField(instance, FIELD_LABELS, cleanedLabels);
    }

    void setImage(Instance instance, String image) {
        if (StringUtils.isNotBlank(image) && !image.matches(IMAGE_KIND_PATTERN)) {
            image = IMAGE_PREFIX + image;
        }

        setField(instance, FIELD_IMAGE_UUID, image);
    }

    void setName(Instance instance, InspectContainerResponse inspect) {
        String name = inspect.getName();
        if (name != null) {
            name = name.replaceFirst("/", "");
            instance.setName(name);
        }
    }

    private ExposedPort[] safeGetExposedPorts(ContainerConfig containerConfig) {
        try {
            return containerConfig.getExposedPorts();
        } catch (NullPointerException e) {
            // Bug in docker-java doesn't account for this property being null
            return null;
        }
    }

    void setDevices(Instance instance, Device[] devices) {
        if (devices == null) {
            devices = new Device[0];
        }

        List<String> instanceDevices = new ArrayList<String>();
        for (Device d : devices) {
            StringBuilder fullDevice = new StringBuilder(d.getPathOnHost()).append(":").append(d.getPathInContainer()).append(":");
            if (StringUtils.isEmpty(d.getcGroupPermissions())) {
                fullDevice.append("rwm");
            } else {
                fullDevice.append(d.getcGroupPermissions());
            }
            instanceDevices.add(fullDevice.toString());
        }

        setField(instance, FIELD_DEVICES, instanceDevices);
    }

    void setRestartPolicy(Instance instance, RestartPolicy restartPolicy) {
        if (restartPolicy == null || StringUtils.isEmpty(restartPolicy.getName())) {
            return;
        }

        io.cattle.platform.core.addon.RestartPolicy rp = new io.cattle.platform.core.addon.RestartPolicy();
        rp.setMaximumRetryCount(restartPolicy.getMaximumRetryCount());
        rp.setName(restartPolicy.getName());
        setField(instance, FIELD_RESTART_POLICY, rp);
    }

    void setCapField(Instance instance, String field, Capability[] caps) {
        if (caps == null) {
            caps = new Capability[0];
        }

        List<String> list = new ArrayList<String>();
        for (Capability cap : caps) {
            list.add(cap.toString());
        }
        setField(instance, field, list);
    }

    void setLxcConf(Instance instance, LxcConf[] lxcConf) {
        if (lxcConf == null || lxcConf.length == 0) {
            lxcConf = new LxcConf[0];
        }

        Map<String, String> instanceLxcConf = new HashMap<String, String>();
        for (LxcConf lxc : lxcConf) {
            instanceLxcConf.put(lxc.getKey(), lxc.getValue());
        }

        setField(instance, FIELD_LXC_CONF, instanceLxcConf);
    }

    void setPorts(Instance instance, ExposedPort[] exposedPorts, Ports portBindings) {
        if (exposedPorts == null) {
            exposedPorts = new ExposedPort[0];
        }

        List<String> ports = new ArrayList<String>();
        for (ExposedPort ep : exposedPorts) {
            String port = ep.toString();

            Binding[] bindings = portBindings == null || portBindings.getBindings() == null ? null : portBindings.getBindings().get(ep);
            if (bindings != null && bindings.length > 0) {
                for (Binding b : bindings) {
                    // HostPort should really be a string, not an int.  Somehow empty string becomes 0
                    if (b.getHostPort() != null && b.getHostPort() != 0) {
                        String fullPort = b.getHostPort() + ":" + port;
                        ports.add(fullPort);
                    } else {
                        ports.add(port);
                    }
                }
            } else {
                ports.add(port);
            }
        }

        setField(instance, FIELD_PORTS, ports);
    }

    void setVolumes(Instance instance, Map<String, ?> volumes, String[] binds) {
        List<String> dataVolumes = new ArrayList<String>();
        if (volumes != null) {
            dataVolumes.addAll(volumes.keySet());
        }

        if (binds != null) {
            dataVolumes.addAll(Arrays.asList(binds));
        }

        setField(instance, FIELD_DATA_VOLUMES, dataVolumes);
    }

    void setListField(Instance instance, String field, String[] value) {
        if (value == null) {
            value = new String[0];
        }

        List<String> list = new ArrayList<String>(Arrays.asList(value));
        setField(instance, field, list);
    }

    void setCommand(Instance instance, String[] cmd) {
        if (cmd == null) {
            cmd = new String[0];
        }

        List<String> args = new ArrayList<String>();
        args.addAll(Arrays.asList(cmd));
        setField(instance, FIELD_COMMAND, args);
    }

    void setEnvironment(Instance instance, String[] env) {
        if (env == null) {
            env = new String[0];
        }

        Map<String, String> envMap = new HashMap<String, String>();
        for (String e : env) {
            String[] kvp = e.split("=", 2);
            if (kvp.length == 2) {
                envMap.put(kvp[0], kvp[1]);
            } else if (kvp.length == 1) {
                // TODO Change the Rancher API to support valueless environment variables.
                // -e FOO and -e FOO="" are not the same thing.
                envMap.put(kvp[0], "");
            }
        }
        setField(instance, FIELD_ENVIRONMENT, envMap);
    }

    private void setField(Instance instance, String field, Object fieldValue) {
        fieldValue = fixEmptyValue(fieldValue);
        DataAccessor.fields(instance).withKey(field).set(fieldValue);
    }

    @SuppressWarnings({ "rawtypes", "unused" })
    private Object fixEmptyValue(Object fieldValue) {
        if (fieldValue instanceof String && StringUtils.isEmpty((String)fieldValue)) {
            return null;
        } else if (fieldValue instanceof Number && ((Number)fieldValue).longValue() == 0L) {
            return null;
        } else if (fieldValue instanceof List && fieldValue == null) {
            return new ArrayList();
        } else if (fieldValue instanceof Map && fieldValue == null) {
            return new HashMap();
        }
        return fieldValue;
    }

    private boolean isEmptyValue(Object fieldValue) {
        return fieldValue == null ||
                (fieldValue instanceof String && StringUtils.isEmpty((String) fieldValue)) ||
                (fieldValue instanceof Number && ((Number) fieldValue).longValue() == 0L) ||
                (fieldValue instanceof List && fieldValue == null) ||
                (fieldValue instanceof Map && fieldValue == null);
    }

    InspectContainerResponse transformInspect(Map<String, Object> inspect) {
        return jsonMapper.convertValue(inspect, InspectContainerResponse.class);
    }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Function template mismatch</title>
<link rel="stylesheet" href="../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../../index.html" title="Boost.Test">
<link rel="up" href="../../../header/boost/test/utils/algorithm_hpp.html" title="Header <boost/test/utils/algorithm.hpp>">
<link rel="prev" href="mismatch_idp27972960.html" title="Function template mismatch">
<link rel="next" href="find_first_not_idp27990016.html" title="Function template find_first_not_of">

Home
Libraries
People
FAQ
More

Function template mismatch

boost::unit_test::utils::mismatch — this algorithm search through two collections for first mismatch position that get returned as a pair of iterators, first pointing to the mismatch position in first collection, second iterator in second one. This algorithms uses supplied predicate for collection elements comparison

Synopsis

// In header: <boost/test/utils/algorithm.hpp>

template<typename InputIter1, typename InputIter2, typename Predicate>
  std::pair< InputIter1, InputIter2 >
  mismatch(InputIter1 first1, InputIter1 last1, InputIter2 first2,
           InputIter2 last2, Predicate pred);

Description

<col align="left" valign="top">

Parameters:

<col align="left" valign="top">

first1

- first collection begin iterator

first2

- second collection begin iterator

last1

- first collection end iterator

last2

- second collection end iterator

pred

- predicate to be used for search

Copyright © 2001-2016 Boost.Test contributors

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
package org.apache.druid.frame.channel;

import com.google.common.util.concurrent.ListenableFuture;
import org.apache.druid.frame.Frame;

import java.io.Closeable;

/**
 * Interface for reading a sequence of frames. Supports nonblocking reads through the {@link #canRead()} and
 * {@link #readabilityFuture()} methods.
 *
 * May be implemented using an in-memory queue, disk file, stream, etc.
 *
 * Channels implementing this interface are used by a single reader; they do not support concurrent reads.
 */
public interface ReadableFrameChannel extends Closeable
{
  /**
   * Returns whether this channel is finished. Finished channels will not generate any further frames or errors.
   *
   * Generally, once you discover that a channel is finished, you should call {@link #close()} and then
   * discard it.
   *
   * Note that it is possible for a channel to be unfinished and also have no available frames or errors. This happens
   * when it is not in a ready-for-reading state. See {@link #readabilityFuture()} for details.
   */
  boolean isFinished();

  /**
   * Returns whether this channel has a frame or error condition currently available. If this method returns true, then
   * you can call {@link #read()} to retrieve the frame or error.
   *
   * Note that it is possible for a channel to be unfinished and also have no available frames or errors. This happens
   * when it is not in a ready-for-reading state. See {@link #readabilityFuture()} for details.
   */
  boolean canRead();

  /**
   * Returns the next available frame from this channel.
   *
   * Before calling this method, you should check {@link #canRead()} to ensure there is a frame or
   * error available.
   *
   * @throws java.util.NoSuchElementException if there is no frame currently available
   */
  Frame read();

  /**
   * Returns a future that will resolve when either {@link #isFinished()} or {@link #canRead()} would
   * return true. The future will never resolve to an exception. If something exceptional has happened, the exception
   * can be retrieved from {@link #read()}.
   */
  ListenableFuture<?> readabilityFuture();

  /**
   * Releases any resources associated with this readable channel. After calling this, you should not call any other
   * methods on the channel.
   */
  @Override
  void close();
}


text:
FROM python:3.7.4-alpine3.9
RUN apk --update add build-base bash jpeg-dev zlib-dev python3-dev
ENV PYTHONUNBUFFERED 1
ENV DEMO_DB_NAME /db.sqlite3
RUN mkdir -p /app
WORKDIR /app

RUN pip install \
    pillow \
    "Django<4.0" \
    choice-enum==1.0.0 \
    "django-bootstrap3>=12.0.1" \
    "python-dateutil>=2.8.1" \
    django_extensions

COPY . .
RUN pip install . demo/ && \
    demo migrate --no-input && \
    demo loaddata demo/demo/fixtures/users.json && \
    demo loaddata demo/demo/fixtures/picker.json && \
    demo import_picks tests/nfl2019.json

EXPOSE 80
RUN echo Load at http://localhost:8080
CMD ["demo", "runserver", "0:80"]


text:
<?php

return [
    /*
    |--------------------------------------------------------------------------
    | Default meta values
    |--------------------------------------------------------------------------
    |
    | The meta keys needed for HMS and a suitable  default value
    | Use php artisan meta:sync to insert missing defaults into the database
    |
    */
    'meta' => [
        'access_guest_wifi_password' => 123456,
        'access_guest_wifi_ssid' => 'HSNOTTS-guest',
        'access_inner_door' => 1234,
        'access_roden_street_door' => 1234,
        'access_street_door' => 1234,
        'access_wifi_password' => 123456,
        'access_wifi_ssid' => 'HSNOTTS',
        'audit_revoke_interval' => 'P2M',
        'audit_warn_interval' => 'P1M14D',
        'content_block_github_url' => 'https://github.com/NottingHack/hms2',
        'google_group_html' => 'https://groups.google.com/group/nottinghack?hl=en',
        'induction_request_html' => 'https://goo.gl/Jl59IM',
        'label_printer_ip' => 'localhost',
        'member_box_cost' => -500,
        'member_box_individual_limit' => 3,
        'member_box_limit' => 129,
        'member_credit_limit' => 0,
        'members_guide_html' => 'https://guide.nottinghack.org.uk',
        'members_guide_pdf' => 'https://readthedocs.org/projects/nottingham-hackspace-members-guide/downloads/pdf/latest/',
        'members_meeting_schedule' => 'first wednesday',
        'members_meeting_reminder_days_before' => 8,
        'purge_cutoff_interval' => 'P6M',
        'quorum_percent' => 20,
        'rules_html' => 'https://rules.nottinghack.org.uk',
        'slack_html' => 'http://slack.nottinghack.org.uk',
        'self_book_info_text' => 'Based on current government guidelines your can only bring guest from you household into the space!',
        'self_book_max_concurrent_per_user' => 1,
        'self_book_max_guests_per_user' => 1,
        'self_book_max_length' => 180,
        'self_book_min_period_between_bookings' => 720,
        'so_bank_id' => 2,
        'temporary_access_email_link' => 'https://wiki.nottinghack.org.uk',
        'temporary_access_notification_delay' => 5,
        'temporary_access_rfid_window' => 10,
        'temporary_access_trustee_notification' => 120,
        'temporary_access_uesr_notification' => 30,
        'wiki_html' => 'https://wiki.nottinghack.org.uk',
        'zone_occupant_reset_interval' => 'P1D',
    ],
];


text:
<?php
namespace Workflow\Execution\Handler\Service\Exception;

class RegistryItemAlreadyExistsException extends \RuntimeException {

}


text:
import argparse
import logging
import sys

from mopy.android import AndroidShell
from mopy.config import Config

USAGE = ('android_mojo_shell.py [<shell-and-app-args>] [<mojo-app>]')

def main():
  logging.basicConfig()

  parser = argparse.ArgumentParser(usage=USAGE)

  debug_group = parser.add_mutually_exclusive_group()
  debug_group.add_argument('--debug', help='Debug build (default)',
                           default=True, action='store_true')
  debug_group.add_argument('--release', help='Release build', default=False,
                           dest='debug', action='store_false')
  parser.add_argument('--target-cpu', help='CPU architecture to run for.',
                      choices=['x64', 'x86', 'arm'], default='arm')
  parser.add_argument('--origin', help='Origin for mojo: URLs.',
                      default='localhost')
  parser.add_argument('--device', help='Serial number of the target device.')
  parser.add_argument('--verbose', default=False, action='store_true')
  parser.add_argument('--apk', help='Name of the APK to run.',
                      default='MojoRunner.apk')
  runner_args, args = parser.parse_known_args()

  logger = logging.getLogger()
  logging.basicConfig(stream=sys.stdout, format='%(levelname)s:%(message)s')
  logger.setLevel(logging.DEBUG if runner_args.verbose else logging.WARNING)
  logger.debug('Initialized logging: level=%s' % logger.level)

  config = Config(target_os=Config.OS_ANDROID,
                  target_cpu=runner_args.target_cpu,
                  is_debug=runner_args.debug,
                  apk_name=runner_args.apk)
  shell = AndroidShell(config)
  shell.InitShell(runner_args.origin, runner_args.device)
  p = shell.ShowLogs()
  shell.StartActivity('MojoShellActivity', args, sys.stdout, p.terminate)
  return 0

if __name__ == '__main__':
  sys.exit(main())


text:
namespace Contour.Transport.RabbitMQ.Internal
{
    internal enum OperationStopReason
    {
        Regular,
        Terminate
    }
}


text:
'use strict';

require('mocha');
var fs = require('fs');
var assert = require('assert');
var Base = require('base');
var vfs = require('base-fs');
var del = require('delete');
var rename = require('./');
var base;

describe('base-rename', function() {
  describe('plugin', function() {
    it('should export a function', function() {
      assert.equal(typeof rename, 'function');
    });

    it('should register as a plugin', function() {
      base = new Base({isApp: true});
      base.use(rename());
      assert.equal(typeof base.rename, 'function');
    });
  });

  describe('rename', function() {
    beforeEach(function() {
      base = new Base({isApp: true});
      base.use(rename());
      base.use(vfs());
    });

    afterEach(function(cb) {
      del('actual/', cb);
    });

    it('should rename a directory', function(cb) {
      base.src('fixtures/a.txt')
        .pipe(base.dest(base.rename('actual')))
        .on('end', function() {
          fs.stat('actual/a.txt', function(err) {
            assert(!err);
            cb();
          });
        });
    });

    it('should rename a file', function(cb) {
      base.src('fixtures/a.txt')
        .pipe(base.dest(base.rename('actual', {basename: 'foo.txt'})))
        .on('end', function() {
          fs.stat('actual/foo.txt', function(err) {
            assert(!err);
            cb();
          });
        });
    });

    it('should rename a file with second arg as a string', function(cb) {
      base.src('fixtures/a.txt')
        .pipe(base.dest(base.rename('actual', 'foo.txt')))
        .on('end', function() {
          fs.stat('actual/foo.txt', function(err) {
            assert(!err);
            cb();
          });
        });
    });

    it('should replace non-word characters when opts.replace is true', function(cb) {
      base = new Base();
      base.isApp = true;
      base.use(rename({ replace: true }));
      base.use(vfs());

      base.src('fixtures/*')
        .pipe(base.dest(base.rename('actual')))
        .on('end', function() {
          fs.stat('actual/.dotfile', function(err) {
            assert(!err);
            cb();
          });
        });
    });
  });
});


text:
function GramMatrix()
  local net = nn.Sequential()
  net:add(nn.View(-1):setNumInputDims(2))
  local concat = nn.ConcatTable()
  concat:add(nn.Identity())
  concat:add(nn.Identity())
  net:add(concat)
  net:add(nn.MM(false, true))
  return net
end

local StyleLoss, parent = torch.class('nn.StyleLoss', 'nn.Module')

function StyleLoss:__init(strength, target, normalize)
  parent.__init(self)
  self.normalize = normalize or false
  self.strength = strength
  self.target = target
  self.loss = 0

  self.gram = GramMatrix()
  self.G = nil
  self.crit = nn.MSECriterion()
end

function StyleLoss:updateOutput(input)
  self.G = self.gram:forward(input)
  self.G:div(input:nElement())
  self.loss = self.crit:forward(self.G, self.target)
  self.loss = self.loss * self.strength
  self.output = input
  return self.output
end

function StyleLoss:updateGradInput(input, gradOutput)
  local dG = self.crit:backward(self.G, self.target)
  dG:div(input:nElement())
  self.gradInput = self.gram:backward(input, dG)
  if self.normalize then
    self.gradInput:div(torch.norm(self.gradInput, 1) + 1e-8)
  end
  self.gradInput:mul(self.strength)
  self.gradInput:add(gradOutput)
  return self.gradInput
end


text: window.globalNamespacePollution = "I'm a bad developer"


text:
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#include "basetypes.h"

void RNG_Reset ();
void RNG_AddEntropy (const void *entropy, SZ size);
U32  RNG_Int32 ();
void RNG_Bytes (void *data, SZ size);

#ifdef __cplusplus
}
#endif


text:
package com.clem.ipoca1.menuhandler;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Build;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;

import com.clem.ipoca1.R;
import com.clem.ipoca1.core.preferences.UserPreferences;

/**
 * Utilities for menu items
 */
public class MenuItemUtils extends com.clem.ipoca1.core.menuhandler.MenuItemUtils {

    public static void adjustTextColor(Context context, SearchView sv) {
        if(Build.VERSION.SDK_INT < 14) {
            EditText searchEditText = (EditText) sv.findViewById(R.id.search_src_text);
            if(UserPreferences.getTheme() == R.style.Theme_AntennaPod_Dark) {
                searchEditText.setTextColor(Color.WHITE);
            } else {
                searchEditText.setTextColor(Color.BLACK);
            }
        }
    }

    @SuppressWarnings("ResourceType")
    public static void refreshLockItem(Context context, Menu menu) {
        final MenuItem queueLock = menu.findItem(R.id.queue_lock);
        int[] lockIcons = new int[] { R.attr.ic_lock_open, R.attr.ic_lock_closed };
        TypedArray ta = context.obtainStyledAttributes(lockIcons);
        if (UserPreferences.isQueueLocked()) {
            queueLock.setTitle(R.string.unlock_queue);
            queueLock.setIcon(ta.getDrawable(0));
        } else {
            queueLock.setTitle(R.string.lock_queue);
            queueLock.setIcon(ta.getDrawable(1));
        }
        ta.recycle();
    }

}


text:
package com.iluwatar.eip.wiretap.routes;

import org.apache.camel.EndpointInject;
import org.apache.camel.Message;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.junit.Assert.assertEquals;

/**
 * Test class for WireTapRoute.
 *

 * In order for it to work we have to mock endpoints we want to read/write to. To mock those we need to substitute
 * original endpoint names to mocks.
 *

 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = WireTapRouteTest.class)
@ActiveProfiles("test")
@EnableAutoConfiguration
@ComponentScan
public class WireTapRouteTest {

  @EndpointInject(uri = "{{entry}}")
  private ProducerTemplate entry;

  @EndpointInject(uri = "{{endpoint}}")
  private MockEndpoint endpoint;

  @EndpointInject(uri = "{{wireTapEndpoint}}")
  private MockEndpoint wireTapEndpoint;

  /**
   * Test if both endpoints receive exactly one message containing the same, unchanged body.
   * @throws Exception in case of en exception during the test
   */
  @Test
  @DirtiesContext
  public void testWireTap() throws Exception {
    entry.sendBody("TEST");

    endpoint.expectedMessageCount(1);
    wireTapEndpoint.expectedMessageCount(1);

    endpoint.assertIsSatisfied();
    wireTapEndpoint.assertIsSatisfied();

    Message endpointIn = endpoint.getExchanges().get(0).getIn();
    Message wireTapEndpointIn = wireTapEndpoint.getExchanges().get(0).getIn();

    assertEquals("TEST", endpointIn.getBody());
    assertEquals("TEST", wireTapEndpointIn.getBody());
  }
}


text:
package org.mindinformatics.gwt.domeo.plugins.annotation.micropubs.model;

import org.mindinformatics.gwt.framework.component.resources.model.MLinkedResource;

public class MMpQualifier extends MMpElement {

	private MLinkedResource qualifier;

	public MLinkedResource getQualifier() {
		return qualifier;
	}

	public void setQualifier(MLinkedResource qualifier) {
		this.qualifier = qualifier;
	}
}


text:
FOUNDATION_EXPORT double ObjectiveGitVersionNumber;

//! Project version string for ObjectiveGit.
FOUNDATION_EXPORT const unsigned char ObjectiveGitVersionString[];

#import <ObjectiveGit/GTRepository.h>
#import <ObjectiveGit/GTRepository+Attributes.h>
#import <ObjectiveGit/GTRepository+Stashing.h>
#import <ObjectiveGit/GTRepository+Committing.h>
#import <ObjectiveGit/GTRepository+Status.h>
#import <ObjectiveGit/GTRepository+References.h>
#import <ObjectiveGit/GTRepository+RemoteOperations.h>
#import <ObjectiveGit/GTRepository+Reset.h>
#import <ObjectiveGit/GTRepository+Pull.h>
#import <ObjectiveGit/GTRepository+Merging.h>
#import <ObjectiveGit/GTEnumerator.h>
#import <ObjectiveGit/GTCommit.h>
#import <ObjectiveGit/GTCredential.h>
#import <ObjectiveGit/GTSignature.h>
#import <ObjectiveGit/GTTree.h>
#import <ObjectiveGit/GTTreeEntry.h>
#import <ObjectiveGit/GTTreeBuilder.h>
#import <ObjectiveGit/GTBlob.h>
#import <ObjectiveGit/GTBlame.h>
#import <ObjectiveGit/GTBlameHunk.h>
#import <ObjectiveGit/GTTag.h>
#import <ObjectiveGit/GTIndex.h>
#import <ObjectiveGit/GTIndexEntry.h>
#import <ObjectiveGit/GTReference.h>
#import <ObjectiveGit/GTBranch.h>
#import <ObjectiveGit/GTObject.h>
#import <ObjectiveGit/GTRemote.h>
#import <ObjectiveGit/GTConfiguration.h>
#import <ObjectiveGit/GTReflog.h>
#import <ObjectiveGit/GTReflogEntry.h>
#import <ObjectiveGit/GTOID.h>
#import <ObjectiveGit/GTSubmodule.h>
#import <ObjectiveGit/GTStatusDelta.h>
#import <ObjectiveGit/GTRepository+Blame.h>
#import <ObjectiveGit/GTFilter.h>
#import <ObjectiveGit/GTFilterList.h>
#import <ObjectiveGit/GTFilterSource.h>
#import <ObjectiveGit/GTFetchHeadEntry.h>
#import <ObjectiveGit/GTNote.h>

#import <ObjectiveGit/GTObjectDatabase.h>
#import <ObjectiveGit/GTOdbObject.h>

#import <ObjectiveGit/NSError+Git.h>
#import <ObjectiveGit/NSData+Git.h>
#import <ObjectiveGit/NSDate+GTTimeAdditions.h>
#import <ObjectiveGit/NSString+Git.h>
#import <ObjectiveGit/NSArray+StringArray.h>

#import <ObjectiveGit/GTDiff.h>
#import <ObjectiveGit/GTDiffDelta.h>
#import <ObjectiveGit/GTDiffFile.h>
#import <ObjectiveGit/GTDiffHunk.h>
#import <ObjectiveGit/GTDiffLine.h>
#import <ObjectiveGit/GTDiffPatch.h>


text:
<?xml version="1.0" encoding="UTF-8"?>
<entities do-package="com.dianping.cat.alarm" gen="true">
	<entity name="alert" table="alert" alias="al">
		<member name="creation-date" insert-expr="NOW()" />
		<var name="start-time" value-type="Date" />
		<var name="end-time" value-type="Date" />
		<var name="categories" value-type="String[]" />
		<param name="domain" />
		<query-defs>
			<query name="query-alerts-by-time-domain" type="SELECT"
				multiple="true">
				<param name="start-time" />
				<param name="end-time" />
				<param name="domain" />
				<statement><![CDATA[
					SELECT <FIELDS/>
			        FROM

			        WHERE <FIELD name='alert-time'/> >= ${start-time}
					AND <FIELD name='alert-time'/> <= ${end-time}
					<IF type='NOT_NULL' field='domain'>
						AND <FIELD name='domain'/> = ${domain}
					</IF>
					ORDER BY <FIELD name='alert-time'/> desc
					]]></statement>
			</query>
			<query name="query-alerts-by-time-domain-categories" type="SELECT"
				multiple="true">
				<param name="start-time" />
				<param name="end-time" />
				<param name="domain" />
				<param name="categories" />
				<statement><![CDATA[
					SELECT <FIELDS/>
			        FROM

			        WHERE <FIELD name='alert-time'/> >= ${start-time}
					AND <FIELD name='alert-time'/> <= ${end-time}
					<IF type='NOT_NULL' field='domain'>
						AND <FIELD name='domain'/> = ${domain}
					</IF>
					AND <FIELD name='category'/> in <IN>${categories}</IN>
					ORDER BY <FIELD name='alert-time'/> desc
					]]></statement>
			</query>
			<query name="query-alerts-by-time-category-domain" type="SELECT"
				multiple="true">
				<param name="start-time" />
				<param name="end-time" />
				<param name="category" />
				<param name="domain" />
				<statement><![CDATA[
					SELECT <FIELDS/>
			        FROM

			        WHERE <FIELD name='alert-time'/> >= ${start-time}
					AND <FIELD name='alert-time'/> <= ${end-time}
					<IF type='NOT_NULL' field='category'>
						AND <FIELD name='category'/> = ${category}
					</IF>
					<IF type='NOT_NULL' field='domain'>
						AND <FIELD name='domain'/> = ${domain}
					</IF>
					ORDER BY <FIELD name='alert-time'/> asc
					]]></statement>
			</query>
			<query name="query-alerts-by-time-category" type="SELECT"
				multiple="true">
				<param name="start-time" />
				<param name="end-time" />
				<param name="category" />
				<statement><![CDATA[
					SELECT <FIELDS/>
			        FROM

			        WHERE <FIELD name='alert-time'/> >= ${start-time}
					AND <FIELD name='alert-time'/> <= ${end-time}
					<IF type='NOT_NULL' field='category'>
						AND <FIELD name='category'/> = ${category}
					</IF>
					ORDER BY <FIELD name='alert-time'/> asc
					]]></statement>
			</query>
		</query-defs>
	</entity>
    <entity name="user-define-rule" table="user_define_rule" alias="udr">
    	<member name="max-id" value-type="int" all="false" select-expr="max(id)" length="19" nullable="false" />
    	<member name="creation-date" insert-expr="NOW()" />
    	<readsets>
	    	<readset name="maxid">
				<member name="max-id" />
			</readset>
		</readsets>
    	<query-defs>
	     	<query name="find-max-id" type="SELECT" multiple="false">
				<statement><![CDATA[
					SELECT <FIELDS/>
					FROM

					]]></statement>
			</query>
		</query-defs>
    </entity>
    <entity name="server-alarm-rule" table="server_alarm_rule" alias="sar">
	 	<member name="creation-date" insert-expr="NOW()" />
	    <member name="updatetime" insert-expr="NOW()" update-expr="NOW()" />
	    <query-defs>
	      <query name="find-all" type="SELECT" multiple="true">
	        <statement><![CDATA[SELECT <FIELDS/>
	        FROM

	        ]]></statement>
	      </query>
	    </query-defs>
	</entity>
</entities>


text:
/*
 * index.js: Top-level include for the mongohq module.
 *
 * (C) 2012 Charlie Robbins, Ken Perkins, Ross Kukulinski & the Contributors.
 *
 */

exports.database = require('./database');


text:
package org.antlr.v4.runtime.atn;

import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.misc.MurmurHash;

/**
 * Implements the {@code pushMode} lexer action by calling
 * {@link Lexer#pushMode} with the assigned mode.
 *
 * @author Sam Harwell
 * @since 4.2
 */
public final class LexerPushModeAction implements LexerAction {
	private final int mode;

	/**
	 * Constructs a new {@code pushMode} action with the specified mode value.
	 * @param mode The mode value to pass to {@link Lexer#pushMode}.
	 */
	public LexerPushModeAction(int mode) {
		this.mode = mode;
	}

	/**
	 * Get the lexer mode this action should transition the lexer to.
	 *
	 * @return The lexer mode for this {@code pushMode} command.
	 */
	public int getMode() {
		return mode;
	}

	/**
	 * {@inheritDoc}
	 * @return This method returns {@link LexerActionType#PUSH_MODE}.
	 */
	@Override
	public LexerActionType getActionType() {
		return LexerActionType.PUSH_MODE;
	}

	/**
	 * {@inheritDoc}
	 * @return This method returns {@code false}.
	 */
	@Override
	public boolean isPositionDependent() {
		return false;
	}

	/**
	 * {@inheritDoc}
	 *
	 *
This action is implemented by calling {@link Lexer#pushMode} with the
	 * value provided by {@link #getMode}.

	 */
	@Override
	public void execute(Lexer lexer) {
		lexer.pushMode(mode);
	}

	@Override
	public int hashCode() {
		int hash = MurmurHash.initialize();
		hash = MurmurHash.update(hash, getActionType().ordinal());
		hash = MurmurHash.update(hash, mode);
		return MurmurHash.finish(hash, 2);
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == this) {
			return true;
		}
		else if (!(obj instanceof LexerPushModeAction)) {
			return false;
		}

		return mode == ((LexerPushModeAction)obj).mode;
	}

	@Override
	public String toString() {
		return String.format("pushMode(%d)", mode);
	}
}


text:
#     @controller =  ExamplesController.new

#     stub_const('Rails', double(:cache => {:fetch => {}}))
#   end

#   describe '#etag_remote_asset' do
#     it 'does something' do
#       @controller.etag_remote_asset
#     end

#   end

# end


text:
So it probably bugged you in the first example that when you submitted a
name, nothing on the page changed. This was improved when the list and the
count of attendees improved, but there is an easier solution if the action
that is being performed doesn't immediately show up. We use the
`set_message` method which adds specific variables to the template only once
and it also handles situations where a user is redirected after a successful
full page POST request.

Note: we don't actually use this that often because often we "show" the user
what action they've performed (for instance, by shifting focus onto the
comment they just posted) rather than "telling" them that it succeeded.

#### In `attendance/views.py`:
```python
class AttendanceEntryStep10Component(AttendanceEntryStep9Component):
    template_name = "example/step_10/entry_component.html"

    def handler(self, request):
        ret = super(AttendanceEntryStep10Component, self).handler(request)
        if ret is True:
            self.set_message(message_type="marked_attendance_successfully",
                             message_text="") # message_text is optional

class AttendanceStep10Page(AttendanceStep9Page):
    template_name = "example/step_10/attendance_page.html"
```

#### In `step_10/entry_component.html`:
```django
<h2>Add new attendee</h2>

Add a new attendee (Currently {{ num_attendees }} attending)

<form method="POST" action="{{ this_form_url }}">
    {% csrf_token %}
    {% if message_type == 'marked_attendance_successfully' %}
    <div style="color: green;" id="saved_div">
        {# Note: we could also use {{ message_text }} here if we set it #}
        Saved!
    </div>
    <script type="text/javascript">
        var oldonload = window.onload || function () {};
        window.onload = function () {
            $('#saved_div').fadeOut(3000);
            oldonload.call(window);
        };
        (function () {
            $('#saved_div').fadeOut(3000);
        })();
    </script>
    {% endif %}
    {{ attendance_form.as_p }}
    <input type="submit">
</form>
```

* [View the result of example 10 locally](http://127.0.0.1:8000/10/)

Cool! That's more than the basics of the `Component` framework, you should
now be able to do all of the important things with the system. It may be
worth going through it again and trying to rebuild the app from memory.
After you're happy, you may want to glance at
[Advanced Topics](../advanced_topics.md) to know what else you may need to
know in the future.

##### Back to [Component Framework Tutorial](00_intro.md)


text:
Phar object: unset file
--SKIPIF--
<?php if (!extension_loaded('phar')) die('skip'); ?>
<?php if (!extension_loaded("spl")) die("skip SPL not available"); ?>
--INI--
phar.readonly=1
phar.require_hash=0
--FILE--
<?php

try
{
	$pharconfig = 0;

	require_once 'files/phar_oo_test.inc';

	$phar = new Phar($fname);
	$phar->setInfoClass('SplFileObject');

	$phar['f.php'] = 'hi';
	var_dump(isset($phar['f.php']));
	echo $phar['f.php'];
	echo "\n";
	unset($phar['f.php']);
	var_dump(isset($phar['f.php']));
}
catch (BadMethodCallException $e)
{
	echo "Exception: " . $e->getMessage() . "\n";
}

?>
===DONE===
--CLEAN--
<?php
unlink(dirname(__FILE__) . '/files/phar_oo_012b.phar.php');
__halt_compiler();
?>
--EXPECTF--
Exception: Write operations disabled by the php.ini setting phar.readonly
===DONE===


text:
<?xml version="1.0" encoding="UTF-8"?><definitions xmlns="http://ws.apache.org/ns/synapse">
    <registry provider="org.wso2.carbon.mediation.registry.WSO2Registry">
        <parameter name="cachableDuration">15000</parameter>
    </registry>
    <proxy xmlns="http://ws.apache.org/ns/synapse" name="enrichSample2" transports="https,http" statistics="disable" trace="disable" startOnLoad="true">
        <target>
            <inSequence>
                <log level="full" />

                <send>
                    <endpoint>
                        <address uri="http://localhost:9000/services/SimpleStockQuoteService" />
                    </endpoint>
                </send>
            </inSequence>
            <outSequence>
                <log level="full" />

                <enrich>
                    <source type="inline" clone="true">
                        <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
                            <soapenv:Header>
                                <TestHeader>Test</TestHeader>
                            </soapenv:Header>
                            <soapenv:Body>

                                <ns:getQuoteResponse xmlns:ns="http://services.samples">
                                    <ns:return xmlns:ax21="http://services.samples/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ax21:GetQuoteResponse">
                                        <ax21:change>3.863100261988071</ax21:change>
                                        <ax21:earnings>-9.934701745247875</ax21:earnings>
                                        <ax21:high>-93.88647573070926</ax21:high>
                                        <ax21:last>94.71661466590444</ax21:last>
                                        <ax21:lastTradeTimestamp>Wed Jul 25 14:11:46 IST 2012</ax21:lastTradeTimestamp>
                                        <ax21:name>ABC Company</ax21:name>
                                        <ax21:symbol>ABC</ax21:symbol>
                                        <ax21:newTag>Test Field</ax21:newTag>
                                    </ns:return>
                                </ns:getQuoteResponse>
                            </soapenv:Body>
                        </soapenv:Envelope>
                    </source>
                    <target type="property" property="payload"/>
                </enrich>

                <enrich>
                    <source type="property" property="payload" />

                    <target type="envelope" />
                </enrich>

                <log level="full" />
                <send />
            </outSequence>
        </target>

        <description></description>
    </proxy>
    <sequence name="fault">
        <log level="full">
            <property name="MESSAGE" value="Executing default 'fault' sequence"/>
            <property name="ERROR_CODE" expression="get-property('ERROR_CODE')"/>
            <property name="ERROR_MESSAGE" expression="get-property('ERROR_MESSAGE')"/>
        </log>
        <drop/>
    </sequence>
    <sequence name="main">
        <in>
            <log level="full"/>
            <filter source="get-property('To')" regex="http://localhost:9000.*">
                <send/>
            </filter>
        </in>
        <out>
            <send/>
        </out>
    </sequence>
</definitions>