text:
package mockup

import (
	"github.com/gopherjs/gopherjs/js"
	"github.com/gopherjs/jquery"
	"github.com/kelwang/gopherjs-mockup/mockup/svg"
)

var jQuery = jquery.NewJQuery
var document = js.Global.Get("document")
var console = js.Global.Get("console")

func jsFloat(s interface{}) float64 {
	if s != nil && s != "" {
		return js.Global.Call("parseFloat", s).Float()
	}
	return 0
}

func jsInt(s interface{}) int {
	if s != nil && s != "" {
		return js.Global.Call("parseInt", s).Int()
	}
	return 0
}

func jsString(a interface{}) string {
	if a != nil {
		s := js.Global.Call("String", a).String()
		if s != "undefined" && s != "null" {
			return s
		}
	}
	return ""
}

type ControlEditable struct {
	Movable
	Scalable
	LineMovable
	Clonable
	Border
}

type Border struct {
	X1 float64
	Y1 float64
	X2 float64
	Y2 float64
}

func NewControlEditable(x1, y1, x2, y2 float64) *ControlEditable {
	return &ControlEditable{
		Movable:     movableNil,
		Scalable:    scalableNill,
		LineMovable: lineMovableNil,
		Clonable:    clonableNil,
		Border: Border{
			X1: x1,
			Y1: y1,
			X2: x2,
			Y2: y2,
		},
	}
}

type LineMovable struct {
	jquery.JQuery
}

type Movable struct {
	jquery.JQuery
}

type Scalable struct {
	jquery.JQuery
}

type Clonable struct {
	jquery.JQuery
}

var movableNil = Movable{JQuery: jQuery(nil)}
var scalableNill = Scalable{JQuery: jQuery(nil)}
var lineMovableNil = LineMovable{JQuery: jQuery(nil)}
var clonableNil = Clonable{JQuery: jQuery(nil)}

func (ed *ControlEditable) BindEvents(m map[string]MockupElement) {
	//dragging
	jQuery(document).On(jquery.MOUSEDOWN, svg.DRAGGABLE.JqSelector(), ed.startDragging)
	jQuery(document).On(jquery.MOUSEMOVE, func(e jquery.Event) { ed.dragging(e, m) })

	//scaling
	jQuery(document).On(jquery.MOUSEOVER, svg.EW_RESIZABLE.JqSelector(), ed.ewResizeMouseOver)
	jQuery(document).On(jquery.MOUSEOVER, svg.NS_RESIZABLE.JqSelector(), ed.nsResizeMouseOver)
	jQuery(document).On(jquery.MOUSEOVER, svg.NESW_RESIZABLE.JqSelector(), ed.neswResizeMouseOver)
	jQuery(document).On(jquery.MOUSEOVER, svg.NWSE_RESIZABLE.JqSelector(), ed.nwseResizeMouseOver)

	jQuery(document).On(jquery.MOUSEDOWN, svg.NWSE_RESIZABLE.JqSelector(), ed.startResize)
	jQuery(document).On(jquery.MOUSEDOWN, svg.NESW_RESIZABLE.JqSelector(), ed.startResize)
	jQuery(document).On(jquery.MOUSEDOWN, svg.NS_RESIZABLE.JqSelector(), ed.startResize)
	jQuery(document).On(jquery.MOUSEDOWN, svg.EW_RESIZABLE.JqSelector(), ed.startResize)

	//line moving
	jQuery(document).On(jquery.MOUSEDOWN, svg.LINE_VERTEX.JqSelector(), ed.startLineEditing)

	// stopping
	jQuery(document).On(jquery.MOUSEUP, ed.stopDraggingResize)

	// clonable
	jQuery(document).On(jquery.MOUSEDOWN, svg.CLONABLE.JqSelector(), func(e jquery.Event) {
		ed.startClone(e, m)
	})

}

func (ed *ControlEditable) startClone(e jquery.Event, m map[string]MockupElement) {
	ed.Movable = movableNil
	ed.Scalable = scalableNill
	ed.LineMovable = lineMovableNil
	id := jQuery(e.CurrentTarget).Attr("id")
	ele := m[id]

	count := len(m)
	nid := "M" + jsString(count)
	clo := newCloneBox(ele, nid)
	m[nid] = clo
	cloJq := clo.Svg().Jq()
	jQuery("svg").Append(cloJq)

	ed.Clonable = Clonable{JQuery: cloJq}
}

func (ed *ControlEditable) startResize(e jquery.Event) {
	ed.Movable = movableNil
	ed.Scalable = Scalable{JQuery: jQuery(e.CurrentTarget)}
	ed.LineMovable = lineMovableNil
	ed.Clonable = clonableNil
}

func (ed *ControlEditable) startLineEditing(e jquery.Event) {
	ed.Movable = movableNil
	ed.Scalable = scalableNill
	ed.LineMovable = LineMovable{JQuery: jQuery(e.CurrentTarget)}
	ed.Clonable = clonableNil
}

func (ed *ControlEditable) ewResizeMouseOver(e jquery.Event) {
	jQuery(e.CurrentTarget).SetCss("cursor", "ew-resize")
}

func (ed *ControlEditable) nsResizeMouseOver(e jquery.Event) {
	jQuery(e.CurrentTarget).SetCss("cursor", "ns-resize")
}

func (ed *ControlEditable) neswResizeMouseOver(e jquery.Event) {
	jQuery(e.CurrentTarget).SetCss("cursor", "nesw-resize")
}

func (ed *ControlEditable) nwseResizeMouseOver(e jquery.Event) {
	jQuery(e.CurrentTarget).SetCss("cursor", "nwse-resize")
}

func (ed *ControlEditable) dragging(e jquery.Event, m map[string]MockupElement) {
	clientX := e.Get("offsetX").Float()
	clientY := e.Get("offsetY").Float()

	if ed.Movable != movableNil {
		id := ed.Movable.Attr("id")
		ele := m[id]
		width := float64(ed.Movable.Width())
		height := float64(ed.Movable.Height())
		if clientX-width >= ed.X1 && clientX < ed.X2 && clientY-height >= ed.Y1 && clientY < ed.Y2 {
			ele.MoveTo(clientX-width, clientY)
		}
	}

	if ed.Scalable != scalableNill {
		id := ed.Scalable.Attr("id")
		sqr := id[2:3]
		id = id[4:]
		ele := m[id]
		switch sqr {
		case "1":
			ele.(*ScaleBox).NWResizeTo(clientX, clientY)
		case "2":
			ele.(*ScaleBox).NResizeTo(clientX, clientY)
		case "3":
			ele.(*ScaleBox).NEResizeTo(clientX, clientY)
		case "4":
			ele.(*ScaleBox).WResizeTo(clientX, clientY)
		case "5":
			ele.(*ScaleBox).EResizeTo(clientX, clientY)
		case "6":
			ele.(*ScaleBox).SWResizeTo(clientX, clientY)
		case "7":
			ele.(*ScaleBox).SResizeTo(clientX, clientY)
		case "8":
			ele.(*ScaleBox).SEesizeTo(clientX, clientY)
		}
	}

	if ed.LineMovable != lineMovableNil {
		id := ed.LineMovable.Attr("id")
		ele := m[id[5:]]
		sqr := id[3:4]
		ele.(*ScaleLine).PointTo(clientX, clientY, jsInt(sqr))
	}

	if ed.Clonable != clonableNil {
		id := ed.Clonable.Attr("id")
		ele := m[id]
		ele.MoveTo(clientX, clientY)
	}

}

func (ed *ControlEditable) startDragging(e jquery.Event) {
	if ed.Scalable == scalableNill && ed.LineMovable == lineMovableNil {
		ed.Movable = Movable{JQuery: jQuery(e.CurrentTarget)}
		ed.Movable.SetCss("cursor", "move")
	}

	ed.Clonable = clonableNil
}

func (ed *ControlEditable) stopDraggingResize(e jquery.Event) {
	println("stop")
	jQuery(e.CurrentTarget).SetCss("cursor", "pointer")
	if ed.Movable != movableNil {
		ed.Movable = movableNil
	}
	if ed.Scalable != scalableNill {
		ed.Scalable = scalableNill
	}
	if ed.LineMovable != lineMovableNil {
		ed.LineMovable = lineMovableNil
	}
	if ed.Clonable != clonableNil {
		ed.Clonable = clonableNil
	}
}


text:
"use strict";

//Se tivermos uma variável declarada fora da função ela será utilizada.
var i;
(function (){
	//Isso não gerará um erro
    for(i = 0;i < 10;i++){
        console.log(i);
    }
})();

console.log('Valor de i', i)

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Azure.Core;
using Azure.Security.KeyVault.Administration.Models;

namespace Azure.Security.KeyVault.Administration
{
    /// <summary>
    /// A factory class which constructs model classes for mocking purposes.
    /// </summary>
    [CodeGenType("AzureSecurityKeyVaultAdministrationModelFactory")]
    public static partial class KeyVaultAdministrationModelFactory
    {
        /// <summary> Initializes a new instance of KeyVaultRoleDefinition. </summary>
        /// <param name="id"> The role definition ID. </param>
        /// <param name="name"> The role definition name. </param>
        /// <param name="type"> The role definition type. </param>
        /// <param name="roleName"> The role name. </param>
        /// <param name="description"> The role definition description. </param>
        /// <param name="roleType"> The role type. </param>
        /// <param name="permissions"> Role definition permissions. </param>
        /// <param name="assignableScopes"> Role definition assignable scopes. </param>
        /// <returns> A new <see cref="Administration.KeyVaultRoleDefinition"/> instance for mocking. </returns>
        [EditorBrowsable(EditorBrowsableState.Never)]
        public static KeyVaultRoleDefinition KeyVaultRoleDefinition(string id, string name, KeyVaultRoleDefinitionType? type, string roleName, string description, KeyVaultRoleType? roleType, IList<KeyVaultPermission> permissions, IList<KeyVaultRoleScope> assignableScopes)
        {
            return new KeyVaultRoleDefinition(id, name, type, roleName, description, roleType, permissions, assignableScopes);
        }

        /// <summary>
        /// Initializes a new instance of RoleDefinition.
        /// </summary>
        /// <param name="id"> The role definition ID. </param>
        /// <param name="name"> The role definition name. </param>
        /// <param name="type"> The role definition type. </param>
        /// <param name="roleName"> The role name. </param>
        /// <param name="description"> The role definition description. </param>
        /// <param name="roleType"> The role type. </param>
        /// <param name="permissions"> Role definition permissions. </param>
        /// <param name="assignableScopes"> Role definition assignable scopes. </param>
        public static KeyVaultRoleDefinition RoleDefinition(string id, string name, string type, string roleName, string description, string roleType, IList<KeyVaultPermission> permissions, IList<KeyVaultRoleScope> assignableScopes) =>
            new KeyVaultRoleDefinition(id, name, type, roleName, description, roleType, permissions, assignableScopes);

        /// <summary>
        /// Initializes a new instance of RoleAssignment.
        /// </summary>
        /// <param name="id"> The role assignment ID. </param>
        /// <param name="name"> The role assignment name. </param>
        /// <param name="type"> The role assignment type. </param>
        /// <param name="properties"> Role assignment properties. </param>
        public static KeyVaultRoleAssignment RoleAssignment(string id, string name, string type, KeyVaultRoleAssignmentProperties properties) =>
            new KeyVaultRoleAssignment(id, name, type, properties);

        /// <summary>
        /// Initializes a new instance of a FullRestoreOperation for mocking purposes.
        /// </summary>
        /// <param name="response">The <see cref="Response" /> that will be returned from <see cref="KeyVaultRestoreOperation.GetRawResponse" />.</param>
        /// <param name="client">An instance of <see cref="KeyVaultBackupClient" />.</param>
        /// <param name="id"> Identifier for the restore operation.</param>
        /// <param name="startTime"> The start time of the restore operation.</param>
        /// <param name="endTime"> The end time of the restore operation.</param>
        /// <param name="errorMessage">The error message generated from the operation, if any.</param>
        public static KeyVaultRestoreOperation RestoreOperation(Response response, KeyVaultBackupClient client, string id, DateTimeOffset? startTime = null, DateTimeOffset? endTime = null, string errorMessage = null) =>
            new KeyVaultRestoreOperation(new RestoreDetailsInternal(
                null,
                null,
                errorMessage == null ? null : new KeyVaultServiceError(string.Empty, errorMessage, null),
                id,
                startTime,
                endTime), response, client);

        /// <summary>
        /// Initializes a new instance of a FullBackupOperation for mocking purposes.
        /// </summary>
        /// <param name="response">The <see cref="Response" /> that will be returned from <see cref="KeyVaultBackupOperation.GetRawResponse" />.</param>
        /// <param name="client">An instance of <see cref="KeyVaultBackupClient" />.</param>
        /// <param name="id"> Identifier for the restore operation.</param>
        /// <param name="blobContainerUri">The Blob Container Uri containing the backup.</param>
        /// <param name="startTime"> The start time of the restore operation.</param>
        /// <param name="endTime"> The end time of the restore operation.</param>
        /// <param name="errorMessage">The error message generated from the operation, if any.</param>
        public static KeyVaultBackupOperation BackupOperation(Response response, KeyVaultBackupClient client, string id, Uri blobContainerUri, DateTimeOffset? startTime = null, DateTimeOffset? endTime = null, string errorMessage = null) =>
            new KeyVaultBackupOperation(new FullBackupDetailsInternal(
                null,
                null,
                errorMessage == null ? null : new KeyVaultServiceError(string.Empty, errorMessage, null),
                startTime,
                endTime,
                id,
                blobContainerUri.AbsoluteUri), response, client);

        /// <summary>
        /// Initializes a new instance of a <see cref="BackupResult"/> for mocking purposes.
        /// </summary>
        /// <param name="folderUri">The location of the backup.</param>
        /// <param name="startTime">The start time of the backup operation.</param>
        /// <param name="endTime">The end time of the backup operation.</param>
        /// <returns>A new <see cref="BackupResult"/> instance.</returns>
        public static KeyVaultBackupResult BackupResult(Uri folderUri, DateTimeOffset startTime, DateTimeOffset endTime) =>
            new KeyVaultBackupResult(folderUri, startTime, endTime);

        /// <summary>
        /// Initializes a new instance of a <see cref="RestoreResult"/> for mocking purposes.
        /// </summary>
        /// <param name="startTime">The start time of the restore operation.</param>
        /// <param name="endTime">The end time of the restore operation.</param>
        /// <returns>A new <see cref="BackupResult"/> instance.</returns>
        public static KeyVaultRestoreResult RestoreResult(DateTimeOffset startTime, DateTimeOffset endTime) =>
            new KeyVaultRestoreResult(startTime, endTime);

        /// <summary>
        /// Initializes a new instance of a <see cref="SelectiveKeyRestoreResult"/> for mocking purposes.
        /// </summary>
        /// <param name="startTime">The start time of the restore operation.</param>
        /// <param name="endTime">The end time of the restore operation.</param>
        /// <returns>A new <see cref="BackupResult"/> instance.</returns>
        public static KeyVaultRestoreResult SelectiveKeyRestoreResult(DateTimeOffset startTime, DateTimeOffset endTime) =>
            new KeyVaultRestoreResult(startTime, endTime);
    }
}


text:
@implementation YKAboutTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self setupUI];
    }
    return self;
}

#pragma mark - 搭建界面
- (void)setupUI{

    UILabel *titleLab = [[UILabel alloc] init];
    titleLab.font = [UIFont systemFontOfSize:14];
    titleLab.textColor = [UIColor yk_colorWithHex:0x333333];
    titleLab.text = @"欢迎页面";
    [self.contentView addSubview:titleLab];
    self.titleLab = titleLab;

    UIImageView *arrowImageView = [[UIImageView alloc] init];
    arrowImageView.image = [UIImage imageNamed:@"me_rightArrow"];
    [self.contentView addSubview:arrowImageView];

    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentView).offset(kSPACING);
        make.centerY.equalTo(self.contentView);
    }];

    [arrowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.contentView).offset(-kSPACING);
        make.centerY.equalTo(self.contentView);
        make.size.mas_equalTo(CGSizeMake(8, 14));
    }];

    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = [UIColor yk_colorWithHex:0xf5f5f5];
    [self.contentView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.contentView);
        make.bottom.equalTo(self.contentView);
        make.height.mas_equalTo(1);
    }];

}

@end


text:
package com.ibm.wuhan.bus.web.controller;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ibm.wuhan.bus.domain.BusLineInfo;
import com.ibm.wuhan.bus.service.impl.BusLineBusinessService;

/**
 * Servlet implementation class ListBusStopInfoServlet
 */
@WebServlet("/bus/ListBusStopInfoServlet")
public class ListBusStopInfoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ListBusStopInfoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		String id = request.getParameter("id");
		BusLineBusinessService service = new BusLineBusinessService();
		BusLineInfo buslineinfo = service.findBus(id);
//		System.out.println(buslineinfo.toString());
//		System.out.println(buslineinfo.getBusstopinfo());
		//Map mapstop = buslineinfo.getBusstopinfo();

		request.getSession().setAttribute("buslininfo", buslineinfo);
		response.sendRedirect("ListStopInfoUIServlet");

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}


text:
class Category
  include Mongoid::Document

  field :name, type: String
  field :description, type: String
  field :category_type, type: String
  field :language, type: String
end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources name="ru" flag="ru" title="Russian">

	<string name="_bx_groups"><![CDATA[Группы]]></string>
	<string name="_bx_groups_cmts"><![CDATA[Группы - Комментарии]]></string>

	<string name="_bx_groups_option_num_connections_quick"><![CDATA[Число элементов в блоке друзей]]></string>
	<string name="_bx_groups_option_per_page_browse"><![CDATA[Число элементов на странице]]></string>
    <string name="_bx_groups_option_num_rss"><![CDATA[Число элементов в ленте RSS]]></string>
    <string name="_bx_groups_option_searchable_fields"><![CDATA[Поля для поиска]]></string>

	<string name="_bx_groups_form_profile"><![CDATA[Группы]]></string>
	<string name="_bx_groups_form_profile_display_add"><![CDATA[Добавление группы]]></string>
	<string name="_bx_groups_form_profile_display_edit"><![CDATA[Редактирование группы]]></string>
	<string name="_bx_groups_form_profile_display_edit_cover"><![CDATA[Редактирование обложки]]></string>
	<string name="_bx_groups_form_profile_display_delete"><![CDATA[Удаление группы]]></string>
	<string name="_bx_groups_form_profile_display_view"><![CDATA[Просмотр группы]]></string>
    <string name="_bx_groups_form_profile_display_view_full"><![CDATA[Полный просмотр группы]]></string>
    <string name="_bx_groups_form_profile_display_invite"><![CDATA[Приглашение в группу]]></string>
    <string name="_bx_groups_form_entry_input_author"><![CDATA[Автор]]></string>
	<string name="_bx_groups_form_profile_input_sys_do_submit"><![CDATA[Выполнить]]></string>
    <string name="_bx_groups_form_profile_input_sys_join_confirm"><![CDATA[Подтверждение регистрации]]></string>
    <string name="_bx_groups_form_profile_input_join_confirm"><![CDATA[Подтверждение регистрации]]></string>
    <string name="_bx_groups_form_profile_input_sys_allow_view_to"><![CDATA[Конфиденциальность]]></string>
    <string name="_bx_groups_form_profile_input_allow_view_to"><![CDATA[Конфиденциальность]]></string>
    <string name="_bx_groups_form_profile_input_sys_initial_members"><![CDATA[Пригласить участников]]></string>
    <string name="_bx_groups_form_profile_input_initial_members"><![CDATA[Пригласить участников]]></string>
    <string name="_bx_groups_form_profile_input_initial_members_desc"><![CDATA[]]></string>
    <string name="_bx_groups_form_profile_input_sys_group_name"><![CDATA[Название группы]]></string>
    <string name="_bx_groups_form_profile_input_group_name"><![CDATA[Название группы]]></string>
    <string name="_bx_groups_form_profile_input_group_name_err"><![CDATA[Эта информация необходима. Пожалуйста, заполните это поле.]]></string>
    <string name="_bx_groups_form_profile_input_sys_group_desc"><![CDATA[Описание]]></string>
    <string name="_bx_groups_form_profile_input_group_desc"><![CDATA[Описание]]></string>
    <string name="_bx_groups_form_profile_input_sys_group_cat"><![CDATA[Категория]]></string>
	<string name="_bx_groups_form_profile_input_group_cat"><![CDATA[Категория]]></string>
    <string name="_bx_groups_form_profile_input_group_cat_err"><![CDATA[Поле категории необходимо]]></string>
	<string name="_bx_groups_form_profile_input_sys_picture"><![CDATA[Картинка группы]]></string>
	<string name="_bx_groups_form_profile_input_picture"><![CDATA[Загрузить новую картинку группы]]></string>
	<string name="_bx_groups_form_profile_input_picture_err"><![CDATA[Необходима картинка группы.]]></string>
	<string name="_bx_groups_form_profile_input_sys_cover"><![CDATA[Картинка обложки]]></string>
	<string name="_bx_groups_form_profile_input_cover"><![CDATA[Загрузить новую картинку обложки]]></string>
	<string name="_bx_groups_form_profile_input_sys_delete_confirm"><![CDATA[Подтверждение на удаление]]></string>
	<string name="_bx_groups_form_profile_input_delete_confirm"><![CDATA[Я уверен, что хочу удалить эту группу]]></string>
	<string name="_bx_groups_form_profile_input_delete_confirm_info"><![CDATA[Это действие не может быть отменено.]]></string>
	<string name="_bx_groups_form_profile_input_delete_confirm_error"><![CDATA[Пожалуйста, отметьте этот флажок, если действительно хотите удалить группу.]]></string>

	<string name="_bx_groups_acl_action_create_profile"><![CDATA[Создать группу]]></string>
	<string name="_bx_groups_acl_action_delete_profile"><![CDATA[Удалить группу]]></string>
	<string name="_bx_groups_acl_action_view_profile"><![CDATA[Просмотреть группу]]></string>
	<string name="_bx_groups_acl_action_edit_any_profile"><![CDATA[Редактировать любую группу]]></string>

	<string name="_bx_groups_page_title_sys_joined_entries"><![CDATA[Участие в группах]]></string>
	<string name="_bx_groups_page_title_joined_entries"><![CDATA[Участие в группах]]></string>
	<string name="_bx_groups_page_title_sys_create_profile"><![CDATA[Создать группу]]></string>
	<string name="_bx_groups_page_title_create_profile"><![CDATA[Создать группу]]></string>
	<string name="_bx_groups_page_title_sys_edit_profile"><![CDATA[Редактировать группу]]></string>
	<string name="_bx_groups_page_title_edit_profile"><![CDATA[Редактировать группу]]></string>
	<string name="_bx_groups_page_title_sys_edit_profile_cover"><![CDATA[Редактировать обложку группы]]></string>
	<string name="_bx_groups_page_title_edit_profile_cover"><![CDATA[Редактировать обложку]]></string>
	<string name="_bx_groups_page_title_sys_delete_profile"><![CDATA[Удалить группу]]></string>
	<string name="_bx_groups_page_title_delete_profile"><![CDATA[Удалить группу]]></string>
	<string name="_bx_groups_page_title_sys_view_profile_closed"><![CDATA[Просмотр закрытой группы]]></string>
	<string name="_bx_groups_page_title_sys_view_profile"><![CDATA[Просмотр группы]]></string>
	<string name="_bx_groups_page_title_view_profile"><![CDATA[{display_name}]]></string>
	<string name="_bx_groups_page_title_browse"><![CDATA[Группы]]></string>
	<string name="_bx_groups_page_title_browse_by_author"><![CDATA[Группы {display_name}]]></string>
	<string name="_bx_groups_page_title_browse_featured"><![CDATA[Продвинутые группы]]></string>
    <string name="_bx_groups_page_title_browse_top"><![CDATA[Популярные группы]]></string>
	<string name="_bx_groups_page_title_browse_recent"><![CDATA[Новые группы]]></string>
	<string name="_bx_groups_page_title_browse_connections"><![CDATA[{0} связей]]></string>
	<string name="_bx_groups_page_title_browse_connections_mutual"><![CDATA[{0} и {1} обоюдных связей]]></string>
	<string name="_bx_groups_page_title_sys_profile_friends"><![CDATA[Друзья]]></string>
	<string name="_bx_groups_page_title_profile_friends"><![CDATA[Друзья]]></string>
	<string name="_bx_groups_page_title_sys_group_fans"><![CDATA[Участники]]></string>
	<string name="_bx_groups_page_title_group_fans"><![CDATA[Участники]]></string>
	<string name="_bx_groups_page_title_sys_profile_comments"><![CDATA[Комментарии]]></string>
    <string name="_bx_groups_page_title_profile_comments"><![CDATA[Комментарии]]></string>
	<string name="_bx_groups_page_title_sys_profile_info"><![CDATA[Инфо группы]]></string>
	<string name="_bx_groups_page_title_profile_info"><![CDATA[Инфо о {display_name}]]></string>
	<string name="_bx_groups_page_title_sys_recent"><![CDATA[Новые группы]]></string>
	<string name="_bx_groups_page_title_recent"><![CDATA[Новые группы]]></string>
	<string name="_bx_groups_page_title_sys_manage"><![CDATA[Управление собственными группами]]></string>
	<string name="_bx_groups_page_title_sys_manage_administration"><![CDATA[Управление всеми группами]]></string>
	<string name="_bx_groups_page_title_manage"><![CDATA[Управление]]></string>
	<string name="_bx_groups_page_title_sys_top"><![CDATA[Популярные группы]]></string>
    <string name="_bx_groups_page_title_top"><![CDATA[Популярные группы]]></string>
    <string name="_bx_groups_page_title_sys_invite_to_group"><![CDATA[Пригласить участников в группу]]></string>
    <string name="_bx_groups_page_title_invite_to_group"><![CDATA[Пригласить участников в группу]]></string>
    <string name="_bx_groups_page_title_sys_entries_search"><![CDATA[Поиск]]></string>
    <string name="_bx_groups_page_title_entries_search"><![CDATA[Поиск]]></string>

	<string name="_bx_groups_page_block_title_favorites_of_author"><![CDATA[Избранные группы]]></string>
    <string name="_bx_groups_page_block_title_sys_favorites_of_author"><![CDATA[Избранные группы]]></string>
	<string name="_bx_groups_page_block_title_sys_joined_entries"><![CDATA[Участие в группах]]></string>
	<string name="_bx_groups_page_block_title_joined_entries"><![CDATA[Участие в группах]]></string>
	<string name="_bx_groups_page_block_title_create_profile"><![CDATA[Создать группу]]></string>
	<string name="_bx_groups_page_block_title_edit_profile"><![CDATA[Редактировать группу]]></string>
	<string name="_bx_groups_page_block_title_edit_profile_cover"><![CDATA[Редактировать обложку]]></string>
	<string name="_bx_groups_page_block_title_delete_profile"><![CDATA[Удалить группу]]></string>
	<string name="_bx_groups_page_block_title_profile_info_link"><![CDATA[{display_name} - Инфо]]></string>
	<string name="_bx_groups_page_block_title_profile_info"><![CDATA[Инфо]]></string>
	<string name="_bx_groups_page_block_title_system_profile_info"><![CDATA[Инфо]]></string>
	<string name="_bx_groups_page_block_title_profile_description"><![CDATA[Описание]]></string>
	<string name="_bx_groups_page_block_title_profile_friends_link"><![CDATA[{display_name} - Друзья]]></string>
	<string name="_bx_groups_page_block_title_profile_friends"><![CDATA[Друзья]]></string>
	<string name="_bx_groups_page_block_title_system_profile_friends"><![CDATA[Друзья]]></string>
	<string name="_bx_groups_page_block_title_admins"><![CDATA[Администраторы]]></string>
	<string name="_bx_groups_page_block_title_fans_link"><![CDATA[Участники группы: {display_name}]]></string>
	<string name="_bx_groups_page_block_title_fans"><![CDATA[Участники]]></string>
	<string name="_bx_groups_page_block_title_system_fans"><![CDATA[Участники]]></string>
	<string name="_bx_groups_page_block_title_profile_comments"><![CDATA[Комментарии]]></string>
    <string name="_bx_groups_page_block_title_profile_comments_link"><![CDATA[Комментарии к {title}]]></string>
	<string name="_bx_groups_page_block_title_profile_actions"><![CDATA[Действия]]></string>
	<string name="_bx_groups_page_block_title_featured_profiles"><![CDATA[Продвинутые группы]]></string>
	<string name="_bx_groups_page_block_title_latest_profiles"><![CDATA[Новые группы]]></string>
	<string name="_bx_groups_page_block_title_system_manage"><![CDATA[Управление собственными группами]]></string>
	<string name="_bx_groups_page_block_title_system_manage_administration"><![CDATA[Управление всеми группами]]></string>
	<string name="_bx_groups_page_block_title_manage"><![CDATA[Управление]]></string>
    <string name="_bx_groups_page_block_title_top_profiles"><![CDATA[Популярные группы]]></string>
    <string name="_bx_groups_page_block_title_entry_social_sharing"><![CDATA[Поделиться]]></string>
    <string name="_bx_groups_page_block_title_categories"><![CDATA[Категории групп]]></string>
    <string name="_bx_groups_page_block_title_invite_to_group"><![CDATA[Пригласить участников в группу]]></string>
    <string name="_bx_groups_page_block_title_search_form"><![CDATA[Форма поиска]]></string>
    <string name="_bx_groups_page_block_title_search_results"><![CDATA[Результаты поиска]]></string>
    <string name="_bx_groups_page_block_title_search_form_cmts"><![CDATA[Форма поиска комментариев]]></string>
    <string name="_bx_groups_page_block_title_search_results_cmts"><![CDATA[Результаты поиска комментариев]]></string>

    <string name="_bx_groups_menu_title_submenu"><![CDATA[Группы - Подменю]]></string>
    <string name="_bx_groups_menu_set_title_submenu"><![CDATA[Группы - Подменю]]></string>
    <string name="_bx_groups_menu_set_title_view_profile_actions"><![CDATA[Группа - Действия]]></string>
    <string name="_bx_groups_menu_title_view_profile_actions"><![CDATA[Группа - Действия]]></string>
    <string name="_bx_groups_menu_set_title_view_profile_actions_more"><![CDATA[Группа - Дополнительные действия]]></string>
    <string name="_bx_groups_menu_title_view_profile_actions_more"><![CDATA[Группа - Дополнительные действия]]></string>
    <string name="_bx_groups_menu_set_title_view_profile_submenu"><![CDATA[Подменю просмотра группы]]></string>
    <string name="_bx_groups_menu_title_view_profile_submenu"><![CDATA[Подменю просмотра группы]]></string>
    <string name="_bx_groups_menu_title_view_profile_submenu_cover"><![CDATA[Подменю группы на обложке]]></string>
	<string name="_bx_groups_menu_set_title_manage_tools"><![CDATA[Инструменты управления - Подменю]]></string>
    <string name="_bx_groups_menu_title_manage_tools"><![CDATA[Инструменты управления - Подменю]]></string>
    <string name="_bx_groups_menu_item_title_system_delete"><![CDATA[Удалить]]></string>
    <string name="_bx_groups_menu_item_title_delete"><![CDATA[Удалить]]></string>
    <string name="_bx_groups_menu_item_title_system_delete_with_content"><![CDATA[Удалить вместе с содержимым]]></string>
    <string name="_bx_groups_menu_item_title_delete_with_content"><![CDATA[Удалить вместе с содержимым]]></string>
    <string name="_bx_groups_menu_item_title_system_edit_cover"><![CDATA[Редактировать обложку]]></string>
    <string name="_bx_groups_menu_item_title_edit_cover"><![CDATA[Редактировать обложку]]></string>
    <string name="_bx_groups_menu_item_title_system_edit_profile"><![CDATA[Редактировать группу]]></string>
    <string name="_bx_groups_menu_item_title_edit_profile"><![CDATA[Редактировать группу]]></string>
    <string name="_bx_groups_menu_item_title_system_delete_profile"><![CDATA[Удалить группу]]></string>
    <string name="_bx_groups_menu_item_title_delete_profile"><![CDATA[Удалить группу]]></string>
    <string name="_bx_groups_menu_item_title_system_delete_account"><![CDATA[Удалить аккаунт]]></string>
    <string name="_bx_groups_menu_item_title_delete_account"><![CDATA[Удалить аккаунт]]></string>
    <string name="_bx_groups_menu_item_title_system_profile_type"><![CDATA[Группа]]></string>
    <string name="_bx_groups_menu_item_title_profile_type"><![CDATA[Группа]]></string>
    <string name="_bx_groups_menu_item_title_system_create_profile"><![CDATA[Создать группу]]></string>
    <string name="_bx_groups_menu_item_title_create_profile"><![CDATA[Создать группу]]></string>
    <string name="_bx_groups_menu_item_title_system_view_profile_friends"><![CDATA[Друзья]]></string>
    <string name="_bx_groups_menu_item_title_view_profile_friends"><![CDATA[Друзья]]></string>
    <string name="_bx_groups_menu_item_title_system_view_joined_groups"><![CDATA[Группы]]></string>
    <string name="_bx_groups_menu_item_title_view_joined_groups"><![CDATA[Группы]]></string>
    <string name="_bx_groups_menu_item_title_system_view_fans"><![CDATA[Участники]]></string>
    <string name="_bx_groups_menu_item_title_view_fans"><![CDATA[Участники]]></string>
    <string name="_bx_groups_menu_item_title_system_view_profile_comments"><![CDATA[Комментарии]]></string>
    <string name="_bx_groups_menu_item_title_view_profile_comments"><![CDATA[Комментарии]]></string>
    <string name="_bx_groups_menu_item_title_system_view_profile_info"><![CDATA[Инфо]]></string>
    <string name="_bx_groups_menu_item_title_view_profile_info"><![CDATA[Инфо]]></string>
    <string name="_bx_groups_menu_item_title_system_view_profile_view"><![CDATA[Группа]]></string>
    <string name="_bx_groups_menu_item_title_view_profile_view"><![CDATA[Группа]]></string>
    <string name="_bx_groups_menu_item_title_system_invite"><![CDATA[Пригласить]]></string>
    <string name="_bx_groups_menu_item_title_invite"><![CDATA[Пригласить]]></string>

    <string name="_bx_groups_menu_item_title_system_befriend"><![CDATA[Добавить друга]]></string>
    <string name="_bx_groups_menu_item_title_befriend"><![CDATA[Добавить друга]]></string>
    <string name="_bx_groups_menu_item_title_befriend_sent"><![CDATA[Добавить друга (запрошено)]]></string>
    <string name="_bx_groups_menu_item_title_befriend_confirm"><![CDATA[Принять запрос о дружбе]]></string>
    <string name="_bx_groups_menu_item_title_system_unfriend"><![CDATA[Перестать дружить]]></string>
    <string name="_bx_groups_menu_item_title_unfriend"><![CDATA[Перестать дружить]]></string>
    <string name="_bx_groups_menu_item_title_unfriend_cancel_request"><![CDATA[Отменить запрос о дружбе]]></string>
    <string name="_bx_groups_menu_item_title_unfriend_reject_request"><![CDATA[Отвергнуть запрос о дружбе]]></string>

    <string name="_bx_groups_menu_item_title_system_become_fan"><![CDATA[Присоединиться]]></string>
    <string name="_bx_groups_menu_item_title_become_fan"><![CDATA[Присоединиться]]></string>
    <string name="_bx_groups_menu_item_title_become_fan_sent"><![CDATA[Присоединение запрошено]]></string>
    <string name="_bx_groups_menu_item_title_become_fan_confirm"><![CDATA[Одобрить присоединение]]></string>
    <string name="_bx_groups_menu_item_title_system_leave_group"><![CDATA[Покинуть группу]]></string>
    <string name="_bx_groups_menu_item_title_leave_group"><![CDATA[Покинуть группу]]></string>
    <string name="_bx_groups_menu_item_title_leave_group_cancel_request"><![CDATA[Отменить присоединение]]></string>
    <string name="_bx_groups_menu_item_title_leave_group_reject_request"><![CDATA[Отвергнуть присоединение]]></string>

    <string name="_bx_groups_menu_item_title_system_subscribe"><![CDATA[Получать уведомления]]></string>
    <string name="_bx_groups_menu_item_title_subscribe"><![CDATA[Получать уведомления]]></string>
    <string name="_bx_groups_menu_item_title_system_unsubscribe"><![CDATA[Отключить уведомления]]></string>
    <string name="_bx_groups_menu_item_title_unsubscribe"><![CDATA[Отключить уведомления]]></string>
    <string name="_bx_groups_menu_item_title_system_more_actions"><![CDATA[Дополнительные действия]]></string>
    <string name="_bx_groups_menu_item_title_more_actions"><![CDATA[]]></string>
    <string name="_bx_groups_menu_item_title_system_friends"><![CDATA[Друзья]]></string>
    <string name="_bx_groups_menu_item_title_friends"><![CDATA[Друзья]]></string>
    <string name="_bx_groups_menu_item_title_system_friend_requests"><![CDATA[Число запросов дружбы]]></string>
    <string name="_bx_groups_menu_item_title_friend_requests"><![CDATA[{addon} запросов дружбы]]></string>
    <string name="_bx_groups_menu_item_title_system_manage_my_groups"><![CDATA[Мои группы]]></string>
    <string name="_bx_groups_menu_item_title_manage_my_groups"><![CDATA[{addon} групп]]></string>
    <string name="_bx_groups_menu_item_title_system_entries_recent"><![CDATA[Новые]]></string>
    <string name="_bx_groups_menu_item_title_entries_recent"><![CDATA[Новые]]></string>
    <string name="_bx_groups_menu_item_title_system_entries_search"><![CDATA[Поиск]]></string>
    <string name="_bx_groups_menu_item_title_entries_search"><![CDATA[Поиск]]></string>
    <string name="_bx_groups_menu_item_title_system_entries_manage"><![CDATA[Управление]]></string>
    <string name="_bx_groups_menu_item_title_entries_manage"><![CDATA[Управление]]></string>
    <string name="_bx_groups_menu_item_title_system_entries_home"><![CDATA[Группы]]></string>
    <string name="_bx_groups_menu_item_title_entries_home"><![CDATA[Группы]]></string>
    <string name="_bx_groups_menu_item_title_system_admt_groups"><![CDATA[Группы]]></string>
	<string name="_bx_groups_menu_item_title_admt_groups"><![CDATA[Группы - {addon} неодобрено]]></string>
	<string name="_bx_groups_menu_item_title_manage_my"><![CDATA[Мои группы]]></string>
	<string name="_bx_groups_menu_item_title_manage_all"><![CDATA[Все группы]]></string>
	<string name="_bx_groups_menu_item_title_system_entries_top"><![CDATA[Популярные]]></string>
	<string name="_bx_groups_menu_item_title_entries_top"><![CDATA[Популярные]]></string>

	<string name="_bx_groups_grid_filter_item_title_adm_select_one_filter1"><![CDATA[Все статусы]]></string>
	<string name="_bx_groups_grid_filter_item_title_adm_active"><![CDATA[Активные]]></string>
	<string name="_bx_groups_grid_filter_item_title_adm_pending"><![CDATA[В ожидании]]></string>
	<string name="_bx_groups_grid_filter_item_title_adm_suspended"><![CDATA[Заблокированные]]></string>
	<string name="_bx_groups_grid_column_title_adm_active"><![CDATA[Активные]]></string>
    <string name="_bx_groups_grid_column_title_adm_name"><![CDATA[Название]]></string>
    <string name="_bx_groups_grid_column_title_adm_added"><![CDATA[Создание]]></string>
    <string name="_bx_groups_grid_column_title_adm_account"><![CDATA[Аккаунт]]></string>
    <string name="_bx_groups_grid_action_title_adm_delete"><![CDATA[Удалить]]></string>
    <string name="_bx_groups_grid_action_title_adm_delete_with_content"><![CDATA[Удалить вместе с содержимым]]></string>
    <string name="_bx_groups_grid_action_title_adm_more_actions"><![CDATA[Дополнительные действия]]></string>
	<string name="_bx_groups_grid_action_err_delete"><![CDATA[Невозможно удалить выбранную(ные) группу(ы).]]></string>
	<string name="_bx_groups_grid_txt_account_manager"><![CDATA[Перенаправить в управление аккаунтом.]]></string>

    <string name="_bx_groups_chart_growth"><![CDATA[Группы: Развитие]]></string>
    <string name="_bx_groups_chart_growth_speed"><![CDATA[Группы: Скорость развития]]></string>

    <string name="_bx_groups_search_extended"><![CDATA[Поиск групп]]></string>
    <string name="_bx_groups_search_extended_cmts"><![CDATA[Поиск комментариев к группам]]></string>

    <string name="_bx_groups_txt_account_pending"><![CDATA[Эта группа ожидает одобрения. Пожалуйста, дождитесь ее активации.]]></string>
    <string name="_bx_groups_txt_account_suspended"><![CDATA[Эта группа заблокирована.]]></string>
    <string name="_bx_groups_txt_N_fans"><![CDATA[{0} участников]]></string>
    <string name="_bx_groups_txt_sample_single"><![CDATA[группа]]></string>
    <string name="_bx_groups_txt_sample_single_with_article"><![CDATA[группа]]></string>
    <string name="_bx_groups_txt_sample_comment_single"><![CDATA[комментарий к группе]]></string>
    <string name="_bx_groups_txt_sample_vote_single"><![CDATA[голос за группу]]></string>
    <string name="_bx_groups_txt_to_admins"><![CDATA[В админы]]></string>
    <string name="_bx_groups_txt_from_admins"><![CDATA[Из админов]]></string>
    <string name="_bx_groups_txt_private_group"><![CDATA[Приватная группа]]></string>

	<string name="_bx_groups_alert_action_fan_added"><![CDATA[присоединение нового участника]]></string>
    <string name="_bx_groups_txt_ntfs_fan_added"><![CDATA[В группу "{owner_name}" добавился новый член - {subentry_sample}]]></string>
    <string name="_bx_groups_alert_action_join_request"><![CDATA[запрос на присоединение к событию]]></string>
    <string name="_bx_groups_txt_ntfs_join_request"><![CDATA[В группу "{owner_name}" хочет присоединиться новый член - {subentry_sample}]]></string>
    <string name="_bx_groups_txt_ntfs_timeline_post_common"><![CDATA[В группе {owner_name} новая публикация от {subentry_sample}]]></string>

    <string name="_bx_groups_pre_lists_cats"><![CDATA[Категории групп]]></string>
    <string name="_bx_groups_cat_General"><![CDATA[Обобщение]]></string>
    <string name="_bx_groups_cat_Business"><![CDATA[Бизнес]]></string>
    <string name="_bx_groups_cat_Interests"><![CDATA[Увлечение]]></string>
    <string name="_bx_groups_cat_Causes"><![CDATA[Движение]]></string>
    <string name="_bx_groups_cat_Fun"><![CDATA[Юмор]]></string>
    <string name="_bx_groups_cat_Uncategorised"><![CDATA[Без категории]]></string>

    <string name="_bx_groups_email_join_request"><![CDATA[Запрос на присоединение к группе]]></string>
    <string name="_bx_groups_email_join_request_subject"><![CDATA[Запрос на присоединение к группе]]></string>
    <string name="_bx_groups_email_join_request_body"><![CDATA[{email_header}

Получен запрос на присоединение к группе {EntryTitle} от {NewMemberDisplayName}

{email_footer}]]></string>

    <string name="_bx_groups_email_join_reject"><![CDATA[Отклонение запроса на присоединение к группе]]></string>
    <string name="_bx_groups_email_join_reject_subject"><![CDATA[Ваш запрос на присоединение к группе был отклонен]]></string>
    <string name="_bx_groups_email_join_reject_body"><![CDATA[{email_header}

Ваш запрос на присоединение к группе {EntryTitle} был отклонен администратором группы.

{email_footer}]]></string>

    <string name="_bx_groups_email_join_confirm"><![CDATA[Одобрение запроса на присоединение к группе]]></string>
    <string name="_bx_groups_email_join_confirm_subject"><![CDATA[Ваш запрос на присоединение к группе был одобрен]]></string>
    <string name="_bx_groups_email_join_confirm_body"><![CDATA[{email_header}

Ваш запрос на присоединение к группе {EntryTitle} был одобрен.

{email_footer}]]></string>

    <string name="_bx_groups_email_fan_remove"><![CDATA[Удаление из группы]]></string>
    <string name="_bx_groups_email_fan_remove_subject"><![CDATA[Вы были удалены из группы]]></string>
    <string name="_bx_groups_email_fan_remove_body"><![CDATA[{email_header}

Ваш профиль был удален из группы {EntryTitle} администратором группы.

{email_footer}]]></string>

    <string name="_bx_groups_email_fan_become_admin"><![CDATA[Получение статуса администратора группы]]></string>
    <string name="_bx_groups_email_fan_become_admin_subject"><![CDATA[Вы стали администратором группы]]></string>
    <string name="_bx_groups_email_fan_become_admin_body"><![CDATA[{email_header}

Вы получили статус администратора группы {EntryTitle}.

{email_footer}]]></string>

    <string name="_bx_groups_email_admin_become_fan"><![CDATA[Лишение статуса администратора группы]]></string>
    <string name="_bx_groups_email_admin_become_fan_subject"><![CDATA[Вы были лишены статуса администратора группы]]></string>
    <string name="_bx_groups_email_admin_become_fan_body"><![CDATA[{email_header}

Вы были лишены статуса администратора группы {EntryTitle}

{email_footer}]]></string>

    <string name="_bx_groups_email_invitation"><![CDATA[Приглашение в группу]]></string>
    <string name="_bx_groups_email_invitation_subject"><![CDATA[Приглашение в группу "{EntryTitle}"]]></string>
    <string name="_bx_groups_email_invitation_body"><![CDATA[{email_header}

{InviterDisplayName} пригласил Вас в группу {EntryTitle}.

{email_footer}]]></string>
</resources>


text:
"""Control the microscope."""
import asyncio
import logging

from async_timeout import timeout as async_timeout
import voluptuous as vol

from camacq.event import Event, EventBus
from camacq.exceptions import CamAcqError, MissingActionError, MissingActionTypeError
from camacq.const import ACTION_TIMEOUT, CAMACQ_START_EVENT, CAMACQ_STOP_EVENT
from camacq.helper import register_signals
from camacq.plugins.sample import Samples
from camacq.util import dotdict

_LOGGER = logging.getLogger(__name__)

class Center:
    """Represent a control center for the microscope.

    Parameters
    ----------
    loop : asyncio.EventLoop
        The event loop.

    Attributes
    ----------
    loop : asyncio.EventLoop
        Return the event loop.
    bus : EventBus instance
        Return the EventBus instance.
    samples : Samples instance
        Return the Samples instance that holds all the Sample instances.
    actions : ActionsRegistry instance
        Return the ActionsRegistry instance.
    data : dict
        Return dict that stores data from other modules than control.
    """

    # pylint: disable=too-many-instance-attributes

    def __init__(self, loop=None):
        """Set up instance."""
        self.loop = loop or asyncio.get_event_loop()
        self.loop.set_exception_handler(loop_exception_handler)
        self.bus = EventBus(self)
        self.actions = ActionsRegistry(self)
        self.samples = Samples()
        self.data = {}
        self._exit_code = 0
        self._stopped = None
        self._pending_tasks = []
        self._track_tasks = False

    def __repr__(self):
        """Return the representation."""
        return "<Center>"

    async def end(self, code):
        """Prepare app for exit.

        Parameters
        ----------
        code : int
            Exit code to return when the app exits.
        """
        _LOGGER.info("Stopping camacq")
        self._track_tasks = True
        await self.bus.notify(CamAcqStopEvent({"exit_code": code}))
        self._exit_code = code
        await self.wait_for()
        if self._stopped is not None:
            self._stopped.set()
        else:
            self.loop.stop()

    async def start(self):
        """Start the app."""
        _LOGGER.info("Starting camacq")
        await self.bus.notify(CamAcqStartEvent())
        self._stopped = asyncio.Event()
        register_signals(self)
        await self._stopped.wait()
        return self._exit_code

    def add_executor_job(self, func, *args):
        """Schedule a function to be run in the thread pool.

        Return a task.
        """
        task = self.loop.run_in_executor(None, func, *args)

        if self._track_tasks:
            self._pending_tasks.append(task)

        return task

    def create_task(self, coro):
        """Schedule a coroutine on the event loop.

        Return a task.
        """
        task = asyncio.create_task(coro)

        if self._track_tasks:
            self._pending_tasks.append(task)

        return task

    async def wait_for(self):
        """Wait for all pending tasks."""
        await asyncio.sleep(0)
        while self._pending_tasks:
            _LOGGER.debug("Waiting for pending tasks")
            pending = [task for task in self._pending_tasks if not task.done()]
            self._pending_tasks.clear()
            if pending:
                await asyncio.wait(pending)
            else:
                await asyncio.sleep(0)

class ActionsRegistry:
    """Manage all registered actions."""

    def __init__(self, center):
        """Set up instance."""
        self._actions = {}
        self._center = center

    def __getattr__(self, action_type):
        """Return registered actions for an action type."""
        try:
            return self._actions[action_type]
        except KeyError as exc:
            raise MissingActionTypeError(action_type) from exc

    @property
    def actions(self):
        """:dict: Return dict of ActionTypes with all registered actions."""
        return self._actions

    def register(self, action_type, action_id, action_func, schema):
        """Register an action.

        Register actions per module.

        Parameters
        ----------
        action_type : str
            The name of the action_type to register the action under.
        action_id : str
            The id of the action to register.
        action_func : callable
            The function that should be called for the action.
        action_func : voluptuous schema
            The voluptuous schema that should validate the parameters
            of the action call.
        """
        if not asyncio.iscoroutinefunction(action_func):
            _LOGGER.error(
                "Action handler function %s is not a coroutine function", action_func
            )
            return
        if action_type not in self._actions:
            self._actions[action_type] = ActionType()
        _LOGGER.debug("Registering action %s.%s", action_type, action_id)
        self._actions[action_type][action_id] = Action(
            action_type, action_id, action_func, schema
        )

    async def call(self, action_type, action_id, **kwargs):
        """Call an action with optional kwargs.

        Parameters
        ----------
        action_type : str
            The name of the module where the action is registered.
        action_id : str
            The id of the action to call.
        **kwargs
            Arbitrary keyword arguments. These will be passed to the action
            function when an action is called.
        """
        if (
            action_type not in self._actions
            or action_id not in self._actions[action_type]
        ):
            _LOGGER.error(
                "No action registered for type %s or id %s", action_type, action_id
            )
            return

        action = self._actions[action_type][action_id]

        await action(**kwargs)

class ActionType(dotdict):
    """Represent an action type."""

    def __getattr__(self, action_id):
        """Return registered action for an action id."""
        try:
            return self[action_id]
        except KeyError as exc:
            raise MissingActionError(action_id) from exc

class Action:
    """Represent an action."""

    # pylint: disable=too-few-public-methods

    def __init__(self, action_type, action_id, func, schema):
        """Set up the instance."""
        self.action_type = action_type
        self.action_id = action_id
        self.func = func
        self.schema = schema

    async def __call__(self, **kwargs):
        """Call action."""
        silent = kwargs.get("silent", False)
        try:
            kwargs = self.schema(kwargs)
        except vol.Invalid as exc:
            _LOGGER.log(
                logging.DEBUG if silent else logging.ERROR,
                "Invalid action call parameters %s: %s for action: %s.%s",
                kwargs,
                exc,
                self.action_type,
                self.action_id,
            )
            return
        _LOGGER.log(
            logging.DEBUG if silent else logging.INFO,
            "Calling action %s.%s: %s",
            self.action_type,
            self.action_id,
            kwargs,
        )
        try:
            async with async_timeout(ACTION_TIMEOUT):
                await self.func(action_id=self.action_id, **kwargs)
        except asyncio.TimeoutError:
            _LOGGER.error(
                "Action %s.%s. timed out after %s seconds",
                self.action_type,
                self.action_id,
                ACTION_TIMEOUT,
            )
        except CamAcqError as exc:
            _LOGGER.error(
                "Failed to call action %s.%s: %s", self.action_type, self.action_id, exc
            )
            raise

def loop_exception_handler(loop, context):
    """Handle exceptions inside the event loop."""
    kwargs = {}
    exc = context.get("exception")
    if exc:
        kwargs["exc_info"] = exc

    _LOGGER.error("Error running job: %s", context["message"], **kwargs)

# pylint: disable=too-few-public-methods
class CamAcqStartEvent(Event):
    """An event fired when camacq has started."""

    __slots__ = ()

    event_type = CAMACQ_START_EVENT

class CamAcqStopEvent(Event):
    """An event fired when camacq is about to stop."""

    __slots__ = ()

    event_type = CAMACQ_STOP_EVENT

    @property
    def exit_code(self):
        """:int: Return the plate instance of the event."""
        return self.data.get("exit_code")


text:
/*
 * This code was generated by
 * ___ _ _ _ _ _    _ ____    ____ ____ _    ____ ____ _  _ ____ ____ ____ ___ __   __
 *  |  | | | | |    | |  | __ |  | |__| | __ | __ |___ |\ | |___ |__/ |__|  | |  | |__/
 *  |  |_|_| | |___ | |__|    |__| |  | |    |__] |___ | \| |___ |  \ |  |  | |__| |  \
 *
 * Twilio - Api
 * This is the public Twilio REST API.
 *
 * NOTE: This class is auto generated by OpenAPI Generator.
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;

namespace Twilio.Rest.Api.V2010.Account.Call
{

    /// <summary> Subscribe to User Defined Messages for a given Call SID. </summary>
    public class CreateUserDefinedMessageSubscriptionOptions : IOptions<UserDefinedMessageSubscriptionResource>
    {

        ///<summary> The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the User Defined Messages subscription is associated with. This refers to the Call SID that is producing the user defined messages. </summary>
        public string PathCallSid { get; }

        ///<summary> The URL we should call using the `method` to send user defined events to your application. URLs must contain a valid hostname (underscores are not permitted). </summary>
        public Uri Callback { get; }

        ///<summary> The HTTP method Twilio will use when requesting the above `Url`. Either `GET` or `POST`. </summary>
        public Twilio.Http.HttpMethod Method { get; }

        ///<summary> The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that subscribed to the User Defined Messages. </summary>
        public string PathAccountSid { get; set; }

        ///<summary> A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. </summary>
        public string IdempotencyKey { get; set; }

        /// <summary> Construct a new CreateUserDefinedMessageSubscriptionOptions </summary>
        /// <param name="pathCallSid"> The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the User Defined Messages subscription is associated with. This refers to the Call SID that is producing the user defined messages. </param>
        /// <param name="callback"> The URL we should call using the `method` to send user defined events to your application. URLs must contain a valid hostname (underscores are not permitted). </param>
        /// <param name="method"> The HTTP method Twilio will use when requesting the above `Url`. Either `GET` or `POST`. </param>
        public CreateUserDefinedMessageSubscriptionOptions(string pathCallSid, Uri callback, Twilio.Http.HttpMethod method)
        {
            PathCallSid = pathCallSid;
            Callback = callback;
            Method = method;
        }

        /// <summary> Generate the necessary parameters </summary>
        public  List<KeyValuePair<string, string>> GetParams()
        {
            var p = new List<KeyValuePair<string, string>>();

            if (Callback != null)
            {
                p.Add(new KeyValuePair<string, string>("Callback", Serializers.Url(Callback)));
            }
            if (Method != null)
            {
                p.Add(new KeyValuePair<string, string>("Method", Method.ToString()));
            }
            if (IdempotencyKey != null)
            {
                p.Add(new KeyValuePair<string, string>("IdempotencyKey", IdempotencyKey));
            }
            return p;
        }

    }
    /// <summary> Delete a specific User Defined Message Subscription. </summary>
    public class DeleteUserDefinedMessageSubscriptionOptions : IOptions<UserDefinedMessageSubscriptionResource>
    {

        ///<summary> The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the User Defined Message Subscription is associated with. This refers to the Call SID that is producing the User Defined Messages. </summary>
        public string PathCallSid { get; }

        ///<summary> The SID that uniquely identifies this User Defined Message Subscription. </summary>
        public string PathSid { get; }

        ///<summary> The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that subscribed to the User Defined Messages. </summary>
        public string PathAccountSid { get; set; }

        /// <summary> Construct a new DeleteUserDefinedMessageSubscriptionOptions </summary>
        /// <param name="pathCallSid"> The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the User Defined Message Subscription is associated with. This refers to the Call SID that is producing the User Defined Messages. </param>
        /// <param name="pathSid"> The SID that uniquely identifies this User Defined Message Subscription. </param>
        public DeleteUserDefinedMessageSubscriptionOptions(string pathCallSid, string pathSid)
        {
            PathCallSid = pathCallSid;
            PathSid = pathSid;
        }

        /// <summary> Generate the necessary parameters </summary>
        public  List<KeyValuePair<string, string>> GetParams()
        {
            var p = new List<KeyValuePair<string, string>>();

            return p;
        }

    }

}


text:
//
// ImageOrientation.cs: Enum for the orientation of an image
//
// Author:
//   Paul Lange (palango@gmx.de)
//
// Copyright (C) 2009 Paul Lange
//
// This library is free software; you can redistribute it and/or modify
// it  under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
// USA

using System;

namespace TagLib.Image
{
	/**

	  1        2       3      4         5            6           7          8

	888888  888888      88  88      8888888888  88                  88  8888888888
	88          88      88  88      88  88      88  88          88  88      88  88
	8888      8888    8888  8888    88          8888888888  8888888888          88
	88          88      88  88
	88          88  888888  888888

	t-l     t-r     b-r     b-l     l-t         r-t         r-b             l-b

	**/

	/// <summary>
	/// Describes the orientation of an image.
	/// Values are viewed in terms of rows and columns.
	/// </summary>
	public enum ImageOrientation : uint
	{
		/// <summary>
		/// No need to do any transformations.
		/// </summary>
		TopLeft = 1,

		/// <summary>
		/// Mirror image vertically.
		/// </summary>
		TopRight = 2,

		/// <summary>
		/// Rotate image 180 degrees.
		/// </summary>
		BottomRight = 3,

		/// <summary>
		/// Mirror image horizontally
		/// </summary>
		BottomLeft = 4,

		/// <summary>
		/// Mirror image horizontally and rotate 90 degrees clockwise.
		/// </summary>
		LeftTop = 5,

		/// <summary>
		/// Rotate image 90 degrees clockwise.
		/// </summary>
		RightTop = 6,

		/// <summary>
		/// Mirror image vertically and rotate 90 degrees clockwise.
		/// </summary>
		RightBottom = 7,

		/// <summary>
		/// Rotate image 270 degrees clockwise.
		/// </summary>
		LeftBottom = 8
	}
}


text:
from sympy import Symbol, symbols
from sympy.physics.vector import Point, ReferenceFrame
from sympy.physics.mechanics import inertia, Body
from sympy.utilities.pytest import raises

def test_default():
    body = Body('body')
    assert body.name == 'body'
    assert body.loads == []
    point = Point('body_masscenter')
    point.set_vel(body.frame, 0)
    com = body.masscenter
    frame = body.frame
    assert com.vel(frame) == point.vel(frame)
    assert body.mass == Symbol('body_mass')
    ixx, iyy, izz = symbols('body_ixx body_iyy body_izz')
    ixy, iyz, izx = symbols('body_ixy body_iyz body_izx')
    assert body.inertia == (inertia(body.frame, ixx, iyy, izz, ixy, iyz, izx),
                            body.masscenter)

def test_custom_rigid_body():
    # Body with RigidBody.
    rigidbody_masscenter = Point('rigidbody_masscenter')
    rigidbody_mass = Symbol('rigidbody_mass')
    rigidbody_frame = ReferenceFrame('rigidbody_frame')
    body_inertia = inertia(rigidbody_frame, 1, 0, 0)
    rigid_body = Body('rigidbody_body', rigidbody_masscenter, rigidbody_mass,
                      rigidbody_frame, body_inertia)
    com = rigid_body.masscenter
    frame = rigid_body.frame
    rigidbody_masscenter.set_vel(rigidbody_frame, 0)
    assert com.vel(frame) == rigidbody_masscenter.vel(frame)
    assert com.pos_from(com) == rigidbody_masscenter.pos_from(com)

    assert rigid_body.mass == rigidbody_mass
    assert rigid_body.inertia == (body_inertia, rigidbody_masscenter)

    assert hasattr(rigid_body, 'masscenter')
    assert hasattr(rigid_body, 'mass')
    assert hasattr(rigid_body, 'frame')
    assert hasattr(rigid_body, 'inertia')

def test_particle_body():
    #  Body with Particle
    particle_masscenter = Point('particle_masscenter')
    particle_mass = Symbol('particle_mass')
    particle_frame = ReferenceFrame('particle_frame')
    particle_body = Body('particle_body', particle_masscenter, particle_mass,
                         particle_frame)
    com = particle_body.masscenter
    frame = particle_body.frame
    particle_masscenter.set_vel(particle_frame, 0)
    assert com.vel(frame) == particle_masscenter.vel(frame)
    assert com.pos_from(com) == particle_masscenter.pos_from(com)

    assert particle_body.mass == particle_mass
    assert not hasattr(particle_body, "_inertia")
    assert hasattr(particle_body, 'frame')
    assert hasattr(particle_body, 'masscenter')
    assert hasattr(particle_body, 'mass')

def test_particle_body_add_force():
    #  Body with Particle
    particle_masscenter = Point('particle_masscenter')
    particle_mass = Symbol('particle_mass')
    particle_frame = ReferenceFrame('particle_frame')
    particle_body = Body('particle_body', particle_masscenter, particle_mass,
                         particle_frame)

    a = Symbol('a')
    force_vector = a * particle_body.frame.x
    particle_body.apply_force(force_vector, particle_body.masscenter)
    assert len(particle_body.loads) == 1
    point = particle_body.masscenter.locatenew(
        particle_body._name + '_point0', 0)
    point.set_vel(particle_body.frame, 0)
    force_point = particle_body.loads[0][0]

    frame = particle_body.frame
    assert force_point.vel(frame) == point.vel(frame)
    assert force_point.pos_from(force_point) == point.pos_from(force_point)

    assert particle_body.loads[0][1] == force_vector

def test_body_add_force():
    # Body with RigidBody.
    rigidbody_masscenter = Point('rigidbody_masscenter')
    rigidbody_mass = Symbol('rigidbody_mass')
    rigidbody_frame = ReferenceFrame('rigidbody_frame')
    body_inertia = inertia(rigidbody_frame, 1, 0, 0)
    rigid_body = Body('rigidbody_body', rigidbody_masscenter, rigidbody_mass,
                      rigidbody_frame, body_inertia)

    l = Symbol('l')
    Fa = Symbol('Fa')
    point = rigid_body.masscenter.locatenew(
        'rigidbody_body_point0',
        l * rigid_body.frame.x)
    point.set_vel(rigid_body.frame, 0)
    force_vector = Fa * rigid_body.frame.z
    # apply_force with point
    rigid_body.apply_force(force_vector, point)
    assert len(rigid_body.loads) == 1
    force_point = rigid_body.loads[0][0]
    frame = rigid_body.frame
    assert force_point.vel(frame) == point.vel(frame)
    assert force_point.pos_from(force_point) == point.pos_from(force_point)
    assert rigid_body.loads[0][1] == force_vector
    # apply_force without point
    rigid_body.apply_force(force_vector)
    assert len(rigid_body.loads) == 2
    assert rigid_body.loads[1][1] == force_vector
    # passing something else than point
    raises(TypeError, lambda: rigid_body.apply_force(force_vector,  0))
    raises(TypeError, lambda: rigid_body.apply_force(0))

def test_body_add_torque():
    body = Body('body')
    torque_vector = body.frame.x
    body.apply_torque(torque_vector)

    assert len(body.loads) == 1
    assert body.loads[0] == (body.frame, torque_vector)
    raises(TypeError, lambda: body.apply_torque(0))


text:
"""
This module is a collection of the linac accelerator nodes which are the subclasses of
the AccNode class. We cannot use here TEAPOT nodes from the TEAPOT package
directly because we use the field as a parameter for quads and dipole correctors
instead of k1 = 1/(B*rho)*(dB/dr). The RF Cavities are different from the ring RF.
"""

import os
import math

# import the function that creates multidimensional arrays
from orbit.utils import orbitFinalize, NamedObject, ParamsDictObject

# import general accelerator elements and lattice
from orbit.lattice import AccNode, AccActionsContainer, AccNodeBunchTracker

# import teapot base functions from wrapper around C++ functions
from orbit.teapot_base import TPB

# from linac import the RF gap classes
from linac import BaseRfGap, MatrixRfGap

class BaseLinacNode(AccNodeBunchTracker):
	"""
	The base abstract class of the linac accelerator elements hierarchy.
	It cannot be tilted. The direct subclasses of this class will be markers,
	user defined nodes etc.
	"""
	def __init__(self, name = "none"):
		"""
		Constructor. Creates the base linac element. This is a superclass for all linac elements.
		"""
		AccNodeBunchTracker.__init__(self,name)
		self.setType("baseLinacNode")
		self.__linacSeqence = None

	def isRFGap(self):
		"""
		Returns False. The RF Gap node returns True.
		"""
		return False

	def setSequence(self, seq):
		"""
		Sets the seqence.
		"""
		self.__linacSeqence = seq

	def getSequence(self):
		"""
		Returns the seqence.
		"""
		return self.__linacSeqence

	def trackDesign(self, paramsDict):
		"""
		The RF First Gap nodes will reload this method to setup the design time of passage
		of the bunch through this node
		"""
		self.track(paramsDict)

class MarkerLinacNode(BaseLinacNode):
	"""
	This is a marker. It does nothing. If the user wants to perform operations with bunch
	he/shi should specify tracking and design tracking functions.
	"""
	def __init__(self, name = "none"):
		BaseLinacNode.__init__(self,name)
		self.setType("markerLinacNode")

class LinacNode(BaseLinacNode):
	"""
	The abstract class of the linac accelerator elements hierarchy that can be tilted.
	"""
	def __init__(self, name = "none"):
		BaseLinacNode.__init__(self,name)
		self.__tiltNodeIN  = TiltElement()
		self.__tiltNodeOUT = TiltElement()
		self.__tiltNodeIN.setName(name+"_tilt_in")
		self.__tiltNodeOUT.setName(name+"_tilt_out")
		self.addChildNode(self.__tiltNodeIN,AccNode.ENTRANCE)
		self.addChildNode(self.__tiltNodeOUT,AccNode.EXIT)
		self.addParam("tilt",self.__tiltNodeIN.getTiltAngle())
		self.setType("linacNode")

	def setTiltAngle(self, angle = 0.):
		"""
		Sets the tilt angle for the tilt operation.
		"""
		self.setParam("tilt", angle)
		self.__tiltNodeIN.setTiltAngle(angle)
		self.__tiltNodeOUT.setTiltAngle( (-1.0) * angle)

	def getTiltAngle(self):
		"""
		Returns the tilt angle for the tilt operation.
		"""
		return self.__tiltNodeIN.getTiltAngle()

	def getNodeTiltIN(self):
		"""
		Returns the Tilt Node instance before this node
		"""
		return self.__tiltNodeIN

	def getNodeTiltOUT(self):
		"""
		Returns the  Tilt Node instance after this node
		"""
		return self.__tiltNodeOUT

class LinacMagnetNode(LinacNode):
	"""
	The abstract class of the linac magnet.
	"""
	def __init__(self, name = "none"):
		LinacNode.__init__(self,name)
		self.__fringeFieldIN = FringeField(self)
		self.__fringeFieldOUT = FringeField(self)
		self.__fringeFieldIN.setName(name+"_fringe_in")
		self.__fringeFieldOUT	.setName(name+"_fringe_out")
		self.addChildNode(self.__fringeFieldIN,AccNode.ENTRANCE)
		self.getChildNodes(AccNode.EXIT).insert(0,self.__fringeFieldOUT)
		self.setType("linacMagnet")

	def getNodeFringeFieldIN(self):
		"""
		Returns the FringeField instance before this node
		"""
		return self.__fringeFieldIN

	def getNodeFringeFieldOUT(self):
		"""
		Returns the FringeField instance after this node
		"""
		return self.__fringeFieldOUT

	def setFringeFieldFunctionIN(self, trackFunction = None):
		"""
		Sets the fringe field function that will track the bunch
		through the fringe at the entrance of the node.
		"""
		self.__fringeFieldIN.setFringeFieldFunction(trackFunction)

	def setFringeFieldFunctionOUT(self, trackFunction = None):
		"""
		Sets the fringe field function that will track the bunch
		through the fringe at the exit of the element.
		"""
		self.__fringeFieldOUT.setFringeFieldFunction(trackFunction)

	def getFringeFieldFunctionIN(self, trackFunction = None):
		"""
		Returns the fringe field function that will track the bunch
		through the fringe at the entrance of the node.
		"""
		return self.__fringeFieldIN.getFringeFieldFunction()

	def getFringeFieldFunctionOUT(self, trackFunction = None):
		"""
		Returns the fringe field function that will track the bunch
		through the fringe at the exit of the element.
		"""
		return self.__fringeFieldOUT.getFringeFieldFunction()

	def setUsageFringeFieldIN(self,usage = True):
		"""
		Sets the property describing if the IN fringe
		field will be used in calculation.
		"""
		self.__fringeFieldIN.setUsage(usage)

	def getUsageFringeFieldIN(self):
		"""
		Returns the property describing if the IN fringe
		field will be used in calculation.
		"""
		return self.__fringeFieldIN.getUsage()

	def setUsageFringeFieldOUT(self,usage = True):
		"""
		Sets the property describing if the OUT fringe
		field will be used in calculation.
		"""
		self.__fringeFieldOUT.setUsage(usage)

	def getUsageFringeFieldOUT(self):
		"""
		Returns the property describing if the OUT fringe
		field will be used in calculation.
		"""
		return self.__fringeFieldOUT.getUsage()

#-----------------------------------------------------
#    LINAC ABST NODES ELEMENTS
#-----------------------------------------------------

class Drift(BaseLinacNode):
	"""
	Drift element.
	"""
	def __init__(self, name = "drift"):
		"""
		Constructor. Creates the Drift element.
		"""
		BaseLinacNode.__init__(self,name)
		self.setType("drift")

	def track(self, paramsDict):
		"""
		The drift class implementation of the AccNode class track(probe) method.
		"""
		length = self.getLength(self.getActivePartIndex())
		bunch = paramsDict["bunch"]
		TPB.drift(bunch, length)

class Quad(LinacMagnetNode):
	"""
	Quad Combined Function TEAPOT element.
	"""
	def __init__(self, name = "quad"):
		"""
		Constructor. Creates the Quad Combined Function element .
		"""
		LinacMagnetNode.__init__(self,name)
		self.addParam("dB/dr",0.)
		self.addParam("poles",[])
		self.addParam("kls",[])
		self.addParam("skews",[])
		self.setnParts(2)
		self.setType("linacQuad")

		# B*rho = 3.335640952*momentum [T*m] if momentum in GeV/c
		def fringeIN(node,paramsDict):
			usageIN = node.getUsage()
			if(not usageIN):
				return
			bunch = paramsDict["bunch"]
			momentum = bunch.getSyncParticle().momentum()
			kq = node.getParam("dB/dr")/(3.335640952*momentum)
			poleArr = node.getParam("poles")
			klArr = node.getParam("kls")
			skewArr = node.getParam("skews")
			length = paramsDict["parentNode"].getLength()
			TPB.quadfringeIN(bunch,kq)
			if(length == 0.):
				return
			for i in xrange(len(poleArr)):
				pole = poleArr[i]
				k = klArr[i]*kq
				skew = skewArr[i]
				TPB.multpfringeIN(bunch,pole,k,skew)

		def fringeOUT(node,paramsDict):
			usageOUT = node.getUsage()
			if(not usageOUT):
				return
			bunch = paramsDict["bunch"]
			momentum = bunch.getSyncParticle().momentum()
			kq = node.getParam("dB/dr")/(3.335640952*momentum)
			poleArr = node.getParam("poles")
			klArr = node.getParam("kls")
			skewArr = node.getParam("skews")
			length = paramsDict["parentNode"].getLength()
			bunch = paramsDict["bunch"]
			TPB.quadfringeOUT(bunch,kq)
			if(length == 0.):
				return
			for i in xrange(len(poleArr)):
				pole = poleArr[i]
				k = klArr[i]*kq
				skew = skewArr[i]
				TPB.multpfringeOUT(bunch,pole,k,skew)

		self.setFringeFieldFunctionIN(fringeIN)
		self.setFringeFieldFunctionOUT(fringeOUT)
		self.getNodeTiltIN().setType("quad tilt in")
		self.getNodeTiltOUT().setType("quad tilt out")
		self.getNodeFringeFieldIN().setType("quad fringe in")
		self.getNodeFringeFieldOUT().setType("quad fringe out")

	def initialize(self):
		"""
		The  Quad Combined Function class implementation
		of the AccNode class initialize() method.
		"""
		nParts = self.getnParts()
		if(nParts < 2 and nParts%2 != 0):
			msg = "The Quad Combined Function class instance should have no less than 2 and even number of parts!"
			msg = msg + os.linesep
			msg = msg + "Method initialize():"
			msg = msg + os.linesep
			msg = msg + "Name of element=" + self.getName()
			msg = msg + os.linesep
			msg = msg + "Type of element=" + self.getType()
			msg = msg + os.linesep
			msg = msg + "nParts =" + str(nParts)
			orbitFinalize(msg)
		lengthIN = (self.getLength()/(nParts - 1))/2.0
		lengthOUT = (self.getLength()/(nParts - 1))/2.0
		lengthStep = lengthIN + lengthOUT
		self.setLength(lengthIN,0)
		self.setLength(lengthOUT,nParts - 1)
		for i in xrange(nParts-2):
			self.setLength(lengthStep,i+1)

	def track(self, paramsDict):
		"""
		The Quad Combined Function TEAPOT  class implementation
		of the AccNode class track(probe) method.
		"""
		bunch = paramsDict["bunch"]
		momentum = bunch.getSyncParticle().momentum()
		kq = self.getParam("dB/dr")/(3.335640952*momentum)
		nParts = self.getnParts()
		index = self.getActivePartIndex()
		length = self.getLength(index)
		poleArr = self.getParam("poles")
		klArr = self.getParam("kls")
		skewArr = self.getParam("skews")
		#print "debug name =",self.getName()," kq=",kq,"  L=",self.getLength()
		if(index == 0):
			TPB.quad1(bunch, length, kq)
			return
		if(index > 0 and index < (nParts-1)):
			TPB.quad2(bunch, length/2.0)
			for i in xrange(len(poleArr)):
				pole = poleArr[i]
				kl = klArr[i]/(nParts - 1)
				skew = skewArr[i]
				TPB.multp(bunch,pole,kl,skew)
			TPB.quad2(bunch, length/2.0)
			TPB.quad1(bunch, length, kq)
			return
		if(index == (nParts-1)):
			#print "debug before xp",	bunch.xp(0)
			TPB.quad2(bunch, length)
			for i in xrange(len(poleArr)):
				pole = poleArr[i]
				kl = klArr[i]*kq*length/(nParts - 1)
				skew = skewArr[i]
				TPB.multp(bunch,pole,kl,skew)
			TPB.quad2(bunch, length)
			TPB.quad1(bunch, length, kq)
			#print "debug after xp",	bunch.xp(0)
		return

class Bend(LinacMagnetNode):
	"""
	Bend Combined Functions TEAPOT element.
	"""
	def __init__(self, name = "bend no name"):
		"""
		Constructor. Creates the Bend Combined Functions TEAPOT element .
		"""
		LinacMagnetNode.__init__(self,name)
		self.addParam("poles",[])
		self.addParam("kls",[])
		self.addParam("skews",[])

		self.addParam("ea1",0.)
		self.addParam("ea2",0.)
		self.addParam("rho",0.)
		self.addParam("theta",1.0e-36)

		self.setnParts(2)
                self.setType("bend linac")
                self.setUsageFringeFieldIN(True)
                self.setUsageFringeFieldOUT(True)

		def fringeIN(node,paramsDict):
                        bunch = paramsDict["bunch"]
                        length = paramsDict["parentNode"].getLength()
			usageIN = node.getUsage()
			e = node.getParam("ea1")
			rho = node.getParam("rho")
			poleArr = node.getParam("poles")
                        klArr =  [-x*bunch.charge()*length for x in self.getParam("kls")]
			skewArr = node.getParam("skews")
			nParts = paramsDict["parentNode"].getnParts()
			if(e != 0.):
				inout = 0
				TPB.wedgedrift(bunch,e,inout)
				if(usageIN):
					frinout = 0
					TPB.wedgerotate(bunch, e, frinout)
					TPB.bendfringeIN(bunch, rho)
					if(length != 0.):
						for i in xrange(len(poleArr)):
							pole = poleArr[i]
							kl = klArr[i]/length
							skew = skewArr[i]
							TPB.multpfringeIN(bunch,pole,kl,skew)
					frinout = 1
					TPB.wedgerotate(bunch, e, frinout)
				TPB.wedgebendCF(bunch, e, inout, rho, len(poleArr), poleArr, klArr, skewArr, nParts - 1)
			else:
				if(usageIN):
					TPB.bendfringeIN(bunch, rho)
					if(length != 0.):
						for i in xrange(len(poleArr)):
							pole = poleArr[i]
							kl = klArr[i]/length
							skew = skewArr[i]
							TPB.multpfringeIN(bunch,pole,kl,skew)

		def fringeOUT(node,paramsDict):
                        bunch = paramsDict["bunch"]
                        length = paramsDict["parentNode"].getLength()
			usageOUT = node.getUsage()
			e = node.getParam("ea2")
			rho = node.getParam("rho")
			poleArr = node.getParam("poles")
                        klArr =  [-x*bunch.charge()*length for x in self.getParam("kls")]
			skewArr = node.getParam("skews")
                        nParts = paramsDict["parentNode"].getnParts()
			if(e != 0.):
				inout = 1
				TPB.wedgebendCF(bunch, e, inout, rho, len(poleArr), poleArr, klArr, skewArr, nParts - 1)
				if(usageOUT):
					frinout = 0
					TPB.wedgerotate(bunch, -e, frinout)
					TPB.bendfringeOUT(bunch, rho)
					if(length != 0.):
						for i in xrange(len(poleArr)):
							pole = poleArr[i]
							kl = klArr[i]/length
							skew = skewArr[i]
							TPB.multpfringeOUT(bunch,pole,kl,skew)
					frinout = 1
					TPB.wedgerotate(bunch, -e, frinout)
				TPB.wedgedrift(bunch,e,inout)
			else:
				if(usageOUT):
					TPB.bendfringeOUT(bunch, rho)
					if(length != 0.):
						for i in xrange(len(poleArr)):
							pole = poleArr[i]
							kl = klArr[i]/length
							skew = skewArr[i]
							TPB.multpfringeOUT(bunch,pole,kl,skew)

		self.setFringeFieldFunctionIN(fringeIN)
		self.setFringeFieldFunctionOUT(fringeOUT)

	def initialize(self):
		"""
		The  Bend Combined Functions TEAPOT class implementation of
		the AccNode class initialize() method.
		"""
		nParts = self.getnParts()
		if(nParts < 2):
			msg = "The Bend Combined Functions TEAPOT class instance should have more than 2 parts!"
			msg = msg + os.linesep
			msg = msg + "Method initialize():"
			msg = msg + os.linesep
			msg = msg + "Name of element=" + self.getName()
			msg = msg + os.linesep
			msg = msg + "Type of element=" + self.getType()
			msg = msg + os.linesep
			msg = msg + "nParts =" + str(nParts)
			orbitFinalize(msg)
		rho = self.getLength()/self.getParam("theta")
		self.addParam("rho",rho)
		lengthIN = (self.getLength()/(nParts - 1))/2.0
		lengthOUT = (self.getLength()/(nParts - 1))/2.0
		lengthStep = lengthIN + lengthOUT
		self.setLength(lengthIN,0)
		self.setLength(lengthOUT,nParts - 1)
		for i in xrange(nParts-2):
			self.setLength(lengthStep,i+1)

	def track(self, paramsDict):
		"""
		The Bend Combined Functions TEAPOT  class implementation of
		the AccNodeBunchTracker class track(probe) method.
		"""
                bunch = paramsDict["bunch"]
		nParts = self.getnParts()
		index = self.getActivePartIndex()
		length = self.getLength(index)
		poleArr = self.getParam("poles")
		klArr =  [-x*bunch.charge()*self.getLength() for x in self.getParam("kls")]
		skewArr = self.getParam("skews")
		theta = self.getParam("theta")/(nParts - 1)
		if(index == 0):
			TPB.bend1(bunch, length, theta/2.0)
			return
		if(index > 0 and index < (nParts-1)):
			TPB.bend2(bunch, length/2.0)
			TPB.bend3(bunch, theta/2.0)
			TPB.bend4(bunch,theta/2.0)
			for i in xrange(len(poleArr)):
				pole = poleArr[i]
				kl = klArr[i]/(nParts - 1)
				skew = skewArr[i]
				TPB.multp(bunch,pole,kl,skew)
			TPB.bend4(bunch,theta/2.0)
			TPB.bend3(bunch, theta/2.0)
			TPB.bend2(bunch, length/2.0)
			TPB.bend1(bunch, length, theta)
			return
		if(index == (nParts-1)):
			TPB.bend2(bunch, length)
			TPB.bend3(bunch, theta/2.0)
			TPB.bend4(bunch, theta/2.0)
			for i in xrange(len(poleArr)):
				pole = poleArr[i]
				kl = klArr[i]/(nParts - 1)
				skew = skewArr[i]
				TPB.multp(bunch,pole,kl,skew)
			TPB.bend4(bunch, theta/2.0)
			TPB.bend3(bunch, theta/2.0)
			TPB.bend2(bunch, length)
			TPB.bend1(bunch, length, theta/2.0)
		return

class DCorrectorH(LinacMagnetNode):
	"""
	The Horizontal Dipole Corrector.
	"""
	def __init__(self, name = "correctorh"):
		"""
		Constructor. Creates the Horizontal Dipole Corrector element .
		"""
		LinacMagnetNode.__init__(self,name)
		self.addParam("B",0.)
		self.addParam("effLength",0.)
		self.setType("dch")
		self.setnParts(1)

	def track(self, paramsDict):
		"""
		The Horizontal Dipole Corrector class implementation of
		the AccNode class track(probe) method.
		"""
		nParts = self.getnParts()
		index = self.getActivePartIndex()
		length = self.getParam("effLength")/nParts
		field = self.getParam("B")
		bunch = paramsDict["bunch"]
		syncPart = bunch.getSyncParticle()
		momentum = syncPart.momentum()
		q = bunch.charge()
		# dp/p = Q*c*B*L/p p in GeV/c c = 2.99792*10^8/10^9
		kick = q*field*length*0.299792/momentum
		TPB.kick(bunch,kick,0.,0.)

class DCorrectorV(LinacMagnetNode):
	"""
	The Vertical Dipole Corrector.
	"""
	def __init__(self, name = "correctorv"):
		"""
		Constructor. Creates the Vertical Dipole Corrector element .
		"""
		LinacMagnetNode.__init__(self,name)
		self.addParam("B",0.)
		self.addParam("effLength",0.)
		self.setType("dcv")
		self.setnParts(1)

	def track(self, paramsDict):
		"""
		The Vertical Dipole Corrector class implementation of
		the AccNode class track(probe) method.
		"""
		nParts = self.getnParts()
		index = self.getActivePartIndex()
		length = self.getParam("effLength")/nParts
		field = self.getParam("B")
		bunch = paramsDict["bunch"]
		syncPart = bunch.getSyncParticle()
		momentum = syncPart.momentum()
		q = bunch.charge()
		# dp/p = Q*c*B*L/p p in GeV/c, c = 2.99792*10^8/10^9
		kick = q*field*length*0.299792/momentum
		TPB.kick(bunch,0,kick,0.)

class BaseRF_Gap(BaseLinacNode):
	"""
	The simplest RF gap representation. The only E*T*L defines all effects of the node.
	By default the Matrix RF Gap model is used. This model can be replaced later with
	a more complex RF gap model by using the setCppGapModel(...) method.
	"""
	def __init__(self, name = "baserfgap"):
		"""
		Constructor for the simplest RF gap. E0TL parameter is in GeV. Phases are in radians.
		It has 3 parts with lengthes: 0.5 + 0. + 0.5
		"""
		BaseLinacNode.__init__(self,name)
		self.addParam("E0TL",0.)
		self.addParam("modePhase",0.)
		self.addParam("gap_phase",0.)
		self.addParam("rfCavity", None)
		self.setType("baserfgap")
		self.__isFirstGap = False
		self.setnParts(3)
		self.cppGapModel = MatrixRfGap()
		#self.cppGapModel = BaseRfGap()

	def setnParts(self, n = 3):
		"""
		Method. Sets the number of body parts of the node. For the RF gap it will be only 3.
		"""
		BaseLinacNode.setnParts(self,3)

	def setCppGapModel(self, cppGapModel = MatrixRfGap()):
		"""
		This method will set the fast c++ simple model for the RF Gap.
		By default it is Matrix RF Gap model which is a linear transport matrix.
		"""
		self.cppGapModel = cppGapModel

	def initialize(self):
		"""
		The Ring RF TEAPOT class implementation
		of the AccNode class initialize() method.
		"""
		nParts = self.getnParts()
		if(nParts != 3):
			msg = "The simple Rf gap should have 3 parts!"
			msg = msg + os.linesep
			msg = msg + "Method initialize():"
			msg = msg + os.linesep
			msg = msg + "Name of element=" + self.getName()
			msg = msg + os.linesep
			msg = msg + "Type of element=" + self.getType()
			msg = msg + os.linesep
			msg = msg + "nParts =" + str(nParts)
			msg = msg + os.linesep
			msg = msg + "lenght =" + str(self.getLength())
			orbitFinalize(msg)
		length = self.getLength()
		self.setLength(length/2.0,0)
		self.setLength(0.,1)
		self.setLength(length/2.0,2)

	def isRFGap(self):
		"""
		Returns True.
		"""
		return True

	def isFirstRFGap(self):
		"""
		Returns True if it is the first gap in RF cavity.
		"""
		return self.__isFirstGap

	def setAsFirstRFGap(self, isFirst):
		"""
		Sets if it is the first gap in RF cavity.
		"""
		self.__isFirstGap = isFirst

	def setRF_Cavity(self, rf_cav):
		"""
		Sets the parent RF Cavity.
		"""
		self.addParam("rfCavity",rf_cav)

	def getRF_Cavity(self):
		"""
		Returns the parent RF Cavity.
		"""
		return self.getParam("rfCavity")

	def setGapPhase(self, gap_phase):
		"""
		Sets the rf gap phase.
		"""
		self.setParam("gap_phase",gap_phase)

	def getGapPhase(self):
		"""
		Returns the rf gap phase.
		"""
		return self.getParam("gap_phase")

	def track(self, paramsDict):
		"""
		The simplest RF gap class implementation of
		the AccNode class track(probe) method.
		"""
		index = self.getActivePartIndex()
		length = self.getLength(index)
		bunch = paramsDict["bunch"]
		syncPart = bunch.getSyncParticle()
		if(index == 0 or index == 2):
			gapOffset = 0.
			if(self.hasParam("gapOffset")): gapOffset = self.getParam("gapOffset")
			if(index == 2): gapOffset = -gapOffset
			TPB.drift(bunch, length + gapOffset)
			return
		E0TL = self.getParam("E0TL")
		modePhase = self.getParam("modePhase")*math.pi
		rfCavity = self.getRF_Cavity()
		frequency = rfCavity.getFrequency()
		rfPhase = rfCavity.getPhase() + modePhase
		rf_ampl = rfCavity.getAmp()
		phase = rfPhase
		arrival_time = syncPart.time()
		designArrivalTime = rfCavity.getDesignArrivalTime()
		if(self.__isFirstGap):
			if(rfCavity.isDesignSetUp()):
				#print "debug RF =",self.getName(),"  phase=",(phase*180./math.pi - 180.)
				phase = math.fmod(frequency*(arrival_time - designArrivalTime)*2.0*math.pi + rfPhase,2.0*math.pi)
				#print "debug RF =",self.getName(),"  phase=",(phase*180./math.pi - 180.)
			else:
				sequence = self.getSequence()
				accLattice = sequence.getLinacAccLattice()
				msg = "The BaseRF_Gap class. You have to run trackDesign on the LinacAccLattice first to initialize all RF Cavities' phases!"
				msg = msg + os.linesep
				msg = msg + "Lattice =" + accLattice.getName()
				msg = msg + os.linesep
				msg = msg + "Sequence =" + sequence.getName()
				msg = msg + os.linesep
				msg = msg + "RF Cavity =" + rfCavity.getName()
				msg = msg + os.linesep
				msg = msg + "Name of element=" + self.getName()
				msg = msg + os.linesep
				msg = msg + "Type of element=" + self.getType()
				msg = msg + os.linesep
				orbitFinalize(msg)
		else:
			phase = math.fmod(frequency*(arrival_time - designArrivalTime)*2.0*math.pi+rfPhase,2.0*math.pi)
		#------------------------------------------------------
		#call rf gap with E0TL phase phase of the gap and a longitudinal shift parameter
		self.cppGapModel.trackBunch(bunch,frequency,E0TL,phase)
		self.setGapPhase(phase)
		#print "debug delta_time in deg=",frequency*(arrival_time - designArrivalTime)*380.
		#print "debug RF =",self.getName()," E0TL=",E0TL," phase=",(phase*180./math.pi - 180.)," eKin[MeV]=",bunch.getSyncParticle().kinEnergy()*1.0e+3

	def trackDesign(self, paramsDict):
		"""
		The RF First Gap node setups the design time of passage
		of the bunch through this node.
		"""
		index = self.getActivePartIndex()
		length = self.getLength(index)
		bunch = paramsDict["bunch"]
		if(index == 0 or index == 2):
			gapOffset = 0.
			if(self.hasParam("gapOffset")): gapOffset = self.getParam("gapOffset")
			if(index == 2): gapOffset = -gapOffset
			TPB.drift(bunch, length + gapOffset)
			return
		E0TL = self.getParam("E0TL")
		rfCavity = self.getRF_Cavity()
		modePhase = self.getParam("modePhase")*math.pi
		arrival_time = bunch.getSyncParticle().time()
		frequency = rfCavity.getFrequency()
		rfPhase = rfCavity.getPhase() + modePhase
		rf_ampl = rfCavity.getDesignAmp()
		phase = rfPhase
		if(self.__isFirstGap):
			rfCavity.setDesignArrivalTime(arrival_time)
			rfCavity.setDesignSetUp(True)
			rfCavity._setDesignPhase(rfCavity.getPhase())
			rfCavity._setDesignAmp(rfCavity.getAmp())
		else:
			first_gap_arr_time = rfCavity.getDesignArrivalTime()
			#print "debug name=",self.getName()," delta_phase=",frequency*(arrival_time - first_gap_arr_time)*360.0," rfPhase=",rfPhase*180/math.pi
			phase = math.fmod(frequency*(arrival_time - first_gap_arr_time)*2.0*math.pi+rfPhase,2.0*math.pi)
		#print "debug name=",self.getName()," arr_time=",arrival_time," phase=",phase*180./math.pi," E0TL=",E0TL*1.0e+3," freq=",frequency
		#------------------------------------------------------
		#call rf gap with E0TL phase phase of the gap and a longitudinal shift parameter
		self.cppGapModel.trackBunch(bunch,frequency,E0TL,phase)
		self.setGapPhase(phase)
		#syncPart = bunch.getSyncParticle()
		#eKin = syncPart.kinEnergy()
		#print "debug design RF=",self.getName()," E0TL=",E0TL," phase=",(phase*180./math.pi- 180.)," eKin[MeV]=",bunch.getSyncParticle().kinEnergy()*1.0e+3

class TiltElement(BaseLinacNode):
	"""
	The class to do tilt at the entrance of an element.
	"""
	def __init__(self, name = "tilt no name", angle = 0.):
		"""
		Constructor. Creates the Tilt element.
		"""
		AccNode.__init__(self,name)
		self.__angle = angle
		self.setType("tilt teapot")

	def setTiltAngle(self, angle = 0.):
		"""
		Sets the tilt angle for the tilt operation.
		"""
		self.__angle = angle

	def getTiltAngle(self):
		"""
		Returns the tilt angle for the tilt operation.
		"""
		return self.__angle

	def track(self, paramsDict):
		"""
		It is tracking the dictionary with parameters through
		the titlt node.
		"""
		if(self.__angle != 0.):
			bunch = paramsDict["bunch"]
			TPB.rotatexy(bunch,self.__angle)

class FringeField(BaseLinacNode):
	"""
	The class is a base class for the fringe field classes for others elements.
	"""
	def __init__(self,  parentNode,  trackFunction = None , name = "fringe field no name"):
		"""
		Constructor. Creates the Fringe Field element.
		"""
		AccNode.__init__(self,name)
		self.setParamsDict(parentNode.getParamsDict())
		self.__trackFunc = trackFunction
		self.__usage = False
		self.setType("fringeField teapot")

	def track(self, paramsDict):
		"""
		It is tracking the dictionary with parameters through
		the fringe field node.
		"""
		if(self.__trackFunc != None):
			self.__trackFunc(self,paramsDict)

	def setFringeFieldFunction(self, trackFunction = None):
		"""
		Sets the fringe field function that will track the bunch through the fringe.
		"""
		self.__trackFunc = trackFunction

	def getFringeFieldFunction(self):
		"""
		Returns the fringe field function.
		"""
		return self.__trackFunc

	def setUsage(self,usage = True):
		"""
		Sets the boolean flag describing if the fringe
		field will be used in calculation.
		"""
		self.__usage = usage

	def getUsage(self):
		"""
		Returns the boolean flag describing if the fringe
		field will be used in calculation.
		"""
		return self.__usage

#----------------------------------------------------------------
# Classes that are specific for the linac model
#----------------------------------------------------------------

class RF_Cavity(NamedObject,ParamsDictObject):
	"""
	This is the class to keep refernces to the RF Gaps which are BaseLinacNode
	subclasses. This class does not belong to the AccNodes.
	"""
	def __init__(self, name = "none"):
		NamedObject.__init__(self, name)
		ParamsDictObject.__init__(self)
		self.__rfGaps = []
		self.addParam("frequency",0.)
		self.addParam("phase",0.)
		self.addParam("amp",0.)
		self.addParam("designPhase",0.)
		self.addParam("designAmp",0.)
		self.addParam("designArrivalTime",0.)
		self.addParam("isDesignSetUp",False)

	def setDesignSetUp(self,designOnOf):
		""" Sets the design set up information (yes,no). """
		self.setParam("isDesignSetUp",designOnOf)

	def isDesignSetUp(self):
		""" Returns the design set up information (yes,no). """
		return self.getParam("isDesignSetUp")

	def setDesignArrivalTime(self,time):
		""" Sets the design arrival time for the first RF gap. """
		self.setParam("designArrivalTime",time)

	def getDesignArrivalTime(self):
		""" Returns the design arrival time for the first RF gap. """
		return self.getParam("designArrivalTime")

	def _setDesignPhase(self,phase):
		""" Sets the design phase for the first RF gap. This method is called from the design tracking. """
		self.setParam("designPhase",phase)

	def getDesignPhase(self):
		""" Returns the design phase for the first RF gap. """
		return self.getParam("designPhase")

	def _setDesignAmp(self,Amp):
		""" Sets the design Amp for the RF cavity. This method is called from the design tracking."""
		self.setParam("designAmp",Amp)

	def getDesignAmp(self):
		""" Returns the design Amp for the RF cavity. """
		return self.getParam("designAmp")

	def setPhase(self,phase):
		""" Sets the phase for the first RF gap. """
		self.setParam("phase",phase)

	def getPhase(self):
		""" Returns the phase for the first RF gap. """
		return self.getParam("phase")

	def setAmp(self,Amp):
		""" Sets the Amp for RF cavity. """
		self.setParam("Amp",Amp)

	def getAmp(self):
		""" Returns the Amp for RF cavity. """
		return self.getParam("Amp")

	def setFrequency(self,freq):
		""" Sets the frequency in Hz. """
		self.setParam("frequency",freq)

	def getFrequency(self):
		""" Returns the frequency in Hz. """
		return self.getParam("frequency")

	def addRF_GapNode(self,rfGap):
		""" Adds the rf gap to the cavity."""
		self.__rfGaps.append(rfGap)
		rfGap.setRF_Cavity(self)
		if(len(self.__rfGaps) == 1):
			rfGap.setAsFirstRFGap(True)
		else:
			rfGap.setAsFirstRFGap(False)

	def getRF_GapNodes(self):
		""" Returns the array with rf gaps. """
		return self.__rfGaps[:]

class Sequence(NamedObject,ParamsDictObject):
	"""
	This is the class to keep refernces to AccNodes that constitute the accelerator sequence.
	"""
	def __init__(self, name = "none"):
		NamedObject.__init__(self, name)
		ParamsDictObject.__init__(self)
		self.__linacNodes = []
		self.addParam("position",0.)
		self.addParam("length",0.)
		self.addParam("linacAccLattice",None)

	def setLinacAccLattice(self,	lattice):
		self.addParam("linacAccLattice",lattice)

	def getLinacAccLattice(self):
		return self.getParam("linacAccLattice")

	def addNode(self,node, index = -1):
		""" Adds the Linac Node to the sequence. """
		node.setSequence(self)
		if(index < 0):
			self.__linacNodes.append(node)
		else:
			self.__linacNodes.insert(index,node)

	def getNodes(self):
		""" Returns the array with Linac Nodes. """
		return self.__linacNodes

	def setNodes(self, linacNodes):
		""" Set a new set of Linac Nodes. """
		self.__linacNodes = linacNodes

	def setPosition(self, pos):
		""" Sets the position of the sequence. """
		return self.setParam("position",pos)

	def getPosition(self):
		""" Returns the position of the sequence. """
		return self.getParam("position")

	def getLength(self):
		"""
		Returns the total length of the sequence [m].
		"""
		return self.getParam("length")

	def setLength(self, length):
		"""
		Sets the total length of the sequence [m].
		"""
		return self.setParam("length",length)