text:
package errors // import "cuelang.org/go/cue/errors"

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"path/filepath"
	"sort"
	"strings"

	"github.com/mpvl/unique"

	"cuelang.org/go/cue/token"
)

// New is a convenience wrapper for errors.New in the core library.
// It does not return a CUE error.
func New(msg string) error {
	return errors.New(msg)
}

// Unwrap returns the result of calling the Unwrap method on err, if err
// implements Unwrap. Otherwise, Unwrap returns nil.
func Unwrap(err error) error {
	return errors.Unwrap(err)
}

// Is reports whether any error in err's chain matches target.
//
// An error is considered to match a target if it is equal to that target or if
// it implements a method Is(error) bool such that Is(target) returns true.
func Is(err, target error) bool {
	return errors.Is(err, target)
}

// As finds the first error in err's chain that matches the type to which target
// points, and if so, sets the target to its value and returns true. An error
// matches a type if it is assignable to the target type, or if it has a method
// As(interface{}) bool such that As(target) returns true. As will panic if
// target is not a non-nil pointer to a type which implements error or is of
// interface type.
//
// The As method should set the target to its value and return true if err
// matches the type to which target points.
func As(err error, target interface{}) bool {
	return errors.As(err, target)
}

// A Message implements the error interface as well as Message to allow
// internationalized messages. A Message is typically used as an embedding
// in a CUE message.
type Message struct {
	format string
	args   []interface{}
}

// NewMessage creates an error message for human consumption. The arguments
// are for later consumption, allowing the message to be localized at a later
// time. The passed argument list should not be modified.
func NewMessage(format string, args []interface{}) Message {
	return Message{format: format, args: args}
}

// Msg returns a printf-style format string and its arguments for human
// consumption.
func (m *Message) Msg() (format string, args []interface{}) {
	return m.format, m.args
}

func (m *Message) Error() string {
	return fmt.Sprintf(m.format, m.args...)
}

// Error is the common error message.
type Error interface {
	// Position returns the primary position of an error. If multiple positions
	// contribute equally, this reflects one of them.
	Position() token.Pos

	// InputPositions reports positions that contributed to an error, including
	// the expressions resulting in the conflict, as well as values that were
	// the input to this expression.
	InputPositions() []token.Pos

	// Error reports the error message without position information.
	Error() string

	// Path returns the path into the data tree where the error occurred.
	// This path may be nil if the error is not associated with such a location.
	Path() []string

	// Msg returns the unformatted error message and its arguments for human
	// consumption.
	Msg() (format string, args []interface{})
}

// Positions returns all positions returned by an error, sorted
// by relevance when possible and with duplicates removed.
func Positions(err error) []token.Pos {
	e := Error(nil)
	if !errors.As(err, &e) {
		return nil
	}

	a := make([]token.Pos, 0, 3)

	sortOffset := 0
	pos := e.Position()
	if pos.IsValid() {
		a = append(a, pos)
		sortOffset = 1
	}

	for _, p := range e.InputPositions() {
		if p.IsValid() && p != pos {
			a = append(a, p)
		}
	}

	byPos := byPos(a[sortOffset:])
	sort.Sort(byPos)
	k := unique.ToFront(byPos)
	return a[:k+sortOffset]
}

type byPos []token.Pos

func (s *byPos) Truncate(n int)    { (*s) = (*s)[:n] }
func (s byPos) Len() int           { return len(s) }
func (s byPos) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s byPos) Less(i, j int) bool { return comparePos(s[i], s[j]) == -1 }

// Path returns the path of an Error if err is of that type.
func Path(err error) []string {
	if e := Error(nil); errors.As(err, &e) {
		return e.Path()
	}
	return nil
}

// Newf creates an Error with the associated position and message.
func Newf(p token.Pos, format string, args ...interface{}) Error {
	return &posError{
		pos:     p,
		Message: NewMessage(format, args),
	}
}

// Wrapf creates an Error with the associated position and message. The provided
// error is added for inspection context.
func Wrapf(err error, p token.Pos, format string, args ...interface{}) Error {
	pErr := &posError{
		pos:     p,
		Message: NewMessage(format, args),
	}
	return Wrap(pErr, err)
}

// Wrap creates a new error where child is a subordinate error of parent.
// If child is list of Errors, the result will itself be a list of errors
// where child is a subordinate error of each parent.
func Wrap(parent Error, child error) Error {
	if child == nil {
		return parent
	}
	a, ok := child.(list)
	if !ok {
		return &wrapped{parent, child}
	}
	b := make(list, len(a))
	for i, err := range a {
		b[i] = &wrapped{parent, err}
	}
	return b
}

type wrapped struct {
	main Error
	wrap error
}

// Error implements the error interface.
func (e *wrapped) Error() string {
	switch msg := e.main.Error(); {
	case e.wrap == nil:
		return msg
	case msg == "":
		return e.wrap.Error()
	default:
		return fmt.Sprintf("%s: %s", msg, e.wrap)
	}
}

func (e *wrapped) Is(target error) bool {
	return Is(e.main, target)
}

func (e *wrapped) As(target interface{}) bool {
	return As(e.main, target)
}

func (e *wrapped) Msg() (format string, args []interface{}) {
	return e.main.Msg()
}

func (e *wrapped) Path() []string {
	if p := Path(e.main); p != nil {
		return p
	}
	return Path(e.wrap)
}

func (e *wrapped) InputPositions() []token.Pos {
	return append(e.main.InputPositions(), Positions(e.wrap)...)
}

func (e *wrapped) Position() token.Pos {
	if p := e.main.Position(); p != token.NoPos {
		return p
	}
	if wrap, ok := e.wrap.(Error); ok {
		return wrap.Position()
	}
	return token.NoPos
}

func (e *wrapped) Unwrap() error { return e.wrap }

func (e *wrapped) Cause() error { return e.wrap }

// Promote converts a regular Go error to an Error if it isn't already one.
func Promote(err error, msg string) Error {
	switch x := err.(type) {
	case Error:
		return x
	default:
		return Wrapf(err, token.NoPos, msg)
	}
}

var _ Error = &posError{}

// In an List, an error is represented by an *posError.
// The position Pos, if valid, points to the beginning of
// the offending token, and the error condition is described
// by Msg.
type posError struct {
	pos    token.Pos
	inputs []token.Pos
	Message
}

func (e *posError) Path() []string              { return nil }
func (e *posError) InputPositions() []token.Pos { return e.inputs }
func (e *posError) Position() token.Pos         { return e.pos }

// Append combines two errors, flattening Lists as necessary.
func Append(a, b Error) Error {
	switch x := a.(type) {
	case nil:
		return b
	case list:
		return appendToList(x, b)
	}
	// Preserve order of errors.
	list := appendToList(nil, a)
	list = appendToList(list, b)
	return list
}

// Errors reports the individual errors associated with an error, which is
// the error itself if there is only one or, if the underlying type is List,
// its individual elements. If the given error is not an Error, it will be
// promoted to one.
func Errors(err error) []Error {
	switch x := err.(type) {
	case nil:
		return nil
	case list:
		return []Error(x)
	case Error:
		return []Error{x}
	default:
		return []Error{Promote(err, "")}
	}
}

func appendToList(a list, err Error) list {
	switch x := err.(type) {
	case nil:
		return a
	case list:
		if a == nil {
			return x
		}
		return append(a, x...)
	default:
		return append(a, err)
	}
}

// list is a list of Errors.
// The zero value for an list is an empty list ready to use.
type list []Error

func (p list) Is(err, target error) bool {
	for _, e := range p {
		if errors.Is(e, target) {
			return true
		}
	}
	return false
}

func (p list) As(err error, target interface{}) bool {
	for _, e := range p {
		if errors.As(e, target) {
			return true
		}
	}
	return false
}

// AddNewf adds an Error with given position and error message to an List.
func (p *list) AddNewf(pos token.Pos, msg string, args ...interface{}) {
	err := &posError{pos: pos, Message: Message{format: msg, args: args}}
	*p = append(*p, err)
}

// Add adds an Error with given position and error message to an List.
func (p *list) Add(err Error) {
	*p = appendToList(*p, err)
}

// Reset resets an List to no errors.
func (p *list) Reset() { *p = (*p)[:0] }

// List implements the sort Interface.
func (p list) Len() int      { return len(p) }
func (p list) Swap(i, j int) { p[i], p[j] = p[j], p[i] }

func (p list) Less(i, j int) bool {
	if c := comparePos(p[i].Position(), p[j].Position()); c != 0 {
		return c == -1
	}
	// Note that it is not sufficient to simply compare file offsets because
	// the offsets do not reflect modified line information (through //line
	// comments).

	if !equalPath(p[i].Path(), p[j].Path()) {
		return lessPath(p[i].Path(), p[j].Path())
	}
	return p[i].Error() < p[j].Error()
}

func lessOrMore(isLess bool) int {
	if isLess {
		return -1
	}
	return 1
}

func comparePos(a, b token.Pos) int {
	if a.Filename() != b.Filename() {
		return lessOrMore(a.Filename() < b.Filename())
	}
	if a.Line() != b.Line() {
		return lessOrMore(a.Line() < b.Line())
	}
	if a.Column() != b.Column() {
		return lessOrMore(a.Column() < b.Column())
	}
	return 0
}

func lessPath(a, b []string) bool {
	for i, x := range a {
		if i >= len(b) {
			return false
		}
		if x != b[i] {
			return x < b[i]
		}
	}
	return len(a) < len(b)
}

func equalPath(a, b []string) bool {
	if len(a) != len(b) {
		return false
	}
	for i, x := range a {
		if x != b[i] {
			return false
		}
	}
	return true
}

// Sanitize sorts multiple errors and removes duplicates on a best effort basis.
// If err represents a single or no error, it returns the error as is.
func Sanitize(err Error) Error {
	if l, ok := err.(list); ok && err != nil {
		a := make(list, len(l))
		copy(a, l)
		a.Sort()
		a.RemoveMultiples()
		return a
	}
	return err
}

// Sort sorts an List. *posError entries are sorted by position,
// other errors are sorted by error message, and before any *posError
// entry.
//
func (p list) Sort() {
	sort.Sort(p)
}

// RemoveMultiples sorts an List and removes all but the first error per line.
func (p *list) RemoveMultiples() {
	p.Sort()
	var last Error
	i := 0
	for _, e := range *p {
		if last == nil || !approximateEqual(last, e) {
			last = e
			(*p)[i] = e
			i++
		}
	}
	(*p) = (*p)[0:i]
}

func approximateEqual(a, b Error) bool {
	aPos := a.Position()
	bPos := b.Position()
	if aPos == token.NoPos || bPos == token.NoPos {
		return a.Error() == b.Error()
	}
	return aPos.Filename() == bPos.Filename() &&
		aPos.Line() == bPos.Line() &&
		equalPath(a.Path(), b.Path())
}

// An List implements the error interface.
func (p list) Error() string {
	format, args := p.Msg()
	return fmt.Sprintf(format, args...)
}

// Msg reports the unformatted error message for the first error, if any.
func (p list) Msg() (format string, args []interface{}) {
	switch len(p) {
	case 0:
		return "no errors", nil
	case 1:
		return p[0].Msg()
	}
	return "%s (and %d more errors)", []interface{}{p[0], len(p) - 1}
}

// Position reports the primary position for the first error, if any.
func (p list) Position() token.Pos {
	if len(p) == 0 {
		return token.NoPos
	}
	return p[0].Position()
}

// InputPositions reports the input positions for the first error, if any.
func (p list) InputPositions() []token.Pos {
	if len(p) == 0 {
		return nil
	}
	return p[0].InputPositions()
}

// Path reports the path location of the first error, if any.
func (p list) Path() []string {
	if len(p) == 0 {
		return nil
	}
	return p[0].Path()
}

// Err returns an error equivalent to this error list.
// If the list is empty, Err returns nil.
func (p list) Err() error {
	if len(p) == 0 {
		return nil
	}
	return p
}

// A Config defines parameters for printing.
type Config struct {
	// Format formats the given string and arguments and writes it to w.
	// It is used for all printing.
	Format func(w io.Writer, format string, args ...interface{})

	// Cwd is the current working directory. Filename positions are taken
	// relative to this path.
	Cwd string

	// ToSlash sets whether to use Unix paths. Mostly used for testing.
	ToSlash bool
}

// Print is a utility function that prints a list of errors to w,
// one error per line, if the err parameter is an List. Otherwise
// it prints the err string.
//
func Print(w io.Writer, err error, cfg *Config) {
	if cfg == nil {
		cfg = &Config{}
	}
	if e, ok := err.(Error); ok {
		err = Sanitize(e)
	}
	for _, e := range Errors(err) {
		printError(w, e, cfg)
	}
}

// Details is a convenience wrapper for Print to return the error text as a
// string.
func Details(err error, cfg *Config) string {
	w := &bytes.Buffer{}
	Print(w, err, cfg)
	return w.String()
}

// String generates a short message from a given Error.
func String(err Error) string {
	w := &strings.Builder{}
	writeErr(w, err)
	return w.String()
}

func writeErr(w io.Writer, err Error) {
	if path := strings.Join(err.Path(), "."); path != "" {
		_, _ = io.WriteString(w, path)
		_, _ = io.WriteString(w, ": ")
	}

	for {
		u := errors.Unwrap(err)

		printed := false
		msg, args := err.Msg()
		if msg != "" || u == nil { // print at least something
			fmt.Fprintf(w, msg, args...)
			printed = true
		}

		if u == nil {
			break
		}

		if printed {
			_, _ = io.WriteString(w, ": ")
		}
		err, _ = u.(Error)
		if err == nil {
			fmt.Fprint(w, u)
			break
		}
	}
}

func defaultFprintf(w io.Writer, format string, args ...interface{}) {
	fmt.Fprintf(w, format, args...)
}

func printError(w io.Writer, err error, cfg *Config) {
	if err == nil {
		return
	}
	fprintf := cfg.Format
	if fprintf == nil {
		fprintf = defaultFprintf
	}

	positions := []string{}
	for _, p := range Positions(err) {
		pos := p.Position()
		s := pos.Filename
		if cfg.Cwd != "" {
			if p, err := filepath.Rel(cfg.Cwd, s); err == nil {
				s = p
				// Some IDEs (e.g. VSCode) only recognize a path if it start
				// with a dot. This also helps to distinguish between local
				// files and builtin packages.
				if !strings.HasPrefix(s, ".") {
					s = fmt.Sprintf(".%s%s", string(filepath.Separator), s)
				}
			}
		}
		if cfg.ToSlash {
			s = filepath.ToSlash(s)
		}
		if pos.IsValid() {
			if s != "" {
				s += ":"
			}
			s += fmt.Sprintf("%d:%d", pos.Line, pos.Column)
		}
		if s == "" {
			s = "-"
		}
		positions = append(positions, s)
	}

	if e, ok := err.(Error); ok {
		writeErr(w, e)
	} else {
		fprintf(w, "%v", err)
	}

	if len(positions) == 0 {
		fprintf(w, "\n")
		return
	}

	fprintf(w, ":\n")
	for _, pos := range positions {
		fprintf(w, "    %s\n", pos)
	}
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Fungus, Wageningen 28: 44 (1958)

#### Original name
Peziza polygoni Lasch

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
DROP TABLE IF EXISTS `migrations`;

CREATE TABLE IF NOT EXISTS `migrations` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `file` varchar(999) NOT NULL,
  `table` varchar(500) NOT NULL,
  `folder` varchar(50) NOT NULL,
  `success` tinyint(3) NOT NULL DEFAULT 0,
  `error_message` varchar(999) NOT NULL,
  `retrys` integer DEFAULT 0 NOT NULL,
  `updated` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
  `created` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;


text:
using System;
using System.Data.Entity;

namespace Darjeel.EntityFramework
{
    public abstract class ContextBase : DbContext, IContext
    {
        protected ContextBase(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
        }

        public DbContextTransaction BeginTransaction()
        {
            return Database.BeginTransaction();
        }

        public void SetValues<TEntity>(TEntity original, TEntity entity)
            where TEntity : class
        {
            if (original == null) throw new ArgumentNullException(nameof(original));
            if (entity == null) throw new ArgumentNullException(nameof(entity));

            Entry(original).CurrentValues.SetValues(entity);
        }
    }
}


text:
package com.test;

import java.util.Scanner;

import com.loganalyzer.common.models.SearchContent;
import com.loganalyzer.common.models.SearchInput;
import com.loganalyzer.searchinputs.DataTypeSearchInput;
import com.loganalyzer.searchinputs.FilePathInput;
import com.loganalyzer.searchinputs.SearchAreaInput;
import com.loganalyzer.searchinputs.SearchRangeTypeInput;
import com.loganalyzer.searchinputs.SearchStringInput;
import com.loganalyzer.searchinputs.SearchTypeInput;

public class TestMain
{
   public static void main(String[]args){
	   System.out.println("WELCOME TO SEARCH ENGINE ");
	   System.out.println("==========================");
	   SearchInput input = new SearchInput();
	   Scanner scanner = new Scanner(System.in);
	   boolean exitFlag = new DataTypeSearchInput().takeInput(input,scanner);
	   if(!exitFlag)
	      exitFlag = new SearchTypeInput().takeInput(input,scanner);

	   if(!exitFlag)
	      exitFlag = new SearchRangeTypeInput().takeInput(input,scanner);

	   if(!exitFlag)
         exitFlag = new SearchAreaInput().takeInput(input,scanner);

	   if(!exitFlag)
         exitFlag = new SearchStringInput().takeInput(input,scanner);

	   SearchContent searchContent = new SearchContent();
	   if(!exitFlag)
		   exitFlag = new FilePathInput().takeInput(searchContent,scanner);
     scanner.close();
      System.out.println("Given Input : "+input);
      System.out.println("File Selected : "+searchContent.getFileList().get(0));

   }
}


text:
module Stakr #:nodoc:
  module PlainOldRubyTemplates #:nodoc:
    module Helpers #:nodoc:

      module Commons #:nodoc:

        def format_helper(string, format)
          case format.to_s
          when 'simple'
            simple_format(string)
          when 'textile'
            textilize(string)
          else
            string
          end
        end

        def conditional_comments_wrapper(string, options)
          if condition = options[:cc]
            "<!--[if #{condition}]>#{string}<![endif]-->"
          elsif condition = options[:rcc]
            "<!--[if #{condition}]><!-->#{string}<!--<![endif]-->"
          else
            string
          end
        end

      end

    end
  end
end


text:
using MatterHackers.Agg;
using MatterHackers.Agg.Image;
using MatterHackers.PolygonMesh;
using MatterHackers.Agg.UI;
using NUnit.Framework;
using System;
using System.Linq;
using System.Threading.Tasks;
using MatterHackers.GuiAutomation;
using MatterHackers.Agg.PlatformAbstract;
using MatterHackers.MatterControl.PartPreviewWindow;
using System.IO;
using MatterHackers.MatterControl.CreatorPlugins;
using MatterHackers.Agg.UI.Tests;
using MatterHackers.MatterControl.PrintQueue;
using MatterHackers.MatterControl.DataStorage;
using System.Diagnostics;

namespace MatterHackers.MatterControl.UI
{
	[TestFixture, Category("MatterControl.UI"), RunInApplicationDomain]
	public class PartPreviewTests
	{
		[Test, RequiresSTA, RunInApplicationDomain]
		public void CopyButtonClickedMakesCopyOfPartOnBed()
		{
			// Run a copy of MatterControl
			Action<AutomationTesterHarness> testToRun = (AutomationTesterHarness resultsHarness) =>
			{
				AutomationRunner testRunner = new AutomationRunner(MatterControlUtilities.DefaultTestImages);
				{

					SystemWindow systemWindow;

					//Navigate to Local Library
					testRunner.ClickByName("Library Tab");
					MatterControlUtilities.NavigateToFolder(testRunner, "Local Library Row Item Collection");
					testRunner.Wait(1);
					testRunner.ClickByName("Row Item Calibration - Box");
					testRunner.ClickByName("Row Item Calibration - Box Print Button");
					testRunner.Wait(1);

					//Get View3DWidget and count MeshGroups before Copy button is clicked
					GuiWidget partPreview = testRunner.GetWidgetByName("View3DWidget", out systemWindow, 3);
					View3DWidget view3D = partPreview as View3DWidget;

					string copyButtonName = "3D View Copy";

					//Click Edit button to make edit controls visible
					testRunner.ClickByName("3D View Edit");
					testRunner.Wait(1);
					int partCountBeforeCopy = view3D.MeshGroups.Count();
					resultsHarness.AddTestResult(partCountBeforeCopy == 1);

					//Click Copy button and count MeshGroups
					testRunner.ClickByName(copyButtonName);
					System.Threading.Thread.Sleep(2000);
					int partCountAfterCopy = view3D.MeshGroups.Count();
					resultsHarness.AddTestResult(partCountAfterCopy == 2);
					testRunner.Wait(1);

					//Click Copy button a second time and count MeshGroups again
					testRunner.ClickByName(copyButtonName);
					System.Threading.Thread.Sleep(2000);
					int partCountAfterSecondCopy = view3D.MeshGroups.Count();
					resultsHarness.AddTestResult(partCountAfterSecondCopy == 3);

					MatterControlUtilities.CloseMatterControl(testRunner);
				}
			};

			AutomationTesterHarness testHarness = MatterControlUtilities.RunTest(testToRun);

			Assert.IsTrue(testHarness.AllTestsPassed);
			Assert.IsTrue(testHarness.TestCount == 3); // make sure we ran all our tests
		}

		[Test, RequiresSTA, RunInApplicationDomain]
		public void GroupAndUngroup()
		{
			// Run a copy of MatterControl
			Action<AutomationTesterHarness> testToRun = (AutomationTesterHarness resultsHarness) =>
			{
				AutomationRunner testRunner = new AutomationRunner(MatterControlUtilities.DefaultTestImages);
				{

					SystemWindow systemWindow;

					//Navigate to Local Library
					testRunner.ClickByName("Library Tab");
					MatterControlUtilities.NavigateToFolder(testRunner, "Local Library Row Item Collection");
					testRunner.Wait(1);
					testRunner.ClickByName("Row Item Calibration - Box");
					testRunner.ClickByName("Row Item Calibration - Box Print Button");
					testRunner.Wait(1);

					//Get View3DWidget and count MeshGroups before Copy button is clicked
					GuiWidget partPreview = testRunner.GetWidgetByName("View3DWidget", out systemWindow, 3);
					View3DWidget view3D = partPreview as View3DWidget;

					string copyButtonName = "3D View Copy";

					//Click Edit button to make edit controls visible
					testRunner.ClickByName("3D View Edit");
					testRunner.Wait(1);
					int partCountBeforeCopy = view3D.MeshGroups.Count();
					resultsHarness.AddTestResult(partCountBeforeCopy == 1);

					for (int i = 0; i <= 4; i++)
						{
							testRunner.ClickByName(copyButtonName);
							testRunner.Wait(1);
						}

					//Get MeshGroupCount before Group is clicked
					System.Threading.Thread.Sleep(2000);
					int partsOnBedBeforeGroup = view3D.MeshGroups.Count();
					resultsHarness.AddTestResult(partsOnBedBeforeGroup == 6);

					//Click Group Button and get MeshGroup count after Group button is clicked
					testRunner.ClickByName("3D View Group");
					System.Threading.Thread.Sleep(2000);
					int partsOnBedAfterGroup = view3D.MeshGroups.Count();
					resultsHarness.AddTestResult(partsOnBedAfterGroup == 1);

					testRunner.ClickByName("3D View Ungroup");
					System.Threading.Thread.Sleep(2000);
					int partsOnBedAfterUngroup = view3D.MeshGroups.Count();
					resultsHarness.AddTestResult(partsOnBedAfterUngroup == 6);

					MatterControlUtilities.CloseMatterControl(testRunner);
				}
			};

			AutomationTesterHarness testHarness = MatterControlUtilities.RunTest(testToRun);

			Assert.IsTrue(testHarness.AllTestsPassed);
			Assert.IsTrue(testHarness.TestCount == 4); // make sure we ran all our tests
		}

		[Test, RequiresSTA, RunInApplicationDomain]
		public void RemoveButtonRemovesParts()
		{
			// Run a copy of MatterControl
			Action<AutomationTesterHarness> testToRun = (AutomationTesterHarness resultsHarness) =>
			{
				AutomationRunner testRunner = new AutomationRunner(MatterControlUtilities.DefaultTestImages);
				{

					SystemWindow systemWindow;

					//Navigate to Local Library
					testRunner.ClickByName("Library Tab");
					MatterControlUtilities.NavigateToFolder(testRunner, "Local Library Row Item Collection");
					testRunner.Wait(1);
					testRunner.ClickByName("Row Item Calibration - Box");
					testRunner.ClickByName("Row Item Calibration - Box Print Button");
					testRunner.Wait(1);

					//Get View3DWidget and count MeshGroups before Copy button is clicked
					GuiWidget partPreview = testRunner.GetWidgetByName("View3DWidget", out systemWindow, 3);
					View3DWidget view3D = partPreview as View3DWidget;

					string copyButtonName = "3D View Copy";

					//Click Edit button to make edit controls visible
					testRunner.ClickByName("3D View Edit");
					testRunner.Wait(1);
					int partCountBeforeCopy = view3D.MeshGroups.Count();
					resultsHarness.AddTestResult(partCountBeforeCopy == 1);

					for (int i = 0; i <= 4; i++)
					{
						testRunner.ClickByName(copyButtonName);
						testRunner.Wait(1);
					}

					//Get MeshGroupCount before Group is clicked
					System.Threading.Thread.Sleep(2000);
					int partsOnBedBeforeRemove= view3D.MeshGroups.Count();
					resultsHarness.AddTestResult(partsOnBedBeforeRemove == 6);

					//Check that MeshCount decreases by 1
					testRunner.ClickByName("3D View Remove");
					System.Threading.Thread.Sleep(2000);
					int meshCountAfterRemove = view3D.MeshGroups.Count();
					resultsHarness.AddTestResult(meshCountAfterRemove == 5);

					MatterControlUtilities.CloseMatterControl(testRunner);
				}
			};

			AutomationTesterHarness testHarness = MatterControlUtilities.RunTest(testToRun);

			Assert.IsTrue(testHarness.AllTestsPassed);
			Assert.IsTrue(testHarness.TestCount == 3); // make sure we ran all our tests
		}

		[Test, RequiresSTA, RunInApplicationDomain]
		public void UndoRedoCopy()
		{
			// Run a copy of MatterControl
			Action<AutomationTesterHarness> testToRun = (AutomationTesterHarness resultsHarness) =>
			{
				AutomationRunner testRunner = new AutomationRunner(MatterControlUtilities.DefaultTestImages);
				{

					SystemWindow systemWindow;

					//Navigate to Local Library
					testRunner.ClickByName("Library Tab");
					MatterControlUtilities.NavigateToFolder(testRunner, "Local Library Row Item Collection");
					testRunner.Wait(1);
					testRunner.ClickByName("Row Item Calibration - Box");
					testRunner.ClickByName("Row Item Calibration - Box Print Button");
					testRunner.Wait(1);

					//Get View3DWidget and count MeshGroups before Copy button is clicked
					GuiWidget partPreview = testRunner.GetWidgetByName("View3DWidget", out systemWindow, 3);
					View3DWidget view3D = partPreview as View3DWidget;

					string copyButtonName = "3D View Copy";

					//Click Edit button to make edit controls visible
					testRunner.ClickByName("3D View Edit");
					testRunner.Wait(1);
					int partCountBeforeCopy = view3D.MeshGroups.Count();
					resultsHarness.AddTestResult(partCountBeforeCopy == 1);

					for (int i = 0; i <= 4; i++)
					{
						testRunner.ClickByName(copyButtonName);
						testRunner.Wait(1);
					}

					testRunner.Wait(1);

					for(int x = 0; x <= 4; x++)
					{

						int meshCountBeforeUndo = view3D.MeshGroups.Count();
						testRunner.ClickByName("3D View Undo");
						System.Threading.Thread.Sleep(2000);
						int meshCountAfterUndo = view3D.MeshGroups.Count();
						resultsHarness.AddTestResult(meshCountAfterUndo == meshCountBeforeUndo - 1);

					}

					testRunner.Wait(1);

					for(int z = 0; z <= 4; z++)
					{
						int meshCountBeforeRedo = view3D.MeshGroups.Count();
						testRunner.ClickByName("3D View Redo");
						System.Threading.Thread.Sleep(2000);
						int meshCountAfterRedo = view3D.MeshGroups.Count();
						resultsHarness.AddTestResult(meshCountAfterRedo == meshCountBeforeRedo + 1);

					}

					MatterControlUtilities.CloseMatterControl(testRunner);
				}
			};

			AutomationTesterHarness testHarness = MatterControlUtilities.RunTest(testToRun);

			Assert.IsTrue(testHarness.AllTestsPassed);
			Assert.IsTrue(testHarness.TestCount == 11); // make sure we ran all our tests
		}

		[Test, RequiresSTA, RunInApplicationDomain]
		public void UndoRedoDelete()
		{
			// Run a copy of MatterControl
			Action<AutomationTesterHarness> testToRun = (AutomationTesterHarness resultsHarness) =>
			{
				AutomationRunner testRunner = new AutomationRunner(MatterControlUtilities.DefaultTestImages);
				{

					SystemWindow systemWindow;

					//Navigate to Local Library
					testRunner.ClickByName("Library Tab");
					MatterControlUtilities.NavigateToFolder(testRunner, "Local Library Row Item Collection");
					testRunner.Wait(1);
					testRunner.ClickByName("Row Item Calibration - Box");
					testRunner.ClickByName("Row Item Calibration - Box Print Button");
					testRunner.Wait(1);

					//Get View3DWidget and count MeshGroups before Copy button is clicked
					GuiWidget partPreview = testRunner.GetWidgetByName("View3DWidget", out systemWindow, 3);
					View3DWidget view3D = partPreview as View3DWidget;

					string copyButtonName = "3D View Copy";

					//Click Edit button to make edit controls visible
					testRunner.ClickByName("3D View Edit");
					testRunner.Wait(1);
					int partCountBeforeCopy = view3D.MeshGroups.Count();
					resultsHarness.AddTestResult(partCountBeforeCopy == 1);

					for (int i = 0; i <= 4; i++)
					{
						testRunner.ClickByName(copyButtonName);
						testRunner.Wait(1);
					}

					testRunner.Wait(1);

					int meshCountAfterCopy = view3D.MeshGroups.Count();
					testRunner.ClickByName("3D View Remove");
					System.Threading.Thread.Sleep(2000);
					int meshCountAfterRemove = view3D.MeshGroups.Count();
					resultsHarness.AddTestResult(meshCountAfterRemove == 5);

					testRunner.ClickByName("3D View Undo");
					System.Threading.Thread.Sleep(2000);
					int meshCountAfterUndo = view3D.MeshGroups.Count();
					resultsHarness.AddTestResult(meshCountAfterUndo == 6);

					testRunner.ClickByName("3D View Redo");
					System.Threading.Thread.Sleep(2000);
					int meshCountAfterRedo = view3D.MeshGroups.Count();
					resultsHarness.AddTestResult(meshCountAfterRedo == 5);

					MatterControlUtilities.CloseMatterControl(testRunner);
				}
			};

			AutomationTesterHarness testHarness = MatterControlUtilities.RunTest(testToRun);

			Assert.IsTrue(testHarness.AllTestsPassed);
			Assert.IsTrue(testHarness.TestCount == 4); // make sure we ran all our tests
		}

		[Test, RequiresSTA, RunInApplicationDomain]
		public void SaveAsToQueue()
		{
			// Run a copy of MatterControl
			Action<AutomationTesterHarness> testToRun = (AutomationTesterHarness resultsHarness) =>
			{
				AutomationRunner testRunner = new AutomationRunner(MatterControlUtilities.DefaultTestImages);
				{

					//Navigate to Local Library
					testRunner.ClickByName("Library Tab");
					MatterControlUtilities.NavigateToFolder(testRunner, "Local Library Row Item Collection");
					testRunner.Wait(1);
					testRunner.ClickByName("Row Item Calibration - Box");
					testRunner.ClickByName("Row Item Calibration - Box Print Button");
					testRunner.Wait(1);

					//Click Edit button to make edit controls visible
					testRunner.ClickByName("3D View Edit");
					testRunner.Wait(1);

					for (int i = 0; i <= 2; i++)
					{
						testRunner.ClickByName("3D View Copy");
						testRunner.Wait(1);
					}

					//Click Save As button to save changes to the part
					testRunner.ClickByName("Save As Menu");
					testRunner.Wait(1);
					testRunner.ClickByName("Save As Menu Item");
					testRunner.Wait(1);

					//Type in name of new part and then save to Print Queue
					testRunner.Type("Save As Print Queue");
					MatterControlUtilities.NavigateToFolder(testRunner,"Print Queue Row Item Collection");
					testRunner.Wait(1);
					testRunner.ClickByName("Save As Save Button");

					//Make sure there is a new Queue item with a name that matcheds the new opart
					testRunner.Wait(1);
					testRunner.ClickByName("Queue Tab");
					testRunner.Wait(1);
					resultsHarness.AddTestResult(testRunner.WaitForName("Queue Item Save As Print Queue", 5));

					MatterControlUtilities.CloseMatterControl(testRunner);
				}
			};

			AutomationTesterHarness testHarness = MatterControlUtilities.RunTest(testToRun);

			Assert.IsTrue(testHarness.AllTestsPassed);
			Assert.IsTrue(testHarness.TestCount == 1); // make sure we ran all our tests
		}

		[Test, RequiresSTA, RunInApplicationDomain]
		public void SaveAsToLocalLibrary()
		{
			// Run a copy of MatterControl
			Action<AutomationTesterHarness> testToRun = (AutomationTesterHarness resultsHarness) =>
			{
				AutomationRunner testRunner = new AutomationRunner(MatterControlUtilities.DefaultTestImages);
				{

					//Navigate to Local Library
					testRunner.ClickByName("Library Tab");
					MatterControlUtilities.NavigateToFolder(testRunner, "Local Library Row Item Collection");
					testRunner.Wait(1);
					testRunner.ClickByName("Row Item Calibration - Box");
					testRunner.ClickByName("Row Item Calibration - Box Print Button");
					testRunner.Wait(1);

					//Click Edit button to make edit controls visible
					testRunner.ClickByName("3D View Edit");
					testRunner.Wait(1);

					for (int i = 0; i <= 2; i++)
					{
						testRunner.ClickByName("3D View Copy");
						testRunner.Wait(1);
					}

					//Click Save As button to save changes to the part
					testRunner.ClickByName("Save As Menu");
					testRunner.Wait(1);
					testRunner.ClickByName("Save As Menu Item");
					testRunner.Wait(1);

					//Type in name of new part and then save to Local Library
					testRunner.Type("Save As Local Library");
					MatterControlUtilities.NavigateToFolder(testRunner, "Local Library Row Item Collection");
					testRunner.Wait(1);
					testRunner.ClickByName("Save As Save Button");

					//Make sure there is a new Local Library item with a name that matcheds the new opart
					testRunner.Wait(1);
					testRunner.ClickByName("Library Tab");
					testRunner.Wait(10);
					resultsHarness.AddTestResult(testRunner.WaitForName("Row Item Save As Local Library", 5));

					MatterControlUtilities.CloseMatterControl(testRunner);
				}
			};

			AutomationTesterHarness testHarness = MatterControlUtilities.RunTest(testToRun);

			Assert.IsTrue(testHarness.AllTestsPassed);
			Assert.IsTrue(testHarness.TestCount == 1); // make sure we ran all our tests
		}

		[Test, RequiresSTA, RunInApplicationDomain]
		public void SaveAsToDownloads()
		{
			// Run a copy of MatterControl
			Action<AutomationTesterHarness> testToRun = (AutomationTesterHarness resultsHarness) =>
			{
				AutomationRunner testRunner = new AutomationRunner(MatterControlUtilities.DefaultTestImages);
				{

					//Navigate to Downloads
					testRunner.ClickByName("Library Tab");
					MatterControlUtilities.NavigateToFolder(testRunner, "Local Library Row Item Collection");
					testRunner.Wait(1);
					testRunner.ClickByName("Row Item Calibration - Box");
					testRunner.ClickByName("Row Item Calibration - Box Print Button");
					testRunner.Wait(1);

					//Click Edit button to make edit controls visible
					testRunner.ClickByName("3D View Edit");
					testRunner.Wait(1);

					for (int i = 0; i <= 2; i++)
					{
						testRunner.ClickByName("3D View Copy");
						testRunner.Wait(1);
					}

					//Click Save As button to save changes to the part
					testRunner.ClickByName("Save As Menu");
					testRunner.Wait(1);
					testRunner.ClickByName("Save As Menu Item");
					testRunner.Wait(1);

					//Type in name of new part and then save to Downloads
					testRunner.Type("Save As Downloads");
					MatterControlUtilities.NavigateToFolder(testRunner, "Downloads Row Item Collection");
					testRunner.Wait(1);
					testRunner.ClickByName("Save As Save Button");

					//Make sure there is a new Downloads item with a name that matches the new opart
					testRunner.Wait(1);
					testRunner.ClickByName("Library Tab");
					testRunner.ClickByName("Bread Crumb Button Home");
					testRunner.Wait(1);
					MatterControlUtilities.NavigateToFolder(testRunner, "Downloads Row Item Collection");
					resultsHarness.AddTestResult(testRunner.WaitForName("Row Item Save As Downloads", 5));

					//Do clean up for Downloads
					testRunner.ClickByName("Row Item Save As Downloads", 2);
					testRunner.ClickByName("Library Edit Button");
					testRunner.ClickByName("Library Remove Item Button");

					MatterControlUtilities.CloseMatterControl(testRunner);
				}
			};

			AutomationTesterHarness testHarness = MatterControlUtilities.RunTest(testToRun);

			Assert.IsTrue(testHarness.AllTestsPassed);
			Assert.IsTrue(testHarness.TestCount == 1); // make sure we ran all our tests
		}
	}
}


text:
#ifndef ASSIMP_BUILD_NO_OGRE_IMPORTER

#include "OgreStructs.h"
#include "TinyFormatter.h"

namespace Assimp
{
namespace Ogre
{

// VertexElement

VertexElement::VertexElement() :
	index(0),
	source(0),
	offset(0),
	type(VET_FLOAT1),
	semantic(VES_POSITION)
{
}

size_t VertexElement::Size() const
{
	return TypeSize(type);
}

size_t VertexElement::ComponentCount() const
{
	return ComponentCount(type);
}

size_t VertexElement::ComponentCount(Type type)
{
	switch(type)
	{
		case VET_COLOUR:
		case VET_COLOUR_ABGR:
		case VET_COLOUR_ARGB:
		case VET_FLOAT1:
		case VET_DOUBLE1:
		case VET_SHORT1:
		case VET_USHORT1:
		case VET_INT1:
		case VET_UINT1:
			return 1;
		case VET_FLOAT2:
		case VET_DOUBLE2:
		case VET_SHORT2:
		case VET_USHORT2:
		case VET_INT2:
		case VET_UINT2:
			return 2;
		case VET_FLOAT3:
		case VET_DOUBLE3:
		case VET_SHORT3:
		case VET_USHORT3:
		case VET_INT3:
		case VET_UINT3:
			return 3;
		case VET_FLOAT4:
		case VET_DOUBLE4:
		case VET_SHORT4:
		case VET_USHORT4:
		case VET_INT4:
		case VET_UINT4:
		case VET_UBYTE4:
			return 4;
	}
	return 0;
}

size_t VertexElement::TypeSize(Type type)
{
	switch(type)
	{
		case VET_COLOUR:
		case VET_COLOUR_ABGR:
		case VET_COLOUR_ARGB:
			return sizeof(unsigned int);
		case VET_FLOAT1:
			return sizeof(float);
		case VET_FLOAT2:
			return sizeof(float)*2;
		case VET_FLOAT3:
			return sizeof(float)*3;
		case VET_FLOAT4:
			return sizeof(float)*4;
		case VET_DOUBLE1:
			return sizeof(double);
		case VET_DOUBLE2:
			return sizeof(double)*2;
		case VET_DOUBLE3:
			return sizeof(double)*3;
		case VET_DOUBLE4:
			return sizeof(double)*4;
		case VET_SHORT1:
			return sizeof(short);
		case VET_SHORT2:
			return sizeof(short)*2;
		case VET_SHORT3:
			return sizeof(short)*3;
		case VET_SHORT4:
			return sizeof(short)*4;
		case VET_USHORT1:
			return sizeof(unsigned short);
		case VET_USHORT2:
			return sizeof(unsigned short)*2;
		case VET_USHORT3:
			return sizeof(unsigned short)*3;
		case VET_USHORT4:
			return sizeof(unsigned short)*4;
		case VET_INT1:
			return sizeof(int);
		case VET_INT2:
			return sizeof(int)*2;
		case VET_INT3:
			return sizeof(int)*3;
		case VET_INT4:
			return sizeof(int)*4;
		case VET_UINT1:
			return sizeof(unsigned int);
		case VET_UINT2:
			return sizeof(unsigned int)*2;
		case VET_UINT3:
			return sizeof(unsigned int)*3;
		case VET_UINT4:
			return sizeof(unsigned int)*4;
		case VET_UBYTE4:
			return sizeof(unsigned char)*4;
	}
	return 0;
}

std::string VertexElement::TypeToString()
{
	return TypeToString(type);
}

std::string VertexElement::TypeToString(Type type)
{
	switch(type)
	{
		case VET_COLOUR:		return "COLOUR";
		case VET_COLOUR_ABGR:	return "COLOUR_ABGR";
		case VET_COLOUR_ARGB:	return "COLOUR_ARGB";
		case VET_FLOAT1:		return "FLOAT1";
		case VET_FLOAT2:		return "FLOAT2";
		case VET_FLOAT3:		return "FLOAT3";
		case VET_FLOAT4:		return "FLOAT4";
		case VET_DOUBLE1:		return "DOUBLE1";
		case VET_DOUBLE2:		return "DOUBLE2";
		case VET_DOUBLE3:		return "DOUBLE3";
		case VET_DOUBLE4:		return "DOUBLE4";
		case VET_SHORT1:		return "SHORT1";
		case VET_SHORT2:		return "SHORT2";
		case VET_SHORT3:		return "SHORT3";
		case VET_SHORT4:		return "SHORT4";
		case VET_USHORT1:		return "USHORT1";
		case VET_USHORT2:		return "USHORT2";
		case VET_USHORT3:		return "USHORT3";
		case VET_USHORT4:		return "USHORT4";
		case VET_INT1:			return "INT1";
		case VET_INT2:			return "INT2";
		case VET_INT3:			return "INT3";
		case VET_INT4:			return "INT4";
		case VET_UINT1:			return "UINT1";
		case VET_UINT2:			return "UINT2";
		case VET_UINT3:			return "UINT3";
		case VET_UINT4:			return "UINT4";
		case VET_UBYTE4:		return "UBYTE4";
	}
	return "Uknown_VertexElement::Type";
}

std::string VertexElement::SemanticToString()
{
	return SemanticToString(semantic);
}

std::string VertexElement::SemanticToString(Semantic semantic)
{
	switch(semantic)
	{
		case VES_POSITION:				return "POSITION";
		case VES_BLEND_WEIGHTS:			return "BLEND_WEIGHTS";
		case VES_BLEND_INDICES:			return "BLEND_INDICES";
		case VES_NORMAL:				return "NORMAL";
		case VES_DIFFUSE:				return "DIFFUSE";
		case VES_SPECULAR:				return "SPECULAR";
		case VES_TEXTURE_COORDINATES:	return "TEXTURE_COORDINATES";
		case VES_BINORMAL:				return "BINORMAL";
		case VES_TANGENT:				return "TANGENT";
	}
	return "Uknown_VertexElement::Semantic";
}

// IVertexData

IVertexData::IVertexData() :
	count(0)
{
}

bool IVertexData::HasBoneAssignments() const
{
	return !boneAssignments.empty();
}

void IVertexData::AddVertexMapping(uint32_t oldIndex, uint32_t newIndex)
{
	BoneAssignmentsForVertex(oldIndex, newIndex, boneAssignmentsMap[newIndex]);
	vertexIndexMapping[oldIndex].push_back(newIndex);
}

void IVertexData::BoneAssignmentsForVertex(uint32_t currentIndex, uint32_t newIndex, VertexBoneAssignmentList &dest) const
{
	for (VertexBoneAssignmentList::const_iterator iter=boneAssignments.begin(), end=boneAssignments.end();
		iter!=end; ++iter)
	{
		if (iter->vertexIndex == currentIndex)
		{
			VertexBoneAssignment a = (*iter);
			a.vertexIndex = newIndex;
			dest.push_back(a);
		}
	}
}

AssimpVertexBoneWeightList IVertexData::AssimpBoneWeights(size_t vertices)
{
	AssimpVertexBoneWeightList weights;
	for(size_t vi=0; vi<vertices; ++vi)
	{
		VertexBoneAssignmentList &vertexWeights = boneAssignmentsMap[vi];
		for (VertexBoneAssignmentList::const_iterator iter=vertexWeights.begin(), end=vertexWeights.end();
			iter!=end; ++iter)
		{
			std::vector<aiVertexWeight> &boneWeights = weights[iter->boneIndex];
			boneWeights.push_back(aiVertexWeight(vi, iter->weight));
		}
	}
	return weights;
}

std::set<uint16_t> IVertexData::ReferencedBonesByWeights() const
{
	std::set<uint16_t> referenced;
	for (VertexBoneAssignmentList::const_iterator iter=boneAssignments.begin(), end=boneAssignments.end();
		iter!=end; ++iter)
	{
		referenced.insert(iter->boneIndex);
	}
	return referenced;
}

// VertexData

VertexData::VertexData()
{
}

VertexData::~VertexData()
{
	Reset();
}

void VertexData::Reset()
{
	// Releases shared ptr memory streams.
	vertexBindings.clear();
	vertexElements.clear();
}

uint32_t VertexData::VertexSize(uint16_t source) const
{
	uint32_t size = 0;
	for(VertexElementList::const_iterator iter=vertexElements.begin(), end=vertexElements.end(); iter != end; ++iter)
	{
		if (iter->source == source)
			size += iter->Size();
	}
	return size;
}

MemoryStream *VertexData::VertexBuffer(uint16_t source)
{
	if (vertexBindings.find(source) != vertexBindings.end())
		return vertexBindings[source].get();
	return 0;
}

VertexElement *VertexData::GetVertexElement(VertexElement::Semantic semantic, uint16_t index)
{
	for(VertexElementList::iterator iter=vertexElements.begin(), end=vertexElements.end(); iter != end; ++iter)
	{
		VertexElement &element = (*iter);
		if (element.semantic == semantic && element.index == index)
			return &element;
	}
	return 0;
}

// VertexDataXml

VertexDataXml::VertexDataXml()
{
}

bool VertexDataXml::HasPositions() const
{
	return !positions.empty();
}

bool VertexDataXml::HasNormals() const
{
	return !normals.empty();
}

bool VertexDataXml::HasTangents() const
{
	return !tangents.empty();
}

bool VertexDataXml::HasUvs() const
{
	return !uvs.empty();
}

size_t VertexDataXml::NumUvs() const
{
	return uvs.size();
}

// IndexData

IndexData::IndexData() :
	count(0),
	faceCount(0),
	is32bit(false)
{
}

IndexData::~IndexData()
{
	Reset();
}

void IndexData::Reset()
{
	// Release shared ptr memory stream.
	buffer.reset();
}

size_t IndexData::IndexSize() const
{
	return (is32bit ? sizeof(uint32_t) : sizeof(uint16_t));
}

size_t IndexData::FaceSize() const
{
	return IndexSize() * 3;
}

// Mesh

Mesh::Mesh() :
	hasSkeletalAnimations(false),
	skeleton(NULL),
	sharedVertexData(NULL)
{
}

Mesh::~Mesh()
{
	Reset();
}

void Mesh::Reset()
{
	OGRE_SAFE_DELETE(skeleton)
	OGRE_SAFE_DELETE(sharedVertexData)

	for(size_t i=0, len=subMeshes.size(); i<len; ++i) {
		OGRE_SAFE_DELETE(subMeshes[i])
	}
	subMeshes.clear();
	for(size_t i=0, len=animations.size(); i<len; ++i) {
		OGRE_SAFE_DELETE(animations[i])
	}
	animations.clear();
	for(size_t i=0, len=poses.size(); i<len; ++i) {
		OGRE_SAFE_DELETE(poses[i])
	}
	poses.clear();
}

size_t Mesh::NumSubMeshes() const
{
	return subMeshes.size();
}

SubMesh *Mesh::GetSubMesh(uint16_t index) const
{
	for(size_t i=0; i<subMeshes.size(); ++i)
		if (subMeshes[i]->index == index)
			return subMeshes[i];
	return 0;
}

void Mesh::ConvertToAssimpScene(aiScene* dest)
{
	// Setup
	dest->mNumMeshes = NumSubMeshes();
	dest->mMeshes = new aiMesh*[dest->mNumMeshes];

	// Create root node
	dest->mRootNode = new aiNode();
	dest->mRootNode->mNumMeshes = dest->mNumMeshes;
	dest->mRootNode->mMeshes = new unsigned int[dest->mRootNode->mNumMeshes];

	// Export meshes
	for(size_t i=0; i<dest->mNumMeshes; ++i)
	{
		dest->mMeshes[i] = subMeshes[i]->ConvertToAssimpMesh(this);
		dest->mRootNode->mMeshes[i] = i;
	}

	// Export skeleton
	if (skeleton)
	{
		// Bones
		if (!skeleton->bones.empty())
		{
			BoneList rootBones = skeleton->RootBones();
			dest->mRootNode->mNumChildren = rootBones.size();
			dest->mRootNode->mChildren = new aiNode*[dest->mRootNode->mNumChildren];

			for(size_t i=0, len=rootBones.size(); i<len; ++i)
			{
				dest->mRootNode->mChildren[i] = rootBones[i]->ConvertToAssimpNode(skeleton, dest->mRootNode);
			}
		}

		// Animations
		if (!skeleton->animations.empty())
		{
			dest->mNumAnimations = skeleton->animations.size();
			dest->mAnimations = new aiAnimation*[dest->mNumAnimations];

			for(size_t i=0, len=skeleton->animations.size(); i<len; ++i)
			{
				dest->mAnimations[i] = skeleton->animations[i]->ConvertToAssimpAnimation();
			}
		}
	}
}

// ISubMesh

ISubMesh::ISubMesh() :
	index(0),
	materialIndex(-1),
	usesSharedVertexData(false),
	operationType(OT_POINT_LIST)
{
}

// SubMesh

SubMesh::SubMesh() :
	vertexData(0),
	indexData(new IndexData())
{
}

SubMesh::~SubMesh()
{
	Reset();
}

void SubMesh::Reset()
{
	OGRE_SAFE_DELETE(vertexData)
	OGRE_SAFE_DELETE(indexData)
}

aiMesh *SubMesh::ConvertToAssimpMesh(Mesh *parent)
{
	if (operationType != OT_TRIANGLE_LIST) {
		throw DeadlyImportError(Formatter::format() << "Only mesh operation type OT_TRIANGLE_LIST is supported. Found " << operationType);
	}

	aiMesh *dest = new aiMesh();
	dest->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;

	if (!name.empty())
		dest->mName = name;

	// Material index
	if (materialIndex != -1)
		dest->mMaterialIndex = materialIndex;

	// Pick source vertex data from shader geometry or from internal geometry.
	VertexData *src = (!usesSharedVertexData ? vertexData : parent->sharedVertexData);

	VertexElement *positionsElement = src->GetVertexElement(VertexElement::VES_POSITION);
	VertexElement *normalsElement   = src->GetVertexElement(VertexElement::VES_NORMAL);
	VertexElement *uv1Element       = src->GetVertexElement(VertexElement::VES_TEXTURE_COORDINATES, 0);
	VertexElement *uv2Element       = src->GetVertexElement(VertexElement::VES_TEXTURE_COORDINATES, 1);

	// Sanity checks
	if (!positionsElement) {
		throw DeadlyImportError("Failed to import Ogre VertexElement::VES_POSITION. Mesh does not have vertex positions!");
	} else if (positionsElement->type != VertexElement::VET_FLOAT3) {
		throw DeadlyImportError("Ogre Mesh position vertex element type != VertexElement::VET_FLOAT3. This is not supported.");
	} else if (normalsElement && normalsElement->type != VertexElement::VET_FLOAT3) {
		throw DeadlyImportError("Ogre Mesh normal vertex element type != VertexElement::VET_FLOAT3. This is not supported.");
	}

	// Faces
	dest->mNumFaces = indexData->faceCount;
	dest->mFaces = new aiFace[dest->mNumFaces];

	// Assimp required unique vertices, we need to convert from Ogres shared indexing.
	size_t uniqueVertexCount = dest->mNumFaces * 3;
	dest->mNumVertices = uniqueVertexCount;
	dest->mVertices = new aiVector3D[dest->mNumVertices];

	// Source streams
	MemoryStream *positions      = src->VertexBuffer(positionsElement->source);
	MemoryStream *normals        = (normalsElement ? src->VertexBuffer(normalsElement->source) : 0);
	MemoryStream *uv1            = (uv1Element ? src->VertexBuffer(uv1Element->source) : 0);
	MemoryStream *uv2            = (uv2Element ? src->VertexBuffer(uv2Element->source) : 0);

	// Element size
	const size_t sizePosition    = positionsElement->Size();
	const size_t sizeNormal      = (normalsElement ? normalsElement->Size() : 0);
	const size_t sizeUv1         = (uv1Element ? uv1Element->Size() : 0);
	const size_t sizeUv2         = (uv2Element ? uv2Element->Size() : 0);

	// Vertex width
	const size_t vWidthPosition  = src->VertexSize(positionsElement->source);
	const size_t vWidthNormal    = (normalsElement ? src->VertexSize(normalsElement->source) : 0);
	const size_t vWidthUv1       = (uv1Element ? src->VertexSize(uv1Element->source) : 0);
	const size_t vWidthUv2       = (uv2Element ? src->VertexSize(uv2Element->source) : 0);

	bool boneAssignments = src->HasBoneAssignments();

	// Prepare normals
	if (normals)
		dest->mNormals = new aiVector3D[dest->mNumVertices];

	// Prepare UVs, ignoring incompatible UVs.
	if (uv1)
	{
		if (uv1Element->type == VertexElement::VET_FLOAT2 || uv1Element->type == VertexElement::VET_FLOAT3)
		{
			dest->mNumUVComponents[0] = uv1Element->ComponentCount();
			dest->mTextureCoords[0] = new aiVector3D[dest->mNumVertices];
		}
		else
		{
			DefaultLogger::get()->warn(Formatter::format() << "Ogre imported UV0 type " << uv1Element->TypeToString() << " is not compatible with Assimp. Ignoring UV.");
			uv1 = 0;
		}
	}
	if (uv2)
	{
		if (uv2Element->type == VertexElement::VET_FLOAT2 || uv2Element->type == VertexElement::VET_FLOAT3)
		{
			dest->mNumUVComponents[1] = uv2Element->ComponentCount();
			dest->mTextureCoords[1] = new aiVector3D[dest->mNumVertices];
		}
		else
		{
			DefaultLogger::get()->warn(Formatter::format() << "Ogre imported UV0 type " << uv2Element->TypeToString() << " is not compatible with Assimp. Ignoring UV.");
			uv2 = 0;
		}
	}

	aiVector3D *uv1Dest = (uv1 ? dest->mTextureCoords[0] : 0);
	aiVector3D *uv2Dest = (uv2 ? dest->mTextureCoords[1] : 0);

	MemoryStream *faces = indexData->buffer.get();
	for (size_t fi=0, isize=indexData->IndexSize(), fsize=indexData->FaceSize();
		 fi<dest->mNumFaces; ++fi)
	{
		// Source Ogre face
		aiFace ogreFace;
		ogreFace.mNumIndices = 3;
		ogreFace.mIndices = new unsigned int[3];

		faces->Seek(fi * fsize, aiOrigin_SET);
		if (indexData->is32bit)
		{
			faces->Read(&ogreFace.mIndices[0], isize, 3);
		}
		else
		{
			uint16_t iout = 0;
			for (size_t ii=0; ii<3; ++ii)
			{
				faces->Read(&iout, isize, 1);
				ogreFace.mIndices[ii] = static_cast<unsigned int>(iout);
			}
		}

		// Destination Assimp face
		aiFace &face = dest->mFaces[fi];
		face.mNumIndices = 3;
		face.mIndices = new unsigned int[3];

		const size_t pos = fi * 3;
		for (size_t v=0; v<3; ++v)
		{
			const size_t newIndex = pos + v;

			// Write face index
			face.mIndices[v] = newIndex;

			// Ogres vertex index to ref into the source buffers.
			const size_t ogreVertexIndex = ogreFace.mIndices[v];
			src->AddVertexMapping(ogreVertexIndex, newIndex);

			// Position
			positions->Seek((vWidthPosition * ogreVertexIndex) + positionsElement->offset, aiOrigin_SET);
			positions->Read(&dest->mVertices[newIndex], sizePosition, 1);

			// Normal
			if (normals)
			{
				normals->Seek((vWidthNormal * ogreVertexIndex) + normalsElement->offset, aiOrigin_SET);
				normals->Read(&dest->mNormals[newIndex], sizeNormal, 1);
			}
			// UV0
			if (uv1 && uv1Dest)
			{
				uv1->Seek((vWidthUv1 * ogreVertexIndex) + uv1Element->offset, aiOrigin_SET);
				uv1->Read(&uv1Dest[newIndex], sizeUv1, 1);
				uv1Dest[newIndex].y = (uv1Dest[newIndex].y * -1) + 1; // Flip UV from Ogre to Assimp form
			}
			// UV1
			if (uv2 && uv2Dest)
			{
				uv2->Seek((vWidthUv2 * ogreVertexIndex) + uv2Element->offset, aiOrigin_SET);
				uv2->Read(&uv2Dest[newIndex], sizeUv2, 1);
				uv2Dest[newIndex].y = (uv2Dest[newIndex].y * -1) + 1; // Flip UV from Ogre to Assimp form
			}
		}
	}

	// Bones and bone weights
	if (parent->skeleton && boneAssignments)
	{
		AssimpVertexBoneWeightList weights = src->AssimpBoneWeights(dest->mNumVertices);
		std::set<uint16_t> referencedBones = src->ReferencedBonesByWeights();

		dest->mNumBones = referencedBones.size();
		dest->mBones = new aiBone*[dest->mNumBones];

		size_t assimpBoneIndex = 0;
		for(std::set<uint16_t>::const_iterator rbIter=referencedBones.begin(), rbEnd=referencedBones.end(); rbIter != rbEnd; ++rbIter, ++assimpBoneIndex)
		{
			Bone *bone = parent->skeleton->BoneById((*rbIter));
			dest->mBones[assimpBoneIndex] = bone->ConvertToAssimpBone(parent->skeleton, weights[bone->id]);
		}
	}

	return dest;
}

// MeshXml

MeshXml::MeshXml() :
	skeleton(0),
	sharedVertexData(0)
{
}

MeshXml::~MeshXml()
{
	Reset();
}

void MeshXml::Reset()
{
	OGRE_SAFE_DELETE(skeleton)
	OGRE_SAFE_DELETE(sharedVertexData)

	for(size_t i=0, len=subMeshes.size(); i<len; ++i) {
		OGRE_SAFE_DELETE(subMeshes[i])
	}
	subMeshes.clear();
}

size_t MeshXml::NumSubMeshes() const
{
	return subMeshes.size();
}

SubMeshXml *MeshXml::GetSubMesh(uint16_t index) const
{
	for(size_t i=0; i<subMeshes.size(); ++i)
		if (subMeshes[i]->index == index)
			return subMeshes[i];
	return 0;
}

void MeshXml::ConvertToAssimpScene(aiScene* dest)
{
	// Setup
	dest->mNumMeshes = NumSubMeshes();
	dest->mMeshes = new aiMesh*[dest->mNumMeshes];

	// Create root node
	dest->mRootNode = new aiNode();
	dest->mRootNode->mNumMeshes = dest->mNumMeshes;
	dest->mRootNode->mMeshes = new unsigned int[dest->mRootNode->mNumMeshes];

	// Export meshes
	for(size_t i=0; i<dest->mNumMeshes; ++i)
	{
		dest->mMeshes[i] = subMeshes[i]->ConvertToAssimpMesh(this);
		dest->mRootNode->mMeshes[i] = i;
	}

	// Export skeleton
	if (skeleton)
	{
		// Bones
		if (!skeleton->bones.empty())
		{
			BoneList rootBones = skeleton->RootBones();
			dest->mRootNode->mNumChildren = rootBones.size();
			dest->mRootNode->mChildren = new aiNode*[dest->mRootNode->mNumChildren];

			for(size_t i=0, len=rootBones.size(); i<len; ++i)
			{
				dest->mRootNode->mChildren[i] = rootBones[i]->ConvertToAssimpNode(skeleton, dest->mRootNode);
			}
		}

		// Animations
		if (!skeleton->animations.empty())
		{
			dest->mNumAnimations = skeleton->animations.size();
			dest->mAnimations = new aiAnimation*[dest->mNumAnimations];

			for(size_t i=0, len=skeleton->animations.size(); i<len; ++i)
			{
				dest->mAnimations[i] = skeleton->animations[i]->ConvertToAssimpAnimation();
			}
		}
	}
}

// SubMeshXml

SubMeshXml::SubMeshXml() :
	indexData(new IndexDataXml()),
	vertexData(0)
{
}

SubMeshXml::~SubMeshXml()
{
	Reset();
}

void SubMeshXml::Reset()
{
	OGRE_SAFE_DELETE(indexData)
	OGRE_SAFE_DELETE(vertexData)
}

aiMesh *SubMeshXml::ConvertToAssimpMesh(MeshXml *parent)
{
	aiMesh *dest = new aiMesh();
	dest->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;

	if (!name.empty())
		dest->mName = name;

	// Material index
	if (materialIndex != -1)
		dest->mMaterialIndex = materialIndex;

	// Faces
	dest->mNumFaces = indexData->faceCount;
	dest->mFaces = new aiFace[dest->mNumFaces];

	// Assimp required unique vertices, we need to convert from Ogres shared indexing.
	size_t uniqueVertexCount = dest->mNumFaces * 3;
	dest->mNumVertices = uniqueVertexCount;
	dest->mVertices = new aiVector3D[dest->mNumVertices];

	VertexDataXml *src = (!usesSharedVertexData ? vertexData : parent->sharedVertexData);
	bool boneAssignments = src->HasBoneAssignments();
	bool normals = src->HasNormals();
	size_t uvs = src->NumUvs();

	// Prepare normals
	if (normals)
		dest->mNormals = new aiVector3D[dest->mNumVertices];

	// Prepare UVs
	for(size_t uvi=0; uvi<uvs; ++uvi)
	{
		dest->mNumUVComponents[uvi] = 2;
		dest->mTextureCoords[uvi] = new aiVector3D[dest->mNumVertices];
	}

	for (size_t fi=0; fi<dest->mNumFaces; ++fi)
	{
		// Source Ogre face
		aiFace &ogreFace = indexData->faces[fi];

		// Destination Assimp face
		aiFace &face = dest->mFaces[fi];
		face.mNumIndices = 3;
		face.mIndices = new unsigned int[3];

		const size_t pos = fi * 3;
		for (size_t v=0; v<3; ++v)
		{
			const size_t newIndex = pos + v;

			// Write face index
			face.mIndices[v] = newIndex;

			// Ogres vertex index to ref into the source buffers.
			const size_t ogreVertexIndex = ogreFace.mIndices[v];
			src->AddVertexMapping(ogreVertexIndex, newIndex);

			// Position
			dest->mVertices[newIndex] = src->positions[ogreVertexIndex];

			// Normal
			if (normals)
				dest->mNormals[newIndex] = src->normals[ogreVertexIndex];

			// UVs
			for(size_t uvi=0; uvi<uvs; ++uvi)
			{
				aiVector3D *uvDest = dest->mTextureCoords[uvi];
				std::vector<aiVector3D> &uvSrc = src->uvs[uvi];
				uvDest[newIndex] = uvSrc[ogreVertexIndex];
			}
		}
	}

	// Bones and bone weights
	if (parent->skeleton && boneAssignments)
	{
		AssimpVertexBoneWeightList weights = src->AssimpBoneWeights(dest->mNumVertices);
		std::set<uint16_t> referencedBones = src->ReferencedBonesByWeights();

		dest->mNumBones = referencedBones.size();
		dest->mBones = new aiBone*[dest->mNumBones];

		size_t assimpBoneIndex = 0;
		for(std::set<uint16_t>::const_iterator rbIter=referencedBones.begin(), rbEnd=referencedBones.end(); rbIter != rbEnd; ++rbIter, ++assimpBoneIndex)
		{
			Bone *bone = parent->skeleton->BoneById((*rbIter));
			dest->mBones[assimpBoneIndex] = bone->ConvertToAssimpBone(parent->skeleton, weights[bone->id]);
		}
	}

	return dest;
}

// Animation

Animation::Animation(Skeleton *parent) :
	parentMesh(NULL),
	parentSkeleton(parent),
	length(0.0f),
	baseTime(-1.0f)
{
}

Animation::Animation(Mesh *parent) :
	parentMesh(parent),
	parentSkeleton(0),
	length(0.0f),
	baseTime(-1.0f)
{
}

VertexData *Animation::AssociatedVertexData(VertexAnimationTrack *track) const
{
	if (!parentMesh)
		return 0;

	bool sharedGeom = (track->target == 0);
	if (sharedGeom)
		return parentMesh->sharedVertexData;
	else
		return parentMesh->GetSubMesh(track->target-1)->vertexData;
}

aiAnimation *Animation::ConvertToAssimpAnimation()
{
	aiAnimation *anim = new aiAnimation();
	anim->mName = name;
	anim->mDuration = static_cast<double>(length);
	anim->mTicksPerSecond = 1.0;

	// Tracks
	if (!tracks.empty())
	{
		anim->mNumChannels = tracks.size();
		anim->mChannels = new aiNodeAnim*[anim->mNumChannels];

		for(size_t i=0, len=tracks.size(); i<len; ++i)
		{
			anim->mChannels[i] = tracks[i].ConvertToAssimpAnimationNode(parentSkeleton);
		}
	}
	return anim;
}

// Skeleton

Skeleton::Skeleton() :
	bones(),
	animations(),
	blendMode(ANIMBLEND_AVERAGE)
{
}

Skeleton::~Skeleton()
{
	Reset();
}

void Skeleton::Reset()
{
	for(size_t i=0, len=bones.size(); i<len; ++i) {
		OGRE_SAFE_DELETE(bones[i])
	}
	bones.clear();
	for(size_t i=0, len=animations.size(); i<len; ++i) {
		OGRE_SAFE_DELETE(animations[i])
	}
	animations.clear();
}

BoneList Skeleton::RootBones() const
{
	BoneList rootBones;
	for(BoneList::const_iterator iter = bones.begin(); iter != bones.end(); ++iter)
	{
		if (!(*iter)->IsParented())
			rootBones.push_back((*iter));
	}
	return rootBones;
}

size_t Skeleton::NumRootBones() const
{
	size_t num = 0;
	for(BoneList::const_iterator iter = bones.begin(); iter != bones.end(); ++iter)
	{
		if (!(*iter)->IsParented())
			num++;
	}
	return num;
}

Bone *Skeleton::BoneByName(const std::string &name) const
{
	for(BoneList::const_iterator iter = bones.begin(); iter != bones.end(); ++iter)
	{
		if ((*iter)->name == name)
			return (*iter);
	}
	return 0;
}

Bone *Skeleton::BoneById(uint16_t id) const
{
	for(BoneList::const_iterator iter = bones.begin(); iter != bones.end(); ++iter)
	{
		if ((*iter)->id == id)
			return (*iter);
	}
	return 0;
}

// Bone

Bone::Bone() :
	id(0),
	parent(0),
	parentId(-1),
	scale(1.0f, 1.0f, 1.0f)
{
}

bool Bone::IsParented() const
{
	return (parentId != -1 && parent != 0);
}

uint16_t Bone::ParentId() const
{
	return static_cast<uint16_t>(parentId);
}

void Bone::AddChild(Bone *bone)
{
	if (!bone)
		return;
	if (bone->IsParented())
		throw DeadlyImportError("Attaching child Bone that is already parented: " + bone->name);

	bone->parent = this;
	bone->parentId = id;
	children.push_back(bone->id);
}

void Bone::CalculateWorldMatrixAndDefaultPose(Skeleton *skeleton)
{
	if (!IsParented())
		worldMatrix = aiMatrix4x4(scale, rotation, position).Inverse();
	else
		worldMatrix = aiMatrix4x4(scale, rotation, position).Inverse() * parent->worldMatrix;

	defaultPose = aiMatrix4x4(scale, rotation, position);

	// Recursively for all children now that the parent matrix has been calculated.
	for (size_t i=0, len=children.size(); i<len; ++i)
	{
		Bone *child = skeleton->BoneById(children[i]);
		if (!child) {
			throw DeadlyImportError(Formatter::format() << "CalculateWorldMatrixAndDefaultPose: Failed to find child bone " << children[i] << " for parent " << id << " " << name);
		}
		child->CalculateWorldMatrixAndDefaultPose(skeleton);
	}
}

aiNode *Bone::ConvertToAssimpNode(Skeleton *skeleton, aiNode *parentNode)
{
	// Bone node
	aiNode* node = new aiNode(name);
	node->mParent = parentNode;
	node->mTransformation = defaultPose;

	// Children
	if (!children.empty())
	{
		node->mNumChildren = children.size();
		node->mChildren = new aiNode*[node->mNumChildren];

		for(size_t i=0, len=children.size(); i<len; ++i)
		{
			Bone *child = skeleton->BoneById(children[i]);
			if (!child) {
				throw DeadlyImportError(Formatter::format() << "ConvertToAssimpNode: Failed to find child bone " << children[i] << " for parent " << id << " " << name);
			}
			node->mChildren[i] = child->ConvertToAssimpNode(skeleton, node);
		}
	}
	return node;
}

aiBone *Bone::ConvertToAssimpBone(Skeleton * /*parent*/, const std::vector<aiVertexWeight> &boneWeights)
{
	aiBone *bone = new aiBone();
	bone->mName = name;
	bone->mOffsetMatrix = worldMatrix;

	if (!boneWeights.empty())
	{
		bone->mNumWeights = boneWeights.size();
		bone->mWeights = new aiVertexWeight[boneWeights.size()];
		memcpy(bone->mWeights, &boneWeights[0], boneWeights.size() * sizeof(aiVertexWeight));
	}

	return bone;
}

// VertexAnimationTrack

VertexAnimationTrack::VertexAnimationTrack() :
	type(VAT_NONE),
	target(0)
{
}

aiNodeAnim *VertexAnimationTrack::ConvertToAssimpAnimationNode(Skeleton *skeleton)
{
	if (boneName.empty() || type != VAT_TRANSFORM) {
		throw DeadlyImportError("VertexAnimationTrack::ConvertToAssimpAnimationNode: Cannot convert track that has no target bone name or is not type of VAT_TRANSFORM");
	}

	aiNodeAnim *nodeAnim = new aiNodeAnim();
	nodeAnim->mNodeName = boneName;

	Bone *bone = skeleton->BoneByName(boneName);
	if (!bone) {
		throw DeadlyImportError("VertexAnimationTrack::ConvertToAssimpAnimationNode: Failed to find bone " + boneName + " from parent Skeleton");
	}

	// Keyframes
	size_t numKeyframes = transformKeyFrames.size();

	nodeAnim->mPositionKeys = new aiVectorKey[numKeyframes];
	nodeAnim->mRotationKeys = new aiQuatKey[numKeyframes];
	nodeAnim->mScalingKeys = new aiVectorKey[numKeyframes];
	nodeAnim->mNumPositionKeys = numKeyframes;
	nodeAnim->mNumRotationKeys = numKeyframes;
	nodeAnim->mNumScalingKeys  = numKeyframes;

	for(size_t kfi=0; kfi<numKeyframes; ++kfi)
	{
		TransformKeyFrame &kfSource = transformKeyFrames[kfi];

		// Calculate the complete transformation from world space to bone space
		aiVector3D pos; aiQuaternion rot; aiVector3D scale;

		aiMatrix4x4 finalTransform = bone->defaultPose * kfSource.Transform();
		finalTransform.Decompose(scale, rot, pos);

		double t = static_cast<double>(kfSource.timePos);
		nodeAnim->mPositionKeys[kfi].mTime = t;
		nodeAnim->mRotationKeys[kfi].mTime = t;
		nodeAnim->mScalingKeys[kfi].mTime = t;

		nodeAnim->mPositionKeys[kfi].mValue = pos;
		nodeAnim->mRotationKeys[kfi].mValue = rot;
		nodeAnim->mScalingKeys[kfi].mValue = scale;
	}

	return nodeAnim;
}

// TransformKeyFrame

TransformKeyFrame::TransformKeyFrame() :
	timePos(0.0f),
	scale(1.0f, 1.0f, 1.0f)
{
}

aiMatrix4x4 TransformKeyFrame::Transform()
{
	return aiMatrix4x4(scale, rotation, position);
}

} // Ogre
} // Assimp

#endif // ASSIMP_BUILD_NO_OGRE_IMPORTER


text:
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>
                {{title}}

Selected Values:

                            <input type="checkbox" data-bind="checked: $parent.checkedOptions" value="{{$data}}">

                <form>

                        Filter
                        <input type="text" class="form-control filter-box" data-bind="textInput: filter">

                </form>

                            <input type="checkbox" data-bind="checked: $parent.checkedOptions" value="{{$data}}">

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


text:
export const up = knex => Promise.resolve(
  knex.schema.createTable('albums', table => {
    table.increments('id').primary();
    table.string('name').notNullable();
    table.integer('genres_id').references('genres.id').notNullable();
    table.integer('artists_id').references('artists.id').notNullable();
    table.string('spotify_id').notNullable();
    table.string('slug').notNullable();
    table.decimal('average_rating', 3, 1).defaultTo(0.0);
    table.integer('reviews_count').defaultTo(0);
    table.timestamps(true, true);
    table.index(['slug']);
    table.index(['spotify_id']);
  }),
);

export const down = knex => Promise.resolve(knex.schema.dropTable('albums'));


text:
// +build linux

package common

import (
	"log"
	"os"
	"os/signal"
	"runtime"
	"runtime/pprof"
	"syscall"
)

// Profile start profiling loop
func Profile() {
	cpu := make(chan os.Signal, 1)
	signal.Notify(cpu, syscall.SIGUSR1)

	memory := make(chan os.Signal, 1)
	signal.Notify(memory, syscall.SIGUSR2)

	for {
		select {
		case <-cpu:
			f, err := os.Create("/tmp/skydive-cpu.prof")
			if err != nil {
				log.Fatal("could not create CPU profile: ", err)
			}
			if err := pprof.StartCPUProfile(f); err != nil {
				log.Fatal("could not start CPU profile: ", err)
			}
			log.Println("CPU profiling Started")

			<-cpu

			pprof.StopCPUProfile()
			f.Close()
			log.Println("CPU profiling Stopped")
		case <-memory:
			// Memory Profile
			runtime.GC()
			memProfile, err := os.Create("/tmp/skydive-memory.prof")
			if err != nil {
				log.Fatal(err)
			}
			if err := pprof.WriteHeapProfile(memProfile); err != nil {
				log.Fatal(err)
			}
			memProfile.Close()
			log.Println("Memory profiling written")
		}
	}
}


text:
/**
 * Created by lx on 2017/2/23.
 */
/**************************************************************************
 * Root reducer                                                           *
 *                                                                        *
 * We will pass to our store just one reducer to handle all the state     *
 * by combining all the reducers                                          *
 *                                                                        *
 * routerStateReducer will provide to the store the routers state so that *
 * we are able to extract it from the store                               *
 **************************************************************************/

import {combineReducers} from 'redux'
import {routerStateReducer} from 'redux-router'

// 真正开发项目的时候State会涉及很多功能,在一个Reducer处理所有逻辑会非常混乱
// 所以需要拆分成多个小Reducer,每个Reducer只处理它管理的那部分State数据。然后在由一个主rootReducers来专门管理这些小Reducer。
// Redux提供了一个方法 combineReducers 专门来管理这些小Reducer。

// Import reducers
import mainLayoutReducer from './MainLayoutReducer';
import Increase from './increaseReducer';
import Theme from './themeReducer';

const rootReducer = combineReducers({
  mainLayoutReducer,
  Increase,
  Theme,
  router: routerStateReducer
});

export default rootReducer

// ================================
// 同步的 Reducers(即应用初始化所必需的)
// ================================
// const syncReducers = {
//   router: routerReducer,
//   userData: userReducer
// };

// var initState = {
//   counter: 0,
//   todos: []
// }

// function reducer(state, action) {
//   // ※ 应用的初始状态是在第一次执行 reducer 时设置的 ※
//   if (!state) state = initState
//
//   switch (action.type) {
//     case 'ADD_TODO':
//       var nextState = _.cloneDeep(state) // 用到了 lodash 的深克隆
//       nextState.todos.push(action.payload)
//       return nextState
//
//     default:
//       // 由于 nextState 会把原 state 整个替换掉
//       // 若无修改,必须返回原 state(否则就是 undefined)
//       return state
//   }
// }

// ================================
// 异步加载的 Reducers(Code Splitting 按需加载的)
// ================================
// const asyncReducers = {}

/**
 * @return {Function} rootReducer
 */
// export function createRootReducer() {
//   return combineReducers({
//     ...syncReducers,
//     ...asyncReducers
//   })
// }

/**
 * 按需加载时,立即注入对应的 Reducer
 * @param  {String}   key
 * @param  {Function} reducer
 */
// export function injectReducer(key, reducer) {
//   asyncReducers[key] = reducer
//   store.replaceReducer(createRootReducer()) // 替换当前的 rootReducer
// }


text:
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

import { ServerConnection } from '../serverconnection';
import { validateSpecModels } from './validate';

import { URLExt } from '@jupyterlab/coreutils';
import { PartialJSONObject } from '@lumino/coreutils';

/**
 * The url for the kernelspec service.
 */
const KERNELSPEC_SERVICE_URL = 'api/kernelspecs';

/**
 * Fetch all of the kernel specs.
 *
 * @param settings - The optional server settings.
 * @param useCache - Whether to use the cache. If false, always request.
 *
 * @returns A promise that resolves with the kernel specs.
 *
 * #### Notes
 * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernelspecs).
 */
export async function getSpecs(
  settings: ServerConnection.ISettings = ServerConnection.makeSettings()
): Promise<ISpecModels> {
  const url = URLExt.join(settings.baseUrl, KERNELSPEC_SERVICE_URL);
  const response = await ServerConnection.makeRequest(url, {}, settings);
  if (response.status !== 200) {
    const err = await ServerConnection.ResponseError.create(response);
    throw err;
  }
  const data = await response.json();
  return validateSpecModels(data);
}

/**
 * Kernel Spec interface.
 *
 * #### Notes
 * See [Kernel specs](https://jupyter-client.readthedocs.io/en/latest/kernels.html#kernelspecs).
 */
export interface ISpecModel extends PartialJSONObject {
  /**
   * The name of the kernel spec.
   */
  readonly name: string;

  /**
   * The name of the language of the kernel.
   */
  readonly language: string;

  /**
   * A list of command line arguments used to start the kernel.
   */
  readonly argv: string[];

  /**
   * The kernel's name as it should be displayed in the UI.
   */
  readonly display_name: string;

  /**
   * A dictionary of environment variables to set for the kernel.
   */
  readonly env?: PartialJSONObject;

  /**
   * A mapping of resource file name to download path.
   */
  readonly resources: { [key: string]: string };

  /**
   * A dictionary of additional attributes about this kernel; used by clients to aid in kernel selection.
   */
  readonly metadata?: PartialJSONObject;
}

/**
 * The available kernelSpec models.
 *
 * #### Notes
 * See the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernelspecs).
 */
export interface ISpecModels extends PartialJSONObject {
  /**
   * The name of the default kernel spec.
   */
  default: string;

  /**
   * A mapping of kernel spec name to spec.
   */
  readonly kernelspecs: { [key: string]: ISpecModel | undefined };
}


text:
ALTER TABLE structural_variation ADD COLUMN alias VARCHAR(255) DEFAULT NULL AFTER variation_name;
ALTER TABLE structural_variation ADD COLUMN clinical_significance_attrib_id int(10) unsigned DEFAULT NULL AFTER class_attrib_id;
ALTER TABLE structural_variation ADD KEY clinical_attrib_idx (clinical_significance_attrib_id);

ALTER TABLE structural_variation_feature ADD COLUMN length INT(10) DEFAULT NULL;
ALTER TABLE structural_variation_feature ADD COLUMN study_id INT(10) unsigned DEFAULT NULL AFTER source_id;

UPDATE structural_variation_feature svf, structural_variation sv SET svf.study_id=sv.study_id
WHERE svf.structural_variation_id=sv.structural_variation_id and sv.study_id is not NULL;

ALTER TABLE structural_variation_feature ADD KEY study_idx (study_id);

# patch identifier
INSERT INTO meta (species_id, meta_key, meta_value) VALUES (NULL, 'patch', 'patch_71_72_g.sql|Add new columns to the tables structural_variation and structural_variation_feature.');


text:
package main

import (
	"flag"
	"html/template"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"regexp"
)

var (
	addr  = flag.Bool("addr", false, "find open address and print to final-port.txt")
	debug = flag.Bool("debug", false, "Turn on debugging")
)

type Page struct {
	Title string
	Body  []byte
}

func (p *Page) save() error {
	filename := p.Title + ".txt"
	return ioutil.WriteFile(filename, p.Body, 0600)
}

func loadPage(title string) (*Page, error) {
	filename := title + ".txt"
	body, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	return &Page{Title: title, Body: body}, nil
}

func viewHandler(w http.ResponseWriter, r *http.Request, title string) {
	p, err := loadPage(title)
	if err != nil {
		http.Redirect(w, r, "/edit/"+title, http.StatusFound)
		return
	}
	renderTemplate(w, "view", p)
}

func editHandler(w http.ResponseWriter, r *http.Request, title string) {
	p, err := loadPage(title)
	if err != nil {
		p = &Page{Title: title}
	}
	renderTemplate(w, "edit", p)
}

func saveHandler(w http.ResponseWriter, r *http.Request, title string) {
	body := r.FormValue("body")
	p := &Page{Title: title, Body: []byte(body)}
	err := p.save()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	http.Redirect(w, r, "/view/"+title, http.StatusFound)
}

var templates = template.Must(template.ParseFiles("edit.html", "view.html"))

func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
	err := templates.ExecuteTemplate(w, tmpl+".html", p)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

var validPath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9]+)$")

func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		m := validPath.FindStringSubmatch(r.URL.Path)
		if m == nil {
			http.NotFound(w, r)
			return
		}
		fn(w, r, m[2])
	}
}

func main() {
	flag.Parse()
	http.HandleFunc("/view/", makeHandler(viewHandler))
	http.HandleFunc("/edit/", makeHandler(editHandler))
	http.HandleFunc("/save/", makeHandler(saveHandler))

	if *addr {
		l, err := net.Listen("tcp", "127.0.0.1:0")
		if err != nil {
			log.Fatal(err)
		}
		err = ioutil.WriteFile("final-port.txt", []byte(l.Addr().String()), 0644)
		if err != nil {
			log.Fatal(err)
		}
		s := &http.Server{}
		s.Serve(l)
		return
	}

	http.ListenAndServe(":8080", nil)
}


text:
module Jb
  class Railtie < ::Rails::Railtie
    initializer 'jb' do
      ActiveSupport.on_load :action_view do
        if Rails::VERSION::MAJOR >= 6
          require 'jb/action_view_monkeys'
        else
          require 'jb/action_view_legacy_monkeys'
        end
        require 'jb/handler'
        ::ActionView::Template.register_template_handler :jb, Jb::Handler
      end
    end

    if Rails::VERSION::MAJOR >= 5
      module ::ActionController
        module ApiRendering
          include ActionView::Rendering
        end
      end

      ActiveSupport.on_load :action_controller do
        if self == ActionController::API
          include ActionController::Helpers
          include ActionController::ImplicitRender
        end
      end
    end

    generators do |app|
      Rails::Generators.configure! app.config.generators
      Rails::Generators.hidden_namespaces.uniq!
      require_relative '../generators/rails/scaffold_controller_generator'
    end
  end
end


text:
package it.polimi.genomics.core.DataStructures.MetaGroupByCondition

import it.polimi.genomics.core.DataStructures.MetaJoinCondition.AttributeEvaluationStrategy

/**
 * specify the groupBy condition which is used by the COVER statement
 *
 * @param attributes is the list of attributes name to be used for the grouping.
 */
case class MetaGroupByCondition(attributes : List[AttributeEvaluationStrategy])


text:
package org.gradle.runtime.base.internal.registry;

import org.gradle.api.internal.plugins.PluginApplicationAction;
import org.gradle.internal.reflect.Instantiator;
import org.gradle.internal.service.ServiceRegistration;
import org.gradle.internal.service.scopes.PluginServiceRegistry;

public class ComponentModelBaseServiceRegistry implements PluginServiceRegistry {

    public void registerGlobalServices(ServiceRegistration registration) {
    }

    public void registerBuildServices(ServiceRegistration registration){
    }

    public void registerProjectServices(ServiceRegistration registration) {
            registration.addProvider(new ProjectScopeServices());
    }

    private static class ProjectScopeServices {
        PluginApplicationAction createComponentModelPluginInspector(Instantiator instantiator) {
            return new ComponentModelPluginApplicationAction(instantiator);
        }
    }
}


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

public class LevelGenerationManager : MonoBehaviour {

    /* This class should be used for level generation-related methods and calculations.
    */

	//One-time use variable, used for the first generation point.
    public Transform initialGenerationPoint;

    //Variables
    //PREFAB variable. RoadObject to generate.
    public GameObject roadObject;

	//How many road objects should be generated ahead and behind the camera, respectively.
    public int generateAheadInstances;
    public int generateBehindInstances;

    //An array for storing past destroyed road objects, keeping them as transforms - WIP.
    public Transform parentDestroyedSector;

    //Class references
    //RoadGenerationController Reference, intended for creating individual sectors.
    public RoadGenerationManager roadGenerationManager;
    public CarController carController;
    public CarManagement carManagement;

    //A transform array for destroyed objects. Before destroying, a reminant transform is left for future reference.
    public List<Transform> transformSectorArray;

    public int roadObjectSignature = 1;

    //This method should be called whenever the player moves into a new sector, run begins, etc.
    //Generates ALL required sectors for playing.
    public void ManageRequiredSectors(GameObject player, Transform baseSectorParent)
	{
		//Generating ahead & behind sectors

		//Finding the index of the players road object. WIP
		int playerRoadIndex = roadGenerationManager.roadObjectSectorArray.IndexOf (player.GetComponent<CarController> ().currentRoadObject);
		//The total amount of times generation is required.
		int toGenerateAmount = generateBehindInstances + generateAheadInstances;
		//The roadObjectSector array index to begin generating from.
		int indexGenerateFrom = playerRoadIndex - generateBehindInstances;
		//The roadObjectSector array index to cease generating from.
		int indexGenerateTo = playerRoadIndex + generateAheadInstances;
        //An array for inserting road objects generated this instance of the method.
        List<GameObject> roadObjectArray = new List<GameObject>();

        //Does not generate objects (run for loop) if index is negative.
        for (int i = Mathf.Max(indexGenerateFrom, 1); i < indexGenerateTo; i++)
        {
            //This function ensures that the index MUST be either 0 or a positive index.
            int a = Mathf.Max(0, i);
            //This sets positiveCondition to true of a is NOT equal to zero.
            bool positiveCondition = !(a == 0);
			Debug.Log (a - 1);

            //Instantiates the road object itself. Also checks that the index of the array is not zero since that would throw an error, AND checks that the referenced gameobject is not null.
            if (roadGenerationManager.roadObjectSectorArray[a - 1] != null)
            {
                //Creates a reference to the RoadBaseController, which is the previously instantiated road object.
                RoadBaseController roadObjectController = roadGenerationManager.roadObjectSectorArray[a - 1].GetComponent<RoadBaseController>();
                GameObject instantiatedRoadObject = roadGenerationManager.GenerateNewRoadSector(positiveCondition ? roadObjectController.LocalGenerationPoint.transform : initialGenerationPoint.transform, baseSectorParent);
                roadObjectArray.Add(instantiatedRoadObject);
            }
            //Adds the road object to the instantiated array for future destroying.

        }

        //For every total generated roadObject in the roadObjectSectorArray, this loop will see if the roadObject has generated in this instance of this method.
		//If not (it was generated sometime else and thus is no longer needed), the roadObject is destroyed.
        foreach (GameObject roadObject in roadGenerationManager.roadObjectSectorArray)
        {
			if(!roadObjectArray.Contains(roadObject)) {
                //GameObject destroyedTransform = (GameObject) Instantiate(new GameObject(), roadObject.GetComponent<RoadBaseController>().LocalGenerationPoint.position, Quaternion.Euler(0, 0, 0));
               // destroyedTransform.transform.SetParent(parentDestroyedSector);
                //transformSectorArray.Add(destroyedTransform.transform);
                Destroy (roadObject);
			}
        }

        //This ensures that the array is OK for next method use, and not full of roads that we have already used.
        roadObjectArray.Clear();
    }

    //2 methods for finding the next generation & append points of the parameter roadObject.

    public Transform getNextGenerationPoint(GameObject roadObject)
    {
        return roadObject.transform.FindChild("GenerationPoint");
    }

    public Transform getNextAppendPoint(GameObject roadObject)
    {
        return roadObject.transform.FindChild("AppendPoint");
    }

    //Gets the roadObject that the car is currently in.
    public GameObject getRoadObjectByCar(GameObject car) {
        return car.GetComponent<CarController>().currentRoadObject;
    }

}