text:
require 'oauth_multi_db/action_controller'

module OauthMultiDb
  class Engine < Rails::Engine
    config.after_initialize do
    end
  end
end

ActionController::Base.send :include, OauthMultiDb::ActionController

redpajama_set_name: RedPajamaGithub


text:
import mimetypes
import os

from cached_property import cached_property

from . import api
from .compat import urljoin
from .requestor import APIRequestor

__all__ = ('Client', 'client')

class Client(object):
    host = 'mntge.com'
    protocol = 'https'
    timeout = 10

    def __init__(self, subdomain, token=None):
        self.subdomain = subdomain
        self.token = token
        self.requestor = APIRequestor(self)

    @property
    def domain(self):
        return '{0}.{1}'.format(self.subdomain, self.host)

    def request(self, endpoint, method=None, **kwargs):
        kwargs.setdefault('timeout', self.timeout)
        return self.requestor.request(self.url(endpoint), method, **kwargs)

    def url(self, endpoint):
        return '{protocol}://{domain}/api/v1/{endpoint}/'.format(
            protocol=self.protocol,
            domain=self.domain,
            endpoint=endpoint,
        )

    def authenticate(self, email, password):
        response = self.request('user', method='post', data={
            'username': email,
            'password': password
        })
        self.token = response.get('data', {}).get('token')
        if self.token is None:
            return False
        return True

    def user(self):
        if self.token:
            return self.request('user')

    def execute(self, **kwargs):
        queryset = {key: executable.as_dict()
            for key, executable in kwargs.items()}
        return self.request('execute', method='post', json=queryset)

    @cached_property
    def documents(self):
        return api.DocumentAPI(self)

    @cached_property
    def files(self):
        return api.FileAPI(self)

    @cached_property
    def policies(self):
        return api.PolicyAPI(self)

    @cached_property
    def project(self):
        return api.ProjectAPI(self)

    @cached_property
    def roles(self):
        return api.RoleAPI(self)

    @cached_property
    def scheduler(self):
        return api.SchedulerAPI(self)

    @cached_property
    def schemas(self):
        return api.SchemaAPI(self)

    @cached_property
    def tasks(self):
        return api.TaskAPI(self)

    @cached_property
    def users(self):
        return api.UserAPI(self)

client = Client(
    subdomain=os.environ.get('MONTAGE_SUBDOMAIN'),
    token=os.environ.get('MONTAGE_TOKEN')
)


text:
<?php

##|+PRIV
##|*IDENT=page-diagnostics-packetcapture
##|*NAME=Diagnostics: Packet Capture
##|*DESCR=Allow access to the 'Diagnostics: Packet Capture' page.
##|*MATCH=diag_packet_capture.php*
##|-PRIV

$allowautocomplete = true;

function fixup_host_logic($value) {
	return str_replace(array(" ", ",", "+", "|", "!"), array("", "and ", "and ", "or ", "not "), $value);
}

function strip_host_logic($value) {
	return str_replace(array(" ", ",", "+", "|", "!"), array("", "", "", "", ""), $value);
}

function get_host_boolean($value, $host) {
	$value = str_replace(array("!", $host), array("", ""), $value);
	$andor = "";
	switch (trim($value)) {
		case "|":
			$andor = "or ";
			break;
		case ",":
		case "+":
			$andor = "and ";
			break;
	}

	return $andor;
}

function has_not($value) {
	return strpos($value, '!') !== false;
}

function fixup_not($value) {
	return str_replace("!", "not ", $value);
}

function strip_not($value) {
	return ltrim(trim($value), '!');
}

function fixup_host($value, $position) {
	$host = strip_host_logic($value);
	$not = has_not($value) ? "not " : "";
	$andor = ($position > 0) ? get_host_boolean($value, $host) : "";
	if (is_ipaddr($host)) {
		return "{$andor}host {$not}" . $host;
	} elseif (is_subnet($host)) {
		return "{$andor}net {$not}" . $host;
	} elseif (is_macaddr($host, false)) {
		return "{$andor}ether host {$not}" . $host;
	} elseif (is_macaddr($host, true)) {
		/* Try to match a partial MAC address. tcpdump only allows
		 * matching 1, 2, or 4 byte chunks so enforce that limit
		 */
		$searchmac = "0x";
		$partcount = 0;
		/* is_macaddr will fail a partial match that has empty sections
		 * but sections may only have one digit (leading 0) so add a
		 * left 0 pad.
		 */
		foreach (explode(':', $host) as $mp) {
			$searchmac .= str_pad($mp, 2, "0", STR_PAD_LEFT);
			$partcount++;
		}
		if (!in_array($partcount, array(1, 2, 4))) {
			return "";
		}
		$eq = has_not($value) ? "!=" : "==";
		// ether[0:2] == 0x0090 or ether[6:2] == 0x0090
		return "{$andor} ( ether[0:{$partcount}] {$eq} {$searchmac} or ether[6:{$partcount}] {$eq} {$searchmac} )";
	} else {
		return "";
	}
}

if ($_POST['downloadbtn'] == gettext("Download Capture")) {
	$nocsrf = true;
}

$pgtitle = array(gettext("Diagnostics"), gettext("Packet Capture"));
require_once("guiconfig.inc");
require_once("pfsense-utils.inc");
require_once("ipsec.inc");

$fp = "/root/";
$fn = "packetcapture.cap";
$snaplen = 0;//default packet length
$count = 100;//default number of packets to capture

$fams = array('ip', 'ip6');
$protos = array('icmp', 'icmp6', 'tcp', 'udp', 'arp', 'carp', 'esp', 'pfsync',
		        '!icmp', '!icmp6', '!tcp', '!udp', '!arp', '!carp', '!esp', '!pfsync');

$input_errors = array();

$interfaces = get_configured_interface_with_descr();
if (ipsec_enabled()) {
	$interfaces['enc0'] = "IPsec";
}
$interfaces['lo0'] = "Localhost";

foreach (array('server' => gettext('OpenVPN Server'), 'client' => gettext('OpenVPN Client')) as $mode => $mode_descr) {
	if (is_array($config['openvpn']["openvpn-{$mode}"])) {
		foreach ($config['openvpn']["openvpn-{$mode}"] as $id => $setting) {
			if (!isset($setting['disable'])) {
				$interfaces['ovpn' . substr($mode, 0, 1) . $setting['vpnid']] = $mode_descr . ": ".htmlspecialchars($setting['description']);
			}
		}
	}
}

if ($_POST) {
	$host = $_POST['host'];
	$selectedif = $_POST['interface'];
	$promiscuous = isset($_POST['promiscuous']);
	$count = $_POST['count'];
	$snaplen = $_POST['snaplen'];
	$port = $_POST['port'];
	$detail = $_POST['detail'];
	$fam = $_POST['fam'];
	$proto = $_POST['proto'];

	if (!array_key_exists($selectedif, $interfaces)) {
		$input_errors[] = gettext("Invalid interface.");
	}

	if ($fam !== "" && $fam !== "ip" && $fam !== "ip6") {
		$input_errors[] = gettext("Invalid address family.");
	}

	if ($fam !== "" && $proto !== "") {
		if ($fam == "ip" && $proto == "icmp6") {
			$input_errors[] = gettext("IPv4 with ICMPv6 is not valid.");
		}
		if ($fam == "ip6" && $proto == "icmp") {
			$input_errors[] = gettext("IPv6 with ICMP is not valid.");
		}
		if ($fam == "ip6" && $proto =="arp") {
			$input_errors[] = gettext("IPv6 with ARP is not valid.");
		}
	}

	if ($proto !== "" && !in_array(strip_not($proto), $protos)) {
		$input_errors[] = gettext("Invalid protocol.");
	}

	if ($host != "") {
		$host_string = str_replace(array(" ", "|", ","), array("", "#|", "#+"), $host);

		if (strpos($host_string, '#') === false) {
			$hosts = array($host);
		} else {
			$hosts = explode('#', $host_string);
		}

		foreach ($hosts as $h) {
			$h = strip_host_logic($h);
			if (!is_subnet($h) && !is_ipaddr($h) && !is_macaddr($h, true)) {
				$input_errors[] = sprintf(gettext("A valid IP address, CIDR block, or MAC address must be specified. [%s]"), $h);
			}
			/* Check length of partial MAC */
			if (!is_macaddr($h, false) && is_macaddr($h, true)) {
				$mac_parts = explode(':', $h);
				if (!in_array(count($mac_parts), array(1, 2, 4))) {
					$input_errors[] = gettext("Partial MAC addresses can only be matched using 1, 2, or 4 MAC segments (bytes).");
				}
			}
		}
	}

	if ($port != "") {
		if (!is_port(strip_not($port))) {
			$input_errors[] = gettext("Invalid value specified for port.");
		}
	}

	if ($snaplen == "") {
		$snaplen = 0;
	} else {
		if (!is_numeric($snaplen) || $snaplen < 0) {
			$input_errors[] = gettext("Invalid value specified for packet length.");
		}
	}

	if ($count == "") {
		$count = 0;
	} else {
		if (!is_numeric($count) || $count < 0) {
			$input_errors[] = gettext("Invalid value specified for packet count.");
		}
	}

	if (!count($input_errors)) {
		$do_tcpdump = true;

		if ($_POST['promiscuous']) {
			//if promiscuous mode is checked
			$disablepromiscuous = "";
		} else {
			//if promiscuous mode is unchecked
			$disablepromiscuous = "-p";
		}

		if ($_POST['dnsquery']) {
			//if dns lookup is checked
			$disabledns = "";
		} else {
			//if dns lookup is unchecked
			$disabledns = "-n";
		}

		if ($_POST['startbtn'] != "") {
			$action = gettext("Start");

			//delete previous packet capture if it exists
			if (file_exists($fp.$fn)) {
				unlink ($fp.$fn);
			}

		} elseif ($_POST['stopbtn'] != "") {
			$action = gettext("Stop");
			$processes_running = trim(shell_exec("/bin/ps axw -O pid= | /usr/bin/grep tcpdump | /usr/bin/grep {$fn} | /usr/bin/egrep -v '(pflog|grep)'"));

			//explode processes into an array, (delimiter is new line)
			$processes_running_array = explode("\n", $processes_running);

			//kill each of the packetcapture processes
			foreach ($processes_running_array as $process) {
				$process_id_pos = strpos($process, ' ');
				$process_id = substr($process, 0, $process_id_pos);
				exec("kill $process_id");
			}

		} elseif ($_POST['downloadbtn'] != "") {
			//download file
			$fs = filesize($fp.$fn);
			header("Content-Type: application/octet-stream");
			header("Content-Disposition: attachment; filename=$fn");
			header("Content-Length: $fs");
			readfile($fp.$fn);
			exit;
		}
	}
} else {
	$do_tcpdump = false;
}

$excl = gettext("Exclude");

$protocollist = array(
	'' => 'Any',
	'icmp' => 'ICMP',
	'!icmp' => $excl . ' ICMP',
	'icmp6' => 'ICMPv6',
	'!icmp6' => $excl . ' ICMPv6',
	'tcp' => 'TCP',
	'!tcp' => $excl . ' TCP',
	'udp' => 'UDP',
	'!udp' => $excl . ' UDP',
	'arp' => 'ARP',
	'!arp' => $excl . ' ARP',
	'carp' => 'CARP',
	'!carp' => $excl . ' CARP',
	'pfsync' => 'pfsync',
	'!pfsync' => $excl . ' pfsync',
	'esp' => 'ESP',
	'!esp' => $excl . ' ESP'
);

include("head.inc");

if ($input_errors) {
	print_input_errors($input_errors);
}

$form = new Form(false); // No button yet. We add those later depending on the required action

$section = new Form_Section('Packet Capture Options');

$section->addInput(new Form_Select(
	'interface',
	'*Interface',
	$selectedif,
	$interfaces
))->setHelp('Select the interface on which to capture traffic. ');

$section->addInput(new Form_Checkbox(
	'promiscuous',
	'Promiscuous',
	'Enable promiscuous mode',
	$promiscuous
))->setHelp('%1$sNon-promiscuous mode captures only traffic that is directly relevant to the host (sent by it, sent or broadcast to it, or routed through it) and ' .
	'does not show packets that are ignored at network adapter level.%2$s%3$sPromiscuous mode%4$s ("sniffing") captures all data seen by the adapter, whether ' .
	'or not it is valid or related to the host, but in some cases may have undesirable side effects and not all adapters support this option. Click Info for details %5$s' .
	'Promiscuous mode requires more kernel processing of packets. This puts a slightly higher demand on system resources, especially ' .
	'on very busy networks or low power processors. The change in packet processing may allow a hostile host to detect that an adapter is in promiscuous mode ' .
	'or to \'fingerprint\' the kernel (see %6$s). Some network adapters may not support or work well in promiscuous mode (see %7$s).%8$s',

	'
',
	'

',
	'',
	'',
	'
',
	' [1]' .
		' [2]',
	' [3]',
	'
'
);

$section->addInput(new Form_Select(
	'fam',
	'*Address Family',
	$fam,
	array('' => 'Any',
		  'ip' => gettext('IPv4 Only'),
		  'ip6' => gettext('IPv6 Only')
	)
))->setHelp('Select the type of traffic to be captured.');

$section->addInput(new Form_Select(
	'proto',
	'*Protocol',
	$proto,
	$protocollist
))->setHelp('Select the protocol to capture, or "Any". ');

$section->addInput(new Form_Input(
	'host',
	'Host Address',
	'text',
	$host
))->setHelp('This value is either the Source or Destination IP address, subnet in CIDR notation, or MAC address.%1$s' .
			'Matching can be negated by preceding the value with "!". Multiple IP addresses or CIDR subnets may be specified. Comma (",") separated values perform a boolean "AND". ' .
			'Separating with a pipe ("|") performs a boolean "OR".%1$s' .
			'MAC addresses must be entered in colon-separated format, such as xx:xx:xx:xx:xx:xx or a partial address consisting of one (xx), two (xx:xx), or four (xx:xx:xx:xx) segments.%1$s' .
			'If this field is left blank, all packets on the specified interface will be captured.',
			'
');

$section->addInput(new Form_Input(
	'port',
	'Port',
	'text',
	$port
))->setHelp('The port can be either the source or destination port. The packet capture will look for this port in either field. ' .
			'Leave blank if not filtering by port.');

$section->addInput(new Form_Input(
	'snaplen',
	'Packet Length',
	'text',
	$snaplen
))->setHelp('The Packet length is the number of bytes of each packet that will be captured. Default value is 0, ' .
			'which will capture the entire frame regardless of its size.');

$section->addInput(new Form_Input(
	'count',
	'Count',
	'text',
	$count
))->setHelp('This is the number of packets the packet capture will grab. Default value is 100.%s' .
			'Enter 0 (zero) for no count limit.',
			'
');

$section->addInput(new Form_Select(
	'detail',
	'Level of detail',
	$detail,
	array('normal' => gettext('Normal'),
		  'medium' => gettext('Medium'),
		  'high' => gettext('High'),
		  'full' => gettext('Full'),
	)
))->setHelp('This is the level of detail that will be displayed after hitting "Stop" when the packets have been captured.%s' .
			'This option does not affect the level of detail when downloading the packet capture. ',
			'
');

$section->addInput(new Form_Checkbox(
	'dnsquery',
	'Reverse DNS Lookup',
	'Do reverse DNS lookup',
	$_POST['dnsquery']
))->setHelp('The packet capture will perform a reverse DNS lookup associated with all IP addresses.%s' .
			'This option can cause delays for large packet captures.',
			'
');

$form->add($section);

/* check to see if packet capture tcpdump is already running */
$processcheck = (trim(shell_exec("/bin/ps axw -O pid= | /usr/bin/grep tcpdump | /usr/bin/grep {$fn} | /usr/bin/egrep -v '(pflog|grep)'")));

$processisrunning = ($processcheck != "");

if (($action == gettext("Stop") or $action == "") and $processisrunning != true) {
	$form->addGlobal(new Form_Button(
		'startbtn',
		'Start',
		null,
		'fa-play-circle'
	))->addClass('btn-success');
} else {
	$form->addGlobal(new Form_Button(
		'stopbtn',
		'Stop',
		null,
		'fa-stop-circle'
	))->addClass('btn-warning');
}

if (file_exists($fp.$fn) and $processisrunning != true) {
	$form->addGlobal(new Form_Button(
		'viewbtn',
		'View Capture',
		null,
		'fa-file-text-o'
	))->addClass('btn-primary');

	$form->addGlobal(new Form_Button(
		'downloadbtn',
		'Download Capture',
		null,
		'fa-download'
	))->addClass('btn-primary');

	$section->addInput(new Form_StaticText(
		'Last capture',
		date("F jS, Y g:i:s a.", filemtime($fp.$fn))
	));
}

print($form);

if ($do_tcpdump) :
	$matches = array();

	if (in_array($fam, $fams)) {
		$matches[] = $fam;
	}

	if (in_array($proto, $protos)) {
		$matches[] = fixup_not($proto);
	}

	if ($port != "") {
		$matches[] = "port ".fixup_not($port);
	}

	if ($host != "") {
		$hostmatch = "";
		$hostcount = 0;

		foreach ($hosts as $h) {
			$h = fixup_host($h, $hostcount++);

			if (!empty($h)) {
				$hostmatch .= " " . $h;
			}
		}

		if (!empty($hostmatch)) {
			$matches[] = "({$hostmatch})";
		}
	}

	if ($count != "0") {
		$searchcount = "-c " . $count;
	} else {
		$searchcount = "";
	}

	$selectedif = convert_friendly_interface_to_real_interface_name($selectedif);

	if ($action == gettext("Start")) {
		$matchstr = implode($matches, " and ");

		print_info_box(gettext('Packet capture is running.'), 'info');

		$cmd = "/usr/sbin/tcpdump -i {$selectedif} {$disablepromiscuous} {$searchcount} -s {$snaplen} -w {$fp}{$fn} " . escapeshellarg($matchstr);
		// Debug
		//echo $cmd;
		mwexec_bg ($cmd);
	} else {
?>

<?=gettext('Packets Captured')?>

<?php
		if ($proto == "carp") {
			$iscarp = "-T carp";
		} else {
			$iscarp = "";
		}
		$detail_args = "";
		switch ($detail) {
			case "full":
				$detail_args = "-vv -e";
				break;
			case "high":
				$detail_args = "-vv";
				break;
			case "medium":
				$detail_args = "-v";
				break;
			case "normal":
			default:
				$detail_args = "-q";
				break;
		}

		print('<textarea class="form-control" rows="20" style="font-size: 13px; font-family: consolas,monaco,roboto mono,liberation mono,courier;">');
		system("/usr/sbin/tcpdump {$disabledns} {$detail_args} {$iscarp} -r {$fp}{$fn}");
		print('</textarea>');

?>

<?php
	}
endif;

include("foot.inc");


text:
using System.Collections.Generic;
using NUnit.Framework;

namespace ReducibleExtensions.Test
{
  [TestFixture]
  class Reductions
  {
    [Test]
    public void SumListUsingReducer()
    {
      var list = new List<int> {1, 2, 3, 4, 5};
      var result = list.AsReducible().Fold((int a, int b) => a + b, 0);
      Assert.That(result, Is.EqualTo(15));
    }

    [Test]
    public void SumListUsingMonoid()
    {
      var list = new List<int> {1, 2, 3, 4, 5};
      var monoid = new Monoid<int,int>((int a, int b) => a + b, 0);
      var result = list.AsReducible().Fold(monoid);
      Assert.That(result, Is.EqualTo(15));
    }
  }
}


text:
<?php

namespace Paymill\Tests\Unit\Models\Request;

use Paymill\Models\Request as Request;
use PHPUnit_Framework_TestCase;

/**
 * Paymill\Models\Request\Payment test case.
 */
class PaymentTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var Request\Payment
     */
    private $_payment;

    /**
     * Prepares the environment before running a test.
     */
    protected function setUp()
    {
        parent::setUp();
        $this->_payment = new Request\Payment();
    }

    /**
     * Cleans up the environment after running a test.
     */
    protected function tearDown()
    {
        $this->_payment = null;
        parent::tearDown();
    }

    //Testmethods
    /**
     * Tests the getters and setters of the model
     * @test
     */
    public function setGetTest()
    {
        $sample = array(
            'client' => 'client_88a388d9dd48f86c3136',
            'token' => '098f6bcd4621d373cade4e832627b4f6'
        );

        $this->_payment->setClient($sample['client'])->setToken($sample['token']);

        $this->assertEquals($this->_payment->getClient(), $sample['client']);
        $this->assertEquals($this->_payment->getToken(), $sample['token']);

        return $this->_payment;
    }

    /**
     * Test the Parameterize function of the model
     * @test
     * @depends setGetTest
     */
    public function parameterizeTest($payment)
    {
        $testId = "payment_88a388d9dd48f86c3136";
        $payment->setId($testId);

        $creationArray = $payment->parameterize("create");
        $getOneArray = $payment->parameterize("getOne");

        $this->assertEquals($creationArray, array('client' => 'client_88a388d9dd48f86c3136', 'token' => '098f6bcd4621d373cade4e832627b4f6')
        );
        $this->assertEquals($getOneArray, array(
            'count' => 1,
            'offset' => 0
        ));
    }

}


text:
@interface SZURLRequestOperationTests : SZTestCase

@end


text:
package ee.ioc.phon.android.speak;

/**
 *
Set of non-standard extras that K6nele supports.

 *
 * @author Kaarel Kaljurand
 */
public class Extras {

	// SERVER_URL should be a legal URL
	public static final String EXTRA_SERVER_URL = "ee.ioc.phon.android.extra.SERVER_URL";

	// GRAMMAR_URL should be a legal URL
	public static final String EXTRA_GRAMMAR_URL = "ee.ioc.phon.android.extra.GRAMMAR_URL";

	// Identifier of the target language (any string)
	public static final String EXTRA_GRAMMAR_TARGET_LANG = "ee.ioc.phon.android.extra.GRAMMAR_TARGET_LANG";

	// Desired transcription.
	// Using this extra, the user can specify to which string the enclosed audio
	// should be transcribed.
	public static final String EXTRA_PHRASE = "ee.ioc.phon.android.extra.PHRASE";

    // Bundle with information about the editor in which the IME is running
    public static final String EXTRA_EDITOR_INFO = "ee.ioc.phon.android.extra.EDITOR_INFO";

    // Boolean to indicate that the recognition service should not stop after delivering the first result
    public static final String EXTRA_UNLIMITED_DURATION = "ee.ioc.phon.android.extra.UNLIMITED_DURATION";

    // Boolean to indicate that the server has sent final=true, i.e. the following hypotheses
    // will not be transcriptions of the same audio anymore.
    public static final String EXTRA_SEMI_FINAL = "ee.ioc.phon.android.extra.SEMI_FINAL";

	// Caller is interested in the recorded audio data (boolean)
	public static final String GET_AUDIO = "android.speech.extra.GET_AUDIO";

	// Caller wants to have the audio data in a certain format (String)
	public static final String GET_AUDIO_FORMAT = "android.speech.extra.GET_AUDIO_FORMAT";

	/**
	 *
Key used to retrieve an {@code ArrayList<String>} from the {@link Bundle} passed to the
	 * {@link RecognitionListener#onResults(Bundle)} and
	 * {@link RecognitionListener#onPartialResults(Bundle)} methods. This list represents structured
	 * data:

	 *

	 *
raw utterance of hypothesis 1
	 *
linearization 1.1
	 *
language code of linearization 1.1
	 *
linearization 1.2
	 *
language code of linearization 1.2
	 *
...
	 *
raw utterance of hypothesis 2
	 *
...
	 *

	 *
	 *
The number of linearizations for each hypothesis is given by an ArrayList<Integer> from a bundle
	 * item accessible via the key RESULTS_RECOGNITION_LINEARIZATION_COUNTS.
	 * Both of these bundle items have to be present for the client to be able to use the results.

	 */
	public static final String RESULTS_RECOGNITION_LINEARIZATIONS = "ee.ioc.phon.android.extra.RESULTS_RECOGNITION_LINEARIZATIONS";
	public static final String RESULTS_RECOGNITION_LINEARIZATION_COUNTS = "ee.ioc.phon.android.extra.RESULTS_RECOGNITION_LINEARIZATION_COUNTS";

}


text:
package net.caustic.http;

import java.net.MalformedURLException;
import java.net.URL;

import net.caustic.http.BadURLException;
import net.caustic.http.HttpUtils;

public class JavaNetHttpUtils implements HttpUtils {

	@Override
	public String getHost(String urlStr) throws BadURLException {
		try {
			return new URL(urlStr).getHost();
		} catch(MalformedURLException e) {
			throw new BadURLException(urlStr, e.getMessage());
		}
	}

}


text:
package org.apache.metron.rest.config;

import kafka.admin.AdminUtils$;
import kafka.utils.ZkUtils;
import org.I0Itec.zkclient.ZkClient;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.common.protocol.SecurityProtocol;
import org.apache.metron.common.utils.KafkaUtils;
import org.apache.metron.rest.MetronRestConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;

import java.util.HashMap;
import java.util.Map;

import static org.apache.metron.rest.MetronRestConstants.TEST_PROFILE;

/**
 * Configuration used for connecting to Kafka.
 */
@Configuration
@Profile("!" + TEST_PROFILE)
public class KafkaConfig {
  /**
   * The Spring environment.
   */
  private Environment environment;

  /**
   * Construvtor used to inject {@link Environment}.
   * @param environment Spring environment to inject.
   */
  @Autowired
  public KafkaConfig(final Environment environment) {
    this.environment = environment;
  }

  /**
   * The client used for ZooKeeper.
   */
  @Autowired
  private ZkClient zkClient;

  /**
   * Bean for ZooKeeper
   */
  @Bean
  public ZkUtils zkUtils() {
    return ZkUtils.apply(zkClient, false);
  }

  /**
   * Create properties that will be used by {@link this#createConsumerFactory()}
   *
   * @return Configurations used by {@link this#createConsumerFactory()}.
   */
  @Bean
  public Map<String, Object> consumerProperties() {
    final Map<String, Object> props = new HashMap<>();
    props.put("bootstrap.servers", environment.getProperty(MetronRestConstants.KAFKA_BROKER_URL_SPRING_PROPERTY));
    props.put("group.id", "metron-rest");
    props.put("enable.auto.commit", "false");
    props.put("auto.commit.interval.ms", "1000");
    props.put("session.timeout.ms", "30000");
    props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
    props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
    if (environment.getProperty(MetronRestConstants.KERBEROS_ENABLED_SPRING_PROPERTY, Boolean.class, false)) {
      props.put("security.protocol", KafkaUtils.INSTANCE.normalizeProtocol(environment.getProperty(MetronRestConstants.KAFKA_SECURITY_PROTOCOL_SPRING_PROPERTY)));
    }
    return props;
  }

  /**
   * Create a {@link ConsumerFactory} which will be used for certain Kafka interactions within config API.
   *
   * @return a {@link ConsumerFactory} used to create {@link KafkaConsumer} for interactions with Kafka.
   */
  @Bean
  public ConsumerFactory<String, String> createConsumerFactory() {
    return new DefaultKafkaConsumerFactory<>(consumerProperties());
  }

  @Bean
  public Map<String, Object> producerProperties() {
    Map<String, Object> producerConfig = new HashMap<>();
    producerConfig.put("bootstrap.servers", environment.getProperty(MetronRestConstants.KAFKA_BROKER_URL_SPRING_PROPERTY));
    producerConfig.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
    producerConfig.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
    producerConfig.put("request.required.acks", 1);
    if (environment.getProperty(MetronRestConstants.KERBEROS_ENABLED_SPRING_PROPERTY, Boolean.class, false)) {
      producerConfig.put("security.protocol", KafkaUtils.INSTANCE.normalizeProtocol(environment.getProperty(MetronRestConstants.KAFKA_SECURITY_PROTOCOL_SPRING_PROPERTY)));
    }
    return producerConfig;
  }

  @Bean
  public KafkaProducer kafkaProducer() {
    return new KafkaProducer<>(producerProperties());
  }

  /**
   * Create a bean for {@link AdminUtils$}. This is primarily done to make testing a bit easier.
   *
   * @return {@link AdminUtils$} is written in scala. We return a reference to this class.
   */
  @Bean
  public AdminUtils$ adminUtils() {
    return AdminUtils$.MODULE$;
  }
}


text:
package com.amazonaws.services.simplesystemsmanagement.model;

import com.amazonaws.AmazonServiceException;

/**
 * <p>
 * You can have at most 100 active configuration documents.
 * </p>
 */
public class DocumentLimitExceededException extends AmazonServiceException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new DocumentLimitExceededException with the specified error
     * message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public DocumentLimitExceededException(String message) {
        super(message);
    }

}


text:
/******************************************************************************
 *
 *	Filename:		I2C.c (for TI's MSP430)
 *
 *	Author:			Adam Johnson
 *
 *	Description:	This is an I2C master transmitter module which uses
 *					interrupts.
 *
 *	Notes:		(1) External pull-ups are required...for some MSP's the GPIO's
 *					internal pull-ups aren't usable when in I2C mode.  Here's
 *					the schematic for the test function:
 *
 *					                     /|\  /|\
 *					    MSP430FR5869     10k  10k       Slave
 *					       master         |    |        Device
 *					  -----------------   |    |   -----------------
 *					-|XIN  P1.6/UCB0SDA|<-|----+->|SDA              |
 *					 |                 |  |       |                 |
 *					-|XOUT             |  |       |                 |
 *					 |     P1.7/UCB0SCL|<-+------>|SCL              |
 *					 |                 |          |                 |
 *
 *				(2) The acts of (1) reading from UCBxRXBUF, (2) setting UCTXSTT
 *					bit, and (2) setting UCTXSTP bit all cause new data to be
 *					clocked into UCBxRXBUF.  So before getting the last byte in
 *					a receive transaction, we disable the RX interrupt, do both
 *					actions, and then enable it again.  Otherwise we will lose
 *					the 2nd-to-last byte of data in the transaction.  We also
 *					need to do something similar when receiving only one byte.
 *
 *	Origin:			github.com/adamj537/Code-Library
 *
 *	Terms of Use:	MIT License
 *
 *****************************************************************************/

#include <stdint.h>
#include <driverlib.h>
#include "project.h"					// global settings
#include "hal_I2C.h"					// header for this module

/******************************************************************************
 * 	Configuration options
 *****************************************************************************/
#ifndef UART_CLOCK_FREQ_HZ
#warning "UART_CLOCK_FREQ_HZ is not defined"
#define UART_CLOCK_FREQ_HZ 	CS_getSMCLK()	// master clock frequency
#endif

#ifndef UART_CLOCK_SOURCE
#warning "UART_CLOCK_SOURCE is not defined"
#define UART_CLOCK_SOURCE	UCSSEL__SMCLK	// use main clock
#endif
/*****************************************************************************/

// USCI registers - the numbers are offsets from a "base address" defined in
// the handleToBaseAddress array below.
#define I2CREG_CTLW0		0x0000		// Control Word
#define I2CREG_CTL1			0x0000		// Control 1
#define I2CREG_CTL0			0x0001		// Control 0
#define I2CREG_BRW			0x0006		// Baud Rate Control Word
#define I2CREG_BR0			0x0006		// Baud Rate Control 0
#define I2CREG_BR1			0x0007		// Baud Rate Control 1
#define I2CREG_STAT			0x0008		// Status Register
#define I2CREG_RXBUF		0x000C		// Receive Buffer
#define I2CREG_TXBUF		0x000E		// Transmit Buffer
#define I2CREG_OA			0x0014		// I2C Own Address
#define I2CREG_SA			0x0020		// I2C Slave Address
#define I2CREG_ICTL			0x002A		// Interrupt Enable Register
#define I2CREG_IE			0x002A		// USCI Bx Interrupt Enable Register
#define I2CREG_IFG			0x002C		// USCI Bx Interrupt Flags Register
#define I2CREG_IV			0x002E		// Interrupt Vector Register

// Macros to help with register access.
#define REG16(x)			(*((volatile uint16_t *)((uint16_t)x)))
#define REG8(x)				(*((volatile uint8_t *)((uint16_t)x)))

// This array holds the address of the lowest register in each I2C peripheral.
// If we know that address and the "offset" of each register (defined above),
// then we can access any register of any I2C peripheral.
static const uint16_t baseAddr[] = {
#ifdef __MSP430_HAS_USCI_B0__			// USCI B0
	__MSP430_BASEADDRESS_USCI_B0__,
#endif

#ifdef __MSP430_HAS_USCI_B1__			// USCI B1
	__MSP430_BASEADDRESS_USCI_B1__,
#endif

#ifdef __MSP430_HAS_USCI_B2__			// USCI B2
	__MSP430_BASEADDRESS_USCI_B2__,
#endif

#ifdef __MSP430_HAS_USCI_B3__			// USCI B3
	__MSP430_BASEADDRESS_USCI_B3__,
#endif

#ifdef __MSP430_HAS_EUSCI_B0__			// eUSCI B0
	__MSP430_BASEADDRESS_EUSCI_B0__,
#endif

#ifdef __MSP430_HAS_EUSCI_A0__			// eUSCI A0
	__MSP430_BASEADDRESS_EUSCI_A0__,
#endif

#ifdef __MSP430_HAS_EUSCI_A1__			// eUSCI A1
	__MSP430_BASEADDRESS_EUSCI_A1__,
#endif
};

// Figure out how many channels we have available.
#define I2C_NUM_CHANNELS	(sizeof(baseAddr)/sizeof(baseAddr[0])

volatile uint8_t *txDataPtr[I2C_NUM_CHANNELS];	// pointer to TX data
volatile uint32_t txByteCtr[I2C_NUM_CHANNELS];	// number of bytes to TX

volatile uint8_t *rxDataPtr[I2C_NUM_CHANNELS];	// pointer to RX data
volatile uint32_t rxByteCtr[I2C_NUM_CHANNELS];	// number of bytes to RX

/******************************************************************************
 *
 *	Function:		I2CInit
 *
 *	Description:	Initializes the specified I2C with the provided settings.
 *
 *	Parameters:		uint8_t channel - which I2C peripheral to act upon
 *					i2cConfig_t *configPtr - settings to apply to the channel
 *
 *	Return Value:	I2C_RESULT_OK for success; other values indicate failure
 *
 *****************************************************************************/

i2cResult_t I2CInit(uint8_t channel, i2cConfig_t *configPtr)
{
	i2cResult_t result = I2C_RESULT_OK;	// an optimistic return value ;)
	uint16_t base = baseAddr[channel];	// Convert channel to base address.
	uint16_t preScalarValue;

	// Reset global variables in case we were stuck somewhere.
	txByteCtr[channel] = 0;
	rxByteCtr[channel] = 0;

	// Check for invalid channel.
	if (channel >= I2C_NUM_CHANNELS)
	{
		result = I2C_RESULT_INVALID_SELECTION;
	}

	// Configure in slave mode if requested.
	else if ((configPtr->mode == I2C_MODE_SLAVE) ||
			(configPtr->mode == I2C_MODE_SLAVE_AND_GEN_CALL))
	{
		// Disable the USCI module and clear the other bits of control register.
		REG16(base + I2CREG_CTLW0) = UCSWRST;

		// Clear USCI master mode.
		REG16(base + I2CREG_CTLW0) &= ~UCMST;

		// Configure I2C as Slave and Synchronous mode.
		REG16(base + I2CREG_CTLW0) = UCMODE_3 | UCSYNC;

		// Set up the slave address.
//		REG16(base + I2CREG_OA) = configPtr->address;

		// Enable general call if requested.
		if (configPtr->mode == I2C_MODE_SLAVE_AND_GEN_CALL)
		{
			REG16(base + I2CREG_OA) |= UCGCEN;
		}
		else
		{
			REG16(base + I2CREG_OA) &= ~UCGCEN;
		}
	}

	// Configure in master (or multi-master) mode if requested.
	else
	{
		// Disable the USCI module and clear the other bits of control register.
		REG16(base + I2CREG_CTLW0) = UCSWRST;

		// Configure as I2C master mode.
		// UCMST = Master mode; UCMODE_3 = I2C mode; UCSYNC = Synchronous mode
		REG16(base + I2CREG_CTLW0) |= UCMST | UCMODE_3 | I2C_CLOCK_SOURCE;

		// If multi-master mode is selected, enable it.
		if (configPtr->mode == I2C_MODE_MULTI_MASTER)
		{
			REG16(base + I2CREG_CTLW0) |= UCMM;
		}
		else
		{
			REG16(base + I2CREG_CTLW0) &= ~UCMM;
		}

		// Compute the clock divider to give close to the desired speed.
		preScalarValue = (uint16_t)(I2C_CLOCK_FREQ_HZ / configPtr->speed);
		REG16(base + I2CREG_BRW) = preScalarValue;

		// Set the address we'll attempt to talk to.
//		REG8(base + I2CREG_SA) = configPtr->address;
	}

	return result;
}

/******************************************************************************
 *
 *	Function:		I2CEnable
 *
 *	Description:	Turns on the specified I2C channel.  This is separate from
 *					the init function so that the channel can be enabled and
 *					disabled without reconfiguring it.
 *
 *	Parameters:		uint8_t channel - which I2C peripheral to act upon
 *
 *	Return Value:	I2C_RESULT_OK for success; other values indicate failure
 *
 *****************************************************************************/

i2cResult_t I2CEnable(uint8_t channel)
{
	i2cResult_t result = I2C_RESULT_OK;	// an optimistic return value :)
	uint16_t base = baseAddr[channel];	// Convert channel to base address.

	// Check for invalid channel.
	if (channel >= I2C_NUM_CHANNELS)
	{
		result = I2C_RESULT_INVALID_SELECTION;
	}
	else
	{
		// Clear the UCSWRST bit to enable the I2C Module.
		REG16(base + I2CREG_CTLW0) &= ~(UCSWRST);

		// Enable transmit, receive, and not-acknowledge interrupts.
		REG8(base + I2CREG_IE) |= UCTXIE | UCRXIE | UCNACKIE;
	}

	return result;
}

/******************************************************************************
 *
 *	Function:		I2CDisable
 *
 *	Description:	Turns off the specified I2C channel.  The configuration
 *					specified in the init function will be preserved, so you
 *					don't need to redo the init function after calling this.
 *
 *	Parameters:		uint8_t channel - which I2C peripheral to act upon
 *
 *	Return Value:	I2C_RESULT_OK for success; other values indicate failure
 *
 *****************************************************************************/

i2cResult_t I2CDisable(uint8_t channel)
{
	i2cResult_t result = I2C_RESULT_OK;	// an optimistic return value :)
	uint16_t base = baseAddr[channel];	// Convert channel to base address.

	// Check for invalid channel.
	if (channel >= I2C_NUM_CHANNELS)
	{
		result = I2C_RESULT_INVALID_SELECTION;
	}

	else
	{
		// Set the UCSWRST bit to disable the I2C Module.
		REG16(base + I2CREG_CTLW0) |= UCSWRST;

		// Disable transmit, receive, and not-acknowledge interrupts.
		REG8(base + I2CREG_IE) &= ~(UCTXIE | UCRXIE | UCNACKIE);
	}

	return result;
}

/******************************************************************************
 *
 *	Function:		I2CIsBusy
 *
 *	Description:	This function indicates whether or not the I2C bus is busy.
 *					It checks the status of the UCBBUSY bit in UCBxSTAT
 *					register.  If you call I2CRead or I2CWrite while the bus is
 *					busy, then both I2C transactions will be clobbered.
 *
 *	Parameters:		uint8_t channel - which I2C peripheral to act upon
 *
 *	Return Value:	TRUE if the I2C Master is busy; FALSE otherwise.
 *
 *****************************************************************************/

uint8_t I2CIsBusy (uint8_t channel)
{
	uint16_t base = baseAddr[channel];	// Convert channel to base address.

    // Check the bus busy bit of the STAT register.
	if ((REG8(base + I2CREG_STAT) & UCBBUSY)	||
		(REG8(base + I2CREG_STAT) & UCSCLLOW)	||
		(REG8(base + I2CREG_CTL1) & UCTXSTP)	||
		(REG8(base + I2CREG_CTL1) & UCTXSTT)	||
		(REG8(base + I2CREG_IFG) & UCTXIFG)		||
		(REG8(base + I2CREG_IFG) & UCRXIFG))
	{
		return 1;
	}
	return 0;
}

/******************************************************************************
 *
 *	Function:		I2CWrite
 *
 *	Description:	Writes to an I2C slave device.
 *
 *	Parameters:		uint8_t channel - which I2C peripheral to act upon
 *					uint8_t address - I2C device address to use
 *					uint8_t *data - array of bytes to write to slave device
 *					uint32_t count - size of data array
 *
 *	Return Value:	I2C_RESULT_OK for success; other values indicate failure
 *
 *****************************************************************************/

i2cResult_t I2CWrite(uint8_t channel, uint8_t address, uint8_t *data, uint32_t count)
{
	i2cResult_t result = I2C_RESULT_OK;	// an optimistic return value :)
	uint16_t base = baseAddr[channel];	// Convert channel to base address.

	// Check for invalid channel.
	if (channel >= I2C_NUM_CHANNELS)
	{
		result = I2C_RESULT_INVALID_SELECTION;
	}

	else
	{
		// Set TX array start address.
		txDataPtr[channel] = data;

		// Load TX byte counter.
		txByteCtr[channel] = count;

		// Indicate that we're not reading.
		rxByteCtr[channel] = 0;

		// Set the address we'll attempt to talk to.
		REG8(base + I2CREG_SA) = address;

		// Send START + address + WRITE.
		REG16(base + I2CREG_CTLW0) |= UCTXSTT | UCTR;

		// The rest of the message will be sent via ISR.
	}

	return result;
}

/******************************************************************************
 *
 *	Function:		I2CRead
 *
 *	Description:	Reads from an I2C slave device.
 *
 *	Parameters:		uint8_t channel - which I2C peripheral to act upon
 *					uint8_t address - I2C device address to use
 *					uint8_t *data - array to put data read from the device
 *					uint32_t count - size of data array
 *
 *	Return Value:	I2C_RESULT_OK for success; other values indicate failure
 *
 *****************************************************************************/

i2cResult_t I2CRead(uint8_t channel, uint8_t address, uint8_t *data, uint32_t count)
{
	i2cResult_t result = I2C_RESULT_OK;	// an optimistic return value :)
	uint16_t base = baseAddr[channel];	// Convert channel to base address.

	// Check for invalid channel.
	if (channel >= I2C_NUM_CHANNELS)
	{
		result = I2C_RESULT_INVALID_SELECTION;
	}

	else
	{
		// Set the address we'll attempt to talk to.
		REG8(base + I2CREG_SA) = address;

		// Indicate that we're not writing.
		txByteCtr[channel] = 0;

		// Set RX array start address.
		rxDataPtr[channel] = data;

		// The case when we send only one byte is strange because of the way
		// the MSP430's I2C hardware state machine works...you have to send
		// START and STOP before you allow the interrupt to fire to get the
		// received byte.  This is similar to the case of the last byte of a
		// receive transaction (see Note 3 above).
		if (count == 1)
		{
			rxByteCtr[channel] = 0;

			// Disable receive interrupt.
			REG8(base + I2CREG_IE) &= ~UCRXIE;

			// Send START + address + READ.
			REG8(base + I2CREG_CTL1) &= ~UCTR;
			REG8(base + I2CREG_CTL1) |= UCTXSTT;

			// Wait for START to be sent.
			while (REG8(base + I2CREG_CTL1) & UCTXSTT);

			// Send STOP.
			REG8(base + I2CREG_CTL1) |= UCTXSTP;

			// Enable receive interrupt.
			REG8(base + I2CREG_IE) |= UCRXIE;
		}
		else if (count > 1)
		{
			// Set RX byte counter.  We subtract 1 because the I2C peripheral
			// reads the first byte after the START condition is sent, which is
			// before the ISR is called.  So by the time we get into the ISR
			// (which uses rxByteCtr), we've already got the first byte.  We
			// subtract another 1 because the ISR needs the rxByteCtr to be
			// 0-indexed.
			rxByteCtr[channel] = count - 2;

			// Send START + address + READ.
			REG8(base + I2CREG_CTL1) &= ~UCTR;
			REG8(base + I2CREG_CTL1) |= UCTXSTT;
		}
		else
		{
			return I2C_RESULT_INVALID_SELECTION;
		}

		// The rest of the message will be sent via ISR.
	}

	return result;
}

/******************************************************************************
 *
 *	Function:		I2CWriteThenRead
 *
 *	Description:	Writes to, and then reads from, an I2C devie.  This is a
 *					common practice, for example we may wish to read data from
 *					an I2C EEPROM, so we will write the location we wish to
 *					start reading from, and then read the data.
 *
 *	Parameters:		uint8_t channel - which I2C peripheral to act upon
 *					uint8_t address - I2C device address to use
 *					uint8_t *writeData - array of bytes to write to slave device
 *					uint32_t writeCount - size of data array
 *					uint8_t *readData - array to put data read from the device
 *					uint32_t readCount - size of data array
 *
 *	Return Value:	I2C_RESULT_OK for success; other values indicate failure
 *
 *****************************************************************************/

i2cResult_t I2CWriteThenRead(uint8_t channel, uint8_t address, uint8_t *writeData,
	uint32_t writeCount, uint8_t *readData, uint32_t readCount)
{
	i2cResult_t result = I2C_RESULT_OK;	// an optimistic return value :)
	uint16_t base = baseAddr[channel];	// Convert channel to base address.

	// Check for invalid channel.
	if (channel >= I2C_NUM_CHANNELS)
	{
		result = I2C_RESULT_INVALID_SELECTION;
	}

	else
	{
		// Set the address we'll attempt to talk to.
		REG8(base + I2CREG_SA) = address;

		// Set TX array start address.
		txDataPtr[channel] = writeData;

		// Load TX byte counter.
		txByteCtr[channel] = writeCount;

		// Set RX array start address.
		rxDataPtr[channel] = readData;

		// Set RX byte counter.  Unlike in I2CRead, we don't subtract anything,
		// because we won't read any bytes until the ISR, and we need this to
		// be 1-indexed (for now).  It's tricky...you might want to step
		// through this operation with a debugger.
		rxByteCtr[channel] = readCount;

		// Send START + address + WRITE.
		REG8(base + I2CREG_CTL1) |= UCTXSTT | UCTR;

		// The rest of the message will be sent via ISR.
	}

	return result;
}

/******************************************************************************
 *
 *	Function:		I2CReadThenWrite
 *
 *	Description:	Writes to, and then reads from, an I2C device.  This is not
 *					common, but the author thought "why not?".
 *
 *	Parameters:		uint8_t channel - which I2C peripheral to act upon
 *					uint8_t address - I2C device address to use
 *					uint8_t *readData - array to put data read from the device
 *					uint32_t readCount - size of data array
 *					uint8_t *writeData - array of bytes to write to slave device
 *					uint32_t writeCount - size of data array
 *
 *	Return Value:	I2C_RESULT_OK for success; other values indicate failure
 *
 *****************************************************************************/

i2cResult_t I2CReadThenWrite(uint8_t channel, uint8_t address, uint8_t *readData,
		uint32_t readCount, uint8_t *writeData, uint32_t writeCount)
{
	i2cResult_t result = I2C_RESULT_OK;	// an optimistic return value :)
	uint16_t base = baseAddr[channel];	// Convert channel to base address.

	// Check for invalid channel.
	if (channel >= I2C_NUM_CHANNELS)
	{
		result = I2C_RESULT_INVALID_SELECTION;
	}

	else
	{
		// Set the address we'll attempt to talk to.
		REG8(base + I2CREG_SA) = address;

		// Set TX array start address.
		txDataPtr[channel] = writeData;

		// Load TX byte counter.
		txByteCtr[channel] = writeCount;

		// Set RX array start address.
		rxDataPtr[channel] = readData;

		// Set RX byte counter.  We subtract 1 because the I2C peripheral reads
		// the first byte after the START condition is sent, which is before
		// the ISR is called.  So by the time we get into the ISR (which uses
		// rxByteCtr), we've already got the first byte.
		rxByteCtr[channel] = readCount - 1;

		// Send START + address + READ.
		REG8(base + I2CREG_CTL1) &= ~UCTR;
		REG8(base + I2CREG_CTL1) |= UCTXSTT;

		// The rest of the message will be sent via ISR.
	}
	return result;
}

/******************************************************************************
 *	Test Functions
 *****************************************************************************/

#ifdef INCLUDE_TESTS

#define I2C_ADDR	0x50

// First message:  Write to EEPROM.
const uint8_t writeMsg[] = {
	0x00,	// register to access
	0x00,	// value for register
	0x01,	// value for register
	0x02,	// value for register
	0x03,
	0x04,
	0x05,
};

// Second message:  Read from EEPROM.  This is for the "write-then-read" test.
const uint8_t readMsg[] = {
	0x00,	// EEPROM register to read from
};

uint8_t I2CTest(uint8_t channel)
{
	i2cResult_t result = I2C_RESULT_OK;	// an optimistic return value :)
	i2cConfig_t config;					// module config data
	volatile uint8_t response[16];		// bytes received from EEPROM

	do	// I'm afraid of goto statements, so I'll use this instead ;}
	{
		// Setup the I2C configuration.
		config.mode = I2C_MODE_MASTER;
		config.speed = 10000;
//		config.address = I2C_ADDR;

		// Initialize the I2C peripheral with the configuration.
		result = I2CInit(channel, &config);
		if (result != I2C_RESULT_OK)
			break;

		// Enable the I2C peripheral.
		result = I2CEnable(channel);
		if (result != I2C_RESULT_OK)
			break;

		// Try a read.
//		result = I2CRead(channel, I2C_ADDR, (uint8_t *)response, sizeof(response));
//		if (result != I2C_RESULT_OK)
//			break;

		// Wait until the device is not busy from the previous operation.
//		while (I2CIsBusy(channel));

		// Try a write.
//		result = I2CWrite(channel, I2C_ADDR, (uint8_t *)writeMsg, sizeof(writeMsg));
//		if (result != I2C_RESULT_OK)
//			break;

		// Wait until the device is not busy from the previous operation.
//		while (I2CIsBusy(channel));

		// Wait > 5 ms for the EEPROM to finish the write cycle (see
		// datasheet).  MCLK = 1048576 Hz (by default), so:
		// MCLK (1/s) * 0.005 s = 5242.88.  Round up to 5250, and wait that
		// many cycles.
//		__delay_cycles(5250);

		// Try a write-then-read.
//		result = I2CWriteThenRead(channel, I2C_ADDR, (uint8_t *)readMsg,
//			sizeof(readMsg), (uint8_t *)response, sizeof(response));
//		if (result != I2C_RESULT_OK)
//			break;

		// Wait until the device is not busy from the previous operation.
//		while (I2CIsBusy(channel));
	} while (false);

	return 0;
}

#endif	/* INCLUDE_TEST */

/******************************************************************************
 *
 *	Function:		I2C_ISR
 *
 *	Description:	This function is called by the interrupt handlers for this
 *					module.  It is structured such that it can be used to
 *					transmit any number of bytes by pre-loading a byte counter
 *					with the byte count, and doing some pointer math.  There
 *					are tricky things about how this hardware works, so	read
 *					Note 3 (above) to learn more.  Also, this function is
 *					declared as "inline" to speed up code execution in the ISR.
 *
 *	Parameters:		uint8_t ch - which I2C peripheral to act upon
 *					volatile uint16_t reg - interrupt vector address
 *
 *****************************************************************************/

static inline void I2C_ISR(uint8_t ch, volatile uint16_t reg)
{
	uint16_t base = baseAddr[ch];						// Convert channel to base address.

	switch(__even_in_range(reg, USCI_I2C_UCBIT9IFG))	// Find the interrupt's cause.
	{
	case USCI_NONE: break;								// Vector  0: No interrupts
	case USCI_I2C_UCALIFG: break;						// Vector  2: ALIFG
	case USCI_I2C_UCNACKIFG:							// Vector  4: NACKIFG
		REG8(base + I2CREG_CTL1) |= UCTXSTP;			// Send STOP.
		REG8(base + I2CREG_CTL1) &= ~UCNACKIFG;			// Clear no-ACK flag.
		break;
	case USCI_I2C_UCSTTIFG: break;						// Vector  6: STTIFG
	case USCI_I2C_UCSTPIFG: break;						// Vector  8: STPIFG
	case USCI_I2C_UCRXIFG3: break;						// Vector 10: RXIFG3
	case USCI_I2C_UCTXIFG3: break;						// Vector 12: TXIFG3
	case USCI_I2C_UCRXIFG2: break;						// Vector 14: RXIFG2
	case USCI_I2C_UCTXIFG2: break;						// Vector 16: TXIFG2
	case USCI_I2C_UCRXIFG1: break;						// Vector 18: RXIFG1
	case USCI_I2C_UCTXIFG1: break;						// Vector 20: TXIFG1
	case USCI_I2C_UCRXIFG0:								// Vector 22: RXIFG0
		if (rxByteCtr[ch])								// Check RX byte counter.
		{
			*rxDataPtr[ch] = REG8(base + I2CREG_RXBUF);	// Save received byte; fetch next byte.
			rxDataPtr[ch]++;							// Increment RX buffer pointer.
			rxByteCtr[ch]--;							// Decrement RX byte counter.
		}
		else if (txByteCtr[ch])							// Is this a read-then-write?
		{
			REG8(base + I2CREG_CTL1) |= UCTR;			// Set WRITE mode.
			REG8(base + I2CREG_CTL1) |= UCTXSTT;		// Send re-START.
		}
		else											// One byte left.
		{
			REG8(base + I2CREG_IE) &= ~UCRXIE;			// Disable RX interrupt (see Note 3).
			REG8(base + I2CREG_CTL1) |= UCTXSTP;		// Send STOP before last byte is read.
			*rxDataPtr[ch] = REG8(base + I2CREG_RXBUF);	// Save received byte; clear int flag.
			rxDataPtr[ch]++;							// Increment RX buffer pointer.
			REG8(base + I2CREG_IE) |= UCRXIE;			// Enable RX interrupt (see Note 3).
		}
		break;
	case USCI_I2C_UCTXIFG0:								// Vector 24: TXIFG0
		if (txByteCtr[ch])								// Check TX byte counter.
		{
			REG8(base + I2CREG_TXBUF) = *txDataPtr[ch];	// Load TX buffer.
			txDataPtr[ch]++;							// Increment TX buffer pointer.
			txByteCtr[ch]--;							// Decrement TX byte counter
		}
		else if (rxByteCtr[ch] == 1)					// Is this a (1-byte) write-then-read?
		{
			REG8(base + I2CREG_IE) &= ~UCRXIE;			// Disable RX interrupt (see Note 3).
			REG8(base + I2CREG_CTL1) &= ~UCTR;			// Set READ mode.
			REG8(base + I2CREG_CTL1) |= UCTXSTT;		// Send re-START (but don't fetch).
			while (REG8(base + I2CREG_CTL1) & UCTXSTT);	// Wait for START to be sent.
			REG8(base + I2CREG_CTL1) |= UCTXSTP;		// Send STOP.
			REG8(base + I2CREG_IE) |= UCRXIE;			// Enable RX interrupt (see Note 3).
			rxByteCtr[ch]--;							// Decrement RX byte counter.
		}
		else if (rxByteCtr[ch])							// Is this a write-then-read?
		{
			REG8(base + I2CREG_CTL1) &= ~UCTR;			// Set READ mode.
			REG8(base + I2CREG_CTL1) |= UCTXSTT;		// Send re-START (fetches 1st byte).
			rxByteCtr[ch] -= 2;							// Decrement RX byte counter by 2.
		}
		else											// We're done!
		{
			REG8(base + I2CREG_CTL1) |= UCTXSTP;		// Send STOP.
//			REG8(base + I2CREG_IFG) &= ~UCTXIFG;		// Clear int flag.
		}
		break;
	default: break;
	}
}

/******************************************************************************
 *
 * 	Function:		USCI_B0_ISR, USCI_B1_ISR, USCI_B2_ISR, USCI_B3_ISR
 *
 * 	Description:	These are interrupt service routines that are triggered by
 * 					USCI events.  It looks messy because of define statements
 * 					which format the code differently for different compilers.
 * 					It is also automatically not included if the processor
 * 					we're using does not have this module.
 *
 *****************************************************************************/

#if defined(__MSP430_HAS_USCI_B0__)

#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
#pragma vector = USCI_B0_VECTOR
__interrupt void USCI_B0_ISR(void)
#elif defined(__GNUC__)
void __attribute__ ((interrupt(USCI_B0_VECTOR))) USCI_B0_ISR (void)
#else
#error Compiler not supported!
#endif
{
	I2C_ISR(I2C_0, UCB0IV);
}

#endif /* USCI B0 */

#if defined(__MSP430_HAS_USCI_B1__)

#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
#pragma vector = USCI_B1_VECTOR
__interrupt void USCI_B1_ISR(void)
#elif defined(__GNUC__)
void __attribute__ ((interrupt(USCI_B1_VECTOR))) USCI_B1_ISR (void)
#else
#error Compiler not supported!
#endif
{
	I2C_ISR(I2C_1, UCB1IV);
}

#endif /* USCI B1 */

#if defined(__MSP430_HAS_USCI_B2__)

#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
#pragma vector = USCI_B2_VECTOR
__interrupt void USCI_B2_ISR(void)
#elif defined(__GNUC__)
void __attribute__ ((interrupt(USCI_B2_VECTOR))) USCI_B2_ISR (void)
#else
#error Compiler not supported!
#endif
{
	I2C_ISR(I2C_2, UCB2IV);
}

#endif /* USCI B2 */

#if defined(__MSP430_HAS_USCI_B3__)

#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
#pragma vector = USCI_B3_VECTOR
__interrupt void USCI_B3_ISR(void)
#elif defined(__GNUC__)
void __attribute__ ((interrupt(USCI_B3_VECTOR))) USCI_B3_ISR (void)
#else
#error Compiler not supported!
#endif
{
	I2C_ISR(I2C_3, UCB3IV);
}

#endif /* USCI B3 */

#if defined(__MSP430_HAS_EUSCI_B0__)

#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
#pragma vector = USCI_B0_VECTOR
__interrupt void USCI_B0_ISR(void)
#elif defined(__GNUC__)
void __attribute__ ((interrupt(USCI_B0_VECTOR))) USCI_B0_ISR (void)
#else
#error Compiler not supported!
#endif
{
	I2C_ISR(I2C_e0, UCB0IV);
}

#endif /* eUSCI B0 */

#if defined(__MSP430_HAS_EUSCI_A0__)

#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
#pragma vector = USCI_A0_VECTOR
__interrupt void USCI_A0_ISR(void)
#elif defined(__GNUC__)
void __attribute__ ((interrupt(USCI_A0_VECTOR))) USCI_A0_ISR (void)
#else
#error Compiler not supported!
#endif
{
	I2C_ISR(I2C_e1, UCA0IV);
}

#endif /* eUSCI A0 */

#if defined(__MSP430_HAS_EUSCI_A1__)

#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
#pragma vector = USCI_A1_VECTOR
__interrupt void USCI_A1_ISR(void)
#elif defined(__GNUC__)
void __attribute__ ((interrupt(USCI_A1_VECTOR))) USCI_A1_ISR (void)
#else
#error Compiler not supported!
#endif
{
	I2C_ISR(I2C_e2, UCA1IV);
}

#endif /* eUSCI A1 */


text:
``` diff
 namespace Microsoft.AspNetCore.Authentication.Cookies {
     public class PostConfigureCookieAuthenticationOptions : IPostConfigureOptions<CookieAuthenticationOptions> {
-        public void PostConfigure(string name, CookieAuthenticationOptions options);
+        public void PostConfigure(string? name, CookieAuthenticationOptions options);
     }
 }
```


text:
package cn.nec.nlc.jamesli.tools.at76contextmenu;

import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView tv = (TextView) findViewById(R.id.textView);
        registerForContextMenu(tv);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    // Create Context Menu
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context_menu, menu);
    }

    // Process clicks on Context Menu Items
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.help_guide:
                Toast.makeText(getApplicationContext(), "ContextMenu Shown",
                        Toast.LENGTH_SHORT).show();
                return true;
            default:
                return false;
        }
    }
}


text:
import os
import sys
sys.path.insert(0, os.pardir)
from testing_harness import TestHarness, PyAPITestHarness
import openmc

class ScoreNuScatterTestHarness(PyAPITestHarness):
    def _build_inputs(self):
        filt = openmc.Filter(type='cell', bins=(10, 21, 22, 23))
        t = openmc.Tally(tally_id=1)
        t.add_filter(filt)
        t.add_score('nu-scatter')
        self._input_set.tallies = openmc.TalliesFile()
        self._input_set.tallies.add_tally(t)

        self._input_set.build_default_materials_and_geometry()
        self._input_set.build_default_settings()

        self._input_set.settings.inactive = 0

        self._input_set.export()

    def _cleanup(self):
        super(ScoreNuScatterTestHarness, self)._cleanup()
        f = os.path.join(os.getcwd(), 'tallies.xml')
        if os.path.exists(f): os.remove(f)

if __name__ == '__main__':
    harness = ScoreNuScatterTestHarness('statepoint.10.*', True)
    harness.main()


text:
<meta http-equiv=Content-Type content="text/html; charset=windows-1252">
<meta name=Generator content="Microsoft Word 15 (filtered)">
<title>October 5</title>

October 5

Subject to Change

While we look not at the things which are seen, but at the
things which are not seen: for the things which are seen are temporal; but the
things which are not seen are eternal. 2 Corinthians 4:18

Don't center your attention on
what you can see in this natural, physical sense realm. Everything you see is
temporal and subject to change. So, put your faith in the unseen eternal realm.
The things which are eternal are not subject to change.

God's Word is eternal and it
contains 7,000 promises to cover any circumstance you'll ever face. And, no
matter what happens in this shifting, changing world you live in, those
promises will forever be the same.

No matter how bad your body
feels, the Word will always say, "By His stripes you were healed" (1
Pet. 2:24). No matter how bad your bank book looks, the Word will always say,
"My God shall supply all your need according to his riches in glory by
Christ Jesus" (Phil. 4:19).

Don't settle for the meager existence
the world says you can have. Lay hold of what the Word says you can have.
Center your attention on the eternal truths of God and look not to the things
which are seen. After all, they're subject to change!

Scripture Reading: 2 Corinthians 4:8-18


text:
Stats and Skills

<skills-display can-select="false" character="vm.character"></skills-display>


text:
set -ex

cd "$(dirname "$0")/../../.."

export GRPC_PYTHON_BUILD_WITH_CYTHON=1
export PYTHON=${PYTHON:-python}
export PIP=${PIP:-pip}
export AUDITWHEEL=${AUDITWHEEL:-auditwheel}

# Allow build_ext to build C/C++ files in parallel
# by enabling a monkeypatch. It speeds up the build a lot.
# Use externally provided GRPC_PYTHON_BUILD_EXT_COMPILER_JOBS value if set.
export GRPC_PYTHON_BUILD_EXT_COMPILER_JOBS=${GRPC_PYTHON_BUILD_EXT_COMPILER_JOBS:-2}

mkdir -p "${ARTIFACTS_OUT}"
ARTIFACT_DIR="$PWD/${ARTIFACTS_OUT}"

# Build the source distribution first because MANIFEST.in cannot override
# exclusion of built shared objects among package resources (for some
# inexplicable reason).
${SETARCH_CMD} "${PYTHON}" setup.py sdist

# Wheel has a bug where directories don't get excluded.
# https://bitbucket.org/pypa/wheel/issues/99/cannot-exclude-directory
${SETARCH_CMD} "${PYTHON}" setup.py bdist_wheel

GRPCIO_STRIP_TEMPDIR=$(mktemp -d)
GRPCIO_TAR_GZ_LIST=( dist/grpcio-*.tar.gz )
GRPCIO_TAR_GZ=${GRPCIO_TAR_GZ_LIST[0]}
GRPCIO_STRIPPED_TAR_GZ=$(mktemp -t "XXXXXXXXXX.tar.gz")

clean_non_source_files() {
( cd "$1"
  find . -type f \
    | grep -v '\.c$' | grep -v '\.cc$' | grep -v '\.cpp$' \
    | grep -v '\.h$' | grep -v '\.hh$' | grep -v '\.inc$' \
    | grep -v '\.s$' | grep -v '\.py$' \
    | while read -r file; do
      rm -f "$file" || true
    done
  find . -type d -empty -delete
)
}

tar xzf "${GRPCIO_TAR_GZ}" -C "${GRPCIO_STRIP_TEMPDIR}"
( cd "${GRPCIO_STRIP_TEMPDIR}"
  find . -type d -name .git -exec rm -fr {} \; || true
  for dir in */third_party/*; do
    clean_non_source_files "${dir}" || true
  done
  tar czf "${GRPCIO_STRIPPED_TAR_GZ}" -- *
)
mv "${GRPCIO_STRIPPED_TAR_GZ}" "${GRPCIO_TAR_GZ}"

# Build gRPC tools package distribution
"${PYTHON}" tools/distrib/python/make_grpcio_tools.py

# Build gRPC tools package source distribution
${SETARCH_CMD} "${PYTHON}" tools/distrib/python/grpcio_tools/setup.py sdist

# Build gRPC tools package binary distribution
${SETARCH_CMD} "${PYTHON}" tools/distrib/python/grpcio_tools/setup.py bdist_wheel

if [ "$GRPC_BUILD_MANYLINUX_WHEEL" != "" ]
then
  for wheel in dist/*.whl; do
    "${AUDITWHEEL}" show "$wheel" | tee /dev/stderr | grep \"manylinux1
    "${AUDITWHEEL}" repair "$wheel" -w "$ARTIFACT_DIR"
    rm "$wheel"
  done
  for wheel in tools/distrib/python/grpcio_tools/dist/*.whl; do
    "${AUDITWHEEL}" show "$wheel" | tee /dev/stderr | grep \"manylinux1
    "${AUDITWHEEL}" repair "$wheel" -w "$ARTIFACT_DIR"
    rm "$wheel"
  done
fi

# We need to use the built grpcio-tools/grpcio to compile the health proto
# Wheels are not supported by setup_requires/dependency_links, so we
# manually install the dependency.  Note we should only do this if we
# are in a docker image or in a virtualenv.
if [ "$GRPC_BUILD_GRPCIO_TOOLS_DEPENDENTS" != "" ]
then
  "${PIP}" install -rrequirements.txt

  if [ "$("$PYTHON" -c "import sys; print(sys.version_info[0])")" == "2" ]
  then
    "${PIP}" install futures>=2.2.0
  fi

  "${PIP}" install grpcio --no-index --find-links "file://$ARTIFACT_DIR/"
  "${PIP}" install grpcio-tools --no-index --find-links "file://$ARTIFACT_DIR/"

  # Build grpcio_testing source distribution
  ${SETARCH_CMD} "${PYTHON}" src/python/grpcio_testing/setup.py preprocess \
      sdist
  cp -r src/python/grpcio_testing/dist/* "$ARTIFACT_DIR"

  # Build grpcio_channelz source distribution
  ${SETARCH_CMD} "${PYTHON}" src/python/grpcio_channelz/setup.py \
      preprocess build_package_protos sdist
  cp -r src/python/grpcio_channelz/dist/* "$ARTIFACT_DIR"

  # Build grpcio_health_checking source distribution
  ${SETARCH_CMD} "${PYTHON}" src/python/grpcio_health_checking/setup.py \
      preprocess build_package_protos sdist
  cp -r src/python/grpcio_health_checking/dist/* "$ARTIFACT_DIR"

  # Build grpcio_reflection source distribution
  ${SETARCH_CMD} "${PYTHON}" src/python/grpcio_reflection/setup.py \
      preprocess build_package_protos sdist
  cp -r src/python/grpcio_reflection/dist/* "$ARTIFACT_DIR"

  # Build grpcio_status source distribution
  ${SETARCH_CMD} "${PYTHON}" src/python/grpcio_status/setup.py \
      preprocess sdist
  cp -r src/python/grpcio_status/dist/* "$ARTIFACT_DIR"
fi

# Ensure the generated artifacts are valid.
"${PYTHON}" -m virtualenv venv || { "${PYTHON}" -m pip install virtualenv && "${PYTHON}" -m virtualenv venv; }
venv/bin/python -m pip install twine
venv/bin/python -m twine check dist/* tools/distrib/python/grpcio_tools/dist/*
rm -rf venv/

cp -r dist/* "$ARTIFACT_DIR"
cp -r tools/distrib/python/grpcio_tools/dist/* "$ARTIFACT_DIR"


text:
namespace Switch {
  namespace TUnit {
    namespace Framework {
      /// @cond
      struct TestFixture;
      class UnitTest;
      /// @endcond

      /// @par Library
      /// Switch.TUnit.Framework
      struct tunit_framework_export_ RegisteredMethod : public object {
        RegisteredMethod(const string& name, delegate<void> method, const System::Runtime::CompilerServices::Caller& caller) : RegisteredMethod(name, method, false, caller) {}
        RegisteredMethod(const string& name, delegate<void> method, bool ignore, const System::Runtime::CompilerServices::Caller& caller) : name(name), method(method), ignore(ignore), caller(caller) {}

      private:
        friend struct Switch::TUnit::Framework::TestFixture;
        friend class Switch::TUnit::Framework::UnitTest;

        string name;
        delegate<void> method;
        bool ignore = false;
        System::Runtime::CompilerServices::Caller caller;
      };
    }
  }
}

using namespace Switch;


text:
<cc-slider
	class="cc-height-settings-panel-row"
	[disabled]="isLabelsSliderDisabled$ | async"
	[title]="
		(isLabelsSliderDisabled$ | async)
			? 'Disabled because color labels are used'
			: 'Display the labels of the ' + (amountOfTopLabels$ | async) + ' highest buildings'
	"
	label="Labels"
	[min]="0"
	[max]="50"
	[value]="amountOfTopLabels$ | async"
	[onChange]="applyDebouncedTopLabels"
></cc-slider>

	<mat-checkbox [checked]="showMetricLabelNodeName$ | async" (change)="setShowMetricLabelNodeName($event)"
		>Show label node names
	</mat-checkbox>

	<mat-checkbox [checked]="showMetricLabelNodeValue$ | async" (change)="setShowMetricLabelNameValue($event)"
		>Show label node metrics
	</mat-checkbox>

<cc-slider
	class="cc-height-settings-panel-row"
	title="Height"
	label="Height"
	[step]="0.1"
	[min]="0.1"
	[max]="5"
	[value]="(scaling$ | async).y"
	[onChange]="applyDebouncedScalingY"
></cc-slider>

	<mat-checkbox (change)="setInvertHeight($event)" *ngIf="!(isDeltaState$ | async)" [checked]="invertHeight$ | async">
		Invert Height
	</mat-checkbox>
	<cc-reset-settings-button
		[settingsKeys]="['appSettings.amountOfTopLabels', 'appSettings.scaling.y', 'appSettings.invertHeight']"
		tooltip="Reset height metric settings to their defaults"
	></cc-reset-settings-button>


text:
package new_simvasos.timebound;

import java.util.Random;
public class UniformDistributionTimeBound extends TimeBound {

  int start;
  int end;
  int tick;
  public UniformDistributionTimeBound(int start, int end) {
    this.start = start;
    this.end = end;
    this.tick = 0;    // None?? what???
  }

  public int getTick() {
    Random random = new Random();

    // Generate random number in Uniform Distribution
    return random.nextInt(end - start + 1) + start;
  }
}


text:
Testing Automation
==================

Automate javascript testing using tools such as TeamCity, Phantom, Jasmine 2.0 and RequireJS

###Overview

The build server will execute a task to run the specRunner.html  in a headless browser that runs the javascript tests and reports out the results such that the build server understands.

Check out the [wiki](https://github.com/EmberConsultingGroup/Testing-Automation/wiki) for details.


text:
package aima.core.learning.framework;

/**
 * @author Ravi Mohan
 *
 */
public class NumericAttribute implements Attribute {
	double value;

	private NumericAttributeSpecification spec;

	public NumericAttribute(double rawValue, NumericAttributeSpecification spec) {
		this.value = rawValue;
		this.spec = spec;
	}

	public String valueAsString() {
		return Double.toString(value);
	}

	public String name() {
		return spec.getAttributeName().trim();
	}

	public double valueAsDouble() {
		return value;
	}
}


text:
package sk.henrichg.phoneprofilesplus;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;

public class ActivateProfileFromExternalApplicationActivity extends AppCompatActivity {

    private DataWrapper dataWrapper;

    private String profileName;
    private long profile_id = 0;

    static final String EXTRA_PROFILE_NAME = "profile_name";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        overridePendingTransition(0, 0);

        Intent intent = getIntent();
        profileName = intent.getStringExtra(ActivateProfileFromExternalApplicationActivity.EXTRA_PROFILE_NAME);

        dataWrapper = new DataWrapper(getApplicationContext(), false, 0, false, 0, 0, 0f);

        if (profileName != null) {
            profileName = profileName.trim();

            if (!profileName.isEmpty()) {
                profile_id = dataWrapper.getProfileIdByName(profileName, true);
                /*dataWrapper.fillProfileList(false, false);
                for (Profile profile : dataWrapper.profileList) {
                    if (profile._name.trim().equals(profileName)) {
                        profile_id = profile._id;
                        break;
                    }
                }*/
            }
        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(LocaleHelper.onAttach(base));
    }

    @Override
    protected void onStart()
    {
        super.onStart();

        boolean serviceStarted = GlobalUtils.isServiceRunning(getApplicationContext(), PhoneProfilesService.class, false);
        if (!serviceStarted) {
            AutostartPermissionNotification.showNotification(getApplicationContext(), true);

            PPApplication.setApplicationStarted(getApplicationContext(), true);
            Intent serviceIntent = new Intent(getApplicationContext(), PhoneProfilesService.class);
            //serviceIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, true);
            //serviceIntent.putExtra(PhoneProfilesService.EXTRA_DEACTIVATE_PROFILE, false);
            serviceIntent.putExtra(PhoneProfilesService.EXTRA_ACTIVATE_PROFILES, false);
            serviceIntent.putExtra(PPApplication.EXTRA_APPLICATION_START, true);
            serviceIntent.putExtra(PPApplication.EXTRA_DEVICE_BOOT, false);
            serviceIntent.putExtra(PhoneProfilesService.EXTRA_START_ON_PACKAGE_REPLACE, false);
            if (profile_id != 0) {
                serviceIntent.putExtra(PhoneProfilesService.EXTRA_START_FOR_EXTERNAL_APPLICATION, true);
                serviceIntent.putExtra(PhoneProfilesService.EXTRA_START_FOR_EXTERNAL_APP_ACTION,
                        ActionForExternalApplicationActivity.ACTION_ACTIVATE_PROFILE);
                serviceIntent.putExtra(PhoneProfilesService.EXTRA_START_FOR_EXTERNAL_APP_DATA_TYPE,
                        PhoneProfilesService.START_FOR_EXTERNAL_APP_PROFILE);
                serviceIntent.putExtra(PhoneProfilesService.EXTRA_START_FOR_EXTERNAL_APP_DATA_VALUE, profileName);
            }
//            PPApplication.logE("[START_PP_SERVICE] ActivateProfileFromExternalApplicationActivity.onStart", "xxx");
            PPApplication.startPPService(this, serviceIntent);
            finish();
            return;
        }

        PPApplication.addActivityLog(getApplicationContext(), PPApplication.ALTYPE_ACTION_FROM_EXTERNAL_APP_PROFILE_ACTIVATION,
                null, profileName, "");

        if (profile_id != 0) {
            Profile profile = dataWrapper.getProfileById(profile_id, false, false, false);
            if (profile != null) {

                //if (Permissions.grantProfilePermissions(getApplicationContext(), profile, false, true,
                //        /*false, false, 0,*/ PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, true, false)) {
                if (!DataWrapperStatic.displayPreferencesErrorNotification(profile, null, true, getApplicationContext())) {
                    dataWrapper.activateProfileFromMainThread(profile, false, PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this, false);
                } else
                    dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
            }
            else
                dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
        }
        else {
            showNotification(getString(R.string.action_for_external_application_notification_title),
                    getString(R.string.action_for_external_application_notification_no_profile_text));

            dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
        }
    }

    /*
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == Permissions.REQUEST_CODE + Permissions.GRANT_TYPE_PROFILE) {
            if (data != null) {
                long profileId = data.getLongExtra(PPApplication.EXTRA_PROFILE_ID, 0);
                int startupSource = data.getIntExtra(PPApplication.EXTRA_STARTUP_SOURCE, 0);
                boolean mergedProfile = data.getBooleanExtra(Permissions.EXTRA_MERGED_PROFILE, false);
                boolean activateProfile = data.getBooleanExtra(Permissions.EXTRA_ACTIVATE_PROFILE, false);

                if (activateProfile) {
                    Profile profile = dataWrapper.getProfileById(profileId, false, false, mergedProfile);
                    dataWrapper.activateProfileFromMainThread(profile, mergedProfile, startupSource, this);
                }
            }
        }
    }
    */

    private void showNotification(String title, String text) {
        PPApplication.createExclamationNotificationChannel(getApplicationContext());
        NotificationCompat.Builder mBuilder =   new NotificationCompat.Builder(getApplicationContext(), PPApplication.EXCLAMATION_NOTIFICATION_CHANNEL)
                .setColor(ContextCompat.getColor(this, R.color.notificationDecorationColor))
                .setSmallIcon(R.drawable.ic_exclamation_notify) // notification icon
                .setContentTitle(title) // title for notification
                .setContentText(text) // message for notification
                .setAutoCancel(true); // clear notification after click
        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(text));
        /*Intent intent = new Intent(context, ImportantInfoActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pi = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pi);*/
        mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
        //if (android.os.Build.VERSION.SDK_INT >= 21)
        //{
            mBuilder.setCategory(NotificationCompat.CATEGORY_RECOMMENDATION);
            mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
        //}

        mBuilder.setGroup(PPApplication.ACTION_FOR_EXTERNAL_APPLICATION_NOTIFICATION_GROUP);

        NotificationManagerCompat mNotificationManager = NotificationManagerCompat.from(getApplicationContext());
        try {
            mNotificationManager.notify(
                    PPApplication.ACTION_FOR_EXTERNAL_APPLICATION_NOTIFICATION_TAG,
                    PPApplication.ACTION_FOR_EXTERNAL_APPLICATION_NOTIFICATION_ID, mBuilder.build());
        } catch (Exception e) {
            //Log.e("ActivateProfileFromExternalApplicationActivity.showNotification", Log.getStackTraceString(e));
            PPApplication.recordException(e);
        }
    }

    @Override
    public void finish()
    {
        super.finish();
        overridePendingTransition(0, 0);
    }

}


text:
    $for(posts)$

            [$date$]
            $title$

    $endfor$


text:
namespace network {

ActorFrequencyTimer::ActorFrequencyTimer( double frequency, int32_t actorId )
    : FrequencyTimer()
    , mActorId( actorId )
{
    SetFrequency( frequency );
}

int32_t ActorFrequencyTimer::GetActorId() const
{
    return mActorId;
}

void ActorFrequencyTimerHolder::Add( ActorFrequencyTimer const& actorFrequencyTimer )
{
    mActorFrequencyTimers.push_back( actorFrequencyTimer );
}

void ActorFrequencyTimerHolder::Update( double DeltaTime )
{
    for( auto&& freqTimer : mActorFrequencyTimers )
    {
        freqTimer.Update( DeltaTime );
    }
}

ActorFrequencyTimerHolder::ActorIds_t ActorFrequencyTimerHolder::GetActorIds() const
{
    ActorIds_t actorIds;
    for( auto&& freqTimer : mActorFrequencyTimers )
    {
        if (freqTimer.IsTime() )
        {
            actorIds.insert( freqTimer.GetActorId() );
        }
    }
    return actorIds;
}

} // namespace network


text:
require 'ebay_trading/types/context_search_asset'

module EbayTrading # :nodoc:
  module Responses # :nodoc:
    # == Attributes
    #  array_node :context_search_assets, 'ContextSearchAsset', :class => ContextSearchAsset, :default_value => []
    class GetContextualKeywords < Abstract
      include XML::Mapping
      include Initializer
      root_element_name 'GetContextualKeywordsResponse'
      array_node :context_search_assets, 'ContextSearchAsset', :class => ContextSearchAsset, :default_value => []
    end
  end
end


text:
  Saint-Léger-sur-Roanne est
      une ville située dans le département de Loire en Rhône-Alpes. Elle totalisait 1 038 habitants en 2008.

La ville offre quelques  équipements sportifs, elle propose entre autres un terrain de tennis, un terrain de sport et une boucle de randonnée.

À coté de Saint-Léger-sur-Roanne sont positionnées géographiquement les villes de
Renaison située à 5 km, 2 834 habitants,
Riorges localisée à 2 km, 10 255 habitants,
Lentigny à 4 km, 1 395 habitants,
Villerest à 5 km, 4 392 habitants,
Ouches à 2 km, 1 149 habitants,
Saint-Alban-les-Eaux localisée à 5 km, 933 habitants,
 entre autres. De plus, Saint-Léger-sur-Roanne est située à seulement cinq km de Roanne.

À Saint-Léger-sur-Roanne, le prix moyen à la vente d'un appartement s'évalue à 993 € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 1 233 € du m². À la location la valeur moyenne se situe à 6,84 € du m² par mois.

Le parc d'habitations, à Saint-Léger-sur-Roanne, était réparti en 2011 en 16 appartements et 474 maisons soit
 un marché relativement équilibré.


text:
/*
 * $Id$
 *
 */

#ifndef MAP_H
#define MAP_H

#include <iostream>

#include "base/hashmap.hh"
#include "mem/gems_common/Vector.hh"

template <class KEY_TYPE, class VALUE_TYPE>
class Map
{
  private:
    typedef typename m5::hash_map<KEY_TYPE, VALUE_TYPE> MapType;
    typedef typename MapType::iterator iterator;
    typedef typename MapType::const_iterator const_iterator;

public:
  Map() { /* empty */ }
  ~Map() { /* empty */ }

  void add(const KEY_TYPE& key, const VALUE_TYPE& value);
  bool exist(const KEY_TYPE& key) const;
  int size() const { return m_map.size(); }
  void erase(const KEY_TYPE& key) { assert(exist(key)); m_map.erase(key); }
  Vector<KEY_TYPE> keys() const;
  Vector<VALUE_TYPE> values() const;
  void deleteKeys();
  void deleteValues();
  VALUE_TYPE& lookup(const KEY_TYPE& key) const;
  void clear() { m_map.clear(); }
    void print(std::ostream& out) const;

  // Synonyms
  void remove(const KEY_TYPE& key) { erase(key); }
  void deallocate(const KEY_TYPE& key) { erase(key); }
  void allocate(const KEY_TYPE& key) { add(key, VALUE_TYPE()); }
  void insert(const KEY_TYPE& key, const VALUE_TYPE& value) { add(key, value); }

  // Use default copy constructor and assignment operator
private:
  // Data members

  // m_map is declared mutable because some methods from the STL "map"
  // class that should be const are not.  Thus we define this as
  // mutable so we can still have conceptually const accessors.
  mutable m5::hash_map<KEY_TYPE, VALUE_TYPE> m_map;
};

template <class KEY_TYPE, class VALUE_TYPE>
std::ostream&
operator<<(std::ostream& out, const Map<KEY_TYPE, VALUE_TYPE>& map);

// *********************

template <class KEY_TYPE, class VALUE_TYPE>
void Map<KEY_TYPE, VALUE_TYPE>::add(const KEY_TYPE& key, const VALUE_TYPE& value)
{
  // Update or add a new key/value pair
  m_map[key] = value;
}

template <class KEY_TYPE, class VALUE_TYPE>
bool Map<KEY_TYPE, VALUE_TYPE>::exist(const KEY_TYPE& key) const
{
  return (m_map.count(key) != 0);
}

template <class KEY_TYPE, class VALUE_TYPE>
VALUE_TYPE& Map<KEY_TYPE, VALUE_TYPE>::lookup(const KEY_TYPE& key) const
{
  if (!exist(key))
    std::cerr << *this << " is looking for " << key << std::endl;
  assert(exist(key));
  return m_map[key];
}

template <class KEY_TYPE, class VALUE_TYPE>
Vector<KEY_TYPE> Map<KEY_TYPE, VALUE_TYPE>::keys() const
{
  Vector<KEY_TYPE> keys;
  const_iterator iter;
  for (iter = m_map.begin(); iter != m_map.end(); iter++) {
    keys.insertAtBottom((*iter).first);
  }
  return keys;
}

template <class KEY_TYPE, class VALUE_TYPE>
Vector<VALUE_TYPE> Map<KEY_TYPE, VALUE_TYPE>::values() const
{
  Vector<VALUE_TYPE> values;
  const_iterator iter;
  std::pair<KEY_TYPE, VALUE_TYPE> p;

  for (iter = m_map.begin(); iter != m_map.end(); iter++) {
    p = *iter;
    values.insertAtBottom(p.second);
  }
  return values;
}

template <class KEY_TYPE, class VALUE_TYPE>
void Map<KEY_TYPE, VALUE_TYPE>::deleteKeys()
{
  const_iterator iter;
  std::pair<KEY_TYPE, VALUE_TYPE> p;

  for (iter = m_map.begin(); iter != m_map.end(); iter++) {
    p = *iter;
    delete p.first;
  }
}

template <class KEY_TYPE, class VALUE_TYPE>
void Map<KEY_TYPE, VALUE_TYPE>::deleteValues()
{
  const_iterator iter;
  std::pair<KEY_TYPE, VALUE_TYPE> p;

  for (iter = m_map.begin(); iter != m_map.end(); iter++) {
    p = *iter;
    delete p.second;
  }
}

template <class KEY_TYPE, class VALUE_TYPE>
void Map<KEY_TYPE, VALUE_TYPE>::print(std::ostream& out) const
{
  const_iterator iter;
  std::pair<KEY_TYPE, VALUE_TYPE> p;

  out << "[";
  for (iter = m_map.begin(); iter != m_map.end(); iter++) {
    // unparse each basic block
    p = *iter;
    out << " " << p.first << "=" << p.second;
  }
  out << " ]";
}

template <class KEY_TYPE, class VALUE_TYPE>
std::ostream&
operator<<(std::ostream& out, const Map<KEY_TYPE, VALUE_TYPE>& map)
{
  map.print(out);
  return out;
}

#endif //MAP_H


text:
package org.apache.shardingsphere.parser.spring.boot.rule;

import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.parser.yaml.config.YamlSQLParserRuleConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * YAML SQL parser rule spring boot configuration.
 */
@ConfigurationProperties(prefix = "spring.shardingsphere.rules")
@Getter
@Setter
public final class YamlSQLParserRuleSpringBootConfiguration {

    private YamlSQLParserRuleConfiguration sqlParser;
}


text:
order: 8
zh-CN:
	title: 不可编辑状态
	days: 天
	discount: 折扣
en-US:
	title: Disabled
	days: days
	discount: discount
---

```jsx
import { Input } from 'zent';

ReactDOM.render(
  <div>
			<Input value="Blah" disabled />
			<Input value="Blah" disabled showClear />
			<Input value="Blah" readOnly showClear />
			<Input icon="search" disabled />
			<Input value="42" disabled addonBefore="$" />
			<Input value="42" readOnly addonAfter="{i18n.days}" />
			<Input value="42" disabled addonBefore="$" addonAfter="{i18n.discount}" />
      <Input type="textarea" placeholder="Blah" readOnly />
  </div>
  , mountNode
);
```


text:
<!DOCTYPE html>
<html>
<head>
  <script src="/resources/testharness.js"></script>
  <script src="/resources/testharnessreport.js"></script>
  <script src="/security/contentSecurityPolicy/resources/cascade-helper.js"></script>
  <meta http-equiv="content-security-policy" content="img-src 'none'">
</head>
<body>
<script>
  // The filesystem test takes some nesting to setup:
  setup({explicit_done: true});

  async_test(t => {
    assert_blocked_image_in_document(t, document, "http://example.test:8000/resources/square.png?img-in-top-level");
  }, "Image loaded in top-level blocked.");

  async_test(t => {
    var frame = document.createElement("iframe");
    frame.onload = _ => {
      assert_blocked_image_in_document(t, frame.contentDocument, "http://example.test:8000/resources/square.png?img-in-blank-frame");
    };
    document.body.appendChild(frame);
  }, "Image loaded via about:blank frame blocked.");

  async_test(t => {
    var frame = document.createElement("iframe");
    frame.setAttribute("srcdoc", "");
    frame.onload = _ => {
      assert_blocked_image_in_document(t, frame.contentDocument, "http://example.test:8000/resources/square.png?img-in-srcdoc-frame");
    };
    document.body.appendChild(frame);
  }, "Image loaded via srcdoc frame blocked.");

  async_test(t => {
    var b = new Blob([], {type: "text/html"});

    var frame = document.createElement("iframe");
    frame.src = URL.createObjectURL(b);
    frame.onload = _ => {
      assert_blocked_image_in_document(t, frame.contentDocument, "http://example.test:8000/resources/square.png?img-in-blob-frame");
    };
    document.body.appendChild(frame);
  }, "Image loaded via 'blob:' frame blocked.");

  async_test(t => {
    window.webkitRequestFileSystem(window.TEMPORARY, 1024*1024, fs => {
      fs.root.getFile('worker.js', { create: true }, entry => {
        entry.createWriter(w => {
          w.onwriteend = _ => {
            var u = entry.toURL();

            var frame = document.createElement("iframe");
            frame.src = URL.createObjectURL(b);
            frame.onload = _ => {
              assert_blocked_image_in_document(t, frame.contentDocument, "http://example.test:8000/resources/square.png?img-in-filsystem-frame");
            };
            document.body.appendChild(frame);

            // explicit_done: yay.
            done();
          };
          w.onerror = t.unreached_func();

          var b = new Blob([], {type: "text/html"});
          w.write(b);
        });
      });
    });
  }, "Image loaded via 'filesystem:' frame blocked.");
</script>
</body>
</html>


text:
package org.apache.derby.impl.sql.catalog;

import org.apache.derby.catalog.UUID;
import org.apache.derby.iapi.types.SQLChar;
import org.apache.derby.iapi.types.SQLVarchar;
import org.apache.derby.iapi.types.DataValueDescriptor;
import org.apache.derby.iapi.sql.dictionary.SystemColumn;
import org.apache.derby.iapi.types.DataValueFactory;
import org.apache.derby.iapi.sql.dictionary.CatalogRowFactory;
import org.apache.derby.iapi.sql.dictionary.DataDescriptorGenerator;
import org.apache.derby.iapi.sql.dictionary.DataDictionary;
import org.apache.derby.iapi.sql.dictionary.RoleGrantDescriptor;
import org.apache.derby.iapi.sql.dictionary.TupleDescriptor;
import org.apache.derby.iapi.sql.execute.ExecutionFactory;
import org.apache.derby.iapi.sql.execute.ExecRow;
import org.apache.derby.iapi.error.StandardException;
import org.apache.derby.iapi.services.uuid.UUIDFactory;
import org.apache.derby.shared.common.sanity.SanityManager;

/**
 * Factory for creating a SYSROLES row.
 */

public class SYSROLESRowFactory extends CatalogRowFactory
{
    private static final String TABLENAME_STRING = "SYSROLES";

    private static final int SYSROLES_COLUMN_COUNT = 6;
    /* Column #s for sysinfo (1 based) */
    private static final int SYSROLES_ROLE_UUID = 1;
    private static final int SYSROLES_ROLEID = 2;
    private static final int SYSROLES_GRANTEE = 3;
    private static final int SYSROLES_GRANTOR = 4;
    private static final int SYSROLES_WITHADMINOPTION = 5;
    static final int SYSROLES_ISDEF = 6;

    private static final int[][] indexColumnPositions =
    {
        {SYSROLES_ROLEID, SYSROLES_GRANTEE, SYSROLES_GRANTOR},
        {SYSROLES_ROLEID, SYSROLES_ISDEF},
        {SYSROLES_ROLE_UUID}
    };

    static final int SYSROLES_ROLEID_COLPOS_IN_INDEX_ID_EE_OR = 1;
    static final int SYSROLES_GRANTEE_COLPOS_IN_INDEX_ID_EE_OR = 2;

    // (role)ID_(grant)EE_(grant)OR
    static final int SYSROLES_INDEX_ID_EE_OR_IDX = 0;
    // (role)ID_(is)DEF
    static final int SYSROLES_INDEX_ID_DEF_IDX = 1;
    // UUID
    static final int SYSROLES_INDEX_UUID_IDX = 2;

    private static  final   boolean[]   uniqueness = {
        true,
        false, // many rows have same roleid and is not a definition
        true};

    private static final String[] uuids = {
        "e03f4017-0115-382c-08df-ffffe275b270", // catalog UUID
        "c851401a-0115-382c-08df-ffffe275b270", // heap UUID
        "c065801d-0115-382c-08df-ffffe275b270", // SYSROLES_INDEX_ID_EE_OR
        "787c0020-0115-382c-08df-ffffe275b270", // SYSROLES_INDEX_ID_DEF
        "629f8094-0116-d8f9-5f97-ffffe275b270"  // SYSROLES_INDEX_UUID
    };

    /**
     * Constructor
     *
     * @param uuidf UUIDFactory
     * @param ef    ExecutionFactory
     * @param dvf   DataValueFactory
     */
    SYSROLESRowFactory(UUIDFactory uuidf,
                       ExecutionFactory ef,
                       DataValueFactory dvf)
    {
        super(uuidf,ef,dvf);
        initInfo(SYSROLES_COLUMN_COUNT, TABLENAME_STRING,
                 indexColumnPositions, uniqueness, uuids );
    }

    /**
     * Make a SYSROLES row
     *
     * @param td a role grant descriptor
     * @param parent unused
     *
     * @return  Row suitable for inserting into SYSROLES.
     *
     * @exception   StandardException thrown on failure
     */

    public ExecRow makeRow(TupleDescriptor td, TupleDescriptor parent)
        throws StandardException
    {
        ExecRow                 row;
        String                  oid_string = null;
        String                  roleid = null;
        String                  grantee = null;
        String                  grantor = null;
        boolean                 wao = false;
        boolean                 isdef = false;

        if (td != null)
        {
            RoleGrantDescriptor rgd = (RoleGrantDescriptor)td;

            roleid = rgd.getRoleName();
            grantee = rgd.getGrantee();
            grantor = rgd.getGrantor();
            wao = rgd.isWithAdminOption();
            isdef = rgd.isDef();
            UUID oid = rgd.getUUID();
            oid_string = oid.toString();
        }

        /* Build the row to insert */
        row = getExecutionFactory().getValueRow(SYSROLES_COLUMN_COUNT);

        /* 1st column is UUID */
        row.setColumn(1, new SQLChar(oid_string));

        /* 2nd column is ROLEID */
        row.setColumn(2, new SQLVarchar(roleid));

        /* 3rd column is GRANTEE */
        row.setColumn(3, new SQLVarchar(grantee));

        /* 4th column is GRANTOR */
        row.setColumn(4, new SQLVarchar(grantor));

        /* 5th column is WITHADMINOPTION */
        row.setColumn(5, new SQLChar(wao ? "Y" : "N"));

        /* 6th column is ISDEF */
        row.setColumn(6, new SQLChar(isdef ? "Y" : "N"));

        return row;
    }

    ///////////////////////////////////////////////////////////////////////////
    //
    //  ABSTRACT METHODS TO BE IMPLEMENTED BY CHILDREN OF CatalogRowFactory
    //
    ///////////////////////////////////////////////////////////////////////////

    /**
     * Make an  Tuple Descriptor out of a SYSROLES row
     *
     * @param row                   a SYSROLES row
     * @param parentTupleDescriptor unused
     * @param dd                    dataDictionary
     *
     * @return  a  descriptor equivalent to a SYSROLES row
     *
     * @exception   StandardException thrown on failure
     */
    public TupleDescriptor buildDescriptor
        (ExecRow                 row,
         TupleDescriptor         parentTupleDescriptor,
         DataDictionary          dd )
        throws StandardException {

        DataValueDescriptor         col;
        RoleGrantDescriptor              descriptor;
        String                      oid_string;
        String                      roleid;
        String                      grantee;
        String                      grantor;
        String                      wao;
        String                      isdef;
        DataDescriptorGenerator     ddg = dd.getDataDescriptorGenerator();

        if (SanityManager.DEBUG)
        {
            SanityManager.ASSERT(row.nColumns() == SYSROLES_COLUMN_COUNT,
                                 "Wrong number of columns for a SYSROLES row");
        }

        // first column is uuid of this role grant descriptor (char(36))
        col = row.getColumn(1);
        oid_string = col.getString();

        // second column is roleid (varchar(128))
        col = row.getColumn(2);
        roleid = col.getString();

        // third column is grantee (varchar(128))
        col = row.getColumn(3);
        grantee = col.getString();

        // fourth column is grantor (varchar(128))
        col = row.getColumn(4);
        grantor = col.getString();

        // fifth column is withadminoption (char(1))
        col = row.getColumn(5);
        wao = col.getString();

        // sixth column is isdef (char(1))
        col = row.getColumn(6);
        isdef = col.getString();

        descriptor = ddg.newRoleGrantDescriptor
            (getUUIDFactory().recreateUUID(oid_string),
             roleid,
             grantee,
             grantor,
             wao.equals("Y") ? true: false,
             isdef.equals("Y") ? true: false);

        return descriptor;
    }

    /**
     * Builds a list of columns suitable for creating this Catalog.
     *
     *
     * @return array of SystemColumn suitable for making this catalog.
     */
    public SystemColumn[]   buildColumnList()
        throws StandardException
    {
        return new SystemColumn[] {
            SystemColumnImpl.getUUIDColumn("UUID", false),
            SystemColumnImpl.getIdentifierColumn("ROLEID", false),
            SystemColumnImpl.getIdentifierColumn("GRANTEE", false),
            SystemColumnImpl.getIdentifierColumn("GRANTOR", false),
            SystemColumnImpl.getIndicatorColumn("WITHADMINOPTION"),
            SystemColumnImpl.getIndicatorColumn("ISDEF"),
        };
    }
}


text:
{% extends "reports/base_report.html" %}
{% import '_macros/activity_log.html' as activity_log %}

{% block title %}
{{ company_name }} activity in OpenStack
{% endblock %}

{% block scripts %}

{% endblock %}

{% block content %}

{{ company_name }} activity report

{{ show_contribution_summary(contribution) }}

{{ activity_log.show_activity_log(company=company_name, gravatar_size=64) }}

{% endblock %}