text:
from __future__ import print_function
import base64
import hashlib
import json
import logging
import os
import passlib.utils as passutils
import six
import struct
import subprocess
import time

from heatclient.common import event_utils
from heatclient.exc import HTTPNotFound
from openstackclient.i18n import _

from tripleoclient import exceptions

_MIN_PASSWORD_SIZE = 25
_PASSWORD_NAMES = (
    "OVERCLOUD_ADMIN_PASSWORD",
    "OVERCLOUD_ADMIN_TOKEN",
    "OVERCLOUD_CEILOMETER_PASSWORD",
    "OVERCLOUD_CEILOMETER_SECRET",
    "OVERCLOUD_CINDER_PASSWORD",
    "OVERCLOUD_DEMO_PASSWORD",
    "OVERCLOUD_GLANCE_PASSWORD",
    "OVERCLOUD_HAPROXY_STATS_PASSWORD",
    "OVERCLOUD_HEAT_PASSWORD",
    "OVERCLOUD_HEAT_STACK_DOMAIN_PASSWORD",
    "OVERCLOUD_NEUTRON_PASSWORD",
    "OVERCLOUD_NOVA_PASSWORD",
    "OVERCLOUD_RABBITMQ_PASSWORD",
    "OVERCLOUD_REDIS_PASSWORD",
    "OVERCLOUD_SAHARA_PASSWORD",
    "OVERCLOUD_SWIFT_HASH",
    "OVERCLOUD_SWIFT_PASSWORD",
    "NEUTRON_METADATA_PROXY_SHARED_SECRET",
)

def generate_overcloud_passwords(output_file="tripleo-overcloud-passwords"):
    """Create the passwords needed for the overcloud

    This will create the set of passwords required by the overcloud, store
    them in the output file path and return a dictionary of passwords. If the
    file already exists the existing passwords will be returned instead,
    """

    passwords = {}
    if os.path.isfile(output_file):
        with open(output_file) as f:
            passwords = dict(line.split('=') for line in f.read().splitlines())

    for name in _PASSWORD_NAMES:
        if not passwords.get(name):
            passwords[name] = passutils.generate_password(
                size=_MIN_PASSWORD_SIZE)

    with open(output_file, 'w') as f:
        for name, password in passwords.items():
            f.write("{0}={1}\n".format(name, password))

    return passwords

def check_hypervisor_stats(compute_client, nodes=1, memory=0, vcpu=0):
    """Check the Hypervisor stats meet a minimum value

    Check the hypervisor stats match the required counts. This is an
    implementation of a command in TripleO with the same name.

    :param compute_client: Instance of Nova client
    :type  compute_client: novaclient.client.v2.Client

    :param nodes: The number of nodes to wait for, defaults to 1.
    :type  nodes: int

    :param memory: The amount of memory to wait for in MB, defaults to 0.
    :type  memory: int

    :param vcpu: The number of vcpus to wait for, defaults to 0.
    :type  vcpu: int
    """

    statistics = compute_client.hypervisors.statistics().to_dict()

    if all([statistics['count'] >= nodes,
            statistics['memory_mb'] >= memory,
            statistics['vcpus'] >= vcpu]):
        return statistics
    else:
        return None

def wait_for_stack_ready(orchestration_client, stack_name, marker=None,
                         action='CREATE', verbose=False):
    """Check the status of an orchestration stack

    Get the status of an orchestration stack and check whether it is complete
    or failed.

    :param orchestration_client: Instance of Orchestration client
    :type  orchestration_client: heatclient.v1.client.Client

    :param stack_name: Name or UUID of stack to retrieve
    :type  stack_name: string

    :param marker: UUID of the last stack event before the current action
    :type  marker: string

    :param action: Current action to check the stack for COMPLETE
    :type action: string

    :param verbose: Whether to print events
    :type verbose: boolean
    """
    stack = get_stack(orchestration_client, stack_name)
    if not stack:
        return False
    stack_name = stack.stack_name

    while True:

        events = event_utils.get_events(orchestration_client,
                                        stack_id=stack_name, nested_depth=2,
                                        event_args={'sort_dir': 'asc',
                                                    'marker': marker})

        if len(events) >= 1:
            # set marker to last event that was received.
            marker = getattr(events[-1], 'id', None)

            if verbose:
                events_log = event_log_formatter(events)
                print(events_log)

        stack = get_stack(orchestration_client, stack_name)
        stack_status = stack.stack_status
        if stack_status == '%s_COMPLETE' % action:
            print("Stack %(name)s %(status)s" % dict(
                name=stack_name, status=stack_status))
            return True
        elif stack_status == '%s_FAILED' % action:
            print("Stack %(name)s %(status)s" % dict(
                name=stack_name, status=stack_status))
            return False

        time.sleep(5)

def event_log_formatter(events):
    """Return the events in log format."""
    event_log = []
    log_format = ("%(event_time)s "
                  "[%(rsrc_name)s]: %(rsrc_status)s  %(rsrc_status_reason)s")
    for event in events:
        event_time = getattr(event, 'event_time', '')
        log = log_format % {
            'event_time': event_time.replace('T', ' '),
            'rsrc_name': getattr(event, 'resource_name', ''),
            'rsrc_status': getattr(event, 'resource_status', ''),
            'rsrc_status_reason': getattr(event, 'resource_status_reason', '')
        }
        event_log.append(log)

    return "\n".join(event_log)

def nodes_in_states(baremetal_client, states):
    """List the introspectable nodes with the right provision_states."""
    nodes = baremetal_client.node.list(maintenance=False, associated=False)
    return [node for node in nodes if node.provision_state in states]

def wait_for_provision_state(baremetal_client, node_uuid, provision_state,
                             loops=10, sleep=1):
    """Wait for a given Provisioning state in Ironic

    Updating the provisioning state is an async operation, we
    need to wait for it to be completed.

    :param baremetal_client: Instance of Ironic client
    :type  baremetal_client: ironicclient.v1.client.Client

    :param node_uuid: The Ironic node UUID
    :type  node_uuid: str

    :param provision_state: The provisioning state name to wait for
    :type  provision_state: str

    :param loops: How many times to loop
    :type loops: int

    :param sleep: How long to sleep between loops
    :type sleep: int

    :raises exceptions.StateTransitionFailed: if node.last_error is set
    """

    for _l in range(0, loops):

        node = baremetal_client.node.get(node_uuid)

        if node is None:
            # The node can't be found in ironic, so we don't need to wait for
            # the provision state
            return
        if node.provision_state == provision_state:
            return

        # node.last_error should be None after any successful operation
        if node.last_error:
            raise exceptions.StateTransitionFailed(
                "Error transitioning node %(uuid)s to provision state "
                "%(state)s: %(error)s. Now in state %(actual)s." % {
                    'uuid': node_uuid,
                    'state': provision_state,
                    'error': node.last_error,
                    'actual': node.provision_state
                }
            )

        time.sleep(sleep)

    raise exceptions.Timeout(
        "Node %(uuid)s did not reach provision state %(state)s. "
        "Now in state %(actual)s." % {
            'uuid': node_uuid,
            'state': provision_state,
            'actual': node.provision_state
        }
    )

def wait_for_node_introspection(inspector_client, auth_token, inspector_url,
                                node_uuids, loops=220, sleep=10):
    """Check the status of Node introspection in Ironic inspector

    Gets the status and waits for them to complete.

    :param inspector_client: Ironic inspector client
    :type  inspector_client: ironic_inspector_client

    :param node_uuids: List of Node UUID's to wait for introspection
    :type node_uuids: [string, ]

    :param loops: How many times to loop
    :type loops: int

    :param sleep: How long to sleep between loops
    :type sleep: int
    """

    log = logging.getLogger(__name__ + ".wait_for_node_introspection")
    node_uuids = node_uuids[:]

    for _l in range(0, loops):

        for node_uuid in node_uuids:
            status = inspector_client.get_status(
                node_uuid,
                base_url=inspector_url,
                auth_token=auth_token)

            if status['finished']:
                log.debug("Introspection finished for node {0} "
                          "(Error: {1})".format(node_uuid, status['error']))
                node_uuids.remove(node_uuid)
                yield node_uuid, status

        if not len(node_uuids):
            raise StopIteration
        time.sleep(sleep)

    if len(node_uuids):
        log.error("Introspection didn't finish for nodes {0}".format(
            ','.join(node_uuids)))

def create_environment_file(path="~/overcloud-env.json",
                            control_scale=1, compute_scale=1,
                            ceph_storage_scale=0, block_storage_scale=0,
                            swift_storage_scale=0):
    """Create a heat environment file

    Create the heat environment file with the scale parameters.

    :param control_scale: Scale value for control roles.
    :type control_scale: int

    :param compute_scale: Scale value for compute roles.
    :type compute_scale: int

    :param ceph_storage_scale: Scale value for ceph storage roles.
    :type ceph_storage_scale: int

    :param block_storage_scale: Scale value for block storage roles.
    :type block_storage_scale: int

    :param swift_storage_scale: Scale value for swift storage roles.
    :type swift_storage_scale: int
    """

    env_path = os.path.expanduser(path)
    with open(env_path, 'w+') as f:
        f.write(json.dumps({
            "parameter_defaults": {
                "ControllerCount": control_scale,
                "ComputeCount": compute_scale,
                "CephStorageCount": ceph_storage_scale,
                "BlockStorageCount": block_storage_scale,
                "ObjectStorageCount": swift_storage_scale}
        }))

    return env_path

def set_nodes_state(baremetal_client, nodes, transition, target_state,
                    skipped_states=()):
    """Make all nodes available in the baremetal service for a deployment

    For each node, make it available unless it is already available or active.
    Available nodes can be used for a deployment and an active node is already
    in use.

    :param baremetal_client: Instance of Ironic client
    :type  baremetal_client: ironicclient.v1.client.Client

    :param nodes: List of Baremetal Nodes
    :type  nodes: [ironicclient.v1.node.Node]

    :param transition: The state to set for a node. The full list of states
                       can be found in ironic.common.states.
    :type  transition: string

    :param target_state: The expected result state for a node. For example when
                         transitioning to 'manage' the result is 'manageable'
    :type  target_state: string

    :param skipped_states: A set of states to skip, for example 'active' nodes
                           are already deployed and the state can't always be
                           changed.
    :type  skipped_states: iterable of strings

    :param error_states: Node states treated as error for this transition
    :type error_states: collection of strings

    :param error_message: Optional message to append to an error message
    :param error_message: str

    :raises exceptions.StateTransitionFailed: if a node enters any of the
                                              states in error_states

    :raises exceptions.Timeout: if a node takes too long to reach target state
    """

    log = logging.getLogger(__name__ + ".set_nodes_state")

    for node in nodes:

        if node.provision_state in skipped_states:
            continue

        log.debug(
            "Setting provision state from {0} to '{1} for Node {2}"
            .format(node.provision_state, transition, node.uuid))

        baremetal_client.node.set_provision_state(node.uuid, transition)
        try:
            wait_for_provision_state(baremetal_client, node.uuid, target_state)
        except exceptions.StateTransitionFailed as e:
            log.error("FAIL: State transition failed for Node {0}. {1}"
                      .format(node.uuid, e))
        except exceptions.Timeout as e:
            log.error("FAIL: Timeout waiting for Node {0}. {1}"
                      .format(node.uuid, e))
        yield node.uuid

def get_hiera_key(key_name):
    """Retrieve a key from the hiera store

    :param password_name: Name of the key to retrieve
    :type  password_name: type

    """
    command = ["hiera", key_name]
    p = subprocess.Popen(command, stdout=subprocess.PIPE)
    out, err = p.communicate()
    return out

def get_config_value(section, option):

    p = six.moves.configparser.ConfigParser()
    p.read(os.path.expanduser("~/undercloud-passwords.conf"))
    return p.get(section, option)

def get_overcloud_endpoint(stack):
    for output in stack.to_dict().get('outputs', {}):
        if output['output_key'] == 'KeystoneURL':
            return output['output_value']

def get_service_ips(stack):
    service_ips = {}
    for output in stack.to_dict().get('outputs', {}):
        service_ips[output['output_key']] = output['output_value']
    return service_ips

__password_cache = None

def get_password(pass_name):
    """Retrieve a password by name, such as 'OVERCLOUD_ADMIN_PASSWORD'.

    Raises KeyError if password does not exist.
    """
    global __password_cache
    if __password_cache is None:
        __password_cache = generate_overcloud_passwords()
    return __password_cache[pass_name]

def get_stack(orchestration_client, stack_name):
    """Get the ID for the current deployed overcloud stack if it exists.

    Caller is responsible for checking if return is None
    """

    try:
        stack = orchestration_client.stacks.get(stack_name)
        return stack
    except HTTPNotFound:
        pass

def remove_known_hosts(overcloud_ip):
    """For a given IP address remove SSH keys from the known_hosts file"""

    known_hosts = os.path.expanduser("~/.ssh/known_hosts")

    if os.path.exists(known_hosts):
        command = ['ssh-keygen', '-R', overcloud_ip, '-f', known_hosts]
        subprocess.check_call(command)

def create_cephx_key():
    # NOTE(gfidente): Taken from
    # https://github.com/ceph/ceph-deploy/blob/master/ceph_deploy/new.py#L21
    key = os.urandom(16)
    header = struct.pack("<hiih", 1, int(time.time()), 0, len(key))
    return base64.b64encode(header + key)

def run_shell(cmd):
    return subprocess.call([cmd], shell=True)

def all_unique(x):
    """Return True if the collection has no duplications."""
    return len(set(x)) == len(x)

def file_checksum(filepath):
    """Calculate md5 checksum on file

    :param filepath: Full path to file (e.g. /home/stack/image.qcow2)
    :type  filepath: string

    """
    if not os.path.isfile(filepath):
        raise ValueError("The given file {0} is not a regular "
                         "file".format(filepath))
    checksum = hashlib.md5()
    with open(filepath, 'rb') as f:
        while True:
            fragment = f.read(65536)
            if not fragment:
                break
            checksum.update(fragment)
    return checksum.hexdigest()

def check_nodes_count(baremetal_client, stack, parameters, defaults):
    """Check if there are enough available nodes for creating/scaling stack"""
    count = 0
    if stack:
        for param in defaults:
            try:
                current = int(stack.parameters[param])
            except KeyError:
                raise ValueError(
                    "Parameter '%s' was not found in existing stack" % param)
            count += parameters.get(param, current)
    else:
        for param, default in defaults.items():
            count += parameters.get(param, default)

    # We get number of nodes usable for the stack by getting already
    # used (associated) nodes and number of nodes which can be used
    # (not in maintenance mode).
    # Assumption is that associated nodes are part of the stack (only
    # one overcloud is supported).
    associated = len(baremetal_client.node.list(associated=True))
    available = len(baremetal_client.node.list(associated=False,
                                               maintenance=False))
    ironic_nodes_count = associated + available

    if count > ironic_nodes_count:
        raise exceptions.DeploymentError(
            "Not enough nodes - available: {0}, requested: {1}".format(
                ironic_nodes_count, count))
    else:
        return True

def ensure_run_as_normal_user():
    """Check if the command runs under normal user (EUID!=0)"""
    if os.geteuid() == 0:
        raise exceptions.RootUserExecution(
            'This command cannot run under root user.'
            ' Switch to a normal user.')

def capabilities_to_dict(caps):
    """Convert the Node's capabilities into a dictionary."""
    if not caps:
        return {}
    return dict([key.split(':', 1) for key in caps.split(',')])

def dict_to_capabilities(caps_dict):
    """Convert a dictionary into a string with the capabilities syntax."""
    return ','.join(["%s:%s" % (key, value)
                     for key, value in caps_dict.items()
                     if value is not None])

def node_get_capabilities(node):
    """Get node capabilities."""
    return capabilities_to_dict(node.properties.get('capabilities'))

def node_add_capabilities(bm_client, node, **updated):
    """Add or replace capabilities for a node."""
    caps = node_get_capabilities(node)
    caps.update(updated)
    converted_caps = dict_to_capabilities(caps)
    node.properties['capabilities'] = converted_caps
    bm_client.node.update(node.uuid, [{'op': 'add',
                                       'path': '/properties/capabilities',
                                       'value': converted_caps}])
    return caps

def assign_and_verify_profiles(bm_client, flavors,
                               assign_profiles=False, dry_run=False):
    """Assign and verify profiles for given flavors.

    :param bm_client: ironic client instance
    :param flavors: map flavor name -> (flavor object, required count)
    :param assign_profiles: whether to allow assigning profiles to nodes
    :param dry_run: whether to skip applying actual changes (only makes sense
                    if assign_profiles is True)
    :returns: tuple (errors count, warnings count)
    """
    log = logging.getLogger(__name__ + ".assign_and_verify_profiles")
    predeploy_errors = 0
    predeploy_warnings = 0

    # nodes available for deployment and scaling (including active)
    bm_nodes = {node.uuid: node
                for node in bm_client.node.list(maintenance=False,
                                                detail=True)
                if node.provision_state in ('available', 'active')}
    # create a pool of unprocessed nodes and record their capabilities
    free_node_caps = {uu: node_get_capabilities(node)
                      for uu, node in bm_nodes.items()}

    # TODO(dtantsur): use command-line arguments to specify the order in
    # which profiles are processed (might matter for assigning profiles)
    profile_flavor_used = False
    for flavor_name, (flavor, scale) in flavors.items():
        if not scale:
            log.debug("Skipping verification of flavor %s because "
                      "none will be deployed", flavor_name)
            continue

        profile = flavor.get_keys().get('capabilities:profile')
        # If there's only a single flavor, then it's expected for it to have
        # no profile assigned.
        if not profile and len(flavors) > 1:
            predeploy_errors += 1
            log.error(
                'Error: The %s flavor has no profile associated', flavor_name)
            log.error(
                'Recommendation: assign a profile with openstack flavor '
                'set --property "capabilities:profile"="PROFILE_NAME" %s',
                flavor_name)
            continue

        profile_flavor_used = True

        # first collect nodes with known profiles
        assigned_nodes = [uu for uu, caps in free_node_caps.items()
                          if caps.get('profile') == profile]
        required_count = scale - len(assigned_nodes)

        if required_count < 0:
            log.warning('%d nodes with profile %s won\'t be used '
                        'for deployment now', -required_count, profile)
            predeploy_warnings += 1
            required_count = 0
        elif required_count > 0 and assign_profiles:
            # find more nodes by checking XXX_profile capabilities that are
            # set by ironic-inspector or manually
            capability = '%s_profile' % profile
            more_nodes = [
                uu for uu, caps in free_node_caps.items()
                # use only nodes without a know profile
                if not caps.get('profile') and
                caps.get(capability, '').lower() in ('1', 'true') and
                # do not assign profiles for active nodes
                bm_nodes[uu].provision_state == 'available'
            ][:required_count]
            assigned_nodes.extend(more_nodes)
            required_count -= len(more_nodes)

        for uu in assigned_nodes:
            # make sure these nodes are not reused for other profiles
            node_caps = free_node_caps.pop(uu)
            # save profile for newly assigned nodes, but only if we
            # succeeded in finding enough of them
            if not required_count and not node_caps.get('profile'):
                node = bm_nodes[uu]
                if not dry_run:
                    node_add_capabilities(bm_client, node, profile=profile)
                log.info('Node %s was assigned profile %s', uu, profile)
            else:
                log.debug('Node %s has profile %s', uu, profile)

        if required_count > 0:
            log.error(
                "Error: only %s of %s requested ironic nodes are tagged "
                "to profile %s (for flavor %s)",
                scale - required_count, scale, profile, flavor_name
            )
            log.error(
                "Recommendation: tag more nodes using ironic node-update "
                "<NODE ID> replace properties/capabilities=profile:%s,"
                "boot_option:local", profile)
            predeploy_errors += 1

    nodes_without_profile = [uu for uu, caps in free_node_caps.items()
                             if not caps.get('profile')]
    if nodes_without_profile and profile_flavor_used:
        predeploy_warnings += 1
        log.warning(
            "There are %d ironic nodes with no profile that will "
            "not be used: %s", len(nodes_without_profile),
            ', '.join(nodes_without_profile)
        )

    return predeploy_errors, predeploy_warnings

def add_deployment_plan_arguments(parser):
    """Add deployment plan arguments (flavors and scales) to a parser"""
    parser.add_argument('--control-scale', type=int,
                        help=_('New number of control nodes.'))
    parser.add_argument('--compute-scale', type=int,
                        help=_('New number of compute nodes.'))
    parser.add_argument('--ceph-storage-scale', type=int,
                        help=_('New number of ceph storage nodes.'))
    parser.add_argument('--block-storage-scale', type=int,
                        help=_('New number of cinder storage nodes.'))
    parser.add_argument('--swift-storage-scale', type=int,
                        help=_('New number of swift storage nodes.'))
    parser.add_argument('--control-flavor',
                        help=_("Nova flavor to use for control nodes."))
    parser.add_argument('--compute-flavor',
                        help=_("Nova flavor to use for compute nodes."))
    parser.add_argument('--ceph-storage-flavor',
                        help=_("Nova flavor to use for ceph storage "
                               "nodes."))
    parser.add_argument('--block-storage-flavor',
                        help=_("Nova flavor to use for cinder storage "
                               "nodes."))
    parser.add_argument('--swift-storage-flavor',
                        help=_("Nova flavor to use for swift storage "
                               "nodes."))

def get_roles_info(parsed_args):
    """Get flavor name and scale for all deployment roles.

    :returns: dict role name -> (flavor name, scale)
    """
    return {
        'control': (parsed_args.control_flavor, parsed_args.control_scale),
        'compute': (parsed_args.compute_flavor, parsed_args.compute_scale),
        'ceph-storage': (parsed_args.ceph_storage_flavor,
                         parsed_args.ceph_storage_scale),
        'block-storage': (parsed_args.block_storage_flavor,
                          parsed_args.block_storage_scale),
        'swift-storage': (parsed_args.swift_storage_flavor,
                          parsed_args.swift_storage_scale)
    }


text:
/**
* My function
* @param {string} a alpha
* @param {number} b beta
* @returns {string}
*/
module.exports = function(a = 'hi', b = null, context, callback) {};
// valid, all types are nullable

redpajama_set_name: RedPajamaGithub


text:
exports.ports = {
	public: [8000, 'localhost'],
	private: [11998, 'localhost']
};

// === {{{ cookie }}} ===
//
// Define the cookie name and how long a session will be stored on the server.
// If you change the cookie name here, you will also need to change it in the
// PHP login script/configuration; if you fail to do this, the Node.js server
// will be looking for a cookie that does not exist.
//
// **Note:** The period for the session should be as long or longer than the
// cookie itself is set to be stored. If it is less, the user won't be logged
// back in automatically, as their cookie will have been deleted.
exports.cookie = {
	name: 'ajaxim_session',
	period: 8760
};


text:
<?xml version='1.0' encoding='UTF-8'?>

<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.apache.aries</groupId>
        <artifactId>java5-parent</artifactId>
        <version>1.0.0</version>
        <relativePath />
    </parent>

    <artifactId>eba-maven-plugin</artifactId>
    <version>1.0.1-SNAPSHOT</version>
    <packaging>maven-plugin</packaging>

    <name>Aries Maven EBA Plugin</name>
    <description>Builds an eba (Enterprise Bundle Archive) from the project for deployment to an aries server.
    </description>

    <scm>
        <connection>scm:svn:http://svn.apache.org/repos/asf/aries/trunk/eba-maven-plugin</connection>
        <developerConnection>scm:svn:https://svn.apache.org/repos/asf/aries/trunk/eba-maven-plugin</developerConnection>
        <url>http://svn.apache.org/viewvc/aries/trunk/eba-maven-plugin</url>
    </scm>

    <dependencies>
        <dependency>
            <groupId>biz.aQute</groupId>
            <artifactId>bndlib</artifactId>
            <version>0.0.357</version>
        </dependency>
        <dependency>
            <groupId>org.apache.felix</groupId>
            <artifactId>maven-bundle-plugin</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-plugin-api</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-project</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-artifact</artifactId>
            <version>2.0.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-archiver</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-model</artifactId>
            <version>2.0.7</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.plexus</groupId>
            <artifactId>plexus-archiver</artifactId>
            <version>1.0-alpha-7</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.plexus</groupId>
            <artifactId>plexus-utils</artifactId>
            <version>1.4.7</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.plexus</groupId>
            <artifactId>plexus-container-default</artifactId>
            <version>1.0-alpha-9-stable-1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.shared</groupId>
            <artifactId>maven-plugin-testing-harness</artifactId>
            <version>1.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <profiles>
        <profile>
            <id>run-its</id>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-invoker-plugin</artifactId>
                        <version>1.4</version>
                        <configuration>
                            <debug>true</debug>
                            <projectsDirectory>src/it</projectsDirectory>
                            <cloneProjectsTo>${project.build.directory}/it</cloneProjectsTo>
                            <pomIncludes>
                                <pomInclude>*/pom.xml</pomInclude>
                            </pomIncludes>
                            <preBuildHookScript>setup</preBuildHookScript>
                            <postBuildHookScript>verify</postBuildHookScript>
                            <localRepositoryPath>${project.build.directory}/local-repo</localRepositoryPath>
                            <settingsFile>src/it/settings.xml</settingsFile>
                            <goals>
                                <goal>clean</goal>
                                <goal>package</goal>
                            </goals>
                        </configuration>
                        <executions>
                            <execution>
                                <id>integration-test</id>
                                <goals>
                                    <goal>install</goal>
                                    <goal>run</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>


text:
{-@ LIQUID "--reflection" @-}
{-@ LIQUID "--ple"        @-}

module ReflectClient5 where

-- import Language.Haskell.Liquid.ProofCombinators

import ReflectLib5

{-@ test5 :: { gapp Nil = Nil } @-}
test5 = ()


text:
'use strict';

chrome.app.runtime.onLaunched.addListener(() => {
  chrome.app.window.create('/kernel/kernel.html', {
    bounds: { width: 640, height: 480 }
  });
});


text:
package minus.android.view;

import android.content.Context;
import android.util.Log;

import junit.framework.Assert;

import minus.android.sdk.R;

public final class PointerFactory {

	/** Arrow icon. */
	public static final int ARROW = PointerIcon.STYLE_ARROW;

	/** Spot hover icon for touchable device. */
	public static final int SPOT_HOVER = PointerIcon.STYLE_SPOT_HOVER;

	/** Spot touch icon for touchable device. Default. */
	public static final int SPOT_TOUCH = PointerIcon.STYLE_SPOT_TOUCH;

	/** Spot anchor icon for touchable device. */
	public static final int SPOT_ANCHOR = PointerIcon.STYLE_SPOT_ANCHOR;

	private static final String TAG = PointerFactory.class.getSimpleName();

	private final Context mContext;

	public PointerFactory(Context context) {
		mContext = context;
	}

	public PointerIcon createDefaultPointer() {
		return createPointer(SPOT_TOUCH, true);
	}

	public PointerIcon createPointer(int style, boolean forceCustomStyle) {
		PointerIcon icon = null;
		if (!forceCustomStyle) {
            icon = PointerIcon.getSystemIcon(mContext, style);
			if (!icon.isLoaded()) {
				icon = icon.load(mContext); // not necessarily the same instance, shit!
			}

			try {
				icon.getHotSpotX(); // throwIfIconIsNotLoaded
			} catch (IllegalStateException e) {
				forceCustomStyle = true;
				Log.w(TAG, "the icon is not loaded, force load.");
			}
		}

		if(forceCustomStyle) {
			int resourceId;
			switch (style) {
			case ARROW:
				resourceId = R.xml.pointer_arrow_icon;
				break;
			case SPOT_HOVER:
				resourceId = R.xml.pointer_spot_hover_icon;
				break;
			case SPOT_TOUCH:
                resourceId = R.xml.pointer_spot_touch_icon;
                break;
			case SPOT_ANCHOR:
				resourceId = R.xml.pointer_spot_hover_icon;
				break;
			default:
				resourceId = R.xml.pointer_spot_touch_icon;
				break;
			}
			icon = PointerIcon.loadCustomIcon(mContext.getResources(), resourceId);

			Assert.assertTrue("force custom load also failed", icon.isLoaded());
		}

		return icon;
	}

}


text:
<?php

namespace app\controllers;

use Yii;
use app\models\Packinglists;
use app\models\PackingslistsSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use dektrium\user\filters\AccessRule;

/**
 * PackinglistsController implements the CRUD actions for Packinglists model.
 */
class PackinglistsController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
	        'access' => [
		        'class' => AccessControl::className(),
		        'ruleConfig' => [
			        'class' => AccessRule::className(),
		        ],
		        'rules' => [
			        [
				        'allow' => true,
				        'roles' => ['admin', '@'],
			        ],
		        ],
	        ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Packinglists models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new PackingslistsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Packinglists model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Packinglists model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Packinglists();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Packinglists model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Packinglists model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Packinglists model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Packinglists the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Packinglists::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
package org.xmlactions.pager.drawing.html;

import org.apache.commons.lang.StringUtils;
import org.xmlactions.action.config.IExecContext;
import org.xmlactions.common.theme.Theme;
import org.xmlactions.db.actions.Image;
import org.xmlactions.pager.actions.form.CommonFormFields;
import org.xmlactions.pager.actions.form.Field;
import org.xmlactions.pager.actions.form.templates.Html;
import org.xmlactions.pager.actions.form.templates.HtmlBr;
import org.xmlactions.pager.actions.form.templates.HtmlDiv;
import org.xmlactions.pager.actions.form.templates.HtmlImg;
import org.xmlactions.pager.actions.form.templates.HtmlInput;
import org.xmlactions.pager.actions.form.templates.HtmlTd;
import org.xmlactions.pager.actions.form.templates.HtmlTh;
import org.xmlactions.pager.actions.form.templates.HtmlTr;
import org.xmlactions.pager.drawing.IDrawField;
import org.xmlactions.pager.drawing.IDrawParams;
import org.xmlactions.pager.drawing.html.DrawDBHTMLHelper;
import org.xmlactions.web.Uploader;

public class ImageHtml extends Image implements IDrawField
{

    private Field field;

    public Field getHtmlField() {
        return field;
    }

    public void setHtmlField(Field field) {
        this.field = field;
    }

	public HtmlTr displayForSearch(String value, Theme theme)
	{

		return new HtmlTr(theme);

	}

	public HtmlTr[] displayForAdd(String value, Theme theme)
	{

		HtmlTr[] trs = new HtmlTr[1];
		HtmlTr tr = new HtmlTr(theme);
		trs[0] = tr;
		tr.addChild(displayHeader(theme));
		HtmlTd td = tr.addTd(theme);
		td.addChild(buildAddHtml(value, theme));
		return trs;

	}

	public HtmlTr[] displayForView(CommonFormFields callingAction, String value, Theme theme)
	{
		HtmlTr[] trs = new HtmlTr[1];
		HtmlTr tr = new HtmlTr(theme);
		trs[0] = tr;

		tr.addChild(displayHeader(theme));
		HtmlTd td = tr.addTd(theme);
		td.addChild(buildAddHtml(value, theme));
		return trs;
	}

    public Html displayForList(IExecContext execContext, Field field, String value, Theme theme)
	{
		throw new IllegalArgumentException("check this code");

	}

    public Html displayForList(IDrawParams params, String value, Theme theme)
	{

		HtmlImg img = new HtmlImg();
		img.setSrc(value);
		img.setAlt("No Image");
		if (StringUtils.isNotEmpty(params.getWidth())) {
			img.setWidth(params.getWidth());
		}
		if (StringUtils.isNotEmpty(params.getHeight())) {
			img.setHeight(params.getHeight());
		}
		return img;
	}

	public HtmlTr[] displayForUpdate(String value, Theme theme)
	{

		HtmlTr[] trs = new HtmlTr[1];
		HtmlTr tr = new HtmlTr(theme);
		trs[0] = tr;

		tr.addChild(displayHeader(theme));
		HtmlTd td = tr.addTd(theme);
		td.addChild(buildAddHtml(value, theme));
		return trs;

	}

	public HtmlTh displayHeader(Theme theme)
	{

		HtmlTh th = new HtmlTh(theme);
		String title = "";
		if (!StringUtils.isBlank(getTooltip())) {
			title += getTooltip();
		}
		if (isMandatory()) {
			title += " - This field is mandatory";
		}
		if (!StringUtils.isBlank(getTooltip())) {
			th.setTitle(title);
		}
		th.setContent(getPresentation_name() + (isMandatory() == true ? "<small>*</small>" : ""));
		return th;
	}

	public Html buildAddHtml(String value, Theme theme) {
		HtmlDiv div = new HtmlDiv(theme);

		HtmlInput input = div.addInput(theme);
		input.setType("text");
		input.setName(DrawDBHTMLHelper.buildName(this));
		input.setReadonly("true");
		input.setSize("" + getPresentation_width());
		input.setMaxlength("" + getLength());
		input.setValue(value);
		div.addChild(new HtmlBr());
		input = div.addInput(theme);
		input.setType("file");
		input.setName(Uploader.UPLOAD + DrawDBHTMLHelper.buildName(this));
		input.setId("upload");
		input.setValue("upload");
		return div;
	}

	public Html buildUpdateHtml(String value, Theme theme)
	{
		HtmlDiv div = new HtmlDiv(theme);

		HtmlInput input = div.addInput(theme);
		input.setType("text");
		input.setName(DrawDBHTMLHelper.buildName(this));
		input.setReadonly("true");
		input.setSize("" + getPresentation_width());
		input.setMaxlength("" + getLength());
		input.setValue(value);
		div.addChild(new HtmlBr());
		input = div.addInput(theme);
		input.setType("file");
		input.setName(Uploader.UPLOAD + DrawDBHTMLHelper.buildName(this));
		input.setId("upload");
		input.setValue("upload");
		return div;

	}

	public Html buildViewHtml(String value, Theme theme) {
		HtmlDiv div = new HtmlDiv(theme);

		HtmlInput input = div.addInput(theme);
		input.setType("text");
		input.setName(DrawDBHTMLHelper.buildName(this));
		input.setReadonly("true");
		input.setSize("" + getPresentation_width());
		input.setMaxlength("" + getLength());
		input.setValue(value);
		div.addChild(new HtmlBr());
		input = div.addInput(theme);
		input.setType("file");
		input.setName(Uploader.UPLOAD + DrawDBHTMLHelper.buildName(this));
		input.setId("upload");
		input.setValue("upload");
		input.setReadonly("true");
		return div;
	}

	public Html[] displayForView(CommonFormFields callingAction, Field field,
			String value, Theme theme) {
		// TODO Auto-generated method stub
		return null;
	}
}


text:
package org.apache.ignite.internal.processors.odbc.odbc;

import java.util.Collection;

/**
 * SQL listener query resultset metadata result.
 */
public class OdbcQueryGetResultsetMetaResult {
    /** Resultset columns metadata. */
    private final Collection<OdbcColumnMeta> columnsMetadata;

    /**
     * @param columnsMetadata Columns metadata.
     */
    public OdbcQueryGetResultsetMetaResult(Collection<OdbcColumnMeta> columnsMetadata) {
        this.columnsMetadata = columnsMetadata;
    }

    /**
     * @return Columns metadata.
     */
    public Collection<OdbcColumnMeta> columnsMetadata() {
        return columnsMetadata;
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Runtime.CompilerServices;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Scripting.Hosting
{
    /// <summary>
    /// Implements an assembly loader for interactive compiler and REPL.
    /// </summary>
    /// <remarks>
    /// <para>
    /// The class is thread-safe.
    /// </para>
    /// </remarks>
    public sealed partial class InteractiveAssemblyLoader : IDisposable
    {
        private class LoadedAssembly
        {
            /// <summary>
            /// The original path of the assembly before it was shadow-copied.
            /// For GAC'd assemblies, this is equal to Assembly.Location no matter what path was used to load them.
            /// </summary>
            public string OriginalPath { get; set; }
        }

        private readonly AssemblyLoaderImpl _runtimeAssemblyLoader;

        private readonly MetadataShadowCopyProvider _shadowCopyProvider;

        // Synchronizes assembly reference tracking.
        // Needs to be thread-safe since assembly loading may be triggered at any time by CLR type loader.
        private readonly object _referencesLock = new object();

        // loaded assembly -> loaded assembly info
        private readonly Dictionary<Assembly, LoadedAssembly> _assembliesLoadedFromLocation;

        // { original full path -> assembly }
        // Note, that there might be multiple entries for a single GAC'd assembly.
        private readonly Dictionary<string, AssemblyAndLocation> _assembliesLoadedFromLocationByFullPath;

        // simple name -> loaded assemblies
        private readonly Dictionary<string, List<LoadedAssemblyInfo>> _loadedAssembliesBySimpleName;

        // simple name -> identity and location of a known dependency
        private readonly Dictionary<string, List<AssemblyIdentityAndLocation>> _dependenciesWithLocationBySimpleName;

        [DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
        private readonly struct AssemblyIdentityAndLocation
        {
            public readonly AssemblyIdentity Identity;
            public readonly string Location;

            public AssemblyIdentityAndLocation(AssemblyIdentity identity, string location)
            {
                Debug.Assert(identity != null && location != null);

                Identity = identity;
                Location = location;
            }

            private string GetDebuggerDisplay() => Identity + " @ " + Location;
        }

        [DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
        private readonly struct LoadedAssemblyInfo
        {
            public readonly Assembly Assembly;
            public readonly AssemblyIdentity Identity;
            public readonly string LocationOpt;

            public LoadedAssemblyInfo(Assembly assembly, AssemblyIdentity identity, string locationOpt)
            {
                Debug.Assert(assembly != null && identity != null);

                Assembly = assembly;
                Identity = identity;
                LocationOpt = locationOpt;
            }

            public bool IsDefault => Assembly == null;
            private string GetDebuggerDisplay() => IsDefault ? "uninitialized" : Identity.GetDisplayName() + (LocationOpt != null ? " @ " + LocationOpt : "");
        }

        public InteractiveAssemblyLoader(MetadataShadowCopyProvider shadowCopyProvider = null)
        {
            _shadowCopyProvider = shadowCopyProvider;

            _assembliesLoadedFromLocationByFullPath = new Dictionary<string, AssemblyAndLocation>();
            _assembliesLoadedFromLocation = new Dictionary<Assembly, LoadedAssembly>();
            _loadedAssembliesBySimpleName = new Dictionary<string, List<LoadedAssemblyInfo>>(AssemblyIdentityComparer.SimpleNameComparer);
            _dependenciesWithLocationBySimpleName = new Dictionary<string, List<AssemblyIdentityAndLocation>>();

            _runtimeAssemblyLoader = AssemblyLoaderImpl.Create(this);
        }

        public void Dispose()
        {
            _runtimeAssemblyLoader.Dispose();
        }

        internal Assembly LoadAssemblyFromStream(Stream peStream, Stream pdbStream)
        {
            Assembly assembly = _runtimeAssemblyLoader.LoadFromStream(peStream, pdbStream);
            RegisterDependency(assembly);
            return assembly;
        }

        private AssemblyAndLocation Load(string reference)
        {
            MetadataShadowCopy copy = null;
            try
            {
                if (_shadowCopyProvider != null)
                {
                    // All modules of the assembly has to be copied at once to keep the metadata consistent.
                    // This API copies the xml doc file and keeps the memory-maps of the metadata.
                    // We don't need that here but presumably the provider is shared with the compilation API that needs both.
                    // Ideally the CLR would expose API to load Assembly given a byte* and not create their own memory-map.
                    copy = _shadowCopyProvider.GetMetadataShadowCopy(reference, MetadataImageKind.Assembly);
                }

                var result = _runtimeAssemblyLoader.LoadFromPath((copy != null) ? copy.PrimaryModule.FullPath : reference);

                if (_shadowCopyProvider != null && result.GlobalAssemblyCache)
                {
                    _shadowCopyProvider.SuppressShadowCopy(reference);
                }

                return result;
            }
            catch (FileNotFoundException)
            {
                return default(AssemblyAndLocation);
            }
            finally
            {
                // copy holds on the file handle, we need to keep the handle
                // open until the file is locked by the CLR assembly loader:
                copy?.DisposeFileHandles();
            }
        }

        /// <summary>
        /// Notifies the assembly loader about a dependency that might be loaded in future.
        /// </summary>
        /// <param name="dependency">Assembly identity.</param>
        /// <param name="path">Assembly location.</param>
        /// <remarks>
        /// Associates a full assembly name with its location. The association is used when an assembly
        /// is being loaded and its name needs to be resolved to a location.
        /// </remarks>
        /// <exception cref="ArgumentNullException"><paramref name="dependency"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="path"/> is not an existing path.</exception>
        public void RegisterDependency(AssemblyIdentity dependency, string path)
        {
            if (dependency == null)
            {
                throw new ArgumentNullException(nameof(dependency));
            }

            if (!PathUtilities.IsAbsolute(path))
            {
                throw new ArgumentException(ScriptingResources.AbsolutePathExpected, nameof(path));
            }

            lock (_referencesLock)
            {
                RegisterDependencyNoLock(new AssemblyIdentityAndLocation(dependency, path));
            }
        }

        /// <summary>
        /// Notifies the assembly loader about an in-memory dependency that should be available within the resolution context.
        /// </summary>
        /// <param name="dependency">Assembly identity.</param>
        /// <exception cref="ArgumentNullException"><paramref name="dependency"/> is null.</exception>
        /// <remarks>
        /// When another in-memory assembly references the <paramref name="dependency"/> the loader
        /// responds with the specified dependency if the assembly identity matches the requested one.
        /// </remarks>
        public void RegisterDependency(Assembly dependency)
        {
            if (dependency == null)
            {
                throw new ArgumentNullException(nameof(dependency));
            }

            lock (_referencesLock)
            {
                RegisterLoadedAssemblySimpleNameNoLock(dependency, locationOpt: null);
            }
        }

        private void RegisterLoadedAssemblySimpleNameNoLock(Assembly assembly, string locationOpt)
        {
            var identity = AssemblyIdentity.FromAssemblyDefinition(assembly);
            var info = new LoadedAssemblyInfo(assembly, identity, locationOpt);

            List<LoadedAssemblyInfo> existingInfos;
            if (_loadedAssembliesBySimpleName.TryGetValue(identity.Name, out existingInfos))
            {
                existingInfos.Add(info);
            }
            else
            {
                _loadedAssembliesBySimpleName.Add(identity.Name, new List<LoadedAssemblyInfo> { info });
            }
        }

        private void RegisterDependencyNoLock(AssemblyIdentityAndLocation dependency)
        {
            List<AssemblyIdentityAndLocation> sameSimpleNameAssemblyIdentities;
            string simpleName = dependency.Identity.Name;
            if (_dependenciesWithLocationBySimpleName.TryGetValue(simpleName, out sameSimpleNameAssemblyIdentities))
            {
                sameSimpleNameAssemblyIdentities.Add(dependency);
            }
            else
            {
                _dependenciesWithLocationBySimpleName.Add(simpleName, new List<AssemblyIdentityAndLocation> { dependency });
            }
        }

        internal Assembly ResolveAssembly(string assemblyDisplayName, Assembly requestingAssemblyOpt)
        {
            AssemblyIdentity identity;
            if (!AssemblyIdentity.TryParseDisplayName(assemblyDisplayName, out identity))
            {
                return null;
            }

            string loadDirectoryOpt;
            lock (_referencesLock)
            {
                LoadedAssembly loadedAssembly;
                if (requestingAssemblyOpt != null &&
                    _assembliesLoadedFromLocation.TryGetValue(requestingAssemblyOpt, out loadedAssembly))
                {
                    loadDirectoryOpt = Path.GetDirectoryName(loadedAssembly.OriginalPath);
                }
                else
                {
                    loadDirectoryOpt = null;
                }
            }

            return ResolveAssembly(identity, loadDirectoryOpt);
        }

        internal Assembly ResolveAssembly(AssemblyIdentity identity, string loadDirectoryOpt)
        {
            // if the referring assembly is already loaded by our loader, load from its directory:
            if (loadDirectoryOpt != null)
            {
                Assembly assembly;
                var conflictingLoadedAssemblyOpt = default(LoadedAssemblyInfo);
                var loadedAssemblyWithEqualNameAndVersionOpt = default(LoadedAssemblyInfo);

                lock (_referencesLock)
                {
                    // Has the file already been loaded?
                    assembly = TryGetAssemblyLoadedFromPath(identity, loadDirectoryOpt);
                    if (assembly != null)
                    {
                        return assembly;
                    }

                    // Has an assembly with the same name and version been loaded (possibly from a different directory)?
                    List<LoadedAssemblyInfo> loadedInfos;
                    if (_loadedAssembliesBySimpleName.TryGetValue(identity.Name, out loadedInfos))
                    {
                        // Desktop FX: A weak-named assembly conflicts with another weak-named assembly of the same simple name,
                        // unless we find an assembly whose identity matches exactly and whose content is exactly the same.
                        // TODO: We shouldn't block this on CoreCLR. https://github.com/dotnet/roslyn/issues/38621

                        if (!identity.IsStrongName)
                        {
                            conflictingLoadedAssemblyOpt = loadedInfos.FirstOrDefault(info => !info.Identity.IsStrongName);
                        }

                        loadedAssemblyWithEqualNameAndVersionOpt = loadedInfos.FirstOrDefault(info =>
                            AssemblyIdentityComparer.SimpleNameComparer.Equals(info.Identity.Name, identity.Name) &&
                            info.Identity.Version == identity.Version);
                    }
                }

                string assemblyFilePathOpt = FindExistingAssemblyFile(identity.Name, loadDirectoryOpt);
                if (assemblyFilePathOpt != null)
                {
                    // TODO: Stop using reflection once ModuleVersionId property once is available in Core contract.
                    if (!loadedAssemblyWithEqualNameAndVersionOpt.IsDefault)
                    {
                        Guid mvid;
                        if (TryReadMvid(assemblyFilePathOpt, out mvid) &&
                            loadedAssemblyWithEqualNameAndVersionOpt.Assembly.ManifestModule.ModuleVersionId == mvid)
                        {
                            return loadedAssemblyWithEqualNameAndVersionOpt.Assembly;
                        }

                        // error: attempt to load an assembly with the same identity as already loaded assembly but different content
                        throw new InteractiveAssemblyLoaderException(
                            string.Format(null, ScriptingResources.AssemblyAlreadyLoaded,
                            identity.Name,
                            identity.Version,
                            loadedAssemblyWithEqualNameAndVersionOpt.LocationOpt,
                            assemblyFilePathOpt)
                        );
                    }

                    // TODO: Desktop FX only https://github.com/dotnet/roslyn/issues/38621
                    if (!conflictingLoadedAssemblyOpt.IsDefault)
                    {
                        // error: attempt to load an assembly with the same identity as already loaded assembly but different content
                        throw new InteractiveAssemblyLoaderException(
                            string.Format(null, ScriptingResources.AssemblyAlreadyLoadedNotSigned,
                            identity.Name,
                            conflictingLoadedAssemblyOpt.LocationOpt,
                            assemblyFilePathOpt)
                        );
                    }

                    assembly = ShadowCopyAndLoadDependency(assemblyFilePathOpt).Assembly;
                    if (assembly != null)
                    {
                        return assembly;
                    }
                }
            }

            return GetOrLoadKnownAssembly(identity);
        }

        private static string FindExistingAssemblyFile(string simpleName, string directory)
        {
            string pathWithoutExtension = Path.Combine(directory, simpleName);
            foreach (var extension in RuntimeMetadataReferenceResolver.AssemblyExtensions)
            {
                string path = pathWithoutExtension + extension;
                if (File.Exists(path))
                {
                    return path;
                }
            }

            return null;
        }

        private Assembly TryGetAssemblyLoadedFromPath(AssemblyIdentity identity, string directory)
        {
            string pathWithoutExtension = Path.Combine(directory, identity.Name);

            foreach (var extension in RuntimeMetadataReferenceResolver.AssemblyExtensions)
            {
                AssemblyAndLocation assemblyAndLocation;
                if (_assembliesLoadedFromLocationByFullPath.TryGetValue(pathWithoutExtension + extension, out assemblyAndLocation) &&
                    identity.Equals(AssemblyIdentity.FromAssemblyDefinition(assemblyAndLocation.Assembly)))
                {
                    return assemblyAndLocation.Assembly;
                }
            }

            return null;
        }

        private static bool TryReadMvid(string filePath, out Guid mvid)
        {
            try
            {
                using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
                {
                    using (var peReader = new PEReader(stream))
                    {
                        var metadataReader = peReader.GetMetadataReader();
                        mvid = metadataReader.GetGuid(metadataReader.GetModuleDefinition().Mvid);
                        return true;
                    }
                }
            }
            catch
            {
                mvid = default;
                return false;
            }
        }

        private Assembly GetOrLoadKnownAssembly(AssemblyIdentity identity)
        {
            Assembly assembly = null;
            string assemblyFileToLoad = null;

            // Try to find the assembly among assemblies that we loaded, comparing its identity with the requested one.
            lock (_referencesLock)
            {
                // already loaded assemblies:
                List<LoadedAssemblyInfo> infos;
                if (_loadedAssembliesBySimpleName.TryGetValue(identity.Name, out infos))
                {
                    assembly = FindHighestVersionOrFirstMatchingIdentity(identity, infos);
                    if (assembly != null)
                    {
                        return assembly;
                    }
                }

                // names:
                List<AssemblyIdentityAndLocation> sameSimpleNameIdentities;
                if (_dependenciesWithLocationBySimpleName.TryGetValue(identity.Name, out sameSimpleNameIdentities))
                {
                    var identityAndLocation = FindHighestVersionOrFirstMatchingIdentity(identity, sameSimpleNameIdentities);
                    if (identityAndLocation.Identity != null)
                    {
                        assemblyFileToLoad = identityAndLocation.Location;
                        AssemblyAndLocation assemblyAndLocation;
                        if (_assembliesLoadedFromLocationByFullPath.TryGetValue(assemblyFileToLoad, out assemblyAndLocation))
                        {
                            return assemblyAndLocation.Assembly;
                        }
                    }
                }
            }

            if (assemblyFileToLoad != null)
            {
                assembly = ShadowCopyAndLoadDependency(assemblyFileToLoad).Assembly;
            }

            return assembly;
        }

        private AssemblyAndLocation ShadowCopyAndLoadDependency(string originalPath)
        {
            AssemblyAndLocation assemblyAndLocation = Load(originalPath);
            if (assemblyAndLocation.IsDefault)
            {
                return default(AssemblyAndLocation);
            }

            lock (_referencesLock)
            {
                // Always remember the path. The assembly might have been loaded from another path or not loaded yet.
                _assembliesLoadedFromLocationByFullPath[originalPath] = assemblyAndLocation;

                LoadedAssembly loadedAssembly;
                if (_assembliesLoadedFromLocation.TryGetValue(assemblyAndLocation.Assembly, out loadedAssembly))
                {
                    return assemblyAndLocation;
                }

                _assembliesLoadedFromLocation.Add(
                    assemblyAndLocation.Assembly,
                    new LoadedAssembly { OriginalPath = assemblyAndLocation.GlobalAssemblyCache ? assemblyAndLocation.Location : originalPath });

                RegisterLoadedAssemblySimpleNameNoLock(assemblyAndLocation.Assembly, assemblyAndLocation.Location);
            }

            return assemblyAndLocation;
        }

        private static Assembly FindHighestVersionOrFirstMatchingIdentity(AssemblyIdentity identity, IEnumerable<LoadedAssemblyInfo> infos)
        {
            Assembly candidate = null;
            Version candidateVersion = null;
            foreach (var info in infos)
            {
                if (DesktopAssemblyIdentityComparer.Default.ReferenceMatchesDefinition(identity, info.Identity))
                {
                    if (candidate == null || candidateVersion < info.Identity.Version)
                    {
                        candidate = info.Assembly;
                        candidateVersion = info.Identity.Version;
                    }
                }
            }

            return candidate;
        }

        private static AssemblyIdentityAndLocation FindHighestVersionOrFirstMatchingIdentity(AssemblyIdentity identity, IEnumerable<AssemblyIdentityAndLocation> assemblies)
        {
            var candidate = default(AssemblyIdentityAndLocation);
            foreach (var assembly in assemblies)
            {
                if (DesktopAssemblyIdentityComparer.Default.ReferenceMatchesDefinition(identity, assembly.Identity))
                {
                    if (candidate.Identity == null || candidate.Identity.Version < assembly.Identity.Version)
                    {
                        candidate = assembly;
                    }
                }
            }

            return candidate;
        }
    }
}


text:
require 'erb'
require 'optparse'
require 'fileutils'
$:.unshift(File.dirname(__FILE__))
require 'vpath'

vpath = VPath.new
timestamp = nil
output = nil
ifchange = nil
source = false

opt = OptionParser.new do |o|
  o.on('-t', '--timestamp[=PATH]') {|v| timestamp = v || true}
  o.on('-o', '--output=PATH') {|v| output = v}
  o.on('-c', '--[no-]if-change') {|v| ifchange = v}
  o.on('-x', '--source') {source = true}
  vpath.def_options(o)
  o.order!(ARGV)
end
template = ARGV.shift or abort opt.to_s
erb = ERB.new(File.read(template), nil, '%-')
erb.filename = template
result = source ? erb.src : erb.result
if output
  if ifchange and (vpath.open(output, "rb") {|f| f.read} rescue nil) == result
    puts "#{output} unchanged"
  else
    open(output, "wb") {|f| f.print result}
    puts "#{output} updated"
  end
  if timestamp
    if timestamp == true
      dir, base = File.split(output)
      timestamp = File.join(dir, ".time." + base)
    end
    FileUtils.touch(timestamp)
  end
else
  print result
end


text:
/* vi: set sw=4 ts=4: */
/*
 * Copyright 1989 - 1994, Julianne Frances Haugh
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of Julianne F. Haugh nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY JULIE HAUGH AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL JULIE HAUGH OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 * This version of obscure.c contains modifications to support "cracklib"
 * by Alec Muffet (alec.muffett@uk.sun.com).  You must obtain the Cracklib
 * library source code for this function to operate.
 */

#include "tinylogin.h"

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

/*
 * can't be a palindrome - like `R A D A R' or `M A D A M'
 */

 /*ARGSUSED*/ static int palindrome(old, new)
	 /* returns 1 if true */
const char *old;
const char *new;
{
	int i, j;

	i = strlen(new);

	for (j = 0; j < i; j++)
		if (new[i - j - 1] != new[j])
			return 0;

	return 1;
}

/*
 * more than half of the characters are different ones.
 */

 /*ARGSUSED*/ static int similiar(old, new)
	 /* returns 1 if true */
const char *old;
const char *new;
{
	int i, j;

	for (i = j = 0; new[i] && old[i]; i++)
		if (strchr(new, old[i]))
			j++;

	if (i >= j * 2)
		return 0;

	return 1;
}

/*
 * a nice mix of characters.
 */

 /*ARGSUSED*/ static int simple(old, new)
const char *old;
const char *new;

	 /* returns 1 if true */
{
	int digits = 0;
	int uppers = 0;
	int lowers = 0;
	int others = 0;
	int size;
	int i;

	for (i = 0; new[i]; i++) {
		if (isdigit(new[i]))
			digits++;
		else if (isupper(new[i]))
			uppers++;
		else if (islower(new[i]))
			lowers++;
		else
			others++;
	}

	/*
	 * The scam is this - a password of only one character type
	 * must be 8 letters long.  Two types, 7, and so on.
	 */

	size = 9;
	if (digits)
		size--;
	if (uppers)
		size--;
	if (lowers)
		size--;
	if (others)
		size--;

	if (size <= i)
		return 0;

	return 1;
}

static char *str_lower(string)
char *string;
{
	char *cp;

	for (cp = string; *cp; cp++)
		*cp = tolower(*cp);
	return string;
}

static char *password_check(old, new, pwdp)
const char *old;
const char *new;
const struct passwd *pwdp;
{
	char *msg = NULL;
	char *oldmono, *newmono, *wrapped;

	if (strcmp(new, old) == 0)
		return "no change";

	newmono = str_lower(xstrdup(new));
	oldmono = str_lower(xstrdup(old));
	wrapped = (char *) xmalloc(strlen(oldmono) * 2 + 1);
	strcpy(wrapped, oldmono);
	strcat(wrapped, oldmono);

	if (palindrome(oldmono, newmono))
		msg = "a palindrome";

	if (!msg && strcmp(oldmono, newmono) == 0)
		msg = "case changes only";

	if (!msg && similiar(oldmono, newmono))
		msg = "too similiar";

	if (!msg && simple(old, new))
		msg = "too simple";

	if (!msg && strstr(wrapped, newmono))
		msg = "rotated";

	bzero(newmono, strlen(newmono));
	bzero(oldmono, strlen(oldmono));
	bzero(wrapped, strlen(wrapped));
	free(newmono);
	free(oldmono);
	free(wrapped);

	return msg;
}

 /*ARGSUSED*/ char *obscure_msg(old, new, pwdp)
	 /* return NULL on OK, message on password error */
const char *old;
const char *new;
const struct passwd *pwdp;
{
	int maxlen, oldlen, newlen;
	char *new1, *old1, *msg;

	oldlen = strlen(old);
	newlen = strlen(new);

#if 0							/* why not check the password when set for the first time?  --marekm */
	if (old[0] == '\0')
		/* return (1); */
		return NULL;
#endif

	if (newlen < 5)
		return "too short";

	/*
	 * Remaining checks are optional.
	 */
	/* Not for us -- Sean
	 *if (!getdef_bool("OBSCURE_CHECKS_ENAB"))
	 *      return NULL;
	 */
	msg = password_check(old, new, pwdp);
	if (msg)
		return msg;

	/* The traditional crypt() truncates passwords to 8 chars.  It is
	   possible to circumvent the above checks by choosing an easy
	   8-char password and adding some random characters to it...
	   Example: "password$%^&*123".  So check it again, this time
	   truncated to the maximum length.  Idea from npasswd.  --marekm */

	maxlen = 8;
	if (oldlen <= maxlen && newlen <= maxlen)
		return NULL;

	new1 = (char *) xstrdup(new);
	old1 = (char *) xstrdup(old);
	if (newlen > maxlen)
		new1[maxlen] = '\0';
	if (oldlen > maxlen)
		old1[maxlen] = '\0';

	msg = password_check(old1, new1, pwdp);

	bzero(new1, newlen);
	bzero(old1, oldlen);
	free(new1);
	free(old1);

	return msg;
}

/*
 * Obscure - see if password is obscure enough.
 *
 *	The programmer is encouraged to add as much complexity to this
 *	routine as desired.  Included are some of my favorite ways to
 *	check passwords.
 */

extern int
obscure(const char *old, const char *new, const struct passwd *pwdp)
{
	char *msg = obscure_msg(old, new, pwdp);

	/*  if (msg) { */
	if (msg != NULL) {
		printf("Bad password: %s.\n", msg);
		/* return 0; */
		return 1;
	}
	/* return 1; */
	return 0;
}


text:
<?php

/**
 * Created by IntelliJ IDEA.
 * User: imam lubis
 * Date: 24/12/2016
 * Time: 20:11
 */
class pengadaansaranabursakerjaonlineModel extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }
    public function record_count() {
        return $this->db->count_all("pengadaansaranabursakerjaonline");
    }
    function get($limit=null,$offset=NULL){
        $this->db->select("*");
        $this->db->from('pengadaansaranabursakerjaonline a');
        $this->db->limit($limit, $offset);
        $query = $this->db->get();
        return $query->result();
    }
    public function total() {
        return $this->db->count_all_results("pengadaansaranabursakerjaonline");
    }

    function add($data)
    {
        $this->db->insert('pengadaansaranabursakerjaonline', $data);
    }
}


text:
package us.kbase.contigfilter;

import com.fasterxml.jackson.core.type.TypeReference;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import us.kbase.auth.AuthToken;
import us.kbase.common.service.JsonClientCaller;
import us.kbase.common.service.JsonClientException;
import us.kbase.common.service.RpcContext;
import us.kbase.common.service.UnauthorizedException;

/**
 *
Original spec-file module name: ContigFilter

 *

 * A KBase module: ContigFilter
 * This sample module contains one small method - filter_contigs.
 *

 */
public class ContigFilterClient {
    private JsonClientCaller caller;
    private String serviceVersion = null;

    /** Constructs a client with a custom URL and no user credentials.
     * @param url the URL of the service.
     */
    public ContigFilterClient(URL url) {
        caller = new JsonClientCaller(url);
    }
    /** Constructs a client with a custom URL.
     * @param url the URL of the service.
     * @param token the user's authorization token.
     * @throws UnauthorizedException if the token is not valid.
     * @throws IOException if an IOException occurs when checking the token's
     * validity.
     */
    public ContigFilterClient(URL url, AuthToken token) throws UnauthorizedException, IOException {
        caller = new JsonClientCaller(url, token);
    }

    /** Constructs a client with a custom URL.
     * @param url the URL of the service.
     * @param user the user name.
     * @param password the password for the user name.
     * @throws UnauthorizedException if the credentials are not valid.
     * @throws IOException if an IOException occurs when checking the user's
     * credentials.
     */
    public ContigFilterClient(URL url, String user, String password) throws UnauthorizedException, IOException {
        caller = new JsonClientCaller(url, user, password);
    }

    /** Constructs a client with a custom URL
     * and a custom authorization service URL.
     * @param url the URL of the service.
     * @param user the user name.
     * @param password the password for the user name.
     * @param auth the URL of the authorization server.
     * @throws UnauthorizedException if the credentials are not valid.
     * @throws IOException if an IOException occurs when checking the user's
     * credentials.
     */
    public ContigFilterClient(URL url, String user, String password, URL auth) throws UnauthorizedException, IOException {
        caller = new JsonClientCaller(url, user, password, auth);
    }

    /** Get the token this client uses to communicate with the server.
     * @return the authorization token.
     */
    public AuthToken getToken() {
        return caller.getToken();
    }

    /** Get the URL of the service with which this client communicates.
     * @return the service URL.
     */
    public URL getURL() {
        return caller.getURL();
    }

    /** Set the timeout between establishing a connection to a server and
     * receiving a response. A value of zero or null implies no timeout.
     * @param milliseconds the milliseconds to wait before timing out when
     * attempting to read from a server.
     */
    public void setConnectionReadTimeOut(Integer milliseconds) {
        this.caller.setConnectionReadTimeOut(milliseconds);
    }

    /** Check if this client allows insecure http (vs https) connections.
     * @return true if insecure connections are allowed.
     */
    public boolean isInsecureHttpConnectionAllowed() {
        return caller.isInsecureHttpConnectionAllowed();
    }

    /** Deprecated. Use isInsecureHttpConnectionAllowed().
     * @deprecated
     */
    public boolean isAuthAllowedForHttp() {
        return caller.isAuthAllowedForHttp();
    }

    /** Set whether insecure http (vs https) connections should be allowed by
     * this client.
     * @param allowed true to allow insecure connections. Default false
     */
    public void setIsInsecureHttpConnectionAllowed(boolean allowed) {
        caller.setInsecureHttpConnectionAllowed(allowed);
    }

    /** Deprecated. Use setIsInsecureHttpConnectionAllowed().
     * @deprecated
     */
    public void setAuthAllowedForHttp(boolean isAuthAllowedForHttp) {
        caller.setAuthAllowedForHttp(isAuthAllowedForHttp);
    }

    /** Set whether all SSL certificates, including self-signed certificates,
     * should be trusted.
     * @param trustAll true to trust all certificates. Default false.
     */
    public void setAllSSLCertificatesTrusted(final boolean trustAll) {
        caller.setAllSSLCertificatesTrusted(trustAll);
    }

    /** Check if this client trusts all SSL certificates, including
     * self-signed certificates.
     * @return true if all certificates are trusted.
     */
    public boolean isAllSSLCertificatesTrusted() {
        return caller.isAllSSLCertificatesTrusted();
    }
    /** Sets streaming mode on. In this case, the data will be streamed to
     * the server in chunks as it is read from disk rather than buffered in
     * memory. Many servers are not compatible with this feature.
     * @param streamRequest true to set streaming mode on, false otherwise.
     */
    public void setStreamingModeOn(boolean streamRequest) {
        caller.setStreamingModeOn(streamRequest);
    }

    /** Returns true if streaming mode is on.
     * @return true if streaming mode is on.
     */
    public boolean isStreamingModeOn() {
        return caller.isStreamingModeOn();
    }

    public void _setFileForNextRpcResponse(File f) {
        caller.setFileForNextRpcResponse(f);
    }

    public String getServiceVersion() {
        return this.serviceVersion;
    }

    public void setServiceVersion(String newValue) {
        this.serviceVersion = newValue;
    }

    /**
     *
Original spec-file function name: filter_contigs

     *

     * The actual function is declared using 'funcdef' to specify the name
     * and input/return arguments to the function.  For all typical KBase
     * Apps that run in the Narrative, your function should have the
     * 'authentication required' modifier.
     *

     * @param   params   instance of type {@link us.kbase.contigfilter.FilterContigsParams FilterContigsParams}
     * @return   parameter "output" of type {@link us.kbase.contigfilter.FilterContigsResults FilterContigsResults}
     * @throws IOException if an IO exception occurs
     * @throws JsonClientException if a JSON RPC exception occurs
     */
    public FilterContigsResults filterContigs(FilterContigsParams params, RpcContext... jsonRpcContext) throws IOException, JsonClientException {
        List<Object> args = new ArrayList<Object>();
        args.add(params);
        TypeReference<List<FilterContigsResults>> retType = new TypeReference<List<FilterContigsResults>>() {};
        List<FilterContigsResults> res = caller.jsonrpcCall("ContigFilter.filter_contigs", args, retType, true, true, jsonRpcContext, this.serviceVersion);
        return res.get(0);
    }

    public Map<String, Object> status(RpcContext... jsonRpcContext) throws IOException, JsonClientException {
        List<Object> args = new ArrayList<Object>();
        TypeReference<List<Map<String, Object>>> retType = new TypeReference<List<Map<String, Object>>>() {};
        List<Map<String, Object>> res = caller.jsonrpcCall("ContigFilter.status", args, retType, true, false, jsonRpcContext, this.serviceVersion);
        return res.get(0);
    }
}


text:
package main

import (
	"log"
	"path"

	"github.com/urfave/cli"
)

func componentRollback(c *cli.Context) error {

	config := c.GlobalString("config")
	ticket := c.String("ticket")
	environments := c.StringSlice("environment")
	components := c.StringSlice("component")

	dir, err := createArtifactsDir("/tmp")
	if err != nil {
		panic(err.Error())
	}

	setLogFile(dir)

	log.Print(">>> Rollback started")
	err = downloadArtifacts(config, dir)
	if err != nil {
		log.Fatal(err.Error())
	}
	log.Printf("Config downloaded to %s", dir)
	log.Print("-----------------")

	for _, component := range components {
		for _, env := range environments {

			componentCfg, exists, err := loadComponent(dir, env, component)
			if err != nil {
				log.Fatal(err.Error())
			}
			if !exists {
				log.Printf("No config found for %s on %s", component, env)
				log.Print("-----------------")
				continue
			}

			if componentCfg.Component.Type == "docker" {
				targets := componentCfg.Component.Target

				// detect leader node and shift it as last in the targets array
				if componentCfg.Component.Mode == "ha" {
					leaderIdx := -1
					var leaderEntry ComponentTarget
					for i, target := range componentCfg.Component.Target {
						isLeader := containerClusterCheck(target.Leadership, 15)
						if isLeader {
							leaderIdx = i
							leaderEntry = target
							break
						}
					}
					if leaderIdx > -1 {
						targets = removeTargetByIndex(targets, leaderIdx)
						targets = append(targets, leaderEntry)
						log.Printf("Leader found on %s", leaderEntry.Host)
					} else {
						log.Printf("No leader found for %s on %s", component, env)
					}
				}

				// run reload on each target host
				for _, target := range targets {

					// mark deployment as started in SYROS
					if len(ticket) > 0 {
						syrosApi, cfgExists, err := loadSyrosConfig(dir, "syros")
						if err != nil {
							log.Printf("Syros config load failed %s", err.Error())
						} else {
							if !cfgExists {
								log.Print("Syros config not found")
							} else {
								err := syrosApi.Start(ticket, env, component, target.Host)
								if err != nil {
									log.Print(err.Error())
								}
							}
						}
					}

					cd := ContainerDeploy{
						Dir:      dir,
						Env:      env,
						HostFrom: target.Host,
						HostTo:   target.Host,
						Service:  component,
						Ticket:   ticket,
						Check:    target.Health,
					}

					err = cd.Rollback()
					if err != nil {
						log.Fatal(err.Error())
					}

					if len(ticket) > 0 {
						// add comment on JIRA ticket
						jira, cfgExists, err := loadJiraConfig(dir, "jira")
						if err != nil {
							log.Printf("Jira config load failed %s", err.Error())
						} else {
							if !cfgExists {
								log.Print("Jira config not found")
							} else {
								err := jira.Post(ticket, "Rollback", env, component, target.Host)
								if err != nil {
									log.Print(err.Error())
								}
							}
						}
						// mark deployment as done in SYROS and upload log
						syrosApi, cfgExists, err := loadSyrosConfig(dir, "syros")
						if err != nil {
							log.Printf("Syros config load failed %s", err.Error())
						} else {
							if !cfgExists {
								log.Print("Syros config not found")
							} else {
								err := syrosApi.Finish(ticket, env, component, target.Host, path.Join(dir, "deployctl.log"))
								if err != nil {
									log.Print(err.Error())
								}
							}
						}
					}

					log.Printf("Rollback complete for %s on %s", component, target.Host)
					log.Print("-----------------")
				}
			}
		}
	}

	// upload log to JIRA
	if len(ticket) > 0 {
		jira, cfgExists, err := loadJiraConfig(dir, "jira")
		if err != nil {
			log.Printf("Jira config load failed %s", err.Error())
		} else {
			if !cfgExists {
				log.Print("Jira config not found")
			} else {
				err := jira.Upload(ticket, dir, "deployctl.log")
				if err != nil {
					log.Print(err.Error())
				}
			}
		}
	}

	log.Print(">>> Rollback complete")

	return nil
}


text:
class ExampleController < AuthenticatedController
end


text:
package redfish

import (
	"encoding/json"

	"github.com/stmcginnis/gofish/common"
)

// NetworkInterfaceLinks references to resources that are related to, but not
// contained by (subordinate to), this resource.
type NetworkInterfaceLinks struct {
	// NetworkAdapter shall be a reference to a
	// resource of type NetworkAdapter that represents the physical container
	// associated with this NetworkInterface.
	NetworkAdapter common.Link
}

// A NetworkInterface contains references linking NetworkAdapter, NetworkPort,
// and NetworkDeviceFunction resources and represents the functionality
// available to the containing system.
type NetworkInterface struct {
	common.Entity

	// ODataContext is the odata context.
	ODataContext string `json:"@odata.context"`
	// ODataType is the odata type.
	ODataType string `json:"@odata.type"`
	// Description provides a description of this resource.
	Description string
	// networkAdapter shall be a reference to a resource of type NetworkAdapter
	// that represents the physical container associated with this NetworkInterface.
	networkAdapter string
	// networkDeviceFunctions shall be a link to a collection of type
	// NetworkDeviceFunctionCollection.
	networkDeviceFunctions string
	// NetworkPorts shall be a link to a collection of type NetworkPortCollection.
	networkPorts string
	// Status shall contain any status or health properties of the resource.
	Status common.Status
}

// UnmarshalJSON unmarshals a NetworkInterface object from the raw JSON.
func (networkinterface *NetworkInterface) UnmarshalJSON(b []byte) error {
	type temp NetworkInterface
	var t struct {
		temp
		NetworkDeviceFunctions common.Link
		NetworkPorts           common.Link
		Links                  NetworkInterfaceLinks
	}

	err := json.Unmarshal(b, &t)
	if err != nil {
		return err
	}

	// Extract the links to other entities for later
	*networkinterface = NetworkInterface(t.temp)
	networkinterface.networkAdapter = string(t.Links.NetworkAdapter)
	networkinterface.networkDeviceFunctions = string(t.NetworkDeviceFunctions)
	networkinterface.networkPorts = string(t.NetworkPorts)

	return nil
}

// GetNetworkInterface will get a NetworkInterface instance from the service.
func GetNetworkInterface(c common.Client, uri string) (*NetworkInterface, error) {
	resp, err := c.Get(uri)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var networkinterface NetworkInterface
	err = json.NewDecoder(resp.Body).Decode(&networkinterface)
	if err != nil {
		return nil, err
	}

	networkinterface.SetClient(c)
	return &networkinterface, nil
}

// ListReferencedNetworkInterfaces gets the collection of NetworkInterface from
// a provided reference.
func ListReferencedNetworkInterfaces(c common.Client, link string) ([]*NetworkInterface, error) { //nolint:dupl
	var result []*NetworkInterface
	if link == "" {
		return result, nil
	}

	links, err := common.GetCollection(c, link)
	if err != nil {
		return result, err
	}

	collectionError := common.NewCollectionError()
	for _, networkinterfaceLink := range links.ItemLinks {
		networkinterface, err := GetNetworkInterface(c, networkinterfaceLink)
		if err != nil {
			collectionError.Failures[networkinterfaceLink] = err
		} else {
			result = append(result, networkinterface)
		}
	}

	if collectionError.Empty() {
		return result, nil
	}

	return result, collectionError
}

// NetworkAdapter gets the NetworkAdapter for this interface.
func (networkinterface *NetworkInterface) NetworkAdapter() (*NetworkAdapter, error) {
	if networkinterface.networkAdapter == "" {
		return nil, nil
	}

	return GetNetworkAdapter(networkinterface.Client, networkinterface.networkAdapter)
}

// NetworkDeviceFunctions gets the collection of NetworkDeviceFunctions of this network interface
func (networkinterface *NetworkInterface) NetworkDeviceFunctions() ([]*NetworkDeviceFunction, error) {
	return ListReferencedNetworkDeviceFunctions(
		networkinterface.Client, networkinterface.networkDeviceFunctions)
}

// NetworkPorts gets the collection of NetworkPorts of this network interface
func (networkinterface *NetworkInterface) NetworkPorts() ([]*NetworkPort, error) {
	return ListReferencedNetworkPorts(
		networkinterface.Client, networkinterface.networkPorts)
}


text:
<!DOCTYPE html>

<meta content="text/html; charset=utf-8" http-equiv="Content-Type">

<title>CONTACTING_US - SEEK Technical Guide</title>

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

    Home
    Classes
    Methods

  <form action="#" method="get" accept-charset="utf-8">

      <input type="text" name="search" placeholder="Search" id="search-field"
             title="Type to search, Up and Down to navigate, Enter to load">

  </form>

Pages

ADMINISTRATION

BACKUPS

CONTACTING_US

CONTRIBUTING_TO_SEEK

CREDITS

EARLIER-UPGRADES

INSTALL

INSTALL-ON-A-SUBURI

INSTALL-PRODUCTION

OTHER-DISTRIBUTIONS

README

SETTING-UP-VIRTUOSO

UPGRADING

UPGRADING-TO-0-18

Class and Module Index

Seek

Seek::Rdf

Seek::Rdf::RdfFileStorage

Seek::Rdf::RdfGeneration

Seek::Rdf::RdfRepository

Seek::Rdf::RdfRepositoryStorage

Seek::Rdf::VirtuosoRepository

Seek::Rdf::VirtuosoRepository::Config

Contacting us

We have 2 mailing lists, using Google Groups, for contacting us, along with
other developers and users.

The 2 lists are

A general SEEK user and site administrators group available at groups.google.com/group/seek4science

A more development orientated group available at groups.google.com/group/seek-developers

[Validate]

Generated by RDoc 3.12.2.

Generated with the Darkfish Rdoc Generator 3.


text:
public partial class GameEventEntity {

    public StateEventComponent stateEvent { get { return (StateEventComponent)GetComponent(GameEventComponentsLookup.StateEvent); } }
    public bool hasStateEvent { get { return HasComponent(GameEventComponentsLookup.StateEvent); } }

    public void AddStateEvent(string newState) {
        var index = GameEventComponentsLookup.StateEvent;
        var component = CreateComponent<StateEventComponent>(index);
        component.state = newState;
        AddComponent(index, component);
    }

    public void ReplaceStateEvent(string newState) {
        var index = GameEventComponentsLookup.StateEvent;
        var component = CreateComponent<StateEventComponent>(index);
        component.state = newState;
        ReplaceComponent(index, component);
    }

    public void RemoveStateEvent() {
        RemoveComponent(GameEventComponentsLookup.StateEvent);
    }
}

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by Entitas.CodeGeneration.Plugins.ComponentMatcherGenerator.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public sealed partial class GameEventMatcher {

    static Entitas.IMatcher<GameEventEntity> _matcherStateEvent;

    public static Entitas.IMatcher<GameEventEntity> StateEvent {
        get {
            if (_matcherStateEvent == null) {
                var matcher = (Entitas.Matcher<GameEventEntity>)Entitas.Matcher<GameEventEntity>.AllOf(GameEventComponentsLookup.StateEvent);
                matcher.componentNames = GameEventComponentsLookup.componentNames;
                _matcherStateEvent = matcher;
            }

            return _matcherStateEvent;
        }
    }
}


text:
package zerodrive.behavior.impl;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import zerodrive.behavior.ActionConfig;
import zerodrive.behavior.ActionExecutor;

/**
 * @author AdachiHjm
 * @created 2015/11/19 23:01:40
 *
 */
public class SimpleActionExecutor extends ActionExecutor {
    //======================================================================
    // Fields
    private final ConcurrentMap<Class<?>, Object> cache = new ConcurrentHashMap<Class<?>, Object>();

    //======================================================================
    // Methods
    /**
     * @see zerodrive.behavior.ActionExecutor#create(zerodrive.behavior.ActionConfig)
     */
    @Override
    protected Object create(ActionConfig config) throws Exception {
        if (this.cache.containsKey(config.getActionClass())) {
            return this.cache.get(config.getActionClass());
        }

        Object action = config.getActionClass().newInstance();

        for (Class<?> type = action.getClass(); !Object.class.equals(type); type = type.getSuperclass()) {
            Field[] fields = type.getDeclaredFields();
            for (Field field : fields) {
                if (config.getProperties().containsKey(field.getName())) {
                    if (Modifier.isPublic(field.getModifiers())) {
                        field.set(action, config.getProperties().get(field.getName()));
                    } else {
                        PropertyDescriptor desc = new PropertyDescriptor(field.getName(), type);
                        Method setter = desc.getWriteMethod();
                        setter.invoke(action, config.getProperties().get(field.getName()));
                    }
                }
            }
        }

        if (config.isOnce()) {
            action = this.cache.putIfAbsent(config.getActionClass(), action);
        }
        return action;
    }

}


text:
<!DOCTYPE HTML>

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

001package io.ebean;
002
003import javax.persistence.PersistenceException;
004import java.util.List;
005import java.util.concurrent.Future;
006import java.util.concurrent.TimeUnit;
007import java.util.concurrent.TimeoutException;
008
009/**
010 * FutureList represents the result of a background query execution that will
011 * return a list of entities.
012 * <p>
013 * It extends the java.util.concurrent.Future with the ability to cancel the
014 * query, check if it is finished and get the resulting list waiting for the
015 * query to finish (ie. the standard features of java.util.concurrent.Future).
016 * </p>
017 * <p>
018 * A simple example:
019 * </p>
020 * <pre>{@code
021 *
022 *  // create a query to find all orders
023 * Query<Order> query = DB.find(Order.class);
024 *
025 *  // execute the query in a background thread
026 *  // immediately returning the futureList
027 * FutureList<Order> futureList = query.findFutureList();
028 *
029 *  // do something else ...
030 *
031 * if (!futureList.isDone()){
032 *      // we can cancel the query execution. This will cancel
033 * // the underlying query if that is supported by the JDBC
034 * // driver and database
035 *      futureList.cancel(true);
036 * }
037 *
038 * if (!futureList.isCancelled()){
039 *      // wait for the query to finish and return the list
040 *      List<Order> list = futureList.get();
041 *      ...
042 * }
043 *
044 * }</pre>
045 */
046public interface FutureList<T> extends Future<List<T>> {
047
048  /**
049   * Return the query that is being executed by a background thread.
050   */
051  Query<T> getQuery();
052
053  /**
054   * Same as {@link #get()} but wraps InterruptedException and ExecutionException in the
055   * unchecked PersistenceException.
056   *
057   * @return The query list result
058   * @throws PersistenceException when a InterruptedException or ExecutionException occurs.
059   */
060  List<T> getUnchecked();
061
062  /**
063   * Same as {@link #get(long, java.util.concurrent.TimeUnit)} but wraps InterruptedException
064   * and ExecutionException in the unchecked PersistenceException.
065   *
066   * @return The query list result
067   * @throws TimeoutException     if the wait timed out
068   * @throws PersistenceException if a InterruptedException or ExecutionException occurs.
069   */
070  List<T> getUnchecked(long timeout, TimeUnit unit) throws TimeoutException;
071
072}