<commit_before>/**
 * Created by Luke on 01/05/15.
 */

const endpoints = {

    /**
     * source: https://wiki.appnexus.com/display/api/API+Services
     */

    ACCOUNT_RECOVERY_SERVICE: '/account-recovery',
    AD_PROFILE_SERVICE: '/ad-profile',
    AD_QUALITY_RULE_SERVICE: '/ad-quality-rule',
    AD_SERVER_SERVICE: '/ad-server',
    ADVERTISER_SERVICE: '/advertiser',
    APP_INSTALLATION_SERVICE: '/app-installation',
    AUTHENTICATION_SERVICE: '/auth',
    BATCH_SEGMENT_SERVICE: '/batch-segment',
    BRAND_COMPANY_SERVICE: '/brand-company',
    BRAND_SERVICE: '/brand',
    BROKER_SERVICE: '/broker',
    BROWSER_SERVICE: '/browser',
    CAMPAIGN_SERVICE: '/campaign',
    CARRIER_SERVICE: '/carrier',
    CATEGORY_SERVICE: '/category',
    CITY_SERVICE: '/city',
    CLICK_TRACKER_SERVICE: '/clicktracker',
    CONTENT_CATEGORY_SERVICE: '/content-category',
    COUNTRY_SERVICE: '/country',
    CREATIVE_CUSTOM_REQUEST_TEMPLATE_SERVICE: '/creative-custom-request-template',
    CREATIVE_CUSTOM_REQUEST_TEMPLATE_TYPE_SERVICE: '/creative-custom-request-template-type',
    CREATIVE_FOLDER_SERVICE: '/creative-folder',
    CREATIVE_FORMAT_SERVICE: '/creative-format',
    CREATIVE_MACRO_CHECK_SERVICE: '/creative-macro-check',
    CREATIVE_SEARCH_SERVICE: '/creative-search',
    CREATIVE_SERVICE: '/creative',
    CREATIVE_TEMPLATE_SERVICE: '/template',
    CURRENCY_SERVICE: '/currency',
    DEAL_BUYER_ACCESS_SERVICE: '/package-buyer-access',
    DEAL_FROM_PACKAGE_SERVICE: '/deal-from-package',
    DEAL_SERVICE: '/deal',
    DEMOGRAPHIC_AREA_SERVICE: '/dma',
    DEVELOPER_SERVICE: '/developer',
    DEVICE_MAKE_SERVICE: '/device-make',
    DEVICE_MODEL_SERVICE: '/device-model',
    DOMAIN_AUDIT_STATUS_SERVICE: '/url-audit-search',
    DOMAIN_LIST_SERVICE: '/domain-list',
    EXTERNAL_INVENTORY_CODE_SERVICE: '/external-inv-code',
    EXTRACT_CLICKTAGS_SERVICE: '/extract-click-tags',
    FEED_STATUS_SERVICE: '/feed-status',
    IMPRESSION_TRACKER_SERVICE: '/imptracker',
    INSERTION_ORDER_SERVICE: '/insertion-order',
    INVENTORY_ATTRIBUTE_SERVICE: '/inventory-attribute',
    INVENTORY_GROUP_SERVICE: '/inventory-group',
    INVENTORY_RESOLD_SERVICE: '/inventory-resold',
    INVENTORY_SOURCE_SERVICE: '/inventory-source',
    IP_RANGE_LIST_SERVICE: '/ip-range-list',
    LABEL_SERVICE: '/label',
    LANGUAGE_SERVICE: '/language',
    LINE_ITEM_SERVICE: '/line-item',
    LOG_LEVEL_DATA_SERVICE: '/siphon',
    LOOKUP_SERVICE: '/lookup',
    MANUAL_OFFER_RANKING_SERVICE: '/manual-offer-ranking',
    MEDIA_SUBTYPE_SERVICE: '/media-subtype',
    MEDIA_TYPE_SERVICE: '/media-type',
    MEMBER_PROFILE_SERVICE: '/member-profile',
    MEMBER_SERVICE: '/member',
    MOBILE_APP_INSTANCE_LIST_SERVICE: '/mobile-app-instance-list',
    MOBILE_APP_INSTANCE_SERVICE: '/mobile-app-instance',
    MOBILE_APP_SERVICE: '/mobile-app',
    MOBILE_APP_STORE_SERVICE: '/mobile-app-store',
    OBJECT_LIMIT_SERVICE: '/object-limit',
    OPERATING_SYSTEM_EXTENDED_SERVICE: '/operating-system-extended',
    OPERATING_SYSTEM_FAMILY_SERVICE: '/operating-system-family',
    OPERATING_SYSTEM_SERVICE: '/operating-system',
    OPTIMIZATION_ZONE_SERVICE: '/optimization-zone',
    PACKAGE_BUYER_ACCESS_SERVICE: '/package-buyer-access',
    PACKAGE_SERVICE: '/package',
    PAYMENT_RULE_SERVICE: '/payment-rule',
    PIXEL_SERVICE: '/pixel',
    PIXEL_TEMPLATE_SERVICE: '/pixel-template',
    PLACEMENT_SERVICE: '/placement',
    PLATFORM_MEMBER_SERVICE: '/platform-member',
    PLUGIN_INSTANCE_SERVICE: '/plugin-instance',
    PLUGIN_SERVICE: '/plugin',
    PROFILE_SERVICE: '/profile',
    PROFILE_SUMMARY_SERVICE: '/profile-summary',
    PUBLISHER_SERVICE: '/publisher',
    REGION_SERVICE: '/region',
    REPORT_SERVICE: '/report',
    REPORT_STATUS_SERVICE: '/report-status',
    SAVED_REPORT_SERVICE: '/saved-report',
    SEARCH_SERVICE: '/search',
    SEGMENT_SERVICE: '/segment',
    SIPHON_CONFIG_SERVICE: '/siphon-config',
    SITE_SERVICE: '/site',
    TAG_PARSER_SERVICE: '/tag-parser-job',
    TECHNICAL_ATTRIBUTE_SERVICE: '/technical-attribute',
    THIRD_PARTY_PAGE_ACCESS_SERVICE: '/thirdparty-pageaccess',
    THIRD_PARTY_PIXEL_SERVICE: '/thirdparty-pixel',
    TOWN_SERVICE: '/town',
    USER_GROUP_PATTERN_SERVICE: '/usergroup-pattern',
    USER_SERVICE: '/user',
    USER_VERIFICATION_SERVICE: '/user-verification',
    VISIBILITY_PROFILE_SERVICE: '/visibility-profile'

};

export default endpoints;
<commit_msg>4 > 2 spaces<commit_after>/**
 * Created by Luke on 01/05/15.
 */

const endpoints = {

  /**
   * source: https://wiki.appnexus.com/display/api/API+Services
   */

  ACCOUNT_RECOVERY_SERVICE: '/account-recovery',
  AD_PROFILE_SERVICE: '/ad-profile',
  AD_QUALITY_RULE_SERVICE: '/ad-quality-rule',
  AD_SERVER_SERVICE: '/ad-server',
  ADVERTISER_SERVICE: '/advertiser',
  APP_INSTALLATION_SERVICE: '/app-installation',
  AUTHENTICATION_SERVICE: '/auth',
  BATCH_SEGMENT_SERVICE: '/batch-segment',
  BRAND_COMPANY_SERVICE: '/brand-company',
  BRAND_SERVICE: '/brand',
  BROKER_SERVICE: '/broker',
  BROWSER_SERVICE: '/browser',
  CAMPAIGN_SERVICE: '/campaign',
  CARRIER_SERVICE: '/carrier',
  CATEGORY_SERVICE: '/category',
  CITY_SERVICE: '/city',
  CLICK_TRACKER_SERVICE: '/clicktracker',
  CONTENT_CATEGORY_SERVICE: '/content-category',
  COUNTRY_SERVICE: '/country',
  CREATIVE_CUSTOM_REQUEST_TEMPLATE_SERVICE: '/creative-custom-request-template',
  CREATIVE_CUSTOM_REQUEST_TEMPLATE_TYPE_SERVICE: '/creative-custom-request-template-type',
  CREATIVE_FOLDER_SERVICE: '/creative-folder',
  CREATIVE_FORMAT_SERVICE: '/creative-format',
  CREATIVE_MACRO_CHECK_SERVICE: '/creative-macro-check',
  CREATIVE_SEARCH_SERVICE: '/creative-search',
  CREATIVE_SERVICE: '/creative',
  CREATIVE_TEMPLATE_SERVICE: '/template',
  CURRENCY_SERVICE: '/currency',
  DEAL_BUYER_ACCESS_SERVICE: '/package-buyer-access',
  DEAL_FROM_PACKAGE_SERVICE: '/deal-from-package',
  DEAL_SERVICE: '/deal',
  DEMOGRAPHIC_AREA_SERVICE: '/dma',
  DEVELOPER_SERVICE: '/developer',
  DEVICE_MAKE_SERVICE: '/device-make',
  DEVICE_MODEL_SERVICE: '/device-model',
  DOMAIN_AUDIT_STATUS_SERVICE: '/url-audit-search',
  DOMAIN_LIST_SERVICE: '/domain-list',
  EXTERNAL_INVENTORY_CODE_SERVICE: '/external-inv-code',
  EXTRACT_CLICKTAGS_SERVICE: '/extract-click-tags',
  FEED_STATUS_SERVICE: '/feed-status',
  IMPRESSION_TRACKER_SERVICE: '/imptracker',
  INSERTION_ORDER_SERVICE: '/insertion-order',
  INVENTORY_ATTRIBUTE_SERVICE: '/inventory-attribute',
  INVENTORY_GROUP_SERVICE: '/inventory-group',
  INVENTORY_RESOLD_SERVICE: '/inventory-resold',
  INVENTORY_SOURCE_SERVICE: '/inventory-source',
  IP_RANGE_LIST_SERVICE: '/ip-range-list',
  LABEL_SERVICE: '/label',
  LANGUAGE_SERVICE: '/language',
  LINE_ITEM_SERVICE: '/line-item',
  LOG_LEVEL_DATA_SERVICE: '/siphon',
  LOOKUP_SERVICE: '/lookup',
  MANUAL_OFFER_RANKING_SERVICE: '/manual-offer-ranking',
  MEDIA_SUBTYPE_SERVICE: '/media-subtype',
  MEDIA_TYPE_SERVICE: '/media-type',
  MEMBER_PROFILE_SERVICE: '/member-profile',
  MEMBER_SERVICE: '/member',
  MOBILE_APP_INSTANCE_LIST_SERVICE: '/mobile-app-instance-list',
  MOBILE_APP_INSTANCE_SERVICE: '/mobile-app-instance',
  MOBILE_APP_SERVICE: '/mobile-app',
  MOBILE_APP_STORE_SERVICE: '/mobile-app-store',
  OBJECT_LIMIT_SERVICE: '/object-limit',
  OPERATING_SYSTEM_EXTENDED_SERVICE: '/operating-system-extended',
  OPERATING_SYSTEM_FAMILY_SERVICE: '/operating-system-family',
  OPERATING_SYSTEM_SERVICE: '/operating-system',
  OPTIMIZATION_ZONE_SERVICE: '/optimization-zone',
  PACKAGE_BUYER_ACCESS_SERVICE: '/package-buyer-access',
  PACKAGE_SERVICE: '/package',
  PAYMENT_RULE_SERVICE: '/payment-rule',
  PIXEL_SERVICE: '/pixel',
  PIXEL_TEMPLATE_SERVICE: '/pixel-template',
  PLACEMENT_SERVICE: '/placement',
  PLATFORM_MEMBER_SERVICE: '/platform-member',
  PLUGIN_INSTANCE_SERVICE: '/plugin-instance',
  PLUGIN_SERVICE: '/plugin',
  PROFILE_SERVICE: '/profile',
  PROFILE_SUMMARY_SERVICE: '/profile-summary',
  PUBLISHER_SERVICE: '/publisher',
  REGION_SERVICE: '/region',
  REPORT_SERVICE: '/report',
  REPORT_STATUS_SERVICE: '/report-status',
  SAVED_REPORT_SERVICE: '/saved-report',
  SEARCH_SERVICE: '/search',
  SEGMENT_SERVICE: '/segment',
  SIPHON_CONFIG_SERVICE: '/siphon-config',
  SITE_SERVICE: '/site',
  TAG_PARSER_SERVICE: '/tag-parser-job',
  TECHNICAL_ATTRIBUTE_SERVICE: '/technical-attribute',
  THIRD_PARTY_PAGE_ACCESS_SERVICE: '/thirdparty-pageaccess',
  THIRD_PARTY_PIXEL_SERVICE: '/thirdparty-pixel',
  TOWN_SERVICE: '/town',
  USER_GROUP_PATTERN_SERVICE: '/usergroup-pattern',
  USER_SERVICE: '/user',
  USER_VERIFICATION_SERVICE: '/user-verification',
  VISIBILITY_PROFILE_SERVICE: '/visibility-profile'

};

export default endpoints;
<|endoftext|>


<commit_before>var JST = (function() {

	/*
	 * Original script title/version: Object.identical.js/1.11 Copyright (c)
	 * 2011, Chris O'Brien, prettycode.org
	 * http://github.com/prettycode/Object.identical.js
	 *
	 * LICENSE: Permission is hereby granted for unrestricted use, modification,
	 * and redistribution of this script, ONLY under the condition that this
	 * code comment is kept wholly complete, appearing above the script's code
	 * body--in all original or modified implementations of this script, except
	 * those that are minified.
	 */

	/*
	 * Requires ECMAScript 5 functions: - Array.isArray() - Object.keys() -
	 * Array.prototype.forEach() - JSON.stringify()
	 */

	function identical(a, b, sortArrays) {

		function sort(o) {

			if (sortArrays === true && Array.isArray(o)) {
				return o.sort();
			} else if (typeof o !== "object" || o === null) {
				return o;
			}

			var result = {};

			Object.keys(o).sort().forEach(function(key) {
				result[key] = sort(o[key]);
			});

			return result;
		}

		return JSON.stringify(sort(a)) === JSON.stringify(sort(b));
	}

	var resultElement;

	var $fail = {};

	function fail(text) {
		resultElement.insert({
			top : "FAIL - ",
			after : "
" + text
		}).up("div").addClassName("fail");

		throw $fail;
	}

	function toString(value) {

		return Object.toJSON(value);
	}

	function failNotEqual(actual, expected) {
		fail(toString(actual) + " !== " + toString(expected));
	}

	function assertSame(actual, expected) {
		if (actual !== expected) {
			failNotEqual(actual, expected);
		}
	}

	function assertEqual(actual, expected) {

		if (!identical(actual, expected)) {
			failNotEqual(actual, expected);
		}
	}

	function doRunTests(elementId) {

		var passCount = 0;
		var failCount = 0;

		$(elementId).addClassName("js-results").select("div:odd").each(
				function(e) {
					e.addClassName("odd");
				});

		$(elementId).select("div").each(
				function(test) {

					test.addClassName("active");

					test.scrollTo();

					resultElement = test.down("p");
					resultNoted = false;

					var testCode = test.down("pre").textContent;

					try {
						eval(testCode);

						passCount++;

						resultElement.insert({
							top : "PASS - "
						});

						test.addClassName("pass");

					} catch (e) {
						failCount++;

						if (e !== $fail) {
							resultElement.next().insert(
									{
										top : "EXCEPTION - ",
										after : "

"
												+ toString(e) + "
"
									});

							test.addClassName("fail");
						}
					}

					test.removeClassName("active");
				});

		$(elementId)
				.insert(
						{
							top : "
Results: #{pass} passed / #{fail} failed
"
									.interpolate({
										class : failCount == 0 ? "pass"
												: "fail",
										pass : passCount,
										fail : failCount
									})
						});
	}

	function runTestSuite(elementId) {
		Tapestry.onDOMLoaded(function() {
			doRunTests(elementId);
		});
	}

	return {
		fail : fail,
		assertEqual : assertEqual,
		assertSame : assertSame,
		runTestSuite : runTestSuite
	};
})();<commit_msg>TAP5-999: More control over scrolling in both success and failure scenarios<commit_after>var JST = (function() {

	/*
	 * Original script title/version: Object.identical.js/1.11 Copyright (c)
	 * 2011, Chris O'Brien, prettycode.org
	 * http://github.com/prettycode/Object.identical.js
	 *
	 * LICENSE: Permission is hereby granted for unrestricted use, modification,
	 * and redistribution of this script, ONLY under the condition that this
	 * code comment is kept wholly complete, appearing above the script's code
	 * body--in all original or modified implementations of this script, except
	 * those that are minified.
	 */

	/*
	 * Requires ECMAScript 5 functions: - Array.isArray() - Object.keys() -
	 * Array.prototype.forEach() - JSON.stringify()
	 */

	function identical(a, b, sortArrays) {

		function sort(o) {

			if (sortArrays === true && Array.isArray(o)) {
				return o.sort();
			} else if (typeof o !== "object" || o === null) {
				return o;
			}

			var result = {};

			Object.keys(o).sort().forEach(function(key) {
				result[key] = sort(o[key]);
			});

			return result;
		}

		return JSON.stringify(sort(a)) === JSON.stringify(sort(b));
	}

	var resultElement;

	var $fail = {};

	function fail(text) {
		resultElement.insert({
			top : "FAIL - ",
			after : "
" + text
		}).up("div").addClassName("fail").scrollTo();

		throw $fail;
	}

	function toString(value) {

		return Object.toJSON(value);
	}

	function failNotEqual(actual, expected) {
		fail(toString(actual) + " !== " + toString(expected));
	}

	function assertSame(actual, expected) {
		if (actual !== expected) {
			failNotEqual(actual, expected);
		}
	}

	function assertEqual(actual, expected) {

		if (!identical(actual, expected)) {
			failNotEqual(actual, expected);
		}
	}

	function doRunTests(elementId) {

		var passCount = 0;
		var failCount = 0;

		$(elementId).addClassName("js-results").select("div:odd").each(
				function(e) {
					e.addClassName("odd");
				});

		$(elementId).select("div").each(
				function(test) {

					test.addClassName("active");

					resultElement = test.down("p");
					resultNoted = false;

					var testCode = test.down("pre").textContent;

					try {
						eval(testCode);

						passCount++;

						resultElement.insert({
							top : "PASS - "
						});

						test.addClassName("pass");

					} catch (e) {
						failCount++;

						if (e !== $fail) {
							resultElement.next().insert(
									{
										top : "EXCEPTION - ",
										after : "

"
												+ toString(e) + "
"
									});

							test.addClassName("fail").scrollTo();
						}
					}

					test.removeClassName("active");
				});

		$(elementId)
				.insert(
						{
							top : "
Results: #{pass} passed / #{fail} failed
"
									.interpolate({
										class : failCount == 0 ? "pass"
												: "fail",
										pass : passCount,
										fail : failCount
									})
						});

		if (failCount == 0) {
			$(elementId).down("p").scrollTo();
		}
	}

	function runTestSuite(elementId) {
		Tapestry.onDOMLoaded(function() {
			doRunTests(elementId);
		});
	}

	return {
		fail : fail,
		assertEqual : assertEqual,
		assertSame : assertSame,
		runTestSuite : runTestSuite
	};
})();<|endoftext|>


<commit_before>const React = require('react');
const ReactNative = React;

ReactNative.StyleSheet = {
  create: function create(styles) {
      return styles;
  }
};

class View extends React.Component {
  render() { return false; }
}

View.propTypes = {
  style: () => null
};

class ListView extends React.Component {
  static DataSource() {
  }
}

class AppRegistry {
  static registerComponent () {
  }
}

const Animated = {
  timing: () => ({ start: () => undefined }),
  Value: class {},
  View: View
};

ReactNative.View = View;
ReactNative.ScrollView = View;
ReactNative.ListView = ListView;
ReactNative.Text = View;
ReactNative.TouchableOpacity = View;
ReactNative.TouchableHighlight = View;
ReactNative.TouchableWithoutFeedback = View;
ReactNative.ToolbarAndroid = View;
ReactNative.Image = View;
ReactNative.AppRegistry = AppRegistry;
ReactNative.Animated = Animated;

module.exports = ReactNative;
<commit_msg>unique native commponents mocks<commit_after>const React = require('react');
const ReactNative = React;

ReactNative.StyleSheet = {
  create: function create(styles) {
      return styles;
  }
};

class View extends React.Component {
  render() { return false; }
}

View.propTypes = {
  style: () => null
};

class ListView extends React.Component {
  static DataSource() {
  }
}

class AppRegistry {
  static registerComponent () {
  }
}

const Animated = {
  timing: () => ({ start: () => undefined }),
  Value: class {},
  View: View
};

const Text = () => "Text";
const TouchableHighlight = () => false;
const TouchableWithoutFeedback = () => false;
const TouchableOpacity = () => false;
const ToolbarAndroid = () => false;
const Image = () => false;
const ScrollView = () => false;

ReactNative.View = View;
ReactNative.ScrollView = ScrollView;
ReactNative.ListView = ListView;
ReactNative.Text = Text;
ReactNative.TouchableOpacity = TouchableOpacity;
ReactNative.TouchableHighlight = TouchableHighlight;
ReactNative.TouchableWithoutFeedback = TouchableWithoutFeedback;
ReactNative.ToolbarAndroid = ToolbarAndroid;
ReactNative.Image = Image;
ReactNative.AppRegistry = AppRegistry;
ReactNative.Animated = Animated;

module.exports = ReactNative;
<|endoftext|>


<commit_before>import React from 'react'
import Link from 'next/link'
import useUser from '../lib/useUser'
import { useRouter } from 'next/router'
import fetchJson from '../lib/fetchJson'

const Header = () => {
  const { user, mutateUser } = useUser()
  const router = useRouter()
  return (

            <Link href="/">
              Home
            </Link>

          {!user?.isLoggedIn && (

              <Link href="/login">
                Login
              </Link>

          )}
          {user?.isLoggedIn && (
            <>

                <Link href="/profile-sg">

                     Profile
                    (Static Generation, recommended)

                </Link>

                <Link href="/profile-ssr">
                  Profile (Server-side Rendering)
                </Link>

                 {
                    e.preventDefault()
                    await mutateUser(fetchJson('/api/logout'))
                    router.push('/login')
                  }}
                >
                  Logout

            </>
          )}

  )
}

export default Header
<commit_msg>Fix typo in Header component of with-iron-session example (#21428)<commit_after>import React from 'react'
import Link from 'next/link'
import useUser from '../lib/useUser'
import { useRouter } from 'next/router'
import fetchJson from '../lib/fetchJson'

const Header = () => {
  const { user, mutateUser } = useUser()
  const router = useRouter()
  return (

            <Link href="/">
              Home
            </Link>

          {!user?.isLoggedIn && (

              <Link href="/login">
                Login
              </Link>

          )}
          {user?.isLoggedIn && (
            <>

                <Link href="/profile-sg">

                     Profile
                    (Static Generation, recommended)

                </Link>

                <Link href="/profile-ssr">
                  Profile (Server-side Rendering)
                </Link>

                 {
                    e.preventDefault()
                    await mutateUser(fetchJson('/api/logout'))
                    router.push('/login')
                  }}
                >
                  Logout

            </>
          )}

  )
}

export default Header
<|endoftext|>


<commit_before>const {Fragment, Slice} = require("../model")

const {ReplaceStep, ReplaceAroundStep} = require("./replace_step")
const {Transform} = require("./transform")

// :: (number, number) → Transform
// Delete the content between the given positions.
Transform.prototype.delete = function(from, to) {
  return this.replace(from, to, Slice.empty)
}

// :: (Node, number, ?number, ?Slice) → ?Step
function replaceStep(doc, from, to = from, slice = Slice.empty) {
  if (from == to && !slice.size) return null

  let $from = doc.resolve(from), $to = doc.resolve(to)
  let placed = placeSlice($from, slice)

  let fittedLeft = fitLeft($from, placed)
  let fitted = fitRight($from, $to, fittedLeft)
  if (!fitted) return null
  if (fittedLeft.size != fitted.size && canMoveText($from, $to, fittedLeft)) {
    let d = $to.depth, after = $to.after(d)
    while (d > 1 && after == $to.end(--d)) ++after
    let fittedAfter = fitRight($from, doc.resolve(after), fittedLeft)
    if (fittedAfter)
      return new ReplaceAroundStep(from, after, to, $to.end(), fittedAfter, fittedLeft.size)
  }
  return new ReplaceStep(from, to, fitted)
}
exports.replaceStep = replaceStep

// :: (number, ?number, ?Slice) → Transform
// Replace the part of the document between `from` and `to` with the
// part of the `source` between `start` and `end`.
Transform.prototype.replace = function(from, to = from, slice = Slice.empty) {
  let step = replaceStep(this.doc, from, to, slice)
  if (step) this.step(step)
  return this
}

// :: (number, number, union<Fragment, Node, [Node]>) → Transform
// Replace the given range with the given content, which may be a
// fragment, node, or array of nodes.
Transform.prototype.replaceWith = function(from, to, content) {
  return this.replace(from, to, new Slice(Fragment.from(content), 0, 0))
}

// :: (number, union<Fragment, Node, [Node]>) → Transform
// Insert the given content at the given position.
Transform.prototype.insert = function(pos, content) {
  return this.replaceWith(pos, pos, content)
}

// :: (number, string) → Transform
// Insert the given text at `pos`, inheriting the marks of the
// existing content at that position.
Transform.prototype.insertText = function(pos, text) {
  return this.insert(pos, this.doc.type.schema.text(text, this.doc.marksAt(pos)))
}

// :: (number, Node) → Transform
// Insert the given node at `pos`, inheriting the marks of the
// existing content at that position.
Transform.prototype.insertInline = function(pos, node) {
  return this.insert(pos, node.mark(this.doc.marksAt(pos)))
}

function fitLeftInner($from, depth, placed, placedBelow) {
  let content = Fragment.empty, openRight = 0, placedHere = placed[depth]
  if ($from.depth > depth) {
    let inner = fitLeftInner($from, depth + 1, placed, placedBelow || placedHere)
    openRight = inner.openRight + 1
    content = Fragment.from($from.node(depth + 1).copy(inner.content))
  }

  if (placedHere) {
    content = content.append(placedHere.content)
    openRight = placedHere.openRight
  }
  if (placedBelow) {
    content = content.append($from.node(depth).contentMatchAt($from.indexAfter(depth)).fillBefore(Fragment.empty, true))
    openRight = 0
  }

  return {content, openRight}
}

function fitLeft($from, placed) {
  let {content, openRight} = fitLeftInner($from, 0, placed, false)
  return new Slice(content, $from.depth, openRight || 0)
}

function fitRightJoin(content, parent, $from, $to, depth, openLeft, openRight) {
  let match, count = content.childCount, matchCount = count - (openRight > 0 ? 1 : 0)
  if (openLeft < 0)
    match = parent.contentMatchAt(matchCount)
  else if (count == 1 && openRight > 0)
    match = $from.node(depth).contentMatchAt(openLeft ? $from.index(depth) : $from.indexAfter(depth))
  else
    match = $from.node(depth).contentMatchAt($from.indexAfter(depth))
      .matchFragment(content, count > 0 && openLeft ? 1 : 0, matchCount)

  let toNode = $to.node(depth)
  if (openRight > 0 && depth < $to.depth) {
    // FIXME find a less allocaty approach
    let after = toNode.content.cutByIndex($to.indexAfter(depth)).addToStart(content.lastChild)
    let joinable = match.fillBefore(after, true)
    // Can't insert content if there's a single node stretched across this gap
    if (joinable && joinable.size && openLeft > 0 && count == 1) joinable = null

    if (joinable) {
      let inner = fitRightJoin(content.lastChild.content, content.lastChild, $from, $to,
                               depth + 1, count == 1 ? openLeft - 1 : -1, openRight - 1)
      if (inner) {
        let last = content.lastChild.copy(inner)
        if (joinable.size)
          return content.cutByIndex(0, count - 1).append(joinable).addToEnd(last)
        else
          return content.replaceChild(count - 1, last)
      }
    }
  }
  if (openRight > 0)
    match = match.matchNode(count == 1 && openLeft > 0 ? $from.node(depth + 1) : content.lastChild)

  // If we're here, the next level can't be joined, so we see what
  // happens if we leave it open.
  let toIndex = $to.index(depth)
  if (toIndex == toNode.childCount && !toNode.type.compatibleContent(parent.type)) return null
  let joinable = match.fillBefore(toNode.content, true, toIndex)
  if (!joinable) return null

  if (openRight > 0) {
    let closed = fitRightClosed(content.lastChild, openRight - 1, $from, depth + 1,
                                count == 1 ? openLeft - 1 : -1)
    content = content.replaceChild(count - 1, closed)
  }
  content = content.append(joinable)
  if ($to.depth > depth)
    content = content.addToEnd(fitRightSeparate($to, depth + 1))
  return content
}

function fitRightClosed(node, openRight, $from, depth, openLeft) {
  let match, content = node.content, count = content.childCount
  if (openLeft >= 0)
    match = $from.node(depth).contentMatchAt($from.indexAfter(depth))
      .matchFragment(content, openLeft > 0 ? 1 : 0, count)
  else
    match = node.contentMatchAt(count)

  if (openRight > 0) {
    let closed = fitRightClosed(content.lastChild, openRight - 1, $from, depth + 1,
                                count == 1 ? openLeft - 1 : -1)
    content = content.replaceChild(count - 1, closed)
  }

  return node.copy(content.append(match.fillBefore(Fragment.empty, true)))
}

function fitRightSeparate($to, depth) {
  let node = $to.node(depth)
  let fill = node.contentMatchAt(0).fillBefore(node.content, true, $to.index(depth))
  if ($to.depth > depth) fill = fill.addToEnd(fitRightSeparate($to, depth + 1))
  return node.copy(fill)
}

function normalizeSlice(content, openLeft, openRight) {
  while (openLeft > 0 && openRight > 0 && content.childCount == 1) {
    content = content.firstChild.content
    openLeft--
    openRight--
  }
  return new Slice(content, openLeft, openRight)
}

// : (ResolvedPos, ResolvedPos, number, Slice) → Slice
function fitRight($from, $to, slice) {
  let fitted = fitRightJoin(slice.content, $from.node(0), $from, $to, 0, slice.openLeft, slice.openRight)
  // FIXME we might want to be clever about selectively dropping nodes here?
  if (!fitted) return null
  return normalizeSlice(fitted, slice.openLeft, $to.depth)
}

function canMoveText($from, $to, slice) {
  if (!$to.parent.isTextblock) return false

  let match
  if (!slice.openRight) {
    let parent = $from.node($from.depth - (slice.openLeft - slice.openRight))
    if (!parent.isTextblock) return false
    match = parent.contentMatchAt(parent.childCount)
    if (slice.size)
      match = match.matchFragment(slice.content, slice.openLeft ? 1 : 0)
  } else {
    let parent = nodeRight(slice.content, slice.openRight)
    if (!parent.isTextblock) return false
    match = parent.contentMatchAt(parent.childCount)
  }
  match = match.matchFragment($to.parent.content, $to.index())
  return match && match.validEnd()
}

// Algorithm for 'placing' the elements of a slice into a gap:
//
// We consider the content of each node that is open to the left to be
// independently placeable. I.e. in <p("foo"), p("bar")>, when the
// paragraph on the left is open, "foo" can be placed (somewhere on
// the left side of the replacement gap) independently from p("bar").
//
// So placeSlice splits up a slice into a number of sub-slices,
// along with information on where they can be placed on the given
// left-side edge. It works by walking the open side of the slice,
// from the inside out, and trying to find a landing spot for each
// element, by simultaneously scanning over the gap side. When no
// place is found for an open node's content, it is left in that node.
//
// If the outer content can't be placed, a set of wrapper nodes is
// made up for it (by rooting it in the document node type using
// findWrapping), and the algorithm continues to iterate over those.
// This is guaranteed to find a fit, since both stacks now start with
// the same node type (doc).

function nodeLeft(content, depth) {
  for (let i = 1; i < depth; i++) content = content.firstChild.content
  return content.firstChild
}

function nodeRight(content, depth) {
  for (let i = 1; i < depth; i++) content = content.lastChild.content
  return content.lastChild
}

function placeSlice($from, slice) {
  let dFrom = $from.depth, unplaced = null
  let placed = [], parents = null

  for (let dSlice = slice.openLeft;; --dSlice) {
    let curType, curAttrs, curFragment
    if (dSlice >= 0) {
      if (dSlice > 0) { // Inside slice
        ;({type: curType, attrs: curAttrs, content: curFragment} = nodeLeft(slice.content, dSlice))
      } else if (dSlice == 0) { // Top of slice
        curFragment = slice.content
      }
      if (dSlice < slice.openLeft) curFragment = curFragment.cut(curFragment.firstChild.nodeSize)
    } else { // Outside slice
      curFragment = Fragment.empty
      let parent = parents[parents.length + dSlice - 1]
      curType = parent.type
      curAttrs = parent.attrs
    }
    if (unplaced)
      curFragment = curFragment.addToStart(unplaced)

    if (curFragment.size == 0 && dSlice <= 0) break

    // FIXME cut/remove marks when it helps find a placement
    let found = findPlacement(curFragment, $from, dFrom)
    if (found) {
      if (found.fragment.size > 0) placed[found.depth] = {
        content: found.fill.append(found.fragment),
        openRight: dSlice > 0 ? 0 : slice.openRight - dSlice,
        depth: found.depth
      }
      if (dSlice <= 0) break
      unplaced = null
      dFrom = Math.max(0, found.depth - 1)
    } else {
      if (dSlice == 0) {
        let top = $from.node(0)
        parents = top.contentMatchAt($from.index(0)).findWrapping(curFragment.firstChild.type, curFragment.firstChild.attrs)
        if (!parents) break
        let last = parents[parents.length - 1]
        if (last ? !last.type.contentExpr.matches(last.attrs, curFragment)
                 : !top.canReplace($from.indexAfter(0), $from.depth ? $from.index(0) : $from.indexAfter(0), curFragment)) break
        parents = [{type: top.type, attrs: top.attrs}].concat(parents)
        curType = parents[parents.length - 1].type
        curAttrs = parents[parents.length - 1].type
      }
      curFragment = curType.contentExpr.start(curAttrs).fillBefore(curFragment, true).append(curFragment)
      unplaced = curType.create(curAttrs, curFragment)
    }
  }

  return placed
}

function findPlacement(fragment, $from, start) {
  let hasMarks = false
  for (let i = 0; i < fragment.childCount; i++)
    if (fragment.child(i).marks.length) hasMarks = true
  for (let d = start; d >= 0; d--) {
    let startMatch = $from.node(d).contentMatchAt($from.indexAfter(d))
    let match = startMatch.fillBefore(fragment)
    if (match) return {depth: d, fill: match, fragment}
    if (hasMarks) {
      let stripped = matchStrippingMarks(startMatch, fragment)
      if (stripped) return {depth: d, fill: Fragment.empty, fragment: stripped}
    }
  }
}

function matchStrippingMarks(match, fragment) {
  let newNodes = []
  for (let i = 0; i < fragment.childCount; i++) {
    let node = fragment.child(i), stripped = node.mark(node.marks.filter(m => match.allowsMark(m.type)))
    match = match.matchNode(stripped)
    if (!match) return null
    newNodes.push(stripped)
  }
  return Fragment.from(newNodes)
}
<commit_msg>Start on Yet Another Different Approach<commit_after>const {Fragment, Slice} = require("../model")

const {ReplaceStep, ReplaceAroundStep} = require("./replace_step")
const {Transform} = require("./transform")

// :: (number, number) → Transform
// Delete the content between the given positions.
Transform.prototype.delete = function(from, to) {
  return this.replace(from, to, Slice.empty)
}

// :: (Node, number, ?number, ?Slice) → ?Step
function replaceStep(doc, from, to = from, slice = Slice.empty) {
  if (from == to && !slice.size) return null

  let $from = doc.resolve(from), $to = doc.resolve(to)
  let placed = placeSlice($from, slice)

  let fittedLeft = fitLeft($from, placed)
  let fitted = fitRight($from, $to, fittedLeft)
  if (!fitted) return null
  if (fittedLeft.size != fitted.size && canMoveText($from, $to, fittedLeft)) {
    let d = $to.depth, after = $to.after(d)
    while (d > 1 && after == $to.end(--d)) ++after
    let fittedAfter = fitRight($from, doc.resolve(after), fittedLeft)
    if (fittedAfter)
      return new ReplaceAroundStep(from, after, to, $to.end(), fittedAfter, fittedLeft.size)
  }
  return new ReplaceStep(from, to, fitted)
}
exports.replaceStep = replaceStep

// :: (number, ?number, ?Slice) → Transform
// Replace the part of the document between `from` and `to` with the
// part of the `source` between `start` and `end`.
Transform.prototype.replace = function(from, to = from, slice = Slice.empty) {
  let step = replaceStep(this.doc, from, to, slice)
  if (step) this.step(step)
  return this
}

// :: (number, number, union<Fragment, Node, [Node]>) → Transform
// Replace the given range with the given content, which may be a
// fragment, node, or array of nodes.
Transform.prototype.replaceWith = function(from, to, content) {
  return this.replace(from, to, new Slice(Fragment.from(content), 0, 0))
}

// :: (number, union<Fragment, Node, [Node]>) → Transform
// Insert the given content at the given position.
Transform.prototype.insert = function(pos, content) {
  return this.replaceWith(pos, pos, content)
}

// :: (number, Node) → Transform
// Insert the given node at `pos`, inheriting the marks of the
// existing content at that position.
Transform.prototype.insertInline = function(pos, node) {
  return this.insert(pos, node.mark(this.doc.marksAt(pos)))
}

function fitLeftInner($from, depth, placed, placedBelow) {
  let content = Fragment.empty, openRight = 0, placedHere = placed[depth]
  if ($from.depth > depth) {
    let inner = fitLeftInner($from, depth + 1, placed, placedBelow || placedHere)
    openRight = inner.openRight + 1
    content = Fragment.from($from.node(depth + 1).copy(inner.content))
  }

  if (placedHere) {
    content = content.append(placedHere.content)
    openRight = placedHere.openRight
  }
  if (placedBelow) {
    content = content.append($from.node(depth).contentMatchAt($from.indexAfter(depth)).fillBefore(Fragment.empty, true))
    openRight = 0
  }

  return {content, openRight}
}

function fitLeft($from, placed) {
  let {content, openRight} = fitLeftInner($from, 0, placed, false)
  return new Slice(content, $from.depth, openRight || 0)
}

function fitRightJoin(content, parent, $from, $to, depth, openLeft, openRight) {
  let match, count = content.childCount, matchCount = count - (openRight > 0 ? 1 : 0)
  if (openLeft < 0)
    match = parent.contentMatchAt(matchCount)
  else if (count == 1 && openRight > 0)
    match = $from.node(depth).contentMatchAt(openLeft ? $from.index(depth) : $from.indexAfter(depth))
  else
    match = $from.node(depth).contentMatchAt($from.indexAfter(depth))
      .matchFragment(content, count > 0 && openLeft ? 1 : 0, matchCount)

  let toNode = $to.node(depth)
  if (openRight > 0 && depth < $to.depth) {
    // FIXME find a less allocaty approach
    let after = toNode.content.cutByIndex($to.indexAfter(depth)).addToStart(content.lastChild)
    let joinable = match.fillBefore(after, true)
    // Can't insert content if there's a single node stretched across this gap
    if (joinable && joinable.size && openLeft > 0 && count == 1) joinable = null

    if (joinable) {
      let inner = fitRightJoin(content.lastChild.content, content.lastChild, $from, $to,
                               depth + 1, count == 1 ? openLeft - 1 : -1, openRight - 1)
      if (inner) {
        let last = content.lastChild.copy(inner)
        if (joinable.size)
          return content.cutByIndex(0, count - 1).append(joinable).addToEnd(last)
        else
          return content.replaceChild(count - 1, last)
      }
    }
  }
  if (openRight > 0)
    match = match.matchNode(count == 1 && openLeft > 0 ? $from.node(depth + 1) : content.lastChild)

  // If we're here, the next level can't be joined, so we see what
  // happens if we leave it open.
  let toIndex = $to.index(depth)
  if (toIndex == toNode.childCount && !toNode.type.compatibleContent(parent.type)) return null
  let joinable = match.fillBefore(toNode.content, true, toIndex)
  if (!joinable) return null

  if (openRight > 0) {
    let closed = fitRightClosed(content.lastChild, openRight - 1, $from, depth + 1,
                                count == 1 ? openLeft - 1 : -1)
    content = content.replaceChild(count - 1, closed)
  }
  content = content.append(joinable)
  if ($to.depth > depth)
    content = content.addToEnd(fitRightSeparate($to, depth + 1))
  return content
}

function fitRightClosed(node, openRight, $from, depth, openLeft) {
  let match, content = node.content, count = content.childCount
  if (openLeft >= 0)
    match = $from.node(depth).contentMatchAt($from.indexAfter(depth))
      .matchFragment(content, openLeft > 0 ? 1 : 0, count)
  else
    match = node.contentMatchAt(count)

  if (openRight > 0) {
    let closed = fitRightClosed(content.lastChild, openRight - 1, $from, depth + 1,
                                count == 1 ? openLeft - 1 : -1)
    content = content.replaceChild(count - 1, closed)
  }

  return node.copy(content.append(match.fillBefore(Fragment.empty, true)))
}

function fitRightSeparate($to, depth) {
  let node = $to.node(depth)
  let fill = node.contentMatchAt(0).fillBefore(node.content, true, $to.index(depth))
  if ($to.depth > depth) fill = fill.addToEnd(fitRightSeparate($to, depth + 1))
  return node.copy(fill)
}

function normalizeSlice(content, openLeft, openRight) {
  while (openLeft > 0 && openRight > 0 && content.childCount == 1) {
    content = content.firstChild.content
    openLeft--
    openRight--
  }
  return new Slice(content, openLeft, openRight)
}

// : (ResolvedPos, ResolvedPos, number, Slice) → Slice
function fitRight($from, $to, slice) {
  let fitted = fitRightJoin(slice.content, $from.node(0), $from, $to, 0, slice.openLeft, slice.openRight)
  // FIXME we might want to be clever about selectively dropping nodes here?
  if (!fitted) return null
  return normalizeSlice(fitted, slice.openLeft, $to.depth)
}

function canMoveText($from, $to, slice) {
  if (!$to.parent.isTextblock) return false

  let match
  if (!slice.openRight) {
    let parent = $from.node($from.depth - (slice.openLeft - slice.openRight))
    if (!parent.isTextblock) return false
    match = parent.contentMatchAt(parent.childCount)
    if (slice.size)
      match = match.matchFragment(slice.content, slice.openLeft ? 1 : 0)
  } else {
    let parent = nodeRight(slice.content, slice.openRight)
    if (!parent.isTextblock) return false
    match = parent.contentMatchAt(parent.childCount)
  }
  match = match.matchFragment($to.parent.content, $to.index())
  return match && match.validEnd()
}

// Algorithm for 'placing' the elements of a slice into a gap:
//
// We consider the content of each node that is open to the left to be
// independently placeable. I.e. in <p("foo"), p("bar")>, when the
// paragraph on the left is open, "foo" can be placed (somewhere on
// the left side of the replacement gap) independently from p("bar").
//
// So placeSlice splits up a slice into a number of sub-slices,
// along with information on where they can be placed on the given
// left-side edge. It works by walking the open side of the slice,
// from the inside out, and trying to find a landing spot for each
// element, by simultaneously scanning over the gap side. When no
// place is found for an open node's content, it is left in that node.
//
// If the outer content can't be placed, a set of wrapper nodes is
// made up for it (by rooting it in the document node type using
// findWrapping), and the algorithm continues to iterate over those.
// This is guaranteed to find a fit, since both stacks now start with
// the same node type (doc).

function nodeLeft(content, depth) {
  for (let i = 1; i < depth; i++) content = content.firstChild.content
  return content.firstChild
}

function nodeRight(content, depth) {
  for (let i = 1; i < depth; i++) content = content.lastChild.content
  return content.lastChild
}

function placeSlice($from, slice) {
  let dFrom = $from.depth, unplaced = null
  let placed = [], parents = null

  for (let dSlice = slice.openLeft;; --dSlice) {
    let curType, curAttrs, curFragment
    if (dSlice >= 0) {
      if (dSlice > 0) { // Inside slice
        ;({type: curType, attrs: curAttrs, content: curFragment} = nodeLeft(slice.content, dSlice))
      } else if (dSlice == 0) { // Top of slice
        curFragment = slice.content
      }
      if (dSlice < slice.openLeft) curFragment = curFragment.cut(curFragment.firstChild.nodeSize)
    } else { // Outside slice
      curFragment = Fragment.empty
      let parent = parents[parents.length + dSlice - 1]
      curType = parent.type
      curAttrs = parent.attrs
    }
    if (unplaced)
      curFragment = curFragment.addToStart(unplaced)

    if (curFragment.size == 0 && dSlice <= 0) break

    // FIXME cut/remove marks when it helps find a placement
    let found = findPlacement(curFragment, $from, dFrom)
    if (found) {
      if (found.fragment.size > 0) placed[found.depth] = {
        content: found.fill.append(found.fragment),
        openRight: dSlice > 0 ? 0 : slice.openRight - dSlice,
        depth: found.depth
      }
      if (dSlice <= 0) break
      unplaced = null
      dFrom = Math.max(0, found.depth - 1)
    } else {
      if (dSlice == 0) {
        let top = $from.node(0)
        parents = top.contentMatchAt($from.index(0)).findWrapping(curFragment.firstChild.type, curFragment.firstChild.attrs)
        if (!parents) break
        let last = parents[parents.length - 1]
        if (last ? !last.type.contentExpr.matches(last.attrs, curFragment)
                 : !top.canReplace($from.indexAfter(0), $from.depth ? $from.index(0) : $from.indexAfter(0), curFragment)) break
        parents = [{type: top.type, attrs: top.attrs}].concat(parents)
        curType = parents[parents.length - 1].type
        curAttrs = parents[parents.length - 1].type
      }
      curFragment = curType.contentExpr.start(curAttrs).fillBefore(curFragment, true).append(curFragment)
      unplaced = curType.create(curAttrs, curFragment)
    }
  }

  return placed
}

function findPlacement(fragment, $from, start) {
  let hasMarks = false
  for (let i = 0; i < fragment.childCount; i++)
    if (fragment.child(i).marks.length) hasMarks = true
  for (let d = start; d >= 0; d--) {
    let startMatch = $from.node(d).contentMatchAt($from.indexAfter(d))
    let match = startMatch.fillBefore(fragment)
    if (match) return {depth: d, fill: match, fragment}
    if (hasMarks) {
      let stripped = matchStrippingMarks(startMatch, fragment)
      if (stripped) return {depth: d, fill: Fragment.empty, fragment: stripped}
    }
  }
}

function matchStrippingMarks(match, fragment) {
  let newNodes = []
  for (let i = 0; i < fragment.childCount; i++) {
    let node = fragment.child(i), stripped = node.mark(node.marks.filter(m => match.allowsMark(m.type)))
    match = match.matchNode(stripped)
    if (!match) return null
    newNodes.push(stripped)
  }
  return Fragment.from(newNodes)
}
<|endoftext|>


<commit_before>/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

$(function() {

//    $('.Update .message a').click(function(){
//        openDialog();
//        return false;
//    });
});

function openDialog(itemId)
{
    $( "#testDialog" ).dialog({
            position: 'center',
            modal: true,
            buttons: {
                    Ok: function() {
                            $( this ).dialog( "close" );
                    }
            }
    });
}

function goToUserPage(userId)
{
    var loc = "www.wishlist.com/user/"+id;
    window.location = loc;
}

<commit_msg>more changes lol<commit_after>/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

// buttons used for the dialog
var okLabel = "Ok";
var addToWishlist = "I want!";
var buttons = {};

buttons[okLabel] = function(){$(this).dialog("close");};
buttons[addToWishlist] = function(){alert('to do');};

$(function() {

});

function openDialog(itemId)
{
    // using the item ID, grab the item's info and display in the dialog

    $( "#testDialog" ).dialog({
            position: 'center',
            modal: true,
            buttons: buttons
    });
}

function goToUserPage(userId)
{
    var loc = "www.wishlist.com/user/"+id;
    window.location = loc;
}

<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { Input, InputPresentation } from '../input';
import InputIconToggle from '../input-icon-toggle';
import FormField from '../form-field';
import { withValidation, validationsPropTypes } from '../../../components/validations';
import withUniqueName from '../../../utils/helpers/with-unique-name';
import OptionsHelper from '../../../utils/helpers/options-helper';

// This component is a working example of what a Textbox might look like
// using only the new input componentry. It is still under development with
// subject to change as we continue to remove the decorator classes.

const Textbox = ({
  children,
  inputIcon,
  leftChildren,
  formattedValue,
  value,
  childOfForm,
  isOptional,
  ...props
}) => {
  return (
    <FormField
      childOfForm={ childOfForm }
      isOptional={ isOptional }
      { ...props }
      useValidationIcon={ false }
    >
      <InputPresentation type='text' { ...removeParentProps(props) }>
        { leftChildren }
        <Input
          { ...removeParentProps(props) }
          placeholder={ props.disabled ? '' : props.placeholder }
          aria-invalid={ props.hasError }
          value={ visibleValue(value, formattedValue) }
        />
        { children }
        { inputIcon && <InputIconToggle { ...removeParentProps(props) } inputIcon={ inputIcon } /> }
      </InputPresentation>
    </FormField>
  );
};

function removeParentProps(props) {
  delete props['data-element'];
  delete props['data-component'];
  delete props['data-role'];
  delete props.className;
  return props;
}

function visibleValue(value, formattedValue) {
  return (typeof formattedValue === 'string') ? formattedValue : value;
}

Textbox.propTypes = {
  /**
   * An optional alternative for props.value, this is useful if the
   * real value is an ID but you want to show a human-readable version.
   */
  formattedValue: PropTypes.string,
  /** The value of the Textbox */
  value: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.array // Allows the textbox to be used in the Multi-Select component
  ]),
  /** If true, the component will be disabled */
  disabled: PropTypes.bool,
  /** If true, the component will be read-only */
  readOnly: PropTypes.bool,
  /** Event handler for the change event */
  onChange: PropTypes.func,
  /** Event handler for the keyDown event */
  onKeyDown: PropTypes.func,
  /** Defered callback called after the onChange event */
  onChangeDeferred: PropTypes.func,
  /** Integer to determine timeout for defered callback */
  deferTimeout: PropTypes.number,
  /** Label */
  label: PropTypes.string,
  /** Text applied to label help tooltip */
  labelHelp: PropTypes.string,
  /** When true, label is placed in line an input */
  labelInline: PropTypes.bool,
  /** Width of a label in percentage. Works only when labelInline is true */
  labelWidth: PropTypes.number,
  /** Width of an input in percentage. Works only when labelInline is true */
  inputWidth: PropTypes.number,
  /** Help content to be displayed under an input */
  fieldHelp: PropTypes.node,
  /** Type of the icon that will be rendered next to the input */
  children: PropTypes.node,
  /** Icon to display inside of the Textbox */
  inputIcon: PropTypes.string,
  /** Adds additional child elements before the input */
  leftChildren: PropTypes.node,
  /** List of error validation functions */
  validations: validationsPropTypes,
  /** List of warning validation functions */
  warnings: validationsPropTypes,
  /** List of info validation functions */
  info: validationsPropTypes,
  /** Flag to configure component when in a Form */
  childOfForm: PropTypes.bool,
  /** Flag to configure component as optional in Form */
  isOptional: PropTypes.bool,
  /** Status of error validations */
  hasError: PropTypes.bool,
  /** Status of warnings */
  hasWarning: PropTypes.bool,
  /** Status of info */
  hasInfo: PropTypes.bool,
  /** Size of an input */
  size: PropTypes.oneOf(OptionsHelper.sizesRestricted),
  /** Placeholder string to be displayed in input */
  placeholder: PropTypes.string
};

Textbox.defaultProps = {
  labelWidth: 30,
  inputWidth: 70,
  size: 'medium'
};

export { Textbox as OriginalTextbox };
export default withUniqueName(withValidation(Textbox));
<commit_msg>Update src/__experimental__/components/textbox/textbox.component.js<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { Input, InputPresentation } from '../input';
import InputIconToggle from '../input-icon-toggle';
import FormField from '../form-field';
import { withValidation, validationsPropTypes } from '../../../components/validations';
import withUniqueName from '../../../utils/helpers/with-unique-name';
import OptionsHelper from '../../../utils/helpers/options-helper';

// This component is a working example of what a Textbox might look like
// using only the new input componentry. It is still under development with
// subject to change as we continue to remove the decorator classes.

const Textbox = ({
  children,
  inputIcon,
  leftChildren,
  formattedValue,
  value,
  childOfForm,
  isOptional,
  ...props
}) => {
  return (
    <FormField
      childOfForm={ childOfForm }
      isOptional={ isOptional }
      { ...props }
      useValidationIcon={ false }
    >
      <InputPresentation type='text' { ...removeParentProps(props) }>
        { leftChildren }
        <Input
          { ...removeParentProps(props) }
          placeholder={ props.disabled ? '' : props.placeholder }
          aria-invalid={ props.hasError }
          value={ visibleValue(value, formattedValue) }
        />
        { children }
        { inputIcon && <InputIconToggle { ...removeParentProps(props) } inputIcon={ inputIcon } /> }
      </InputPresentation>
    </FormField>
  );
};

function removeParentProps(props) {
  delete props['data-element'];
  delete props['data-component'];
  delete props['data-role'];
  delete props.className;
  return props;
}

function visibleValue(value, formattedValue) {
  return (typeof formattedValue === 'string') ? formattedValue : value;
}

Textbox.propTypes = {
  /**
   * An optional alternative for props.value, this is useful if the
   * real value is an ID but you want to show a human-readable version.
   */
  formattedValue: PropTypes.string,
  /** The value of the Textbox */
  value: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.array // Allows the textbox to be used in the Multi-Select component
  ]),
  /** If true, the component will be disabled */
  disabled: PropTypes.bool,
  /** If true, the component will be read-only */
  readOnly: PropTypes.bool,
  /** Event handler for the change event */
  onChange: PropTypes.func,
  /** Event handler for the keyDown event */
  onKeyDown: PropTypes.func,
  /** Defered callback called after the onChange event */
  onChangeDeferred: PropTypes.func,
  /** Integer to determine timeout for defered callback */
  deferTimeout: PropTypes.number,
  /** Label */
  label: PropTypes.string,
  /** Text applied to label help tooltip */
  labelHelp: PropTypes.string,
  /** When true, label is placed in line an input */
  labelInline: PropTypes.bool,
  /** Width of a label in percentage. Works only when labelInline is true */
  labelWidth: PropTypes.number,
  /** Width of an input in percentage. Works only when labelInline is true */
  inputWidth: PropTypes.number,
  /** Help content to be displayed under an input */
  fieldHelp: PropTypes.node,
  /** Type of the icon that will be rendered next to the input */
  children: PropTypes.node,
  /** Icon to display inside of the Textbox */
  inputIcon: PropTypes.string,
  /** Additional child elements to display before the input */
  leftChildren: PropTypes.node,
  /** List of error validation functions */
  validations: validationsPropTypes,
  /** List of warning validation functions */
  warnings: validationsPropTypes,
  /** List of info validation functions */
  info: validationsPropTypes,
  /** Flag to configure component when in a Form */
  childOfForm: PropTypes.bool,
  /** Flag to configure component as optional in Form */
  isOptional: PropTypes.bool,
  /** Status of error validations */
  hasError: PropTypes.bool,
  /** Status of warnings */
  hasWarning: PropTypes.bool,
  /** Status of info */
  hasInfo: PropTypes.bool,
  /** Size of an input */
  size: PropTypes.oneOf(OptionsHelper.sizesRestricted),
  /** Placeholder string to be displayed in input */
  placeholder: PropTypes.string
};

Textbox.defaultProps = {
  labelWidth: 30,
  inputWidth: 70,
  size: 'medium'
};

export { Textbox as OriginalTextbox };
export default withUniqueName(withValidation(Textbox));
<|endoftext|>


<commit_before>function narrowCoords()
{
    var input = elim_arrays[armselect.selectedIndex];
    initial = {nestlevel: "t"};
    initial["i"] = input.slice();

    solutions = findOverlappers();

    function findOverlappers()
    {
        var solutions = {};

        for(var coord1 = 0; coord1 < input.length; coord1++)
        {
            var coordslist = [];
            var coord1_full = input[coord1];
            var coord1_left = Number(coord1_full.split(";")[0]);
            var coord1_right = Number(coord1_full.split(";")[1]);
            var did_overlap = false;
            var does_overlap = false;
            var name = coord1 + "";
            solutions[name] = [];
            solution = solutions[name];

            for(var coord2 = Number(coord1) + 1; coord2 < input.length; coord2++)
            {
                if(!does_overlap && did_overlap)
                {
                    break;
                }

                var coord2_full = input[coord2];
                var coord2_left = Number(coord2_full.split(";")[0]);
                var coord2_right = Number(coord2_full.split(";")[1]);

                if(Math.min(coord1_right,coord2_right) > Math.max(coord1_left,coord2_left)) //Overlap test
                {
                var did_overlap = true;
                var does_overlap = true;

                solution.push(input[coord2]);
                }
            }
        }

        return solutions;

    }

    function objectify(obj,sub_arr)
    {
        old_arr = obj[sub_arr];
        obj[sub_arr] = {};
        obj[sub_arr]["nestlevel"] = "" + arr + obj["nestlevel"];
        console.log(obj[sub_arr]["nestlevel"]);

        for(index in old_arr)
        {
           obj[sub_arr][input.indexOf(old_arr[index])] = solutions[input.indexOf(old_arr[index])];
        }

        return obj[sub_arr];
    }

    function buildTree(obj)
    {
        for(arr in obj)
        {
            if(arr !== "nestlevel")
            {
                buildTree(objectify(obj,arr));

                for(index in obj[arr])
                {
                    for(parent in obj["nestlevel"])
                    {
                    	if(obj["nestlevel"][parent].match(/i|t/) !== null)
                    	{
                    		obj[arr][index] = undefined;
                    		obj[arr].sort(); obj[arr].pop();
                    	}
                    	else if(solutions[obj["nestlevel"][parent]].indexOf(obj[arr][index]) === -1)
                    	{
                    		continue
                    	}
                    }
                }
                /*if(obj[arr][0] === undefined)
                {
                    console.log(obj["nestedlevel"] + arr)
                    continue;
                }*/
            }
        }
    }
        buildTree(initial); console.log(initial);
}
//buildTree(objectify(obj,arr));<commit_msg>Delete dnarrow_hotspots.js<commit_after><|endoftext|>


<commit_before>/*
Gradebook from Names and Scores

I worked on this challenge with: Kevin Sullivan
                                 Luis Ybarra
This challenge took me [#] hours.

You will work with the following two variables.  The first, students, holds the names of four students.
The second, scores, holds groups of test scores.  The relative positions of elements within the two
variables match (i.e., 'Joseph' is the first element in students; his scores are the first value in scores.).

Do not alter the students and scores code.

*/

// var students = ["Joseph", "Susan", "William", "Elizabeth"]

// var scores = [ [80, 70, 70, 100],
//                [85, 80, 90, 90],
//                [75, 70, 80, 75],
//                [100, 90, 95, 85] ]

// // __________________________________________
// // Write your code below.

// // Make each student name in students a property of gradebook and assign each the value of a new object.
// var gradebook = {};

// for (var i = 0; i < students.length; i++) {
//   gradebook[students[i]] = {};
// }

// // Give each student property of gradebook its own testScores property and assign it the value of the respective students scores from scores.

// for (var i = 0; i < students.length; i++) {
//   //gradebook[students[i]].testScores = scores[i];
//  gradebook[students[i]] = { testScores: scores[i] };
// }

// // Assign an addScore property to gradebook. Give it the value of a function that accepts name and scorearguments.
// // Have addScore push the score to the value of the testScore property of the gradebook property that matches the value of the name argument.
// // gradebook[students name].testscores.push (new value)

// gradebook.addScore = function (name, score) {
//   this[name].testScores.push(score);
// }

// // Add the getAverage property to gradebook and assign it the value of a function. (This won't actually do anything just yet...)

// gradebook.getAverage = function(name) {
//   var scores = gradebook[name].testScores;
//   return average(scores);
// };

// // Create a new function average that accepts an array of integers and return the average of those integers.
// // NOTE: getAverage and average are different functions.

// var average = function(arr){
//   var summ = 0;
//   for (var j = 0; j < arr.length; j++){
//     summ += arr[j];
//   }
//   return summ / arr.length;
// };

// __________________________________________
// Refactored Solution

var students = ["Joseph", "Susan", "William", "Elizabeth"]

var scores = [ [80, 70, 70, 100],
               [85, 80, 90, 90],
               [75, 70, 80, 75],
               [100, 90, 95, 85] ]

var gradebook = {};

for (var i in students) {
  gradebook[students[i]] = {};
}

for (var i in students) {
  gradebook[students[i]].testScores = scores[i];
}

gradebook.addScore = function (name, score) {
  this[name].testScores.push(score);
}

gradebook.getAverage = function(name) {
  var scores = gradebook[name].testScores;
  return average(scores);
};

var average = function(arr){
  var summ = 0;
  for (var j in arr){
    summ += arr[j];
  }
  return summ / arr.length;
};

// __________________________________________
// Reflect
/*
What did you learn about adding functions to objects?
How did you iterate over nested arrays in JavaScript?
Were there any new methods you were able to incorporate? If so, what were they and how did they work?

*/
// __________________________________________
// Test Code:  Do not alter code below this line.

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

assert(
  (gradebook instanceof Object),
  "The value of gradebook should be an Object.\n",
  "1. "
)

assert(
  (gradebook["Elizabeth"] instanceof Object),
  "gradebook's Elizabeth property should be an object.",
  "2. "
)

assert(
  (gradebook.William.testScores === scores[2]),
  "William's testScores should equal the third element in scores.",
  "3. "
)

assert(
  (gradebook.addScore instanceof Function),
  "The value of gradebook's addScore property should be a Function.",
  "4. "
)

gradebook.addScore("Susan", 80)

assert(
  (gradebook.Susan.testScores.length === 5
   && gradebook.Susan.testScores[4] === 80),
  "Susan's testScores should have a new score of 80 added to the end.",
  "5. "
)

assert(
  (gradebook.getAverage instanceof Function),
  "The value of gradebook's getAverage property should be a Function.",
  "6. "
)

assert(
  (average instanceof Function),
  "The value of average should be a Function.\n",
  "7. "
)
assert(
  average([1, 2, 3]) === 2,
  "average should return the average of the elements in the array argument.\n",
  "8. "
)

assert(
  (gradebook.getAverage("Joseph") === 80),
  "gradebook's getAverage should return 80 if passed 'Joseph'.",
  "9. "
)<commit_msg>complete 8.2 challenge<commit_after>/*
Gradebook from Names and Scores

I worked on this challenge with: Kevin Sullivan

This challenge took me 2 hours.

You will work with the following two variables.  The first, students, holds the names of four students.
The second, scores, holds groups of test scores.  The relative positions of elements within the two
variables match (i.e., 'Joseph' is the first element in students; his scores are the first value in scores.).

Do not alter the students and scores code.

*/

// var students = ["Joseph", "Susan", "William", "Elizabeth"]

// var scores = [ [80, 70, 70, 100],
//                [85, 80, 90, 90],
//                [75, 70, 80, 75],
//                [100, 90, 95, 85] ]

// // __________________________________________
// // Write your code below.

// // Make each student name in students a property of gradebook and assign each the value of a new object.
// var gradebook = {};

// for (var i = 0; i < students.length; i++) {
//   gradebook[students[i]] = {};
// }

// // Give each student property of gradebook its own testScores property and assign it the value of the respective students scores from scores.

// for (var i = 0; i < students.length; i++) {
//   //gradebook[students[i]].testScores = scores[i];
//  gradebook[students[i]] = { testScores: scores[i] };
// }

// // Assign an addScore property to gradebook. Give it the value of a function that accepts name and scorearguments.
// // Have addScore push the score to the value of the testScore property of the gradebook property that matches the value of the name argument.
// // gradebook[students name].testscores.push (new value)

// gradebook.addScore = function (name, score) {
//   this[name].testScores.push(score);
// }

// // Add the getAverage property to gradebook and assign it the value of a function. (This won't actually do anything just yet...)

// gradebook.getAverage = function(name) {
//   var scores = gradebook[name].testScores;
//   return average(scores);
// };

// // Create a new function average that accepts an array of integers and return the average of those integers.
// // NOTE: getAverage and average are different functions.

// var average = function(arr){
//   var summ = 0;
//   for (var j = 0; j < arr.length; j++){
//     summ += arr[j];
//   }
//   return summ / arr.length;
// };

// __________________________________________
// Refactored Solution

var students = ["Joseph", "Susan", "William", "Elizabeth"]

var scores = [ [80, 70, 70, 100],
               [85, 80, 90, 90],
               [75, 70, 80, 75],
               [100, 90, 95, 85] ]

var gradebook = {};

for (var i in students) {
  gradebook[students[i]] = {};
}

for (var i in students) {
  gradebook[students[i]].testScores = scores[i];
}

gradebook.addScore = function (name, score) {
  this[name].testScores.push(score);
}

gradebook.getAverage = function(name) {
  var scores = gradebook[name].testScores;
  return average(scores);
};

var average = function(arr){
  var summ = 0;
  for (var j in arr){
    summ += arr[j];
  }
  return summ / arr.length;
};

// __________________________________________
// Reflect
/*
What did you learn about adding functions to objects?

> The proper syntax. In JavaScript, a function is an attribute of an object and it is simple to add one.

How did you iterate over nested arrays in JavaScript?

> Using a simple for loop

Were there any new methods you were able to incorporate? If so, what were they and how did they work?

> No, not this time.
*/
// __________________________________________
// Test Code:  Do not alter code below this line.

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

assert(
  (gradebook instanceof Object),
  "The value of gradebook should be an Object.\n",
  "1. "
)

assert(
  (gradebook["Elizabeth"] instanceof Object),
  "gradebook's Elizabeth property should be an object.",
  "2. "
)

assert(
  (gradebook.William.testScores === scores[2]),
  "William's testScores should equal the third element in scores.",
  "3. "
)

assert(
  (gradebook.addScore instanceof Function),
  "The value of gradebook's addScore property should be a Function.",
  "4. "
)

gradebook.addScore("Susan", 80)

assert(
  (gradebook.Susan.testScores.length === 5
   && gradebook.Susan.testScores[4] === 80),
  "Susan's testScores should have a new score of 80 added to the end.",
  "5. "
)

assert(
  (gradebook.getAverage instanceof Function),
  "The value of gradebook's getAverage property should be a Function.",
  "6. "
)

assert(
  (average instanceof Function),
  "The value of average should be a Function.\n",
  "7. "
)
assert(
  average([1, 2, 3]) === 2,
  "average should return the average of the elements in the array argument.\n",
  "8. "
)

assert(
  (gradebook.getAverage("Joseph") === 80),
  "gradebook's getAverage should return 80 if passed 'Joseph'.",
  "9. "
)<|endoftext|>


<commit_before>Type.registerNamespace("ExoWeb.UI");

///////////////////////////////////////////////////////////////////////////////
///
/// In addition to defining template markup, also defines rules that are used
/// to determine if it should be chosen as the template for a given element
/// based on a CSS selector as well as a javascript filter that is evaluated
/// against the element in question.
///
///
/// <example>
///		<div sys:attach="template" template:for="table.inputform tr" template:if="<some condition>">

/// </example>
ExoWeb.UI.Template = function(element) {
	ExoWeb.UI.Template.initializeBase(this, [element]);
}

ExoWeb.UI.Template.prototype = {
	get_for: function() {
		return this._for;
	},
	set_for: function(value) {
		this._for = value;
	},
	get_if: function() {
		return this._if;
	},
	set_if: function(value) {
		this._if = value;
	},
	satisfies: function(e) {
		// return true by default if no filter
		var result = true;

		if (this._if) {
			var func = null;

			try {
				// turn arbitrary javascript code into function
				func = new Function("return " + this._if + ";");
			}
			catch (e) {
				throw ("Statement \"" + this._if + "\" causes the following error: " + e);
			}

			if (func) {
				try {
					result = func.call(e);
				}
				catch (e) {
					throw ("Calling \"" + this._if + "\" causes the following error: " + e);
				}
			}
		}

		return result;
	},
	matches: function(e) {
		return $(e).is(this._for);
	},
	test: function(e) {
		return this.matches(e) && this.satisfies(e);
	},
	initialize: function() {
		ExoWeb.UI.Template.callBaseMethod(this, "initialize");

		// add a class that can be used to search for templates
		// and make sure that the template element is hidden
		$(this.get_element()).addClass("vc3-template").hide();
	}
}

///
/// Finds the first field template with a selector and filter that
/// match the given element and returns the template.
///
ExoWeb.UI.Template.find = function(element) {
	var templates = $(".vc3-template");
	for (var t = 0; t < templates.length; t++) {
		var tmpl = templates[t];
		if (ExoWeb.UI.Template.isInstanceOfType(tmpl.control) && tmpl.control.test(element))
			return tmpl;
	}

	return null;
}

ExoWeb.UI.Template.registerClass("ExoWeb.UI.Template", Sys.UI.Control);

///////////////////////////////////////////////////////////////////////////////
///
/// Finds its matching template and renders using the provided data as the
/// binding context.  It can be used as a "field control", using part of the
/// context data to select the appropriate control template.  Another common
/// usage would be to select the appropriate template for a portion of the UI,
/// as in the example where an objects meta type determines how it is
/// displayed in the UI.
///
///
/// <example>
///

/// </example>
ExoWeb.UI.Content = function(element) {
	ExoWeb.UI.Content.initializeBase(this, [element]);
}

ExoWeb.UI.Content.prototype = {
	get_template: function() {
		if (!this._template) {
			var element = this.get_element();
			this._template = ExoWeb.UI.Template.find(element);

			if (!this._template) {
				throw ("This content region does not match any available templates.");
			}
		}

		if (!Sys.UI.Template.isInstanceOfType(this._template))
			this._template = new Sys.UI.Template(this._template);

		return this._template;
	},
	get_data: function() {
		return this._data;
	},
	set_data: function(value) {
		this._data = value;
	},
	render: function() {
		try {
			var tmpl = this.get_template();

			// get custom classes from template
			var classes = $(tmpl.get_element()).attr("class").replace("vc3-template", "").replace("sys-template", "").trim();

			var ctx = tmpl.instantiateIn(this.get_element(), null, this.get_data());

			//ctx.dataItem = this.get_data();

			// copy custom classes from template to content control
			$(this.get_element()).addClass(classes);

			// necessary in order to render components found within the template (like a nested dataview)
			ctx.initializeComponents();
		}
		catch (e) {
			(console && console.log ? console.log : alert)(e);
		}
	},
	initialize: function() {
		ExoWeb.UI.Content.callBaseMethod(this, "initialize");

		// TODO: include meta info about field?

		this.render();
	}
}

ExoWeb.UI.Content.registerClass("ExoWeb.UI.Content", Sys.UI.Control);

///////////////////////////////////////////////////////////////////////////////
///
///
///
ExoWeb.UI.Field = function(element) {
	ExoWeb.UI.Field.initializeBase(this, [element]);
}

ExoWeb.UI.Field.prototype = {
	get_source: function() {
		return this._source;
	},
	set_source: function(value) {
		if (this._source !== value) {
			this._data = null;
			// TODO: can't tell whether label was inferred
			this._source = value;
		}
	},
	get_label: function() {
		if (!this._label) {
			this._label = this.get_source();

			// TODO: more robust solution to human-friendly format
			this._label = this._label.replace(/([^^])([A-Z])/g, "$1 $2");
		}

		return this._label;
	},
	set_label: function(value) {
		this._label = value;
	},
	get_isReadOnly: function() {
		return this._isReadOnly || false;
	},
	set_isReadOnly: function(value) {
		if (!value) throw ("Value is not defined.");

		if (this._isReadOnly != value) {
			// TODO: better bool conversion
			if (typeof (value) == "boolean")
				this._isReadOnly = value;
			else if (typeof (value) == "string")
				this._isReadOnly = (value.toLowerCase() == "true");
			else
				throw ($format("The value \"{val}\" could not be converted to a boolean.", { val: value }));
		}
	},
	get_data: function() {
		if (!this._data) {
			var ctx = this.findContext();
			var target = ctx.dataItem;
			var props = target.meta.property(this.get_source());

			if (!props)
				throw ($format("Property \"{p}\" could not be found.", { p: this.get_source() }));

			var dt = props.lastProperty().get_dataType();

			var format;
			if (!(format = props.lastProperty().get_format()) && dt.formats)
				format = dt.formats.$default;

			this._data = new ExoWeb.Model.Adapter(target, props, format, { label: this.get_label(), readonly: this.get_isReadOnly() });
		}
		return this._data;
	},
	findContext: function(element) {
		/// Finds the containing template control for the given element and
		/// then finds the element's corresponding context (for repeated content).

		var element = this.get_element();
		var container = null;
		var subcontainer = null;

		// find the first parent that is an ASP.NET Ajax template
		while (element.parentNode && !element.parentNode._msajaxtemplate)
			element = element.parentNode;

		// containing template was not found
		if (!element.parentNode || !element.parentNode._msajaxtemplate)
			throw Error.invalidOperation("The field's parent template could not be found.");

		container = element.parentNode;
		subcontainer = element;

		// find the correct context (in the case of repeated content)
		var contexts = container.control.get_contexts();
		if (contexts) {
			for (var i = 0, l = contexts.length; i < l; i++) {
				var ctx = contexts[i];
				if ((ctx.containerElement === container) && (Sys._indexOf(ctx.nodes, subcontainer) > -1)) {
					return ctx;
				}
			}
		}

		return null;
	}
}

ExoWeb.UI.Field.registerClass("ExoWeb.UI.Field", ExoWeb.UI.Content);

///////////////////////////////////////////////////////////////////////////////
//Type.registerNamespace("ExoWeb.Data");

//ExoWeb.Data.DataContext = function ExoWeb$Data$DataContext(rawData) {
//	ExoWeb.Data.DataContext.initializeBase(this);
//	this._rawData = rawData;
//	this.initialize();
//}

//ExoWeb.Data.DataContext.prototype = {
//	// TODO: temporary hack to allow using data context without service
//	fetchData: function(operation, parameters, mergeOption, httpVerb, succeededCallback, failedCallback, timeout, userContext) {
//		succeededCallback(this.get_graph());
//	},
//	get_root: function() {
//		return this._root;
//	},
//	set_root: function(value) {
//		this._root = value;
//	},
//	initialize: function() {
//		$load(this._rawData.__metadata, this._rawData.__data);
//	}
//}

//ExoWeb.Data.DataContext.registerClass("ExoWeb.Data.DataContext", Sys.Data.DataContext);

// Since this script is not loaded by System.Web.Handlers.ScriptResourceHandler
// invoke Sys.Application.notifyScriptLoaded to notify ScriptManager
// that this is the end of the script.
if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
<commit_msg>formatting<commit_after>Type.registerNamespace("ExoWeb.UI");

///////////////////////////////////////////////////////////////////////////////
///
/// In addition to defining template markup, also defines rules that are used
/// to determine if it should be chosen as the template for a given element
/// based on a CSS selector as well as a javascript filter that is evaluated
/// against the element in question.
///
///
/// <example>
///		<div sys:attach="template" template:for="table.inputform tr" template:if="<some condition>">

/// </example>
ExoWeb.UI.Template = function(element) {
	ExoWeb.UI.Template.initializeBase(this, [element]);
}

ExoWeb.UI.Template.prototype = {
	// CSS Selectors
	///////////////////////////////////////////////////////////////////////////
	get_for: function() {
		return this._for;
	},
	set_for: function(value) {
		this._for = value;
	},
	matches: function(e) {
		return $(e).is(this._for);
	},

	// Arbitrary JavaScript
	///////////////////////////////////////////////////////////////////////////
	get_if: function() {
		return this._if;
	},
	set_if: function(value) {
		this._if = value;
	},
	satisfies: function(e) {
		// return true by default if no filter
		var result = true;

		if (this._if) {
			var func = null;

			try {
				// turn arbitrary javascript code into function
				func = new Function("return " + this._if + ";");
			}
			catch (e) {
				throw ("Statement \"" + this._if + "\" causes the following error: " + e);
			}

			if (func) {
				try {
					result = func.call(e);
				}
				catch (e) {
					throw ("Calling \"" + this._if + "\" causes the following error: " + e);
				}
			}
		}

		return result;
	},

	test: function(e) {
		// determines if the given element matches this template
		return this.matches(e) && this.satisfies(e);
	},

	initialize: function() {
		ExoWeb.UI.Template.callBaseMethod(this, "initialize");

		// add a class that can be used to search for templates
		// and make sure that the template element is hidden
		$(this.get_element()).addClass("vc3-template").hide();
	}
}

///
/// Finds the first field template with a selector and filter that
/// match the given element and returns the template.
///
ExoWeb.UI.Template.find = function(element) {
	var templates = $(".vc3-template");
	for (var t = 0; t < templates.length; t++) {
		var tmpl = templates[t];
		if (ExoWeb.UI.Template.isInstanceOfType(tmpl.control) && tmpl.control.test(element))
			return tmpl;
	}

	return null;
}

ExoWeb.UI.Template.registerClass("ExoWeb.UI.Template", Sys.UI.Control);

///////////////////////////////////////////////////////////////////////////////
///
/// Finds its matching template and renders using the provided data as the
/// binding context.  It can be used as a "field control", using part of the
/// context data to select the appropriate control template.  Another common
/// usage would be to select the appropriate template for a portion of the UI,
/// as in the example where an objects meta type determines how it is
/// displayed in the UI.
///
///
/// <example>
///

/// </example>
ExoWeb.UI.Content = function(element) {
	ExoWeb.UI.Content.initializeBase(this, [element]);
}

ExoWeb.UI.Content.prototype = {
	get_template: function() {
		if (!this._template) {
			var element = this.get_element();
			this._template = ExoWeb.UI.Template.find(element);

			if (!this._template) {
				throw ("This content region does not match any available templates.");
			}
		}

		if (!Sys.UI.Template.isInstanceOfType(this._template))
			this._template = new Sys.UI.Template(this._template);

		return this._template;
	},
	get_data: function() {
		return this._data;
	},
	set_data: function(value) {
		this._data = value;
	},
	render: function() {
		try {
			var tmpl = this.get_template();

			// get custom classes from template
			var classes = $(tmpl.get_element()).attr("class").replace("vc3-template", "").replace("sys-template", "").trim();

			var ctx = tmpl.instantiateIn(this.get_element(), null, this.get_data());

			//ctx.dataItem = this.get_data();

			// copy custom classes from template to content control
			$(this.get_element()).addClass(classes);

			// necessary in order to render components found within the template (like a nested dataview)
			ctx.initializeComponents();
		}
		catch (e) {
			(console && console.log ? console.log : alert)(e);
		}
	},
	initialize: function() {
		ExoWeb.UI.Content.callBaseMethod(this, "initialize");

		// TODO: include meta info about field?

		this.render();
	}
}

ExoWeb.UI.Content.registerClass("ExoWeb.UI.Content", Sys.UI.Control);

///////////////////////////////////////////////////////////////////////////////
///
///
///
ExoWeb.UI.Field = function(element) {
	ExoWeb.UI.Field.initializeBase(this, [element]);
}

ExoWeb.UI.Field.prototype = {
	get_source: function() {
		return this._source;
	},
	set_source: function(value) {
		if (this._source !== value) {
			this._data = null;
			// TODO: can't tell whether label was inferred
			this._source = value;
		}
	},
	get_label: function() {
		if (!this._label) {
			this._label = this.get_source();

			// TODO: more robust solution to human-friendly format
			this._label = this._label.replace(/([^^])([A-Z])/g, "$1 $2");
		}

		return this._label;
	},
	set_label: function(value) {
		this._label = value;
	},
	get_isReadOnly: function() {
		return this._isReadOnly || false;
	},
	set_isReadOnly: function(value) {
		if (!value) throw ("Value is not defined.");

		if (this._isReadOnly != value) {
			// TODO: better bool conversion
			if (typeof (value) == "boolean")
				this._isReadOnly = value;
			else if (typeof (value) == "string")
				this._isReadOnly = (value.toLowerCase() == "true");
			else
				throw ($format("The value \"{val}\" could not be converted to a boolean.", { val: value }));
		}
	},
	get_data: function() {
		if (!this._data) {
			var ctx = this.findContext();
			var target = ctx.dataItem;
			var props = target.meta.property(this.get_source());

			if (!props)
				throw ($format("Property \"{p}\" could not be found.", { p: this.get_source() }));

			var dt = props.lastProperty().get_dataType();

			var format;
			if (!(format = props.lastProperty().get_format()) && dt.formats)
				format = dt.formats.$default;

			this._data = new ExoWeb.Model.Adapter(target, props, format, { label: this.get_label(), readonly: this.get_isReadOnly() });
		}
		return this._data;
	},
	findContext: function(element) {
		/// Finds the containing template control for the given element and
		/// then finds the element's corresponding context (for repeated content).

		var element = this.get_element();
		var container = null;
		var subcontainer = null;

		// find the first parent that is an ASP.NET Ajax template
		while (element.parentNode && !element.parentNode._msajaxtemplate)
			element = element.parentNode;

		// containing template was not found
		if (!element.parentNode || !element.parentNode._msajaxtemplate)
			throw Error.invalidOperation("The field's parent template could not be found.");

		container = element.parentNode;
		subcontainer = element;

		// find the correct context (in the case of repeated content)
		var contexts = container.control.get_contexts();
		if (contexts) {
			for (var i = 0, l = contexts.length; i < l; i++) {
				var ctx = contexts[i];
				if ((ctx.containerElement === container) && (Sys._indexOf(ctx.nodes, subcontainer) > -1)) {
					return ctx;
				}
			}
		}

		return null;
	}
}

ExoWeb.UI.Field.registerClass("ExoWeb.UI.Field", ExoWeb.UI.Content);

///////////////////////////////////////////////////////////////////////////////
//Type.registerNamespace("ExoWeb.Data");

//ExoWeb.Data.DataContext = function ExoWeb$Data$DataContext(rawData) {
//	ExoWeb.Data.DataContext.initializeBase(this);
//	this._rawData = rawData;
//	this.initialize();
//}

//ExoWeb.Data.DataContext.prototype = {
//	// TODO: temporary hack to allow using data context without service
//	fetchData: function(operation, parameters, mergeOption, httpVerb, succeededCallback, failedCallback, timeout, userContext) {
//		succeededCallback(this.get_graph());
//	},
//	get_root: function() {
//		return this._root;
//	},
//	set_root: function(value) {
//		this._root = value;
//	},
//	initialize: function() {
//		$load(this._rawData.__metadata, this._rawData.__data);
//	}
//}

//ExoWeb.Data.DataContext.registerClass("ExoWeb.Data.DataContext", Sys.Data.DataContext);

// Since this script is not loaded by System.Web.Handlers.ScriptResourceHandler
// invoke Sys.Application.notifyScriptLoaded to notify ScriptManager
// that this is the end of the script.
if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
<|endoftext|>


<commit_before>'use babel'

import _ from 'lodash'
import fs from 'fs-plus'
import path from 'path'

const outputPattern = new RegExp('' +
  '^Output\\swritten\\son\\s' + // Leading text.
  '(.*)' +                      // Output path.
  '\\s\\(.*\\)\\.$'             // Trailing text.
)

const errorPattern = /^(?:(?:\.\/)?(.*):(\d+):|!)(?: (.+) Error:)? (.*)\.$/
const boxPattern = /^((?:Over|Under)full \\[vh]box \([^)]*\)) in paragraph at lines (\d+)--(\d+)$/
const warningInfoPattern = /^((?:(?:Class|Package) \S+)|LaTeX|LaTeX Font) (Warning|Info):\s+(.*?)(?: on input line (\d+))?\.$/
const incompleteFontPattern = /^LaTeX Font .*[^.]$/

export default class LogParser {
  constructor (filePath, texFilePath) {
    this.filePath = filePath
    this.texFilePath = texFilePath
    this.projectPath = path.dirname(filePath)
  }

  parse () {
    const result = {
      logFilePath: this.filePath,
      outputFilePath: null,
      messages: []
    }

    const lines = this.getLines()
    _.forEach(lines, (line, index) => {
      // Simplest Thing That Works™ and KISS®
      const logRange = [[index, 0], [index, line.length]]
      let match = line.match(outputPattern)
      if (match) {
        const filePath = match[1].replace(/"/g, '') // TODO: Fix with improved regex.
        result.outputFilePath = path.resolve(this.projectPath, filePath)
        return
      }

      match = line.match(errorPattern)
      if (match) {
        const lineNumber = match[2] ? parseInt(match[2], 10) : undefined
        result.messages.push({
          type: 'Error',
          text: (match[3] && match[3] !== 'LaTeX') ? match[3] + ': ' + match[4] : match[4],
          filePath: match[1] ? this.alterParentPath(this.texFilePath, match[1]) : this.texFilePath,
          range: lineNumber ? [[lineNumber - 1, 0], [lineNumber - 1, 65536]] : undefined,
          logPath: this.filePath,
          logRange: logRange
        })
        return
      }

      match = line.match(boxPattern)
      if (match) {
        result.messages.push({
          type: 'Warning',
          text: match[1],
          filePath: this.texFilePath,
          range: [[parseInt(match[2], 10) - 1, 0], [parseInt(match[3], 10) - 1, 65536]],
          logPath: this.filePath,
          logRange: logRange
        })
        return
      }

      match = (incompleteFontPattern.test(line) ? line + lines[index + 1].substring(15) : line).match(warningInfoPattern)
      if (match) {
        const lineNumber = match[4] ? parseInt(match[4], 10) : undefined
        result.messages.push({
          type: match[2],
          text: ((match[1] !== 'LaTeX') ? match[1] + ': ' + match[3] : match[3]).replace(/\s+/g, ' '),
          filePath: this.texFilePath,
          range: lineNumber ? [[lineNumber - 1, 0], [lineNumber - 1, 65536]] : undefined,
          logPath: this.filePath,
          logRange: logRange
        })
        return
      } })

    return result
  }

  getLines () {
    if (!fs.existsSync(this.filePath)) {
      throw new Error(`No such file: ${this.filePath}`)
    }

    const rawFile = fs.readFileSync(this.filePath, {encoding: 'utf-8'})
    const lines = rawFile.replace(/(\r\n)|\r/g, '\n').split('\n')
    return lines
  }

  alterParentPath (targetPath, originalPath) {
    const targetDir = path.dirname(targetPath)
    return path.join(targetDir, path.basename(originalPath))
  }

}
<commit_msg>Document RegExp patterns for log parsing<commit_after>'use babel'

import _ from 'lodash'
import fs from 'fs-plus'
import path from 'path'

const outputPattern = new RegExp('' +
  '^Output\\swritten\\son\\s' + // Leading text.
  '(.*)' +                      // Output path.
  '\\s\\(.*\\)\\.$'             // Trailing text.
)

// Error pattern
const errorPattern = new RegExp('' +
  '^(?:(?:\\.\\/)?(.*):(\\d+):|!)' + // File path and line number ignoring leading './'
  '(?: (.+) Error:)? ' +             // Error type
  '(.*)\\.$'                         // Message text
)

// Pattern for overfull/underfull boxes
const boxPattern = new RegExp('' +
  '^((?:Over|Under)full \\\\[vh]box \\([^)]*\\))' + // Message text
  ' in paragraph at lines (\\d+)--(\\d+)$'          // Line range
)

// Warning and Info pattern
const warningInfoPattern = new RegExp('' +
  '^((?:(?:Class|Package) \\S+)|LaTeX|LaTeX Font) ' + // Message origin
  '(Warning|Info):\\s+' +                             // Message type
  '(.*?)' +                                           // Message text
  '(?: on input line (\\d+))?\\.$'                    // Line number
)

// Pattern for font messages that overflow onto the next line. We do not capture
// anything from the match, but we need to know where the error message is
// located in the log file.
const incompleteFontPattern = /^LaTeX Font .*[^.]$/

export default class LogParser {
  constructor (filePath, texFilePath) {
    this.filePath = filePath
    this.texFilePath = texFilePath
    this.projectPath = path.dirname(filePath)
  }

  parse () {
    const result = {
      logFilePath: this.filePath,
      outputFilePath: null,
      messages: []
    }

    const lines = this.getLines()
    _.forEach(lines, (line, index) => {
      // Simplest Thing That Works™ and KISS®
      const logRange = [[index, 0], [index, line.length]]
      let match = line.match(outputPattern)
      if (match) {
        const filePath = match[1].replace(/"/g, '') // TODO: Fix with improved regex.
        result.outputFilePath = path.resolve(this.projectPath, filePath)
        return
      }

      match = line.match(errorPattern)
      if (match) {
        const lineNumber = match[2] ? parseInt(match[2], 10) : undefined
        result.messages.push({
          type: 'Error',
          text: (match[3] && match[3] !== 'LaTeX') ? match[3] + ': ' + match[4] : match[4],
          filePath: match[1] ? this.alterParentPath(this.texFilePath, match[1]) : this.texFilePath,
          range: lineNumber ? [[lineNumber - 1, 0], [lineNumber - 1, 65536]] : undefined,
          logPath: this.filePath,
          logRange: logRange
        })
        return
      }

      match = line.match(boxPattern)
      if (match) {
        result.messages.push({
          type: 'Warning',
          text: match[1],
          filePath: this.texFilePath,
          range: [[parseInt(match[2], 10) - 1, 0], [parseInt(match[3], 10) - 1, 65536]],
          logPath: this.filePath,
          logRange: logRange
        })
        return
      }

      match = (incompleteFontPattern.test(line) ? line + lines[index + 1].substring(15) : line).match(warningInfoPattern)
      if (match) {
        const lineNumber = match[4] ? parseInt(match[4], 10) : undefined
        result.messages.push({
          type: match[2],
          text: ((match[1] !== 'LaTeX') ? match[1] + ': ' + match[3] : match[3]).replace(/\s+/g, ' '),
          filePath: this.texFilePath,
          range: lineNumber ? [[lineNumber - 1, 0], [lineNumber - 1, 65536]] : undefined,
          logPath: this.filePath,
          logRange: logRange
        })
        return
      } })

    return result
  }

  getLines () {
    if (!fs.existsSync(this.filePath)) {
      throw new Error(`No such file: ${this.filePath}`)
    }

    const rawFile = fs.readFileSync(this.filePath, {encoding: 'utf-8'})
    const lines = rawFile.replace(/(\r\n)|\r/g, '\n').split('\n')
    return lines
  }

  alterParentPath (targetPath, originalPath) {
    const targetDir = path.dirname(targetPath)
    return path.join(targetDir, path.basename(originalPath))
  }

}
<|endoftext|>


<commit_before>const DrawCard = require('../../../drawcard.js');

class MaesterAemon extends DrawCard {
    setupCardAbilities() {
        this.interrupt({
            when: {
                onKillingCharacter: (event, player, card, allowSaves) => {
                    if(!allowSaves || card.getFaction() !== 'thenightswatch' || player !== card.controller || this.kneeled) {
                        return false;
                    }

                    this.toKill = card;

                    event.cancel = true;

                    return true;
                }
            },
            handler: () => {
                this.game.addMessage('{0} kneels {1} to save {2}', this.controller, this, this.toKill);

                this.controller.kneelCard(this);
            },
            onCancel: () => {
                this.controller.killCharacter(this.toKill, false);

                return true;
            }
        });
    }
}

MaesterAemon.code = '01125';

module.exports = MaesterAemon;
<commit_msg>until we implenent cancellable callbacks, do not let maester aemon trigger twice when multiple characters are killed<commit_after>const DrawCard = require('../../../drawcard.js');

class MaesterAemon extends DrawCard {
    setupCardAbilities() {
        this.interrupt({
            when: {
                onKillingCharacter: (event, player, card, allowSaves) => {
                    if(!allowSaves || card.getFaction() !== 'thenightswatch' || player !== card.controller || this.kneeled || this.triggered) {
                        return false;
                    }

                    this.toKill = card;
                    this.triggered = true;

                    event.cancel = true;

                    return true;
                }
            },
            handler: () => {
                this.game.addMessage('{0} kneels {1} to save {2}', this.controller, this, this.toKill);

                this.controller.kneelCard(this);

                this.triggered = false;
            },
            onCancel: () => {
                this.controller.killCharacter(this.toKill, false);

                this.triggered = false;

                return true;
            }
        });
    }
}

MaesterAemon.code = '01125';

module.exports = MaesterAemon;
<|endoftext|>


<commit_before>// use higher values to slow down tests for debugging
var promisesDelay;

const syncingTestsActive = (process.argv.length > 5 && process.argv[5] == '--suite=syncing');
if (syncingTestsActive) {
    promisesDelay = 150;
} else {
    promisesDelay = 0;
}

function delayPromises(milliseconds) {
    var executeFunction = browser.driver.controlFlow().execute;

    browser.driver.controlFlow().execute = function() {
        var args = arguments;

        executeFunction.call(browser.driver.controlFlow(), function() {
            return protractor.promise.delayed(milliseconds);
        });

        return executeFunction.apply(browser.driver.controlFlow(), args);
    };
}

console.log("Set promises delay to " + promisesDelay + " ms.");
delayPromises(promisesDelay);

var ECWaitTime = 20000;
var shortRest = 200;

module.exports = {
    ECWaitTime: ECWaitTime,
    shortRest: shortRest
};
<commit_msg>set promises delay to 0ms for syncing tests<commit_after>// use higher values to slow down tests for debugging
var promisesDelay;

// const syncingTestsActive = (process.argv.length > 5 && process.argv[5] == '--suite=syncing');
promisesDelay = 0;

function delayPromises(milliseconds) {
    var executeFunction = browser.driver.controlFlow().execute;

    browser.driver.controlFlow().execute = function() {
        var args = arguments;

        executeFunction.call(browser.driver.controlFlow(), function() {
            return protractor.promise.delayed(milliseconds);
        });

        return executeFunction.apply(browser.driver.controlFlow(), args);
    };
}

console.log("Set promises delay to " + promisesDelay + " ms.");
delayPromises(promisesDelay);

var ECWaitTime = 20000;
var shortRest = 200;

module.exports = {
    ECWaitTime: ECWaitTime,
    shortRest: shortRest
};
<|endoftext|>