text:
package org.metacsp.multi.spatial.DE9IM;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.logging.Logger;

import org.metacsp.framework.Constraint;
import org.metacsp.framework.ConstraintNetwork;
import org.metacsp.framework.ConstraintSolver;
import org.metacsp.framework.Variable;
import org.metacsp.multi.spatial.DE9IM.DE9IMRelation.Type;
import org.metacsp.utility.logging.MetaCSPLogging;

/**
 * A solver for constraint networks of {@link DE9IMRelation}s. This solver handles variables of type {@link GeometricShapeVariable}, which represent
 * points, line strings, or polygons. The latter are not necessarily convex.
 *
 * @author Federico Pecora
 *
 */
public class DE9IMRelationSolver extends ConstraintSolver {

	protected Constraint[] addedConstraints = null;
	protected boolean removedConstraints = false;
	protected boolean addedVariables = false;
	protected boolean removedVariables = false;

	protected DE9IMRelationSolver(Class<?>[] constraintTypes, Class<?> variableType) {
		super(constraintTypes, variableType);
	}

	/**
	 * Creates a new solver for {@link DE9IMRelation}s.
	 */
	public DE9IMRelationSolver() {
		super(new Class<?>[] {DE9IMRelation.class}, GeometricShapeVariable.class);
		this.setOptions(OPTIONS.DOMAINS_AUTO_INSTANTIATED, OPTIONS.AUTO_PROPAGATE);
	}

	private static final long serialVersionUID = 2872228080625654304L;

	/**
	 * Get all the implicit {@link DE9IMRelation}s that exist among the variables in this solver's {@link ConstraintNetwork}.
	 * @return All the implicit {@link DE9IMRelation}s that exist among the variables in this solver's {@link ConstraintNetwork}.
	 */
	public Constraint[] getAllImplicitRelations() {
		return this.getAllImplicitRelations(false);
	}

	/**
	 * Get all the implicit {@link DE9IMRelation}s that exist among the variables in this solver's {@link ConstraintNetwork}. These
	 * are limited to the eight Jointly Exclusive, Pairwise Disjoint relations

	 *

	 *
Contains

	 *
Within

	 *
Covers

	 *
CoveredBy

	 *
Disjoint

	 *
Overlaps

	 *
Touches

	 *
Equals

	 *

	 * These eight relations are equivalent to te basic RCC8 relations (Cohn et al., 1997).
	 * @return All the implicit {@link DE9IMRelation}s that are also RCC8 relations existing among the variables in this solver's {@link ConstraintNetwork}.
	 */
	public Constraint[] getAllImplicitRCC8Relations() {
		return this.getAllImplicitRelations(true);
	}

	private Constraint[] getAllImplicitRelations(boolean rcc8relations) {
		ArrayList<Constraint> cons = new ArrayList<Constraint>();
		Variable[] vars = this.getVariables();
		for (int i = 0; i < vars.length; i++) {
			GeometricShapeVariable g1 = (GeometricShapeVariable)vars[i];
			for (int j = 0; j < vars.length; j++) {
				if (i != j) {
					GeometricShapeVariable g2 = (GeometricShapeVariable)vars[j];
					Type[] rels = null;
					if (!rcc8relations) rels = DE9IMRelation.getRelations(g1, g2);
					else rels = DE9IMRelation.getRCC8Relations(g1, g2);
					DE9IMRelation con = new DE9IMRelation(rels);
					con.setFrom(g1);
					con.setTo(g2);
					cons.add(con);
				}
			}
		}
		return cons.toArray(new Constraint[cons.size()]);
	}

	@Override
	public boolean propagate() {
		if (addedConstraints != null) {
			for (Constraint con : addedConstraints) {
				if (con instanceof DE9IMRelation) {
					if (!propagateEdge((DE9IMRelation)con)) return false;
				}
			}
			addedConstraints = null;
			return true;
		}
		if (removedConstraints) {
			logger.fine("Propagation skipped because only removing constriants");
			removedConstraints = false;
			return true;
		}
		if (addedVariables) {
			logger.fine("Propagation skipped because only adding variables");
			addedVariables = false;
			return true;
		}
		if (removedVariables) {
			logger.fine("Propagation skipped because only removing variables");
			removedVariables = false;
			return true;
		}
		return propagateFull();
	}

	private boolean propagateEdge(DE9IMRelation con) {
		logger.fine("Edge propagation performed");
		GeometricShapeVariable g1 = (GeometricShapeVariable)con.getFrom();
		GeometricShapeVariable g2 = (GeometricShapeVariable)con.getTo();
		//Are explicit (given) relations compatible with implicit ones?
		Type[] implicitRelsA = DE9IMRelation.getRelations(g1, g2);
		HashSet<Type> implicitRels = new HashSet<Type>();
		for (Type t : implicitRelsA) implicitRels.add(t);
			for (Type t : con.getTypes()) {
			//System.out.println(implicitRels + " contains " + t + "?");
			if (!implicitRels.contains(t)) {
				//System.out.println("... no!");
				return false;
			}
		}
		//... yes!
		return true;
	}

	private boolean propagateFull() {
		logger.fine("Full propagation performed");
		Variable[] vars = this.getVariables();
		for (int i = 0; i < vars.length; i++) {
			GeometricShapeVariable g1 = (GeometricShapeVariable)vars[i];
			for (int j = 0; j < vars.length; j++) {
				if (i != j) {
					GeometricShapeVariable g2 = (GeometricShapeVariable)vars[j];
					//Are explicit (given) relations compatible with implicit ones?
					Type[] implicitRelsA = DE9IMRelation.getRelations(g1, g2);
					HashSet<Type> implicitRels = new HashSet<Type>();
					for (Type t : implicitRelsA) implicitRels.add(t);
					Constraint[] cons = this.getConstraints(g1, g2);
					for (Constraint c : cons) {
						for (Type t : ((DE9IMRelation)c).getTypes()) {
							//System.out.println(implicitRels + " contains " + t + "?");
							if (!implicitRels.contains(t)) {
								//System.out.println("... no!");
								return false;
							}
						}
					}
					//... yes!
				}
			}
		}
		return true;
	}

	private boolean propagateRCC8() {
		Variable[] vars = this.getVariables();
		for (int i = 0; i < vars.length; i++) {
			GeometricShapeVariable g1 = (GeometricShapeVariable)vars[i];
			for (int j = 0; j < vars.length; j++) {
				if (i != j) {
					GeometricShapeVariable g2 = (GeometricShapeVariable)vars[j];
					//Are explicit (given, RCC8) relations compatible with implicit ones?
					Type[] implicitRelsA = DE9IMRelation.getRCC8Relations(g1, g2);
					HashSet<Type> implicitRels = new HashSet<Type>();
					for (Type t : implicitRelsA) implicitRels.add(t);
					Constraint[] cons = this.getConstraints(g1, g2);
					for (Constraint c : cons) {
						for (Type t : ((DE9IMRelation)c).getTypes()) {
							if (!DE9IMRelation.isRCC8Relation(t)) {
								//System.out.println(t + " is not RCC8, skipping...");
								continue;
							}
							//System.out.println(implicitRels + " contains " + t + "?");
							if (!implicitRels.contains(t)) {
								//System.out.println("... no!");
								return false;
							}
						}
					}
					//... yes!
				}
			}
		}
		return true;
	}

	@Override
	protected boolean addConstraintsSub(Constraint[] c) {
		addedConstraints = c;
		return true;
	}

	@Override
	protected void removeConstraintsSub(Constraint[] c) {
		removedConstraints = true;
	}

	@Override
	protected Variable[] createVariablesSub(int num) {
		addedVariables = true;
		Variable[] ret = new Variable[num];
		for (int i = 0; i < num; i++) {
			ret[i] = new GeometricShapeVariable(this, IDs++);
		}
		return ret;
	}

	@Override
	protected void removeVariablesSub(Variable[] v) {
		removedVariables = true;
	}

	@Override
	public void registerValueChoiceFunctions() {
		// TODO Auto-generated method stub
	}

}


text:
package com.themodernway.server.core.io;

import java.io.Writer;
import java.nio.charset.Charset;

public class WriterProxyOutputStream extends AbstractWriterProxyOutputStream<WriterProxyOutputStream>
{
    public WriterProxyOutputStream(final Writer writer)
    {
        super(writer, IO.UTF_8_CHARSET);
    }

    public WriterProxyOutputStream(final Writer writer, final Charset charset)
    {
        super(writer, charset);
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
using InternalRealtimeCSG;
using RealtimeCSG.Helpers;

namespace RealtimeCSG
{
	[System.Reflection.Obfuscation(Exclude = true)]
	internal sealed class CSGBrushEditorManager : ScriptableObject
	{
		static CSGBrushEditorManager instance = null;

//		[NonSerialized ] bool				isEnabled				= false;
		[NonSerialized ] bool				generateMode			= false;
		[NonSerialized ] FilteredSelection	filteredSelection = new FilteredSelection();

		[SerializeField] ToolEditMode		editMode				= ToolEditMode.Object;
//		[SerializeField] ToolEditMode		prevUsedEditMode		= ToolEditMode.Object;
		[SerializeField] IBrushTool			activeTool				= null;

		static IBrushTool[]					brushTools              = null;

		public static FilteredSelection	FilteredSelection	{ get { InitTools(); return instance.filteredSelection; } }
		public static IBrushTool		ActiveTool			{ get { InitTools(); return instance.activeTool; } }

		public static ToolEditMode EditMode
		{
			get
			{
				InitTools();
				return instance.editMode;
			}
			set
			{
				if (instance.editMode == value)
					return;

				Undo.RecordObject(instance, "Changed edit mode");

				instance.editMode = value;
				instance.generateMode = false;

				RealtimeCSG.CSGSettings.EditMode = instance.editMode;
				RealtimeCSG.CSGSettings.Save();

				if (ActiveTool != null)
					SceneView.RepaintAll();
			}
		}

		static public IBrushTool CurrentTool
		{
			get
			{
				InitTools();

				if (instance.generateMode)
					return brushTools[(int)ToolEditMode.Generate] as GenerateBrushTool;

				var editMode = instance.editMode;
				if (editMode < firstEditMode ||
					editMode > lastEditModes)
					return brushTools[0];

				return brushTools[(int)editMode];
			}
		}

		static ToolEditMode firstEditMode;
		static ToolEditMode lastEditModes;

		const HideFlags scriptableObjectHideflags = HideFlags.DontSaveInBuild | HideFlags.DontSaveInEditor | HideFlags.NotEditable | HideFlags.HideInHierarchy;

		static void InitTools()
		{
			if (instance)
				return;

			var values = Enum.GetValues(typeof(ToolEditMode)).Cast<ToolEditMode>().ToList();
			values.Sort();
			firstEditMode = values[0];
			lastEditModes = values[values.Count - 1];

			Undo.undoRedoPerformed -= UndoRedoPerformed;
			Undo.undoRedoPerformed += UndoRedoPerformed;

			EditorApplication.modifierKeysChanged -= OnModifierKeysChanged;
			EditorApplication.modifierKeysChanged += OnModifierKeysChanged;

			var managers = FindObjectsOfType<CSGBrushEditorManager>().ToArray();
			for (int i = 0; i < managers.Length; i++)
				DestroyImmediate(managers[i]);
			instance = ScriptableObject.CreateInstance<CSGBrushEditorManager>();
			instance.hideFlags = scriptableObjectHideflags;

			var types = new Type[]
			{
				typeof(ObjectEditBrushTool),
				typeof(GenerateBrushTool),
				typeof(MeshEditBrushTool),
				typeof(ClipBrushTool),
				typeof(SurfaceEditBrushTool)
			};
			if (types.Length != values.Count)
			{
				Debug.Log("types.Length != values.Count");
			}

			brushTools = new IBrushTool[values.Count];
			for (int j = 0; j < types.Length; j++)
			{
				var objects = FindObjectsOfType(types[j]).ToArray();
				for (int i = 0; i < objects.Length; i++)
					DestroyImmediate(objects[i]);

				var obj = ScriptableObject.CreateInstance(types[j]);
				brushTools[j] = obj as IBrushTool;
				if (brushTools[j] == null)
				{
					Debug.Log("brushTools[j] == null");
					continue;
				}
				if (!(brushTools[j] is ScriptableObject))
				{
					Debug.Log("!(brushTools[j] is ScriptableObject)");
					continue;
				}
				obj.hideFlags = scriptableObjectHideflags;
			}

			GenerateBrushTool.ShapeCommitted -= OnShapeCommittedEvent;
			GenerateBrushTool.ShapeCommitted += OnShapeCommittedEvent;
			GenerateBrushTool.ShapeCancelled -= OnShapeCancelledEvent;
			GenerateBrushTool.ShapeCancelled += OnShapeCancelledEvent;

			RealtimeCSG.CSGSettings.Reload();
			instance.editMode = RealtimeCSG.CSGSettings.EditMode;
			InitTargets();
		}

		static HashSet<CSGNode>		selectedNodes = new HashSet<CSGNode>();
		static HashSet<Transform>	selectedOthers = new HashSet<Transform>();
		public static void UpdateSelection(bool forceUpdate = false)
		{
			InitTools();

			GetTargetSelection(ref selectedNodes, ref selectedOthers);

			//filteredSelection.Validate();
			if (!instance.filteredSelection.UpdateSelection(selectedNodes, selectedOthers) &&
				!forceUpdate)
			{
				return;
			}

			InternalCSGModelManager.skipRefresh = true;
			try
			{
				InternalCSGModelManager.Refresh();
			}
			finally
			{
				InternalCSGModelManager.skipRefresh = false;
			}

			//if (nodes.Count > 0)
			{/*
				if (!instance.isEnabled)
				{
					InitTargets();
					instance.isEnabled = true;
				}*/

				foreach (var tool in brushTools)
					tool.SetTargets(instance.filteredSelection);
			} /*else
			if (isEnabled)
			{
				CleanupTargets();
				activeTool		= null;
				isEnabled		= false;
			}*/
		}

		public static void ResetMessage()
		{
			if (SceneView.lastActiveSceneView     != null) { SceneView.lastActiveSceneView.RemoveNotification(); return; }
			if (SceneView.currentDrawingSceneView != null) { SceneView.lastActiveSceneView.RemoveNotification(); return; }
		}

		public static void ShowMessage(string message)
		{
			if (string.IsNullOrEmpty(message))
				return;

			if (SceneView.lastActiveSceneView     != null) { SceneView.lastActiveSceneView.ShowNotification(new GUIContent(message)); return; }
			if (SceneView.currentDrawingSceneView != null) { SceneView.lastActiveSceneView.ShowNotification(new GUIContent(message)); return; }
			Debug.LogWarning(message);
		}

		static void OnEnableTool(IBrushTool tool)
		{
			if (tool != null)
				tool.OnEnableTool();
		}

		static void OnDisableTool(IBrushTool tool)
		{
			if (tool != null)
				tool.OnDisableTool();
		}

		public static bool DeselectAll()
		{
			if (instance.activeTool != null &&
				instance.activeTool.DeselectAll())
				return true;
			return false;
		}

		static void UndoRedoPerformed()
		{
			if (instance.activeTool != null)
			{
				instance.activeTool.UndoRedoPerformed();
			}

			InternalCSGModelManager.UpdateMaterialRegistration();

			CSGBrushEditorManager.UpdateSelection(forceUpdate: true);
		}

		static void OnModifierKeysChanged()
		{
			SceneView.RepaintAll();
		}

		static bool GetTargetSelection(ref HashSet<CSGNode> nodes, ref HashSet<Transform> others)
		{
			selectedNodes.Clear();
			selectedOthers.Clear();

			if (Selection.gameObjects == null)
				return false;

			foreach (var gameObject in Selection.gameObjects)
			{
				if (!gameObject)
					continue;
				var node = gameObject.GetComponent<CSGNode>();
				if (node && node.enabled && (node.hideFlags & HideFlags.HideInInspector) == HideFlags.None)
					nodes.Add(node);
				else
					others.Add(gameObject.transform);
			}
			return true;
		}

		static void InitTargets()
		{
			var newTool = CurrentTool;
			if (newTool == instance.activeTool)
			{
				if (instance.filteredSelection.NodeTargets != null &&
					instance.filteredSelection.NodeTargets.Length > 0)
					OnEnableTool(instance.activeTool);
				else
					OnDisableTool(instance.activeTool);
			} else
			{
				UpdateTool();
			}
		}

		static void CleanupTargets()
		{
			InitTools();

			var newTool = CurrentTool;
			if (newTool == instance.activeTool)
			{
				if (instance.activeTool != null)
				{
					if (instance.filteredSelection.NodeTargets != null &&
						instance.filteredSelection.NodeTargets.Length > 0)
						OnDisableTool(instance.activeTool);
				}
			} else
			{
				UpdateTool();
			}

			if (newTool == null)
			{
				Tools.hidden = false;
			}
		}

		static void NextEditMode()
		{
			InitTools();
			if (instance.editMode == lastEditModes)
			{
				EditMode = firstEditMode;
			} else
			{
				EditMode = (ToolEditMode)(instance.editMode + 1);
			}
		}

		static void PrevEditMode()
		{
			InitTools();
			if (instance.editMode == firstEditMode)
			{
				EditMode = lastEditModes;
			} else
			{
				EditMode = (ToolEditMode)(instance.editMode - 1);
			}
		}

		static void UpdateTool()
		{
			if (!RealtimeCSG.CSGSettings.EnableRealtimeCSG)
				return;

			var newTool = CurrentTool;
			if (instance.activeTool != newTool)
			{
				if (instance.activeTool != null)
					OnDisableTool(instance.activeTool);

				instance.activeTool		= newTool;

				if (newTool != null)
					OnEnableTool(newTool);
			}
		}

		static void FinishShapeBuilder()
		{
			Tools.hidden = false;
			//filteredSelection.Validate();
			//SceneView.RepaintAll();
		}

		public static Vector3 SnapPointToGrid(Vector3 point, CSGPlane plane, ref List<Vector3> snappingEdges, out CSGBrush snappedOnBrush, CSGBrush[] ignoreBrushes, bool ignoreAllBrushes = false)
		{
			snappedOnBrush = null;
			var toggleSnapping	= SelectionUtility.IsSnappingToggled;
			var doSnapping		= RealtimeCSG.CSGSettings.SnapToGrid ^ toggleSnapping;

			var snappedPoint = point;
			if (doSnapping)
			{
				snappedPoint = snappedPoint + Grid.ForceSnapDeltaToGrid(MathConstants.zeroVector3, snappedPoint);
				snappedPoint = Grid.PointFromGridSpace(Grid.CubeProject(Grid.PlaneToGridSpace(plane), Grid.PointToGridSpace(snappedPoint)));

				// snap twice to get rid of some tiny movements caused by the projection in depth
				snappedPoint = snappedPoint + Grid.ForceSnapDeltaToGrid(MathConstants.zeroVector3, snappedPoint);
				snappedPoint = Grid.PointFromGridSpace(Grid.CubeProject(Grid.PlaneToGridSpace(plane), Grid.PointToGridSpace(snappedPoint)));
			} else
				snappedPoint = GeometryUtility.ProjectPointOnPlane(plane, snappedPoint);

			//GeometryUtility.ProjectPointOnPlane(plane, snappedPoint);
			if (doSnapping && !ignoreAllBrushes)
			{
				return GridUtility.SnapToWorld(plane, point, snappedPoint, ref snappingEdges, out snappedOnBrush, ignoreBrushes);
			}

			return snappedPoint;
		}

		public static Vector3 SnapPointToRay(Vector3 point, Ray ray, ref List<Vector3> snappingEdges, out CSGBrush snappedOnBrush)
		{
			snappedOnBrush = null;
			var toggleSnapping	= SelectionUtility.IsSnappingToggled;
			var doSnapping		= RealtimeCSG.CSGSettings.SnapToGrid ^ toggleSnapping;

			var snappedPoint = point;

			snappingEdges = null;
			if (doSnapping)
			{
				snappedPoint = snappedPoint + Grid.ForceSnapDeltaToRay(ray, MathConstants.zeroVector3, snappedPoint);
			}
			return snappedPoint;

		}

		static void OnShapeCancelledEvent()
		{
			if (!instance.generateMode)
				return;
			instance.generateMode = false;
			//EditMode = instance.prevUsedEditMode;
		}

		static void OnShapeCommittedEvent()
		{
			instance.generateMode = false;
			//EditMode = instance.prevUsedEditMode;
		}

		static bool HandleBuilderEvents()
        {
			if (RealtimeCSG.CSGSettings.EditMode != instance.editMode)
			{
				RealtimeCSG.CSGSettings.EditMode = instance.editMode;
				RealtimeCSG.CSGSettings.Save();
			}

			//if (GUIUtility.hotControl != 0)
			//	return false;

			switch (Event.current.type)
			{
				case EventType.KeyDown:
				{
					if (GUIUtility.hotControl == 0 &&
						Keys.FreeBuilderMode.IsKeyPressed() && !instance.generateMode)
					{
						var generateBrushTool = brushTools[(int)ToolEditMode.Generate] as GenerateBrushTool;
						generateBrushTool.BuilderMode = ShapeMode.FreeDraw;
//						instance.prevUsedEditMode = EditMode;
						instance.generateMode = true;
						Event.current.Use();
						return true;
					}
					if (Keys.CylinderBuilderMode.IsKeyPressed() && !instance.generateMode)
					{
						var generateBrushTool = brushTools[(int)ToolEditMode.Generate] as GenerateBrushTool;
						generateBrushTool.BuilderMode = ShapeMode.Cylinder;
//						instance.prevUsedEditMode = EditMode;
						instance.generateMode = true;
						Event.current.Use();
						return true;
					}
					if (Keys.BoxBuilderMode.IsKeyPressed() && !instance.generateMode)
					{
						var generateBrushTool = brushTools[(int)ToolEditMode.Generate] as GenerateBrushTool;
						generateBrushTool.BuilderMode = ShapeMode.Box;
//						instance.prevUsedEditMode = EditMode;
						instance.generateMode = true;
						Event.current.Use();
						return true;
					}
					if (Keys.SphereBuilderMode.IsKeyPressed() && !instance.generateMode)
					{
						var generateBrushTool = brushTools[(int)ToolEditMode.Generate] as GenerateBrushTool;
						generateBrushTool.BuilderMode = ShapeMode.Sphere;
//						instance.prevUsedEditMode = EditMode;
						instance.generateMode = true;
						Event.current.Use();
						return true;
					}
					else if (Keys.SwitchToObjectEditMode	.IsKeyPressed()) { Event.current.Use(); return true; }
					else if (Keys.SwitchToGenerateEditMode	.IsKeyPressed()) { Event.current.Use(); return true; }
					else if (Keys.SwitchToMeshEditMode		.IsKeyPressed()) { Event.current.Use(); return true; }
					else if (Keys.SwitchToClipEditMode		.IsKeyPressed()) { Event.current.Use(); return true; }
					else if (Keys.SwitchToSurfaceEditMode	.IsKeyPressed()) { Event.current.Use(); return true; }
					break;
				}
				case EventType.KeyUp:
				{
					if (instance.generateMode &&
						(Keys.FreeBuilderMode.IsKeyPressed() ||
						Keys.CylinderBuilderMode.IsKeyPressed() ||
						Keys.BoxBuilderMode.IsKeyPressed() ||
                        Keys.SphereBuilderMode.IsKeyPressed()))
					{
						Event.current.Use();
						var generateBrushTool = brushTools[(int)ToolEditMode.Generate] as GenerateBrushTool;
						if (!generateBrushTool.HotKeyReleased())
						{
							instance.generateMode = false;
						}
					}
					else if (Keys.SwitchToObjectEditMode	.IsKeyPressed()) { InitTools(); EditMode = ToolEditMode.Object; Event.current.Use(); return true; }
					else if (Keys.SwitchToGenerateEditMode	.IsKeyPressed()) { InitTools(); EditMode = ToolEditMode.Generate; Event.current.Use(); return true; }
					else if (Keys.SwitchToMeshEditMode		.IsKeyPressed()) { InitTools(); EditMode = ToolEditMode.Mesh; Event.current.Use(); return true; }
					else if (Keys.SwitchToClipEditMode		.IsKeyPressed()) { InitTools(); EditMode = ToolEditMode.Clip; Event.current.Use(); return true; }
					else if (Keys.SwitchToSurfaceEditMode	.IsKeyPressed()) { InitTools(); EditMode = ToolEditMode.Surfaces; Event.current.Use(); return true; }
					break;
				}
				case EventType.ValidateCommand:
				{
					if ((GUIUtility.hotControl == 0 && Keys.FreeBuilderMode  .IsKeyPressed()) ||
						Keys.CylinderBuilderMode.IsKeyPressed() ||
                        Keys.SphereBuilderMode.IsKeyPressed() ||
                        Keys.BoxBuilderMode.IsKeyPressed() ||
						Keys.SwitchToObjectEditMode.IsKeyPressed() ||
						Keys.SwitchToGenerateEditMode.IsKeyPressed() ||
						Keys.SwitchToMeshEditMode.IsKeyPressed() ||
						Keys.SwitchToClipEditMode.IsKeyPressed() ||
						Keys.SwitchToSurfaceEditMode.IsKeyPressed())
					{
						Event.current.Use();
						return true;
					}
					break;
				}
			}
            return false;
        }
		/*
		static bool HandleYMode()
        {
			switch (Event.current.type)
			{
				case EventType.KeyDown:
				{
					if (Keys.VerticalMoveMode.IsKeyPressed())
					{
						Grid.YMoveModeActive = true; Event.current.Use();
						return true;
					}
					break;
				}
				case EventType.KeyUp:
				{
					if (Keys.VerticalMoveMode.IsKeyPressed())
					{
						Grid.YMoveModeActive = false; Event.current.Use();
						return true;
					}
					break;
				}
				case EventType.ValidateCommand:
				{
					if (Keys.VerticalMoveMode.IsKeyPressed())
					{
						Event.current.Use();
						return true;
					}
					break;
				}
			}
            return false;
		}
		*/
		[NonSerialized] LineMeshManager zTestLineMeshManager	= new LineMeshManager();
		[NonSerialized] LineMeshManager noZTestLineMeshManager	= new LineMeshManager();

		void OnDestroy()
		{
			zTestLineMeshManager.Destroy();
			noZTestLineMeshManager.Destroy();
		}

		private static readonly int SceneWindowHash		= "SceneWindowHash".GetHashCode();
		//		private static readonly int BottomBarInputHash	= "BottomBarInputHash".GetHashCode();
		//private static bool holdingDownMouse = false;

		static List<CSGBrushEditorWindow>  currentEditorWindows = new List<CSGBrushEditorWindow>();

		public static bool InitSceneGUI(SceneView sceneView)
		{
			currentEditorWindows	= CSGBrushEditorWindow.GetEditorWindows();

			return (currentEditorWindows.Count == 0);
		}

		//void OnSceneGUI() <- paints -everything- again for every selected brush
		public static void OnSceneGUI(SceneView sceneView)
		{
			/*
			int prevHotControl		= GUIUtility.hotControl;
			int prevKeyboardControl = GUIUtility.keyboardControl;

			// make it impossible for the tool to click in the bottom bar area
			int bottomBarId	 = GUIUtility.GetControlID (BottomBarInputHash, FocusType.Passive);
			bool forceRevert = false;
			//if (GUIUtility.hotControl == 0)
			{
				var bottomBarRect = sceneView.position;
				var min = bottomBarRect.min;
				var max = bottomBarRect.max;

				min.y = max.y - (GUIStyleUtility.BottomToolBarHeight + 18);

				bottomBarRect.min = min;
				bottomBarRect.max = max;

				if (bottomBarRect.Contains(Event.current.mousePosition))
				{
					GUIUtility.hotControl	   = bottomBarId;
					GUIUtility.keyboardControl = bottomBarId;
					forceRevert = true;
				}
			}
			*/
			SelectionUtility.HandleEvents();
			InitTools();

			HandleBuilderEvents();
			//HandleYMode();
			{
				UpdateTool();

				if (instance.activeTool != null)
				{
					if (RealtimeCSG.CSGSettings.EnableRealtimeCSG)
					{
						// handle the tool
						var sceneSize = sceneView.position.size;
						var sceneRect = new Rect(0, 0, sceneSize.x, sceneSize.y - ((GUIStyleUtility.BottomToolBarHeight + 4) + 17));
						//var originalEventType = Event.current.type;
						//if (originalEventType == EventType.MouseMove ||
						//	originalEventType == EventType.MouseUp)
						//	holdingDownMouse = false;

						//var mousePos = Event.current.mousePosition;
						//if (originalEventType == EventType.Layout ||
						//	originalEventType == EventType.Repaint ||
						//	sceneRect.Contains(mousePos) ||
						//	holdingDownMouse)
							instance.activeTool.HandleEvents(sceneRect);

						//if (originalEventType == EventType.MouseDown ||
						//	originalEventType == EventType.MouseDrag)
						//	holdingDownMouse = true;
					} else
					{
						if (Event.current.type == EventType.repaint)
						{
							var brushes = instance.filteredSelection.BrushTargets;
							var wireframes = new List<GeometryWireframe>(brushes.Length);
							var translations = new List<Vector3>(brushes.Length);
							for (int i = 0; i < brushes.Length; i++)
							{
								var brush = brushes[i];
								if (!brush)
									continue;

								var brushCache = InternalCSGModelManager.GetBrushCache(brush);
								if (brushCache == null ||
									brushCache.childData == null ||
									!brushCache.childData.Model)
									continue;

								var brushTranslation = brushCache.compareTransformation.modelLocalPosition + brushCache.childData.ModelTransform.position;

								wireframes.Add(BrushOutlineManager.GetBrushOutline(brushes[i].brushID));
								translations.Add(brushTranslation);
							}
							if (wireframes.Count > 0)
							{
								CSGRenderer.DrawSelectedBrushes(instance.zTestLineMeshManager, instance.noZTestLineMeshManager,
									wireframes.ToArray(), translations.ToArray(),
									ColorSettings.SelectedOutlines, ToolConstants.thickLineScale);
							}
							MaterialUtility.LineDashMultiplier = 1.0f;
							MaterialUtility.LineThicknessMultiplier = 1.0f;
							instance.zTestLineMeshManager.Render(MaterialUtility.ZTestGenericLine);
							instance.zTestLineMeshManager.Render(MaterialUtility.ZTestGenericLine);
						}
					}
				}
			}
			/*
			// reset the control so the bottom bar can take over
			if (forceRevert)
			{
				GUIUtility.hotControl		= prevHotControl;
				GUIUtility.keyboardControl	= prevKeyboardControl;
			}
			*/

			int sceneWindowId	= GUIUtility.GetControlID (SceneWindowHash, FocusType.Passive);
			var sceneWindowType = Event.current.GetTypeForControl(sceneWindowId);
			if (sceneWindowType == EventType.repaint)
			{
				if (currentEditorWindows.Count > 0)
				{
					for (int i = 0; i < currentEditorWindows.Count; i++)
						currentEditorWindows[i].Repaint();
					return;
				}
			}

			if (sceneWindowType == EventType.MouseMove)
			{
				SceneTools.IsDraggingObjectInScene = false;
			}

			if (RealtimeCSG.CSGSettings.EnableRealtimeCSG)
			{
				if (sceneView != null && sceneWindowType != EventType.used && !SceneTools.IsDraggingObjectInScene)
				{
					if (currentEditorWindows.Count == 0)
					{
						try
						{
							Handles.BeginGUI();
							Rect windowRect = new Rect(Vector2.zero, sceneView.position.size);
							CSGBrushEditorGUI.HandleWindowGUI(windowRect);
						}
						finally
						{
							Handles.EndGUI();
						}
					}
				}
			}
		}

		public static void GenerateFromSurface(CSGBrush cSGBrush, CSGPlane polygonPlane, Vector3 direction, Vector3[] points, int[] pointIndices, uint[] smoothingGroups, bool drag)
		{
			CSGBrushEditorManager.EditMode = ToolEditMode.Generate;
			UpdateTool();
			var generateBrushTool = brushTools[(int)ToolEditMode.Generate] as GenerateBrushTool;
			generateBrushTool.GenerateFromPolygon(cSGBrush, polygonPlane, direction, points, pointIndices, smoothingGroups, drag);
		}

		public delegate void SetTransformation(Transform newTransform, Transform originalTransform);

		public static Transform[] CloneTargets(SetTransformation setTransform = null)
		{
			if (instance.filteredSelection.NodeTargets.Length == 0)
				return new Transform[0];

			var groupId = Undo.GetCurrentGroup();
			Undo.IncrementCurrentGroup();

			var newTargets	= new GameObject[instance.filteredSelection.NodeTargets.Length];
			var newTransforms = new Transform[instance.filteredSelection.NodeTargets.Length];
			for (int i = 0; i < instance.filteredSelection.NodeTargets.Length; i++)
			{
				var originalGameObject	= instance.filteredSelection.NodeTargets[i].gameObject;
				var originalTransform	= originalGameObject.GetComponent<Transform>();
				newTargets[i] = UnityEngine.Object.Instantiate(originalGameObject) as GameObject;
				var newTransform = newTargets[i].GetComponent<Transform>();
				if (originalTransform.parent != null)
				{
					newTransform.SetParent(originalTransform.parent, false);
					newTransform.SetSiblingIndex(originalTransform.GetSiblingIndex() + 1);
					newTransform.name = GameObjectUtility.GetUniqueNameForSibling(originalTransform.parent, originalTransform.name);
				}
				if (setTransform == null)
				{
					newTransform.localScale		= originalTransform.localScale;
					newTransform.localPosition	= originalTransform.localPosition;
					newTransform.localRotation	= originalTransform.localRotation;
				} else
					setTransform(newTransform, originalTransform);

				var childBrushes = newTargets[i].GetComponentsInChildren<CSGBrush>();

				Dictionary<uint, uint> uniqueSmoothingGroups = new Dictionary<uint, uint>();
				foreach (var childBrush in childBrushes)
				{
					for (int g = 0; g < childBrush.Shape.TexGens.Length; g++)
					{
						var smoothingGroup = childBrush.Shape.TexGens[g].SmoothingGroup;
						if (smoothingGroup == 0)
							continue;

						uint newSmoothingGroup;
						if (!uniqueSmoothingGroups.TryGetValue(smoothingGroup, out newSmoothingGroup))
						{
							newSmoothingGroup = SurfaceUtility.FindUnusedSmoothingGroupIndex();
							uniqueSmoothingGroups[smoothingGroup] = newSmoothingGroup;
						}

						childBrush.Shape.TexGens[g].SmoothingGroup = newSmoothingGroup;
					}
				}

				newTransforms[i] = newTransform;
				Undo.RegisterCreatedObjectUndo(newTargets[i], "Created clone of " + originalGameObject.name);
			}

			Selection.objects = newTargets;
			Undo.CollapseUndoOperations(groupId);

			return newTransforms;
		}
	}
}


text:
title: Nextopia Shopify App
subtitle: Ruby on Rails
layout: project
modal-id: 1
date: 2015-04-01
img: shopify.png
thumbnail: shopify-thumbnail.png
alt: image-alt
project-date: April 2015
client: Nextopia
category: Web Development
link: https://apps.shopify.com/nextopia-search
description: This app was built using Ruby on Rails and Shopify's "shopify-app" gem. This app allows Shopify customers to integrate Nextopia search into their online store without having to provide a feed file for their product catalog to Nextopia.

---


text:
layout: post
title: Solving a puzzle game the easy way
---

An android game I've been really enjoying lately is
[move](https://play.google.com/store/apps/details?id=com.nitako.move) from
Nitako Brain Studios. It is a game with simple mechanics and extremely good
puzzle design.

Game Mechanics
==============

Their [trailer](https://www.youtube.com/watch?v=up3lf5Rd97k)
shows off pretty much everything you need to know about it. If you don't
access to youtube then I'll do my best to explain.

A board consists of an n by n square featuring n colored dots, n shaded squares
whose colors match the dots and any number of blocking obstacles. Each move,
you select one cardinal direction and swipe the screen in that direction. All
dots move one square in that direction unless they are blocked by a wall, an
obstacle, or another blocked dot.

Consider the following example:

Here is the initial state of the board

We swipe left to move the top and bottom dots one space to the left and
producing this board

Next we swipe down moving the rightmost dot down

Finally we swipe left to align all dots with shaded square

For each board, the game tells you how many moves are in the optimal solution.

A Puzzle I Couldn't Solve
=========================

I had solved 99/100 of the 4x4, 1 color puzzles with the shortest possible
solution but struggled on puzzle number 74. My shortest solution, URURDRURLLDU
was two moves too long.

Trying to Brute Force on Paper
==============================
My strategy to solve the game was to work both forward and backward. Working
forward it was easy to see that the first move must be up; all other moves have
no effect. Working backward it was easy to see that the last move must be up as
well. No state exists such that a left, right or down leads to the goal state.
From there the options became far more numerous. I met in the middle believing
we knew all states that could be reached after 4 moves and all states that could
be reached after 6 moves. I then used heuristics to pairwise rule out all the
options. I concluded that the board could be solved in at best 11 moves.

Solving the game in code
========================
I decided to write some python to settle whether or not this puzzle could be
completed in ten moves. My implementation has two parts.

1. A python class that more or less implements the entire game
2. A python main that tries possible move sequences to see if they cause victory.

I reused the python class with only minor modifications across my version of the
solver. The class treated a board state as a 2D array of ints where 0's
represented empty space, -1's represented unmoving blockers and 1's represented
dots. For puzzles featuring more than one color, number other than 1 can be used
to specify the color of a dot/goal position. It had a function to do the action
of swiping in each direction and not much else.

###V1
My first version of the program optimized for programmer time not runtime. There
are at most 4^10 (roughly one million) possible move sequences. It isn't that
expensive to compute one move on the board. Lets just simulate each of the one
million sequences and print the first successful solution we find.

The two interesting pieces of code were as follows.

     1 def move_sequence(self, instructions, num_instructions):
     2      for i in range(num_instructions):
     3           todo = instructions % 4
     4           instructions = instructions / 4
     5           if todo == 0:
     6                self.move_down()
     7           elif todo == 1:
     8                self.move_up()
     9           elif todo == 2:
    10                self.move_right()
    11           else: # todo == 3
    12                self.move_left()

The board class exposed a function that took an integer, treated it as a
sequence of moves, and executed that sequence on its internal board.

     1 num_moves = 10
     2 for i in range(4**num_moves):
     3     my_board.reset()
     4     my_board.move_sequence(i, num_moves)
     5     if my_board == goal_board:
     6         print 'FOUND IT!'
     7         my_board.move_sequence_str(i, num_moves)
     8         break

The main function then called the move_sequence function on every integer in
the valid range and then compared the result against the desired final board.

####The Good
 - Very quick to write
 - Potentially parallelizable?

####The Bad
 - Slow
   - 17 second runtime
 - Tons of recomputed data
   - The transitions from the starting state to each of the 4 following states
     were each calculated ~250,000 times.
 - Doesn't abandon fruitless paths
   - Swiping down as a first move has no effect so it can't possibly be the
     first move but this iteration of the program tries ~250k sequences that
     begin with swiping down.
 - Needs to know how long the ideal solution is at compile time

###V2
This version of the program attempted to leverage the fact that early
subsequences were being executed many times by using memoization. I also
decided to return a list of solutions in case there were multiple.

     1 def search(path, board, depth, max_depth, goal):
     2     if depth == max_depth:
     3         if board == goal:
     4             return [path]
     5         return []
     6     else:
     7         ret = []
     8         for char, board in {'U': board.move_up(),
     9                             'D': board.move_down(),
    10                             'L': board.move_left(),
    11                             'R': board.move_right(),
    12                             }.iteritems():
    13             if(board):
    14                 success = search(path + char, board, depth + 1, max_depth, goal)
    15                 if success:
    16                     ret += success
    17         return ret

I made a minor change to my board class here to make the move_* functions return
false if they failed to change the board state (not shown).

The above function then depth first explores a tree where every node holds the
state of the board after the sequence of steps leading to it. The change to the
board class made it easy to ignore fruitless subsequences. Whenever I
encountered a move that didn't change the board state, I stopped exploring that
branch of the tree (line 13).

####The Good
 - Much faster than V1
   - 4 second runtime
 - Relatively memory inexpensive - The memoization stored at most as many boards
   as the length of the solution at a given time.

####The Bad
 - No sense of duplicate state
   - Up then Down on the board resets initial state but this program still tries
     up to 4^8 sequences beginning with that sequence - none of which are viable
   - Not only that but it computes those paths multiple times, once for each way
     of re-entering the starting state.
 - Needs to know how long the ideal solution is at compile time

###V3
This version switched from depth first search to breadth first search. It is
built on the idea that most states are reachable in many ways and we shouldn't
have to keep paying to do the same computations on those states.

     1 # key, Board object
     2 # val, string
     3 # represtents all visited states and the shortest paths to them
     4 boards = {}
     5 boards[my_board] = ""
     6
     7 # a deque of (Board, str) tuples
     8 to_search = deque()
     9 to_search.append((my_board, ""))
    10
    11 while to_search:
    12     (working_board, path) = to_search.popleft()
    13     for char, board in {'U': working_board.move_up(),
    14                         'D': working_board.move_down(),
    15                         'L': working_board.move_left(),
    16                         'R': working_board.move_right(),
    17                         }.iteritems():
    18         if board == goal_board:
    19             print path + char + '\n'
    20         elif board in boards:
    21             pass
    22         else:
    23             boards[board] = path + char
    24             to_search.append((board, path + char))

It maintains dict of all visited states and the shortest known path to them.
Whenever a state is computed, the algorithm checks if it is new and ignores if
it is not. In the case of the board in question, only ~500 states were reachable
in any number of moves.

####The Good
 - Much faster than V2
   - 0.2 second runtime
   - Does not need to be told how long the ideal solution is

####The Bad
 - Requires more memory
 - I forgot to tell it when to stop other than when it has reached all states

Result and Analysis
===================
It turns out there were two solutions.

 - UURDULLDRU
 - ULUULDRDDU

It is clear to me now that a state centric approach with caching of intermediate
results is the correct method. V1 computed as many as 4 million transitions
between states. V3 only did work on each state once so it computed at most ~2000
transitions.

Where We Went Wrong on Paper
============================
1. Working backward was harder than it seemed. One move to enter a state may
   mean many possible preceding states.
2. Seemingly implausible states may be easier to get into than anticipated.

Open Questions
==============
1. How was this puzzle generated?
  * More generally, how were the 1000+ puzzles in the game generated
2. Given the set of solutions to a puzzle, is it possible to reconstruct the
   initial board?
  * What additional information helps (i.e. board size, distribution of colors...)
3. What is the board/goal pair with the longest possible solution at each board
   size?
   * In the case of puzzle 74, there is a state that cannot be reached in
     fewer than 19 moves!
4. The two solutions to this puzzle are nearly anagrams.  The first has an extra
   R and the second has an extra D. How far can solutions to the same board be
   from each other in terms of distribution of moves?


text:
// @flow

import React from 'react';
import { Route } from 'react-router-dom';
import { getDefault } from '../../../shared/util/ModuleUtil';
import logger from '../../../shared/logger';
// eslint-disable-next-line import/no-unresolved
import routeModules from 'val-loader!./_find-routes';

// TODO: expose @withQueryParams which provides an URLSearchParam instance

const SourceFileName = Symbol('sourceFileName');

export default function createRoutes() {

  const fileNames = routeModules.__debugFileNames || [];

  if (routeModules.length === 0) {
    logger.warn('Your framework does not contain any route. Create a file matching your "route" glob as defined in your configuration file.');
  }

  const routes = routeModules
    .map((routeModule, i) => {
      let route = getDefault(routeModule);

      if (route == null || typeof route !== 'object') {
        return null;
      }

      if (typeof route.toJSON === 'function') {
        route = route.toJSON() || route;
      }

      route = Object.assign({}, route);
      route[SourceFileName] = fileNames[i];

      if (route.status === 404) {
        route.priority = route.priority || Number.MIN_SAFE_INTEGER + 2;
        route.path = route.path || '*';
      }

      if (route.status && Math.floor(route.status / 100) !== 2) {
        route.priority = route.priority || Number.MIN_SAFE_INTEGER + 1;
        route.path = route.path || '*';
      }

      return route;
    });

  if (process.env.NODE_ENV === 'development') {
    // dev 404 route
    routes.push({
      path: '*',
      priority: Number.MIN_SAFE_INTEGER,
      status: 404,
      component: require('./dev-404.js').default,
    });
  }

  return routes
    .filter(route => route !== null)
    .sort((a, b) => (b.priority || 0) - (a.priority || 0))
    .map(route => sanitizeRoute(route, route[SourceFileName]));
}

function sanitizeRoute(routeData /* , fileName */) {

  delete routeData.priority;

  // TODO: add support for status & getComponent in EnhancedRoute component & use EnhancedRoute
  // by default here.

  // const { getComponent, status, ...passDownRoute } = routeData;
  // let routeElement = <Route {...passDownRoute} />;

  return <Route {...routeData} key={routeData.path} />;
}


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

require 'active_support/core_ext/array/wrap'

require 'active_support/core_ext/numeric/time'
require 'active_support/core_ext/object/acts_like'
require 'active_support/core_ext/time/acts_like'
require 'active_support/core_ext/time/calculations'

describe 'querying models' do

  before do
    @record_a = @record = {:id => new_uuid, :title => "Datapathy is amazing!", :text => "It really is!", :published_at => 2.days.ago }
    @record_b =           {:id => new_uuid, :title => "Datapathy is awesome!", :text => "Try it today!", :published_at => 1.day.ago }
    @record_c =           {:id => new_uuid, :title => "Datapathy is awesome!", :text => "Title is same, but text is different", :published_at => 1.minute.ago }

    @records = [@record_a, @record_b, @record_c]
    @records.each do |record|
      test_adapter.datastore[Article][record[:id]] = record
    end
  end

  after do
    test_adapter.clear!
  end

  Spec::Matchers.define :include_records do |*expected_records|
    match do |matched_records|
      @expected_records = expected_records
      matched_keys = matched_records.map { |r| r.id }
      expected_keys = expected_records.map { |r| r[:id] }
      expected_keys.all? { |key| matched_keys.include?(key) }
    end
    failure_message_for_should do |matched_records|
      "Expected #{matched_records.to_a.inspect} to include all of #{@expected_records.inspect}"
    end

  end

  describe '(&blk)' do

    it 'should match ==' do
      Article.select { |a| a.title == "Datapathy is awesome!" }.
        should include_records(@record_b, @record_c)
    end

    it 'should match chained selects' do
      Article.select { |a| a.title == "Datapathy is awesome!" }.
              select { |a| a.text == "Try it today!" }.
        should include_records(@record_b)
    end

    it 'should match >' do
      Article.select { |a| a.published_at > 1.day.ago }.
        should include_records(@record_c)
    end

    describe 'limit' do

      it 'should limit records' do
        pending
        Article.select { |a| limit 2 }.
          should include_records(@record_a, @record_b)
      end

    end

  end

  describe '{hash}' do

    before do
      @articles = Article.select(:title => @record_b[:title])
    end

    it 'should retrieve all matching records' do
      @articles.should have(2).items
    end

    it 'should retrieve the correct records' do
      @articles.map { |a| a.id }.should include(@record_b[:id])
      @articles.map { |a| a.id }.should include(@record_c[:id])
    end

  end

end


text:
#include <gloperate-glkernel/stages/MultiFrameAggregationStage.h>

#include <glbinding/gl/functions.h>
#include <glbinding/gl/enum.h>

#include <globjects/Framebuffer.h>
#include <globjects/FramebufferAttachment.h>
#include <globjects/AttachedTexture.h>

#include <gloperate/rendering/ColorRenderTarget.h>
#include <gloperate/rendering/AttachmentType.h>

namespace gloperate_glkernel
{

CPPEXPOSE_COMPONENT(MultiFrameAggregationStage, gloperate::Stage)

MultiFrameAggregationStage::MultiFrameAggregationStage(gloperate::Environment * environment, const std::string & name)
: Stage(environment, name)
, renderInterface  (this)
, intermediateFrame("intermediateFrame", this)
, aggregationFactor("aggregationFactor", this)
{
}

MultiFrameAggregationStage::~MultiFrameAggregationStage()
{
}

void MultiFrameAggregationStage::onContextInit(gloperate::AbstractGLContext * /*context*/)
{
    m_triangle = cppassist::make_unique<gloperate::ScreenAlignedTriangle>();

    renderInterface.onContextInit();
}

void MultiFrameAggregationStage::onContextDeinit(gloperate::AbstractGLContext * /*context*/)
{
    m_triangle = nullptr;

    renderInterface.onContextDeinit();
}

void MultiFrameAggregationStage::onProcess()
{
    if (!renderInterface.allRenderTargetsCompatible())
    {
        cppassist::warning("gloperate") << "Framebuffer configuration not compatible";

        return;
    }

    auto fbo = renderInterface.obtainFBO();

    gl::glViewport(
        renderInterface.viewport->x,
        renderInterface.viewport->y,
        renderInterface.viewport->z,
        renderInterface.viewport->w
    );

    fbo->bind(gl::GL_FRAMEBUFFER);
    fbo->printStatus(true);

    if (*aggregationFactor > 0.99f) // first frame, no blending required
    {
        gl::glDisable(gl::GL_BLEND);
    }
    else
    {
        gl::glBlendColor(0.0f, 0.0f, 0.0f, *aggregationFactor);
        gl::glBlendFunc(gl::GL_CONSTANT_ALPHA, gl::GL_ONE_MINUS_CONSTANT_ALPHA);
        gl::glBlendEquation(gl::GL_FUNC_ADD);
        gl::glEnable(gl::GL_BLEND);
    }

    gl::glDisable(gl::GL_DEPTH_TEST);

    m_triangle->setTexture(*intermediateFrame);
    m_triangle->draw();

    gl::glDisable(gl::GL_BLEND);
    gl::glBlendFunc(gl::GL_SRC_ALPHA, gl::GL_ONE_MINUS_SRC_ALPHA);
    gl::glEnable(gl::GL_DEPTH_TEST);

    renderInterface.updateRenderTargetOutputs();
}

} // namespace gloperate_glkernel


text:
{% extends 'settings_js.html' %}{% load jsonify %}

{% block settings_javascript %}
{{ block.super }}
var MAPIT = {{ WAZIMAP.mapit|jsonify|safe }};
{% endblock settings_javascript %}


text:
layout: default
---

    {% for post in paginator.posts %}

        {{ post.title }}

        {{ post.date | date: "%b %-d, %Y" }}
        {% for category in post.categories %}
         {{category   }}
         {% endfor %}

          {{post.excerpt}}

    {% endfor %}

{% if paginator.total_pages > 1 %}

  {% if paginator.previous_page == 1 %}
   Previous
  {% elsif paginator.previous_page > 1 %}
    Previous
  {% else %}
    Previous
  {% endif %}
  Page: {{paginator.page}} of {{paginator.total_pages}}
  {% if paginator.next_page %}
    Next
  {% else %}
    Next
  {% endif %}

{% endif %}


text:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {

  constructor() {
      super();
      this.retrieveProducerStatus = this.retrieveProducerStatus.bind(this);
      this.state = {
        producer: {
          status: 'loading...',
          currentDateTime: 'loading...'
        }
      };
    }

    componentDidMount() {
      window.setInterval(this.retrieveProducerStatus, 1000);
    }

    retrieveProducerStatus() {
      fetch(`http://localhost:8080/status`)
        .then(result => result.json())
        .then(json => this.setState({
          producer: {
            status: json.status,
            currentDateTime: json.currentDateTime
          }
        }));
    }

    render() {
      return (

pact-sample :: consumer

            status: {this.state.producer.status}

            current date time: {this.state.producer.currentDateTime}

      );
    }

}

export default App;


text:
#ifndef SKY_ENGINE_CORE_RENDERING_STYLE_SHADOWDATA_H_
#define SKY_ENGINE_CORE_RENDERING_STYLE_SHADOWDATA_H_

#include "flutter/sky/engine/platform/geometry/FloatPoint.h"
#include "flutter/sky/engine/platform/graphics/Color.h"

namespace blink {

enum ShadowStyle { Normal, Inset };

// This class holds information about shadows for the text-shadow and box-shadow properties.
class ShadowData {
    WTF_MAKE_FAST_ALLOCATED;
public:
    ShadowData(const FloatPoint& location, float blur, float spread, ShadowStyle style, const Color& color)
        : m_location(location)
        , m_blur(blur)
        , m_spread(spread)
        , m_color(color)
        , m_style(style)
    {
    }

    bool operator==(const ShadowData&) const;
    bool operator!=(const ShadowData& o) const { return !(*this == o); }

    ShadowData blend(const ShadowData& from, double progress) const;

    float x() const { return m_location.x(); }
    float y() const { return m_location.y(); }
    FloatPoint location() const { return m_location; }
    float blur() const { return m_blur; }
    float spread() const { return m_spread; }
    ShadowStyle style() const { return m_style; }
    const Color& color() const { return m_color; }

private:
    FloatPoint m_location;
    float m_blur;
    float m_spread;
    // FIXME: We should use StyleColor here to allow currentColor to work correctly with visited links
    Color m_color;
    ShadowStyle m_style;
};

} // namespace blink

#endif  // SKY_ENGINE_CORE_RENDERING_STYLE_SHADOWDATA_H_


text:
namespace PatientManagement.PatientManagement {
    export interface VisitTypesForm {
        Name: Serenity.StringEditor;
        BorderColor: Serenity.StringEditor;
        BackgroundColor: Serenity.StringEditor;
        ShowInMenu: BsSwitchEditor;
        Price: Serenity.DecimalEditor;
        CurrencyId: Serenity.LookupEditor;
        TenantId: Serenity.IntegerEditor;
        IsActive: Serenity.BooleanEditor;
    }

    export class VisitTypesForm extends Serenity.PrefixedContext {
        static formKey = 'PatientManagement.VisitTypes';
        private static init: boolean;

        constructor(prefix: string) {
            super(prefix);

            if (!VisitTypesForm.init)  {
                VisitTypesForm.init = true;

                var s = Serenity;
                var w0 = s.StringEditor;
                var w1 = BsSwitchEditor;
                var w2 = s.DecimalEditor;
                var w3 = s.LookupEditor;
                var w4 = s.IntegerEditor;
                var w5 = s.BooleanEditor;

                Q.initFormType(VisitTypesForm, [
                    'Name', w0,
                    'BorderColor', w0,
                    'BackgroundColor', w0,
                    'ShowInMenu', w1,
                    'Price', w2,
                    'CurrencyId', w3,
                    'TenantId', w4,
                    'IsActive', w5
                ]);
            }
        }
    }
}


text:
import zstackwoodpecker.test_state as ts_header
import os
TestAction = ts_header.TestAction
def path():

    return dict(initial_formation="template5", checking_point=8, path_list=[
		[TestAction.create_vm, 'vm1', ],
		[TestAction.create_volume, 'volume1', 'flag=scsi'],
		[TestAction.attach_volume, 'vm1', 'volume1'],
		[TestAction.create_volume, 'volume2', 'flag=scsi'],
		[TestAction.attach_volume, 'vm1', 'volume2'],
		[TestAction.create_volume, 'volume3', 'flag=scsi'],
		[TestAction.attach_volume, 'vm1', 'volume3'],
		[TestAction.create_volume_snapshot, 'vm1-root', 'vm1-root-snapshot1'],
		[TestAction.stop_vm, 'vm1'],
		[TestAction.use_volume_snapshot, 'vm1-root-snapshot1'],
		[TestAction.start_vm, 'vm1'],
		[TestAction.create_vm_snapshot, 'vm1', 'vm1-snapshot2'],
		[TestAction.reboot_vm, 'vm1'],
		[TestAction.stop_vm, 'vm1'],
		[TestAction.use_volume_snapshot, 'vm1-root-snapshot1'],
		[TestAction.start_vm, 'vm1'],
		[TestAction.create_vm_snapshot, 'vm1', 'vm1-snapshot6'],
		[TestAction.stop_vm, 'vm1'],
		[TestAction.use_vm_snapshot, 'vm1-snapshot2'],
		[TestAction.start_vm, 'vm1'],
])

'''
The final status:
Running:['vm1']
Stopped:[]
Enadbled:['vm1-root-snapshot1', 'vm1-snapshot2', 'volume1-snapshot2', 'volume2-snapshot2', 'volume3-snapshot2', 'vm1-snapshot6', 'volume1-snapshot6', 'volume2-snapshot6', 'volume3-snapshot6']
attached:['volume1', 'volume2', 'volume3']
Detached:[]
Deleted:[]
Expunged:[]
Ha:[]
Group:
	vm_snap2:['vm1-snapshot6', 'volume1-snapshot6', 'volume2-snapshot6', 'volume3-snapshot6']---vm1volume1_volume2_volume3
	vm_snap1:['vm1-snapshot2', 'volume1-snapshot2', 'volume2-snapshot2', 'volume3-snapshot2']---vm1volume1_volume2_volume3
'''


text:
import {Injectable, NgZone} from '@angular/core';

import Feature from 'ol/Feature';
import {Geometry} from 'ol/geom';
import {forkJoin} from 'rxjs';

import {DatasetType, HsAddDataService} from '../add-data.service';
import {EndpointsWithDatasourcesPipe} from '../../../common/widgets/endpoints-with-datasources.pipe';
import {HsAddDataCatalogueMapService} from './catalogue-map.service';
import {HsAddDataLayerDescriptor} from './layer-descriptor.model';
import {HsAddDataOwsService} from '../url/add-data-ows.service';
import {HsAddDataVectorService} from '../vector/vector.service';
import {HsCommonEndpointsService} from '../../../common/endpoints/endpoints.service';
import {HsCommonLaymanService} from '../../../common/layman/layman.service';
import {HsConfig} from '../../../config.service';
import {HsEndpoint} from '../../../common/endpoints/endpoint.interface';
import {HsEventBusService} from '../../core/event-bus.service';
import {HsLaymanBrowserService} from './layman/layman.service';
import {HsLayoutService} from '../../layout/layout.service';
import {HsMapService} from '../../map/map.service';
import {HsMickaBrowserService} from './micka/micka.service';
import {HsUtilsService} from '../../utils/utils.service';

//TODO: Find a better name and possibly turn it into a public interface
type WhatToAddDescriptor = {
  type: string;
  dsType?: string;
  layer?;
  link?;
  name?;
  title?: string;
  abstract?: string;
  projection?;
  extractStyles?;
  editable?: boolean;
  workspace?: string;
  style?: string;
  recordType?: string;
};

export class HsAddDataCatalogueParams {
  data: any = {
    query: {
      textFilter: '',
      title: '',
      type: 'all',
      Subject: '',
      sortby: 'date',
    },
    textField: 'AnyText',
    selectedLayer: null,
    id_selected: 'OWS',
    filterByExtent: true,
    onlyMine: false,
  };
  selectedEndpoint: HsEndpoint;
  selectedLayer: HsAddDataLayerDescriptor;
  catalogEntries: HsAddDataLayerDescriptor[] = [];
  dataLoading: boolean;
  recordsPerPage = 20;
  listStart = 0;
  listNext = this.recordsPerPage;
  catalogQuery;
  endpointsWithDatasources: HsEndpoint[];
  matchedRecords: number;
  extentChangeSuppressed = false;

  constructor() {}
}

@Injectable({
  providedIn: 'root',
})
export class HsAddDataCatalogueService {
  apps: {
    [id: string]: HsAddDataCatalogueParams;
  } = {default: new HsAddDataCatalogueParams()};

  constructor(
    public hsConfig: HsConfig,
    public hsAddDataVectorService: HsAddDataVectorService,
    public hsEventBusService: HsEventBusService,
    public hsMickaBrowserService: HsMickaBrowserService,
    public hsLaymanBrowserService: HsLaymanBrowserService,
    public hsLayoutService: HsLayoutService,
    public hsCommonEndpointsService: HsCommonEndpointsService,
    public hsUtilsService: HsUtilsService,
    public hsMapService: HsMapService,
    public hsAddDataCatalogueMapService: HsAddDataCatalogueMapService,
    public hsAddDataService: HsAddDataService,
    public endpointsWithDatasourcesPipe: EndpointsWithDatasourcesPipe,
    private zone: NgZone,
    public hsCommonLaymanService: HsCommonLaymanService,
    public hsAddDataOwsService: HsAddDataOwsService
  ) {
    this.hsEventBusService.mainPanelChanges.subscribe(({which, app}) => {
      if (this.dataSourceExistsAndEmpty(app) && this.panelVisible(app)) {
        this.reloadData(app);
        this.get(app).extentChangeSuppressed = true;
      }
      this.calcExtentLayerVisibility(app);
    });

    this.hsCommonLaymanService.authChange.subscribe(({app}) => {
      if (this.panelVisible(app)) {
        this.reloadData(app);
      }
    });

    this.hsAddDataService.datasetSelected.subscribe(({type, app}) => {
      if (type == 'catalogue' && this.panelVisible(app)) {
        this.reloadData(app);
      }
    });
  }

  get(app: string): HsAddDataCatalogueParams {
    if (this.apps[app ?? 'default'] == undefined) {
      this.apps[app ?? 'default'] = new HsAddDataCatalogueParams();
    }
    return this.apps[app ?? 'default'];
  }

  init(_app: string) {
    this.get(_app).endpointsWithDatasources =
      this.endpointsWithDatasourcesPipe.transform(
        this.hsCommonEndpointsService.endpoints
      );

    if (this.dataSourceExistsAndEmpty(_app) && this.panelVisible(_app)) {
      this.queryCatalogs(_app);
      // this.hsMickaFilterService.fillCodesets();
    }
    this.hsEventBusService.mapExtentChanges.subscribe(
      this.hsUtilsService.debounce(
        ({map, event, extent, app}) => {
          if (app == _app) {
            const appRef = this.get(app);
            if (!this.panelVisible(app) || appRef.extentChangeSuppressed) {
              appRef.extentChangeSuppressed = false;
              return;
            }
            if (appRef.data.filterByExtent) {
              this.zone.run(() => {
                this.reloadData(app);
              });
            }
          }
        },
        500,
        false,
        this
      )
    );
  }

  resetList(app: string): void {
    const appRef = this.get(app);
    appRef.listStart = 0;
    appRef.listNext = appRef.recordsPerPage;
    appRef.selectedLayer = <HsAddDataLayerDescriptor>{};
    appRef.endpointsWithDatasources.forEach((ep: HsEndpoint) => {
      ep.datasourcePaging.start = 0;
      ep.datasourcePaging.next = ep.datasourcePaging.limit;
      ep.datasourcePaging.matched = 0;
    });
  }

  reloadData(app: string): void {
    this.get(app).endpointsWithDatasources =
      this.endpointsWithDatasourcesPipe.transform(
        this.hsCommonEndpointsService.endpoints
      );
    this.resetList(app);

    this.queryCatalogs(app);
    // this.hsMickaFilterService.fillCodesets();
    this.calcExtentLayerVisibility(app);
  }

  /**
   * Queries all configured catalogs for datasources (layers)
   * @param suspendLimitCalculation -
   */
  queryCatalogs(app: string, suspendLimitCalculation?: boolean): void {
    const appRef = this.get(app);
    if (appRef.endpointsWithDatasources.length > 0) {
      if (appRef.catalogQuery) {
        appRef.catalogQuery.unsubscribe();
        delete appRef.catalogQuery;
      }
      this.clearLoadedData(app);

      this.hsMapService.loaded(app).then(() => {
        appRef.dataLoading = true;
        this.hsAddDataCatalogueMapService.clearExtentLayer(app);
        const observables = [];

        //TODO Mark non functional endpoint
        for (const endpoint of appRef.endpointsWithDatasources) {
          if (!appRef.data.onlyMine || endpoint.type == 'layman') {
            const promise = this.queryCatalog(endpoint, app);
            observables.push(promise);
          }
        }
        appRef.catalogQuery = forkJoin(observables).subscribe(() => {
          suspendLimitCalculation
            ? this.createLayerList(app)
            : this.calculateEndpointLimits(app);
        });
      });
    }
  }
  /**
   * Calculates each endpoint layer request limit, based on the matched layers ratio
   * from all endpoint matched layers
   */
  calculateEndpointLimits(app: string): void {
    const appRef = this.get(app);
    appRef.matchedRecords = 0;
    appRef.endpointsWithDatasources = appRef.endpointsWithDatasources.filter(
      (ep) => ep.datasourcePaging.matched != 0
    );
    if (appRef.endpointsWithDatasources.length == 0) {
      appRef.dataLoading = false;
      return;
    }
    appRef.endpointsWithDatasources.forEach(
      (ep) => (appRef.matchedRecords += ep.datasourcePaging.matched)
    );
    let sumLimits = 0;
    appRef.endpointsWithDatasources.forEach((ep) => {
      ep.datasourcePaging.limit = Math.floor(
        (ep.datasourcePaging.matched / appRef.matchedRecords) *
          appRef.recordsPerPage
      );
      if (ep.datasourcePaging.limit == 0) {
        ep.datasourcePaging.limit = 1;
      }
      sumLimits += ep.datasourcePaging.limit;
    });
    appRef.recordsPerPage = sumLimits;
    appRef.listNext = appRef.recordsPerPage;
    this.queryCatalogs(app, true);
  }

  createLayerList(app: string): void {
    const appRef = this.get(app);
    for (const endpoint of appRef.endpointsWithDatasources) {
      if (!appRef.data.onlyMine || endpoint.type == 'layman') {
        if (endpoint.layers) {
          endpoint.layers.forEach((layer) => {
            layer.endpoint = endpoint;
            // this.catalogEntries.push(layer);
          });

          if (appRef.catalogEntries.length > 0) {
            this.filterDuplicates(endpoint, app);
          } else {
            appRef.catalogEntries = appRef.catalogEntries.concat(
              endpoint.layers
            );
          }
        }
      }
    }

    if (appRef.matchedRecords < appRef.recordsPerPage) {
      appRef.listNext = appRef.matchedRecords;
    }

    appRef.catalogEntries.sort((a, b) => a.title.localeCompare(b.title));
    appRef.dataLoading = false;
  }

  filterDuplicates(endpoint: HsEndpoint, app: string): Array<any> {
    const appRef = this.get(app);
    if (endpoint.layers === undefined || endpoint.layers?.length == 0) {
      return [];
    }

    const filteredLayers = endpoint.layers.filter(
      (layer) =>
        appRef.catalogEntries.filter(
          (u) =>
            u.id == layer.id ||
            u.id == 'm-' + layer.id ||
            'm-' + u.id == layer.id
        ).length == 0
    );

    if (endpoint.type != 'layman') {
      appRef.matchedRecords -= endpoint.layers.length - filteredLayers.length;
    }
    appRef.catalogEntries = appRef.catalogEntries.concat(filteredLayers);
  }

  getNextRecords(app: string): void {
    const appRef = this.get(app);
    appRef.listStart += appRef.recordsPerPage;
    appRef.listNext += appRef.recordsPerPage;
    if (appRef.listNext > appRef.matchedRecords) {
      appRef.listNext = appRef.matchedRecords;
    }
    appRef.endpointsWithDatasources.forEach(
      (ep) => (ep.datasourcePaging.start += ep.datasourcePaging.limit)
    );
    this.queryCatalogs(app, true);
  }

  getPreviousRecords(app: string): void {
    const appRef = this.get(app);
    if (appRef.listStart - appRef.recordsPerPage <= 0) {
      appRef.listStart = 0;
      appRef.listNext = appRef.recordsPerPage;
      appRef.endpointsWithDatasources.forEach(
        (ep: HsEndpoint) => (ep.datasourcePaging.start = 0)
      );
    } else {
      appRef.listStart -= appRef.recordsPerPage;
      appRef.listNext = appRef.listStart + appRef.recordsPerPage;
      appRef.endpointsWithDatasources.forEach(
        (ep: HsEndpoint) =>
          (ep.datasourcePaging.start -= ep.datasourcePaging.limit)
      );
    }
    this.queryCatalogs(app, true);
  }

  changeRecordsPerPage(perPage: number, app: string): void {
    this.resetList(app);
    this.queryCatalogs(app);
  }

  clearLoadedData(app: string): void {
    const appRef = this.get(app);
    appRef.catalogEntries = [];
    appRef.endpointsWithDatasources.forEach((ep) => (ep.layers = []));
  }

  /**
   * Loads datasets metadata from selected source (CSW server).
   * Uses pagination set by 'start' attribute of 'dataset' param.
   * Currently supports only "Micka" type of source.
   * Use all query params (search text, bbox, params.., sorting, start)
   * @param catalog - Configuration of selected datasource (from app config)
   */
  queryCatalog(catalog: HsEndpoint, app: string): any {
    const appRef = this.get(app);
    this.hsAddDataCatalogueMapService.clearDatasetFeatures(catalog, app);
    let query;
    switch (catalog.type) {
      case 'micka':
        query = this.hsMickaBrowserService.queryCatalog(
          catalog,
          appRef.data,
          (feature: Feature<Geometry>) =>
            this.hsAddDataCatalogueMapService.addExtentFeature(feature, app),
          appRef.data.textField,
          app
        );
        return query;
      case 'layman':
        query = this.hsLaymanBrowserService.queryCatalog(
          catalog,
          app,
          appRef.data,
          (feature: Feature<Geometry>) =>
            this.hsAddDataCatalogueMapService.addExtentFeature(feature, app)
        );
        return query;
      default:
        break;
    }
  }

  /**
   * Test if layer of selected record is downloadable (KML and JSON files, with direct URL) and gives URL.
   * @param ds - Datasource of selected layer
   * @param layer - Metadata record of selected layer
   * @returns Download URL of layer if possible
   */
  layerDownload(ds: HsEndpoint, layer): string {
    if (ds.download == true) {
      if (
        ['kml', 'geojson', 'json'].includes(layer.formats[0].toLowerCase()) &&
        layer.url.length > 0
      ) {
        return layer.url;
      }
    }
    return '#';
  }

  /**
   * Get URL for RDF-DCAT record of selected layer
   * @param ds - Datasource of selected layer
   * @param layer - Metadata record of selected layer
   * @returns URL to record file
   */
  layerRDF(ds: HsEndpoint, layer): string {
    return `${ds.url}?request=GetRecordById&id=${layer.id}&outputschema=http://www.w3.org/ns/dcat%23`;
  }

  /**
   * Add selected layer to map (into layer manager) if possible
   * @param ds - Datasource of selected layer
   * @param layer - Metadata record of selected layer
   * @param type - Type of layer (supported values: WMS, WFS, Sparql, kml, geojson, json)
   * @returns Type or array of types in which this layer can be added to map
   */
  async addLayerToMap(
    ds: HsEndpoint,
    layer: HsAddDataLayerDescriptor,
    app: string,
    type?: string
  ): Promise<string[] | string | void> {
    let whatToAdd: WhatToAddDescriptor;

    if (ds.type == 'micka') {
      whatToAdd = await this.hsMickaBrowserService.describeWhatToAdd(
        ds,
        layer,
        app
      );
    } else if (ds.type == 'layman') {
      whatToAdd = await this.hsLaymanBrowserService.describeWhatToAdd(
        ds,
        layer,
        app
      );
    } else {
      whatToAdd = {type: 'none'};
    }

    if (!whatToAdd) {
      return;
    }
    if (type) {
      whatToAdd.type = type;
    }
    if (Array.isArray(whatToAdd.type)) {
      return whatToAdd.type;
    }
    if (whatToAdd.type == 'WMS') {
      whatToAdd.link = Array.isArray(whatToAdd.link)
        ? whatToAdd.link.filter((link) => link.toLowerCase().includes('wms'))[0]
        : whatToAdd.link;
      if (ds.type == 'micka' && whatToAdd.recordType != 'dataset') {
        this.datasetSelect('url', app);
      }
      await this.hsAddDataOwsService.connectToOWS(
        {
          type: whatToAdd.type.toLowerCase(),
          uri: decodeURIComponent(whatToAdd.link),
          layer:
            ds.type == 'layman' || whatToAdd.recordType === 'dataset'
              ? ds.type == 'layman'
                ? layer.name
                : whatToAdd.name
              : undefined,
        },
        app
      );
    } else if (whatToAdd.type == 'WFS') {
      if (ds.type == 'micka') {
        if (!whatToAdd.workspace) {
          this.datasetSelect('url', app);
        }
        whatToAdd.link = Array.isArray(whatToAdd.link)
          ? whatToAdd.link.filter((link) =>
              link.toLowerCase().includes('wfs')
            )[0]
          : whatToAdd.link;
        await this.hsAddDataOwsService.connectToOWS(
          {
            type: whatToAdd.type.toLowerCase(),
            uri: decodeURIComponent(whatToAdd.link),
            layer: whatToAdd.workspace
              ? `${whatToAdd.workspace}:${whatToAdd.name}`
              : undefined,
            style: whatToAdd.style,
          },
          app
        );
      } else {
        //Layman layers of logged user/ with write access
        if (whatToAdd.editable) {
          const layer = await this.hsAddDataVectorService.addVectorLayer(
            'wfs',
            whatToAdd.link.replace('_wms/ows', '/wfs'),
            whatToAdd.name,
            whatToAdd.title,
            whatToAdd.abstract,
            whatToAdd.projection,
            {
              extractStyles: whatToAdd.extractStyles,
              workspace: whatToAdd.workspace,
              style: whatToAdd.style,
              saveToLayman: true,
            },
            app
          );
          this.hsAddDataVectorService.fitExtent(layer, app);
          this.datasetSelect('catalogue', app);
        } else {
          //Layman layers without write access
          await this.hsAddDataOwsService.connectToOWS(
            {
              type: 'wfs',
              uri: whatToAdd.link.replace('_wms/ows', '/wfs'),
              style: whatToAdd.style,
              layer: `${whatToAdd.workspace}:${whatToAdd.name}`,
            },
            app
          );
        }
        this.hsLayoutService.setMainPanel('layermanager', app);
      }
    } else if (['KML', 'GEOJSON'].includes(whatToAdd.type)) {
      const layer = await this.hsAddDataVectorService.addVectorLayer(
        whatToAdd.type.toLowerCase(),
        whatToAdd.link,
        whatToAdd.name,
        whatToAdd.title,
        whatToAdd.abstract,
        whatToAdd.projection,
        {extractStyles: whatToAdd.extractStyles},
        app
      );
      this.hsAddDataVectorService.fitExtent(layer, app);
    } else if (whatToAdd.type == 'WMTS' && ds.type == 'micka') {
      //Micka only  yet
      if (whatToAdd.recordType === 'service') {
        this.datasetSelect('url', app);
      }
      await this.hsAddDataOwsService.connectToOWS(
        {
          type: whatToAdd.type.toLowerCase(),
          uri: decodeURIComponent(whatToAdd.link),
          layer:
            whatToAdd.recordType === 'dataset' ? whatToAdd.name : undefined,
        },
        app
      );
    } else {
      this.hsLayoutService.setMainPanel('layermanager', app);
    }
    return whatToAdd.type;
  }

  datasetSelect(id_selected: DatasetType, app: string): void {
    this.get(app).data.id_selected = id_selected;
    this.hsAddDataService.selectType(id_selected, app);
    this.calcExtentLayerVisibility(app);
  }
  /**
   * Clear query variable
   */
  clear(app: string): void {
    const appRef = this.get(app);
    appRef.data.query.textFilter = '';
    appRef.data.query.title = '';
    appRef.data.query.Subject = '';
    appRef.data.query.keywords = '';
    appRef.data.query.OrganisationName = '';
    appRef.data.query.sortby = '';
  }

  /**
   *
   */
  private dataSourceExistsAndEmpty(app: string): boolean {
    return !!this.get(app).endpointsWithDatasources;
  }

  /**
   *
   */
  private panelVisible(app: string): boolean {
    return this.hsLayoutService.panelVisible('addData', app);
  }

  calcExtentLayerVisibility(app: string): void {
    this.hsAddDataCatalogueMapService
      .get(app)
      .extentLayer.setVisible(
        this.panelVisible(app) &&
          this.hsAddDataService.get(app).dsSelected == 'catalogue'
      );
  }
}


text: “nicht weiß, ob der Iterator bewegt wird oder ein neuer erzeugt"


text:
SMBIOS Validation Tool is an open source tool that will validate SMBIOS records
in vendor's firmware (BIOS) conformance to the SMBIOS requirements to Google
Server Firmware Specification.

Note: This is not an officially supported Google product.

## Terminology

*   **SMBIOS** - System Management BIOS. The SMBIOS Specification addresses how
    motherboard and system vendors present management information about their
    products in a standard format by extending the BIOS interface on x86
    architecture systems. The information is intended to allow generic
    instrumentation to deliver this information to management applications that
    use DMI, CIM or direct access, eliminating the need for error prone
    operations like probing system hardware for presence detection.

*   **SMBIOS Record** - One specific SMBIOS Structure. Each record has a type, a
    unique handle id, and required fields with corresponding info. See below
    graph for more intuitive understanding.

![SMBIOS Table](https://docs.google.com/drawings/d/e/2PACX-1vTEVmlZfL6CkpNs44IZ1BAz3lxyBZ1VQRhjAmjwKpj8oJQcUtte3YcQgijGKAWc2Shl2LSaRoGojGIg/pub?w=562&h=434)

## Installation

Note: Python3 is recommended to run this tool. The following instruction assumes
Python3 is installed on the host.

To install the tool, simply run:

```shell
git clone https://github.com/google/smbios-validation-tool.git
pip3 install absl-py
pip3 install termcolor
```

## Execution

Access to the root directory of the tool and simply run:

```shell
python3 smbios_validation.py
```

The tool can also analyze a dmi dump file, although this is a rare use case:

```shell
python3 smbios_validation.py --file=path/to/your/dump_file.txt
```

## Output

The tool is designed to provide the error and suggested action messages as
clearly as possible, to help users correct errors in SMBIOS much easier.

Whenever the tool finds a rule is not valid on the host, an error message in a
fixed format will be printed out, followed by the suggested action. The tool
uses termcolor to highlight the output to make it more readable. Please install
termcolor as stated in 'Quick Start' section.

### Error Messages

Error message will have fixed format for individual records, and is displayed as
red color:

```
ERROR: Invalid <field_name> field in Type <type_id> (<type_name>) record.
Handle ID: <handle_id>
```

Error messages for validating groups of records do not have a fixed format, but
will also contain all necessary information for debugging.

### Action Messages

Action messages will provide users with the suggestion of how to fix the error.
Action messages will also have fixed format for individual records, and are
displayed right below the corresponding error messages as orange color and with
underline:

```
ACTION: Please populate <field_name> field with valid string/number/handle/etc.
<Optional extra messages>
```

Again, action messages for validating groups of records do not have a fixed
format. Our goal is to provide useful information for users to correct the
error, so usually the action message will clearly state what the rule is and/or
which part of the rule is not valid.

## Troubleshooting

### No such file or directory: 'dmidecode': 'dmidecode'

Usually dmidecode should be included in Linux package. If this is not the case,
install dmidecode first, and ensure the dmidecode executable is available in
PATH when executing the utility, then run the following command:

```shell
PATH=$PATH:. python3 smbios_validation.py
```


text:
scout.FileTreeField = function() {
  scout.FileTreeField.parent.call(this);
};
scout.inherits(scout.FileTreeField, scout.FormField);

scout.FileTreeField.prototype._render = function($parent) {
  this.addContainer($parent, 'filetree-field');
  this.addLabel();
  this.addStatus();

  var filetreeId = scout.objectFactory.createUniqueId();
  var $fieldContent = this.$container.makeDiv('filetree').attr('id', filetreeId);

  var field = this;
  var rootFolder = field.rootFolder.value;

  this._folderContents = new Map(); // depends on browser
  this._fileTree = $fieldContent.fileTree({
      root: rootFolder,
      script: function(data) {
        return field._handleFolderClicked(data);
      },
      collapseSpeed: field.collapseSpeed,
      multiFolder: field.multiFolder
    },
    function(file) {
      field._handleFileClicked(file);
    })[0];
  this._$fileTree = $(this._fileTree);
  this._fileTreeInstance = this._$fileTree.data('fileTree');

  this.addField($fieldContent);
};

scout.FileTreeField.prototype._renderProperties = function() {
  scout.FileTreeField.parent.prototype._renderProperties.call(this);
  this._renderExpandSpeed();
  this._renderCollapseSpeed();
  this._renderMultiFolder();
};

scout.FileTreeField.prototype._remove = function() {
  scout.FileTreeField.parent.prototype._remove.call(this);
  this._$fileTree = null;
  this._fileTreeInstance = null;
  this._folderContents.clear();
  this._folderContents = null;
  this._fileTree = null;
};

scout.FileTreeField.prototype._handleFolderClicked = function(folder) {
  if (!this._fileTree) {
    return this._wrapWithUl(this._makeLi({
      isDir: true,
      isCollapsed: true,
      name: this.label,
      path: folder.dir
    }));
  }

  var $clickedObjParent = this._getElement(folder.dir).parent();
  if (this._folderContents.has(folder.dir)) {
    $clickedObjParent.removeClass('waitForCallback').addClass('directory').addClass('expanded');
    var treeFieldElementArr = this._folderContents.get(folder.dir);
    if (treeFieldElementArr && treeFieldElementArr.length > 0) {
      var index;
      var itemStr = '';
      for (index = 0; index < treeFieldElementArr.length; index++) {
        itemStr += this._makeLi(treeFieldElementArr[index]);
      }
      return this._wrapWithUl(itemStr);
    }
    return '';
  } else {
    $clickedObjParent.addClass('waitForCallback').removeClass('directory').removeClass('expanded');
    this._send('folderClicked', folder);
    return '';
  }
};

scout.FileTreeField.prototype._makeLi = function(attribs) {
  var cssClass;
  if (attribs.isDir) {
    cssClass = 'directory';
    if (attribs.isCollapsed) {
      cssClass += ' collapsed';
    } else {
      cssClass += ' expanded';
    }
  } else {
    cssClass = 'file';
    var ext = '';
    var pos = attribs.name.lastIndexOf('.');
    if (pos >= 0) {
      ext = attribs.name.substring(pos + 1, attribs.name.length);
    }
    if (ext) {
      cssClass += ' ext_' + ext;
    }
  }
  var attribsName = scout.strings.encode(attribs.name);
  return '
' + attribsName + '
';
};

scout.FileTreeField.prototype._wrapWithUl = function(str) {
  return '
' + str + '
';
};

scout.FileTreeField.prototype._getElement = function(dir) {
  return this._$fileTree.find("a[rel='" + dir + "']").first();
};

//scout.ModelAdapter.prototype._syncExpandSpeed = function(expandSpeed) {
//  this.expandSpeed = expandSpeed;
//};

scout.FileTreeField.prototype._renderExpandSpeed = function() {
  this._fileTreeInstance.options.expandSpeed = this.expandSpeed;
};

scout.FileTreeField.prototype._renderCollapseSpeed = function() {
  this._fileTreeInstance.options.collapseSpeed = this.collapseSpeed;
};

scout.FileTreeField.prototype._renderMultiFolder = function() {
  this._fileTreeInstance.options.multiFolder = this.multiFolder;
};

scout.FileTreeField.prototype._onFolderContentLoaded = function(event) {
  var $clickedObj = this._getElement(event.dir);
  this._folderContents.set(event.dir, event.content);
  this._fileTreeInstance.showTree($clickedObj.parent(), event.dir, function() {
    this._fileTreeInstance._trigger('filetreeexpanded', this._fileTreeInstance.data);
  }.bind(this));
};

scout.FileTreeField.prototype._handleFileClicked = function(file) {
  this._send('fileClicked', {
    path: file
  });
};

scout.FileTreeField.prototype.onModelAction = function(event) {
  if (event.type === 'folderLoaded') {
    this._onFolderContentLoaded(event);
  } else {
    scout.FileTreeField.parent.prototype.onModelAction.call(this, event);
  }
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/objects/tools/nozzles" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/objects/tools/nozzles</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Nozzles</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/objects/tools/nozzles</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/objects/tools/nozzles</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/Topic</sem:object>
  </sem:triple>
</sem:triples>


text:
package org.apache.servicecomb.common.rest.definition.path;

import static org.junit.Assert.assertEquals;

import org.apache.servicecomb.common.rest.definition.path.URLPathBuilder.URLPathStringBuilder;
import org.junit.Test;

public class URLPathStringBuilderTest {
  @Test
  public void testNormal() {
    URLPathStringBuilder builder = new URLPathStringBuilder();
    builder.appendPath("/path");
    builder.appendQuery("q", "abc");
    assertEquals("/path?q=abc", builder.build());
  }

  @Test
  public void appendPath() {
    URLPathStringBuilder builder = new URLPathStringBuilder();
    builder.appendPath("/abc");
    assertEquals("/abc", builder.build());
    builder.appendPath("/de fg");
    assertEquals("/abc/de fg", builder.build());
  }

  @Test
  public void appendQuery() {
    URLPathStringBuilder builder = new URLPathStringBuilder();
    assertEquals("", builder.build());
    builder.appendQuery("ab", "cd");
    assertEquals("?ab=cd", builder.build());
    builder.appendQuery("ef", "");
    assertEquals("?ab=cd&ef=", builder.build());
    builder.appendQuery("gh", "jk");
    assertEquals("?ab=cd&ef=&gh=jk", builder.build());
  }
}


text:
page_title: Managing Data in Containers
page_description: How to manage data inside your Docker containers.
page_keywords: Examples, Usage, volume, docker, documentation, user guide, data, volumes

# Managing Data in Containers

So far we've been introduced to some [basic Docker
concepts](/userguide/usingdocker/), seen how to work with [Docker
images](/userguide/dockerimages/) as well as learned about [networking
and links between containers](/userguide/dockerlinks/). In this section
we're going to discuss how you can manage data inside and between your
Docker containers.

We're going to look at the two primary ways you can manage data in
Docker.

* Data volumes, and
* Data volume containers.

## Data volumes

A *data volume* is a specially-designated directory within one or more
containers that bypasses the [*Union File
System*](/terms/layer/#union-file-system) to provide several useful features for
persistent or shared data:

- Volumes are initialized when a container is created
- Data volumes can be shared and reused between containers
- Changes to a data volume are made directly
- Changes to a data volume will not be included when you update an image
- Volumes persist until no containers use them

### Adding a data volume

You can add a data volume to a container using the `-v` flag with the
`docker create` and `docker run` command. You can use the `-v` multiple times
to mount multiple data volumes. Let's mount a single volume now in our web
application container.

    $ sudo docker run -d -P --name web -v /webapp training/webapp python app.py

This will create a new volume inside a container at `/webapp`.

> **Note:**
> You can also use the `VOLUME` instruction in a `Dockerfile` to add one or
> more new volumes to any container created from that image.

### Mount a Host Directory as a Data Volume

In addition to creating a volume using the `-v` flag you can also mount a
directory from your Docker daemon's host into a container.

> **Note:**
> If you are using Boot2Docker, your Docker daemon only has limited access to
> your OSX/Windows filesystem. Boot2Docker tries to auto-share your `/Users`
> (OSX) or `C:\Users` (Windows) directory - and so you can mount files or directories
> using `docker run -v /Users/<path>:/<container path> ...` (OSX) or
> `docker run -v /c/Users/<path>:/<container path ...` (Windows). All other paths
> come from the Boot2Docker virtual machine's filesystem.

    $ sudo docker run -d -P --name web -v /src/webapp:/opt/webapp training/webapp python app.py

This will mount the host directory, `/src/webapp`, into the container at
`/opt/webapp`.

> **Note:**
> If the path `/opt/webapp` already exists inside the container's image, its
> contents will be replaced by the contents of `/src/webapp` on the host to stay
> consistent with the expected behavior of `mount`

This is very useful for testing, for example we can
mount our source code inside the container and see our application at work as
we change the source code. The directory on the host must be specified as an
absolute path and if the directory doesn't exist Docker will automatically
create it for you.

> **Note:**
> This is not available from a `Dockerfile` due to the portability
> and sharing purpose of built images. The host directory is, by its nature,
> host-dependent, so a host directory specified in a `Dockerfile` probably
> wouldn't work on all hosts.

Docker defaults to a read-write volume but we can also mount a directory
read-only.

    $ sudo docker run -d -P --name web -v /src/webapp:/opt/webapp:ro training/webapp python app.py

Here we've mounted the same `/src/webapp` directory but we've added the `ro`
option to specify that the mount should be read-only.

### Mount a Host File as a Data Volume

The `-v` flag can also be used to mount a single file  - instead of *just*
directories - from the host machine.

    $ sudo docker run --rm -it -v ~/.bash_history:/.bash_history ubuntu /bin/bash

This will drop you into a bash shell in a new container, you will have your bash
history from the host and when you exit the container, the host will have the
history of the commands typed while in the container.

> **Note:**
> Many tools used to edit files including `vi` and `sed --in-place` may result
> in an inode change. Since Docker v1.1.0, this will produce an error such as
> "*sed: cannot rename ./sedKdJ9Dy: Device or resource busy*". In the case where
> you want to edit the mounted file, it is often easiest to instead mount the
> parent directory.

## Creating and mounting a Data Volume Container

If you have some persistent data that you want to share between
containers, or want to use from non-persistent containers, it's best to
create a named Data Volume Container, and then to mount the data from
it.

Let's create a new named container with a volume to share.
While this container doesn't run an application, it reuses the `training/postgres`
image so that all containers are using layers in common, saveing disk space.

    $ sudo docker create -v /dbdata --name dbdata training/postgres

You can then use the `--volumes-from` flag to mount the `/dbdata` volume in another container.

    $ sudo docker run -d --volumes-from dbdata --name db1 training/postgres

And another:

    $ sudo docker run -d --volumes-from dbdata --name db2 training/postgres

You can use multiple `--volumes-from` parameters to bring together multiple data
volumes from multiple containers.

You can also extend the chain by mounting the volume that came from the
`dbdata` container in yet another container via the `db1` or `db2` containers.

    $ sudo docker run -d --name db3 --volumes-from db1 training/postgres

If you remove containers that mount volumes, including the initial `dbdata`
container, or the subsequent containers `db1` and `db2`, the volumes will not
be deleted.  To delete the volume from disk, you must explicitly call
`docker rm -v` against the last container with a reference to the volume. This
allows you to upgrade, or effectively migrate data volumes between containers.

## Backup, restore, or migrate data volumes

Another useful function we can perform with volumes is use them for
backups, restores or migrations.  We do this by using the
`--volumes-from` flag to create a new container that mounts that volume,
like so:

    $ sudo docker run --volumes-from dbdata -v $(pwd):/backup ubuntu tar cvf /backup/backup.tar /dbdata

Here we've launched a new container and mounted the volume from the
`dbdata` container. We've then mounted a local host directory as
`/backup`. Finally, we've passed a command that uses `tar` to backup the
contents of the `dbdata` volume to a `backup.tar` file inside our
`/backup` directory. When the command completes and the container stops
we'll be left with a backup of our `dbdata` volume.

You could then restore it to the same container, or another that you've made
elsewhere. Create a new container.

    $ sudo docker run -v /dbdata --name dbdata2 ubuntu /bin/bash

Then un-tar the backup file in the new container's data volume.

    $ sudo docker run --volumes-from dbdata2 -v $(pwd):/backup busybox tar xvf /backup/backup.tar

You can use the techniques above to automate backup, migration and
restore testing using your preferred tools.

# Next steps

Now we've learned a bit more about how to use Docker we're going to see how to
combine Docker with the services available on
[Docker Hub](https://hub.docker.com) including Automated Builds and private
repositories.

Go to [Working with Docker Hub](/userguide/dockerrepos).


text:
export const name = 'Techcrunch',
  sortParameters = ['top', 'latest'],
  id = 'techcrunch',
  sortBy = 'top',
  news = [{
    author: 'Reporter',
    title: 'Reasons to be cheerful',
    description: null,
    url: 'https://foo.hotnews.com',
    urlImage: 'https://bar.hotnews.com/image.png',
    date: '2017-05-21T14:40:57Z',
  },
  {
    author: 'Repo',
    title: 'Reasons to be cheerful2',
    description: 'There are many reasons to be cheerful. Number one...',
    url: 'https://foo.hotnews2.com',
    urlImage: 'https://bar.hotnews.com/image.png',
    date: '2017-05-21T14:40:57B',
  }],
  sortedNews = [{
    author: 'Repo',
    title: 'Reasons to be cheerful2',
    description: 'There are many reasons to be cheerful. Number one...',
    url: 'https://foo.hotnews2.com',
    urlImage: 'https://bar.hotnews2.com/image.png',
    date: '2017-05-21T14:40:57B',
  },
  {
    author: 'Reporter',
    title: 'Reasons to be cheerful',
    description: 'There are many reasons to be cheerful. Number one...',
    url: 'https://foo.hotnews.com',
    urlImage: 'https://bar.hotnews.com/image.png',
    date: '2017-05-21T14:40:57Z',
  }],
  sources = [{
    id: 'ars-technica',
    name: 'Ars Technica',
    description: 'The PC enthusiast\'s resource. Power users..',
    category: 'technology',
    sortBy: [
      'top',
      'latest',
    ],
  },
  {
    id: 'techcrunch',
    name: 'TechCrunch',
    description: 'Anything Technology',
    category: 'technology',
    sortBy: [
      'top',
      'latest',
    ],
  }],
  user = {
    name: 'Ignatius',
    email: 'ignatius.ukwuoma@andela.com',
    uid: '8575894',
    photo: 'http://andela.com',
  };


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Budgeting.Core.Model
{
    public class Wallet
    {
        public Guid _id { get; set; }
        public string _walletName { get; set; }
        public double _salary { get; set; }

        public Wallet( Guid id, string walletName, double salary)
        {
            this._walletName = walletName;
            this._id = id;
            this._salary = salary;
        }
    }
}


text:
@module {function()} steal.steal-clone steal-clone
@parent StealJS.modules
@description
Steal-clone is a module that allows you to clone Steal's loader and provide module definitions that will be used when doing dynamic imports.

@signature `clone(moduleOverrides)`

@param {Object} moduleOverrides Module identifiers and definitions used to override modules of the same name. These definitions will be used when importing parent modules using the `import` statement of the returned loader.

@return {Object} The cloned loader.

@body

## Use

If you have `moduleA` defined as:

```js
import moduleB from 'moduleB';

export default function() {
  return 'moduleA ' + moduleB();
};
```

and `moduleB` defined as:

```js
export default function() {
  return 'moduleB';
};
```

You can use `clone` to override the definition of moduleB that will be used from within moduleA:

```js
import clone from 'steal-clone';

clone({
  'moduleB': {
    default: function() {
      return 'moduleBOverride';
    }
  }
})
.import('moduleA')
.then(function(moduleA) {
  moduleA(); // moduleA moduleBOverride
});
```

### Module Identifiers

The keys passed in the `moduleOverrides` object ("moduleB" in the example above) can be any valid module identifier. All of the module syntaxes supported by Steal are supported by steal-clone. If you're using [ES6 modules](http://stealjs.com/docs/syntax.es6.html), you can use the same value used in your import statement. Similarly, if you're using [CommonJS](http://stealjs.com/docs/syntax.CommonJS.html), you can use the same value that you pass to 'require'.

You can also use relative paths to override modules based on where you are using steal-clone:

```js
clone({
	'./moduleB': ...
});
```

### Module Definitions

The values passed in the `moduleOverrides` object define the exports for that module. In the above example, `moduleB` has a single default export.

If `moduleB` is defined like:

```js
const name = 'moduleB';

export let getName = function() {
  return name;
};

export let getExcitedName = function() {
  return name + '!';
};
```

You can override both of the module's exports like this:

```js
clone({
  'moduleB': {
    getName: function() {
      return 'moduleBOverride';
    },
    getExcitedName: function() {
      return 'moduleBOverride!';
    }
  }
});
```

### Dynamically imported modules

It's possible to provide overrides to modules that will be later dynamically imported. If you have a `moduleC` defined as:

```js
import loader from '@loader';

loader.import('moduleB').then(function(){

});
```

You will be able to override the value of `moduleB`. Note that for this to work you must import [@loader] to use for dynamic loading instead of using `steal.import`. This is because `@loader` will refer to the cloned loader you created where as `steal.loader` always refers back to the global loader. Using [@loader] is always recommended anyways.

### Use with npm

Steal-clone can be used to override dependencies from [npm](http://stealjs.com/docs/npm.html) in the same way as any other module.