text:
import { Blueprint, Schemas } from '@boost/common/optimal';
import { Context } from './Context';
import { createWorkUnit } from './createWorkUnit';
import { Pipeline } from './Pipeline';
import { Action } from './types';
import { WorkUnit } from './WorkUnit';

export abstract class SerialPipeline<
	Options extends object,
	Ctx extends Context,
	Input = unknown,
	Output = Input,
> extends Pipeline<Options, Ctx, Input, Output> {
	// Unknown does not work here as the output type changes for each
	// node in the linked list chain.
	// eslint-disable-next-line @typescript-eslint/no-explicit-any
	root: SerialPipeline<Options, Ctx, any> = this;

	// Empty blueprint so that sub-classes may type correctly
	blueprint(schemas: Schemas): Blueprint<object> {
		return {};
	}

	/**
	 * Pipe a work unit to be ran with the return value of the previous work unit.
	 */
	pipe<O>(
		title: string,
		action: Action<Ctx, Input, O>,
		scope?: unknown,
	): SerialPipeline<Options, Ctx, O>;
	pipe<O>(workUnit: WorkUnit<{}, Input, O>): SerialPipeline<Options, Ctx, O>;
	pipe<O>(
		titleOrWorkUnit: WorkUnit<{}, Input, O> | string,
		action?: Action<Ctx, Input, O>,
		scope?: unknown,
	): SerialPipeline<Options, Ctx, O> {
		const workUnit = createWorkUnit(titleOrWorkUnit, action, scope);

		workUnit.depth = this.depth;
		workUnit.index = this.getWorkUnits().length;

		this.root.work.push(workUnit);

		// @ts-expect-error How to type this?
		const next = new this.constructor(this.context, this.value, this.options) as SerialPipeline<
			Options,
			Ctx,
			O
		>;

		next.depth = this.depth;
		next.root = this.root;

		if (this.monitorInstance) {
			next.monitor(this.monitorInstance);
		}

		return next;
	}

	/**
	 * Traverse the linked list to return a list of work units in defined order.
	 */
	override getWorkUnits(): WorkUnit<{}, Input, Output>[] {
		// eslint-disable-next-line @typescript-eslint/no-unsafe-return
		return this.root.work;
	}

	/**
	 * Run and process the work units synchronously.
	 */
	abstract run(): Promise<Output>;
}


text:
SB.Include(Path.Join(SB.DIRS.SRC, 'view/editor.lua'))

HeightmapEditor = Editor:extends{}
HeightmapEditor:Register({
    name = "heightmapEditor",
    tab = "Map",
    caption = "Terrain",
    tooltip = "Edit heightmap",
    image = Path.Join(SB.DIRS.IMG, 'peaks.png'),
    order = 0,
})

function HeightmapEditor:init()
    self:super("init")

    self:AddField(AssetField({
        name = "patternTexture",
        title = "Pattern:",
        rootDir = "brush_patterns/terrain/",
        expand = true,
        itemWidth = 65,
        itemHeight = 65,
        Validate = function(obj, value)
            if value == nil then
                return true
            end
            if not AssetField.Validate(obj, value) then
                return false
            end

            local ext = Path.GetExt(value) or ""
            return table.ifind(SB_IMG_EXTS, ext), value
        end,
        Update = function(...)
            AssetField.Update(...)
            local texture = self.fields["patternTexture"].value
            SB.model.terrainManager:generateShape(texture)
        end
    }))

    self.btnAddState = TabbedPanelButton({
        x = 0,
        y = 0,
        tooltip = "Left Click to add height, Right Click to remove height",
        children = {
            TabbedPanelImage({ file = Path.Join(SB.DIRS.IMG, 'up-card.png') }),
            TabbedPanelLabel({ caption = "Add" }),
        },
        OnClick = {
            function()
                SB.stateManager:SetState(TerrainShapeModifyState(self))
            end
        },
    })

    self.btnSetState = TabbedPanelButton({
        x = 70,
        y = 0,
        tooltip = "Left Click to set height. Right click to sample height",
        children = {
            TabbedPanelImage({ file = Path.Join(SB.DIRS.IMG, 'terrain-set.png') }),
            TabbedPanelLabel({ caption = "Set" }),
        },
        OnClick = {
            function()
                SB.stateManager:SetState(TerrainSetState(self))
            end
        },
    })

    self.btnSmoothState = TabbedPanelButton({
        x = 140,
        y = 0,
        tooltip = "Click to smooth terrain",
        children = {
            TabbedPanelImage({ file = Path.Join(SB.DIRS.IMG, 'terrain-smooth.png') }),
            TabbedPanelLabel({ caption = "Smooth" }),
        },
        OnClick = {
            function()
                SB.stateManager:SetState(TerrainSmoothState(self))
            end
        },
    })
    self:AddDefaultKeybinding({
        self.btnAddState,
        self.btnSetState,
        self.btnSmoothState
    })

    self:AddControl("btn-show-elevation", {
        Button:New {
            caption = "Show elevation",
            width = 200,
            height = 40,
            OnClick = {
                function()
                    Spring.SendCommands('showelevation')
                end
            }
        },
    })

    self:AddField(NumericField({
        name = "size",
        value = 100,
        minValue = 10,
        maxValue = 5000,
        title = "Size:",
        tooltip = "Size of the height brush",
    }))
    self:AddField(NumericField({
        name = "rotation",
        value = 0,
        minValue = -360,
        maxValue = 360,
        title = "Rotation:",
        tooltip = "Rotation of the shape",
    }))
    self:AddField(NumericField({
        name = "strength",
        value = 10,
        step = 0.1,
        title = "Strength:",
        tooltip = "Strength of the height map tool",
    }))
    self:AddField(NumericField({
        name = "height",
        value = 10,
        step = 0.1,
        title = "Height:",
        tooltip = "Goal height",
    }))
    self:AddField(ChoiceField({
        name = "applyDir",
        items = {"Both", "Only Raise", "Only Lower"},
        tooltip = "Whether terrain should be only lowered, raised or both.",
    }))
    self:Update("size")
    self:SetInvisibleFields("applyDir")

    local children = {
        self.btnAddState,
        self.btnSetState,
        self.btnSmoothState,
        ScrollPanel:New {
            x = 0,
            y = 70,
            bottom = 30,
            right = 0,
            borderColor = {0,0,0,0},
            horizontalScrollbar = false,
            children = { self.stackPanel },
        },
    }

    self:Finalize(children)
end

function HeightmapEditor:OnLeaveState(state)
    for _, btn in pairs({self.btnAddState, self.btnSmoothState, self.btnSetState}) do
        btn:SetPressedState(false)
    end
end

function HeightmapEditor:OnEnterState(state)
    local btn
    if state:is_A(TerrainShapeModifyState) then
        self:SetInvisibleFields("applyDir")
        btn = self.btnAddState
    elseif state:is_A(TerrainSetState) then
        self:SetInvisibleFields()
        btn = self.btnSetState
    elseif state:is_A(TerrainSmoothState) then
        self:SetInvisibleFields("applyDir")
        btn = self.btnSmoothState
    end
    btn:SetPressedState(true)
end

function HeightmapEditor:IsValidState(state)
    return state:is_A(AbstractHeightmapEditingState)
end

redpajama_set_name: RedPajamaGithub


text:
/**
 * A type of dialogue used as for choosing options.
 *
 * @module moodle-core-chooserdialogue
 */

/**
 * A type of dialogue used as for choosing options.
 *
 * @constructor
 * @class M.core.chooserdialogue
 */
var CHOOSERDIALOGUE = function() {
    CHOOSERDIALOGUE.superclass.constructor.apply(this, arguments);
};

Y.extend(CHOOSERDIALOGUE, Y.Base, {
    // The panel widget
    panel: null,

    // The submit button - we disable this until an element is set
    submitbutton: null,

    // The chooserdialogue container
    container: null,

    // Any event listeners we may need to cancel later
    listenevents: [],

    bodycontent: null,
    headercontent: null,
    instanceconfig: null,

    // The hidden field storing the disabled element values for submission.
    hiddenRadioValue: null,

    setup_chooser_dialogue: function(bodycontent, headercontent, config) {
        this.bodycontent = bodycontent;
        this.headercontent = headercontent;
        this.instanceconfig = config;
    },

    prepare_chooser: function() {
        if (this.panel) {
            return;
        }

        // Ensure that we're showing the JS version of the chooser.
        Y.one(Y.config.doc.body).addClass('jschooser');

        // Set Default options
        var paramkey,
            params = {
                bodyContent: this.bodycontent.get('innerHTML'),
                headerContent: this.headercontent.get('innerHTML'),
                width: '540px',
                draggable: true,
                visible: false, // Hide by default
                zindex: 100, // Display in front of other items
                modal: true, // This dialogue should be modal.
                shim: true,
                closeButtonTitle: this.get('closeButtonTitle'),
                focusOnPreviousTargetAfterHide: true,
                render: false,
                extraClasses: this._getClassNames()
            };

        // Override with additional options
        for (paramkey in this.instanceconfig) {
          params[paramkey] = this.instanceconfig[paramkey];
        }

        // Create the panel
        this.panel = new M.core.dialogue(params);

        // Remove the template for the chooser
        this.bodycontent.remove();
        this.headercontent.remove();

        // Hide and then render the panel
        this.panel.hide();
        this.panel.render();

        // Set useful links.
        this.container = this.panel.get('boundingBox').one('.choosercontainer');
        this.options = this.container.all('.option input[type=radio]');

        // The hidden form element we use when submitting.
        this.hiddenRadioValue = Y.Node.create('<input type="hidden" value="" />');
        this.container.one('form').appendChild(this.hiddenRadioValue);

        // Add the chooserdialogue class to the container for styling
        this.panel.get('boundingBox').addClass('chooserdialogue');
    },

    /**
      * Display the module chooser
      *
      * @method display_chooser
      * @param {EventFacade} e Triggering Event
      */
    display_chooser: function(e) {
        var bb, dialogue, thisevent;
        this.prepare_chooser();

        // Stop the default event actions before we proceed
        e.preventDefault();

        bb = this.panel.get('boundingBox');
        dialogue = this.container.one('.alloptions');

        // This will detect a change in orientation and retrigger centering
        thisevent = Y.one('document').on('orientationchange', function() {
            this.center_dialogue(dialogue);
        }, this);
        this.listenevents.push(thisevent);

        // Detect window resizes (most browsers)
        thisevent = Y.one('window').on('resize', function() {
            this.center_dialogue(dialogue);
        }, this);
        this.listenevents.push(thisevent);

        // These will trigger a check_options call to display the correct help
        thisevent = this.container.on('click', this.check_options, this);
        this.listenevents.push(thisevent);
        thisevent = this.container.on('key_up', this.check_options, this);
        this.listenevents.push(thisevent);
        thisevent = this.container.on('dblclick', function(e) {
            if (e.target.ancestor('div.option')) {
                this.check_options();

                // Prevent duplicate submissions
                this.submitbutton.setAttribute('disabled', 'disabled');
                this.options.setAttribute('disabled', 'disabled');
                this.cancel_listenevents();

                this.container.one('form').submit();
            }
        }, this);
        this.listenevents.push(thisevent);

        this.container.one('form').on('submit', function() {
            // Prevent duplicate submissions on submit
            this.submitbutton.setAttribute('disabled', 'disabled');
            this.options.setAttribute('disabled', 'disabled');
            this.cancel_listenevents();
        }, this);

        // Hook onto the cancel button to hide the form
        thisevent = this.container.one('.addcancel').on('click', this.cancel_popup, this);
        this.listenevents.push(thisevent);

        // Hide will be managed by cancel_popup after restoring the body overflow
        thisevent = bb.one('button.closebutton').on('click', this.cancel_popup, this);
        this.listenevents.push(thisevent);

        // Grab global keyup events and handle them
        thisevent = Y.one('document').on('keydown', this.handle_key_press, this);
        this.listenevents.push(thisevent);

        // Add references to various elements we adjust
        this.submitbutton = this.container.one('.submitbutton');

        // Disable the submit element until the user makes a selection
        this.submitbutton.set('disabled', 'true');

        // Ensure that the options are shown
        this.options.removeAttribute('disabled');

        // Display the panel
        this.panel.show(e);

        // Re-centre the dialogue after we've shown it.
        this.center_dialogue(dialogue);

        // Finally, focus the first radio element - this enables form selection via the keyboard
        this.container.one('.option input[type=radio]').focus();

        // Trigger check_options to set the initial jumpurl
        this.check_options();
    },

    /**
     * Cancel any listen events in the listenevents queue
     *
     * Several locations add event handlers which should only be called before the form is submitted. This provides
     * a way of cancelling those events.
     *
     * @method cancel_listenevents
     */
    cancel_listenevents: function() {
        // Detach all listen events to prevent duplicate triggers
        var thisevent;
        while (this.listenevents.length) {
            thisevent = this.listenevents.shift();
            thisevent.detach();
        }
    },

    /**
      * Calculate the optimum height of the chooser dialogue
      *
      * This tries to set a sensible maximum and minimum to ensure that some options are always shown, and preferably
      * all, whilst fitting the box within the current viewport.
      *
      * @method center_dialogue
      * @param Node {dialogue} Y.Node The dialogue
      */
    center_dialogue: function(dialogue) {
        var bb = this.panel.get('boundingBox'),
            winheight = bb.get('winHeight'),
            newheight, totalheight;

        if (this.panel.shouldResizeFullscreen()) {
            // No custom sizing required for a fullscreen dialog.
            return;
        }

        // Try and set a sensible max-height -- this must be done before setting the top
        // Set a default height of 640px
        newheight = this.get('maxheight');
        if (winheight <= newheight) {
            // Deal with smaller window sizes
            if (winheight <= this.get('minheight')) {
                newheight = this.get('minheight');
            } else {
                newheight = winheight;
            }
        }

        // If the dialogue is larger than a reasonable minimum height, we
        // disable the page scrollbars.
        if (newheight > this.get('minheight')) {
            // Disable the page scrollbars.
            if (this.panel.lockScroll && !this.panel.lockScroll.isActive()) {
                this.panel.lockScroll.enableScrollLock(true);
            }
        } else {
            // Re-enable the page scrollbars.
            if (this.panel.lockScroll && this.panel.lockScroll.isActive()) {
                this.panel.lockScroll.disableScrollLock();
            }
        }

        // Take off 15px top and bottom for borders, plus 40px each for the title and button area before setting the
        // new max-height
        totalheight = newheight;
        newheight = newheight - (15 + 15 + 40 + 40);
        dialogue.setStyle('maxHeight', newheight + 'px');

        var dialogueheight = bb.getStyle('height');
        if (dialogueheight.match(/.*px$/)) {
            dialogueheight = dialogueheight.replace(/px$/, '');
        } else {
            dialogueheight = totalheight;
        }

        if (dialogueheight < this.get('baseheight')) {
            dialogueheight = this.get('baseheight');
            dialogue.setStyle('height', dialogueheight + 'px');
        }

        this.panel.centerDialogue();
    },

    handle_key_press: function(e) {
        if (e.keyCode === 27) {
            this.cancel_popup(e);
        }
    },

    cancel_popup: function(e) {
        // Prevent normal form submission before hiding
        e.preventDefault();
        this.hide();
    },

    hide: function() {
        // Cancel all listen events
        this.cancel_listenevents();

        this.container.detachAll();
        this.panel.hide();
    },

    check_options: function() {
        // Check which options are set, and change the parent class
        // to show/hide help as required
        this.options.each(function(thisoption) {
            var optiondiv = thisoption.get('parentNode').get('parentNode');
            if (thisoption.get('checked')) {
                optiondiv.addClass('selected');

                // Trigger any events for this option
                this.option_selected(thisoption);

                // Ensure that the form may be submitted
                this.submitbutton.removeAttribute('disabled');

                // Ensure that the radio remains focus so that keyboard navigation is still possible
                thisoption.focus();
            } else {
                optiondiv.removeClass('selected');
            }
        }, this);
    },

    option_selected: function(e) {
        // Set a hidden input field with the value and name of the radio button.  When we submit the form, we
        // disable the radios to prevent duplicate submission. This has the result however that the value is never
        // submitted so we set this value to a hidden field instead
        this.hiddenRadioValue.setAttrs({
            value: e.get('value'),
            name: e.get('name')
        });
    },

    /**
     * Return an array of class names prefixed with 'chooserdialogue-' and
     * the name of the type of dialogue.
     *
     * Note: Class name are converted to lower-case.
     *
     * If an array of arguments is supplied, each of these is prefixed and
     * lower-cased also.
     *
     * If no arguments are supplied, then the prefix is returned on it's
     * own.
     *
     * @method _getClassNames
     * @param {Array} [args] Any additional names to prefix and lower-case.
     * @return {Array}
     * @private
     */
    _getClassNames: function(args) {
        var prefix = 'chooserdialogue-' + this.name,
            results = [];

        results.push(prefix.toLowerCase());
        if (args) {
            var arg;
            for (arg in args) {
                results.push((prefix + '-' + arg).toLowerCase());
            }
        }

        return results;
    }
},
{
    NAME: 'moodle-core-chooserdialogue',
    ATTRS: {
        /**
         * The minimum height (in pixels) before resizing is prevented and scroll
         * locking disabled.
         *
         * @attribute minheight
         * @type Number
         * @default 300
         */
        minheight: {
            value: 300
        },

        /**
         * The base height??
         *
         * @attribute baseheight
         * @type Number
         * @default 400
         */
        baseheight: {
            value: 400
        },

        /**
         * The maximum height (in pixels) at which we stop resizing.
         *
         * @attribute maxheight
         * @type Number
         * @default 300
         */
        maxheight: {
            value: 660
        },

        /**
         * The title of the close button.
         *
         * @attribute closeButtonTitle
         * @type String
         * @default 'Close'
         */
        closeButtonTitle: {
            validator: Y.Lang.isString,
            value: 'Close'
        }
    }
});
M.core = M.core || {};
M.core.chooserdialogue = CHOOSERDIALOGUE;


text:
/**
 * example apps and non-automated tests for appstates
 */
package jme3test.app.state;


text:
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_SEGMENTED_FONT_FACE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_SEGMENTED_FONT_FACE_H_

#include "base/callback.h"
#include "third_party/blink/renderer/platform/fonts/font_cache_key.h"
#include "third_party/blink/renderer/platform/fonts/font_selection_types.h"
#include "third_party/blink/renderer/platform/fonts/segmented_font_data.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/lru_cache.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"

namespace blink {

class FontData;
class FontDescription;
class FontFace;
class SegmentedFontData;

// CSSSegmentedFontFace stores two FontFace list-sets, CSS-connected and
// non-CSS-connected. This class combines the two such that they can be
// conveniently operated as one.
// Note however, |Insert| has to be instructed which sub-list to insert it to.
// Iterating over the combined set, behaves as if all non-CSS-connected
// FontFaces were stored after the CSS-connected ones.
class FontFaceList : public GarbageCollected<FontFaceList> {
  using FontFaceListPart = HeapListHashSet<Member<FontFace>>;

 public:
  bool IsEmpty() const;
  void Insert(FontFace* font_face, bool css_connected);
  bool Erase(FontFace* font_face);

  // Iterate over CSS-connected FontFaces first, and then non-CSS-connected
  // ones.
  // Modifying the collection is not allowed during iteration.
  bool ForEachUntilTrue(
      const base::RepeatingCallback<bool(Member<FontFace>)>& callback) const;
  bool ForEachUntilFalse(
      const base::RepeatingCallback<bool(Member<FontFace>)>& callback) const;
  void ForEach(
      const base::RepeatingCallback<void(Member<FontFace>)>& callback) const;

  // Iterate (in reverse order) over non-CSS-connected FontFaces first, and
  // then CSS-connected ones.
  // Modifying the collection is not allowed during iteration.
  bool ForEachReverseUntilTrue(
      const base::RepeatingCallback<bool(Member<FontFace>)>& callback) const;
  bool ForEachReverseUntilFalse(
      const base::RepeatingCallback<bool(Member<FontFace>)>& callback) const;
  void ForEachReverse(
      const base::RepeatingCallback<void(Member<FontFace>)>& callback) const;

  void Trace(Visitor* visitor);

 private:
  FontFaceListPart css_connected_face_;
  FontFaceListPart non_css_connected_face_;
};

class CSSSegmentedFontFace final
    : public GarbageCollected<CSSSegmentedFontFace> {
 public:
  CSSSegmentedFontFace(FontSelectionCapabilities);
  ~CSSSegmentedFontFace();

  FontSelectionCapabilities GetFontSelectionCapabilities() const {
    return font_selection_capabilities_;
  }

  // Called when status of a FontFace has changed (e.g. loaded or timed out)
  // so cached FontData must be discarded.
  void FontFaceInvalidated();

  void AddFontFace(FontFace*, bool css_connected);
  void RemoveFontFace(FontFace*);
  bool IsEmpty() const { return font_faces_->IsEmpty(); }

  scoped_refptr<FontData> GetFontData(const FontDescription&);

  bool CheckFont(const String&) const;
  void Match(const String&, HeapVector<Member<FontFace>>*) const;
  void WillUseFontData(const FontDescription&, const String& text);
  void WillUseRange(const FontDescription&, const blink::FontDataForRangeSet&);
  size_t ApproximateCharacterCount() const {
    return approximate_character_count_;
  }

  void Trace(Visitor*);

 private:
  void PruneTable();
  bool IsValid() const;

  FontSelectionCapabilities font_selection_capabilities_;

  WTF::LruCache<FontCacheKey, scoped_refptr<SegmentedFontData>>
      font_data_table_;

  // All non-CSS-connected FontFaces are stored after the CSS-connected ones.
  Member<FontFaceList> font_faces_;

  // Approximate number of characters styled with this CSSSegmentedFontFace.
  // LayoutText::StyleDidChange() increments this on the first
  // CSSSegmentedFontFace in the style's font family list, so this is not
  // counted if this font is used as a fallback font. Also, this may be double
  // counted by style recalcs.
  // TODO(ksakamoto): Revisit the necessity of this. crbug.com/613500
  size_t approximate_character_count_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_SEGMENTED_FONT_FACE_H_


text:
source $RBW_PLUGINS/system/utils.sh

# Create the variables calling the functions:
PROMPT_COMMAND="rbw_system_set_exit_status;\
$PROMPT_COMMAND"


text:
module Ci
  # Currently this is artificial object, constructed dynamically
  # We should migrate this object to actual database record in the future
  class LegacyStage
    include StaticModel
    include Presentable

    attr_reader :pipeline, :name

    delegate :project, to: :pipeline

    def initialize(pipeline, name:, status: nil, warnings: nil)
      @pipeline = pipeline
      @name = name
      @status = status
      # support ints and booleans
      @has_warnings = ActiveRecord::Type::Boolean.new.cast(warnings)
    end

    def groups
      @groups ||= Ci::Group.fabricate(project, self)
    end

    def to_param
      name
    end

    def statuses_count
      @statuses_count ||= statuses.count
    end

    def status
      @status ||= statuses.latest.composite_status
    end

    def detailed_status(current_user)
      Gitlab::Ci::Status::Stage::Factory
        .new(self, current_user)
        .fabricate!
    end

    def latest_statuses
      statuses.ordered.latest
    end

    def statuses
      @statuses ||= pipeline.statuses.where(stage: name)
    end

    def builds
      @builds ||= pipeline.builds.where(stage: name)
    end

    def success?
      status.to_s == 'success'
    end

    def has_warnings?
      # lazilly calculate the warnings
      if @has_warnings.nil?
        @has_warnings = statuses.latest.failed_but_allowed.any?
      end

      @has_warnings
    end

    def manual_playable?
      %[manual scheduled skipped].include?(status.to_s)
    end
  end
end


text:
<?php
namespace metastore;

/**
 * Autogenerated by Thrift Compiler (0.14.1)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
use Thrift\Base\TBase;
use Thrift\Type\TType;
use Thrift\Type\TMessageType;
use Thrift\Exception\TException;
use Thrift\Exception\TProtocolException;
use Thrift\Protocol\TProtocol;
use Thrift\Protocol\TBinaryProtocolAccelerated;
use Thrift\Exception\TApplicationException;

class SeedTableWriteIdsRequest
{
    static public $isValidate = false;

    static public $_TSPEC = array(
        1 => array(
            'var' => 'dbName',
            'isRequired' => true,
            'type' => TType::STRING,
        ),
        2 => array(
            'var' => 'tableName',
            'isRequired' => true,
            'type' => TType::STRING,
        ),
        3 => array(
            'var' => 'seedWriteId',
            'isRequired' => true,
            'type' => TType::I64,
        ),
    );

    /**
     * @var string
     */
    public $dbName = null;
    /**
     * @var string
     */
    public $tableName = null;
    /**
     * @var int
     */
    public $seedWriteId = null;

    public function __construct($vals = null)
    {
        if (is_array($vals)) {
            if (isset($vals['dbName'])) {
                $this->dbName = $vals['dbName'];
            }
            if (isset($vals['tableName'])) {
                $this->tableName = $vals['tableName'];
            }
            if (isset($vals['seedWriteId'])) {
                $this->seedWriteId = $vals['seedWriteId'];
            }
        }
    }

    public function getName()
    {
        return 'SeedTableWriteIdsRequest';
    }

    public function read($input)
    {
        $xfer = 0;
        $fname = null;
        $ftype = 0;
        $fid = 0;
        $xfer += $input->readStructBegin($fname);
        while (true) {
            $xfer += $input->readFieldBegin($fname, $ftype, $fid);
            if ($ftype == TType::STOP) {
                break;
            }
            switch ($fid) {
                case 1:
                    if ($ftype == TType::STRING) {
                        $xfer += $input->readString($this->dbName);
                    } else {
                        $xfer += $input->skip($ftype);
                    }
                    break;
                case 2:
                    if ($ftype == TType::STRING) {
                        $xfer += $input->readString($this->tableName);
                    } else {
                        $xfer += $input->skip($ftype);
                    }
                    break;
                case 3:
                    if ($ftype == TType::I64) {
                        $xfer += $input->readI64($this->seedWriteId);
                    } else {
                        $xfer += $input->skip($ftype);
                    }
                    break;
                default:
                    $xfer += $input->skip($ftype);
                    break;
            }
            $xfer += $input->readFieldEnd();
        }
        $xfer += $input->readStructEnd();
        return $xfer;
    }

    public function write($output)
    {
        $xfer = 0;
        $xfer += $output->writeStructBegin('SeedTableWriteIdsRequest');
        if ($this->dbName !== null) {
            $xfer += $output->writeFieldBegin('dbName', TType::STRING, 1);
            $xfer += $output->writeString($this->dbName);
            $xfer += $output->writeFieldEnd();
        }
        if ($this->tableName !== null) {
            $xfer += $output->writeFieldBegin('tableName', TType::STRING, 2);
            $xfer += $output->writeString($this->tableName);
            $xfer += $output->writeFieldEnd();
        }
        if ($this->seedWriteId !== null) {
            $xfer += $output->writeFieldBegin('seedWriteId', TType::I64, 3);
            $xfer += $output->writeI64($this->seedWriteId);
            $xfer += $output->writeFieldEnd();
        }
        $xfer += $output->writeFieldStop();
        $xfer += $output->writeStructEnd();
        return $xfer;
    }
}


text:
package com.vitreoussoftware.bioinformatics.alignment;

import com.vitreoussoftware.bioinformatics.sequence.Sequence;
import org.javatuples.Pair;

import java.util.Collection;
import java.util.LinkedList;
import java.util.stream.Collectors;

/**
 * Aligners allow users to determine the locations of a set of Patterns from within a set of Texts,
 * based on a matching function.
 *

 * A PatternFirstAligner pre-processes the Text that is to be aligned against, then runs the Patterns against
 * that pre-processed Text.
 *

 * An Example would be creating a KeywordMap from the set of reads and then aligning them against the GreenGeenes set.
 *

 * This is not the standard way of approaching alignment, as in most cases the Texts are fairly stable however the
 * read sets change on a per experiment basis. This is more useful if using an iterative approach that generates new
 * candidate sequences and needs to align against them periodically.
 *

 * Created by John on 8/23/14.
 */
public interface PatternFirstAligner {
    /**
     * Adds a new pattern to the suffix tree
     *
     * @param pattern the pattern to add
     */
    public void addPattern(final Sequence pattern);

    /**
     * Does the text contain one or more of the patterns
     *
     * @param text the sequence to search in
     * @return if the text contained one of the patterns
     */
    public boolean contained(Sequence text);

    /**
     * For all texts which are have contained patterns
     *
     * @param texts collection of sequences to search in
     * @return List of (Text, contained?) pairs.
     */
    default public Collection<Pair<Sequence, Boolean>> contained(final Collection<Sequence> texts) {
        return texts.stream().map(pattern -> Pair.with(pattern, this.contained(pattern))).collect(Collectors.toCollection(LinkedList::new));
    }

    /**
     * Find the set of alignments for the text of interest
     *
     * @param text to find alignments for
     * @return the set of parents, or empty list if no parents
     */
    public Collection<Alignment> getAlignments(Sequence text);

    /**
     * Find the set of alignments for the each pattern of interest
     *
     * @param texts to find alignments for
     * @return List of (Pattern, Collection<Alignment) pairs.
     */
    default public Collection<Pair<Sequence, Collection<Alignment>>> getAlignments(final Collection<Sequence> texts) {
        return texts.stream().map(pattern -> Pair.with(pattern, this.getAlignments(pattern))).collect(Collectors.toCollection(LinkedList::new));
    }

    /**
     * Return the minimum shortestDistance from the given text to each of the sequences making up the Aligner
     *
     * @param text the DNA text to check shortestDistance for
     * @return The collection of tuples showing the shortestDistance and the collection of sequences for that shortestDistance
     */
    default public Collection<Alignment> shortestDistance(final Sequence text) {
        // Negative number used to indicate no distance cap
        return shortestDistance(text, -1);
    }

    /**
     * Return the minimum shortestDistance from the given texts to each of the sequences making up the Aligner
     *
     * @param texts the DNA texts to check shortestDistance for
     * @return The collection of tuples showing the shortestDistance and the collection of sequences for that shortestDistance
     */
    default public Collection<Pair<Sequence, Collection<Alignment>>> shortestDistance(final Collection<Sequence> texts) {
        // Negative number used to indicate no distance cap
        return shortestDistance(texts, -1);
    }

    /**
     * Return the minimum shortestDistance from the given text to each of the sequences making up the Aligner
     *
     * @param text        the DNA text to check shortestDistance for
     * @param maxDistance the maximum shortestDistance before which we give up
     * @return The collection of tuples showing the shortestDistance and the collection of sequences for that shortestDistance
     */
    public Collection<Alignment> shortestDistance(Sequence text, int maxDistance);

    /**
     * Return the minimum shortestDistance from the given texts to each of the sequences making up the Aligner
     *
     * @param texts       the DNA texts to check shortestDistance for
     * @param maxDistance the maximum shortestDistance before which we give up
     * @return The collection of tuples showing the shortestDistance and the collection of sequences for that shortestDistance
     */
    default public Collection<Pair<Sequence, Collection<Alignment>>> shortestDistance(final Collection<Sequence> texts, final int maxDistance) {
        return texts.stream().map(pattern -> Pair.with(pattern, shortestDistance(pattern, maxDistance))).collect(Collectors.toCollection(LinkedList::new));
    }

    /**
     * Return the set of distances for each parent Sequence given the target Sequences
     *
     * @param text the target Sequence
     * @return the tuples of parent Sequences and the shortestDistance lists
     */
    default public Collection<Alignment> distances(final Sequence text) {
        // Negative number used to indicate no distance cap
        return distances(text, -1);
    }

    /**
     * Return the set of distances for each parent Sequence given the target Sequences
     *
     * @param texts the target Sequence
     * @return the tuples of parent Sequences and the shortestDistance lists
     */
    default public Collection<Pair<Sequence, Collection<Alignment>>> distances(final Collection<Sequence> texts) {
        // Negative number used to indicate no distance cap
        return distances(texts, -1);
    }

    /**
     * Return the set of distances for each text Sequence within the maximum for the given text Sequence
     *
     * @param text        the target Sequence
     * @param maxDistance the maximum shortestDistance that will be considered
     * @return the tuples of parent Sequences and the shortestDistance lists
     */
    public Collection<Alignment> distances(Sequence text, int maxDistance);

    /**
     * Return the set of distances for each parent Sequence within the maximum for the given pattern Sequences
     *
     * @param texts       the target Sequences
     * @param maxDistance the maximum shortestDistance that will be considered
     * @return the tuples of parent Sequences and the shortestDistance lists
     */
    default public Collection<Pair<Sequence, Collection<Alignment>>> distances(final Collection<Sequence> texts, final int maxDistance) {
        return texts.stream().map(pattern -> Pair.with(pattern, distances(pattern, maxDistance))).collect(Collectors.toCollection(LinkedList::new));
    }
}


text:
from __future__ import unicode_literals

import base64
import json
import logging
import mimetools
import re

from django.conf.urls import include, patterns, url
from django.dispatch import receiver
from django.utils import six
from django.utils.six.moves.urllib.parse import urlparse
from django.utils.six.moves.urllib.request import (Request as BaseURLRequest,
                                                   HTTPBasicAuthHandler,
                                                   urlopen)
from django.utils.translation import ugettext_lazy as _
from djblets.registries.errors import ItemLookupError
from djblets.registries.registry import (ALREADY_REGISTERED, LOAD_ENTRY_POINT,
                                         NOT_REGISTERED)

import reviewboard.hostingsvcs.urls as hostingsvcs_urls
from reviewboard.registries.registry import EntryPointRegistry
from reviewboard.signals import initializing

class URLRequest(BaseURLRequest):
    def __init__(self, url, body='', headers={}, method='GET'):
        BaseURLRequest.__init__(self, url, body, headers)
        self.method = method

    def get_method(self):
        return self.method

class HostingServiceClient(object):
    """Client for communicating with a hosting service's API.

    This implementation includes abstractions for performing HTTP operations,
    and wrappers for those to interpret responses as JSON data.

    HostingService subclasses can also include an override of this class to add
    additional checking (such as GitHub's checking of rate limit headers), or
    add higher-level API functionality.
    """
    def __init__(self, hosting_service):
        pass

    #
    # HTTP utility methods
    #

    def http_delete(self, url, headers={}, *args, **kwargs):
        """Perform an HTTP DELETE on the given URL."""
        return self.http_request(url, headers=headers, method='DELETE',
                                 **kwargs)

    def http_get(self, url, *args, **kwargs):
        """Perform an HTTP GET on the given URL."""
        return self.http_request(url, method='GET', **kwargs)

    def http_post(self, url, body=None, fields={}, files={}, content_type=None,
                  headers={}, *args, **kwargs):
        """Perform an HTTP POST on the given URL."""
        headers = headers.copy()

        if body is None:
            if fields is not None:
                body, content_type = self._build_form_data(fields, files)
            else:
                body = ''

        if content_type:
            headers['Content-Type'] = content_type

        headers['Content-Length'] = '%d' % len(body)

        return self.http_request(url, body=body, headers=headers,
                                 method='POST', **kwargs)

    def http_request(self, url, body=None, headers={}, method='GET', **kwargs):
        """Perform some HTTP operation on a given URL."""
        r = self._build_request(url, body, headers, method=method, **kwargs)
        u = urlopen(r)

        return u.read(), u.headers

    #
    # JSON utility methods
    #

    def json_delete(self, *args, **kwargs):
        """Perform an HTTP DELETE and interpret the results as JSON."""
        return self._do_json_method(self.http_delete, *args, **kwargs)

    def json_get(self, *args, **kwargs):
        """Perform an HTTP GET and interpret the results as JSON."""
        return self._do_json_method(self.http_get, *args, **kwargs)

    def json_post(self, *args, **kwargs):
        """Perform an HTTP POST and interpret the results as JSON."""
        return self._do_json_method(self.http_post, *args, **kwargs)

    def _do_json_method(self, method, *args, **kwargs):
        """Internal helper for JSON operations."""
        data, headers = method(*args, **kwargs)

        if data:
            data = json.loads(data)

        return data, headers

    #
    # Internal utilities
    #

    def _build_request(self, url, body=None, headers={}, username=None,
                       password=None, method='GET'):
        """Build a URLRequest object, including HTTP Basic auth"""
        r = URLRequest(url, body, headers, method=method)

        if username is not None and password is not None:
            if isinstance(username, six.text_type):
                username = username.encode('utf-8')

            if isinstance(password, six.text_type):
                password = password.encode('utf-8')

            auth_key = username + b':' + password
            r.add_header(HTTPBasicAuthHandler.auth_header,
                         b'Basic %s' %
                         base64.b64encode(auth_key))

        return r

    def _build_form_data(self, fields, files):
        """Encodes data for use in an HTTP POST."""
        BOUNDARY = mimetools.choose_boundary()
        content = ""

        for key in fields:
            content += "--" + BOUNDARY + "\r\n"
            content += "Content-Disposition: form-data; name=\"%s\"\r\n" % key
            content += "\r\n"
            content += six.text_type(fields[key]) + "\r\n"

        for key in files:
            filename = files[key]['filename']
            value = files[key]['content']
            content += "--" + BOUNDARY + "\r\n"
            content += "Content-Disposition: form-data; name=\"%s\"; " % key
            content += "filename=\"%s\"\r\n" % filename
            content += "\r\n"
            content += value + "\r\n"

        content += "--" + BOUNDARY + "--\r\n"
        content += "\r\n"

        content_type = "multipart/form-data; boundary=%s" % BOUNDARY

        return content, content_type

class HostingService(object):
    """An interface to a hosting service for repositories and bug trackers.

    HostingService subclasses are used to more easily configure repositories
    and to make use of third party APIs to perform special operations not
    otherwise usable by generic repositories.

    A HostingService can specify forms for repository and bug tracker
    configuration.

    It can also provide a list of repository "plans" (such as public
    repositories, private repositories, or other types available to the hosting
    service), along with configuration specific to the plan. These plans will
    be available when configuring the repository.
    """
    name = None
    plans = None
    supports_bug_trackers = False
    supports_post_commit = False
    supports_repositories = False
    supports_ssh_key_association = False
    supports_two_factor_auth = False
    supports_list_remote_repositories = False
    has_repository_hook_instructions = False

    self_hosted = False
    repository_url_patterns = None

    client_class = HostingServiceClient

    #: Optional form used to configure authentication settings for an account.
    auth_form = None

    # These values are defaults that can be overridden in repository_plans
    # above.
    needs_authorization = False
    supported_scmtools = []
    form = None
    fields = []
    repository_fields = {}
    bug_tracker_field = None

    def __init__(self, account):
        assert account
        self.account = account

        self.client = self.client_class(self)

    def is_authorized(self):
        """Returns whether or not the account is currently authorized.

        An account may no longer be authorized if the hosting service
        switches to a new API that doesn't match the current authorization
        records. This function will determine whether the account is still
        considered authorized.
        """
        return False

    def get_password(self):
        """Returns the raw password for this hosting service.

        Not all hosting services provide this, and not all would need it.
        It's primarily used when building a Subversion client, or other
        SCMTools that still need direct access to the repository itself.
        """
        return None

    def is_ssh_key_associated(self, repository, key):
        """Returns whether or not the key is associated with the repository.

        If the ``key`` (an instance of :py:mod:`paramiko.PKey`) is present
        among the hosting service's deploy keys for a given ``repository`` or
        account, then it is considered associated. If there is a problem
        checking with the hosting service, an :py:exc:`SSHKeyAssociationError`
        will be raised.
        """
        raise NotImplementedError

    def associate_ssh_key(self, repository, key):
        """Associates an SSH key with a given repository

        The ``key`` (an instance of :py:mod:`paramiko.PKey`) will be added to
        the hosting service's list of deploy keys (if possible). If there
        is a problem uploading the key to the hosting service, a
        :py:exc:`SSHKeyAssociationError` will be raised.
        """
        raise NotImplementedError

    def authorize(self, username, password, hosting_url, credentials,
                  two_factor_auth_code=None, local_site_name=None,
                  *args, **kwargs):
        """Authorize an account for the hosting service.

        Args:
            username (unicode):
                The username for the account.

            password (unicode):
                The password for the account.

            hosting_url (unicode):
                The hosting URL for the service, if self-hosted.

            credentials (dict):
                All credentials provided by the authentication form. This
                will contain the username, password, and anything else
                provided by that form.

            two_factor_auth_code (unicode, optional):
                The two-factor authentication code provided by the user.

            local_site_name (unicode, optional):
                The Local Site name, if any, that the account should be
                bound to.

            *args (tuple):
                Extra unused positional arguments.

            **kwargs (dict):
                Extra keyword arguments containing values from the
                repository's configuration.

        Raises:
            reviewboard.hostingsvcs.errors.AuthorizationError:
                The credentials provided were not valid.

            reviewboard.hostingsvcs.errors.TwoFactorAuthCodeRequiredError:
                A two-factor authentication code is required to authorize
                this account. The request must be retried with the same
                credentials and with the ``two_factor_auth_code`` parameter
                provided.
        """
        raise NotImplementedError

    def check_repository(self, path, username, password, scmtool_class,
                         local_site_name, *args, **kwargs):
        """Checks the validity of a repository configuration.

        This performs a check against the hosting service or repository
        to ensure that the information provided by the user represents
        a valid repository.

        This is passed in the repository details, such as the path and
        raw credentials, as well as the SCMTool class being used, the
        LocalSite's name (if any), and all field data from the
        HostingServiceForm as keyword arguments.
        """
        return scmtool_class.check_repository(path, username, password,
                                              local_site_name)

    def get_file(self, repository, path, revision, *args, **kwargs):
        if not self.supports_repositories:
            raise NotImplementedError

        return repository.get_scmtool().get_file(path, revision, **kwargs)

    def get_file_exists(self, repository, path, revision, *args, **kwargs):
        if not self.supports_repositories:
            raise NotImplementedError

        return repository.get_scmtool().file_exists(path, revision, **kwargs)

    def get_branches(self, repository):
        """Get a list of all branches in the repositories.

        This should be implemented by subclasses, and is expected to return a
        list of Branch objects. One (and only one) of those objects should have
        the "default" field set to True.
        """
        raise NotImplementedError

    def get_commits(self, repository, branch=None, start=None):
        """Get a list of commits backward in history from a given point.

        This should be implemented by subclasses, and is expected to return a
        list of Commit objects (usually 30, but this is flexible depending on
        the limitations of the APIs provided.

        This can be called multiple times in succession using the "parent"
        field of the last entry as the start parameter in order to paginate
        through the history of commits in the repository.
        """
        raise NotImplementedError

    def get_change(self, repository, revision):
        """Get an individual change.

        This should be implemented by subclasses, and is expected to return a
        tuple of (commit message, diff), both strings.
        """
        raise NotImplementedError

    def get_remote_repositories(self, owner=None, owner_type=None,
                                filter_type=None, start=None, per_page=None):
        """Get a list of remote repositories for the owner.

        This should be implemented by subclasses, and is expected to return an
        APIPaginator providing pages of RemoteRepository objects.

        The ``start`` and ``per_page`` parameters can be used to control
        where pagination begins and how many results are returned per page,
        if the subclass supports it.

        ``owner`` is expected to default to a reasonable value (typically
        the linked account's username). The hosting service may also require
        an ``owner_type`` value that identifies what the ``owner`` means.
        This value is specific to the hosting service backend.

        Likewise, ``filter_type`` is specific to the hosting service backend.
        If supported, it may be used to filter the types of hosting services.
        """
        raise NotImplementedError

    def get_remote_repository(self, repository_id):
        """Get the remote repository for the ID.

        This should be implemented by subclasses, and is expected to return
        a RemoteRepository if found, or raise ObjectDoesNotExist if not found.
        """
        raise NotImplementedError

    @classmethod
    def get_repository_fields(cls, username, hosting_url, plan, tool_name,
                              field_vars):
        if not cls.supports_repositories:
            raise NotImplementedError

        # Grab the list of fields for population below. We have to do this
        # differently depending on whether or not this hosting service has
        # different repository plans.
        fields = cls._get_field(plan, 'repository_fields')

        new_vars = field_vars.copy()
        new_vars['hosting_account_username'] = username

        if cls.self_hosted:
            new_vars['hosting_url'] = hosting_url
            new_vars['hosting_domain'] = urlparse(hosting_url)[1]

        results = {}

        assert tool_name in fields

        for field, value in six.iteritems(fields[tool_name]):
            try:
                results[field] = value % new_vars
            except KeyError as e:
                logging.error('Failed to generate %s field for hosting '
                              'service %s using %s and %r: Missing key %s'
                              % (field, six.text_type(cls.name), value,
                                 new_vars, e),
                              exc_info=1)
                raise KeyError(
                    _('Internal error when generating %(field)s field '
                      '(Missing key "%(key)s"). Please report this.') % {
                        'field': field,
                        'key': e,
                    })

        return results

    def get_repository_hook_instructions(self, request, repository):
        """Returns instructions for setting up incoming webhooks.

        Subclasses can override this (and set
        `has_repository_hook_instructions = True` on the subclass) to provide
        instructions that administrators can see when trying to configure an
        incoming webhook for the hosting service.

        This is expected to return HTML for the instructions. The function
        is responsible for escaping any content.
        """
        raise NotImplementedError

    @classmethod
    def get_bug_tracker_requires_username(cls, plan=None):
        if not cls.supports_bug_trackers:
            raise NotImplementedError

        return ('%(hosting_account_username)s' in
                cls._get_field(plan, 'bug_tracker_field', ''))

    @classmethod
    def get_bug_tracker_field(cls, plan, field_vars):
        if not cls.supports_bug_trackers:
            raise NotImplementedError

        bug_tracker_field = cls._get_field(plan, 'bug_tracker_field')

        if not bug_tracker_field:
            return ''

        try:
            return bug_tracker_field % field_vars
        except KeyError as e:
            logging.error('Failed to generate %s field for hosting '
                          'service %s using %r: Missing key %s'
                          % (bug_tracker_field, six.text_type(cls.name),
                             field_vars, e),
                          exc_info=1)
            raise KeyError(
                _('Internal error when generating %(field)s field '
                  '(Missing key "%(key)s"). Please report this.') % {
                    'field': bug_tracker_field,
                    'key': e,
                })

    @classmethod
    def _get_field(cls, plan, name, default=None):
        if cls.plans:
            assert plan

            for plan_name, info in cls.plans:
                if plan_name == plan and name in info:
                    return info[name]

        return getattr(cls, name, default)

_hostingsvcs_urlpatterns = {}

class HostingServiceRegistry(EntryPointRegistry):
    """A registry for managing hosting services."""

    entry_point = 'reviewboard.hosting_services'
    lookup_attrs = ['hosting_service_id']

    errors = {
        ALREADY_REGISTERED: _(
            '"%(item)s" is already a registered hosting service.'
        ),
        LOAD_ENTRY_POINT: _(
            'Unable to load repository hosting service %(entry_point)s: '
            '%(error)s.'
        ),
        NOT_REGISTERED: _(
            '"%(attr_value)s" is not a registered hosting service.'
        ),
    }

    def __init__(self):
        super(HostingServiceRegistry, self).__init__()
        self._url_patterns = {}

    def unregister(self, service):
        """Unregister a hosting service.

        This will remove all registered URLs that the hosting service has
        defined.

        Args:
            service (type):
                The
                :py:class:`~reviewboard.hostingsvcs.service.HostingService`
                subclass.
        """
        super(HostingServiceRegistry, self).unregister(service)

        if service.hosting_service_id in self._url_patterns:
            cls_urlpatterns = self._url_patterns[service.hosting_service_id]
            hostingsvcs_urls.dynamic_urls.remove_patterns(cls_urlpatterns)
            del self._url_patterns[service.hosting_service_id]

    def process_value_from_entry_point(self, entry_point):
        """Load the class from the entry point.

        The ``id`` attribute will be set on the class from the entry point's
        name.

        Args:
            entry_point (pkg_resources.EntryPoint):
                The entry point.

        Returns:
            type:
            The :py:class:`HostingService` subclass.
        """
        cls = entry_point.load()
        cls.hosting_service_id = entry_point.name
        return cls

    def register(self, service):
        """Register a hosting service.

        This also adds the URL patterns defined by the hosting service. If the
        hosting service has a :py:attr:`HostingService.repository_url_patterns`
        attribute that is non-``None``, they will be automatically added.

        Args:
            service (type):
                The :py:class:`HostingService` subclass.
        """
        super(HostingServiceRegistry, self).register(service)

        if service.repository_url_patterns:
            cls_urlpatterns = patterns(
                '',
                url(r'^(?P<hosting_service_id>%s)/'
                    % re.escape(service.hosting_service_id),
                    include(service.repository_url_patterns)))

            self._url_patterns[service.hosting_service_id] = cls_urlpatterns
            hostingsvcs_urls.dynamic_urls.add_patterns(cls_urlpatterns)

_hosting_service_registry = HostingServiceRegistry()

def get_hosting_services():
    """Return the list of hosting services.

    Returns:
        list:
        The :py:class:`~reviewboard.hostingsvcs.service.HostingService`
        subclasses.
    """
    return list(_hosting_service_registry)

def get_hosting_service(name):
    """Return the hosting service with the given name.

    If the hosting service is not found, None will be returned.
    """
    try:
        return _hosting_service_registry.get('hosting_service_id', name)
    except ItemLookupError:
        return None

def register_hosting_service(name, cls):
    """Register a custom hosting service class.

    A name can only be registered once. A KeyError will be thrown if attempting
    to register a second time.

    Args:
        name (unicode):
            The name of the hosting service.

        cls (type):
            The hosting service class. This should be a subclass of
            :py:class:`~reviewboard.hostingsvcs.service.HostingService`.
    """
    cls.hosting_service_id = name
    _hosting_service_registry.register(cls)

def unregister_hosting_service(name):
    """Unregister a previously registered hosting service.

    Args:
        name (unicode):
            The name of the hosting service.
    """
    try:
        _hosting_service_registry.unregister_by_attr('hosting_service_id',
                                                     name)
    except ItemLookupError as e:
        logging.error('Failed to unregister unknown hosting service "%s"'
                      % name)
        raise e

@receiver(initializing, dispatch_uid='populate_hosting_services')
def _on_initializing(**kwargs):
    _hosting_service_registry.populate()


text:
package net.runelite.client.events;

import java.awt.TrayIcon;
import lombok.Value;

@Value
public class NotificationFired
{
	final String message;
	final TrayIcon.MessageType type;
}


text:
frequency
=========

A library for frequency analysis of ASCII text.

You feed the analyzer a corpus of text, be it English, source code, etc.
You can then score strings or byte arrays of content on a scale 0 - 1, depending on
how close they match the frequency and character occurance of the original corpus.

When training the analyzer, a larger corpus is better than a small one.
When scoring data, a larger input is better than a small one.

Install
=======
```
$ go get github.com/solvip/frequency
```

Example
=======
An example program using this library can be found at https://github.com/solvip/frequency-english

Usage
=====

Initializing and training the analyzer, where corpus.txt is a file containing your reference corpus
```
contents, _ := ioutil.ReadFile("corpus.txt")

a := frequency.NewAnalyzer()
a.Feed(contents)
```

Scoring content
```
score := a.ScoreString("This is a piece of english text.  The quick brown fox jumped over the lazy dog")
```

Saving the analyzer state
```
a.Save("/path/to/a/file.gob")
```

Restoring the analyzer state
```
a := frequency.New()
err := a.Restore("/path to/previously saved state")
if err != nil {
   ... maybe load data from corpus?
}
```

License
=======
Copyright 2014 Sölvi Páll Ásgeirsson
The MIT License


text:
using System;
using SS.Integration.Adapter.Model.Interfaces;
using log4net;

namespace SS.Integration.Adapter.Model
{
	public class CachedObjectStoreWithPersistance<T> : CachedObjectStore<T> where T : class
	{
		private readonly IObjectProvider<T> _persistanceStore;
		private readonly ILog _logger = LogManager.GetLogger(typeof(CachedObjectStoreWithPersistance<T>));

		public CachedObjectStoreWithPersistance(IObjectProvider<T> persistanceStore, string cacheUniqueId,
												int cacheExpiryInSecs = 60)
			: base(cacheUniqueId, cacheExpiryInSecs)
		{
			_persistanceStore = persistanceStore;
		}

		public override T GetObject(string id)
		{
			try
			{
				var item = base.GetObject(id);
				var notInCache = item == null;

				if (notInCache)
					item = _persistanceStore.GetObject(id);

				if (notInCache && item != null)
				{
					base.SetObject(id, item);
				}

				return item;
			}
			catch (Exception ex)
			{
				_logger.Error(string.Format("Deserialization error occured for item with id={0}. Storage file must be corrupted and will be removed", id), ex);

				Remove(id);

			}

			return null;
		}

		public override bool Remove(string id)
		{
			_persistanceStore.Remove(id);
			base.Remove(id);
			return true;
		}

		public override void SetObject(string id, T item)
		{
			base.SetObject(id, item);
			_persistanceStore.SetObject(id, item);
		}
	}
}


text:
package gravity;

public interface ComponentKey
{
    Class getComponentInterface();
}


text:
package hackerrank;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Scanner;

/**
 * Standard snake and ladder problem.
 *
 * @author harish.sharma
 *
 */
public class SnakeAndLadders {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        for (int i = 0; i < t; i++) {
            int n = in.nextInt();
            Map<Integer, Integer> mapOfSnakesAndLadders = new HashMap<>();
            for (int j = 0; j < n; j++) {
                mapOfSnakesAndLadders.put(in.nextInt(), in.nextInt());
            }
            int m = in.nextInt();
            for (int j = 0; j < m; j++) {
                mapOfSnakesAndLadders.put(in.nextInt(), in.nextInt());
            }
            System.out.println(solve(mapOfSnakesAndLadders));
        }
        in.close();
    }

    private static int solve(Map<Integer, Integer> mapOfSnakesAndLadders) {
        Queue<Integer> queue = new LinkedList<>();
        queue.add(1);
        int[] values = new int[101];
        boolean finished = false;
        int res = -1;
        while (!queue.isEmpty() && !finished) {
            int head = queue.poll();
            for (int i = 1; i <= 6; i++) {
                int next = mapOfSnakesAndLadders.containsKey(head + i) ? mapOfSnakesAndLadders.get(head + i) : head + i;
                if (values[next] == 0) {
                    values[next] = values[head] + 1;
                    queue.add(next);
                }
                if (next == 100) {
                    finished = true;
                    res = next;
                    break;
                }
            }
        }
        if (res > 0) {
            return values[res];
        }
        return -1;
    }
}


text:
package com.blogspot.aptgetmoo.dhjclient.company;

import java.io.IOException;

import org.apache.commons.lang3.StringEscapeUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;
import org.jsoup.select.Elements;

import com.blogspot.aptgetmoo.dhjclient.parser.Webpage;

/**
 * @author Dzul Nizam
 */
public class CompanyFinder implements ICompanyFinder {

    private Webpage mPage;

    /**
     * @param 	pPage 	CompanyPage
     */
    public CompanyFinder(CompanyPage pPage) {
        mPage = pPage;
    }

    @Override
    public Company find(String pCompCode) throws IOException {
        ((CompanyPage) mPage).setCompanyCode(pCompCode);

        Document doc;
        doc = Jsoup.parse(mPage.getParseable());
        Company company = new Company(pCompCode);

        if (doc != null) {
            company = parseRows(company, doc.select("table table tr"));
        }

        return company;
    }

    private Company parseRows(Company pCom, Elements pRows) {
        if (pRows.size() < 9) return null;

        Elements temp;
        if ((temp = pRows.get(1).select("td")).size() > 0) pCom.name = cleanUp(temp.get(1).text());
        if (pCom.name.trim().length() == 0) {
            // That's it, no need further processing, the company doesn't exists
            return null;
        }

        if ((temp = pRows.get(2).select("td")).size() > 0) pCom.address = cleanUp(temp.get(1).html());
        if ((temp = pRows.get(4).select("td")).size() > 0) pCom.phone = temp.get(1).text();
        if ((temp = pRows.get(5).select("td")).size() > 0) pCom.fax = temp.get(1).text();
        if ((temp = pRows.get(6).select("td")).size() > 0) pCom.email = temp.get(1).text();
        if ((temp = pRows.get(7).select("td")).size() > 0) pCom.web = temp.get(1).text();
        if ((temp = pRows.get(8).select("td")).size() > 0) pCom.jakimRefNo = temp.get(1).text();
        if ((temp = pRows.get(9).select("td")).size() > 0) pCom.jakimOfficer = temp.get(1).text();

        return pCom;
    }

    private String cleanUp(String pStr) {
        final Whitelist whiteList = new Whitelist();
        pStr = StringEscapeUtils.unescapeHtml4(Jsoup.clean(pStr, whiteList.addTags("br")));

        return pStr.replace("
", "")
            .replace("
", "")
            // .replace(" ", " ")
            .replaceAll("(?m)(?:^|\\G) ", "")
            .replaceAll("\r?\n", "\n");
    }

}


text:
{% load i18n %}

{% url 'dashboard' as url_dashboard %}

{% if question.is_active %}

			{% if not question.hide_data %}
				{% if question.votes > 0 %}
					{% if question.data_require_vote %}
						{% if voted %}
							{% include 'questions/donut_chart.html' with replies_ordered=replies_ordered replies=replies %}
						{% else %}

{% trans "To see the question results, you have to vote first" %}

						{% endif %}
					{% else %}
						{% include 'questions/donut_chart.html' with replies_ordered=replies_ordered replies=replies %}
					{% endif %}
				{% else %}

{% trans 'There are no votes for this question yet' %}.

				{% endif %}
			{% else  %}

{% trans "The question results are not available at the moment" %}.

			{% endif %}

{% elif not question.is_active and question.time_to_begin %}

{% else %}

			{% if not question.hide_data %}
				{% if question.votes > 0 %}
					{% include 'questions/donut_chart.html' with replies_ordered=replies_ordered replies=replies %}
				{% else %}

{% trans 'There are no votes for this question yet' %}.

				{% endif %}
			{% else  %}

{% trans "The question results are not available at the moment" %}

			{% endif %}

{% endif %}


text:
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>popularioty.analytics</groupId>
    <artifactId>popularioty-analytics</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>
  <groupId>popularioty.analytics.feedback</groupId>
  <artifactId>popularioty-analytics-feedback</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>popularioty-analytics-feedback</name>
  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
  	<dependency>
     <groupId>popularioty.commons</groupId>
     <artifactId>popularioty-commons</artifactId>
     <version>0.0.1</version>
    </dependency>
    <dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-hdfs</artifactId>
    <version>2.6.0</version>
   </dependency>
   <dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-auth</artifactId>
    <version>2.6.0</version>
   </dependency>
   <dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-common</artifactId>
    <version>2.6.0</version>
   </dependency>
   <dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-client</artifactId>
    <version>2.2.0</version>
    <scope>provided</scope>
  </dependency>
  <dependency>
	<groupId>org.apache.mrunit</groupId>
	<artifactId>mrunit</artifactId>
	<version>1.1.0</version>
	<classifier>hadoop2</classifier>
  </dependency>
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.3.0</version>
  </dependency>
  <dependency>
    <groupId>com.fasterxml.jackson.jaxrs</groupId>
    <artifactId>jackson-jaxrs-json-provider</artifactId>
    <version>2.3.0</version>
  </dependency>
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.3.0</version>
  </dependency>
  <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
  </dependency>
  </dependencies>
  <build>
   <plugins>
   <plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-compiler-plugin</artifactId>
     <configuration>
       <source>1.7</source>
       <target>1.7</target>
     </configuration>
    </plugin>
    <plugin>
      <artifactId>maven-assembly-plugin</artifactId>
      <version>2.2.1</version>
      <configuration>
        <descriptors>
          <descriptor>src/main/assembly/hadoop-job.xml</descriptor>
        </descriptors>
        <archive>
          <manifest>
            <mainClass>popularioty.analytics.feedback.start.HadoopJobs</mainClass>
          </manifest>
        </archive>
      </configuration>
      <executions>
        <execution>
          <id>make-assembly</id>
          <phase>package</phase>
          <goals>
            <goal>single</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
   </plugins>
 </build>
</project>


text:
<?xml version="1.0" encoding="UTF-8"?>

	<item value="250" key="org.eclipse.jdt.internal.debug.ui.actions.PopupInspectAction$2DIALOG_HEIGHT"/>
	<item value="300" key="org.eclipse.jdt.internal.debug.ui.actions.PopupInspectAction$2DIALOG_WIDTH"/>

		<item value="320" key="DIALOG_WIDTH"/>
		<item value="1|Ubuntu|11.0|0|GTK|1|" key="DIALOG_FONT_NAME"/>
		<item value="394" key="DIALOG_HEIGHT"/>

		<item value="800" key="DIALOG_WIDTH"/>
		<item value="1|Microsoft YaHei UI|9.0|0|WINDOWS|1|-12|0|0|0|400|0|0|0|1|0|0|0|0|Microsoft YaHei UI" key="DIALOG_FONT_NAME"/>
		<item value=", org.eclipse.jdt.launching.localJavaApplication, " key="org.eclipse.debug.ui.EXPANDED_NODES"/>
		<item value="762" key="org.eclipse.debug.ui.DIALOG_SASH_WEIGHTS_2"/>
		<item value="640" key="DIALOG_HEIGHT"/>
		<item value="237" key="org.eclipse.debug.ui.DIALOG_SASH_WEIGHTS_1"/>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

       Copyright 2009-2016 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.apache.ibatis.submitted.keygen.CountryMapper" >
  <insert id="insertList" parameterType="org.apache.ibatis.submitted.keygen.Country" useGeneratedKeys="true" keyProperty="id">
      insert into country (countryname,countrycode)
      values
      <foreach collection="list" separator="," item="country">
          (#{country.countryname},#{country.countrycode})
      </foreach>
  </insert>
  <insert id="insertUndefineKeyProperty" parameterType="org.apache.ibatis.submitted.keygen.Country" useGeneratedKeys="true" keyProperty="country_id">
      insert into country (countryname,countrycode) values (#{countryname},#{countrycode})
  </insert>
</mapper>


text:
namespace mediapipe {

// Returns the path to the directory where trace logs will be stored by default.
// If the function is unable to find an appropriate directory, it returns an
// error.
StatusOr<std::string> GetDefaultTraceLogDirectory();

// Given a log file path, this function provides an absolute path with which
// it can be accessed as a file.  Enclosing directories are created as needed.
StatusOr<std::string> PathToLogFile(const std::string& path);

}  // namespace mediapipe

#endif  // MEDIAPIPE_FRAMEWORK_PROFILER_PROFILER_RESOURCE_UTIL_H_


text:
#ifndef logging_logging_tssstorage_H
#define logging_logging_tssstorage_H

#ifndef __cplusplus
#error This is a C++ include file and cannot be used from plain C
#endif

#include <ace/Hash_Map_Manager.h>
#include <ace/Task.h>

class LoggingTSSStorage
{
  public:
    LoggingTSSStorage() : m_threadName(0),
    tmpStr((size_t)512)
	{
	    m_ldata.open(3);
	    m_attributes.open(3);
	    clear();
	}

    ~LoggingTSSStorage()
	{
	    if (m_threadName)
		{
		delete[] m_threadName;
		m_threadName = 0;
		}
	    m_ldata.close();
	    m_attributes.close();
	}

    void clear()
	{
	    m_logEntryType = 0;
	    m_routine = 0;
	    m_file = 0;
	    m_line = 0UL;
	    sourceObject_m = 0;
	    audience_m = 0;
            array_m = 0;
            antenna_m = 0;
	    m_lflags = 0;
	    m_stackId = 0;
	    m_stackLevel = 0;
	    m_context = 0;
	    m_uri = 0;
	    m_logId = 0;
	    m_host = 0;
	    m_privateFlags = 0;
	    logLevelLocalType_m = 6;
	    logLevelRemoteType_m = 6;
	    m_ldata.unbind_all();
	    m_attributes.unbind_all();
	}

    void resetAttributes() { m_attributes.unbind_all(); };

    const ACE_TCHAR * routine() { return m_routine; };
    void routine(const ACE_TCHAR * routine) { m_routine=routine; };

    const ACE_TCHAR * file() { return m_file; };
    void file(const ACE_TCHAR * fileName) { m_file=fileName; };

    const unsigned long line() { return m_line; };
    void line(unsigned long lineNumber) { m_line=lineNumber; };

    const ACE_TCHAR *
    sourceObject() { return sourceObject_m; };

    void
    sourceObject(const ACE_TCHAR * soName) { sourceObject_m = soName; };

    const ACE_TCHAR *
    audience() { return audience_m; };

    void
    audience(const ACE_TCHAR * soName) { audience_m = soName; };

    const ACE_TCHAR *
    array() { return array_m; };

    void
    array(const ACE_TCHAR * soName) { array_m = soName; };

    const ACE_TCHAR *
    antenna() { return antenna_m; };

    void
    antenna(const ACE_TCHAR * soName) { antenna_m = soName; };

    unsigned int flags() { return m_lflags; };
    void flags(unsigned int flags) { m_lflags=flags; };

    const ACE_TCHAR * threadName() { return m_threadName; };
    void threadName(const ACE_TCHAR * name)
	{
	    if (m_threadName)
		{
		delete[] m_threadName;
		m_threadName = 0;
		}

	    if (name)
		{
		m_threadName = new ACE_TCHAR[ACE_OS::strlen(name)+1];
		ACE_OS::strcpy(m_threadName, name);
		}
	};

    const ACE_TCHAR * logEntryType() { return m_logEntryType; };
    void logEntryType(const ACE_TCHAR * logEntryType) { m_logEntryType=logEntryType; };

    const ACE_TCHAR * context() { return m_context; };
    void context(const ACE_TCHAR * context) { m_context=context; };

    int stackLevel() { return m_stackLevel; };
    void stackLevel(int stackLevel) { m_stackLevel=stackLevel; };

    const ACE_TCHAR * stackId() { return m_stackId; };
    void stackId(const ACE_TCHAR * stackId) { m_stackId=stackId; };

    const ACE_TCHAR * logId() { return m_logId; };
    void logId(const ACE_TCHAR * logId) { m_logId=logId; };

    const ACE_TCHAR * uri() { return m_uri; };
    void uri(const ACE_TCHAR * uri) { m_uri=uri; };

    const ACE_TCHAR * host() { return m_host; };
    void host(const ACE_TCHAR * host) { m_host=host; };

    int privateFlags() { return m_privateFlags; };
    void privateFlags(int privateFlags) { m_privateFlags=privateFlags; };

    int logLevelLocalType() { return logLevelLocalType_m; };
    void logLevelLocalType(int logLevelLocalType) { logLevelLocalType_m=logLevelLocalType; };

    int logLevelRemoteType() { return logLevelRemoteType_m; };
    void logLevelRemoteType(int logLevelRemoteType) { logLevelRemoteType_m=logLevelRemoteType; };
    typedef ACE_Hash_Map_Manager <ACE_CString, ACE_CString, ACE_Thread_Mutex> HASH_MAP;
    typedef ACE_Hash_Map_Iterator <ACE_CString, ACE_CString, ACE_Thread_Mutex> HASH_MAP_ITER;
    typedef ACE_Hash_Map_Entry <ACE_CString, ACE_CString> HASH_MAP_ENTRY;

    void addAttribute(const ACE_TCHAR * name,  const ACE_TCHAR * value)
	{
	    m_attributes.bind(name, value);
	};

    void addData(const ACE_TCHAR * name,  const ACE_TCHAR * value)
	{
	    m_ldata.bind(name, value);
	};

    HASH_MAP_ITER getAttributes() {
	return HASH_MAP_ITER(m_attributes);
    };

    HASH_MAP_ITER getData() {
	return HASH_MAP_ITER(m_ldata);
    };

    ACE_CString& getTmpStr(){
		return tmpStr;
    }
  private:

    ACE_TCHAR * m_threadName;		// deep copy

    const ACE_TCHAR * m_logEntryType;
    const ACE_TCHAR * m_routine;
    const ACE_TCHAR * m_file;
    unsigned long m_line;
    const ACE_TCHAR * sourceObject_m;
    const ACE_TCHAR * audience_m;
    const ACE_TCHAR * array_m;
    const ACE_TCHAR * antenna_m;
    unsigned int m_lflags;
    const ACE_TCHAR * m_stackId;
    int m_stackLevel;
    const ACE_TCHAR * m_context;
    const ACE_TCHAR * m_logId;
    const ACE_TCHAR * m_uri;
    const ACE_TCHAR * m_host;

    // used internally by logger
    // bit 0 (LSB) = prohibit stdout
    // bit 1       = prohibit remote
    int m_privateFlags;
    int logLevelLocalType_m;
    int logLevelRemoteType_m;

    LoggingTSSStorage::HASH_MAP m_ldata;
    LoggingTSSStorage::HASH_MAP m_attributes;
    // temporary string that can be used to create log message on the fly.
    ACE_CString tmpStr;
};

#endif /*!logging_logging_tssstorage_H*/


text:
require File.dirname(__FILE__) + '/../spec_helper'

#########################################################################################################
describe "persitence of aln_path", :shared => true do

  it "should occur when a termination is added to connection" do
    @p.should_not persist
    @p << @t
    @p.should persist
  end

end

#########################################################################################################
describe "destruction of aln_path", :shared => true do

  def create_destroy_path
    @p << @t
    @p.should persist
    AlnResource.to_aln_resource(@t).should persist
    AlnTermination.to_aln_termination(@t).should persist
    @t.should persist
    @p.destroy
    @p.should_not persist
    AlnResource.to_aln_resource(@t).should persist
    AlnTermination.to_aln_termination(@t).should persist
    @t.should persist
  end

  it "should not destroy contained terminations" do
    create_destroy_path
  end

  it "should set termination path association to nil" do
    create_destroy_path
    @t.reload
    @t.aln_path_id.should be_nil
    @t.aln_path.should be_nil
  end

end

#########################################################################################################
describe "persistence of terminations from aln_path", :shared => true do

  it "should occur when a termination is added to path" do
    @t.should_not persist
    @p << @t
    @t.should persist
  end

end

#########################################################################################################
describe "management of aln_terminations in a connection" do

  before(:each) do
    @t = AlnTermination.new(model_data[:aln_termination_supported_1])
    @p = AlnPath.new(:termination_type => 'AlnTermination')
  end

  after(:each) do
    @t.destroy
    @p.destroy
  end

  it_should_behave_like "persitence of aln_path"

  it_should_behave_like "destruction of aln_path"

  it_should_behave_like "persistence of terminations from aln_path"

end

#########################################################################################################
describe "management of aln_termination descendants in a connection" do

  before(:each) do
    @t = IpTermination.new(model_data[:ip_termination_remove_1])
    @p = AlnPath.new(:termination_type => 'IpTermination')
  end

  after(:each) do
    @t.destroy
    @p.destroy
  end

  it_should_behave_like "persitence of aln_path"

  it_should_behave_like "destruction of aln_path"

  it_should_behave_like "persistence of terminations from aln_path"

end


text:
typedef enum {
    kTSDropDownPanelState_Hidden,
    kTSDropDownPanelState_Show,
    kTSDropDownPanelState_Shown,
    kTSDropDownPanelState_Hide
} TSDropDownPanelState;

@interface TSTabViewWithDropDownPanel ()
{
    UIView *_dropDownPanelContainer;
    UIView *_dropDownPanelClipContainer;
    BOOL _dropDownPanelMovedDown; // Remember direction of last panel's move
    TSDropDownPanelState _dropDownPanelState;
}

@end

@implementation TSTabViewWithDropDownPanel

- (id)initWithFrame:(CGRect)rect navigationMenu:(TSNavigationStripView *)navigationMenu
{
    VerboseLog();
    self = [super initWithFrame:rect navigationMenu:navigationMenu];
    if (self)
    {
        _showPanelBelowNavigationMenu = YES;
        _showPanelOnSelectedSectionTap = YES;
        _shouldAdjustTabsContainerSize = YES;
        _dropDownPanelState = kTSDropDownPanelState_Hidden;
        _dropDownPanelContainer = [[UIView alloc] initWithFrame:CGRectMake(0, (_showPanelBelowNavigationMenu ? navigationMenu.frame.size.height : 0), rect.size.width, 0)];
        _dropDownPanelContainer.backgroundColor = [UIColor clearColor];
        _dropDownPanelContainer.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        _dropDownPanelContainer.clipsToBounds = NO;
        [self insertSubview:_dropDownPanelContainer belowSubview:navigationMenu];

        _dropDownPanelClipContainer = [[UIView alloc] initWithFrame:_dropDownPanelContainer.bounds];
        _dropDownPanelClipContainer.backgroundColor = [UIColor clearColor];
        _dropDownPanelClipContainer.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _dropDownPanelClipContainer.clipsToBounds = YES;
        [_dropDownPanelContainer addSubview:_dropDownPanelClipContainer];
    }
    return self;
}

#pragma mark - Setters & getters

- (void)setAttachedPanel:(UIView *)attachedPanel
{
    VerboseLog();
    if(_attachedPanel == attachedPanel)
        return;
    if(_attachedPanel)
    {
        [_attachedPanel removeFromSuperview];
    }
    _attachedPanel = attachedPanel;
    if(_attachedPanel)
    {
        _dropDownPanelContainer.layer.shadowColor = _attachedPanel.layer.shadowColor;
        _dropDownPanelContainer.layer.shadowOffset = _attachedPanel.layer.shadowOffset;
        _dropDownPanelContainer.layer.shadowOpacity = _attachedPanel.layer.shadowOpacity;
        _dropDownPanelContainer.layer.shadowRadius = _attachedPanel.layer.shadowRadius;

        [_dropDownPanelClipContainer addSubview:_attachedPanel];
        _attachedPanel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
        _attachedPanel.frame = CGRectMake(0, _dropDownPanelContainer.frame.size.height - _attachedPanel.frame.size.height, _dropDownPanelContainer.frame.size.width, _attachedPanel.frame.size.height);
    }
}

- (void)setshowPanelBelowNavigationMenu:(BOOL)showPanelBelowNavigationMenu
{
    _showPanelBelowNavigationMenu = showPanelBelowNavigationMenu;
    [self updateComponentsLayout];
}

- (BOOL)panelIsHidden
{
    return (_dropDownPanelState == kTSDropDownPanelState_Hidden);
}

- (void)showDropDownPanelWithAnimation:(BOOL)animated
{
    VerboseLog();
    if(_attachedPanel)
    {
        if(self.delegate && [self.delegate respondsToSelector:@selector(tabViewWithDropDownPanel:willShowPanel:animated:)])
        {
            [self.delegate tabViewWithDropDownPanel:self willShowPanel:_attachedPanel animated:animated];
        }
        _dropDownPanelState = kTSDropDownPanelState_Show;
        _scrollView.scrollEnabled = NO;
        _dropDownPanelContainer.hidden = NO;
        [TSUtils performViewAnimationBlock:^{
            VerboseLog();
            _dropDownPanelContainer.frame = CGRectMake(_dropDownPanelContainer.frame.origin.x, _dropDownPanelContainer.frame.origin.y, _dropDownPanelContainer.frame.size.width, _attachedPanel.frame.size.height);
             [self updateComponentsLayout];
        } withCompletion:^{
            VerboseLog();
            if(_dropDownPanelState == kTSDropDownPanelState_Show)
            {
                _dropDownPanelState = kTSDropDownPanelState_Shown;
                _scrollView.scrollEnabled = YES;
                if(self.delegate && [self.delegate respondsToSelector:@selector(tabViewWithDropDownPanel:didShowPanel:)])
                {
                    [self.delegate tabViewWithDropDownPanel:self didShowPanel:_attachedPanel];
                }
            }
        } animated:animated];
    }
}

- (void)hideDropDownPanelWithAnimation:(BOOL)animated
{
    VerboseLog();
    if(_attachedPanel)
    {
        if(self.delegate && [self.delegate respondsToSelector:@selector(tabViewWithDropDownPanel:willHidePanel:animated:)])
        {
            [self.delegate tabViewWithDropDownPanel:self willHidePanel:_attachedPanel animated:animated];
        }
        _dropDownPanelState = kTSDropDownPanelState_Hide;
        _scrollView.scrollEnabled = NO;
        [TSUtils performViewAnimationBlock:^{
            VerboseLog();
            _dropDownPanelContainer.frame = CGRectMake(_dropDownPanelContainer.frame.origin.x, _dropDownPanelContainer.frame.origin.y, _dropDownPanelContainer.frame.size.width, 0);
            [self updateComponentsLayout];
        } withCompletion:^{
            VerboseLog();
            if(_dropDownPanelState == kTSDropDownPanelState_Hide)
            {
                _scrollView.scrollEnabled = YES;
                _dropDownPanelContainer.hidden = YES;
                _dropDownPanelState = kTSDropDownPanelState_Hidden;
                if(self.delegate && [self.delegate respondsToSelector:@selector(tabViewWithDropDownPanel:didHidePanel:)])
                {
                    [self.delegate tabViewWithDropDownPanel:self didHidePanel:_attachedPanel];
                }
            }
        } animated:animated];
    }
}

- (void)movePanel:(CGFloat)delta finished:(BOOL)finished
{
    VerboseLog();
    if(_attachedPanel)
    {
        CGFloat height = MAX(0, MIN(_dropDownPanelContainer.frame.size.height + delta, _attachedPanel.frame.size.height));
        _dropDownPanelContainer.hidden = (height == 0);
        _scrollView.scrollEnabled = NO;
        if(height != _dropDownPanelContainer.frame.size.height)
        {
            _dropDownPanelMovedDown = (height > _dropDownPanelContainer.frame.size.height);
        }
        if(finished)
        {
            const CGFloat threshold = 0.1f * _attachedPanel.frame.size.height;
            if(_dropDownPanelContainer.frame.size.height < threshold ||
               (!_dropDownPanelMovedDown && _dropDownPanelContainer.frame.size.height < _attachedPanel.frame.size.height - threshold))
            {
                [self hideDropDownPanelWithAnimation:YES];
            }
            else
            {
                [self showDropDownPanelWithAnimation:YES];
            }
        }
        else
        {
            _dropDownPanelContainer.frame = CGRectMake(_dropDownPanelContainer.frame.origin.x, _dropDownPanelContainer.frame.origin.y, _dropDownPanelContainer.frame.size.width, height);
            [self updateComponentsLayout];
        }
    }
}

#pragma mark - Update layout

- (void)updateComponentsLayout
{
    VerboseLog();
    CGPoint leftCorner = CGPointMake(self.navigationMenuEdgeInsets.left, self.navigationMenuEdgeInsets.top);
    CGPoint rightCorner = CGPointMake(self.frame.size.width - self.navigationMenuEdgeInsets.right, self.navigationMenuEdgeInsets.top);
    CGRect navigationMenuRect = CGRectMake(leftCorner.x,
                                           leftCorner.y,
                                           rightCorner.x - leftCorner.x,
                                           self.navigationMenu.frame.size.height);
    CGRect dropDownPanelRect = CGRectMake(navigationMenuRect.origin.x,
                                          CGRectGetMaxY(navigationMenuRect),
                                          navigationMenuRect.size.width,
                                          _dropDownPanelContainer.frame.size.height);

    if(!_showPanelBelowNavigationMenu)
    {
        // swap views location
        dropDownPanelRect = CGRectMake(dropDownPanelRect.origin.x, navigationMenuRect.origin.y, dropDownPanelRect.size.width,dropDownPanelRect.size.height);
        navigationMenuRect = CGRectOffset(navigationMenuRect,0,_dropDownPanelContainer.frame.size.height);
    }

    self.navigationMenu.frame = navigationMenuRect;

    _dropDownPanelContainer.frame = dropDownPanelRect;

    // if _navigationMenuEdgeInsets is not Zero, then calculate frame for _scrollView relative to root view bounds
    if(self.navigationMenuEdgeInsets.left   != UIEdgeInsetsZero.left ||
       self.navigationMenuEdgeInsets.right  != UIEdgeInsetsZero.right ||
       self.navigationMenuEdgeInsets.top    != UIEdgeInsetsZero.top ||
       self.navigationMenuEdgeInsets.bottom != UIEdgeInsetsZero.bottom)
    {
         // -> (navigationMenu is above scrollView)
        leftCorner = CGPointMake(self.contentViewEdgeInsets.left, self.contentViewEdgeInsets.top);
        rightCorner = CGPointMake(self.frame.size.width - self.contentViewEdgeInsets.right, self.frame.size.height - self.contentViewEdgeInsets.bottom);
        _scrollView.frame = CGRectMake(leftCorner.x, leftCorner.y, rightCorner.x - leftCorner.x, rightCorner.y - leftCorner.y);
    }
    else // if _navigationMenuEdgeInsets is Zero, then calculate frame for _scrollView relative to _navigationMenu
    {
        // -> (navigationMenu is next to scrollView)
        CGFloat height = self.navigationMenu.frame.size.height + (self.shouldAdjustTabsContainerSize ? dropDownPanelRect.size.height : 0);
        leftCorner = CGPointMake(self.contentViewEdgeInsets.left, height + self.contentViewEdgeInsets.top);
        rightCorner = CGPointMake(self.frame.size.width - self.contentViewEdgeInsets.right, self.frame.size.height - self.contentViewEdgeInsets.bottom);
        _scrollView.frame = CGRectMake(leftCorner.x, leftCorner.y, rightCorner.x - leftCorner.x, rightCorner.y - leftCorner.y);
    }
}

#pragma mark - TSNavigationStripViewDelegate

- (void)navigationStripDidRecognizeTapOnSelectedSection:(TSNavigationStripView *)navigationStripView
{
    VerboseLog();
    if(self.showPanelOnSelectedSectionTap)
    {
        if([self panelIsHidden])
        {
            [self showDropDownPanelWithAnimation:YES];
        }
        else
        {
            [self hideDropDownPanelWithAnimation:YES];
        }
    }
}

@end


text:
package ch.romix.wichtel.integration;

import java.net.URI;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.client.RestTemplate;

import ch.romix.wichtel.WichtelApp;
import ch.romix.wichtel.rest.WichtelEvent;

import static org.hamcrest.Matchers.is;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = WichtelApp.class)
@WebAppConfiguration
@IntegrationTest({"server.port=0"})
public class EventResourceTest {

  @Value("${local.server.port}")
  private int port;

  private RestTemplate restTemplate = new RestTemplate();

  @Test
  public void testAddingAndReadingWichtelEntry() {
    WichtelEvent eventToPost = new WichtelEvent();
    eventToPost.setName("Weihnachten 2014");
    ResponseEntity<Void> response = restTemplate.postForEntity("http://localhost:" + port + "/rest/event/", eventToPost, Void.class);
    assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
    URI locationOfNewEvent = response.getHeaders().getLocation();
    assertNotNull(locationOfNewEvent);
    WichtelEvent eventRead = restTemplate.getForObject(locationOfNewEvent, WichtelEvent.class);
    assertThat(eventRead.getName(), is(eventToPost.getName()));
  }
}


text:
package grim

import (
	"sync"

	"golang.org/x/net/context"
)

// GrimReaper is a task runner which will wait until all the tasks
// are complete until continuing. Reapers can also kill tasks prematurely if
// they are listening to the given context.
type GrimReaper interface {
	// New creates a sub-reaper which is attached to the parent context. If
	// the parent context is killed, so are the children. However, Wait must
	// still be called for child reapers.
	New() GrimReaper

	// SpawnFunc starts a new goroutine for the given function. The task should
	// return as soon as possible after the context completes.
	SpawnFunc(TaskFunc)

	// Spawn starts a new goroutine for the given Task. The task should
	// return as soon as possible after the context completes.
	Spawn(Task)

	// Kill sends a message to all running tasks to stop. If child reapers
	// have also been created, they will be triggered to stop as well.
	Kill()

	// Wait will block until all tasks have completed. This will NOT block
	// until chlid reapers are finished. Each reaper must call wait
	// independently.
	Wait()

	// Dead returns the underlying net.Context done channel.
	Dead() <-chan struct{}
}

// Reaper returns an implementation of the GrimReaper interface.
func Reaper() GrimReaper {
	var wg sync.WaitGroup
	ctx, cancel := context.WithCancel(context.Background())
	return &reaper{wg, ctx, cancel}
}

// ReaperWithContext creates a new GrimReaper implementation and uses the given
// context as the parent context.
func ReaperWithContext(c context.Context) GrimReaper {
	var wg sync.WaitGroup
	ctx, cancel := context.WithCancel(c)
	return &reaper{wg, ctx, cancel}
}

// TaskFunc is a killable function which runs in a separate go routine. In order to fulfill the contract the function MUST listen to the context and exit if it fires.
type TaskFunc func(context.Context)

type Task interface {
	Execute(context.Context)
}

// reaper implements the GrimReaper interface.
type reaper struct {
	wg     sync.WaitGroup
	ctx    context.Context
	cancel context.CancelFunc
}

// SpawnFunc runs a task.
func (r *reaper) SpawnFunc(t TaskFunc) {
	r.wg.Add(1)
	c, _ := context.WithCancel(r.ctx)
	go func(ctx context.Context) {
		defer r.wg.Done()
		t(ctx)
	}(c)
}

// Spawn runs a task.
func (r *reaper) Spawn(t Task) {
	r.wg.Add(1)
	c, _ := context.WithCancel(r.ctx)
	go func(ctx context.Context) {
		defer r.wg.Done()
		t.Execute(ctx)
	}(c)
}

// Wait blocks until all tasks have completed.
func (r *reaper) Wait() {
	r.wg.Wait()
}

// Kill cancels the context and waits for all tasks to exit.
func (r *reaper) Kill() {
	r.cancel()
	// r.Wait()
}

// New creates a new reaper with the current context as the parent context of
// the new reaper.
func (r *reaper) New() GrimReaper {
	return ReaperWithContext(r.ctx)
}

func (r *reaper) Dead() <-chan struct{} {
	return r.ctx.Done()
}