text:
USING_NS_CC;
Scene* GameOverScene::createScene(cocos2d::CCDictionary *dic)
{
	auto scene = Scene::create();
	auto layer = GameOverScene::create();
    layer->initWithColor(Color4B::WHITE);
	layer->initDict(dic);
	scene->addChild(layer);
	return scene;
}

GameOverScene::~GameOverScene(){
    ThirdPartyHelper::setAd(SET_AD_HID);
}

static float godelay = 0;

static void show(Node *node){
    node->setScale(0.01);
    DelayTime *d = DelayTime::create(godelay);
    ScaleTo *b = ScaleTo::create(0.1, 1.2);
    ScaleTo *s = ScaleTo::create(0.03, 1);
    Sequence *ac = Sequence::create(d,b,s, NULL);
    node->runAction(ac);
    godelay += 0.05f;
}

bool GameOverScene::initDict(cocos2d::CCDictionary *dic)
{
    ThirdPartyHelper::setAd(SET_AD_SHOW);
    godelay = 0;

    Size vs = Director::getInstance()->getVisibleSize();
    Vec2 vo = Director::getInstance()->getVisibleOrigin();

    int step = ((CCInteger*)dic->objectForKey("step"))->getValue();
    int level = ((CCInteger*)dic->objectForKey("level"))->getValue();

    UserDefault::getInstance()->setBoolForKey(StringUtils::format("level%d_lock",level+1).c_str(), false);
    UserDefault::getInstance()->flush();

    auto gameover = ui::Text::create(StringUtils::format("Level %d Pass!",level+1), Common_Font, 70);
    gameover->setPosition(Vec2(vs.width/2, vs.height/3*2 + vo.y));
    gameover->setColor(Color3B::BLACK);
    this->addChild(gameover);
    show(gameover);

    int best = UserDefault::getInstance()->getIntegerForKey(StringUtils::format("level%d_step",level).c_str(), INT16_MAX);
    if (step<best) {
        best = step;
        UserDefault::getInstance()->setIntegerForKey(StringUtils::format("level%d_step",level).c_str(), best);
    }

    auto scorelabel = ui::Text::create(StringUtils::format("Step:%d",step), Common_Font, 50);
    scorelabel->setPosition(Vec2(vs.width/2, vs.height/2+scorelabel->getContentSize().height/2 + vo.y));
    scorelabel->setColor(Color3B::BLACK);
    this->addChild(scorelabel);
    show(scorelabel);

    auto bestlabel = ui::Text::create(StringUtils::format("Best:%d",best), Common_Font, 50);
    bestlabel->setPosition(Vec2(vs.width/2, vs.height/2-bestlabel->getContentSize().height/2 + vo.y));
    bestlabel->setColor(Color3B::BLACK);
    this->addChild(bestlabel);
    show(bestlabel);

    float by = vs.height/6 + vo.y;
    float fs = 40;

    if (level >= LVCOUNT-1) {

    }else{
        auto replay = ui::Button::create("rb.png");
        replay->setTitleText("Next");
        replay->setTitleFontSize(fs);
        replay->setPosition(Vec2(vs.width/2, vs.height/3 + vo.y));
        replay->addTouchEventListener([level](Ref *ps,ui::Widget::TouchEventType type){
            if (type == ui::Widget::TouchEventType::ENDED) {
                Dictionary *dict = Dictionary::create();
                dict->setObject(CCInteger::create(level+1),"level");
                Director::getInstance()->replaceScene(PlayScene::createScene(dict));
            }
        });
        this->addChild(replay);
        show(replay);
    }

    auto back = ui::Button::create("rr.png");
    back->setPosition(Vec2(vs.width/3, by));
    back->setTitleFontSize(fs);
    back->setTitleText("Back");
    back->addTouchEventListener([](Ref *ps,ui::Widget::TouchEventType type){
        if (type == ui::Widget::TouchEventType::ENDED) {
            Director::getInstance()->replaceScene(HelloWorld::createScene());
        }
    });
    this->addChild(back);
    show(back);

    auto share = LHShareButton::defaultButton("rr.png","Lucky Puzzle!");
    share->setTitleFontSize(fs);
    share->setTitleText("Share");
    share->setPosition(Vec2(vs.width/3*2, by));
    this->addChild(share);
    show(share);

	return true;
}


text:
'use strict';

(function () {

    var services = angular.module('myApp.messageBrokerService',[]);

      services.factory('messageBrokerService', ['$rootScope', '$q', function ($rootScope, $q) {
          /*        var HeartBeat = new Worker("js/CustomTimer.js");
           HeartBeat.postMessage({MessageType:'RegisterTimer'});           */

          var SubscribDetail = (function () { return { SubcribObj: null, SubcribCallback: null } });

          var SubLst = angular.GetNewDictionaryInstance();
          var PendingSubLst = angular.GetNewDictionaryInstance();

          var MessageBroker = {
              Server: angular.getAppSection('StompConfiguration').Server,
              Port: angular.getAppSection('StompConfiguration').Port,
              Protocol: angular.getAppSection('StompConfiguration').Protocol,
              UserName: angular.getAppSection('StompConfiguration').UserName,
              Password: angular.getAppSection('StompConfiguration').Password,
              Client: null,
              Debug: null,
              ConnectionState: 'Offline',
              onError: function (frame) {
                  if (MessageBroker.Debug != null) {
                      MessageBroker.Debug("Connection Error: " + (frame.headers != undefined ? frame.headers.message : frame));
                  }
                  if (frame.toString().indexOf('Lost connection to') != -1)
                  {
                      MessageBroker.ConnectionState = 'Offline';
                      MessageBroker.Client = null;
                      while (SubLst.Count() > 0) {
                          var Requst = SubLst.ReturnFirstObject();
                          PendingSubLst.Add(Requst, SubLst.getValue(Requst).SubcribCallback);
                          SubLst.Remove(Requst);
                      }
                      if (PendingSubLst.Count() > 0)
                      {
                          MessageBroker.GetClientInstance();
                      }
                  }
              },
              GetClientInstance: function () {

                  if (Stomp == null) {
                      alert('Stomp object is not available. Please check the reference to Stomp.Js');
                      return null;
                  }

                  if (MessageBroker.Client == null) {
                      MessageBroker.Client = Stomp.client(MessageBroker.Protocol + '://' + MessageBroker.Server + ':' + MessageBroker.Port);
                      if (MessageBroker.Debug != null) {
                          MessageBroker.Client.debug = MessageBroker.Debug;
                      }
                  }

                  if (MessageBroker.Client.connected == false) {
                      if (MessageBroker.ConnectionState != 'Connecting') {
                          MessageBroker.ConnectionState = 'Connecting';
                          // alert('Register Success');
                          MessageBroker.Client.connect(MessageBroker.UserName, MessageBroker.Password, MessageBroker.RegisterPendingSubscribtion, MessageBroker.onError);
                      };
                  }

              },
              GetSubcribDetail: function (callBackReference, SubcribReference) {
                  var SubDetail = new SubscribDetail();
                  SubDetail.SubcribCallback = callBackReference;
                  SubDetail.SubcribObj = SubcribReference;
                  return SubDetail;
              },
              RegisterPendingSubscribtion: function (frame) {

                  MessageBroker.ConnectionState = 'Online';
                  while (PendingSubLst.Count() > 0) {
                      var Requst = PendingSubLst.ReturnFirstObject();
                      var Callback = PendingSubLst.getValue(Requst);
                      SubLst.Add(Requst, MessageBroker.GetSubcribDetail(Callback, MessageBroker.Client.subscribe(Requst, Callback)));
                      PendingSubLst.Remove(Requst);
                  }
              },
              Publish: function (topicName, message) {
                  if (MessageBroker.ConnectionState == 'Online') {
                      MessageBroker.Client.send(topicName, {}, message);
                  } else {
                      throw {
                          name: "Stomp Error",
                          level: "",
                          message: "Connection not established yet!. please try after sometime. Check the connection status property.",
                          htmlMessage: "
Connection not established yet!. please try after sometime. Check the connection status property.
",
                          toString: function () { return this.name + ": " + this.message }
                      };
                  }
              },
              Subscribe: function (topicName, callbackFunction) {
                  if (MessageBroker.ConnectionState != 'Online') {
                      MessageBroker.GetClientInstance();
                      PendingSubLst.Add(topicName, callbackFunction);
                  }
                  else {
                      SubLst.Add(topicName, MessageBroker.GetSubcribDetail(callbackFunction, MessageBroker.Client.subscribe(topicName, callbackFunction)));
                  }
              },
              UnSubscribe: function (topicName, callBackFunction) {
                  var subid = SubLst.getValue(topicName).SubcribObj;
                  MessageBroker.Client.unsubscribe(subid);
                  SubLst.Remove(topicName);
                  if (SubLst.Count() < 1) {
                      if (MessageBroker.Client.connected == true) {
                          MessageBroker.Client.disconnect(callBackFunction);
                          MessageBroker.Client = null;
                          MessageBroker.ConnectionState = 'Offline';
                      }
                  }
              }
          };

          MessageBroker.Debug = function (str) {
              var elem = document.getElementById('DebugWindow');
              elem.innerHTML += ("
" + str + "

");
              elem.scrollTop = elem.scrollHeight;
          };

          return MessageBroker;

      }]);
})();

redpajama_set_name: RedPajamaGithub


text:
namespace ClassLibraryToReference
{
    public static class Class1
    {
        public static string GetTest()
        {
            return "Hi from embedded assembly";
        }
    }
}


text:
import 'material-design-lite';
import PropTypes from 'prop-types';
import React from 'react';
import ActivityListItem from './ActivityListItem';

/* global componentHandler */

class ActivityList extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const {activities, imageHost, imageWidth} = this.props;
    const items = activities.map((activity, index) => {
      return (
        <ActivityListItem
          activity={activity}
          key={index}
          componentHandler={componentHandler}
          imageHost={imageHost}
          imageWidth={imageWidth}
        />
      );
    });

    return (
      <ul className='mdl-list'>
        {items}
      </ul>
    );
  }
}

ActivityList.propTypes = {
  activities: PropTypes.array,
  imageHost: PropTypes.string,
  imageWidth: PropTypes.object
};

export default ActivityList;


text:
import JSONSerializer from "ember-data/serializers/json";

const { hasOwnProperty } = {};

export default JSONSerializer.extend({
	/**
	 * @param {Snapshot} snapshot
	 * @param {Model} snapshot.record
	 * @returns {Object}
	 */
	serialize({ record }) {
		const json = this._super( ...arguments );
		const { models, modelBaseName, typeKey } = this;

		for ( const [ type, model ] of models ) {
			if ( record instanceof model ) {
				json[ typeKey ] = `${modelBaseName}-${type}`;
				break;
			}
		}

		return json;
	},

	/**
	 * Fix removal of the `typeKey` property
	 * @param {Model} modelClass
	 * @param {Object} [data]
	 * @returns {Object}
	 */
	extractAttributes( modelClass, data ) {
		const { typeKey } = this;
		const attributes = this._super( ...arguments );
		if ( data && hasOwnProperty.call( data, typeKey ) ) {
			attributes[ typeKey ] = data[ typeKey ];
		}

		return attributes;
	}
});


text:
package fr.laas.fape.anml.model

import fr.laas.fape.anml.model.concrete.{InstanceRef, TemporalInterval}
import fr.laas.fape.anml.model.ir.{IRSimpleVar, IRVar}

/** A context where all references are fully defined (i.e. every local reference has a corresponding global reference).
  *
  * {{{
  *   // Definition of the action
  *   action Move(Location a, Location b) {
  *     ...
  *   };
  *
  *   // Reference of the action, where LA is an instance of type Location
  *   Move(LA, any_)
  * }}}
  *
  * The previous example would give an [[Action]] with the following Context:
  *
  *  - parentContext: `Some(anmlProblem)`
  *
  *  - variables : `{ a -> (Location, LA, b -> (Location, any_ }`
  *
  *  - actions: {}
  *
  *  - varsToCreate: `{(Location, any_)}`
  *
  * @param parentContext An optional parent context. If given it has to be a [[Context]] (ie fully defined).
  */
class Context(
    pb:AnmlProblem,
    val label: String,
    val parentContext:Option[Context],
    val interval: TemporalInterval)
  extends AbstractContext(pb) {

    override def addUndefinedVar(v: IRSimpleVar): Unit = {
      assert(!variables.contains(v), "Local variable already defined: "+v)
      assert(!nameToLocalVar.contains(v.name), "Local variable already recorded: "+v)
      nameToLocalVar. += ((v.name, v))
    }

    def bindVarToConstant(name:LVarRef, const:InstanceRef): Unit = {
      assert(variables.contains(name))
      val previousGlobal = variables(name)
      variables.put(name, const)
    }
  }


text:
module ResourcePoolHelper
  include_concern 'TextualSummary'

  def calculate_rp_config(db_record)
    rp_config = []
    unless db_record.memory_reserve.nil?
      rp_config.push(:field       => _("Memory Reserve"),
                     :description => db_record.memory_reserve)
    end
    unless db_record.memory_reserve_expand.nil?
      rp_config.push(:field       => _("Memory Reserve Expand"),
                     :description => db_record.memory_reserve_expand)
    end
    unless db_record.memory_limit.nil?
      mem_limit = db_record.memory_limit
      mem_limit = "Unlimited" if db_record.memory_limit == -1
      rp_config.push(:field       => _("Memory Limit"),
                     :description => mem_limit)
    end
    unless db_record.memory_shares.nil?
      rp_config.push(:field       => _("Memory Shares"),
                     :description => db_record.memory_shares)
    end
    unless db_record.memory_shares_level.nil?
      rp_config.push(:field       => _("Memory Shares Level"),
                     :description => db_record.memory_shares_level)
    end
    unless db_record.cpu_reserve.nil?
      rp_config.push(:field       => _("CPU Reserve"),
                     :description => db_record.cpu_reserve)
    end
    unless db_record.cpu_reserve_expand.nil?
      rp_config.push(:field       => _("CPU Reserve Expand"),
                     :description => db_record.cpu_reserve_expand)
    end
    unless db_record.cpu_limit.nil?
      cpu_limit = db_record.cpu_limit
      cpu_limit = "Unlimited" if db_record.cpu_limit == -1
      rp_config.push(:field       => _("CPU Limit"),
                     :description => cpu_limit)
    end
    unless db_record.cpu_shares.nil?
      rp_config.push(:field       => _("CPU Shares"),
                     :description => db_record.cpu_shares)
    end
    unless db_record.cpu_shares_level.nil?
      rp_config.push(:field       => _("CPU Shares Level"),
                     :description => db_record.cpu_shares_level)
    end

    rp_config
  end
end


text:
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Runtime.Serialization;

namespace CakeMail.RestClient.Models
{
	/// <summary>
	/// Enumeration to indicate transfer encoding.
	/// </summary>
	[JsonConverter(typeof(StringEnumConverter))]
	public enum TransferEncoding
	{
		/// <summary>
		/// Quoted-printable
		/// </summary>
		[EnumMember(Value = "quoted-printable")]
		QuotedPrintable,

		/// <summary>
		/// Base64
		/// </summary>
		[EnumMember(Value = "base64")]
		Base64
	}
}


text:
package com.myandroid.myapp;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class ZhuyiliceshibiaoIndexActivity extends ActionBarActivity{

	private Button ksBtn;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_zhuyiliceshi_index);

		ksBtn = (Button) this.findViewById(R.id.ksbtn);

		ksBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				Intent intent = new Intent(ZhuyiliceshibiaoIndexActivity.this,
						ZhuyiliceshibiaoItemActivity.class);
				// Æô¶¯Activity
				startActivity(intent);
			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		// getMenuInflater().inflate(R.menu.kbcx, menu);
		return true;
	}

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


text:
import os
import shutil
from pathlib import Path
from shutil import copyfile

from rasa.core.constants import (
    CONFUSION_MATRIX_STORIES_FILE,
    STORIES_WITH_WARNINGS_FILE,
)
from rasa.constants import RESULTS_FILE
from rasa.shared.constants import DEFAULT_RESULTS_PATH
from rasa.shared.utils.io import list_files, write_yaml, write_text_file
from typing import Callable
from _pytest.pytester import RunResult, Testdir, Pytester, ExitCode

def test_test_core(run_in_simple_project: Callable[..., RunResult]):
    run_in_simple_project("test", "core", "--stories", "data")

    assert os.path.exists("results")

def test_test_core_no_plot(run_in_simple_project: Callable[..., RunResult]):
    run_in_simple_project("test", "core", "--no-plot")

    assert not os.path.exists(f"results/{CONFUSION_MATRIX_STORIES_FILE}")

def test_test_core_warnings(run_in_simple_project_with_model: Callable[..., RunResult]):
    write_yaml(
        {
            "language": "en",
            "pipeline": [],
            "policies": [
                {"name": "MemoizationPolicy", "max_history": 3},
                {"name": "UnexpecTEDIntentPolicy", "max_history": 5, "epochs": 1},
                {
                    "name": "TEDPolicy",
                    "max_history": 5,
                    "epochs": 1,
                    "constrain_similarities": True,
                },
                {"name": "RulePolicy"},
            ],
        },
        "config.yml",
    )

    simple_test_story_yaml = """
version: "3.0"
stories:
- story: unlikely path
  steps:
  - user: |
      very terrible
    intent: mood_unhappy
  - action: utter_cheer_up
  - action: utter_did_that_help
  - intent: affirm
  - action: utter_happy
"""
    with open("tests/test_stories.yaml", "w") as f:
        f.write(simple_test_story_yaml)

    run_in_simple_project_with_model("test", "core", "--no-warnings")
    assert not os.path.exists(f"results/{STORIES_WITH_WARNINGS_FILE}")

    run_in_simple_project_with_model("test", "core")
    assert os.path.exists(f"results/{STORIES_WITH_WARNINGS_FILE}")

def test_test_core_with_no_model(run_in_simple_project: Callable[..., RunResult]):
    assert not os.path.exists("models")

    output = run_in_simple_project("test", "core")

    assert (
        "No model provided. Please make sure to specify the model to test with"
        in output.outlines[7]
    )

def test_test(run_in_simple_project_with_model: Callable[..., RunResult]):
    write_yaml(
        {
            "pipeline": "KeywordIntentClassifier",
            "policies": [{"name": "MemoizationPolicy"}],
        },
        "config2.yml",
    )

    run_in_simple_project_with_model("test")

    assert os.path.exists("results")
    assert os.path.exists("results/intent_histogram.png")
    assert os.path.exists("results/intent_confusion_matrix.png")

def test_test_with_no_user_utterance(
    run_in_simple_project_with_model: Callable[..., RunResult]
):
    write_yaml(
        {"pipeline": "KeywordIntentClassifier", "policies": [{"name": "TEDPolicy"}],},
        "config.yml",
    )

    simple_test_story_yaml = """
stories:
- story: happy path 1
  steps:
  - intent: greet
  - action: utter_greet
  - intent: mood_great
  - action: utter_happy
"""
    with open("tests/test_story_no_utterance.yaml", "w") as f:
        f.write(simple_test_story_yaml)

    run_in_simple_project_with_model("test", "--fail-on-prediction-errors")
    assert os.path.exists("results")
    assert not os.path.exists("results/failed_test_stories.yml")

def test_test_no_plot(run_in_simple_project: Callable[..., RunResult]):
    run_in_simple_project("test", "--no-plot")

    assert not os.path.exists("results/intent_histogram.png")
    assert not os.path.exists("results/intent_confusion_matrix.png")
    assert not os.path.exists("results/story_confmat.pdf")

def test_test_nlu(run_in_simple_project_with_model: Callable[..., RunResult]):
    run_in_simple_project_with_model("test", "nlu", "--nlu", "data", "--successes")

    assert os.path.exists("results/intent_histogram.png")
    assert os.path.exists("results/intent_confusion_matrix.png")
    assert os.path.exists("results/intent_successes.json")

def test_test_nlu_no_plot(run_in_simple_project: Callable[..., RunResult]):
    run_in_simple_project("test", "nlu", "--no-plot")

    assert not os.path.exists("results/intent_histogram.png")
    assert not os.path.exists("results/intent_confusion_matrix.png")

def test_test_nlu_cross_validation(run_in_simple_project: Callable[..., RunResult]):
    run_in_simple_project(
        "test", "nlu", "--cross-validation", "-c", "config.yml", "-f", "2", "-r", "1"
    )

    assert os.path.exists("results/intent_histogram.png")
    assert os.path.exists("results/intent_confusion_matrix.png")

def test_test_nlu_cross_validation_with_autoconfig(
    testdir: Testdir, moodbot_nlu_data_path: Path
):
    os.environ["LOG_LEVEL"] = "ERROR"
    config_path = str(testdir.tmpdir / "config.yml")
    nlu_path = str(testdir.tmpdir / "nlu.yml")
    shutil.copy(str(moodbot_nlu_data_path), nlu_path)
    write_yaml(
        {"language": "en", "pipeline": None, "policies": None,}, config_path,
    )
    args = [
        shutil.which("rasa"),
        "test",
        "nlu",
        "--cross-validation",
        "-c",
        "config.yml",
        "--nlu",
        "nlu.yml",
    ]

    # we don't wanna run the cross validation for real, just want to see that it does
    # not crash
    try:
        run_result = testdir.run(*args, timeout=8.0)
        # we'll only get here if the run fails due to an exception
        assert run_result.ret != ExitCode.TESTS_FAILED
    except Pytester.TimeoutExpired:
        pass

def test_test_nlu_comparison(run_in_simple_project: Callable[..., RunResult]):
    write_yaml({"pipeline": "KeywordIntentClassifier"}, "config.yml")
    write_yaml({"pipeline": "KeywordIntentClassifier"}, "config2.yml")

    # TODO: Loading still needs fixing
    run_in_simple_project(
        "test",
        "nlu",
        "--config",
        "config.yml",
        "config2.yml",
        "--run",
        "2",
        "--percentages",
        "75",
        "25",
    )

    assert os.path.exists("results/run_1")
    assert os.path.exists("results/run_2")

def test_test_core_comparison(
    run_in_simple_project_with_model: Callable[..., RunResult]
):
    files = list_files("models")
    copyfile(files[0], "models/copy-model.tar.gz")

    run_in_simple_project_with_model(
        "test",
        "core",
        "-m",
        files[0],
        "models/copy-model.tar.gz",
        "--stories",
        "data/stories.yml",
    )

    assert os.path.exists(os.path.join(DEFAULT_RESULTS_PATH, RESULTS_FILE))

def test_test_core_comparison_after_train(
    run_in_simple_project: Callable[..., RunResult],
    trained_rasa_model: str,
    tmp_path: Path,
):
    path = Path(tmp_path / "comparison_models")
    path.mkdir()

    run_one = Path(path / "run_1")
    run_one.mkdir()
    shutil.copy(trained_rasa_model, run_one)

    run_two = Path(path / "run_2")
    run_two.mkdir()
    shutil.copy(trained_rasa_model, run_two)

    write_text_file("[1]", path / "num_stories.json")

    run_in_simple_project(
        "test",
        "core",
        "-m",
        str(path),
        "--stories",
        "data/stories",
        "--evaluate-model-directory",
    )

    assert os.path.exists(os.path.join(DEFAULT_RESULTS_PATH, RESULTS_FILE))
    assert os.path.exists(
        os.path.join(DEFAULT_RESULTS_PATH, "core_model_comparison_graph.pdf")
    )

def test_test_help(run: Callable[..., RunResult]):
    output = run("test", "--help")

    help_text = """usage: rasa test [-h] [-v] [-vv] [--quiet] [-m MODEL] [-s STORIES]
                 [--max-stories MAX_STORIES] [--endpoints ENDPOINTS]
                 [--fail-on-prediction-errors] [--url URL]
                 [--evaluate-model-directory] [-u NLU]
                 [-c CONFIG [CONFIG ...]] [--cross-validation] [-f FOLDS]
                 [-r RUNS] [-p PERCENTAGES [PERCENTAGES ...]] [--no-plot]
                 [--successes] [--no-errors] [--no-warnings] [--out OUT]
                 {core,nlu} ..."""

    lines = help_text.split("\n")
    # expected help text lines should appear somewhere in the output
    printed_help = set(output.outlines)
    for line in lines:
        assert line in printed_help

def test_test_nlu_help(run: Callable[..., RunResult]):
    output = run("test", "nlu", "--help")

    help_text = """usage: rasa test nlu [-h] [-v] [-vv] [--quiet] [-m MODEL] [-u NLU] [--out OUT]
                     [-c CONFIG [CONFIG ...]] [--cross-validation] [-f FOLDS]
                     [-r RUNS] [-p PERCENTAGES [PERCENTAGES ...]] [--no-plot]
                     [--successes] [--no-errors] [--no-warnings]"""

    lines = help_text.split("\n")
    # expected help text lines should appear somewhere in the output
    printed_help = set(output.outlines)
    for line in lines:
        assert line in printed_help

def test_test_core_help(run: Callable[..., RunResult]):
    output = run("test", "core", "--help")

    help_text = """usage: rasa test core [-h] [-v] [-vv] [--quiet] [-m MODEL [MODEL ...]]
                      [-s STORIES] [--max-stories MAX_STORIES] [--out OUT]
                      [--e2e] [--endpoints ENDPOINTS]
                      [--fail-on-prediction-errors] [--url URL]
                      [--evaluate-model-directory] [--no-plot] [--successes]
                      [--no-errors] [--no-warnings]"""

    lines = help_text.split("\n")
    # expected help text lines should appear somewhere in the output
    printed_help = set(output.outlines)
    for line in lines:
        assert line in printed_help


text:
using namespace std;

int main(int argc, char *argv[])
{
   int returnCode = 0;

   ossimArgumentParser ap(&argc, argv);
   ossimInit::instance()->addOptions(ap);
   ossimInit::instance()->initialize(ap);

   if (argc < 3)
   {
      cout<<"\nUsage: "<<argv[0]<<"<image-A> <image-B>\n"<<endl;
      exit(0);
   }

   try
   {
      ossimFilename imageA (argv[1]);
      ossimFilename imageB (argv[2]);

      Json::Value rootJson;
      rootJson["algorithm"] = "omg";
      rootJson["method"] = "generate";
      rootJson["filename"] = "dem-test-output.tif";
      rootJson["postSpacing"] = 1.0;
      rootJson["postSpacingUnits"] = "meters";

      Json::Value imagesJson;
      Json::Value imageAJson;
      imageAJson["filename"] = imageA.string();
      imagesJson[0] = imageAJson;
      Json::Value imageBJson;
      imageBJson["filename"] = imageB.string();
      imagesJson[1] = imageBJson;

      Json::Value pbJson;
      pbJson["images"] = imagesJson;
      rootJson["photoblock"] = pbJson;

      cout<<"Input JSON:\n"<<rootJson<<endl;

      ossimDemTool demTool;
      demTool.loadJSON(rootJson);

      demTool.execute();
   }
   catch(const ossimException& e)
   {
      ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl;
      returnCode = 1;
   }
   catch( ... )
   {
      ossimNotify(ossimNotifyLevel_WARN)
         << argv[0] <<" caught unhandled exception!" << std::endl;
      returnCode = 1;
   }

   return returnCode;
}


text:
require 'active_support/all'

require "active_datastore/version"
require "active_datastore/client"
require "active_datastore/dataset"

module ActiveDatastore
  # Your code goes here...
end


text:
module Zappa
  class WaveData
    attr_reader :samples, :chunk_id, :chunk_size

    def initialize
      @chunk_id = 'data'
      @chunk_size = 0
      @samples = []
    end

    def set_samples(samples)
      @samples = samples
      frame_size = samples[1].size
      @chunk_size = @samples.size * frame_size * 2
    end

    def ==(other)
      other.chunk_size == @chunk_size && other.chunk_id == @chunk_id
    end
  end
end


text:
package lib.driver.lims.driver_class;

import lib.SessionFactoryUtil;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import java.util.Collection;
import java.util.List;

import core.classes.lims.Category;
import core.classes.lims.ParentTestFields;
import core.classes.lims.SpecimenRetentionType;
import core.classes.lims.SpecimenType;
import core.classes.lims.SubCategory;
import core.classes.lims.SubTestFields;
import core.classes.lims.TestFieldsRange;
import core.classes.lims.TestNames;
import core.classes.opd.OutPatient;

public class SubTestFieldsDBDriver {

	Session session = SessionFactoryUtil.getSessionFactory().openSession();

	public boolean addNewSubTestField(SubTestFields subtestfields) {

		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.save(subtestfields);

			tx.commit();
			return true;
		} catch (RuntimeException ex) {
			if (tx != null && tx.isActive()) {
				try {
					tx.rollback();
				} catch (HibernateException he) {
					System.err.println("Error rolling back transaction");
				}
				throw ex;
			}
			return false;
		}

	}

	/**
	 * This method retrieve a list of laboratory tests currently available in the system
	 *
	 * @return lab test list List<TestNames>
	 * @throws Method
	 *             throws a {@link RuntimeException} in failing the return,
	 *             throws a {@link HibernateException} on error rolling back
	 *             transaction.
	 */
	public List<SubTestFields> getSubTestFieldsList() {
		Transaction tx = null;
		try {
			//catID = 2;
			tx = session.beginTransaction();
			Query query = session.createQuery("select s from SubTestFields s" );
			//query.setParameter("catID", catID);
			List<SubTestFields> subTestFieldsList = query.list();
			tx.commit();
			return subTestFieldsList;
		} catch (RuntimeException ex) {
			if (tx != null && tx.isActive()) {
				try {
					tx.rollback();
				} catch (HibernateException he) {
					System.err.println("Error rolling back transaction");
				}
				throw ex;
			}
			return null;
		}
	}

	public SubTestFields getSubTestFieldByID(int id) {
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Query query = session.createQuery("select s from SubTestFields s where s.sub_TestFieldID="+id);
			List<SubTestFields> subfieldList = query.list();
			if (subfieldList.size() == 0)
				return null;
			tx.commit();
			return (SubTestFields)subfieldList.get(0);
		} catch (RuntimeException ex) {
			if (tx != null && tx.isActive()) {
				try {
					tx.rollback();
				} catch (HibernateException he) {
					System.err.println("Error rolling back transaction");
				}
				throw ex;
			}
			return null;
		}
	}

	public String getsubtestfieldID() {
		Transaction tx = null;
		try {

			tx = session.beginTransaction();
			Query query1 = session.createQuery("select max(sub_TestFieldID) from SubTestFields" );
			//query1.setParameter("testID", testObj);
			List list = query1.list();
			tx.commit();
			return list.get(0).toString();
		} catch (RuntimeException ex) {
			if (tx != null && tx.isActive()) {
				try {
					tx.rollback();
				} catch (HibernateException he) {
					System.err.println("Error rolling back transaction");
				}
				throw ex;
			}
			return "0";
		}
	}

	public SubTestFields addNewSubTestField(SubTestFields subtestfields, String idd) {
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			int id = Integer.parseInt(idd);
			ParentTestFields p = (ParentTestFields)session.get(ParentTestFields.class,id);
			subtestfields.setfPar_Test_FieldID(p);
			session.save(subtestfields);

			tx.commit();
			return subtestfields;
		} catch (RuntimeException ex) {
			if (tx != null && tx.isActive()) {
				try {
					System.out.println(ex.getMessage());
					tx.rollback();
				} catch (HibernateException he) {
					System.out.println(ex.getMessage());
				}
				throw ex;
			}
			return null;
		}

	}

	public List<SubTestFields> getSubTestFieldsList(int id) {

			Transaction tx = null;
			try {
				tx = session.beginTransaction();
				Query query = session.createQuery("select s from SubTestFields s where s.fPar_Test_FieldID="+id);
				List<SubTestFields> subfieldList = query.list();
				if (subfieldList.size() == 0)
					return null;
				tx.commit();
				return subfieldList;
			} catch (RuntimeException ex) {
				if (tx != null && tx.isActive()) {
					try {
						tx.rollback();
					} catch (HibernateException he) {
						System.out.print(he.getMessage());
						System.err.println("Error rolling back transaction");
					}
					throw ex;
				}
				return null;

		}
	}

}


text:
"use strict";
gereji.extend('os', {
	sandbox: {},
	apps: {},
	register : function(appId, creator) {
		this.apps[appId] = {
			creator : creator,
			instance : null
		};
	},
	start : function(appId) {
		var app = this.apps[appId];
		app.instance = app.creator(this.sandbox);
		try {
			app.instance.init();
		} catch (e) {
			console && console.error(e.stack);
		}
	},
	stop : function(appId) {
		var data = this.apps[appId];
		if(!data.instance)
			return;
		data.instance.kill();
		data.instance = null;
	},
	boot : function() {
		this.sandbox = new gereji.broker();
		this.sandbox.init();
		this.sandbox.models = {};
		this.sandbox.collections = {};
		this.sandbox.validator = new gereji.validator();
		this.sandbox.transition = new gereji.transition();
		this.sandbox.storage = new gereji.storage();
		this.sandbox.sync = new gereji.sync();
		this.sandbox.storage.init();
		this.sandbox.sync.init();
		for (var i in this.apps) {
			this.apps.hasOwnProperty(i) && this.start(i);
		}
		this.sandbox.emit({type: "body:load", data: {}});
	},
	halt : function() {
		for ( var i in this.apps) {
			this.apps.hasOwnProperty(i) && this.stop(i);
		}
	}
});
gereji.apps = new gereji.os();


text:
<?php

namespace backend\assets;

use yii\web\AssetBundle;

class FlightsAsset extends AssetBundle
{
    public $sourcePath = '@backend/assets';

    public $css = [
        'css/flights.css',
    ];

    public $js = [
        'js/flights.js',
    ];

    public $depends = [
        'yii\jui\JuiAsset',
    ];
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18444
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Nrepo.Properties {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Nrepo.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The argument '{0}' is null..
        /// </summary>
        internal static string ArgumentIsNull1 {
            get {
                return ResourceManager.GetString("ArgumentIsNull1", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The argument '{0}' is null or empty..
        /// </summary>
        internal static string ArgumentIsNullOrEmpty1 {
            get {
                return ResourceManager.GetString("ArgumentIsNullOrEmpty1", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The property '{0}' is null..
        /// </summary>
        internal static string PropertyIsNull1 {
            get {
                return ResourceManager.GetString("PropertyIsNull1", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The property '{0}' was not found..
        /// </summary>
        internal static string PropertyNotFound1 {
            get {
                return ResourceManager.GetString("PropertyNotFound1", resourceCulture);
            }
        }
    }
}


text:
package com.github.edgar615.gateway.core.plugin.predicate;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

import com.github.edgar615.gateway.core.dispatch.ApiContext;
import com.github.edgar615.util.base.Randoms;
import io.vertx.core.http.HttpMethod;
import org.junit.Assert;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class HeaderContainsPredicateTest {

    @Test
    public void testNoHeader() {
        Multimap<String, String> header = ArrayListMultimap.create();
        ApiContext apiContext
                = ApiContext.create(HttpMethod.GET, "/", header, ArrayListMultimap.create(), null);
        List<String> headerContains = new ArrayList<>();
        headerContains.add("x-request-id");
        HeaderContainsPredicate predicate = new HeaderContainsPredicate(headerContains);
        Assert.assertFalse(predicate.test(apiContext));
    }

    @Test
    public void testContainsOneHeader() {
        Multimap<String, String> header = ArrayListMultimap.create();
        header.put("x-request-id", UUID.randomUUID().toString());
        header.put("Content-Type", "application/json");
        ApiContext apiContext
                = ApiContext.create(HttpMethod.GET, "/", header, ArrayListMultimap.create(), null);
        List<String> headerContains = new ArrayList<>();
        headerContains.add("x-request-id");
        HeaderContainsPredicate predicate = new HeaderContainsPredicate(headerContains);
        Assert.assertTrue(predicate.test(apiContext));
    }

    @Test
    public void testContainsTwoHeader() {
        Multimap<String, String> header = ArrayListMultimap.create();
        header.put("x-request-id", UUID.randomUUID().toString());
        header.put("Content-Type", "application/json");
        ApiContext apiContext
                = ApiContext.create(HttpMethod.GET, "/", header, ArrayListMultimap.create(), null);
        List<String> headerContains = new ArrayList<>();
        headerContains.add("x-request-id");
        headerContains.add("Content-Type");
        HeaderContainsPredicate predicate = new HeaderContainsPredicate(headerContains);
        Assert.assertTrue(predicate.test(apiContext));
    }

    @Test
    public void testNotContainsOneHeader() {
        Multimap<String, String> header = ArrayListMultimap.create();
        header.put("x-request-id", UUID.randomUUID().toString());
        header.put("Content-Type", "application/json");
        ApiContext apiContext
                = ApiContext.create(HttpMethod.GET, "/", header, ArrayListMultimap.create(), null);
        List<String> headerContains = new ArrayList<>();
        headerContains.add(Randoms.randomAlphabet(8));
        HeaderContainsPredicate predicate = new HeaderContainsPredicate(headerContains);
        Assert.assertFalse(predicate.test(apiContext));
    }

    @Test
    public void testNotContainsTwoHeader() {
        Multimap<String, String> header = ArrayListMultimap.create();
        header.put("x-request-id", UUID.randomUUID().toString());
        header.put("Content-Type", "application/json");
        ApiContext apiContext
                = ApiContext.create(HttpMethod.GET, "/", header, ArrayListMultimap.create(), null);
        List<String> headerContains = new ArrayList<>();
        headerContains.add("x-request-id");
        headerContains.add(Randoms.randomAlphabet(8));
        HeaderContainsPredicate predicate = new HeaderContainsPredicate(headerContains);
        Assert.assertFalse(predicate.test(apiContext));
    }
}


text:
/**
 * This program and the accompanying materials
 * are made available under the terms of the License
 * which accompanies this distribution in the file LICENSE.txt
 */
package com.archimatetool.modelimporter;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.CommandStack;
import org.eclipse.gef.commands.CompoundCommand;
import org.eclipse.osgi.util.NLS;

import com.archimatetool.editor.diagram.commands.DiagramCommandFactory;
import com.archimatetool.editor.model.DiagramModelUtils;
import com.archimatetool.editor.model.IEditorModelManager;
import com.archimatetool.editor.model.commands.EObjectFeatureCommand;
import com.archimatetool.editor.model.commands.NonNotifyingCompoundCommand;
import com.archimatetool.model.IArchimateConcept;
import com.archimatetool.model.IArchimateModel;
import com.archimatetool.model.IArchimateModelObject;
import com.archimatetool.model.IArchimatePackage;
import com.archimatetool.model.IArchimateRelationship;
import com.archimatetool.model.ICloneable;
import com.archimatetool.model.IConnectable;
import com.archimatetool.model.IDiagramModel;
import com.archimatetool.model.IDiagramModelArchimateComponent;
import com.archimatetool.model.IDiagramModelArchimateConnection;
import com.archimatetool.model.IFeature;
import com.archimatetool.model.IFeatures;
import com.archimatetool.model.IFolder;
import com.archimatetool.model.IIdentifier;
import com.archimatetool.model.IProfile;
import com.archimatetool.model.IProperties;
import com.archimatetool.model.IProperty;
import com.archimatetool.model.util.ArchimateModelUtils;
import com.archimatetool.modelimporter.StatusMessage.StatusMessageLevel;

/**
 * Model Importer
 *
 * @author Phillip Beauvoir
 * @author Jean-Baptiste Sarrodie
 */
public class ModelImporter {

    private boolean update; // If true update target objects with source objects
    private boolean updateAll; // If true update model name, purpose, documentation and top level folders with source

    private IArchimateModel importedModel;
    private IArchimateModel targetModel;

    // Keep a cache of objects in the target model
    private Map<String, IIdentifier> objectCache;

    // Status Messages
    private List<StatusMessage> statusMessages;

    // Undo/Redo commands
    private NonNotifyingCompoundCommand compoundCommand;

    // Ecore attributes that should not be imported
    private static Set<EAttribute> IGNORED_EATTRIBUTES = Set.of(
            IArchimatePackage.Literals.DIAGRAM_MODEL_IMAGE_PROVIDER__IMAGE_PATH, // Image Path - we will set this
            IArchimatePackage.Literals.ARCHIMATE_MODEL__FILE,                    // File path - definitely not!
            IArchimatePackage.Literals.ARCHIMATE_MODEL__VERSION                  // Model version
    );

    public ModelImporter() {
    }

    public void doImport(File importedFile, IArchimateModel targetModel) throws IOException, ImportException {
        if(!importedFile.exists()) {
            throw new IOException(NLS.bind(Messages.ModelImporter_2, importedFile));
        }

        doImport(IEditorModelManager.INSTANCE.load(importedFile), targetModel);
    }

    public void doImport(IArchimateModel importedModel, IArchimateModel targetModel) throws IOException, ImportException {
        this.importedModel = importedModel;
        this.targetModel = targetModel;

        objectCache = createObjectIDCache();

        statusMessages = new ArrayList<>();

        compoundCommand = new NonNotifyingCompoundCommand(Messages.ModelImporter_1);

        // Upate root model object if the option is set
        if(updateAll) {
            updateObject(importedModel, targetModel);
            logMessage(StatusMessageLevel.INFO, Messages.ModelImporter_3, targetModel);
        }

        // Iterate through all model contents
        for(Iterator<EObject> iter = importedModel.eAllContents(); iter.hasNext();) {
            EObject eObject = iter.next();

            // Update folders
            if(eObject instanceof IFolder) {
                new FolderImporter(this).importFolder((IFolder)eObject);
            }
            // Update concepts
            else if(eObject instanceof IArchimateConcept) {
                new ConceptImporter(this).importConcept((IArchimateConcept)eObject);
            }
            // Update Views
            else if(eObject instanceof IDiagramModel) {
                new ViewImporter(this).importView((IDiagramModel)eObject);
            }
            // Update Profiles
            else if(eObject instanceof IProfile) {
                new ProfileImporter(this).importProfile((IProfile)eObject);
            }
        }

        if(compoundCommand.canExecute()) {
            // Check view connection ends are valid if we have done some commands and even if update is off
            addCommand(new SetArchimateReconnectionCommand(targetModel));

            // Check duplicate names in Profiles
            // TODO: No more needed because we match profiles by name and can't generate duplicates
            // addCommand(new UnduplicateProfileNamesCommand(targetModel));
        }

        // Run Commands
        CommandStack stack = (CommandStack)targetModel.getAdapter(CommandStack.class);
        stack.execute(compoundCommand);

        objectCache.clear();
        objectCache = null;
        importedModel = null;
        this.targetModel = null;
    }

    protected IArchimateModel getImportedModel() {
        return importedModel;
    }

    protected IArchimateModel getTargetModel() {
        return targetModel;
    }

    /**
     * If true update/replace target objects with source objects - sub-folders, concepts, folder structure, views
     */
    public void setUpdate(boolean update) {
        this.update = update;
    }

    public boolean shouldUpdate() {
        return update;
    }

    /**
     * If true update/replace model and top level folders' name, purpose, documentation and properties with source
     */
    public void setUpdateAll(boolean updateAll) {
        this.updateAll = updateAll;
        if(updateAll) {
            update = true; // If we are updating all then set this too
        }
    }

    public boolean shouldUpdateAll() {
        return updateAll;
    }

    public List<StatusMessage> getStatusMessages() {
        return statusMessages;
    }

    /**
     * Create a cache of objects in the target model
     */
    private Map<String, IIdentifier> createObjectIDCache() {
        HashMap<String, IIdentifier> map = new HashMap<String, IIdentifier>();

        for(Iterator<EObject> iter = targetModel.eAllContents(); iter.hasNext();) {
            EObject eObject = iter.next();

            String key = getObjectKey(eObject);
            if(key != null) {
                map.put(key, (IIdentifier)eObject);
            }
        }

        return map;
    }

    /**
     * @return Object's Key for lookup
     */
    private String getObjectKey(EObject eObject) {
        // Profile uses Concept Type and Name (case-insensitive)
        if(eObject instanceof IProfile) {
            return ((IProfile)eObject).getConceptType() + ((IProfile)eObject).getName().toLowerCase();
        }
        // Else use ID
        else if(eObject instanceof IIdentifier) {
            return ((IIdentifier)eObject).getId();
        }

        return null;
    }

    // ===================================================================================
    // Shared methods
    // ===================================================================================

    /**
     * Add a command to the Compound Command for later execution
     */
    void addCommand(Command cmd) {
        if(cmd.canExecute()) {
            compoundCommand.add(cmd);
        }
    }

    /**
     * Find an object in the target model based on the eObject's identifier and class
     * Existing and newly added objects in the target model are added to the objectCache
     */
    @SuppressWarnings("unchecked")
    <T extends IIdentifier> T findObjectInTargetModel(T eObject) throws ImportException {
    	EObject foundObject = objectCache.get(getObjectKey(eObject));

        // Not found
        if(foundObject == null) {
            return null;
        }

        // Not the right class, so that's an error we should report
        if(foundObject.eClass() != eObject.eClass()) {
            throw new ImportException("Found object with same id but different class: " + eObject.getId()); //$NON-NLS-1$
        }

        // Found an element with same key and the class is the same
        return (T)foundObject;
    }

    /**
     * Create a new object based on class of a given object and set its data to that in the given object
     */
    @SuppressWarnings("unchecked")
    <T extends IArchimateModelObject> T cloneObject(T eObject) {
        IArchimateModelObject newObject;

        if(eObject instanceof ICloneable) {
            newObject = (IArchimateModelObject)((ICloneable)eObject).getCopy();
        }
        else {
            newObject = (IArchimateModelObject)EcoreUtil.create(eObject.eClass());
            updateObject(eObject, newObject);
        }

        newObject.setId(eObject.getId());

        // Update global object cache
        objectCache.put(getObjectKey(newObject), newObject);

        return (T)newObject;
    }

    /**
     * Update target object with data from source object
     */
    void updateObject(EObject importedObject, EObject targetObject) {
    	// EAttributes
        updateEObjectFeatures(importedObject, targetObject);

        // Properties
        if(importedObject instanceof IProperties  && targetObject instanceof IProperties) {
            addCommand(new UpdatePropertiesCommand((IProperties)importedObject, (IProperties)targetObject));
        }

        // Features
        if(importedObject instanceof IFeatures && targetObject instanceof IFeatures) {
            addCommand(new UpdateFeaturesCommand((IFeatures)importedObject, (IFeatures)targetObject));
        }
    }

    /**
     * Update all EAttributes (Name, Documentation, Access type, Influence streangth...) in a generic manner
     */
    void updateEObjectFeatures(EObject importedObject, EObject targetObject) {
        if(importedObject == null || targetObject == null) {
            return;
        }

        for(EStructuralFeature eStructuralFeature : importedObject.eClass().getEAllStructuralFeatures()) {
            if(eStructuralFeature instanceof EAttribute                     // EAttribute
                    && !IGNORED_EATTRIBUTES.contains(eStructuralFeature)    // Check ignored list
                    && eStructuralFeature.isChangeable()                    // Can change it
                    && !eStructuralFeature.isDerived()                      // Is not derived
                    && !((EAttribute)eStructuralFeature).isID())            // Is not ID
            {
                addCommand(new EObjectFeatureCommand(null, targetObject, eStructuralFeature, importedObject.eGet(eStructuralFeature)));
            }
        }
    }

    /**
     * Log a status message
     */
    void logMessage(StatusMessageLevel level, String message, Object... objs) {
        statusMessages.add(new StatusMessage(level, message, objs));
    }

    // ====================================================================================================
    // Commands
    // ====================================================================================================

    private static class UpdatePropertiesCommand extends Command {
        private IProperties importedObject;
        private IProperties targetObject;
        private List<IProperty> oldProperties;

        private UpdatePropertiesCommand(IProperties importedObject, IProperties targetObject) {
            this.importedObject = importedObject;
            this.targetObject = targetObject;
            oldProperties = new ArrayList<>(targetObject.getProperties());
        }

        @Override
        public void execute() {
            targetObject.getProperties().clear();
            targetObject.getProperties().addAll(EcoreUtil.copyAll(importedObject.getProperties()));
        }

        @Override
        public void undo() {
            targetObject.getProperties().clear();
            targetObject.getProperties().addAll(oldProperties);
        }

        @Override
        public void dispose() {
            importedObject = null;
            targetObject = null;
            oldProperties = null;
        }
    }

    private static class UpdateFeaturesCommand extends Command {
        private IFeatures importedObject;
        private IFeatures targetObject;
        private ArrayList<IFeature> oldFeatures;

        private UpdateFeaturesCommand(IFeatures importedObject, IFeatures targetObject) {
            this.importedObject = importedObject;
            this.targetObject = targetObject;
            oldFeatures = new ArrayList<>(targetObject.getFeatures());
        }

        @Override
        public void execute() {
            targetObject.getFeatures().clear();
            targetObject.getFeatures().addAll(EcoreUtil.copyAll(importedObject.getFeatures()));
        }

        @Override
        public void undo() {
            targetObject.getFeatures().clear();
            targetObject.getFeatures().addAll(oldFeatures);
        }

        @Override
        public void dispose() {
            importedObject = null;
            targetObject = null;
            oldFeatures = null;
        }
    }

    /**
     * Archimate View Connections might need reconnecting or disconnecting
     * This can only be executed once all previous commands have run so that the target model is in the correct state
     */
    private class SetArchimateReconnectionCommand extends CompoundCommand {
        private IArchimateModel model;

        private SetArchimateReconnectionCommand(IArchimateModel model) {
            this.model = model;

            // Add an empty Command so this always executes
            add(new Command() {});
        }

        @Override
        public void execute() {
            for(Iterator<EObject> iter = model.eAllContents(); iter.hasNext();) {
                EObject eObject = iter.next();

                if(eObject instanceof IDiagramModelArchimateConnection) {
                    addArchimateReconnectionCommand((IDiagramModelArchimateConnection)eObject);
                }
            }

            super.execute();
        }

        @Override
        public void dispose() {
            super.dispose();
            model = null;
        }

        /**
         * Reconnect Archimate connections in case of relationship ends having changed
         */
        private void addArchimateReconnectionCommand(IDiagramModelArchimateConnection connection) {
            IArchimateRelationship relationship = connection.getArchimateRelationship();

            // Is source object valid?
            if(((IDiagramModelArchimateComponent)connection.getSource()).getArchimateConcept() != relationship.getSource()) {
                // Get the first instance of the new source in this view and connect to that
                List<IDiagramModelArchimateComponent> list = DiagramModelUtils.findDiagramModelComponentsForArchimateConcept(connection.getDiagramModel(),
                        relationship.getSource());
                if(!list.isEmpty()) {
                    IDiagramModelArchimateComponent matchingComponent = list.get(0);
                    IConnectable oldSource = connection.getSource();

                    add(new Command() {
                        @Override
                        public void execute() {
                            connection.connect(matchingComponent, connection.getTarget());
                        }

                        @Override
                        public void undo() {
                            connection.connect(oldSource, connection.getTarget());
                        }
                    });

                    logMessage(StatusMessageLevel.WARNING, Messages.ModelImporter_4, connection, connection.getDiagramModel());
                }
                // Not found, so delete the matching connection
                else {
                    add(DiagramCommandFactory.createDeleteDiagramConnectionCommand(connection));
                    logMessage(StatusMessageLevel.WARNING, Messages.ModelImporter_5, connection, connection.getDiagramModel());
                }
            }

            // Is target object valid?
            if(((IDiagramModelArchimateComponent)connection.getTarget()).getArchimateConcept() != relationship.getTarget()) {
                // Get the first instance of the new source in this view and connect to that
                List<IDiagramModelArchimateComponent> list = DiagramModelUtils.findDiagramModelComponentsForArchimateConcept(connection.getDiagramModel(), relationship.getTarget());
                if(!list.isEmpty()) {
                    IDiagramModelArchimateComponent matchingComponent = list.get(0);
                    IConnectable oldTarget = connection.getTarget();

                    add(new Command() {
                        @Override
                        public void execute() {
                            connection.connect(connection.getSource(), matchingComponent);
                        }

                        @Override
                        public void undo() {
                            connection.connect(connection.getSource(), oldTarget);
                        }
                    });

                    logMessage(StatusMessageLevel.WARNING, Messages.ModelImporter_6, connection, connection.getDiagramModel());
                }
                // Not found, so delete the matching connection
                else {
                    add(DiagramCommandFactory.createDeleteDiagramConnectionCommand(connection));
                    logMessage(StatusMessageLevel.WARNING, Messages.ModelImporter_5, connection, connection.getDiagramModel());
                }
            }
        }
    }

    /**
     * Check for duplicate names in Profiles and append a string
     * TODO: can be removed (if kept, then should be refactored so that suffixes are not duplicates)
     */
    @SuppressWarnings("unused")
    private static class UnduplicateProfileNamesCommand extends CompoundCommand {
        private IArchimateModel targetModel;

        private UnduplicateProfileNamesCommand(IArchimateModel targetModel) {
            this.targetModel = targetModel;

            // Add an empty Command so this always executes
            add(new Command() {});

        }

        @Override
        public void execute() {
            for(IProfile profile : targetModel.getProfiles()) {
                IProfile p = ArchimateModelUtils.getProfileByNameAndType(targetModel, profile.getName(), profile.getConceptType());
                if(p != null && p != profile) {
                    add(new EObjectFeatureCommand(null, profile, IArchimatePackage.Literals.NAMEABLE__NAME, profile.getName() + "_1")); //$NON-NLS-1$
                }
            }

            super.execute();
        }

        @Override
        public void dispose() {
            super.dispose();
            targetModel = null;
        }
    }
}


text:
Dose
====

This is the repository for the Dose Project.
The Dose project is about implementing controllers and devices
as Arduino compatible solutions that fit into a flush-mounted box.