text:
describe RFunk::None do
  context 'None' do
    context 'nil is none' do
      When(:result) { RFunk.option(nil) }
      Then { result == RFunk.none }
    end

    context 'value' do
      context 'value is none' do
        When(:result) { RFunk.option(nil) }
        Then { result.value == RFunk.none }
      end

      context 'value({}) is none' do
        When(:result) { RFunk.option(nil) }
        Then { result.value == RFunk.none }
      end

      context 'value(none) is none' do
        When(:result) { RFunk.option(nil) }
        Then { result.value == RFunk.none }
      end
    end

    context 'Maybe(none) is none' do
      When(:result) { RFunk.option(RFunk.none) }
      Then { result == RFunk.none }
    end

    context 'nil always has none as a result' do
      context 'single value' do
        When(:result) { RFunk.option(nil).a }
        Then { result == RFunk.none }
      end

      context 'double value' do
        When(:result) { RFunk.option(nil).a.b }
        Then { result == RFunk.none }
      end

      context 'triple value' do
        When(:result) { RFunk.option(nil).a.b.c }
        Then { result == RFunk.none }
      end
    end

    context 'non-existent methods always has none as a result' do
      context 'single value' do
        When(:result) { RFunk.option({}).a }
        Then { result == RFunk.none }
      end

      context 'double value' do
        When(:result) { RFunk.option({}).a.b }
        Then { result == RFunk.none }
      end

      context 'triple value' do
        When(:result) { RFunk.option({}).a.b.c }
        Then { result == RFunk.none }
      end
    end

    context 'non-existent keys always has none as a result' do
      context 'single value' do
        When(:result) { RFunk.option({})[:a] }
        Then { result == RFunk.none }
      end

      context 'double value' do
        When(:result) { RFunk.option({})[:a][:b] }
        Then { result == RFunk.none }
      end

      context 'triple value' do
        When(:result) { RFunk.option({})[:a][:b][:c] }
        Then { result == RFunk.none }
      end
    end

    context 'none with or to return the other value' do
      context 'single value' do
        When(:result) { RFunk.option(nil).a.or('test') }
        Then { result == RFunk.some('test') }
      end

      context 'double value' do
        When(:result) { RFunk.option(nil).a.b.or('test') }
        Then { result == RFunk.some('test') }
      end

      context 'triple value' do
        When(:result) { RFunk.option(nil).a.b.c.or('test') }
        Then { result == RFunk.some('test') }
      end

      context 'nil value' do
        When(:result) { RFunk.option(nil).a.b.c.or(nil) }
        Then { result == RFunk.none }
      end
    end

    context 'already a None' do
      When(:result) { RFunk.option(RFunk.none) }
      Then { result == RFunk.none }
    end

    context 'pipeline' do
      When(:result) { RFunk.none.pipe { |h| h.merge(b: 1) }.pipe { |h| h.merge(c: 1) } }
      Then { result == RFunk.none }
    end
  end
end


text:
#ifndef __CACHE_H
#define __CACHE_H

#include <freerdp/api.h>
#include <freerdp/types.h>
#include <freerdp/update.h>
#include <freerdp/utils/stream.h>

#include <freerdp/cache/glyph.h>
#include <freerdp/cache/brush.h>
#include <freerdp/cache/pointer.h>
#include <freerdp/cache/bitmap.h>
#include <freerdp/cache/offscreen.h>
#include <freerdp/cache/palette.h>

struct rdp_cache
{
	rdpGlyphCache* glyph; /* 0 */
	rdpBrushCache* brush; /* 1 */
	rdpPointerCache* pointer; /* 2 */
	rdpBitmapCache* bitmap; /* 3 */
	rdpOffscreenCache* offscreen; /* 4 */
	rdpPaletteCache* palette; /* 5 */

	/* internal */

	rdpSettings* settings;
};

FREERDP_API rdpCache* cache_new(rdpSettings* settings);
FREERDP_API void cache_free(rdpCache* cache);

#endif /* __CACHE_H */

redpajama_set_name: RedPajamaGithub


text:
FROM fedora:23
RUN dnf install -y socat
CMD ["/usr/bin/socat", "TCP-LISTEN:3000,fork", "TCP:server:2000"]


text:
import * as React from "react";
import { Link, LinkProps } from "react-router-dom";
import cn from "./RouterLink.less";

type Props = {
    icon?: React.ReactNode;
} & LinkProps<typeof Link>;

export default function RouterLink(props: Props): React.ReactElement<typeof Link> {
    const { icon, className, children } = props;
    return (
        <Link className={cn(className, "link")} {...props}>
            {icon}
            {icon ? " " : ""}
            {children}
        </Link>
    );
}


text:
package aQute.bnd.service.message;

import java.util.regex.Pattern;

import org.osgi.util.promise.Promise;

import aQute.service.reporter.Reporter;

/**
 * A simple dialog handler for prompting for an input string from the user,
 * displaying a message to the user, or showing a set of errors and warnings.
 * These methods can be called on any thread.
 */
public interface Dialogs {

	/**
	 * Display a message and optionally a set of buttons. Return the index of
	 * the selected button or -1 if the dialog was canceled.
	 *
	 * @param title The title of the dialog, must not be null
	 * @param message The message displayed, must not be null
	 * @param buttons A list of buttons, may be null
	 * @param defaultIndex The default index. Must be -1 for none or between
	 *            0..n, where n is the number of buttons specified.
	 * @return -1 if canceled, otherwise the index of the given button that was
	 *         pressed.
	 */
	Promise<Integer> message(String title, String message, String[] buttons, int defaultIndex) throws Exception;

	/**
	 * Display a dialog where the user can input a string. An initial value can
	 * be supplied and a validator can optionally beused to validate any input.
	 * Either null is returned when the user cancels or a string with valid
	 * input.
	 *
	 * @param title The title of the dialog, must not be null
	 * @param query The query displayed, must not be null
	 * @param initialValue The initial value, can be null
	 * @param validator A pattern that must match the input, can be null if no
	 *            validator is necessary
	 * @return A string object or null if no input was given
	 */
	Promise<String> prompt(String title, String query, String initialValue, Pattern validator) throws Exception;

	/**
	 * Display a list of errors and warnings. This method will return
	 * immediately, it will not wait for the user to dismiss this window.
	 * Multiple calls might actually be aggregated into a single dialog
	 *
	 * @param message The message displayed, must not be null
	 * @param reporter Contains the errors and warnings
	 */
	void errors(String message, Reporter reporter) throws Exception;

	/**
	 * Create a progress monitor
	 */

	Progress createProgress(String title) throws Exception;

}


text:
#include "cli/pch.h"

#include "cli/ui_password.h"

#include "test_error.h"
#include "test_device.h"
#include "test_exec.h"

// cli::ui::Password unit-tests.
const bool CheckGetPassword(void)
{
    class Test {
    public:
        static const bool Password(
                const cli::CallInfo& CLI_CallInfo,
                const bool B_DisplayStars,
                const char* const STR_Input, const unsigned int UI_MinLength, const unsigned int UI_MaxLength,
                const bool B_ExpectedResult, const char* const STR_StringOutput, const char* const STR_DeviceOutput)
        {
            TestBlockingDevice cli_BlockingDevice(false);
            if (! Password(CLI_CallInfo, cli_BlockingDevice, cli_BlockingDevice, B_DisplayStars, STR_Input, UI_MinLength, UI_MaxLength, B_ExpectedResult, STR_StringOutput, STR_DeviceOutput)) {
                return false;
            }
            TestNonBlockingDevice cli_NonBlockingDevice(false);
            if (! Password(CLI_CallInfo, cli_NonBlockingDevice, cli_NonBlockingDevice, B_DisplayStars, STR_Input, UI_MinLength, UI_MaxLength, B_ExpectedResult, STR_StringOutput, STR_DeviceOutput)) {
                return false;
            }
            return true;
        }
    private:
        static const bool Password(
                const cli::CallInfo& CLI_CallInfo, cli::IODevice& CLI_TestDevice, TestDeviceData& CLI_TestDeviceData,
                const bool B_DisplayStars,
                const char* const STR_Input, const unsigned int UI_MinLength, const unsigned int UI_MaxLength,
                const bool B_ExpectedResult, const char* const STR_StringOutput, const char* const STR_DeviceOutput)
        {
            cli::ui::Password cli_Password(B_DisplayStars, UI_MinLength, UI_MaxLength);
            cli_Password.SetStream(cli::WELCOME_STREAM, cli::OutputDevice::GetNullDevice());
            cli_Password.SetStream(cli::PROMPT_STREAM, cli::OutputDevice::GetNullDevice());
            const bool b_Result = (
                CheckExecuteContext(CLI_CallInfo, cli_Password, CLI_TestDevice, STR_Input)
                && cli_Password.GetbExecResult()
            );

            if (b_Result != B_ExpectedResult) {
                TestError(CLI_CallInfo) << "UI::GetPassword() returned " << b_Result << " (" << B_ExpectedResult << " was expected)" << cli::endl;
                return false;
            }
            if (strcmp((const char* const) cli_Password.GetPassword(), STR_StringOutput) != 0) {
                TestError(CLI_CallInfo) << "String output '" << cli_Password.GetPassword() << "' does not match '" << STR_StringOutput << "'" << cli::endl;
                return false;
            }
            const cli::tk::String cli_OutputString = CLI_TestDeviceData.GetOutput();
            if (strcmp((const char* const) cli_OutputString, STR_DeviceOutput) != 0) {
                TestError(CLI_CallInfo) << "Device output '" << cli_OutputString << "' does not match '" << STR_DeviceOutput << "'" << cli::endl;
                return false;
            }
            return true;
        }
    };

    // Test basic character inputs (no star).
    if (! Test::Password(__CALL_INFO__, false, "012345\n", 0, 10, true, "012345", Out().endl())) return false;
    // Test basic character inputs (star).
    if (! Test::Password(__CALL_INFO__, true, "012345\n", 0, 10, true, "012345", Out().txt("******").endl())) return false;
    // Test maximum password length.
    if (! Test::Password(__CALL_INFO__, true, "0123456789\n", 0, 10, true, "0123456789", Out().txt("**********").endl())) return false;
    if (! Test::Password(__CALL_INFO__, true, "0123456789a\n", 0, 10, true, "0123456789", Out().txt("**********").beep().endl())) return false;
    if (! Test::Password(__CALL_INFO__, true, "012345\b6789a\n", 0, 10, true, "012346789a", Out().txt("******").bsp(1).txt("*****").endl())) return false;
    if (! Test::Password(__CALL_INFO__, true, "\b0123456789a\n", 0, 10, true, "0123456789", Out().beep().txt("**********").beep().endl())) return false;
    // Test minimum password length.
    if (! Test::Password(__CALL_INFO__, true, "0\n", 5, 10, false, "", Out().txt("*").beep().bsp(1).endl())) return false;

    // Test LEFT/RIGHT moves the cursor in the line (insert mode).
    if (! Test::Password(__CALL_INFO__, true, "abcdef%lx%r\n", 0, 10, true, "abcdexf", Out().txt("******").left(1).txt("**\b").right("*").endl())) return false;
    // Test LEFT/RIGHT moves the cursor in the line (replace mode).
    if (! Test::Password(__CALL_INFO__, true, "abcdef%i%lx%r\n", 0, 10, true, "abcdex", Out().txt("******").left(1).txt("*").beep().endl())) return false;
    // Test UP/DOWN/PUP/PDOWN does nothing.
    if (! Test::Password(__CALL_INFO__, true, "abcdef%u%d\n", 0, 10, true, "abcdef", Out().txt("******").endl())) return false;
    if (! Test::Password(__CALL_INFO__, true, "abcdef%U%D\n", 0, 10, true, "abcdef", Out().txt("******").endl())) return false;
    // Test HOME/END keys.
    if (! Test::Password(__CALL_INFO__, true, "abcdef%H%E\n", 0, 10, true, "abcdef", Out().txt("******").left(6).right("******").endl())) return false;

    // Test ESCAPE breaks the current input.
    if (! Test::Password(__CALL_INFO__, true, "abcdef\b\b%]", 0, 10, false, "", Out().txt("******").bsp(1).bsp(1).bsp(4).endl())) return false;
    // Test CTRL+C breaks the current input.
    if (! Test::Password(__CALL_INFO__, true, "abcdef\b\b%!", 0, 10, false, "", Out().txt("******").bsp(1).bsp(1).bsp(4).endl())) return false;

    return true;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE topic
  PUBLIC "-//OASIS//DTD DITA Composite//EN" "ditabase.dtd">
<topic id="topic1">
  <title id="dm20941">DROP USER</title>

Removes a database role.

      <title>Synopsis</title>
      <codeblock id="sql_command_synopsis">DROP USER [IF EXISTS] <name> [, ...]</codeblock>

      <title>Description</title>

<codeph>DROP USER</codeph> is an alias for <xref href="DROP_ROLE.xml#topic1"
            type="topic" format="dita"/>. See <xref href="DROP_ROLE.xml#topic1"
            type="topic" format="dita"/> for more information.

      <title>Compatibility</title>

There is no <codeph>DROP USER</codeph> statement in the SQL standard. The SQL standard
        leaves the definition of users to the implementation.

      <title>See Also</title>

<xref href="DROP_ROLE.xml#topic1" type="topic" format="dita"/>,
            <xref href="CREATE_USER.xml#topic1" type="topic" format="dita"/>

</topic>


text:
package models.dao

import play.api.db.slick.Profile

case class DepositsPlaceRecord(id: Option[Long], title: String, description: String)

trait DepositsPlaceComponent { this: Profile =>
  import profile.simple._

  class DepositsPlaces extends Table[DepositsPlaceRecord]("deposits_places") {
    def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
    def title = column[String]("title", O.NotNull)
    def description = column[String]("description", O.NotNull, O.DBType("text"))

    def * = id.? ~ title ~ description <> (DepositsPlaceRecord, DepositsPlaceRecord.unapply _)

    def autoInc = * returning id
  }
}


text:
import StockData from '../StockData';
import CandlestickFinder from './CandlestickFinder';
export default class BearishHammer extends CandlestickFinder {
    constructor();
    logic(data: StockData): boolean;
}
export declare function bearishhammer(data: StockData): any;


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using DevExpress.MailClient.Win.Helpers;
using DevExpress.XtraSplashScreen;
using DevExpress.Skins;
using DevExpress.Data.Filtering;
using DevExpress.MailClient.Win.Forms;
using System.Drawing;
using System.Threading;
using DevExpress.MailClient.EF;
using DevExpress.XtraEditors;
using System.Net.Mail;
using System.Xml;
using DevExpress.MailClient.Win.Helpers.Accounts;

// Hello eveybody! Gabi was here :P
// And I'm still here...

namespace DevExpress.MailClient.Win {
    static class Program {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] arguments) {

            // TODO uncomment to test EF code first sample
            // Prerequisites: SQL Server express
            //using (var mailContext = new MailContext())
            //{
            //    var savedUser = new User {Name = "Test", Password = "Test"};
            //    mailContext.Users.Add(savedUser);
            //    mailContext.SaveChanges();

            //    var retrievedUser = mailContext.Users.First();
            //    Console.WriteLine($"User: {retrievedUser.Name}");
            //}

            DataHelper.ApplicationArguments = arguments;
            DevExpress.Utils.LocalizationHelper.SetCurrentCulture(DataHelper.ApplicationArguments);
            DevExpress.UserSkins.BonusSkins.Register();
            DevExpress.Utils.AppearanceObject.DefaultFont = new Font("Segoe UI", 8);
            DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle("Office 2013");
            SkinManager.EnableFormSkins();
            EnumProcessingHelper.RegisterEnum<TaskStatus>();
            UnpackHelper.Unpack();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            bool accountCreated = CheckAccountExists();
            if (!accountCreated)
            {
                accountCreated = CreateAccount();
            }

            if (accountCreated)
            {
                ShowSplashScreen();
                Application.Run(new frmMain());
            }
        }

        private static void ShowSplashScreen()
        {
            if (AppContext.CurrentContext.Settings.ShowSplashScreen)
            {
                SplashScreenManager.ShowForm(null, typeof(ssMain), true, true, false, 1000);
            }
        }

        private static bool CheckAccountExists()
        {
            try
            {
                return AppContext.CurrentContext.Accounts.Any();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("Error - Cannot load accounts file" + ex.Message);
            }
            return false;
        }

        private static bool CreateAccount()
        {
            using (var accountForm = new EmailAccountForm())
            {
                return accountForm.ShowDialog() == DialogResult.OK;
            }
        }
    }
}


text:
using System;
using System.Web;
using System.Web.Mvc;

using CMS.Core;
using CMS.Helpers;
using CMS.Newsletters;
using CMS.SiteProvider;

using DancingGoat.Models.Subscription;

using Kentico.Membership;
using Kentico.Newsletters;

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

namespace DancingGoat.Web.Controllers
{
    public class SubscriptionController : Controller
    {
        private readonly INewsletterSubscriptionService mSubscriptionService;

        private NewsletterSubscriptionSettings mNewsletterSubscriptionSettings;

        private readonly IContactProvider mContactProvider = Service.Resolve<IContactProvider>();

        private NewsletterSubscriptionSettings NewsletterSubscriptionSettings
        {
            get
            {
                return mNewsletterSubscriptionSettings ?? (mNewsletterSubscriptionSettings = new NewsletterSubscriptionSettings
                {
                    AllowOptIn = true,
                    RemoveAlsoUnsubscriptionFromAllNewsletters = true,
                    SendConfirmationEmail = true
                });
            }
        }

        private UserManager UserManager
        {
            get
            {
                return HttpContext.GetOwinContext().Get<UserManager>();
            }
        }

        public SubscriptionController(INewsletterSubscriptionService subscriptionService)
        {
            mSubscriptionService = subscriptionService;
        }

        // POST: Subscription/Subscribe
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Subscribe(SubscribeModel model)
        {
            if (!ModelState.IsValid)
            {
                return PartialView("_Subscribe", model);
            }

            var newsletter = NewsletterInfoProvider.GetNewsletterInfo("DancingGoatMvcNewsletter", SiteContext.CurrentSiteID);

            var contact = mContactProvider.GetContactForSubscribing(model.Email);
            bool newlySubscribed = mSubscriptionService.Subscribe(contact, newsletter, NewsletterSubscriptionSettings);

            string resultMessage;

            if (newlySubscribed)
            {
                // The subscription service is configured to use double opt-in, but newsletter must allow for it
                resultMessage = ResHelper.GetString(newsletter.NewsletterEnableOptIn ? "DancingGoatMvc.News.ConfirmationSent" : "DancingGoatMvc.News.Subscribed");
            }
            else
            {
                resultMessage = ResHelper.GetString("DancingGoatMvc.News.AlreadySubscribed");
            }

            return Content(resultMessage);
        }

        // POST: Subscription/SubscribeAuthenticated
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult SubscribeAuthenticated()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return Show();
            }

            var user = UserManager.FindByName(User.Identity.Name);
            var newsletter = NewsletterInfoProvider.GetNewsletterInfo("DancingGoatMvcNewsletter", SiteContext.CurrentSiteID);
            var contact = mContactProvider.GetContactForSubscribing(user.Email, user.FirstName, user.LastName);

            bool newlySubscribed = mSubscriptionService.Subscribe(contact, newsletter, NewsletterSubscriptionSettings);

            string resultMessage;

            if (newlySubscribed)
            {
                // The subscription service is configured to use double opt-in, but newsletter must allow for it
                resultMessage = ResHelper.GetString(newsletter.NewsletterEnableOptIn ? "DancingGoatMvc.News.ConfirmationSent" : "DancingGoatMvc.News.Subscribed");
            }
            else
            {
                resultMessage = ResHelper.GetString("DancingGoatMvc.News.AlreadySubscribed");
            }

            return Content(resultMessage);
        }

        // GET: Subscription/ConfirmSubscription
        [ValidateInput(false)]
        public ActionResult ConfirmSubscription(ConfirmSubscriptionModel model)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError(String.Empty, ResHelper.GetString("DancingGoatMvc.News.ConfirmSubscriptionInvalidLink"));

                return View(model);
            }

            DateTime parsedDateTime = DateTimeHelper.ZERO_TIME;

            // Parse date and time from query string, if present
            if (!string.IsNullOrEmpty(model.DateTime) && !DateTimeUrlFormatter.TryParse(model.DateTime, out parsedDateTime))
            {
                ModelState.AddModelError(String.Empty, ResHelper.GetString("DancingGoatMvc.News.ConfirmSubscriptionInvalidDateTime"));

                return View(model);
            }

            var result = mSubscriptionService.ConfirmSubscription(model.SubscriptionHash, false, parsedDateTime);
            switch (result)
            {
                case ApprovalResult.Success:
                    model.ConfirmationResult = ResHelper.GetString("DancingGoatMvc.News.ConfirmSubscriptionSucceeded");
                    break;

                case ApprovalResult.AlreadyApproved:
                    model.ConfirmationResult = ResHelper.GetString("DancingGoatMvc.News.ConfirmSubscriptionAlreadyConfirmed");
                    break;

                case ApprovalResult.TimeExceeded:
                    ModelState.AddModelError(String.Empty, ResHelper.GetString("DancingGoatMvc.News.ConfirmSubscriptionTimeExceeded"));
                    break;

                case ApprovalResult.NotFound:
                    ModelState.AddModelError(String.Empty, ResHelper.GetString("DancingGoatMvc.News.ConfirmSubscriptionInvalidLink"));
                    break;

                default:
                    ModelState.AddModelError(String.Empty, ResHelper.GetString("DancingGoatMvc.News.ConfirmSubscriptionFailed"));

                    break;
            }

            return View(model);
        }

        // GET: Subscription/Unsubscribe
        [ValidateInput(false)]
        public ActionResult Unsubscribe(UnsubscriptionModel model)
        {
            string invalidUrlMessage = ResHelper.GetString("DancingGoatMvc.News.InvalidUnsubscriptionLink");

            if (ModelState.IsValid)
            {
                bool emailIsValid = mSubscriptionService.ValidateEmail(model.Email, model.Hash);

                if (emailIsValid)
                {
                    try
                    {
                        if (model.UnsubscribeFromAll)
                        {
                            mSubscriptionService.UnsubscribeFromAll(model.Email, model.NewsletterGuid, model.IssueGuid);
                            model.UnsubscriptionResult = ResHelper.GetString("DancingGoatMvc.News.UnsubscribedAll");
                        }
                        else
                        {
                            mSubscriptionService.Unsubscribe(model.Email, model.NewsletterGuid, model.IssueGuid);
                            model.UnsubscriptionResult = ResHelper.GetString("DancingGoatMvc.News.Unsubscribed");
                        }
                    }
                    catch (ArgumentException)
                    {
                        ModelState.AddModelError(String.Empty, invalidUrlMessage);
                    }
                }
                else
                {
                    ModelState.AddModelError(String.Empty, invalidUrlMessage);
                }
            }
            else
            {
                ModelState.AddModelError(String.Empty, invalidUrlMessage);
            }

            return View(model);
        }

        // GET: Subscription/Show
        public ActionResult Show()
        {
            if (User.Identity.IsAuthenticated)
            {
                // Handle authenticated user
                return PartialView("_SubscribeAuthenticated");
            }
            var model = new SubscribeModel();

            return PartialView("_Subscribe", model);
        }
    }
}


text:
#include "lib/zt_common.h"

#include "ibmOSAMibUtil.h"
#include "ibmOSAMib.h"

/* ptr to OSA Express MIB information stored in linked lists */
TABLE_OID* oid_list_head;

/* ptr to interface information on this system */
IF_LIST* if_list;
int ifNumber;

/**********************************************************************
 * init_ibmOSAMib():
 *  Initialization routine. This function is called when the agent
 *  starts up.
 *  parameters:
 *  IN  uses global MIB data
 *  OUT none
 *  returns: none
 *********************************************************************/
void init_ibmOSAMib(void) {

  int i,
    sd,         /* socket descriptor */
    error_code, /* holds errno value */
    osaexp_num, /* number of OSA Express devices */
    retc;       /* return code from register_tables */

  struct ifreq ifr;             /* request structure for ioctl */
  IPA_CMD_REG* ipa_reg_mib;     /* structure for IPA REGISTER MIB command header */
  char*        buffer;          /* a data buffer */
  char         time_buf[TIME_BUF_SIZE]; /* date/time buffer */

  /* init head for Toplevel OID linked list */
  oid_list_head = init_oid_list();
  if ( oid_list_head == NULL )
    {
      fprintf( stderr, "init_ibmOSAMib(): "
	       "malloc() for OID list head failed\n"
               "Cannot start subagent...exiting...\n");
      exit(1);
    }

  /* GET net-snmp ifNumber/ifIndex/ifDescr from IF-MIB for all interfaces */
  /* on this system                                                       */
  ifNumber = query_IF_MIB( &if_list );
  if ( ifNumber < 0 )
    {
      fprintf( stderr, "init_ibmOSAMib(): "
	       "could not obtain interface info from IF-MIB\n"
	       "check if: snmpd daemon is started and subagent "
	       "access control is correct\n"
	       "see agent log file for more details\n"
               "Cannot start subagent...exiting...\n");
      exit(1);
    }
  else if ( ifNumber == 0 )
    {
      get_time( time_buf );
      snmp_log( LOG_ERR, "%s init_ibmOSAMib(): "
		"SNMP reports no devices within IF-MIB"
		" - starting subagent anyway\n", time_buf );
      return;
    } /* end if */

  /* query OSA-E device driver for OSA-E devices and mark them in IF-MIB interface list */
  osaexp_num = query_OSA_EXP ( &if_list, ifNumber );
  if ( osaexp_num == 0 )
    {
      get_time( time_buf );
      snmp_log( LOG_ERR, "%s init_ibmOSAMib(): none of the %d interfaces is a real "
			 "OSA-E device - starting subagent anyway\n", time_buf, ifNumber);
      return;
    }
  /* end if */

  /* allocate area, that should contain retrieved MIB data for a single interface */
  buffer = (char*) malloc ( MIB_AREA_LEN );
  if ( buffer == NULL )
    {
      fprintf( stderr, "init_ibmOSAMib(): "
	       "malloc() for REGISTER MIB data buffer "
	       "failed\ninit_ibmOSAMib(): requested %d bytes\n"
	       "Cannot start subagent...exiting...\n",
	       MIB_AREA_LEN );
      exit(1);
    } /* end if */

  /* open socket for ioctl */
  sd = socket( AF_INET, SOCK_STREAM, 0 );
  if ( sd < 0 )
    {
      error_code = errno;
      fprintf( stderr, "init_ibmOSAMIB(): "
	       "error opening socket() - reason %s\n"
	       "Cannot start subagent...exiting...\n",
	       strerror( error_code ) );
      exit(1);
    } /* end if */

  /* walk through interface list and query MIB data for all OSA-E devices */
  /* register MIB data with subagent driving code afterwards              */
  for ( i=0; i < ifNumber; i++ )
    {
      if ( if_list[i].is_OSAEXP == TRUE )
	{
	  /* clear buffer */
	  memset( buffer, 0, MIB_AREA_LEN );

	  /* setup ioctl buffer with request and input parameters */
	  ipa_reg_mib = (IPA_CMD_REG*) buffer;                /* map command structure */
          ipa_reg_mib->ioctl_cmd.data_len  =                  /* length of IPA data area */
                       MIB_AREA_LEN - offsetof( IOCTL_CMD_HDR, ipa_cmd_hdr );
          ipa_reg_mib->ioctl_cmd.req_len =                    /* length of IPA subcommand */
                       sizeof( ipa_reg_mib->ioctl_cmd );

	  ipa_reg_mib->ioctl_cmd.ipa_cmd_hdr.request  = IPA_REG_MIB; /* IPA subcommand code */
          ipa_reg_mib->ioctl_cmd.ipa_cmd_hdr.ifIndex  = if_list[i].ifIndex; /* assign IF-MIB ifIndex */
          ipa_reg_mib->ioctl_cmd.ipa_cmd_hdr.ret_code = 0;
          ipa_reg_mib->ioctl_cmd.ipa_cmd_hdr.seq_num  = 0;           /* sequence number not used */

	  /* do ioctl */
	  strcpy( ifr.ifr_name, if_list[i].if_Name );         /* add interface name */
	  ifr.ifr_ifru.ifru_data = (char*) buffer;            /* add data buffer    */

	  if ( ioctl( sd, SIOC_QETH_ADP_SET_SNMP_CONTROL, &ifr ) < 0 )
	    {
	      error_code = errno;

              /* see if we got a common I/O error */
              if ( error_code == -EIO )
                {
                   get_time( time_buf );
                   snmp_log( LOG_ERR, "%s init_ibmOSAMib(): "
			     "ioctl() failed - reason %s for interface %s\n"
                             "init_ibmOSAMib(): start subagent anyway\n",
                              time_buf, strerror( error_code ), if_list[i].if_Name );
                   close( sd );
                   free( buffer );
                   return;
                   break;
                } /* end if */

	      /* let's see, if we got a return code from IPAssists */
	      /* or if MIB buffer is exhausted */
	      switch ( ipa_reg_mib->ioctl_cmd.ipa_cmd_hdr.ret_code ) {
	      case IPA_FAILED:
		fprintf( stderr, "init_ibmOSAMib(): "
			 "ioctl() failed - IPA command failed "
			 "init_ibmOSAMib(): "
			 "Can't get MIB information for network interface %s\n"
			 "Cannot start subagent...exiting...\n", if_list[i].if_Name );
		break;

	      case IPA_NOT_SUPP:
		fprintf( stderr, "init_ibmOSAMib(): "
			 "ioctl() failed - IPA command not supported "
			 "init_ibmOSAMib(): "
			 "Can't get MIB information for network interface %s\n"
			 "Cannot start subagent...exiting...\n", if_list[i].if_Name );
		break;

	      case IPA_NO_DATA:
		get_time( time_buf );
		snmp_log( LOG_ERR, "%s init_ibmOSAMib(): "
			  "ioctl() failed - valid IPA command, but no"
			  " SNMP data is available for interface %s\n"
			  "init_ibmOSAMib(): start subagent anyway\n",
			  time_buf, if_list[i].if_Name );
		close( sd );
		free( buffer );
		return;
		break;

	      case -ENOMEM: /* should not happen in the near future ;-) */
		fprintf( stderr, "init_ibmOSAMib(): "
			 "ioctl() failed - MIB data size > "
			 "constant MIB_AREA_LEN\n"
			 "init_ibmOSAMib(): "
			 "Enlarge constant for MIB_AREA_LEN within "
			 "ibmOSAMibDefs.h and recompile the subagent\n"
			 "init_ibmOSAMib(): "
			 "Can't get MIB information for network interfaces\n"
			 "Cannot start subagent...exiting...\n" );
		break;
	      default:
		fprintf( stderr, "init_ibmOSAMib(): "
			 "ioctl() failed - reason %s\n"
			 "init_ibmOSAMib(): "
			 "Can't get MIB information for network interface %s\n"
			 "Cannot start subagent...exiting...\n",
			 strerror( error_code ), if_list[i].if_Name );
		break;
	      } /* end switch */

	      exit(1);
	    }
	  else if( ipa_reg_mib->ioctl_cmd.ipa_cmd_hdr.ret_code != 0 )
	    {
	      /* now check IPA SNMP subcommand return code */
	      switch ( ipa_reg_mib->ioctl_cmd.ipa_cmd_hdr.ret_code ) {

	      case IPA_SNMP_INV_TOPOID:
	      case IPA_SNMP_INV_GROUP:
	      case IPA_SNMP_INV_SUFFIX:
	      case IPA_SNMP_INV_INST:
	      case IPA_SNMP_OID_NREAD:
	      case IPA_SNMP_OID_NWRIT:
		get_time( time_buf );
		snmp_log( LOG_ERR, "%s init_ibmOSAMib(): "
			  "IPA SNMP subcommand failed\n"
                          "init_ibmOSAMib(): "
			  "IPA SNMP subcommand  return code 0x%x\n"
			  "init_ibmOSAMib(): "
			  "Can't get MIB information for network interface %s\n"
			  "Cannot start subagent...exiting...\n", time_buf,
			  ipa_reg_mib->ioctl_cmd.ipa_cmd_hdr.ret_code,
			  if_list[i].if_Name );
		break;

	      case IPA_SNMP_NOT_SUPP:
		get_time( time_buf );
		snmp_log( LOG_ERR, "%s init_ibmOSAMib(): "
			  "IPA SNMP subcommand failed - subcommand 0x%x "
			  "not supported\ninit_ibmOSAMib(): "
			  "Can't get MIB information for network interface %s\n"
			  "Cannot start subagent...exiting...\n", time_buf,
			  ipa_reg_mib->ioctl_cmd.ipa_cmd_hdr.request,
			  if_list[i].if_Name );
		break;

	      case IPA_SNMP_NO_DATA:
		get_time( time_buf );
		snmp_log( LOG_ERR, "%s init_ibmOSAMib(): "
			  "IPA SNMP subcommand failed - no data available\n"
			  "init_ibmOSAMib(): "
			  "Can't get MIB information for network interface %s\n"
			  "Cannot start subagent...exiting...\n", time_buf,
			  if_list[i].if_Name );
		break;

	      default:
		get_time( time_buf );
		snmp_log( LOG_ERR, "%s init_ibmOSAMib(): "
			  "IPA SNMP subcommand failed - undefined return code"
			  " 0x%x\ninit_ibmOSAMib(): "
			  "Can't get MIB information for network interface %s\n"
			  "Cannot start subagent...exiting...\n", time_buf,
			  ipa_reg_mib->ioctl_cmd.ipa_cmd_hdr.ret_code,
			  if_list[i].if_Name );
		break;

	      } /* end switch */

	      exit(1);

	    } /* end if */

          /* save microcode level */
	  if_list[i].ipa_ver = ipa_reg_mib->ioctl_cmd.ipa_cmd_hdr.ipa_ver;

	  /* register initial table information, that we got from IPAssists */
	  retc = register_tables ( buffer, oid_list_head );
	  if ( retc != 0 )
	    {
	      fprintf( stderr, "init_ibmOSAMib(): "
		       "register MIB data with subagent driving "
		       "code failed\ninit_ibmOSAMib(): for ifIndex %d ifDescr %s\n"
		       "check agent log file for more details\n"
		       "Cannot start subagent...exiting...\n",
		       if_list[i].ifIndex, if_list[i].if_Name );
	      exit(1);
	    } /* end if */
	} /* end if */

    } /* end for */

  /* log IPA microcode level per interface */
  for ( i=0; i < ifNumber; i++ )
    {
       if ( if_list[i].is_OSAEXP == TRUE )
	  snmp_log( LOG_INFO, "OSA-E microcode level is %x for interface %s\n",
	                      if_list[i].ipa_ver,
			      if_list[i].if_Name );
    } /* end for */

  /* free resources */
  close( sd );
  free( buffer );

} /* end init_ibmOSAMib */

/**********************************************************************
 * var_ibmOSAMib():
 *  This function is called every time the agent gets a request for
 *  any MIB data for the IBM OSA express MIB. It's up to this function
 *  to return the appropriate data back to the subagent driving code.
 *  This function supports all standard SNMIv2 data types.
 *  parameters:
 *  IN  variable vp       - entry in variableN array
 *  INOUT oid    *name    - OID from original request/OID being returned
 *  INOUT size_t *length  - length of orig. OID/length of ret. OID
 *  IN    int    exact    - exact/inexact request
 *  OUT   size_t *var_len - length of answer being returned
 *  OUT   WriteMethod **write_method - unused
 *  returns: NULL - vp entry does not match or instance wrong
 *                - something within ioctl handling failed
 *           else   data returned as answer
 *********************************************************************/
unsigned char* var_ibmOSAMib( struct variable *vp,
    	                         oid         *name,
    	                         size_t      *length,
    	                         int         exact,
    	                         size_t      *var_len,
    	                         WriteMethod **write_method)
{
  /* variables for returning data back to the subagent driving code */
  static long long_ret;
  static unsigned char octetstr_buf[MAX_GET_DATA];
  static oid objid[MAX_OID_LEN];
  static struct counter64 osa_counter64;
  long             *ptr_long;
  int              *ptr_int;
  unsigned char    *ptr_uchar;

  int  ifIndex;     /* IF-MIB ifIndex of the OSA device that is queried for data */
  int  offset;      /* offset to returned data portion within GET command area */
  char time_buf[TIME_BUF_SIZE]; /* date/time buffer */

  IPA_CMD_GET  *get_cmd;        /* area for GET command */
  IPA_GET_DATA *get_res;        /* pointer to offset where data portion starts */
  void         *tmp_ptr;

  /*
   * This function compares the full OID that is passed in to the registered
   * OIDs from this subagent.
   * It is the IBM OSA Express specific version of the default
   * header_simple_table() function, that is normally used in case of a simple
   * table. Place a mutual exlusion lock around this operation to avoid
   * interfering threads, when updating the internal MIB table thru thread
   * update_mib_info()
   */

  ifIndex = header_osa_table( vp, name, length, exact, var_len, write_method,
			      oid_list_head );

  if ( ifIndex == MATCH_FAILED )
    return NULL;

  /* issue ioctl to query Get/Getnext request data */
  offset = do_GET_ioctl ( ifIndex, name, *length, &get_cmd );
  if ( offset < 0 )
    {
      return NULL;
    }

  /*
   * return the result to subagent driving code
   */

  /* map data portion returned by IPAssists */
  /* # ptr GET command area + offset returned data portion */
  /* # align PTR to 4 byte bdy where data portion starts   */
  tmp_ptr = (char*) get_cmd;
  tmp_ptr += offset;
  get_res = (IPA_GET_DATA*) (PTR_ALIGN4( tmp_ptr ));

  switch( vp->type ) {

  case ASN_INTEGER: case ASN_COUNTER: case ASN_GAUGE: case ASN_TIMETICKS:
    /* ASN_UNSIGNED is same as ASN_GAUGE (RFC1902) */

    if ( get_res->len == sizeof(int) )
      {
	    ptr_int = (int*) get_res->data;
	    long_ret = (long) *ptr_int;
      }
    else
      {
	    ptr_long = (long*) get_res->data;
	    long_ret = (long) *ptr_long;
      } /* end if */

    free( get_cmd );

    return (unsigned char *) &long_ret;
    break;

  case ASN_COUNTER64:

    if ( get_res->len > 8 )
    {
      get_time( time_buf );
      snmp_log( LOG_ERR, "%s var_ibmOSAMib(): "
		"IPA data length for ASN_COUNTER64 > 8 bytes\n"
		"var_ibmOSAMib(): rejected Get/Getnext request\n", time_buf );
      free( get_cmd );
      return NULL;
    } /* end if */

    /* IPA returns 8 bytes for COUNTER64 */
    ptr_int = (int*) get_res->data;
    osa_counter64.high = (int) *ptr_int;
    ptr_int++;
    osa_counter64.low  = (int) *ptr_int;

    *var_len = sizeof( osa_counter64 );
    free( get_cmd );

    return (unsigned char *) &osa_counter64;
    break;

  case ASN_OPAQUE:    /* old v1 type/included for compatibility */
  case ASN_OCTET_STR: /* used for Binary data */
                      /* case Display String is handled within var_DisplayStr() */

    if ( get_res->len > MAX_GET_DATA )
    {
      get_time( time_buf );
      snmp_log( LOG_ERR, "%s var_ibmOSAMib(): "
		"IPA data length %d  for ASN_OCTET_STR > "
		"MAX_GET_DATA (%d  bytes)\n"
		"var_ibmOSAMib(): rejected Get/Getnext request\n",
		time_buf, get_res->len, MAX_GET_DATA );
      free( get_cmd );
      return NULL;
    } /* end if */

    *var_len = get_res->len;
    ptr_uchar = (unsigned char*) get_res->data;
    memcpy( octetstr_buf, ptr_uchar, *var_len );
    free( get_cmd );

    return (unsigned char *) octetstr_buf;
    break;

  case ASN_IPADDRESS:

    /* IPA IpAddress within 4 bytes hex data */
    ptr_int = (int*) get_res->data;
    long_ret = (long) *ptr_int;
    free( get_cmd );

    return (unsigned char *) &long_ret;
    break;

  case ASN_OBJECT_ID:

    /* IPA returned ObjectId as character string, have to convert... */
    *var_len = str_to_oid_conv ( get_res->data, objid );
    if ( *var_len == 0 )
    {
      get_time( time_buf );
      snmp_log( LOG_ERR, "%s var_ibmOSAMib(): IPA returned bad ObjectId - "
		"cannot convert net-snmp oid type\n"
		"var_ibmOSAMib(): rejected Get/Getnext request\n", time_buf );
      free( get_cmd );
      return NULL;
    } /* end if */

    *var_len = (*var_len) * sizeof( oid );
    free( get_cmd );

    return (unsigned char *) &objid;
    break;

  default:
    get_time( time_buf );
    snmp_log( LOG_ERR, "%s var_ibmOSAMib(): "
	      "got a not known ASN data type %x\n"
	      "var_ibmOSAMib(): "
	      "rejected Get/Getnext request\n", time_buf, vp->type );

  } /* end switch */

  free( get_cmd );

  return NULL;

} /* end var_ibmOSAMib */

/**********************************************************************
 * var_DisplayStr():
 *  This function handles the special case for Display Strings, which are
 *  a textual convention to Octet Strings. The binary data case for
 *  Octet Strings is handled within var_ibmOSAMib().
 *  It's up to this function to return the appropriate data back to the
 *  subagent driving code.
 *  parameters:
 *  IN  variable vp       - entry in variableN array
 *  INOUT oid    *name    - OID from original request/OID being returned
 *  INOUT size_t *length  - length of orig. OID/length of ret. OID
 *  IN    int    exact    - exact/inexact request
 *  OUT   size_t *var_len - length of answer being returned
 *  OUT   WriteMethod **write_method - unused
 *  returns: NULL - vp entry does not match or instance wrong
 *                - something within ioctl handling failed
 *           else   data returned as answer
 *********************************************************************/
unsigned char* var_DisplayStr( struct variable *vp,
    	                       oid         *name,
    	                       size_t      *length,
    	                       int         exact,
    	                       size_t      *var_len,
    	                       WriteMethod **write_method)
{
  /* variables for returning a display string to the subagent driving code */
  static char string[SPRINT_MAX_LEN];
  char                 time_buf[TIME_BUF_SIZE]; /* date/time buffer */

  int  ifIndex;     /* IF-MIB ifIndex of the OSA device that is queried for data */
  int  offset;      /* offset to returned data portion within GET command area */

  IPA_CMD_GET  *get_cmd;        /* area for GET command */
  IPA_GET_DATA *get_res;        /* pointer to offset where data portion starts */
  void         *tmp_ptr;

  /*
   * This function compares the full OID that is passed in to the registered
   * OIDs from this subagent.
   * It is the IBM OSA Express specific version of the default
   * header_simple_table() function, that is normally used in case of a simple
   * table. Place a mutual exlusion lock around this operation to avoid
   * interfering threads, when updating the internal MIB table thru thread
   * update_mib_info()
   */

  ifIndex = header_osa_table( vp, name, length, exact, var_len, write_method,
			      oid_list_head );

  if ( ifIndex == MATCH_FAILED )
    return NULL;

  /* issue ioctl to query Get/Getnext request data */
  offset = do_GET_ioctl ( ifIndex, name, *length, &get_cmd );
  if ( offset < 0 )
    {
      return NULL;
    }

  /*
   * return the result to subagent driving code
   */

  /* map data portion returned by IPAssists */
  /* # ptr GET command area + offset returned data portion */
  /* # align PTR to 4 byte bdy where data portion starts   */
  tmp_ptr = (char*) get_cmd;
  tmp_ptr += offset;
  get_res = (IPA_GET_DATA*) (PTR_ALIGN4( tmp_ptr ));

  if ( vp->type == ASN_OCTET_STR)
    {
      if ( get_res->len >= SPRINT_MAX_LEN )
	{
	  get_time( time_buf );
	  snmp_log( LOG_ERR, "%s var_DisplayStr(): "
		    "IPA data length %d  for Display "
		    "String >= SPRINT_MAX_LEN (%d  bytes)\n"
		    "var_ibmOSAMib(): rejected Get/Getnext request\n"
		    ,time_buf, get_res->len, SPRINT_MAX_LEN );
	  free( get_cmd );
	  return NULL;
	} /* end if */

      strncpy( string, get_res->data, get_res->len );
      string[ get_res->len ] = '\0';
      *var_len = strlen( string );
      free( get_cmd );

      return (unsigned char *) string;
    }
  else
    {
      get_time( time_buf );
      snmp_log( LOG_ERR, "%s var_DisplayStr(): "
		"expected a Display String here, "
		"but got a different ASN data type: %x\n"
		"var_DisplayStr(): "
		"rejected Get/Getnext request\n", time_buf, vp->type );
    } /* end if */

  free( get_cmd );

  return NULL;

} /* end var_DisplayStr */

/**********************************************************************
 * do_GET_ioctl()
 *  This function handles the communication with an OSA Express Card
 *  to query the appropriate MIB information from IPAssists.
 *  An ioctl is used in order to qet the appropriate information.
 *  parameters:
 *  IN    int ifIndex       - IF-MIB interface index
 *  IN    oid    *name      - OID being returned
 *  IN    size_t len        - length of ret. OID
 *  INOUT IPA_CMD_GET** cmd - GET command area
 *  returns:  cmd_len - return offset to returned data
 *           -1 -  ioctl() was not successful
 *********************************************************************/
int do_GET_ioctl ( int ifIndex, oid *name, size_t len, IPA_CMD_GET **cmd )
{
  int  sd;                                   /* socket descriptor */
  int  i, error_code;
  char oid_str[MAX_OID_STR_LEN];             /* may hold an OID as string */
  char time_buf[TIME_BUF_SIZE];              /* date/time buffer */
  char device[IFNAME_MAXLEN] = "not_found";  /* device name for ioctl */
  struct ifreq ifr;                          /* request structure for ioctl */

  /* search device name in in global interface list for ifIndex */
  for ( i=0; i < ifNumber; i++ )
    {
      if ( if_list[i].ifIndex == ifIndex )
	{
	  strcpy( device, if_list[i].if_Name );
	  break;
	}
    } /* end for */

  if ( strcmp( device, "not_found" ) == 0 )
    {
      get_time( time_buf );
      snmp_log( LOG_ERR, "%s do_GET_ioctl(): "
		"ifIndex %d is not recorded in "
		"interface list\n"
		"OSA Subagent MIB information may be incomplete!\n"
		,time_buf, ifIndex );
      return -1;
    }

  /*
   * query IPAssists for data appropriate to the OID that we just validated
   */

  /* convert Get/GetNext OID to a string used by IPA */
  if( oid_to_str_conv ( name, len, oid_str ) == FALSE )
    {
      get_time( time_buf );
      snmp_log( LOG_ERR, "%s do_GET_ioctl(): "
		"cannot convert OID to string object\n"
		"do_GET_ioctl(): rejected request\n", time_buf );
      return -1;
    }

  /* allocate memory for Get/GetNext command area */
  *cmd = ( IPA_CMD_GET* ) malloc( GET_AREA_LEN );
  if ( *cmd == NULL )
    {
      get_time( time_buf );
      snmp_log( LOG_ERR,
		"%s do_GET_ioctl(): "
		"malloc() for GET command area failed\n"
		"do_GET_ioctl(): rejected request for .%s\n",
		time_buf, oid_str );
      return -1;
    } /* end if */

  /* set up input parameters in Get/GetNext command area */
  /* size of IPA data area */
  (*cmd)->ioctl_cmd.data_len =
          GET_AREA_LEN - offsetof( IOCTL_CMD_HDR, ipa_cmd_hdr );

  /* size of IPA GET subcommand padded to 4-byte bdy */
  (*cmd)->ioctl_cmd.req_len =
    (sizeof((*cmd)->ioctl_cmd) + strlen( oid_str ) + 1 + 3)&(~3);

  /* set up input parameters in Get/GetNext command area */
  (*cmd)->ioctl_cmd.ipa_cmd_hdr.request  = IPA_GET_OID;  /* IPA subcommand code   */
  (*cmd)->ioctl_cmd.ipa_cmd_hdr.ifIndex  = ifIndex;      /* assign IF-MIB ifIndex */
  (*cmd)->ioctl_cmd.ipa_cmd_hdr.ret_code = 0;
  (*cmd)->ioctl_cmd.ipa_cmd_hdr.seq_num  = 0;            /* sequence# is not used */
  strcpy( (*cmd)->full_oid, oid_str );                   /* requested OID         */
                                                         /* (fully qualified)     */

  /*
   *  issue Get/GetNext command against IPAssists
   */

  /* create socket for ioctl */
  sd = socket( AF_INET, SOCK_STREAM, 0 );
  if ( sd < 0 )
    {
      error_code = errno;
      get_time( time_buf );
      snmp_log(LOG_ERR, "%s do_GET_ioctl(): "
	       "error opening socket() - reason %s\n"
	       "do_GET_ioctl(): rejected request for .%s\n",
	       time_buf, strerror( error_code ), oid_str );
      free( *cmd );
      return -1;
    } /* end if */

  /* do ioctl */
  strcpy( ifr.ifr_name, device );
  ifr.ifr_ifru.ifru_data = (char*) (*cmd);
  if ( ioctl( sd, SIOC_QETH_ADP_SET_SNMP_CONTROL, &ifr ) < 0 )
    {
      error_code = errno;
      get_time( time_buf );

      /* see if we got a common I/O error */
      if ( error_code == -EIO )
        {
           snmp_log( LOG_ERR, "%s do_GET_ioctl(): "
		     "ioctl() failed - reason %s\n"
                     "do_GET_ioctl(): rejected request for .%s\n",
                     time_buf, strerror( error_code ), oid_str );
           close( sd );
           free( *cmd );
           return -1;
        } /* end if */

      /* let's see, if we got a return code from IPAssists */
      /* or if MIB buffer is exhausted */
      switch ( (*cmd)->ioctl_cmd.ipa_cmd_hdr.ret_code ) {

      case IPA_FAILED:
	snmp_log( LOG_ERR, "%s do_GET_ioctl(): "
		  "ioctl() failed - IPA command failed\n"
		  "do_GET_ioctl(): rejected request for .%s\n",
		  time_buf, oid_str );
	break;

      case IPA_NOT_SUPP:
	snmp_log( LOG_ERR, "%s do_GET_ioctl(): "
		  "ioctl() failed - IPA command not supported\n"
		  "do_GET_ioctl(): rejected request for .%s\n",
		  time_buf,  oid_str );
	break;

      case IPA_NO_DATA:
	snmp_log( LOG_ERR, "%s do_GET_ioctl(): "
		  "ioctl() failed - valid IPA command, but no "
		  "SNMP data is available\n"
		  "do_GET_ioctl(): rejected request for .%s\n",
		  time_buf, oid_str );
	break;

      case -ENOMEM:
        snmp_log( LOG_ERR, "%s do_GET_ioctl(): "
		  "ioctl() failed - response data > "
		  "constant MAX_GET_DATA %d\n"
	          "do_GET_ioctl(): rejected request for .%s\n",
	          time_buf, MAX_GET_DATA, oid_str );
	break;

      default:
	snmp_log(LOG_ERR, "%s do_GET_ioctl(): "
		 "ioctl() failed - reason %s\n"
		 "do_GET_ioctl(): rejected request for .%s\n",
		 time_buf, strerror( error_code ), oid_str );
	break;
      } /* end switch */

      close( sd );
      free( *cmd );
      return -1;

    } /* end if */

  /* close socket */
  close( sd );

  /* now check IPA SNMP subcommand return code */
  switch ( (*cmd)->ioctl_cmd.ipa_cmd_hdr.ret_code ) {

  case IPA_SNMP_SUCCESS:
    /* return offset to data portion */
    return ( sizeof( IPA_CMD_GET ) + strlen( oid_str ) + 1 );
    break;

  case IPA_SNMP_INV_TOPOID:
  case IPA_SNMP_INV_GROUP:
  case IPA_SNMP_INV_SUFFIX:
  case IPA_SNMP_INV_INST:
  case IPA_SNMP_OID_NREAD:
  case IPA_SNMP_OID_NWRIT:
    get_time( time_buf );
    snmp_log( LOG_ERR, "%s do_GET_ioctl(): "
	      "IPA SNMP subcommand failed - cannot handle OID\n"
              "do_GET_ioctl(): IPA SNMP subcommand return code 0x%x\n"
              "do_GET_ioctl(): rejected request for .%s\n",
              time_buf, (*cmd)->ioctl_cmd.ipa_cmd_hdr.ret_code, oid_str );
    break;

  case IPA_SNMP_NOT_SUPP:
    get_time( time_buf );
    snmp_log( LOG_ERR, "%s do_GET_ioctl(): "
	      "IPA SNMP subcommand failed - subcommand 0x%x not supported\n"
	      "do_GET_ioctl(): rejected request for .%s\n",
	      time_buf, (*cmd)->ioctl_cmd.ipa_cmd_hdr.request, oid_str );
    break;

  case IPA_SNMP_NO_DATA:
    get_time( time_buf );
    snmp_log( LOG_ERR, "%s do_GET_ioctl(): "
	      "IPA SNMP subcommand failed - no data available\n"
	      "do_GET_ioctl(): rejected request for .%s\n",
	      time_buf, oid_str );
    break;

  default:
    get_time( time_buf );
    snmp_log( LOG_ERR, "%s do_GET_ioctl(): "
	      "IPA SNMP subcommand failed - undefined return code 0x%x\n"
	      "do_GET_ioctl(): rejected request for .%s\n",
	      time_buf, (*cmd)->ioctl_cmd.ipa_cmd_hdr.ret_code, oid_str );
    break;

  } /* end switch */

  /* return error */
  free( *cmd );
  return -1;

} /* end do_GET_ioctl */

/**********************************************************************
 * write_ibmOSAMib():
 *  !!! Set processing is not supported in version 1.0.0 !!!
 *  !!! Function is defind as a skeleton for later use   !!!
 *  This function handles any SET requests raised against the
 *  ibmOSAMib.
 *  The flow of actions is to preserve proper transaction handling
 *  with other transactions in the same set request.
 *  parameters:
 *  IN    int    action       - current action state
 *  IN    u_char *var_val     - new variable value
 *  IN    u_char var_val_type - data type of above variable
 *  IN    size_t var_val_len  - length of variable value
 *  IN    u_char *statP       - value that a GET request would return
 *                              for this variable
 *  IN    oid    *name        - OID to be set
 *  IN    size_t name_len     - len of OID to be set
 *  returns: SNMP_ERR_WRONGTYPE  - wrong data type passed in
 *           SNMP_ERR_GENERR     - general error occurred
 *           SNMP_ERR_UNDOFAILED - undo operation failed
 *           SNMP_ERR_NOERROR    - variable set successful
 *********************************************************************/
int write_ibmOSAMib( int      action,
                        u_char   *UNUSED(var_val),
                        u_char   UNUSED(var_val_type),
                        size_t   UNUSED(var_val_len),
                        u_char   *UNUSED(statP),
                        oid      *UNUSED(name),
                        size_t   UNUSED(name_len) )
{
/*  static unsigned char string[SPRINT_MAX_LEN]; */
/*  int size; */

  switch ( action ) {
        case RESERVE1:
          /* check to see that everything is possible */
          break;

        case RESERVE2:
          /* allocate needed memory here */
          break;

        case FREE:
          /* Release any resources that have been allocated */
          break;

        case ACTION:
          /* Actually make the change requested. Note that anything done
             here must be reversible in the UNDO case */
          break;

        case UNDO:
          /* Back out any changes made in the ACTION case */
          break;

        case COMMIT:
          /* Things are working well, so it's now safe to make the change
             permanently.  Make sure that anything done here can't fail! */
          break;
  }
  return SNMP_ERR_NOERROR;
} /* end write_ibmOSAMib */


text:
#include <chaos/task_service/task_service_group.h>

/*!
 *  @file           task_service_group.h
 *  @author         yunjie.lu
 *  @email          lyjdamzwf@gmail.com
 *  @weibo          http://weibo.com/crazyprogramerlyj
 *  @date           2012.4.15
 *  @brief          task service group
 *  @last changed
 *
 */

namespace chaos
{

namespace task_service
{

task_service_group_t::task_service_group_t(const string& service_name_)
    :
        m_started(false),
        m_service_name(service_name_)
{
}

task_service_group_t::~task_service_group_t()
{
    stop();

    for (uint32_t i = 0; i < m_removed_service_group.size(); ++i)
    {
        task_service_t*& task_service_ptr = m_removed_service_group[i];
        SAFE_DELETE(task_service_ptr);
    }
}

task_service_t* task_service_group_t::new_service()
{
    return new task_service_t(m_service_name);
}

int task_service_group_t::start(
                                int task_service_num_,
                                int thread_num_per_service_
                               )
{
    LOGTRACE((TASK_SERVICE_MODULE, "task_service_group_t::start args-[task_service_num:%d, thread_num_per_service:%d] begin", task_service_num_, thread_num_per_service_));

    if (m_started)
    {
            LOGWARN((TASK_SERVICE_MODULE, "task_service_group_t::start task service has started, return."));
            return 0;
    }

    for (int i = 0; i < task_service_num_; ++i)
    {
        task_service_t* task_service_ptr = new_service();
        if (NULL == task_service_ptr)
        {
            LOGWARN((TASK_SERVICE_MODULE, "task_service_group_t::start new task_service_t failed, return."));
            return -1;
        }

        if (-1 == task_service_ptr->start(thread_num_per_service_))
        {
            LOGWARN((TASK_SERVICE_MODULE, "task_service_group_t::start task_service start failed, return."));

            for (task_service_container_t::iterator it = m_task_service_group.begin();
                 it != m_task_service_group.end();
                 ++it
                )
            {
                (*it)->stop();
                SAFE_DELETE(*it);
            }

            m_task_service_group.clear();

            return -1;
        }

        m_task_service_group.push_back(task_service_ptr);
    }

    m_started = true;

    LOGTRACE((TASK_SERVICE_MODULE, "task_service_group_t::start args-[task_service_num:%d, thread_num_per_service:%d] end", task_service_num_, thread_num_per_service_));
    return 0;
}

int task_service_group_t::stop()
{
    LOGTRACE((TASK_SERVICE_MODULE, "task_service_group_t::stop begin"));

    if (!m_started)
    {
        LOGWARN((TASK_SERVICE_MODULE, "task_service_group_t::stop task service has stopped, return."));
        return 0;
    }

    for (uint32_t i = 0; i < m_task_service_group.size(); ++i)
    {
        task_service_t*& task_service_ptr = m_task_service_group[i];
        if (NULL == task_service_ptr)
        {
            LOGWARN((TASK_SERVICE_MODULE, "task_service_group_t::stop task service is NULL"));
            continue;
        }

        if (-1 == task_service_ptr->stop())
        {
            LOGWARN((TASK_SERVICE_MODULE, "task_service_group_t::stop task_service stop failed."));
        }

        //! yunjie: 将service ptr放到移除容器中
        //          真正的delete将会在析构时进行, 是
        //          为了防止stop之后业务层还继续post
        //          消息造成崩溃
        m_removed_service_group.push_back(task_service_ptr);
    }

    m_task_service_group.clear();
    m_started = false;

    LOGTRACE((TASK_SERVICE_MODULE, "task_service_group_t::stop end"));
    return 0;
}

task_service_t* task_service_group_t::operator[](uint32_t index_)
{
    if (index_ >= m_task_service_group.size())
    {
        return NULL;
    }
    else
    {
        return m_task_service_group[index_];
    }
}

}

}


text:
layout: page
title: Home
---

SpringyRecords is a framework to generate Data Access Classes based on a database schema. It can be used out of the box or it can be extended to generate the code according to your preferences.

## Goals of the project:

- Generate boilerplate code to interact with an existing Database.

- Take advantage of the infrastructure already avaiable in spring-jdbc.

- Make it light, simple and flexible.

- It is a light ORM or a micro ORM.

## How is it compares with an ORM.

It is lighter than a traditional ORM. It maps records and tables not domain objects. This approach is better if you are dealing with a legacy relational database that may not be perfectly designed. It doesn't attempt to map complex structures.

Other benefits:

 * It is lighter. The initialization time is very small, even for databases with many tables.

 * You handcraft your database access code. Furthermore, your code is reusable and it is organized by table.

 * It is very flexible and highly customizable.


text:
module TokyoMetro::Factory::Generate::Api::TrainTimetable
end


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

<title>ParticleControllerComponent (libgdx API)</title>
<meta name="date" content="2016-02-02">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

				libgdx API

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.badlogic.gdx.graphics.g3d.particles

Class ParticleControllerComponent

java.lang.Object

com.badlogic.gdx.graphics.g3d.particles.ParticleControllerComponent

All Implemented Interfaces:

ResourceData.Configurable, Disposable, Json.Serializable

Direct Known Subclasses:

Emitter, Influencer, ParticleControllerRenderer

public abstract class ParticleControllerComponent
extends java.lang.Object
implements Disposable, Json.Serializable, ResourceData.Configurable

It's the base class of every ParticleController component.
 A component duty is to participate in one or some events during the simulation.
 (i.e it can handle the particles emission or modify particle properties, etc.).

Author:

inferno

Field Summary

Fields

Modifier and Type
Field and Description

protected ParticleController
controller

protected static Matrix3
TMP_M3

protected static Matrix4
TMP_M4

protected static Quaternion
TMP_Q

protected static Quaternion
TMP_Q2

protected static Vector3
TMP_V1

protected static Vector3
TMP_V2

protected static Vector3
TMP_V3

protected static Vector3
TMP_V4

protected static Vector3
TMP_V5

protected static Vector3
TMP_V6

Constructor Summary

Constructors

Constructor and Description

ParticleControllerComponent()

Method Summary

All Methods Instance Methods Abstract Methods Concrete Methods

Modifier and Type
Method and Description

void
activateParticles(int startIndex,
                 int count)

Called to initialize new emitted particles.

void
allocateChannels()

Called during initialization to allocate additional particles channels

abstract ParticleControllerComponent
copy()

void
dispose()

Releases all resources of this object.

void
end()

Called at the end of the simulation.

void
init()

Called once during intialization

void
killParticles(int startIndex,
             int count)

Called to notify which particles have been killed.

void
load(AssetManager manager,
    ResourceData data)

void
read(Json json,
    JsonValue jsonData)

void
save(AssetManager manager,
    ResourceData data)

void
set(ParticleController particleController)

void
start()

Called at the start of the simulation.

void
update()

Called to execute the component behavior.

void
write(Json json)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

TMP_V1

protected static final Vector3 TMP_V1

TMP_V2

protected static final Vector3 TMP_V2

TMP_V3

protected static final Vector3 TMP_V3

TMP_V4

protected static final Vector3 TMP_V4

TMP_V5

protected static final Vector3 TMP_V5

TMP_V6

protected static final Vector3 TMP_V6

TMP_Q

protected static final Quaternion TMP_Q

TMP_Q2

protected static final Quaternion TMP_Q2

TMP_M3

protected static final Matrix3 TMP_M3

TMP_M4

protected static final Matrix4 TMP_M4

controller

protected ParticleController controller

Constructor Detail

ParticleControllerComponent

public ParticleControllerComponent()

Method Detail

activateParticles

public void activateParticles(int startIndex,
                              int count)

Called to initialize new emitted particles.

killParticles

public void killParticles(int startIndex,
                          int count)

Called to notify which particles have been killed.

update

public void update()

Called to execute the component behavior.

init

public void init()

Called once during intialization

start

public void start()

Called at the start of the simulation.

end

public void end()

Called at the end of the simulation.

dispose

public void dispose()

Description copied from interface: Disposable

Releases all resources of this object.

Specified by:

dispose in interface Disposable

copy

public abstract ParticleControllerComponent copy()

allocateChannels

public void allocateChannels()

Called during initialization to allocate additional particles channels

set

public void set(ParticleController particleController)

save

public void save(AssetManager manager,
                 ResourceData data)

Specified by:

save in interface ResourceData.Configurable

load

public void load(AssetManager manager,
                 ResourceData data)

Specified by:

load in interface ResourceData.Configurable

write

public void write(Json json)

Specified by:

write in interface Json.Serializable

read

public void read(Json json,
                 JsonValue jsonData)

Specified by:

read in interface Json.Serializable

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

libgdx API

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

				Copyright © 2010-2013 Mario Zechner (contact@badlogicgames.com), Nathan Sweet (admin@esotericsoftware.com)


text:
/* global browser */
//jshint esnext:true

var config = {
    // Extension name
    name: 'WakaTime',
    // Extension version
    version: browser.runtime.getManifest().version,
    // Time for idle state of the browser
    // The user is considered idle if there was
    // no activity in the browser for x seconds
    detectionIntervalInSeconds: 60,
    // Default logging style
    // Log all except blacklisted sites
    // or log only the white listed sites.
    loggingStyle: 'blacklist',
    // Default logging type
    loggingType: 'domain',
    // By default logging is enabled
    loggingEnabled: true,
    // Url to which to send the heartbeat
    heartbeatApiUrl: 'https://wakatime.com/api/v1/users/current/heartbeats',
    // Url from which to detect if the user is logged in
    currentUserApiUrl: 'https://wakatime.com/api/v1/users/current',
    // The url to logout the user from wakatime
    logoutUserUrl: 'https://wakatime.com/logout',
    // Gets stats from the WakaTime API
    summariesApiUrl: 'https://wakatime.com/api/v1/users/current/summaries',
    // Different colors for different states of the extension
    colors: {
        allGood: '',
        notLogging: 'gray',
        notSignedIn: 'red',
        lightTheme: 'white'
    },
    // Tooltips for each of the extension states
    tooltips: {
        allGood: '',
        notLogging: 'Not logging',
        notSignedIn: 'Not signed In',
        blacklisted: 'This URL is blacklisted',
        whitelisted: 'This URL is not on your whitelist'
    },
    // Default theme
    theme: 'light',
    // Valid extension states
    states: [
        'allGood',
        'notLogging',
        'notSignedIn',
        'blacklisted',
        'whitelisted'
    ],
    // Predefined alert type and text for success and failure.
    alert: {
        success: {
            type: 'success',
            text: 'Options have been saved!'
        },
        failure: {
            type: 'danger',
            text: 'There was an error while saving the options!'
        }
    }
};

module.exports = config;


text:
package org.apache.phoenix.end2end;

import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.regionserver.HRegion;
import org.apache.hadoop.hbase.regionserver.RegionScanner;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.mapreduce.Job;
import org.apache.phoenix.jdbc.PhoenixConnection;
import org.apache.phoenix.mapreduce.index.IndexTool;
import org.apache.phoenix.query.ConnectionQueryServices;
import org.apache.phoenix.mapreduce.index.PhoenixIndexImportDirectMapper;
import org.apache.phoenix.mapreduce.index.PhoenixIndexImportMapper;
import org.apache.phoenix.mapreduce.index.PhoenixServerBuildIndexMapper;

import org.apache.phoenix.query.QueryServices;
import org.apache.phoenix.query.QueryServicesOptions;
import org.apache.phoenix.schema.PTable;
import org.apache.phoenix.transaction.PhoenixTransactionProvider.Feature;
import org.apache.phoenix.transaction.TransactionFactory;
import org.apache.phoenix.util.PhoenixRuntime;
import org.apache.phoenix.util.PropertiesUtil;
import org.apache.phoenix.util.QueryUtil;
import org.apache.phoenix.util.ReadOnlyProps;
import org.apache.phoenix.util.SchemaUtil;
import org.apache.phoenix.util.TestUtil;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

@RunWith(Parameterized.class)
public class IndexToolIT extends BaseUniqueNamesOwnClusterIT {

    private final boolean localIndex;
    private final boolean mutable;
    private final boolean transactional;
    private final boolean directApi;
    private final String tableDDLOptions;
    private final boolean useSnapshot;
    private final boolean useTenantId;

    public IndexToolIT(String transactionProvider, boolean mutable, boolean localIndex,
            boolean directApi, boolean useSnapshot, boolean useTenantId) {
        this.localIndex = localIndex;
        this.mutable = mutable;
        this.transactional = transactionProvider != null;
        this.directApi = directApi;
        this.useSnapshot = useSnapshot;
        this.useTenantId = useTenantId;
        StringBuilder optionBuilder = new StringBuilder();
        if (!mutable) {
            optionBuilder.append(" IMMUTABLE_ROWS=true ");
        }
        if (transactional) {
            if (!(optionBuilder.length() == 0)) {
                optionBuilder.append(",");
            }
            optionBuilder.append(" TRANSACTIONAL=true,TRANSACTION_PROVIDER='" + transactionProvider + "'");
        }
        optionBuilder.append(" SPLIT ON(1,2)");
        this.tableDDLOptions = optionBuilder.toString();
    }

    @BeforeClass
    public static void setup() throws Exception {
        Map<String, String> serverProps = Maps.newHashMapWithExpectedSize(2);
        serverProps.put(QueryServices.STATS_GUIDEPOST_WIDTH_BYTES_ATTRIB, Long.toString(20));
        serverProps.put(QueryServices.MAX_SERVER_METADATA_CACHE_TIME_TO_LIVE_MS_ATTRIB, Long.toString(5));
        serverProps.put(QueryServices.EXTRA_JDBC_ARGUMENTS_ATTRIB,
            QueryServicesOptions.DEFAULT_EXTRA_JDBC_ARGUMENTS);
        Map<String, String> clientProps = Maps.newHashMapWithExpectedSize(2);
        clientProps.put(QueryServices.USE_STATS_FOR_PARALLELIZATION, Boolean.toString(true));
        clientProps.put(QueryServices.STATS_UPDATE_FREQ_MS_ATTRIB, Long.toString(5));
        clientProps.put(QueryServices.TRANSACTIONS_ENABLED, Boolean.TRUE.toString());
        clientProps.put(QueryServices.FORCE_ROW_KEY_ORDER_ATTRIB, Boolean.TRUE.toString());
        setUpTestDriver(new ReadOnlyProps(serverProps.entrySet().iterator()),
            new ReadOnlyProps(clientProps.entrySet().iterator()));
    }

    @Parameters(
            name = "transactionProvider={0},mutable={1},localIndex={2},directApi={3},useSnapshot={4}")
    public static Collection<Object[]> data() {
        List<Object[]> list = Lists.newArrayListWithExpectedSize(48);
        boolean[] Booleans = new boolean[] { false, true };
        for (String transactionProvider : new String[] {"TEPHRA", "OMID", null}) {
            for (boolean mutable : Booleans) {
                for (boolean localIndex : Booleans) {
                    if (!localIndex
                            || transactionProvider == null
                            || !TransactionFactory.getTransactionProvider(
                                    TransactionFactory.Provider.valueOf(transactionProvider))
                                .isUnsupported(Feature.ALLOW_LOCAL_INDEX)) {
                        if (localIndex) {
                            for (boolean directApi : Booleans) {
                                list.add(new Object[]{transactionProvider, mutable, localIndex,
                                        directApi, false, false});
                            }
                        }
                        else {
                            // Due to PHOENIX-5375 and PHOENIX-5376, the snapshot and bulk load options are ignored for global indexes
                            list.add(new Object[]{transactionProvider, mutable, localIndex,
                                    true, false, false});
                        }
                    }
                }
            }
        }
        // Add the usetenantId
        list.add(new Object[] { null, false, false, true, false, true});
        return TestUtil.filterTxParamData(list,0);
    }

    @Test
    public void testSecondaryIndex() throws Exception {
        String schemaName = generateUniqueName();
        String dataTableName = generateUniqueName();
        String dataTableFullName = SchemaUtil.getTableName(schemaName, dataTableName);
        String indexTableName = generateUniqueName();
        String indexTableFullName = SchemaUtil.getTableName(schemaName, indexTableName);
        Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
        Connection conn = DriverManager.getConnection(getUrl(), props);
        try {
            String stmString1 =
                    "CREATE TABLE " + dataTableFullName
                            + " (ID INTEGER NOT NULL PRIMARY KEY, NAME VARCHAR, ZIP INTEGER) "
                            + tableDDLOptions;
            conn.createStatement().execute(stmString1);
            String upsertQuery = String.format("UPSERT INTO %s VALUES(?, ?, ?)", dataTableFullName);
            PreparedStatement stmt1 = conn.prepareStatement(upsertQuery);

            // insert two rows
            upsertRow(stmt1, 1);
            upsertRow(stmt1, 2);
            conn.commit();

            if (transactional) {
                // insert two rows in another connection without committing so that they are not
                // visible to other transactions
                try (Connection conn2 = DriverManager.getConnection(getUrl(), props)) {
                    conn2.setAutoCommit(false);
                    PreparedStatement stmt2 = conn2.prepareStatement(upsertQuery);
                    upsertRow(stmt2, 5);
                    upsertRow(stmt2, 6);
                    ResultSet rs =
                            conn.createStatement()
                                    .executeQuery("SELECT count(*) from " + dataTableFullName);
                    assertTrue(rs.next());
                    assertEquals("Unexpected row count ", 2, rs.getInt(1));
                    assertFalse(rs.next());
                    rs =
                            conn2.createStatement()
                                    .executeQuery("SELECT count(*) from " + dataTableFullName);
                    assertTrue(rs.next());
                    assertEquals("Unexpected row count ", 4, rs.getInt(1));
                    assertFalse(rs.next());
                }
            }

            String stmtString2 =
                    String.format(
                        "CREATE %s INDEX %s ON %s  (LPAD(UPPER(NAME, 'en_US'),8,'x')||'_xyz') ASYNC ",
                        (localIndex ? "LOCAL" : ""), indexTableName, dataTableFullName);
            conn.createStatement().execute(stmtString2);

            // verify rows are fetched from data table.
            String selectSql =
                    String.format(
                        "SELECT ID FROM %s WHERE LPAD(UPPER(NAME, 'en_US'),8,'x')||'_xyz' = 'xxUNAME2_xyz'",
                        dataTableFullName);
            ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + selectSql);
            String actualExplainPlan = QueryUtil.getExplainPlan(rs);

            // assert we are pulling from data table.
            assertEquals(String.format(
                "CLIENT PARALLEL 1-WAY FULL SCAN OVER %s\n"
                        + "    SERVER FILTER BY (LPAD(UPPER(NAME, 'en_US'), 8, 'x') || '_xyz') = 'xxUNAME2_xyz'",
                dataTableFullName), actualExplainPlan);

            rs = stmt1.executeQuery(selectSql);
            assertTrue(rs.next());
            assertEquals(2, rs.getInt(1));
            assertFalse(rs.next());
            conn.commit();

            // run the index MR job.
            runIndexTool(directApi, useSnapshot, schemaName, dataTableName, indexTableName);

            // insert two more rows
            upsertRow(stmt1, 3);
            upsertRow(stmt1, 4);
            conn.commit();

            // assert we are pulling from index table.
            rs = conn.createStatement().executeQuery("EXPLAIN " + selectSql);
            actualExplainPlan = QueryUtil.getExplainPlan(rs);
            assertExplainPlan(localIndex, actualExplainPlan, dataTableFullName, indexTableFullName);

            rs = conn.createStatement().executeQuery(selectSql);
            assertTrue(rs.next());
            assertEquals(2, rs.getInt(1));
            assertFalse(rs.next());
        } finally {
            conn.close();
        }
    }

    @Test
    public void testIndexToolWithTenantId() throws Exception {
        if (!useTenantId) { return;}
        String tenantId = generateUniqueName();
        String schemaName = generateUniqueName();
        String dataTableName = generateUniqueName();
        String viewTenantName = generateUniqueName();
        String indexNameGlobal = generateUniqueName();
        String indexNameTenant = generateUniqueName();
        String viewIndexTableName = "_IDX_" + dataTableName;

        Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
        Connection connGlobal = DriverManager.getConnection(getUrl(), props);
        props.setProperty(PhoenixRuntime.TENANT_ID_ATTRIB, tenantId);
        Connection connTenant = DriverManager.getConnection(getUrl(), props);
        String createTblStr = "CREATE TABLE %s (TENANT_ID VARCHAR(15) NOT NULL,ID INTEGER NOT NULL"
                + ", NAME VARCHAR, CONSTRAINT PK_1 PRIMARY KEY (TENANT_ID, ID)) MULTI_TENANT=true";
        String createViewStr = "CREATE VIEW %s AS SELECT * FROM %s";

        String upsertQueryStr = "UPSERT INTO %s (TENANT_ID, ID, NAME) VALUES('%s' , %d, '%s')";
        String createIndexStr = "CREATE INDEX %s ON %s (NAME) ";

        try {
            String tableStmtGlobal = String.format(createTblStr, dataTableName);
            connGlobal.createStatement().execute(tableStmtGlobal);

            String viewStmtTenant = String.format(createViewStr, viewTenantName, dataTableName);
            connTenant.createStatement().execute(viewStmtTenant);

            String idxStmtTenant = String.format(createIndexStr, indexNameTenant, viewTenantName);
            connTenant.createStatement().execute(idxStmtTenant);

            connTenant.createStatement()
                    .execute(String.format(upsertQueryStr, viewTenantName, tenantId, 1, "x"));
            connTenant.commit();

            runIndexTool(true, false, "", viewTenantName, indexNameTenant,
                    tenantId, 0, new String[0]);

            String selectSql = String.format("SELECT ID FROM %s WHERE NAME='x'", viewTenantName);
            ResultSet rs = connTenant.createStatement().executeQuery("EXPLAIN " + selectSql);
            String actualExplainPlan = QueryUtil.getExplainPlan(rs);
            assertExplainPlan(false, actualExplainPlan, "", viewIndexTableName);
            rs = connTenant.createStatement().executeQuery(selectSql);
            assertTrue(rs.next());
            assertEquals(1, rs.getInt(1));
            assertFalse(rs.next());

            // Remove from tenant view index and build.
            ConnectionQueryServices queryServices = connGlobal.unwrap(PhoenixConnection.class).getQueryServices();
            Admin admin = queryServices.getAdmin();
            TableName tableName = TableName.valueOf(viewIndexTableName);
            admin.disableTable(tableName);
            admin.truncateTable(tableName, false);

            runIndexTool(true, false, "", viewTenantName, indexNameTenant,
                    tenantId, 0, new String[0]);

            Table htable= queryServices.getTable(Bytes.toBytes(viewIndexTableName));
            int count = getUtility().countRows(htable);
            // Confirm index has rows
            assertTrue(count == 1);

            selectSql = String.format("SELECT /*+ INDEX(%s) */ COUNT(*) FROM %s",
                    indexNameTenant, viewTenantName);
            rs = connTenant.createStatement().executeQuery(selectSql);
            assertTrue(rs.next());
            assertEquals(1, rs.getInt(1));
            assertFalse(rs.next());

            String idxStmtGlobal =
                    String.format(createIndexStr, indexNameGlobal, dataTableName);
            connGlobal.createStatement().execute(idxStmtGlobal);

            // run the index MR job this time with tenant id.
            // We expect it to return -1 because indexTable is not correct for this tenant.
            runIndexTool(true, false, schemaName, dataTableName, indexNameGlobal,
                    tenantId, -1, new String[0]);

        } finally {
            connGlobal.close();
            connTenant.close();
        }
    }

    @Test
    public void testSaltedVariableLengthPK() throws Exception {
        if (!mutable) return;
        if (transactional) return;
        String schemaName = generateUniqueName();
        String dataTableName = generateUniqueName();
        String dataTableFullName = SchemaUtil.getTableName(schemaName, dataTableName);
        String indexTableName = generateUniqueName();
        try (Connection conn =
                DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TEST_PROPERTIES))) {
            String dataDDL =
                    "CREATE TABLE " + dataTableFullName + "(\n"
                            + "ID VARCHAR NOT NULL PRIMARY KEY,\n"
                            + "\"info\".CAR_NUM VARCHAR(18) NULL,\n"
                            + "\"info\".CAP_DATE VARCHAR NULL,\n" + "\"info\".ORG_ID BIGINT NULL,\n"
                            + "\"info\".ORG_NAME VARCHAR(255) NULL\n" + ") SALT_BUCKETS=3";
            conn.createStatement().execute(dataDDL);

            String upsert =
                    "UPSERT INTO " + dataTableFullName
                            + "(ID,CAR_NUM,CAP_DATE,ORG_ID,ORG_NAME) VALUES('1','car1','2016-01-01 00:00:00',11,'orgname1')";
            conn.createStatement().execute(upsert);
            conn.commit();

            String indexDDL =
                    String.format(
                        "CREATE %s INDEX %s on %s (\"info\".CAR_NUM,\"info\".CAP_DATE) ASYNC",
                        (localIndex ? "LOCAL" : ""), indexTableName, dataTableFullName);
            conn.createStatement().execute(indexDDL);

            runIndexTool(directApi, useSnapshot, schemaName, dataTableName, indexTableName);

            ResultSet rs =
                    conn.createStatement().executeQuery(
                        "SELECT ORG_ID,CAP_DATE,CAR_NUM,ORG_NAME FROM " + dataTableFullName
                                + " WHERE CAR_NUM='car1' AND CAP_DATE>='2016-01-01' AND CAP_DATE<='2016-05-02' LIMIT 10");
            assertTrue(rs.next());
            int orgId = rs.getInt(1);
            assertEquals(11, orgId);
        }
    }

    /**
     * Test presplitting an index table
     */
    @Test
    public void testSplitIndex() throws Exception {
        if (localIndex) return; // can't split local indexes
        if (!mutable) return;
        if (transactional) return;
        String schemaName = generateUniqueName();
        String dataTableName = generateUniqueName();
        String dataTableFullName = SchemaUtil.getTableName(schemaName, dataTableName);
        final TableName dataTN = TableName.valueOf(dataTableFullName);
        String indexTableName = generateUniqueName();
        String indexTableFullName = SchemaUtil.getTableName(schemaName, indexTableName);
        TableName indexTN = TableName.valueOf(indexTableFullName);
        try (Connection conn =
                DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TEST_PROPERTIES));
                Admin admin = conn.unwrap(PhoenixConnection.class).getQueryServices().getAdmin()) {
            String dataDDL =
                    "CREATE TABLE " + dataTableFullName + "(\n"
                            + "ID VARCHAR NOT NULL PRIMARY KEY,\n"
                            + "\"info\".CAR_NUM VARCHAR(18) NULL,\n"
                            + "\"test\".CAR_NUM VARCHAR(18) NULL,\n"
                            + "\"info\".CAP_DATE VARCHAR NULL,\n" + "\"info\".ORG_ID BIGINT NULL,\n"
                            + "\"info\".ORG_NAME VARCHAR(255) NULL\n" + ") COLUMN_ENCODED_BYTES = 0";
            conn.createStatement().execute(dataDDL);

            String[] carNumPrefixes = new String[] {"a", "b", "c", "d"};

            // split the data table, as the tool splits the index table to have the same # of regions
            // doesn't really matter what the split points are, we just want a target # of regions
            int numSplits = carNumPrefixes.length;
            int targetNumRegions = numSplits + 1;
            byte[][] splitPoints = new byte[numSplits][];
            for (String prefix : carNumPrefixes) {
                splitPoints[--numSplits] = Bytes.toBytes(prefix);
            }
            HTableDescriptor dataTD = admin.getTableDescriptor(dataTN);
            admin.disableTable(dataTN);
            admin.deleteTable(dataTN);
            admin.createTable(dataTD, splitPoints);
            assertEquals(targetNumRegions, admin.getTableRegions(dataTN).size());

            // insert data where index column values start with a, b, c, d
            int idCounter = 1;
            try (PreparedStatement ps = conn.prepareStatement("UPSERT INTO " + dataTableFullName
                + "(ID,\"info\".CAR_NUM,\"test\".CAR_NUM,CAP_DATE,ORG_ID,ORG_NAME) VALUES(?,?,?,'2016-01-01 00:00:00',11,'orgname1')")){
                for (String carNum : carNumPrefixes) {
                    for (int i = 0; i < 100; i++) {
                        ps.setString(1, idCounter++ + "");
                        ps.setString(2, carNum + "_" + i);
                        ps.setString(3, "test-" + carNum + "_ " + i);
                        ps.addBatch();
                    }
                }
                ps.executeBatch();
                conn.commit();
            }

            String indexDDL =
                    String.format(
                        "CREATE INDEX %s on %s (\"info\".CAR_NUM,\"test\".CAR_NUM,\"info\".CAP_DATE) ASYNC",
                        indexTableName, dataTableFullName);
            conn.createStatement().execute(indexDDL);

            // run with 50% sampling rate, split if data table more than 3 regions
            runIndexTool(directApi, useSnapshot, schemaName, dataTableName, indexTableName,"-sp", "50", "-spa", "3");

            assertEquals(targetNumRegions, admin.getTableRegions(indexTN).size());
            List<Cell> values = new ArrayList<>();
            // every index region should have been written to, if the index table was properly split uniformly
            for (HRegion region : getUtility().getHBaseCluster().getRegions(indexTN)) {
                values.clear();
                RegionScanner scanner = region.getScanner(new Scan());
                scanner.next(values);
                if (values.isEmpty()) {
                    fail("Region did not have any results: " + region.getRegionInfo());
                }
            }
        }
    }

    public static void assertExplainPlan(boolean localIndex, String actualExplainPlan,
            String dataTableFullName, String indexTableFullName) {
        String expectedExplainPlan;
        if (localIndex) {
            expectedExplainPlan = String.format(" RANGE SCAN OVER %s [1,", dataTableFullName);
        } else {
            expectedExplainPlan = String.format(" RANGE SCAN OVER %s", indexTableFullName);
        }
        assertTrue(actualExplainPlan + "\n expected to contain \n" + expectedExplainPlan,
            actualExplainPlan.contains(expectedExplainPlan));
    }

    public static String[] getArgValues(boolean directApi, boolean useSnapshot, String schemaName,
            String dataTable, String indxTable, String tenantId) {
        final List<String> args = Lists.newArrayList();
        if (schemaName != null) {
            args.add("-s");
            args.add(schemaName);
        }
        args.add("-dt");
        args.add(dataTable);
        args.add("-it");
        args.add(indxTable);
        if (directApi) {
            args.add("-direct");
            // Need to run this job in foreground for the test to be deterministic
            args.add("-runfg");
        }

        if (useSnapshot) {
            args.add("-snap");
        }

        if (tenantId != null) {
            args.add("-tenant");
            args.add(tenantId);
        }

        args.add("-op");
        args.add("/tmp/" + UUID.randomUUID().toString());
        return args.toArray(new String[0]);
    }

    public static void upsertRow(PreparedStatement stmt, int i) throws SQLException {
        // insert row
        stmt.setInt(1, i);
        stmt.setString(2, "uname" + String.valueOf(i));
        stmt.setInt(3, 95050 + i);
        stmt.executeUpdate();
    }

    public static void runIndexTool(boolean directApi, boolean useSnapshot, String schemaName,
            String dataTableName, String indexTableName) throws Exception {
        runIndexTool(directApi, useSnapshot, schemaName, dataTableName, indexTableName, new String[0]);
    }

    private static void verifyMapper(Job job, boolean directApi, boolean useSnapshot, String schemaName,
                                  String dataTableName, String indexTableName, String tenantId) throws Exception {
        Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
        if (tenantId != null) {
            props.setProperty(PhoenixRuntime.TENANT_ID_ATTRIB, tenantId);
        }
        try (Connection conn =
                     DriverManager.getConnection(getUrl(), props)) {
            PTable dataTable = PhoenixRuntime.getTable(conn, SchemaUtil.getTableName(schemaName, dataTableName));
            PTable indexTable = PhoenixRuntime.getTable(conn, SchemaUtil.getTableName(schemaName, indexTableName));
            boolean transactional = dataTable.isTransactional();
            boolean localIndex = PTable.IndexType.LOCAL.equals(indexTable.getIndexType());

            if (directApi) {
                if ((localIndex || !transactional) && !useSnapshot) {
                    assertEquals(job.getMapperClass(), PhoenixServerBuildIndexMapper.class);
                } else {
                    assertEquals(job.getMapperClass(), PhoenixIndexImportDirectMapper.class);
                }
            }
            else {
                assertEquals(job.getMapperClass(), PhoenixIndexImportMapper.class);
            }
        }
    }

    public static void runIndexTool(boolean directApi, boolean useSnapshot, String schemaName,
            String dataTableName, String indexTableName, String... additionalArgs) throws Exception {
        runIndexTool(directApi, useSnapshot, schemaName, dataTableName, indexTableName, null, 0, additionalArgs);
    }

    public static void runIndexTool(boolean directApi, boolean useSnapshot, String schemaName,
            String dataTableName, String indexTableName, String tenantId, int expectedStatus,
            String... additionalArgs) throws Exception {
        IndexTool indexingTool = new IndexTool();
        Configuration conf = new Configuration(getUtility().getConfiguration());
        conf.set(QueryServices.TRANSACTIONS_ENABLED, Boolean.TRUE.toString());
        indexingTool.setConf(conf);
        final String[] cmdArgs =
                getArgValues(directApi, useSnapshot, schemaName, dataTableName, indexTableName, tenantId);
        List<String> cmdArgList = new ArrayList<>(Arrays.asList(cmdArgs));
        cmdArgList.addAll(Arrays.asList(additionalArgs));
        int status = indexingTool.run(cmdArgList.toArray(new String[cmdArgList.size()]));

        if (expectedStatus == 0) {
            verifyMapper(indexingTool.getJob(), directApi, useSnapshot, schemaName, dataTableName, indexTableName, tenantId);
        }
        assertEquals(expectedStatus, status);
    }
}


text:
package com.apexxs.neonblack.solr;

import com.apexxs.neonblack.setup.Configuration;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
import org.apache.solr.client.solrj.impl.ConcurrentUpdateSolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SolrServerFactory
{
    public final static Logger logger = LoggerFactory.getLogger(SolrServerFactory.class);
    public SolrServerFactory() {}

/*
    public SolrServer getEmbeddedSolrServer(String coreName)
    {
        SolrServer server = null;
        URL solrDir = SolrServerFactory.class.getResource("/solr/solr.xml");
        File solrConfigFile = new File(solrDir.getFile());
        String path = solrConfigFile.getParent();

        try
        {
            CoreContainer container = new CoreContainer(path);
            container.load();
            server = new EmbeddedSolrServer(container, coreName);
        }
        catch(Exception ex)
        {
            System.out.println();
            ex.printStackTrace();
        }

        return server;
    }*/

    public SolrServer getHTTPServer(String coreName)
    {
        Configuration config = Configuration.getInstance();
        SolrServer server = null;
        String connString = config.getSolrURL() + coreName;
        try
        {
          server = new HttpSolrServer(connString);
        }
        catch(Exception ex)
        {
            logger.error("Error in getHTTPServer: " + ex.getMessage());
        }
        return server;
    }

    public SolrServer getConcurrentSolrServer(String coreName)
    {
        Configuration config = Configuration.getInstance();
        SolrServer server = null;
        String connString = config.getSolrURL() + coreName;
        try
        {
            server = new ConcurrentUpdateSolrServer(connString, 25000, 4);
        }
        catch(Exception ex)
        {
            logger.error("Error in getConcurrentSolrServer: " + ex.getMessage());
        }
        return server;
    }

    public SolrServer getConcurrentSolrServer(String coreName, int queueSize, int numThreads)
    {
        Configuration config = Configuration.getInstance();
        SolrServer server = null;
        String connString = config.getSolrURL() + coreName;
        try
        {
            server = new ConcurrentUpdateSolrServer(connString, queueSize, numThreads);
        }
        catch(Exception ex)
        {
            logger.error("Error in getConcurrentSolrServer: " + ex.getMessage());
        }
        return server;
    }
}


text:
#include <Core/Core.h>

void *SysAllocRaw(size_t size);
void  SysFreeRaw(void *ptr, size_t size);

void *AllocRaw4KB();
void *AllocRaw64KB();
void *LAlloc(size_t& size);
void  LFree(void *ptr);

#define sHeapStat(k)
#define sDoPeakProfile()

using namespace Upp;

#include "Malloc6.h"

void IdMapBenchmark();

extern thread__ MSmall heap;

#ifndef UPP_HEAP

#include <new>

inline void *operator new(size_t size) throw(std::bad_alloc) { void *ptr = heap.Alloc(size); return ptr; }
inline void operator  delete(void *ptr) throw()              { heap.Free(ptr); }

inline void *operator new[](size_t size) throw(std::bad_alloc) { void *ptr = heap.Alloc(size); return ptr; }
inline void operator  delete[](void *ptr) throw()              { heap.Free(ptr); }

inline void *operator new(size_t size, const std::nothrow_t&) throw() { void *ptr = heap.Alloc(size); return ptr; }
inline void operator  delete(void *ptr, const std::nothrow_t&) throw() { heap.Free(ptr); }

inline void *operator new[](size_t size, const std::nothrow_t&) throw() { void *ptr = heap.Alloc(size); return ptr; }
inline void operator  delete[](void *ptr, const std::nothrow_t&) throw() { heap.Free(ptr); }

#endif

inline void *MemAlloc(size_t sz) { return heap.Alloc(sz); }
inline void  MemFree(void *ptr)  { heap.Free(ptr); }

inline void  HeapCheck()         { heap.Check(); }

void HeapTest();

#endif