text:
package org.jboss.test.clusterbench.ejb.stateful;

import javax.naming.Context;
import javax.naming.InitialContext;
import java.util.Hashtable;

public class AbstractForwardingStatefulSBImpl {
    private RemoteStatefulSB bean;

    @SuppressWarnings("unchecked")
    private RemoteStatefulSB forward() {
        if (bean == null) {
            try {
                Hashtable props = new Hashtable();
                props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
                Context context = new InitialContext(props);
                bean = (RemoteStatefulSB) context.lookup(
                        "ejb:clusterbench-ee10/clusterbench-ee10-ejb/RemoteStatefulSBImpl!org.jboss.test.clusterbench.ejb.stateful.RemoteStatefulSB?stateful"
                );
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        return bean;
    }

    public int getSerial() {
        return forward().getSerial();
    }

    public int getSerialAndIncrement() {
        return forward().getSerialAndIncrement();
    }

    public byte[] getCargo() {
        return forward().getCargo();
    }
}


text:
#include <common.h>
#include <os.h>
#include <asm/getopt.h>
#include <asm/sections.h>
#include <asm/state.h>

DECLARE_GLOBAL_DATA_PTR;

int sandbox_early_getopt_check(void)
{
	struct sandbox_state *state = state_get_current();
	struct sandbox_cmdline_option **sb_opt = __u_boot_sandbox_option_start;
	size_t num_options = __u_boot_sandbox_option_count();
	size_t i;
	int max_arg_len, max_noarg_len;

	/* parse_err will be a string of the faulting option */
	if (!state->parse_err)
		return 0;

	if (strcmp(state->parse_err, "help")) {
		printf("u-boot: error: failed while parsing option: %s\n"
			"\ttry running with --help for more information.\n",
			state->parse_err);
		os_exit(1);
	}

	printf(
		"u-boot, a command line test interface to U-Boot\n\n"
		"Usage: u-boot [options]\n"
		"Options:\n");

	max_arg_len = 0;
	for (i = 0; i < num_options; ++i)
		max_arg_len = max(strlen(sb_opt[i]->flag), max_arg_len);
	max_noarg_len = max_arg_len + 7;

	for (i = 0; i < num_options; ++i) {
		struct sandbox_cmdline_option *opt = sb_opt[i];

		/* first output the short flag if it has one */
		if (opt->flag_short >= 0x100)
			printf("      ");
		else
			printf("  -%c, ", opt->flag_short);

		/* then the long flag */
		if (opt->has_arg)
			printf("--%-*s <arg> ", max_arg_len, opt->flag);
		else
			printf("--%-*s", max_noarg_len, opt->flag);

		/* finally the help text */
		printf("  %s\n", opt->help);
	}

	os_exit(0);
}

static int sandbox_cmdline_cb_help(struct sandbox_state *state, const char *arg)
{
	/* just flag to sandbox_early_getopt_check to show usage */
	return 1;
}
SANDBOX_CMDLINE_OPT_SHORT(help, 'h', 0, "Display help");

int sandbox_main_loop_init(void)
{
	struct sandbox_state *state = state_get_current();

	/* Execute command if required */
	if (state->cmd) {
		run_command_list(state->cmd, -1, 0);
		if (!state->interactive)
			os_exit(state->exit_type);
	}

	return 0;
}

static int sandbox_cmdline_cb_command(struct sandbox_state *state,
				      const char *arg)
{
	state->cmd = arg;
	return 0;
}
SANDBOX_CMDLINE_OPT_SHORT(command, 'c', 1, "Execute U-Boot command");

static int sandbox_cmdline_cb_fdt(struct sandbox_state *state, const char *arg)
{
	state->fdt_fname = arg;
	return 0;
}
SANDBOX_CMDLINE_OPT_SHORT(fdt, 'd', 1, "Specify U-Boot's control FDT");

static int sandbox_cmdline_cb_interactive(struct sandbox_state *state,
					  const char *arg)
{
	state->interactive = true;
	return 0;
}

SANDBOX_CMDLINE_OPT_SHORT(interactive, 'i', 0, "Enter interactive mode");

static int sandbox_cmdline_cb_jump(struct sandbox_state *state,
				   const char *arg)
{
	/* Remember to delete this U-Boot image later */
	state->jumped_fname = arg;

	return 0;
}
SANDBOX_CMDLINE_OPT_SHORT(jump, 'j', 1, "Jumped from previous U-Boot");

static int sandbox_cmdline_cb_memory(struct sandbox_state *state,
				     const char *arg)
{
	int err;

	/* For now assume we always want to write it */
	state->write_ram_buf = true;
	state->ram_buf_fname = arg;

	if (os_read_ram_buf(arg)) {
		printf("Failed to read RAM buffer\n");
		return err;
	}

	return 0;
}
SANDBOX_CMDLINE_OPT_SHORT(memory, 'm', 1,
			  "Read/write ram_buf memory contents from file");

static int sandbox_cmdline_cb_rm_memory(struct sandbox_state *state,
					const char *arg)
{
	state->ram_buf_rm = true;

	return 0;
}
SANDBOX_CMDLINE_OPT(rm_memory, 0, "Remove memory file after reading");

static int sandbox_cmdline_cb_state(struct sandbox_state *state,
				    const char *arg)
{
	state->state_fname = arg;
	return 0;
}
SANDBOX_CMDLINE_OPT_SHORT(state, 's', 1, "Specify the sandbox state FDT");

static int sandbox_cmdline_cb_read(struct sandbox_state *state,
				   const char *arg)
{
	state->read_state = true;
	return 0;
}
SANDBOX_CMDLINE_OPT_SHORT(read, 'r', 0, "Read the state FDT on startup");

static int sandbox_cmdline_cb_write(struct sandbox_state *state,
				    const char *arg)
{
	state->write_state = true;
	return 0;
}
SANDBOX_CMDLINE_OPT_SHORT(write, 'w', 0, "Write state FDT on exit");

static int sandbox_cmdline_cb_ignore_missing(struct sandbox_state *state,
					     const char *arg)
{
	state->ignore_missing_state_on_read = true;
	return 0;
}
SANDBOX_CMDLINE_OPT_SHORT(ignore_missing, 'n', 0,
			  "Ignore missing state on read");

static int sandbox_cmdline_cb_show_lcd(struct sandbox_state *state,
				       const char *arg)
{
	state->show_lcd = true;
	return 0;
}
SANDBOX_CMDLINE_OPT_SHORT(show_lcd, 'l', 0,
			  "Show the sandbox LCD display");

static const char *term_args[STATE_TERM_COUNT] = {
	"raw-with-sigs",
	"raw",
	"cooked",
};

static int sandbox_cmdline_cb_terminal(struct sandbox_state *state,
				       const char *arg)
{
	int i;

	for (i = 0; i < STATE_TERM_COUNT; i++) {
		if (!strcmp(arg, term_args[i])) {
			state->term_raw = i;
			return 0;
		}
	}

	printf("Unknown terminal setting '%s' (", arg);
	for (i = 0; i < STATE_TERM_COUNT; i++)
		printf("%s%s", i ? ", " : "", term_args[i]);
	puts(")\n");

	return 1;
}
SANDBOX_CMDLINE_OPT_SHORT(terminal, 't', 1,
			  "Set terminal to raw/cooked mode");

int main(int argc, char *argv[])
{
	struct sandbox_state *state;
	int ret;

	ret = state_init();
	if (ret)
		goto err;

	state = state_get_current();
	if (os_parse_args(state, argc, argv))
		return 1;

	ret = sandbox_read_state(state, state->state_fname);
	if (ret)
		goto err;

	/* Remove old memory file if required */
	if (state->ram_buf_rm && state->ram_buf_fname)
		os_unlink(state->ram_buf_fname);

	/* Do pre- and post-relocation init */
	board_init_f(0);

	board_init_r(gd->new_gd, 0);

	/* NOTREACHED - board_init_r() does not return */
	return 0;

err:
	printf("Error %d\n", ret);
	return 1;
}

redpajama_set_name: RedPajamaGithub


text:
$LOAD_PATH.unshift File.dirname(__FILE__) + '/../../lib'
require 'thread'
require 'drb/drb'
require 'jsx'
require 'tempfile'

class IndCS5
  def run text
    @text = text
    tpl = File.read('./test.jsx.erb')
    body = ERB.new(tpl).result(binding)

    tmp = Tempfile.new ['','.jsx']
    tmp.open
    tmp.write body
    tmp.close

    Jsx.run!(tmp.path, {:compile => true, :with_directory => false})

    tmp.close!
  end
end

Thread.abort_on_exception = true
trap('INT'){ puts "\rBye!";exit}

uri = 'druby://192.168.1.138:12345'
DRb.start_service uri, IndCS5.new
puts DRb.uri
DRb.thread.join


text:
/* ------------------------------------------------------------------------
   Headers
   ------------------------------------------------------------------------ */

#include <hl7parser/config.h>
#include <hl7parser/element.h>
#include <hl7parser/export.h>
#include <hl7parser/segment.h>
#include <hl7parser/seg_zau.h>

BEGIN_C_DECL()

/* ------------------------------------------------------------------------ */
HL7_EXPORT HL7_Element *hl7_zau_prev_authorization_id( HL7_Segment *segment )
{
    return hl7_segment_component( segment, 0, 0 );
}

/* ------------------------------------------------------------------------ */
HL7_EXPORT int hl7_zau_set_prev_authorization_id( HL7_Segment *segment, HL7_Element *element )
{
    return hl7_segment_set_component( segment, 0, 0, element );
}

/* ------------------------------------------------------------------------ */
HL7_EXPORT int hl7_zau_set_prev_authorization_id_str( HL7_Segment *segment, const char *value )
{
    int         rc;
    HL7_Element element;

    rc = hl7_element_copy_str( &element, value, segment->allocator );

    return ( rc == 0 ? hl7_segment_set_component( segment, 0, 0, &element ) : rc );
}

/* ------------------------------------------------------------------------ */
HL7_EXPORT HL7_Element *hl7_zau_payor_control_id( HL7_Segment *segment )
{
    return hl7_segment_component( segment, 1, 0 );
}

/* ------------------------------------------------------------------------ */
HL7_EXPORT int hl7_zau_set_payor_control_id( HL7_Segment *segment, HL7_Element *element )
{
    return hl7_segment_set_component( segment, 1, 0, element );
}

/* ------------------------------------------------------------------------ */
HL7_EXPORT int hl7_zau_set_payor_control_id_str( HL7_Segment *segment, const char *value )
{
    int         rc;
    HL7_Element element;

    rc = hl7_element_copy_str( &element, value, segment->allocator );

    return ( rc == 0 ? hl7_segment_set_component( segment, 1, 0, &element ) : rc );
}

/* ------------------------------------------------------------------------ */
HL7_EXPORT HL7_Element *hl7_zau_authorization_status( HL7_Segment *segment )
{
    return hl7_segment_component( segment, 2, 0 );
}

/* ------------------------------------------------------------------------ */
HL7_EXPORT int hl7_zau_set_authorization_status( HL7_Segment *segment, HL7_Element *element )
{
    return hl7_segment_set_component( segment, 2, 0, element );
}

/* ------------------------------------------------------------------------ */
HL7_EXPORT int hl7_zau_set_authorization_status_str( HL7_Segment *segment, const char *value )
{
    int         rc;
    HL7_Element element;

    rc = hl7_element_copy_str( &element, value, segment->allocator );

    return ( rc == 0 ? hl7_segment_set_component( segment, 2, 0, &element ) : rc );
}

/* ------------------------------------------------------------------------ */
HL7_EXPORT HL7_Element *hl7_zau_authorization_status_text( HL7_Segment *segment )
{
    return hl7_segment_component( segment, 2, 1 );
}

/* ------------------------------------------------------------------------ */
HL7_EXPORT int hl7_zau_set_authorization_status_text( HL7_Segment *segment, HL7_Element *element )
{
    return hl7_segment_set_component( segment, 2, 1, element );
}

/* ------------------------------------------------------------------------ */
HL7_EXPORT int hl7_zau_set_authorization_status_text_str( HL7_Segment *segment, const char *value )
{
    int         rc;
    HL7_Element element;

    rc = hl7_element_copy_str( &element, value, segment->allocator );

    return ( rc == 0 ? hl7_segment_set_component( segment, 2, 1, &element ) : rc );
}

/* ------------------------------------------------------------------------ */
HL7_EXPORT HL7_Element *hl7_zau_pre_authorization_id( HL7_Segment *segment )
{
    return hl7_segment_component( segment, 3, 0 );
}

/* ------------------------------------------------------------------------ */
HL7_EXPORT int hl7_zau_set_pre_authorization_id( HL7_Segment *segment, HL7_Element *element )
{
    return hl7_segment_set_component( segment, 3, 0, element );
}

/* ------------------------------------------------------------------------ */
HL7_EXPORT int hl7_zau_set_pre_authorization_id_str( HL7_Segment *segment, const char *value )
{
    int         rc;
    HL7_Element element;

    rc = hl7_element_copy_str( &element, value, segment->allocator );

    return ( rc == 0 ? hl7_segment_set_component( segment, 3, 0, &element ) : rc );
}

/* ------------------------------------------------------------------------ */
HL7_EXPORT HL7_Element *hl7_zau_pre_authorization_date( HL7_Segment *segment )
{
    return hl7_segment_field( segment, 4 );
}

/* ------------------------------------------------------------------------ */
HL7_EXPORT int hl7_zau_set_pre_authorization_date( HL7_Segment *segment, HL7_Element *element )
{
    return hl7_segment_set_field( segment, 4, element );
}

/* ------------------------------------------------------------------------ */
HL7_EXPORT int hl7_zau_set_pre_authorization_date_str( HL7_Segment *segment, const char *value )
{
    int         rc;
    HL7_Element element;

    rc = hl7_element_copy_str( &element, value, segment->allocator );

    return ( rc == 0 ? hl7_segment_set_field( segment, 4, &element ) : rc );
}

/* ------------------------------------------------------------------------ */
HL7_EXPORT HL7_Element *hl7_zau_copay( HL7_Segment *segment )
{
    return hl7_segment_subcomponent( segment, 5, 0, 0 );
}

/* ------------------------------------------------------------------------ */
HL7_EXPORT int hl7_zau_set_copay( HL7_Segment *segment, HL7_Element *element )
{
    return hl7_segment_set_subcomponent( segment, 5, 0, 0, element );
}

/* ------------------------------------------------------------------------ */
HL7_EXPORT int hl7_zau_set_copay_str( HL7_Segment *segment, const char *value )
{
    int         rc;
    HL7_Element element;

    rc = hl7_element_copy_str( &element, value, segment->allocator );

    return ( rc == 0 ? hl7_segment_set_subcomponent( segment, 5, 0, 0, &element ) : rc );
}

/* ------------------------------------------------------------------------ */
HL7_EXPORT HL7_Element *hl7_zau_copay_currency( HL7_Segment *segment )
{
    return hl7_segment_subcomponent( segment, 5, 0, 1 );
}

/* ------------------------------------------------------------------------ */
HL7_EXPORT int hl7_zau_set_copay_currency( HL7_Segment *segment, HL7_Element *element )
{
    return hl7_segment_set_subcomponent( segment, 5, 0, 1, element );
}

/* ------------------------------------------------------------------------ */
HL7_EXPORT int hl7_zau_set_copay_currency_str( HL7_Segment *segment, const char *value )
{
    int         rc;
    HL7_Element element;

    rc = hl7_element_copy_str( &element, value, segment->allocator );

    return ( rc == 0 ? hl7_segment_set_subcomponent( segment, 5, 0, 1, &element ) : rc );
}

END_C_DECL()


text:
import { isPrimitive } from '@tdm/core/tdm';
import {
  TDMCollection as ARecordColl,
  ActionMethodType,
  TargetDAO,
  IdentityValueType,
  ExecuteContext
} from '@tdm/data';

import { LocalForageActionOptions } from './core';
import { LocalForageActionMetadata } from './metadata';
import { LocalForageAction } from './decorators';

export const LocalForageDaoActions = {
  query: LocalForageAction({
    method: ActionMethodType.READ,
    isCollection: true,
    collInstance: true,
    validation: 'incoming' as 'incoming',
    alias: 'findAll'
  }),

  findById: LocalForageAction({
    method: ActionMethodType.READ,
    validation: 'incoming' as 'incoming',
    pre: (ctx: ExecuteContext<LocalForageActionMetadata>,
          id: IdentityValueType,
          options?: LocalForageActionOptions) => {
      ctx.setIdentity(id);
      return options;
    }
  }),

  find: LocalForageAction({
    method: ActionMethodType.READ,
    validation: 'incoming' as 'incoming',
    alias: 'findOne'
  }),

  create: LocalForageAction({
    method: ActionMethodType.CREATE,
    validation: 'both' as 'both',
    pre: (ctx: ExecuteContext<LocalForageActionMetadata>, data: any, options?: LocalForageActionOptions) => {
      ctx.data = data;
      return options;
    }
  }),

  createBulk: LocalForageAction({
    method: ActionMethodType.CREATE,
    isCollection: true,
    validation: 'both' as 'both',
    pre: (ctx: ExecuteContext<LocalForageActionMetadata>, data: any, options?: LocalForageActionOptions) => {
      ctx.data = data;
      return options;
    }
  }),

  update: LocalForageAction({
    method: ActionMethodType.UPDATE,
    validation: 'both' as 'both',
    pre: (ctx: ExecuteContext<LocalForageActionMetadata>, data: any, options?: LocalForageActionOptions) => {
      ctx.data = data;
      return options;
    }
  }),

  replace: LocalForageAction({
    method: ActionMethodType.REPLACE,
    validation: 'both' as 'both',
    pre: (ctx: ExecuteContext<LocalForageActionMetadata>, data: any, options?: LocalForageActionOptions) => {
      ctx.data = data;
      return options;
    }
  }),

  remove: LocalForageAction({
    method: ActionMethodType.DELETE,
    validation: 'skip' as 'skip',
    pre: (ctx: ExecuteContext<LocalForageActionMetadata>,
          id: IdentityValueType | any,
          options?: LocalForageActionOptions) => {

      if ( isPrimitive(id) ) {
        ctx.setIdentity(id);
      } else if ( ctx.instanceOf(id) ) {
        ctx.setInstance(id);
      } else {
        ctx.deserialize(id);
      }

      return options;
    }
  }),

  clear: LocalForageAction({
    method: ActionMethodType.DELETE,
    validation: 'skip' as 'skip'
  })
};

export class LocalForageDao<T> implements TargetDAO<T, LocalForageActionOptions> {
  @LocalForageDaoActions.query
  query: (options?: LocalForageActionOptions) => Promise<ARecordColl<T>>;
  findAll: (options?: LocalForageActionOptions) => Promise<ARecordColl<T>>;

  @LocalForageDaoActions.findById
  findById: (id: IdentityValueType, options?: LocalForageActionOptions) => Promise<T>;

  @LocalForageDaoActions.find
  find: (options: LocalForageActionOptions) => Promise<T>;
  findOne: (options: LocalForageActionOptions) => Promise<T>;

  @LocalForageDaoActions.create
  create: (data: T | Partial<T>, options?: LocalForageActionOptions) => Promise<T | void>;

  @LocalForageDaoActions.createBulk
  createBulk: (data: T[] | Partial<T[]>, options?: LocalForageActionOptions) => Promise<T[] | void>;

  @LocalForageDaoActions.update
  update: (data: T | Partial<T>, options?: LocalForageActionOptions) => Promise<T | void>;

  @LocalForageDaoActions.replace
  replace: (data: T | Partial<T>, options?: LocalForageActionOptions) => Promise<T | void>;

  @LocalForageDaoActions.remove
  remove: ( (id: IdentityValueType | T, options?: LocalForageActionOptions) => Promise<void> );

  @LocalForageDaoActions.clear
  clear: ( () => Promise<void> );
}


text:
package aima.test.core.unit.probability.temporal;

import java.util.ArrayList;
import java.util.List;

import org.junit.Assert;

import aima.core.probability.CategoricalDistribution;
import aima.core.probability.example.ExampleRV;
import aima.core.probability.proposition.AssignmentProposition;
import aima.core.probability.temporal.BackwardStepInference;
import aima.core.probability.temporal.ForwardBackwardInference;
import aima.core.probability.temporal.ForwardStepInference;
import aima.core.probability.util.ProbabilityTable;

/**
 *
 * @author Ciaran O'Reilly
 */
public abstract class CommonForwardBackwardTest {
	public static final double DELTA_THRESHOLD = 1e-3;

	//
	// PROTECTED METHODS
	//
	protected void testForwardStep_UmbrellaWorld(ForwardStepInference uw) {
		// AIMA3e pg. 572
		// Day 0, no observations only the security guards prior beliefs
		// P(R0) = <0.5, 0.5>
		CategoricalDistribution prior = new ProbabilityTable(new double[] {
				0.5, 0.5 }, ExampleRV.RAIN_t_RV);

		// Day 1, the umbrella appears, so U1 = true.
		// ≈ <0.818, 0.182>
		List<AssignmentProposition> e1 = new ArrayList<AssignmentProposition>();
		e1
				.add(new AssignmentProposition(ExampleRV.UMBREALLA_t_RV,
						Boolean.TRUE));
		CategoricalDistribution f1 = uw.forward(prior, e1);
		Assert.assertArrayEquals(new double[] { 0.818, 0.182 }, f1.getValues(),
				DELTA_THRESHOLD);

		// Day 2, the umbrella appears, so U2 = true.
		// ≈ <0.883, 0.117>
		List<AssignmentProposition> e2 = new ArrayList<AssignmentProposition>();
		e2
				.add(new AssignmentProposition(ExampleRV.UMBREALLA_t_RV,
						Boolean.TRUE));
		CategoricalDistribution f2 = uw.forward(f1, e2);
		Assert.assertArrayEquals(new double[] { 0.883, 0.117 }, f2.getValues(),
				DELTA_THRESHOLD);
	}

	protected void testBackwardStep_UmbrellaWorld(BackwardStepInference uw) {
		// AIMA3e pg. 575
		CategoricalDistribution b_kp2t = new ProbabilityTable(new double[] {
				1.0, 1.0 }, ExampleRV.RAIN_t_RV);
		List<AssignmentProposition> e2 = new ArrayList<AssignmentProposition>();
		e2
				.add(new AssignmentProposition(ExampleRV.UMBREALLA_t_RV,
						Boolean.TRUE));
		CategoricalDistribution b1 = uw.backward(b_kp2t, e2);
		Assert.assertArrayEquals(new double[] { 0.69, 0.41 }, b1.getValues(),
				DELTA_THRESHOLD);
	}

	protected void testForwardBackward_UmbrellaWorld(ForwardBackwardInference uw) {
		// AIMA3e pg. 572
		// Day 0, no observations only the security guards prior beliefs
		// P(R0) = <0.5, 0.5>
		CategoricalDistribution prior = new ProbabilityTable(new double[] {
				0.5, 0.5 }, ExampleRV.RAIN_t_RV);

		// Day 1
		List<List<AssignmentProposition>> evidence = new ArrayList<List<AssignmentProposition>>();
		List<AssignmentProposition> e1 = new ArrayList<AssignmentProposition>();
		e1
				.add(new AssignmentProposition(ExampleRV.UMBREALLA_t_RV,
						Boolean.TRUE));
		evidence.add(e1);

		List<CategoricalDistribution> smoothed = uw.forwardBackward(evidence,
				prior);

		Assert.assertEquals(1, smoothed.size());
		Assert.assertArrayEquals(new double[] { 0.818, 0.182 }, smoothed.get(0)
				.getValues(), DELTA_THRESHOLD);

		// Day 2
		List<AssignmentProposition> e2 = new ArrayList<AssignmentProposition>();
		e2
				.add(new AssignmentProposition(ExampleRV.UMBREALLA_t_RV,
						Boolean.TRUE));
		evidence.add(e2);

		smoothed = uw.forwardBackward(evidence, prior);

		Assert.assertEquals(2, smoothed.size());
		Assert.assertArrayEquals(new double[] { 0.883, 0.117 }, smoothed.get(0)
				.getValues(), DELTA_THRESHOLD);
		Assert.assertArrayEquals(new double[] { 0.883, 0.117 }, smoothed.get(1)
				.getValues(), DELTA_THRESHOLD);

		// Day 3
		List<AssignmentProposition> e3 = new ArrayList<AssignmentProposition>();
		e3.add(new AssignmentProposition(ExampleRV.UMBREALLA_t_RV,
				Boolean.FALSE));
		evidence.add(e3);

		smoothed = uw.forwardBackward(evidence, prior);

		Assert.assertEquals(3, smoothed.size());
		Assert.assertArrayEquals(new double[] { 0.861, 0.138 }, smoothed.get(0)
				.getValues(), DELTA_THRESHOLD);
		Assert.assertArrayEquals(new double[] { 0.799, 0.201 }, smoothed.get(1)
				.getValues(), DELTA_THRESHOLD);
		Assert.assertArrayEquals(new double[] { 0.190, 0.810 }, smoothed.get(2)
				.getValues(), DELTA_THRESHOLD);
	}
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.trafodion.dcs.util;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.SQLException;
import java.sql.Types;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Hashtable;
import java.util.Arrays;
import java.io.UnsupportedEncodingException;

import org.trafodion.dcs.Constants;
import org.trafodion.dcs.servermt.ServerConstants;
import org.trafodion.dcs.servermt.serverDriverInputOutput.Descriptor2;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SqlUtils {

    private static  final Log LOG = LogFactory.getLog(SqlUtils.class);

    private SqlUtils() {
    }

    static private Hashtable valueToCharset;
    static {
        valueToCharset = new Hashtable(11);
        valueToCharset.put(new Integer(1), "ISO8859_1"); // ISO
        valueToCharset.put(new Integer(10), "MS932"); // SJIS
        valueToCharset.put(new Integer(11), "UTF-16BE"); // UCS2
        valueToCharset.put(new Integer(12), "EUCJP"); // EUCJP
        valueToCharset.put(new Integer(13), "MS950"); // BIG5
        valueToCharset.put(new Integer(14), "GB18030"); // GB18030
        valueToCharset.put(new Integer(15), "UTF-8"); // UTF8
        valueToCharset.put(new Integer(16), "MS949"); // MB_KSC5601
        valueToCharset.put(new Integer(17), "GB2312"); // GB2312
    }
    static private Hashtable charsetToValue;
    static {
        charsetToValue = new Hashtable(11);
        charsetToValue.put("ISO8859_1", new Integer(1)); // ISO
        charsetToValue.put("MS932", new Integer(10)); // SJIS
        charsetToValue.put("UTF-16BE", new Integer(11)); // UCS2
        charsetToValue.put("EUCJP", new Integer(12)); // EUCJP
        charsetToValue.put("MS950", new Integer(13)); // BIG5
        charsetToValue.put("GB18030", new Integer(14)); // GB18030
        charsetToValue.put("UTF-8", new Integer(15)); // UTF8
        charsetToValue.put("MS949", new Integer(16)); // MB_KSC5601
        charsetToValue.put("GB2312", new Integer(17)); // GB2312
    }

    static final int SQLCHARSETCODE_UNKNOWN = 0;
    static final String SQLCHARSET_UNKNOWN = "UNKNOWN";

    // these are the only real column types
    static public final int SQLCHARSETCODE_ISO88591 = 1;
    static public final String SQLCHARSET_ISO88591 = "ISO88591";
    static public final int SQLCHARSETCODE_UNICODE = 11;
    static public final String SQLCHARSET_UNICODE = "UCS2";

    // ISO_MAPPING values
    static public final int SQLCHARSETCODE_SJIS = 10;
    static public final int SQLCHARSETCODE_UTF8 = 15;

    static public String getCharsetName(int charset) {
        String ret = (String) valueToCharset.get(new Integer(charset));

        if (ret == null)
            ret = SQLCHARSET_UNKNOWN;

        return ret;
    }

    static public int getCharsetValue(String charset) {
        Integer i = (Integer) charsetToValue.get(charset);
        int ret;

        if (i == null)
            ret = SQLCHARSETCODE_UNKNOWN;
        else
            ret = i.intValue();

        return ret;
    }

    static public String getComponentId(int componentId){
        String str = "UNKNOWN Component [" + componentId + "]";
        switch (componentId){
            case ServerConstants.DCS_MASTER_COMPONENT:
                str = "DCS_MASTER_COMPONENT [" + componentId + "]";
                break;
            case ServerConstants.SQL_COMPONENT:
                str = "SQL_COMPONENT [" + componentId + "]";
                break;
            case ServerConstants.ODBC_SRVR_COMPONENT:
                str = "ODBC_SRVR_COMPONENT [" + componentId + "]";
                break;
            case ServerConstants.DRVR_COMPONENT:
                str = "DRVR_COMPONENT [" + componentId + "]";
                break;
            case ServerConstants.APP_COMPONENT:
                str = "APP_COMPONENT [" + componentId + "]";
                break;
            case ServerConstants.JDBC_DRVR_COMPONENT:
                str = "JDBC_DRVR_COMPONENT [" + componentId + "]";
                break;
            case ServerConstants.LINUX_DRVR_COMPONENT:
                str = "LINUX_DRVR_COMPONENT [" + componentId + "]";
                break;
            case ServerConstants.DOT_NET_DRVR_COMPONENT:
                str = "DOT_NET_DRVR_COMPONENT [" + componentId + "]";
                break;
            case ServerConstants.WIN_UNICODE_DRVR_COMPONENT:
                str = "WIN_UNICODE_DRVR_COMPONENT [" + componentId + "]";
                break;
            case ServerConstants.LINUX_UNICODE_DRVR_COMPONENT:
                str = "LINUX_UNICODE_DRVR_COMPONENT [" + componentId + "]";
                break;
            default:
        }
        return str;
    }
    static public int getSqlStmtType(int stmtType) {
        int retQueryType;
        switch(stmtType){
            case ServerConstants.TYPE_SELECT:
                retQueryType = ServerConstants.SQL_SELECT_NON_UNIQUE;
                break;
            case ServerConstants.TYPE_UPDATE:
                retQueryType = ServerConstants.SQL_UPDATE_NON_UNIQUE;
                break;
            case ServerConstants.TYPE_DELETE:
                retQueryType = ServerConstants.SQL_DELETE_NON_UNIQUE;
                break;
            case ServerConstants.TYPE_INSERT:
                retQueryType = ServerConstants.SQL_INSERT_NON_UNIQUE;
                break;
            default:
                retQueryType = stmtType;
        }
        return retQueryType;
    }
    static public short getSqlStmtType(String str) {
        //
        // Kludge to determin if the type of statement.
        //
        String tokens[] = str.split("[^a-zA-Z]+", 3);
        short rt1 = ServerConstants.TYPE_UNKNOWN;
        String str3 = "";
        //
        // If there are no separators (i.e. no spaces, {, =, etc.) in front of
        // the
        // first token, then the first token is the key word we are looking for.
        // Else, the first token is an empty string (i.e. split thinks the first
        // token is the empty string followed by a separator), and the second
        // token is the key word we are looking for.
        //
        if (tokens[0].length() > 0) {
            str3 = tokens[0].toUpperCase();
        } else {
            str3 = tokens[1].toUpperCase();
        }
        if ((str3.equals("SELECT")) || (str3.equals("SHOWSHAPE"))
                || (str3.equals("INVOKE")) || (str3.equals("SHOWCONTROL"))
                || (str3.equals("SHOWPLAN"))) {
              rt1 = ServerConstants.SQL_SELECT_NON_UNIQUE;
//            rt1 = ServerConstants.TYPE_SELECT;
       } else if (str3.equals("UPDATE")) {
              rt1 = ServerConstants.SQL_UPDATE_NON_UNIQUE;
//            rt1 = ServerConstants.TYPE_UPDATE;
        } else if (str3.equals("DELETE")) {
              rt1 = ServerConstants.SQL_DELETE_NON_UNIQUE;
//            rt1 = ServerConstants.TYPE_DELETE;
        } else if (str3.equals("INSERT") || (str.equals("UPSERT"))) {
            if (str.indexOf('?') == -1) {
              rt1 = ServerConstants.SQL_INSERT_NON_UNIQUE;
//            rt1 = ServerConstants.TYPE_INSERT;
            } else {
                rt1 = ServerConstants.TYPE_INSERT_PARAM;
            }
        } else if (str3.equals("EXPLAIN")) {
            rt1 = ServerConstants.TYPE_EXPLAIN;
        } else if (str3.equals("CREATE")) {
            rt1 = ServerConstants.TYPE_CREATE;
        } else if (str3.equals("GRANT")) {
            rt1 = ServerConstants.TYPE_GRANT;
        } else if (str3.equals("DROP")) {
            rt1 = ServerConstants.TYPE_DROP;
        } else if (str3.equals("CALL")) {
            rt1 = ServerConstants.TYPE_CALL;
        } else if (str3.equals("EXPLAIN")) {
            rt1 = ServerConstants.TYPE_EXPLAIN;
        } else if (str3.equals("CONTROL")) {
            rt1 = ServerConstants.TYPE_CONTROL;
        } else {
            rt1 = ServerConstants.TYPE_UNKNOWN;
        }
        return rt1;
    }
    static public String getSqlCharsetName(int code) {

        String str = ServerConstants.sqlCharsetSTRING_UNKNOWN;
        switch (code){
        case ServerConstants.sqlCharsetCODE_ISO88591:
            return ServerConstants.sqlCharsetSTRING_ISO88591;
        case ServerConstants.sqlCharsetCODE_KANJI:
            return ServerConstants.sqlCharsetSTRING_KANJI;
        case ServerConstants.sqlCharsetCODE_KSC5601:
            return ServerConstants.sqlCharsetSTRING_KSC5601;
        case ServerConstants.sqlCharsetCODE_SJIS:
            return ServerConstants.sqlCharsetSTRING_SJIS;
        case ServerConstants.sqlCharsetCODE_UCS2:
            return ServerConstants.sqlCharsetSTRING_UNICODE;
        default:
        }
        return str;
    }
    static public String getSqlError(int retcode)
    {
        String rc;

        // SQL_NO_DATA_FOUND can be defined as SQL_NO_DATA
        if (retcode==ServerConstants.SQL_NO_DATA_FOUND)
        {
            if (ServerConstants.SQL_NO_DATA_FOUND==ServerConstants.SQL_NO_DATA) return "SQL_NO_DATA_FOUND|SQL_NO_DATA" ;
            return("SQL_NO_DATA_FOUND");
        }
        switch (retcode)
        {
        case ServerConstants.SQL_SUCCESS:
            return("SQL_SUCCESS");
        case ServerConstants.SQL_SUCCESS_WITH_INFO:
            return("SQL_SUCCESS_WITH_INFO");
        case ServerConstants.SQL_NO_DATA:
            return("SQL_NO_DATA");
        case ServerConstants.SQL_ERROR:
            return("SQL_ERROR");
/*
        case ServerConstants.SQL_INVALID_HANDLE:
            return("SQL_INVALID_HANDLE");
        case ServerConstants.SQL_STILL_EXECUTING:
            return("SQL_STILL_EXECUTING");
        case ServerConstants.SQL_NEED_DATA:
            return("SQL_NEED_DATA");
        case ServerConstants.STMT_ID_MISMATCH_ERROR:
            return("STMT_ID_MISMATCH_ERROR");
        case ServerConstants.DIALOGUE_ID_NULL_ERROR:
            return("DIALOGUE_ID_NULL_ERROR");
        case ServerConstants.STMT_ID_NULL_ERROR:
            return("STMT_ID_NULL_ERROR");
        case ServerConstants.NOWAIT_PENDING:
            return("NOWAIT_PENDING");
        case ServerConstants.STMT_ALREADY_EXISTS:
            return("STMT_ALREADY_EXISTS");
        case ServerConstants.STMT_DOES_NOT_EXIST:
            return("STMT_DOES_NOT_EXIST");
        case ServerConstants.STMT_IS_NOT_CALL:
            return("STMT_IS_NOT_CALL");
        case ServerConstants.RS_INDEX_OUT_OF_RANGE:
            return("RS_INDEX_OUT_OF_RANGE");
        case ServerConstants.RS_ALREADY_EXISTS:
            return("RS_ALREADY_EXISTS");
        case ServerConstants.RS_ALLOC_ERROR:
            return("RS_ALLOC_ERROR");
        case ServerConstants.RS_DOES_NOT_EXIST:
            return("RS_DOES_NOT_EXIST");
        case ServerConstants.PROGRAM_ERROR:
            return("PROGRAM_ERROR");
        case ServerConstants.ODBC_SERVER_ERROR:
            return("ODBC_SERVER_ERROR");
        case ServerConstants.ODBC_RG_ERROR:
            return("ODBC_RG_ERROR");
        case ServerConstants.ODBC_RG_WARNING:
            return("ODBC_RG_WARNING");
        case ServerConstants.SQL_RETRY_COMPILE_AGAIN:
            return("SQL_RETRY_COMPILE_AGAIN");
        case SQL_QUERY_CANCELLED:
            return("SQL_QUERY_CANCELLED");
        case ServerConstants.CANCEL_NOT_POSSIBLE:
            return("CANCEL_NOT_POSSIBLE");
        case ServerConstants.NOWAIT_ERROR:
            return("NOWAIT_ERROR");
*/
        }
        rc = "Unknown SQL Error (" + retcode + ")";
        return rc;
    }
    static public String getSqlStatementType(short stmtType)
    {
        String rc;

        if (stmtType == ServerConstants.TYPE_UNKNOWN) return "TYPE_UNKNOWN";
        rc = "";
        if ((stmtType & ServerConstants.TYPE_SELECT) != 0) rc = rc + "|TYPE_SELECT";
        if ((stmtType & ServerConstants.TYPE_UPDATE) != 0) rc = rc + "|TYPE_UPDATE";
        if ((stmtType & ServerConstants.TYPE_DELETE) != 0) rc = rc + "|TYPE_DELETE";
        if ((stmtType & ServerConstants.TYPE_INSERT) != 0) rc = rc + "|TYPE_INSERT";
        if ((stmtType & ServerConstants.TYPE_EXPLAIN) != 0) rc = rc + "|TYPE_EXPLAIN";
        if ((stmtType & ServerConstants.TYPE_CREATE) != 0) rc = rc + "|TYPE_CREATE";
        if ((stmtType & ServerConstants.TYPE_GRANT) != 0) rc = rc + "|TYPE_GRANT";
        if ((stmtType & ServerConstants.TYPE_DROP) != 0) rc = rc + "|TYPE_DROP";
        if ((stmtType & ServerConstants.TYPE_CALL) != 0) rc = rc + "|TYPE_CALL";
        if (rc.length()==0) rc = "UNKNOWN(" + stmtType +")";
        return rc;
    }
    static public String getSqlQueryStatementType(int stmtType)
    {
        switch (stmtType)
        {
        case ServerConstants.INVALID_SQL_QUERY_STMT_TYPE:
            return("INVALID_SQL_QUERY_STMT_TYPE");
        case ServerConstants.SQL_OTHER:
            return("SQL_OTHER");
        case ServerConstants.SQL_UNKNOWN:
            return("SQL_UNKNOWN");
        case ServerConstants.SQL_SELECT_UNIQUE:
            return("SQL_SELECT_UNIQUE");
        case ServerConstants.SQL_SELECT_NON_UNIQUE:
            return("SQL_SELECT_NON_UNIQUE");
        case ServerConstants.SQL_INSERT_UNIQUE:
            return("SQL_INSERT_UNIQUE");
        case ServerConstants.SQL_INSERT_NON_UNIQUE:
            return("SQL_INSERT_NON_UNIQUE");
        case ServerConstants.SQL_UPDATE_UNIQUE:
            return("SQL_UPDATE_UNIQUE");
        case ServerConstants.SQL_UPDATE_NON_UNIQUE:
            return("SQL_UPDATE_NON_UNIQUE");
        case ServerConstants.SQL_DELETE_UNIQUE:
            return("SQL_DELETE_UNIQUE");
        case ServerConstants.SQL_DELETE_NON_UNIQUE:
            return("SQL_DELETE_NON_UNIQUE");
        case ServerConstants.SQL_CONTROL:
            return("SQL_CONTROL");
        case ServerConstants.SQL_SET_TRANSACTION:
            return("SQL_SET_TRANSACTION");
        case ServerConstants.SQL_SET_CATALOG:
            return("SQL_SET_CATALOG");
        case ServerConstants.SQL_SET_SCHEMA:
            return("SQL_SET_SCHEMA");
        case ServerConstants.SQL_CALL_NO_RESULT_SETS:
            return("SQL_CALL_NO_RESULT_SETS");
        case ServerConstants.SQL_CALL_WITH_RESULT_SETS:
            return("SQL_CALL_WITH_RESULT_SETS");
        case ServerConstants.SQL_SP_RESULT_SET:
            return("SQL_SP_RESULT_SET");
        }
        return "Unknown (" + stmtType + ")";
    };

    static public String getSqlAttrType(int code)
    {
        String rc;
        switch (code)
        {
            case ServerConstants.SQL_ATTR_CURSOR_HOLDABLE:
                return("SQL_ATTR_CURSOR_HOLDABLE");
            case ServerConstants.SQL_ATTR_INPUT_ARRAY_MAXSIZE:
                return("SQL_ATTR_INPUT_ARRAY_MAXSIZE");
            case ServerConstants.SQL_ATTR_QUERY_TYPE:
                return("SQL_ATTR_QUERY_TYPE");
            case ServerConstants.SQL_ATTR_MAX_RESULT_SETS:
                return("SQL_ATTR_MAX_RESULT_SETS");
        }
        rc = "Unknown (" + code + ")";
        return rc;
    }
    static public String getSqlDataType(int code)
    {
        String rc;
        switch (code)
        {
            case ServerConstants.SQLTYPECODE_CHAR:
                return("SQLTYPECODE_CHAR");
            case ServerConstants.SQLTYPECODE_NUMERIC:
                return("SQLTYPECODE_NUMERIC");
            case ServerConstants.SQLTYPECODE_NUMERIC_UNSIGNED:
                return("SQLTYPECODE_NUMERIC_UNSIGNED");
            case ServerConstants.SQLTYPECODE_DECIMAL:
                return("SQLTYPECODE_DECIMAL");
            case ServerConstants.SQLTYPECODE_DECIMAL_UNSIGNED:
                return("SQLTYPECODE_DECIMAL_UNSIGNED");
            case ServerConstants.SQLTYPECODE_DECIMAL_LARGE:
                return("SQLTYPECODE_DECIMAL_LARGE");
            case ServerConstants.SQLTYPECODE_DECIMAL_LARGE_UNSIGNED:
                return("SQLTYPECODE_DECIMAL_LARGE_UNSIGNED");
            case ServerConstants.SQLTYPECODE_INTEGER:
                return("SQLTYPECODE_INTEGER");
            case ServerConstants.SQLTYPECODE_INTEGER_UNSIGNED:
                return("SQLTYPECODE_INTEGER_UNSIGNED");
            case ServerConstants.SQLTYPECODE_LARGEINT:
                return("SQLTYPECODE_LARGEINT");
            case ServerConstants.SQLTYPECODE_SMALLINT:
                return("SQLTYPECODE_SMALLINT");
            case ServerConstants.SQLTYPECODE_SMALLINT_UNSIGNED:
                return("SQLTYPECODE_SMALLINT_UNSIGNED");
            case ServerConstants.SQLTYPECODE_BPINT_UNSIGNED:
                return("SQLTYPECODE_BPINT_UNSIGNED");
            case ServerConstants.SQLTYPECODE_TDM_FLOAT:
                return("SQLTYPECODE_TDM_FLOAT");
            case ServerConstants.SQLTYPECODE_IEEE_FLOAT:
                return("SQLTYPECODE_IEEE_FLOAT");
            case ServerConstants.SQLTYPECODE_TDM_REAL:
                return("SQLTYPECODE_TDM_REAL");
            case ServerConstants.SQLTYPECODE_IEEE_REAL:
                return("SQLTYPECODE_IEEE_REAL");
            case ServerConstants.SQLTYPECODE_TDM_DOUBLE:
                return("SQLTYPECODE_TDM_DOUBLE");
            case ServerConstants.SQLTYPECODE_IEEE_DOUBLE:
                return("SQLTYPECODE_IEEE_DOUBLE");
            case ServerConstants.SQLTYPECODE_DATETIME:
                return("SQLTYPECODE_DATETIME");
            case ServerConstants.SQLTYPECODE_INTERVAL:
                return("SQLTYPECODE_INTERVAL");
            case ServerConstants.SQLTYPECODE_VARCHAR:
                return("SQLTYPECODE_VARCHAR");
            case ServerConstants.SQLTYPECODE_VARCHAR_WITH_LENGTH:
                return("SQLTYPECODE_VARCHAR_WITH_LENGTH");
            case ServerConstants.SQLTYPECODE_VARCHAR_LONG:
                return("SQLTYPECODE_VARCHAR_LONG");
            case ServerConstants.SQLTYPECODE_BIT:
                return("SQLTYPECODE_BIT");
            case ServerConstants.SQLTYPECODE_BITVAR:
                return("SQLTYPECODE_BITVAR");
        };
        rc = "UNKNOWN (" + code + ")";
        return rc;
    }
    static public String getDataType(int dataType)
    {
        switch (dataType)
        {
            case Types.SMALLINT:
                return "SMALLINT";
            case Types.INTEGER:
                return "INTEGER";
            case Types.BIGINT:
                return "BIGINT";
            case Types.REAL:
                return "REAL";
            case Types.FLOAT:
                return "FLOAT";
            case Types.DOUBLE:
                return "DOUBLE PRECISION";
            case Types.NUMERIC:
                return "NUMERIC";
            case Types.DECIMAL:
                return "DECIMAL";
            case Types.CHAR:
                return "CHAR";
            case Types.VARCHAR:
                return "VARCHAR";
            case Types.LONGVARCHAR:
                return "LONG VARCHAR";
            case Types.DATE:
                return "DATE";
            case Types.TIME:
                return "TIME";
            case Types.TIMESTAMP:
                return "TIMESTAMP";
            case Types.BLOB:
                return "BLOB";
            case Types.CLOB:
                return "CLOB";
            case Types.OTHER:
                return "OTHER";
            case Types.BIT:
                return "BIT";
            case Types.TINYINT:
                return "TINYINT";
            default:
                return "UNKNOWN (" + dataType + ")";
        }
    }
    static public BigDecimal getBigDecimalValue(Object paramValue) throws SQLException {
        BigDecimal tmpbd;

        if (paramValue instanceof Long) {
            tmpbd = BigDecimal.valueOf(((Long) paramValue).longValue());
        } else if (paramValue instanceof Integer) {
            tmpbd = BigDecimal.valueOf(((Integer) paramValue).longValue());
        } else if (paramValue instanceof BigDecimal) {
            tmpbd = (BigDecimal) paramValue;
        } else if (paramValue instanceof String) {
            String sVal = (String) paramValue;
            if (sVal.equals("true") == true) {
                sVal = "1";
            } else if (sVal.equals("false") == true) {
                sVal = "0";
            }
            tmpbd = new BigDecimal(sVal);
        } else if (paramValue instanceof Float) {
            tmpbd = new BigDecimal(paramValue.toString());
        } else if (paramValue instanceof Double) {
            tmpbd = new BigDecimal(((Double) paramValue).toString());
        } else if (paramValue instanceof Boolean) {
            tmpbd = BigDecimal.valueOf(((((Boolean) paramValue).booleanValue() == true) ? 1 : 0));
        } else if (paramValue instanceof Byte) {
            tmpbd = BigDecimal.valueOf(((Byte) paramValue).longValue());
        } else if (paramValue instanceof Short) {
            tmpbd = BigDecimal.valueOf(((Short) paramValue).longValue());
        } else if (paramValue instanceof Integer) {
            tmpbd = BigDecimal.valueOf(((Integer) paramValue).longValue());
            // For LOB Support SB: 10/25/2004
            /*
             * else if (paramValue instanceof DataWrapper) tmpbd =
             * BigDecimal.valueOf(((DataWrapper)paramValue).longValue);
             */
        } else {
            throw new SQLException("object_type_not_supported");
        }
        return tmpbd;
    } // end getBigDecimalValue

    static public BigDecimal convertSQLBigNumToBigDecimal(ByteBuffer sourceData, int len, int scale, boolean isUnSigned) {
        String strVal = ""; // our final String
        boolean negative = false;

        // we need the data in an array which can hold UNSIGNED 16 bit values
        // in java we dont have unsigned datatypes so 32-bit signed is the best
        // we can do
        int[] dataInShorts = new int[len / 2];
        for (int i = 0; i < dataInShorts.length; i++){
            dataInShorts[i] = ByteBufferUtils.extractUShort(sourceData); // copy
        // the
        // data
            LOG.debug("dataInShorts[" + i + "] :" + dataInShorts[i]);
        }
        if (isUnSigned == false){
            if ((dataInShorts[dataInShorts.length - 1] & 0xFF00) > 0){
                negative = ((dataInShorts[dataInShorts.length - 1] & 0x8000) > 0);
                dataInShorts[dataInShorts.length - 1] &= 0x7FFF; // force sign to 0, continue
            }
            else {
                negative = ((dataInShorts[dataInShorts.length - 1] & 0x0080) > 0);
                dataInShorts[dataInShorts.length - 1] &= 0xFF7F; // force sign to 0, continue
            }
            // normally
        }

        int curPos = dataInShorts.length - 1; // start at the end
        while (curPos >= 0 && dataInShorts[curPos] == 0)
            // get rid of any trailing 0's
            curPos--;

        int remainder = 0;
        long temp; // we need to use a LONG since we will have to hold up to
        // 32-bit UNSIGNED values

        // we now have the huge value stored in 2 bytes chunks
        // we will divide by 10000 many times, converting the remainder to
        // String
        // when we are left with a single chunk <10000 we will handle it using a
        // special case
        while (curPos >= 0 || dataInShorts[0] >= 10000) {
            // start on the right, divide the 16 bit value by 10000
            // use the remainder as the upper 16 bits for the next division
            for (int j = curPos; j >= 0; j--) {
                // these operations got messy when java tried to infer what size
                // to store the value in
                // leave these as separate operations for now...always casting
                // back to a 64 bit value to avoid sign problems
                temp = remainder;
                temp &= 0xFFFF;
                temp = temp << 16;
                temp += dataInShorts[j];

                dataInShorts[j] = (int) (temp / 10000);
                remainder = (int) (temp % 10000);
            }

            // if we are done with the current 16bits, move on
            if (dataInShorts[curPos] == 0)
                curPos--;

            // go through the remainder and add each digit to the final String
            for (int j = 0; j < 4; j++) {
                strVal = (remainder % 10) + strVal;
                remainder /= 10;
            }
        }

        // when we finish the above loop we still have 1 <10000 value to include
        remainder = dataInShorts[0];
        for (int j = 0; j < 4; j++) {
            strVal = (remainder % 10) + strVal;
            remainder /= 10;
        }

        BigInteger bi = new BigInteger(strVal); // create a java BigInt
        if (negative && isUnSigned == false)
            bi = bi.negate();

        return new BigDecimal(bi, scale); // create a new BigDecimal with the
        // descriptor's scale
    }
    static public byte[] formatSqlT4Output(Descriptor2 dsc, byte[] sqlarray, long curOutPos, byte[] outValues, ByteOrder bo) throws UnsupportedEncodingException{

        ByteBuffer bb = null;
        byte[] dst = null;
        int len = 0;
        int offset = 0;
        int insNull = 0;

        String[] stDate = null;
        String[] stTime = null;
        String[] stTimestamp = null;
        String[] stNanos = null;
        Integer year = 0;
        Integer month = 0;
        Integer day = 0;
        Integer hour = 0;
        Integer minutes = 0;
        Integer seconds = 0;
        Integer nanos = 0;

        String setString = "";
        short setShort = 0;
        int setInt = 0;
        long setLong = 0L;
        boolean setSign = false;
        String charSet = "";

        int precision = dsc.getPrecision();
        int scale = dsc.getScale();
        int datetimeCode = dsc.getDatetimeCode();
        int FSDataType = dsc.getFsDataType();
        int OdbcDataType = dsc.getOdbcDataType();
        int dataCharSet = dsc.getSqlCharset();
        int length = dsc.getMaxLen();
        int dataType = dsc.getDataType();

        if(dataCharSet == SqlUtils.SQLCHARSETCODE_UNICODE)
            charSet = "UTF-16LE";
        else
            charSet = SqlUtils.getCharsetName(dataCharSet);

        len = sqlarray.length;
        ByteBuffer tb = ByteBuffer.wrap(sqlarray).order(bo);

        if(LOG.isDebugEnabled())
            LOG.debug("formatSqlT4Output: -----------");

        switch(dataType){
        case ServerConstants.SQLTYPECODE_CHAR:
            if(LOG.isDebugEnabled())
                LOG.debug("formatSqlT4Output: SQLTYPECODE_CHAR :" + Arrays.toString(sqlarray));
            break;
        case ServerConstants.SQLTYPECODE_VARCHAR:
        case ServerConstants.SQLTYPECODE_VARCHAR_LONG:
            if(LOG.isDebugEnabled())
                LOG.debug("formatSqlT4Output: SQLTYPECODE_VARCHAR/VARCHAR_LONG :" + Arrays.toString(sqlarray));
            break;
        case ServerConstants.SQLTYPECODE_VARCHAR_WITH_LENGTH:       //-601
            if( length > Short.MAX_VALUE ){
                len = tb.getInt() + 4;
            } else {
                len = tb.getShort() + 2;
            }
            if(LOG.isDebugEnabled())
                LOG.debug("formatSqlT4Output: SQLTYPECODE_VARCHAR :" + Arrays.toString(sqlarray));
            break;
        case ServerConstants.SQLTYPECODE_DATETIME:
            LOG.debug("formatSqlT4Output: SQLTYPECODE_DATETIME :" + Arrays.toString(sqlarray));
            switch(datetimeCode){
                case ServerConstants.SQLDTCODE_DATE:
                case ServerConstants.SQLDTCODE_TIME:
                case ServerConstants.SQLDTCODE_TIMESTAMP:
                    len = tb.getShort();
                    dst = new byte[len];
                    System.arraycopy(sqlarray, 2, dst, 0, len);
                    setString = new String(dst,"UTF8");
                    tb.clear();
                    switch(datetimeCode){
                        case ServerConstants.SQLDTCODE_DATE:
                            stDate = setString.split("-");
                            year = Integer.valueOf(stDate[0]);
                            month = Integer.valueOf(stDate[1]);
                            day = Integer.valueOf(stDate[2]);
                            tb.putShort(year.shortValue());
                            tb.put(month.byteValue());
                            tb.put(day.byteValue());
                            break;
                        case ServerConstants.SQLDTCODE_TIME:
                            stTime = setString.split(":");
                            hour = Integer.valueOf(stTime[0]);
                            minutes = Integer.valueOf(stTime[1]);
                            seconds = Integer.valueOf(stTime[2]);
                            tb.put(hour.byteValue());
                            tb.put(minutes.byteValue());
                            tb.put(seconds.byteValue());
                            break;
                        case ServerConstants.SQLDTCODE_TIMESTAMP:
                            stTimestamp = setString.split(" ");
                            stDate = stTimestamp[0].split("-");
                            stNanos = stTimestamp[1].split("\\.");
                            stTime = stNanos[0].split(":");
                            year = Integer.valueOf(stDate[0]);
                            month = Integer.valueOf(stDate[1]);
                            day = Integer.valueOf(stDate[2]);
                            hour = Integer.valueOf(stTime[0]);
                            minutes = Integer.valueOf(stTime[1]);
                            seconds = Integer.valueOf(stTime[2]);
                            nanos = Integer.valueOf(stNanos[1]);
                            tb.putShort(year.shortValue());
                            tb.put(month.byteValue());
                            tb.put(day.byteValue());
                            tb.put(hour.byteValue());
                            tb.put(minutes.byteValue());
                            tb.put(seconds.byteValue());
                            tb.putInt(nanos);
                            break;
                        case ServerConstants.SQLDTCODE_MPDATETIME:
                            break;
                    }
                default:
            }
            break;
        case ServerConstants.SQLTYPECODE_INTERVAL:
            if(LOG.isDebugEnabled())
                LOG.debug("formatSqlT4Output: SQLTYPECODE_INTERVAL :" + Arrays.toString(sqlarray));
            len = tb.getShort();
            dst = new byte[len];
            System.arraycopy(sqlarray, 2, dst, 0, len);
            Arrays.fill(sqlarray, (byte)0);
            tb.clear();
            if(dst[0] != '-'){
                len++;
                tb.put((byte)' ');
            }
            tb.put(dst, 0, dst.length);
            if(LOG.isDebugEnabled())
                LOG.debug("formatSqlT4Output: sqlarray :" + Arrays.toString(sqlarray));
            break;
        case ServerConstants.SQLTYPECODE_INTEGER:                    //4
            if(LOG.isDebugEnabled())
                LOG.debug("formatSqlT4Output: SQLTYPECODE_INTEGER :" + Arrays.toString(sqlarray));
            break;
        case ServerConstants.SQLTYPECODE_INTEGER_UNSIGNED:
            if(LOG.isDebugEnabled())
                LOG.debug("formatSqlT4Output: SQLTYPECODE_INTEGER_UNSIGNED :" + Arrays.toString(sqlarray));
            break;
        case ServerConstants.SQLTYPECODE_SMALLINT:
            if(LOG.isDebugEnabled())
                LOG.debug("formatSqlT4Output: SQLTYPECODE_SMALLINT :" + Arrays.toString(sqlarray));
            break;
        case ServerConstants.SQLTYPECODE_SMALLINT_UNSIGNED:
            if(LOG.isDebugEnabled())
                LOG.debug("formatSqlT4Output: SQLTYPECODE_SMALLINT_UNSIGNED :" + Arrays.toString(sqlarray));
            break;
        case ServerConstants.SQLTYPECODE_LARGEINT:
            if(LOG.isDebugEnabled())
                LOG.debug("formatSqlT4Output: SQLTYPECODE_LARGEINT :" + Arrays.toString(sqlarray));
            break;
        case ServerConstants.SQLTYPECODE_DECIMAL:
        case ServerConstants.SQLTYPECODE_DECIMAL_UNSIGNED:
            if(LOG.isDebugEnabled())
                LOG.debug("formatSqlT4Output: SQLTYPECODE_DECIMAL :" + Arrays.toString(sqlarray));
            break;
        case ServerConstants.SQLTYPECODE_IEEE_REAL:                    //6
            if(LOG.isDebugEnabled())
                LOG.debug("formatSqlT4Output: SQLTYPECODE_IEEE_REAL :" + Arrays.toString(sqlarray));
            break;
        case ServerConstants.SQLTYPECODE_IEEE_FLOAT:                   //7
            if(LOG.isDebugEnabled())
                LOG.debug("formatSqlT4Output: SQLTYPECODE_IEEE_FLOAT :" + Arrays.toString(sqlarray));
            break;
        case ServerConstants.SQLTYPECODE_IEEE_DOUBLE:                  //8
            if(LOG.isDebugEnabled())
                LOG.debug("formatSqlT4Output: SQLTYPECODE_IEEE_DOUBLE :" + Arrays.toString(sqlarray));
            break;
        case ServerConstants.SQLTYPECODE_NUMERIC:
        case ServerConstants.SQLTYPECODE_NUMERIC_UNSIGNED:
            if(LOG.isDebugEnabled())
                LOG.debug("formatSqlT4Output: SQLTYPECODE_NUMERIC :" + Arrays.toString(sqlarray));
            switch (len) {
            case 2:
                setShort = tb.getShort();
                setLong = setShort;
                if(setLong < 0){
                    setLong = -1L * setLong;
                    setSign = true;
                    tb.clear();
                    tb.put((byte) ((setLong) & 0xff));
                    tb.put((byte) (((setLong >>> 8) | 0x80) & 0xff));
                }
                break;
            case 4:
                setInt = tb.getInt();
                setLong = setInt;
                if(setLong < 0){
                    setLong = -1L * setLong;
                    setSign = true;
                    tb.clear();
                    tb.put((byte) ((setLong) & 0xff));
                    tb.put((byte) ((setLong >>> 8) & 0xff));
                    tb.put((byte) ((setLong >>> 16) & 0xff));
                    tb.put((byte) (((setLong >>> 24) | 0x80) & 0xff));
                }
                break;
            case 8:
                setLong = tb.getLong();
                if(setLong < 0){
                    setLong = -1L * setLong;
                    setSign = true;
                    tb.clear();
                    tb.put((byte) ((setLong) & 0xff));
                    tb.put((byte) ((setLong >>> 8) & 0xff));
                    tb.put((byte) ((setLong >>> 16) & 0xff));
                    tb.put((byte) ((setLong >>> 24) & 0xff));
                    tb.put((byte) ((setLong >>> 32) & 0xff));
                    tb.put((byte) ((setLong >>> 40) & 0xff));
                    tb.put((byte) ((setLong >>> 48) & 0xff));
                    tb.put((byte) (((setLong >>> 56) | 0x80) & 0xff));
                }
                break;
            }
            break;
        case ServerConstants.SQLTYPECODE_DECIMAL_LARGE:
        case ServerConstants.SQLTYPECODE_DECIMAL_LARGE_UNSIGNED:
        case ServerConstants.SQLTYPECODE_BIT:
        case ServerConstants.SQLTYPECODE_BITVAR:
        case ServerConstants.SQLTYPECODE_BPINT_UNSIGNED:
        default:
            if(LOG.isDebugEnabled())
                LOG.debug("formatSqlT4Output: default :" + Arrays.toString(sqlarray));
            break;
        }
        if(LOG.isDebugEnabled()){
            LOG.debug("formatSqlT4Output: offset :" + offset);
            LOG.debug("formatSqlT4Output: curOutPos :" + curOutPos);
            LOG.debug("formatSqlT4Output: len :" + len);
        }
        System.arraycopy(sqlarray, offset, outValues, (int)curOutPos, len);
        return outValues;
    }
}


text:
<meta charset="UTF-8">
<title>DocumentsProcessorRunner.log - biomedicus-core</title>
<link rel="stylesheet" href="../../../style.css">

biomedicus-core / edu.umn.biomedicus.framework / DocumentsProcessorRunner / log

log

val log: Logger


text:
package com.centzy.badger.api;

import com.centzy.badger.core.BadgerEntityDescriptor;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.protobuf.Message;

/**
 * @author Peter Edge (peter@locality.com).
 */
public class BadgerArchiveEntity<M extends Message> {

  private final BadgerEntityDescriptor<M> badgerEntityDescriptor;
  private final String entityId;

  public BadgerArchiveEntity(BadgerEntityDescriptor<M> badgerEntityDescriptor, String entityId) {
    this.badgerEntityDescriptor = Preconditions.checkNotNull(badgerEntityDescriptor);
    this.entityId = Preconditions.checkNotNull(entityId);
  }

  public BadgerEntityDescriptor<M> getBadgerEntityDescriptor() {
    return badgerEntityDescriptor;
  }

  public String getEntityId() {
    return entityId;
  }

  @Override
  public int hashCode() {
    return Objects.hashCode(badgerEntityDescriptor, entityId);
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null || getClass() != obj.getClass()) {
      return false;
    }
    final BadgerArchiveEntity other = (BadgerArchiveEntity) obj;
    return Objects.equal(this.badgerEntityDescriptor, other.badgerEntityDescriptor) && Objects.equal(this.entityId, other.entityId);
  }

  @Override
  public String toString() {
    return Objects.toStringHelper(this)
        .add("badgerEntityDescriptor", badgerEntityDescriptor)
        .add("entityId", entityId)
        .toString();
  }
}


text:
from __future__ import division
from math import pi as M_PI  # used by many snippets
import sys

import cairo
if not cairo.HAS_SVG_SURFACE:
    raise SystemExit ('cairo was not compiled with SVG support')

from snippets import snip_list, snippet_normalize

width_in_inches, height_in_inches = 2, 2
width_in_points, height_in_points = width_in_inches * 72, height_in_inches * 72
width, height = width_in_points, height_in_points # used by snippet_normalize()

def do_snippet (snippet):
    if verbose_mode:
        print 'processing %s' % snippet,

    filename = 'snippets/%s.svg' % snippet
    surface = cairo.SVGSurface (filename, width_in_points, height_in_points)
    cr = cairo.Context (surface)

    cr.save()
    try:
        execfile ('snippets/%s.py' % snippet, globals(), locals())
    except:
        exc_type, exc_value = sys.exc_info()[:2]
        print >> sys.stderr, exc_type, exc_value
    else:
        cr.restore()
        cr.show_page()
        surface.finish()

    if verbose_mode:
        print

if __name__ == '__main__':
    verbose_mode = True
    if len(sys.argv) > 1 and sys.argv[1] == '-s':
        verbose_mode = False
        del sys.argv[1]

    if len(sys.argv) > 1: # do specified snippets
        snippet_list = sys.argv[1:]
    else:                 # do all snippets
        snippet_list = snip_list

    for s in snippet_list:
        do_snippet (s)


text:
var testFiles = [];

// Used to convert paths to find test files
var pathToModule = function(path) {
    return path.replace(/^\/base\//, "../../").replace(/\.js$/, '');
};

// Loop over each file karma is aware of and check which are test file
Object.keys(window.__karma__.files).forEach(function(file) {
    if (/\.spec\.js$/.test(file)) {
        testFiles.push(pathToModule(file));
    }
});

// The nitty gritty
requirejs.config({
    baseUrl: "/base/www/js/",

    paths: {
        // If you want to actually test your modules, you put those here.
        // Just like a standard requirejs config
    },

    deps: testFiles,

    // kickoff jasmine
    callback: window.__karma__.start
});


text:
import os
import giphypop
import random
import re
import subprocess
import requests
import traceback
import database
import roast
import spotify
import urban
import oxford
from oxford import *
from urban import *
from roast import *
from database import *
from spotify import *
from compliments import generate_compliment
from libs import *
from help import help_text
from os.path import join, dirname
from dotenv import load_dotenv
from flask import Flask
from flask import request
app = Flask(__name__)

dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)

gif = giphypop.Giphy()
admin_sender_id = os.environ.get("ADMIN_SENDER_ID")
access_token = os.environ.get("GROUPME_ACCESS_TOKEN")
ball_responses=["It is certain.", "It is decidedly so.", "Without a doubt.", "Yes - definitely.", "You may rely on it.",
 "As I see it, yes.", "Most likely.", "Outlook is good.", "Yes.", "Signs point to yes.", "Reply hazy, try again.",
 "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.",
 "Don't count on it.", "My reply is no.", "My sources say no.", "No.", "Absolutely the frik not.", "Outlook not so good.",
 "Very doubtful."]
profanity=["damn", "shit", "fuck", "bitch", "dammit"]

@app.route('/callback/get', methods=['GET'])
def get_access_token():
    try:
        print(request.args.get('access_token',''))
        return 'OK'
    except:
        return 'Not OK'

@app.route('/callback/<bot_id>', methods=['POST'])
def parse_messages(bot_id):
    try:

        # Grab message info
        message = request.get_json()

        # Ignore non user messages (aka bots)
        if message['sender_type'] != "user":
            return 'OK'

        """ Remembering Stuff """
        # Update group and person
        if message['sender_type'] == "user":
            add_person(message['sender_id'], message['name'])
            add_group(message['group_id'], bot_id)

        """ Admin Actions """

        # Ventriloquism
        if message['text'].startswith("/dummy"):
            if message['sender_id'] == admin_sender_id:
                print("Start dummy")
                search = re.search(r"/dummy (\S*)\s?(.*)?$", message['text'])
                (nickname, msg) = search.groups('test post pls ignore')
                if(nickname == 'help'):
                    dummies = show_all_dummy()
                    msg = "All available dummies:\n"
                    for x in dummies:
                        msg += x[0] + "\n"
                    dummy_bot = bot_id
                else:
                    dummy_bot = find_bot_nname(nickname)
                    if not dummy_bot:
                        dummy_bot = bot_id
                        msg = "No group with nickname '" + nickname + "'"
                    else:
                        dummy_bot = dummy_bot[0][0]
                print("Dummy msg: "+ msg)
                print("Dummy bot: " + dummy_bot)
            else:
                dummy_bot = bot_id
                msg = "No u."
            post_text(msg, dummy_bot)

        # Silence bot
        if message['text'].startswith("/botoff") and message['sender_id'] == admin_sender_id:
            post_text(":((", bot_id)
            silence_awaken_bot(bot_id, True)
        if message['text'].startswith("/boton") and message['sender_id'] == admin_sender_id:
            silence_awaken_bot(bot_id, False)
            post_text("thx bb :)", bot_id)

        # Testing command
        if message['text'].startswith("/test") and message['sender_id'] == admin_sender_id:
            post_text(get_top_song(bot_id), bot_id)

        """ Actions for all groups """

        # Say hello to anyone that says "Hi"
        if re.search(r"\bhi\b", message['text'].lower()):
            post_text("Hi " + message['name'].split(" ")[0] + "!", bot_id)

        # Help text
        if message['text'].lower().startswith("/help"):
            bot_name = request.args.get('name','')
            msg = "Hi " + message['name'].split(" ")[0] + ", I'm " + bot_name + "! \n" + help_text
            post_text_mention(msg, bot_id, message['sender_id'])

        # Post gif from Giphy
        if message['text'].lower().startswith("/gif"):
            search = re.search(r"/gif (.*?)( \d+)?$", message['text'])
            (gif_search, num) = search.groups('1')
            if int(num) < 20:
                num = min(int(num), 5)
                for i in range(int(num)):
                    post_text(gif.translate(gif_search).media_url, bot_id)
            else:
                post_text_mention("Can you not.", bot_id, message['sender_id'])

        # Clap a bunch
        if message['text'].lower().startswith("/clap"):
            msg = message['text'][5:]
            msg = msg.upper()
            clap = '\U0001F44F'
            if message['sender_id'] == admin_sender_id:
                clap += '\U0001F3FF'
            msg = clap.join(msg.split())
            post_text(msg, bot_id)

        # Hurr Durr
        if message['text'].lower().startswith("/durr"):
            msg_row = find_last_msg(message['group_id'])
            if msg_row:
                msg = msg_row[0] + " "
                sender = msg_row[1].lower()
                lastSenderId = msg_row[2]
                low = (x.lower() for x in msg[0::2])
                upp = (x.upper() for x in msg[1::2])
                msg = ''.join(a + b for a, b in zip(low, upp))
                sender = re.sub(r"\s", "_", sender)
                durr_url = "https://memegen.link/spongebob/hurr_durr_i'm_" + sender + "/and_i_just_want_to_say.jpg?watermark=none&height=600&width=600"
                if lastSenderId != admin_sender_id or message['sender_id'] == admin_sender_id:
                    post_text(durr_url, bot_id)
                    post_text_mention(msg, bot_id, lastSenderId)
                else:
                    post_text_mention("I'm sorry " + message['name'].split(" ")[0] + ", I'm afraid I can't do that.", bot_id, message['sender_id'])

        # Jokes
        if message['text'].lower().startswith("/joke"):
            headers = {'Accept': 'text/plain'}
            joke = requests.get("https://icanhazdadjoke.com", headers=headers)
            joke.raise_for_status()
            post_text(joke.content.decode("UTF-8"), bot_id)

        # Random song
        if message['text'].lower().startswith("/randsong"):
            post_rand_song(bot_id)

        # Dice
        if message['text'].lower().startswith("/dice"):
            num = int(message['text'][5:])
            rand = random.randint(1, num)
            post_text(u'\U0001F3B2: ' + str(rand), bot_id)

        # @all
        if re.search(r"@all\b", message['text'].lower()):
            message_info = get_group_info(message['group_id'])
            user_ids = []
            for x in message_info['response']['members']:
                user_ids.append(x['user_id'])
            txt = "^^HEY LISTEN, " + message['name'].split(" ")[0].upper() + " SAID SOMETHING IMPORTANT^^"
            post_text_mention(txt, bot_id, user_ids)

        # Shakesperian roast
        if message['text'].lower().startswith("/roast"):
            txt = generate_insult()
            if len(message['text']) > 6:
                victim = message['text'][7:].strip()
                user_id = -1
                print("Roasting: " + victim)
                message_info = get_group_info(message['group_id'])
                for x in message_info['response']['members']:
                    if victim.lower() in x['nickname'].lower():
                        user_id = x['user_id']
                if user_id == -1:
                    post_text("Couldn't find anyone by that name.", bot_id)
                else:
                    post_text_mention(txt, bot_id, user_id)
            else:
                post_text_mention("I need someone to roast dingus.", bot_id, message['sender_id'])

        # Compliments
        if message['text'].lower().startswith('/flatter'):
            if len(message['text']) > 8:
                recipient = message['text'][9:].strip()
                user_id = -1
                print("Compliments: " + recipient)
                message_info = get_group_info(message['group_id'])
                for x in message_info['response']['members']:
                    if recipient.lower() in x['nickname'].lower():
                        user_id = x['user_id']
                        nickname = x['nickname'].split(" ")[0]
                        txt = nickname + ", " + generate_compliment()
                if user_id == -1:
                    post_text("Couldn't find anyone by that name.", bot_id)
                else:
                    post_text_mention(txt, bot_id, user_id)
            else:
                post_text_mention("I need someone to compliment dingus.", bot_id, message['sender_id'])

        # Terminate a user
        if message['text'].lower().startswith("/terminate"):
            victim = message['text'][11:].strip()
            member_id = -1
            user_id = -1
            print(victim)
            message_info = get_group_info(message['group_id'])
            for x in message_info['response']['members']:
                if victim.lower() in x['nickname'].lower():
                    member_id = x['id']
                    user_id = x['user_id']
            if user_id == -1:
                post_text("No one to terminate by that name", bot_id)
            elif user_id == admin_sender_id:
                post_text("LEAVE MY MAKER ALONE", bot_id)
            else:
                post_text_mention("BYE FELICIA.", bot_id, user_id)
                remove_user(message['group_id'], member_id, bot_id)

        # 8Ball
        if message['text'].lower().startswith("/8ball"):
            question = message['text'][7:].strip()
            if len(question) <= 0:
                answer = "Can't answer a blank question."
            else:
                answer = random.choice(ball_responses)
            post_text_mention(answer, bot_id, message['sender_id'])

        # Coin flip
        if message['text'].lower().startswith("/flip"):
            coin = random.randint(1,2)
            if coin == 1:
                result = "Heads."
            else:
                result = "Tails."
            post_text(result, bot_id)

        # Oxford Dictionary
        if message['text'].lower().startswith("/define"):
            word = message['text'][8:].strip()
            if len(word) <= 0:
                define = "Don't have anything to define."
            else:
                define = define_word(word)
            post_text(define, bot_id)

        # Urban Dictionary
        if message['text'].lower().startswith("/urban"):
            term = message['text'][7:].strip()
            if len(term) <= 0:
                define = "Don't have anything to define."
            else:
                define = urban_define(term)
            post_text(define, bot_id)

        # Watch ur profanity - EHH
        """if any(word in message['text'].lower() for word in profanity):
            post_text("https://media.giphy.com/media/4vYksifnc7Sw/giphy.gif", bot_id)"""

        """ Store last message """
        # Save msg and update group and person
        if message['sender_type'] == "user":
            store_last_msg(message['group_id'], message['id'], message['text'], message['name'], message['sender_id'])
            add_person(message['sender_id'], message['name'])
            add_group(message['group_id'], bot_id)

        return 'OK'
    except:
            post_text(u'\U0001F916\u2620: ' + traceback.format_exc(), bot_id)
            return 'Not OK'


text:
<link rel="stylesheet" type="text/css" href="__STATIC__/weixin/css/dingcan/css2.css"/>

		<volist name='keyinfo' id='item' >

规则:{$item.kename}

关键字:{$item.kyword}

            	<if condition='$item.type eq 1'>
回复:文本消息
<else/>
回复:图文消息
</if>

      </volist>

    	上传图片

	<input type="button" value="上传图片" class="uploadbtn"/>
    <form action="{:U('keyword/ajaxupload')}" method="post" id="zsc_myform" enctype="multipart/form-data" target="yframe">
    	<input type="file" value="上传图片" class="uploadbtn" style="position:absolute; top:75px; left:20px; filter:alpha(pacity=0);opacity:0; z-index:999;" onchange="zsc_upload()" name="image[]" />大小不超过1M ,仅限png,jpeg,jpg
        <input type="hidden" name="sub" value="submit" />
    </form>

<input type="button" class="submit" id="zsc_surebtn" />

    正在上传...


text:
class Tabs {

  constructor() {
    this.tabs = browser.tabs;
  }

  get(tabId) {
    return this.tabs.get(tabId);
  }

  create(options = {}) {
    return this.tabs.create(options);
  }

  update(tabId, options = {}) {
    return this.tabs.update(tabId, options);
  }

  remove(tabId) {
    return this.tabs.remove(tabId);
  }

  query(queryInfo = {}) {
    return this.tabs.query(queryInfo);
  }
}

export default new Tabs();


text:
using NldbApi.Interfaces;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Npgsql;
using NldbApi.Models;
using NldbApi.Infrastructure;
using System.Data.Common;
using System.Linq;

namespace NldbApi.Repositories
{
    public class WatchedVideoRepository : IWatchedVideoRepository
    {
        private DefaultDatabaseConnection _connection;
        private IdentityDatabaseConnection _identityConnection;
        private IVideoRepository _videoRepository;

        public WatchedVideoRepository(DefaultDatabaseConnection connection, IVideoRepository videoRepository, IdentityDatabaseConnection identityConnection)
        {
            _connection = connection;
            _videoRepository = videoRepository;
            _identityConnection = identityConnection;
        }

        public async Task<int> AddWatchedVideoForUserAsync(string videoId, string sub, DateTime watchtime)
        {
            bool videoExists = await _videoRepository.GetVideoByIdAsync(videoId) != null;

            int dbChanges = 0;

            if (sub == null)
            {

            }

            if (videoExists)
            {
                bool watchedAlready = await CheckIfUserWatchedVideoAlreadyAsync(videoId, sub);

                if (watchedAlready)
                {
                    return await IncreaseViewCountForUserAsync(videoId, sub, watchtime);
                }

                using (NpgsqlConnection con = await _connection.GetConnectionAsync())
                {
                    string query = "INSERT INTO watchedvideos (video, sub, watchtime, viewcount)"
                        + " VALUES (@vid, @sub, @time, @count)";

                    using (NpgsqlCommand q = new NpgsqlCommand(query, con))
                    {
                        q.Parameters.AddWithValue("@vid", videoId);
                        q.Parameters.AddWithValue("@sub", sub);
                        q.Parameters.AddWithValue("@time", watchtime);
                        q.Parameters.AddWithValue("@count", 1);

                        dbChanges = await q.ExecuteNonQueryAsync();
                    }
                }
            }

            return dbChanges;
        }

        public async Task<bool> CheckIfUserWatchedVideoAlreadyAsync(string videoId, string sub)
        {
            bool watchedAlready = false;

            using (NpgsqlConnection con = await _connection.GetConnectionAsync())
            {
                string query = "SELECT * FROM watchedvideos"
                    + " WHERE sub = @sub"
                    + " AND video = @vid";

                using (NpgsqlCommand q = new NpgsqlCommand(query, con))
                {
                    q.Parameters.AddWithValue("@sub", sub);
                    q.Parameters.AddWithValue("@vid", videoId);

                    await q.ExecuteNonQueryAsync();

                    using (DbDataReader reader = await q.ExecuteReaderAsync())
                    {
                        if (reader.HasRows)
                        {
                            watchedAlready = true;
                        }
                    }
                }
            }

            return watchedAlready;
        }

        public async Task<List<WatchedVideo>> GetWatchedVideosForUser(string sub)
        {
            List<WatchedVideo> videos = new List<WatchedVideo>();

            string query =
                "SELECT DISTINCT videos.youtubeid, videos.upanddownvoreratio, videos.title, videos.thumbnail,"
                    + " videos.releasedate, videos.duration, videos.iscompleted, videos.numberofruns,"
                    + " AVG(ratings.power), AVG(ratings.insanity), AVG(ratings.enjoyment), watchedvideos.viewcount, videos.requiresupdate, watchedvideos.watchtime, videos.seed"
                    + " FROM videos, ratings, watchedvideos"
                    + " WHERE videos.youtubeid = ratings.video"
                    + " AND videos.youtubeid = watchedvideos.video"
                    + " AND watchedvideos.sub = @sub"
                    + " GROUP BY videos.id";

            using (NpgsqlConnection con = await _connection.GetConnectionAsync())
            {
                using (NpgsqlCommand q = new NpgsqlCommand(query, con))
                {
                    q.Parameters.AddWithValue("@sub", sub);

                    await q.ExecuteNonQueryAsync();

                    using (DbDataReader reader = await q.ExecuteReaderAsync())
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                videos.Add(new WatchedVideo
                                {
                                    YoutubeId = reader.GetString(0),
                                    UpAndDownVoteRatio = reader.IsDBNull(1) ? null : (double?)reader.GetDouble(1),
                                    Title = reader.GetString(2),
                                    Thumbnail = reader.GetString(3),
                                    Releasedate = reader.GetDateTime(4),
                                    Duration = reader.IsDBNull(5) ? null : (int?)reader.GetInt32(5),
                                    IsCompleted = reader.GetBoolean(6),
                                    NumberOfRuns = reader.IsDBNull(7) ? null : (int?)reader.GetInt32(7),
                                    Power = reader.IsDBNull(8) ? null : (double?)reader.GetDouble(8),
                                    Insanity = reader.IsDBNull(9) ? null : (double?)reader.GetDouble(9),
                                    Enjoyment = reader.IsDBNull(10) ? null : (double?)reader.GetDouble(10),
                                    ViewCount = reader.GetInt32(11),
                                    RequiresUpdate = reader.GetBoolean(12),
                                    LastWatched = reader.GetDateTime(13),
                                    Seed = reader.IsDBNull(14) ? null : reader.GetString(14)
                                });
                            }
                        }
                    }
                }
            }
            return videos;
        }

        public async Task<int> IncreaseViewCountForUserAsync(string videoId, string sub, DateTime watchtime)
        {
            int dbChanges = 0;

            using (NpgsqlConnection con = await _connection.GetConnectionAsync())
            {
                string query = "UPDATE watchedvideos"
                    + " SET viewcount = viewcount + 1, watchtime = @time"
                    + " WHERE video = @vid"
                    + " AND sub = @sub";

                using (NpgsqlCommand q = new NpgsqlCommand(query, con))
                {
                    q.Parameters.AddWithValue("@vid", videoId);
                    q.Parameters.AddWithValue("@sub", sub);
                    q.Parameters.AddWithValue("@time", watchtime);

                    dbChanges = await q.ExecuteNonQueryAsync();
                }
            }

            return dbChanges;
        }

        public async Task<IEnumerable<string>> GetUsersWhoWatchedVideoAsync(string videoId)
        {
            List<string> usernames = new List<string>();
            List<string> subs = new List<string>();

            using (NpgsqlConnection con = await _connection.GetConnectionAsync())
            {
                string query = "SELECT sub"
                    + " FROM watchedvideos"
                    + " WHERE video = @video";

                using (NpgsqlCommand q = new NpgsqlCommand(query, con))
                {
                    q.Parameters.AddWithValue("@video", videoId);

                    await q.ExecuteNonQueryAsync();

                    using (DbDataReader reader = await q.ExecuteReaderAsync())
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                subs.Add(reader.GetString(0));
                            }
                        }
                    }
                }
            }

            using (NpgsqlConnection con = await _identityConnection.GetConnectionAsync())
            {
                string query = $"SELECT \"UserName\" FROM \"AspNetUsers\" WHERE \"Id\" IN ('{string.Join("', '", subs)}')";

                using (NpgsqlCommand q = new NpgsqlCommand(query, con))
                {
                    q.Parameters.AddWithValue("@ids", subs);

                    await q.ExecuteNonQueryAsync();

                    using (DbDataReader reader = await q.ExecuteReaderAsync())
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                usernames.Add(reader.GetString(0));
                            }
                        }
                    }
                }
            }

            return usernames;
        }

        public async Task<List<TopContributor>> GetTopContributors(int amount)
        {
            List<TopContributor> contributors = new List<TopContributor>();

            using (NpgsqlConnection con = await _connection.GetConnectionAsync())
            {
                string query =
                    "SELECT"
                        + " sub,"
                        + " COUNT(*) as amount"
                    + " FROM"
                        + " watchedvideos"
                    + " GROUP BY"
                        + " sub"
                    + " ORDER BY"
                        + " amount DESC"
                    + " LIMIT @amount";

                using (NpgsqlCommand q = new NpgsqlCommand(query, con))
                {
                    q.Parameters.AddWithValue("@amount", amount);

                    await q.ExecuteNonQueryAsync();

                    using (DbDataReader reader = await q.ExecuteReaderAsync())
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                contributors.Add(new TopContributor
                                {
                                    Sub = reader.GetString(0),
                                    NumberOfContributedVideos = reader.GetInt32(1)
                                });
                            }
                        }
                    }
                }
            }

            using (NpgsqlConnection con = await _identityConnection.GetConnectionAsync())
            {
                string joinedSubs = string.Empty;
                int numberOfSubs = contributors.Count();

                for (int i = 0; i < numberOfSubs; i++)
                {
                    joinedSubs += "'" + contributors[i].Sub + "'";

                    if (i != numberOfSubs - 1)
                    {
                        joinedSubs += ", ";
                    }
                }

                string query = "SELECT \"UserName\", \"Id\" FROM \"AspNetUsers\" WHERE \"Id\" IN (" + joinedSubs + ")";

                using (NpgsqlCommand q = new NpgsqlCommand(query, con))
                {
                    await q.ExecuteNonQueryAsync();

                    using (DbDataReader reader = await q.ExecuteReaderAsync())
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                contributors.FirstOrDefault(x => x.Sub == reader.GetString(1)).Name = reader.GetString(0);
                            }
                        }
                    }
                }
            }

            return contributors;
        }
    }

    public class TopContributor
    {
        public string Name { get; set; }
        public string Sub { get; set; }
        public int NumberOfContributedVideos { get; set; }
    }
}


text:
package org.apache.carbondata.examples

import java.io.File
import java.sql.{DriverManager, ResultSet, Statement}

import org.apache.hadoop.fs.Path
import org.apache.hadoop.fs.permission.{FsAction, FsPermission}
import org.apache.spark.sql.SparkSession

import org.apache.carbondata.common.logging.LogServiceFactory
import org.apache.carbondata.core.datastore.impl.FileFactory
import org.apache.carbondata.examples.util.ExampleUtils
import org.apache.carbondata.hive.test.server.HiveEmbeddedServer2

// scalastyle:off println
object HiveExample {

  private val driverName: String = "org.apache.hive.jdbc.HiveDriver"
  val rootPath = new File(this.getClass.getResource("/").getPath
                          + "../../../..").getCanonicalPath
  val projectLoc = s"$rootPath/examples/spark"
  System.setProperty("derby.system.home", s"$projectLoc")
  val metaStoreLoc = s"$projectLoc/metastore_db"
  val LOGGER = LogServiceFactory.getLogService(this.getClass.getCanonicalName)

  def main(args: Array[String]) {
    val sparkSession = ExampleUtils.createSparkSession("HiveExample")
    createCarbonTable(sparkSession)
    readFromHive
    System.exit(0)
  }

  def createCarbonTable(sparkSession: SparkSession): Unit = {

    sparkSession.sql("""DROP TABLE IF EXISTS HIVE_CARBON_EXAMPLE""".stripMargin)

    sparkSession.sql(
      s"""
         | CREATE TABLE HIVE_CARBON_EXAMPLE
         | (ID int,NAME string,SALARY double)
         | STORED AS carbondata
       """.stripMargin)

    var inputPath = FileFactory
      .getUpdatedFilePath(s"$rootPath/examples/spark/src/main/resources/sample.csv")

    sparkSession.sql(
      s"""
         | LOAD DATA LOCAL INPATH '$inputPath'
         | INTO TABLE HIVE_CARBON_EXAMPLE
       """.stripMargin)

    sparkSession.sql(
      s"""
         | LOAD DATA LOCAL INPATH '$inputPath'
         | INTO TABLE HIVE_CARBON_EXAMPLE
       """.stripMargin)

    sparkSession.sql("SELECT * FROM HIVE_CARBON_EXAMPLE").show()

    sparkSession.sql("DROP TABLE IF EXISTS TEST_BOUNDARY")

    sparkSession
      .sql(
        s"""CREATE TABLE TEST_BOUNDARY (c1_int int,c2_Bigint Bigint,c3_Decimal Decimal(38,30),
           |c4_double double,c5_string string,c6_Timestamp Timestamp,c7_Datatype_Desc string)
           |STORED AS carbondata""".stripMargin)

    inputPath = FileFactory
      .getUpdatedFilePath(s"$rootPath/examples/spark/src/main/resources/Test_Data1.csv")

    sparkSession
      .sql(
        s"LOAD DATA INPATH '$inputPath' INTO table TEST_BOUNDARY OPTIONS('DELIMITER'=','," +
        "'QUOTECHAR'='\"', 'BAD_RECORDS_ACTION'='FORCE','FILEHEADER'='c1_int,c2_Bigint," +
        "c3_Decimal,c4_double,c5_string,c6_Timestamp,c7_Datatype_Desc')")

    sparkSession.sql("""DROP TABLE IF EXISTS complexMap""".stripMargin)

    sparkSession.sql("create table complexMap(name map<string,string>) STORED AS carbondata")

    sparkSession
      .sql(
        "insert into complexMap values(map('Manish','Nalla','Shardul','Singh','Vishal','Kumar'," +
        "'EmptyVal','','NullVal', 'null'))")

    sparkSession.sql("""DROP TABLE IF EXISTS carbonLocalDictionary""".stripMargin)

    sparkSession.sql(
      s"create table carbonLocalDictionary(id int, name string, scale decimal, country string, " +
      s"salary double) stored as carbondata TBLPROPERTIES ('local_dictionary_enable'='true'," +
      s"'local_dictionary_include'='name') ")

    // delete the already existing lock on metastore so that new derby instance
    // for HiveServer can run on the same metastore
    checkAndDeleteDBLock
  }

  def checkAndDeleteDBLock: Unit = {
    val dbLockPath = FileFactory.getUpdatedFilePath(s"$metaStoreLoc/db.lck")
    val dbexLockPath = FileFactory.getUpdatedFilePath(s"$metaStoreLoc/dbex.lck")
    if(FileFactory.isFileExist(dbLockPath)) {
      FileFactory.deleteFile(dbLockPath)
    }
    if(FileFactory.isFileExist(dbexLockPath)) {
      FileFactory.deleteFile(dbexLockPath)
    }
  }

  def readFromHive: Unit = {
    try {
      Class.forName(driverName)
    }
    catch {
      case classNotFoundException: ClassNotFoundException =>
        classNotFoundException.printStackTrace()
    }

    // make HDFS writable
    val path = new Path(projectLoc)
    val fileSys = path.getFileSystem(FileFactory.getConfiguration)
    fileSys.setPermission(path, new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.ALL))

    val hiveEmbeddedServer2 = new HiveEmbeddedServer2()
    hiveEmbeddedServer2.start(projectLoc)
    val port = hiveEmbeddedServer2.getFreePort
    val connection = DriverManager.getConnection(s"jdbc:hive2://localhost:$port/default", "", "")
    val statement: Statement = connection.createStatement

    LOGGER.info(s"============HIVE CLI IS STARTED ON PORT $port ==============")

    val resultSet: ResultSet = statement.executeQuery("SELECT * FROM HIVE_CARBON_EXAMPLE")

    var rowsFetched = 0
    var resultId = ""
    var resultName = ""
    var resultSalary = ""

    while (resultSet.next) {
      if (rowsFetched == 0) {
        println("+---+" + "+-------+" + "+--------------+")
        println("| ID|" + "| NAME |" + "| SALARY        |")

        println("+---+" + "+-------+" + "+--------------+")

        resultId = resultSet.getString("id")
        resultName = resultSet.getString("name")
        resultSalary = resultSet.getString("salary")

        println(s"| $resultId |" + s"| $resultName |" + s"| $resultSalary  |")
        println("+---+" + "+-------+" + "+--------------+")
      }
      else {
        resultId = resultSet.getString("ID")
        resultName = resultSet.getString("NAME")
        resultSalary = resultSet.getString("SALARY")

        println(s"| $resultId |" + s"| $resultName |" + s"| $resultSalary   |")
        println("+---+" + "+-------+" + "+--------------+")
      }
      rowsFetched = rowsFetched + 1
    }
    println(s"******Total Number Of Rows Fetched ****** $rowsFetched")
    assert(rowsFetched == 4)

    LOGGER.info("Fetching the Individual Columns ")

    // fetching the separate columns
    var individualColRowsFetched = 0

    val resultIndividualCol = statement.executeQuery("SELECT NAME FROM HIVE_CARBON_EXAMPLE")

    while (resultIndividualCol.next) {
      if (individualColRowsFetched == 0) {
        println("+--------------+")
        println("| NAME         |")

        println("+---++---------+")

        resultName = resultIndividualCol.getString("name")

        println(s"| $resultName    |")
        println("+---+" + "+---------+")
      }
      else {
        resultName = resultIndividualCol.getString("NAME")

        println(s"| $resultName      |")
        println("+---+" + "+---------+")
      }
      individualColRowsFetched = individualColRowsFetched + 1
    }
    println(" ********** Total Rows Fetched When Quering The Individual Columns **********" +
            s"$individualColRowsFetched")
    assert(individualColRowsFetched == 4)

    LOGGER.info("Fetching the Out Of Order Columns ")

    val resultOutOfOrderCol = statement
      .executeQuery("SELECT SALARY,ID,NAME FROM HIVE_CARBON_EXAMPLE")
    var outOfOrderColFetched = 0

    while (resultOutOfOrderCol.next()) {
      if (outOfOrderColFetched == 0) {
        println("+---+" + "+-------+" + "+--------------+")
        println("| Salary|" + "| ID |" + "| NAME        |")

        println("+---+" + "+-------+" + "+--------------+")

        resultId = resultOutOfOrderCol.getString("id")
        resultName = resultOutOfOrderCol.getString("name")
        resultSalary = resultOutOfOrderCol.getString("salary")

        println(s"| $resultSalary |" + s"| $resultId |" + s"| $resultName  |")
        println("+---+" + "+-------+" + "+--------------+")
      }
      else {
        resultId = resultOutOfOrderCol.getString("ID")
        resultName = resultOutOfOrderCol.getString("NAME")
        resultSalary = resultOutOfOrderCol.getString("SALARY")

        println(s"| $resultSalary |" + s"| $resultId |" + s"| $resultName   |")
        println("+---+" + "+-------+" + "+--------------+")
      }
      outOfOrderColFetched = outOfOrderColFetched + 1
    }
    println(" ********** Total Rows Fetched When Quering The Out Of Order Columns **********" +
            s"$outOfOrderColFetched")
    assert(outOfOrderColFetched == 4)

    println(" ********** Local Dictionary details from Describe Formatted **********")

    val resultDictQuery = statement.executeQuery("describe formatted carbonLocalDictionary")

    var dataType = ""

    while (resultDictQuery.next) {
      dataType = dataType + resultDictQuery.getString("data_type")
      if (resultDictQuery.getString("data_type") != null &&
          resultDictQuery.getString("data_type").contains("local_dictionary_enable")) {
        println(s"| " + resultDictQuery.getString("data_type") + " |    " + "| " +
                resultDictQuery.getString("comment") + " |")
        assert(resultDictQuery.getString("comment").contains("true"))
      }
      if (resultDictQuery.getString("data_type") != null &&
          resultDictQuery.getString("data_type").contains("local_dictionary_include")) {
        println(s"| " + resultDictQuery.getString("data_type") + " |    " + "| " +
                resultDictQuery.getString("comment") + " |")
        assert(resultDictQuery.getString("comment").contains("name"))
      }
    }
    assert(dataType.contains("local_dictionary_enable"))
    assert(dataType.contains("local_dictionary_include"))

    val resultAggQuery = statement
      .executeQuery(
        "SELECT min(c3_Decimal) as min, max(c3_Decimal) as max, " +
        "sum(c3_Decimal) as sum FROM TEST_BOUNDARY")

    var resultAggQueryFetched = 0

    var resultMin = ""
    var resultMax = ""
    var resultSum = ""

    while (resultAggQuery.next) {
      if (resultAggQueryFetched == 0) {
        println("+-----+" + "+-------------------+" + "+--------------------------------+")
        println("| min |" + "| max               |" + "| sum                            |")

        println("+-----+" + "+-------------------+" + "+--------------------------------+")

        resultMin = resultAggQuery.getString("min")
        resultMax = resultAggQuery.getString("max")
        resultSum = resultAggQuery.getString("sum")

        println(s"| $resultMin   |" + s"| $resultMax               |" + s"| $resultSum|")
        println("+-----+" + "+-------------------+" + "+--------------------------------+")
      }
      resultAggQueryFetched = resultAggQueryFetched + 1
    }
    println(" ********** Total Rows Fetched When Aggregate Query **********" +
            s"$resultAggQueryFetched")
    assert(resultAggQueryFetched == 1)

    val resultComplexQuery = statement
      .executeQuery(
        "SELECT name FROM complexMap")

    var resultComplex = 0

    var name = ""

    while (resultComplexQuery.next) {
      if (resultComplex == 0) {
        println("+------------------------------------------------------------------------------" +
                "------+")
        println("| name                                                                          " +
                "     |")

        println("+-------------------------------------------------------------------------------" +
                "-----+")

        name = resultComplexQuery.getString("name")

        println(s"|$name|")
        println("+-------------------------------------------------------------------------------" +
                "-----+")      }
      resultComplex = resultComplex + 1
    }
    println(" ********** Total Rows Fetched When Complex Query **********" +
            s"$resultComplex")
    assert(resultComplex == 1)

    hiveEmbeddedServer2.stop()
  }
}