text:
namespace peloton {
namespace codegen {

class CodeGen;
class Value;

namespace type {

class Type;

//===----------------------------------------------------------------------===//
// This class contains all the type-system functionality for the codegen
// component. In reality, there is tremendous overlap with the Peloton type
// system. In the future, this class should replace that one ...
//
// This class implements an operator table similar in spirit to Postgres. In
// Peloton, operators are categorized as casting, comparison, unary or binary
// operators. Every SQL type configures a TypeSystem with supported operators.
// As in Postgres, each operator can be configured to be overriden by a user-
// provided implementation.
//===----------------------------------------------------------------------===//
class TypeSystem {
 public:
  //===--------------------------------------------------------------------===//
  // Casting operator
  //===--------------------------------------------------------------------===//
  struct Cast {
    // Virtual destructor
    virtual ~Cast() {}

    // Does this cast support casting from the given type to the given type?
    virtual bool SupportsTypes(const Type &from_type,
                               const Type &to_type) const = 0;

    // Perform the cast on the given value to the provided type
    virtual Value DoCast(CodeGen &codegen, const Value &value,
                         const Type &to_type) const = 0;
  };

  class CastWithNullPropagation : public Cast {
   public:
    CastWithNullPropagation(const TypeSystem::Cast &inner_cast)
        : inner_cast_(inner_cast) {}

    // Does this cast support casting from the given type to the given type?
    bool SupportsTypes(const Type &from_type,
                       const Type &to_type) const override;

    // Perform the cast on the given value to the provided type
    Value DoCast(CodeGen &codegen, const Value &value,
                 const Type &to_type) const override;

   private:
    const TypeSystem::Cast &inner_cast_;
  };

  struct CastInfo {
    peloton::type::TypeId from_type;
    peloton::type::TypeId to_type;
    const Cast &cast_operation;
  };

  //===--------------------------------------------------------------------===//
  // The generic comparison interface for all comparisons between all types
  //===--------------------------------------------------------------------===//
  struct Comparison {
    // Virtual destructor
    virtual ~Comparison() {}

    // Does this instance support comparison of the values of the given left and
    // right SQL types?
    virtual bool SupportsTypes(const Type &left_type,
                               const Type &right_type) const = 0;

    // Main comparison operators
    virtual Value DoCompareLt(CodeGen &codegen, const Value &left,
                              const Value &right) const = 0;

    virtual Value DoCompareLte(CodeGen &codegen, const Value &left,
                               const Value &right) const = 0;

    virtual Value DoCompareEq(CodeGen &codegen, const Value &left,
                              const Value &right) const = 0;

    virtual Value DoCompareNe(CodeGen &codegen, const Value &left,
                              const Value &right) const = 0;

    virtual Value DoCompareGt(CodeGen &codegen, const Value &left,
                              const Value &right) const = 0;

    virtual Value DoCompareGte(CodeGen &codegen, const Value &left,
                               const Value &right) const = 0;

    // Perform a comparison used for sorting. We need a stable and transitive
    // sorting comparison operator here. The operator returns:
    //  < 0 - if the left value comes before the right value when sorted
    //  = 0 - if the left value is equivalent to the right element
    //  > 0 - if the left value comes after the right value when sorted
    virtual Value DoComparisonForSort(CodeGen &codegen, const Value &left,
                                      const Value &right) const = 0;
  };

  class ComparisonWithNullPropagation : public Comparison {
   public:
    ComparisonWithNullPropagation(
        const TypeSystem::Comparison &inner_comparison)
        : inner_comparison_(inner_comparison) {}

    bool SupportsTypes(const Type &left_type,
                       const Type &right_type) const override;

    // Main comparison operators
    Value DoCompareLt(CodeGen &codegen, const Value &left,
                      const Value &right) const override;

    Value DoCompareLte(CodeGen &codegen, const Value &left,
                       const Value &right) const override;

    Value DoCompareEq(CodeGen &codegen, const Value &left,
                      const Value &right) const override;

    Value DoCompareNe(CodeGen &codegen, const Value &left,
                      const Value &right) const override;

    Value DoCompareGt(CodeGen &codegen, const Value &left,
                      const Value &right) const override;

    Value DoCompareGte(CodeGen &codegen, const Value &left,
                       const Value &right) const override;

    // Perform a comparison used for sorting. We need a stable and transitive
    // sorting comparison operator here. The operator returns:
    //  < 0 - if the left value comes before the right value when sorted
    //  = 0 - if the left value is equivalent to the right element
    //  > 0 - if the left value comes after the right value when sorted
    Value DoComparisonForSort(CodeGen &codegen, const Value &left,
                              const Value &right) const override;

   private:
    const Comparison &inner_comparison_;
  };

  struct ComparisonInfo {
    // The operation
    const Comparison &comparison;
  };

  //===--------------------------------------------------------------------===//
  // A unary operator (i.e., an operator that accepts a single argument)
  //===--------------------------------------------------------------------===//
  struct UnaryOperator {
    virtual ~UnaryOperator() {}

    // Does this unary operator support values of the given type?
    virtual bool SupportsType(const Type &type) const = 0;

    // What is the SQL type of the result of applying the unary operator on a
    // value of the provided type?
    virtual Type ResultType(const Type &val_type) const = 0;

    // Apply the operator on the given value
    virtual Value DoWork(CodeGen &codegen, const Value &val) const = 0;
  };

  class UnaryOperatorWithNullPropagation : public UnaryOperator {
   public:
    UnaryOperatorWithNullPropagation(const UnaryOperator &inner_op)
        : inner_op_(inner_op) {}

    // Does this unary operator support values of the given type?
    bool SupportsType(const Type &type) const override;

    // What is the SQL type of the result of applying the unary operator on a
    // value of the provided type?
    Type ResultType(const Type &val_type) const override;

    // Apply the operator on the given value
    Value DoWork(CodeGen &codegen, const Value &val) const override;

   private:
    const UnaryOperator &inner_op_;
  };

  struct UnaryOpInfo {
    // The ID of the operation
    OperatorId op_id;

    // The operation
    const UnaryOperator &unary_operation;
  };

  //===--------------------------------------------------------------------===//
  // A binary operator (i.e., an operator that accepts two arguments)
  //===--------------------------------------------------------------------===//
  struct BinaryOperator {
    virtual ~BinaryOperator() {}

    // Does this binary operator support the two provided input types?
    virtual bool SupportsTypes(const Type &left_type,
                               const Type &right_type) const = 0;

    // What is the SQL type of the result of applying the binary operator on the
    // provided left and right value types?
    virtual Type ResultType(const Type &left_type,
                            const Type &right_type) const = 0;

    // Execute the actual operator
    virtual Value DoWork(CodeGen &codegen, const Value &left,
                         const Value &right, OnError on_error) const = 0;
  };

  struct BinaryOperatorWithNullPropagation : public BinaryOperator {
   public:
    BinaryOperatorWithNullPropagation(
        const TypeSystem::BinaryOperator &inner_op)
        : inner_op_(inner_op) {}

    bool SupportsTypes(const Type &left_type,
                       const Type &right_type) const override;

    Type ResultType(const Type &left_type,
                    const Type &right_type) const override;

    Value DoWork(CodeGen &codegen, const Value &left, const Value &right,
                 OnError on_error) const override;

   private:
    const BinaryOperator &inner_op_;
  };

  struct BinaryOpInfo {
    // The ID of the operation
    OperatorId op_id;

    // The operation
    const BinaryOperator &binary_operation;
  };

 public:
  TypeSystem(const std::vector<peloton::type::TypeId> &implicit_cast_table,
             const std::vector<CastInfo> &explicit_cast_table,
             const std::vector<ComparisonInfo> &comparison_table,
             const std::vector<UnaryOpInfo> &unary_op_table,
             const std::vector<BinaryOpInfo> &binary_op_table);

  // Can values of the provided type be implicitly casted into a value of the
  // other provided type?
  static bool CanImplicitlyCastTo(const Type &from_type, const Type &to_type);

  // Lookup comparison handler for the given type
  static const Cast *GetCast(const Type &from_type, const Type &to_type);

  // Lookup comparison handler for the given type
  static const Comparison *GetComparison(const Type &left_type,
                                         Type &left_casted_type,
                                         const Type &right_type,
                                         Type &right_casted_type);

  // Lookup the given binary operator that works on the left and right types
  static const UnaryOperator *GetUnaryOperator(OperatorId op_id,
                                               const Type &input_type);

  // Lookup the given binary operator that works on the left and right types
  static const BinaryOperator *GetBinaryOperator(OperatorId op_id,
                                                 const Type &left_type,
                                                 Type &left_casted_type,
                                                 const Type &right_type,
                                                 Type &right_casted_type);

 private:
  // The list of types a given type can be implicitly casted to
  const std::vector<peloton::type::TypeId> &implicit_cast_table_;

  // The table of explicit casting functions
  const std::vector<CastInfo> &explicit_cast_table_;

  // The comparison table
  const std::vector<ComparisonInfo> &comparison_table_;

  // The table of builtin unary operators
  const std::vector<UnaryOpInfo> &unary_op_table_;

  // The table of builtin binary operators
  const std::vector<BinaryOpInfo> &binary_op_table_;

 private:
  DISALLOW_COPY_AND_MOVE(TypeSystem);
};

}  // namespace type
}  // namespace codegen
}  // namespace peloton


text:
package br.com.starcode.jerichoselector.matcher;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import net.htmlparser.jericho.Element;
import br.com.starcode.parccser.Parser;
import br.com.starcode.parccser.ParserException;
import br.com.starcode.parccser.model.Combinator;
import br.com.starcode.parccser.model.Selector;
import br.com.starcode.parccser.model.SimpleSelector;
import br.com.starcode.parccser.model.SimpleSelectorSequence;

public class SelectorMatcher {

	private MatcherRegistry matcherRegistry;

	public SelectorMatcher(MatcherRegistry matcherRegistry) {
		if (matcherRegistry == null) {
			throw new IllegalArgumentException("Matcher cannot be null!");
		}
		this.matcherRegistry = matcherRegistry;
	}

	public Set<Element> applySelector(Element e, String selectorStr) throws ParserException {
		List<Selector> selectors = Parser.parse(selectorStr);
		Set<Element> elements = new TreeSet<Element>();
		for (Selector selector : selectors) {
			elements.addAll(matchSelector(e, selector));
		}
		return elements;
	}

	protected Set<Element> matchSelector(Element e, Selector selector) {
		int i = 0;
		Set<Element> elements = new TreeSet<Element>();
		for (SimpleSelectorSequence simpleSelectorSequence : selector.getSelectors()) {
			if (i == 0) {
				elements = matchSimpleSelectorSequence(e, simpleSelectorSequence);
			} else {
				Combinator combinator = selector.getCombinators().get(i - 1);
				elements = matchSimpleSelectorSequence(e, simpleSelectorSequence, combinator, elements);
			}
			i++;
		}
		return elements;
	}

	protected Set<Element> matchSimpleSelectorSequence(
			Element e,
			SimpleSelectorSequence simpleSelectorSequence) {
		List<SimpleSelector> simpleSelectors = simpleSelectorSequence.getSimpleSelectors();
		return walkAndMatchSimpleSelectorList(e, simpleSelectors, e.getAllElements());
	}

	protected Set<Element> matchSimpleSelectorSequence(
			Element e,
			SimpleSelectorSequence simpleSelectorSequence,
			Combinator combinator,
			Set<Element> elements) {
		List<SimpleSelector> simpleSelectors = simpleSelectorSequence.getSimpleSelectors();
		Set<Element> returnedElements = new TreeSet<Element>();
		for (Element element : elements) {
			walkAndCombineSimpleSelectorList(element, simpleSelectors, combinator, returnedElements);
		}
		return returnedElements;
	}

	protected Set<Element> walkAndMatchSimpleSelectorList(
			Element e,
			List<SimpleSelector> simpleSelectors,
			List<Element> elements) {
		Set<Element> resultElements = new TreeSet<Element>();
		for (Element element : elements) {
			if (matchSimpleSelectorList(element, simpleSelectors)) {
				resultElements.add(element);
			}
		}
		return resultElements;
	}

	protected void walkAndCombineSimpleSelectorList(
			Element e,
			List<SimpleSelector> simpleSelectors,
			Combinator combinator,
			Set<Element> elements) {

		List<Element> combinedElements = new ArrayList<Element>();
		switch (combinator) {
		case DESCENDANT:
			combinedElements.addAll(e.getAllElements());
			combinedElements.remove(e);
			break;
		case CHILD:
			combinedElements.addAll(e.getChildElements());
			break;
		case ADJASCENT_SIBLING:
			if (e.getParentElement() != null) {
				List<Element> siblings = e.getParentElement().getChildElements();
				int pos = siblings.indexOf(e);
				if (pos < siblings.size() - 1) {
					combinedElements.add(siblings.get(pos + 1));
				}
			}
			break;
		case GENERAL_SIBLING:
			if (e.getParentElement() != null) {
				combinedElements.addAll(e.getParentElement().getChildElements());
				combinedElements.remove(e);
			}
			break;
		default:
			return;
		}

		elements.addAll(walkAndMatchSimpleSelectorList(e, simpleSelectors, combinedElements));
	}

	protected boolean matchSimpleSelectorList(
			Element e,
			List<SimpleSelector> simpleSelectors) {
		for (SimpleSelector simpleSelector : simpleSelectors) {
			if (!matcherRegistry.matches(e, simpleSelector)) {
				return false;
			}
		}
		return true;
	}

}

redpajama_set_name: RedPajamaGithub


text:
#ifndef  FREEGLUT_INTERNAL_EGL_H
#define  FREEGLUT_INTERNAL_EGL_H

#include <EGL/egl.h>

/* -- GLOBAL TYPE DEFINITIONS ---------------------------------------------- */
/* The structure used by display initialization in fg_init.c */
struct tagSFG_Window;
struct tagSFG_PlatformDisplayEGL
{
  /* Used to initialize and deinitialize EGL */
  EGLDisplay          Display;
  EGLint              MajorVersion;
  EGLint              MinorVersion;
};

/*
 * Make "freeglut" window handle and context types so that we don't need so
 * much conditionally-compiled code later in the library.
 */
typedef EGLNativeWindowType SFG_WindowHandleType ;
typedef EGLContext SFG_WindowContextType ;
struct tagSFG_PlatformContextEGL
{
  EGLSurface          Surface;
  EGLConfig           Config;
};

#endif


text:
org = typeof(org) === 'undefined' ? {} : org;
org.sriku = org.sriku || {};

org.sriku.Carnot = (function (Carnot) {

    var GLOBAL = this;

#include "eventable.js"

    Carnot = Eventable(Carnot);

#include "parser.js"
#include "svg-renderer.js"

    // notation = text
    // style = object
    // => svg element
    Carnot['renderNotation'] = function (notation, style) {
        style = style || {};

        var pre = GLOBAL.document.createElement('pre');
        pre.textContent = notation;

        return RenderSVG(GLOBAL, Parse(pre), style);
    };

    Carnot['renderSections'] = function (sectionSelector, style) {
        style = style || {};
        var sections = (typeof(sectionSelector) === 'string'
            ? GLOBAL.document.querySelectorAll(sectionSelector)
            : sectionSelector);

        WARNIF(sections.length === 0, "Carnot: No sections to render.");

        var svgs = [], i, N;
        sections = Array.prototype.slice.call(sections);
        sections.forEach(function (s) { return s.hidden = true; }); // Hide them all first.
        for (i = 0, N = sections.length; i < N; ++i) {
            svgs.push(RenderSVG(GLOBAL, Parse(sections[i]), style));
            sections[i].parentElement.insertBefore(svgs[i], sections[i]);
            Carnot.emit('rendered_section', svgs[i]);
        }

        Carnot.emit('render_complete', svgs);
    };

    Carnot['renderPage'] = function (style) {
        if (GLOBAL.document.readyState === 'interactive') {
            setTimeout(Carnot.renderSections, 0, findSections(GLOBAL.document), style);
        } else {
            GLOBAL.document.addEventListener('readystatechange', function () {
                if (GLOBAL.document.readyState === 'interactive') {
                    Carnot.renderSections('pre.carnot_section', style);
                    GLOBAL.document.removeEventListener('readystatechange', arguments.callee);
                }
            });
        }
    };

    Carnot['findSections'] = findSections;
    Carnot['scanStyle'] = scanStyle;

    // Search for <pre> tags with class "carnot_section",
    // or pre tags which begin with the line - "tala pattern = ..."
    // and don't have class "carnot_ignore".
    function findSections(topNode) {
        topNode = topNode || GLOBAL.document;
        var explicitSections = topNode.querySelectorAll('pre.carnot_section');
        var sections = Array.prototype.slice.call(explicitSections);

        var allPreTags = topNode.querySelectorAll('pre');
        var i, N, pre;
        for (i = 0, N = allPreTags.length; i < N; ++i) {
            pre = allPreTags[i];
            if (!pre.classList.contains('carnot_ignore')) {
                if (/^\s*tala\s+pattern\s*=/.test(pre.textContent)) {
                    // Starts with "tala pattern = " and does not
                    // have class "carnot_ignore", so we consider it
                    // to be a carnot_section.
                    sections.push(pre);
                }
            }
        }

        return sections;
    }

    function scanStyle(topNode) {
        topNode = topNode || GLOBAL.document;
        var style = topNode.querySelector('pre.carnot_style');
        if (style) {
            style.hidden = true;
            style = Parse(style);
            return style[style.length - 1].properties;
        } else {
            return {};
        }
    }

    function renderDocWithStyle() {
        var style = GLOBAL.document.querySelector('pre.carnot_style');
        if (style) {
            style.hidden = true;
            style = Parse(style)[0].properties;
        } else {
            style = {};
        }

        Carnot.renderPage(style);
    }

    // If a "carnot_style" class pre is present, load it up
    // and immediately begin rendering. Otherwise wait for
    // an explicit Carnot.render call.
    if (GLOBAL.document.readyState === "interactive") {
        renderDocWithStyle();
    } else {
        GLOBAL.document.addEventListener('readystatechange', function () {
            if (GLOBAL.document.readyState === 'interactive') {
                renderDocWithStyle();
                GLOBAL.document.removeEventListener('readystatechange', arguments.callee);
            }
        });
    }

    return Carnot;

}({}));


text:
<module xmlns="urn:jboss:module:1.0" name="org.camunda.commons.camunda-commons-typed-values">
  <resources>
    <resource-root path="camunda-commons-typed-values-@version.camunda.commons@.jar" />
  </resources>

  <dependencies>
    <module name="javax.api"/>

    <module name="org.camunda.commons.camunda-commons-utils" />

  </dependencies>
</module>


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security;
using Microsoft.Deployment.WindowsInstaller;
using Microsoft.Win32;

namespace InstallerCA
{
    public class CustomActions
    {
        #region Methods

        #region CaRegisterAddIn

        [CustomAction]
        public static ActionResult CaRegisterAddIn(Session session)
        {
            var szOfficeRegKeyVersions = string.Empty;
            var szBaseAddInKey = @"Software\Microsoft\Office\";
            var szXll32Bit = string.Empty;
            var szXll64Bit = string.Empty;
            var szXllToRegister = string.Empty;
            int nOpenVersion;
            double nVersion;
            var bFoundOffice = false;
            List<string> lstVersions;

            try
            {
                session.Log("Enter try block of CaRegisterAddIn");

                szOfficeRegKeyVersions = session["OFFICEREGKEYS"];
                szXll32Bit = session["XLL32"];
                szXll64Bit = session["XLL64"];

                if (szOfficeRegKeyVersions.Length > 0)
                {
                    lstVersions = szOfficeRegKeyVersions.Split(',').ToList();

                    foreach (var szOfficeVersionKey in lstVersions)
                    {
                        nVersion = double.Parse(szOfficeVersionKey, NumberStyles.Any, CultureInfo.InvariantCulture);

                        session.Log("Retrieving Registry Information for : " + szBaseAddInKey + szOfficeVersionKey);

                        // get the OPEN keys from the Software\Microsoft\Office\[Version]\Excel\Options key, skip if office version not found.
                        if (Registry.CurrentUser.OpenSubKey(szBaseAddInKey + szOfficeVersionKey, false) != null)
                        {
                            var szKeyName = szBaseAddInKey + szOfficeVersionKey + @"\Excel\Options";

                            szXllToRegister = GetAddInName(szXll32Bit, szXll64Bit, szOfficeVersionKey, nVersion);

                            var rkExcelXll = Registry.CurrentUser.OpenSubKey(szKeyName, true);

                            if (szXllToRegister != string.Empty && rkExcelXll != null)
                            {
                                var szValueNames = rkExcelXll.GetValueNames();
                                var bIsOpen = false;
                                var nMaxOpen = -1;

                                // check every value for OPEN keys
                                foreach (var szValueName in szValueNames)
                                {
                                    // if there are already OPEN keys, determine if our key is installed
                                    if (szValueName.StartsWith("OPEN"))
                                    {
                                        nOpenVersion = int.TryParse(szValueName.Substring(4), NumberStyles.Any,
                                            CultureInfo.InvariantCulture, out nOpenVersion)
                                            ? nOpenVersion
                                            : 0;
                                        var nNewOpen = szValueName == "OPEN" ? 0 : nOpenVersion;
                                        if (nNewOpen > nMaxOpen)
                                        {
                                            nMaxOpen = nNewOpen;
                                        }

                                        // if the key is our key, set the open flag
                                        //NOTE: this line means if the user has changed its office from 32 to 64 (or conversly) without removing the addin then we will not update the key properly
                                        //The user will have to uninstall addin before installing it again
                                        if (rkExcelXll.GetValue(szValueName).ToString().Contains(szXllToRegister))
                                        {
                                            bIsOpen = true;
                                        }
                                    }
                                }

                                // if adding a new key
                                if (!bIsOpen)
                                {
                                    if (nMaxOpen == -1)
                                    {
                                        rkExcelXll.SetValue("OPEN", "/R \"" + szXllToRegister + "\"");
                                    }
                                    else
                                    {
                                        rkExcelXll.SetValue("OPEN" + (nMaxOpen + 1), "/R \"" + szXllToRegister + "\"");
                                    }
                                    rkExcelXll.Close();
                                }
                                bFoundOffice = true;
                            }
                            else
                            {
                                session.Log("Unable to retrieve key for : " + szKeyName);
                            }
                        }
                        else
                        {
                            session.Log("Unable to retrieve registry Information for : " + szBaseAddInKey +
                                        szOfficeVersionKey);
                        }
                    }
                }

                session.Log("End CaRegisterAddIn");
            }
            catch (SecurityException ex)
            {
                session.Log("CaRegisterAddIn SecurityException" + ex.Message);
                bFoundOffice = false;
            }
            catch (UnauthorizedAccessException ex)
            {
                session.Log("CaRegisterAddIn UnauthorizedAccessException" + ex.Message);
                bFoundOffice = false;
            }
            catch (Exception ex)
            {
                session.Log("CaRegisterAddIn Exception" + ex.Message);
                bFoundOffice = false;
            }

            return bFoundOffice ? ActionResult.Success : ActionResult.Failure;
        }

        #endregion

        #region CaUnRegisterAddIn

        [CustomAction]
        public static ActionResult CaUnRegisterAddIn(Session session)
        {
            var szOfficeRegKeyVersions = string.Empty;
            var szBaseAddInKey = @"Software\Microsoft\Office\";
            var szXll32Bit = string.Empty;
            var szXll64Bit = string.Empty;
            var bFoundOffice = false;
            List<string> lstVersions;

            try
            {
                session.Log("Begin CaUnRegisterAddIn");

                szOfficeRegKeyVersions = session["OFFICEREGKEYS"];
                szXll32Bit = session["XLL32"];
                szXll64Bit = session["XLL64"];

                if (szOfficeRegKeyVersions.Length > 0)
                {
                    lstVersions = szOfficeRegKeyVersions.Split(',').ToList();

                    foreach (var szOfficeVersionKey in lstVersions)
                    {
                        // only remove keys where office version is found
                        if (Registry.CurrentUser.OpenSubKey(szBaseAddInKey + szOfficeVersionKey, false) != null)
                        {
                            bFoundOffice = true;

                            var szKeyName = szBaseAddInKey + szOfficeVersionKey + @"\Excel\Options";

                            var rkAddInKey = Registry.CurrentUser.OpenSubKey(szKeyName, true);
                            if (rkAddInKey != null)
                            {
                                var szValueNames = rkAddInKey.GetValueNames();

                                foreach (var szValueName in szValueNames)
                                {
                                    //unregister both 32 and 64 xll
                                    if (szValueName.StartsWith("OPEN") &&
                                        (rkAddInKey.GetValue(szValueName).ToString().Contains(szXll32Bit) ||
                                         rkAddInKey.GetValue(szValueName).ToString().Contains(szXll64Bit)))
                                    {
                                        rkAddInKey.DeleteValue(szValueName);
                                    }
                                }
                            }
                        }
                    }
                }

                session.Log("End CaUnRegisterAddIn");
            }
            catch (Exception ex)
            {
                session.Log(ex.Message);
            }

            return bFoundOffice ? ActionResult.Success : ActionResult.Failure;
        }

        #endregion

        #region ClosePrompt

        [CustomAction]
        public static ActionResult ClosePrompt(Session session)
        {
            session.Log("Begin PromptToCloseApplications");
            try
            {
                var productName = session["ProductName"];
                var processes = session["PromptToCloseProcesses"].Split(',');
                var displayNames = session["PromptToCloseDisplayNames"].Split(',');

                if (processes.Length != displayNames.Length)
                {
                    session.Log(
                        @"Please check that 'PromptToCloseProcesses' and 'PromptToCloseDisplayNames' exist and have same number of items.");
                    return ActionResult.Failure;
                }

                for (var i = 0; i < processes.Length; i++)
                {
                    session.Log("Prompting process {0} with name {1} to close.", processes[i], displayNames[i]);
                    using (var prompt = new PromptCloseApplication(productName, processes[i], displayNames[i]))
                    {
                        if (!prompt.Prompt())
                        {
                            return ActionResult.Failure;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                session.Log(
                    "Missing properties or wrong values. Please check that 'PromptToCloseProcesses' and 'PromptToCloseDisplayNames' exist and have same number of items. \nException:" +
                    ex.Message);
                return ActionResult.Failure;
            }

            session.Log("End PromptToCloseApplications");
            return ActionResult.Success;
        }

        #endregion

        #region GetAddInName

        public static string GetAddInName(string szXll32Name, string szXll64Name, string szOfficeVersionKey,
            double nVersion)
        {
            var szXllToRegister = string.Empty;

            if (nVersion >= 14)
            {
                // determine if office is 32-bit or 64-bit
                var localMachineRegistry = // 64bit machines need to determine correct hive.
                    RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,
                        Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32);
                var rkBitness =
                    localMachineRegistry.OpenSubKey(@"Software\Microsoft\Office\" + szOfficeVersionKey + @"\Outlook",
                        false);
                if (rkBitness != null)
                {
                    var oBitValue = rkBitness.GetValue("Bitness");
                    if (oBitValue != null)
                    {
                        if (oBitValue.ToString() == "x64")
                        {
                            szXllToRegister = szXll64Name;
                        }
                        else
                        {
                            szXllToRegister = szXll32Name;
                        }
                    }
                    else
                    {
                        szXllToRegister = szXll32Name;
                    }
                }
                else
                {
                    if (Environment.Is64BitOperatingSystem)
                    {
                        localMachineRegistry = //64bit machines need to check 32bit registry too!
                            RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
                        rkBitness =
                            localMachineRegistry.OpenSubKey(
                                @"Software\Microsoft\Office\" + szOfficeVersionKey + @"\Outlook", false);
                        if (rkBitness != null)
                        {
                            var oBitValue = rkBitness.GetValue("Bitness");
                            if (oBitValue != null)
                            {
                                if (oBitValue.ToString() == "x64")
                                {
                                    szXllToRegister = szXll64Name;
                                }
                                else
                                {
                                    szXllToRegister = szXll32Name;
                                }
                            }
                            else
                            {
                                szXllToRegister = szXll32Name;
                            }
                        }
                        else
                        {
                            szXllToRegister = szXll32Name;
                        }
                    }
                    else
                        szXllToRegister = szXll32Name;
                }
            }
            else
            {
                szXllToRegister = szXll32Name;
            }

            return szXllToRegister;
        }

        #endregion

        #endregion
    }
}


text:
#ifndef ORGANIZER_UDATEWIDGET_H
#define ORGANIZER_UDATEWIDGET_H

#include <QtWidgets/QDialog>
#include <QtWidgets/QCalendarWidget>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QTimeEdit>
#include <utils/widgets/dates/UDateItem.h>
#include "UDatesWidget.h"

class UDatesWidget;

class UDateItem;

class UDateDialog : public QDialog {
    QCalendarWidget *date;
    QLineEdit *l_name;

    bool is_with_name;

public:
    explicit UDateDialog(bool with_name = false, UDateItem *item = nullptr);

    static QString setDate(UDatesWidget *wgt, UDateItem *item);
};

#endif //ORGANIZER_UDATEWIDGET_H


text:
using System;
using System.Collections.Generic;
using System.Reflection;

namespace Boo.Lang.Runtime.DynamicDispatching
{
	public class PropertyDispatcherFactory : AbstractDispatcherFactory
	{
		public PropertyDispatcherFactory(ExtensionRegistry extensions, object target, Type type, string name, params object[] arguments) : base(extensions, target, type, name, arguments)
		{
		}

		public Dispatcher CreateSetter()
		{
			return Create(SetOrGet.Set);
		}

		public Dispatcher CreateGetter()
		{
			return Create(SetOrGet.Get);
		}

		private Dispatcher Create(SetOrGet gos)
		{
			MemberInfo[] candidates = _type.GetMember(_name, MemberTypes.Property|MemberTypes.Field, RuntimeServices.DefaultBindingFlags);
			if (candidates.Length == 0) return FindExtension(GetCandidateExtensions(gos));
			if (candidates.Length > 1) throw new AmbiguousMatchException(Builtins.join(candidates, ", "));
			return EmitDispatcherFor(candidates[0], gos);
		}

		private Dispatcher FindExtension(IEnumerable<MethodInfo> candidates)
		{
			CandidateMethod found = ResolveExtension(candidates);
			if (null != found) return EmitExtensionDispatcher(found);
			throw MissingField();
		}

		private IEnumerable<MethodInfo> GetCandidateExtensions(SetOrGet gos)
		{
			foreach (PropertyInfo p in GetExtensions<PropertyInfo>(MemberTypes.Property))
			{
				MethodInfo m = Accessor(p, gos);
				if (null == m) continue;
				yield return m;
			}
		}

		private static MethodInfo Accessor(PropertyInfo p, SetOrGet gos)
		{
			return gos == SetOrGet.Get ? p.GetGetMethod(true) : p.GetSetMethod(true);
		}

		private Dispatcher EmitDispatcherFor(MemberInfo info, SetOrGet gos)
		{
			switch (info.MemberType)
			{
				case MemberTypes.Property:
					return EmitPropertyDispatcher((PropertyInfo) info, gos);
				default:
					return EmitFieldDispatcher((FieldInfo) info, gos);
			}
		}

		private Dispatcher EmitFieldDispatcher(FieldInfo field, SetOrGet gos)
		{
#if NO_SYSTEM_REFLECTION_EMIT
			return ReflectionBasedFieldDispatcherFor(field, gos);
#else
			if (field.IsLiteral)
				return ReflectionBasedFieldDispatcherFor(field, gos);
			return SetOrGet.Get == gos
				? new Emitters.GetFieldEmitter(field).Emit()
				: new Emitters.SetFieldEmitter(field, GetArgumentTypes()[0]).Emit();
#endif
		}

		static Dispatcher ReflectionBasedFieldDispatcherFor(FieldInfo field, SetOrGet gos)
		{
			switch (gos)
			{
				case SetOrGet.Get:
					return (target, args) => field.GetValue(target);
				case SetOrGet.Set:
					return (target, args) =>
					{
						var value = args[0];
						field.SetValue(target, RuntimeServices.Coerce(value, field.FieldType));
						return value;
					};
				default:
					throw new ArgumentException();
			}
		}

		private Dispatcher EmitPropertyDispatcher(PropertyInfo property, SetOrGet gos)
		{
			Type[] argumentTypes = GetArgumentTypes();
			MethodInfo accessor = Accessor(property, gos);
			if (null == accessor) throw MissingField();
			CandidateMethod found = ResolveMethod(argumentTypes, new MethodInfo[] { accessor });
			if (null == found) throw MissingField();

#if NO_SYSTEM_REFLECTION_EMIT
			switch (gos)
			{
				case SetOrGet.Get:
					return (target, args) => property.GetValue(target, args);
				case SetOrGet.Set:
					return (target, args) =>
					       	{
								var value = args[args.Length - 1];
								var remainingArgs = new object[args.Length - 1];
								Array.Copy(args, remainingArgs, remainingArgs.Length);
								property.SetValue(target, RuntimeServices.Coerce(value, property.PropertyType), remainingArgs);
								return value;
					       	};
				default:
					throw new ArgumentException();
			}
#else
			if (SetOrGet.Get == gos) return new Emitters.MethodDispatcherEmitter(_type, found, argumentTypes).Emit();
			return new Emitters.SetPropertyEmitter(_type, found, argumentTypes).Emit();
#endif
		}
	}
}


text:
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import {connect} from 'react-redux'

import Helmet from 'react-helmet'
import $ from 'jquery'

import {SpaceHeader} from './header'
import {SpaceToolbar} from './Toolbar/index'
import {SpaceSidebar} from './sidebar'
import {ClosedSpaceSidebar} from './closed_sidebar'
import Canvas from 'gComponents/spaces/canvas'
import {NewCalculatorForm} from 'gComponents/calculators/new'
import {EditCalculatorForm} from 'gComponents/calculators/edit'
import {CalculatorCompressedShow} from 'gComponents/calculators/show/CalculatorCompressedShow'
import {ButtonCloseText} from 'gComponents/utility/buttons/close'
import {ButtonEditText, ButtonDeleteText, ButtonExpandText} from 'gComponents/utility/buttons/button'
import {FactListContainer} from 'gComponents/facts/list/container'
import {Tutorial} from './Tutorial/index'

import {denormalizedSpaceSelector} from '../denormalized-space-selector'

import {allowEdits, forbidEdits, clearEditsAllowed} from 'gModules/canvas_state/actions'
import * as spaceActions from 'gModules/spaces/actions'
import * as simulationActions from 'gModules/simulations/actions'
import * as copiedActions from 'gModules/copied/actions'
import * as calculatorActions from 'gModules/calculators/actions'
import * as userActions from 'gModules/users/actions'
import {removeSelectedMetrics} from 'gModules/metrics/actions'
import {undo, redo} from 'gModules/checkpoints/actions'
import {navigateFn} from 'gModules/navigation/actions'

import {parseSlurp} from 'lib/slurpParser'

import e from 'gEngine/engine'

import * as elev from 'servers/elev/index'

import './style.css'

function mapStateToProps(state) {
  return {
    me: state.me
  }
}

const PT = PropTypes

const CLOSED = 0
const NEW_CALCULATOR_FORM = 1
const EDIT_CALCULATOR_FORM = 2
const SHOW_CALCULATOR = 3
const FACT_SIDEBAR = 4

const ShowCalculatorHeader = ({id, editableByMe, onEdit, onDelete, onClose}) => (

        <ButtonExpandText onClick={navigateFn(`/calculators/${id}`)}/>
        {editableByMe && <ButtonEditText onClick={onEdit}/>}
        {editableByMe && <ButtonDeleteText onClick={onDelete}/>}
        <ButtonCloseText onClick={onClose}/>

)

const CalculatorFormHeader = ({isNew, onClose}) => (

{`${isNew ? 'New' : 'Edit'} Calculator`}

<ButtonCloseText onClick={onClose}/>

)

const FactSidebarHeader = ({onClose, organizationId}) => (

 Metric Library

      <ButtonExpandText onClick={navigateFn(`/organizations/${organizationId}/facts`)}/>

<ButtonCloseText onClick={onClose}/>

)

@connect(mapStateToProps)
@connect(denormalizedSpaceSelector)
export default class SpacesShow extends Component {
  displayName: 'RepoDetailPage'

  static propTypes = {
    dispatch: PT.func.isRequired,
    spaceId: PT.number,
    denormalizedSpace: PT.object,
    embed: PT.bool
  }

  state = {
    showLeftSidebar: true,
    showTutorial: !!_.get(this, 'props.me.profile.needs_tutorial'),
    attemptedFetch: false,
    rightSidebar: {
      type: !!this.props.showCalculatorId ? SHOW_CALCULATOR : !!this.props.factsShown ? FACT_SIDEBAR : CLOSED,
      showCalculatorResults: this.props.showCalculatorResults,
      showCalculatorId: this.props.showCalculatorId,
    },
  }

  componentWillMount() {
    window.recorder.recordMountEvent(this)

    this.considerFetch(this.props)
    this.props.dispatch(clearEditsAllowed())
    if (!(this.props.embed || this.state.rightSidebar.type !== CLOSED)) { elev.show() }
  }

  openTutorial() {
    this.setState({showTutorial: true})
  }
  closeTutorial() {
    if (!!_.get(this, 'props.me.profile.needs_tutorial')) { this.props.dispatch(userActions.finishedTutorial(this.props.me.profile)) }
    this.setState({showTutorial: false})
  }

  componentWillUnmount() {
    window.recorder.recordUnmountEvent(this)

    if (!this.props.embed) { elev.hide() }
  }

  componentWillUpdate() {
    window.recorder.recordRenderStartEvent(this)
    if (this.props.embed) { $('#intercom-container').remove() }
  }

  componentDidUpdate(prevProps) {
    window.recorder.recordRenderStopEvent(this)

    this.considerFetch(prevProps)
  }

  considerFetch({denormalizedSpace: space}) {
    if (this.state.attemptedFetch) { return }

    const hasGraph = _.has(space, 'graph')
    const hasData = hasGraph && e.space.prepared(space)

    if (!hasData) {
      this.props.dispatch(spaceActions.fetchById(this._id(), this.props.shareableLinkToken))
      this.setState({attemptedFetch: true})
    }
  }

  onSave() {
    this.props.dispatch(spaceActions.update(this._id()))
  }

  onRedo() {
    this.props.dispatch(redo(this._id()))
  }

  onUndo() {
    this.props.dispatch(undo(this._id()))
  }

  destroy() {
    this.props.dispatch(spaceActions.destroy(this.props.denormalizedSpace))
  }

  onImportSlurp(slurpObj) {
    const space = this.props.denormalizedSpace

    const spaceUpdates = parseSlurp(slurpObj, space)
    if (!space.name || !space.description) {
      let nonGraphUpdates = {}
      if (!space.name) {nonGraphUpdates.name = spaceUpdates.name}
      if (!space.description) {nonGraphUpdates.description = spaceUpdates.description}
      this.props.dispatch(spaceActions.update(this._id(), nonGraphUpdates))
    }
    if (!_.isEmpty(spaceUpdates.newMetrics)) {
      this.props.dispatch({type: 'ADD_METRICS', items: spaceUpdates.newMetrics, newGuesstimates: spaceUpdates.newGuesstimates})
      this.props.dispatch(spaceActions.updateGraph(this._id()))
      this.props.dispatch(simulationActions.runSimulations({spaceId: this._id(), simulateSubset: spaceUpdates.newMetrics.map(m => m.id)}))
    }
  }

  onPublicSelect() { this.props.dispatch(spaceActions.generalUpdate(this._id(), {is_private: false})) }
  onPrivateSelect() { this.props.dispatch(spaceActions.generalUpdate(this._id(), {is_private: true})) }

  onEnableShareableLink() { this.props.dispatch(spaceActions.enableShareableLink(this._id())) }
  onDisableShareableLink() { this.props.dispatch(spaceActions.disableShareableLink(this._id())) }
  onRotateShareableLink() { this.props.dispatch(spaceActions.rotateShareableLink(this._id())) }

  onSaveName(name) { this.props.dispatch(spaceActions.update(this._id(), {name})) }
  onSaveDescription(description) { this.props.dispatch(spaceActions.update(this._id(), {description})) }

  hideLeftSidebar() {
    this.setState({showLeftSidebar: false})
  }
  openLeftSidebar() {
    this.setState({showLeftSidebar: true})
  }

  _handleCopyModel() {
    this.props.dispatch(spaceActions.copy(this._id()))
  }

  onCopy() {
    this.props.dispatch(copiedActions.copy(this._id()))
  }

  onPaste() {
    this.props.dispatch(copiedActions.paste(this._id()))
  }

  onDeleteMetrics() {
    this.props.dispatch(removeSelectedMetrics(this.props.spaceId))
  }

  onCut() {
    this.props.dispatch(copiedActions.cut(this._id()))
  }

  _id() {
    return parseInt(this.props.spaceId)
  }

  canUseOrganizationFacts() {
    const organization = _.get(this, 'props.denormalizedSpace.organization')
    if (!organization) { return false }

    const orgHasPrivateAccess = e.organization.hasPrivateAccess(organization)
    const isPrivate = _.get(this, 'props.denormalizedSpace.is_private')
    return !!isPrivate && orgHasPrivateAccess
  }

  closeRightSidebar() {
    elev.show()
    this.setState({rightSidebar: {type: CLOSED}})
  }
  openRightSidebar(rightSidebarState) {
    elev.hide()
    this.setState({rightSidebar: rightSidebarState})
  }
  showCalculator({id}) { this.openRightSidebar({type: SHOW_CALCULATOR, showCalculatorId: id}) }
  editCalculator(id) { this.openRightSidebar({type: EDIT_CALCULATOR_FORM, editCalculatorId: id}) }
  deleteCalculator(id) {
    this.props.dispatch(calculatorActions.destroy(id))
    this.closeRightSidebar()
  }
  makeNewCalculator() { this.openRightSidebar({type: NEW_CALCULATOR_FORM}) }
  toggleFactSidebar() {
    if (this.state.rightSidebar.type !== FACT_SIDEBAR) { this.openRightSidebar({type: FACT_SIDEBAR}) }
    else { this.closeRightSidebar() }
  }

  rightSidebarBody() {
    const {
      props: {denormalizedSpace, spaceId, organizationFacts},
      state: {rightSidebar: {type, showCalculatorResults, showCalculatorId, editCalculatorId}},
    } = this
    const {editableByMe, calculators, organization, imported_fact_ids} = denormalizedSpace
    switch (type) {
      case CLOSED:
        return {}
      case SHOW_CALCULATOR:
        return {
          classes: [],
          header: (
            <ShowCalculatorHeader
              editableByMe={editableByMe}
              id={showCalculatorId}
              onEdit={this.editCalculator.bind(this, showCalculatorId)}
              onDelete={this.deleteCalculator.bind(this, showCalculatorId)}
              onClose={this.closeRightSidebar.bind(this)}
            />
          ),
          main: <CalculatorCompressedShow calculatorId={showCalculatorId} startFilled={showCalculatorResults}/>,
        }
      case EDIT_CALCULATOR_FORM:
        return {
          classes: [],
          header: <CalculatorFormHeader isNew={false} onClose={this.closeRightSidebar.bind(this)}/>,
          main: (
            <EditCalculatorForm
              space={denormalizedSpace}
              calculator={calculators.find(c => c.id === editCalculatorId)}
              onCalculatorSave={this.showCalculator.bind(this)}
            />
          ),
        }
      case NEW_CALCULATOR_FORM:
        return {
          classes: [],
          header: <CalculatorFormHeader isNew={true} onClose={this.closeRightSidebar.bind(this)}/>,
          main: (
            <NewCalculatorForm
              space={denormalizedSpace}
              onCalculatorSave={this.showCalculator.bind(this)}
            />
          ),
        }
      case FACT_SIDEBAR:
        return {
          classes: ['grey'],
          header: (
            <FactSidebarHeader
              onClose={this.closeRightSidebar.bind(this)}
              organizationId={organization.id}
            />
          ),
          main: (

              <FactListContainer
                existingVariableNames={organizationFacts.map(e.facts.getVar)}
                facts={organizationFacts}
                organization={organization}
                canMakeNewFacts={true}
                spaceId={spaceId}
                imported_fact_ids={imported_fact_ids}
              />

          ),
        }
    }
  }

  rightSidebar() {
    if (this.state.rightSidebar.type === CLOSED) { return false }
    const {classes, header, main} = this.rightSidebarBody()

    return (

{header}

        {main}

    )
  }

  render() {
    const {exportedFacts, organizationHasFacts, me} = this.props
    const space = this.props.denormalizedSpace

    if (!e.space.prepared(space)) { return

 }

    const sidebarIsViseable = space.editableByMe || !_.isEmpty(space.description)
    const isLoggedIn = e.me.isLoggedIn(this.props.me)
    const shareableLinkUrl = e.space.urlWithToken(space)

    if (this.props.embed) {
      return (

          <Canvas
            denormalizedSpace={space}
            canUseOrganizationFacts={this.canUseOrganizationFacts()}
            exportedFacts={exportedFacts}
            overflow={'hidden'}
            screenshot={true}
          />

      )
    }

    const hasOrg = _.has(space, 'organization.name')
    const owner = hasOrg ? space.organization : space.user
    const {users} = space
    const ownerUrl = hasOrg ? e.organization.url(space.organization) : e.user.url(space.user)

    const canBePrivate = hasOrg ? e.organization.canMakeMorePrivateModels(space.organization) : e.me.canMakeMorePrivateModels(this.props.me)

    const authorCallout = `Made by ${owner.name}`
    const tagDescription = _.isEmpty(space.description) ? authorCallout : `${authorCallout}: ${space.description}`

    return (

        {!space.name &&
          <Helmet
            meta={[
              {name: 'Description', content: tagDescription},
              {property: 'og:description', content: tagDescription},
              {property: 'og:site_name', content: 'Guesstimate'},
              {property: 'og:image', content: space.big_screenshot},
            ]}
          />
        }
        {space.name &&
          <Helmet
            title={space.name}
            meta={[
              {name: 'Description', content: tagDescription},
              {property: 'og:title', content: space.name},
              {property: 'og:description', content: tagDescription},
              {property: 'og:site_name', content: 'Guesstimate'},
              {property: 'og:image', content: space.big_screenshot},
            ]}
          />
        }
        {this.state.showTutorial && <Tutorial onClose={this.closeTutorial.bind(this)} />}

          <SpaceHeader
            name={space.name}
            isPrivate={space.is_private}
            editableByMe={space.editableByMe}
            canBePrivate={canBePrivate}
            shareableLinkUrl={shareableLinkUrl}
            ownerName={owner.name}
            ownerPicture={owner.picture}
            ownerUrl={ownerUrl}
            ownerIsOrg={hasOrg}
            editors={users}
            onSaveName={this.onSaveName.bind(this)}
            onPublicSelect={this.onPublicSelect.bind(this)}
            onPrivateSelect={this.onPrivateSelect.bind(this)}
            onEnableShareableLink={this.onEnableShareableLink.bind(this)}
            onDisableShareableLink={this.onDisableShareableLink.bind(this)}
            onRotateShareableLink={this.onRotateShareableLink.bind(this)}
          />

          <SpaceToolbar
            editsAllowed={space.canvasState.editsAllowedManuallySet ? space.canvasState.editsAllowed : space.editableByMe}
            onAllowEdits={() => {
              this.props.dispatch(allowEdits())
            }}
            onForbidEdits={() => {
              this.props.dispatch(forbidEdits())
            }}
            isLoggedIn={isLoggedIn}
            onDestroy={this.destroy.bind(this)}
            onCopyModel={this._handleCopyModel.bind(this)}
            onCopyMetrics={this.onCopy.bind(this, false)}
            onPasteMetrics={this.onPaste.bind(this, false)}
            onDeleteMetrics={this.onDeleteMetrics.bind(this)}
            onCutMetrics={this.onCut.bind(this, false)}
            isPrivate={space.is_private}
            editableByMe={space.editableByMe}
            actionState={space.canvasState.actionState}
            onUndo={this.onUndo.bind(this)}
            onRedo={this.onRedo.bind(this)}
            canUndo={space.checkpointMetadata.head !== space.checkpointMetadata.length - 1}
            canRedo={space.checkpointMetadata.head !== 0}
            onImportSlurp={this.onImportSlurp.bind(this)}
            calculators={space.calculators}
            makeNewCalculator={this.makeNewCalculator.bind(this)}
            showCalculator={this.showCalculator.bind(this)}
            toggleFactSidebar={this.toggleFactSidebar.bind(this)}
            canShowFactSidebar={this.canUseOrganizationFacts()}
            onOpenTutorial={this.openTutorial.bind(this)}
          />

          {sidebarIsViseable && this.state.showLeftSidebar &&
            <SpaceSidebar
              description={space.description}
              canEdit={space.editableByMe}
              onClose={this.hideLeftSidebar.bind(this)}
              onSaveDescription={this.onSaveDescription.bind(this)}
            />
          }
          {sidebarIsViseable && !this.state.showLeftSidebar &&
            <ClosedSpaceSidebar onOpen={this.openLeftSidebar.bind(this)}/>
          }
          <Canvas
            canUseOrganizationFacts={this.canUseOrganizationFacts()}
            exportedFacts={exportedFacts}
            denormalizedSpace={space}
            onCopy={this.onCopy.bind(this, true)}
            onPaste={this.onPaste.bind(this, true)}
            onCut={this.onCut.bind(this, true)}
          />
          {this.rightSidebar()}

    )
  }
}


text:
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use backend\assets\AppAsset;

/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \common\models\LoginForm */
AppAsset::register($this);
?>
<?php $this->beginPage() ?>
    <!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Banana Bandy | Admin Login</title>
        <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
        <?php $this->head() ?>

    <?php $this->beginBody() ?>

            <a href="<?= Yii::$app->homeUrl;?>">BananaBandy

                Please fill out the following fields to login:

            <?php $form = ActiveForm::begin(['id' => 'login-form']); ?>

                <?= $form->field($model, 'email', [
                    'template' => "{input}\n{hint}\n{error}"
                ])->textInput(array('placeholder' => 'Email'))->label(false); ?>

                <?= $form->field($model, 'password', [
                    'template' => "{input}\n{hint}\n{error}"
                ])->passwordInput(array('placeholder' => 'Password'))->label(false); ?>

                    <?= $form->field($model, 'rememberMe')->checkbox() ?>

                    <?= Html::submitButton('Login', ['class' => 'btn btn-primary btn-block btn-flat', 'name' => 'login-button']) ?>

            <?php ActiveForm::end(); ?>

    <?php $this->endBody() ?>

<?php $this->endPage() ?>


text:
import {forOwn, isObject, takeRight, last, initial} from 'lodash';
import {Graph} from 'graphlib';
import {fulex} from '../utils/utils.js';
import {getAvailableRoute} from './reactRouterApi.js';
import {mapModel, mapModelForNode, makeNodeWrapper, traverseGraphBranch, adjustIndices} from './graphUtils.js';
import {detachGraphNode, detachGraphNodes, copyGraphNode, copyGraphNodes} from './graphUtils.js';

let bufferKey = undefined;

let graphObject = {
	graph: undefined,
	model: undefined,
	pageNodes: []
};

let history = [];

export function pushHistory(pagePath) {
	if (history.length >= 50) {
		history = takeRight(history, 50);
	}
	history.push({
		model: fulex(graphObject.model),
		markedKeys: getAllMarkedKeys(),
		pagePath: pagePath
	});
}

export function popHistory() {
	if (history.length > 0) {
		const historyObject = last(history);
		initGraph(historyObject.model);
		history = initial(history);
		return historyObject;
	}
	return undefined;
}

export function getHistorySize() {
	return history.length;
}

export function initGraph(initialModel) {
	if (graphObject.graph) {
		delete graphObject.graph;
	}
	if (graphObject.model) {
		delete graphObject.model;
	}
	if (graphObject.pageNodes) {
		delete graphObject.pageNodes;
	}
	graphObject.model = fulex(initialModel);
	if (graphObject.model && graphObject.model.pages && graphObject.model.pages.length > 0) {
		graphObject.graph = new Graph({compound: true});
		graphObject.graph.setDefaultEdgeLabel('link');
		graphObject.pageNodes = [];
		let pageKey;
		graphObject.model.pages.forEach((page, index) => {
			pageKey = mapModel(graphObject.graph, page, index);
			graphObject.pageNodes.push({
				pagePath: page.pagePath,
				pageName: page.pageName,
				pageKey: pageKey
			});
		});
	}
}

export function getGraph() {
	return graphObject.graph;
}

export function getModel() {
	return graphObject.model;
}

export function getPages() {
	return graphObject.pageNodes;
}

export function getNode(key) {
	return graphObject.graph.node(key);
}

export function getPagePath(pathname) {
	let paths = [];
	graphObject.pageNodes.forEach(pageNode => {
		paths.push(pageNode.pagePath);
	});
	return getAvailableRoute(paths, pathname);
}

export function getPageModelByPagePath(pathname) {
	let found = undefined;
	if (graphObject.model && graphObject.model.pages) {
		found = graphObject.model.pages.find(page => page.pagePath === pathname);
	}
	return found;
}

export function getWrappedModelByPagePath(pathname) {
	let wrappedModel = undefined;
	let paths = [];
	graphObject.pageNodes.forEach(pageNode => {
		paths.push(pageNode.pagePath);
	});
	const path = getAvailableRoute(paths, pathname);
	const pageNode = graphObject.pageNodes.find(pageNode => {
		return pageNode.pagePath === path;
	});
	if (pageNode) {
		wrappedModel = traverseGraph(pageNode.pageKey);
	}
	return wrappedModel;
}

export function getMarkedKeysByPagePath(pathname) {
	let paths = [];
	graphObject.pageNodes.forEach(pageNode => {
		paths.push(pageNode.pagePath);
	});
	const path = getAvailableRoute(paths, pathname);
	const pageNode = graphObject.pageNodes.find(pageNode => {
		return pageNode.pagePath === path;
	});
	return getMarkedKeys(pageNode ? pageNode.pageKey : undefined);
}

export function getChildNodes(key) {
	let result = [];
	const children = graphObject.graph.children(key);
	if (children && children.length > 0) {
		children.forEach(child => {
			result.push(makeNodeWrapper(child, graphObject.graph.node(child)));
		});
		result.sort((a, b) => a.index - b.index);
	}
	return result;
}

export function hasNode(key) {
	return graphObject.graph.hasNode(key);
}

function traverseGraph(rootNodeKey, result) {
	const {graph} = graphObject;
	let rootNode = graph.node(rootNodeKey);
	if (rootNode) {
		let resultNode = makeNodeWrapper(rootNodeKey, rootNode);
		const parentKey = graph.parent(rootNodeKey);
		if (!parentKey) {
			resultNode.isRoot = true;
		}
		let children = graph.children(rootNodeKey);
		if (children && children.length > 0) {
			children.forEach(child => {
				traverseGraph(child, resultNode);
			});
			if (resultNode.children && resultNode.children.length > 0) {
				resultNode.children.sort((a, b) => a.index - b.index);
			}
		}
		if (!result) {
			result = resultNode;
		} else if (rootNode.prop) {
			result.props = result.props || {};
			result.props[rootNode.prop] = resultNode;
		} else {
			result.children = result.children || [];
			result.children.push(resultNode);
		}
	}
	return result;
}

export function traverseAllGraph() {
	const {pageNodes} = graphObject;
	let result = [];
	pageNodes.forEach(pNode => {
		result = result.concat(traverseGraph(pNode.pageKey));
	});
	return result;
}

export function getParentsList(childNodeKey, result) {
	const {graph} = graphObject;
	let childNode = graph.node(childNodeKey);
	if (childNode) {
		let childModelNode = makeNodeWrapper(childNodeKey, childNode);
		result = result || [];
		result.push(childModelNode);
		const parentNodeKey = graph.parent(childNodeKey);
		if (parentNodeKey) {
			getParentsList(parentNodeKey, result);
		} else {
			childModelNode.isRoot = true;
		}
	}
	return result;
}

export function changePagePathAndName(pagePath, nextPagePath, nextPageName) {
	const {graph, pageNodes} = graphObject;
	const pageNode = pageNodes.find(pNode => {
		return pNode.pagePath === pagePath;
	});
	if (!pageNode) {
		throw Error('Change page path and name: specified path ' + pagePath + ' was not found.');
	}
	let rootNode = graph.node(pageNode.pageKey);
	if (rootNode) {
		let modelNode = rootNode.modelNode;
		modelNode.pageName = nextPageName;
		modelNode.pagePath = nextPagePath;
		pageNode.pageName = nextPageName;
		pageNode.pagePath = nextPagePath;
	}
	return graphObject.pageNodes;
}

export function addNewPage(initialModel, pagePath, pageName) {
	let {graph, model, pageNodes} = graphObject;
	let pageModel = fulex(initialModel);
	pageModel.pagePath = pagePath;
	pageModel.pageName = pageName;
	model.pages.push(pageModel);
	const pageKey = mapModel(graph, pageModel, pageNodes.length, true);
	pageNodes.push({
		pagePath: pagePath,
		pageName: pageName,
		pageKey: pageKey
	});
	return pageNodes;
}

export function duplicatePage(pagePath, nextPagePath, nextPageName) {
	let {graph, model, pageNodes} = graphObject;
	const pageNode = pageNodes.find(pNode => {
		return pNode.pagePath === pagePath;
	});
	if (!pageNode) {
		throw Error('Duplicate page: specified path ' + pagePath + ' was not found.');
	}
	let rootNode = graph.node(pageNode.pageKey);
	if (rootNode) {
		let pageModel = fulex(rootNode.modelNode);
		pageModel.pagePath = nextPagePath;
		pageModel.pageName = nextPageName;
		model.pages.push(pageModel);
		const pageKey = mapModel(graph, pageModel, pageNodes.length, true);
		pageNodes.push({
			pagePath: pageModel.pagePath,
			pageName: pageModel.pageName,
			pageKey: pageKey
		});
	}
	return pageNodes;
}

export function setIndexPage(pagePath) {
	let {graph, model, pageNodes} = graphObject;

	const pageNode = pageNodes.find(pNode => {
		return pNode.pagePath === pagePath;
	});
	if (!pageNode) {
		throw Error('Set index page: specified path ' + pagePath + ' was not found.');
	}

	let rootNode = graph.node(pageNode.pageKey);
	if (rootNode) {
		const tempModel = model.pages.splice(rootNode.index, 1)[0];
		if (tempModel) {
			model.pages.splice(0, 0, tempModel);
		} else {
			console.error('Page model was not found in pages model index: ' + rootNode.index);
		}
		let newPageNodes = [];
		let newPageNode;
		let graphNode;
		model.pages.forEach((page, index) => {
			newPageNode = pageNodes.find(pNode => {
				return pNode.pagePath === page.pagePath;
			});
			if (newPageNode) {
				graphNode = graph.node(newPageNode.pageKey);
				graphNode.index = index;
				newPageNodes.push(newPageNode);
			}
		});
		graphObject.pageNodes = newPageNodes;
	}
	return graphObject.pageNodes;
}

export function deletePage(pagePath) {
	let {graph, model, pageNodes} = graphObject;

	if (model.pages && model.pages.length === 1) {
		throw Error('The current page is the only page in the project and can not be deleted.');
	}

	const pageNode = pageNodes.find(pNode => {
		return pNode.pagePath === pagePath;
	});
	if (!pageNode) {
		throw Error('Delete page: specified path ' + pagePath + ' was not found.');
	}

	let rootNode = graph.node(pageNode.pageKey);
	if (rootNode) {
		model.pages.splice(rootNode.index, 1);
		traverseGraphBranch(graph, pageNode.pageKey, (nodeKey => {
			graph.removeNode(nodeKey);
		}));

		let newPageNodes = [];
		let newPageNode;
		let graphNode;
		model.pages.forEach((page, index) => {
			newPageNode = pageNodes.find(pNode => {
				return pNode.pagePath === page.pagePath;
			});
			if (newPageNode) {
				graphNode = graph.node(newPageNode.pageKey);
				graphNode.index = index;
				newPageNodes.push(newPageNode);
			}
		});
		graphObject.pageNodes = newPageNodes;
	}
	return graphObject.pageNodes;
}

function getDetachedKeysForCutting() {
	const {graph, pageNodes} = graphObject;
	const testFunc = node => node.isForCutting;
	let detachedKeys = [];
	pageNodes.forEach(pNode => {
		detachGraphNodes(graph, pNode.pageKey, testFunc, detachedKeys);
	});
	return detachedKeys;
}

function getDetachedKeysForCopying() {
	const {graph, pageNodes} = graphObject;
	const testFunc = node => node.isForCopying;
	let detachedKeys = [];
	pageNodes.forEach(pNode => {
		copyGraphNodes(graph, pNode.pageKey, testFunc, detachedKeys);
	});
	return detachedKeys;
}

export function isCutPasteAvailable(nodeKey) {
	let childNode = graphObject.graph.node(nodeKey);
	return !!(childNode && !childNode.isForCuttingChild && !childNode.isForCutting);
}

export function cutPasteBeforeOrAfter(isAfter) {
	const {selected} = getAllMarkedKeys();
	let resultKeys = [];
	if (selected && selected.length === 1 && isCutPasteAvailable(selected[0])) {
		const {graph} = graphObject;
		const nodeKey = selected[0];
		const node = graph.node(nodeKey);
		if (!node) {
			console.error('Cut & paste before or after node: node with key ' + nodeKey + ' was not found.');
		} else if (!node.prop) {
			let detachedKeys = getDetachedKeysForCutting();
			if (detachedKeys.length > 0) {
				const parentKey = graph.parent(nodeKey);
				if (parentKey) {
					let detachedModelNodes = [];
					let detachedNode;
					detachedKeys.forEach(detachedKey => {
						detachedNode = graph.node(detachedKey);
						if (detachedNode && detachedNode.modelNode) {
							graph.setParent(detachedKey, parentKey);
							detachedModelNodes.push(detachedNode.modelNode);
						}
					});
					let parentNode = graph.node(parentKey);
					let {modelNode} = parentNode;
					let modelNodesArgs = [node.index + (isAfter ? 1 : 0), 0].concat(detachedModelNodes);
					modelNode.children.splice.apply(modelNode.children, modelNodesArgs);
					adjustIndices(graph, parentKey);
				}
			}
			resultKeys = resultKeys.concat(detachedKeys);
		} else {
			resultKeys.push(nodeKey);
		}
	} else {
		console.error('Cut & paste before or after node: pasting can not be provided for the same component or its children, or a multiple selection');
	}
	return resultKeys;
}

export function cutPasteFirstOrLast(isFirst) {
	const {selected} = getAllMarkedKeys();
	let resultKeys = [];
	if (selected && selected.length === 1 && isCutPasteAvailable(selected[0])) {
		const {graph} = graphObject;
		const nodeKey = selected[0];
		const node = graph.node(nodeKey);
		if (!node) {
			console.error('Cut & paste first or last node: node with key ' + nodeKey + ' was not found.');
		} else {
			let detachedKeys = getDetachedKeysForCutting();
			if (detachedKeys.length > 0) {
				let detachedModelNodes = [];
				let detachedNode;
				detachedKeys.forEach(detachedKey => {
					detachedNode = graph.node(detachedKey);
					if (detachedNode && detachedNode.modelNode) {
						graph.setParent(detachedKey, nodeKey);
						detachedModelNodes.push(detachedNode.modelNode);
					}
				});
				let {modelNode} = node;
				modelNode.children = modelNode.children || [];
				const lastIndex = modelNode.children.length > 0 ? modelNode.children.length : 0;
				let modelNodesArgs = [(isFirst ? 0 : lastIndex), 0].concat(detachedModelNodes);
				modelNode.children.splice.apply(modelNode.children, modelNodesArgs);
				adjustIndices(graph, nodeKey);
			}
			resultKeys = resultKeys.concat(detachedKeys);
		}
	} else {
		console.error('Cut & paste first or last node: pasting can not be provided for the same component or its children, or a multiple selection');
	}
	return resultKeys;
}

export function cutPasteReplace() {
	const {selected} = getAllMarkedKeys();
	let resultKeys = [];
	if (selected && selected.length === 1 && isCutPasteAvailable(selected[0])) {
		const {graph} = graphObject;
		const nodeKey = selected[0];
		const node = graph.node(nodeKey);
		if (!node) {
			console.error('Cut & paste replace: node with key ' + nodeKey + ' was not found.');
		} else if (!node.prop) {
			let detachedKeys = getDetachedKeysForCutting();
			if (detachedKeys.length > 0) {
				const parentKey = graph.parent(nodeKey);
				if (parentKey) {
					const nodeIndex = node.index;
					traverseGraphBranch(graph, nodeKey, (key => {
						graph.removeNode(key);
					}));
					delete node.modelNode;
					let detachedModelNodes = [];
					let detachedNode;
					detachedKeys.forEach(detachedKey => {
						detachedNode = graph.node(detachedKey);
						if (detachedNode && detachedNode.modelNode) {
							graph.setParent(detachedKey, parentKey);
							detachedModelNodes.push(detachedNode.modelNode);
						}
					});
					let parentNode = graph.node(parentKey);
					let {modelNode} = parentNode;
					modelNode.children = modelNode.children || [];
					let modelNodesArgs = [nodeIndex, 1].concat(detachedModelNodes);
					modelNode.children.splice.apply(modelNode.children, modelNodesArgs);
					adjustIndices(graph, parentKey);
				}
			}
			resultKeys = resultKeys.concat(detachedKeys);
		} else {
			resultKeys.push(nodeKey);
		}
	} else {
		console.error('Cut & paste replace: replacing can not be provided for the same component or a multiple selection');
	}
	return resultKeys;
}

//export function cutPasteWrap(nodeKey){
//    if(!isCutPasteAvailable(nodeKey)){
//        throw Error('Node with key ' + nodeKey + ' is not available to cut & paste operation.');
//    }
//    const {graph} = graphObject;
//    const node = graph.node(nodeKey);
//    if(!node){
//        throw Error('Cut & paste wrap: node with key ' + nodeKey + ' was not found.');
//    }
//    if(!node.prop){
//        const { forCutting } = getAllMarkedKeys();
//        if(forCutting.length !== 1){
//            throw Error('Cut & paste wrap: wrapping can be applied only for single component');
//        }
//        const pastedKeys = cutPasteBeforeOrAfter(nodeKey, false);
//        removeForCutting(pastedKeys[0]);
//        setForCutting(nodeKey);
//        cutPasteFirstOrLast(pastedKeys[0], false);
//        removeForCutting(nodeKey);
//        return pastedKeys;
//    } else {
//        return [nodeKey];
//    }
//}

export function copyPasteBeforeOrAfter(isAfter) {
	const {selected} = getAllMarkedKeys();
	const {graph} = graphObject;
	let resultKeys = [];
	if (selected && selected.length > 0) {
		selected.forEach(nodeKey => {
			const node = graph.node(nodeKey);
			if (!node) {
				console.error('Copy & paste before or after node: node with key ' + nodeKey + ' was not found.');
			} else if (!node.prop) {
				let detachedKeys = getDetachedKeysForCopying();
				if (detachedKeys.length > 0) {
					const parentKey = graph.parent(nodeKey);
					if (parentKey) {
						let detachedModelNodes = [];
						let detachedNode;
						detachedKeys.forEach(detachedKey => {
							detachedNode = graph.node(detachedKey);
							if (detachedNode && detachedNode.modelNode) {
								graph.setParent(detachedKey, parentKey);
								detachedModelNodes.push(detachedNode.modelNode);
							}
						});
						let parentNode = graph.node(parentKey);
						let {modelNode} = parentNode;
						modelNode.children = modelNode.children || [];
						let modelNodesArgs = [node.index + (isAfter ? 1 : 0), 0].concat(detachedModelNodes);
						modelNode.children.splice.apply(modelNode.children, modelNodesArgs);
						adjustIndices(graph, parentKey);
					}
				}
				resultKeys = resultKeys.concat(detachedKeys);
			} else {
				resultKeys.push(nodeKey);
			}
		});
	}
	return resultKeys;
}

export function copyPasteFirstOrLast(isFirst) {
	const {selected} = getAllMarkedKeys();
	const {graph} = graphObject;
	let resultKeys = [];
	if (selected && selected.length > 0) {
		selected.forEach(nodeKey => {
			const node = graph.node(nodeKey);
			if (!node) {
				console.error('Copy & paste first or last node: node with key ' + nodeKey + ' was not found.');
			} else {
				let detachedKeys = getDetachedKeysForCopying();
				if (detachedKeys.length > 0) {

					let detachedModelNodes = [];
					let detachedNode;
					detachedKeys.forEach(detachedKey => {
						detachedNode = graph.node(detachedKey);
						if (detachedNode && detachedNode.modelNode) {
							graph.setParent(detachedKey, nodeKey);
							detachedModelNodes.push(detachedNode.modelNode);
						}
					});
					let {modelNode} = node;
					modelNode.children = modelNode.children || [];
					const lastIndex = modelNode.children.length > 0 ? modelNode.children.length : 0;
					let modelNodesArgs = [(isFirst ? 0 : lastIndex), 0].concat(detachedModelNodes);
					modelNode.children.splice.apply(modelNode.children, modelNodesArgs);
					adjustIndices(graph, nodeKey);
				}
				resultKeys = resultKeys.concat(detachedKeys);
			}
		});
	}
	return resultKeys;
}

export function copyPasteReplace() {
	const {selected, forCopying} = getAllMarkedKeys();
	const {graph} = graphObject;
	let resultKeys = [];
	if (selected && selected.length > 0) {
		selected.forEach(nodeKey => {
			if (forCopying.indexOf(nodeKey) < 0) {
				const node = graph.node(nodeKey);
				if (!node) {
					throw Error('Copy & paste replace: node with key ' + nodeKey + ' was not found.');
				} else if (!node.prop) {
					let detachedKeys = getDetachedKeysForCopying();
					if (detachedKeys.length > 0) {
						const parentKey = graph.parent(nodeKey);
						if (parentKey) {
							const nodeIndex = node.index;
							traverseGraphBranch(graph, nodeKey, (key => {
								graph.removeNode(key);
								const removedIndex = resultKeys.indexOf(key);
								if (removedIndex >= 0) {
									resultKeys.splice(removedIndex, 1);
								}
							}));
							delete node.modelNode;
							let detachedModelNodes = [];
							let detachedNode;
							detachedKeys.forEach(detachedKey => {
								detachedNode = graph.node(detachedKey);
								if (detachedNode && detachedNode.modelNode) {
									graph.setParent(detachedKey, parentKey);
									detachedModelNodes.push(detachedNode.modelNode);
								}
							});
							let parentNode = graph.node(parentKey);
							let {modelNode} = parentNode;
							modelNode.children = modelNode.children || [];
							let modelNodesArgs = [nodeIndex, 1].concat(detachedModelNodes);
							modelNode.children.splice.apply(modelNode.children, modelNodesArgs);
							adjustIndices(graph, parentKey);
						}
					}
					resultKeys = resultKeys.concat(detachedKeys);
				} else {
					resultKeys.push(nodeKey);
				}
			} else {
				console.warn('Copy & paste replace: replacing can not be provided for the same component.');
			}
		});
	}
	return resultKeys;
}
//
// export function copyPasteWrap (nodeKey) {
//   const {graph} = graphObject
//   const node = graph.node(nodeKey)
//   if (!node) {
//     throw Error('Copy & paste wrap: node with key ' + nodeKey + ' was not found.')
//   }
//   if (!node.prop) {
//     const {forCopying} = getAllMarkedKeys()
//     if (forCopying.length !== 1) {
//       throw Error('Copy & paste wrap: wrapping can be applied only for single component')
//     }
//     const pastedKeys = copyPasteBeforeOrAfter(nodeKey, false)
//     setForCutting(nodeKey)
//     cutPasteFirstOrLast(pastedKeys[0], false)
//     removeForCutting(nodeKey)
//     return pastedKeys
//   } else {
//     return [nodeKey]
//   }
// }

export function setBuffer(model) {
	const {graph} = graphObject;
	if (bufferKey) {
		removeBuffer();
	}
	const newModel = fulex(model);
	bufferKey = mapModel(graph, newModel, 0);
	return bufferKey;
}

export function removeBuffer() {
	const {graph} = graphObject;
	let childNode;
	if (bufferKey) {
		traverseGraphBranch(graph, bufferKey, childKey => {
			childNode = graph.node(childKey);
			if (childNode) {
				delete childNode.modelNode;
				graph.removeNode(childKey);
			}
		});
		bufferKey = undefined;
	}
}

export function fromBufferBeforeOrAfter(isAfter, quickKey) {
	const {selected} = getAllMarkedKeys();
	const {graph} = graphObject;
	let resultKeys = [];
	if (selected && selected.length > 0) {
		selected.forEach(nodeKey => {
			const node = graph.node(nodeKey);
			if (!node) {
				console.error('From buffer to before or after node: node with key ' + nodeKey + ' was not found.');
			} else if (!node.prop) {
				let detachedKey = copyGraphNode(graph, quickKey ? quickKey : bufferKey);
				if (detachedKey) {
					const parentKey = graph.parent(nodeKey);
					if (parentKey) {
						let detachedModelNodes = [];
						let detachedNode = graph.node(detachedKey);
						if (detachedNode && detachedNode.modelNode) {
							graph.setParent(detachedKey, parentKey);
							detachedModelNodes.push(detachedNode.modelNode);
						}
						let parentNode = graph.node(parentKey);
						let {modelNode} = parentNode;
						modelNode.children = modelNode.children || [];
						let modelNodesArgs = [node.index + (isAfter ? 1 : 0), 0].concat(detachedModelNodes);
						modelNode.children.splice.apply(modelNode.children, modelNodesArgs);
						adjustIndices(graph, parentKey);
					}
				}
				resultKeys.push(detachedKey);
			} else {
				resultKeys.push(nodeKey);
			}
		});
	}
	return resultKeys;
}

export function quickBeforeOrAfter(model, isAfter) {
	const {graph} = graphObject;
	let newModel = fulex(model);
	let quickKey = mapModel(graph, newModel, 0);
	const resultKeys = fromBufferBeforeOrAfter(isAfter, quickKey);
	let childNode;
	traverseGraphBranch(graph, quickKey, childKey => {
		childNode = graph.node(childKey);
		if (childNode) {
			delete childNode.modelNode;
			graph.removeNode(childKey);
		}
	});
	newModel = undefined;
	quickKey = undefined;
	return resultKeys;
}

export function fromBufferFirstOrLast(isFirst, quickKey) {
	const {selected} = getAllMarkedKeys();
	const {graph} = graphObject;
	let resultKeys = [];
	if (selected && selected.length > 0) {
		selected.forEach(nodeKey => {
			const node = graph.node(nodeKey);
			if (!node) {
				console.error('From buffer to first or last node: node with key ' + nodeKey + ' was not found.');
			} else {
				let detachedKey = copyGraphNode(graph, quickKey ? quickKey : bufferKey);
				if (detachedKey) {

					let detachedModelNodes = [];
					let detachedNode = graph.node(detachedKey);
					if (detachedNode && detachedNode.modelNode) {
						graph.setParent(detachedKey, nodeKey);
						detachedModelNodes.push(detachedNode.modelNode);
					}
					let {modelNode} = node;
					modelNode.children = modelNode.children || [];
					const lastIndex = modelNode.children.length > 0 ? modelNode.children.length : 0;
					let modelNodesArgs = [(isFirst ? 0 : lastIndex), 0].concat(detachedModelNodes);
					modelNode.children.splice.apply(modelNode.children, modelNodesArgs);
					adjustIndices(graph, nodeKey);
				}
				resultKeys.push(detachedKey);
			}
		});
	}
	return resultKeys;
}

export function quickFirstOrLast(model, isFirst) {
	const {graph} = graphObject;
	let newModel = fulex(model);
	let quickKey = mapModel(graph, newModel, 0);
	const resultKeys = fromBufferFirstOrLast(isFirst, quickKey);
	let childNode;
	traverseGraphBranch(graph, quickKey, childKey => {
		childNode = graph.node(childKey);
		if (childNode) {
			delete childNode.modelNode;
			graph.removeNode(childKey);
		}
	});
	newModel = undefined;
	quickKey = undefined;
	return resultKeys;
}

export function fromBufferReplace(quickKey) {
	const {selected} = getAllMarkedKeys();
	const {graph} = graphObject;
	let resultKeys = [];
	if (selected && selected.length > 0) {
		selected.forEach(nodeKey => {
			const node = graph.node(nodeKey);
			if (!node) {
				console.error('From buffer replace: node with key ' + nodeKey + ' was not found.');
			} else if (!node.prop) {
				let detachedKey = copyGraphNode(graph, quickKey ? quickKey : bufferKey);
				if (detachedKey) {
					const parentKey = graph.parent(nodeKey);
					if (parentKey) {
						const nodeIndex = node.index;
						traverseGraphBranch(graph, nodeKey, (key => {
							graph.removeNode(key);
						}));
						delete node.modelNode;
						let detachedModelNodes = [];
						let detachedNode = graph.node(detachedKey);
						if (detachedNode && detachedNode.modelNode) {
							graph.setParent(detachedKey, parentKey);
							detachedModelNodes.push(detachedNode.modelNode);
						}
						let parentNode = graph.node(parentKey);
						let {modelNode} = parentNode;
						modelNode.children = modelNode.children || [];
						let modelNodesArgs = [nodeIndex, 1].concat(detachedModelNodes);
						modelNode.children.splice.apply(modelNode.children, modelNodesArgs);
						adjustIndices(graph, parentKey);
					}
				}
				resultKeys.push(detachedKey);
			} else {
				resultKeys.push(nodeKey);
			}
		});
	}
	return resultKeys;
}

export function quickReplace(model) {
	const {graph} = graphObject;
	let newModel = fulex(model);
	let quickKey = mapModel(graph, newModel, 0);
	const resultKeys = fromBufferReplace(quickKey);
	let childNode;
	traverseGraphBranch(graph, quickKey, childKey => {
		childNode = graph.node(childKey);
		if (childNode) {
			delete childNode.modelNode;
			graph.removeNode(childKey);
		}
	});
	newModel = undefined;
	quickKey = undefined;
	return resultKeys;
}

//export function fromBufferWrap(nodeKey, quickKey){
//    const {graph} = graphObject;
//    const node = graph.node(nodeKey);
//    if(!node){
//        throw Error('From buffer wrap: node with key ' + nodeKey + ' was not found.');
//    }
//    if(!node.prop){
//        const pastedKeys = fromBufferBeforeOrAfter(nodeKey, false, quickKey);
//        setForCutting(nodeKey);
//        cutPasteFirstOrLast(pastedKeys[0], false);
//        removeForCutting(nodeKey);
//        return pastedKeys;
//    } else {
//        return [nodeKey];
//    }
//}

//export function quickWrap(model, nodeKey){
//    const {graph} = graphObject;
//    let newModel = fulex(model);
//    let quickKey = mapModel(graph, newModel, 0);
//    const resultKeys = fromBufferWrap(nodeKey, quickKey);
//    let childNode;
//    traverseGraphBranch(graph, quickKey, childKey => {
//        childNode = graph.node(childKey);
//        if(childNode){
//            delete childNode.modelNode;
//            graph.removeNode(childKey);
//        }
//    });
//    newModel = undefined;
//    quickKey = undefined;
//    return resultKeys;
//}

export function cloneSelected() {
	const {graph} = graphObject;
	const {selected} = getAllMarkedKeys();
	let pastedKeys = [];
	if (selected && selected.length > 0) {

		let clonedMap = new Map();
		let newNodeKey;
		selected.forEach(selectedKey => {
			const selectedNode = graph.node(selectedKey);
			if (selectedNode && !selectedNode.prop) {
				newNodeKey = copyGraphNode(graph, selectedKey);
				clonedMap.set(selectedKey, newNodeKey);
			}
		});

		clonedMap.forEach((newKey, targetKey) => {
			const parentKey = graph.parent(targetKey);
			let parentNode = graph.node(parentKey);
			const selectedNode = graph.node(targetKey);
			if (parentNode && selectedNode) {
				let detachedModelNodes = [];
				let detachedNode = graph.node(newKey);
				if (detachedNode && detachedNode.modelNode) {
					graph.setParent(newKey, parentKey);
					detachedModelNodes.push(detachedNode.modelNode);
					let {modelNode} = parentNode;
					modelNode.children = modelNode.children || [];
					let modelNodesArgs = [selectedNode.index + 1, 0].concat(detachedModelNodes);
					modelNode.children.splice.apply(modelNode.children, modelNodesArgs);
					adjustIndices(graph, parentKey);
					pastedKeys.push(newKey);
				}

			}
		});
	}
	return pastedKeys;
}

export function moveSelected(isUp) {
	const {graph} = graphObject;
	const {selected} = getAllMarkedKeys();
	if (selected && selected.length > 0) {

		let parentMap = new Map();
		let parentKey;
		let childrenGroup;
		let child;
		selected.forEach(selectedKey => {
			child = graph.node(selectedKey);
			if (child) {
				parentKey = graph.parent(selectedKey);
				if (parentKey) {
					childrenGroup = parentMap.get(parentKey);
					if (!childrenGroup) {
						childrenGroup = [];
						parentMap.set(parentKey, childrenGroup);
					}
					childrenGroup.push(child);
				}
			}
		});
		let parentNode;
		parentMap.forEach((group, parentKey) => {
			parentNode = graph.node(parentKey);
			let {modelNode} = parentNode;
			if (modelNode.children && modelNode.children.length !== 1) {
				if (isUp) {
					group.sort((a, b) => a.index - b.index);
					for (let u = 0; u < group.length; u++) {
						if (group[u].index <= 0) {
							break;
						}
						modelNode.children.splice(group[u].index, 1);
						modelNode.children.splice(group[u].index - 1, 0, group[u].modelNode);
					}
				} else {
					group.sort((a, b) => b.index - a.index);
					for (let d = 0; d < group.length; d++) {
						if (group[d].index >= modelNode.children.length - 1) {
							break;
						}
						modelNode.children.splice(group[d].index, 1);
						modelNode.children.splice(group[d].index + 1, 0, group[d].modelNode);
					}
				}
				adjustIndices(graph, parentKey);
			}
		});
	}
}

export function deleteSelected() {
	const {graph, pageNodes} = graphObject;
	const testFunc = node => node.selected;
	let detachedKeys = [];
	let resultKeys = [];
	pageNodes.forEach(pNode => {
		traverseGraphBranch(graph, pNode.pageKey, (key => {
			let childNode = graph.node(key);
			if (childNode.selected) {
				const parentKey = graph.parent(key);
				if (parentKey) {
					//const parentNode = graph.node(parentKey);
					const childKeys = graph.children(parentKey);
					if (childKeys && childKeys.length > 1) {
						let children = [];
						childKeys.forEach(childKey => {
							children.push({key: childKey, node: graph.node(childKey)});
						});
						children.sort((a, b) => a.node.index - b.node.index);
						if (childNode.index === 0) {
							resultKeys.push(children[1].key);
						} else {
							resultKeys.push(children[childNode.index - 1].key);
						}
					} else {
						resultKeys.push(parentKey);
					}
				}
			}
		}));
		detachGraphNodes(graph, pNode.pageKey, testFunc, detachedKeys);
	});
	let newResultKeys = [];
	if (detachedKeys.length > 0) {
		resultKeys.forEach(key => {
			if (detachedKeys.indexOf(key) < 0) {
				newResultKeys.push(key);
			}
		});
		let childNode;
		detachedKeys.forEach(key => {
			traverseGraphBranch(graph, key, childKey => {
				childNode = graph.node(childKey);
				if (childNode) {
					delete childNode.modelNode;
					graph.removeNode(childKey);
				}
			});
		});
	}
	return newResultKeys;
}

export function changeModelNodeType(nodeKey, newModel) {
	const {graph} = graphObject;
	let node = graph.node(nodeKey);
	const parentKey = graph.parent(nodeKey);
	const detachedModel = fulex(newModel);
	if (node && parentKey) {
		traverseGraphBranch(graph, nodeKey, childKey => {
			if (childKey !== nodeKey) {
				let childNode = graph.node(childKey);
				if (childNode) {
					delete childNode.modelNode;
					graph.removeNode(childKey);
				}
			}
		});
		mapModelForNode(graph, detachedModel, node.index, undefined, undefined, nodeKey);
		let parentNode = graph.node(parentKey);
		let {modelNode} = parentNode;
		modelNode.children = modelNode.children || [];
		let modelNodesArgs = [node.index, 1].concat([detachedModel]);
		modelNode.children.splice.apply(modelNode.children, modelNodesArgs);
		adjustIndices(graph, parentKey);
	}
}

export function setForCutting(nodeKey) {
	const {graph} = graphObject;
	let node = graph.node(nodeKey);
	if (node) {
		node.isForCutting = true;
		traverseGraphBranch(graph, nodeKey, (key => {
			let childNode = graph.node(key);
			childNode.isForCuttingChild = true;
		}));
	}
}

export function removeForCutting(nodeKey) {
	const {graph} = graphObject;
	let node = graph.node(nodeKey);
	if (node) {
		node.isForCutting = undefined;
		traverseGraphBranch(graph, nodeKey, (key => {
			let childNode = graph.node(key);
			childNode.isForCuttingChild = undefined;
		}));
	}
}

export function setForCopying(nodeKey) {
	const {graph} = graphObject;
	let node = graph.node(nodeKey);
	if (node) {
		node.isForCopying = true;
	}
}

export function removeForCopying(nodeKey) {
	const {graph} = graphObject;
	let node = graph.node(nodeKey);
	if (node) {
		node.isForCopying = undefined;
	}
}

export function removeClipboardMarks(nodeKey) {
	removeForCutting(nodeKey);
	removeForCopying(nodeKey);
}

export function getMarkedKeys(rootKey) {
	let selected = [];
	let highlighted = [];
	let forCutting = [];
	let forCopying = [];
	const {graph} = graphObject;
	traverseGraphBranch(graph, rootKey, (key => {
		let childNode = graph.node(key);
		if (childNode) {
			if (childNode.highlighted) {
				highlighted.push(key);
			}
			if (childNode.selected) {
				selected.push(key);
			}
			if (childNode.isForCutting) {
				forCutting.push(key);
			}
			if (childNode.isForCopying) {
				forCopying.push(key);
			}
		}
	}));
	//console.log('Get marked keys, root: ' + rootKey +
	//    ', selected: ' + selected.length +
	//    ', highlighted: ' + highlighted.length +
	//    ', forCutting: ' + forCutting.length +
	//    ', forCopying: ' + forCopying.length);
	return {selected, highlighted, forCutting, forCopying};
}

export function getAllMarkedKeys() {
	const {graph, pageNodes} = graphObject;
	let result = undefined;
	pageNodes.forEach(pNode => {
		if (!result) {
			result = getMarkedKeys(pNode.pageKey);
		} else {
			const {selected, highlighted, forCutting, forCopying} = getMarkedKeys(pNode.pageKey);
			result.selected = result.selected.concat(selected);
			result.highlighted = result.highlighted.concat(highlighted);
			result.forCutting = result.forCutting.concat(forCutting);
			result.forCopying = result.forCopying.concat(forCopying);
		}
	});
	return result;
}


text:
package org.killbill.billing.catalog.dao;

import java.math.BigDecimal;

import org.killbill.billing.catalog.CatalogTestSuiteWithEmbeddedDB;
import org.killbill.commons.jdbi.mapper.LowerToCamelBeanMapperFactory;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.TransactionCallback;
import org.skife.jdbi.v2.TransactionStatus;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;

public class TestCatalogOverridePhaseDefinitionSqlDao extends CatalogTestSuiteWithEmbeddedDB {

    @BeforeClass(groups = "slow")
    public void beforeClass() throws Exception {
        if (hasFailed()) {
            return;
        }

        super.beforeClass();
        ((DBI) dbi).registerMapper(new LowerToCamelBeanMapperFactory(CatalogOverridePhaseDefinitionModelDao.class));
    }

    @Test(groups = "slow")
    public void testBasic() throws Exception {

        final CatalogOverridePhaseDefinitionModelDao obj1 = new CatalogOverridePhaseDefinitionModelDao("p1", "EUR", BigDecimal.ONE, BigDecimal.TEN, clock.getUTCNow());

        performTestInTransaction(new WithCatalogOverridePhaseDefinitionSqlDaoTransaction<Void>() {
            @Override
            public Void doTransaction(final CatalogOverridePhaseDefinitionSqlDao sqlDao) {
                final Long lastInserted = sqlDao.create(obj1, internalCallContext);

                final CatalogOverridePhaseDefinitionModelDao rehydrated = sqlDao.getByRecordId(lastInserted, internalCallContext);
                assertEquals(rehydrated.getParentPhaseName(), obj1.getParentPhaseName());
                assertEquals(rehydrated.getFixedPrice().compareTo(obj1.getFixedPrice()), 0);
                assertEquals(rehydrated.getRecurringPrice().compareTo(obj1.getRecurringPrice()), 0);
                assertEquals(rehydrated.getCurrency(), obj1.getCurrency());
                return null;
            }
        });
    }

    @Test(groups = "slow")
    public void testBasicWithNullPrices() throws Exception {

        final CatalogOverridePhaseDefinitionModelDao obj1 = new CatalogOverridePhaseDefinitionModelDao("p2", "USD", null, new BigDecimal("54.21"), clock.getUTCNow());

        performTestInTransaction(new WithCatalogOverridePhaseDefinitionSqlDaoTransaction<Void>() {
            @Override
            public Void doTransaction(final CatalogOverridePhaseDefinitionSqlDao sqlDao) {
                final Long lastInserted = sqlDao.create(obj1, internalCallContext);

                final CatalogOverridePhaseDefinitionModelDao rehydrated = sqlDao.getByRecordId(lastInserted, internalCallContext);
                assertEquals(rehydrated.getParentPhaseName(), obj1.getParentPhaseName());
                assertNull(rehydrated.getFixedPrice());
                assertEquals(rehydrated.getRecurringPrice().compareTo(obj1.getRecurringPrice()), 0);
                assertEquals(rehydrated.getCurrency(), obj1.getCurrency());
                return null;
            }
        });
    }

    @Test(groups = "slow")
    public void testGetByAttributes() throws Exception {

        final CatalogOverridePhaseDefinitionModelDao objWithNoNullPrices = new CatalogOverridePhaseDefinitionModelDao("p2", "USD", BigDecimal.ZERO, new BigDecimal("12.453"), clock.getUTCNow());
        final CatalogOverridePhaseDefinitionModelDao objWithNullFixedPrice = new CatalogOverridePhaseDefinitionModelDao("p3", "BTC", null, new BigDecimal("14.443"), clock.getUTCNow());
        final CatalogOverridePhaseDefinitionModelDao objWithNullRecurringPrice = new CatalogOverridePhaseDefinitionModelDao("p4", "EUR", new BigDecimal("11.243"), null, clock.getUTCNow());

        performTestInTransaction(new WithCatalogOverridePhaseDefinitionSqlDaoTransaction<Void>() {
            @Override
            public Void doTransaction(final CatalogOverridePhaseDefinitionSqlDao sqlDao) {
                sqlDao.create(objWithNoNullPrices, internalCallContext);
                checkRehydrated(objWithNoNullPrices, sqlDao);

                sqlDao.create(objWithNullFixedPrice, internalCallContext);
                checkRehydrated(objWithNullFixedPrice, sqlDao);

                sqlDao.create(objWithNullRecurringPrice, internalCallContext);
                checkRehydrated(objWithNullRecurringPrice, sqlDao);
                return null;
            }

            private void checkRehydrated(final CatalogOverridePhaseDefinitionModelDao obj, final CatalogOverridePhaseDefinitionSqlDao sqlDao) {
                final CatalogOverridePhaseDefinitionModelDao rehydrated = sqlDao.getByAttributes(obj.getParentPhaseName(), obj.getCurrency(), obj.getFixedPrice(), obj.getRecurringPrice(), internalCallContext).get(0);
                assertEquals(rehydrated.getParentPhaseName(), obj.getParentPhaseName());
                if (obj.getFixedPrice() != null) {
                    assertEquals(rehydrated.getFixedPrice().compareTo(obj.getFixedPrice()), 0);
                } else {
                    assertNull(rehydrated.getFixedPrice());
                }
                if (obj.getRecurringPrice() != null) {
                    assertEquals(rehydrated.getRecurringPrice().compareTo(obj.getRecurringPrice()), 0);
                } else {
                    assertNull(rehydrated.getRecurringPrice());
                }
                assertEquals(rehydrated.getCurrency(), obj.getCurrency());
            }
        });
    }

    private interface WithCatalogOverridePhaseDefinitionSqlDaoTransaction<T> {

        public <T> T doTransaction(final CatalogOverridePhaseDefinitionSqlDao sqlDao);
    }

    private <T> T performTestInTransaction(final WithCatalogOverridePhaseDefinitionSqlDaoTransaction<T> callback) {
        return dbi.inTransaction(new TransactionCallback<T>() {
            @Override
            public T inTransaction(final Handle handle, final TransactionStatus status) throws Exception {
                final CatalogOverridePhaseDefinitionSqlDao sqlDao = handle.attach(CatalogOverridePhaseDefinitionSqlDao.class);
                return callback.doTransaction(sqlDao);
            }
        });
    }

}