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

public class GalaxyGUI : MonoBehaviour
{
	public GameObject coloniseButton, snapColoniseButton, planetSelectionWindow, purgeButton;
	private List<GameObject> planetSelectionList = new List<GameObject>();
	private int selectedSystem;
	private string tempRace, knowledgeString, powerString, wealthString, turnNumber;
	public UILabel knowledgeLabel, powerLabel, wealthLabel, raceLabel, turnLabel, diplomacyLabelOne, diplomacyLabelTwo, rareResources;

	void Start()
	{
		foreach(Transform child in planetSelectionWindow.transform)
		{
			planetSelectionList.Add (child.gameObject);
		}
	}

	void Update()
	{
		UpdateVariables();
		UpdateLabels ();
	}

	private void UpdateVariables()
	{
		if(MasterScript.playerTurnScript.playerRace != null && MasterScript.cameraFunctionsScript.selectedSystem != null)
		{
			knowledgeString = ((int)MasterScript.playerTurnScript.knowledge).ToString();
			powerString = ((int)MasterScript.playerTurnScript.power).ToString ();
			wealthString = ((int)MasterScript.playerTurnScript.wealth).ToString ();
			turnNumber = "Year: " + (2200 + (int)(MasterScript.turnInfoScript.turn / 2f)).ToString();
			selectedSystem = MasterScript.RefreshCurrentSystem(MasterScript.cameraFunctionsScript.selectedSystem);

			if(MasterScript.systemListConstructor.systemList[selectedSystem].systemOwnedBy == null)
			{
				NGUITools.SetActive(coloniseButton, true);

				if(MasterScript.playerTurnScript.playerRace == "Nereides")
				{
					float totalPower = 20;
					float totalWealth = 10;

					for(int i = 0; i < MasterScript.systemListConstructor.systemList[selectedSystem].systemSize; ++i)
					{
						totalWealth += MasterScript.systemListConstructor.systemList[selectedSystem].planetsInSystem[i].wealthValue;
						totalPower += ((float)MasterScript.systemListConstructor.systemList[selectedSystem].planetsInSystem[i].wealthValue / 3f) * 20f;
					}

					string cost = "Power: " + totalPower + "\nWealth: " + totalWealth;

					snapColoniseButton.GetComponent<UILabel>().text = cost;

					NGUITools.SetActive(snapColoniseButton, true);
				}
			}
		}
	}

	public void SelectRace(string thisRace)
	{
		MasterScript.playerTurnScript.playerRace = thisRace;
		MasterScript.playerTurnScript.StartTurn();
		MasterScript.turnInfoScript.CreateEnemyAI ();

		for(int i = 0; i < MasterScript.turnInfoScript.allPlayers.Count; ++i)
		{
			MasterScript.turnInfoScript.allPlayers[i].RaceStart(MasterScript.turnInfoScript.allPlayers[i].playerRace);
		}

		raceLabel.text = MasterScript.playerTurnScript.playerRace;

		if(MasterScript.playerTurnScript.playerRace == "Nereides")
		{
			NGUITools.SetActive(purgeButton, true);
		}

		MasterScript.turnInfoScript.StartGame ();
	}

	private void UpdateLabels()
	{
		knowledgeLabel.text = knowledgeString;
		powerLabel.text = powerString;
		wealthLabel.text = wealthString;
		turnLabel.text = turnNumber;

		string resources = null;

		if(MasterScript.playerTurnScript.antimatter > 0)
		{
			resources = "ANTIMATTER: " + MasterScript.playerTurnScript.antimatter + "  ";
		}
		if(MasterScript.playerTurnScript.blueCarbon > 0)
		{
			resources = resources + "BLUE CARBON: " + MasterScript.playerTurnScript.blueCarbon + "  ";
		}
		if(MasterScript.playerTurnScript.radioisotopes > 0)
		{
			resources = resources + "RADIOISOTOPES: " + MasterScript.playerTurnScript.radioisotopes + "  ";
		}
		if(MasterScript.playerTurnScript.liquidH2 > 0)
		{
			resources = resources + "LIQUID HYDROGEN: " + MasterScript.playerTurnScript.liquidH2 + "  ";
		}

		rareResources.text = resources;

		string tempString = null;

		for(int i = 0; i < MasterScript.diplomacyScript.relationsList.Count; ++i)
		{
			if(MasterScript.diplomacyScript.relationsList[i].playerOne.playerRace == MasterScript.playerTurnScript.playerRace
			   || MasterScript.diplomacyScript.relationsList[i].playerTwo.playerRace == MasterScript.playerTurnScript.playerRace)
			{
				tempString = tempString + MasterScript.diplomacyScript.relationsList[i].diplomaticState + " | " + MasterScript.diplomacyScript.relationsList[i].stateCounter;

				if(i != MasterScript.diplomacyScript.relationsList.Count - 1)
				{
					tempString = tempString + "\n";
				}
			}
		}

		diplomacyLabelOne.text = tempString;
	}

	public void CheckToColoniseSystem()
	{
		if(MasterScript.playerTurnScript.wealth >= 10)
		{
			MasterScript.playerTurnScript.FindSystem (selectedSystem);
			SelectFirstPlanet();
			NGUITools.SetActive(coloniseButton, false);
			NGUITools.SetActive(snapColoniseButton, false);
		}
	}

	public void SnapColonise()
	{
		float totalPower = 20;
		float totalWealth = 10;

		for(int i = 0; i < MasterScript.systemListConstructor.systemList[selectedSystem].systemSize; ++i)
		{
			totalWealth += MasterScript.systemListConstructor.systemList[selectedSystem].planetsInSystem[i].wealthValue;
			totalPower += ((float)MasterScript.systemListConstructor.systemList[selectedSystem].planetsInSystem[i].wealthValue / 3f) * 20f;
		}

		if(MasterScript.playerTurnScript.wealth >= totalWealth && MasterScript.playerTurnScript.power > totalPower)
		{
			MasterScript.playerTurnScript.FindSystem (selectedSystem);
			MasterScript.playerTurnScript.wealth -= totalWealth;
			MasterScript.playerTurnScript.power -= totalPower;

			for(int i = 0; i < MasterScript.systemListConstructor.systemList[selectedSystem].systemSize; ++i)
			{
				MasterScript.systemListConstructor.systemList[selectedSystem].planetsInSystem[i].planetColonised = true;
				MasterScript.systemListConstructor.systemList [selectedSystem].planetsInSystem [i].expansionPenaltyTimer = Time.time;
			}

			NGUITools.SetActive(coloniseButton, false);
			NGUITools.SetActive(snapColoniseButton, false);
		}
	}

	public void ColonisePlanet()
	{
		int planet = planetSelectionList.IndexOf (UIButton.current.gameObject);

		MasterScript.systemListConstructor.systemList[selectedSystem].planetsInSystem[planet].planetColonised = true;

		MasterScript.systemListConstructor.systemList [selectedSystem].planetsInSystem [planet].expansionPenaltyTimer = Time.time;

		++MasterScript.playerTurnScript.planetsColonisedThisTurn;

		++MasterScript.playerTurnScript.systemsColonisedThisTurn;

		MasterScript.playerTurnScript.systemHasBeenColonised = false;

		NGUITools.SetActive (planetSelectionWindow, false);
	}

	private void SelectFirstPlanet()
	{
		NGUITools.SetActive (planetSelectionWindow, true);

		for(int i = 0; i < planetSelectionList.Count; ++i)
		{
			if(i < MasterScript.systemListConstructor.systemList[selectedSystem].systemSize)
			{
				float planetSIM = MasterScript.systemListConstructor.systemList[selectedSystem].planetsInSystem[i].planetKnowledge + MasterScript.systemListConstructor.systemList[selectedSystem].planetsInSystem[i].planetPower;

				string planetInfo = MasterScript.systemListConstructor.systemList[selectedSystem].planetsInSystem[i].planetType + " " + planetSIM.ToString() + " SIM";

				planetSelectionList[i].transform.Find ("Label").gameObject.GetComponent<UILabel>().text = planetInfo.ToUpper();

				NGUITools.SetActive(planetSelectionList[i], true);
			}

			if(i >= MasterScript.systemListConstructor.systemList[selectedSystem].systemSize)
			{
				NGUITools.SetActive(planetSelectionList[i], false);
			}
		}

		planetSelectionWindow.GetComponent<UIScrollView> ().ResetPosition ();
		planetSelectionWindow.GetComponent<UIGrid> ().repositionNow = true;
	}
}

redpajama_set_name: RedPajamaGithub


text:
module.exports = function(kernelP) {
  return (function() {
    var Utils = require('../../utils.js');

    var gKernelP = kernelP;

    /**
     * @classdesc
     * A feature transformer that takes the 1D discrete cosine transform of a real vector. No zero
     * padding is performed on the input vector.
     * It returns a real vector of the same length representing the DCT. The return vector is scaled
     * such that the transform matrix is unitary (aka scaled DCT-II).
     *
     * More information on [[https://en.wikipedia.org/wiki/Discrete_cosine_transform#DCT-II Wikipedia]].
     * @class
     * @memberof module:eclairjs/ml/feature
     */

    /**
     * @param {string} uid
     * @constructor
     */
    function DCT() {
      Utils.handleConstructor(this, arguments, gKernelP);
    }

    /**
     * Indicates whether to perform the inverse DCT (true) or forward DCT (false).
     * Default: false
     * @returns {Promise.<BooleanParam>}
     */
    DCT.prototype.inverse = function() {
      var args = {
        target: this,
        method: 'inverse',
        args: Utils.wrapArguments(arguments),
        returnType: DCT
      };

      return Utils.generate(args);
    };

    /**
     * @param {boolean} value
     * @returns {module:eclairjs/ml/feature.DCT}
     */
    DCT.prototype.setInverse = function(value) {
      var args = {
        target: this,
        method: 'setInverse',
        args: Utils.wrapArguments(arguments),
        returnType: DCT
      };

      return Utils.generate(args);
    };

    /**
     * @returns {Promise.<boolean>}
     */
    DCT.prototype.getInverse = function() {
      var args = {
        target: this,
        method: 'getInverse',
        args: Utils.wrapArguments(arguments),
        returnType: Boolean
      };

      return Utils.generate(args);
    };

    /**
     * An immutable unique ID for the object and its derivatives.
     * @returns {Promise.<string>}
     */
    DCT.prototype.uid = function() {
      var args = {
        target: this,
        method: 'uid',
        args: Utils.wrapArguments(arguments),
        returnType: String
      };

      return Utils.generate(args);
    };

    /**
     * @param {module:eclairjs/sql.DataFrame} dataset
     * @returns {module:eclairjs/sql.DataFrame}
     */
    DCT.prototype.transform = function(dataset) {
      var DataFrame = require('../../sql/DataFrame.js');

      var args = {
        target: this,
        method: 'transform',
        args: Utils.wrapArguments(arguments),
        returnType: DataFrame
      };

      return Utils.generate(args);
    };

    /**
     * @param {module:eclairjs/sql/types.StructType} schema
     * @returns {module:eclairjs/sql/types.StructType}
     */
    DCT.prototype.transformSchema = function(schema) {
      var StructType = require('../../sql/types/StructType.js')();

      var args = {
        target: this,
        method: 'transformSchema',
        args: Utils.wrapArguments(arguments),
        returnType: StructType
      };

      return Utils.generate(args);
    };

    /**
     * @param {module:eclairjs/ml/param.ParamMap} extra
     * @returns {module:eclairjs/ml/feature.DCT}
     */
    DCT.prototype.copy = function(extra) {
      var args = {
        target: this,
        method: 'copy',
        args: Utils.wrapArguments(arguments),
        returnType: DCT
      };

      return Utils.generate(args);
    };

    /**
     * @param {string} value
     * @returns {module:eclairjs/ml/feature.DCT}
     */
    DCT.prototype.setInputCol = function(value) {
      var args = {
        target: this,
        method: 'setInputCol',
        args: Utils.wrapArguments(arguments),
        returnType: DCT
      };

      return Utils.generate(args);
    };

    /**
     * @param {string} value
     * @returns {module:eclairjs/ml/feature.DCT}
     */
    DCT.prototype.setOutputCol = function(value) {
      var args = {
        target: this,
        method: 'setOutputCol',
        args: Utils.wrapArguments(arguments),
        returnType: DCT
      };

      return Utils.generate(args);
    };

    //
    // static methods
    //

    /**
     * @param {string} path
     * @returns {module:eclairjs/ml/feature.DCT}
     */
    DCT.load = function(path) {
      var args = {
        target: DCT,
        method: 'load',
        kernelP: gKernelP,
        static: true,
        args: Utils.wrapArguments(arguments),
        returnType: DCT
      };

      return Utils.generate(args);
    };

    DCT.moduleLocation = '/ml/feature/DCT';

    return DCT;
  })();
};


text:
class Author < ActiveRecord::Base
  # Include default devise modules.
  devise :database_authenticatable, :registerable,
          :recoverable, :rememberable, :trackable, :validatable,
          :confirmable,:timeoutable,:omniauthable
  include DeviseTokenAuth::Concerns::User

	before_save -> do
    self.uid = SecureRandom.uuid
    skip_confirmation!
  end
  def self.create_with_omniauth(auth)
    create! do |user|
      user.email = auth.extra.raw_info.email
      user.provider = auth["provider"]
      user.uid = auth["uid"]
      user.name = auth["info"]["name"]
      user.password = SecureRandom.urlsafe_base64
    end
  end
end


text:
namespace DotNetGroup.Web.Controllers
{
    using System.Collections.Generic;
    using System.Configuration;
    using System.Linq;
    using System.Web.Mvc;

    using DotNetGroup.Services.Model;
    using DotNetGroup.Services.Web;
    using DotNetGroup.Web.ViewModels;

    public class StreamController : Controller
    {
        private readonly string apiUrl;
        private readonly IJsonClient jsonClient;
        private readonly IStreamItemMapper mapper;

        public StreamController()
            : this(ConfigurationManager.AppSettings["api.url"], new JsonClient(), new StreamItemMapper())
        {
        }

        public StreamController(string apiUrl, IJsonClient jsonClient, IStreamItemMapper mapper)
        {
            this.apiUrl = apiUrl;
            this.jsonClient = jsonClient;
            this.mapper = mapper;
        }

        public ActionResult Index()
        {
            var stream = this.Get(this.apiUrl);

            return this.View("Index", stream);
        }

        public ActionResult Newer(string id)
        {
            var url = string.Format("{0}/?min_id={1}", this.apiUrl, id);
            var stream = this.Get(url);

            return this.PartialView("Stream", stream);
        }

        public ActionResult Older(string id)
        {
            var url = string.Format("{0}/?max_id={1}", this.apiUrl, id);
            var stream = this.Get(url);

            return Request.IsAjaxRequest()
                       ? this.PartialView("Stream", stream)
                       : (ActionResult)this.View("Index", stream);
        }

        private IEnumerable<StreamItem> Get(string url)
        {
            return this.jsonClient.Get<IEnumerable<Item>>(url).Select(item => this.mapper.MapFrom(item));
        }
    }
}


text:
package volume

import (
	"fmt"
	"os"
	"path"

	"k8s.io/kubernetes/pkg/api"
	client "k8s.io/kubernetes/pkg/client/unversioned"
	"k8s.io/kubernetes/pkg/cloudprovider"
	"k8s.io/kubernetes/pkg/types"
	"k8s.io/kubernetes/pkg/util"
	"k8s.io/kubernetes/pkg/util/io"
	"k8s.io/kubernetes/pkg/util/mount"
)

// fakeVolumeHost is useful for testing volume plugins.
type fakeVolumeHost struct {
	rootDir    string
	kubeClient client.Interface
	pluginMgr  VolumePluginMgr
	cloud      cloudprovider.Interface
	mounter    mount.Interface
	writer     io.Writer
}

func NewFakeVolumeHost(rootDir string, kubeClient client.Interface, plugins []VolumePlugin) *fakeVolumeHost {
	host := &fakeVolumeHost{rootDir: rootDir, kubeClient: kubeClient, cloud: nil}
	host.mounter = &mount.FakeMounter{}
	host.writer = &io.StdWriter{}
	host.pluginMgr.InitPlugins(plugins, host)
	return host
}

func (f *fakeVolumeHost) GetPluginDir(podUID string) string {
	return path.Join(f.rootDir, "plugins", podUID)
}

func (f *fakeVolumeHost) GetPodVolumeDir(podUID types.UID, pluginName, volumeName string) string {
	return path.Join(f.rootDir, "pods", string(podUID), "volumes", pluginName, volumeName)
}

func (f *fakeVolumeHost) GetPodPluginDir(podUID types.UID, pluginName string) string {
	return path.Join(f.rootDir, "pods", string(podUID), "plugins", pluginName)
}

func (f *fakeVolumeHost) GetKubeClient() client.Interface {
	return f.kubeClient
}

func (f *fakeVolumeHost) GetCloudProvider() cloudprovider.Interface {
	return f.cloud
}

func (f *fakeVolumeHost) GetMounter() mount.Interface {
	return f.mounter
}

func (f *fakeVolumeHost) GetWriter() io.Writer {
	return f.writer
}

func (f *fakeVolumeHost) NewWrapperBuilder(spec *Spec, pod *api.Pod, opts VolumeOptions) (Builder, error) {
	plug, err := f.pluginMgr.FindPluginBySpec(spec)
	if err != nil {
		return nil, err
	}
	return plug.NewBuilder(spec, pod, opts)
}

func (f *fakeVolumeHost) NewWrapperCleaner(spec *Spec, podUID types.UID) (Cleaner, error) {
	plug, err := f.pluginMgr.FindPluginBySpec(spec)
	if err != nil {
		return nil, err
	}
	return plug.NewCleaner(spec.Name(), podUID)
}

func ProbeVolumePlugins(config VolumeConfig) []VolumePlugin {
	if _, ok := config.OtherAttributes["fake-property"]; ok {
		return []VolumePlugin{
			&FakeVolumePlugin{
				PluginName: "fake-plugin",
				Host:       nil,
				// SomeFakeProperty: config.OtherAttributes["fake-property"] -- string, may require parsing by plugin
			},
		}
	}
	return []VolumePlugin{&FakeVolumePlugin{PluginName: "fake-plugin"}}
}

// FakeVolumePlugin is useful for testing.  It tries to be a fully compliant
// plugin, but all it does is make empty directories.
// Use as:
//   volume.RegisterPlugin(&FakePlugin{"fake-name"})
type FakeVolumePlugin struct {
	PluginName string
	Host       VolumeHost
	Config     VolumeConfig
}

var _ VolumePlugin = &FakeVolumePlugin{}
var _ RecyclableVolumePlugin = &FakeVolumePlugin{}
var _ DeletableVolumePlugin = &FakeVolumePlugin{}
var _ ProvisionableVolumePlugin = &FakeVolumePlugin{}

func (plugin *FakeVolumePlugin) Init(host VolumeHost) {
	plugin.Host = host
}

func (plugin *FakeVolumePlugin) Name() string {
	return plugin.PluginName
}

func (plugin *FakeVolumePlugin) CanSupport(spec *Spec) bool {
	// TODO: maybe pattern-match on spec.Name() to decide?
	return true
}

func (plugin *FakeVolumePlugin) NewBuilder(spec *Spec, pod *api.Pod, opts VolumeOptions) (Builder, error) {
	return &FakeVolume{pod.UID, spec.Name(), plugin}, nil
}

func (plugin *FakeVolumePlugin) NewCleaner(volName string, podUID types.UID) (Cleaner, error) {
	return &FakeVolume{podUID, volName, plugin}, nil
}

func (plugin *FakeVolumePlugin) NewRecycler(spec *Spec) (Recycler, error) {
	return NewFakeRecycler(spec, plugin.Host, plugin.Config)
}

func (plugin *FakeVolumePlugin) NewDeleter(spec *Spec) (Deleter, error) {
	return &FakeDeleter{"/attributesTransferredFromSpec"}, nil
}

func (plugin *FakeVolumePlugin) NewProvisioner(options VolumeOptions) (Provisioner, error) {
	return &FakeProvisioner{options, plugin.Host}, nil
}

func (plugin *FakeVolumePlugin) GetAccessModes() []api.PersistentVolumeAccessMode {
	return []api.PersistentVolumeAccessMode{}
}

type FakeVolume struct {
	PodUID  types.UID
	VolName string
	Plugin  *FakeVolumePlugin
}

func (_ *FakeVolume) SupportsOwnershipManagement() bool {
	return false
}

func (fv *FakeVolume) SetUp() error {
	return fv.SetUpAt(fv.GetPath())
}

func (fv *FakeVolume) SetUpAt(dir string) error {
	return os.MkdirAll(dir, 0750)
}

func (fv *FakeVolume) IsReadOnly() bool {
	return false
}

func (fv *FakeVolume) SupportsSELinux() bool {
	return false
}

func (fv *FakeVolume) GetPath() string {
	return path.Join(fv.Plugin.Host.GetPodVolumeDir(fv.PodUID, util.EscapeQualifiedNameForDisk(fv.Plugin.PluginName), fv.VolName))
}

func (fv *FakeVolume) TearDown() error {
	return fv.TearDownAt(fv.GetPath())
}

func (fv *FakeVolume) TearDownAt(dir string) error {
	return os.RemoveAll(dir)
}

type fakeRecycler struct {
	path string
}

func (fr *fakeRecycler) Recycle() error {
	// nil is success, else error
	return nil
}

func (fr *fakeRecycler) GetPath() string {
	return fr.path
}

func NewFakeRecycler(spec *Spec, host VolumeHost, config VolumeConfig) (Recycler, error) {
	if spec.PersistentVolume == nil || spec.PersistentVolume.Spec.HostPath == nil {
		return nil, fmt.Errorf("fakeRecycler only supports spec.PersistentVolume.Spec.HostPath")
	}
	return &fakeRecycler{
		path: spec.PersistentVolume.Spec.HostPath.Path,
	}, nil
}

type FakeDeleter struct {
	path string
}

func (fd *FakeDeleter) Delete() error {
	// nil is success, else error
	return nil
}

func (fd *FakeDeleter) GetPath() string {
	return fd.path
}

type FakeProvisioner struct {
	Options VolumeOptions
	Host    VolumeHost
}

func (fc *FakeProvisioner) NewPersistentVolumeTemplate() (*api.PersistentVolume, error) {
	fullpath := fmt.Sprintf("/tmp/hostpath_pv/%s", util.NewUUID())
	return &api.PersistentVolume{
		ObjectMeta: api.ObjectMeta{
			GenerateName: "pv-fakeplugin-",
			Annotations: map[string]string{
				"kubernetes.io/createdby": "fakeplugin-provisioner",
			},
		},
		Spec: api.PersistentVolumeSpec{
			PersistentVolumeReclaimPolicy: fc.Options.PersistentVolumeReclaimPolicy,
			AccessModes:                   fc.Options.AccessModes,
			Capacity: api.ResourceList{
				api.ResourceName(api.ResourceStorage): fc.Options.Capacity,
			},
			PersistentVolumeSource: api.PersistentVolumeSource{
				HostPath: &api.HostPathVolumeSource{
					Path: fullpath,
				},
			},
		},
	}, nil
}

func (fc *FakeProvisioner) Provision(pv *api.PersistentVolume) error {
	return nil
}


text:
import React from 'react';
import {shallow} from 'enzyme';
import {VideoPreview} from '../VideoPreview';

describe('VideoPreview', () => {
  test('renders', () => {
    const wrapper = shallow(<VideoPreview/>);
    expect(wrapper).toMatchSnapshot();
  });
});


text:
class WXDLLIMPEXP_CORE wxToggleButton: public wxToggleButtonBase
{
public:
    wxToggleButton();

    wxToggleButton(wxWindow *parent,
             wxWindowID id,
             const wxString& label = wxEmptyString,
             const wxPoint& pos = wxDefaultPosition,
             const wxSize& size = wxDefaultSize,
             long style = 0,
             const wxValidator& validator = wxDefaultValidator,
             const wxString& name = wxASCII_STR(wxCheckBoxNameStr));

    // Create the control
    bool Create(wxWindow *parent,
                wxWindowID id,
                const wxString& lbl = wxEmptyString,
                const wxPoint& pos = wxDefaultPosition,
                const wxSize& size = wxDefaultSize,
                long style = 0,
                const wxValidator& validator = wxDefaultValidator,
                const wxString& name = wxASCII_STR(wxCheckBoxNameStr));

    virtual bool IsPressed() const wxOVERRIDE { return m_isPressed || m_value; }

    // wxToggleButton actions
    virtual void Toggle() wxOVERRIDE;
    virtual void Click() wxOVERRIDE;

    // Get/set the value
    void SetValue(bool state);
    bool GetValue() const { return m_value; }

protected:
    virtual wxBorder GetDefaultBorder() const wxOVERRIDE { return wxBORDER_NONE; }

    // the current value
    bool m_value;

private:
    // common part of all ctors
    void Init();

    wxDECLARE_DYNAMIC_CLASS(wxToggleButton);
};

#endif // _WX_UNIV_TGLBTN_H_


text:
@implementation CMMotionManager (Shared)

+ (CMMotionManager *)sharedMotionManager
{
    static CMMotionManager *manager = nil;
    if (!manager)
    {
        // make sure we only create one, thread safe
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            manager = [[CMMotionManager alloc] init];
        });
    }
    return manager;
}

@end


text:
PLEASE NOTE: This document applies to the HEAD of the source tree

If you are using a released version of Kubernetes, you should
refer to the docs that go with that version.

The latest release of this document can be found
[here](http://releases.k8s.io/release-1.3/docs/proposals/container-init.md).

Documentation for other releases can be found at
[releases.k8s.io](http://releases.k8s.io).

--

# Pod initialization

@smarterclayton

March 2016

## Proposal and Motivation

Within a pod there is a need to initialize local data or adapt to the current
cluster environment that is not easily achieved in the current container model.
Containers start in parallel after volumes are mounted, leaving no opportunity
for coordination between containers without specialization of the image. If
two containers need to share common initialization data, both images must
be altered to cooperate using filesystem or network semantics, which introduces
coupling between images. Likewise, if an image requires configuration in order
to start and that configuration is environment dependent, the image must be
altered to add the necessary templating or retrieval.

This proposal introduces the concept of an **init container**, one or more
containers started in sequence before the pod's normal containers are started.
These init containers may share volumes, perform network operations, and perform
computation prior to the start of the remaining containers. They may also, by
virtue of their sequencing, block or delay the startup of application containers
until some precondition is met. In this document we refer to the existing pod
containers as **app containers**.

This proposal also provides a high level design of **volume containers**, which
initialize a particular volume, as a feature that specializes some of the tasks
defined for init containers. The init container design anticipates the existence
of volume containers and highlights where they will take future work

## Design Points

* Init containers should be able to:
  * Perform initialization of shared volumes
    * Download binaries that will be used in app containers as execution targets
    * Inject configuration or extension capability to generic images at startup
    * Perform complex templating of information available in the local environment
    * Initialize a database by starting a temporary execution process and applying
      schema info.
  * Delay the startup of application containers until preconditions are met
  * Register the pod with other components of the system
* Reduce coupling:
  * Between application images, eliminating the need to customize those images for
    Kubernetes generally or specific roles
  * Inside of images, by specializing which containers perform which tasks
    (install git into init container, use filesystem contents
    in web container)
  * Between initialization steps, by supporting multiple sequential init containers
* Init containers allow simple start preconditions to be implemented that are
  decoupled from application code
  * The order init containers start should be predictable and allow users to easily
    reason about the startup of a container
  * Complex ordering and failure will not be supported - all complex workflows can
    if necessary be implemented inside of a single init container, and this proposal
    aims to enable that ordering without adding undue complexity to the system.
    Pods in general are not intended to support DAG workflows.
* Both run-once and run-forever pods should be able to use init containers
* As much as possible, an init container should behave like an app container
  to reduce complexity for end users, for clients, and for divergent use cases.
  An init container is a container with the minimum alterations to accomplish
  its goal.
* Volume containers should be able to:
  * Perform initialization of a single volume
  * Start in parallel
  * Perform computation to initialize a volume, and delay start until that
    volume is initialized successfully.
  * Using a volume container that does not populate a volume to delay pod start
    (in the absence of init containers) would be an abuse of the goal of volume
    containers.
* Container pre-start hooks are not sufficient for all initialization cases:
  * They cannot easily coordinate complex conditions across containers
  * They can only function with code in the image or code in a shared volume,
    which would have to be statically linked (not a common pattern in wide use)
  * They cannot be implemented with the current Docker implementation - see
    [#140](https://github.com/kubernetes/kubernetes/issues/140)

## Alternatives

* Any mechanism that runs user code on a node before regular pod containers
  should itself be a container and modeled as such - we explicitly reject
  creating new mechanisms for running user processes.
* The container pre-start hook (not yet implemented) requires execution within
  the container's image and so cannot adapt existing images. It also cannot
  block startup of containers
* Running a "pre-pod" would defeat the purpose of the pod being an atomic
  unit of scheduling.

## Design

Each pod may have 0..N init containers defined along with the existing
1..M app containers.

On startup of the pod, after the network and volumes are initialized, the
init containers are started in order. Each container must exit successfully
before the next is invoked. If a container fails to start (due to the runtime)
or exits with failure, it is retried according to the pod RestartPolicy.
RestartPolicyNever pods will immediately fail and exit. RestartPolicyAlways
pods will retry the failing init container with increasing backoff until it
succeeds. To align with the design of application containers, init containers
will only support "infinite retries" (RestartPolicyAlways) or "no retries"
(RestartPolicyNever).

A pod cannot be ready until all init containers have succeeded. The ports
on an init container are not aggregated under a service. A pod that is
being initialized is in the `Pending` phase but should have a distinct
condition. Each app container and all future init containers should have
the reason `PodInitializing`. The pod should have a condition `Initializing`
set to `false` until all init containers have succeeded, and `true` thereafter.
If the pod is restarted, the `Initializing` condition should be set to `false.

If the pod is "restarted" all containers stopped and started due to
a node restart, change to the pod definition, or admin interaction, all
init containers must execute again. Restartable conditions are defined as:

* An init container image is changed
* The pod infrastructure container is restarted (shared namespaces are lost)
* The Kubelet detects that all containers in a pod are terminated AND
  no record of init container completion is available on disk (due to GC)

Changes to the init container spec are limited to the container image field.
Altering the container image field is equivalent to restarting the pod.

Because init containers can be restarted, retried, or reexecuted, container
authors should make their init behavior idempotent by handling volumes that
are already populated or the possibility that this instance of the pod has
already contacted a remote system.

Each init container has all of the fields of an app container. The following
fields are prohibited from being used on init containers by validation:

* `readinessProbe` - init containers must exit for pod startup to continue,
  are not included in rotation, and so cannot define readiness distinct from
  completion.

Init container authors may use `activeDeadlineSeconds` on the pod and
`livenessProbe` on the container to prevent init containers from failing
forever. The active deadline includes init containers.

Because init containers are semantically different in lifecycle from app
containers (they are run serially, rather than in parallel), for backwards
compatibility and design clarity they will be identified as distinct fields
in the API:

    pod:
      spec:
        containers: ...
        initContainers:
        - name: init-container1
          image: ...
          ...
        - name: init-container2
        ...
      status:
        containerStatuses: ...
        initContainerStatuses:
        - name: init-container1
          ...
        - name: init-container2
          ...

This separation also serves to make the order of container initialization
clear - init containers are executed in the order that they appear, then all
app containers are started at once.

The name of each app and init container in a pod must be unique - it is a
validation error for any container to share a name.

While pod containers are in alpha state, they will be serialized as an annotation
on the pod with the name `pod.alpha.kubernetes.io/init-containers` and the status
of the containers will be stored as `pod.alpha.kubernetes.io/init-container-statuses`.
Mutation of these annotations is prohibited on existing pods.

### Resources

Given the ordering and execution for init containers, the following rules
for resource usage apply:

* The highest of any particular resource request or limit defined on all init
  containers is the **effective init request/limit**
* The pod's **effective request/limit** for a resource is the higher of:
  * sum of all app containers request/limit for a resource
  * effective init request/limit for a resource
* Scheduling is done based on effective requests/limits, which means
  init containers can reserve resources for initialization that are not used
  during the life of the pod.
* The lowest QoS tier of init containers per resource is the **effective init QoS tier**,
  and the highest QoS tier of both init containers and regular containers is the
  **effective pod QoS tier**.

So the following pod:

    pod:
      spec:
        initContainers:
        - limits:
            cpu: 100m
            memory: 1GiB
        - limits:
            cpu: 50m
            memory: 2GiB
        containers:
        - limits:
            cpu: 10m
            memory: 1100MiB
        - limits:
            cpu: 10m
            memory: 1100MiB

has an effective pod limit of `cpu: 100m`, `memory: 2200MiB` (highest init
container cpu is larger than sum of all app containers, sum of container
memory is larger than the max of all init containers). The scheduler, node,
and quota must respect the effective pod request/limit.

In the absence of a defined request or limit on a container, the effective
request/limit will be applied. For example, the following pod:

    pod:
      spec:
        initContainers:
        - limits:
            cpu: 100m
            memory: 1GiB
        containers:
        - request:
            cpu: 10m
            memory: 1100MiB

will have an effective request of `10m / 1100MiB`, and an effective limit
of `100m / 1GiB`, i.e.:

    pod:
      spec:
        initContainers:
        - request:
            cpu: 10m
            memory: 1GiB
        - limits:
            cpu: 100m
            memory: 1100MiB
        containers:
        - request:
            cpu: 10m
            memory: 1GiB
        - limits:
            cpu: 100m
            memory: 1100MiB

and thus have the QoS tier **Burstable** (because request is not equal to
limit).

Quota and limits will be applied based on the effective pod request and
limit.

Pod level cGroups will be based on the effective pod request and limit, the
same as the scheduler.

### Kubelet and container runtime details

Container runtimes should treat the set of init and app containers as one
large pool. An individual init container execution should be identical to
an app container, including all standard container environment setup
(network, namespaces, hostnames, DNS, etc).

All app container operations are permitted on init containers. The
logs for an init container should be available for the duration of the pod
lifetime or until the pod is restarted.

During initialization, app container status should be shown with the reason
PodInitializing if any init containers are present. Each init container
should show appropriate container status, and all init containers that are
waiting for earlier init containers to finish should have the `reason`
PendingInitialization.

The container runtime should aggressively prune failed init containers.
The container runtime should record whether all init containers have
succeeded internally, and only invoke new init containers if a pod
restart is needed (for Docker, if all containers terminate or if the pod
infra container terminates). Init containers should follow backoff rules
as necessary. The Kubelet *must* preserve at least the most recent instance
of an init container to serve logs and data for end users and to track
failure states. The Kubelet *should* prefer to garbage collect completed
init containers over app containers, as long as the Kubelet is able to
track that initialization has been completed. In the future, container
state checkpointing in the Kubelet may remove or reduce the need to
preserve old init containers.

For the initial implementation, the Kubelet will use the last termination
container state of the highest indexed init container to determine whether
the pod has completed initialization. During a pod restart, initialization
will be restarted from the beginning (all initializers will be rerun).

### API Behavior

All APIs that access containers by name should operate on both init and
app containers. Because names are unique the addition of the init container
should be transparent to use cases.

A client with no knowledge of init containers should see appropriate
container status `reason` and `message` fields while the pod is in the
`Pending` phase, and so be able to communicate that to end users.

### Example init containers

* Wait for a service to be created

        pod:
          spec:
            initContainers:
            - name: wait
              image: centos:centos7
              command: ["/bin/sh", "-c", "for i in {1..100}; do sleep 1; if dig myservice; then exit 0; fi; exit 1"]
            containers:
            - name: run
              image: application-image
              command: ["/my_application_that_depends_on_myservice"]

* Register this pod with a remote server

        pod:
          spec:
            initContainers:
            - name: register
              image: centos:centos7
              command: ["/bin/sh", "-c", "curl -X POST http://$MANAGEMENT_SERVICE_HOST:$MANAGEMENT_SERVICE_PORT/register -d 'instance=$(POD_NAME)&ip=$(POD_IP)'"]
              env:
              - name: POD_NAME
                valueFrom:
                  field: metadata.name
              - name: POD_IP
                valueFrom:
                  field: status.podIP
            containers:
            - name: run
              image: application-image
              command: ["/my_application_that_depends_on_myservice"]

* Wait for an arbitrary period of time

        pod:
          spec:
            initContainers:
            - name: wait
              image: centos:centos7
              command: ["/bin/sh", "-c", "sleep 60"]
            containers:
            - name: run
              image: application-image
              command: ["/static_binary_without_sleep"]

* Clone a git repository into a volume (can be implemented by volume containers in the future):

        pod:
          spec:
            initContainers:
            - name: download
              image: image-with-git
              command: ["git", "clone", "https://github.com/myrepo/myrepo.git", "/var/lib/data"]
              volumeMounts:
              - mountPath: /var/lib/data
                volumeName: git
            containers:
            - name: run
              image: centos:centos7
              command: ["/var/lib/data/binary"]
              volumeMounts:
              - mountPath: /var/lib/data
                volumeName: git
            volumes:
            - emptyDir: {}
              name: git

* Execute a template transformation based on environment (can be implemented by volume containers in the future):

        pod:
          spec:
            initContainers:
            - name: copy
              image: application-image
              command: ["/bin/cp", "mytemplate.j2", "/var/lib/data/"]
              volumeMounts:
              - mountPath: /var/lib/data
                volumeName: data
            - name: transform
              image: image-with-jinja
              command: ["/bin/sh", "-c", "jinja /var/lib/data/mytemplate.j2 > /var/lib/data/mytemplate.conf"]
              volumeMounts:
              - mountPath: /var/lib/data
                volumeName: data
            containers:
            - name: run
              image: application-image
              command: ["/myapplication", "-conf", "/var/lib/data/mytemplate.conf"]
              volumeMounts:
              - mountPath: /var/lib/data
                volumeName: data
            volumes:
            - emptyDir: {}
              name: data

* Perform a container build

        pod:
          spec:
            initContainers:
            - name: copy
              image: base-image
              workingDir: /home/user/source-tree
              command: ["make"]
            containers:
            - name: commit
              image: image-with-docker
              command:
              - /bin/sh
              - -c
              - docker commit $(complex_bash_to_get_container_id_of_copy) \
                docker push $(commit_id) myrepo:latest
              volumesMounts:
              - mountPath: /var/run/docker.sock
                volumeName: dockersocket

## Backwards compatibilty implications

Since this is a net new feature in the API and Kubelet, new API servers during upgrade may not
be able to rely on Kubelets implementing init containers. The management of feature skew between
master and Kubelet is tracked in issue [#4855](https://github.com/kubernetes/kubernetes/issues/4855).

## Future work

* Unify pod QoS class with init containers
* Implement container / image volumes to make composition of runtime from images efficient

[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/proposals/container-init.md?pixel)]()


text:
package xisbigdata.adapter;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Emf2EaXMIAdapter {

	public static void main(String[] args) {
		try {
			if (args.length < 2) {
				System.out.println("Arguments not valid : { EMF_model_path, EA_Result_model_path}.");
			} else {
				InputStream f = Emf2EaXMIAdapter.class.getResourceAsStream("Template.xml");
				DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
				Document docEA = builder.parse(f);
				Element xmiElement = docEA.getDocumentElement();
				xmiElement.normalize();

				NodeList model = docEA.getElementsByTagName("xmi:XMI");

				if (model.getLength() == 1) {
					Element xmi = (Element) model.item(0);
					addUMLContent(builder, docEA, xmi, args[0]);

					if (model.getLength() == 2) {
						xmi = (Element) model.item(1);
						NodeList childNodes = xmi.getChildNodes();

						for (int i = 0; i < childNodes.getLength(); i++) {
							xmi.getParentNode().insertBefore(childNodes.item(i).cloneNode(true), null);
						}
						xmi.getParentNode().removeChild(xmi);

						//Relocate Associations
						XPath path = XPathFactory.newInstance().newXPath();
						XPathExpression expr = path.compile("/*/*/packagedElement[@*[name()='xmi:type']='uml:Package']");
						Element umlPackage = (Element)((NodeList) expr.evaluate(docEA, XPathConstants.NODESET)).item(0);
						expr = path.compile("/*/*/packagedElement[@*[name()='xmi:type']='uml:Association']");
						NodeList associations = (NodeList) expr.evaluate(docEA, XPathConstants.NODESET);
						java.util.ArrayList<Element> assocs = new java.util.ArrayList<Element>();

						for (int i = 0; i < associations.getLength(); i++) {
							Element assoc = (Element) associations.item(i);
							assocs.add(assoc);
						}

						Element connectorTemplate = (Element) docEA.getElementsByTagName("connector").item(0);

						for (Element ass : assocs) {
							//Add Missing Attributes
							ass.setAttribute("visibility", "public");
							ass.removeAttribute("memberEnd");
							umlPackage.insertBefore(ass, null);

							NodeList ownedEnds = ass.getElementsByTagName("ownedEnd");
							//MemberEnd #1
							Element memberEnd = docEA.createElement("memberEnd");
							String value = ((Element)ownedEnds.item(0)).getAttribute("xmi:id");
							memberEnd.setAttribute("xmi:idref", value);
							ass.insertBefore(memberEnd, null);

							String type = ((Element)ownedEnds.item(0)).getAttribute("type");
							Element typeTag = docEA.createElement("type");
							typeTag.setAttribute("xmi:idref", type);
							((Element)ownedEnds.item(0)).appendChild(typeTag);

							//MemberEnd #2
							Element memberEnd2 = docEA.createElement("memberEnd");
							value = ((Element)ownedEnds.item(1)).getAttribute("xmi:id");
							memberEnd2.setAttribute("xmi:idref", value);
							ass.insertBefore(memberEnd2, null);

							type = ((Element)ownedEnds.item(1)).getAttribute("type");
							typeTag = docEA.createElement("type");
							typeTag.setAttribute("xmi:idref", type);
							((Element)ownedEnds.item(1)).appendChild(typeTag);

							//Extensions/Connectors/Connector
							Element connectorExt = (Element) connectorTemplate.cloneNode(true);
							connectorExt.setAttribute("xmi:idref", ass.getAttribute("xmi:id"));
							//Connector/Source
							Element sourceOwnedEnd = ((Element)ownedEnds.item(1));
							Element targetOwnedEnd = ((Element)ownedEnds.item(0));
							Element source = (Element) connectorExt.getElementsByTagName("source").item(0);
							source.setAttribute("xmi:idref", memberEnd.getAttribute("xmi:idref"));
							Element sourceModel = (Element) source.getElementsByTagName("model").item(0);
							String sourceName = sourceOwnedEnd.getAttribute("name");
							sourceModel.setAttribute("name", sourceName.substring(0, 1).toUpperCase() + sourceName.substring(1));
							Element sourceRole = (Element) source.getElementsByTagName("role").item(0);
							sourceRole.setAttribute("name", sourceName);
							Element sourceType = (Element) source.getElementsByTagName("type").item(0);
							String sourceLMult = ((Element)sourceOwnedEnd.getElementsByTagName("lowerValue").item(0)).getAttribute("value");
							String sourceUMult = ((Element)sourceOwnedEnd.getElementsByTagName("upperValue").item(0)).getAttribute("value");
							sourceType.setAttribute("multiplicity", sourceLMult + ".." + sourceUMult);
							String sourceAggregation = targetOwnedEnd.getAttribute("aggregation");

							if (sourceAggregation.isEmpty()) {
								sourceType.removeAttribute("aggregation");
							} else {
								sourceType.setAttribute("aggregation", sourceAggregation);
							}
							//Connector/Target
							Element target = (Element) connectorExt.getElementsByTagName("target").item(0);
							target.setAttribute("xmi:idref", memberEnd2.getAttribute("xmi:idref"));
							Element targetModel = (Element) target.getElementsByTagName("model").item(0);
							String targetName = targetOwnedEnd.getAttribute("name");
							targetModel.setAttribute("name", targetName.substring(0, 1).toUpperCase() + targetName.substring(1));
							Element targetRole = (Element) target.getElementsByTagName("role").item(0);
							targetRole.setAttribute("name", targetName);
							Element targetType = (Element) target.getElementsByTagName("type").item(0);
							String targetLMult = ((Element)targetOwnedEnd.getElementsByTagName("lowerValue").item(0)).getAttribute("value");
							String targetUMult = ((Element)targetOwnedEnd.getElementsByTagName("upperValue").item(0)).getAttribute("value");
							targetType.setAttribute("multiplicity", targetLMult + ".." + targetUMult);
							String targetAggregation = sourceOwnedEnd.getAttribute("aggregation");

							if (targetAggregation.isEmpty()) {
								targetType.removeAttribute("aggregation");
							} else {
								targetType.setAttribute("aggregation", targetAggregation);
							}
							//Connector/xrefs
							Element xrefs = (Element) connectorExt.getElementsByTagName("xrefs").item(2);
							String xrefsValue = "$XREFPROP=$XID={"+ UUID.randomUUID() + "}$XID;$NAM=Stereotypes$NAM;$TYP=connector property$TYP;$VIS=Public$VIS;$PAR=0$PAR;$DES=@STEREO;Name=XisEntityAssociation;FQName=XIS-Mobile::XisEntityAssociation;@ENDSTEREO;$DES;$CLT={" + ass.getAttribute("xmi:id")  + "}$CLT;$SUP=<none>$SUP;$ENDXREF;";
							xrefs.setAttribute("value", xrefsValue);
							//Connector/tags
							Element tags = (Element) connectorExt.getElementsByTagName("tags").item(2);
							Element tag = (Element) tags.getElementsByTagName("tag").item(0);
							tag.setAttribute("xmi:id", UUID.randomUUID().toString().replace("-", "_"));
							tag.setAttribute("value", ass.getAttribute("name"));
							connectorTemplate.getParentNode().appendChild(connectorExt);
						}

						//Remove Connector Template
						connectorTemplate.getParentNode().removeChild(connectorTemplate);

						//Set Diagram Properties
						Element diagram = (Element) docEA.getElementsByTagName("diagram").item(0);
						diagram.setAttribute("xmi:id", UUID.randomUUID().toString().replace("-", "_"));
						//diagram/model
						Element diagModel = (Element) diagram.getElementsByTagName("model").item(0);
						diagModel.setAttribute("owner", umlPackage.getAttribute("xmi:id"));
						diagModel.setAttribute("package", umlPackage.getAttribute("xmi:id"));
						//diagram/project
						Element diagProject = (Element) diagram.getElementsByTagName("project").item(0);
						String dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
						diagProject.setAttribute("created", dateTime);
						diagProject.setAttribute("modified", dateTime);

						//Set Elements
						Element elementTemplate = (Element) docEA.getElementsByTagName("element").item(0);
						Element elementExt = (Element) elementTemplate.cloneNode(true);
						elementExt.setAttribute("xmi:idref", umlPackage.getAttribute("xmi:id"));
						elementExt.setAttribute("xmi:type", umlPackage.getAttribute("xmi:type"));
						elementExt.setAttribute("name", umlPackage.getAttribute("name"));
						//Element/Model
						Element modelEl = (Element) elementExt.getElementsByTagName("model").item(0);
						modelEl.setAttribute("package", UUID.randomUUID().toString().replace("-", "_"));
						modelEl.setAttribute("package2", UUID.randomUUID().toString().replace("-", "_"));
						modelEl.setAttribute("ea_eleType", "package");
						//Element/properties
						Element propertiesEl = (Element) elementExt.getElementsByTagName("properties").item(0);
						propertiesEl.setAttribute("sType", "Package");
						propertiesEl.setAttribute("stereotype", "Domain View");
						propertiesEl.removeAttribute("isAbstract");
						propertiesEl.removeAttribute("isActive");
						propertiesEl.removeAttribute("isLeaf");
						propertiesEl.removeAttribute("isRoot");
						//Element/Tags
						Element tagsEl = (Element) elementExt.getElementsByTagName("tags").item(0);
						while (tagsEl.hasChildNodes()) {
							tagsEl.removeChild(tagsEl.getFirstChild());
						}
						//Element/xrefs
						Element xrefs = (Element) elementExt.getElementsByTagName("xrefs").item(0);
						String guid = UUID.randomUUID().toString();
						String xrefsValue = "$XREFPROP=$XID={" + UUID.randomUUID() + "}$XID;$NAM=CustomProperties$NAM;$TYP=element property$TYP;$VIS=Public$VIS;$PAR=0$PAR;$DES=@PROP=@NAME=_defaultDiagramType@ENDNAME;@TYPE=string@ENDTYPE;@VALU=XIS-Mobile_Diagrams::DomainViewModel@ENDVALU;@PRMT=@ENDPRMT;@ENDPROP;@PROP=@NAME=_makeComposite@ENDNAME;@TYPE=string@ENDTYPE;@VALU=true@ENDVALU;@PRMT=@ENDPRMT;@ENDPROP;$DES;$CLT={" + guid + "}$CLT;$ENDXREF;$XREFPROP=$XID={" + UUID.randomUUID() + "}$XID;$NAM=Stereotypes$NAM;$TYP=element property$TYP;$VIS=Public$VIS;$PAR=0$PAR;$DES=@STEREO;Name=Domain View;FQName=XIS-Mobile::Domain View;@ENDSTEREO;$DES;$CLT={" + guid + "}$CLT;$ENDXREF;";
						xrefs.setAttribute("value", xrefsValue);
						//Element/extendedProperties
						Element extendedProperties = (Element) elementExt.getElementsByTagName("extendedProperties").item(0);
						extendedProperties.setAttribute("package_name", umlPackage.getAttribute("name"));
						//Element/packageProperties
						Element packageProperties = (Element) docEA.createElement("packageProperties");
						packageProperties.setAttribute("version", "1.0");
						elementExt.insertBefore(packageProperties, null);
						//Element/paths
						Element pathsEl = (Element) docEA.createElement("paths");
						elementExt.insertBefore(pathsEl, null);
						//Element/times
						Element timesEl = (Element) docEA.createElement("times");
						timesEl.setAttribute("created", "1.0");
						timesEl.setAttribute("modified", "1.0");
						timesEl.setAttribute("lastloaddate", "1.0");
						timesEl.setAttribute("lastsavedate", "1.0");
						elementExt.insertBefore(timesEl, null);
						//Element/flags
						Element flagsEl = (Element) docEA.createElement("flags");
						flagsEl.setAttribute("iscontrolled", "FALSE");
						flagsEl.setAttribute("isprotected", "FALSE");
						flagsEl.setAttribute("batchsave", "0");
						flagsEl.setAttribute("batchload", "0");
						flagsEl.setAttribute("usedtd", "FALSE");
						flagsEl.setAttribute("logxml", "FALSE");
						elementExt.insertBefore(flagsEl, null);
						//Remove Element/attributes
						Element attributesEl = (Element) elementExt.getElementsByTagName("attributes").item(0);
						elementExt.removeChild(attributesEl);
						//Remove Element/links
						Element linksEl = (Element) elementExt.getElementsByTagName("links").item(0);
						elementExt.removeChild(linksEl);
						elementTemplate.getParentNode().insertBefore(elementExt, null);

						NodeList packageChildren = umlPackage.getChildNodes();

						for (int i = 0; i < packageChildren.getLength(); i++) {
							if (packageChildren.item(i) instanceof Element) {
								Element el = (Element) packageChildren.item(i);

								if (el.getAttribute("xmi:type").equals("uml:Class")) {
									elementExt = (Element) elementTemplate.cloneNode(true);
									elementExt.setAttribute("xmi:idref", el.getAttribute("xmi:id"));
									elementExt.setAttribute("xmi:type", el.getAttribute("xmi:type"));
									elementExt.setAttribute("name", el.getAttribute("name"));
									//Element/Model
									modelEl = (Element) elementExt.getElementsByTagName("model").item(0);
									modelEl.setAttribute("package", umlPackage.getAttribute("xmi:id"));
									//Element/Tags
									tagsEl = (Element) elementExt.getElementsByTagName("tags").item(0);
									Element tag = (Element) tagsEl.getElementsByTagName("tag").item(0);
									tag.setAttribute("xmi:id", UUID.randomUUID().toString().replace("-", "_"));
									tag.setAttribute("value", el.getAttribute("name"));
									tag.setAttribute("modelElement", el.getAttribute("xmi:id"));
									tag = (Element) tagsEl.getElementsByTagName("tag").item(1);
									tag.setAttribute("xmi:id", UUID.randomUUID().toString().replace("-", "_"));
									tag.setAttribute("modelElement", el.getAttribute("xmi:id"));
									//Element/xrefs
									xrefs = (Element) elementExt.getElementsByTagName("xrefs").item(0);
									xrefsValue = "$XREFPROP=$XID={" + UUID.randomUUID() + "}$XID;$NAM=Stereotypes$NAM;$TYP=element property$TYP;$VIS=Public$VIS;$PAR=0$PAR;$DES=@STEREO;Name=XisEntity;FQName=XIS-Mobile::XisEntity;@ENDSTEREO;$DES;$CLT={" + el.getAttribute("xmi:id") + "}$CLT;$SUP=<none>$SUP;$ENDXREF;";
									xrefs.setAttribute("value", xrefsValue);
									//Element/extendedProperties
									extendedProperties = (Element) elementExt.getElementsByTagName("extendedProperties").item(0);
									extendedProperties.setAttribute("package_name", umlPackage.getAttribute("name"));
									//Element/attributes
									NodeList attrList = el.getElementsByTagName("ownedAttribute");
									Element attributes = (Element) elementExt.getElementsByTagName("attributes").item(0);
									Element attributeTemplate = (Element) attributes.getElementsByTagName("attribute").item(0);

									for (int j = 0; j < attrList.getLength(); j++) {
										Element attr = (Element) attrList.item(j);
										Element attributeExt = (Element) attributeTemplate.cloneNode(true);
										attributeExt.setAttribute("xmi:idref", attr.getAttribute("xmi:id"));
										attributeExt.setAttribute("name", attr.getAttribute("name"));
										//attribute/model
										Element attrModel = (Element) attributeExt.getElementsByTagName("model").item(0);
										attrModel.setAttribute("ea_guid", "{" + attr.getAttribute("xmi:id") + "}");
										//attribute/properties
										Element attrProperties = (Element) attributeExt.getElementsByTagName("properties").item(0);
										attrProperties.setAttribute("type", getAttributeType(attr));
										//attribute/tags
										Element attrTags = (Element) attributeExt.getElementsByTagName("tags").item(0);
										NodeList tagsList = attrTags.getElementsByTagName("tag");
										Element attrTag = (Element) tagsList.item(0);
										//name
										attrTag.setAttribute("xmi:id", UUID.randomUUID().toString());
										attrTag.setAttribute("value", attr.getAttribute("name"));
										//value
										attrTag = (Element) tagsList.item(1);
										attrTag.setAttribute("xmi:id", UUID.randomUUID().toString());
										//type
										attrTag = (Element) tagsList.item(2);
										attrTag.setAttribute("xmi:id", UUID.randomUUID().toString());
										attrTag.setAttribute("value", getXisEntityAttributeType(attrProperties.getAttribute("type")));
										//nullable
										attrTag = (Element) tagsList.item(3);
										attrTag.setAttribute("xmi:id", UUID.randomUUID().toString());
										//isKey
										attrTag = (Element) tagsList.item(4);
										attrTag.setAttribute("xmi:id", UUID.randomUUID().toString());
										//attribute/xrefs
										Element attrXrefs = (Element) attributeExt.getElementsByTagName("xrefs").item(0);
										String attrXrefsValue = "$XREFPROP=$XID={" + UUID.randomUUID() + "}$XID;$NAM=Stereotypes$NAM;$TYP=attribute property$TYP;$VIS=Public$VIS;$PAR=0$PAR;$DES=@STEREO;Name=XisEntityAttribute;FQName=XIS-Mobile::XisEntityAttribute;@ENDSTEREO;$DES;$CLT={"+ attr.getAttribute("xmi:id") + "}$CLT;$SUP=<none>$SUP;$ENDXREF;";
										attrXrefs.setAttribute("xrefs", attrXrefsValue);
										attributeTemplate.getParentNode().appendChild(attributeExt);
									}

									//Delete Attribute Template
									attributeTemplate.getParentNode().removeChild(attributeTemplate);

									//Element/links
									linksEl = (Element) elementExt.getElementsByTagName("links").item(0);
									//TODO Properly set the links attributes
									elementTemplate.getParentNode().insertBefore(elementExt, null);
								}
							}
						}

						//Delete Element Template
						elementTemplate.getParentNode().removeChild(elementTemplate);

						//Relocate XIS-Mobile Stereotypes
						Element umlModel = (Element) docEA.getElementsByTagName("uml:Model").item(0);
						expr = path.compile("/*/*[starts-with(name(), 'XIS')]");
						NodeList stereotypes = (NodeList) expr.evaluate(docEA, XPathConstants.NODESET);

						for (int i = 0; i < stereotypes.getLength(); i++) {
							Element s = (Element) stereotypes.item(i);
							s = (Element) docEA.renameNode(s, "", s.getTagName().replace("XIS", "XIS-"));
							umlModel.insertBefore(s, null);
						}

						Element profileApplication = (Element) docEA.getElementsByTagName("profileApplication").item(0);
						profileApplication.getParentNode().removeChild(profileApplication);
					}
				}

				NodeList typesNodes = docEA.getElementsByTagName("type");

				for (int i = 0; i < typesNodes.getLength(); i++) {
					Element el = (Element) typesNodes.item(i);
					setTypeIdRef(el);
				}

				File nFile = new File(args[1]);

				Transformer transformer = TransformerFactory.newInstance().newTransformer();
				DOMSource source = new DOMSource(docEA);
				StreamResult result = new StreamResult(nFile);

				// StreamResult result2 = new StreamResult(System.out);

				transformer.setOutputProperty(OutputKeys.INDENT, "yes");
				transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
				transformer.transform(source, result);
				// transformer.transform(source, result2);
				System.out.println("Document successfully parsed!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void addUMLContent(DocumentBuilder builder,
			Document document, Element element, String modelPath) throws SAXException,
	IOException {
		InputStream f = new FileInputStream(new File(modelPath));
		//InputStream f = Emf2EaXMIAdapter.class.getResourceAsStream("result.uml");
		//InputStream f = Emf2EaXMIAdapter.class.getResourceAsStream("refugees.uml");
		Document doc = builder.parse(f);
		Element profile = doc.getDocumentElement();
		profile.normalize();
		element.appendChild(document.importNode(profile, true));
	}

	private static void setTypeIdRef(Element el) {
		String type = el.getAttribute("href");

		if (type.contains("#Boolean")) {
			el.removeAttribute("href");
			el.removeAttribute("xmi:type");
			el.setAttribute("xmi:idref", "EAJava_bool");
		} else if (type.contains("#Integer")) {
			el.removeAttribute("href");
			el.removeAttribute("xmi:type");
			el.setAttribute("xmi:idref", "EAJava_int");
		} else if (type.contains("#Real") || type.contains("#UnlimitedNatural")) {
			el.removeAttribute("href");
			el.removeAttribute("xmi:type");
			el.setAttribute("xmi:idref", "EAJava_double");
		} else if (type.contains("#String")) {
			el.removeAttribute("href");
			el.removeAttribute("xmi:type");
			el.setAttribute("xmi:idref", "EAJava_String");
		}
	}

	private static String getAttributeType(Element el) {
		String attrType = "int";
		Element typeEl = ((Element)el.getElementsByTagName("type").item(0));
		String type = typeEl.getAttribute("href");

		if (type.contains("double")) {
			attrType = "double";
		} else if (type.contains("String")) {
			attrType = "String";
		} else if (type.contains("bool")) {
			attrType = "bool";
		}
		return attrType;
	}

	private static String getXisEntityAttributeType(String type) {
		String attrType = "Integer";

		if (type.contains("double")) {
			attrType = "Double";
		} else if (type.contains("String")) {
			attrType = "String";
		} else if (type.contains("bool")) {
			attrType = "Boolean";
		}
		return attrType;
	}
}


text:
import _plotly_utils.basevalidators

class AxisValidator(_plotly_utils.basevalidators.CompoundValidator):
    def __init__(self, plotly_name="axis", parent_name="splom.dimension", **kwargs):
        super(AxisValidator, self).__init__(
            plotly_name=plotly_name,
            parent_name=parent_name,
            data_class_str=kwargs.pop("data_class_str", "Axis"),
            data_docs=kwargs.pop(
                "data_docs",
                """
            matches
                Determines whether or not the x & y axes
                generated by this dimension match. Equivalent
                to setting the `matches` axis attribute in the
                layout with the correct axis id.
            type
                Sets the axis type for this dimension's
                generated x and y axes. Note that the axis
                `type` values set in layout take precedence
                over this attribute.
""",
            ),
            **kwargs,
        )


text:
package hackerRank.Algorithms.Implementation;

import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
import java.util.TreeSet;

/*
 * Link:https://www.hackerrank.com/challenges/manasa-and-stones
 */
public class _12ManasaAndStones {

	public static void main(String ards[])
	{
		Scanner scanner=new Scanner(new InputStreamReader(System.in));
		int noOfTestCases=Integer.parseInt(scanner.nextLine());
		for (int i = 0; i < noOfTestCases; i++) {
			int n=Integer.parseInt(scanner.nextLine());
			int a=Integer.parseInt(scanner.nextLine());
			int b=Integer.parseInt(scanner.nextLine());
			if(b>a)
			{
				a=a^b;b=a^b;a=a^b;
			}
			int sum=(n-1)*a;
			TreeSet<Integer> sumset=new TreeSet<>();
			sumset.add(sum);
			for (int j = 0; j < n-1; j++) {
				sum=sum-a+b;
				sumset.add(sum);
			}
			System.out.println(Arrays.toString(sumset.toArray()).replaceAll(", ", " ").replace("[","").replace("]",""));
		}
	}
}


text:
public class Main {
    public static void main(String[] args) {
        Special special = new Special();
        special.callInner();
    }

    public static class Special {
        Blort mBlort = null;

        Special() {
            System.out.println("new Special()");
        }

        public void callInner() {
            mBlort.repaint();
        }
    }

    private class Blort {
        public void repaint() {
            System.out.println("shouldn't see this");
        }
    }

}


text:
from ....._deps import _HAS_TF_2

if _HAS_TF_2:
    # importing these causes all its imports to be registered
    from coremltools.converters.mil.frontend.tensorflow.tf_op_registry import \
        register_tf_op

    from . import ops


text:
package org.jpedal.jbig2.segment.symboldictionary;

import org.jpedal.jbig2.decoders.JBIG2StreamDecoder;
import org.jpedal.jbig2.segment.Flags;

public class SymbolDictionaryFlags extends Flags {

	public static String SD_HUFF = "SD_HUFF";
	public static String SD_REF_AGG = "SD_REF_AGG";
	public static String SD_HUFF_DH = "SD_HUFF_DH";
	public static String SD_HUFF_DW = "SD_HUFF_DW";
	public static String SD_HUFF_BM_SIZE = "SD_HUFF_BM_SIZE";
	public static String SD_HUFF_AGG_INST = "SD_HUFF_AGG_INST";
	public static String BITMAP_CC_USED = "BITMAP_CC_USED";
	public static String BITMAP_CC_RETAINED = "BITMAP_CC_RETAINED";
	public static String SD_TEMPLATE = "SD_TEMPLATE";
	public static String SD_R_TEMPLATE = "SD_R_TEMPLATE";

	public void setFlags(int flagsAsInt) {
		this.flagsAsInt = flagsAsInt;

		/** extract SD_HUFF */
		flags.put(SD_HUFF, new Integer(flagsAsInt & 1));

		/** extract SD_REF_AGG */
		flags.put(SD_REF_AGG, new Integer((flagsAsInt >> 1) & 1));

		/** extract SD_HUFF_DH */
		flags.put(SD_HUFF_DH, new Integer((flagsAsInt >> 2) & 3));

		/** extract SD_HUFF_DW */
		flags.put(SD_HUFF_DW, new Integer((flagsAsInt >> 4) & 3));

		/** extract SD_HUFF_BM_SIZE */
		flags.put(SD_HUFF_BM_SIZE, new Integer((flagsAsInt >> 6) & 1));

		/** extract SD_HUFF_AGG_INST */
		flags.put(SD_HUFF_AGG_INST, new Integer((flagsAsInt >> 7) & 1));

		/** extract BITMAP_CC_USED */
		flags.put(BITMAP_CC_USED, new Integer((flagsAsInt >> 8) & 1));

		/** extract BITMAP_CC_RETAINED */
		flags.put(BITMAP_CC_RETAINED, new Integer((flagsAsInt >> 9) & 1));

		/** extract SD_TEMPLATE */
		flags.put(SD_TEMPLATE, new Integer((flagsAsInt >> 10) & 3));

		/** extract SD_R_TEMPLATE */
		flags.put(SD_R_TEMPLATE, new Integer((flagsAsInt >> 12) & 1));

		if (JBIG2StreamDecoder.debug)
			System.out.println(flags);
	}
}


text:
import tkinter as tk

from tkinter import ttk
from PIL import Image, ImageTk
from .logic_logger import logging
from .gui_autoscrollbar import AutoScrollbar

class ImageFrame():
    """ Display an image and necessary functional for rectangle, zoom, shift, etc. """
    def __init__(self, placeholder, path, roi_size):
        """ Initialize the ImageFrame """
        self.path = path  # path to the image, should be public to remember it into INI config file
        self.__roi_size = roi_size  # obtain size of the roi
        self.__roi_tag = 'roi'
        self.__text_size = 14  # size of the text
        self.__text_tag = 'text'
        self.__font = 'Helvetica {size} normal'
        self.__font_max_size = 20  # max font size
        self.__font_min_size = 7  # min font size
        self.__imscale = 1.0  # scale for the canvas image zoom
        self.__delta = 1.3  # zoom magnitude
        self.__previous_state = 0  # previous state of the keyboard
        # Create ImageFrame in placeholder widget and make it expandable
        self.__imframe = ttk.Frame(placeholder)  # placeholder of the ImageFrame object
        self.__imframe.grid(row=0, column=0, sticky='nswe')
        self.__imframe.rowconfigure(0, weight=1)  # make grid cell expandable
        self.__imframe.columnconfigure(0, weight=1)
        # Vertical and horizontal scrollbars for canvas
        hbar = AutoScrollbar(self.__imframe, orient='horizontal')
        vbar = AutoScrollbar(self.__imframe, orient='vertical')
        hbar.grid(row=1, column=0, sticky='we')
        vbar.grid(row=0, column=1, sticky='ns')
        # Create canvas and bind it with scrollbars
        self.__canvas = tk.Canvas(self.__imframe, highlightthickness=0,
                                  xscrollcommand=hbar.set, yscrollcommand=vbar.set)
        self.__canvas.grid(row=0, column=0, sticky='nswe')
        self.__canvas.update()  # wait till canvas is created
        hbar.configure(command=self.__scroll_x)  # bind scrollbars to the canvas
        vbar.configure(command=self.__scroll_y)
        # Bind events to the Canvas
        self.__canvas.bind('<Configure>', self.__show_image)  # canvas is resized
        self.__canvas.bind('<ButtonPress-1>', self.__move_from)  # remember canvas position
        self.__canvas.bind('<B1-Motion>', self.__move_to)  # move canvas to the new position
        self.__canvas.bind('<Motion>', self.__motion)  # handle mouse motion
        self.__canvas.bind('<MouseWheel>', self.__wheel)  # zoom for Windows and MacOS, but not Linux
        self.__canvas.bind('<Button-5>', self.__wheel)  # zoom for Linux, wheel scroll down
        self.__canvas.bind('<Button-4>', self.__wheel)  # zoom for Linux, wheel scroll up
        self.__canvas.bind('<Leave>', self.__rid_focus)  # hide roi and remove focus from the canvas
        self.__canvas.bind('<Enter>', self.__set_focus)  # set focus on the canvas
        # Handle keystrokes in idle mode, because program slows down on a weak computers,
        # when too many key stroke events in the same time
        self.__canvas.bind('<Key>', lambda event: self.__canvas.after_idle(self.__keystroke, event))
        logging.info('Open image: {}'.format(self.path))
        self.__state = 'hidden'
        self.__image = Image.open(self.path)  # open image
        # Put image into container rectangle and use it to set proper coordinates to the image
        self.__container = self.__canvas.create_rectangle((0, 0, self.__image.size), width=0)
        # Set region of interest (roi) rectangle on the canvas and make it invisible
        self.__roi_rect = self.__canvas.create_rectangle((0, 0, 0, 0), width=2, outline='red',
                                                         state='hidden')
        # Set text-warning on the canvas and make it invisible
        self.__text_warning = self.__canvas.create_text(
            (0, 0), anchor='sw', fill='red', text='Too close to the edge', state='hidden',
            font=self.__font.format(size=self.__text_size), tag=self.__text_tag)
        #
        self.__w, self.__h = self.__image.size  # image width and height
        self.__min_side = min(self.__w, self.__h)  # get the smaller image side
        self.__filter = Image.ANTIALIAS  # could be: NEAREST, BILINEAR, BICUBIC and ANTIALIAS
        self.__show_image()  # show image on the canvas
        self.__canvas.event_generate('<Enter>')  # set focus on the canvas

    def __move_from(self, event):
        """ Remember previous coordinates for scrolling with the mouse """
        self.__canvas.scan_mark(event.x, event.y)

    def __move_to(self, event):
        """ Drag (move) canvas to the new position """
        self.__canvas.scan_dragto(event.x, event.y, gain=1)
        self.__show_image()  # zoom tile and show it on the canvas

    def __motion(self, event):
        """ Track mouse position over the canvas """
        x = self.__canvas.canvasx(event.x)  # get coordinates of the event on the canvas
        y = self.__canvas.canvasy(event.y)
        w = (self.__roi_size[0] * self.__imscale) / 2
        h = (self.__roi_size[1] * self.__imscale) / 2
        bbox = self.__canvas.coords(self.__container)  # get image area
        # Draw roi rectangle
        if bbox[0] + w <= x < bbox[2] - w and bbox[1] + h <= y < bbox[3] - h:
            self.__canvas.coords(self.__roi_rect, (x - w, y - h, x + w, y + h))  # relocate roi
            if self.__state == 'hidden':
                self.__state = 'normal'
                self.__canvas.itemconfigure(self.__roi_rect, state='normal')  # show roi
                self.__canvas.itemconfigure(self.__text_warning, state='hidden')  # hide warning
        else:  # otherwise show warning
            self.__canvas.coords(self.__text_warning, (x, y))  # relocate text
            if self.__state == 'normal':
                self.__state = 'hidden'
                self.__canvas.itemconfigure(self.__text_warning, state='normal')  # show warning
                self.__canvas.itemconfigure(self.__roi_rect, state='hidden')  # hide roi
        self.__get_roi()  # update roi position in the console

    def __get_roi(self):
        """ Obtain roi image rectangle and output in the console
            upper left and bottom right corners of the rectangle """
        if self.__canvas.itemcget(self.__roi_rect, 'state') == 'normal':  # roi is not hidden
            bbox1 = self.__canvas.coords(self.__container)  # get image area
            bbox2 = self.__canvas.coords(self.__roi_rect)  # get roi area
            x1 = int((bbox2[0] - bbox1[0]) / self.__imscale)  # get upper left corner (x1,y1)
            y1 = int((bbox2[1] - bbox1[1]) / self.__imscale)
            x2 = x1 + self.__roi_size[0]  # get bottom right corner (x2,y2)
            y2 = y1 + self.__roi_size[1]
            print('({x1}, {y1})\t({x2}, {y2})'.format(x1=x1, y1=y1, x2=x2, y2=y2))
            return x1, y1, x2, y2

    def __wheel(self, event):
        """ Zoom with mouse wheel """
        x = self.__canvas.canvasx(event.x)  # get coordinates of the event on the canvas
        y = self.__canvas.canvasy(event.y)
        bbox = self.__canvas.coords(self.__container)  # get image area
        if bbox[0] < x < bbox[2] and bbox[1] < y < bbox[3]: pass  # Ok! Inside the image
        else: return  # zoom only inside image area
        scale = 1.0
        # Respond to Linux (event.num) or Windows (event.delta) wheel event
        if event.num == 5 or event.delta == -120:  # scroll down
            if int(self.__min_side * self.__imscale) < 30: return  # image is less than 30 pixels
            self.__imscale /= self.__delta
            scale          /= self.__delta
        if event.num == 4 or event.delta == 120:  # scroll up
            i = min(self.__canvas.winfo_width(), self.__canvas.winfo_height())
            if i < self.__imscale: return  # 1 pixel is bigger than the visible area
            self.__imscale *= self.__delta
            scale          *= self.__delta
        self.__canvas.scale('all', x, y, scale, scale)  # rescale all objects
        # Configure font size
        size = min(self.__font_max_size, max(self.__font_min_size,
                                             int(self.__text_size * self.__imscale)))
        self.__canvas.itemconfigure(self.__text_tag, font=self.__font.format(size=size))
        self.__show_image()  # zoom image and show it on the canvas

    def __set_focus(self, event):
        """ Set focus on the canvas and handle <Alt>+<Tab> switches between windows """
        self.__canvas.focus_set()
        self.__motion(event)

    def __rid_focus(self, event=None):
        """ Hide region of interest and remove focus from the canvas """
        self.__canvas.itemconfigure(self.__text_warning, state='hidden')  # hide warning
        self.__canvas.itemconfigure(self.__roi_rect, state='hidden')  # hide roi
        self.__imframe.focus_set()  # remove focus from the canvas by setting it elsewhere

    def __keystroke(self, event):
        """ Scrolling with the keyboard.
            Independent from the language of the keyboard, CapsLock, <Ctrl>+<key>, etc. """
        if event.state - self.__previous_state == 4:  # means that the Control key is pressed
            pass  # do nothing if Control key is pressed
        else:
            self.__previous_state = event.state  # remember the last keystroke state
            # Up, Down, Left, Right keystrokes
            if event.keycode in [68, 39, 102]:  # scroll right, keys 'd' or 'Right'
                self.__scroll_x('scroll',  1, 'unit', event=event)
            elif event.keycode in [65, 37, 100]:  # scroll left, keys 'a' or 'Left'
                self.__scroll_x('scroll', -1, 'unit', event=event)
            elif event.keycode in [87, 38, 104]:  # scroll up, keys 'w' or 'Up'
                self.__scroll_y('scroll', -1, 'unit', event=event)
            elif event.keycode in [83, 40, 98]:  # scroll down, keys 's' or 'Down'
                self.__scroll_y('scroll',  1, 'unit', event=event)

    def __scroll_x(self, *args, **kwargs):
        """ Scroll canvas horizontally and redraw the image """
        self.__canvas.xview(*args)  # scroll horizontally
        self.__show_image()  # redraw the image
        if kwargs and kwargs['event']:
            self.__motion(kwargs['event'])

    def __scroll_y(self, *args, **kwargs):
        """ Scroll canvas vertically and redraw the image """
        self.__canvas.yview(*args)  # scroll vertically
        self.__show_image()  # redraw the image
        if kwargs and kwargs['event']:
            self.__motion(kwargs['event'])

    def __show_image(self, event=None):
        """ Show image on the Canvas. Implements correct image zoom almost like in Google Maps """
        box_image = self.__canvas.coords(self.__container)  # get image area
        box_canvas = (self.__canvas.canvasx(0),  # get visible area of the canvas
                      self.__canvas.canvasy(0),
                      self.__canvas.canvasx(self.__canvas.winfo_width()),
                      self.__canvas.canvasy(self.__canvas.winfo_height()))
        box_img_int = tuple(map(int, box_image))  # convert to integer or it will not work properly
        # Get scroll region box
        box_scroll = [min(box_img_int[0], box_canvas[0]), min(box_img_int[1], box_canvas[1]),
                      max(box_img_int[2], box_canvas[2]), max(box_img_int[3], box_canvas[3])]
        # Horizontal part of the image is in the visible area
        if  box_scroll[0] == box_canvas[0] and box_scroll[2] == box_canvas[2]:
            box_scroll[0]  = box_img_int[0]
            box_scroll[2]  = box_img_int[2]
        # Vertical part of the image is in the visible area
        if  box_scroll[1] == box_canvas[1] and box_scroll[3] == box_canvas[3]:
            box_scroll[1]  = box_img_int[1]
            box_scroll[3]  = box_img_int[3]
        # Convert scroll region to tuple and to integer
        self.__canvas.configure(scrollregion=tuple(map(int, box_scroll)))  # set scroll region
        x1 = max(box_canvas[0] - box_image[0], 0)  # get coordinates (x1,y1,x2,y2) of the image tile
        y1 = max(box_canvas[1] - box_image[1], 0)
        x2 = min(box_canvas[2], box_image[2]) - box_image[0]
        y2 = min(box_canvas[3], box_image[3]) - box_image[1]
        if int(x2 - x1) > 0 and int(y2 - y1) > 0:  # show image if it in the visible area
            image = self.__image.crop((int(x1 / self.__imscale), int(y1 / self.__imscale),
                                       int(x2 / self.__imscale), int(y2 / self.__imscale)))
            #
            imagetk = ImageTk.PhotoImage(image.resize((int(x2 - x1), int(y2 - y1)), self.__filter))
            imageid = self.__canvas.create_image(max(box_canvas[0], box_img_int[0]),
                                                 max(box_canvas[1], box_img_int[1]),
                                                 anchor='nw', image=imagetk)
            self.__canvas.lower(imageid)  # set image into background
            self.__canvas.imagetk = imagetk  # keep an extra reference to prevent garbage-collection

    def destroy(self):
        """ ImageFrame destructor """
        logging.info('Close image: {}'.format(self.path))
        self.__image.close()
        self.__canvas.destroy()
        self.__imframe.destroy()


text:
{% extends "templates/layout.html" %}

{% block page_title %}
  NHS Medicines alpha
{% endblock %}

{% block content %}

Paracetamol

Dosage

Paracetamol 500g tablets

How to take paracetomol tablets

The normal dose for adults, the elderly and children over 12 years of age, is one or two tablets to be swallowed with a drink of water.

The dose may be taken every 4 - 6 hours, as required. Do not exceed 8 tablets in one day.

For children between 6 and 12 years, a half to one tablet can be given up to 4 times a day. Do not exceed 4 tablets in one day. Not for use in under 6 year olds.

Do not take more frequently than every 4 hours. If symptoms persist for more
      than three days, consult your doctor.

If you forget to take Paracetamol Tablets:

If you forget to take one dose, you should never make up for the missing dose by doubling the dose next time. Instead you should simply continue with the next dose when it is due.

Do not exceed the stated dose. Immediate medical advice should be sought in the event of an overdose, even if you feel well, because of the risk of delayed, serious liver damage.

If you have any further questions on the use of this product, ask your doctor or pharmacist.

            Previous page:
            Dosage

{% endblock %}


text:
/**
 * @fileOverview Contains the third and last part of the {@link CKEDITOR} object
 *		definition.
 */

// Remove the CKEDITOR.loadFullCore reference defined on ckeditor_basic.
delete CKEDITOR.loadFullCore;

/**
 * Holds references to all editor instances created. The name of the properties
 * in this object correspond to instance names, and their values contains the
 * {@link CKEDITOR.editor} object representing them.
 * @type {Object}
 * @example
 * alert( CKEDITOR.instances.editor1.name );  // "editor1"
 */
CKEDITOR.instances = {};

/**
 * The document of the window holding the CKEDITOR object.
 * @type {CKEDITOR.dom.document}
 * @example
 * alert( CKEDITOR.document.getBody().getName() );  // "body"
 */
CKEDITOR.document = new CKEDITOR.dom.document( document );

/**
 * Adds an editor instance to the global {@link CKEDITOR} object. This function
 * is available for internal use mainly.
 * @param {CKEDITOR.editor} editor The editor instance to be added.
 * @example
 */
CKEDITOR.add = function( editor )
{
	CKEDITOR.instances[ editor.name ] = editor;

	editor.on( 'focus', function()
		{
			if ( CKEDITOR.currentInstance != editor )
			{
				CKEDITOR.currentInstance = editor;
				CKEDITOR.fire( 'currentInstance' );
			}
		});

	editor.on( 'blur', function()
		{
			if ( CKEDITOR.currentInstance == editor )
			{
				CKEDITOR.currentInstance = null;
				CKEDITOR.fire( 'currentInstance' );
			}
		});
};

/**
 * Removes and editor instance from the global {@link CKEDITOR} object. his function
 * is available for internal use mainly.
 * @param {CKEDITOR.editor} editor The editor instance to be added.
 * @example
 */
CKEDITOR.remove = function( editor )
{
	delete CKEDITOR.instances[ editor.name ];
};

// Load the bootstrap script.
CKEDITOR.loader.load( 'core/_bootstrap' );		// @Packager.RemoveLine

// Tri-state constants.

/**
 * Used to indicate the ON or ACTIVE state.
 * @constant
 * @example
 */
CKEDITOR.TRISTATE_ON = 1;

/**
 * Used to indicate the OFF or NON ACTIVE state.
 * @constant
 * @example
 */
CKEDITOR.TRISTATE_OFF = 2;

/**
 * Used to indicate DISABLED state.
 * @constant
 * @example
 */
CKEDITOR.TRISTATE_DISABLED = 0;


text: .. cmake-module:: ../../Modules/CPackWIX.cmake


text:
package com.falkirks.elevens;

/**
 * This is a class that tests the Deck class.
 */
public class DeckTester {

	/**
	 * The main method in this class checks the Deck operations for consistency.
	 *	@param args is not used.
	 */
	public static void main(String[] args) {
		Deck deck = new Deck(
				new String[]{"ten", "nine", "eigth", "two"},
				new String[]{"diamonds", "clubs", "spades", "spades"},
				new int[]{10, 9, 8, 2}
		);
		System.out.println(deck.toString());
		deck.shuffle();
		System.out.println(deck.toString());

	}
}


text:
//
//  KCTMSFactory+NSingle.h
//  KCHttpNetworkDemo
//  这里只负责编写 小霸王项目的单个对象请求
//  Created by jinlb on 2016/11/15.
//  Copyright © 2016年 jinlb. All rights reserved.
//

#import "KCTMSFactory.h"

@interface KCTMSFactory (NSingle)

/**
 单个JsonModel对象请求
 @param urlStr URL
 @param requestValue 请求对象,注意必须实现
 @param success 成功
 @param error 失败
 */
+(void)postNTMSWithURL:(NSString*)urlStr
                value:(JSONModel*)requestValue
              success:(KCTMSSuccessBlock )success
                 fail:(KCTMSErrorBlock )error;

/**
 以对象形式传入

 @param urlStr URL
 @param key serviceKey
 @param requestValue 请求字典对象@{}
 @param responseClass 返回的对象实例
 @param success 成功
 @param error 失败
 */
+(void)postNTMSWithURL:(NSString*)urlStr
                   key:(NSString*)key
         requestValue:(NSDictionary*)requestValue
         responseClass:(NSString*)responseClass
               success:(KCTMSSuccessBlock )success
                  fail:(KCTMSErrorBlock )error;

/**
 没有参数传入
 @param urlStr URL
 @param key serviceKey
 @param responseClass 返回的对象实例
 @param success 成功
 @param error 失败
 */
+(void)postNTMSWithURL:(NSString*)urlStr
                   key:(NSString*)key
         responseClass:(NSString*)responseClass
               success:(KCTMSSuccessBlock )success
                  fail:(KCTMSErrorBlock )error;

/**
 小霸王项目单个对象万能请求

 @param urlStr URL
 @param value 请求value 对象为: JsonModel{包含key} 、@{key:@{}}、key
 @param responseClass 返回对象
 @param success 成功
 @param error 失败
 */
+(void)postNTMSWithURL:(NSString*)urlStr
                 value:(id)value
          reponseClass:(NSString*)responseClass
               success:(KCTMSSuccessBlock )success
                  fail:(KCTMSErrorBlock )error;

/**
 上传图片
 @param success 成功
 @param error 失败
 */
+(void)postNTMSUploadImageWithURL:(NSString *)url
                        imageName:(NSString *)imageName
                         photoImg:(UIImage *)photoImg
                     reponseClass:(NSString*)responseClass
                          success:(KCTMSSuccessBlock )success
                             fail:(KCTMSErrorBlock )error;

/**
 删除图片
 @param success 成功
 @param error 失败
 */
+(void)postNTMSDeleteUploadImageWithURL:(NSString *)url
                               filePath:(NSString *)filePath
                           reponseClass:(NSString*)responseClass
                                success:(KCTMSSuccessBlock )success
                                   fail:(KCTMSErrorBlock )error;

@end


text:
#include <string>
#include <utility>

#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/tools/graph_transforms/transform_utils.h"

namespace tensorflow {
namespace graph_transforms {

// Declare here, so we don't need a public header.
Status RenameNode(const GraphDef& input_graph_def,
                  const TransformFuncContext& context,
                  GraphDef* output_graph_def);

TEST(RenameNodeTest, Rename) {
  GraphDef in_graph;
  NodeDef* node = in_graph.add_node();
  node->set_name("input");
  node->set_op("Placeholder");

  NodeDef* node_splitter = in_graph.add_node();
  node_splitter->set_name("splitter");
  node_splitter->set_op("Split");

  NodeDef* node_adder = in_graph.add_node();
  node_adder->set_op("Add");
  node_adder->set_name("adder");
  node_adder->add_input("splitter");
  node_adder->add_input("splitter:1");

  GraphDef result;
  TransformFuncContext context;
  context.input_names = {};
  context.output_names = {"adder"};
  context.params.insert(std::pair<string, std::vector<string>>(
      {"old_node_name", {std::string("splitter")}}));
  context.params.insert(std::pair<string, std::vector<string>>(
      {"new_node_name", {string("demux")}}));
  TF_ASSERT_OK(RenameNode(in_graph, context, &result));

  std::map<string, const NodeDef*> node_lookup;
  MapNamesToNodes(result, &node_lookup);
  EXPECT_EQ(1, node_lookup.count("demux"));
  EXPECT_EQ(1, node_lookup.count("adder"));
  EXPECT_EQ(2, node_lookup["adder"]->input().size());
  EXPECT_EQ("demux", node_lookup["adder"]->input()[0]);
  EXPECT_EQ("demux:1", node_lookup["adder"]->input()[1]);
}

TEST(RenameNodeTest, FailWhenNameAlreadyExists) {
  GraphDef in_graph;
  NodeDef* node = in_graph.add_node();
  node->set_name("input");
  node->set_op("Placeholder");

  NodeDef* node_splitter = in_graph.add_node();
  node_splitter->set_name("splitter");
  node_splitter->set_op("Split");

  NodeDef* node_adder = in_graph.add_node();
  node_adder->set_op("Add");
  node_adder->set_name("adder");
  node_adder->add_input("splitter");
  node_adder->add_input("splitter:1");

  GraphDef result;
  TransformFuncContext context;
  context.input_names = {};
  context.output_names = {"adder"};
  context.params.insert(std::pair<string, std::vector<string>>(
      {"old_node_name", {std::string("splitter")}}));
  context.params.insert(std::pair<string, std::vector<string>>(
      {"new_node_name", {string("adder")}}));
  EXPECT_FALSE(RenameNode(in_graph, context, &result).ok());
}

}  // namespace graph_transforms
}  // namespace tensorflow


text:
<mat-input-container floatPlaceholder="${4:auto|always|never}">
    <textarea matInput formControlName="${1:formControlName}" ${3:required}
              placeholder="$2"></textarea>
</mat-input-container>$END$


text:
$("#accordion").accordion({ header: "h3", active: 0, collapsible: true, autoHeight: false, icons:{header:"sc-arrow-r",headerSelected:"sc-arrow-d"} });

// Link Sortable
$('ol.sortable').nestedSortable({
	disableNesting: 'no-nest',
	forcePlaceholderSize: true,
	handle: 'div',
	helper:	'clone',
	items: 'li',
	opacity: .6,
	placeholder: 'placeholder',
	revert: 250,
	tabSize: 25,
	tolerance: 'pointer',
	toleranceElement: '> div',
	stop:function(){
		post = {};
		post.order = $('ol.sortable').nestedSortable("toHierarchy");
		post.group = $(this).parent('div').attr('id');
		$.post(SITEURL+ADMIN+'/navigation/order',post);
	}
});

//Link Type Change Event
$('#type_selected').on('change', function(){

	var box = $(this).val(),
		showBox = $('#' + box);
	$('.nav-type-wrap').hide();

	$(showBox).fadeIn(700);

});

// Add new link box open @ close
$('#option-control > a').on('click', function(){
	$('#option-control').toggleClass('selected');
	var oOrc = $('#option-control').hasClass('selected');
	if(oOrc) {
		$('.r-container').slideDown(700);
	} else {
		$('.r-container').slideUp(700);
	}
});

// Nav Link Edit Function
$('.link-edit').colorbox({
	width:"50%",
	height:"80%",
	title: "Navigation Link Edit",
	onComplete:function(){
		$.colorbox.resize();

		//Link Type Change Event in Edit
		$('#type_select_edit').on('change', function(){

			var boxe = $(this).val();

			$('.nav-type-wrap-e').hide();

			$('#' + boxe + 'e').fadeIn(700);

		});

		$('#edit-link-btn').click(function(e) {
			e.preventDefault();
			var form = $('#link-edit-form');
			$.ajax({
				url: $(form).attr('action'),
				type: 'POST',
				data:$(form).serialize(),
				success: function(result){
					if(result.status == 'success') {
						$('#message-wrap').removeClass('success fail error');
						$('#message-wrap').addClass('success');
						$('#message-wrap').html(result.message);
					} else if(result.status == 'fail') {
						$('#message-wrap').removeClass('success fail error');
						$('#message-wrap').addClass('fail');
						$('#message-wrap').html(result.message);
					} else {
						$('#message-wrap').removeClass('success fail error');
						$('#message-wrap').addClass('error');
						$('#message-wrap').html(result.message);
					}

					$.colorbox.resize();

					if (result.status == 'success') {
						$.colorbox.close();
					};
				}
			});

			return false;
		});
	},
	onClosed:function(){
		window.location.reload();
	}
});


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

namespace Mastersign.Bench
{
    public interface IUserInterface
    {
        BenchUserInfo ReadUserInfo(string prompt);

        SecureString ReadPassword(string prompt);

        void EditTextFile(string file);

        void EditTextFile(string file, string prompt);

        void ShowInfo(string topic, string message);

        void ShowWarning(string topic, string message);

        void ShowError(string topic, string message);
    }
}