text:
package com.vondear.rxtools.view.ticker;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Build;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Interpolator;

import com.vondear.rxtools.R;

/**
 * The primary view for showing a ticker text view that handles smoothly scrolling from the
 * current text to a given text. The scrolling behavior is defined by
 * {@link #setCharacterList(char[])} which dictates what characters come in between the starting
 * and ending characters.
 *
 *
This class primarily handles the drawing customization of the ticker view, for example
 * setting animation duration, interpolator, colors, etc. It ensures that the canvas is properly
 * positioned, and then it delegates the drawing of each column of text to
 * {@link RxTickerColumnManager}.
 *
 *
This class's API should behave similarly to that of a {@link android.widget.TextView}.
 * However, I chose to extend from {@link View} instead of {@link android.widget.TextView}
 * because it allows me full flexibility in customizing the drawing and also support different
 * customization attributes as they are implemented.
 */
public class RxTickerView extends View {
    private static final int DEFAULT_TEXT_SIZE = 12;
    private static final int DEFAULT_TEXT_COLOR = Color.BLACK;
    private static final int DEFAULT_ANIMATION_DURATION = 350;
    private static final Interpolator DEFAULT_ANIMATION_INTERPOLATOR =
            new AccelerateDecelerateInterpolator();
    private static final int DEFAULT_GRAVITY = Gravity.START;

    protected final Paint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);

    private final RxTickerDrawMetrics metrics = new RxTickerDrawMetrics(textPaint);
    private final RxTickerColumnManager columnManager = new RxTickerColumnManager(metrics);
    private final ValueAnimator animator = ValueAnimator.ofFloat(1f);

    // Minor optimizations for re-positioning the canvas for the composer.
    private final Rect viewBounds = new Rect();

    private int lastMeasuredDesiredWidth, lastMeasuredDesiredHeight;

    // View attributes, defaults are set in init().
    private float textSize;
    private int textColor;
    private long animationDurationInMillis;
    private Interpolator animationInterpolator;
    private int gravity;
    private boolean animateMeasurementChange;

    public RxTickerView(Context context) {
        super(context);
        init(context, null, 0, 0);
    }

    public RxTickerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0, 0);
    }

    public RxTickerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr, 0);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public RxTickerView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs, defStyleAttr, defStyleRes);
    }

    /**
     * We currently only support the following set of XML attributes:
     *

     *
app:textColor
     *
app:textSize
     *

     *
     * @param context context from constructor
     * @param attrs attrs from constructor
     * @param defStyleAttr defStyleAttr from constructor
     * @param defStyleRes defStyleRes from constructor
     */
    protected void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        final Resources res = context.getResources();

        int textColor = DEFAULT_TEXT_COLOR;
        float textSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, DEFAULT_TEXT_SIZE,
                res.getDisplayMetrics());
        int gravity = DEFAULT_GRAVITY;

        // Set the view attributes from XML or from default values defined in this class
        final TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.ticker_TickerView,
                defStyleAttr, defStyleRes);

        final int textAppearanceResId = arr.getResourceId(
                R.styleable.ticker_TickerView_android_textAppearance, -1);

        // Check textAppearance first
        if (textAppearanceResId != -1) {
            final TypedArray textAppearanceArr = context.obtainStyledAttributes(
                    textAppearanceResId,
                    new int[] {
                            // TODO: having textColor first here does not work, why?
                            android.R.attr.textSize,
                            android.R.attr.textColor,
                    });

            textSize = textAppearanceArr.getDimension(0, textSize);
            textColor = textAppearanceArr.getColor(1, textColor);

            textAppearanceArr.recycle();
        }

        // Custom set attributes on the view should override textAppearance if applicable.
        gravity = arr.getInt(R.styleable.ticker_TickerView_android_gravity, gravity);
        textColor = arr.getColor(R.styleable.ticker_TickerView_android_textColor, textColor);
        textSize = arr.getDimension(R.styleable.ticker_TickerView_android_textSize, textSize);

        // After we've fetched the correct values for the attributes, set them on the view
        animationInterpolator = DEFAULT_ANIMATION_INTERPOLATOR;
        this.animationDurationInMillis = arr.getInt(
                R.styleable.ticker_TickerView_ticker_animationDuration, DEFAULT_ANIMATION_DURATION);
        this.animateMeasurementChange = arr.getBoolean(
                R.styleable.ticker_TickerView_ticker_animateMeasurementChange, false);
        this.gravity = gravity;
        setTextColor(textColor);
        setTextSize(textSize);

        arr.recycle();

        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                columnManager.setAnimationProgress(animation.getAnimatedFraction());
                checkForRelayout();
                invalidate();
            }
        });
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                columnManager.onAnimationEnd();
                checkForRelayout();
            }
        });
    }

    /********** BEGIN PUBLIC API **********/

    /**
     * This is the primary API that the view uses to determine how to animate from one character
     * to another. The provided character array dictates what characters will appear between
     * the start and end characters.
     *
     *
For example, given the list [a,b,c,d,e], if the view wants to animate from 'd' to 'a',
     * it will know that it has to go from 'd' to 'c' to 'b' to 'a', and these are the characters
     * that show up during the animation scroll.
     *
     *
You can find some helpful character list generators in {@link RxTickerUtils}.
     *
     *
Special note: the character list must contain {@link RxTickerUtils#EMPTY_CHAR} because the
     * ticker needs to know how to animate from empty to another character (e.g. when the length
     * of the string changes).
     *
     * @param characterList the character array that dictates character orderings.
     */
    public void setCharacterList(char[] characterList) {
        boolean foundEmpty = false;
        for (char character : characterList) {
            if (character == RxTickerUtils.EMPTY_CHAR) {
                foundEmpty = true;
                break;
            }
        }

        if (!foundEmpty) {
            throw new IllegalArgumentException("Missing RxTickerUtils#EMPTY_CHAR in character list");
        }

        columnManager.setCharacterList(characterList);
    }

    /**
     * Sets the string value to display. If the TickerView is currently empty, then this method
     * will immediately display the provided text. Otherwise, it will run the default animation
     * to reach the provided text.
     *
     * @param text the text to display.
     */
    public void setText(String text) {
        setText(text, columnManager.getCurrentWidth() > 0);
    }

    /**
     * Similar to {@link #setText(String)} but provides the optional argument of whether to
     * animate to the provided text or not.
     *
     * @param text the text to display.
     * @param animate whether to animate to text.
     */
    public synchronized void setText(String text, boolean animate) {
        final char[] targetText = text == null ? new char[0] : text.toCharArray();

        if (columnManager.shouldDebounceText(targetText)) {
            return;
        }

        columnManager.setText(targetText);
        setContentDescription(text);

        if (animate) {
            // Kick off the animator that draws the transition
            if (animator.isRunning()) {
                animator.cancel();
            }

            animator.setDuration(animationDurationInMillis);
            animator.setInterpolator(animationInterpolator);
            animator.start();
        } else {
            columnManager.setAnimationProgress(1f);
            columnManager.onAnimationEnd();
            checkForRelayout();
            invalidate();
        }
    }

    /**
     * @return the current text color that's being used to draw the text.
     */
    public int getTextColor() {
        return textColor;
    }

    /**
     * Sets the text color used by this view. The default text color is defined by
     * {@link #DEFAULT_TEXT_COLOR}.
     *
     * @param color the color to set the text to.
     */
    public void setTextColor(int color) {
        if (this.textColor != color) {
            textColor = color;
            textPaint.setColor(textColor);
            invalidate();
        }
    }

    /**
     * @return the current text size that's being used to draw the text.
     */
    public float getTextSize() {
        return textSize;
    }

    /**
     * Sets the text size used by this view. The default text size is defined by
     * {@link #DEFAULT_TEXT_SIZE}.
     *
     * @param textSize the text size to set the text to.
     */
    public void setTextSize(float textSize) {
        if (this.textSize != textSize) {
            this.textSize = textSize;
            textPaint.setTextSize(textSize);
            onTextPaintMeasurementChanged();
        }
    }

    /**
     * @return the current text typeface.
     */
    public Typeface getTypeface() {
        return textPaint.getTypeface();
    }

    /**
     * Sets the typeface size used by this view.
     *
     * @param typeface the typeface to use on the text.
     */
    public void setTypeface(Typeface typeface) {
        textPaint.setTypeface(typeface);
        onTextPaintMeasurementChanged();
    }

    /**
     * @return the duration in milliseconds that the transition animations run for.
     */
    public long getAnimationDuration() {
        return animationDurationInMillis;
    }

    /**
     * Sets the duration in milliseconds that this TickerView runs its transition animations. The
     * default animation duration is defined by {@link #DEFAULT_ANIMATION_DURATION}.
     *
     * @param animationDurationInMillis the duration in milliseconds.
     */
    public void setAnimationDuration(long animationDurationInMillis) {
        this.animationDurationInMillis = animationDurationInMillis;
    }

    /**
     * @return the interpolator used to interpolate the animated values.
     */
    public Interpolator getAnimationInterpolator() {
        return animationInterpolator;
    }

    /**
     * Sets the interpolator for the transition animation. The default interpolator is defined by
     * {@link #DEFAULT_ANIMATION_INTERPOLATOR}.
     *
     * @param animationInterpolator the interpolator for the animation.
     */
    public void setAnimationInterpolator(Interpolator animationInterpolator) {
        this.animationInterpolator = animationInterpolator;
    }

    /**
     * @return the current text gravity used to align the text. Should be one of the values defined
     *         in {@link Gravity}.
     */
    public int getGravity() {
        return gravity;
    }

    /**
     * Sets the gravity used to align the text.
     *
     * @param gravity the new gravity, should be one of the values defined in
     *                {@link Gravity}.
     */
    public void setGravity(int gravity) {
        if (this.gravity != gravity) {
            this.gravity = gravity;
            invalidate();
        }
    }

    /**
     * Enables/disables the flag to animate measurement changes. If this flag is enabled, any
     * animation that changes the content's text width (e.g. 9999 to 10000) will have the view's
     * measured width animated along with the text width. However, a side effect of this is that
     * the entering/exiting character might get truncated by the view's view bounds as the width
     * shrinks or expands.
     *
     *
Warning: using this feature may degrade performance as it will force a re-measure and
     * re-layout during each animation frame.
     *
     *
This flag is disabled by default.
     *
     * @param animateMeasurementChange whether or not to animate measurement changes.
     */
    public void setAnimateMeasurementChange(boolean animateMeasurementChange) {
        this.animateMeasurementChange = animateMeasurementChange;
    }

    /**
     * @return whether or not we are currently animating measurement changes.
     */
    public boolean getAnimateMeasurementChange() {
        return animateMeasurementChange;
    }

    /**
     * Adds a custom {@link Animator.AnimatorListener} to listen to animator
     * update events used by this view.
     *
     * @param animatorListener the custom animator listener.
     */
    public void addAnimatorListener(Animator.AnimatorListener animatorListener) {
        animator.addListener(animatorListener);
    }

    /**
     * Removes the specified custom {@link Animator.AnimatorListener} from
     * this view.
     *
     * @param animatorListener the custom animator listener.
     */
    public void removeAnimatorListener(Animator.AnimatorListener animatorListener) {
        animator.removeListener(animatorListener);
    }

    /********** END PUBLIC API **********/

    /**
     * Force the view to call {@link #requestLayout()} if the new text doesn't match the old bounds
     * we set for the previous view state.
     */
    private void checkForRelayout() {
        final boolean widthChanged = lastMeasuredDesiredWidth != computeDesiredWidth();
        final boolean heightChanged = lastMeasuredDesiredHeight != computeDesiredHeight();

        if (widthChanged || heightChanged) {
            requestLayout();
        }
    }

    private int computeDesiredWidth() {
        final int contentWidth = (int) (animateMeasurementChange ?
                columnManager.getCurrentWidth() : columnManager.getMinimumRequiredWidth());
        return contentWidth + getPaddingLeft() + getPaddingRight();
    }

    private int computeDesiredHeight() {
        return (int) metrics.getCharHeight() + getPaddingTop() + getPaddingBottom();
    }

    /**
     * Re-initialize all of our variables that are dependent on the TextPaint measurements.
     */
    private void onTextPaintMeasurementChanged() {
        metrics.invalidate();
        checkForRelayout();
        invalidate();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int desiredWidth = MeasureSpec.getSize(widthMeasureSpec);
        int desiredHeight = MeasureSpec.getSize(heightMeasureSpec);

        lastMeasuredDesiredWidth = computeDesiredWidth();
        lastMeasuredDesiredHeight = computeDesiredHeight();

        switch (widthMode) {
            case MeasureSpec.EXACTLY:
                break;
            case MeasureSpec.AT_MOST:
                desiredWidth = Math.min(desiredWidth, lastMeasuredDesiredWidth);
                break;
            case MeasureSpec.UNSPECIFIED:
                desiredWidth = lastMeasuredDesiredWidth;
                break;
        }

        switch (heightMode) {
            case MeasureSpec.EXACTLY:
                break;
            case MeasureSpec.AT_MOST:
                desiredHeight = Math.min(desiredHeight, lastMeasuredDesiredHeight);
                break;
            case MeasureSpec.UNSPECIFIED:
                desiredHeight = lastMeasuredDesiredHeight;
                break;
        }

        setMeasuredDimension(desiredWidth, desiredHeight);
    }

    @Override
    protected void onSizeChanged(int width, int height, int oldw, int oldh) {
        super.onSizeChanged(width, height, oldw, oldh);
        viewBounds.set(getPaddingLeft(), getPaddingTop(), width - getPaddingRight(),
                height - getPaddingBottom());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.save();

        realignAndClipCanvasForGravity(canvas);

        // canvas.drawText writes the text on the baseline so we need to translate beforehand.
        canvas.translate(0f, metrics.getCharBaseline());

        columnManager.draw(canvas, textPaint);

        canvas.restore();
    }

    private void realignAndClipCanvasForGravity(Canvas canvas) {
        final float currentWidth = columnManager.getCurrentWidth();
        final float currentHeight = metrics.getCharHeight();
        realignAndClipCanvasForGravity(canvas, gravity, viewBounds, currentWidth, currentHeight);
    }

    // VisibleForTesting
    static void realignAndClipCanvasForGravity(Canvas canvas, int gravity, Rect viewBounds,
            float currentWidth, float currentHeight) {
        final int availableWidth = viewBounds.width();
        final int availableHeight = viewBounds.height();

        float translationX = 0;
        float translationY = 0;
        if ((gravity & Gravity.CENTER_VERTICAL) == Gravity.CENTER_VERTICAL) {
            translationY = viewBounds.top + (availableHeight - currentHeight) / 2f;
        }
        if ((gravity & Gravity.CENTER_HORIZONTAL) == Gravity.CENTER_HORIZONTAL) {
            translationX = viewBounds.left + (availableWidth - currentWidth) / 2f;
        }
        if ((gravity & Gravity.TOP) == Gravity.TOP) {
            translationY = 0;
        }
        if ((gravity & Gravity.BOTTOM) == Gravity.BOTTOM) {
            translationY = viewBounds.top + (availableHeight - currentHeight);
        }
        if ((gravity & Gravity.START) == Gravity.START) {
            translationX = 0;
        }
        if ((gravity & Gravity.END) == Gravity.END) {
            translationX = viewBounds.left + (availableWidth - currentWidth);
        }

        canvas.translate(translationX ,translationY);
        canvas.clipRect(0f, 0f, currentWidth, currentHeight);
    }
}


text:
<!DOCTYPE html >

          <title>Monoid - io.gearpump.streaming.state.api.Monoid</title>
          <meta name="description" content="Monoid - io.gearpump.streaming.state.api.Monoid" />
          <meta name="keywords" content="Monoid io.gearpump.streaming.state.api.Monoid" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../../../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />

io.gearpump.streaming.state.api

Monoid

Related Doc:
            package api

        trait

        Monoid[T] extends Serializable

          Linear Supertypes

Serializable, AnyRef, Any

            Known Subclasses

AlgebirdGroup, AlgebirdMonoid, Group

<input id="mbrsel-input" type="text" accesskey="/" />

              Ordering

Alphabetic

By Inheritance

                Inherited

Monoid

Serializable

AnyRef

Any

Hide All

Show All

            Visibility

Public

All

Abstract Value Members

        abstract
        def

        plus(l: T, r: T): T

        abstract
        def

        zero: T

Concrete Value Members

        final
        def

        !=(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        final
        def

        ##(): Int

Definition Classes

AnyRef → Any

        final
        def

        ==(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        final
        def

        asInstanceOf[T0]: T0

Definition Classes

Any

        def

        clone(): AnyRef

Attributes

protected[java.lang]

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        final
        def

        eq(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        def

        equals(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        def

        finalize(): Unit

Attributes

protected[java.lang]

Definition Classes

AnyRef

Annotations

                @throws(

      classOf[java.lang.Throwable]
    )

        final
        def

        getClass(): Class[_]

Definition Classes

AnyRef → Any

        def

        hashCode(): Int

Definition Classes

AnyRef → Any

        final
        def

        isInstanceOf[T0]: Boolean

Definition Classes

Any

        final
        def

        ne(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        final
        def

        notify(): Unit

Definition Classes

AnyRef

        final
        def

        notifyAll(): Unit

Definition Classes

AnyRef

        final
        def

        synchronized[T0](arg0: ⇒ T0): T0

Definition Classes

AnyRef

        def

        toString(): String

Definition Classes

AnyRef → Any

        final
        def

        wait(): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        final
        def

        wait(arg0: Long, arg1: Int): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        final
        def

        wait(arg0: Long): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

Inherited from Serializable

Inherited from AnyRef

Inherited from Any

Ungrouped

redpajama_set_name: RedPajamaGithub


text:
require 'test_helper'

class MailingsHelperTest < ActionView::TestCase
end


text:
package io.crate.execution.ddl.index;

import org.elasticsearch.action.support.master.AcknowledgedRequest;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;

import java.io.IOException;

/**
 * Renames source to target, and dropping the former target - effectively overriding the target
 */
public final class SwapAndDropIndexRequest extends AcknowledgedRequest<SwapAndDropIndexRequest> {

    private final String source;
    private final String target;

    public SwapAndDropIndexRequest(String source, String target) {
        this.source = source;
        this.target = target;
    }

    public SwapAndDropIndexRequest(StreamInput in) throws IOException {
        super(in);
        this.source = in.readString();
        this.target = in.readString();
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        super.writeTo(out);
        out.writeString(source);
        out.writeString(target);
    }

    public String source() {
        return source;
    }

    public String target() {
        return target;
    }
}


text:
// Dstl (c) Crown Copyright 2017
package uk.gov.dstl.baleen.annotators.regex;

import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.uima.UIMAException;
import org.apache.uima.UimaContext;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.fit.descriptor.ConfigurationParameter;
import org.apache.uima.fit.factory.JCasFactory;
import org.apache.uima.resource.ResourceInitializationException;

import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;

import uk.gov.dstl.baleen.core.pipelines.orderers.AnalysisEngineAction;
import uk.gov.dstl.baleen.core.utils.ConfigUtils;
import uk.gov.dstl.baleen.exceptions.BaleenException;
import uk.gov.dstl.baleen.types.semantic.Entity;
import uk.gov.dstl.baleen.uima.BaleenTextAwareAnnotator;
import uk.gov.dstl.baleen.uima.data.TextBlock;
import uk.gov.dstl.baleen.uima.utils.TypeSystemSingleton;
import uk.gov.dstl.baleen.uima.utils.TypeUtils;

/**
 * Process the document using user supplied regular expressions and annotating matches as a user
 * specified type
 *
 * <p>The regular expression supplied by the user is run over the document content. Matches are
 * annotated as a user specified type, which must inherit from the Entity class. Users can supply a
 * confidence to assign to annotations created by this RegEx.
 *
 * @baleen.javadoc
 */
public class Custom extends BaleenTextAwareAnnotator {
  private Pattern p = null;
  private Class<? extends Entity> et = null;

  /**
   * Is the regular expression case sensitive?
   *
   * @baleen.config false
   */
  public static final String PARAM_CASE_SENSITIVE = "caseSensitive";

  @ConfigurationParameter(name = PARAM_CASE_SENSITIVE, defaultValue = "false")
  private boolean caseSensitive = false;

  /**
   * Which group in the regular expression should be used as the entity value?
   *
   * @baleen.config 0
   */
  public static final String PARAM_GROUP = "group";

  @ConfigurationParameter(name = PARAM_GROUP, defaultValue = "0")
  private String patternGroupString;

  // Parse the patternGroup config parameter into this variable to avoid issues with parameter types
  private int patternGroup;

  /**
   * The regular expression to search for
   *
   * @baleen.config
   */
  public static final String PARAM_PATTERN = "pattern";

  @ConfigurationParameter(name = PARAM_PATTERN, defaultValue = "")
  private String pattern;

  /**
   * The entity type to use for matched entities
   *
   * @baleen.config uk.gov.dstl.baleen.types.semantic.Entity
   */
  public static final String PARAM_TYPE = "type";

  @ConfigurationParameter(
      name = PARAM_TYPE,
      defaultValue = "uk.gov.dstl.baleen.types.semantic.Entity")
  private String type = "uk.gov.dstl.baleen.types.semantic.Entity";

  /**
   * The entity subType to use for matched entities
   *
   * @baleen.config
   */
  public static final String PARAM_SUB_TYPE = "subType";

  @ConfigurationParameter(name = PARAM_SUB_TYPE, defaultValue = "")
  private String subType = "";

  /**
   * The confidence to assign to matched entities
   *
   * @baleen.config 1.0
   */
  public static final String PARAM_CONFIDENCE = "confidence";

  @ConfigurationParameter(name = PARAM_CONFIDENCE, defaultValue = "1.0")
  private String confidenceString;

  // Parse the confidence config parameter into this variable to avoid issues with parameter types
  private Float confidence;

  @Override
  public void doInitialize(UimaContext aContext) throws ResourceInitializationException {
    patternGroup = ConfigUtils.stringToInteger(patternGroupString, 0);
    confidence = ConfigUtils.stringToFloat(confidenceString, 1.0f);

    if (caseSensitive) {
      p = Pattern.compile(pattern);
      getMonitor().debug("The regular expression is \"{}\"", p.pattern());
    } else {
      p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
    }
    try {
      et =
          TypeUtils.getEntityClass(
              type, JCasFactory.createJCas(TypeSystemSingleton.getTypeSystemDescriptionInstance()));
    } catch (UIMAException | BaleenException e) {
      throw new ResourceInitializationException(e);
    }
  }

  @Override
  public void doProcessTextBlock(TextBlock block) throws AnalysisEngineProcessException {
    String text = block.getCoveredText();

    Matcher m = p.matcher(text);
    while (m.find()) {
      Entity ret;
      try {
        ret = block.newAnnotation(et, m.start(), m.end());
      } catch (Exception e) {
        throw new AnalysisEngineProcessException(e);
      }

      ret.setValue(m.group(patternGroup));

      ret.setConfidence(confidence);
      if (!Strings.isNullOrEmpty(subType)) {
        ret.setSubType(subType);
      }

      addToJCasIndex(ret);
    }
  }

  @Override
  public void doDestroy() {
    pattern = null;
    et = null;
  }

  @Override
  public AnalysisEngineAction getAction() {
    return new AnalysisEngineAction(Collections.emptySet(), ImmutableSet.of(et));
  }
}


text:
class Mob < ActiveRecord::Base
end


text:
package org.ovirt.engine.core.common.action;

import org.ovirt.engine.core.compat.*;
import org.ovirt.engine.core.common.businessentities.*;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

import java.util.ArrayList;

@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = "ImportVmParameters")
public class ImportVmParameters extends MoveVmParameters implements java.io.Serializable {
    private static final long serialVersionUID = -8952177290494146953L;
    @XmlElement
    private VM _vm;
    @XmlElement
    private Guid _sourceDomainId = new Guid();
    @XmlElement
    private Guid _destDomainId = new Guid();
    @XmlElement
    private java.util.ArrayList<DiskImage> _images;
    @XmlElement
    private Guid _vdsGroupId;

    public ImportVmParameters(VM vm, Guid sourceStorageDomainId, Guid destStorageDomainId, Guid storagePoolId,
            Guid vdsGroupId) {
        super(vm.getvm_guid(), destStorageDomainId);
        _vm = vm;
        _sourceDomainId = sourceStorageDomainId;
        _destDomainId = destStorageDomainId;
        setStorageDomainId(destStorageDomainId);
        setStoragePoolId(storagePoolId);
        _vdsGroupId = vdsGroupId;
    }

    public VM getVm() {
        return _vm;
    }

    public Guid getSourceDomainId() {
        return _sourceDomainId;
    }

    public Guid getDestDomainId() {
        return _destDomainId;
    }

    public java.util.ArrayList<DiskImage> getImages() {
        return _images == null ? new ArrayList<DiskImage>() : _images;
    }

    public void setImages(java.util.ArrayList<DiskImage> value) {
        _images = value;
    }

    public Guid getVdsGroupId() {
        return _vdsGroupId;
    }

    public void setVdsGroupId(Guid value) {
        _vdsGroupId = value;
    }

    public ImportVmParameters() {
    }
}


text:
package com.thoughtworks.go.server.service.materials;

import java.io.File;
import java.util.List;

import com.thoughtworks.go.config.materials.SubprocessExecutionContext;
import com.thoughtworks.go.config.materials.dependency.DependencyMaterial;
import com.thoughtworks.go.domain.materials.Modification;
import com.thoughtworks.go.domain.materials.Revision;

public class DependencyMaterialPoller implements MaterialPoller<DependencyMaterial> {

    @Override
    public List<Modification> latestModification(DependencyMaterial material, File baseDir, SubprocessExecutionContext execCtx) {
        return material.latestModification(baseDir, execCtx);
    }

    @Override
    public List<Modification> modificationsSince(DependencyMaterial material, File baseDir, Revision revision, SubprocessExecutionContext execCtx) {
        return material.modificationsSince(baseDir, revision, execCtx);
    }

    @Override
    public void checkout(DependencyMaterial material, File baseDir, Revision revision, SubprocessExecutionContext execCtx) {
        throw new RuntimeException("not supported");
    }
}


text:
const { ipcRenderer, webFrame } = require('electron');

webFrame.executeJavaScript(`(() => {
  return {};
})()`).then((obj) => {
  // Considered safe if the object is constructed in this world
  ipcRenderer.send('executejs-safe', obj.constructor === Object);
});


text:
#include <folly/portability/Constexpr.h>

#include <folly/portability/GTest.h>

using folly::constexpr_strcmp;

TEST(ConstexprTest, constexpr_strlen_cstr) {
  constexpr auto v = "hello";
  constexpr auto a = folly::constexpr_strlen(v);
  EXPECT_EQ(5, a);
  EXPECT_TRUE((std::is_same<const size_t, decltype(a)>::value));
}

// gcc-4.9 cannot compile the following constexpr code correctly
#if !(defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 5)
TEST(ConstexprTest, constexpr_strlen_ints) {
  constexpr int v[] = {5, 3, 4, 0, 7};
  constexpr auto a = folly::constexpr_strlen(v);
  EXPECT_EQ(3, a);
  EXPECT_TRUE((std::is_same<const size_t, decltype(a)>::value));
}

TEST(ConstexprTest, constexpr_strcmp_ints) {
  constexpr int v[] = {5, 3, 4, 0, 7};
  constexpr int v1[] = {6, 4};
  static_assert(constexpr_strcmp(v1, v) > 0, "constexpr_strcmp is broken");
  static_assert(constexpr_strcmp(v, v) == 0, "constexpr_strcmp is broken");
}
#endif

static_assert(
    constexpr_strcmp("abc", "abc") == 0,
    "constexpr_strcmp is broken");
static_assert(constexpr_strcmp("", "") == 0, "constexpr_strcmp is broken");
static_assert(constexpr_strcmp("abc", "def") < 0, "constexpr_strcmp is broken");
static_assert(constexpr_strcmp("xyz", "abc") > 0, "constexpr_strcmp is broken");
static_assert(constexpr_strcmp("a", "abc") < 0, "constexpr_strcmp is broken");
static_assert(constexpr_strcmp("abc", "a") > 0, "constexpr_strcmp is broken");


text:
import { Routes, RouterModule } from '@angular/router';

import { AnimationsComponent } from './animations.component';
import { AnimationsBasicExamplesComponent } from './basic-examples/basic-examples.component';
import { AnimationsRepeatingItemsComponent } from './repeating-items/repeating-items.component';

const routes: Routes = [
  {
    path: '', component: AnimationsComponent, children: [
      { path: 'basicanimation', component: AnimationsBasicExamplesComponent },
      { path: 'repeatinganimations', component: AnimationsRepeatingItemsComponent }
    ]
  },
];

export const routing = RouterModule.forChild(routes);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace QuestionAsker
{
    static class Program
    {
        static TimeSpan SleepSpan = new TimeSpan(0, 30, 0);
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            while(true)
            {
                Application.Run(new PopupForm());

                System.Threading.Thread.Sleep(SleepSpan);
            }
        }
    }
}


text:
CKEDITOR.plugins.setLang( 'filetools', 'sq', {
	loadError: 'Gabimi u paraqit gjatë leximit të skedës.',
	networkError: 'Gabimi në rrjetë u paraqitë gjatë ngarkimit të skedës.',
	httpError404: 'Gabimi në HTTP u paraqit gjatë ngarkimit të skedës (404: Skeda nuk u gjetë).',
	httpError403: 'Gabimi në HTTP u paraqitë gjatë ngarkimit të skedës (403: E ndaluar).',
	httpError: 'Gabimi në HTTP u paraqit gjatë ngarkimit të skedës (gjendja e gabimit: %1).',
	noUrlError: 'URL e ngarkimit nuk është vendosur.',
	responseError: 'Përgjigje e gabuar e serverit.'
} );


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.salil.futureapp</groupId>
	<artifactId>futureapp-parent</artifactId>
	<version>1.0.0</version>
	<packaging>pom</packaging>
	<name>futureapp-parent</name>
	<description>Maven 2 + Spring 3 + Hibernate 3 multi layered project</description>
	<url>http://localhost:8080/futureapp-web</url>
	<modules>
		<module>futureapp-base</module>
		<module>futureapp-model</module>
		<module>futureapp-service</module>
		<module>futureapp-dao</module>
		<module>futureapp-web</module>
	</modules>
	<properties>
		<spring.version>3.1.2.RELEASE</spring.version>
		<slf4j.version>1.5.6</slf4j.version>
		<log4j.version>1.2.14</log4j.version>
	</properties>
	<organization>
		<name>The Missing Link</name>
	</organization>
	<developers>
		<developer>
			<id>salil</id>
			<name>Salil Walavalkar</name>
			<roles>
				<role>The Lone Developer</role>
			</roles>
		</developer>
	</developers>
	<!-- Build Management - Start -->
	<build>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-compiler-plugin</artifactId>
					<version>2.0.2</version>
					<configuration>
						<source>1.5</source>
						<target>1.5</target>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
	<!-- Build Management - End -->
	<!-- JXR (source code cross-reference) reporting -->
	<reporting>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<version>2.5</version>
				<configuration>
					<aggregate>true</aggregate>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jxr-plugin</artifactId>
				<version>2.1</version>
				<configuration>
					<aggregate>true</aggregate>
				</configuration>
			</plugin>
		</plugins>
	</reporting>
</project>


text:
package tipster

import java.lang.Thread

import scala.concurrent._
import scala.concurrent.duration._
import scala.util._

import akka._
import akka.actor._
import akka.pattern._
import akka.stream._
import akka.util._

import akka.http.scaladsl.model._
import akka.http.scaladsl.server._
import akka.http.scaladsl._

import com.typesafe

import tipster.management._
import tipster.storage._
import tipster.tips._
import tipster.tips.services._

final class TipsterGuardianStrategy extends SupervisorStrategyConfigurator {
  def create() = OneForOneStrategy() {
    case _: ConfigurationException => SupervisorStrategy.Escalate
    case _: TipsterFatalError      => SupervisorStrategy.Escalate
  }
}

object TipsterGuardianStrategy {
  def apply() = new TipsterGuardianStrategy
}

trait TipsterFatalError

case class FailedToBind(
  listenAddress: String,
  listenPort: Int,
  cause: Throwable
) extends Exception(s"Failed to bind to ${listenAddress}:${listenPort}", cause)
  with TipsterFatalError

final class TipsterService(shutdownPromise: Promise[Done]) extends Actor
  with ActorLogging
  with ManagementApi
  with TipsApi
{
  import Http.ServerBinding
  import StorageManager.Messages._
  // These are vars because we can't initialize them until after
  // migrations are complete. Otherwise, weird things seem to happen
  // with connections not having the correct `search_path`. They're
  // never accessed outside of this actor so "unsafe" just means
  // they're mutable.
  @SuppressWarnings(Array("org.wartremover.warts.Var"))
  private var unsafeTipsWriter: Option[PostgresTipsWriter] = None
  @SuppressWarnings(Array("org.wartremover.warts.Var"))
  private var unsafeTipsReader: Option[PostgresTipsReader] = None

  override def tipsWriter: Option[PostgresTipsWriter] = unsafeTipsWriter
  override def tipsReader: Option[PostgresTipsReader] = unsafeTipsReader

  implicit val system = context.system
  implicit val materializer = ActorMaterializer()(context)
  implicit val dispatcher = context.dispatcher

  val storage = context.actorOf(StorageManager.props, "storage")
  val allRoutes = managementRoutes ~ tipsRoutes
  val config = TipsterConfiguration(context.system)

  override val supervisorStrategy = TipsterGuardianStrategy().create

  @SuppressWarnings(Array("org.wartremover.warts.Any"))
  override def receive: Receive = {
    case StorageReady => {
      unsafeTipsWriter = Some(PostgresTipsWriter(context.system))
      unsafeTipsReader = Some(PostgresTipsReader(context.system))
      val _ = Http().bindAndHandle(allRoutes,
                           config.apiListenAddress,
                           config.apiListenPort) pipeTo self
      context.become(binding)
    }
  }

  @SuppressWarnings(Array("org.wartremover.warts.Any", "org.wartremover.warts.Throw"))
  def binding: Receive = {
    case serverBinding: ServerBinding => {
			system.log.info(s"Tipster Server started on http://${config.apiListenAddress}:${config.apiListenPort}")
      context.become(running(serverBinding))
    }
    case Failure(e) => throw FailedToBind(config.apiListenAddress, config.apiListenPort, e)
  }

  @SuppressWarnings(Array("org.wartremover.warts.Any"))
  def running(serverBinding: ServerBinding): Receive = {
    case _ =>
  }

  override def postStop: Unit = {
    system.log.info(s"Tipster Server terminated")
    val _ = shutdownPromise.success(Done)
  }
}

object TipsterService {
  def props(shutdownPromise: Promise[Done]) = Props(classOf[TipsterService], shutdownPromise)
}

object Tipster
{

  val banner = """
  |  _______ _____  _____  _______ _______ _______  ______
  |     |      |   |_____] |______    |    |______ |_____/
  |     |    __|__ |       ______|    |    |______ |    \_
  |
  |  Starting Up...
  """.stripMargin

  def main(args: Array[String]): Unit = {
		println(banner)
    val system  = ActorSystem("Tipster")
    val config  = TipsterConfiguration(system)
		val shutdown =  {
			val shutdownPromise = Promise[Done]
      val service = system.actorOf(TipsterService.props(shutdownPromise), "tipster")
			shutdownPromise.future
		}

		val _ = Await.ready(shutdown, Duration.Inf)
  }
}


text:
package net._5tingr4y.stingUtils.math.logic;

/**
 * A logic utility class that provides some additional functions on booleans such as random booleans with a given chance for true and logic operations on boolean arrays.
 */
public class LogicUtil {

    /**
     * Randomly returns true or false with equal probability.
     * @return
     */
    public static boolean randomBool() {
        return Math.random() < 0.5;
    }

    /**
     * Randomly returns true or false with the given probability for true.
     * @param chanceForTrue The probability that this method will return true ranging from {@code 0 - 1}. The probability for false will be {@code 1 - chanceForTrue}
     * @return
     */
    public static boolean randomBool(double chanceForTrue) {
        if(chanceForTrue <= 0) return false;
        if(chanceForTrue >= 1) return true;
        return Math.random() < chanceForTrue;
    }

    /**
     * Returns true only if all the given booleans are true. Returns false if the array is empty.
     *
If the number of given booleans is 0, this method will return true.
     * @param bools
     * @return
     */
    public static boolean and(boolean... bools) {
        for(boolean b: bools) {
            if(!b)
                return false;
        }
        return true;
    }

    /**
     * Returns true if at least one of the given booleans is true. Returns false if the array is empty.
     *
If the number of given booleans is 0, this method will return false.
     * @param bools
     * @return
     */
    public static boolean or(boolean... bools) {
        for(boolean b: bools) {
            if(b)
                return true;
        }
        return false;
    }

    /**
     * Returns true if all given booleans have the same value. Returns false if the array is empty.
     *
If the number of given booleans is 0, this method will return true.
     * @param bools
     * @return
     */
    public static boolean equivalent(boolean... bools) {
        if(bools.length == 0) return true;
        boolean start = bools[0];
        for(int i = 1; i < bools.length; i++) {
            if(bools[i] != start)
                return false;
        }
        return true;
    }

    /**
     * Returns the result of {@code a -> b}.
     * @param a
     * @param b
     * @return
     */
    public static boolean implies(boolean a, boolean b) {
        return !a || b;
    }
}


text:
using Microsoft.Bot.Builder.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading.Tasks;
using Microsoft.Bot.Connector;
using NavigationBot.Properties;

namespace NavigationBot.Dialogs
{
    [Serializable]
    public class Topic3Dialog : IDialog<object>
    {
        public async Task StartAsync(IDialogContext context)
        {
            await this.ShowMenuAsync(context);
        }

        private async Task ShowMenuAsync(IDialogContext context)
        {
            var reply = context.MakeMessage();

            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

            reply.Attachments.Add(CreateHeroCardAttachment(Resources.Topic3_1_Option));
            reply.Attachments.Add(CreateHeroCardAttachment(Resources.Topic3_2_Option));
            reply.Attachments.Add(CreateHeroCardAttachment(Resources.Topic3_3_Option));

            await context.PostAsync(reply);

            context.Wait(this.ShowMenuResumeAfterAsync);
        }

        private async Task ShowMenuResumeAfterAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
        {
            var message = await result;

            // Everything in dialog is navigation, so anything returned here not picked up by global message handler is not understood.
            // Should implement retries here.
            await this.StartOverAsync(context, $"I'm sorry, I don't understand '{ message.Text }'.");
        }

        private Attachment CreateHeroCardAttachment(string title)
        {
            var heroCard = new HeroCard
            {
                Title = title,
                Text = $"To learn more about { title }...",

                Images = new List<CardImage>() {
                        new CardImage($"https://placeholdit.imgix.net/~text?txtsize=28&txt={ HttpContext.Current.Server.UrlEncode(title) }&w=320&h=160") },

                Buttons = new List<CardAction>
                {
                    new CardAction(ActionTypes.ImBack, title, value: title)
                }
            };

            return heroCard.ToAttachment();
        }

        private async Task StartOverAsync(IDialogContext context, string text)
        {
            var message = context.MakeMessage();
            message.Text = text;
            await this.StartOverAsync(context, message);
        }

        private async Task StartOverAsync(IDialogContext context, IMessageActivity message)
        {
            await context.PostAsync(message);
            await this.ShowMenuAsync(context);
        }
    }
}


text:
function [varargout]=repop(varargin)
% Replicating arithemetical and logical operators.
%
% [Z]=repop(X,operator,Y [,options])
%
% Does element by element operations on X and Y where non-same sized
% dimensions are implicity wrapped round to match the size of the larger
% to give a result matrix Z with size max(size(X),size(Y));
%
% What this means is that if you give a [Nx1] and a [1xM] input you get
% a [NxM] output, or if you give it a [Nx1xQ] and a [NxMx1xP] you get
% [NxMxQxP] output etc..
% Note that the size of the input *completely and uniquely* determines the
% size of the output.
%
% In general this is at least 2x faster than the equivalent matlab code
% using repmats and has the advantage of requiring no additional memory.
%
% Example Usage:
%     X = randn(10000,10);                  % example signal with data in rows
%     stdX = repop(X,'-',mean(X,1));        % subtract the mean vector
%     stdX = repop(stdX,'/',std(stdX,0,1)); % divide by std-deviation
%
% Operator can be one of:
%
% Arthemetical -- returns a double matrix
%   '+','.+',plus   - Implicitly repmatted elementwise addition
%   '-','.-',minus  - Implicitly repmatted elementwise addition
%   '*','.*',times  - Implicitly repmatted elementwise multiplication
%   '^','.^',power  - Implicitly repmatted elementwise raise X to power Y
%   '\','.\',ldivide- Implicitly repmatted elementwise divide Y by X
%   '/','./',rdivide- Implicitly repmatted elementwise divide X by Y
%   'min'           - Implicitly repmatted elementwise min of X by Y
%   'max'           - Implicitly repmatted elementwise max of X by Y
%
% Relational -- returns a logical matrix
% N.B. for complex inputs the <,>,<=,>= operators are based upon abs(x)
% (not real(x) as in matlab)
%   '==',eq         - Implicitly repmatted elementwise equality
%   '~=',ne         - Implicitly repmatted elementwise dis-equality
%   '<' ,lt         - Implicitly repmatted elementwise less than
%   '>' ,gt         - Implicitly repmatted elementwise greater than
%   '<=',le         - Implicitly repmatted elementwise less than equal
%   '>=',ge         - Implicitly repmatted elementwise greater than equal
%
% N.B. the operator can go in any of the 3 argument positions, i.e.
% these are all valid: repop(X,'-',Y), repop(X,Y,'-'), repop('-',X,Y)
%
% The optional final argument is a string of single letter switches
% consisting off
%  'm'  -- allows replication of non-unit dimensions if the larger
%          dimensions size is an integer multiple of the smaller ones
%  'n'  -- allow replication of non-unit dimensions in *all* cases
%  'i'  -- perform "inplace" operation.  This means that we use a
%          *dangerous* matlab *hack* to perform the operation *without*
%          allocating new memory for the output, but by simply overwriting
%          the memory used for X in the input.  Thus the following code is
%          a memory (and time) efficient way to increment X.
%              X = repop(X,'+',1,'i');
%
%
% Class support of input P:
%     float: double, single
%
% SEE ALSO:   repop_testcases rplus rminus rtimes rpower rldivide rrdivide
%             req rne rlt rgt rle rge
%
% Copyright 2006-     by Jason D.R. Farquhar (jdrf@zepler.org)
% Permission is granted for anyone to copy, use, or modify this
% software and accompanying documents for any uncommercial
% purposes, provided this copyright notice is retained, and note is
% made of any changes that have been made. This software and
% documents are distributed without any warranty, express or
% implied
%
% Inspired by code from Douglas M. Schwarz and & Aki Vehtari.

% The rest of this code is a mex-hiding mechanism which compilies the mex if
% this runs and recursivly calls itself.
% Based upon code from: http://theoval.sys.uea.ac.uk/matlab
cwd  = pwd; % store the current working directory
name = mfilename('fullpath'); % get the directory where we are
% find out what directory it is defined in
name(name=='\')='/'; % deal with dos'isms
dir=name(1:max(find(name == '/')-1)); % dir is everything before final '/'
try % try changing to that directory
   cd(dir);
catch   % this should never happen, but just in case!
   cd(cwd);
   error(['unable to locate directory containing ''' name '.m''']);
end

try % try recompiling the MEX file
   fprintf(['Compiling ' mfilename ' for first use\n']);
   mex('ddrepop.c','dsrepop.c','sdrepop.c','ssrepop.c','repop_util.c','repop_mex.c','mxInfo.c','mxInfo_mex.c','-O','-output',mfilename);
   fprintf('done\n');
catch
   % this may well happen happen, get back to current working directory!
   cd(cwd);
   error('unable to compile MEX version of ''%s''%s\n%s%s', name, ...
         ', please make sure your', 'MEX compiler is set up correctly', ...
         ' (try ''mex -setup'').');
end

cd(cwd); % change back to the current working directory
rehash;  % refresh the function and file system caches

% recursively invoke MEX version using the same input and output arguments
[varargout{1:nargout}] = feval(mfilename, varargin{:});

% bye bye...

return;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<TITLE
>Example</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.2.8 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="BKI Backend Interface"
HREF="bki.html"><LINK
REL="PREVIOUS"
TITLE="Structure of the Bootstrap BKI File"
HREF="bki-structure.html"><LINK
REL="NEXT"
TITLE="How the Planner Uses Statistics"
HREF="planner-stats-details.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2014-03-17T19:46:29">

PostgreSQL 9.2.8 Documentation

Prev	Up	Chapter 57. <ACRONYM
CLASS="ACRONYM"
>BKI</ACRONYM
> Backend Interface	Next

57.4. Example

   The following sequence of commands will create the
   table <TT
CLASS="LITERAL"
>test_table</TT
> with OID 420, having two columns
   <TT
CLASS="LITERAL"
>cola</TT
> and <TT
CLASS="LITERAL"
>colb</TT
> of type
   <TT
CLASS="TYPE"
>int4</TT
> and <TT
CLASS="TYPE"
>text</TT
>, respectively, and insert
   two rows into the table:

create test_table 420 (cola = int4, colb = text)
open test_table
insert OID=421 ( 1 "value1" )
insert OID=422 ( 2 _null_ )
close test_table

Prev	Home	Next

Structure of the Bootstrap <ACRONYM
CLASS="ACRONYM"
>BKI</ACRONYM
> File	Up	How the Planner Uses Statistics


text:
package com.opengamma.strata.market.curve.node;

import java.io.Serializable;
import java.time.LocalDate;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;

import org.joda.beans.Bean;
import org.joda.beans.BeanDefinition;
import org.joda.beans.ImmutableBean;
import org.joda.beans.ImmutableDefaults;
import org.joda.beans.ImmutablePreBuild;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectFieldsBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;

import com.google.common.collect.ImmutableSet;
import com.opengamma.strata.basics.ReferenceData;
import com.opengamma.strata.basics.currency.FxRate;
import com.opengamma.strata.basics.date.Tenor;
import com.opengamma.strata.collect.ArgChecker;
import com.opengamma.strata.data.FxRateId;
import com.opengamma.strata.data.MarketData;
import com.opengamma.strata.data.MarketDataId;
import com.opengamma.strata.data.ObservableId;
import com.opengamma.strata.market.ValueType;
import com.opengamma.strata.market.curve.CurveNode;
import com.opengamma.strata.market.curve.CurveNodeDate;
import com.opengamma.strata.market.curve.CurveNodeDateOrder;
import com.opengamma.strata.market.param.DatedParameterMetadata;
import com.opengamma.strata.market.param.LabelDateParameterMetadata;
import com.opengamma.strata.market.param.TenorDateParameterMetadata;
import com.opengamma.strata.product.common.BuySell;
import com.opengamma.strata.product.fx.FxSwapTrade;
import com.opengamma.strata.product.fx.ResolvedFxSwapTrade;
import com.opengamma.strata.product.fx.type.FxSwapTemplate;

/**
 * A curve node whose instrument is an FX Swap.
 *

 * The trade produced by the node will pay near and receive far in the second currency (BUY)
 * for a positive quantity and a receive near and pay far (SELL) for a negative quantity.
 * This convention is line with other nodes where a positive quantity is similar to long a bond or deposit,
 * here the long deposit-like is in the second currency.
 */
@BeanDefinition
public final class FxSwapCurveNode
    implements CurveNode, ImmutableBean, Serializable {

  /**
   * The template for the FX Swap associated with this node.
   */
  @PropertyDefinition(validate = "notNull")
  private final FxSwapTemplate template;
  /**
   * The identifier used to obtain the FX rate market value, defaulted from the template.
   * This only needs to be specified if using multiple market data sources.
   */
  @PropertyDefinition(validate = "notNull")
  private final FxRateId fxRateId;
  /**
   * The identifier of the market data value which provides the FX forward points.
   */
  @PropertyDefinition(validate = "notNull")
  private final ObservableId farForwardPointsId;
  /**
   * The label to use for the node, defaulted.
   *

   * When building, this will default based on the far period if not specified.
   */
  @PropertyDefinition(validate = "notEmpty", overrideGet = true)
  private final String label;
  /**
   * The method by which the date of the node is calculated, defaulted to 'End'.
   */
  @PropertyDefinition
  private final CurveNodeDate date;
  /**
   * The date order rules, used to ensure that the dates in the curve are in order.
   * If not specified, this will default to {@link CurveNodeDateOrder#DEFAULT}.
   */
  @PropertyDefinition(validate = "notNull", overrideGet = true)
  private final CurveNodeDateOrder dateOrder;

  //-------------------------------------------------------------------------
  /**
   * Returns a curve node for an FX Swap using the specified instrument template and keys.
   *

   * A suitable default label will be created.
   *
   * @param template  the template used for building the instrument for the node
   * @param farForwardPointsId  the identifier of the FX points at the far date
   * @return a node whose instrument is built from the template using a market rate
   */
  public static FxSwapCurveNode of(FxSwapTemplate template, ObservableId farForwardPointsId) {
    return builder()
        .template(template)
        .farForwardPointsId(farForwardPointsId)
        .build();
  }

  /**
   * Returns a curve node for an FX Swap using the specified instrument template and keys and label.
   *
   * @param template  the template used for building the instrument for the node
   * @param farForwardPointsId  the identifier of the FX points at the far date
   * @param label  the label to use for the node
   * @return a node whose instrument is built from the template using a market rate
   */
  public static FxSwapCurveNode of(FxSwapTemplate template, ObservableId farForwardPointsId, String label) {
    return builder()
        .template(template)
        .farForwardPointsId(farForwardPointsId)
        .label(label)
        .build();
  }

  @ImmutableDefaults
  private static void applyDefaults(Builder builder) {
    builder.date = CurveNodeDate.END;
    builder.dateOrder = CurveNodeDateOrder.DEFAULT;
  }

  @ImmutablePreBuild
  private static void preBuild(Builder builder) {
    if (builder.template != null) {
      if (builder.label == null) {
        builder.label = Tenor.of(builder.template.getPeriodToFar()).toString();
      }
      if (builder.fxRateId == null) {
        builder.fxRateId = FxRateId.of(builder.template.getCurrencyPair());
      } else {
        ArgChecker.isTrue(
            builder.fxRateId.getPair().toConventional().equals(builder.template.getCurrencyPair().toConventional()),
            "FxRateId currency pair '{}' must match that of the template '{}'",
            builder.fxRateId.getPair(),
            builder.template.getCurrencyPair());
      }
    }
  }

  //-------------------------------------------------------------------------
  @Override
  public Set<? extends MarketDataId<?>> requirements() {
    // TODO: extra identifier for near forward points
    return ImmutableSet.of(fxRateId, farForwardPointsId);
  }

  @Override
  public LocalDate date(LocalDate valuationDate, ReferenceData refData) {
    return date.calculate(
        () -> calculateEnd(valuationDate, refData),
        () -> calculateLastFixingDate(valuationDate, refData));
  }

  @Override
  public DatedParameterMetadata metadata(LocalDate valuationDate, ReferenceData refData) {
    LocalDate nodeDate = date(valuationDate, refData);
    if (date.isFixed()) {
      return LabelDateParameterMetadata.of(nodeDate, label);
    }
    Tenor tenor = Tenor.of(template.getPeriodToFar());
    return TenorDateParameterMetadata.of(nodeDate, tenor, label);
  }

  // calculate the end date
  private LocalDate calculateEnd(LocalDate valuationDate, ReferenceData refData) {
    FxSwapTrade trade = template.createTrade(valuationDate, BuySell.BUY, 1, 1, 0, refData);
    return trade.getProduct().getFarLeg().resolve(refData).getPaymentDate();
  }

  // calculate the last fixing date
  private LocalDate calculateLastFixingDate(LocalDate valuationDate, ReferenceData refData) {
    throw new UnsupportedOperationException("Node date of 'LastFixing' is not supported for FxSwap");
  }

  @Override
  public FxSwapTrade trade(double quantity, MarketData marketData, ReferenceData refData) {
    FxRate fxRate = marketData.getValue(fxRateId);
    double rate = fxRate.fxRate(template.getCurrencyPair());
    double fxPts = marketData.getValue(farForwardPointsId);
    BuySell buySell = quantity > 0 ? BuySell.BUY : BuySell.SELL;
    return template.createTrade(marketData.getValuationDate(), buySell, Math.abs(quantity), rate, fxPts, refData);
  }

  @Override
  public ResolvedFxSwapTrade resolvedTrade(double quantity, MarketData marketData, ReferenceData refData) {
    return trade(quantity, marketData, refData).resolve(refData);
  }

  @Override
  public double initialGuess(MarketData marketData, ValueType valueType) {
    if (ValueType.DISCOUNT_FACTOR.equals(valueType)) {
      return 1d;
    }
    return 0d;
  }

  //-------------------------------------------------------------------------
  /**
   * Returns a copy of this node with the specified date.
   *
   * @param date  the date to use
   * @return the node based on this node with the specified date
   */
  public FxSwapCurveNode withDate(CurveNodeDate date) {
    return new FxSwapCurveNode(template, fxRateId, farForwardPointsId, label, date, dateOrder);
  }

  //------------------------- AUTOGENERATED START -------------------------
  ///CLOVER:OFF
  /**
   * The meta-bean for {@code FxSwapCurveNode}.
   * @return the meta-bean, not null
   */
  public static FxSwapCurveNode.Meta meta() {
    return FxSwapCurveNode.Meta.INSTANCE;
  }

  static {
    JodaBeanUtils.registerMetaBean(FxSwapCurveNode.Meta.INSTANCE);
  }

  /**
   * The serialization version id.
   */
  private static final long serialVersionUID = 1L;

  /**
   * Returns a builder used to create an instance of the bean.
   * @return the builder, not null
   */
  public static FxSwapCurveNode.Builder builder() {
    return new FxSwapCurveNode.Builder();
  }

  private FxSwapCurveNode(
      FxSwapTemplate template,
      FxRateId fxRateId,
      ObservableId farForwardPointsId,
      String label,
      CurveNodeDate date,
      CurveNodeDateOrder dateOrder) {
    JodaBeanUtils.notNull(template, "template");
    JodaBeanUtils.notNull(fxRateId, "fxRateId");
    JodaBeanUtils.notNull(farForwardPointsId, "farForwardPointsId");
    JodaBeanUtils.notEmpty(label, "label");
    JodaBeanUtils.notNull(dateOrder, "dateOrder");
    this.template = template;
    this.fxRateId = fxRateId;
    this.farForwardPointsId = farForwardPointsId;
    this.label = label;
    this.date = date;
    this.dateOrder = dateOrder;
  }

  @Override
  public FxSwapCurveNode.Meta metaBean() {
    return FxSwapCurveNode.Meta.INSTANCE;
  }

  @Override
  public <R> Property<R> property(String propertyName) {
    return metaBean().<R>metaProperty(propertyName).createProperty(this);
  }

  @Override
  public Set<String> propertyNames() {
    return metaBean().metaPropertyMap().keySet();
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the template for the FX Swap associated with this node.
   * @return the value of the property, not null
   */
  public FxSwapTemplate getTemplate() {
    return template;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the identifier used to obtain the FX rate market value, defaulted from the template.
   * This only needs to be specified if using multiple market data sources.
   * @return the value of the property, not null
   */
  public FxRateId getFxRateId() {
    return fxRateId;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the identifier of the market data value which provides the FX forward points.
   * @return the value of the property, not null
   */
  public ObservableId getFarForwardPointsId() {
    return farForwardPointsId;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the label to use for the node, defaulted.
   *

   * When building, this will default based on the far period if not specified.
   * @return the value of the property, not empty
   */
  @Override
  public String getLabel() {
    return label;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the method by which the date of the node is calculated, defaulted to 'End'.
   * @return the value of the property
   */
  public CurveNodeDate getDate() {
    return date;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the date order rules, used to ensure that the dates in the curve are in order.
   * If not specified, this will default to {@link CurveNodeDateOrder#DEFAULT}.
   * @return the value of the property, not null
   */
  @Override
  public CurveNodeDateOrder getDateOrder() {
    return dateOrder;
  }

  //-----------------------------------------------------------------------
  /**
   * Returns a builder that allows this bean to be mutated.
   * @return the mutable builder, not null
   */
  public Builder toBuilder() {
    return new Builder(this);
  }

  @Override
  public boolean equals(Object obj) {
    if (obj == this) {
      return true;
    }
    if (obj != null && obj.getClass() == this.getClass()) {
      FxSwapCurveNode other = (FxSwapCurveNode) obj;
      return JodaBeanUtils.equal(template, other.template) &&
          JodaBeanUtils.equal(fxRateId, other.fxRateId) &&
          JodaBeanUtils.equal(farForwardPointsId, other.farForwardPointsId) &&
          JodaBeanUtils.equal(label, other.label) &&
          JodaBeanUtils.equal(date, other.date) &&
          JodaBeanUtils.equal(dateOrder, other.dateOrder);
    }
    return false;
  }

  @Override
  public int hashCode() {
    int hash = getClass().hashCode();
    hash = hash * 31 + JodaBeanUtils.hashCode(template);
    hash = hash * 31 + JodaBeanUtils.hashCode(fxRateId);
    hash = hash * 31 + JodaBeanUtils.hashCode(farForwardPointsId);
    hash = hash * 31 + JodaBeanUtils.hashCode(label);
    hash = hash * 31 + JodaBeanUtils.hashCode(date);
    hash = hash * 31 + JodaBeanUtils.hashCode(dateOrder);
    return hash;
  }

  @Override
  public String toString() {
    StringBuilder buf = new StringBuilder(224);
    buf.append("FxSwapCurveNode{");
    buf.append("template").append('=').append(template).append(',').append(' ');
    buf.append("fxRateId").append('=').append(fxRateId).append(',').append(' ');
    buf.append("farForwardPointsId").append('=').append(farForwardPointsId).append(',').append(' ');
    buf.append("label").append('=').append(label).append(',').append(' ');
    buf.append("date").append('=').append(date).append(',').append(' ');
    buf.append("dateOrder").append('=').append(JodaBeanUtils.toString(dateOrder));
    buf.append('}');
    return buf.toString();
  }

  //-----------------------------------------------------------------------
  /**
   * The meta-bean for {@code FxSwapCurveNode}.
   */
  public static final class Meta extends DirectMetaBean {
    /**
     * The singleton instance of the meta-bean.
     */
    static final Meta INSTANCE = new Meta();

    /**
     * The meta-property for the {@code template} property.
     */
    private final MetaProperty<FxSwapTemplate> template = DirectMetaProperty.ofImmutable(
        this, "template", FxSwapCurveNode.class, FxSwapTemplate.class);
    /**
     * The meta-property for the {@code fxRateId} property.
     */
    private final MetaProperty<FxRateId> fxRateId = DirectMetaProperty.ofImmutable(
        this, "fxRateId", FxSwapCurveNode.class, FxRateId.class);
    /**
     * The meta-property for the {@code farForwardPointsId} property.
     */
    private final MetaProperty<ObservableId> farForwardPointsId = DirectMetaProperty.ofImmutable(
        this, "farForwardPointsId", FxSwapCurveNode.class, ObservableId.class);
    /**
     * The meta-property for the {@code label} property.
     */
    private final MetaProperty<String> label = DirectMetaProperty.ofImmutable(
        this, "label", FxSwapCurveNode.class, String.class);
    /**
     * The meta-property for the {@code date} property.
     */
    private final MetaProperty<CurveNodeDate> date = DirectMetaProperty.ofImmutable(
        this, "date", FxSwapCurveNode.class, CurveNodeDate.class);
    /**
     * The meta-property for the {@code dateOrder} property.
     */
    private final MetaProperty<CurveNodeDateOrder> dateOrder = DirectMetaProperty.ofImmutable(
        this, "dateOrder", FxSwapCurveNode.class, CurveNodeDateOrder.class);
    /**
     * The meta-properties.
     */
    private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap(
        this, null,
        "template",
        "fxRateId",
        "farForwardPointsId",
        "label",
        "date",
        "dateOrder");

    /**
     * Restricted constructor.
     */
    private Meta() {
    }

    @Override
    protected MetaProperty<?> metaPropertyGet(String propertyName) {
      switch (propertyName.hashCode()) {
        case -1321546630:  // template
          return template;
        case -1054985843:  // fxRateId
          return fxRateId;
        case -566044884:  // farForwardPointsId
          return farForwardPointsId;
        case 102727412:  // label
          return label;
        case 3076014:  // date
          return date;
        case -263699392:  // dateOrder
          return dateOrder;
      }
      return super.metaPropertyGet(propertyName);
    }

    @Override
    public FxSwapCurveNode.Builder builder() {
      return new FxSwapCurveNode.Builder();
    }

    @Override
    public Class<? extends FxSwapCurveNode> beanType() {
      return FxSwapCurveNode.class;
    }

    @Override
    public Map<String, MetaProperty<?>> metaPropertyMap() {
      return metaPropertyMap$;
    }

    //-----------------------------------------------------------------------
    /**
     * The meta-property for the {@code template} property.
     * @return the meta-property, not null
     */
    public MetaProperty<FxSwapTemplate> template() {
      return template;
    }

    /**
     * The meta-property for the {@code fxRateId} property.
     * @return the meta-property, not null
     */
    public MetaProperty<FxRateId> fxRateId() {
      return fxRateId;
    }

    /**
     * The meta-property for the {@code farForwardPointsId} property.
     * @return the meta-property, not null
     */
    public MetaProperty<ObservableId> farForwardPointsId() {
      return farForwardPointsId;
    }

    /**
     * The meta-property for the {@code label} property.
     * @return the meta-property, not null
     */
    public MetaProperty<String> label() {
      return label;
    }

    /**
     * The meta-property for the {@code date} property.
     * @return the meta-property, not null
     */
    public MetaProperty<CurveNodeDate> date() {
      return date;
    }

    /**
     * The meta-property for the {@code dateOrder} property.
     * @return the meta-property, not null
     */
    public MetaProperty<CurveNodeDateOrder> dateOrder() {
      return dateOrder;
    }

    //-----------------------------------------------------------------------
    @Override
    protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
      switch (propertyName.hashCode()) {
        case -1321546630:  // template
          return ((FxSwapCurveNode) bean).getTemplate();
        case -1054985843:  // fxRateId
          return ((FxSwapCurveNode) bean).getFxRateId();
        case -566044884:  // farForwardPointsId
          return ((FxSwapCurveNode) bean).getFarForwardPointsId();
        case 102727412:  // label
          return ((FxSwapCurveNode) bean).getLabel();
        case 3076014:  // date
          return ((FxSwapCurveNode) bean).getDate();
        case -263699392:  // dateOrder
          return ((FxSwapCurveNode) bean).getDateOrder();
      }
      return super.propertyGet(bean, propertyName, quiet);
    }

    @Override
    protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
      metaProperty(propertyName);
      if (quiet) {
        return;
      }
      throw new UnsupportedOperationException("Property cannot be written: " + propertyName);
    }

  }

  //-----------------------------------------------------------------------
  /**
   * The bean-builder for {@code FxSwapCurveNode}.
   */
  public static final class Builder extends DirectFieldsBeanBuilder<FxSwapCurveNode> {

    private FxSwapTemplate template;
    private FxRateId fxRateId;
    private ObservableId farForwardPointsId;
    private String label;
    private CurveNodeDate date;
    private CurveNodeDateOrder dateOrder;

    /**
     * Restricted constructor.
     */
    private Builder() {
      applyDefaults(this);
    }

    /**
     * Restricted copy constructor.
     * @param beanToCopy  the bean to copy from, not null
     */
    private Builder(FxSwapCurveNode beanToCopy) {
      this.template = beanToCopy.getTemplate();
      this.fxRateId = beanToCopy.getFxRateId();
      this.farForwardPointsId = beanToCopy.getFarForwardPointsId();
      this.label = beanToCopy.getLabel();
      this.date = beanToCopy.getDate();
      this.dateOrder = beanToCopy.getDateOrder();
    }

    //-----------------------------------------------------------------------
    @Override
    public Object get(String propertyName) {
      switch (propertyName.hashCode()) {
        case -1321546630:  // template
          return template;
        case -1054985843:  // fxRateId
          return fxRateId;
        case -566044884:  // farForwardPointsId
          return farForwardPointsId;
        case 102727412:  // label
          return label;
        case 3076014:  // date
          return date;
        case -263699392:  // dateOrder
          return dateOrder;
        default:
          throw new NoSuchElementException("Unknown property: " + propertyName);
      }
    }

    @Override
    public Builder set(String propertyName, Object newValue) {
      switch (propertyName.hashCode()) {
        case -1321546630:  // template
          this.template = (FxSwapTemplate) newValue;
          break;
        case -1054985843:  // fxRateId
          this.fxRateId = (FxRateId) newValue;
          break;
        case -566044884:  // farForwardPointsId
          this.farForwardPointsId = (ObservableId) newValue;
          break;
        case 102727412:  // label
          this.label = (String) newValue;
          break;
        case 3076014:  // date
          this.date = (CurveNodeDate) newValue;
          break;
        case -263699392:  // dateOrder
          this.dateOrder = (CurveNodeDateOrder) newValue;
          break;
        default:
          throw new NoSuchElementException("Unknown property: " + propertyName);
      }
      return this;
    }

    @Override
    public Builder set(MetaProperty<?> property, Object value) {
      super.set(property, value);
      return this;
    }

    @Override
    public Builder setString(String propertyName, String value) {
      setString(meta().metaProperty(propertyName), value);
      return this;
    }

    @Override
    public Builder setString(MetaProperty<?> property, String value) {
      super.setString(property, value);
      return this;
    }

    @Override
    public Builder setAll(Map<String, ? extends Object> propertyValueMap) {
      super.setAll(propertyValueMap);
      return this;
    }

    @Override
    public FxSwapCurveNode build() {
      preBuild(this);
      return new FxSwapCurveNode(
          template,
          fxRateId,
          farForwardPointsId,
          label,
          date,
          dateOrder);
    }

    //-----------------------------------------------------------------------
    /**
     * Sets the template for the FX Swap associated with this node.
     * @param template  the new value, not null
     * @return this, for chaining, not null
     */
    public Builder template(FxSwapTemplate template) {
      JodaBeanUtils.notNull(template, "template");
      this.template = template;
      return this;
    }

    /**
     * Sets the identifier used to obtain the FX rate market value, defaulted from the template.
     * This only needs to be specified if using multiple market data sources.
     * @param fxRateId  the new value, not null
     * @return this, for chaining, not null
     */
    public Builder fxRateId(FxRateId fxRateId) {
      JodaBeanUtils.notNull(fxRateId, "fxRateId");
      this.fxRateId = fxRateId;
      return this;
    }

    /**
     * Sets the identifier of the market data value which provides the FX forward points.
     * @param farForwardPointsId  the new value, not null
     * @return this, for chaining, not null
     */
    public Builder farForwardPointsId(ObservableId farForwardPointsId) {
      JodaBeanUtils.notNull(farForwardPointsId, "farForwardPointsId");
      this.farForwardPointsId = farForwardPointsId;
      return this;
    }

    /**
     * Sets the label to use for the node, defaulted.
     *

     * When building, this will default based on the far period if not specified.
     * @param label  the new value, not empty
     * @return this, for chaining, not null
     */
    public Builder label(String label) {
      JodaBeanUtils.notEmpty(label, "label");
      this.label = label;
      return this;
    }

    /**
     * Sets the method by which the date of the node is calculated, defaulted to 'End'.
     * @param date  the new value
     * @return this, for chaining, not null
     */
    public Builder date(CurveNodeDate date) {
      this.date = date;
      return this;
    }

    /**
     * Sets the date order rules, used to ensure that the dates in the curve are in order.
     * If not specified, this will default to {@link CurveNodeDateOrder#DEFAULT}.
     * @param dateOrder  the new value, not null
     * @return this, for chaining, not null
     */
    public Builder dateOrder(CurveNodeDateOrder dateOrder) {
      JodaBeanUtils.notNull(dateOrder, "dateOrder");
      this.dateOrder = dateOrder;
      return this;
    }

    //-----------------------------------------------------------------------
    @Override
    public String toString() {
      StringBuilder buf = new StringBuilder(224);
      buf.append("FxSwapCurveNode.Builder{");
      buf.append("template").append('=').append(JodaBeanUtils.toString(template)).append(',').append(' ');
      buf.append("fxRateId").append('=').append(JodaBeanUtils.toString(fxRateId)).append(',').append(' ');
      buf.append("farForwardPointsId").append('=').append(JodaBeanUtils.toString(farForwardPointsId)).append(',').append(' ');
      buf.append("label").append('=').append(JodaBeanUtils.toString(label)).append(',').append(' ');
      buf.append("date").append('=').append(JodaBeanUtils.toString(date)).append(',').append(' ');
      buf.append("dateOrder").append('=').append(JodaBeanUtils.toString(dateOrder));
      buf.append('}');
      return buf.toString();
    }

  }

  ///CLOVER:ON
  //-------------------------- AUTOGENERATED END --------------------------
}


text:
THORSANVIL_ROOT				?= $(realpath ../../../)

HAVE_DEVLOADER_yes			= -DHAVE_DEVLOADER
HAVE_DEVLOADER				= $(HAVE_DEVLOADER_$(HAVE_ThorsSerialize))
THOR_SERIALIZER_NEEDED_yes	= ThorSerialize
THOR_SERIALIZER_NEEDED		= $(THOR_SERIALIZER_NEEDED_$(HAVE_ThorsSerialize))

PRETEST						= TestLoadableLibBuild
TARGET						= ThorsNisseProtocolHTTP.a
CXXFLAGS					+= -I$(event_ROOT_DIR)/include $(thorsSerialize_ROOT_INCDIR) $(HAVE_DEVLOADER) -Wno-ignored-attributes
LDLIBS						+= -L$(event_ROOT_DIR)/lib -l$(event_ROOT_LIB) $(thorsSerialize_ROOT_LIBDIR) $(BOOST_SYSTEM_LIB) $(BOOST_COROUTINE_LIB) $(BOOST_CONTEXT_LIB) -ldl
LINK_LIBS					= ThorsNisseCoreService ThorsNisseCoreSocket ThorsSerialize
TEST_IGNORE					= http_parser.cpp http_parser.h
UNITTEST_LDLIBS				= -ldl $(thorsSerialize_ROOT_LIBDIR)
UNITTEST_LINK_LIBS			= ThorsNisseCoreService ThorsNisseCoreSocket $(THOR_SERIALIZER_NEEDED)

IGNORE_BOOST_ISSUES_2	= -Wno-extra -Wno-terminate
IGNORE_BOOST_ISSUES		= $(IGNORE_BOOST_ISSUES_$(BOOST_COROUTINE_VERSION))

UNITTEST_RUNTIME_PATH		= $(subst -L,,$(thorsSerialize_ROOT_LIBDIR))

FILE_WARNING_FLAGS	+= -Wno-unknown-pragmas
%/HTTPProtocol.o:		FILE_WARNING_FLAGS	+= $(IGNORE_BOOST_ISSUES)
%/HttpScanner.o:		FILE_WARNING_FLAGS	+= $(IGNORE_BOOST_ISSUES)
%/Binder.o:				FILE_WARNING_FLAGS	+= $(IGNORE_BOOST_ISSUES)
%/Route.o:				FILE_WARNING_FLAGS	+= $(IGNORE_BOOST_ISSUES)
%/Types.o:				FILE_WARNING_FLAGS	+= $(IGNORE_BOOST_ISSUES)

include $(THORSANVIL_ROOT)/build/tools/Makefile

.PHONEY:	TestLoadableLibBuild
TestLoadableLibBuild:
	@make -C TestLib/Loadable all
	@make -C TestLib/NoGet    all
	@make -C TestLib/GetNull  all


text:
require "carafe/version"

load File.expand_path("../capistrano/tasks/defaults.rake", __FILE__)
load File.expand_path("../capistrano/tasks/deploy.rake", __FILE__)
load File.expand_path("../capistrano/tasks/local.rake", __FILE__)
load File.expand_path("../capistrano/tasks/buildhost.rake", __FILE__)
load File.expand_path("../capistrano/tasks/node.rake", __FILE__)

module Carafe
  # The methods in this module are made available to all Capistrano tasks.
  module DSL
    # Returns the build host, to be consumed by capistrano's +on+ method like this:
    #
    #   task :my_task do
    #     on build_host do
    #       ...
    #     end
    #   end
    def build_host
      hosts = roles(:build)

      raise "No build host available." if hosts.none?
      raise "There can only be one build host." if hosts.length > 1

      hosts.first
    end

    # Returns the build path on the build host, can be used with capistrano's +within+ method like this:
    #
    #   task :my_task do
    #     on build_host do |host|
    #       within build_path do
    #         ...
    #       end
    #     end
    #   end
    #
    # @return [Pathname]
    def build_path
      Pathname(fetch(:build_path) { raise "no :build_path configured" })
    end

    # Returns the mix environment to be used when preparing and creating the release.
    # Can be used with capistrano's +with+ method like this:
    #
    #   task :my_task do
    #     on build_host do |host|
    #       within build_path do
    #         with mix_env: mix_env do
    #           ...
    #         end
    #       end
    #     end
    #   end
    #
    # Note that +with+ upcases the key, such that the name of the OS environment variable
    # will be +MIX_ENV+.
    #
    # @return [String]
    def mix_env
      fetch(:mix_env).to_s
    end

    # Returns the path on the target hosts where releases are extracted and loaded from.
    #
    # @return [Pathname]
    def app_path
      Pathname(fetch(:app_path) { raise "set :app_path node path where the release is unpacked an run" })
    end

    # Returns an array of application nodes, to be consumed by capistrano's +on+ method like this:
    #
    #   task :my_task do
    #     on app_hosts do
    #       ...
    #     end
    #   end
    #
    def app_hosts
      hosts = roles(:app)

      raise "No hosts have been configured with role 'app'" if hosts.none?

      hosts
    end

    # Returns the distillery environment to use, defaulting to the result of +mix_env+.
    # The distillery environment is configured in +rel/config.exs+.
    #
    # @return [String]
    def distillery_environment
      fetch(:distillery_environment).to_s
    end

    # Executes the given elixir code on the node, through the rpc interface.
    # Fails if the code raises an exception or returns +:error+ or <tt>{:error, _}</tt>.
    def execute_elixir(elixir_string)
      script = fetch(:distillery_release)
      execute "bin/#{script}", "rpc", "Elixir.Carafe", "execute_elixir", elixir_string.shellescape
    end
  end
end

extend Carafe::DSL
SSHKit::Backend::Abstract.include Carafe::DSL


text:
Allows you to change your osu! background without supporter status!

## Usage
1. Open the program
2. Through the "File" menu, press "Open" and select an `osu!seasonal.dll` file.
3. Replace any image you want by selecting them from the list and picking a new image with "Replace" from the "Edit" menu.
4. Save the file with the "Save" option in the "File" menu.
5. Rename the saved file to `osu!seasonal.dll` and place it in your osu! directory, overwriting the old file.
6. Make sure the `Seasonal backgrounds` option in osu! is set to `Always`!

## Changelog
Note: this list only includes main features.
* **v1.1**
  * Add exporting of images
  * Add clearing of images
  * Add keyboard shortcuts for nearly every action
  * Replace images on doubleclick
* **v1.0**
  * Initial release.


text:
using java.lang;
using org.eclipse.core.resources;
using org.eclipse.core.runtime;
using org.eclipse.jface.action;
using org.eclipse.jface.viewers;
using org.eclipse.ui;
using cnatural.eclipse.helpers;

namespace cnatural.eclipse {

	//
	// The nature for the Stab language
	//
	public class Nature : IProjectNature {
		private IProject project;

		public Nature() {
		}

		public IProject getProject() {
			return project;
		}

		public void setProject(IProject project) {
			this.project = project;
		}

		public void configure() {
			var description = project.getDescription();
			var commands = description.getBuildSpec();
			var newCommands = new ICommand[sizeof(commands) + 1];
			System.arraycopy(commands, 0, newCommands, 0, sizeof(commands));
			var buildCommand = description.newCommand();
			buildCommand.setBuilderName(Environment.BUILDER_ID);
			newCommands[sizeof(commands)] = buildCommand;
			description.setBuildSpec(newCommands);
			project.setDescription(description, IProject.FORCE, null);
			Environment.configureProject(project);
		}

		public void deconfigure() {
			var description = project.getDescription();
			var commands = description.getBuildSpec();
			var newCommands = new ICommand[sizeof(commands) - 1];
			for (int i = 0, j = 0; i < sizeof(commands); i++, j++) {
				if (Environment.BUILDER_ID.equals(commands[i].getBuilderName())) {
					i++;
				} else {
					newCommands[j] = commands[i];
				}
			}
			description.setBuildSpec(newCommands);
			project.setDescription(description, IProject.FORCE, null);
			Environment.deconfigureProject(project);
		}
	}

	//
	// The action used to add/remove Stab support to/from a project.
	//
	public class ToggleNatureAction : IObjectActionDelegate {
		private ISelection selection;

		public ToggleNatureAction() {
		}

		public void selectionChanged(IAction action, ISelection selection) {
			this.selection = selection;
		}

		public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		}

		public void run(IAction action) {
			var project = EclipseHelper.getProjectFromSelection(selection);
			if (project != null) {
				try {
					var description = project.getDescription();
					var natureIds = description.getNatureIds();
					String[] newNatureIds;
					if (project.hasNature(Environment.NATURE_ID)) {
						newNatureIds = new String[sizeof(natureIds) - 1];
						for (int i = 0, j = 0; i < sizeof(natureIds); i++, j++) {
							if (natureIds[i].equals(Environment.NATURE_ID)) {
								i++;
							} else {
								newNatureIds[j] = natureIds[i];
							}
						}
					} else {
						newNatureIds = new String[sizeof(natureIds) + 1];
						newNatureIds[0] = Environment.NATURE_ID;
						System.arraycopy(natureIds, 0, newNatureIds, 1, sizeof(natureIds));
					}
					description.setNatureIds(newNatureIds);
					project.setDescription(description, IProject.FORCE, null);
				} catch (CoreException e) {
					Environment.logException(e);
				}
			}
		}
	}
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Traffic Lights Controller</title>

    <link rel="stylesheet" href="css/bootstrap.css">
    <link rel="stylesheet" href="css/main.css">

Traffic Lights Controller

Current Status