text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textview"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:text="Just a textView" />

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="90px"
        android:layout_below="@+id/textview"
        android:onClick="reset"
        android:text="RESET" />

    <!--
    Remember to create a VideoView container because FVView is added in its
    original parent, when coming back from fullscreen.
    So, is important to put VideoView inside a View container with fixed size.
    I'm going to change it in near future. But, it will not affect this container
    implementation.
    -->
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/button">

        <com.github.rtoshiro.view.video.FullscreenVideoLayout
            android:id="@+id/videoview"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </FrameLayout>

</RelativeLayout>


text:
import authorize from '../middlewares/authorization';
import allowUser from '../middlewares/allowUser';
import Recipe from '../controllers/recipeControl';
import Review from '../controllers/reviewControl';
import Vote from '../controllers/voteControl';
import Favourite from '../controllers/favouriteControl';
import userRoutes from './user';
import Validate from '../functions/validate';

const router = (app) => {
  app.get('/api', (req, res) => {
    res.status(200)
      .json({ message: 'Welcome to my api' });
  });

  userRoutes(app);

  app.post('/api/v1/recipes', authorize, Validate.recipe, Recipe.addRecipe); // auth user adds recipe
  app.post('/api/v1/search', Recipe.search); // Search recipe
  app.put('/api/v1/recipes/:recipeId', authorize, Validate.Id, Validate.updateRecipe, Recipe.updateRecipe); // auth user updates recipe
  app.delete('/api/v1/recipes/:recipeId', authorize, Validate.Id, Recipe.deleteRecipe); // auth user deletes recipe
  app.get('/api/v1/recipes/:recipeId', allowUser, Validate.Id, Recipe.viewOne); // user can view a recipe
  app.get('/api/v1/recipes', Recipe.getAll); // user can get all recipes
  app.post('/api/v1/recipes/:recipeId/review', authorize, Validate.Id, Validate.review, Review.addReview); // auth user can add review to recipe
  app.get('/api/v1/recipes/:recipeId/review', Validate.Id, Review.getReviews); // auth user can view all reviews
  app.get('/api/v1/recipes/user/all', authorize, Recipe.getAllUser); // user can get all recipes by them
  app.post('/api/v1/recipes/:recipeId/favourite', authorize, Validate.Id, Favourite.addFavourite); // User can add recipe as favourite
  app.delete('/api/v1/favourites/:recipeId/delete', authorize, Validate.Id, Favourite.delete); // User can delete recipe from favourites
  app.get('/api/v1/recipes?sort=up&order=des', Recipe.getAll); // user can get recipe with most upvotes
  app.post('/api/v1/recipes/:recipeId/upvote', authorize, Validate.Id, Vote.upvote); // user can upvote recipe
  app.post('/api/v1/recipes/:recipeId/downvote', authorize, Validate.Id, Vote.downVote); // user can downvote recipe
};

export default router;

redpajama_set_name: RedPajamaGithub


text:
import * as React from 'react';
import { StandardProps } from '..';
import { Theme } from '../styles/createMuiTheme';
import { TransitionProps } from '../transitions/transition';

export interface CollapseProps extends StandardProps<TransitionProps, CollapseClassKey, 'timeout'> {
  children?: React.ReactNode;
  collapsedHeight?: string;
  component?: React.ReactType<CollapseProps>;
  theme?: Theme;
  timeout?: TransitionProps['timeout'] | 'auto';
}

export type CollapseClassKey = 'container' | 'entered' | 'wrapper' | 'wrapperInner';

declare const Collapse: React.ComponentType<CollapseProps>;

export default Collapse;


text:
title: Detailed OSN Integration
category: detailedfeature
authors: danken, lvernia, mkolesni, moti, mpavlik
wiki_category: DetailedFeature
wiki_title: Features/Detailed OSN Integration
wiki_revision_count: 72
wiki_last_updated: 2014-03-24
---

# Detailed OSN Integration

## Summary

We intend to add support for OpenStack Neutron as a network provider. Please see further details in [Features/OSN_Integration](Features/OSN_Integration)

## Owner

*   Name: [ Mike Kolesnik](User:Mkolesni)

<!-- -->

*   Email: <mkolesni@redhat.com>

## Current status

*   Target Release: oVirt 3.4
*   Status: Finished phase 2
*   Last updated: ,

### Change log

#### Planned changes for 3.3.1

*   Virtual NIC integration:
    -   Instead of deleting the port on the Neutron network when VM is stopped, it is now deleted when the virtual NIC no longer uses the network or exists.

#### Planned changes for 3.4

*   Implement the items detailed at [Features/Detailed_OSN_Integration#Phase_2_-_Enhanced_VM_networking](Features/Detailed_OSN_Integration#Phase_2_-_Enhanced_VM_networking)

## Detailed Description

The integration of network providers into oVirt will be incremental. The following phases outline the general guidelines and considerations.

### Phase 1 - Tech Preview

*   Add Neutron as an external provider.
    -   Support for Linux Bridge plugin
    -   Support for OVS plugin?
*   Each Neutron plugin will have a corresponding vNIC driver in VDSM, that can connect the vNIC to Neutron.
    -   Current implementation will be done by hooks.
*   No support for pre-built ovirt-node (or RHEV-H).
*   Integration - with Neutron Grizzly.

#### Network provider entity

*   Introducing a 'Provider' entity that will have the following properties:
    -   Name
    -   Description
    -   Type (from a fixed list of types)
    -   URL
    -   User/Password ?
*   Possibly, different providers can have additional properties that are needed by them.

#### Changes in network entity

*   Each network can be provided **either** by oVirt or by the external provider.
*   This requires that each network has a link to the provider:
    -   If the link is set, then this network is provided by the external provider.
    -   If the link is not set, the network is not provided externally.
*   There should also be an ID property of the network on the external provider.
*   One external provider will be supported for a network.
    -   However, an external provider can provide multiple networks.

#### Effective limitations

*   All networks provided by an external provider will be VM networks.
*   Importing the same network more than once should be defined as supported for different DCs but blocked otherwise.
*   External network cannot be used as a display network.
*   If a network is externally provided, it will **not** be editable in oVirt, since the external provider is responsible for managing the actual network configuration.
*   External network will always be non required.
    -   Scheduling for the cluster the network is attached to will not take the network into host selection consideration.
    -   This effectively means that the user is responsible for Neutron availability on all the hosts in a given cluster the external network is attached to.
*   Port mirroring is not available for virtual NICs connected to external networks.
*   Block deleting provider if there are VMs using the networks it provides.

#### Integration with virtual NIC lifecycle

![A flow chart outlining the major lifecycle stages and the transitions between them.](Neutron_vNIC_lifecycle.png "A flow chart outlining the major lifecycle stages and the transitions between them.")

*   Port creation on the external network will be done at this phase for running virtual machine and hot plug of NICs.
    -   Rewiring will **not** be supported for externally provided networks (Will be supported in a future phase).
*   When VM is being run we need to include all hosts in the cluster for scheduling decision of available networks.
*   For each virtual NIC that is using an externally provided network, we would need to provision the NIC (create port or use existing one) on the provider and receive the NIC connection details prior to running the VM.
    -   Once we have all the details available, we would need to pass those details to VDSM.
        -   This requires API change in the 'create' verb that would pass the connection details for each NIC.
*   The port will be deleted in these cases:
    -   The virtual NIC is deleted from the VM.
    -   The virtual VNIC profile is changed, so that it is no longer connected to the external network.
    -   The VM is deleted.
    -   The data center containing the external networks is deleted forcefully.
    -   Snapshot operations (Preview, Undo) on the VM.

### Phase 2 - Enhanced VM networking

*   Supporting Havana version.
*   Enhance network editing via oVirt.
*   Support proper scheduling for VMs on hosts.
*   Add support for IPAM.
*   Add support for security groups.

#### Enhanced network support

*   Add ability to delete the network from neutron as well.
    -   When deleting the network from oVirt the user can check a box saying "Delete from external provider".

#### Scheduling changes

*   Scheduling algorithm will take into account the fact that external networks are expected to be on the host.
    -   The "hack" with config-tool will not be required anymore.

#### Subnets sub-tab for external networks

*   A sub-tab will be added listing the subnets defined for the external network.
    -   Sub-tab contents will be taken from the external provider itself, not cached by oVirt.
    -   It will be possible to add/delete the subnets.
*   A subnet entity will consist of:
    -   Name - A name for the subnet
    -   CIDR - An IP address specifying the network name plus the net mask prefix. e.g. 10.0.0.0/24
        -   This will be used to allocate addresses to VMs on the subnet.
    -   IP version - Can choose either ipv4 (default) or ipv6
*   The subnet will be used to allocate IPs to VMs on the external network.
    -   If no subnets exist, the VM will not receive an IP.
    -   If a subnet exists, the VM will receive an IP from it.
    -   If more than one subnet exists, the VM will receive an IP from either of the subnets.
*   IP will be delivered to the guest OS via DHCP (provided by the Neutron service).

#### Security groups

**Note:** Security groups are an API extensions which is only supported by some plugins. Since it's supported by OVS and LB plugins this should work out of the box.

*   A custom property for specifying the security group(s) will be added to the vNIC custom properties list.
    -   Using this property the user can specify on profile level what security group(s) this profile uses. Example of security groupt ID 45361d2f-4c45-4b85-8ed1-32f028495c8b
    -   When using the property:
        -   If not specifying it, the default Neutron behavior will occur (the default security group should be used).
        -   If specifying with empty value, no security group should apply.
        -   If specifying a list of one or more UUIDs of security groups, these groups will be used.
*   The hook on VDSM will be changed to allow applying security groups (when necessary).
    -   OVS does not support security groups yet, so the vNIC will be connected to a dedicated LB which will have the securtiy groups applied on. The LB will be connected to the integration OVS bridge using a veth pair (mimicking a patch cable).

### Future phases

#### REST API support

*   Providers will be added as a top-level collection.
*   A provider will have a capabilities sub collection:
    -   Currently, the only capability type will be "networking".
    -   Capability resource ID will be computed according to provider ID + capability type.
    -   Networking capability will have a "networks" sub collection:
        -   Networks sub collection will be the networks as discovered on the provider.
        -   Network resource will have an ID matching its identity on the provider (or computed from it).
*   Importing a network would be done by copying the resource XML and posting it on the top level networks resource.
    -   The imported network would have a new ID which is oVirt internal.
    -   The imported network would have a link to it's origin network (The resource in the provider/capability context).

#### Better provisioning of networks on external providers

*   Add a way to know network no longer exists on the provider.
*   Experimental - add a way to convert an oVirt network to an external network (nice to have).
    -   The user can choose to export the network to an external provider.
    -   The network needs to be manually removed from hosts that have it (or perhaps with host profile this can be improved).
    -   The network parameters will be exported to the provider, the existing configuration (vNICs, profiles, permissions) will remain.

#### Auto-Discovery of networks

*   An external provider would be set up as the provider of networking for a DC, such that any network defined on the provider will be discovered by oVirt and automatically set-up on the DC.

#### Leverage advanced technologies

*   L3 routing for creating virtual routers.
*   VPNAAS, LBAAS

### User Experience

![ thumb | right](Providers.png  "fig: thumb | right") ![ thumb | right](Discovery.png  "fig: thumb | right") ![ thumb | right](Add.png  "fig: thumb | right") ![ thumb | right](Networks.png  "fig: thumb | right")

*   To represent the new Provider entity in our project, we're planning to add a new tab for Providers. At first it will only be populated with network Providers, but later on it might include Providers of other resource types as well.
*   Adding a new Provider in oVirt will comprise supplying an arbitrary name for it, and a URL address from which entities may be imported. We're planning to add a graphical indication of the connection to the supplied URL address.
*   When a specific Provider is chosen, subtabs displaying information concerning that Provider will appear (as with any other entity). To begin with, General and Networks subtabs will be implemented.
*   The main function in the Provider/Networks subtab will be to "Discover" the networks provided, which will open a popup window enabling attachment of provided networks to DC(s).
*   The user will also be able to create new networks to be attached to the Provider from within oVirt.
*   The provider entity should also be reflected in the system tree. We are currently intending to add another node between the System node and the specific DCs called "Data Centers", and on the same level a node called "Providers" (as they are not part of the DCs, but rather interfaces to external entities). Under the Providers node, will be displayed the Providers that exist in the engine's DB. We haven't thought about icons for these entities - maybe something general for Providers and something to do with Neutron for the current network providers (future providers will have other icons corresponding to their types).
*   The link between the Provider and its provided entity (in our case, a network) needs to also be reflected in the provided entity. Therefore, we'll add a Provider column to each network tab/subtab. Also, to make access to the Provider easier for the user, we're planning to have the text link to the actual Provider tab.

### Installation/Upgrade

### User work-flows

#### OpenStack Networking & Identity (Keystone) installation

All the components need to be installed, and set to run on startup.

Good documentation is available at <https://access.redhat.com/site/documentation/en-US/Red_Hat_OpenStack/2/html/Getting_Started_Guide/chap-Deploying__OpenStack_Networking_Services.html>

##### Configure Keystone

1.  Install keystone
    1.  Steps described at: <http://docs.openstack.org/developer/keystone/installing.html#installing-from-packages-fedora>
    2.  And: <http://fedoraproject.org/wiki/Getting_started_with_OpenStack_on_Fedora_17#Initial_Keystone_setup>

2.  Configure Neutron in keystone
    1.  Steps described at: <http://docs.openstack.org/grizzly/openstack-network/admin/content/keystone.html>
        1.  Add Neutron service
        2.  Add Neutron admin user

Note: get_id function is:

      function get_id () {
      `     echo `"$@" | grep ' id ' | awk '{print $4}'` `
      }

##### Configure Neutron manager

1.  Install Neutron manger
    1.  Steps described at: <http://docs.openstack.org/trunk/install-guide/install/yum/content/ch_neutron.html>
        1.  Install Neutron plugin
        2.  Run plugin self configuration (This will create the DB)
        3.  Configure /etc/quantum/quantum.conf:
            1.  Choose qpid by un-commenting the corresponding values
            2.  Un-comment notification_driver = quantum.openstack.common.notifier.list_notifier

        4.  Configure /etc/quantum/plugin.ini:
            1.  Fill correct IP in sql_connection
            2.  Change: tenant_network_type = vlan
            3.  Edit: network_vlan_ranges = <label>:<tag start>:<tag end>,physnet1:1000:2999

#### oVirt Engine required configuration

You need to configure the keystone URL:

      engine-config --set KeystoneAuthUrl=http://<host.fqdn>:35357/v2.0/

For oVirt versions less than 3.4, You also need to enable a setting that only required networks are considered for VM scheduling:

      engine-config --set OnlyRequiredNetworksMandatoryForVdsSelection=true

Don't forget to restart the ovirt-engine service!

#### Agent installation on host

1.  Install Neutron plugin (same plugin as in the manager)
2.  Configure the Neutron manger IP (rabbit_host =)
3.  Run plugin self configuration (for creating the link of plugin.ini to the specific config)
4.  When using Linux Bridge only:
    1.  Override file for creating a tap connected to dummy bridge

#### Linuxbridge Agent installation steps

The following properties are required:

      QPID_HOST - the QPID host address
      INTERFACE_MAPPING - the physical interface mapping, e.g. default:eth1.

The following properties are optional:

      qpid_username - QPID server's username
      qpid_password - QPID server user's password
      qpid_port - QPID server port

Once the properties are set, the following sequence will install, configure and start the linuxbridge agent:

      yum install -y openstack-quantum-linuxbridge
      LB_CONF=/etc/quantum/plugins/linuxbridge/linuxbridge_conf.ini
      Q_CONF=/etc/quantum/quantum.conf
      # configuring QPID host
      /usr/bin/openstack-config --set ${Q_CONF} DEFAULT rpc_backend quantum.openstack.common.rpc.impl_qpid
      /usr/bin/openstack-config --set ${Q_CONF} DEFAULT qpid_hostname ${QPID_HOST}
      if [[ -n "${qpid_username}" ]]; then
          /usr/bin/openstack-config --set ${Q_CONF} DEFAULT qpid_username ${qpid_username}
      fi
      if [[ -n "${qpid_password}" ]]; then
          /usr/bin/openstack-config --set ${Q_CONF} DEFAULT qpid_password ${qpid_password}
      fi
      if [[ -n "${qpid_port}" ]]; then
          /usr/bin/openstack-config --set ${Q_CONF} DEFAULT qpid_port ${qpid_port}
      fi
      rm -f /etc/quantum/plugin.ini
      ln -s ${LB_CONF} /etc/quantum/plugin.ini
      # edit /etc/quantum/plugin.ini physical_interface_mappings
      /usr/bin/openstack-config --set ${LB_CONF} LINUX_BRIDGE physical_interface_mappings ${INTERFACE_MAPPING}
      systemctl daemon-reload
      service quantum-linuxbridge-agent start
      chkconfig quantum-linuxbridge-agent on

#### OVS Agent installation steps

The following properties are required:

      QPID_HOST - the QPID host address
      BRIDGE_MAPPINGS - List of `<physical_network>`:`<bridge>`, each specifying the OVS bridge used by the agent for a connected physical network.
      INTERNAL_BRIDGE - the OVS integration bridge (default br-int)

The following properties are optional:

      qpid_username - QPID server's username
      qpid_password - QPID server user's password
      qpid_port - QPID server port

Once the properties are set, the following sequence will install, configure and start the OVS agent:

      sudo yum install -y openstack-quantum-openvswitch
      OVS_CONF=/etc/quantum/plugins/openvswitch/ovs_quantum_plugin.ini
      Q_CONF=/etc/quantum/quantum.conf
      # configuring QPID host
      /usr/bin/openstack-config --set ${Q_CONF} DEFAULT rpc_backend quantum.openstack.common.rpc.impl_qpid
      /usr/bin/openstack-config --set ${Q_CONF} DEFAULT qpid_hostname ${QPID_HOST}
      if [[ -n "${qpid_username}" ]]; then
          /usr/bin/openstack-config --set ${Q_CONF} DEFAULT qpid_username ${qpid_username}
      fi
      if [[ -n "${qpid_password}" ]]; then
          /usr/bin/openstack-config --set ${Q_CONF} DEFAULT qpid_password ${qpid_password}
      fi
      if [[ -n "${qpid_port}" ]]; then
          /usr/bin/openstack-config --set ${Q_CONF} DEFAULT qpid_port ${qpid_port}
      fi
      rm -f /etc/quantum/plugin.ini
      ln -s ${OVS_CONF} /etc/quantum/plugin.ini
      /usr/bin/openstack-config --set ${OVS_CONF} OVS bridge_mappings ${BRIDGE_MAPPINGS}
      service openvswitch start
      chkconfig openvswitch on
      ovs-vsctl add-br ${INTERNAL_BRIDGE}
      ovs-vsctl add-br br-eth0 # should create bridge for each network as specified on ${BRIDGE_MAPPINGS}
      service quantum-openvswitch-agent start
      chkconfig quantum-openvswitch-agent on
      chkconfig quantum-ovs-cleanup on

### Events

## Dependencies / Related Features and Projects

Please see the [feature page](Features/OSN_Integration).

## Documentation / External references

*   <https://wiki.openstack.org/wiki/Neutron/APIv2-specification>
*   <http://docs.openstack.org/api/openstack-network/2.0/content/>
*   <http://docs.openstack.org/trunk/openstack-network/admin/content/>

## Comments and Discussion

<Talk:Features/Detailed_OSN_Integration>

## Open Issues

*   Scheduling:
    -   Neutron exposes an API (Agent Scheduler) which can be used to know which hosts will be able to provision it's networks.
        -   Need to take advantage of this.
*   [Libvirt bug](https://bugzilla.redhat.com/878481) still not solved, but we have a fix for it as a post-start hook.
*   REST API support will not be available in Phase 1, how will this effect the REST API clients?

## Proof of Concept

A POC was done with the proposed ideas in "Phase 1" section, integrating [Openstack Neutron](https://wiki.openstack.org/wiki/Neutron) as an external network provider. the POC is available for review & testing.

### POC Sources

The POC sources can be found in the oVirt gerrit under a topic branch: <http://gerrit.ovirt.org/#/q/status:open+project:ovirt-engine+branch:master+topic:POC_NetworkProvider,n,z>

### Hack in Neutron linux bridge agent

Due to a bug in libvirt (https://bugzilla.redhat.com/show_bug.cgi?id=878481) we had to connect the vNIC to the ;vdsmdummy; bridge in VDSM. The Neutron agent will detect the tap device (the physical implementation of the vNIC) and attempt to connect it to it's bridge but fail because it's already connected to the dummy bridge.

To fix this, you would need to edit the installed linuxbridge_quantum_agent.py file and add this line of code:

                 utils.execute(['brctl', 'delif', ';vdsmdummy;', tap_device_name], root_helper=self.root_helper)

Inside the method **add_tap_interface**, right before:

                 if utils.execute(['brctl', 'addif', bridge_name, tap_device_name],
                                  root_helper=self.root_helper):

### Demo Videos

Demo videos of the POC in action are available on youtube.

#### The 1st part (the providers tab, discovery, etc)

<http://www.youtube.com/watch?v=yXqN17KktjE>

#### The 2nd part (VM connectivity)

<http://www.youtube.com/watch?v=uW3vrY2Y3xc>

<Category:DetailedFeature> <Category:Networking>


text:
<?php

namespace Ongoing;

class OrderUpdateIdentificationType
{
    const __default = 'GoodsOwnerOrderNumber';
    const GoodsOwnerOrderNumber = 'GoodsOwnerOrderNumber';
    const GoodsOwnerOrderId = 'GoodsOwnerOrderId';
    const SystemId = 'SystemId';

}


text:
<%
//console.log('model in AnnotationModalForm.html');
//console.log(model);
%>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Annotate Stream

<%= model.get('referenceDesignator') %>

<%= model.get('stream') %>

        <form>

                User
                <input id="username" type="text" class="form-control modal-form-input input" value="<%= username %>" disabled="disabled">

                Start Date (YYYY-MM-DD HH:mm:ss.sss)

                    <input type='text' class="form-control" />

                End Date (YYYY-MM-DD HH:mm:ss.sss)

                    <input type='text' class="form-control" />

                Annotation
                <textarea id="comments-input" class="modal-form-textarea-row-3 form-control" required></textarea>

                QC Flag
                <select id="qcflag-input" title="QC Flag" class="form-control">
                  <% //console.log('Creating QC Flags SELECT form element'); %>
                  <% //console.log(qcFlags); %>
                  <% for(var key in qcFlags.attributes.qcflags){ %>
                  <% //console.log(key); %>
                  <option value="<%= qcFlags.attributes.qcflags[key] %>"><%= key %></option>
                  <% }; %>
                </select>

                Exclude Data
                <select id="exclusionFlag-input" title="Exclude Data" class="form-control">
                  <option value=true>Yes</option>
                  <option value=false selected>No</option>
                </select>

                Parameter Selection
                <select id="parameters-input" title="Parameter Selection" class="form-group-sm" multiple>
                  <option value="null" selected="selected">No Parameters</option>
                  <% //console.log('Creating Parameter SELECT form element'); %>
                  <% //console.log(model); %>
                  <% for(var i=0; i<parameterDisplayNames.length;i++){ %>
                  <option value="<%= parameterIds[i].substring(2) %>"><%= parameterDisplayNames[i] %></option>
                  <% }; %>
                </select>

                <button class="btn btn-default" type="button" id="submit-button">Add</button>

                <button class="btn btn-default" type="reset" id="reset-button">Reset</button>

        </form>


text:
<?php

namespace Dingo\Blueprint;

use ReflectionClass;
use RuntimeException;
use Dingo\Blueprint\Annotation;
use Illuminate\Support\Collection;
use Doctrine\Common\Annotations\AnnotationRegistry;
use Doctrine\Common\Annotations\SimpleAnnotationReader;

class Blueprint
{
    /**
     * Simple annotation reader instance.
     *
     * @var \Doctrine\Common\Annotations\SimpleAnnotationReader
     */
    protected $reader;

    /**
     * Create a new generator instance.
     *
     * @param \Doctrine\Common\Annotations\SimpleAnnotationReader $reader
     *
     * @return void
     */
    public function __construct(SimpleAnnotationReader $reader)
    {
        $this->reader = $reader;

        $this->registerAnnotationLoader();
    }

    /**
     * Register the annotation loader.
     *
     * @return void
     */
    protected function registerAnnotationLoader()
    {
        $this->reader->addNamespace('Dingo\\Blueprint\\Annotation');
        $this->reader->addNamespace('Dingo\\Blueprint\\Annotation\\Method');

        AnnotationRegistry::registerLoader(function ($class) {
            $path = __DIR__.'/'.str_replace(['Dingo\\Blueprint\\', '\\'], ['', DIRECTORY_SEPARATOR], $class).'.php';

            if (file_exists($path)) {
                require_once $path;

                return true;
            }
        });
    }

    /**
     * Generate documentation with the name and version.
     *
     * @param string $name
     * @param string $version
     *
     * @return bool
     */
    public function generate(Collection $controllers, $name, $version)
    {
        $resources = $controllers->map(function ($controller) use ($version) {
            $controller = $controller instanceof ReflectionClass ? $controller : new ReflectionClass($controller);

            $actions = new Collection;

            // Spin through all the methods on the controller and compare the version
            // annotation (if supplied) with the version given for the generation.
            // We'll also build up an array of actions on each resource.
            foreach ($controller->getMethods() as $method) {
                if ($versionAnnotation = $this->reader->getMethodAnnotation($method, Annotation\Versions::class)) {
                    if (! in_array($version, $versionAnnotation->value)) {
                        continue;
                    }
                }

                if ($annotations = $this->reader->getMethodAnnotations($method)) {
                    if (! $actions->contains($method)) {
                        $actions->push(new Action($method, new Collection($annotations)));
                    }
                }
            }

            $annotations = new Collection($this->reader->getClassAnnotations($controller));

            return new Resource($controller->getName(), $controller, $annotations, $actions);
        });

        return $this->generateContentsFromResources($resources, $name);
    }

    /**
     * Generate the documentation contents from the resources collection.
     *
     * @param \Illuminate\Support\Collection $resources
     * @param string                         $name
     *
     * @return string
     */
    protected function generateContentsFromResources(Collection $resources, $name)
    {
        $contents = '';

        $contents .= $this->getFormat();
        $contents .= $this->line(2);
        $contents .= sprintf('# %s', $name);
        $contents .= $this->line(2);

        $resources->each(function ($resource) use (&$contents) {
            $contents .= $resource->getDefinition();

            if ($description = $resource->getDescription()) {
                $contents .= $this->line();
                $contents .= $description;
            }

            if (($parameters = $resource->getParameters()) && ! $parameters->isEmpty()) {
                $this->appendParameters($contents, $parameters);
            }

            $resource->getActions()->each(function ($action) use (&$contents) {
                $contents .= $this->line(2);
                $contents .= $action->getDefinition();

                if ($description = $action->getDescription()) {
                    $contents .= $this->line();
                    $contents .= $description;
                }

                if (($parameters = $action->getParameters()) && ! $parameters->isEmpty()) {
                    $this->appendParameters($contents, $parameters);
                }

                if ($request = $action->getRequest()) {
                    $this->appendRequest($contents, $request);
                }

                if ($response = $action->getResponse()) {
                    $this->appendResponse($contents, $response);
                }

                if ($transaction = $action->getTransaction()) {
                    foreach ($transaction->value as $value) {
                        if ($value instanceof Annotation\Request) {
                            $this->appendRequest($contents, $value);
                        } elseif ($value instanceof Annotation\Response) {
                            $this->appendResponse($contents, $value);
                        } else {
                            throw new RuntimeException('Unsupported annotation type given in transaction.');
                        }
                    }
                }
            });

            $contents .= $this->line(2);
        });

        return stripslashes(trim($contents));
    }

    /**
     * Append the parameters subsection to a resource or action.
     *
     * @param string                         $contents
     * @param \Illuminate\Support\Collection $parameters
     *
     * @return void
     */
    protected function appendParameters(&$contents, Collection $parameters)
    {
        $this->appendSection($contents, 'Parameters');

        $parameters->each(function ($parameter) use (&$contents) {
            $contents .= $this->line();
            $contents .= $this->tab();
            $contents .= sprintf(
                '+ %s (%s, %s) - %s',
                $parameter->identifier,
                $parameter->type,
                $parameter->required ? 'required' : 'optional',
                $parameter->description
            );

            if (isset($parameter->default)) {
                $this->appendSection($contents, sprintf('Default: %s', $parameter->default), 2, 1);
            }
        });
    }

    /**
     * Append a response subsection to an action.
     *
     * @param string                               $contents
     * @param \Dingo\Blueprint\Annotation\Response $response
     *
     * @return void
     */
    protected function appendResponse(&$contents, Annotation\Response $response)
    {
        $this->appendSection($contents, sprintf('Response %s', $response->statusCode));

        if (isset($response->contentType)) {
            $contents .= ' ('.$response->contentType.')';
        }

        if (! empty($request->headers)) {
            $this->appendHeaders($contents, $request->headers);
        }

        if (isset($response->body)) {
            $this->appendBody($contents, $this->prepareBody($response->body, $response->contentType));
        }
    }

    /**
     * Append a request subsection to an action.
     *
     * @param string                              $contents
     * @param \Dingo\Blueprint\Annotation\Request $request
     *
     * @return void
     */
    protected function appendRequest(&$contents, $request)
    {
        $this->appendSection($contents, 'Request');

        if (isset($request->identifier)) {
            $contents .= ' '.$request->identifier;
        }

        $contents .= ' ('.$request->contentType.')';

        if (! empty($request->headers)) {
            $this->appendHeaders($contents, $request->headers);
        }

        if (isset($request->body)) {
            $this->appendBody($contents, $this->prepareBody($request->body, $request->contentType));
        }
    }

    /**
     * Append a body subsection to an action.
     *
     * @param string $contents
     * @param string $body
     *
     * @return void
     */
    protected function appendBody(&$contents, $body)
    {
        $this->appendSection($contents, 'Body', 1, 1);

        $contents .= $this->line(2);

        $line = strtok($body, "\r\n");

        while ($line !== false) {
            $contents .= $this->tab(3).$line;

            $line = strtok("\r\n");

            if ($line !== false) {
                $contents .= $this->line();
            }
        }
    }

    /**
     * Append a headers subsection to an action.
     *
     * @param string $contents
     * @param array  $response
     *
     * @return void
     */
    protected function appendHeaders(&$contents, array $headers)
    {
        $this->appendSection($contents, 'Headers', 1, 1);

        $contents .= $this->line();

        foreach ($headers as $header => $value) {
            $contents .= $this->line().$this->tab(3).sprintf('%s: %s', $header, $value);
        }
    }

    /**
     * Append a subsection to an action.
     *
     * @param string $contents
     * @param string $name
     * @param int    $indent
     * @param int    $lines
     *
     * @return void
     */
    protected function appendSection(&$contents, $name, $indent = 0, $lines = 2)
    {
        $contents .= $this->line($lines);
        $contents .= $this->tab($indent);
        $contents .= '+ '.$name;
    }

    /**
     * Prepare a body.
     *
     * @param string $body
     * @param string $contentType
     *
     * @return string
     */
    protected function prepareBody($body, $contentType)
    {
        if ($contentType == 'application/json') {
            return json_encode($body, JSON_PRETTY_PRINT);
        }

        return $body;
    }

    /**
     * Create a new line character.
     *
     * @param int $repeat
     *
     * @return string
     */
    protected function line($repeat = 1)
    {
        return str_repeat("\n", $repeat);
    }

    /**
     * Create a tab character.
     *
     * @param int $repeat
     *
     * @return string
     */
    protected function tab($repeat = 1)
    {
        return str_repeat("    ", $repeat);
    }

    /**
     * Get the API Blueprint format.
     *
     * @return string
     */
    protected function getFormat()
    {
        return 'FORMAT: 1A';
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

GridSphere Portlet Container API

The GridSphere portlet container is responsible for the dynamic management of
{@link org.gridsphere.portletcontainer.PortletWebApplication}s. A portlet web application is a collection
of portlets packaged as a WAR file. Portlets are defined by a portlet descriptor file, web.xml located
in the WEB-INF directory of the portlet web application. The porlet descriptor file defines one or more
application portlets defined in {@link org.gridsphere.portletcontainer.ApplicationPortlet} each of which
may have one or more concrete portlet definitions as defined in
{@link org.gridsphere.portletcontainer.ConcretePortlet}. Both the application portlet and concrete portlet
have configuration settings that are defined in the {@link org.gridsphere.portletcontainer.ApplicationPortletConfig}
and the {@link org.gridsphere.portletcontainer.ConcretePortletConfig} respectively.

All portlets including the portlet web applications are registered with the
{@link org.gridsphere.portletcontainer.PortletRegistry}, a singleton used by other components to request
information about portlets and obtain a {@link org.gridsphere.portletcontainer.impl.SportletDispatcher}, which is
used to invoke a lifecyle method on a chosen portlet. To make portlet invocation easy, the
{@link org.gridsphere.portletcontainer.PortletInvoker} offers static methods that are essentially wrappers
around the PortletDispatcher.

The GridSphere portlet container is implemented as the master
{@link org.gridsphere.servlets.GridSphereServlet} servlet which receives all requests to the portal
and is responsible for generating a {@link org.gridsphere.portletcontainer.GridSphereEvent} which is
passed to the layout components for rendering the portal presentation.

The {@link org.gridsphere.portletcontainer.PortletDataManager} and
{@link org.gridsphere.portletcontainer.PortletMessageManager} are singletons used to manage persistent
{@link org.gridsphere.portlet.PortletData} and {@link org.gridsphere.portlet.PortletMessage}
information respectively.


text:
<?php
namespace Evolution\DJob\Listeners;

use League\Event\AbstractListener;
use League\Event\EventInterface;

/**
 * Created by PhpStorm.
 * User: evolution
 * Date: 17-4-24
 * Time: 下午6:01
 */
class BeforeCreateProcessListener extends AbstractListener
{
    public function handle(EventInterface $event, $param = null)
    {
        \SeasLog::debug("准备开启进程去处理任务\n");
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright 2019 Google LLC
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     https://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/menu_edit_delete"
        android:title="@string/edit_menu_delete_title"
        app:showAsAction="ifRoom"
        android:icon="@drawable/ic_delete"/>

    <item
        android:id="@+id/menu_edit_done"
        android:title="@string/edit_menu_done_title"
        app:showAsAction="ifRoom"
        android:icon="@drawable/ic_check"/>

</menu>


text:
SHELL := /usr/bin/env bash

all: check_shell check_python check_golang check_terraform check_docker check_base_files test_check_headers check_headers check_trailing_whitespace generate_docs ## Run all linters and update documentation

# The .PHONY directive tells make that this isn't a real target and so
# the presence of a file named 'check_shell' won't cause this target to stop
# working
.PHONY: check_shell
check_shell: ## Lint shell scripts
	@source test/make.sh && check_shell

.PHONY: check_python
check_python: ## Lint Python source files
	@source test/make.sh && check_python

.PHONY: check_golang
check_golang: ## Lint Go source files
	@source test/make.sh && golang

.PHONY: check_terraform
check_terraform: ## Lint Terraform source files
	@source test/make.sh && check_terraform

.PHONY: check_docker
check_docker: ## Lint Dockerfiles
	@source test/make.sh && docker

.PHONY: check_base_files
check_base_files:
	@source test/make.sh && basefiles

.PHONY: check_shebangs
check_shebangs: ## Check that scripts have correct shebangs
	@source test/make.sh && check_bash

.PHONY: check_trailing_whitespace
check_trailing_whitespace:
	@source test/make.sh && check_trailing_whitespace

.PHONY: test_check_headers
test_check_headers:
	@echo "Testing the validity of the header check"
	@python test/test_verify_boilerplate.py

.PHONY: check_headers
check_headers: ## Check that source files have appropriate boilerplate
	@echo "Checking file headers"
	@python test/verify_boilerplate.py

# Integration tests
.PHONY: test_integration
test_integration: ## Run integration tests
	bundle install
	bundle exec kitchen create
	bundle exec kitchen converge
	bundle exec kitchen converge
	bundle exec kitchen verify
	bundle exec kitchen destroy

.PHONY: generate_docs
generate_docs: ## Update README documentation for Terraform variables and outputs
	@source test/make.sh && generate_docs

.PHONY: release-new-version
release-new-version:
	@source helpers/release-new-version.sh

help: ## Prints help for targets with comments
	@grep -E '^[a-zA-Z._-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'


text:
- Deprecated threatq-search-by-name command
- Fix default parameters for the following commands:
    - threatq-search-by-name
    - threatq-upload-file
    - threatq-get-all-indicators
    - threatq-get-all-events
    - threatq-get-all-adversaries


text:
package com.exxeta.iss.sonar.esql.test;

import org.junit.Before;
import org.junit.Test;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.Settings;

import com.exxeta.iss.sonar.esql.EsqlPlugin;

import static org.fest.assertions.Assertions.assertThat;

public class EsqlPluginTest {

  private EsqlPlugin plugin;

  @Before
  public void setUp() throws Exception {
    plugin = new EsqlPlugin();
  }

  @Test
  public void testGetExtensions() throws Exception {
    assertThat(plugin.getExtensions().size()).isEqualTo(9);
  }

  @Test
  public void testProperties() {
    Settings settings = new Settings(new PropertyDefinitions(plugin));
    // SONARPLUGINS-2524
    assertThat(settings.getString(EsqlPlugin.TEST_FRAMEWORK_KEY)).isNull();
  }

}


text:
(function(exports) {
	'use strict';

	/**
	 * A null function - does nothing, returns nothing
	 */
	var nullFunction = function() {};

	/**
	 * The null platform, which doesn't support anything
	 */
	var nullPlatform = {
		getType: function() {
			return 'null';
		},
		isSupported: function() {
			return false;
		},
		update: nullFunction
	};

	/**
	 * This strategy uses a timer function to call an update function.
	 * The timer (re)start function can be provided or the strategy reverts to
	 * one of the window.*requestAnimationFrame variants.
	 *
	 * @class AnimFrameUpdateStrategy
	 * @constructor
	 * @param {Function} [requestAnimationFrame] function to use for timer creation
	 * @module Gamepad
	 */
	var AnimFrameUpdateStrategy = function(requestAnimationFrame) {
		var that = this;
		var win = window;

		this.update = nullFunction;

		this.requestAnimationFrame = requestAnimationFrame || win.requestAnimationFrame ||
			win.webkitRequestAnimationFrame || win.mozRequestAnimationFrame;

		/**
		 * This method calls the (user) update and restarts itself
		 * @method tickFunction
		 */
		this.tickFunction = function() {
			that.update();
			that.startTicker();
		};

		/**
		 * (Re)Starts the ticker
		 * @method startTicker
		 */
		this.startTicker = function() {
			that.requestAnimationFrame.apply(win, [that.tickFunction]);
		};
	};

	/**
	 * Starts the update strategy using the given function
	 *
	 * @method start
	 * @param {Function} updateFunction the function to call at each update
	 */
	AnimFrameUpdateStrategy.prototype.start = function(updateFunction) {
		this.update = updateFunction || nullFunction;
		this.startTicker();
	};

	/**
	 * This strategy gives the user the ability to call the library internal
	 * update function on request. Use this strategy if you already have a
	 * timer function running by requestAnimationFrame and you need fine control
	 * over when the gamepads are updated.
	 *
	 * @class ManualUpdateStrategy
	 * @constructor
	 * @module Gamepad
	 */
	var ManualUpdateStrategy = function() {

	};

	/**
	 * Calls the update function in the started state. Does nothing otherwise.
	 * @method update
	 */
	ManualUpdateStrategy.prototype.update = nullFunction;

	/**
	 * Starts the update strategy using the given function
	 *
	 * @method start
	 * @param {Function} updateFunction the function to call at each update
	 */
	ManualUpdateStrategy.prototype.start = function(updateFunction) {
		this.update = updateFunction || nullFunction;
	};

	/**
	 * This platform is for webkit based environments that need to be polled
	 * for updates.
	 *
	 * @class WebKitPlatform
	 * @constructor
	 * @param {Object} listener the listener to provide _connect and _disconnect callbacks
	 * @param {Function} gamepadGetter the poll function to return an array of connected gamepads
	 * @module Gamepad
	 */
	var WebKitPlatform = function(listener, gamepadGetter) {
		this.listener = listener;
		this.gamepadGetter = gamepadGetter;
		this.knownGamepads = [];
	};

	/**
	 * Provides a platform object that returns true for isSupported() if valid.
	 * @method factory
	 * @static
	 * @param {Object} listener the listener to use
	 * @return {Object} a platform object
	 */
	WebKitPlatform.factory = function(listener) {
		var platform = nullPlatform;
		var navigator = window && window.navigator;

		if (navigator) {
			if (typeof(navigator.getGamepads) !== 'undefined') {
				platform = new WebKitPlatform(listener, function() {
					return navigator.getGamepads();
				});
			} else if (typeof(navigator.webkitGamepads) !== 'undefined') {
				platform = new WebKitPlatform(listener, function() {
					return navigator.webkitGamepads();
				});
			} else if (typeof(navigator.webkitGetGamepads) !== 'undefined') {
				platform = new WebKitPlatform(listener, function() {
					return navigator.webkitGetGamepads();
				});
			}
		}

		return platform;
	};

	/**
	 * @method getType()
	 * @static
	 * @return {String} 'WebKit'
	 */
	WebKitPlatform.getType = function() {
		return 'WebKit';
	},

	/**
	 * @method getType()
	 * @return {String} 'WebKit'
	 */
	WebKitPlatform.prototype.getType = function() {
		return WebKitPlatform.getType();
	},

	/**
	 * @method isSupported
	 * @return {Boolean} true
	 */
	WebKitPlatform.prototype.isSupported = function() {
		return true;
	};

	/**
	 * Queries the currently connected gamepads and reports any changes.
	 * @method update
	 */
	WebKitPlatform.prototype.update = function() {
		var that = this;
		var gamepads = Array.prototype.slice.call(this.gamepadGetter(), 0);
		var gamepad;
		var i;

		for (i = this.knownGamepads.length - 1; i >= 0; i--) {
			gamepad = this.knownGamepads[i];
			if (gamepads.indexOf(gamepad) < 0) {
				this.knownGamepads.splice(i, 1);
				this.listener._disconnect(gamepad);
			}
		}

		for (i = 0; i < gamepads.length; i++) {
			gamepad = gamepads[i];
			if (gamepad && (that.knownGamepads.indexOf(gamepad) < 0)) {
				that.knownGamepads.push(gamepad);
				that.listener._connect(gamepad);
			}
		}
	};

	/**
	 * This platform is for mozilla based environments that provide gamepad
	 * updates via events.
	 *
	 * @class FirefoxPlatform
	 * @constructor
	 * @module Gamepad
	 */
	var FirefoxPlatform = function(listener) {
		this.listener = listener;

		window.addEventListener('gamepadconnected', function(e) {
			listener._connect(e.gamepad);
		});
		window.addEventListener('gamepaddisconnected', function(e) {
			listener._disconnect(e.gamepad);
		});
	};

	/**
	 * Provides a platform object that returns true for isSupported() if valid.
	 * @method factory
	 * @static
	 * @param {Object} listener the listener to use
	 * @return {Object} a platform object
	 */
	FirefoxPlatform.factory = function(listener) {
		var platform = nullPlatform;

		if (window && (typeof(window.addEventListener) !== 'undefined')) {
			platform = new FirefoxPlatform(listener);
		}

		return platform;
	};

	/**
	 * @method getType()
	 * @static
	 * @return {String} 'Firefox'
	 */
	FirefoxPlatform.getType = function() {
		return 'Firefox';
	},

	/**
	 * @method getType()
	 * @return {String} 'Firefox'
	 */
	FirefoxPlatform.prototype.getType = function() {
		return FirefoxPlatform.getType();
	},

	/**
	 * @method isSupported
	 * @return {Boolean} true
	 */
	FirefoxPlatform.prototype.isSupported = function() {
		var navigator = window && window.navigator;
		return navigator.userAgent.indexOf('Firefox') !== -1;
	};

	/**
	 * Does nothing on the Firefox platform
	 * @method update
	 */
	FirefoxPlatform.prototype.update = nullFunction;

	/**
	 * Provides simple interface and multi-platform support for the gamepad API.
	 *
	 * You can change the deadzone and maximizeThreshold parameters to suit your
	 * taste but the defaults should generally work fine.
	 *
	 * @class Gamepad
	 * @constructor
	 * @param {Object} [updateStrategy] an update strategy, defaulting to
	 *		{{#crossLink "AnimFrameUpdateStrategy"}}{{/crossLink}}
	 * @module Gamepad
	 * @author Priit Kallas <kallaspriit@gmail.com>
	 */
	var Gamepad = function(updateStrategy) {
		this.updateStrategy = updateStrategy || new AnimFrameUpdateStrategy();
		this.gamepads = [];
		this.listeners = {};
		this.platform = nullPlatform;
		this.deadzone = 0.03;
		this.maximizeThreshold = 0.97;
	};

	/**
	 * The available update strategies
	 * @property UpdateStrategies
	 * @param {AnimFrameUpdateStrategy} AnimFrameUpdateStrategy
	 * @param {ManualUpdateStrategy} ManualUpdateStrategy
	 */
	Gamepad.UpdateStrategies = {
		AnimFrameUpdateStrategy: AnimFrameUpdateStrategy,
		ManualUpdateStrategy: ManualUpdateStrategy
	};

	/**
	 * List of factories of supported platforms. Currently available platforms:
	 * {{#crossLink "WebKitPlatform"}}{{/crossLink}},
	 * {{#crossLink "FirefoxPlatform"}}{{/crossLink}},
	 * @property PlatformFactories
	 * @type {Array}
	 */
	Gamepad.PlatformFactories = [FirefoxPlatform.factory, WebKitPlatform.factory];

	/**
	 * List of supported controller types.
	 *
	 * @property Type
	 * @param {String} Type.N64 Retrolink N64 controller
	 * @param {String} Type.PLAYSTATION Playstation controller
	 * @param {String} Type.LOGITECH Logitech controller
	 * @param {String} Type.XBOX XBOX controller
	 * @param {String} Type.UNKNOWN Unknown controller
	 */
	Gamepad.Type = {
		N64: 'n64',
		PLAYSTATION: 'playstation',
		LOGITECH: 'logitech',
		XBOX: 'xbox',
		UNKNOWN: 'unknown'
	};

	/*
	 * List of events you can expect from the library.
	 *
	 * CONNECTED, DISCONNECTED and UNSUPPORTED events include the gamepad in
	 * question and tick provides the list of all connected gamepads.
	 *
	 * BUTTON_DOWN and BUTTON_UP events provide an alternative to polling button states at each tick.
	 *
	 * AXIS_CHANGED is called if a value of some specific axis changes.
	 */
	Gamepad.Event = {
		/**
		 * Triggered when a new controller connects.
		 *
		 * @event connected
		 * @param {Object} device
		 */
		CONNECTED: 'connected',

		/**
		 * Called when an unsupported controller connects.
		 *
		 * @event unsupported
		 * @param {Object} device
		 * @deprecated not used anymore. Any controller is supported.
		 */
		UNSUPPORTED: 'unsupported',

		/**
		 * Triggered when a controller disconnects.
		 *
		 * @event disconnected
		 * @param {Object} device
		 */
		DISCONNECTED: 'disconnected',

		/**
		 * Called regularly with the latest controllers info.
		 *
		 * @event tick
		 * @param {Array} gamepads
		 */
		TICK: 'tick',

		/**
		 * Called when a gamepad button is pressed down.
		 *
		 * @event button-down
		 * @param {Object} event
		 * @param {Object} event.gamepad The gamepad object
		 * @param {String} event.control Control name
		 */
		BUTTON_DOWN: 'button-down',

		/**
		 * Called when a gamepad button is released.
		 *
		 * @event button-up
		 * @param {Object} event
		 * @param {Object} event.gamepad The gamepad object
		 * @param {String} event.control Control name
		 */
		BUTTON_UP: 'button-up',

		/**
		 * Called when gamepad axis value changed.
		 *
		 * @event axis-changed
		 * @param {Object} event
		 * @param {Object} event.gamepad The gamepad object
		 * @param {String} event.axis Axis name
		 * @param {Number} event.value New axis value
		 */
		AXIS_CHANGED: 'axis-changed'
	};

	/**
	 * List of standard button names. The index is the according standard button
	 * index as per standard.
	 *
	 * @property StandardButtons
	 */
	Gamepad.StandardButtons = [
		'FACE_1', 'FACE_2', 'FACE_3', 'FACE_4',
		'LEFT_TOP_SHOULDER', 'RIGHT_TOP_SHOULDER', 'LEFT_BOTTOM_SHOULDER', 'RIGHT_BOTTOM_SHOULDER',
		'SELECT_BACK', 'START_FORWARD', 'LEFT_STICK', 'RIGHT_STICK',
		'DPAD_UP', 'DPAD_DOWN', 'DPAD_LEFT', 'DPAD_RIGHT',
		'HOME'
	];

	/**
	 * List of standard axis names. The index is the according standard axis
	 * index as per standard.
	 *
	 * @property StandardAxes
	 */
	Gamepad.StandardAxes = ['LEFT_STICK_X', 'LEFT_STICK_Y', 'RIGHT_STICK_X', 'RIGHT_STICK_Y'];

	var getControlName = function(names, index, extraPrefix) {
		return (index < names.length) ? names[index] : extraPrefix + (index - names.length + 1);
	};

	/**
	 * The standard mapping that represents the mapping as per definition.
	 * Each button and axis map to the same index.
	 *
	 * @property StandardMapping
	 */
	Gamepad.StandardMapping = {
		env: {},
		buttons: {
			byButton: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
		},
		axes: {
			byAxis: [0, 1, 2, 3]
		}
	};

	/**
	 * Mapping of various gamepads that differ from the standard mapping on
	 * different platforms too unify their buttons and axes.
	 *
	 * Each mapping should have an 'env' object, which describes the environment
	 * in which the mapping is active. The more entries such an environment has,
	 * the more specific it is.
	 *
	 * Mappings are expressed for both buttons and axes. Buttons might refer to
	 * axes if they are notified as such.
	 *
	 * @property Mappings
	 */
	Gamepad.Mappings = [
		// Retrolink N64 controller on Firefox
		{
			env: {
				platform: FirefoxPlatform.getType(),
				type: Gamepad.Type.N64
			},
			buttons: {
				byButton: [
					// TODO: Figure out which buttons to map A and Z buttons to.
					2, // FACE_1 -- C-down button
					1, // FACE_2 -- C-right button
					3, // FACE_3 -- C-left button
					0, // FACE_4 -- C-down button
					4, // LEFT_TOP_SHOULDER -- L button
					5, // RIGHT_TOP_SHOULDER -- R button
					-1, // LEFT_BOTTOM_SHOULDER -- missing on controller
					-1, // RIGHT_BOTTOM_SHOULDER -- missing on controller
					8, // SELECT_BACK -- B button (is this right?)
					9, // START_FORWARD -- START button
					-1, // LEFT_STICK -- missing on controller
					-1, // RIGHT_STICK -- missing on controller
					12, // DPAD_UP -- not supported by API (but may eventually)
					13, // DPAD_DOWN -- not supported by API (but may eventually)
					14, // DPAD_LEFT -- not supported by API (but may eventually)
					15, // DPAD_RIGHT -- not supported by API (but may eventually)
					-1 // HOME -- missing on controller (could be START/B?)
				]
			},
			axes: {
				byAxis: [
					1, // LEFT_STICK_X
					2, // LEFT_STICK_Y
					-1, // RIGHT_STICK_X
					-1 // RIGHT_STICK_Y
				]
			}
		},
		// Retrolink N64 controller on WebKit
		{
			env: {
				platform: WebKitPlatform.getType(),
				type: Gamepad.Type.N64
			},
			buttons: {
				byButton: [
					// TODO: Figure out which buttons to map A and Z buttons to.
					2, // FACE_1 -- C-down button
					1, // FACE_2 -- C-right button
					3, // FACE_3 -- C-left button
					0, // FACE_4 -- C-down button
					4, // LEFT_TOP_SHOULDER -- L button
					5, // RIGHT_TOP_SHOULDER -- R button
					-1, // LEFT_BOTTOM_SHOULDER -- missing on controller
					-1, // RIGHT_BOTTOM_SHOULDER -- missing on controller
					8, // SELECT_BACK -- B button (is this right?)
					9, // START_FORWARD -- START button
					-1, // LEFT_STICK -- missing on controller
					-1, // RIGHT_STICK -- missing on controller
					12, // DPAD_UP -- D-Pad-up button
					13, // DPAD_DOWN -- D-Pad-down button
					14, // DPAD_LEFT -- D-Pad-left button
					15, // DPAD_RIGHT -- D-Pad-right button
					-1 // HOME -- missing on controller (could be START/B?)
				]
			},
			axes: {
				byAxis: [
					0, // LEFT_STICK_X
					1, // LEFT_STICK_Y
					-1, // RIGHT_STICK_X
					-1 // RIGHT_STICK_Y
				]
			}
		},
		// XBOX360 controller on Firefox
		{
			env: {
				platform: FirefoxPlatform.getType(),
				type: Gamepad.Type.XBOX
			},
			buttons: {
				byButton: [0, 1, 2, 3, 4, 5, 15, 16, 9, 8, 6, 7, 11, 12, 13, 14, 10]
			},
			axes: {
				byAxis: [0, 1, 2, 3]
			}
		},
		// PS3 controller on Firefox
		{
			env: {
				platform: FirefoxPlatform.getType(),
				type: Gamepad.Type.PLAYSTATION
			},
			buttons: {
				byButton: [14, 13, 15, 12, 10, 11, 8, 9, 0, 3, 1, 2, 4, 6, 7, 5, 16]
			},
			axes: {
				byAxis: [0, 1, 2, 3]
			}
		},
		// Logitech gamepad on WebKit
		{
			env: {
				platform: WebKitPlatform.getType(),
				type: Gamepad.Type.LOGITECH
			},
			buttons: { // TODO: This can't be right - LEFT/RIGHT_STICK have same mappings as HOME/DPAD_UP
				byButton: [1, 2, 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11, 12, 13, 14, 10]
			},
			axes: {
				byAxis: [0, 1, 2, 3]
			}
		},
		// Logitech gamepad on Firefox
		{
			env: {
				platform: FirefoxPlatform.getType(),
				type: Gamepad.Type.LOGITECH
			},
			buttons: {
				byButton: [0, 1, 2, 3, 4, 5, -1, -1, 6, 7, 8, 9, 11, 12, 13, 14, 10],
				byAxis: [-1, -1, -1, -1, -1, -1, [2, 0, 1],
					[2, 0, -1]
				]
			},
			axes: {
				byAxis: [0, 1, 3, 4]
			}
		}
	];

	/**
	 * Initializes the gamepad.
	 *
	 * You usually want to bind to the events first and then initialize it.
	 *
	 * @method init
	 * @return {Boolean} true if a supporting platform was detected, false otherwise.
	 */
	Gamepad.prototype.init = function() {
		var platform = Gamepad.resolvePlatform(this);
		var that = this;

		this.platform = platform;
		this.updateStrategy.start(function() {
			that._update();
		});

		return platform.isSupported();
	};

	/**
	 * Binds a listener to a gamepad event.
	 *
	 * @method bind
	 * @param {String} event Event to bind to, one of Gamepad.Event..
	 * @param {Function} listener Listener to call when given event occurs
	 * @return {Gamepad} Self
	 */
	Gamepad.prototype.bind = function(event, listener) {
		if (typeof(this.listeners[event]) === 'undefined') {
			this.listeners[event] = [];
		}

		this.listeners[event].push(listener);

		return this;
	};

	/**
	 * Removes listener of given type.
	 *
	 * If no type is given, all listeners are removed. If no listener is given, all
	 * listeners of given type are removed.
	 *
	 * @method unbind
	 * @param {String} [type] Type of listener to remove
	 * @param {Function} [listener] The listener function to remove
	 * @return {Boolean} Was unbinding the listener successful
	 */
	Gamepad.prototype.unbind = function(type, listener) {
		if (typeof(type) === 'undefined') {
			this.listeners = {};

			return;
		}

		if (typeof(listener) === 'undefined') {
			this.listeners[type] = [];

			return;
		}

		if (typeof(this.listeners[type]) === 'undefined') {
			return false;
		}

		for (var i = 0; i < this.listeners[type].length; i++) {
			if (this.listeners[type][i] === listener) {
				this.listeners[type].splice(i, 1);

				return true;
			}
		}

		return false;
	};

	/**
	 * Returns the number of connected gamepads.
	 *
	 * @method count
	 * @return {Number}
	 */
	Gamepad.prototype.count = function() {
		return this.gamepads.length;
	};

	/**
	 * Fires an internal event with given data.
	 *
	 * @method _fire
	 * @param {String} event Event to fire, one of Gamepad.Event..
	 * @param {*} data Data to pass to the listener
	 * @private
	 */
	Gamepad.prototype._fire = function(event, data) {
		if (typeof(this.listeners[event]) === 'undefined') {
			return;
		}

		for (var i = 0; i < this.listeners[event].length; i++) {
			this.listeners[event][i].apply(this.listeners[event][i], [data]);
		}
	};

	/**
	 * @method getNullPlatform
	 * @static
	 * @return {Object} a platform that does not support anything
	 */
	Gamepad.getNullPlatform = function() {
		return Object.create(nullPlatform);
	};

	/**
	 * Resolves platform.
	 *
	 * @method resolvePlatform
	 * @static
	 * @param listener {Object} the listener to handle _connect() or _disconnect() calls
	 * @return {Object} A platform instance
	 */
	Gamepad.resolvePlatform = function(listener) {
		var platform = nullPlatform;
		var i;

		for (i = 0; !platform.isSupported() && (i < Gamepad.PlatformFactories.length); i++) {
			platform = Gamepad.PlatformFactories[i](listener);
		}

		return platform;
	};

	/**
	 * Registers given gamepad.
	 *
	 * @method _connect
	 * @param {Object} gamepad Gamepad to connect to
	 * @private
	 */
	Gamepad.prototype._connect = function(gamepad) {
		var mapping = this._resolveMapping(gamepad);
		var count;
		var i;

		//gamepad.mapping = this._resolveMapping(gamepad);
		gamepad.state = {};
		gamepad.lastState = {};
		gamepad.updater = [];

		count = mapping.buttons.byButton.length;
		for (i = 0; i < count; i++) {
			this._addButtonUpdater(gamepad, mapping, i);
		}

		count = mapping.axes.byAxis.length;
		for (i = 0; i < count; i++) {
			this._addAxisUpdater(gamepad, mapping, i);
		}

		this.gamepads[gamepad.index] = gamepad;

		this._fire(Gamepad.Event.CONNECTED, gamepad);
	};

	/**
	 * Adds an updater for a button control
	 *
	 * @method _addButtonUpdater
	 * @private
	 * @param {Object} gamepad the gamepad for which to create the updater
	 * @param {Object} mapping the mapping on which to work on
	 * @param {Number} index button index
	 */
	Gamepad.prototype._addButtonUpdater = function(gamepad, mapping, index) {
		var updater = nullFunction;
		var controlName = getControlName(Gamepad.StandardButtons, index, 'EXTRA_BUTTON_');
		var getter = this._createButtonGetter(gamepad, mapping.buttons, index);
		var that = this;
		var buttonEventData = {
			gamepad: gamepad,
			control: controlName
		};

		gamepad.state[controlName] = 0;
		gamepad.lastState[controlName] = 0;

		updater = function() {
			var value = getter();
			var lastValue = gamepad.lastState[controlName];
			var isDown = value > 0.5;
			var wasDown = lastValue > 0.5;

			gamepad.state[controlName] = value;

			if (isDown && !wasDown) {
				that._fire(Gamepad.Event.BUTTON_DOWN, Object.create(buttonEventData));
			} else if (!isDown && wasDown) {
				that._fire(Gamepad.Event.BUTTON_UP, Object.create(buttonEventData));
			}

			if ((value !== 0) && (value !== 1) && (value !== lastValue)) {
				that._fireAxisChangedEvent(gamepad, controlName, value);
			}

			gamepad.lastState[controlName] = value;
		};

		gamepad.updater.push(updater);
	};

	/**
	 * Adds an updater for an axis control
	 *
	 * @method _addAxisUpdater
	 * @private
	 * @param {Object} gamepad the gamepad for which to create the updater
	 * @param {Object} mapping the mapping on which to work on
	 * @param {Number} index axis index
	 */
	Gamepad.prototype._addAxisUpdater = function(gamepad, mapping, index) {
		var updater = nullFunction;
		var controlName = getControlName(Gamepad.StandardAxes, index, 'EXTRA_AXIS_');
		var getter = this._createAxisGetter(gamepad, mapping.axes, index);
		var that = this;

		gamepad.state[controlName] = 0;
		gamepad.lastState[controlName] = 0;

		updater = function() {
			var value = getter();
			var lastValue = gamepad.lastState[controlName];

			gamepad.state[controlName] = value;

			if ((value !== lastValue)) {
				that._fireAxisChangedEvent(gamepad, controlName, value);
			}

			gamepad.lastState[controlName] = value;
		};

		gamepad.updater.push(updater);
	};

	/**
	 * Fires an AXIS_CHANGED event
	 * @method _fireAxisChangedEvent
	 * @private
	 * @param {Object} gamepad the gamepad to notify for
	 * @param {String} controlName name of the control that changes its value
	 * @param {Number} value the new value
	 */
	Gamepad.prototype._fireAxisChangedEvent = function(gamepad, controlName, value) {
		var eventData = {
			gamepad: gamepad,
			axis: controlName,
			value: value
		};

		this._fire(Gamepad.Event.AXIS_CHANGED, eventData);
	};

	/**
	 * Creates a getter according to the mapping entry for the specific index.
	 * Currently supported entries:
	 *
	 * buttons.byButton[index]: Number := Index into gamepad.buttons; -1 tests byAxis
	 * buttons.byAxis[index]: Array := [Index into gamepad.axes; Zero Value, One Value]
	 *
	 * @method _createButtonGetter
	 * @private
	 * @param {Object} gamepad the gamepad for which to create a getter
	 * @param {Object} buttons the mappings entry for the buttons
	 * @param {Number} index the specific button entry
	 * @return {Function} a getter returning the value for the requested button
	 */
	Gamepad.prototype._createButtonGetter = (function() {
		var nullGetter = function() {
			return 0;
		};

		var createRangeGetter = function(valueGetter, from, to) {
			var getter = nullGetter;

			if (from < to) {
				getter = function() {
					var range = to - from;
					var value = valueGetter();

					value = (value - from) / range;

					return (value < 0) ? 0 : value;
				};
			} else if (to < from) {
				getter = function() {
					var range = from - to;
					var value = valueGetter();

					value = (value - to) / range;

					return (value > 1) ? 0 : (1 - value);
				};
			}

			return getter;
		};

		var isArray = function(thing) {
			return Object.prototype.toString.call(thing) === '[object Array]';
		};

		return function(gamepad, buttons, index) {
			var getter = nullGetter;
			var entry;
			var that = this;

			entry = buttons.byButton[index];
			if (entry !== -1) {
				if ((typeof(entry) === 'number') && (entry < gamepad.buttons.length)) {
					getter = function() {
						var value = gamepad.buttons[entry];

						if (typeof value === 'number') {
							return value;
						}

						if (typeof value.value === 'number') {
							return value.value;
						}

						return 0;
					};
				}
			} else if (buttons.byAxis && (index < buttons.byAxis.length)) {
				entry = buttons.byAxis[index];
				if (isArray(entry) && (entry.length == 3) && (entry[0] < gamepad.axes.length)) {
					getter = function() {
						var value = gamepad.axes[entry[0]];

						return that._applyDeadzoneMaximize(value);
					};

					getter = createRangeGetter(getter, entry[1], entry[2]);
				}
			}

			return getter;
		};
	})();

	/**
	 * Creates a getter according to the mapping entry for the specific index.
	 * Currently supported entries:
	 *
	 * axes.byAxis[index]: Number := Index into gamepad.axes; -1 ignored
	 *
	 * @method _createAxisGetter
	 * @private
	 * @param {Object} gamepad the gamepad for which to create a getter
	 * @param {Object} axes the mappings entry for the axes
	 * @param {Number} index the specific axis entry
	 * @return {Function} a getter returning the value for the requested axis
	 */
	Gamepad.prototype._createAxisGetter = (function() {
		var nullGetter = function() {
			return 0;
		};

		return function(gamepad, axes, index) {
			var getter = nullGetter;
			var entry;
			var that = this;

			entry = axes.byAxis[index];
			if (entry !== -1) {
				if ((typeof(entry) === 'number') && (entry < gamepad.axes.length)) {
					getter = function() {
						var value = gamepad.axes[entry];

						return that._applyDeadzoneMaximize(value);
					};
				}
			}

			return getter;
		};
	})();

	/**
	 * Disconnects from given gamepad.
	 *
	 * @method _disconnect
	 * @param {Object} gamepad Gamepad to disconnect
	 * @private
	 */
	Gamepad.prototype._disconnect = function(gamepad) {
		var newGamepads = [],
			i;

		if (typeof(this.gamepads[gamepad.index]) !== 'undefined') {
			delete this.gamepads[gamepad.index];
		}

		for (i = 0; i < this.gamepads.length; i++) {
			if (typeof(this.gamepads[i]) !== 'undefined') {
				newGamepads[i] = this.gamepads[i];
			}
		}

		this.gamepads = newGamepads;

		this._fire(Gamepad.Event.DISCONNECTED, gamepad);
	};

	/**
	 * Resolves controller type from its id.
	 *
	 * @method _resolveControllerType
	 * @param {String} id Controller id
	 * @return {String} Controller type, one of Gamepad.Type
	 * @private
	 */
	Gamepad.prototype._resolveControllerType = function(id) {
		// Lowercase and strip all extra whitespace.
		id = id.toLowerCase().replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '');

		if (id.indexOf('playstation') !== -1) {
			return Gamepad.Type.PLAYSTATION;
		} else if (
			id.indexOf('logitech') !== -1 || id.indexOf('wireless gamepad') !== -1) {
			return Gamepad.Type.LOGITECH;
		} else if (id.indexOf('xbox') !== -1 || id.indexOf('360') !== -1) {
			return Gamepad.Type.XBOX;
		} else if ((id.indexOf('79-6-generic') !== -1 && id.indexOf('joystick') !== -1) ||
			(id.indexOf('vendor: 0079 product: 0006') !== -1 &&
				id.indexOf('generic usb joystick') !== -1)) {
			return Gamepad.Type.N64;
		} else {
			return Gamepad.Type.UNKNOWN;
		}
	};

	/**
	 * @method _resolveMapping
	 * @private
	 * @param {Object} gamepad the gamepad for which to resolve the mapping
	 * @return {Object} a mapping object for the given gamepad
	 */
	Gamepad.prototype._resolveMapping = function(gamepad) {
		var mappings = Gamepad.Mappings;
		var mapping = null;
		var env = {
			platform: this.platform.getType(),
			type: this._resolveControllerType(gamepad.id)
		};
		var i;
		var test;

		for (i = 0; !mapping && (i < mappings.length); i++) {
			test = mappings[i];
			if (Gamepad.envMatchesFilter(test.env, env)) {
				mapping = test;
			}
		}

		return mapping || Gamepad.StandardMapping;
	};

	/**
	 * @method envMatchesFilter
	 * @static
	 * @param {Object} filter the filter object describing properties to match
	 * @param {Object} env the environment object that is matched against filter
	 * @return {Boolean} true if env is covered by filter
	 */
	Gamepad.envMatchesFilter = function(filter, env) {
		var result = true;
		var field;

		for (field in filter) {
			if (filter[field] !== env[field]) {
				result = false;
			}
		}

		return result;
	};

	/**
	 * Updates the controllers, triggering TICK events.
	 *
	 * @method _update
	 * @private
	 */
	Gamepad.prototype._update = function() {
		this.platform.update();

		this.gamepads.forEach(function(gamepad) {
			if (gamepad) {
				gamepad.updater.forEach(function(updater) {
					updater();
				});
			}
		});

		if (this.gamepads.length > 0) {
			this._fire(Gamepad.Event.TICK, this.gamepads);
		}
	},

	/**
	 * Applies deadzone and maximization.
	 *
	 * You can change the thresholds via deadzone and maximizeThreshold members.
	 *
	 * @method _applyDeadzoneMaximize
	 * @param {Number} value Value to modify
	 * @param {Number} [deadzone] Deadzone to apply
	 * @param {Number} [maximizeThreshold] From which value to maximize value
	 * @private
	 */
	Gamepad.prototype._applyDeadzoneMaximize = function(
		value,
		deadzone,
		maximizeThreshold) {
		deadzone = typeof(deadzone) !== 'undefined' ? deadzone : this.deadzone;
		maximizeThreshold = typeof(maximizeThreshold) !== 'undefined' ? maximizeThreshold : this.maximizeThreshold;

		if (value >= 0) {
			if (value < deadzone) {
				value = 0;
			} else if (value > maximizeThreshold) {
				value = 1;
			}
		} else {
			if (value > -deadzone) {
				value = 0;
			} else if (value < -maximizeThreshold) {
				value = -1;
			}
		}

		return value;
	};

	exports.Gamepad = Gamepad;

})(((typeof(module) !== 'undefined') && module.exports) || window);


text:
package org.elasticsearch.search.aggregations.pipeline.movavg.models;

import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.search.SearchParseException;

import java.io.IOException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;

public abstract class MovAvgModel {

    /**
     * Checks to see this model can produce a new value, without actually running the algo.
     * This can be used for models that have certain preconditions that need to be met in order
     * to short-circuit execution
     *
     * @param windowLength  Length of current window
     * @return              Returns `true` if calling next() will produce a value, `false` otherwise
     */
    public boolean hasValue(int windowLength) {
        // Default implementation can always provide a next() value
        return windowLength > 0;
    }

    /**
     * Returns the next value in the series, according to the underlying smoothing model
     *
     * @param values    Collection of numerics to movingAvg, usually windowed
     * @param <T>       Type of numeric
     * @return          Returns a double, since most smoothing methods operate on floating points
     */
    public abstract <T extends Number> double next(Collection<T> values);

    /**
     * Predicts the next `n` values in the series.
     *
     * @param values            Collection of numerics to movingAvg, usually windowed
     * @param numPredictions    Number of newly generated predictions to return
     * @param <T>               Type of numeric
     * @return                  Returns an array of doubles, since most smoothing methods operate on floating points
     */
    public <T extends Number> double[] predict(Collection<T> values, int numPredictions) {
        assert(numPredictions >= 1);

        // If there are no values, we can't do anything.  Return an array of NaNs.
        if (values.isEmpty()) {
            return emptyPredictions(numPredictions);
        }

        return doPredict(values, numPredictions);
    }

    /**
     * Calls to the model-specific implementation which actually generates the predictions
     *
     * @param values            Collection of numerics to movingAvg, usually windowed
     * @param numPredictions    Number of newly generated predictions to return
     * @param <T>               Type of numeric
     * @return                  Returns an array of doubles, since most smoothing methods operate on floating points
     */
    protected abstract <T extends Number> double[] doPredict(Collection<T> values, int numPredictions);

    /**
     * Returns an empty set of predictions, filled with NaNs
     */
    protected double[] emptyPredictions(int numPredictions) {
        double[] predictions = new double[numPredictions];
        Arrays.fill(predictions, Double.NaN);
        return predictions;
    }

    /**
     * Write the model to the output stream
     *
     * @param out   Output stream
     * @throws IOException
     */
    public abstract void writeTo(StreamOutput out) throws IOException;

    /**
     * Abstract class which also provides some concrete parsing functionality.
     */
    public abstract static class AbstractModelParser {

        /**
         * Returns the name of the model
         *
         * @return The model's name
         */
        public abstract String getName();

        /**
         * Parse a settings hash that is specific to this model
         *
         * @param settings           Map of settings, extracted from the request
         * @param pipelineName       Name of the parent pipeline agg
         * @param windowSize         Size of the window for this moving avg
         * @param parseFieldMatcher  Matcher for field names
         * @return                   A fully built moving average model
         */
        public abstract MovAvgModel parse(@Nullable Map<String, Object> settings, String pipelineName, int windowSize, ParseFieldMatcher parseFieldMatcher) throws ParseException;

        /**
         * Extracts a 0-1 inclusive double from the settings map, otherwise throws an exception
         *
         * @param settings      Map of settings provided to this model
         * @param name          Name of parameter we are attempting to extract
         * @param defaultValue  Default value to be used if value does not exist in map
         *
         * @throws ParseException
         *
         * @return Double value extracted from settings map
         */
        protected double parseDoubleParam(@Nullable Map<String, Object> settings, String name, double defaultValue) throws ParseException {
            if (settings == null) {
                return defaultValue;
            }

            Object value = settings.get(name);
            if (value == null) {
                return defaultValue;
            } else if (value instanceof Number) {
                double v = ((Number) value).doubleValue();
                if (v >= 0 && v <= 1) {
                    return v;
                }

                throw new ParseException("Parameter [" + name + "] must be between 0-1 inclusive.  Provided"
                        + "value was [" + v + "]", 0);
            }

            throw new ParseException("Parameter [" + name + "] must be a double, type `"
                    + value.getClass().getSimpleName() + "` provided instead", 0);
        }

        /**
         * Extracts an integer from the settings map, otherwise throws an exception
         *
         * @param settings      Map of settings provided to this model
         * @param name          Name of parameter we are attempting to extract
         * @param defaultValue  Default value to be used if value does not exist in map
         *
         * @throws ParseException
         *
         * @return Integer value extracted from settings map
         */
        protected int parseIntegerParam(@Nullable Map<String, Object> settings, String name, int defaultValue) throws ParseException {
            if (settings == null) {
                return defaultValue;
            }

            Object value = settings.get(name);
            if (value == null) {
                return defaultValue;
            } else if (value instanceof Number) {
                return ((Number) value).intValue();
            }

            throw new ParseException("Parameter [" + name + "] must be an integer, type `"
                    + value.getClass().getSimpleName() + "` provided instead", 0);
        }

        /**
         * Extracts a boolean from the settings map, otherwise throws an exception
         *
         * @param settings      Map of settings provided to this model
         * @param name          Name of parameter we are attempting to extract
         * @param defaultValue  Default value to be used if value does not exist in map
         *
         * @throws SearchParseException
         *
         * @return Boolean value extracted from settings map
         */
        protected boolean parseBoolParam(@Nullable Map<String, Object> settings, String name, boolean defaultValue) throws ParseException {
            if (settings == null) {
                return defaultValue;
            }

            Object value = settings.get(name);
            if (value == null) {
                return defaultValue;
            } else if (value instanceof Boolean) {
                return (Boolean)value;
            }

            throw new ParseException("Parameter [" + name + "] must be a boolean, type `"
                    + value.getClass().getSimpleName() + "` provided instead", 0);
        }
    }

}


text:
using Cofoundry.Domain.Data.Internal;

namespace Cofoundry.Domain.Internal;

/// <summary>
/// Logs user auditing information in the database to record
/// the successful authentication of a user account.
/// </summary>
public class LogSuccessfulAuthenticationCommandHandler
    : ICommandHandler<LogSuccessfulAuthenticationCommand>
    , IIgnorePermissionCheckHandler
{
    private readonly IUserStoredProcedures _userStoredProcedures;
    private readonly IClientConnectionService _clientConnectionService;

    public LogSuccessfulAuthenticationCommandHandler(
        IUserStoredProcedures userStoredProcedures,
        IClientConnectionService clientConnectionService
        )
    {
        _userStoredProcedures = userStoredProcedures;
        _clientConnectionService = clientConnectionService;
    }

    public async Task ExecuteAsync(LogSuccessfulAuthenticationCommand command, IExecutionContext executionContext)
    {
        var connectionInfo = _clientConnectionService.GetConnectionInfo();

        await _userStoredProcedures.LogAuthenticationSuccessAsync(
            command.UserId,
            connectionInfo.IPAddress,
            executionContext.ExecutionDate
            );
    }
}


text:
package de.slikey.game.event;

import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;

import de.slikey.game.player.PlayerClass;

/**
 * Called when a PlayerClass is enabled for a player.
 *
 * @author Kevin Carstens
 * @since 01.05.2014
 */
public class EnablePlayerClassEvent extends PlayerClassEvent {

	private static final HandlerList handlers = new HandlerList();

	public EnablePlayerClassEvent(final Player player, final PlayerClass playerclass) {
		super(player, playerclass);
	}

	@Override
	public HandlerList getHandlers() {
		return handlers;
	}

	public static HandlerList getHandlerList() {
		return handlers;
	}

}