text:
package org.apache.reef.io.network.naming;

import org.apache.reef.io.naming.NameAssignment;
import org.apache.reef.io.naming.NamingLookup;
import org.apache.reef.io.network.naming.exception.NamingException;
import org.apache.reef.io.network.naming.parameters.NameResolverCacheTimeout;
import org.apache.reef.io.network.naming.parameters.NameResolverIdentifierFactory;
import org.apache.reef.io.network.naming.parameters.NameResolverNameServerAddr;
import org.apache.reef.io.network.naming.parameters.NameResolverNameServerPort;
import org.apache.reef.io.network.naming.parameters.NameResolverRetryCount;
import org.apache.reef.io.network.naming.parameters.NameResolverRetryTimeout;
import org.apache.reef.io.network.naming.serialization.NamingLookupRequest;
import org.apache.reef.io.network.naming.serialization.NamingLookupResponse;
import org.apache.reef.io.network.naming.serialization.NamingMessage;
import org.apache.reef.tang.annotations.Parameter;
import org.apache.reef.util.cache.Cache;
import org.apache.reef.wake.EventHandler;
import org.apache.reef.wake.Identifier;
import org.apache.reef.wake.IdentifierFactory;
import org.apache.reef.wake.Stage;
import org.apache.reef.wake.impl.SyncStage;
import org.apache.reef.wake.remote.Codec;
import org.apache.reef.wake.remote.address.LocalAddressProvider;
import org.apache.reef.wake.remote.impl.TransportEvent;
import org.apache.reef.wake.remote.transport.Link;
import org.apache.reef.wake.remote.transport.Transport;
import org.apache.reef.wake.remote.transport.TransportFactory;
import org.apache.reef.wake.remote.transport.netty.LoggingLinkListener;

import javax.inject.Inject;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Naming lookup client.
 */
public final class NameLookupClient implements Stage, NamingLookup {

  private static final Logger LOG = Logger.getLogger(NameLookupClient.class.getName());
  private final SocketAddress serverSocketAddr;
  private final Transport transport;
  private final Codec<NamingMessage> codec;
  private final BlockingQueue<NamingLookupResponse> replyQueue;
  private final long timeout;
  private final Cache<Identifier, InetSocketAddress> cache;
  private final int retryCount;
  private final int retryTimeout;

  /**
   * Constructs a naming lookup client.
   *
   * @param serverAddr a server address
   * @param serverPort a server port number
   * @param timeout    request timeout in ms
   * @param factory    an identifier factory
   * @param retryCount a count of retrying lookup
   * @param retryTimeout retry timeout
   * @param replyQueue a reply queue
   * @param transport  a transport
   */
  NameLookupClient(final String serverAddr,
                          final int serverPort,
                          final long timeout,
                          final IdentifierFactory factory,
                          final int retryCount,
                          final int retryTimeout,
                          final BlockingQueue<NamingLookupResponse> replyQueue,
                          final Transport transport) {
    this.serverSocketAddr = new InetSocketAddress(serverAddr, serverPort);
    this.timeout = timeout;
    this.cache = new NameCache(timeout);
    this.codec = NamingCodecFactory.createFullCodec(factory);
    this.replyQueue = replyQueue;
    this.retryCount = retryCount;
    this.retryTimeout = retryTimeout;
    this.transport = transport;
  }

  /**
    * Constructs a naming lookup client.
    *
    * @param serverAddr a server address
    * @param serverPort a server port number
    * @param timeout    request timeout in ms
    * @param factory    an identifier factory
    * @param tpFactory  a transport factory
    */
  @Inject
  private NameLookupClient(
            @Parameter(NameResolverNameServerAddr.class) final String serverAddr,
            @Parameter(NameResolverNameServerPort.class) final int serverPort,
            @Parameter(NameResolverCacheTimeout.class) final long timeout,
            @Parameter(NameResolverIdentifierFactory.class) final IdentifierFactory factory,
            @Parameter(NameResolverRetryCount.class) final int retryCount,
            @Parameter(NameResolverRetryTimeout.class) final int retryTimeout,
            final LocalAddressProvider localAddressProvider,
            final TransportFactory tpFactory) {
    this.serverSocketAddr = new InetSocketAddress(serverAddr, serverPort);
    this.timeout = timeout;
    this.cache = new NameCache(timeout);
    this.codec = NamingCodecFactory.createLookupCodec(factory);
    this.replyQueue = new LinkedBlockingQueue<>();

    this.transport = tpFactory.newInstance(localAddressProvider.getLocalAddress(), 0,
            new SyncStage<>(new NamingLookupClientHandler(
                    new NamingLookupResponseHandler(this.replyQueue), this.codec)),
            null, retryCount, retryTimeout);

    this.retryCount = retryCount;
    this.retryTimeout = retryTimeout;
  }

  /**
   * Finds an address for an identifier.
   *
   * @param id an identifier
   * @return an Internet socket address
   */
  @Override
  public InetSocketAddress lookup(final Identifier id) throws Exception {

    return cache.get(id, new Callable<InetSocketAddress>() {

      @Override
      public InetSocketAddress call() throws Exception {
        final int origRetryCount = NameLookupClient.this.retryCount;
        int retriesLeft = origRetryCount;
        while (true) {
          try {
            return remoteLookup(id);
          } catch (final NamingException e) {
            if (retriesLeft <= 0) {
              throw e;
            } else {
              final int currentRetryTimeout = NameLookupClient.this.retryTimeout
                  * (origRetryCount - retriesLeft + 1);
              LOG.log(Level.WARNING,
                  "Caught Naming Exception while looking up " + id
                      + " with Name Server. Will retry " + retriesLeft
                      + " time(s) after waiting for " + currentRetryTimeout + " msec.");
              Thread.sleep(currentRetryTimeout);
              --retriesLeft;
            }
          }
        }
      }

    });
  }

  /**
   * Retrieves an address for an identifier remotely.
   *
   * @param id an identifier
   * @return an Internet socket address
   * @throws Exception
   */
  public InetSocketAddress remoteLookup(final Identifier id) throws Exception {
    // the lookup is not thread-safe, because concurrent replies may
    // be read by the wrong thread.
    // TODO: better fix uses a map of id's after REEF-198
    synchronized (this) {

      LOG.log(Level.INFO, "Looking up {0} on NameServer {1}", new Object[]{id, serverSocketAddr});

      final List<Identifier> ids = Arrays.asList(id);
      final Link<NamingMessage> link = transport.open(serverSocketAddr, codec,
          new LoggingLinkListener<NamingMessage>());
      link.write(new NamingLookupRequest(ids));

      final NamingLookupResponse resp;
      for (;;) {
        try {
          resp = replyQueue.poll(timeout, TimeUnit.MILLISECONDS);
          break;
        } catch (final InterruptedException e) {
          LOG.log(Level.INFO, "Lookup interrupted", e);
          throw new NamingException(e);
        }
      }

      final List<NameAssignment> list = resp.getNameAssignments();
      if (list.isEmpty()) {
        throw new NamingException("Cannot find " + id + " from the name server");
      } else {
        return list.get(0).getAddress();
      }
    }
  }

  /**
   * Closes resources.
   */
  @Override
  public void close() throws Exception {
    // Should not close transport as we did not
    // create it
  }
}

/**
 * Naming lookup client transport event handler.
 */
class NamingLookupClientHandler implements EventHandler<TransportEvent> {

  private final EventHandler<NamingLookupResponse> handler;
  private final Codec<NamingMessage> codec;

  NamingLookupClientHandler(final EventHandler<NamingLookupResponse> handler, final Codec<NamingMessage> codec) {
    this.handler = handler;
    this.codec = codec;
  }

  @Override
  public void onNext(final TransportEvent value) {
    handler.onNext((NamingLookupResponse) codec.decode(value.getData()));
  }

}

/**
 * Naming lookup response handler.
 */
class NamingLookupResponseHandler implements EventHandler<NamingLookupResponse> {
  private static final Logger LOG = Logger.getLogger(NamingLookupResponseHandler.class.getName());

  private final BlockingQueue<NamingLookupResponse> replyQueue;

  NamingLookupResponseHandler(final BlockingQueue<NamingLookupResponse> replyQueue) {
    this.replyQueue = replyQueue;
  }

  @Override
  public void onNext(final NamingLookupResponse value) {
    if (!replyQueue.offer(value)) {
      LOG.log(Level.FINEST, "Element {0} was not added to the queue", value);
    }
  }
}


text:
#include "StagePanel.h"
#include "StageCanvas.h"
#include "FileIO.h"

#include "Context.h"
#include "LibraryPanel.h"
//#include "ComplexSprite.h"

namespace coceditor
{
namespace complex
{
	StagePanel::StagePanel(wxWindow* parent,
						   wxTopLevelWindow* frame,
						   LibraryPanel* library,
						   complex::Symbol* complexSymbol)
		: EditPanel(parent, frame)
		, ee::MultiSpritesImpl(this)
		, m_library(library)
		, m_complexSymbol(complexSymbol)
	{
		m_editOP = NULL;
		m_canvas = new StageCanvas(this);

		SetDropTarget(new DragSymbolTarget(this, m_library));

//		load();
	}

	StagePanel::~StagePanel()
	{

	}

	void StagePanel::traverseSprites(ee::IVisitor& visitor, ee::TraverseType type/* = ee::e_allExisting*/,
		bool order/* = true*/) const
	{
		if (order)
		{
			std::vector<ee::ISprite*>::const_iterator itr = m_complexSymbol->m_sprites.begin();
			for ( ; itr != m_complexSymbol->m_sprites.end(); ++itr)
			{
				bool hasNext;
				visitor.visit(*itr, hasNext);
				if (!hasNext) break;
			}
		}
		else
		{
			std::vector<ee::ISprite*>::const_reverse_iterator itr = m_complexSymbol->m_sprites.rbegin();
			for ( ; itr != m_complexSymbol->m_sprites.rend(); ++itr)
			{
				bool hasNext;
				visitor.visit(*itr, hasNext);
				if (!hasNext) break;
			}
		}
	}

	void StagePanel::insertSprite(ee::ISprite* sprite)
	{
		m_complexSymbol->m_sprites.push_back(sprite);
		Refresh();
	}

	void StagePanel::resetSpriteOrder(ee::ISprite* sprite, bool up)
	{
//		ee::SpritesPanelImpl::resetSpriteOrder(sprite, up);
	}

// 	void StagePanel::onDraw()
// 	{
// 		if (m_complexSymbol) m_complexSymbol->draw();
// 	}

	void StagePanel::loadSymbol()
	{

	}

	void StagePanel::storeSymbol()
	{
		if (!m_complexSymbol) return;

		wxString filepath = m_complexSymbol->getFilepath();
		if (filepath.empty())
		{
			std::string ext = ee::FileNameParser::getFileTag(ee::FileNameParser::e_complex);
			ext = "_" + ext + ".json";
			filepath = ee::Context::Instance()->getDir() + "\\" + m_complexSymbol->getName() + ext;
		}

		FileIO::store(filepath, m_complexSymbol);
	}

	//////////////////////////////////////////////////////////////////////////
	// class StagePanel::DragSymbolTarget
	//////////////////////////////////////////////////////////////////////////

	StagePanel::DragSymbolTarget::DragSymbolTarget(StagePanel* stage,
		LibraryPanel* library)
		: m_stage(stage)
		, m_library(library)
	{
	}

	bool StagePanel::DragSymbolTarget::OnDropText(wxCoord x, wxCoord y, const wxString& data)
	{
 		wxString sType = data.substr(0, data.find(","));
 		wxString sIndex = data.substr(data.find(",") + 1);

 		long index;
 		sIndex.ToLong(&index);

		ee::ISymbol* symbol = NULL;
		if (sType == "symbol")
			symbol = static_cast<ee::ISymbol*>(m_library->getImagePage()->getSymbol(index));
		else if (sType == "complex")
			symbol = static_cast<ee::ISymbol*>(m_library->getComplexPage()->getSymbol(index));

		if (symbol)
		{
			ee::Vector pos = m_stage->transPosScreenToProject(x, y);
			ee::ISprite* sprite = ee::SpriteFactory::Instance()->create(symbol);
			sprite->translate(pos);
			m_stage->insertSprite(sprite);
		}

 		return true;
	}
}
}

redpajama_set_name: RedPajamaGithub


text:
from django.apps import AppConfig

class DjangoModelToDictConfig(AppConfig):
    name = 'django_model_to_dict'


text:
<?php
	#
	# lib_filter.txt
	#
	# A PHP HTML filtering library
	#
	# $Id$
	#
	# http://iamcal.com/publish/articles/php/processing_html/
	# http://iamcal.com/publish/articles/php/processing_html_part_2/
	#
	# By Cal Henderson <cal@iamcal.com>
	# This code is licensed under a Creative Commons Attribution-ShareAlike 2.5 License
	# http://creativecommons.org/licenses/by-sa/2.5/
	#
	# Thanks to Jang Kim for adding support for single quoted attributes
	# Thanks to Dan Bogan for dealing with entity decoding outside attributes
	#

	class lib_filter {

		var $tag_counts = array();

		#
		# tags and attributes that are allowed
		#

		var $allowed = array(
			'a' => array('href', 'target'),
			'b' => array(),
			'img' => array('src', 'width', 'height', 'alt'),
		);

		#
		# tags which should always be self-closing (e.g. "")
		#

		var $no_close = array(
			'img',
		);

		#
		# tags which must always have seperate opening and closing tags (e.g. "")
		#

		var $always_close = array(
			'a',
			'b',
		);

		#
		# attributes which should be checked for valid protocols
		#

		var $protocol_attributes = array(
			'src',
			'href',
		);

		#
		# protocols which are allowed
		#

		var $allowed_protocols = array(
			'http',
			'ftp',
			'mailto',
		);

		#
		# tags which should be removed if they contain no content (e.g. "" or "")
		#

		var $remove_blanks = array(
			'a',
			'b',
		);

		#
		# should we remove comments?
		#

		var $strip_comments = 1;

		#
		# should we try and make a b tag out of "b>"
		#

		var $always_make_tags = 1;

		#
		# should we allow dec/hex entities within the input?
		# if you set this to zero, '{' will be converted to '&#123;'
		#

		var $allow_numbered_entities = 1;

		#
		# these non-numeric entities are allowed. non allowed entities will be
		# converted from '&foo;' to '&foo;'
		#

		var $allowed_entities = array(
			'amp',
			'gt',
			'lt',
			'quot',
		);

		#
		# should we convert dec/hex entities in the general doc (not inside protocol attribute)
		# into raw characters? this is important if you're planning on running autolink on
		# the output, to make it easier to filter out unwanted spam URLs. without it, an attacker
		# could insert a working URL you'd otherwise be filtering (googlA.com would avoid
		# a string-matching spam filter, for instance). this only affects character codes below
		# 128 (that is, the ASCII characters).
		#
		# this setting overrides $allow_numbered_entities
		#

		var $normalise_ascii_entities = 0;

		#####################################################################################

		#
		# this is the main entry point - pass your document to be filtered into here
		#

		function go($data){

			$this->tag_counts = array();

			$data = $this->escape_comments($data);
			$data = $this->balance_html($data);
			$data = $this->check_tags($data);
			$data = $this->process_remove_blanks($data);
			$data = $this->cleanup_non_tags($data);

			return $data;
		}

		#####################################################################################

		#
		# the first step is to make sure we don't have HTML inside the comments.
		# comment are (optionally) stripped later on, but this ensures we don't
		# waste time matching stuff inside them.
		#

		function escape_comments($data){

			$data = preg_replace("//se", "''", $data);

			return $data;
		}

		#####################################################################################

		function balance_html($data){

			if ($this->always_make_tags){

				#
				# try and form html
				#

				$data = preg_replace("/>>+/", ">", $data);
				$data = preg_replace("/<<+/", "<", $data);
				$data = preg_replace("/^>/", "", $data);
				$data = preg_replace("/<([^>]*?)(?=<|$)/", "<$1>", $data);
				$data = preg_replace("/(^|>)([^<]*?)(?=>)/", "$1<$2", $data);

			}else{

				#
				# escape stray brackets
				#

				$data = preg_replace("/<([^>]*?)(?=<|$)/", "<$1", $data);
				$data = preg_replace("/(^|>)([^<]*?)(?=>)/", "$1$2><", $data);

				#
				# the last regexp causes '<>' entities to appear
				# (we need to do a lookahead assertion so that the last bracket can
				# be used in the next pass of the regexp)
				#

				$data = str_replace('<>', '', $data);
			}

			#echo "::".HtmlSpecialChars($data)."
\n";

			return $data;
		}

		#####################################################################################

		function check_tags($data){

			$data = preg_replace("/<(.*?)>/se", "\$this->process_tag(\$this->StripSingle('\\1'))",	$data);

			foreach(array_keys($this->tag_counts) as $tag){
				for($i=0; $i<$this->tag_counts[$tag]; $i++){
					$data .= "</$tag>";
				}
			}

			return $data;
		}

		#####################################################################################

		function process_tag($data){

			# ending tags
			if (preg_match("/^\/([a-z0-9]+)/si", $data, $matches)){
				$name = StrToLower($matches[1]);
				if (in_array($name, array_keys($this->allowed))){
					if (!in_array($name, $this->no_close)){
						if ($this->tag_counts[$name]){
							$this->tag_counts[$name]--;
							return '</'.$name.'>';
						}
					}
				}else{
					return '';
				}
			}

			# starting tags
			if (preg_match("/^([a-z0-9]+)(.*?)(\/?)$/si", $data, $matches)){

				$name = StrToLower($matches[1]);
				$body = $matches[2];
				$ending = $matches[3];
				if (in_array($name, array_keys($this->allowed))){
					$params = "";
					preg_match_all("/([a-z0-9]+)=([\"'])(.*?)\\2/si", $body, $matches_2, PREG_SET_ORDER);		# <foo a="b" />
					preg_match_all("/([a-z0-9]+)(=)([^\"\s']+)/si", $body, $matches_1, PREG_SET_ORDER);		# <foo a=b />
					preg_match_all("/([a-z0-9]+)=([\"'])([^\"']*?)\s*$/si", $body, $matches_3, PREG_SET_ORDER);	# <foo a="b />
					$matches = array_merge($matches_1, $matches_2, $matches_3);

					foreach($matches as $match){
						$pname = StrToLower($match[1]);
						if (in_array($pname, $this->allowed[$name])){
							$value = $match[3];
							if (in_array($pname, $this->protocol_attributes)){
								$value = $this->process_param_protocol($value);
							}
							$params .= " $pname=\"$value\"";
						}
					}
					if (in_array($name, $this->no_close)){
						$ending = ' /';
					}
					if (in_array($name, $this->always_close)){
						$ending = '';
					}
					if (!$ending){
						if (isset($this->tag_counts[$name])){
							$this->tag_counts[$name]++;
						}else{
							$this->tag_counts[$name] = 1;
						}
					}
					if ($ending){
						$ending = ' /';
					}
					return '<'.$name.$params.$ending.'>';
				}else{
					return '';
				}
			}

			# comments
			if (preg_match("/^!--(.*)--$/si", $data)){
				if ($this->strip_comments){
					return '';
				}else{
					return '<'.$data.'>';
				}
			}

			# garbage, ignore it
			return '';
		}

		#####################################################################################

		function process_param_protocol($data){

			$data = $this->validate_entities($data, 1);

			if (preg_match("/^([^:]+)\:/si", $data, $matches)){
				if (!in_array($matches[1], $this->allowed_protocols)){
					$data = '#'.substr($data, strlen($matches[1])+1);
				}
			}

			return $data;
		}

		#####################################################################################

		#
		# this function removes certain tag pairs if they have no content. for instance,
		# 'foobar' is converted to 'foobar'.
		#

		function process_remove_blanks($data){

			foreach($this->remove_blanks as $tag){

				$data = preg_replace("/<{$tag}(\s[^>]*)?"."><\\/{$tag}>/", '', $data);
				$data = preg_replace("/<{$tag}(\s[^>]*)?\\/>/", '', $data);
			}
			return $data;
		}

		#####################################################################################

		#
		# given some HTML input, find out if the non-HTML part is too
		# shouty. that is, does it solely consist of capital letters.
		# if so, make it less shouty.
		#

		function fix_case($data){

			#
			# extract only the (latin) letters in the string
			#

			$data_notags = Strip_Tags($data);
			$data_notags = preg_replace('/[^a-zA-Z]/', '', $data_notags);

			#
			# if there are less than 5, just allow it as-is
			#

			if (strlen($data_notags)<5){
				return $data;
			}

			#
			# if there are lowercase letters somewhere, allow it as-is
			#

			if (preg_match('/[a-z]/', $data_notags)){
				return $data;
			}

			#
			# we have more than 5 letters and they're all capitals. we
			# want to case-normalize.
			#

			return preg_replace_callback(
				"/(>|^)([^<]+?)(<|$)/s",
				array($this, 'fix_case_inner'),
				$data
			);
		}

		#####################################################################################

		#
		# given a block of non-HTML, filter it for shoutyness by lowercasing
		# the whole thing and then capitalizing the first letter of each
		# 'sentance'.
		#

		function fix_case_inner($m){

			$data = StrToLower($m[2]);

			$data = preg_replace_callback(
				'/(^|[^\w\s\';,\\-])(\s*)([a-z])/',
				create_function(
					'$m',
					'return $m[1].$m[2].StrToUpper($m[3]);'
				),
				$data
			);

			return $m[1].$data.$m[3];
		}

		#####################################################################################

		#
		# this function is called in two places - inside of each href-like
		# attributes and then on the whole document. it's job is to make
		# sure that anything that looks like an entity (starts with an
		# ampersand) is allowed, else corrects it.
		#

		function validate_entities($data, $in_attribute){

			#
			# turn ascii characters into their actual characters, if requested.
			# we need to always do this inside URLs to avoid people using
			# entities or URL escapes to insert 'javascript:' or something like
			# that. outside of attributes, we optionally filter entities to
			# stop people from inserting text that they shouldn't (since it might
			# make it into a clickable URL via lib_autolink).
			#

			if ($in_attribute || $this->normalise_ascii_entities){
				$data = $this->decode_entities($data, $in_attribute);
			}

			#
			# find every remaining ampersand in the string and check if it looks
			# like it's an entity (then validate it) or if it's not (then escape
			# it).
			#

			$data = preg_replace(
				'!&([^&;]*)(?=(;|&|$))!e',
				"\$this->check_entity(\$this->StripSingle('\\1'), \$this->StripSingle('\\2'))",
				$data
			);

			return $data;
		}

		#####################################################################################

		#
		# this function comes last in processing, to clean up data outside of tags.
 		#

		function cleanup_non_tags($data){

			return preg_replace_callback(
				"/(>|^)([^<]+?)(<|$)/s",
				array($this, 'cleanup_non_tags_inner'),
				$data
			);

		}

		function cleanup_non_tags_inner($m){

			#
			# first, deal with the entities
			#

			$m[2] = $this->validate_entities($m[2], 0);

			#
			# find any literal quotes outside of tags and replace them
			# with ". we call it last thing before returning.
			#

			$m[2] = str_replace("\"", """, $m[2]);

			return $m[1].$m[2].$m[3];
		}

		#####################################################################################

		#
		# this function gets passed the 'inside' and 'end' of a suspected
		# entity. the ampersand is not included, but must be part of the
		# return value. $term is a look-ahead assertion, so don't return
		# it.
		#

		function check_entity($preamble, $term){

			#
			# if the terminating character is not a semi-colon, treat
			# this as a non-entity
			#

			if ($term != ';'){

				return '&'.$preamble;
			}

			#
			# if it's an allowed entity, go for it
			#

			if ($this->is_valid_entity($preamble)){

				return '&'.$preamble;
			}

			#
			# not an allowed antity, so escape the ampersand
			#

			return '&'.$preamble;
		}

		#####################################################################################

		#
		# this function determines whether the body of an entity (the
		# stuff between '&' and ';') is valid.
		#

		function is_valid_entity($entity){

			#
			# numeric entity. over 127 is always allowed, else it's a pref
			#

			if (preg_match('!^#([0-9]+)$!i', $entity, $m)){

				return ($m[1] > 127) ? 1 : $this->allow_numbered_entities;
			}

			#
			# hex entity. over 127 is always allowed, else it's a pref
			#

			if (preg_match('!^#x([0-9a-f]+)$!i', $entity, $m)){

				return (hexdec($m[1]) > 127) ? 1 : $this->allow_numbered_entities;
			}

			if (in_array($entity, $this->allowed_entities)){

				return 1;
			}

			return 0;
		}

		#####################################################################################

		#
		# within attributes, we want to convert all hex/dec/url escape sequences into
		# their raw characters so that we can check we don't get stray quotes/brackets
		# inside strings. within general text, we decode hex/dec entities.
		#

		function decode_entities($data, $in_attribute=1){

			$data = preg_replace_callback('!(&)#(\d+);?!', array($this, 'decode_dec_entity'), $data);
			$data = preg_replace_callback('!(&)#x([0-9a-f]+);?!i', array($this, 'decode_hex_entity'), $data);

			if ($in_attribute){
				$data = preg_replace_callback('!(%)([0-9a-f]{2});?!i', array($this, 'decode_hex_entity'), $data);
			}

			return $data;
		}

		function decode_hex_entity($m){

			return $this->decode_num_entity($m[1], hexdec($m[2]));
		}

		function decode_dec_entity($m){

			return $this->decode_num_entity($m[1], intval($m[2]));
		}

		#####################################################################################

		#
		# given a character code and the starting escape character (either '%' or '&'),
		# return either a hex entity (if the character code is non-ascii), or a raw
		# character. remeber to escape XML characters!
		#

		function decode_num_entity($orig_type, $d){

			if ($d < 0){ $d = 32; } # treat control characters as spaces

			#
			# don't mess with high characters - what to replace them with is
			# character-set independant, so we leave them as entities. besides,
			# you can't use them to pass 'javascript:' etc (at present)
			#

			if ($d > 127){
				if ($orig_type == '%'){ return '%'.dechex($d); }
				if ($orig_type == '&'){ return "&#$d;"; }
			}

			#
			# we want to convert this escape sequence into a real character.
			# we call HtmlSpecialChars() incase it's one of [<>"&]
			#

			return HtmlSpecialChars(chr($d));
		}

		#####################################################################################

		function StripSingle($data){
			return str_replace(array('\\"', "\\0"), array('"', chr(0)), $data);
		}

		#####################################################################################

	}


text:
(async function() {
  TestRunner.addResult(`Tests that pause on promise rejection works.\n`);
  await TestRunner.loadLegacyModule('sources'); await TestRunner.loadTestModule('sources_test_runner');
  await TestRunner.showPanel('sources');
  await TestRunner.evaluateInPagePromise(`
      function createPromise()
      {
          var result = {};
          var p = new Promise(function(resolve, reject) {
              result.resolve = resolve;
              result.reject = reject;
          });
          result.promise = p;
          return result;
      }

      function testFunction()
      {
          var resolved = createPromise();
          var caught = createPromise();
          var uncaught = createPromise();

          caught.promise
              .then(function c1() {})
              .then(function c2() {})
              .catch(function c3() {});
          uncaught.promise
              .then(function f1() {})
              .then(function f2() {})
              .then(function f3() {}); // Last is uncaught.

          resolved.resolve(42); // Should not pause.
          caught.reject(new Error("caught"));
          uncaught.reject(new Error("uncaught"));
      }
  `);

  SourcesTestRunner.setQuiet(true);
  SourcesTestRunner.startDebuggerTest(step1);

  function waitUntilPausedNTimes(count, callback) {
    function inner() {
      if (count--)
        SourcesTestRunner.waitUntilPausedAndDumpStackAndResume(inner);
      else
        callback();
    }
    inner();
  }

  function step1() {
    TestRunner.DebuggerAgent.setPauseOnExceptions(
        SDK.DebuggerModel.PauseOnExceptionsState.PauseOnUncaughtExceptions);
    SourcesTestRunner.showScriptSource(
        'debugger-pause-on-promise-rejection.js', step2);
  }

  function step2() {
    TestRunner.addResult('=== Pausing only on uncaught exceptions ===');
    SourcesTestRunner.runTestFunction();
    waitUntilPausedNTimes(1, step3);
  }

  function step3() {
    TestRunner.DebuggerAgent.setPauseOnExceptions(
        SDK.DebuggerModel.PauseOnExceptionsState.PauseOnAllExceptions);
    TestRunner.addResult('\n=== Pausing on all exceptions ===');
    SourcesTestRunner.runTestFunction();
    waitUntilPausedNTimes(2, step4);
  }

  function step4() {
    TestRunner.DebuggerAgent.setPauseOnExceptions(
        SDK.DebuggerModel.PauseOnExceptionsState.DontPauseOnExceptions);
    SourcesTestRunner.completeDebuggerTest();
  }
})();