text:
def evt01_handler():
	"""
	Threaded handler.
	Called when the transport's loaded and users initialized
	But before the modules are being loaded
	"""
	print "WOW! That's my awesome plugin event!"

registerHandler("evt01", evt01_handler)

def evt02_handler():
	"""
	Linear handler.
	Called when transport's shutting down
	"""
	print "NOOOOOOOOO! Transport is so awesome, why are you stopping it?"

registerHandler("evt02", evt02_handler)

def evt03_handler(user):
	"""
	Linear handler.
	Called when user has removed his registration ("unsubscribe" presence or "delete" in disco)
	Parameters:
		user: User class object
	Look at the User class for advanced information
	"""
	print "Print user %s is going to remove us" % (user.source)

registerHandler("evt03", evt03_handler)

def evt04_handler(vk):
	"""
	Linear handler.
	Called when user received a captcha
	Parameters:
		vk: VK class object
	"""
	print "Look at this man, he've got a captcha: %s. This image: %s is not for robots" % (vk.source, vk.engine.captcha["img"])

registerHandler("evt04", evt04_handler)

def evt05_handler(user):
	"""
	Threaded handler.
	Called when user became online (our xmpp user, so we received available/probe presence)
	Exactly at end of the user.initialize() function
	Parameters:
		user: User class object
	"""
	print "Hey, look who come to see us: %s" % user.source

registerHandler("evt05", evt05_handler)

def evt06_handler(vk):
	"""
	Threaded handler.
	Called when user is disconnected (vk)
	Exactly when user.vk.disconnect() is called
	Parameters:
		vk: VK class object
	"""
	print "We've lost this guy: %s" % vk.source ## yes VK class object too have source attribute

registerHandler("evt06", evt06_handler)

def evt08_handler(source):
	"""
	Linear handler
	Called when a new user registered
	"""

registerHandler("evt08", watch_registered)

def evt09_handler(source):
	"""
	Linear handler
	Called when a user has unregistered
	"""

registerHandler("evt09", watch_unregistered)

def evt07_handler(user):
	"""
	Linear handler
	Called when user is connecting (if authenticated)
	Parameters:
		user: User class object
	"""
	print "User", user.source, "is authenticated!"

def msg01_handler(user, message):
	"""
	Linear handler.
	Called for each message has been received from VK
	Parameters:
		user: User class object
		message: single message json object
	Return values:
		None: the function itself should send a message
		str type: transport's core will add returned string to existing body
	"""
	return "\nmsg01_handler is awesome"

registerHandler("msg01", msg01_handler)

def msg02_handler(msg):
	"""
	Linear handler.
	Called for each message has been received from xmpp
	Parameters:
		msg: xmpp.Message object
	"""
	print "Look who's trying to send us a message: %s" % msg.getFrom().getStripped()

registerHandler("msg02", msg02_handler)

def msg03_handler(msg, destination, source):
	"""
	Linear handler.
	Called when transport sending a message to XMPP
	Could be used for modifying message before it being sent
	Parameters:
		msg: xmpp.Message object
		destination: message destination
		source: message source
	Look at sendMessage() in transport's core for advanced information
	"""
	msg.setTag("awesome", namespace="urn:xmpp:awesome")

registerHandler("msg03", msg03_handler)

def prs01_handler(source, prs):
	"""
	Trheaded handler. I have no idea why.
	Called when presence received (no matter which one, when user in Transport)
	Also called when user is just initialized (only after "probe" presence)
	Parameters:
		source: presence source
		prs: xmpp.Presence object
	"""
	print "Hey, user %s is became %s in xmpp!" % (source, prs.getType())

registerHandler("prs01", prs01_handler)

def prs02_handler(prs, destination, source):
	"""
	Linear handler.
	Same as msg02_handler, but this one is for presence
	Parameters:
		prs: xmpp.Presence object
		destination: message destination
		source: message source
	Look at sendPresence() in transport's core for advanced information
	"""
	prs.setTag("c", {"node": "http://psi-dev.googlecode.com/caps", "ver": "0.16"}, xmpp.NS_CAPS)

registerHandler("prs02", prs02_handler)

## AdHoc. To add adhoc option (now only for user settings and only boolean values supported)
## You need to add form field to GLOBAL_USER_SETTINGS
## Example: GLOBAL_USER_SETTINGS["setting_name"] = {"label": "field label", "value": "default-value", "type": "field-type"}
## For field types look http://xmpp.org/extensions/xep-0004.html section 3.3 "Field Types"
## Ok now, look here.
GLOBAL_USER_SETTINGS["awesome_setting"] = {"label": "My new setting", "value": 0} ## If not type added, then boolean will be used
## Settings are being automatically saved as soon as they changed.
## To check if the value is equal to something, do:
## print user.settings.awesome_setting == 0
## where "user" is the User class object


text:
package com.paulhammant.ngwebdriver;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.support.AbstractFindByBuilder;
import org.openqa.selenium.support.PageFactoryFinder;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;

import static com.paulhammant.ngwebdriver.NgWebDriver.DEFAULT_ROOT_SELECTOR;

public class ByAngularExactBinding extends ByAngular.BaseBy {

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.FIELD, ElementType.TYPE})
    @PageFactoryFinder(NgFindByBuilder.class)
    public @interface FindBy {
        String rootSelector() default DEFAULT_ROOT_SELECTOR;
        String exactBinding();
    }

    public static class NgFindByBuilder extends AbstractFindByBuilder {
        @Override
        public By buildIt(final Object annotation, Field field) {
            final FindBy findBy = (FindBy) annotation;
            return new ByAngularExactBinding(findBy.rootSelector(), findBy.exactBinding());
        }
    }

    public ByAngularExactBinding(String rootSelector, String exactBinding) {
        super(rootSelector);
        this.binding = exactBinding;
    }

    private String binding;

    protected Object getObject(SearchContext context, JavascriptExecutor javascriptExecutor) {
        return javascriptExecutor.executeScript(
                "var using = arguments[0] || document;\n" +
                        "var rootSelector = '" + rootSelector + "';\n" +
                        "var exactMatch = true;\n" +
                        "var binding = '" + binding + "';\n" +
                        "\n" +
                        ByAngular.functions.get("findBindings")
                , context);
    }

    @Override
    public String toString() {
        return "exactBinding(" + binding + ')';
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<module rename-to='example'>
  <inherits name='com.google.gwt.user.User'/>
  <inherits name='com.google.gwt.logging.Logging'/>
  <inherits name='com.google.gwt.precompress.Precompress'/>

  <add-linker name='xsiframe'/>

  <entry-point class='org.realityforge.gwt.cache_filter.example.client.Example'/>

  <source path='client'/>
</module>


text:
package metal
package immutable

trait WrappedSortedSet[K] extends WrappedSet[K] {

  def w: metal.immutable.SortedSet[K]

}

trait SortedSet[K] extends generic.SortedSet[K] with immutable.Set[K] { lhs =>

  type Immutable >: lhs.type <: immutable.SortedSet[K]

}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Test Cropper's options</title>
  <link rel="stylesheet" href="../assets/css/qunit.css">
  <link rel="stylesheet" href="../dist/cropper.css">
  <link rel="stylesheet" href="css/main.css">


text:
public class X {
    public boolean compare2Strings(java.lang.String s1, java.lang.String s2) {
        return (s1.equals(s2));
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <name>Application_Date__c</name>
    <help>La fecha y la hora cuando se envió la solicitud.</help>
    <label>Fecha de solicitud</label>
</CustomFieldTranslation>


text:
require 'httpclient'
require 'multi_json'

module YSpell
  class SpellError
    class UnknownWord < SpellError
      COLOR = :red
    end
    class RepeatedWord < SpellError
      COLOR = :yellow
    end
    class Capitalization < SpellError
      COLOR = :yellow
    end
    class TooManyErrors < SpellError
      COLOR = :red
    end

    #COLOR = :red

    attr_reader :code, :position, :row, :column, :length, :word, :suggestions

    CODE_TO_ERROR = [UnknownWord, RepeatedWord, Capitalization, TooManyErrors]

    def self.from_result(result)
      class_by_code(result['code']).new(result)
    end

    def self.class_by_code(code)
      key = code - 1

      raise(UnknownCodeError, "Code #{code} is unknown") if CODE_TO_ERROR[key].nil?
      CODE_TO_ERROR[key]
    end

    def initialize(result)
      @position = result['pos']
      @row = result['row']
      @column = result['col']
      @length = result['len']
      @word = result['word']
      @suggestions = result['s']
      @code = result['code']
    end

    def colored_word
      word.color(self.class::COLOR)
    end
  end
end


text:
/* @internal */
namespace ts.formatting {
    const standardScanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ false, LanguageVariant.Standard);
    const jsxScanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ false, LanguageVariant.JSX);

    export interface FormattingScanner {
        advance(): void;
        getStartPos(): number;
        isOnToken(): boolean;
        isOnEOF(): boolean;
        readTokenInfo(n: Node): TokenInfo;
        readEOFTokenRange(): TextRangeWithKind;
        getCurrentLeadingTrivia(): TextRangeWithKind[] | undefined;
        lastTrailingTriviaWasNewLine(): boolean;
        skipToEndOf(node: Node): void;
        skipToStartOf(node: Node): void;
    }

    const enum ScanAction {
        Scan,
        RescanGreaterThanToken,
        RescanSlashToken,
        RescanTemplateToken,
        RescanJsxIdentifier,
        RescanJsxText,
        RescanJsxAttributeValue,
    }

    export function getFormattingScanner<T>(text: string, languageVariant: LanguageVariant, startPos: number, endPos: number, cb: (scanner: FormattingScanner) => T): T {
        const scanner = languageVariant === LanguageVariant.JSX ? jsxScanner : standardScanner;

        scanner.setText(text);
        scanner.setTextPos(startPos);

        let wasNewLine = true;
        let leadingTrivia: TextRangeWithTriviaKind[] | undefined;
        let trailingTrivia: TextRangeWithTriviaKind[] | undefined;

        let savedPos: number;
        let lastScanAction: ScanAction | undefined;
        let lastTokenInfo: TokenInfo | undefined;

        const res = cb({
            advance,
            readTokenInfo,
            readEOFTokenRange,
            isOnToken,
            isOnEOF,
            getCurrentLeadingTrivia: () => leadingTrivia,
            lastTrailingTriviaWasNewLine: () => wasNewLine,
            skipToEndOf,
            skipToStartOf,
            getStartPos: () => lastTokenInfo?.token.pos ?? scanner.getTokenPos(),
        });

        lastTokenInfo = undefined;
        scanner.setText(undefined);

        return res;

        function advance(): void {
            lastTokenInfo = undefined;
            const isStarted = scanner.getStartPos() !== startPos;

            if (isStarted) {
                wasNewLine = !!trailingTrivia && last(trailingTrivia).kind === SyntaxKind.NewLineTrivia;
            }
            else {
                scanner.scan();
            }

            leadingTrivia = undefined;
            trailingTrivia = undefined;

            let pos = scanner.getStartPos();

            // Read leading trivia and token
            while (pos < endPos) {
                const t = scanner.getToken();
                if (!isTrivia(t)) {
                    break;
                }

                // consume leading trivia
                scanner.scan();
                const item: TextRangeWithTriviaKind = {
                    pos,
                    end: scanner.getStartPos(),
                    kind: t
                };

                pos = scanner.getStartPos();

                leadingTrivia = append(leadingTrivia, item);
            }

            savedPos = scanner.getStartPos();
        }

        function shouldRescanGreaterThanToken(node: Node): boolean {
            switch (node.kind) {
                case SyntaxKind.GreaterThanEqualsToken:
                case SyntaxKind.GreaterThanGreaterThanEqualsToken:
                case SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken:
                case SyntaxKind.GreaterThanGreaterThanGreaterThanToken:
                case SyntaxKind.GreaterThanGreaterThanToken:
                    return true;
            }

            return false;
        }

        function shouldRescanJsxIdentifier(node: Node): boolean {
            if (node.parent) {
                switch (node.parent.kind) {
                    case SyntaxKind.JsxAttribute:
                    case SyntaxKind.JsxOpeningElement:
                    case SyntaxKind.JsxClosingElement:
                    case SyntaxKind.JsxSelfClosingElement:
                        // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier.
                        return isKeyword(node.kind) || node.kind === SyntaxKind.Identifier;
                }
            }

            return false;
        }

        function shouldRescanJsxText(node: Node): boolean {
            return isJsxText(node);
        }

        function shouldRescanSlashToken(container: Node): boolean {
            return container.kind === SyntaxKind.RegularExpressionLiteral;
        }

        function shouldRescanTemplateToken(container: Node): boolean {
            return container.kind === SyntaxKind.TemplateMiddle ||
                container.kind === SyntaxKind.TemplateTail;
        }

        function shouldRescanJsxAttributeValue(node: Node): boolean {
            return node.parent && isJsxAttribute(node.parent) && node.parent.initializer === node;
        }

        function startsWithSlashToken(t: SyntaxKind): boolean {
            return t === SyntaxKind.SlashToken || t === SyntaxKind.SlashEqualsToken;
        }

        function readTokenInfo(n: Node): TokenInfo {
            Debug.assert(isOnToken());

            // normally scanner returns the smallest available token
            // check the kind of context node to determine if scanner should have more greedy behavior and consume more text.
            const expectedScanAction = shouldRescanGreaterThanToken(n) ? ScanAction.RescanGreaterThanToken :
                shouldRescanSlashToken(n) ? ScanAction.RescanSlashToken :
                shouldRescanTemplateToken(n) ? ScanAction.RescanTemplateToken :
                shouldRescanJsxIdentifier(n) ? ScanAction.RescanJsxIdentifier :
                shouldRescanJsxText(n) ? ScanAction.RescanJsxText :
                shouldRescanJsxAttributeValue(n) ? ScanAction.RescanJsxAttributeValue :
                ScanAction.Scan;

            if (lastTokenInfo && expectedScanAction === lastScanAction) {
                // readTokenInfo was called before with the same expected scan action.
                // No need to re-scan text, return existing 'lastTokenInfo'
                // it is ok to call fixTokenKind here since it does not affect
                // what portion of text is consumed. In contrast rescanning can change it,
                // i.e. for '>=' when originally scanner eats just one character
                // and rescanning forces it to consume more.
                return fixTokenKind(lastTokenInfo, n);
            }

            if (scanner.getStartPos() !== savedPos) {
                Debug.assert(lastTokenInfo !== undefined);
                // readTokenInfo was called before but scan action differs - rescan text
                scanner.setTextPos(savedPos);
                scanner.scan();
            }

            let currentToken = getNextToken(n, expectedScanAction);

            const token = createTextRangeWithKind(
                scanner.getStartPos(),
                scanner.getTextPos(),
                currentToken,
            );

            // consume trailing trivia
            if (trailingTrivia) {
                trailingTrivia = undefined;
            }
            while (scanner.getStartPos() < endPos) {
                currentToken = scanner.scan();
                if (!isTrivia(currentToken)) {
                    break;
                }
                const trivia = createTextRangeWithKind(
                    scanner.getStartPos(),
                    scanner.getTextPos(),
                    currentToken,
                );

                if (!trailingTrivia) {
                    trailingTrivia = [];
                }

                trailingTrivia.push(trivia);

                if (currentToken === SyntaxKind.NewLineTrivia) {
                    // move past new line
                    scanner.scan();
                    break;
                }
            }

            lastTokenInfo = { leadingTrivia, trailingTrivia, token };

            return fixTokenKind(lastTokenInfo, n);
        }

        function getNextToken(n: Node, expectedScanAction: ScanAction): SyntaxKind {
            const token = scanner.getToken();
            lastScanAction = ScanAction.Scan;
            switch (expectedScanAction) {
                case ScanAction.RescanGreaterThanToken:
                    if (token === SyntaxKind.GreaterThanToken) {
                        lastScanAction = ScanAction.RescanGreaterThanToken;
                        const newToken = scanner.reScanGreaterToken();
                        Debug.assert(n.kind === newToken);
                        return newToken;
                    }
                    break;
                case ScanAction.RescanSlashToken:
                    if (startsWithSlashToken(token)) {
                        lastScanAction = ScanAction.RescanSlashToken;
                        const newToken = scanner.reScanSlashToken();
                        Debug.assert(n.kind === newToken);
                        return newToken;
                    }
                    break;
                case ScanAction.RescanTemplateToken:
                    if (token === SyntaxKind.CloseBraceToken) {
                        lastScanAction = ScanAction.RescanTemplateToken;
                        return scanner.reScanTemplateToken(/* isTaggedTemplate */ false);
                    }
                    break;
                case ScanAction.RescanJsxIdentifier:
                    lastScanAction = ScanAction.RescanJsxIdentifier;
                    return scanner.scanJsxIdentifier();
                case ScanAction.RescanJsxText:
                    lastScanAction = ScanAction.RescanJsxText;
                    return scanner.reScanJsxToken(/* allowMultilineJsxText */ false);
                case ScanAction.RescanJsxAttributeValue:
                    lastScanAction = ScanAction.RescanJsxAttributeValue;
                    return scanner.reScanJsxAttributeValue();
                case ScanAction.Scan:
                    break;
                default:
                    Debug.assertNever(expectedScanAction);
            }
            return token;
        }

        function readEOFTokenRange(): TextRangeWithKind<SyntaxKind.EndOfFileToken> {
            Debug.assert(isOnEOF());
            return createTextRangeWithKind(scanner.getStartPos(), scanner.getTextPos(), SyntaxKind.EndOfFileToken);
        }

        function isOnToken(): boolean {
            const current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken();
            return current !== SyntaxKind.EndOfFileToken && !isTrivia(current);
        }

        function isOnEOF(): boolean {
            const current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken();
            return current === SyntaxKind.EndOfFileToken;
        }

        // when containing node in the tree is token
        // but its kind differs from the kind that was returned by the scanner,
        // then kind needs to be fixed. This might happen in cases
        // when parser interprets token differently, i.e keyword treated as identifier
        function fixTokenKind(tokenInfo: TokenInfo, container: Node): TokenInfo {
            if (isToken(container) && tokenInfo.token.kind !== container.kind) {
                tokenInfo.token.kind = container.kind;
            }
            return tokenInfo;
        }

        function skipToEndOf(node: Node): void {
            scanner.setTextPos(node.end);
            savedPos = scanner.getStartPos();
            lastScanAction = undefined;
            lastTokenInfo = undefined;
            wasNewLine = false;
            leadingTrivia = undefined;
            trailingTrivia = undefined;
        }

        function skipToStartOf(node: Node): void {
            scanner.setTextPos(node.pos);
            savedPos = scanner.getStartPos();
            lastScanAction = undefined;
            lastTokenInfo = undefined;
            wasNewLine = false;
            leadingTrivia = undefined;
            trailingTrivia = undefined;
        }
    }
}


text:
const adapter = require('./adapter');
const mutationAdapter = require('./mutation-adapter');
const xmlEscape = require('../util/xml-escape');
const MonitorRecord = require('./monitor-record');
const Clone = require('../util/clone');
const {Map} = require('immutable');
const BlocksExecuteCache = require('./blocks-execute-cache');
const BlocksRuntimeCache = require('./blocks-runtime-cache');
const log = require('../util/log');
const Variable = require('./variable');
const getMonitorIdForBlockWithArgs = require('../util/get-monitor-id');

/**
 * @fileoverview
 * Store and mutate the VM block representation,
 * and handle updates from Scratch Blocks events.
 */

/**
 * Create a block container.
 * @param {Runtime} runtime The runtime this block container operates within
 * @param {boolean} optNoGlow Optional flag to indicate that blocks in this container
 * should not request glows. This does not affect glows when clicking on a block to execute it.
 */
class Blocks {
    constructor (runtime, optNoGlow) {
        this.runtime = runtime;

        /**
         * All blocks in the workspace.
         * Keys are block IDs, values are metadata about the block.
         * @type {Object.<string, Object>}
         */
        this._blocks = {};

        /**
         * All top-level scripts in the workspace.
         * A list of block IDs that represent scripts (i.e., first block in script).
         * @type {Array.<String>}
         */
        this._scripts = [];

        /**
         * Runtime Cache
         * @type {{inputs: {}, procedureParamNames: {}, procedureDefinitions: {}}}
         * @private
         */
        Object.defineProperty(this, '_cache', {writable: true, enumerable: false});
        this._cache = {
            /**
             * Cache block inputs by block id
             * @type {object.<string, !Array.<object>>}
             */
            inputs: {},
            /**
             * Cache procedure Param Names by block id
             * @type {object.<string, ?Array.<string>>}
             */
            procedureParamNames: {},
            /**
             * Cache procedure definitions by block id
             * @type {object.<string, ?string>}
             */
            procedureDefinitions: {},

            /**
             * A cache for execute to use and store on. Only available to
             * execute.
             * @type {object.<string, object>}
             */
            _executeCached: {},

            /**
             * A cache of block IDs and targets to start threads on as they are
             * actively monitored.
             * @type {Array<{blockId: string, target: Target}>}
             */
            _monitored: null,

            /**
             * A cache of hat opcodes to collection of theads to execute.
             * @type {object.<string, object>}
             */
            scripts: {}
        };

        /**
         * Flag which indicates that blocks in this container should not glow.
         * Blocks will still glow when clicked on, but this flag is used to control
         * whether the blocks in this container can request a glow as part of
         * a running stack. E.g. the flyout block container and the monitor block container
         * should not be able to request a glow, but blocks containers belonging to
         * sprites should.
         * @type {boolean}
         */
        this.forceNoGlow = optNoGlow || false;
    }

    /**
     * Blockly inputs that represent statements/branch.
     * are prefixed with this string.
     * @const{string}
     */
    static get BRANCH_INPUT_PREFIX () {
        return 'SUBSTACK';
    }

    /**
     * Provide an object with metadata for the requested block ID.
     * @param {!string} blockId ID of block we have stored.
     * @return {?object} Metadata about the block, if it exists.
     */
    getBlock (blockId) {
        return this._blocks[blockId];
    }

    /**
     * Get all known top-level blocks that start scripts.
     * @return {Array.<string>} List of block IDs.
     */
    getScripts () {
        return this._scripts;
    }

    /**
      * Get the next block for a particular block
      * @param {?string} id ID of block to get the next block for
      * @return {?string} ID of next block in the sequence
      */
    getNextBlock (id) {
        const block = this._blocks[id];
        return (typeof block === 'undefined') ? null : block.next;
    }

    /**
     * Get the branch for a particular C-shaped block.
     * @param {?string} id ID for block to get the branch for.
     * @param {?number} branchNum Which branch to select (e.g. for if-else).
     * @return {?string} ID of block in the branch.
     */
    getBranch (id, branchNum) {
        const block = this._blocks[id];
        if (typeof block === 'undefined') return null;
        if (!branchNum) branchNum = 1;

        let inputName = Blocks.BRANCH_INPUT_PREFIX;
        if (branchNum > 1) {
            inputName += branchNum;
        }

        // Empty C-block?
        const input = block.inputs[inputName];
        return (typeof input === 'undefined') ? null : input.block;
    }

    /**
     * Get the opcode for a particular block
     * @param {?object} block The block to query
     * @return {?string} the opcode corresponding to that block
     */
    getOpcode (block) {
        return (typeof block === 'undefined') ? null : block.opcode;
    }

    /**
     * Get all fields and their values for a block.
     * @param {?object} block The block to query.
     * @return {?object} All fields and their values.
     */
    getFields (block) {
        return (typeof block === 'undefined') ? null : block.fields;
    }

    /**
     * Get all non-branch inputs for a block.
     * @param {?object} block the block to query.
     * @return {?Array.<object>} All non-branch inputs and their associated blocks.
     */
    getInputs (block) {
        if (typeof block === 'undefined') return null;
        let inputs = this._cache.inputs[block.id];
        if (typeof inputs !== 'undefined') {
            return inputs;
        }

        inputs = {};
        for (const input in block.inputs) {
            // Ignore blocks prefixed with branch prefix.
            if (input.substring(0, Blocks.BRANCH_INPUT_PREFIX.length) !==
                Blocks.BRANCH_INPUT_PREFIX) {
                inputs[input] = block.inputs[input];
            }
        }

        this._cache.inputs[block.id] = inputs;
        return inputs;
    }

    /**
     * Get mutation data for a block.
     * @param {?object} block The block to query.
     * @return {?object} Mutation for the block.
     */
    getMutation (block) {
        return (typeof block === 'undefined') ? null : block.mutation;
    }

    /**
     * Get the top-level script for a given block.
     * @param {?string} id ID of block to query.
     * @return {?string} ID of top-level script block.
     */
    getTopLevelScript (id) {
        let block = this._blocks[id];
        if (typeof block === 'undefined') return null;
        while (block.parent !== null) {
            block = this._blocks[block.parent];
        }
        return block.id;
    }

    /**
     * Get the procedure definition for a given name.
     * @param {?string} name Name of procedure to query.
     * @return {?string} ID of procedure definition.
     */
    getProcedureDefinition (name) {
        const blockID = this._cache.procedureDefinitions[name];
        if (typeof blockID !== 'undefined') {
            return blockID;
        }

        for (const id in this._blocks) {
            if (!this._blocks.hasOwnProperty(id)) continue;
            const block = this._blocks[id];
            if (block.opcode === 'procedures_definition') {
                const internal = this._getCustomBlockInternal(block);
                if (internal && internal.mutation.proccode === name) {
                    this._cache.procedureDefinitions[name] = id; // The outer define block id
                    return id;
                }
            }
        }

        this._cache.procedureDefinitions[name] = null;
        return null;
    }

    /**
     * Get names and ids of parameters for the given procedure.
     * @param {?string} name Name of procedure to query.
     * @return {?Array.<string>} List of param names for a procedure.
     */
    getProcedureParamNamesAndIds (name) {
        return this.getProcedureParamNamesIdsAndDefaults(name).slice(0, 2);
    }

    /**
     * Get names, ids, and defaults of parameters for the given procedure.
     * @param {?string} name Name of procedure to query.
     * @return {?Array.<string>} List of param names for a procedure.
     */
    getProcedureParamNamesIdsAndDefaults (name) {
        const cachedNames = this._cache.procedureParamNames[name];
        if (typeof cachedNames !== 'undefined') {
            return cachedNames;
        }

        for (const id in this._blocks) {
            if (!this._blocks.hasOwnProperty(id)) continue;
            const block = this._blocks[id];
            if (block.opcode === 'procedures_prototype' &&
                block.mutation.proccode === name) {
                const names = JSON.parse(block.mutation.argumentnames);
                const ids = JSON.parse(block.mutation.argumentids);
                const defaults = JSON.parse(block.mutation.argumentdefaults);

                this._cache.procedureParamNames[name] = [names, ids, defaults];
                return this._cache.procedureParamNames[name];
            }
        }

        this._cache.procedureParamNames[name] = null;
        return null;
    }

    duplicate () {
        const newBlocks = new Blocks(this.runtime, this.forceNoGlow);
        newBlocks._blocks = Clone.simple(this._blocks);
        newBlocks._scripts = Clone.simple(this._scripts);
        return newBlocks;
    }
    // ---------------------------------------------------------------------

    /**
     * Create event listener for blocks, variables, and comments. Handles validation and
     * serves as a generic adapter between the blocks, variables, and the
     * runtime interface.
     * @param {object} e Blockly "block" or "variable" event
     */
    blocklyListen (e) {
        // Validate event
        if (typeof e !== 'object') return;
        if (typeof e.blockId !== 'string' && typeof e.varId !== 'string' &&
            typeof e.commentId !== 'string') {
            return;
        }
        const stage = this.runtime.getTargetForStage();
        const editingTarget = this.runtime.getEditingTarget();

        // UI event: clicked scripts toggle in the runtime.
        if (e.element === 'stackclick') {
            this.runtime.toggleScript(e.blockId, {stackClick: true});
            return;
        }

        // Block create/update/destroy
        switch (e.type) {
        case 'create': {
            const newBlocks = adapter(e);
            // A create event can create many blocks. Add them all.
            for (let i = 0; i < newBlocks.length; i++) {
                this.createBlock(newBlocks[i]);
            }
            break;
        }
        case 'change':
            this.changeBlock({
                id: e.blockId,
                element: e.element,
                name: e.name,
                value: e.newValue
            });
            break;
        case 'move':
            this.moveBlock({
                id: e.blockId,
                oldParent: e.oldParentId,
                oldInput: e.oldInputName,
                newParent: e.newParentId,
                newInput: e.newInputName,
                newCoordinate: e.newCoordinate
            });
            break;
        case 'dragOutside':
            this.runtime.emitBlockDragUpdate(e.isOutside);
            break;
        case 'endDrag':
            this.runtime.emitBlockDragUpdate(false /* areBlocksOverGui */);

            // Drag blocks onto another sprite
            if (e.isOutside) {
                const newBlocks = adapter(e);
                this.runtime.emitBlockEndDrag(newBlocks, e.blockId);
            }
            break;
        case 'delete':
            // Don't accept delete events for missing blocks,
            // or shadow blocks being obscured.
            if (!this._blocks.hasOwnProperty(e.blockId) ||
                this._blocks[e.blockId].shadow) {
                return;
            }
            // Inform any runtime to forget about glows on this script.
            if (this._blocks[e.blockId].topLevel) {
                this.runtime.quietGlow(e.blockId);
            }
            this.deleteBlock(e.blockId);
            break;
        case 'var_create':
            // Check if the variable being created is global or local
            // If local, create a local var on the current editing target, as long
            // as there are no conflicts, and the current target is actually a sprite
            // If global or if the editing target is not present or we somehow got
            // into a state where a local var was requested for the stage,
            // create a stage (global) var after checking for name conflicts
            // on all the sprites.
            if (e.isLocal && editingTarget && !editingTarget.isStage && !e.isCloud) {
                if (!editingTarget.lookupVariableById(e.varId)) {
                    editingTarget.createVariable(e.varId, e.varName, e.varType);
                    this.emitProjectChanged();
                }
            } else {
                if (stage.lookupVariableById(e.varId)) {
                    // Do not re-create a variable if it already exists
                    return;
                }
                // Check for name conflicts in all of the targets
                const allTargets = this.runtime.targets.filter(t => t.isOriginal);
                for (const target of allTargets) {
                    if (target.lookupVariableByNameAndType(e.varName, e.varType, true)) {
                        return;
                    }
                }
                stage.createVariable(e.varId, e.varName, e.varType, e.isCloud);
                this.emitProjectChanged();
            }
            break;
        case 'var_rename':
            if (editingTarget && editingTarget.variables.hasOwnProperty(e.varId)) {
                // This is a local variable, rename on the current target
                editingTarget.renameVariable(e.varId, e.newName);
                // Update all the blocks on the current target that use
                // this variable
                editingTarget.blocks.updateBlocksAfterVarRename(e.varId, e.newName);
            } else {
                // This is a global variable
                stage.renameVariable(e.varId, e.newName);
                // Update all blocks on all targets that use the renamed variable
                const targets = this.runtime.targets;
                for (let i = 0; i < targets.length; i++) {
                    const currTarget = targets[i];
                    currTarget.blocks.updateBlocksAfterVarRename(e.varId, e.newName);
                }
            }
            this.emitProjectChanged();
            break;
        case 'var_delete': {
            const target = (editingTarget && editingTarget.variables.hasOwnProperty(e.varId)) ?
                editingTarget : stage;
            target.deleteVariable(e.varId);
            this.emitProjectChanged();
            break;
        }
        case 'comment_create':
            if (this.runtime.getEditingTarget()) {
                const currTarget = this.runtime.getEditingTarget();
                currTarget.createComment(e.commentId, e.blockId, e.text,
                    e.xy.x, e.xy.y, e.width, e.height, e.minimized);

                if (currTarget.comments[e.commentId].x === null &&
                    currTarget.comments[e.commentId].y === null) {
                    // Block comments imported from 2.0 projects are imported with their
                    // x and y coordinates set to null so that scratch-blocks can
                    // auto-position them. If we are receiving a create event for these
                    // comments, then the auto positioning should have taken place.
                    // Update the x and y position of these comments to match the
                    // one from the event.
                    currTarget.comments[e.commentId].x = e.xy.x;
                    currTarget.comments[e.commentId].y = e.xy.y;
                }
            }
            this.emitProjectChanged();
            break;
        case 'comment_change':
            if (this.runtime.getEditingTarget()) {
                const currTarget = this.runtime.getEditingTarget();
                if (!currTarget.comments.hasOwnProperty(e.commentId)) {
                    log.warn(`Cannot change comment with id ${e.commentId} because it does not exist.`);
                    return;
                }
                const comment = currTarget.comments[e.commentId];
                const change = e.newContents_;
                if (change.hasOwnProperty('minimized')) {
                    comment.minimized = change.minimized;
                }
                if (change.hasOwnProperty('width') && change.hasOwnProperty('height')){
                    comment.width = change.width;
                    comment.height = change.height;
                }
                if (change.hasOwnProperty('text')) {
                    comment.text = change.text;
                }
                this.emitProjectChanged();
            }
            break;
        case 'comment_move':
            if (this.runtime.getEditingTarget()) {
                const currTarget = this.runtime.getEditingTarget();
                if (currTarget && !currTarget.comments.hasOwnProperty(e.commentId)) {
                    log.warn(`Cannot change comment with id ${e.commentId} because it does not exist.`);
                    return;
                }
                const comment = currTarget.comments[e.commentId];
                const newCoord = e.newCoordinate_;
                comment.x = newCoord.x;
                comment.y = newCoord.y;

                this.emitProjectChanged();
            }
            break;
        case 'comment_delete':
            if (this.runtime.getEditingTarget()) {
                const currTarget = this.runtime.getEditingTarget();
                if (!currTarget.comments.hasOwnProperty(e.commentId)) {
                    // If we're in this state, we have probably received
                    // a delete event from a workspace that we switched from
                    // (e.g. a delete event for a comment on sprite a's workspace
                    // when switching from sprite a to sprite b)
                    return;
                }
                delete currTarget.comments[e.commentId];
                if (e.blockId) {
                    const block = currTarget.blocks.getBlock(e.blockId);
                    if (!block) {
                        log.warn(`Could not find block referenced by comment with id: ${e.commentId}`);
                        return;
                    }
                    delete block.comment;
                }

                this.emitProjectChanged();
            }
            break;
        }
    }

    // ---------------------------------------------------------------------

    /**
     * Reset all runtime caches.
     */
    resetCache () {
        this._cache.inputs = {};
        this._cache.procedureParamNames = {};
        this._cache.procedureDefinitions = {};
        this._cache._executeCached = {};
        this._cache._monitored = null;
        this._cache.scripts = {};
    }

    /**
     * Emit a project changed event if this is a block container
     * that can affect the project state.
     */
    emitProjectChanged () {
        if (!this.forceNoGlow) {
            this.runtime.emitProjectChanged();
        }
    }

    /**
     * Block management: create blocks and scripts from a `create` event
     * @param {!object} block Blockly create event to be processed
     */
    createBlock (block) {
        // Does the block already exist?
        // Could happen, e.g., for an unobscured shadow.
        if (this._blocks.hasOwnProperty(block.id)) {
            return;
        }
        // Create new block.
        this._blocks[block.id] = block;
        // Push block id to scripts array.
        // Blocks are added as a top-level stack if they are marked as a top-block
        // (if they were top-level XML in the event).
        if (block.topLevel) {
            this._addScript(block.id);
        }

        this.resetCache();

        // A new block was actually added to the block container,
        // emit a project changed event
        this.emitProjectChanged();
    }

    /**
     * Block management: change block field values
     * @param {!object} args Blockly change event to be processed
     */
    changeBlock (args) {
        // Validate
        if (['field', 'mutation', 'checkbox'].indexOf(args.element) === -1) return;
        let block = this._blocks[args.id];
        if (typeof block === 'undefined') return;
        switch (args.element) {
        case 'field':
            // TODO when the field of a monitored block changes,
            // update the checkbox in the flyout based on whether
            // a monitor for that current combination of selected parameters exists
            // e.g.
            // 1. check (current [v year])
            // 2. switch dropdown in flyout block to (current [v minute])
            // 3. the checkbox should become unchecked if we're not already
            //    monitoring current minute

            // Update block value
            if (!block.fields[args.name]) return;
            if (args.name === 'VARIABLE' || args.name === 'LIST' ||
                args.name === 'BROADCAST_OPTION') {
                // Get variable name using the id in args.value.
                const variable = this.runtime.getEditingTarget().lookupVariableById(args.value);
                if (variable) {
                    block.fields[args.name].value = variable.name;
                    block.fields[args.name].id = args.value;
                }
            } else {
                // Changing the value in a dropdown
                block.fields[args.name].value = args.value;

                // The selected item in the sensing of block menu needs to change based on the
                // selected target.  Set it to the first item in the menu list.
                // TODO: (#1787)
                if (block.opcode === 'sensing_of_object_menu') {
                    if (block.fields.OBJECT.value === '_stage_') {
                        this._blocks[block.parent].fields.PROPERTY.value = 'backdrop #';
                    } else {
                        this._blocks[block.parent].fields.PROPERTY.value = 'x position';
                    }
                    this.runtime.requestBlocksUpdate();
                }

                const flyoutBlock = block.shadow && block.parent ? this._blocks[block.parent] : block;
                if (flyoutBlock.isMonitored) {
                    this.runtime.requestUpdateMonitor(Map({
                        id: flyoutBlock.id,
                        params: this._getBlockParams(flyoutBlock)
                    }));
                }
            }
            break;
        case 'mutation':
            block.mutation = mutationAdapter(args.value);
            break;
        case 'checkbox': {
            // A checkbox usually has a one to one correspondence with the monitor
            // block but in the case of monitored reporters that have arguments,
            // map the old id to a new id, creating a new monitor block if necessary
            if (block.fields && Object.keys(block.fields).length > 0 &&
                block.opcode !== 'data_variable' && block.opcode !== 'data_listcontents') {

                // This block has an argument which needs to get separated out into
                // multiple monitor blocks with ids based on the selected argument
                const newId = getMonitorIdForBlockWithArgs(block.id, block.fields);
                // Note: we're not just constantly creating a longer and longer id everytime we check
                // the checkbox because we're using the id of the block in the flyout as the base

                // check if a block with the new id already exists, otherwise create
                let newBlock = this.runtime.monitorBlocks.getBlock(newId);
                if (!newBlock) {
                    newBlock = JSON.parse(JSON.stringify(block));
                    newBlock.id = newId;
                    this.runtime.monitorBlocks.createBlock(newBlock);
                }

                block = newBlock; // Carry on through the rest of this code with newBlock
            }

            const wasMonitored = block.isMonitored;
            block.isMonitored = args.value;

            // Variable blocks may be sprite specific depending on the owner of the variable
            let isSpriteLocalVariable = false;
            if (block.opcode === 'data_variable') {
                isSpriteLocalVariable = !(this.runtime.getTargetForStage().variables[block.fields.VARIABLE.id]);
            } else if (block.opcode === 'data_listcontents') {
                isSpriteLocalVariable = !(this.runtime.getTargetForStage().variables[block.fields.LIST.id]);
            }

            const isSpriteSpecific = isSpriteLocalVariable ||
                (this.runtime.monitorBlockInfo.hasOwnProperty(block.opcode) &&
                this.runtime.monitorBlockInfo[block.opcode].isSpriteSpecific);
            if (isSpriteSpecific) {
                // If creating a new sprite specific monitor, the only possible target is
                // the current editing one b/c you cannot dynamically create monitors.
                // Also, do not change the targetId if it has already been assigned
                block.targetId = block.targetId || this.runtime.getEditingTarget().id;
            } else {
                block.targetId = null;
            }

            if (wasMonitored && !block.isMonitored) {
                this.runtime.requestHideMonitor(block.id);
            } else if (!wasMonitored && block.isMonitored) {
                // Tries to show the monitor for specified block. If it doesn't exist, add the monitor.
                if (!this.runtime.requestShowMonitor(block.id)) {
                    this.runtime.requestAddMonitor(MonitorRecord({
                        id: block.id,
                        targetId: block.targetId,
                        spriteName: block.targetId ? this.runtime.getTargetById(block.targetId).getName() : null,
                        opcode: block.opcode,
                        params: this._getBlockParams(block),
                        // @todo(vm#565) for numerical values with decimals, some countries use comma
                        value: '',
                        mode: block.opcode === 'data_listcontents' ? 'list' : 'default'
                    }));
                }
            }
            break;
        }
        }

        this.emitProjectChanged();

        this.resetCache();
    }

    /**
     * Block management: move blocks from parent to parent
     * @param {!object} e Blockly move event to be processed
     */
    moveBlock (e) {
        if (!this._blocks.hasOwnProperty(e.id)) {
            return;
        }

        const block = this._blocks[e.id];
        // Track whether a change actually occurred
        // ignoring changes like routine re-positioning
        // of a block when loading a workspace
        let didChange = false;

        // Move coordinate changes.
        if (e.newCoordinate) {

            didChange = (block.x !== e.newCoordinate.x) || (block.y !== e.newCoordinate.y);

            block.x = e.newCoordinate.x;
            block.y = e.newCoordinate.y;
        }

        // Remove from any old parent.
        if (typeof e.oldParent !== 'undefined') {
            const oldParent = this._blocks[e.oldParent];
            if (typeof e.oldInput !== 'undefined' &&
                oldParent.inputs[e.oldInput].block === e.id) {
                // This block was connected to the old parent's input.
                oldParent.inputs[e.oldInput].block = null;
            } else if (oldParent.next === e.id) {
                // This block was connected to the old parent's next connection.
                oldParent.next = null;
            }
            this._blocks[e.id].parent = null;
            didChange = true;
        }

        // Is this block a top-level block?
        if (typeof e.newParent === 'undefined') {
            this._addScript(e.id);
        } else {
            // Remove script, if one exists.
            this._deleteScript(e.id);
            // Otherwise, try to connect it in its new place.
            if (typeof e.newInput === 'undefined') {
                // Moved to the new parent's next connection.
                this._blocks[e.newParent].next = e.id;
            } else {
                // Moved to the new parent's input.
                // Don't obscure the shadow block.
                let oldShadow = null;
                if (this._blocks[e.newParent].inputs.hasOwnProperty(e.newInput)) {
                    oldShadow = this._blocks[e.newParent].inputs[e.newInput].shadow;
                }

                // If the block being attached is itself a shadow, make sure to set
                // both block and shadow to that blocks ID. This happens when adding
                // inputs to a custom procedure.
                if (this._blocks[e.id].shadow) oldShadow = e.id;

                this._blocks[e.newParent].inputs[e.newInput] = {
                    name: e.newInput,
                    block: e.id,
                    shadow: oldShadow
                };
            }
            this._blocks[e.id].parent = e.newParent;
            didChange = true;
        }
        this.resetCache();

        if (didChange) this.emitProjectChanged();
    }

    /**
     * Block management: run all blocks.
     * @param {!object} runtime Runtime to run all blocks in.
     */
    runAllMonitored (runtime) {
        if (this._cache._monitored === null) {
            this._cache._monitored = Object.keys(this._blocks)
                .filter(blockId => this.getBlock(blockId).isMonitored)
                .map(blockId => {
                    const targetId = this.getBlock(blockId).targetId;
                    return {
                        blockId,
                        target: targetId ? runtime.getTargetById(targetId) : null
                    };
                });
        }

        const monitored = this._cache._monitored;
        for (let i = 0; i < monitored.length; i++) {
            const {blockId, target} = monitored[i];
            runtime.addMonitorScript(blockId, target);
        }
    }

    /**
     * Block management: delete blocks and their associated scripts. Does nothing if a block
     * with the given ID does not exist.
     * @param {!string} blockId Id of block to delete
     */
    deleteBlock (blockId) {
        // @todo In runtime, stop threads running on this script.

        // Get block
        const block = this._blocks[blockId];
        if (!block) {
            // No block with the given ID exists
            return;
        }

        // Delete children
        if (block.next !== null) {
            this.deleteBlock(block.next);
        }

        // Delete inputs (including branches)
        for (const input in block.inputs) {
            // If it's null, the block in this input moved away.
            if (block.inputs[input].block !== null) {
                this.deleteBlock(block.inputs[input].block);
            }
            // Delete obscured shadow blocks.
            if (block.inputs[input].shadow !== null &&
                block.inputs[input].shadow !== block.inputs[input].block) {
                this.deleteBlock(block.inputs[input].shadow);
            }
        }

        // Delete any script starting with this block.
        this._deleteScript(blockId);

        // Delete block itself.
        delete this._blocks[blockId];

        this.resetCache();
        this.emitProjectChanged();
    }

    /**
     * Returns a map of all references to variables or lists from blocks
     * in this block container.
     * @param {Array<object>} optBlocks Optional list of blocks to constrain the search to.
     * This is useful for getting variable/list references for a stack of blocks instead
     * of all blocks on the workspace
     * @param {?boolean} optIncludeBroadcast Optional whether to include broadcast fields.
     * @return {object} A map of variable ID to a list of all variable references
     * for that ID. A variable reference contains the field referencing that variable
     * and also the type of the variable being referenced.
     */
    getAllVariableAndListReferences (optBlocks, optIncludeBroadcast) {
        const blocks = optBlocks ? optBlocks : this._blocks;
        const allReferences = Object.create(null);
        for (const blockId in blocks) {
            let varOrListField = null;
            let varType = null;
            if (blocks[blockId].fields.VARIABLE) {
                varOrListField = blocks[blockId].fields.VARIABLE;
                varType = Variable.SCALAR_TYPE;
            } else if (blocks[blockId].fields.LIST) {
                varOrListField = blocks[blockId].fields.LIST;
                varType = Variable.LIST_TYPE;
            } else if (optIncludeBroadcast && blocks[blockId].fields.BROADCAST_OPTION) {
                varOrListField = blocks[blockId].fields.BROADCAST_OPTION;
                varType = Variable.BROADCAST_MESSAGE_TYPE;
            }
            if (varOrListField) {
                const currVarId = varOrListField.id;
                if (allReferences[currVarId]) {
                    allReferences[currVarId].push({
                        referencingField: varOrListField,
                        type: varType
                    });
                } else {
                    allReferences[currVarId] = [{
                        referencingField: varOrListField,
                        type: varType
                    }];
                }
            }
        }
        return allReferences;
    }

    /**
     * Keep blocks up to date after a variable gets renamed.
     * @param {string} varId The id of the variable that was renamed
     * @param {string} newName The new name of the variable that was renamed
     */
    updateBlocksAfterVarRename (varId, newName) {
        const blocks = this._blocks;
        for (const blockId in blocks) {
            let varOrListField = null;
            if (blocks[blockId].fields.VARIABLE) {
                varOrListField = blocks[blockId].fields.VARIABLE;
            } else if (blocks[blockId].fields.LIST) {
                varOrListField = blocks[blockId].fields.LIST;
            }
            if (varOrListField) {
                const currFieldId = varOrListField.id;
                if (varId === currFieldId) {
                    varOrListField.value = newName;
                }
            }
        }
    }

    /**
     * Keep blocks up to date after they are shared between targets.
     * @param {boolean} isStage If the new target is a stage.
     */
    updateTargetSpecificBlocks (isStage) {
        const blocks = this._blocks;
        for (const blockId in blocks) {
            if (isStage && blocks[blockId].opcode === 'event_whenthisspriteclicked') {
                blocks[blockId].opcode = 'event_whenstageclicked';
            } else if (!isStage && blocks[blockId].opcode === 'event_whenstageclicked') {
                blocks[blockId].opcode = 'event_whenthisspriteclicked';
            }
        }
    }

    /**
     * Update blocks after a sound, costume, or backdrop gets renamed.
     * Any block referring to the old name of the asset should get updated
     * to refer to the new name.
     * @param {string} oldName The old name of the asset that was renamed.
     * @param {string} newName The new name of the asset that was renamed.
     * @param {string} assetType String representation of the kind of asset
     * that was renamed. This can be one of 'sprite','costume', 'sound', or
     * 'backdrop'.
     */
    updateAssetName (oldName, newName, assetType) {
        let getAssetField;
        if (assetType === 'costume') {
            getAssetField = this._getCostumeField.bind(this);
        } else if (assetType === 'sound') {
            getAssetField = this._getSoundField.bind(this);
        } else if (assetType === 'backdrop') {
            getAssetField = this._getBackdropField.bind(this);
        } else if (assetType === 'sprite') {
            getAssetField = this._getSpriteField.bind(this);
        } else {
            return;
        }
        const blocks = this._blocks;
        for (const blockId in blocks) {
            const assetField = getAssetField(blockId);
            if (assetField && assetField.value === oldName) {
                assetField.value = newName;
            }
        }
    }

    /**
     * Update sensing_of blocks after a variable gets renamed.
     * @param {string} oldName The old name of the variable that was renamed.
     * @param {string} newName The new name of the variable that was renamed.
     * @param {string} targetName The name of the target the variable belongs to.
     * @return {boolean} Returns true if any of the blocks were updated.
     */
    updateSensingOfReference (oldName, newName, targetName) {
        const blocks = this._blocks;
        let blockUpdated = false;
        for (const blockId in blocks) {
            const block = blocks[blockId];
            if (block.opcode === 'sensing_of' &&
                block.fields.PROPERTY.value === oldName &&
                // If block and shadow are different, it means a block is inserted to OBJECT, and should be ignored.
                block.inputs.OBJECT.block === block.inputs.OBJECT.shadow) {
                const inputBlock = this.getBlock(block.inputs.OBJECT.block);
                if (inputBlock.fields.OBJECT.value === targetName) {
                    block.fields.PROPERTY.value = newName;
                    blockUpdated = true;
                }
            }
        }
        if (blockUpdated) this.resetCache();
        return blockUpdated;
    }

    /**
     * Helper function to retrieve a costume menu field from a block given its id.
     * @param {string} blockId A unique identifier for a block
     * @return {?object} The costume menu field of the block with the given block id.
     * Null if either a block with the given id doesn't exist or if a costume menu field
     * does not exist on the block with the given id.
     */
    _getCostumeField (blockId) {
        const block = this.getBlock(blockId);
        if (block && block.fields.hasOwnProperty('COSTUME')) {
            return block.fields.COSTUME;
        }
        return null;
    }

    /**
     * Helper function to retrieve a sound menu field from a block given its id.
     * @param {string} blockId A unique identifier for a block
     * @return {?object} The sound menu field of the block with the given block id.
     * Null, if either a block with the given id doesn't exist or if a sound menu field
     * does not exist on the block with the given id.
     */
    _getSoundField (blockId) {
        const block = this.getBlock(blockId);
        if (block && block.fields.hasOwnProperty('SOUND_MENU')) {
            return block.fields.SOUND_MENU;
        }
        return null;
    }

    /**
     * Helper function to retrieve a backdrop menu field from a block given its id.
     * @param {string} blockId A unique identifier for a block
     * @return {?object} The backdrop menu field of the block with the given block id.
     * Null, if either a block with the given id doesn't exist or if a backdrop menu field
     * does not exist on the block with the given id.
     */
    _getBackdropField (blockId) {
        const block = this.getBlock(blockId);
        if (block && block.fields.hasOwnProperty('BACKDROP')) {
            return block.fields.BACKDROP;
        }
        return null;
    }

    /**
     * Helper function to retrieve a sprite menu field from a block given its id.
     * @param {string} blockId A unique identifier for a block
     * @return {?object} The sprite menu field of the block with the given block id.
     * Null, if either a block with the given id doesn't exist or if a sprite menu field
     * does not exist on the block with the given id.
     */
    _getSpriteField (blockId) {
        const block = this.getBlock(blockId);
        if (!block) {
            return null;
        }
        const spriteMenuNames = ['TOWARDS', 'TO', 'OBJECT', 'VIDEOONMENU2',
            'DISTANCETOMENU', 'TOUCHINGOBJECTMENU', 'CLONE_OPTION'];
        for (let i = 0; i < spriteMenuNames.length; i++) {
            const menuName = spriteMenuNames[i];
            if (block.fields.hasOwnProperty(menuName)) {
                return block.fields[menuName];
            }
        }
        return null;
    }

    // ---------------------------------------------------------------------

    /**
     * Encode all of `this._blocks` as an XML string usable
     * by a Blockly/scratch-blocks workspace.
     * @param {object<string, Comment>} comments Map of comments referenced by id
     * @return {string} String of XML representing this object's blocks.
     */
    toXML (comments) {
        return this._scripts.map(script => this.blockToXML(script, comments)).join();
    }

    /**
     * Recursively encode an individual block and its children
     * into a Blockly/scratch-blocks XML string.
     * @param {!string} blockId ID of block to encode.
     * @param {object<string, Comment>} comments Map of comments referenced by id
     * @return {string} String of XML representing this block and any children.
     */
    blockToXML (blockId, comments) {
        const block = this._blocks[blockId];
        // block should exist, but currently some blocks' next property point
        // to a blockId for non-existent blocks. Until we track down that behavior,
        // this early exit allows the project to load.
        if (!block) return;
        // Encode properties of this block.
        const tagName = (block.shadow) ? 'shadow' : 'block';
        let xmlString =
            `<${tagName}
                id="${block.id}"
                type="${block.opcode}"
                ${block.topLevel ? `x="${block.x}" y="${block.y}"` : ''}
            >`;
        const commentId = block.comment;
        if (commentId) {
            if (comments) {
                if (comments.hasOwnProperty(commentId)) {
                    xmlString += comments[commentId].toXML();
                } else {
                    log.warn(`Could not find comment with id: ${commentId} in provided comment descriptions.`);
                }
            } else {
                log.warn(`Cannot serialize comment with id: ${commentId}; no comment descriptions provided.`);
            }
        }
        // Add any mutation. Must come before inputs.
        if (block.mutation) {
            xmlString += this.mutationToXML(block.mutation);
        }
        // Add any inputs on this block.
        for (const input in block.inputs) {
            if (!block.inputs.hasOwnProperty(input)) continue;
            const blockInput = block.inputs[input];
            // Only encode a value tag if the value input is occupied.
            if (blockInput.block || blockInput.shadow) {
                xmlString += `<value name="${blockInput.name}">`;
                if (blockInput.block) {
                    xmlString += this.blockToXML(blockInput.block, comments);
                }
                if (blockInput.shadow && blockInput.shadow !== blockInput.block) {
                    // Obscured shadow.
                    xmlString += this.blockToXML(blockInput.shadow, comments);
                }
                xmlString += '</value>';
            }
        }
        // Add any fields on this block.
        for (const field in block.fields) {
            if (!block.fields.hasOwnProperty(field)) continue;
            const blockField = block.fields[field];
            xmlString += `<field name="${blockField.name}"`;
            const fieldId = blockField.id;
            if (fieldId) {
                xmlString += ` id="${fieldId}"`;
            }
            const varType = blockField.variableType;
            if (typeof varType === 'string') {
                xmlString += ` variabletype="${varType}"`;
            }
            let value = blockField.value;
            if (typeof value === 'string') {
                value = xmlEscape(blockField.value);
            }
            xmlString += `>${value}</field>`;
        }
        // Add blocks connected to the next connection.
        if (block.next) {
            xmlString += `<next>${this.blockToXML(block.next, comments)}</next>`;
        }
        xmlString += `</${tagName}>`;
        return xmlString;
    }

    /**
     * Recursively encode a mutation object to XML.
     * @param {!object} mutation Object representing a mutation.
     * @return {string} XML string representing a mutation.
     */
    mutationToXML (mutation) {
        let mutationString = `<${mutation.tagName}`;
        for (const prop in mutation) {
            if (prop === 'children' || prop === 'tagName') continue;
            let mutationValue = (typeof mutation[prop] === 'string') ?
                xmlEscape(mutation[prop]) : mutation[prop];

            // Handle dynamic extension blocks
            if (prop === 'blockInfo') {
                mutationValue = xmlEscape(JSON.stringify(mutation[prop]));
            }

            mutationString += ` ${prop}="${mutationValue}"`;
        }
        mutationString += '>';
        for (let i = 0; i < mutation.children.length; i++) {
            mutationString += this.mutationToXML(mutation.children[i]);
        }
        mutationString += `</${mutation.tagName}>`;
        return mutationString;
    }

    // ---------------------------------------------------------------------
    /**
     * Helper to serialize block fields and input fields for reporting new monitors
     * @param {!object} block Block to be paramified.
     * @return {!object} object of param key/values.
     */
    _getBlockParams (block) {
        const params = {};
        for (const key in block.fields) {
            params[key] = block.fields[key].value;
        }
        for (const inputKey in block.inputs) {
            const inputBlock = this._blocks[block.inputs[inputKey].block];
            for (const key in inputBlock.fields) {
                params[key] = inputBlock.fields[key].value;
            }
        }
        return params;
    }

    /**
     * Helper to get the corresponding internal procedure definition block
     * @param {!object} defineBlock Outer define block.
     * @return {!object} internal definition block which has the mutation.
     */
    _getCustomBlockInternal (defineBlock) {
        if (defineBlock.inputs && defineBlock.inputs.custom_block) {
            return this._blocks[defineBlock.inputs.custom_block.block];
        }
    }

    /**
     * Helper to add a stack to `this._scripts`.
     * @param {?string} topBlockId ID of block that starts the script.
     */
    _addScript (topBlockId) {
        const i = this._scripts.indexOf(topBlockId);
        if (i > -1) return; // Already in scripts.
        this._scripts.push(topBlockId);
        // Update `topLevel` property on the top block.
        this._blocks[topBlockId].topLevel = true;
    }

    /**
     * Helper to remove a script from `this._scripts`.
     * @param {?string} topBlockId ID of block that starts the script.
     */
    _deleteScript (topBlockId) {
        const i = this._scripts.indexOf(topBlockId);
        if (i > -1) this._scripts.splice(i, 1);
        // Update `topLevel` property on the top block.
        if (this._blocks[topBlockId]) this._blocks[topBlockId].topLevel = false;
    }
}

/**
 * A private method shared with execute to build an object containing the block
 * information execute needs and that is reset when other cached Blocks info is
 * reset.
 * @param {Blocks} blocks Blocks containing the expected blockId
 * @param {string} blockId blockId for the desired execute cache
 * @param {function} CacheType constructor for cached block information
 * @return {object} execute cache object
 */
BlocksExecuteCache.getCached = function (blocks, blockId, CacheType) {
    let cached = blocks._cache._executeCached[blockId];
    if (typeof cached !== 'undefined') {
        return cached;
    }

    const block = blocks.getBlock(blockId);
    if (typeof block === 'undefined') return null;

    if (typeof CacheType === 'undefined') {
        cached = {
            id: blockId,
            opcode: blocks.getOpcode(block),
            fields: blocks.getFields(block),
            inputs: blocks.getInputs(block),
            mutation: blocks.getMutation(block)
        };
    } else {
        cached = new CacheType(blocks, {
            id: blockId,
            opcode: blocks.getOpcode(block),
            fields: blocks.getFields(block),
            inputs: blocks.getInputs(block),
            mutation: blocks.getMutation(block)
        });
    }

    blocks._cache._executeCached[blockId] = cached;
    return cached;
};

/**
 * Cache class constructor for runtime. Used to consider what threads should
 * start based on hat data.
 * @type {function}
 */
const RuntimeScriptCache = BlocksRuntimeCache._RuntimeScriptCache;

/**
 * Get an array of scripts from a block container prefiltered to match opcode.
 * @param {Blocks} blocks - Container of blocks
 * @param {string} opcode - Opcode to filter top blocks by
 * @returns {Array.<RuntimeScriptCache>} - Array of RuntimeScriptCache cache
 *   objects
 */
BlocksRuntimeCache.getScripts = function (blocks, opcode) {
    let scripts = blocks._cache.scripts[opcode];
    if (!scripts) {
        scripts = blocks._cache.scripts[opcode] = [];

        const allScripts = blocks._scripts;
        for (let i = 0; i < allScripts.length; i++) {
            const topBlockId = allScripts[i];
            const block = blocks.getBlock(topBlockId);
            if (block.opcode === opcode) {
                scripts.push(new RuntimeScriptCache(blocks, topBlockId));
            }
        }
    }
    return scripts;
};

module.exports = Blocks;


text:
package com.exalttech.trex.ui.controllers;

import com.exalttech.trex.ui.dialog.DialogView;
import com.exalttech.trex.ui.models.ChartSeries;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.StringProperty;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * FXML Controller class
 *
 * @author Georgekh
 */
public class LatencySeriesOptionWindowController extends DialogView implements Initializable {

    @FXML
    VBox optionContainer;
    private BooleanProperty updateChartProperty;
    @FXML
    ToggleGroup latencyInterval;
    private StringProperty intervalProperty;

    /**
     * Initializes the controller class.
     *
     * @param url
     * @param rb
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        //
    }

    /**
     *
     * @param chartSeriesList
     * @param updateChartProperty
     * @param intervalProperty
     */
    public void initOption(List<ChartSeries> chartSeriesList, BooleanProperty updateChartProperty, StringProperty intervalProperty) {
        this.updateChartProperty = updateChartProperty;
        this.intervalProperty = intervalProperty;
        updateIntervalSelection();
        optionContainer.getChildren().clear();
        for (ChartSeries series : chartSeriesList) {
            CheckBox showSeriesCB = new CheckBox(series.getName());
            showSeriesCB.selectedProperty().bindBidirectional(series.getShowSeriesProperty());
            optionContainer.getChildren().add(showSeriesCB);
        }
    }

    /**
     * Update interval selection
     */
    private void updateIntervalSelection() {
        for (Toggle toggle : latencyInterval.getToggles()) {
            if (((RadioButton) toggle).getText().equals(intervalProperty.get())) {
                latencyInterval.selectToggle(toggle);
                return;
            }
        }
    }

    @Override
    public void onEnterKeyPressed(Stage stage) {
        close(stage);
    }

    private void close(Stage stage) {
        stage.hide();
    }

    /**
     *
     * @param event
     */
    @FXML
    public void handleOKButtonClicked(ActionEvent event) {
        intervalProperty.set(((RadioButton) latencyInterval.getSelectedToggle()).getText());
        updateChartProperty.set(!updateChartProperty.get());
        Button source = (Button) event.getSource();
        Stage stage = (Stage) source.getScene().getWindow();
        close(stage);
    }
}


text:
package convey

import "github.com/smartystreets/goconvey/convey/reporting"

// Convey is the method intended for use when declaring the scopes
// of a specification. Each scope has a description and a func()
// which may contain other calls to Convey(), Reset() or Should-style
// assertions. Convey calls can be nested as far as you see fit.
//
// IMPORTANT NOTE: The top-level Convey() within a Test method
// must conform to the following signature:
//
//     Convey(description string, t *testing.T, action func())
//
// All other calls should like like this (no need to pass in *testing.T):
//
//     Convey(description string, action func())
//
// Don't worry, the goconvey will panic if you get it wrong so you can fix it.
//
// See the examples package for, well, examples.
func Convey(items ...interface{}) {
	entry := discover(items)
	register(entry)
}

// SkipConvey is analagous to Convey except that the scope is not executed
// (which means that child scopes defined within this scope are not run either).
// The reporter will be notified that this step was skipped.
func SkipConvey(items ...interface{}) {
	entry := discover(items)
	entry.action = newSkippedAction(skipReport)
	register(entry)
}

// FocusConvey is has the inverse effect of SkipConvey. If the top-level
// Convey is changed to `FocusConvey`, only nested scopes that are defined
// with FocusConvey will be run. The rest will be ignored completely. This
// is handy when debugging a large suite that runs a misbehaving function
// repeatedly as you can disable all but one of that function
// without swaths of `SkipConvey` calls, just a targeted chain of calls
// to FocusConvey.
func FocusConvey(items ...interface{}) {
	entry := discover(items)
	entry.Focus = true
	register(entry)
}

func register(entry *registration) {
	if entry.IsTopLevel() {
		suites.Run(entry)
	} else {
		suites.Current().Register(entry)
	}
}

func skipReport() {
	suites.Current().Report(reporting.NewSkipReport())
}

// Reset registers a cleanup function to be run after each Convey()
// in the same scope. See the examples package for a simple use case.
func Reset(action func()) {
	suites.Current().RegisterReset(newAction(action))
}

// So is the means by which assertions are made against the system under test.
// The majority of exported names in the assertions package begin with the word
// 'Should' and describe how the first argument (actual) should compare with any
// of the final (expected) arguments. How many final arguments are accepted
// depends on the particular assertion that is passed in as the assert argument.
// See the examples package for use cases and the assertions package for
// documentation on specific assertion methods.
func So(actual interface{}, assert assertion, expected ...interface{}) {
	if result := assert(actual, expected...); result == assertionSuccess {
		suites.Current().Report(reporting.NewSuccessReport())
	} else {
		suites.Current().Report(reporting.NewFailureReport(result))
	}
}

// SkipSo is analagous to So except that the assertion that would have been passed
// to So is not executed and the reporter is notified that the assertion was skipped.
func SkipSo(stuff ...interface{}) {
	skipReport()
}

// assertion is an alias for a function with a signature that the convey.So()
// method can handle. Any future or custom assertions should conform to this
// method signature. The return value should be an empty string if the assertion
// passes and a well-formed failure message if not.
type assertion func(actual interface{}, expected ...interface{}) string

const assertionSuccess = ""


text:
package dgeffects;

import dggameComponents.DGPlayer;
import dgcards.CreatureCard;
import base.CardZone;
import base.Effect;

public class CreatureDeath extends Effect {

	static final long serialVersionUID = 557;

	public CreatureDeath(CreatureCard source) {
		super(source, source.getName() + "Death");
		// TODO Auto-generated constructor stub
	}

	@Override
	public void activate() {
		DGPlayer player = (DGPlayer) this.source.getOwner();
		if(player != null && player instanceof DGPlayer)
		{
			//System.out.println("This creature should be destroyed like wtf!!!");
			source.destroy();
			CardZone.moveCard(source, source.getCurrentZone() , player.getGraveyard());
		}

	}

	@Override
	public void deactivate() {
		System.out.println("Silly rabbit, you can't undo creature death!");
	}

	public void update()
	{

	}
}


text:
<!DOCTYPE html>

 <meta charset="UTF-8">

<title>CentralAxes—Wolfram Language Documentation</title>
<meta name="buildnumber" content="0000000" />
<meta name="historydata" content="{XX, , , }" />
<meta name="keywords" content="CentralAxes" />

<meta name="description" content="CentralAxes[mask, vox] calculates the center of the lumen from a mask of the left ventricle. vox is the voxels size, {slice, x, y}. CentralAxes[mask, maskp, vox] allows for fancy visualization of the other structures using maskp. Output is {centerpoints, normalvecs, inout} or {centerpoints, normalvecs, inout, fit}." />

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<link rel="stylesheet" href="../css/reference.css" />

            <link rel="stylesheet" href="../css/clipboard.css" />

   Q M R I TOOLS PACKAGE SYMBOL

    Related Guides

      CardiacTools

CentralAxes

CentralAxes[mask, vox]
calculates the center of the lumen from a mask of the left ventricle. vox is the voxels size, {slice, x, y}.

CentralAxes[mask, maskp, vox]
allows for fancy visualization of the other structures using maskp. Output is {centerpoints, normalvecs, inout} or {centerpoints, normalvecs, inout, fit}.

DetailsDetails

The following options can be given:

       <col width="1%" />
       <col width="28%" />
       <col width="28%" />
       <col width="43%" />

ShowFit	True	ShowFit is an option for CentralAxes. True shows the fit of the central axes.

RowSize	Automatic	RowSize is an option for CentralAxes. defines the number or images per showing the segmentation.
Can be "Automatic" of an integer.

AxesMethod	Cubic	AxesMethod is an option for HelixAngleCalc and CentralAxes. Can be "Linear", "Quadratic", "Cubic".

Related GuidesRelated Guides

      CardiacTools


text:
package com.pablode.mbgvn.app.cards;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.pablode.mbgvn.app.R;

public class ExpandableCard<T> extends MBGVNCard<T> {

    protected boolean expandedOnCreation = false;

    protected boolean expanded = true, locked = false;
    protected FrameLayout mContent;
    protected ImageView mExpander;

    public ExpandableCard(Context context, int innerlayout, T info) {
        super(context, innerlayout, info);
    }

    // Thanks to this answer on stackoverflow :) works great
    // https://stackoverflow.com/questions/4946295/android-expand-collapse-animation
    public void Expand() {

        // This code is supposed to be supported on every targeted version (14+)
        if(!locked) {
            mExpander.setBackgroundResource(R.drawable.ic_action_collapse);
            mContent.measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            final int targetHeight = mContent.getMeasuredHeight();
            mContent.getLayoutParams().height = 0;
            mContent.setVisibility(View.VISIBLE);
            Animation a = new Animation() {
                @Override
                protected void applyTransformation(float interpolatedTime, Transformation t) {
                    mContent.getLayoutParams().height = interpolatedTime == 1
                            ? ViewGroup.LayoutParams.WRAP_CONTENT
                            : (int) (targetHeight * interpolatedTime);
                    mContent.requestLayout();
                }
                @Override
                public boolean willChangeBounds() {
                    return true;
                }
            };
            // 1dp/ms
            a.setDuration((int) (targetHeight / mContent.getContext().getResources().getDisplayMetrics().density));
            mContent.startAnimation(a);
            expanded = true;
        }
    }
    public void Collapse() {

        if(!locked) {
            mExpander.setBackgroundResource(R.drawable.ic_action_expand);
            final int initialHeight = mContent.getMeasuredHeight();
            Animation a = new Animation() {
                @Override
                protected void applyTransformation(float interpolatedTime, Transformation t) {
                    if (interpolatedTime == 1) {
                        mContent.setVisibility(View.GONE);
                    } else {
                        mContent.getLayoutParams().height = initialHeight - (int) (initialHeight * interpolatedTime);
                        mContent.requestLayout();
                    }
                }
                @Override
                public boolean willChangeBounds() {
                    return true;
                }
            };
            // 1dp/ms
            a.setDuration((int) (initialHeight / mContent.getContext().getResources().getDisplayMetrics().density));
            mContent.startAnimation(a);
            expanded = false;
        }
    }

    // Disables ability to collapse/expand when refreshing the fragment
    public void Lock() {
        locked = true;
    }
    public void Unlock() {
        locked = false;
    }
}


text:
import {
  Component,
  Input,
  Directive,
  AfterContentInit,
  ContentChild,
  ContentChildren,
  ElementRef,
  QueryList,
  ViewEncapsulation,
  Optional,
  Output,
  EventEmitter,
  Renderer
} from '@angular/core';
import {coerceBooleanProperty} from '../core';
import {NgControl} from '@angular/forms';
import {getSupportedInputTypes} from '../core/platform/features';
import {
  MdInputContainerUnsupportedTypeError,
  MdInputContainerPlaceholderConflictError,
  MdInputContainerDuplicatedHintError,
  MdInputContainerMissingMdInputError
} from './input-container-errors';

// Invalid input type. Using one of these will throw an MdInputContainerUnsupportedTypeError.
const MD_INPUT_INVALID_TYPES = [
  'button',
  'checkbox',
  'color',
  'file',
  'hidden',
  'image',
  'radio',
  'range',
  'reset',
  'submit'
];

let nextUniqueId = 0;

/**
 * The placeholder directive. The content can declare this to implement more
 * complex placeholders.
 */
@Directive({
  selector: 'md-placeholder, mat-placeholder'
})
export class MdPlaceholder {}

/** The hint directive, used to tag content as hint labels (going under the input). */
@Directive({
  selector: 'md-hint, mat-hint',
  host: {
    'class': 'md-hint',
    '[class.md-right]': 'align == "end"',
  }
})
export class MdHint {
  // Whether to align the hint label at the start or end of the line.
  @Input() align: 'start' | 'end' = 'start';
}

/** The input directive, used to mark the input that `MdInputContainer` is wrapping. */
@Directive({
  selector: 'input[md-input], textarea[md-input], input[mat-input], textarea[mat-input]',
  host: {
    'class': 'md-input-element',
    '[id]': 'id',
    '(blur)': '_onBlur()',
    '(focus)': '_onFocus()',
    '(input)': '_onInput()',
  }
})
export class MdInputDirective implements AfterContentInit {
  /** Whether the element is disabled. */
  @Input()
  get disabled() { return this._disabled; }
  set disabled(value: any) { this._disabled = coerceBooleanProperty(value); }
  private _disabled = false;

  /** Unique id of the element. */
  @Input()
  get id() { return this._id; };
  set id(value: string) { this._id = value || this._uid; }
  private _id: string;

  /** Placeholder attribute of the element. */
  @Input()
  get placeholder() { return this._placeholder; }
  set placeholder(value: string) {
    if (this._placeholder != value) {
      this._placeholder = value;
      this._placeholderChange.emit(this._placeholder);
    }
  }
  private _placeholder = '';

  /** Whether the element is required. */
  @Input()
  get required() { return this._required; }
  set required(value: any) { this._required = coerceBooleanProperty(value); }
  private _required = false;

  /** Input type of the element. */
  @Input()
  get type() { return this._type; }
  set type(value: string) {
    this._type = value || 'text';
    this._validateType();
  }
  private _type = 'text';

  /** The element's value. */
  value: any;

  /**
   * Emits an event when the placeholder changes so that the `md-input-container` can re-validate.
   */
  @Output() _placeholderChange = new EventEmitter<string>();

  get empty() { return (this.value == null || this.value === '') && !this._isNeverEmpty(); }

  focused = false;

  private get _uid() { return this._cachedUid = this._cachedUid || `md-input-${nextUniqueId++}`; }
  private _cachedUid: string;

  private _neverEmptyInputTypes = [
    'date',
    'datetime',
    'datetime-local',
    'month',
    'time',
    'week'
  ].filter(t => getSupportedInputTypes().has(t));

  constructor(private _elementRef: ElementRef,
              private _renderer: Renderer,
              @Optional() public _ngControl: NgControl) {
    // Force setter to be called in case id was not specified.
    this.id = this.id;

    if (this._ngControl && this._ngControl.valueChanges) {
      this._ngControl.valueChanges.subscribe((value) => {
        this.value = value;
      });
    }
  }

  ngAfterContentInit() {
    this.value = this._elementRef.nativeElement.value;
  }

  /** Focuses the input element. */
  focus() { this._renderer.invokeElementMethod(this._elementRef.nativeElement, 'focus'); }

  _onFocus() { this.focused = true; }

  _onBlur() { this.focused = false; }

  _onInput() { this.value = this._elementRef.nativeElement.value; }

  /** Make sure the input is a supported type. */
  private _validateType() {
    if (MD_INPUT_INVALID_TYPES.indexOf(this._type) != -1) {
      throw new MdInputContainerUnsupportedTypeError(this._type);
    }
  }

  private _isNeverEmpty() { return this._neverEmptyInputTypes.indexOf(this._type) != -1; }
}

/**
 * Component that represents a text input. It encapsulates the <input> HTMLElement and
 * improve on its behaviour, along with styling it according to the Material Design.
 */
@Component({
  moduleId: module.id,
  selector: 'md-input-container, mat-input-container',
  templateUrl: 'input-container.html',
  styleUrls: ['input.css', 'input-container.css'],
  host: {
    // Remove align attribute to prevent it from interfering with layout.
    '[attr.align]': 'null',
    '[class.ng-untouched]': '_isUntouched()',
    '[class.ng-touched]': '_isTouched()',
    '[class.ng-pristine]': '_isPristine()',
    '[class.ng-dirty]': '_isDirty()',
    '[class.ng-valid]': '_isValid()',
    '[class.ng-invalid]': '_isInvalid()',
    '[class.ng-pending]': '_isPending()',
    '(click)': '_focusInput()',
  },
  encapsulation: ViewEncapsulation.None,
})
export class MdInputContainer implements AfterContentInit {
  /** Alignment of the input container's content. */
  @Input() align: 'start' | 'end' = 'start';

  /** Color of the input divider, based on the theme. */
  @Input() dividerColor: 'primary' | 'accent' | 'warn' = 'primary';

  /** Text for the input hint. */
  @Input()
  get hintLabel() { return this._hintLabel; }
  set hintLabel(value: string) {
    this._hintLabel = value;
    this._validateHints();
  }
  private _hintLabel = '';

  /** Text or the floating placeholder. */
  @Input()
  get floatingPlaceholder(): boolean { return this._floatingPlaceholder; }
  set floatingPlaceholder(value) { this._floatingPlaceholder = coerceBooleanProperty(value); }
  private _floatingPlaceholder: boolean = true;

  @ContentChild(MdInputDirective) _mdInputChild: MdInputDirective;

  @ContentChild(MdPlaceholder) _placeholderChild: MdPlaceholder;

  @ContentChildren(MdHint) _hintChildren: QueryList<MdHint>;

  ngAfterContentInit() {
    if (!this._mdInputChild) {
      throw new MdInputContainerMissingMdInputError();
    }

    this._validateHints();
    this._validatePlaceholders();

    // Re-validate when things change.
    this._hintChildren.changes.subscribe(() => {
      this._validateHints();
    });
    this._mdInputChild._placeholderChange.subscribe(() => {
      this._validatePlaceholders();
    });
  }

  _isUntouched() { return this._hasNgControl() && this._mdInputChild._ngControl.untouched; }

  _isTouched() { return this._hasNgControl() && this._mdInputChild._ngControl.touched; }

  _isPristine() { return this._hasNgControl() && this._mdInputChild._ngControl.pristine; }

  _isDirty() { return this._hasNgControl() && this._mdInputChild._ngControl.dirty; }

  _isValid() { return this._hasNgControl() && this._mdInputChild._ngControl.valid; }

  _isInvalid() { return this._hasNgControl() && this._mdInputChild._ngControl.invalid; }

  _isPending() { return this._hasNgControl() && this._mdInputChild._ngControl.pending; }

  /** Whether the input has a placeholder. */
  _hasPlaceholder() { return !!(this._mdInputChild.placeholder || this._placeholderChild); }

  _focusInput() { this._mdInputChild.focus(); }

  private _hasNgControl() { return !!(this._mdInputChild && this._mdInputChild._ngControl); }

  /**
   * Ensure that there is only one placeholder (either `input` attribute or child element with the
   * `md-placeholder` attribute.
   */
  private _validatePlaceholders() {
    if (this._mdInputChild.placeholder && this._placeholderChild) {
      throw new MdInputContainerPlaceholderConflictError();
    }
  }

  /**
   * Ensure that there is a maximum of one of each `<md-hint>` alignment specified, with the
   * attribute being considered as `align="start"`.
   */
  private _validateHints() {
    if (this._hintChildren) {
      let startHint: MdHint = null;
      let endHint: MdHint = null;
      this._hintChildren.forEach((hint: MdHint) => {
        if (hint.align == 'start') {
          if (startHint || this.hintLabel) {
            throw new MdInputContainerDuplicatedHintError('start');
          }
          startHint = hint;
        } else if (hint.align == 'end') {
          if (endHint) {
            throw new MdInputContainerDuplicatedHintError('end');
          }
          endHint = hint;
        }
      });
    }
  }
}


text:
package net.sky.scweather;

import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;

import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.*;

/**
 * Instrumentation test, which will execute on an Android device.
 *
 * @see Testing documentation
 */
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
    @Test
    public void useAppContext() throws Exception {
        // Context of the app under test.
        Context appContext = InstrumentationRegistry.getTargetContext();

        assertEquals("net.sky.scweather", appContext.getPackageName());
    }
}


text:
require('@rails/ujs').start()

// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)

require('social-likes')
require('./bulma')
require('./timeago')

$(document).ready(() => {

    window.open_player = (url) => {
        var nw;
        nw = window.open(url, 'player', 'width=640,height=160,status=0,menubar=0,location=0,toolbar=0,scrollbars=0');
        if (window.focus) {
            nw.focus();
        }
        return false;
    };

    $('.open_player').click((event) => {
        return open_player(event.currentTarget.href);
    });

    function stop_all_players() {
        var ref = $('audio');
        for (var _i = 0, _len = ref.length; _i < _len; _i++) {
            ref[_i].pause();
        }
    }

    function seconds_from_hash(hash) {
        var h_m_s = hash.replace('#play-', '').split(':');
        var seconds = 0;
        if (h_m_s.length === 2) {
            seconds = parseInt(h_m_s[0]) * 60 + parseInt(h_m_s[1]);
        } else if (h_m_s.length === 3) {
            seconds = parseInt(h_m_s[0]) * 3600 + parseInt(h_m_s[1]) * 60 + parseInt(h_m_s[2]);
        }
        return seconds < 8000 ? seconds : 0;
    }

    function seek_and_play(href, player) {
        var current_time = seconds_from_hash(href);
        if (player && current_time > 0) {
            stop_all_players();
            player.currentTime = current_time;
            player.play();
            player.oncanplay = (e) => {
                if (player.currentTime == 0) {
                    player.currentTime = current_time;
                }
            }
        }
    }

    $(document).on('click', 'a[href^="#play-"]', (event) => {
        var target, player;
        event.preventDefault();
        target = event.currentTarget;
        player = $(target).parents('article.post').first().find('audio')[0];
        seek_and_play($(target).attr('href'), player);
    });

    if (window.location.pathname.startsWith('/posts/') && window.location.hash.startsWith('#play-')) {
        var audios = $('audio')
        var seconds = seconds_from_hash(window.location.hash);
        if (audios.length > 0 && seconds > 0) {
            $('h1.title').append('' + window.location.hash.split('-')[1] + '')
        }
    }
})


text:
import fs from 'fs';
import path from 'path'
import express from 'express'
import React from 'react'
import ReactDOMServer, { renderToString } from 'react-dom/server'
import { StaticRouter } from 'react-router-dom'
import { matchRoutes } from 'react-router-config'
import App from './src/App'
import routes from './src/routes'

const app = express()
const viewPath = process.env.DEVELOPMENT ? 'view' : 'build'

// Set view engine & serve static assets
app.set('view engine', 'ejs')
app.set('views', path.join(__dirname, viewPath))
app.use(express.static(path.join(__dirname, 'build')))

// Always return the main index.html, so react-router render the route in the client
app.get('*', (req, res) => {
	const branch = matchRoutes(routes, req.url)
	const promises = []

	branch.forEach( ({route, match}) => {
		if (route.loadData)
			promises.push(route.loadData(match))
	})

	Promise.all(promises).then(data => {
		// data will be an array[] of datas returned by each promises.
		// console.log(data)

		const context = data.reduce( (context, data) => {
			return Object.assign(context, data)
		}, {})

		const html = renderToString(
			<StaticRouter location={req.url} context={context} >
				<App/>
			</StaticRouter>
		)

		if(context.url) {
			res.writeHead(301, {Location: context.url})
			res.end()
		}
		return res.render('index', {html})
	})
})

// Run server
const port = process.env.PORT || 3000
app.listen(port, err => {
	if (err) return console.error(err)
	console.log(`Server listening at http://localhost:${port}`)
})