text:
import {
	copyPropsTo,
	isArray,
	isAttrAnEvent,
	isFunction,
	isInvalid,
	isNull,
	isNullOrUndef,
	isNumber,
	isObject,
	isString,
	isStringOrNumber,
	isUndefined,
	NO_OP,
	LifecycleClass,
	throwError
} from 'inferno-shared';
import VNodeFlags from 'inferno-vnode-flags';
import options from '../core/options';
import {
	cloneVNode,
	createTextVNode,
	createVoidVNode,
	isVNode,
	VNode
} from '../core/VNodes';
import {
	booleanProps,
	delegatedProps,
	isUnitlessNumber,
	namespaces,
	skipProps,
	strictProps
} from './constants';
import {
	handleEvent
} from './events/delegation';
import {
	mount,
	mountArrayChildren,
	mountComponent,
	mountElement,
	mountFunctionalComponentCallbacks,
	mountRef,
	mountText,
	mountVoid
} from './mounting';
import {
	appendChild,
	createFunctionalComponentInput,
	insertOrAppend,
	isKeyed,
	removeAllChildren,
	replaceChild,
	replaceLastChildAndUnmount,
	replaceVNode,
	replaceWithNewNode,
	setTextContent,
	updateTextContent,
	EMPTY_OBJ
} from './utils';

import {Styles} from '../core/structures';
import { componentToDOMNodeMap } from './rendering';
import { unmount } from './unmounting';
import processElement from './wrappers/processElement';

export function patch(lastVNode: VNode, nextVNode: VNode, parentDom: Element, lifecycle: LifecycleClass, context: Object, isSVG: boolean, isRecycling: boolean) {
	if (lastVNode !== nextVNode) {
		const lastFlags = lastVNode.flags;
		const nextFlags = nextVNode.flags;

		if (nextFlags & VNodeFlags.Component) {
			if (lastFlags & VNodeFlags.Component) {
				patchComponent(
					lastVNode,
					nextVNode,
					parentDom,
					lifecycle,
					context,
					isSVG,
					nextFlags & VNodeFlags.ComponentClass,
					isRecycling
				);
			} else {
				replaceVNode(
					parentDom,
					mountComponent(
						nextVNode,
						null,
						lifecycle,
						context,
						isSVG,
						nextFlags & VNodeFlags.ComponentClass
					),
					lastVNode,
					lifecycle,
					isRecycling
				);
			}
		} else if (nextFlags & VNodeFlags.Element) {
			if (lastFlags & VNodeFlags.Element) {
				patchElement(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG, isRecycling);
			} else {
				replaceVNode(
					parentDom,
					mountElement(
						nextVNode,
						null,
						lifecycle,
						context,
						isSVG
					),
					lastVNode,
					lifecycle,
					isRecycling
				);
			}
		} else if (nextFlags & VNodeFlags.Text) {
			if (lastFlags & VNodeFlags.Text) {
				patchText(lastVNode, nextVNode);
			} else {
				replaceVNode(parentDom, mountText(nextVNode, null), lastVNode, lifecycle, isRecycling);
			}
		} else if (nextFlags & VNodeFlags.Void) {
			if (lastFlags & VNodeFlags.Void) {
				patchVoid(lastVNode, nextVNode);
			} else {
				replaceVNode(parentDom, mountVoid(nextVNode, null), lastVNode, lifecycle, isRecycling);
			}
		} else {
			// Error case: mount new one replacing old one
			replaceLastChildAndUnmount(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG, isRecycling);
		}
	}
}

function unmountChildren(children, dom: Element, lifecycle: LifecycleClass, isRecycling: boolean) {
	if (isVNode(children)) {
		unmount(children, dom, lifecycle, true, isRecycling);
	} else if (isArray(children)) {
		removeAllChildren(dom, children, lifecycle, isRecycling);
	} else {
		dom.textContent = '';
	}
}

export function patchElement(lastVNode: VNode, nextVNode: VNode, parentDom: Node, lifecycle: LifecycleClass, context: Object, isSVG: boolean, isRecycling: boolean) {
	const nextTag = nextVNode.type;
	const lastTag = lastVNode.type;

	if (lastTag !== nextTag) {
		replaceWithNewNode(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG, isRecycling);
	} else {
		const dom = lastVNode.dom;
		const lastProps = lastVNode.props;
		const nextProps = nextVNode.props;
		const lastChildren = lastVNode.children;
		const nextChildren = nextVNode.children;
		const lastFlags = lastVNode.flags;
		const nextFlags = nextVNode.flags;
		const lastRef = lastVNode.ref;
		const nextRef = nextVNode.ref;
		const lastEvents = lastVNode.events;
		const nextEvents = nextVNode.events;

		nextVNode.dom = dom;
		if (isSVG || (nextFlags & VNodeFlags.SvgElement)) {
			isSVG = true;
		}
		if (lastChildren !== nextChildren) {
			patchChildren(lastFlags, nextFlags, lastChildren, nextChildren, dom as Element, lifecycle, context, isSVG, isRecycling);
		}

		let hasControlledValue = false;
		if (!(nextFlags & VNodeFlags.HtmlElement)) {
			hasControlledValue = processElement(nextFlags, nextVNode, dom, false);
		}

		// inlined patchProps  -- starts --
		if (lastProps !== nextProps) {
			const lastPropsOrEmpty = lastProps || EMPTY_OBJ;
			const nextPropsOrEmpty = nextProps || EMPTY_OBJ;

			if (nextPropsOrEmpty !== EMPTY_OBJ) {
				for (let prop in nextPropsOrEmpty) {
					// do not add a hasOwnProperty check here, it affects performance
					const nextValue = nextPropsOrEmpty[prop];
					const lastValue = lastPropsOrEmpty[prop];

					if (isNullOrUndef(nextValue)) {
						removeProp(prop, nextValue, dom);
					} else {
						patchProp(prop, lastValue, nextValue, dom, isSVG, hasControlledValue);
					}
				}
			}
			if (lastPropsOrEmpty !== EMPTY_OBJ) {
				for (let prop in lastPropsOrEmpty) {
					// do not add a hasOwnProperty check here, it affects performance
					if (isNullOrUndef(nextPropsOrEmpty[prop])) {
						removeProp(prop, lastPropsOrEmpty[prop], dom);
					}
				}
			}
		}
		// inlined patchProps  -- ends --

		if (lastEvents !== nextEvents) {
			patchEvents(lastEvents, nextEvents, dom as Element);
		}
		if (nextRef) {
			if (lastRef !== nextRef || isRecycling) {
				mountRef(dom as Element, nextRef, lifecycle);
			}
		}
	}
}

function patchChildren(lastFlags: VNodeFlags, nextFlags: VNodeFlags, lastChildren, nextChildren, dom: Element, lifecycle: LifecycleClass, context: Object, isSVG: boolean, isRecycling: boolean) {
	let patchArray = false;
	let patchKeyed = false;

	if (nextFlags & VNodeFlags.HasNonKeyedChildren) {
		patchArray = true;
	} else if ((lastFlags & VNodeFlags.HasKeyedChildren)  && (nextFlags & VNodeFlags.HasKeyedChildren)) {
		patchKeyed = true;
		patchArray = true;
	} else if (isInvalid(nextChildren)) {
		unmountChildren(lastChildren, dom, lifecycle, isRecycling);
	} else if (isInvalid(lastChildren)) {
		if (isStringOrNumber(nextChildren)) {
			setTextContent(dom, nextChildren);
		} else {
			if (isArray(nextChildren)) {
				mountArrayChildren(nextChildren, dom, lifecycle, context, isSVG);
			} else {
				mount(nextChildren, dom, lifecycle, context, isSVG);
			}
		}
	} else if (isStringOrNumber(nextChildren)) {
		if (isStringOrNumber(lastChildren)) {
			updateTextContent(dom, nextChildren);
		} else {
			unmountChildren(lastChildren, dom, lifecycle, isRecycling);
			setTextContent(dom, nextChildren);
		}
	} else if (isArray(nextChildren)) {
		if (isArray(lastChildren)) {
			patchArray = true;
			if (isKeyed(lastChildren, nextChildren)) {
				patchKeyed = true;
			}
		} else {
			unmountChildren(lastChildren, dom, lifecycle, isRecycling);
			mountArrayChildren(nextChildren, dom, lifecycle, context, isSVG);
		}
	} else if (isArray(lastChildren)) {
		removeAllChildren(dom, lastChildren, lifecycle, isRecycling);
		mount(nextChildren, dom, lifecycle, context, isSVG);
	} else if (isVNode(nextChildren)) {
		if (isVNode(lastChildren)) {
			patch(lastChildren, nextChildren, dom, lifecycle, context, isSVG, isRecycling);
		} else {
			unmountChildren(lastChildren, dom, lifecycle, isRecycling);
			mount(nextChildren, dom, lifecycle, context, isSVG);
		}
	}
	if (patchArray) {
		if (patchKeyed) {
			patchKeyedChildren(lastChildren, nextChildren, dom, lifecycle, context, isSVG, isRecycling);
		} else {
			patchNonKeyedChildren(lastChildren, nextChildren, dom, lifecycle, context, isSVG, isRecycling);
		}
	}
}

export function patchComponent(lastVNode, nextVNode, parentDom, lifecycle: LifecycleClass, context, isSVG: boolean, isClass: number, isRecycling: boolean) {
	const lastType = lastVNode.type;
	const nextType = nextVNode.type;
	const nextProps = nextVNode.props || EMPTY_OBJ;
	const lastKey = lastVNode.key;
	const nextKey = nextVNode.key;
	const defaultProps = nextType.defaultProps;

	if (!isUndefined(defaultProps)) {
		// When defaultProps are used we need to create new Object
		const props = nextVNode.props || {};
		copyPropsTo(defaultProps, props);
		nextVNode.props = props;
	}

	if (lastType !== nextType) {
		if (isClass) {
			replaceWithNewNode(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG, isRecycling);
		} else {
			const lastInput = lastVNode.children._lastInput || lastVNode.children;
			const nextInput = createFunctionalComponentInput(nextVNode, nextType, nextProps, context);

			unmount(lastVNode, null, lifecycle, false, isRecycling);
			patch(lastInput, nextInput, parentDom, lifecycle, context, isSVG, isRecycling);
			const dom = nextVNode.dom = nextInput.dom;

			nextVNode.children = nextInput;
			mountFunctionalComponentCallbacks(nextVNode.ref, dom, lifecycle);
		}
	} else {
		if (isClass) {
			if (lastKey !== nextKey) {
				replaceWithNewNode(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG, isRecycling);
				return false;
			}
			const instance = lastVNode.children;

			if (instance._unmounted) {
				if (isNull(parentDom)) {
					return true;
				}
				replaceChild(
					parentDom,
					mountComponent(
						nextVNode,
						null,
						lifecycle,
						context,
						isSVG,
						nextVNode.flags & VNodeFlags.ComponentClass
					),
					lastVNode.dom
				);
			} else {
				const lastState = instance.state;
				const nextState = instance.state;
				const lastProps = instance.props;
				let childContext = instance.getChildContext();

				nextVNode.children = instance;
				instance._isSVG = isSVG;
				instance._syncSetState = false;
				if (isNullOrUndef(childContext)) {
					childContext = context;
				} else {
					childContext = Object.assign({}, context, childContext);
				}
				const lastInput = instance._lastInput;
				let nextInput = instance._updateComponent(lastState, nextState, lastProps, nextProps, context, false, false);
				let didUpdate = true;

				instance._childContext = childContext;
				if (isInvalid(nextInput)) {
					nextInput = createVoidVNode();
				} else if (nextInput === NO_OP) {
					nextInput = lastInput;
					didUpdate = false;
				} else if (isStringOrNumber(nextInput)) {
					nextInput = createTextVNode(nextInput);
				} else if (isArray(nextInput)) {
					if (process.env.NODE_ENV !== 'production') {
						throwError('a valid Inferno VNode (or null) must be returned from a component render. You may have returned an array or an invalid object.');
					}
					throwError();
				} else if (isObject(nextInput) && nextInput.dom) {
					nextInput = cloneVNode(nextInput);
				}
				if (nextInput.flags & VNodeFlags.Component) {
					nextInput.parentVNode = nextVNode;
				} else if (lastInput.flags & VNodeFlags.Component) {
					lastInput.parentVNode = nextVNode;
				}
				instance._lastInput = nextInput;
				instance._vNode = nextVNode;
				if (didUpdate) {
					patch(lastInput, nextInput, parentDom, lifecycle, childContext, isSVG, isRecycling);
					instance.componentDidUpdate(lastProps, lastState);
					options.afterUpdate && options.afterUpdate(nextVNode);
					options.findDOMNodeEnabled && componentToDOMNodeMap.set(instance, nextInput.dom);
				}
				instance._syncSetState = true;
				nextVNode.dom = nextInput.dom;
			}
		} else {
			let shouldUpdate = true;
			const lastProps = lastVNode.props;
			const nextHooks = nextVNode.ref;
			const nextHooksDefined = !isNullOrUndef(nextHooks);
			const lastInput = lastVNode.children;
			let nextInput = lastInput;

			nextVNode.dom = lastVNode.dom;
			nextVNode.children = lastInput;
			if (lastKey !== nextKey) {
				shouldUpdate = true;
			} else {
				if (nextHooksDefined && !isNullOrUndef(nextHooks.onComponentShouldUpdate)) {
					shouldUpdate = nextHooks.onComponentShouldUpdate(lastProps, nextProps);
				}
			}
			if (shouldUpdate !== false) {
				if (nextHooksDefined && !isNullOrUndef(nextHooks.onComponentWillUpdate)) {
					nextHooks.onComponentWillUpdate(lastProps, nextProps);
				}
				nextInput = nextType(nextProps, context);

				if (isInvalid(nextInput)) {
					nextInput = createVoidVNode();
				} else if (isStringOrNumber(nextInput) && nextInput !== NO_OP) {
					nextInput = createTextVNode(nextInput);
				} else if (isArray(nextInput)) {
					if (process.env.NODE_ENV !== 'production') {
						throwError('a valid Inferno VNode (or null) must be returned from a component render. You may have returned an array or an invalid object.');
					}
					throwError();
				} else if (isObject(nextInput) && nextInput.dom) {
					nextInput = cloneVNode(nextInput);
				}
				if (nextInput !== NO_OP) {
					patch(lastInput, nextInput, parentDom, lifecycle, context, isSVG, isRecycling);
					nextVNode.children = nextInput;
					if (nextHooksDefined && !isNullOrUndef(nextHooks.onComponentDidUpdate)) {
						nextHooks.onComponentDidUpdate(lastProps, nextProps);
					}
					nextVNode.dom = nextInput.dom;
				}
			}
			if (nextInput.flags & VNodeFlags.Component) {
				nextInput.parentVNode = nextVNode;
			} else if (lastInput.flags & VNodeFlags.Component) {
				lastInput.parentVNode = nextVNode;
			}
		}
	}
	return false;
}

export function patchText(lastVNode: VNode, nextVNode: VNode) {
	const nextText = nextVNode.children as string;
	const dom = lastVNode.dom;

	nextVNode.dom = dom;

	if (lastVNode.children !== nextText) {
		dom.nodeValue = nextText;
	}
}

export function patchVoid(lastVNode: VNode, nextVNode: VNode) {
	nextVNode.dom = lastVNode.dom;
}

export function patchNonKeyedChildren(lastChildren, nextChildren, dom, lifecycle: LifecycleClass, context: Object, isSVG: boolean, isRecycling: boolean) {
	const lastChildrenLength = lastChildren.length;
	const nextChildrenLength = nextChildren.length;
	const commonLength = lastChildrenLength > nextChildrenLength ? nextChildrenLength : lastChildrenLength;
	let i = 0;

	for (; i < commonLength; i++) {
		let nextChild = nextChildren[i];

		if (nextChild.dom) {
			nextChild = nextChildren[i] = cloneVNode(nextChild);
		}
		patch(lastChildren[i], nextChild, dom, lifecycle, context, isSVG, isRecycling);
	}
	if (lastChildrenLength < nextChildrenLength) {
		for (i = commonLength; i < nextChildrenLength; i++) {
			let nextChild = nextChildren[i];

			if (nextChild.dom) {
				nextChild = nextChildren[i] = cloneVNode(nextChild);
			}
			appendChild(dom, mount(nextChild, null, lifecycle, context, isSVG));
		}
	} else if (nextChildrenLength === 0) {
		removeAllChildren(dom, lastChildren, lifecycle, isRecycling);
	} else if (lastChildrenLength > nextChildrenLength) {
		for (i = commonLength; i < lastChildrenLength; i++) {
			unmount(lastChildren[i], dom, lifecycle, false, isRecycling);
		}
	}
}

export function patchKeyedChildren(
	a: VNode[],
	b: VNode[],
	dom,
	lifecycle: LifecycleClass,
	context,
	isSVG: boolean,
	isRecycling: boolean
) {
	let aLength = a.length;
	let bLength = b.length;
	let aEnd = aLength - 1;
	let bEnd = bLength - 1;
	let aStart = 0;
	let bStart = 0;
	let i;
	let j;
	let aNode;
	let bNode;
	let nextNode;
	let nextPos;
	let node;

	if (aLength === 0) {
		if (bLength !== 0) {
			mountArrayChildren(b, dom, lifecycle, context, isSVG);
		}
		return;
	} else if (bLength === 0) {
		removeAllChildren(dom, a, lifecycle, isRecycling);
		return;
	}
	let aStartNode = a[aStart];
	let bStartNode = b[bStart];
	let aEndNode = a[aEnd];
	let bEndNode = b[bEnd];

	if (bStartNode.dom) {
		b[bStart] = bStartNode = cloneVNode(bStartNode);
	}
	if (bEndNode.dom) {
		b[bEnd] = bEndNode = cloneVNode(bEndNode);
	}
	// Step 1
	/* eslint no-constant-condition: 0 */
	outer: while (true) {
		// Sync nodes with the same key at the beginning.
		while (aStartNode.key === bStartNode.key) {
			patch(aStartNode, bStartNode, dom, lifecycle, context, isSVG, isRecycling);
			aStart++;
			bStart++;
			if (aStart > aEnd || bStart > bEnd) {
				break outer;
			}
			aStartNode = a[aStart];
			bStartNode = b[bStart];
			if (bStartNode.dom) {
				b[bStart] = bStartNode = cloneVNode(bStartNode);
			}
		}

		// Sync nodes with the same key at the end.
		while (aEndNode.key === bEndNode.key) {
			patch(aEndNode, bEndNode, dom, lifecycle, context, isSVG, isRecycling);
			aEnd--;
			bEnd--;
			if (aStart > aEnd || bStart > bEnd) {
				break outer;
			}
			aEndNode = a[aEnd];
			bEndNode = b[bEnd];
			if (bEndNode.dom) {
				b[bEnd] = bEndNode = cloneVNode(bEndNode);
			}
		}

		// Move and sync nodes from right to left.
		if (aEndNode.key === bStartNode.key) {
			patch(aEndNode, bStartNode, dom, lifecycle, context, isSVG, isRecycling);
			insertOrAppend(dom, bStartNode.dom, aStartNode.dom);
			aEnd--;
			bStart++;
			aEndNode = a[aEnd];
			bStartNode = b[bStart];
			if (bStartNode.dom) {
				b[bStart] = bStartNode = cloneVNode(bStartNode);
			}
			continue;
		}

		// Move and sync nodes from left to right.
		if (aStartNode.key === bEndNode.key) {
			patch(aStartNode, bEndNode, dom, lifecycle, context, isSVG, isRecycling);
			nextPos = bEnd + 1;
			nextNode = nextPos < b.length ? b[nextPos].dom : null;
			insertOrAppend(dom, bEndNode.dom, nextNode);
			aStart++;
			bEnd--;
			aStartNode = a[aStart];
			bEndNode = b[bEnd];
			if (bEndNode.dom) {
				b[bEnd] = bEndNode = cloneVNode(bEndNode);
			}
			continue;
		}
		break;
	}

	if (aStart > aEnd) {
		if (bStart <= bEnd) {
			nextPos = bEnd + 1;
			nextNode = nextPos < b.length ? b[nextPos].dom : null;
			while (bStart <= bEnd) {
				node = b[bStart];
				if (node.dom) {
					b[bStart] = node = cloneVNode(node);
				}
				bStart++;
				insertOrAppend(dom, mount(node, null, lifecycle, context, isSVG), nextNode);
			}
		}
	} else if (bStart > bEnd) {
		while (aStart <= aEnd) {
			unmount(a[aStart++], dom, lifecycle, false, isRecycling);
		}
	} else {
		aLength = aEnd - aStart + 1;
		bLength = bEnd - bStart + 1;
		const sources = new Array(bLength);

		// Mark all nodes as inserted.
		for (i = 0; i < bLength; i++) {
			sources[i] = -1;
		}
		let moved = false;
		let pos = 0;
		let patched = 0;

		// When sizes are small, just loop them through
		if ((bLength <= 4) || (aLength * bLength <= 16)) {
			for (i = aStart; i <= aEnd; i++) {
				aNode = a[i];
				if (patched < bLength) {
					for (j = bStart; j <= bEnd; j++) {
						bNode = b[j];
						if (aNode.key === bNode.key) {
							sources[j - bStart] = i;

							if (pos > j) {
								moved = true;
							} else {
								pos = j;
							}
							if (bNode.dom) {
								b[j] = bNode = cloneVNode(bNode);
							}
							patch(aNode, bNode, dom, lifecycle, context, isSVG, isRecycling);
							patched++;
							a[i] = null;
							break;
						}
					}
				}
			}
		} else {
			const keyIndex = new Map();

			// Map keys by their index in array
			for (i = bStart; i <= bEnd; i++) {
				node = b[i];
				keyIndex.set(node.key, i);
			}

			// Try to patch same keys
			for (i = aStart; i <= aEnd; i++) {
				aNode = a[i];

				if (patched < bLength) {
					j = keyIndex.get(aNode.key);

					if (!isUndefined(j)) {
						bNode = b[j];
						sources[j - bStart] = i;
						if (pos > j) {
							moved = true;
						} else {
							pos = j;
						}
						if (bNode.dom) {
							b[j] = bNode = cloneVNode(bNode);
						}
						patch(aNode, bNode, dom, lifecycle, context, isSVG, isRecycling);
						patched++;
						a[i] = null;
					}
				}
			}
		}
		// fast-path: if nothing patched remove all old and add all new
		if (aLength === a.length && patched === 0) {
			removeAllChildren(dom, a, lifecycle, isRecycling);
			while (bStart < bLength) {
				node = b[bStart];
				if (node.dom) {
					b[bStart] = node = cloneVNode(node);
				}
				bStart++;
				insertOrAppend(dom, mount(node, null, lifecycle, context, isSVG), null);
			}
		} else {
			i = aLength - patched;
			while (i > 0) {
				aNode = a[aStart++];
				if (!isNull(aNode)) {
					unmount(aNode, dom, lifecycle, true, isRecycling);
					i--;
				}
			}
			if (moved) {
				const seq = lis_algorithm(sources);
				j = seq.length - 1;
				for (i = bLength - 1; i >= 0; i--) {
					if (sources[i] === -1) {
						pos = i + bStart;
						node = b[pos];
						if (node.dom) {
							b[pos] = node = cloneVNode(node);
						}
						nextPos = pos + 1;
						nextNode = nextPos < b.length ? b[nextPos].dom : null;
						insertOrAppend(dom, mount(node, dom, lifecycle, context, isSVG), nextNode);
					} else {
						if (j < 0 || i !== seq[j]) {
							pos = i + bStart;
							node = b[pos];
							nextPos = pos + 1;
							nextNode = nextPos < b.length ? b[nextPos].dom : null;
							insertOrAppend(dom, node.dom, nextNode);
						} else {
							j--;
						}
					}
				}
			} else if (patched !== bLength) {
				// when patched count doesn't match b length we need to insert those new ones
				// loop backwards so we can use insertBefore
				for (i = bLength - 1; i >= 0; i--) {
					if (sources[i] === -1) {
						pos = i + bStart;
						node = b[pos];
						if (node.dom) {
							b[pos] = node = cloneVNode(node);
						}
						nextPos = pos + 1;
						nextNode = nextPos < b.length ? b[nextPos].dom : null;
						insertOrAppend(dom, mount(node, null, lifecycle, context, isSVG), nextNode);
					}
				}
			}
		}
	}
}

// // https://en.wikipedia.org/wiki/Longest_increasing_subsequence
function lis_algorithm(arr) {
	const p = arr.slice(0);
	const result: any[] = [0];
	let i;
	let j;
	let u;
	let v;
	let c;
	const len = arr.length;

	for (i = 0; i < len; i++) {
		let arrI = arr[i];

		if (arrI === -1) {
			continue;
		}

		j = result[result.length - 1];
		if (arr[j] < arrI) {
			p[i] = j;
			result.push(i);
			continue;
		}

		u = 0;
		v = result.length - 1;

		while (u < v) {
			c = ((u + v) / 2) | 0;
			if (arr[result[c]] < arrI) {
				u = c + 1;
			} else {
				v = c;
			}
		}

		if (arrI < arr[result[u]]) {
			if (u > 0) {
				p[i] = result[u - 1];
			}
			result[u] = i;
		}
	}

	u = result.length;
	v = result[u - 1];

	while (u-- > 0) {
		result[u] = v;
		v = p[v];
	}

	return result;
}

export function patchProp(prop, lastValue, nextValue, dom: Element, isSVG: boolean, hasControlledValue: boolean) {
	if (skipProps[prop] || hasControlledValue && prop === 'value') {
		return;
	}
	if (booleanProps[prop]) {
		dom[prop] = !!nextValue;
	} else if (strictProps[prop]) {
		const value = isNullOrUndef(nextValue) ? '' : nextValue;

		if (dom[prop] !== value) {
			dom[prop] = value;
		}
	} else if (lastValue !== nextValue) {
		if (isAttrAnEvent(prop)) {
			patchEvent(prop, lastValue, nextValue, dom);
		} else if (isNullOrUndef(nextValue)) {
			dom.removeAttribute(prop);
		} else if (prop === 'className') {
			if (isSVG) {
				dom.setAttribute('class', nextValue);
			} else {
				dom.className = nextValue;
			}
		} else if (prop === 'style') {
			patchStyle(lastValue, nextValue, dom);
		} else if (prop === 'dangerouslySetInnerHTML') {
			const lastHtml = lastValue && lastValue.__html;
			const nextHtml = nextValue && nextValue.__html;

			if (lastHtml !== nextHtml) {
				if (!isNullOrUndef(nextHtml)) {
					dom.innerHTML = nextHtml;
				}
			}
		} else {
			const ns = namespaces[prop];

			if (ns) {
				dom.setAttributeNS(ns, prop, nextValue);
			} else {
				dom.setAttribute(prop, nextValue);
			}
		}
	}
}

export function patchEvents(lastEvents, nextEvents, dom: Element) {
	lastEvents = lastEvents || EMPTY_OBJ;
	nextEvents = nextEvents || EMPTY_OBJ;

	if (nextEvents !== EMPTY_OBJ) {
		for (let name in nextEvents) {
			// do not add a hasOwnProperty check here, it affects performance
			patchEvent(name, lastEvents[name], nextEvents[name], dom);
		}
	}
	if (lastEvents !== EMPTY_OBJ) {
		for (let name in lastEvents) {
			// do not add a hasOwnProperty check here, it affects performance
			if (isNullOrUndef(nextEvents[name])) {
				patchEvent(name, lastEvents[name], null, dom);
			}
		}
	}
}

export function patchEvent(name: string, lastValue, nextValue, dom) {
	if (lastValue !== nextValue) {
		const nameLowerCase = name.toLowerCase();
		const domEvent = dom[nameLowerCase];
		// if the function is wrapped, that means it's been controlled by a wrapper
		if (domEvent && domEvent.wrapped) {
			return;
		}
		if (delegatedProps[name]) {
			handleEvent(name, lastValue, nextValue, dom);
		} else {
			if (lastValue !== nextValue) {
				if (!isFunction(nextValue) && !isNullOrUndef(nextValue)) {
					const linkEvent = nextValue.event;

					if (linkEvent && isFunction(linkEvent)) {
						if (!dom._data) {
							dom[nameLowerCase] = function(e) {
								linkEvent(e.currentTarget._data, e);
							};
						}
						dom._data = nextValue.data;
					} else {
						if (process.env.NODE_ENV !== 'production') {
							throwError(`an event on a VNode "${ name }". was not a function or a valid linkEvent.`);
						}
						throwError();
					}
				} else {
					dom[nameLowerCase] = nextValue;
				}
			}
		}
	}
}

// We are assuming here that we come from patchProp routine
// -nextAttrValue cannot be null or undefined
export function patchStyle(lastAttrValue: string | Styles, nextAttrValue: string | Styles, dom) {
	if (isString(nextAttrValue)) {
		dom.style.cssText = nextAttrValue;
		return;
	}

	for (let style in nextAttrValue as Styles) {
		// do not add a hasOwnProperty check here, it affects performance
		const value = nextAttrValue[style];

		if (isNumber(value) && !isUnitlessNumber[style]) {
			dom.style[style] = value + 'px';
		} else {
			dom.style[style] = value;
		}
	}

	if (!isNullOrUndef(lastAttrValue)) {
		for (let style in lastAttrValue as Styles) {
			if (isNullOrUndef(nextAttrValue[style])) {
				dom.style[style] = '';
			}
		}
	}
}

function removeProp(prop: string, lastValue, dom) {
	if (prop === 'className') {
		dom.removeAttribute('class');
	} else if (prop === 'value') {
		dom.value = '';
	} else if (prop === 'style') {
		dom.removeAttribute('style');
	} else if (isAttrAnEvent(prop)) {
		handleEvent(name, lastValue, null, dom);
	} else {
		dom.removeAttribute(prop);
	}
}


text:
import('GlobalVars')

FONT_SIZE = 22
CONSOLE_MAX = 5

consoleHistory = {}
line = 0
lineFocus = 0
isPopDown = false
isShiftPressed = false
isCapsOn = false
consoleBuffer = nil
endsInCloseParen = nil
doProcessConsole = false
nestLevel = 0
newHistory = nil
io.output("XseraOutput.txt")

do
    originalPrint = print
    newPrint = function(...)
        local bigTable = {...}
        i = 1
        while bigTable[i] ~= nil do
            ConsoleAdd(tostring(bigTable[i]))
            i = i + 1
        end
    end
    SetOriginalPrint = function() print = originalPrint end
    SetNewPrint = function() print = newPrint end
end

function ConsoleDraw(FONT_SIZE)
    graphics.set_camera(-240 * aspectRatio, -240, 240 * aspectRatio, 240)
    local i = 1
    for i = 1, #consoleHistory do
        graphics.draw_text(consoleHistory[i], MAIN_FONT, "left", { x = -240 * aspectRatio + 1, y = 232 - (i - 1) * FONT_SIZE + 1 }, FONT_SIZE)
    end
end

function ConsoleAdd(text, doPrint, output)
    if output ~= nil then
        io.output(output)
    else
        io.output("XseraOutput.txt")
    end
    table.insert(consoleHistory, text)
    if ((text ~= ">") and (text ~= ">>")) then
        if doPrint ~= false then
            originalPrint("[Console] " .. text)
        end
        io.write(text, "\n")
    end
    line = line + 1
    lineFocus = line
end

function ConsoleKeyup (k)
    if k:gsub("(M)(%w+)", "%1", 1) == "M" then
        local side = nil
        local cmd = nil
        if k:gsub("(M)(%w+)(L)", "%3", 1) == "L" then
            side = "left"
            cmd = k:gsub("(M)(%w+)(L)", "%2", 1)
        elseif k:gsub("(M)(%w+)(R)", "%3", 1) == "R" then
            side = "right"
            cmd = k:gsub("(M)(%w+)(R)", "%2", 1)
        else
            cmd = k:gsub("(M)(%w+)", "%2", 1)
        end
        if cmd == "shift" then
            isShiftPressed = false
        end
    end
end

function ConsoleKey (k)
    if k == "unhandled" then
        return
    end

    asciiKey = k:byte(1)
    if k == "return" then
        if ((consoleHistory == ">>") or (consoleHistory == ">")) then
            return
        end
        io.write(consoleHistory[line], "\n")
        originalPrint("[Console] " .. consoleHistory[line])
        local string = nil
        local error = nil
        local list = { "if", "do", "while", "repeat", "for", "function", "local function" }
        num = 1
        while list[num] ~= nil do
            if consoleHistory[line]:find(list[num]) ~= nil then
                nestLevel = nestLevel + 1
                num = 8 -- outside of the range
            end
            num = num + 1
        end
        if (consoleHistory[line]:sub(-1, -1) == ")") then
            endsInCloseParen = true
        else
            endsInCloseParen = false
        end
        local withoutGT = nil
        if consoleHistory[line]:gsub("(>>)(.)", "%2", 1) ~= nil then
            withoutGT = consoleHistory[line]:gsub("(>>)(.)", "%2", 1)
        else
            withoutGT = consoleHistory[line]:gsub("(>>)(.)", "%2", 1)
        end
        if withoutGT == "end" then
            nestLevel = nestLevel - 1
            if nestLevel == 0 then
                doProcessConsole = true
            elseif nestLevel < 0 then
                doProcessConsole = true
            end
        end
        if consoleBuffer ~= nil then
            consoleBuffer = consoleBuffer .. "\n" .. withoutGT
        else
            consoleBuffer = consoleHistory[line]:gsub("(>)(.)", "%2", 1)
        end
        if endsInCloseParen then
            if consoleBuffer == consoleHistory[line]:gsub("(>)(.)", "%2", 1) then
                if consoleBuffer:find("function") == nil then
                    doProcessConsole = true
                end
            end
        end
        if doProcessConsole == false then
            ConsoleAdd(">>")
        else
            string, error = loadstring(consoleBuffer)
            if error == nil then
                string()
            else
                ConsoleAdd(error)
            end
            consoleBuffer = nil
            nestLevel = 0
            ConsoleAdd(">")
        end
    elseif k == "escape" then
        SetNewPrint()
        if isPopDown then
            keyboard[4][10].active = false
            isPopDown = false
        else
            mode_manager.switch("Xsera/MainMenu")
        end
    elseif k == "backspace" then
        if ((consoleHistory[line] ~= ">") and (consoleHistory[line] ~= ">>")) then
            consoleHistory[line] = consoleHistory[line]:sub(1, -2)
        end
    elseif k == "tab" then
        keyboard[4][10].active = false
        release = true
    elseif asciiKey >= 97 and asciiKey <= 122 then
        if k:byte(2, 2) == nil then
            if isShiftPressed or isCapsOn then
                consoleHistory[line] = consoleHistory[line] .. k:upper()
            else
                consoleHistory[line] = consoleHistory[line] .. k
            end
        end
    elseif asciiKey == 32 then
        consoleHistory[line] = consoleHistory[line] .. k
    elseif charSubTable[k] then
        if isShiftPressed or isCapsOn then
            consoleHistory[line] = consoleHistory[line] .. charSubTable[k]
        else
            consoleHistory[line] = consoleHistory[line] .. k
        end
    elseif k == "left" then
        originalPrint("BOING")
    elseif k == "right" then
        originalPrint("BOING")
    elseif k == "up" then
        originalPrint("BOING")
    elseif k == "down" then
        originalPrint("BOING")
    elseif k == "KP9" then
        if lineFocus > 1 then
            if newHistory == nil then
                newHistory = consoleHistory[line]
                originalPrint(newHistory)
            end
            lineFocus = lineFocus - 1
            if consoleHistory[lineFocus]:sub(1, 1) == "$" then
                lineFocus = lineFocus + 1
            end
            while consoleHistory[lineFocus]:sub(1, 1) ~= ">" do
                lineFocus = lineFocus - 1
            end
        end
        consoleHistory[line] = consoleHistory[lineFocus]
    elseif k == "KP3" then
        originalPrint(lineFocus, line)
        if lineFocus < line then
            lineFocus = lineFocus + 1
            while consoleHistory[lineFocus]:sub(1, 1) ~= ">" do
                lineFocus = lineFocus + 1
            end
            consoleHistory[line] = consoleHistory[lineFocus]
        end
        originalPrint(lineFocus, line)
        if ((lineFocus == line) and (newHistory ~= nil)) then
            consoleHistory[line] = newHistory
            newHistory = nil
        end
        originalPrint(lineFocus, line)
        if lineFocus > line then
            lineFocus = lineFocus - 1
        end
        originalPrint(lineFocus, line)
        originalPrint("----------")
    else
        if k:gsub("(M)(%w+)", "%1", 1) == "M" then
            local side = nil
            local cmd = nil
            if k:gsub("(M)(%w+)(L)", "%3", 1) == "L" then
                side = "left"
                cmd = k:gsub("(M)(%w+)(L)", "%2", 1)
            elseif k:gsub("(M)(%w+)(R)", "%3", 1) == "R" then
                side = "right"
                cmd = k:gsub("(M)(%w+)(R)", "%2", 1)
            else
                cmd = k:gsub("(M)(%w+)", "%2", 1)
            end
            if cmd == "shift" then
                isShiftPressed = true
            end
            if cmd == "caps" then
                isCapsOn = not isCapsOn
                originalPrint("Caps: ", isCapsOn)
            end
        end
    end
end

charSubTable = { [","] = "<", ["."] = ">", ["-"] = "_", ["1"] = "!",
    ["2"] = "@", ["3"] = "#", ["4"] = "$", ["5"] = "%", ["6"] = "^",
    ["7"] = "&", ["8"] = "*", ["9"] = "(", ["0"] = ")", ["\'"] = "\"",
    ["\="] = "\+", ["/"] = "?", ["["] = "{", ["]"] = "}", [";"] = ":" }

function CoutTable (t, name, doPrint)
    ConsoleAdd(table_define(t, name), doPrint, "XseraTables.txt")
end

function LogError(text, current)
    ConsoleAdd(text .. "(current " .. current .. ")")
    if current > 10 then
        mode_manager.quit()
    end
    if current > 5 then
        errNotice = { start = mode_manager.time(), duration = current - 5, text = text }
    end
end

--[[ error current scheme:
    1-5: non-fatal, continue
        1: code not implemented
        2: load error
    6-10: non-fatal, display on screen
    11-15: fatal, exit
        11: Improper input - data is not of the correct type
        12: No input given - file is missing necessary data
--]]

redpajama_set_name: RedPajamaGithub


text:
using System.Net;
using System.Web;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Core.Mapping;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.ContentEditing;
using Umbraco.Cms.Core.Models.Membership;
using Umbraco.Cms.Core.Security;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Snippets;
using Umbraco.Cms.Core.Strings;
using Umbraco.Cms.Core.Strings.Css;
using Umbraco.Cms.Web.BackOffice.Filters;
using Umbraco.Cms.Web.BackOffice.Trees;
using Umbraco.Cms.Web.Common.ActionsResults;
using Umbraco.Cms.Web.Common.Attributes;
using Umbraco.Cms.Web.Common.Authorization;
using Umbraco.Cms.Web.Common.DependencyInjection;
using Umbraco.Extensions;
using Stylesheet = Umbraco.Cms.Core.Models.Stylesheet;
using StylesheetRule = Umbraco.Cms.Core.Models.ContentEditing.StylesheetRule;

namespace Umbraco.Cms.Web.BackOffice.Controllers;

// TODO: Put some exception filters in our webapi to return 404 instead of 500 when we throw ArgumentNullException
// ref: https://www.exceptionnotfound.net/the-asp-net-web-api-exception-handling-pipeline-a-guided-tour/
[PluginController(Constants.Web.Mvc.BackOfficeApiArea)]
//[PrefixlessBodyModelValidator]
[Authorize(Policy = AuthorizationPolicies.SectionAccessSettings)]
public class CodeFileController : BackOfficeNotificationsController
{
    private readonly IBackOfficeSecurityAccessor _backOfficeSecurityAccessor;
    private readonly IFileService _fileService;
    private readonly FileSystems _fileSystems;
    private readonly GlobalSettings _globalSettings;
    private readonly IHostingEnvironment _hostingEnvironment;

    private readonly ILocalizedTextService _localizedTextService;
    private readonly IShortStringHelper _shortStringHelper;
    private readonly IUmbracoMapper _umbracoMapper;
    private readonly PartialViewSnippetCollection _partialViewSnippetCollection;
    private readonly PartialViewMacroSnippetCollection _partialViewMacroSnippetCollection;

    [ActivatorUtilitiesConstructor]
    public CodeFileController(
        IHostingEnvironment hostingEnvironment,
        FileSystems fileSystems,
        IFileService fileService,
        IBackOfficeSecurityAccessor backOfficeSecurityAccessor,
        ILocalizedTextService localizedTextService,
        IUmbracoMapper umbracoMapper,
        IShortStringHelper shortStringHelper,
        IOptionsSnapshot<GlobalSettings> globalSettings,
        PartialViewSnippetCollection partialViewSnippetCollection,
        PartialViewMacroSnippetCollection partialViewMacroSnippetCollection)
    {
        _hostingEnvironment = hostingEnvironment;
        _fileSystems = fileSystems;
        _fileService = fileService;
        _backOfficeSecurityAccessor = backOfficeSecurityAccessor;
        _localizedTextService = localizedTextService;
        _umbracoMapper = umbracoMapper;
        _shortStringHelper = shortStringHelper;
        _globalSettings = globalSettings.Value;
        _partialViewSnippetCollection = partialViewSnippetCollection;
        _partialViewMacroSnippetCollection = partialViewMacroSnippetCollection;
    }

    [Obsolete("Use ctor will all params. Scheduled for removal in V12.")]
    public CodeFileController(
        IHostingEnvironment hostingEnvironment,
        FileSystems fileSystems,
        IFileService fileService,
        IBackOfficeSecurityAccessor backOfficeSecurityAccessor,
        ILocalizedTextService localizedTextService,
        IUmbracoMapper umbracoMapper,
        IShortStringHelper shortStringHelper,
        IOptionsSnapshot<GlobalSettings> globalSettings) : this(
        hostingEnvironment,
        fileSystems,
        fileService,
        backOfficeSecurityAccessor,
        localizedTextService,
        umbracoMapper,
        shortStringHelper,
        globalSettings,
        StaticServiceProvider.Instance.GetRequiredService<PartialViewSnippetCollection>(),
        StaticServiceProvider.Instance.GetRequiredService<PartialViewMacroSnippetCollection>())
    {
    }

    /// <summary>
    ///     Used to create a brand new file
    /// </summary>
    /// <param name="type">This is a string but will be 'scripts' 'partialViews', 'partialViewMacros'</param>
    /// <param name="display"></param>
    /// <returns>Will return a simple 200 if file creation succeeds</returns>
    [ValidationFilter]
    public ActionResult<CodeFileDisplay> PostCreate(string type, CodeFileDisplay display)
    {
        if (display == null)
        {
            throw new ArgumentNullException("display");
        }

        if (string.IsNullOrWhiteSpace(type))
        {
            throw new ArgumentException("Value cannot be null or whitespace.", "type");
        }

        IUser? currentUser = _backOfficeSecurityAccessor.BackOfficeSecurity?.CurrentUser;
        switch (type)
        {
            case Constants.Trees.PartialViews:
                var view = new PartialView(PartialViewType.PartialView, display.VirtualPath ?? string.Empty)
                {
                    Content = display.Content,
                };
                Attempt<IPartialView?> result = _fileService.CreatePartialView(view, display.Snippet, currentUser?.Id);
                if (result.Success)
                {
                    return Ok();
                }

                return ValidationProblem(result.Exception?.Message);

            case Constants.Trees.PartialViewMacros:
                var viewMacro = new PartialView(PartialViewType.PartialViewMacro, display.VirtualPath ?? string.Empty)
                {
                    Content = display.Content,
                };
                Attempt<IPartialView?> resultMacro =
                    _fileService.CreatePartialViewMacro(viewMacro, display.Snippet, currentUser?.Id);
                if (resultMacro.Success)
                {
                    return Ok();
                }

                return ValidationProblem(resultMacro.Exception?.Message);

            case Constants.Trees.Scripts:
                var script = new Script(display.VirtualPath ?? string.Empty);
                _fileService.SaveScript(script, currentUser?.Id);
                return Ok();

            default:
                return NotFound();
        }
    }

    /// <summary>
    ///     Used to create a container/folder in 'partialViews', 'partialViewMacros', 'scripts' or 'stylesheets'
    /// </summary>
    /// <param name="type">'partialViews', 'partialViewMacros' or 'scripts'</param>
    /// <param name="parentId">The virtual path of the parent.</param>
    /// <param name="name">The name of the container/folder</param>
    /// <returns></returns>
    [HttpPost]
    public ActionResult<CodeFileDisplay> PostCreateContainer(string type, string parentId, string name)
    {
        if (string.IsNullOrWhiteSpace(type))
        {
            throw new ArgumentException("Value cannot be null or whitespace.", "type");
        }

        if (string.IsNullOrWhiteSpace(parentId))
        {
            throw new ArgumentException("Value cannot be null or whitespace.", "parentId");
        }

        if (string.IsNullOrWhiteSpace(name))
        {
            throw new ArgumentException("Value cannot be null or whitespace.", "name");
        }

        if (name.ContainsAny(Path.GetInvalidPathChars()))
        {
            return ValidationProblem(_localizedTextService.Localize("codefile", "createFolderIllegalChars"));
        }

        // if the parentId is root (-1) then we just need an empty string as we are
        // creating the path below and we don't want -1 in the path
        if (parentId == Constants.System.RootString)
        {
            parentId = string.Empty;
        }

        name = HttpUtility.UrlDecode(name);

        if (parentId.IsNullOrWhiteSpace() == false)
        {
            parentId = HttpUtility.UrlDecode(parentId);
            name = parentId.EnsureEndsWith("/") + name;
        }

        var virtualPath = string.Empty;
        switch (type)
        {
            case Constants.Trees.PartialViews:
                virtualPath = NormalizeVirtualPath(name, Constants.SystemDirectories.PartialViews);
                _fileService.CreatePartialViewFolder(virtualPath);
                break;
            case Constants.Trees.PartialViewMacros:
                virtualPath = NormalizeVirtualPath(name, Constants.SystemDirectories.MacroPartials);
                _fileService.CreatePartialViewMacroFolder(virtualPath);
                break;
            case Constants.Trees.Scripts:
                virtualPath = NormalizeVirtualPath(name, _globalSettings.UmbracoScriptsPath);
                _fileService.CreateScriptFolder(virtualPath);
                break;
            case Constants.Trees.Stylesheets:
                virtualPath = NormalizeVirtualPath(name, _globalSettings.UmbracoCssPath);
                _fileService.CreateStyleSheetFolder(virtualPath);
                break;
        }

        return new CodeFileDisplay { VirtualPath = virtualPath, Path = Url.GetTreePathFromFilePath(virtualPath) };
    }

    /// <summary>
    ///     Used to get a specific file from disk via the FileService
    /// </summary>
    /// <param name="type">This is a string but will be 'scripts' 'partialViews', 'partialViewMacros' or 'stylesheets'</param>
    /// <param name="virtualPath">The filename or URL encoded path of the file to open</param>
    /// <returns>The file and its contents from the virtualPath</returns>
    public ActionResult<CodeFileDisplay?> GetByPath(string type, string virtualPath)
    {
        if (string.IsNullOrWhiteSpace(type))
        {
            throw new ArgumentException("Value cannot be null or whitespace.", "type");
        }

        if (string.IsNullOrWhiteSpace(virtualPath))
        {
            throw new ArgumentException("Value cannot be null or whitespace.", "virtualPath");
        }

        virtualPath = HttpUtility.UrlDecode(virtualPath);

        switch (type)
        {
            case Constants.Trees.PartialViews:
                IPartialView? view = _fileService.GetPartialView(virtualPath);
                if (view != null)
                {
                    CodeFileDisplay? display = _umbracoMapper.Map<IPartialView, CodeFileDisplay>(view);

                    if (display is not null)
                    {
                        display.FileType = Constants.Trees.PartialViews;
                        display.Path = Url.GetTreePathFromFilePath(view.Path);
                        display.Id = HttpUtility.UrlEncode(view.Path);
                    }

                    return display;
                }

                break;
            case Constants.Trees.PartialViewMacros:
                IPartialView? viewMacro = _fileService.GetPartialViewMacro(virtualPath);
                if (viewMacro != null)
                {
                    CodeFileDisplay? display = _umbracoMapper.Map<IPartialView, CodeFileDisplay>(viewMacro);

                    if (display is not null)
                    {
                        display.FileType = Constants.Trees.PartialViewMacros;
                        display.Path = Url.GetTreePathFromFilePath(viewMacro.Path);
                        display.Id = HttpUtility.UrlEncode(viewMacro.Path);
                    }

                    return display;
                }

                break;
            case Constants.Trees.Scripts:
                IScript? script = _fileService.GetScript(virtualPath);
                if (script != null)
                {
                    CodeFileDisplay? display = _umbracoMapper.Map<IScript, CodeFileDisplay>(script);

                    if (display is not null)
                    {
                        display.FileType = Constants.Trees.Scripts;
                        display.Path = Url.GetTreePathFromFilePath(script.Path);
                        display.Id = HttpUtility.UrlEncode(script.Path);
                    }

                    return display;
                }

                break;
            case Constants.Trees.Stylesheets:
                IStylesheet? stylesheet = _fileService.GetStylesheet(virtualPath);
                if (stylesheet != null)
                {
                    CodeFileDisplay? display = _umbracoMapper.Map<IStylesheet, CodeFileDisplay>(stylesheet);

                    if (display is not null)
                    {
                        display.FileType = Constants.Trees.Stylesheets;
                        display.Path = Url.GetTreePathFromFilePath(stylesheet.Path);
                        display.Id = HttpUtility.UrlEncode(stylesheet.Path);
                    }

                    return display;
                }

                break;
        }

        return NotFound();
    }

    /// <summary>
    ///     Used to get a list of available templates/snippets to base a new Partial View or Partial View Macro from
    /// </summary>
    /// <param name="type">This is a string but will be 'partialViews', 'partialViewMacros'</param>
    /// <returns>Returns a list of <see cref="SnippetDisplay" /> if a correct type is sent</returns>
    public ActionResult<IEnumerable<SnippetDisplay>> GetSnippets(string type)
    {
        if (string.IsNullOrWhiteSpace(type))
        {
            throw new ArgumentException("Value cannot be null or whitespace.", "type");
        }

        IEnumerable<string> snippets;
        switch (type)
        {
            case Constants.Trees.PartialViews:
                snippets = _partialViewSnippetCollection.GetNames();
                break;
            case Constants.Trees.PartialViewMacros:
                snippets = _partialViewMacroSnippetCollection.GetNames();
                break;
            default:
                return NotFound();
        }

        return snippets.Select(snippet => new SnippetDisplay
        {
            Name = snippet.SplitPascalCasing(_shortStringHelper).ToFirstUpperInvariant(),
            FileName = snippet,
        }).ToList();
    }

    /// <summary>
    ///     Used to scaffold the json object for the editors for 'scripts', 'partialViews', 'partialViewMacros' and
    ///     'stylesheets'
    /// </summary>
    /// <param name="type">This is a string but will be 'scripts' 'partialViews', 'partialViewMacros' or 'stylesheets'</param>
    /// <param name="id"></param>
    /// <param name="snippetName"></param>
    /// <returns></returns>
    public ActionResult<CodeFileDisplay?> GetScaffold(string type, string id, string? snippetName = null)
    {
        if (string.IsNullOrWhiteSpace(type))
        {
            throw new ArgumentException("Value cannot be null or whitespace.", "type");
        }

        if (string.IsNullOrWhiteSpace(id))
        {
            throw new ArgumentException("Value cannot be null or whitespace.", "id");
        }

        CodeFileDisplay? codeFileDisplay;

        switch (type)
        {
            case Constants.Trees.PartialViews:
                codeFileDisplay =
                    _umbracoMapper.Map<IPartialView, CodeFileDisplay>(new PartialView(PartialViewType.PartialView, string.Empty));
                if (codeFileDisplay is not null)
                {
                    codeFileDisplay.VirtualPath = Constants.SystemDirectories.PartialViews;
                    if (snippetName.IsNullOrWhiteSpace() == false)
                    {
                            codeFileDisplay.Content = _partialViewSnippetCollection.GetContentFromName(snippetName!);
                    }
                }

                break;
            case Constants.Trees.PartialViewMacros:
                codeFileDisplay =
                    _umbracoMapper.Map<IPartialView, CodeFileDisplay>(new PartialView(PartialViewType.PartialViewMacro, string.Empty));
                if (codeFileDisplay is not null)
                {
                    codeFileDisplay.VirtualPath = Constants.SystemDirectories.MacroPartials;
                    if (snippetName.IsNullOrWhiteSpace() == false)
                    {
                        codeFileDisplay.Content = _partialViewMacroSnippetCollection.GetContentFromName(snippetName!);
                    }
                }

                break;
            case Constants.Trees.Scripts:
                codeFileDisplay = _umbracoMapper.Map<Script, CodeFileDisplay>(new Script(string.Empty));
                if (codeFileDisplay is not null)
                {
                    codeFileDisplay.VirtualPath = _globalSettings.UmbracoScriptsPath;
                }

                break;
            case Constants.Trees.Stylesheets:
                codeFileDisplay = _umbracoMapper.Map<Stylesheet, CodeFileDisplay>(new Stylesheet(string.Empty));
                if (codeFileDisplay is not null)
                {
                    codeFileDisplay.VirtualPath = _globalSettings.UmbracoCssPath;
                }

                break;
            default:
                return new UmbracoProblemResult("Unsupported editortype", HttpStatusCode.BadRequest);
        }

        if (codeFileDisplay is null)
        {
            return codeFileDisplay;
        }

        // Make sure that the root virtual path ends with '/'
        codeFileDisplay.VirtualPath = codeFileDisplay.VirtualPath?.EnsureEndsWith("/");

        if (id != Constants.System.RootString)
        {
            codeFileDisplay.VirtualPath += id.TrimStart(Constants.CharArrays.ForwardSlash).EnsureEndsWith("/");
            //if it's not new then it will have a path, otherwise it won't
            codeFileDisplay.Path = Url.GetTreePathFromFilePath(id);
        }

        codeFileDisplay.VirtualPath = codeFileDisplay.VirtualPath?.TrimStart("~");
        codeFileDisplay.FileType = type;
        return codeFileDisplay;
    }

    /// <summary>
    ///     Used to delete a specific file from disk via the FileService
    /// </summary>
    /// <param name="type">This is a string but will be 'scripts' 'partialViews', 'partialViewMacros' or 'stylesheets'</param>
    /// <param name="virtualPath">The filename or URL encoded path of the file to delete</param>
    /// <returns>Will return a simple 200 if file deletion succeeds</returns>
    [HttpDelete]
    [HttpPost]
    public IActionResult Delete(string type, string virtualPath)
    {
        if (string.IsNullOrWhiteSpace(type))
        {
            throw new ArgumentException("Value cannot be null or whitespace.", "type");
        }

        if (string.IsNullOrWhiteSpace(virtualPath))
        {
            throw new ArgumentException("Value cannot be null or whitespace.", "virtualPath");
        }

        virtualPath = HttpUtility.UrlDecode(virtualPath);
        IUser? currentUser = _backOfficeSecurityAccessor.BackOfficeSecurity?.CurrentUser;
        switch (type)
        {
            case Constants.Trees.PartialViews:
                if (IsDirectory(
                        _hostingEnvironment.MapPathContentRoot(Path.Combine(Constants.SystemDirectories.PartialViews, virtualPath))))
                {
                    _fileService.DeletePartialViewFolder(virtualPath);
                    return Ok();
                }

                if (_fileService.DeletePartialView(virtualPath, currentUser?.Id))
                {
                    return Ok();
                }

                return new UmbracoProblemResult("No Partial View or folder found with the specified path", HttpStatusCode.NotFound);

            case Constants.Trees.PartialViewMacros:
                if (IsDirectory(
                        _hostingEnvironment.MapPathContentRoot(Path.Combine(Constants.SystemDirectories.MacroPartials, virtualPath))))
                {
                    _fileService.DeletePartialViewMacroFolder(virtualPath);
                    return Ok();
                }

                if (_fileService.DeletePartialViewMacro(virtualPath, currentUser?.Id))
                {
                    return Ok();
                }

                return new UmbracoProblemResult("No Partial View Macro or folder found with the specified path", HttpStatusCode.NotFound);

            case Constants.Trees.Scripts:
                if (IsDirectory(
                        _hostingEnvironment.MapPathWebRoot(Path.Combine(_globalSettings.UmbracoScriptsPath, virtualPath))))
                {
                    _fileService.DeleteScriptFolder(virtualPath);
                    return Ok();
                }

                if (_fileService.GetScript(virtualPath) != null)
                {
                    _fileService.DeleteScript(virtualPath, currentUser?.Id);
                    return Ok();
                }

                return new UmbracoProblemResult("No Script or folder found with the specified path", HttpStatusCode.NotFound);
            case Constants.Trees.Stylesheets:
                if (IsDirectory(
                        _hostingEnvironment.MapPathWebRoot(Path.Combine(_globalSettings.UmbracoCssPath, virtualPath))))
                {
                    _fileService.DeleteStyleSheetFolder(virtualPath);
                    return Ok();
                }

                if (_fileService.GetStylesheet(virtualPath) != null)
                {
                    _fileService.DeleteStylesheet(virtualPath, currentUser?.Id);
                    return Ok();
                }

                return new UmbracoProblemResult("No Stylesheet found with the specified path", HttpStatusCode.NotFound);
            default:
                return NotFound();
        }
    }

    /// <summary>
    ///     Used to create or update a 'partialview', 'partialviewmacro', 'script' or 'stylesheets' file
    /// </summary>
    /// <param name="display"></param>
    /// <returns>The updated CodeFileDisplay model</returns>
    public ActionResult<CodeFileDisplay> PostSave(CodeFileDisplay display)
    {
        if (display == null)
        {
            throw new ArgumentNullException("display");
        }

        TryValidateModel(display);
        if (ModelState.IsValid == false)
        {
            return ValidationProblem(ModelState);
        }

        switch (display.FileType)
        {
            case Constants.Trees.PartialViews:
                Attempt<IPartialView?> partialViewResult = CreateOrUpdatePartialView(display);
                if (partialViewResult.Success)
                {
                    display = _umbracoMapper.Map(partialViewResult.Result, display);
                    display.Path = Url.GetTreePathFromFilePath(partialViewResult.Result?.Path);
                    display.Id = HttpUtility.UrlEncode(partialViewResult.Result?.Path);
                    return display;
                }

                display.AddErrorNotification(
                    _localizedTextService.Localize("speechBubbles", "partialViewErrorHeader"),
                    _localizedTextService.Localize("speechBubbles", "partialViewErrorText"));
                break;

            case Constants.Trees.PartialViewMacros:
                Attempt<IPartialView?> partialViewMacroResult = CreateOrUpdatePartialViewMacro(display);
                if (partialViewMacroResult.Success)
                {
                    display = _umbracoMapper.Map(partialViewMacroResult.Result, display);
                    display.Path = Url.GetTreePathFromFilePath(partialViewMacroResult.Result?.Path);
                    display.Id = HttpUtility.UrlEncode(partialViewMacroResult.Result?.Path);
                    return display;
                }

                display.AddErrorNotification(
                    _localizedTextService.Localize("speechBubbles", "partialViewErrorHeader"),
                    _localizedTextService.Localize("speechBubbles", "partialViewErrorText"));
                break;

            case Constants.Trees.Scripts:

                IScript? scriptResult = CreateOrUpdateScript(display);
                display = _umbracoMapper.Map(scriptResult, display);
                display.Path = Url.GetTreePathFromFilePath(scriptResult?.Path);
                display.Id = HttpUtility.UrlEncode(scriptResult?.Path);
                return display;

            //display.AddErrorNotification(
            //    _localizedTextService.Localize("speechBubbles/partialViewErrorHeader"),
            //    _localizedTextService.Localize("speechBubbles/partialViewErrorText"));

            case Constants.Trees.Stylesheets:

                IStylesheet? stylesheetResult = CreateOrUpdateStylesheet(display);
                display = _umbracoMapper.Map(stylesheetResult, display);
                display.Path = Url.GetTreePathFromFilePath(stylesheetResult?.Path);
                display.Id = HttpUtility.UrlEncode(stylesheetResult?.Path);
                return display;

            default:
                return NotFound();
        }

        return display;
    }

    /// <summary>
    ///     Extracts "umbraco style rules" from a style sheet
    /// </summary>
    /// <param name="data">The style sheet data</param>
    /// <returns>The style rules</returns>
    public StylesheetRule[]? PostExtractStylesheetRules(StylesheetData data)
    {
        if (data.Content.IsNullOrWhiteSpace())
        {
            return new StylesheetRule[0];
        }

        return StylesheetHelper.ParseRules(data.Content)?.Select(rule => new StylesheetRule
        {
            Name = rule.Name,
            Selector = rule.Selector,
            Styles = rule.Styles
        }).ToArray();
    }

    /// <summary>
    ///     Creates a style sheet from CSS and style rules
    /// </summary>
    /// <param name="data">The style sheet data</param>
    /// <returns>The style sheet combined from the CSS and the rules</returns>
    /// <remarks>
    ///     Any "umbraco style rules" in the CSS will be removed and replaced with the rules passed in <see cref="data" />
    /// </remarks>
    public string? PostInterpolateStylesheetRules(StylesheetData data)
    {
        // first remove all existing rules
        Core.Strings.Css.StylesheetRule[] existingRules = data.Content.IsNullOrWhiteSpace()
            ? new Core.Strings.Css.StylesheetRule[0]
            : StylesheetHelper.ParseRules(data.Content).ToArray();
        foreach (Core.Strings.Css.StylesheetRule rule in existingRules)
        {
            data.Content = StylesheetHelper.ReplaceRule(data.Content, rule.Name, null);
        }

        data.Content = data.Content?.TrimEnd(Constants.CharArrays.LineFeedCarriageReturn);

        // now add all the posted rules
        if (data.Rules != null && data.Rules.Any())
        {
            foreach (StylesheetRule rule in data.Rules)
            {
                data.Content = StylesheetHelper.AppendRule(
                    data.Content,
                    new Core.Strings.Css.StylesheetRule
                    {
                        Name = rule.Name,
                        Selector = rule.Selector,
                        Styles = rule.Styles
                    });
            }

            data.Content += Environment.NewLine;
        }

        return data.Content;
    }

    /// <summary>
    ///     Create or Update a Script
    /// </summary>
    /// <param name="display"></param>
    /// <returns></returns>
    /// <remarks>
    ///     It's important to note that Scripts are DIFFERENT from cshtml files since scripts use IFileSystem and cshtml files
    ///     use a normal file system because they must exist on a real file system for ASP.NET to work.
    /// </remarks>
    private IScript? CreateOrUpdateScript(CodeFileDisplay display) =>
        CreateOrUpdateFile(
            display,
            ".js",
            _fileSystems.ScriptsFileSystem,
            name => _fileService.GetScript(name),
            (script, userId) => _fileService.SaveScript(script, userId),
            name => new Script(name ?? string.Empty));

    private IStylesheet? CreateOrUpdateStylesheet(CodeFileDisplay display) =>
        CreateOrUpdateFile(
            display,
            ".css",
            _fileSystems.StylesheetsFileSystem,
            name => _fileService.GetStylesheet(name),
            (stylesheet, userId) => _fileService.SaveStylesheet(stylesheet, userId),
            name => new Stylesheet(name ?? string.Empty));

    private T CreateOrUpdateFile<T>(CodeFileDisplay display, string extension, IFileSystem? fileSystem, Func<string?, T> getFileByName, Action<T, int?> saveFile, Func<string?, T> createFile)
        where T : IFile?
    {
        //must always end with the correct extension
        display.Name = EnsureCorrectFileExtension(display.Name, extension);

        var virtualPath = display.VirtualPath ?? string.Empty;
        // this is all weird, should be using relative paths everywhere!
        var relPath = fileSystem?.GetRelativePath(virtualPath);

        if (relPath?.EndsWith(extension) == false)
        {
            //this would typically mean it's new
            relPath = relPath.IsNullOrWhiteSpace()
                ? relPath + display.Name
                : relPath.EnsureEndsWith('/') + display.Name;
        }

        IUser? currentUser = _backOfficeSecurityAccessor.BackOfficeSecurity?.CurrentUser;
        T file = getFileByName(relPath);
        if (file != null)
        {
            // might need to find the path
            var orgPath = file.Name is null
                ? string.Empty
                : file.OriginalPath.Substring(0, file.OriginalPath.IndexOf(file.Name));
            file.Path = orgPath + display.Name;

            file.Content = display.Content;
            //try/catch? since this doesn't return an Attempt?
            saveFile(file, currentUser?.Id);
        }
        else
        {
            file = createFile(relPath);
            if (file is not null)
            {
                file.Content = display.Content;
            }

            saveFile(file, currentUser?.Id);
        }

        return file;
    }

    private Attempt<IPartialView?> CreateOrUpdatePartialView(CodeFileDisplay display) =>
        CreateOrUpdatePartialView(
            display,
            Constants.SystemDirectories.PartialViews,
            _fileService.GetPartialView,
            _fileService.SavePartialView,
            _fileService.CreatePartialView);

    private Attempt<IPartialView?> CreateOrUpdatePartialViewMacro(CodeFileDisplay display) =>
        CreateOrUpdatePartialView(display, Constants.SystemDirectories.MacroPartials, _fileService.GetPartialViewMacro, _fileService.SavePartialViewMacro, _fileService.CreatePartialViewMacro);

    /// <summary>
    ///     Helper method to take care of persisting partial views or partial view macros - so we're not duplicating the same
    ///     logic
    /// </summary>
    /// <param name="display"></param>
    /// <param name="systemDirectory"></param>
    /// <param name="getView"></param>
    /// <param name="saveView"></param>
    /// <param name="createView"></param>
    /// <returns></returns>
    private Attempt<IPartialView?> CreateOrUpdatePartialView(
        CodeFileDisplay display,
        string systemDirectory,
        Func<string, IPartialView?> getView,
        Func<IPartialView, int?,
            Attempt<IPartialView?>> saveView,
        Func<IPartialView, string?,
            int?, Attempt<IPartialView?>> createView)
    {
        //must always end with the correct extension
        display.Name = EnsureCorrectFileExtension(display.Name, ".cshtml");

        Attempt<IPartialView?> partialViewResult;
        IUser? currentUser = _backOfficeSecurityAccessor.BackOfficeSecurity?.CurrentUser;

        var virtualPath = NormalizeVirtualPath(display.VirtualPath, systemDirectory);
        IPartialView? view = getView(virtualPath);
        if (view != null)
        {
            // might need to find the path
            var orgPath = view.OriginalPath.Substring(0, view.OriginalPath.IndexOf(view.Name ?? string.Empty));
            view.Path = orgPath + display.Name;

            view.Content = display.Content;
            partialViewResult = saveView(view, currentUser?.Id);
        }
        else
        {
            view = new PartialView(PartialViewType.PartialView, virtualPath + display.Name)
            {
                Content = display.Content
            };
            partialViewResult = createView(view, display.Snippet, currentUser?.Id);
        }

        return partialViewResult;
    }

    private string NormalizeVirtualPath(string? virtualPath, string systemDirectory)
    {
        if (virtualPath.IsNullOrWhiteSpace())
        {
            return string.Empty;
        }

        systemDirectory = systemDirectory.TrimStart("~");
        systemDirectory = systemDirectory.Replace('\\', '/');
        virtualPath = virtualPath!.TrimStart("~");
        virtualPath = virtualPath.Replace('\\', '/');
        virtualPath = virtualPath.ReplaceFirst(systemDirectory, string.Empty);

        return virtualPath;
    }

    private string? EnsureCorrectFileExtension(string? value, string extension)
    {
        if (value?.EndsWith(extension) == false)
        {
            value += extension;
        }

        return value;
    }

    private bool IsDirectory(string path)
    {
        var dirInfo = new DirectoryInfo(path);

        // If you turn off indexing in Windows this will have the attribute:
        // `FileAttributes.Directory | FileAttributes.NotContentIndexed`
        return (dirInfo.Attributes & FileAttributes.Directory) != 0;
    }

    // this is an internal class for passing stylesheet data from the client to the controller while editing
    public class StylesheetData
    {
        public string? Content { get; set; }

        public StylesheetRule[]? Rules { get; set; }
    }
}


text:
namespace System.Xml.Serialization
{
    /// <summary>
    /// When applied to a type, stores the name of a static method of the type that returns an XML schema and a XmlQualifiedName
    /// (or XmlSchemaType for anonymous types) that controls the serialization of the type.
    /// </summary>
    [AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Struct|AttributeTargets.Interface)]
    public class XmlSchemaProviderAttribute : Attribute
    {
        private string elementName;

        /// <summary>
        /// Method name ctor
        /// </summary>
        public XmlSchemaProviderAttribute(string elementName)
        {
            this.elementName = elementName;
        }

        /// <summary>
        /// Gets/sets whether the target class is a wildcard, or that the schema for the class has contains only an xs:any element.
        /// </summary>
        public bool IsAny { get; set; }

        /// <summary>
        /// Gets the name of the static method that supplies the type's XML schema and the name of its XML Schema data type.
        /// </summary>
        public string MethodName
        {
            get { return elementName ?? string.Empty; }
            set { elementName = value; }
        }
    }
}


text:
//
// Copyright (C) 2011-14 Mark Wiebe, DyND Developers
// BSD 2-Clause License, see LICENSE.txt
//
// This header defines some functions to
// interoperate with numpy
//

#ifndef _DYND__NUMPY_INTEROP_HPP_
#define _DYND__NUMPY_INTEROP_HPP_

#include <Python.h>

// Define this to 1 or 0 depending on whether numpy interop
// should be compiled in.
#define DYND_NUMPY_INTEROP 1

// Only expose the things in this header when numpy interop is enabled
#if DYND_NUMPY_INTEROP

#include <numpy/numpyconfig.h>

// Don't use the deprecated Numpy functions
#ifdef NPY_1_7_API_VERSION
# define NPY_NO_DEPRECATED_API 8 // NPY_1_7_API_VERSION
#else
# define NPY_ARRAY_NOTSWAPPED   NPY_NOTSWAPPED
# define NPY_ARRAY_ALIGNED      NPY_ALIGNED
# define NPY_ARRAY_WRITEABLE    NPY_WRITEABLE
# define NPY_ARRAY_UPDATEIFCOPY NPY_UPDATEIFCOPY
#endif

#define PY_ARRAY_UNIQUE_SYMBOL pydynd_ARRAY_API
#define PY_UFUNC_UNIQUE_SYMBOL pydynd_UFUNC_API
// Invert the importing signal to match how numpy wants it
#ifndef NUMPY_IMPORT_ARRAY
# define NO_IMPORT_ARRAY
# define NO_IMPORT_UFUNC
#endif

#include <sstream>

#include <dynd/type.hpp>
#include <dynd/array.hpp>

#include <numpy/ndarrayobject.h>
#include <numpy/ufuncobject.h>

#ifndef NPY_DATETIME_NAT
#define NPY_DATETIME_NAT NPY_MIN_INT64
#endif
#ifndef NPY_ARRAY_WRITEABLE
#define NPY_ARRAY_WRITEABLE NPY_WRITEABLE
#endif
#ifndef NPY_ARRAY_ALIGNED
#define NPY_ARRAY_ALIGNED NPY_ALIGNED
#endif

namespace pydynd {

inline int import_numpy()
{
#ifdef NUMPY_IMPORT_ARRAY
    import_array1(-1);
    import_umath1(-1);
#endif

    return 0;
}

/**
 * Converts a numpy dtype to a dynd type. Use the data_alignment
 * parameter to get accurate alignment, as Numpy may have misaligned data,
 * or may report a smaller alignment than is necessary based on the data.
 *
 * \param d  The numpy dtype to convert.
 * \param data_alignment  If associated with particular data, the actual
 *                        alignment of that data. The default of zero
 *                        causes it to use Numpy's data alignment.
 *
 * \returns  The dynd equivalent of the numpy dtype.
 */
dynd::ndt::type ndt_type_from_numpy_dtype(PyArray_Descr *d, size_t data_alignment = 0);

/**
 * Converts a numpy type number to a dynd type. This produces an
 * aligned output type.
 *
 * \param numpy_type_num  The numpy type number.
 *
 * \returns  The dynd equivalent of the numpy dtype.
 */
dynd::ndt::type ndt_type_from_numpy_type_num(int numpy_type_num);

/**
 * When the function ndt_type_from_numpy_dtype returns a type which requires
 * additional arrmeta to be filled in, this function should be called to populate
 * that arrmeta in a created nd::array.
 *
 * \param dt  The dynd type returned by ndt_type_from_numpy_dtype.
 * \param d  The numpy dtype passed to ndt_type_from_numpy_dtype.
 * \param arrmeta  A pointer to the arrmeta to populate.
 */
void fill_arrmeta_from_numpy_dtype(const dynd::ndt::type& tp, PyArray_Descr *d, char *arrmeta);

/**
 * Converts a dynd type to a numpy dtype.
 *
 * \param dt  The dynd type to convert.
 */
PyArray_Descr *numpy_dtype_from_ndt_type(const dynd::ndt::type& tp);

/** Small helper for cython parameter */
inline PyObject *numpy_dtype_obj_from_ndt_type(const dynd::ndt::type& tp)
{
    return (PyObject *)numpy_dtype_from_ndt_type(tp);
}

/**
 * Converts a dynd type to a numpy dtype, also supporting types which
 * rely on their arrmeta for field offset information.
 *
 * \param dt  The dynd type to convert.
 * \param arrmeta  The arrmeta for the dynd type.
 */
PyArray_Descr *numpy_dtype_from_ndt_type(const dynd::ndt::type& tp, const char *arrmeta);

/**
 * Converts a pytypeobject for a n`umpy scalar
 * into a dynd type.
 *
 * Returns 0 on success, -1 if it didn't match.
 */
int ndt_type_from_numpy_scalar_typeobject(PyTypeObject* obj, dynd::ndt::type& out_tp);

/**
 * Gets the dynd type of a numpy scalar object
 */
dynd::ndt::type ndt_type_of_numpy_scalar(PyObject* obj);

/**
 * Views or copies a numpy PyArrayObject as an nd::array.
 *
 * \param obj  The numpy array object.
 * \param access_flags  The requested access flags (0 for default).
 * \param always_copy  If true, produce a copy instead of a view.
 */
dynd::nd::array array_from_numpy_array(PyArrayObject* obj, uint32_t access_flags, bool always_copy);

/**
 * Creates a dynd::nd::array from a numpy scalar. This always produces
 * a copy.
 *
 * \param obj  The numpy scalar object.
 * \param access_flags  The requested access flags (0 for default).
 */
dynd::nd::array array_from_numpy_scalar(PyObject* obj, uint32_t access_flags);

/**
 * Returns the numpy kind ('i', 'f', etc) of the array.
 */
char numpy_kindchar_of(const dynd::ndt::type& tp);

} // namespace pydynd

#endif // DYND_NUMPY_INTEROP

// Make a no-op import_numpy for Cython to call,
// so it doesn't need to know about DYND_NUMPY_INTEROP
#if !DYND_NUMPY_INTEROP
namespace pydynd {

inline int import_numpy()
{
    return 0;
}

// If we're not building against Numpy, define our
// own version of this struct to use.
typedef struct {
    int two;              /*
                           * contains the integer 2 as a sanity
                           * check
                           */

    int nd;               /* number of dimensions */

    char typekind;        /*
                           * kind in array --- character code of
                           * typestr
                           */

    int element_size;         /* size of each element */

    int flags;            /*
                           * how should be data interpreted. Valid
                           * flags are CONTIGUOUS (1), F_CONTIGUOUS (2),
                           * ALIGNED (0x100), NOTSWAPPED (0x200), and
                           * WRITEABLE (0x400).  ARR_HAS_DESCR (0x800)
                           * states that arrdescr field is present in
                           * structure
                           */

    npy_intp *shape;       /*
                            * A length-nd array of shape
                            * information
                            */

    npy_intp *strides;    /* A length-nd array of stride information */

    void *data;           /* A pointer to the first element of the array */

    PyObject *descr;      /*
                           * A list of fields or NULL (ignored if flags
                           * does not have ARR_HAS_DESCR flag set)
                           */
} PyArrayInterface;

} // namespace pydynd
#endif // !DYND_NUMPY_INTEROP

#endif // _DYND__NUMPY_INTEROP_HPP_


text:
package io.github.dagezi.gradle_android_9patch_plugin;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        TextView textView = (TextView) findViewById(R.id.text_200x100);

        textView.setText(String.format("dpi:%1.2f, L:%d R:%d T:%d B:%d",
                getResources().getDisplayMetrics().density,
                textView.getPaddingLeft(),
                textView.getPaddingRight(),
                textView.getPaddingTop(),
                textView.getPaddingBottom()));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


text:
import React from 'react'
import {Link} from 'react-router'
import {Source} from '../model/source'
import {findChange, emptyChange, diffImport, diffChapter, changeUrl, FieldChange, diffChapters, ChapterDiff, emptyChapterDiff} from '../model/change'
import {Chapter, contentText, chapterContentURL, emptyChapter, urlPath} from '../model/chapter'
import {FormSection} from '../comp'
import {diffBasic} from '../model/change'
import {toDateString} from '../helpers'
import {displayIf, Colors} from '../style'
import {assign} from 'lodash'
import {Routes} from '../router'

// render the source form
export class SourceChange extends React.Component {

  // load the change, then load the change it is based on

  static load(params) {
    var fc = findChange(params.id)

    return {
      change: fc,
      base: fc.then(function(c) {
        if (c.baseId) {
          return findChange(c.baseId)
        }
        else {
          return c
        }
      })
    }
  }

  render():React.Element {

    if (!this.props.change || !this.props.base) {
      return

    }

    var change = this.props.change
    var base = this.props.base
    var user = change.createdBy

    var dBasic = diffBasic(base.source, change.source)
    var dImport = diffImport(base.source.importSettings, change.source.importSettings)
    var dChapters = diffChapters(base.source.chapters, change.source.chapters)

    var label = {
      fontWeight: 'bold'
    }

    var row = {
      marginBottom: 15
    }

    return

Change: <Link to={Routes.source} params={change.source}>{change.source.name}</Link>

          <ChangeHeader change={base}>Old</ChangeHeader>
          <ChangeInfo change={base}/>

          <ChangeHeader change={change}>New</ChangeHeader>
          <ChangeInfo change={change}/>

          <ChangeArrow />

Book Settings

        {dBasic.map(this.renderChange.bind(this))}

Scan Settings

        {dImport.map(this.renderChange.bind(this))}

Chapters

        {dChapters.map(this.renderChapterChange.bind(this))}

  }

  renderChange(change:FieldChange):React.Element {
    return <FieldChangeView key={change.field} change={change} />
  }

  renderChapterChange(change:FieldChange):React.Element {
    // it already works, but it doesn't show when they've been moved
    // if it has been deleted, show it

    var chapter:ChapterDiff = change.newValue || change.oldValue || emptyChapterDiff()
    var from:ChapterDiff = change.oldValue || emptyChapterDiff()
    var to:ChapterDiff = change.newValue || emptyChapterDiff()

    function title(d:ChapterDiff) {
      return {'(' + d.index + ')'} {hidden(d)} {d.text}
    }

    function hidden(d:ChapterDiff) {
      if (d.hidden) return
      return
    }

    return

        <ChangeBox title={title(from)}>

{urlPath(from.url || "")}

        </ChangeBox>

        <ChangeBox title={title(to)} change={change.change}>

{urlPath(to.url || "")}

          <ChangeArrow />
        </ChangeBox>

  }
}

class ChangeArrow extends React.Component {

  render():React.Element {
    return

  }
}

var ChangeHeaderStyle = {
  borderBottom: 'solid 1px ' + Colors.dark,
  fontWeight: 'bold',
  padding: 10,
  paddingBottom: 0,
  paddingTop: 5,
  color: Colors.dark,
  background: Colors.light,
  marginBottom: 10
}

export class ChangeHeader extends React.Component {
  render():React.Element {
    var change = this.props.change
    return

{this.props.children}

  }
}

export class ChangeInfo extends React.Component {
  render():React.Element {
    var change = this.props.change
    return

      <Link to={Routes.change} params={change}>
        {toDateString(change.createdAt)} by {change.createdBy.firstName} {change.createdBy.lastName}
      </Link>

  }
}

export class FieldChangeView extends React.Component  {

  props: {
    change:FieldChange;
  };

  render():React.Element {
    var change = this.props.change || {}

    return

          <ChangeBox title={change.field}>
            {change.oldValue}
          </ChangeBox>

          <ChangeBox title={change.field} change={change.change}>
            {change.newValue}
            <ChangeArrow />
          </ChangeBox>

  }
}

class ChangeBox extends React.Component {

  render():React.Element {

    var change = this.props.change

    var fieldStyle = {
      fontWeight: 'bold',
      display: 'inline',
      marginRight: 10,
      fontSize: 12,
    }

    var valueStyle = {
      display: 'inline-block'
    }

    var style = {
      fontSize: 12,
      background: Colors.code,
      border: 'solid 1px ' + Colors.codeTone,
      marginTop: 4,
      padding: 8,
      fontFamily: ['Consolas', "Liberation Mono", 'Menlo', 'Courier', 'monospace']
    }

    var newStyle = assign({}, style)

    if (change === "deleted") {
      newStyle.backgroundColor = Colors.diffRemove
    }

    else if (change === "new") {
      newStyle.backgroundColor = Colors.diffAdd
    }

    else if (change === "updated") {
      newStyle.backgroundColor = Colors.paper
    }

    else if (change === "unchanged") {
      newStyle.display = "none"
    }

    return

      {this.props.title}
      {this.props.children}

  }
}


text:
<%#
 Copyright 2013-2017 the original author or authors from the StackStack project.

 This file is part of the StackStack project, see http://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
package <%=packageName%>.config;

import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * Properties specific to StackStack.
 * <p>
 * Properties are configured in the application.yml file.
 */
@ConfigurationProperties(prefix = "application", ignoreUnknownFields = false)
public class ApplicationProperties {

}


text:
[Yesterday I said](http://www.yesodweb.com/blog/2013/12/book-updates-1-2) that
the Yesod book was almost fully updated for version 1.2, and that I'd let
everyone know when it was completely updated. Turns out that the last chapter
took far less time to update than I'd expected. So I'm happy to announce that
the Yesod book is now fully revised and up-to-date with version 1.2 of Yesod.
The final chapter [on using
Sphinx](http://www.yesodweb.com/book/case-study-sphinx) is now available, and
benefitted greatly from the simplified streaming data primitives introduced in
Yesod 1.2.


text:
Assignment for Code 201 to create a personal page with a guessing game.

I like popsicles. And dogs. And bacon. And I can/will eat Mexican food every day.

THE NWS WILL STOP SCREAMING


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Symb. bot. upsal. 25(no. 1): 21 (1985)

#### Original name
Pirottaea saxonica Nannf.

### Remarks
null


text:
/*! \file
 *
 * \brief The rd_rng random number generator, based on: P L'Ecuyer,
 * F Panneton, and M Matsumoto. Improved Long-Period Generators Based on Linear
 * Recurrences Modulo 2.
 */

#ifndef RD_RNG_H_
#define RD_RNG_H_

#include <stdbool.h>
#include <stdint.h>

#include "common.h"

#ifdef __cplusplus
extern "C" {
#endif

    /**
     * \brief The state of a rd_rng random number generator.
     */
    typedef struct {
        /**
         * \brief Internal state of the generator.
         */
        uint32_t state[32];
        /**
         * \brief Internal state of the generator.
         */
        uint32_t state_n;
        /**
         * \brief The initial seed used to initiate the generator.
         */
        uint32_t seed;
        /**
         * \brief Has a next double.
         */
        bool has_next;
        /**
         * \brief Next double.
         */
        double next_normal;
    } rd_rng;

    /**
     * \brief Julienne Walker's portable function (from www.eternallyconfuzzled.com)
     * to get an uint32_t from time().
     *
     * Warning: on most systems it will return the same value if called twice within
     * one second.
     *
     * \return          An uint32_teger derived from time().
     */
    uint32_t rd_time_seed();

    /**
     * \brief Seed a rd_rng generator with an uint32_teger.
     *
     * \param rng       The generator.
     * \param seed      The seed used to initialize the generator.
     * \return          Returns the seed used.
     */
    uint32_t rd_rng_init(rd_rng *r, uint32_t seed);

    /**
     * \brief Initialize with time using time_seed().
     *
     * \param rng       The generator.
     * \return          The seed used.
     */
    uint32_t rd_rng_init_time(rd_rng *r);

    /**
     * \brief Return a double in the [0, 1) uniform range.
     *
     * \param rng       The generator.
     * \return          A random value in the [0, 1) uniform range.
     */
    double rd_rng_double(rd_rng *r);

    /**
     * \brief Returns a number in the [0, 4294967296] range.
     *
     * \param rng       The generator.
     * \return          A random value in the [0, 4294967296] uniform range.
     */
    uint32_t rd_rng_uint(rd_rng *r);

    /**
     * \brief Return an integer in the [0, b) uniform range (including 0, excluding
     * b).
     *
     * Bechmarks show ~5% performane improvement over a normal function, which
     * is enough to justify the define for such procedure.
     *
     * \param rng       The generator.
     * \param b         Upper limit: the highest possible value is b - 1.
     * \return          A random interger in the [0, b) uniform range.
     */
#define rd_rng_intb(r, b) ((int)(rd_rng_double(r) * (b)))

    /**
     * \brief Return an uint32_teger in the [0, b) uniform range (including 0,
     * excluding b).
     *
     * \param rng       The generator.
     * \param b         Upper limit: the highest possible value is b - 1.
     * \return          A random interger in the [0, b) uniform range.
     */
#define rd_rng_uintb(r, b) ((uint32_t)(rd_rng_double(r) * (b)))

    /**
     * \brief Return a double from the normal distribution.
     *
     * \param rng       The generator.
     * \return          An exponential random variable.
     */
    double rd_rng_normal(rd_rng *r);

    /**
     * \brief Returns a double from the exponential distribution (between 0 and 1).
     *
     * \param rng       The generator.
     * \return          An exponential random variable.
     */
    double rd_rng_exp(rd_rng *r);

    /**
     * \brief Returns an integer from a poisson distribution given lambda.
     *
     * \param rng       The generator.
     * \param lambda    The lambda parameter of the poisson distribution.
     * \return          A number in the poisson distribution.
     */
    int rd_rng_poisson(rd_rng *r, double lambda);

    /**
     * \brief Allocates a random block of memory.
     *
     * \param r         The generator.
     * \param size      Number of bytes to allocate.
     * \return          The address of the block of memory.
     */
    void * rd_randalloc(rd_rng *r, size_t size);

#ifdef __cplusplus
}
#endif

#endif


text:
namespace EstateSocialSystem.Web.Models
{
    using System.Collections.Generic;

    public class EstatePersonalListViewModel
    {
        public int CurrentPage { get; set; }

        public int TotalPages { get; set; }

        public IEnumerable<EstatePersonalViewModel> Estates { get; set; }
    }
}