text:
package org.w3.x2001.smil20;

/**
 * An XML animatePrototype(@http://www.w3.org/2001/SMIL20/).
 *
 * This is a complex type.
 */
public interface AnimatePrototype extends org.apache.xmlbeans.XmlObject
{
    public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType)
        org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(AnimatePrototype.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s6E28D279B6C224D74769DB8B98AF1665").resolveHandle("animateprototype9ecetype");

    /**
     * Gets the "attributeName" attribute
     */
    java.lang.String getAttributeName();

    /**
     * Gets (as xml) the "attributeName" attribute
     */
    org.apache.xmlbeans.XmlString xgetAttributeName();

    /**
     * Sets the "attributeName" attribute
     */
    void setAttributeName(java.lang.String attributeName);

    /**
     * Sets (as xml) the "attributeName" attribute
     */
    void xsetAttributeName(org.apache.xmlbeans.XmlString attributeName);

    /**
     * Gets the "attributeType" attribute
     */
    org.w3.x2001.smil20.AnimatePrototype.AttributeType.Enum getAttributeType();

    /**
     * Gets (as xml) the "attributeType" attribute
     */
    org.w3.x2001.smil20.AnimatePrototype.AttributeType xgetAttributeType();

    /**
     * True if has "attributeType" attribute
     */
    boolean isSetAttributeType();

    /**
     * Sets the "attributeType" attribute
     */
    void setAttributeType(org.w3.x2001.smil20.AnimatePrototype.AttributeType.Enum attributeType);

    /**
     * Sets (as xml) the "attributeType" attribute
     */
    void xsetAttributeType(org.w3.x2001.smil20.AnimatePrototype.AttributeType attributeType);

    /**
     * Unsets the "attributeType" attribute
     */
    void unsetAttributeType();

    /**
     * Gets the "additive" attribute
     */
    org.w3.x2001.smil20.AnimatePrototype.Additive.Enum getAdditive();

    /**
     * Gets (as xml) the "additive" attribute
     */
    org.w3.x2001.smil20.AnimatePrototype.Additive xgetAdditive();

    /**
     * True if has "additive" attribute
     */
    boolean isSetAdditive();

    /**
     * Sets the "additive" attribute
     */
    void setAdditive(org.w3.x2001.smil20.AnimatePrototype.Additive.Enum additive);

    /**
     * Sets (as xml) the "additive" attribute
     */
    void xsetAdditive(org.w3.x2001.smil20.AnimatePrototype.Additive additive);

    /**
     * Unsets the "additive" attribute
     */
    void unsetAdditive();

    /**
     * Gets the "accumulate" attribute
     */
    org.w3.x2001.smil20.AnimatePrototype.Accumulate.Enum getAccumulate();

    /**
     * Gets (as xml) the "accumulate" attribute
     */
    org.w3.x2001.smil20.AnimatePrototype.Accumulate xgetAccumulate();

    /**
     * True if has "accumulate" attribute
     */
    boolean isSetAccumulate();

    /**
     * Sets the "accumulate" attribute
     */
    void setAccumulate(org.w3.x2001.smil20.AnimatePrototype.Accumulate.Enum accumulate);

    /**
     * Sets (as xml) the "accumulate" attribute
     */
    void xsetAccumulate(org.w3.x2001.smil20.AnimatePrototype.Accumulate accumulate);

    /**
     * Unsets the "accumulate" attribute
     */
    void unsetAccumulate();

    /**
     * Gets the "to" attribute
     */
    java.lang.String getTo();

    /**
     * Gets (as xml) the "to" attribute
     */
    org.apache.xmlbeans.XmlString xgetTo();

    /**
     * True if has "to" attribute
     */
    boolean isSetTo();

    /**
     * Sets the "to" attribute
     */
    void setTo(java.lang.String to);

    /**
     * Sets (as xml) the "to" attribute
     */
    void xsetTo(org.apache.xmlbeans.XmlString to);

    /**
     * Unsets the "to" attribute
     */
    void unsetTo();

    /**
     * Gets the "from" attribute
     */
    java.lang.String getFrom();

    /**
     * Gets (as xml) the "from" attribute
     */
    org.apache.xmlbeans.XmlString xgetFrom();

    /**
     * True if has "from" attribute
     */
    boolean isSetFrom();

    /**
     * Sets the "from" attribute
     */
    void setFrom(java.lang.String from);

    /**
     * Sets (as xml) the "from" attribute
     */
    void xsetFrom(org.apache.xmlbeans.XmlString from);

    /**
     * Unsets the "from" attribute
     */
    void unsetFrom();

    /**
     * Gets the "by" attribute
     */
    java.lang.String getBy();

    /**
     * Gets (as xml) the "by" attribute
     */
    org.apache.xmlbeans.XmlString xgetBy();

    /**
     * True if has "by" attribute
     */
    boolean isSetBy();

    /**
     * Sets the "by" attribute
     */
    void setBy(java.lang.String by);

    /**
     * Sets (as xml) the "by" attribute
     */
    void xsetBy(org.apache.xmlbeans.XmlString by);

    /**
     * Unsets the "by" attribute
     */
    void unsetBy();

    /**
     * Gets the "values" attribute
     */
    java.lang.String getValues();

    /**
     * Gets (as xml) the "values" attribute
     */
    org.apache.xmlbeans.XmlString xgetValues();

    /**
     * True if has "values" attribute
     */
    boolean isSetValues();

    /**
     * Sets the "values" attribute
     */
    void setValues(java.lang.String values);

    /**
     * Sets (as xml) the "values" attribute
     */
    void xsetValues(org.apache.xmlbeans.XmlString values);

    /**
     * Unsets the "values" attribute
     */
    void unsetValues();

    /**
     * An XML attributeType(@).
     *
     * This is an atomic type that is a restriction of org.w3.x2001.smil20.AnimatePrototype$AttributeType.
     */
    public interface AttributeType extends org.apache.xmlbeans.XmlString
    {
        public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType)
            org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(AttributeType.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s6E28D279B6C224D74769DB8B98AF1665").resolveHandle("attributetype50acattrtype");

        org.apache.xmlbeans.StringEnumAbstractBase enumValue();
        void set(org.apache.xmlbeans.StringEnumAbstractBase e);

        static final Enum XML = Enum.forString("XML");
        static final Enum CSS = Enum.forString("CSS");
        static final Enum AUTO = Enum.forString("auto");

        static final int INT_XML = Enum.INT_XML;
        static final int INT_CSS = Enum.INT_CSS;
        static final int INT_AUTO = Enum.INT_AUTO;

        /**
         * Enumeration value class for org.w3.x2001.smil20.AnimatePrototype$AttributeType.
         * These enum values can be used as follows:
         *

         * enum.toString(); // returns the string value of the enum
         * enum.intValue(); // returns an int value, useful for switches
         * // e.g., case Enum.INT_XML
         * Enum.forString(s); // returns the enum value for a string
         * Enum.forInt(i); // returns the enum value for an int
         *

         * Enumeration objects are immutable singleton objects that
         * can be compared using == object equality. They have no
         * public constructor. See the constants defined within this
         * class for all the valid values.
         */
        static final class Enum extends org.apache.xmlbeans.StringEnumAbstractBase
        {
            /**
             * Returns the enum value for a string, or null if none.
             */
            public static Enum forString(java.lang.String s)
                { return (Enum)table.forString(s); }
            /**
             * Returns the enum value corresponding to an int, or null if none.
             */
            public static Enum forInt(int i)
                { return (Enum)table.forInt(i); }

            private Enum(java.lang.String s, int i)
                { super(s, i); }

            static final int INT_XML = 1;
            static final int INT_CSS = 2;
            static final int INT_AUTO = 3;

            public static final org.apache.xmlbeans.StringEnumAbstractBase.Table table =
                new org.apache.xmlbeans.StringEnumAbstractBase.Table
            (
                new Enum[]
                {
                    new Enum("XML", INT_XML),
                    new Enum("CSS", INT_CSS),
                    new Enum("auto", INT_AUTO),
                }
            );
            private static final long serialVersionUID = 1L;
            private java.lang.Object readResolve() { return forInt(intValue()); }
        }

        /**
         * A factory class with static methods for creating instances
         * of this type.
         */

        public static final class Factory
        {
            public static org.w3.x2001.smil20.AnimatePrototype.AttributeType newValue(java.lang.Object obj) {
              return (org.w3.x2001.smil20.AnimatePrototype.AttributeType) type.newValue( obj ); }

            public static org.w3.x2001.smil20.AnimatePrototype.AttributeType newInstance() {
              return (org.w3.x2001.smil20.AnimatePrototype.AttributeType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); }

            public static org.w3.x2001.smil20.AnimatePrototype.AttributeType newInstance(org.apache.xmlbeans.XmlOptions options) {
              return (org.w3.x2001.smil20.AnimatePrototype.AttributeType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); }

            private Factory() { } // No instance of this class allowed
        }
    }

    /**
     * An XML additive(@).
     *
     * This is an atomic type that is a restriction of org.w3.x2001.smil20.AnimatePrototype$Additive.
     */
    public interface Additive extends org.apache.xmlbeans.XmlString
    {
        public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType)
            org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(Additive.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s6E28D279B6C224D74769DB8B98AF1665").resolveHandle("additive33baattrtype");

        org.apache.xmlbeans.StringEnumAbstractBase enumValue();
        void set(org.apache.xmlbeans.StringEnumAbstractBase e);

        static final Enum REPLACE = Enum.forString("replace");
        static final Enum SUM = Enum.forString("sum");

        static final int INT_REPLACE = Enum.INT_REPLACE;
        static final int INT_SUM = Enum.INT_SUM;

        /**
         * Enumeration value class for org.w3.x2001.smil20.AnimatePrototype$Additive.
         * These enum values can be used as follows:
         *

         * enum.toString(); // returns the string value of the enum
         * enum.intValue(); // returns an int value, useful for switches
         * // e.g., case Enum.INT_REPLACE
         * Enum.forString(s); // returns the enum value for a string
         * Enum.forInt(i); // returns the enum value for an int
         *

         * Enumeration objects are immutable singleton objects that
         * can be compared using == object equality. They have no
         * public constructor. See the constants defined within this
         * class for all the valid values.
         */
        static final class Enum extends org.apache.xmlbeans.StringEnumAbstractBase
        {
            /**
             * Returns the enum value for a string, or null if none.
             */
            public static Enum forString(java.lang.String s)
                { return (Enum)table.forString(s); }
            /**
             * Returns the enum value corresponding to an int, or null if none.
             */
            public static Enum forInt(int i)
                { return (Enum)table.forInt(i); }

            private Enum(java.lang.String s, int i)
                { super(s, i); }

            static final int INT_REPLACE = 1;
            static final int INT_SUM = 2;

            public static final org.apache.xmlbeans.StringEnumAbstractBase.Table table =
                new org.apache.xmlbeans.StringEnumAbstractBase.Table
            (
                new Enum[]
                {
                    new Enum("replace", INT_REPLACE),
                    new Enum("sum", INT_SUM),
                }
            );
            private static final long serialVersionUID = 1L;
            private java.lang.Object readResolve() { return forInt(intValue()); }
        }

        /**
         * A factory class with static methods for creating instances
         * of this type.
         */

        public static final class Factory
        {
            public static org.w3.x2001.smil20.AnimatePrototype.Additive newValue(java.lang.Object obj) {
              return (org.w3.x2001.smil20.AnimatePrototype.Additive) type.newValue( obj ); }

            public static org.w3.x2001.smil20.AnimatePrototype.Additive newInstance() {
              return (org.w3.x2001.smil20.AnimatePrototype.Additive) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); }

            public static org.w3.x2001.smil20.AnimatePrototype.Additive newInstance(org.apache.xmlbeans.XmlOptions options) {
              return (org.w3.x2001.smil20.AnimatePrototype.Additive) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); }

            private Factory() { } // No instance of this class allowed
        }
    }

    /**
     * An XML accumulate(@).
     *
     * This is an atomic type that is a restriction of org.w3.x2001.smil20.AnimatePrototype$Accumulate.
     */
    public interface Accumulate extends org.apache.xmlbeans.XmlString
    {
        public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType)
            org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(Accumulate.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s6E28D279B6C224D74769DB8B98AF1665").resolveHandle("accumulate94d0attrtype");

        org.apache.xmlbeans.StringEnumAbstractBase enumValue();
        void set(org.apache.xmlbeans.StringEnumAbstractBase e);

        static final Enum NONE = Enum.forString("none");
        static final Enum SUM = Enum.forString("sum");

        static final int INT_NONE = Enum.INT_NONE;
        static final int INT_SUM = Enum.INT_SUM;

        /**
         * Enumeration value class for org.w3.x2001.smil20.AnimatePrototype$Accumulate.
         * These enum values can be used as follows:
         *

         * enum.toString(); // returns the string value of the enum
         * enum.intValue(); // returns an int value, useful for switches
         * // e.g., case Enum.INT_NONE
         * Enum.forString(s); // returns the enum value for a string
         * Enum.forInt(i); // returns the enum value for an int
         *

         * Enumeration objects are immutable singleton objects that
         * can be compared using == object equality. They have no
         * public constructor. See the constants defined within this
         * class for all the valid values.
         */
        static final class Enum extends org.apache.xmlbeans.StringEnumAbstractBase
        {
            /**
             * Returns the enum value for a string, or null if none.
             */
            public static Enum forString(java.lang.String s)
                { return (Enum)table.forString(s); }
            /**
             * Returns the enum value corresponding to an int, or null if none.
             */
            public static Enum forInt(int i)
                { return (Enum)table.forInt(i); }

            private Enum(java.lang.String s, int i)
                { super(s, i); }

            static final int INT_NONE = 1;
            static final int INT_SUM = 2;

            public static final org.apache.xmlbeans.StringEnumAbstractBase.Table table =
                new org.apache.xmlbeans.StringEnumAbstractBase.Table
            (
                new Enum[]
                {
                    new Enum("none", INT_NONE),
                    new Enum("sum", INT_SUM),
                }
            );
            private static final long serialVersionUID = 1L;
            private java.lang.Object readResolve() { return forInt(intValue()); }
        }

        /**
         * A factory class with static methods for creating instances
         * of this type.
         */

        public static final class Factory
        {
            public static org.w3.x2001.smil20.AnimatePrototype.Accumulate newValue(java.lang.Object obj) {
              return (org.w3.x2001.smil20.AnimatePrototype.Accumulate) type.newValue( obj ); }

            public static org.w3.x2001.smil20.AnimatePrototype.Accumulate newInstance() {
              return (org.w3.x2001.smil20.AnimatePrototype.Accumulate) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); }

            public static org.w3.x2001.smil20.AnimatePrototype.Accumulate newInstance(org.apache.xmlbeans.XmlOptions options) {
              return (org.w3.x2001.smil20.AnimatePrototype.Accumulate) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); }

            private Factory() { } // No instance of this class allowed
        }
    }

    /**
     * A factory class with static methods for creating instances
     * of this type.
     */

    public static final class Factory
    {
        public static org.w3.x2001.smil20.AnimatePrototype newInstance() {
          return (org.w3.x2001.smil20.AnimatePrototype) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); }

        public static org.w3.x2001.smil20.AnimatePrototype newInstance(org.apache.xmlbeans.XmlOptions options) {
          return (org.w3.x2001.smil20.AnimatePrototype) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); }

        /** @param xmlAsString the string value to parse */
        public static org.w3.x2001.smil20.AnimatePrototype parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException {
          return (org.w3.x2001.smil20.AnimatePrototype) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, null ); }

        public static org.w3.x2001.smil20.AnimatePrototype parse(java.lang.String xmlAsString, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
          return (org.w3.x2001.smil20.AnimatePrototype) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, options ); }

        /** @param file the file from which to load an xml document */
        public static org.w3.x2001.smil20.AnimatePrototype parse(java.io.File file) throws org.apache.xmlbeans.XmlException, java.io.IOException {
          return (org.w3.x2001.smil20.AnimatePrototype) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, null ); }

        public static org.w3.x2001.smil20.AnimatePrototype parse(java.io.File file, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
          return (org.w3.x2001.smil20.AnimatePrototype) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, options ); }

        public static org.w3.x2001.smil20.AnimatePrototype parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException {
          return (org.w3.x2001.smil20.AnimatePrototype) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, null ); }

        public static org.w3.x2001.smil20.AnimatePrototype parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
          return (org.w3.x2001.smil20.AnimatePrototype) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, options ); }

        public static org.w3.x2001.smil20.AnimatePrototype parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException {
          return (org.w3.x2001.smil20.AnimatePrototype) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, null ); }

        public static org.w3.x2001.smil20.AnimatePrototype parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
          return (org.w3.x2001.smil20.AnimatePrototype) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, options ); }

        public static org.w3.x2001.smil20.AnimatePrototype parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException {
          return (org.w3.x2001.smil20.AnimatePrototype) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, null ); }

        public static org.w3.x2001.smil20.AnimatePrototype parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
          return (org.w3.x2001.smil20.AnimatePrototype) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, options ); }

        public static org.w3.x2001.smil20.AnimatePrototype parse(javax.xml.stream.XMLStreamReader sr) throws org.apache.xmlbeans.XmlException {
          return (org.w3.x2001.smil20.AnimatePrototype) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, null ); }

        public static org.w3.x2001.smil20.AnimatePrototype parse(javax.xml.stream.XMLStreamReader sr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
          return (org.w3.x2001.smil20.AnimatePrototype) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, options ); }

        public static org.w3.x2001.smil20.AnimatePrototype parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException {
          return (org.w3.x2001.smil20.AnimatePrototype) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, null ); }

        public static org.w3.x2001.smil20.AnimatePrototype parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
          return (org.w3.x2001.smil20.AnimatePrototype) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, options ); }

        /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
        @Deprecated
        public static org.w3.x2001.smil20.AnimatePrototype parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
          return (org.w3.x2001.smil20.AnimatePrototype) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, null ); }

        /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
        @Deprecated
        public static org.w3.x2001.smil20.AnimatePrototype parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
          return (org.w3.x2001.smil20.AnimatePrototype) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, options ); }

        /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
        @Deprecated
        public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
          return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); }

        /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
        @Deprecated
        public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
          return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); }

        private Factory() { } // No instance of this class allowed
    }
}


text:
'use strict';

/* This module is the event handler for the bot, client events are passed onto here from bot.js for
reactions to be sorted */

const bootServers = require('./botData/bootServers.js');
const commands = require('./commands/commands.js');
const data = require('./botData/data.js');
const database = require('./database/database.js');
const directMessages = require('./directMessages.js');
const log = require('./logger.js')(module);

module.exports = {
    disconnect() {
        database.disconnect();
    },

    message(message) {
        /* Admin section (perform admin tasks first) */

        /* Filtering Section */

        // Ignore bot messages
        if (message.author.bot) { log.silly('Ignored bot message'); return false; }

        // Filter out and handle DMs
        if (message.channel.type === 'dm' || message.channel.type === 'group') {
            return directMessages.execute(message);
        }

        /* Commands Section */

        // Ignore message if there is not a valid command prefix
        if (!commands.prefix(message)) {
            log.silly('Ignored message without command prefix');
            return false;
        }

        // Pass message to be checked for a valid command
        const cmd = commands.filter(message);
        if (!cmd) {
            log.silly('Ignored message without valid command');
            return false;
        }

        // Message does contain a valid command, but check that the command should be executed first
        if (!commands.check(message)) {
            log.silly('Commands check returned false, ignoring message');
            return false;
        }

        return commands.commandCall(cmd, message);
    },

    ready(client) {
        const booted = data.getBooted();

        // If this is the first ready event, perform boot functions
        if (!booted) {
            bootServers.execute(client);
            database.boot(client);
            data.setStarted();
        }

        data.setClient(client);

        database.ready();
    },

    reconnecting() {
    },

    warn() {

    },
};

redpajama_set_name: RedPajamaGithub


text:
set a json value quickly

SJSON is a Go package that provides a [very fast](#performance) and simple way to set a value in a json document.
For quickly retrieving json values check out [GJSON](https://github.com/tidwall/gjson).

For a command line interface check out [JJ](https://github.com/tidwall/jj).

Getting Started
===============

Installing
----------

To start using SJSON, install Go and run `go get`:

```sh
$ go get -u github.com/tidwall/sjson
```

This will retrieve the library.

Set a value
-----------
Set sets the value for the specified path.
A path is in dot syntax, such as "name.last" or "age".
This function expects that the json is well-formed and validated.
Invalid json will not panic, but it may return back unexpected results.
Invalid paths may return an error.

```go
package main

import "github.com/tidwall/sjson"

const json = `{"name":{"first":"Janet","last":"Prichard"},"age":47}`

func main() {
	value, _ := sjson.Set(json, "name.last", "Anderson")
	println(value)
}
```

This will print:

```json
{"name":{"first":"Janet","last":"Anderson"},"age":47}
```

Path syntax
-----------

A path is a series of keys separated by a dot.
The dot and colon characters can be escaped with ``\``.

```json
{
  "name": {"first": "Tom", "last": "Anderson"},
  "age":37,
  "children": ["Sara","Alex","Jack"],
  "fav.movie": "Deer Hunter",
  "friends": [
	{"first": "James", "last": "Murphy"},
	{"first": "Roger", "last": "Craig"}
  ]
}
```
```
"name.last"          >> "Anderson"
"age"                >> 37
"children.1"         >> "Alex"
"friends.1.last"     >> "Craig"
```

The `-1` key can be used to append a value to an existing array:

```
"children.-1"  >> appends a new value to the end of the children array
```

Normally number keys are used to modify arrays, but it's possible to force a numeric object key by using the colon character:

```json
{
  "users":{
    "2313":{"name":"Sara"},
    "7839":{"name":"Andy"}
  }
}
```

A colon path would look like:

```
"users.:2313.name"    >> "Sara"
```

Supported types
---------------

Pretty much any type is supported:

```go
sjson.Set(`{"key":true}`, "key", nil)
sjson.Set(`{"key":true}`, "key", false)
sjson.Set(`{"key":true}`, "key", 1)
sjson.Set(`{"key":true}`, "key", 10.5)
sjson.Set(`{"key":true}`, "key", "hello")
sjson.Set(`{"key":true}`, "key", []string{"hello", "world"})
sjson.Set(`{"key":true}`, "key", map[string]interface{}{"hello":"world"})
```

When a type is not recognized, SJSON will fallback to the `encoding/json` Marshaller.

Examples
--------

Set a value from empty document:
```go
value, _ := sjson.Set("", "name", "Tom")
println(value)

// Output:
// {"name":"Tom"}
```

Set a nested value from empty document:
```go
value, _ := sjson.Set("", "name.last", "Anderson")
println(value)

// Output:
// {"name":{"last":"Anderson"}}
```

Set a new value:
```go
value, _ := sjson.Set(`{"name":{"last":"Anderson"}}`, "name.first", "Sara")
println(value)

// Output:
// {"name":{"first":"Sara","last":"Anderson"}}
```

Update an existing value:
```go
value, _ := sjson.Set(`{"name":{"last":"Anderson"}}`, "name.last", "Smith")
println(value)

// Output:
// {"name":{"last":"Smith"}}
```

Set a new array value:
```go
value, _ := sjson.Set(`{"friends":["Andy","Carol"]}`, "friends.2", "Sara")
println(value)

// Output:
// {"friends":["Andy","Carol","Sara"]
```

Append an array value by using the `-1` key in a path:
```go
value, _ := sjson.Set(`{"friends":["Andy","Carol"]}`, "friends.-1", "Sara")
println(value)

// Output:
// {"friends":["Andy","Carol","Sara"]
```

Append an array value that is past the end:
```go
value, _ := sjson.Set(`{"friends":["Andy","Carol"]}`, "friends.4", "Sara")
println(value)

// Output:
// {"friends":["Andy","Carol",null,null,"Sara"]
```

Delete a value:
```go
value, _ := sjson.Delete(`{"name":{"first":"Sara","last":"Anderson"}}`, "name.first")
println(value)

// Output:
// {"name":{"last":"Anderson"}}
```

Delete an array value:
```go
value, _ := sjson.Delete(`{"friends":["Andy","Carol"]}`, "friends.1")
println(value)

// Output:
// {"friends":["Andy"]}
```

Delete the last array value:
```go
value, _ := sjson.Delete(`{"friends":["Andy","Carol"]}`, "friends.-1")
println(value)

// Output:
// {"friends":["Andy"]}
```

## Performance

Benchmarks of SJSON alongside [encoding/json](https://golang.org/pkg/encoding/json/),
[ffjson](https://github.com/pquerna/ffjson),
[EasyJSON](https://github.com/mailru/easyjson),
and [Gabs](https://github.com/Jeffail/gabs)

```
Benchmark_SJSON-8                  	 3000000	       805 ns/op	    1077 B/op	       3 allocs/op
Benchmark_SJSON_ReplaceInPlace-8   	 3000000	       449 ns/op	       0 B/op	       0 allocs/op
Benchmark_JSON_Map-8               	  300000	     21236 ns/op	    6392 B/op	     150 allocs/op
Benchmark_JSON_Struct-8            	  300000	     14691 ns/op	    1789 B/op	      24 allocs/op
Benchmark_Gabs-8                   	  300000	     21311 ns/op	    6752 B/op	     150 allocs/op
Benchmark_FFJSON-8                 	  300000	     17673 ns/op	    3589 B/op	      47 allocs/op
Benchmark_EasyJSON-8               	 1500000	      3119 ns/op	    1061 B/op	      13 allocs/op
```

JSON document used:

```json
{
  "widget": {
    "debug": "on",
    "window": {
      "title": "Sample Konfabulator Widget",
      "name": "main_window",
      "width": 500,
      "height": 500
    },
    "image": {
      "src": "Images/Sun.png",
      "hOffset": 250,
      "vOffset": 250,
      "alignment": "center"
    },
    "text": {
      "data": "Click Here",
      "size": 36,
      "style": "bold",
      "vOffset": 100,
      "alignment": "center",
      "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
    }
  }
}
```

Each operation was rotated though one of the following search paths:

```
widget.window.name
widget.image.hOffset
widget.text.onMouseUp
```

*These benchmarks were run on a MacBook Pro 15" 2.8 GHz Intel Core i7 using Go 1.7 and can be be found [here](https://github.com/tidwall/sjson-benchmarks)*.

## Contact
Josh Baker [@tidwall](http://twitter.com/tidwall)

## License

SJSON source code is available under the MIT [License](/LICENSE).


text:
<!DOCTYPE html>

Tests that motion path animations prevent a future transform animation from being composited.

The two squares should make equivalent movements from left to right and back to left. They need not be perfectly in time.


text:
struct tcp_info;

namespace Envoy {
namespace Extensions {
namespace TransportSockets {
namespace TcpStats {

#define ALL_TCP_STATS(COUNTER, GAUGE, HISTOGRAM)                                                   \
  COUNTER(cx_tx_segments)                                                                          \
  COUNTER(cx_rx_segments)                                                                          \
  COUNTER(cx_tx_data_segments)                                                                     \
  COUNTER(cx_rx_data_segments)                                                                     \
  COUNTER(cx_tx_retransmitted_segments)                                                            \
  GAUGE(cx_tx_unsent_bytes, Accumulate)                                                            \
  GAUGE(cx_tx_unacked_segments, Accumulate)                                                        \
  HISTOGRAM(cx_tx_percent_retransmitted_segments, Percent)                                         \
  HISTOGRAM(cx_rtt_us, Microseconds)                                                               \
  HISTOGRAM(cx_rtt_variance_us, Microseconds)

struct TcpStats {
  ALL_TCP_STATS(GENERATE_COUNTER_STRUCT, GENERATE_GAUGE_STRUCT, GENERATE_HISTOGRAM_STRUCT)
};

class Config {
public:
  Config(const envoy::extensions::transport_sockets::tcp_stats::v3::Config& config_proto,
         Stats::Scope& scope);

  TcpStats stats_;
  const absl::optional<std::chrono::milliseconds> update_period_;

private:
  TcpStats generateStats(Stats::Scope& scope);
};

using ConfigConstSharedPtr = std::shared_ptr<const Config>;

class TcpStatsSocket : public TransportSockets::PassthroughSocket,
                       Logger::Loggable<Logger::Id::connection> {
public:
  TcpStatsSocket(ConfigConstSharedPtr config, Network::TransportSocketPtr inner_socket);

  // Network::TransportSocket
  void setTransportSocketCallbacks(Network::TransportSocketCallbacks& callbacks) override;
  void onConnected() override;
  void closeSocket(Network::ConnectionEvent event) override;

private:
  absl::optional<struct tcp_info> querySocketInfo();
  void recordStats();

  const ConfigConstSharedPtr config_;
  Network::TransportSocketCallbacks* callbacks_{};
  Event::TimerPtr timer_;

  uint32_t last_cx_tx_segments_{};
  uint32_t last_cx_rx_segments_{};
  uint32_t last_cx_tx_data_segments_{};
  uint32_t last_cx_rx_data_segments_{};
  uint32_t last_cx_tx_retransmitted_segments_{};
  uint32_t last_cx_tx_unsent_bytes_{};
  uint32_t last_cx_tx_unacked_segments_{};
};

} // namespace TcpStats
} // namespace TransportSockets
} // namespace Extensions
} // namespace Envoy

#endif // defined(__linux__)


text:
package com.hazelcast.client.impl.protocol.codec;

import com.hazelcast.client.impl.protocol.ClientMessage;
import com.hazelcast.client.impl.protocol.Generated;
import com.hazelcast.client.impl.protocol.codec.builtin.*;
import com.hazelcast.client.impl.protocol.codec.custom.*;

import javax.annotation.Nullable;

import static com.hazelcast.client.impl.protocol.ClientMessage.*;
import static com.hazelcast.client.impl.protocol.codec.builtin.FixedSizeTypesCodec.*;

/*
 * This file is auto-generated by the Hazelcast Client Protocol Code Generator.
 * To change this file, edit the templates or the protocol
 * definitions on the https://github.com/hazelcast/hazelcast-client-protocol
 * and regenerate it.
 */

/**
 * Return true if this collection contains all of the elements in the specified collection.
 */
@Generated("640655530da67570c51929efd0a242e5")
public final class QueueContainsAllCodec {
    //hex: 0x030C00
    public static final int REQUEST_MESSAGE_TYPE = 199680;
    //hex: 0x030C01
    public static final int RESPONSE_MESSAGE_TYPE = 199681;
    private static final int REQUEST_INITIAL_FRAME_SIZE = PARTITION_ID_FIELD_OFFSET + INT_SIZE_IN_BYTES;
    private static final int RESPONSE_RESPONSE_FIELD_OFFSET = RESPONSE_BACKUP_ACKS_FIELD_OFFSET + BYTE_SIZE_IN_BYTES;
    private static final int RESPONSE_INITIAL_FRAME_SIZE = RESPONSE_RESPONSE_FIELD_OFFSET + BOOLEAN_SIZE_IN_BYTES;

    private QueueContainsAllCodec() {
    }

    @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({"URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD"})
    public static class RequestParameters {

        /**
         * Name of the Queue
         */
        public java.lang.String name;

        /**
         * Collection to be checked for containment in this collection
         */
        public java.util.List<com.hazelcast.internal.serialization.Data> dataList;
    }

    public static ClientMessage encodeRequest(java.lang.String name, java.util.Collection<com.hazelcast.internal.serialization.Data> dataList) {
        ClientMessage clientMessage = ClientMessage.createForEncode();
        clientMessage.setRetryable(false);
        clientMessage.setOperationName("Queue.ContainsAll");
        ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[REQUEST_INITIAL_FRAME_SIZE], UNFRAGMENTED_MESSAGE);
        encodeInt(initialFrame.content, TYPE_FIELD_OFFSET, REQUEST_MESSAGE_TYPE);
        encodeInt(initialFrame.content, PARTITION_ID_FIELD_OFFSET, -1);
        clientMessage.add(initialFrame);
        StringCodec.encode(clientMessage, name);
        ListMultiFrameCodec.encode(clientMessage, dataList, DataCodec::encode);
        return clientMessage;
    }

    public static QueueContainsAllCodec.RequestParameters decodeRequest(ClientMessage clientMessage) {
        ClientMessage.ForwardFrameIterator iterator = clientMessage.frameIterator();
        RequestParameters request = new RequestParameters();
        //empty initial frame
        iterator.next();
        request.name = StringCodec.decode(iterator);
        request.dataList = ListMultiFrameCodec.decode(iterator, DataCodec::decode);
        return request;
    }

    @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({"URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD"})
    public static class ResponseParameters {

        /**
         * <tt>true</tt> if this collection contains all of the elements in the specified collection
         */
        public boolean response;
    }

    public static ClientMessage encodeResponse(boolean response) {
        ClientMessage clientMessage = ClientMessage.createForEncode();
        ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[RESPONSE_INITIAL_FRAME_SIZE], UNFRAGMENTED_MESSAGE);
        encodeInt(initialFrame.content, TYPE_FIELD_OFFSET, RESPONSE_MESSAGE_TYPE);
        encodeBoolean(initialFrame.content, RESPONSE_RESPONSE_FIELD_OFFSET, response);
        clientMessage.add(initialFrame);

        return clientMessage;
    }

    public static QueueContainsAllCodec.ResponseParameters decodeResponse(ClientMessage clientMessage) {
        ClientMessage.ForwardFrameIterator iterator = clientMessage.frameIterator();
        ResponseParameters response = new ResponseParameters();
        ClientMessage.Frame initialFrame = iterator.next();
        response.response = decodeBoolean(initialFrame.content, RESPONSE_RESPONSE_FIELD_OFFSET);
        return response;
    }

}


text:
import React from 'react'
import { Route, Switch } from 'react-router-dom'
import BlogFilters from './blogFilters.js'
import BlogPostList from './blogPostList.js'
import BlogPost from './blogPost.js'

export default class Blog extends React.Component {
  render () {
    return (
      <div>
        <Switch>
          <Route path='/blog/filters' exact component={BlogFilters} />
          <Route path='/blog/posted/:year' component={BlogPostList} />
          <Route path='/blog/tagged/:tag' component={BlogPostList} />
          <Route path='/blog/page/:page' component={BlogPostList} />
          <Route path='/page/:page' component={BlogPostList} />
          <Route path='/blog/posted/:year/page/:page' component={BlogPostList} />
          <Route path='/blog/tagged/:tag/page/:page' component={BlogPostList} />
          <Route path='/blog/:id/:slug' component={BlogPost} />
        </Switch>
      </div>)
  }
}


text:
<?php

namespace Symfony\Cmf\Bundle\CoreBundle\Admin\Extension;

use Sonata\AdminBundle\Admin\AdminExtension;
use Sonata\AdminBundle\Form\FormMapper;

/**
 * Admin extension to add publish workflow time period fields for models
 * implementing PublishTimePeriodInterface.
 *
 * @author Daniel Leech <daniel@dantleech.com>
 */
class PublishTimePeriodExtension extends AdminExtension
{
    /**
     * @var string
     */
    protected $formGroup;

    /**
     * @param string $formGroup - group to use for form mapper
     */
    public function __construct($formGroup = 'form.group_publish_workflow')
    {
        $this->formGroup = $formGroup;
    }

    /**
     * {@inheritDoc}
     */
    public function configureFormFields(FormMapper $formMapper)
    {
        $dateOptions = array(
            'empty_value' => '',
            'required' => false,
        );

        $formMapper->with($this->formGroup, array(
            'translation_domain' => 'CmfCoreBundle',
            ))
            ->add('publish_start_date', 'date', $dateOptions, array(
                'help' => 'form.help_publish_start_date',
            ))
            ->add('publish_end_date', 'date', $dateOptions, array(
                'help' => 'form.help_publish_end_date',
            ))
            ->end();
    }
}


text:
package org.keycloak.validate.validators;

import java.util.Collection;

import org.keycloak.validate.SimpleValidator;
import org.keycloak.validate.ValidationContext;
import org.keycloak.validate.ValidationError;
import org.keycloak.validate.ValidatorConfig;

/**
 * Validate that value exists and is not empty nor blank. Supports String and collection of Strings as input. For
 * collection of Strings input has to contain at least one element and it have to be non-blank to satisfy this
 * validation. If collection contains something else than String, or if even one String in it is blank, then this
 * validation fails.
 *
 * @see NotEmptyValidator
 */
public class NotBlankValidator implements SimpleValidator {

    public static final String ID = "blank";

    public static final String MESSAGE_BLANK = "error-invalid-blank";

    public static final NotBlankValidator INSTANCE = new NotBlankValidator();

    private NotBlankValidator() {
    }

    @Override
    public String getId() {
        return ID;
    }

    @Override
    public ValidationContext validate(Object input, String inputHint, ValidationContext context, ValidatorConfig config) {

        if (input == null) {
            context.addError(new ValidationError(ID, inputHint, MESSAGE_BLANK, input));
        } else if (input instanceof String) {
            validateStringValue((String) input, inputHint, context, config);
        } else if (input instanceof Collection) {
            @SuppressWarnings("unchecked")
            Collection<Object> values = (Collection<Object>) input;
            if (!values.isEmpty()) {
                for (Object value : values) {
                    if (!(value instanceof String)) {
                        context.addError(new ValidationError(getId(), inputHint, ValidationError.MESSAGE_INVALID_VALUE, input));
                        return context;
                    } else if (!validateStringValue((String) value, inputHint, context, config)) {
                        return context;
                    }
                }
            } else {
                context.addError(new ValidationError(ID, inputHint, MESSAGE_BLANK, input));
            }
        } else {
            context.addError(new ValidationError(ID, inputHint, ValidationError.MESSAGE_INVALID_VALUE, input));
        }

        return context;
    }

    protected boolean validateStringValue(String value, String inputHint, ValidationContext context, ValidatorConfig config) {
        if (value == null || value.trim().length() == 0) {
            context.addError(new ValidationError(ID, inputHint, MESSAGE_BLANK, value));
            return false;
        }
        return true;
    }
}


text:
"""
Aqara Gateway

Gateway abstraction

Features:
- Call discovery
- Persist list of sensors
- Control gateway lights

"""

import json
import logging
import binascii

from Crypto.Cipher import AES
from pydispatch import dispatcher
from aqara.device import (create_device, AqaraBaseDevice)
from aqara.const import (
    AQARA_ENCRYPT_IV,
    AQARA_DEVICE_GATEWAY,
    AQARA_MID_STOP,
    AQARA_EVENT_NEW_DEVICE,
    AQARA_DATA_RGB,
    AQARA_DATA_ILLUMINATION
)

_LOGGER = logging.getLogger(__name__)

class AqaraGateway(AqaraBaseDevice):
    """Aqara Gateway implementation."""
    def __init__(self, client, sid, addr, secret):
        super().__init__(AQARA_DEVICE_GATEWAY, self, sid)
        self._client = client
        self._addr = addr

        # enable encryption if secret is set
        self._secret = secret
        if secret != None:
            _LOGGER.info("Encryption enabled for gateway %s", sid)
        else:
            _LOGGER.info("Encryption disabled for gateway %s", sid)
        self._token = None
        self._rgbw = 0
        self._illumination = 0
        self._devices = {}
        self._devices[sid] = self

    @property
    def devices(self):
        """property: devices"""
        return self._devices

    @property
    def addr(self):
        """property: addr"""
        return self._addr

    @property
    def rgbw(self):
        """property: rgbw"""
        return self._rgbw

    @property
    def illumination(self):
        """property: illumination"""
        return self._illumination

    def connect(self):
        """Start the gateway"""
        self.discover_devices()
        self.read_device(self._sid)

    def discover_devices(self):
        """discover devices attached to this gateway"""
        self.log_info('discovering devices...')
        self._client.discover_devices(self._addr)

    def read_device(self, sid):
        """force read the value of a device attached to this gateway"""
        self._client.read_device(self._addr, sid)

    def write_device(self, device, data, meta):
        """write data to device"""
        if self._secret != None:
            data["key"] = self._make_key()
        self._client.write_device(self._addr, device.model, device.sid, data, meta)

    def set_light(self, rgbw):
        """Set gateway light (rgbw)"""
        self._rgbw = rgbw
        data = {
            "rgb": rgbw,
        }
        meta = {
            "short_id": 0,
            "key": 8
        }
        self.write_device(self, data, meta)

    def play_ringtone(self, mid):
        """Play ringtone id 'mid'"""
        self._set_mid(mid)

    def stop_ringtone(self):
        """Stop playing ringtone"""
        self._set_mid(AQARA_MID_STOP)

    def on_devices_discovered(self, sids):
        """Callback when devices are discovered"""
        for sid in sids:
            self._client.read_device(self._addr, sid)

    def on_read_ack(self, model, sid, data):
        """Callback on read_ack"""
        self.log_debug("on_read_ack: [{}] {}: {}".format(model, sid, json.dumps(data)))
        if model == "gateway" and sid == self.sid:
            # handle read_ack for gateway itself
            self.on_update(data)
        else:
            # handle read_ack for devices attached to this gateway
            if sid not in self._devices:
                new_device = create_device(self, model, sid)
                self.log_info("added new device {} [{}]".format(sid, model))
                self._devices[sid] = new_device
                dispatcher.send(signal=AQARA_EVENT_NEW_DEVICE, device=new_device, sender=self)
            self._try_update_device(model, sid, data)

    def on_write_ack(self, model, sid, data):
        """Callback on write_ack"""
        self.log_debug("on_write_ack: {} [{}]: {}".format(sid, model, json.dumps(data)))
        if model == "gateway" and sid == self.sid:
            # handle write_ack for gateway
            self.on_update(data)

    def on_device_report(self, model, sid, data):
        """Callback on report"""
        self.log_debug("on_report: {} [{}]: {}".format(sid, model, json.dumps(data)))
        self._try_update_device(model, sid, data)

    def on_device_heartbeat(self, model, sid, data, gw_token):
        """Callback on heartbeat"""
        self.log_debug("on_heartbeat: {} [{}]: {}".format(sid, model, json.dumps(data)))
        if sid == self._sid:
            # handle as gateway heartbeat
            self._token = gw_token
        else:
            # handle as device heartbeat
            self._try_heartbeat_device(model, sid, data)

    def do_update(self, data):
        if AQARA_DATA_RGB in data:
            self._rgbw = data[AQARA_DATA_RGB]
        if AQARA_DATA_ILLUMINATION in data:
            self._illumination = data[AQARA_DATA_ILLUMINATION]

    def subscribe(self, handle_new_device):
        """Subscribe to new device event."""
        dispatcher.connect(handle_new_device, signal=AQARA_EVENT_NEW_DEVICE, sender=self)

    def unsubscribe(self, handle_new_device):
        """Unsubscribe from new device event."""
        dispatcher.disconnect(handle_new_device, signal=AQARA_EVENT_NEW_DEVICE, sender=self)

    def _try_update_device(self, model, sid, data):
        """Update device data"""
        if sid not in self._devices:
            self.log_warning('unregistered device: {} [{}]'.format(model, sid))
            return
        self._devices[sid].on_update(data)

    def _try_heartbeat_device(self, model, sid, data):
        """Send heartbeat to device"""
        if sid not in self._devices:
            self.log_warning('unregistered device: {} [{}]'.format(model, sid))
            return
        self._devices[sid].on_heartbeat(data)

    def _make_key(self):
        if self._secret is None:
            raise Exception('EncyrptionNotEnabledError')
        if self._token is None:
            raise Exception('EncryptionTokenNotAvailableError')
        cipher = AES.new(self._secret, AES.MODE_CBC, IV=AQARA_ENCRYPT_IV)
        return binascii.hexlify(cipher.encrypt(self._token)).decode("utf-8")

    def _set_mid(self, mid):
        data = {
            "mid": mid,
        }
        meta = {
            "short_id": 0,
            "key": 8
        }
        self.write_device(self, data, meta)


text:
@interface DocumentPreviewViewController ()
{
    NSData *data;
}
@property(strong, nonatomic) UIImageView *img;
@end

@implementation DocumentPreviewViewController

- (instancetype)initWithURL:(NSURL *)url
{
    self = [super init];
    if (!self) {
        //TODO: init
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor redColor];
    // Do any additional setup after loading the view.
    queue = dispatch_queue_create("com.signit.wesign.queue", NULL);

    ctx = fz_new_context(NULL, NULL, 25<<20);
    fz_register_document_handlers(ctx);
    screenScale = [[UIScreen mainScreen]scale];
#ifdef CRASHLYTICS_ENABLE
    NSLog(@"Starting Crashlytics");
    [Crashlytics startWithAPIKey:CRASHLYTICS_API_KEY];
#endif
    NSString *file = [[NSBundle mainBundle]pathForResource:@"b" ofType:@"pdf"];
    data = [NSData dataWithContentsOfFile:file];
    self.img = [[UIImageView alloc]initWithFrame:CGRectMake(0, 70, 300, 300)];
    self.img.image = [self getFirstPageWithSize:CGSizeMake(300, 300)];
    [self.view addSubview:self.img];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

+ (void)infomation
{
    NSLog(@"infomation");
}

- (UIImage*)getFirstPageWithSize:(CGSize)imageSize
{
    NSString* outpath = [NSString stringWithFormat:@"%@/Documents/cache.png", NSHomeDirectory()];
    UIImage *img;
    dispatch_sync(queue, ^{
    });
    //渲染第一页
    fz_stream* stream = fz_open_memory(ctx, (unsigned char*)data.bytes, (int)data.length);
    fz_document* doc = fz_open_document_with_stream(ctx, "application/pdf", stream);
    if (fz_needs_password(doc)) //需要密码
    {
        fz_close_document(doc);
        fz_close(stream);
        return nil;
    }
    if (fz_count_pages(doc) == 0) {
        fz_close_document(doc);
        fz_close(stream);
        return nil;
    }
    //load the page, page number starts from zero
    fz_page* page = fz_load_page(doc, 0);

    //calculate a transform, transform contains zooms and rotation
    fz_matrix transform;
    fz_rotate(&transform, 0);
    fz_pre_scale(&transform, 1.0f, 1.0f);

    //calculate page bounds
    fz_rect bounds;
    fz_bound_page(doc, page, &bounds);
    fz_transform_rect(&bounds, &transform);

    //create a blank pixmap to hold the result of rendering.
    fz_irect bbox;
    fz_round_rect(&bbox, &bounds);
    fz_pixmap* pix = fz_new_pixmap_with_bbox(ctx, fz_device_rgb(ctx), &bbox);

    fz_clear_pixmap_with_value(ctx, pix, 0xff);

    //create a draw device with pixmap as its target
    fz_device* dev = fz_new_draw_device(ctx, pix);
    fz_run_page(doc, page, dev, &transform, NULL);
    fz_free_device(dev);

    char* _outpath = malloc(strlen([outpath UTF8String]) + 1);
    strcpy(_outpath, [outpath UTF8String]);
    fz_write_png(ctx, pix, _outpath, 0);
    data = [NSData dataWithContentsOfFile:outpath];
    img = [UIImage imageWithData:data];
    //clean up
    free(_outpath);
    fz_drop_pixmap(ctx, pix);
    fz_free_page(doc, page);
    fz_close_document(doc);
    fz_close(stream);
    return img;
}

@end


text:
package org.springframework.cloud.contract.spec.internal;

import java.util.Objects;

/**
 * @author Marcin Grzejszczak
 */
public class PathBodyMatcher implements BodyMatcher {

	private String path;

	private MatchingTypeValue matchingTypeValue;

	PathBodyMatcher(String path, MatchingTypeValue matchingTypeValue) {
		this.path = path;
		this.matchingTypeValue = matchingTypeValue;
	}

	@Override
	public MatchingType matchingType() {
		return this.matchingTypeValue.getType();
	}

	@Override
	public String path() {
		return this.path;
	}

	@Override
	public Object value() {
		return this.matchingTypeValue.getValue();
	}

	@Override
	public Integer minTypeOccurrence() {
		return this.matchingTypeValue.getMinTypeOccurrence();
	}

	@Override
	public Integer maxTypeOccurrence() {
		return this.matchingTypeValue.getMaxTypeOccurrence();
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) {
			return true;
		}
		if (o == null || getClass() != o.getClass()) {
			return false;
		}
		PathBodyMatcher that = (PathBodyMatcher) o;
		return Objects.equals(path, that.path) && Objects.equals(matchingTypeValue, that.matchingTypeValue);
	}

	@Override
	public int hashCode() {
		return Objects.hash(path, matchingTypeValue);
	}

	@Override
	public String toString() {
		return "PathBodyMatcher{" + "path='" + path + '\'' + ", matchingTypeValue=" + matchingTypeValue + '}';
	}

}


text:
import {PlatformApplication, PlatformTest} from "@tsed/common";
import {PlatformExpress} from "@tsed/platform-express";
import {expect} from "chai";
import Express from "express";
import Sinon from "sinon";
import {stub} from "../../../../../test/helper/tools";

const sandbox = Sinon.createSandbox();

describe("PlatformExpressApplication", () => {
  class TestServer {}

  beforeEach(
    PlatformTest.bootstrap(TestServer, {
      platform: PlatformExpress
    })
  );
  afterEach(() => PlatformTest.reset());

  describe("statics()", () => {
    beforeEach(async () => {
      sandbox.stub(Express, "static");
    });

    afterEach(() => {
      sandbox.restore();
    });

    it("should create a PlatformApplication", async () => {
      const middlewareServeStatic = sandbox.stub();

      stub(Express.static).returns(middlewareServeStatic);

      const app = await PlatformTest.invoke<PlatformApplication>(PlatformApplication);

      sandbox.stub(app, "use");

      app.statics("/path", {
        root: "/publics",
        options: "options"
      });

      expect(Express.static).to.have.been.calledWithExactly(Sinon.match("/publics"), {options: "options"});
      expect(app.use).to.have.been.calledWithExactly("/path", Sinon.match.func);
    });
  });
});


text:
@interface BYBGoodDetailsCell4 ()<WKNavigationDelegate,UIWebViewDelegate>

@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) NSMutableDictionary *heightDic;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, assign) BOOL hasLoad;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIWebView *uiwebView;

@end
@implementation BYBGoodDetailsCell4
- (NSMutableDictionary *)heightDic{
    if (_heightDic == nil) {
        _heightDic = [[NSMutableDictionary alloc]init];
    }
    return _heightDic;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        [self setupUI];
    }
    return self;
}

- (void)setupUI{

    self.label = [JXFactoryTool creatLabel:CGRectZero font:[UIFont systemFontOfSize:15 weight:.3] textColor:BYBTEXTColor2 text:@"商品详情" textAlignment:0];
    [self.contentView addSubview:self.label];
    [self.label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(self.contentView).offset(15);
    }];

    self.lineView = [[UIView alloc]init];
    self.lineView.backgroundColor = BYBTEXTColor0;
    [self.contentView addSubview:self.lineView];
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.label.mas_bottom).offset(15);
        make.right.left.mas_equalTo(self.contentView);
        make.height.mas_equalTo(0.25);
    }];

//    NSString *js = @"document.documentElement.style.webkitUserSelect='none';" ;
//    WKUserScript *script = [[WKUserScript alloc]initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
//
//    NSString *js2 = @"document.documentElement.style.webkitTouchCallout='none';";
//    WKUserScript *script2 = [[WKUserScript alloc]initWithSource:js2 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
//    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
//    [config.userContentController addUserScript:script];
//    [config.userContentController addUserScript:script2];
//
//    self.webView = [[WKWebView alloc]initWithFrame:CGRectZero configuration:config];
//    self.webView.scrollView.scrollEnabled = NO;
//    self.webView.navigationDelegate = self;
//    self.webView.backgroundColor = [UIColor whiteColor];
//    [self.contentView addSubview:self.webView];
//    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(self.lineView.mas_bottom).offset(20);
//        make.right.left.mas_equalTo(self.contentView);
//        make.bottom.mas_equalTo(self.contentView.mas_bottom).offset(-10);
//    }];
//

    self.uiwebView = [[UIWebView alloc]init];
    self.uiwebView.delegate = self;
    self.uiwebView.scalesPageToFit = NO;
    self.uiwebView.scrollView.bounces = NO;
    [self.uiwebView setAutoresizingMask:UIViewAutoresizingNone];
    [self.uiwebView.scrollView setScrollsToTop:NO];
    self.uiwebView.scrollView.scrollEnabled = NO;
    [self.contentView addSubview:self.uiwebView];
    self.uiwebView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(webViewTapAction:)];
    tap.delegate = self;
    tap.cancelsTouchesInView = NO;
    tap.delaysTouchesBegan = YES;
    [self.uiwebView addGestureRecognizer:tap];

    [self.uiwebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.lineView.mas_bottom).offset(20);
        make.right.left.mas_equalTo(self.contentView);
        make.bottom.mas_equalTo(self.contentView.mas_bottom).offset(-10);
    }];

}
#pragma mark - <UIWebViewDelegate>
//- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation{
//
//    if (self.hasLoad) {
//        return;
//    }
//
//    self.hasLoad = YES;
//
//    JXWeakSelf;
//    //获取内容实际高度(像素)@"document.getElementById(\"content\").offsetHeight;"
//    [webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable result,NSError * _Nullable error) {
//        // 此处js字符串采用scrollHeight而不是offsetHeight是因为后者并获取不到高度,看参考资料说是对于加载html字符串的情况下使用后者可以(@"document.getElementById(\"content\").offsetHeight;"),但如果是和我一样直接加载原站内容使用前者更合适
//        //获取页面高度,并重置webview的frame
//        // 防止死循环
//        if (![weakSelf.heightDic objectForKey:@"height"] || [[weakSelf.heightDic objectForKey:@"height"] doubleValue] != [result doubleValue]) {
//
//            [weakSelf.heightDic setObject:result forKey:@"height"];
//
//            JXLog(@"UpdateGoodDetailCell4Height --- ");
//
//            [[NSNotificationCenter defaultCenter]postNotificationName:UpdateGoodDetailCell4Height object:@([result doubleValue] + 50)];
//        }
//
//    }];
//
//
//}

- (void)setStrInfoContent:(NSString *)strInfoContent{
    _strInfoContent = strInfoContent;

    if (strInfoContent.length) {

        NSURL *cssURL = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"GoodDetail" ofType:@"css"]];
//        [self.webView loadHTMLString:[self handleWithHtmlBody:strInfoContent] baseURL:cssURL];

        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            // 处理耗时操作的代码块...
            [self.uiwebView loadHTMLString:[self handleWithHtmlBody:strInfoContent] baseURL:cssURL];

        });

    }
}

- (NSString *)handleWithHtmlBody:(NSString *)htmlBody
{
    NSString *html = [htmlBody stringByReplacingOccurrencesOfString:@"\t" withString:@""];
//    html = [html stringByReplacingOccurrencesOfString:@"
" withString:@""];
    NSString *cssName = @"GoodDetail.css";
    NSMutableString *htmlString =[[NSMutableString alloc]initWithString:@""];
    [htmlString appendString:@"<meta charset=\"UTF-8\">"];
    [htmlString appendString:@"<link rel =\"stylesheet\" href = \""];
    [htmlString appendString:cssName];
    [htmlString appendString:@"\" type=\"text/css\" />"];
    [htmlString appendString:@""];
    [htmlString appendString:@""];
    [htmlString appendString:html];
    [htmlString appendString:@""];
    [htmlString appendString:@""];
    return htmlString;
}

#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView{

    if (self.hasLoad) {
        return;
    }

    self.hasLoad = YES;

    CGFloat height = [[webView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"]floatValue]+50;

    if (![self.heightDic objectForKey:@"height"] || [[self.heightDic objectForKey:@"height"] doubleValue] != height) {

        [self.heightDic setObject:@(height) forKey:@"height"];

        JXLog(@"uilCell4Height --- ");

        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter]postNotificationName:UpdateGoodDetailCell4Height object:@(height)];
        });
    }

}

#pragma mark - action
// 点击图片
- (void)webViewTapAction:(UITapGestureRecognizer *)tap{

    CGPoint pt = [tap locationInView:self.uiwebView];
    //判断点击到的是否是图片,可设置特殊的url,
    NSString *imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", pt.x, pt.y];
    NSString *urlToSave = [self.uiwebView stringByEvaluatingJavaScriptFromString:imgURL];

    if (urlToSave.length > 0) {
        NSLog(@"%@",urlToSave);
        [self showImageURL:urlToSave point:pt];
    }
}

- (void)showImageURL:(NSString *)url point:(CGPoint)point{
    if(![url hasPrefix:@"http"])return;
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    imageInfo.imageURL = [NSURL URLWithString:url];
    imageInfo.referenceView = self;

    UIViewController *vc = [BYBControllerManger getControllerFormView:self];

    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    [imageViewer showFromViewController:vc.navigationController transition:JTSImageViewControllerTransition_FromOffscreen];

}

#pragma mark - UIGestureRecognizerDelegate
/// 注意 一定要实现这个方法,否则点击webView没反应
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

@end


text:
class Course::AnnouncementNotifier < Notifier::Base
  # To be called when an announcement is made.
  def new_announcement(user, announcement)
    email_enabled = Course::Settings::AnnouncementsComponent.
                    email_enabled?(announcement.course, :new_announcement)

    create_activity(actor: user, object: announcement, event: :new).
      notify(announcement.course, :email).
      save if email_enabled
  end

  private

  # Create an email for the users of a course based on a given course notification record.
  # Overrides email_course in Notifier::Base to pass a custom layout for this notifier.
  #
  # @param [CourseNotification] notification The notification which is used to generate emails
  def email_course(notification)
    notification.course.users.each do |user|
      @pending_emails << ActivityMailer.email(recipient: user,
                                              notification: notification,
                                              view_path: notification_view_path(notification),
                                              layout_path: 'no_greeting_mailer')
    end
  end
end


text:
function startup()
    if file.open("init.lua") == nil then
        print("init.lua deleted or renamed")
    else
        print("Running")
        file.close("init.lua")
        dofile("application.lua")
    end
end

print("Connecting to WiFi access point...")
wifi.setmode(wifi.STATION)
wifi.sta.config('WIFI access point name', 'Wifi password')
wifi.sta.connect()
tmr.alarm(1, 1000, 1, function()
    if wifi.sta.getip() == nil then
        print("Waiting for IP address...")
    else
        tmr.stop(1)
        print("WiFi connection established, IP address: " .. wifi.sta.getip())
        print("You have 3 seconds to abort")
        print("Waiting...")
        tmr.alarm(0, 3000, 0, startup)
    end
end)


text:
using Newtonsoft.Json.Linq;
using System.Linq;

namespace EDDiscovery.EliteDangerous.JournalEvents
{
    //When written: when enough material has been collected from a solar jet code (at a white dwarf or neutron star) for a jump boost
    //Parameters:
    //•	BoostValue
    public class JournalJetConeBoost : JournalEntry
    {
        public JournalJetConeBoost(JObject evt ) : base(evt, JournalTypeEnum.JetConeBoost)
        {
            BoostValue = JSONHelper.GetDouble(evt["BoostValue"]);

        }
        public double BoostValue { get; set; }

    }
}


text:
import requestParam from './common/request-param'

const tokens = {
  admin: {
    token: 'admin-token'
  },
  root: {
    token: 'root-token'
  },
  editor: {
    token: 'editor-token'
  }
}

const users = {
  'admin-token': {
    roles: ['admin', 'editor', 'root'],
    userName: 'admin',
    enabled: true,
    username: 'admin',
    loginName: 'admin',
    password: '123456',
    email: 'admin@qq.com',
    lastPasswordResetDate: new Date(),
    authorities: []
  },
  'root-token': {
    roles: ['admin', 'editor', 'root'],
    userName: 'root',
    enabled: true,
    username: 'root',
    loginName: 'root',
    password: '123456',
    email: 'root@qq.com',
    lastPasswordResetDate: new Date(),
    authorities: []
  },
  'editor-token': {
    roles: ['editor'],
    userName: 'editor',
    enabled: true,
    username: 'editor',
    loginName: 'editor',
    password: '123456',
    email: 'editor@qq.com',
    lastPasswordResetDate: new Date(),
    authorities: [],
    introduction: 'I am a super administrator',
    avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
    name: 'Super Admin'
  }
}

export default [
  // user login
  {
    url: '/user/login',
    type: 'post',
    response: config => {
      const { username } = config.body
      const token = tokens[username]

      // mock error
      if (!token) {
        return requestParam.handleResponseContent({}, false, 401, 'do not find user.')
      }
      return requestParam.handleResponseContent(token)
    }
  },

  // get user info
  {
    url: '/user/info\.*',
    type: 'get',
    response: (config, b, c) => {
      const { authorization } = config.headers
      const info = users[authorization.indexOf('Bearer ') >= 0 ? authorization.substr(7) : authorization]

      // mock error
      if (!info) {
        return requestParam.handleResponseContent({}, false, 404, 'Login failed, unable to get user details.')
      }

      return requestParam.handleResponseContent(info)
    }
  },
  // user logout
  {
    url: '/user/password',
    type: 'post',
    response: (config, b, c) => {
      const { authorization } = config.headers
      const info = users[authorization.indexOf('Bearer ') >= 0 ? authorization.substr(7) : authorization]
      return requestParam.handleResponseContent(info, true)
    }
  },

  // user logout
  {
    url: '/user/logout',
    type: 'post',
    response: _ => {
      return requestParam.handleResponseContent({}, true)
    }
  }
]


text:
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution

import json

class RadarSearch(Choreography):

    def __init__(self, temboo_session):
        """
        Create a new instance of the RadarSearch Choreo. A TembooSession object, containing a valid
        set of Temboo credentials, must be supplied.
        """
        super(RadarSearch, self).__init__(temboo_session, '/Library/Google/Places/RadarSearch')

    def new_input_set(self):
        return RadarSearchInputSet()

    def _make_result_set(self, result, path):
        return RadarSearchResultSet(result, path)

    def _make_execution(self, session, exec_id, path):
        return RadarSearchChoreographyExecution(session, exec_id, path)

class RadarSearchInputSet(InputSet):
    """
    An InputSet with methods appropriate for specifying the inputs to the RadarSearch
    Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
    """
    def set_Key(self, value):
        """
        Set the value of the Key input for this Choreo. ((required, string) Enter your Google API key.)
        """
        super(RadarSearchInputSet, self)._set_input('Key', value)
    def set_Keyword(self, value):
        """
        Set the value of the Keyword input for this Choreo. ((conditional, string) Enter a keyword (term, address, type, customer review, etc.) to be matched against all results retrieved for this Place.  At least one of Keyword, Name or Types must be specified.)
        """
        super(RadarSearchInputSet, self)._set_input('Keyword', value)
    def set_Language(self, value):
        """
        Set the value of the Language input for this Choreo. ((optional, string) Set the language in which to return restults.  A list of supported languages is available here: https://spreadsheets.google.com/pub?key=p9pdwsai2hDMsLkXsoM05KQ&gid=1)
        """
        super(RadarSearchInputSet, self)._set_input('Language', value)
    def set_Latitude(self, value):
        """
        Set the value of the Latitude input for this Choreo. ((required, string) Specify a latitude point around which Places results will be retrieved.)
        """
        super(RadarSearchInputSet, self)._set_input('Latitude', value)
    def set_Longitude(self, value):
        """
        Set the value of the Longitude input for this Choreo. ((required, string) Specify a longitude point around which Places results will be retrieved.)
        """
        super(RadarSearchInputSet, self)._set_input('Longitude', value)
    def set_MaxPrice(self, value):
        """
        Set the value of the MaxPrice input for this Choreo. ((optional, integer) Restricts results to only those places within the specified range. Valid values range between 0 (most affordable) to 4 (most expensive), inclusive. The exact amount will vary from region to region.)
        """
        super(RadarSearchInputSet, self)._set_input('MaxPrice', value)
    def set_MinPrice(self, value):
        """
        Set the value of the MinPrice input for this Choreo. ((optional, integer) Restricts results to only those places within the specified range. Valid values range between 0 (most affordable) to 4 (most expensive), inclusive. The exact amount will vary from region to region.)
        """
        super(RadarSearchInputSet, self)._set_input('MinPrice', value)
    def set_Name(self, value):
        """
        Set the value of the Name input for this Choreo. ((conditional, string) Enter a name to be matched when results are retrieved for this specified Place.  At least one of Keyword, Name or Types must be specified.)
        """
        super(RadarSearchInputSet, self)._set_input('Name', value)
    def set_OpenNow(self, value):
        """
        Set the value of the OpenNow input for this Choreo. ((optional, boolean) Returns only those Places that are open for business at the time the query is sent. Places that do not specify opening hours in the Google Places database will not be returned.)
        """
        super(RadarSearchInputSet, self)._set_input('OpenNow', value)
    def set_PageToken(self, value):
        """
        Set the value of the PageToken input for this Choreo. ((optional, string) The "NextPageToken" returned in the choreo output from a previous run. Used to page through large result sets. When the PageToken is specified, all other inputs are ignored.)
        """
        super(RadarSearchInputSet, self)._set_input('PageToken', value)
    def set_Radius(self, value):
        """
        Set the value of the Radius input for this Choreo. ((required, integer) Specify the radius in meters for which Places results will be returned. Maximum radius is limited to 50,000 meters.)
        """
        super(RadarSearchInputSet, self)._set_input('Radius', value)
    def set_ResponseFormat(self, value):
        """
        Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that response should be in. Can be set to xml or json. Defaults to json.)
        """
        super(RadarSearchInputSet, self)._set_input('ResponseFormat', value)
    def set_Sensor(self, value):
        """
        Set the value of the Sensor input for this Choreo. ((optional, boolean) Indicates whether or not the directions request is from a device with a location sensor. Value must be either 1 or 0. Defaults to 0 (false).)
        """
        super(RadarSearchInputSet, self)._set_input('Sensor', value)
    def set_Types(self, value):
        """
        Set the value of the Types input for this Choreo. ((conditional, string) Filter results by types, such as: bar, dentist.  Multiple types must be separated by the pipe ("|") symbol: bar|dentist|airport.   At least one of Keyword, Name or Types must be specified.)
        """
        super(RadarSearchInputSet, self)._set_input('Types', value)

class RadarSearchResultSet(ResultSet):
    """
    A ResultSet with methods tailored to the values returned by the RadarSearch Choreo.
    The ResultSet object is used to retrieve the results of a Choreo execution.
    """

    def getJSONFromString(self, str):
        return json.loads(str)

    def get_Response(self):
        """
        Retrieve the value for the "Response" output from this Choreo execution. (The response from Google.)
        """
        return self._output.get('Response', None)

class RadarSearchChoreographyExecution(ChoreographyExecution):

    def _make_result_set(self, response, path):
        return RadarSearchResultSet(response, path)


text:
require 'pry-stack_explorer'

module PryExceptionExplorer
  module ExceptionHelpers
    include PryStackExplorer::FrameHelpers

    private
    def in_exception?
      frame_manager && frame_manager.user[:exception]
    end

    def last_exception
      _pry_.last_exception
    end

    def enterable_exception?
      last_exception && last_exception.exception_call_stack
    end

    def inline_exception?
      frame_manager && frame_manager.user[:exception] &&
        frame_manager.user[:inline_exception]
    end

    def normal_exception?
      frame_manager && frame_manager.user[:exception] &&
        frame_manager.user[:exception].continuation
    end
  end

  Commands = Pry::CommandSet.new do
    create_command "enter-exception", "Enter the context of the last exception" do
      include PryExceptionExplorer::ExceptionHelpers

      banner <<-BANNER
        Usage: enter-exception
        Enter the context of the last exception
      BANNER

      def process
        if enterable_exception?
          PryStackExplorer.create_and_push_frame_manager(last_exception.exception_call_stack, _pry_)
          PryExceptionExplorer.setup_exception_context(last_exception, _pry_)

          # have to use _pry_.run_command instead of 'run' here as
          # 'run' works on the current target which hasnt been updated
          # yet, whereas _pry_.run_command operates on the newly
          # updated target (the context of the exception)
          _pry_.run_command "whereami"
        elsif last_exception
          raise Pry::CommandError, "Current exception can't be entered! (perhaps a C exception)"
        else
          raise Pry::CommandError,  "No exception to enter!"
        end
      end
    end

    create_command "exit-exception", "Leave the context of the current exception." do
      include ExceptionHelpers

      banner <<-BANNER
        Usage: exit-exception
        Exit active exception and return to containing context.
      BANNER

      def process
        if !in_exception?
          raise Pry::CommandError, "You are not in an exception!"
        elsif !prior_context_exists?
          run "exit-all"
        else
          popped_fm = PryStackExplorer.pop_frame_manager(_pry_)
          _pry_.last_exception = popped_fm.user[:exception]
        end
      end
    end

    create_command "continue-exception", "Attempt to continue the current exception." do
      include ExceptionHelpers

      banner <<-BANNER
        Usage: continue-exception
        Attempt to continue the current exception.
      BANNER

      def process
        if inline_exception?
          PryStackExplorer.pop_frame_manager(_pry_)
          run "exit-all PryExceptionExplorer::CONTINUE_INLINE_EXCEPTION"
        elsif normal_exception?
          popped_fm = PryStackExplorer.pop_frame_manager(_pry_)
          popped_fm.user[:exception].continue
        else
          raise Pry::CommandError, "No exception to continue!"
        end
      end
    end

  end
end


text:
<?php

/**
 * Add page type class name as a css class on body.
 *
 * @param  array $classes
 *
 * @return array
 */
function papi_body_class( array $classes ) {
	$classes = array_merge( $classes, papi_get_entry_type_body_classes() );

	if ( $class = papi_get_entry_type_css_class() ) {
		$classes[] = $class;
	}

	return array_unique( $classes );
}
add_filter( 'body_class', 'papi_body_class' );

/**
 * Get template file name.
 *
 * @param  string $template
 *
 * @return string|null
 */
function papi_get_template_file_name( $template ) {
	if ( ! is_string( $template ) ) {
		return;
	}

	$extension = '.php';
	$ext_reg   = '/(' . $extension . ')+$/';

	if ( preg_match( '/\.\w+$/', $template, $matches ) && preg_match( $ext_reg, $matches[0] ) ) {
		return str_replace( '.', '/', preg_replace( '/' . $matches[0] . '$/', '', $template ) ) . $matches[0];
	}

	$template = str_replace( '.', '/', $template );
	$template = substr( $template, -strlen( $extension ) ) === $extension ? $template : $template . $extension;

	return $template === $extension ? null : $template;
}

/**
 * Include partial view.
 *
 * @param string $file
 * @param array $vars
 */
function papi_include_template( $file, array $vars = [] ) {
	if ( ! is_string( $file ) || empty( $file ) ) {
		return;
	}

	$path = PAPI_PLUGIN_DIR;
	$path = rtrim( $path, '/' ) . '/';

	if ( file_exists( $path . $file ) ) {
		require $path . $file;
	}
}

/**
 * Load a template array file and merge values with it.
 *
 * @param  string $file
 * @param  array  $values
 * @param  bool   $convert_to_object
 *
 * @return array|object
 */
function papi_template( $file, array $values = [], $convert_to_object = false ) {
	if ( ! is_string( $file ) || empty( $file ) ) {
		return [];
	}

	$filepath = papi_get_file_path( $file );

	if ( empty( $filepath ) && is_file( $file ) ) {
		$filepath = $file;
	}

	if ( empty( $filepath ) || ! file_exists( $filepath ) || is_dir( $filepath ) ) {
		return [];
	}

	$template = require $filepath;

	if ( papi_is_property( $template ) ) {
		foreach ( $values as $key => $value ) {
			$template->set_option( $key, $value );
		}

		$result = $template;
	} else {
		$result = array_merge( (array) $template, $values );
	}

	if ( $convert_to_object ) {
		return (object) $result;
	}

	return $result;
}

/**
 * Include template files from Papis custom page template meta field.
 *
 * @param  string $original_template
 *
 * @return string
 */
function papi_template_include( $original_template ) {
	global $post;

	// Check so we only change template on single and page posts.
	if ( ! is_single() && ! is_page() && ! is_tag() ) {
		return $original_template;
	}

	// Determine which id to use.
	$id = is_tag() ? get_queried_object()->term_id : $post->ID;

	// Only load a template if it exists.
	if ( $page_template = papi_get_entry_type_template( $id ) ) {
		if ( $template = locate_template( $page_template ) ) {
			/**
			 * Change which template that is used by Papi.
			 *
			 * @param  string $template
			 *
			 * @return string
			 */
			return apply_filters( 'papi/template_include', $template );
		}
	}

	return $original_template;
}
add_filter( 'template_include', 'papi_template_include' );


text:
module Node::Views::Admin
  class EditBlurb
    include Node::View

    def blurb_form

      blurb_text = node.meta['long_blurb'] || ''

      form_for :node, "/node/update_blurb/#{node.id}" do

        label :blurb
        text_area :blurb,  blurb_text

        hidden_field :node_id, value: node.id

        submit 'Update',  class: "waves-effect waves-light btn"

      end
    end

  end
end


text:
CREATE OR REPLACE VIEW OSP$NOTIFICATION_TYPE AS SELECT
  NOTIFICATION_TYPE_ID NOTIFICATION_NUMBER,
  MODULE_CODE,
  ACTION_CODE,
  DESCRIPTION,
  SUBJECT,
  MESSAGE,
  PROMPT_USER,
  SEND_NOTIFICATION,
  SYSTEM_GENERATED,
  UPDATE_USER,
  UPDATE_TIMESTAMP
  FROM NOTIFICATION_TYPE;


text:
import $ from 'cheerio'

export function prop( prop ) {
  if ( prop === undefined || typeof this !== 'object' ) {
    return undefined
  } else if ( !this[0] && this[ prop ] ) {
    return typeof this[ prop ] === 'function' ?
      this[ prop ]() : this[ prop ]
  } else if ( this[0] && this[0][ prop ] ) {
    return this[0][ prop ]
  }
  return undefined
}

export function content() {
  if ( this.children && Array.isArray( this.children )) {
    return this.children
  } else if ( typeof this.contents === 'function' ) {
    return this.contents()
  }
  return [ null ]
}

export function type()   {  return this::prop( 'type' )  }
export function first()  {  return this::content()[0]  }
export function prev()   {  return this::prop( 'prev' )  }
export function next()   {  return this::prop( 'next' )  }
export function parent() {  return this::prop( 'parent' )  }
export function html()   {  return $.html( this )  }

export function empty() {
  if ( typeof this !== 'object' ) {
    return
  } else if ( typeof this.empty === 'function' ) {
    return this.empty()
  }

  if ( this::type() === 'text' ) {
    this.data = ''
  } else {
    this.children = []
  }

  return this
}

export function before( content ) {
  content = typeof content === 'string' ?
    $( content ) : content

  if ( typeof this !== 'object' ) {
    return
  } else if ( typeof this.before === 'function' ) {
    return this.before.apply( this, content )
  }

  const parent = this.parent || this.root

  if ( !parent || !Array.isArray( parent.children )) {
    return
  }

  const idxBefore = parent.children.indexOf( this )
  const idxAfter  = idxBefore + content.contents().length

  this::replaceWith(
    `<fibrio-fake>${
      $.html( content ) +
      $.html( this )
    }</fibrio-fake>`
  )

  parent.children = Array.from($(
    $.html( parent ).replace( /<\/?fibrio\-fake>/gi, '' )
  ).contents())

  return parent.children[ idxAfter ]
}

export function rm() {
  if ( typeof this !== 'object' ) {
    return
  } else if ( typeof this.remove === 'function' ) {
    return this.remove()
  }

  const parent = this.parent || this.root

  if ( !parent || !Array.isArray( parent.children )) {
    return
  }

  let sib = parent.children
  let idx = sib.indexOf( this )

  if ( idx < 0 )  return
  sib.splice( idx, 1 )
  if ( this.prev )  this.prev.next = this.next
  if ( this.next )  this.next.prev = this.prev
  this.prev = this.next = this.parent = this.root = null
  return this
}

export function replaceWith( content ) {
  if ( typeof this !== 'object' ) {
    return
  } else if ( typeof this.replaceWith === 'function' ) {
    return this.replaceWith( content )
  }

  const parent = this.parent || this.root

  if ( !parent || !Array.isArray( parent.children )) {
    return
  }

  let sib = parent.children
  let idx = sib.indexOf( this )
  let newNode = typeof content === 'string' ?
    $( content ) : content

  if ( idx < 0 )  return
  if ( !newNode.type && newNode[0] )  newNode = newNode[0]

  sib[ idx ] = newNode
  return sib[ idx ]
}

export function createText( text ) {
  return $( `<fibrio-text>${ text }</fibrio-text>` )
}


text:
package gov.nih.nci.cabig.caaers.tools;

import gov.nih.nci.cabig.ctms.tools.DataSourceSelfDiscoveringPropertiesFactoryBean;

import org.springframework.beans.factory.InitializingBean;

/**
 * This class searches through the following directories, looking for a file named
 * ${databaseConfigurationName}.properties:
 *

 *
${catalina.home}/conf/caaers

 *
${user.home}/.caaers

 *
/etc/caaers

 *

 *
 * It loads this file and returns it when {@link #getObject} is called.
 *
 * @author Rhett Sutphin
 */
public class CaaersDataSourcePropertiesFactoryBean extends
                DataSourceSelfDiscoveringPropertiesFactoryBean implements InitializingBean{
    public static final String QUARTZ_DELEGATE_PROPERTY_NAME = "jdbc.quartz.delegateClassName";

    public static final String SCHEMA_PROPERTY_NAME = "datasource.schema";

    public static final String AUTH_MODE_PROPERTY_NAME = "authenticationMode";

    public static final String WEBSSO_BASE_URL = "webSSO.server.baseUrl";

    public static final String WEBSSO_SERVER_TRUST_CERTIFICATE = "webSSO.trustStore";

    public static final String WEBSSO_HOST_CERTIFICATE = "hostCertificate";

    public static final String WEBSSO_HOST_KEY = "hostKey";

    public static final String WEBSSO_CAS_ACEGI_SECURITY_URL = "webSSO.cas.acegi.security.url";

    public static final String GRID_STUDYCONSUMER_ROLLBACK_INTERVAL = "grid.studyconsumer.rollbackInterval";

    public static final String GRID_REGISTRATIONCONSUMER_ROLLBACK_INTERVAL = "grid.registrationconsumer.rollbackInterval";

    public static final String RULES_DB_FILE = "rules.dbfile";

    public static final String DB_NAME  = "databaseName";

    private static CaaersDataSourcePropertiesFactoryBean theBean;

    public CaaersDataSourcePropertiesFactoryBean() {
        setApplicationDirectoryName("caaers");
    }

    public void afterPropertiesSet() throws Exception {
    	theBean = this;
    }

    public static CaaersDataSourcePropertiesFactoryBean getLoadedInstance(){
    	return theBean;
    }

    /**
     * Sets reasonable defaults for caAERS-specific properties
     */
    @Override
    protected void computeProperties() {
        String quartzDelegateClass = selectQuartzDelegateClass();
        if (quartzDelegateClass != null) properties.setProperty(QUARTZ_DELEGATE_PROPERTY_NAME,
                        quartzDelegateClass);
        String schema = selectSchema();
        if (schema != null) properties.setProperty(SCHEMA_PROPERTY_NAME, schema);
        if (properties.getProperty(AUTH_MODE_PROPERTY_NAME) == null) properties.setProperty(
                        AUTH_MODE_PROPERTY_NAME, "local");
        if (properties.getProperty(WEBSSO_BASE_URL) == null) properties.setProperty(
                        WEBSSO_BASE_URL, "http://dummyurl.com/url");
        if (properties.getProperty(WEBSSO_SERVER_TRUST_CERTIFICATE) == null) properties
                        .setProperty(WEBSSO_SERVER_TRUST_CERTIFICATE, System.getProperty("java.home") + "/lib/security/cacerts");
        if (properties.getProperty(WEBSSO_HOST_CERTIFICATE) == null) properties.setProperty(
                        WEBSSO_HOST_CERTIFICATE, "dummyHostCert");
        if (properties.getProperty(WEBSSO_HOST_KEY) == null) properties.setProperty(
                        WEBSSO_HOST_KEY, "dummykey");
        if (properties.getProperty(WEBSSO_CAS_ACEGI_SECURITY_URL) == null) properties.setProperty(
                        WEBSSO_CAS_ACEGI_SECURITY_URL, "http://dummy.com/casurl/");
        if (properties.getProperty(GRID_STUDYCONSUMER_ROLLBACK_INTERVAL) == null) properties
                        .setProperty(GRID_STUDYCONSUMER_ROLLBACK_INTERVAL, "1");
        if (properties.getProperty(GRID_REGISTRATIONCONSUMER_ROLLBACK_INTERVAL) == null) properties
                        .setProperty(GRID_REGISTRATIONCONSUMER_ROLLBACK_INTERVAL, "1");

        if(properties.getProperty(RULES_DB_FILE) == null) properties.setProperty(RULES_DB_FILE, selectRulesDBConfiguration());
        if(properties.getProperty(DB_NAME) == null) properties.setProperty(DB_NAME, dbName());
    }

    /**
     * To determin the quartz delegate class to use
     *
     * @return
     */
    private String selectQuartzDelegateClass() {
        // //hsql for time being will use default (http://jira.opensymphony.com/browse/QUARTZ-560)
        String defaultClass = "org.quartz.impl.jdbcjobstore.StdJDBCDelegate";
        String postgresClass = "org.quartz.impl.jdbcjobstore.PostgreSQLDelegate";
        String oracleClass = "org.quartz.impl.jdbcjobstore.oracle.OracleDelegate";

        String db = selectSchema();
        if (db != null) {
            if (db.contains("postgresql")) return postgresClass;
            if (db.contains("oracle")) return oracleClass;
        }
        return defaultClass;

    }

    /**
     * This method sets the DB_NAME property
     * @return String
     */
    private String dbName(){
    	String db = selectSchema();
    	if(db != null) {
    		if(db.contains("oracle")) return "oracle";
    		else if (db.contains("postgresql")) return "postgres";
    	}
    	return null;
    }

    private String selectRulesDBConfiguration(){
    	String db = selectSchema();
        if (db != null && db.contains("oracle")) {
        	return "classpath:db/jackrabbit-repo-oracle.xml";
        }
    	return "classpath:db/jackrabbit-repo-database.xml";
    }

    /**
     * Jackrabbit calls database vendor as schema , jackrabbit needs this variable
     *
     * @return
     */
    private String selectSchema() {
        String rdbms = properties.getProperty(RDBMS_PROPERTY_NAME);
        String driver = properties.getProperty(DRIVER_PROPERTY_NAME);

        String db = (rdbms != null) ? rdbms : driver;
        if (db != null) {
            if (db.toLowerCase().contains("postgres")) return "postgresql";
            if (db.toLowerCase().contains("oracle")) return "oracle";
        }
        return db;

    }
}


text:
class ApplicationControllerImpl final
    : public chromium::cast::ApplicationController {
 public:
  ApplicationControllerImpl(fuchsia::web::Frame* frame,
                            chromium::cast::ApplicationContext* context);

  ApplicationControllerImpl(const ApplicationControllerImpl&) = delete;
  ApplicationControllerImpl& operator=(const ApplicationControllerImpl&) =
      delete;

  ~ApplicationControllerImpl() override;

 protected:
  // chromium::cast::ApplicationController implementation.
  void SetTouchInputEnabled(bool enable) override;
  void GetMediaPlayer(
      ::fidl::InterfaceRequest<fuchsia::media::sessions2::Player> request)
      override;
  void SetBlockMediaLoading(bool blocked) override;
  void GetPrivateMemorySize(GetPrivateMemorySizeCallback callback) override;

 private:
  fidl::Binding<chromium::cast::ApplicationController> binding_;
  fuchsia::web::Frame* const frame_;
};

#endif  // FUCHSIA_RUNNERS_CAST_APPLICATION_CONTROLLER_IMPL_H_


text:
package li.kazu.java.audio.id3;

import java.io.File;

/**
 * try to get ID3 information<br>
 * first try ID3v2, if not successful try ID3v1
 *
 * @author kazu
 *
 */
public class ID3 implements ID3Provider {

	/* attributes */
	private boolean			isOK = false;
	private String			title = "";
	private String 			artist = "";
	private String			album = "";
	private String			year = "";
	private String			comment = "";
	private String			genre = "";
	private ID3Image		cover = null;

	/** create ID3 reader for the given fill (this will try ID3v2 first, then ID3v1) */
	public ID3(File file) {

		// try V2
		ID3Provider dataSrc = new ID3v2(file);

		// failed? => try v1
		if (!dataSrc.isOK()) {dataSrc = new ID3v1(file);}

		// ok? => set values
		if (dataSrc.isOK()) {
			isOK = true;
			readTags(dataSrc);
		}

		dataSrc = null;

	}

	/* tags einlesen */
	private void readTags(ID3Provider dataSrc) {
		artist = dataSrc.getArtist();
		title = dataSrc.getTitle();
		album = dataSrc.getAlbum();
		year = dataSrc.getYear();
		comment = dataSrc.getComment();
		genre = dataSrc.getGenre();
		cover = dataSrc.getCover();
	}

	@Override
	public boolean isOK()           {return isOK;}

	@Override
	public String getArtist()       {return artist;}

	@Override
	public String getTitle()        {return title;}

	@Override
	public String getAlbum()        {return album;}

	@Override
	public String getYear()         {return year;}

	@Override
	public String getComment()      {return comment;}

	@Override
	public String getGenre()        {return genre;}

	@Override
	public ID3Image getCover() 		{return cover;}

	@Override
	public String toString()		{return artist + " - " + title;}

}


text:
Community
=========
Learn how to contribute to the project and how you can become part of the community
of content developers working to integrate content into the Kolibri platform,
and more broadly into all offline learning tools.

.. toctree::
   :maxdepth: 1

   contributing
   authors
   ../history

.. TODOC: volunteers progam, step-by-step guide to small contribution, etc.


text:
#pragma once

#include "MainPage.g.h"
#include "FolderItem.h"
#include "ManipulableContentControl.xaml.h"

namespace PhotoScatter
{
    public ref class MainPage sealed
    {
    public:
        MainPage();

    private:
        void OnMainPageLoaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
        void BuildFolderListBox(Windows::Storage::StorageFolder^ parentStorageFolder, int level);
        void OnFolderListBoxSelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ args);
        void OnManipulableControlManipulationStarted(Platform::Object^ sender, Windows::UI::Xaml::Input::ManipulationStartedRoutedEventArgs^ args);
        Concurrency::task<Windows::UI::Xaml::Media::Imaging::WriteableBitmap^> LoadBitmapAsync(Windows::Storage::StorageFile^ storageFile);
        Concurrency::task<Windows::UI::Xaml::Media::Imaging::WriteableBitmap^> LoadBitmapAsync(Windows::Storage::FileProperties::StorageItemThumbnail^ thumbnail);
        Concurrency::task<Windows::UI::Xaml::Media::Imaging::WriteableBitmap^> LoadBitmapAsync(Windows::Storage::Streams::IRandomAccessStream^ stream);
        Concurrency::task<Windows::UI::Xaml::Media::Imaging::WriteableBitmap^> CreateBitmapAsync(Windows::Graphics::Imaging::BitmapFrame^ bitmapFrame);
    };
}


text:
class Admin::ProductsController < ApplicationController

  before_action :authenticate_user!
  before_filter :verify_admin

  def index
    @products = Product.paginate(:page => params[:page], :per_page => 10).order(:id)
  end

  def show
    @product = Product.find(params[:id])
    if request.xhr?
      render "_modal", layout: false
    end
  end

  def new
    @product = Product.new
    @categories = Category.order(:name)
  end

  def edit
    @product = Product.find(params[:id])
    @categories = Category.order(:name)
  end

  def create
    @product = Product.new(product_params)
    @categories = Category.order(:name)
    @product.set_categories(params[:category])

    if @product.save
      flash[:success] = "Product successfully created"
      redirect_to admin_products_path
    else
      render 'new'
    end
  end

  def update
    @product = Product.find(params[:id])
    @categories = Category.order(:name)
    @product.categories = []
    @product.set_categories(params[:category])

    if @product.update(product_params)
      flash[:success] = "Product successfully updated"
      redirect_to admin_products_path
    else
      render "edit"
    end
  end

  def destroy
    @product = Product.find(params[:id])
    @product.destroy
    flash[:info] = "Product successfully deleted"
    redirect_to admin_products_path
  end

  private

  def product_params
    params.require(:product).permit(:title, :description, :price, :picture_link)
  end

  def verify_admin
    (current_user.nil?) ? redirect_to(root_path) : (redirect_to(root_path) unless current_user.admin?)
  end
end