text:
using System;
using System.Collections.Generic;
using System.Diagnostics;

using OpenTK.Platform;

namespace OpenTK.Graphics
{

    ///
    /// Represents and provides methods to manipulate an OpenGL render context.
    ///
    public sealed class GraphicsContext : IGraphicsContext, IGraphicsContextInternal
    {

        public static event EventHandler ContextCreationError;
        public class GraphicContextCreationErrorArgs : EventArgs
        {
            public GraphicContextCreationErrorArgs(string msg)
            {
                Msg = msg;
            }
            public string Msg { get; set; }
        }

        ///
        /// Used to retrive function pointers by name.
        ///
        /// <param name="function">The function name.</param>
        /// <returns>A function pointer to <paramref name="function"/>, or <c>IntPtr.Zero</c></returns>
        public delegate IntPtr GetAddressDelegate(string function);

        ///
        /// Used to return the handle of the current OpenGL context.
        ///
        /// <returns>The current OpenGL context, or <c>IntPtr.Zero</c> if no context is on the calling thread.</returns>
        public delegate ContextHandle GetCurrentContextDelegate();

        private IGraphicsContext _implementation;  // The actual render context implementation for the underlying platform.
        private bool _disposed;

        // Cache for the context handle. We need this for RemoveContext()
        // in case the user does not call Dispose(). When this happens,
        // RemoveContext() is called by the finalizer, in which case
        // the IGraphicsContext implementation may already be null
        // (hence we cannot call implementation.Context to retrieve
        // the handle.)
        private ContextHandle _handle_cached;

        private readonly static object SyncRoot = new object();
        // Maps OS-specific context handles to GraphicsContext instances.
        private readonly static Dictionary<ContextHandle, IGraphicsContext> s_available_contexts =
            new Dictionary<ContextHandle, IGraphicsContext>();

        /////
        ///// Constructs a new GraphicsContext with the specified GraphicsMode and attaches it to the specified window.
        /////
        ///// <param name="mode">The OpenTK.Graphics.GraphicsMode of the GraphicsContext.</param>
        ///// <param name="window">The OpenTK.Platform.IWindowInfo to attach the GraphicsContext to.</param>
        //public GraphicsContext(GraphicsMode mode, IWindowInfo window)
        //    : this(mode, window, 1, 0, GraphicsContextFlags.Default)
        //{ }

        ///
        /// Constructs a new GraphicsContext with the specified GraphicsMode, version and flags,  and attaches it to the specified window.
        ///
        /// <param name="mode">The OpenTK.Graphics.GraphicsMode of the GraphicsContext.</param>
        /// <param name="window">The OpenTK.Platform.IWindowInfo to attach the GraphicsContext to.</param>
        /// <param name="major">The major version of the new GraphicsContext.</param>
        /// <param name="minor">The minor version of the new GraphicsContext.</param>
        /// <param name="flags">The GraphicsContextFlags for the GraphicsContext.</param>
        /// <remarks>
        /// Different hardware supports different flags, major and minor versions. Invalid parameters will be silently ignored.
        /// </remarks>
        public GraphicsContext(GraphicsMode mode, IWindowInfo window, int major, int minor, GraphicsContextFlags flags)
            : this(mode, window, FindSharedContext(), major, minor, flags)
        {
        }

        ///
        /// Constructs a new GraphicsContext with the specified GraphicsMode, version and flags, and attaches it to the specified window. A dummy context will be created if both
        /// the handle and the window are null.
        ///
        /// <param name="mode">The OpenTK.Graphics.GraphicsMode of the GraphicsContext.</param>
        /// <param name="window">The OpenTK.Platform.IWindowInfo to attach the GraphicsContext to.</param>
        /// <param name="shareContext">The GraphicsContext to share resources with, or null for explicit non-sharing.</param>
        /// <param name="major">The major version of the new GraphicsContext.</param>
        /// <param name="minor">The minor version of the new GraphicsContext.</param>
        /// <param name="flags">The GraphicsContextFlags for the GraphicsContext.</param>
        /// <remarks>
        /// Different hardware supports different flags, major and minor versions. Invalid parameters will be silently ignored.
        /// </remarks>
        public GraphicsContext(GraphicsMode mode, IWindowInfo window, IGraphicsContext shareContext, int major, int minor, GraphicsContextFlags flags)
        {
            bool success = false;
            string errMsg = null;

            lock (SyncRoot)
            {
                bool designMode = false;
                if (mode == null && window == null)
                {
                    designMode = true;
                }
                else if (mode == null)
                {
                    throw new ArgumentNullException("mode", "Must be a valid GraphicsMode.");
                }
                else if (window == null)
                {
                    throw new ArgumentNullException("window", "Must point to a valid window.");
                }

                // Silently ignore invalid major and minor versions.
                if (major <= 0)
                {
                    major = 1;
                }
                if (minor < 0)
                {
                    minor = 0;
                }

                // Angle needs an embedded context
                const GraphicsContextFlags useAngleFlag = GraphicsContextFlags.Angle
                                                          | GraphicsContextFlags.AngleD3D9
                                                          | GraphicsContextFlags.AngleD3D11
                                                          | GraphicsContextFlags.AngleOpenGL;

                flags = useAngleFlag;
                var useAngle = false;
                if ((flags & useAngleFlag) != 0)
                {
                    flags |= GraphicsContextFlags.Embedded;
                    useAngle = true;
                }

                Debug.WriteLine("Creating GraphicsContext.");

                try
                {
                    Debug.WriteLine("");
                    Debug.WriteLine($"GraphicsMode: {mode}");
                    Debug.WriteLine($"IWindowInfo: {window}");
                    Debug.WriteLine($"GraphicsContextFlags: {flags}");
                    Debug.WriteLine($"Requested version: {major}.{minor}");

                    // Todo: Add a DummyFactory implementing IPlatformFactory.
                    if (designMode)
                    {
                        _implementation = new Platform.Dummy.DummyGLContext();
                    }
                    else
                    {
                        IPlatformFactory factory = null;
                        switch ((flags & GraphicsContextFlags.Embedded) == GraphicsContextFlags.Embedded)
                        {
                            case false:
                                factory = Factory.Default;
                                break;
                            case true:
                                factory = useAngle ? Factory.Angle : Factory.Embedded;
                                break;
                        }

                        // Note: this approach does not allow us to mix native and EGL contexts in the same process.
                        // This should not be a problem, as this use-case is not interesting for regular applications.
                        // Note 2: some platforms may not support a direct way of getting the current context
                        // (this happens e.g. with DummyGLContext). In that case, we use a slow fallback which
                        // iterates through all known contexts and checks if any is current (check GetCurrentContext
                        // declaration).
                        if (GetCurrentContext == null)
                        {
                            GetCurrentContext = factory.CreateGetCurrentGraphicsContext();
                        }

                        _implementation = factory.CreateGLContext(mode, window, shareContext, DirectRendering, major, minor, flags);
                        _handle_cached = ((IGraphicsContextInternal)_implementation).Context;
                        factory.RegisterResource(this);
                    }

                    AddContext(this);
                    success = true;
                }
                catch (Exception ex)
                {
                    //some exception err here
                    //we write a log file

                }
                finally
                {

                }
            }

            if (!success)
            {
                ContextCreationError?.Invoke(null, new GraphicContextCreationErrorArgs(errMsg));
            }

        }

        ///
        /// Initializes a new instance of the <see cref="OpenTK.Graphics.GraphicsContext"/> class using
        /// an external context handle that was created by a third-party library.
        ///
        /// <param name="handle">
        /// A valid, unique handle for an external OpenGL context, or <c>ContextHandle.Zero</c> to use the current context.
        /// It is an error to specify a handle that has been created through OpenTK or that has been passed to OpenTK before.
        /// </param>
        /// <param name="getAddress">
        /// A <c>GetAddressDelegate</c> instance that accepts the name of an OpenGL function and returns
        /// a valid function pointer, or <c>IntPtr.Zero</c> if that function is not supported. This delegate should be
        /// implemented using the same toolkit that created the OpenGL context (i.e. if the context was created with
        /// SDL_GL_CreateContext(), then this delegate should use SDL_GL_GetProcAddress() to retrieve function
        /// pointers.)
        /// </param>
        /// <param name="getCurrent">
        /// A <c>GetCurrentContextDelegate</c> instance that returns the handle of the current OpenGL context,
        /// or <c>IntPtr.Zero</c> if no context is current on the calling thread. This delegate should be implemented
        /// using the same toolkit that created the OpenGL context (i.e. if the context was created with
        /// SDL_GL_CreateContext(), then this delegate should use SDL_GL_GetCurrentContext() to retrieve
        /// the current context.)
        /// </param>
        public GraphicsContext(ContextHandle handle, GetAddressDelegate getAddress, GetCurrentContextDelegate getCurrent)
        {
            if (getAddress == null || getCurrent == null)
            {
                throw new ArgumentNullException();
            }

            // Make sure OpenTK has been initialized.
            // Fixes https://github.com/opentk/opentk/issues/52
            //Toolkit.Init();

            lock (SyncRoot)
            {
                // Replace a zero-handle by the current context, if any
                if (handle == ContextHandle.Zero)
                {
                    handle = getCurrent();
                }

                // Make sure this handle corresponds to a valid, unique OpenGL context
                if (handle == ContextHandle.Zero)
                {
                    throw new GraphicsContextMissingException();
                }
                else if (s_available_contexts.ContainsKey(handle))
                {
                    throw new InvalidOperationException("Context handle has already been added");
                }

                // We have a valid handle for an external OpenGL context, wrap it into a
                // DummyGLContext instance.
                _implementation = new Platform.Dummy.DummyGLContext(handle, getAddress);
                GetCurrentContext = getCurrent ?? GetCurrentContext;
                AddContext(this);
            }
            _implementation.LoadAll();
        }

        /////
        ///// Constructs a new GraphicsContext from a pre-existing context created outside of OpenTK. A dummy context will be created if both
        ///// the handle and the window are null.
        /////
        ///// <param name="handle">The handle of the existing context. This must be a valid, unique handle that is not known to OpenTK.</param>
        ///// <param name="window">This parameter is reserved.</param>
        //public GraphicsContext(ContextHandle handle, IWindowInfo window)
        //    : this(handle, window, null, 1, 0, GraphicsContextFlags.Default)
        //{ }

        /////
        ///// Constructs a new GraphicsContext from a pre-existing context created outside of OpenTK.
        /////
        ///// <param name="handle">The handle of the existing context. This must be a valid, unique handle that is not known to OpenTK.</param>
        ///// <param name="window">This parameter is reserved.</param>
        ///// <param name="shareContext">This parameter is reserved.</param>
        ///// <param name="major">This parameter is reserved.</param>
        ///// <param name="minor">This parameter is reserved.</param>
        ///// <param name="flags">This parameter is reserved..</param>
        //public GraphicsContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, int major, int minor, GraphicsContextFlags flags)
        //    : this(handle, PlatformAddressPortal.GetAddressDelegate, OpenTK.Platform.Factory.Default.CreateGetCurrentGraphicsContext())
        //{ }

        ///
        /// Returns a <see cref="System.String"/> representing this instance.
        ///
        /// <returns>A <see cref="System.String"/>  that contains a string representation of this instance.</returns>
        public override string ToString()
        {
            return (this as IGraphicsContextInternal).Context.ToString();
        }

        ///
        /// Returns the hash code for this instance.
        ///
        /// <returns>A System.Int32 with the hash code of this instance.</returns>
        public override int GetHashCode()
        {
            return (this as IGraphicsContextInternal).Context.GetHashCode();
        }

        ///
        /// Compares two instances.
        ///
        /// <param name="obj">The instance to compare to.</param>
        /// <returns>True, if obj is equal to this instance; false otherwise.</returns>
        public override bool Equals(object obj)
        {
            return (obj is GraphicsContext) &&
                (this as IGraphicsContextInternal).Context == (obj as IGraphicsContextInternal).Context;
        }

        private static void AddContext(IGraphicsContextInternal context)
        {
            ContextHandle ctx = context.Context;
            if (!s_available_contexts.ContainsKey(ctx))
            {
                s_available_contexts.Add(ctx, (IGraphicsContext)context);
            }
            else
            {
                Debug.WriteLine($"A GraphicsContext with handle {ctx} already exists.");
                Debug.WriteLine("Did you forget to call Dispose()?");
                s_available_contexts[ctx] = (IGraphicsContext)context;
            }
        }

        private static void RemoveContext(IGraphicsContextInternal context)
        {
            ContextHandle ctx = context.Context;
            if (s_available_contexts.ContainsKey(ctx))
            {
                s_available_contexts.Remove(ctx);
            }
            else
            {
                Debug.WriteLine("");
                Debug.WriteLine($"Tried to remove non-existent GraphicsContext handle {ctx}. Call Dispose() to avoid this error.");
            }
        }

        private static IGraphicsContext FindSharedContext()
        {
            if (GraphicsContext.ShareContexts)
            {
                // A small hack to create a shared context with the first available context.
                foreach (IGraphicsContext target in GraphicsContext.s_available_contexts.Values)
                {
                    // Fix for bug 1874: if a GraphicsContext gets finalized
                    // (but not disposed), it won't be removed from available_contexts
                    // making this return null even if another valid context exists.
                    // The workaround is to simply ignore null targets.
                    if (target != null)
                    {
                        return target;
                    }
                }
            }
            return null;
        }

        ///
        /// Checks if a GraphicsContext exists in the calling thread and throws a GraphicsContextMissingException if it doesn't.
        ///
        /// <exception cref="GraphicsContextMissingException">Generated when no GraphicsContext is current in the calling thread.</exception>
        public static void Assert()
        {
            if (GraphicsContext.CurrentContext == null)
            {
                throw new GraphicsContextMissingException();
            }
        }

        public static GetCurrentContextDelegate GetCurrentContext;

        ///
        /// Gets the handle of the current GraphicsContext in the calling thread.
        ///
        public static ContextHandle CurrentContextHandle
        {
            get { return GetCurrentContext(); }
        }

        ///
        /// Gets the GraphicsContext that is current in the calling thread.
        ///
        /// <remarks>
        /// Note: this property will not function correctly when both desktop and EGL contexts are
        /// available in the same process. This scenario is very unlikely to appear in practice.
        /// </remarks>
        public static IGraphicsContext CurrentContext
        {
            get
            {
                lock (SyncRoot)
                {
                    if (s_available_contexts.Count > 0)
                    {
                        ContextHandle handle = CurrentContextHandle;
                        if (handle.Handle != IntPtr.Zero)
                        {
                            return (IGraphicsContext)s_available_contexts[handle];
                        }
                    }
                    return null;
                }
            }
        }

        /// Gets or sets a System.Boolean, indicating whether GraphicsContext resources are shared
        /// <remarks>
        /// <para>If ShareContexts is true, new GLContexts will share resources. If this value is
        /// false, new GLContexts will not share resources.</para>
        /// <para>Changing this value will not affect already created GLContexts.</para>
        /// </remarks>
        public static bool ShareContexts { get; set; } = true;

        /// Gets or sets a System.Boolean, indicating whether GraphicsContexts will perform direct rendering.
        /// <remarks>
        /// <para>
        /// If DirectRendering is true, new contexts will be constructed with direct rendering capabilities, if possible.
        /// If DirectRendering is false, new contexts will be constructed with indirect rendering capabilities.
        /// </para>
        /// <para>This property does not affect existing GraphicsContexts, unless they are recreated.</para>
        /// <para>
        /// This property is ignored on Operating Systems without support for indirect rendering, like Windows and OS X.
        /// </para>
        /// </remarks>
        public static bool DirectRendering { get; set; } = true;

        ///
        /// Gets or sets a System.Boolean, indicating whether automatic error checking should be performed.
        /// Influences the debug version of OpenTK.dll, only.
        ///
        /// <remarks>Automatic error checking will clear the OpenGL error state. Set CheckErrors to false if you use
        /// the OpenGL error state in your code flow (e.g. for checking supported texture formats).</remarks>
        public bool ErrorChecking { get; set; } = true;

        ///
        /// Swaps buffers on a context. This presents the rendered scene to the user.
        ///
        public void SwapBuffers()
        {
            _implementation.SwapBuffers();
        }

        ///
        /// Makes the GraphicsContext the current rendering target.
        ///
        /// <param name="window">A valid <see cref="OpenTK.Platform.IWindowInfo" /> structure.</param>
        /// <remarks>
        /// You can use this method to bind the GraphicsContext to a different window than the one it was created from.
        /// </remarks>
        public void MakeCurrent(IWindowInfo window)
        {
            _implementation.MakeCurrent(window);
        }

        ///
        /// Gets a <see cref="System.Boolean"/> indicating whether this instance is current in the calling thread.
        ///
        public bool IsCurrent
        {
            get { return _implementation.IsCurrent; }
        }

        ///
        /// Gets a <see cref="System.Boolean"/> indicating whether this instance has been disposed.
        /// It is an error to access any instance methods if this property returns true.
        ///
        public bool IsDisposed
        {
            get { return _disposed && _implementation.IsDisposed; }
            private set { _disposed = value; }
        }

        ///
        /// Gets or sets a positive integer in the range [1, n), indicating the number of
        /// <see cref="DisplayDevice"/> refreshes between consecutive
        /// <see cref="SwapBuffers()"/> calls. The maximum value for n is
        /// implementation-dependent. The default value is 1.
        /// Invalid values will be clamped to the valid range.
        ///
        public int SwapInterval
        {
            get { return _implementation.SwapInterval; }
            set { _implementation.SwapInterval = value; }
        }

        ///
        /// Updates the graphics context.  This must be called when the render target
        /// is resized for proper behavior on Mac OS X.
        ///
        /// <param name="window"></param>
        public void Update(IWindowInfo window)
        {
            _implementation.Update(window);
        }

        ///
        /// Loads all OpenGL entry points.
        ///
        /// <exception cref="OpenTK.Graphics.GraphicsContextException">
        /// Occurs when this instance is not current on the calling thread.
        /// </exception>
        public void LoadAll()
        {
            if (GraphicsContext.CurrentContext != this)
            {
                throw new GraphicsContextException();
            }

            _implementation.LoadAll();
        }

        ///
        /// Gets the platform-specific implementation of this IGraphicsContext.
        ///
        IGraphicsContext IGraphicsContextInternal.Implementation
        {
            get { return _implementation; }
        }

        ///
        /// Gets a handle to the OpenGL rendering context.
        ///
        ContextHandle IGraphicsContextInternal.Context
        {
            get
            {
                if (_implementation != null)
                {
                    _handle_cached = ((IGraphicsContextInternal)_implementation).Context;
                }
                return _handle_cached;
            }
        }

        ///
        /// Gets the GraphicsMode of the context.
        ///
        public GraphicsMode GraphicsMode
        {
            get { return (_implementation as IGraphicsContext).GraphicsMode; }
        }

        ///
        /// Retrieves the implementation-defined address of an OpenGL function.
        ///
        /// <param name="function">The name of the OpenGL function (e.g. "glGetString")</param>
        /// <returns>
        /// A pointer to the specified function or an invalid pointer if the function is not
        /// available in the current OpenGL context. The return value and calling convention
        /// depends on the underlying platform.
        /// </returns>
        IntPtr IGraphicsContextInternal.GetAddress(string function)
        {
            IntPtr name = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(function);
            IntPtr address = (_implementation as IGraphicsContextInternal).GetAddress(name);
            System.Runtime.InteropServices.Marshal.FreeHGlobal(name);
            return address;
        }

        ///
        /// Retrieves the implementation-defined address of an OpenGL function.
        ///
        /// <param name="function">
        /// A pointer to a null-terminated buffer
        /// containing the name of the OpenGL function.
        /// </param>
        /// <returns>
        /// A pointer to the specified function or an invalid pointer if the function is not
        /// available in the current OpenGL context. The return value and calling convention
        /// depends on the underlying platform.
        /// </returns>
        IntPtr IGraphicsContextInternal.GetAddress(IntPtr function)
        {
            return (_implementation as IGraphicsContextInternal).GetAddress(function);
        }

        ///
        /// Disposes of the GraphicsContext.
        ///
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool manual)
        {
            if (!IsDisposed)
            {
                lock (SyncRoot)
                {
                    RemoveContext(this);
                }

                // Note: we cannot dispose the implementation
                // from a different thread. See wglDeleteContext.
                // This is also known to crash GLX implementations.
                if (manual)
                {
                    Debug.WriteLine($"Disposing context {(this as IGraphicsContextInternal).Context.ToString()}.");
                    if (_implementation != null)
                    {
                        _implementation.Dispose();
                    }
                }
                else
                {
                    Debug.WriteLine("GraphicsContext leaked, did you forget to call Dispose()?");
                }
                IsDisposed = true;
            }
        }

        ///
        /// Marks this context as deleted, but does not actually release unmanaged resources
        /// due to the threading requirements of OpenGL. Use <see cref="GraphicsContext.Dispose()"/>
        /// instead.
        ///
        ~GraphicsContext()
        {
            Dispose(false);
        }

        //////////////////////////////////////////////////////////////////////////////////////////////////
        ///
        /// TODO: for used with glfw context
        ///
        /// <param name="handle"></param>
        /// <returns></returns>
        public static GraphicsContext CreateExternalContext(Platform.External.ExternalGraphicsContext externalGfxContext)
        {
            return new GraphicsContext(externalGfxContext);
        }

        GraphicsContext(OpenTK.Platform.External.ExternalGraphicsContext externalGraphicsContext)
        {
            _implementation = externalGraphicsContext;

            lock (SyncRoot)
            {

                // Angle needs an embedded context
                //const GraphicsContextFlags useAngleFlag = GraphicsContextFlags.Angle
                //                                          | GraphicsContextFlags.AngleD3D9
                //                                          | GraphicsContextFlags.AngleD3D11
                //                                          | GraphicsContextFlags.AngleOpenGL;

                bool useAngle = true;
                try
                {

                    IPlatformFactory factory = Factory.Embedded;

                    // Note: this approach does not allow us to mix native and EGL contexts in the same process.
                    // This should not be a problem, as this use-case is not interesting for regular applications.
                    // Note 2: some platforms may not support a direct way of getting the current context
                    // (this happens e.g. with DummyGLContext). In that case, we use a slow fallback which
                    // iterates through all known contexts and checks if any is current (check GetCurrentContext
                    // declaration).

                    if (GetCurrentContext == null)
                    {
                        GetCurrentContext = externalGraphicsContext.CreateCurrentContextDel(); // factory.CreateGetCurrentGraphicsContext();
                    }

                    s_available_contexts.Add((_implementation as IGraphicsContextInternal).Context, this);
                    (this as IGraphicsContextInternal).LoadAll();

                    _handle_cached = ((IGraphicsContextInternal)_implementation).Context;
                    factory.RegisterResource(this);
                }
                catch (Exception ex)
                {

                }
            }
        }
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////
    }
}


text:
<?hh // strict

namespace Titon\Route\Annotation;

use Titon\Annotation\Annotation;
use Titon\Route\Mixin\FilterMixin;
use Titon\Route\Mixin\MethodMixin;
use Titon\Route\Mixin\PatternMixin;
use Titon\Route\Route as BaseRoute;
use Titon\Route\Router;
use Titon\Utility\Col;

/**
 * The Route annotation provides a low-level way of mapping paths, methods, filters, and patterns
 * to a method or class that can be mapped through `Titon\Route\Router::wire()`.
 *
 * <<Route($key, $path[, $methods[, $filters[, $patterns]]])>>
 *
 * @package Titon\Route\Annotation
 */
class Route extends Annotation {
    use FilterMixin, MethodMixin, PatternMixin;

    /**
     * The unique key.
     *
     * @var string
     */
    protected string $key;

    /**
     * The path to match.
     *
     * @var string
     */
    protected string $path;

    /**
     * Store all route settings.
     *
     * @param string $key
     * @param string $path
     * @param mixed $methods
     * @param mixed $filters
     * @param mixed $patterns
     */
    public function __construct(string $key, string $path, mixed $methods = [], mixed $filters = [], array<string, string> $patterns = []) {
        $this->key = $key;
        $this->path = $path;
        $this->setMethods(Col::toVector($methods));
        $this->setFilters(Col::toVector($filters));
        $this->setPatterns(Col::toMap($patterns));
    }

    /**
     * Return the key.
     *
     * @return string
     */
    public function getKey(): string {
        return $this->key;
    }

    /**
     * Return the path.
     *
     * @return string
     */
    public function getPath(): string {
        return $this->path;
    }

    /**
     * Convert the annotation to a `Route` object.
     *
     * @param string $class
     * @param string $action
     * @return \Titon\Route\Route
     */
    public function toRoute(string $class, string $action = 'index'): BaseRoute {
        $route = new BaseRoute($this->getPath(), Router::buildAction(shape('class' => $class, 'action' => $action)));
        $route->setMethods($this->getMethods());
        $route->setFilters($this->getFilters());
        $route->setPatterns($this->getPatterns());

        return $route;
    }

}

redpajama_set_name: RedPajamaGithub


text:
Hook
====

Hook for Web workflow - **under construction**


text:
typedef void (^netCallBackBlock)(id, NSInteger);

@interface  RequestUserData:NSObject

@property  (nonatomic, strong)  netCallBackBlock callBack;
@property  (nonatomic)  BOOL bPromptNoNetWork;
@property  (nonatomic)  BOOL bCanOffline;

@end

@interface JMASIHTTPRequest : NSObject{
    ASINetworkQueue *networkQueue;
}

@end


text:
<?php
/**
 * Shipping Calculator
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/cart/shipping-calculator.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see     https://docs.woocommerce.com/document/template-structure/
 * @package WooCommerce/Templates
 * @version 3.4.0
 */

defined( 'ABSPATH' ) || exit;

if ( 'no' === get_option( 'woocommerce_enable_shipping_calc' ) || ! WC()->cart->needs_shipping() ) {
	return;
}

wp_enqueue_script( 'wc-country-select' );

do_action( 'woocommerce_before_shipping_calculator' ); ?>

<form class="woocommerce-shipping-calculator" action="<?php echo esc_url( wc_get_cart_url() ); ?>" method="post">

<?php esc_html_e( 'Calculate shipping', 'woocommerce' ); ?>

			<select name="calc_shipping_country" id="calc_shipping_country" class="country_to_state country_select" rel="calc_shipping_state">
				<option value=""><?php esc_html_e( 'Select a country…', 'woocommerce' ); ?></option>
				<?php
				foreach ( WC()->countries->get_shipping_countries() as $key => $value ) {
					echo '<option value="' . esc_attr( $key ) . '"' . selected( WC()->customer->get_shipping_country(), esc_attr( $key ), false ) . '>' . esc_html( $value ) . '</option>';
				}
				?>
			</select>

		<?php if ( apply_filters( 'woocommerce_shipping_calculator_enable_state', true ) ) : ?>

				<?php
				$current_cc = WC()->customer->get_shipping_country();
				$current_r  = WC()->customer->get_shipping_state();
				$states     = WC()->countries->get_states( $current_cc );

				if ( is_array( $states ) && empty( $states ) ) {
					?>
					<input type="hidden" name="calc_shipping_state" id="calc_shipping_state" placeholder="<?php esc_attr_e( 'State / County', 'woocommerce' ); ?>" />
					<?php
				} elseif ( is_array( $states ) ) {
					?>

						<select name="calc_shipping_state" class="state_select" id="calc_shipping_state" placeholder="<?php esc_attr_e( 'State / County', 'woocommerce' ); ?>">
							<option value=""><?php esc_html_e( 'Select a state…', 'woocommerce' ); ?></option>
							<?php
							foreach ( $states as $ckey => $cvalue ) {
								echo '<option value="' . esc_attr( $ckey ) . '" ' . selected( $current_r, $ckey, false ) . '>' . esc_html( $cvalue ) . '</option>';
							}
							?>
						</select>

					<?php
				} else {
					?>
					<input type="text" class="input-text" value="<?php echo esc_attr( $current_r ); ?>" placeholder="<?php esc_attr_e( 'State / County', 'woocommerce' ); ?>" name="calc_shipping_state" id="calc_shipping_state" />
					<?php
				}
				?>

		<?php endif; ?>

		<?php if ( apply_filters( 'woocommerce_shipping_calculator_enable_city', true ) ) : ?>

				<input type="text" class="input-text" value="<?php echo esc_attr( WC()->customer->get_shipping_city() ); ?>" placeholder="<?php esc_attr_e( 'City', 'woocommerce' ); ?>" name="calc_shipping_city" id="calc_shipping_city" />

		<?php endif; ?>

		<?php if ( apply_filters( 'woocommerce_shipping_calculator_enable_postcode', true ) ) : ?>

				<input type="text" class="input-text" value="<?php echo esc_attr( WC()->customer->get_shipping_postcode() ); ?>" placeholder="<?php esc_attr_e( 'Postcode / ZIP', 'woocommerce' ); ?>" name="calc_shipping_postcode" id="calc_shipping_postcode" />

		<?php endif; ?>

<button type="submit" name="calc_shipping" value="1" class="button"><?php esc_html_e( 'Update totals', 'woocommerce' ); ?></button>

		<?php wp_nonce_field( 'woocommerce-shipping-calculator', 'woocommerce-shipping-calculator-nonce' ); ?>

</form>

<?php do_action( 'woocommerce_after_shipping_calculator' ); ?>


text:
module HttpdCookbook
  module Helpers
    module Rhel
      def apache_name
        "httpd-#{instance}"
      end

      def libarch
        return 'lib64' if node['kernel']['machine'] == 'x86_64'
        return 'lib' if node['kernel']['machine'] == 'i686'
      end

      def module_path
        if platform_family?('suse')
          "/usr/#{libarch}/apache2/#{filename}"
        else
          "/usr/#{libarch}/httpd/modules/#{filename}"
        end
      end

      # suse compiles in modules and fails to start if you try to load them
      # like they're shared modules
      def built_in_module?(name)
        true if platform_family?('suse') &&
                %w(systemd unixd http so access_compat core mpm_event mpm_prefork mpm_worker).include?(name)
      end

      def http_binary_name
        platform_family?('suse') ? 'httpd2' : 'httpd'
      end

      def elversion
        return 6 if node['platform_version'].to_i == 2013
        return 6 if node['platform_version'].to_i == 2014
        return 6 if node['platform_version'].to_i == 2015
        return 6 if node['platform_version'].to_i == 2016
        return 7 if node['platform_family'] == 'fedora'
        node['platform_version'].to_i
      end

      def pid_file
        return "/var/run/#{apache_name}.pid" if elversion == 5
        "/var/run/#{apache_name}/httpd.pid"
      end

      def includes
        return unless version.to_f < 2.4
        [
          'conf.d/*.load',
          'conf.d/*.conf',
        ]
      end

      def include_optionals
        return unless version.to_f >= 2.4
        [
          'conf.d/*.load',
          'conf.modules.d/*.load',
          'conf.d/*.conf',
          'conf.modules.d/*.conf',
        ]
      end
    end
  end
end


text:
package org.jfree.chart.title;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
import static org.junit.Assert.assertNull;

import java.awt.Color;
import java.awt.GradientPaint;

import org.jfree.chart.TestUtilities;

import org.jfree.chart.block.BlockBorder;
import org.jfree.chart.block.BlockContainer;
import org.jfree.ui.RectangleInsets;
import org.junit.Test;

/**
 * Tests for the {@link CompositeTitle} class.
 */
public class CompositeTitleTest {

    /**
     * Some checks for the constructor.
     */
    @Test
    public void testConstructor() {
        CompositeTitle t = new CompositeTitle();
        assertNull(t.getBackgroundPaint());
    }

    /**
     * Check that the equals() method distinguishes all fields.
     */
    @Test
    public void testEquals() {
        CompositeTitle t1 = new CompositeTitle(new BlockContainer());
        CompositeTitle t2 = new CompositeTitle(new BlockContainer());
        assertEquals(t1, t2);
        assertEquals(t2, t1);

        // margin
        t1.setMargin(new RectangleInsets(1.0, 2.0, 3.0, 4.0));
        assertFalse(t1.equals(t2));
        t2.setMargin(new RectangleInsets(1.0, 2.0, 3.0, 4.0));
        assertTrue(t1.equals(t2));

        // border
        t1.setBorder(new BlockBorder(Color.red));
        assertFalse(t1.equals(t2));
        t2.setBorder(new BlockBorder(Color.red));
        assertTrue(t1.equals(t2));

        // padding
        t1.setPadding(new RectangleInsets(1.0, 2.0, 3.0, 4.0));
        assertFalse(t1.equals(t2));
        t2.setPadding(new RectangleInsets(1.0, 2.0, 3.0, 4.0));
        assertTrue(t1.equals(t2));

        // contained titles
        t1.getContainer().add(new TextTitle("T1"));
        assertFalse(t1.equals(t2));
        t2.getContainer().add(new TextTitle("T1"));
        assertTrue(t1.equals(t2));

        t1.setBackgroundPaint(new GradientPaint(1.0f, 2.0f, Color.red,
                3.0f, 4.0f, Color.yellow));
        assertFalse(t1.equals(t2));
        t2.setBackgroundPaint(new GradientPaint(1.0f, 2.0f, Color.red,
                3.0f, 4.0f, Color.yellow));
        assertTrue(t1.equals(t2));

    }

    /**
     * Two objects that are equal are required to return the same hashCode.
     */
    @Test
    public void testHashcode() {
        CompositeTitle t1 = new CompositeTitle(new BlockContainer());
        t1.getContainer().add(new TextTitle("T1"));
        CompositeTitle t2 = new CompositeTitle(new BlockContainer());
        t2.getContainer().add(new TextTitle("T1"));
        assertTrue(t1.equals(t2));
        int h1 = t1.hashCode();
        int h2 = t2.hashCode();
        assertEquals(h1, h2);
    }

    /**
     * Confirm that cloning works.
     */
    @Test
    public void testCloning() {
        CompositeTitle t1 = new CompositeTitle(new BlockContainer());
        t1.getContainer().add(new TextTitle("T1"));
        t1.setBackgroundPaint(new GradientPaint(1.0f, 2.0f, Color.red,
                3.0f, 4.0f, Color.yellow));
        CompositeTitle t2 = null;
        try {
            t2 = (CompositeTitle) t1.clone();
        }
        catch (CloneNotSupportedException e) {
            fail(e.toString());
        }
        assertTrue(t1 != t2);
        assertTrue(t1.getClass() == t2.getClass());
        assertTrue(t1.equals(t2));
    }

    /**
     * Serialize an instance, restore it, and check for equality.
     */
    @Test
    public void testSerialization() {
        CompositeTitle t1 = new CompositeTitle(new BlockContainer());
        t1.getContainer().add(new TextTitle("T1"));
        t1.setBackgroundPaint(new GradientPaint(1.0f, 2.0f, Color.red,
                3.0f, 4.0f, Color.blue));
        CompositeTitle t2 = (CompositeTitle) TestUtilities.serialised(t1);
        assertEquals(t1, t2);
    }

}


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

class Driver extends CI_Controller {
	public function __construct() {
		parent::__construct();
		$this->load->model('driver_model');
		$this->load->helper('url');
	}
	public function index() {
		// $driver = $this->driver_model->getdriver();
		// //var_dump($user);
		// echo 'User: '.$driver[0]->NAME;
		echo "driver controller";
	}

	public function driverList()
	{
        if(isset($_SESSION['login'])){
            //echo "<pre>";
            //$test=$this->session->userdata('login');
            //var_dump($test);
            $this->load->model('district_model');
            $values = $this->district_model->selectDistrict();
            //var_dump($district);
            if(isset($_POST['district'])) {
                    $driver = $this->driver_model->selectDriver($_POST['district']);
                    $data = array(
                        'title' => 'my page',
                        'driver' => $driver,
                        'district'=>$values,
                    );
                } else {
                    $driver = $this->driver_model->selectDriver('#####');
                    $data = array(
                        'title' => 'my page',
                        'driver' => $driver,
                        'district'=>$values,
                    );
                }
           // }
            $this->load->view('user/report', $data);
        }
        else{
            $data=array(
                'title'=>'Login',
                'check'=> -1
            );
            header("location:".base_url()."index.php/login");
        }

	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.neko.androidexamples.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginStart="5dp"
        android:layout_marginTop="5dp"
        android:orientation="vertical">

        <Button
            android:id="@+id/btnListView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/listview"
            android:onClick="onOptionButtonSelected"/>

        <Button
            android:id="@+id/btnViewPager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/viewpager"
            android:onClick="onOptionButtonSelected"/>

        <Button
            android:id="@+id/btnViewPagerTabbed"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/viewpagertabbed"
            android:onClick="onOptionButtonSelected"/>

        <Button
            android:id="@+id/btnRecyclerView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/recycler_view"
            android:onClick="onOptionButtonSelected"/>

        <Button
            android:id="@+id/btnIntents"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/intents_and_intentfilters"
            android:onClick="onOptionButtonSelected"/>

        <Button
            android:id="@+id/btnFragments"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/fragments"
            android:onClick="onOptionButtonSelected"/>

    </LinearLayout>

</ScrollView>


text:
package uconfig.test

import uconfig.PathSeq
import PathSeq._
import utest._

object PathSeqTest extends TestSuite {
  val tests = Tests {
    val complexPath = "\"a complex {} [.+*#$]:path=\".with-multiple.\" quoted \".and-unquoted.\"seg!ments\""
    val complexPathSeq = PathSeq("\"a complex {} [.+*#$]:path=\"","with-multiple","\" quoted \"","and-unquoted","\"seg!ments\"")

    'toPath-{
      assert( complexPathSeq.toPath == complexPath )
    }
    'fromString-{
      assert( PathSeq.fromString(complexPath) == complexPathSeq )
    }
  }
}


text:
package me.yoctopus.cac.tx;

/**
 * Created by yoctopus on 4/22/17.
 */

interface Future {
    void cancel();
    boolean isCancelled();
    boolean isDone();

}


text:
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
// DebugInfoStore

#include "common.h"
#include "debuginfostore.h"
#include "nibblestream.h"

#ifdef _DEBUG
// For debug builds only.
static bool Dbg_ShouldUseCookies()
{
    SUPPORTS_DAC;

    // Normally we want this as false b/c it would bloat the image.
    // But give us a hook to enable it in case we need it.
    return false;
}
#endif

//-----------------------------------------------------------------------------
// We have "Transfer" objects that sit on top of the streams.
// The objects look identical, but one serializes and the other deserializes.
// This lets the compression + restoration routines share all their compression
// logic and just swap out Transfer objects.
//
// It's not ideal that we have a lot of redundancy maintaining both Transfer
// objects, but at least the compiler can enforce that the Reader & Writer are
// in sync. It can't enforce that a 2 separate routines for Compression &
// restoration are in sync.
//
// We could have the TransferReader + Writer be polymorphic off a base class,
// but the virtual function calls will be extra overhead. May as well use
// templates and let the compiler resolve it all statically at compile time.
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Serialize to a NibbleWriter stream.
//-----------------------------------------------------------------------------
class TransferWriter
{
public:
    TransferWriter(NibbleWriter & w) : m_w(w)
    {
    }

    // Write an raw U32 in nibble encoded form.
    void DoEncodedU32(DWORD dw) { m_w.WriteEncodedU32(dw); }

    // Use to encode a monotonically increasing delta.
    void DoEncodedDeltaU32(DWORD & dw, DWORD dwLast)
    {
        CONTRACTL
        {
            THROWS;
            GC_NOTRIGGER;
            MODE_ANY;
        }
        CONTRACTL_END;
        _ASSERTE(dw >= dwLast);
        DWORD dwDelta = dw - dwLast;
        m_w.WriteEncodedU32(dwDelta);
    }

    // Some U32 may have a few sentinal negative values .
    // We adjust it to be a real U32 and then encode that.
    // dwAdjust should be the lower bound on the enum.
    void DoEncodedAdjustedU32(DWORD dw, DWORD dwAdjust)
    {
        //_ASSERTE(dwAdjust < 0); // some negative lower bound.
        m_w.WriteEncodedU32(dw - dwAdjust);
    }

    // Typesafe versions of EncodeU32.
    void DoEncodedSourceType(ICorDebugInfo::SourceTypes & dw) { m_w.WriteEncodedU32(dw); }
    void DoEncodedVarLocType(ICorDebugInfo::VarLocType & dw) { m_w.WriteEncodedU32(dw); }
    void DoEncodedUnsigned(unsigned & dw) { m_w.WriteEncodedU32(dw); }

    // Stack offsets are aligned on a DWORD boundary, so that lets us shave off 2 bits.
    void DoEncodedStackOffset(signed & dwOffset)
    {
        CONTRACTL
        {
            THROWS;
            GC_NOTRIGGER;
            MODE_ANY;
        }
        CONTRACTL_END;
#ifdef _TARGET_X86_
        _ASSERTE(dwOffset % sizeof(DWORD) == 0); // should be dword aligned. That'll save us 2 bits.
        m_w.WriteEncodedI32(dwOffset / sizeof(DWORD));
#else
        // Non x86 platforms don't need it to be dword aligned.
        m_w.WriteEncodedI32(dwOffset);
#endif
    }

    void DoEncodedRegIdx(ICorDebugInfo::RegNum & reg) { m_w.WriteEncodedU32(reg); }

    // For debugging purposes, inject cookies into the Compression.
    void DoCookie(BYTE b) {
#ifdef _DEBUG
        if (Dbg_ShouldUseCookies())
        {
            m_w.WriteNibble(b);
        }
#endif
    }

protected:
    NibbleWriter & m_w;

};

//-----------------------------------------------------------------------------
// Deserializer that sits on top of a NibbleReader
// This class interface matches TransferWriter exactly. See that for details.
//-----------------------------------------------------------------------------
class TransferReader
{
public:
    TransferReader(NibbleReader & r) : m_r(r)
    {
        SUPPORTS_DAC;
    }

    void DoEncodedU32(DWORD & dw)
    {
        SUPPORTS_DAC;
        dw = m_r.ReadEncodedU32();
    }

    // Use to decode a monotonically increasing delta.
    // dwLast was the last value; we update it to the current value on output.
    void DoEncodedDeltaU32(DWORD & dw, DWORD dwLast)
    {
        SUPPORTS_DAC;
        DWORD dwDelta = m_r.ReadEncodedU32();
        dw = dwLast + dwDelta;
    }

    void DoEncodedAdjustedU32(DWORD & dw, DWORD dwAdjust)
    {
        SUPPORTS_DAC;
        //_ASSERTE(dwAdjust < 0);
        dw = m_r.ReadEncodedU32() + dwAdjust;
    }

    void DoEncodedSourceType(ICorDebugInfo::SourceTypes & dw)
    {
        SUPPORTS_DAC;
        dw = (ICorDebugInfo::SourceTypes) m_r.ReadEncodedU32();
    }

    void DoEncodedVarLocType(ICorDebugInfo::VarLocType & dw)
    {
        SUPPORTS_DAC;
        dw = (ICorDebugInfo::VarLocType) m_r.ReadEncodedU32();
    }

    void DoEncodedUnsigned(unsigned & dw)
    {
        SUPPORTS_DAC;
        dw = (unsigned) m_r.ReadEncodedU32();
    }

    // Stack offsets are aligned on a DWORD boundary, so that lets us shave off 2 bits.
    void DoEncodedStackOffset(signed & dwOffset)
    {
        SUPPORTS_DAC;
#ifdef _TARGET_X86_
        dwOffset = m_r.ReadEncodedI32() * sizeof(DWORD);
#else
        // Non x86 platforms don't need it to be dword aligned.
        dwOffset = m_r.ReadEncodedI32();
#endif
    }

    void DoEncodedRegIdx(ICorDebugInfo::RegNum & reg)
    {
        SUPPORTS_DAC;
        reg = (ICorDebugInfo::RegNum) m_r.ReadEncodedU32();
    }

    // For debugging purposes, inject cookies into the Compression.
    void DoCookie(BYTE b)
    {
        SUPPORTS_DAC;

#ifdef _DEBUG
        if (Dbg_ShouldUseCookies())
        {
            BYTE b2 = m_r.ReadNibble();
            _ASSERTE(b == b2);
        }
#endif
    }

protected:
    NibbleReader & m_r;
};

#if defined(_DEBUG) && !defined(DACCESS_COMPILE)
// Perf tracking
static int g_CDI_TotalMethods           = 0;
static int g_CDI_bMethodTotalUncompress = 0;
static int g_CDI_bMethodTotalCompress   = 0;

static int g_CDI_bVarsTotalUncompress   = 0;
static int g_CDI_bVarsTotalCompress     = 0;
#endif

//-----------------------------------------------------------------------------
// Serialize Bounds info.
//-----------------------------------------------------------------------------
template <class T>
void DoBounds(
    T trans, // transfer object.
    ULONG32                       cMap,
    ICorDebugInfo::OffsetMapping *pMap
)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
        SUPPORTS_DAC;
    }
    CONTRACTL_END;

    // Bounds info contains (Native Offset, IL Offset, flags)
    // - Sorted by native offset (so use a delta encoding for that).
    // - IL offsets aren't sorted, but they should be close to each other (so a signed delta encoding)
    //   They may also include a sentinel value from MappingTypes.
    // - flags is 3 indepedent bits.

    // Loop through and transfer each Entry in the Mapping.
    DWORD dwLastNativeOffset = 0;
    for(DWORD i = 0; i < cMap; i++)
    {
        ICorDebugInfo::OffsetMapping * pBound = &pMap[i];

        trans.DoEncodedDeltaU32(pBound->nativeOffset, dwLastNativeOffset);
        dwLastNativeOffset = pBound->nativeOffset;

        trans.DoEncodedAdjustedU32(pBound->ilOffset, (DWORD) ICorDebugInfo::MAX_MAPPING_VALUE);

        trans.DoEncodedSourceType(pBound->source);

        trans.DoCookie(0xA);
    }
}

// Helper to write a compressed Native Var Info
template<class T>
void DoNativeVarInfo(
    T trans,
    ICorDebugInfo::NativeVarInfo * pVar
)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
        SUPPORTS_DAC;
    }
    CONTRACTL_END;

    // Each Varinfo has a:
    // - native start +End offset. We can use a delta for the end offset.
    // - Il variable number. These are usually small.
    // - VarLoc information. This is a tagged variant.
    // The entries aren't sorted in any particular order.
    trans.DoCookie(0xB);
    trans.DoEncodedU32(pVar->startOffset);

    trans.DoEncodedDeltaU32(pVar->endOffset, pVar->startOffset);

    // record var number.
    trans.DoEncodedAdjustedU32(pVar->varNumber, (DWORD) ICorDebugInfo::MAX_ILNUM);

    // Now write the VarLoc... This is a variant like structure and so we'll get different
    // compressioned depending on what we've got.
    trans.DoEncodedVarLocType(pVar->loc.vlType);

    switch(pVar->loc.vlType)
    {
    case ICorDebugInfo::VLT_REG:
    case ICorDebugInfo::VLT_REG_FP:     // fall through
    case ICorDebugInfo::VLT_REG_BYREF:  // fall through
        trans.DoEncodedRegIdx(pVar->loc.vlReg.vlrReg);
        break;

    case ICorDebugInfo::VLT_STK:
    case ICorDebugInfo::VLT_STK_BYREF:  // fall through
        trans.DoEncodedRegIdx(pVar->loc.vlStk.vlsBaseReg);
        trans.DoEncodedStackOffset(pVar->loc.vlStk.vlsOffset);
        break;

#ifdef MDIL
    case ICorDebugInfo::VLT_STK | ICorDebugInfo::VLT_MDIL_SYMBOLIC:
    case ICorDebugInfo::VLT_STK_BYREF | ICorDebugInfo::VLT_MDIL_SYMBOLIC:  // fall through
        _ASSERTE(pVar->loc.vlStk.vlsOffset >= 0);
        trans.DoEncodedRegIdx(pVar->loc.vlStk.vlsBaseReg);
        trans.DoEncodedU32((DWORD&)pVar->loc.vlStk.vlsOffset);
        break;
#endif // MDIL

    case ICorDebugInfo::VLT_REG_REG:
        trans.DoEncodedRegIdx(pVar->loc.vlRegReg.vlrrReg1);
        trans.DoEncodedRegIdx(pVar->loc.vlRegReg.vlrrReg2);
        break;

    case ICorDebugInfo::VLT_REG_STK:
        trans.DoEncodedRegIdx(pVar->loc.vlRegStk.vlrsReg);
        trans.DoEncodedRegIdx(pVar->loc.vlRegStk.vlrsStk.vlrssBaseReg);
        trans.DoEncodedStackOffset(pVar->loc.vlRegStk.vlrsStk.vlrssOffset);
        break;

#ifdef MDIL
    case ICorDebugInfo::VLT_REG_STK | ICorDebugInfo::VLT_MDIL_SYMBOLIC:
        _ASSERTE(pVar->loc.vlRegStk.vlrsStk.vlrssOffset >= 0);
        trans.DoEncodedRegIdx(pVar->loc.vlRegStk.vlrsReg);
        trans.DoEncodedRegIdx(pVar->loc.vlRegStk.vlrsStk.vlrssBaseReg);
        trans.DoEncodedU32((DWORD&)pVar->loc.vlRegStk.vlrsStk.vlrssOffset);
        break;
#endif // MDIL

    case ICorDebugInfo::VLT_STK_REG:
        trans.DoEncodedStackOffset(pVar->loc.vlStkReg.vlsrStk.vlsrsOffset);
        trans.DoEncodedRegIdx(pVar->loc.vlStkReg.vlsrStk.vlsrsBaseReg);
        trans.DoEncodedRegIdx(pVar->loc.vlStkReg.vlsrReg);
        break;

#ifdef MDIL
    case ICorDebugInfo::VLT_STK_REG | ICorDebugInfo::VLT_MDIL_SYMBOLIC:
        _ASSERTE(pVar->loc.vlStkReg.vlsrStk.vlsrsOffset >= 0);
        trans.DoEncodedU32((DWORD&)pVar->loc.vlStkReg.vlsrStk.vlsrsOffset);
        trans.DoEncodedRegIdx(pVar->loc.vlStkReg.vlsrStk.vlsrsBaseReg);
        trans.DoEncodedRegIdx(pVar->loc.vlStkReg.vlsrReg);
        break;
#endif // MDIL

    case ICorDebugInfo::VLT_STK2:
        trans.DoEncodedRegIdx(pVar->loc.vlStk2.vls2BaseReg);
        trans.DoEncodedStackOffset(pVar->loc.vlStk2.vls2Offset);
        break;

#ifdef MDIL
    case ICorDebugInfo::VLT_STK2 | ICorDebugInfo::VLT_MDIL_SYMBOLIC:
        _ASSERTE(pVar->loc.vlStk2.vls2Offset >= 0);
        trans.DoEncodedRegIdx(pVar->loc.vlStk2.vls2BaseReg);
        trans.DoEncodedU32((DWORD&)pVar->loc.vlStk2.vls2Offset);
        break;
#endif // MDIL

    case ICorDebugInfo::VLT_FPSTK:
        trans.DoEncodedUnsigned(pVar->loc.vlFPstk.vlfReg);
        break;

    case ICorDebugInfo::VLT_FIXED_VA:
        trans.DoEncodedUnsigned(pVar->loc.vlFixedVarArg.vlfvOffset);
        break;

    default:
        _ASSERTE(!"Unknown varloc type!");
        break;
    }

    trans.DoCookie(0xC);
}

#ifndef DACCESS_COMPILE

void CompressDebugInfo::CompressBoundaries(
    IN ULONG32                       cMap,
    IN ICorDebugInfo::OffsetMapping *pMap,
    IN OUT NibbleWriter             *pWriter
)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    _ASSERTE(pWriter != NULL);
    _ASSERTE((pMap == NULL) == (cMap == 0));

    if (cMap != 0)
    {
        pWriter->WriteEncodedU32(cMap);

        TransferWriter t(*pWriter);
        DoBounds(t, cMap, pMap);

        pWriter->Flush();
    }

#ifdef _DEBUG
    DWORD cbBlob;
    PVOID pBlob = pWriter->GetBlob(&cbBlob);

    // Track perf #s for compression...
    g_CDI_TotalMethods++;
    g_CDI_bMethodTotalUncompress += sizeof(ICorDebugInfo::OffsetMapping) * cMap;
    g_CDI_bMethodTotalCompress   += (int) cbBlob;
#endif // _DEBUG
}

void CompressDebugInfo::CompressVars(
    IN ULONG32                         cVars,
    IN ICorDebugInfo::NativeVarInfo    *vars,
    IN OUT NibbleWriter                *pWriter
)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    _ASSERTE(pWriter != NULL);
    _ASSERTE((cVars == 0) == (vars == NULL));

    if (cVars != 0)
    {
        pWriter->WriteEncodedU32(cVars);

        TransferWriter t(*pWriter);
        for(ULONG32 i = 0; i < cVars; i ++)
        {
            DoNativeVarInfo(t, &vars[i]);
        }

        pWriter->Flush();
    }

#ifdef _DEBUG
    DWORD cbBlob;
    PVOID pBlob = pWriter->GetBlob(&cbBlob);

    g_CDI_bVarsTotalUncompress += cVars * sizeof(ICorDebugInfo::NativeVarInfo);
    g_CDI_bVarsTotalCompress   += (int) cbBlob;
#endif
}

PTR_BYTE CompressDebugInfo::CompressBoundariesAndVars(
    IN ICorDebugInfo::OffsetMapping * pOffsetMapping,
    IN ULONG            iOffsetMapping,
    IN ICorDebugInfo::NativeVarInfo * pNativeVarInfo,
    IN ULONG            iNativeVarInfo,
    IN OUT SBuffer    * pDebugInfoBuffer,
    IN LoaderHeap     * pLoaderHeap
    )
{
    CONTRACTL {
        THROWS; // compression routines throw
        PRECONDITION((iOffsetMapping == 0) == (pOffsetMapping == NULL));
        PRECONDITION((iNativeVarInfo == 0) == (pNativeVarInfo == NULL));
        PRECONDITION((pDebugInfoBuffer != NULL) ^ (pLoaderHeap != NULL));
    } CONTRACTL_END;

    // Actually do the compression. These will throw on oom.
    NibbleWriter boundsBuffer;
    DWORD cbBounds = 0;
    PVOID pBounds = NULL;
    if (iOffsetMapping > 0)
    {
        CompressDebugInfo::CompressBoundaries(iOffsetMapping, pOffsetMapping, &boundsBuffer);
        pBounds = boundsBuffer.GetBlob(&cbBounds);
    }

    NibbleWriter varsBuffer;
    DWORD cbVars = 0;
    PVOID pVars = NULL;
    if (iNativeVarInfo > 0)
    {
        CompressDebugInfo::CompressVars(iNativeVarInfo, pNativeVarInfo, &varsBuffer);
        pVars = varsBuffer.GetBlob(&cbVars);
    }

    // Now write it all out to the buffer in a compact fashion.
    NibbleWriter w;
    w.WriteEncodedU32(cbBounds);
    w.WriteEncodedU32(cbVars);
    w.Flush();

    DWORD cbHeader;
    PVOID pHeader = w.GetBlob(&cbHeader);

    S_UINT32 cbFinalSize = S_UINT32(cbHeader) + S_UINT32(cbBounds) + S_UINT32(cbVars);
    if (cbFinalSize.IsOverflow())
        ThrowHR(COR_E_OVERFLOW);

    BYTE *ptrStart = NULL;
    if (pLoaderHeap != NULL)
    {
        ptrStart = (BYTE *)(void *)pLoaderHeap->AllocMem(S_SIZE_T(cbFinalSize.Value()));
    }
    else
    {
        // Create a conservatively large buffer to hold all the data.
        ptrStart = pDebugInfoBuffer->OpenRawBuffer(cbFinalSize.Value());
    }
    _ASSERTE(ptrStart != NULL); // throws on oom.

    BYTE *ptr = ptrStart;

    memcpy(ptr, pHeader, cbHeader);
    ptr += cbHeader;

    memcpy(ptr, pBounds, cbBounds);
    ptr += cbBounds;

    memcpy(ptr, pVars, cbVars);
    ptr += cbVars;

    if (pLoaderHeap != NULL)
    {
        return ptrStart;
    }
    else
    {
        pDebugInfoBuffer->CloseRawBuffer(cbFinalSize.Value());
        return NULL;
    }
}

#endif // DACCESS_COMPILE

//-----------------------------------------------------------------------------
// Compression routines
// DAC only needs to run the uncompression routines.
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Uncompression (restore) routines
//-----------------------------------------------------------------------------

// Uncompress data supplied by Compress functions.
void CompressDebugInfo::RestoreBoundariesAndVars(
    IN FP_IDS_NEW fpNew, IN void * pNewData,
    IN PTR_BYTE                         pDebugInfo,
    OUT ULONG32                       * pcMap, // number of entries in ppMap
    OUT ICorDebugInfo::OffsetMapping **ppMap, // pointer to newly allocated array
    OUT ULONG32                         *pcVars,
    OUT ICorDebugInfo::NativeVarInfo    **ppVars
    )
{
    CONTRACTL
    {
        THROWS; // reading from nibble stream may throw on invalid data.
        GC_NOTRIGGER;
        MODE_ANY;
        SUPPORTS_DAC;
    }
    CONTRACTL_END;

    if (pcMap != NULL) *pcMap = 0;
    if (ppMap != NULL) *ppMap = NULL;
    if (pcVars != NULL) *pcVars = 0;
    if (ppVars != NULL) *ppVars = NULL;

    NibbleReader r(pDebugInfo, 12 /* maximum size of compressed 2 UINT32s */);

    ULONG cbBounds = r.ReadEncodedU32();
    ULONG cbVars   = r.ReadEncodedU32();

    PTR_BYTE addrBounds = pDebugInfo + r.GetNextByteIndex();
    PTR_BYTE addrVars   = addrBounds + cbBounds;

    if ((pcMap != NULL || ppMap != NULL) && (cbBounds != 0))
    {
        NibbleReader r(addrBounds, cbBounds);
        TransferReader t(r);

        UINT32 cNumEntries = r.ReadEncodedU32();
        _ASSERTE(cNumEntries > 0);

        if (pcMap != NULL)
            *pcMap = cNumEntries;

        if (ppMap != NULL)
        {
            ICorDebugInfo::OffsetMapping * pMap = reinterpret_cast<ICorDebugInfo::OffsetMapping *>
                (fpNew(pNewData, cNumEntries * sizeof(ICorDebugInfo::OffsetMapping)));
            if (pMap == NULL)
            {
                ThrowOutOfMemory();
            }
            *ppMap = pMap;

            // Main decompression routine.
            DoBounds(t, cNumEntries, pMap);
        }
    }

    if ((pcVars != NULL || ppVars != NULL) && (cbVars != 0))
    {
        NibbleReader r(addrVars, cbVars);
        TransferReader t(r);

        UINT32 cNumEntries = r.ReadEncodedU32();
        _ASSERTE(cNumEntries > 0);

        if (pcVars != NULL)
            *pcVars = cNumEntries;

        if (ppVars != NULL)
        {
            ICorDebugInfo::NativeVarInfo * pVars = reinterpret_cast<ICorDebugInfo::NativeVarInfo *>
                (fpNew(pNewData, cNumEntries * sizeof(ICorDebugInfo::NativeVarInfo)));
            if (pVars == NULL)
            {
                ThrowOutOfMemory();
            }
            *ppVars = pVars;

            for(UINT32 i = 0; i < cNumEntries; i++)
            {
                DoNativeVarInfo(t, &pVars[i]);
            }
        }
    }
}

#ifdef DACCESS_COMPILE
void CompressDebugInfo::EnumMemoryRegions(CLRDataEnumMemoryFlags flags, PTR_BYTE pDebugInfo)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        SUPPORTS_DAC;
    }
    CONTRACTL_END;

    NibbleReader r(pDebugInfo, 12 /* maximum size of compressed 2 UINT32s */);

    ULONG cbBounds = r.ReadEncodedU32();
    ULONG cbVars   = r.ReadEncodedU32();

    DacEnumMemoryRegion(dac_cast<TADDR>(pDebugInfo), r.GetNextByteIndex() + cbBounds + cbVars);
}
#endif // DACCESS_COMPILE

#ifndef BINDER
// Init given a starting address from the start of code.
void DebugInfoRequest::InitFromStartingAddr(MethodDesc * pMD, PCODE addrCode)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        SUPPORTS_DAC;
    }
    CONTRACTL_END;

    _ASSERTE(pMD != NULL);
    _ASSERTE(addrCode != NULL);

    this->m_pMD       = pMD;
    this->m_addrStart = addrCode;
}

//-----------------------------------------------------------------------------
// Impl for DebugInfoManager's IDebugInfoStore
//-----------------------------------------------------------------------------
BOOL DebugInfoManager::GetBoundariesAndVars(
    const DebugInfoRequest & request,
    IN FP_IDS_NEW fpNew, IN void * pNewData,
    OUT ULONG32 * pcMap,
    OUT ICorDebugInfo::OffsetMapping ** ppMap,
    OUT ULONG32 * pcVars,
    OUT ICorDebugInfo::NativeVarInfo ** ppVars)
{
    CONTRACTL
    {
        THROWS;
        WRAPPER(GC_TRIGGERS); // depends on fpNew
        SUPPORTS_DAC;
    }
    CONTRACTL_END;

    IJitManager* pJitMan = ExecutionManager::FindJitMan(request.GetStartAddress());
    if (pJitMan == NULL)
    {
        return FALSE; // no info available.
    }

    return pJitMan->GetBoundariesAndVars(request, fpNew, pNewData, pcMap, ppMap, pcVars, ppVars);
}

#ifdef DACCESS_COMPILE
void DebugInfoManager::EnumMemoryRegionsForMethodDebugInfo(CLRDataEnumMemoryFlags flags, MethodDesc * pMD)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        SUPPORTS_DAC;
    }
    CONTRACTL_END;

    PCODE addrCode = pMD->GetNativeCode();
    if (addrCode == NULL)
    {
        return;
    }

    IJitManager* pJitMan = ExecutionManager::FindJitMan(addrCode);
    if (pJitMan == NULL)
    {
        return; // no info available.
    }

    pJitMan->EnumMemoryRegionsForMethodDebugInfo(flags, pMD);
}
#endif

#endif // BINDER


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding field 'Test.slug'
        db.add_column(u'dojo_test', 'slug',
                      self.gf('django.db.models.fields.SlugField')(default='', max_length=50),
                      keep_default=False)

    def backwards(self, orm):
        # Deleting field 'Test.slug'
        db.delete_column(u'dojo_test', 'slug')

    models = {
        u'auth.group': {
            'Meta': {'object_name': 'Group'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        u'auth.permission': {
            'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        u'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        u'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        u'dojo.discipline': {
            'Meta': {'ordering': "['-created']", 'object_name': 'Discipline'},
            'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 4, 6, 0, 0)', 'null': 'True', 'blank': 'True'}),
            'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['dojo.Student']"}),
            'description': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}),
            'dojo': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['dojo.Dojo']", 'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'private': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'slug': ('autoslug.fields.AutoSlugField', [], {'unique_with': '()', 'max_length': '50', 'populate_from': "'title'"}),
            'test_in_order': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        u'dojo.dojo': {
            'Meta': {'object_name': 'Dojo'},
            'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 4, 6, 0, 0)', 'null': 'True', 'blank': 'True'}),
            'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['dojo.Student']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'owners': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.User']", 'symmetrical': 'False'}),
            'private': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'slug': ('autoslug.fields.AutoSlugField', [], {'unique_with': '()', 'max_length': '50', 'populate_from': "'title'"}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        u'dojo.rank': {
            'Meta': {'ordering': "['order']", 'object_name': 'Rank'},
            'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 4, 6, 0, 0)', 'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'order': ('django.db.models.fields.IntegerField', [], {'max_length': '2'}),
            'slug': ('autoslug.fields.AutoSlugField', [], {'unique_with': '()', 'max_length': '50', 'populate_from': "'title'"}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        u'dojo.student': {
            'Meta': {'object_name': 'Student'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 4, 6, 0, 0)', 'null': 'True', 'blank': 'True'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"})
        },
        u'dojo.test': {
            'Meta': {'ordering': "['rank_awarded__order']", 'object_name': 'Test'},
            'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 4, 6, 0, 0)', 'null': 'True', 'blank': 'True'}),
            'discipline': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['dojo.Discipline']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'pass_percentage': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
            'rank_awarded': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['dojo.Rank']"}),
            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'})
        },
        u'dojo.testanswer': {
            'Meta': {'object_name': 'TestAnswer'},
            'answer': ('django.db.models.fields.TextField', [], {}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'order': ('django.db.models.fields.IntegerField', [], {'default': '1'})
        },
        u'dojo.testattempt': {
            'Meta': {'ordering': "['test', 'test__rank_awarded']", 'object_name': 'TestAttempt'},
            'correct_answers': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['dojo.TestQuestion']", 'null': 'True', 'blank': 'True'}),
            'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 4, 6, 0, 0)', 'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'student': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['dojo.Student']"}),
            'test': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['dojo.Test']"})
        },
        u'dojo.testquestion': {
            'Meta': {'object_name': 'TestQuestion'},
            'answers': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['dojo.TestAnswer']", 'symmetrical': 'False'}),
            'correct_answer': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'correct_answer'", 'to': u"orm['dojo.TestAnswer']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'question': ('django.db.models.fields.TextField', [], {}),
            'test': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['dojo.Test']"})
        }
    }

    complete_apps = ['dojo']


text:
layout:				post
comments: 			true

title:				Vagabond
subtitle:			London
address:

date:				2016-01-24
author_date:		2016-01-30

categories:
- england

tags:
- town
- wine
- food
- london

images_folder:		vagabond
---

> You're left to your own devices to discover the many wines they have to offer.

Need a place to go on a Friday night after work? Or for a Sunday afternoon to get the mind set for the week ahead? Or maybe you just want a good glass of wine… and it doesn't matter why. I have found the place, [Vagabonds, Spitalfields](https://vagabondwines.co.uk/).

{% image full /images/vagabond/bar.jpg %}

So the concept is you pay a £5 deposit for a card and you top it up with what ever amount you want. Then off you go! You're left to your own devices to discover the many wines they have to offer. They are presented in self serving machines, with a cheeky description and a random fact. You eye up the one you want, insert you card and press the button. Voila, the wine is served!

{% image full /images/vagabond/push.jpg %}

> One was a £20 glass of wine… slightly out of my budget.

Some people may not like the idea of having to serve themselves in a bar but I love it. It gives you a chance to try a variety of wines, at ease and at your own pace. Also, if you like wine a lot ( like me darling)  but still trying to find your feet in the big, scary wine tasting world this a good start. You can have tasters, do the swish and flick of the old wine glass and discover which wine is best for you.

The bar itself is small and intimate which gives the place a nice buzz when it's busy. I love sitting outside with the heaters and blankets, watching people walk by in the market. The staff are very helpful too, giving advice on wine and making suggestions. One was a £20 glass of wine… slightly out of my budget.

{% image full /images/vagabond/sister.jpg %}

**Do try the food too!** The charcuterie boards are cracking. There is a really good selection of meats and they have my favourite salami, finocchiona which has fennel in it. The sausage roll goes down well with a '*Vibrant*' glass of red!


text:
/*
 * Created by SharpDevelop.
 * User: dehalleux
 * Date: 18/05/2004
 * Time: 11:36
 *
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;

namespace QuickGraph.UnitTests.Algorithm.Ranking
{
	[TestFixture]
	public class PageRankAlgorithmTest
	{
	}
}


text:
package com.github.lothar.security.acl.jpa.repository;

import java.util.List;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;

import com.github.lothar.security.acl.jpa.annotation.NoAcl;
import com.github.lothar.security.acl.jpa.domain.Customer;

public interface CustomerRepository extends JpaRepository<Customer, String> {

  Customer findByFirstName(String firstName);

  List<Customer> findByLastName(String lastName);

  List<Customer> findByFirstNameContains(String firstNameContains, Sort sort);

  List<Customer> findByFirstNameContains(String firstNameContains, Pageable pageable);

  int countByLastName(String lastName);

  @NoAcl
  int countByLastNameContains(String firstName);
}


text:
package org.apache.spark.streaming.ui

import javax.servlet.http.HttpServletRequest

import scala.xml._

import org.apache.commons.lang3.StringEscapeUtils

import org.apache.spark.streaming.Time
import org.apache.spark.streaming.ui.StreamingJobProgressListener.SparkJobId
import org.apache.spark.ui.{UIUtils => SparkUIUtils, WebUIPage}
import org.apache.spark.ui.jobs.UIData.JobUIData

private[ui] case class SparkJobIdWithUIData(sparkJobId: SparkJobId, jobUIData: Option[JobUIData])

private[ui] class BatchPage(parent: StreamingTab) extends WebUIPage("batch") {
  private val streamingListener = parent.listener
  private val sparkListener = parent.sparkUI.jobProgressListener
  private def columns: Seq[Node] = {
    Output Op Id
      Description
      Output Op Duration
      Status
      Job Id
      Job Duration
      Stages: Succeeded/Total
      Tasks (for all stages): Succeeded/Total
      Error
  }

  private def generateJobRow(
      outputOpData: OutputOperationUIData,
      outputOpDescription: Seq[Node],
      formattedOutputOpDuration: String,
      numSparkJobRowsInOutputOp: Int,
      isFirstRow: Boolean,
      sparkJob: SparkJobIdWithUIData): Seq[Node] = {
    if (sparkJob.jobUIData.isDefined) {
      generateNormalJobRow(outputOpData, outputOpDescription, formattedOutputOpDuration,
        numSparkJobRowsInOutputOp, isFirstRow, sparkJob.jobUIData.get)
    } else {
      generateDroppedJobRow(outputOpData, outputOpDescription, formattedOutputOpDuration,
        numSparkJobRowsInOutputOp, isFirstRow, sparkJob.sparkJobId)
    }
  }

  private def generateOutputOpRowWithoutSparkJobs(
    outputOpData: OutputOperationUIData,
    outputOpDescription: Seq[Node],
    formattedOutputOpDuration: String): Seq[Node] = {

      {outputOpData.id.toString}
      {outputOpDescription}
      {formattedOutputOpDuration}
      {outputOpStatusCell(outputOpData, rowspan = 1)}

      -

      -

      -

      -

      -

  }

  /**
   * Generate a row for a Spark Job. Because duplicated output op infos needs to be collapsed into
   * one cell, we use "rowspan" for the first row of an output op.
   */
  private def generateNormalJobRow(
      outputOpData: OutputOperationUIData,
      outputOpDescription: Seq[Node],
      formattedOutputOpDuration: String,
      numSparkJobRowsInOutputOp: Int,
      isFirstRow: Boolean,
      sparkJob: JobUIData): Seq[Node] = {
    val duration: Option[Long] = {
      sparkJob.submissionTime.map { start =>
        val end = sparkJob.completionTime.getOrElse(System.currentTimeMillis())
        end - start
      }
    }
    val lastFailureReason =
      sparkJob.stageIds.sorted.reverse.flatMap(sparkListener.stageIdToInfo.get).
      dropWhile(_.failureReason == None).take(1). // get the first info that contains failure
      flatMap(info => info.failureReason).headOption.getOrElse("")
    val formattedDuration = duration.map(d => SparkUIUtils.formatDuration(d)).getOrElse("-")
    val detailUrl = s"${SparkUIUtils.prependBaseUri(parent.basePath)}/jobs/job?id=${sparkJob.jobId}"

    // In the first row, output op id and its information needs to be shown. In other rows, these
    // cells will be taken up due to "rowspan".
    // scalastyle:off
    val prefixCells =
      if (isFirstRow) {
        {outputOpData.id.toString}

          {outputOpDescription}

        {formattedOutputOpDuration}	 ++
        {outputOpStatusCell(outputOpData, numSparkJobRowsInOutputOp)}
      } else {
        Nil
      }
    // scalastyle:on

      {prefixCells}

          {sparkJob.jobId}{sparkJob.jobGroup.map(id => s"($id)").getOrElse("")}

        {formattedDuration}

        {sparkJob.completedStageIndices.size}/{sparkJob.stageIds.size - sparkJob.numSkippedStages}
        {if (sparkJob.numFailedStages > 0) s"(${sparkJob.numFailedStages} failed)"}
        {if (sparkJob.numSkippedStages > 0) s"(${sparkJob.numSkippedStages} skipped)"}

        {
          SparkUIUtils.makeProgressBar(
            started = sparkJob.numActiveTasks,
            completed = sparkJob.numCompletedTasks,
            failed = sparkJob.numFailedTasks,
            skipped = sparkJob.numSkippedTasks,
            reasonToNumKilled = sparkJob.reasonToNumKilled,
            total = sparkJob.numTasks - sparkJob.numSkippedTasks)
        }

      {UIUtils.failureReasonCell(lastFailureReason)}

  }

  /**
   * If a job is dropped by sparkListener due to exceeding the limitation, we only show the job id
   * with "-" cells.
   */
  private def generateDroppedJobRow(
      outputOpData: OutputOperationUIData,
      outputOpDescription: Seq[Node],
      formattedOutputOpDuration: String,
      numSparkJobRowsInOutputOp: Int,
      isFirstRow: Boolean,
      jobId: Int): Seq[Node] = {
    // In the first row, output op id and its information needs to be shown. In other rows, these
    // cells will be taken up due to "rowspan".
    // scalastyle:off
    val prefixCells =
      if (isFirstRow) {
        {outputOpData.id.toString}
          {outputOpDescription}
          {formattedOutputOpDuration}	 ++
          {outputOpStatusCell(outputOpData, numSparkJobRowsInOutputOp)}
      } else {
        Nil
      }
    // scalastyle:on

      {prefixCells}

        {if (jobId >= 0) jobId.toString else "-"}

      -

      -

      -

      -

  }

  private def generateOutputOpIdRow(
      outputOpData: OutputOperationUIData,
      sparkJobs: Seq[SparkJobIdWithUIData]): Seq[Node] = {
    val formattedOutputOpDuration =
      if (outputOpData.duration.isEmpty) {
        "-"
      } else {
        SparkUIUtils.formatDuration(outputOpData.duration.get)
      }

    val description = generateOutputOpDescription(outputOpData)

    if (sparkJobs.isEmpty) {
      generateOutputOpRowWithoutSparkJobs(outputOpData, description, formattedOutputOpDuration)
    } else {
      val firstRow =
        generateJobRow(
          outputOpData,
          description,
          formattedOutputOpDuration,
          sparkJobs.size,
          true,
          sparkJobs.head)
      val tailRows =
        sparkJobs.tail.map { sparkJob =>
          generateJobRow(
            outputOpData,
            description,
            formattedOutputOpDuration,
            sparkJobs.size,
            false,
            sparkJob)
        }
      (firstRow ++ tailRows).flatten
    }
  }

  private def generateOutputOpDescription(outputOp: OutputOperationUIData): Seq[Node] = {

      {outputOp.name}

          +details

{outputOp.description}

  }

  private def getJobData(sparkJobId: SparkJobId): Option[JobUIData] = {
    sparkListener.activeJobs.get(sparkJobId).orElse {
      sparkListener.completedJobs.find(_.jobId == sparkJobId).orElse {
        sparkListener.failedJobs.find(_.jobId == sparkJobId)
      }
    }
  }

  private def generateOutputOperationStatusForUI(failure: String): String = {
    if (failure.startsWith("org.apache.spark.SparkException")) {
      "Failed due to Spark job error\n" + failure
    } else {
      var nextLineIndex = failure.indexOf("\n")
      if (nextLineIndex < 0) {
        nextLineIndex = failure.length
      }
      val firstLine = failure.substring(0, nextLineIndex)
      s"Failed due to error: $firstLine\n$failure"
    }
  }

  /**
   * Generate the job table for the batch.
   */
  private def generateJobTable(batchUIData: BatchUIData): Seq[Node] = {
    val outputOpIdToSparkJobIds = batchUIData.outputOpIdSparkJobIdPairs.groupBy(_.outputOpId).
      map { case (outputOpId, outputOpIdAndSparkJobIds) =>
        // sort SparkJobIds for each OutputOpId
        (outputOpId, outputOpIdAndSparkJobIds.map(_.sparkJobId).toSeq.sorted)
      }

    val outputOps: Seq[(OutputOperationUIData, Seq[SparkJobId])] =
      batchUIData.outputOperations.map { case (outputOpId, outputOperation) =>
        val sparkJobIds = outputOpIdToSparkJobIds.getOrElse(outputOpId, Seq.empty)
        (outputOperation, sparkJobIds)
      }.toSeq.sortBy(_._1.id)
    sparkListener.synchronized {
      val outputOpWithJobs = outputOps.map { case (outputOpData, sparkJobIds) =>
          (outputOpData,
            sparkJobIds.map(sparkJobId => SparkJobIdWithUIData(sparkJobId, getJobData(sparkJobId))))
        }

          {columns}

          {
            outputOpWithJobs.map { case (outputOpData, sparkJobIds) =>
              generateOutputOpIdRow(outputOpData, sparkJobIds)
            }
          }

    }
  }

  def render(request: HttpServletRequest): Seq[Node] = streamingListener.synchronized {
    // stripXSS is called first to remove suspicious characters used in XSS attacks
    val batchTime =
      Option(SparkUIUtils.stripXSS(request.getParameter("id"))).map(id => Time(id.toLong))
      .getOrElse {
      throw new IllegalArgumentException(s"Missing id parameter")
    }
    val formattedBatchTime =
      UIUtils.formatBatchTime(batchTime.milliseconds, streamingListener.batchDuration)

    val batchUIData = streamingListener.getBatchUIData(batchTime).getOrElse {
      throw new IllegalArgumentException(s"Batch $formattedBatchTime does not exist")
    }

    val formattedSchedulingDelay =
      batchUIData.schedulingDelay.map(SparkUIUtils.formatDuration).getOrElse("-")
    val formattedProcessingTime =
      batchUIData.processingDelay.map(SparkUIUtils.formatDuration).getOrElse("-")
    val formattedTotalDelay = batchUIData.totalDelay.map(SparkUIUtils.formatDuration).getOrElse("-")

    val inputMetadatas = batchUIData.streamIdToInputInfo.values.flatMap { inputInfo =>
      inputInfo.metadataDescription.map(desc => inputInfo.inputStreamId -> desc)
    }.toSeq
    val summary: NodeSeq =

            Batch Duration:
            {SparkUIUtils.formatDuration(streamingListener.batchDuration)}

            Input data size:
            {batchUIData.numRecords} records

            Scheduling delay:
            {formattedSchedulingDelay}

            Processing time:
            {formattedProcessingTime}

            Total delay:
            {formattedTotalDelay}

          {
            if (inputMetadatas.nonEmpty) {

                Input Metadata:{generateInputMetadataTable(inputMetadatas)}

            }
          }

    val content = summary ++ generateJobTable(batchUIData)

    SparkUIUtils.headerSparkPage(s"Details of batch at $formattedBatchTime", content, parent)
  }

  def generateInputMetadataTable(inputMetadatas: Seq[(Int, String)]): Seq[Node] = {

          Input
          Metadata

        {inputMetadatas.flatMap(generateInputMetadataRow)}

  }

  def generateInputMetadataRow(inputMetadata: (Int, String)): Seq[Node] = {
    val streamId = inputMetadata._1

      {streamingListener.streamName(streamId).getOrElse(s"Stream-$streamId")}
      {metadataDescriptionToHTML(inputMetadata._2)}

  }

  private def metadataDescriptionToHTML(metadataDescription: String): Seq[Node] = {
    // tab to 4 spaces and "\n" to "
"
    Unparsed(StringEscapeUtils.escapeHtml4(metadataDescription).
      replaceAllLiterally("\t", "    ").replaceAllLiterally("\n", "
"))
  }

  private def outputOpStatusCell(outputOp: OutputOperationUIData, rowspan: Int): Seq[Node] = {
    outputOp.failureReason match {
      case Some(failureReason) =>
        val failureReasonForUI = UIUtils.createOutputOperationFailureForUI(failureReason)
        UIUtils.failureReasonCell(
          failureReasonForUI, rowspan, includeFirstLineInExpandDetails = false)
      case None =>
        if (outputOp.endTime.isEmpty) {
          -
        } else {
          Succeeded
        }
    }
  }
}


text:
package helpers

import (
	"golang.org/x/net/context"
	"vitess.io/vitess/go/vt/log"
	"vitess.io/vitess/go/vt/topo"
)

// TeeFactory is an implementation of topo.Factory that uses a primary
// underlying topo.Server for all changes, but also duplicates the
// changes to a secondary topo.Server. It also locks both topo servers
// when needed.  It is meant to be used during transitions from one
// topo.Server to another.
//
// - primary: we read everything from it, and write to it. We also create
//     MasterParticipation from it.
// - secondary: we write to it as well, but we usually don't fail.
// - we lock primary/secondary if reverseLockOrder is False,
// or secondary/primary if reverseLockOrder is True.
type TeeFactory struct {
	primary          *topo.Server
	secondary        *topo.Server
	reverseLockOrder bool
}

// HasGlobalReadOnlyCell is part of the topo.Factory interface.
func (f *TeeFactory) HasGlobalReadOnlyCell(serverAddr, root string) bool {
	return false
}

// Create is part of the topo.Factory interface.
func (f *TeeFactory) Create(cell, serverAddr, root string) (topo.Conn, error) {
	ctx := context.Background()
	primaryConn, err := f.primary.ConnForCell(ctx, cell)
	if err != nil {
		return nil, err
	}
	secondaryConn, err := f.secondary.ConnForCell(ctx, cell)
	if err != nil {
		return nil, err
	}

	lockFirst := primaryConn
	lockSecond := secondaryConn
	if f.reverseLockOrder {
		lockFirst = secondaryConn
		lockSecond = primaryConn
	}

	return &TeeConn{
		primary:    primaryConn,
		secondary:  secondaryConn,
		lockFirst:  lockFirst,
		lockSecond: lockSecond,
	}, nil
}

// NewTee returns a new topo.Server object. It uses a TeeFactory.
func NewTee(primary, secondary *topo.Server, reverseLockOrder bool) (*topo.Server, error) {
	f := &TeeFactory{
		primary:          primary,
		secondary:        secondary,
		reverseLockOrder: reverseLockOrder,
	}
	return topo.NewWithFactory(f, "" /*serverAddress*/, "" /*root*/)
}

// TeeConn implements the topo.Conn interface.
type TeeConn struct {
	primary   topo.Conn
	secondary topo.Conn

	lockFirst  topo.Conn
	lockSecond topo.Conn
}

// Close is part of the topo.Conn interface.
func (c *TeeConn) Close() {
	c.primary.Close()
	c.secondary.Close()
}

// ListDir is part of the topo.Conn interface.
func (c *TeeConn) ListDir(ctx context.Context, dirPath string, full bool) ([]topo.DirEntry, error) {
	return c.primary.ListDir(ctx, dirPath, full)
}

// Create is part of the topo.Conn interface.
func (c *TeeConn) Create(ctx context.Context, filePath string, contents []byte) (topo.Version, error) {
	primaryVersion, err := c.primary.Create(ctx, filePath, contents)
	if err != nil {
		return nil, err
	}

	// This is critical enough that we want to fail. However, we support
	// an unconditional update if the file already exists.
	_, err = c.secondary.Create(ctx, filePath, contents)
	if topo.IsErrType(err, topo.NodeExists) {
		_, err = c.secondary.Update(ctx, filePath, contents, nil)
	}
	if err != nil {
		return nil, err
	}

	return primaryVersion, nil
}

// Update is part of the topo.Conn interface.
func (c *TeeConn) Update(ctx context.Context, filePath string, contents []byte, version topo.Version) (topo.Version, error) {
	primaryVersion, err := c.primary.Update(ctx, filePath, contents, version)
	if err != nil {
		// Failed on primary, not updating secondary.
		return nil, err
	}

	// Always do an unconditional update on secondary.
	if _, err = c.secondary.Update(ctx, filePath, contents, nil); err != nil {
		log.Warningf("secondary.Update(%v,unconditonal) failed: %v", filePath, err)
	}
	return primaryVersion, nil
}

// Get is part of the topo.Conn interface.
func (c *TeeConn) Get(ctx context.Context, filePath string) ([]byte, topo.Version, error) {
	return c.primary.Get(ctx, filePath)
}

// Delete is part of the topo.Conn interface.
func (c *TeeConn) Delete(ctx context.Context, filePath string, version topo.Version) error {
	// If primary fails, no need to go further.
	if err := c.primary.Delete(ctx, filePath, version); err != nil {
		return err
	}

	// Always do an unconditonal delete on secondary.
	if err := c.secondary.Delete(ctx, filePath, nil); err != nil && !topo.IsErrType(err, topo.NoNode) {
		// Secondary didn't work, and the node wasn't gone already.
		log.Warningf("secondary.Delete(%v) failed: %v", filePath, err)
	}

	return nil
}

// Watch is part of the topo.Conn interface
func (c *TeeConn) Watch(ctx context.Context, filePath string) (*topo.WatchData, <-chan *topo.WatchData, topo.CancelFunc) {
	return c.primary.Watch(ctx, filePath)
}

//
// Lock management.
//

// teeTopoLockDescriptor implements the topo.LockDescriptor interface.
type teeTopoLockDescriptor struct {
	c                    *TeeConn
	dirPath              string
	firstLockDescriptor  topo.LockDescriptor
	secondLockDescriptor topo.LockDescriptor
}

// Lock is part of the topo.Conn interface.
func (c *TeeConn) Lock(ctx context.Context, dirPath, contents string) (topo.LockDescriptor, error) {
	// Lock lockFirst.
	fLD, err := c.lockFirst.Lock(ctx, dirPath, contents)
	if err != nil {
		return nil, err
	}

	// Lock lockSecond.
	sLD, err := c.lockSecond.Lock(ctx, dirPath, contents)
	if err != nil {
		if err := fLD.Unlock(ctx); err != nil {
			log.Warningf("Failed to unlock lockFirst after failed lockSecond lock for %v: %v", dirPath, err)
		}
		return nil, err
	}

	// Remember both locks in teeTopoLockDescriptor.
	return &teeTopoLockDescriptor{
		c:                    c,
		dirPath:              dirPath,
		firstLockDescriptor:  fLD,
		secondLockDescriptor: sLD,
	}, nil
}

// Check is part of the topo.LockDescriptor interface.
func (ld *teeTopoLockDescriptor) Check(ctx context.Context) error {
	if err := ld.firstLockDescriptor.Check(ctx); err != nil {
		return err
	}
	return ld.secondLockDescriptor.Check(ctx)
}

// Unlock is part of the topo.LockDescriptor interface.
func (ld *teeTopoLockDescriptor) Unlock(ctx context.Context) error {
	// Unlock lockSecond, then lockFirst.
	serr := ld.secondLockDescriptor.Unlock(ctx)
	ferr := ld.firstLockDescriptor.Unlock(ctx)

	if serr != nil {
		if ferr != nil {
			log.Warningf("First Unlock(%v) failed: %v", ld.dirPath, ferr)
		}
		return serr
	}
	return ferr
}

// NewMasterParticipation is part of the topo.Conn interface.
func (c *TeeConn) NewMasterParticipation(name, id string) (topo.MasterParticipation, error) {
	return c.primary.NewMasterParticipation(name, id)
}