text:
from __future__ import with_statement

import ConfigParser
import copy
import errno
import glob
import logging
import os
import pprint
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import thread
import threading
import time
import traceback
import types
import unittest.case
from collections import OrderedDict
from subprocess import CalledProcessError
from unittest import TestCase

import ccmlib.repository
from cassandra import ConsistencyLevel
from cassandra.auth import PlainTextAuthProvider
from cassandra.cluster import Cluster as PyCluster
from cassandra.cluster import NoHostAvailable
from cassandra.policies import RetryPolicy, WhiteListRoundRobinPolicy
from ccmlib.cluster import Cluster
from ccmlib.cluster_factory import ClusterFactory
from ccmlib.common import get_version_from_build, is_win
from ccmlib.node import TimeoutError
from nose.exc import SkipTest
from six import print_

from plugins.dtestconfig import _CONFIG as CONFIG
# We don't want test files to know about the plugins module, so we import
# constants here and re-export them.
from plugins.dtestconfig import GlobalConfigObject
from utils.funcutils import merge_dicts

LOG_SAVED_DIR = "logs"
try:
    os.mkdir(LOG_SAVED_DIR)
except OSError:
    pass

LAST_LOG = os.path.join(LOG_SAVED_DIR, "last")

LAST_TEST_DIR = 'last_test_dir'

DEFAULT_DIR = './'
config = ConfigParser.RawConfigParser()
if len(config.read(os.path.expanduser('~/.cassandra-dtest'))) > 0:
    if config.has_option('main', 'default_dir'):
        DEFAULT_DIR = os.path.expanduser(config.get('main', 'default_dir'))
CASSANDRA_DIR = os.environ.get('CASSANDRA_DIR', DEFAULT_DIR)

NO_SKIP = os.environ.get('SKIP', '').lower() in ('no', 'false')
DEBUG = os.environ.get('DEBUG', '').lower() in ('yes', 'true')
TRACE = os.environ.get('TRACE', '').lower() in ('yes', 'true')
KEEP_LOGS = os.environ.get('KEEP_LOGS', '').lower() in ('yes', 'true')
KEEP_TEST_DIR = os.environ.get('KEEP_TEST_DIR', '').lower() in ('yes', 'true')
PRINT_DEBUG = os.environ.get('PRINT_DEBUG', '').lower() in ('yes', 'true')
OFFHEAP_MEMTABLES = os.environ.get('OFFHEAP_MEMTABLES', '').lower() in ('yes', 'true')
NUM_TOKENS = os.environ.get('NUM_TOKENS', '256')
RECORD_COVERAGE = os.environ.get('RECORD_COVERAGE', '').lower() in ('yes', 'true')
REUSE_CLUSTER = os.environ.get('REUSE_CLUSTER', '').lower() in ('yes', 'true')
SILENCE_DRIVER_ON_SHUTDOWN = os.environ.get('SILENCE_DRIVER_ON_SHUTDOWN', 'true').lower() in ('yes', 'true')
IGNORE_REQUIRE = os.environ.get('IGNORE_REQUIRE', '').lower() in ('yes', 'true')
DATADIR_COUNT = os.environ.get('DATADIR_COUNT', '3')
ENABLE_ACTIVE_LOG_WATCHING = os.environ.get('ENABLE_ACTIVE_LOG_WATCHING', '').lower() in ('yes', 'true')
RUN_STATIC_UPGRADE_MATRIX = os.environ.get('RUN_STATIC_UPGRADE_MATRIX', '').lower() in ('yes', 'true')

# devault values for configuration from configuration plugin
_default_config = GlobalConfigObject(
    vnodes=True,
)

if CONFIG is None:
    CONFIG = _default_config

DISABLE_VNODES = not CONFIG.vnodes

if os.environ.get('DISABLE_VNODES', '').lower() in ('yes', 'true'):
    print 'DISABLE_VNODES environment variable deprecated. Use `./run_dtests.py --vnodes false` instead.'

CURRENT_TEST = ""

logging.basicConfig(filename=os.path.join(LOG_SAVED_DIR, "dtest.log"),
                    filemode='w',
                    format='%(asctime)s,%(msecs)d %(name)s %(current_test)s %(levelname)s %(message)s',
                    datefmt='%H:%M:%S',
                    level=logging.DEBUG)

LOG = logging.getLogger('dtest')
# set python-driver log level to INFO by default for dtest
logging.getLogger('cassandra').setLevel(logging.INFO)

def get_sha(repo_dir):
    try:
        output = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo_dir).strip()
        prefix = 'git:'
        if os.environ.get('LOCAL_GIT_REPO') is not None:
            prefix = 'local:'
        return "{}{}".format(prefix, output)
    except CalledProcessError, e:
        if re.search('Not a git repository', e.message) is not None:
            # we tried to get a sha, but repo_dir isn't a git repo. No big deal, must just be working from a non-git install.
            return None
        else:
            # git call failed for some unknown reason
            raise

# There are times when we want to know the C* version we're testing against
# before we call Tester.setUp. In the general case, we can't know that -- the
# test method could use any version it wants for self.cluster. However, we can
# get the version from build.xml in the C* repository specified by
# CASSANDRA_VERSION or CASSANDRA_DIR. This should use the same resolution
# strategy as the actual checkout code in Tester.setUp; if it does not, that is
# a bug.
_cassandra_version_slug = os.environ.get('CASSANDRA_VERSION')
# Prefer CASSANDRA_VERSION if it's set in the environment. If not, use CASSANDRA_DIR
if _cassandra_version_slug:
    # fetch but don't build the specified C* version
    ccm_repo_cache_dir, _ = ccmlib.repository.setup(_cassandra_version_slug)
    CASSANDRA_VERSION_FROM_BUILD = get_version_from_build(ccm_repo_cache_dir)
    CASSANDRA_GITREF = get_sha(ccm_repo_cache_dir)  # will be set None when not a git repo
else:
    CASSANDRA_VERSION_FROM_BUILD = get_version_from_build(CASSANDRA_DIR)
    CASSANDRA_GITREF = get_sha(CASSANDRA_DIR)

# Determine the location of the libjemalloc jar so that we can specify it
# through environment variables when start Cassandra.  This reduces startup
# time, making the dtests run faster.
def find_libjemalloc():
    if is_win():
        # let the normal bat script handle finding libjemalloc
        return ""

    this_dir = os.path.dirname(os.path.realpath(__file__))
    script = os.path.join(this_dir, "findlibjemalloc.sh")
    try:
        p = subprocess.Popen([script], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = p.communicate()
        if stderr or not stdout:
            return "-"  # tells C* not to look for libjemalloc
        else:
            return stdout
    except Exception as exc:
        print "Failed to run script to prelocate libjemalloc ({}): {}".format(script, exc)
        return ""

CASSANDRA_LIBJEMALLOC = find_libjemalloc()

class expect_control_connection_failures(object):
    """
    We're just using a class here as a one-off object with a filter method, for
    use as a filter object in the driver logger. It's frustrating that we can't
    just pass in a function, but we need an object with a .filter method. Oh
    well, I guess that's what old stdlib libraries are like.
    """
    @staticmethod
    def filter(record):
        expected_strings = [
            'Control connection failed to connect, shutting down Cluster:',
            '[control connection] Error connecting to '
        ]
        for s in expected_strings:
            if s in record.msg or s in record.name:
                return False
        return True

# copy the initial environment variables so we can reset them later:
initial_environment = copy.deepcopy(os.environ)

class DtestTimeoutError(Exception):
    pass

def reset_environment_vars():
    os.environ.clear()
    os.environ.update(initial_environment)

def warning(msg):
    LOG.warning(msg, extra={"current_test": CURRENT_TEST})
    if PRINT_DEBUG:
        print "WARN: " + msg

def debug(msg):
    LOG.debug(msg, extra={"current_test": CURRENT_TEST})
    if PRINT_DEBUG:
        print msg

def retry_till_success(fun, *args, **kwargs):
    timeout = kwargs.pop('timeout', 60)
    bypassed_exception = kwargs.pop('bypassed_exception', Exception)

    deadline = time.time() + timeout
    while True:
        try:
            return fun(*args, **kwargs)
        except bypassed_exception:
            if time.time() > deadline:
                raise
            else:
                # brief pause before next attempt
                time.sleep(0.25)

class FlakyRetryPolicy(RetryPolicy):
    """
    A retry policy that retries 5 times by default, but can be configured to
    retry more times.
    """

    def __init__(self, max_retries=5):
        self.max_retries = max_retries

    def on_read_timeout(self, *args, **kwargs):
        if kwargs['retry_num'] < self.max_retries:
            debug("Retrying read after timeout. Attempt #" + str(kwargs['retry_num']))
            return (self.RETRY, None)
        else:
            return (self.RETHROW, None)

    def on_write_timeout(self, *args, **kwargs):
        if kwargs['retry_num'] < self.max_retries:
            debug("Retrying write after timeout. Attempt #" + str(kwargs['retry_num']))
            return (self.RETRY, None)
        else:
            return (self.RETHROW, None)

    def on_unavailable(self, *args, **kwargs):
        if kwargs['retry_num'] < self.max_retries:
            debug("Retrying request after UE. Attempt #" + str(kwargs['retry_num']))
            return (self.RETRY, None)
        else:
            return (self.RETHROW, None)

class Runner(threading.Thread):

    def __init__(self, func):
        threading.Thread.__init__(self)
        self.__func = func
        self.__error = None
        self.__stopped = False
        self.daemon = True

    def run(self):
        i = 0
        while True:
            if self.__stopped:
                return
            try:
                self.__func(i)
            except Exception as e:
                self.__error = e
                return
            i = i + 1

    def stop(self):
        self.__stopped = True
        self.join()
        if self.__error is not None:
            raise self.__error

    def check(self):
        if self.__error is not None:
            raise self.__error

class Tester(TestCase):

    maxDiff = None

    def __init__(self, *argv, **kwargs):
        # if False, then scan the log of each node for errors after every test.
        self.allow_log_errors = False
        self.cluster_options = kwargs.pop('cluster_options', None)
        super(Tester, self).__init__(*argv, **kwargs)

    def set_node_to_current_version(self, node):
        version = os.environ.get('CASSANDRA_VERSION')
        cdir = CASSANDRA_DIR

        if version:
            node.set_install_dir(version=version)
        else:
            node.set_install_dir(install_dir=cdir)

    def init_config(self):
        init_default_config(self.cluster, self.cluster_options)

    def setUp(self):
        self.set_current_tst_name()
        kill_windows_cassandra_procs()
        maybe_cleanup_cluster_from_last_test_file()

        self.test_path = get_test_path()
        self.cluster = create_ccm_cluster(self.test_path, name='test')

        self.maybe_begin_active_log_watch()
        maybe_setup_jacoco(self.test_path)

        self.init_config()
        write_last_test_file(self.test_path, self.cluster)

        set_log_levels(self.cluster)
        self.connections = []
        self.runners = []

    # this is intentionally spelled 'tst' instead of 'test' to avoid
    # making unittest think it's a test method
    def set_current_tst_name(self):
        global CURRENT_TEST
        CURRENT_TEST = self.id() + self._testMethodName

    def maybe_begin_active_log_watch(self):
        if ENABLE_ACTIVE_LOG_WATCHING:
            if not self.allow_log_errors:
                self.begin_active_log_watch()

    def begin_active_log_watch(self):
        """
        Calls into ccm to start actively watching logs.

        In the event that errors are seen in logs, ccm will call back to _log_error_handler.

        When the cluster is no longer in use, stop_active_log_watch should be called to end log watching.
        (otherwise a 'daemon' thread will (needlessly) run until the process exits).
        """
        # log watching happens in another thread, but we want it to halt the main
        # thread's execution, which we have to do by registering a signal handler
        signal.signal(signal.SIGINT, self._catch_interrupt)
        self._log_watch_thread = self.cluster.actively_watch_logs_for_error(self._log_error_handler, interval=0.25)

    def _log_error_handler(self, errordata):
        """
        Callback handler used in conjunction with begin_active_log_watch.
        When called, prepares exception instance, then will indirectly
        cause _catch_interrupt to be called, which can raise the exception in the main
        program thread.

        @param errordata is a dictonary mapping node name to failure list.
        """
        # in some cases self.allow_log_errors may get set after proactive log checking has been enabled
        # so we need to double-check first thing before proceeding
        if self.allow_log_errors:
            return

        reportable_errordata = OrderedDict()

        for nodename, errors in errordata.items():
            filtered_errors = list(self.__filter_errors(['\n'.join(msg) for msg in errors]))
            if len(filtered_errors) is not 0:
                reportable_errordata[nodename] = filtered_errors

        # no errors worthy of halting the test
        if not reportable_errordata:
            return

        message = "Errors seen in logs for: {nodes}".format(nodes=", ".join(reportable_errordata.keys()))
        for nodename, errors in reportable_errordata.items():
            for error in errors:
                message += "\n{nodename}: {error}".format(nodename=nodename, error=error)

        try:
            debug('Errors were just seen in logs, ending test (if not ending already)!')
            print_("Error details: \n{message}".format(message=message))
            self.test_is_ending  # will raise AttributeError if not present
        except AttributeError:
            self.test_is_ending = True
            self.exit_with_exception = AssertionError("Log error encountered during active log scanning, see stdout")
            # thread.interrupt_main will SIGINT in the main thread, which we can
            # catch to raise an exception with useful information
            thread.interrupt_main()

    """
    Finds files matching the glob pattern specified as argument on
    the given keyspace in all nodes
    """

    def glob_data_dirs(self, path, ks="ks"):
        result = []
        for node in self.cluster.nodelist():
            for data_dir in node.data_directories():
                ks_dir = os.path.join(data_dir, ks, path)
                result.extend(glob.glob(ks_dir))
        return result

    def _catch_interrupt(self, signal, frame):
        """
        Signal handler for registering on SIGINT.

        If called will look for a stored exception and raise it to abort test.
        If a stored exception is not present, this handler has likely caught a
        user interrupt via CTRL-C, and will raise a KeyboardInterrupt.
        """
        try:
            # check if we have a persisted exception to fail with
            raise self.exit_with_exception
        except AttributeError:
            # looks like this was just a plain CTRL-C event
            raise KeyboardInterrupt()

    def copy_logs(self, cluster, directory=None, name=None):
        """Copy the current cluster's log files somewhere, by default to LOG_SAVED_DIR with a name of 'last'"""
        if directory is None:
            directory = LOG_SAVED_DIR
        if name is None:
            name = LAST_LOG
        else:
            name = os.path.join(directory, name)
        if not os.path.exists(directory):
            os.mkdir(directory)
        logs = [(node.name, node.logfilename(), node.debuglogfilename(), node.gclogfilename(), node.compactionlogfilename())
                for node in self.cluster.nodes.values()]
        if len(logs) is not 0:
            basedir = str(int(time.time() * 1000)) + '_' + self.id()
            logdir = os.path.join(directory, basedir)
            os.mkdir(logdir)
            for n, log, debuglog, gclog, compactionlog in logs:
                if os.path.exists(log):
                    self.assertGreaterEqual(os.path.getsize(log), 0)
                    shutil.copyfile(log, os.path.join(logdir, n + ".log"))
                if os.path.exists(debuglog):
                    self.assertGreaterEqual(os.path.getsize(debuglog), 0)
                    shutil.copyfile(debuglog, os.path.join(logdir, n + "_debug.log"))
                if os.path.exists(gclog):
                    self.assertGreaterEqual(os.path.getsize(gclog), 0)
                    shutil.copyfile(gclog, os.path.join(logdir, n + "_gc.log"))
                if os.path.exists(compactionlog):
                    self.assertGreaterEqual(os.path.getsize(compactionlog), 0)
                    shutil.copyfile(compactionlog, os.path.join(logdir, n + "_compaction.log"))
            if os.path.exists(name):
                os.unlink(name)
            if not is_win():
                os.symlink(basedir, name)

    def get_eager_protocol_version(self, cassandra_version):
        """
        Returns the highest protocol version accepted
        by the given C* version
        """
        if cassandra_version >= '2.2':
            protocol_version = 4
        elif cassandra_version >= '2.1':
            protocol_version = 3
        elif cassandra_version >= '2.0':
            protocol_version = 2
        else:
            protocol_version = 1
        return protocol_version

    def cql_connection(self, node, keyspace=None, user=None,
                       password=None, compression=True, protocol_version=None, port=None, ssl_opts=None):

        return self._create_session(node, keyspace, user, password, compression,
                                    protocol_version, port=port, ssl_opts=ssl_opts)

    def exclusive_cql_connection(self, node, keyspace=None, user=None,
                                 password=None, compression=True, protocol_version=None, port=None, ssl_opts=None):

        node_ip = self.get_ip_from_node(node)
        wlrr = WhiteListRoundRobinPolicy([node_ip])

        return self._create_session(node, keyspace, user, password, compression,
                                    protocol_version, wlrr, port=port, ssl_opts=ssl_opts)

    def _create_session(self, node, keyspace, user, password, compression, protocol_version, load_balancing_policy=None,
                        port=None, ssl_opts=None):
        node_ip = self.get_ip_from_node(node)
        if not port:
            port = self.get_port_from_node(node)

        if protocol_version is None:
            protocol_version = self.get_eager_protocol_version(self.cluster.version())

        if user is not None:
            auth_provider = self.get_auth_provider(user=user, password=password)
        else:
            auth_provider = None

        cluster = PyCluster([node_ip], auth_provider=auth_provider, compression=compression,
                            protocol_version=protocol_version, load_balancing_policy=load_balancing_policy, default_retry_policy=FlakyRetryPolicy(),
                            port=port, ssl_options=ssl_opts, connect_timeout=10)
        session = cluster.connect()

        # temporarily increase client-side timeout to 1m to determine
        # if the cluster is simply responding slowly to requests
        session.default_timeout = 60.0

        if keyspace is not None:
            session.set_keyspace(keyspace)

        # override driver default consistency level of LOCAL_QUORUM
        session.default_consistency_level = ConsistencyLevel.ONE

        self.connections.append(session)
        return session

    def patient_cql_connection(self, node, keyspace=None,
                               user=None, password=None, timeout=30, compression=True,
                               protocol_version=None, port=None, ssl_opts=None):
        """
        Returns a connection after it stops throwing NoHostAvailables due to not being ready.

        If the timeout is exceeded, the exception is raised.
        """
        if is_win():
            timeout *= 2

        logging.getLogger('cassandra.cluster').addFilter(expect_control_connection_failures)
        try:
            session = retry_till_success(
                self.cql_connection,
                node,
                keyspace=keyspace,
                user=user,
                password=password,
                timeout=timeout,
                compression=compression,
                protocol_version=protocol_version,
                port=port,
                ssl_opts=ssl_opts,
                bypassed_exception=NoHostAvailable
            )
        finally:
            logging.getLogger('cassandra.cluster').removeFilter(expect_control_connection_failures)

        return session

    def patient_exclusive_cql_connection(self, node, keyspace=None,
                                         user=None, password=None, timeout=30, compression=True,
                                         protocol_version=None, port=None, ssl_opts=None):
        """
        Returns a connection after it stops throwing NoHostAvailables due to not being ready.

        If the timeout is exceeded, the exception is raised.
        """
        if is_win():
            timeout *= 2

        return retry_till_success(
            self.exclusive_cql_connection,
            node,
            keyspace=keyspace,
            user=user,
            password=password,
            timeout=timeout,
            compression=compression,
            protocol_version=protocol_version,
            port=port,
            ssl_opts=ssl_opts,
            bypassed_exception=NoHostAvailable
        )

    def create_ks(self, session, name, rf):
        query = 'CREATE KEYSPACE %s WITH replication={%s}'
        if isinstance(rf, types.IntType):
            # we assume simpleStrategy
            session.execute(query % (name, "'class':'SimpleStrategy', 'replication_factor':%d" % rf))
        else:
            self.assertGreaterEqual(len(rf), 0, "At least one datacenter/rf pair is needed")
            # we assume networkTopologyStrategy
            options = (', ').join(['\'%s\':%d' % (d, r) for d, r in rf.iteritems()])
            session.execute(query % (name, "'class':'NetworkTopologyStrategy', %s" % options))
        session.execute('USE {}'.format(name))

    # We default to UTF8Type because it's simpler to use in tests
    def create_cf(self, session, name, key_type="varchar", speculative_retry=None, read_repair=None, compression=None,
                  gc_grace=None, columns=None, validation="UTF8Type", compact_storage=False):

        additional_columns = ""
        if columns is not None:
            for k, v in columns.items():
                additional_columns = "{}, {} {}".format(additional_columns, k, v)

        if additional_columns == "":
            query = 'CREATE COLUMNFAMILY %s (key %s, c varchar, v varchar, PRIMARY KEY(key, c)) WITH comment=\'test cf\'' % (name, key_type)
        else:
            query = 'CREATE COLUMNFAMILY %s (key %s PRIMARY KEY%s) WITH comment=\'test cf\'' % (name, key_type, additional_columns)

        if compression is not None:
            query = '%s AND compression = { \'sstable_compression\': \'%sCompressor\' }' % (query, compression)
        else:
            # if a compression option is omitted, C* will default to lz4 compression
            query += ' AND compression = {}'

        if read_repair is not None:
            query = '%s AND read_repair_chance=%f AND dclocal_read_repair_chance=%f' % (query, read_repair, read_repair)
        if gc_grace is not None:
            query = '%s AND gc_grace_seconds=%d' % (query, gc_grace)
        if speculative_retry is not None:
            query = '%s AND speculative_retry=\'%s\'' % (query, speculative_retry)

        if compact_storage:
            query += ' AND COMPACT STORAGE'

        session.execute(query)
        time.sleep(0.2)

    @classmethod
    def tearDownClass(cls):
        reset_environment_vars()
        if os.path.exists(LAST_TEST_DIR):
            with open(LAST_TEST_DIR) as f:
                test_path = f.readline().strip('\n')
                name = f.readline()
                try:
                    cluster = ClusterFactory.load(test_path, name)
                    # Avoid waiting too long for node to be marked down
                    if KEEP_TEST_DIR:
                        cluster.stop(gently=RECORD_COVERAGE)
                    else:
                        cluster.remove()
                        os.rmdir(test_path)
                except IOError:
                    # after a restart, /tmp will be emptied so we'll get an IOError when loading the old cluster here
                    pass
            try:
                os.remove(LAST_TEST_DIR)
            except IOError:
                # Ignore - see comment above
                pass

    def tearDown(self):
        # test_is_ending prevents active log watching from being able to interrupt the test
        # which we don't want to happen once tearDown begins
        self.test_is_ending = True

        reset_environment_vars()

        for con in self.connections:
            con.cluster.shutdown()

        for runner in self.runners:
            try:
                runner.stop()
            except:
                pass

        failed = did_fail()
        try:
            if not self.allow_log_errors and self.check_logs_for_errors():
                failed = True
                raise AssertionError('Unexpected error in log, see stdout')
        finally:
            try:
                # save the logs for inspection
                if failed or KEEP_LOGS:
                    self.copy_logs(self.cluster)
            except Exception as e:
                print "Error saving log:", str(e)
            finally:
                log_watch_thread = getattr(self, '_log_watch_thread', None)
                cleanup_cluster(self.cluster, self.test_path, log_watch_thread)

    def check_logs_for_errors(self):
        for node in self.cluster.nodelist():
            errors = list(self.__filter_errors(
                ['\n'.join(msg) for msg in node.grep_log_for_errors()]))
            if len(errors) is not 0:
                for error in errors:
                    print_("Unexpected error in {node_name} log, error: \n{error}".format(node_name=node.name, error=error))
                return True

    def go(self, func):
        runner = Runner(func)
        self.runners.append(runner)
        runner.start()
        return runner

    def skip(self, msg):
        if not NO_SKIP:
            raise SkipTest(msg)

    def __filter_errors(self, errors):
        """Filter errors, removing those that match self.ignore_log_patterns"""
        if not hasattr(self, 'ignore_log_patterns'):
            self.ignore_log_patterns = []
        for e in errors:
            for pattern in self.ignore_log_patterns:
                if re.search(pattern, e):
                    break
            else:
                yield e

    def get_ip_from_node(self, node):
        if node.network_interfaces['binary']:
            node_ip = node.network_interfaces['binary'][0]
        else:
            node_ip = node.network_interfaces['thrift'][0]
        return node_ip

    def get_port_from_node(self, node):
        """
        Return the port that this node is listening on.
        We only use this to connect the native driver,
        so we only care about the binary port.
        """
        try:
            return node.network_interfaces['binary'][1]
        except Exception:
            raise RuntimeError("No network interface defined on this node object. {}".format(node.network_interfaces))

    def get_auth_provider(self, user, password):
        return PlainTextAuthProvider(username=user, password=password)

    def make_auth(self, user, password):
        def private_auth(node_ip):
            return {'username': user, 'password': password}
        return private_auth

    # Disable docstrings printing in nosetest output
    def shortDescription(self):
        return None

    def wait_for_any_log(self, nodes, pattern, timeout, filename='system.log'):
        """
        Look for a pattern in the system.log of any in a given list
        of nodes.
        @param nodes The list of nodes whose logs to scan
        @param pattern The target pattern
        @param timeout How long to wait for the pattern. Note that
                        strictly speaking, timeout is not really a timeout,
                        but a maximum number of attempts. This implies that
                        the all the grepping takes no time at all, so it is
                        somewhat inaccurate, but probably close enough.
        @return The first node in whose log the pattern was found
        """
        for _ in range(timeout):
            for node in nodes:
                found = node.grep_log(pattern, filename=filename)
                if found:
                    return node
            time.sleep(1)

        raise TimeoutError(time.strftime("%d %b %Y %H:%M:%S", time.gmtime()) +
                           " Unable to find: " + pattern + " in any node log within " + str(timeout) + "s")

    def get_jfr_jvm_args(self):
        """
        @return The JVM arguments required for attaching flight recorder to a Java process.
        """
        return ["-XX:+UnlockCommercialFeatures", "-XX:+FlightRecorder"]

    def start_jfr_recording(self, nodes):
        """
        Start Java flight recorder provided the cluster was started with the correct jvm arguments.
        """
        for node in nodes:
            p = subprocess.Popen(['jcmd', str(node.pid), 'JFR.start'],
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
            stdout, stderr = p.communicate()
            debug(stdout)
            debug(stderr)

    def dump_jfr_recording(self, nodes):
        """
        Save Java flight recorder results to file for analyzing with mission control.
        """
        for node in nodes:
            p = subprocess.Popen(['jcmd', str(node.pid), 'JFR.dump',
                                  'recording=1', 'filename=recording_{}.jfr'.format(node.address())],
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
            stdout, stderr = p.communicate()
            debug(stdout)
            debug(stderr)

def kill_windows_cassandra_procs():
    # On Windows, forcefully terminate any leftover previously running cassandra processes. This is a temporary
    # workaround until we can determine the cause of intermittent hung-open tests and file-handles.
    if is_win():
        try:
            import psutil
            for proc in psutil.process_iter():
                try:
                    pinfo = proc.as_dict(attrs=['pid', 'name', 'cmdline'])
                except psutil.NoSuchProcess:
                    pass
                else:
                    if (pinfo['name'] == 'java.exe' and '-Dcassandra' in pinfo['cmdline']):
                        print 'Found running cassandra process with pid: ' + str(pinfo['pid']) + '. Killing.'
                        psutil.Process(pinfo['pid']).kill()
        except ImportError:
            debug("WARN: psutil not installed. Cannot detect and kill "
                  "running cassandra processes - you may see cascading dtest failures.")

def get_test_path():
    test_path = tempfile.mkdtemp(prefix='dtest-')

    # ccm on cygwin needs absolute path to directory - it crosses from cygwin space into
    # regular Windows space on wmic calls which will otherwise break pathing
    if sys.platform == "cygwin":
        process = subprocess.Popen(["cygpath", "-m", test_path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        test_path = process.communicate()[0].rstrip()

    return test_path
# nose will discover this as a test, so we manually make it not a test
get_test_path.__test__ = False

def create_ccm_cluster(test_path, name):
    debug("cluster ccm directory: " + test_path)
    version = os.environ.get('CASSANDRA_VERSION')
    cdir = CASSANDRA_DIR

    if version:
        cluster = Cluster(test_path, name, cassandra_version=version)
    else:
        cluster = Cluster(test_path, name, cassandra_dir=cdir)

    if DISABLE_VNODES:
        cluster.set_configuration_options(values={'num_tokens': None})
    else:
        cluster.set_configuration_options(values={'initial_token': None, 'num_tokens': NUM_TOKENS})

    if OFFHEAP_MEMTABLES:
        cluster.set_configuration_options(values={'memtable_allocation_type': 'offheap_objects'})

    cluster.set_datadir_count(DATADIR_COUNT)
    cluster.set_environment_variable('CASSANDRA_LIBJEMALLOC', CASSANDRA_LIBJEMALLOC)

    return cluster

def cleanup_cluster(cluster, test_path, log_watch_thread=None):
    if SILENCE_DRIVER_ON_SHUTDOWN:
        # driver logging is very verbose when nodes start going down -- bump up the level
        logging.getLogger('cassandra').setLevel(logging.CRITICAL)

    if KEEP_TEST_DIR:
        cluster.stop(gently=RECORD_COVERAGE)
    else:
        # when recording coverage the jvm has to exit normally
        # or the coverage information is not written by the jacoco agent
        # otherwise we can just kill the process
        if RECORD_COVERAGE:
            cluster.stop(gently=True)

        # Cleanup everything:
        try:
            if log_watch_thread:
                stop_active_log_watch(log_watch_thread)
        finally:
            debug("removing ccm cluster {name} at: {path}".format(name=cluster.name, path=test_path))
            cluster.remove()

            debug("clearing ssl stores from [{0}] directory".format(test_path))
            for filename in ('keystore.jks', 'truststore.jks', 'ccm_node.cer'):
                try:
                    os.remove(os.path.join(test_path, filename))
                except OSError as e:
                    # once we port to py3, which has better reporting for exceptions raised while
                    # handling other excpetions, we should just assert e.errno == errno.ENOENT
                    if e.errno != errno.ENOENT:  # ENOENT = no such file or directory
                        raise

            os.rmdir(test_path)
            cleanup_last_test_dir()

def cleanup_last_test_dir():
    if os.path.exists(LAST_TEST_DIR):
        os.remove(LAST_TEST_DIR)

def stop_active_log_watch(log_watch_thread):
    """
    Joins the log watching thread, which will then exit.
    Should be called after each test, ideally after nodes are stopped but before cluster files are removed.

    Can be called multiple times without error.
    If not called, log watching thread will remain running until the parent process exits.
    """
    log_watch_thread.join(timeout=60)

def maybe_cleanup_cluster_from_last_test_file():
    # cleaning up if a previous execution didn't trigger tearDown (which
    # can happen if it is interrupted by KeyboardInterrupt)
    if os.path.exists(LAST_TEST_DIR):
        with open(LAST_TEST_DIR) as f:
            test_path = f.readline().strip('\n')
            name = f.readline()
        try:
            cluster = ClusterFactory.load(test_path, name)
            # Avoid waiting too long for node to be marked down
            cleanup_cluster(cluster, test_path)
        except IOError:
            # after a restart, /tmp will be emptied so we'll get an IOError when loading the old cluster here
            pass

def init_default_config(cluster, cluster_options):
    # the failure detector can be quite slow in such tests with quick start/stop
    phi_values = {'phi_convict_threshold': 5}

    timeout = 10000
    if cluster_options is not None:
        values = merge_dicts(cluster_options, phi_values)
    else:
        values = merge_dicts(phi_values, {
            'read_request_timeout_in_ms': timeout,
            'range_request_timeout_in_ms': timeout,
            'write_request_timeout_in_ms': timeout,
            'truncate_request_timeout_in_ms': timeout,
            'request_timeout_in_ms': timeout
        })

    cluster.set_configuration_options(values)
    debug("Done setting configuration options:\n" + pprint.pformat(cluster._config_options, indent=4))

def write_last_test_file(test_path, cluster):
    with open(LAST_TEST_DIR, 'w') as f:
        f.write(test_path + '\n')
        f.write(cluster.name)

def set_log_levels(cluster):
    if DEBUG:
        cluster.set_log_level("DEBUG")
    if TRACE:
        cluster.set_log_level("TRACE")

    if os.environ.get('DEBUG', 'no').lower() not in ('no', 'false', 'yes', 'true'):
        classes_to_debug = os.environ.get('DEBUG').split(":")
        cluster.set_log_level('DEBUG', None if len(classes_to_debug) == 0 else classes_to_debug)

    if os.environ.get('TRACE', 'no').lower() not in ('no', 'false', 'yes', 'true'):
        classes_to_trace = os.environ.get('TRACE').split(":")
        cluster.set_log_level('TRACE', None if len(classes_to_trace) == 0 else classes_to_trace)

def maybe_setup_jacoco(test_path, cluster_name='test'):
    """Setup JaCoCo code coverage support"""

    if not RECORD_COVERAGE:
        return

    # use explicit agent and execfile locations
    # or look for a cassandra build if they are not specified
    cdir = CASSANDRA_DIR

    agent_location = os.environ.get('JACOCO_AGENT_JAR', os.path.join(cdir, 'build/lib/jars/jacocoagent.jar'))
    jacoco_execfile = os.environ.get('JACOCO_EXECFILE', os.path.join(cdir, 'build/jacoco/jacoco.exec'))

    if os.path.isfile(agent_location):
        debug("Jacoco agent found at {}".format(agent_location))
        with open(os.path.join(
                test_path, cluster_name, 'cassandra.in.sh'), 'w') as f:

            f.write('JVM_OPTS="$JVM_OPTS -javaagent:{jar_path}=destfile={exec_file}"'
                    .format(jar_path=agent_location, exec_file=jacoco_execfile))

            if os.path.isfile(jacoco_execfile):
                debug("Jacoco execfile found at {}, execution data will be appended".format(jacoco_execfile))
            else:
                debug("Jacoco execfile will be created at {}".format(jacoco_execfile))
    else:
        debug("Jacoco agent not found or is not file. Execution will not be recorded.")

def did_fail():
    if sys.exc_info() == (None, None, None):
        return False

    exc_class, _, _ = sys.exc_info()
    return not issubclass(exc_class, unittest.case.SkipTest)

class ReusableClusterTester(Tester):
    """
    A Tester designed for reusing the same cluster across multiple
    test methods.  This makes test suites with many small tests run
    much, much faster.  However, there are a couple of downsides:

    First, test setup and teardown must be diligent about cleaning
    up any data or schema elements that may interfere with other
    tests.

    Second, errors triggered by one test method may cascade
    into other test failures.  In an attempt to limit this, the
    cluster will be restarted if a test fails or an exception is
    caught.  However, there may still be undetected problems in
    Cassandra that cause cascading failures.
    """

    test_path = None
    cluster = None
    cluster_options = None

    @classmethod
    def setUpClass(cls):
        kill_windows_cassandra_procs()
        maybe_cleanup_cluster_from_last_test_file()
        cls.initialize_cluster()

    def setUp(self):
        self.set_current_tst_name()
        self.connections = []

        # TODO enable active log watching
        # This needs to happen in setUp() and not setUpClass() so that individual
        # test methods can set allow_log_errors and so that error handling
        # only fails a single test method instead of the entire class.
        # The problem with this is that ccm doesn't yet support stopping the
        # active log watcher -- it runs until the cluster is destroyed.  Since
        # we reuse the same cluster, this doesn't work for us.

    def tearDown(self):
        # test_is_ending prevents active log watching from being able to interrupt the test
        self.test_is_ending = True

        failed = did_fail()
        try:
            if not self.allow_log_errors and self.check_logs_for_errors():
                failed = True
                raise AssertionError('Unexpected error in log, see stdout')
        finally:
            try:
                # save the logs for inspection
                if failed or KEEP_LOGS:
                    self.copy_logs(self.cluster)
            except Exception as e:
                print "Error saving log:", str(e)
            finally:
                reset_environment_vars()
                if failed:
                    cleanup_cluster(self.cluster, self.test_path)
                    kill_windows_cassandra_procs()
                    self.initialize_cluster()

    @classmethod
    def initialize_cluster(cls):
        """
        This method is responsible for initializing and configuring a ccm
        cluster for the next set of tests.  This can be called for two
        different reasons:
         * A class of tests is starting
         * A test method failed/errored, so the cluster has been wiped

        Subclasses that require custom initialization should generally
        do so by overriding post_initialize_cluster().
        """
        cls.test_path = get_test_path()
        cls.cluster = create_ccm_cluster(cls.test_path, name='test')
        cls.init_config()

        maybe_setup_jacoco(cls.test_path)
        cls.init_config()
        write_last_test_file(cls.test_path, cls.cluster)
        set_log_levels(cls.cluster)

        cls.post_initialize_cluster()

    @classmethod
    def post_initialize_cluster(cls):
        """
        This method is called after the ccm cluster has been created
        and default config options have been applied.  Any custom
        initialization for a test class should generally be done
        here in order to correctly handle cluster restarts after
        test method failures.
        """
        pass

    @classmethod
    def init_config(cls):
        init_default_config(cls.cluster, cls.cluster_options)

def canReuseCluster(Tester):
    orig_init = Tester.__init__
    # make copy of original __init__, so we can call it without recursion

    def __init__(self, *args, **kwargs):
        self._preserve_cluster = REUSE_CLUSTER
        orig_init(self, *args, **kwargs)  # call the original __init__

    Tester.__init__ = __init__  # set the class' __init__ to the new one
    return Tester

class freshCluster():

    def __call__(self, f):
        def wrapped(obj):
            obj._preserve_cluster = False
            obj.setUp()
            f(obj)
        wrapped.__name__ = f.__name__
        wrapped.__doc__ = f.__doc__
        return wrapped

class MultiError(Exception):
    """
    Extends Exception to provide reporting multiple exceptions at once.
    """

    def __init__(self, exceptions, tracebacks):
        # an exception and the corresponding traceback should be found at the same
        # position in their respective lists, otherwise __str__ will be incorrect
        self.exceptions = exceptions
        self.tracebacks = tracebacks

    def __str__(self):
        output = "\n****************************** BEGIN MultiError ******************************\n"

        for (exc, tb) in zip(self.exceptions, self.tracebacks):
            output += str(exc)
            output += str(tb) + "\n"

        output += "****************************** END MultiError ******************************"

        return output

def run_scenarios(scenarios, handler, deferred_exceptions=tuple()):
    """
    Runs multiple scenarios from within a single test method.

    "Scenarios" are mini-tests where a common procedure can be reused with several different configurations.
    They are intended for situations where complex/expensive setup isn't required and some shared state is acceptable (or trivial to reset).

    Arguments: scenarios should be an iterable, handler should be a callable, and deferred_exceptions should be a tuple of exceptions which
    are safe to delay until the scenarios are all run. For each item in scenarios, handler(item) will be called in turn.

    Exceptions which occur will be bundled up and raised as a single MultiError exception, either when: a) all scenarios have run,
    or b) on the first exception encountered which is not whitelisted in deferred_exceptions.
    """
    errors = []
    tracebacks = []

    for i, scenario in enumerate(scenarios, 1):
        debug("running scenario {}/{}: {}".format(i, len(scenarios), scenario))

        try:
            handler(scenario)
        except deferred_exceptions as e:
            tracebacks.append(traceback.format_exc(sys.exc_info()))
            errors.append(type(e)('encountered {} {} running scenario:\n  {}\n'.format(e.__class__.__name__, e.message, scenario)))
            debug("scenario {}/{} encountered a deferrable exception, continuing".format(i, len(scenarios)))
        except Exception as e:
            # catch-all for any exceptions not intended to be deferred
            tracebacks.append(traceback.format_exc(sys.exc_info()))
            errors.append(type(e)('encountered {} {} running scenario:\n  {}\n'.format(e.__class__.__name__, e.message, scenario)))
            debug("scenario {}/{} encountered a non-deferrable exception, aborting".format(i, len(scenarios)))
            raise MultiError(errors, tracebacks)

    if errors:
        raise MultiError(errors, tracebacks)


text:
/* @flow */

import React, { Component, PropTypes } from 'react';
import {
  TouchableNativeFeedback,
  TouchableOpacity,
  Platform,
  View,
} from 'react-native';

const LOLLIPOP = 21;

type Props = {
  borderless?: boolean;
  pressColor?: string;
  children?: React.Element<any>;
  style?: any;
}

type DefaultProps = {
  pressColor: string;
}

export default class TouchableItem extends Component<DefaultProps, Props, void> {
  static propTypes = {
    borderless: PropTypes.bool,
    pressColor: PropTypes.string,
    children: PropTypes.node.isRequired,
    style: View.propTypes.style,
  };

  static defaultProps = {
    pressColor: 'rgba(255, 255, 255, .4)',
  };

  render() {
    if (Platform.OS === 'android' && Platform.Version >= LOLLIPOP) {
      return (
        <TouchableNativeFeedback
          {...this.props}
          style={null}
          background={TouchableNativeFeedback.Ripple(this.props.pressColor, this.props.borderless)}
        >
          <View style={this.props.style}>
            {this.props.children}
          </View>
        </TouchableNativeFeedback>
      );
    } else {
      return (
        <TouchableOpacity {...this.props}>
          {this.props.children}
        </TouchableOpacity>
      );
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
#import "EC2ProductCode.h"

@implementation EC2ProductCode

@synthesize productCodeId;
@synthesize productCodeType;

-(id)init
{
    if (self = [super init]) {
        productCodeId   = nil;
        productCodeType = nil;
    }

    return self;
}

-(NSString *)description
{
    NSMutableString *buffer = [[NSMutableString alloc] initWithCapacity:256];

    [buffer appendString:@"{"];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"ProductCodeId: %@,", productCodeId] autorelease]];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"ProductCodeType: %@,", productCodeType] autorelease]];
    [buffer appendString:[super description]];
    [buffer appendString:@"}"];

    return [buffer autorelease];
}

-(void)dealloc
{
    [productCodeId release];
    [productCodeType release];

    [super dealloc];
}

@end


text:
namespace RangeIt.Tests.Ranges
{
    using FluentAssertions;
    using RangeIt.Ranges;
    using System.Collections.Generic;
    using System.Linq;
    using Traits;
    using Xunit;

    public class Range_Iota_Tests
    {
        [Fact]
        [Category("Ranges.Range.Iota")]
        public void Test_Range_Iota()
        {
            Range<int> range = Range.Iota(1, 11);

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(10)
                          .And.ContainInOrder(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        }

        [Fact]
        [Category("Ranges.Range.Iota")]
        public void Test_Range_Iota_With_To_SmallerThan_From()
        {
            Range<int> range = Range.Iota(1, 0);
            range.Should().NotBeNull().And.BeEmpty();
        }

        [Fact]
        [Category("Ranges.Range.Iota")]
        public void Test_Range_Iota_WithEqualArguments()
        {
            Range<int> range = Range.Iota(1, 1);
            range.Should().NotBeNull().And.BeEmpty();
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithStep")]
        public void Test_Range_Iota_WithStep()
        {
            Range<int> range = Range.Iota(1, 11, 2);

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(5)
                          .And.ContainInOrder(1, 3, 5, 7, 9);
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithStep")]
        public void Test_Range_Iota_WithNegativeStep()
        {
            Range<int> range = Range.Iota(1, 11, -2);

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(5)
                          .And.ContainInOrder(1, 3, 5, 7, 9);
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithStep")]
        public void Test_Range_Iota_WithZeroStep()
        {
            Range<int> range = Range.Iota(1, 11, 0);

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(10)
                          .And.ContainInOrder(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithStep")]
        public void Test_Range_Iota_WithStep_With_To_SmallerThan_From()
        {
            Range<int> range = Range.Iota(1, 0, 2);
            range.Should().NotBeNull().And.BeEmpty();
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithStep")]
        public void Test_Range_Iota_WithStep_WithEqualArguments()
        {
            Range<int> range = Range.Iota(1, 1, 2);
            range.Should().NotBeNull().And.BeEmpty();
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithFunctor.WithStartValue")]
        public void Test_Range_Iota_WithFunctor_WithStartValue_IntIteration()
        {
            Range<int> range = Range.Iota(1, 10, (i) => i + 1);

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(10)
                          .And.ContainInOrder(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithFunctor.WithStartValue")]
        public void Test_Range_Iota_WithFunctor_WithStartValue_NegativeIntIteration()
        {
            Range<int> range = Range.Iota(1, 10, (i) => i - 1);

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(10)
                          .And.ContainInOrder(1, 0, -1, -2, -3, -4, -5, -6, -7, -8);
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithFunctor.WithStartValue")]
        public void Test_Range_Iota_WithFunctor_WithStartValue_IntMultiplications()
        {
            Range<int> range = Range.Iota(1, 10, (i) => i * 2);

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(10)
                          .And.ContainInOrder(1, 2, 4, 8, 16, 32, 64, 128, 256, 512);
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithFunctor.WithStartValue")]
        public void Test_Range_Iota_WithFunctor_WithStartValue_NegativeIntMultiplications()
        {
            Range<int> range = Range.Iota(1, 10, (i) => i * -2);

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(10)
                          .And.ContainInOrder(1, -2, 4, -8, 16, -32, 64, -128, 256, -512);
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithFunctor.WithStartValue")]
        public void Test_Range_Iota_WithFunctor_WithStartValue_StringIteration()
        {
            Range<string> range = Range.Iota("a", 10, (s) => s + "a");

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(10)
                          .And.ContainInOrder("a", "aa", "aaa", "aaaa", "aaaaa",
                                              "aaaaaa", "aaaaaaa", "aaaaaaaa",
                                              "aaaaaaaaa", "aaaaaaaaaa");
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithFunctor.WithStartValue")]
        public void Test_Range_Iota_WithFunctor_WithStartValue_WithZeroCount()
        {
            Range<int> range = Range.Iota(1, 0, (i) => i + 1);

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(1)
                          .And.ContainInOrder(1);
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithSimpleFunctor.WithStartValue")]
        public void Test_Range_Iota_WithSimpleFunctor_WithStartValue_Ints()
        {
            Range<int> range = Range.Iota(1, 10, () => 5 * 5);

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(10)
                          .And.ContainInOrder(1, 25, 25, 25, 25, 25, 25, 25, 25, 25);
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithSimpleFunctor.WithStartValue")]
        public void Test_Range_Iota_WithSimpleFunctor_WithStartValue_Strings()
        {
            Range<string> range = Range.Iota("hello", 10, () => "world");

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(10)
                          .And.ContainInOrder("hello", "world", "world", "world", "world",
                                              "world", "world", "world", "world", "world");
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithSimpleFunctor.WithStartValue")]
        public void Test_Range_Iota_WithSimpleFunctor_WithStartValue_WithZeroCount()
        {
            Range<int> range = Range.Iota(1, 0, () => 1);

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(1)
                          .And.ContainInOrder(1);
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithSimpleFunctor")]
        public void Test_Range_Iota_WithSimpleFunctor_Ints()
        {
            Range<int> range = Range.Iota(10, () => 5 * 5);

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(10)
                          .And.ContainInOrder(25, 25, 25, 25, 25, 25, 25, 25, 25, 25);
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithSimpleFunctor")]
        public void Test_Range_Iota_WithSimpleFunctor_Strings()
        {
            Range<string> range = Range.Iota(10, () => "hello");

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(10)
                          .And.ContainInOrder("hello", "hello", "hello", "hello", "hello",
                                              "hello", "hello", "hello", "hello", "hello");
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithSimpleFunctor")]
        public void Test_Range_Iota_WithSimpleFunctor_WithZeroCount()
        {
            Range<int> range = Range.Iota(0, () => 1);
            range.Should().NotBeNull().And.BeEmpty();
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithGenerator")]
        public void Test_Range_Iota_WithGenerator_Ints()
        {
            // startValue is 0 (excluding)
            Range<int> range = Range.Iota<int>((i) => i + 1, (i) => i == 15);

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(15)
                          .And.ContainInOrder(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithGenerator")]
        public void Test_Range_Iota_WithGenerator_Strings()
        {
            // startValue is null (excluding)
            Range<string> range = Range.Iota<string>((s) => s != null ? s + "a" : "a",
                                                     (s) => s?.Length == 10);

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(10)
                          .And.ContainInOrder("a", "aa", "aaa", "aaaa", "aaaaa",
                                              "aaaaaa", "aaaaaaa", "aaaaaaaa",
                                              "aaaaaaaaa", "aaaaaaaaaa");
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithSimpleGenerator")]
        public void Test_Range_Iota_WithSimpleGenerator_Ints()
        {
            int val = 0;
            Range<int> range = Range.Iota(() => val++, (i) => i == 15);

            List<int> list = range.ToList();

            list.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(16)
                          .And.ContainInOrder(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithSimpleGenerator")]
        public void Test_Range_Iota_WithSimpleGenerator_Strings()
        {
            string val = "a";
            Range<string> range = Range.Iota(() => { val += "a"; return val; },
                                             (s) => s?.Length == 10);

            List<string> list = range.ToList();

            list.Should().NotBeNull()
                         .And.NotBeEmpty()
                         .And.HaveCount(9)
                         .And.ContainInOrder("aa", "aaa", "aaaa", "aaaaa",
                                             "aaaaaa", "aaaaaaa", "aaaaaaaa",
                                             "aaaaaaaaa", "aaaaaaaaaa");
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithSimpleGenerator.WithStartValue")]
        public void Test_Range_Iota_WithGenerator_WithStartValue_Ints()
        {
            Range<int> range = Range.Iota(5, (i) => i + 1, (i) => i == 15);

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(11)
                          .And.ContainInOrder(5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithGenerator.WithStartValue")]
        public void Test_Range_Iota_WithGenerator_WithStartValue_Strings()
        {
            Range<string> range = Range.Iota("hello", (s) => s + "a", (s) => s?.Length == 10);

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(6)
                          .And.ContainInOrder("hello", "helloa", "helloaa", "helloaaa",
                                              "helloaaaa", "helloaaaaa");
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithGenerator.WithStartValue")]
        public void Test_Range_Iota_WithGenerator_WithStartValue_StartValueEqualsPredicateCondition()
        {
            Range<int> range = Range.Iota(5, (i) => i + 1, (i) => i == 5);

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(1)
                          .And.Contain(5);
        }

        [Fact]
        [Category("Ranges.Range.Iota.WithGenerator.WithStartValue")]
        public void Test_Range_Iota_WithGenerator_WithStartValue_VeryNearValueEqualsPredicateCondition()
        {
            Range<int> range = Range.Iota(5, (i) => i + 1, (i) => i == 6);

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(2)
                          .And.ContainInOrder(5, 6);
        }
    }
}


text:
#ifndef __CLOCK_H__
#define __CLOCK_H__

extern const uint32_t CLOCK_SECOND;
typedef uint32_t tClockTime;

void Clock_Init(void);
tClockTime Clock_Time(void);
void Clock_Wait(uint32_t i);
void Clock_Suspend(void);

#endif /* __CLOCK_H__ */


text:
using System;
using Org.Apache.REEF.Utilities.Diagnostics;
using Org.Apache.REEF.Utilities.Logging;
using Xunit;

namespace Org.Apache.REEF.Tests.Utility
{
    public class TestExceptions
    {
        private static readonly Logger LOGGER = Logger.GetLogger(typeof(TestExceptions));

        [Fact]
        public void TestThrowCaught()
        {
            string msg = null;
            try
            {
                Exceptions.Throw(new ApplicationException("test"), LOGGER);
                msg = "not supposed to reach here";
                Assert.True(false, msg);
            }
            catch (ApplicationException e)
            {
                Exceptions.Caught(e, Level.Info, LOGGER);
            }
            Assert.Null(msg);
        }
    }
}


text:
package goldi_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"fmt"
	"github.com/fgrosse/goldi"
)

var _ = Describe("TypeConfigurator", func() {
	var container *goldi.Container

	BeforeEach(func() {
		container = goldi.NewContainer(goldi.NewTypeRegistry(), map[string]interface{}{})
	})

	Describe("Configure", func() {
		Context("when the type configurator has not been defined correctly", func() {
			It("should return an error", func() {
				someType := new(Foo)
				configurator := goldi.NewTypeConfigurator("configurator", "Configure")
				Expect(configurator.Configure(someType, container)).To(MatchError(`the configurator type "@configurator" has not been defined`))
			})
		})

		Context("when the type configurator is no struct or pointer to struct", func() {
			It("should return an error", func() {
				container.InjectInstance("configurator", 42)
				someType := new(Foo)
				configurator := goldi.NewTypeConfigurator("configurator", "Configure")
				Expect(configurator.Configure(someType, container)).To(MatchError("the configurator instance is no struct or pointer to struct but a int"))
			})
		})

		Context("when the type configurator method does not exist", func() {
			It("should return an error", func() {
				someType := new(Foo)
				configurator := goldi.NewTypeConfigurator("configurator", "Fooobar")
				container.Register("configurator", goldi.NewInstanceType(&MyConfigurator{}))

				Expect(configurator.Configure(someType, container)).To(MatchError(`the configurator does not have a method "Fooobar"`))
			})
		})

		Context("when the type configurator has been defined properly", func() {
			var configurator *MyConfigurator
			BeforeEach(func() {
				configurator = &MyConfigurator{ConfiguredValue: "success!"}
				container.Register("configurator", goldi.NewInstanceType(configurator))
			})

			It("should return an error if the first argument is nil", func() {
				configuratorType := goldi.NewTypeConfigurator("configurator", "Configure")
				Expect(configuratorType.Configure(nil, container)).To(MatchError("can not configure nil"))
			})

			It("should call the requested function on the configurator", func() {
				someType := new(Foo)
				configuratorType := goldi.NewTypeConfigurator("configurator", "Configure")

				Expect(someType.Value).NotTo(Equal("success!"))
				Expect(configuratorType.Configure(someType, container)).To(Succeed())
				Expect(someType.Value).To(Equal("success!"))
			})

			It("should return an error if the configurator returned an error", func() {
				configurator.ReturnError = true

				someType := new(Foo)
				configuratorType := goldi.NewTypeConfigurator("configurator", "Configure")

				Expect(configuratorType.Configure(someType, container)).To(MatchError("this is the error message from the tests.MockTypeConfigurator"))
			})

			It("should return nil if the configurator returned nil", func() {
				configurator.ReturnError = false

				someType := new(Foo)
				configuratorType := goldi.NewTypeConfigurator("configurator", "Configure")

				Expect(configuratorType.Configure(someType, container)).To(BeNil())
			})
		})
	})
})

type MyConfigurator struct {
	ConfiguredValue string
	ReturnError     bool
}

func (c *MyConfigurator) Configure(f *Foo) error {
	if c.ReturnError {
		return fmt.Errorf("this is the error message from the tests.MockTypeConfigurator")
	}

	f.Value = c.ConfiguredValue
	return nil
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

Open console to view results


text:
CREATE DATABASE twitter;

#2 connect db
\c twitter

#3 create tables

CREATE TABLE users (id SERIAL PRIMARY KEY,
  name varchar(255), password varchar(255),
  email varchar(255));

CREATE TABLE tweets (id SERIAL PRIMARY KEY,
  user_id integer, tweet varchar(140));


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="vertical"
    tools:ignore="ResourceName">

    <uk.co.senab.photoview.PhotoView
        android:id="@+id/iv_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>


text:
package picard.util;

import htsjdk.samtools.util.Interval;
import htsjdk.samtools.util.IntervalList;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author mccowan
 */
public class IntervalListScatterer {

    public enum Mode {
        /**
         * A simple scatter approach in which all output intervals have size equal to the total base count of the source list divide by the
         * scatter count (except for possible variance in the final interval list).
         */
        INTERVAL_SUBDIVISION,
        /**
         * A scatter approach that differs from {@link Mode#INTERVAL_SUBDIVISION} in a few ways.
         *

         *
No interval will be subdivided, and consequently, the requested scatter count is an upper bound of scatter count, not a
         * guarantee as to how many {@link IntervalList}s will be produced (e.g., if scatterCount = 10 but there is only one input interval,
         * only 1 interval list will be emitted).

         *
When an interval would otherwise be split, it is instead deferred to the next scatter list.

         *
The "target width" of each scatter list may be wider than what is computed for {@link Mode#INTERVAL_SUBDIVISION}.
         * Specifically, if the widest interval in the source interval list is larger than what would otherwise be the target width, that
         * interval's width is used.

The reasoning for this is that this approach produces more consistently-sized interval lists,
         * which is one of the objectives of scattering.

         *

         */
        BALANCING_WITHOUT_INTERVAL_SUBDIVISION,
        /**
         * A scatter approach that differs from {@link Mode#BALANCING_WITHOUT_INTERVAL_SUBDIVISION}.
         *

         *
We try to balance the number of unique bases in each interval list by estimating the remaining interval lists sizes.  This is
         * computed from the total number of unique bases and the bases we have consumed.  This means that the interval list with the most
         * number of unique bases is at most the ideal split length larger than the smallest interval list (unique # of bases).

         *

         */
        BALANCING_WITHOUT_INTERVAL_SUBDIVISION_WITH_OVERFLOW
    }

    private final Mode mode;

    public IntervalListScatterer(final Mode mode) {this.mode = mode;}

    private int deduceIdealSplitLength(final IntervalList uniquedList, final int scatterCount) {
        final int splitWidth = Math.max((int) Math.floor(uniquedList.getBaseCount() / (1.0 * scatterCount)), 1);
        switch (mode) {
            case INTERVAL_SUBDIVISION:
                return splitWidth;
            case BALANCING_WITHOUT_INTERVAL_SUBDIVISION:
            case BALANCING_WITHOUT_INTERVAL_SUBDIVISION_WITH_OVERFLOW:
                final int widestIntervalLength = Collections.max(uniquedList.getIntervals(), new Comparator<Interval>() {
                    @Override
                    public int compare(final Interval o1, final Interval o2) {
                        return Integer.valueOf(o1.length()).compareTo(o2.length());
                    }
                }).length();

                // There is no purpose to splitting more granularly than the widest interval, so do not.
                return Math.max(widestIntervalLength, splitWidth);
            default:
                throw new IllegalStateException();
        }
    }

    public List<IntervalList> scatter(final IntervalList uniquedIntervalList, final int scatterCount) {
        return scatter(uniquedIntervalList, scatterCount, false);
    }

    /** Helper for the scatter method */
    private boolean shouldAddToRunningIntervalList(final long idealSplitLength, final long projectedSize, final double projectedSizeOfRemainingDivisions) {
        switch (mode) {
            case BALANCING_WITHOUT_INTERVAL_SUBDIVISION_WITH_OVERFLOW:
                return (projectedSize <= idealSplitLength || idealSplitLength < projectedSizeOfRemainingDivisions);
            default:
                return (projectedSize <= idealSplitLength);
        }
    }

    public List<IntervalList> scatter(final IntervalList sourceIntervalList, final int scatterCount, final boolean isUniqued) {
        if (scatterCount < 1) throw new IllegalArgumentException("scatterCount < 1");

        final IntervalList uniquedList = isUniqued ? sourceIntervalList : sourceIntervalList.uniqued();
        final long idealSplitLength = deduceIdealSplitLength(uniquedList, scatterCount);
        System.err.println("idealSplitLength=" + idealSplitLength);

        final List<IntervalList> accumulatedIntervalLists = new ArrayList<IntervalList>();

        IntervalList runningIntervalList = new IntervalList(uniquedList.getHeader());
        final ArrayDeque<Interval> intervalQueue = new ArrayDeque<Interval>(uniquedList.getIntervals());

        long numBasesLeft = uniquedList.getBaseCount();

        while (!intervalQueue.isEmpty() && accumulatedIntervalLists.size() < scatterCount - 1) {
            final Interval interval = intervalQueue.pollFirst();
            final long projectedSize = runningIntervalList.getBaseCount() + interval.length();

            // The mean expected size of the remaining divisions
            // NOTE: that this looks like double counting but isn't, we subtract here the bases that are in the _current_ running intervalList,
            // and when we create a new intervalList (below) we modify numBasesLeft.
            // Another Note: the -1 in the denominator is for "runningIntervalList" that isn't yet counted in  accumulatedIntervalLists.size()
            final double projectedSizeOfRemainingDivisions = (numBasesLeft - runningIntervalList.getBaseCount()) / ((double)(scatterCount - accumulatedIntervalLists.size() - 1));

            // should we add this interval to the list of running intervals?
            if (shouldAddToRunningIntervalList(idealSplitLength, projectedSize, projectedSizeOfRemainingDivisions)) {
                runningIntervalList.add(interval);
            }
            else {
                switch (mode) {
                    case INTERVAL_SUBDIVISION:
                        final int amountToConsume = (int) (idealSplitLength - runningIntervalList.getBaseCount());
                        final Interval left = new Interval(
                                interval.getContig(),
                                interval.getStart(),
                                interval.getStart() + amountToConsume - 1,
                                interval.isNegativeStrand(),
                                interval.getName()
                        );
                        final Interval right = new Interval(
                                interval.getContig(),
                                interval.getStart() + amountToConsume,
                                interval.getEnd(),
                                interval.isNegativeStrand(),
                                interval.getName()
                        );
                        runningIntervalList.add(left);

                        // Push back the excess back onto our queue for reconsideration.
                        intervalQueue.addFirst(right);
                        break;

                    case BALANCING_WITHOUT_INTERVAL_SUBDIVISION:
                    case BALANCING_WITHOUT_INTERVAL_SUBDIVISION_WITH_OVERFLOW:
                        if (runningIntervalList.getIntervals().isEmpty()) {
                            runningIntervalList.add(interval);
                        } else {
                            // Push this interval into the next scatter; re-inject it into the queue, then advance the scatter.
                            intervalQueue.addFirst(interval);
                            numBasesLeft -= runningIntervalList.getBaseCount();
                            accumulatedIntervalLists.add(runningIntervalList.uniqued());
                            runningIntervalList = new IntervalList(uniquedList.getHeader());
                        }
                        break;
                }
            }

            if (runningIntervalList.getBaseCount() >= idealSplitLength) {
                numBasesLeft -= runningIntervalList.getBaseCount(); // keep track of the number of *unique* bases left
                accumulatedIntervalLists.add(runningIntervalList.uniqued());
                runningIntervalList = new IntervalList(uniquedList.getHeader());
            }
        }

        // Flush the remaining intervals into the last split.
        while (!intervalQueue.isEmpty()) {
            runningIntervalList.add(intervalQueue.pollFirst());
        }
        if (!runningIntervalList.getIntervals().isEmpty()) {
            accumulatedIntervalLists.add(runningIntervalList.uniqued());
        }

        long maximumIntervalSize = -1, minimumIntervalSize = Integer.MAX_VALUE;
        for (final IntervalList intervalList : accumulatedIntervalLists) {
            final long baseCount = intervalList.getBaseCount();
            if (baseCount < minimumIntervalSize) minimumIntervalSize = baseCount;
            if (maximumIntervalSize < baseCount) maximumIntervalSize = baseCount;
        }

        return accumulatedIntervalLists;
    }
}


text:
package org.perfcake.pc4idea.impl.run.execution;

import com.intellij.icons.AllIcons;

import javax.swing.*;
import java.awt.*;

/**
 * Created by miron on 21. 12. 2014. This swing component is shown in console window, when running scenario.
 * It is adding toolbar for scenario stopping button.
 */
public class ConsoleContentWrapper extends JPanel {

    private JComponent consoleContent;
    private MyToolbar toolbar;

    public ConsoleContentWrapper(JComponent consoleContent) {
        super(new BorderLayout());
        this.consoleContent = consoleContent;
        toolbar = new MyToolbar();

        add(consoleContent, BorderLayout.CENTER);
        add(toolbar, BorderLayout.WEST);
    }

    public JComponent getConsoleContent() {
        return consoleContent;
    }

    public MyToolbar getToolbar() {
        return toolbar;
    }

    public class MyToolbar extends JToolBar {
        private JButton stopButton;

        public MyToolbar() {
            super(JToolBar.VERTICAL);
            setFloatable(false);
            setRollover(true);

            stopButton = new JButton(AllIcons.Actions.Suspend);
            add(stopButton);
        }

        public JButton getStopButton() {
            return stopButton;
        }
    }
}


text:
sap.ui.define(["sap/ui/test/Opa5","./Common"], function(Opa5,Common){
	"use strict";

	Opa5.createPageObjects({
		onPage1 : {
			baseClass : Common,

			assertions : {
				iShouldSeeThePage1Text : function () {
					//I can call some utility functionality from my common page object, serving as base class
					return this.iShouldSeeTheText("text1","This is Page 1");
				}
			}
		}
	});

});


text:
<!DOCTYPE html>

<link rel="stylesheet" type= 'text/css' href="gps1-2.css">
<title>Title Here</title>

GPS Website

 Mike Henkelman & Jeff Greer

 GPS Topics

Pair programming is concept of having two individuals working on the same code or coding project with one as the driver, and one as the navigator. Pair programming emphasises the concept of pair programming and collaboration.

Pair programming is important for several reasons when it comes to DBC. First and foremost getting a second set of eyes and a new brain to look over what you are working on. It also gets you into the practice of working with others when collaborting on programs or projects.

The driver is the main person that is doing the actual typing at that particular moment and examining the current line of code being input. The navigator


text:
package myDrawTraingle;

import javax.swing.JOptionPane;

public class DrawTriagngle {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int ManyStars = Integer.parseInt(JOptionPane.showInputDialog("How High U WANT"));
		char chara = JOptionPane.showInputDialog("CHARACHTER").charAt(0);
		String output = "";
		int spacesize =0;
		for (int loop1=ManyStars;loop1>=1;loop1--)
		{
			for (int spaces=1;spaces<=spacesize;spaces++)
			{
				output+="  ";
			}
			spacesize++;
			for (int loop2=1;loop2<=loop1;loop2++)
			{
				output+=chara;
			}
			output+="\n";
		}

		JOptionPane.showMessageDialog(null, output);

	}

}


text:
module LockJar
  # still the version
  VERSION = '0.15.2'.freeze
end


text:
import {resolve} from "path";
import rc from "rc";

export default async function(opts) {
	const {basedir=process.cwd()} = opts;
	const pkgfile = resolve(basedir, "package.json");
	const pkg = require(pkgfile);

	return rc("autorelease", {}, {
		...pkg.autorelease,
		...opts,
		basedir,
		package: pkg,
		packageFile: pkgfile
	});
}


text:
package info.mornlight.gw2s.android.app;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import butterknife.InjectView;
import info.mornlight.gw2s.android.R;
import info.mornlight.gw2s.android.model.*;
import info.mornlight.gw2s.android.model.wvw.WvwMap;
import info.mornlight.gw2s.android.model.wvw.WvwMapType;
import info.mornlight.gw2s.android.model.wvw.WvwMatchDetails;
import info.mornlight.gw2s.android.model.wvw.WvwObjective;
import info.mornlight.gw2s.android.ui.*;

import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class WvwDetailsFragment extends RefreshableFragment<WvwMatchDetails, View> {
    private String matchId;
    private int redWorldId;
    private int blueWorldId;
    private int greenWorldId;

    private Timer autoUpdateTimer;

    private static final int RED = 0;
    private static final int BLUE = 1;
    private static final int GREEN = 2;

    @InjectView(R.id.score_bar_red)
    protected TextView scoreBarRed;
    @InjectView(R.id.score_bar_blue)
    protected TextView scoreBarBlue;
    @InjectView(R.id.score_bar_green)
    protected TextView scoreBarGreen;
    @InjectView(R.id.red_world)
    protected TextView redWorld;
    @InjectView(R.id.blue_world)
    protected TextView blueWorld;
    @InjectView(R.id.green_world)
    protected TextView greenWorld;
    @InjectView(R.id.score_red)
    protected TextView scoreRed;
    @InjectView(R.id.score_blue)
    protected TextView scoreBlue;
    @InjectView(R.id.score_green)
    protected TextView scoreGreen;
    @InjectView(R.id.maps)
    protected ExpandableListView maps;

    public void update(String matchId, int redWorldId, int blueWorldId, int greenWorldId) {
        this.matchId = matchId;
        this.redWorldId = redWorldId;
        this.blueWorldId = blueWorldId;
        this.greenWorldId = greenWorldId;
    }

    @Override
    protected View onCreateContentView(LayoutInflater inflater, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.wvw_details_fragment, null);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        boolean autoUpdate = prefs.getBoolean(Prefs.WVW_AUTO_UPDATE, false);
        if(autoUpdate) {
            int updateInterval = prefs.getInt(Prefs.WVW_AUTO_UPDATE_INTERVAL, 30) * 1000;
            autoUpdateTimer = new Timer();
            autoUpdateTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            refresh();
                        }
                    });
                }
            }, updateInterval, updateInterval);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if(autoUpdateTimer != null) {
            autoUpdateTimer.cancel();
            autoUpdateTimer = null;
        }
    }

    @Override
    public Loader<WvwMatchDetails> onCreateLoader(int i, Bundle bundle) {
        return new ThrowableLoader<WvwMatchDetails>(getActivity(), null) {
            @Override
            public WvwMatchDetails loadData() throws Exception {
                if(matchId == null)
                    return null;

                App.instance().ensureWorldNames();
                App.instance().ensureObjectiveNames();

                return App.instance().getClient().readWvwMatchDetails(matchId);
            }
        };
    }

    @Override
    protected void onLoadSucceed(Loader<WvwMatchDetails> loader, WvwMatchDetails data) {
        this.data = data;

        updateView();
    }
    private void updateView() {
        scoreBarRed.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, data.getScores().get(RED) / 10));
        scoreBarBlue.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, data.getScores().get(BLUE) / 10));
        scoreBarGreen.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, data.getScores().get(GREEN) / 10));

        Map<Integer, IntName> worldNames = App.instance().getWorldNames();
        redWorld.setText(worldNames.get(redWorldId).getName());
        blueWorld.setText(worldNames.get(blueWorldId).getName());
        greenWorld.setText(worldNames.get(greenWorldId).getName());

        scoreRed.setText(Integer.toString(data.getScores().get(RED)));
        scoreBlue.setText(Integer.toString(data.getScores().get(BLUE)));
        scoreGreen.setText(Integer.toString(data.getScores().get(GREEN)));

        updateMapsList();
    }

    class WvwMapAdapter extends BaseExpandableListAdapter {
        List<WvwMap> maps;
        LayoutInflater inflater;

        WvwMapAdapter(LayoutInflater inflater, List<WvwMap> maps) {
            this.maps = maps;
            this.inflater = inflater;
        }

        @Override
        public int getGroupCount() {
            return maps.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return maps.get(groupPosition).getObjectives().size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return maps.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return maps.get(groupPosition).getObjectives().get(childPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition * 100;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return groupPosition * 100 + childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            MapItemView v = convertView != null ? (MapItemView) convertView.getTag() : null;
            if(v == null) {
                convertView = inflater.inflate(R.layout.wvw_details_map_item, null);
                v = new MapItemView(convertView);
                convertView.setTag(v);
            }

            v.update((WvwMap) getGroup(groupPosition));
            return convertView;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            ObjectiveItemView v = convertView != null ? (ObjectiveItemView) convertView.getTag() : null;
            if(v == null) {
                convertView = inflater.inflate(R.layout.wvw_details_objective_item, null);
                v = new ObjectiveItemView(convertView);
                convertView.setTag(v);
            }

            v.update((WvwObjective) getChild(groupPosition, childPosition));
            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return false;
        }

        public void update(List<WvwMap> maps) {
            this.maps = maps;
        }
    }

    class ObjectiveItemView extends ItemView<WvwObjective> {
        private TextView name;
        private TextView owner;
        //private TextView ownerGuild;

        public ObjectiveItemView(View view) {
            super(view);

            name = (TextView) view.findViewById(R.id.name);
            owner = (TextView) view.findViewById(R.id.owner);
            //ownerGuild = (TextView) view.findViewById(R.id.owner_guild);
        }

        @Override
        public void update(WvwObjective item) {
            super.update(item);
            Map<Integer, IntName> objectiveNames = App.instance().getObjectiveNames();

            name.setText(objectiveNames.get(item.getId()).getName());
            owner.setText(item.getOwner().toString());

            int color = R.color.world_red;
            switch (item.getOwner()) {
                case Red:
                    color = R.color.world_red;
                    break;
                case Blue:
                    color = R.color.world_blue;
                    break;
                case Green:
                    color = R.color.world_green;
                    break;
                default:
                    color = R.color.world_neutral;
                    break;
            }
            owner.setTextColor(getResources().getColor(color));
            //ownerGuild
        }
    }
    class MapItemView extends ItemView<WvwMap> {
        private TextView name;
        private TextView objectiveNum;
        private TextView scoreRed;
        private TextView scoreBlue;
        private TextView scoreGreen;

        public MapItemView(View view) {
            super(view);

            name = (TextView) view.findViewById(R.id.name);
            objectiveNum = (TextView) view.findViewById(R.id.objective_num);
            scoreRed = (TextView) view.findViewById(R.id.score_red);
            scoreBlue = (TextView) view.findViewById(R.id.score_blue);
            scoreGreen = (TextView) view.findViewById(R.id.score_green);
        }

        @Override
        public void update(WvwMap item) {
            super.update(item);

            name.setText(getMapName(item.getType()));
            objectiveNum.setText("(" + item.getObjectives().size() + ")");
            scoreRed.setText(Integer.toString(item.getScores().get(RED)));
            scoreBlue.setText(Integer.toString(item.getScores().get(BLUE)));
            scoreGreen.setText(Integer.toString(item.getScores().get(GREEN)));
        }

        private String getMapName(WvwMapType type) {
            switch(type) {
                case RedHome: return getResources().getString(R.string.red_home);
                case BlueHome: return getResources().getString(R.string.blue_home);
                case GreenHome: return getResources().getString(R.string.green_home);
                case Center: return getResources().getString(R.string.center);
                default: return "";
            }
        }
    }

    private void updateMapsList() {
        if(maps.getExpandableListAdapter() == null) {
            WvwMapAdapter adapter = new WvwMapAdapter(getActivity().getLayoutInflater(), data.getMaps());
            maps.setAdapter(adapter);
        } else {
            WvwMapAdapter adapter = (WvwMapAdapter) maps.getExpandableListAdapter();
            adapter.update(data.getMaps());
            adapter.notifyDataSetChanged();
        }
    }
}