text:
import time
import copy

import numpy as np

from .. import pick_channels
from ..utils import logger, verbose
from ..epochs import BaseEpochs
from ..event import _find_events

class RtEpochs(BaseEpochs):
    """Realtime Epochs.

    Can receive epochs in real time from an RtClient.

    For example, to get some epochs from a running mne_rt_server on
    'localhost', you could use::

        client = mne.realtime.RtClient('localhost')
        event_id, tmin, tmax = 1, -0.2, 0.5

        epochs = mne.realtime.RtEpochs(client, event_id, tmin, tmax)
        epochs.start()  # start the measurement and start receiving epochs

        evoked_1 = epochs.average()  # computed over all epochs
        evoked_2 = epochs[-5:].average()  # computed over the last 5 epochs

    Parameters
    ----------
    client : instance of mne.realtime.RtClient
        The realtime client.
    event_id : int | list of int
        The id of the event to consider. If int, only events with the
        ID specified by event_id are considered. Multiple event ID's
        can be specified using a list.
    tmin : float
        Start time before event.
    tmax : float
        End time after event.
    stim_channel : string or list of string
        Name of the stim channel or all the stim channels affected by
        the trigger.
    sleep_time : float
        Time in seconds to wait between checking for new epochs when epochs
        are requested and the receive queue is empty.
    baseline : None (default) or tuple of length 2
        The time interval to apply baseline correction.
        If None do not apply it. If baseline is (a, b)
        the interval is between "a (s)" and "b (s)".
        If a is None the beginning of the data is used
        and if b is None then b is set to the end of the interval.
        If baseline is equal to (None, None) all the time
        interval is used.
    picks : array-like of int | None (default)
        Indices of channels to include (if None, all channels are used).
    reject : dict | None
        Rejection parameters based on peak-to-peak amplitude.
        Valid keys are 'grad' | 'mag' | 'eeg' | 'eog' | 'ecg'.
        If reject is None then no rejection is done. Example::

            reject = dict(grad=4000e-13, # T / m (gradiometers)
                          mag=4e-12, # T (magnetometers)
                          eeg=40e-6, # V (EEG channels)
                          eog=250e-6 # V (EOG channels))

    flat : dict | None
        Rejection parameters based on flatness of signal.
        Valid keys are 'grad' | 'mag' | 'eeg' | 'eog' | 'ecg', and values
        are floats that set the minimum acceptable peak-to-peak amplitude.
        If flat is None then no rejection is done.
    proj : bool, optional
        Apply SSP projection vectors
    decim : int
        Factor by which to downsample the data from the raw file upon import.
        Warning: This simply selects every nth sample, data is not filtered
        here. If data is not properly filtered, aliasing artifacts may occur.
    reject_tmin : scalar | None
        Start of the time window used to reject epochs (with the default None,
        the window will start with tmin).
    reject_tmax : scalar | None
        End of the time window used to reject epochs (with the default None,
        the window will end with tmax).
    detrend : int | None
        If 0 or 1, the data channels (MEG and EEG) will be detrended when
        loaded. 0 is a constant (DC) detrend, 1 is a linear detrend. None
        is no detrending. Note that detrending is performed before baseline
        correction. If no DC offset is preferred (zeroth order detrending),
        either turn off baseline correction, as this may introduce a DC
        shift, or set baseline correction to use the entire time interval
        (will yield equivalent results but be slower).
    isi_max : float
        The maximum time in seconds between epochs. If no epoch
        arrives in the next isi_max seconds the RtEpochs stops.
    find_events : dict
        The arguments to the real-time `find_events` method as a dictionary.
        If `find_events` is None, then default values are used.
        Example (also default values)::

            find_events = dict(output='onset', consecutive='increasing',
                               min_duration=0, mask=0, mask_type='not_and',
                               verbose='ERROR')

        See :func:`mne.find_events` for detailed explanation of these options.
    verbose : bool, str, int, or None
        If not None, override default verbose level (see :func:`mne.verbose`
        and :ref:`Logging documentation <tut_logging>` for more). Defaults to
        client.verbose.

    Attributes
    ----------
    info : dict
        Measurement info.
    event_id : dict
        Names of  of conditions corresponding to event_ids.
    ch_names : list of string
        List of channels' names.
    events : array, shape (n_events, 3)
        The events associated with the epochs currently in the queue.
    verbose : bool, str, int, or None
        See above.

    Notes
    -----
    - Calling `next()` on an `RtEpochs` object (as internally done when
      iterating over the object) is blocking, i.e., waits for at most `isi_max`
      seconds for a new epoch to be received.
    - Calling `get_data()` on an `RtEpochs` object immediately returns the
      epochs received so far (without waiting for new epochs).
    """

    @verbose
    def __init__(self, client, event_id, tmin, tmax, stim_channel='STI 014',
                 sleep_time=0.1, baseline=(None, 0), picks=None,
                 reject=None, flat=None, proj=True,
                 decim=1, reject_tmin=None, reject_tmax=None, detrend=None,
                 isi_max=2., find_events=None, verbose=None):  # noqa: D102
        info = client.get_measurement_info()

        # the measurement info of the data as we receive it
        self._client_info = copy.deepcopy(info)

        verbose = client.verbose if verbose is None else verbose

        # FIFO queues for received epochs and events
        # need to be initialized to validate invariants in base constructor
        self._epoch_queue = list()
        self._events = list()
        self._selection = list()

        # call BaseEpochs constructor
        super(RtEpochs, self).__init__(
            info, None, None, event_id, tmin, tmax, baseline, picks=picks,
            reject=reject, flat=flat, decim=decim,
            reject_tmin=reject_tmin, reject_tmax=reject_tmax, detrend=detrend,
            verbose=verbose, proj=True)
        self._bad_dropped = True

        self._client = client

        if not isinstance(stim_channel, list):
            stim_channel = [stim_channel]

        stim_picks = pick_channels(self._client_info['ch_names'],
                                   include=stim_channel, exclude=[])

        if len(stim_picks) == 0:
            raise ValueError('No stim channel found to extract event '
                             'triggers.')

        self._stim_picks = stim_picks

        # find_events default options
        self._find_events_kwargs = dict(output='onset',
                                        consecutive='increasing',
                                        min_duration=0, mask=0,
                                        mask_type='not_and',
                                        verbose='ERROR')
        # update default options if dictionary is provided
        if find_events is not None:
            self._find_events_kwargs.update(find_events)
        min_samples = (self._find_events_kwargs['min_duration'] *
                       self.info['sfreq'])
        self._find_events_kwargs.pop('min_duration', None)
        self._find_events_kwargs['min_samples'] = min_samples

        self._sleep_time = sleep_time

        # add calibration factors
        cals = np.zeros(self._client_info['nchan'])
        for k in range(self._client_info['nchan']):
            cals[k] = (self._client_info['chs'][k]['range'] *
                       self._client_info['chs'][k]['cal'])
        self._cals = cals[:, None]

        # variables needed for receiving raw buffers
        self._last_buffer = None
        self._first_samp = 0
        self._event_backlog = list()

        # Number of good and bad epochs received
        self._n_good = 0
        self._n_bad = 0

        self._started = False
        self._last_time = time.time()

        self.isi_max = isi_max

    @property
    def events(self):
        """The events associated with the epochs currently in the queue."""
        return np.array(self._events)

    @events.setter
    def events(self, new_events):
        """
        Update the internal event list.

        Parameters
        ----------
        new_events : array of int, shape (n_events, 3)
            new events
        """
        self._events = [tuple(new_events[i, :])
                        for i in range(len(new_events))]

    @property
    def selection(self):
        """Array of integers of the current selection."""
        return np.asarray(self._selection, dtype=int)

    @selection.setter
    def selection(self, new_selection):
        """
        Update the internal selection list.

        Parameters
        ----------
        new_selection : iterable of epoch indices

        """
        self._selection = list(new_selection)

    def copy(self):
        """Return copy of Epochs instance."""
        client = self._client
        del self._client
        new = super(RtEpochs, self).copy()
        self._client = client
        new._client = client
        return new

    def _getitem(self, item, reason='IGNORED', copy=True, drop_event_id=True,
                 select_data=True, return_indices=False):

        epochs, select = super(RtEpochs, self)._getitem(
            item=item, reason=reason, copy=copy, drop_event_id=drop_event_id,
            select_data=False, return_indices=True)

        # try to be compatible with numpy indexing
        new_queue = list()
        for kept_idx in np.arange(len(epochs._epoch_queue), dtype=int)[select]:
            new_queue.append(epochs._epoch_queue[kept_idx])
        epochs._epoch_queue = new_queue

        epochs._n_good = len(epochs._epoch_queue)

        return epochs

    def start(self):
        """Start receiving epochs.

        The measurement will be started if it has not already been started.
        """
        if not self._started:
            # register the callback
            self._client.register_receive_callback(self._process_raw_buffer)

            # start the measurement and the receive thread
            nchan = self._client_info['nchan']
            self._client.start_receive_thread(nchan)
            self._started = True
            self._last_time = np.inf  # init delay counter. Will stop iters

    def stop(self, stop_receive_thread=False, stop_measurement=False):
        """Stop receiving epochs.

        Parameters
        ----------
        stop_receive_thread : bool
            Stop the receive thread. Note: Other RtEpochs instances will also
            stop receiving epochs when the receive thread is stopped. The
            receive thread will always be stopped if stop_measurement is True.

        stop_measurement : bool
            Also stop the measurement. Note: Other clients attached to the
            server will also stop receiving data.
        """
        if self._started:
            self._client.unregister_receive_callback(self._process_raw_buffer)
            self._started = False

        if stop_receive_thread or stop_measurement:
            self._client.stop_receive_thread(stop_measurement=stop_measurement)

    def next(self, return_event_id=False):
        """Make iteration over epochs easy.

        Parameters
        ----------
        return_event_id : bool
            If True, return both an epoch and and event_id.

        Returns
        -------
        epoch : instance of Epochs
            The epoch.
        event_id : int
            The event id. Only returned if ``return_event_id`` is ``True``.
        """
        first = True
        while True:
            current_time = time.time()
            if len(self._epoch_queue) > self._current:
                epoch = self._epoch_queue[self._current]
                event_id = self._events[self._current][-1]
                self._current += 1
                self._last_time = current_time
                return (epoch, event_id) if return_event_id else epoch
            if current_time > (self._last_time + self.isi_max):
                logger.info('Time of %s seconds exceeded.' % self.isi_max)
                return  # signal the end properly
            if self._started:
                if first:
                    logger.info('Waiting for epoch %d' % (self._current + 1))
                    first = False
                time.sleep(self._sleep_time)
            else:
                raise RuntimeError('Not enough epochs in queue and currently '
                                   'not receiving epochs, cannot get epochs!')

    @verbose
    def _get_data(self, out=True, verbose=None):
        """
        Return all data as numpy array.

        Parameters
        ----------
        out : bool
            Return the data.
        verbose: bool, str, int, or None
            If not None, override default verbose level (see
            :func:`mne.verbose` and :ref:`Logging documentation <tut_logging>`
            for more). Defaults to self.verbose.

        Returns
        -------
        np.ndarray or None
        epochs data

        Notes
        -----
        Rejection in RtEpochs already happens at epoch creation,
        not on data loading.
        """
        if out:
            epochs = list()
            for epoch in self._epoch_queue:
                epochs.append(epoch)

            data = np.array(epochs)

            return data

    def _process_raw_buffer(self, raw_buffer):
        """Process raw buffer (callback from RtClient).

        Note: Do not print log messages during regular use. It will be printed
        asynchronously which is annoying when working in an interactive shell.

        Parameters
        ----------
        raw_buffer : array of float, shape=(nchan, n_times)
            The raw buffer.
        """
        sfreq = self.info['sfreq']
        n_samp = len(self._raw_times)

        # relative start and stop positions in samples
        tmin_samp = int(round(sfreq * self.tmin))
        tmax_samp = tmin_samp + n_samp

        last_samp = self._first_samp + raw_buffer.shape[1] - 1

        # apply calibration without inplace modification
        raw_buffer = self._cals * raw_buffer

        # detect events
        data = np.abs(raw_buffer[self._stim_picks]).astype(np.int)
        # if there is a previous buffer check the last samples from it too
        if self._last_buffer is not None:
            prev_data = self._last_buffer[self._stim_picks,
                                          -raw_buffer.shape[1]:].astype(np.int)
            data = np.concatenate((prev_data, data), axis=1)
            data = np.atleast_2d(data)
            buff_events = _find_events(data,
                                       self._first_samp - raw_buffer.shape[1],
                                       **self._find_events_kwargs)
        else:
            data = np.atleast_2d(data)
            buff_events = _find_events(data, self._first_samp,
                                       **self._find_events_kwargs)

        events = self._event_backlog

        # remove events before the last epoch processed
        min_event_samp = self._first_samp - \
            int(self._find_events_kwargs['min_samples'])
        if len(self._event_backlog) > 0:
            backlog_samps = np.array(self._event_backlog)[:, 0]
            min_event_samp = backlog_samps[-1] + 1

        if buff_events.shape[0] > 0:
            valid_events_idx = buff_events[:, 0] >= min_event_samp
            buff_events = buff_events[valid_events_idx]

        # add events from this buffer to the list of events
        # processed so far
        for event_id in self.event_id.values():
            idx = np.where(buff_events[:, -1] == event_id)[0]
            events.extend(zip(list(buff_events[idx, 0]),
                              list(buff_events[idx, -1])))

        events.sort()

        event_backlog = list()
        for event_samp, event_id in events:
            epoch = None
            if (event_samp + tmin_samp >= self._first_samp and
                    event_samp + tmax_samp <= last_samp):
                # easy case: whole epoch is in this buffer
                start = event_samp + tmin_samp - self._first_samp
                stop = event_samp + tmax_samp - self._first_samp
                epoch = raw_buffer[:, start:stop]
            elif (event_samp + tmin_samp < self._first_samp and
                    event_samp + tmax_samp <= last_samp):
                # have to use some samples from previous buffer
                if self._last_buffer is None:
                    continue
                n_last = self._first_samp - (event_samp + tmin_samp)
                n_this = n_samp - n_last
                epoch = np.c_[self._last_buffer[:, -n_last:],
                              raw_buffer[:, :n_this]]
            elif event_samp + tmax_samp > last_samp:
                # we need samples from the future
                # we will process this epoch with the next buffer
                event_backlog.append((event_samp, event_id))
            else:
                raise RuntimeError('Unhandled case..')

            if epoch is not None:
                self._append_epoch_to_queue(epoch, event_samp, event_id)

        # set things up for processing of next buffer
        self._event_backlog = event_backlog
        n_buffer = raw_buffer.shape[1]
        if self._last_buffer is None:
            self._last_buffer = raw_buffer
        elif self._last_buffer.shape[1] <= n_samp + n_buffer:
            self._last_buffer = np.c_[self._last_buffer, raw_buffer]
        else:
            # do not increase size of _last_buffer any further
            self._last_buffer[:, :-n_buffer] = self._last_buffer[:, n_buffer:]
            self._last_buffer[:, -n_buffer:] = raw_buffer
        self._first_samp = self._first_samp + n_buffer

    def _append_epoch_to_queue(self, epoch, event_samp, event_id):
        """Append a (raw) epoch to queue.

        Note: Do not print log messages during regular use. It will be printed
        asynchronously which is annyoing when working in an interactive shell.

        Parameters
        ----------
        epoch : array of float, shape=(nchan, n_times)
            The raw epoch (only calibration has been applied) over all
            channels.
        event_samp : int
            The time in samples when the epoch occurred.
        event_id : int
            The event ID of the epoch.
        """
        # select the channels
        epoch = epoch[self.picks, :]

        # Detrend, baseline correct, decimate
        epoch = self._detrend_offset_decim(epoch, verbose='ERROR')

        # apply SSP
        epoch = self._project_epoch(epoch)

        # Decide if this is a good epoch
        is_good, offending_reasons = self._is_good_epoch(epoch,
                                                         verbose='ERROR')

        if is_good:
            self._epoch_queue.append(epoch)
            self._events.append((event_samp, 0, event_id))
            self.drop_log.append(list())
            self._selection.append(len(self.drop_log) - 1)
            self._n_good += 1
        else:
            self.drop_log.append(offending_reasons)
            self._n_bad += 1

    @verbose
    def decimate(self, decim, offset=0, verbose=None):
        """Decimate the epochs.

        .. note:: No filtering is performed. To avoid aliasing, ensure
                  your data are properly lowpassed.

        Parameters
        ----------
        decim : int
            The amount to decimate data.
        offset : int
            Apply an offset to where the decimation starts relative to the
            sample corresponding to t=0. The offset is in samples at the
            current sampling rate.

            .. versionadded:: 0.12

        verbose : bool, str, int, or None
            If not None, override default verbose level (see
            :func:`mne.verbose` and :ref:`Logging documentation <tut_logging>`
            for more).

        Returns
        -------
        epochs : instance of Epochs
            The decimated Epochs object.

        See Also
        --------
        mne.Evoked.decimate
        mne.Epochs.resample
        mne.io.Raw.resample

        Notes
        -----
        Decimation can be done multiple times. For example,
        ``epochs.decimate(2).decimate(2)`` will be the same as
        ``epochs.decimate(4)``.
        If `decim` is 1, this method does not copy the underlying data.

        .. versionadded:: 0.10.0
        """
        super(RtEpochs, self).decimate(decim, offset, verbose)
        for i in range(len(self._epoch_queue)):
            self._epoch_queue[i] = self._epoch_queue[i][:, self._decim_slice]
        return self

    def __repr__(self):  # noqa: D105
        s = 'good / bad epochs received: %d / %d, epochs in queue: %d, '\
            % (self._n_good, self._n_bad, len(self._epoch_queue))
        s += ', tmin : %s (s)' % self.tmin
        s += ', tmax : %s (s)' % self.tmax
        s += ', baseline : %s' % str(self.baseline)
        return '<RtEpochs  |  %s>' % s


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `Borrow` trait in crate `std`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, Borrow">

    <title>std::borrow::Borrow - Rust</title>

    <link rel="stylesheet" type="text/css" href="../../main.css">

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

std::<wbr>borrow

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Trait std::<wbr>borrow::<wbr>Borrow<wbr>Stable
            [-] [+]
        [src]

pub trait Borrow<Borrowed> where Borrowed: ?Sized {
    fn borrow(&self) -> &Borrowed;
}

A trait for borrowing data.

In general, there may be several ways to "borrow" a piece of data.  The
typical ways of borrowing a type T are &T (a shared borrow) and &mut T
(a mutable borrow). But types like Vec<T> provide additional kinds of
borrows: the borrowed slices &[T] and &mut [T].

When writing generic code, it is often desirable to abstract over all ways
of borrowing data from a given type. That is the role of the Borrow
trait: if T: Borrow<U>, then &U can be borrowed from &T.  A given
type can be borrowed as multiple different types. In particular, Vec<T>:
Borrow<Vec<T>> and Vec<T>: Borrow<[T]>.

Required Methods

fn borrow(&self) -> &Borrowed

Immutably borrow from an owned value.

Implementors

impl<T> Borrow<T> for T where T: ?Sized

impl<'a, T> Borrow<T> for &'a T where T: ?Sized

impl<'a, T> Borrow<T> for &'a mut T where T: ?Sized

impl<T> Borrow<T> for Rc<T>

impl<T> Borrow<T> for Arc<T>

impl<'a, B> Borrow<B> for Cow<'a, B> where B: ToOwned, <B as ToOwned>::Owned: 'a, B: ?Sized

impl<T> Borrow<[T]> for Vec<T>

impl Borrow<str> for String

impl Borrow<OsStr> for OsString

impl Borrow<Path> for PathBuf

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var conf = require('../../lib/config');
var logger = require('../../lib/logger');
var GCM = require('gcm').GCM;

// Implementation of google messaging service for Android
var LocMapGoogleCloudMessagingService = function() {
    this.notifications = {};// we just store notifications here if not in production. key is token, value is array of messages for this token
    this.gcm = new GCM(conf.get('googleCloudMessagingApiKey'));

};

LocMapGoogleCloudMessagingService.prototype = {};
// push notification to device with deviceToken and text notificationText.
// You can define payload which will be sent also to client or leave it undefined. payload must be an object
LocMapGoogleCloudMessagingService.prototype.pushNotification = function(deviceToken, notificationText, payload) {
    // Detect if we run unit tests (in local machine), and dont push notifications.
    if (!conf.get('pushNotifications')) {
        if (this.notifications[deviceToken] === undefined) {
            this.notifications[deviceToken] = [];
        }
        this.notifications[deviceToken].push(notificationText);// we just store notifications here if not in production
        return;
    }

    var message = {
        'registration_id': deviceToken, // required
        'collapse_key': 'Message',
        'data.message': notificationText
    };
    if (payload) {
        message['data.payload'] = JSON.stringify(payload);
    }

    logger.trace('GCM Send for device: ' + deviceToken);
    this.gcm.send(message, function(err) {
        if (err) {
            logger.error('%j when sending message: %j', err, message);
        }
    });

};

module.exports = LocMapGoogleCloudMessagingService;


text:
require 'ghee/version'
require 'ghee/connection'
require 'ghee/resource_proxy'
require 'ghee/state_methods'
require 'ghee/api/authorizations'
require 'ghee/api/gists'
require 'ghee/api/users'
require 'ghee/api/events'
require 'ghee/api/repos'
require 'ghee/api/issues'
require 'ghee/api/milestones'
require 'ghee/api/orgs'
require 'ghee/api/git_data'
require 'ghee/api/downloads'

class Ghee
  attr_reader :connection

  include Ghee::API::Authorizations
  include Ghee::API::Gists
  include Ghee::API::Users
  include Ghee::API::Events
  include Ghee::API::Repos
  include Ghee::API::Issues
  include Ghee::API::Milestones
  include Ghee::API::Orgs

  # Instantiates Ghee, accepts an access_token
  # for authenticated access
  #
  # Access_token - String of the access_token
  #
  def initialize(options = {})
    @connection = Ghee::Connection.new(options)
  end

  def self.basic_auth(user_name, password)
      Ghee.new :basic_auth  => {:user_name => user_name, :password => password}
  end

  def self.access_token(token)
    Ghee.new :access_token => token
  end

  def self.create_token(user_name, password, scopes)
    auth = Ghee.basic_auth(user_name, password).authorizations.create({
      :scopes => scopes})
    auth["token"]
  end
end


text:
#ifndef DALI_INTERNAL_PROJECTION_H
#define DALI_INTERNAL_PROJECTION_H

namespace Dali
{
struct Vector4;
struct Vector2;

class Matrix;

namespace Internal
{
bool XyPlaneIntersect(const Dali::Vector4& pointA,
                      const Dali::Vector4& pointB,
                      Dali::Vector4&       intersect);

bool UnprojectFull(const Dali::Vector4& windowPos,
                   const Matrix&        modelView,
                   const Matrix&        projection,
                   float                viewportWidth,
                   float                viewportHeight,
                   Dali::Vector4&       objectPos);

bool Unproject(const Dali::Vector4& windowPos,
               const Matrix&        inverseMvp,
               float                viewportWidth,
               float                viewportHeight,
               Dali::Vector4&       objectPos);

bool ProjectFull(const Vector4& position,
                 const Matrix&  modelView,
                 const Matrix&  projection,
                 float          viewportX,
                 float          viewportY,
                 float          viewportWidth,
                 float          viewportHeight,
                 Vector4&       windowPos);

} // namespace Internal

} // namespace Dali

#endif // DALI_INTERNAL_PROJECTION_H


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
    <type>org.netbeans.modules.php.project</type>
    <configuration>
        <data xmlns="http://www.netbeans.org/ns/php-project/1">
            <name>skaphandrus_v4</name>
        </data>
    </configuration>
</project>


text:
var chapter1section1 = new app.SingleSection({
	name:"Section 1",
	link:"c1s1"
});
var chapter1section2 = new app.SingleSection({
	name:"Section2",
	link:"c1s2"
});
var chapter1section3 = new app.SingleSection({
	name:"Section3",
	link:"c1s3"
});

var lessonGroup = new app.AllLessons([
	chapter1section1, chapter1section2, chapter1section3
]);

var lessonGroupView = new app.AllLessonsView({collection:lessonGroup});
$("allLessons").html(lessonGroupView.render().el);


text:
@interface GridMatrix : NSObject
@property (retain)NSMutableArray* matrix;
@property (getter = getColumns, readonly)NSInteger columns;
@property (getter = getRows, readonly)NSInteger rows;
-(BOOL)isMarked:(NSInteger)row :(NSInteger)column;
-(BOOL)mark:(NSInteger)row :(NSInteger)column;
-(BOOL)unmark:(NSInteger)row :(NSInteger)column;
-(BOOL)flip:(NSInteger)row :(NSInteger)column;
-(id)initGridMatrix:(NSInteger)rows :(NSInteger)columns;

//methods that use linear index
-(BOOL)isMarked:(NSInteger)x;
-(BOOL)mark:(NSInteger)x;
-(BOOL)unmark:(NSInteger)x;
-(BOOL)flip:(NSInteger)x;

-(GridMatrix*)newMatrix: (NSInteger)newHeight :(NSInteger)newWidth;
@end
#endif


text:
package main

import (
	"fmt"
	"math/rand"
	"time"
)

// START OMIT
func pointlessFunc(msg string, quit chan bool) <-chan string {
	c := make(chan string)
	go func() { // Lanunch a go rotutine from the function using an anymonous function
		for i := 0; i < 10; i++ {
			c <- fmt.Sprintf("%s %d", msg, i)
			time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
			quit <- true // We send a signal down the quit channel
		}
	}()
	return c
}

func main() {
	quit := make(chan bool)
	c := pointlessFunc("My names Charlie", quit)
	for {
		select {
		case s := <-c:
			fmt.Println(s)
		case <-quit:
			fmt.Println("I'm quiting...")
			return // The main function will finish after this is executed
		}
	}
}

// END OMIT


text:
#ifdef MODULE
#include <linux/module.h>
#include <linux/version.h>
#else
#define MOD_INC_USE_COUNT
#define MOD_DEC_USE_COUNT
#endif

#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/major.h>
#include <linux/sched.h>
#include <linux/lp.h>
#include <linux/malloc.h>
#include <linux/ioport.h>
#include <linux/fcntl.h>

#include <asm/io.h>
#include <asm/segment.h>
#include <asm/system.h>

/* the BIOS manuals say there can be up to 4 lpt devices
 * but I have not seen a board where the 4th address is listed
 * if you have different hardware change the table below
 * please let me know if you have different equipment
 * if you have more than 3 printers, remember to increase LP_NO
 */
struct lp_struct lp_table[] = {
	{ 0x3bc, 0, 0, LP_INIT_CHAR, LP_INIT_TIME, LP_INIT_WAIT, NULL, NULL, },
	{ 0x378, 0, 0, LP_INIT_CHAR, LP_INIT_TIME, LP_INIT_WAIT, NULL, NULL, },
	{ 0x278, 0, 0, LP_INIT_CHAR, LP_INIT_TIME, LP_INIT_WAIT, NULL, NULL, },
};
#define LP_NO 3

/* Test if printer is ready (and optionally has no error conditions) */
#define LP_READY(minor, status) \
  ((LP_F(minor) & LP_CAREFUL) ? _LP_CAREFUL_READY(status) : (status & LP_PBUSY))
#define LP_CAREFUL_READY(minor, status) \
  ((LP_F(minor) & LP_CAREFUL) ? _LP_CAREFUL_READY(status) : 1)
#define _LP_CAREFUL_READY(status) \
   (status & (LP_PBUSY|LP_POUTPA|LP_PSELECD|LP_PERRORP)) == \
      (LP_PBUSY|LP_PSELECD|LP_PERRORP)

/* Allow old versions of tunelp to continue to work */
#define OLD_LPCHAR   0x0001
#define OLD_LPTIME   0x0002
#define OLD_LPABORT  0x0004
#define OLD_LPSETIRQ 0x0005
#define OLD_LPGETIRQ 0x0006
#define OLD_LPWAIT   0x0008
#define OLD_IOCTL_MAX 8

/*
 * All my debugging code assumes that you debug with only one printer at
 * a time. RWWH
 */

#undef LP_DEBUG

static int lp_reset(int minor)
{
	int testvalue;
	unsigned char command;

	command = LP_PSELECP | LP_PINITP;

	/* reset value */
	outb_p(0, LP_C(minor));
	for (testvalue = 0 ; testvalue < LP_DELAY ; testvalue++)
		;
	outb_p(command, LP_C(minor));
	return LP_S(minor);
}

#ifdef LP_DEBUG
static int lp_max_count = 1;
#endif

static int lp_char_polled(char lpchar, int minor)
{
	int status = 0, wait = 0;
	unsigned long count  = 0;

	do {
		status = LP_S(minor);
		count ++;
		if(need_resched)
			schedule();
	} while(!LP_READY(minor,status) && count < LP_CHAR(minor));

	if (count == LP_CHAR(minor)) {
		return 0;
		/* we timed out, and the character was /not/ printed */
	}
#ifdef LP_DEBUG
	if (count > lp_max_count) {
		printk("lp success after %d counts.\n",count);
		lp_max_count=count;
	}
#endif
	outb_p(lpchar, LP_B(minor));
	/* must wait before taking strobe high, and after taking strobe
	   low, according spec.  Some printers need it, others don't. */
	while(wait != LP_WAIT(minor)) wait++;
        /* control port takes strobe high */
	outb_p(( LP_PSELECP | LP_PINITP | LP_PSTROBE ), ( LP_C( minor )));
	while(wait) wait--;
        /* take strobe low */
	outb_p(( LP_PSELECP | LP_PINITP ), ( LP_C( minor )));

	return 1;
}

static int lp_char_interrupt(char lpchar, int minor)
{
	int wait = 0;
	unsigned char status;

	if (!((status = LP_S(minor)) & LP_PACK) || (status & LP_PBUSY)
	|| !((status = LP_S(minor)) & LP_PACK) || (status & LP_PBUSY)
	|| !((status = LP_S(minor)) & LP_PACK) || (status & LP_PBUSY)) {

		if (!LP_CAREFUL_READY(minor, status))
			return 0;
		outb_p(lpchar, LP_B(minor));
		/* must wait before taking strobe high, and after taking strobe
		   low, according spec.  Some printers need it, others don't. */
		while(wait != LP_WAIT(minor)) wait++;
		/* control port takes strobe high */
		outb_p(( LP_PSELECP | LP_PINITP | LP_PSTROBE ), ( LP_C( minor )));
		while(wait) wait--;
		/* take strobe low */
		outb_p(( LP_PSELECP | LP_PINITP ), ( LP_C( minor )));
		return 1;
	}

	return 0;
}

#ifdef LP_DEBUG
	unsigned int lp_total_chars = 0;
	unsigned int lp_last_call = 0;
#endif

static void lp_interrupt(int irq, struct pt_regs *regs)
{
	struct lp_struct *lp = &lp_table[0];
	struct lp_struct *lp_end = &lp_table[LP_NO];

	while (irq != lp->irq) {
		if (++lp >= lp_end)
			return;
	}

	wake_up(&lp->lp_wait_q);
}

static int lp_write_interrupt(struct inode * inode, struct file * file, char * buf, int count)
{
	unsigned int minor = MINOR(inode->i_rdev);
	unsigned long copy_size;
	unsigned long total_bytes_written = 0;
	unsigned long bytes_written;
	struct lp_struct *lp = &lp_table[minor];
	unsigned char status;

	do {
		bytes_written = 0;
		copy_size = (count <= LP_BUFFER_SIZE ? count : LP_BUFFER_SIZE);
		memcpy_fromfs(lp->lp_buffer, buf, copy_size);

		while (copy_size) {
			if (lp_char_interrupt(lp->lp_buffer[bytes_written], minor)) {
				--copy_size;
				++bytes_written;
			} else {
				int rc = total_bytes_written + bytes_written;
				status = LP_S(minor);
				if ((status & LP_POUTPA)) {
					printk(KERN_INFO "lp%d out of paper\n", minor);
					if (LP_F(minor) & LP_ABORT)
						return rc?rc:-ENOSPC;
				} else if (!(status & LP_PSELECD)) {
					printk(KERN_INFO "lp%d off-line\n", minor);
					if (LP_F(minor) & LP_ABORT)
						return rc?rc:-EIO;
				} else if (!(status & LP_PERRORP)) {
					printk(KERN_ERR "lp%d printer error\n", minor);
					if (LP_F(minor) & LP_ABORT)
						return rc?rc:-EIO;
				}
				cli();
				outb_p((LP_PSELECP|LP_PINITP|LP_PINTEN), (LP_C(minor)));
				status = LP_S(minor);
				if ((!(status & LP_PACK) || (status & LP_PBUSY))
				  && LP_CAREFUL_READY(minor, status)) {
					outb_p((LP_PSELECP|LP_PINITP), (LP_C(minor)));
					sti();
					continue;
				}
				current->timeout = jiffies + LP_TIMEOUT_INTERRUPT;
				interruptible_sleep_on(&lp->lp_wait_q);
				outb_p((LP_PSELECP|LP_PINITP), (LP_C(minor)));
				sti();
				if (current->signal & ~current->blocked) {
					if (total_bytes_written + bytes_written)
						return total_bytes_written + bytes_written;
					else
						return -EINTR;
				}
			}
		}

		total_bytes_written += bytes_written;
		buf += bytes_written;
		count -= bytes_written;

	} while (count > 0);

	return total_bytes_written;
}

static int lp_write_polled(struct inode * inode, struct file * file,
			   char * buf, int count)
{
	int  retval;
	unsigned int minor = MINOR(inode->i_rdev);
	char c, *temp = buf;

#ifdef LP_DEBUG
	if (jiffies-lp_last_call > LP_TIME(minor)) {
		lp_total_chars = 0;
		lp_max_count = 1;
	}
	lp_last_call = jiffies;
#endif

	temp = buf;
	while (count > 0) {
		c = get_fs_byte(temp);
		retval = lp_char_polled(c, minor);
		/* only update counting vars if character was printed */
		if (retval) { count--; temp++;
#ifdef LP_DEBUG
			lp_total_chars++;
#endif
		}
		if (!retval) { /* if printer timed out */
			int status = LP_S(minor);

			if (status & LP_POUTPA) {
				printk(KERN_INFO "lp%d out of paper\n", minor);
				if(LP_F(minor) & LP_ABORT)
					return temp-buf?temp-buf:-ENOSPC;
				current->state = TASK_INTERRUPTIBLE;
				current->timeout = jiffies + LP_TIMEOUT_POLLED;
				schedule();
			} else
			if (!(status & LP_PSELECD)) {
				printk(KERN_INFO "lp%d off-line\n", minor);
				if(LP_F(minor) & LP_ABORT)
					return temp-buf?temp-buf:-EIO;
				current->state = TASK_INTERRUPTIBLE;
				current->timeout = jiffies + LP_TIMEOUT_POLLED;
				schedule();
			} else
	                /* not offline or out of paper. on fire? */
			if (!(status & LP_PERRORP)) {
				printk(KERN_ERR "lp%d reported invalid error status (on fire, eh?)\n", minor);
				if(LP_F(minor) & LP_ABORT)
					return temp-buf?temp-buf:-EIO;
				current->state = TASK_INTERRUPTIBLE;
				current->timeout = jiffies + LP_TIMEOUT_POLLED;
				schedule();
			}

			/* check for signals before going to sleep */
			if (current->signal & ~current->blocked) {
				if (temp != buf)
					return temp-buf;
				else
					return -EINTR;
			}
#ifdef LP_DEBUG
			printk("lp sleeping at %d characters for %d jiffies\n",
				lp_total_chars, LP_TIME(minor));
			lp_total_chars=0;
#endif
			current->state = TASK_INTERRUPTIBLE;
			current->timeout = jiffies + LP_TIME(minor);
			schedule();
		}
	}
	return temp-buf;
}

static int lp_write(struct inode * inode, struct file * file, char * buf, int count)
{
	if (LP_IRQ(MINOR(inode->i_rdev)))
		return lp_write_interrupt(inode, file, buf, count);
	else
		return lp_write_polled(inode, file, buf, count);
}

static int lp_lseek(struct inode * inode, struct file * file,
		    off_t offset, int origin)
{
	return -ESPIPE;
}

static int lp_open(struct inode * inode, struct file * file)
{
	unsigned int minor = MINOR(inode->i_rdev);
	int ret;
	unsigned int irq;

	if (minor >= LP_NO)
		return -ENODEV;
	if ((LP_F(minor) & LP_EXIST) == 0)
		return -ENODEV;
	if (LP_F(minor) & LP_BUSY)
		return -EBUSY;

	MOD_INC_USE_COUNT;

	/* If ABORTOPEN is set and the printer is offline or out of paper,
	   we may still want to open it to perform ioctl()s.  Therefore we
	   have commandeered O_NONBLOCK, even though it is being used in
	   a non-standard manner.  This is strictly a Linux hack, and
	   should most likely only ever be used by the tunelp application. */
        if ((LP_F(minor) & LP_ABORTOPEN) && !(file->f_flags & O_NONBLOCK)) {
		int status = LP_S(minor);
		if (status & LP_POUTPA) {
			printk(KERN_INFO "lp%d out of paper\n", minor);
			MOD_DEC_USE_COUNT;
			return -ENOSPC;
		} else if (!(status & LP_PSELECD)) {
			printk(KERN_INFO "lp%d off-line\n", minor);
			MOD_DEC_USE_COUNT;
			return -EIO;
		} else if (!(status & LP_PERRORP)) {
			printk(KERN_ERR "lp%d printer error\n", minor);
			MOD_DEC_USE_COUNT;
			return -EIO;
		}
	}

	if ((irq = LP_IRQ(minor))) {
		lp_table[minor].lp_buffer = (char *) kmalloc(LP_BUFFER_SIZE, GFP_KERNEL);
		if (!lp_table[minor].lp_buffer) {
			MOD_DEC_USE_COUNT;
			return -ENOMEM;
		}

		ret = request_irq(irq, lp_interrupt, SA_INTERRUPT, "printer");
		if (ret) {
			kfree_s(lp_table[minor].lp_buffer, LP_BUFFER_SIZE);
			lp_table[minor].lp_buffer = NULL;
			printk("lp%d unable to use interrupt %d, error %d\n", minor, irq, ret);
			MOD_DEC_USE_COUNT;
			return ret;
		}
	}

	LP_F(minor) |= LP_BUSY;
	return 0;
}

static void lp_release(struct inode * inode, struct file * file)
{
	unsigned int minor = MINOR(inode->i_rdev);
	unsigned int irq;

	if ((irq = LP_IRQ(minor))) {
		free_irq(irq);
		kfree_s(lp_table[minor].lp_buffer, LP_BUFFER_SIZE);
		lp_table[minor].lp_buffer = NULL;
	}

	LP_F(minor) &= ~LP_BUSY;
	MOD_DEC_USE_COUNT;
}

static int lp_ioctl(struct inode *inode, struct file *file,
		    unsigned int cmd, unsigned long arg)
{
	unsigned int minor = MINOR(inode->i_rdev);
	int retval = 0;

#ifdef LP_DEBUG
	printk("lp%d ioctl, cmd: 0x%x, arg: 0x%x\n", minor, cmd, arg);
#endif
	if (minor >= LP_NO)
		return -ENODEV;
	if ((LP_F(minor) & LP_EXIST) == 0)
		return -ENODEV;
	if (cmd <= OLD_IOCTL_MAX)
		printk(KERN_NOTICE "lp%d: warning: obsolete ioctl %#x (perhaps you need a new tunelp)\n",
		    minor, cmd);
	switch ( cmd ) {
		case OLD_LPTIME:
		case LPTIME:
			LP_TIME(minor) = arg;
			break;
		case OLD_LPCHAR:
		case LPCHAR:
			LP_CHAR(minor) = arg;
			break;
		case OLD_LPABORT:
		case LPABORT:
			if (arg)
				LP_F(minor) |= LP_ABORT;
			else
				LP_F(minor) &= ~LP_ABORT;
			break;
		case LPABORTOPEN:
			if (arg)
				LP_F(minor) |= LP_ABORTOPEN;
			else
				LP_F(minor) &= ~LP_ABORTOPEN;
			break;
		case LPCAREFUL:
			if (arg)
				LP_F(minor) |= LP_CAREFUL;
			else
				LP_F(minor) &= ~LP_CAREFUL;
			break;
		case OLD_LPWAIT:
		case LPWAIT:
			LP_WAIT(minor) = arg;
			break;
		case OLD_LPSETIRQ:
		case LPSETIRQ: {
			int oldirq;
			int newirq = arg;
			struct lp_struct *lp = &lp_table[minor];

			if (!suser())
				return -EPERM;

			oldirq = LP_IRQ(minor);

			/* Allocate buffer now if we are going to need it */
			if (!oldirq && newirq) {
				lp->lp_buffer = (char *) kmalloc(LP_BUFFER_SIZE, GFP_KERNEL);
				if (!lp->lp_buffer)
					return -ENOMEM;
			}

			if (oldirq) {
				free_irq(oldirq);
			}
			if (newirq) {
				/* Install new irq */
				if ((retval = request_irq(newirq, lp_interrupt, SA_INTERRUPT, "printer"))) {
					if (oldirq) {
						/* restore old irq */
						request_irq(oldirq, lp_interrupt, SA_INTERRUPT, "printer");
					} else {
						/* We don't need the buffer */
						kfree_s(lp->lp_buffer, LP_BUFFER_SIZE);
						lp->lp_buffer = NULL;
					}
					return retval;
				}
			}
			if (oldirq && !newirq) {
				/* We don't need the buffer */
				kfree_s(lp->lp_buffer, LP_BUFFER_SIZE);
				lp->lp_buffer = NULL;
			}
			LP_IRQ(minor) = newirq;
			lp_reset(minor);
			break;
		}
		case OLD_LPGETIRQ:
			retval = LP_IRQ(minor);
			break;
		case LPGETIRQ:
			retval = verify_area(VERIFY_WRITE, (void *) arg,
			    sizeof(int));
		    	if (retval)
		    		return retval;
			memcpy_tofs((int *) arg, &LP_IRQ(minor), sizeof(int));
			break;
		case LPGETSTATUS:
			retval = verify_area(VERIFY_WRITE, (void *) arg,
			    sizeof(int));
		    	if (retval)
		    		return retval;
			else {
				int status = LP_S(minor);
				memcpy_tofs((int *) arg, &status, sizeof(int));
			}
			break;
		case LPRESET:
			lp_reset(minor);
			break;
		default:
			retval = -EINVAL;
	}
	return retval;
}

static struct file_operations lp_fops = {
	lp_lseek,
	NULL,		/* lp_read */
	lp_write,
	NULL,		/* lp_readdir */
	NULL,		/* lp_select */
	lp_ioctl,
	NULL,		/* lp_mmap */
	lp_open,
	lp_release
};

#ifndef MODULE

long lp_init(long kmem_start)
{
	int offset = 0;
	unsigned int testvalue = 0;
	int count = 0;

	if (register_chrdev(LP_MAJOR,"lp",&lp_fops)) {
		printk("unable to get major %d for line printer\n", LP_MAJOR);
		return kmem_start;
	}
	/* take on all known port values */
	for (offset = 0; offset < LP_NO; offset++) {
		if (check_region(LP_B(offset), 3))
			continue;
		/* write to port & read back to check */
		outb_p( LP_DUMMY, LP_B(offset));
		for (testvalue = 0 ; testvalue < LP_DELAY ; testvalue++)
			;
		testvalue = inb_p(LP_B(offset));
		if (testvalue == LP_DUMMY) {
			LP_F(offset) |= LP_EXIST;
			lp_reset(offset);
			printk("lp%d at 0x%04x, ", offset,LP_B(offset));
			request_region(LP_B(offset), 3, "lp");
			if (LP_IRQ(offset))
				printk("using IRQ%d\n", LP_IRQ(offset));
			else
				printk("using polling driver\n");
			count++;
		}
	}
	if (count == 0)
		printk("lp_init: no lp devices found\n");
	return kmem_start;
}

#else

char kernel_version[]= UTS_RELEASE;

int init_module(void)
{
	int offset = 0;
	unsigned int testvalue = 0;
	int count = 0;

	if (register_chrdev(LP_MAJOR,"lp",&lp_fops)) {
		printk("unable to get major %d for line printer\n", LP_MAJOR);
		return -EIO;
	}
	/* take on all known port values */
	for (offset = 0; offset < LP_NO; offset++) {
		/* write to port & read back to check */
		outb_p( LP_DUMMY, LP_B(offset));
		for (testvalue = 0 ; testvalue < LP_DELAY ; testvalue++)
			;
		testvalue = inb_p(LP_B(offset));
		if (testvalue == LP_DUMMY) {
			LP_F(offset) |= LP_EXIST;
			lp_reset(offset);
			printk("lp%d at 0x%04x, ", offset,LP_B(offset));
			request_region(LP_B(offset),3,"lp");
			if (LP_IRQ(offset))
				printk("using IRQ%d\n", LP_IRQ(offset));
			else
				printk("using polling driver\n");
			count++;
		}
	}
	if (count == 0)
		printk("lp_init: no lp devices found\n");
	return 0;
}

void cleanup_module(void)
{
        int offset;
	if(MOD_IN_USE)
               printk("lp: busy - remove delayed\n");
        else
               unregister_chrdev(LP_MAJOR,"lp");
	       for (offset = 0; offset < LP_NO; offset++)
			if(LP_F(offset) && LP_EXIST)
		 		release_region(LP_B(offset),3);
}

#endif


text:
var chai = require('chai')

var expect = chai.expect

var awspricing = require('../../lib')

describe('AWS', function () {

  it('should return a JSON object when asked for aws on demand pricing.', function (done) {

    awspricing.requestOnDemandPricing(function (err, data) {
      expect(err).to.not.exist
      expect(data.vers).to.exist
      done()
    })
  })

  it('should return a JSON object when asked for aws data transfer pricing.', function (done) {

    awspricing.requestDataTransferPricing(function(err, data){
      expect(err).to.not.exist
      expect(data.vers).to.exist
      done()
    })

  })

  it('should return a JSON object when asked for aws elastic ips pricing.', function (done) {

    awspricing.requestElasticIpsPricing(function(err, data){
      expect(err).to.not.exist
      expect(data.vers).to.exist
      done()
    })

  })

  it('should return a JSON object when asked for aws elastic load balancer pricing.', function (done) {

    awspricing.requestElasticLoadBalancerPricing(function(err, data){
      expect(err).to.not.exist
      expect(data.vers).to.exist
      done()
    })

  })

})


text:
script_directory=`perl -e 'use File::Basename;
 use Cwd "abs_path";
 print dirname(abs_path(@ARGV[0]));' -- "$0"`
cd $script_directory

# However in order to give Docker access to all the code we have to
# move up a level
cd ..

# Ensure that postgres is running
if ! [[ $(docker ps --filter name=drdb -q) ]]; then
    echo "You must start Postgres first with:" >&2
    echo "./run_postgres.sh" >&2
    exit 1
fi

./prepare_image.sh -i common_tests -s common

source common.sh
DB_HOST_IP=$(get_docker_db_ip_address)
HOST_IP=$(get_ip_address)

docker run \
       --add-host=database:$DB_HOST_IP \
       --add-host=nomad:$HOST_IP \
       --env-file common/environments/test \
       --link drdb:postgres \
       -it ccdlstaging/dr_common_tests bash -c "$(run_tests_with_coverage $@)" --parallel


text:
<?php

declare(strict_types=1);

namespace Zhiyi\Plus\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        \Zhiyi\Plus\Models\FeedTopic::class => \Zhiyi\Plus\Policies\Feed\Topic::class,
        \Zhiyi\Component\ZhiyiPlus\PlusComponentNews\Models\News::class => \Zhiyi\Plus\Policies\NewsPostPolicy::class,
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();
    }
}


text:
"""Test protodict implementation.

An Dict is a generic dictionary implementation which has keys of type
string, and values of varying types. The Dict can be used to serialize
and transport arbitrary python dictionaries containing a limited set of value.

Dict objects behave generally like a dict (with __getitem__, items() and
an __iter__) method, but are serializable as an RDFProto.
"""

import collections

from grr.lib import rdfvalue
from grr.lib.rdfvalues import client as rdf_client
from grr.lib.rdfvalues import protodict as rdf_protodict
from grr.lib.rdfvalues import structs
from grr.lib.rdfvalues import test_base

class TestRDFValueArray(rdf_protodict.RDFValueArray):
  rdf_type = rdfvalue.RDFString

class DictTest(test_base.RDFProtoTestCase):
  """Test the Dict implementation."""

  rdfvalue_class = rdf_protodict.Dict

  def GenerateSample(self, number=0):
    return rdf_protodict.Dict(foo=number, bar="hello")

  def CheckRDFValue(self, value, sample):
    super(DictTest, self).CheckRDFValue(value, sample)

    self.assertEqual(value.ToDict(), sample.ToDict())

  def CheckTestDict(self, test_dict, sample):
    for k, v in test_dict.items():
      # Test access through getitem.
      self.assertEqual(sample[k], v)

  def testIsMapping(self):
    test_dict = rdf_protodict.Dict(a=1)
    self.assertTrue(isinstance(test_dict, collections.Mapping))

  def testDictBehaviour(self):
    tested = rdf_protodict.Dict(a=1)

    now = rdfvalue.RDFDatetime().Now()
    tested["b"] = now

    self.assertEqual(tested["b"], now)
    self.assertEqual(tested["a"], 1)

    tested["b"] = rdfvalue.RDFURN("aff4:/users/")
    self.assertEqual(len(tested), 2)
    self.assertEqual(tested["b"].SerializeToString(), "aff4:/users")

  def testSerialization(self):
    test_dict = dict(
        key1=1,                # Integer.
        key2="foo",            # String.
        key3=u"\u4f60\u597d",  # Unicode.
        key5=rdfvalue.RDFDatetime("2012/12/11"),  # RDFValue.
        key6=None,             # Support None Encoding.
        key7=structs.Enum(5, name="Test"),  # Integer like objects.
    )

    # Initialize through keywords.
    sample = rdf_protodict.Dict(**test_dict)
    self.CheckTestDict(test_dict, sample)

    # Initialize through dict.
    sample = rdf_protodict.Dict(test_dict)
    self.CheckTestDict(test_dict, sample)

    # Initialize through a serialized form.
    serialized = sample.SerializeToString()
    self.assertIsInstance(serialized, str)

    sample = rdf_protodict.Dict(serialized)
    self.CheckTestDict(test_dict, sample)

    # Convert to a dict.
    self.CheckTestDict(test_dict, sample.ToDict())

  def testNestedDicts(self):
    test_dict = dict(
        key1={"A": 1},
        key2=rdf_protodict.Dict({"A": 1}),
    )

    sample = rdf_protodict.Dict(**test_dict)
    self.CheckTestDict(test_dict, sample)
    self.CheckTestDict(test_dict, sample.ToDict())

  def testNestedDictsMultipleTypes(self):
    test_dict = dict(
        key1={"A": 1},
        key2=rdf_protodict.Dict({"A": 1}),
        key3=[1, 2, 3, [1, 2, [3]]],
        key4=[[], None, ["abc"]]
    )

    sample = rdf_protodict.Dict(**test_dict)
    self.CheckTestDict(test_dict, sample)
    self.CheckTestDict(test_dict, sample.ToDict())

  def testNestedDictsOpaqueTypes(self):

    class UnSerializable(object):
      pass

    test_dict = dict(
        key1={"A": 1},
        key2=rdf_protodict.Dict({"A": 1}),
        key3=[1, UnSerializable(), 3, [1, 2, [3]]],
        key4=[[], None, ["abc"]],
        key5=UnSerializable(),
        key6=["a", UnSerializable(), "b"]
    )

    self.assertRaises(TypeError, rdf_protodict.Dict, **test_dict)

    sample = rdf_protodict.Dict()
    for key, value in test_dict.iteritems():
      sample.SetItem(key, value, raise_on_error=False)

    # Need to do some manual checking here since this is a lossy conversion.
    self.assertEqual(test_dict["key1"], sample["key1"])
    self.assertEqual(test_dict["key2"], sample["key2"])

    self.assertEqual(1, sample["key3"][0])
    self.assertTrue("Unsupported type" in sample["key3"][1])
    self.assertItemsEqual(test_dict["key3"][2:], sample["key3"][2:])

    self.assertEqual(test_dict["key4"], sample["key4"])
    self.assertTrue("Unsupported type" in sample["key5"])
    self.assertEqual("a", sample["key6"][0])
    self.assertTrue("Unsupported type" in sample["key6"][1])
    self.assertEqual("b", sample["key6"][2])

  def testBool(self):
    sample = rdf_protodict.Dict(a=True)
    self.assertTrue(isinstance(sample["a"], bool))
    sample = rdf_protodict.Dict(a="true")
    self.assertEqual(sample["a"], "true")

  def testOverwriting(self):
    req = rdf_client.Iterator(client_state=rdf_protodict.Dict({"A": 1}))
    # There should be one element now.
    self.assertEqual(len(list(req.client_state.items())), 1)

    req.client_state = rdf_protodict.Dict({"B": 2})
    # Still one element.
    self.assertEqual(len(list(req.client_state.items())), 1)

    req.client_state = rdf_protodict.Dict({})

    # And now it's gone.
    self.assertEqual(len(list(req.client_state.items())), 0)

class AttributedDictTest(test_base.RDFValueTestCase):
  """Test AttributedDictFile operations."""

  rdfvalue_class = rdf_protodict.AttributedDict

  def GenerateSample(self, number=0):
    return rdf_protodict.AttributedDict({"number": number})

  def testInitialize(self):
    arnie = {"target": "Sarah Connor", "mission": "Protect"}
    t800 = {"target": "Sarah Connor", "mission": "Terminate"}
    terminator = rdf_protodict.AttributedDict(arnie)
    self.assertEquals(terminator.GetItem("target"), "Sarah Connor")
    self.assertEquals(terminator.GetItem("mission"), "Protect")
    terminator = rdf_protodict.AttributedDict(t800)
    self.assertEquals(terminator.target, "Sarah Connor")
    self.assertEquals(terminator.mission, "Terminate")
    # We don't want a conflicted Terminator
    self.assertFalse(terminator.GetItem("happy_face"))
    self.assertRaises(AttributeError, terminator.happy_face)

  def testAttributedDictSettingsAreAttr(self):
    t800 = {"target": "Sarah Connor", "mission": "Terminate"}
    terminator = rdf_protodict.AttributedDict(t800)
    self.assertEquals(terminator.target, "Sarah Connor")
    self.assertEquals(terminator.mission, "Terminate")

class RDFValueArrayTest(test_base.RDFProtoTestCase):
  """Test the Dict implementation."""

  rdfvalue_class = rdf_protodict.RDFValueArray

  def GenerateSample(self, number=0):
    return rdf_protodict.RDFValueArray([number])

  def testArray(self):
    sample = rdf_protodict.RDFValueArray()

    # Add a string.
    sample.Append("hello")
    self.assertEqual(len(sample), 1)
    self.assertEqual(sample[0], "hello")

    # Add another RDFValue
    sample.Append(rdfvalue.RDFString("hello"))
    self.assertIsInstance(sample[1], rdfvalue.RDFString)

    # Test iterator.
    sample_list = list(sample)
    self.assertIsInstance(sample_list, list)
    self.assertIsInstance(sample_list[0], str)
    self.assertIsInstance(sample_list[1], rdfvalue.RDFString)

    # Test initialization from a list of variable types.
    test_list = [1, 2,   # Integers.
                 None,   # None.
                 rdfvalue.RDFDatetime().Now(),  # An RDFValue instance.
                 [1, 2],  # A nested list.
                 u"升级程序",  # Unicode.
                ]
    sample = rdf_protodict.RDFValueArray(test_list)

    for x, y in zip(sample, test_list):
      self.assertEqual(x.__class__, y.__class__)
      self.assertEqual(x, y)

  def testEnforcedArray(self):
    """Check that arrays with a forced type are enforced."""
    sample = TestRDFValueArray()

    # Simple type should be coerced to an RDFString.
    sample.Append("hello")
    self.assertIsInstance(sample[0], rdfvalue.RDFString)

    # Reject appending invalid types.
    self.assertRaises(ValueError,
                      sample.Append, rdfvalue.RDFDatetime().Now())

  def testPop(self):
    sample = TestRDFValueArray()

    # Simple type should be coerced to an RDFString.
    sample.Append("hello")
    sample.Append("world")
    sample.Append("!")

    self.assertEqual(sample.Pop(), "hello")
    self.assertEqual(sample.Pop(1), "!")
    self.assertEqual(sample.Pop(), "world")

class EmbeddedRDFValueTest(test_base.RDFProtoTestCase):
  rdfvalue_class = rdf_protodict.EmbeddedRDFValue

  def GenerateSample(self, number=0):
    return rdf_protodict.EmbeddedRDFValue(rdf_protodict.RDFValueArray([number]))

  def testAgePreserved(self):
    data = rdf_protodict.RDFValueArray([1, 2, 3])
    now = rdfvalue.RDFDatetime().Now()
    original_age = data.age.Now()

    self.assertTrue((now - data.age) < rdfvalue.Duration("5s"))

    embedded = rdf_protodict.EmbeddedRDFValue(payload=data)
    self.assertEqual(embedded.payload.age, original_age)

    new_log = rdf_protodict.EmbeddedRDFValue(embedded).payload
    self.assertEqual(new_log.age, original_age, "Age not preserved: %s != %s" %
                     (new_log.age.AsMicroSecondsFromEpoch(),
                      original_age.AsMicroSecondsFromEpoch()))


text:
# [3.0.0](https://github.com/mbamobi/authentication/compare/v2.0.0...v3.0.0) (2017-04-07)

# [2.0.0](https://github.com/mbamobi/authentication/compare/v1.0.0...v2.0.0) (2017-04-06)

### Bug Fixes

* **module:** assign storage default ([2d8992a](https://github.com/mbamobi/authentication/commit/2d8992a))
* **module:** useClass null to adapter ([98caa55](https://github.com/mbamobi/authentication/commit/98caa55))

# [2.0.0](https://github.com/mbamobi/authentication/compare/v1.0.0...v2.0.0) (2017-04-06)

### Bug Fixes

* **module:** assign storage default ([2d8992a](https://github.com/mbamobi/authentication/commit/2d8992a))
* **module:** useClass null to adapter ([98caa55](https://github.com/mbamobi/authentication/commit/98caa55))

# 1.0.0 (2017-04-06)

### Bug Fixes

* **authentication:** typo ([6d315af](https://github.com/mbamobi/authentication/commit/6d315af))
* **authentication:** write dataExtra ([2e0d4d6](https://github.com/mbamobi/authentication/commit/2e0d4d6))
* **http.adapter:** adicionando retorno :any ao método buildParams, para permitir a sobrescrita ([a4853f2](https://github.com/mbamobi/authentication/commit/a4853f2))
* **httpAdapter:** merge requestOptions default ([57eaf33](https://github.com/mbamobi/authentication/commit/57eaf33))
* **httpAdapter:** result callback resolve and reject ([2268bc5](https://github.com/mbamobi/authentication/commit/2268bc5))
* **httpAdapter:** return to class with inheritance ([5859c77](https://github.com/mbamobi/authentication/commit/5859c77))
* **httpAdapter:** run promise result how callback ([1297354](https://github.com/mbamobi/authentication/commit/1297354))
* **httpAdapter:** send params GET and POST ([a2e0bb5](https://github.com/mbamobi/authentication/commit/a2e0bb5))
* **httpTwoLevelsAdapter:** failure promise ([1d0b96b](https://github.com/mbamobi/authentication/commit/1d0b96b))
* **httpTwoLevelsAdapter:** order setOptions ([c1b28de](https://github.com/mbamobi/authentication/commit/c1b28de))
* **httpTwoLevelsAdapter:** preRequestCallback interface ([5459196](https://github.com/mbamobi/authentication/commit/5459196))
* **httpTwoLevelsAdapter:** set id to option ([a7ccc72](https://github.com/mbamobi/authentication/commit/a7ccc72))
* **localstorage:** fix clear data ([731c7ea](https://github.com/mbamobi/authentication/commit/731c7ea))
* **localstorage:** fix compare emtpy null string ([6e343d1](https://github.com/mbamobi/authentication/commit/6e343d1))
* **module:** definitions providers ([441c30d](https://github.com/mbamobi/authentication/commit/441c30d))
* **module:** initialize modules with data type ([ac27db3](https://github.com/mbamobi/authentication/commit/ac27db3))
* **module:** initialize provider how useClass ([64ed6fe](https://github.com/mbamobi/authentication/commit/64ed6fe))

### Features

* **authentication:** implementation dataExtra to persist acessToken, refreshToken etc... ([8f76bab](https://github.com/mbamobi/authentication/commit/8f76bab))
* **httpAdapter:** add resolve how optional ([d186854](https://github.com/mbamobi/authentication/commit/d186854))
* **httpAdapter:** check if return callResult success and failure is promise ([03c9be3](https://github.com/mbamobi/authentication/commit/03c9be3))
* **httpAdapter:** implementation with timeout ([6d7391e](https://github.com/mbamobi/authentication/commit/6d7391e))
* **httpAdapter:** serialize params how UrlSearchParams ([40b2a5c](https://github.com/mbamobi/authentication/commit/40b2a5c))
* **httpAdapter:** set method with resolve.getMethod() ([2c10f51](https://github.com/mbamobi/authentication/commit/2c10f51))
* **httpAdapterTwoLevels:** add implementation initial ([73c2012](https://github.com/mbamobi/authentication/commit/73c2012))
* **httpAdapterTwoLevels:** implements set request options ([ffe9f57](https://github.com/mbamobi/authentication/commit/ffe9f57))
* **httpAdapterTwoLevels:** set method ([35ba339](https://github.com/mbamobi/authentication/commit/35ba339))
* **httpAdapterTwoLevsl:** add request options to http ([85e9ea0](https://github.com/mbamobi/authentication/commit/85e9ea0))
* **httpTwoLevelsAdapter:** add set headers ([5fa0e28](https://github.com/mbamobi/authentication/commit/5fa0e28))
* **httpTwoLevelsAdapter:** implements preRequestCallback to called of function before ([5d7bc30](https://github.com/mbamobi/authentication/commit/5d7bc30))
* **module:** add providers storage in modules ([c228b1a](https://github.com/mbamobi/authentication/commit/c228b1a))
* **module:** add structure module initial ([d819117](https://github.com/mbamobi/authentication/commit/d819117))
* **storage:** add namespace to storages ([1ed03bc](https://github.com/mbamobi/authentication/commit/1ed03bc))


text:
//
//  HomeModel.h
//  guodegangjingxuanji
//
//  Created by qianfeng on 15/9/6.
//  Copyright (c) 2015年 lyning. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface HomeModel : NSObject

@property (nonatomic, copy) NSString *uid;
@property (nonatomic, copy) NSString *nickname;
@property (nonatomic, copy) NSString *mediumLogo;
@property (nonatomic, copy) NSString *personDescribe;
@property (nonatomic, copy) NSString *albums;

/*
 "uid": 1000202,
 "nickname": "郭德纲相声",
 "mediumLogo": "http://fdfs.xmcdn.com/group1/M00/0B/3D/wKgDrlESHqyTqakZAADewk1yMt8360_mobile_large.jpg",
 "personDescribe": "都是"真事儿"啊,很"三俗"",
 "albums": 15
 */

@end


text:
import React from 'react';
import { shallow, mount, render } from 'enzyme';
import Foo from '../src/Foo';

describe("A suite", () => {
  it("contains foo", () => {
    assert(shallow(<Foo />).contains(<div className="foo" />));
  });

  it("contains .foo", () => {
    assert(shallow(<Foo />).is('.foo'));
  });

  it("contains .foo length 1", () => {
    assert(mount(<Foo />).find('.foo').length === 1);
  });
});


text:
/**
* @file DataLogger_HDF5.cpp
* @brief Implementation of the DataLogger_HDF5 class
* @author Ben Frazier
* @date 08/12/2017 */

#include "DataLogger_HDF5.h"

  /**
   * \brief Standard Constructor
   *
   */
  DataLoggerHDF5::DataLoggerHDF5():
  initialized_(false)
  {

  }

    /**
   * \brief Overloaded Constructor
   * @param fileName The file name to create
   */
  DataLoggerHDF5::DataLoggerHDF5(std::string fileName)
  {
 	CreateFile(fileName);
  }

      /**
   * \brief Create File
    * @param fileName The file name to create
   */
 void DataLoggerHDF5::CreateFile(std::string fileName)
    {
     file_ = H5File( fileName, H5F_ACC_TRUNC );
	 initialized_ = true;
	}


text:
#ifndef __M88K_ASM_H__
#define __M88K_ASM_H__

#ifdef __STDC__
#	define FUNC(NAME) _##NAME
#else
#	define FUNC(NAME) _/**/NAME
#endif

/* Define EH_DEBUG to be non-zero to compile-in various debugging things */
#ifndef	EH_DEBUG
#define EH_DEBUG 1
#endif	EH_DEBUG

#if 0
/* this gives the offsets into various structures of various elements, etc */
#include "assym.s"
#endif

#define	ENTRY(NAME) \
    .align 8; .globl FUNC(NAME); FUNC(NAME):

#define  LABEL(name)	 name:  .globl name ;
/*
 * _LABEL(name)
 *	Defines one visible only to the file, unless debugging
 * 	is enabled, in which case it's visible to the world (and
 *	hence to debuggers, and such).
 */
#if EH_DEBUG
#  define _LABEL(name)	name:	.globl name ;
#else
#  define _LABEL(name)	name:               ;
#endif

#define RTE	NOP ; rte

#define PID	cr0
#define PSR	cr1
#define EPSR	cr2
#define SSBR	cr3
#define SXIP	cr4
#define SNIP	cr5
#define SFIP	cr6
#define VBR	cr7
#define DMT0	cr8
#define DMD0	cr9
#define DMA0	cr10
#define DMT1	cr11
#define DMD1	cr12
#define DMA1	cr13
#define DMT2	cr14
#define DMD2	cr15
#define DMA2	cr16
#define SR0	cr17
#define SR1	cr18
#define SR2	cr19
#define SR3	cr20
#define FPECR	fcr0
#define FPHS1	fcr1
#define FPLS1	fcr2
#define FPHS2	fcr3
#define FPLS2	fcr4
#define FPPT	fcr5
#define FPRH	fcr6
#define FPRL	fcr7
#define FPIT	fcr8
#define FPSR	fcr62
#define FPCR	fcr63

/*
 * At various times, there is the need to clear the pipeline (i.e.
 * synchronize).  A "tb1 0, r0, foo" will do that (because a trap
 * instruction always synchronizes, and this particular instruction
 * will never actually take the trap).
 */
#if 0
#define FLUSH_PIPELINE	tcnd	ne0, r0, 0
#else
#define FLUSH_PIPELINE	tb1 0, r0, 0
#endif
#define NOP		or r0, r0, r0

/*
 * Useful in some situations.
 * NOTE: If ARG1 or ARG2 are r2 or r3, strange things may happen.  Watch out!
 */
#define CALL(NAME, ARG1, ARG2)             \
  		subu	r31, r31, 32	; \
                or      r2, r0, ARG1    ; \
                bsr.n   NAME            ; \
                or      r3, r0, ARG2	; \
		addu	r31, r31, 32

/*
 * SR1 - CPU FLAGS REGISTER
 * XXX clean this when the trap handler is reworked. Among the things
 * I like to see is having the trap frame on the kernel stack instead
 * of putting in the PCB. If done properly, we don't need SR1 for doing
 * anything special. nivas
 *
 * SR1 contains flags about the current CPU status.
 *
 * The bit FLAG_IGNORE_DATA_EXCEPTION indicates that any data exceptions
 * 	should be ignored (well, at least treated in a special way).
 * The bit FLAG_INTERRUPT_EXCEPTION indicates that the current exception
 * 	is the interrupt exception.  Such information can be gotten
 * 	in other ways, but having it in the flags makes it easy for the
 *	exception handler to check quickly.
 * The bit FLAG_ENABLING_FPU indicates that the exception handler is
 * 	in the process of enabling the FPU (so that an exception can
 * 	be serviced).  This is needed because enabling the FPU can
 *	cause other exceptions to happen, and the whole system is
 *	in a rather precarious state and so special cautions must
 * 	be taken.
 */
#define FLAG_CPU_FIELD_WIDTH		4	/* must be <= 12 */

#define FLAG_IGNORE_DATA_EXCEPTION	5	/* bit number 5 */
#define FLAG_INTERRUPT_EXCEPTION	6	/* bit number 6 */
#define FLAG_ENABLING_FPU		7	/* bit number 7 */

/* REGister OFFset into the E.F. (exception frame) */
#define REG_OFF(reg_num)  ((reg_num) * 4) /* (num * sizeof(register int))  */
#define GENREG_OFF(num)	(REG_OFF(EF_R0 + (num))) /* GENeral REGister OFFset */

#define GENERAL_BREATHING_ROOM	/* arbitrarily */ 200
#define KERNEL_STACK_BREATHING_ROOM 	\
	(GENERAL_BREATHING_ROOM + SIZEOF_STRUCT_PCB + SIZEOF_STRUCT_UTHREAD)

/*
 * Some registers used during the setting up of the new exception frame.
 * Don't choose r1, r30, or r31 for any of them.
 *
 * Also, if any are 'r2' or 'r3', be careful using with CALL above!
 */
#define FLAGS	r2
#define TMP	r3
#define TMP2	r10
#define TMP3	r11
#define SAVE_TMP2	st	r10, r31, GENREG_OFF(10)
#define SAVE_TMP3	st	r11, r31, GENREG_OFF(11)
#define RESTORE_TMP2	ld	r10, r31, GENREG_OFF(10)
#define RESTORE_TMP3	ld	r11, r31, GENREG_OFF(11)

/*
 * Info about the PSR
 */
#define PSR_SHADOW_FREEZE_BIT		 0
#define PSR_INTERRUPT_DISABLE_BIT	 1
#define PSR_FPU_DISABLE_BIT		 3
#define PSR_BIG_ENDIAN_MODE		30
#define PSR_SUPERVISOR_MODE_BIT		31

/*
 * Status bits for an SXIP/SNIP/SFIP address.
 */
#define RTE_VALID_BIT	 1
#define RTE_ERROR_BIT	 0

/*
 * Info about DMT0/DMT1/DMT2
 */
#define DMT_VALID_BIT	 0
#define DMT_WRITE_BIT 	 1
#define DMT_LOCK_BIT	12
#define DMT_DOUBLE_BIT	13
#define DMT_DAS_BIT     14
#define DMT_DREG_OFFSET	 7
#define DMT_DREG_WIDTH	 5

/*
 * Bits for eh_debug.
 */
#define DEBUG_INTERRUPT_BIT		 0
#define DEBUG_DATA_BIT			 1
#define DEBUG_INSTRUCTION_BIT		 2
#define DEBUG_MISALIGN_BIT		 3
#define DEBUG_UNIMP_BIT			 4
#define DEBUG_DIVIDE_BIT		 5
#define DEBUG_OF_BIT			 6
#define DEBUG_FPp_BIT			 7
#define DEBUG_FPi_BIT			 8
#define DEBUG_SYSCALL_BIT	 	 9
#define DEBUG_MACHSYSCALL_BIT		10
#define DEBUG_UNIMPLEMENTED_BIT		11
#define DEBUG_PRIVILEGE_BIT		12
#define DEBUG_BOUNDS_BIT		13
#define DEBUG_OVERFLOW_BIT		14
#define DEBUG_ERROR_BIT			15
#define DEBUG_SIGSYS_BIT		16
#define DEBUG_SIGTRAP_BIT		17
#define DEBUG_BREAK_BIT			18
#define DEBUG_TRACE_BIT			19
#define DEBUG_KDB_BIT			20
#define DEBUG_JKDB_BIT			21
#define DEBUG_BUGCALL_BIT		22

#define DEBUG_UNKNOWN_BIT		31

/*
 * These things for vector_init.c and locore.c
 */
#if defined(ASSEMBLER)
# define  PREDEFINED_BY_ROM       0xffffffff
# define  END_OF_VECTOR_LIST      0xfffffffe
#else
# define  PREDEFINED_BY_ROM       0xffffffffU
# define  END_OF_VECTOR_LIST      0xfffffffeU
#endif

/*
 * Define ERROR__XXX_USR if the xxx.usr bug (mask C82N) is present.
 * This implements the workaround.
 */
#define ERRATA__XXX_USR 	1

#if !defined(CMMU_I)
#define CMMU_I	0xFFF77000
#endif
#if !defined(CMMU_D)
#define CMMU_D	0xFFF7F000
#endif

#endif /* __M88K_ASM_H__ */


text: require('./stripe');


text:
/************************************/
/*            BASE STYLING          */
/************************************/

/* Welcome to the inner sanctum.
   Nothing goes here that is site-specific.
   Seriously.
*/

/* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, masthead, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}
/* end meyer reset */

/* Bold/Strong should be bold and strong! */
b,
strong {
    font-weight: bold;
}

/* Give abbr and acronym dotted underline. */
abbr,
acronym {
    border-bottom: 1px dotted;
}

/* >> The Magnificent CLEARFIX <<
   Lifted from html5boilerplate.com
   License is Public domain */
.c:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; }
.c { display: inline-block; }
* html .c { height: 1%; } /* Hides from IE-mac \*/
.c { display: block; }


text:
import test from 'ava';
import m from '.';

test('get brightness', async t => {
	const brightness = await m.get();
	t.is(typeof brightness, 'number');
});

test('set brightness', async t => {
	await m.set(0.5);
	const brightness = await m.get();
	t.is(Math.round(brightness * 10) / 10, 0.5);
});


text:
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ArkSavegameToolkitNet.Data
{
    public class ExtraDataZeroHandler : IExtraDataHandler
    {
        private static ILog _logger = LogManager.GetLogger(typeof(ExtraDataZeroHandler));
        private static readonly ExtraDataZero INSTANCE = new ExtraDataZero();

        public bool CanHandle(GameObject obj, long length)
        {
            return length == 4;
        }

        public IExtraData Read(GameObject obj, ArkArchive archive, long length)
        {
            var shouldBeZero = archive.GetInt();
            if (shouldBeZero != 0) _logger.Warn($"Expected int after properties to be 0 but found {shouldBeZero} at {archive.Position - 4:X}");

            return INSTANCE;
        }
    }
}


text:
'use strict'

angular.module('myApp.twitter', [])

.controller('TwitterListCtrl', function($scope, Twitters) {
	$scope.tweet = "This is the string";
})


text:
<?php

/**
 * @file
 * Contains \Drupal\views\Tests\ViewsHooksTest.
 */

namespace Drupal\views\Tests;

use Drupal\Core\Render\RenderContext;
use Drupal\views\Views;

/**
 * Tests that views hooks are registered when defined in $module.views.inc.
 *
 * @group views
 * @see views_hook_info().
 * @see field_hook_info().
 */
class ViewsHooksTest extends ViewKernelTestBase {

  /**
   * Views used by this test.
   *
   * @var array
   */
  public static $testViews = array('test_view');

  /**
   * An array of available views hooks to test.
   *
   * @var array
   */
  protected static $hooks = array (
    'views_data' => 'all',
    'views_data_alter' => 'alter',
    'views_query_substitutions' => 'view',
    'views_form_substitutions' => 'view',
    'views_analyze' => 'view',
    'views_pre_view' => 'view',
    'views_pre_build' => 'view',
    'views_post_build' => 'view',
    'views_pre_execute' => 'view',
    'views_post_execute' => 'view',
    'views_pre_render' => 'view',
    'views_post_render' => 'view',
    'views_query_alter'  => 'view',
    'views_invalidate_cache' => 'all',
  );

  /**
   * The module handler to use for invoking hooks.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  protected function setUp() {
    parent::setUp();

    $this->moduleHandler = $this->container->get('module_handler');
  }

  /**
   * Tests the hooks.
   */
  public function testHooks() {
    $view = Views::getView('test_view');
    $view->setDisplay();

    // Test each hook is found in the implementations array and is invoked.
    foreach (static::$hooks as $hook => $type) {
      $this->assertTrue($this->moduleHandler->implementsHook('views_test_data', $hook), format_string('The hook @hook was registered.', array('@hook' => $hook)));

      if ($hook == 'views_post_render') {
        $this->moduleHandler->invoke('views_test_data', $hook, array($view, &$view->display_handler->output, $view->display_handler->getPlugin('cache')));
        continue;
      }

      switch ($type) {
        case 'view':
          $this->moduleHandler->invoke('views_test_data', $hook, array($view));
          break;

        case 'alter':
          $data = array();
          $this->moduleHandler->invoke('views_test_data', $hook, array($data));
          break;

        default:
          $this->moduleHandler->invoke('views_test_data', $hook);
      }

      $this->assertTrue($this->container->get('state')->get('views_hook_test_' . $hook), format_string('The %hook hook was invoked.', array('%hook' => $hook)));
      // Reset the module implementations cache, so we ensure that the
      // .views.inc file is loaded actively.
      $this->moduleHandler->resetImplementations();
    }
  }

  /**
   * Tests how hook_views_form_substitutions() makes substitutions.
   *
   * @see views_test_data_views_form_substitutions()
   * @see views_pre_render_views_form_views_form()
   */
  public function testViewsPreRenderViewsFormViewsForm() {
    $element = [
      'output' => [
        '#plain_text' => '',
      ],
      '#substitutions' => ['#value' => []],
    ];
    $element = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function() use ($element) {
      return views_pre_render_views_form_views_form($element);
    });
    $this->setRawContent((string) $element['output']['#markup']);
    $this->assertEscaped('escaped');
    $this->assertRaw('unescaped');
  }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sydowia 16: 304 (1963)

#### Original name
Meliola petiveriae Hansf.

### Remarks
null


text:
<?php
namespace ATWS\AutotaskObjects;

class TimeEntry extends Entity
{
    // Required
    public $DateWorked;
    public $ResourceID;
    public $RoleID;
    public $Type;

    // Optional
    public $AllocationCodeID;
    public $BillingApprovalDateTime;
    public $BillingApprovalLevelMostRecent;
    public $BillingApprovalResourceID;
    public $ContractID;
    public $ContractServiceBundleID;
    public $ContractServiceID;
    public $CreateDateTime;
    public $CreatorUserID;
    public $EndDateTime;
    public $HoursToBill;
    public $HoursWorked;
    public $ImpersonatorCreatorResourceID;
    public $ImpersonatorUpdaterResourceID;
    public $InternalAllocationCodeID;
    public $InternalNotes;
    public $LastModifiedDateTime;
    public $LastModifiedUserID;
    public $NonBillable;
    public $OffsetHours;
    public $ShowOnInvoice;
    public $StartDateTime;
    public $SummaryNotes;
    public $TaskID;
    public $TicketID;
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Cryptog. Mycol. 5(1): 58 (1984)

#### Original name
Agaricus tricolor Bull., 1791

### Remarks
null


text:
<?php include_once('Common/PhpCommonConstants.php'); ?>
<?php include_once('Common/Constants.php'); ?>
<?php include_once('Common/GetTimestamp.php'); ?>
<?php if($NoSQL['DEBUG']) include_once('Common/DebugArray.php'); ?>
<?php if($NoSQL['DEBUG']) include_once('Common/EchoDebug.php'); ?>
<?php include_once('Common/GetCFS.php'); ?>
<?php include_once('Common/CheckCFS.php'); ?>
<?php include_once('Search/SearchIndex/AddSearchIndex/AddSearchIndexCheckParams.php'); ?>
<?php include_once('Search/SearchIndex/AddSearchIndex/AddSearchIndexDealWith.php'); ?>
<?php include_once('Search/SearchIndex/SerializeKeySearchIndex.php'); ?>
<?php include_once('Search/SearchIndex/SerializeColumnNameSearchIndex.php'); ?>
<?php include_once('Search/SearchIndex/SerializeColumnValueSearchIndex.php'); ?>
<?php include_once('Common/SetData.php'); ?>
<?php /* include_once('Common/GetData.php'); */ ?>
<?php /* include_once('Common/MultiGetData.php'); */ ?>
<?php /* include_once('Common/GetIndexedData.php'); */ ?>
<?php /* include_once('Common/RemoveData.php'); */ ?>
<?php ?>
<?php
///////////
/// # MEMO
/// 增加到 search_index
///
/// #### GENERAL REQUIRE
/// 1. params['key_id']/(表示 key 的 id (請參考 dynamic::search_index))
/// 2. 除非有在 dynamic::search_index 特別說明. 否則 column_name/column_value 裡的 structure 都需要設定.
/// 2.1. (column_name_id_format 在 api-1 會自動設定. the_timestamp/info 是 optional)
/// 3. 如果 2 沒有辦法提供的話. 可以直接提供 column_name_id/column_value_id
///
/// # DO
/// 1. 如果有設定 cols 的話:
/// 1.1. 設定 key_id.
/// 1. else
/// 1.1. 設定 the_timestamp
/// 1.2. 檢查 params 是 ok 的. (CheckParams)
/// 1.3. 設定 info
/// 1.4. serialize key/column_name/column_value
/// 2. 設定 CF.
/// 3. 設定 cols. 並且實際對 cassandra SetData
/// 4. 增加時要做的其他事情. (DealWith)
///////////
function AddSearchIndex(&$params, $ttl = null, $is_check_params = true, $is_deal_with = true) {
  global $NoSQL;
  $DEBUG_FILENAME = "#" . __FILE__ . "@" . __FUNCTION__;

  $result = array("error" => 0);
  $function_name = "ADD";

  if(isset($params['session']) && !isset($NoSQL['SESSION'])) $NoSQL['SESSION'] = $params['session'];

  $key_id = null;
  if(isset($params['cols'])) {
    if(isset($params['key_id'])) $key_id = $params['key_id']; else $key_id = SerializeKeySearchIndex($params);
    $params['key_id'] = $key_id;
  }
  else {
    if(!isset($params['the_timestamp'])) $params['the_timestamp'] = GetTimestamp();

    //1.2
    if($is_check_params && $result_check_params = AddSearchIndexCheckParams($params, $result)) {
      $result['error'] = ErrorCode('SEARCH_INDEX', $function_name, 'API1_CHECK_PARAMS', $result_check_params);
      return $result;
    }

    if(!isset($params['info'])) $params['info'] = $NoSQL['LEFT_BRACKET'] . $NoSQL['RIGHT_BRACKET'];

    //1.4.
    if(isset($params['key_id'])) $key_id = $params['key_id']; else $key_id = SerializeKeySearchIndex($params);
    $params['key_id'] = $key_id;

    if(!isset($params['cols'])) {
      if(isset($params['column_name_id'])) $column_name_id = $params['column_name_id']; else $column_name_id = SerializeColumnNameSearchIndex($params);
      $params['column_name_id'] = $column_name_id;
      $params['column_name_id_format'] = FormatKeyString($params['column_name_id']);
      if(isset($params['column_value_id'])) $column_value_id = $params['column_value_id']; else $column_value_id = SerializeColumnValueSearchIndex($params);
      $params['column_value_id'] = $column_value_id;
    }
  }

  //2.
  $cf_search_index = GetCFS('search_index', $params);
  if(CheckCFS(array($cf_search_index))) {
    $result['error'] = ErrorCode('SEARCH_INDEX', $function_name, 'CFS');
    return $result;
  }

  //3.
  if(isset($params['cols'])) $cols =& $params['cols'];
  else $cols[$column_name_id] = $column_value_id;
  if(SetData($cf_search_index, $key_id, $cols)) { //設定 search_index1 錯誤.
    $result['error'] = ErrorCode('SEARCH_INDEX', $function_name, 'CF1');
    return $result;
  }

  if(isset($params['cols'])) {
    $column_name_ids = array_keys($params['cols']);

    $column_name_ids_format = array();
    foreach($column_name_ids as $each_column_name_id) {
      $each_column_name_id_format = FormatKeyString($each_column_name_id);
      $column_name_ids_format[$each_column_name_id_format] = $each_column_name_id_format;
    }
    $result['column_name_id_format'] = $column_name_ids_format;
    $result['column_name_id'] = $column_name_ids;
  }
  else {
    $result['column_name_id_format'] = FormatKeyString($params['column_name_id']);
    $result['column_name_id'] = $params['column_name_id'];
  }

  //4.
  if($is_deal_with && $result_deal_with = AddSearchIndexDealWith($key_id, $params, $result)) {
    $result['error'] = ErrorCode('SEARCH_INDEX', $function_name, 'API1_DEAL_WITH', $result_deal_with);
    return $result;
  }

  /**********
   * return
   */
  return $result;
}
?>


text:
def getconf(var)
  cmd = Mixlib::ShellOut.new("getconf #{var}").run_command
  cmd.error!
  cmd.stdout.split("\n")[-1]
end

if node['postgresql']['version'].to_f <= 9.3 &&
   # sysctl: setting key "kernel.shmmax": Read-only file system
   !::File.exist?('/.dockerinit')

  page_size = getconf('PAGE_SIZE').to_i
  phys_pages = getconf('_PHYS_PAGES').to_i

  shmall = phys_pages / 2
  shmmax = shmall * page_size

  execute 'sysctl -p /etc/sysctl.d/postgresql.conf' do
    action :nothing
  end

  template '/etc/sysctl.d/postgresql.conf' do
    source 'sysctl.conf.erb'
    variables(
      values: {
        'kernel.shmall' => shmall,
        'kernel.shmmax' => shmmax
      }
    )
    only_if { ::File.exist?('/etc/sysctl.d') }
    notifies :run, 'execute[sysctl -p /etc/sysctl.d/postgresql.conf]',
             :immediately
  end
end


text:
require File.expand_path('../boot', __FILE__)

require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"

Bundler.require(*Rails.groups(assets: %w(development test))) if defined?(Bundler)

module S3Upload
  class Application < Rails::Application
    # Custom directories with classes and modules you want to be autoloadable.
    # config.autoload_paths += %W(#{config.root}/extras)

    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
    # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
    config.time_zone = 'Central Time (US & Canada)'

    # Configure the default encoding used in templates for Ruby 1.9.
    config.encoding = "utf-8"

    # Configure sensitive parameters which will be filtered from the log file.
    config.filter_parameters += [:password]

    # Enable the asset pipeline
    config.assets.enabled = true

    # Version of your assets, change this if you want to expire all your assets
    config.assets.version = '1.0'

    config.generators do |g|
      g.orm                 :mongoid
      g.test_framework      :rspec, fixture: true
      g.fixture_replacement :fabrication
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace StockRequestRERWeb.Models
{
	public class StockRequestItem
	{
		public string Title { get; set; }
		public int Amount { get; set; }
		public int TotalPrice { get; set; }
		public string MaterialType { get; set; }
		public int EditedID { get; set; }
	}
}


text:
cs4243-project
==============

### Installation

The project is made as a web application based on flask, a Python web framework.
Firstly, install flask if it is not already installed:
```
pip install flask
```

To run the flask application, navigate to the root directory and do:
```
python server.py
```
The app will be running on `http://localhost:8080/`.

### Using the Application

We have used two images for demonstration of our application:

##### 1. Carnegie Mellon University
Navigate to `http://localhost:8080/#cmu`.

##### 2. Stanford
Navigate to `http://localhost:8080/#stanford`.

Click on the **Plan View** tab and click within the red boundary rectangles to specify points of the bezier curve.
Once more than 4 points are specified, the **Render Video** button will be enabled. Click on it to generate a video based on the path you have specified. After the video is fully generated, it will be shown in a window.

The generated videos will be inside `app/static/video/`.

### Team Members
- Le Minh Tu
- Tay Yang Shun
- Nguyen Trung Hieu
- Tay Xiu Li


text:
using System.Collections.Concurrent;
using StreamingServer.CityIndexLightstreamerClient.Models;
using StreamingServer.Core.Handlers.Interfaces;
using StreamingServer.LightstreamerClient.EventArguments;
using StreamingServer.LightstreamerClient.Interfaces;

#endregion

namespace StreamingServer.Core.Handlers
{
	public class PriceEventHandler : IStreamingEventHandler<PriceDTO>
	{
		public ConcurrentQueue<string> Queue { get; set; }
		public IStreamingListener Listener { get; set; }

		public PriceEventHandler(IStreamingListener<PriceDTO> listener)
		{
			Listener = listener;
			listener.MessageReceived += OnMessageReceived;

			Queue = new ConcurrentQueue<string>();
		}

		public void OnMessageReceived(object sender, MessageEventArgs<PriceDTO> e)
		{
			Queue.Enqueue(e.Data.ToString());
		}

		public void Dispose()
		{
			var l = (IStreamingListener<PriceDTO>)Listener;
			l.MessageReceived -= OnMessageReceived;

			string ignored;
			while (Queue.TryDequeue(out ignored))
			{
			}
		}
	}
}


text:
/* Provide support for both ANSI and non-ANSI environments.  */

/* Some ANSI environments are "broken" in the sense that __STDC__ cannot be
   relied upon to have it's intended meaning.  Therefore we must use our own
   concoction: _HAVE_STDC.  Always use _HAVE_STDC instead of __STDC__ in newlib
   sources!

   To get a strict ANSI C environment, define macro _STRICT_ANSI.  This will
   "comment out" the non-ANSI parts of the ANSI header files (non-ANSI header
   files aren't affected).  */

#ifndef	_ANSIDECL_H_
#define	_ANSIDECL_H_

#include <sys/config.h>

/* First try to figure out whether we really are in an ANSI C environment.  */
/* FIXME: This probably needs some work.  Perhaps sys/config.h can be
   prevailed upon to give us a clue.  */

#if __STDC__ == 1
#define _HAVE_STDC
#endif

#ifdef _HAVE_STDC
#define	_PTR		void *
#define	_AND		,
#define	_NOARGS		void
#define	_CONST		const
#define	_VOLATILE	volatile
#define	_SIGNED		signed
#define	_DOTS		, ...
#define _VOID void
#define	_EXFUN(name, proto)		name proto
#define	_DEFUN(name, arglist, args)	name(args)
#define	_DEFUN_VOID(name)		name(_NOARGS)
#define _CAST_VOID (void)
#ifndef _LONG_DOUBLE
#define _LONG_DOUBLE long double
#endif
#ifndef _PARAMS
#define _PARAMS(paramlist)		paramlist
#endif
#else
#define	_PTR		char *
#define	_AND		;
#define	_NOARGS
#define	_CONST
#define	_VOLATILE
#define	_SIGNED
#define	_DOTS
#define _VOID void
#define	_EXFUN(name, proto)		name()
#define	_DEFUN(name, arglist, args)	name arglist args;
#define	_DEFUN_VOID(name)		name()
#define _CAST_VOID
#define _LONG_DOUBLE double
#ifndef _PARAMS
#define _PARAMS(paramlist)		()
#endif
#endif

/* Support gcc's __attribute__ facility.  */

#ifdef __GNUC__
#define _ATTRIBUTE(attrs) __attribute__ (attrs)
#else
#define _ATTRIBUTE(attrs)
#endif

#endif /* _ANSIDECL_H_ */


text:
import React, { memo, useState } from 'react';
import { useIntl } from 'react-intl';
import get from 'lodash/get';
import isEqual from 'react-fast-compare';
import { Button } from '@strapi/design-system/Button';
import Trash from '@strapi/icons/Trash';
import { ConfirmDialog, useNotification } from '@strapi/helper-plugin';
import PropTypes from 'prop-types';
import { getTrad } from '../../../utils';
import { connect, select } from './utils';

const DeleteLink = ({ isCreatingEntry, onDelete, onDeleteSucceeded, trackerProperty }) => {
  const [showWarningDelete, setWarningDelete] = useState(false);
  const [isModalConfirmButtonLoading, setIsModalConfirmButtonLoading] = useState(false);
  const { formatMessage } = useIntl();
  const toggleNotification = useNotification();

  const toggleWarningDelete = () => setWarningDelete(prevState => !prevState);

  const handleConfirmDelete = async () => {
    try {
      // Show the loading state
      setIsModalConfirmButtonLoading(true);

      await onDelete(trackerProperty);

      setIsModalConfirmButtonLoading(false);

      toggleWarningDelete();
      onDeleteSucceeded();
    } catch (err) {
      const errorMessage = get(
        err,
        'response.payload.message',
        formatMessage({ id: getTrad('error.record.delete') })
      );
      setIsModalConfirmButtonLoading(false);
      toggleWarningDelete();
      toggleNotification({ type: 'warning', message: errorMessage });
    }
  };

  if (isCreatingEntry) {
    return null;
  }

  return (
    <>
      <Button onClick={toggleWarningDelete} size="S" startIcon={<Trash />} variant="danger-light">
        {formatMessage({
          id: getTrad('containers.Edit.delete-entry'),
          defaultMessage: 'Delete this entry',
        })}
      </Button>
      <ConfirmDialog
        isConfirmButtonLoading={isModalConfirmButtonLoading}
        isOpen={showWarningDelete}
        onConfirm={handleConfirmDelete}
        onToggleDialog={toggleWarningDelete}
      />
    </>
  );
};

DeleteLink.propTypes = {
  isCreatingEntry: PropTypes.bool.isRequired,
  onDelete: PropTypes.func.isRequired,
  onDeleteSucceeded: PropTypes.func.isRequired,
  trackerProperty: PropTypes.object.isRequired,
};

const Memoized = memo(DeleteLink, isEqual);

export default connect(Memoized, select);


text:
#pragma once

#include <base/structureddataname.h>
#include <memory>
#include <string>
#include <vector>

namespace aft {
namespace base {
// Forward reference
class StructuredData;
class StructuredDataName;
}

namespace ui
{

/**
 *  Category of UIFacet. Note that facets are organized by category and name/value.
 */
enum class UIFacetCategory {
    START,
    Unknown = START,
    Border,
    Color,
    Decoration,
    Dimension,
    Input,
    Output,
    Other,
    Theme,
    Widget,
    // add new categories above this line
    LAST,
    SIZE = LAST - START
};

/**
 *  UIFacet's modify the look and feel, behavior, size, position or other attributes of UI elements.
 *  Most facets are optional but can be made mandatory.
 */
class UIFacet {
public:
    /** Default constructor for use by STL containers. */
    UIFacet();
    /** Construct a UIFacet with name, value and category.
     *
     *  UIFacet hold many name/value pairs under multiple categories.
     *  @param name Name of this facet, which should be unique within each category.
     *  @param value Initial string value of facet. This may be parsed and converted by subclasses.
     *  @param category Category of facet. Set to UIFacetCategory::Other if not specified.
     */
    UIFacet(const std::string& name, const std::string& value,
            UIFacetCategory category = UIFacetCategory::Other);
    /** Copy constructor. */
    UIFacet(const UIFacet& other);
    virtual ~UIFacet();

    UIFacet& operator=(const UIFacet& other);

    //TODO, along with category?  bool isInitialized() const;
    bool getMandatory() const;
    void setMandatory(bool isMandatory);

    virtual bool get(const std::string& name, std::string& value,
                     UIFacetCategory category = UIFacetCategory::Other) const;
    virtual bool get(const std::string& name, int& value,
                     UIFacetCategory category = UIFacetCategory::Other) const;
    virtual bool get(const std::string& name, float& value,
                     UIFacetCategory category = UIFacetCategory::Other) const;
    virtual bool set(const std::string& name, const std::string& value,
                     UIFacetCategory category = UIFacetCategory::Other);
    virtual bool set(const std::string& name, int value,
                     UIFacetCategory category = UIFacetCategory::Other);
    virtual bool set(const std::string& name, float value,
                     UIFacetCategory category = UIFacetCategory::Other);

    virtual bool remove(const std::string& name, UIFacetCategory category = UIFacetCategory::Other);

    std::vector<UIFacetCategory> getCategories() const;
    std::vector<std::string> getNames(UIFacetCategory category) const;

public:
    static UIFacetCategory getCategory(const std::string& catName);
    static const std::string& getCategoryName(UIFacetCategory category);

protected:
    static base::StructuredDataName makeKeyName(UIFacetCategory category, const std::string& name);

    /** Used by subclasses of UIFacet to get named values. */
    bool getFacetValue(const std::string& name, std::string& value);
    /** Used by subclasses of UIFacet to set named values. */
    void setFacetValue(const std::string& name, const std::string& value);

private:
    std::unique_ptr<base::StructuredData> data_;
    bool isMandatory_;
};

} // namespace ui
} // namespace aft


text:
docker-play
===========

Docker Play framework image


text:
package com.opengamma.analytics.financial.interestrate.payments.provider;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.opengamma.analytics.financial.interestrate.payments.derivative.CouponIborGearing;
import com.opengamma.analytics.financial.provider.description.interestrate.MulticurveProviderInterface;
import com.opengamma.analytics.financial.provider.sensitivity.multicurve.ForwardSensitivity;
import com.opengamma.analytics.financial.provider.sensitivity.multicurve.MulticurveSensitivity;
import com.opengamma.analytics.financial.provider.sensitivity.multicurve.MultipleCurrencyMulticurveSensitivity;
import com.opengamma.analytics.financial.provider.sensitivity.multicurve.SimplyCompoundedForwardSensitivity;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.money.MultipleCurrencyAmount;
import com.opengamma.util.tuple.DoublesPair;

/**
 * Method to compute present value and present value sensitivity for Ibor coupon with gearing factor and spread.
 */
public final class CouponIborGearingDiscountingMethod {

  /**
   * The method unique instance.
   */
  private static final CouponIborGearingDiscountingMethod INSTANCE = new CouponIborGearingDiscountingMethod();

  /**
   * Return the unique instance of the class.
   *
   * @return The instance.
   */
  public static CouponIborGearingDiscountingMethod getInstance() {
    return INSTANCE;
  }

  /**
   * Private constructor.
   */
  private CouponIborGearingDiscountingMethod() {
  }

  /**
   * Compute the present value of a Ibor coupon with gearing factor and spread by discounting.
   *
   * @param coupon
   *          The coupon.
   * @param multicurves
   *          The multi-curve provider.
   * @return The present value.
   */
  public MultipleCurrencyAmount presentValue(final CouponIborGearing coupon, final MulticurveProviderInterface multicurves) {
    ArgumentChecker.notNull(coupon, "Coupon");
    ArgumentChecker.notNull(multicurves, "Multi-curves");
    final double forward = multicurves.getSimplyCompoundForwardRate(coupon.getIndex(), coupon.getFixingPeriodStartTime(), coupon.getFixingPeriodEndTime(),
        coupon.getFixingAccrualFactor());
    final double df = multicurves.getDiscountFactor(coupon.getCurrency(), coupon.getPaymentTime());
    final double value = (coupon.getNotional() * coupon.getPaymentYearFraction() * (coupon.getFactor() * forward) + coupon.getSpreadAmount()) * df;
    return MultipleCurrencyAmount.of(coupon.getCurrency(), value);
  }

  /**
   * Compute the present value sensitivity to rates of a Ibor coupon with gearing and spread by discounting.
   *
   * @param coupon
   *          The coupon.
   * @param multicurves
   *          The multi-curve provider.
   * @return The present value sensitivity.
   */
  public MultipleCurrencyMulticurveSensitivity presentValueCurveSensitivity(final CouponIborGearing coupon, final MulticurveProviderInterface multicurves) {
    ArgumentChecker.notNull(coupon, "Coupon");
    ArgumentChecker.notNull(multicurves, "Curves");
    final double forward = multicurves.getSimplyCompoundForwardRate(coupon.getIndex(), coupon.getFixingPeriodStartTime(), coupon.getFixingPeriodEndTime(),
        coupon.getFixingAccrualFactor());
    final double df = multicurves.getDiscountFactor(coupon.getCurrency(), coupon.getPaymentTime());
    // Backward sweep
    final double pvBar = 1.0;
    final double forwardBar = coupon.getNotional() * coupon.getPaymentYearFraction() * coupon.getFactor() * df * pvBar;
    final double dfBar = (coupon.getNotional() * coupon.getPaymentYearFraction() * (coupon.getFactor() * forward) + coupon.getSpreadAmount()) * pvBar;
    final Map<String, List<DoublesPair>> mapDsc = new HashMap<>();
    final List<DoublesPair> listDiscounting = new ArrayList<>();
    listDiscounting.add(DoublesPair.of(coupon.getPaymentTime(), -coupon.getPaymentTime() * df * dfBar));
    mapDsc.put(multicurves.getName(coupon.getCurrency()), listDiscounting);
    final Map<String, List<ForwardSensitivity>> mapFwd = new HashMap<>();
    final List<ForwardSensitivity> listForward = new ArrayList<>();
    listForward.add(new SimplyCompoundedForwardSensitivity(coupon.getFixingPeriodStartTime(), coupon.getFixingPeriodEndTime(), coupon.getFixingAccrualFactor(),
        forwardBar));
    mapFwd.put(multicurves.getName(coupon.getIndex()), listForward);
    final MultipleCurrencyMulticurveSensitivity result = MultipleCurrencyMulticurveSensitivity.of(coupon.getCurrency(),
        MulticurveSensitivity.of(mapDsc, mapFwd));
    return result;
  }

}