text:
package org.apache.pdfbox.pdmodel.documentinterchange.taggedpdf;

import org.apache.pdfbox.cos.COSDictionary;

/**
 * An Export Format attribute object.
 *
 * @author Johannes Koch
 */
public class PDExportFormatAttributeObject extends PDLayoutAttributeObject
{

    /**
     *  standard attribute owner: XML-1.00
     */
    public static final String OWNER_XML_1_00 = "XML-1.00";
    /**
     *  standard attribute owner: HTML-3.2
     */
    public static final String OWNER_HTML_3_20 = "HTML-3.2";
    /**
     *  standard attribute owner: HTML-4.01
     */
    public static final String OWNER_HTML_4_01 = "HTML-4.01";
    /**
     *  standard attribute owner: OEB-1.00
     */
    public static final String OWNER_OEB_1_00 = "OEB-1.00";
    /**
     *  standard attribute owner: RTF-1.05
     */
    public static final String OWNER_RTF_1_05 = "RTF-1.05";
    /**
     *  standard attribute owner: CSS-1.00
     */
    public static final String OWNER_CSS_1_00 = "CSS-1.00";
    /**
     *  standard attribute owner: CSS-2.00
     */
    public static final String OWNER_CSS_2_00 = "CSS-2.00";

    /**
     * Default constructor.
     *
     * @param owner the owner of the attributes
     */
    public PDExportFormatAttributeObject(String owner)
    {
        this.setOwner(owner);
    }

    /**
     * Creates a new ExportFormat attribute object with a given dictionary.
     *
     * @param dictionary the dictionary
     */
    public PDExportFormatAttributeObject(COSDictionary dictionary)
    {
        super(dictionary);
    }

    /**
     * Gets the list numbering (ListNumbering). The default value is
     * {@link PDListAttributeObject#LIST_NUMBERING_NONE}.
     *
     * @return the list numbering
     */
    public String getListNumbering()
    {
        return this.getName(PDListAttributeObject.LIST_NUMBERING,
            PDListAttributeObject.LIST_NUMBERING_NONE);
    }

    /**
     * Sets the list numbering (ListNumbering). The value shall be one of the
     * following:
     *

     *
{@link PDListAttributeObject#LIST_NUMBERING_NONE},

     *
{@link PDListAttributeObject#LIST_NUMBERING_DISC},

     *
{@link PDListAttributeObject#LIST_NUMBERING_CIRCLE},

     *
{@link PDListAttributeObject#LIST_NUMBERING_SQUARE},

     *
{@link PDListAttributeObject#LIST_NUMBERING_DECIMAL},

     *
{@link PDListAttributeObject#LIST_NUMBERING_UPPER_ROMAN},

     *
{@link PDListAttributeObject#LIST_NUMBERING_LOWER_ROMAN},

     *
{@link PDListAttributeObject#LIST_NUMBERING_UPPER_ALPHA},

     *
{@link PDListAttributeObject#LIST_NUMBERING_LOWER_ALPHA}.

     *

     *
     * @param listNumbering the list numbering
     */
    public void setListNumbering(String listNumbering)
    {
        this.setName(PDListAttributeObject.LIST_NUMBERING, listNumbering);
    }

    /**
     * Gets the number of rows in the enclosing table that shall be spanned by
     * the cell (RowSpan). The default value is 1.
     *
     * @return the row span
     */
    public int getRowSpan()
    {
        return this.getInteger(PDTableAttributeObject.ROW_SPAN, 1);
    }

    /**
     * Sets the number of rows in the enclosing table that shall be spanned by
     * the cell (RowSpan).
     *
     * @param rowSpan the row span
     */
    public void setRowSpan(int rowSpan)
    {
        this.setInteger(PDTableAttributeObject.ROW_SPAN, rowSpan);
    }

    /**
     * Gets the number of columns in the enclosing table that shall be spanned
     * by the cell (ColSpan). The default value is 1.
     *
     * @return the column span
     */
    public int getColSpan()
    {
        return this.getInteger(PDTableAttributeObject.COL_SPAN, 1);
    }

    /**
     * Sets the number of columns in the enclosing table that shall be spanned
     * by the cell (ColSpan).
     *
     * @param colSpan the column span
     */
    public void setColSpan(int colSpan)
    {
        this.setInteger(PDTableAttributeObject.COL_SPAN, colSpan);
    }

    /**
     * Gets the headers (Headers). An array of byte strings, where each string
     * shall be the element identifier (see the
     * {@link org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDStructureElement#getElementIdentifier()}) for a TH structure
     * element that shall be used as a header associated with this cell.
     *
     * @return the headers.
     */
    public String[] getHeaders()
    {
        return this.getArrayOfString(PDTableAttributeObject.HEADERS);
    }

    /**
     * Sets the headers (Headers). An array of byte strings, where each string
     * shall be the element identifier (see the
     * {@link org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDStructureElement#getElementIdentifier()}) for a TH structure
     * element that shall be used as a header associated with this cell.
     *
     * @param headers the headers
     */
    public void setHeaders(String[] headers)
    {
        this.setArrayOfString(PDTableAttributeObject.HEADERS, headers);
    }

    /**
     * Gets the scope (Scope). It shall reflect whether the header cell applies
     * to the rest of the cells in the row that contains it, the column that
     * contains it, or both the row and the column that contain it.
     *
     * @return the scope
     */
    public String getScope()
    {
        return this.getName(PDTableAttributeObject.SCOPE);
    }

    /**
     * Sets the scope (Scope). It shall reflect whether the header cell applies
     * to the rest of the cells in the row that contains it, the column that
     * contains it, or both the row and the column that contain it. The value
     * shall be one of the following:
     *

     *
{@link PDTableAttributeObject#SCOPE_ROW},

     *
{@link PDTableAttributeObject#SCOPE_COLUMN}, or

     *
{@link PDTableAttributeObject#SCOPE_BOTH}.

     *

     *
     * @param scope the scope
     */
    public void setScope(String scope)
    {
        this.setName(PDTableAttributeObject.SCOPE, scope);
    }

    /**
     * Gets the summary of the table's purpose and structure.
     *
     * @return the summary
     */
    public String getSummary()
    {
        return this.getString(PDTableAttributeObject.SUMMARY);
    }

    /**
     * Sets the summary of the table's purpose and structure.
     *
     * @param summary the summary
     */
    public void setSummary(String summary)
    {
        this.setString(PDTableAttributeObject.SUMMARY, summary);
    }

    @Override
    public String toString()
    {
        StringBuilder sb = new StringBuilder().append(super.toString());
        if (this.isSpecified(PDListAttributeObject.LIST_NUMBERING))
        {
            sb.append(", ListNumbering=").append(this.getListNumbering());
        }
        if (this.isSpecified(PDTableAttributeObject.ROW_SPAN))
        {
            sb.append(", RowSpan=").append(this.getRowSpan());
        }
        if (this.isSpecified(PDTableAttributeObject.COL_SPAN))
        {
            sb.append(", ColSpan=").append(this.getColSpan());
        }
        if (this.isSpecified(PDTableAttributeObject.HEADERS))
        {
            sb.append(", Headers=").append(arrayToString(this.getHeaders()));
        }
        if (this.isSpecified(PDTableAttributeObject.SCOPE))
        {
            sb.append(", Scope=").append(this.getScope());
        }
        if (this.isSpecified(PDTableAttributeObject.SUMMARY))
        {
            sb.append(", Summary=").append(this.getSummary());
        }
        return sb.toString();
    }

}


text:
<?php
/**
 * PHP version 5
 *
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
namespace Mandragora;

use Zend_Mail;
use Zend_View;

/**
 * Sends e-mails using Zend_View templates
 */
class HtmlEmailSender
{
    /**
     * @var Zend_View
     */
    protected static $defaultView;

    /**
     * @var Zend_View
     */
    protected $view;

    /**
     * @var Zend_Mail
     */
    protected $mailer;

    /**
     * @param Zend_Mail $mailer
     */
    public function __construct(Zend_Mail $mailer)
    {
        $this->mailer = $mailer;
        $this->view = self::getDefaultView();
    }

    /**
     * @return Zend_View
     */
    protected static function getDefaultView()
    {
        if(self::$defaultView === null) {
            self::$defaultView = new Zend_View();
            self::$defaultView->setScriptPath(
                APPLICATION_PATH . '/views/scripts/common/mail'
            );
            self::$defaultView->setHelperPath(
                'Mandragora/View/Helper', 'Mandragora_View_Helper'
            );
        }
        return self::$defaultView;
    }

    /**
     * @param string $template
     * @return void
     */
    public function sendHtmlTemplate($template)
    {
        $html = $this->view->render((string)$template);
        $this->mailer->setBodyHtml($html, $this->mailer->getCharset());
        $this->mailer->send();
    }

    /**
     * @param string $property
     * @param string $value
     * @return Mandragora_HtmlEmailSender
     */
    public function setViewParam($property, $value)
    {
        $this->view->__set($property, $value);
        return $this;
    }
}

redpajama_set_name: RedPajamaGithub


text:
ContrastFilter::ContrastFilter(float contrast) : AbstractFilter(0, 0) {
    _addParameter(new ParameterF("contrast", contrast));
    _setupShader();
}
ContrastFilter::~ContrastFilter() {}

void ContrastFilter::setContrast(float contrast) {
    updateParameter("contrast", contrast);
}

string ContrastFilter::_getFragSrc() {
    return GLSL_STRING(120,
                       varying vec2 textureCoordinate;

                       uniform sampler2D inputImageTexture;
                       uniform float contrast;

                       void main()
                       {
                           vec2 uv = gl_TexCoord[0].xy;
                           vec4 textureColor = texture2D(inputImageTexture, uv);

                           gl_FragColor = vec4(((textureColor.rgb - vec3(0.5)) * contrast + vec3(0.5)), textureColor.w);
                       }
                       );
}


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

namespace OpenTK.Platform.MacOS
{
    using Carbon;
    using Graphics;

    using AGLRendererInfo = IntPtr;
    using AGLPixelFormat = IntPtr;
    using AGLContext = IntPtr;
    using AGLPbuffer = IntPtr;

    class AglContext : DesktopGraphicsContext
    {
        bool mVSync = false;
        // Todo: keep track of which display adapter was specified when the context was created.
        // IntPtr displayID;

        GraphicsMode graphics_mode;
        CarbonWindowInfo carbonWindow;
        IntPtr shareContextRef;
        DisplayDevice device;
        bool mIsFullscreen = false;

        public AglContext(GraphicsMode mode, IWindowInfo window, IGraphicsContext shareContext)
        {
            Debug.Print("Context Type: {0}", shareContext);
            Debug.Print("Window info: {0}", window);

            this.graphics_mode = mode;
            this.carbonWindow = (CarbonWindowInfo)window;

            if (shareContext is AglContext)
                shareContextRef = ((AglContext)shareContext).Handle.Handle;
            if (shareContext is GraphicsContext)
            {
                ContextHandle shareHandle = shareContext != null ? (shareContext as IGraphicsContextInternal).Context : (ContextHandle)IntPtr.Zero;

                shareContextRef = shareHandle.Handle;
            }

            if (shareContextRef == IntPtr.Zero)
            {
                Debug.Print("No context sharing will take place.");
            }

            CreateContext(mode, carbonWindow, shareContextRef, true);
        }

        public AglContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext)
        {
            if (handle == ContextHandle.Zero)
                throw new ArgumentException("handle");
            if (window == null)
                throw new ArgumentNullException("window");

            Handle = handle;
            carbonWindow = (CarbonWindowInfo)window;
        }

        private void AddPixelAttrib(List<int> aglAttributes, Agl.PixelFormatAttribute pixelFormatAttribute)
        {
            Debug.Print(pixelFormatAttribute.ToString());

            aglAttributes.Add((int)pixelFormatAttribute);
        }
        private void AddPixelAttrib(List<int> aglAttributes, Agl.PixelFormatAttribute pixelFormatAttribute, int value)
        {
            Debug.Print("{0} : {1}", pixelFormatAttribute, value);

            aglAttributes.Add((int)pixelFormatAttribute);
            aglAttributes.Add(value);
        }
        void CreateContext(GraphicsMode mode, CarbonWindowInfo carbonWindow, IntPtr shareContextRef, bool fullscreen)
        {
            List<int> aglAttributes = new List<int>();

            Debug.Print("AGL pixel format attributes:");
            Debug.Indent();

            AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_RGBA);
            AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_DOUBLEBUFFER);
            AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_RED_SIZE, mode.ColorFormat.Red);
            AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_GREEN_SIZE, mode.ColorFormat.Green);
            AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_BLUE_SIZE, mode.ColorFormat.Blue);
            AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_ALPHA_SIZE, mode.ColorFormat.Alpha);

            if (mode.Depth > 0)
                AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_DEPTH_SIZE, mode.Depth);

            if (mode.Stencil > 0)
                AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_STENCIL_SIZE, mode.Stencil);

            if (mode.AccumulatorFormat.BitsPerPixel > 0)
            {
                AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_ACCUM_RED_SIZE, mode.AccumulatorFormat.Red);
                AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_ACCUM_GREEN_SIZE, mode.AccumulatorFormat.Green);
                AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_ACCUM_BLUE_SIZE, mode.AccumulatorFormat.Blue);
                AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_ACCUM_ALPHA_SIZE, mode.AccumulatorFormat.Alpha);
            }

            if (mode.Samples > 1)
            {
                AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_SAMPLE_BUFFERS_ARB, 1);
                AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_SAMPLES_ARB, mode.Samples);
            }

            if (fullscreen)
            {
                AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_FULLSCREEN);
            }
            AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_NONE);

            Debug.Unindent();

            Debug.Write("Attribute array:  ");
            for (int i = 0; i < aglAttributes.Count; i++)
                Debug.Write(aglAttributes[i].ToString() + "  ");
            Debug.WriteLine("");

            AGLPixelFormat myAGLPixelFormat;

            // Choose a pixel format with the attributes we specified.
            if (fullscreen)
            {
                IntPtr gdevice;
                IntPtr cgdevice = GetQuartzDevice(carbonWindow);

                if (cgdevice == IntPtr.Zero)
                    cgdevice = (IntPtr)DisplayDevice.Default.Id;

                OSStatus status = Carbon.API.DMGetGDeviceByDisplayID(cgdevice, out gdevice, false);

                if (status != OSStatus.NoError)
                    throw new MacOSException(status, "DMGetGDeviceByDisplayID failed.");

                myAGLPixelFormat = Agl.aglChoosePixelFormat(ref gdevice, 1, aglAttributes.ToArray());

                Agl.AglError err = Agl.GetError();

                if (err == Agl.AglError.BadPixelFormat)
                {
                    Debug.Print("Failed to create full screen pixel format.");
                    Debug.Print("Trying again to create a non-fullscreen pixel format.");

                    CreateContext(mode, carbonWindow, shareContextRef, false);
                    return;
                }
            }

            else
            {
                myAGLPixelFormat = Agl.aglChoosePixelFormat(IntPtr.Zero, 0, aglAttributes.ToArray());

                MyAGLReportError("aglChoosePixelFormat");
            }

            Debug.Print("Creating AGL context.  Sharing with {0}", shareContextRef);

            // create the context and share it with the share reference.
            Handle = new ContextHandle(Agl.aglCreateContext(myAGLPixelFormat, shareContextRef));
            MyAGLReportError("aglCreateContext");

            // Free the pixel format from memory.
            Agl.aglDestroyPixelFormat(myAGLPixelFormat);
            MyAGLReportError("aglDestroyPixelFormat");

            Debug.Print("IsControl: {0}", carbonWindow.IsControl);

            SetDrawable(carbonWindow);
            SetBufferRect(carbonWindow);
            Update(carbonWindow);

            MakeCurrent(carbonWindow);

            Debug.Print("context: {0}", Handle.Handle);
        }

        private IntPtr GetQuartzDevice(CarbonWindowInfo carbonWindow)
        {
            IntPtr windowRef = carbonWindow.WindowRef;

            if (CarbonGLNative.WindowRefMap.ContainsKey(windowRef) == false)
                return IntPtr.Zero;

            WeakReference nativeRef = CarbonGLNative.WindowRefMap[windowRef];
            if (nativeRef.IsAlive == false)
                return IntPtr.Zero;

            CarbonGLNative window = nativeRef.Target as CarbonGLNative;

            if (window == null)
                return IntPtr.Zero;

            return QuartzDisplayDeviceDriver.HandleTo(window.TargetDisplayDevice);

        }

        void SetBufferRect(CarbonWindowInfo carbonWindow)
        {
            if (carbonWindow.IsControl == false)
                return;

            // Todo: See if there is a way around using WinForms.
            throw new NotImplementedException();
#if false
            System.Windows.Forms.Control ctrl = Control.FromHandle(carbonWindow.WindowRef);

            if (ctrl.TopLevelControl == null)
                return;

            Rect rect = API.GetControlBounds(carbonWindow.WindowRef);
            System.Windows.Forms.Form frm = (System.Windows.Forms.Form)ctrl.TopLevelControl;

            System.Drawing.Point loc = frm.PointToClient(ctrl.PointToScreen(System.Drawing.Point.Empty));

            rect.X = (short)loc.X;
            rect.Y = (short)loc.Y;

            Debug.Print("Setting buffer_rect for control.");
            Debug.Print("MacOS Coordinate Rect:   {0}", rect);

            rect.Y = (short)(ctrl.TopLevelControl.ClientSize.Height - rect.Y - rect.Height);
            Debug.Print("  AGL Coordinate Rect:   {0}", rect);

            int[] glrect = new int[4];

            glrect[0] = rect.X;
            glrect[1] = rect.Y;
            glrect[2] = rect.Width;
            glrect[3] = rect.Height;

            Agl.aglSetInteger(Handle.Handle, Agl.ParameterNames.AGL_BUFFER_RECT, glrect);
            MyAGLReportError("aglSetInteger");

            Agl.aglEnable(Handle.Handle, Agl.ParameterNames.AGL_BUFFER_RECT);
            MyAGLReportError("aglEnable");
#endif
        }
        void SetDrawable(CarbonWindowInfo carbonWindow)
        {
            IntPtr windowPort = GetWindowPortForWindowInfo(carbonWindow);
            //Debug.Print("Setting drawable for context {0} to window port: {1}", Handle.Handle, windowPort);

            Agl.aglSetDrawable(Handle.Handle, windowPort);

            MyAGLReportError("aglSetDrawable");

        }

        private static IntPtr GetWindowPortForWindowInfo(CarbonWindowInfo carbonWindow)
        {
            IntPtr windowPort;
            if (carbonWindow.IsControl)
            {
                IntPtr controlOwner = API.GetControlOwner(carbonWindow.WindowRef);

                windowPort = API.GetWindowPort(controlOwner);
            }

            else
                windowPort = API.GetWindowPort(carbonWindow.WindowRef);

            return windowPort;
        }
        public override void Update(IWindowInfo window)
        {
            CarbonWindowInfo carbonWindow = (CarbonWindowInfo)window;

            if (carbonWindow.GoFullScreenHack)
            {
                carbonWindow.GoFullScreenHack = false;
                CarbonGLNative wind = GetCarbonWindow(carbonWindow);

                if (wind != null)
                    wind.SetFullscreen(this);
                else
                    Debug.Print("Could not find window!");

                return;
            }

            else if (carbonWindow.GoWindowedHack)
            {
                carbonWindow.GoWindowedHack = false;
                CarbonGLNative wind = GetCarbonWindow(carbonWindow);

                if (wind != null)
                    wind.UnsetFullscreen(this);
                else
                    Debug.Print("Could not find window!");

            }

            if (mIsFullscreen)
                return;

            SetDrawable(carbonWindow);
            SetBufferRect(carbonWindow);

            Agl.aglUpdateContext(Handle.Handle);
        }

        private CarbonGLNative GetCarbonWindow(CarbonWindowInfo carbonWindow)
        {
            WeakReference r = CarbonGLNative.WindowRefMap[carbonWindow.WindowRef];

            if (r.IsAlive)
            {
                return (CarbonGLNative)r.Target;
            }

            else
                return null;
        }

        void MyAGLReportError(string function)
        {
            Agl.AglError err = Agl.GetError();

            if (err != Agl.AglError.NoError)
                throw new MacOSException((OSStatus)err, string.Format("AGL Error from function {0}: {1}  {2}", function, err, Agl.ErrorString(err)));
        }

        bool firstFullScreen = false;

        internal void SetFullScreen(CarbonWindowInfo info, out int width, out int height)
        {
            CarbonGLNative wind = GetCarbonWindow(info);

            Debug.Print("Switching to full screen {0}x{1} on context {2}", wind.TargetDisplayDevice.Width, wind.TargetDisplayDevice.Height, Handle.Handle);

            CG.DisplayCapture(GetQuartzDevice(info));
            Agl.aglSetFullScreen(Handle.Handle, wind.TargetDisplayDevice.Width, wind.TargetDisplayDevice.Height, 0, 0);
            MakeCurrent(info);

            width = wind.TargetDisplayDevice.Width;
            height = wind.TargetDisplayDevice.Height;

            // This is a weird hack to workaround a bug where the first time a context
            // is made fullscreen, we just end up with a blank screen.  So we undo it as fullscreen
            // and redo it as fullscreen.
            if (firstFullScreen == false)
            {
                firstFullScreen = true;
                UnsetFullScreen(info);
                SetFullScreen(info, out width, out height);
            }

            mIsFullscreen = true;
        }
        internal void UnsetFullScreen(CarbonWindowInfo windowInfo)
        {
            Debug.Print("Unsetting AGL fullscreen.");
            Agl.aglSetDrawable(Handle.Handle, IntPtr.Zero);
            Agl.aglUpdateContext(Handle.Handle);

            CG.DisplayRelease(GetQuartzDevice(windowInfo));
            Debug.Print("Resetting drawable.");
            SetDrawable(windowInfo);

            mIsFullscreen = false;
        }

        #region IGraphicsContext Members

        bool firstSwap = false;
        public override void SwapBuffers()
        {
            // this is part of the hack to avoid dropping the first frame when
            // using multiple GLControls.
            if (firstSwap == false && carbonWindow.IsControl)
            {
                Debug.WriteLine("--> Resetting drawable. <--");
                firstSwap = true;
                SetDrawable(carbonWindow);
                Update(carbonWindow);
            }

            Agl.aglSwapBuffers(Handle.Handle);
            MyAGLReportError("aglSwapBuffers");
        }

        public override void MakeCurrent(IWindowInfo window)
        {
            if (Agl.aglSetCurrentContext(Handle.Handle) == false)
                MyAGLReportError("aglSetCurrentContext");
        }

        public override bool IsCurrent
        {
            get { return (Handle.Handle == Agl.aglGetCurrentContext()); }
        }

        public override bool VSync
        {
            get { return mVSync; }
            set
            {
                int intVal = value ? 1 : 0;

                Agl.aglSetInteger(Handle.Handle, Agl.ParameterNames.AGL_SWAP_INTERVAL, ref intVal);

                mVSync = value;
            }
        }

        #endregion

        #region IDisposable Members

        ~AglContext()
        {
            Dispose(false);
        }

        public override void Dispose()
        {
            Dispose(true);
        }

        void Dispose(bool disposing)
        {
            if (IsDisposed || Handle.Handle == IntPtr.Zero)
                return;

            Debug.Print("Disposing of AGL context.");
            Agl.aglSetCurrentContext(IntPtr.Zero);

            //Debug.Print("Setting drawable to null for context {0}.", Handle.Handle);
            //Agl.aglSetDrawable(Handle.Handle, IntPtr.Zero);

            // I do not know MacOS allows us to destroy a context from a separate thread,
            // like the finalizer thread.  It's untested, but worst case is probably
            // an exception on application exit, which would be logged to the console.
            Debug.Print("Destroying context");
            if (Agl.aglDestroyContext(Handle.Handle) == true)
            {
                Debug.Print("Context destruction completed successfully.");
                Handle = ContextHandle.Zero;
                return;
            }

            // failed to destroy context.
            Debug.WriteLine("Failed to destroy context.");
            Debug.WriteLine(Agl.ErrorString(Agl.GetError()));

            // don't throw an exception from the finalizer thread.
            if (disposing)
            {
                throw new MacOSException((OSStatus)Agl.GetError(), Agl.ErrorString(Agl.GetError()));
            }

            IsDisposed = true;
        }

        #endregion

        #region IGraphicsContextInternal Members

        private const string Library = "libdl.dylib";

        [DllImport(Library, EntryPoint = "NSIsSymbolNameDefined")]
        private static extern bool NSIsSymbolNameDefined(string s);
        [DllImport(Library, EntryPoint = "NSLookupAndBindSymbol")]
        private static extern IntPtr NSLookupAndBindSymbol(string s);
        [DllImport(Library, EntryPoint = "NSAddressOfSymbol")]
        private static extern IntPtr NSAddressOfSymbol(IntPtr symbol);

        public override IntPtr GetAddress(string function)
        {
            string fname = "_" + function;
            if (!NSIsSymbolNameDefined(fname))
                return IntPtr.Zero;

            IntPtr symbol = NSLookupAndBindSymbol(fname);
            if (symbol != IntPtr.Zero)
                symbol = NSAddressOfSymbol(symbol);

            return symbol;
        }

        #endregion
    }
}


text:
<?php

namespace Lthrt\ContactBundle\Form\Combo\Listener;

use Lthrt\ContactBundle\Form\Combo\ComboTrait\AddCityTrait;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

class CitySubscriber implements EventSubscriberInterface
{
    use AddCityTrait;

    private $cityRep;
    private $options;

    public function __construct($cityRep, $options)
    {
        $this->cityRep = $cityRep;
        $this->options = $options;
    }

    public static function getSubscribedEvents()
    {
        return [FormEvents::POST_SUBMIT => 'postSubmit'];
    }

    public function postSubmitData(FormEvent $event)
    {
        $state = $event->getData();
        $form  = $event->getForm();

        $form->remove('city');
        $this->addCity($form, $this->options);
    }
}


text:
package restaurant.gui;

import restaurant.CookAgent;
import restaurant.CustomerAgent;
import restaurant.MarketAgent;
import restaurant.WaiterAgent;

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
/**
 * Main GUI class.
 * Contains the main frame and subsequent panels
 */
public class RestaurantGui extends JFrame implements ActionListener {
    /* The GUI has two frames, the control frame (in variable gui)
     * and the animation frame, (in variable animationFrame within gui)
     */
	//JFrame animationFrame = new JFrame("Restaurant Animation");
	AnimationPanel animationPanel = new AnimationPanel();

    /* restPanel holds 2 panels
     * 1) the staff listing, menu, and lists of current customers all constructed
     *    in RestaurantPanel()
     * 2) the infoPanel about the clicked Customer (created just below)
     */
    private RestaurantPanel restPanel = new RestaurantPanel(this);

    /* infoPanel holds information about the clicked customer, if there is one*/
    private JPanel infoPanel;
    private JLabel infoLabel; //part of infoPanel
    private JLabel stockLabel;
    private JCheckBox stateCB;//part of infoLabel
    private JButton requestbreak ;

    private final int Restaurantx = 550 ;

    private Object currentPerson;/* Holds the agent that the info is about.
    								Seems like a hack */

    /**
     * Constructor for RestaurantGui class.
     * Sets up all the gui components.
     */
    public RestaurantGui() {
        int WINDOWX = 750;
        int WINDOWY = 750;

        // Fix to make it all in one window
        Dimension aniDim = new Dimension(Restaurantx, (int) (WINDOWY * .5));
        animationPanel.setPreferredSize(aniDim);
        animationPanel.setMinimumSize(aniDim);
        animationPanel.setMaximumSize(aniDim);
        animationPanel.setBorder(BorderFactory.createTitledBorder("Simulation"));
        add(animationPanel) ;

    	setBounds(50, 50, WINDOWX, WINDOWY);

        setLayout(new BoxLayout((Container) getContentPane(),
        		BoxLayout.Y_AXIS));

        Dimension restDim = new Dimension(WINDOWX, (int) (WINDOWY * .325));
        restPanel.setPreferredSize(restDim);
        restPanel.setMinimumSize(restDim);
        restPanel.setMaximumSize(restDim);
        add(restPanel);

        // Now, setup the info panel
        Dimension infoDim = new Dimension(WINDOWX, (int) (WINDOWY * .175));
        infoPanel = new JPanel();
        infoPanel.setPreferredSize(infoDim);
        infoPanel.setMinimumSize(infoDim);
        infoPanel.setMaximumSize(infoDim);
        infoPanel.setBorder(BorderFactory.createTitledBorder("Information"));

        stateCB = new JCheckBox();
        stateCB.setVisible(false);
        stateCB.addActionListener(this);

        infoPanel.setLayout(new GridLayout(2, 4, 5, 5));

        infoLabel = new JLabel();
        infoLabel.setText("
Click Add to make customers and waiters
");
        stockLabel = new JLabel();
        stockLabel.setText("Steak: 		, Chicken: 	, Pizza: 		, Salad:	");
        stockLabel.setSize(getMaximumSize());
        stockLabel.setSize(getPreferredSize());
        infoPanel.add(infoLabel);
        infoPanel.add(stockLabel);
        stockLabel.setVisible(false);
        infoPanel.add(stateCB);
        requestbreak = new JButton("Ask for Break")  ;
        requestbreak.setVisible(false);
        requestbreak.addActionListener(this);
        infoPanel.add(requestbreak);
        add(infoPanel);
    }
    /**
     * updateInfoPanel() takes the given customer (or, for v3, Host) object and
     * changes the information panel to hold that person's info.
     *
     * @param person customer (or waiter) object
     */
    public void updateInfoPanel(Object person) {
        stateCB.setVisible(true);
        stockLabel.setVisible(false) ;
        currentPerson = person;

        if (person instanceof CustomerAgent) {
        	requestbreak.setVisible(false);
            CustomerAgent customer = (CustomerAgent) person;
            stateCB.setText("Hungry?");
          //Should checkmark be there?
            stateCB.setSelected(customer.getGui().isHungry());
          //Is customer hungry? Hack. Should ask customerGui
            stateCB.setEnabled(!customer.getGui().isHungry());
          // Hack. Should ask customerGui
            infoLabel.setText(
               "
     Name: " + customer.getName() + "
");
        }
        else if (person instanceof WaiterAgent) {
        	requestbreak.setVisible(true);
            WaiterAgent waiter = (WaiterAgent) person;
            if(waiter.isonbreak())
            	requestbreak.setText("Return to Work");
            else
            	requestbreak.setText("Ask for Break") ;
            stateCB.setText("On Break?");
           //Should checkmark be there?
            stateCB.setEnabled(false);
            stateCB.setSelected(waiter.isonbreak()) ;
            infoLabel.setText(
               "
     Name: " + waiter.getName() + "
");
        }
        else if (person instanceof CookAgent) {
        	stockLabel.setVisible(true) ;
        	CookAgent cook = (CookAgent) person;
        	stockLabel.setText("Steak: 		"+cook.getFood("Steak")+", Chicken: 	"
        			+cook.getFood("Chicken")+", Pizza: 		"+cook.getFood("Pizza")+", Salad:	"+
        			cook.getFood("Salad"));
        	requestbreak.setVisible(false);
            stateCB.setVisible(false);
            infoLabel.setText(
               "
     Name: " + cook.getName() + "
");
        }
        else if (person instanceof MarketAgent) {
        	stockLabel.setVisible(true) ;
        	MarketAgent market = (MarketAgent) person;
        	stockLabel.setText("Steak: 		"+market.getFood("Steak")+", Chicken: 	"
        			+market.getFood("Chicken")+", Pizza: 		"+market.getFood("Pizza")+", Salad:	"+
        			market.getFood("Salad"));
        	requestbreak.setVisible(false);
            stateCB.setVisible(false);
            infoLabel.setText(
               "
     Name: " + market.getName() + "
");
        }
        infoPanel.validate();
    }
    /**
     * Action listener method that reacts to the checkbox being clicked;
     * If it's the customer's checkbox, it will make him hungry
     * For v3, it will propose a break for the waiter.
     */
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == stateCB) {
            if (currentPerson instanceof CustomerAgent) {
                CustomerAgent c = (CustomerAgent) currentPerson;
                c.getGui().resetHungry();
                stateCB.setEnabled(false);
            }
            else if (currentPerson instanceof WaiterAgent) {
                WaiterAgent w = (WaiterAgent) currentPerson;
                w.setonbreak(stateCB.isSelected());
                w.gethost().msgNewWaiter();
            }
        }
        else if(e.getSource() == requestbreak) {
        	WaiterAgent w = (WaiterAgent) currentPerson ;
        	if(!w.isonbreak())
        		w.msgBreakButton();
        	else
        		w.msgGoBackToWork();
        }
    }
    /**
     * Message sent from a customer gui to enable that customer's
     * "I'm hungry" checkbox.
     *
     * @param c reference to the customer
     */
    public void setCustomerEnabled(CustomerAgent c) {
        if (currentPerson instanceof CustomerAgent) {
            CustomerAgent cust = (CustomerAgent) currentPerson;
            if (c.equals(cust)) {
                stateCB.setEnabled(true);
                stateCB.setSelected(false);
            }
        }
    }
    /**
     * Main routine to get gui started
     */
    public static void main(String[] args) {
        RestaurantGui gui = new RestaurantGui();
        gui.setTitle("csci201 Restaurant");
        gui.setVisible(true);
        gui.setResizable(false);
        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}


text:
package com.graphhopper.routing.util.countryrules;

import com.graphhopper.reader.ReaderWay;
import com.graphhopper.routing.ev.RoadAccess;
import com.graphhopper.routing.ev.Toll;
import com.graphhopper.routing.util.TransportationMode;

/**
 * GraphHopper uses country rules to adjust the routing behavior based on the country an edge is located in
 */
public interface CountryRule {
    default double getMaxSpeed(ReaderWay readerWay, TransportationMode transportationMode, double currentMaxSpeed) {
        return currentMaxSpeed;
    }

    default RoadAccess getAccess(ReaderWay readerWay, TransportationMode transportationMode, RoadAccess currentRoadAccess) {
        return currentRoadAccess;
    }

    default Toll getToll(ReaderWay readerWay, Toll currentToll) {
        return currentToll;
    }
}


text: installBiocDataPackage.sh "snplocs.hsapiens.dbsnp155.grch38-0.99.22"


text:
package org.apache.harmony.test.func.api.java.beans.beans;

import java.beans.beancontext.BeanContextSupport;

/**
 */
public class SimpleBeanContext extends BeanContextSupport {
    ClassLoader classLoader;
    Object      bean;

    public boolean add(Object targetChild) {
        classLoader = targetChild.getClass().getClassLoader();
        bean = targetChild;
        return super.add(targetChild);
    }
}


text:
package org.mbari.vars.ui.javafx.cbpanel;

import javafx.application.Platform;
import javafx.collections.ListChangeListener;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.Pane;
import org.mbari.vars.core.EventBus;
import org.mbari.vars.ui.UIToolBox;
import org.mbari.vars.ui.messages.*;
import org.mbari.vars.services.ConceptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.prefs.Preferences;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author Brian Schlining
 * @since 2017-06-13T14:13:00
 */
public class ConceptButtonPaneController {
    protected Pane pane;
    private final Preferences panePreferences;
    private final UIToolBox toolBox;

    private final EventBus eventBus;
    private final ResourceBundle i18n;
    private final DragPaneDecorator dragPaneDecorator;

    private static final String PREF_BUTTON_NAME = "name";
    private static final String PREF_BUTTON_ORDER = "order";
    private static final String BAD_KEY = "__unknown__";

    private final Logger log = LoggerFactory.getLogger(getClass());

    /**
     *
     * @param toolBox
     * @param panePreferences Holds the button preferences for this tab
     */
    public ConceptButtonPaneController(UIToolBox toolBox,
                                       Preferences panePreferences) {
        this.toolBox = toolBox;
        this.panePreferences = panePreferences;
        this.eventBus = toolBox.getEventBus();
        this.i18n = toolBox.getI18nBundle();

        dragPaneDecorator = new DragPaneDecorator(toolBox);

    }

    public void setLocked(boolean locked) {
        dragPaneDecorator.setLocked(locked);
    }

    public boolean isLocked() {
        return dragPaneDecorator.isLocked();
    }

    public Pane getPane() {
        if (pane == null) {
            pane = new FlowPane();
            pane.setUserData(this);
            pane.setPrefSize(800, 250);
            dragPaneDecorator.decorate(pane);
            loadButtonsFromPreferences();
            // Save everything when a new button is added or removed
            pane.getChildren()
                    .addListener((ListChangeListener<Node>) c ->  saveButtonsToPreferences());
        }
        return pane;
    }

    public DragPaneDecorator getDragPaneDecorator() {
        return dragPaneDecorator;
    }

    protected void loadButtonsFromPreferences() {
        ConceptButtonFactory factory =
                new ConceptButtonFactory(toolBox);
        var eventBus = toolBox.getEventBus();
        // Load async so we don't block ui
        toolBox.getExecutorService().submit(() -> {
            try {
                // NOTE: Don't add any progress bar. That's done in ConceptButtonPanesController
                List<Button> buttons = Arrays.stream(panePreferences.childrenNames())
                        .map(nodeName -> {
                            Preferences buttonPreferences = panePreferences.node(nodeName);
                            String conceptName = buttonPreferences.get(PREF_BUTTON_NAME, BAD_KEY);
                            int order = buttonPreferences.getInt(PREF_BUTTON_ORDER, 0);
                            Button button = factory.build(conceptName);
                            return new ButtonPref(button, order);
                        })
                        .filter(buttonPref -> !buttonPref.getButton().getText().equals(BAD_KEY))
                        .sorted(Comparator.comparingInt(ButtonPref::getOrder))
                        .map(ButtonPref::getButton)
                        .collect(Collectors.toList());
                Platform.runLater(() -> getPane().getChildren().addAll(buttons));
            }
            catch (Exception e) {
                eventBus.send(new ShowNonfatalErrorAlert(
                        i18n.getString("cbpanel.alert.prefsfail.load.title"),
                        i18n.getString("cbpanel.alert.prefsfail.load.header"),
                        i18n.getString("cbpanel.alert.prefsfail.load.content"),
                        e));
            }
        });

    }

    /**
     * When removing the tab pane
     */
    private void saveButtonsToPreferences() {
        List<Button> buttons = getPane().getChildren()
                .stream()
                .filter(n -> n.getUserData().toString().equalsIgnoreCase(ConceptButtonFactory.USERDATA))
                .map(n -> (Button) n)
                .collect(Collectors.toList());

        // Store existing buttons
        IntStream.range(0, buttons.size())
                .forEach(i -> {
                    Button button = buttons.get(i);
                    String name = button.getText();
                    Preferences prefs = panePreferences.node(name);
                    prefs.putInt(PREF_BUTTON_ORDER, i);
                    prefs.put(PREF_BUTTON_NAME, name);
                });

        // Remove non-longer used buttons
        try {
            // Arrays.asList returns unmodifiable list. Need to create ArrayList.
            List<String> storedButtons = new ArrayList<>(Arrays.asList(panePreferences.childrenNames()));
            List<String> existingButtons = buttons.stream()
                    .map(Button::getText)
                    .collect(Collectors.toList());
            storedButtons.removeAll(existingButtons);
            storedButtons.forEach(s -> {
                try {
                    panePreferences.node(s).removeNode();
                }
                catch (Exception e) {
                    log.error("Failed to delete concept button named '" + s + "'.", e);
                }
            });
        }
        catch (Exception e) {
            eventBus.send(new ShowNonfatalErrorAlert(
                    i18n.getString("cbpanel.alert.prefsfail.save.title"),
                    i18n.getString("cbpanel.alert.prefsfail.save.header"),
                    i18n.getString("cbpanel.alert.prefsfail.save.content"),
                    e));
        }

    }
}

class ButtonPref {

    private final Button button;
    private final int order;

    ButtonPref(Button button, int order) {
        this.button = button;
        this.order = order;
    }

    Button getButton() {
        return button;
    }

    int getOrder() {
        return order;
    }
}


text:
package org.dcdnt.model;

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

import heronarts.lx.model.LXAbstractFixture;
import heronarts.lx.model.LXModel;
import heronarts.lx.model.LXPoint;
import heronarts.lx.transform.LXTransform;

public class Tree extends LXModel {

	public enum TreeType {
		SIX_ARM, EIGHT_ARM, TWELVE_ARM
	}

	/**
	 * Global x-position of center of top of Tree
	 */
	public final float x;

	/**
	 * Global y-position of center of top of Tree
	 */
	public final float y;

	/**
	 * Global z-position of center of top of Tree
	 */
	public final float z;

	/**
	 * List of LEDBars on the tree
	 */
	public final List<LEDBar> ledBars;

	public final List<TreeArm> treeArms;

	Tree(TreeType type, float x, float y, float z, String pusherMac, int stripNo) {
		super(new Fixture(type, x, y, z, pusherMac, stripNo));
		Fixture f = (Fixture) this.fixtures.get(0);
		this.x = x;
		this.y = y;
		this.z = z;
		this.ledBars = Collections.unmodifiableList(f.ledBars);
		this.treeArms = Collections.unmodifiableList(f.treeArms);
	}

	private static class Fixture extends LXAbstractFixture {
		final List<LEDBar> ledBars;
		final List<TreeArm> treeArms;

		Fixture(TreeType type, float x, float y, float z, String pusherMac,
				int stripNo) {
			LXTransform transform = new LXTransform();
			transform.translate(x, y, z);
			this.ledBars = new ArrayList<LEDBar>();
			this.treeArms = new ArrayList<TreeArm>();
			int pixelNo = 0;
			float spaceBetweenLeds;
			int armLength;
			switch (type) {
			case SIX_ARM:
				armLength = 100;
				spaceBetweenLeds = (float) (armLength / 4.0);
				for (int armNumber = 0; armNumber < 6; armNumber++) {
					ArrayList<LEDBar> thisArmsBars = new ArrayList<LEDBar>();
					float theta = (float) (360.0 / armNumber);
					thisArmsBars.add(new LEDBar(transform,
							spaceBetweenLeds * 1, theta, pusherMac, stripNo,
							pixelNo++));
					thisArmsBars.add(new LEDBar(transform,
							spaceBetweenLeds * 3, theta, pusherMac, stripNo,
							pixelNo++));
					thisArmsBars.add(new LEDBar(transform,
							spaceBetweenLeds * 2, theta, pusherMac, stripNo,
							pixelNo++));
					thisArmsBars.add(new LEDBar(transform,
							spaceBetweenLeds * 0, theta, pusherMac, stripNo,
							pixelNo++));
					this.ledBars.addAll(thisArmsBars);
					this.treeArms.add(new TreeArm(armNumber, thisArmsBars,
							theta));
				}

				break;
			case EIGHT_ARM:
				armLength = 100;
				spaceBetweenLeds = (float) (armLength / 3.0);
				for (int armNumber = 0; armNumber < 8; armNumber++) {
					ArrayList<LEDBar> thisArmsBars = new ArrayList<LEDBar>();
					float theta = (float) (360.0 / armNumber);
					thisArmsBars.add(new LEDBar(transform,
							spaceBetweenLeds * 0, 360 / armNumber, pusherMac,
							stripNo, pixelNo++));
					thisArmsBars.add(new LEDBar(transform,
							spaceBetweenLeds * 2, 360 / armNumber, pusherMac,
							stripNo, pixelNo++));
					thisArmsBars.add(new LEDBar(transform,
							spaceBetweenLeds * 1, 360 / armNumber, pusherMac,
							stripNo, pixelNo++));
					this.ledBars.addAll(thisArmsBars);
					this.treeArms.add(new TreeArm(armNumber, thisArmsBars,
							theta));
				}
				break;
			case TWELVE_ARM:
				armLength = 100;
				spaceBetweenLeds = (float) (armLength / 2.0);
				for (int armNumber = 0; armNumber < 12; armNumber++) {
					ArrayList<LEDBar> thisArmsBars = new ArrayList<LEDBar>();
					float theta = (float) (360.0 / armNumber);
					thisArmsBars.add(new LEDBar(transform,
							spaceBetweenLeds * 0, 360 / armNumber, pusherMac,
							stripNo, pixelNo++));
					thisArmsBars.add(new LEDBar(transform,
							spaceBetweenLeds * 1, 360 / armNumber, pusherMac,
							stripNo, pixelNo++));
					this.ledBars.addAll(thisArmsBars);
					this.treeArms.add(new TreeArm(armNumber, thisArmsBars,
							theta));
				}
				break;
			default:
				break;
			}

			for (LEDBar bar : this.ledBars) {
				for (LXPoint p : bar.points) {
					this.points.add(p);
				}
			}
		}
	}
}


text:
import { population } from "../src/population";

let testPopulation: { fieldA: number | string; fieldB: number; fieldC: number }[] = [
    { fieldA: 10, fieldB: 100, fieldC: 1000 },
    { fieldA: 20, fieldB: 200, fieldC: 2000 },
    { fieldA: 30, fieldB: 300, fieldC: 3000 },
    { fieldA: "Peter", fieldB: 400, fieldC: 4000 }
]

let testPrimativePopulation = [10, 20, 30];
let testStringPopulation = ['bryan', 'sam', 'roger'];
let testMixPopulation = ['roger', 10, 'peter', 20, 30];

describe("Testing population tool", () => {

    let testResultArray = (array: Array<number>) => {
        it("Result Length is 3", () => expect(array.length).toEqual(3));
        it("First Value 10", () => expect(array[0]).toEqual(10));
        it("First Value 20", () => expect(array[1]).toEqual(20));
        it("First Value 30", () => expect(array[2]).toEqual(30));
    }

    it("Input length is 4", () => expect(testPopulation.length).toEqual(4));

    describe("Object Tests", () => {
        testResultArray(population(testPopulation, "fieldA"));
    });
    describe("Primative Tests", () => {
        testResultArray(population(testPrimativePopulation, null));
        testResultArray(population(testMixPopulation, null));

        it("Non numeric array length = 0", () => expect(population(testStringPopulation, null).length).toEqual(0));
    });
    describe("Mean failure check", () => {
        let primArrayMixed = [10, 'a', 12, 'b', '13'];
        let primArrayMixedPop = population(primArrayMixed, null);
        it("Mixed Array Length = 3", () => expect(primArrayMixedPop.length).toEqual(3));
        it("Mixed Array [0] ==> 10", () => expect(primArrayMixedPop[0]).toEqual(10));
        it("Mixed Array [1] ==> 12", () => expect(primArrayMixedPop[1]).toEqual(12));
        it("Mixed Array [2] ==> 13", () => expect(primArrayMixedPop[2]).toEqual(13));
    });
});


text:
package org.pyknic.ck4j.visitors.measures.interfaces;

import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.generic.ConstantPoolGen;
import org.pyknic.ck4j.metrics.CKMetricsBuilderMgr;

/**
 *
 * @author Emil Forslund
 */
public abstract class Metric {

    private final JavaClass visited;
    private final CKMetricsBuilderMgr mgr;
    private final ConstantPoolGen constants;

    public Metric(JavaClass visited, CKMetricsBuilderMgr mgr) {
        this.visited = visited;
        this.mgr = mgr;
        this.constants = new ConstantPoolGen(visited.getConstantPool());
    }

    protected final JavaClass visited() {
        return visited;
    }

    protected final CKMetricsBuilderMgr mgr() {
        return mgr;
    }

    protected final ConstantPoolGen constants() {
        return constants;
    }

    public abstract int getResult();
}


text:
package edu.emory.cci.aiw.cvrg.eureka.services.resource;

import com.google.inject.Inject;
import edu.emory.cci.aiw.cvrg.eureka.common.comm.AppProperties;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import edu.emory.cci.aiw.cvrg.eureka.common.comm.AppPropertiesModes;
import edu.emory.cci.aiw.cvrg.eureka.common.comm.AppPropertiesLinks;
import edu.emory.cci.aiw.cvrg.eureka.common.comm.AppPropertiesRegistration;
import edu.emory.cci.aiw.cvrg.eureka.services.config.ServiceProperties;
/**
 *
 * @author Miao Ai
 */

@Path("/appproperties")
@Produces(MediaType.APPLICATION_JSON)
public class AppPropertyResource {
	private final ServiceProperties serviceProperties;

	@Inject
	public AppPropertyResource(ServiceProperties inServiceProperties){
		this.serviceProperties= inServiceProperties;
	}

	@GET
	public AppProperties getAppProperties() {
		return this.serviceProperties.getAppProperties();
	}

	@GET
	@Path("/modes")
	public AppPropertiesModes getAppPropertiesModes() {
		return this.serviceProperties.getAppPropertiesModes();
	}

	@GET
	@Path("/links")
	public AppPropertiesLinks getAppPropertiesLinks() {
		return this.serviceProperties.getAppPropertiesLinks();
	}

	@GET
	@Path("/registration")
	public AppPropertiesRegistration getAppPropertiesRegistration() {
		return this.serviceProperties.getAppPropertiesRegistration();
	}
}


text:
struct entity_sprite {
    const struct tileset *tileset;

    int tile;
};

#endif


text:
package com.diandi.demo.ui.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;

import com.diandi.demo.R;
import com.diandi.demo.adapter.NewFriendAdapter;
import com.diandi.demo.widget.HeaderLayout;
import com.diandi.demo.widget.dialog.DialogTips;

import cn.bmob.im.bean.BmobInvitation;
import cn.bmob.im.db.BmobDB;

public class NewFriendActivity extends ActivityBase implements OnItemLongClickListener {

    ListView listview;
    NewFriendAdapter adapter;
    String from = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        findView();
        initView();
    }

    void initView() {
        initTopBarForBoth("新朋友", R.drawable.icon_clear_selector, new HeaderLayout.onRightImageButtonClickListener() {
            @Override
            public void onClick() {
                DialogTips dialog = new DialogTips(NewFriendActivity.this, "提示", "删除所有好友请求", "确定", true, true);
                // 设置成功事件
                dialog.SetOnSuccessListener(new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface, int userId) {
                        deleteAllInvite();
                        adapter.removeAll();
                    }
                });
                // 显示确认对话框
                dialog.show();
                dialog = null;

            }
        });
        from = getIntent().getStringExtra("from");
        adapter = new NewFriendAdapter(this, BmobDB.create(this).queryBmobInviteList());
        listview.setAdapter(adapter);
        if (from == null) {//若来自通知栏的点击,则定位到最后一条
            listview.setSelection(adapter.getCount());
        }
        bindEvent();
    }

    @Override
    void findView() {
        setContentView(R.layout.activity_new_friend);
        listview = (ListView) findViewById(R.id.list_newfriend);

    }

    @Override
    void bindEvent() {
        listview.setOnItemLongClickListener(this);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position,
                                   long arg3) {
        BmobInvitation invite = adapter.getItem(position);
        showDeleteDialog(position, invite);
        return true;
    }

    public void showDeleteDialog(final int position, final BmobInvitation invite) {
        DialogTips dialog = new DialogTips(this, invite.getFromname(), "删除好友请求", "确定", true, true);
        // 设置成功事件
        dialog.SetOnSuccessListener(new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int userId) {
                deleteInvite(position, invite);
            }
        });
        // 显示确认对话框
        dialog.show();
        dialog = null;
    }

    /**
     * 删除请求
     * deleteRecent
     *
     * @param @param recent
     * @return void
     * @throws
     */
    private void deleteInvite(int position, BmobInvitation invite) {
        adapter.remove(position);
        BmobDB.create(this).deleteInviteMsg(invite.getFromid(), Long.toString(invite.getTime()));
    }

    private void deleteAllInvite() {
        for (BmobInvitation invitation : adapter.getList()) {
            BmobDB.create(this).deleteInviteMsg(invitation.getFromid(), Long.toString(invitation.getTime()));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (from == null) {
            startAnimActivity(MainActivity.class);
        }
    }

}


text:
<?php

class FirstMigrationSettings extends CakeMigration {

/**
 * Migration description
 *
 * @var string
 * @access public
 */
	public $description = '';

/**
 * Actions to be performed
 *
 * @var array $migration
 * @access public
 */
	public $migration = array(
		'up' => array(
			'create_table' => array(
				'languages' => array(
					'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'),
					'title' => array('type' => 'string', 'null' => false, 'default' => null, 'collate' => 'utf8_unicode_ci', 'charset' => 'utf8'),
					'native' => array('type' => 'string', 'null' => false, 'default' => null, 'collate' => 'utf8_unicode_ci', 'charset' => 'utf8'),
					'alias' => array('type' => 'string', 'null' => false, 'default' => null, 'collate' => 'utf8_unicode_ci', 'charset' => 'utf8'),
					'status' => array('type' => 'boolean', 'null' => false, 'default' => '1'),
					'weight' => array('type' => 'integer', 'null' => true, 'default' => null),
					'updated' => array('type' => 'datetime', 'null' => false, 'default' => null),
					'created' => array('type' => 'datetime', 'null' => false, 'default' => null),
					'indexes' => array(
						'PRIMARY' => array('column' => 'id', 'unique' => 1)
					),
					'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_unicode_ci', 'engine' => 'InnoDB')
				),
				'settings' => array(
					'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => 20, 'key' => 'primary'),
					'key' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 64, 'key' => 'unique', 'collate' => 'utf8_unicode_ci', 'charset' => 'utf8'),
					'value' => array('type' => 'text', 'null' => false, 'default' => null, 'collate' => 'utf8_unicode_ci', 'charset' => 'utf8'),
					'title' => array('type' => 'string', 'null' => false, 'default' => null, 'collate' => 'utf8_unicode_ci', 'charset' => 'utf8'),
					'description' => array('type' => 'string', 'null' => true, 'default' => null, 'collate' => 'utf8_unicode_ci', 'charset' => 'utf8'),
					'input_type' => array('type' => 'string', 'null' => false, 'default' => 'text', 'collate' => 'utf8_unicode_ci', 'charset' => 'utf8'),
					'editable' => array('type' => 'boolean', 'null' => false, 'default' => '1'),
					'weight' => array('type' => 'integer', 'null' => true, 'default' => null),
					'params' => array('type' => 'text', 'null' => false, 'default' => null, 'collate' => 'utf8_unicode_ci', 'charset' => 'utf8'),
					'indexes' => array(
						'PRIMARY' => array('column' => 'id', 'unique' => 1),
						'key' => array('column' => 'key', 'unique' => 1)
					),
					'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_unicode_ci', 'engine' => 'InnoDB')
				),
			),
		),
		'down' => array(
			'drop_table' => array(
				'languages', 'settings'
			),
		),
	);

/**
 * Before migration callback
 *
 * @param string $direction, up or down direction of migration process
 * @return boolean Should process continue
 * @access public
 */
	public function before($direction) {
		if ($direction == 'down') {
			return false;
		}
		return true;
	}

/**
 * After migration callback
 *
 * @param string $direction, up or down direction of migration process
 * @return boolean Should process continue
 * @access public
 */
	public function after($direction) {
		return true;
	}

}


text:
layout: post
title:  "Summary to AngularJS"
date:   2017-05-02 23:00:00 +0800
categories: blog
id: 36
---
*AngularJS* is a fairly complex front-end framework. There are a lot of things you need to pay attention to.Therefore it is necessary to give a summary to this framework and this post is devoted to this. One post is actually too short for the summary to this huge framework. Here we only summarize some of the pitfalls of this framework so that you can avoid these and explore more of it yourself later.

* Different versions are really different:

The newest version of *AngularJS* up to the writing of this post is version 1.6.4. Different versions are different even though they belong to the same version 1.x category. This means that the code that works for version 1.4 may not work for 1.6.  For example, you need to use `$locationProvider.hashPrefix("")` in order for routing to work in version 1.6 but you can ommit it in version 1.4 and 1.5. There are also other tricky things you need to care about.

For more information, please consult the *angularJS* website [angularjs][angularjs].

* Abstract the common things:

You may have a lot of common things among different pages in your project, for example the part of header and footer. One good way to make your project more concise and more maitainable is to make the common things become seperate templates and then include those templates in your pages. The following code shows this:

{% highlight javascript %}

{% endhighlight %}

* Making fully use of ngAnimate:

*ngAnimate* can be fully used to make your web pages more user-friendly. There two ways to utilize the *ngAnimate* module. One is the *CSS way* and the other is the *JavaScript way*. The example code of the *CSS way* is as follows:

{% highlight css %}
.index-page {
  position: absolute;
  width: 100%;
}
.index-page.ng-enter,
.index-page.ng-leave {
  transition: all .5s linear;
}
.index-page.ng-enter {
  left: 100%;
  opacity: 0;
}
.index-page.ng-enter-active {
  left: 0;
  opacity: 1;
}
.index-page.ng-leave {
  left: 0;
  opacity: 1;
}
.index-page.ng-leave-active {
  left: -100%;
  opacity: 0;
}
{% endhighlight %}

* Always seperate *Controllers*, *Services* and *Directives*:

It is a good practice to seperate controllers, Services and Directives, etc. and put them into different JavaScript files. An example of `index.html` file is as follows:

{% highlight html %}

{% endhighlight %}

[angularjs]: https://angularjs.org/


text:
module ApplicationHelper

  include ArticlesHelper
  include DisqusHelper

  def user_details(id)
    user = User.find_by_id(id)
    if user.present?
      user.display_name
    else
      'Anonymous'
    end
  end

  def resource_name
    :user
  end

  def privileged_visitor?
    current_user && current_user.is_privileged?
  end

  def static_page_path(page)
    "/#{StaticPage.url_for_me(page)}"
  end

  def is_in_static_page?(static_page_name)
    return params[:controller] == 'static_pages' &&
      params[:action] == 'show' &&
      params[:id] == StaticPage.url_for_me(static_page_name)
  end

  def resource
    @resource ||= User.new({karma: Karma.new})
  end

  def devise_mapping
    @devise_mapping ||= Devise.mappings[:user]
  end

  def current_projects
    Project.where(status: ["active", "Active"]).order('title ASC').order('commit_count DESC NULLS LAST')
  end

  def date_format(date)
    date.strftime("#{date.day.ordinalize} %b %Y")
  end

  DISPLAY_NAME = {
      'github' => 'GitHub',
      'gplus' => 'Google'
  }

  FA_ICON = {
      'github' => 'github-alt',
      'gplus' => 'google'
  }

  def social_button(provider, options={})
    provider = provider.downcase

    options[:url] = root_path unless options[:url].present?

    text = options[:text] || (options[:delete] ? 'Remove' : prefix)
    path = options[:delete] ? "/auth/destroy/#{current_user.authentications.where(provider: provider).first.id}" :
        "/auth/#{provider}?origin=#{CGI.escape(options[:url].gsub(/^[\/]*/, '/'))}"

    raw <<-HTML

         #{text} #{DISPLAY_NAME[provider]}

    HTML
  end

  def prefix
    action_name == 'new' ? 'with' : ''
  end

  def supported_third_parties
    %w{ github gplus }
  end

  def valid_email?(email)
    !!(email =~ /\A([^@\s]+)@((?:[\w]+\.)+[a-z]{2,})\z/i)
  end

  def custom_css_btn(text, icon_class, path, options={})
    s = ''
    options.each do |k, v|
      if v.is_a?(Hash)
        # Bryan: this extra level is to support data tags
        v.each do |key, value|
          s = %Q{#{s} #{k}-#{key.to_s.gsub(/_/, '-')}="#{value}"}
        end
      else
        s = %Q{#{s} #{k.to_s}="#{v}"}
      end
    end
    # Bryan: data-link-text attribute is used to find this element in the tests
    raw <<-HTML

    HTML
  end

  def awesome_text_field(f, object_name, options = {})
    awesome_text_method(:text_field, f, object_name, options)
  end

  def awesome_text_area(f, object_name, options = {})
    awesome_text_method(:text_area, f, object_name, options)
  end

  def awesome_text_method(method_name, f, object_name, options = {})
    errors = f.object.errors.messages[object_name]
    result = "
"
    result << f.label(object_name, options[:label_text], { class: 'control-label' }.merge(options[:label] || {}))
    result << f.send(method_name, object_name, { class: 'form-control' }.merge(options))
    result << "#{errors.join(', ')}" if errors.present?
    result << '
'
    clean_html result
  end
  private :awesome_text_method

  def active_if(condition)
    condition ? 'active' : nil
  end

  def active_if_controller_is(controller_name)
    active_if(params[:controller] == controller_name)
  end

  def shared_meta_keywords
    'AgileVentures, pair programming, crowdsourced learning'
  end

  def default_meta_description
    @default_meta_description ||= '' +
        'AgileVentures is a project incubator that stimulates and supports development of social innovations, ' +
        'open source and free software. We are also a community for learning and personal development with members ' +
        'from across the world with various levels of competence and experience in software development. We hold ' +
        'scrum meetings and pair programming sessions every day with participants from all time zones and on all ' +
        'levels. Come and join us.'
  end

  def present(model)
    yield(model.presenter)
  end
end


text:
@protocol WMLDITestProtocol1 <NSObject> @end

@interface WMLDITestProtocol1Implementation1 : NSObject <WMLDITestProtocol1> @end
@implementation WMLDITestProtocol1Implementation1 @end

@interface WMLDITestProtocol1Implementation2 : NSObject <WMLDITestProtocol1> @end
@implementation WMLDITestProtocol1Implementation2 @end

@protocol WMLDITestProtocol2 <NSObject> @end

@interface WMLDITestProtocol2Implementation1 : NSObject <WMLDITestProtocol2> @end
@implementation WMLDITestProtocol2Implementation1 @end

@protocol WMLDITestEmptyProtocol <NSObject> @end

@interface WMLSuperclass1 : NSObject @end
@implementation WMLSuperclass1 @end

@interface WMLSuperclass1Sublclass1 : WMLSuperclass1 @end
@implementation WMLSuperclass1Sublclass1 @end

@interface WMLSuperclass1Sublclass2 : WMLSuperclass1 @end
@implementation WMLSuperclass1Sublclass2 @end

@interface WMLSuperclass2 : NSObject @end
@implementation WMLSuperclass2 @end

@interface WMLSuperclass2Subclass1 : WMLSuperclass2 @end
@implementation WMLSuperclass2Subclass1 @end

@interface WMLSuperclass3 : NSObject @end
@implementation WMLSuperclass3 @end

@interface WMLSuperclass3Subclass1 : WMLSuperclass3 @end
@implementation WMLSuperclass3Subclass1 @end

@interface WMLSuperclass3Subclass1Grandsubclass1 : WMLSuperclass3Subclass1 @end
@implementation WMLSuperclass3Subclass1Grandsubclass1 @end

@interface WMLEmptySuperclass : NSObject @end
@implementation WMLEmptySuperclass @end

SpecBegin(WMLDIUnit)

describe(@"WMLDI", ^{
    context(@"protocols", ^{
        describe(@"enumerateClassesConformingToProtocol", ^{
            it(@"should enumerate through all classes implementing protocol", ^{
                NSMutableSet *conformingClasses = [NSMutableSet set];
                [[WMLDI di] enumerateClassesConformingToProtocol:@protocol(WMLDITestProtocol1) usingBlock:^(__unsafe_unretained Class class, BOOL *stop) {
                    [conformingClasses addObject:class];
                }];
                expect(conformingClasses).to.haveCountOf(2);
                expect(conformingClasses).to.contain([WMLDITestProtocol1Implementation1 class]);
                expect(conformingClasses).to.contain([WMLDITestProtocol1Implementation2 class]);
            });

            it(@"should not enumerate if protocol is not implemented by any class", ^{
                NSMutableSet *conformingClasses = [NSMutableSet set];
                [[WMLDI di] enumerateClassesConformingToProtocol:@protocol(WMLDITestEmptyProtocol) usingBlock:^(__unsafe_unretained Class class, BOOL *stop) {
                    [conformingClasses addObject:class];
                }];
                expect(conformingClasses).to.beEmpty();
            });
        });

        describe(@"enumerateClassesConformingToProtocol", ^{
            it(@"should return any class for protocol", ^{
                Class class = [[WMLDI di] anyClassImplementingProtocol:@protocol(WMLDITestProtocol2)];
                expect(class).to.equal([WMLDITestProtocol2Implementation1 class]);
            });

            it(@"should return nil for protocol not implemented by any classes", ^{
                Class class = [[WMLDI di] anyClassImplementingProtocol:@protocol(WMLDITestEmptyProtocol)];
                expect(class).to.beNil();
            });
        });
    });

    context(@"subclasses", ^{
        describe(@"enumerateSubclassesOfClass", ^{
            it(@"should include direct subclasses of a class", ^{
                NSMutableSet *subclasses = [NSMutableSet set];
                [[WMLDI di] enumerateSubclassesOfClass:[WMLSuperclass1 class] usingBlock:^(__unsafe_unretained Class class, BOOL *stop) {
                    [subclasses addObject:class];
                }];
                expect(subclasses).to.haveCountOf(2);
                expect(subclasses).to.contain([WMLSuperclass1Sublclass1 class]);
                expect(subclasses).to.contain([WMLSuperclass1Sublclass2 class]);
            });

            it(@"should include not direct subclasses", ^{
                NSMutableSet *subclasses = [NSMutableSet set];
                [[WMLDI di] enumerateSubclassesOfClass:[WMLSuperclass3 class] usingBlock:^(__unsafe_unretained Class class, BOOL *stop) {
                    [subclasses addObject:class];
                }];
                expect(subclasses).to.haveCountOf(2);
                expect(subclasses).to.contain([WMLSuperclass3Subclass1Grandsubclass1 class]);
            });

            it(@"should not include any classes for a class that does not have any subclasses", ^{
                NSMutableSet *subclasses = [NSMutableSet set];
                [[WMLDI di] enumerateSubclassesOfClass:[WMLEmptySuperclass class] usingBlock:^(__unsafe_unretained Class class, BOOL *stop) {
                    [subclasses addObject:class];
                }];
                expect(subclasses).to.beEmpty();
            });
        });

        describe(@"anySubclassOfClass", ^{
            it(@"should return correct subclass for superclass", ^{
                Class class = [[WMLDI di] anySubclassOfClass:[WMLSuperclass2 class]];
                expect(class).to.equal([WMLSuperclass2Subclass1 class]);
            });

            it(@"should not return any entities of a class that does not have any subclasses", ^{
                Class class = [[WMLDI di] anySubclassOfClass:[WMLEmptySuperclass class]];
                expect(class).to.beNil();
            });
        });
    });
});

SpecEnd


text:
package com.zutubi.android.ant;

import static java.util.Arrays.asList;
import static junit.framework.Assert.assertEquals;

import org.junit.Test;

import java.util.ArrayList;

public class VersionTest {
    @Test(expected = IllegalArgumentException.class)
    public void testParseEmpty() {
        new Version("");
    }

    @Test(expected = IllegalArgumentException.class)
    public void testParseDot() {
        new Version(".");
    }

    @Test(expected = IllegalArgumentException.class)
    public void testParseInvalidElement() {
        new Version("1.hello.2");
    }

    @Test(expected = IllegalArgumentException.class)
    public void testParseEmptyElement() {
        new Version("1..2");
    }

    @Test(expected = IllegalArgumentException.class)
    public void testParseEmptyElementFirst() {
        new Version(".1.2");
    }

    @Test(expected = IllegalArgumentException.class)
    public void testParseEmptyElementLast() {
        new Version("1.2.");
    }

    @Test(expected = IllegalArgumentException.class)
    public void testNoElements() {
        new Version(new ArrayList<Integer>());
    }

    @Test
    public void testParseSingleElement() {
        final Version version = new Version("42");
        assertEquals(asList(42), version.getElements());
    }

    @Test
    public void testParseMultipleElements() {
        final Version version = new Version("2.4.54");
        assertEquals(asList(2, 4, 54), version.getElements());
    }

    @Test
    public void testParseNegativeElement() {
        final Version version = new Version("22.0.-1");
        assertEquals(asList(22, 0, -1), version.getElements());
    }

    @Test
    public void testBumpSingleElement() {
        final Version version = new Version("3");
        assertEquals(new Version("4"), version.bump());
    }

    @Test
    public void testBumpMultipleElements() {
        final Version version = new Version("2.6.11");
        assertEquals(new Version("2.6.12"), version.bump());
    }

    @Test
    public void testToStringSingleElement() {
        final Version version = new Version("11");
        assertEquals("11", version.toString());
    }

    @Test
    public void testToStringMultipleElements() {
        final Version version = new Version("11.0.1");
        assertEquals("11.0.1", version.toString());
    }
}


text:
mackerel-plugin-mysql
=====================

MySQL custom metrics plugin for mackerel.io agent.

## Synopsis

```shell
mackerel-plugin-mysql [-host=<host>] [-port=<port>] [-username=<username>] [-password=<password>] [-tempfile=<tempfile>] [-disable_innodb=true]
```

## Example of mackerel-agent.conf

```
[plugin.metrics.mysql]
command = "/path/to/mackerel-plugin-mysql"
```


text:
/*
 * Do not modify this file. This file is generated from the config-2014-11-12.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;

using Amazon.ConfigService.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;

namespace Amazon.ConfigService.Model.Internal.MarshallTransformations
{
    /// <summary>
    /// Response Unmarshaller for EvaluationResultQualifier Object
    /// </summary>
    public class EvaluationResultQualifierUnmarshaller : IUnmarshaller<EvaluationResultQualifier, XmlUnmarshallerContext>, IUnmarshaller<EvaluationResultQualifier, JsonUnmarshallerContext>
    {
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        EvaluationResultQualifier IUnmarshaller<EvaluationResultQualifier, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public EvaluationResultQualifier Unmarshall(JsonUnmarshallerContext context)
        {
            context.Read();
            if (context.CurrentTokenType == JsonToken.Null)
                return null;

            EvaluationResultQualifier unmarshalledObject = new EvaluationResultQualifier();

            int targetDepth = context.CurrentDepth;
            while (context.ReadAtDepth(targetDepth))
            {
                if (context.TestExpression("ConfigRuleName", targetDepth))
                {
                    var unmarshaller = StringUnmarshaller.Instance;
                    unmarshalledObject.ConfigRuleName = unmarshaller.Unmarshall(context);
                    continue;
                }
                if (context.TestExpression("ResourceId", targetDepth))
                {
                    var unmarshaller = StringUnmarshaller.Instance;
                    unmarshalledObject.ResourceId = unmarshaller.Unmarshall(context);
                    continue;
                }
                if (context.TestExpression("ResourceType", targetDepth))
                {
                    var unmarshaller = StringUnmarshaller.Instance;
                    unmarshalledObject.ResourceType = unmarshaller.Unmarshall(context);
                    continue;
                }
            }

            return unmarshalledObject;
        }

        private static EvaluationResultQualifierUnmarshaller _instance = new EvaluationResultQualifierUnmarshaller();

        /// <summary>
        /// Gets the singleton.
        /// </summary>
        public static EvaluationResultQualifierUnmarshaller Instance
        {
            get
            {
                return _instance;
            }
        }
    }
}


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

		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<meta name="viewport" content="width=974; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0"/>
		<title>BLOBkit Samples</title>
		<link rel='stylesheet' type='text/css' href='../tvb.css' />

innerHTML: ...

DOM: ...

innerHTML: ...

DOM: ...


text:
require_relative 'container_health_check_worker'

module Kontena::Workers
  class HealthCheckWorker
    include Celluloid
    include Celluloid::Notifications
    include Kontena::Logging

    attr_reader :etcd, :workers

    finalizer :terminate_workers

    START_EVENTS = ['start']
    STOP_EVENTS = ['die', 'kill']
    ETCD_PREFIX = '/kontena/log_worker/containers'

    # @param [Boolean] autostart
    def initialize(autostart = true)
      @queue_processing = false
      @workers = {}
      subscribe('container:event', :on_container_event)
      info 'initialized'

      async.start if autostart
    end

    def start
      Docker::Container.all.each do |container|
        self.start_container_check(container)
      end
    end

    def stop
      @workers.keys.dup.each do |id|
        self.stop_container_check(id)
      end
    rescue => exc
      error "#{exc.class.name}: #{exc.message}"
    end

    # @param [Docker::Container] container
    def start_container_check(container)
      return unless container && container.health_check?

      exclusive {
        unless workers[container.id]
          workers[container.id] = ContainerHealthCheckWorker.new(container)
          workers[container.id].async.start
        end
      }
    rescue => exc
      error "#{exc.class.name}: #{exc.message}"
    end

    # @param [String] container_id
    def stop_container_check(container_id)
      worker = workers.delete(container_id)
      if worker
        worker.terminate if worker.alive?
      end
    end

    # @param [String] topic
    # @param [Docker::Event] event
    def on_container_event(topic, event)
      if STOP_EVENTS.include?(event.status)
        stop_container_check(event.id)
      elsif START_EVENTS.include?(event.status)
        container = Docker::Container.get(event.id) rescue nil
        if container
          start_container_check(container)
        end
      end
    end
  end
end


text:
package org.apache.cloudstack.api.command.admin.backup;

import javax.inject.Inject;

import org.apache.cloudstack.acl.RoleType;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseAsyncCmd;
import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.BackupOfferingResponse;
import org.apache.cloudstack.api.response.ZoneResponse;
import org.apache.cloudstack.backup.BackupManager;
import org.apache.cloudstack.backup.BackupOffering;
import org.apache.cloudstack.context.CallContext;

import com.cloud.event.EventTypes;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.utils.exception.CloudRuntimeException;

@APICommand(name = ImportBackupOfferingCmd.APINAME,
        description = "Imports a backup offering using a backup provider",
        responseObject = BackupOfferingResponse.class, since = "4.14.0",
        authorized = {RoleType.Admin})
public class ImportBackupOfferingCmd extends BaseAsyncCmd {
    public static final String APINAME = "importBackupOffering";

    @Inject
    private BackupManager backupManager;

    /////////////////////////////////////////////////////
    //////////////// API parameters /////////////////////
    ////////////////////////////////////////////////////

    @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true,
            description = "the name of the backup offering")
    private String name;

    @Parameter(name = ApiConstants.DESCRIPTION, type = CommandType.STRING, required = true,
            description = "the description of the backup offering")
    private String description;

    @Parameter(name = ApiConstants.EXTERNAL_ID,
            type = CommandType.STRING,
            required = true,
            description = "The backup offering ID (from backup provider side)")
    private String externalId;

    @Parameter(name = ApiConstants.ZONE_ID, type = BaseCmd.CommandType.UUID, entityType = ZoneResponse.class,
            description = "The zone ID", required = true)
    private Long zoneId;

    @Parameter(name = ApiConstants.ALLOW_USER_DRIVEN_BACKUPS, type = CommandType.BOOLEAN,
            description = "Whether users are allowed to create adhoc backups and backup schedules", required = true)
    private Boolean userDrivenBackups;

    /////////////////////////////////////////////////////
    /////////////////// Accessors ///////////////////////
    /////////////////////////////////////////////////////

    public String getName() {
        return name;
    }

    public String getExternalId() {
        return externalId;
    }

    public Long getZoneId() {
        return zoneId;
    }

    public String getDescription() {
        return description;
    }

    public Boolean getUserDrivenBackups() {
        return userDrivenBackups == null ? false : userDrivenBackups;
    }

    /////////////////////////////////////////////////////
    /////////////// API Implementation///////////////////
    /////////////////////////////////////////////////////

    @Override
    public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException {
        try {
            BackupOffering policy = backupManager.importBackupOffering(this);
            if (policy != null) {
                BackupOfferingResponse response = _responseGenerator.createBackupOfferingResponse(policy);
                response.setResponseName(getCommandName());
                setResponseObject(response);
            } else {
                throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add a backup offering");
            }
        } catch (InvalidParameterValueException e) {
            throw new ServerApiException(ApiErrorCode.PARAM_ERROR, e.getMessage());
        } catch (CloudRuntimeException e) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage());
        }
    }

    @Override
    public String getCommandName() {
        return APINAME.toLowerCase() + RESPONSE_SUFFIX;
    }

    @Override
    public long getEntityOwnerId() {
        return CallContext.current().getCallingAccount().getId();
    }

    @Override
    public String getEventType() {
        return EventTypes.EVENT_VM_BACKUP_IMPORT_OFFERING;
    }

    @Override
    public String getEventDescription() {
        return "Importing backup offering: " + name + " (external ID: " + externalId + ") on zone ID " + zoneId ;
    }
}


text:
using System;
using libsecondlife;

namespace libsecondlife.TestClient
{
    public class MD5Command : Command
    {
        public MD5Command(TestClient testClient)
        {
            Name = "md5";
            Description = "Creates an MD5 hash from a given password. Usage: md5 [password]";
        }

        public override string Execute(string[] args, LLUUID fromAgentID)
        {
            if (args.Length == 1)
                return Helpers.MD5(args[0]);
            else
                return "Usage: md5 [password]";
        }
    }
}


text:
<?php
namespace PhpUnitConversion\Traits;

use PhpUnitConversion\Unit;

trait BaseUnit
{
    /**
     * @return $this|Unit
     */
    protected function toBaseUnit()
    {
        if (static::class === self::class) {
            return $this;
        }
        return parent::toBaseUnit();
    }
}


text:
cryptopals
==========

My solutions to the cryptopals set of cryptography programming challenges
http://cryptopals.com


text:
package loon.live2d.type;

public class LDColor
{
    public int a;

    public LDColor() {
    }

    public LDColor(int color, final boolean useAlpha) {
        if (!useAlpha) {
            color |= 0xFF000000;
        }
        this.a = color;
    }
}


text:
import './empty-state.less';
import template from './empty-state.html';

const EmptyStateComponent = {
  template,
  replace: true,
  bindings: {
    icon: '@',
    title: '@',
    description: '@',
    helpLink: '@',
    showAlertStep: '<',
    showDashboardStep: '<',
    showInviteStep: '<',
    onboardingMode: '<',
  },
  controller($http, $uibModal, currentUser) {
    this.loading = true;
    this.isAdmin = currentUser.isAdmin;

    $http.get('api/organization/status').then((response) => {
      this.loading = false;

      const counters = response.data.object_counters;
      this.dataSourceStepCompleted = counters.data_sources > 0;
      this.queryStepCompleted = counters.queries > 0;
      this.dashboardStepCompleted = counters.dashboards > 0;
      this.alertStepCompleted = counters.alerts > 0;
      this.inviteStepCompleted = counters.users > 1;
    });

    this.shouldShowOnboarding = () => {
      if (this.loading) {
        return false;
      }

      if (!this.onboardingMode) {
        return true;
      }

      return !(
        this.dataSourceStepCompleted &&
        this.queryStepCompleted &&
        this.dashboardStepCompleted &&
        this.inviteStepCompleted
      );
    };

    this.newDashboard = () => {
      $uibModal.open({
        component: 'editDashboardDialog',
        resolve: {
          dashboard: () => ({ name: null, layout: null }),
        },
      });
    };
  },
};

export default function init(ngModule) {
  ngModule.component('emptyState', EmptyStateComponent);
}


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <!-- 字体样式 start -->
    <style name="chat_date_style">
        <item name="android:textColor">#F5F5F5</item>
        <item name="android:background">#BEBDBE</item>
        <item name="android:textSize">12sp</item>
        <item name="android:padding">2dp</item>
        <item name="android:layout_gravity">center</item>
    </style>

</resources>


text:
Block state functions are a class of functions designed to access state information about the most recently-executed block.
These functions can access information such as the current iteration number, the separator pattern, and the total number of
repetitions the block will perform. Some can also perform certain actions depending on the current state of the block.

## List of functions

|Function|Description|
|--------|-----------|
|[`[repnum]`](/language/functions#repnum)|Current iteration number.
**Sequence:** [1 ... n]|
|[`[repelapsed]`](/language/functions#repelapsed)|Number of finished iterations.
**Sequence:** [0 ... n - 1]|
|[`[reprem]`](/language/functions#reprem)|Number of iterations remaining after current one.
**Sequence:** [n - 1 ... 0]|
|[`[repqueued]`](/language/functions#repqueued)|Number of iterations not completed yet.
**Sequence:** [n ... 1]|
|[`[repcount]`](/language/functions#repcount)|Repetition count.|
|[`[depth]`](/language/functions#depth)|Number of currently active blocks.|
|[`[index]`](/language/functions#index)|Zero-based index of current item.|
|[`[index1]`](/language/functions#index1)|One-based index of current item.|
|[`[even]`](/language/functions#even)|Runs callback if current iteration is even.|
|[`[odd]`](/language/functions#odd)|Runs callback if current iteration is odd.|
|[`[nth]`](/language/functions#nth)|Runs callback if current iteration is a multiple of specified number.|
|[`[notnth]`](/language/functions#notnth)|Runs callback if current iteration is not a multiple of specified number.|
|[`[ntho]`](/language/functions#ntho)|Runs callback if current iteration with offset is a multiple of specified number.|
|[`[notntho]`](/language/functions#notntho)|Runs callback if current iteration with offset is not a multiple of specified number.|
|[`[first]`](/language/functions#first)|Runs callback if current iteration is the first.|
|[`[last]`](/language/functions#last)|Runs callback if current iteration is the last.|
|[`[ends]`](/language/functions#ends)|Runs callback if current iteration is the first or last.|
|[`[middle]`](/language/functions#ends)|Runs callback if current iteration is neither the first nor last.|
|[`[sep]`](/language/functions#sep)|Runs separator pattern.|

> TODO: Needs examples


text:
#import <UIKit/UIKit.h>
#import "TiDimension.h"
#import "TiUtils.h"

@protocol LayoutAutosizing

@optional

-(CGFloat)minimumParentWidthForSize:(CGSize)size;
-(CGFloat)minimumParentHeightForSize:(CGSize)size;

-(CGFloat)autoWidthForSize:(CGSize)size;
-(CGFloat)autoHeightForSize:(CGSize)size;

-(CGFloat)contentWidthForWidth:(CGFloat)suggestedWidth;
-(CGFloat)contentHeightForWidth:(CGFloat)width;

-(CGFloat)verifyWidth:(CGFloat)suggestedWidth;
-(CGFloat)verifyHeight:(CGFloat)suggestedHeight;

-(UIViewAutoresizing)verifyAutoresizing:(UIViewAutoresizing)suggestedResizing;

-(TiDimension)defaultAutoWidthBehavior:(id)unused;
-(TiDimension)defaultAutoHeightBehavior:(id)unused;

@end

typedef enum {
	TiLayoutRuleAbsolute,
	TiLayoutRuleVertical,
	TiLayoutRuleHorizontal,
} TiLayoutRule;

TI_INLINE CGFloat TiFixedValueRuleFromObject(id object)
{
	return [TiUtils floatValue:object def:0];
}

TI_INLINE TiLayoutRule TiLayoutRuleFromObject(id object)
{
	if ([object isKindOfClass:[NSString class]])
	{
		if ([object caseInsensitiveCompare:@"vertical"]==NSOrderedSame)
		{
			return TiLayoutRuleVertical;
		}
		if ([object caseInsensitiveCompare:@"horizontal"]==NSOrderedSame)
		{
			return TiLayoutRuleHorizontal;
		}
	}
	return TiLayoutRuleAbsolute;
}

TI_INLINE BOOL TiLayoutRuleIsAbsolute(TiLayoutRule rule)
{
	return rule==TiLayoutRuleAbsolute;
}

TI_INLINE BOOL TiLayoutRuleIsVertical(TiLayoutRule rule)
{
	return rule==TiLayoutRuleVertical;
}

TI_INLINE BOOL TiLayoutRuleIsHorizontal(TiLayoutRule rule)
{
	return rule==TiLayoutRuleHorizontal;
}

typedef struct LayoutConstraint {

	TiDimension centerX;
	TiDimension left;
	TiDimension right;
	TiDimension width;

	TiDimension centerY;
	TiDimension top;
	TiDimension bottom;
	TiDimension height;

	TiLayoutRule layoutStyle;
	struct {
		unsigned int horizontalWrap:1;
	} layoutFlags;

	CGFloat minimumHeight;
	CGFloat minimumWidth;

} LayoutConstraint;

TI_INLINE BOOL TiLayoutFlagsHasHorizontalWrap(LayoutConstraint *constraint)
{
	return constraint->layoutFlags.horizontalWrap;
}

@class TiUIView;
@class TiViewProxy;
void ApplyConstraintToViewWithBounds(LayoutConstraint * constraint, TiUIView * subView, CGRect viewBounds);
CGFloat WidthFromConstraintGivenWidth(LayoutConstraint * constraint,CGFloat viewWidth);
CGSize SizeConstraintViewWithSizeAddingResizing(LayoutConstraint * constraint, NSObject<LayoutAutosizing> * autoSizer, CGSize referenceSize, UIViewAutoresizing * resultResizing);
CGPoint PositionConstraintGivenSizeBoundsAddingResizing(LayoutConstraint * constraint, TiViewProxy* viewProxy, CGSize viewSize, CGPoint anchorPoint, CGSize referenceSize, CGSize sandboxSize, UIViewAutoresizing * resultResizing);
BOOL IsLayoutUndefined(LayoutConstraint *constraint);


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.curso</groupId>
    <artifactId>PracticaMvc0002</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>PracticaMvc0002</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.3.RELEASE</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
            <type>jar</type>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.2.4.Final</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>7.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
<?php # -*- coding: utf-8 -*-

namespace Requisite\Test\Example\Domain;

/**
 * Just an empty class body for autoload testing
 */
class Model {}


text:
/**
 * General purpose types for runtime support.
 */
@Incubating
package org.gradle.platform.base;

import org.gradle.api.Incubating;