text:
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc);
    switch (arguments.length) {
        case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);
        case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);
        case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);
    }
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Injectable } from 'angular2/angular2';
import { OverlayController } from '../overlay/overlay-controller';
import { Config } from '../../config/config';
import { Animation } from '../../animations/animation';
import { extend } from 'ionic/util';
/**
 * The Modal is a content pane that can go over the user's current page.
 * Usually used for making a choice or editing an item. A modal can be opened
 * similar to how NavController#push works, where it is passed a Page component,
 * along with optional Page params, and options for presenting the modal.
 *
 * @usage
 * ```ts
 * class MyApp {
 *
 *  constructor(modal: Modal) {
 *    this.modal = modal;
 *  }
 *
 *  openContactModal() {
 *    this.modal.open(ContactUs);
 *  }
 *
 *  openProfileModal() {
 *    this.modal.open(Profile, { userId: 8675309 }, {
 *      enterAnimation: 'my-fade-in',
 *      leaveAnimation: 'my-fade-out',
 *      handle: 'profile-modal'
 *    });
 *  }
 *
 * }
 * ```
 */
export let Modal = class {
    constructor(ctrl, config) {
        this.ctrl = ctrl;
        this.config = config;
    }
    /**
     * Opens a new modal using the page component is was pass as the first
     * argument. This is similar to how NavController's `push` method works.
     * Currently you must have `<ion-overlay>` in the @App component's template
     * for the modal to work correctly. (This is something that will
     * be hopefully be removed in the near future.)
     * @param pageComponent  The Page component to load in the modal.
     * @param {Object} [params={}]  Optional data which can be passed to the page
     * component, which can be read from the constructor's `NavParams`.
     * @param {Object} [opts={}]  Additional options for this one modal instance of.
     * Options include `enterAnimation` and `leaveAnimation`, which
     * allows customization of which animation to use.
     * @returns {Promise} Returns a promise which resolves when the modal has
     * loaded and its entering animation has completed. The resolved promise's
     * value is the instance of the newly created modal.
     */
    open(pageComponent, params = {}, opts = {}) {
        opts = extend({
            pageType: OVERLAY_TYPE,
            enterAnimation: this.config.get('modalEnter'),
            leaveAnimation: this.config.get('modalLeave'),
        }, opts);
        return this.ctrl.open(pageComponent, params, opts);
    }
    /**
     * Get the instance of a modal. This is usually helpful to getting ahold of a
     * certain modal, from anywhere within the app, and closing it. By calling
     * just `get()` without a `handle` argument, it'll return the active modal
     * on top (it is possible to have multipe modals opened at the same time).
     * If getting just the active modal isn't enough, when creating
     * a modal, it's options can be given a `handle`, which is simply a string-based
     * name for the modal instance. You can later get a reference to that modal's
     * instance by calling this method with the same handle name.
     * @param  [handle]  Optional string name given in the modal's options when it was opened.
     * @returns Returns the instance of the modal if it is found, otherwise `null`.
     */
    get(handle) {
        if (handle) {
            return this.ctrl.getByHandle(handle);
        }
        return this.ctrl.getByType(OVERLAY_TYPE);
    }
};
Modal = __decorate([
    Injectable(),
    __metadata('design:paramtypes', [(typeof (_a = typeof OverlayController !== 'undefined' && OverlayController) === 'function' && _a) || Object, (typeof (_b = typeof Config !== 'undefined' && Config) === 'function' && _b) || Object])
], Modal);
const OVERLAY_TYPE = 'modal';
/**
 * Animations for modals
 */
class ModalSlideIn extends Animation {
    constructor(enteringView, leavingView, opts) {
        super(enteringView.pageRef(), opts);
        this
            .easing('cubic-bezier(0.36,0.66,0.04,1)')
            .duration(400)
            .fromTo('translateY', '100%', '0%')
            .before.addClass('show-page');
    }
}
Animation.register('modal-slide-in', ModalSlideIn);
class ModalSlideOut extends Animation {
    constructor(enteringView, leavingView, opts) {
        super(leavingView.pageRef(), opts);
        this
            .easing('ease-out')
            .duration(250)
            .fromTo('translateY', '0%', '100%');
    }
}
Animation.register('modal-slide-out', ModalSlideOut);
class ModalMDSlideIn extends Animation {
    constructor(enteringView, leavingView, opts) {
        super(enteringView.pageRef(), opts);
        this
            .easing('cubic-bezier(0.36,0.66,0.04,1)')
            .duration(280)
            .fromTo('translateY', '40px', '0px')
            .fadeIn()
            .before.addClass('show-page');
    }
}
Animation.register('modal-md-slide-in', ModalMDSlideIn);
class ModalMDSlideOut extends Animation {
    constructor(enteringView, leavingView, opts) {
        super(leavingView.pageRef(), opts);
        this
            .duration(200)
            .easing('cubic-bezier(0.47,0,0.745,0.715)')
            .fromTo('translateY', '0px', '40px')
            .fadeOut();
    }
}
Animation.register('modal-md-slide-out', ModalMDSlideOut);
var _a, _b;


text:
from . import VecEnvWrapper
from baselines.common.running_mean_std import RunningMeanStd
import numpy as np

class VecNormalize(VecEnvWrapper):
    """
    A vectorized wrapper that normalizes the observations
    and returns from an environment.
    """

    def __init__(self, venv, ob=True, ret=True, clipob=10., cliprew=10., gamma=0.99, epsilon=1e-8, eval=False):
        VecEnvWrapper.__init__(self, venv)
        self.ob_rms = RunningMeanStd(shape=self.observation_space.shape) if ob else None
        self.ret_rms = RunningMeanStd(shape=()) if ret else None
        self.clipob = clipob
        self.cliprew = cliprew
        self.ret = np.zeros(self.num_envs)
        self.gamma = gamma
        self.epsilon = epsilon
        self.eval = eval

    def step_wait(self):
        obs, rews, news, infos = self.venv.step_wait()
        self.ret = self.ret * self.gamma + rews
        obs = self._obfilt(obs)
        if self.ret_rms:
            if not self.eval :
                self.ret_rms.update(self.ret)
            rews = np.clip(rews / np.sqrt(self.ret_rms.var + self.epsilon), -self.cliprew, self.cliprew)
        self.ret[news] = 0.
        return obs, rews, news, infos

    def _obfilt(self, obs):
        if self.ob_rms:
            if not self.eval :
                self.ob_rms.update(obs)
            obs = np.clip((obs - self.ob_rms.mean) / np.sqrt(self.ob_rms.var + self.epsilon), -self.clipob, self.clipob)
            return obs
        else:
            return obs

    def reset(self):
        self.ret = np.zeros(self.num_envs)
        obs = self.venv.reset()
        return self._obfilt(obs)

    def save(self,loc):
        s = {}
        if self.ret_rms :
            s['ret_rms'] = self.ret_rms
        if self.ob_rms :
            s['ob_rms'] = self.ob_rms

        import pickle
        with open(loc+'.env_stat.pkl', 'wb') as f :
            pickle.dump(s,f)

    def load(self,loc):
        import pickle
        with open(loc+'.env_stat.pkl', 'rb') as f :
            s = pickle.load(f)

        if self.ret_rms :
            self.ret_rms = s['ret_rms']
        if self.ob_rms :
            self.ob_rms = s['ob_rms']

redpajama_set_name: RedPajamaGithub


text:
#include "core/editing/commands/TypingCommand.h"

#include "core/HTMLNames.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/dom/ElementTraversal.h"
#include "core/editing/EditingUtilities.h"
#include "core/editing/Editor.h"
#include "core/editing/PlainTextRange.h"
#include "core/editing/SelectionModifier.h"
#include "core/editing/VisiblePosition.h"
#include "core/editing/VisibleUnits.h"
#include "core/editing/commands/BreakBlockquoteCommand.h"
#include "core/editing/commands/InsertIncrementalTextCommand.h"
#include "core/editing/commands/InsertLineBreakCommand.h"
#include "core/editing/commands/InsertParagraphSeparatorCommand.h"
#include "core/editing/commands/InsertTextCommand.h"
#include "core/editing/spellcheck/SpellChecker.h"
#include "core/events/BeforeTextInsertedEvent.h"
#include "core/events/TextEvent.h"
#include "core/frame/LocalFrame.h"
#include "core/html/HTMLBRElement.h"
#include "core/layout/LayoutObject.h"

namespace blink {

namespace {

String dispatchBeforeTextInsertedEvent(const String& text,
                                       const VisibleSelection& selection) {
  String newText = text;
  if (Node* startNode = selection.start().computeContainerNode()) {
    if (rootEditableElement(*startNode)) {
      // Send BeforeTextInsertedEvent. The event handler will update text if
      // necessary.
      BeforeTextInsertedEvent* evt = BeforeTextInsertedEvent::create(text);
      rootEditableElement(*startNode)->dispatchEvent(evt);
      newText = evt->text();
    }
  }
  return newText;
}

DispatchEventResult dispatchTextInputEvent(LocalFrame* frame,
                                           const String& text) {
  if (Element* target = frame->document()->focusedElement()) {
    // Send TextInputEvent. Unlike BeforeTextInsertedEvent, there is no need to
    // update text for TextInputEvent as it doesn't have the API to modify text.
    TextEvent* event = TextEvent::create(frame->domWindow(), text,
                                         TextEventInputIncrementalInsertion);
    event->setUnderlyingEvent(nullptr);
    return target->dispatchEvent(event);
  }
  return DispatchEventResult::CanceledBeforeDispatch;
}

PlainTextRange getSelectionOffsets(LocalFrame* frame) {
  EphemeralRange range = firstEphemeralRangeOf(frame->selection().selection());
  if (range.isNull())
    return PlainTextRange();
  ContainerNode* editable =
      frame->selection().rootEditableElementOrTreeScopeRootNode();
  DCHECK(editable);
  return PlainTextRange::create(*editable, range);
}

VisibleSelection createSelection(const size_t start,
                                 const size_t end,
                                 const bool isDirectional,
                                 Element* element) {
  const EphemeralRange& startRange =
      PlainTextRange(0, static_cast<int>(start)).createRange(*element);
  DCHECK(startRange.isNotNull());
  const Position& startPosition = startRange.endPosition();

  const EphemeralRange& endRange =
      PlainTextRange(0, static_cast<int>(end)).createRange(*element);
  DCHECK(endRange.isNotNull());
  const Position& endPosition = endRange.endPosition();

  const VisibleSelection& selection =
      createVisibleSelection(SelectionInDOMTree::Builder()
                                 .setBaseAndExtent(startPosition, endPosition)
                                 .setIsDirectional(isDirectional)
                                 .build());
  return selection;
}

bool canAppendNewLineFeedToSelection(const VisibleSelection& selection) {
  Element* element = selection.rootEditableElement();
  if (!element)
    return false;

  BeforeTextInsertedEvent* event =
      BeforeTextInsertedEvent::create(String("\n"));
  element->dispatchEvent(event);
  return event->text().length();
}

}  // anonymous namespace

using namespace HTMLNames;

TypingCommand::TypingCommand(Document& document,
                             ETypingCommand commandType,
                             const String& textToInsert,
                             Options options,
                             TextGranularity granularity,
                             TextCompositionType compositionType)
    : CompositeEditCommand(document),
      m_commandType(commandType),
      m_textToInsert(textToInsert),
      m_openForMoreTyping(true),
      m_selectInsertedText(options & SelectInsertedText),
      m_smartDelete(options & SmartDelete),
      m_granularity(granularity),
      m_compositionType(compositionType),
      m_killRing(options & KillRing),
      m_openedByBackwardDelete(false),
      m_shouldRetainAutocorrectionIndicator(options &
                                            RetainAutocorrectionIndicator),
      m_shouldPreventSpellChecking(options & PreventSpellChecking) {
  updatePreservesTypingStyle(m_commandType);
}

void TypingCommand::deleteSelection(Document& document, Options options) {
  LocalFrame* frame = document.frame();
  DCHECK(frame);

  if (!frame->selection().isRange())
    return;

  if (TypingCommand* lastTypingCommand =
          lastTypingCommandIfStillOpenForTyping(frame)) {
    updateSelectionIfDifferentFromCurrentSelection(lastTypingCommand, frame);

    lastTypingCommand->setShouldPreventSpellChecking(options &
                                                     PreventSpellChecking);
    // InputMethodController uses this function to delete composition
    // selection.  It won't be aborted.
    lastTypingCommand->deleteSelection(options & SmartDelete,
                                       ASSERT_NO_EDITING_ABORT);
    return;
  }

  TypingCommand::create(document, DeleteSelection, "", options)->apply();
}

void TypingCommand::deleteKeyPressed(Document& document,
                                     Options options,
                                     TextGranularity granularity) {
  if (granularity == CharacterGranularity) {
    LocalFrame* frame = document.frame();
    if (TypingCommand* lastTypingCommand =
            lastTypingCommandIfStillOpenForTyping(frame)) {
      // If the last typing command is not Delete, open a new typing command.
      // We need to group continuous delete commands alone in a single typing
      // command.
      if (lastTypingCommand->commandTypeOfOpenCommand() == DeleteKey) {
        updateSelectionIfDifferentFromCurrentSelection(lastTypingCommand,
                                                       frame);
        lastTypingCommand->setShouldPreventSpellChecking(options &
                                                         PreventSpellChecking);
        EditingState editingState;
        lastTypingCommand->deleteKeyPressed(granularity, options & KillRing,
                                            &editingState);
        return;
      }
    }
  }

  TypingCommand::create(document, DeleteKey, "", options, granularity)->apply();
}

void TypingCommand::forwardDeleteKeyPressed(Document& document,
                                            EditingState* editingState,
                                            Options options,
                                            TextGranularity granularity) {
  // FIXME: Forward delete in TextEdit appears to open and close a new typing
  // command.
  if (granularity == CharacterGranularity) {
    LocalFrame* frame = document.frame();
    if (TypingCommand* lastTypingCommand =
            lastTypingCommandIfStillOpenForTyping(frame)) {
      updateSelectionIfDifferentFromCurrentSelection(lastTypingCommand, frame);
      lastTypingCommand->setShouldPreventSpellChecking(options &
                                                       PreventSpellChecking);
      lastTypingCommand->forwardDeleteKeyPressed(
          granularity, options & KillRing, editingState);
      return;
    }
  }

  TypingCommand::create(document, ForwardDeleteKey, "", options, granularity)
      ->apply();
}

String TypingCommand::textDataForInputEvent() const {
  if (m_commands.isEmpty() || isIncrementalInsertion())
    return m_textToInsert;
  return m_commands.back()->textDataForInputEvent();
}

void TypingCommand::updateSelectionIfDifferentFromCurrentSelection(
    TypingCommand* typingCommand,
    LocalFrame* frame) {
  DCHECK(frame);
  VisibleSelection currentSelection = frame->selection().selection();
  if (currentSelection == typingCommand->endingSelection())
    return;

  typingCommand->setStartingSelection(currentSelection);
  typingCommand->setEndingVisibleSelection(currentSelection);
}

void TypingCommand::insertText(Document& document,
                               const String& text,
                               Options options,
                               TextCompositionType composition,
                               const bool isIncrementalInsertion) {
  LocalFrame* frame = document.frame();
  DCHECK(frame);

  if (!text.isEmpty())
    document.frame()->spellChecker().updateMarkersForWordsAffectedByEditing(
        isSpaceOrNewline(text[0]));

  insertText(document, text, frame->selection().selection(), options,
             composition, isIncrementalInsertion);
}

void TypingCommand::adjustSelectionAfterIncrementalInsertion(
    TypingCommand* command,
    LocalFrame* frame,
    const size_t start,
    const size_t end) {
  // TODO(xiaochengh): The use of updateStyleAndLayoutIgnorePendingStylesheets
  // needs to be audited. see http://crbug.com/590369 for more details.
  frame->document()->updateStyleAndLayoutIgnorePendingStylesheets();

  Element* element = frame->selection().selection().rootEditableElement();
  DCHECK(element);

  const VisibleSelection& selection = createSelection(
      start, end, command->endingSelection().isDirectional(), element);

  if (selection != frame->selection().selection()) {
    command->setEndingVisibleSelection(selection);
    frame->selection().setSelection(selection);
  }
}

// FIXME: We shouldn't need to take selectionForInsertion. It should be
// identical to FrameSelection's current selection.
void TypingCommand::insertText(Document& document,
                               const String& text,
                               const VisibleSelection& selectionForInsertion,
                               Options options,
                               TextCompositionType compositionType,
                               const bool isIncrementalInsertion) {
  LocalFrame* frame = document.frame();
  DCHECK(frame);

  VisibleSelection currentSelection = frame->selection().selection();

  String newText = text;
  if (compositionType != TextCompositionUpdate)
    newText = dispatchBeforeTextInsertedEvent(text, selectionForInsertion);

  if (compositionType == TextCompositionConfirm) {
    if (dispatchTextInputEvent(frame, newText) !=
        DispatchEventResult::NotCanceled)
      return;
  }

  // Do nothing if no need to delete and insert.
  if (selectionForInsertion.isCaret() && newText.isEmpty())
    return;

  // TODO(xiaochengh): The use of updateStyleAndLayoutIgnorePendingStylesheets
  // needs to be audited. see http://crbug.com/590369 for more details.
  document.updateStyleAndLayoutIgnorePendingStylesheets();

  const PlainTextRange selectionOffsets = getSelectionOffsets(frame);

  // Set the starting and ending selection appropriately if we are using a
  // selection that is different from the current selection.  In the future, we
  // should change EditCommand to deal with custom selections in a general way
  // that can be used by all of the commands.
  if (TypingCommand* lastTypingCommand =
          lastTypingCommandIfStillOpenForTyping(frame)) {
    if (lastTypingCommand->endingSelection() != selectionForInsertion) {
      lastTypingCommand->setStartingSelection(selectionForInsertion);
      lastTypingCommand->setEndingVisibleSelection(selectionForInsertion);
    }

    lastTypingCommand->setCompositionType(compositionType);
    lastTypingCommand->setShouldRetainAutocorrectionIndicator(
        options & RetainAutocorrectionIndicator);
    lastTypingCommand->setShouldPreventSpellChecking(options &
                                                     PreventSpellChecking);
    EditingState editingState;
    lastTypingCommand->m_isIncrementalInsertion = isIncrementalInsertion;
    lastTypingCommand->insertText(newText, options & SelectInsertedText,
                                  &editingState);

    if (editingState.isAborted())
      return;

    if (isIncrementalInsertion) {
      const size_t newEnd = selectionOffsets.start() + newText.length();
      const size_t newStart = (compositionType == TextCompositionUpdate)
                                  ? selectionOffsets.start()
                                  : newEnd;
      adjustSelectionAfterIncrementalInsertion(lastTypingCommand, frame,
                                               newStart, newEnd);
    }
    return;
  }

  TypingCommand* command = TypingCommand::create(document, InsertText, newText,
                                                 options, compositionType);
  bool changeSelection = selectionForInsertion != currentSelection;
  if (changeSelection) {
    command->setStartingSelection(selectionForInsertion);
    command->setEndingVisibleSelection(selectionForInsertion);
  }
  command->m_isIncrementalInsertion = isIncrementalInsertion;
  const bool aborted = !(command->apply());

  if (changeSelection) {
    command->setEndingVisibleSelection(currentSelection);
    frame->selection().setSelection(currentSelection);
    return;
  }

  if (aborted)
    return;

  if (isIncrementalInsertion) {
    const size_t newEnd = selectionOffsets.start() + newText.length();
    const size_t newStart = (compositionType == TextCompositionUpdate)
                                ? selectionOffsets.start()
                                : newEnd;
    adjustSelectionAfterIncrementalInsertion(command, frame, newStart, newEnd);
  }
}

bool TypingCommand::insertLineBreak(Document& document) {
  if (TypingCommand* lastTypingCommand =
          lastTypingCommandIfStillOpenForTyping(document.frame())) {
    lastTypingCommand->setShouldRetainAutocorrectionIndicator(false);
    EditingState editingState;
    lastTypingCommand->insertLineBreak(&editingState);
    return !editingState.isAborted();
  }

  return TypingCommand::create(document, InsertLineBreak, "", 0)->apply();
}

bool TypingCommand::insertParagraphSeparatorInQuotedContent(
    Document& document) {
  if (TypingCommand* lastTypingCommand =
          lastTypingCommandIfStillOpenForTyping(document.frame())) {
    EditingState editingState;
    lastTypingCommand->insertParagraphSeparatorInQuotedContent(&editingState);
    return !editingState.isAborted();
  }

  return TypingCommand::create(document,
                               InsertParagraphSeparatorInQuotedContent)
      ->apply();
}

bool TypingCommand::insertParagraphSeparator(Document& document) {
  if (TypingCommand* lastTypingCommand =
          lastTypingCommandIfStillOpenForTyping(document.frame())) {
    lastTypingCommand->setShouldRetainAutocorrectionIndicator(false);
    EditingState editingState;
    lastTypingCommand->insertParagraphSeparator(&editingState);
    return !editingState.isAborted();
  }

  return TypingCommand::create(document, InsertParagraphSeparator, "", 0)
      ->apply();
}

TypingCommand* TypingCommand::lastTypingCommandIfStillOpenForTyping(
    LocalFrame* frame) {
  DCHECK(frame);

  CompositeEditCommand* lastEditCommand = frame->editor().lastEditCommand();
  if (!lastEditCommand || !lastEditCommand->isTypingCommand() ||
      !static_cast<TypingCommand*>(lastEditCommand)->isOpenForMoreTyping())
    return nullptr;

  return static_cast<TypingCommand*>(lastEditCommand);
}

void TypingCommand::closeTyping(LocalFrame* frame) {
  if (TypingCommand* lastTypingCommand =
          lastTypingCommandIfStillOpenForTyping(frame))
    lastTypingCommand->closeTyping();
}

void TypingCommand::doApply(EditingState* editingState) {
  if (!endingSelection().isNonOrphanedCaretOrRange())
    return;

  if (m_commandType == DeleteKey) {
    if (m_commands.isEmpty())
      m_openedByBackwardDelete = true;
  }

  switch (m_commandType) {
    case DeleteSelection:
      deleteSelection(m_smartDelete, editingState);
      return;
    case DeleteKey:
      deleteKeyPressed(m_granularity, m_killRing, editingState);
      return;
    case ForwardDeleteKey:
      forwardDeleteKeyPressed(m_granularity, m_killRing, editingState);
      return;
    case InsertLineBreak:
      insertLineBreak(editingState);
      return;
    case InsertParagraphSeparator:
      insertParagraphSeparator(editingState);
      return;
    case InsertParagraphSeparatorInQuotedContent:
      insertParagraphSeparatorInQuotedContent(editingState);
      return;
    case InsertText:
      insertText(m_textToInsert, m_selectInsertedText, editingState);
      return;
  }

  NOTREACHED();
}

InputEvent::InputType TypingCommand::inputType() const {
  using InputType = InputEvent::InputType;

  switch (m_commandType) {
    // TODO(chongz): |DeleteSelection| is used by IME but we don't have
    // direction info.
    case DeleteSelection:
      return InputType::DeleteContentBackward;
    case DeleteKey:
      if (m_compositionType != TextCompositionNone)
        return InputType::DeleteComposedCharacterBackward;
      return deletionInputTypeFromTextGranularity(DeleteDirection::Backward,
                                                  m_granularity);
    case ForwardDeleteKey:
      if (m_compositionType != TextCompositionNone)
        return InputType::DeleteComposedCharacterForward;
      return deletionInputTypeFromTextGranularity(DeleteDirection::Forward,
                                                  m_granularity);
    case InsertText:
      return InputType::InsertText;
    case InsertLineBreak:
      return InputType::InsertLineBreak;
    case InsertParagraphSeparator:
    case InsertParagraphSeparatorInQuotedContent:
      return InputType::InsertParagraph;
    default:
      return InputType::None;
  }
}

void TypingCommand::typingAddedToOpenCommand(
    ETypingCommand commandTypeForAddedTyping) {
  LocalFrame* frame = document().frame();
  if (!frame)
    return;

  updatePreservesTypingStyle(commandTypeForAddedTyping);
  updateCommandTypeOfOpenCommand(commandTypeForAddedTyping);

  frame->editor().appliedEditing(this);
}

void TypingCommand::insertText(const String& text,
                               bool selectInsertedText,
                               EditingState* editingState) {
  if (text.isEmpty()) {
    insertTextRunWithoutNewlines(text, selectInsertedText, editingState);
    return;
  }
  // FIXME: Need to implement selectInsertedText for cases where more than one
  // insert is involved. This requires support from insertTextRunWithoutNewlines
  // and insertParagraphSeparator for extending an existing selection; at the
  // moment they can either put the caret after what's inserted or select what's
  // inserted, but there's no way to "extend selection" to include both an old
  // selection that ends just before where we want to insert text and the newly
  // inserted text.
  unsigned offset = 0;
  size_t newline;
  while ((newline = text.find('\n', offset)) != kNotFound) {
    if (newline > offset) {
      const bool notSelectInsertedText = false;
      insertTextRunWithoutNewlines(text.substring(offset, newline - offset),
                                   notSelectInsertedText, editingState);
      if (editingState->isAborted())
        return;
    }

    insertParagraphSeparator(editingState);
    if (editingState->isAborted())
      return;

    offset = newline + 1;
  }

  if (!offset) {
    insertTextRunWithoutNewlines(text, selectInsertedText, editingState);
    return;
  }

  if (text.length() > offset) {
    insertTextRunWithoutNewlines(text.substring(offset, text.length() - offset),
                                 selectInsertedText, editingState);
  }
}

void TypingCommand::insertTextRunWithoutNewlines(const String& text,
                                                 bool selectInsertedText,
                                                 EditingState* editingState) {
  CompositeEditCommand* command;
  if (isIncrementalInsertion()) {
    command = InsertIncrementalTextCommand::create(
        document(), text, selectInsertedText,
        m_compositionType == TextCompositionNone
            ? InsertIncrementalTextCommand::
                  RebalanceLeadingAndTrailingWhitespaces
            : InsertIncrementalTextCommand::RebalanceAllWhitespaces);
  } else {
    command = InsertTextCommand::create(
        document(), text, selectInsertedText,
        m_compositionType == TextCompositionNone
            ? InsertTextCommand::RebalanceLeadingAndTrailingWhitespaces
            : InsertTextCommand::RebalanceAllWhitespaces);
  }

  applyCommandToComposite(command, endingSelection(), editingState);
  if (editingState->isAborted())
    return;

  m_textToInsert = text;
  typingAddedToOpenCommand(InsertText);
}

void TypingCommand::insertLineBreak(EditingState* editingState) {
  if (!canAppendNewLineFeedToSelection(endingSelection()))
    return;

  applyCommandToComposite(InsertLineBreakCommand::create(document()),
                          editingState);
  if (editingState->isAborted())
    return;
  typingAddedToOpenCommand(InsertLineBreak);
}

void TypingCommand::insertParagraphSeparator(EditingState* editingState) {
  if (!canAppendNewLineFeedToSelection(endingSelection()))
    return;

  applyCommandToComposite(InsertParagraphSeparatorCommand::create(document()),
                          editingState);
  if (editingState->isAborted())
    return;
  typingAddedToOpenCommand(InsertParagraphSeparator);
}

void TypingCommand::insertParagraphSeparatorInQuotedContent(
    EditingState* editingState) {
  // If the selection starts inside a table, just insert the paragraph separator
  // normally Breaking the blockquote would also break apart the table, which is
  // unecessary when inserting a newline
  if (enclosingNodeOfType(endingSelection().start(), &isTableStructureNode)) {
    insertParagraphSeparator(editingState);
    return;
  }

  applyCommandToComposite(BreakBlockquoteCommand::create(document()),
                          editingState);
  if (editingState->isAborted())
    return;
  typingAddedToOpenCommand(InsertParagraphSeparatorInQuotedContent);
}

bool TypingCommand::makeEditableRootEmpty(EditingState* editingState) {
  Element* root = endingSelection().rootEditableElement();
  if (!root || !root->hasChildren())
    return false;

  if (root->firstChild() == root->lastChild()) {
    if (isHTMLBRElement(root->firstChild())) {
      // If there is a single child and it could be a placeholder, leave it
      // alone.
      if (root->layoutObject() && root->layoutObject()->isLayoutBlockFlow())
        return false;
    }
  }

  while (Node* child = root->firstChild()) {
    removeNode(child, editingState);
    if (editingState->isAborted())
      return false;
  }

  addBlockPlaceholderIfNeeded(root, editingState);
  if (editingState->isAborted())
    return false;
  setEndingSelection(SelectionInDOMTree::Builder()
                         .collapse(Position::firstPositionInNode(root))
                         .setIsDirectional(endingSelection().isDirectional())
                         .build());

  return true;
}

void TypingCommand::deleteKeyPressed(TextGranularity granularity,
                                     bool killRing,
                                     EditingState* editingState) {
  LocalFrame* frame = document().frame();
  if (!frame)
    return;

  frame->spellChecker().updateMarkersForWordsAffectedByEditing(false);

  VisibleSelection selectionToDelete;
  VisibleSelection selectionAfterUndo;

  switch (endingSelection().getSelectionType()) {
    case RangeSelection:
      selectionToDelete = endingSelection();
      selectionAfterUndo = selectionToDelete;
      break;
    case CaretSelection: {
      // After breaking out of an empty mail blockquote, we still want continue
      // with the deletion so actual content will get deleted, and not just the
      // quote style.
      bool breakOutResult =
          breakOutOfEmptyMailBlockquotedParagraph(editingState);
      if (editingState->isAborted())
        return;
      if (breakOutResult)
        typingAddedToOpenCommand(DeleteKey);

      m_smartDelete = false;
      document().updateStyleAndLayoutIgnorePendingStylesheets();

      SelectionModifier selectionModifier(*frame, endingSelection());
      selectionModifier.modify(FrameSelection::AlterationExtend,
                               DirectionBackward, granularity);
      if (killRing && selectionModifier.selection().isCaret() &&
          granularity != CharacterGranularity)
        selectionModifier.modify(FrameSelection::AlterationExtend,
                                 DirectionBackward, CharacterGranularity);

      VisiblePosition visibleStart(endingSelection().visibleStart());
      if (previousPositionOf(visibleStart, CannotCrossEditingBoundary)
              .isNull()) {
        // When the caret is at the start of the editable area in an empty list
        // item, break out of the list item.
        bool breakOutOfEmptyListItemResult =
            breakOutOfEmptyListItem(editingState);
        if (editingState->isAborted())
          return;
        if (breakOutOfEmptyListItemResult) {
          typingAddedToOpenCommand(DeleteKey);
          return;
        }
        // When there are no visible positions in the editing root, delete its
        // entire contents.
        if (nextPositionOf(visibleStart, CannotCrossEditingBoundary).isNull() &&
            makeEditableRootEmpty(editingState)) {
          typingAddedToOpenCommand(DeleteKey);
          return;
        }
        if (editingState->isAborted())
          return;
      }

      // If we have a caret selection at the beginning of a cell, we have
      // nothing to do.
      Node* enclosingTableCell =
          enclosingNodeOfType(visibleStart.deepEquivalent(), &isTableCell);
      if (enclosingTableCell &&
          visibleStart.deepEquivalent() ==
              VisiblePosition::firstPositionInNode(enclosingTableCell)
                  .deepEquivalent())
        return;

      // If the caret is at the start of a paragraph after a table, move content
      // into the last table cell.
      if (isStartOfParagraph(visibleStart) &&
          tableElementJustBefore(
              previousPositionOf(visibleStart, CannotCrossEditingBoundary))) {
        // Unless the caret is just before a table.  We don't want to move a
        // table into the last table cell.
        if (tableElementJustAfter(visibleStart))
          return;
        // Extend the selection backward into the last cell, then deletion will
        // handle the move.
        selectionModifier.modify(FrameSelection::AlterationExtend,
                                 DirectionBackward, granularity);
        // If the caret is just after a table, select the table and don't delete
        // anything.
      } else if (Element* table = tableElementJustBefore(visibleStart)) {
        setEndingSelection(
            SelectionInDOMTree::Builder()
                .collapse(Position::beforeNode(table))
                .extend(endingSelection().start())
                .setIsDirectional(endingSelection().isDirectional())
                .build());
        typingAddedToOpenCommand(DeleteKey);
        return;
      }

      selectionToDelete = selectionModifier.selection();

      if (granularity == CharacterGranularity &&
          selectionToDelete.end().computeContainerNode() ==
              selectionToDelete.start().computeContainerNode() &&
          selectionToDelete.end().computeOffsetInContainerNode() -
                  selectionToDelete.start().computeOffsetInContainerNode() >
              1) {
        // If there are multiple Unicode code points to be deleted, adjust the
        // range to match platform conventions.
        selectionToDelete.setWithoutValidation(
            selectionToDelete.end(),
            previousPositionOf(selectionToDelete.end(),
                               PositionMoveType::BackwardDeletion));
      }

      if (!startingSelection().isRange() ||
          selectionToDelete.base() != startingSelection().start()) {
        selectionAfterUndo = selectionToDelete;
      } else {
        // It's a little tricky to compute what the starting selection would
        // have been in the original document. We can't let the VisibleSelection
        // class's validation kick in or it'll adjust for us based on the
        // current state of the document and we'll get the wrong result.
        selectionAfterUndo.setWithoutValidation(startingSelection().end(),
                                                selectionToDelete.extent());
      }
      break;
    }
    case NoSelection:
      NOTREACHED();
      break;
  }

  DCHECK(!selectionToDelete.isNone());
  if (selectionToDelete.isNone())
    return;

  if (selectionToDelete.isCaret())
    return;

  if (killRing)
    frame->editor().addToKillRing(
        selectionToDelete.toNormalizedEphemeralRange());
  // On Mac, make undo select everything that has been deleted, unless an undo
  // will undo more than just this deletion.
  // FIXME: This behaves like TextEdit except for the case where you open with
  // text insertion and then delete more text than you insert.  In that case all
  // of the text that was around originally should be selected.
  if (frame->editor().behavior().shouldUndoOfDeleteSelectText() &&
      m_openedByBackwardDelete)
    setStartingSelection(selectionAfterUndo);
  CompositeEditCommand::deleteSelection(selectionToDelete, editingState,
                                        m_smartDelete);
  if (editingState->isAborted())
    return;
  setSmartDelete(false);
  typingAddedToOpenCommand(DeleteKey);
}

void TypingCommand::forwardDeleteKeyPressed(TextGranularity granularity,
                                            bool killRing,
                                            EditingState* editingState) {
  LocalFrame* frame = document().frame();
  if (!frame)
    return;

  frame->spellChecker().updateMarkersForWordsAffectedByEditing(false);

  VisibleSelection selectionToDelete;
  VisibleSelection selectionAfterUndo;

  switch (endingSelection().getSelectionType()) {
    case RangeSelection:
      selectionToDelete = endingSelection();
      selectionAfterUndo = selectionToDelete;
      break;
    case CaretSelection: {
      m_smartDelete = false;
      document().updateStyleAndLayoutIgnorePendingStylesheets();

      // Handle delete at beginning-of-block case.
      // Do nothing in the case that the caret is at the start of a
      // root editable element or at the start of a document.
      SelectionModifier selectionModifier(*frame, endingSelection());
      selectionModifier.modify(FrameSelection::AlterationExtend,
                               DirectionForward, granularity);
      if (killRing && selectionModifier.selection().isCaret() &&
          granularity != CharacterGranularity)
        selectionModifier.modify(FrameSelection::AlterationExtend,
                                 DirectionForward, CharacterGranularity);

      Position downstreamEnd =
          mostForwardCaretPosition(endingSelection().end());
      VisiblePosition visibleEnd = endingSelection().visibleEnd();
      Node* enclosingTableCell =
          enclosingNodeOfType(visibleEnd.deepEquivalent(), &isTableCell);
      if (enclosingTableCell &&
          visibleEnd.deepEquivalent() ==
              VisiblePosition::lastPositionInNode(enclosingTableCell)
                  .deepEquivalent())
        return;
      if (visibleEnd.deepEquivalent() ==
          endOfParagraph(visibleEnd).deepEquivalent())
        downstreamEnd = mostForwardCaretPosition(
            nextPositionOf(visibleEnd, CannotCrossEditingBoundary)
                .deepEquivalent());
      // When deleting tables: Select the table first, then perform the deletion
      if (isDisplayInsideTable(downstreamEnd.computeContainerNode()) &&
          downstreamEnd.computeOffsetInContainerNode() <=
              caretMinOffset(downstreamEnd.computeContainerNode())) {
        setEndingSelection(
            SelectionInDOMTree::Builder()
                .setBaseAndExtentDeprecated(
                    endingSelection().end(),
                    Position::afterNode(downstreamEnd.computeContainerNode()))
                .setIsDirectional(endingSelection().isDirectional())
                .build());
        typingAddedToOpenCommand(ForwardDeleteKey);
        return;
      }

      // deleting to end of paragraph when at end of paragraph needs to merge
      // the next paragraph (if any)
      if (granularity == ParagraphBoundary &&
          selectionModifier.selection().isCaret() &&
          isEndOfParagraph(selectionModifier.selection().visibleEnd()))
        selectionModifier.modify(FrameSelection::AlterationExtend,
                                 DirectionForward, CharacterGranularity);

      selectionToDelete = selectionModifier.selection();
      if (!startingSelection().isRange() ||
          selectionToDelete.base() != startingSelection().start()) {
        selectionAfterUndo = selectionToDelete;
      } else {
        // It's a little tricky to compute what the starting selection would
        // have been in the original document. We can't let the VisibleSelection
        // class's validation kick in or it'll adjust for us based on the
        // current state of the document and we'll get the wrong result.
        Position extent = startingSelection().end();
        if (extent.computeContainerNode() !=
            selectionToDelete.end().computeContainerNode()) {
          extent = selectionToDelete.extent();
        } else {
          int extraCharacters;
          if (selectionToDelete.start().computeContainerNode() ==
              selectionToDelete.end().computeContainerNode())
            extraCharacters =
                selectionToDelete.end().computeOffsetInContainerNode() -
                selectionToDelete.start().computeOffsetInContainerNode();
          else
            extraCharacters =
                selectionToDelete.end().computeOffsetInContainerNode();
          extent =
              Position(extent.computeContainerNode(),
                       extent.computeOffsetInContainerNode() + extraCharacters);
        }
        selectionAfterUndo.setWithoutValidation(startingSelection().start(),
                                                extent);
      }
      break;
    }
    case NoSelection:
      NOTREACHED();
      break;
  }

  DCHECK(!selectionToDelete.isNone());
  if (selectionToDelete.isNone())
    return;

  if (selectionToDelete.isCaret())
    return;

  if (killRing)
    frame->editor().addToKillRing(
        selectionToDelete.toNormalizedEphemeralRange());
  // Make undo select what was deleted on Mac alone
  if (frame->editor().behavior().shouldUndoOfDeleteSelectText())
    setStartingSelection(selectionAfterUndo);
  CompositeEditCommand::deleteSelection(selectionToDelete, editingState,
                                        m_smartDelete);
  if (editingState->isAborted())
    return;
  setSmartDelete(false);
  typingAddedToOpenCommand(ForwardDeleteKey);
}

void TypingCommand::deleteSelection(bool smartDelete,
                                    EditingState* editingState) {
  CompositeEditCommand::deleteSelection(editingState, smartDelete);
  if (editingState->isAborted())
    return;
  typingAddedToOpenCommand(DeleteSelection);
}

void TypingCommand::updatePreservesTypingStyle(ETypingCommand commandType) {
  switch (commandType) {
    case DeleteSelection:
    case DeleteKey:
    case ForwardDeleteKey:
    case InsertParagraphSeparator:
    case InsertLineBreak:
      m_preservesTypingStyle = true;
      return;
    case InsertParagraphSeparatorInQuotedContent:
    case InsertText:
      m_preservesTypingStyle = false;
      return;
  }
  NOTREACHED();
  m_preservesTypingStyle = false;
}

bool TypingCommand::isTypingCommand() const {
  return true;
}

}  // namespace blink


text:
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1, user-scalable=yes">

    <title>paper-button</title>

    <script src="bower_components/webcomponentsjs/webcomponents.js"></script>

    <link href="bower_components/font-roboto/roboto.html" rel="import">
    <link href="bower_components/core-icon/core-icon.html" rel="import">
    <link href="bower_components/core-icons/core-icons.html" rel="import">
    <link href="bower_components/paper-button/paper-button.html" rel="import">

    <style shim-shadowdom>
        body {
            font-family: RobotoDraft, 'Helvetica Neue', Helvetica, Arial;
            font-size: 14px;
            margin: 0;
            padding: 24px;
            -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
            -webkit-touch-callout: none;
        }

        section {
            padding: 20px 0;
        }

        section > div {
            padding: 14px;
            font-size: 16px;
        }

        paper-button.colored {
            color: #4285f4;
        }

        paper-button[raised].colored {
            background: #4285f4;
            color: #fff;
        }

        paper-button.custom > core-icon {
            margin-right: 4px;
        }

        paper-button.hover:hover {
            background: #eee;
        }

        paper-button.blue-ripple::shadow #ripple {
            color: #4285f4;
        }

    </style>

</head>
<body unresolved>

<section>
    <paper-button id="button_1">button</paper-button>
    <paper-button id="button_2" disabled>disabled</paper-button>
    <paper-button id="button_3" raised>raised button</paper-button>

    <paper-button id="button_4" class="colored custom">
        <core-icon icon="check"></core-icon>
        ok
    </paper-button>
</section>

</body>
</html>


text:
export KUBERNETES_PROVIDER="kubemark"
export KUBE_CONFIG_FILE="config-default.sh"

KUBE_ROOT=$(dirname "${BASH_SOURCE}")/../..

# We need an absolute path to KUBE_ROOT
ABSOLUTE_ROOT=$(readlink -f ${KUBE_ROOT})

source ${KUBE_ROOT}/cluster/kubemark/util.sh
source ${KUBE_ROOT}/cluster/kubemark/config-default.sh

echo "Kubemark master name: ${MASTER_NAME}"

detect-master

export KUBE_MASTER_URL="https://${KUBE_MASTER_IP}"
export KUBECONFIG="${ABSOLUTE_ROOT}/test/kubemark/kubeconfig.loc"
export E2E_MIN_STARTUP_PODS=0

if [ -z "$@" ]; then
	ARGS='--ginkgo.focus=should\sallow\sstarting\s30\spods\sper\snode'
else
	ARGS=$@
fi

${KUBE_ROOT}/hack/ginkgo-e2e.sh "--e2e-verify-service-account=false" "$ARGS"


text:
package org.apache.rya.indexing.geotemporal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.rya.indexing.external.matching.ExternalSetConverter;
import org.apache.rya.indexing.external.matching.JoinSegment;
import org.apache.rya.indexing.external.matching.QuerySegment;
import org.apache.rya.indexing.geotemporal.model.EventQueryNode;
import org.eclipse.rdf4j.query.algebra.Filter;
import org.eclipse.rdf4j.query.algebra.QueryModelNode;
import org.eclipse.rdf4j.query.algebra.ValueExpr;

import com.google.common.base.Preconditions;

/**
 * Implementation of {@link ExternalSetConverter} to convert {@link EventQueryNode}s
 * to {@link QuerySegment}s.
 *
 */
public class GeoTemporalToSegmentConverter implements ExternalSetConverter<EventQueryNode> {
    @Override
    public QuerySegment<EventQueryNode> setToSegment(final EventQueryNode set) {
        Preconditions.checkNotNull(set);
        final Set<QueryModelNode> matched = new HashSet<>(set.getPatterns());
        matched.addAll(set.getFilters());
        final List<QueryModelNode> unmatched = new ArrayList<>(set.getPatterns());
        return new JoinSegment<EventQueryNode>(matched, unmatched, new HashMap<ValueExpr, Filter>());
    }
}


text:
import os
from os.path import sep, join, exists
from collections import namedtuple
from subprocess import Popen, PIPE
import shutil
import re
import sys

from tools.targets import TARGET_MAP
from tools.export.exporters import Exporter, TargetNotSupportedException
import json
from tools.export.cmsis import DeviceCMSIS
from tools.utils import NotSupportedException
from multiprocessing import cpu_count

def _supported(mcu, iar_targets):
    if "IAR" not in mcu.supported_toolchains:
        return False
    if hasattr(mcu, 'device_name') and mcu.device_name in iar_targets:
        return True
    if mcu.name in iar_targets:
        return True
    return False

_iar_defs = os.path.join(
    os.path.dirname(os.path.abspath(__file__)), 'iar_definitions.json')

with open(_iar_defs, 'r') as f:
    _GUI_OPTIONS = json.load(f)

class IAR(Exporter):
    NAME = 'iar'
    TOOLCHAIN = 'IAR'

    @classmethod
    def is_target_supported(cls, target_name):
        target = TARGET_MAP[target_name]
        return _supported(target, _GUI_OPTIONS.keys())

    def iar_groups(self, grouped_src):
        """Return a namedtuple of group info
        Positional Arguments:
        grouped_src: dictionary mapping a group(str) to sources
            within it (list of file names)
        Relevant part of IAR template
        {% for group in groups %}
	    <group>
	        <name>group.name</name>
	        {% for file in group.files %}
	        <file>
	        <name>$PROJ_DIR${{file}}</name>
	        </file>
	        {% endfor %}
	    </group>
	    {% endfor %}
        """
        IARgroup = namedtuple('IARgroup', ['name','files'])
        groups = []
        for name, files in grouped_src.items():
            groups.append(IARgroup(name,files))
        return groups

    def iar_device(self):
        """Retrieve info from iar_definitions.json"""
        tgt = TARGET_MAP[self.target]
        device_name = (tgt.device_name if hasattr(tgt, "device_name") else
                       tgt.name)
        device_info = _GUI_OPTIONS[device_name]
        iar_defaults ={
            "OGChipSelectEditMenu": "",
            "CoreVariant": '',
            "GFPUCoreSlave": '',
            "GFPUCoreSlave2": 40,
            "GBECoreSlave": 35,
            "GBECoreSlave2": '',
            "FPU2": 0,
            "NrRegs": 0,
            "NEON": '',
            "CExtraOptionsCheck": 0,
            "CExtraOptions": "",
            "CMSISDAPJtagSpeedList": 0,
        }

        iar_defaults.update(device_info)
        IARdevice = namedtuple('IARdevice', iar_defaults.keys())
        return IARdevice(**iar_defaults)

    def format_file(self, file):
        """Make IAR compatible path"""
        return join('$PROJ_DIR$',file)

    def format_src(self, srcs):
        """Group source files"""
        grouped = self.group_project_files(srcs)
        for group, files in grouped.items():
            grouped[group] = [self.format_file(src) for src in files]
        return grouped

    def generate(self):
        """Generate the .eww, .ewd, and .ewp files"""
        if not self.resources.linker_script:
            raise NotSupportedException("No linker script found.")
        srcs = self.resources.headers + self.resources.s_sources + \
               self.resources.c_sources + self.resources.cpp_sources + \
               self.resources.objects + self.resources.libraries
        flags = self.flags
        c_flags = list(set(flags['common_flags']
                                    + flags['c_flags']
                                    + flags['cxx_flags']))
        # Flags set in template to be set by user in IDE
        template = ["--vla", "--no_static_destruction"]
        # Flag invalid if set in template
        # Optimizations are also set in template
        invalid_flag = lambda x: x in template or re.match("-O(\d|time|n|hz?)", x)
        flags['c_flags'] = [flag for flag in c_flags if not invalid_flag(flag)]

        try:
            debugger = DeviceCMSIS(self.target).debug.replace('-','').upper()
        except TargetNotSupportedException:
            debugger = "CMSISDAP"

        ctx = {
            'name': self.project_name,
            'groups': self.iar_groups(self.format_src(srcs)),
            'linker_script': self.format_file(self.resources.linker_script),
            'include_paths': [self.format_file(src) for src in self.resources.inc_dirs],
            'device': self.iar_device(),
            'ewp': sep+self.project_name + ".ewp",
            'debugger': debugger
        }
        ctx.update(flags)

        self.gen_file('iar/eww.tmpl', ctx, self.project_name + ".eww")
        self.gen_file('iar/ewd.tmpl', ctx, self.project_name + ".ewd")
        self.gen_file('iar/ewp.tmpl', ctx, self.project_name + ".ewp")

    @staticmethod
    def build(project_name, log_name="build_log.txt", cleanup=True):
        """ Build IAR project """
        # > IarBuild [project_path] -build [project_name]
        proj_file = project_name + ".ewp"
        cmd = ["IarBuild", proj_file, '-build', project_name]

        # IAR does not support a '0' option to automatically use all
        # available CPUs, so we use Python's multiprocessing library
        # to detect the number of CPUs available
        cpus_available = cpu_count()
        jobs = cpus_available if cpus_available else None

        # Only add the parallel flag if we're using more than one CPU
        if jobs:
            cmd += ['-parallel', str(jobs)]

        # Build the project
        p = Popen(cmd, stdout=PIPE, stderr=PIPE)
        out, err = p.communicate()
        ret_code = p.returncode

        out_string = "=" * 10 + "STDOUT" + "=" * 10 + "\n"
        out_string += out
        out_string += "=" * 10 + "STDERR" + "=" * 10 + "\n"
        out_string += err

        if ret_code == 0:
            out_string += "SUCCESS"
        else:
            out_string += "FAILURE"

        print out_string

        if log_name:
            # Write the output to the log file
            with open(log_name, 'w+') as f:
                f.write(out_string)

        # Cleanup the exported and built files
        if cleanup:
            os.remove(project_name + ".ewp")
            os.remove(project_name + ".ewd")
            os.remove(project_name + ".eww")
            # legacy output file location
            if exists('.build'):
                shutil.rmtree('.build')
            if exists('BUILD'):
                shutil.rmtree('BUILD')

        if ret_code !=0:
            # Seems like something went wrong.
            return -1
        else:
            return 0


text:
"""This module defines dep for DagRun ID validation"""

from airflow.ti_deps.deps.base_ti_dep import BaseTIDep
from airflow.utils.session import provide_session
from airflow.utils.types import DagRunType

class DagrunIdDep(BaseTIDep):
    """Dep for valid DagRun ID to schedule from scheduler"""

    NAME = "Dagrun run_id is not backfill job ID"
    IGNORABLE = True

    @provide_session
    def _get_dep_statuses(self, ti, session, dep_context=None):
        """
        Determines if the DagRun is valid for scheduling from scheduler.

        :param ti: the task instance to get the dependency status for
        :param session: database session
        :param dep_context: the context for which this dependency should be evaluated for
        :return: True if DagRun ID is valid for scheduling from scheduler.
        """
        dagrun = ti.get_dagrun(session)

        if dagrun.run_type == DagRunType.BACKFILL_JOB:
            yield self._failing_status(
                reason=f"Task's DagRun run_type is {dagrun.run_type} and cannot be run by the scheduler"
            )


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

const fs = require("fs");
const rxjs_1 = require("rxjs");
const operators_1 = require("rxjs/operators");
const src_1 = require("../src");
// This will only be initialized if the watch() method is called.
// Otherwise chokidar appears only in type positions, and shouldn't be referenced
// in the JavaScript output.
let FSWatcher;
function loadFSWatcher() {
    if (!FSWatcher) {
        try {
            // tslint:disable-next-line:no-implicit-dependencies
            FSWatcher = require('chokidar').FSWatcher;
        }
        catch (e) {
            if (e.code !== 'MODULE_NOT_FOUND') {
                throw new Error('As of angular-devkit version 8.0, the "chokidar" package ' +
                    'must be installed in order to use watch() features.');
            }
            throw e;
        }
    }
}
function _callFs(fn, ...args) {
    return new rxjs_1.Observable(obs => {
        fn(...args, (err, result) => {
            if (err) {
                obs.error(err);
            }
            else {
                obs.next(result);
                obs.complete();
            }
        });
    });
}
/**
 * An implementation of the Virtual FS using Node as the background. There are two versions; one
 * synchronous and one asynchronous.
 */
class NodeJsAsyncHost {
    get capabilities() {
        return { synchronous: false };
    }
    write(path, content) {
        return new rxjs_1.Observable(obs => {
            // Create folders if necessary.
            const _createDir = (path) => {
                if (fs.existsSync(src_1.getSystemPath(path))) {
                    return;
                }
                if (src_1.dirname(path) === path) {
                    throw new Error();
                }
                _createDir(src_1.dirname(path));
                fs.mkdirSync(src_1.getSystemPath(path));
            };
            _createDir(src_1.dirname(path));
            _callFs(fs.writeFile, src_1.getSystemPath(path), new Uint8Array(content)).subscribe(obs);
        });
    }
    read(path) {
        return _callFs(fs.readFile, src_1.getSystemPath(path)).pipe(operators_1.map(buffer => new Uint8Array(buffer).buffer));
    }
    delete(path) {
        return this.isDirectory(path).pipe(operators_1.mergeMap(isDirectory => {
            if (isDirectory) {
                const allFiles = [];
                const allDirs = [];
                const _recurseList = (path) => {
                    for (const fragment of fs.readdirSync(src_1.getSystemPath(path))) {
                        if (fs.statSync(src_1.getSystemPath(src_1.join(path, fragment))).isDirectory()) {
                            _recurseList(src_1.join(path, fragment));
                            allDirs.push(src_1.join(path, fragment));
                        }
                        else {
                            allFiles.push(src_1.join(path, fragment));
                        }
                    }
                };
                _recurseList(path);
                return rxjs_1.concat(rxjs_1.from(allFiles).pipe(operators_1.mergeMap(p => _callFs(fs.unlink, src_1.getSystemPath(p))), operators_1.ignoreElements()), rxjs_1.from(allDirs).pipe(operators_1.concatMap(p => _callFs(fs.rmdir, src_1.getSystemPath(p)))));
            }
            else {
                return _callFs(fs.unlink, src_1.getSystemPath(path));
            }
        }), operators_1.map(() => undefined));
    }
    rename(from, to) {
        return _callFs(fs.rename, src_1.getSystemPath(from), src_1.getSystemPath(to));
    }
    list(path) {
        return _callFs(fs.readdir, src_1.getSystemPath(path)).pipe(operators_1.map(names => names.map(name => src_1.fragment(name))));
    }
    exists(path) {
        // Exists is a special case because it cannot error.
        return new rxjs_1.Observable(obs => {
            fs.exists(path, exists => {
                obs.next(exists);
                obs.complete();
            });
        });
    }
    isDirectory(path) {
        return _callFs(fs.stat, src_1.getSystemPath(path)).pipe(operators_1.map(stat => stat.isDirectory()));
    }
    isFile(path) {
        return _callFs(fs.stat, src_1.getSystemPath(path)).pipe(operators_1.map(stat => stat.isFile()));
    }
    // Some hosts may not support stat.
    stat(path) {
        return _callFs(fs.stat, src_1.getSystemPath(path));
    }
    // Some hosts may not support watching.
    watch(path, _options) {
        return new rxjs_1.Observable(obs => {
            loadFSWatcher();
            const watcher = new FSWatcher({ persistent: true }).add(src_1.getSystemPath(path));
            watcher
                .on('change', path => {
                obs.next({
                    path: src_1.normalize(path),
                    time: new Date(),
                    type: 0 /* Changed */,
                });
            })
                .on('add', path => {
                obs.next({
                    path: src_1.normalize(path),
                    time: new Date(),
                    type: 1 /* Created */,
                });
            })
                .on('unlink', path => {
                obs.next({
                    path: src_1.normalize(path),
                    time: new Date(),
                    type: 2 /* Deleted */,
                });
            });
            return () => watcher.close();
        }).pipe(operators_1.publish(), operators_1.refCount());
    }
}
exports.NodeJsAsyncHost = NodeJsAsyncHost;
/**
 * An implementation of the Virtual FS using Node as the backend, synchronously.
 */
class NodeJsSyncHost {
    get capabilities() {
        return { synchronous: true };
    }
    write(path, content) {
        return new rxjs_1.Observable(obs => {
            // TODO: remove this try+catch when issue https://github.com/ReactiveX/rxjs/issues/3740 is
            // fixed.
            try {
                // Create folders if necessary.
                const _createDir = (path) => {
                    if (fs.existsSync(src_1.getSystemPath(path))) {
                        return;
                    }
                    _createDir(src_1.dirname(path));
                    fs.mkdirSync(src_1.getSystemPath(path));
                };
                _createDir(src_1.dirname(path));
                fs.writeFileSync(src_1.getSystemPath(path), new Uint8Array(content));
                obs.next();
                obs.complete();
            }
            catch (err) {
                obs.error(err);
            }
        });
    }
    read(path) {
        return new rxjs_1.Observable(obs => {
            // TODO: remove this try+catch when issue https://github.com/ReactiveX/rxjs/issues/3740 is
            // fixed.
            try {
                const buffer = fs.readFileSync(src_1.getSystemPath(path));
                obs.next(new Uint8Array(buffer).buffer);
                obs.complete();
            }
            catch (err) {
                obs.error(err);
            }
        });
    }
    delete(path) {
        return this.isDirectory(path).pipe(operators_1.concatMap(isDir => {
            // TODO: remove this try+catch when issue https://github.com/ReactiveX/rxjs/issues/3740 is
            // fixed.
            if (isDir) {
                const dirPaths = fs.readdirSync(src_1.getSystemPath(path));
                const rmDirComplete = new rxjs_1.Observable((obs) => {
                    try {
                        fs.rmdirSync(src_1.getSystemPath(path));
                        obs.complete();
                    }
                    catch (e) {
                        obs.error(e);
                    }
                });
                return rxjs_1.concat(...dirPaths.map(name => this.delete(src_1.join(path, name))), rmDirComplete);
            }
            else {
                try {
                    fs.unlinkSync(src_1.getSystemPath(path));
                }
                catch (err) {
                    return rxjs_1.throwError(err);
                }
                return rxjs_1.of(undefined);
            }
        }));
    }
    rename(from, to) {
        return new rxjs_1.Observable(obs => {
            // TODO: remove this try+catch when issue https://github.com/ReactiveX/rxjs/issues/3740 is
            // fixed.
            try {
                fs.renameSync(src_1.getSystemPath(from), src_1.getSystemPath(to));
                obs.next();
                obs.complete();
            }
            catch (err) {
                obs.error(err);
            }
        });
    }
    list(path) {
        return new rxjs_1.Observable(obs => {
            // TODO: remove this try+catch when issue https://github.com/ReactiveX/rxjs/issues/3740 is
            // fixed.
            try {
                const names = fs.readdirSync(src_1.getSystemPath(path));
                obs.next(names.map(name => src_1.fragment(name)));
                obs.complete();
            }
            catch (err) {
                obs.error(err);
            }
        });
    }
    exists(path) {
        return new rxjs_1.Observable(obs => {
            // TODO: remove this try+catch when issue https://github.com/ReactiveX/rxjs/issues/3740 is
            // fixed.
            try {
                obs.next(fs.existsSync(src_1.getSystemPath(path)));
                obs.complete();
            }
            catch (err) {
                obs.error(err);
            }
        });
    }
    isDirectory(path) {
        // tslint:disable-next-line:no-non-null-assertion
        return this.stat(path).pipe(operators_1.map(stat => stat.isDirectory()));
    }
    isFile(path) {
        // tslint:disable-next-line:no-non-null-assertion
        return this.stat(path).pipe(operators_1.map(stat => stat.isFile()));
    }
    // Some hosts may not support stat.
    stat(path) {
        return new rxjs_1.Observable(obs => {
            // TODO: remove this try+catch when issue https://github.com/ReactiveX/rxjs/issues/3740 is
            // fixed.
            try {
                obs.next(fs.statSync(src_1.getSystemPath(path)));
                obs.complete();
            }
            catch (err) {
                obs.error(err);
            }
        });
    }
    // Some hosts may not support watching.
    watch(path, _options) {
        return new rxjs_1.Observable(obs => {
            const opts = { persistent: false };
            loadFSWatcher();
            const watcher = new FSWatcher(opts).add(src_1.getSystemPath(path));
            watcher
                .on('change', path => {
                obs.next({
                    path: src_1.normalize(path),
                    time: new Date(),
                    type: 0 /* Changed */,
                });
            })
                .on('add', path => {
                obs.next({
                    path: src_1.normalize(path),
                    time: new Date(),
                    type: 1 /* Created */,
                });
            })
                .on('unlink', path => {
                obs.next({
                    path: src_1.normalize(path),
                    time: new Date(),
                    type: 2 /* Deleted */,
                });
            });
            return () => watcher.close();
        }).pipe(operators_1.publish(), operators_1.refCount());
    }
}
exports.NodeJsSyncHost = NodeJsSyncHost;


text:
using System;

namespace MicroIoc
{
    public class ResolutionException : Exception
    {
        public ResolutionException(string message)
            : base(message) { }

        public ResolutionException(string message, Exception innerException)
            : base(message, innerException) { }
    }
}


text:
<!doctype html>

		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>microscheme.org</title>
		<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,700italic,400,300,700" />
		<link type="text/css" rel="stylesheet" href="../css/foundation.css" />
		<link type="text/css" rel="stylesheet" href="../local.css" />

Language Guide: Page 7

A crash course in the particular workings of microscheme

Runtime Exceptions

Like Scheme, microscheme is strongly, dynamically typed. Exceptions are semmantic errors that arise at runtime. Microscheme makes use of the Arduino's built-in LED on digital pin 13 to give on-device indications of these situations. Generally, exceptions are not recoverable, and the device will need to be reset if an exception is raised. While it is possible to use digital pin 13 for general input and output, it is highly recommended to leave it free for exception indication.

Status	Meaning	Indication

RUN	Program Running	No Light

NVP	Not a Valued Procedure	Single Flashes

NAR	Number of ARguments	2 Flashes

NAN	Not A Number	3 Flashes

NAP	Not A Pair	4 Flashes

NAV	Not A Vector	5 Flashes

OOB	Out Of Bounds	6 Flashes

DBZ	Divide By Zero	7 Flashes

ERR	Custom Exception	Continuous Flashes

HALT	Program Completed	Continuous Light

Exception Details

NVP: A procedure application takes the form (proc X1 X2 ... Xn) where proc is an expression. At the time of application, if proc does not evaluate to a (valued) procedure, such as the result of a (lambda …) form, or a variable bound to a procedure, then NVP will be raised.

NAR: A procedure application takes the form (proc X1 X2 ... Xn) where X1 X2 ... Xn are arguments. At the time of application, if proc evaluates to a procedure taking m arguments, but m ≠ n, then NAR will be raised.

NAN: Indicates that an arithmetic operator (+, -, *, /, div, mod) received an argument that did not evaluate to a number.

NAP: Indicates that a pair operator (car, cdr, set-car!, set-cdr!) received an argument that did not evaluate to a pair.

NAV: Indicates that a vector operator (vector-ref, vector-set!) received an argument that did not evaluate to a vector.

OOB: Indicates that a vector operator (vector-ref, vector-set!) received an index that was outside the dimensions of the vector given.

DBZ: Indicates an attempt to divide by zero.

ERR: This exception is raised manually by the programmer. See (error) and (assert expr) in the language guide.

«

1

2

3

4

5

6

7

»

<img src="../logosmall.png"

About

Download

Workflow

Examples

Language Guide

Caveats

Help

© Ryan Suchocki


text:
#ifndef KYTHE_CXX_VERIFIER_PRETTY_PRINTER_H_
#define KYTHE_CXX_VERIFIER_PRETTY_PRINTER_H_

#include <sstream>

#include "absl/strings/string_view.h"

namespace kythe {
namespace verifier {

/// \brief Prints human-readable representations of various objects.
class PrettyPrinter {
 public:
  /// \brief Prints `string`.
  virtual void Print(absl::string_view string) = 0;

  /// \brief Prints `string`.
  virtual void Print(const char* string) = 0;

  /// \brief Prints `ptr` in hex with a 0x prefix (or 0 for null pointers).
  virtual void Print(const void* ptr) = 0;

  virtual ~PrettyPrinter();
};

/// \brief A `PrettyPrinter` using a `string` as its backing store.
class StringPrettyPrinter : public PrettyPrinter {
 public:
  /// \copydoc PrettyPrinter::Print(absl::string_view)
  void Print(absl::string_view string) override;
  /// \copydoc PrettyPrinter::Print(const char*)
  void Print(const char* string) override;
  /// \copydoc PrettyPrinter::Print(const void *)
  void Print(const void* ptr) override;
  /// Returns the `string` printed to thus far.
  std::string str() { return data_.str(); }

 private:
  /// The `string` storing this `PrettyPrinter`'s data.
  std::stringstream data_;
};

/// \brief A `PrettyPrinter` that directs its output to a file handle.
class FileHandlePrettyPrinter : public PrettyPrinter {
 public:
  /// \param file The file handle to print to.
  explicit FileHandlePrettyPrinter(FILE* file) : file_(file) {}
  /// \copydoc PrettyPrinter::Print(absl::string_view)
  void Print(absl::string_view string) override;
  /// \copydoc PrettyPrinter::Print(const char*)
  void Print(const char* string) override;
  /// \copydoc PrettyPrinter::Print(const void *)
  void Print(const void* ptr) override;

 private:
  FILE* file_;
};

/// \brief A `PrettyPrinter` that wraps another `PrettyPrinter` but escapes
/// to a C/JavaScript-style quotable form.
class QuoteEscapingPrettyPrinter : public PrettyPrinter {
 public:
  /// \param wrapped The `PrettyPrinter` to which transformed text should be
  /// sent.
  explicit QuoteEscapingPrettyPrinter(PrettyPrinter& wrapped)
      : wrapped_(wrapped) {}
  /// \copydoc PrettyPrinter::Print(absl::string_view)
  void Print(absl::string_view string) override;
  /// \copydoc PrettyPrinter::Print(const char*)
  void Print(const char* string) override;
  /// \copydoc PrettyPrinter::Print(const void *)
  void Print(const void* ptr) override;

 private:
  PrettyPrinter& wrapped_;
};

/// \brief A `PrettyPrinter` that wraps another `PrettyPrinter` but escapes
/// HTML special characters ("&<>) to HTML entities.
class HtmlEscapingPrettyPrinter : public PrettyPrinter {
 public:
  /// \param wrapped The `PrettyPrinter` to which transformed text should be
  /// sent.
  explicit HtmlEscapingPrettyPrinter(PrettyPrinter& wrapped)
      : wrapped_(wrapped) {}
  /// \copydoc PrettyPrinter::Print(absl::string_view)
  void Print(absl::string_view string) override;
  /// \copydoc PrettyPrinter::Print(const char*)
  void Print(const char* string) override;
  /// \copydoc PrettyPrinter::Print(const void *)
  void Print(const void* ptr) override;

 private:
  PrettyPrinter& wrapped_;
};

}  // namespace verifier
}  // namespace kythe

#endif  // KYTHE_CXX_VERIFIER_PRETTY_PRINTER_H_


text:
package org.cybergarage.round.rpc;

import org.json.*;
import org.cybergarage.round.Error;
import java.util.Map;

public class Message extends JSONObject
{
	public static final String VERSION = "2.0";
	public static final String JSONRPC = "jsonrpc";
	public static final String METHOD = "method";
	public static final String ID = "id";
	public static final String PARAMS = "params";
	public static final String RESULT = "result";
	public static final String ERROR = "error";
	public static final String CODE = "code";
	public static final String MESSAGE = "message";

	public Message()
	{
		set(JSONRPC, VERSION);
		setId("1");
	}

	public String getVersion()
	{
		return getStr(VERSION);
	}

	public boolean setId(String value)
	{
		return set(ID, value);
	}

	public String getId()
	{
		return getStr(ID);
	}

	public boolean setMethod(String value)
	{
		return set(METHOD, value);
	}

	public String getMethod()
	{
		return getStr(METHOD);
	}

	public boolean setParams(String value)
	{
		return set(PARAMS, value);
	}

	public boolean setParams(Map values)
	{
		try {
			put(PARAMS, values);
		}
		catch (JSONException e) {
			return false;
		}
		return true;
	}

	public String getParams()
	{
		return getStr(PARAMS);
	}

	public boolean setResult(String value)
	{
		return set(RESULT, value);
	}

	public String getResult()
	{
		return getStr(RESULT);
	}

	public boolean setError(Error err)
	{
		JSONObject error = new JSONObject();
		try {
			error.put(CODE, err.getCode());
			error.put(MESSAGE, err.getMessage());
			put(ERROR, error);
		}
		catch (JSONException e) {
			return false;
		}

		return true;
	}

	public Error getError()
	{
		int errorCode = 0;
		String errorMsg = "";
		try {
			JSONObject error = getJSONObject(ERROR);
			if (error == null)
				return null;
			errorCode = error.getInt(CODE);
			errorMsg = error.getString(MESSAGE);
		}
		catch (JSONException e) {
			return null;
		}

		return new Error(errorCode, errorMsg);
	}

	private boolean set(String key, String value)
	{
		try {
			put(key, value);
		}
		catch (JSONException e) {
			return false;
		}
		return true;
	}

	private String getStr(String key)
	{
		try {
			return getString(key);
		}
		catch (JSONException e) {
			return null;
		}
	}
}


text:
package de.isibboi.agentsim.game.entities.ai;

import de.isibboi.agentsim.game.map.Point;

/**
 * Provides knowledge about a certain feature of the map.
 *
 * @author Sebastian Schmidt
 * @since 0.3.0
 *
 * @param <Knowledge> The type of provider knowledge.
 */
public interface KnowledgeProvider<Knowledge> {
	/**
	 * Returns the current version of the knowledge.
	 * @return The version of the knowledge.
	 */
	long getAge();

	/**
	 * Returns the knowledge about the specified location.
	 * @param location The location.
	 * @return The knowledge about {@code location}.
	 */
	Knowledge getKnowledge(Point location);
}


text:
namespace android_webview {

class SmokeTest : public RenderingTest {
  void StartTest() override { browser_view_renderer_->PostInvalidate(); }

  void DidDrawOnRT(RenderThreadManager* functor) override {
    EndTest();
  }
};

RENDERING_TEST_F(SmokeTest);

class ClearViewTest : public RenderingTest {
 public:
  ClearViewTest() : on_draw_count_(0) {}

  void StartTest() override {
    browser_view_renderer_->PostInvalidate();
    browser_view_renderer_->ClearView();
  }

  void DidOnDraw(bool success) override {
    on_draw_count_++;
    if (on_draw_count_ == 1) {
      // First OnDraw should be skipped due to ClearView.
      EXPECT_FALSE(success);
      browser_view_renderer_->DidUpdateContent();  // Unset ClearView.
      browser_view_renderer_->PostInvalidate();
    } else {
      // Following OnDraws should succeed.
      EXPECT_TRUE(success);
    }
  }

  void DidDrawOnRT(RenderThreadManager* functor) override {
    EndTest();
  }
 private:
  int on_draw_count_;
};

RENDERING_TEST_F(ClearViewTest);

class TestAnimateInAndOutOfScreen : public RenderingTest {
 public:
  TestAnimateInAndOutOfScreen() : on_draw_count_(0), draw_gl_count_on_rt_(0) {}

  void StartTest() override {
    new_constraints_ = ParentCompositorDrawConstraints(
        false, gfx::Transform(), window_->surface_size().IsEmpty());
    new_constraints_.transform.Scale(2.0, 2.0);
    browser_view_renderer_->PostInvalidate();
  }

  void WillOnDraw() override {
    RenderingTest::WillOnDraw();
    // Step 0: A single onDraw on screen. The parent draw constraints
    // of the BVR will updated to be the initial constraints.
    // Step 1: A single onDrraw off screen. The parent draw constraints of the
    // BVR will be updated to the new constraints.
    // Step 2: This onDraw is to introduce the DrawGL that animates the
    // webview onto the screen on render thread. End the test when the parent
    // draw constraints of BVR is updated to initial constraints.
    if (on_draw_count_ == 1 || on_draw_count_ == 2)
      browser_view_renderer_->PrepareToDraw(gfx::Vector2d(), gfx::Rect());
  }

  void DidOnDraw(bool success) override {
    EXPECT_TRUE(success);
    on_draw_count_++;
  }

  bool WillDrawOnRT(RenderThreadManager* functor,
                    AwDrawGLInfo* draw_info) override {
    if (draw_gl_count_on_rt_ == 1) {
      draw_gl_count_on_rt_++;
      ui_task_runner_->PostTask(
          FROM_HERE,
          base::Bind(&RenderingTest::PostInvalidate, base::Unretained(this)));
      return false;
    }

    draw_info->width = window_->surface_size().width();
    draw_info->height = window_->surface_size().height();
    draw_info->is_layer = false;

    gfx::Transform transform;
    if (draw_gl_count_on_rt_ == 0)
      transform = new_constraints_.transform;

    transform.matrix().asColMajorf(draw_info->transform);
    return true;
  }

  void DidDrawOnRT(RenderThreadManager* functor) override {
    draw_gl_count_on_rt_++;
  }

  bool DrawConstraintsEquals(
      const ParentCompositorDrawConstraints& constraints1,
      const ParentCompositorDrawConstraints& constraints2) {
    if (constraints1.is_layer != constraints2.is_layer ||
        constraints1.transform != constraints2.transform)
      return false;

    return !constraints1.is_layer ||
           constraints1.surface_rect_empty == constraints2.surface_rect_empty;
  }

  void OnParentDrawConstraintsUpdated() override {
    RenderingTest::OnParentDrawConstraintsUpdated();
    ParentCompositorDrawConstraints constraints =
        render_thread_manager_->GetParentDrawConstraintsOnUI();
    switch (on_draw_count_) {
      case 1u:
        EXPECT_TRUE(DrawConstraintsEquals(constraints, new_constraints_));
        break;
      case 3u:
        EXPECT_TRUE(DrawConstraintsEquals(constraints, initial_constraints_));
        EndTest();
        break;
      // There will be a following 4th onDraw. But the hardware renderer won't
      // post back the draw constraints in DrawGL because the constraints
      // don't change.
      default:
        FAIL();
    }
  }

 private:
  int on_draw_count_;
  int draw_gl_count_on_rt_;
  ParentCompositorDrawConstraints initial_constraints_;
  ParentCompositorDrawConstraints new_constraints_;
};

RENDERING_TEST_F(TestAnimateInAndOutOfScreen);

class CompositorNoFrameTest : public RenderingTest {
 public:
  CompositorNoFrameTest() : on_draw_count_(0) {}

  void StartTest() override {
    browser_view_renderer_->PostInvalidate();
  }

  void WillOnDraw() override {
    if (0 == on_draw_count_) {
      // No frame from compositor.
    } else if (1 == on_draw_count_) {
      compositor_->SetHardwareFrame(0u, ConstructEmptyFrame());
    } else if (2 == on_draw_count_) {
      // No frame from compositor.
    }
    // There may be trailing invalidates.
  }

  void DidOnDraw(bool success) override {
    if (0 == on_draw_count_) {
      // Should fail as there has been no frames from compositor.
      EXPECT_FALSE(success);
      browser_view_renderer_->PostInvalidate();
    } else if (1 == on_draw_count_) {
      // Should succeed with frame from compositor.
      EXPECT_TRUE(success);
      browser_view_renderer_->PostInvalidate();
    } else if (2 == on_draw_count_) {
      // Should still succeed with last frame, even if no frame from compositor.
      EXPECT_TRUE(success);
      EndTest();
    }
    on_draw_count_++;
  }

 private:
  int on_draw_count_;
};

RENDERING_TEST_F(CompositorNoFrameTest);

class SwitchOutputSurfaceIdTest : public RenderingTest {
 public:
  struct FrameInfo {
    uint32_t output_surface_id;
    cc::ResourceId resource_id;  // Each frame contains a single resource.
  };

  void StartTest() override {
    last_output_surface_id_ = 0;
    FrameInfo infos[] = {
        // First output surface.
        {0u, 1u}, {0u, 1u}, {0u, 2u}, {0u, 2u}, {0u, 3u}, {0u, 3u}, {0u, 4u},
        // Second output surface.
        {1u, 1u}, {1u, 1u}, {1u, 2u}, {1u, 2u}, {1u, 3u}, {1u, 3u}, {1u, 4u},
    };
    for (const auto& info : infos) {
      content::SynchronousCompositor::Frame frame;
      frame.output_surface_id = info.output_surface_id;
      frame.frame = ConstructEmptyFrame();
      cc::TransferableResource resource;
      resource.id = info.resource_id;
      frame.frame->delegated_frame_data->resource_list.push_back(resource);
      frames_.push(std::move(frame));

      // Keep a id -> count map for the last ouptut_surface_id.
      if (last_output_surface_id_ != info.output_surface_id) {
        expected_return_count_.clear();
        last_output_surface_id_ = info.output_surface_id;
      }
      if (expected_return_count_.count(info.resource_id)) {
        expected_return_count_[info.resource_id]++;
      } else {
        expected_return_count_[info.resource_id] = 1;
      }
    }

    browser_view_renderer_->PostInvalidate();
  }

  void WillOnDraw() override {
    if (!frames_.empty()) {
      compositor_->SetHardwareFrame(frames_.front().output_surface_id,
                                    std::move(frames_.front().frame));
    }
  }

  void DidOnDraw(bool success) override {
    EXPECT_TRUE(success);
    if (frames_.empty()) {
      ui_task_runner_->PostTask(
          FROM_HERE, base::Bind(&SwitchOutputSurfaceIdTest::CheckResults,
                                base::Unretained(this)));
    } else {
      frames_.pop();
      browser_view_renderer_->PostInvalidate();
    }
  }

  void CheckResults() {
    window_->Detach();
    window_.reset();

    // Make sure resources for the last output surface are returned.
    content::TestSynchronousCompositor::FrameAckArray returned_resources_array;
    compositor_->SwapReturnedResources(&returned_resources_array);
    for (const auto& resources : returned_resources_array) {
      if (resources.output_surface_id != last_output_surface_id_)
        continue;
      for (const auto& returned_resource : resources.resources) {
        EXPECT_TRUE(!!expected_return_count_.count(returned_resource.id));
        EXPECT_GE(expected_return_count_[returned_resource.id],
                  returned_resource.count);
        expected_return_count_[returned_resource.id] -=
            returned_resource.count;
        if (!expected_return_count_[returned_resource.id])
          expected_return_count_.erase(returned_resource.id);
      }
    }
    EXPECT_TRUE(expected_return_count_.empty());

    EndTest();
  }

 private:
  std::queue<content::SynchronousCompositor::Frame> frames_;
  uint32_t last_output_surface_id_;
  std::map<cc::ResourceId, int> expected_return_count_;
};

RENDERING_TEST_F(SwitchOutputSurfaceIdTest);

}  // namespace android_webview


text:
//-----------------------------------------------------------------------
// <copyright file="ClusterShardingSpec.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com>
//     Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Linq;
using Akka.Actor;
using Akka.Cluster.TestKit;
using Akka.Cluster.Tools.Singleton;
using Akka.Configuration;
using Akka.Remote.TestKit;
using FluentAssertions;

namespace Akka.Cluster.Sharding.Tests.MultiNode
{
    public class ShardedDaemonProcessSpecConfig : MultiNodeConfig
    {
        public RoleName First { get; }
        public RoleName Second { get; }
        public RoleName Third { get; }

        public ShardedDaemonProcessSpecConfig()
        {
            First = Role("first");
            Second = Role("second");
            Third = Role("third");

            CommonConfig = DebugConfig(false)
                .WithFallback(ConfigurationFactory.ParseString(@"
                    akka.loglevel = INFO
                    akka.cluster.sharded-daemon-process {{
                      sharding {{
                        # First is likely to be ignored as shard coordinator not ready
                        retry-interval = 0.2s
                      }}
                      # quick ping to make test swift
                      keep-alive-interval = 1s
                    }}
                "))
                .WithFallback(ClusterSharding.DefaultConfig())
                .WithFallback(ClusterSingletonManager.DefaultConfig())
                .WithFallback(MultiNodeClusterSpec.ClusterConfig());
        }
    }

    public class ShardedDaemonProcessMultiNode : ShardedDaemonProcessSpec
    {
        public ShardedDaemonProcessMultiNode() : this(new ShardedDaemonProcessSpecConfig()) { }
        protected ShardedDaemonProcessMultiNode(ShardedDaemonProcessSpecConfig config) : base(config, typeof(ShardedDaemonProcessMultiNode)) { }
    }

    public abstract class ShardedDaemonProcessSpec : MultiNodeClusterSpec
    {
        private readonly ShardedDaemonProcessSpecConfig _config;

        protected ShardedDaemonProcessSpec(ShardedDaemonProcessSpecConfig config, Type type)
            : base(config, type)
        {
            _config = config;
        }

        [MultiNodeFact]
        public void ShardedDaemonProcess_Specs()
        {
            ShardedDaemonProcess_Should_Init_Actor_Set();
        }

        public void ShardedDaemonProcess_Should_Init_Actor_Set()
        {
            // HACK
            RunOn(() => FormCluster(_config.First, _config.Second, _config.Third), _config.First);

            var probe = CreateTestProbe();
            ShardedDaemonProcess.Get(Sys).Init("the-fearless", 4, id => ProcessActor.Props(id, probe.Ref));
            EnterBarrier("sharded-daemon-process-initialized");

            RunOn(() =>
            {
                var startedIds = Enumerable.Range(0, 4).Select(_ =>
                {
                    var evt = probe.ExpectMsg<ProcessActorEvent>(TimeSpan.FromSeconds(5));
                    evt.Event.Should().Be("Started");
                    return evt.Id;
                }).ToList();
                startedIds.Count.Should().Be(4);
            }, _config.First);
            EnterBarrier("sharded-daemon-process-started");
        }

        private void FormCluster(RoleName first, params RoleName[] rest)
        {
            RunOn(() =>
            {
                Cluster.Join(GetAddress(first));
                AwaitAssert(() =>
                {
                    Cluster.State.Members.Select(i => i.UniqueAddress).Should().Contain(Cluster.SelfUniqueAddress);
                    Cluster.State.Members.Select(i => i.Status).Should().OnlyContain(i => i == MemberStatus.Up);
                });
            }, first);
            EnterBarrier(first.Name + "-joined");

            foreach (var node in rest)
            {
                RunOn(() =>
                {
                    Cluster.Join(GetAddress(first));
                    AwaitAssert(() =>
                    {
                        Cluster.State.Members.Select(i => i.UniqueAddress).Should().Contain(Cluster.SelfUniqueAddress);
                        Cluster.State.Members.Select(i => i.Status).Should().OnlyContain(i => i == MemberStatus.Up);
                    });
                }, node);
            }
            EnterBarrier("all-joined");
        }
    }

    internal class ProcessActor : UntypedActor
    {
        #region Protocol

        [Serializable]
        public sealed class Stop
        {
            public static readonly Stop Instance = new Stop();
            private Stop() { }
        }

        #endregion

        public static Props Props(int id, IActorRef probe) =>
            Actor.Props.Create(() => new ProcessActor(id, probe));

        public ProcessActor(int id, IActorRef probe)
        {
            Probe = probe;
            Id = id;
        }

        public IActorRef Probe { get; }
        public int Id { get; }

        protected override void PreStart()
        {
            base.PreStart();
            Probe.Tell(new ProcessActorEvent(Id, "Started"));
        }

        protected override void OnReceive(object message)
        {
            if (message is Stop)
            {
                Probe.Tell(new ProcessActorEvent(Id, "Stopped"));
                Context.Stop(Self);
            }
        }
    }

    internal sealed class ProcessActorEvent
    {
        public ProcessActorEvent(int id, object @event)
        {
            Id = id;
            Event = @event;
        }

        public int Id { get; }
        public object Event { get; }
    }
}


text:
import horizon

from openstack_dashboard.dashboards.settings import dashboard

class Multisettings(horizon.Panel):
    name = ("Multisettings")
    slug = "multisettings"

dashboard.Settings.register(Multisettings)


text:
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VsExtension.Shell
{
    public class StatusBarLogger
    {
        private IServiceProvider _serviceProvider;

        private readonly IVsStatusbar _statusBar;

        public StatusBarLogger(Package package)
        {
            _serviceProvider = package;

            _statusBar = (IVsStatusbar)_serviceProvider.GetService(typeof(SVsStatusbar));
        }

        public void StartProgressAnimation()
        {
            object icon = (short)Constants.SBAI_General;

            _statusBar.Animation(1, ref icon);
        }

        public void SetText(string text)
        {
            _statusBar.IsFrozen(out int frozen);
            if (frozen == 0)
            {
                _statusBar.SetText(text);
            }
        }

        public void Clear()
        {
            _statusBar.Clear();
        }

        public void StopProgressAnimation()
        {
            object icon = (short)Constants.SBAI_General;

            _statusBar.Animation(0, ref icon);
        }
    }
}


text:
{% from "govuk_frontend_jinja/components/error-summary/macro.html" import govukErrorSummary %}

{% macro errorSummary(form) %}
  {% if form.errors %}
    {% set errors = [] %}
    {% for field_name, error_list in form.errors.items() %}
      {% if field_name %}
        {% set _ = errors.append({"href": "#" + form[field_name].id, "text": error_list[0]}) %}
      {% else %}
        {# field_name is None for form level errors #}
        {% set _ = errors.append({"text": error_list[0]}) %}
      {% endif %}
    {% endfor %}

    {{ govukErrorSummary({
      "titleText": "There is a problem",
      "errorList": errors
    }) }}
  {% endif %}
{% endmacro %}


text:
namespace ymaps.interfaces {

    interface IHotspot extends IDomEventEmitter {
        getShape():IShape;
        setShape(shape:IShape):any;
        getZIndex():number;
        setZIndex(zIndex:number):any;
    }
}


text:
/**
 * @fileoverview Shared interfaces for functions that check CSP policies.
 */

import {Csp} from '../csp';
import {Finding} from '../finding';

/**
 * A function that checks a given Csp for problems and returns an unordered
 * list of Findings.
 */
export type CheckerFunction = (csp: Csp) => Finding[];