text:
package org.spongepowered.api.text;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.spongepowered.api.text.action.ClickAction;
import org.spongepowered.api.text.action.HoverAction;
import org.spongepowered.api.text.action.ShiftClickAction;
import org.spongepowered.api.text.format.TextColor;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.text.format.TextStyle;
import org.spongepowered.api.text.format.TextStyles;
import org.spongepowered.api.text.translation.Translation;

import java.util.Collections;
import java.util.List;

import javax.annotation.Nullable;

/**
 * Represents a builder class to create immutable {@link Text} instances.
 *
 * @see Text
 */
public abstract class TextBuilder {

    protected TextColor color = TextColors.NONE;
    protected TextStyle style = TextStyles.NONE;
    protected List<Text> children = Lists.newArrayList();
    @Nullable protected ClickAction<?> clickAction;
    @Nullable protected HoverAction<?> hoverAction;
    @Nullable protected ShiftClickAction<?> shiftClickAction;

    /**
     * Constructs a new empty {@link TextBuilder}.
     */
    protected TextBuilder() {
    }

    /**
     * Constructs a new {@link TextBuilder} with the properties of the given
     * {@link Text} as initial values.
     *
     * @param text The text to copy the values from
     */
    public TextBuilder(Text text) {
        checkNotNull(text, "text");
        this.color = text.color;
        this.style = text.style;
        this.children = Lists.newArrayList(text.children);
        this.clickAction = text.clickAction.orNull();
        this.hoverAction = text.hoverAction.orNull();
        this.shiftClickAction = text.shiftClickAction.orNull();
    }

    /**
     * Returns the current color of the {@link Text} in this builder.
     *
     * @return The current color
     * @see Text#getColor()
     */
    public final TextColor getColor() {
        return this.color;
    }

    /**
     * Sets the {@link TextColor} of this text.
     *
     * @param color The new text color for this text
     * @return This text builder
     * @see Text#getColor()
     */
    public TextBuilder color(TextColor color) {
        this.color = checkNotNull(color, "color");
        return this;
    }

    /**
     * Returns the current style of the {@link Text} in this builder.
     *
     * @return The current style
     * @see Text#getStyle()
     */
    public final TextStyle getStyle() {
        return this.style;
    }

    /**
     * Sets the text styles of this text. This will construct a composite
     * {@link TextStyle} of the current style and the specified styles first and
     * set it to the text.
     *
     * @param styles The text styles to apply
     * @return This text builder
     * @see Text#getStyle()
     */
    // TODO: Make sure this is the correct behaviour
    public TextBuilder style(TextStyle... styles) {
        this.style = this.style.and(styles);
        return this;
    }

    /**
     * Returns the current {@link ClickAction} of this builder.
     *
     * @return The current click action or {@link Optional#absent()} if none
     * @see Text#getClickAction()
     */
    public final Optional<ClickAction<?>> getClickAction() {
        return Optional.<ClickAction<?>>fromNullable(this.clickAction);
    }

    /**
     * Sets the {@link ClickAction} that will be executed if the text is clicked
     * in the chat.
     *
     * @param clickAction The new click action for the text
     * @return This text builder
     * @see Text#getClickAction()
     */
    public TextBuilder onClick(@Nullable ClickAction<?> clickAction) {
        this.clickAction = clickAction;
        return this;
    }

    /**
     * Returns the current {@link HoverAction} of this builder.
     *
     * @return The current hover action or {@link Optional#absent()} if none
     * @see Text#getHoverAction()
     */
    public final Optional<HoverAction<?>> getHoverAction() {
        return Optional.<HoverAction<?>>fromNullable(this.hoverAction);
    }

    /**
     * Sets the {@link HoverAction} that will be executed if the text is hovered
     * in the chat.
     *
     * @param hoverAction The new hover action for the text
     * @return This text builder
     * @see Text#getHoverAction()
     */
    public TextBuilder onHover(@Nullable HoverAction<?> hoverAction) {
        this.hoverAction = hoverAction;
        return this;
    }

    /**
     * Returns the current {@link ShiftClickAction} of this builder.
     *
     * @return The current shift click action or {@link Optional#absent()} if
     *         none
     * @see Text#getShiftClickAction()
     */
    public final Optional<ShiftClickAction<?>> getShiftClickAction() {
        return Optional.<ShiftClickAction<?>>fromNullable(this.shiftClickAction);
    }

    /**
     * Sets the {@link ShiftClickAction} that will be executed if the text is
     * shift-clicked in the chat.
     *
     * @param shiftClickAction The new shift click action for the text
     * @return This text builder
     * @see Text#getShiftClickAction()
     */
    public TextBuilder onShiftClick(@Nullable ShiftClickAction<?> shiftClickAction) {
        this.shiftClickAction = shiftClickAction;
        return this;
    }

    /**
     * Returns a view of the current children of this builder.
     *
     *
The returned list is unmodifiable, but not immutable. It will change
     * if new children get added through this builder.

     *
     * @return An unmodifiable list of the current children
     * @see Text#getChildren()
     */
    public final List<Text> getChildren() {
        return Collections.unmodifiableList(this.children);
    }

    /**
     * Appends the specified {@link Text} to the end of this text.
     *
     * @param children The texts to append
     * @return This text builder
     * @see Text#getChildren()
     */
    public TextBuilder append(Text... children) {
        for (Text child : checkNotNull(children, "children")) {
            checkNotNull(child, "child");
            this.children.add(child);
        }
        return this;
    }

    /**
     * Appends the specified {@link Text} to the end of this text.
     *
     * @param children The texts to append
     * @return This text builder
     * @see Text#getChildren()
     */
    public TextBuilder append(Iterable<? extends Text> children) {
        for (Text child : checkNotNull(children, "children")) {
            this.children.add(checkNotNull(child, "child"));
        }
        return this;
    }

    /**
     * Inserts the specified {@link Text} at the given position of this builder.
     *
     * @param pos The position to insert the texts to
     * @param children The texts to insert
     * @return This text builder
     * @throws IndexOutOfBoundsException If the position is out of bounds
     * @see Text#getChildren()
     */
    public TextBuilder insert(int pos, Text... children) {
        for (Text child : checkNotNull(children, "children")) {
            this.children.add(pos++, checkNotNull(child, "child"));
        }
        return this;
    }

    /**
     * Inserts the specified {@link Text} at the given position of this builder.
     *
     * @param pos The position to insert the texts to
     * @param children The texts to insert
     * @return This text builder
     * @throws IndexOutOfBoundsException If the position is out of range
     * @see Text#getChildren()
     */
    public TextBuilder insert(int pos, Iterable<? extends Text> children) {
        for (Text child : checkNotNull(children, "children")) {
            this.children.add(pos++, checkNotNull(child, "child"));
        }
        return this;
    }

    /**
     * Removes the specified {@link Text} from this builder.
     *
     * @param children The texts to remove
     * @return This text builder
     * @see Text#getChildren()
     */
    public TextBuilder remove(Text... children) {
        for (Text child : checkNotNull(children, "children")) {
            this.children.remove(checkNotNull(child));
        }
        return this;
    }

    /**
     * Removes the specified {@link Text} from this builder.
     *
     * @param children The texts to remove
     * @return This text builder
     * @see Text#getChildren()
     */
    public TextBuilder remove(Iterable<? extends Text> children) {
        for (Text child : checkNotNull(children, "children")) {
            this.children.remove(checkNotNull(child));
        }
        return this;
    }

    /**
     * Removes all children from this builder.
     *
     * @return This text builder
     * @see Text#getChildren()
     */
    public TextBuilder removeAll() {
        this.children.clear();
        return this;
    }

    /**
     * Builds an immutable instance of the current state of this text builder.
     *
     * @return An immutable {@link Text} with the current properties of this
     *         builder
     */
    public abstract Text build();

    @Override
    public boolean equals(@Nullable Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof TextBuilder)) {
            return false;
        }

        TextBuilder that = (TextBuilder) o;
        return Objects.equal(this.color, that.color)
                && Objects.equal(this.style, that.style)
                && Objects.equal(this.clickAction, that.clickAction)
                && Objects.equal(this.hoverAction, that.hoverAction)
                && Objects.equal(this.shiftClickAction, that.shiftClickAction)
                && Objects.equal(this.children, that.children);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(this.color, this.style, this.clickAction, this.hoverAction, this.shiftClickAction, this.children);
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(TextBuilder.class)
                .add("color", this.color)
                .add("style", this.style)
                .add("children", this.children)
                .add("clickAction", this.clickAction)
                .add("hoverAction", this.hoverAction)
                .add("shiftClickAction", this.shiftClickAction)
                .toString();
    }

    /**
     * Represents a {@link TextBuilder} creating immutable {@link Text.Literal}
     * instances.
     *
     * @see Text.Literal
     */
    public static class Literal extends TextBuilder {

        protected String content;

        /**
         * Constructs a new empty {@link Literal}.
         */
        public Literal() {
            this("");
        }

        /**
         * Constructs a new unformatted {@link Literal} with the given content.
         *
         * @param content The content for the text builder
         */
        public Literal(String content) {
            content(content);
        }

        /**
         * Constructs a new {@link Literal} with the formatting and actions of
         * the specified {@link Text} and the given content.
         *
         * @param text The text to apply the properties from
         * @param content The content for the text builder
         */
        public Literal(Text text, String content) {
            super(text);
            content(content);
        }

        /**
         * Constructs a new {@link Literal} with the formatting, actions and
         * content of the specified {@link Text.Literal}.
         *
         * @param text The text to apply the properties from
         */
        public Literal(Text.Literal text) {
            super(text);
            this.content = text.content;
        }

        /**
         * Returns the current content of this builder.
         *
         * @return The current content
         * @see Text.Literal#getContent()
         */
        public final String getContent() {
            return this.content;
        }

        /**
         * Sets the plain text content of this text.
         *
         * @param content The content of this text
         * @return This text builder
         * @see Text.Literal#getContent()
         */
        public Literal content(String content) {
            this.content = checkNotNull(content, "content");
            return this;
        }

        @Override
        public Text.Literal build() {
            // Special case for empty builder
            if (this.content.isEmpty() && this.color == TextColors.NONE && this.style.isEmpty() && this.children.isEmpty()
                    && this.clickAction == null && this.hoverAction == null && this.shiftClickAction == null) {
                return Texts.EMPTY;
            }

            return new Text.Literal(
                    this.color,
                    this.style,
                    ImmutableList.copyOf(this.children),
                    this.clickAction,
                    this.hoverAction,
                    this.shiftClickAction,
                    this.content);
        }

        @Override
        public boolean equals(@Nullable Object o) {
            if (this == o) {
                return true;
            }
            if (!(o instanceof Literal) || !super.equals(o)) {
                return false;
            }

            Literal that = (Literal) o;
            return Objects.equal(this.content, that.content);

        }

        @Override
        public int hashCode() {
            return Objects.hashCode(super.hashCode(), this.content);
        }

        @Override
        public String toString() {
            return Objects.toStringHelper(this)
                    .addValue(super.toString())
                    .add("content", this.content)
                    .toString();
        }

        @Override
        public Literal color(TextColor color) {
            return (Literal) super.color(color);
        }

        @Override
        public Literal style(TextStyle... styles) {
            return (Literal) super.style(styles);
        }

        @Override
        public Literal onClick(@Nullable ClickAction<?> clickAction) {
            return (Literal) super.onClick(clickAction);
        }

        @Override
        public Literal onHover(@Nullable HoverAction<?> hoverAction) {
            return (Literal) super.onHover(hoverAction);
        }

        @Override
        public Literal onShiftClick(@Nullable ShiftClickAction<?> shiftClickAction) {
            return (Literal) super.onShiftClick(shiftClickAction);
        }

        @Override
        public Literal append(Text... children) {
            return (Literal) super.append(children);
        }

        @Override
        public Literal append(Iterable<? extends Text> children) {
            return (Literal) super.append(children);
        }

        @Override
        public Literal insert(int pos, Text... children) {
            return (Literal) super.insert(pos, children);
        }

        @Override
        public Literal insert(int pos, Iterable<? extends Text> children) {
            return (Literal) super.insert(pos, children);
        }

        @Override
        public Literal remove(Text... children) {
            return (Literal) super.remove(children);
        }

        @Override
        public Literal remove(Iterable<? extends Text> children) {
            return (Literal) super.remove(children);
        }

        @Override
        public Literal removeAll() {
            return (Literal) super.removeAll();
        }

    }

    /**
     * Represents a {@link TextBuilder} creating immutable
     * {@link Text.Translatable} instances.
     *
     * @see Text.Translatable
     */
    public static class Translatable extends TextBuilder {

        protected Translation translation;
        protected ImmutableList<Object> arguments;

        /**
         * Constructs a new unformatted {@link Translatable} with the given
         * {@link Translation} and arguments.
         *
         * @param translation The translation for the builder
         * @param args The arguments for the translation
         */
        public Translatable(Translation translation, Object... args) {
            translation(translation, args);
        }

        /**
         * Constructs a new unformatted {@link TextBuilder.Translatable} from
         * the given {@link org.spongepowered.api.text.translation.Translatable}
         * .
         *
         * @param translatable The translatable for the builder
         * @param args The arguments for the translation
         */
        public Translatable(org.spongepowered.api.text.translation.Translatable translatable, Object... args) {
            translation(translatable, args);
        }

        /**
         * Constructs a new {@link Translatable} with the formatting and actions
         * of the specified {@link Text} and the given {@link Translation} and
         * arguments.
         *
         * @param text The text to apply the properties from
         * @param translation The translation for the builder
         * @param args The arguments for the translation
         */
        public Translatable(Text text, Translation translation, Object... args) {
            super(text);
            translation(translation, args);
        }

        /**
         * Constructs a new {@link Translatable} with the formatting and actions
         * of the specified {@link Text} and the given
         * {@link org.spongepowered.api.text.translation.Translatable}.
         *
         * @param text The text to apply the properties from
         * @param translatable The translatable for the builder
         * @param args The arguments for the translation
         */
        public Translatable(Text text, org.spongepowered.api.text.translation.Translatable translatable, Object... args) {
            super(text);
            translation(translatable, args);
        }

        /**
         * Constructs a new {@link Translatable} with the formatting, actions
         * and translation of the specified {@link Text.Translatable}.
         *
         * @param text The text to apply the properties from
         */
        public Translatable(Text.Translatable text) {
            super(text);
            this.translation = text.translation;
            this.arguments = text.arguments;
        }

        /**
         * Returns the current translation of this builder.
         *
         * @return The current content
         * @see Text.Translatable#getTranslation()
         */
        public final Translation getTranslation() {
            return this.translation;
        }

        /**
         * Returns the current translation arguments of this builder.
         *
         * @return The current translation arguments
         * @see Text.Translatable#getArguments()
         */
        public final ImmutableList<Object> getArguments() {
            return this.arguments;
        }

        /**
         * Sets the translation of the text.
         *
         * @param translation The translation to use for this builder
         * @param args The arguments for the translation
         * @return This text builder
         */
        public Translatable translation(Translation translation, Object... args) {
            this.translation = checkNotNull(translation, "translation");
            this.arguments = ImmutableList.copyOf(checkNotNull(args, "args"));
            return this;
        }

        /**
         * Sets the translation of the text.
         *
         * @param translatable The translatable object to use for this builder
         * @param args The arguments for the translation
         * @return This text builder
         */
        public Translatable translation(org.spongepowered.api.text.translation.Translatable translatable, Object... args) {
            return translation(checkNotNull(translatable, "translatable").getTranslation(), args);
        }

        @Override
        public Text.Translatable build() {
            return new Text.Translatable(
                    this.color,
                    this.style,
                    ImmutableList.copyOf(this.children),
                    this.clickAction,
                    this.hoverAction,
                    this.shiftClickAction,
                    this.translation,
                    this.arguments);
        }

        @Override
        public boolean equals(@Nullable Object o) {
            if (this == o) {
                return true;
            }
            if (!(o instanceof Translatable) || !super.equals(o)) {
                return false;
            }

            Translatable that = (Translatable) o;
            return Objects.equal(this.translation, that.translation)
                    && Objects.equal(this.arguments, that.arguments);

        }

        @Override
        public int hashCode() {
            return Objects.hashCode(super.hashCode(), this.translation, this.arguments);
        }

        @Override
        public String toString() {
            return Objects.toStringHelper(this)
                    .addValue(super.toString())
                    .add("translation", this.translation)
                    .add("arguments", this.arguments)
                    .toString();
        }

        @Override
        public Translatable color(TextColor color) {
            return (Translatable) super.color(color);
        }

        @Override
        public Translatable style(TextStyle... styles) {
            return (Translatable) super.style(styles);
        }

        @Override
        public Translatable onClick(@Nullable ClickAction<?> clickAction) {
            return (Translatable) super.onClick(clickAction);
        }

        @Override
        public Translatable onHover(@Nullable HoverAction<?> hoverAction) {
            return (Translatable) super.onHover(hoverAction);
        }

        @Override
        public Translatable onShiftClick(@Nullable ShiftClickAction<?> shiftClickAction) {
            return (Translatable) super.onShiftClick(shiftClickAction);
        }

        @Override
        public Translatable append(Text... children) {
            return (Translatable) super.append(children);
        }

        @Override
        public Translatable append(Iterable<? extends Text> children) {
            return (Translatable) super.append(children);
        }

        @Override
        public Translatable insert(int pos, Text... children) {
            return (Translatable) super.insert(pos, children);
        }

        @Override
        public Translatable insert(int pos, Iterable<? extends Text> children) {
            return (Translatable) super.insert(pos, children);
        }

        @Override
        public Translatable remove(Text... children) {
            return (Translatable) super.remove(children);
        }

        @Override
        public Translatable remove(Iterable<? extends Text> children) {
            return (Translatable) super.remove(children);
        }

        @Override
        public Translatable removeAll() {
            return (Translatable) super.removeAll();
        }

    }

    /**
     * Represents a {@link TextBuilder} creating immutable {@link Text.Selector}
     * instances.
     *
     * @see Text.Selector
     */
    public static class Selector extends TextBuilder {

        protected org.spongepowered.api.text.selector.Selector selector;

        /**
         * Constructs a new unformatted {@link Selector} with the given
         * selector.
         *
         * @param selector The selector for the builder
         */
        public Selector(org.spongepowered.api.text.selector.Selector selector) {
            selector(selector);
        }

        /**
         * Constructs a new {@link Selector} with the formatting and actions of
         * the specified {@link Text} and the given selector.
         *
         * @param text The text to apply the properties from
         * @param selector The selector for the builder
         */
        public Selector(Text text, org.spongepowered.api.text.selector.Selector selector) {
            super(text);
            selector(selector);
        }

        /**
         * Constructs a new {@link Selector} with the formatting, actions and
         * selector of the specified {@link Text.Selector}.
         *
         * @param text The text to apply the properties from
         */
        public Selector(Text.Selector text) {
            super(text);
            this.selector = text.selector;
        }

        /**
         * Returns the current selector of this builder.
         *
         * @return The current selector
         * @see Text.Selector#getSelector()
         */
        public final org.spongepowered.api.text.selector.Selector getSelector() {
            return this.selector;
        }

        /**
         * Sets the selector of the text.
         *
         * @param selector The selector for this builder to use
         * @return This text builder
         * @see Text.Selector#getSelector()
         */
        public Selector selector(org.spongepowered.api.text.selector.Selector selector) {
            this.selector = checkNotNull(selector, "selector");
            return this;
        }

        @Override
        public Text.Selector build() {
            return new Text.Selector(
                    this.color,
                    this.style,
                    ImmutableList.copyOf(this.children),
                    this.clickAction,
                    this.hoverAction,
                    this.shiftClickAction,
                    this.selector);
        }

        @Override
        public boolean equals(@Nullable Object o) {
            if (this == o) {
                return true;
            }
            if (!(o instanceof Selector) || !super.equals(o)) {
                return false;
            }

            Selector that = (Selector) o;
            return Objects.equal(this.selector, that.selector);

        }

        @Override
        public int hashCode() {
            return Objects.hashCode(super.hashCode(), this.selector);
        }

        @Override
        public String toString() {
            return Objects.toStringHelper(this)
                    .addValue(super.toString())
                    .add("selector", this.selector)
                    .toString();
        }

        @Override
        public Selector color(TextColor color) {
            return (Selector) super.color(color);
        }

        @Override
        public Selector style(TextStyle... styles) {
            return (Selector) super.style(styles);
        }

        @Override
        public Selector onClick(@Nullable ClickAction<?> clickAction) {
            return (Selector) super.onClick(clickAction);
        }

        @Override
        public Selector onHover(@Nullable HoverAction<?> hoverAction) {
            return (Selector) super.onHover(hoverAction);
        }

        @Override
        public Selector onShiftClick(@Nullable ShiftClickAction<?> shiftClickAction) {
            return (Selector) super.onShiftClick(shiftClickAction);
        }

        @Override
        public Selector append(Text... children) {
            return (Selector) super.append(children);
        }

        @Override
        public Selector append(Iterable<? extends Text> children) {
            return (Selector) super.append(children);
        }

        @Override
        public Selector insert(int pos, Text... children) {
            return (Selector) super.insert(pos, children);
        }

        @Override
        public Selector insert(int pos, Iterable<? extends Text> children) {
            return (Selector) super.insert(pos, children);
        }

        @Override
        public Selector remove(Text... children) {
            return (Selector) super.remove(children);
        }

        @Override
        public Selector remove(Iterable<? extends Text> children) {
            return (Selector) super.remove(children);
        }

        @Override
        public Selector removeAll() {
            return (Selector) super.removeAll();
        }

    }

    /**
     * Represents a {@link TextBuilder} creating immutable {@link Text.Score}
     * instances.
     *
     * @see Text.Score
     */
    public static class Score extends TextBuilder {

        protected org.spongepowered.api.scoreboard.Score score;
        @Nullable protected String override;

        /**
         * Constructs a new unformatted {@link Score} with the given score.
         *
         * @param score The score for the text builder
         */
        public Score(org.spongepowered.api.scoreboard.Score score) {
            score(score);
        }

        /**
         * Constructs a new {@link Score} with the formatting and actions of the
         * specified {@link Text} and the given score.
         *
         * @param text The text to apply the properties from
         * @param score The score for the text builder
         */
        public Score(Text text, org.spongepowered.api.scoreboard.Score score) {
            super(text);
            score(score);
        }

        /**
         * Constructs a new {@link Score} with the formatting, actions and score
         * of the specified {@link Text.Score}.
         *
         * @param text The text to apply the properties from
         */
        public Score(Text.Score text) {
            super(text);
            this.score = text.score;
            this.override = text.override.orNull();
        }

        /**
         * Returns the current score of this builder.
         *
         * @return The current score
         * @see Text.Score#getScore()
         */
        public final org.spongepowered.api.scoreboard.Score getScore() {
            return this.score;
        }

        /**
         * Sets the score of the text.
         *
         * @param score The score for this builder to use
         * @return This text builder
         * @see Text.Score#getScore()
         */
        public Score score(org.spongepowered.api.scoreboard.Score score) {
            this.score = checkNotNull(score, "score");
            return this;
        }

        /**
         * Returns the current override of this builder.
         *
         * @return The current override, or {@link Optional#absent()} if none
         * @see Text.Score#getOverride()
         */
        public final Optional<String> getOverride() {
            return Optional.fromNullable(this.override);
        }

        /**
         * Overrides the real score and displays a custom text instead.
         *
         * @param override The text to override the score with or {@code null}
         *        to reset
         * @return This text builder
         * @see Text.Score#getOverride()
         */
        public Score override(@Nullable String override) {
            this.override = override;
            return this;
        }

        @Override
        public Text.Score build() {
            return new Text.Score(
                    this.color,
                    this.style,
                    ImmutableList.copyOf(this.children),
                    this.clickAction,
                    this.hoverAction,
                    this.shiftClickAction,
                    this.score,
                    this.override);
        }

        @Override
        public boolean equals(@Nullable Object o) {
            if (this == o) {
                return true;
            }
            if (!(o instanceof Score) || !super.equals(o)) {
                return false;
            }

            Score that = (Score) o;
            return Objects.equal(this.score, that.score)
                    && Objects.equal(this.override, that.override);
        }

        @Override
        public int hashCode() {
            return Objects.hashCode(super.hashCode(), this.score, this.override);
        }

        @Override
        public String toString() {
            return Objects.toStringHelper(this)
                    .addValue(super.toString())
                    .add("score", this.score)
                    .add("override", this.override)
                    .toString();
        }

        @Override
        public Score color(TextColor color) {
            return (Score) super.color(color);
        }

        @Override
        public Score style(TextStyle... styles) {
            return (Score) super.style(styles);
        }

        @Override
        public Score onClick(@Nullable ClickAction<?> clickAction) {
            return (Score) super.onClick(clickAction);
        }

        @Override
        public Score onHover(@Nullable HoverAction<?> hoverAction) {
            return (Score) super.onHover(hoverAction);
        }

        @Override
        public Score onShiftClick(@Nullable ShiftClickAction<?> shiftClickAction) {
            return (Score) super.onShiftClick(shiftClickAction);
        }

        @Override
        public Score append(Text... children) {
            return (Score) super.append(children);
        }

        @Override
        public Score append(Iterable<? extends Text> children) {
            return (Score) super.append(children);
        }

        @Override
        public Score insert(int pos, Text... children) {
            return (Score) super.insert(pos, children);
        }

        @Override
        public Score insert(int pos, Iterable<? extends Text> children) {
            return (Score) super.insert(pos, children);
        }

        @Override
        public Score remove(Text... children) {
            return (Score) super.remove(children);
        }

        @Override
        public Score remove(Iterable<? extends Text> children) {
            return (Score) super.remove(children);
        }

        @Override
        public Score removeAll() {
            return (Score) super.removeAll();
        }

    }

}


text:
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { RouterTestingModule } from '@angular/router/testing';
import { FilterEvent } from 'patternfly-ng/filter';
import { SortEvent } from 'patternfly-ng/sort';
import { initContext, TestContext } from 'testing/test-context';
import { AreasToolbarComponent } from './areas-toolbar.component';

@Component({
  template: `
    <areas-toolbar
      (onFilterChange)="filterChange($event)"
      (onSortChange)="sortChange($event)"
      [resultsCount]="resultsCount"
    >
    </areas-toolbar>
  `,
})
class HostComponent {
  public resultsCount = 0;

  public filterChange($event: FilterEvent) {}

  public sortChange($event: SortEvent) {}
}

@Component({
  selector: 'pfng-toolbar',
  template: '',
})
class FakePfngToolbarComponent {
  @Input() config: any;

  @Input() viewTemplate: any;

  @Output() onFilterChange = new EventEmitter<FilterEvent>();

  @Output() onSortChange = new EventEmitter<SortEvent>();
}

describe('AreasToolbarComponent', () => {
  type Context = TestContext<AreasToolbarComponent, HostComponent>;
  const testContext = initContext(AreasToolbarComponent, HostComponent, {
    declarations: [FakePfngToolbarComponent],
    imports: [RouterTestingModule],
  });

  it('should update filterConfig resultsCount', () => {
    const initialCount = 0;
    expect(testContext.testedDirective.filterConfig.resultsCount).toBe(initialCount);

    const nextCount = 5;
    testContext.hostComponent.resultsCount = nextCount;
    testContext.detectChanges();

    expect(testContext.testedDirective.filterConfig.resultsCount).toBe(nextCount);
  });
});

redpajama_set_name: RedPajamaGithub


text:
using FluentSharp.NUnit;
using NUnit.Framework;

namespace FluentSharp.CoreLib.Test
{
    [TestFixture]
    public class Test_Reflection_ExtensionMethods_Types : NUnitTests

    {
        [Test(Description="Returns the base types of the provided objects (if addParent is set, the type provided will be included)")]
        public void baseTypes()
        {

            var type = this.type();

            type.baseTypes()     .assert_Not_Null()
                                 .assert_Not_Empty()
                                 .assert_Size_Is(2)
                                 .assert_Item_Is_Equal(0, typeof(NUnitTests))
                                 .assert_Item_Is_Equal(1, typeof(object));

            //with addParent = false, the result should be the same as above
            type.baseTypes(false).assert_Not_Null()
                                 .assert_Not_Empty()
                                 .assert_Size_Is(2)
                                 .assert_Item_Is_Equal(0, typeof(NUnitTests))
                                 .assert_Item_Is_Equal(1, typeof(object));

            //with addParent = true, the result should have one more class (the type used to map the base types)
            type.baseTypes(true ).assert_Not_Null()
                                 .assert_Not_Empty()
                                 .assert_Size_Is(3)
                                 .assert_Item_Is_Equal(0, this.type())
                                 .assert_Item_Is_Equal(1, typeof(NUnitTests))
                                 .assert_Item_Is_Equal(2, typeof(object));

        }
    }
}


text:
package runtime_test

import (
	"testing"

	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/testapi"
	"k8s.io/kubernetes/pkg/apimachinery/registered"
	"k8s.io/kubernetes/pkg/runtime"
)

func TestDecodeList(t *testing.T) {
	pl := &api.List{
		Items: []runtime.Object{
			&api.Pod{ObjectMeta: api.ObjectMeta{Name: "1"}},
			&runtime.Unknown{
				TypeMeta:    runtime.TypeMeta{Kind: "Pod", APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String()},
				Raw:         []byte(`{"kind":"Pod","apiVersion":"` + registered.GroupOrDie(api.GroupName).GroupVersion.String() + `","metadata":{"name":"test"}}`),
				ContentType: runtime.ContentTypeJSON,
			},
			&runtime.Unstructured{
				Object: map[string]interface{}{
					"kind":       "Foo",
					"apiVersion": "Bar",
					"test":       "value",
				},
			},
		},
	}
	if errs := runtime.DecodeList(pl.Items, testapi.Default.Codec()); len(errs) != 0 {
		t.Fatalf("unexpected error %v", errs)
	}
	if pod, ok := pl.Items[1].(*api.Pod); !ok || pod.Name != "test" {
		t.Errorf("object not converted: %#v", pl.Items[1])
	}
}


text:
package org.apache.cassandra.cql3;

import org.junit.Test;

public class RangeDeletionTest extends CQLTester
{
    @Test
    public void testCassandra8558() throws Throwable
    {
        createTable("CREATE TABLE %s (a int, b int, c int, d int, PRIMARY KEY (a, b, c))");

        execute("INSERT INTO %s (a, b, c, d) VALUES (?, ?, ?, ?)", 1, 1, 1, 1);
        flush();
        execute("DELETE FROM %s WHERE a=? AND b=?", 1, 1);
        flush();
        assertEmpty(execute("SELECT * FROM %s WHERE a=? AND b=? AND c=?", 1, 1, 1));
    }
}


text:
/*
 * (c) 2013-2018 Andreas Kuntner
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using MVVMbasics.Attributes;
using MVVMbasics.Exceptions;
using MVVMbasics.Services;

namespace MVVMbasics.Helpers
{
	/// <summary>
	/// Service locator that allows services to be registered and retrieved. All services must implement the
	/// <see cref="MVVMbasics.Services.IService">IService</see> interface in order to be detected by
	/// <c>ServiceLocator</c>.
	/// </summary>
	public class ServiceLocator
	{
		#region Members

		/// <summary>
		/// Collection of all registered service instances.
		/// </summary>
		private readonly List<IService> _instances = new List<IService>();

		/// <summary>
		/// Collection of all registered service types that have not yet been registered.
		/// </summary>
		private readonly List<TypeInfo> _types = new List<TypeInfo>();

		#endregion

		#region Register Methods

		/// <summary>
		/// Registers an instance of a certain service.
		/// </summary>
		/// <param name="service">Service to be registered.</param>
		public void Register(IService service)
		{
			// If service of the same kind has already been registered,
			// throw an exception
			if (_instances.Any(i => i.GetType() == service.GetType())
				|| _types.Any(t => t.Equals(service.GetType().GetTypeInfo())))
			{
				throw new ServiceRegistrationException("Service of type '" + service.GetType().FullName + "' is already registered.");
			}
			// If not, register the given service
			_instances.Add(service);
		}

		/// <summary>
		/// Registers a reference to a certain service type, without instantly instantiating it.
		/// </summary>
		/// <typeparam name="T">Type of service to be registered (must be a subclass of
		/// <see cref="MVVMbasics.Services.IService">IService</see>).</typeparam>
		public void Register<T>() where T : IService
		{
			// If service of the same kind has already been registered,
			// throw an exception
			if (_instances.Any(i => i.GetType() == typeof(T))
				|| _types.Any(t => t.Equals(typeof(T).GetTypeInfo())))
			{
				throw new ServiceRegistrationException("Service of type '" + typeof(T).FullName + "' is already registered.");
			}
			// If not, register the given service
			_types.Add(typeof(T).GetTypeInfo());
		}

		/// <summary>
		/// Traverses all services that are located in a given assembly and registers their types, without instantly
		/// instantiating them.
		/// </summary>
		/// <param name="assembly">The assembly to be scanned. If NULL or not specified, the calling  assembly will be
		/// scanned.</param>
		public void RegisterAll(Assembly assembly = null)
		{
			RegisterAll(null, assembly);
		}

		/// <summary>
		/// Traverses all services that are located in a given namespace inside a given assembly and registers their
		/// types, without instantly instantiating them.
		/// </summary>
		/// <param name="ns">Namespace to be scanned. If ends with '.*', also sub-directories will be scanned. If NULL,
		/// the whole assembly will be scanned.</param>
		/// <param name="assembly">The assembly to be scanned. If NULL, the calling assembly will be scanned.</param>
		public void RegisterAll(string ns, Assembly assembly = null)
		{
			// List all classes that fulfill the following criteria:
			// (1) extend IService
			// (2) are located in the given namespace
			if (assembly == null)
				assembly = Assembly.GetEntryAssembly();
			IEnumerable<TypeInfo> services;
			if (ns != null)
				services = from t in assembly.DefinedTypes
						   where
							   t.Namespace != null && t.IsClass && typeof(IService).GetTypeInfo().IsAssignableFrom(t) &&
							   t.GetCustomAttributes(typeof(MvvmServiceAttribute), true).Any() &&
							   (t.Namespace.Equals(ns) || (ns.EndsWith(".*") && t.Namespace.StartsWith(ns.Replace(".*", String.Empty))))
						   select t;
			else
				services = from t in assembly.DefinedTypes
						   where t.IsClass && typeof(IService).GetTypeInfo().IsAssignableFrom(t) &&
							t.GetCustomAttributes(typeof(MvvmServiceAttribute), true).Any()
						   select t;

			// Register all detected service types, if not already registered
			foreach (var service in services)
			{
				if (_instances.All(i => !i.GetType().GetTypeInfo().Equals(service))
					&& _types.All(t => !t.Equals(service)))
				{
					_types.Add(service);
				}
			}
		}

		#endregion

		#region Contains Method

		/// <summary>
		/// Returns TRUE if a certain kind of service has been registered, FALSE otherwise.
		/// </summary>
		/// <typeparam name="T">Type of service to be retrieved (must be a subclass of
		/// <see cref="MVVMbasics.Services.IService">IService</see>.</typeparam>
		/// <returns>TRUE if a certain kind of service has been registered, FALSE otherwise.</returns>
		public bool Contains<T>()
		{
			return (_instances.Any(i => i is T) || _types.Any(t => typeof(T).GetTypeInfo().IsAssignableFrom(t)));
		}

		#endregion

		#region Retrieve Methods

		/// <summary>
		/// Creates a service instance, stores and returns it, or throws an exception if no matching service has been
		/// registered.
		/// </summary>
		/// <typeparam name="T">Type of service to be retrieved (must be a subclass of
		/// <see cref="MVVMbasics.Services.IService">IService</see>.</typeparam>
		/// <returns>Instance of the requested service.</returns>
		public T Retrieve<T>()
		{
			return Retrieve<T>(true);
		}

		/// <summary>
		/// Creates and returns a service instance without storing it, or throws an exception if no matching service has
		/// been registered.
		/// </summary>
		/// <typeparam name="T">Type of service to be retrieved (must be a subclass of
		/// <see cref="MVVMbasics.Services.IService">IService</see>.</typeparam>
		/// <returns>Instance of the requested service.</returns>
		public T RetrieveOnce<T>()
		{
			return Retrieve<T>(false);
		}

		/// <summary>
		/// Creates a service instance, stores it, and returns TRUE, if a matching service has been registered. If no
		/// matching service is found, returns FALSE.
		/// </summary>
		/// <typeparam name="T">Type of service to be retrieved (must be a subclass of
		/// <see cref="MVVMbasics.Services.IService">IService</see>.</typeparam>
		/// <param name="serviceInstance">Instance of the requested service.</param>
		/// <returns>TRUE if the requested service was found, FALSE otherwise.</returns>
		public bool TryRetrieve<T>(out T serviceInstance)
		{
			return TryRetrieve(out serviceInstance, true);
		}

		/// <summary>
		/// Creates a service instance and returns TRUE, if a matching service has been registered. If no matching
		/// service is found, returns FALSE.
		/// </summary>
		/// <typeparam name="T">Type of service to be retrieved</typeparam>
		/// <param name="serviceInstance">Instance of the requested service</param>
		/// <returns>TRUE if the requested service was found, FALSE otherwise</returns>
		public bool TryRetrieveOnce<T>(out T serviceInstance)
		{
			return TryRetrieve(out serviceInstance, false);
		}

		/// <summary>
		/// Creates a service instance, stores it if desired, and returns TRUE, if a matching service has been
		/// registered. If no matching service is found, returns FALSE.
		/// </summary>
		/// <typeparam name="T">Type of service to be retrieved (must be a subclass of
		/// <see cref="MVVMbasics.Services.IService">IService</see>.</typeparam>
		/// <param name="serviceInstance">Instance of the requested service.</param>
		/// <param name="instantiateAndStore">Flag indicating whether the service's instance shall be stored or not.
		/// </param>
		/// <returns>TRUE if the requested service was found, FALSE otherwise.</returns>
		private bool TryRetrieve<T>(out T serviceInstance, bool instantiateAndStore)
		{
			if (Contains<T>())
			{
				serviceInstance = Retrieve<T>(instantiateAndStore);
				return true;
			}
			else
			{
				serviceInstance = default(T);
				return false;
			}
		}

		/// <summary>
		/// Creates a service instance and stores and returns it if desired. If no matching service has been registered,
		/// an exception is thrown.
		/// </summary>
		/// <typeparam name="T">Type of service to be retrieved (must be a subclass of
		/// <see cref="MVVMbasics.Services.IService">IService</see>.</typeparam>
		/// <param name="instantiateAndStore">Flag indicating whether the service's instance shall be stored or not.
		/// </param>
		/// <returns>Instance of the requested service.</returns>
		private T Retrieve<T>(bool instantiateAndStore)
		{
			// Loop through all registered services that have already been instantiated to find the requested one
			foreach (var instance in _instances)
			{
				if (instance is T)
				{
					return (T)instance;
				}
			}

			// If not found, loop through all registered services that are not yet instantiated to find the requested
			// type
			foreach (var type in _types)
			{
				if (typeof(T).GetTypeInfo().IsAssignableFrom(type))
				{
					// If a matching type is found, instantiate it and pass a reference to the ServiceLocator if
					// requested
					object instance = null;
					foreach (var constructor in typeof(T).GetTypeInfo().DeclaredConstructors)
					{
						if (constructor.GetParameters().Count() == 1)
						{
							if (constructor.GetParameters()[0].ParameterType == typeof(ServiceLocator))
							{
								instance = Activator.CreateInstance(type.AsType(), this);
							}
						}
					}
					if (instance == null)
						instance = (T)Activator.CreateInstance(type.AsType());

					// If desired, delete the type reference and store the instance
					if (instantiateAndStore)
					{
						_instances.Add((IService)instance);
						_types.Remove(type);
					}

					// Finally return the instance
					return (T) instance;
				}
			}

			// If no matching service is found, throw an exception
			throw new ServiceNotFoundException();
		}

		#endregion
	}
}


text:
var app = angular.module('HackathonApp', ['firebase']);

app.controller('HackathonCtl', ['$scope', '$firebase', function($scope, $firebase) {

    $scope.init = function() {
        // Firebase
        var my_chat_ref = new Firebase('https://glowing-fire-2233.firebaseio.com/my_chats');

        $scope.my_name = '';
        $scope.my_saved_name = 'Friend';
        $scope.my_chat = '';
        $scope.my_chats = $firebase(my_chat_ref);
        $scope.my_name_is_saved = false;
        $scope.my_channels = [
            'Lobby',
            'Among Friends',
            'Hover to delete'
        ];
        $scope.my_channel = $scope.my_channels[0];
        $scope.my_new_channel = '';
    };

    $scope.send_my_name = function() {
        $scope.my_saved_name = $scope.my_name;
        $scope.my_name_is_saved = true;
    };

    $scope.send_my_chat = function() {
        $scope.my_chats.$add({
            user: $scope.my_saved_name,
            channel: $scope.my_channel,
            message: $scope.my_chat
        });
        $scope.my_chat = '';
    };

    $scope.set_my_channel = function(channel) {
        $scope.my_channel = channel;
    };

    $scope.delete_my_channel = function(channel) {
        var index = $scope.my_channels.indexOf(channel);
        $scope.my_channels.splice(index);
    };

    $scope.create_new_channel = function() {
        $scope.my_channels.push($scope.my_new_channel);
        $scope.my_channel = $scope.my_new_channel;
        $scope.my_new_channel = '';
    };

}]);


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="aliens" content="">
    <meta name="daily dose" content="">

    <title>Blogs</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/clean-blog.min.css" rel="stylesheet">

    <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                        Home

                        About

                        Blogs

                        Contact

Extra Terrestials

Threat, Hoax Or Future

                        Posted by Daily Dose on ,Sep 22 2015

Written By- Mahesh Prasad Mishra

Editing And Inputs By- Baibaswata Jena

Overview

Most of us firmly believe that the universe originated from a single point, followed by a big bang phenomenon and after an unpredictable number of years ,we came into existence on a small celestial sphere called planet Earth. The question that "From where did that 'single point' originate?" is certainly a food for thought. We may also have a thought sometimes that "Are we the only entities in this whole universe ?".But over few decades there have been instances which have challenged our beliefs and thoughts.My personal opinion: "We are not alone". But opinions differ.
Let us discuss few instances.

Apollo 11 Mission

This was a revolutionary mission for the human race and it certainly possessed its own set of intricacies and intrigues.Neil Amstrong became the first man to step on Moon followed by his compatriot Edwin 'Buzz' Aldrin. But,Russians said that it was  faked by USA,but their protest did not garner any support as it was not based on a scientific foundation.However,there is belief that the crew of Apollo 11 had witnessed some extra terrestial activities.But,they were sworn to secrecy till death by the government. The full report of the program is believed to be kept in a file referred to as "X-files" by the conspiracy theorists.  Aldrin clarified what he saw on July 8:
On Apollo 11  on route to the Moon, I observed a light out of the window that appeared to be moving alongside us.

There were many explanations of what that could be, other than another spacecraft from another country or another world - it was either the rocket we had separated from, or the 4 panels that moved away when we extracted the lander from the rocket and we were nose to nose with the two spacecraft. So in close vicinity, moving away, were 4 panels. And I feel absolutely convinced that we were looking at the sun reflected off of one of these panels. Which one? I don't know. So technically, the definition could be "unidentified."
So this phenomenon raises  a lot of question.

Area 51

Area 51 is located in the southern portion of Nevada in the western United States, 83 miles (134 km) north-northwest of Las Vegas. Situated at its centre, on the southern shore of Groom Lake, is a large military airfield. The site was acquired by the United States Air Force in 1955, primarily for the flight testing of the Lockheed U-2 aircraft. The area around Area 51, including the small town of Rachel on the aptly named "Extraterrestrial Highway", is a popular tourist destination.

There have been a lot of conspiracy theories on this highly secretive and complicated area where things happen beyond our imagination, may be something not very earthly. Conspiracy theorists believe that the remains of crashed UFO spacecrafts are stored at this Area 51, an Air Force base about 150 miles from Las Vegas, where government scientists reverse-engineer the aliens' highly advanced technology. Fodder for this has come from a variety of supposed UFO sightings in the area and testimony from a retired Army colonel who says he was given access to extraterrestrial materials gathered from an alien spacecraft that crashed in Roswell, New Mexico. Some believe that the government studies time travel at Area 51, also known as Groom Lake or Dreamland.

Yet More Unsolved Mysteries

1.Crop Circles

2.The Bermuda Triangle

3.Mysterious huge rock formations at Stonehenge

4.The Aluminium Wedge of Aiud

 In 1974, this  wedge-shaped object was found 1.2 miles east of Aiud, Romania. It was discovered on the banks of the Mures River.  Since it was found in the same layer as mastodon bones, it would indicate that this wedge was at least 11,000 years old. Many people believe that this wedge is evidence that aliens visited earth, since there is no way that humans created such an alloy so many thousands of years ago.

5.The Green Children

 The Green Children of Woolpit were two children who appeared in the village of Woolpit in Suffolk, UK, in the 12th century. The brother and sister had green colored skin, even though they appeared normal in all other ways. They spoke an unrecognized language and refused to eat anything other than pitch from bean pods. Eventually, their skin lost its green color. After they learned English, they explained that they were from the "Land of St Martin," which was a dark place because the sun never rose far above the horizon. They claimed that they were tending their father's herd and followed a river of light when they heard the sounds of bells. Then they arrived in Woolpit. Some of the more unusual theories proposed for the origin of the children are that they were Hollow Earth children, children from the parallel dimension, or Extraterrestrial children.

Conclusion

 The above instances are just a reflection of my opinions and perception.There are many more occurrences all over the world, in fact there are thousands of UFO sightings all over the world each year.
We may be unaware about our future, but we must be aware of the presence of these transcendental beings around us. They may be sitting near us at a coffee shop, they may be anywhere camouflaged and hiding in plain sight to avoid any type of suspicions. We might never know the true nature of these aliens and unearthly species.
"But we should be optimistic, if Goodness prevails in humanity then why not in alien life, we are also alien to those guys."
 So theorizing without any concrete knowledge can cause a lot of inconvenience, it is possible that we may be coexisting on this earth with the alien life beside us after an unknown number of years. So keep your fingers crossed and increase your curiosity.

Please enable JavaScript to view the comments powered by Disqus.
   <![endif]-->

Copyright © Daily Dose 2015


text:
require "i18n"

# Add gem translations to load path
I18n.load_path += Dir[File.expand_path("../locales/*.yml",__FILE__)]

module Ventana
  SCOPE = :ventana
end


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Cognitive biases | Don't worry - be safe!</title>
    <link>/tag/cognitive-biases/</link>
      <atom:link href="/tag/cognitive-biases/index.xml" rel="self" type="application/rss+xml" />
    <description>Cognitive biases</description>
    <generator>Source Themes Academic (https://sourcethemes.com/academic/)</generator><language>en-us</language><lastBuildDate>Wed, 27 Apr 2016 00:00:00 +0000</lastBuildDate>
    <image>
      <url>/images/icon_hu0b7a4cb9992c9ac0e91bd28ffd38dd00_9727_512x512_fill_lanczos_center_2.png</url>
      <title>Cognitive biases</title>
      <link>/tag/cognitive-biases/</link>
    </image>

    <item>
      <title>Individual differences in STWM biases.</title>
      <link>/project/depression-stwm-project/</link>
      <pubDate>Wed, 27 Apr 2016 00:00:00 +0000</pubDate>
      <guid>/project/depression-stwm-project/</guid>
      <description>
The cognitive model of depression hypothesize that depressed and cognitive vulnerable individuals are prone to emotional biases in attention, interpretation, and memory  which could exacerbate distress. In one project, we studied the effects of negative cognitive style, sad mood, and facial affect on the short-term memory for the self-face and for other faces.
Following a sad mood induction, we examined the effect on working memory of an incidental association between facial affect, facial identity, and head-pose orientation. We found that participants high in negative cognitive style who experienced higher levels of sadness displayed a stronger self-face advantage (SFA) for sad expressions than happy expressions. The remaining participants displayed an opposite bias (a stronger SFA for happy expressions than sad expressions), or no bias. These findings highlight the importance of trait-vulnerability status in the working memory biases related to emotional facial expressions.

Caudek, C., &amp; Monni, A. (2013). Do you remember your sad face? The roles of negative cognitive style and sad mood. Memory, 21(8), 891-903.

</description>
    </item>

  </channel>
</rss>


text:
"""
Given two binary trees s and t, check if t is a subtree of s.
A subtree of a tree t is a tree consisting of a node in t and
all of its descendants in t.

Example 1:

Given s:

     3
    / \
   4   5
  / \
 1   2

Given t:

   4
  / \
 1   2
Return true, because t is a subtree of s.

Example 2:

Given s:

     3
    / \
   4   5
  / \
 1   2
    /
   0

Given t:

     3
    /
   4
  / \
 1   2
Return false, because even though t is part of s,
it does not contain all descendants of t.

Follow up:
What if one tree is significantly lager than the other?
"""
import collections

def is_subtree(big, small):
    flag = False
    queue = collections.deque()
    queue.append(big)
    while queue:
        node = queue.popleft()
        if node.val == small.val:
            flag = comp(node, small)
            break
        else:
            queue.append(node.left)
            queue.append(node.right)
    return flag

def comp(p, q):
    if not p and not q:
        return True
    if p and q:
        return p.val == q.val and comp(p.left,q.left) and comp(p.right, q.right)
    return False


text:
/*!
 * \file custom.cc
 * \brief
 * \author Junyuan Xie
*/
#include "./custom-inl.h"
#include <mxnet/base.h>
#include <mxnet/ndarray.h>
#include <mxnet/imperative.h>

#include "../elemwise_op_common.h"

namespace mxnet {
namespace op {
namespace custom {

Registry* Registry::Get() {
  static Registry inst;
  return &inst;
}

struct CustomParam {
  std::string op_type;
  size_t num_args, num_outs, num_auxs;
  std::vector<int> bwd_idx;
  std::shared_ptr<MXCallbackList> info;
};

template<CustomOpPropCallbacks Type>
std::vector<std::string> List(const NodeAttrs& attrs) {
  const CustomParam& params = nnvm::get<CustomParam>(attrs.parsed);
  char ** args = NULL;
  CHECK(reinterpret_cast<CustomOpListFunc>(
    params.info->callbacks[Type])(
      &args, params.info->contexts[Type]));
  std::vector<std::string> ret;
  for (int i = 0; args[i] != NULL; ++i) {
    ret.push_back(args[i]);
  }
  return ret;
}

void AttrParser(NodeAttrs* attrs) {
  attrs->parsed = CustomParam();
  CustomParam& params = nnvm::get<CustomParam>(attrs->parsed);

  std::vector<const char*> keys, vals;
  for (auto &p : attrs->dict) {
    if (p.first == "op_type") {
      params.op_type = p.second;
    } else {
      keys.push_back(p.first.c_str());
      vals.push_back(p.second.c_str());
    }
  }
  CHECK(!params.op_type.empty()) << "Required argument `op_type` is missing.";
  CustomOpPropCreator creator = Registry::Get()->Find(params.op_type);
  CHECK(Registry::Get()->Find(params.op_type) != nullptr)
      << "Cannot find custom operator " << params.op_type;
  params.info.reset(new MXCallbackList, [](MXCallbackList* ptr){
      reinterpret_cast<CustomOpDelFunc>(ptr->callbacks[kCustomOpPropDelete])(
        ptr->contexts[kCustomOpPropDelete]);
      delete ptr;
    });
  CHECK(creator(params.op_type.c_str(), keys.size(), keys.data(),
                vals.data(), params.info.get()));

  params.num_args = List<kCustomOpPropListArguments>(*attrs).size();
  params.num_outs = List<kCustomOpPropListOutputs>(*attrs).size();
  params.num_auxs = List<kCustomOpPropListAuxiliaryStates>(*attrs).size();

  int num_dep, *rdeps, counter = 0;
  std::vector<int> out_grad, in_data, out_data;
  for (size_t i = 0; i < params.num_outs; ++i) out_grad.push_back(counter++);
  for (size_t i = 0; i < params.num_args; ++i) in_data.push_back(counter++);
  for (size_t i = 0; i < params.num_outs; ++i) out_data.push_back(counter++);
  CHECK(reinterpret_cast<CustomOpBwdDepFunc>(
    params.info->callbacks[kCustomOpPropDeclareBackwardDependency])(
      out_grad.data(), in_data.data(), out_data.data(), &num_dep,
      &rdeps, params.info->contexts[kCustomOpPropDeclareBackwardDependency]));
  params.bwd_idx.insert(params.bwd_idx.end(), rdeps, rdeps+num_dep);
}

bool InferShape(const NodeAttrs& attrs,
                std::vector<TShape> *in_shape,
                std::vector<TShape> *out_shape) {
  const CustomParam& params = nnvm::get<CustomParam>(attrs.parsed);

  size_t total = params.num_args + params.num_outs + params.num_auxs;
  std::vector<uint32_t*> shapes(total);
  std::vector<int> ndims(total);
  size_t buff_size = 0;
  for (const auto& i : *in_shape) buff_size += i.ndim();
  std::vector<uint32_t> buff(buff_size);
  uint32_t *ptr = buff.data();
  for (size_t i = 0; i < in_shape->size(); ++i) {
    shapes[i] = ptr;
    ndims[i] = (*in_shape)[i].ndim();
    for (size_t j = 0; j < (*in_shape)[i].ndim(); ++j, ++ptr) {
      *ptr = static_cast<uint32_t>((*in_shape)[i][j]);
    }
  }

  CHECK(reinterpret_cast<CustomOpInferShapeFunc>(
      params.info->callbacks[kCustomOpPropInferShape])(
          shapes.size(), ndims.data(), shapes.data(),
          params.info->contexts[kCustomOpPropInferShape]));

  for (size_t i = 0; i < params.num_args; ++i) {
    SHAPE_ASSIGN_CHECK(*in_shape, i, TShape(shapes[i], shapes[i]+ndims[i]));
  }

  size_t base = params.num_args;
  for (size_t i = 0; i < params.num_outs; ++i) {
    SHAPE_ASSIGN_CHECK(*out_shape, i,
        TShape(shapes[base+i], shapes[base+i]+ndims[base+i]));
  }

  base = params.num_args + params.num_outs;
  for (size_t i = 0; i < params.num_auxs; ++i) {
    SHAPE_ASSIGN_CHECK(*in_shape, params.num_args+i,
        TShape(shapes[base+i], shapes[base+i]+ndims[base+i]));
  }
  return true;
}

bool InferType(const NodeAttrs& attrs,
               std::vector<int> *in_type,
               std::vector<int> *out_type) {
  const CustomParam& params = nnvm::get<CustomParam>(attrs.parsed);

  if (params.info->num_callbacks <= kCustomOpPropInferType) {
    return ElemwiseAttr<int, type_is_none, type_assign, true, type_string>(
        attrs, in_type, out_type, -1);
  }

  std::vector<int> types;
  types.reserve(params.num_args + params.num_outs + params.num_auxs);
  for (size_t i = 0; i < params.num_args; ++i) {
    types.push_back((*in_type)[i]);
  }
  for (const auto &i : *out_type) {
    types.push_back(i);
  }
  for (size_t i = 0; i < params.num_auxs; ++i) {
    types.push_back((*in_type)[params.num_args+i]);
  }

  CHECK(reinterpret_cast<CustomOpInferTypeFunc>(
      params.info->callbacks[kCustomOpPropInferType])(
          types.size(), types.data(), params.info->contexts[kCustomOpPropInferType]));

  for (size_t i = 0; i < params.num_args; ++i) {
    TYPE_ASSIGN_CHECK(*in_type, i, types[i]);
  }
  for (size_t i = 0; i < params.num_outs; ++i) {
    TYPE_ASSIGN_CHECK(*out_type, i, types[params.num_args+i]);
  }
  for (size_t i = 0; i < params.num_auxs; ++i) {
    TYPE_ASSIGN_CHECK(*in_type, params.num_args+i,
                      types[params.num_args+params.num_outs+i]);
  }
  return true;
}

std::vector<nnvm::NodeEntry> Gradient(
    const nnvm::NodePtr& n,
    const std::vector<nnvm::NodeEntry>& out_grads) {
  const CustomParam& params = nnvm::get<CustomParam>(n->attrs.parsed);

  nnvm::NodePtr g = nnvm::Node::Create();
  g->attrs.op = nnvm::Op::Get("_backward_Custom");
  g->attrs.name = n->attrs.name;
  g->attrs.parsed = params;
  g->control_deps.emplace_back(n);

  g->inputs.reserve(params.bwd_idx.size());
  for (const int& t : params.bwd_idx) {
    size_t i = static_cast<size_t>(t);
    if (i >= params.num_outs + params.num_args) {
      uint32_t idx = static_cast<uint32_t>(i-params.num_outs-params.num_args);
      g->inputs.push_back(nnvm::NodeEntry{n, idx, 0});
    } else if (i >= params.num_outs) {
      g->inputs.push_back(n->inputs[i-params.num_outs]);
    } else {
      g->inputs.push_back(out_grads[i]);
    }
  }

  for (size_t i = 0; i < params.num_auxs; ++i) {
    g->inputs.push_back(n->inputs[i+params.num_args]);
  }

  std::vector<nnvm::NodeEntry> ret;
  for (index_t i = 0; i < g->num_outputs(); ++i) {
    ret.emplace_back(nnvm::NodeEntry{g, i, 0});
  }

  return ret;
}

OpStatePtr CreateState(const NodeAttrs& attrs, Context ctx,
                       const std::vector<TShape>& in_shape,
                       const std::vector<int>& in_type) {
  const CustomParam& params = nnvm::get<CustomParam>(attrs.parsed);

  std::vector<uint32_t*> shapes(params.num_args);
  std::vector<int> ndims(params.num_args);
  size_t buff_size = 0;
  for (const auto& i : in_shape) buff_size += i.ndim();
  std::vector<uint32_t> buff(buff_size);
  uint32_t *ptr = buff.data();
  for (size_t i = 0; i < in_shape.size(); ++i) {
    shapes[i] = ptr;
    ndims[i] = in_shape[i].ndim();
    for (size_t j = 0; j < in_shape[i].ndim(); ++j, ++ptr) {
      *ptr = static_cast<uint32_t>(in_shape[i][j]);
    }
  }

  std::ostringstream os;
  os << ctx;

  MXCallbackList *op_info = new MXCallbackList;
  CHECK(reinterpret_cast<CustomOpCreateFunc>(
      params.info->callbacks[kCustomOpPropCreateOperator])(
          os.str().c_str(), params.num_args, shapes.data(), ndims.data(), in_type.data(),
          op_info, params.info->contexts[kCustomOpPropCreateOperator]));

  CustomParam state = params;
  state.info.reset(op_info, [](MXCallbackList *ptr){
    reinterpret_cast<CustomOpDelFunc>(ptr->callbacks[kCustomOpDelete])(
      ptr->contexts[kCustomOpDelete]);
    delete ptr;
  });

  return OpStatePtr::Create<CustomParam>(state);
}

void Forward(const OpStatePtr& state,
             const OpContext& ctx,
             const std::vector<NDArray>& inputs,
             const std::vector<OpReqType>& req,
             const std::vector<NDArray>& outputs) {
  const CustomParam& params = state.get_state<CustomParam>();
  std::vector<void*> ptrs;
  std::vector<int> tags;

  for (size_t i = 0; i < params.num_args; ++i) {
    NDArray *nd = new NDArray(inputs[i].Detach());
    ptrs.push_back(reinterpret_cast<void*>(nd));
    tags.push_back(0);
  }

  for (size_t i = 0; i < params.num_outs; ++i) {
    NDArray *nd = new NDArray(outputs[i].Detach());
    ptrs.push_back(reinterpret_cast<void*>(nd));
    tags.push_back(1);
  }

  for (size_t i = 0; i < params.num_auxs; ++i) {
    NDArray *nd = new NDArray(inputs[i+params.num_args].Detach());
    ptrs.push_back(reinterpret_cast<void*>(nd));
    tags.push_back(4);
  }

  bool prev_recording = Imperative::Get()->set_is_recording(false);
  bool prev_training = Imperative::Get()->set_is_training(ctx.is_train);

  CHECK(reinterpret_cast<CustomOpFBFunc>(params.info->callbacks[kCustomOpForward])(
    ptrs.size(), ptrs.data(), tags.data(), reinterpret_cast<const int*>(req.data()),
    static_cast<int>(ctx.is_train), params.info->contexts[kCustomOpForward]));

  Imperative::Get()->set_is_training(prev_training);
  Imperative::Get()->set_is_recording(prev_recording);
}

void Backward(const OpStatePtr& state,
              const OpContext& ctx,
              const std::vector<NDArray>& inputs,
              const std::vector<OpReqType>& req,
              const std::vector<NDArray>& outputs) {
  const CustomParam& params = state.get_state<CustomParam>();

  size_t total = 2*params.num_args + 2*params.num_outs + params.num_auxs;
  std::vector<void*> ptrs(params.num_args + 2*params.num_outs, nullptr);
  std::vector<int> tags;
  ptrs.reserve(total);
  tags.reserve(total);
  for (size_t i = 0; i < params.num_outs; ++i) tags.push_back(3);
  for (size_t i = 0; i < params.num_args; ++i) tags.push_back(0);
  for (size_t i = 0; i < params.num_outs; ++i) tags.push_back(1);

  for (size_t i = 0; i < params.bwd_idx.size(); ++i) {
    NDArray *nd = new NDArray(inputs[i].Detach());
    ptrs[params.bwd_idx[i]] = reinterpret_cast<void*>(nd);
  }
  for (size_t i = 0; i < ptrs.size(); ++i) {
    if (ptrs[i] == nullptr) ptrs[i] = reinterpret_cast<void*>(new NDArray());
  }
  for (const auto& i : outputs) {
    NDArray* nd = new NDArray(i.Detach());
    ptrs.push_back(reinterpret_cast<void*>(nd));
    tags.push_back(2);
  }
  for (size_t i = 0; i < params.num_auxs; ++i) {
    NDArray* nd = new NDArray(inputs[inputs.size()-params.num_auxs+i].Detach());
    ptrs.push_back(reinterpret_cast<void*>(nd));
    tags.push_back(4);
  }

  bool prev_recording = Imperative::Get()->set_is_recording(false);
  bool prev_training = Imperative::Get()->set_is_training(ctx.is_train);

  CHECK(reinterpret_cast<CustomOpFBFunc>(params.info->callbacks[kCustomOpBackward])(
    ptrs.size(), ptrs.data(), tags.data(), reinterpret_cast<const int*>(req.data()),
    static_cast<int>(ctx.is_train), params.info->contexts[kCustomOpBackward]));

  Imperative::Get()->set_is_training(prev_training);
  Imperative::Get()->set_is_recording(prev_recording);
}

NNVM_REGISTER_OP(Custom)
.describe(R"code(Apply a custom operator implemented in a frontend language (like Python).

Custom operators should override required methods like `forward` and `backward`.
The custom operator must be registered before it can be used.
Please check the tutorial here: http://mxnet.io/how_to/new_op.html.

)code" ADD_FILELINE)
.set_num_inputs([](const NodeAttrs& attrs){
    const CustomParam& params = nnvm::get<CustomParam>(attrs.parsed);
    return params.num_args + params.num_auxs;
  })
.set_num_outputs([](const NodeAttrs& attrs){
    const CustomParam& params = nnvm::get<CustomParam>(attrs.parsed);
    return params.num_outs;
  })
.set_attr_parser(AttrParser)
.set_attr<nnvm::FInferShape>("FInferShape", InferShape)
.set_attr<nnvm::FInferType>("FInferType", InferType)
.set_attr<nnvm::FListInputNames>("FListInputNames", [](const NodeAttrs& attrs) {
    std::vector<std::string> args = List<kCustomOpPropListArguments>(attrs);
    std::vector<std::string> auxs = List<kCustomOpPropListAuxiliaryStates>(attrs);
    args.insert(args.end(), auxs.begin(), auxs.end());
    return args;
  })
.set_attr<nnvm::FListOutputNames>("FListOutputNames", List<kCustomOpPropListOutputs>)
.set_attr<nnvm::FMutateInputs>("FMutateInputs", [](const NodeAttrs& attrs) {
    const CustomParam& params = nnvm::get<CustomParam>(attrs.parsed);
    std::vector<uint32_t> ret;
    for (size_t i = 0; i < params.num_auxs; ++i) ret.push_back(i+params.num_args);
    return ret;
  })
.set_attr<FExecType>("FExecType", [](const NodeAttrs& attrs) {
    return ExecType::kLocal;
  })
.set_attr<nnvm::FGradient>("FGradient", Gradient)
.set_attr<FCreateOpState>("FCreateOpState", CreateState)
.set_attr<FStatefulComputeEx>("FStatefulComputeEx<cpu>", Forward)
.set_attr<FStatefulComputeEx>("FStatefulComputeEx<gpu>", Forward)
.add_argument("data", "NDArray-or-Symbol[]", "Input data for the custom operator.")
.add_argument("op_type", "string", "Name of the custom operator. "
              "This is the name that is passed to `mx.operator.register` "
              "to register the operator.");

NNVM_REGISTER_OP(_backward_Custom)
.set_num_inputs([](const NodeAttrs& attrs){
    const CustomParam& params = nnvm::get<CustomParam>(attrs.parsed);
    return params.bwd_idx.size();
  })
.set_num_outputs([](const NodeAttrs& attrs){
    const CustomParam& params = nnvm::get<CustomParam>(attrs.parsed);
    return params.num_args;
  })
.set_attr<bool>("TIsLayerOpBackward", true)
.set_attr<bool>("TIsBackward", true)
.set_attr<FExecType>("FExecType", [](const NodeAttrs& attrs) {
    return ExecType::kLocal;
  })
.set_attr<FStatefulComputeEx>("FStatefulComputeEx<cpu>", Backward)
.set_attr<FStatefulComputeEx>("FStatefulComputeEx<gpu>", Backward);

}  // namespace custom
}  // namespace op
}  // namespace mxnet


text:
var util = require('util');
var BaseType = require('./base');

/**********************************************************
 Boolean
 ***********************************************************/

function BooleanType() {
  BaseType.apply(this, arguments);
}
util.inherits(BooleanType, BaseType);

BooleanType.prototype._checkType = function _checkType(value) {
  return BooleanType.super_.prototype._checkType(value) &&
    (value === true || value === false);
};

module.exports = BooleanType;