text:
# A0124863A
###### \java\savvytodo\logic\commands\ListCommand.java
``` java
/**
 * Lists all tasks or by category or by priority or by status in the task manager to the user.
 */
public class ListCommand extends Command {

    public static final String COMMAND_WORD = "list";

    public static final String MESSAGE_USAGE = COMMAND_WORD
            + ": List tasks based on priority or category or status or all. "
            + "Parameters: [p/PRIORITY_LEVEL] or [c/CATEGORY] or [s/STATUS] or none\n"
            + "Example: " + COMMAND_WORD + " "
            + "p/high or " + COMMAND_WORD + " "
            + "c/CS2103 or " + COMMAND_WORD + " "
            + "s/completed or just " + COMMAND_WORD;

    public static final String LIST_BY_CATEGORY_PRIORITY_SUCCESS = "Listed all tasks in ";
    public static final String LIST_ALL_SUCCESS = "Listed all tasks";

    private Optional<String> priority;
    private Optional<String> category;
    private Optional<String> status;

    public ListCommand(Optional<String> priority, Optional<String> category, Optional<String> status)
            throws IllegalValueException {
        this.priority = priority;
        this.category = category;
        this.status = status;
    }

    /**
     * Finds if the input category is in the category list of the task manager
     *
     */
    public Optional<Category> findCategoryInModel(String key) {
        for (Category c: model.getTaskManager().getCategoryList()) {
            if (c.categoryName.equalsIgnoreCase(key)) {
                return Optional.of(c);
            }
        }
        return Optional.empty();
    }

    @Override
    public CommandResult execute() throws CommandException {

        if (priority.isPresent()) {

            try {
                Priority inputPriority = new Priority(priority.get());
                model.updateFilteredTaskList(inputPriority.getPredicate());
                return new CommandResult(LIST_BY_CATEGORY_PRIORITY_SUCCESS + priority.get() + " priority");

            } catch (IllegalValueException ie) {
                throw new CommandException(Priority.MESSAGE_PRIORITY_CONSTRAINTS);
            }

        } else if (category.isPresent()) {

            Optional<Category> categoryInModel = findCategoryInModel(category.get());

            if (categoryInModel.isPresent()) {
                Category validCategory = categoryInModel.get();
                model.updateFilteredTaskList(validCategory.getPredicate());
                return new CommandResult(LIST_BY_CATEGORY_PRIORITY_SUCCESS + category.get());

            } else {
                throw new CommandException(Messages.MESSAGE_CATEGORY_NOT_EXISTS);
            }

        } else if (status.isPresent()) {

            try {
                Status inputStatus = new Status(status.get());
                model.updateFilteredTaskList(inputStatus.getPredicate());
                return new CommandResult("Listed all " + status.get() + " tasks");

            } catch (IllegalValueException ie) {
                throw new CommandException(Status.MESSAGE_STATUS_CONSTRAINTS);
            }

        } else {
            model.updateFilteredListToShowAll();
            return new CommandResult(LIST_ALL_SUCCESS);
        }
    }
}
```
###### \java\savvytodo\logic\commands\RedoCommand.java
``` java
/**
 * @author A0124863A
 * Redo an operation to the task manager
 *
 */
public class RedoCommand extends Command {
    public static final String COMMAND_WORD = "redo";
    public static final String MESSAGE_USAGE = COMMAND_WORD + ": Redo an operation to the task manager";
    public static final String MESSAGE_SUCCESS = "redo successfully";
    public static final String MESSAGE_FAILURE = "cannot redo";

    @Override
    public CommandResult execute() throws CommandException {
        assert model != null;
        try {
            model.redo();
            return new CommandResult(MESSAGE_SUCCESS);
        } catch (RedoFailureException e) {
            throw new CommandException(MESSAGE_FAILURE + ", " + e.getMessage());
        }
    }
}
```
###### \java\savvytodo\logic\commands\UndoCommand.java
``` java
/**
 * @author A0124863A
 * Undo an operation to the task manager
 */
public class UndoCommand extends Command {
    public static final String COMMAND_WORD = "undo";
    public static final String MESSAGE_USAGE = COMMAND_WORD + ": Undo an operation to the task manager";
    public static final String MESSAGE_SUCCESS = "undo successfully";
    public static final String MESSAGE_FAILURE = "cannot undo";

    @Override
    public CommandResult execute() throws CommandException {
        assert model != null;
        try {
            model.undo();
            return new CommandResult(MESSAGE_SUCCESS);
        } catch (UndoFailureException e) {
            throw new CommandException(MESSAGE_FAILURE + ", " + e.getMessage());
        }
    }

}
```
###### \java\savvytodo\logic\parser\ListCommandParser.java
``` java
/**
 * @author A0124863A
 * Parses input arguments and creates a new ListCommand object
 */
public class ListCommandParser {

    public Command parse(String args) {
        ArgumentTokenizer argsTokenizer = new ArgumentTokenizer(PREFIX_PRIORITY, PREFIX_CATEGORY, PREFIX_STATUS);
        argsTokenizer.tokenize(args);

        try {
            return new ListCommand(argsTokenizer.getValue(PREFIX_PRIORITY),
                    argsTokenizer.getValue(PREFIX_CATEGORY), argsTokenizer.getValue(PREFIX_STATUS));
        } catch (NoSuchElementException nsee) {
            return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListCommand.MESSAGE_USAGE));
        } catch (IllegalValueException ive) {
            return new IncorrectCommand(ive.getMessage());
        }

    }

}
```
###### \java\savvytodo\model\category\Category.java
``` java
    /**
     * Return predicate of the category to filter tasks
     * @return predicate expression to help filter tasks
     */
    public Predicate<ReadOnlyTask> getPredicate() {
        return (ReadOnlyTask task) -> task.getCategories().contains(this);
    }
```
###### \java\savvytodo\model\Model.java
``` java
    /** Updates the filter of the filtered task list to filter by the given predicate*/
    void updateFilteredTaskList(Predicate<ReadOnlyTask> predicate);

    /** Updates the filter of the filtered task list to filter by the given keywords*/
    void updateFilteredTaskList(Set<String> keywords);

```
###### \java\savvytodo\model\Model.java
``` java
    /** Undo an operation */
    void undo() throws UndoFailureException;

```
###### \java\savvytodo\model\Model.java
``` java
    /** Redo an operation */
    void redo() throws RedoFailureException;

```
###### \java\savvytodo\model\Model.java
``` java
    /** Record a mark or unmark for undo*/
    void recordMark(int index);

}
```
###### \java\savvytodo\model\ModelManager.java
``` java
    @Override
    public void resetData(ReadOnlyTaskManager newData) {
        UndoClearOperation undoClear = new UndoClearOperation(taskManager, newData);
        undoRedoOpCentre.storeUndoOperation(undoClear);
        undoRedoOpCentre.resetRedo();

        taskManager.resetData(newData);

        indicateTaskManagerChanged();
    }
```
###### \java\savvytodo\model\ModelManager.java
``` java
    @Override
    public synchronized void deleteTask(ReadOnlyTask target) throws TaskNotFoundException {
        try {
            taskManager.removeTask(target);
        } catch (DuplicateTaskException e) {
            e.printStackTrace();
        }

        UndoDeleteOperation undoDelete = new UndoDeleteOperation(target);
        undoRedoOpCentre.storeUndoOperation(undoDelete);
        undoRedoOpCentre.resetRedo();

        indicateTaskManagerChanged();
    }

```
###### \java\savvytodo\model\ModelManager.java
``` java
    @Override
    public synchronized void addTask(Task task) throws UniqueTaskList.DuplicateTaskException {
        taskManager.addTask(task);
        UndoAddOperation undoAdd = new UndoAddOperation(task);
        undoRedoOpCentre.storeUndoOperation(undoAdd);
        undoRedoOpCentre.resetRedo();

        updateFilteredListToShowAll();
        indicateTaskManagerChanged();
    }

```
###### \java\savvytodo\model\ModelManager.java
``` java
    @Override
    public void updateTask(int filteredTaskListIndex, ReadOnlyTask editedTask)
            throws UniqueTaskList.DuplicateTaskException {
        assert editedTask != null;
        Task originalTask = new Task(getFilteredTasks(editedTask.getType()).get(filteredTaskListIndex));
        int taskManagerIndex = getFilteredTasks(originalTask.getType()).getSourceIndex(filteredTaskListIndex);
        UndoEditOperation undoEdit = new UndoEditOperation(taskManagerIndex, originalTask, editedTask);
        undoRedoOpCentre.storeUndoOperation(undoEdit);
        undoRedoOpCentre.resetRedo();

        taskManager.updateTask(taskManagerIndex, editedTask);
        indicateTaskManagerChanged();
    }

```
###### \java\savvytodo\model\ModelManager.java
``` java
    @Override
    public void recordMark(int numToUnmark) {
        UndoMarkOperation undoMark = new UndoMarkOperation(numToUnmark);
        undoRedoOpCentre.storeUndoOperation(undoMark);
    }

```
###### \java\savvytodo\model\ModelManager.java
``` java
    @Override
    public void undo() throws UndoFailureException {
        try {
            Operation undo = undoRedoOpCentre.getUndoOperation();
            if (undo.getClass().isAssignableFrom(UndoMarkOperation.class)) {
                UndoMarkOperation undoMark = (UndoMarkOperation) undo;
                undoMark.setTaskManager(taskManager);
                undoMark.setUndoRedoOperationCentre(undoRedoOpCentre);
                undoMark.execute();
                indicateTaskManagerChanged();

            } else {
                undo.setTaskManager(taskManager);
                undo.execute();
                indicateTaskManagerChanged();
            }
        } catch (EmptyStackException e) {
            throw new UndoFailureException("empty stack");
        } catch (CommandException e) {
            throw new UndoFailureException(e.getMessage());
        }
    }

```
###### \java\savvytodo\model\ModelManager.java
``` java
    @Override
    public void redo() throws RedoFailureException {
        try {
            Operation redo = undoRedoOpCentre.getRedoOperation();
            if (redo.getClass().isAssignableFrom(RedoMarkOperation.class)) {
                RedoMarkOperation redoMark = (RedoMarkOperation) redo;
                redoMark.setTaskManager(taskManager);
                redoMark.setUndoRedoOperationCentre(undoRedoOpCentre);
                redoMark.execute();
                indicateTaskManagerChanged();

            } else {
                redo.setTaskManager(taskManager);
                redo.execute();
                indicateTaskManagerChanged();
            }
        } catch (EmptyStackException e) {
            throw new RedoFailureException("empty stack");
        } catch (CommandException e) {
            throw new RedoFailureException(e.getMessage());
        }
    }

```
###### \java\savvytodo\model\operations\exceptions\RedoFailureException.java
``` java
/**
 * @author A0124863A
 * Signals that redo cannot be performed
 */
public class RedoFailureException extends Exception {

    public RedoFailureException(String s) {
        super(s);
    }
}
```
###### \java\savvytodo\model\operations\exceptions\UndoFailureException.java
``` java
/**
 * @author A0124863A
 * Signals that undo cannot be performed
 */
public class UndoFailureException extends Exception {

    public UndoFailureException(String s) {
        super(s);
    }
}
```
###### \java\savvytodo\model\operations\Operation.java
``` java
/**
 * @author A0124863A
 * Represents undo command with hidden internal logic and the ability to be executed.
 */
public abstract class Operation {
    protected TaskManager taskManager;

    /**
     * Executes the command
     */
    public abstract void execute() throws CommandException;

    /**
     * @return the reverse operation just performed
     */
    public abstract Operation reverse();

    /**
     * Provides any needed dependencies to the command.
     * Commands making use of any of these should override this method to gain
     * access to the dependencies.
     */
    public void setTaskManager(TaskManager taskManager) {
        this.taskManager = taskManager;
    }

}
```
###### \java\savvytodo\model\operations\RedoMarkOperation.java
``` java
/**
* @author A0124863A
* Redo a mark operation by restoring the marked or unmarked task to its original
*/
public class RedoMarkOperation extends Operation {
    private int numToUnmark;
    private UndoRedoOperationCentre undoRedoOpCentre;

    public RedoMarkOperation(int numToUnmark) {
        this.numToUnmark = numToUnmark;
        this.setTaskManager(taskManager);
    }

    public void setUndoRedoOperationCentre(UndoRedoOperationCentre undoRedoOpCentre) {
        this.undoRedoOpCentre = undoRedoOpCentre;
    }

    @Override
    public void execute() throws CommandException {
        assert taskManager != null;
        assert undoRedoOpCentre != null;

        try {
            for (int i = 0; i < numToUnmark; i++) {
                Operation redo = undoRedoOpCentre.getRedoOperation();
                assert redo.getClass().isAssignableFrom(UndoEditOperation.class)
                        || redo.getClass().isAssignableFrom(UndoDeleteOperation.class);
                redo.setTaskManager(taskManager);
                redo.execute();
            }
        } catch (EmptyStackException e) {
            throw new CommandException(e.getMessage());
        } catch (CommandException e) {
            throw new CommandException(e.getMessage());
        }

        undoRedoOpCentre.storeUndoOperation(this.reverse());

    }

    @Override
    public Operation reverse() {
        return new UndoMarkOperation(numToUnmark);
    }

}
```
###### \java\savvytodo\model\operations\UndoAddOperation.java
``` java
/**
 * @author A0124863A
 * Undo an add operation by deleting the added task
 */
public class UndoAddOperation extends Operation {
    private Task task;

    public UndoAddOperation(Task task) {
        this.task = task;
    }
    @Override
    public void execute() throws CommandException {
        assert taskManager != null;
        try {
            taskManager.removeTask(task);
        } catch (TaskNotFoundException e) {
            assert false : "The target task cannot be missing";
        } catch (DuplicateTaskException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Operation reverse() {
        return new UndoDeleteOperation(task);
    }

}
```
###### \java\savvytodo\model\operations\UndoClearOperation.java
``` java
/**
 * @author A0124863A
 * Undo an clear operation by restoring the original
 */

public class UndoClearOperation extends Operation {
    private TaskManager currTaskManager;
    private TaskManager newTaskManager;
    public UndoClearOperation(ReadOnlyTaskManager currTaskManager, ReadOnlyTaskManager newTaskManager) {
        this.currTaskManager = new TaskManager(currTaskManager);
        this.newTaskManager = new TaskManager(newTaskManager);
    }

    @Override
    public void execute() {
        assert taskManager != null;
        taskManager.resetData(currTaskManager);
    }

    @Override
    public Operation reverse() {
        return new UndoClearOperation(newTaskManager, currTaskManager);
    }

}
```
###### \java\savvytodo\model\operations\UndoDeleteOperation.java
``` java
/**
 * @author A0124863A
 * Undo an delete operation by adding back the deleted task
 */
public class UndoDeleteOperation extends Operation {
    private Task task;

    public static final String MESSAGE_DUPLICATE_TASK = "This task already exists in the task manager";

    public UndoDeleteOperation(ReadOnlyTask task) {
        this.task = new Task(task);
    }

    @Override
    public void execute() throws CommandException {
        assert taskManager != null;
        try {
            taskManager.addTask(task);
        } catch (DuplicateTaskException e) {
            throw new CommandException(MESSAGE_DUPLICATE_TASK);
        }
    }

    @Override
    public Operation reverse() {
        return new UndoAddOperation(task);
    }

}
```
###### \java\savvytodo\model\operations\UndoEditOperation.java
``` java
/**
 * @author A0124863A
 * Undo an edit operation by restoring the edited task to its original
 */
public class UndoEditOperation extends Operation {
    private Task undoTask;
    private Task redoTask;
    private int index;

    public static final String MESSAGE_DUPLICATE_TASK = "This task already exists in the task manager";

    public UndoEditOperation(int index, ReadOnlyTask undoTask, ReadOnlyTask redoTask) {
        this.undoTask = new Task(undoTask);
        this.redoTask = new Task(redoTask);
        this.index = index;

    }

    @Override
    public void execute() throws CommandException {
        assert taskManager != null;
        try {
            taskManager.updateTask(index, undoTask);

        } catch (DuplicateTaskException e) {
            throw new CommandException(MESSAGE_DUPLICATE_TASK);
        }
    }

    @Override
    public Operation reverse() {
        return new UndoEditOperation(index, redoTask, undoTask);
    }

}
```
###### \java\savvytodo\model\operations\UndoMarkOperation.java
``` java
/**
* @author A0124863A
* Undo a mark operation by restoring the marked or unmarked task to its original
*/
public class UndoMarkOperation extends Operation {
    private int numToUnmark;
    private UndoRedoOperationCentre undoRedoOpCentre;

    public UndoMarkOperation(int numToUnmark) {
        this.numToUnmark = numToUnmark;
        this.setTaskManager(taskManager);
    }

    public void setUndoRedoOperationCentre(UndoRedoOperationCentre undoRedoOpCentre) {
        this.undoRedoOpCentre = undoRedoOpCentre;
    }

    @Override
    public void execute() throws CommandException {
        assert taskManager != null;
        assert undoRedoOpCentre != null;

        try {
            for (int i = 0; i < numToUnmark; i++) {
                Operation undo = undoRedoOpCentre.getUndoOperation();
                assert undo.getClass().isAssignableFrom(UndoEditOperation.class)
                        || undo.getClass().isAssignableFrom(UndoAddOperation.class);
                undo.setTaskManager(taskManager);
                undo.execute();
            }
        } catch (EmptyStackException e) {
            throw new CommandException(e.getMessage());
        } catch (CommandException e) {
            throw new CommandException(e.getMessage());
        }

        undoRedoOpCentre.storeRedoOperation(this.reverse());

    }

    @Override
    public Operation reverse() {
        return new RedoMarkOperation(numToUnmark);
    }

}
```
###### \java\savvytodo\model\operations\UndoRedoOperationCentre.java
``` java
/**
 * @author A0124863A
 * Class that stores the undo and redo commands
 */
public class UndoRedoOperationCentre {
    private Stack<Operation> undoStack = new Stack<Operation>();
    private Stack<Operation> redoStack = new Stack<Operation>();

    public void storeUndoOperation(Operation undoOperation) {
        undoStack.push(undoOperation);
    }

    public void storeRedoOperation(Operation redoOperation) {
        redoStack.push(redoOperation);
    }

    public void resetRedo() {
        redoStack.clear();
    }

    public Operation getUndoOperation() throws EmptyStackException {
        Operation undo = undoStack.pop();
        if (undo.getClass().isAssignableFrom(UndoMarkOperation.class)) {
            return undo;
        } else {
            Operation redo = undo.reverse();
            redoStack.push(redo);
            return undo;
        }
    }

    public Operation getRedoOperation() throws EmptyStackException {
        Operation redo = redoStack.pop();
        if (redo.getClass().isAssignableFrom(UndoMarkOperation.class)) {
            return redo;
        } else {
            Operation undo = redo.reverse();
            undoStack.push(undo);
            return redo;
        }
    }

}
```
###### \java\savvytodo\model\task\Priority.java
``` java
    /**
     * Return predicate of the priority to filter tasks
     * @return predicate expression to help filter tasks
     */
    public Predicate<ReadOnlyTask> getPredicate() {
        return (ReadOnlyTask task) -> task.getPriority().equals(this);
    }
```
###### \java\savvytodo\model\task\Status.java
``` java
    public Status(String status) throws IllegalValueException {
        if (status.equalsIgnoreCase(MESSAGE_STATUS_COMPLETED)) {
            value = COMPLETED;
        } else if (status.equalsIgnoreCase(MESSAGE_STATUS_ONGOING)) {
            value = ONGOING;
        } else {
            throw new IllegalValueException(MESSAGE_STATUS_CONSTRAINTS);
        }
    }

```
###### \java\savvytodo\model\task\Status.java
``` java
    public Predicate<ReadOnlyTask> getPredicate() {
        return (ReadOnlyTask task) -> task.isCompleted().equals(this);
    }

```
###### \java\savvytodo\model\task\Task.java
``` java
    @Override
    public TimeStamp getTimeStamp() {
        return timeStamp;
    }

    public void setTimeStamp(TimeStamp timeStamp) {
        assert timeStamp != null;
        this.timeStamp = timeStamp;
    }

```
###### \java\savvytodo\model\task\TimeStamp.java
``` java
/**
 * Represents a time stamp of when the task is added
 */
public class TimeStamp {
    private LocalDateTime dateTimeAdded;
    public static final LocalDateTime DEFAULT_DATE_TIME = LocalDateTime.of(2017, 04, 15, 11, 30);

    public TimeStamp() {
        dateTimeAdded = LocalDateTime.now();
    }

    public TimeStamp(TimeStamp timeStamp) {
        dateTimeAdded = timeStamp.getDateTimeAdded();
    }

    public TimeStamp(LocalDateTime dateTime) {
        dateTimeAdded = dateTime;
    }

    public LocalDateTime getDateTimeAdded() {
        return dateTimeAdded;
    }

    @Override
    public String toString() {
        return dateTimeAdded.toString();
    }

    @Override
    public boolean equals(Object other) {
        if (other == null) {
            return false;
        }

        if (this == other) {
            return true;
        }

        if (!(other instanceof TimeStamp)) {
            return false;
        }

        TimeStamp otherTimeStamp = (TimeStamp) other;
        if (!dateTimeAdded.equals(otherTimeStamp.getDateTimeAdded())) {
            return false;
        }

        return true;

    }
}
```
###### \java\savvytodo\model\task\UniqueTaskList.java
``` java
    /**
     * Adds a task to the list, list is then sorted by the data and time it was added
     *
     * @throws DuplicateTaskException if the task to add is a duplicate of an existing task in the list.
     */
    public void add(Task toAdd) throws DuplicateTaskException {
        assert toAdd != null;
        if (contains(toAdd)) {
            throw new DuplicateTaskException(toAdd);
        }
        internalList.add(toAdd);
        internalList.sort((ReadOnlyTask task1, ReadOnlyTask task2) -> task1.getTimeStamp()
                .getDateTimeAdded().compareTo(task2.getTimeStamp().getDateTimeAdded()));
    }
```


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Rhododendron moultonii Ridl.

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
.. _keys-traits-configs:

Keys, Traits, and Configs
=========================

You have probably seen snippets of Chisel referencing keys, traits, and configs by this point.
This section aims to elucidate the interactions between these Chisel/Scala components, and provide
best practices for how these should be used to create a parameterized design and configure it.

We will continue to use the GCD example.

Keys
----

Keys specify some parameter which controls some custom widget. Keys should typically be implemented as **Option types**, with a default value of ``None`` that means no change in the system. In other words, the default behavior when the user does not explicitly set the key should be a no-op.

Keys should be defined and documented in sub-projects, since they generally deal with some specific block, and not system-level integration. (We make an exception for the example GCD widget).

.. literalinclude:: ../../generators/chipyard/src/main/scala/example/GCD.scala
    :language: scala
    :start-after: DOC include start: GCD key
    :end-before: DOC include end: GCD key

The object within a key is typically a ``case class XXXParams``, which defines a set of parameters which some block accepts. For example, the GCD widget's ``GCDParams`` parameterizes its address, operand widths, whether the widget should be connected by Tilelink or AXI4, and whether the widget should use the blackbox-Verilog implementation, or the Chisel implementation.

.. literalinclude:: ../../generators/chipyard/src/main/scala/example/GCD.scala
    :language: scala
    :start-after: DOC include start: GCD params
    :end-before: DOC include end: GCD params

Accessing the value stored in the key is easy in Chisel, as long as the ``implicit p: Parameters`` object is being passed through to the relevant module. For example, ``p(GCDKey).get.address`` returns the address field of ``GCDParams``. Note this only works if ``GCDKey`` was not set to ``None``, so your Chisel should check for that case!

Traits
------

Typically, most custom blocks will need to modify the behavior of some pre-existing block. For example, the GCD widget needs the ``DigitalTop`` module to instantiate and connect the widget via Tilelink, generate a top-level ``gcd_busy`` port, and connect that to the module as well. Traits let us do this without modifying the existing code for the ``DigitalTop``, and enables compartmentalization of code for different custom blocks.

Top-level traits specify that the ``DigitalTop`` has been parameterized to read some custom key and optionally instantiate and connect a widget defined by that key. Traits **should not** mandate the instantiation of custom logic. In other words, traits should be written with ``CanHave`` semantics, where the default behavior when the key is unset is a no-op.

Top-level traits should be defined and documented in subprojects, alongside their corresponding keys. The traits should then be added to the ``DigitalTop`` being used by Chipyard.

Below we see the traits for the GCD example. The Lazy trait connects the GCD module to the Diplomacy graph, while the Implementation trait causes the ``DigitalTop`` to instantiate an additional port and concretely connect it to the GCD module.

.. literalinclude:: ../../generators/chipyard/src/main/scala/example/GCD.scala
    :language: scala
    :start-after: DOC include start: GCD lazy trait
    :end-before: DOC include end: GCD imp trait

These traits are added to the default ``DigitalTop`` in Chipyard.

.. literalinclude:: ../../generators/chipyard/src/main/scala/DigitalTop.scala
    :language: scala
    :start-after: DOC include start: DigitalTop
    :end-before: DOC include end: DigitalTop

Config Fragments
----------------

Config fragments set the keys to a non-default value. Together, the collection of config fragments which define a configuration generate the values for all the keys used by the generator.

For example, the ``WithGCD`` config fragment is parameterized by the type of GCD widget you want to instantiate. When this config fragment is added to a config, the ``GCDKey`` is set to a instance of ``GCDParams``, informing the previously mentioned traits to instantiate and connect the GCD widget appropriately.

.. literalinclude:: ../../generators/chipyard/src/main/scala/example/GCD.scala
    :language: scala
    :start-after: DOC include start: GCD config fragment
    :end-before: DOC include end: GCD config fragment

We can use this config fragment when composing our configs.

.. literalinclude:: ../../generators/chipyard/src/main/scala/config/RocketConfigs.scala
    :language: scala
    :start-after: DOC include start: GCDTLRocketConfig
    :end-before: DOC include end: GCDTLRocketConfig

.. note::
   Readers who want more information on the configuration system may be interested in reading :ref:`cdes`.


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/container/v1/cluster_service.proto

package com.google.container.v1;

public interface UsableSubnetworkSecondaryRangeOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.container.v1.UsableSubnetworkSecondaryRange)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * The name associated with this subnetwork secondary range, used when adding
   * an alias IP range to a VM instance.
   *

   *
   * string range_name = 1;
   *
   * @return The rangeName.
   */
  java.lang.String getRangeName();
  /**
   *
   *
   *

   * The name associated with this subnetwork secondary range, used when adding
   * an alias IP range to a VM instance.
   *

   *
   * string range_name = 1;
   *
   * @return The bytes for rangeName.
   */
  com.google.protobuf.ByteString getRangeNameBytes();

  /**
   *
   *
   *

   * The range of IP addresses belonging to this subnetwork secondary range.
   *

   *
   * string ip_cidr_range = 2;
   *
   * @return The ipCidrRange.
   */
  java.lang.String getIpCidrRange();
  /**
   *
   *
   *

   * The range of IP addresses belonging to this subnetwork secondary range.
   *

   *
   * string ip_cidr_range = 2;
   *
   * @return The bytes for ipCidrRange.
   */
  com.google.protobuf.ByteString getIpCidrRangeBytes();

  /**
   *
   *
   *

   * This field is to determine the status of the secondary range programmably.
   *

   *
   * .google.container.v1.UsableSubnetworkSecondaryRange.Status status = 3;
   *
   * @return The enum numeric value on the wire for status.
   */
  int getStatusValue();
  /**
   *
   *
   *

   * This field is to determine the status of the secondary range programmably.
   *

   *
   * .google.container.v1.UsableSubnetworkSecondaryRange.Status status = 3;
   *
   * @return The status.
   */
  com.google.container.v1.UsableSubnetworkSecondaryRange.Status getStatus();
}


text:
/*jslint node:true, debug:true*/
/*global before */
// call the debugger in case we are in debug mode
before(function () {
	debugger;
});


text:
<!DOCTYPE html>

		<title>three.js webgl - animation - groups</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<link type="text/css" rel="stylesheet" href="main.css">

			three.js webgl - animation - groups


text:
/*
Icon classes can be used entirely standalone. They are named after their original file names.

Example usage in HTML:

`display: block` sprite:

To change `display` (e.g. `display: inline-block;`), we suggest using a common CSS class:

// CSS
.icon {
  display: inline-block;
}

// HTML

*/
.icon-email-error {
  background-image: url(icons.png);
  background-position: 0px 0px;
  width: 16px;
  height: 16px;
}
.icon-eye {
  background-image: url(icons.png);
  background-position: 0px -16px;
  width: 16px;
  height: 12px;
}
.icon-ponyfoo {
  background-image: url(icons.png);
  background-position: -16px 0px;
  width: 16px;
  height: 16px;
}


text:
.. eventer documentation master file, created by
   sphinx-quickstart on Thu Jan  5 20:33:55 2017.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to quartz's documentation!
==================================

Quartz is a platform for registering events from various sources
and visualize the data. It is built using the `pymicroservice <https://github.com/vladcalin/pymicroservice>`_
library and `MongoDB <https://www.mongodb.com/>`_

.. toctree::
   :maxdepth: 2
   :caption: Contents:

   installation
   usage
   queries
   visualize

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.AspNetCore.Http.Connections;

/// <summary>
/// Constants related to HTTP transports.
/// </summary>
public static class HttpTransports
{
    /// <summary>
    /// A bitmask combining all available <see cref="HttpTransportType"/> values.
    /// </summary>
    public static readonly HttpTransportType All = HttpTransportType.WebSockets | HttpTransportType.ServerSentEvents | HttpTransportType.LongPolling;
}


text:
package com.tle.web.sections.standard;

import com.tle.web.sections.standard.model.HtmlBooleanState;
import com.tle.web.sections.standard.model.Option;

public class ListOption<T> {
  private final Option<T> option;
  private final HtmlBooleanState booleanState;

  public ListOption(Option<T> option, HtmlBooleanState state) {
    this.option = option;
    this.booleanState = state;
  }

  public Option<T> getOption() {
    return option;
  }

  public HtmlBooleanState getBooleanState() {
    return booleanState;
  }
}


text:
<?php
/**
 * Register
 *
 * This page deals with user registration, allowing them
 * to sign up for the game and be insert into the database.
 *
 **/

 /* Require the Header file */
require_once("./header.php");

/* Check if user is logged in already */
if(logged_in()) {
    output("You are already logged in!");
}
/* User is not logged in, did they try to register? */
elseif($_SERVER['REQUEST_METHOD'] == 'POST') {
    /* Protect the form data from SQL injection */
    $form_username = protect($_POST['username']);
    $form_password = protect($_POST['password']);
    $form_confpass = protect($_POST['confpass']);
    $form_emailadd = protect($_POST['emailadd']);
    $hash_password = md5(md5($form_password));
    $hash_confpass = md5(md5($form_confpass));

    /* Attempt to get user information from database */
    $get_user = $mysqli->query("SELECT id FROM users WHERE
                                username = '{$form_username}' LIMIT 1");
    $get_email = $mysqli->query("SELECT id FROM users WHERE
                                email = '{$form_emailadd}' LIMIT 1");

    /* Check for invalid form data (e.g. empty input) */
    if($form_username == '' || $form_password == '' ||
       $form_confpass == '' || $form_emailadd == '') {
        output("You must fill out all fields!");
    }
    /* Check for correct username length */
    elseif(strlen($form_username) < 3 || strlen($form_username) > 20) {
        output("Username must be between 3 and 20 characters!");
    }
    /* Check if the passwords match */
    elseif($hash_confpass != $hash_password) {
        output("Passwords do not match!");
    }
    /* Check if e-mail is correct length */
    elseif(strlen($form_emailadd) > 100) {
        output("E-mail address must be less than 100 characters!");
    }
    /* Check if e-mail is valid format */
    elseif(!filter_var($form_emailadd, FILTER_VALIDATE_EMAIL)) {
        output("E-mail address format is invalid!");
    }
    /* Does the user exist in the database? */
    elseif($get_user->num_rows > 0) {
        output("Username is already in use!");
    }
    /* Does the e-mail address exist in the database? */
    elseif($get_email->num_rows > 0) {
        output("E-mail address is already in use!");
    }
    /* Everything is good, register the user */
    else {
        $mysqli->query("INSERT INTO users (username,password,email) VALUES
                ('{$form_username}','{$hash_confpass}','{$form_emailadd}')");
        /* The database handles the default values */
        $mysqli->query("INSERT INTO stats () VALUES ()");
        $mysqli->query("INSERT INTO units () VALUES ()");
        $mysqli->query("INSERT INTO weapons () VALUES ()");
        $mysqli->query("INSERT INTO rankings () VALUES ()");
        output("You are now registered! Please login to the left.");
    }
}
/* User is not logged in and hasn't tried to register */
else {
    ?>
    <form action="register.php" method="post">
        Username: <input type="text" name="username">

        Password: <input type="password" name="password">

        Confirm: <input type="password" name="confpass">

        E-mail: <input type="text" name="emailadd">

        <input type="submit" name="register" value="Register">
    </form>
    <?php
}

/* Require the Footer file */
require_once("./footer.php");
?>


text:
require_relative 'file_renderer'
require 'fileutils'

module PortletGenerator
  class PortletTemplateIndex < FileRenderer
    def generate
      make_template_dir

      super
    end

    def template
      File.read(File.expand_path('templates/index.html.erb', __dir__))
    end

    def target_file
      "#{template_dir}/index.html"
    end

    def template_dir
      "src/main/webapp/templates/#{generator.name}"
    end

    private

    def make_template_dir
      FileUtils.mkdir_p template_dir
    end
  end
end


text:
function [coeff, Xmean, explained] = compute_pca(setting)
% Load features (with their metadata)
features = load_features(setting);

% Load data
X = [features.data].';

% Compute PCA
[coeff, score, latent, tsquared, explained, Xmean] = pca(X);

% Generate savefile name
prefix = ['PCA_', setting2prefix(setting)];

% Get host name
pcinfo = java.net.InetAddress.getLocalHost();
host = pcinfo.getHostName(); % class is java.lang.String
host = char(host); % convert to MATLAB char array

% Get date
date = datestr(now());

% Save
if ~exist('PCAs', 'dir')
    mkdir('PCAs');
end
savefile_path = ['PCAs/', savefile_name];
save(savefile_path, 'coeff', 'Xmean', 'explained');

% Print termination message
disp('--------------------------------------------------------------------------------');
disp(['Finished PCA on host ', host,' at ', date,' with settings:']);
disp(setting);
disp(['Elapsed time is ', elapsed_str, ' seconds.']);
end


text:
<?php

/**
 * Export CSV button for shipping table rates
 *
 * @category   Mage
 * @package    Mage_Adminhtml
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Adminhtml_Block_System_Config_Form_Field_Export extends Varien_Data_Form_Element_Abstract
{
    public function getElementHtml()
    {
        $buttonBlock = $this->getForm()->getParent()->getLayout()->createBlock('adminhtml/widget_button');

        $params = array(
            'website' => $buttonBlock->getRequest()->getParam('website')
        );

        $data = array(
            'label'     => Mage::helper('adminhtml')->__('Export CSV'),
            'onclick'   => 'setLocation(\''.Mage::helper('adminhtml')->getUrl("*/*/exportTablerates", $params) . 'conditionName/\' + $(\'carriers_tablerate_condition_name\').value + \'/tablerates.csv\' )',
            'class'     => '',
        );

        $html = $buttonBlock->setData($data)->toHtml();

        return $html;
    }
}


text:
namespace OnlineCrystalStore.Web.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web.Mvc;
    using Microsoft.AspNet.Identity;
    using OnlineCrystalStore.Data.Common;
    using OnlineCrystalStore.Data.Models;
    using OnlineCrystalStore.Web.Controllers;
    using ViewModels.OrderDetails;

    [Authorize]
    public class OrderDetailsController : BaseController
    {
        private IDbRepository<OrderDetails> orders;
        private IDbRepository<ShoppingCart> shoppingCarts;
        private IDbRepository<Crystal> crystals;

        public OrderDetailsController(
                            IDbRepository<OrderDetails> orders,
                            IDbRepository<ShoppingCart> shoppingCarts,
                            IDbRepository<Crystal> crystals)
        {
            this.orders = orders;
            this.shoppingCarts = shoppingCarts;
            this.crystals = crystals;
        }

        [HttpGet]
        public ActionResult Create()
        {
            return this.View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(OrderDetailsViewModel model, int id)
        {
            if (!this.ModelState.IsValid)
            {
                return this.View(model);
            }

            var newOrder = new OrderDetails()
            {
                Id = model.Id,
                Address = model.Address,
                BuyerId = this.User.Identity.GetUserId(),
                City = model.City,
                Country = model.Country,
                ShoppingCartId = id,
                PaymentMethod = model.PaymentMethod
            };
            var currentShoppingCart = this.shoppingCarts.All().FirstOrDefault(x => x.Id == id);
            newOrder.TotalPrice = currentShoppingCart.Crystals.Sum(x => x.Price);

            this.orders.Add(newOrder);
            this.orders.Save();

            foreach (var item in currentShoppingCart.Crystals)
            {
                this.crystals.Delete(item);
            }

            this.shoppingCarts.Delete(currentShoppingCart);
            this.crystals.Save();
            this.shoppingCarts.Save();

            return this.Redirect("/Home/Index");
        }

        // admin
        // list
    }
}


text:
<?xml version="1.0"?>
<Document>

	<Sentence>
		<value>Chemotherapy and radiation therapy can also cause ovarian hypofunction.</value>
		<pattern_crowdsource> [[Chemotherapy|C0013216]] and [[radiation therapy|C0034618]] can also cause [[ovarian hypofunction|C0542031]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Chemotherapy</surface-form>
				<RDF-ID>C0013216</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>radiation therapy</surface-form>
				<RDF-ID>C0034618</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>ovarian hypofunction</surface-form>
				<RDF-ID>C0542031</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0034618 CAUSES C0542031</triple>
			<triple>C0013216 CAUSES C0542031</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Women with ovarian hypofunction may develop symptoms of menopause, which include:   - Hot flashes  - Irregular or absent periods  - Mood swings  - Night sweats  - Vaginal dryness    Ovarian hypofunction may also make it hard for a woman to become pregnant.</value>
		<pattern_crowdsource> [[Women|C0043210]] with [[ovarian hypofunction|C0542031]] may develop [[symptoms|C1457887]] of menopause, which include:   - Hot flashes  - Irregular or absent periods  - Mood swings  - Night sweats  - Vaginal dryness    [[Ovarian hypofunction|C0542031]] may also make it hard for a woman to become pregnant.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Women</surface-form>
				<RDF-ID>C0043210</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>ovarian hypofunction</surface-form>
				<RDF-ID>C0542031</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>symptoms</surface-form>
				<RDF-ID>C1457887</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>menopause</surface-form>
				<RDF-ID>C0025320</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Hot flashes</surface-form>
				<RDF-ID>C0020040</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Irregular</surface-form>
				<RDF-ID>C0205271</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>absent</surface-form>
				<RDF-ID>C0332197</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>periods</surface-form>
				<RDF-ID>C0439531</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Mood swings</surface-form>
				<RDF-ID>C0085633</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Night sweats</surface-form>
				<RDF-ID>C0028081</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Vaginal dryness</surface-form>
				<RDF-ID>C0241633</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Ovarian hypofunction</surface-form>
				<RDF-ID>C0542031</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>hard</surface-form>
				<RDF-ID>C0018599</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>woman</surface-form>
				<RDF-ID>C0043210</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0542031 PROCESS_OF C0043210</triple>
			<triple>C0542031 PROCESS_OF C0043210</triple>
			<triple>C1457887 PROCESS_OF C0043210</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Estrogen therapy often helps relieve menopausal symptoms and prevents bone loss.</value>
		<pattern_crowdsource> [[Estrogen therapy|C0279494]] often helps relieve [[menopausal symptoms|C0236075]] and prevents bone loss.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Estrogen therapy</surface-form>
				<RDF-ID>C0279494</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>often</surface-form>
				<RDF-ID>C0332183</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>menopausal symptoms</surface-form>
				<RDF-ID>C0236075</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>bone loss</surface-form>
				<RDF-ID>C0599877</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0279494 TREATS C0236075</triple>
		</triples>
	</Sentence>

</Document>


text:
<?php

/**
 * Our homepage. Show the most recently added quote.
 *
 * controllers/Welcome.php
 *
 * ------------------------------------------------------------------------
 */
class Welcome extends Application {

    function __construct() {
        parent::__construct();
        $this->load->model('TimeSchedule');
        //$this->load->model('order');
    }

    //-------------------------------------------------------------
    //  Homepage: show a list of the orders on file
    //-------------------------------------------------------------

    function index() {
        // Build a list of orders

        $this->data["daysofweek"] = $this->TimeSchedule->getDays();
//        $temp=$this->TimeSchedule->getDays();
//        var_dump($temp);

        $this->data['timeslots'] = $this->TimeSchedule->getTimeslots();

        $this->data['courses'] = $this->TimeSchedule->getCourses();

        $this->data['pagebody']='homepage';
        $this->render();
    }

    function search(){
        $this->data['pagebody']='searchresults';
        $timeslotSelected = $this->input->post('timeslots');
        $daySelected = $this->input->post('days');

        $timeslotArray = $this->TimeSchedule->getTimeslotForDropdown();
        $timeslotSelected = $timeslotArray[$timeslotSelected];

        $dayArray = $this->TimeSchedule->getDayForDropdown();
        $daySelected = $dayArray[$daySelected];

        $dayResults = $this->TimeSchedule->searchDays($timeslotSelected, $daySelected);
        $timeslotResults = $this->TimeSchedule->searchTimeslots($timeslotSelected, $daySelected);
        $courseResults = $this->TimeSchedule->searchCourses($timeslotSelected, $daySelected);

        if(count($dayResults) == 1 && count($timeslotResults) == 1 && count($courseResults) == 1){
            if($dayResults==$timeslotResults && $dayResults==$courseResults && $courseResults==$timeslotResults){
                $this->data['dayinfo']=$dayResults;
                $this->data['timeinfo']=$timeslotResults;
                $this->data['courseinfo']=$courseResults;
                $this->render();
            } else //Bad Search result, load error page
            {
                $this->data['pagebody']='errorsearch';
                $this->data['dayinfo']=$dayResults;
                $this->data['timeinfo']=$timeslotResults;
                $this->data['courseinfo']=$courseResults;
                $this->render();
            }
        } else //Bad Search result, load error page
        {
            $this->data['pagebody']='errorsearch';
            $this->data['dayinfo']=$dayResults;
            $this->data['timeinfo']=$timeslotResults;
            $this->data['courseinfo']=$courseResults;
            $this->render();
        }
    }
}


text:
<?php

namespace lithium\core;

use lithium\util\Collection;
use lithium\core\Environment;
use SplDoublyLinkedList;
use lithium\core\ConfigException;

/**
 * The `Adaptable` static class is the base class from which all adapter implementations extend.
 *
 * `Adaptable` provides the logic necessary for generic configuration of named adapter
 * configurations (such as the ones used in `Cache`) as well as a unified method of locating and
 * obtaining an instance to a specified adapter.
 *
 * All immediate subclasses to `Adaptable` must define the protected attributes `$_configurations`
 * and `$_adapters`. The former is where all local adapter named configurations will be
 * stored (as an array of named configuration settings), and the latter must contain the
 * `Libraries::locate()`-compatible path string (or array of strings) specifying how adapter classes
 * should be located.
 *
 * This static class should **never** be called explicitly.
 */
class Adaptable extends \lithium\core\StaticObject {

	/**
	 * To be re-defined in sub-classes.
	 *
	 * @var object `Collection` of configurations, indexed by name.
	 */
	protected static $_configurations = array();

	/**
	 * To be re-defined in sub-classes.
	 *
	 * Holds the Libraries::locate() compatible path string where the strategy in question
	 * may be found.
	 *
	 * @var string Path string.
	 */
	protected static $_strategies = null;

	/**
	 * To be re-defined in sub-classes.
	 *
	 * Holds the `Libraries::locate()`-compatible path string where the adapter in question
	 * may be found.
	 *
	 * @var string Path string.
	 */
	protected static $_adapters = null;

	/**
	 * Sets configurations for a particular adaptable implementation, or returns the current
	 * configuration settings.
	 *
	 * @param array $config Configurations, indexed by name.
	 * @return object|void `Collection` of configurations or void if setting configurations.
	 */
	public static function config($config = null) {
		if ($config && is_array($config)) {
			static::$_configurations = $config;
			return;
		}
		if ($config) {
			return static::_config($config);
		}
		$result = array();
		static::$_configurations = array_filter(static::$_configurations);

		foreach (array_keys(static::$_configurations) as $key) {
			$result[$key] = static::_config($key);
		}
		return $result;
	}

	/**
	 * Clears all configurations.
	 *
	 * @return void
	 */
	public static function reset() {
		static::$_configurations = array();
	}

	/**
	 * Returns adapter class name for given `$name` configuration, using
	 * the `$_adapter` path defined in Adaptable subclasses.
	 *
	 * @param string $name Class name of adapter to load.
	 * @return object Adapter object.
	 */
	public static function adapter($name = null) {
		$config = static::_config($name);

		if ($config === null) {
			throw new ConfigException("Configuration '{$name}' has not been defined.");
		}

		if (isset($config['object'])) {
			return $config['object'];
		}
		$class = static::_class($config, static::$_adapters);
		$settings = static::$_configurations[$name];
		$settings[0]['object'] = new $class($config);

		static::$_configurations[$name] = $settings;
		return static::$_configurations[$name][0]['object'];
	}

	/**
	 * Obtain an `SplStack` of the strategies for the given `$name` configuration, using
	 * the `$_strategies` path defined in `Adaptable` subclasses.
	 *
	 * @param string $name Class name of adapter to load.
	 * @return object `SplStack` of strategies, or `null` if none are defined.
	 */
	public static function strategies($name) {
		$config = static::_config($name);

		if ($config === null) {
			throw new ConfigException("Configuration '{$name}' has not been defined.");
		}
		if (!isset($config['strategies'])) {
			return null;
		}
		$stack = new SplDoublyLinkedList();

		foreach ($config['strategies'] as $key => $strategy) {
			$arguments = array();

			if (is_array($strategy)) {
				$name = $key;
				$class = static::_strategy($name, static::$_strategies);
				$index = (isset($config['strategies'][$name])) ? $name : $class;
				$arguments = $config['strategies'][$index];
			} else {
				$name = $strategy;
				$class = static::_strategy($name, static::$_strategies);
			}
			$stack->push(new $class($arguments));
		}
		return $stack;
	}

	/**
	 * Applies strategies configured in `$name` for `$method` on `$data`.
	 *
	 * @param string $method The strategy method to be applied.
	 * @param string $name The named configuration
	 * @param mixed $data The data to which the strategies will be applied.
	 * @param array $options If `mode` is set to 'LIFO', the strategies are applied in reverse.
	 *        order of their definition.
	 * @return mixed Result of application of strategies to data. If no strategies
	 *         have been configured, this method will simply return the original data.
	 */
	public static function applyStrategies($method, $name, $data, array $options = array()){
		$options += array('mode' => null);

		if (!$strategies = static::strategies($name)) {
			return $data;
		}
		if (!count($strategies)) {
			return $data;
		}

		if (isset($options['mode']) && ($options['mode'] === 'LIFO')) {
			$strategies->setIteratorMode(SplDoublyLinkedList::IT_MODE_LIFO);
			unset($options['mode']);
		}

		foreach ($strategies as $strategy) {
			if (method_exists($strategy, $method)) {
				$data = $strategy->{$method}($data, $options);
			}
		}
		return $data;
	}

	/**
	 * Determines if the adapter specified in the named configuration is enabled.
	 *
	 * `Enabled` can mean various things, e.g. having a PECL memcached extension compiled
	 * & loaded, as well as having the memcache server up & available.
	 *
	 * @param string $name The named configuration whose adapter will be checked.
	 * @return boolean|null  True if adapter is enabled, false if not. This method will
	 *         return null if no configuration under the given $name exists.
	 */
	public static function enabled($name) {
		if (!static::_config($name)) {
			return null;
		}
		$adapter = static::adapter($name);
		return $adapter::enabled();
	}

	/**
	 * Looks up an adapter by class by name.
	 *
	 * @see lithium\core\libraries::locate()
	 * @param string $config Configuration array of class to be found.
	 * @param array $paths Optional array of search paths that will be checked.
	 * @return string Returns a fully-namespaced class reference to the adapter class.
	 */
	protected static function _class($config, $paths = array()) {
		if (!$name = $config['adapter']) {
			$self = get_called_class();
			throw new ConfigException("No adapter set for configuration in class {$self}.");
		}
		if (!$class = static::_locate($paths, $name)) {
			$self = get_called_class();
			throw new ConfigException("Could not find adapter '{$name}' in class {$self}.");
		}
		return $class;
	}

	/**
	 * Looks up a strategy by class by name.
	 *
	 * @see lithium\core\libraries::locate()
	 * @param string $name The strategy to locate.
	 * @param array $paths Optional array of search paths that will be checked.
	 * @return string Returns a fully-namespaced class reference to the adapter class.
	 */
	protected static function _strategy($name, $paths = array()) {
		if (!$name) {
			$self = get_called_class();
			throw new ConfigException("No strategy set for configuration in class {$self}.");
		}
		if (!$class = static::_locate($paths, $name)) {
			$self = get_called_class();
			throw new ConfigException("Could not find strategy '{$name}' in class {$self}.");
		}
		return $class;
	}

	/**
	 * Perform library location for an array of paths or a single string-based path.
	 *
	 * @param string|array $paths Paths that Libraries::locate() will utilize.
	 * @param string $name The name of the class to be located.
	 * @return null|string Fully-namespaced path to the class, or null if not found.
	 */
	protected static function _locate($paths, $name) {
		foreach ((array) $paths as $path) {
			if ($class = Libraries::locate($path, $name)) {
				return $class;
			}
		}
		return null;
	}

	/**
	 * Gets an array of settings for the given named configuration in the current
	 * environment.
	 *
	 * The default types of settings for all adapters will contain keys for:
	 * `adapter` - The class name of the adapter
	 * `filters` - An array of filters to be applied to the adapter methods
	 *
	 * @see lithium\core\Environment
	 * @param string $name Named configuration.
	 * @return array Settings for the named configuration.
	 */
	protected static function _config($name) {
		if (!isset(static::$_configurations[$name])) {
			return null;
		}
		$settings = static::$_configurations[$name];

		if (isset($settings[0])) {
			return $settings[0];
		}
		$env = Environment::get();
		$config = isset($settings[$env]) ? $settings[$env] : $settings;
		static::$_configurations[$name] += array(static::_initConfig($name, $config));
		return static::$_configurations[$name][0];
	}

	/**
	 * A stub method called by `_config()` which allows `Adaptable` subclasses to automatically
	 * assign or auto-generate additional configuration data, once a configuration is first
	 * accessed. This allows configuration data to be lazy-loaded from adapters or other data
	 * sources.
	 *
	 * @param string $name The name of the configuration which is being accessed. This is the key
	 *               name containing the specific set of configuration passed into `config()`.
	 * @param array $config Contains the configuration assigned to `$name`. If this configuration is
	 *              segregated by environment, then this will contian the configuration for the
	 *              current environment.
	 * @return array Returns the final array of settings for the given named configuration.
	 */
	protected static function _initConfig($name, $config) {
		$defaults = array('adapter' => null, 'filters' => array());
		return (array) $config + $defaults;
	}
}

?>


text:
import random

import discord
from discord.ext.commands import Bot, Context

rand = random.SystemRandom()

def is_direct_message(ctx: Context) -> bool:
    return ctx.message.channel.is_private

def get_invite_url(bot: Bot) -> str:
    permissions = discord.Permissions.text()
    return discord.utils.oauth_url(bot.client_id, permissions=permissions)


text:
#include "public/platform/WebInputEvent.h"

#include "platform/KeyboardCodes.h"
#include "public/platform/WebGestureEvent.h"
#include "public/platform/WebMouseWheelEvent.h"
#include "wtf/ASCIICType.h"
#include "wtf/Assertions.h"
#include "wtf/StringExtras.h"
#include <ctype.h>

namespace blink {

struct SameSizeAsWebInputEvent {
  int inputData[8];
};

struct SameSizeAsWebKeyboardEvent : public SameSizeAsWebInputEvent {
  int keyboardData[9];
};

struct SameSizeAsWebMouseEvent : public SameSizeAsWebInputEvent {
  int mouseData[17];
};

struct SameSizeAsWebMouseWheelEvent : public SameSizeAsWebMouseEvent {
  int mousewheelData[12];
};

struct SameSizeAsWebGestureEvent : public SameSizeAsWebInputEvent {
  int gestureData[14];
};

struct SameSizeAsWebTouchEvent : public SameSizeAsWebInputEvent {
  WebTouchPoint touchPoints[WebTouchEvent::kTouchesLengthCap];
  int touchData[4];
};

static_assert(sizeof(WebInputEvent) == sizeof(SameSizeAsWebInputEvent),
              "WebInputEvent should not have gaps");
static_assert(sizeof(WebKeyboardEvent) == sizeof(SameSizeAsWebKeyboardEvent),
              "WebKeyboardEvent should not have gaps");
static_assert(sizeof(WebMouseEvent) == sizeof(SameSizeAsWebMouseEvent),
              "WebMouseEvent should not have gaps");
static_assert(sizeof(WebMouseWheelEvent) ==
                  sizeof(SameSizeAsWebMouseWheelEvent),
              "WebMouseWheelEvent should not have gaps");
static_assert(sizeof(WebGestureEvent) == sizeof(SameSizeAsWebGestureEvent),
              "WebGestureEvent should not have gaps");
static_assert(sizeof(WebTouchEvent) == sizeof(SameSizeAsWebTouchEvent),
              "WebTouchEvent should not have gaps");

#define CASE_TYPE(t)     \
  case WebInputEvent::t: \
    return #t
// static
const char* WebInputEvent::GetName(WebInputEvent::Type type) {
  switch (type) {
    CASE_TYPE(Undefined);
    CASE_TYPE(MouseDown);
    CASE_TYPE(MouseUp);
    CASE_TYPE(MouseMove);
    CASE_TYPE(MouseEnter);
    CASE_TYPE(MouseLeave);
    CASE_TYPE(ContextMenu);
    CASE_TYPE(MouseWheel);
    CASE_TYPE(RawKeyDown);
    CASE_TYPE(KeyDown);
    CASE_TYPE(KeyUp);
    CASE_TYPE(Char);
    CASE_TYPE(GestureScrollBegin);
    CASE_TYPE(GestureScrollEnd);
    CASE_TYPE(GestureScrollUpdate);
    CASE_TYPE(GestureFlingStart);
    CASE_TYPE(GestureFlingCancel);
    CASE_TYPE(GestureShowPress);
    CASE_TYPE(GestureTap);
    CASE_TYPE(GestureTapUnconfirmed);
    CASE_TYPE(GestureTapDown);
    CASE_TYPE(GestureTapCancel);
    CASE_TYPE(GestureDoubleTap);
    CASE_TYPE(GestureTwoFingerTap);
    CASE_TYPE(GestureLongPress);
    CASE_TYPE(GestureLongTap);
    CASE_TYPE(GesturePinchBegin);
    CASE_TYPE(GesturePinchEnd);
    CASE_TYPE(GesturePinchUpdate);
    CASE_TYPE(TouchStart);
    CASE_TYPE(TouchMove);
    CASE_TYPE(TouchEnd);
    CASE_TYPE(TouchCancel);
    CASE_TYPE(TouchScrollStarted);
    default:
      NOTREACHED();
      return "";
  }
}
#undef CASE_TYPE

}  // namespace blink


text:
<?xml version="1.0" encoding="utf-8" ?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <group android:checkableBehavior="single">
    <item android:id="@+id/nav_dogShow" android:icon="@drawable/ic_dashboard" android:title="@string/DogShow" android:visible ="true" android:checked="true"/>
    <item android:id="@+id/nav_hallOfFame" android:icon="@drawable/ic_event" android:title="@string/HallOfFame" android:visible ="true"/>
    <item android:id="@+id/nav_myDog" android:icon="@drawable/ic_forum" android:title="@string/MyDog" android:visible ="false"/>
    <item android:id="@+id/nav_adminPanel" android:icon="@drawable/ic_headset" android:title="@string/AdminPanel" android:visible ="false"/>
    <item android:id="@+id/nav_expertPanel" android:icon="@drawable/ic_forum" android:title="@string/ExpertPanel" android:visible ="false"/>
  </group>
</menu>


text:
package org.createnet.raptor.models.payload;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.createnet.raptor.models.acl.EntityType;
import org.createnet.raptor.models.acl.Operation;
import org.createnet.raptor.models.objects.RaptorComponent;
import org.createnet.raptor.models.objects.Device;

/**
 *
 * @author Luca Capra <luca.capra@fbk.eu>
 */
public class DevicePayload extends AbstractPayload {

    public String userId;
    public Device device;

    public DevicePayload() {
    }

    public DevicePayload(Device obj, Operation op) {
        userId = obj.userId();
        device = obj;
        type = EntityType.device;
        this.op = op;
    }

    @Override
    public String toString() {
        try {
            return Device.getMapper().writeValueAsString(this);
        } catch (JsonProcessingException ex) {
            throw new RaptorComponent.ParserException(ex);
        }
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public Device getDevice() {
        return device;
    }

    public void setDevice(Device device) {
        this.device = device;
    }

}


text:
id: getting_started
title: Getting Started
---

import InstallInstructions from '../src/install_instructions'

## Adding SpotifyAPI-NET to your project

The library can be added to your project via the following methods:

### Package Managers

<InstallInstructions />

### Add DLL Manually

You can also grab the latest compiled DLL from our [GitHub Releases Page](https://github.com/johnnycrazy/spotifyapi-net/releases). It can be added to your project via Visual Studio or directly in your `.csproj`:

```xml
<ItemGroup>
  <Reference Include="SpotifyAPI.Web">
    <HintPath>..\Dlls\SpotifyAPI.Web.dll</HintPath>
  </Reference>
</ItemGroup>
```

### Compile Yourself

```sh
git clone https://github.com/JohnnyCrazy/SpotifyAPI-NET.git
cd SpotifyAPI-NET
dotnet restore
dotnet build

ls -la SpotifyAPI.Web/bin/Debug/netstandard2.1/SpotifyAPI.Web.dll
```

## First API Calls

You're now ready to issue your first calls to the Spotify API, a small console example:

```csharp
using System;
using System.Threading.Tasks;
using SpotifyAPI.Web;

class Program
{
    static async Task Main()
    {
      var spotify = new SpotifyClient("YourAccessToken");

      var track = await spotify.Tracks.Get("1s6ux0lNiTziSrd7iUAADH");
      Console.WriteLine(track.Name);
    }
}
```

:::tip
Notice that the spotify api does not allow unauthorized API access. Wondering where you should get an access token from? For a quick test, head over to the [Spotify Developer Console](https://developer.spotify.com/console/get-album/) and generate an access token with the required scopes! For a permanent solution, head over to the [authentication guides](auth_introduction.md).

:::

There is no online documentation for every available API call, but XML inline docs are available:

* [UserProfile](https://github.com/JohnnyCrazy/SpotifyAPI-NET/blob/master/SpotifyAPI.Web/Clients/Interfaces/IUserProfileClient.cs)
* [Browse](https://github.com/JohnnyCrazy/SpotifyAPI-NET/blob/master/SpotifyAPI.Web/Clients/Interfaces/IBrowseClient.cs)
* [Shows](https://github.com/JohnnyCrazy/SpotifyAPI-NET/blob/master/SpotifyAPI.Web/Clients/Interfaces/IShowsClient.cs)
* [Playlists](https://github.com/JohnnyCrazy/SpotifyAPI-NET/blob/master/SpotifyAPI.Web/Clients/Interfaces/IPlaylistsClient.cs)
* [Search](https://github.com/JohnnyCrazy/SpotifyAPI-NET/blob/master/SpotifyAPI.Web/Clients/Interfaces/ISearchClient.cs)
* [Follow](https://github.com/JohnnyCrazy/SpotifyAPI-NET/blob/master/SpotifyAPI.Web/Clients/Interfaces/IFollowClient.cs)
* [Tracks](https://github.com/JohnnyCrazy/SpotifyAPI-NET/blob/master/SpotifyAPI.Web/Clients/Interfaces/ITracksClient.cs)
* [Player](https://github.com/JohnnyCrazy/SpotifyAPI-NET/blob/master/SpotifyAPI.Web/Clients/Interfaces/IPlayerClient.cs)
* [Albums](https://github.com/JohnnyCrazy/SpotifyAPI-NET/blob/master/SpotifyAPI.Web/Clients/Interfaces/IAlbumsClient.cs)
* [Artists](https://github.com/JohnnyCrazy/SpotifyAPI-NET/blob/master/SpotifyAPI.Web/Clients/Interfaces/IArtistsClient.cs)
* [Personalization](https://github.com/JohnnyCrazy/SpotifyAPI-NET/blob/master/SpotifyAPI.Web/Clients/Interfaces/IPersonalizationClient.cs)
* [Episodes](https://github.com/JohnnyCrazy/SpotifyAPI-NET/blob/master/SpotifyAPI.Web/Clients/Interfaces/IEpisodesClient.cs)
* [Library](https://github.com/JohnnyCrazy/SpotifyAPI-NET/blob/master/SpotifyAPI.Web/Clients/Interfaces/ILibraryClient.cs)

All calls have the [Spotify Web API documentation reference](https://developer.spotify.com/documentation/web-api/reference-beta/) attached as a remark.

## Query/Body Parameters

If an API endpoint has query or body parameters, a request model can be supplied to the method

```csharp
// No optional or required query/body parameters
// The track ID is part of the request path --> it's not treated as query/body parameter
var track = await spotify.Tracks.Get("1s6ux0lNiTziSrd7iUAADH");

// Optional query/body parameter
var track = await spotify.Tracks.Get("1s6ux0lNiTziSrd7iUAADH", new TrackRequest{
  Market = "DE"
});

// Sometimes, query/body parameters are also required!
var tracks = await spotify.Tracks.GetSeveral(new TracksRequest(new List<string> {
  "1s6ux0lNiTziSrd7iUAADH",
  "6YlOxoHWLjH6uVQvxUIUug"
}));
```

If a query/body parameter is required, it has to be supplied in the constructor of the request model. In the background, empty/null checks are also performed to make sure required parameters are not empty/null. If it is optional, it can be supplied as a property to the request model.

## Guides

All other relevant topics are covered in the "Guides" and [Authentication Guides](auth_introduction.md) section in the sidebar!


text:
module Recombinator
  VERSION = "0.1.0"
end


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.kirauks.pixelrunner.scene.base.element;

/**
 *
 * @author Karl
 */
public interface IScrollPageShortcutTouchListener {
    public void onShortcut(int index);
}


text:
class Player;

class InputHandler
{
public:
	InputHandler(Player* player);
	void update(const sf::Time& elapsed, sf::RenderWindow& win);
private:
	sf::Vector2f pos;
	sf::Vector2f moveVec;
	float speed;
	Player* owner;
};


text:
require 'cru_lib/version'
require 'cru_lib/async'
require 'cru_lib/global_registry_methods'
require 'cru_lib/global_registry_relationship_methods'
require 'cru_lib/global_registry_master_person_methods'
require 'cru_lib/railtie'

module CruLib
end


text:
require 'rails_helper'

module BeachApiCore
  describe 'V1::EntityMessages', type: :request do
    INTERACTION_USER_KEYS = %i(id email username first_name last_name avatar_url).freeze
    INTERACTION_KEEPER_KEYS = %i(id keeper_type keeper_id).freeze
    INTERACTION_ATTRIBUTE_KEYS = %i(id key values).freeze

    include_context 'signed up developer'
    include_context 'authenticated user'
    include_context 'bearer token authentication'

    let(:message_text) { Faker::Lorem.sentence }
    let(:new_message_text) { Faker::Lorem.sentence }
    let(:entity) { create :entity, user: oauth_user }

    describe '#create' do
      context 'when invalid' do
        it_behaves_like 'an authenticated resource' do
          before { post beach_api_core.v1_entity_messages_path(entity) }
        end
        it_behaves_like 'an authenticated resource' do
          before { post beach_api_core.v1_entity_messages_path(entity), headers: invalid_bearer_auth }
        end
      end

      context 'when valid' do
        let(:message_params) { { text: message_text } }

        it 'should create interaction with correct fields' do
          expect do
            post beach_api_core.v1_entity_messages_path(entity),
                 params: { message: message_params },
                 headers: bearer_auth
          end.to change(BeachApiCore::Interaction, :count).by(1)

          interaction = BeachApiCore::Interaction.last

          expect(interaction.kind).to eq 'chat'
          expect(interaction.user).to eq oauth_user
          expect(interaction.interaction_keepers.size).to eq 1
          expect(interaction.interaction_keepers.first.keeper).to eq entity
          expect(interaction.interaction_attributes.size).to eq 1
          expect(interaction.interaction_attributes.first.key).to eq 'message'
          expect(interaction.interaction_attributes.first.values.keys).to eq ['text']
        end

        describe 'interaction response' do
          before do
            post beach_api_core.v1_entity_messages_path(entity),
                 params: { message: message_params },
                 headers: bearer_auth
            @interaction = BeachApiCore::Interaction.last
          end
          let(:interaction_body) { json_body[:interaction] }

          it_behaves_like 'successful response'
          it_behaves_like 'request: entity message response'
        end
      end
    end

    context 'with interaction' do
      before do
        @interaction = create(:interaction,
                              kind: 'chat',
                              user: oauth_user,
                              interaction_keepers: [build(:interaction_keeper, keeper: entity)],
                              interaction_attributes: [build(:interaction_attribute,
                                                             key: 'message', values: { text: message_text })])
      end

      describe '#index' do
        context 'when invalid' do
          it_behaves_like 'an authenticated resource' do
            before { get beach_api_core.v1_entity_messages_path(entity) }
          end
          it_behaves_like 'an authenticated resource' do
            before { get beach_api_core.v1_entity_messages_path(entity), headers: invalid_bearer_auth }
          end
        end

        context 'when valid' do
          describe 'interaction response' do
            before { get beach_api_core.v1_entity_messages_path(entity), headers: bearer_auth }
            let(:interaction_body) { json_body[:interactions].first }

            it_behaves_like 'successful response'
            it_behaves_like 'request: entity message response'

            it 'should return correct interaction array' do
              expect(json_body[:interactions].size).to eq 1
            end
          end
        end
      end

      describe '#update' do
        context 'when invalid' do
          it_behaves_like 'an authenticated resource' do
            before { put beach_api_core.v1_entity_message_path(entity, @interaction) }
          end
          it_behaves_like 'an authenticated resource' do
            before { put beach_api_core.v1_entity_message_path(entity, @interaction), headers: invalid_bearer_auth }
          end
        end

        context 'when valid' do
          let(:message_params) { { text: new_message_text } }

          it 'should update interaction attribute message' do
            expect do
              put beach_api_core.v1_entity_message_path(entity, @interaction),
                  params: { message: message_params },
                  headers: bearer_auth
            end.to(change { @interaction.reload.interaction_attributes.first.values })

            expect(@interaction.interaction_attributes.first.values['text']).to eq new_message_text
          end

          describe 'interaction response' do
            before do
              put beach_api_core.v1_entity_message_path(entity, @interaction),
                  params: { message: message_params },
                  headers: bearer_auth
              @interaction = BeachApiCore::Interaction.last
            end
            let(:interaction_body) { json_body[:interaction] }

            it_behaves_like 'successful response'
            it_behaves_like 'request: entity message response' do
              let(:message_text) { new_message_text }
            end
          end
        end
      end

      describe '#destroy' do
        context 'when invalid' do
          it_behaves_like 'an authenticated resource' do
            before { delete beach_api_core.v1_entity_message_path(entity, @interaction) }
          end
          it_behaves_like 'an authenticated resource' do
            before { delete beach_api_core.v1_entity_message_path(entity, @interaction), headers: invalid_bearer_auth }
          end
        end

        context 'when valid' do
          it 'should destroy interaction' do
            expect do
              delete beach_api_core.v1_entity_message_path(entity, @interaction), headers: bearer_auth
            end.to change(BeachApiCore::Interaction, :count).by(-1)

            expect(response.status).to eq 204
          end
        end
      end
    end
  end
end


text:
namespace content {
class SpeechRecognitionManagerDelegate;
}

namespace speech {

class SpeechRecognizerImpl;

// This is the manager for speech recognition. It is a singleton instance in
// the browser process and can serve several requests. Each recognition request
// corresponds to a session, initiated via |CreateSession|.
// In every moment the manager has at most one "interactive" session (identified
// by |interactive_session_id_|), that is the session that is currently holding
// user attention. For privacy reasons, only the interactive session is allowed
// to capture audio from the microphone. However, after audio capture is
// completed, a session can be sent to background and can live in parallel with
// other sessions, while waiting for its results.
//
// More in details, SpeechRecognitionManager has the following responsibilities:
//  - Handles requests received from various render views and makes sure only
//    one of them accesses the audio device at any given time.
//  - Relays recognition results/status/error events of each session to the
//    corresponding listener (demuxing on the base of their session_id).
//  - Handles the instantiation of SpeechRecognitionEngine objects when
//    requested by SpeechRecognitionSessions.
class CONTENT_EXPORT SpeechRecognitionManagerImpl :
    public NON_EXPORTED_BASE(content::SpeechRecognitionManager),
    public NON_EXPORTED_BASE(content::SpeechRecognitionEventListener) {
 public:
  static SpeechRecognitionManagerImpl* GetInstance();

  // SpeechRecognitionManager implementation.
  virtual int CreateSession(
      const content::SpeechRecognitionSessionConfig& config,
      SpeechRecognitionEventListener* event_listener) OVERRIDE;
  virtual void StartSession(int session_id) OVERRIDE;
  virtual void AbortSession(int session_id) OVERRIDE;
  virtual void AbortAllSessionsForListener(
        content::SpeechRecognitionEventListener* listener) OVERRIDE;
  virtual void StopAudioCaptureForSession(int session_id) OVERRIDE;
  virtual void SendSessionToBackground(int session_id) OVERRIDE;
  virtual content::SpeechRecognitionSessionContext GetSessionContext(
      int session_id) const OVERRIDE;
  virtual int LookupSessionByContext(
      base::Callback<bool(
          const content::SpeechRecognitionSessionContext&)> matcher)
            const OVERRIDE;
  virtual bool HasAudioInputDevices() OVERRIDE;
  virtual bool IsCapturingAudio() OVERRIDE;
  virtual string16 GetAudioInputDeviceModel() OVERRIDE;
  virtual void ShowAudioInputSettings() OVERRIDE;

  // SpeechRecognitionEventListener methods.
  virtual void OnRecognitionStart(int session_id) OVERRIDE;
  virtual void OnAudioStart(int session_id) OVERRIDE;
  virtual void OnEnvironmentEstimationComplete(int session_id) OVERRIDE;
  virtual void OnSoundStart(int session_id) OVERRIDE;
  virtual void OnSoundEnd(int session_id) OVERRIDE;
  virtual void OnAudioEnd(int session_id) OVERRIDE;
  virtual void OnRecognitionEnd(int session_id) OVERRIDE;
  virtual void OnRecognitionResult(
      int session_id, const content::SpeechRecognitionResult& result) OVERRIDE;
  virtual void OnRecognitionError(
      int session_id, const content::SpeechRecognitionError& error) OVERRIDE;
  virtual void OnAudioLevelsChange(int session_id, float volume,
                                   float noise_volume) OVERRIDE;

 protected:
  // Private constructor to enforce singleton.
  friend struct DefaultSingletonTraits<SpeechRecognitionManagerImpl>;
  SpeechRecognitionManagerImpl();
  virtual ~SpeechRecognitionManagerImpl();

 private:
  // Data types for the internal Finite State Machine (FSM).
  enum FSMState {
    STATE_IDLE = 0,
    STATE_INTERACTIVE,
    STATE_BACKGROUND,
    STATE_WAITING_FOR_DELETION,
    STATE_MAX_VALUE = STATE_WAITING_FOR_DELETION
  };

  enum FSMEvent {
    EVENT_ABORT = 0,
    EVENT_START,
    EVENT_STOP_CAPTURE,
    EVENT_SET_BACKGROUND,
    EVENT_RECOGNITION_ENDED,
    EVENT_RECOGNITION_RESULT,
    EVENT_RECOGNITION_ERROR,
    EVENT_MAX_VALUE = EVENT_RECOGNITION_ERROR
  };

  struct Session {
    Session();
    ~Session();

    int id;
    content::SpeechRecognitionEventListener* event_listener;
    content::SpeechRecognitionSessionContext context;
    scoped_refptr<SpeechRecognizerImpl> recognizer;
    FSMState state;
    bool error_occurred;
  };

  struct FSMEventArgs {
    explicit FSMEventArgs(FSMEvent event_value);
    ~FSMEventArgs();

    FSMEvent event;
    content::SpeechRecognitionError speech_error;
  };

  // Callback issued by the SpeechRecognitionManagerDelegate for reporting
  // asynchronously the result of the CheckRecognitionIsAllowed call.
  void RecognitionAllowedCallback(int session_id, bool is_allowed);

  // Entry point for pushing any external event into the session handling FSM.
  void DispatchEvent(int session_id, FSMEventArgs args);

  // Defines the behavior of the session handling FSM, selecting the appropriate
  // transition according to the session, its current state and the event.
  FSMState ExecuteTransitionAndGetNextState(Session& session,
                                            const FSMEventArgs& event_args);

  // The methods below handle transitions of the session handling FSM.
  FSMState SessionStart(Session& session, const FSMEventArgs& event_args);
  FSMState SessionAbort(Session& session, const FSMEventArgs& event_args);
  FSMState SessionStopAudioCapture(Session& session,
                                   const FSMEventArgs& event_args);
  FSMState SessionAbortIfCapturingAudioOrBackground(
      Session& session, const FSMEventArgs& event_args);
  FSMState SessionSetBackground(Session& session,
                                const FSMEventArgs& event_args);
  FSMState SessionReportError(Session& session, const FSMEventArgs& event_args);
  FSMState SessionReportNoMatch(Session& session,
                                const FSMEventArgs& event_args);
  FSMState SessionDelete(Session& session, const FSMEventArgs& event_args);
  FSMState DoNothing(Session& session, const FSMEventArgs& event_args);
  FSMState NotFeasible(Session& session, const FSMEventArgs& event_args);

  bool SessionExists(int session_id) const;
  content::SpeechRecognitionEventListener* GetListener(int session_id) const;
  int GetNextSessionID();

  typedef std::map<int, Session> SessionsTable;
  SessionsTable sessions_;
  int interactive_session_id_;
  int last_session_id_;
  bool is_dispatching_event_;
  content::SpeechRecognitionManagerDelegate* delegate_;
};

}  // namespace speech

#endif  // CONTENT_BROWSER_SPEECH_SPEECH_RECOGNITION_MANAGER_IMPL_H_


text:
<?php
namespace Contentinum\Factory\Controller;

use Zend\Mvc\Controller\ControllerManager;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Http\PhpEnvironment\Request as HttpRequest;

class ApplicationControllerFactory implements FactoryInterface
{

    /**
     * Create controller
     *
     * @param ControllerManager $serviceLocator
     * @return Contentinum\Controller\ApplicationController
     */
    public function createService(ServiceLocatorInterface $controllerManager)
    {
        $sl = $controllerManager->getServiceLocator();
        /**
         *
         * @var $pageOptions Contentinum\Options\PageOptions
         */
        $pageOptions = $sl->get('contentinum_pages');
        $opt = $sl->get('contentinum_customer');
        if (isset($opt['default']['google_map_apikey'])) {
            define('GOOGLE_API_KEY', $opt['default']['google_map_apikey']);
        }
        $request = new HttpRequest();
        define('LOCALENAV', '');
        $language = 'de';
        $pageOptions->setLanguage($language);
        $controllerName = false;
        $pageOptions->setHost($request->getUri()->getHost());
        $pageOptions->setQuery($request->getUri()->getPath());
        $pageOptions->setProtocol($request->getUri()->getScheme());
        $pagefiles = $sl->get('contentinum_page_files');
        $page = $pageOptions->split();
        $defaults = $sl->get('contentinum_page_defaults');
        if (isset($pagefiles[$page . '_pages'])) {
            $defaults->setCacheKey($page . '_pages');
            $pages = $defaults->get($pagefiles[$page . '_pages']);
            $pageOptions->addOptions($pages);
            if (isset($pages[$pageOptions->getQuery()])) {
                $pageOptions->addOptions($pages, '/' . $pageOptions->split(null, 5), true);
                $pageOptions->setActive('/' . $pageOptions->split(null, 5));
            } else {
                switch ($page) {
                    case 'api':
                    case 'mcevent':
                    case 'mcwork':
                    case 'municipal':
                    case 'feuerwehr':
                    case 'guestbook':
                    case 'newsletter':
                    case 'citizensbudget':
                    case 'eildienst':
                    case 'notification':
                    case 'registerdownload':
                        if (isset($pages['/' . $pageOptions->split(null, 3)])) {
                            $pageOptions->addOptions($pages, '/' . $pageOptions->split(null, 3), true);
                            $pageOptions->setActive('/' . $pageOptions->split(null, 3));
                        } elseif (isset($pages['/' . $pageOptions->split(null, $pageOptions->getSplitQuery())])) { // ... or isset page ...
                            $pageOptions->addOptions($pages, '/' . $pageOptions->split(null, $pageOptions->getSplitQuery()), true);
                            $pageOptions->setActive('/' . $pageOptions->split(null, $pageOptions->getSplitQuery()));
                        } else { // ... page not found send 404
                            die('not found');
                        }
                    break;
                    default:
                        die('not found');
                        break;
                }
            }
        } elseif (in_array($page, array(
            'login',
            'logout'
        ))) {
            if (isset($pagefiles['mcuser_customer_pages']) && is_file($pagefiles['mcuser_customer_pages'])){
                $defaults->setCacheKey('mcuser_customer_pages');
                $pages = $defaults->get('mcuser_customer_pages');
            } else {
                $defaults->setCacheKey('mcuser_pages');
                $pages = $defaults->get($pagefiles['mcuser_pages']);
            }
            $pageOptions->addOptions($pages); // default options
            $pageOptions->addOptions($pages, '/' . $pageOptions->split(null, 2), true);
            $pageOptions->setActive('/' . $pageOptions->split(null, 2));
         } else {

            $defaults->setCacheKey('app_pages');
            $pageOptions->addOptions($defaults->get($pagefiles['app_pages']));
            $url = $pageOptions->split($pageOptions->getQuery(), 1);
            switch ($url) {
                case 'sitemap.xml':
                case 'feed':
                case 'pdf':
                case 'emailrecom':
                case 'contentplugin':
                case 'jsonpages':
                    $pageOptions->addOptions($defaults->get($pagefiles['app_pages']), $url);
                    break;
                default:
                    if ('suche' == $url){
                        $controllerName = 'Contentinum\Controller\SearchController';
                    }

                    $preferences = $sl->get('contentinum_preference');
                    $pageOptions->addOptions($preferences);
                    $pageOptions->addOptions($preferences, $pageOptions->getHost());
                    $pages = $sl->get('contentinum_public_pages');
                    $hostId = $pageOptions->getHostId();
                    if (strlen($url) == 0) {
                        $url = 'index';
                    }
                    if (null !== ($page = $pages->$hostId->$language->$url)) {
                        $attribute = $sl->get('contentinum_attribute_pages');
                        $attribute = (is_array($attribute)) ? $attribute : $attribute->toArray();
                        (isset($attribute[$page['parentPage']])) ? $pageOptions->addOptions($attribute, $page['parentPage']) : false;
                        (isset($attribute[$page['id']])) ? $pageOptions->addOptions($attribute, $page['id']) : false;
                        $pageHeaders = $sl->get('contentinum_page_headers');
                        (isset($pageHeaders[$page['parentPage']])) ? $pageOptions->addPageHeaders($pageHeaders,$page['parentPage']) : false;
                        (isset($pageHeaders[$page['id']])) ? $pageOptions->addPageHeaders($pageHeaders, $page['id']) : false;
                        $pageOptions->addPage($page);
                    } else {
                        $preferences = $sl->get('contentinum_preference');
                        $pageOptions->addOptions($preferences);
                        $pageOptions->addOptions($preferences, $pageOptions->getHost());
                        $pages = $sl->get('contentinum_public_pages');
                        $hostId = $pageOptions->getHostId();
                        $page = $pages->$hostId->error;
                        $attribute = $sl->get('contentinum_attribute_pages');
                        $attribute = (is_array($attribute)) ? $attribute : $attribute->toArray();
                        (isset($attribute[$page['parentPage']])) ? $pageOptions->addOptions($attribute, $page['parentPage']) : false;
                        (isset($attribute[$page['id']])) ? $pageOptions->addOptions($attribute, $page['id']) : false;
                        $pageOptions->addPage($page);
                        $pageOptions->addAppOptions('controller', 'Contentinum\Controller\ErrorController');
                    }
                    break;
            }
        }
        $em = $sl->get($pageOptions->getApp('entitymanager'));
        $workerName = $pageOptions->getApp('worker');
        $worker = new $workerName($em);
        $worker->setSl($sl);
        if (false !== ($entityName = $pageOptions->getApp('entity'))) {
            $worker->setEntity(new $entityName());
        }
        if (false === $controllerName){
            $controllerName = $pageOptions->getApp('controller');
        }
        $controller = new $controllerName($pageOptions);
        $controller->setConfiguration($opt);
        $controller->setWorker($worker);
        $controller->setFormFactory($this->formFactory($sl, $pageOptions, $worker));
        return $controller;
    }

    /**
     *
     * @param ControllerManager $sl
     * @param Contentinum\Options\PageOptions $pageOptions
     * @param ContentinumComponents\Mapper\Worker $worker
     */
    protected function formFactory($sl, $pageOptions, $worker)
    {
        if (false !== ($formName = $pageOptions->getApp('form'))) {
            if (false !== ($targetEntities = $pageOptions->getApp('targetentities'))) {
                if (is_array($targetEntities) && ! empty($targetEntities)) {
                    foreach ($targetEntities as $key => $tEntity) {
                        $worker->addTargetEntities($key, $tEntity);
                    }
                }
            }
            $formFactory = new $formName($worker);
            $decorators = $sl->get($pageOptions->getApp('formdecorators'));
            $decorators = $decorators->default->toArray();
            if (false != ($formAttribs = $pageOptions->getApp('formattributes'))) {
                $decorators['deco-form']['form-attributtes'] = array_merge($decorators['deco-form']['form-attributtes'], $formAttribs);
            }
            $formFactory->setDecorators($decorators);
            $formFactory->setServiceLocator($sl);
            return $formFactory;
        } else {
            return false;
        }
    }
}


text:
import { Now, MapNowTuple } from "./now";
import { Behavior, SinkBehavior, MapBehaviorTuple } from "./behavior";
import { Stream, SinkStream } from "./stream";
import { Future, MapFutureTuple } from "./future";

export * from "./common";
export * from "./now";
export * from "./behavior";
export * from "./stream";
export * from "./future";
export * from "./time";
export * from "./placeholder";
export * from "./animation";
export * from "./clock";

export interface UnknownMappable {
  readonly map: (f: (a: A) => B) => UnknownMappable;
}

/**
 * Map a function over a behavior or stream. This means that if at some point in
 * time the value of `b` is `bVal` then the value of the returned
 * behavior is `fn(bVal)`.
 */
export function map(fn: (a: A) => B, future: Future): Future;
export function map(fn: (a: A) => B, stream: Stream): Stream;
export function map(fn: (a: A) => B, behavior: Behavior): Behavior;
export function map(fn: (a: A) => B, behavior: Now): Now;
export function map(
  fn: (a: A) => B,
  b: UnknownMappable
): UnknownMappable {
  return b.map(fn);
}

export function lift(
  f: (...args: A) => R,
  ...args: MapFutureTuple
): Future<R>;
export function lift(
  f: (...args: A) => R,
  ...args: MapBehaviorTuple
): Behavior<R>;
export function lift(
  f: (...args: A) => R,
  ...args: MapNowTuple
): Now<R>;
export function lift<R>(f: (...args: any) => R, ...args: any): any {
  return args[0].lift(f, ...args);
}

export function flat(b: Behavior<Behavior>): Behavior;
export function flat(f: Future<Future>): Future;
export function flat(n: Now<Now>): Now;
export function flat(o: { flat: () => any }): any {
  return o.flat();
}

export function push(a: A, sink: SinkBehavior | SinkStream): void {
  sink.push(a);
}

export function combine(...futures: Future[]): Future;
export function combine(...streams: Stream[]): Stream;
export function combine(
  ...values: Future[] | Stream[]
): Future | Stream {
  // FIXME: More performant implementation with benchmark
  return (values as any).reduce((a: any, b: any) => a.combine(b));
}


text:
package com.pedido.restaurante;

public class ObjetoProduto {

	private int _id;
	private int imagem, id_categoria;
	private String nome;
	private double preco;

	public ObjetoProduto( int _id , int id_categoria,  int imagem, String nome, double preco) {
		this._id = _id;
		this.id_categoria = id_categoria;
		this.imagem = imagem;
		this.nome = nome;
		this.preco = preco;
	}

	public int getId_categoria() {
		return id_categoria;
	}

	public void setId_categoria(int id_categoria) {
		this.id_categoria = id_categoria;
	}

	public int get_id() {
		return _id;
	}

	public void set_id(int _id) {
		this._id = _id;
	}

	public int getImagem() {
		return imagem;
	}

	public void setImagem(int imagem) {
		this.imagem = imagem;
	}

	public String getNome() {
		return nome;
	}

	public void setNome(String nome) {
		this.nome = nome;
	}

	public double getPreco() {
		return preco;
	}

	public void setPreco(double preco) {
		this.preco = preco;
	}
}