text:
/* eslint no-constant-condition: 0 */
/**
 * Mnemonist CritBitTreeMap
 * =========================
 *
 * JavaScript implementation of a crit-bit tree, also called PATRICIA tree.
 * This tree is a basically a bitwise radix tree and is supposedly much more
 * efficient than a standard Trie.
 *
 * [References]:
 * https://cr.yp.to/critbit.html
 * https://www.imperialviolet.org/binary/critbit.pdf
 */
var bitwise = require('./utils/bitwise.js');

/**
 * Helpers.
 */

/**
 * Helper returning the direction we need to take given a key and an
 * encoded critbit.
 *
 * @param  {string} key     - Target key.
 * @param  {number} critbit - Packed address of byte + mask.
 * @return {number}         - 0, left or 1, right.
 */
function getDirection(key, critbit) {
  var byteIndex = critbit >> 8;

  if (byteIndex > key.length - 1)
    return 0;

  var byte = key.charCodeAt(byteIndex),
      mask = critbit & 0xff;

  return (1 + (byte | mask)) >> 8;
}

/**
 * Helper returning the packed address of byte + mask or -1 if strings
 * are identical.
 *
 * @param  {string} a      - First key.
 * @param  {string} b      - Second key.
 * @return {number}        - Packed address of byte + mask.
 */
function findCriticalBit(a, b) {
  var i = 0,
      tmp;

  // Swapping so a is the shortest
  if (a.length > b.length) {
    tmp = b;
    b = a;
    a = tmp;
  }

  var l = a.length,
      mask;

  while (i < l) {
    if (a[i] !== b[i]) {
      mask = bitwise.criticalBit8Mask(
        a.charCodeAt(i),
        b.charCodeAt(i)
      );

      return (i << 8) | mask;
    }

    i++;
  }

  // Strings are identical
  if (a.length === b.length)
    return -1;

  // NOTE: x ^ 0 is the same as x
  mask = bitwise.criticalBit8Mask(b.charCodeAt(i));

  return (i << 8) | mask;
}

/**
 * Class representing a crit-bit tree's internal node.
 *
 * @constructor
 * @param {number} critbit - Packed address of byte + mask.
 */
function InternalNode(critbit) {
  this.critbit = critbit;
  this.left = null;
  this.right = null;
}

/**
 * Class representing a crit-bit tree's external node.
 * Note that it is possible to replace those nodes by flat arrays.
 *
 * @constructor
 * @param {string} key   - Node's key.
 * @param {any}    value - Arbitrary value.
 */
function ExternalNode(key, value) {
  this.key = key;
  this.value = value;
}

/**
 * CritBitTreeMap.
 *
 * @constructor
 */
function CritBitTreeMap() {

  // Properties
  this.root = null;
  this.size = 0;

  this.clear();
}

/**
 * Method used to clear the CritBitTreeMap.
 *
 * @return {undefined}
 */
CritBitTreeMap.prototype.clear = function() {

  // Properties
  this.root = null;
  this.size = 0;
};

/**
 * Method used to set the value of the given key in the trie.
 *
 * @param  {string}         key   - Key to set.
 * @param  {any}            value - Arbitrary value.
 * @return {CritBitTreeMap}
 */
CritBitTreeMap.prototype.set = function(key, value) {

  // Tree is empty
  if (this.size === 0) {
    this.root = new ExternalNode(key, value);
    this.size++;

    return this;
  }

  // Walk state
  var node = this.root,
      ancestors = [],
      path = [],
      ancestor,
      parent,
      child,
      critbit,
      internal,
      left,
      leftPath,
      best,
      dir,
      i,
      l;

  // Walking the tree
  while (true) {

    // Traversing an internal node
    if (node instanceof InternalNode) {
      dir = getDirection(key, node.critbit);

      // Going left & creating key if not yet there
      if (dir === 0) {
        if (!node.left) {
          node.left = new ExternalNode(key, value);
          return this;
        }

        ancestors.push(node);
        path.push(true);

        node = node.left;
      }

      // Going right & creating key if not yet there
      else {
        if (!node.right) {
          node.right = new ExternalNode(key, value);
          return this;
        }

        ancestors.push(node);
        path.push(false);

        node = node.right;
      }
    }

    // Reaching an external node
    else {

      // 1. Creating a new external node
      critbit = findCriticalBit(key, node.key);

      // Key is identical, we just replace the value
      if (critbit === -1) {
        node.value = value;
        return this;
      }

      this.size++;

      internal = new InternalNode(critbit);

      left = getDirection(key, critbit) === 0;

      // TODO: maybe setting opposite pointer is not necessary
      if (left) {
        internal.left = new ExternalNode(key, value);
        internal.right = node;
      }
      else {
        internal.left = node;
        internal.right = new ExternalNode(key, value);
      }

      // 2. Bubbling up
      best = -1;
      l = ancestors.length;

      for (i = l - 1; i >= 0; i--) {
        ancestor = ancestors[i];

        if (ancestor.critbit > critbit)
          continue;

        best = i;
        break;
      }

      // Do we need to attach to the root?
      if (best < 0) {
        this.root = internal;

        // Need to rewire parent as child?
        if (l > 0) {
          parent = ancestors[0];

          if (left)
            internal.right = parent;
          else
            internal.left = parent;
        }
      }

      // Simple case without rotation
      else if (best === l - 1) {
        parent = ancestors[best];
        leftPath = path[best];

        if (leftPath)
          parent.left = internal;
        else
          parent.right = internal;
      }

      // Full rotation
      else {
        parent = ancestors[best];
        leftPath = path[best];
        child = ancestors[best + 1];

        if (leftPath)
          parent.left = internal;
        else
          parent.right = internal;

        if (left)
          internal.right = child;
        else
          internal.left = child;
      }

      return this;
    }
  }
};

/**
 * Method used to get the value attached to the given key in the tree or
 * undefined if not found.
 *
 * @param  {string} key   - Key to get.
 * @return {any}
 */
CritBitTreeMap.prototype.get = function(key) {

  // Walk state
  var node = this.root,
      dir;

  // Walking the tree
  while (true) {

    // Dead end
    if (node === null)
      return;

    // Traversing an internal node
    if (node instanceof InternalNode) {
      dir = getDirection(key, node.critbit);

      node = dir ? node.right : node.left;
    }

    // Reaching an external node
    else {
      if (node.key !== key)
        return;

      return node.value;
    }
  }
};

/**
 * Method used to return whether the given key exists in the tree.
 *
 * @param  {string} key - Key to test.
 * @return {boolean}
 */
CritBitTreeMap.prototype.has = function(key) {

  // Walk state
  var node = this.root,
      dir;

  // Walking the tree
  while (true) {

    // Dead end
    if (node === null)
      return false;

    // Traversing an internal node
    if (node instanceof InternalNode) {
      dir = getDirection(key, node.critbit);

      node = dir ? node.right : node.left;
    }

    // Reaching an external node
    else {
      return node.key === key;
    }
  }
};

/**
 * Method used to delete the given key from the tree and return whether the
 * key did exist or not.
 *
 * @param  {string} key - Key to delete.
 * @return {boolean}
 */
CritBitTreeMap.prototype.delete = function(key) {

  // Walk state
  var node = this.root,
      dir;

  var parent = null,
      grandParent = null,
      wentLeftForParent = false,
      wentLeftForGrandparent = false;

  // Walking the tree
  while (true) {

    // Dead end
    if (node === null)
      return false;

    // Traversing an internal node
    if (node instanceof InternalNode) {
      dir = getDirection(key, node.critbit);

      if (dir === 0) {
        grandParent = parent;
        wentLeftForGrandparent = wentLeftForParent;
        parent = node;
        wentLeftForParent = true;

        node = node.left;
      }
      else {
        grandParent = parent;
        wentLeftForGrandparent = wentLeftForParent;
        parent = node;
        wentLeftForParent = false;

        node = node.right;
      }
    }

    // Reaching an external node
    else {
      if (key !== node.key)
        return false;

      this.size--;

      // Rewiring
      if (parent === null) {
        this.root = null;
      }

      else if (grandParent === null) {
        if (wentLeftForParent)
          this.root = parent.right;
        else
          this.root = parent.left;
      }

      else {
        if (wentLeftForGrandparent) {
          if (wentLeftForParent) {
            grandParent.left = parent.right;
          }
          else {
            grandParent.left = parent.left;
          }
        }
        else {
          if (wentLeftForParent) {
            grandParent.right = parent.right;
          }
          else {
            grandParent.right = parent.left;
          }
        }
      }

      return true;
    }
  }
};

/**
 * Method used to iterate over the tree in key order.
 *
 * @param  {function}  callback - Function to call for each item.
 * @param  {object}    scope    - Optional scope.
 * @return {undefined}
 */
CritBitTreeMap.prototype.forEach = function(callback, scope) {
  scope = arguments.length > 1 ? scope : this;

  // Inorder traversal of the tree
  var current = this.root,
      stack = [];

  while (true) {

    if (current !== null) {
      stack.push(current);

      current = current instanceof InternalNode ? current.left : null;
    }

    else {
      if (stack.length > 0) {
        current = stack.pop();

        if (current instanceof ExternalNode)
          callback.call(scope, current.value, current.key);

        current = current instanceof InternalNode ? current.right : null;
      }
      else {
        break;
      }
    }
  }
};

/**
 * Convenience known methods.
 */
CritBitTreeMap.prototype.inspect = function() {
  return this;
};

if (typeof Symbol !== 'undefined')
  CritBitTreeMap.prototype[Symbol.for('nodejs.util.inspect.custom')] = CritBitTreeMap.prototype.inspect;

/**
 * Static @.from function taking an arbitrary iterable & converting it into
 * a CritBitTreeMap.
 *
 * @param  {Iterable} iterable - Target iterable.
 * @return {CritBitTreeMap}
 */
// CritBitTreeMap.from = function(iterable) {

// };

/**
 * Exporting.
 */
module.exports = CritBitTreeMap;


text:
/**
 *  UI module for Az.
 *
 **/

define(['modules/az-utils'], function (utils) {
    'use strict';

    /* Polyfill Custom Event */
    (function () {
        function CustomEvent(event, params) {
            params = params || {bubbles: false, cancelable: false, detail: undefined};
            var evt = document.createEvent('CustomEvent');
            evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
            return evt;
        }

        if (!window.CustomEvent) {
            CustomEvent.prototype = window.Event.prototype;
            window.CustomEvent = CustomEvent;
        }
    })();

    var NAMESPACE = 'az.ui';

    /**
     * Template Engine via Krasimir Tsonev
     * https://github.com/krasimir/absurd/blob/master/lib/processors/html/helpers/TemplateEngine.js
     * Usage: render( '{{ this.foo }}' , { foo: 'bar' });
     * @param {string} tpl
     * @param context
     */
    var render = function (tpl, context) {
        var re = /\{\{([^%>]+)?}}/g,
            reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g,
            code = 'var r=[];\n',
            cursor = 0,
            match,
            add = function(line, js) {
                js? (code += line.match(reExp) ? line + '\n' : 'r.push(' + line + ');\n') :
                    (code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');
                return add;
            };
        while(match = re.exec(tpl)) {
            add(tpl.slice(cursor, match.index))(match[1], true);
            cursor = match.index + match[0].length;
        }
        add(tpl.substr(cursor, tpl.length - cursor));
        code += 'return r.join("");';
        return new Function(code.replace(/[\r\t\n]/g, '')).apply(context);
    };

    /*
     * Inspired via Atom https://github.com/theshock/atomjs
     */
    var dom = {
            regexp: {
                'tag': /^[-_a-z0-9]+$/i,
                'class': /^\.[-_a-z0-9]+$/i,
                'id': /^#[-_a-z0-9]+$/i
            },

            ready: false,
            readyQueue: [],
            readyCallback: function () {
                if (!dom.ready) {
                    dom.ready = true;

                    for (var i = 0; i < dom.readyQueue.length; i++) {
                        dom.readyQueue[i]();
                    }

                    dom.readyQueue = [];
                }
            },

            camelCase: function (str) {
                return String(str).replace(/-\D/g, function (match) {
                    return match[1].toUpperCase();
                });
            },

            hyphenate: function (str) {
                return String(str).replace(/[A-Z]/g, function (match) {
                    return '-' + match[0].toLowerCase();
                });
            },

            each: function (elements, func) {
                elements = Array.isArray(elements) ? elements : [elements];
                Array.prototype.forEach.call(elements, func);
            },

            on: function (elements, event, callback) {
                if (elements && event && callback) {
                    dom.each(elements, function (elem) {
                        elem.addEventListener(event, callback, false);
                    });
                }
            },

            off: function (elements, event, callback) {
                if (elements && event) {
                    dom.each(elements, function (elem) {
                        elem.removeEventListener(event, callback, false);
                    });
                }
            },

            onReady: function (callback) {
                if (typeof callback === 'function') {
                    dom.ready ? setTimeout(callback, 1) : dom.readyQueue.push(callback);
                }
            },

            query: function (selector, context) {
                if (typeof selector === 'string') {
                    context = context || document;

                    if (selector.match(dom.regexp.id)) {
                        return context.getElementById(selector.substr(1));
                    } else if (selector.match(dom.regexp.class)) {
                        return context.getElementsByClassName(selector.substr(1));
                    } else if (selector.match(dom.regexp.tag)) {
                        return context.getElementsByTagName(selector);
                    } else {
                        return context.querySelectorAll(selector);
                    }
                }
            },

            is: function (element, selector) {
                var filter;

                if (!selector) {
                    return;
                }

                if (element.length) {
                    element = elements[0];
                }

                filter = dom.query(selector, element.parentNode);

                if (Array.isArray(filter) ? filter.length : filter) {
                    return utils.toArray(filter).indexOf(element) >= 0;
                } else {
                    return false;
                }
            },

            get: function (selector, context) {
                return dom.query(selector, context)[0];
            },

            isElement: function (node) {
                return !!(node && node.nodeName);
            },

            create: function (str, properties) {
                var elem;

                str = str ? str.toString() : undefined;

                if (str) {
                    if (str.indexOf('<') >=0 && str.indexOf('>') >=0) {
                        elem = document.createRange().createContextualFragment(str);
                    } else {
                        elem = document.createElement(str);

                        if (utils.typeOf(properties) === 'object') {
                            for (var i in properties) {
                                if (properties.hasOwnProperty(i)) {
                                    elem[i] = properties[i];
                                }
                            }
                        }
                    }

                    return elem;
                }
            },

            attr: function (elements, name, value) {
                if (!elements || !elements.length || !name) {
                    return;
                }

                var i = elements.length;

                if (value === undefined && dom.isElement(elements[0])) {
                    return elements[0].getAttribute(name);
                } else if (value === null) {
                    for (i; i--;) {
                        elements[i].removeAttribute(name);
                    }
                } else {
                    for (i; i--;) {
                        elements[i].setAttribute(name, value);
                    }
                }
            },

            /**
             * @private
             * Helper for addClass and removeClass
             * */
            withClass: function (elements, classes, func) {
                if (!elements && !classes) {
                    return;
                }

                if (!Array.isArray(classes)) {
                    classes = [classes];
                }

                dom.each(elements, function (elem) {
                    var elemClasses = elem.className.split(/\s+/);

                    for (var i = classes.length; i--;) {
                        func.call(undefined, elemClasses, classes[i]);
                    }

                    elem.className = elemClasses.join(' ').trim();
                });
            },

            addClass: function (elements, classes) {
                dom.withClass(elements, classes, function (all, item) {
                    if (all.indexOf(item) < 0) {
                        all.push(item);
                    }
                });
            },

            removeClass: function (elements, classes) {
                dom.withClass(elements, classes, function (all, item) {
                    for (var i = all.length; i--;) {
                        if (all[i] == item) {
                            all.splice(i, 1);
                        }
                    }
                });
            },

            hasClass: function (elements, classes) {
                if (!elements || !classes) {
                    return;
                }

                if (!Array.isArray(classes)) {
                    classes = [classes];
                }

                var result = false;

                dom.each(elements, function (elem) {
                    if (result) {
                        return;
                    }

                    var all = elem.className.split(/\s+/);

                    for (var i = classes.length; i--;) {
                        if (all.indexOf(classes[i]) < 0) {
                            return;
                        }
                    }

                    result = true;
                });

                return result;
            },

            css: function (elements, styles) {
                if (!elements) {
                    return;
                }

                var result = {},
                    i;

                if (!styles) {
                    for (i in styles) {
                        if (styles.hasOwnProperty(i)) {
                            result[i] = window.getComputedStyle(elements[0], '').getPropertyValue(dom.hyphenate(i));
                        }
                    }

                    return result;
                } else if (typeof styles === 'string') {
                    return window.getComputedStyle(elements[0], '').getPropertyValue(dom.hyphenate(styles));
                }

                dom.each(elements, function (elem) {
                    for (i in styles) {
                        if (styles.hasOwnProperty(i)) {
                            elem.style[dom.camelCase(i)] = styles[i];
                        }
                    }
                });
            },

            empty: function (elements) {
                dom.each(elements, function (elem) {
                    while (elem.hasChildNodes()) {
                        elem.removeChild(elem.firstChild);
                    }
                });
            },

            destroy: function (elements) {
                dom.each(elements, function (elem) {
                    if (elem.parentNode) {
                        elem.parentNode.removeChild(elem);
                    }
                });
            },

            offset: function (element) {
                element = element.length ? element[0] : element;

                if (element.offsetX != null) {
                    return {
                        x: element.offsetX,
                        y: element.offsetY
                    };
                }

                var box = element.getBoundingClientRect(),
                    body    = document.body,
                    docElem = document.documentElement,
                    scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft,
                    scrollTop  = window.pageYOffset || docElem.scrollTop  || body.scrollTop,
                    clientLeft = docElem.clientLeft || body.clientLeft    || 0,
                    clientTop  = docElem.clientTop  || body.clientTop     || 0;

                return {
                    x: Math.round(box.left + scrollLeft - clientLeft),
                    y: Math.round(box.top  + scrollTop  - clientTop )
                };
            },

            appendTo: function (elements, target) {
                var fragment = document.createDocumentFragment();

                dom.each(elements, function (elem) {
                    fragment.appendChild(elem);
                });
                target.appendChild(fragment);
            },

            appendBefore: function (elements, target) {
                var fragment = document.createDocumentFragment();

                dom.each(elements, function (elem) {
                    fragment.appendChild(elem);
                });
                target.parentNode.insertBefore(fragment, target);
            },

            appendAfter: function (elements, target) {
                var parent = target.parentNode,
                    next = target.nextSibling,
                    fragment = document.createDocumentFragment();

                dom.each(elements, function (elem) {
                    fragment.appendChild(elem);
                });

                if (next) {
                    parent.insertBefore(fragment, next);
                } else {
                    parent.appendChild(fragment);
                }

                return this;
            }
        };

    var settings = {
            heading: 'Название игры', // допускается HTML-код
            location: 'Название локации', // название локации
            theme: '',   // путь к css-файлу со стилями, относительно index.html,
            placeholder: '>',
            executeTitle: 'Выполнить',
            gameLookTitle: 'Осмотреться',
            gameInventoryTitle: 'Инвентарь',
            // Шаблон интерфейса
            template: '\

{{ this.title }}
\

{{ this.location }}
\
                       \

\
                       \

\

\

\
                                   <input type="text" class="az-inputs__text" placeholder="{{ this.placeholder }}">\
                                   <button type="button" class="az-inputs__btn az-inputs__execute" title="{{ this.executeTitle }}"></button>\
                                   <button type="button" class="az-inputs__btn az-inputs__game-look" title="{{ this.gameLookTitle }}"></button>\
                                   <button type="button" class="az-inputs__btn az-inputs__game-inv" title="{{ this.gameInventoryTitle }}"></button>\

\

\
                       ',
            templateSuggestion: '{{ this }}'
        },

        selectors = {
            main: '.az-main',
            heading: '.az-title',
            location: '.az-location',
            story: '.az-story',
            suggestions: '.az-suggestions',
            suggestionItem: '.az-suggestions__item',
            input: '.az-inputs__text',
            execute: '.az-inputs__execute',
            gameLook: '.az-inputs__game-look',
            gameInventory: '.az-inputs__game-inv'
        },
        classes = {
            main: 'az-main'
        },
        elements = {
            // Заполняются в renderView
        },

        /**
         * Строим базовый интерфейс игры.
         */
        renderView = function () {
            var main = dom.create('div', {
                    id: classes.main,
                    className: classes.main,
                    innerHTML: render(settings.template, settings)
                });

            document.body.appendChild(main);

            utils.extend(elements, {
                main: main,
                heading: dom.get(selectors.heading, main),
                location: dom.get(selectors.location, main),
                story: dom.get(selectors.story, main),
                suggestions: dom.get(selectors.suggestions, main),
                input: dom.get(selectors.input, main),
                execute: dom.get(selectors.execute, main),
                gameLook: dom.get(selectors.gameLook, main),
                gameInventory: dom.get(selectors.gameInventory, main)
            });
        },

        /**
         * Изменение настроек интерфейса
         * @param options
         */
        changeSettings = function (options) {
            options = options || {};
            utils.extend(settings, options);
        },

        /**
         * Изменение placeholder у поля ввода
         * @param {string} text
         */
        setPlaceholder = function (text) {
            if (!text) {
                return;
            }

            changeSettings({ placeholder: text });
            elements.input.placeholder = text;
        },

        /**
         * Изменение заголовка игры
         * @param {string} text Заголовок игры, допускается HTML-код
         */
        setTitle = function (text) {
            if (!text) {
                return;
            }

            changeSettings({ heading: text });
            elements.heading.innerHtml = text;
        },

        /**
         * Изменение заголовка локации
         * @param {string} text Заголовок локации, допускается HTML-код
         */
        setLocation = function (text) {
            if (!text) {
                return;
            }

            changeSettings({ location: text });
            elements.location.innerHtml = text;
        },

        /**
         * Добавить фрагмент текста
         * @param text Текст, допускается HTML-код
         * @param template Шаблон для функции render.
         */
        write = function (text, template) {
            if (!text) {
                return;
            }

            template = template ? ' ' + template : '
{{ this }}
';
            dom.appendTo( dom.create(render(template, text)), elements.story );
            window.scrollTo(0, window.outerHeight);
        },

        /**
         * Очистка текста
         */
        clear = function () {
            elements.story.innerHTML = '';
        },

        /**
         * Вывести догадки парсера
         * @param {Array} data Массив догадок
         */
        setSuggestions = function (data) {
            var i = 0,
                result = '';

            if (data && Array.isArray(data)) {
                for (i; i < data.length; i++) {
                    result += render(settings.templateSuggestion, data[i]);
                }

                elements.suggestions.innerHTML = result;
                elements.suggestions.style.display = 'block';
            }
        },

        /**
         * Применение догадки
         * @param {string} text Текст догадки
         */
        applySuggestion = function (text) {
            var value,
                words;

            if (text && typeof text === 'string') {
                text.trim();
                value = elements.input.value.trim().replace(/\s+/g, ' ');
                words = value.split(' ');
                words[words.length - 1] = text;
                elements.input.value = words.join(' ');
                elements.input.focus();
                clearSuggestions();
            }
        },

        /**
         * Очистка догадок
         */
        clearSuggestions = function () {
            elements.suggestions.innerHTML = '';
            elements.suggestions.style.display = 'none';
        },

        /**
         * Обработчик ввода команды
         * @param text
         */
        submitInput = function (text) {
            text = text || elements.input.value.trim();

            clearInput();
            clearSuggestions();
            text && triggerEvent('submit', { value: text });
        },

        /**
         * Очистка поля ввода
         */
        clearInput = function () {
            elements.input.value = '';
        },

        /**
         * Вызов события интерфейса
         * @param event Имя события
         * @param data Объект данных события
         */
        triggerEvent = function (event, data) {
            var eventObj;

            data = utils.typeOf(data) === 'object' ? data : {};

            if (event) {
                eventObj = new document.defaultView.CustomEvent(NAMESPACE + '.' + event, { detail: data });
                document.dispatchEvent(eventObj);
            }
        },

        /**
         * Подписка на событие
         * @param event Имя события
         * @param callback Обработчик
         */
        on = function (event, callback) {
            dom.on(document, event, callback);
        },

        handleEvents = function () {
            dom.on(elements.input, 'keydown', function (event) {
                var key = event.keyCode,
                    item;

                if (key === 13) { // Enter
                    submitInput();
                } else if (key === 27) {
                    clearInput();
                } else if (key === 9) {
                    event.preventDefault();
                    item = dom.query(selectors.suggestionItem)[0];

                    if (item) {
                        applySuggestion(item.innerHTML);
                    }
                }
            });

            dom.on(elements.input, 'input', function (event) {
                triggerEvent('input', { text : elements.input.value.trim() });
            });

            dom.on(elements.execute, 'click', function () {
                submitInput();
            });

            dom.on(elements.gameLook, 'click', function () {
                submitInput('Осмотреться');
            });

            dom.on(elements.gameInventory, 'click', function () {
                submitInput('Инвентарь');
            });

            dom.on(elements.suggestions, 'click', function (event) {
                if (dom.is(event.target, selectors.suggestionItem)) {
                    applySuggestion(event.target.innerHTML.trim());
                }
            });
        },

        /**
         * Инициализация интерфейса игры
         * @param options Настройки интерфейса. Значения по умолчанию см. в переменной settings.
         * @param callback Функция, вызываемая после инициализации интерфейса.
         * */
        init = function (options, callback) {
            dom.onReady(function () {
                changeSettings(options);
                renderView();
                handleEvents();
                clearSuggestions();
                elements.input.focus();
                callback && callback();
            });
        };

    if (document.readyState == "complete") {
        dom.ready = true;
        dom.readyCallback();
    } else {
        document.addEventListener('DOMContentLoaded', dom.readyCallback, false);
        window.addEventListener('load', dom.readyCallback, false);
    }

    return {
        dom: dom,
        setTitle: setTitle,
        setLocation: setLocation,
        setPlaceholder: setPlaceholder,
        write: write,
        clear: clear,
        clearInput: clearInput,
        setSuggestions: setSuggestions,
        render: render,
        on: on,
        init: init
    };
});

redpajama_set_name: RedPajamaGithub


text:
require "spec_helper"
require "hamster/vector"

describe Hamster::Vector do
  describe "#first" do
    [
      [[], nil],
      [["A"], "A"],
      [%w[A B C], "A"],
      [(1..32), 1],
    ].each do |values, expected|
      describe "on #{values.inspect}" do
        it "returns #{expected.inspect}" do
          Hamster.vector(*values).first.should == expected
        end
      end
    end
  end
end


text:
@implementation CLLocation (VCHDistance)

+ (CLLocationDistance)vch_distanceFromCoordinates:(const CLLocationCoordinate2D *)coords count:(NSUInteger)count {
    CLLocationDistance distance = 0;
    for (NSUInteger i = 0; i < count - 1; i++) {
        distance += [self vch_distanceFromCoordinate:coords[i] to:coords[i + 1]];
    }
    return distance;
}

+ (CLLocationDistance)vch_distanceFromCoordinate:(CLLocationCoordinate2D)fromCoord to:(CLLocationCoordinate2D)toCoord {
    @autoreleasepool {
        CLLocation *loc0 = [[CLLocation alloc] initWithLatitude:fromCoord.latitude longitude:fromCoord.longitude];
        CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:toCoord.latitude longitude:toCoord.longitude];
        return [loc0 distanceFromLocation:loc1];
    }
}

@end


text:
import unittest
import json
import sys
import os
import uuid
import logging
import time

# Our imports
import emission.tests.common

# Technically, unit tests should only test one piece of functionality
# I am breaking that rule here to test both the put and the get at the same time, because:
# a) we get to ensure that the put and get are consistent
# b) otherwise, we would have to replicate the "get" code here

import emission.net.usercache.abstract_usercache as ucauc # ucauc = usercache.abstract_usercache
import emission.net.api.usercache as mauc
from emission.core.get_database import get_db, get_usercache_db

class TestBuiltinUserCache(unittest.TestCase):
  def setUp(self):
    self.testUserUUID = uuid.uuid4()
    emission.tests.common.dropAllCollections(get_db())

  def tearDown(self):
    emission.tests.common.dropAllCollections(get_db())

  def testPutUserDataForPhone(self):
    uc = ucauc.UserCache.getUserCache(self.testUserUUID)
    footprintData = {"mine": 30, "avg": 40, "optimal": 50, "alldrive": 60}
    uc.putDocument("data/footprint", footprintData)

    retrievedData = mauc.sync_server_to_phone(self.testUserUUID)
    logging.debug("retrievedData = %s" % retrievedData)
    self.assertTrue(retrievedData is not None) # if it doesn't exist, the method returns None
    self.assertEquals(len(retrievedData),1)
    self.assertEquals(retrievedData[0].keys(), ["data", "metadata"])
    self.assertEquals(retrievedData[0]["data"]["mine"], 30)

  def testPutTwoSetsOfUserDataForPhone(self):
    uc = ucauc.UserCache.getUserCache(self.testUserUUID)

    footprintData = {"mine": 30, "avg": 40, "optimal": 50, "alldrive": 60}
    uc.putDocument("data/footprint", footprintData)

    gameData = {"my_score": 30, "other_scores": {'josh': 40, 'jillie': 20, 'naomi': 50}}
    uc.putDocument("data/game", gameData)

    retrievedData = mauc.sync_server_to_phone(self.testUserUUID)
    logging.debug("retrievedData = %s" % retrievedData)
    self.assertTrue(retrievedData is not None) # if it doesn't exist, the method returns None

    self.assertEqual(len(retrievedData), 2)
    self.assertTrue(retrievedData[0].keys(), ["data", "metadata"])
    self.assertTrue(retrievedData[1].keys(), ["data", "metadata"])

    for data in retrievedData:
        if data["metadata"]["key"] == "data/game":
            self.assertEqual(data["data"]["my_score"], 30)

  def testClearObsoleteDocument(self):
    self.testPutTwoSetsOfUserDataForPhone()

    uc = ucauc.UserCache.getUserCache(self.testUserUUID)
    uc.clearObsoleteDocument("data/footprint")
    uc.clearObsoleteDocument("data/game")

    retrievedData = mauc.sync_server_to_phone(self.testUserUUID)
    logging.debug("retrievedData = %s" % retrievedData)

    self.assertTrue(retrievedData is not None) # if it doesn't exist, the method returns None
    self.assertEqual(len(retrievedData), 0)

  def testGetDocumentKeyList(self):
    self.testPutTwoSetsOfUserDataForPhone()

    uc = ucauc.UserCache.getUserCache(self.testUserUUID)
    self.assertEqual(uc.getDocumentKeyList(), ["data/footprint", "data/game"])
    uc.clearObsoleteDocument("data/footprint")
    uc.clearObsoleteDocument("data/game")

    retrievedData = mauc.sync_server_to_phone(self.testUserUUID)
    logging.debug("retrievedData = %s" % retrievedData)

    self.assertTrue(retrievedData is not None) # if it doesn't exist, the method returns None
    self.assertEqual(len(retrievedData), 0)

  def testGetTwoSetsOfUserDataFromPhone(self):
    user_data_from_phone = [
      {
        "metadata": {
          "write_ts": 1435856237,
          "type": "rw-document",
          "key": "diary/mode-confirmation",
        },
        "data" : {
          "sid": "this-is-one-long-section-id",
          "mode": "walking",
        }
      },
      {
        "metadata": {
          "write_ts": 1435856337,
          "type": "rw-document",
          "key": "diary/mode-confirmation",
        },
        "data" : {
          "sid": "this-is-two-long-section-id",
          "mode": "cycling",
        }
      },
    ]

    mauc.sync_phone_to_server(self.testUserUUID, user_data_from_phone)

    uc = ucauc.UserCache.getUserCache(self.testUserUUID)
    msgs = uc.getMessage(key_list = ["diary/mode-confirmation"])
    self.assertEqual(len(msgs), 2)
    self.assertEqual(msgs[0]["data"]["mode"], "walking")

  def testPutTwoSetsOfBackgroundConfigForPhone(self):
    start_ts = time.time()
    uc = ucauc.UserCache.getUserCache(self.testUserUUID)

    pull_probes_list = ["accelerometer", "gyrometer", "linear_accelerometer"]
    uc.putDocument("config/pull_probes", pull_probes_list)

    location_config = {"accuracy": "POWER_BALANCED_ACCURACY",
                       "filter": "DISTANCE_FILTER",
                       "geofence_radius": 100,
                      }
    uc.putDocument("config/location_config", location_config)

    end_ts = time.time()

    retrievedData = mauc.sync_server_to_phone(self.testUserUUID)
    logging.debug("retrievedData = %s" % retrievedData)
    self.assertTrue(retrievedData is not None) # if it doesn't exist, the method returns None

    expectedData = [
        ["accelerometer", "gyrometer", "linear_accelerometer"],
        {
          "accuracy": "POWER_BALANCED_ACCURACY",
          "filter": "DISTANCE_FILTER",
          "geofence_radius": 100,
        }
    ]
    expectedKeys = ["config/pull_probes", "config/location_config"]

    for i, rd in enumerate(retrievedData):
        self.assertEqual(rd["data"], expectedData[i])

    for i, rd in enumerate(retrievedData):
        self.assertEqual(rd["metadata"]["key"], expectedKeys[i])

    for i, rd in enumerate(retrievedData):
        self.assertGreaterEqual(rd["metadata"]["write_ts"], start_ts) and \
            self.assertLessEqual(rd["metadata"]["write_ts"], end_ts)

  def testGetTwoSetsOfBackgroundDataFromPhone(self):
    background_data_from_phone = [
      {
        "metadata": {
          "write_ts": 1435856235,
          "type": "message",
          "key": "background/location",
        },
        "data" : { "mLat": 45.64, "mLng": 21.35, "mElapsedTime": 112233, }
      },
      {
        "metadata": {
          "write_ts": 1435886337,
          "type": "message",
          "key": "background/location",
        },
        "data" : { "mLat": 49.64, "mLng": 25.35, "mElapsedTime": 142233, }
      },
      {
        "metadata": {
          "write_ts": 1435856337,
          "type": "message",
          "key": "background/activity",
        },
        "data" : { "mode": "walking", "confidence": 90 }
      },
      {
        "metadata": {
          "write_ts": 1435886337,
          "type": "message",
          "key": "background/activity",
        },
        "data" : { "mode": "cycling", "confidence": 70 }
      },
      {
        "metadata": {
          "write_ts": 1435856337,
          "type": "message",
          "key": "background/accelerometer",
        },
        "data" : {"x": 1234, "y": 2345, "z": 3456}
      },
      {
        "metadata": {
          "write_ts": 1435886337,
          "type": "message",
          "key": "background/accelerometer",
        },
        "data" : {"x": 2345, "y": 3456, "z": 4567}
      },
    ]

    mauc.sync_phone_to_server(self.testUserUUID, background_data_from_phone)

    uc = ucauc.UserCache.getUserCache(self.testUserUUID)
    self.assertEqual(len(uc.getMessage(["background/location"])), 2)
    self.assertEqual(len(uc.getMessage(["background/activity"])), 2)
    self.assertEqual(len(uc.getMessage(["background/accelerometer"])), 2)
    self.assertEqual(uc.getMessage(["background/location"])[1]["data"]["mElapsedTime"], 142233)
    self.assertEqual(uc.getMessage(["background/activity"])[1]["data"]["mode"], "cycling")
    self.assertEqual(uc.getMessage(["background/accelerometer"])[1]["data"]["x"], 2345)

  def testClearBackgroundData(self):
    start_ts = time.time()
    background_data_from_phone = [
      {
        "metadata": {
          "write_ts": time.time(),
          "type": "message",
          "key": "background/location",
        },
        "data" : { "mLat": 45.64, "mLng": 21.35, "mElapsedTime": 112233, }
      },
      {
        "metadata": {
          "write_ts": time.time(),
          "type": "message",
          "key": "background/activity",
        },
        "data" : { "mode": "walking", "confidence": 90 }
      },
      {
        "metadata": {
          "write_ts": time.time(),
          "type": "message",
          "key": "background/accelerometer",
        },
        "data" : {"x": 1234, "y": 2345, "z": 3456}
      },
    ]

    # sleep() expects an argument in seconds. We want to sleep for 5 ms.
    time.sleep(float(5)/1000)

    background_data_from_phone_2 = [
      {
        "metadata": {
          "write_ts": time.time(),
          "type": "message",
          "key": "background/location",
        },
        "data" : { "mLat": 49.64, "mLng": 25.35, "mElapsedTime": 142233, }
      },
      {
        "metadata": {
          "write_ts": time.time(),
          "type": "message",
          "key": "background/activity",
        },
        "data" : { "mode": "cycling", "confidence": 70 }
      },
      {
        "metadata": {
          "write_ts": time.time(),
          "type": "message",
          "key": "background/accelerometer",
        },
        "data" : {"x": 2345, "y": 3456, "z": 4567}
      },
    ]

    time.sleep(float(5)/ 1000)

    # We look for entries that are > 5 secs old, so it is fine to set the
    # end_ts after all the entries have been inserted.
    end_ts = time.time()

    background_data_from_phone_3 = [
      {
        "metadata": {
          "write_ts": time.time(),
          "type": "message",
          "key": "background/location",
        },
        "data" : { "mLat": 45.64, "mLng": 21.35, "mElapsedTime": 112233, }
      },
      {
        "metadata": {
          "write_ts": time.time() + 30,
          "type": "message",
          "key": "background/location",
        },
        "data" : { "mLat": 49.64, "mLng": 25.35, "mElapsedTime": 142233, }
      },
      {
        "metadata": {
          "write_ts": time.time(),
          "type": "message",
          "key": "background/activity",
        },
        "data" : { "mode": "walking", "confidence": 90 }
      },
      {
        "metadata": {
          "write_ts": time.time() + 30,
          "type": "message",
          "key": "background/activity",
        },
        "data" : { "mode": "cycling", "confidence": 70 }
      },
      {
        "metadata": {
          "write_ts": time.time(),
          "type": "message",
          "key": "background/accelerometer",
        },
        "data" : {"x": 1234, "y": 2345, "z": 3456}
      },
      {
        "metadata": {
          "write_ts": time.time() + 30,
          "type": "message",
          "key": "background/accelerometer",
        },
        "data" : {"x": 2345, "y": 3456, "z": 4567}
      },
    ]

    mauc.sync_phone_to_server(self.testUserUUID, background_data_from_phone)
    mauc.sync_phone_to_server(self.testUserUUID, background_data_from_phone_2)
    mauc.sync_phone_to_server(self.testUserUUID, background_data_from_phone_3)

    uc = ucauc.UserCache.getUserCache(self.testUserUUID)
    tq = ucauc.UserCache.TimeQuery("write_ts", start_ts, end_ts)
    self.assertEqual(len(uc.getMessage(["background/location"], tq)), 2)
    self.assertEqual(len(uc.getMessage(["background/activity"], tq)), 2)
    self.assertEqual(len(uc.getMessage(["background/accelerometer"], tq)), 2)

    uc.clearProcessedMessages(tq, ["background/location", "background/accelerometer"])
    self.assertEqual(len(uc.getMessage(["background/accelerometer"], tq)), 0)
    self.assertEqual(len(uc.getMessage(["background/location"], tq)), 0)
    self.assertEqual(len(uc.getMessage(["background/activity"], tq)), 2)

  def testGetUUIDList(self):
    self.testGetTwoSetsOfUserDataFromPhone()
    uuid_list = ucauc.UserCache.get_uuid_list()
    self.assertEquals(uuid_list, [self.testUserUUID])

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    unittest.main()


text:
**LabMaze** is a standalone release of the same maze generator that is used by
[DeepMind Lab](https://github.com/deepmind/lab), which is a backtracking maze
generator that can be configured to simplify paths and create rooms.

The primary purpose of LabMaze is to provide Python bindings to DeepMind Lab's
maze generator, so that the generated maze layout can be used to create
navigation tasks through other libraries. This package also includes art assets
for texturing the resulting maze environment in the same style as in DeepMind
Lab.

The maze generation algorithm and code was originally designed and authored by
Charlie Beattie at DeepMind.

## Citation

If you use LabMaze in your research, we suggest that you cite the
[DeepMind Lab paper](https://arxiv.org/abs/1612.03801) along with a link to the
this GitHub repository.

## Installation from PyPI

LabMaze contains C++ code that first needs to be compiled into a Python
extension. For Python 3.6, 3.7, 3.8, and 3.9 on x64 Linux, macOS, and
Windows, we provide
[built distributions (bdist)](https://packaging.python.org/glossary/#term-built-distribution)
that can be straightforwardly installed via:

```sh
pip install labmaze
```

We also upload a
[source distribution (sdist)](https://packaging.python.org/glossary/#term-source-distribution-or-sdist)
to PyPI, which would allow LabMaze to be installed via `pip install labmaze` on
other platforms as well. However, you will first need to
[install Bazel](https://docs.bazel.build/versions/master/install.html), along
with the requisite platform-specific build toolchain as documented in the linked
page.

## Installation from GitHub repository

Alternatively, you can also use `pip` to install directly from our GitHub
repository. You will first need to
[install Bazel](https://docs.bazel.build/versions/master/install.html), along
with the requisite platform-specific build toolchain as documented in the linked
page, then install via

```sh
pip install git+git://github.com/deepmind/labmaze
```

## Example usage: random mazes

To generate a random maze:

```python
import labmaze
maze = labmaze.RandomMaze(height=11, width=13, random_seed=42)
print(maze.entity_layer)

*************
*   *   *****
*   *   *****
*           *
*** *** *** *
*           *
*   *****   *
*   *****   *
*   *****   *
*   *****   *
*************
```

By default, maze wall is represented by the `'*'` token. The `RandomMaze` object
can be re-randomized:

```python
maze.regenerate()
print(maze.entity_layer)

*************
*******     *
*******     *
*     *     *
* *** ***** *
*   *       *
*   *** *** *
*       *   *
*   *   *   *
*   *       *
*************
```

We can also generate spawn locations and goal object locations, e.g. for use in
a navigation task. These locations are also re-randomized along with the maze
layout itself when the `regenerate()` method is called.

```python
maze = labmaze.RandomMaze(height=11, width=13, random_seed=42,
                          spawns_per_room=1, objects_per_room=1)
print(maze.entity_layer)

*************
*P  *P  *****
*   * G *****
* G         *
*** *** *** *
* P      PG *
*   *****   *
*   *****   *
*   *****   *
*G  *****   *
*************
```

By default, player spawn positions are represented by the `'P'` token, and the
goal positions are represented by the `'G'` token. In the example above, one
player spawn position has been generated for each "room" in the maze. One way to
use the layout generated above be to pick one of the four spawn points at
random, but place an object at all four goal positions.

The `RandomMaze` object also contains "variation layers" that specifies how
different sections of the maze should be textured:

```python
.............
.BBB.DDD.....
.BBB.DDD.....
.BBB.DDD.....
.............
.CCC.....AAA.
.CCC.....AAA.
.CCC.....AAA.
.CCC.....AAA.
.CCC.....AAA.
.............
```

The `'.'` token represents the "default" texturing style, while each of the
alphabetical token represents distinct styles. It is up to the user to decide
how translate the suggested layout into different textures.

## Example usage: fixed-layout mazes

LabMaze also supports fixed-layout mazes that are specified via a string:

```python
MAZE_LAYOUT = """
*********
*********
*********
***   ***
***   ***
***   ***
*********
"""[1:]
maze = labmaze.FixedMazeWithRandomGoals(entity_layer=MAZE_LAYOUT)
print(maze.entity_layer)

*********
*********
*********
***   ***
***   ***
***   ***
*********
```

Spawn and goal positions can also be either specified or randomized into a
fixed-layout maze. For example, if one fixed spawn point and one randomized goal
is required:

```python
MAZE_LAYOUT = """
*********
***   ***
***   ***
*** P ***
***   ***
***   ***
*********
"""[1:]
maze = labmaze.FixedMazeWithRandomGoals(entity_layer=MAZE_LAYOUT,
                                        num_spawns=1, num_objects=1)
print(maze.entity_layer)

*********
***   ***
***   ***
*** P ***
***   ***
***G  ***
*********

maze.regenerate()
print(maze.entity_layer)

*********
***   ***
***   ***
*** PG***
***   ***
***   ***
*********
```

More generally, any spawn or goal tokens present in the fixed-layout string are
left unmodified by the maze generator. If `num_objects` is greater than the
number of goal tokens already present in the string then additional ones are
randomly generated. The same goes for `num_spawns`.

## Disclaimer

This is not an official Google product.


text:
<?php

namespace spec\Lamudi\UseCaseBundle\Processor\Input;

use Lamudi\UseCaseBundle\Processor\Input\InputProcessorInterface;
use Lamudi\UseCaseBundle\Processor\Input\JsonInputProcessor;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Symfony\Component\HttpFoundation\Request as HttpRequest;
use Symfony\Component\Serializer\Encoder\DecoderInterface;

/**
 * @mixin JsonInputProcessor
 */
class JsonInputProcessorSpec extends ObjectBehavior
{
    public function let(DecoderInterface $jsonDecoder)
    {
        $this->beConstructedWith($jsonDecoder);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('Lamudi\UseCaseBundle\Processor\Input\JsonInputProcessor');
    }

    public function it_is_an_input_processor()
    {
        $this->shouldHaveType(InputProcessorInterface::class);
    }

    public function it_does_nothing_if_input_is_not_a_symfony_http_request(DecoderInterface $jsonDecoder)
    {
        $jsonDecoder->decode(Argument::cetera())->shouldNotBeCalled();
        $this->initializeRequest(new \stdClass(), new \stdClass());
    }

    public function it_populates_the_request_with_json_body_data(HttpRequest $httpRequest, DecoderInterface $jsonDecoder)
    {
        $data = ['stringField' => 'asd', 'numberField' => 123, 'booleanField' => true, 'arrayField' => [3, 2, 1]];
        $jsonDecoder->decode(Argument::any(), 'json')->willReturn($data);

        /** @var JsonRequest $request */
        $request = $this->initializeRequest(new JsonRequest(), $httpRequest);
        $request->stringField->shouldBe($data['stringField']);
        $request->numberField->shouldBe($data['numberField']);
        $request->booleanField->shouldBe($data['booleanField']);
        $request->arrayField->shouldBe($data['arrayField']);
    }

    public function it_populates_the_request_by_mapping_json_fields_to_request_object(
        HttpRequest $httpRequest, DecoderInterface $jsonDecoder
    )
    {
        $data = ['foo' => 'qwe', 'n' => 999, 'opt' => true, 'nums' => [3, 2, 1]];
        $jsonDecoder->decode(Argument::any(), 'json')->willReturn($data);

        $options = ['map' => [
            'foo'  => 'stringField',
            'n'    => 'numberField',
            'opt'  => 'booleanField',
            'nums' => 'arrayField'
        ]];
        /** @var JsonRequest $request */
        $request = $this->initializeRequest(new JsonRequest(), $httpRequest, $options);
        $request->stringField->shouldBe($data['foo']);
        $request->numberField->shouldBe($data['n']);
        $request->booleanField->shouldBe($data['opt']);
        $request->arrayField->shouldBe($data['nums']);
    }
}

class JsonRequest
{
    public $stringField;
    public $numberField;
    public $booleanField;
    public $arrayField;
}


text:
@interface PURLogger ()

@property (nonatomic) PURLoggerConfiguration *configuration;
@property (nonatomic) PURFilter *defaultFilter;
@property (nonatomic) NSDictionary *filters;
@property (nonatomic) NSDictionary *filterReactionTagPatterns;
@property (nonatomic) NSDictionary *outputs;
@property (nonatomic) NSDictionary *outputReactionTagPatterns;

@end

@implementation PURLogger

+ (PURTagCheckingResult *)matchesTag:(NSString *)tag pattern:(NSString *)pattern
{
    if ([tag isEqualToString:pattern]) {
        return [PURTagCheckingResult successResult];
    }

    NSString *elementsSeparator = @".";
    NSString *wildcard = @"*";
    NSString *allWildcard = @"**";

    NSArray *patternElements = [pattern componentsSeparatedByString:elementsSeparator];
    NSArray *tagElements = [tag componentsSeparatedByString:elementsSeparator];
    NSString *lastPatternElement = [patternElements lastObject];

    if ([lastPatternElement isEqualToString:allWildcard]) {
        __block BOOL matched = YES;
        [patternElements enumerateObjectsUsingBlock:^(NSString *patternElement, NSUInteger idx, BOOL *stop){
            if (idx == [patternElements count] - 1) {
                return;
            }

            NSString *tagElement = tagElements[idx];
            if (![tagElement isEqualToString:patternElement]) {
                matched = NO;
                *stop = YES;
            }
        }];

        if (matched) {
            NSInteger location = [patternElements count] - 1;
            NSInteger capturedLength = [tagElements count] - location;
            NSString *capturedString = @"";
            if (capturedLength > 0) {
                capturedString = [[tagElements subarrayWithRange:NSMakeRange(location, capturedLength)] componentsJoinedByString:elementsSeparator];
            }
            return [PURTagCheckingResult successResultWithCapturedString:capturedString];
        }
    } else if ([lastPatternElement isEqualToString:wildcard]) {
        if ([tagElements count] == [patternElements count]) {
            __block BOOL matched = YES;
            [patternElements enumerateObjectsUsingBlock:^(NSString *patternElement, NSUInteger idx, BOOL *stop){
                if (idx == [patternElements count] - 1) {
                    return;
                }

                NSString *tagElement = tagElements[idx];
                if (![tagElement isEqualToString:patternElement]) {
                    matched = NO;
                    *stop = YES;
                }
            }];

            if (matched) {
                return [PURTagCheckingResult successResultWithCapturedString:[tagElements lastObject]];
            }
        }
    }

    return [PURTagCheckingResult failureResult];
}

- (instancetype)init
{
    return nil;
}

- (instancetype)initWithConfiguration:(PURLoggerConfiguration *)configuration
{
    self = [super init];
    if (self) {
        _configuration = configuration;

        [self configure];
        [self startPlugins];
    }
    return self;
}

- (void)dealloc
{
    [self shutdown];
}

- (PURLogStore *)logStore
{
    return self.configuration.logStore;
}

- (NSDate *)currentDate
{
    return [NSDate date];
}

- (void)configure
{
    PURLogStore *logStore = self.configuration.logStore;
    [logStore prepare];

    [self configureFilterPlugins];
    [self configureOutputPlugins];

    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self
                           selector:@selector(applicationDidEnterBackground:)
                               name:UIApplicationDidEnterBackgroundNotification
                             object:nil];
    [notificationCenter addObserver:self
                           selector:@selector(applicationWillEnterForeground:)
                               name:UIApplicationWillEnterForegroundNotification
                             object:nil];
}

- (void)configureFilterPlugins
{
    self.defaultFilter = [[PURFilter alloc] initWithLogger:self tagPattern:nil];

    NSMutableDictionary *filters = [NSMutableDictionary new];
    NSMutableDictionary *filterReactionTagPatterns = [NSMutableDictionary new];
    for (PURFilterSetting *setting in self.configuration.filterSettings) {
        if (![setting isKindOfClass:[PURFilterSetting class]]) {
            continue;
        }

        PURFilter *filter = [[setting.filterClass alloc] initWithLogger:self tagPattern:setting.tagPattern];
        if (![filter isKindOfClass:[PURFilter class]]) {
            continue;
        }

        [filter configure:setting.settings];
        filters[filter.identifier] = filter;
        filterReactionTagPatterns[filter.identifier] = setting.tagPattern;
    }
    self.filters = filters;
    self.filterReactionTagPatterns = filterReactionTagPatterns;
}

- (void)configureOutputPlugins
{
    NSMutableDictionary *outputs = [NSMutableDictionary new];
    NSMutableDictionary *outputReactionTagPatterns = [NSMutableDictionary new];
    for (PUROutputSetting *setting in self.configuration.outputSettings) {
        if (![setting isKindOfClass:[PUROutputSetting class]]) {
            continue;
        }

        PUROutput *output = [[setting.outputClass alloc] initWithLogger:self tagPattern:setting.tagPattern];
        if (![output isKindOfClass:[PUROutput class]]) {
            continue;
        }

        [output configure:setting.settings];
        outputs[output.identifier] = output;
        outputReactionTagPatterns[output.identifier] = setting.tagPattern;
    }
    self.outputs = outputs;
    self.outputReactionTagPatterns = outputReactionTagPatterns;
}

- (void)startPlugins
{
    for (PUROutput *output in [self.outputs allValues]) {
        [output start];
    }
}

- (void)applicationDidEnterBackground:(NSNotification *)notification
{
    for (PUROutput *output in [self.outputs allValues]) {
        [output suspend];
    }
}

- (void)applicationWillEnterForeground:(NSNotification *)notification
{
    for (PUROutput *output in [self.outputs allValues]) {
        [output resume];
    }
}

- (NSArray *)filteredLogsWithObject:(id)object tag:(NSString *)tag
{
    NSMutableArray *logs = [NSMutableArray new];

    for (NSString *identifier in self.filterReactionTagPatterns) {
        NSString *pattern = self.filterReactionTagPatterns[identifier];
        PURTagCheckingResult *result = [PURLogger matchesTag:tag pattern:pattern];

        if (!result.matched) {
            continue;
        }

        PURFilter *filter = self.filters[identifier];
        NSArray *filteredLogs = [filter logsWithObject:object tag:tag captured:result.capturedString];
        [logs addObjectsFromArray:filteredLogs];
    }

    if ([logs count] == 0) {
        return [self.defaultFilter logsWithObject:object tag:tag captured:nil];
    }
    return logs;
}

- (void)postLog:(id)object tag:(NSString *)sourceTag
{
    for (PURLog *log in [self filteredLogsWithObject:object tag:sourceTag]) {
        NSSet *reactionOutputIdentifiers = [self.outputReactionTagPatterns keysOfEntriesPassingTest:^BOOL(NSString *identifier, NSString *pattern, BOOL *stop){
            return [PURLogger matchesTag:log.tag pattern:pattern].matched;
        }];

        for (NSString *identifier in reactionOutputIdentifiers) {
            PUROutput *output = self.outputs[identifier];
            [output emitLog:log];
        }
    }
}

- (void)shutdown
{
    self.filters = nil;
    self.filterReactionTagPatterns = nil;

    for (PUROutput *output in [self.outputs allValues]) {
        [output suspend];
    }
    self.outputs = nil;
    self.outputReactionTagPatterns = nil;

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end


text:
#ifndef ENV_H
#define ENV_H

#include <QObject>
#include <QVariantMap>

class Env : public QObject
{
    Q_OBJECT

public:
    static Env *instance();

    QVariantMap asVariantMap() const;

private:
    Env();

    QVariantMap m_map;
};

#endif // ENV_H


text:
package main

import (
	"io"
	"net"
	"net/http"
	"net/url"
	"time"
)

type Client struct {
	UserAgent string
	client    *http.Client
	EndPoint  *url.URL
}

func NewClient(endpoint *url.URL) *Client {
	return &Client{
		UserAgent: "Mezasi/0.1",
		client: &http.Client{
			Transport: &http.Transport{
				Dial: func(netw, addr string) (net.Conn, error) {
					return net.DialTimeout(netw, addr, time.Duration(time.Second*300))
				},
			},
		},
		EndPoint: endpoint,
	}
}

func (c *Client) Do(req *http.Request) (*http.Response, error) {
	return c.client.Do(req)
}

func (c *Client) NewRequest(method string, pathStr string, body io.Reader) (*http.Request, error) {
	urlPath, err := url.Parse(pathStr)
	if err != nil {
		return nil, err
	}
	u := c.EndPoint.ResolveReference(urlPath)
	req, err := http.NewRequest(method, u.String(), body)
	if err != nil {
		return nil, err
	}
	req.Header.Add("User-Agent", c.UserAgent)
	return req, nil
}


text:
from __future__ import absolute_import

from sentry.interfaces.base import Interface
from sentry.interfaces.stacktrace import Stacktrace
from sentry.utils.safe import trim

__all__ = ('Threads',)

def get_stacktrace(value):
    # Special case: if the thread has no frames we set the
    # stacktrace to none.  Otherwise this will fail really
    # badly.
    if value and value.get('frames'):
        return Stacktrace.to_python(value, slim_frames=True)

class Threads(Interface):
    score = 1900

    @classmethod
    def to_python(cls, data):
        threads = []

        for thread in data.get('values') or ():
            threads.append({
                'stacktrace': get_stacktrace(thread.get('stacktrace')),
                'raw_stacktrace': get_stacktrace(thread.get('raw_stacktrace')),
                'id': trim(thread.get('id'), 40),
                'crashed': bool(thread.get('crashed')),
                'current': bool(thread.get('current')),
                'name': trim(thread.get('name'), 200),
            })

        return cls(values=threads)

    def to_json(self):
        def export_thread(data):
            rv = {
                'id': data['id'],
                'current': data['current'],
                'crashed': data['crashed'],
                'name': data['name'],
                'stacktrace': None,
            }
            if data['stacktrace']:
                rv['stacktrace'] = data['stacktrace'].to_json()
            if data['raw_stacktrace']:
                rv['raw_stacktrace'] = data['raw_stacktrace'].to_json()
            return rv

        return {
            'values': [export_thread(x) for x in self.values],
        }

    def get_api_context(self, is_public=False):
        def export_thread(data):
            rv = {
                'id': data['id'],
                'current': data['current'],
                'crashed': data['crashed'],
                'name': data['name'],
                'stacktrace': None,
                'rawStacktrace': None,
            }
            if data['stacktrace']:
                rv['stacktrace'] = data['stacktrace'].get_api_context(
                    is_public=is_public)
            if data['raw_stacktrace']:
                rv['rawStacktrace'] = data['raw_stacktrace'].get_api_context(
                    is_public=is_public)
            return rv

        return {
            'values': [export_thread(x) for x in self.values],
        }

    def get_path(self):
        return 'threads'


text:
.. index:: Style Guide

.. _Style-Guide:

Style Guide
===========

This document provides some general guidelines for writing documentation, both code and user
documents. It is by no means inclusive.

For Python coding conventions, please refer to the `Python Style Guide
<http://legacy.python.org/dev/peps/pep-0008/>`_.

.. index:: docstring standard

Standard for Coding Docstrings
------------------------------

OpenMDAO uses documentation strings, or `docstrings,` written in `reStructuredText
<http://docutils.sourceforge.net/rst.html>`_ (reST) to document code. Please follow the docstring
standard described below.

We would like to acknowledge the NumPy/SciPy standard, which we referred to
frequently when developing our own standard.

*Docstring*
+++++++++++

A docstring describes a module, function, class, or method definition. A docstring is a special
attribute of an object (``object.__doc__``) and, for consistency, is surrounded by triple
double-quotes, for example::

   """A simple iteration driver. Basically runs a workflow, passing the output
   to the input for the next iteration. Relative change and number of
   iterations are used as termination criteria.
   """

A docstring may be one line or spread over several lines. Line length should not exceed 80 characters.

*Sections of a Docstring*
++++++++++++++++++++++++++

The following sections can be included in a docstring, but in many cases, are optional.

1. **Summary (required)**

   You need at least a one-line summary that does not use variable names or the function name, for
   example::

     class ExternalCode(Component):
          """ Run an external code as a component. """

   You may want a longer summary (a few sentences) to clarify functionality. Do not discuss
   implementation details or background theory in the summary.

2. **Parameters (required)**

   These are descriptions of the function arguments, keywords, and their respective types. Parameters
   should follow the docstring summary. For the parameter types, be as precise as possible. A few
   examples of parameters, their types, and descriptions follow::

     *Parameters*

     value: ndarray
         Array of values to insert.

     row_start: integer
         Starting row for inserting the array. This is relative
         to the anchor, and can be negative.

     row_end: integer
         Final row for the array, relative to the anchor.

     field_start: integer
         Starting field in the given row_start as denoted by
         delimiter(s).

     field_end: integer
         The final field the array uses in row_end.
         We need this to figure out if the template is too small or large.

     sep: str (optional) (Currently unsupported)
         Separator to append between values if we go beyond the template.

   - Do not put a space before the colon.

   - Indent the description four spaces.

   - For consistency, please capitalize the first word of the description and put a period at the end,
     even though it is not a complete sentence. In many cases, the first part of the description,
     although a sentence fragment, will be followed by a sentence.

  In the above example, we italicized *Parameters* (indicated by the single asterisk on either side of
  the word) and used it as a heading for the parameters section. We did this merely to show how it can
  be done. Parameters and returns should be clear to users, so section headings aren't required. On
  the other hand, you might want them for the optional sections.

  If a keyword argument is not necessary, put ``optional`` (lower case) after it in parentheses::

     x: int (optional)

  Optional keyword parameters have default values that are displayed in brackets as part of the
  function signature::

     include_errors: bool (optional) [False]

  Default values can also be explained in the description::

    scaler: float (optional)
        Multiplicative scale factor applied to both sides of the constraint's boolean expression. It
	should be a positive nonzero value. Default is unity (1.0).

  When a parameter can assume only one of a fixed set of values, those values can be listed in
  braces::

     order: {'C', 'F', 'A'}
         Description of order.

  When two or more input parameters have exactly the same type, shape, and description, they can
  be combined::

    x1, x2: array_like
        Input arrays, description of x1, x2.

3. **Returns (required, if any)**

   Any returns should follow the parameters. Use the same format as for parameters.

4. **Raises (optional)**

   This section lists errors that get raised and under what conditions::

     *Raises*

     LinAlgException
          If the matrix is not numerically invertible.

   You may want to include this section for errors that aren't obvious or that have a good chance of
   getting raised.

5. **Notes (optional)**

   This section is for additional information about the code. Include any information that will be
   helpful to users.

6. **References (optional)**

   References should augment the docstring and not be required to understand it. If you have a *Notes*
   section and happened to cite references in it using the reST text ``[1]_, [2]_``, you can
   include the actual references in this section. For example, to cite the article below, include it
   as follows::

       .. [1] Keane, A. J., "Statistical Improvement Criteria for Use in Multiobjective Design
      Optimization," AIAA JOURNAL, Vol. 44, 2006, pp. 879-891.

   It will be rendered as:

   .. [1] Keane, A. J., "Statistical Improvement Criteria for Use in Multiobjective Design
	  Optimization," AIAA JOURNAL, Vol. 44, 2006, pp. 879-891.

   If possible, avoid referencing sources of a temporary nature, such as web pages. Follow the
   format above and number all references, starting from one, in the order you cite them.

7. **Examples (optional)**

   This section should illustrate usage. Use the Python doctest format.

   When providing multiple examples, separate them by blank lines. Leave blank lines
   above and below the comments explaining the examples::

     >>> np.add(1, 2)
     3

     Comment explaining the second example

     >>> np.add([1, 2], [3, 4])
     array([4, 6])

   You do not need to use the doctest markup ``<BLANKLINE>`` to indicate empty lines in the
   output.

*Other Information*
+++++++++++++++++++

- When referring to functions in the same sub-module, no prefix is needed; the tree is searched
  upwards for a match.

- Add prefixes to functions from other sub-modules appropriately. For example, when documenting
  the ``scipy.random`` module, refer to a function in ``scipy.fft`` by::

    fft.fft2: 2-D fast discrete Fourier transform

- When referring to an entirely different module::

    scipy.random.norm: Random variates, PDFs, etc.

- If there are points in the docstring that deserve special emphasis, you can use the reST directives
  for a note or warning. Syntax is:

  ::

    .. warning:: Warning text.

    .. note:: Note text.

  It is seldom necessary to use either directive, but one situation in which a warning might be useful
  is for marking a known bug that has not yet been fixed.

  .. note:: A note directive is different from the *Notes* section of a docstring. A note will
appear in a gray box.

- Line spacing and indentation are important. New paragraphs are marked with a blank
  line. Indentation in paragraphs indicates that the output is indented. Sphinx will
  complain if a paragraph appears to be indented for no reason.

General Documentation Issues
----------------------------

.. index:: underlines in reST

*Underlines (and Overlines)*
++++++++++++++++++++++++++++

This section pertains only to the user documents, not source code. Never use
underlines in source code as Sphinx will complain.

**- Document title:**

In general, underline and overline are used only for the title of document and appear
in the index for the document. In OpenMDAO, we typically use a double line for
titles as shown in the following example:

::

  ================
  Developer Guide
  ================

* The overline and underline must be the same length or you will get an error and the
  build will fail.

* If you use just underline and it is shorter than the text, you will get a warning,
  but the documents will build.

* If you use underline only and it is equal in length or longer than the text, Sphinx
  is fine with it.

**- File title:**

Use just underline for the title of a file. (This would be the Heading 1 equivalent).
For example:

::

  Overview
  ========

The double underline is preferred, but you may see a file or document that varies from
this guideline. The main thing is to be consistent throughout a file.

**- Heading Levels**

OpenMDAO documents do not have outline numbers so they look different from print
documents and because they are generally not read sequentially. While they have no
outline numbers, they do have heading levels.

In general it is preferred that the heading levels go no more than four levels deep.
If there are more than four levels, readers may forget where they are in the
hierarchy. Of course, there are always exceptions, and the subject matter should be
your guide.

When creating your document, be sure each heading level has a different underline
style, and be consistent. The following example shows how heading levels may
be set up:

::

  Heading 1     (Title of the file)
  =========

  Heading 2
  ---------

  *Heading 3*
  +++++++++++

  Heading 4
  ~~~~~~~~~

Notice that the italics designation (a set of asterisks) is used for Heading 3. Heading levels 2 and 3 are similar in size, so asterisks are used to
better designate the hierarchy.

About Heading Levels:

* If you are adding text to an existing file, you *must* use the same
  underlining scheme as the file's creator.
* If you are adding a new file to an existing document, it is not imperative (but it is
  preferred) that you use the same underlining scheme as used in the rest of the document.
  However you do it, you must be consistent.
* If you are creating a new document, you do not have to use the same underlining
  scheme as shown in the example. As long as each heading level is different and
  you are consistent, it is fine. It is better to use what you will remember.

The tech writer will review new documentation to make sure you are consistent.
Although, if you are not consistent, Sphinx will complain when you try to build.

*Italics*
++++++++++

Use italics for the following:

* Titles of books and our OpenMDAO documents (e.g., *Developer Guide*)

* The first time you refer to a term  (". . . is called a *Component*.")

* In place of quotation marks (in many cases). Before the widespread use of
  computers and desktop publishing, italics could not be designated, so quotation marks
  were used. Now italics can easily be specified and, in general, should be used in place
  of quotes, for example, when discussing a parameter in a code sample.  (If it's a
  long parameter, it might be better to use literal text.

.. index:: Python; capitalization

*Capitalization*
++++++++++++++++

Class Names
~~~~~~~~~~~~~

Always capitalize class names (e.g., Component, Assembly, Driver, Engine, etc.).
Sometimes, a  class represents a concept having the same name. In that case, the name
of the concept would generally *not* be capitalized.

Fortran
~~~~~~~~~

Capitalize only the first letter of *Fortran* unless you are
referring to a version earlier than Fortran 90, when it was known as FORTRAN (e.g.,
FORTRAN 77).

HTML
~~~~~~

This initialism stands for *HyperText Markup Language* and should be typed in
all caps.

Python
~~~~~~

Capitalize *Python* when referring to the programming language, for example, a
*Python* module. However, *python* should be lower case when it refers to an
OpenMDAO path name, script name, command, part of a URL, etc., that is lower case.

This rule also applies to other programming languages or software programs; for example,
``Enthought, Inc.`` is capitalized, but ``enthoughts.traits.api`` is not.

reStructuredText
~~~~~~~~~~~~~~~~~

Please capitalize the appropriate letters and type it as one word:
reStructuredText.

website
~~~~~~~

In our OpenMDAO documents, we will not capitalize *website* but use all lower case letters
(one word). Please **do not** use any of the following variants: *Web site, web site,* or
*Website.* Not only is *website* easier to type, but in 2003, in a survey of over 150 WordBiz Report
subscribers, 65% of those surveyed preferred *website* -- even those who thought *Web site*
was correct. And as noted in *The American Heritage Dictionary,* 4th ed., the use of
*website* reflects the trend of other technological expressions which have moved to
unhyphenated forms as they become more familiar (e.g., email, online). The main thing is
consistency, so please be consistent and use *website.*

*Numbers*
+++++++++

*  Write out numbers between zero and nine (0--9) when they are modifiers (two
   assemblies).
*  Numbers above nine may be written in digit form (12 components).
*  Numbers that are values should always be written in digit form (default value is 8).

.. _Using-Inline-Literal-Text:

*Inline Literal Text*
+++++++++++++++++++++

Inline literal test is designated by back quotes (the same computer key as the
tilde) enclosing the specified text. ``Inline literal text`` can be used in many
situations; in OpenMDAO documentation please use it to designate the following:

::

  path names: 		``/OpenMDAO/dev/shared/working_main``
  directory names:   	``docs/dev-guide``
  api names: 	 	``openmdao.main.api``
  Python packages:	``openmdao.lib``
  file names		``example.rst``

which will result in text that looks like this:

* ``/OpenMDAO/dev/shared/working_main``
* ``docs/dev-guide``
* ``openmdao.main.api``
* ``openmdao.lib``

Additionally, if a word or phrase contains an underscore (_) or a dot (.), use literal text, so it
is easier to read, e.g., ``_init_`` function, ``self.driver``, and ``optimization_constrained.py``.

*Abbreviations and Acronyms*
+++++++++++++++++++++++++++++

An acronym is a pronounceable word formed from the  initial letter or letters of major
parts of a compound term. An abbreviation is usually formed in the same way but is not
pronounced as a word. Abbreviations are often lowercase or a mix of lowercase and
uppercase. Acronyms are almost always all caps, regardless of the capitalization style
of the spelled-out form.

	| ``Abbreviation: 	mph,for miles per hour; MB/s, for megabytes per second``
	| ``Acronym: 		ROM, for read-only memory``

Acronyms and abbreviations should go in the glossary. We have one glossary and one
index for all OpenMDAO user documents.

* *When to spell out:* In general, spell out the term when you introduce it. You may
  also spell out an abbreviation or acronym if you think your audience may not be
  familiar with it.
* *How to spell out:* Generally put the spelled-out version first, with the
  abbreviation or acronym in parentheses, for example:

	| ``Internet service provider (ISP)``

  If the abbreviation or acronym is much more familiar than the spelled-out version,
  you can put the abbreviation or acronym first, followed by the spelled-out version in
  parentheses, or you can explain that the abbreviation is short for the spelled-out
  version and place the spelled-out version in italics.

   	| You can share your personal URL (Uniform Resource Locator).
	| An Internet address is sometimes called a *URL,* short for *Uniform
	  Resource Locator.*

* *File types:* Use all caps for abbreviations of file types.

	| ``JPEG file, PDF file, MP3 file``

  Filename extensions, which indicate the file type, should be in lowercase.

	| ``.jpg, .pdf, .mp3``

* *Punctuation:* Don't use periods except in abbreviations for customary (non-metric)
  units of measure and in the abbreviations U.S., a.m., and p.m.

* *Plural:* Don't add an apostrophe before the "s" when you form the plural of an
  abbreviation.

  	| ``CDs, URLs``

**Abbreviations:**

2D - Abbreviation for two-dimensional. No hyphen in the abbreviation.

3D - Abbreviation for three-dimensional. No hyphen in the abbreviation.

*Hyphens and Dashes*
+++++++++++++++++++++

**- Hyphen:**

Use a hyphen (-) for the following:

* Simple compound modifiers (twentieth-century writers) -- Do not use a hyphen with
  adverb-adjective modifiers (wholly owned subsidiary)
* Certain prefixes and suffixes	-- American English tends toward the omission of
  hyphens, particularly for certain prefixes (co-, pre-, mid-, non-, anti-, de-,
  etc.) However, a hyphen is required when a prefix is applied to a proper noun
  (un-American, non-Sphinx).
* Adjectival phrases formed by connecting numbers and words

  * Numerals or words for numbers    (320-foot wingspan, twenty-eight-year-old man)
  * Spelled out fractions	(two-thirds majority)
  * Symbols or SI units that are spelled out	(25-kilogram sphere, as opposed to 25 kg
    sphere)

* Two-word numbers less than a hundred  (twenty-nine)

.. note:: Do not put a hyphen in the word *plugin.* While *plug-in* is a correct
variation, we must be consistent, and we chose to omit the hyphen. (This
   follows the trend of omitting hyphens in technological terminology.)

**- En dash:**

Use an en dash (--) for the following:

* To indicate a range (pp. 25--36, June--July 2006, 1:00--2:00 p.m., etc. Note
  that there are no spaces on either side of the dash.

* For parenthetical expressions	-- Use an en dash (--) and leave a single space on
  either side.

* To contrast values or show a  relationship between two things (New York--London flight,
  Supreme Court's 5--4 decision)

In reST an en dash is formed by typing two hyphens (minus signs).

*Comma (in a Compound Sentence)*
++++++++++++++++++++++++++++++++++

* Use a comma before "and" when you have a compound sentence, for example:

    ``Many analysis components will require some representation of geometry, and
    that representation could vary in detail from simple parameters, e.g., length,
    up to a full 3D mesh.``

 | A comma is required before the "and" because the sentence has two independent
   clauses, i.e., each clause has a subject and a verb, making the sentence compound.

*  Do *not* use a comma before "and" when the construction is merely a compound verb,
   as in:

     ``Some of these effects were derived from empirical data and are essentially
     valid over an engine speed ranging from 1000 RPM to 6000 RPM.``

 | In this case the sentence has one subject *(some)* but two verbs *(were derived*
   and *are*). It is not a compound sentence.


text:
description("This test aims to check for typeMismatch flag and sanitization with type=email input fields.");

var i = document.createElement('input');
i.type = 'email';

function emailCheck(value, expectedValue, expectedMismatch, multiple)
{
    i.value = value;
    i.multiple = !!multiple;
    var mismatch = i.validity.typeMismatch;
    var mismatchPass = mismatch == expectedMismatch;
    var sanitizePass = i.value == expectedValue;
    var mismatchResult = '"' + value + '" is a ' + (mismatch ? 'invalid' : 'valid') + ' email address' + (multiple ? ' list. ' : '. ');
    var sanitizeResult = 'It was sanitized to "' + i.value + '"' + (sanitizePass ? '.' : ', but should be sanitized to "' + expectedValue + '"');
    var result = mismatchResult;
    if (value != expectedValue || !sanitizePass)
        result += sanitizeResult;

    if (mismatchPass && sanitizePass)
        testPassed(result);
    else
        testFailed(result);
}

var expectValid = false;
var expectInvalid = true;
var multiple = true;

debug("Valid single addresses when 'multiple' attribute is not set.");
emailCheck("something@something.com", "something@something.com", expectValid);
emailCheck("someone@localhost.localdomain", "someone@localhost.localdomain", expectValid);
emailCheck("someone@127.0.0.1", "someone@127.0.0.1", expectValid);
emailCheck("a@b.b", "a@b.b", expectValid);
emailCheck("a/b@domain.com", "a/b@domain.com", expectValid);
emailCheck("{}@domain.com", "{}@domain.com", expectValid);
emailCheck("ddjk-s-jk@asl-.com", "ddjk-s-jk@asl-.com", expectValid);
emailCheck("m*'!%@something.sa", "m*'!%@something.sa", expectValid);
emailCheck("tu!!7n7.ad##0!!!@company.ca", "tu!!7n7.ad##0!!!@company.ca", expectValid);
emailCheck("%@com.com", "%@com.com", expectValid);
emailCheck("!#$%&'*+/=?^_`{|}~.-@com.com", "!#$%&'*+/=?^_`{|}~.-@com.com", expectValid);
emailCheck(".wooly@example.com", ".wooly@example.com", expectValid);
emailCheck("wo..oly@example.com", "wo..oly@example.com", expectValid);
emailCheck("someone@do-ma-in.com", "someone@do-ma-in.com", expectValid);
emailCheck("someone@do-.com", "someone@do-.com", expectValid);
emailCheck("somebody@-.com", "somebody@-.com", expectValid);
emailCheck("somebody@example", "somebody@example", expectValid);
emailCheck("\u000Aa@p.com\u000A", "a@p.com", expectValid);
emailCheck("\u000Da@p.com\u000D", "a@p.com", expectValid);
emailCheck("a\u000A@p.com", "a@p.com", expectValid);
emailCheck("a\u000D@p.com", "a@p.com", expectValid);
emailCheck("", "", expectValid);
emailCheck(" ", "", expectValid);
emailCheck(" a@p.com", "a@p.com", expectValid);
emailCheck("a@p.com ", "a@p.com", expectValid);
emailCheck(" a@p.com ", "a@p.com", expectValid);
emailCheck("\u0020a@p.com\u0020", "a@p.com", expectValid);
emailCheck("\u0009a@p.com\u0009", "a@p.com", expectValid);
emailCheck("\u000Ca@p.com\u000C", "a@p.com", expectValid);

debug("Invalid single addresses when 'multiple' attribute is not set.");
emailCheck("invalid:email@example.com", "invalid:email@example.com", expectInvalid);
emailCheck("@somewhere.com", "@somewhere.com", expectInvalid);
emailCheck("example.com", "example.com", expectInvalid);
emailCheck("@@example.com", "@@example.com", expectInvalid);
emailCheck("a space@example.com", "a space@example.com", expectInvalid);
emailCheck("something@ex..ample.com", "something@ex..ample.com", expectInvalid);
emailCheck("a\b@c", "a\b@c", expectInvalid);
emailCheck("someone@somewhere.com.", "someone@somewhere.com.", expectInvalid);
emailCheck("\"\"test\blah\"\"@example.com", "\"\"test\blah\"\"@example.com", expectInvalid);
emailCheck("\"testblah\"@example.com", "\"testblah\"@example.com", expectInvalid);
emailCheck("someone@somewhere.com@", "someone@somewhere.com@", expectInvalid);
emailCheck("someone@somewhere_com", "someone@somewhere_com", expectInvalid);
emailCheck("someone@some:where.com", "someone@some:where.com", expectInvalid);
emailCheck(".", ".", expectInvalid);
emailCheck("F/s/f/a@feo+re.com", "F/s/f/a@feo+re.com", expectInvalid);
emailCheck("some+long+email+address@some+host-weird-/looking.com", "some+long+email+address@some+host-weird-/looking.com", expectInvalid);
emailCheck("a @p.com", "a @p.com", expectInvalid);
emailCheck("a\u0020@p.com", "a\u0020@p.com", expectInvalid);
emailCheck("a\u0009@p.com", "a\u0009@p.com", expectInvalid);
emailCheck("a\u000B@p.com", "a\u000B@p.com", expectInvalid);
emailCheck("a\u000C@p.com", "a\u000C@p.com", expectInvalid);
emailCheck("a\u2003@p.com", "a\u2003@p.com", expectInvalid);
emailCheck("a\u3000@p.com", "a\u3000@p.com", expectInvalid);

debug("Valid single addresses when 'multiple' attribute is set.");
emailCheck("something@something.com", "something@something.com", expectValid, multiple);
emailCheck("someone@localhost.localdomain", "someone@localhost.localdomain", expectValid, multiple);
emailCheck("someone@127.0.0.1", "someone@127.0.0.1", expectValid, multiple);
emailCheck("a@b.b", "a@b.b", expectValid, multiple);
emailCheck("a/b@domain.com", "a/b@domain.com", expectValid, multiple);
emailCheck("{}@domain.com", "{}@domain.com", expectValid, multiple);
emailCheck("ddjk-s-jk@asl-.com", "ddjk-s-jk@asl-.com", expectValid, multiple);
emailCheck("m*'!%@something.sa", "m*'!%@something.sa", expectValid, multiple);
emailCheck("tu!!7n7.ad##0!!!@company.ca", "tu!!7n7.ad##0!!!@company.ca", expectValid, multiple);
emailCheck("%@com.com", "%@com.com", expectValid, multiple);
emailCheck("!#$%&'*+/=?^_`{|}~.-@com.com", "!#$%&'*+/=?^_`{|}~.-@com.com", expectValid, multiple);
emailCheck(".wooly@example.com", ".wooly@example.com", expectValid, multiple);
emailCheck("wo..oly@example.com", "wo..oly@example.com", expectValid, multiple);
emailCheck("someone@do-ma-in.com", "someone@do-ma-in.com", expectValid, multiple);
emailCheck("someone@do-.com", "someone@do-.com", expectValid, multiple);
emailCheck("somebody@-.com", "somebody@-.com", expectValid, multiple);
emailCheck("somebody@example", "somebody@example", expectValid, multiple);
emailCheck("\u0020a@p.com\u0020", "a@p.com", expectValid, multiple);
emailCheck("\u0009a@p.com\u0009", "a@p.com", expectValid, multiple);
emailCheck("\u000Aa@p.com\u000A", "a@p.com", expectValid, multiple);
emailCheck("\u000Ca@p.com\u000C", "a@p.com", expectValid, multiple);
emailCheck("\u000Da@p.com\u000D", "a@p.com", expectValid, multiple);
emailCheck("a\u000A@p.com", "a@p.com", expectValid, multiple);
emailCheck("a\u000D@p.com", "a@p.com", expectValid, multiple);
emailCheck("", "", expectValid, multiple);
emailCheck(" ", "", expectValid, multiple);
emailCheck(" a@p.com", "a@p.com", expectValid, multiple);
emailCheck("a@p.com ", "a@p.com", expectValid, multiple);
emailCheck(" a@p.com ", "a@p.com", expectValid, multiple);

debug("Invalid single addresses when 'multiple' attribute is set.");
emailCheck("invalid:email@example.com", "invalid:email@example.com", expectInvalid, multiple);
emailCheck("@somewhere.com", "@somewhere.com", expectInvalid, multiple);
emailCheck("example.com", "example.com", expectInvalid, multiple);
emailCheck("@@example.com", "@@example.com", expectInvalid, multiple);
emailCheck("a space@example.com", "a space@example.com", expectInvalid, multiple);
emailCheck("something@ex..ample.com", "something@ex..ample.com", expectInvalid, multiple);
emailCheck("a\b@c", "a\b@c", expectInvalid, multiple);
emailCheck("someone@somewhere.com.", "someone@somewhere.com.", expectInvalid, multiple);
emailCheck("\"\"test\blah\"\"@example.com", "\"\"test\blah\"\"@example.com", expectInvalid, multiple);
emailCheck("\"testblah\"@example.com", "\"testblah\"@example.com", expectInvalid, multiple);
emailCheck("someone@somewhere.com@", "someone@somewhere.com@", expectInvalid, multiple);
emailCheck("someone@somewhere_com", "someone@somewhere_com", expectInvalid, multiple);
emailCheck("someone@some:where.com", "someone@some:where.com", expectInvalid, multiple);
emailCheck(".", ".", expectInvalid, multiple);
emailCheck("F/s/f/a@feo+re.com", "F/s/f/a@feo+re.com", expectInvalid, multiple);
emailCheck("some+long+email+address@some+host-weird-/looking.com", "some+long+email+address@some+host-weird-/looking.com", expectInvalid, multiple);
emailCheck("\u000Ba@p.com\u000B", "\u000Ba@p.com\u000B", expectInvalid, multiple);
emailCheck("\u2003a@p.com\u2003", "\u2003a@p.com\u2003", expectInvalid, multiple);
emailCheck("\u3000a@p.com\u3000", "\u3000a@p.com\u3000", expectInvalid, multiple);
emailCheck("a @p.com", "a @p.com", expectInvalid, multiple);
emailCheck("a\u0020@p.com", "a\u0020@p.com", expectInvalid, multiple);
emailCheck("a\u0009@p.com", "a\u0009@p.com", expectInvalid, multiple);
emailCheck("a\u000B@p.com", "a\u000B@p.com", expectInvalid, multiple);
emailCheck("a\u000C@p.com", "a\u000C@p.com", expectInvalid, multiple);
emailCheck("a\u2003@p.com", "a\u2003@p.com", expectInvalid, multiple);
emailCheck("a\u3000@p.com", "a\u3000@p.com", expectInvalid, multiple);

debug("Valid multiple addresses when 'multiple' attribute is set.");
emailCheck("someone@somewhere.com,john@doe.com,a@b.c,a/b@c.c,ualla@ualla.127", "someone@somewhere.com,john@doe.com,a@b.c,a/b@c.c,ualla@ualla.127", expectValid, multiple);
emailCheck("tu!!7n7.ad##0!!!@company.ca,F/s/f/a@feo-re.com,m*'@a.b", "tu!!7n7.ad##0!!!@company.ca,F/s/f/a@feo-re.com,m*'@a.b", expectValid, multiple);
emailCheck(" a@p.com,b@p.com", "a@p.com,b@p.com", expectValid, multiple);
emailCheck("a@p.com ,b@p.com", "a@p.com,b@p.com", expectValid, multiple);
emailCheck("a@p.com, b@p.com", "a@p.com,b@p.com", expectValid, multiple);
emailCheck("a@p.com,b@p.com ", "a@p.com,b@p.com", expectValid, multiple);
emailCheck("   a@p.com   ,   b@p.com   ", "a@p.com,b@p.com", expectValid, multiple);
emailCheck("\u0020a@p.com\u0020,\u0020b@p.com\u0020", "a@p.com,b@p.com", expectValid, multiple);
emailCheck("\u0009a@p.com\u0009,\u0009b@p.com\u0009", "a@p.com,b@p.com", expectValid, multiple);
emailCheck("\u000Aa@p.com\u000A,\u000Ab@p.com\u000A", "a@p.com,b@p.com", expectValid, multiple);
emailCheck("\u000Ca@p.com\u000C,\u000Cb@p.com\u000C", "a@p.com,b@p.com", expectValid, multiple);
emailCheck("\u000Da@p.com\u000D,\u000Db@p.com\u000D", "a@p.com,b@p.com", expectValid, multiple);

debug("Invalid multiple addresses when 'multiple' attribute is set.");
emailCheck("someone@somewhere.com,john@doe..com,a@b,a/b@c,ualla@ualla.127", "someone@somewhere.com,john@doe..com,a@b,a/b@c,ualla@ualla.127", expectInvalid, multiple);
emailCheck("some+long+email+address@some+host:weird-/looking.com,F/s/f/a@feo+re.com,,m*'@'!%", "some+long+email+address@some+host:weird-/looking.com,F/s/f/a@feo+re.com,,m*'@'!%", expectInvalid, multiple);
emailCheck("   a @p.com   ,   b@p.com   ", "a @p.com,b@p.com", expectInvalid, multiple);
emailCheck("   a@p.com   ,   b @p.com   ", "a@p.com,b @p.com", expectInvalid, multiple);
emailCheck("\u000Ba@p.com\u000B,\u000Bb@p.com\u000B", "\u000Ba@p.com\u000B,\u000Bb@p.com\u000B", expectInvalid, multiple);
emailCheck("\u2003a@p.com\u2003,\u2003b@p.com\u2003", "\u2003a@p.com\u2003,\u2003b@p.com\u2003", expectInvalid, multiple);
emailCheck("\u3000a@p.com\u3000,\u3000b@p.com\u3000", "\u3000a@p.com\u3000,\u3000b@p.com\u3000", expectInvalid, multiple);
emailCheck(",,", ",,", expectInvalid, multiple);
emailCheck(" ,,", ",,", expectInvalid, multiple);
emailCheck(", ,", ",,", expectInvalid, multiple);
emailCheck(",, ", ",,", expectInvalid, multiple);
emailCheck("  ,  ,  ", ",,", expectInvalid, multiple);
emailCheck("\u0020,\u0020,\u0020", ",,", expectInvalid, multiple);
emailCheck("\u0009,\u0009,\u0009", ",,", expectInvalid, multiple);
emailCheck("\u000A,\u000A,\u000A", ",,", expectInvalid, multiple);
emailCheck("\u000B,\u000B,\u000B", "\u000B,\u000B,\u000B", expectInvalid, multiple);
emailCheck("\u000C,\u000C,\u000C", ",,", expectInvalid, multiple);
emailCheck("\u000D,\u000D,\u000D", ",,", expectInvalid, multiple);
emailCheck("\u2003,\u2003,\u2003", "\u2003,\u2003,\u2003", expectInvalid, multiple);
emailCheck("\u3000,\u3000,\u3000", "\u3000,\u3000,\u3000", expectInvalid, multiple);


text:
import os
import sys

# Add a temporary path so that we can import the funfactory
tmp_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                        'vendor', 'src', 'funfactory')
sys.path.append(tmp_path)

from funfactory import manage

# Let the path magic happen in setup_environ() !
sys.path.remove(tmp_path)

manage.setup_environ(__file__)

if __name__ == "__main__":
    manage.main()


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using System.Threading.Tasks.Dataflow;

namespace Squidex.Infrastructure.Tasks;

public class PartitionedActionBlockTests
{
    private const int Partitions = 10;

    [Fact]
    public async Task Should_propagate_in_order()
    {
        var lists = new List<int>[Partitions];

        for (var i = 0; i < Partitions; i++)
        {
            lists[i] = new List<int>();
        }

        var block = new PartitionedActionBlock<(int P, int V)>(x =>
        {
            Random.Shared.Next(10);

            lists[x.P].Add(x.V);

            return Task.CompletedTask;
        }, x => x.P, new ExecutionDataflowBlockOptions
        {
            MaxDegreeOfParallelism = 100,
            MaxMessagesPerTask = 1,
            BoundedCapacity = 100
        });

        for (var i = 0; i < Partitions; i++)
        {
            for (var j = 0; j < 10; j++)
            {
                await block.SendAsync((i, j));
            }
        }

        block.Complete();

        await block.Completion;

        foreach (var list in lists)
        {
            Assert.Equal(Enumerable.Range(0, 10).ToList(), list);
        }
    }
}


text:
<!-- layout: archive -->
title: "Mianlun Zheng (郑棉仑)"
permalink: /cv/
author_profile: true
redirect_from:
  - /resume
---

{% include base_path %}

[Click to View My Up-to-date Curriculum Vitae [PDF]](/files/CV.pdf)


text:
//
//  CMImagePickerController.h
//  ImagePickerTool
//
//  Created by pro on 16/4/12.
//  Copyright © 2016年 CM. All rights reserved.
//

#import <UIKit/UIKit.h>

@protocol CMImagePickerControllerDelegate;
@class CMImagePickerController;
@import Photos;

@protocol CMImagePickerControllerDelegate <NSObject>

/**
 *  图像选择完成代理方法
 *
 *  @param picker         图像选择控制器
 *  @param images         用户选中图像数组
 *  @param selectedAssets 选中素材数组,方便重新定位图像
 */
- (void)imagePickerController:(CMImagePickerController *)picker didFinishPickingWithSelectedImages:(NSArray <UIImage *> *)images selectedAssets:(NSMutableArray<PHAsset *>*)selectedAssets;

@end

@interface CMImagePickerController : UINavigationController

/**
 *  构造函数
 *
 *  @param selectAssets 选中素材数组,可以用于预览之前选中的照片集合
 *
 *  @return 图像选择控制器
 */
-(instancetype)initWithSelectAssets:(NSMutableArray <PHAsset *>*)selectAssets;

/**
 *  加载图像尺寸(以像素为单位,默认大小 600 * 600)
 */
@property (nonatomic) CGSize targetSize;

/**
 *  最大选中图片数
 */
@property (nonatomic) NSInteger maxPickerCount;

@property(nonatomic, weak) id <CMImagePickerControllerDelegate> pickerDelegate;
@end