text:
//  **********************************************************************************
//  CassiniDev - http://cassinidev.codeplex.com
//
//  Copyright (c) 2010 Sky Sanders. All rights reserved.
//  Copyright (c) Microsoft Corporation. All rights reserved.
//
//  This source code is subject to terms and conditions of the Microsoft Public
//  License (Ms-PL). A copy of the license can be found in the license.txt file
//  included in this distribution.
//
//  You must not remove this notice, or any other, from this software.
//
//  **********************************************************************************

#region

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.Remoting;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Hosting;
using CassiniDev.Configuration;
using CassiniDev.ServerLog;

#endregion

namespace CassiniDev
{
    ///
    ///
    [PermissionSet(SecurityAction.LinkDemand, Name = "Everything"),
     PermissionSet(SecurityAction.InheritanceDemand, Name = "FullTrust")]
    public class Server : MarshalByRefObject, IDisposable
    {
        private readonly bool _useLogger;
        ///
        ///
        public List<string> Plugins = new List<string>();
        ///
        ///
        public readonly ApplicationManager ApplicationManager;

        private readonly bool _disableDirectoryListing;

        private readonly string _hostName;

        private readonly IPAddress _ipAddress;

        private readonly object _lockObject;

        private readonly string _physicalPath;

        private readonly int _port;
        private readonly bool _requireAuthentication;
        //private readonly int _timeoutInterval;
        private readonly string _virtualPath;
        private bool _disposed;

        private Host _host;

        private IntPtr _processToken;

        private string _processUser;

        //private int _requestCount;

        private bool _shutdownInProgress;

        private Socket _socket;

        //private Timer _timer;

        private string _appId;
        ///
        ///
        public string AppId
		{
			get { return _appId; }
		}
        ///
        ///
        public AppDomain HostAppDomain
        {
            get
            {
                if (_host == null)
                {
                    GetHost();
                }
                if (_host != null)
                {
                    return _host.AppDomain;
                }
                return null;
            }
        }

        ///
        ///
        ///<param name="port"></param>
        ///<param name="virtualPath"></param>
        ///<param name="physicalPath"></param>
        public Server(int port, string virtualPath, string physicalPath)
            : this(port, virtualPath, physicalPath, false, false)
        {
        }

        ///
        ///
        ///<param name="port"></param>
        ///<param name="physicalPath"></param>
        public Server(int port, string physicalPath)
            : this(port, "/", physicalPath, IPAddress.Loopback)
        {
        }

        ///
        ///
        ///<param name="physicalPath"></param>
        public Server(string physicalPath)
            : this(CassiniNetworkUtils.GetAvailablePort(32768, 65535, IPAddress.Loopback, false), physicalPath)
        {
        }

        ///
        ///
        ///<param name="port"></param>
        ///<param name="virtualPath"></param>
        ///<param name="physicalPath"></param>
        ///<param name="ipAddress"></param>
        ///<param name="hostName"></param>
        ///<param name="requireAuthentication"></param>
        public Server(int port, string virtualPath, string physicalPath, IPAddress ipAddress, string hostName,
                      bool requireAuthentication)
            : this(port, virtualPath, physicalPath, ipAddress, hostName, requireAuthentication, false)
        {
        }

        ///
        ///
        ///<param name="port"></param>
        ///<param name="virtualPath"></param>
        ///<param name="physicalPath"></param>
        ///<param name="requireAuthentication"></param>
        public Server(int port, string virtualPath, string physicalPath, bool requireAuthentication)
            : this(port, virtualPath, physicalPath, requireAuthentication, false)
        {
        }

        ///
        ///
        ///<param name="port"></param>
        ///<param name="virtualPath"></param>
        ///<param name="physicalPath"></param>
        ///<param name="ipAddress"></param>
        ///<param name="hostName"></param>
        public Server(int port, string virtualPath, string physicalPath, IPAddress ipAddress, string hostName)
            : this(port, virtualPath, physicalPath, ipAddress, hostName, false, false)
        {
        }

        ///
        ///
        ///<param name="port"></param>
        ///<param name="virtualPath"></param>
        ///<param name="physicalPath"></param>
        ///<param name="ipAddress"></param>
        ///<param name="hostName"></param>
        ///<param name="requireAuthentication"></param>
        ///<param name="disableDirectoryListing"></param>
        public Server(int port, string virtualPath, string physicalPath, IPAddress ipAddress, string hostName,
                      bool requireAuthentication, bool disableDirectoryListing)
            : this(port, virtualPath, physicalPath, requireAuthentication, disableDirectoryListing)
        {
            _ipAddress = ipAddress;
            _hostName = hostName;
            //_timeoutInterval = timeout;
        }

        ///
        ///
        ///<param name="port"></param>
        ///<param name="virtualPath"></param>
        ///<param name="physicalPath"></param>
        ///<param name="ipAddress"></param>
        public Server(int port, string virtualPath, string physicalPath, IPAddress ipAddress)
            : this(port, virtualPath, physicalPath, ipAddress, null, false, false)
        {
        }

        ///
        ///
        ///<param name="port"></param>
        ///<param name="virtualPath"></param>
        ///<param name="physicalPath"></param>
        ///<param name="requireAuthentication"></param>
        ///<param name="disableDirectoryListing"></param>
        public Server(int port, string virtualPath, string physicalPath, bool requireAuthentication,
                      bool disableDirectoryListing)
        {
            try
            {
                Assembly.ReflectionOnlyLoad("Common.Logging");
                _useLogger = true;
            }
            // ReSharper disable EmptyGeneralCatchClause
            catch
            // ReSharper restore EmptyGeneralCatchClause
            {
            }
            _ipAddress = IPAddress.Loopback;
            _requireAuthentication = requireAuthentication;
            _disableDirectoryListing = disableDirectoryListing;
            _lockObject = new object();
            _port = port;
            _virtualPath = virtualPath;
            _physicalPath = Path.GetFullPath(physicalPath);
            _physicalPath = _physicalPath.EndsWith("\\", StringComparison.Ordinal)
                                ? _physicalPath
                                : _physicalPath + "\\";
            ProcessConfiguration();

            ApplicationManager = ApplicationManager.GetApplicationManager();
            string uniqueAppString = string.Concat(virtualPath, physicalPath,":",_port.ToString()).ToLowerInvariant();
            _appId = (uniqueAppString.GetHashCode()).ToString("x", CultureInfo.InvariantCulture);
            ObtainProcessToken();
        }

        private void ProcessConfiguration()
        {
            // #TODO: how to identify profile to use?
            // current method is to either use default '*' profile or match port
            // port can be an arbitrary value, especially in testing scenarios so
            // perhaps a regex based path matching strategy can also be offered

            var config = CassiniDevConfigurationSection.Instance;
            if (config != null)
            {
                foreach (CassiniDevProfileElement profile in config.Profiles)
                {
                    if (profile.Port == "*" || Convert.ToInt64(profile.Port) == _port)
                    {
                        foreach (PluginElement plugin in profile.Plugins)
                        {
                            Plugins.Insert(0, plugin.Type);
                        }
                    }
                }
            }
        }

        ///
        ///
        ///<param name="physicalPath"></param>
        ///<param name="requireAuthentication"></param>
        public Server(string physicalPath, bool requireAuthentication)
            : this(
                CassiniNetworkUtils.GetAvailablePort(32768, 65535, IPAddress.Loopback, false), "/", physicalPath,
                requireAuthentication)
        {
        }

        ///
        ///
        public bool DisableDirectoryListing
        {
            get { return _disableDirectoryListing; }
        }

        ///
        ///
        public bool RequireAuthentication
        {
            get { return _requireAuthentication; }
        }

        /////
        /////
        //public int TimeoutInterval
        //{
        //    get { return _timeoutInterval; }
        //}

        ///
        ///
        public string HostName
        {
            get { return _hostName; }
        }

        ///
        ///
// ReSharper disable InconsistentNaming
        public IPAddress IPAddress
// ReSharper restore InconsistentNaming
        {
            get { return _ipAddress; }
        }

        ///
        ///
        public string PhysicalPath
        {
            get { return _physicalPath; }
        }

        ///
        ///
        public int Port
        {
            get { return _port; }
        }

        ///
        ///
        public string RootUrl
        {
            get
            {
                string hostname = _hostName;
                if (string.IsNullOrEmpty(_hostName))
                {
                    if (_ipAddress.Equals(IPAddress.Loopback) || _ipAddress.Equals(IPAddress.IPv6Loopback) ||
                        _ipAddress.Equals(IPAddress.Any) || _ipAddress.Equals(IPAddress.IPv6Any))
                    {
                        hostname = "localhost";
                    }
                    else
                    {
                        hostname = _ipAddress.ToString();
                    }
                }

                return _port != 80
                           ?
                               String.Format("http://{0}:{1}{2}", hostname, _port, _virtualPath)
                           :
                    //FIX: #12017 - TODO:TEST
                       string.Format("http://{0}{1}", hostname, _virtualPath);
            }
        }

        ///
        ///
        public string VirtualPath
        {
            get { return _virtualPath; }
        }

        #region IDisposable Members

        ///
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        ///
        /// <filterpriority>2</filterpriority>
        public void Dispose()
        {
            if (!_disposed)
            {
                ShutDown();
            }
            _disposed = true;
            GC.SuppressFinalize(this);
        }

        #endregion

        ///
        ///
        public event EventHandler<RequestEventArgs> RequestComplete;

        /////
        /////
        //public event EventHandler TimedOut;

        ///
        ///
        ///<returns></returns>
        public IntPtr GetProcessToken()
        {
            return _processToken;
        }

        ///
        ///
        ///<returns></returns>
        public string GetProcessUser()
        {
            return _processUser;
        }

        ///
        ///
        public void HostStopped()
        {
            _host = null;
        }

        ///
        /// Obtains a lifetime service object to control the lifetime policy for this instance.
        ///
        /// <returns>
        /// An object of type <see cref="T:System.Runtime.Remoting.Lifetime.ILease"/> used to control the lifetime policy for this instance. This is the current lifetime service object for this instance if one exists; otherwise, a new lifetime service object initialized to the value of the <see cref="P:System.Runtime.Remoting.Lifetime.LifetimeServices.LeaseManagerPollTime"/> property.
        /// </returns>
        /// <exception cref="T:System.Security.SecurityException">The immediate caller does not have infrastructure permission.
        ///                 </exception><filterpriority>2</filterpriority><PermissionSet><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="RemotingConfiguration, Infrastructure"/></PermissionSet>
        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
        public override object InitializeLifetimeService()
        {
            // never expire the license
            return null;
        }

        // called at the end of request processing
        // to disconnect the remoting proxy for Connection object
        // and allow GC to pick it up
        ///
        ///
        /// <param name="conn"></param>
        /// <param name="userName"></param>
        public void OnRequestEnd(Connection conn, string userName)
        {
            try
            {
                LogInfo connRequestLogClone = conn.RequestLog.Clone();
                connRequestLogClone.Identity = userName;
                LogInfo connResponseLogClone = conn.ResponseLog.Clone();
                connResponseLogClone.Identity = userName;
                OnRequestComplete(conn.Id, connRequestLogClone, connResponseLogClone);
            }
            catch
            {
                // swallow - we don't want consumer killing the server
            }
            RemotingServices.Disconnect(conn);
            //DecrementRequestCount();
        }

        ///
        ///
        public void Start()
        {
            _socket = CreateSocketBindAndListen(AddressFamily.InterNetwork, _ipAddress, _port);

            //start the timer
            //DecrementRequestCount();

            ThreadPool.QueueUserWorkItem(delegate
                {
                    while (!_shutdownInProgress)
                    {
                        try
                        {
                            Socket acceptedSocket = _socket.Accept();

                            ThreadPool.QueueUserWorkItem(delegate
                                {
                                    if (!_shutdownInProgress)
                                    {
                                        Connection conn = new Connection(this, acceptedSocket);

                                        if (conn.WaitForRequestBytes() == 0)
                                        {
                                            conn.WriteErrorAndClose(400);
                                            return;
                                        }

                                        Host host = GetHost();

                                        if (host == null)
                                        {
                                            conn.WriteErrorAndClose(500);
                                            return;
                                        }

                                        //IncrementRequestCount();
                                        host.ProcessRequest(conn);
                                    }
                                });
                        }
                        catch
                        {
                            Thread.Sleep(100);
                        }
                    }
                });
        }

        ///
        /// Allows an <see cref="T:System.Object"/> to attempt to free resources and perform other cleanup operations before the <see cref="T:System.Object"/> is reclaimed by garbage collection.
        ///
        ~Server()
        {
            Dispose();
        }

        private static Socket CreateSocketBindAndListen(AddressFamily family, IPAddress address, int port)
        {
            Socket socket = new Socket(family, SocketType.Stream, ProtocolType.Tcp);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            socket.Bind(new IPEndPoint(address, port));
            socket.Listen((int)SocketOptionName.MaxConnections);
            return socket;
        }

        ///
        ///
        ///
        /// <param name="virtualPath"></param>
        /// <param name="physicalPath"></param>
        /// <param name="hostType"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        /// <remarks>
        /// This is Dmitry's hack to enable running outside of GAC.
        /// There are some errors being thrown when running in proc
        /// </remarks>
        private object CreateWorkerAppDomainWithHost(string virtualPath, string physicalPath, Type hostType,int port)
        {

            // create BuildManagerHost in the worker app domain
            //ApplicationManager appManager = ApplicationManager.GetApplicationManager();
            Type buildManagerHostType = typeof(HttpRuntime).Assembly.GetType("System.Web.Compilation.BuildManagerHost");
            IRegisteredObject buildManagerHost = ApplicationManager.CreateObject(_appId, buildManagerHostType, virtualPath,
                                                                          physicalPath, false);

            // call BuildManagerHost.RegisterAssembly to make Host type loadable in the worker app domain
            buildManagerHostType.InvokeMember("RegisterAssembly",
                                              BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic,
                                              null,
                                              buildManagerHost,
                                              new object[] { hostType.Assembly.FullName, hostType.Assembly.Location });

            // create Host in the worker app domain
            // FIXME: getting FileLoadException Could not load file or assembly 'WebDev.WebServer20, Version=4.0.1.6, Culture=neutral, PublicKeyToken=f7f6e0b4240c7c27' or one of its dependencies. Failed to grant permission to execute. (Exception from HRESULT: 0x80131418)
            // when running dnoa 3.4 samples - webdev is registering trust somewhere that we are not
            return ApplicationManager.CreateObject(_appId, hostType, virtualPath, physicalPath, false);
        }

        //private void DecrementRequestCount()
        //{
        //    lock (_lockObject)
        //    {
        //        _requestCount--;

        //        if (_requestCount < 1)
        //        {
        //            _requestCount = 0;

        //            if (_timeoutInterval > 0 && _timer == null)
        //            {
        //                _timer = new Timer(TimeOut, null, _timeoutInterval, Timeout.Infinite);
        //            }
        //        }
        //    }
        //}

        private Host GetHost()
        {
            if (_shutdownInProgress)
                return null;
            Host host = _host;
            if (host == null)
            {
#if NET40
                object obj2 = new object();
                bool flag = false;
                try
                {
                    Monitor.Enter(obj2 = _lockObject, ref flag);
                    host = _host;
                    if (host == null)
                    {
                        host = (Host)CreateWorkerAppDomainWithHost(_virtualPath, _physicalPath, typeof(Host),Port);
                        host.Configure(this, _port, _virtualPath, _physicalPath, _requireAuthentication, _disableDirectoryListing);
                        _host = host;
                    }
                }
                finally
                {
                    if (flag)
                    {
                        Monitor.Exit(obj2);
                    }
                }
#else

                lock (_lockObject)
                {
                    host = _host;
                    if (host == null)
                    {
                        host = (Host)CreateWorkerAppDomainWithHost(_virtualPath, _physicalPath, typeof(Host),Port);
                        host.Configure(this, _port, _virtualPath, _physicalPath, _requireAuthentication, _disableDirectoryListing);
                        _host = host;
                    }
                }

#endif
            }

            return host;
        }

        //private void IncrementRequestCount()
        //{

        //    lock (_lockObject)
        //    {
        //        _requestCount++;

        //        if (_timer != null)
        //        {

        //            _timer.Dispose();
        //            _timer = null;
        //        }
        //    }
        //}

        private void ObtainProcessToken()
        {
            if (Interop.ImpersonateSelf(2))
            {
                Interop.OpenThreadToken(Interop.GetCurrentThread(), 0xf01ff, true, ref _processToken);
                Interop.RevertToSelf();
                // ReSharper disable PossibleNullReferenceException
                _processUser = WindowsIdentity.GetCurrent().Name;
                // ReSharper restore PossibleNullReferenceException
            }
        }

        private void OnRequestComplete(Guid id, LogInfo requestLog, LogInfo responseLog)
        {
            PublishLogToCommonLogging(requestLog);
            PublishLogToCommonLogging(responseLog);

            EventHandler<RequestEventArgs> complete = RequestComplete;

            if (complete != null)
            {
                complete(this, new RequestEventArgs(id, requestLog, responseLog));
            }
        }

        private void PublishLogToCommonLogging(LogInfo item)
        {
            if(!_useLogger )
            {
                return;
            }

            Common.Logging.ILog logger = Common.Logging.LogManager.GetCurrentClassLogger();

            var bodyAsString = String.Empty;
            try
            {
                bodyAsString = Encoding.UTF8.GetString(item.Body);
            }
            // ReSharper disable EmptyGeneralCatchClause
            catch
            // ReSharper restore EmptyGeneralCatchClause
            {
                /* empty bodies should be allowed */
            }

            var type = item.RowType == 0 ? "" : item.RowType == 1 ? "Request" : "Response";
            logger.Debug(type + " | " +
                          item.Created + " | " +
                          item.StatusCode + " | " +
                          item.Url + " | " +
                          item.PathTranslated + " | " +
                          item.Identity + " | " +
                          "\n===>Headers<====\n" + item.Headers +
                          "\n===>Body<=======\n" + bodyAsString
                );
        }

        ///
        ///
        public void ShutDown()
        {
            if (_shutdownInProgress)
            {
                return;
            }

            _shutdownInProgress = true;

            try
            {
                if (_socket != null)
                {
                    _socket.Close();
                }
            }
            // ReSharper disable EmptyGeneralCatchClause
            catch
            // ReSharper restore EmptyGeneralCatchClause
            {
                // TODO: why the swallow?
            }
            finally
            {
                _socket = null;
            }

            try
            {
                if (_host != null)
                {
                    _host.Shutdown();
                }

                // the host is going to raise an event that this class uses to null the field.
                // just wait until the field is nulled and continue.

                while (_host != null)
                {
                    new AutoResetEvent(false).WaitOne(100);
                }
            }
            // ReSharper disable EmptyGeneralCatchClause
            catch
            // ReSharper restore EmptyGeneralCatchClause
            {
                // TODO: what am i afraid of here?
            }

        }

        //private void TimeOut(object ignored)
        //{
        //    TimeOut();
        //}

        /////
        /////
        //public void TimeOut()
        //{
        //    ShutDown();
        //    OnTimeOut();
        //}

        //private void OnTimeOut()
        //{
        //    EventHandler handler = TimedOut;
        //    if (handler != null) handler(this, EventArgs.Empty);
        //}
    }
}


text:
module PartialDependencies
  VERSION = "0.0.1"
end

redpajama_set_name: RedPajamaGithub


text:
require 'opennebula/pool_element'

module OpenNebula
    class Cluster < PoolElement
        #######################################################################
        # Constants and Class Methods
        #######################################################################

        CLUSTER_METHODS = {
            :info           => "cluster.info",
            :allocate       => "cluster.allocate",
            :delete         => "cluster.delete",
            :addhost        => "cluster.addhost",
            :delhost        => "cluster.delhost",
            :adddatastore   => "cluster.adddatastore",
            :deldatastore   => "cluster.deldatastore",
            :addvnet        => "cluster.addvnet",
            :delvnet        => "cluster.delvnet",
            :update         => "cluster.update",
            :rename         => "cluster.rename"
        }

        # Creates a Cluster description with just its identifier
        # this method should be used to create plain Cluster objects.
        # +id+ the id of the host
        #
        # Example:
        #   cluster = Cluster.new(Cluster.build_xml(3),rpc_client)
        #
        def Cluster.build_xml(pe_id=nil)
            if pe_id
                cluster_xml = "<CLUSTER><ID>#{pe_id}</ID></CLUSTER>"
            else
                cluster_xml = "<CLUSTER></CLUSTER>"
            end

            XMLElement.build_xml(cluster_xml,'CLUSTER')
        end

        # Class constructor
        def initialize(xml, client)
            super(xml,client)
        end

        #######################################################################
        # XML-RPC Methods for the Cluster Object
        #######################################################################

        # Retrieves the information of the given Cluster.
        def info()
            super(CLUSTER_METHODS[:info], 'CLUSTER')
        end

        alias_method :info!, :info

        # Allocates a new Cluster in OpenNebula
        #
        # +clustername+ A string containing the name of the Cluster.
        def allocate(clustername)
            super(CLUSTER_METHODS[:allocate], clustername)
        end

        # Deletes the Cluster
        def delete()
            super(CLUSTER_METHODS[:delete])
        end

        # Adds a Host to this Cluster
        # @param hid [Integer] Host ID
        # @return [nil, OpenNebula::Error] nil in case of success, Error
        #   otherwise
        def addhost(hid)
            return Error.new('ID not defined') if !@pe_id

            rc = @client.call(CLUSTER_METHODS[:addhost], @pe_id, hid)
            rc = nil if !OpenNebula.is_error?(rc)

            return rc
        end

        # Deletes a Host from this Cluster
        # @param hid [Integer] Host ID
        # @return [nil, OpenNebula::Error] nil in case of success, Error
        #   otherwise
        def delhost(hid)
            return Error.new('ID not defined') if !@pe_id

            rc = @client.call(CLUSTER_METHODS[:delhost], @pe_id, hid)
            rc = nil if !OpenNebula.is_error?(rc)

            return rc
        end

        # Adds a Datastore to this Cluster
        # @param ds_id [Integer] Datastore ID
        # @return [nil, OpenNebula::Error] nil in case of success, Error
        #   otherwise
        def adddatastore(ds_id)
            return Error.new('ID not defined') if !@pe_id

            rc = @client.call(CLUSTER_METHODS[:adddatastore], @pe_id, ds_id)
            rc = nil if !OpenNebula.is_error?(rc)

            return rc
        end

        # Deletes a Datastore from this Cluster
        # @param ds_id [Integer] Datastore ID
        # @return [nil, OpenNebula::Error] nil in case of success, Error
        #   otherwise
        def deldatastore(ds_id)
            return Error.new('ID not defined') if !@pe_id

            rc = @client.call(CLUSTER_METHODS[:deldatastore], @pe_id, ds_id)
            rc = nil if !OpenNebula.is_error?(rc)

            return rc
        end

        # Adds a VNet to this Cluster
        # @param vnet_id [Integer] VNet ID
        # @return [nil, OpenNebula::Error] nil in case of success, Error
        #   otherwise
        def addvnet(vnet_id)
            return Error.new('ID not defined') if !@pe_id

            rc = @client.call(CLUSTER_METHODS[:addvnet], @pe_id, vnet_id)
            rc = nil if !OpenNebula.is_error?(rc)

            return rc
        end

        # Deletes a VNet from this Cluster
        # @param vnet_id [Integer] VNet ID
        # @return [nil, OpenNebula::Error] nil in case of success, Error
        #   otherwise
        def delvnet(vnet_id)
            return Error.new('ID not defined') if !@pe_id

            rc = @client.call(CLUSTER_METHODS[:delvnet], @pe_id, vnet_id)
            rc = nil if !OpenNebula.is_error?(rc)

            return rc
        end

        # Replaces the template contents
        #
        # @param new_template [String] New template contents
        # @param append [true, false] True to append new attributes instead of
        #   replace the whole template
        #
        # @return [nil, OpenNebula::Error] nil in case of success, Error
        #   otherwise
        def update(new_template, append=false)
            super(CLUSTER_METHODS[:update], new_template, append ? 1 : 0)
        end

        # Renames this Cluster
        #
        # @param name [String] New name for the Cluster.
        #
        # @return [nil, OpenNebula::Error] nil in case of success, Error
        #   otherwise
        def rename(name)
            return call(CLUSTER_METHODS[:rename], @pe_id, name)
        end

        # ---------------------------------------------------------------------
        # Helpers to get information
        # ---------------------------------------------------------------------

        # Returns whether or not the host with 'id' is part of this cluster
        # @param id [Integer|Array] host ID
        # @return [Boolean] true if found
        def contains_host?(id)
            contains_resource?('HOSTS/ID', id)
        end

        # Returns an array with the numeric host ids
        # @return [Array<Integer>]
        def host_ids
            array = Array.new

            self.each("HOSTS/ID") do |id|
                array << id.text.to_i
            end

            return array
        end

        # Returns whether or not the datastore with 'id' is part of this cluster
        # @param id [Integer|Array] datastore ID
        # @return [Boolean] true if found
        def contains_datastore?(id)
            contains_resource?('DATASTORES/ID', id)
        end

        # Returns an array with the numeric datastore ids
        # @return [Array<Integer>]
        def datastore_ids
            array = Array.new

            self.each("DATASTORES/ID") do |id|
                array << id.text.to_i
            end

            return array
        end

        # Returns whether or not the vnet with 'id' is part of this cluster
        # @param id [Integer|Arrray] vnet ID
        # @return [Boolean] true if found
        def contains_vnet?(id)
            contains_resource?('VNETS/ID', id)
        end

        # Returns an array with the numeric vnet ids
        # @return [Array<Integer>]
        def vnet_ids
            array = Array.new

            self.each("VNETS/ID") do |id|
                array << id.text.to_i
            end

            return array
        end

        private

        def contains_resource?(xpath, id)
            id_array = retrieve_elements(xpath)

            return false if id_array.nil?

            id = [id] if id.class != Array

            id.each { |i|
                return false if !id_array.include?(i.to_s)
            }

            return true
        end
    end
end


text:
import * as angular from 'angular';

class BinaryDataManipHelperService{

	constructor(){}
	/**
	*
	*/
	public base64ToArrayBuffer(stringBase64) {
		var binaryString = window.atob(stringBase64);
		var len = binaryString.length;
		var bytes = new Uint8Array(len);
		for (var i = 0; i < len; i++) {
			var ascii = binaryString.charCodeAt(i);
			bytes[i] = ascii;
		}
		return bytes.buffer;
	};

	/**
	*
	*/
	public arrayBufferToBase64(buffer) {
		var binary = '';
		var bytes = new Uint8Array(buffer);
		var len = bytes.byteLength;
		for (var i = 0; i < len; i++) {
			binary += String.fromCharCode(bytes[i]);
		}
		return window.btoa(binary);
	};

	/**
	*
	public stringToArrayBuffer(str) {
		var ab = new ArrayBuffer(str.length);
		var view = new Uint8Array(ab);
		for (var i = 0; i < str.length; ++i) {
			view[i] = str.charCodeAt(i);
		}
		return ab;
	};
	*/

}

angular.module('emuwebApp')
.service('BinaryDataManipHelperService', BinaryDataManipHelperService);


text:
set -euo pipefail
AIRFLOW_SOURCES="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../" && pwd)"

# Check common named remotes for the upstream repo
for remote in origin apache; do
   git remote get-url --push "$remote" 2>/dev/null | grep -q git@github.com:apache/airflow && break
   unset remote
done

: "${remote?Could not find remote configured to push to apache/airflow}"

tags=()
for file in "${AIRFLOW_SOURCES}/dist/"*.whl
do
   if [[ ${file} =~ .*airflow_providers_(.*)-(.*)-py3.* ]]; then
        provider="providers-${BASH_REMATCH[1]}"
        tag="${provider//_/-}/${BASH_REMATCH[2]}"
        { git tag "${tag}" && tags+=("$tag") ; } || true
   fi
done
if [[ -n "${tags:-}" && "${#tags}" -gt 0 ]]; then
   git push $remote "${tags[@]}"
fi


text:
/** Generated by FG **/
@font-face {
	font-family: 'Conv_CircularStd-Book';
	src: url('fonts/CircularStd-Book.eot');
	src: local('☺'), url('fonts/CircularStd-Book.woff') format('woff'), url('fonts/CircularStd-Book.ttf') format('truetype'), url('fonts/CircularStd-Book.svg') format('svg');
	font-weight: normal;
	font-style: normal;
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/dataflow/v1beta3/jobs.proto

namespace Google\Cloud\Dataflow\V1beta3;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Defines a particular step within a Cloud Dataflow job.
 * A job consists of multiple steps, each of which performs some
 * specific operation as part of the overall job.  Data is typically
 * passed from one step to another as part of the job.
 * Here's an example of a sequence of steps which together implement a
 * Map-Reduce job:
 *   * Read a collection of data from some source, parsing the
 *     collection's elements.
 *   * Validate the elements.
 *   * Apply a user-defined function to map each element to some value
 *     and extract an element-specific key value.
 *   * Group elements with the same key into a single element with
 *     that key, transforming a multiply-keyed collection into a
 *     uniquely-keyed collection.
 *   * Write the elements out to some data sink.
 * Note that the Cloud Dataflow service may be used to run many different
 * types of jobs, not just Map-Reduce.
 *
 * Generated from protobuf message google.dataflow.v1beta3.Step
 */
class Step extends \Google\Protobuf\Internal\Message
{
    /**
     * The kind of step in the Cloud Dataflow job.
     *
     * Generated from protobuf field string kind = 1;
     */
    private $kind = '';
    /**
     * The name that identifies the step. This must be unique for each
     * step with respect to all other steps in the Cloud Dataflow job.
     *
     * Generated from protobuf field string name = 2;
     */
    private $name = '';
    /**
     * Named properties associated with the step. Each kind of
     * predefined step has its own required set of properties.
     * Must be provided on Create.  Only retrieved with JOB_VIEW_ALL.
     *
     * Generated from protobuf field .google.protobuf.Struct properties = 3;
     */
    private $properties = null;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $kind
     *           The kind of step in the Cloud Dataflow job.
     *     @type string $name
     *           The name that identifies the step. This must be unique for each
     *           step with respect to all other steps in the Cloud Dataflow job.
     *     @type \Google\Protobuf\Struct $properties
     *           Named properties associated with the step. Each kind of
     *           predefined step has its own required set of properties.
     *           Must be provided on Create.  Only retrieved with JOB_VIEW_ALL.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Dataflow\V1Beta3\Jobs::initOnce();
        parent::__construct($data);
    }

    /**
     * The kind of step in the Cloud Dataflow job.
     *
     * Generated from protobuf field string kind = 1;
     * @return string
     */
    public function getKind()
    {
        return $this->kind;
    }

    /**
     * The kind of step in the Cloud Dataflow job.
     *
     * Generated from protobuf field string kind = 1;
     * @param string $var
     * @return $this
     */
    public function setKind($var)
    {
        GPBUtil::checkString($var, True);
        $this->kind = $var;

        return $this;
    }

    /**
     * The name that identifies the step. This must be unique for each
     * step with respect to all other steps in the Cloud Dataflow job.
     *
     * Generated from protobuf field string name = 2;
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * The name that identifies the step. This must be unique for each
     * step with respect to all other steps in the Cloud Dataflow job.
     *
     * Generated from protobuf field string name = 2;
     * @param string $var
     * @return $this
     */
    public function setName($var)
    {
        GPBUtil::checkString($var, True);
        $this->name = $var;

        return $this;
    }

    /**
     * Named properties associated with the step. Each kind of
     * predefined step has its own required set of properties.
     * Must be provided on Create.  Only retrieved with JOB_VIEW_ALL.
     *
     * Generated from protobuf field .google.protobuf.Struct properties = 3;
     * @return \Google\Protobuf\Struct|null
     */
    public function getProperties()
    {
        return $this->properties;
    }

    public function hasProperties()
    {
        return isset($this->properties);
    }

    public function clearProperties()
    {
        unset($this->properties);
    }

    /**
     * Named properties associated with the step. Each kind of
     * predefined step has its own required set of properties.
     * Must be provided on Create.  Only retrieved with JOB_VIEW_ALL.
     *
     * Generated from protobuf field .google.protobuf.Struct properties = 3;
     * @param \Google\Protobuf\Struct $var
     * @return $this
     */
    public function setProperties($var)
    {
        GPBUtil::checkMessage($var, \Google\Protobuf\Struct::class);
        $this->properties = $var;

        return $this;
    }

}


text:
package org.springframework.http;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.core.log.LogDelegateFactory;

/**
 * Holds the shared logger named "org.springframework.web.HttpLogging" for HTTP
 * related logging when "org.springframework.http" is not enabled but
 * "org.springframework.web" is.
 *
 *
That means "org.springframework.web" enables all web logging including
 * from lower level packages such as "org.springframework.http" and modules
 * such as codecs from {@literal "spring-core"} when those are wrapped with
 * {@link org.springframework.http.codec.EncoderHttpMessageWriter EncoderHttpMessageWriter} or
 * {@link org.springframework.http.codec.DecoderHttpMessageReader DecoderHttpMessageReader}.
 *
 *
To see logging from the primary class loggers simply enable logging for
 * "org.springframework.http" and "org.springframework.codec".
 *
 * @author Rossen Stoyanchev
 * @since 5.1
 * @see LogDelegateFactory
 */
public abstract class HttpLogging {

	private static final Log fallbackLogger =
			LogFactory.getLog("org.springframework.web." + HttpLogging.class.getSimpleName());

	/**
	 * Create a primary logger for the given class and wrap it with a composite
	 * that delegates to it or to the fallback logger
	 * "org.springframework.web.HttpLogging", if the primary is not enabled.
	 * @param primaryLoggerClass the class for the name of the primary logger
	 * @return the resulting composite logger
	 */
	public static Log forLogName(Class<?> primaryLoggerClass) {
		Log primaryLogger = LogFactory.getLog(primaryLoggerClass);
		return forLog(primaryLogger);
	}

	/**
	 * Wrap the given primary logger with a composite logger that delegates to
	 * it or to the fallback logger "org.springframework.web.HttpLogging",
	 * if the primary is not enabled.
	 * @param primaryLogger the primary logger to use
	 * @return the resulting composite logger
	 */
	public static Log forLog(Log primaryLogger) {
		return LogDelegateFactory.getCompositeLog(primaryLogger, fallbackLogger);
	}

}


text:
module ArelExtensions
  module Nodes
    class LevenshteinDistance < Function
      RETURN_TYPE = :number

      def initialize expr
        super [convert_to_node(expr.first), Arel.quoted(expr[1])]
      end
    end
  end
end


text:
"""
    sliding (rolling) window module.

    If you apply sliding window with size='3' to
        [0, 1, 2, 3, 4, 5, 6, 7]
    you will get something like this
        [(0, 1, 2), (1, 2, 3),
            (2, 3, 4), (3, 4, 5),
                (4, 5, 6), (5, 6, 7)]
"""

from __future__ import absolute_import, division, print_function

from shot_detector.utils.collections import RepeatedSlidingWindow

class PointWindow(RepeatedSlidingWindow):
    """
        ...
    """

    __slots__ = []

    class Options(object):
        """
            Options for PointWindow
        """
        check_init_parameters = False
        check_generator_parameters = False

    def __repr__(self):
        """
        Represents `SlidingWindow` as a string.

        :return string: representation
        """
        name = 'sw'
        return "{}({}, {})".format(
            name,
            list(self),
            self.window_size)

    @property
    def features(self):
        """
        :return:
        """
        return self.get_features()

    def get_features(self, **_):
        """

        :param _:
        :return:
        """
        for item in iter(self):
            if hasattr(item, 'feature'):
                yield item.feature

if __name__ == "__main__":
    import doctest

    doctest.testmod()


text:
// (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

angular.module('mm.core.courses')

/**
 * Service to handle site courses.
 *
 * @module mm.core.courses
 * @ngdoc service
 * @name $mmCourses
 */
.factory('$mmCourses', function($q, $mmSite, $log, $mmSitesManager, mmCoursesSearchPerPage, mmCoursesEnrolInvalidKey) {

    $log = $log.getInstance('$mmCourses');

    var self = {},
        currentCourses = {};

    /**
     * Get categories. They can be filtered by id.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#getCategories
     * @param   {Number}  categoryId        Category ID to get.
     * @param   {Boolean} addSubcategories  If add subcategories to the list.
     * @param   {String}  [siteId]          Site to get the courses from. If not defined, use current site.
     * @return  {Promise}                   Promise to be resolved when the categories are retrieved.
     */
    self.getCategories = function(categoryId, addSubcategories, siteId) {
        return $mmSitesManager.getSite(siteId).then(function(site) {
            // Get parent when id is the root category.
            var criteriaKey = categoryId == 0 ? 'parent' : 'id';

            var data = {
                    criteria: [
                        { key: criteriaKey, value: categoryId }
                    ],
                    addsubcategories: addSubcategories ? 1 : 0
                },
                preSets = {
                    cacheKey: getCategoriesCacheKey(categoryId, addSubcategories)
                };

            return site.read('core_course_get_categories', data, preSets);
        });
    };

    /**
     * Get cache key for get categories methods WS call.
     *
     * @param   {Number}    categoryId        Category ID to get.
     * @param   {Boolean}   addSubcategories  If add subcategories to the list.
     * @return  {String}    Cache key.
     */
    function getCategoriesCacheKey(categoryId, addSubcategories) {
        return 'mmCourses:categories:' + categoryId + ':' + addSubcategories;
    }

    /**
     * Given a list of course IDs to get course options, return the list of courseIds to use.
     *
     * @param  {Number[]} courseIds Course IDs.
     * @param  {String} [siteId]    Site Id. If not defined, use current site.
     * @return {Promise}            Promise resolved with the list of course IDs.
     */
    function getCourseIdsForOptions(courseIds, siteId) {
        return $mmSitesManager.getSite(siteId).then(function(site) {
            var siteHomeId = site.getSiteHomeId();

            if (courseIds.length == 1) {
                // Only 1 course, check if it belongs to the user courses. If so, use all user courses.
                return self.getUserCourses(true, siteId).then(function(courses) {
                    var courseId = courseIds[0],
                        useAllCourses = false;

                    if (courseId == siteHomeId) {
                        // It's site home, use all courses.
                        useAllCourses = true;
                    } else {
                        for (var i = 0; i < courses.length; i++) {
                            if (courses[i].id == courseId) {
                                useAllCourses = true;
                                break;
                            }
                        }
                    }

                    if (useAllCourses) {
                        // User is enrolled, retrieve all the courses.
                        courseIds = courses.map(function(course) {
                            return course.id;
                        });

                        // Always add the site home ID.
                        courseIds.push(siteHomeId);
                    }

                    return courseIds;
                }).catch(function() {
                    // Ignore errors.
                    return courseIds;
                });
            } else {
                return courseIds;
            }
        });
    }

    /**
     * Check if get cateogries WS is available.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#isGetCategoriesAvailable
     * @return {Boolean} True if get categories is available, false otherwise.
     */
    self.isGetCategoriesAvailable = function() {
        return $mmSite.wsAvailable('core_course_get_categories');
    };

    /**
     * Check if My Courses is disabled in a certain site.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#isMyCoursesDisabled
     * @param  {String} [siteId] Site Id. If not defined, use current site.
     * @return {Promise}         Promise resolved with true if disabled, rejected or resolved with false otherwise.
     */
    self.isMyCoursesDisabled = function(siteId) {
        return $mmSitesManager.getSite(siteId).then(function(site) {
            return self.isMyCoursesDisabledInSite(site);
        });
    };

    /**
     * Check if My Courses is disabled in a certain site.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#isMyCoursesDisabledInSite
     * @param  {Object} [site] Site. If not defined, use current site.
     * @return {Boolean}       True if disabled, false otherwise.
     */
    self.isMyCoursesDisabledInSite = function(site) {
        site = site || $mmSite;
        return site.isFeatureDisabled('$mmSideMenuDelegate_mmCourses');
    };

    /**
     * Check if Search Courses is disabled in a certain site.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#isSearchCoursesDisabled
     * @param  {String} [siteId] Site Id. If not defined, use current site.
     * @return {Promise}         Promise resolved with true if disabled, rejected or resolved with false otherwise.
     */
    self.isSearchCoursesDisabled = function(siteId) {
        return $mmSitesManager.getSite(siteId).then(function(site) {
            return self.isSearchCoursesDisabledInSite(site);
        });
    };

    /**
     * Check if Search Courses is disabled in a certain site.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#isSearchCoursesDisabledInSite
     * @param  {Object} [site] Site. If not defined, use current site.
     * @return {Boolean}       True if disabled, false otherwise.
     */
    self.isSearchCoursesDisabledInSite = function(site) {
        site = site || $mmSite;
        return site.isFeatureDisabled('$mmCoursesDelegate_search');
    };

    /**
     * DEPRECATED: this function will be removed in a future version.
     * Clear current courses array. Reserved for core use.
     *
     * @deprecated since version 2.5
     * @protected
     */
    self.clearCurrentCourses = function() {
        currentCourses = {};
    };

    /**
     * Get course.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#getCourse
     * @param {Number} id       ID of the course to get.
     * @param {String} [siteid] Site to get the courses from. If not defined, use current site.
     * @return {Promise}        Promise to be resolved when the courses are retrieved.
     */
    self.getCourse = function(id, siteid) {
        return self.getCourses([id], siteid).then(function(courses) {
            if (courses && courses.length > 0) {
                return courses[0];
            }
            return $q.reject();
        });
    };

    /**
     * Get the enrolment methods from a course.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#getCourseEnrolmentMethods
     * @param {Number} id ID of the course.
     * @return {Promise}  Promise to be resolved when the methods are retrieved.
     */
    self.getCourseEnrolmentMethods = function(id) {
        var params = {
                courseid: id
            },
            preSets = {
                cacheKey: getCourseEnrolmentMethodsCacheKey(id)
            };

        return $mmSite.read('core_enrol_get_course_enrolment_methods', params, preSets);
    };

    /**
     * Get cache key for get course enrolment methods WS call.
     *
     * @param  {Number} id Course ID.
     * @return {String}    Cache key.
     */
    function getCourseEnrolmentMethodsCacheKey(id) {
        return 'mmCourses:enrolmentmethods:' + id;
    }

    /**
     * Get info from a course guest enrolment method.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#getCourseGuestEnrolmentInfo
     * @param {Number} instanceId Guest instance ID.
     * @return {Promise}          Promise to be resolved when the info is retrieved.
     */
    self.getCourseGuestEnrolmentInfo = function(instanceId) {
        var params = {
                instanceid: instanceId
            },
            preSets = {
                cacheKey: getCourseGuestEnrolmentInfoCacheKey(instanceId)
            };

        return $mmSite.read('enrol_guest_get_instance_info', params, preSets).then(function(response) {
            return response.instanceinfo;
        });
    };

    /**
     * Get cache key for get course enrolment methods WS call.
     *
     * @param {Number} instanceId Guest instance ID.
     * @return {String}           Cache key.
     */
    function getCourseGuestEnrolmentInfoCacheKey(instanceId) {
        return 'mmCourses:guestinfo:' + instanceId;
    }

    /**
     * Get courses.
     * Warning: if the user doesn't have permissions to view some of the courses passed the WS call will fail.
     * The user must be able to view ALL the courses passed.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#getCourses
     * @param {Number[]} ids    List of IDs of the courses to get.
     * @param {String} [siteid] Site to get the courses from. If not defined, use current site.
     * @return {Promise}        Promise to be resolved when the courses are retrieved.
     */
    self.getCourses = function(ids, siteid) {
        if (!angular.isArray(ids)) {
            return $q.reject();
        } else if (ids.length === 0) {
            return $q.when([]);
        }

        return $mmSitesManager.getSite(siteid).then(function(site) {

            var data = {
                    options: {
                        ids: ids
                    }
                },
                preSets = {
                    cacheKey: getCoursesCacheKey(ids)
                };

            return site.read('core_course_get_courses', data, preSets).then(function(courses) {
                if (typeof courses != 'object' && !angular.isArray(courses)) {
                    return $q.reject();
                }
                return courses;
            });
        });
    };

    /**
     * Get cache key for get courses WS call.
     *
     * @param  {Number[]} ids Courses IDs.
     * @return {String}       Cache key.
     */
    function getCoursesCacheKey(ids) {
        return 'mmCourses:course:' + JSON.stringify(ids);
    }

    /**
     * Get courses. They can be filtered by field.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#getCoursesByField
     * @param {String}  [field]     The field to search can be left empty for all courses or:
     *                                  id: course id.
     *                                  ids: comma separated course ids.
     *                                  shortname: course short name.
     *                                  idnumber: course id number.
     *                                  category: category id the course belongs to.
     * @param {Mixed}   [value]     The value to match.
     * @param {String}  [siteId]    Site to get the courses from. If not defined, use current site.
     * @return {Promise}        Promise to be resolved when the courses are retrieved.
     */
    self.getCoursesByField = function(field, value, siteId) {
        return $mmSitesManager.getSite(siteId).then(function(site) {
            var data = {
                    field: field || "",
                    value: field ? value : ""
                },
                preSets = {
                    cacheKey: getCoursesByFieldCacheKey(field, value)
                };

            return site.read('core_course_get_courses_by_field', data, preSets).then(function(courses) {
                if (courses.courses) {
                    // Courses will be sorted using sortorder if avalaible.
                    return courses.courses.sort(function(a, b) {
                        if (typeof a.sortorder == "undefined" && typeof b.sortorder == "undefined") {
                            return b.id - a.id;
                        }

                        if (typeof a.sortorder == "undefined") {
                            return 1;
                        }

                        if (typeof b.sortorder == "undefined") {
                            return -1;
                        }

                        return a.sortorder - b.sortorder;
                    });
                }
                return $q.reject();
            });
        });
    };

    /**
     * Get cache key for get courses WS call.
     *
     * @param  {String} [field]     The field to search.
     * @param  {Mixed}  [value]     The value to match.
     * @return {String}       Cache key.
     */
    function getCoursesByFieldCacheKey(field, value) {
        field = field || "";
        value = field ? value : "";
        return 'mmCourses:coursesbyfield:' + field + ":" + value;
    }

    /**
     * Check if get courses by field WS is available.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#isGetCoursesByFieldAvailable
     * @return {Boolean} True if get courses by field is available, false otherwise.
     */
    self.isGetCoursesByFieldAvailable = function() {
        return $mmSite.wsAvailable('core_course_get_courses_by_field');
    };

    /**
     * DEPRECATED: this function will be removed in a future version. Please use $mmCourses#getUserCourse.
     * Get a course stored in memory.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#getStoredCourse
     * @param  {Number} id ID of the course to get.
     * @return {Object}    Course.
     * @deprecated since version 2.5
     */
    self.getStoredCourse = function(id) {
        $log.warn('The function \'getStoredCourse\' is deprecated. Please use \'getUserCourse\' instead');
        return currentCourses[id];
    };

    /**
     * Get the navigation and administration options for the given courses.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#getCoursesOptions
     * @param  {Number[]} courseIds IDs of courses to get.
     * @param  {String} [siteId]    Site ID. If not defined, current site.
     * @return {Promise}            Promise resolved with the options for each course.
     */
    self.getCoursesOptions = function(courseIds, siteId) {
        var promises = [],
            navOptions,
            admOptions;

        // Get the list of courseIds to use based on the param.
        return getCourseIdsForOptions(courseIds, siteId).then(function(courseIds) {

            // Get user navigation and administration options.
            promises.push(self.getUserNavigationOptions(courseIds, siteId).catch(function() {
                // Couldn't get it, return empty options.
                return {};
            }).then(function(options) {
                navOptions = options;
            }));

            promises.push(self.getUserAdministrationOptions(courseIds, siteId).catch(function() {
                // Couldn't get it, return empty options.
                return {};
            }).then(function(options) {
                admOptions = options;
            }));

            return $q.all(promises).then(function() {
                return {navOptions: navOptions, admOptions: admOptions};
            });
        });
    };

    /**
     * Get the common part of the cache keys for user administration options WS calls.
     *
     * @return {String} Cache key.
     */
    function getUserAdministrationOptionsCommonCacheKey() {
        return 'mmCourses:administrationOptions:';
    }

    /**
     * Get cache key for get user administration options WS call.
     *
     * @return {String} Cache key.
     */
    function getUserAdministrationOptionsCacheKey(courseIds) {
        return getUserAdministrationOptionsCommonCacheKey() + courseIds.join(',');
    }

    /**
     * Get user administration options for a set of courses.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#getUserAdministrationOptions
     * @param  {Number[]} courseIds IDs of courses to get.
     * @param  {String} [siteId]    Site ID. If not defined, current site.
     * @return {Promise}            Promise resolved with administration options for each course.
     */
    self.getUserAdministrationOptions = function(courseIds, siteId) {
        return $mmSitesManager.getSite(siteId).then(function(site) {
            var params = {
                    courseids: courseIds
                },
                preSets = {
                    cacheKey: getUserAdministrationOptionsCacheKey(courseIds)
                };

            return site.read('core_course_get_user_administration_options', params, preSets).then(function(response) {
                // Format returned data.
                return formatUserOptions(response.courses);
            });
        });
    };

    /**
     * Get a course the user is enrolled in. This function relies on $mmCourses#getUserCourses.
     * preferCache=true will try to speed up the response, but the data returned might not be updated.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#getUserCourse
     * @param {Number} id                   ID of the course to get.
     * @param {Boolean} [preferCache=false] True if shouldn't call WS if data is cached, false otherwise.
     * @param {String} [siteid]             Site to get the courses from. If not defined, use current site.
     * @return {Promise}                    Promise resolved with the course.
     * @since 2.5
     */
    self.getUserCourse = function(id, preferCache, siteid) {
        if (!id) {
            return $q.reject();
        }

        if (typeof preferCache == 'undefined') {
            preferCache = false;
        }

        return self.getUserCourses(preferCache, siteid).then(function(courses) {
            var course;
            angular.forEach(courses, function(c) {
                if (c.id == id) {
                    course = c;
                }
            });
            return course ? course : $q.reject();
        });
    };

    /**
     * Get user courses.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#getUserCourses
     * @param {Boolean} [preferCache=false] True if shouldn't call WS if data is cached, false otherwise.
     * @param {String} [siteid]            Site to get the courses from. If not defined, use current site.
     * @return {Promise}                   Promise to be resolved when the courses are retrieved.
     */
    self.getUserCourses = function(preferCache, siteid) {
        if (typeof preferCache == 'undefined') {
            preferCache = false;
        }

        return $mmSitesManager.getSite(siteid).then(function(site) {

            var userid = site.getUserId(),
                presets = {
                    cacheKey: getUserCoursesCacheKey(),
                    omitExpires: preferCache
                },
                data = {userid: userid};

            if (typeof userid === 'undefined') {
                return $q.reject();
            }

            return site.read('core_enrol_get_users_courses', data, presets).then(function(courses) {
                siteid = siteid || site.getId();
                if (siteid === $mmSite.getId()) {
                    // Only store courses if we're getting current site courses. This function is deprecated and will be removed.
                    storeCoursesInMemory(courses);
                }
                return courses;
            });
        });
    };

    /**
     * Get cache key for get user courses WS call.
     *
     * @return {String}       Cache key.
     */
    function getUserCoursesCacheKey() {
        return 'mmCourses:usercourses';
    }

    /**
     * Get the common part of the cache keys for user navigation options WS calls.
     *
     * @return {String} Cache key.
     */
    function getUserNavigationOptionsCommonCacheKey() {
        return 'mmCourses:navigationOptions:';
    }

    /**
     * Get cache key for get user navigation options WS call.
     *
     * @return {String} Cache key.
     */
    function getUserNavigationOptionsCacheKey(courseIds) {
        return getUserNavigationOptionsCommonCacheKey() + courseIds.join(',');
    }

    /**
     * Get user navigation options for a set of courses.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#getUserNavigationOptions
     * @param  {Number[]} courseIds IDs of courses to get.
     * @param  {String} [siteId]    Site ID. If not defined, current site.
     * @return {Promise}            Promise resolved with navigation options for each course.
     */
    self.getUserNavigationOptions = function(courseIds, siteId) {
        return $mmSitesManager.getSite(siteId).then(function(site) {
            var params = {
                    courseids: courseIds
                },
                preSets = {
                    cacheKey: getUserNavigationOptionsCacheKey(courseIds)
                };

            return site.read('core_course_get_user_navigation_options', params, preSets).then(function(response) {
                // Format returned data.
                return formatUserOptions(response.courses);
            });
        });
    };

    /**
     * Format user navigation or administration options.
     *
     * @param  {Object[]} courses Navigation or administration options for each course.
     * @return {Object}           Formatted options.
     */
    function formatUserOptions(courses) {
        var result = {};

        angular.forEach(courses, function(course) {
            var options = {};

            angular.forEach(course.options, function(option) {
                options[option.name] = option.available;
            });

            result[course.id] = options;
        });

        return result;
    }

    /**
     * Invalidates get categories WS call.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#invalidateCategories
     * @param  {Number}  categoryId          Category id to get.
     * @param  {Boolean} addSubcategories    If add subcategories to the list.
     * @param  {String}  [siteId]            Site Id. If not defined, use current site.
     * @return {Promise}                     Promise resolved when the data is invalidated.
     */
    self.invalidateCategories = function(categoryId, addSubcategories, siteId) {
        return $mmSitesManager.getSite(siteId).then(function(site) {
            return site.invalidateWsCacheForKey(getCategoriesCacheKey(categoryId, addSubcategories));
        });
    };

    /**
     * Invalidates get course WS call.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#invalidateCourse
     * @param  {Number}   id          Course ID.
     * @param  {String}   [siteId]    Site Id. If not defined, use current site.
     * @return {Promise}   Promise resolved when the data is invalidated.
     */
    self.invalidateCourse = function(id, siteId) {
        return self.invalidateCourses([id], siteId);
    };

    /**
     * Invalidates get course enrolment methods WS call.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#invalidateCourseEnrolmentMethods
     * @param {Number} id Course ID.
     * @return {Promise}  Promise resolved when the data is invalidated.
     */
    self.invalidateCourseEnrolmentMethods = function(id) {
        return $mmSite.invalidateWsCacheForKey(getCourseEnrolmentMethodsCacheKey(id));
    };

    /**
     * Invalidates get course guest enrolment info WS call.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#invalidateCourseGuestEnrolmentInfo
     * @param {Number} instanceId Guest instance ID.
     * @return {Promise}          Promise resolved when the data is invalidated.
     */
    self.invalidateCourseGuestEnrolmentInfo = function(instanceId) {
        return $mmSite.invalidateWsCacheForKey(getCourseGuestEnrolmentInfoCacheKey(instanceId));
    };

    /**
     * Invalidates the navigation and administration options for the given courses.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#invalidateCoursesOptions
     * @param  {Number[]} courseIds IDs of courses to get.
     * @param  {String} [siteId]    Site ID to invalidate. If not defined, use current site.
     * @return {Promise}            Promise resolved when the data is invalidated.
     */
    self.invalidateCoursesOptions = function(courseIds, siteId) {
        return getCourseIdsForOptions(courseIds, siteId).then(function(ids) {
            var promises = [];

            promises.push(self.invalidateUserAdministrationOptionsForCourses(ids, siteId));
            promises.push(self.invalidateUserNavigationOptionsForCourses(ids, siteId));

            return $q.all(promises);
        });
    };

    /**
     * Invalidates get courses WS call.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#invalidateCourses
     * @param  {Number[]} ids         Courses IDs.
     * @param  {String}   [siteId]    Site Id. If not defined, use current site.
     * @return {Promise}              Promise resolved when the data is invalidated.
     */
    self.invalidateCourses = function(ids, siteId) {
        return $mmSitesManager.getSite(siteId).then(function(site) {
            return site.invalidateWsCacheForKey(getCoursesCacheKey(ids));
        });
    };

    /**
     * Invalidates get courses by field WS call.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#invalidateCoursesByField
     * @param {String}  [field]     See mmCourses#getCoursesByField for info.
     * @param {Mixed}   [value]     The value to match.
     * @param {String}  [siteId]    Site Id. If not defined, use current site.
     * @return {Promise}   Promise resolved when the data is invalidated.
     */
    self.invalidateCoursesByField = function(field, value, siteId) {
        return $mmSitesManager.getSite(siteId).then(function(site) {
            return site.invalidateWsCacheForKey(getCoursesByFieldCacheKey(field, value));
        });
    };

    /**
     * Invalidates all user administration options.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#invalidateUserAdministrationOptions
     * @param {String} [siteId] Site ID to invalidate. If not defined, use current site.
     * @return {Promise}        Promise resolved when the data is invalidated.
     */
    self.invalidateUserAdministrationOptions = function(siteId) {
        return $mmSitesManager.getSite(siteId).then(function(site) {
            return site.invalidateWsCacheForKeyStartingWith(getUserAdministrationOptionsCommonCacheKey());
        });
    };

    /**
     * Invalidates user administration options for certain courses.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#invalidateUserAdministrationOptionsForCourses
     * @param  {Number[]} courseIds IDs of courses.
     * @param {String} [siteId]     Site ID to invalidate. If not defined, use current site.
     * @return {Promise}            Promise resolved when the data is invalidated.
     */
    self.invalidateUserAdministrationOptionsForCourses = function(courseIds, siteId) {
        return $mmSitesManager.getSite(siteId).then(function(site) {
            return site.invalidateWsCacheForKey(getUserAdministrationOptionsCacheKey(courseIds));
        });
    };

    /**
     * Invalidates get user courses WS call.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#invalidateUserCourses
     * @param {String} [siteid] Site ID to invalidate. If not defined, use current site.
     * @return {Promise}        Promise resolved when the data is invalidated.
     */
    self.invalidateUserCourses = function(siteid) {
        return $mmSitesManager.getSite(siteid).then(function(site) {
            return site.invalidateWsCacheForKey(getUserCoursesCacheKey());
        });
    };

    /**
     * Invalidates all user navigation options.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#invalidateUserNavigationOptions
     * @param {String} [siteId] Site ID to invalidate. If not defined, use current site.
     * @return {Promise}        Promise resolved when the data is invalidated.
     */
    self.invalidateUserNavigationOptions = function(siteId) {
        return $mmSitesManager.getSite(siteId).then(function(site) {
            return site.invalidateWsCacheForKeyStartingWith(getUserNavigationOptionsCommonCacheKey());
        });
    };

    /**
     * Invalidates user navigation options for certain courses.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#invalidateUserNavigationOptionsForCourses
     * @param  {Number[]} courseIds IDs of courses.
     * @param {String} [siteId]     Site ID to invalidate. If not defined, use current site.
     * @return {Promise}            Promise resolved when the data is invalidated.
     */
    self.invalidateUserNavigationOptionsForCourses = function(courseIds, siteId) {
        return $mmSitesManager.getSite(siteId).then(function(site) {
            return site.invalidateWsCacheForKey(getUserNavigationOptionsCacheKey(courseIds));
        });
    };

    /**
     * Check if WS to retrieve guest enrolment data is available.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#isGuestWSAvailable
     * @return {Boolean} True if guest WS is available, false otherwise.
     */
    self.isGuestWSAvailable = function() {
        return $mmSite.wsAvailable('enrol_guest_get_instance_info');
    };

    /**
     * Check if search courses feature is available in the current site.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#isSearchCoursesAvailable
     * @return {Boolean} True if is available, false otherwise.
     */
    self.isSearchCoursesAvailable = function() {
        return $mmSite.wsAvailable('core_course_search_courses');
    };

    /**
     * Check if self enrolment is available.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#isSelfEnrolmentEnabled
     * @return {Boolean} True if self enrolment is available, false otherwise.
     */
    self.isSelfEnrolmentEnabled = function() {
        return $mmSite.wsAvailable('enrol_self_enrol_user');
    };

    /**
     * Search courses.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#search
     * @param {String} text      Text to search.
     * @param {Number} [page]    Page to get. Defaults to 0.
     * @param {Number} [perpage] Number of courses per page. Defaults to mmCoursesSearchPerPage.
     * @return {Promise}         Promise resolved with the courses and the total of matches.
     */
    self.search = function(text, page, perpage) {
        page = page || 0;
        perpage = perpage || mmCoursesSearchPerPage;

        var params = {
                criterianame: 'search',
                criteriavalue: text,
                page: page,
                perpage: perpage
            }, preSets = {
                getFromCache: false
            };

        return $mmSite.read('core_course_search_courses', params, preSets).then(function(response) {
            if (typeof response == 'object') {
                return {total: response.total, courses: response.courses};
            }
            return $q.reject();
        });
    };

    /**
     * Self enrol current user in a certain course.
     *
     * @module mm.core.courses
     * @ngdoc method
     * @name $mmCourses#selfEnrol
     * @param {String} courseid     Course ID.
     * @param {String} [password]   Password to use.
     * @param {Number} [instanceId] Enrol instance ID.
     * @return {Promise}            Promise resolved if the user is enrolled. If the password is invalid,
     *                              the promise is rejected with an object with code = mmCoursesEnrolInvalidKey.
     */
    self.selfEnrol = function(courseid, password, instanceId) {
        if (typeof password == 'undefined') {
            password = '';
        }

        var params = {
            courseid: courseid,
            password: password
        };
        if (instanceId) {
            params.instanceid = instanceId;
        }

        return $mmSite.write('enrol_self_enrol_user', params).then(function(response) {
            if (response) {
                if (response.status) {
                    return true;
                } else if (response.warnings && response.warnings.length) {
                    var message;
                    angular.forEach(response.warnings, function(warning) {
                        // Invalid password warnings.
                        if (warning.warningcode == '2' || warning.warningcode == '3' || warning.warningcode == '4') {
                            message = warning.message;
                        }
                    });

                    if (message) {
                        return $q.reject({code: mmCoursesEnrolInvalidKey, message: message});
                    }
                }
            }
            return $q.reject();
        });
    };

    /**
     * DEPRECATED: this function will be removed in a future version.
     * Stores a list of courses in memory so they can be retrieved later.
     *
     * @param  {Object[]} courses Courses to store
     * @return {Void}
     * @deprecated since version 2.5
     */
    function storeCoursesInMemory(courses) {
        angular.forEach(courses, function(course) {
            currentCourses[course.id] = angular.copy(course); // Store a copy to prevent unwanted modifications.
        });
    }

    return self;
});


text:
/**
 * This software is released as part of the Pumpernickel project.
 *
 * All com.pump resources in the Pumpernickel project are distributed under the
 * MIT License:
 * https://github.com/mickleness/pumpernickel/raw/master/License.txt
 *
 * More information about the Pumpernickel project is available here:
 * https://mickleness.github.io/pumpernickel/
 */
package com.pump.graphics.vector;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.Image;
import java.awt.Paint;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.RenderingHints.Key;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.geom.Arc2D;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Path2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ImageObserver;
import java.awt.image.RenderedImage;
import java.awt.image.renderable.RenderableImage;
import java.text.AttributedCharacterIterator;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.pump.graphics.Graphics2DContext;
import com.pump.image.ImageSize;

/**
 * This is a Graphics2D that stores every drawing instruction as an
 * {@link Operation}. You can create a VectorGraphics2D independently, but it
 * also works well with the {@link VectorImage} class.
 *

 * Graphics2D methods can generally be divided into two groups:
 *

 *
Methods that actually draw something. (For example: they change pixels,
 * like {@link Graphics2D#fill(Shape)}.) These are stored as Operations.

 *
Methods that relate to properties for future Operations. (For example see
 * {@link Graphics2D#setComposite(AlphaComposite)} /
 * {@link Graphics2D#getComposite()}). These calls are all directed to the
 * {@link Graphics2DContext} class. Each new Operation records a snapshot
 * (clone) of the Graphics2DContext of this VectorGraphics2D when it was
 * created.

 *

 */
public class VectorGraphics2D extends Graphics2D {

	protected Graphics2DContext context;
	protected List<Operation> operations;

	/**
	 * Create a new empty VectorGraphics2D.
	 */
	public VectorGraphics2D() {
		this(new Graphics2DContext(), new ArrayList<Operation>());
	}

	/**
	 * Create a VectorGraphics2D that appends all its Operations to the given
	 * argument.
	 *
	 * @param operations
	 */
	public VectorGraphics2D(Graphics2DContext context,
			List<Operation> operations) {
		Objects.requireNonNull(context);
		Objects.requireNonNull(operations);
		this.operations = operations;
		this.context = context;
	}

	/**
	 * Add an Operation to this VectorGraphics2D.
	 *

	 * This method immediately returns if this Graphics2D has been disposed.
	 *
	 * @param operation
	 *            the Operation to add.
	 */
	protected void addOperation(Operation operation) {
		if (context.isDisposed())
			return;

		operations.add(operation);
	}

	/**
	 * Return the underlying list of all Operations.
	 */
	public List<Operation> getOperations() {
		return operations;
	}

	// context-related methods;

	/**
	 * Return a copy of the current Graphics2DContext.
	 */
	public Graphics2DContext getContext() {
		return context.clone();
	}

	@Override
	public void setComposite(Composite comp) {
		context.setComposite(comp);
	}

	@Override
	public void setPaint(Paint paint) {
		context.setPaint(paint);
	}

	@Override
	public void setStroke(Stroke s) {
		context.setStroke(s);
	}

	@Override
	public void setRenderingHint(Key hintKey, Object hintValue) {
		context.setRenderingHint(hintKey, hintValue);
	}

	@Override
	public Object getRenderingHint(Key hintKey) {
		return context.getRenderingHint(hintKey);
	}

	@Override
	public void setRenderingHints(Map<?, ?> hints) {
		context.setRenderingHints(hints);
	}

	@Override
	public void addRenderingHints(Map<?, ?> hints) {
		context.addRenderingHints(hints);
	}

	@Override
	public RenderingHints getRenderingHints() {
		return context.getRenderingHints();
	}

	@Override
	public void translate(int x, int y) {
		context.translate(x, y);
	}

	@Override
	public void translate(double tx, double ty) {
		context.translate(tx, ty);
	}

	@Override
	public void rotate(double theta) {
		context.rotate(theta);
	}

	@Override
	public void rotate(double theta, double x, double y) {
		context.rotate(theta, x, y);
	}

	@Override
	public void scale(double sx, double sy) {
		context.scale(sx, sy);
	}

	@Override
	public void shear(double shx, double shy) {
		context.shear(shx, shy);
	}

	@Override
	public void transform(AffineTransform Tx) {
		context.transform(Tx);
	}

	@Override
	public void setTransform(AffineTransform Tx) {
		context.setTransform(Tx);
	}

	@Override
	public AffineTransform getTransform() {
		return context.getTransform();
	}

	@Override
	public Paint getPaint() {
		return context.getPaint();
	}

	@Override
	public Composite getComposite() {
		return context.getComposite();
	}

	@Override
	public void setBackground(Color color) {
		context.setBackground(color);
	}

	@Override
	public Color getBackground() {
		return context.getBackground();
	}

	@Override
	public Stroke getStroke() {
		return context.getStroke();
	}

	@Override
	public void clip(Shape s) {
		context.clip(s);
	}

	@Override
	public FontRenderContext getFontRenderContext() {
		return context.getFontRenderContext();
	}

	@Override
	public VectorGraphics2D create() {
		return new VectorGraphics2D(getContext(), operations);
	}

	@Override
	public Color getColor() {
		return context.getColor();
	}

	@Override
	public void setColor(Color c) {
		context.setColor(c);
	}

	@Override
	public void setPaintMode() {
		context.setPaintMode();
	}

	@Override
	public void setXORMode(Color c1) {
		context.setXORMode(c1);
	}

	@Override
	public Font getFont() {
		return context.getFont();
	}

	@Override
	public void setFont(Font font) {
		context.setFont(font);
	}

	@Override
	public Rectangle getClipBounds() {
		return context.getClipBounds();
	}

	@Override
	public void clipRect(int x, int y, int width, int height) {
		context.clipRect(x, y, width, height);
	}

	@Override
	public void setClip(int x, int y, int width, int height) {
		context.setClip(x, y, width, height);
	}

	@Override
	public Shape getClip() {
		return context.getClip(true);
	}

	@Override
	public void setClip(Shape clip) {
		context.setClip(clip);
	}

	@Override
	public void dispose() {
		context.dispose();
	}

	// shape-related methods:

	@Override
	public void draw(Shape s) {
		addOperation(new DrawOperation(getContext(), s));
	}

	@Override
	public void fill(Shape s) {
		addOperation(new FillOperation(getContext(), s));
	}

	@Override
	public void drawLine(int x1, int y1, int x2, int y2) {
		Line2D l = new Line2D.Float(x1, y1, x2, y2);
		draw(l);
	}

	@Override
	public void fillRect(int x, int y, int width, int height) {
		Rectangle r = new Rectangle(x, y, width, height);
		fill(r);
	}

	@Override
	public void drawRoundRect(int x, int y, int width, int height, int arcWidth,
			int arcHeight) {
		RoundRectangle2D r = new RoundRectangle2D.Float(x, y, width, height,
				arcWidth, arcHeight);
		draw(r);
	}

	@Override
	public void fillRoundRect(int x, int y, int width, int height, int arcWidth,
			int arcHeight) {
		RoundRectangle2D r = new RoundRectangle2D.Float(x, y, width, height,
				arcWidth, arcHeight);
		fill(r);
	}

	@Override
	public void drawOval(int x, int y, int width, int height) {
		Ellipse2D e = new Ellipse2D.Float(x, y, width, height);
		draw(e);
	}

	@Override
	public void drawRect(int x, int y, int width, int height) {
		// if we use super.drawRect(..) we'll get 4 lines,
		// which (depending on the opacity of the stroke) may be the wrong
		// behavior
		Rectangle r = new Rectangle(x, y, width, height);
		draw(r);
	}

	@Override
	public void fillOval(int x, int y, int width, int height) {
		Ellipse2D e = new Ellipse2D.Float(x, y, width, height);
		fill(e);
	}

	@Override
	public void drawArc(int x, int y, int width, int height, int startAngle,
			int arcAngle) {
		Arc2D a = new Arc2D.Float(x, y, width, height, startAngle, arcAngle,
				Arc2D.OPEN);
		draw(a);
	}

	@Override
	public void fillArc(int x, int y, int width, int height, int startAngle,
			int arcAngle) {
		Arc2D a = new Arc2D.Float(x, y, width, height, startAngle, arcAngle,
				Arc2D.OPEN);
		fill(a);
	}

	@Override
	public void drawPolyline(int[] xPoints, int[] yPoints, int nPoints) {
		if (nPoints == 0)
			return;
		Path2D p = new Path2D.Float();
		p.moveTo(xPoints[0], yPoints[0]);
		for (int a = 1; a < nPoints; a++) {
			p.lineTo(xPoints[a], yPoints[a]);
		}
		draw(p);
	}

	@Override
	public void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) {
		Polygon p = new Polygon(xPoints, yPoints, nPoints);
		draw(p);
	}

	@Override
	public void fillPolygon(int[] xPoints, int[] yPoints, int nPoints) {
		Polygon p = new Polygon(xPoints, yPoints, nPoints);
		fill(p);
	}

	// image-related methods:

	@Override
	public boolean drawImage(Image img, AffineTransform xform,
			ImageObserver obs) {
		Graphics2D g = create();
		g.transform(xform);
		boolean returnValue = g.drawImage(img, 0, 0, obs);
		g.dispose();
		return returnValue;
	}

	/**
	 * This is shorthand for:

	 *
	 * BufferedImage img1 = op.filter(img, null);
	 * drawImage(img1, new AffineTransform(1f, 0f, 0f, 1f, x, y), null);
	 *
	 */
	@Override
	public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) {
		// the Graphics2D javadoc for this method says its equivalent to:
		BufferedImage img1 = op.filter(img, null);
		drawImage(img1, new AffineTransform(1f, 0f, 0f, 1f, x, y), null);
	}

	@Override
	public void drawRenderedImage(RenderedImage img, AffineTransform xform) {
		addOperation(new RenderedImageOperation(getContext(), img, xform));

	}

	@Override
	public void drawRenderableImage(RenderableImage img,
			AffineTransform xform) {
		addOperation(new RenderableImageOperation(getContext(), img, xform));
	}

	@Override
	public boolean drawImage(Image img, int x, int y, ImageObserver observer) {
		Dimension size = ImageSize.get(img);
		return drawImage(img, x, y, x + size.width, y + size.height, 0, 0,
				size.width, size.height, null, observer);
	}

	@Override
	public boolean drawImage(Image img, int x, int y, int width, int height,
			ImageObserver observer) {
		Dimension size = ImageSize.get(img);
		return drawImage(img, x, y, x + width, y + height, 0, 0, size.width,
				size.height, null, observer);
	}

	@Override
	public boolean drawImage(Image img, int x, int y, Color bgcolor,
			ImageObserver observer) {
		Dimension size = ImageSize.get(img);
		return drawImage(img, x, y, size.width + x, size.height + y, 0, 0,
				size.width, size.height, bgcolor, observer);
	}

	@Override
	public boolean drawImage(Image img, int x, int y, int width, int height,
			Color bgcolor, ImageObserver observer) {
		Dimension size = ImageSize.get(img);
		return drawImage(img, x, y, x + width, y + height, 0, 0, size.width,
				size.height, bgcolor, null);
	}

	@Override
	public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2,
			int sx1, int sy1, int sx2, int sy2, ImageObserver observer) {
		return drawImage(img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, null,
				observer);
	}

	@Override
	public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2,
			int sx1, int sy1, int sx2, int sy2, Color bgcolor,
			ImageObserver observer) {

		// this is what SunGraphics2D does for null images:
		if (img == null)
			return true;

		addOperation(new ImageOperation(getContext(), img, dx1, dy1, dx2, dy2,
				sx1, sy1, sx2, sy2, bgcolor));
		return true;
	}

	// string-related methods:

	@Override
	public void drawString(String str, int x, int y) {
		drawString(str, (float) x, (float) y);
	}

	@Override
	public void drawString(String str, float x, float y) {
		addOperation(new StringOperation(getContext(), str, x, y));

		// this is equivalent to:
		// TextLayout layout = new TextLayout(iterator, getFontRenderContext());
		// layout.draw(this, x, y);

		// using a GlyphVector may work for English, but limited experience
		// suggests it may fail for Arabic or other more complex languages.
		// (TextLayouts do support Arabic well, though.)

		// GlyphVector glyphVector = getFont().createGlyphVector(
		// getFontRenderContext(), str);
		// drawGlyphVector(glyphVector, x, y);
	}

	@Override
	public void drawString(AttributedCharacterIterator iterator, int x, int y) {
		drawString(iterator, (float) x, (float) y);
	}

	@Override
	public void drawString(AttributedCharacterIterator iterator, float x,
			float y) {
		addOperation(new AttributedCharacterIteratorOperation(getContext(),
				iterator, x, y));

		// this is equivalent to:
		// TextLayout layout = new TextLayout(iterator, getFontRenderContext());
		// layout.draw(this, x, y);
	}

	@Override
	public void drawGlyphVector(GlyphVector g, float x, float y) {
		addOperation(new GlyphVectorOperation(getContext(), g, x, y));
	}

	// other:

	@Override
	public boolean hit(Rectangle rect, Shape s, boolean onStroke) {
		if (onStroke) {
			return hit(rect, getStroke().createStrokedShape(s), false);
		}

		Area area = new Area(s);
		return area.intersects(rect);
	}

	@Override
	public GraphicsConfiguration getDeviceConfiguration() {
		return new VectorGraphicsConfiguration();
	}

	@Override
	public void copyArea(int x, int y, int width, int height, int dx, int dy) {
		addOperation(new CopyAreaOperation(getContext(), x, y, width, height,
				dx, dy));
	}

	@Override
	public void clearRect(int x, int y, int width, int height) {
		// this is based on SunGraphics2D's implementation of clearRect
		Graphics2DContext context = getContext();
		context.setComposite(AlphaComposite.Src);
		context.setColor(getBackground());
		Rectangle rect = new Rectangle(x, y, width, height);
		addOperation(new FillOperation(context, rect));
	}

	@Override
	public FontMetrics getFontMetrics(Font f) {
		// This one stumped me; I'm not sure how we're supposed to handle this?
		BufferedImage bi = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
		Graphics2D g = bi.createGraphics();
		context.install(g);
		FontMetrics returnValue = g.getFontMetrics(f);
		g.dispose();
		return returnValue;
	}
}


text:
from collections import OrderedDict

from requests_toolbelt.multipart.encoder import MultipartEncoder

class MultipartStream(MultipartEncoder):
    """
    Subclass of the requests_toolbelt's :class:`MultipartEncoder` that ensures that data
    is encoded before files. This allows a server to process information in the data before
    receiving the file bytes.
    """
    def __init__(self, data, files):
        fields = OrderedDict()
        for k in data:
            fields[k] = data[k]
        for k in files:
            fields[k] = files[k]
        super().__init__(fields)


text:
(function() {
  var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) {
    for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; }
    function ctor() { this.constructor = child; }
    ctor.prototype = parent.prototype;
    child.prototype = new ctor;
    child.__super__ = parent.prototype;
    return child;
  };
  window.AppRouter = (function() {
    __extends(AppRouter, Backbone.Router);
    function AppRouter() {
      this.showDocuments = __bind(this.showDocuments, this);
      this.showCollection = __bind(this.showCollection, this);
      this.showDatabase = __bind(this.showDatabase, this);
      this.clear = __bind(this.clear, this);
      AppRouter.__super__.constructor.apply(this, arguments);
    }
    AppRouter.prototype.routes = {
      "": "clear",
      "databases/:databaseName/collections/:collectionName/documents": "showDocuments",
      "databases/:databaseName/collections/:collectionName/documents/*paging": "showDocuments",
      "databases/:databaseName/collections/:collectionName": "showCollection",
      "databases/:name": "showDatabase"
    };
    AppRouter.prototype.clear = function() {
      var homeView;
      homeView = new HomeView();
      return homeView.render();
    };
    AppRouter.prototype.showDatabase = function(name) {
      var database, databaseDetailView;
      database = databases.getDatabase(name);
      if (database) {
        databaseDetailView = new DatabaseDetailView({
          model: database
        });
        return databaseDetailView.render();
      }
    };
    AppRouter.prototype.showCollection = function(databaseName, collectionName) {
      var collection, collectionDetailView, database;
      database = databases.getDatabase(databaseName);
      if (database) {
        collection = databases.getCollection(databaseName, collectionName);
        if (collection) {
          collectionDetailView = new CollectionDetailView({
            databaseModel: database,
            model: collection
          });
          return collectionDetailView.render();
        }
      }
    };
    AppRouter.prototype.showDocuments = function(databaseName, collectionName, paging) {
      var collection, documentView, pagingParams;
      collection = new Documents({}, {
        databaseName: databaseName,
        collectionName: collectionName
      });
      if (paging) {
        pagingParams = paging.split('/');
        if (pagingParams.length > 0) {
          collection.pageDetails.pageSize = pagingParams[0];
        }
        if (pagingParams.length > 1) {
          collection.pageDetails.page = pagingParams[1];
        }
      }
      documentView = new DocumentListView({
        collection: collection,
        databaseName: databaseName,
        collectionName: collectionName
      });
      return collection.fetch();
    };
    return AppRouter;
  })();
}).call(this);