text:
package org.apache.logging.log4j.taglib;

import javax.servlet.jsp.tagext.Tag;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.MarkerManager;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.status.StatusLogger;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.mock.web.MockPageContext;

import static org.junit.Assert.*;

/**
 *
 */
public class IfEnabledTagTest {
    private static final String CONFIG = "log4j-test1.xml";

    @BeforeClass
    public static void setUpClass() {
        System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG);
        final LoggerContext context = LoggerContext.getContext(false);
        context.getConfiguration();
    }

    @AfterClass
    public static void cleanUpClass() {
        System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
        final LoggerContext context = LoggerContext.getContext(false);
        context.reconfigure();
        StatusLogger.getLogger().reset();
    }

    private final Logger logger = LogManager.getLogger("IfEnabledTagTest");
    private IfEnabledTag tag;

    @Before
    public void setUp() {
        this.tag = new IfEnabledTag();
        this.tag.setPageContext(new MockPageContext());
        this.tag.setLogger(this.logger);
    }

    @Test
    public void testDoStartTagEnabledString() throws Exception {
        this.tag.setLevel("warn");

        assertEquals("The return value is not correct.", Tag.EVAL_BODY_INCLUDE, this.tag.doStartTag());
    }

    @Test
    public void testDoStartTagEnabledLevel() throws Exception {
        this.tag.setLevel(Level.WARN);

        assertEquals("The return value is not correct.", Tag.EVAL_BODY_INCLUDE, this.tag.doStartTag());
    }

    @Test
    public void testDoStartTagEnabledStringMarker() throws Exception {
        this.tag.setMarker(MarkerManager.getMarker("E01"));
        this.tag.setLevel("error");

        assertEquals("The return value is not correct.", Tag.EVAL_BODY_INCLUDE, this.tag.doStartTag());
    }

    @Test
    public void testDoStartTagEnabledLevelMarker() throws Exception {
        this.tag.setMarker(MarkerManager.getMarker("F02"));
        this.tag.setLevel(Level.ERROR);

        assertEquals("The return value is not correct.", Tag.EVAL_BODY_INCLUDE, this.tag.doStartTag());
    }

    @Test
    public void testDoStartTagDisabledString() throws Exception {
        this.tag.setLevel("info");

        assertEquals("The return value is not correct.", Tag.SKIP_BODY, this.tag.doStartTag());
    }

    @Test
    public void testDoStartTagDisabledLevel() throws Exception {
        this.tag.setLevel(Level.INFO);

        assertEquals("The return value is not correct.", Tag.SKIP_BODY, this.tag.doStartTag());
    }

    @Test
    public void testDoStartTagDisabledStringMarker() throws Exception {
        this.tag.setMarker(MarkerManager.getMarker("E01"));
        this.tag.setLevel("trace");

        assertEquals("The return value is not correct.", Tag.SKIP_BODY, this.tag.doStartTag());
    }

    @Test
    public void testDoStartTagDisabledLevelMarker() throws Exception {
        this.tag.setMarker(MarkerManager.getMarker("F02"));
        this.tag.setLevel(Level.TRACE);

        assertEquals("The return value is not correct.", Tag.SKIP_BODY, this.tag.doStartTag());
    }
}


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

    <title>Close tabs unit tests</title>

    <link rel="stylesheet" href="qunit.css" type="text/css" media="screen" />

Close tabs unit tests

redpajama_set_name: RedPajamaGithub


text:
drop database if exists yumbox;
create database yumbox default character set utf8 default collate utf8_general_ci;

grant all on yumbox.* to 'yumbox'@'localhost';
grant all on yumbox.* to 'sphinx'@'localhost';

use yumbox;

drop table if exists user;
create table user
(
	id int unsigned not null auto_increment,
    status tinyint unsigned not null default 1,	# 0=inactive, 1=active, 2=licensed
    date_joined datetime not null,
    name varchar(255) not null,
    email varchar(255) not null,
    is_open tinyint(1) not null default 0,
    can_deliver tinyint(1) not null default 0,

    /* food pickup times */
    # set to 00:00:00 for not available
    pickup_mon time not null default '20:00:00',
    pickup_tue time not null default '20:00:00',
    pickup_wed time not null default '20:00:00',
    pickup_thu time not null default '20:00:00',
    pickup_fri time not null default '20:00:00',
    pickup_sat time not null default '20:00:00',
    pickup_sun time not null default '20:00:00',

    stripe_managed_account_id varchar(32),

	fb_id varchar(25),
    google_id varchar(25),

	alternate_name varchar(255),
    descr text,
    phone varchar(25),
    driver_lic varchar(30),
    passport_num varchar(30),

    primary key (id),
    index fb_id_index (fb_id),
    index stripe_managed_account_id_index (stripe_managed_account_id)
) engine = InnoDB;

drop table if exists user_picture;
create table user_picture
(
	id bigint unsigned not null auto_increment,
	user_id int unsigned not null,
	path varchar(255) not null,

	primary key (id),
	index user_id_picture_index (user_id),

	constraint user_id_picture_constraint
		foreign key (user_id)
		references user (id)
		on delete cascade
) engine = InnoDB;

drop table if exists user_follow_assoc;
create table user_follow_assoc
(
	id bigint unsigned not null auto_increment,
    user_id int unsigned not null,
	vendor_id int unsigned not null,

    primary key (id),
    index user_id_user_follow_index (user_id),
    index vendor_id_user_follow_index (vendor_id),

    constraint user_id_user_follow_constraint
		foreign key (user_id)
        references user (id)
        on delete cascade,
	constraint vendor_id_user_follow_constraint
		foreign key (vendor_id)
        references user (id)
        on delete cascade
) engine = InnoDB;

drop table if exists address;
create table address
(
    id int unsigned not null auto_increment,
    is_primary tinyint(1) unsigned not null default 1,
    user_id int unsigned not null,

    address varchar(255),
    city varchar(50),
    province varchar(50),
    postal_code varchar(10),
    country varchar(50),

    # geocoded location from above address
    latitude float,
    longitude float,

    primary key (id),
    index user_id_address_index (user_id),

    constraint user_id_address_constraint
		foreign key (user_id)
        references user (id)
        on delete cascade
) engine = InnoDB;

drop table if exists food_category;
create table food_category
(
	id int unsigned not null auto_increment,
    name varchar(255) not null,
    main tinyint(1) not null default 0,

    primary key (id),
    index name_food_category_index (name),
    index main_food_category_index (main)
) engine = InnoDB;

drop table if exists food;
create table food
(
	id bigint unsigned not null auto_increment,
    status tinyint unsigned not null default 1,		# 0=inactive, 1=active
    user_id int unsigned not null,
    name varchar(255) not null,
    price decimal(5,2) unsigned not null,
    quota smallint unsigned not null default 1,

    /* food preparation */
    pickup_method tinyint(2) not null default 0,		# 0=any time the food is ready after prep_time_hours, # 1=limit pickup to times as specified in user table
    prep_time_hours float not null default 2.0,

	alternate_name varchar(255),
    descr text,
    ingredients text,
    health_benefits text,
    eating_instructions text,

    primary key (id),
    index user_id_food_index (user_id),

    constraint user_id_food_constraint
		foreign key (user_id)
        references user (id)
        on delete cascade
) engine = InnoDB;

drop table if exists food_category_assoc;
create table food_category_assoc
(
	id bigint unsigned not null auto_increment,
    food_id bigint unsigned not null,
    food_category_id int unsigned not null,

    primary key (id),
    index food_id_assoc_index (food_id),
    index food_category_id_assoc_index (food_category_id),

    constraint food_id_assoc_constraint
		foreign key (food_id)
        references food (id)
        on delete cascade,
	constraint food_cat_id_assoc_constraint
		foreign key (food_category_id)
        references food_category (id)
        on delete cascade
) engine = InnoDB;

drop table if exists food_picture;
create table food_picture
(
	id bigint unsigned not null auto_increment,
	food_id bigint unsigned not null,
	path varchar(255) not null,

	primary key (id),
	index food_id_picture_index (food_id),

	constraint food_id_picture_constraint
		foreign key (food_id)
		references food (id)
		on delete cascade
) engine = InnoDB;

drop table if exists food_follow_assoc;
create table food_follow_assoc
(
	id bigint unsigned not null auto_increment,
    user_id int unsigned not null,
	food_id bigint unsigned not null,

    primary key (id),
    index user_id_food_follow_index (user_id),
    index food_id_food_follow_index (food_id),

    constraint user_id_food_follow_constraint
		foreign key (user_id)
        references user (id)
        on delete cascade,
	constraint food_id_food_follow_constraint
		foreign key (food_id)
        references food (id)
        on delete cascade
) engine = InnoDB;

drop table if exists food_review;
create table food_review
(
	id bigint unsigned not null auto_increment,
    food_id bigint unsigned not null,
    user_id int unsigned not null,
    rating tinyint unsigned not null default 3,		# scale 0 to 5
    created_on timestamp not null,

    review text,

    primary key (id),
    index food_id_review_index (food_id),
    index user_id_review_index (user_id),

    constraint food_id_review_constraint
		foreign key (food_id)
        references food (id)
        on delete cascade,
	constraint user_id_review_constraint
		foreign key (user_id)
        references user (id)
        on delete cascade
) engine = InnoDB;

drop table if exists credit_card;
create table if not exists credit_card(
	id bigint unsigned not null auto_increment,

    stripe_cust_id varchar(50),
    stripe_card_id varchar(50),

    exp_month tinyint unsigned,
    exp_year smallint unsigned,
    last4 smallint unsigned,
    type varchar(10),		# Visa, Master

    primary key (id),
    index stripe_cust_id_index (stripe_cust_id),
    index stripe_card_id_index (stripe_card_id)
) engine = InnoDB;

drop table if exists order_basket;
create table order_basket
(
	id bigint unsigned not null auto_increment,
    order_date datetime not null,
    user_id int unsigned not null,
    is_paid tinyint(1) unsigned not null default 0,

	description text,

    primary key (id),
    index user_id_order_index (user_id),

    constraint user_id_order_constraint
		foreign key (user_id)
        references user (id)
        on delete cascade,
	constraint address_order_constraint
		foreign key (delivery_address)
        references address (id)
        on delete set null
) engine = InnoDB;

drop table if exists order_item;
create table order_item
(
	id bigint unsigned not null auto_increment,
    food_id bigint unsigned not null,
    quantity smallint unsigned not null,
    order_basket_id bigint unsigned not null,
    is_filled tinyint(1) not null default 0,	# 0 = unfilled, 1 = delivered

    primary key (id),
    index food_id_order_index (food_id),
    index order_item_basket_index (order_basket_id),

    constraint food_id_order_constraint
		foreign key (food_id)
        references food (id)
        on delete cascade,
	constraint order_item_basket_constraint
		foreign key (order_basket_id)
        references order_basket (id)
        on delete cascade
) engine = InnoDB;

/* payment received from the consumer */
drop table if exists payment;
create table if not exists payment
(
	id bigint unsigned not null auto_increment,
    amount decimal(8,2) not null,
    payment_date datetime not null,
    order_item_id bigint unsigned not null,
    tax_rate float not null default 0.00,
    take_rate float not null default 0.00,

    stripe_charge_id varchar(50),

    primary key (id),
    index stripe_charge_id_index (stripe_charge_id),
    index order_item_payment_index (order_item_id),

    constraint payment_order_constraint
		foreign key (order_item_id)
        references order_item (id)
        on delete restrict
) engine = InnoDB;

/* payout to the vendor */
drop table if exists payout;
create table if not exists payout
(
	id bigint unsigned not null auto_increment,
    amount decimal(8,2) not null,
    payment_date datetime not null,
    order_item_id bigint unsigned not null,
    take_rate float not null default 0.1,

    primary key (id),
    index payout_order_item_index (order_item_id),

	constraint payout_order_item_constraint
		foreign key (order_item_id)
        references order_item (id)
        on delete restrict
) engine = InnoDB;

/* refund to the consumer */
drop table if exists refund;
create table refund
(
	id bigint unsigned not null auto_increment,
    type tinyint unsigned not null,		# 0 = from customer, 1 = from chef
    amount decimal(8,2) not null,
    payment_date datetime not null,
    order_item_id bigint unsigned not null,

    stripe_refund_id varchar(50),
    explanation text,

    primary key (id),
    index refund_order_item_index (order_item_id),
    index stripe_refund_id_index (stripe_refund_id),

	constraint refund_order_item_constraint
		foreign key (order_item_id)
        references order_item (id)
        on delete restrict
) engine = InnoDB;

/** Email queue tables **/
CREATE TABLE IF NOT EXISTS `mail_queue` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `from_address` VARCHAR(255) NOT NULL,
  `from_name` VARCHAR(255) NOT NULL,
  `replyto` VARCHAR(255) NOT NULL,
  `replyto_name` VARCHAR(255) NOT NULL,
  `subject` VARCHAR(1024) NOT NULL,
  `body` MEDIUMTEXT NOT NULL,
  `enqueue_date` DATETIME NOT NULL,
  `sent_date` DATETIME NOT NULL,
  `tries` SMALLINT NOT NULL DEFAULT 0,
  `try_date` DATETIME NOT NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS `mail_recipient` (
  `mail_id` BIGINT UNSIGNED NOT NULL,
  `address` VARCHAR(255) NOT NULL,
  `recipient_type` TINYINT NOT NULL,
  `name` VARCHAR(255) NOT NULL,
  PRIMARY KEY (`mail_id`, `address`, `recipient_type`),
  CONSTRAINT `fk_mail_recipient_mail_queue`
    FOREIGN KEY (`mail_id`)
    REFERENCES `mail_queue` (`id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB;

drop table if exists ci_sessions;
CREATE TABLE IF NOT EXISTS `ci_sessions` (
        `id` varchar(40) NOT NULL,
        `ip_address` varchar(45) NOT NULL,
        `timestamp` int(10) unsigned DEFAULT 0 NOT NULL,
        `data` blob NOT NULL,
        KEY `ci_sessions_timestamp` (`timestamp`)
) engine = InnoDB;

drop procedure if exists add_user;
delimiter //
create procedure add_user(in name varchar(255), in email varchar(255),
	in fb_id varchar(25), in google_id varchar(25))
begin
	declare id int unsigned;

    if (fb_id is not null) then
		select u.id into id
        from user u
        where
			u.fb_id = fb_id;

		if (id is null) then
			insert into user (status, date_joined, name, email, fb_id)
            values (1, now(), name, email, fb_id);
		end if;
    elseif (google_id is not null) then
		select u.id into id
        from user u
        where
			u.google_id = google_id;

		if (id is null) then
			insert into user (status, date_joined, name, email, google_id)
            values (1, now(), name, email, google_id);
		end if;
    end if;

end//
delimiter ;

drop procedure if exists add_user_follower;
delimiter //
create procedure add_user_follower(in user_id int unsigned, in vendor_id int unsigned)
begin
	declare exist bigint unsigned;

    select a.id into exist
    from user_follow_assoc a
    where
		a.user_id = user_id
        and a.vendor_id = vendor_id;

	if (exist is null) then
		insert into user_follow_assoc (user_id, vendor_id)
        values (user_id, vendor_id);
    end if;
end//
delimiter ;

drop function if exists average_rating;
delimiter //
create function average_rating(food_id bigint unsigned)
returns float not deterministic
begin
	declare average float;

    select avg(r.rating) into average
    from food_review r
    where
		r.food_id = food_id
	group by
		r.food_id;

    if (average is null) then
		set average = 0;
	end if;

    return average;
end//
delimiter ;

drop function if exists total_orders;
delimiter //
create function total_orders(food_id bigint unsigned)
returns int not deterministic
begin
	declare total int;

    select sum(o.quantity) into total
    from order_item o
    where
		o.food_id = food_id
	group by
		o.food_id;

	if (total is null) then
		set total = 0;
	end if;

    return total;
end//
delimiter ;

drop function if exists distance_btw_coords;
delimiter //
create function distance_btw_coords(latA float, lonA float, latB float, lonB float)
returns float not deterministic
begin
	/* radius of Earth */
	declare R float default 6371;
    declare dLat_rad float default (latB-latA)/180*pi();
    declare dLon_rad float default (lonB-lonA)/180*pi();
    declare latA_rad float default latA/180*pi();
    declare latB_rad float default latB/180*pi();

    declare a float default sin(dLat_rad/2)*sin(dLat_rad/2)
		+ sin(dLon_rad/2)*sin(dLon_rad/2)*cos(latA_rad)*cos(latB_rad);
    declare c float default 2*atan2(sqrt(a),sqrt(1-a));

    return R*c;
end//
delimiter ;

drop procedure if exists add_order;
delimiter //
create procedure add_order(in order_basket_id bigint unsigned, in food_id bigint unsigned, in quantity smallint unsigned)
begin
	declare o_id bigint unsigned;
    declare is_open tinyint unsigned;
    declare current_quantity smallint unsigned;
    declare quota smallint unsigned;

    /* Find out if kitchen is closed */
    select o.id, u.is_open
    into o_id, is_open
    from order_item o
    left join
		food f
	on f.id = o.food_id
    left join
		user u
	on u.id = f.user_id
    where
		o.food_id = food_id
        and o.order_basket_id = order_basket_id;

	/* Find out quantity and quota */
    select sum(o.quantity), f.quota
    into current_quantity, quota
    from order_item o
    left join
		food f
	on f.id = o.food_id
    left join
		refund r
	on r.order_item_id = o.id
    where
		f.id = food_id
        and o.is_filled = 0
        and r.id is null
	group by f.id;

	if (is_open = 0) then
		/* we cannot process if the kitchen is closed */
        signal sqlstate '45000'
			set message_text = 'kitchen is closed';
	elseif (quantity+current_quantity > quota) then
		/* we cannot process more orders than quota */
        signal sqlstate '45000'
			set message_text = 'orders cannot be larger than quota';
    else
		if (o_id is null) then
			insert into order_item
				(food_id, quantity, order_basket_id)
			values
				(food_id, quantity, order_basket_id);
		else
			update order_item o
			set
				o.quantity = o.quantity + quantity
			where
				o.order_basket_id = order_basket_id
				and o.food_id = food_id;
		end if;
    end if;
end//
delimiter ;

drop procedure if exists add_payment;
delimiter //
create procedure add_payment(in amount decimal(8,2), in take_rate float, in tax_rate float, in stripe_id varchar(50), in order_item_id bigint unsigned)
begin
	declare p_id bigint unsigned;

    select p.id into p_id
    from payment p
    where
		p.stripe_charge_id = stripe_id;

	if (p_id is null) then
		insert into payment
			(amount, take_rate, tax_rate, stripe_charge_id, payment_date, order_item_id)
		values
			(amount, take_rate, tax_rate, stripe_id, now(), order_item_id);
	else
		signal sqlstate '45000'
			set message_text = 'stripe payment exists';
	end if;
end//
delimiter ;

drop procedure if exists add_refund;
delimiter //
create procedure add_refund(in amount decimal(8,2), in stripe_id varchar(50), in order_item_id bigint unsigned,
	in type tinyint unsigned, in explanation text)
begin
	declare r_id bigint unsigned;

    select r.id into r_id
    from refund r
    where
		r.stripe_refund_id = stripe_id;

	if (r_id is null) then
		insert into refund
			(amount, stripe_refund_id, payment_date, order_item_id, type, explanation)
		values
			(amount, stripe_id, now(), order_item_id, type, explanation);
	else
		signal sqlstate '45000'
			set message_text = 'stripe refund exists';
	end if;
end//
delimiter ;

drop procedure if exists add_user_picture;
delimiter //
create procedure add_user_picture(in user_id int, in path varchar(255))
begin
	declare p_id bigint unsigned;

    select p.id into p_id
    from user_picture p
    where
		p.user_id = user_id;

	if (p_id is null) then
		insert into user_picture
			(user_id, path)
		values
			(user_id, path);
	else
		update user_picture p
        set p.path = path
        where
			p.user_id = user_id;
	end if;
end//
delimiter ;

drop procedure if exists add_food_picture;
delimiter //
create procedure add_food_picture(in food_id bigint, in path varchar(255))
begin
	declare p_id bigint unsigned;

    select p.id into p_id
    from food_picture p
    where
		p.food_id = food_id;

	if (p_id is null) then
		insert into food_picture
			(food_id, path)
		values
			(food_id, path);
	else
		update food_picture f
        set f.path = path
        where
			f.food_id = food_id;
	end if;
end//
delimiter ;

/** essential data **/
insert into food_category (name, main) values ('dessert', 1); #1
insert into food_category (name, main) values ('indian', 1); #2
insert into food_category (name, main) values ('chinese', 1); #3
insert into food_category (name, main) values ('french', 1); #4
insert into food_category (name, main) values ('fruit', 0); #5
insert into food_category (name, main) values ('thai', 1); #6
insert into food_category (name, main) values ('vietnam', 1); #7
insert into food_category (name, main) values ('burger', 0); #8
insert into food_category (name, main) values ('sandwich', 0); #9
insert into food_category (name, main) values ('soup', 0); #10
insert into food_category (name, main) values ('breakfast', 0); #11
insert into food_category (name, main) values ('vegetarian', 1); #12
insert into food_category (name, main) values ('sea food', 1); #13
insert into food_category (name, main) values ('drink', 1); #14
insert into food_category (name, main) values ('italian', 1); #15
insert into food_category (name, main) values ('mexican', 1); #16
insert into food_category (name, main) values ('persian', 1); #17


text:
package org.apache.shardingsphere.elasticjob.cloud.executor.prod;

import com.google.common.base.Strings;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.lang3.SerializationUtils;
import org.apache.mesos.Executor;
import org.apache.mesos.ExecutorDriver;
import org.apache.mesos.Protos;
import org.apache.mesos.Protos.TaskInfo;
import org.apache.shardingsphere.elasticjob.api.ElasticJob;
import org.apache.shardingsphere.elasticjob.api.JobConfiguration;
import org.apache.shardingsphere.elasticjob.cloud.facade.CloudJobFacade;
import org.apache.shardingsphere.elasticjob.executor.ElasticJobExecutor;
import org.apache.shardingsphere.elasticjob.executor.JobFacade;
import org.apache.shardingsphere.elasticjob.infra.concurrent.ElasticJobExecutorService;
import org.apache.shardingsphere.elasticjob.infra.exception.ExceptionUtils;
import org.apache.shardingsphere.elasticjob.infra.listener.ShardingContexts;
import org.apache.shardingsphere.elasticjob.infra.pojo.JobConfigurationPOJO;
import org.apache.shardingsphere.elasticjob.infra.yaml.YamlEngine;
import org.apache.shardingsphere.elasticjob.tracing.JobTracingEventBus;
import org.apache.shardingsphere.elasticjob.tracing.api.TracingConfiguration;

import javax.sql.DataSource;
import java.util.Map;
import java.util.concurrent.ExecutorService;

/**
 * Task executor.
 */
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
@Slf4j
public final class TaskExecutor implements Executor {

    private final ElasticJob elasticJob;

    private final String elasticJobType;

    private final ExecutorService executorService = new ElasticJobExecutorService("cloud-task-executor", Runtime.getRuntime().availableProcessors() * 100).createExecutorService();

    private volatile ElasticJobExecutor jobExecutor;

    private volatile JobTracingEventBus jobTracingEventBus = new JobTracingEventBus();

    public TaskExecutor(final ElasticJob elasticJob) {
        this(elasticJob, null);
    }

    public TaskExecutor(final String elasticJobType) {
        this(null, elasticJobType);
    }

    @Override
    public void registered(final ExecutorDriver executorDriver, final Protos.ExecutorInfo executorInfo, final Protos.FrameworkInfo frameworkInfo, final Protos.SlaveInfo slaveInfo) {
        if (!executorInfo.getData().isEmpty()) {
            Map<String, String> data = SerializationUtils.deserialize(executorInfo.getData().toByteArray());
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName(data.get("event_trace_rdb_driver"));
            dataSource.setUrl(data.get("event_trace_rdb_url"));
            dataSource.setPassword(data.get("event_trace_rdb_password"));
            dataSource.setUsername(data.get("event_trace_rdb_username"));
            jobTracingEventBus = new JobTracingEventBus(new TracingConfiguration<DataSource>("RDB", dataSource));
        }
    }

    @Override
    public void reregistered(final ExecutorDriver executorDriver, final Protos.SlaveInfo slaveInfo) {
    }

    @Override
    public void disconnected(final ExecutorDriver executorDriver) {
    }

    @Override
    public void launchTask(final ExecutorDriver executorDriver, final Protos.TaskInfo taskInfo) {
        executorService.submit(new TaskThread(executorDriver, taskInfo));
    }

    @Override
    public void killTask(final ExecutorDriver executorDriver, final Protos.TaskID taskID) {
        executorDriver.sendStatusUpdate(Protos.TaskStatus.newBuilder().setTaskId(taskID).setState(Protos.TaskState.TASK_KILLED).build());
        DaemonTaskScheduler.shutdown(taskID);
    }

    @Override
    public void frameworkMessage(final ExecutorDriver executorDriver, final byte[] bytes) {
        if (null != bytes && "STOP".equals(new String(bytes))) {
            log.error("call frameworkMessage executor stopped.");
            executorDriver.stop();
        }
    }

    @Override
    public void shutdown(final ExecutorDriver executorDriver) {
    }

    @Override
    public void error(final ExecutorDriver executorDriver, final String message) {
        log.error("call executor error, message is: {}", message);
    }

    @RequiredArgsConstructor
    class TaskThread implements Runnable {

        private final ExecutorDriver executorDriver;

        private final TaskInfo taskInfo;

        @Override
        public void run() {
            Thread.currentThread().setContextClassLoader(TaskThread.class.getClassLoader());
            executorDriver.sendStatusUpdate(Protos.TaskStatus.newBuilder().setTaskId(taskInfo.getTaskId()).setState(Protos.TaskState.TASK_RUNNING).build());
            Map<String, Object> data = SerializationUtils.deserialize(taskInfo.getData().toByteArray());
            ShardingContexts shardingContexts = (ShardingContexts) data.get("shardingContext");
            JobConfiguration jobConfig = YamlEngine.unmarshal(data.get("jobConfigContext").toString(), JobConfigurationPOJO.class).toJobConfiguration();
            try {
                JobFacade jobFacade = new CloudJobFacade(shardingContexts, jobConfig, jobTracingEventBus);
                if (isTransient(jobConfig)) {
                    getJobExecutor(jobFacade).execute();
                    executorDriver.sendStatusUpdate(Protos.TaskStatus.newBuilder().setTaskId(taskInfo.getTaskId()).setState(Protos.TaskState.TASK_FINISHED).build());
                } else {
                    new DaemonTaskScheduler(elasticJob, elasticJobType, jobConfig, jobFacade, executorDriver, taskInfo.getTaskId()).init();
                }
                // CHECKSTYLE:OFF
            } catch (final Throwable ex) {
                // CHECKSTYLE:ON
                log.error("ElasticJob-Cloud Executor error:", ex);
                executorDriver.sendStatusUpdate(Protos.TaskStatus.newBuilder().setTaskId(taskInfo.getTaskId()).setState(Protos.TaskState.TASK_ERROR).setMessage(ExceptionUtils.transform(ex)).build());
                executorDriver.stop();
                throw ex;
            }
        }

        private boolean isTransient(final JobConfiguration jobConfig) {
            return Strings.isNullOrEmpty(jobConfig.getCron());
        }

        private ElasticJobExecutor getJobExecutor(final JobFacade jobFacade) {
            if (null == jobExecutor) {
                createJobExecutor(jobFacade);
            }
            return jobExecutor;
        }

        private synchronized void createJobExecutor(final JobFacade jobFacade) {
            if (null != jobExecutor) {
                return;
            }
            jobExecutor = null == elasticJob
                    ? new ElasticJobExecutor(elasticJobType, jobFacade.loadJobConfiguration(true), jobFacade)
                    : new ElasticJobExecutor(elasticJob, jobFacade.loadJobConfiguration(true), jobFacade);
        }
    }
}


text:
/**
 * Created by joel on 8/20/16.
 */

import {editor, editor_element} from './editor/editor';
import {state, defaults} from './utils';
import CodeMirror from 'codemirror';
const mac = CodeMirror.keyMap["default"] == CodeMirror.keyMap.macDefault;
const ctrl = mac ? "Cmd-" : "Ctrl-";

const icon_elements = [];
const icon_collection = document.getElementsByClassName('icon');
for (let i = 0; icon_collection[i]; i++) icon_elements.push(icon_collection[i]);
const icons = {
    settings: {
        'monokai': document.getElementById('icon-settings-white'),
        'default': document.getElementById('icon-settings-black')
    },
    close: {
        'monokai': document.getElementById('icon-close-white'),
        'default': document.getElementById('icon-close-black')
    }
};
const hint = document.getElementById('hint');
const labels = [
    {
        element: document.getElementById('eval-expression'),
        emacs: 'Meta-Z',
        sublime: ctrl + 'Enter'
    },
    {
        element: document.getElementById('eval-document'),
        emacs: 'Meta-O',
        sublime: ctrl + 'Shift-Enter'
    },
    {
        element: document.getElementById('clear-values'),
        emacs: 'Ctrl-Shift-Backspace',
        sublime: ctrl + 'Shift-Backspace'
    },
    // {
    //     element: document.getElementById('view'),
    //     emacs: 'Tab',
    //     sublime: 'Tab'
    // },
    {
        element: document.getElementById('autocomplete'),
        emacs: 'Meta-/',
        sublime: 'Alt-/'
    },
    {
        element: document.getElementById('open'),
        emacs: 'Ctrl-X F',
        sublime: ctrl + 'O'
    },
    {
        element: document.getElementById('save'),
        emacs: 'Ctrl-X S',
        sublime: ctrl + 'S'
    },
    {
        element: document.getElementById('interrupt'),
        emacs: 'Ctrl-C',
        sublime: ctrl + 'B'
    },
    {
        element: document.getElementById('help'),
        emacs: 'Meta-H',
        sublime: ctrl + 'Shift-H'
    }
];

labels.forEach(({element}) => element.parentNode.onclick = e => editor.execCommand(element.id));

function set_theme(theme) {
    state.theme = theme;
    icon_elements.forEach(element => element.style.visibility = 'hidden');
    icons[state.visibility][theme].style.visibility = 'visible';
    editor.setOption('theme', theme);
    editor.focus();
}

function set_visibility(visibility) {
    state.visibility = visibility;
    if (visibility === 'settings') {
        hint.style.display = 'none';
        editor_element.style.right = 0;
    }
    else if (visibility === 'close') {
        hint.style.display = 'block';
        editor_element.style.right = 320;
    }
    icon_elements.forEach(element => element.style.visibility = 'hidden');
    icons[visibility][state.theme].style.visibility = 'visible';
    editor.focus();
}

function cm_help(cm) {
    const visibility = (state.visibility === 'close' ? 'settings' : 'close');
    set_visibility(visibility);
    cm.focus();
}

function set_keyMap(keyMap) {
    labels.forEach(label => label.element.textContent = label[keyMap]);
    editor.setOption('keyMap', keyMap);
    editor.focus();
}

document.getElementById('icons').onclick = e => cm_help(editor);
document.getElementById('keyMap-emacs').onclick = e => set_keyMap('emacs');
document.getElementById('keyMap-sublime').onclick = e => set_keyMap('sublime');
document.getElementById('theme-light').onclick = e => set_theme('default');
document.getElementById('theme-dark').onclick = e => set_theme('monokai');
set_visibility(defaults.visibility);
set_keyMap(defaults.keyMap);
set_theme(defaults.theme);

editor.focus();

export {cm_help, set_visibility}


text:
package io.fintrospect.parameters

import com.twitter.finagle.http.{Request, RequestProxy}
import io.fintrospect.util.Extraction

case class ExtractedRouteRequest(override val request: Request, private val contents: Map[Any, Extraction[Any]]) extends RequestProxy {
  private val contentsByName = contents.map(e => e._1.toString -> e._2)
  def get[T, Wrapper](p: Any, fallback: Wrapper => Extraction[T]): Extraction[T] = contentsByName.getOrElse(p.toString, fallback(request.asInstanceOf[Wrapper])).asInstanceOf[Extraction[T]]
}


text:
#ifndef RTC_BASE_KEEP_REF_UNTIL_DONE_H_
#define RTC_BASE_KEEP_REF_UNTIL_DONE_H_

#include "rtc_base/bind.h"
#include "rtc_base/callback.h"
#include "rtc_base/refcount.h"
#include "rtc_base/scoped_ref_ptr.h"

namespace rtc {

namespace impl {
template <class T>
static inline void DoNothing(const scoped_refptr<T>& object) {}
}  // namespace impl

// KeepRefUntilDone keeps a reference to |object| until the returned
// callback goes out of scope. If the returned callback is copied, the
// reference will be released when the last callback goes out of scope.
template <class ObjectT>
static inline Callback0<void> KeepRefUntilDone(ObjectT* object) {
  return rtc::Bind(&impl::DoNothing<ObjectT>, scoped_refptr<ObjectT>(object));
}

template <class ObjectT>
static inline Callback0<void> KeepRefUntilDone(
    const scoped_refptr<ObjectT>& object) {
  return rtc::Bind(&impl::DoNothing<ObjectT>, object);
}

}  // namespace rtc

#endif  // RTC_BASE_KEEP_REF_UNTIL_DONE_H_


text:
package org.batfish.datamodel.route.nh;

import static com.google.common.base.Preconditions.checkArgument;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.batfish.datamodel.Interface;
import org.batfish.datamodel.Ip;
import org.batfish.datamodel.Route;

/**
 * Route next hop indicating that a route must go out a particular interface, with an
 * optional next hop IP that would be ARP'ed for.
 *
 *
This is not to be confused with the interface resolution done by the FIB. This next hop type
 * is used for interface routes, such as: connected, local, and static interface routes.
 */
public final class NextHopInterface implements NextHop {

  // Soft values: let it be garbage collected in times of pressure.
  // Maximum size 2^20: Just some upper bound on cache size, well less than GiB.
  //   (8 bytes seems smallest possible entry (long), would be 8 MiB total).
  private static final LoadingCache<NextHopInterface, NextHopInterface> CACHE =
      CacheBuilder.newBuilder().softValues().maximumSize(1 << 20).build(CacheLoader.from(x -> x));

  /** The interface name to which the traffic should be routed */
  @JsonProperty(PROP_INTERFACE)
  @Nonnull
  public String getInterfaceName() {
    return _interfaceName;
  }

  /** Optional next hop/ARP IP to use */
  @JsonProperty(PROP_IP)
  @Nullable
  public Ip getIp() {
    return _ip;
  }

  /**
   * Create a new interface next hop without a specific ARP IP
   *
   * @param interfaceName name of the interface
   * @throws IllegalArgumentException if the interface name is not valid, e.g., {@link
   *     Interface#NULL_INTERFACE_NAME}
   */
  @Nonnull
  public static NextHopInterface of(String interfaceName) {
    return CACHE.getUnchecked(new NextHopInterface(interfaceName, null));
  }

  /**
   * Create a new interface next hop with a specific ARP IP
   *
   * @param interfaceName name of the interface
   * @param ip the IP to ARP for
   * @throws IllegalArgumentException if the interface name is not valid, e.g., {@link
   *     Interface#NULL_INTERFACE_NAME} or the IP is invalid, e.g., {@link Ip#AUTO}
   */
  @Nonnull
  public static NextHopInterface of(String interfaceName, Ip ip) {
    return CACHE.getUnchecked(new NextHopInterface(interfaceName, ip));
  }

  @Override
  public boolean equals(@Nullable Object o) {
    if (this == o) {
      return true;
    }
    if (!(o instanceof NextHopInterface)) {
      return false;
    }
    NextHopInterface that = (NextHopInterface) o;
    return _interfaceName.equals(that._interfaceName) && Objects.equals(_ip, that._ip);
  }

  @Override
  public int hashCode() {
    // This hashcode could be hot, so compute manually instead of Objects.hash(...)
    return _interfaceName.hashCode() + (_ip == null ? 0 : 31 * _ip.hashCode());
  }

  @Override
  public String toString() {
    return MoreObjects.toStringHelper(NextHopInterface.class)
        .omitNullValues()
        .add("interfaceName", _interfaceName)
        .add("ip", _ip)
        .toString();
  }

  @Override
  public <T> T accept(NextHopVisitor<T> visitor) {
    return visitor.visitNextHopInterface(this);
  }

  private static final String PROP_INTERFACE = "interface";
  private static final String PROP_IP = "ip";

  @Nonnull private final String _interfaceName;
  @Nullable private final Ip _ip;

  @JsonCreator
  private static @Nonnull NextHopInterface create(
      @JsonProperty(PROP_INTERFACE) @Nullable String iface,
      @JsonProperty(PROP_IP) @Nullable Ip ip) {
    checkArgument(iface != null, "Missing %s", PROP_INTERFACE);
    return of(iface, ip);
  }

  private NextHopInterface(String interfaceName, @Nullable Ip ip) {
    checkArgument(
        !Interface.NULL_INTERFACE_NAME.equals(interfaceName),
        "NULL interface cannot be used as NextHopInterface, use NextHopDiscard");
    checkArgument(
        !Route.UNSET_NEXT_HOP_INTERFACE.equals(interfaceName),
        "NextHopInterface cannot have unset interface. Received %s",
        interfaceName);
    checkArgument(
        ip == null || (!ip.equals(Ip.AUTO) && !ip.equals(Ip.ZERO) && !ip.equals(Ip.MAX)),
        "NextHopIp must be a valid concrete IP address. Received %s",
        ip);
    _interfaceName = interfaceName;
    _ip = ip;
  }
}


text:
'use strict';

function parse (root) {
  console.log(document.documentElement);
}

// init.push(traverse);


text:
create table AccountCMEProgress (
	id serial,

	account integer not null references Account(id) on delete cascade,
	quiz integer references Inquisition(id) on delete cascade,
	evaluation integer references Inquisition(id) on delete cascade,

	primary key (id)
);

create index AccountCMEProgress_account_index
	on AccountCMEProgress(account);


text:
Default Length (100 Characters)

      Over 100 Characters:

      Under 100 Characters:

Custom Length (50 Characters)

      Over 50 Characters:

      Under 50 Characters:


text:
namespace Examples.Ci.WebApi.Infrastructures
{
    using Castle.MicroKernel.Registration;
    using Castle.MicroKernel.SubSystems.Configuration;
    using Castle.Windsor;
    using Controllers;
    using System.Diagnostics.CodeAnalysis;

    [ExcludeFromCodeCoverage]
    public class TestInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            #region code examples
            //container.Register(Component.For<ITest>().ImplementedBy<Test>().DependsOn(Dependency.OnValue("message", "hello, world!")).LifestylePerWebRequest());

            //container.Register(Component.For<ISettings>().ImplementedBy<Settings>().LifestyleSingleton());

            //var settings = container.Resolve<ISettings>();

            //Debug.WriteLine(settings);

            //container.Register(Component.For<ITest>().ImplementedBy<Test>().DependsOn(Dependency.OnComponent(typeof(ISettings), typeof(Settings).FullName)).DependsOn(Dependency.OnValue("message", "123")).OnCreate(a =>
            //{
            //    var settings = container.Resolve<ISettings>();
            //    Debug.WriteLine(settings);
            //}).LifestylePerWebRequest());
            #endregion

            #region enable priority from ioc
            //var settings = container.Resolve<Utils.ISettings>();
            //System.Diagnostics.Debug.WriteLine(settings);
            //container.Register(Component.For<ITest>().ImplementedBy<Test>().DependsOn(Dependency.OnValue("message", settings.DefaultConnectionString)).LifestylePerWebRequest());
            #endregion

            container.Register(Component.For<ITest>().ImplementedBy<Test>().LifestylePerWebRequest());
        }
    }
}


text:
package com.glaf.core.job;

import java.util.Date;

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

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.glaf.core.context.ContextFactory;
import com.glaf.core.util.DateUtils;
import com.glaf.core.service.SysDataLogService;

public class SysDataLogSaveJob extends BaseJob {
	protected final static Log logger = LogFactory
			.getLog(SysDataLogSaveJob.class);

	public void runJob(JobExecutionContext context)
			throws JobExecutionException {
		String jobName = context.getJobDetail().getKey().getName();
		logger.info("Executing job: " + jobName + " executing at "
				+ DateUtils.getDateTime(new Date()));
		SysDataLogService sysDataLogService = ContextFactory
				.getBean("sysDataLogService");
		sysDataLogService.saveAll();
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pdm.ivchecker" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".ActividadPrincipal"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ListaVerbos"
            android:label="@string/title_activity_lista_verbos" >
        </activity>
        <activity
            android:name=".Juego"
            android:label="@string/title_activity_juego" >
        </activity>
        <activity
            android:name=".About"
            android:label="@string/title_activity_about"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name=".TrainingAreaInicio"
            android:label="@string/title_activity_training_area_inicio" >
        </activity>
        <activity
            android:name=".JuegoTraining"
            android:label="@string/title_activity_juego_training" >
        </activity>
        <activity
            android:name=".Configuracion"
            android:label="@string/title_activity_configuracion" >
        </activity>
        <activity
            android:name=".wcr"
            android:label="@string/title_activity_wcr"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name=".ResultadosTraining"
            android:label="@string/title_activity_resultados_training" >
        </activity>
        <activity
            android:name=".Resultado"
            android:label="@string/title_activity_resultado" >
        </activity>
        <activity
            android:name=".HistorialPuntuacionTraining"
            android:label="@string/title_activity_historial_puntuacion_training" >
        </activity>
        <activity
            android:name="com.google.android.gms.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
        <activity
            android:name=".ListaVerbos2"
            android:label="@string/title_activity_lista_verbos2" >
        </activity>
        <activity
            android:name=".ActivityFinalJuego"
            android:label="@string/title_activity_activity_final_juego" >
        </activity>
    </application>

</manifest>


text:
package io.opentelemetry.opentracingshim;

import static io.opentelemetry.opentracingshim.TestUtils.getBaggageMap;
import static org.assertj.core.api.Assertions.assertThat;

import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.trace.SpanContext;
import io.opentelemetry.api.trace.SpanKind;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Context;
import io.opentelemetry.sdk.trace.ReadableSpan;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.data.LinkData;
import io.opentelemetry.sdk.trace.data.SpanData;
import io.opentelemetry.sdk.trace.data.StatusData;
import io.opentelemetry.sdk.trace.samplers.Sampler;
import io.opentelemetry.sdk.trace.samplers.SamplingResult;
import io.opentelemetry.semconv.trace.attributes.SemanticAttributes;
import io.opentracing.References;
import io.opentracing.tag.Tags;
import java.math.BigInteger;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

class SpanBuilderShimTest {

  private final SdkTracerProvider tracerSdkFactory = SdkTracerProvider.builder().build();
  private final Tracer tracer = tracerSdkFactory.get("SpanShimTest");
  private final TelemetryInfo telemetryInfo =
      new TelemetryInfo(tracer, OpenTracingPropagators.builder().build());

  private static final String SPAN_NAME = "Span";

  @BeforeEach
  void setUp() {
    GlobalOpenTelemetry.resetForTest();
  }

  @Test
  void default_values() {
    SpanShim span = (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).start();
    try {
      SpanData spanData = ((ReadableSpan) span.getSpan()).toSpanData();
      assertThat(spanData.getName()).isEqualTo(SPAN_NAME);
      assertThat(spanData.getStatus()).isEqualTo(StatusData.unset());
      assertThat(spanData.getSpanContext()).isNotEqualTo(SpanContext.getInvalid());
      assertThat(spanData.getKind()).isEqualTo(SpanKind.INTERNAL);
      assertThat(spanData.getAttributes().size()).isEqualTo(0);
      assertThat(spanData.getEvents()).hasSize(0);
      assertThat(spanData.getLinks()).hasSize(0);
    } finally {
      span.finish();
    }
  }

  @Test
  void parent_single() {
    SpanShim parentSpan = (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).start();
    try {
      SpanShim childSpan =
          (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).asChildOf(parentSpan).start();

      try {
        SpanData spanData = ((ReadableSpan) childSpan.getSpan()).toSpanData();
        assertThat(parentSpan.context().toSpanId()).isEqualTo(spanData.getParentSpanId());
      } finally {
        childSpan.finish();
      }
    } finally {
      parentSpan.finish();
    }
  }

  @Test
  void parent_multipleFollowsFrom() {
    SpanShim parentSpan1 = (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).start();
    SpanShim parentSpan2 = (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).start();

    try {
      SpanShim childSpan =
          (SpanShim)
              new SpanBuilderShim(telemetryInfo, SPAN_NAME)
                  .addReference(References.FOLLOWS_FROM, parentSpan1.context())
                  .addReference(References.FOLLOWS_FROM, parentSpan2.context())
                  .start();

      try {
        // If no parent of CHILD_OF type exists, use the first value as main parent.
        SpanData spanData = ((ReadableSpan) childSpan.getSpan()).toSpanData();
        assertThat(parentSpan1.context().toSpanId()).isEqualTo(spanData.getParentSpanId());
      } finally {
        childSpan.finish();
      }
    } finally {
      parentSpan1.finish();
      parentSpan2.finish();
    }
  }

  @Test
  void parent_multipleDifferentRefType() {
    SpanShim parentSpan1 = (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).start();
    SpanShim parentSpan2 = (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).start();
    SpanShim parentSpan3 = (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).start();

    try {
      SpanShim childSpan =
          (SpanShim)
              new SpanBuilderShim(telemetryInfo, SPAN_NAME)
                  .addReference(References.FOLLOWS_FROM, parentSpan1.context())
                  .addReference(References.CHILD_OF, parentSpan2.context())
                  .addReference(References.CHILD_OF, parentSpan3.context())
                  .start();

      try {
        // The first parent with CHILD_OF becomes the direct parent (if any).
        SpanData spanData = ((ReadableSpan) childSpan.getSpan()).toSpanData();
        assertThat(parentSpan2.context().toSpanId()).isEqualTo(spanData.getParentSpanId());
      } finally {
        childSpan.finish();
      }
    } finally {
      parentSpan1.finish();
      parentSpan2.finish();
      parentSpan3.finish();
    }
  }

  @Test
  void parent_multipleLinks() {
    SpanShim parentSpan1 = (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).start();
    SpanShim parentSpan2 = (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).start();
    SpanShim parentSpan3 = (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).start();

    try {
      SpanShim childSpan =
          (SpanShim)
              new SpanBuilderShim(telemetryInfo, SPAN_NAME)
                  .addReference(References.FOLLOWS_FROM, parentSpan1.context())
                  .addReference(References.CHILD_OF, parentSpan2.context())
                  .addReference(References.FOLLOWS_FROM, parentSpan3.context())
                  .start();

      try {
        SpanData spanData = ((ReadableSpan) childSpan.getSpan()).toSpanData();
        List<LinkData> links = spanData.getLinks();
        assertThat(links).hasSize(3);

        assertThat(links.get(0).getSpanContext()).isEqualTo(parentSpan1.getSpan().getSpanContext());
        assertThat(links.get(1).getSpanContext()).isEqualTo(parentSpan2.getSpan().getSpanContext());
        assertThat(links.get(2).getSpanContext()).isEqualTo(parentSpan3.getSpan().getSpanContext());
        assertThat(links.get(0).getAttributes().get(SemanticAttributes.OPENTRACING_REF_TYPE))
            .isEqualTo(SemanticAttributes.OpentracingRefTypeValues.FOLLOWS_FROM);
        assertThat(links.get(1).getAttributes().get(SemanticAttributes.OPENTRACING_REF_TYPE))
            .isEqualTo(SemanticAttributes.OpentracingRefTypeValues.CHILD_OF);
        assertThat(links.get(2).getAttributes().get(SemanticAttributes.OPENTRACING_REF_TYPE))
            .isEqualTo(SemanticAttributes.OpentracingRefTypeValues.FOLLOWS_FROM);

      } finally {
        childSpan.finish();
      }
    } finally {
      parentSpan1.finish();
      parentSpan2.finish();
      parentSpan3.finish();
    }
  }

  @Test
  void parent_wrongRefType() {
    SpanShim parentSpan = (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).start();
    try {
      SpanShim childSpan =
          (SpanShim)
              new SpanBuilderShim(telemetryInfo, SPAN_NAME)
                  .addReference("wrongreftype-value", parentSpan.context())
                  .start();

      try {
        // Incorrect typeref values get discarded.
        SpanData spanData = ((ReadableSpan) childSpan.getSpan()).toSpanData();
        assertThat(spanData.getParentSpanContext())
            .isEqualTo(io.opentelemetry.api.trace.SpanContext.getInvalid());
        assertThat(spanData.getLinks()).isEmpty();
      } finally {
        childSpan.finish();
      }
    } finally {
      parentSpan.finish();
    }
  }

  @Test
  void baggage_parent() {
    SpanShim parentSpan = (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).start();
    try {
      parentSpan.setBaggageItem("key1", "value1");

      SpanShim childSpan =
          (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).asChildOf(parentSpan).start();
      try {
        assertThat("value1").isEqualTo(childSpan.getBaggageItem("key1"));
        assertThat(getBaggageMap(parentSpan.context().baggageItems()))
            .isEqualTo(getBaggageMap(childSpan.context().baggageItems()));
      } finally {
        childSpan.finish();
      }
    } finally {
      parentSpan.finish();
    }
  }

  @Test
  void baggage_parentContext() {
    SpanShim parentSpan = (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).start();
    try {
      parentSpan.setBaggageItem("key1", "value1");

      SpanShim childSpan =
          (SpanShim)
              new SpanBuilderShim(telemetryInfo, SPAN_NAME).asChildOf(parentSpan.context()).start();
      try {
        assertThat("value1").isEqualTo(childSpan.getBaggageItem("key1"));
        assertThat(getBaggageMap(parentSpan.context().baggageItems()))
            .isEqualTo(getBaggageMap(childSpan.context().baggageItems()));
      } finally {
        childSpan.finish();
      }
    } finally {
      parentSpan.finish();
    }
  }

  @Test
  void baggage_multipleParents() {
    SpanShim parentSpan1 = (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).start();
    SpanShim parentSpan2 = (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).start();
    try {
      parentSpan1.setBaggageItem("key1", "value1");
      parentSpan2.setBaggageItem("key2", "value2");

      SpanShim childSpan =
          (SpanShim)
              new SpanBuilderShim(telemetryInfo, SPAN_NAME)
                  .addReference(References.FOLLOWS_FROM, parentSpan1.context())
                  .addReference(References.CHILD_OF, parentSpan2.context())
                  .start();
      try {
        assertThat(childSpan.getBaggageItem("key1")).isEqualTo("value1");
        assertThat(childSpan.getBaggageItem("key2")).isEqualTo("value2");
      } finally {
        childSpan.finish();
      }
    } finally {
      parentSpan1.finish();
      parentSpan2.finish();
    }
  }

  @Test
  void baggage_spanWithInvalidSpan() {
    io.opentelemetry.api.baggage.Baggage baggage =
        io.opentelemetry.api.baggage.Baggage.builder().put("foo", "bar").build();
    SpanShim span =
        new SpanShim(telemetryInfo, io.opentelemetry.api.trace.Span.getInvalid(), baggage);

    SpanShim childSpan =
        (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).asChildOf(span).start();
    assertThat(childSpan.getBaggage()).isEqualTo(baggage);
  }

  @Test
  void baggage_spanContextWithInvalidSpan() {
    io.opentelemetry.api.baggage.Baggage baggage =
        io.opentelemetry.api.baggage.Baggage.builder().put("foo", "bar").build();
    SpanContextShim spanContext =
        new SpanContextShim(
            telemetryInfo, io.opentelemetry.api.trace.Span.getInvalid().getSpanContext(), baggage);

    SpanShim childSpan =
        (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).asChildOf(spanContext).start();
    assertThat(childSpan.getBaggage()).isEqualTo(baggage);
  }

  @Test
  void parent_NullContextShim() {
    /* SpanContextShim is null until Span.context() or Span.getBaggageItem() are called.
     * Verify a null SpanContextShim in the parent is handled properly. */
    SpanShim parentSpan = (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).start();
    try {
      SpanShim childSpan =
          (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).asChildOf(parentSpan).start();
      try {
        assertThat(childSpan.context().baggageItems().iterator().hasNext()).isFalse();
      } finally {
        childSpan.finish();
      }
    } finally {
      parentSpan.finish();
    }
  }

  @Test
  void withStartTimestamp() {
    long micros = 123447307984L;
    SpanShim spanShim =
        (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).withStartTimestamp(micros).start();
    SpanData spanData = ((ReadableSpan) spanShim.getSpan()).toSpanData();
    assertThat(spanData.getStartEpochNanos()).isEqualTo(micros * 1000L);
  }

  @Test
  void setAttribute_errorAsBoolean() {
    SpanShim span1 =
        (SpanShim)
            new SpanBuilderShim(telemetryInfo, SPAN_NAME)
                .withTag(Tags.ERROR.getKey(), true)
                .start();
    SpanShim span2 =
        (SpanShim)
            new SpanBuilderShim(telemetryInfo, SPAN_NAME)
                .withTag(Tags.ERROR.getKey(), false)
                .start();
    try {
      SpanData spanData1 = ((ReadableSpan) span1.getSpan()).toSpanData();
      assertThat(spanData1.getStatus()).isEqualTo(StatusData.error());

      SpanData spanData2 = ((ReadableSpan) span2.getSpan()).toSpanData();
      assertThat(spanData2.getStatus()).isEqualTo(StatusData.ok());
    } finally {
      span1.finish();
      span2.finish();
    }
  }

  @Test
  void setAttribute_errorAsString() {
    SpanShim span1 =
        (SpanShim)
            new SpanBuilderShim(telemetryInfo, SPAN_NAME)
                .withTag(Tags.ERROR.getKey(), "tRuE")
                .start();
    SpanShim span2 =
        (SpanShim)
            new SpanBuilderShim(telemetryInfo, SPAN_NAME)
                .withTag(Tags.ERROR.getKey(), "FaLsE")
                .start();
    try {
      SpanData spanData1 = ((ReadableSpan) span1.getSpan()).toSpanData();
      assertThat(spanData1.getStatus()).isEqualTo(StatusData.error());

      SpanData spanData2 = ((ReadableSpan) span2.getSpan()).toSpanData();
      assertThat(spanData2.getStatus()).isEqualTo(StatusData.ok());
    } finally {
      span1.finish();
      span2.finish();
    }
  }

  @Test
  void setAttribute_unrecognizedType() {
    SpanShim span =
        (SpanShim)
            new SpanBuilderShim(telemetryInfo, SPAN_NAME).withTag("foo", BigInteger.TEN).start();
    try {
      SpanData spanData = ((ReadableSpan) span.getSpan()).toSpanData();
      assertThat(spanData.getAttributes().size()).isEqualTo(1);
      assertThat(spanData.getAttributes().get(AttributeKey.stringKey("foo"))).isEqualTo("10");
    } finally {
      span.finish();
    }
  }

  @Test
  void setAttributes_beforeSpanStart() {
    SdkTracerProvider tracerSdkFactory =
        SdkTracerProvider.builder().setSampler(SamplingPrioritySampler.INSTANCE).build();
    Tracer tracer = tracerSdkFactory.get("SpanShimTest");
    TelemetryInfo telemetryInfo =
        new TelemetryInfo(tracer, OpenTracingPropagators.builder().build());

    SpanBuilderShim spanBuilder1 = new SpanBuilderShim(telemetryInfo, SPAN_NAME);
    SpanBuilderShim spanBuilder2 = new SpanBuilderShim(telemetryInfo, SPAN_NAME);
    SpanShim span1 =
        (SpanShim)
            spanBuilder1
                .withTag(
                    SamplingPrioritySampler.SAMPLING_PRIORITY_TAG,
                    SamplingPrioritySampler.UNSAMPLED_VALUE)
                .start();
    SpanShim span2 =
        (SpanShim)
            spanBuilder2
                .withTag(
                    SamplingPrioritySampler.SAMPLING_PRIORITY_TAG,
                    SamplingPrioritySampler.SAMPLED_VALUE)
                .start();
    assertThat(span1.getSpan().isRecording()).isFalse();
    assertThat(span2.getSpan().isRecording()).isTrue();
    assertThat(span1.getSpan().getSpanContext().isSampled()).isFalse();
    assertThat(span2.getSpan().getSpanContext().isSampled()).isTrue();
  }

  static final class SamplingPrioritySampler implements Sampler {
    static final SamplingPrioritySampler INSTANCE = new SamplingPrioritySampler();
    static final String SAMPLING_PRIORITY_TAG = "sampling.priority";
    static final long UNSAMPLED_VALUE = 0;
    static final long SAMPLED_VALUE = 1;

    @Override
    public String getDescription() {
      return "SamplingPrioritySampler";
    }

    @Override
    public SamplingResult shouldSample(
        Context parentContext,
        String traceId,
        String name,
        SpanKind spanKind,
        Attributes attributes,
        List<LinkData> parentLinks) {

      if (attributes.get(AttributeKey.longKey(SAMPLING_PRIORITY_TAG)) == UNSAMPLED_VALUE) {
        return SamplingResult.drop();
      }

      return SamplingResult.recordAndSample();
    }
  }
}


text:
"use strict";

/* Parser combinator based parser for the
 * protobuf text format.
 */

var Parsimmon = require('parsimmon');

var regex = Parsimmon.regex
  , string = Parsimmon.string
  , optWhitespace = Parsimmon.optWhitespace
  , lazy = Parsimmon.lazy
  , alt = Parsimmon.alt
  , seq = Parsimmon.seq;

var comment = regex(/#.+/).then(optWhitespace.atMost(1));
var whitespace = optWhitespace.then(comment.atMost(1));

var lexeme = function(p){ return p.skip(whitespace); }

var colon = lexeme(string(':'));

var lbrace = lexeme(string('{'))
  , rbrace = lexeme(string('}'));

var stripFirstLast = function(x) {
  return x.substr(1, x.length-2);
};

var identifier = lexeme(regex(/[a-zA-Z_][0-9a-zA-Z_+-]*/));
var doubleString = lexeme(regex(/\"([^\"\n\\\\]|\\\\.)*(\"|\\\\?$)/).map(stripFirstLast));
var singleString = lexeme(regex(/\'([^\'\n\\\\]|\\\\.)*(\'|\\\\?$)/).map(stripFirstLast));

var number = lexeme(regex(/[.]?[0-9+-][0-9a-zA-Z_.+-]*/)).map(Number);
var trueLiteral = lexeme(string('true')).result(true);
var falseLiteral = lexeme(string('false')).result(false);

var expr = lazy('an expression', function() { return alt(pair, message).many(); });

var message = seq(identifier, colon.times(0, 1).then(lbrace).then(expr).skip(rbrace))
                .map(function(message) {
                  return { type: 'message', name: message[0], values: message[1] };
                });

var value = alt(trueLiteral, falseLiteral, number, doubleString, singleString, identifier);

var pair = seq(identifier.skip(colon), value)
            .map(function(pair) {
              return { type: 'pair', name: pair[0], value: pair[1] };
            });

module.exports = function(input) {
  var result = whitespace.then(expr).parse(input);
  if (!result.status) {
    result.error = Parsimmon.formatError(input, result);
  }
  return result;
};


text:
/*
 */
package com.agricraft.agricore.util;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author Ryan
 */
public class TypeHelperTest {

    private final int int_a = 1;
    private final int int_b = 2;
    private final int int_c = 3;

    private final double double_a = 1.0;
    private final double double_b = 2.0;
    private final double double_c = 3.0;

    private final String[] array_string = { "abc", "123", "you and me" };
    private final List<String> list_string = Arrays.asList(array_string);
    private final Set<String> set_string = Arrays.stream(array_string).collect(Collectors.toSet());

    /**
     * Test of forEachIn method, of class ReflectionHelper.
     */
    @Test
    public void testAsArray() {
        // Test Strings
        assertArrayEquals("Conversion from list to array works.", array_string, TypeHelper.asArray(list_string, String.class));
        final String[] set_expected = Arrays.copyOf(array_string, array_string.length);
        Arrays.sort(set_expected);
        final String[] set_result = TypeHelper.asArray(set_string, String.class);
        Arrays.sort(set_result);
        assertArrayEquals("Conversion from set to array works.", set_expected, set_result);
    }

}


text:
import { applyMiddleware, compose, createStore } from 'redux'

import DockMonitor from 'redux-devtools-dock-monitor'
import LogMonitor from 'redux-devtools-log-monitor'
import React from 'react'

import { createDevTools } from 'redux-devtools'
import reducer from './reducer'
import { routerMiddleware } from 'react-router-redux'

export const DevTools = createDevTools(
    <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-q">
        <LogMonitor theme="tomorrow" preserveScrollTop={false}/>
    </DockMonitor>
)

export function configureStore(history, initialState) {

    let devTools = []
    if (typeof document !== `undefined`) {
        devTools = [ DevTools.instrument() ]
    }

    const store = createStore(
        reducer,
        initialState,
        compose(
            applyMiddleware(
                routerMiddleware(history)
            ),
            ...devTools
        )
    )

    return store
}


text:
'use strict';

angular.module('swFrontApp')
  .controller('TransferCtrl',["$scope","$location","$http","ngDialog", "billDrawer", function ($scope, $location, $http, ngDialog, billDrawer) {

    $scope.currentTransferElement;
    $scope.recipientCheck = true;
    $scope.canceledTrasfer = false;
    $scope.ammountExcedsBalance = false;
    $scope.pausedTrasfer = false;
    $scope.selectedIndex = -1; // Whatever the default selected index is, use -1 for no selection
    $scope.cancelWarningMsg = false;

    $scope.accountNumber = 'AC30345897';
    $scope.customerID;

    $scope.transferElements = [
      angular.element('.transfer-step0'),
      angular.element('.transfer-step1'),
      angular.element('.transfer-step2'),
      angular.element('.transfer-step3'),
      angular.element('.transfer-step4'),
      angular.element('.transfer-step5')
    ]

    $scope.transferData = {
      recipient : '',
      amount : '',
      left : ''
    }

    $http.get(  'http://localhost:3000/accounts/' + $scope.accountNumber,
      { "headers": { "Authorization": "Basic " + btoa("bob" + ":" + "secret") }
    })
    .success(function(response) {
      $scope.accountBalance = parseFloat(response[0].currentBalance)/100;
      $scope.customerID = response[0].customerID;
    })
    .then(function() {
      $http.get(  'http://localhost:3000/recipients/customer/' + $scope.customerID,
        { "headers": { "Authorization": "Basic " + btoa("bob" + ":" + "secret") }
      })
      .success(function(response) {
        $scope.recipients = response;
      })
    });

    $scope.go = function ( path ) {
      $location.path( path );
    };

    // sets variables to start a new transfer
    $scope.startTransfer = function () {
      angular.element('.sout-btn').hide();

      $scope.transferElements[0].hide();
      $scope.transferElements[1].show();

      $scope.currentTransferElement = 1;
      $scope.recipientCheck = true;
      $scope.canceledTrasfer = false;
      $scope.pausedTrasfer = false;
      $scope.ammountInput = '';

      $scope.step4Value1 = false;
      $scope.step4Value2 = false;

    }

    $scope.stopTransfer = function () {
      $scope.pausedTrasfer = true;
      window.print();
    }

    $scope.cancelWarning = function () {
      $scope.cancelWarningMsg = !$scope.cancelWarningMsg;
    }

    $scope.cancelTransfer = function () {
      angular.element('.sout-btn').show();
      angular.element('.cancel-warning').hide();
      for (var i=0; i < $scope.transferElements.length ; i++){
        $scope.transferElements[i].hide();
      }
      $scope.transferElements[0].show();
      $scope.transferData = {
        recipient : '',
        amount : '',
        left : ''
      }
      $scope.canceledTrasfer = true;
      $scope.currentTransferElement = 0;
      $scope.recipientCheck = true;
    }

    $scope.pauseTransfer = function () {
      angular.element('.sout-btn').show();
      angular.element('.pause-warning').hide();
      for (var i=0; i < $scope.transferElements.length ; i++){
        $scope.transferElements[i].hide();
      }
      $scope.transferElements[0].show();
      $scope.transferData = {
        recipient : '',
        amount : '',
        left : ''
      }
      $scope.pausedTrasfer = true;
      $scope.currentTransferElement = 0;
      $scope.recipientCheck = true;
    }

    $scope.nextStepTransfer = function() {

      $scope.pausedTrasfer = false;
      $scope.cancelWarningMsg = false;

      if ($scope.currentTransferElement != 6){
        $scope.transferElements[$scope.currentTransferElement].hide();
        $scope.transferElements[$scope.currentTransferElement+1].show();
      }
      $scope.currentTransferElement = $scope.currentTransferElement+1;
    }

    $scope.backStepTransfer = function () {
      if ($scope.currentTransferElement != 0){
        $scope.transferElements[$scope.currentTransferElement].hide();
        $scope.transferElements[$scope.currentTransferElement-1].show();
      }
      $scope.currentTransferElement = $scope.currentTransferElement-1;
    }

    // dialog control for any new transfer recipiants
    $scope.addTransferRecipient = function (){
      ngDialog.open({
        template: '<form role="form" ng-submit="close()">
 Name <input type="text" class="form-control" id="exampleInput1" placeholder="Name">
Suspendisse vel consequat elit, et vehicula tortor.

 Bank <input type="text" class="form-control" id="exampleInput2" placeholder="Bank">
Suspendisse vel consequat elit, et vehicula tortor.

 IBAN <input type="text" class="form-control" id="exampleInput3" placeholder="IBAN">
Suspendisse vel consequat elit, et vehicula tortor.

<button type="submit" class="btn btn-default">Submit</button> </form>',
        plain: true,
        controller: ['$scope', function($scope) {
          $scope.close = function () {
            $scope.closeThisDialog('');
          }
        }]
      });
    }

    // lets the user just select one user at a time
    $scope.itemClicked = function ($index) {
      $scope.selectedIndex = $index;
      $scope.recipientCheck = false;
      $scope.transferData.recipient = $scope.recipients[$index].recipientName;
      $scope.transferData.photo = $scope.recipients[$index].recipientPhoto;
    };

    // watches transfer ammount input field for any changes
    $scope.$watch( 'ammountInput' , function () {
      if ($scope.transferAmmountForm.transferAmmountInput.$dirty && !$scope.transferAmmountForm.transferAmmountInput.$error.pattern && !$scope.transferAmmountForm.transferAmmountInput.$error.required) {

        //check if the user inserts a comma, and replace it with a .
        if ($scope.ammountInput.indexOf(",") > -1) {
          $scope.transAmmountInput = $scope.ammountInput.replace(',','.');
        }else {
          $scope.transAmmountInput = $scope.ammountInput;
        }

        // check if the user has enough money in their account
        if ($scope.accountBalance - $scope.transAmmountInput < 0) {
          $scope.ammountExcedsBalance = true;
        } else {
          $scope.ammountExcedsBalance = false;
        }

        // draw bills function
        if ($scope.ammountExcedsBalance == false && !$scope.transferAmmountForm.transferAmmountInput.$error.pattern){
          $scope.currency = billDrawer.draw($scope.transAmmountInput);
          var a=0,b=0;
          $scope.bills = [];
          $scope.coins = [];
          for (var i = 0; i < $scope.currency.length; i++){
            if ($scope.currency[i].type == 'bill'){
              $scope.bills[a] = $scope.currency[i];
              a++;
            } else if($scope.currency[i].type == 'coin'){
              $scope.coins[b] = $scope.currency[i];
              b++;
            }
          }
        }

        // give ammount to the transferData object
        $scope.transferData.amount = $scope.transAmmountInput;

        // calculate how much money is left
        $scope.transferData.left = $scope.accountBalance - $scope.transferData.amount;

      }

      $scope.getNumber = function(num) {
        return new Array(num);
      }

      $scope.printPage = function() {
        window.print();
      }

      $scope.updateAccount = function() {
        $http.get( 'http://localhost:3000/accounts/' + $scope.accountNumber + '/updateBalance/' +  ($scope.transferData.left) * 100,
          { "headers": { "Authorization": "Basic " + btoa("bob" + ":" + "secret") } }
        )
        .success(function( ) {
          console.log('Account Updated!');
        })
      }

      $scope.savePage = function () {
        document.execCommand("SaveAs")
      }

      $scope.sendEmail = function () {
        ngDialog.open({
          template: '<form role="form" ng-submit="close()">
 Email <input type="text" class="form-control" id="exampleInput1" placeholder="Name">

 Message <input type="text" class="form-control" id="exampleInput2" placeholder="Bank">
<button type="submit" class="btn btn-default">Submit</button> </form>',
          plain: true,
          controller: ['$scope', function($scope) {
            $scope.close = function () {
              $scope.closeThisDialog('');
            }
          }]
        });
      }

    });
  }])


text:
package org.camunda.bpm.engine.impl.form;

import org.camunda.bpm.engine.form.StartFormData;
import org.camunda.bpm.engine.repository.ProcessDefinition;

/**
 * @author Tom Baeyens
 */
public class StartFormDataImpl extends FormDataImpl implements StartFormData {

  private static final long serialVersionUID = 1L;

  protected ProcessDefinition processDefinition;

  // getters and setters //////////////////////////////////////////////////////

  public ProcessDefinition getProcessDefinition() {
    return processDefinition;
  }

  public void setProcessDefinition(ProcessDefinition processDefinition) {
    this.processDefinition = processDefinition;
  }
}


text:
<?xml version="1.0"?>
<project name="PHPUnit_Function_Mocker" default="build">
    <target name="build" description="Run CI jobs" depends="clean,prepare,phpunit"/>

    <target name="clean">
        <delete dir="${basedir}/build/" includes="**/*" excludes="**/.gitkeep"/>
        <mkdir dir="${basedir}/build/logs/"/>
        <mkdir dir="${basedir}/build/coverage/"/>
    </target>

    <target name="prepare">
        <get src="http://getcomposer.org/composer.phar" dest="build/composer.phar"/>
        <exec executable="php" failonerror="true">
            <arg value="build/composer.phar"/>
            <arg value="install"/>
            <arg value="--dev"/>
        </exec>
    </target>

    <target name="phpunit">
        <exec executable="phpunit" failonerror="true"/>
    </target>
</project>


text:
package org.apache.calcite.sql;

import org.apache.calcite.linq4j.function.Function1;
import org.apache.calcite.linq4j.function.Functions;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeFactory;
import org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.calcite.sql.type.SqlOperandTypeChecker;
import org.apache.calcite.sql.type.SqlOperandTypeInference;
import org.apache.calcite.sql.type.SqlReturnTypeInference;
import org.apache.calcite.sql.type.SqlTypeName;
import org.apache.calcite.sql.validate.SqlValidator;
import org.apache.calcite.sql.validate.SqlValidatorScope;
import org.apache.calcite.util.Util;

import com.google.common.collect.ImmutableList;

import java.util.List;

import static org.apache.calcite.util.Static.RESOURCE;

/**
 * A SqlFunction is a type of operator which has conventional
 * function-call syntax.
 */
public class SqlFunction extends SqlOperator {
  /** Function that generates "arg{n}" for the {@code n}th argument name. */
  private static final Function1<Integer, String> ARG_FN =
      new Function1<Integer, String>() {
        public String apply(Integer a0) {
          return "arg" + a0;
        }
      };

  //~ Instance fields --------------------------------------------------------

  private final SqlFunctionCategory category;

  private final SqlIdentifier sqlIdentifier;

  private final List<RelDataType> paramTypes;

  //~ Constructors -----------------------------------------------------------

  /**
   * Creates a new SqlFunction for a call to a builtin function.
   *
   * @param name                 Name of builtin function
   * @param kind                 kind of operator implemented by function
   * @param returnTypeInference  strategy to use for return type inference
   * @param operandTypeInference strategy to use for parameter type inference
   * @param operandTypeChecker   strategy to use for parameter type checking
   * @param category             categorization for function
   */
  public SqlFunction(
      String name,
      SqlKind kind,
      SqlReturnTypeInference returnTypeInference,
      SqlOperandTypeInference operandTypeInference,
      SqlOperandTypeChecker operandTypeChecker,
      SqlFunctionCategory category) {
    // We leave sqlIdentifier as null to indicate
    // that this is a builtin.  Same for paramTypes.
    this(name, null, kind, returnTypeInference, operandTypeInference,
        operandTypeChecker, null, category);

    assert !((category == SqlFunctionCategory.USER_DEFINED_CONSTRUCTOR)
        && (returnTypeInference == null));
  }

  /**
   * Creates a placeholder SqlFunction for an invocation of a function with a
   * possibly qualified name. This name must be resolved into either a builtin
   * function or a user-defined function.
   *
   * @param sqlIdentifier        possibly qualified identifier for function
   * @param returnTypeInference  strategy to use for return type inference
   * @param operandTypeInference strategy to use for parameter type inference
   * @param operandTypeChecker   strategy to use for parameter type checking
   * @param paramTypes           array of parameter types
   * @param funcType             function category
   */
  public SqlFunction(
      SqlIdentifier sqlIdentifier,
      SqlReturnTypeInference returnTypeInference,
      SqlOperandTypeInference operandTypeInference,
      SqlOperandTypeChecker operandTypeChecker,
      List<RelDataType> paramTypes,
      SqlFunctionCategory funcType) {
    this(Util.last(sqlIdentifier.names), sqlIdentifier, SqlKind.OTHER_FUNCTION,
        returnTypeInference, operandTypeInference, operandTypeChecker,
        paramTypes, funcType);
  }

  /**
   * Internal constructor.
   */
  protected SqlFunction(
      String name,
      SqlIdentifier sqlIdentifier,
      SqlKind kind,
      SqlReturnTypeInference returnTypeInference,
      SqlOperandTypeInference operandTypeInference,
      SqlOperandTypeChecker operandTypeChecker,
      List<RelDataType> paramTypes,
      SqlFunctionCategory category) {
    super(name, kind, 100, 100, returnTypeInference, operandTypeInference,
        operandTypeChecker);

    this.sqlIdentifier = sqlIdentifier;
    this.category = category;
    this.paramTypes =
        paramTypes == null ? null : ImmutableList.copyOf(paramTypes);
    assert category != null;
  }

  //~ Methods ----------------------------------------------------------------

  public SqlSyntax getSyntax() {
    return SqlSyntax.FUNCTION;
  }

  /**
   * @return fully qualified name of function, or null for a builtin function
   */
  public SqlIdentifier getSqlIdentifier() {
    return sqlIdentifier;
  }

  /**
   * @return fully qualified name of function
   */
  public SqlIdentifier getNameAsId() {
    if (sqlIdentifier != null) {
      return sqlIdentifier;
    }
    return new SqlIdentifier(
        getName(),
        SqlParserPos.ZERO);
  }

  /**
   * @return array of parameter types, or null for builtin function
   */
  public List<RelDataType> getParamTypes() {
    return paramTypes;
  }

  /**
   * Returns a list of parameter names.
   *
   *
The default implementation returns {@code [arg0, arg1, ..., argN]}.
   */
  public List<String> getParamNames() {
    return Functions.generate(paramTypes.size(), ARG_FN);
  }

  public void unparse(
      SqlWriter writer,
      SqlCall call,
      int leftPrec,
      int rightPrec) {
    getSyntax().unparse(writer, this, call, leftPrec, rightPrec);
  }

  /**
   * @return function category
   */
  public SqlFunctionCategory getFunctionType() {
    return this.category;
  }

  /**
   * Returns whether this function allows a DISTINCT or
   * ALL quantifier. The default is false; some aggregate
   * functions return true.
   */
  public boolean isQuantifierAllowed() {
    return false;
  }

  public void validateCall(
      SqlCall call,
      SqlValidator validator,
      SqlValidatorScope scope,
      SqlValidatorScope operandScope) {
    // This implementation looks for the quantifier keywords DISTINCT or
    // ALL as the first operand in the list.  If found then the literal is
    // not called to validate itself.  Further the function is checked to
    // make sure that a quantifier is valid for that particular function.
    //
    // If the first operand does not appear to be a quantifier then the
    // parent ValidateCall is invoked to do normal function validation.

    super.validateCall(call, validator, scope, operandScope);
    validateQuantifier(validator, call);
  }

  /**
   * Throws a validation error if a DISTINCT or ALL quantifier is present but
   * not allowed.
   */
  protected void validateQuantifier(SqlValidator validator, SqlCall call) {
    if ((null != call.getFunctionQuantifier()) && !isQuantifierAllowed()) {
      throw validator.newValidationError(call.getFunctionQuantifier(),
          RESOURCE.functionQuantifierNotAllowed(call.getOperator().getName()));
    }
  }

  public RelDataType deriveType(
      SqlValidator validator,
      SqlValidatorScope scope,
      SqlCall call) {
    return deriveType(validator, scope, call, true);
  }

  private RelDataType deriveType(
      SqlValidator validator,
      SqlValidatorScope scope,
      SqlCall call,
      boolean convertRowArgToColumnList) {

    // Scope for operands. Usually the same as 'scope'.
    final SqlValidatorScope operandScope = scope.getOperandScope(call);

    // Indicate to the validator that we're validating a new function call
    validator.pushFunctionCall();

    // If any arguments are named, construct a map.
    final ImmutableList.Builder<String> nameBuilder = ImmutableList.builder();
    final ImmutableList.Builder<SqlNode> argBuilder = ImmutableList.builder();
    for (SqlNode operand : call.getOperandList()) {
      if (operand.getKind() == SqlKind.ARGUMENT_ASSIGNMENT) {
        final List<SqlNode> operandList = ((SqlCall) operand).getOperandList();
        nameBuilder.add(((SqlIdentifier) operandList.get(1)).getSimple());
        argBuilder.add(operandList.get(0));
      }
    }
    ImmutableList<String> argNames = nameBuilder.build();
    final List<SqlNode> args;
    if (argNames.isEmpty()) {
      args = call.getOperandList();
      argNames = null;
    } else {
      if (argNames.size() < call.getOperandList().size()) {
        throw validator.newValidationError(call,
            RESOURCE.someButNotAllArgumentsAreNamed());
      }
      int duplicate = Util.firstDuplicate(argNames);
      if (duplicate >= 0) {
        throw validator.newValidationError(call,
            RESOURCE.duplicateArgumentName(argNames.get(duplicate)));
      }
      args = argBuilder.build();
    }
    try {
      final ImmutableList.Builder<RelDataType> argTypeBuilder =
          ImmutableList.builder();
      boolean containsRowArg = false;
      for (SqlNode operand : args) {
        RelDataType nodeType;

        // for row arguments that should be converted to ColumnList
        // types, set the nodeType to a ColumnList type but defer
        // validating the arguments of the row constructor until we know
        // for sure that the row argument maps to a ColumnList type
        if (operand.getKind() == SqlKind.ROW && convertRowArgToColumnList) {
          containsRowArg = true;
          RelDataTypeFactory typeFactory = validator.getTypeFactory();
          nodeType = typeFactory.createSqlType(SqlTypeName.COLUMN_LIST);
        } else {
          nodeType = validator.deriveType(operandScope, operand);
        }
        validator.setValidatedNodeType(operand, nodeType);
        argTypeBuilder.add(nodeType);
      }

      final List<RelDataType> argTypes = argTypeBuilder.build();
      SqlFunction function =
          SqlUtil.lookupRoutine(
              validator.getOperatorTable(),
              getNameAsId(),
              argTypes,
              argNames,
              getFunctionType());

      // if we have a match on function name and parameter count, but
      // couldn't find a function with  a COLUMN_LIST type, retry, but
      // this time, don't convert the row argument to a COLUMN_LIST type;
      // if we did find a match, go back and re-validate the row operands
      // (corresponding to column references), now that we can set the
      // scope to that of the source cursor referenced by that ColumnList
      // type
      if (containsRowArg) {
        if (function == null
            && SqlUtil.matchRoutinesByParameterCount(
                validator.getOperatorTable(), getNameAsId(), argTypes,
                getFunctionType())) {
          // remove the already validated node types corresponding to
          // row arguments before re-validating
          for (SqlNode operand : args) {
            if (operand.getKind() == SqlKind.ROW) {
              validator.removeValidatedNodeType(operand);
            }
          }
          return deriveType(validator, scope, call, false);
        } else if (function != null) {
          validator.validateColumnListParams(function, argTypes, args);
        }
      }

      if (getFunctionType() == SqlFunctionCategory.USER_DEFINED_CONSTRUCTOR) {
        return validator.deriveConstructorType(scope, call, this, function,
            argTypes);
      }
      if (function == null) {
        throw validator.handleUnresolvedFunction(call, this, argTypes,
            argNames);
      }

      // REVIEW jvs 25-Mar-2005:  This is, in a sense, expanding
      // identifiers, but we ignore shouldExpandIdentifiers()
      // because otherwise later validation code will
      // choke on the unresolved function.
      ((SqlBasicCall) call).setOperator(function);
      return function.validateOperands(
          validator,
          operandScope,
          call);
    } finally {
      validator.popFunctionCall();
    }
  }
}

// End SqlFunction.java


text:
require "hipchat_exception_notifier/version"
require "hipchat"

class HipchatExceptionNotifier
  def self.default_ignore_exceptions
    [].tap do |exceptions|
      exceptions << ::ActiveRecord::RecordNotFound if defined? ::ActiveRecord::RecordNotFound
      exceptions << ::AbstractController::ActionNotFound if defined? ::AbstractController::ActionNotFound
      exceptions << ::ActionController::RoutingError if defined? ::ActionController::RoutingError
    end
  end

  def initialize(app, options = {})
    @app, @options = app, options
    @options[:ignore_exceptions] ||= self.class.default_ignore_exceptions
  end

  def call(env)
    @app.call(env)
  rescue Exception => ex
    unless Array.wrap(@options[:ignore_exceptions]).include?(ex.class)
      deliver_exception(ex)
    end

    raise ex
  end

  private

  def deliver_exception(ex)
    client = HipChat::Client.new(hipchat_token, hipchat_options)
    client[hipchat_room_name].
      send(hipchat_user, "Error: #{ex.message}", notify: hipchat_announce, color: hipchat_color)
  end

  def hipchat_token
    @options.fetch(:token)
  end

  def hipchat_room_name
    @options.fetch(:room_name)
  end

  def hipchat_user
    @options.fetch(:user)
  end

  def hipchat_announce
    @options.fetch(:announce) { false }
  end

  def hipchat_options
    @options.fetch(:options) { Hash.new }
  end

  def hipchat_color
    @options.fetch(:color) { 'yellow' }
  end
end