text:
namespace zetasql {

class QueryResolutionInfo;
struct ExprResolutionInfo;

// Return true if <expr> can be treated like a constant,
// meaning it has the same value for the entire query and has no
// side effects.
//
// This shouldn't fail, except for unimplemented cases.
//
// Functions like RAND() are not constant.  UDFs may not be constant.
// Functions like CURRENT_TIMESTAMP() are considered constant because they
// always return a constant within the same query.
//
// The current definition uses these rules:
// - literals and parameters are constant
// - column references are not constant
// - scalar functions are constant if FunctionOptions::volatility is
//   IMMUTABLE or STABLE, and if all arguments are constant
// - aggregate and analytic functions are not constant
// - expression subqueries are not constant
// - built-in operators like CAST and CASE and struct field access are
//   constant if all arguments are constant
absl::StatusOr<bool> IsConstantExpression(const ResolvedExpr* expr);

// Helper for representing if we're allowed to flatten (ie: allowed to dot into
// the fields of a proto/struct/json array), and if so, if we're already in a
// ResolvedFlatten from having previously done so.
//
// Flattening is allowed:
// - inside an explicit FLATTEN(...) call
// - in an UNNEST
//
// Once we're allowed to flatten and we do a field access on an array, then we
// being constructing a ResolvedFlatten. The FlattenState tracks the current
// ResolvedFlatten we're building and whether it's active or not.
//
// This allows us to differentiate:
//    FLATTEN(a.b.c)[OFFSET(0)]
// from
//    FLATTEN(a.b.c[OFFSET(0)])
//
// In both cases, the input expression to the offset is the ResolvedFlatten
// but in the former case (no active flatten), the offset should be on the
// result, whereas in the latter the offset should be on the active flatten.
class FlattenState {
 public:
  FlattenState() = default;
  FlattenState(const FlattenState&) = delete;
  FlattenState& operator=(const FlattenState&) = delete;

  ~FlattenState() {
    if (parent_ != nullptr) parent_->active_flatten_ = active_flatten_;
  }

  // Sets the parent for this FlattenState. This copies state from the parent,
  // but also causes the active flatten to propagate back to parent after
  // destruction so a child ExprResolutionInfo can essentially share
  // FlattenState.
  void SetParent(FlattenState* parent) {
    ZETASQL_DCHECK(parent_ == nullptr) << "Parent shouldn't be set more than once";
    ZETASQL_CHECK(parent);
    parent_ = parent;
    can_flatten_ = parent->can_flatten_;
    active_flatten_ = parent->active_flatten_;
  }

  // Helper to allow restoring original `can_flatten` state when desired.
  class Restorer {
   public:
    ~Restorer() {
      if (can_flatten_) *can_flatten_ = original_can_flatten_;
    }
    void Activate(bool* can_flatten) {
      can_flatten_ = can_flatten;
      original_can_flatten_ = *can_flatten;
    }
   private:
    bool* can_flatten_ = nullptr;
    bool original_can_flatten_;
  };
  bool can_flatten() const { return can_flatten_; }
  void set_can_flatten(bool can_flatten, Restorer* restorer) {
    restorer->Activate(&can_flatten_);
    can_flatten_ = can_flatten;
  }

  ResolvedFlatten* active_flatten() const { return active_flatten_; }
  void set_active_flatten(ResolvedFlatten* flatten) {
    active_flatten_ = flatten;
  }

 private:
  FlattenState* parent_ = nullptr;
  bool can_flatten_ = false;
  ResolvedFlatten* active_flatten_ = nullptr;
};

// This contains common info needed to resolve and validate an expression.
// It includes both the constant info describing what is allowed while
// resolving the expression and mutable info that returns what it actually
// has. It is passed recursively down through all expressions.
struct ExprResolutionInfo {
  // Construct an ExprResolutionInfo with given resolution context and
  // constraints.  Takes a <name_scope_in> that is used to resolve the
  // expression against, and an <aggregate_name_scope_in> that is used
  // to resolve any expression that is an aggregate function argument, and
  // likewise <analytic_name_scope_in> with analytic function arguments. Does
  // not take ownership of <select_column_state_list_in>,
  // <query_resolution_info_in>, or <top_level_ast_expr_in>.
  ExprResolutionInfo(const NameScope* name_scope_in,
                     const NameScope* aggregate_name_scope_in,
                     const NameScope* analytic_name_scope_in,
                     bool allows_aggregation_in, bool allows_analytic_in,
                     bool use_post_grouping_columns_in,
                     const char* clause_name_in,
                     QueryResolutionInfo* query_resolution_info_in,
                     const ASTExpression* top_level_ast_expr_in = nullptr,
                     IdString column_alias_in = IdString());

  // Construct an ExprResolutionInfo that allows both aggregation and
  // analytic expressions.
  // Does not take ownership of <query_resolution_info_in>.
  // Currently used for initially resolving select list columns, and
  // resolving LIMIT with an empty NameScope, so never resolves against
  // post-grouping columns.
  ExprResolutionInfo(const NameScope* name_scope_in,
                     QueryResolutionInfo* query_resolution_info_in,
                     const ASTExpression* top_level_ast_expr_in = nullptr,
                     IdString column_alias_in = IdString());

  // Construct an ExprResolutionInfo that disallows aggregation and analytic
  // expressions.
  ExprResolutionInfo(const NameScope* name_scope_in,
                     const char* clause_name_in);

  // Construct an ExprResolutionInfo that initializes itself from another
  // ExprResolutionInfo.
  // has_aggregation and has_analytic will be updated in parent on destruction.
  // can_flatten does not propagate.
  // Does not take ownership of <parent>.
  explicit ExprResolutionInfo(ExprResolutionInfo* parent);

  // Construct an ExprResolutionInfo that initializes itself from another
  // ExprResolutionInfo, overriding <name_scope>, <clause_name>, and
  // <allows_analytic>.
  // has_aggregation and has_analytic will be updated in parent on destruction.
  // Does not take ownership of <parent>. <can_flatten> does not propagate.
  ExprResolutionInfo(ExprResolutionInfo* parent, const NameScope* name_scope_in,
                     const char* clause_name_in, bool allows_analytic_in);

  ExprResolutionInfo(const ExprResolutionInfo&) = delete;
  ExprResolutionInfo& operator=(const ExprResolutionInfo&) = delete;

  ~ExprResolutionInfo();

  // Returns whether or not the current expression resolution is happening
  // after DISTINCT.
  bool is_post_distinct() const;

  std::string DebugString() const;

  // Constant info.

  ExprResolutionInfo* const parent = nullptr;

  // NameScope to use while resolving this expression.
  const NameScope* const name_scope = nullptr;

  // NameScope to use while resolving any aggregate function arguments that
  // are in this expression.
  const NameScope* const aggregate_name_scope = nullptr;

  // NameScope to use while resolving any analytic function arguments that
  // are in this expression.
  const NameScope* const analytic_name_scope = nullptr;

  // Indicates whether this expression allows aggregations.
  const bool allows_aggregation;

  // Indicates whether this expression allows analytic functions.
  const bool allows_analytic;

  // <clause_name> is used to generate an error saying aggregation/analytic
  // functions are not allowed in this clause, e.g. "WHERE clause".  It is
  // also used in error messages related to path expression resolution
  // after GROUP BY.
  // This can be empty if both aggregations and analytic functions are
  // allowed, or if there is no clear clause name to use in error messages
  // (for instance when resolving correlated path expressions that are in
  // a subquery's SELECT list but the subquery itself is in the outer
  // query's ORDER BY clause).
  const char* const clause_name;

  // Mutable info.

  // Must be non-NULL if <allows_aggregation> or <allows_analytic>.
  // If non-NULL, <query_resolution_info> gets updated during expression
  // resolution with aggregate and analytic function information present
  // in the expression.  It is unused if aggregate and analytic functions
  // are not allowed in the expression.
  // Not owned.
  QueryResolutionInfo* const query_resolution_info;

  // True if this expression contains an aggregation function.
  bool has_aggregation = false;

  // True if this expression contains an analytic function.
  bool has_analytic = false;

  // True if this expression should be resolved against post-grouping
  // columns.  Gets set to false when resolving arguments of aggregation
  // functions.
  bool use_post_grouping_columns = false;

  // The top-level AST expression being resolved in the current context. This
  // field is set only when resolving SELECT columns. Not owned.
  const ASTExpression* const top_level_ast_expr = nullptr;

  // The column alias of the top-level AST expression in SELECT list, which will
  // be used as the name of the resolved column when the top-level AST
  // expression being resolved is an aggregate or an analytic function. This
  // field is set only when resolving SELECT columns.
  const IdString column_alias = IdString();

  // Context around if we can flatten and if we're currently actively doing so.
  // See FlattenState for details.
  FlattenState flatten_state;
};

// Create a vector<const ASTNode*> from another container.
// It would be preferable to express this as a cast without a copy but that
// is not possible with the std::vector interface.
template <class NodeContainer>
std::vector<const ASTNode*> ToASTNodes(const NodeContainer& nodes) {
  std::vector<const ASTNode*> ast_locations;
  ast_locations.reserve(nodes.size());
  for (const ASTNode* node : nodes) {
    ast_locations.push_back(node);
  }
  return ast_locations;
}

// This helper class is for resolving table-valued functions. It represents a
// resolved argument to the TVF. The argument can be either a scalar
// expression, in which case <expr> is filled, a relation, in which case
// <scan> and <name_list> are filled (where <name_list> is for <scan>), or a
// machine learning model, in which case <model> is filled.
// The public accessors provide ways to set and retrieve the fields in a type
// safe manner.
class ResolvedTVFArg {
 public:
  void SetExpr(std::unique_ptr<const ResolvedExpr> expr) {
    expr_ = std::move(expr);
    type_ = EXPR;
  }
  void SetScan(std::unique_ptr<const ResolvedScan> scan,
               std::shared_ptr<const NameList> name_list) {
    scan_ = std::move(scan);
    name_list_ = name_list;
    type_ = SCAN;
  }
  void SetModel(std::unique_ptr<const ResolvedModel> model) {
    model_ = std::move(model);
    type_ = MODEL;
  }
  void SetConnection(std::unique_ptr<const ResolvedConnection> connection) {
    connection_ = std::move(connection);
    type_ = CONNECTION;
  }
  void SetDescriptor(std::unique_ptr<const ResolvedDescriptor> descriptor) {
    descriptor_ = std::move(descriptor);
    type_ = DESCRIPTOR;
  }

  bool IsExpr() const { return type_ == EXPR; }
  bool IsScan() const { return type_ == SCAN; }
  bool IsModel() const { return type_ == MODEL; }
  bool IsConnection() const { return type_ == CONNECTION; }
  bool IsDescriptor() const { return type_ == DESCRIPTOR; }

  absl::StatusOr<const ResolvedExpr*> GetExpr() const {
    ZETASQL_RET_CHECK(IsExpr());
    return expr_.get();
  }
  absl::StatusOr<const ResolvedScan*> GetScan() const {
    ZETASQL_RET_CHECK(IsScan());
    return scan_.get();
  }
  absl::StatusOr<const ResolvedModel*> GetModel() const {
    ZETASQL_RET_CHECK(IsModel());
    return model_.get();
  }
  absl::StatusOr<const ResolvedConnection*> GetConnection() const {
    ZETASQL_RET_CHECK(IsConnection());
    return connection_.get();
  }
  absl::StatusOr<const ResolvedDescriptor*> GetDescriptor() const {
    ZETASQL_RET_CHECK(IsDescriptor());
    return descriptor_.get();
  }
  absl::StatusOr<std::shared_ptr<const NameList>> GetNameList() const {
    ZETASQL_RET_CHECK(IsScan());
    return name_list_;
  }

  absl::StatusOr<std::unique_ptr<const ResolvedExpr>> MoveExpr() {
    ZETASQL_RET_CHECK(IsExpr());
    return std::move(expr_);
  }
  absl::StatusOr<std::unique_ptr<const ResolvedScan>> MoveScan() {
    ZETASQL_RET_CHECK(IsScan());
    return std::move(scan_);
  }
  absl::StatusOr<std::unique_ptr<const ResolvedModel>> MoveModel() {
    ZETASQL_RET_CHECK(IsModel());
    return std::move(model_);
  }
  absl::StatusOr<std::unique_ptr<const ResolvedConnection>> MoveConnection() {
    ZETASQL_RET_CHECK(IsConnection());
    return std::move(connection_);
  }
  absl::StatusOr<std::unique_ptr<const ResolvedDescriptor>> MoveDescriptor() {
    ZETASQL_RET_CHECK(IsDescriptor());
    return std::move(descriptor_);
  }

 private:
  enum {
    UNDEFINED,
    EXPR,
    SCAN,
    MODEL,
    CONNECTION,
    DESCRIPTOR
  } type_ = UNDEFINED;
  std::unique_ptr<const ResolvedExpr> expr_;
  std::unique_ptr<const ResolvedScan> scan_;
  std::unique_ptr<const ResolvedModel> model_;
  std::unique_ptr<const ResolvedConnection> connection_;
  std::unique_ptr<const ResolvedDescriptor> descriptor_;
  std::shared_ptr<const NameList> name_list_;
};

}  // namespace zetasql

#endif  // ZETASQL_ANALYZER_EXPR_RESOLVER_HELPER_H_


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.

package org.apache.impala.rewrite;

import org.apache.impala.analysis.Analyzer;
import org.apache.impala.analysis.BetweenPredicate;
import org.apache.impala.analysis.BinaryPredicate;
import org.apache.impala.analysis.CompoundPredicate;
import org.apache.impala.analysis.Expr;
import org.apache.impala.analysis.Predicate;

/**
 * Rewrites BetweenPredicates into an equivalent conjunctive/disjunctive
 * CompoundPredicate.
 * It can be applied to pre-analysis expr trees and therefore does not reanalyze
 * the transformation output itself.
 * Examples:
 * A BETWEEN X AND Y ==> A >= X AND A <= Y
 * A NOT BETWEEN X AND Y ==> A < X OR A > Y
 */
public class BetweenToCompoundRule implements ExprRewriteRule {
  public static ExprRewriteRule INSTANCE = new BetweenToCompoundRule();

  @Override
  public Expr apply(Expr expr, Analyzer analyzer) {
    if (!(expr instanceof BetweenPredicate)) return expr;
    BetweenPredicate bp = (BetweenPredicate) expr;
    Expr result = null;
    if (bp.isNotBetween()) {
      // Rewrite into disjunction.
      Predicate lower = new BinaryPredicate(BinaryPredicate.Operator.LT,
          bp.getChild(0), bp.getChild(1));
      Predicate upper = new BinaryPredicate(BinaryPredicate.Operator.GT,
          bp.getChild(0), bp.getChild(2));
      result = new CompoundPredicate(CompoundPredicate.Operator.OR, lower, upper);
    } else {
      // Rewrite into conjunction.
      Predicate lower = new BinaryPredicate(BinaryPredicate.Operator.GE,
          bp.getChild(0), bp.getChild(1));
      Predicate upper = new BinaryPredicate(BinaryPredicate.Operator.LE,
          bp.getChild(0), bp.getChild(2));
      result = new CompoundPredicate(CompoundPredicate.Operator.AND, lower, upper);
    }
    return result;
  }

  private BetweenToCompoundRule() {}
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var passport = require('passport'),
	User = require('mongoose').model('User'),
	path = require('path'),
	utilities = require('./utilities');

module.exports = function() {
	// Serialize sessions
	passport.serializeUser(function(user, done) {
		done(null, user.id);
	});

	// Deserialize sessions
	passport.deserializeUser(function(id, done) {
		User.findOne({
			_id: id
		}, '-salt -hashed_password', function(err, user) {
			done(err, user);
		});
	});

	// Initialize strategies
	utilities.walk('./config/strategies', /(.*)\.(js$|coffee$)/).forEach(function(strategyPath) {
		require(path.resolve(strategyPath))();
	});
};


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W29700_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans15.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">EMERALD
OIL lNC. 10.08.2014

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Attachment to NDIC Form 1H Emerald Oil. Inc,

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">.v. -.., ".—
SWSE Section 9 —T148N-R102W, McKenzie County

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">To: NDIC

    <p class="styleSans13.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Emerald Oil, Inc. is planning to drill the Mortimer Duke 1-9-4H, Coleman 3-16-21H and Coleman 4-1621H (all on the same multi - well pad) upon APD approval (Pending).
There will be "No Pit" on site and the drill cuttings will be hauled off to one of the following "approved" disposal sites:
Primary:
Indian Hills Disposal 14070 43rd Street NW Williston, ND 58801 701.774.8514
Secondary:
Dishon Disposal, Inc. 15242 39th Lane NW Williston, ND 58801 701.572.9079

    <p class="styleSans59.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Thank you,
Erin kblad Regulatory Specialist
Emerald Oil, Inc. 1600 Broadway, Suite 1360 Denver, CO 80202
Main: 303.595.5600 Direct: 303.595.5690 Mobile: 303.550.2375
erine@emeraldoil.com
EMERALD OIL


text:
package com.meelock.theTimeParadoxMod.items;

import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;

public class Paradoxchip extends Item{
	public Paradoxchip() {
		super();
		this.setCreativeTab(CreativeTabs.tabMaterials);
	}
}


text:
/* global define */
define("{{DEST}}", ["{{SRC}}", "ember", "exports"], function(__index__, __Ember__, __exports__) {
  "use strict";
  __Ember__["default"].keys(__index__).forEach(function(key){
    __exports__[key] = __index__[key];
  });
});


text:
package com.opengamma.analytics.financial.interestrate.future.provider;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

import org.testng.annotations.Test;
import org.threeten.bp.ZonedDateTime;

import com.mcleodmoores.date.CalendarAdapter;
import com.mcleodmoores.date.WorkingDayCalendar;
import com.opengamma.analytics.financial.instrument.future.InterestRateFutureSecurityDefinition;
import com.opengamma.analytics.financial.instrument.future.InterestRateFutureTransactionDefinition;
import com.opengamma.analytics.financial.instrument.index.IborIndex;
import com.opengamma.analytics.financial.interestrate.future.derivative.InterestRateFutureSecurity;
import com.opengamma.analytics.financial.interestrate.future.derivative.InterestRateFutureTransaction;
import com.opengamma.analytics.financial.model.interestrate.definition.HullWhiteOneFactorPiecewiseConstantParameters;
import com.opengamma.analytics.financial.provider.calculator.hullwhite.MarketQuoteHullWhiteCalculator;
import com.opengamma.analytics.financial.provider.calculator.hullwhite.PresentValueCurveSensitivityHullWhiteCalculator;
import com.opengamma.analytics.financial.provider.calculator.hullwhite.PresentValueHullWhiteCalculator;
import com.opengamma.analytics.financial.provider.description.MulticurveProviderDiscountDataSets;
import com.opengamma.analytics.financial.provider.description.interestrate.HullWhiteOneFactorProviderDiscount;
import com.opengamma.analytics.financial.provider.description.interestrate.HullWhiteOneFactorProviderInterface;
import com.opengamma.analytics.financial.provider.description.interestrate.MulticurveProviderDiscount;
import com.opengamma.analytics.financial.provider.sensitivity.hullwhite.ParameterSensitivityHullWhiteDiscountInterpolatedFDCalculator;
import com.opengamma.analytics.financial.provider.sensitivity.multicurve.MultipleCurrencyParameterSensitivity;
import com.opengamma.analytics.financial.provider.sensitivity.parameter.ParameterSensitivityParameterCalculator;
import com.opengamma.analytics.financial.schedule.ScheduleCalculator;
import com.opengamma.analytics.financial.util.AssertSensitivityObjects;
import com.opengamma.util.money.Currency;
import com.opengamma.util.money.MultipleCurrencyAmount;
import com.opengamma.util.test.TestGroup;
import com.opengamma.util.time.DateUtils;

/**
 * Tests for the methods related to interest rate securities pricing with Hull-White model convexity adjustment.
 */
@Test(groups = TestGroup.UNIT)
public class InterestRateFutureTransactionHullWhiteMethodTest {

  private static final MulticurveProviderDiscount MULTICURVES = MulticurveProviderDiscountDataSets.createMulticurveEurUsd();
  private static final IborIndex[] INDEX_LIST = MulticurveProviderDiscountDataSets.getIndexesIborMulticurveEurUsd();
  private static final IborIndex EURIBOR3M = INDEX_LIST[0];
  private static final Currency EUR = EURIBOR3M.getCurrency();
  private static final WorkingDayCalendar CALENDAR = MulticurveProviderDiscountDataSets.getEURCalendar();
  // Future
  private static final ZonedDateTime SPOT_LAST_TRADING_DATE = DateUtils.getUTCDate(2012, 9, 19);
  private static final ZonedDateTime LAST_TRADING_DATE = ScheduleCalculator.getAdjustedDate(SPOT_LAST_TRADING_DATE, -EURIBOR3M.getSpotLag(),
      CALENDAR);
  private static final double NOTIONAL = 1000000.0; // 1m
  private static final double FUTURE_FACTOR = 0.25;
  private static final String NAME = "ERU2";
  private static final int QUANTITY = 400;

  private static final ZonedDateTime REFERENCE_DATE = DateUtils.getUTCDate(2011, 5, 12);
  private static final ZonedDateTime TRADE_DATE = ScheduleCalculator.getAdjustedDate(REFERENCE_DATE, -1, CALENDAR);
  private static final double TRADE_PRICE = 0.99;
  private static final InterestRateFutureSecurityDefinition ERU2_SEC_DEFINITION = new InterestRateFutureSecurityDefinition(
      LAST_TRADING_DATE, EURIBOR3M, NOTIONAL, FUTURE_FACTOR, NAME, CalendarAdapter.of(CALENDAR));
  private static final InterestRateFutureTransactionDefinition ERU2_TRA_DEFINITION = new InterestRateFutureTransactionDefinition(
      ERU2_SEC_DEFINITION, QUANTITY, TRADE_DATE, TRADE_PRICE);

  private static final double REFERENCE_PRICE = 0.98;
  private static final InterestRateFutureSecurity ERU2_SEC = ERU2_SEC_DEFINITION.toDerivative(REFERENCE_DATE);
  private static final InterestRateFutureTransaction ERU2_TRA = ERU2_TRA_DEFINITION.toDerivative(REFERENCE_DATE, REFERENCE_PRICE);

  private static final double MEAN_REVERSION = 0.01;
  private static final double[] VOLATILITY = new double[] { 0.01, 0.011, 0.012, 0.013, 0.014 };
  private static final double[] VOLATILITY_TIME = new double[] { 0.5, 1.0, 2.0, 5.0 };
  private static final HullWhiteOneFactorPiecewiseConstantParameters MODEL_PARAMETERS = new HullWhiteOneFactorPiecewiseConstantParameters(
      MEAN_REVERSION, VOLATILITY, VOLATILITY_TIME);

  private static final HullWhiteOneFactorProviderDiscount HW_MULTICURVES = new HullWhiteOneFactorProviderDiscount(MULTICURVES,
      MODEL_PARAMETERS, EUR);

  private static final InterestRateFutureTransactionHullWhiteMethod METHOD_IRFUT_TRA_HW = InterestRateFutureTransactionHullWhiteMethod
      .getInstance();
  private static final InterestRateFutureSecurityHullWhiteMethod METHOD_IRFUT_SEC_HW = InterestRateFutureSecurityHullWhiteMethod
      .getInstance();

  private static final MarketQuoteHullWhiteCalculator MQHWC = MarketQuoteHullWhiteCalculator.getInstance();
  private static final PresentValueHullWhiteCalculator PVHWC = PresentValueHullWhiteCalculator.getInstance();
  private static final PresentValueCurveSensitivityHullWhiteCalculator PVCSHWC = PresentValueCurveSensitivityHullWhiteCalculator
      .getInstance();

  private static final double SHIFT_FD = 1.0E-6;
  private static final ParameterSensitivityParameterCalculator<HullWhiteOneFactorProviderInterface> PSHWC = new ParameterSensitivityParameterCalculator<>(
      PVCSHWC);
  private static final ParameterSensitivityHullWhiteDiscountInterpolatedFDCalculator PSHWC_FD = new ParameterSensitivityHullWhiteDiscountInterpolatedFDCalculator(
      PVHWC, SHIFT_FD);

  private static final double TOLERANCE_PV = 1.0E-2;
  private static final double TOLERANCE_PV_DELTA = 1.0E+2;
  private static final double TOLERANCE_PRICE = 1.0E-10;

  /**
   * Test the present value computed from the curves and HW parameters.
   */
  @Test
  public void presentValue() {
    final MultipleCurrencyAmount pvComputed = METHOD_IRFUT_TRA_HW.presentValue(ERU2_TRA, HW_MULTICURVES);
    final double price = METHOD_IRFUT_SEC_HW.price(ERU2_SEC, HW_MULTICURVES);
    final double pvExpected = (price - REFERENCE_PRICE) * ERU2_SEC.getNotional() * ERU2_SEC.getPaymentAccrualFactor() * QUANTITY;
    assertEquals(pvExpected, pvComputed.getAmount(EUR), TOLERANCE_PV);
  }

  /**
   *
   */
  @Test
  public void presentValueMethodVsCalculator() {
    final MultipleCurrencyAmount pvMethod = METHOD_IRFUT_TRA_HW.presentValue(ERU2_TRA, HW_MULTICURVES);
    final MultipleCurrencyAmount pvCalculator = ERU2_TRA.accept(PVHWC, HW_MULTICURVES);
    assertEquals(pvCalculator.getAmount(EUR), pvMethod.getAmount(EUR), TOLERANCE_PV);
  }

  /**
   * Test the price as "MarketQuote"
   */
  @Test
  public void marketQuote() {
    final double priceMethod = METHOD_IRFUT_SEC_HW.price(ERU2_SEC, HW_MULTICURVES);
    final double marketQuote = ERU2_TRA.accept(MQHWC, HW_MULTICURVES);
    assertEquals(priceMethod, marketQuote, TOLERANCE_PRICE);
  }

  /**
   * Tests present value curve sensitivity.
   */
  @Test
  public void presentValueCurveSensitivity() {
    final MultipleCurrencyParameterSensitivity pvpsDepositExact = PSHWC.calculateSensitivity(ERU2_TRA, HW_MULTICURVES,
        HW_MULTICURVES.getMulticurveProvider().getAllNames());
    final MultipleCurrencyParameterSensitivity pvpsDepositFD = PSHWC_FD.calculateSensitivity(ERU2_TRA, HW_MULTICURVES);
    AssertSensitivityObjects.assertEquals(pvpsDepositExact, pvpsDepositFD, TOLERANCE_PV_DELTA);
  }

  /**
   * Compare the price with a price without convexity adjustment.
   */
  @Test
  public void comparisonDiscounting() {
    final InterestRateFutureSecurityDiscountingMethod methodDiscounting = InterestRateFutureSecurityDiscountingMethod.getInstance();
    final double priceDiscounting = methodDiscounting.price(ERU2_SEC, HW_MULTICURVES);
    final double priceHullWhite = METHOD_IRFUT_SEC_HW.price(ERU2_SEC, HW_MULTICURVES);
    assertTrue(priceDiscounting > priceHullWhite);
  }

}


text:
<?php

namespace Application\Controller;
use \Application\Controller\CommonController;

class AboutController extends CommonController
{
    /**
     * The index action
     * @return \Zend\View\Model\JsonModel | \Zend\View\Model\ViewModel
     */
    public function indexAction()
    {
        return $this->acceptableViewModelSelector($this->acceptCriteria);
    }
}


text:
from mayavi import mlab
from traitsui.api import View, VGroup, Group, Item
from traits.api import HasTraits, Instance

from simphony_mayavi.plugins.engine_manager import EngineManager
from simphony_mayavi.plugins.add_engine_panel import AddEnginePanel
from simphony_mayavi.plugins.add_source_panel import AddSourcePanel
from simphony_mayavi.plugins.run_and_animate_panel import RunAndAnimatePanel
from simphony_mayavi.plugins.tabbed_panel_collection import (
    TabbedPanelCollection)

class EngineManagerStandaloneUI(EngineManager):
    """Standalone GUI for visualising datasets from a modeling engine,
    running the engine and animating the results
    """

    #: The collection of panels
    panels = Instance(TabbedPanelCollection)

    traits_view = View(
        VGroup(
            Group(Item("engine_name", label="Engine Wrapper")),
            Group(Item("panels", style="custom", show_label=False))),
        title="Engine Manager",
        resizable=True)

    def __init__(self, engine_name="", engine=None, mayavi_engine=None):
        '''
        Parameters
        ----------
        engine_name : str
            Name of the Simphony Modeling Engine wrapper

        engine : ABCModelingEngine
            Simphony Modeling Engine wrapper

        mayavi_engine : mayavi.api.engine
            Default to be mayavi.mlab.get_engine()

        '''
        # Traits initialisation
        HasTraits.__init__(self)

        if mayavi_engine is None:
            # Standalone Mayavi Engine
            mayavi_engine = mlab.get_engine()
        else:
            mayavi_engine = mayavi_engine

        # Add panels
        self.panels = TabbedPanelCollection.create(
            add_engine=AddEnginePanel(engine_manager=self),
            add_source=AddSourcePanel(engine_name=self.engine_name,
                                      engine=self.engine,
                                      mayavi_engine=mayavi_engine),
            run_and_animate=RunAndAnimatePanel(engine=self.engine,
                                               mayavi_engine=mayavi_engine))

        if engine and engine_name:
            self.add_engine(engine_name, engine)

    def _engine_name_changed(self):
        # Sync panels when engine_name (i.e. engine) changes
        for panel in self.panels:
            if hasattr(panel, "engine"):
                panel.engine = self.engine
        self.panels.add_source.engine_name = self.engine_name

    # --------------------------------------------------------------
    # Public methods
    # --------------------------------------------------------------

    def show_config(self):
        ''' Show the GUI with all the panels '''
        return self.edit_traits()


text:
package org.apache.sling.models.testmodels.classes;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.models.annotations.Model;

import javax.inject.Inject;

@Model(adaptables = SlingHttpServletRequest.class)
public class UncachedModel {

    @Inject
    private String testValue;

    public String getTestValue() {
        return testValue;
    }
}


text:
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>Module V1</title>
	</head>
	<body>
		@yield('content')
	</body>
</html>


text:
module WOW::Capture::WOWObject::Utility::LogItems
  class Chat < Base
    attr_reader :text, :sender_name, :channel_name

    def type
      :chat
    end

    def parse!
      @sender_name = packet.record.sender_name
      @channel_name = packet.record.channel_name
      @text = packet.record.text
    end

    def pretty_print
      output = ''

      output << pretty_prefix

      lines = []

      lines << " Channel: [#{@channel_name}]" if !@channel_name.to_s.empty?
      lines << " Sender:  [#{@sender_name}]" if !@sender_name.to_s.empty?
      lines << " Text:    #{@text}"

      output << lines.join(pretty_line)
    end
  end
end


text:
import {Block} from './block';

export class Snake {
  constructor(startX=0, startY=0) {
    this.body = [new Block(startX, startY)]
    let [last] = this.body
    this.last = last
    let [head] = this.body
    this.head = head
    this.moveUp = this.verticalMoveBody.bind(this,-1, 10)
    this.moveDown = this.verticalMoveBody.bind(this, 1, 10)
    this.moveLeft = this.horizontalMoveBody.bind(this, -1)
    this.moveRight = this.horizontalMoveBody.bind(this, 1)
  }

  set isEating(value) {
    if (value === true) {
      this.grow()
    }
  }

  grow() {
    let block = new Block(this.last.x - 10, this.last.y);
    this.body.push(block)
    this.last = block
    return this;
  }

  horizontalMoveBody(xOffset) {
    this.body.forEach((block) => {
      block.x += xOffset;
    })
    return this;
  }

  verticalMoveBody(yOffset, tailOffset) {
    let [head, ...tail] = this.body
    head.y += yOffset
    tail.forEach((block) => {
      if (head.x > block.x) {
        block.x += tailOffset;
      } else {
        block.x -= tailOffset;
      }
    })
    return this;
  }

  move(userInput) {
    if (userInput.isDown(userInput.UP)) this.moveUp();
    if (userInput.isDown(userInput.LEFT)) this.moveLeft();
    if (userInput.isDown(userInput.DOWN)) this.moveDown();
    if (userInput.isDown(userInput.RIGHT)) this.moveRight();
  }

  draw(context) {
    this.body.forEach((block) => {
      block.draw(context)
    });
    return this;
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="app_name" msgid="559800164925277094">"PhotoViewerSample"</string>
    <string name="menu_settings" msgid="1259682084875185697">"Cài đặt"</string>
    <string name="title_activity_main" msgid="7695239211427024237">"MainActivity"</string>
    <string name="launch" msgid="2345080120370773520">"Khởi chạy trình xem ảnh"</string>
</resources>


text:
/// <reference path='fourslash.ts'/>

// Should go to object literals within cast expressions when invoked on interface

//// interface Fo/*interface_definition*/o { hello: () => void }
////
//// var x = <Foo> [|{ hello: () => {} }|];

verify.allRangesAppearInImplementationList("interface_definition");


text:
#include "../Shape/TriangleMesh.h"

#include <fstream>

#include <vector>

namespace Crystal {
	namespace Shape {
		class PolygonMesh;
	}
	namespace IO {

class STLAsciiFileReader
{
public:
	STLAsciiFileReader()
	{}

	bool read(const std::string& filename);

	bool read(std::istream& stream);

	std::vector<Shape::TriangleFace> getFaces() const { return faces; }

private:
	std::vector<Shape::TriangleFace> faces;
	std::string title;
};

	}
}

#endif


text:
{% load staticfiles %}
<!DOCTYPE html>

  <title>Swagger UI</title>
  <link href='//fonts.googleapis.com/css?family=Droid+Sans:400,700' rel='stylesheet' type='text/css'/>
  <link href='{% static "rest_framework_swagger/css/highlight.default.css" %}' media='screen' rel='stylesheet' type='text/css'/>
  <link href='{% static "rest_framework_swagger/css/rest_framework_swagger.css" %}' media='screen' rel='stylesheet' type='text/css'/>
  <link href='{% static "rest_framework_swagger/css/screen.css" %}' media='screen' rel='stylesheet' type='text/css'/>

    swagger

    <form id='api_selector'>

<input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/>

<input placeholder="api_key" id="input_apiKey" name="apiKey" type="text"/>

Explore

    </form>

    Django REST Swagger


text:
package br.com.caelum.fj91.classloader.teste;

import java.net.URL;
import java.net.URLClassLoader;

public class TesteComparaClasses {

	public static void main(String[] args) throws Exception {

		// cria um novo classloader a partir da pasta bin
		ClassLoader loader = new URLClassLoader(new URL[] { new URL("file:bin/") }, null);

		// carrega a classe pelo novo classloader
		Class<?> classe = loader.loadClass("br.com.caelum.fj91.classloader.teste.ObjetoTeste");

		// carrega a mesma classe pelo classloader atual, do main, o application classloader
		Class<?> outraClasse = Class.forName("br.com.caelum.fj91.classloader.teste.ObjetoTeste");

		// executa alguns testes
		System.out.println("ClassLoader da 1a classe: " + classe.getClassLoader());
		System.out.println("ClassLoader da 2a classe: " + outraClasse.getClassLoader());
		System.out.println("Classes são iguais? " + (classe == outraClasse));

		Object o = classe.newInstance();

	}
}


text:
@implementation BoundaryStorageSet

- (NSArray *)descriptionInArray {

    NSArray *tAarray = [setOfObjects allObjects];

    return tAarray;
}

- (void)addRecord:(BoundaryStorageItem *)record {

    [setOfObjects addObject: record];

};

- (void)deleteRecord:(BoundaryStorageItem *)record {

    [setOfObjects removeObject: record];

}

- (int)count {

    return (int)[setOfObjects count];
}

- (instancetype)init {
    self = [super init];

    if (self) {
        setOfObjects = [NSMutableSet set];
    }

    return self;
}

@end


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

SILTUSSIN SA - guaifenesin liquid
Preferred  Pharmaceuticals, Inc

Disclaimer: Most OTC drugs are not reviewed and approved by FDA, however they may be marketed if they comply with applicable regulations and policies. FDA has not evaluated whether this product complies.

Siltussin SA (Guaifenesin Liquid)

Active Ingredient: Guaifenesin 100 mg (in each 5 mL)

Purpose: Expectorant

Uses Helps loosen phlegm (mucus) and thin bronchial secretions to make coughs more productive

Warnings

Ask a doctor before use if you have

cough that occurs with too much phlegm (mucus)

cough that lasts or is chronic such as occurs with smoking, asthma, chronic bronchitis, or emphysema

Stop use and ask a doctor if cough lasts more than 7 days, comes back, or is accompanied by fever, rash, or persistent headache. These could be signs of a serious condition.

If pregnant or breast-feeding, ask a health professional before use.

Keep out of reach of children. In case of overdose, get medical help or contact a Poison Control Center right away.

Directions

do not take more than 6 doses in any 24-hour period

repeat dose every 4 hours

adults and children 12 years and over

2-4 teaspoonfuls

children under 12 years
DO NOT USE

Other information

Store at room temperature 20°-25°C (68°-77°F). Do not accept if imprinted tamperevident safety seal around cap is broken or missing.

Inactive ingredients

citric acid, D&C yellow no. 10, FD&C blue no. 1, FD&C red no. 40, strawberry flavor, glycerin, propylene glycol, saccharin sodium, sodium benzoate, sodium citrate, sorbitol, purified water.

Questions

888-974-5279

† This product is not manufactured or distributed by Wyeth Consumer Healthcare, owner of the registered trademark Robitussin®.

Manufactured by:

Silarx Pharmaceuticals, Inc.
19 West Street
Spring Valley, NY 10977
USA

Relabeled by:

Preferred Pharmaceuticals, Inc.
1Anaheim, CA 92807

SILTUSSIN SA

guaifenesin liquid

Product Information

Product Type
HUMAN OTC DRUG LABEL
Item Code (Source)
NDC:68788-9098(NDC:54838-117)

Route of Administration
ORAL
DEA Schedule

Active Ingredient/Active Moiety

Ingredient Name
Basis of Strength
Strength

Guaifenesin (Guaifenesin)
Guaifenesin
100 mg  in 5 mL

Inactive Ingredients

Ingredient Name
Strength

anhydrous citric acid

D&C yellow no. 10

FD&C blue no. 1

FD&C red no. 40

glycerin

propylene glycol

saccharin sodium

sodium benzoate

sodium citrate

sorbitol

water

Product Characteristics

Color

Score

Shape

Size

Flavor
STRAWBERRY (strawberry flavor)
Imprint Code

Contains

Packaging

#
Item Code
Package Description
Marketing Start Date
Marketing End Date

1
NDC:68788-9098-1
118 mL in 1 BOTTLE, PLASTIC

Marketing Information

Marketing Category
Application Number or Monograph Citation
Marketing Start Date
Marketing End Date

OTC monograph final
part341
10/05/1998

Labeler - Preferred  Pharmaceuticals, Inc
							(791119022)

Establishment

Name
Address
ID/FEI
Business Operations

Preferred Pharmaceuticals, Inc

791119022
relabel

Revised: 6/2011

Document Id: 264abf3d-c466-4209-b911-29ce18b0b816

Set id: 264abf3d-c466-4209-b911-29ce18b0b816

Version: 1

Effective Time: 20110617

Preferred  Pharmaceuticals, Inc


text:
package coyote.i13n;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URI;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import coyote.commons.DateUtil;
import coyote.commons.ExceptionUtil;
import coyote.commons.FileUtil;
import coyote.commons.GUID;
import coyote.commons.UriUtil;
import coyote.commons.Version;
import coyote.commons.network.IpInterface;
import coyote.dataframe.DataFrame;
import coyote.loader.component.Component;
import coyote.loader.log.Log;

/**
 * The Tabs class defines static resources for tracking the state and operation
 * of business logic running in the VM and making those measurements available
 * to the external entities.
 *
 *
This class runs a single thread that communicates to the outside world by
 * establishing a UDP socket on the default network interface and communicating
 * with other Tabs facilities.

 *
 * @author Stephan D. Cote' - Enterprise Architecture
 */
public class Tabs {
  /** Tag used in various class identifying locations */
  public static final String CLASS_TAG = "Tabs";

  /** Current version of the instrumentation package */
  public static final Version VERSION = new Version(3, 0, 0, Version.EXPERIMENTAL);

  private static String FIXTUREID = new GUID().toString().toLowerCase();
  private static String FIXTUREGRP = null;
  private static Tabs fixture;
  private static File workDirectory;
  private static File logDirectory;
  static boolean useudp = true;
  private static volatile boolean checkedClasspathAlready = false;
  private static final String LF = System.getProperty("line.separator");

  /**
   * The name of the system property that contains the path to the home
   * directory.
   */
  public static final String HOMEDIR_TAG = "tabs.home";

  public static final String DEFAULT_HOME = System.getProperty("user.home") + System.getProperty("file.separator") + Tabs.CLASS_TAG.toLowerCase();

  /**
   * A map that holds component identifiers for components that desire their
   * presence be made known to others.
   */
  private static final HashMap componentMap = new HashMap();

  private final EventList eventList = new EventList();
  private static final HashMap masterTimers = new HashMap();
  private static final HashMap armMasters = new HashMap();
  private static final HashMap counters = new HashMap();
  private static final HashMap states = new HashMap();
  private static final HashMap gauges = new HashMap();

  /** For the zipFile method */
  private static final int STREAM_BUFFER_SIZE = 8 * 1024;

  public static final String ID_TAG = "tabs.id";
  public static final String GROUP_TAG = "tabs.group";
  public static final String NOUDP_TAG = "tabs.noudp";

  /** Timing is disabled by default */
  private static boolean timingEnabled = false;

  /** Application Response Measurement is disabled by default */
  private static boolean armEnabled = false;

  /** Gauges are disabled by default */
  private static boolean gaugesEnabled = false;

  /** Re-usable null gauge to save object creation and GC'n */
  private static final Gauge NULL_GAUGE = new NullGauge(null);

  /** Re-usable null ARM transaction to save object creation and GC'n */
  private static final ArmTransaction NULL_ARM = new NullArm(null, null, null);

  /** Re-usable null timer to save object creation and GC'n */
  private static final Timer NULL_TIMER = new NullTimer(null);

  /** The time this fixture started. */
  private static long startedTimestamp = 0;

  private static IpInterface primaryInterface = null;

  private static HashMap shadowClasses = new HashMap();
  private static ArrayList missingLibraries = new ArrayList();

  /**
   * Private constructor to eliminate the creation of instances of this class.
   */
  private Tabs() {
    Tabs.fixture = this;

    Tabs.startedTimestamp = System.currentTimeMillis();

    // Add a shutdown hook into the JVM to help us shut everything down nicely
    try {
      Runtime.getRuntime().addShutdownHook(new Thread("TabsHook") {
        public void run() {
          shutdown("Runtime termination");
        }
      });
    } catch (final java.lang.NoSuchMethodError nsme) {
      // Ignore
    } catch (final Throwable e) {
      // Ignore
    }

  }

  public static synchronized Tabs getInstance() {
    if (Tabs.fixture == null) {
      // create the true singleton
      Tabs.fixture = new Tabs();
    }
    return Tabs.fixture;
  }

  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

  /**
   * Compress log files older than 7 days and delete archives older than 30
   * days.
   *
   *
This can be called any time and will archive and delete files as
   * appropriate for ALL files in the log directory of the Tabs home directory
   * for ALL instances of Tabs running on this platform.

   *
   *
A separate thread is created to run this logic so the processing does
   * not take too long in the callers thread of execution.

   */
  public void archiveLogs() {
    final Thread archiver = new Thread("TabsLogArchiver") {
      public void run() {
        Calendar cal = GregorianCalendar.getInstance();

        // / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
        // Archive files older than 7 days
        cal.add(Calendar.DATE, -7);

        long cutoff = cal.getTimeInMillis();
        long lastAccessed = cutoff;

        String[] children = Tabs.logDirectory.list();

        if (children != null) {
          for (int i = 0; i < children.length; i++) {
            File source = new File(Tabs.logDirectory, children[i]);
            lastAccessed = FileUtil.getFileAge(source);

            if (source.isFile() && (lastAccessed <= cutoff)) {
              if (source.length() == 0) {
                source.delete();
              } else {
                if (!source.getName().toLowerCase().endsWith(".zip")) {
                  try {
                    Tabs.zipFile(source);
                    source.delete();
                  } catch (Exception ex) {
                    Log.debug("Could not archive file: '" + source.getAbsolutePath() + "' reason:" + ex.getMessage() + " - (This file will be archived later)");
                  }
                } // not a zip file
              } // file has any data
            } // file is old
          } // for each path in log directory
        } // there are children in log directory

        // / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
        // Now go back 23 more days (30 total) and delete all old files and
        // directories based upon when they or their children were last modified.
        cal.add(Calendar.DATE, -23);

        cutoff = cal.getTimeInMillis();

        if (children != null) {
          for (int i = 0; i < children.length; i++) {
            File source = new File(Tabs.logDirectory, children[i]);

            if (source.exists()) {
              lastAccessed = FileUtil.getFileAge(source);

              if ((lastAccessed <= cutoff) && source.canWrite()) {
                source.delete();
              }
            } // file exists
          } // for each child in the metric dir list
        } // if metric dir has children
        createEvent(null, null, "Tabs", "Log archiving completed", 0, 0, 0, "INFO");
      }
    };
    archiver.setDaemon(false);
    archiver.start();
  }

  /**
   * Create and send an event to any listening agents.
   *
   * @param appid The identifier of the application sending the event.
   * @param sysid The identifier of the system sending the event.
   * @param cmpid The component identifier sending the event.
   * @param msg The descriptive message of the event.
   * @param sv The severity of the event.
   * @param maj Major code to classify the event.
   * @param min Minor code to sub-clasify the event.
   * @param cat The category of the event.
   *
   * @return The sequence number of the event created.
   */
  public long createEvent(final String appid, final String sysid, final String cmpid, final String msg, final int sv, final int maj, final int min, final String cat) {
    final AppEvent event = eventList.createEvent(appid, sysid, cmpid, msg, sv, maj, min, cat);
    // return Tabs.oamManager.sendEvent( event );
    return event.getSequence();
  }

  /**
   * Decrease the value with the given name by the given amount.
   *
   *
This method retrieves the counter with the given name or creates one by
   * that name if it does not yet exist. The retrieved counter is then
   * decreased by the given amount.

   *
   * @param tag The name of the counter to decrease.
   * @param value the amount to decrease
   *
   * @return The final value of the counter after the operation.
   */
  public static long decrease(final String tag, final long value) {
    return Tabs.getCounter(tag).decrease(value);
  }

  /**
   * Decrement the value with the given name.
   *
   *
This method retrieves the counter with the given name or creates one by
   * that name if it does not yet exist. The retrieved counter is then
   * decreased by one (1).

   *
   * @param tag The name of the counter to decrement.
   *
   * @return The final value of the counter after the operation.
   */
  public static long decrement(final String tag) {
    return Tabs.getCounter(tag).decrement();
  }

  /**
   * Deactivate a particular class of Application Response Measurement calls
   * from this point on.
   *
   * @param name the name of the ARM to disable
   */
  public static void disableArmClass(final String name) {
    synchronized (Tabs.armMasters) {
      // get an existing master ARM or create a new one
      ArmMaster master = (ArmMaster)Tabs.armMasters.get(name);
      if (master == null) {
        master = new ArmMaster(name);
        Tabs.armMasters.put(name, master);
      }
      master.setEnabled(false);
    }
  }

  /**
   * Disable the timer with the given name.
   *
   *
Disabling a timer will cause all new timers with the given name to
   * skip processing reducing the amount of processing performed by the
   * timers without losing the existing data in the timer. Any existing
   * timers will continue to accumulate data.

   *
   *
If a timer is disabled that has not already been created, a disabled
   * timer will be created in memory that can be enabled at a later time.

   *
   * @param tag The name of the timer to disable.
   */
  public static void disableTimer(final String tag) {
    synchronized (Tabs.masterTimers) {
      // get an existing master timer or create a new one
      TimingMaster master = (TimingMaster)Tabs.masterTimers.get(tag);
      if (master == null) {
        master = new TimingMaster(tag);
        Tabs.masterTimers.put(tag, master);
      }
      master.setEnabled(false);
    }
  }

  /**
   * Activate all Application Response Measurement calls from this point on.
   *
   * @param flag true to enable, false to disable
   */
  public static void enableArm(final boolean flag) {
    synchronized (Tabs.armMasters) {
      Tabs.armEnabled = flag;
    }
  }

  /**
   * Activate a particular class of Application Response Measurement calls from
   * this point on.
   *
   * @param name the name of the ARM to enable
   */
  public static void enableArmClass(final String name) {
    synchronized (Tabs.armMasters) {
      // get an existing master ARM or create a new one
      ArmMaster master = (ArmMaster)Tabs.armMasters.get(name);
      if (master == null) {
        master = new ArmMaster(name);
        Tabs.armMasters.put(name, master);
      }
      master.setEnabled(true);
    }
  }

  /**
   * Activate all gauges calls from this point on.
   *
   * @param flag true to activate all gauges, false disables all gauges
   */
  public static void enableGauges(final boolean flag) {
    synchronized (Tabs.gauges) {
      Tabs.gaugesEnabled = flag;
    }
  }

  /**
   * Enable the timer with the given name.
   *
   *
If a timer is enabled that has not already been created, a new
   * timer will be created in memory.

   *
   * @param tag The name of the timer to enable.
   */
  public static void enableTimer(final String tag) {
    synchronized (Tabs.masterTimers) {
      // get an existing master timer or create a new one
      TimingMaster master = (TimingMaster)Tabs.masterTimers.get(tag);
      if (master == null) {
        master = new TimingMaster(tag);
        Tabs.masterTimers.put(tag, master);
      }
      master.setEnabled(true);
    }
  }

  /**
   * Enable fully-functional timers from this point forward.
   *
   *
When timing is enabled, functional timers are returned and their
   * metrics are collected for later reporting. when timing is disabled, null
   * timers are be returned each time a timer is requested. This keeps all code
   * operational regardless of the runtime status of timing.

   *
   * @param flag true to enable timing, false to disable timing
   */
  public static void enableTiming(final boolean flag) {
    synchronized (Tabs.masterTimers) {
      Tabs.timingEnabled = flag;
    }
  }

  /**
   * Get an iterator over all the ARM Masters in the fixture.
   *
   * @return an iterator over all the ARMs
   */
  public static Iterator getArmIterator() {
    final ArrayList list = new ArrayList();
    synchronized (Tabs.armMasters) {
      for (final Iterator it = Tabs.armMasters.values().iterator(); it.hasNext(); list.add((ArmMaster)it.next())) {
        ;
      }
    }
    return list.iterator();
  }

  /**
   * Available memory is the maximum memory available to the VM less the total
   * memory currently allocated for the heap.
   *
   *
This is different from free memory in that this returns the difference
   * between the allocated heap and the maximum Heap size. It does not include
   * the amount of memory available on the current heap allocation.

   *
   *
Keep in mind this and all memory values are approximate as the garbage
   * collector can be running at the same time. Also, other threads may be
   * allocating object on the heap, changing the values between calls.

   *
   * @return The number of bytes the heap can grow before MaxMemory is reached.
   */
  public static long getAvailableMemory() {
    return Runtime.getRuntime().maxMemory() - Runtime.getRuntime().totalMemory();
  }

  /**
   * @return An array of component identifiers that are currently registered
   *         with this fixture.
   */
  public static String[] getComponentIds() {
    synchronized (Tabs.componentMap) {
      // get the size of the map
      int x = Tabs.componentMap.size();

      // create a return value the size of the map then decrement the size so
      // we can start populating the return value starting from the last
      // position in the return value array
      final String[] retval = new String[x--];

      // enumerate through the keys, placing them in the return value starting
      // from the end of the array and working to the front
      for (final Iterator it = Tabs.componentMap.keySet().iterator(); it.hasNext(); retval[x--] = (String)it.next()) {
        ;
      }

      // Return the populated array of component identifiers registered with us.
      return retval;
    }
  }

  public static Iterator getComponentIterator() {
    final ArrayList cmpnts = new ArrayList();
    synchronized (Tabs.componentMap) {
      for (final Iterator it = Tabs.componentMap.values().iterator(); it.hasNext();) {
        final Component cmpnt = (Component)it.next();
        if (cmpnt != null) {
          cmpnts.add(cmpnt);
        } // if
      } // for
    } // sync
    return cmpnts.iterator();
  }

  /**
   * Return the counter with the given name.
   *
   *
If the counter does not exist, one will be created and added to the
   * static list of counters for later retrieval.

   *
   * @param name The name of the counter to return.
   *
   * @return The counter with the given name.
   */
  public static Counter getCounter(final String name) {
    Counter counter = null;
    synchronized (Tabs.counters) {
      counter = (Counter)Tabs.counters.get(name);
      if (counter == null) {
        counter = new Counter(name);
        Tabs.counters.put(name, counter);
      }
    }
    return counter;
  }

  /**
   * @return The number of counters in the fixture at the present time.
   */
  public static int getCounterCount() {
    return Tabs.counters.size();
  }

  /**
   * Access an interator over the counters.
   *
   *
NOTE: this iterator is detached from the counters in that the remove()
   * call on the iterator will only affect the returned iterator and not the
   * counter collection in the fixture. If you wish to remove a counter, you
   * MUST call removeCounter(Counter) with the reference returned from this
   * iterator as well.

   *
   * @return a detached iterator over the counters.
   */
  public static Iterator getCounterIterator() {
    final ArrayList list = new ArrayList();
    for (final Iterator it = Tabs.counters.values().iterator(); it.hasNext(); list.add((Counter)it.next())) {
      ;
    }
    return list.iterator();
  }

  /**
   * @return All counters as attributes of a packet.
   */
  public static DataFrame getCounterMessage() {
    final DataFrame retval = new DataFrame();
    //retval.setType( "Counters" );

    synchronized (Tabs.counters) {
      for (final Iterator it = Tabs.counters.entrySet().iterator(); it.hasNext();) {
        final Counter cntr = (Counter)((Map.Entry)it.next()).getValue();
        try {
          retval.put(cntr.getName(), new Long(cntr.getValue()));
        } catch (final Exception ignore) {}
      }
    }
    return retval;
  }

  /**
   * Returns the total amount of memory currently in use by the heap.
   *
   *
It is composed of all currently allocated objects and possibly some
   * space that was freed by the garbage collector.

   *
   *
Heap size is allocated and release in blocks. This is the current size
   * of the heap allocation.

   *
   *
Keep in mind this and all memory values are approximate as the garbage
   * collector can be running at the same time. Also, other threads may be
   * allocating object on the heap, changing the values between calls.

   *
   * @return The number of bytes currently allocated by the heap.
   */
  public static long getCurrentHeapSize() {
    return Runtime.getRuntime().totalMemory();
  }

  /**
   * @return Just the domain portion of this hosts name.
   */
  public static String getDomain() {
    return Tabs.primaryInterface.getDomain();
  }

  public int getEventListSize() {
    return eventList.getSize();
  }

  /**
   * Returns an approximation of the total amount of memory currently available
   * on the heap for newly allocated objects.
   *
   *
This is what is available on the current heap allocation before the
   * next block of memory is requested to be added to total heap memory. In
   * other words, this is the number of bytes available before the heap will
   * attempt to grow.

   *
   *
Keep in mind this and all memory values are approximate as the garbage
   * collector can be running at the same time. Also, other threads may be
   * allocating object on the heap, changing the values between calls.

   *
   * @return The number of bytes available on the currently allocated heap.
   */
  public static long getFreeHeapSize() {
    return Runtime.getRuntime().freeMemory();
  }

  /**
   * Free memory is the total amount of memory that can be allocated prior to
   * running out of memory in the VM.
   *
   *
This can be used to approximate the amount of memory available to the
   * application. This will never be totally accurate because the garbage
   * collection process could change things at any time.

   *
   *
Keep in mind this and all memory values are approximate as the garbage
   * collector can be running at the same time. Also, other threads may be
   * allocating object on the heap, changing the values between calls.

   *
   * @return Available Memory and Free Heap size added together.
   */
  public static long getFreeMemory() {
    return Runtime.getRuntime().freeMemory() + (Runtime.getRuntime().maxMemory() - Runtime.getRuntime().totalMemory());
  }

  /**
   *
Keep in mind this and all memory values are approximate as the garbage
   * collector can be running at the same time. Also, other threads may be
   * allocating object on the heap, changing the values between calls.

   *
   * @return The percentage of total free memory available both on the heap and
   *         memory that has not yet been allocated to the heap.
   */
  public static float getFreeMemoryPercentage() {
    return (float)((float)Tabs.getFreeMemory() / (float)Tabs.getMaxHeapSize());
  }

  /**
   * Return the reference to the named gauge.
   *
   *
This will always return an object; it may be a stub, or a working
   * implementation depending upon the state of the fixture at the time. If
   * gauges are enabled, then a working gauge is returned, otherwise a null
   * gauge is returned.

   *
   *
Because the state of gauge operation can change over the operation of
   * the fixture, it is not advisable to hold on to the reference between calls
   * to the gauge. Always get the appropriate reference to the gauge
   *
   * @param name the name of the gauge to return.
   *
   * @return Either the
   *
   * @throws IllegalArgumentException if the name of the gauge is null
   */
  public static Gauge getGauge(final String name) {
    if (name == null) {
      throw new IllegalArgumentException("Gauge name is null");
    }

    Gauge retval = null;
    if (Tabs.gaugesEnabled) {
      synchronized (Tabs.gauges) {
        retval = (Gauge)Tabs.gauges.get(name);
        if (retval == null) {
          retval = new GaugeBase(name);
          Tabs.gauges.put(name, (Gauge)retval);
        }
      }
    } else {
      // just return the do-nothing gauge
      retval = Tabs.NULL_GAUGE;
    }

    return retval;
  }

  /**
   * Get an iterator over all the gauges in the fixture.
   *
   * @return an iterator of all the gauges
   */
  public static Iterator getGaugeIterator() {
    final ArrayList list = new ArrayList();
    synchronized (Tabs.gauges) {
      for (final Iterator it = Tabs.gauges.values().iterator(); it.hasNext(); list.add((Gauge)it.next())) {
        ;
      }
    }
    return list.iterator();
  }

  /**
   * Return the percentage of the Maximum Memory the currently allocated heap
   * occupies.
   *
   *
In some cases this will always return 1.0 indicating that all memory
   * has been allocated to the heap. These cases include runtimes where the Ms
   * and Mx systems properties are set to the same value. This will not mean
   * that the runtime is out of memory, just that the heap has been allocated
   * to fill the entire space. The FreeHeap value will then determine the
   * amount of free memory and should be the same value as FreeMemory.

   *
   *
Keep in mind this and all memory values are approximate as the garbage
   * collector can be running at the same time. Also, other threads may be
   * allocating object on the heap, changing the values between calls.

   *
   * @return The percentage of maximum heap memory currently allocated to the
   *         heap.
   */
  public static float getHeapPercentage() {
    return (float)(1 - ((float)Tabs.getAvailableMemory() / (float)Tabs.getMaxHeapSize())); // percent of max
  }

  /**
   * @return The default IP address of this host.
   */
  public static InetAddress getHostIpAddress() {
    return Tabs.primaryInterface.getAddress().toInetAddress();
  }

  /**
   * @return The default DNS name of this host.
   */
  public static String getHostname() {
    return Tabs.primaryInterface.getDnsName();
  }

  /**
   * Return the identifier the fixture is using to differentiate itself from
   * other fixtures on this host.
   *
   * @return The identifier for this fixture.
   */
  public static String getId() {
    return Tabs.FIXTUREID;
  }

  /**
   * Return a string describing the source location of a given exception.
   *
   * @param t The exception on which to report.
   *
   * @return The class and line number throwing the exception.
   */
  public static String getLocation(final Throwable t) {
    final StringBuffer buffer = new StringBuffer();

    final StackTraceElement[] stack = t.getStackTrace();
    StackTraceElement elem = stack[(stack.length - 1)];

    buffer.append(elem.getClassName());
    buffer.append(".");
    buffer.append(elem.getMethodName());
    buffer.append("(");

    if (elem.getLineNumber() < 0) {
      buffer.append("Native Method");
    } else {
      buffer.append(elem.getFileName());
      buffer.append(":");
      buffer.append(elem.getLineNumber());
    }
    buffer.append(")");

    if (stack.length > 1) {
      buffer.append(" - root cause: ");

      elem = stack[0];

      // -- yes, duplicate code, but inline is still faster --
      buffer.append(elem.getClassName());
      buffer.append(".");
      buffer.append(elem.getMethodName());
      buffer.append("(");

      if (elem.getLineNumber() < 0) {
        buffer.append("Native Method");
      } else {
        buffer.append(elem.getFileName());
        buffer.append(":");
        buffer.append(elem.getLineNumber());
      }

      buffer.append(")");
    }
    return buffer.toString();
  }

  /**
   * Access the contents of the current Tabs log file.
   *
   *
This will return the entire log file as a string and care should be
   * taken to ensure the runtime does not run out of memory by trying to read
   * in a very large log file.

   *
   * @return The entire log file as a string.
   */
  public static String getLogContents() {
    // TODO - perform file checks. What if the file is memory based?
    return FileUtil.fileToString(UriUtil.getFile(Tabs.getLogTarget()));
  }

  /**
   * Access the last lines in the current log file.
   *
   *
Will return the last portion of the log file in a manner similar to the
   * UNIX tail command.

   *
   * @param lines The number of lines to return. If the number is less than
   *        one, then the default of 20 is used.
   *
   * @return The tail portion of the current Tabs log file.
   */
  public static String getLogContents(final int lines) {
    // TODO - perform file checks. What if the file is memory based?
    final LinkedList entries = new LinkedList();
    int limit = lines;

    if (lines < 1) {
      limit = 20;
    }

    final File file = UriUtil.getFile(Tabs.getLogTarget());

    if (file.exists() && file.canRead()) {
      FileInputStream fin = null;
      String logLine;

      try {
        fin = new FileInputStream(file);
        final BufferedReader myInput = new BufferedReader(new InputStreamReader(fin));
        while ((logLine = myInput.readLine()) != null) {
          entries.add(logLine);
          if (entries.size() > limit) {
            entries.removeFirst();
          }
        }
      } catch (final Exception e) {}
      finally {
        try {
          if (fin != null) {
            fin.close();
          }
        } catch (final Exception ignore) {}
      }
    }

    final StringBuffer buffer = new StringBuffer();

    while (entries.size() > 0) {
      buffer.append((String)entries.removeFirst());
      if (entries.size() > 0) {
        buffer.append(Tabs.LF);
      }
    }

    return buffer.toString();
  }

  /**
   * @return The URI to the current log file.
   */
  public static URI getLogTarget() {
    return null;// ( (CyclingFileAppender)Tabs.logger ).getTarget();
  }

  /**
   * @return Returns the maximum number of events to keep in the MIB.
   */
  public  int getMaxEvents() {
    return eventList.getMaxEvents();
  }

  /**
   * Returns the maximum amount of memory that the virtual machine will attempt
   * to use.
   *
   *
The heap can grow to this limit but never more than this.

   *
   *
Keep in mind this and all memory values are approximate as the garbage
   * collector can be running at the same time. Also, other threads may be
   * allocating object on the heap, changing the values between calls.

   *
   * @return The maximum number of bytes the heap can ever allocate.
   */
  public static long getMaxHeapSize() {
    return Runtime.getRuntime().maxMemory();
  }

  /**
   * @return The netmask for this hosts primary interface or 255.255.255.255 if
   *         the netmask could not be otherwise determined.
   */
  public static String getNetmask() {
    return Tabs.primaryInterface.getNetmask().toString();
  }

  /**
   * @return  the primary IP interface on this host.
   */
  public static IpInterface getPrimaryInterface() {
    return Tabs.primaryInterface;
  }

  /**
   * @return The hostname without the domain portion
   */
  public static String getRelativeHostname() {
    return Tabs.primaryInterface.getRelativeHostname();
  }

  /**
   * @return The epoch time in milliseconds this fixture was started.
   */
  public static long getStartedTime() {
    return Tabs.startedTimestamp;
  }

  /**
   * Return the state with the given name.
   *
   *
If the state does not exist, one will be created and added to the
   * static list of states for later retrieval.

   *
   * @param name The name of the state to return.
   *
   * @return The state with the given name.
   */
  public static State getState(final String name) {
    State state = null;
    synchronized (Tabs.states) {
      state = (State)Tabs.states.get(name);
      if (state == null) {
        state = new State(name);
        Tabs.states.put(name, state);
      }
    }
    return state;
  }

  /**
   * @return The number of states in the fixture at the present time.
   */
  public static int getStateCount() {
    return Tabs.states.size();
  }

  /**
   * Access an interator over the states.
   *
   *
NOTE: this iterator is detached from the states in that the remove()
   * call on the iterator will only affect the returned iterator and not the
   * state collection in the fixture. If you wish to remove a state, you MUST
   * call removeState(Counter) with the reference returned from this iterator
   * as well.

   *
   * @return a detached iterator over the states.
   */
  public static Iterator getStateIterator() {
    final ArrayList list = new ArrayList();
    for (final Iterator it = Tabs.states.values().iterator(); it.hasNext(); list.add((State)it.next())) {
      ;
    }
    return list.iterator();
  }

  /**
   * @return All states as attributes of a packet.
   */
  public static DataFrame getStateMessage() {
    final DataFrame retval = new DataFrame();
    //retval.setType( "States" );

    synchronized (Tabs.states) {
      for (final Iterator it = Tabs.states.entrySet().iterator(); it.hasNext();) {
        final State stayt = (State)((Map.Entry)it.next()).getValue();
        try {
          retval.put(stayt.getName(), stayt.getValue());
        } catch (final Exception ignore) {}
      }
    }

    return retval;
  }

  /**
   * @return The subnet address for this hosts primary interface in CIDR format.
   */
  public static String getSubnet() {
    return Tabs.primaryInterface.getSubnet().toString();
  }

  /**
   * Get an iterator over all the Master Timers in the fixture.
   *
   * @return an iterator over all the timers
   */
  public static Iterator getTimerIterator() {
    final ArrayList list = new ArrayList();
    synchronized (Tabs.masterTimers) {
      for (final Iterator it = Tabs.masterTimers.values().iterator(); it.hasNext(); list.add((TimingMaster)it.next())) {
        ;
      }
    }
    return list.iterator();
  }

  /**
   * Get the master timer with the given name.
   *
   * @param name The name of the master timer to retrieve.
   *
   * @return The master timer with the given name or null if that timer
   *         does not exist.
   */
  public static TimingMaster getTimerMaster(final String name) {
    synchronized (Tabs.masterTimers) {
      return (TimingMaster)Tabs.masterTimers.get(name);
    }
  }

  public static DataFrame getTimerDataFrame() {
    final DataFrame retval = new DataFrame();
    //retval.setType( "Timers" );

    synchronized (Tabs.masterTimers) {
      for (final Iterator it = Tabs.masterTimers.entrySet().iterator(); it.hasNext();) {
        final TimingMaster timer = (TimingMaster)((Map.Entry)it.next()).getValue();
        //TODO: retval.add( timer.toMessage() );
      }
    }
    return retval;
  }

  /**
   * Return how long the fixture has been active in a format using only the
   * significant time measurements.
   *
   *
Significant measurements means if the number of seconds extend past 24
   * hours, then only report the days and hours skipping the minutes and
   * seconds. Examples include <tt>4m 23s</tt> or <tt>22d 4h</tt>. The format
   * is designed to make reporting fixture uptime more polished.

   *
   * @return the time the fixture has been active in a reportable format.
   */
  public static String getUptimeString() {
    return DateUtil.formatSignificantElapsedTime((System.currentTimeMillis() - Tabs.startedTimestamp) / 1000);
  }

  /**
   * Return the amount of memory used by the heap.
   *
   *
This shows how much memory is used in the currently allocated heap. The
   * MaxHeapSize thould equale this return value added to the FreeMemory
   * value.

   *
   *
Keep in mind this and all memory values are approximate as the garbage
   * collector can be running at the same time. Also, other threads may be
   * allocating object on the heap, changing the values between calls.

   *
   * @return Total used memory percentage of maximum memory.
   */
  public static float getUsedMemory() {
    return Tabs.getMaxHeapSize() - Tabs.getFreeMemory();
  }

  /**
   * Return the percentage of used memory of the maximum memory.
   *
   *
This is different from the Heap Percentage in that this calculation
   * takes both available memory and free heap to determine how much memory is
   * actually used by the runtime.

   *
   *
Keep in mind this and all memory values are approximate as the garbage
   * collector can be running at the same time. Also, other threads may be
   * allocating object on the heap, changing the values between calls.

   *
   * @return Total used memory percentage of maximum memory.
   */
  public static float getUsedMemoryPercentage() {
    return (float)(1 - ((float)Tabs.getFreeMemory() / (float)Tabs.getMaxHeapSize())); // percent of max
  }

  /**
   * @return  Returns the workDirectory.
   * @uml.property  name="workDirectory"
   */
  static File getWorkDirectory() {
    return Tabs.workDirectory;
  }

  /**
   * Increase the value with the given name by the given amount.
   *
   *
This method retrieves the counter with the given name or creates one by
   * that name if it does not yet exist. The retrieved counter is then
   * increased by the given amount.

   *
   * @param tag The name of the counter to increase.
   * @param value the amount to increase
   *
   * @return The final value of the counter after the operation.
   */
  public static long increase(final String tag, final long value) {
    return Tabs.getCounter(tag).increase(value);
  }

  /**
   * Increment the value with the given name.
   *
   *
This method retrieves the counter with the given name or creates one by
   * that name if it does not yet exist. The retrieved counter is then
   * increased by one (1).

   *
   * @param tag The name of the counter to increment.
   *
   * @return The final value of the counter after the operation.
   */
  public static long increment(final String tag) {
    return Tabs.getCounter(tag).increment();
  }

  /**
   * Process the given exception in a uniform manner.
   *
   *
This method will log the exception, generate an event for the exception
   * and send the exception to the event queue for agents to pick-up.

   *
   * @param t The excpetion to process
   *
   * @return The identifier of the event created. This can later be used to
   *         retrieve the event from the event list.
   */
  public long process(final Throwable t) {
    return process(t, null, null, null, null);
  }

  /**
   * Process the given exception in a uniform manner.
   *
   *
This method will log the exception, generate an event for the exception
   * and send the exception to the event queue for agents to pick-up.

   *
   * @param t The excpetion to process
   * @param info more information about the exception
   *
   * @return The identifier of the event created. This can later be used to
   *         retrieve the event from the event list.
   */
  public long process(final Throwable t, final String info) {
    return process(t, info, null, null, null);
  }

  /**
   * Process the given exception in a uniform manner.
   *
   *
This method will log the exception, generate an event for the exception
   * and send the exception to the event queue for agents to pick-up.

   *
   * @param t The excpetion to process
   * @param info more information about the exception
   * @param appId A correlating identifier representing the application.
   * @param sysId A correlating identifier representing a subsystem in the application.
   * @param cmpId A correlating identifier representing a component within a subsystem.
   *
   * @return The identifier of the event created. This can later be used to
   *         retrieve the event from the event list.
   */
  public long process(final Throwable t, final String info, final String appId, final String sysId, final String cmpId) {
    // create an event from the exception
    final AppEvent event = eventList.createEvent(appId, sysId, cmpId, info, AppEvent.WARNING, 0, 0, "EXCEPTION");

    final StringBuffer b = new StringBuffer();
    if (info != null) {
      b.append(info);
      b.append(Tabs.LF);
    }

    // Some helpful information in tracking down the source of the exception
    b.append("EXCEPTION: ");
    b.append(t.getClass().getName());

    b.append(Tabs.LF);
    b.append("Message: ");
    b.append(t.getMessage());

    b.append(Tabs.LF);
    b.append("Location: ");
    b.append(Tabs.getLocation(t));

    b.append(Tabs.LF);
    b.append("EventID: ");
    b.append(event.getSequence());

    b.append(Tabs.LF);
    b.append("RuntimeID: ");
    b.append(Tabs.getId());

    b.append(Tabs.LF);
    b.append("Host: ");
    b.append(Tabs.getHostname());
    b.append("(");
    b.append(Tabs.getHostIpAddress().getHostAddress());
    b.append(")");

    b.append(Tabs.LF);
    b.append("Runtime: Java ");
    b.append(System.getProperty("java.version"));
    b.append("(");
    b.append(System.getProperty("java.vendor"));
    b.append(")");

    b.append(Tabs.LF);
    b.append("Platform: ");
    b.append(System.getProperty("os.arch"));
    b.append(" OS: ");
    b.append(System.getProperty("os.name"));
    b.append("(");
    b.append(System.getProperty("os.version"));
    b.append(")");

    b.append(Tabs.LF);
    b.append("Heap Memory: ");
    b.append(Tabs.getMaxHeapSize());
    b.append(" bytes max, ");
    b.append(Tabs.getCurrentHeapSize());
    b.append(" bytes (");
    b.append(Tabs.getHeapPercentage() * 100);
    b.append("%) allocated");
    b.append(Tabs.LF);
    b.append("Free Memory: ");
    b.append(Tabs.getFreeMemory());
    b.append(" bytes (");
    b.append(Tabs.getFreeMemoryPercentage() * 100);
    b.append("%)");

    b.append(Tabs.LF);
    b.append("Thread: name='");
    b.append(Thread.currentThread().getName());
    b.append("\' type=");
    if (Thread.currentThread().isDaemon()) {
      b.append("daemon, group='");
    } else {
      b.append("user, group='");
    }

    b.append(Thread.currentThread().getThreadGroup().getName());
    b.append("'");
    b.append(Tabs.LF);
    b.append("Thread Call Stack:");
    b.append(Tabs.LF);
    b.append(ExceptionUtil.stackTrace(t));

    // set the exception details in the event
    event.setMessage(b.toString());

    // Exceptions should be logged
    Log.warn(b.toString());

    // final long retval = Tabs.oamManager.sendEvent( event );
    final long retval = event.getSequence();

    return retval;
  }

  /**
   * Add the given component / identifier to the fixture.
   *
   *
If the argument is a string, then the argument will be used to only
   * record the identifier of the component. If the argument implements
   * <tt>ManageableComponent</tt>, then the component identifier will be
   * extracted from the component and a reference to the passed component will
   * be stored for later reporting operations.

   *
   *
This is helpful when it is desired to know what components are residing
   * with this fixture. Often other components are required to report if a
   * particular set of components are loaded, and this facility gives those
   * components a place to register.

   *
   * @see #removeComponent(String)
   *
   * @param cmpnt The component identifier to add
   */
  public static void registerComponent(final Object cmpnt) {
    String cmpntid = null;
    if (cmpnt != null) {
      if (cmpnt instanceof String) {
        cmpntid = (String)cmpnt;
        if (cmpntid.length() > 0) {
          synchronized (Tabs.componentMap) {
            if (!Tabs.componentMap.containsKey(cmpntid)) {
              Tabs.componentMap.put(cmpntid, null);
            }
          }
        }
      } else if (cmpnt instanceof Component) {
        cmpntid = ((Component)cmpnt).getId();
        if ((cmpntid != null) && (cmpntid.length() > 0)) {
          synchronized (Tabs.componentMap) {
            if (Tabs.componentMap.containsKey(cmpntid)) {
              final Exception ex = new Exception();
              ex.fillInStackTrace();

              Log.warn("Overwriting existing named component '" + cmpntid + "' - Make sure component names are unique! Stacktrace:\r\n" + ExceptionUtil.stackTrace(ex));

            }
            Tabs.componentMap.put(cmpntid, (Component)cmpnt);
          }
        }
      }

      // else, try to reflect into the class for a getId() method

      // If all else fails, then just use the classname
      else {
        cmpntid = cmpnt.getClass().getName();
        synchronized (Tabs.componentMap) {
          Tabs.componentMap.put(cmpntid, null);
        }
      }
    } else {
      Log.error("Can not register a NULL component");
    }

  }

  /**
   * Remove the given component identifier from the fixture.
   *
   *
Components that registered their logical identifiers can use this
   * method to remove their registration when those components terminate or
   * otherwise wish to record their absence.

   *
   * @param cmpntid The component identifier to remove
   */
  public static void removeComponent(final String cmpntid) {
    if ((cmpntid != null) && (cmpntid.length() > 0)) {
      synchronized (Tabs.componentMap) {
        Tabs.componentMap.remove(cmpntid);
      }
    }
  }

  /**
   * Remove the counter with the given name.
   *
   * @param name Name of the counter to remove.
   *
   * @return The removed counter.
   */
  public static Counter removeCounter(final String name) {
    synchronized (Tabs.counters) {
      return (Counter)Tabs.counters.remove(name);
    }
  }

  /**
   * Remove the state with the given name.
   *
   * @param name Name of the state to remove.
   *
   * @return The removed state.
   */
  public static State removeState(final String name) {
    if (name == null) {
      return null;
    }

    synchronized (Tabs.states) {
      return (State)Tabs.states.remove(name);
    }
  }

  /**
   * Reset the counter with the given name returning a copy of the counter
   * before the reset occurred.
   *
   *
The return value will represent a copy of the counter prior to the
   * reset and is useful for applications that desire delta values. These delta
   * values are simply the return values of successive reset calls.

   *
   *
If the counter does not exist, it will be created prior to being reset.
   * The return value will reflect an empty counter with the given name.

   *
   * @param name The name of the counter to reset.
   *
   * @return a counter containing the values of the counter prior to the reset.
   */
  public static Counter resetCounter(final String name) {
    Counter retval = null;
    synchronized (Tabs.counters) {
      retval = Tabs.getCounter(name).reset();
    }

    return retval;
  }

  /**
   * Reset and clear-out the named gauge.
   *
   * @param name The name of the gauge to clear out.
   */
  public static void resetGauge(final String name) {
    if ((name != null) && (name.length() > 0)) {
      Tabs.getGauge(name).reset();
    }
  }

  /**
   * Removes all timers from the fixture and frees them up for garbage
   * collection.
   */
  public static void resetTimers() {
    synchronized (Tabs.masterTimers) {
      Tabs.masterTimers.clear();
    }
  }

  /**
   * Set the maximum number of events to keep in the MIB.
   *
   * @param max The maximum number of events to keep.
   */
  public void setMaxEvents(final int max) {
    eventList.setMaxEvents(max);
  }

  /**
   * Set the named state to the given value.
   *
   * @param name The name of the state to set.
   *
   * @param value The value to set in the state.
   */
  public static void setState(final String name, final double value) {
    Tabs.getState(name).set(value);
  }

  /**
   * Set the named state to the given value.
   *
   * @param name The name of the state to set.
   *
   * @param value The value to set in the state.
   */
  public static void setState(final String name, final long value) {
    Tabs.getState(name).set(value);
  }

  /**
   * Set the named state to the given value.
   *
   * @param name The name of the state to set.
   *
   * @param value The value to set in the state.
   */
  public static void setState(final String name, final String value) {
    if ((name != null) && (name.length() != 0)) {
      if (value == null) {
        Tabs.removeState(name);
      } else {
        Tabs.getState(name).set(value);
      }
    }
  }

  /**
   * Start an Application Response Measurement transaction.
   *
   * @param tag Grouping tag.
   *
   * @return A transaction to collect ARM data.
   */
  public static ArmTransaction startArm(final String tag) {
    return Tabs.startArm(tag, null);
  }

  /**
   * Start an Application Response Measurement transaction using a particular
   * correlation identifier.
   *
   * @param tag Grouping tag.
   * @param crid correlation identifier
   *
   * @return A transaction to collect ARM data.
   */
  public static ArmTransaction startArm(final String tag, final String crid) {
    ArmTransaction retval = null;
    if (Tabs.armEnabled) {
      synchronized (Tabs.armMasters) {
        // get an existing ARM master or create a new one
        ArmMaster master = (ArmMaster)Tabs.armMasters.get(tag);
        if (master == null) {
          master = new ArmMaster(tag);
          Tabs.armMasters.put(tag, master);
        }

        // have the master ARM return a transaction instance
        retval = master.createArm(tag, crid);

        //start the ARM transaction
        retval.start();
      }
    } else {
      // just return the do-nothing timer
      retval = Tabs.NULL_ARM;
    }

    return retval;
  }

  /**
   * Start a timer with the given name.
   *
   *
Use the returned Timer to stop the interval measurement.

   *
   * @param tag The name of the timer instance to start.
   *
   * @return The timer instance that should be stopped when the interval is
   *         completed.
   */
  public static Timer startTimer(final String tag) {
    Timer retval = null;
    if (Tabs.timingEnabled) {
      synchronized (Tabs.masterTimers) {
        // get an existing master timer or create a new one
        TimingMaster master = (TimingMaster)Tabs.masterTimers.get(tag);
        if (master == null) {
          master = new TimingMaster(tag);
          Tabs.masterTimers.put(tag, master);
        }

        // have the master timer return a timer instance
        retval = master.createTimer();

        //start the timer instance
        retval.start();
      }
    } else {
      // just return the do-nothing timer
      retval = Tabs.NULL_TIMER;
    }

    // return the started timer
    return retval;
  }

  /**
   * Update the named gauge with the given value.
   *
   * @param name The name of the gauge to update.
   * @param value The value with which to update the gauge.
   */
  public static void updateGauge(final String name, final long value) {
    if ((name != null) && (name.length() > 0)) {
      Tabs.getGauge(name).update(value);
    }
  }

  /**
   * Zip a single file into a compressed ZIP archive.
   *
   *
This will result in a compressed archive that contain a single file
   * entry. The name of the archive will be the name of the source file with
   * the added extension of 'zip'.

   *
   * @param source The file to archive.
   *
   * @throws IOException If problems were experienced.
   */
  private static void zipFile(final File source) throws IOException {
    BufferedInputStream origin = null;
    ZipOutputStream out = null;
    try {
      final FileOutputStream dest = new FileOutputStream(source.getAbsolutePath() + ".zip");
      out = new ZipOutputStream(new BufferedOutputStream(dest));

      final byte data[] = new byte[Tabs.STREAM_BUFFER_SIZE];

      final FileInputStream fi = new FileInputStream(source);
      origin = new BufferedInputStream(fi, Tabs.STREAM_BUFFER_SIZE);

      final ZipEntry entry = new ZipEntry(source.getName());
      out.putNextEntry(entry);

      int count;
      while ((count = origin.read(data, 0, Tabs.STREAM_BUFFER_SIZE)) != -1) {
        out.write(data, 0, count);
      }
    } catch (final FileNotFoundException e) {
      throw new IOException(e.getMessage());
    }
    finally {
      try {
        origin.close();
      } catch (final IOException ignore) {}
      try {
        out.close();
      } catch (final IOException ignore) {}
    }
  }

  public void finalize() throws Throwable {
    shutdown("Finalization");
  }

  /**
   * This will initialize the environment for the fixture.
   */
  private void open() {
    // Get the primary interface for this host
    Tabs.primaryInterface = IpInterface.getPrimary();

    // Make sure we have a home directory we can use
    if (System.getProperty(Tabs.HOMEDIR_TAG) == null) {
      System.setProperty(Tabs.HOMEDIR_TAG, Tabs.DEFAULT_HOME);
    } else {
      // Normalize the "." that sometimes is set in the SG_HOME property
      if (System.getProperty(Tabs.HOMEDIR_TAG).trim().equals(".")) {
        System.setProperty(Tabs.HOMEDIR_TAG, Tabs.DEFAULT_HOME);
      } else if (System.getProperty(Tabs.HOMEDIR_TAG).trim().length() == 0) {
        // catch empty home property and just use the home directory
        System.setProperty(Tabs.HOMEDIR_TAG, Tabs.DEFAULT_HOME);
      }
    }

    // Remove all the relations and extra slashes from the home path
    System.setProperty(Tabs.HOMEDIR_TAG, FileUtil.normalizePath(System.getProperty(Tabs.HOMEDIR_TAG)));

    // Check for a configured Fixture Id
    String prop = System.getProperty(Tabs.ID_TAG);
    if (prop != null) {
      Tabs.FIXTUREID = prop;
    }

    // Check for a configured Fixture Group
    prop = System.getProperty(Tabs.GROUP_TAG);
    if (prop != null) {
      Tabs.FIXTUREGRP = prop;
    }
  }

  /**
   * Called by the shutdown hook to make sure everything is closed properly.
   */
  private void shutdown(final String msg) {}
}