text:
"""
    synaptiks.monitors.keyboard
    ===========================

    Implementation of keyboard monitoring.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@googlemail.com>
"""

from __future__ import (print_function, division, unicode_literals,
                        absolute_import)

from threading import Event
from array import array
from itertools import izip

from PyQt4.QtCore import QObject, QTimer, QTime, QThread, pyqtSignal
from PyQt4.QtGui import QApplication

from synaptiks.x11 import Display
from synaptiks._bindings import xlib
from synaptiks._bindings import xrecord
from synaptiks._bindings.util import scoped_pointer

__all__ = ['create_keyboard_monitor', 'AbstractKeyboardMonitor',
           'PollingKeyboardMonitor', 'RecordingKeyboardMonitor']

class AbstractKeyboardMonitor(QObject):
    """
    Abstract base class for keyboard monitors.

    This class defines the interface for keyboard monitoring classes.
    Currently there are two base classes:

    - :class:`RecordingKeyboardMonitor`
    - :class:`PollingKeyboardMonitor`

    Use :func:`create_keyboard_monitor` to create an instance of the "best"
    monitoring class.

    Keyboard monitoring means to emit signals, whenever the user starts or
    stops typing.  Whenever a keyboard event occurs, the keyboard is considered
    active and :attr:`typingStarted` is emitted.  After the last keyboard
    event, this class waits a configurable timespan (see :attr:`idle_time`)
    before considering the keyboard inactive and emitting
    :attr:`typingStopped`.  This is done to make sure, that the user really
    stopped typing and didn't just type a bit slower.

    Modifier keys can be ignored (see :attr:`keys_to_ignore`) as this kind of
    keys is mostly involved in hotkeys and shortcuts and doesn't really
    indicate keyboard activity.
    """

    #: default time span before considering the keyboard inactive again
    DEFAULT_IDLETIME = 2000

    #: Ignore no keys
    IGNORE_NO_KEYS = 0
    #: Ignore modifier keys alone
    IGNORE_MODIFIER_KEYS = 1
    #: Ignore combinations of modifiers and standard keys
    IGNORE_MODIFIER_COMBOS = 2

    #: Qt signal, emitted once this monitor is started.  Has no arguments.
    started = pyqtSignal()
    #: Qt signal, emitted once this monitor is stopped.  Has no arguments.
    stopped = pyqtSignal()
    #: Qt signal, emitted if typing is started.  Has no arguments.
    typingStarted = pyqtSignal()
    #: Qt signal, emitted if typing is stopped.  Has no arguments.
    typingStopped = pyqtSignal()

    def start():
        """
        Start monitoring the keyboard.
        """
        raise NotImplementedError()

    def stop(self):
        """
        Stop monitoring the keyboard.
        """
        # since we are not monitoring the keyboard anymore, we assume, that
        # there is no keyboard activity anymore.
        self.typingStopped.emit()

    @property
    def is_running(self):
        """
        ``True``, if the keyboard monitor is currently running, ``False``
        otherwise.
        """
        raise NotImplementedError()

    @property
    def idle_time(self):
        """
        The time to wait before assuming, that the typing has stopped, in
        seconds as float.
        """
        raise NotImplementedError()

    @idle_time.setter
    def idle_time(self, value):
        raise NotImplementedError()

    @property
    def keys_to_ignore(self):
        """
        The keys to ignore while observing the keyboard.

        If such a key is pressed, the keyboard will not be considered active,
        the signal :attr:`typingStarted` will consequently not be emitted.

        Raise :exc:`~exceptions.ValueError` upon assignment, if the given value
        is not one of :attr:`IGNORE_NO_KEYS`, :attr:`IGNORE_MODIFIER_KEYS` or
        :attr:`IGNORE_MODIFIER_COMBOS`.
        """
        raise NotImplementedError()

    @keys_to_ignore.setter
    def keys_to_ignore(self, value):
        raise NotImplementedError()

    @property
    def keyboard_active(self):
        """
        Is the keyboard currently active (with respect to
        :attr:`keys_to_ignore`)?

        ``True``, if the keyboard is currently active, ``False`` otherwise.
        """
        raise NotImplementedError()

class EventRecorder(QThread):
    """
    A thread to record keyboard events.

    Once started, this thread connects to the X11 display, and records all
    keyboard events.  On every keyboard event, the :attr:`keyboardEvent` signal
    is emitted.

    Use :meth:`stop()` to stop recording.
    """

    #: Qt signal emitted whenever a key was pressed.  Has a single argument,
    #: which is the key code of the pressed key
    keyPressed = pyqtSignal(int)
    #: Qt signal emitted whenever a key was released.  Has a single argument,
    #: which is the key code of the pressed key
    keyReleased = pyqtSignal(int)

    def __init__(self, parent=None):
        QThread.__init__(self, parent)
        # to synchronize startup
        self._started = Event()
        # XXX: dirty hack: ctypes insists on a per-instance reference to the
        # event handling callback, otherwise "self" is garbage in the event
        # handler, and access to "self" causes a segfault.  Reason is unknown
        # to me.
        self._callback = self._handle_event
        # maps event types to signals
        self._event_signal_map = {xlib.KEY_PRESS: self.keyPressed,
                                  xlib.KEY_RELEASE: self.keyReleased}

    def run(self):
        # create a special display connection for recording
        with Display.from_name() as recording_display:
            # record all key presses and releases, as these events indicate
            # keyboard activity
            key_events = (xlib.KEY_PRESS, xlib.KEY_RELEASE)
            with xrecord.context(recording_display, xrecord.ALL_CLIENTS,
                                 device_events=key_events) as context:
                self._context = context
                # create the recording context and enable it.  This function
                # does not return until disable_context is called, which
                # happens in stop.
                xrecord.enable_context(recording_display, context,
                                       self._callback, None)

    def stop(self):
        """
        Stop this recorder.
        """
        if not self.isRunning():
            return
        self._started.wait()
        xrecord.disable_context(Display.from_qt(), self._context)
        # immediately process the end of data event.  This allows us to wait
        # for this thread to terminate in the next line, thus making this
        # method synchronous.
        QApplication.instance().processEvents()
        self.wait()
        self._started.clear()

    def _handle_event(self, _, data):
        with scoped_pointer(data, xrecord.free_data):
            if data.contents.category == xrecord.START_OF_DATA:
                # the recorder has started
                self._started.set()
            elif data.contents.category == xrecord.FROM_SERVER:
                event_type, keycode = data.contents.event
                signal = self._event_signal_map.get(event_type)
                if signal is not None:
                    signal.emit(keycode)
            # all other client side events are ignored (e.g. END_OF_DATA)

class RecordingKeyboardMonitor(AbstractKeyboardMonitor):
    """
    Monitor the keyboard by recording X11 protocol data.
    """

    def __init__(self, parent=None):
        AbstractKeyboardMonitor.__init__(self, parent)
        self.display = Display.from_qt()
        # this timer is started on every keyboard event, its timeout signals,
        # that the keyboard is to be considered inactive again
        self._idle_timer = QTimer(self)
        self._idle_timer.setInterval(self.DEFAULT_IDLETIME)
        self._idle_timer.timeout.connect(self.typingStopped)
        self._idle_timer.setSingleShot(True)
        # this object records events
        self._recorder = EventRecorder(self)
        self._recorder.keyPressed.connect(self._key_pressed)
        self._recorder.keyReleased.connect(self._key_released)
        self._recorder.started.connect(self.started)
        self._recorder.finished.connect(self.stopped)
        # a set of all known modifier keycodes
        modifier_mapping = xlib.get_modifier_mapping(self.display)
        self._modifiers = frozenset(keycode for modifiers in modifier_mapping
                                    for keycode in modifiers if keycode != 0)
        # a set holding all pressed, but not yet released modifier keys
        self._pressed_modifiers = set()
        # the value of keys to ignore
        self._keys_to_ignore = self.IGNORE_NO_KEYS

    def _is_ignored_modifier(self, keycode):
        """
        Return ``True``, if ``keycode`` as a modifier key, which has to be
        ignored, ``False`` otherwise.
        """
        return (self._keys_to_ignore >= self.IGNORE_MODIFIER_KEYS and
                keycode in self._modifiers)

    def _is_ignored_modifier_combo(self):
        """
        Return ``True``, if the current key event occurred in combination
        with a modifier, which has to be ignored, ``False`` otherwise.
        """
        return (self._keys_to_ignore == self.IGNORE_MODIFIER_COMBOS and
                self._pressed_modifiers)

    def _is_ignored(self, keycode):
        """
        Return ``True``, if the given ``keycode`` has to be ignored,
        ``False`` otherwise.
        """
        return (self._is_ignored_modifier(keycode) or
                self._is_ignored_modifier_combo())

    def _key_pressed(self, keycode):
        if keycode in self._modifiers:
            self._pressed_modifiers.add(keycode)
        if not self._is_ignored(keycode):
            if not self.keyboard_active:
                self.typingStarted.emit()
            # reset the idle timeout
            self._idle_timer.start()

    def _key_released(self, keycode):
        self._pressed_modifiers.discard(keycode)
        if not self._is_ignored(keycode):
            if not self.keyboard_active:
                self.typingStarted.emit()
            # reset the idle timeout
            self._idle_timer.start()

    @property
    def is_running(self):
        return self._recorder.isRunning()

    def start(self):
        self._recorder.start()

    def stop(self):
        AbstractKeyboardMonitor.stop(self)
        self._idle_timer.stop()
        self._recorder.stop()

    @property
    def keys_to_ignore(self):
        return self._keys_to_ignore

    @keys_to_ignore.setter
    def keys_to_ignore(self, value):
        if not (self.IGNORE_NO_KEYS <= value <= self.IGNORE_MODIFIER_COMBOS):
            raise ValueError('unknown constant for keys_to_ignore')
        self._keys_to_ignore = value

    @property
    def idle_time(self):
        return self._idle_timer.interval() / 1000

    @idle_time.setter
    def idle_time(self, value):
        self._idle_timer.setInterval(int(value * 1000))

    @property
    def keyboard_active(self):
        return self._idle_timer.isActive()

class PollingKeyboardMonitor(AbstractKeyboardMonitor):
    """
    Monitor the keyboard for state changes by constantly polling the keyboard.
    """

    #: default polling interval
    DEFAULT_POLLDELAY = 200
    #: size of the X11 keymap array
    _KEYMAP_SIZE = 32

    def __init__(self, parent=None):
        AbstractKeyboardMonitor.__init__(self, parent)
        self._keyboard_was_active = False
        self._old_keymap = array(b'B', b'\0' * 32)
        self._keyboard_timer = QTimer(self)
        self._keyboard_timer.timeout.connect(self._check_keyboard_activity)
        self._keyboard_timer.setInterval(self.DEFAULT_POLLDELAY)
        self._activity = QTime()
        self._keys_to_ignore = self.IGNORE_NO_KEYS
        self._keymap_mask = self._setup_mask()
        self._idle_time = self.DEFAULT_IDLETIME

    @property
    def is_running(self):
        return self._keyboard_timer.isActive()

    def start(self):
        self._keyboard_timer.start()
        self.started.emit()

    def stop(self):
        AbstractKeyboardMonitor.stop(self)
        self._keyboard_timer.stop()
        self.stopped.emit()

    @property
    def keys_to_ignore(self):
        return self._keys_to_ignore

    @keys_to_ignore.setter
    def keys_to_ignore(self, value):
        if not (self.IGNORE_NO_KEYS <= value <= self.IGNORE_MODIFIER_COMBOS):
            raise ValueError('unknown constant for keys_to_ignore')
        self._keys_to_ignore = value
        self._keymap_mask = self._setup_mask()

    @property
    def idle_time(self):
        return self._idle_time / 1000

    @idle_time.setter
    def idle_time(self, value):
        self._idle_time = int(value * 1000)

    def _setup_mask(self):
        mask = array(b'B', b'\xff' * 32)
        if self._keys_to_ignore >= self.IGNORE_MODIFIER_KEYS:
            modifier_mappings = xlib.get_modifier_mapping(self.display)
            for modifier_keys in modifier_mappings:
                for keycode in modifier_keys:
                    mask[keycode // 8] &= ~(1 << (keycode % 8))
        return mask

    @property
    def keyboard_active(self):
        is_active = False

        _, raw_keymap = xlib.query_keymap(self.display)
        keymap = array(b'B', raw_keymap)

        is_active = keymap != self._old_keymap
        for new_state, old_state, mask in izip(keymap, self._old_keymap,
                                               self._keymap_mask):
            is_active = new_state & ~old_state & mask
            if is_active:
                break

        if self._keys_to_ignore == self.IGNORE_MODIFIER_COMBOS:
            for state, mask in izip(keymap, self._keymap_mask):
                if state & ~mask:
                    is_active = False
                    break

        self._old_keymap = keymap
        return is_active

    def _check_keyboard_activity(self):
        if self.keyboard_active:
            self._activity.start()
            if not self._keyboard_was_active:
                self._keyboard_was_active = True
                self.typingStarted.emit()
        elif self._activity.elapsed() > self._idle_time and \
                 self._keyboard_was_active:
            self._keyboard_was_active = False
            self.typingStopped.emit()

def create_keyboard_monitor(parent=None):
    """
    Create a new keyboard monitor:

    >>> monitor = create_keyboard_monitor(parent)
    >>> monitor.idle_time = 0.5
    >>> monitor.keys_to_ignore = monitor.IGNORE_MODIFIER_COMBOS
    >>> monitor.typingStarted.connect(lambda: print('typing started'))
    >>> monitor.typingStopped.connect(lambda: print('typing stopped'))
    >>> monitor.start()

    This function automatically chooses the "best" available implementation.
    Currently this means, that a :class:`RecordingKeyboardMonitor` is created,
    if the XRecord extension is available.  Otherwise this functions falls back
    to :class:`PollingKeyboardMonitor`.

    ``parent`` is the parent :class:`~PyQt4.QtCore.QObject`.

    Return an implementation of :class:`AbstractKeyboardMonitor`.
    """
    if xrecord:
        success, _ = xrecord.query_version(Display.from_qt())
        if success:
            return RecordingKeyboardMonitor(parent)
    return PollingKeyboardMonitor(parent)


text:
 In LOL world, there is a hero called Teemo and his attacking can make his enemy Ashe be in poisoned condition. Now, given the Teemo's attacking ascending time series towards Ashe and the poisoning time duration per Teemo's attacking, you need to output the total time that Ashe is in poisoned condition.

You may assume that Teemo attacks at the very beginning of a specific time point, and makes Ashe be in poisoned condition immediately.

Example 1:

Input: [1,4], 2
Output: 4
Explanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned immediately.
This poisoned status will last 2 seconds until the end of time point 2.
And at time point 4, Teemo attacks Ashe again, and causes Ashe to be in poisoned status for another 2 seconds.
So you finally need to output 4.

Example 2:

Input: [1,2], 2
Output: 3
Explanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned.
This poisoned status will last 2 seconds until the end of time point 2.
However, at the beginning of time point 2, Teemo attacks Ashe again who is already in poisoned status.
Since the poisoned status won't add up together, though the second poisoning attack will still work at time point 2, it will stop at the end of time point 3.
So you finally need to output 3.

Note:

    You may assume the length of given time series array won't exceed 10000.
    You may assume the numbers in the Teemo's attacking time series and his poisoning time duration per attacking are non-negative integers, which won't exceed 10,000,000.

redpajama_set_name: RedPajamaGithub


text:
/**
 * Base class for graph nodes.
 */
export class Node {
    /**
     * The unique index of this node. The default value *-1* means invalid index.
     * @default -1
     */
    index: number;

    /**
     * Constructs a new node.
     *
     * @param [index=-1] - The unique index of this node.
     */
    constructor(index?: number);

    /**
     * Transforms this instance into a JSON object.
     */
    toJSON(): { [s: string]: any };

    /**
     * Restores this instance from the given JSON object.
     *
     * @param json - The JSON object.
     */
    fromJSON(json: { [s: string]: any }): this;
}


text:
package org.cleartk.ml.libsvm;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.cleartk.ml.Feature;
import org.cleartk.ml.Instance;
import org.cleartk.ml.jar.DefaultDataWriterFactory;
import org.cleartk.ml.jar.DirectoryDataWriterFactory;
import org.cleartk.ml.jar.Train;
import org.cleartk.ml.libsvm.LibSvmBooleanOutcomeClassifier;
import org.cleartk.ml.libsvm.LibSvmBooleanOutcomeClassifierBuilder;
import org.cleartk.ml.libsvm.LibSvmBooleanOutcomeDataWriter;
import org.cleartk.ml.libsvm.LibSvmStringOutcomeClassifier;
import org.cleartk.ml.libsvm.LibSvmStringOutcomeClassifierBuilder;
import org.cleartk.ml.libsvm.LibSvmStringOutcomeDataWriter;
import org.cleartk.ml.libsvm.ExampleInstanceFactory.BooleanAnnotator;
import org.cleartk.ml.libsvm.ExampleInstanceFactory.StringAnnotator;
import org.cleartk.test.util.DefaultTestBase;
import org.junit.Assert;
import org.junit.Test;
import org.apache.uima.fit.factory.UimaContextFactory;
import org.apache.uima.fit.testing.util.HideOutput;

/**
 *

 * Copyright (c) 2007-2008, Regents of the University of Colorado

 * All rights reserved.
 *
 * @author Steven Bethard
 */
public class LibSvmTest extends DefaultTestBase {

  @Test
  public void testBinaryLIBSVM() throws Exception {
    // create the data writer
    BooleanAnnotator annotator = new BooleanAnnotator();
    annotator.initialize(UimaContextFactory.createUimaContext(
        DirectoryDataWriterFactory.PARAM_OUTPUT_DIRECTORY,
        this.outputDirectoryName,
        DefaultDataWriterFactory.PARAM_DATA_WRITER_CLASS_NAME,
        LibSvmBooleanOutcomeDataWriter.class.getName()));

    // run process to produce a bunch of instances
    annotator.process(null);

    annotator.collectionProcessComplete();

    // check that the output file was written and is not empty
    BufferedReader reader = new BufferedReader(new FileReader(new File(
        this.outputDirectoryName,
        "training-data.libsvm")));
    Assert.assertTrue(reader.readLine().length() > 0);
    reader.close();

    // run the training command
    HideOutput hider = new HideOutput();
    Train.main(this.outputDirectoryName, "-c", "1.0", "-s", "0", "-t", "0");
    hider.restoreOutput();

    // read in the classifier and test it on new instances
    LibSvmBooleanOutcomeClassifierBuilder builder = new LibSvmBooleanOutcomeClassifierBuilder();
    LibSvmBooleanOutcomeClassifier classifier;
    classifier = builder.loadClassifierFromTrainingDirectory(this.outputDirectory);
    for (Instance<Boolean> instance : ExampleInstanceFactory.generateBooleanInstances(1000)) {
      List<Feature> features = instance.getFeatures();
      Boolean outcome = instance.getOutcome();
      Assert.assertEquals(outcome, classifier.classify(features));

      Map<Boolean, Double> scoredOutcomes = classifier.score(features);
      Assert.assertTrue(scoredOutcomes.get(outcome) > scoredOutcomes.get(!outcome));
    }
  }

  @Test
  public void testMultiClassLIBSVM() throws Exception {
    // create the data writer
    StringAnnotator annotator = new StringAnnotator();
    annotator.initialize(UimaContextFactory.createUimaContext(
        DirectoryDataWriterFactory.PARAM_OUTPUT_DIRECTORY,
        this.outputDirectoryName,
        DefaultDataWriterFactory.PARAM_DATA_WRITER_CLASS_NAME,
        LibSvmStringOutcomeDataWriter.class.getName()));

    // run process to produce a bunch of instances
    annotator.process(null);

    annotator.collectionProcessComplete();

    // check that the output files were written for each class
    BufferedReader reader = new BufferedReader(new FileReader(new File(
        this.outputDirectoryName,
        "training-data.libsvm")));
    Assert.assertTrue(reader.readLine().length() > 0);
    reader.close();

    // run the training command
    HideOutput hider = new HideOutput();
    Train.main(this.outputDirectoryName, "-c", "10", "-t", "0");
    hider.restoreOutput();

    // read in the classifier and test it on new instances
    LibSvmStringOutcomeClassifierBuilder builder = new LibSvmStringOutcomeClassifierBuilder();
    LibSvmStringOutcomeClassifier classifier;
    classifier = builder.loadClassifierFromTrainingDirectory(this.outputDirectory);
    for (Instance<String> instance : ExampleInstanceFactory.generateStringInstances(1000)) {
      List<Feature> features = instance.getFeatures();
      String outcome = instance.getOutcome();
      Assert.assertEquals(outcome, classifier.classify(features));

      Map<String, Double> scoredOutcomes = classifier.score(features);
      for (String otherOutcome : Arrays.asList("A", "B", "C")) {
        if (!otherOutcome.equals(outcome)) {
          Assert.assertTrue(scoredOutcomes.get(outcome) > scoredOutcomes.get(otherOutcome));
        }
      }
    }
  }
}


text:
title: PapljStructureOutliner.<init> - aesi-intellij
---

[aesi-intellij](../../index.html) / [org.metaborg.paplj.structureoutline](../index.html) / [PapljStructureOutliner](index.html) / [<init>](.)

# <init>

`PapljStructureOutliner()`


text:
package io.fabric8.kubernetes.api.model;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
import io.fabric8.kubernetes.api.builder.Visitor;

import static org.junit.Assert.*;

public class KubernetesListTest {

    @Test
    public void testDefaultValues() throws JsonProcessingException {
        Service service = new io.fabric8.kubernetes.api.model.ServiceBuilder()
                .withNewMetadata()
                    .withName("test-service")
                .endMetadata()
                .build();
        assertNotNull(service.getApiVersion());
        assertEquals(service.getKind(), "Service");

        ReplicationController replicationController = new io.fabric8.kubernetes.api.model.ReplicationControllerBuilder()
                .withNewMetadata()
                .withName("test-controller")
                .endMetadata()
                .build();
        assertNotNull(replicationController.getApiVersion());
        assertEquals(replicationController.getKind(), "ReplicationController");

        KubernetesList kubernetesList;
        kubernetesList = new io.fabric8.kubernetes.api.model.KubernetesListBuilder()
                .addNewServiceItem()
                .withNewMetadata()
                    .withName("test-service")
                .endMetadata()
                .and()
                .addNewReplicationControllerItem()
                .withNewMetadata()
                    .withName("test-controller")
                .endMetadata()
                .and()
                .build();

        assertNotNull(kubernetesList.getApiVersion());
        assertEquals(kubernetesList.getApiVersion(), "v1");
        assertEquals(kubernetesList.getKind(), "List");
        assertThat(kubernetesList.getItems(), CoreMatchers.hasItem(service));
        assertThat(kubernetesList.getItems(), CoreMatchers.hasItem(replicationController));
    }

    @Test
    public void testVisitor() throws JsonProcessingException {
        KubernetesList list = new io.fabric8.kubernetes.api.model.KubernetesListBuilder()
                .addNewPodItem()
                    .withNewSpec()
                        .addNewContainer()
                            .withName("my-container")
                            .withImage("my/image")
                        .endContainer()
                    .endSpec()
                .and()
                .build();

        list = new io.fabric8.kubernetes.api.model.KubernetesListBuilder(list).accept(new Visitor() {
            public void visit(Object item) {
                if (item instanceof io.fabric8.kubernetes.api.model.PodSpecBuilder) {
                    ((io.fabric8.kubernetes.api.model.PodSpecBuilder)item).addNewContainer()
                            .withName("other-container")
                            .withImage("other/image")
                            .and();
                }
            }
        }).build();
    }

    @Test
    public void testDefaultNullValues() throws JsonProcessingException {
        Container container = new io.fabric8.kubernetes.api.model.ContainerBuilder().build();
        assertNull(container.getLifecycle());
        assertNull(container.getLivenessProbe());

        Pod pod = new io.fabric8.kubernetes.api.model.PodBuilder().build();
        assertNull(pod.getSpec());
        assertNull(pod.getStatus());
    }
}


text:
describe("Wizard: Unit Tests Restricted Navigation", function() {

    var steps = {
            theme     : 0,
            demo      : 1,
            doc       : 0,
            community : 0
    };

    var w;

    beforeEach(module('myApp'));
    beforeEach(inject(function(wizard) {
        w = wizard;
        callback = jasmine.createSpy('cb');
        w.init(steps, callback);
    }));

    it('should contain the wizard service', function() {
        expect(w).not.toEqual(null);
    });

    it('should init on step 2 (DEMO)', function() {
        expect(w.index).toEqual(1);
    });

    it('should have previous step', function() {
        expect(w.hasPrev()).toBe(true);
    });

    it('should have next step', function() {
        expect(w.hasNext()).toBe(true);
    });

    it('should have one completed step', function() {
        expect(Object.keys(w.completed).length).toEqual(1);
        expect(w.completed.theme).toEqual(1);
    });

    it('should go to prev step (THEME), not marking current step complete, and then callback', function() {
        w.back();
        expect(Object.keys(w.completed).length).toEqual(1);
        expect(callback).toHaveBeenCalled();
    });

    it('should not have a prev step', function() {
        expect(w.hasPrev()).toBe(false);
    });

    it('should go to next step (DEMO), the current step marked completed already (keep), and callback', function() {
        w.next();
        expect(Object.keys(w.completed).length).toEqual(1);
        expect(w.index).toEqual(1);
        expect(callback).toHaveBeenCalled();
    });

    it('should NOT be able to go to the last step (restricted navigation). Still callback.', function() {
        w.goto('community');
        expect(Object.keys(w.completed).length).toEqual(1);
        expect(w.index).toEqual(1);
        expect(callback).toHaveBeenCalled();
    });

    it('should go to next step (DOC), mark current one as complete, and callback', function() {
        w.next();
        expect(Object.keys(w.completed).length).toEqual(2);
        expect(w.index).toEqual(2);
        expect(w.completed.demo).toEqual(1);
        expect(callback).toHaveBeenCalled();
    });

    it('should mark completed, go next (COMMUNITY), callback', function() {
        w.next();
        expect(Object.keys(w.completed).length).toEqual(3);
        expect(w.index).toEqual(3);
        expect(w.completed.doc).toEqual(1);
        expect(callback).toHaveBeenCalled();
    });

    it('should not have a next available', function() {
        expect(w.index).toEqual(3);
        expect(w.hasNext()).toBe(false);
    });

    it('should go to the first step, without marking last one complete, and callback', function() {
        w.goto('theme');
        expect(Object.keys(w.completed).length).toEqual(3);
        expect(callback).toHaveBeenCalled();
    });
});


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

@SuppressWarnings("all")
public class CustomizationWinOptions extends CustomizationOptions {
  public boolean changeSID;
  public boolean deleteAccounts;
  public CustomizationSysprepRebootOption reboot;

  public boolean isChangeSID() {
    return this.changeSID;
  }

  public boolean isDeleteAccounts() {
    return this.deleteAccounts;
  }

  public CustomizationSysprepRebootOption getReboot() {
    return this.reboot;
  }

  public void setChangeSID(boolean changeSID) {
    this.changeSID=changeSID;
  }

  public void setDeleteAccounts(boolean deleteAccounts) {
    this.deleteAccounts=deleteAccounts;
  }

  public void setReboot(CustomizationSysprepRebootOption reboot) {
    this.reboot=reboot;
  }
}


text:
// Copyright 2010 Chris Patterson
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace Stact
{
	using Configuration.Internal;

	public static class ExtensionsForLastChannels
	{
		public static LastConfigurator<TChannel> Last<TChannel>(this IntervalConfigurator<TChannel> configurator)
		{
			var lastConfigurator = new LastConfiguratorImpl<TChannel>();

			configurator.AddConfigurator(lastConfigurator);

			return lastConfigurator;
		}
	}
}


text:
<?php

namespace Dzangocart\Bundle\SubscriptionBundle\Propel;

use PropelPDO;
use Dzangocart\Bundle\SubscriptionBundle\Model\PlanInterface;
use Dzangocart\Bundle\SubscriptionBundle\Propel\om\BasePlan;

class Plan extends BasePlan implements PlanInterface
{
    public static function getDefaultPlan()
    {
        return PlanQuery::create()
            ->isDefault()
            ->findOne();
    }

    public static function getDefaultPlanForTrial()
    {
        return PlanQuery::create()
            ->filterByTrial(true)
            ->findOne();
    }

    public function isDisabled()
    {
        return $this->getDisabled();
    }

    public function isActive()
    {
        if ($this->isDisabled()) {
            return false;
        }

        $start = $this->getStart('U');
        $end = $this->getFinish('U');
        $now = time();

        return ($start == null || $start <= $now) &&
            ($end == null || $now <= $end);
    }

    public function isInactive()
    {
        return !$this->isActive();
    }

    public function isDefault()
    {
        return $this->getTrial();
    }

    public function isFree()
    {
        return !$this->getPrice();
    }

    public function getFree()
    {
        return $this->isFree();
    }

    public function getFeatures($criteria = null, PropelPDO $con = null)
    {
        $plan_features = array();

        foreach (parent::getFeatures() as $plan_feature) {
            $plan_features[$plan_feature->getFeatureId()] = $plan_feature;
        }

        $query = FeatureQuery::create()
            ->joinWithI18n($this->getLocale())
            ->orderByRank();

        foreach ($query->find() as $feature) {
            $id = $feature->getId();

            if (!array_key_exists($id, $plan_features)) {
                $plan_feature = new PlanFeature();
                $plan_feature->setFeature($feature);
                $plan_feature->setPlan($this);

                $plan_features[$id] = $plan_feature;
            }
        }

        return $plan_features;
    }

    public function getDefaultPrice()
    {
        return $this->getPrices(PriceQuery::create()->getDefault())
            ->getFirst();
    }

    public function disable()
    {
        $this->setDisabled(true);
    }

    public function enable()
    {
        $this->setDisabled(false);
    }

    public function isDefaultForTrial()
    {
        return $this->getTrial();
    }

    public function setAsTrialPlan()
    {
        $plans = PlanQuery::create()
            ->filterByTrial(true)
            ->find();

        foreach ($plans as $plan) {
            $plan->unsetAsTrialPlan();
        }

        $this->setTrial(true);

        $this->save();
    }

    public function unsetAsTrialPlan()
    {
        $this->setTrial(false);
        $this->save();
    }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Typedef Index</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../index.html" title="Chapter 1. Boost.TypeTraits">
<link rel="up" href="../index.html" title="Chapter 1. Boost.TypeTraits">
<link rel="prev" href="s11.html" title="Class Index">
<link rel="next" href="s13.html" title="Macro Index">

Home
Libraries
People
FAQ
More

Typedef Index

A F R T

A

align_t

aligned_storage

alignment_of

F

false_type

integral_constant

R

result_type

function_traits

Rhs_nocv

Operator Type Traits

Rhs_noptr

Operator Type Traits

Rhs_noref

Operator Type Traits

T

true_type

integral_constant

Copyright © 2000, 2011 Adobe Systems Inc, David Abrahams,
      Frederic Bron, Steve Cleary, Beman Dawes, Aleksey Gurtovoy, Howard Hinnant,
      Jesse Jones, Mat Marcus, Itay Maman, John Maddock, Alexander Nasonov, Thorsten
      Ottosen, Roman Perepelitsa, Robert Ramey, Jeremy Siek, Robert Stewart and Steven
      Watanabe

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
<?php

declare(strict_types=1);

namespace Bitrix24\SDK\Services\Placement\Service;

use Bitrix24\SDK\Services\AbstractService;
use Bitrix24\SDK\Services\Placement\Result\DeleteUserTypeResult;
use Bitrix24\SDK\Services\Placement\Result\RegisterUserTypeResult;
use Bitrix24\SDK\Services\Placement\Result\UserFieldTypesResult;

class UserFieldType extends AbstractService
{
    /**
     * Registration of new type of user fields. This method returns true or an error with description.
     *
     * @param string $userTypeId  Inline code of the type. Required parameter. a-z0-9
     * @param string $handlerUrl  Address of user type handler. Required parameter. Shall be in the same domain as the main application address.
     * @param string $title       Type text name. Will be displayed in the admin interface of user field settings.
     * @param string $description Type text description. Will be displayed in the admin interface of user field settings.
     *
     * @return \Bitrix24\SDK\Services\Placement\Result\RegisterUserTypeResult
     * @throws \Bitrix24\SDK\Core\Exceptions\BaseException
     * @throws \Bitrix24\SDK\Core\Exceptions\TransportException
     * @link https://training.bitrix24.com/rest_help/application_embedding/user_field/userfieldtype_add.php
     */
    public function add(string $userTypeId, string $handlerUrl, string $title, string $description): RegisterUserTypeResult
    {
        return new RegisterUserTypeResult(
            $this->core->call(
                'userfieldtype.add',
                [
                    'USER_TYPE_ID' => $userTypeId,
                    'HANDLER'      => $handlerUrl,
                    'TITLE'        => $title,
                    'DESCRIPTION'  => $description,
                ]
            )
        );
    }

    /**
     * Retrieves list of user field types, registrered by the application. List method. Results in the list of field types with page-by-page navigation.
     *
     * @return UserFieldTypesResult
     * @throws \Bitrix24\SDK\Core\Exceptions\BaseException
     * @throws \Bitrix24\SDK\Core\Exceptions\TransportException
     * @link https://training.bitrix24.com/rest_help/application_embedding/user_field/userfieldtype_list.php
     */
    public function list(): UserFieldTypesResult
    {
        return new UserFieldTypesResult(
            $this->core->call('userfieldtype.list')
        );
    }

    /**
     * Modifies settings of user field types, registered by the application. This method returns true or an error with description.
     *
     * @param string $userTypeId  Inline code of the type. Required parameter. a-z0-9
     * @param string $handlerUrl  Address of user type handler. Required parameter. Shall be in the same domain as the main application address.
     * @param string $title       Type text name. Will be displayed in the admin interface of user field settings.
     * @param string $description Type text description. Will be displayed in the admin interface of user field settings.
     *
     * @return \Bitrix24\SDK\Services\Placement\Result\RegisterUserTypeResult
     * @throws \Bitrix24\SDK\Core\Exceptions\BaseException
     * @throws \Bitrix24\SDK\Core\Exceptions\TransportException
     * @link https://training.bitrix24.com/rest_help/application_embedding/user_field/userfieldtype_update.php
     */
    public function update(string $userTypeId, string $handlerUrl, string $title, string $description): RegisterUserTypeResult
    {
        return new RegisterUserTypeResult(
            $this->core->call(
                'userfieldtype.update',
                [
                    'USER_TYPE_ID' => $userTypeId,
                    'HANDLER'      => $handlerUrl,
                    'TITLE'        => $title,
                    'DESCRIPTION'  => $description,
                ]
            )
        );
    }

    /**
     * Deletes user field type, registered by the application. This method returns true or an error with description.
     *
     * @param string $userTypeId Inline code of the type. Required parameter. a-z0-9
     *
     * @return \Bitrix24\SDK\Services\Placement\Result\DeleteUserTypeResult
     * @throws \Bitrix24\SDK\Core\Exceptions\BaseException
     * @throws \Bitrix24\SDK\Core\Exceptions\TransportException
     * @link https://training.bitrix24.com/rest_help/application_embedding/user_field/userfieldtype_delete.php
     */
    public function delete(string $userTypeId): DeleteUserTypeResult
    {
        return new DeleteUserTypeResult(
            $this->core->call(
                'userfieldtype.delete',
                [
                    'USER_TYPE_ID' => $userTypeId,
                ]
            )
        );
    }
}


text:
using System.Collections.Generic;
using System.Xml.Schema;

namespace Jolt.Testing.Assertions
{
    internal sealed class AssertionFactory : IAssertionFactory
    {
        #region IAssertionFactory members ---------------------------------------------------------

        /// <summary>
        /// <see cref="IAssertionFactory.CreateXmlValidityAssertion(XmlSchemaSet)"/>
        /// </summary>
        XmlValidityAssertion IAssertionFactory.CreateXmlValidityAssertion(XmlSchemaSet schemas)
        {
            return new XmlValidityAssertion(schemas);
        }

        /// <summary>
        /// <see cref="IAssertionFactory.CreateXmlValidityAssertion(XmlSchemaSet, XmlSchemaValidationFlags)"/>
        /// </summary>
        XmlValidityAssertion IAssertionFactory.CreateXmlValidityAssertion(XmlSchemaSet schemas, XmlSchemaValidationFlags flags)
        {
            return new XmlValidityAssertion(schemas, flags);
        }

        /// <summary>
        /// <see cref="IAssertionFactory.CreateXmlEqualityAssertion"/>
        /// </summary>
        XmlEqualityAssertion IAssertionFactory.CreateXmlEqualityAssertion()
        {
            return new XmlEqualityAssertion();
        }

        /// <summary>
        /// <see cref="IAssertionFactory.CreateXmlEquivalencyAssertion"/>
        /// </summary>
        XmlEquivalencyAssertion IAssertionFactory.CreateXmlEquivalencyAssertion(XmlComparisonFlags strictness)
        {
            return new XmlEquivalencyAssertion(strictness);
        }
        #endregion
    }
}


text:
<link rel="import" href="../polymer/polymer.html">

<polymer-element name="core-pubnub" hidden constructor="corePubNub" attributes="publish_key subscribe_key auth_key origin uuid cipher_key noleave keepalive secret_key ssl windwoing jsonp done pubnub">

</polymer-element>

<polymer-element name="core-pubnub-subscribe" hidden attributes="channel timetoken windowing heartbeat state messages presence subscribe pubnub done">

</polymer-element>

<polymer-element name="core-pubnub-publish" hidden attributes="channel message publish_key publish pubnub done">

</polymer-element>

<polymer-element name="core-pubnub-history" hidden attributes="channel count end reverse start history pubnub done">

</polymer-element>

<polymer-element name="core-pubnub-here-now" hidden attributes="channel state uuids presence pubnub done">

</polymer-element>

<polymer-element name="core-pubnub-where-now" hidden attributes="uuid presence pubnub done">

</polymer-element>

<polymer-element name="core-pubnub-replay" hidden attributes="source destination end limit reverse start stop pubnub done">

</polymer-element>


text:
package com.wondersgroup.healthxuhui.ui.main;

import com.wondersgroup.healthxuhui.core.AppApplication;
import com.wondersgroup.healthxuhui.data.source.DataSource;
import com.wondersgroup.healthxuhui.data.entity.HttpResponeEntity;
import com.wondersgroup.healthxuhui.data.entity.SecondItemEntity;
import com.wondersgroup.healthxuhui.data.entity.VersonUpdateEntity;
import com.wondersgroup.healthxuhui.ui.permission.PermissionsActivity;
import com.wondersgroup.healthxuhui.ui.permission.PermissionsChecker;
import com.wondersgroup.healthxuhui.ui.second.SecondItemEnum;
import com.wondersgroup.healthxuhui.util.AppUrlUtil;
import com.wondersgroup.healthxuhui.util.LogUtil;
import com.wondersgroup.healthxuhui.util.VersonUtil;

import java.util.List;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by yang on 16/7/3.
 */
public class MainPresenter implements MainContract.Presenter{

    private final CompositeSubscription mCompositeSubscription;
    private MainContract.View mainView;
    private DataSource mDataSource;

    public MainPresenter(DataSource dataSource, MainContract.View view){
        mainView = view;
        mainView.setPresenter(this);
        this.mDataSource = dataSource;
        mCompositeSubscription = new CompositeSubscription();
    }

    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {
        mCompositeSubscription.clear();
    }

    @Override
    public void loadHomeWebPage() {
        String homeUrl = AppUrlUtil.getHomeUrl(AppApplication.getInstance().getApplicationContext());
        mainView.loadUrl(homeUrl);
    }

    @Override
    public void updateVerion() {
        Subscription subscription = mDataSource.getLatestVersionInfo()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<HttpResponeEntity<List<VersonUpdateEntity>>>() {
                    @Override
                    public void onCompleted() {
                        LogUtil.i("version onCompleted");
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtil.i("version onError");
                    }

                    @Override
                    public void onNext(HttpResponeEntity<List<VersonUpdateEntity>> listHttpResponeEntity) {
                        LogUtil.i("version onNext");
                        int currVersion = VersonUtil.getVersionCode(AppApplication.getInstance().getApplicationContext());
                        VersonUpdateEntity entity = listHttpResponeEntity.getLocalObject().get(0);
                        if (currVersion < entity.getVersionId()){
                            mainView.showUpdateDialog(entity);
                        }else {
                            LogUtil.i("已经是最新版本了");
                        }
                    }
                });
        mCompositeSubscription.add(subscription);
    }

    @Override
    public void openQygk() {
        List<SecondItemEntity> qygk = AppUrlUtil.getSecondItemListByItemName(AppApplication.getInstance().getApplicationContext(), "qygk");
        mainView.showBrowser(qygk.get(0).getUrl());
    }

    @Override
    public void openQyws() {
        mainView.showSecond(SecondItemEnum.QYWS);
    }

    @Override
    public void openYlfw() {
        mainView.showSecond(SecondItemEnum.YLFW);
    }

    @Override
    public void openGGws() {
        mainView.showSecond(SecondItemEnum.GGWS);
    }

}


text:
package com.jfinal.ext.plugin.jms;

import javax.jms.Connection;

/**
 * Created by kid on 15-1-31.
 */
public class ActiveMqProvider implements JmsConnectionProvider {
    @Override
    public Connection getConnection() {
        return null;
    }
}


text:
"""
Create a rosbag for data collected by an openlog artemis and a video camera
The video camera records a video and a timestamp file.
Each line in the timestamp file: frame time by sensor clock (ns), ...., frame unix time by computer (sec).
The artemis records an IMU file, each line
unix time by computer (sec), ax, ay, az, gx, gy, gz, time by sensor (sec)

Sometimes, the unix time of the video has to plus an offset say 8 hours to account for the local time shift.
"""
import argparse
import os
import sys

import rospy
import rosbag

import kalibr_bagcreater
import utility_functions

def parse_args():
    parser = argparse.ArgumentParser(
        description='create a ROS bag containing image and imu topics '
        'from a video clip and inertial data.')

    parser.add_argument('--output_bag',
                        default="output.bag",
                        help='ROS bag file %(default)s')

    parser.add_argument('video_file',
                        nargs='?',
                        help='Video filename')

    parser.add_argument(
        'imu_file',
        help='Imu filename.')

    parser.add_argument('--video_file_time_offset',
                        type=float,
                        default=0.0,
                        help='When the time file for the video is provided, '
                             'the video_file_time_offset may be added to '
                             'these timestamps.(default: %(default)s)',
                        required=False)

    parser.add_argument('--video_from_to',
                        type=float,
                        nargs=2,
                        help='Use the video frames starting from up to this'
                        ' time [s] relative to the video beginning.')

    parser.add_argument('--video_time_file',
                        default='',
                        nargs='?',
                        help='The csv file containing timestamps of every '
                        'video frames in IMU clock(default: %(default)s).'
                        ' Except for the header, each row has the '
                        'device timestamp in nanoseconds as the first component '
                        'and the host timestamp in seconds as the last component',
                        required=False)

    parser.add_argument(
        '--max_video_frame_height',
        type=int,
        default=100000,
        help='For a video frame, if min(rows, cols) > %(default)s, '
        'it will be downsampled by 2. If the resultant bag is '
        'used for photogrammetry, the original focal_length and '
        'principal_point should be half-sized, but the '
        'distortion parameters should not be changed. (default: %(default)s)',
        required=False)

    if len(sys.argv) < 2:
        msg = 'Example usage: {} --video /dataset/' \
               'IMG_2805.avi --imu /dataset/gyro_accel.csv ' \
               '--video_time_file /dataset/movie_metadata.csv ' \
               '--output_bag /dataset/IMG_2805.bag\n'. \
            format(sys.argv[0])

        print(msg)
        parser.print_help()
        sys.exit(1)

    parsed = parser.parse_args()
    return parsed

def main():
    parsed = parse_args()
    bag = rosbag.Bag(parsed.output_bag, 'w')

    # write video
    utility_functions.check_file_exists(parsed.video_file)
    if parsed.video_from_to:
        print('Frame time range within the video: {}'.format(parsed.video_from_to))
    frame_local_timestamps = None
    frame_remote_timestamps = None

    if parsed.video_time_file:
        frame_timestamps = kalibr_bagcreater.load_local_and_remote_times(parsed.video_time_file)
        aligned_local_timestamps = [time[0] + rospy.Duration.from_sec(parsed.video_file_time_offset)
                                    for time in frame_timestamps]
        frame_local_timestamps = aligned_local_timestamps
        frame_remote_timestamps = [time[1] for time in frame_timestamps]
        print('Loaded {} timestamps for frames'.format(len(frame_timestamps)))
        first_frame_imu_time = frame_local_timestamps[0].to_sec()
    videotimerange = kalibr_bagcreater.write_video_to_rosbag(
        bag,
        parsed.video_file,
        parsed.video_from_to,
        first_frame_imu_time,
        frame_local_timestamps,
        frame_remote_timestamps,
        parsed.max_video_frame_height,
        shift_in_time=0.0,
        topic="/cam0/image_raw")
    print('video time range {}'.format(videotimerange))

    # write IMU data that falling into the unix time range
    kalibr_bagcreater.write_imufile_remotetime_to_rosbag(bag, parsed.imu_file, videotimerange, 5, "/imu0")

    bag.close()
    print('Saved to bag file {}'.format(parsed.output_bag))

if __name__ == "__main__":
    main()


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml.Serialization;

namespace DataCloner.Core.Configuration
{
    [DebuggerDisplay("{Id.ToString() + \"_\" + Var}")]
    [Serializable]
    public class DbSettings : IEquatable<DbSettings>
    {
        [XmlAttribute]
        public string Id { get; set; }

        [XmlAttribute]
        public string ForSchemaId { get; set; }

        [XmlAttribute]
        public string Description { get; set; }

        [XmlAttribute]
        public string BasedOn { get; set; }

        [XmlElement("Table")]
        public List<Table> Tables { get; set; }

        public DbSettings()
        {
            Tables = new List<Table>();
        }

        public override bool Equals(object obj)
        {
            var o = obj as DbSettings;
            return Equals(o);
        }

        public bool Equals(DbSettings other)
        {
            return other != null && other.Id == Id;
        }

        public override int GetHashCode()
        {
            return Id.GetHashCode();
        }
    }
}


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

package com.google.api.graphql.rejoiner;

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.EnumDescriptor;
import com.google.protobuf.Descriptors.FileDescriptor;
import graphql.relay.Relay;
import graphql.schema.GraphQLInterfaceType;
import graphql.schema.GraphQLObjectType;
import graphql.schema.GraphQLType;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/** Registers Protos for building a GraphQL schema. */
final class ProtoRegistry {
  private final BiMap<String, GraphQLType> mapping;
  private final GraphQLInterfaceType nodeInterface;

  private ProtoRegistry(BiMap<String, GraphQLType> mapping, GraphQLInterfaceType nodeInterface) {
    this.mapping = mapping;
    this.nodeInterface = nodeInterface;
  }

  static Builder newBuilder() {
    return new Builder();
  }

  Set<GraphQLType> listTypes() {
    return mapping.values();
  }

  boolean hasRelayNode() {
    return mapping.values().stream()
        .anyMatch(
            type ->
                type instanceof GraphQLObjectType
                    && ((GraphQLObjectType) type).getInterfaces().contains(nodeInterface));
  }

  GraphQLInterfaceType getRelayNode() {
    return nodeInterface;
  }

  static Set<FileDescriptor> extractDependencies(List<FileDescriptor> fileDescriptors) {
    LinkedList<FileDescriptor> loop = new LinkedList<>(fileDescriptors);
    HashSet<FileDescriptor> fileDescriptorSet = new HashSet<>(fileDescriptors);

    while (!loop.isEmpty()) {
      FileDescriptor fileDescriptor = loop.pop();
      for (FileDescriptor dependency : fileDescriptor.getDependencies()) {
        if (!fileDescriptorSet.contains(dependency)) {
          fileDescriptorSet.add(dependency);
          loop.push(dependency);
        }
      }
    }

    return ImmutableSet.copyOf(fileDescriptorSet);
  }
  /** Builder for {@see ProtoRegistry}. */
  public static class Builder {
    private final ArrayList<FileDescriptor> fileDescriptors = new ArrayList<>();
    private final ArrayList<Descriptor> descriptors = new ArrayList<>();
    private final ArrayList<EnumDescriptor> enumDescriptors = new ArrayList<>();
    private final Set<TypeModification> typeModifications = new HashSet<>();
    private SchemaOptions schemaOptions = SchemaOptions.defaultOptions();

    Builder add(FileDescriptor fileDescriptor) {
      fileDescriptors.add(fileDescriptor);
      return this;
    }

    Builder addAll(Collection<FileDescriptor> fileDescriptors) {
      this.fileDescriptors.addAll(fileDescriptors);
      return this;
    }

    Builder add(Descriptor descriptor) {
      descriptors.add(descriptor);
      return this;
    }

    Builder add(EnumDescriptor enumDescriptor) {
      enumDescriptors.add(enumDescriptor);
      return this;
    }

    Builder add(Collection<TypeModification> modifications) {
      typeModifications.addAll(modifications);
      return this;
    }

    ProtoRegistry build() {
      ImmutableListMultimap<String, TypeModification> modificationsMap =
          ImmutableListMultimap.copyOf(
              this.typeModifications.stream()
                  .map(
                      modification ->
                          new SimpleImmutableEntry<>(modification.getTypeName(), modification))
                  .collect(Collectors.toList()));

      final BiMap<String, GraphQLType> mapping = HashBiMap.create();

      GraphQLInterfaceType nodeInterface =
          new Relay()
              .nodeInterface(
                  env -> {
                    Relay.ResolvedGlobalId resolvedGlobalId =
                        new Relay().fromGlobalId(env.getArguments().get("id").toString());
                    return (GraphQLObjectType) mapping.get(resolvedGlobalId.getType());
                  });

      mapping.putAll(
          modifyTypes(
              getMap(fileDescriptors, descriptors, enumDescriptors, nodeInterface, schemaOptions),
              modificationsMap));

      return new ProtoRegistry(mapping, nodeInterface);
    }

    private static BiMap<String, GraphQLType> getMap(
        List<FileDescriptor> fileDescriptors,
        List<Descriptor> descriptors,
        List<EnumDescriptor> enumDescriptors,
        GraphQLInterfaceType nodeInterface,
        SchemaOptions schemaOptions) {
      HashBiMap<String, GraphQLType> mapping =
          HashBiMap.create(getEnumMap(enumDescriptors, schemaOptions));
      LinkedList<Descriptor> loop = new LinkedList<>(descriptors);

      Set<FileDescriptor> fileDescriptorSet = extractDependencies(fileDescriptors);

      for (FileDescriptor fileDescriptor : fileDescriptorSet) {
        loop.addAll(fileDescriptor.getMessageTypes());
        mapping.putAll(getEnumMap(fileDescriptor.getEnumTypes(), schemaOptions));
      }

      while (!loop.isEmpty()) {
        Descriptor descriptor = loop.pop();
        if (!mapping.containsKey(descriptor.getFullName())) {
          mapping.put(
              ProtoToGql.getReferenceName(descriptor),
              ProtoToGql.convert(descriptor, nodeInterface, schemaOptions));
          GqlInputConverter inputConverter =
              GqlInputConverter.newBuilder().add(descriptor.getFile()).build();
          mapping.put(
              GqlInputConverter.getReferenceName(descriptor),
              inputConverter.getInputType(descriptor, schemaOptions));
          loop.addAll(descriptor.getNestedTypes());

          mapping.putAll(getEnumMap(descriptor.getEnumTypes(), schemaOptions));
        }
      }
      return ImmutableBiMap.copyOf(mapping);
    }

    private static BiMap<String, GraphQLType> getEnumMap(
        Iterable<EnumDescriptor> descriptors, SchemaOptions schemaOptions) {
      HashBiMap<String, GraphQLType> mapping = HashBiMap.create();
      for (EnumDescriptor enumDescriptor : descriptors) {
        mapping.put(
            ProtoToGql.getReferenceName(enumDescriptor),
            ProtoToGql.convert(enumDescriptor, schemaOptions));
      }
      return mapping;
    }

    /** Applies the supplied modifications to the GraphQLTypes. */
    private static BiMap<String, GraphQLType> modifyTypes(
        BiMap<String, GraphQLType> mapping,
        ImmutableListMultimap<String, TypeModification> modifications) {
      BiMap<String, GraphQLType> result = HashBiMap.create(mapping.size());
      for (String key : mapping.keySet()) {
        if (mapping.get(key) instanceof GraphQLObjectType) {
          GraphQLObjectType val = (GraphQLObjectType) mapping.get(key);
          if (modifications.containsKey(key)) {
            for (TypeModification modification : modifications.get(key)) {
              val = modification.apply(val);
            }
          }
          result.put(key, val);
        } else {
          result.put(key, mapping.get(key));
        }
      }
      return result;
    }

    public Builder setSchemaOptions(SchemaOptions schemaOptions) {
      this.schemaOptions = schemaOptions;
      return this;
    }
  }
}


text:
The settings.json file contains a node named `templates` with two entries : `screen` and `html`.

The `screen` template is used for the application itself : how the interface should looks like.

The `html` template is used by the application for the generation of `.html` files.  This is done every time you click on a note : the note is stored on the disk.  The template used for this is defined here.

## Use your own

Just take a copy of the template (f.i.`templates/screen.php`), rename it (f.i. `myTemplate.php`) and specify the filename (without extension) in the settings.json file.

Edit settings.json, locate the `templates` node and replace the desired template name.  For instance, replace

```json
   "templates": {
      "screen": "screen",
```

by

```json
   "templates": {
      "screen": "myTemplate",
```

*Please note : the template's name can only contains letters (a-z and A-Z), figures (0-9) and three special characters : the dot, the minus or the underscore sign.*


text:
package org.cipango.sip;

import javax.servlet.sip.ServletParseException;

import org.eclipse.jetty.io.Buffer;
import org.eclipse.jetty.io.ByteArrayBuffer;

public class RAck implements Cloneable
{
	private long _rseq;
	private long _number;
	private String _method;
	private String _rack;

	public RAck(String rack) throws ServletParseException
    {
		_rack = rack;
		parse();
	}

	private void parse() throws ServletParseException
	{
		int index = skipSpaces(0);

		int index2 = _rack.indexOf(' ', index);

    	if (index2 < 0)
    		throw new ServletParseException("Invalid RAck header: " + _rack);

    	String s = _rack.substring(index, index2);
    	try
    	{
    		_rseq = Long.parseLong(s);
    	}
    	catch (NumberFormatException _)
    	{
    		throw new ServletParseException("Invalid RSeq number: " + s);
    	}

    	index = skipSpaces(index2);

    	index2 = _rack.indexOf(' ', index);
    	if (index2 < 0)
    		throw new ServletParseException("Invalid RAck header: " + _rack);

    	s = _rack.substring(index, index2);
    	try
    	{
    		_number = Long.parseLong(s);
    	}
    	catch (NumberFormatException _)
    	{
    		throw new ServletParseException("Invalid CSeq number: " + s);
    	}

    	index = skipSpaces(index2);

    	_method = _rack.substring(index).trim();

    	if (!SipGrammar.isToken(_method))
    		throw new ServletParseException("Invalid RAck method: " + _method);
	}

	private int skipSpaces(int start)
	{
		int i = start;
		while (_rack.charAt(i) == ' ')
			i++;
		return i;
	}

    public Buffer toBuffer()
    {
        return new ByteArrayBuffer(_rack);
    }

	public long getCSeq()
	{
		return _number;
	}

	public String getMethod()
	{
		return _method;
	}

	public long getRSeq()
	{
		return _rseq;
	}

	@Override
	public String toString()
	{
		return _rack;
	}

	@Override
	public Object clone() throws CloneNotSupportedException
	{
		return super.clone();
	}
}


text:
/**
 * This is a little tool to generate reference documentation of all math.js
 * functions under ./lib/functions. This is NO generic solution.
 *
 * The tool can parse documentation information from the block comment in the
 * functions code, and generate a markdown file with the documentation.
 */
var fs = require('fs');
var glob = require('glob');
var mkdirp = require('mkdirp');
var gutil = require('gulp-util');

// special cases for function syntax
var SYNTAX = {
  gcd: 'gcd(a, b)',
  log: 'log(x [, base])',
  lcm: 'lcm(a, b)',
  norm: 'norm(x [, p])',
  round: 'round(x [, n])',
  complex: 'complex(re, im)',
  matrix: 'matrix(x)',
  sparse: 'sparse(x)',
  unit: 'unit(x)',
  eval: 'eval(expr [, scope])',
  parse: 'parse(expr [, scope])',
  concat: 'concat(a, b, c, ... [, dim])',
  ones: 'ones(m, n, p, ...)',
  range: 'range(start, end [, step])',
  resize: 'resize(x, size [, defaultValue])',
  subset: 'subset(x, index [, replacement])',
  zeros: 'zeros(m, n, p, ...)',
  permutations: 'permutations(n [, k])',
  random: 'random([min, max])',
  randomInt: 'randomInt([min, max])',
  format: 'format(value [, precision])',
  'import': 'import(object, override)',
  print: 'print(template, values [, precision])'
};

var IGNORE_FUNCTIONS = {
  distribution: true
};

var IGNORE_WARNINGS = {
  seeAlso: ['help', 'intersect', 'clone', 'typeof', 'chain'],
  parameters: ['parser'],
  returns: ['forEach']
};

/**
 * Extract JSON documentation from the comments in a file with JavaScript code
 * @param {String} name    Function name
 * @param {String} code    javascript code containing a block comment
 *                         describing a math.js function
 * @return {Object} doc    json document
 */
function generateDoc(name, code) {
  // get block comment from code
  var match = /\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\//.exec(code);

  if (!match) {
    return null;
  }

  // get text content inside block comment
  var comment = match[0].replace('/**', '')
      .replace('*/', '')
      .replace(/\n\s*\* ?/g, '\n')
      .replace(/\r/g, '');

  var lines = comment.split('\n'),
      line = '';

  // get next line
  function next () {
    line = lines.shift();
  }

  // returns true if current line is empty
  function empty() {
    return !line || !line.trim();
  }

  // returns true if there still is a current line
  function exists() {
    return line !== undefined;
  }

  // returns true if current line is a header like 'Syntax:'
  function isHeader() {
    return /^(Name|Syntax|Description|Examples|See also)/i.test(line);
  }

  // returns true if the current line starts with an annotation like @param
  function isAnnotation() {
    return /^@/.test(line);
  }

  function skipEmptyLines () {
    while (exists() && empty()) next();
  }

  function stripLeadingSpaces(lines) {
    var spaces = null;
    lines.forEach(function (line) {
      var match = /^ +/.exec(line);
      var s = match && match[0] && match[0].length;
      if (s > 0 && (spaces == null || s < spaces)) {
        spaces = s;
      }
    });

    if (spaces) {
      lines.forEach(function (line, index) {
        lines[index] = line.substring(spaces);
      })
    }
  }

  function parseDescription () {
    var description = '';

    while (exists() && !isHeader() && !isAnnotation()) {
      description += line + '\n';

      next();
    }

    // remove trailing returns
    while (description.charAt(description.length - 1) == '\n') {
      description = description.substring(0, description.length - 1);
    }

    doc.description = description;
  }

  function parseSyntax() {
    if (/^syntax/i.test(line)) {
      next();
      skipEmptyLines();

      while (exists() && !empty()) {
        doc.syntax.push(line);
        next();
      }
      stripLeadingSpaces(doc.syntax);

      skipEmptyLines();

      return true;
    }
    return false;
  }

  function parseWhere() {
    if (/^where/i.test(line)) {
      next();
      skipEmptyLines();

      while (exists() && !empty()) {
        doc.where.push(line);
        next();
      }

      skipEmptyLines();

      return true;
    }
    return false;
  }

  function parseExamples() {
    if (/^example/i.test(line)) {
      next();
      skipEmptyLines();

      while (exists() && (empty() || line.charAt(0) == ' ')) {
        doc.examples.push(line);
        next();
      }
      stripLeadingSpaces(doc.examples);

      if (doc.examples[doc.examples.length - 1].trim() == '') doc.examples.pop();

      skipEmptyLines();

      return true;
    }
    return false;
  }

  function parseSeeAlso() {
    if (/^see also/i.test(line)) {
      next();
      skipEmptyLines();

      while (exists() && !empty()) {
        var names = line.split(',');
        doc.seeAlso = doc.seeAlso.concat(names.map(function (name) {
          return name.trim();
        }));
        next();
      }

      skipEmptyLines();

      return true;
    }
    return false;
  }

  function parseParameters() {
    var count = 0;
    do {
      var match = /\s*@param\s*\{(.*)}\s*\[?(\w*)]?\s*(.*)?$/.exec(line);
      if (match) {
        next();

        count++;
        var annotation = {
          name: match[2] || '',
          description: (match[3] || '').trim(),
          types: match[1].split('|').map(function (t) {
            return t.trim();
          })
        };
        doc.parameters.push(annotation);

        // TODO: this is an ugly hack to extract the default value
        var index = annotation.description.indexOf(']');
        var defaultValue = null;
        if (index != -1) {
          defaultValue = annotation.description.substring(1, index).trim();
          annotation.description = annotation.description.substring(index + 1).trim();
        }

        // multi line description
        while (exists() && !empty() && /^\s{6}/.test(line)) {
          annotation.description += ' ' + line.trim();
          next();
        }

        if (defaultValue !== null) {
          annotation.description += ' Default value: ' + defaultValue + '.';
        }
      }
    } while (match);

    return count > 0;
  }

  function parseReturns() {
    var match = /\s*@returns?\s*\{(.*)}\s*(.*)?$/.exec(line);
    if (match) {
      next();

      doc.returns = {
        description: match[2] || '',
        types: match[1].split('|').map(function (t) {
          return t.trim();
        })
      };

      // multi line description
      while (exists() && !empty() && /^\s{6}/.test(line)) {
        doc.returns.description += ' ' + line.trim();
        next();
      }

      return true;
    }
    return false;
  }

  // initialize doc
  var doc = {
    name: name,
    description: '',
    syntax: [],
    where: [],
    examples: [],
    seeAlso: [],
    parameters: [],
    returns: null
  };

  next();
  skipEmptyLines();
  parseDescription();

  do {
    skipEmptyLines();

    var handled = parseSyntax() ||
        parseWhere() ||
        parseExamples() ||
        parseSeeAlso() ||
        parseParameters() ||
        parseReturns();

    if (!handled) {
      // skip this line, no one knows what to do with it
      next();
    }
  } while (exists());

  return doc;
}

/**
 * Validate whether all required fields are available in given doc
 * @param {Object} doc
 * @return {String[]} issues
 */
function validateDoc (doc) {
  var issues = [];

  function ignore(field) {
    return IGNORE_WARNINGS[field].indexOf(doc.name) !== -1
  }

  if (!doc.name) {
    issues.push('name missing in document');
  }

  if (!doc.description) {
    issues.push('function "' + doc.name + '": description missing');
  }

  if (!doc.syntax || doc.syntax.length == 0) {
    issues.push('function "' + doc.name + '": syntax missing');
  }

  if (!doc.examples || doc.examples.length == 0) {
    issues.push('function "' + doc.name + '": examples missing');
  }

  if (doc.parameters && doc.parameters.length) {
    doc.parameters.forEach(function (param, index) {
      if (!param.name || !param.name.trim()) {
        issues.push('function "' + doc.name + '": name missing of parameter ' + index + '');
      }
      if (!param.description || !param.description.trim()) {
        issues.push('function "' + doc.name + '": description missing for parameter ' + (param.name || index));
      }
      if (!param.types || !param.types.length) {
        issues.push('function "' + doc.name + '": types missing for parameter ' + (param.name || index));
      }
    });
  }
  else {
    if (!ignore('parameters')) {
      issues.push('function "' + doc.name + '": parameters missing');
    }
  }

  if (doc.returns) {
    if (!doc.returns.description || !doc.returns.description.trim()) {
      issues.push('function "' + doc.name + '": description missing of returns');
    }
    if (!doc.returns.types || !doc.returns.types.length) {
      issues.push('function "' + doc.name + '": types missing of returns');
    }
  }
  else {
    if (!ignore('returns')) {
      issues.push('function "' + doc.name + '": returns missing');
    }
  }

  if (!doc.seeAlso || doc.seeAlso.length == 0) {
    if (!ignore('seeAlso')) {
      issues.push('function "' + doc.name + '": seeAlso missing');
    }
  }

  return issues;
}

/**
 * Generate markdown
 * @param {Object} doc          A JSON object generated with generateDoc()
 * @param {Object} functions    All functions, used to generate correct links
 *                              under seeAlso
 * @returns {string} markdown   Markdown contents
 */
function generateMarkdown (doc, functions) {
  var text = '';

  // TODO: should escape HTML characters in text

  text += '# Function ' + doc.name + '\n\n';

  text += doc.description + '\n\n\n';

  if (doc.syntax && doc.syntax.length) {
    text += '## Syntax\n\n' +
        '```js\n' +
        doc.syntax.join('\n') +
        '\n```\n\n';
  }

  if (doc.where && doc.where.length) {
    text += '### Where\n\n' + doc.where.join('\n') + '\n\n';
  }

  text += '### Parameters\n\n' +
      'Parameter | Type | Description\n' +
      '--------- | ---- | -----------\n' +
      doc.parameters.map(function (p) {
        return '`' + p.name + '` | ' +
            (p.types ? p.types.join(' | ') : '') + ' | ' +
            p.description
      }).join('\n') +
      '\n\n';

  if (doc.returns) {
    text += '### Returns\n\n' +
        'Type | Description\n' +
        '---- | -----------\n' +
        (doc.returns.types ? doc.returns.types.join(' | ') : '') + ' | ' + doc.returns.description +
        '\n\n\n';
  }

  if (doc.examples && doc.examples.length) {
    text += '## Examples\n\n' +
        '```js\n' +
        doc.examples.join('\n') +
        '\n```\n\n\n';
  }

  if (doc.seeAlso && doc.seeAlso.length) {
    text += '## See also\n\n' +
        doc.seeAlso.map(function (name) {
          return '[' + name + '](' + name + '.md)';
        }).join(',\n') +
        '\n';
  }

  text += '\n\n';

  text += '<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->\n';

  return text;
}

/**
 * Iterate over all source files and generate markdown documents for each of them
 * @param {String} inputPath
 * @param {String} outputPath
 */
function iteratePath (inputPath, outputPath) {
  if (!fs.existsSync(outputPath)) {
    mkdirp.sync(outputPath);
  }

  glob(inputPath + '**/*.js', null, function (err, files) {
    // generate path information for each of the files
    var functions = {}; // TODO: change to array

    files.forEach(function (fullPath) {
      var path = fullPath.split('/');
      var name = path.pop().replace(/.js$/, '');
      var functionIndex = path.indexOf('function');
      var category;

      // Note: determining whether a file is a function and what it's category
      // is is a bit tricky and quite specific to the structure of the code,
      // we reckon with some edge cases here.
      if (path.indexOf('docs') === -1 && functionIndex !== -1) {
        if (path.indexOf('expression') !== -1) {
          category = 'expression';
        }
        else if (path[0] === '.' && path[1] === 'lib' && path[2] === 'type' && path[4] === 'function') {
          category = 'construction';
        }
        else {
          category = path[functionIndex + 1];
        }
      }
      else if (path.join('/') === './lib/type') {
        // for boolean.js, number.js, string.js
        category = 'construction';
      }

      if (IGNORE_FUNCTIONS[name]) {
        category = null;
      }

      if (category) {
        functions[name] = {
          name: name,
          category: category,
          fullPath: fullPath,
          relativePath: fullPath.substring(inputPath.length)
        };
      }
    });

    // loop over all files, generate a doc for each of them
    var issues = [];
    for (var name in functions) {
      if (functions.hasOwnProperty(name)) {
        var fn = functions[name];
        var code = String(fs.readFileSync(fn.fullPath));

        var isFunction = code.indexOf('exports.name') !== -1
            && code.indexOf('exports.factory') !== -1
            && code.indexOf('exports.path') === -1;
        var doc = isFunction && generateDoc(name, code);

        if (isFunction && doc) {
          fn.doc = doc;
          issues = issues.concat(validateDoc(doc));
          var markdown = generateMarkdown(doc, functions);
          fs.writeFileSync(outputPath + '/' + fn.name + '.md', markdown);
        }
        else {
          //gutil.log('Ignoring', fn.fullPath);
          delete functions[name];
        }
      }
    }

    /**
     * Helper function to generate a markdown list entry for a function.
     * Used to generate both alphabetical and categorical index pages.
     * @param {string} name Function name
     * @returns {string}    Returns a markdown list entry
     */
    function functionEntry (name) {
      var fn = functions[name];
      var syntax = SYNTAX[name] || fn.doc && fn.doc.syntax && fn.doc.syntax[0] || name;
      syntax = syntax
          .replace(/^math\./, '')
          .replace(/\s+\/\/.*$/, '')
          .replace(/;$/, '');
      return '- [' + syntax + '](' + name + '.md)';
    }

    // generate alphabetical index page
    var alphabetical = '# Function reference (alphabetical)\n\n';
    alphabetical += Object.keys(functions).sort().map(functionEntry).join('\n');
    fs.writeFileSync(outputPath + '/alphabetical.md', alphabetical);

    // generate categorical index page
    var categories = {};
    Object.keys(functions).forEach(function (name) {
      var fn = functions[name];
      var category = categories[fn.category];
      if (!category) {
        categories[fn.category] = {};
      }
      categories[fn.category][name] = fn;
    });
    var categorical = '# Function reference (categorical)\n\n';
    categorical += Object.keys(categories).sort().map(function (category) {
      var functions = categories[category];
      return '## ' + category + '\n\n' +
        Object.keys(functions).sort().map(functionEntry).join('\n') + '\n';
    }).join('\n');
    fs.writeFileSync(outputPath + '/categorical.md', categorical);

    // output all issues
    if (issues.length) {
      issues.forEach(function (issue) {
        gutil.log('Warning: ' + issue);
      });
      gutil.log(issues.length + ' warnings');
    }
  });
}

// exports
exports.iteratePath = iteratePath;
exports.generateDoc = generateDoc;
exports.validateDoc = validateDoc;
exports.generateMarkdown = generateMarkdown;


text:
  $(document).foundation();
	$(document).ready(function () {
    function inIframe() {
      try {
        if (window.self !== window.top) {
          //IN IFRAME
          $('.iFrameSection').hide();
          window.location = 'login.aspx';
        }
        else {
          //NOT IN IFRAME
        }
      } catch (e) {
        //IN IFRAME
        $('.iFrameSection').hide();
        window.location = 'login.aspx';
      }
    }
    inIframe()

    // Toggle menu expansion when link is clicked on mobile
    $('#crm-menu a').click(function () {
      if ($('[data-responsive-toggle]').is(':visible')) {
        $('#crm-menu').toggle();
      }
    });

    // Type Animation
    $(function () {
      $("#typed").typed({
        stringsElement: $('#typed-strings'),
        typeSpeed: 30,
        startDelay: 700,
        backSpeed: 50,
        backDelay: 500,
        loop: true,
        cursorChar: "|",
        contentType: 'html', // or text
        loopCount: 5 // defaults to false for infinite loop
      });
    });

    // Set src of youtube video iframe
    var setPromoVideoSrc = function () { $('#video iframe').attr('src', 'https://www.youtube.com/embed/tTzWVQs1-8A?rel=0&autoplay=1'); }
    var removePromoVideoSrc = function () { $('#video iframe').attr('src', ''); }

    // Set promo video to autoplay when "watch video" link is clicked
    $('[data-open=video]').on('click', function () {
      setPromoVideoSrc();
    });

    // Stop promo video when modal is closed
    $('#video').on('closed.zf.reveal', function (event) {
      removePromoVideoSrc();
    });

    //Get URL query string
    function getQueryVariable(variable) {
      var query = window.location.search.substring(1);
      var vars = query.split("&");
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) { return pair[1]; }
      }
      return (false);
    }
    // Show speaker modal if query string variable exists
    var id = getQueryVariable('id');

    var scrollToGetStartedSection = function () {
      var target = $('#get-started');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }

    var toggleFreeTrialForm = function () {
      $('[data-free-trial-form]').fadeToggle();
      $('[data-toggle-free-trial-form]').toggleClass('is-active');
      $('[data-get-started-background]').toggleClass('is-active');
      $('[data-free-trial-form] input:text:visible:first').focus();
    }

    // Toggle Free Trial Form when all free trial buttons are clicked
    $('[data-toggle-free-trial-form]').on('click', function (e) {
      e.preventDefault();
      toggleFreeTrialForm();
    });

    // Execute functions based on query string
    switch (id) {
      case 'free-trial':
        scrollToGetStartedSection();
        toggleFreeTrialForm();
    }

    // Feature List Accordion - For Mobile
    // Toggle Image When List Item is Clicked
    $("[data-mobile-feature]").click(function () {
      var value;
      switch ($("[data-mobile-feature]").index(this)) {
        case 0:
          value = "goals";
          break;
        case 1:
          value = "pac";
          break;
        case 2:
          value = "contacts";
          break;
        case 3:
          value = "pop-by";
          break;
        case 4:
          value = "to-do";
          break;
        case 5:
          value = "calendar";
          break;
        case 6:
          value = "resources";
          break;
      }
      $("[data-mobile-feature-screen]").attr('src', 'assets/images/screens/mobile/' + value + '-skewed.png');
    });

    // Feature List Accordion - for Desktop
    // Toggle Image When List Item is Clicked
    $("[data-desktop-feature]").click(function () {
      var value;
      switch ($("[data-desktop-feature]").index(this)) {
        case 0:
          value = "dashboard";
          break;
        case 1:
          value = "pac";
          break;
        case 2:
          value = "relationships";
          break;
        case 3:
          value = "marketing";
          break;
        case 4:
          value = "business";
          break;
        case 5:
          value = "calendar";
          break;
        case 6:
          value = "groups";
          break;
      }
      $("[data-desktop-feature-screen]").attr('src', 'assets/images/screens/desktop/' + value + '-skewed.png');
    });

    // Feature List Accordion - For Teams
    // Toggle Image When List Item is Clicked
    $("[data-teams-feature]").click(function () {
      var value;
      switch ($("[data-teams-feature]").index(this)) {
        case 0:
          value = "dashboard";
          break;
        case 1:
          value = "activity-report";
          break;
        case 2:
          value = "activity-report";
          break;
        case 3:
          value = "transaction-report";
          break;
        case 4:
          value = "lead-progress-report";
          break;
        case 5:
          value = "contacts";
          break;
        case 6:
          value = "marketing";
          break;
      }
      $("[data-teams-feature-screen]").attr('src', 'assets/images/screens/teams/teams-' + value + '-skewed.jpg');
    });

    // Toggle visibility of content based on date
    $("[data-show-date], [data-hide-date]").each(function () {
      var showDateValue = $(this).data("show-date");
      var hideDateValue = $(this).data("hide-date");
      var showDate = new Date(showDateValue);
      var hideDate = new Date(hideDateValue);
      var today = new Date();
      // Hide all elements with data-show-date and data-hide-date attributes
      $(this).hide();
      // If element only has show-date attribute
      if ($(this).attr('data-show-date')) {
        if (today >= showDate) {
          $(this).show();
        } else {
          $(this).remove();
        }
      }
      // If element only has hide-date attribute
      if ($(this).attr('data-hide-date')) {
        if (today <= hideDate) {
          $(this).show();
        } else {
          $(this).remove();
        }
      }
      // If element has show-date and hide-date attribute
      if ($(this).attr('data-show-date') && $(this).attr('data-hide-date')) {
        if (today >= showDate && today <= hideDate) {
          $(this).show();
        } else {
          $(this).remove();
        }
      }
    });

  });


text:
using System.Collections.Generic;
using MobileSecondHand.API.Models.Shared.Enumerations;
using MobileSecondHand.API.Models.Shared.Location;

namespace MobileSecondHand.Models.Settings
{
	public class AppSettingsModel
	{
		public CoordinatesForAdvertisementsModel LocationSettings { get; set; } = new CoordinatesForAdvertisementsModel();
		public IDictionary<int, string> Keywords { get; set; } = new Dictionary<int, string>();
		public List<ClothSize> Sizes { get; set; } = new List<ClothSize>();
		public bool ChatDisabled { get; set; }
		public bool NotificationsDisabled { get; set; }
		public string UserName { get; set; }
		public string ProfileImagePath { get; set; }
	}
}


text:
import {ScrollView, TextInput, contentView} from 'tabris';

const scrollView = new ScrollView({
  left: 0, top: 0, right: 0, bottom: 0
}).appendTo(contentView);

createTextInput('default', 'multiline');
createTextInput('send', 'multiline');
createTextInput('done', 'multiline');

const textInput = createTextInput();
createTextInput('send');
createTextInput('go');
createTextInput('search');
createTextInput('done').onAccept(() => textInput.focused = false);
createTextInput('next');
createTextInput('next').onAccept(() => textInput.focused = true);
createTextInput();

/**
 * @param {TextInput['enterKeyType']} enterKeyType
 * @param {TextInput['type']} type
 */
function createTextInput(enterKeyType = 'default', type = 'default') {
  return new TextInput({
    top: 'prev() 16', left: '16', right: '16',
    message: message(enterKeyType, type),
    type,
    enterKeyType
  }).onAccept(() => console.log(message(enterKeyType, type)))
    .appendTo(scrollView);
}

function message(enterKeyType, type) {
  return `Enter key: ${enterKeyType} (${type === 'default' ? 'singleline' : type})`;
}


text:
/*
 * SearchPage Messages
 *
 * This contains all the text for the SearchPage component.
 */
import { defineMessages } from 'react-intl';

export default defineMessages({
  header: {
    id: 'app.containers.SearchPage.header',
    defaultMessage: 'This is SearchPage container !',
  },
  overall_status: {
    id: 'app.containers.SearchPage.status',
    defaultMessage: 'status',
  },
  start_date: {
    id: 'app.containers.SearchPage.start_date',
    defaultMessage: 'started',
  },
  completion_date: {
    id: 'app.containers.SearchPage.completed',
    defaultMessage: 'completed',
  },
  average_rating: {
    id: 'app.containers.SearchPage.average_rating',
    defaultMessage: 'overall rating',
  },
});


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.operator.scalar.timestamptz;

import io.airlift.slice.Slice;
import io.prestosql.spi.connector.ConnectorSession;
import io.prestosql.spi.function.Description;
import io.prestosql.spi.function.LiteralParameters;
import io.prestosql.spi.function.ScalarFunction;
import io.prestosql.spi.function.SqlType;
import io.prestosql.spi.type.LongTimestampWithTimeZone;
import io.prestosql.spi.type.StandardTypes;

import static io.prestosql.operator.scalar.DateTimeFunctions.dateFormat;
import static io.prestosql.spi.type.DateTimeEncoding.unpackMillisUtc;
import static io.prestosql.spi.type.TimeZoneKey.getTimeZoneKey;
import static io.prestosql.type.DateTimes.roundToEpochMillis;
import static io.prestosql.util.DateTimeZoneIndex.getChronology;
import static io.prestosql.util.DateTimeZoneIndex.unpackChronology;

@ScalarFunction
@Description("Formats the given timestamp by the given format")
public class DateFormat
{
    private DateFormat() {}

    @LiteralParameters({"x", "p"})
    @SqlType(StandardTypes.VARCHAR)
    public static Slice format(ConnectorSession session, @SqlType("timestamp(p) with time zone") long packedEpochMillis, @SqlType("varchar(x)") Slice formatString)
    {
        return dateFormat(unpackChronology(packedEpochMillis), session.getLocale(), unpackMillisUtc(packedEpochMillis), formatString);
    }

    @LiteralParameters({"x", "p"})
    @SqlType(StandardTypes.VARCHAR)
    public static Slice format(ConnectorSession session, @SqlType("timestamp(p) with time zone") LongTimestampWithTimeZone timestamp, @SqlType("varchar(x)") Slice formatString)
    {
        return dateFormat(getChronology(getTimeZoneKey(timestamp.getTimeZoneKey())), session.getLocale(), roundToEpochMillis(timestamp), formatString);
    }
}


text:
package org.elasticsearch.xpack.core.security;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.search.ClearScrollRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequest;
import org.elasticsearch.action.support.ContextPreservingActionListener;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.search.SearchHit;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;

public final class ScrollHelper {

    private static final Logger LOGGER = LogManager.getLogger(ScrollHelper.class);
    private ScrollHelper() {}

    /**
     * This method fetches all results for the given search request, parses them using the given hit parser and calls the
     * listener once done.
     */
    public static <T> void fetchAllByEntity(Client client, SearchRequest request, final ActionListener<Collection<T>> listener,
                                            Function<SearchHit, T> hitParser) {
        final List<T> results = new ArrayList<>();
        if (request.scroll() == null) { // we do scroll by default lets see if we can get rid of this at some point.
            throw new IllegalArgumentException("request must have scroll set");
        }
        final Consumer<SearchResponse> clearScroll = (response) -> {
            if (response != null && response.getScrollId() != null) {
                ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
                clearScrollRequest.addScrollId(response.getScrollId());
                client.clearScroll(clearScrollRequest, ActionListener.wrap((r) -> {}, e ->
                    LOGGER.warn(new ParameterizedMessage("clear scroll failed for scroll id [{}]", response.getScrollId()), e)
                ));
            }
        };
        // This function is MADNESS! But it works, don't think about it too hard...
        // simon edit: just watch this if you got this far https://www.youtube.com/watch?v=W-lF106Dgk8
        client.search(request, new ContextPreservingActionListener<>(client.threadPool().getThreadContext().newRestorableContext(true),
                new ActionListener<SearchResponse>() {
            private volatile SearchResponse lastResponse = null;

            @Override
            public void onResponse(SearchResponse resp) {
                try {
                    lastResponse = resp;
                    if (resp.getHits().getHits().length > 0) {
                        for (SearchHit hit : resp.getHits().getHits()) {
                            final T oneResult = hitParser.apply(hit);
                            if (oneResult != null) {
                                results.add(oneResult);
                            }
                        }

                        if (results.size() > resp.getHits().getTotalHits()) {
                            clearScroll.accept(lastResponse);
                            listener.onFailure(new IllegalStateException("scrolling returned more hits [" + results.size()
                                    + "] than expected [" + resp.getHits().getTotalHits() + "] so bailing out to prevent unbounded "
                                    + "memory consumption."));
                        } else if (results.size() == resp.getHits().getTotalHits()) {
                            clearScroll.accept(resp);
                            // Finally, return the list of the entity
                            listener.onResponse(Collections.unmodifiableList(results));
                        } else {
                            SearchScrollRequest scrollRequest = new SearchScrollRequest(resp.getScrollId());
                            scrollRequest.scroll(request.scroll().keepAlive());
                            client.searchScroll(scrollRequest, this);
                        }
                    } else {
                        clearScroll.accept(resp);
                        // Finally, return the list of the entity
                        listener.onResponse(Collections.unmodifiableList(results));
                    }
                } catch (Exception e){
                    onFailure(e); // lets clean up things
                }
            }

            @Override
            public void onFailure(Exception t) {
                try {
                    // attempt to clear the scroll request
                    clearScroll.accept(lastResponse);
                } finally {
                    if (t instanceof IndexNotFoundException) {
                        // since this is expected to happen at times, we just call the listener with an empty list
                        listener.onResponse(Collections.<T>emptyList());
                    } else {
                        listener.onFailure(t);
                    }
                }
            }
        }));
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
StripLineComments (Apache Ant API)
</TITLE>

<META NAME="date" CONTENT="2013-03-05">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.tools.ant.filters

Class StripLineComments

java.lang.Object
  java.io.Reader
      java.io.FilterReader
          org.apache.tools.ant.filters.BaseFilterReader
              org.apache.tools.ant.filters.BaseParamFilterReader
                  org.apache.tools.ant.filters.StripLineComments

All Implemented Interfaces:
java.io.Closeable, java.lang.Readable, ChainableReader, Parameterizable

public final class StripLineComments
extends BaseParamFilterReader
implements ChainableReader

This filter strips line comments.

 Example:

<striplinecomments>
   <comment value="#"/>
   <comment value="--"/>
   <comment value="REM "/>
   <comment value="rem "/>
   <comment value="//"/>
 </striplinecomments>

 Or:

<filterreader
      classname="org.apache.tools.ant.filters.StripLineComments">
   <param type="comment" value="#"/>
   <param type="comment" value="--"/>
   <param type="comment" value="REM "/>
   <param type="comment" value="rem "/>
   <param type="comment" value="//"/>
 </filterreader>

Nested Class Summary

static class
StripLineComments.Comment

          The class that holds a comment representation.

Field Summary

Fields inherited from class java.io.FilterReader

in

Fields inherited from class java.io.Reader

lock

Constructor Summary

StripLineComments()

          Constructor for "dummy" instances.

StripLineComments(java.io.Reader in)

          Creates a new filtered reader.

Method Summary

 void
addConfiguredComment(StripLineComments.Comment comment)

          Adds a comment element to the list of prefixes.

 java.io.Reader
chain(java.io.Reader rdr)

          Creates a new StripLineComments using the passed in
 Reader for instantiation.

 int
read()

          Returns the next character in the filtered stream, only including
 lines from the original stream which don't start with any of the
 specified comment prefixes.

Methods inherited from class org.apache.tools.ant.filters.BaseParamFilterReader

getParameters, setParameters

Methods inherited from class org.apache.tools.ant.filters.BaseFilterReader

getInitialized, getProject, read, readFully, readLine, setInitialized, setProject, skip

Methods inherited from class java.io.FilterReader

close, mark, markSupported, ready, reset

Methods inherited from class java.io.Reader

read, read

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

StripLineComments

public StripLineComments()

Constructor for "dummy" instances.

See Also:
BaseFilterReader.BaseFilterReader()

StripLineComments

public StripLineComments(java.io.Reader in)

Creates a new filtered reader.

Parameters:
in - A Reader object providing the underlying stream.
           Must not be null.

Method Detail

read

public int read()
         throws java.io.IOException

Returns the next character in the filtered stream, only including
 lines from the original stream which don't start with any of the
 specified comment prefixes.

Overrides:
read in class java.io.FilterReader

Returns:
the next character in the resulting stream, or -1
 if the end of the resulting stream has been reached

Throws:

java.io.IOException - if the underlying stream throws an IOException
 during reading

addConfiguredComment

public void addConfiguredComment(StripLineComments.Comment comment)

Adds a comment element to the list of prefixes.

Parameters:
comment - The comment element to add to the
 list of comment prefixes to strip. Must not be null.

chain

public java.io.Reader chain(java.io.Reader rdr)

Creates a new StripLineComments using the passed in
 Reader for instantiation.

Specified by:
chain in interface ChainableReader

Parameters:
rdr - A Reader object providing the underlying stream.
            Must not be null.

Returns:
a new filter based on this configuration, but filtering
         the specified reader

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD