text:
import logging
import os
import shutil
import stat
import time
from datetime import datetime

from django.conf import settings
from django.db.models import Q

import commonware.log
import cronjobs
from celery import chord

import mkt
from lib.metrics import get_monolith_client
from mkt.api.models import Nonce
from mkt.developers.models import ActivityLog
from mkt.files.models import File, FileUpload
from mkt.site.decorators import write
from mkt.site.utils import chunked, days_ago, walkfiles

from .indexers import WebappIndexer
from .models import Installed, Installs, Trending, Webapp
from .tasks import delete_logs, dump_user_installs, zip_users

log = commonware.log.getLogger('z.cron')
task_log = logging.getLogger('z.task')

def _change_last_updated(next):
    # We jump through some hoops here to make sure we only change the add-ons
    # that really need it, and to invalidate properly.
    current = dict(Webapp.objects.values_list('id', 'last_updated'))
    changes = {}

    for addon, last_updated in next.items():
        try:
            if current[addon] != last_updated:
                changes[addon] = last_updated
        except KeyError:
            pass

    if not changes:
        return

    log.debug('Updating %s add-ons' % len(changes))
    # Update + invalidate.
    qs = Webapp.objects.no_cache().filter(id__in=changes).no_transforms()
    for addon in qs:
        addon.last_updated = changes[addon.id]
        addon.save()

@cronjobs.register
@write
def addon_last_updated():
    next = {}
    qs = Webapp._last_updated_queries().values()
    for addon, last_updated in qs.values_list('id', 'last_updated'):
        next[addon] = last_updated

    _change_last_updated(next)

    # Get anything that didn't match above.
    other = (Webapp.objects.no_cache().filter(last_updated__isnull=True)
             .values_list('id', 'created'))
    _change_last_updated(dict(other))

@cronjobs.register
def hide_disabled_files():
    # If an add-on or a file is disabled, it should be moved to
    # GUARDED_ADDONS_PATH so it's not publicly visible.
    #
    # We ignore deleted versions since we hide those files when deleted and
    # also due to bug 980916.
    ids = (File.objects
           .filter(version__deleted=False)
           .filter(Q(status=mkt.STATUS_DISABLED) |
                   Q(version__addon__status=mkt.STATUS_DISABLED) |
                   Q(version__addon__disabled_by_user=True))
           .values_list('id', flat=True))
    for chunk in chunked(ids, 300):
        qs = File.objects.no_cache().filter(id__in=chunk)
        qs = qs.select_related('version')
        for f in qs:
            f.hide_disabled_file()

@cronjobs.register
def unhide_disabled_files():
    # Files are getting stuck in /guarded-addons for some reason. This job
    # makes sure guarded add-ons are supposed to be disabled.
    log = logging.getLogger('z.files.disabled')
    q = (Q(version__addon__status=mkt.STATUS_DISABLED) |
         Q(version__addon__disabled_by_user=True))
    files = set(File.objects.filter(q | Q(status=mkt.STATUS_DISABLED))
                .values_list('version__addon', 'filename'))
    for filepath in walkfiles(settings.GUARDED_ADDONS_PATH):
        addon, filename = filepath.split('/')[-2:]
        if tuple([int(addon), filename]) not in files:
            log.warning('File that should not be guarded: %s.' % filepath)
            try:
                file_ = (File.objects.select_related('version__addon')
                         .get(version__addon=addon, filename=filename))
                file_.unhide_disabled_file()
            except File.DoesNotExist:
                log.warning('File object does not exist for: %s.' % filepath)
            except Exception:
                log.error('Could not unhide file: %s.' % filepath,
                          exc_info=True)

@cronjobs.register
def clean_old_signed(seconds=60 * 60):
    """Clean out apps signed for reviewers."""
    log.info('Removing old apps signed for reviewers')
    root = settings.SIGNED_APPS_REVIEWER_PATH
    for path in os.listdir(root):
        full = os.path.join(root, path)
        age = time.time() - os.stat(full)[stat.ST_ATIME]
        if age > seconds:
            log.debug('Removing signed app: %s, %dsecs old.' % (full, age))
            shutil.rmtree(full)

def _get_installs(app_id):
    """
    Calculate popularity of app for all regions and per region.

    Returns value in the format of::

        {'all': <global installs>,
         <region_slug>: <regional installs>,
         ...}

    """
    # How many days back do we include when calculating popularity.
    POPULARITY_PERIOD = 90

    client = get_monolith_client()

    popular = {
        'filter': {
            'range': {
                'date': {
                    'gte': days_ago(POPULARITY_PERIOD).date().isoformat(),
                    'lte': days_ago(1).date().isoformat()
                }
            }
        },
        'aggs': {
            'total_installs': {
                'sum': {
                    'field': 'app_installs'
                }
            }
        }
    }

    query = {
        'query': {
            'filtered': {
                'query': {'match_all': {}},
                'filter': {'term': {'app-id': app_id}}
            }
        },
        'aggregations': {
            'popular': popular,
            'region': {
                'terms': {
                    'field': 'region',
                    # Add size so we get all regions, not just the top 10.
                    'size': len(mkt.regions.ALL_REGIONS)
                },
                'aggregations': {
                    'popular': popular
                }
            }
        },
        'size': 0
    }

    try:
        res = client.raw(query)
    except ValueError as e:
        task_log.error('Error response from Monolith: {0}'.format(e))
        return {}

    if 'aggregations' not in res:
        task_log.error('No installs for app {}'.format(app_id))
        return {}

    results = {
        'all': res['aggregations']['popular']['total_installs']['value']
    }

    if 'region' in res['aggregations']:
        for regional_res in res['aggregations']['region']['buckets']:
            region_slug = regional_res['key']
            popular = regional_res['popular']['total_installs']['value']
            results[region_slug] = popular

    return results

@cronjobs.register
@write
def update_app_installs():
    """
    Update app install counts for all published apps.

    We break these into chunks so we can bulk index them. Each chunk will
    process the apps in it and reindex them in bulk. After all the chunks are
    processed we find records that haven't been updated and purge/reindex those
    so we nullify their values.

    """
    chunk_size = 100

    ids = list(Webapp.objects.filter(status=mkt.STATUS_PUBLIC,
                                     disabled_by_user=False)
                     .values_list('id', flat=True))

    for chunk in chunked(ids, chunk_size):

        count = 0
        times = []
        reindex_ids = []

        for app in Webapp.objects.filter(id__in=chunk).no_transforms():

            reindex = False
            count += 1
            now = datetime.now()
            t_start = time.time()

            scores = _get_installs(app.id)

            # Update global installs, then per-region installs below.
            value = scores.get('all')
            if value > 0:
                reindex = True
                installs, created = app.installs.get_or_create(
                    region=0, defaults={'value': value})
                if not created:
                    installs.update(value=value, modified=now)
            else:
                # The value is <= 0 so we can just ignore it.
                app.installs.filter(region=0).delete()

            for region in mkt.regions.REGIONS_DICT.values():
                value = scores.get(region.slug)
                if value > 0:
                    reindex = True
                    installs, created = app.installs.get_or_create(
                        region=region.id, defaults={'value': value})
                    if not created:
                        installs.update(value=value, modified=now)
                else:
                    # The value is <= 0 so we can just ignore it.
                    app.installs.filter(region=region.id).delete()

            if reindex:
                reindex_ids.append(app.id)

            times.append(time.time() - t_start)

        # Now reindex the apps that actually have a popularity value.
        if reindex_ids:
            WebappIndexer.run_indexing(reindex_ids)

        log.info('Installs calculated for %s apps. Avg time overall: '
                 '%0.2fs' % (count, sum(times) / count))

    # Purge any records that were not updated.
    #
    # Note: We force update `modified` even if no data changes so any records
    # with older modified times can be purged.
    now = datetime.now()
    midnight = datetime(year=now.year, month=now.month, day=now.day)

    qs = Installs.objects.filter(modified__lte=midnight)
    # First get the IDs so we know what to reindex.
    purged_ids = qs.values_list('addon', flat=True).distinct()
    # Then delete them.
    qs.delete()

    for ids in chunked(purged_ids, chunk_size):
        WebappIndexer.run_indexing(ids)

def _get_trending(app_id):
    """
    Calculate trending for app for all regions and per region.

    a = installs from 8 days ago to 1 day ago
    b = installs from 29 days ago to 9 days ago, averaged per week
    trending = (a - b) / b if a > 100 and b > 1 else 0

    Returns value in the format of::

        {'all': <global trending score>,
         <region_slug>: <regional trending score>,
         ...}

    """
    # How many app installs are required in the prior week to be considered
    # "trending". Adjust this as total Marketplace app installs increases.
    #
    # Note: AMO uses 1000.0 for add-ons.
    PRIOR_WEEK_INSTALL_THRESHOLD = 100.0

    client = get_monolith_client()

    week1 = {
        'filter': {
            'range': {
                'date': {
                    'gte': days_ago(8).date().isoformat(),
                    'lte': days_ago(1).date().isoformat()
                }
            }
        },
        'aggs': {
            'total_installs': {
                'sum': {
                    'field': 'app_installs'
                }
            }
        }
    }
    week3 = {
        'filter': {
            'range': {
                'date': {
                    'gte': days_ago(29).date().isoformat(),
                    'lte': days_ago(9).date().isoformat()
                }
            }
        },
        'aggs': {
            'total_installs': {
                'sum': {
                    'field': 'app_installs'
                }
            }
        }
    }

    query = {
        'query': {
            'filtered': {
                'query': {'match_all': {}},
                'filter': {'term': {'app-id': app_id}}
            }
        },
        'aggregations': {
            'week1': week1,
            'week3': week3,
            'region': {
                'terms': {
                    'field': 'region',
                    # Add size so we get all regions, not just the top 10.
                    'size': len(mkt.regions.ALL_REGIONS)
                },
                'aggregations': {
                    'week1': week1,
                    'week3': week3
                }
            }
        },
        'size': 0
    }

    try:
        res = client.raw(query)
    except ValueError as e:
        task_log.error('Error response from Monolith: {0}'.format(e))
        return {}

    if 'aggregations' not in res:
        task_log.error('No installs for app {}'.format(app_id))
        return {}

    def _score(week1, week3):
        # If last week app installs are < 100, this app isn't trending.
        if week1 < PRIOR_WEEK_INSTALL_THRESHOLD:
            return 0.0

        score = 0.0
        if week3 > 1.0:
            score = (week1 - week3) / week3
        if score < 0.0:
            score = 0.0
        return score

    # Global trending score.
    week1 = res['aggregations']['week1']['total_installs']['value']
    week3 = res['aggregations']['week3']['total_installs']['value'] / 3.0

    if week1 < PRIOR_WEEK_INSTALL_THRESHOLD:
        # If global installs over the last week aren't over 100, we
        # short-circuit and return a zero-like value as this is not a trending
        # app by definition. Since global installs aren't above 100, per-region
        # installs won't be either.
        return {}

    results = {
        'all': _score(week1, week3)
    }

    if 'region' in res['aggregations']:
        for regional_res in res['aggregations']['region']['buckets']:
            region_slug = regional_res['key']
            week1 = regional_res['week1']['total_installs']['value']
            week3 = regional_res['week3']['total_installs']['value'] / 3.0
            results[region_slug] = _score(week1, week3)

    return results

@cronjobs.register
@write
def update_app_trending():
    """
    Update trending for all published apps.

    We break these into chunks so we can bulk index them. Each chunk will
    process the apps in it and reindex them in bulk. After all the chunks are
    processed we find records that haven't been updated and purge/reindex those
    so we nullify their values.

    """
    chunk_size = 100

    ids = list(Webapp.objects.filter(status=mkt.STATUS_PUBLIC,
                                     disabled_by_user=False)
                     .values_list('id', flat=True))

    for chunk in chunked(ids, chunk_size):

        count = 0
        times = []
        reindex_ids = []

        for app in Webapp.objects.filter(id__in=chunk).no_transforms():

            reindex = False
            count += 1
            now = datetime.now()
            t_start = time.time()

            scores = _get_trending(app.id)

            # Update global trending, then per-region trending below.
            value = scores.get('all')
            if value > 0:
                reindex = True
                trending, created = app.trending.get_or_create(
                    region=0, defaults={'value': value})
                if not created:
                    trending.update(value=value, modified=now)
            else:
                # The value is <= 0 so the app is not trending. Let's remove it
                # from the trending table.
                app.trending.filter(region=0).delete()

            for region in mkt.regions.REGIONS_DICT.values():
                value = scores.get(region.slug)
                if value > 0:
                    reindex = True
                    trending, created = app.trending.get_or_create(
                        region=region.id, defaults={'value': value})
                    if not created:
                        trending.update(value=value, modified=now)
                else:
                    # The value is <= 0 so the app is not trending.
                    # Let's remove it from the trending table.
                    app.trending.filter(region=region.id).delete()

            times.append(time.time() - t_start)

            if reindex:
                reindex_ids.append(app.id)

        # Now reindex the apps that actually have a trending score.
        if reindex_ids:
            WebappIndexer.run_indexing(reindex_ids)

        log.info('Trending calculated for %s apps. Avg time overall: '
                 '%0.2fs' % (count, sum(times) / count))

    # Purge any records that were not updated.
    #
    # Note: We force update `modified` even if no data changes so any records
    # with older modified times can be purged.
    now = datetime.now()
    midnight = datetime(year=now.year, month=now.month, day=now.day)

    qs = Trending.objects.filter(modified__lte=midnight)
    # First get the IDs so we know what to reindex.
    purged_ids = qs.values_list('addon', flat=True).distinct()
    # Then delete them.
    qs.delete()

    for ids in chunked(purged_ids, chunk_size):
        WebappIndexer.run_indexing(ids)

@cronjobs.register
def dump_user_installs_cron():
    """
    Sets up tasks to do user install dumps.
    """
    chunk_size = 100
    # Get valid users to dump.
    user_ids = set(Installed.objects.filter(user__enable_recommendations=True)
                   .values_list('user', flat=True))

    # Remove old dump data before running.
    user_dir = os.path.join(settings.DUMPED_USERS_PATH, 'users')
    if os.path.exists(user_dir):
        shutil.rmtree(user_dir)

    grouping = []
    for chunk in chunked(user_ids, chunk_size):
        grouping.append(dump_user_installs.subtask(args=[chunk]))

    post = zip_users.subtask(immutable=True)
    ts = chord(grouping, post)
    ts.apply_async()

def _remove_stale_files(path, age, msg):
    for file_name in os.listdir(path):
        file_path = os.path.join(path, file_name)
        if (os.stat(file_path).st_mtime < time.time() - age):
            log.debug(msg.format(file_path))
            os.remove(file_path)

@cronjobs.register
def mkt_gc(**kw):
    """Site-wide garbage collections."""
    log.debug('Collecting data to delete')
    logs = (ActivityLog.objects.filter(created__lt=days_ago(90))
            .exclude(action__in=mkt.LOG_KEEP).values_list('id', flat=True))

    for chunk in chunked(logs, 100):
        chunk.sort()
        log.debug('Deleting log entries: %s' % str(chunk))
        delete_logs.delay(chunk)

    # Clear oauth nonce rows. These expire after 10 minutes but we're just
    # clearing those that are more than 1 day old.
    Nonce.objects.filter(created__lt=days_ago(1)).delete()

    # Delete the dump apps over 30 days.
    _remove_stale_files(settings.DUMPED_APPS_PATH,
                        settings.DUMPED_APPS_DAYS_DELETE,
                        'Deleting old tarball: {0}')

    # Delete the dumped user installs over 30 days.
    _remove_stale_files(settings.DUMPED_USERS_PATH,
                        settings.DUMPED_USERS_DAYS_DELETE,
                        'Deleting old tarball: {0}')

    # Delete old files in select directories under TMP_PATH.
    _remove_stale_files(os.path.join(settings.TMP_PATH, 'preview'),
                        settings.TMP_PATH_DAYS_DELETE,
                        'Deleting TMP_PATH file: {0}')
    _remove_stale_files(os.path.join(settings.TMP_PATH, 'icon'),
                        settings.TMP_PATH_DAYS_DELETE,
                        'Deleting TMP_PATH file: {0}')

    # Delete stale FileUploads.
    for fu in FileUpload.objects.filter(created__lte=days_ago(90)):
        log.debug(u'[FileUpload:{uuid}] Removing file: {path}'
                  .format(uuid=fu.uuid, path=fu.path))
        if fu.path:
            try:
                os.remove(fu.path)
            except OSError:
                pass
        fu.delete()


text:
package org.springframework.data.elasticsearch.core.query;

import org.elasticsearch.index.query.QueryBuilder;

/**
 * DeleteQuery
 *
 * @author Rizwan Idrees
 * @author Mohsin Husen
 */
public class DeleteQuery {

	private QueryBuilder query;
	private String index;
	private String type;
	private Integer pageSize;
	private Long scrollTimeInMillis;

	public QueryBuilder getQuery() {
		return query;
	}

	public void setQuery(QueryBuilder query) {
		this.query = query;
	}

	public String getIndex() {
		return index;
	}

	public void setIndex(String index) {
		this.index = index;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public Integer getPageSize() {
		return pageSize;
	}

	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}

	public Long getScrollTimeInMillis() {
		return scrollTimeInMillis;
	}

	public void setScrollTimeInMillis(Long scrollTimeInMillis) {
		this.scrollTimeInMillis = scrollTimeInMillis;
	}
}

redpajama_set_name: RedPajamaGithub


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.01.11 at 02:39:34 PM EST
//

package schemas.docbook;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlIDREF;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element ref="{http://docbook.org/ns/docbook}colspec" maxOccurs="unbounded" minOccurs="0"/>
 *         <element ref="{http://docbook.org/ns/docbook}spanspec" maxOccurs="unbounded" minOccurs="0"/>
 *         <element ref="{http://docbook.org/ns/docbook}thead" minOccurs="0"/>
 *         <element ref="{http://docbook.org/ns/docbook}tbody"/>
 *       </sequence>
 *       <attGroup ref="{http://docbook.org/ns/docbook}db.common.attributes"/>
 *       <attGroup ref="{http://docbook.org/ns/docbook}db.common.linking.attributes"/>
 *       <attribute name="role" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
 *       <attribute name="char" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
 *       <attribute name="charoff" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
 *       <attribute name="colname" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
 *       <attribute name="namest" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
 *       <attribute name="spanname" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
 *       <attribute name="nameend" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
 *       <attribute name="tgroupstyle" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
 *       <attribute name="cols" type="{http://www.w3.org/2001/XMLSchema}NMTOKEN" />
 *       <attribute name="colsep">
 *         <simpleType>
 *           <restriction base="{http://www.w3.org/2001/XMLSchema}token">
 *             <enumeration value="0"/>
 *             <enumeration value="1"/>
 *           </restriction>
 *         </simpleType>
 *       </attribute>
 *       <attribute name="rowsep">
 *         <simpleType>
 *           <restriction base="{http://www.w3.org/2001/XMLSchema}token">
 *             <enumeration value="0"/>
 *             <enumeration value="1"/>
 *           </restriction>
 *         </simpleType>
 *       </attribute>
 *       <attribute name="align">
 *         <simpleType>
 *           <restriction base="{http://www.w3.org/2001/XMLSchema}token">
 *             <enumeration value="center"/>
 *             <enumeration value="char"/>
 *             <enumeration value="justify"/>
 *             <enumeration value="left"/>
 *             <enumeration value="right"/>
 *           </restriction>
 *         </simpleType>
 *       </attribute>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "colspecs",
    "spanspecs",
    "thead",
    "tbody"
})
@XmlRootElement(name = "entrytbl")
public class Entrytbl {

    @XmlElement(name = "colspec")
    protected List<Colspec> colspecs;
    @XmlElement(name = "spanspec")
    protected List<Spanspec> spanspecs;
    protected Thead thead;
    @XmlElement(required = true)
    protected Tbody tbody;
    @XmlAttribute(name = "role")
    @XmlSchemaType(name = "anySimpleType")
    protected String role;
    @XmlAttribute(name = "char")
    @XmlSchemaType(name = "anySimpleType")
    protected String _char;
    @XmlAttribute(name = "charoff")
    @XmlSchemaType(name = "anySimpleType")
    protected String charoff;
    @XmlAttribute(name = "colname")
    @XmlSchemaType(name = "anySimpleType")
    protected String colname;
    @XmlAttribute(name = "namest")
    @XmlSchemaType(name = "anySimpleType")
    protected String namest;
    @XmlAttribute(name = "spanname")
    @XmlSchemaType(name = "anySimpleType")
    protected String spanname;
    @XmlAttribute(name = "nameend")
    @XmlSchemaType(name = "anySimpleType")
    protected String nameend;
    @XmlAttribute(name = "tgroupstyle")
    @XmlSchemaType(name = "anySimpleType")
    protected String tgroupstyle;
    @XmlAttribute(name = "cols")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "NMTOKEN")
    protected String cols;
    @XmlAttribute(name = "colsep")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    protected String colsep;
    @XmlAttribute(name = "rowsep")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    protected String rowsep;
    @XmlAttribute(name = "align")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    protected String align;
    @XmlAttribute(name = "id", namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlID
    @XmlSchemaType(name = "ID")
    protected String id;
    @XmlAttribute(name = "version")
    @XmlSchemaType(name = "anySimpleType")
    protected String commonVersion;
    @XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlSchemaType(name = "anySimpleType")
    protected String xmlLang;
    @XmlAttribute(name = "base", namespace = "http://www.w3.org/XML/1998/namespace")
    @XmlSchemaType(name = "anySimpleType")
    protected String base;
    @XmlAttribute(name = "remap")
    @XmlSchemaType(name = "anySimpleType")
    protected String remap;
    @XmlAttribute(name = "xreflabel")
    @XmlSchemaType(name = "anySimpleType")
    protected String xreflabel;
    @XmlAttribute(name = "revisionflag")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    protected String revisionflag;
    @XmlAttribute(name = "dir")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    protected String dir;
    @XmlAttribute(name = "arch")
    @XmlSchemaType(name = "anySimpleType")
    protected String arch;
    @XmlAttribute(name = "audience")
    @XmlSchemaType(name = "anySimpleType")
    protected String audience;
    @XmlAttribute(name = "condition")
    @XmlSchemaType(name = "anySimpleType")
    protected String condition;
    @XmlAttribute(name = "conformance")
    @XmlSchemaType(name = "anySimpleType")
    protected String conformance;
    @XmlAttribute(name = "os")
    @XmlSchemaType(name = "anySimpleType")
    protected String os;
    @XmlAttribute(name = "revision")
    @XmlSchemaType(name = "anySimpleType")
    protected String commonRevision;
    @XmlAttribute(name = "security")
    @XmlSchemaType(name = "anySimpleType")
    protected String security;
    @XmlAttribute(name = "userlevel")
    @XmlSchemaType(name = "anySimpleType")
    protected String userlevel;
    @XmlAttribute(name = "vendor")
    @XmlSchemaType(name = "anySimpleType")
    protected String vendor;
    @XmlAttribute(name = "wordsize")
    @XmlSchemaType(name = "anySimpleType")
    protected String wordsize;
    @XmlAttribute(name = "annotations")
    @XmlSchemaType(name = "anySimpleType")
    protected String annotations;
    @XmlAttribute(name = "linkend")
    @XmlIDREF
    @XmlSchemaType(name = "IDREF")
    protected Object linkend;
    @XmlAttribute(name = "href", namespace = "http://www.w3.org/1999/xlink")
    @XmlSchemaType(name = "anySimpleType")
    protected String href;
    @XmlAttribute(name = "type", namespace = "http://www.w3.org/1999/xlink")
    @XmlSchemaType(name = "anySimpleType")
    protected String xlinkType;
    @XmlAttribute(name = "role", namespace = "http://www.w3.org/1999/xlink")
    @XmlSchemaType(name = "anySimpleType")
    protected String xlinkRole;
    @XmlAttribute(name = "arcrole", namespace = "http://www.w3.org/1999/xlink")
    @XmlSchemaType(name = "anySimpleType")
    protected String arcrole;
    @XmlAttribute(name = "title", namespace = "http://www.w3.org/1999/xlink")
    @XmlSchemaType(name = "anySimpleType")
    protected String xlinkTitle;
    @XmlAttribute(name = "show", namespace = "http://www.w3.org/1999/xlink")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    protected String show;
    @XmlAttribute(name = "actuate", namespace = "http://www.w3.org/1999/xlink")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    protected String actuate;

    /**
     * Gets the value of the colspecs property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the colspecs property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getColspecs().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link Colspec }
     *
     *
     */
    public List<Colspec> getColspecs() {
        if (colspecs == null) {
            colspecs = new ArrayList<Colspec>();
        }
        return this.colspecs;
    }

    /**
     * Gets the value of the spanspecs property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the spanspecs property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getSpanspecs().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link Spanspec }
     *
     *
     */
    public List<Spanspec> getSpanspecs() {
        if (spanspecs == null) {
            spanspecs = new ArrayList<Spanspec>();
        }
        return this.spanspecs;
    }

    /**
     * Gets the value of the thead property.
     *
     * @return
     *     possible object is
     *     {@link Thead }
     *
     */
    public Thead getThead() {
        return thead;
    }

    /**
     * Sets the value of the thead property.
     *
     * @param value
     *     allowed object is
     *     {@link Thead }
     *
     */
    public void setThead(Thead value) {
        this.thead = value;
    }

    /**
     * Gets the value of the tbody property.
     *
     * @return
     *     possible object is
     *     {@link Tbody }
     *
     */
    public Tbody getTbody() {
        return tbody;
    }

    /**
     * Sets the value of the tbody property.
     *
     * @param value
     *     allowed object is
     *     {@link Tbody }
     *
     */
    public void setTbody(Tbody value) {
        this.tbody = value;
    }

    /**
     * Gets the value of the role property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getRole() {
        return role;
    }

    /**
     * Sets the value of the role property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setRole(String value) {
        this.role = value;
    }

    /**
     * Gets the value of the char property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getChar() {
        return _char;
    }

    /**
     * Sets the value of the char property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setChar(String value) {
        this._char = value;
    }

    /**
     * Gets the value of the charoff property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getCharoff() {
        return charoff;
    }

    /**
     * Sets the value of the charoff property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setCharoff(String value) {
        this.charoff = value;
    }

    /**
     * Gets the value of the colname property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getColname() {
        return colname;
    }

    /**
     * Sets the value of the colname property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setColname(String value) {
        this.colname = value;
    }

    /**
     * Gets the value of the namest property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getNamest() {
        return namest;
    }

    /**
     * Sets the value of the namest property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setNamest(String value) {
        this.namest = value;
    }

    /**
     * Gets the value of the spanname property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getSpanname() {
        return spanname;
    }

    /**
     * Sets the value of the spanname property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setSpanname(String value) {
        this.spanname = value;
    }

    /**
     * Gets the value of the nameend property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getNameend() {
        return nameend;
    }

    /**
     * Sets the value of the nameend property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setNameend(String value) {
        this.nameend = value;
    }

    /**
     * Gets the value of the tgroupstyle property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getTgroupstyle() {
        return tgroupstyle;
    }

    /**
     * Sets the value of the tgroupstyle property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setTgroupstyle(String value) {
        this.tgroupstyle = value;
    }

    /**
     * Gets the value of the cols property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getCols() {
        return cols;
    }

    /**
     * Sets the value of the cols property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setCols(String value) {
        this.cols = value;
    }

    /**
     * Gets the value of the colsep property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getColsep() {
        return colsep;
    }

    /**
     * Sets the value of the colsep property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setColsep(String value) {
        this.colsep = value;
    }

    /**
     * Gets the value of the rowsep property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getRowsep() {
        return rowsep;
    }

    /**
     * Sets the value of the rowsep property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setRowsep(String value) {
        this.rowsep = value;
    }

    /**
     * Gets the value of the align property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getAlign() {
        return align;
    }

    /**
     * Sets the value of the align property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setAlign(String value) {
        this.align = value;
    }

    /**
     * Gets the value of the id property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getId() {
        return id;
    }

    /**
     * Sets the value of the id property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setId(String value) {
        this.id = value;
    }

    /**
     * Gets the value of the commonVersion property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getCommonVersion() {
        return commonVersion;
    }

    /**
     * Sets the value of the commonVersion property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setCommonVersion(String value) {
        this.commonVersion = value;
    }

    /**
     * Gets the value of the xmlLang property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getXmlLang() {
        return xmlLang;
    }

    /**
     * Sets the value of the xmlLang property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setXmlLang(String value) {
        this.xmlLang = value;
    }

    /**
     * Gets the value of the base property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getBase() {
        return base;
    }

    /**
     * Sets the value of the base property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setBase(String value) {
        this.base = value;
    }

    /**
     * Gets the value of the remap property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getRemap() {
        return remap;
    }

    /**
     * Sets the value of the remap property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setRemap(String value) {
        this.remap = value;
    }

    /**
     * Gets the value of the xreflabel property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getXreflabel() {
        return xreflabel;
    }

    /**
     * Sets the value of the xreflabel property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setXreflabel(String value) {
        this.xreflabel = value;
    }

    /**
     * Gets the value of the revisionflag property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getRevisionflag() {
        return revisionflag;
    }

    /**
     * Sets the value of the revisionflag property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setRevisionflag(String value) {
        this.revisionflag = value;
    }

    /**
     * Gets the value of the dir property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getDir() {
        return dir;
    }

    /**
     * Sets the value of the dir property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDir(String value) {
        this.dir = value;
    }

    /**
     * Gets the value of the arch property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getArch() {
        return arch;
    }

    /**
     * Sets the value of the arch property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setArch(String value) {
        this.arch = value;
    }

    /**
     * Gets the value of the audience property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getAudience() {
        return audience;
    }

    /**
     * Sets the value of the audience property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setAudience(String value) {
        this.audience = value;
    }

    /**
     * Gets the value of the condition property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getCondition() {
        return condition;
    }

    /**
     * Sets the value of the condition property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setCondition(String value) {
        this.condition = value;
    }

    /**
     * Gets the value of the conformance property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getConformance() {
        return conformance;
    }

    /**
     * Sets the value of the conformance property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setConformance(String value) {
        this.conformance = value;
    }

    /**
     * Gets the value of the os property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getOs() {
        return os;
    }

    /**
     * Sets the value of the os property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setOs(String value) {
        this.os = value;
    }

    /**
     * Gets the value of the commonRevision property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getCommonRevision() {
        return commonRevision;
    }

    /**
     * Sets the value of the commonRevision property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setCommonRevision(String value) {
        this.commonRevision = value;
    }

    /**
     * Gets the value of the security property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getSecurity() {
        return security;
    }

    /**
     * Sets the value of the security property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setSecurity(String value) {
        this.security = value;
    }

    /**
     * Gets the value of the userlevel property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getUserlevel() {
        return userlevel;
    }

    /**
     * Sets the value of the userlevel property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setUserlevel(String value) {
        this.userlevel = value;
    }

    /**
     * Gets the value of the vendor property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getVendor() {
        return vendor;
    }

    /**
     * Sets the value of the vendor property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setVendor(String value) {
        this.vendor = value;
    }

    /**
     * Gets the value of the wordsize property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getWordsize() {
        return wordsize;
    }

    /**
     * Sets the value of the wordsize property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setWordsize(String value) {
        this.wordsize = value;
    }

    /**
     * Gets the value of the annotations property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getAnnotations() {
        return annotations;
    }

    /**
     * Sets the value of the annotations property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setAnnotations(String value) {
        this.annotations = value;
    }

    /**
     * Gets the value of the linkend property.
     *
     * @return
     *     possible object is
     *     {@link Object }
     *
     */
    public Object getLinkend() {
        return linkend;
    }

    /**
     * Sets the value of the linkend property.
     *
     * @param value
     *     allowed object is
     *     {@link Object }
     *
     */
    public void setLinkend(Object value) {
        this.linkend = value;
    }

    /**
     * Gets the value of the href property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getHref() {
        return href;
    }

    /**
     * Sets the value of the href property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setHref(String value) {
        this.href = value;
    }

    /**
     * Gets the value of the xlinkType property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getXlinkType() {
        return xlinkType;
    }

    /**
     * Sets the value of the xlinkType property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setXlinkType(String value) {
        this.xlinkType = value;
    }

    /**
     * Gets the value of the xlinkRole property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getXlinkRole() {
        return xlinkRole;
    }

    /**
     * Sets the value of the xlinkRole property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setXlinkRole(String value) {
        this.xlinkRole = value;
    }

    /**
     * Gets the value of the arcrole property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getArcrole() {
        return arcrole;
    }

    /**
     * Sets the value of the arcrole property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setArcrole(String value) {
        this.arcrole = value;
    }

    /**
     * Gets the value of the xlinkTitle property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getXlinkTitle() {
        return xlinkTitle;
    }

    /**
     * Sets the value of the xlinkTitle property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setXlinkTitle(String value) {
        this.xlinkTitle = value;
    }

    /**
     * Gets the value of the show property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getShow() {
        return show;
    }

    /**
     * Sets the value of the show property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setShow(String value) {
        this.show = value;
    }

    /**
     * Gets the value of the actuate property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getActuate() {
        return actuate;
    }

    /**
     * Sets the value of the actuate property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setActuate(String value) {
        this.actuate = value;
    }

}


text:
namespace Atomiv.Infrastructure.Selenium.SystemTest.Fixtures.Pages.Interfaces
{
    public interface ILoginPage
    {
        void InputUserName(string userName);

        void InputPassword(string password);

        void ClickLogin();

        bool HasErrorMessage();

        string GetErrorMessage();
    }
}


text:
package org.iplantcollaborative;

import org.apache.commons.collections4.map.LRUMap;

/**
 *
 * @author iychoi
 */
public class UUIDCache {

    private static final int DEFAULT_CACHE_SIZE = 10000;

    private LRUMap<String, String> cache = new LRUMap<String, String>(DEFAULT_CACHE_SIZE);

    public UUIDCache() {
    }

    public void cache(String uuid, String path) {
        this.cache.put(uuid, path);
    }

    public String get(String uuid) {
        return this.cache.get(uuid);
    }

    public void clearCache() {
        this.cache.clear();
    }
}


text:
package org.dashbuilder.displayer.client;

import org.dashbuilder.displayer.DisplayerSettings;

/**
 * Helper methods for dealing with Displayer instances.
 */
public class DisplayerHelper {

    /**
     * Get a Displayer instance for displaying the specified data set with the given display configuration.
     *
     * @param displayerSettings The given display configuration.
     */
    public static Displayer lookupDisplayer(DisplayerSettings displayerSettings ) {
        return DisplayerLocator.get().lookupDisplayer(displayerSettings);
    }

    /**
     * Issues a draw request for the given Displayer instances.
     */
    public static void draw(Displayer... displayers ) {
        DisplayerCoordinator coordinator = new DisplayerCoordinator();
        for (Displayer displayer : displayers ) {
            coordinator.addDisplayer( displayer );
        }
        coordinator.drawAll();
    }

    /**
     * Issues a redraw request for the given Displayer instances.
     */
    public static void redraw(Displayer... displayers ) {
        DisplayerCoordinator coordinator = new DisplayerCoordinator();
        for (Displayer displayer : displayers ) {
            coordinator.addDisplayer( displayer );
        }
        coordinator.redrawAll();
    }
}


text:
package hr.lowcostflights.service;

import java.time.LocalDate;
import java.util.List;

import hr.lowcostflights.domain.Airport;
import hr.lowcostflights.domain.Flight;

public interface SearchService {

	/**
	 * Returns list of possible flight intineraries for given input parameters.
	 *

	 * Method relies on external Amadeus REST API for retrieval of possible
	 * flight itineraries. Once retrieved from Amadeus, results are stored in
	 * local database so they can be fetched for subsequent searches without
	 * contacting Amadeus API.
	 *

	 * Search logic workflow is as follows:
	 *

	 *
1. Try to find if there already was a search with given parameters,
	 * if such search exists just return already stored flight itineraries from
	 * local database.
	 *
2. If this is a brand new search, retrieve flight itineraries from
	 * Amadeus API.
	 *
3. Save each unique flight itinerary from Amadeus to local database.
	 *
4. Assign retrieved (and saved) flight itinerararies to search instance.
	 *
5. Return list of stored flight itineraries.
	 *
	 * @param origin Originating airport
	 * @param destination Destination airport
	 * @param departureDate Departure date
	 * @param returnDate Return date (optional)
	 * @param adults Number of adult passengers (optional)
	 * @param children Number of children passengers (optional)
	 * @param infants Number of infant passengers (optional)
	 * @param currency Flight total price currency (optional)
	 * @return List of Flight instances
	 */
	public List<Flight> findFlights(Airport origin, Airport destination, LocalDate departureDate, LocalDate returnDate,
			Integer adults, Integer children, Integer infants, String currency);

}


text:
import PopupWindow from 'popup-window';

// Ensure we can use and instantiate PopupWindow class.
const popup1 = new PopupWindow();
// PopupWindow instance should have open() method.
popup1.open();
// PopupWindow instance should have close() method.
popup1.close();

const popup2 = new PopupWindow();
// Test common use-case with passing opened, blocked and closed callbacks.
popup2.opened(win => {
  // The callback argument should be an instance of PopupWindow.
  console.log(win.url);
  console.log(win.name);
}).blocked(win => {
  // The callback argument should be an instance of PopupWindow.
  console.log(win.url);
  console.log(win.name);
}).closed(win => {
  // The callback argument should be an instance of PopupWindow.
  console.log(win.url);
  console.log(win.name);
});

// PopupWindow class should accept URL contructor argument.
const popup3 = new PopupWindow('http://example.com');

// PopupWindow class should accept both URL and configuration constructor arguments.
const popup4 = new PopupWindow(
  'http://example.com',
  // Test configuration interface.
  {
    width: 350,
    height: 250,
    resizable: true,
    menubar: false
  }
);


text:
module NATSD #:nodoc: all

  module Connection #:nodoc: all

    attr_accessor :in_msgs, :out_msgs, :in_bytes, :out_bytes
    attr_reader :cid, :closing, :last_activity, :writev_size, :subscriptions
    alias :closing? :closing

    def flush_data
      return if @writev.nil? || closing?
      send_data(@writev.join)
      @writev, @writev_size = nil, 0
    end

    def queue_data(data)
      EM.next_tick { flush_data } if @writev.nil?
      (@writev ||= []) << data
      @writev_size += data.bytesize
      flush_data if @writev_size > MAX_WRITEV_SIZE
    end

    def client_info
      cur_peername = get_peername
      @client_info ||= (cur_peername.nil? ? 'N/A' : Socket.unpack_sockaddr_in(cur_peername))
    end

    def info
      {
        :cid => cid,
        :ip => client_info[1],
        :port => client_info[0],
        :subscriptions => @subscriptions.size,
        :pending_size => get_outbound_data_size,
        :in_msgs => @in_msgs,
        :out_msgs => @out_msgs,
        :in_bytes => @in_bytes,
        :out_bytes => @out_bytes
      }
    end

    def max_connections_exceeded?
      return false unless (Server.num_connections > Server.max_connections)
      error_close MAX_CONNS_EXCEEDED
      debug "Maximum #{Server.max_connections} connections exceeded, c:#{cid} will be closed"
      true
    end

    def post_init
      @cid = Server.cid
      @subscriptions = {}
      @verbose = @pedantic = true # suppressed by most clients, but allows friendly telnet
      @in_msgs = @out_msgs = @in_bytes = @out_bytes = 0
      @writev_size = 0
      @parse_state = AWAITING_CONTROL_LINE
      send_info
      debug "#{type} connection created", client_info, cid
      if Server.ssl_required?
        debug "Starting TLS/SSL", client_info, cid
        flush_data
        @ssl_pending = EM.add_timer(NATSD::Server.ssl_timeout) { connect_ssl_timeout }
        start_tls(:verify_peer => true) if Server.ssl_required?
      end
      @auth_pending = EM.add_timer(NATSD::Server.auth_timeout) { connect_auth_timeout } if Server.auth_required?
      @ping_timer = EM.add_periodic_timer(NATSD::Server.ping_interval) { send_ping }
      @pings_outstanding = 0
      inc_connections
      return if max_connections_exceeded?
    end

    def send_ping
      return if @closing
      if @pings_outstanding > NATSD::Server.ping_max
        error_close UNRESPONSIVE
        return
      end
      queue_data(PING_RESPONSE)
      flush_data
      @pings_outstanding += 1
    end

    def connect_auth_timeout
      error_close AUTH_REQUIRED
      debug "#{type} connection timeout due to lack of auth credentials", cid
    end

    def connect_ssl_timeout
      error_close SSL_REQUIRED
      debug "#{type} connection timeout due to lack of TLS/SSL negotiations", cid
    end

    def receive_data(data)
      @buf = @buf ? @buf << data : data

      while (@buf && !@closing)
        case @parse_state
        when AWAITING_CONTROL_LINE
          case @buf
          when PUB_OP
            ctrace('PUB OP', strip_op($&)) if NATSD::Server.trace_flag?
            return connect_auth_timeout if @auth_pending
            @buf = $'
            @parse_state = AWAITING_MSG_PAYLOAD
            @msg_sub, @msg_reply, @msg_size = $1, $3, $4.to_i
            if (@msg_size > NATSD::Server.max_payload)
              debug_print_msg_too_big(@msg_size)
              error_close PAYLOAD_TOO_BIG
            end
            queue_data(INVALID_SUBJECT) if (@pedantic && !(@msg_sub =~ SUB_NO_WC))
          when SUB_OP
            ctrace('SUB OP', strip_op($&)) if NATSD::Server.trace_flag?
            return connect_auth_timeout if @auth_pending
            @buf = $'
            sub, qgroup, sid = $1, $3, $4
            return queue_data(INVALID_SUBJECT) if !($1 =~ SUB)
            return queue_data(INVALID_SID_TAKEN) if @subscriptions[sid]
            sub = Subscriber.new(self, sub, sid, qgroup, 0)
            @subscriptions[sid] = sub
            Server.subscribe(sub)
            queue_data(OK) if @verbose
          when UNSUB_OP
            ctrace('UNSUB OP', strip_op($&)) if NATSD::Server.trace_flag?
            return connect_auth_timeout if @auth_pending
            @buf = $'
            sid, sub = $1, @subscriptions[$1]
            if sub
              # If we have set max_responses, we will unsubscribe once we have received
              # the appropriate amount of responses.
              sub.max_responses = ($2 && $3) ? $3.to_i : nil
              delete_subscriber(sub) unless (sub.max_responses && (sub.num_responses < sub.max_responses))
              queue_data(OK) if @verbose
            else
              queue_data(INVALID_SID_NOEXIST) if @pedantic
            end
          when PING
            ctrace('PING OP') if NATSD::Server.trace_flag?
            @buf = $'
            queue_data(PONG_RESPONSE)
            flush_data
          when PONG
            ctrace('PONG OP') if NATSD::Server.trace_flag?
            @buf = $'
            @pings_outstanding -= 1
          when CONNECT
            ctrace('CONNECT OP', strip_op($&)) if NATSD::Server.trace_flag?
            @buf = $'
            begin
              config = JSON.parse($1)
              process_connect_config(config)
            rescue => e
              queue_data(INVALID_CONFIG)
              log_error
            end
          when INFO_REQ
            ctrace('INFO_REQUEST OP') if NATSD::Server.trace_flag?
            return connect_auth_timeout if @auth_pending
            @buf = $'
            send_info
          when UNKNOWN
            ctrace('Unknown Op', strip_op($&)) if NATSD::Server.trace_flag?
            return connect_auth_timeout if @auth_pending
            @buf = $'
            queue_data(UNKNOWN_OP)
          when CTRL_C # ctrl+c or ctrl+d for telnet friendly
            ctrace('CTRL-C encountered', strip_op($&)) if NATSD::Server.trace_flag?
            return close_connection
          when CTRL_D # ctrl+d for telnet friendly
            ctrace('CTRL-D encountered', strip_op($&)) if NATSD::Server.trace_flag?
            return close_connection
          else
            # If we are here we do not have a complete line yet that we understand.
            # If too big, cut the connection off.
            if @buf.bytesize > NATSD::Server.max_control_line
              debug_print_controlline_too_big(@buf.bytesize)
              close_connection
            end
            return
          end
          @buf = nil if (@buf && @buf.empty?)

        when AWAITING_MSG_PAYLOAD
          return unless (@buf.bytesize >= (@msg_size + CR_LF_SIZE))
          msg = @buf.slice(0, @msg_size)
          ctrace('Processing msg', @msg_sub, @msg_reply, msg) if NATSD::Server.trace_flag?
          queue_data(OK) if @verbose
          Server.route_to_subscribers(@msg_sub, @msg_reply, msg)
          @in_msgs += 1
          @in_bytes += @msg_size
          @buf = @buf.slice((@msg_size + CR_LF_SIZE), @buf.bytesize)
          @msg_sub = @msg_size = @reply = nil
          @parse_state = AWAITING_CONTROL_LINE
          @buf = nil if (@buf && @buf.empty?)
        end
      end
    end

    def send_info
      queue_data("INFO #{Server.info_string}#{CR_LF}")
    end

    # Placeholder
    def process_info(info)
    end

    def auth_ok?(user, pass)
      Server.auth_ok?(user, pass)
    end

    def process_connect_config(config)
      @verbose  = config['verbose'] unless config['verbose'].nil?
      @pedantic = config['pedantic'] unless config['pedantic'].nil?

      return queue_data(OK) unless Server.auth_required?

      EM.cancel_timer(@auth_pending)
      if auth_ok?(config['user'], config['pass'])
        queue_data(OK) if @verbose
        @auth_pending = nil
      else
        error_close AUTH_FAILED
        debug "Authorization failed for #{type.downcase} connection", cid
      end
    end

    def delete_subscriber(sub)
      ctrace('DELSUB OP', sub.subject, sub.qgroup, sub.sid) if NATSD::Server.trace_flag?
      Server.unsubscribe(sub, is_route?)
      @subscriptions.delete(sub.sid)
    end

    def error_close(msg)
      queue_data(msg)
      flush_data
      EM.next_tick { close_connection_after_writing }
      @closing = true
    end

    def debug_print_controlline_too_big(line_size)
      sizes = "#{pretty_size(line_size)} vs #{pretty_size(NATSD::Server.max_control_line)} max"
      debug "Control line size exceeded (#{sizes}), closing connection.."
    end

    def debug_print_msg_too_big(msg_size)
      sizes = "#{pretty_size(msg_size)} vs #{pretty_size(NATSD::Server.max_payload)} max"
      debug "Message payload size exceeded (#{sizes}), closing connection"
    end

    def inc_connections
      Server.num_connections += 1
      Server.connections[cid] = self
    end

    def dec_connections
      Server.num_connections -= 1
      Server.connections.delete(cid)
    end

    def process_unbind
      dec_connections
      EM.cancel_timer(@ssl_pending) if @ssl_pending
      @ssl_pending = nil
      EM.cancel_timer(@auth_pending) if @auth_pending
      @auth_pending = nil
      EM.cancel_timer(@ping_timer) if @ping_timer
      @ping_timer = nil
      @subscriptions.each_value { |sub| Server.unsubscribe(sub) }
      @closing = true
    end

    def unbind
      debug "Client connection closed", client_info, cid
      process_unbind
    end

    def ssl_handshake_completed
      EM.cancel_timer(@ssl_pending)
      @ssl_pending = nil
      cert = get_peer_cert
      debug "#{type} Certificate:", cert ? cert : 'N/A', cid
    end

    # FIXME! Cert accepted by default
    def ssl_verify_peer(cert)
      true
    end

    def ctrace(*args)
      trace(args, "c: #{cid}")
    end

    def strip_op(op='')
      op.dup.sub(CR_LF, EMPTY)
    end

    def is_route?
      false
    end

    def type
      'Client'
    end

  end

end


text:
package org.apache.commons.math3.transform;

import java.io.Serializable;
import java.lang.reflect.Array;

import org.apache.commons.math3.analysis.FunctionUtils;
import org.apache.commons.math3.analysis.UnivariateFunction;
import org.apache.commons.math3.complex.Complex;
import org.apache.commons.math3.exception.DimensionMismatchException;
import org.apache.commons.math3.exception.MathIllegalArgumentException;
import org.apache.commons.math3.exception.MathIllegalStateException;
import org.apache.commons.math3.exception.util.LocalizedFormats;
import org.apache.commons.math3.util.ArithmeticUtils;
import org.apache.commons.math3.util.FastMath;
import org.apache.commons.math3.util.MathArrays;

/**
 * Implements the Fast Fourier Transform for transformation of one-dimensional
 * real or complex data sets. For reference, see Applied Numerical Linear
 * Algebra, ISBN 0898713897, chapter 6.
 *

 * There are several variants of the discrete Fourier transform, with various
 * normalization conventions, which are specified by the parameter
 * {@link DftNormalization}.
 *

 * The current implementation of the discrete Fourier transform as a fast
 * Fourier transform requires the length of the data set to be a power of 2.
 * This greatly simplifies and speeds up the code. Users can pad the data with
 * zeros to meet this requirement. There are other flavors of FFT, for
 * reference, see S. Winograd,
 * On computing the discrete Fourier transform, Mathematics of
 * Computation, 32 (1978), 175 - 199.
 *
 * @see DftNormalization
 * @since 1.2
 */
public class FastFourierTransformer implements Serializable {

    /** Serializable version identifier. */
    static final long serialVersionUID = 20120210L;

    /**
     * {@code W_SUB_N_R[i]} is the real part of
     * {@code exp(- 2 * i * pi / n)}:
     * {@code W_SUB_N_R[i] = cos(2 * pi/ n)}, where {@code n = 2^i}.
     */
    private static final double[] W_SUB_N_R =
            {  0x1.0p0, -0x1.0p0, 0x1.1a62633145c07p-54, 0x1.6a09e667f3bcdp-1
            , 0x1.d906bcf328d46p-1, 0x1.f6297cff75cbp-1, 0x1.fd88da3d12526p-1, 0x1.ff621e3796d7ep-1
            , 0x1.ffd886084cd0dp-1, 0x1.fff62169b92dbp-1, 0x1.fffd8858e8a92p-1, 0x1.ffff621621d02p-1
            , 0x1.ffffd88586ee6p-1, 0x1.fffff62161a34p-1, 0x1.fffffd8858675p-1, 0x1.ffffff621619cp-1
            , 0x1.ffffffd885867p-1, 0x1.fffffff62161ap-1, 0x1.fffffffd88586p-1, 0x1.ffffffff62162p-1
            , 0x1.ffffffffd8858p-1, 0x1.fffffffff6216p-1, 0x1.fffffffffd886p-1, 0x1.ffffffffff621p-1
            , 0x1.ffffffffffd88p-1, 0x1.fffffffffff62p-1, 0x1.fffffffffffd9p-1, 0x1.ffffffffffff6p-1
            , 0x1.ffffffffffffep-1, 0x1.fffffffffffffp-1, 0x1.0p0, 0x1.0p0
            , 0x1.0p0, 0x1.0p0, 0x1.0p0, 0x1.0p0
            , 0x1.0p0, 0x1.0p0, 0x1.0p0, 0x1.0p0
            , 0x1.0p0, 0x1.0p0, 0x1.0p0, 0x1.0p0
            , 0x1.0p0, 0x1.0p0, 0x1.0p0, 0x1.0p0
            , 0x1.0p0, 0x1.0p0, 0x1.0p0, 0x1.0p0
            , 0x1.0p0, 0x1.0p0, 0x1.0p0, 0x1.0p0
            , 0x1.0p0, 0x1.0p0, 0x1.0p0, 0x1.0p0
            , 0x1.0p0, 0x1.0p0, 0x1.0p0 };

    /**
     * {@code W_SUB_N_I[i]} is the imaginary part of
     * {@code exp(- 2 * i * pi / n)}:
     * {@code W_SUB_N_I[i] = -sin(2 * pi/ n)}, where {@code n = 2^i}.
     */
    private static final double[] W_SUB_N_I =
            {  0x1.1a62633145c07p-52, -0x1.1a62633145c07p-53, -0x1.0p0, -0x1.6a09e667f3bccp-1
            , -0x1.87de2a6aea963p-2, -0x1.8f8b83c69a60ap-3, -0x1.917a6bc29b42cp-4, -0x1.91f65f10dd814p-5
            , -0x1.92155f7a3667ep-6, -0x1.921d1fcdec784p-7, -0x1.921f0fe670071p-8, -0x1.921f8becca4bap-9
            , -0x1.921faaee6472dp-10, -0x1.921fb2aecb36p-11, -0x1.921fb49ee4ea6p-12, -0x1.921fb51aeb57bp-13
            , -0x1.921fb539ecf31p-14, -0x1.921fb541ad59ep-15, -0x1.921fb5439d73ap-16, -0x1.921fb544197ap-17
            , -0x1.921fb544387bap-18, -0x1.921fb544403c1p-19, -0x1.921fb544422c2p-20, -0x1.921fb54442a83p-21
            , -0x1.921fb54442c73p-22, -0x1.921fb54442cefp-23, -0x1.921fb54442d0ep-24, -0x1.921fb54442d15p-25
            , -0x1.921fb54442d17p-26, -0x1.921fb54442d18p-27, -0x1.921fb54442d18p-28, -0x1.921fb54442d18p-29
            , -0x1.921fb54442d18p-30, -0x1.921fb54442d18p-31, -0x1.921fb54442d18p-32, -0x1.921fb54442d18p-33
            , -0x1.921fb54442d18p-34, -0x1.921fb54442d18p-35, -0x1.921fb54442d18p-36, -0x1.921fb54442d18p-37
            , -0x1.921fb54442d18p-38, -0x1.921fb54442d18p-39, -0x1.921fb54442d18p-40, -0x1.921fb54442d18p-41
            , -0x1.921fb54442d18p-42, -0x1.921fb54442d18p-43, -0x1.921fb54442d18p-44, -0x1.921fb54442d18p-45
            , -0x1.921fb54442d18p-46, -0x1.921fb54442d18p-47, -0x1.921fb54442d18p-48, -0x1.921fb54442d18p-49
            , -0x1.921fb54442d18p-50, -0x1.921fb54442d18p-51, -0x1.921fb54442d18p-52, -0x1.921fb54442d18p-53
            , -0x1.921fb54442d18p-54, -0x1.921fb54442d18p-55, -0x1.921fb54442d18p-56, -0x1.921fb54442d18p-57
            , -0x1.921fb54442d18p-58, -0x1.921fb54442d18p-59, -0x1.921fb54442d18p-60 };

    /** The type of DFT to be performed. */
    private final DftNormalization normalization;

    /**
     * Creates a new instance of this class, with various normalization
     * conventions.
     *
     * @param normalization the type of normalization to be applied to the
     * transformed data
     */
    public FastFourierTransformer(final DftNormalization normalization) {
        this.normalization = normalization;
    }

    /**
     * Performs identical index bit reversal shuffles on two arrays of identical
     * size. Each element in the array is swapped with another element based on
     * the bit-reversal of the index. For example, in an array with length 16,
     * item at binary index 0011 (decimal 3) would be swapped with the item at
     * binary index 1100 (decimal 12).
     *
     * @param a the first array to be shuffled
     * @param b the second array to be shuffled
     */
    private static void bitReversalShuffle2(double[] a, double[] b) {
        final int n = a.length;
        assert b.length == n;
        final int halfOfN = n >> 1;

        int j = 0;
        for (int i = 0; i < n; i++) {
            if (i < j) {
                // swap indices i & j
                double temp = a[i];
                a[i] = a[j];
                a[j] = temp;

                temp = b[i];
                b[i] = b[j];
                b[j] = temp;
            }

            int k = halfOfN;
            while (k <= j && k > 0) {
                j -= k;
                k >>= 1;
            }
            j += k;
        }
    }

    /**
     * Applies the proper normalization to the specified transformed data.
     *
     * @param dataRI the unscaled transformed data
     * @param normalization the normalization to be applied
     * @param type the type of transform (forward, inverse) which resulted in the specified data
     */
    private static void normalizeTransformedData(final double[][] dataRI,
        final DftNormalization normalization, final TransformType type) {

        final double[] dataR = dataRI[0];
        final double[] dataI = dataRI[1];
        final int n = dataR.length;
        assert dataI.length == n;

        switch (normalization) {
            case STANDARD:
                if (type == TransformType.INVERSE) {
                    final double scaleFactor = 1.0 / ((double) n);
                    for (int i = 0; i < n; i++) {
                        dataR[i] *= scaleFactor;
                        dataI[i] *= scaleFactor;
                    }
                }
                break;
            case UNITARY:
                final double scaleFactor = 1.0 / FastMath.sqrt(n);
                for (int i = 0; i < n; i++) {
                    dataR[i] *= scaleFactor;
                    dataI[i] *= scaleFactor;
                }
                break;
            default:
                /*
                 * This should never occur in normal conditions. However this
                 * clause has been added as a safeguard if other types of
                 * normalizations are ever implemented, and the corresponding
                 * test is forgotten in the present switch.
                 */
                throw new MathIllegalStateException();
        }
    }

    /**
     * Computes the standard transform of the specified complex data. The
     * computation is done in place. The input data is laid out as follows
     *

     *
{@code dataRI[0][i]} is the real part of the {@code i}-th data point,

     *
{@code dataRI[1][i]} is the imaginary part of the {@code i}-th data point.

     *

     *
     * @param dataRI the two dimensional array of real and imaginary parts of the data
     * @param normalization the normalization to be applied to the transformed data
     * @param type the type of transform (forward, inverse) to be performed
     * @throws DimensionMismatchException if the number of rows of the specified
     *   array is not two, or the array is not rectangular
     * @throws MathIllegalArgumentException if the number of data points is not
     *   a power of two
     */
    public static void transformInPlace(final double[][] dataRI,
        final DftNormalization normalization, final TransformType type) {

        if (dataRI.length != 2) {
            throw new DimensionMismatchException(dataRI.length, 2);
        }
        final double[] dataR = dataRI[0];
        final double[] dataI = dataRI[1];
        if (dataR.length != dataI.length) {
            throw new DimensionMismatchException(dataI.length, dataR.length);
        }

        final int n = dataR.length;
        if (!ArithmeticUtils.isPowerOfTwo(n)) {
            throw new MathIllegalArgumentException(
                LocalizedFormats.NOT_POWER_OF_TWO_CONSIDER_PADDING,
                Integer.valueOf(n));
        }

        if (n == 1) {
            return;
        } else if (n == 2) {
            final double srcR0 = dataR[0];
            final double srcI0 = dataI[0];
            final double srcR1 = dataR[1];
            final double srcI1 = dataI[1];

            // X_0 = x_0 + x_1
            dataR[0] = srcR0 + srcR1;
            dataI[0] = srcI0 + srcI1;
            // X_1 = x_0 - x_1
            dataR[1] = srcR0 - srcR1;
            dataI[1] = srcI0 - srcI1;

            normalizeTransformedData(dataRI, normalization, type);
            return;
        }

        bitReversalShuffle2(dataR, dataI);

        // Do 4-term DFT.
        if (type == TransformType.INVERSE) {
            for (int i0 = 0; i0 < n; i0 += 4) {
                final int i1 = i0 + 1;
                final int i2 = i0 + 2;
                final int i3 = i0 + 3;

                final double srcR0 = dataR[i0];
                final double srcI0 = dataI[i0];
                final double srcR1 = dataR[i2];
                final double srcI1 = dataI[i2];
                final double srcR2 = dataR[i1];
                final double srcI2 = dataI[i1];
                final double srcR3 = dataR[i3];
                final double srcI3 = dataI[i3];

                // 4-term DFT
                // X_0 = x_0 + x_1 + x_2 + x_3
                dataR[i0] = srcR0 + srcR1 + srcR2 + srcR3;
                dataI[i0] = srcI0 + srcI1 + srcI2 + srcI3;
                // X_1 = x_0 - x_2 + j * (x_3 - x_1)
                dataR[i1] = srcR0 - srcR2 + (srcI3 - srcI1);
                dataI[i1] = srcI0 - srcI2 + (srcR1 - srcR3);
                // X_2 = x_0 - x_1 + x_2 - x_3
                dataR[i2] = srcR0 - srcR1 + srcR2 - srcR3;
                dataI[i2] = srcI0 - srcI1 + srcI2 - srcI3;
                // X_3 = x_0 - x_2 + j * (x_1 - x_3)
                dataR[i3] = srcR0 - srcR2 + (srcI1 - srcI3);
                dataI[i3] = srcI0 - srcI2 + (srcR3 - srcR1);
            }
        } else {
            for (int i0 = 0; i0 < n; i0 += 4) {
                final int i1 = i0 + 1;
                final int i2 = i0 + 2;
                final int i3 = i0 + 3;

                final double srcR0 = dataR[i0];
                final double srcI0 = dataI[i0];
                final double srcR1 = dataR[i2];
                final double srcI1 = dataI[i2];
                final double srcR2 = dataR[i1];
                final double srcI2 = dataI[i1];
                final double srcR3 = dataR[i3];
                final double srcI3 = dataI[i3];

                // 4-term DFT
                // X_0 = x_0 + x_1 + x_2 + x_3
                dataR[i0] = srcR0 + srcR1 + srcR2 + srcR3;
                dataI[i0] = srcI0 + srcI1 + srcI2 + srcI3;
                // X_1 = x_0 - x_2 + j * (x_3 - x_1)
                dataR[i1] = srcR0 - srcR2 + (srcI1 - srcI3);
                dataI[i1] = srcI0 - srcI2 + (srcR3 - srcR1);
                // X_2 = x_0 - x_1 + x_2 - x_3
                dataR[i2] = srcR0 - srcR1 + srcR2 - srcR3;
                dataI[i2] = srcI0 - srcI1 + srcI2 - srcI3;
                // X_3 = x_0 - x_2 + j * (x_1 - x_3)
                dataR[i3] = srcR0 - srcR2 + (srcI3 - srcI1);
                dataI[i3] = srcI0 - srcI2 + (srcR1 - srcR3);
            }
        }

        int lastN0 = 4;
        int lastLogN0 = 2;
        while (lastN0 < n) {
            int n0 = lastN0 << 1;
            int logN0 = lastLogN0 + 1;
            double wSubN0R = W_SUB_N_R[logN0];
            double wSubN0I = W_SUB_N_I[logN0];
            if (type == TransformType.INVERSE) {
                wSubN0I = -wSubN0I;
            }

            // Combine even/odd transforms of size lastN0 into a transform of size N0 (lastN0 * 2).
            for (int destEvenStartIndex = 0; destEvenStartIndex < n; destEvenStartIndex += n0) {
                int destOddStartIndex = destEvenStartIndex + lastN0;

                double wSubN0ToRR = 1;
                double wSubN0ToRI = 0;

                for (int r = 0; r < lastN0; r++) {
                    double grR = dataR[destEvenStartIndex + r];
                    double grI = dataI[destEvenStartIndex + r];
                    double hrR = dataR[destOddStartIndex + r];
                    double hrI = dataI[destOddStartIndex + r];

                    // dest[destEvenStartIndex + r] = Gr + WsubN0ToR * Hr
                    dataR[destEvenStartIndex + r] = grR + wSubN0ToRR * hrR - wSubN0ToRI * hrI;
                    dataI[destEvenStartIndex + r] = grI + wSubN0ToRR * hrI + wSubN0ToRI * hrR;
                    // dest[destOddStartIndex + r] = Gr - WsubN0ToR * Hr
                    dataR[destOddStartIndex + r] = grR - (wSubN0ToRR * hrR - wSubN0ToRI * hrI);
                    dataI[destOddStartIndex + r] = grI - (wSubN0ToRR * hrI + wSubN0ToRI * hrR);

                    // WsubN0ToR *= WsubN0R
                    double nextWsubN0ToRR = wSubN0ToRR * wSubN0R - wSubN0ToRI * wSubN0I;
                    double nextWsubN0ToRI = wSubN0ToRR * wSubN0I + wSubN0ToRI * wSubN0R;
                    wSubN0ToRR = nextWsubN0ToRR;
                    wSubN0ToRI = nextWsubN0ToRI;
                }
            }

            lastN0 = n0;
            lastLogN0 = logN0;
        }

        normalizeTransformedData(dataRI, normalization, type);
    }

    /**
     * Returns the (forward, inverse) transform of the specified real data set.
     *
     * @param f the real data array to be transformed
     * @param type the type of transform (forward, inverse) to be performed
     * @return the complex transformed array
     * @throws MathIllegalArgumentException if the length of the data array is not a power of two
     */
    public Complex[] transform(final double[] f, final TransformType type) {
        final double[][] dataRI = new double[][] {
            MathArrays.copyOf(f, f.length), new double[f.length]
        };

        transformInPlace(dataRI, normalization, type);

        return TransformUtils.createComplexArray(dataRI);
    }

    /**
     * Returns the (forward, inverse) transform of the specified real function,
     * sampled on the specified interval.
     *
     * @param f the function to be sampled and transformed
     * @param min the (inclusive) lower bound for the interval
     * @param max the (exclusive) upper bound for the interval
     * @param n the number of sample points
     * @param type the type of transform (forward, inverse) to be performed
     * @return the complex transformed array
     * @throws org.apache.commons.math3.exception.NumberIsTooLargeException
     *   if the lower bound is greater than, or equal to the upper bound
     * @throws org.apache.commons.math3.exception.NotStrictlyPositiveException
     *   if the number of sample points {@code n} is negative
     * @throws MathIllegalArgumentException if the number of sample points
     *   {@code n} is not a power of two
     */
    public Complex[] transform(final UnivariateFunction f,
                               final double min, final double max, final int n,
                               final TransformType type) {

        final double[] data = FunctionUtils.sample(f, min, max, n);
        return transform(data, type);
    }

    /**
     * Returns the (forward, inverse) transform of the specified complex data set.
     *
     * @param f the complex data array to be transformed
     * @param type the type of transform (forward, inverse) to be performed
     * @return the complex transformed array
     * @throws MathIllegalArgumentException if the length of the data array is not a power of two
     */
    public Complex[] transform(final Complex[] f, final TransformType type) {
        final double[][] dataRI = TransformUtils.createRealImaginaryArray(f);

        transformInPlace(dataRI, normalization, type);

        return TransformUtils.createComplexArray(dataRI);
    }

    /**
     * Performs a multi-dimensional Fourier transform on a given array. Use
     * {@link #transform(Complex[], TransformType)} in a row-column
     * implementation in any number of dimensions with
     * O(N×log(N)) complexity with
     * N = n1 × n2 ×n3 × ...
     * × nd, where nk is the number of elements in
     * dimension k, and d is the total number of dimensions.
     *
     * @param mdca Multi-Dimensional Complex Array, i.e. {@code Complex[][][][]}
     * @param type the type of transform (forward, inverse) to be performed
     * @return transform of {@code mdca} as a Multi-Dimensional Complex Array, i.e. {@code Complex[][][][]}
     * @throws IllegalArgumentException if any dimension is not a power of two
     * @deprecated see MATH-736
     */
    @Deprecated
    public Object mdfft(Object mdca, TransformType type) {
        MultiDimensionalComplexMatrix mdcm = (MultiDimensionalComplexMatrix)
                new MultiDimensionalComplexMatrix(mdca).clone();
        int[] dimensionSize = mdcm.getDimensionSizes();
        //cycle through each dimension
        for (int i = 0; i < dimensionSize.length; i++) {
            mdfft(mdcm, type, i, new int[0]);
        }
        return mdcm.getArray();
    }

    /**
     * Performs one dimension of a multi-dimensional Fourier transform.
     *
     * @param mdcm input matrix
     * @param type the type of transform (forward, inverse) to be performed
     * @param d index of the dimension to process
     * @param subVector recursion subvector
     * @throws IllegalArgumentException if any dimension is not a power of two
     * @deprecated see MATH-736
     */
    @Deprecated
    private void mdfft(MultiDimensionalComplexMatrix mdcm,
            TransformType type, int d, int[] subVector) {

        int[] dimensionSize = mdcm.getDimensionSizes();
        //if done
        if (subVector.length == dimensionSize.length) {
            Complex[] temp = new Complex[dimensionSize[d]];
            for (int i = 0; i < dimensionSize[d]; i++) {
                //fft along dimension d
                subVector[d] = i;
                temp[i] = mdcm.get(subVector);
            }

            temp = transform(temp, type);

            for (int i = 0; i < dimensionSize[d]; i++) {
                subVector[d] = i;
                mdcm.set(temp[i], subVector);
            }
        } else {
            int[] vector = new int[subVector.length + 1];
            System.arraycopy(subVector, 0, vector, 0, subVector.length);
            if (subVector.length == d) {
                //value is not important once the recursion is done.
                //then an fft will be applied along the dimension d.
                vector[d] = 0;
                mdfft(mdcm, type, d, vector);
            } else {
                for (int i = 0; i < dimensionSize[subVector.length]; i++) {
                    vector[subVector.length] = i;
                    //further split along the next dimension
                    mdfft(mdcm, type, d, vector);
                }
            }
        }
    }

    /**
     * Complex matrix implementation. Not designed for synchronized access may
     * eventually be replaced by jsr-83 of the java community process
     * http://jcp.org/en/jsr/detail?id=83
     * may require additional exception throws for other basic requirements.
     *
     * @deprecated see MATH-736
     */
    @Deprecated
    private static class MultiDimensionalComplexMatrix
        implements Cloneable {

        /** Size in all dimensions. */
        protected int[] dimensionSize;

        /** Storage array. */
        protected Object multiDimensionalComplexArray;

        /**
         * Simple constructor.
         *
         * @param multiDimensionalComplexArray array containing the matrix
         * elements
         */
        public MultiDimensionalComplexMatrix(
                Object multiDimensionalComplexArray) {

            this.multiDimensionalComplexArray = multiDimensionalComplexArray;

            // count dimensions
            int numOfDimensions = 0;
            for (Object lastDimension = multiDimensionalComplexArray;
                 lastDimension instanceof Object[];) {
                final Object[] array = (Object[]) lastDimension;
                numOfDimensions++;
                lastDimension = array[0];
            }

            // allocate array with exact count
            dimensionSize = new int[numOfDimensions];

            // fill array
            numOfDimensions = 0;
            for (Object lastDimension = multiDimensionalComplexArray;
                 lastDimension instanceof Object[];) {
                final Object[] array = (Object[]) lastDimension;
                dimensionSize[numOfDimensions++] = array.length;
                lastDimension = array[0];
            }

        }

        /**
         * Get a matrix element.
         *
         * @param vector indices of the element
         * @return matrix element
         * @exception DimensionMismatchException if dimensions do not match
         */
        public Complex get(int... vector)
                throws DimensionMismatchException {

            if (vector == null) {
                if (dimensionSize.length > 0) {
                    throw new DimensionMismatchException(
                            0,
                            dimensionSize.length);
                }
                return null;
            }
            if (vector.length != dimensionSize.length) {
                throw new DimensionMismatchException(
                        vector.length,
                        dimensionSize.length);
            }

            Object lastDimension = multiDimensionalComplexArray;

            for (int i = 0; i < dimensionSize.length; i++) {
                lastDimension = ((Object[]) lastDimension)[vector[i]];
            }
            return (Complex) lastDimension;
        }

        /**
         * Set a matrix element.
         *
         * @param magnitude magnitude of the element
         * @param vector indices of the element
         * @return the previous value
         * @exception DimensionMismatchException if dimensions do not match
         */
        public Complex set(Complex magnitude, int... vector)
                throws DimensionMismatchException {

            if (vector == null) {
                if (dimensionSize.length > 0) {
                    throw new DimensionMismatchException(
                            0,
                            dimensionSize.length);
                }
                return null;
            }
            if (vector.length != dimensionSize.length) {
                throw new DimensionMismatchException(
                        vector.length,
                        dimensionSize.length);
            }

            Object[] lastDimension = (Object[]) multiDimensionalComplexArray;
            for (int i = 0; i < dimensionSize.length - 1; i++) {
                lastDimension = (Object[]) lastDimension[vector[i]];
            }

            Complex lastValue = (Complex) lastDimension[vector[dimensionSize.length - 1]];
            lastDimension[vector[dimensionSize.length - 1]] = magnitude;

            return lastValue;
        }

        /**
         * Get the size in all dimensions.
         *
         * @return size in all dimensions
         */
        public int[] getDimensionSizes() {
            return dimensionSize.clone();
        }

        /**
         * Get the underlying storage array.
         *
         * @return underlying storage array
         */
        public Object getArray() {
            return multiDimensionalComplexArray;
        }

        /** {@inheritDoc} */
        @Override
        public Object clone() {
            MultiDimensionalComplexMatrix mdcm =
                    new MultiDimensionalComplexMatrix(Array.newInstance(
                    Complex.class, dimensionSize));
            clone(mdcm);
            return mdcm;
        }

        /**
         * Copy contents of current array into mdcm.
         *
         * @param mdcm array where to copy data
         */
        private void clone(MultiDimensionalComplexMatrix mdcm) {

            int[] vector = new int[dimensionSize.length];
            int size = 1;
            for (int i = 0; i < dimensionSize.length; i++) {
                size *= dimensionSize[i];
            }
            int[][] vectorList = new int[size][dimensionSize.length];
            for (int[] nextVector : vectorList) {
                System.arraycopy(vector, 0, nextVector, 0,
                                 dimensionSize.length);
                for (int i = 0; i < dimensionSize.length; i++) {
                    vector[i]++;
                    if (vector[i] < dimensionSize[i]) {
                        break;
                    } else {
                        vector[i] = 0;
                    }
                }
            }

            for (int[] nextVector : vectorList) {
                mdcm.set(get(nextVector), nextVector);
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<level-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:maxLevel="0">
        <bitmap android:src="@drawable/loop" android:gravity="center"/>
    </item>
    <item android:maxLevel="1">
        <bitmap android:src="@drawable/random" android:gravity="center"/>
    </item>
    <item android:maxLevel="2">
        <bitmap android:src="@drawable/loop_one" android:gravity="center"/>
    </item>
</level-list>


text:
package main

import (
	"errors"
	"fmt"
	"io"
	"os"
	"runtime"
	"time"

	"github.com/jessevdk/go-flags"
	"github.com/rlmcpherson/s3gof3r"
)

const (
	name    = "gof3r"
	version = "0.4.11"
)

func main() {
	// set the number of processors to use to the number of cpus for parallelization of concurrent transfers
	runtime.GOMAXPROCS(runtime.NumCPU())

	start := time.Now()

	// parse ini file
	if err := parseIni(); err != nil {
		fmt.Fprintln(os.Stderr, err)
	}

	// parser calls the Execute function for the command after parsing the command line options.
	if _, err := parser.Parse(); err != nil {

		if appOpts.WriteIni {
			writeIni() // exits
		}

		// handling for flag parse errors
		if ferr, ok := err.(*flags.Error); ok {
			if ferr.Type == flags.ErrHelp {
				parser.WriteHelp(os.Stderr)
			} else {
				var cmd string
				if parser.Active != nil {
					cmd = parser.Active.Name
				}
				fmt.Fprintf(os.Stderr, "gof3r error: %s\n", err)
				fmt.Fprintf(os.Stderr, "run 'gof3r %s --help' for usage.\n", cmd)
			}
		} else { // handle non-parse errors
			fmt.Fprintf(os.Stderr, "gof3r error: %s\n", err)
		}
		os.Exit(1)
	}
	fmt.Fprintf(os.Stderr, "duration: %v\n", time.Since(start))
}

// getAWSKeys gets the AWS Keys from environment variables or the instance-based metadata on EC2
// Environment variables are attempted first, followed by the instance-based credentials.
func getAWSKeys() (keys s3gof3r.Keys, err error) {

	keys, err = s3gof3r.EnvKeys()
	if err == nil {
		return
	}
	keys, err = s3gof3r.InstanceKeys()
	if err == nil {
		return
	}
	err = errors.New("no AWS keys found")
	return
}

func checkClose(c io.Closer, err error) {
	if c != nil {
		cerr := c.Close()
		if err == nil {
			err = cerr
		}
	}
}


text:
============================
Atlas block library
============================

-----------
Description
-----------
Infographics have become an extremely important for any project, so this library was created with an intention to simplify the creation of nice looking diagrams.

 | If a diagram is worth 1000 words, then it's worth 1000 words of our attention.
 | -- Edward Tufte

The library provides simplified isometric blocks to help visualize software architectures, network topologies, deployment strategies, etc.

--------
Features
--------
- modular design
- basic shapes and colors
- various connectors and arrows
- proper text placement

.. image:: doc/images/atlas-blocks-01.png?raw=true
   :align: center

-------
Library content
-------
The library provides all buidlding blocks in various colors in order to simplify the creationg of a distinct diagrams.

.. image:: doc/images/atlas-blocks-02.png?raw=true
   :align: center

All elements were created with `Inkscape`_

.. _Inkscape: https://inkscape.org/en/

 | Inkscape is professional quality vector graphics software which runs on Windows, Mac OS X and GNU/Linux. It is used by design professionals and hobbyists worldwide, for creating a wide variety of graphics such as illustrations, icons, logos, diagrams, maps and web graphics. Inkscape uses the W3C open standard SVG (Scalable Vector Graphics) as its native format, and is free and open-source software.

-------
License
-------
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 a

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

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


text:
<?php

/**
 * core/MY_Controller.php
 *
 * Default application controller
 *
 * ------------------------------------------------------------------------
 */
class Application extends CI_Controller {

    protected $data = array();      // parameters for view components
    protected $id;                  // identifier for our content
    protected $links = array(       // our menu navbar
        'Expertise' => '/expertise',
        'Services' => '/services',
        'Investments' => '/investments',
        'About' => '/about',
        'Contact' => '/contact'
    );

    /**
     * Constructor.
     * Establish view parameters & load common helpers
     */
    function __construct() {
        parent::__construct();
        // $this->load->helper('validate'); // load the helper file 'validate_helper.php'
        $this->data = array();
        $this->data['title'] = "Northcoast Shipping Agency"; // references the title of the entire website
    }

    /**
     * Render this page
     */
    function render($page) {
        $this->data['menubar'] = build_menu_bar($this->links, $page);
        $this->data['content'] = $this->parser->parse($this->data['pagebody'],$this->data,true);
        $this->data['data'] = &$this->data;
        $this->parser->parse('_template', $this->data);
    }
}

/* End of file MY_Controller.php */
/* Location: application/core/MY_Controller.php */


text:
import urls from '../../../../../../src/lib/urls'

const selectors = {
  collectionItem: '[data-test="item-content"]',
  reminderSettings: 'a[data-test="reminders-settings-link"]',
  ELDSettingsClose: '#estimated-land-date-toggle-toggle-button-close',
  ELDSettingsOpen: '#estimated-land-date-toggle-toggle-button-open',
  ELDEdit: '[data-test="estimated-land-date-link"]',
  NRISettingsClose: '#no-recent-interaction-toggle-toggle-button-close',
  NRISettingsOpen: '#no-recent-interaction-toggle-toggle-button-open',
  NRIEdit: '[data-test="no-recent-interaction-link"]',
}

describe('Notification settings', () => {
  context('when in estimated land date page', () => {
    before(() => {
      cy.visit(urls.reminders.estimatedLandDate())
      cy.get(selectors.collectionItem).should('be.visible')
      cy.get(selectors.reminderSettings).eq(1).should('be.visible').click()
    })

    it('should have approaching estimated land date settings expanded', () => {
      cy.get(selectors.ELDSettingsClose).should('be.visible')
    })

    it('should have no recent interaction settings collapsed', () => {
      cy.get(selectors.NRISettingsOpen).should('be.visible')
    })

    it('should have approaching estimated land date settings expanded after edit', () => {
      cy.get(selectors.ELDEdit).click()
      cy.contains('Save').click()

      cy.contains('Settings updated').should('be.visible')
      cy.get(selectors.ELDSettingsClose).should('be.visible')
    })
  })

  context('when in no recent interaction page', () => {
    beforeEach(() => {
      cy.visit(urls.reminders.noRecentInteraction())
      cy.contains('days since last interaction').should('be.visible')
      cy.get(selectors.reminderSettings).eq(1).should('be.visible').click()
    })

    it('should have no recent interaction settings expanded', () => {
      cy.get(selectors.NRISettingsClose).should('be.visible')
    })

    it('should have approaching estimated land date settings collapsed', () => {
      cy.get(selectors.ELDSettingsOpen).should('be.visible')
    })

    it('should have no recent interaction settings expanded after edit', () => {
      cy.get(selectors.NRIEdit).click()
      cy.contains('Save').click()

      cy.contains('Settings updated').should('be.visible')
      cy.get(selectors.NRISettingsClose).should('be.visible')
    })
  })
})


text:
var rete = require('./rete.js');

function RuleBase(retenetwork){

    this.__init = function() {
        this.reteNetwork = null;

        this.items = {};
    };

    this.addRule = function(rule){
        //can add metadata here
        //.addMetaDataToRule(fact);

        //add to rulebase
        this.items[rule.name] = rule;

        //send to rete - note: may immediately fire
        var terminalNode = this.reteNetwork.addRule(rule);

        return terminalNode;
    };

    this.removeRule = function(rulename){
        if (this.items[rulename]){
            this.reteNetwork.removeRule(rulename);
            //may need notifications???
            delete this.items[rulename];
        }
    };

    this.getRule = function(rulename){
        if (this.items[rulename]){
            return this.items[rulename];
        }
        return null;
    };

    this.reset = function(){
        this.items = {};
    };

    this.__init();

}
exports.RuleBase = RuleBase;


text:
<?php

if (!($loader = @include __DIR__ . '/../vendor/autoload.php')) {
        exit(<<<EOT
You need to install the project dependencies using Composer:
$ wget http://getcomposer.org/composer.phar
OR
$ curl -s https://getcomposer.org/installer | php
$ php composer.phar install --dev
$ phpunit
EOT
            );
}

$baseDir = dirname(__DIR__);

$loader = require __DIR__.'/../vendor/autoload.php';
$loader->add('GaufretteFastExtras', array($baseDir.'/src/', $baseDir.'/tests/'));
$loader->register();