text:
"""
OpenNebula.org driver.
"""

__docformat__ = 'epytext'

from base64 import b64encode
import hashlib

from libcloud.utils.py3 import ET
from libcloud.utils.py3 import httplib
from libcloud.utils.py3 import next
from libcloud.utils.py3 import b

from libcloud.compute.base import NodeState, NodeDriver, Node, NodeLocation
from libcloud.common.base import ConnectionUserAndKey, XmlResponse
from libcloud.compute.base import NodeImage, NodeSize, StorageVolume
from libcloud.common.types import InvalidCredsError
from libcloud.compute.providers import Provider

__all__ = [
    'ACTION',
    'OpenNebulaResponse',
    'OpenNebulaConnection',
    'OpenNebulaNodeSize',
    'OpenNebulaNetwork',
    'OpenNebulaNodeDriver',
    'OpenNebula_1_4_NodeDriver',
    'OpenNebula_2_0_NodeDriver',
    'OpenNebula_3_0_NodeDriver',
    'OpenNebula_3_2_NodeDriver',
    'OpenNebula_3_8_NodeDriver']

API_HOST = ''
API_PORT = (4567, 443)
API_SECURE = True
API_PLAIN_AUTH = False
DEFAULT_API_VERSION = '3.2'

class ACTION(object):
    """
    All actions, except RESUME, only apply when the VM is in the "Running"
    state.
    """

    STOP = 'STOPPED'
    """
    The VM is stopped, and its memory state stored to a checkpoint file. VM
    state, and disk image, are transferred back to the front-end. Resuming
    the VM requires the VM instance to be re-scheduled.
    """

    SUSPEND = 'SUSPENDED'
    """
    The VM is stopped, and its memory state stored to a checkpoint file. The VM
    state, and disk image, are left on the host to be resumed later. Resuming
    the VM does not require the VM to be re-scheduled. Rather, after
    suspending, the VM resources are reserved for later resuming.
    """

    RESUME = 'RESUME'
    """
    The VM is resumed using the saved memory state from the checkpoint file,
    and the VM's disk image. The VM is either started immediately, or
    re-scheduled depending on how it was suspended.
    """

    CANCEL = 'CANCEL'
    """
    The VM is forcibly shutdown, its memory state is deleted. If a persistent
    disk image was used, that disk image is transferred back to the front-end.
    Any non-persistent disk images are deleted.
    """

    SHUTDOWN = 'SHUTDOWN'
    """
    The VM is gracefully shutdown by sending the ACPI signal. If the VM does
    not shutdown, then it is considered to still be running. If successfully,
    shutdown, its memory state is deleted. If a persistent disk image was used,
    that disk image is transferred back to the front-end. Any non-persistent
    disk images are deleted.
    """

    REBOOT = 'REBOOT'
    """
    Introduced in OpenNebula v3.2.

    The VM is gracefully restarted by sending the ACPI signal.
    """

    DONE = 'DONE'
    """
    The VM is forcibly shutdown, its memory state is deleted. If a persistent
    disk image was used, that disk image is transferred back to the front-end.
    Any non-persistent disk images are deleted.
    """

class OpenNebulaResponse(XmlResponse):
    """
    XmlResponse class for the OpenNebula.org driver.
    """

    def success(self):
        """
        Check if response has the appropriate HTTP response code to be a
        success.

        :rtype:  ``bool``
        :return: True is success, else False.
        """
        i = int(self.status)
        return 200 <= i <= 299

    def parse_error(self):
        """
        Check if response contains any errors.

        @raise: :class:`InvalidCredsError`

        :rtype:  :class:`ElementTree`
        :return: Contents of HTTP response body.
        """
        if int(self.status) == httplib.UNAUTHORIZED:
            raise InvalidCredsError(self.body)
        return self.body

class OpenNebulaConnection(ConnectionUserAndKey):
    """
    Connection class for the OpenNebula.org driver.
    with plain_auth support
    """

    host = API_HOST
    port = API_PORT
    secure = API_SECURE
    plain_auth = API_PLAIN_AUTH
    responseCls = OpenNebulaResponse

    def __init__(self, *args, **kwargs):
        if 'plain_auth' in kwargs:
            self.plain_auth = kwargs.pop('plain_auth')
        super(OpenNebulaConnection, self).__init__(*args, **kwargs)

    def add_default_headers(self, headers):
        """
        Add headers required by the OpenNebula.org OCCI interface.

        Includes adding Basic HTTP Authorization headers for authenticating
        against the OpenNebula.org OCCI interface.

        :type  headers: ``dict``
        :param headers: Dictionary containing HTTP headers.

        :rtype:  ``dict``
        :return: Dictionary containing updated headers.
        """
        if self.plain_auth:
            passwd = self.key
        else:
            passwd = hashlib.sha1(b(self.key)).hexdigest()
        headers['Authorization'] =\
            ('Basic %s' % b64encode(b('%s:%s' % (self.user_id,
                                                 passwd))).decode('utf-8'))
        return headers

class OpenNebulaNodeSize(NodeSize):
    """
    NodeSize class for the OpenNebula.org driver.
    """

    def __init__(self, id, name, ram, disk, bandwidth, price, driver,
                 cpu=None, vcpu=None):
        super(OpenNebulaNodeSize, self).__init__(id=id, name=name, ram=ram,
                                                 disk=disk,
                                                 bandwidth=bandwidth,
                                                 price=price, driver=driver)
        self.cpu = cpu
        self.vcpu = vcpu

    def __repr__(self):
        return (('<OpenNebulaNodeSize: id=%s, name=%s, ram=%s, disk=%s, '
                 'bandwidth=%s, price=%s, driver=%s, cpu=%s, vcpu=%s ...>')
                % (self.id, self.name, self.ram, self.disk, self.bandwidth,
                   self.price, self.driver.name, self.cpu, self.vcpu))

class OpenNebulaNetwork(object):
    """
    Provide a common interface for handling networks of all types.

    Network objects are analogous to physical switches connecting two or
    more physical nodes together. The Network object provides the interface in
    libcloud through which we can manipulate networks in different cloud
    providers in the same way. Network objects don't actually do much directly
    themselves, instead the network driver handles the connection to the
    network.

    You don't normally create a network object yourself; instead you use
    a driver and then have that create the network for you.

    >>> from libcloud.compute.drivers.dummy import DummyNodeDriver
    >>> driver = DummyNodeDriver()
    >>> network = driver.create_network()
    >>> network = driver.list_networks()[0]
    >>> network.name
    'dummy-1'
    """

    def __init__(self, id, name, address, size, driver, extra=None):
        self.id = str(id)
        self.name = name
        self.address = address
        self.size = size
        self.driver = driver
        self.uuid = self.get_uuid()
        self.extra = extra or {}

    def get_uuid(self):
        """
        Unique hash for this network.

        The hash is a function of an SHA1 hash of the network's ID and
        its driver which means that it should be unique between all
        networks. In some subclasses (e.g. GoGrid) there is no ID
        available so the public IP address is used. This means that,
        unlike a properly done system UUID, the same UUID may mean a
        different system install at a different time

        >>> from libcloud.network.drivers.dummy import DummyNetworkDriver
        >>> driver = DummyNetworkDriver()
        >>> network = driver.create_network()
        >>> network.get_uuid()
        'd3748461511d8b9b0e0bfa0d4d3383a619a2bb9f'

        Note, for example, that this example will always produce the
        same UUID!

        :rtype:  ``str``
        :return: Unique identifier for this instance.
        """
        return hashlib.sha1(b("%s:%s" % (self.id,
                                         self.driver.type))).hexdigest()

    def __repr__(self):
        return (('<OpenNebulaNetwork: uuid=%s, name=%s, address=%s, size=%s, '
                 'provider=%s ...>')
                % (self.uuid, self.name, self.address, self.size,
                   self.driver.name))

class OpenNebulaNodeDriver(NodeDriver):
    """
    OpenNebula.org node driver.
    """

    connectionCls = OpenNebulaConnection
    name = 'OpenNebula'
    website = 'http://opennebula.org/'
    type = Provider.OPENNEBULA

    NODE_STATE_MAP = {
        'INIT': NodeState.PENDING,
        'PENDING': NodeState.PENDING,
        'HOLD': NodeState.PENDING,
        'ACTIVE': NodeState.RUNNING,
        'STOPPED': NodeState.TERMINATED,
        'SUSPENDED': NodeState.PENDING,
        'DONE': NodeState.TERMINATED,
        'FAILED': NodeState.TERMINATED}

    def __new__(cls, key, secret=None, api_version=DEFAULT_API_VERSION,
                **kwargs):
        if cls is OpenNebulaNodeDriver:
            if api_version in ['1.4']:
                cls = OpenNebula_1_4_NodeDriver
            elif api_version in ['2.0', '2.2']:
                cls = OpenNebula_2_0_NodeDriver
            elif api_version in ['3.0']:
                cls = OpenNebula_3_0_NodeDriver
            elif api_version in ['3.2']:
                cls = OpenNebula_3_2_NodeDriver
            elif api_version in ['3.6']:
                cls = OpenNebula_3_6_NodeDriver
            elif api_version in ['3.8']:
                cls = OpenNebula_3_8_NodeDriver
                if 'plain_auth' not in kwargs:
                    kwargs['plain_auth'] = cls.plain_auth
                else:
                    cls.plain_auth = kwargs['plain_auth']
            else:
                raise NotImplementedError(
                    "No OpenNebulaNodeDriver found for API version %s" %
                    (api_version))
            return super(OpenNebulaNodeDriver, cls).__new__(cls)

    def create_node(self, **kwargs):
        """
        Create a new OpenNebula node.

        @inherits: :class:`NodeDriver.create_node`

        :keyword networks: List of virtual networks to which this node should
                           connect. (optional)
        :type    networks: :class:`OpenNebulaNetwork` or
            ``list`` of :class:`OpenNebulaNetwork`
        """
        compute = ET.Element('COMPUTE')

        name = ET.SubElement(compute, 'NAME')
        name.text = kwargs['name']

        instance_type = ET.SubElement(compute, 'INSTANCE_TYPE')
        instance_type.text = kwargs['size'].name

        storage = ET.SubElement(compute, 'STORAGE')
        ET.SubElement(storage,
                      'DISK',
                      {'image': '%s' % (str(kwargs['image'].id))})

        if 'networks' in kwargs:
            if not isinstance(kwargs['networks'], list):
                kwargs['networks'] = [kwargs['networks']]

            networkGroup = ET.SubElement(compute, 'NETWORK')
            for network in kwargs['networks']:
                if network.address:
                    ET.SubElement(networkGroup, 'NIC',
                                  {'network': '%s' % (str(network.id)),
                                   'ip': network.address})
                else:
                    ET.SubElement(networkGroup, 'NIC',
                                  {'network': '%s' % (str(network.id))})

        xml = ET.tostring(compute)
        node = self.connection.request('/compute', method='POST',
                                       data=xml).object

        return self._to_node(node)

    def destroy_node(self, node):
        url = '/compute/%s' % (str(node.id))
        resp = self.connection.request(url, method='DELETE')

        return resp.status == httplib.OK

    def list_nodes(self):
        return self._to_nodes(self.connection.request('/compute').object)

    def list_images(self, location=None):
        return self._to_images(self.connection.request('/storage').object)

    def list_sizes(self, location=None):
        """
        Return list of sizes on a provider.

        @inherits: :class:`NodeDriver.list_sizes`

        :return: List of compute node sizes supported by the cloud provider.
        :rtype:  ``list`` of :class:`OpenNebulaNodeSize`
        """
        return [
            NodeSize(id=1,
                     name='small',
                     ram=None,
                     disk=None,
                     bandwidth=None,
                     price=None,
                     driver=self),
            NodeSize(id=2,
                     name='medium',
                     ram=None,
                     disk=None,
                     bandwidth=None,
                     price=None,
                     driver=self),
            NodeSize(id=3,
                     name='large',
                     ram=None,
                     disk=None,
                     bandwidth=None,
                     price=None,
                     driver=self),
        ]

    def list_locations(self):
        return [NodeLocation(0, '', '', self)]

    def ex_list_networks(self, location=None):
        """
        List virtual networks on a provider.

        :param location: Location from which to request a list of virtual
                         networks. (optional)
        :type  location: :class:`NodeLocation`

        :return: List of virtual networks available to be connected to a
                 compute node.
        :rtype:  ``list`` of :class:`OpenNebulaNetwork`
        """
        return self._to_networks(self.connection.request('/network').object)

    def ex_node_action(self, node, action):
        """
        Build action representation and instruct node to commit action.

        Build action representation from the compute node ID, and the
        action which should be carried out on that compute node. Then
        instruct the node to carry out that action.

        :param node: Compute node instance.
        :type  node: :class:`Node`

        :param action: Action to be carried out on the compute node.
        :type  action: ``str``

        :return: False if an HTTP Bad Request is received, else, True is
                 returned.
        :rtype:  ``bool``
        """
        compute_node_id = str(node.id)

        compute = ET.Element('COMPUTE')

        compute_id = ET.SubElement(compute, 'ID')
        compute_id.text = compute_node_id

        state = ET.SubElement(compute, 'STATE')
        state.text = action

        xml = ET.tostring(compute)

        url = '/compute/%s' % compute_node_id
        resp = self.connection.request(url, method='PUT',
                                       data=xml)

        if resp.status == httplib.BAD_REQUEST:
            return False
        else:
            return True

    def _to_images(self, object):
        """
        Request a list of images and convert that list to a list of NodeImage
        objects.

        Request a list of images from the OpenNebula web interface, and
        issue a request to convert each XML object representation of an image
        to a NodeImage object.

        :rtype:  ``list`` of :class:`NodeImage`
        :return: List of images.
        """
        images = []
        for element in object.findall('DISK'):
            image_id = element.attrib['href'].partition('/storage/')[2]
            image = self.connection.request(
                ('/storage/%s' % (image_id))).object
            images.append(self._to_image(image))

        return images

    def _to_image(self, image):
        """
        Take XML object containing an image description and convert to
        NodeImage object.

        :type  image: :class:`ElementTree`
        :param image: XML representation of an image.

        :rtype:  :class:`NodeImage`
        :return: The newly extracted :class:`NodeImage`.
        """
        return NodeImage(id=image.findtext('ID'),
                         name=image.findtext('NAME'),
                         driver=self.connection.driver,
                         extra={'size': image.findtext('SIZE'),
                                'url': image.findtext('URL')})

    def _to_networks(self, object):
        """
        Request a list of networks and convert that list to a list of
        OpenNebulaNetwork objects.

        Request a list of networks from the OpenNebula web interface, and
        issue a request to convert each XML object representation of a network
        to an OpenNebulaNetwork object.

        :rtype:  ``list`` of :class:`OpenNebulaNetwork`
        :return: List of virtual networks.
        """
        networks = []
        for element in object.findall('NETWORK'):
            network_id = element.attrib['href'].partition('/network/')[2]
            network_element = self.connection.request(
                ('/network/%s' % (network_id))).object
            networks.append(self._to_network(network_element))

        return networks

    def _to_network(self, element):
        """
        Take XML object containing a network description and convert to
        OpenNebulaNetwork object.

        Take XML representation containing a network description and
        convert to OpenNebulaNetwork object.

        :rtype:  :class:`OpenNebulaNetwork`
        :return: The newly extracted :class:`OpenNebulaNetwork`.
        """
        return OpenNebulaNetwork(id=element.findtext('ID'),
                                 name=element.findtext('NAME'),
                                 address=element.findtext('ADDRESS'),
                                 size=element.findtext('SIZE'),
                                 driver=self.connection.driver)

    def _to_nodes(self, object):
        """
        Request a list of compute nodes and convert that list to a list of
        Node objects.

        Request a list of compute nodes from the OpenNebula web interface, and
        issue a request to convert each XML object representation of a node
        to a Node object.

        :rtype:  ``list`` of :class:`Node`
        :return: A list of compute nodes.
        """
        computes = []
        for element in object.findall('COMPUTE'):
            compute_id = element.attrib['href'].partition('/compute/')[2]
            compute = self.connection.request(
                ('/compute/%s' % (compute_id))).object
            computes.append(self._to_node(compute))

        return computes

    def _to_node(self, compute):
        """
        Take XML object containing a compute node description and convert to
        Node object.

        Take XML representation containing a compute node description and
        convert to Node object.

        :type  compute: :class:`ElementTree`
        :param compute: XML representation of a compute node.

        :rtype:  :class:`Node`
        :return: The newly extracted :class:`Node`.
        """
        try:
            state = self.NODE_STATE_MAP[compute.findtext('STATE').upper()]
        except KeyError:
            state = NodeState.UNKNOWN

        return Node(id=compute.findtext('ID'),
                    name=compute.findtext('NAME'),
                    state=state,
                    public_ips=self._extract_networks(compute),
                    private_ips=[],
                    driver=self.connection.driver,
                    image=self._extract_images(compute))

    def _extract_networks(self, compute):
        """
        Extract networks from a compute node XML representation.

        Extract network descriptions from a compute node XML representation,
        converting each network to an OpenNebulaNetwork object.

        :type  compute: :class:`ElementTree`
        :param compute: XML representation of a compute node.

        :rtype:  ``list`` of :class:`OpenNebulaNetwork`s.
        :return: List of virtual networks attached to the compute node.
        """
        networks = list()

        network_list = compute.find('NETWORK')
        for element in network_list.findall('NIC'):
            networks.append(
                OpenNebulaNetwork(id=element.attrib.get('network', None),
                                  name=None,
                                  address=element.attrib.get('ip', None),
                                  size=1,
                                  driver=self.connection.driver))

        return networks

    def _extract_images(self, compute):
        """
        Extract image disks from a compute node XML representation.

        Extract image disk descriptions from a compute node XML representation,
        converting the disks to an NodeImage object.

        :type  compute: :class:`ElementTree`
        :param compute: XML representation of a compute node.

        :rtype:  :class:`NodeImage`.
        :return: First disk attached to a compute node.
        """
        disks = list()

        disk_list = compute.find('STORAGE')
        if disk_list is not None:
            for element in disk_list.findall('DISK'):
                disks.append(
                    NodeImage(id=element.attrib.get('image', None),
                              name=None,
                              driver=self.connection.driver,
                              extra={'dev': element.attrib.get('dev', None)}))

        # @TODO: Return all disks when the Node type accepts multiple
        # attached disks per node.
        if len(disks) > 0:
            return disks[0]
        else:
            return None

class OpenNebula_1_4_NodeDriver(OpenNebulaNodeDriver):
    """
    OpenNebula.org node driver for OpenNebula.org v1.4.
    """

    name = 'OpenNebula (v1.4)'

class OpenNebula_2_0_NodeDriver(OpenNebulaNodeDriver):
    """
    OpenNebula.org node driver for OpenNebula.org v2.0 through OpenNebula.org
    v2.2.
    """

    name = 'OpenNebula (v2.0 - v2.2)'

    def create_node(self, **kwargs):
        """
        Create a new OpenNebula node.

        @inherits: :class:`NodeDriver.create_node`

        :keyword networks: List of virtual networks to which this node should
                           connect. (optional)
        :type    networks: :class:`OpenNebulaNetwork` or ``list``
                           of :class:`OpenNebulaNetwork`

        :keyword context: Custom (key, value) pairs to be injected into
                          compute node XML description. (optional)
        :type    context: ``dict``

        :return: Instance of a newly created node.
        :rtype:  :class:`Node`
        """
        compute = ET.Element('COMPUTE')

        name = ET.SubElement(compute, 'NAME')
        name.text = kwargs['name']

        instance_type = ET.SubElement(compute, 'INSTANCE_TYPE')
        instance_type.text = kwargs['size'].name

        disk = ET.SubElement(compute, 'DISK')
        ET.SubElement(disk,
                      'STORAGE',
                      {'href': '/storage/%s' % (str(kwargs['image'].id))})

        if 'networks' in kwargs:
            if not isinstance(kwargs['networks'], list):
                kwargs['networks'] = [kwargs['networks']]

            for network in kwargs['networks']:
                nic = ET.SubElement(compute, 'NIC')
                ET.SubElement(nic, 'NETWORK',
                              {'href': '/network/%s' % (str(network.id))})
                if network.address:
                    ip_line = ET.SubElement(nic, 'IP')
                    ip_line.text = network.address

        if 'context' in kwargs:
            if isinstance(kwargs['context'], dict):
                contextGroup = ET.SubElement(compute, 'CONTEXT')
                for key, value in list(kwargs['context'].items()):
                    context = ET.SubElement(contextGroup, key.upper())
                    context.text = value

        xml = ET.tostring(compute)
        node = self.connection.request('/compute', method='POST',
                                       data=xml).object

        return self._to_node(node)

    def destroy_node(self, node):
        url = '/compute/%s' % (str(node.id))
        resp = self.connection.request(url, method='DELETE')

        return resp.status == httplib.NO_CONTENT

    def list_sizes(self, location=None):
        """
        Return list of sizes on a provider.

        @inherits: :class:`NodeDriver.list_sizes`

        :return: List of compute node sizes supported by the cloud provider.
        :rtype:  ``list`` of :class:`OpenNebulaNodeSize`
        """
        return [
            OpenNebulaNodeSize(id=1,
                               name='small',
                               ram=1024,
                               cpu=1,
                               disk=None,
                               bandwidth=None,
                               price=None,
                               driver=self),
            OpenNebulaNodeSize(id=2,
                               name='medium',
                               ram=4096,
                               cpu=4,
                               disk=None,
                               bandwidth=None,
                               price=None,
                               driver=self),
            OpenNebulaNodeSize(id=3,
                               name='large',
                               ram=8192,
                               cpu=8,
                               disk=None,
                               bandwidth=None,
                               price=None,
                               driver=self),
            OpenNebulaNodeSize(id=4,
                               name='custom',
                               ram=0,
                               cpu=0,
                               disk=None,
                               bandwidth=None,
                               price=None,
                               driver=self),
        ]

    def _to_images(self, object):
        """
        Request a list of images and convert that list to a list of NodeImage
        objects.

        Request a list of images from the OpenNebula web interface, and
        issue a request to convert each XML object representation of an image
        to a NodeImage object.

        :rtype:  ``list`` of :class:`NodeImage`
        :return: List of images.
        """
        images = []
        for element in object.findall('STORAGE'):
            image_id = element.attrib["href"].partition("/storage/")[2]
            image = self.connection.request(
                ("/storage/%s" % (image_id))).object
            images.append(self._to_image(image))

        return images

    def _to_image(self, image):
        """
        Take XML object containing an image description and convert to
        NodeImage object.

        :type  image: :class:`ElementTree`
        :param image: XML representation of an image.

        :rtype:  :class:`NodeImage`
        :return: The newly extracted :class:`NodeImage`.
        """
        return NodeImage(id=image.findtext('ID'),
                         name=image.findtext('NAME'),
                         driver=self.connection.driver,
                         extra={'description': image.findtext('DESCRIPTION'),
                                'type': image.findtext('TYPE'),
                                'size': image.findtext('SIZE'),
                                'fstype': image.findtext('FSTYPE', None)})

    def _to_node(self, compute):
        """
        Take XML object containing a compute node description and convert to
        Node object.

        Take XML representation containing a compute node description and
        convert to Node object.

        :type  compute: :class:`ElementTree`
        :param compute: XML representation of a compute node.

        :rtype:  :class:`Node`
        :return: The newly extracted :class:`Node`.
        """
        try:
            state = self.NODE_STATE_MAP[compute.findtext('STATE').upper()]
        except KeyError:
            state = NodeState.UNKNOWN

        return Node(id=compute.findtext('ID'),
                    name=compute.findtext('NAME'),
                    state=state,
                    public_ips=self._extract_networks(compute),
                    private_ips=[],
                    driver=self.connection.driver,
                    image=self._extract_images(compute),
                    size=self._extract_size(compute),
                    extra={'context': self._extract_context(compute)})

    def _extract_networks(self, compute):
        """
        Extract networks from a compute node XML representation.

        Extract network descriptions from a compute node XML representation,
        converting each network to an OpenNebulaNetwork object.

        :type  compute: :class:`ElementTree`
        :param compute: XML representation of a compute node.

        :rtype:  ``list`` of :class:`OpenNebulaNetwork`
        :return: List of virtual networks attached to the compute node.
        """
        networks = []

        for element in compute.findall('NIC'):
            network = element.find('NETWORK')
            network_id = network.attrib['href'].partition('/network/')[2]

            networks.append(
                OpenNebulaNetwork(id=network_id,
                                  name=network.attrib.get('name', None),
                                  address=element.findtext('IP'),
                                  size=1,
                                  driver=self.connection.driver,
                                  extra={'mac': element.findtext('MAC')}))

        return networks

    def _extract_images(self, compute):
        """
        Extract image disks from a compute node XML representation.

        Extract image disk descriptions from a compute node XML representation,
        converting the disks to an NodeImage object.

        :type  compute: :class:`ElementTree`
        :param compute: XML representation of a compute node.

        :rtype:  ``list`` of :class:`NodeImage`
        :return: Disks attached to a compute node.
        """
        disks = list()

        for element in compute.findall('DISK'):
            disk = element.find('STORAGE')
            image_id = disk.attrib['href'].partition('/storage/')[2]

            if 'id' in element.attrib:
                disk_id = element.attrib['id']
            else:
                disk_id = None

            disks.append(
                NodeImage(id=image_id,
                          name=disk.attrib.get('name', None),
                          driver=self.connection.driver,
                          extra={'type': element.findtext('TYPE'),
                                 'disk_id': disk_id,
                                 'target': element.findtext('TARGET')}))

        # Return all disks when the Node type accepts multiple attached disks
        # per node.
        if len(disks) > 1:
            return disks
        elif len(disks) == 1:
            return disks[0]
        else:
            return None

    def _extract_size(self, compute):
        """
        Extract size, or node type, from a compute node XML representation.

        Extract node size, or node type, description from a compute node XML
        representation, converting the node size to a NodeSize object.

        :type  compute: :class:`ElementTree`
        :param compute: XML representation of a compute node.

        :rtype:  :class:`OpenNebulaNodeSize`
        :return: Node type of compute node.
        """
        instance_type = compute.find('INSTANCE_TYPE')

        try:
            return next((node_size for node_size in self.list_sizes()
                        if node_size.name == instance_type.text))
        except StopIteration:
            return None

    def _extract_context(self, compute):
        """
        Extract size, or node type, from a compute node XML representation.

        Extract node size, or node type, description from a compute node XML
        representation, converting the node size to a NodeSize object.

        :type  compute: :class:`ElementTree`
        :param compute: XML representation of a compute node.

        :rtype:  ``dict``
        :return: Dictionary containing (key, value) pairs related to
                 compute node context.
        """
        contexts = dict()
        context = compute.find('CONTEXT')

        if context is not None:
            for context_element in list(context):
                contexts[context_element.tag.lower()] = context_element.text

        return contexts

class OpenNebula_3_0_NodeDriver(OpenNebula_2_0_NodeDriver):
    """
    OpenNebula.org node driver for OpenNebula.org v3.0.
    """

    name = 'OpenNebula (v3.0)'

    def ex_node_set_save_name(self, node, name):
        """
        Build action representation and instruct node to commit action.

        Build action representation from the compute node ID, the disk image
        which will be saved, and the name under which the image will be saved
        upon shutting down the compute node.

        :param node: Compute node instance.
        :type  node: :class:`Node`

        :param name: Name under which the image should be saved after shutting
                     down the compute node.
        :type  name: ``str``

        :return: False if an HTTP Bad Request is received, else, True is
                 returned.
        :rtype:  ``bool``
        """
        compute_node_id = str(node.id)

        compute = ET.Element('COMPUTE')

        compute_id = ET.SubElement(compute, 'ID')
        compute_id.text = compute_node_id

        disk = ET.SubElement(compute, 'DISK', {'id': str(node.image.id)})

        ET.SubElement(disk, 'STORAGE',
                      {'href': '/storage/%s' % (str(node.image.id)),
                       'name': node.image.name})

        ET.SubElement(disk, 'SAVE_AS', {'name': str(name)})

        xml = ET.tostring(compute)

        url = '/compute/%s' % compute_node_id
        resp = self.connection.request(url, method='PUT',
                                       data=xml)

        if resp.status == httplib.BAD_REQUEST:
            return False
        else:
            return True

    def _to_network(self, element):
        """
        Take XML object containing a network description and convert to
        OpenNebulaNetwork object.

        Take XML representation containing a network description and
        convert to OpenNebulaNetwork object.

        :return: The newly extracted :class:`OpenNebulaNetwork`.
        :rtype:  :class:`OpenNebulaNetwork`
        """
        return OpenNebulaNetwork(id=element.findtext('ID'),
                                 name=element.findtext('NAME'),
                                 address=element.findtext('ADDRESS'),
                                 size=element.findtext('SIZE'),
                                 driver=self.connection.driver,
                                 extra={'public': element.findtext('PUBLIC')})

class OpenNebula_3_2_NodeDriver(OpenNebula_3_0_NodeDriver):
    """
    OpenNebula.org node driver for OpenNebula.org v3.2.
    """

    name = 'OpenNebula (v3.2)'

    def reboot_node(self, node):
        return self.ex_node_action(node, ACTION.REBOOT)

    def list_sizes(self, location=None):
        """
        Return list of sizes on a provider.

        @inherits: :class:`NodeDriver.list_sizes`

        :return: List of compute node sizes supported by the cloud provider.
        :rtype:  ``list`` of :class:`OpenNebulaNodeSize`
        """
        return self._to_sizes(self.connection.request('/instance_type').object)

    def _to_sizes(self, object):
        """
        Request a list of instance types and convert that list to a list of
        OpenNebulaNodeSize objects.

        Request a list of instance types from the OpenNebula web interface,
        and issue a request to convert each XML object representation of an
        instance type to an OpenNebulaNodeSize object.

        :return: List of instance types.
        :rtype:  ``list`` of :class:`OpenNebulaNodeSize`
        """
        sizes = []
        size_id = 1

        attributes = [('name', str, None), ('ram', int, 'MEMORY'),
                      ('cpu', float, None), ('vcpu', float, None),
                      ('disk', str, None), ('bandwidth', float, None),
                      ('price', float, None)]

        for element in object.findall('INSTANCE_TYPE'):
            size_kwargs = {'id': size_id, 'driver': self}
            values = self._get_attributes_values(attributes=attributes,
                                                 element=element)
            size_kwargs.update(values)

            size = OpenNebulaNodeSize(**size_kwargs)
            sizes.append(size)
            size_id += 1

        return sizes

    def _get_attributes_values(self, attributes, element):
        values = {}

        for attribute_name, attribute_type, alias in attributes:
                key = alias if alias else attribute_name.upper()
                value = element.findtext(key)

                if value is not None:
                    value = attribute_type(value)

                values[attribute_name] = value

        return values

class OpenNebula_3_6_NodeDriver(OpenNebula_3_2_NodeDriver):
    """
    OpenNebula.org node driver for OpenNebula.org v3.6.
    """

    name = 'OpenNebula (v3.6)'

    def create_volume(self, size, name, location=None, snapshot=None):
        storage = ET.Element('STORAGE')

        vol_name = ET.SubElement(storage, 'NAME')
        vol_name.text = name

        vol_type = ET.SubElement(storage, 'TYPE')
        vol_type.text = 'DATABLOCK'

        description = ET.SubElement(storage, 'DESCRIPTION')
        description.text = 'Attached storage'

        public = ET.SubElement(storage, 'PUBLIC')
        public.text = 'NO'

        persistent = ET.SubElement(storage, 'PERSISTENT')
        persistent.text = 'YES'

        fstype = ET.SubElement(storage, 'FSTYPE')
        fstype.text = 'ext3'

        vol_size = ET.SubElement(storage, 'SIZE')
        vol_size.text = str(size)

        xml = ET.tostring(storage)
        volume = self.connection.request('/storage',
                                         {'occixml': xml},
                                         method='POST').object

        return self._to_volume(volume)

    def destroy_volume(self, volume):
        url = '/storage/%s' % (str(volume.id))
        resp = self.connection.request(url, method='DELETE')

        return resp.status == httplib.NO_CONTENT

    def attach_volume(self, node, volume, device):
        action = ET.Element('ACTION')

        perform = ET.SubElement(action, 'PERFORM')
        perform.text = 'ATTACHDISK'

        params = ET.SubElement(action, 'PARAMS')

        ET.SubElement(params,
                      'STORAGE',
                      {'href': '/storage/%s' % (str(volume.id))})

        target = ET.SubElement(params, 'TARGET')
        target.text = device

        xml = ET.tostring(action)

        url = '/compute/%s/action' % node.id

        resp = self.connection.request(url, method='POST', data=xml)
        return resp.status == httplib.ACCEPTED

    def _do_detach_volume(self, node_id, disk_id):
        action = ET.Element('ACTION')

        perform = ET.SubElement(action, 'PERFORM')
        perform.text = 'DETACHDISK'

        params = ET.SubElement(action, 'PARAMS')

        ET.SubElement(params,
                      'DISK',
                      {'id': disk_id})

        xml = ET.tostring(action)

        url = '/compute/%s/action' % node_id

        resp = self.connection.request(url, method='POST', data=xml)
        return resp.status == httplib.ACCEPTED

    def detach_volume(self, volume):
        # We need to find the node using this volume
        for node in self.list_nodes():
            if type(node.image) is not list:
                # This node has only one associated image. It is not the one we
                # are after.
                continue

            for disk in node.image:
                if disk.id == volume.id:
                    # Node found. We can now detach the volume
                    disk_id = disk.extra['disk_id']
                    return self._do_detach_volume(node.id, disk_id)

        return False

    def list_volumes(self):
        return self._to_volumes(self.connection.request('/storage').object)

    def _to_volume(self, storage):
        return StorageVolume(id=storage.findtext('ID'),
                             name=storage.findtext('NAME'),
                             size=int(storage.findtext('SIZE')),
                             driver=self.connection.driver)

    def _to_volumes(self, object):
        volumes = []
        for storage in object.findall('STORAGE'):
            storage_id = storage.attrib['href'].partition('/storage/')[2]

            volumes.append(self._to_volume(
                self.connection.request('/storage/%s' % storage_id).object))

        return volumes

class OpenNebula_3_8_NodeDriver(OpenNebula_3_6_NodeDriver):
    """
    OpenNebula.org node driver for OpenNebula.org v3.8.
    """

    name = 'OpenNebula (v3.8)'
    plain_auth = API_PLAIN_AUTH

    def _to_sizes(self, object):
        """
        Request a list of instance types and convert that list to a list of
        OpenNebulaNodeSize objects.

        Request a list of instance types from the OpenNebula web interface,
        and issue a request to convert each XML object representation of an
        instance type to an OpenNebulaNodeSize object.

        :return: List of instance types.
        :rtype:  ``list`` of :class:`OpenNebulaNodeSize`
        """
        sizes = []
        size_id = 1

        attributes = [('name', str, None), ('ram', int, 'MEMORY'),
                      ('cpu', float, None), ('vcpu', float, None),
                      ('disk', str, None), ('bandwidth', float, None),
                      ('price', float, None)]

        for element in object.findall('INSTANCE_TYPE'):
            element = self.connection.request(
                ('/instance_type/%s') % (element.attrib['name'])).object

            size_kwargs = {'id': size_id, 'driver': self}
            values = self._get_attributes_values(attributes=attributes,
                                                 element=element)
            size_kwargs.update(values)

            size = OpenNebulaNodeSize(**size_kwargs)
            sizes.append(size)
            size_id += 1
        return sizes

    def _ex_connection_class_kwargs(self):
        """
        Set plain_auth as an extra :class:`OpenNebulaConnection_3_8` argument

        :return: ``dict`` of :class:`OpenNebulaConnection_3_8` input arguments
        """

        return {'plain_auth': self.plain_auth}


text:
/* jshint node: true */
/* eslint-env node, browser */

var es    = require("event-stream");

module.exports = function() {

    "use strict";

    return es.map( function (file, callback) {

        file.contents = new Buffer(
            file.contents.toString().replace("/** @jsx React.DOM */", "")
        );

        callback(null, file);

    } );

};

redpajama_set_name: RedPajamaGithub


text:
package skinny.engine.async

import skinny.engine.{ Context, RouteTransformer }
import skinny.engine.base.{ SkinnyEngineContextInitializer, RouteRegistryAccessor }
import skinny.engine.routing.Route

/**
 * Before/After DSL for Async web apps.
 */
trait AsyncBeforeAfterDsl { self: RouteRegistryAccessor with SkinnyEngineContextInitializer =>

  /**
   * Adds a filter to run before the route.  The filter only runs if each
   * routeMatcher returns Some.  If the routeMatchers list is empty, the
   * filter runs for all routes.
   */
  def before(transformers: RouteTransformer*)(fun: (Context) => Any): Unit = {
    routes.appendBeforeFilter(Route(transformers, () => fun(context)))
  }

  /**
   * Adds a filter to run after the route.  The filter only runs if each
   * routeMatcher returns Some.  If the routeMatchers list is empty, the
   * filter runs for all routes.
   */
  def after(transformers: RouteTransformer*)(fun: (Context) => Any): Unit = {
    routes.appendAfterFilter(Route(transformers, () => fun(context)))
  }

}


text:
package com.github.jreddit.retrieval.params;

/**
 * Enum to represent comment sorts on Reddit. You see these on a page that lists comments.
 *
 * @author Evin Ugur
 * @author Raul Rene Lepsa
 * @author Simon Kassing
 */
public enum CommentSort {

    NEW("new"),
    HOT("hot"),
    TOP("top"),
    CONTROVERSIAL("controversial"),
    OLD("old"),
    RANDOM("random"),
    CONFIDENCE("confidence");

    private final String value;

    CommentSort(String value) {
        this.value = value;
    }

    public String value() {
        return this.value;
    }

}


text:
module Views.MainContainer {

    export class NestedWithExternalViewModelItem {

        public label: string;
        public color: string;
        constructor(label: string, color: string) {

            this.label = label;
            this.color = color;
        }
    }

    export class MainContainerViewModel {

        public nestedWithExternalViewModelItems: Array<NestedWithExternalViewModelItem>;
        public nestedWithExternalViewModelObservableItems = ko.observableArray<NestedWithExternalViewModelItem>();

        public nestedWithExternalViewModel: NestedWithExternalViewModelItem;
        public nestedWithExternalViewModelObservable = ko.observable<NestedWithExternalViewModelItem>();

        private _itemCounter: number = 0;
        private _itemCreationIntervalHandle: any = null;
        constructor() {
            this.init();
        }

        public init() : void {

            this.nestedWithExternalViewModelItems = [
                new NestedWithExternalViewModelItem("One", "rgb(240, 30, 30)"),
                new NestedWithExternalViewModelItem("Two", "rgb(30, 30, 240)"),
                new NestedWithExternalViewModelItem("Three", "rgb(30, 240, 30)")
            ];

            this.nestedWithExternalViewModel = new NestedWithExternalViewModelItem("Amazing!", "rgb(240, 70, 30)");

            this.nestedWithExternalViewModelObservable(new NestedWithExternalViewModelItem("Amazing!", "rgb(240, 70, 30)"));

            // asynchronous view / view model injection.
            this.createViewItem();
            this._itemCreationIntervalHandle = window.setInterval(this.createViewItem, 2000);
            var _a = window.setInterval(
                () => {
                    window.setInterval(this.deleteItem, 2000);
                    window.clearInterval(_a);

                }, 9000);
        }

        private createViewItem = () => {

            var randGray = () => Math.round(Math.random() * 255);
            var createColor = () => "rgb(" + randGray() + ", " + randGray() + ", " +  randGray() +  ")"

            this._itemCounter++;

            var newView = new NestedWithExternalViewModelItem("Item #" + this._itemCounter, createColor());

            this.nestedWithExternalViewModelObservableItems.unshift(newView);

            var content = ["Fantascic!", "This is great!", "Dreamy!", "Yep!"];
            this.nestedWithExternalViewModelObservable(
                new NestedWithExternalViewModelItem(
                    content[Math.round(Math.random() * (content.length - 1))],
                    createColor()));
        }

        private deleteItem = () => {
            this.nestedWithExternalViewModelObservableItems.pop();
        }
    }
}


text:
<idea-plugin>
  <id>org.ollide.java2smali</id>
  <name>java2smali</name>
  <version>patched</version>
  <vendor email="hg.otothel@gmail.com" url="https://github.com/ollide">ollide</vendor>

  <description><![CDATA[
      Simple plugin to easily compile Java & Kotlin files to smali.
      ]]></description>

  <change-notes><![CDATA[
      version 2.0.1

      Rewrote plugin to be more resilient across build setups (Gradle, Maven, Android)

      Support for IntelliJ IDEA 2020.1 / Android Studio 3.6.3

      New minimum build version: 191 (2019.1)

      version 1.6

      fixed 'Write access is allowed from write-safe contexts only' error

      minimum IDEA version is now 143 (IntelliJ IDEA 15)

      updated baksmali.jar to version 2.2.1

      build plugin with Gradle (4.0) & gradle-intellij-plugin

      continuous integration with Travis CI and AppVeyor

      version 1.5

      kotlin runtime 1.0.3

      updated baksmali.jar to version 2.1.3

      updated dx.jar (Android build-tools 23.0.2)

      version 1.4

      initial support for kotlin files

      all inner classes, including anonymous, are now converted to smali

      fix: dex file was accidentally placed in the IDE's bin directory

      updated baksmali jar to version 2.1.0

      rewrote entire plugin in kotlin

      version 1.3

      disabled plugin for Java files outside of a module

      improved file type detection (ignore caret position)

      updated dx.jar (Android build-tools 22.0.0)

      version 1.2

      fixed NoSuchMethodError on new IntelliJ versions

      updated dx.jar (Android build-tools 21.1.2)

      version 1.1

      added Java module dependency in plugin.xml

      updated dx.jar (Android build-tools 20.0.0)

      version 1.0

      initial release
      ]]>
  </change-notes>

  <idea-version since-build="191"/>
  <depends>com.intellij.modules.java</depends>

  <application-components>

  </application-components>

  <project-components>

  </project-components>

  <actions>
      <action id="generateSmaliCode" class="org.ollide.java2smali.GenerateAction" text="Compile to Smali"
              description="Creates and shows a smali version of this file">
          <add-to-group group-id="BuildMenu" anchor="after" relative-to-action="Compile"/>
      </action>
  </actions>

  <extensions defaultExtensionNs="com.intellij">

  </extensions>
</idea-plugin>


text:
package tp1;

public class TwoPartsMatching extends Matching {

	@Override
	public boolean doesMatch(String text) {
		return doesMatch("([a-zA-Z]{2,5})\\1", text);
	}

}


text:
layout: page
title: Bear Spring Motors Party
date: 2016-05-24
author: Joe Murillo
tags: weekly links, java
status: published
summary: Phasellus rhoncus, neque vitae sollicitudin dictum, dolor ipsum pretium.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 05/13/2016
  endDate: 05/18/2016
  ctyhocn: ORFCPHX
  groupCode: BSMP
published: true
---
Nullam pulvinar mollis dui quis gravida. Aliquam elementum lacinia bibendum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Pellentesque tincidunt ullamcorper commodo. Ut lobortis est eget augue rutrum, non ultricies eros maximus. Nam sit amet tristique risus. Donec a purus consequat, auctor nibh volutpat, hendrerit quam. Curabitur sed ullamcorper ligula. Etiam commodo tortor non ligula commodo sodales. Phasellus iaculis tincidunt lectus, eget tempus arcu egestas ut. Nullam non tincidunt enim. Vestibulum lacus ante, hendrerit non magna vel, ullamcorper faucibus massa. Etiam gravida aliquam lorem sed venenatis.
Morbi maximus ut urna et varius. Nunc sagittis venenatis pulvinar. Aenean fermentum quam id aliquet lobortis. Nullam pharetra augue in dui volutpat, non volutpat diam ullamcorper. Morbi et felis vitae ante ornare sodales. Nunc ac neque id eros finibus placerat a suscipit felis. Sed pretium malesuada hendrerit. Integer sit amet maximus sapien. Curabitur accumsan, magna non dictum commodo, tortor mi laoreet nisi, eu ultricies erat leo pretium nunc. Proin congue risus ut suscipit dapibus.

* Duis porttitor metus eget nisl dictum, nec dignissim sapien bibendum
* Aenean faucibus augue id est rutrum convallis
* Maecenas quis ex efficitur, porta risus eget, tristique turpis.

Duis eget neque turpis. Phasellus eget quam at nulla maximus maximus. Donec sit amet eros id nisl consectetur lobortis vehicula egestas velit. Nunc sit amet fermentum ante. Sed a nisl lacus. Aenean sollicitudin purus eu mollis mattis. In vulputate nunc vitae leo finibus, vitae mollis leo congue.


text:
<Record>
<Term>Adiposis Dolorosa</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<ParentTerm>Lipomatosis</ParentTerm>
<ClassificationPath>Skin and Connective Tissue Diseases/Skin Diseases/Lipomatosis/Adiposis Dolorosa</ClassificationPath>
<ClassificationPath>Nutritional and Metabolic Diseases/Metabolic Diseases/Lipid Metabolism Disorders/Lipomatosis/Adiposis Dolorosa</ClassificationPath>
<BroaderTerm>Lipid Metabolism Disorders</BroaderTerm>
<BroaderTerm>Lipomatosis</BroaderTerm>
<BroaderTerm>Metabolic Diseases</BroaderTerm>
<BroaderTerm>Skin Diseases</BroaderTerm>
<BroaderTerm>Nutritional and Metabolic Diseases</BroaderTerm>
<BroaderTerm>Skin and Connective Tissue Diseases</BroaderTerm>
<BroaderTerm>Adiposis Dolorosa</BroaderTerm>
<Synonym>Dercums Disease</Synonym>
<Synonym>Dercum's Disease</Synonym>
<Synonym>Dercum Disease</Synonym>
<Synonym>Adiposis Dolorosa</Synonym>
<Description>A rare disease characterized by multiple tumor-like fatty deposits that press on nerves in various sites causing pain and weakness. Often these lipoma-like structures are located on the trunk and limbs but sparing the face and hands.</Description>
<Source>MeSH</Source>
</Record>


text:
/**
 * Fichier src/ajax/factory.js
 *
 * @author D'oria Antony
 * @package GRA.ajax
 * @version 1.0
 */
(function (GRA) {

    GRA.ajax = GRA.ajax || {};

    /**
     * Classe Factory
     * Fabrique de requête Ajax
     *
     * @constructor
     */
    GRA.ajax.Factory = function Factory() {
        /**
         * Permet de créer une nouvelle requête Ajax
         *
         * @returns {Ajax}
         */
        this.createRequest = function createRequest() {
            return new GRA.ajax.Ajax();
        };

        /**
         * Permet de créer une nouvelle requête Ajax qui retournera une réponse
         * de type JSON
         *
         * @returns {Ajax}
         */
        this.createJsonRequest = function createJsonRequest() {
            var request = new GRA.ajax.Ajax();
            request.setResponseType(GRA.ajax.const.type.JSON);

            return request;
        };

        /**
         * Permet de créer une nouvelle requête Ajax qui retournera une réponse
         * de type XML
         *
         * @returns {Ajax}
         */
        this.createXmlRequest = function createXmlRequest() {
            var request = new GRA.ajax.Ajax();
            request.setResponseType(GRA.ajax.const.type.XML);

            return request;
        };
    };

    GRA.ajax.Factory = new GRA.ajax.Factory();
}(GRA || {}));


text:
package com.intellij.openapi.wm.impl.status.widget;

import com.intellij.ide.IdeBundle;
import com.intellij.ide.SearchTopHitProvider;
import com.intellij.ide.ui.search.BooleanOptionDescription;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.openapi.wm.StatusBarWidgetFactory;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.psi.codeStyle.WordPrefixMatcher;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.function.Consumer;

public class StatusBarWidgetsOptionProvider implements SearchTopHitProvider {

  @Override
  public void consumeTopHits(@NotNull String pattern, @NotNull Consumer<Object> collector, @Nullable Project project) {
    if (project == null) return;

    StatusBarWidgetsManager manager = project.getService(StatusBarWidgetsManager.class);
    StatusBar statusBar = WindowManager.getInstance().getStatusBar(project);
    if (statusBar == null) return;

    WordPrefixMatcher matcher = new WordPrefixMatcher(pattern);
    for (StatusBarWidgetFactory factory : manager.getWidgetFactories()) {
      if (!factory.isConfigurable() || !factory.isAvailable(project) || !manager.canBeEnabledOnStatusBar(factory, statusBar)) continue;

      String name = IdeBundle.message("label.show.status.bar.widget", factory.getDisplayName());
      if (matcher.matches(name)) collector.accept(new StatusBarWidgetOption(factory, name));
    }
  }

  private static class StatusBarWidgetOption extends BooleanOptionDescription {
    private final StatusBarWidgetFactory myWidgetFactory;

    private StatusBarWidgetOption(StatusBarWidgetFactory factory, @Nls String name) {
      super(name, "statusBar.show.widget." + factory.getId());
      myWidgetFactory = factory;
    }

    @Override
    public boolean isOptionEnabled() {
      return ApplicationManager.getApplication().getService(StatusBarWidgetSettings.class).isEnabled(myWidgetFactory);
    }

    @Override
    public void setOptionState(boolean enabled) {
      ApplicationManager.getApplication().getService(StatusBarWidgetSettings.class).setEnabled(myWidgetFactory, enabled);
      for (Project project : ProjectManager.getInstance().getOpenProjects()) {
        project.getService(StatusBarWidgetsManager.class).updateWidget(myWidgetFactory);
      }
    }
  }
}


text:
<!DOCTYPE html>
<html lang="en-us">

{% include head.html %}

<body class="layout-reverse">

  {% include sidebar.html %}

  <div class="content container">
    {{ content }}
  </div>

</body>

</html>


text:
package cn.wizzer.app.web.commons.shiro.filter;

import cn.wizzer.framework.shiro.token.CaptchaToken;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.nutz.mvc.ActionContext;
import org.nutz.mvc.ActionFilter;
import org.nutz.mvc.View;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by wizzer on 2017/1/10.
 */
public class PlatformAuthenticationFilter extends FormAuthenticationFilter implements ActionFilter {

    private String captchaParam = "platformCaptcha";

    public String getCaptchaParam() {
        return captchaParam;
    }

    protected String getCaptcha(ServletRequest request) {
        return WebUtils.getCleanParam(request, getCaptchaParam());
    }

    protected AuthenticationToken createToken(HttpServletRequest request) {
        String username = getUsername(request);
        String password = getPassword(request);
        String captcha = getCaptcha(request);
        boolean rememberMe = isRememberMe(request);
        String host = getHost(request);
        return new CaptchaToken(username, password, rememberMe, host, captcha);
    }

    public View match(ActionContext actionContext) {
        HttpServletRequest request = actionContext.getRequest();
        AuthenticationToken authenticationToken = createToken(request);
        request.setAttribute("loginToken", authenticationToken);
        return null;
    }
}


text:
#include <string.h>
#include <dirent.h>
#include <dlfcn.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include <keytouchd.h>

static void add_plugin (KeytouchPlugin *plugin, KTPluginList *plugin_list);
static KeytouchPlugin *load_plugin (char *file_name);
static void read_plugin_dir (char *dir, KTPluginList *plugin_list);
static int always_true (const struct dirent *file);

KTPluginFunction
*get_plugin_function (	char	*plugin_name,
			char	*function_name )
/*
Input:
	plugin_name	- The name of the plugin to find
	function_name	- The function in the plugin to find
Output:
	-
Global:
	plugin_list	- List containing al available plugins
Returns:
	A pointer to the KTPluginFunction named function_name of the plugin named
	plugin_name. If no such function was found it returns NULL.
Description:
	The function searches for a KTPluginFunction in the list of available
	plugins.
*/
{
	KeytouchPlugin	*plugin;
	int		count;

	plugin = find_plugin(plugin_name);

	/* If the plugin does not exist */
	if (plugin == NULL)
	{
		return (NULL);
	}
	/* Find the function */
	for (count = 0;
	      count < plugin->num_functions &&
	      strcmp(plugin->function[count].name, function_name) != EQUAL;
	     count++)
		; /* NULL Statement */

	/* If the function does not exist */
	if (count == plugin->num_functions)
	{
		return (NULL);
	}
	return (&plugin->function[count]);
}

KeytouchPlugin
*find_plugin (char *plugin_name)
/*
Input:
	plugin_name	- The name of the plugin to find
Output:
	-
Global:
	plugin_list	- List containing al available plugins
Returns:
	A pointer to the KeytouchPlugin named plugin_name. If no such plugin was
	found it returns NULL.
Description:
	The function searches for a KeytouchPlugin in the list of available plugins.
*/
{
	KTPluginListEntry *plugin;

	/* Find the plugin */
	for (plugin = plugin_list.head;
	     plugin != NULL && strcmp(plugin->plugin->info.name, plugin_name) != EQUAL;
	     plugin = plugin->next)
		; /* NULL Statement */

	/* If the plugin does not exist */
	if (plugin == NULL)
	{
		return (NULL);
	}

	return (plugin->plugin);
}

void
add_plugin (	KeytouchPlugin	*plugin,
		KTPluginList	*plugin_list  )
/*
Input:
	plugin		- The plugin to add to plugin_list
Output:
	plugin_list	- plugin is added to this list
Returns:
	-
Description:
	This function adds plugin to plugin_list.
*/
{
	KTPluginListEntry *entry;

	entry = keytouch_malloc(sizeof(KTPluginListEntry));
	entry->plugin = plugin;
	entry->next = NULL;
	if (plugin_list->head == NULL)
	{
		plugin_list->head = plugin_list->tail = entry;
	}
	else
	{
		plugin_list->tail->next = entry;
		plugin_list->tail = entry;
	}
}

int
always_true (const struct dirent *file)
{
	return (TRUE);
}

KeytouchPlugin
*load_plugin (char *file_name)
/*
Input:
	file_name	- The file name of the plugin
Output:
	-
Returns:
	A pointer to the KeytouchPlugin structure if the plugin was succesfully
	loaded, otherwise NULL.
Description:
	This function loads the plugin which file name is file_name.
*/
{
	void		*plugin_file;
	KeytouchPlugin	*plugin;

	/* Open the plugin */
	plugin_file = dlopen(file_name, RTLD_LAZY);
	if (plugin_file == NULL)
	{
		return (NULL);
        }
	/* Get the plugin structure */
	plugin = dlsym(plugin_file, "plugin_struct");
	/* If an error occured or the plugin is already in the list */
	if (dlerror() != NULL || find_plugin(plugin->info.name) != NULL)
	{
		dlclose (plugin); /* Close the opened plugin */
		return (NULL);
	}
	return (plugin);
}

void
read_plugin_dir (	char		*dir,
			KTPluginList	*plugin_list  )
/*
Input:
	dir		- The directory to read the plugins from.
Output:
	plugin_list	- The plugins in dir are added to this list.
Returns:
	-
Description:
	This function reads the plugins from the directory which path is dir and
	adds them to plugin_list.
*/
{
	struct dirent	**file_list;
	int		num_files,
			count;
	KeytouchPlugin	*plugin;
	char		*complete_file_name;

	num_files = scandir (dir, &file_list, always_true, alphasort);
	if (num_files >= 0)
	{
		for (count = 0; count < num_files; count++)
		{
			complete_file_name = keytouch_malloc(strlen(file_list[count]->d_name) +
			                                     strlen(dir) + 2);
			strcpy (complete_file_name, dir);
			strcat (complete_file_name, "/");
			strcat (complete_file_name, file_list[count]->d_name);
			plugin = load_plugin(complete_file_name);
			if (plugin != NULL)
			{
				add_plugin (plugin, plugin_list);
			}
			free (complete_file_name);
		}
	}
	else
	{
		KTError ("Plugin directory '%s' does not exist. "
		         "This program will continue without loading "
			 "the plugins in this directory.", dir);
	}
}

void
read_plugins (KTPluginList *plugin_list)
/*
Input:
	-
Output:
	plugin_list	- The plugins are added to this list.
Returns:
	-
Description:
	This function reads the plugins from the plugin directories and adds them to
	plugin_list.
*/
{
	char	*home_dir,
		*local_plugin_dir;
	int	local_plugin_dir_len;

	read_plugin_dir (PLUGIN_DIR, plugin_list);
	home_dir = getenv("HOME");
	if (home_dir != NULL)
	{
		local_plugin_dir_len = strlen(home_dir)+strlen("/"LOCAL_PLUGIN_DIR);
		local_plugin_dir = keytouch_malloc(local_plugin_dir_len+1);
		strcpy (local_plugin_dir, home_dir);
		strcat (local_plugin_dir, "/"LOCAL_PLUGIN_DIR);
		read_plugin_dir (local_plugin_dir, plugin_list);
		free (local_plugin_dir);
	}
}

void
init_plugins (KTPluginList *plugin_list)
/*
Input:
	-
Output:
	plugin_list	- Initialized empty plugin list.
Returns:
	-
Description:
	This function initializes plugin_list to be empty.
*/
{
	plugin_list->head = plugin_list->tail = NULL;
}


text:
Example App
===

Rails + AngularJS + PostgreSql

[See in action](https://eventsfeed.herokuapp.com)

[Documentation](https://eventsfeed.herokuapp.com/api)

## Usage

~~~
rake db:create db:migrate db:seed
foreman start
~~~


text:
<!DOCTYPE>

    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="/admin/static/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="/admin/static/css/style.css">

    {% block head %}{% endblock %}
    <title>{% block title %}{% endblock %}</title>

          管理
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bar">

          </button>

文章

页面

配置

      {% block content %}
      {% endblock %}


text:
require 'test_helper'

class SiloTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
<?xml version="1.0"?>
<folder name="Types of items"/>


text:
/**
 * 发票领用
 * @class
 * @extends Ext.form.FormPanel
 */
ReceiveInvoicePanel = Ext.extend(CommonInvoicePanel,{
	initComponent:function(){
		ReceiveInvoicePanel.superclass.initComponent.call(this);
		this.items.itemAt(0).title=lsys('TransferInvoice._title');
		this.form.insert(0,{columnWidth:1,layout:'form', labelWidth:120,border:false,items:[
		                        {xtype: 'hidden', name:'transDepotId', value: App.data.optr['dept_id'] },
	     						{xtype:'combo',fieldLabel:lsys('ReceiveInvoice.optrId'),hiddenName:'optrId',allowBlank: false,
	     							store:new Ext.data.JsonStore({
	     								baseParams: {
	     									deptId : App.data.optr['dept_id']
	     								},
	     								autoLoad: true,
	     								url:'resource/Invoice!getByDeptId.action',
	     								fields:['optr_id','optr_name']
	     							}),displayField:'optr_name',valueField:'optr_id',
	     							triggerAction:'all',mode:'local'
	     						}]});
		this.items.itemAt(0).anchor = '100% 25%';
		this.items.itemAt(1).anchor = '100% 75%';
		this.doLayout();
	}
});

ReceiveInvoice = Ext.extend(Ext.Panel,{
	receiveInvoicePanel:null,
	constructor:function(){
		this.receiveInvoicePanel = new ReceiveInvoicePanel("RECEIVE");
		ReceiveInvoice.superclass.constructor.call(this,{
			id:'ReceiveInvoice',
			title:lsys('ReceiveInvoice._title'),
			closable: true,
			border : false ,
			baseCls: "x-plain",
			layout:'border',
			items:[this.receiveInvoicePanel]
		});
	}
});


text:
#include <stdio.h>
#include <string.h>
#include "mbed.h"
#include "greentea-client/test_env.h"
#include "unity/unity.h"
#include "utest/utest.h"

using namespace utest::v1;

// Echo server (echo payload to host)
template<int N>
void test_case_echo_server_x() {
    char _key[11] = {};
    char _value[128] = {};
    const int echo_count = N;
    const char _key_const[] = "echo_count";
    int expected_key = 1;

    greentea_send_kv(_key_const, echo_count);
    // Handshake with host
    do {
        greentea_parse_kv(_key, _value, sizeof(_key), sizeof(_value));
        expected_key = strcmp(_key_const, _key);
    } while (expected_key);
    TEST_ASSERT_EQUAL_INT(echo_count, atoi(_value));

    for (int i=0; i < echo_count; ++i) {
        greentea_parse_kv(_key, _value, sizeof(_key), sizeof(_value));
        greentea_send_kv(_key, _value);
    }
}

utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason) {
    greentea_case_failure_abort_handler(source, reason);
    return STATUS_CONTINUE;
}

Case cases[] = {
    Case("Echo server: x16", test_case_echo_server_x<16>, greentea_failure_handler),
};

utest::v1::status_t greentea_test_setup(const size_t number_of_cases) {
    GREENTEA_SETUP(30, "echo");
    return greentea_test_setup_handler(number_of_cases);
}

Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler);

int main() {
    Harness::run(specification);
}


text:
FROM datt/datt-openjdk7:latest
MAINTAINER John Albietz "inthecloud247@gmail.com"

RUN `# install scala;` \
  \
  `# libjansi + deps needed for scala`; \
  apt-get update; \
  apt-get install -y libhawtjni-runtime-java libjansi-java libjansi-native-java; \
  \
  export SCALA_PKG="scala-2.10.3.deb"; \
  wget http://www.scala-lang.org/files/archive/$SCALA_PKG; \
  dpkg -i $SCALA_PKG; \
  rm -vf $SCALA_PKG; \
  which scala; \
  apt-get clean;

RUN `# install sbt;` \
  export SBT_PKG="sbt.deb"; \
  wget http://repo.scala-sbt.org/scalasbt/sbt-native-packages/org/scala-sbt/sbt/0.13.1/$SBT_PKG; \
  dpkg -i $SBT_PKG; \
  rm -vf $SBT_PKG; \
  which sbt;

# update java, scala and sbt jars by running the commands

RUN java -version

# the `true` is needed for the image to build w/o errors.
RUN scala -version || true

RUN sbt update || true

ADD files/ /files/


text:
package com.cinchapi.runway;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * A marker to indicate that a method provides a derived
 * property.
 *

 * A derived property is additional information that is not directly stored in
 * the database, but can be inferred based on {@link Record#intrinsic()
 * intrinsic} properties.
 *

 *
 * @author Jeff Nelson
 */
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Derived {

    /**
     * The name of derived property. By default, the name of the annotated
     * method is used.
     *
     * @return the name of the derived property
     */
    String value() default "";
}


text:
Makes [`libzip`](http://www.nih.at/libzip/) asynchronous by mimicing the `uv_fs_*` APIs.

# Usage

See [`test/test.cpp`](test/test.cpp)

# Testing

```bash
$ ./configure
[...]
$ make test
[...]
* open_failure (0.9ms)
* open_from_fd (0.9ms)
* missing_file (0.2ms)
* read_file (0.2ms)
```

**Note: This binding is not complete and only provides read-only support.**


text:
package edu.byu.support.feature;

import android.os.Bundle;
import android.os.Parcel;
import android.support.annotation.NonNull;

import edu.byu.support.ByuParcelable;
import edu.byu.support.adapter.ByuSearchableRecyclerAdapter;

/**
 * Created by benjamin on 5/12/16
 */
public class Feature extends ByuParcelable implements ByuSearchableRecyclerAdapter.Queryable, Comparable<Feature> {
    private int imageResId;
    private String id;
    private String name;
    private String description;
    private String activityName;
	private boolean requiresInternet;
	private boolean requiresLogin;
	private String groGroup;

    public Feature(int imageResId, String id, String name, String description, String activityName, boolean requiresInternet, boolean requiresLogin, String groGroup) {
        this.imageResId = imageResId;
        this.id = id;
        this.name = name;
        this.description = description;
        this.activityName = activityName;
		this.requiresInternet = requiresInternet;
		this.requiresLogin = requiresLogin;
		this.groGroup = groGroup;
	}

	protected Feature(Parcel in) {
		imageResId = in.readInt();
		id = in.readString();
		name = in.readString();
		description = in.readString();
		activityName = in.readString();
		requiresInternet = in.readByte() != 0;
		requiresLogin = in.readByte() != 0;
		groGroup = in.readString();
	}

	@Override
	public void writeToParcel(Parcel parcel, int flags) {
		parcel.writeInt(imageResId);
		parcel.writeString(id);
		parcel.writeString(name);
		parcel.writeString(description);
		parcel.writeString(activityName);
		parcel.writeByte((byte) (requiresInternet ? 1 : 0));
		parcel.writeByte((byte) (requiresLogin ? 1 : 0));
		parcel.writeString(groGroup);
	}

	public static final Creator<Feature> CREATOR = new Creator<Feature>() {
		@Override
		public Feature createFromParcel(Parcel in) {
			return new Feature(in);
		}

		@Override
		public Feature[] newArray(int size) {
			return new Feature[size];
		}
	};

	public int getImageResId() {
        return imageResId;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public String getActivityName() {
        return activityName;
    }

	public boolean requiresInternet() {
		return requiresInternet;
	}

	public boolean requiresLogin() {
		return requiresLogin;
	}

	public String getGroGroup() {
		return groGroup;
	}

    @Override
    public boolean matchesQuery(String lowerCaseQuery) {
		return name.toLowerCase().contains(lowerCaseQuery) || description.toLowerCase().contains(lowerCaseQuery);
    }

    @Override
    public int compareTo(@NonNull Feature another) {
        return getName().toLowerCase().compareTo(another.getName().toLowerCase());
    }

    public static Feature fromMetaData(Bundle metaData) {
        return new Feature(
				metaData.getInt("icon"),
				metaData.getString("featureId"),
				metaData.getString("name"),
				metaData.getString("description"),
				metaData.getString("activityName"),
				metaData.getBoolean("requiresInternet", true),
				metaData.getBoolean("requiresLogin", true),
				metaData.getString("groGroup"));
    }
}


text:
<?php

namespace Widget\Support\Scopes;

use Illuminate\Database\Eloquent\Builder;

trait WidgetTrait
{
	/**
	 * Check if viewable by the user.
	 *
	 * @return boolean
	 */
	public function isViewable()
	{
		if (user() && user()->hasRole($this->roles()->pluck('code', 'name')->toArray())) {
			return true;
		}

		return false;
	}
}


text:
{% extends "conference/user_panel/base.html" %}

{% load cms_tags crispy_forms_tags %}

{% block breadcrumbs %}
{{ block.super }}

    Profile settings

{% endblock breadcrumbs %}

{% block user_content %}

        {% if profile_form.errors %}
            {% for field in profile_form %}
                {% for error in field.errors %}

                    {{ error|escape }}

                {% endfor %}
            {% endfor %}
        {% endif %}
        <form method="POST" action="." enctype="multipart/form-data">
            {% csrf_token %}
            {% crispy profile_form %}
        </form>

{% endblock %}

{% block morecss %}

{% endblock %}


text:
package xyz.danielcooper.emergencynotifier;

import android.app.LoaderManager;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;

import java.util.ArrayList;

/**
 * Created by Dan on 11/01/2016.
 */
public class ContactsLoader implements LoaderManager.LoaderCallbacks<Cursor> {

    Context context;

    public static final String TAG = "ContactsLoader";
    public static final String QUERY_KEY = "QueryKey";

    public ContactsLoader(Context context) { context = context; }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {

        String query = args.getString(QUERY_KEY);
        Uri uri = Uri.withAppendedPath(
                ContactsContract.CommonDataKinds.Contactables.CONTENT_FILTER_URI, query);

        String selection =
                ContactsContract.CommonDataKinds.Contactables.HAS_PHONE_NUMBER + " = " + 1;

        String sortBy = ContactsContract.CommonDataKinds.Contactables.LOOKUP_KEY;

        return new CursorLoader(
                context,
                uri,
                null,
                selection,
                null,
                sortBy);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

        if (context == null) {
            throw new IllegalArgumentException("context");
        }

        ArrayList<Person> contacts = ((SelectContactsActivity)context).Contacts;

        if(contacts == null) {
            throw new IllegalArgumentException("contacts");
        }

        if (data.getCount() == 0) {
            return;
        }

        int nameColumnIndex = data.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.DISPLAY_NAME);
        int phoneColumnIndex = data.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
        int typeColumnIndex = data.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.MIMETYPE);
        int lookupColumnIndex = data.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.LOOKUP_KEY);

        data.moveToFirst();

        String lookupKey = "";
        String displayName = "";

        do {
            Person contact = new Person();

            String currentLookupKey = data.getString(lookupColumnIndex);
            if (!lookupKey.equals(currentLookupKey)) {
                displayName = data.getString(nameColumnIndex);
                lookupKey = currentLookupKey;
            }

            contact.setName(displayName);

            String mimeType = data.getString(typeColumnIndex);

            if (mimeType.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) {
               contact.setNumber(data.getString(phoneColumnIndex));

                contacts.add(contact);
            }
        } while (data.moveToNext());
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {

    }
}


text:
<?php

declare(strict_types=1);

namespace Service\TaskHandler;

use App\Api\Issue\NullIssueApi;
use App\Api\PullRequest\NullPullRequestApi;
use App\Entity\Task;
use App\Service\RepositoryProvider;
use App\Service\TaskHandler\CloseDraftHandler;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;

class CloseDraftHandlerTest extends TestCase
{
    public function testHandleStillInDraft()
    {
        $prApi = $this->getMockBuilder(NullPullRequestApi::class)
            ->disableOriginalConstructor()
            ->setMethods(['show'])
            ->getMock();
        $prApi->expects($this->once())->method('show')->willReturn(['draft' => true]);

        $issueApi = $this->getMockBuilder(NullIssueApi::class)
            ->disableOriginalConstructor()
            ->setMethods(['close'])
            ->getMock();
        $issueApi->expects($this->once())->method('close');

        $repoProvider = new RepositoryProvider(['carsonbot-playground/symfony' => []]);

        $handler = new CloseDraftHandler($prApi, $issueApi, $repoProvider, new NullLogger());
        $handler->handle(new Task('carsonbot-playground/symfony', 4711, Task::ACTION_CLOSE_DRAFT, new \DateTimeImmutable()));
    }

    public function testHandleNotDraft()
    {
        $prApi = $this->getMockBuilder(NullPullRequestApi::class)
            ->disableOriginalConstructor()
            ->setMethods(['show'])
            ->getMock();
        $prApi->expects($this->once())->method('show')->willReturn(['draft' => false]);

        $issueApi = $this->getMockBuilder(NullIssueApi::class)
            ->disableOriginalConstructor()
            ->setMethods(['close'])
            ->getMock();
        $issueApi->expects($this->never())->method('close');

        $repoProvider = new RepositoryProvider(['carsonbot-playground/symfony' => []]);

        $handler = new CloseDraftHandler($prApi, $issueApi, $repoProvider, new NullLogger());
        $handler->handle(new Task('carsonbot-playground/symfony', 4711, Task::ACTION_CLOSE_DRAFT, new \DateTimeImmutable()));
    }
}


text:
package com.mattunderscore.tcproxy.selector.general;

import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;

import java.nio.channels.ClosedChannelException;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;

import com.mattunderscore.tcproxy.io.selection.IOSelector;
import com.mattunderscore.tcproxy.io.socket.IOServerSocketChannel;
import com.mattunderscore.tcproxy.selector.SelectionRunnable;

/**
 * Unit tests for {@link IOServerSocketChannelRegistrationRequest}.
 *
 * @author Matt Champion on 14/11/2015
 */
public final class IOServerSocketChannelRegistrationRequestTest {
    @Mock
    private IOSelector selector;
    @Mock
    private IOServerSocketChannel channel;
    @Mock
    private SelectionRunnable<IOServerSocketChannel> task;

    @Before
    public void setUp() {
        initMocks(this);
    }

    @Test
    public void register() throws ClosedChannelException {
        final RegistrationRequest registrationRequest = new IOServerSocketChannelRegistrationRequest(channel, task);

        registrationRequest.register(selector);

        verify(channel).register(eq(selector), isA(IOServerSocketChannelRegistration.class));
    }
}


text:
import React from 'react';
import styled from 'styled-components';
import Card from './Card';
import getCardFromLocation from '../modules/cardFromLocationBuilder.module';
import home from '../data/home.json';

const border = `
  border: 1px solid #d8d8d8;
  background-color: white;
  border-radius: 8px;
`;

const position = px => `
    top: 0px;
    left: ${px}px;
    right: ${px}px;
    bottom: -${px}px;
`;

const getFakeCards = (cardCount) => {
  const middleCard = `
    &::before{
      content: '';
      position: absolute;
      ${position(5)}
      ${border}
      z-index: -1;
    }
    `;
  const bottomCard = `
    &::after{
      content: '';
      position: absolute;
      ${position(15)}
      ${border}
      z-index: -2;
    }
    `;

  if (cardCount > 2) {
    return `${middleCard}${bottomCard}`;
  } else if (cardCount > 1) {
    return middleCard;
  }

  return '';
};

const CardContainerStyle = styled.div`
  font-family: Roboto, sans-serif;
  margin: 0 auto;
  width: 400px;
  height: 500px;
  position: relative;
  ${props => getFakeCards(props.cardCount)}
`;

const NextCard = styled(Card)`
  position: absolute;
  top: 0;
  z-index: -1;
`;

const HomeCard = styled(Card)`
  position: absolute;
  top: 0;
  z-index: -2;
`;

const CardContainer = ({ cardCount, currentCard, nextCard, animation }) => (
  <CardContainerStyle cardCount={cardCount}>
    {currentCard && <Card currentCard={currentCard} animation={animation} />}
    {nextCard && <NextCard currentCard={nextCard} />}
    {<HomeCard currentCard={getCardFromLocation(home)} />}
  </CardContainerStyle>
);

module.exports = CardContainer;


text:
/**
 * PhotonUI - Javascript Web User Interface.
 *
 * @module PhotonUI
 * @main PhotonUI
 * @namespace photonui
 */

var photonui = {};

// Include libraries in module.
photonui.lib = {};
photonui.lib.Class = require("abitbol");
photonui.lib.KeyboardJS = require("keyboardjs");
photonui.lib.Stone = require("stonejs");
photonui.lib.uuid = require("uuid");

// Base
photonui.Helpers = require("./helpers.js");
photonui.Base = require("./base.js");
photonui.Widget = require("./widget.js");

// Methods
photonui.domInsert = photonui.Widget.domInsert;
photonui.getWidget = photonui.Widget.getWidget;

// Widgets
photonui.FileManager = require("./nonvisual/filemanager.js");
photonui.Translation = require("./nonvisual/translation.js");
photonui.AccelManager = require("./nonvisual/accelmanager.js");
photonui.MouseManager = require("./nonvisual/mousemanager.js");
photonui.BaseIcon = require("./visual/baseicon.js");
photonui.FAIcon = require("./visual/faicon.js");
photonui.Image = require("./visual/image.js");
photonui.SpriteSheet = require("./nonvisual/spritesheet.js");
photonui.SpriteIcon = require("./visual/spriteicon.js");
photonui.Canvas = require("./visual/canvas.js");
photonui.Label = require("./visual/label.js");
photonui.Text = require("./visual/text.js");
photonui.ProgressBar = require("./visual/progressbar.js");
photonui.Separator = require("./visual/separator.js");
photonui.Button = require("./interactive/button.js");
photonui.ColorButton = require("./composite/colorbutton.js");
photonui.CheckBox = require("./interactive/checkbox.js");
photonui.Switch = require("./interactive/switch.js");
photonui.ToggleButton = require("./interactive/togglebutton.js");
photonui.Color = require("./nonvisual/color.js");
photonui.ColorPalette = require("./interactive/colorpalette.js");
photonui.ColorPicker = require("./interactive/colorpicker.js");
photonui.Field = require("./interactive/field.js");
photonui.NumericField = require("./interactive/numericfield.js");
photonui.TextAreaField = require("./interactive/textareafield.js");
photonui.TextField = require("./interactive/textfield.js");
photonui.Select = require("./composite/select.js");
photonui.FontSelect = require("./composite/fontselect.js");
photonui.Slider = require("./interactive/slider.js");
photonui.Container = require("./container/container.js");
photonui.Layout = require("./layout/layout.js");
photonui.BoxLayout = require("./layout/boxlayout.js");
photonui.FluidLayout = require("./layout/fluidlayout.js");
photonui.GridLayout = require("./layout/gridlayout.js");
photonui.Menu = require("./layout/menu.js");
photonui.MenuItem = require("./container/menuitem.js");
photonui.SubMenuItem = require("./container/submenuitem.js");
photonui.Viewport = require("./container/viewport.js");
photonui.BaseWindow = require("./container/basewindow.js");
photonui.Window = require("./container/window.js");
photonui.PopupWindow = require("./container/popupwindow.js");
photonui.Dialog = require("./container/dialog.js");
photonui.ColorPickerDialog = require("./composite/colorpickerdialog.js");
photonui.PopupMenu = require("./composite/popupmenu.js");
photonui.TabItem = require("./container/tabitem.js");
photonui.TabLayout = require("./layout/tablayout.js");
// [generator]
// DO NOT MODIFY/REMOVE THE PREVIOUS COMMENT, IT IS USED BY THE WIDGET GENERATOR!

module.exports = photonui;


text:
package com.alorma.github.ui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.BounceInterpolator;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.alorma.github.R;
import com.alorma.github.utils.AttributesUtils;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.nineoldandroids.animation.IntEvaluator;
import com.nineoldandroids.animation.ValueAnimator;

/**
 * Created by Bernat on 26/08/2014.
 */
public class FABCenterLayout extends RelativeLayout implements ViewTreeObserver.OnScrollChangedListener {

	private static final long FOLD_DURATION = 500;
	private FABScrollContentListener fabScrollContentListener;
	private FloatingActionButton fabView;
	private int topId;
	private OnClickListener fabClickListener;
	private boolean fabVisible;
	private String fabTag;
	private View scrolledChild;
	private boolean forceVisbility;
	private int scrollableId;
	private boolean isFold = true;
	private View topView;
	private int topFoldedSize;
	private int topUnfoldedSize;

	public FABCenterLayout(Context context) {
		super(context);
		init(null, 0);
	}

	public FABCenterLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(attrs, 0);
	}

	public FABCenterLayout(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(attrs, defStyle);
	}

	private void init(AttributeSet attrs, int defStyle) {
		isInEditMode();

		TypedValue tv = new TypedValue();

		topFoldedSize = (int) (56 * getResources().getDisplayMetrics().density);
		if (getContext().getTheme().resolveAttribute(R.attr.actionBarSize, tv, true)) {
			topFoldedSize = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
		}

		topUnfoldedSize = topFoldedSize * 2;

		if (attrs != null) {
			TypedArray attr = getContext().obtainStyledAttributes(attrs, R.styleable.FABCenterLayout, defStyle, 0);

			if (attr.hasValue(R.styleable.FABCenterLayout_top_id)) {
				topId = attr.getResourceId(R.styleable.FABCenterLayout_top_id, 0);
				if (topId != 0) {
					fabVisible = true;
					createFabView();
				}
			}

			if (attr.hasValue(R.styleable.FABCenterLayout_scrollable_id)) {
				scrollableId = attr.getResourceId(R.styleable.FABCenterLayout_scrollable_id, 0);
			}

			if (attr.hasValue(R.styleable.FABCenterLayout_folded_size)) {
				topFoldedSize = attr.getDimensionPixelOffset(R.styleable.FABCenterLayout_folded_size, topFoldedSize);
			}

			if (attr.hasValue(R.styleable.FABCenterLayout_unfolded_size)) {
				topUnfoldedSize = attr.getDimensionPixelOffset(R.styleable.FABCenterLayout_unfolded_size, topUnfoldedSize);
			}
			attr.recycle();
		}
	}

	private void addChildScrollListener(View child) {
		if (child != null && fabView != null && child != fabView && child.getId() != topId && child.getId() == scrollableId) {
			scrolledChild = child;
			child.getViewTreeObserver().addOnScrollChangedListener(this);
		}
	}

	private void createFabView() {
		fabView = (FloatingActionButton) LayoutInflater.from(getContext()).inflate(R.layout.fab, this, false);

		int accent = AttributesUtils.getAttributeId(getContext(), R.attr.colorAccent);
		fabView.setColorNormal(getResources().getColor(accent));

		fabView.setOnClickListener(fabClickListener);
		setFabTag();
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		super.onLayout(changed, l, t, r, b);

		if (topView != null && fabVisible && fabView != null) {

			int bottom = topView.getBottom();

			if (bottom > 0) {
				int int16 = getResources().getDimensionPixelOffset(R.dimen.gapLarge);
				fabView.layout(r - fabView.getWidth() - int16, bottom - fabView.getHeight() / 2, r - int16, bottom + fabView.getHeight() / 2);
				removeView(fabView);
				addView(fabView);

				ViewCompat.setElevation(fabView, 6f);
			}
		}
	}

	public void setFabIcon(Drawable drawable) {
		if (fabView != null) {
			fabView.setImageDrawable(drawable);
		}
	}

	public void setFabColor(int color) {
		if (fabView != null) {
			fabView.setColorNormal(color);
		}
	}

	public void setFabColorPressed(int color) {
		if (fabView != null) {
			fabView.setColorPressed(color);
		}
	}

	public void setFabClickListener(OnClickListener fabClickListener, final String tag) {
		this.fabClickListener = fabClickListener;
		this.fabTag = tag;
		if (fabView != null) {
			fabView.setOnClickListener(fabClickListener);
			setFabTag();
		}
	}

	private void setFabTag() {
		if (fabView != null && fabTag != null) {
			fabView.setTag(fabTag);
			fabView.setOnLongClickListener(new OnLongClickListener() {
				@Override
				public boolean onLongClick(View v) {
					Toast.makeText(v.getContext(), String.valueOf(v.getTag()), Toast.LENGTH_SHORT).show();
					return true;
				}
			});
		}
	}

	public void setFabViewVisibility(int visibility, boolean forced) {
		forceVisbility = forced;
		if (fabView != null) {
			fabView.setVisibility(visibility);
		}
	}

	@Override
	public void onScrollChanged() {

		if (!forceVisbility && scrolledChild != null) {
			int scrollY = scrolledChild.getScrollY();

			int fabViewHeight = fabView != null ? fabView.getHeight() : 0;
			int minimScroll = fabViewHeight / 2;

			setFabClickListener(scrollY < minimScroll ? fabClickListener : null, "");

			float alpha = ((float) (255 - scrollY)) / 255f;

			if (scrollY < minimScroll) {
				if (fabView != null) {
					ViewCompat.setAlpha(fabView, alpha);
				}
				setFabViewVisibility(View.VISIBLE, false);
			} else {
				setFabViewVisibility(View.INVISIBLE, false);
			}

			if (fabScrollContentListener != null) {
				fabScrollContentListener.onScrollFactor(scrollY, alpha);
			}
		}
	}

	public void setFabScrollContentListener(FABScrollContentListener fabScrollContentListener) {
		this.fabScrollContentListener = fabScrollContentListener;
	}

	public void removeFab() {
		if (fabView != null) {
			removeView(fabView);
			fabView = null;
		}
	}

	public int getFabId() {
		return fabView != null ? fabView.getId() : 0;
	}

	public void setFold(boolean fold) {
		this.isFold = fold;
		if (fold) {
			fold();
		} else {
			unfold();
		}
	}

	public boolean isFold() {
		return isFold;
	}

	public void fold() {
		animFold(topFoldedSize);
	}

	public void unfold() {
		animFold(topUnfoldedSize);
	}

	private void animFold(int finalValue) {
		ValueAnimator animator = ValueAnimator.ofInt(topView.getMeasuredHeight(), finalValue);
		animator.addUpdateListener(new TopFoldAnimatorListener(topView));
		animator.setDuration(FOLD_DURATION);
		animator.setInterpolator(new AccelerateDecelerateInterpolator());
		animator.start();

	}

	public interface FABScrollContentListener {
		void onScrollFactor(int alpha, float factor);
	}

	@Override
	public void addView(View child, int index, ViewGroup.LayoutParams params) {
		super.addView(child, index, params);
		if (child.getId() == scrollableId) {
			scrolledChild = child;
			addChildScrollListener(scrolledChild);
		} else if (child.getId() == topId) {
			topView = child;
		} else {
			View viewTop = child.findViewById(topId);
			if (viewTop != null) {
				topView = viewTop;
			}
			View viewScroll = child.findViewById(scrollableId);
			if (viewScroll != null) {
				scrolledChild = viewScroll;
			}
		}
	}

	private class TopFoldAnimatorListener implements ValueAnimator.AnimatorUpdateListener {
		private View animatedView;

		private TopFoldAnimatorListener(View animatedView) {
			this.animatedView = animatedView;
		}

		@Override
		public void onAnimationUpdate(ValueAnimator animation) {
			int height = (Integer) animation.getAnimatedValue();
			ViewGroup.LayoutParams params = animatedView.getLayoutParams();
			params.height = height;
			animatedView.setLayoutParams(params);
		}
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>@yield('title')</title>

    <link href="{{ $bootstrap_css }}" rel="stylesheet">

    <link rel="stylesheet" href="{{ $font_awesome_css }}">

    <link href="{{ $res_root }}/css/admin/sb-admin-2.css" rel="stylesheet">
    <link href="{{ $res_root }}/css/admin/template.css" rel="stylesheet" type="text/css">
    @yield('css')

            @include('admin.navigator')
            @include('admin.sidebar')

            @yield('container')

    @yield('script')


text:
package de.uniulm.omi.cloudiator.axe.aggregator.communication.rmi.observer;

import de.uniulm.omi.cloudiator.axe.aggregator.communication.rmi.observer.internal.ExternalReferenced;
import de.uniulm.omi.cloudiator.axe.aggregator.communication.rmi.observer.internal.NetworkParameter;
import de.uniulm.omi.cloudiator.axe.aggregator.communication.rmi.observer.internal.ObserverParameter;
import de.uniulm.omi.cloudiator.axe.aggregator.communication.rmi.observer.internal.ThresholdParameter;
import de.uniulm.omi.cloudiator.axe.aggregator.entities.FormulaOperator;

import java.io.Serializable;
import java.rmi.Remote;

/**
 * Created by Frank on 26.08.2015.
 */
public interface ZeroMqObserverParameter extends
        ObserverParameter,
        ExternalReferenced,
        NetworkParameter,
        ThresholdParameter {
}


text:
package bay

import (
	"time"
)

type webhook struct {
	Ref        string     `json:"ref"`
	Before     string     `json:"before"`
	After      string     `json:"after"`
	Created    bool       `json:"created"`
	Deleted    bool       `json:"deleted"`
	Forced     bool       `json:"forced"`
	Commits    []commit   `json:"commits"`
	Repository repository `json:"repository"`
}

type commit struct {
	Id        string    `json:"id"`
	Distinct  bool      `json:"distinct"`
	Message   string    `json:"message"`
	Timestamp time.Time `json:"timestamp"`
	URL       string    `json:"url"`
	Auther    User      `json:"author"`
	Committer User      `json:"committer"`
}

type repository struct {
	Id       int    `json:"id"`
	Name     string `json:"name"`
	FullName string `json:"full_name"`
	Owner    User   `json:"owner"`
	HtmlURL  string `json:"html_url"`
	URL      string `json:"url"`
}

type User struct {
	Name     string `json:"name"`
	Email    string `json:"email"`
	Username string `json:"username"`
}


text:
package com.ebay.pulsar.analytics.query.result;

import java.util.List;
import java.util.Map;

/**
 *
 * @author mingmwang
 *
 */
public class ColumnNameRevisor implements ResultRevisor {
	private List<String> dimensions;
	private Map<String, String> nameAliasMap;

	public ColumnNameRevisor(List<String> dimensions,
			Map<String, String> nameAliasMap) {
		this.dimensions = dimensions;
		this.nameAliasMap = nameAliasMap;
	}

	@Override
	public void revise(ResultNode node) {
		if(dimensions!=null && dimensions.contains(node.getName())){
			 String newColumnName = replaceColumnToUserRequest(node.getName(), nameAliasMap);
			 node.setName(newColumnName);
		}
	}

	private String replaceColumnToUserRequest(String columnName, Map<String, String> nameAliasMap) {
		if(nameAliasMap != null && nameAliasMap.get(columnName) != null){
			return nameAliasMap.get(columnName);
		}
		return columnName;
	}
}