text:
package resolvers

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/emwalker/digraph/cmd/frontend/models"
	"github.com/emwalker/digraph/cmd/frontend/queries"
	"github.com/emwalker/digraph/cmd/frontend/services"
	perrors "github.com/pkg/errors"
	"github.com/volatiletech/sqlboiler/boil"
	"github.com/volatiletech/sqlboiler/queries/qm"
)

// MutationResolver holds configuration information for a mutation.
type MutationResolver struct {
	*Resolver
}

// Special errors.
var (
	ErrNoAnonymousMutations = errors.New("anonymous users cannot make updates or deletions")
	ErrUnauthorized         = errors.New("you are not allowed to do that")
)

func init() {
	log.SetOutput(os.Stdout)
}

func findRepo(
	ctx context.Context, exec boil.ContextExecutor, actor *models.User, orgLogin, repoName string,
) (*models.Repository, error) {
	log.Printf("Looking for repo %s/%s as user %v", orgLogin, repoName, actor)
	mods := []qm.QueryMod{
		qm.InnerJoin("organizations o on o.id = repositories.organization_id"),
		qm.InnerJoin("organization_members om on o.id = om.organization_id"),
		qm.Where(`
			o.login = ? and repositories.name = ? and om.user_id = ?
		`, orgLogin, repoName, actor.ID),
	}
	return models.Repositories(mods...).One(ctx, exec)
}

type createSessionFunc func(*sql.Tx, *models.User) (*services.CreateSessionResult, error)

func (r *MutationResolver) sessionPayload(
	ctx context.Context, serverSecret string, createSession createSessionFunc,
) (*models.CreateSessionPayload, error) {
	rc := GetRequestContext(ctx)
	actor := rc.Viewer()

	if !rc.InitiatedByServer(serverSecret) {
		log.Printf("Session creation initiated by %s rather than the server", actor)
		return nil, ErrUnauthorized
	}
	log.Printf("Request comes from server, creating session for %s", actor)

	var result *services.CreateSessionResult

	err := queries.Transact(r.DB, func(tx *sql.Tx) error {
		var err error
		result, err = createSession(tx, actor)
		return err
	})

	if err != nil {
		log.Printf("There was a problem creating a session: %s", err)
		return nil, perrors.Wrap(err, "resolvers: failed to create session")
	}

	return &models.CreateSessionPayload{
		Alerts:      result.Alerts,
		UserEdge:    &models.UserEdge{Node: result.User},
		SessionEdge: &models.SessionEdge{Node: result.Session},
	}, nil
}

// CreateGithubSession creates a new session for the user passed in, possibly alongside any existing
// sessions.  If the user is not yet in the database, a new user is created.  Sessions are destroyed
// using DestroySession, which is called when someone logs out of the client.
func (r *MutationResolver) CreateGithubSession(
	ctx context.Context, input models.CreateGithubSessionInput,
) (*models.CreateSessionPayload, error) {
	return r.sessionPayload(ctx, input.ServerSecret, func(tx *sql.Tx, actor *models.User) (*services.CreateSessionResult, error) {
		c := services.New(tx, actor, nil)
		return c.CreateGithubSession(
			ctx, input.Name, input.PrimaryEmail, input.GithubUsername, input.GithubAvatarURL,
		)
	})
}

// CreateGoogleSession creates a new session for the user passed in.  See CreateGithubSession for
// details.
func (r *MutationResolver) CreateGoogleSession(
	ctx context.Context, input models.CreateGoogleSessionInput,
) (*models.CreateSessionPayload, error) {
	return r.sessionPayload(ctx, input.ServerSecret, func(tx *sql.Tx, actor *models.User) (*services.CreateSessionResult, error) {
		c := services.New(tx, actor, nil)
		return c.CreateGoogleSession(
			ctx, input.Name, input.PrimaryEmail, input.GoogleProfileID, input.GoogleAvatarURL,
		)
	})
}

// DeleteAccount deletes the user account and any private data associated with it.  Links and topics
// added to the public repo will not be removed, but the association between the user and the links
// and topics will no longer exist.
func (r *MutationResolver) DeleteAccount(
	ctx context.Context, input models.DeleteAccountInput,
) (*models.DeleteAccountPayload, error) {
	actor := GetRequestContext(ctx).Viewer()

	if actor.IsGuest() {
		return nil, ErrNoAnonymousMutations
	}

	if actor.ID != input.UserID {
		return nil, fmt.Errorf("not allowed to delete account %s", input.UserID)
	}

	c := services.Connection{Exec: r.DB, Actor: actor}
	result, err := c.DeleteAccount(ctx, actor)

	if err != nil {
		return nil, err
	}

	return &models.DeleteAccountPayload{
		Alerts:        result.Alerts,
		DeletedUserID: actor.ID,
	}, nil
}

// DeleteLink sets the parent topics on a topic.
func (r *MutationResolver) DeleteLink(
	ctx context.Context, input models.DeleteLinkInput,
) (*models.DeleteLinkPayload, error) {
	actor := GetRequestContext(ctx).Viewer()

	if actor.IsGuest() {
		return nil, ErrNoAnonymousMutations
	}

	link, err := models.Links(
		qm.InnerJoin("organization_members om on links.organization_id = om.organization_id"),
		qm.Where("links.id = ? and om.user_id = ?", input.LinkID, actor.ID),
		qm.Load("Repository"),
	).One(ctx, r.DB)

	if err != nil {
		log.Printf("There was a problem looking up link: %s", input.LinkID)
		return nil, err
	}
	repo := link.R.Repository

	err = queries.Transact(r.DB, func(tx *sql.Tx) error {
		c := services.Connection{Exec: tx, Actor: actor}

		_, err := c.DeleteLink(ctx, repo, link)
		if err != nil {
			return err
		}

		return nil
	})

	if err != nil {
		log.Printf(
			"%s failed to delete link %s from repo %s: %s", actor, link, repo, err,
		)
	}

	return &models.DeleteLinkPayload{
		ClientMutationID: input.ClientMutationID,
		DeletedLinkID:    input.LinkID,
	}, nil
}

// DeleteSession deletes a user session.
func (r *MutationResolver) DeleteSession(
	ctx context.Context, input models.DeleteSessionInput,
) (*models.DeleteSessionPayload, error) {
	actor := GetRequestContext(ctx).Viewer()

	session, err := actor.Sessions(qm.Where("id = ?", input.SessionID)).One(ctx, r.DB)
	if err != nil {
		return nil, perrors.Wrap(err, "resolvers: failed to fetch session")
	}

	if _, err = session.Delete(ctx, r.DB); err != nil {
		return nil, perrors.Wrap(err, "resolvers: failed to delete session")
	}

	return &models.DeleteSessionPayload{DeletedSessionID: input.SessionID}, nil
}

// DeleteTopic deletes a topic.
func (r *MutationResolver) DeleteTopic(
	ctx context.Context, input models.DeleteTopicInput,
) (*models.DeleteTopicPayload, error) {
	actor := GetRequestContext(ctx).Viewer()

	if actor.IsGuest() {
		return nil, ErrNoAnonymousMutations
	}

	topic, err := fetchTopic(ctx, r.DB, input.TopicID, actor)
	if err != nil {
		log.Printf("There was a problem looking up topic: %s", input.TopicID)
		return nil, perrors.Wrap(err, "resolvers: failed to fetch topic")
	}

	err = queries.Transact(r.DB, func(tx *sql.Tx) error {
		service := services.DeleteTopic{
			Actor: actor,
			Topic: topic,
		}
		if _, err = service.Call(ctx, tx); err != nil {
			log.Printf("There was a problem deleting topic: %#v", topic)
			return err
		}
		return nil
	})
	if err != nil {
		return nil, perrors.Wrap(err, "resolvers: failed to delete topic")
	}

	return &models.DeleteTopicPayload{
		ClientMutationID: input.ClientMutationID,
		DeletedTopicID:   input.TopicID,
	}, nil
}

// DeleteTopicTimeRange deletes a topic.
func (r *MutationResolver) DeleteTopicTimeRange(
	ctx context.Context, input models.DeleteTopicTimeRangeInput,
) (*models.DeleteTopicTimeRangePayload, error) {
	actor := GetRequestContext(ctx).Viewer()

	if actor.IsGuest() {
		return nil, ErrNoAnonymousMutations
	}

	topic, err := fetchTopic(ctx, r.DB, input.TopicID, actor)
	if err != nil {
		log.Printf("There was a problem looking up topic: %s", input.TopicID)
		return nil, err
	}

	c := services.Connection{Exec: r.DB, Actor: actor}
	result, err := c.DeleteTopicTimeRange(ctx, topic)
	if err != nil {
		return nil, perrors.Wrap(err, "resolvers: failed to delete time range")
	}

	return &models.DeleteTopicTimeRangePayload{
		DeletedTimeRangeID: result.DeletedTimeRangeID,
		Topic:              &models.TopicValue{Topic: result.Topic, View: actor.DefaultView()},
	}, nil
}

// ReviewLink marks a link reviewed.
func (r *MutationResolver) ReviewLink(
	ctx context.Context, input models.ReviewLinkInput,
) (*models.ReviewLinkPayload, error) {
	log.Printf("Adding review to link %s", input.LinkID)
	actor := GetRequestContext(ctx).Viewer()

	c := services.Connection{Exec: r.DB, Actor: actor}

	link, err := models.Links(
		qm.InnerJoin("repositories r on r.id = links.repository_id"),
		qm.InnerJoin("organization_members om on om.organization_id = r.organization_id"),
		qm.Where("links.id = ?", input.LinkID),
		qm.Where("om.user_id = ?", actor.ID),
	).One(ctx, r.DB)

	if err != nil {
		log.Printf("Did not find link %s in the repos visible to %s: %s", input.LinkID, actor, err)
		return nil, err
	}

	result, err := c.ReviewLink(ctx, link, input.Reviewed)
	if err != nil {
		return nil, err
	}

	return &models.ReviewLinkPayload{
		Link: &models.LinkValue{result.Link, false, actor.DefaultView()},
	}, nil
}

// SelectRepository selects the repository for the current user.
func (r *MutationResolver) SelectRepository(
	ctx context.Context, input models.SelectRepositoryInput,
) (*models.SelectRepositoryPayload, error) {
	repoID := input.RepositoryID
	actor := GetRequestContext(ctx).Viewer()
	log.Printf("Atempting to select repository %v for %#v", repoID, actor)

	var err error
	var repo *models.Repository

	if repoID == nil {
		exists, err := actor.SelectedRepository().Exists(ctx, r.DB)
		if exists {
			log.Printf("Unselecting repository from %s", actor.ID)
			repo, err = actor.SelectedRepository().One(ctx, r.DB)

			if err = actor.RemoveSelectedRepository(ctx, r.DB, repo); err != nil {
				return nil, err
			}

			if err = actor.Reload(ctx, r.DB); err != nil {
				return nil, err
			}
		}
		return &models.SelectRepositoryPayload{nil, actor}, nil
	}

	repo = &models.Repository{ID: *repoID}
	log.Printf("Selecting repository %s for user %s", repo.ID, actor.ID)
	if err = actor.SetSelectedRepository(ctx, r.DB, false, repo); err != nil {
		return nil, err
	}

	log.Printf("Reloading repo %s", repo.ID)
	if err = repo.Reload(ctx, r.DB); err != nil {
		return nil, err
	}

	log.Printf("Reloading user %s", actor.ID)
	if err = actor.Reload(ctx, r.DB); err != nil {
		return nil, err
	}

	return &models.SelectRepositoryPayload{repo, actor}, nil
}

// UpsertTopic creates a new topic.
func (r *MutationResolver) UpsertTopic(
	ctx context.Context, input models.UpsertTopicInput,
) (*models.UpsertTopicPayload, error) {
	actor := GetRequestContext(ctx).Viewer()

	var result *services.UpsertTopicResult
	var err error
	var repo *models.Repository

	err = queries.Transact(r.DB, func(tx *sql.Tx) error {
		repo, err = findRepo(ctx, tx, actor, input.OrganizationLogin, input.RepositoryName)
		if err != nil {
			return err
		}

		c := services.Connection{Exec: tx, Actor: actor}
		result, err = c.UpsertTopic(
			ctx,
			repo,
			input.Name,
			input.Description,
			input.TopicIds,
		)

		return err
	})

	if err != nil {
		return nil, fmt.Errorf("UpsertTopic: %s", err)
	}

	if result.Topic == nil {
		return &models.UpsertTopicPayload{Alerts: result.Alerts}, nil
	}

	return &models.UpsertTopicPayload{
		Alerts: result.Alerts,
		TopicEdge: &models.TopicEdge{
			Node: &models.TopicValue{result.Topic, result.TopicCreated, actor.DefaultView()},
		},
	}, nil
}

// UpdateSynonyms updates the synonyms for a topic.
func (r *MutationResolver) UpdateSynonyms(
	ctx context.Context, input models.UpdateSynonymsInput,
) (*models.UpdateSynonymsPayload, error) {
	actor := GetRequestContext(ctx).Viewer()

	var result *services.UpdateSynonymsResult
	var err error

	topic, err := fetchTopic(ctx, r.DB, input.TopicID, actor)
	if err != nil {
		return nil, err
	}

	synonyms := make([]models.Synonym, len(input.Synonyms))

	for i, synonym := range input.Synonyms {
		locale := models.LocaleIdentifier(synonym.Locale)
		if !locale.IsValid() {
			return nil, fmt.Errorf("not a valid locale: %s", synonym.Locale)
		}

		synonyms[i] = models.Synonym{
			Locale: synonym.Locale,
			Name:   synonym.Name,
		}
	}

	err = queries.Transact(r.DB, func(tx *sql.Tx) error {
		c := services.Connection{Exec: tx, Actor: actor}

		result, err = c.UpdateSynonyms(ctx, topic, synonyms)
		if err != nil {
			return err
		}

		return nil
	})

	if err != nil {
		log.Printf(
			"%s failed update synonyms (%v) topic %s: %s", actor, synonyms, topic.ID, err,
		)
	}

	return &models.UpdateSynonymsPayload{
		Alerts: result.Alerts,
		Topic:  &models.TopicValue{Topic: topic, View: actor.DefaultView()},
	}, nil
}

// UpdateTopic updates the fields on a topic.
func (r *MutationResolver) UpdateTopic(
	ctx context.Context, input models.UpdateTopicInput,
) (*models.UpdateTopicPayload, error) {
	actor := GetRequestContext(ctx).Viewer()

	c := services.New(r.DB, actor, nil)

	topic, err := models.Topics(queries.Topic(actor.ID, input.ID)...).One(ctx, r.DB)
	if err != nil {
		log.Printf("No topic %s is visible to %s", input.ID, actor)
		return nil, err
	}

	log.Printf("%s attempting to update %s", actor, topic)
	result, err := c.UpdateTopic(ctx, topic, input.Name, input.Description)
	if err != nil {
		log.Printf("There was a problem updating %s", topic)
		return nil, err
	}

	return &models.UpdateTopicPayload{
		Alerts: result.Alerts,
		Topic:  &models.TopicValue{topic, false, actor.DefaultView()},
	}, nil
}

// UpdateLinkTopics sets the parent topics on a link.
func (r *MutationResolver) UpdateLinkTopics(
	ctx context.Context, input models.UpdateLinkTopicsInput,
) (*models.UpdateLinkTopicsPayload, error) {
	actor := GetRequestContext(ctx).Viewer()
	var result *services.UpdateLinkTopicsResult

	err := queries.Transact(r.DB, func(tx *sql.Tx) error {
		link, err := models.FindLink(ctx, tx, input.LinkID)
		if err != nil {
			return err
		}

		log.Printf("Updating topics for %s to be %v", link, input.ParentTopicIds)
		service := services.UpdateLinkTopics{
			Actor:          actor,
			ParentTopicIds: input.ParentTopicIds,
			Link:           &models.LinkValue{link, false, actor.DefaultView()},
		}
		result, err = service.Call(ctx, tx)
		return err
	})
	if err != nil {
		log.Printf("There was a problem updating the topics: %s", err)
		return nil, err
	}

	return &models.UpdateLinkTopicsPayload{
		Link: result.Link,
	}, nil
}

// UpdateTopicParentTopics sets the parent topics on a topic.
func (r *MutationResolver) UpdateTopicParentTopics(
	ctx context.Context, input models.UpdateTopicParentTopicsInput,
) (*models.UpdateTopicParentTopicsPayload, error) {
	actor := GetRequestContext(ctx).Viewer()
	var result *services.UpdateTopicParentTopicsResult

	err := queries.Transact(r.DB, func(tx *sql.Tx) error {
		topic, err := models.FindTopic(ctx, tx, input.TopicID)
		if err != nil {
			return err
		}

		service := services.UpdateTopicParentTopics{
			Actor:          actor,
			Topic:          &models.TopicValue{topic, false, actor.DefaultView()},
			ParentTopicIds: input.ParentTopicIds,
		}
		result, err = service.Call(ctx, tx)
		return err
	})
	if err != nil {
		return nil, err
	}

	return &models.UpdateTopicParentTopicsPayload{
		Alerts: result.Alerts,
		Topic:  result.Topic,
	}, nil
}

// UpsertLink adds a new link to the database.
func (r *MutationResolver) UpsertLink(
	ctx context.Context, input models.UpsertLinkInput,
) (*models.UpsertLinkPayload, error) {
	actor := GetRequestContext(ctx).Viewer()
	var result *services.UpsertLinkResult

	err := queries.Transact(r.DB, func(tx *sql.Tx) error {
		repo, err := findRepo(ctx, tx, actor, input.OrganizationLogin, input.RepositoryName)
		if err != nil {
			log.Printf("resolvers.UpsertLink: repo %s/%s not found", input.OrganizationLogin, input.RepositoryName)
			return perrors.Wrap(err, "resolvers.UpsertLink")
		}

		service := services.UpsertLink{
			Actor:          actor,
			Fetcher:        r.Fetcher,
			ProvidedURL:    input.URL,
			Repository:     repo,
			ProvidedTitle:  input.Title,
			ParentTopicIds: input.AddParentTopicIds,
		}
		result, err = service.Call(ctx, tx)

		return perrors.Wrap(err, "resolvers.UpsertLink")
	})
	if err != nil {
		return nil, err
	}

	if result.Link == nil {
		return &models.UpsertLinkPayload{Alerts: result.Alerts}, nil
	}

	return &models.UpsertLinkPayload{
		Alerts: result.Alerts,
		LinkEdge: &models.LinkEdge{
			Node: &models.LinkValue{result.Link, result.LinkCreated, actor.DefaultView()},
		},
	}, nil
}

// UpsertTopicTimeRange adds a timeline to a topic.
func (r *MutationResolver) UpsertTopicTimeRange(
	ctx context.Context, input models.UpsertTopicTimeRangeInput,
) (*models.UpsertTopicTimeRangePayload, error) {
	actor := GetRequestContext(ctx).Viewer()
	c := services.Connection{Exec: r.DB, Actor: actor}

	topic, err := models.Topics(queries.Topic(actor.ID, input.TopicID)...).One(ctx, r.DB)
	if err != nil {
		return nil, perrors.Wrap(err, "resolveres: topic not found")
	}

	startsAt, err := time.Parse(time.RFC3339, input.StartsAt)
	if err != nil {
		return nil, perrors.Wrap(err, "resolveres: failed to parse startsAt")
	}

	result, err := c.UpsertTopicTimeRange(ctx, topic, startsAt, nil, input.PrefixFormat)
	if err != nil {
		return nil, perrors.Wrap(err, "resolvers: failed to upsert topic timline")
	}

	timeline := &models.TimeRange{
		StartsAt:     startsAt.Format(time.RFC3339),
		PrefixFormat: models.TimeRangePrefixFormat(result.TimeRange.PrefixFormat),
	}

	if err = topic.Reload(ctx, r.DB); err != nil {
		return nil, perrors.Wrap(err, "resolvers: failed to reload topic")
	}

	return &models.UpsertTopicTimeRangePayload{
		Topic:         &models.TopicValue{Topic: topic, View: actor.DefaultView()},
		TimeRangeEdge: &models.TimeRangeEdge{Node: timeline},
	}, nil
}


text:
struct CustomShaderBindingData
{
public:
	enum UniformType
	{
		Float = 0,
		Float2,
		Float3,
		Float4,
		Texture2D,
		Texture3D,
		Cubemap,
		Matrix2x2,
		Matrix2x3,
		Matrix2x4,
		Matrix3x2,
		Matrix3x3,
		Matrix3x4,
		Matrix4x2,
		Matrix4x3,
		Matrix4x4
	};
private:
	StringTableEntry targetedUniformName = StringTable->EmptyString();

	//ShaderConstHandles shaderConstHandle;

	UniformType type = CustomShaderBindingData::Float;

	F32 mFloat = 0.0f;
	Point2F mFloat2;
	Point3F mFloat3;
	Point4F mFloat4;

	//Image stuff
	GFXTexHandle texture;
	GFXSamplerStateDesc samplerState;

public:
	void setFloat(StringTableEntry shaderConstName, F32 f)
	{
		targetedUniformName = shaderConstName;
		mFloat = f;
		type = UniformType::Float;
	}
	F32 getFloat() { return mFloat; }

	void setFloat2(StringTableEntry shaderConstName, Point2F f)
	{
		targetedUniformName = shaderConstName;
		mFloat2 = f;
		type = Float2;
	}
	Point2F getFloat2() { return mFloat2; }

	void setFloat3(StringTableEntry shaderConstName, Point3F f)
	{
		targetedUniformName = shaderConstName;
		mFloat3 = f;
		type = Float3;
	}
	Point3F getFloat3() { return mFloat3; }

	void setFloat4(StringTableEntry shaderConstName, Point4F f)
	{
		targetedUniformName = shaderConstName;
		mFloat4 = f;
		type = Float4;
	}
	Point4F getFloat4() { return mFloat4; }

   void setTexture2D(StringTableEntry shaderConstName, GFXTexHandle f)
   {
      targetedUniformName = shaderConstName;
      texture = f;
      type = Texture2D;
   }
   GFXTexHandle getTexture2D() { return texture; }

	StringTableEntry getHandleName() {
		return targetedUniformName;
	}

	UniformType getType() {
		return type;
	}
};

#endif

redpajama_set_name: RedPajamaGithub


text:
exec java \
    ${JAVA_OPTIONS} \
    -jar /ontrack/acceptance/app/ontrack-acceptance.jar \
    --ontrack.acceptance.url=${ONTRACK_ACCEPTANCE_TARGET_URL} \
    --ontrack.acceptance.selenium-grid-url=${ONTRACK_ACCEPTANCE_SELENIUM_GRID_URL} \
    --ontrack.acceptance.selenium-browser-name=${ONTRACK_ACCEPTANCE_SELENIUM_BROWSER_NAME} \
    --ontrack.acceptance.disable-ssl=${ONTRACK_ACCEPTANCE_TARGET_SSL_DISABLED} \
    --ontrack.acceptance.admin=${ONTRACK_ACCEPTANCE_TARGET_ADMIN_PASSWORD} \
    --ontrack.acceptance.context=${ONTRACK_ACCEPTANCE_CONTEXT} \
    --ontrack.acceptance.timeout=${ONTRACK_ACCEPTANCE_TIMEOUT} \
    --ontrack.acceptance.implicit-wait=${ONTRACK_ACCEPTANCE_IMPLICIT_WAIT} \
    --ontrack.acceptance.output-dir=/ontrack/acceptance/output \
    --ontrack.acceptance.result-file-name=acceptance-tests.xml \
    --ontrack.acceptance.influxdb-uri=${ONTRACK_ACCEPTANCE_INFLUXDB_URI}


text:
require 'spec_helper'

RSpec.describe Admin::ToolsController, type: :controller do

  let(:params_key) { :tool }

  let(:admin_user) {FactoryBot.generate(:admin_user)}
  let(:stubs) {{}}
  let(:mock_content) {
    mock_model Tool, stubs
  }
  let(:mock_content_id) do
    mock_content.id
  end

  before(:each) do
    sign_in admin_user
  end

  describe "GET new" do
    it "renders the new form" do
      get :new
      expect(response).to render_template("new")
      expect(response).to be_successful
    end
  end

  describe '#index' do
    it 'GET index' do
      get :index
      expect(response).to have_http_status(:ok)
    end
  end

  describe '#show' do
    it 'GET show' do
      expect(Tool).to receive(:find).and_return(mock_content)
      get :show, params: { id: mock_content_id }
      expect(response).to have_http_status(:ok)
    end
  end

  describe '#edit' do
    it 'GET edit' do
      expect(Tool).to receive(:find).and_return(mock_content)
      get :edit, params: { id: mock_content_id }
      expect(response).to have_http_status(:ok)
    end
  end

  describe '#create' do
    it "creates a new model, redirects to index" do
      post :create, params: { tool: {} }
      expect(response).to have_http_status(:redirect)
    end
  end

  describe '#update' do
    let(:stubs) {{update: true}}
    it "updates the model, redirects to index" do
      expect(Tool).to receive(:find).and_return(mock_content)
      put :update, params: { :id => mock_content_id, params_key => {:params => 'params'} }
      expect(response).to have_http_status(:redirect)
    end
  end

  describe '#destroy' do
    it 'DELETE destroy' do
      expect(Tool).to receive(:find).and_return(mock_content)
      delete :destroy, params: { id: mock_content_id }
      expect(response).to have_http_status(:redirect)
    end

    it "nullifies the tool_id of external activities" do
      tool = FactoryBot.create(:tool)
      external_activity = FactoryBot.create(:external_activity, tool: tool)

      expect(external_activity.tool_id).to_not be_nil

      tool.destroy
      external_activity.reload
      expect(external_activity.tool_id).to be_nil
    end
  end

end


text:
Web.Router.map(function () {

  // this.resource('color', { path: '/colors/:hex' });
  this.route('random');

  this.resource('colors', { path: '/colors' }, function() {
    this.resource('colors.color', { path: ':hex' });
  });
});


text:
function ZaBulkProvision () {
    if (arguments.length == 0) return;
    ZaItem.call (this, "ZaBulkProvision") ;
	this._init();
	this.type = ZaItem.BULK_PROVISION;
}

ZaItem.BULK_PROVISION = "BulkProvsion";
ZaItem.BULK_PROVISION_TASK = "BulkProvsionTask";
ZaBulkProvision.URN = "urn:zimbraAdminExt" ;

ZaBulkProvision.prototype = new ZaItem;
ZaBulkProvision.prototype.constructor = ZaBulkProvision;

ZaBulkProvision.A_aid = "aid" ; //uploaded csv file attachment id
ZaBulkProvision.A_csv_aid = "csv_aid" ;
ZaBulkProvision.A_provision_accounts = "provision_accounts";
ZaBulkProvision.A_mustChangePassword = "mustChangePassword"; //the value of the must change password check box
ZaBulkProvision.A_isValidCSV = "isValidCSV" ;

ZaBulkProvision.A2_fileFormat = "fileFormat";
ZaBulkProvision.A2_op = "op";
ZaBulkProvision.A2_isToProvision = "isToProvision" ;
ZaBulkProvision.A2_accountName = "accountName" ;
ZaBulkProvision.A2_displayName = "displayName" ;
ZaBulkProvision.A2_status = "status" ;
ZaBulkProvision.A2_isValid = "isValid" ;
ZaBulkProvision.A2_password = "password";
ZaBulkProvision.A2_confirmPassword = "confirmPassword";
ZaBulkProvision.A2_generatePassword = "generatePassword" ;
ZaBulkProvision.A2_genPasswordLength = "genPasswordLength" ;
ZaBulkProvision.A2_accountLimit = "accountLimit" ;
ZaBulkProvision.A2_provAction = "provAction";
ZaBulkProvision.A2_generatedFileLink = "generatedFileLink";
ZaBulkProvision.A2_TargetDomainName = "TargetDomainName";
ZaBulkProvision.A2_completedAccountsFileLink = "completedAccountsFileLink";
ZaBulkProvision.A2_failedAccountsFileLink = "failedAccountsFileLink";

//provisioning options
ZaBulkProvision.A2_errorReportFileLink = "errorReportFileLink";
ZaBulkProvision.A2_successReportFileLink = "successReportFileLink";
ZaBulkProvision.A2_skippedCount = "skippedCount";
ZaBulkProvision.A2_errorCount = "errorCount";
ZaBulkProvision.A2_provisionedCount = "provisionedCount";
ZaBulkProvision.A2_totalCount = "totalCount";
ZaBulkProvision.A2_runningCount = "runningCount";
ZaBulkProvision.A2_idleCount = "idleCount";
ZaBulkProvision.A2_finishedCount = "finishedCount";
ZaBulkProvision.A2_progress = "progress";
ZaBulkProvision.A2_fileToken = "fileToken";
ZaBulkProvision.A2_createDomains = "createDomains";
ZaBulkProvision.A2_domainCount = "domainCount";
ZaBulkProvision.A2_skippedAccountCount = "skippedAccountCount";
ZaBulkProvision.A2_skippedDomainCount = "skippedDomainCount";
ZaBulkProvision.A2_SMTPHost = "SMTPHost";
ZaBulkProvision.A2_SMTPPort = "SMTPPort";
ZaBulkProvision.A2_sourceType = "sourceType";
ZaBulkProvision.A2_account = "account";
ZaBulkProvision.A2_accountPool = "accountPool";
ZaBulkProvision.A2_activateSearch = "activateSearch";
ZaBulkProvision.A2_poolNumPages = "poolNumPages";
ZaBulkProvision.A2_poolPagenum = "poolPagenum";
ZaBulkProvision.A2_src_acct_selection_pool = "src_acct_selection_pool";
ZaBulkProvision.A2_tgt_acct_selection_pool = "tgt_acct_selection_pool";

//LDAP import options
ZaBulkProvision.A2_maxResults = "maxResults";
ZaBulkProvision.A2_GalLdapURL = "zimbraGalLdapURL";
ZaBulkProvision.A2_GalLdapSearchBase = "zimbraGalLdapSearchBase";
ZaBulkProvision.A2_GalLdapBindDn = "zimbraGalLdapBindDn";
ZaBulkProvision.A2_GalLdapBindPassword = "zimbraGalLdapBindPassword";
ZaBulkProvision.A2_GalLdapFilter = "zimbraGalLdapFilter";

//IMAP Migration options
ZaBulkProvision.A2_sourceServerType = "sourceServerType";
ZaBulkProvision.A2_IMAPHost = "IMAPHost";
ZaBulkProvision.A2_IMAPPort = "IMAPPort";
ZaBulkProvision.A2_useAdminLogin = "UseAdminLogin";
ZaBulkProvision.A2_IMAPAdminLogin = "IMAPAdminLogin";
ZaBulkProvision.A2_IMAPAdminPassword = "IMAPAdminPassword";
ZaBulkProvision.A2_IMAPAdminPasswordConfirm = "IMAPAdminPasswordConfirm";
ZaBulkProvision.A2_connectionType = "ConnectionType";

//options for Exchange Migration wizard
ZaBulkProvision.A2_importMails = "importMails";
ZaBulkProvision.A2_importContacts = "importContacts";
ZaBulkProvision.A2_importTasks = "importTasks";
ZaBulkProvision.A2_importCalendar = "importCalendar";
ZaBulkProvision.A2_importDeletedItems = "importDeletedItems";
ZaBulkProvision.A2_importJunk = "importJunk";
ZaBulkProvision.A2_ignorePreviouslyImported = "ignorePreviouslyImported";
ZaBulkProvision.A2_InvalidSSLOk = "InvalidSSLOk";
ZaBulkProvision.A2_MapiProfile = "MapiProfile";
ZaBulkProvision.A2_MapiServer = "MapiServer";
ZaBulkProvision.A2_MapiLogonUserDN = "MapiLogonUserDN";
ZaBulkProvision.A2_ZimbraAdminPassword = "ZimbraAdminPassword";
ZaBulkProvision.A2_ZimbraAdminLogin = "ZimbraAdminLogin";
ZaBulkProvision.A2_ZimbraAdminPasswordConfirm = "ZimbraAdminPasswordConfirm";
ZaBulkProvision.A2_provisionUsers = "provisionUsers";
ZaBulkProvision.A2_importEmail = "importEmail";

ZaBulkProvision.iSTATUS_NOT_RUNNING = -1;
ZaBulkProvision.iSTATUS_IDLE = 0;
ZaBulkProvision.iSTATUS_STARTED = 1;
ZaBulkProvision.iSTATUS_STARTING = 2;
ZaBulkProvision.iSTATUS_CREATING_ACCOUNTS = 3;
ZaBulkProvision.iSTATUS_FINISHED = 4;
ZaBulkProvision.iSTATUS_ABORT = 5;
ZaBulkProvision.iSTATUS_ABORTED = 6;
ZaBulkProvision.iSTATUS_ERROR = 100;

ZaBulkProvision.ACTION_IMPORT_CSV = 1;
ZaBulkProvision.ACTION_IMPORT_XML = 2;
ZaBulkProvision.ACTION_IMPORT_LDAP = 3;
ZaBulkProvision.ACTION_GENERATE_MIG_XML = 4;
ZaBulkProvision.ACTION_GENERATE_BULK_XML = 5;
ZaBulkProvision.ACTION_GENERATE_BULK_CSV = 6;
ZaBulkProvision.ACTION_IMPORT_AD = 7;
ZaBulkProvision.ACTION_IMPORT_ZIMBRA = 8;

ZaBulkProvision.FILE_FORMAT_PREVIEW = "preview";
ZaBulkProvision.FILE_FORMAT_MIGRATION_XML = "migrationxml";
ZaBulkProvision.FILE_FORMAT_BULK_XML = "bulkxml";
ZaBulkProvision.FILE_FORMAT_BULK_CSV = "csv";

ZaBulkProvision.SOURCE_TYPE_ZIMBRA = "zimbra";
ZaBulkProvision.SOURCE_TYPE_LDAP = "ldap";
ZaBulkProvision.SOURCE_TYPE_XML = "bulkxml";
ZaBulkProvision.SOURCE_TYPE_REUSE_XML = "reusebulkxml";
ZaBulkProvision.SOURCE_TYPE_CSV = "csv";

ZaBulkProvision.MAIL_SOURCE_TYPE_IMAP = "IMAP";
ZaBulkProvision.MAIL_SOURCE_TYPE_EXCHANGE = "EXCHANGE";
ZaBulkProvision.MAIL_SOURCE_TYPE_ZIMBRA = "ZIMBRA";
ZaBulkProvision.MAIL_SOURCE_TYPE_EXCHANGE_IMAP = "EXCHANGE_IMAP";
ZaBulkProvision.OP_PREVIEW = "preview";
ZaBulkProvision.OP_GET_STATUS = "getStatus";
ZaBulkProvision.OP_PREVIEW_ACTIVE_IMPORTS = "previewActiveImports";
ZaBulkProvision.OP_START_IMPORT = "startImport";
ZaBulkProvision.OP_ABORT_IMPORT = "abortImport";
ZaBulkProvision.OP_DISMISS_IMPORT = "dismissImport";

ZaBulkProvision.CONNECTION_SSL = "ssl";
ZaBulkProvision.CONNECTION_CLEARTEXT = "cleartext";
ZaBulkProvision.CONNECTION_TLS = "tls";
ZaBulkProvision.CONNECTION_TLS_IF_AVAILABLE = "tls_if_available";

ZaBulkProvision.TOO_MANY_ACCOUNTS = "bulkprovision.BP_TOO_MANY_ACCOUNTS";
ZaBulkProvision.BP_INVALID_SEARCH_FILTER = "bulkprovision.BP_INVALID_SEARCH_FILTER";
ZaBulkProvision.BP_NAMING_EXCEPTION = "bulkprovision.BP_NAMING_EXCEPTION";
ZaBulkProvision.BP_NO_ACCOUNTS_TO_IMPORT =  "bulkprovision.BP_NO_ACCOUNTS_TO_IMPORT";

ZaBulkProvision.getMyXModel = function () {
	ZaBulkProvision.ProvActionChoices = [
		{value:ZaBulkProvision.ACTION_IMPORT_LDAP,label:com_zimbra_bulkprovision.ActionImportFromLDAP},
		{value:ZaBulkProvision.ACTION_IMPORT_CSV,label:com_zimbra_bulkprovision.ActionImportFromSCV},
		{value:ZaBulkProvision.ACTION_IMPORT_XML,label:com_zimbra_bulkprovision.ActionImportFromXML},
		{value:ZaBulkProvision.ACTION_GENERATE_MIG_XML,label:com_zimbra_bulkprovision.ActionGenerateMigXML},
		{value:ZaBulkProvision.ACTION_IMPORT_AD,label:com_zimbra_bulkprovision.ActionImportAccountsFromAD},
		{value:ZaBulkProvision.ACTION_GENERATE_BULK_XML,label:com_zimbra_bulkprovision.ActionGenerateBulkXML},
		{value:ZaBulkProvision.ACTION_GENERATE_BULK_CSV,label:com_zimbra_bulkprovision.ActionGenerateBulkCSV}
    ];

	ZaBulkProvision.SourceServerTypeChoices = [
        {label:com_zimbra_bulkprovision.SourceServerTypeIMAP, value:ZaBulkProvision.MAIL_SOURCE_TYPE_IMAP},
        {label:com_zimbra_bulkprovision.SourceServerTypeZimbra, value:ZaBulkProvision.MAIL_SOURCE_TYPE_ZIMBRA}
	];

	ZaBulkProvision.AccountListSourceTypeChoices = [
        {label:com_zimbra_bulkprovision.AccountListTypeLDAP, value:ZaBulkProvision.SOURCE_TYPE_LDAP},
        {label:com_zimbra_bulkprovision.AccountListTypeXML, value:ZaBulkProvision.SOURCE_TYPE_XML}
    ];

	ZaBulkProvision.IMAPConnectionTypeChoices = [
        {label:com_zimbra_bulkprovision.IMAPConnectionCleartext, value:ZaBulkProvision.CONNECTION_CLEARTEXT},
        {label:com_zimbra_bulkprovision.IMAPConnectionSSL, value:ZaBulkProvision.CONNECTION_SSL},
        {label:com_zimbra_bulkprovision.IMAPConnectionTLS, value:ZaBulkProvision.CONNECTION_TLS},
        {label:com_zimbra_bulkprovision.IMAPConnectionTLSIfAvailable, value:ZaBulkProvision.CONNECTION_TLS_IF_AVAILABLE}
    ];

	var xmodel = {
        items: [
            {id:ZaBulkProvision.A2_activateSearch,ref:ZaBulkProvision.A2_activateSearch, type:_NUMBER_,defaultValue:1},
            {id:ZaBulkProvision.A2_poolNumPages,ref:ZaBulkProvision.A2_poolNumPages, type:_NUMBER_,defaultValue:1},
            {id:ZaBulkProvision.A2_poolPagenum,ref:ZaBulkProvision.A2_poolPagenum, type:_NUMBER_,defaultValue:1},
    		{id:ZaBulkProvision.A2_src_acct_selection_pool, ref:ZaBulkProvision.A2_src_acct_selection_pool, type:_LIST_},
    		{id:ZaBulkProvision.A2_tgt_acct_selection_pool, ref:ZaBulkProvision.A2_tgt_acct_selection_pool, type:_LIST_},
            {id:ZaBulkProvision.A_csv_aid, type: _STRING_, ref: ZaBulkProvision.A_csv_aid},
	        {id:ZaBulkProvision.A_aid, type: _STRING_, ref: ZaBulkProvision.A_aid},
	        {id:ZaBulkProvision.A_provision_accounts, ref: ZaBulkProvision.A_provision_accounts,type:_LIST_ , dataType: _STRING_ ,outputType:_LIST_ } ,
	        {id:ZaBulkProvision.A_mustChangePassword,ref: ZaBulkProvision.A_mustChangePassword,type:_ENUM_, choices:ZaModel.BOOLEAN_CHOICES },
	        {id:ZaBulkProvision.A_isValidCSV,ref: ZaBulkProvision.A_isValidCSV,type:_ENUM_, choices:ZaModel.BOOLEAN_CHOICES },
	        {id:ZaBulkProvision.A2_provAction, ref:ZaBulkProvision.A2_provAction, type:_ENUM_, choices:ZaBulkProvision.ProvActionChoices},
	        {id:ZaBulkProvision.A2_generatedFileLink, type:_STRING_, ref:ZaBulkProvision.A2_generatedFileLink},
	        {id:ZaBulkProvision.A2_failedAccountsFileLink, type:_STRING_, ref:ZaBulkProvision.A2_failedAccountsFileLink},
	        {id:ZaBulkProvision.A2_completedAccountsFileLink, type:_STRING_, ref:ZaBulkProvision.A2_completedAccountsFileLink},
	        {id:ZaBulkProvision.A2_maxResults, type:_NUMBER_, ref:ZaBulkProvision.A2_maxResults},
	        {id:ZaBulkProvision.A2_errorCount, type:_NUMBER_, ref:ZaBulkProvision.A2_errorCount},
	        {id:ZaBulkProvision.A2_provisionedCount, type:_NUMBER_, ref:ZaBulkProvision.A2_provisionedCount},
	        {id:ZaBulkProvision.A2_totalCount, type:_NUMBER_, ref:ZaBulkProvision.A2_totalCount},
	        {id:ZaBulkProvision.A2_idleCount, type:_NUMBER_, ref:ZaBulkProvision.A2_idleCount},
	        {id:ZaBulkProvision.A2_finishedCount, type:_NUMBER_, ref:ZaBulkProvision.A2_finishedCount},
	        {id:ZaBulkProvision.A2_runningCount, type:_NUMBER_, ref:ZaBulkProvision.A2_runningCount},
	        {id:ZaBulkProvision.A2_domainCount, type:_NUMBER_, ref:ZaBulkProvision.A2_domainCount},
	        {id:ZaBulkProvision.A2_skippedAccountCount, type:_NUMBER_, ref:ZaBulkProvision.A2_skippedAccountCount},
	        {id:ZaBulkProvision.A2_skippedDomainCount, type:_NUMBER_, ref:ZaBulkProvision.A2_skippedDomainCount},
	        {id:ZaBulkProvision.A2_progress, type:_STRING_, ref:ZaBulkProvision.A2_progress},
	        {id:ZaBulkProvision.A2_fileToken, type:_NUMBER_, ref:ZaBulkProvision.A2_fileToken},
	        {id:ZaBulkProvision.A2_skippedCount, type:_NUMBER_, ref:ZaBulkProvision.A2_skippedCount},
	        {id:ZaBulkProvision.A2_status, type:_NUMBER_, ref:ZaBulkProvision.A2_status},
	        {id:ZaBulkProvision.A2_GalLdapURL, type:_SHORT_URL_, ref:ZaBulkProvision.A2_GalLdapURL},
	        {id:ZaBulkProvision.A2_GalLdapSearchBase, type:_STRING_, ref:ZaBulkProvision.A2_GalLdapSearchBase},
	        {id:ZaBulkProvision.A2_GalLdapBindDn, type:_STRING_, ref:ZaBulkProvision.A2_GalLdapBindDn},
	        {id:ZaBulkProvision.A2_GalLdapBindPassword, type:_STRING_, ref:ZaBulkProvision.A2_GalLdapBindPassword},
	        {id:ZaBulkProvision.A2_GalLdapFilter, type:_STRING_, ref:ZaBulkProvision.A2_GalLdapFilter},
	        {id:ZaBulkProvision.A2_password, type:_STRING_, ref:ZaBulkProvision.A2_password},
	        {id:ZaBulkProvision.A2_confirmPassword, type:_STRING_, ref:ZaBulkProvision.A2_confirmPassword},
	        {id:ZaBulkProvision.A2_generatePassword, type:_ENUM_, choices:ZaModel.BOOLEAN_CHOICES, ref:ZaBulkProvision.A2_generatePassword},
	        {id:ZaBulkProvision.A2_useAdminLogin, type:_ENUM_, choices:ZaModel.getBooleanChoices2(), ref:ZaBulkProvision.A2_useAdminLogin},
	        {id:ZaBulkProvision.A2_IMAPAdminLogin,type:_STRING_,ref:ZaBulkProvision.A2_IMAPAdminLogin},
	        {id:ZaBulkProvision.A2_IMAPAdminPassword,type:_STRING_,ref:ZaBulkProvision.A2_IMAPAdminPassword},
	        {id:ZaBulkProvision.A2_IMAPAdminPasswordConfirm,type:_STRING_,ref:ZaBulkProvision.A2_IMAPAdminPasswordConfirm},
	        {id:ZaBulkProvision.A2_genPasswordLength, type:_NUMBER_, ref:ZaBulkProvision.A2_genPasswordLength, maxInclusive:64},
	        {id:ZaBulkProvision.A2_sourceServerType, type:_ENUM_, ref:ZaBulkProvision.A2_sourceServerType, choices:ZaBulkProvision.SourceServerTypeChoices},
	        {id:ZaBulkProvision.A2_sourceType, type:_ENUM_, ref:ZaBulkProvision.A2_sourceType, choices:ZaBulkProvision.AccountListSourceTypeChoices},
	        {id:ZaBulkProvision.A2_connectionType, type:_ENUM_, ref:ZaBulkProvision.A2_connectionType, choices:ZaBulkProvision.IMAPConnectionTypeChoices},
	        {id:ZaBulkProvision.A2_op, type:_STRING_, ref:ZaBulkProvision.A2_op},
	        {id:ZaBulkProvision.A2_account,type:_LIST_,ref:ZaBulkProvision.A2_account},
	        {id:ZaBulkProvision.A2_accountPool,type:_LIST_,ref:ZaBulkProvision.A2_accountPool},
	        //exchange migration wizard
	        {id:ZaBulkProvision.A2_TargetDomainName, type:_STRING_, ref:ZaBulkProvision.A2_TargetDomainName},
	        {id:ZaBulkProvision.A2_importMails, type:_ENUM_, choices:ZaModel.BOOLEAN_CHOICES, ref:ZaBulkProvision.A2_importMails},
	        {id:ZaBulkProvision.A2_importContacts, type:_ENUM_, choices:ZaModel.BOOLEAN_CHOICES, ref:ZaBulkProvision.A2_importContacts},
	        {id:ZaBulkProvision.A2_importTasks, type:_ENUM_, choices:ZaModel.BOOLEAN_CHOICES, ref:ZaBulkProvision.A2_importTasks},
	        {id:ZaBulkProvision.A2_importCalendar, type:_ENUM_, choices:ZaModel.BOOLEAN_CHOICES, ref:ZaBulkProvision.A2_importCalendar},
	        {id:ZaBulkProvision.A2_importDeletedItems, type:_ENUM_, choices:ZaModel.BOOLEAN_CHOICES, ref:ZaBulkProvision.A2_importDeletedItems},
	        {id:ZaBulkProvision.A2_importJunk, type:_ENUM_, choices:ZaModel.BOOLEAN_CHOICES, ref:ZaBulkProvision.A2_importJunk},
	        {id:ZaBulkProvision.A2_ignorePreviouslyImported, type:_ENUM_, choices:ZaModel.BOOLEAN_CHOICES, ref:ZaBulkProvision.A2_ignorePreviouslyImported},
	        {id:ZaBulkProvision.A2_InvalidSSLOk, type:_ENUM_, choices:ZaModel.BOOLEAN_CHOICES, ref:ZaBulkProvision.A2_InvalidSSLOk},
	        {id:ZaBulkProvision.A2_MapiProfile, type:_STRING_, ref:ZaBulkProvision.A2_MapiProfile},
	        {id:ZaBulkProvision.A2_MapiServer, type:_STRING_, ref:ZaBulkProvision.A2_MapiServer},
	        {id:ZaBulkProvision.A2_MapiLogonUserDN, type:_STRING_, ref:ZaBulkProvision.A2_MapiLogonUserDN},
	        {id:ZaBulkProvision.A2_ZimbraAdminPassword, type:_STRING_, ref:ZaBulkProvision.A2_ZimbraAdminPassword},
	        {id:ZaBulkProvision.A2_ZimbraAdminPasswordConfirm, type:_STRING_, ref:ZaBulkProvision.A2_ZimbraAdminPasswordConfirm},
	        {id:ZaBulkProvision.A2_ZimbraAdminLogin, type:_STRING_, ref:ZaBulkProvision.A2_ZimbraAdminLogin},
	        {id:ZaBulkProvision.A2_provisionUsers, type:_ENUM_, choices:ZaModel.BOOLEAN_CHOICES, ref:ZaBulkProvision.A2_provisionUsers},
	        {id:ZaBulkProvision.A2_importEmail, type:_ENUM_, choices:ZaModel.BOOLEAN_CHOICES, ref:ZaBulkProvision.A2_importEmail},
	        //direct import from LDAP
	        {id:ZaBulkProvision.A2_createDomains, type:_ENUM_, choices:ZaModel.BOOLEAN_CHOICES, ref:ZaBulkProvision.A2_createDomains},
	        {id:ZaBulkProvision.A2_IMAPAdminPassword, type:_STRING_, ref:ZaBulkProvision.A2_IMAPAdminPassword},
	        {id:ZaBulkProvision.A2_IMAPAdminLogin, type:_STRING_, ref:ZaBulkProvision.A2_IMAPAdminLogin},
	        {id:ZaBulkProvision.A2_SMTPHost, type:_STRING_, ref:ZaBulkProvision.A2_SMTPHost},
	        {id:ZaBulkProvision.A2_SMTPPort, type:_NUMBER_, ref:ZaBulkProvision.A2_SMTPPort},
	        {id:ZaBulkProvision.A2_IMAPHost, type:_STRING_, ref:ZaBulkProvision.A2_IMAPHost},
	        {id:ZaBulkProvision.A2_IMAPPort, type:_NUMBER_, ref:ZaBulkProvision.A2_IMAPPort,defaultValue:993}
        ]
    }

    return xmodel ;
}

ZaBulkProvision.bulkDataIMport = function(obj, callback) {
	var soapDoc = AjxSoapDoc.create("BulkIMAPDataImportRequest", ZaBulkProvision.URN, null);
	var aid = obj [ZaBulkProvision.A_csv_aid] ;
	soapDoc.set(ZaBulkProvision.A2_op, obj[ZaBulkProvision.A2_op]);
	var controller = ZaApp.getInstance().getCurrentController();
	if(obj[ZaBulkProvision.A2_sourceType] == ZaBulkProvision.SOURCE_TYPE_XML) {
		if (obj[ZaBulkProvision.A_aid] != null) {
	    	soapDoc.set("aid", obj[ZaBulkProvision.A_aid]) ;
	    } else{
	    	controller.popupErrorDialog(com_zimbra_bulkprovision.error_no_aid) ;
	    	return ;
	    }
	}
	if(obj[ZaBulkProvision.A2_sourceType] == ZaBulkProvision.SOURCE_TYPE_ZIMBRA) {
		var cnt = obj[ZaBulkProvision.A2_account].length;
		for(var i = 0; i < cnt; i ++) {
			var accEl = soapDoc.set(ZaBulkProvision.A2_account, "");
			accEl.setAttribute("name", obj[ZaBulkProvision.A2_account][i]);
		}
	}
	attr = soapDoc.set(ZaBulkProvision.A2_sourceType, obj[ZaBulkProvision.A2_sourceType]);
	attr = soapDoc.set(ZaBulkProvision.A2_useAdminLogin,obj[ZaBulkProvision.A2_useAdminLogin]);
	if(obj[ZaBulkProvision.A2_IMAPAdminPassword])
		attr = soapDoc.set(ZaBulkProvision.A2_IMAPAdminPassword,obj[ZaBulkProvision.A2_IMAPAdminPassword]);

	if(obj[ZaBulkProvision.A2_IMAPAdminLogin]) {
		attr = soapDoc.set(ZaBulkProvision.A2_IMAPAdminLogin,obj[ZaBulkProvision.A2_IMAPAdminLogin]);
	}
	if(obj[ZaBulkProvision.A2_IMAPHost]) {
		attr = soapDoc.set(ZaBulkProvision.A2_IMAPHost,obj[ZaBulkProvision.A2_IMAPHost]);
	}
	if(obj[ZaBulkProvision.A2_IMAPPort]) {
		attr = soapDoc.set(ZaBulkProvision.A2_IMAPPort,obj[ZaBulkProvision.A2_IMAPPort]);
	}
	if(obj[ZaBulkProvision.A2_connectionType]) {
		attr = soapDoc.set(ZaBulkProvision.A2_connectionType,obj[ZaBulkProvision.A2_connectionType]);
	}
	if(obj[ZaBulkProvision.A2_sourceServerType]) {
		attr = soapDoc.set(ZaBulkProvision.A2_sourceServerType,obj[ZaBulkProvision.A2_sourceServerType]);
	}

	var csfeParams = new Object();
	csfeParams.soapDoc = soapDoc;
	csfeParams.asyncMode = true;
	csfeParams.callback = callback;

	var reqMgrParams = {} ;
	reqMgrParams.controller = controller;
	reqMgrParams.busyMsg = com_zimbra_bulkprovision.BUSY_START_PROVISION_ACCOUNTS;
	ZaRequestMgr.invoke(csfeParams, reqMgrParams);
}

ZaBulkProvision.getBulkProvisionAccounts = function (app, obj) {
    var controller = ZaApp.getInstance().getCurrentController();
    var soapDoc = AjxSoapDoc.create("GetBulkProvisionAccountsRequest", ZaBulkProvision.URN, null);
    var aid = obj [ZaBulkProvision.A_csv_aid] ;
    if (aid != null) {
    	soapDoc.set("aid", aid) ;
    } else{
    	controller.popupErrorDialog(com_zimbra_bulkprovision.error_no_aid) ;
    	return ;
    }

    var accountLimit = obj [ZaBulkProvision.A2_accountLimit] ;

    if (accountLimit != null) {
        soapDoc.setMethodAttribute(ZaBulkProvision.A2_accountLimit, accountLimit) ;
    }

    var csfeParams = new Object();
	csfeParams.soapDoc = soapDoc;
	var reqMgrParams = {} ;
	reqMgrParams.controller = controller ;
	reqMgrParams.busyMsg = com_zimbra_bulkprovision.BUSY_GET_PROVISION_ACCOUNTS ;

    /*
    if (callback) {
		csfeParams.callback = callback;
		csfeParams.asyncMode = true ;
	}*/

    var resp = ZaRequestMgr.invoke(csfeParams, reqMgrParams).Body.GetBulkProvisionAccountsResponse ;
    var accounts = [] ;
    var aid, isValidCSV ;
    if (resp && resp.account ) {
        for (var i=0; i < resp.account.length ; i ++) {
            accounts.push (resp.account[i]._attrs) ;
        }
    }

    if (resp && resp.aid) {
        aid = resp.aid[0]._content ;
    }

    if (resp && resp[ZaBulkProvision.A_isValidCSV])    {
        isValidCSV = resp[ZaBulkProvision.A_isValidCSV][0]._content ;
    }
    return { accounts: accounts, aid: aid, isValidCSV: isValidCSV  } ;
}

ZaBulkProvision.initProvisionAccounts = function (accounts) {
    for (var i=0; i < accounts.length; i ++) {
        if (accounts[i][ZaBulkProvision.A2_isValid] == "TRUE") {
            accounts[i][ZaBulkProvision.A2_isToProvision] = true ;
        }
    }

    return accounts ;
}

ZaBulkProvision.abortImportThread = function(callback) {
	var soapDoc = AjxSoapDoc.create("BulkImportAccountsRequest",ZaBulkProvision.URN, null);
	soapDoc.getMethod().setAttribute(ZaBulkProvision.A2_op, ZaBulkProvision.OP_ABORT_IMPORT);
	var csfeParams = new Object();
	csfeParams.soapDoc = soapDoc;
	csfeParams.asyncMode = true;
	csfeParams.callback = callback;

	var reqMgrParams = {} ;
	reqMgrParams.controller = ZaApp.getInstance().getCurrentController();
	reqMgrParams.busyMsg = com_zimbra_bulkprovision.BUSY_ABORTING_IMPORT_THREAD;
	ZaRequestMgr.invoke(csfeParams, reqMgrParams);
}

ZaBulkProvision.getImportStatus = function(callback) {
	var soapDoc = AjxSoapDoc.create("BulkImportAccountsRequest",ZaBulkProvision.URN, null);
	soapDoc.getMethod().setAttribute(ZaBulkProvision.A2_op, ZaBulkProvision.OP_GET_STATUS);
	var csfeParams = new Object();
	csfeParams.soapDoc = soapDoc;
	if(callback) {
		csfeParams.asyncMode = true;
		csfeParams.callback = callback;
	}
	var reqMgrParams = {} ;
	reqMgrParams.controller = ZaApp.getInstance().getCurrentController();
	reqMgrParams.busyMsg = com_zimbra_bulkprovision.BUSY_GETTING_PROVISIONING_STATUS;
	return ZaRequestMgr.invoke(csfeParams, reqMgrParams);
}

ZaBulkProvision.importAccountsFromFile = function (obj, callback) {
	var soapDoc = AjxSoapDoc.create("BulkImportAccountsRequest",ZaBulkProvision.URN, null);

	soapDoc.getMethod().setAttribute(ZaBulkProvision.A2_op, obj[ZaBulkProvision.A2_op]);
	var attr = soapDoc.set(ZaBulkProvision.A2_sourceType,obj[ZaBulkProvision.A2_sourceType]);
	attr = soapDoc.set(ZaBulkProvision.A2_createDomains,obj[ZaBulkProvision.A2_createDomains]);
	attr = soapDoc.set(ZaBulkProvision.A_aid,obj[ZaBulkProvision.A_aid]);

	if(obj[ZaBulkProvision.A2_SMTPHost]) {
		attr = soapDoc.set(ZaBulkProvision.A2_SMTPHost,obj[ZaBulkProvision.A2_SMTPHost]);
	}
	if(obj[ZaBulkProvision.A2_SMTPPort]) {
		attr = soapDoc.set(ZaBulkProvision.A2_SMTPPort,obj[ZaBulkProvision.A2_SMTPPort]);
	}

	var csfeParams = new Object();
	csfeParams.soapDoc = soapDoc;
	csfeParams.asyncMode = true;
	csfeParams.callback = callback;

	var reqMgrParams = {} ;
	reqMgrParams.controller = ZaApp.getInstance().getCurrentController();
	reqMgrParams.busyMsg = com_zimbra_bulkprovision.BUSY_START_PROVISION_ACCOUNTS;
	ZaRequestMgr.invoke(csfeParams, reqMgrParams);
}

ZaBulkProvision.importAccountsFromLDAP = function (obj, callback) {
	var soapDoc = AjxSoapDoc.create("BulkImportAccountsRequest",ZaBulkProvision.URN, null);
	soapDoc.getMethod().setAttribute(ZaBulkProvision.A2_op, ZaBulkProvision.OP_START_IMPORT);

	var attr = soapDoc.set("a", ZaDomain.GAL_Mode_external);
	attr.setAttribute("n", ZaDomain.A_zimbraGalMode);

	attr = soapDoc.set("a", obj[ZaBulkProvision.A2_GalLdapURL]);
	attr.setAttribute("n", ZaBulkProvision.A2_GalLdapURL);

	attr = soapDoc.set("a", obj[ZaBulkProvision.A2_GalLdapSearchBase]);
	attr.setAttribute("n", ZaBulkProvision.A2_GalLdapSearchBase);

	attr = soapDoc.set("a", obj[ZaBulkProvision.A2_GalLdapFilter]);
	attr.setAttribute("n", ZaBulkProvision.A2_GalLdapFilter);

	attr = soapDoc.set("a", obj[ZaBulkProvision.A2_GalLdapBindDn]);
	attr.setAttribute("n", ZaBulkProvision.A2_GalLdapBindDn);

	attr = soapDoc.set("a", obj[ZaBulkProvision.A2_GalLdapBindPassword]);
	attr.setAttribute("n", ZaBulkProvision.A2_GalLdapBindPassword);

	attr = soapDoc.set(ZaBulkProvision.A2_sourceType,ZaBulkProvision.SOURCE_TYPE_LDAP);
	if(obj[ZaBulkProvision.A2_password]) {
		attr = soapDoc.set(ZaBulkProvision.A2_password,obj[ZaBulkProvision.A2_password]);
	}
	if(obj[ZaBulkProvision.A2_SMTPHost]) {
		attr = soapDoc.set(ZaBulkProvision.A2_SMTPHost,obj[ZaBulkProvision.A2_SMTPHost]);
	}
	if(obj[ZaBulkProvision.A2_SMTPPort]) {
		attr = soapDoc.set(ZaBulkProvision.A2_SMTPPort,obj[ZaBulkProvision.A2_SMTPPort]);
	}

	attr = soapDoc.set(ZaBulkProvision.A2_generatePassword,obj[ZaBulkProvision.A2_generatePassword]);
	attr = soapDoc.set(ZaBulkProvision.A2_genPasswordLength,obj[ZaBulkProvision.A2_genPasswordLength]);
	attr = soapDoc.set(ZaBulkProvision.A_mustChangePassword,obj[ZaBulkProvision.A_mustChangePassword]);
	attr = soapDoc.set(ZaBulkProvision.A2_maxResults,obj[ZaBulkProvision.A2_maxResults]);
	attr = soapDoc.set(ZaBulkProvision.A2_createDomains,obj[ZaBulkProvision.A2_createDomains]);

	var csfeParams = new Object();
	csfeParams.soapDoc = soapDoc;
	csfeParams.asyncMode = true;
	csfeParams.callback = callback;

	var reqMgrParams = {} ;
	reqMgrParams.controller = ZaApp.getInstance().getCurrentController();
	reqMgrParams.busyMsg = com_zimbra_bulkprovision.BUSY_START_PROVISION_ACCOUNTS;
	ZaRequestMgr.invoke(csfeParams, reqMgrParams);
}

ZaBulkProvision.generateBulkProvisionPreview = function(obj, callback) {
	var soapDoc = AjxSoapDoc.create("GenerateBulkProvisionFileFromLDAPRequest",ZaBulkProvision.URN, null);
	var attr = soapDoc.set("a", ZaDomain.GAL_Mode_external);
	attr.setAttribute("n", ZaDomain.A_zimbraGalMode);

	attr = soapDoc.set("a", obj[ZaBulkProvision.A2_GalLdapURL]);
	attr.setAttribute("n", ZaBulkProvision.A2_GalLdapURL);

	attr = soapDoc.set("a", obj[ZaBulkProvision.A2_GalLdapSearchBase]);
	attr.setAttribute("n", ZaBulkProvision.A2_GalLdapSearchBase);

	attr = soapDoc.set("a", obj[ZaBulkProvision.A2_GalLdapFilter]);
	attr.setAttribute("n", ZaBulkProvision.A2_GalLdapFilter);

	attr = soapDoc.set("a", obj[ZaBulkProvision.A2_GalLdapBindDn]);
	attr.setAttribute("n", ZaBulkProvision.A2_GalLdapBindDn);

	attr = soapDoc.set("a", obj[ZaBulkProvision.A2_GalLdapBindPassword]);
	attr.setAttribute("n", ZaBulkProvision.A2_GalLdapBindPassword);

	if(obj[ZaBulkProvision.A2_password]) {
		attr = soapDoc.set(ZaBulkProvision.A2_password,obj[ZaBulkProvision.A2_password]);
	}

	if(obj[ZaBulkProvision.A2_SMTPHost]) {
		attr = soapDoc.set(ZaBulkProvision.A2_SMTPHost,obj[ZaBulkProvision.A2_SMTPHost]);
	}
	if(obj[ZaBulkProvision.A2_SMTPPort]) {
		attr = soapDoc.set(ZaBulkProvision.A2_SMTPPort,obj[ZaBulkProvision.A2_SMTPPort]);
	}

	attr = soapDoc.set(ZaBulkProvision.A2_maxResults,obj[ZaBulkProvision.A2_maxResults]);
	attr = soapDoc.set(ZaBulkProvision.A2_fileFormat,ZaBulkProvision.FILE_FORMAT_PREVIEW);
	attr = soapDoc.set(ZaBulkProvision.A2_generatePassword,obj[ZaBulkProvision.A2_generatePassword]);
	attr = soapDoc.set(ZaBulkProvision.A2_genPasswordLength,obj[ZaBulkProvision.A2_genPasswordLength]);
	attr = soapDoc.set(ZaBulkProvision.A_mustChangePassword,obj[ZaBulkProvision.A_mustChangePassword]);

	var csfeParams = new Object();
	csfeParams.soapDoc = soapDoc;
	csfeParams.asyncMode = true;
	csfeParams.callback = callback;

	var reqMgrParams = {} ;
	reqMgrParams.controller = ZaApp.getInstance().getCurrentController();
	reqMgrParams.busyMsg = com_zimbra_bulkprovision.BUSY_GENERATING_BULK_FILE;
	ZaRequestMgr.invoke(csfeParams, reqMgrParams );
};

ZaBulkProvision.generateBulkProvisionFile = function(obj, callback) {
	var soapDoc = AjxSoapDoc.create("GenerateBulkProvisionFileFromLDAPRequest",ZaBulkProvision.URN, null);
	var attr = soapDoc.set("a", ZaDomain.GAL_Mode_external);
	attr.setAttribute("n", ZaDomain.A_zimbraGalMode);

	attr = soapDoc.set("a", obj[ZaBulkProvision.A2_GalLdapURL]);
	attr.setAttribute("n", ZaBulkProvision.A2_GalLdapURL);

	attr = soapDoc.set("a", obj[ZaBulkProvision.A2_GalLdapSearchBase]);
	attr.setAttribute("n", ZaBulkProvision.A2_GalLdapSearchBase);

	attr = soapDoc.set("a", obj[ZaBulkProvision.A2_GalLdapFilter]);
	attr.setAttribute("n", ZaBulkProvision.A2_GalLdapFilter);

	attr = soapDoc.set("a", obj[ZaBulkProvision.A2_GalLdapBindDn]);
	attr.setAttribute("n", ZaBulkProvision.A2_GalLdapBindDn);

	attr = soapDoc.set("a", obj[ZaBulkProvision.A2_GalLdapBindPassword]);
	attr.setAttribute("n", ZaBulkProvision.A2_GalLdapBindPassword);

	if(obj[ZaBulkProvision.A2_password]) {
		attr = soapDoc.set(ZaBulkProvision.A2_password,obj[ZaBulkProvision.A2_password]);
	}
	attr = soapDoc.set(ZaBulkProvision.A2_generatePassword,obj[ZaBulkProvision.A2_generatePassword]);
	attr = soapDoc.set(ZaBulkProvision.A2_genPasswordLength,obj[ZaBulkProvision.A2_genPasswordLength]);
	attr = soapDoc.set(ZaBulkProvision.A_mustChangePassword,obj[ZaBulkProvision.A_mustChangePassword]);
	attr = soapDoc.set(ZaBulkProvision.A2_maxResults,obj[ZaBulkProvision.A2_maxResults]);

	if(obj[ZaBulkProvision.A2_provAction] == ZaBulkProvision.ACTION_GENERATE_MIG_XML) {
		attr = soapDoc.set(ZaBulkProvision.A2_fileFormat,ZaBulkProvision.FILE_FORMAT_MIGRATION_XML);
		attr = soapDoc.set(ZaBulkProvision.A2_importMails,obj[ZaBulkProvision.A2_importMails]);
		attr = soapDoc.set(ZaBulkProvision.A2_importContacts,obj[ZaBulkProvision.A2_importContacts]);
		attr = soapDoc.set(ZaBulkProvision.A2_importTasks,obj[ZaBulkProvision.A2_importTasks]);
		attr = soapDoc.set(ZaBulkProvision.A2_importCalendar,obj[ZaBulkProvision.A2_importCalendar]);
		attr = soapDoc.set(ZaBulkProvision.A2_importDeletedItems,obj[ZaBulkProvision.A2_importDeletedItems]);
		attr = soapDoc.set(ZaBulkProvision.A2_importJunk,obj[ZaBulkProvision.A2_importJunk]);
		attr = soapDoc.set(ZaBulkProvision.A2_ignorePreviouslyImported,obj[ZaBulkProvision.A2_ignorePreviouslyImported]);
		attr = soapDoc.set(ZaBulkProvision.A2_InvalidSSLOk,obj[ZaBulkProvision.A2_InvalidSSLOk]);
		attr = soapDoc.set(ZaBulkProvision.A2_TargetDomainName,obj[ZaBulkProvision.A2_TargetDomainName]);
		attr = soapDoc.set(ZaBulkProvision.A2_ZimbraAdminLogin,obj[ZaBulkProvision.A2_ZimbraAdminLogin]);
		attr = soapDoc.set(ZaBulkProvision.A2_ZimbraAdminPassword,obj[ZaBulkProvision.A2_ZimbraAdminPassword]);
		attr = soapDoc.set(ZaBulkProvision.A2_MapiProfile,obj[ZaBulkProvision.A2_MapiProfile]);
		attr = soapDoc.set(ZaBulkProvision.A2_MapiServer,obj[ZaBulkProvision.A2_MapiServer]);
		attr = soapDoc.set(ZaBulkProvision.A2_MapiLogonUserDN,obj[ZaBulkProvision.A2_MapiLogonUserDN]);
		attr = soapDoc.set(ZaBulkProvision.A2_provisionUsers,obj[ZaBulkProvision.A2_provisionUsers]);
	} else if(obj[ZaBulkProvision.A2_provAction] == ZaBulkProvision.ACTION_GENERATE_BULK_XML) {
		attr = soapDoc.set(ZaBulkProvision.A2_fileFormat,ZaBulkProvision.FILE_FORMAT_BULK_XML);
	} else if(obj[ZaBulkProvision.A2_provAction] == ZaBulkProvision.ACTION_GENERATE_BULK_CSV) {
		attr = soapDoc.set(ZaBulkProvision.A2_fileFormat,ZaBulkProvision.FILE_FORMAT_BULK_CSV);
	}

	var csfeParams = new Object();
	csfeParams.soapDoc = soapDoc;
	csfeParams.asyncMode = true;
	csfeParams.callback = callback;

	var reqMgrParams = {} ;
	reqMgrParams.controller = ZaApp.getInstance().getCurrentController();
	reqMgrParams.busyMsg = com_zimbra_bulkprovision.BUSY_GENERATING_BULK_FILE;
	ZaRequestMgr.invoke(csfeParams, reqMgrParams );
};

ZaBulkProvision.getBulkDataImportTasks = function() {
	var servers = ZaApp.getInstance().getMailServers(true);
	var taskList = new ZaItemList(ZaBulkProvisionTask);
	for(var j=0;j<servers.length;j++) {
		var soapDoc = AjxSoapDoc.create("GetBulkIMAPImportTaskListRequest",ZaBulkProvision.URN, null);
		var params = new Object();
		params.soapDoc = soapDoc;
		params.asyncMode=false;
		params.targetServer = servers[j].id;
		var reqMgrParams = {
			controller : ZaApp.getInstance().getCurrentController(),
			busyMsg : com_zimbra_bulkprovision.BUSY_GET_BULK_TASKS
		}
		var resp = ZaRequestMgr.invoke(params, reqMgrParams).Body.GetBulkIMAPImportTaskListResponse;
		var list = new ZaItemList(ZaBulkProvisionTask);
		list.loadFromJS(resp);
		var arr = list.getArray();
		for(var i=0;i<arr.length;i++) {
			taskList.add(arr[i]);
		}
	}
	return taskList;
}

ZaBulkProvision.deleteBulkDataImportTasks = function () {
	var soapDoc = AjxSoapDoc.create("PurgeBulkIMAPImportTasksRequest",ZaBulkProvision.URN, null);
	var params = new Object();
	params.soapDoc = soapDoc;
	params.asyncMode=false;
	var reqMgrParams = {
		controller : ZaApp.getInstance().getCurrentController(),
		busyMsg : com_zimbra_bulkprovision.BUSY_GET_BULK_TASKS
	}
	var resp = ZaRequestMgr.invoke(params, reqMgrParams).Body.PurgeBulkIMAPImportTasksResponse;
}

ZaBulkProvisionTask = function () {
	ZaItem.call(this, "ZaBulkProvisionTask");
	this._init();
	//The type is required. The application tab uses it to show the right icon
	this.type = ZaItem.BULK_PROVISION_TASK;
}

ZaBulkProvisionTask.prototype = new ZaItem;
ZaBulkProvisionTask.prototype.constructor = ZaBulkProvisionTask;

ZaBulkProvisionTask.A_owner = "owner";
ZaBulkProvisionTask.A_totalTasks = "totalTasks";
ZaBulkProvisionTask.A_finishedTasks = "finishedTasks";
ZaBulkProvisionTask.A_failedTasks = "failedTasks";
ZaBulkProvisionTask.A_status = "status";


text:
namespace printing {

const char kSettingSavePath[] = "savePath";
const char kSettingAppState[] = "appState";

StickySettings::StickySettings() {}

StickySettings::~StickySettings() {}

void StickySettings::StoreAppState(const std::string& data) {
  printer_app_state_.reset(new std::string(data));
}

void StickySettings::StoreSavePath(const FilePath& path) {
  save_path_.reset(new FilePath(path));
}

void StickySettings::SaveInPrefs(PrefService* prefs) {
  DCHECK(prefs);
  if (prefs) {
    scoped_ptr<DictionaryValue> value(new DictionaryValue);
    if (save_path_.get())
      value->SetString(printing::kSettingSavePath, save_path_->value());
    if (printer_app_state_.get())
      value->SetString(printing::kSettingAppState,
          *printer_app_state_);
    prefs->Set(prefs::kPrintPreviewStickySettings, *value);
  }
}

void StickySettings::RestoreFromPrefs(PrefService* prefs) {
  DCHECK(prefs);
  if (prefs) {
    const DictionaryValue* value =
        prefs->GetDictionary(prefs::kPrintPreviewStickySettings);

    FilePath::StringType save_path;
    if (value->GetString(printing::kSettingSavePath, &save_path))
      save_path_.reset(new FilePath(save_path));
    std::string buffer;
    if (value->GetString(printing::kSettingAppState, &buffer))
      printer_app_state_.reset(new std::string(buffer));
  }
}

void StickySettings::RegisterUserPrefs(PrefService* prefs) {
  prefs->RegisterDictionaryPref(prefs::kPrintPreviewStickySettings,
                                PrefService::UNSYNCABLE_PREF);
}

std::string* StickySettings::printer_app_state() {
  return printer_app_state_.get();
}

FilePath* StickySettings::save_path() {
  return save_path_.get();
}

} // namespace printing


text:
package com.consol.citrus.dsl.design;

import com.consol.citrus.TestCase;
import com.consol.citrus.actions.SendMessageAction;
import com.consol.citrus.container.SequenceAfterTest;
import com.consol.citrus.container.SequenceBeforeTest;
import com.consol.citrus.dsl.actions.DelegatingTestAction;
import com.consol.citrus.message.DefaultMessage;
import com.consol.citrus.report.TestActionListeners;
import com.consol.citrus.testng.AbstractTestNGUnitTest;
import com.consol.citrus.validation.builder.StaticMessageContentBuilder;
import com.consol.citrus.ws.actions.SendSoapMessageAction;
import com.consol.citrus.ws.client.WebServiceClient;
import com.consol.citrus.ws.message.SoapAttachment;
import com.consol.citrus.ws.message.SoapMessageHeaders;
import org.mockito.Mockito;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;

import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.when;

/**
 * @author Christoph Deppisch
 */
public class SendSoapMessageTestDesignerTest extends AbstractTestNGUnitTest {

    private WebServiceClient soapClient = Mockito.mock(WebServiceClient.class);

    private ApplicationContext applicationContextMock = Mockito.mock(ApplicationContext.class);
    private Resource resource = Mockito.mock(Resource.class);

    private SoapAttachment testAttachment = new SoapAttachment();

    /**
     * Setup test attachment.
     */
    @BeforeClass
    public void setup() {
        testAttachment.setContentId("attachment01");
        testAttachment.setContent("This is an attachment");
        testAttachment.setContentType("text/plain");
        testAttachment.setCharsetName("UTF-8");
    }

    @Test
    public void testFork() {
        MockTestDesigner builder = new MockTestDesigner(applicationContext, context) {
            @Override
            public void configure() {
                send(soapClient)
                    .message(new DefaultMessage("Foo").setHeader("operation", "foo"))
                        .header("additional", "additionalValue");

                send(soapClient)
                    .message(new DefaultMessage("Foo").setHeader("operation", "foo"))
                    .fork(true);
            }
        };

        builder.configure();

        TestCase test = builder.getTestCase();
        Assert.assertEquals(test.getActionCount(), 2);
        Assert.assertEquals(test.getActions().get(0).getClass(), DelegatingTestAction.class);
        Assert.assertEquals(((DelegatingTestAction)test.getActions().get(0)).getDelegate().getClass(), SendMessageAction.class);
        Assert.assertEquals(test.getActions().get(1).getClass(), DelegatingTestAction.class);
        Assert.assertEquals(((DelegatingTestAction)test.getActions().get(1)).getDelegate().getClass(), SendMessageAction.class);

        SendMessageAction action = (SendMessageAction) ((DelegatingTestAction)test.getActions().get(0)).getDelegate();
        Assert.assertEquals(action.getName(), "send");

        Assert.assertEquals(action.getEndpoint(), soapClient);
        Assert.assertEquals(action.getMessageBuilder().getClass(), StaticMessageContentBuilder.class);

        StaticMessageContentBuilder messageBuilder = (StaticMessageContentBuilder) action.getMessageBuilder();
        Assert.assertEquals(messageBuilder.getMessage().getPayload(String.class), "Foo");
        Assert.assertEquals(messageBuilder.getMessage().getHeader("operation"), "foo");
        Assert.assertEquals(messageBuilder.getMessageHeaders().size(), 1L);
        Assert.assertEquals(messageBuilder.getMessageHeaders().get("additional"), "additionalValue");

        Assert.assertFalse(action.isForkMode());

        action = (SendMessageAction) ((DelegatingTestAction)test.getActions().get(1)).getDelegate();
        Assert.assertEquals(action.getName(), "send");

        Assert.assertEquals(action.getEndpoint(), soapClient);
        Assert.assertEquals(action.getMessageBuilder().getClass(), StaticMessageContentBuilder.class);

        Assert.assertTrue(action.isForkMode());
    }

    @Test
    public void testSoapAction() {
        MockTestDesigner builder = new MockTestDesigner(applicationContext, context) {
            @Override
            public void configure() {
                soap().client(soapClient)
                        .send()
                        .soapAction("TestService/sayHello")
                        .payload("<TestRequest><Message>Hello World!</Message></TestRequest>");
            }
        };

        builder.configure();

        TestCase test = builder.getTestCase();
        Assert.assertEquals(test.getActionCount(), 1);
        Assert.assertEquals(test.getActions().get(0).getClass(), DelegatingTestAction.class);
        Assert.assertEquals(((DelegatingTestAction)test.getActions().get(0)).getDelegate().getClass(), SendSoapMessageAction.class);

        SendSoapMessageAction action = (SendSoapMessageAction) ((DelegatingTestAction)test.getActions().get(0)).getDelegate();
        Assert.assertEquals(action.getName(), "send");

        Assert.assertEquals(action.getEndpoint(), soapClient);
        Assert.assertEquals(action.getMessageBuilder().getClass(), StaticMessageContentBuilder.class);

        StaticMessageContentBuilder messageBuilder = (StaticMessageContentBuilder) action.getMessageBuilder();
        Assert.assertEquals(messageBuilder.getMessage().getPayload(), "<TestRequest><Message>Hello World!</Message></TestRequest>");
        Assert.assertEquals(messageBuilder.getMessage().getHeaders().size(), 3L);
        Assert.assertEquals(messageBuilder.getMessage().getHeaders().get(SoapMessageHeaders.SOAP_ACTION), "TestService/sayHello");
    }

    @Test
    public void testSoapAttachment() {
        MockTestDesigner builder = new MockTestDesigner(applicationContext, context) {
            @Override
            public void configure() {
                soap().client(soapClient)
                    .send()
                    .payload("<TestRequest><Message>Hello World!</Message></TestRequest>")
                    .attachment(testAttachment);
            }
        };

        builder.configure();

        TestCase test = builder.getTestCase();
        Assert.assertEquals(test.getActionCount(), 1);
        Assert.assertEquals(test.getActions().get(0).getClass(), DelegatingTestAction.class);
        Assert.assertEquals(((DelegatingTestAction)test.getActions().get(0)).getDelegate().getClass(), SendSoapMessageAction.class);

        SendSoapMessageAction action = (SendSoapMessageAction) ((DelegatingTestAction)test.getActions().get(0)).getDelegate();
        Assert.assertEquals(action.getName(), "send");

        Assert.assertEquals(action.getEndpoint(), soapClient);
        Assert.assertEquals(action.getMessageBuilder().getClass(), StaticMessageContentBuilder.class);

        StaticMessageContentBuilder messageBuilder = (StaticMessageContentBuilder) action.getMessageBuilder();
        Assert.assertEquals(messageBuilder.getMessage().getPayload(), "<TestRequest><Message>Hello World!</Message></TestRequest>");
        Assert.assertEquals(messageBuilder.getMessageHeaders().size(), 0L);

        Assert.assertEquals(action.getAttachments().size(), 1L);
        Assert.assertNull(action.getAttachments().get(0).getContentResourcePath());
        Assert.assertEquals(action.getAttachments().get(0).getContent(), testAttachment.getContent());
        Assert.assertEquals(action.getAttachments().get(0).getContentId(), testAttachment.getContentId());
        Assert.assertEquals(action.getAttachments().get(0).getContentType(), testAttachment.getContentType());
        Assert.assertEquals(action.getAttachments().get(0).getCharsetName(), testAttachment.getCharsetName());
    }

    @Test
    public void testMtomSoapAttachment() {
        MockTestDesigner builder = new MockTestDesigner(applicationContext, context) {
            @Override
            public void configure() {
                soap().client(soapClient)
                    .send()
                    .mtomEnabled(true)
                    .payload("<TestRequest><data>cid:attachment01</data></TestRequest>")
                    .attachment(testAttachment);
            }
        };

        builder.configure();

        TestCase test = builder.getTestCase();
        Assert.assertEquals(test.getActionCount(), 1);
        Assert.assertEquals(test.getActions().get(0).getClass(), DelegatingTestAction.class);
        Assert.assertEquals(((DelegatingTestAction)test.getActions().get(0)).getDelegate().getClass(), SendSoapMessageAction.class);

        SendSoapMessageAction action = (SendSoapMessageAction) ((DelegatingTestAction)test.getActions().get(0)).getDelegate();
        Assert.assertEquals(action.getName(), "send");

        Assert.assertEquals(action.getEndpoint(), soapClient);
        Assert.assertEquals(action.getMessageBuilder().getClass(), StaticMessageContentBuilder.class);

        StaticMessageContentBuilder messageBuilder = (StaticMessageContentBuilder) action.getMessageBuilder();
        Assert.assertEquals(messageBuilder.getMessage().getPayload(), "<TestRequest><data>cid:attachment01</data></TestRequest>");
        Assert.assertEquals(messageBuilder.getMessageHeaders().size(), 0L);

        Assert.assertTrue(action.getMtomEnabled());

        Assert.assertEquals(action.getAttachments().size(), 1L);
        Assert.assertNull(action.getAttachments().get(0).getContentResourcePath());
        Assert.assertEquals(action.getAttachments().get(0).getContent(), testAttachment.getContent());
        Assert.assertEquals(action.getAttachments().get(0).getContentId(), testAttachment.getContentId());
        Assert.assertEquals(action.getAttachments().get(0).getContentType(), testAttachment.getContentType());
        Assert.assertEquals(action.getAttachments().get(0).getCharsetName(), testAttachment.getCharsetName());
    }

    @Test
    public void testSoapAttachmentData() {
        MockTestDesigner builder = new MockTestDesigner(applicationContext, context) {
            @Override
            public void configure() {
                soap().client(soapClient)
                    .send()
                    .payload("<TestRequest><Message>Hello World!</Message></TestRequest>")
                    .attachment(testAttachment.getContentId(), testAttachment.getContentType(), testAttachment.getContent());
            }
        };

        builder.configure();

        TestCase test = builder.getTestCase();
        Assert.assertEquals(test.getActionCount(), 1);
        Assert.assertEquals(test.getActions().get(0).getClass(), DelegatingTestAction.class);
        Assert.assertEquals(((DelegatingTestAction)test.getActions().get(0)).getDelegate().getClass(), SendSoapMessageAction.class);

        SendSoapMessageAction action = (SendSoapMessageAction) ((DelegatingTestAction)test.getActions().get(0)).getDelegate();
        Assert.assertEquals(action.getName(), "send");

        Assert.assertEquals(action.getEndpoint(), soapClient);
        Assert.assertEquals(action.getMessageBuilder().getClass(), StaticMessageContentBuilder.class);

        StaticMessageContentBuilder messageBuilder = (StaticMessageContentBuilder) action.getMessageBuilder();
        Assert.assertEquals(messageBuilder.getMessage().getPayload(), "<TestRequest><Message>Hello World!</Message></TestRequest>");
        Assert.assertEquals(messageBuilder.getMessageHeaders().size(), 0L);

        Assert.assertEquals(action.getAttachments().size(), 1L);
        Assert.assertNull(action.getAttachments().get(0).getContentResourcePath());
        Assert.assertEquals(action.getAttachments().get(0).getContent(), testAttachment.getContent());
        Assert.assertEquals(action.getAttachments().get(0).getContentId(), testAttachment.getContentId());
        Assert.assertEquals(action.getAttachments().get(0).getContentType(), testAttachment.getContentType());
        Assert.assertEquals(action.getAttachments().get(0).getCharsetName(), testAttachment.getCharsetName());
    }

    @Test
    public void testMultipleSoapAttachmentData() {
        MockTestDesigner builder = new MockTestDesigner(applicationContext, context) {
            @Override
            public void configure() {
                soap().client(soapClient)
                        .send()
                        .payload("<TestRequest><Message>Hello World!</Message></TestRequest>")
                        .attachment(testAttachment.getContentId() + 1, testAttachment.getContentType(), testAttachment.getContent() + 1)
                        .attachment(testAttachment.getContentId() + 2, testAttachment.getContentType(), testAttachment.getContent() + 2);
            }
        };

        builder.configure();

        TestCase test = builder.getTestCase();
        Assert.assertEquals(test.getActionCount(), 1);
        Assert.assertEquals(test.getActions().get(0).getClass(), DelegatingTestAction.class);
        Assert.assertEquals(((DelegatingTestAction)test.getActions().get(0)).getDelegate().getClass(), SendSoapMessageAction.class);

        SendSoapMessageAction action = (SendSoapMessageAction) ((DelegatingTestAction)test.getActions().get(0)).getDelegate();
        Assert.assertEquals(action.getName(), "send");

        Assert.assertEquals(action.getEndpoint(), soapClient);
        Assert.assertEquals(action.getMessageBuilder().getClass(), StaticMessageContentBuilder.class);

        StaticMessageContentBuilder messageBuilder = (StaticMessageContentBuilder) action.getMessageBuilder();
        Assert.assertEquals(messageBuilder.getMessage().getPayload(), "<TestRequest><Message>Hello World!</Message></TestRequest>");
        Assert.assertEquals(messageBuilder.getMessageHeaders().size(), 0L);

        Assert.assertEquals(action.getAttachments().size(), 2L);
        Assert.assertNull(action.getAttachments().get(0).getContentResourcePath());
        Assert.assertEquals(action.getAttachments().get(0).getContent(), testAttachment.getContent() + 1);
        Assert.assertEquals(action.getAttachments().get(0).getContentId(), testAttachment.getContentId() + 1);
        Assert.assertEquals(action.getAttachments().get(0).getContentType(), testAttachment.getContentType());
        Assert.assertEquals(action.getAttachments().get(0).getCharsetName(), testAttachment.getCharsetName());
        Assert.assertNull(action.getAttachments().get(1).getContentResourcePath());
        Assert.assertEquals(action.getAttachments().get(1).getContent(), testAttachment.getContent() + 2);
        Assert.assertEquals(action.getAttachments().get(1).getContentId(), testAttachment.getContentId() + 2);
        Assert.assertEquals(action.getAttachments().get(1).getContentType(), testAttachment.getContentType());
        Assert.assertEquals(action.getAttachments().get(1).getCharsetName(), testAttachment.getCharsetName());
    }

    @Test
    public void testSoapAttachmentResource() throws IOException {
        MockTestDesigner builder = new MockTestDesigner(applicationContext, context) {
            @Override
            public void configure() {
                soap().client(soapClient)
                    .send()
                    .payload("<TestRequest><Message>Hello World!</Message></TestRequest>")
                    .attachment(testAttachment.getContentId(), testAttachment.getContentType(), resource);
            }
        };

        reset(resource);
        when(resource.getInputStream()).thenReturn(new ByteArrayInputStream("someAttachmentData".getBytes()));
        builder.configure();

        TestCase test = builder.getTestCase();
        Assert.assertEquals(test.getActionCount(), 1);
        Assert.assertEquals(test.getActions().get(0).getClass(), DelegatingTestAction.class);
        Assert.assertEquals(((DelegatingTestAction)test.getActions().get(0)).getDelegate().getClass(), SendSoapMessageAction.class);

        SendSoapMessageAction action = (SendSoapMessageAction) ((DelegatingTestAction)test.getActions().get(0)).getDelegate();
        Assert.assertEquals(action.getName(), "send");

        Assert.assertEquals(action.getEndpoint(), soapClient);
        Assert.assertEquals(action.getMessageBuilder().getClass(), StaticMessageContentBuilder.class);

        StaticMessageContentBuilder messageBuilder = (StaticMessageContentBuilder) action.getMessageBuilder();
        Assert.assertEquals(messageBuilder.getMessage().getPayload(), "<TestRequest><Message>Hello World!</Message></TestRequest>");
        Assert.assertEquals(messageBuilder.getMessageHeaders().size(), 0L);

        Assert.assertEquals(action.getAttachments().get(0).getContent(), "someAttachmentData");
        Assert.assertEquals(action.getAttachments().get(0).getContentId(), testAttachment.getContentId());
        Assert.assertEquals(action.getAttachments().get(0).getContentType(), testAttachment.getContentType());
        Assert.assertEquals(action.getAttachments().get(0).getCharsetName(), testAttachment.getCharsetName());
    }

    @Test
    public void testSendBuilderWithEndpointName() {
        reset(applicationContextMock);
        when(applicationContextMock.getBean(TestActionListeners.class)).thenReturn(new TestActionListeners());
        when(applicationContextMock.getBeansOfType(SequenceBeforeTest.class)).thenReturn(new HashMap<String, SequenceBeforeTest>());
        when(applicationContextMock.getBeansOfType(SequenceAfterTest.class)).thenReturn(new HashMap<String, SequenceAfterTest>());
        MockTestDesigner builder = new MockTestDesigner(applicationContextMock, context) {
            @Override
            public void configure() {
                soap().client("soapClient")
                    .send()
                    .payload("<TestRequest><Message>Hello World!</Message></TestRequest>")
                    .header("operation", "soapOperation")
                    .attachment(testAttachment);

                send("otherClient")
                    .payload("<TestRequest><Message>Hello World!</Message></TestRequest>");
            }
        };

        builder.configure();

        TestCase test = builder.getTestCase();
        Assert.assertEquals(test.getActionCount(), 2);
        Assert.assertEquals(test.getActions().get(0).getClass(), DelegatingTestAction.class);
        Assert.assertEquals(((DelegatingTestAction)test.getActions().get(0)).getDelegate().getClass(), SendSoapMessageAction.class);
        Assert.assertEquals(test.getActions().get(1).getClass(), DelegatingTestAction.class);
        Assert.assertEquals(((DelegatingTestAction)test.getActions().get(1)).getDelegate().getClass(), SendMessageAction.class);

        SendMessageAction action = (SendSoapMessageAction) ((DelegatingTestAction)test.getActions().get(0)).getDelegate();
        Assert.assertEquals(action.getName(), "send");
        Assert.assertEquals(action.getEndpointUri(), "soapClient");

        StaticMessageContentBuilder messageBuilder = (StaticMessageContentBuilder) action.getMessageBuilder();
        Assert.assertEquals(messageBuilder.getMessage().getPayload(), "<TestRequest><Message>Hello World!</Message></TestRequest>");
        Assert.assertEquals(messageBuilder.getMessageHeaders().size(), 1L);
        Assert.assertTrue(messageBuilder.getMessageHeaders().containsKey("operation"));

        action = (SendMessageAction) ((DelegatingTestAction)test.getActions().get(1)).getDelegate();
        Assert.assertEquals(action.getName(), "send");
        Assert.assertEquals(action.getEndpointUri(), "otherClient");
    }

}


text:
import * as reroute from '../update-add-stops-terminus'

const newStop = {
  stop_lon: -70,
  stop_lat: 40,
  stop_id: 'newStopId',
  stop_name: 'Stop name'
}

const newStopId = `feedId:${newStop.stop_id}`

describe('Utils > Reroute', () => {
  describe('segmentsFromStop', () => {
    it('should handle empty segments', () => {
      const segments = reroute.segmentsFromStop(newStop, [], newStopId)
      expect(segments).toHaveLength(1)
      expect(segments[0].geometry.type).toBe('Point')
      expect(segments[0].fromStopId).toBe(newStopId)
      expect(segments[0].toStopId).toBe(newStopId)
      expect(segments[0].geometry.coordinates[0]).toBe(newStop.stop_lon)
      expect(segments[0].geometry.coordinates[1]).toBe(newStop.stop_lat)
    })
  })

  describe('segmentsToStop', () => {
    it('should handle empty segments', () => {
      const segments = reroute.segmentsToStop(newStop, [], newStopId)
      expect(segments).toHaveLength(1)
      expect(segments[0].geometry.type).toBe('Point')
      expect(segments[0].fromStopId).toBe(newStopId)
      expect(segments[0].toStopId).toBe(newStopId)
      expect(segments[0].geometry.coordinates[0]).toBe(newStop.stop_lon)
      expect(segments[0].geometry.coordinates[1]).toBe(newStop.stop_lat)
    })

    it('should handle one point', () => {
      const segments = reroute.segmentsToStop(newStop, [
        reroute.stopToPoint([newStop.stop_lon, newStop.stop_lat], newStop.stop_id)
      ], newStopId)
      expect(segments).toHaveLength(1)
      expect(segments[0].geometry.type).toBe('LineString')
      expect(segments[0].fromStopId).toBe(newStop.stop_id)
      expect(segments[0].toStopId).toBe(newStopId)
      expect(segments[0].geometry.coordinates).toHaveLength(2)
      expect(segments[0].geometry.coordinates[0]).toHaveLength(2)
    })
  })
})


text:
#requires -Version 3
function Remove-RubrikNutanixVMSnapshot
{
  <#
      .SYNOPSIS
      Connects to Rubrik and removes an expired Nutanix VM snapshot available for garbage collection.

      .DESCRIPTION
      The Remove-RubrikNutanixVMSnapshot cmdlet will request that the Rubrik API delete an an expired Nutanix VM snapshot.
      The snapshot must a snapshot from a Nutanix VM that is not assigned to an SLA Domain.

      .NOTES
      Written by Mike Preston for community usage
      Twitter: @mwpreston
      GitHub: mwpreston

      .LINK
      https://rubrik.gitbook.io/rubrik-sdk-for-powershell/command-documentation/reference/remove-rubriknutanixvmsnapshot

      .EXAMPLE
      Remove-RubrikNutanixVMSnapshot -id '01234567-8910-1abc-d435-0abc1234d567'
      This will attempt to remove Nutanix VM snapshot (backup) data with the snapshot id `01234567-8910-1abc-d435-0abc1234d567`

      .EXAMPLE
      Remove-RubrikNutanixVMSnapshot -id '01234567-8910-1abc-d435-0abc1234d567' -location local -Confirm:$false
      This will attempt to remove the local copy of the Nutanix VM snapshot (backup) data with the snapshot id `01234567-8910-1abc-d435-0abc1234d567` without user intevention

      .EXAMPLE
      Get-RubrikNutanixVM VM1 | Get-RubrikSnapshot -Date '03/21/2017' | Remove-RubrikNutanixVMSnapshot
      This will attempt to remove any snapshot from `03/21/2017` for the Nutanix VM named `VM1`.
  #>

  [CmdletBinding(SupportsShouldProcess = $true,ConfirmImpact = 'High')]
  Param(
    # ID of the snapshot to delete
    [Parameter(Mandatory = $true,ValueFromPipelineByPropertyName = $true)]
    [String]$id,
    # Snapshot location to delete, either "local" or "all". Defaults to "all"
    [ValidateSet('all','local')]
    [String]$location = "all",
    # Rubrik server IP or FQDN
    [String]$Server = $global:RubrikConnection.server,
    # API version
    [ValidateNotNullorEmpty()]
    [String]$api = $global:RubrikConnection.api
  )

  Begin {

    # The Begin section is used to perform one-time loads of data necessary to carry out the function's purpose
    # If a command needs to be run with each iteration or pipeline input, place it in the Process section

    # Check to ensure that a session to the Rubrik cluster exists and load the needed header data for authentication
    Test-RubrikConnection

    # API data references the name of the function
    # For convenience, that name is saved here to $function
    $function = $MyInvocation.MyCommand.Name

    # Retrieve all of the URI, method, body, query, result, filter, and success details for the API endpoint
    Write-Verbose -Message "Gather API Data for $function"
    $resources = Get-RubrikAPIData -endpoint $function
    Write-Verbose -Message "Load API data for $($resources.Function)"
    Write-Verbose -Message "Description: $($resources.Description)"

  }

  Process {
    if ($PSCmdlet.ShouldProcess("$id", "Remove snapshot ")) {
        $uri = New-URIString -server $Server -endpoint ($resources.URI) -id $id
        $uri = Test-QueryParam -querykeys ($resources.Query.Keys) -parameters ((Get-Command $function).Parameters.Values) -uri $uri
        $body = New-BodyString -bodykeys ($resources.Body.Keys) -parameters ((Get-Command $function).Parameters.Values)
        $result = Submit-Request -uri $uri -header $Header -method $($resources.Method) -body $body
        $result = Test-ReturnFormat -api $api -result $result -location $resources.Result
        $result = Test-FilterObject -filter ($resources.Filter) -result $result

        return $result
    }
  } # End of process
} # End of function


text:
/*************************************************************************/
/*  button_group.h                                                       */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur.                 */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#ifndef BUTTON_GROUP_H
#define BUTTON_GROUP_H

#include "scene/gui/box_container.h"

class BaseButton;

class ButtonGroup : public BoxContainer {

	OBJ_TYPE(ButtonGroup,BoxContainer);

	Set<BaseButton*> buttons;

	Array _get_button_list() const;
	void _pressed(Object *p_button);

protected:
friend class BaseButton;

	void _add_button(BaseButton *p_button);
	void _remove_button(BaseButton *p_button);

	static void _bind_methods();
public:

	void get_button_list(List<BaseButton*> *p_buttons) const;
	BaseButton *get_pressed_button() const;
	BaseButton *get_focused_button() const;
	void set_pressed_button(BaseButton *p_button);
	int get_pressed_button_index() const;

	ButtonGroup();
};

#endif // BUTTON_GROUP_H


text:
tinyMCE.addI18n('pl.media_dlg',{
title:"Wstaw/Edytuj wbudowane media",
general:"G\u0142\u00F3wny",
advanced:"Zaawansowany",
file:"Plik/URL",
list:"Lista",
size:"Wymiary",
preview:"Podgl\u0105d",
constrain_proportions:"Zachowaj proporcje",
type:"Typ",
id:"Id",
name:"Nazwa",
class_name:"Klasa",
vspace:"V-Space",
hspace:"H-Space",
play:"Autoodtwarzanie",
loop:"Zap\u0119tlenie",
menu:"Poka\u017C menu",
quality:"Jako\u015B\u0107",
scale:"Skala",
align:"Wyr\u00F3wnaj",
salign:"SAlign",
wmode:"WMode",
bgcolor:"T\u0142o",
base:"Baza",
flashvars:"Flashvars",
liveconnect:"SWLiveConnect",
autohref:"AutoHREF",
cache:"Cache",
hidden:"Ukryty",
controller:"Controller",
kioskmode:"Kiosk mode",
playeveryframe:"Play every frame",
targetcache:"Target cache",
correction:"Bez korekcji",
enablejavascript:"W\u0142\u0105cz JavaScript",
starttime:"Start time",
endtime:"End time",
href:"Href",
qtsrcchokespeed:"Choke speed",
target:"Kom\u00F3rka",
volume:"G\u0142o\u015Bno\u015B\u0107",
autostart:"Auto start",
enabled:"Enabled",
fullscreen:"Pe\u0142ny ekran",
invokeurls:"Odwo\u0142aj si\u0119 do URLs",
mute:"Wycisz",
stretchtofit:"Rozci\u0105gnij aby dopasowa\u0107",
windowlessvideo:"Windowless video",
balance:"Balance",
baseurl:"Base URL",
captioningid:"Captioning id",
currentmarker:"Current marker",
currentposition:"Aktualna pozycja",
defaultframe:"Default frame",
playcount:"Play count",
rate:"Rate",
uimode:"UI Mode",
flash_options:"Flash opcje",
qt_options:"Quicktime opcje",
wmp_options:"Windows media player opcje",
rmp_options:"Real media player options",
shockwave_options:"Shockwave options",
autogotourl:"Auto goto URL",
center:"Center",
imagestatus:"Image status",
maintainaspect:"Maintain aspect",
nojava:"No java",
prefetch:"Prefetch",
shuffle:"Shuffle",
console:"Konsola",
numloop:"Liczba powt\u00F3rze\u0144",
controls:"Controls",
scriptcallbacks:"Script callbacks",
swstretchstyle:"Stretch style",
swstretchhalign:"Stretch H-Align",
swstretchvalign:"Stretch V-Align",
sound:"D\u017Awi\u0119k",
progress:"Progress",
qtsrc:"QT Src",
qt_stream_warn:"Streamed rtsp resources should be added to the QT Src field under the advanced tab.\nYou should also add a non streamed version to the Src field..",
align_top:"G\u00F3ra",
align_right:"Prawo",
align_bottom:"D\u00F3\u0142",
align_left:"Lewo",
align_center:"\u015Arodek",
align_top_left:"G\u00F3rny lewy",
align_top_right:"G\u00F3rny prawy",
align_bottom_left:"Dolny lewy",
align_bottom_right:"Dolny prawy",
flv_options:"Flash video opcje",
flv_scalemode:"Scale mode",
flv_buffer:"Buffer",
flv_startimage:"Start image",
flv_starttime:"Start time",
flv_defaultvolume:"Default volumne",
flv_hiddengui:"Ukryte GUI",
flv_autostart:"Auto start",
flv_loop:"Loop",
flv_showscalemodes:"Show scale modes",
flv_smoothvideo:"Smooth video",
flv_jscallback:"JS Callback"
});


text:
Cylon.js exists thanks to the efforts of the hardworking humans on the core team:

- Ron Evans ([@deadprogram](https://github.com/deadprogram))
- Edgar Silva ([@edgarSilva](https://github.com/edgarSilva))
- Andrew Stewart ([@stewart](https://github.com/stewart))
- Adrian Zankich ([@zankich](https://github.com/zankich))

And to the fine work of these wonderful contributors:

- Andrew Nesbitt ([@andrew](https://github.com/andrew))
- Chris Boette ([@chrisbodhi](https://github.com/chrisbodhi))
- Chris Mattheiu ([@chrismatthieu](https://github.com/chrismatthieu))
- Fábio Franco Uechi ([@fabito](https://github.com/fabito))
- Loren West ([@lorenwest](https://github.com/lorenwest))
- Mario "Kuroir" Ricalde ([@MarioRicalde](https://github.com/MarioRicalde))
- Javier Cervantes ([@solojavier](https://github.com/solojavier))
- Gize Bonilla ([@XixeBombilla](https://github.com/XixeBombilla))
- Nathan Zankich ([@zankavrogin](https://github.com/zankavrogin))

Thank you!

Please join us, we'd love your contribution too.


text:
<?php

namespace Dime\TimetrackerBundle\Tests\Entity;

use Dime\TimetrackerBundle\Entity\RateUnitTypeRepository;

class RateUnitTypeRepositoryTest extends DimeRepositoryTestCase
{
    // set up const for tests
    protected const ENTITY_NAME='DimeTimetrackerBundle:RateUnitType';
    protected const QB_ALIAS='r';

    // TESTS
    public function testSearch()
    {
        $rate_unit = $this->getRepo()->find('h');

        // find it by name
        // important: the internal query contains like queries, so we can't figure out
        // the exact amount through another query
        // but we know, that it should at least fire as much back as the findBy query
        $rate_units = $this->getRepo()->findBy(['name' => $rate_unit->getName()]);
        $this->assertGreaterThanOrEqual(count($rate_units), count($this->getRepoWithQB()
            ->search($rate_unit->getName())->getCurrentQueryBuilder()->getQuery()->execute()));
    }

    public function testScopeByDate()
    {
        // not implemented in this class
        $this->assertInstanceOf(
            RateUnitTypeRepository::class,
            $this->getRepoWithQB()->scopeByDate('date')
        );
    }
}


text:
'use strict';

var genericStyleBuilder = function(selectedText, styleMatchPre, styleMatchPost, stylePre, stylePost) {
  var regex = new RegExp('^' + styleMatchPre + '(.*)' + styleMatchPost + '$');
  var isStyled = regex.exec(selectedText);
  var text;
  if (isStyled && isStyled.length === 2) {
    text = isStyled[1];
  } else {
    text = stylePre + selectedText + stylePost;
  }
  return {
    text: text,
    defaultSelection: stylePre.length
  };
};

var genericListBuilder = function(selectedText, bulletMatch, bullet) {
  var regex = new RegExp(bulletMatch + '(\\s)(.*)(\\n{0,1})', 'gm');
  var isList = selectedText.match(regex);
  var text = '';
  if (isList) {
    isList.forEach(function(li) {
      var replaceRegex = new RegExp(bulletMatch + '(\\s)');
      text += li.replace(replaceRegex, '');
    });
  } else {
    var lines = selectedText.split('\n');
    text = bullet + ' ' + lines.join('\n' + bullet + ' ');
  }
  return {
    text: text,
    defaultSelection: bullet.length + 1
  };
};

var hotkeys = {
  'cge-bold': ['ctrl+b', 'meta+b'],
  'cge-italic': ['ctrl+i', 'meta+i'],
  'cge-strikethrough': ['ctrl+s', 'meta+s'],
  'cge-h1': ['alt+1'],
  'cge-h2': ['alt+2'],
  'cge-h3': ['alt+3'],
  'cge-quote': ['ctrl+q', 'meta+q'],
  'cge-code': ['ctrl+d', 'meta+d'],
  'cge-link': ['ctrl+k', 'meta+k'],
  'cge-image': ['ctrl+m', 'meta+m'],
  'cge-unordered-list': ['ctrl+u', 'meta+u'],
  'cge-ordered-list': ['ctrl+o', 'meta+o'],
  'cge-check-list': ['ctrl+h', 'meta+h'],
  'cge-horizontal-rule': ['ctrl+l', 'meta+l']
};

var listeners = {
  'cge-bold': function(selectedText) {
    return genericStyleBuilder(selectedText, '\\*\\*', '\\*\\*', '**', '**');
  },
  'cge-italic': function(selectedText) {
    return genericStyleBuilder(selectedText, '\\*', '\\*', '*', '*');
  },
  'cge-strikethrough': function(selectedText) {
    return genericStyleBuilder(selectedText, '~~', '~~', '~~', '~~');
  },
  'cge-quote': function(selectedText) {
    return genericStyleBuilder(selectedText, '> ', '', '> ', '');
  },
  'cge-h1': function(selectedText) {
    return genericStyleBuilder(selectedText, '\\#{1} ', '', '# ', '');
  },
  'cge-h2': function(selectedText) {
    return genericStyleBuilder(selectedText, '\\#{2} ', '', '## ', '');
  },
  'cge-h3': function(selectedText) {
    return genericStyleBuilder(selectedText, '\\#{3} ', '', '### ', '');
  },
  'cge-code': function(selectedText) {
    var isMultiCode = /^```\n((.|\n)*)\n```$/m.exec(selectedText);
    var text;
    if (isMultiCode && isMultiCode.length >= 2) {
      text = isMultiCode[1];
    } else {
      var isSingleCode = /^`(.*)`$/i.exec(selectedText);
      if (isSingleCode && isSingleCode.length === 2) {
        text = isSingleCode[1];
      } else if (selectedText.indexOf('\n') >= 0) {
        text = '```\n' + selectedText + '\n```';
      } else {
        text = '`' + selectedText + '`';
      }
    }
    return {
      text: text,
      defaultSelection: 1
    };
  },
  'cge-link': function(selectedText) {
    var isLink = /^\[(.*)\]\(.*\)$/i.exec(selectedText);
    var text, selectionStart, selectionEnd;
    if (isLink && isLink.length === 2) {
      text = isLink[1];
    } else {
      text = '[' + selectedText + ']()';
      selectionStart = selectedText.length + 3;
      selectionEnd = selectionStart;
    }
    return {
      text: text,
      selectionStart: selectionStart,
      selectionEnd: selectionEnd,
      defaultSelection: 3
    };
  },
  'cge-image': function(selectedText) {
    var isLink = /^\!\[(.*)\]\(.*\)$/i.exec(selectedText);
    var text, selectionStart, selectionEnd;
    if (isLink && isLink.length === 2) {
      text = isLink[1];
    } else {
      text = '![' + selectedText + ']()';
      selectionStart = selectedText.length + 4;
      selectionEnd = selectionStart;
    }
    return {
      text: text,
      selectionStart: selectionStart,
      selectionEnd: selectionEnd,
      defaultSelection: 2
    };
  },
  'cge-unordered-list': function(selectedText) {
    return genericListBuilder(selectedText, '(\\*|-)', '*');
  },
  'cge-ordered-list': function(selectedText) {
    return genericListBuilder(selectedText, '(\\d\\.)', '1.');
  },
  'cge-check-list': function(selectedText) {
    return genericListBuilder(selectedText, '(\\*|-)(\\s)(\\[(\\s|x|X)\\])', '* [ ]');
  },
  'cge-horizontal-rule': function(selectedText) {
    var isRule = /^\n(-{2,})$/.exec(selectedText);
    var text = '';
    if (!isRule) {
      text = '\n------';
    }
    return {
      text: text,
      defaultSelection: text.length
    };
  }
};

var getTextAreaSelection = function(textArea) {
  return [textArea.selectionStart, textArea.selectionEnd];
};

var applyEvent = function(eventType) {
  return function(event) {
    var textArea = $(event.target).parents('.chrome-github-editor').siblings('textarea.comment-form-textarea')[0];
    var selection = getTextAreaSelection(textArea);

    // get the selected text and its surroundings
    var content = $(textArea).val();
    var preText = content.substring(0, selection[0]);
    var selectedText = content.substring(selection[0], selection[1]);
    var postText = content.substring(selection[1], content.length);

    var newTextObj = listeners[eventType](selectedText);
    $(textArea)[0].value = preText + newTextObj.text + postText;

    // if there was something selected
    if (selection[0] < selection[1]) {
      // select the new content
      textArea.selectionStart = selection[0] + (newTextObj.selectionStart || 0);
      textArea.selectionEnd = selection[0] + (newTextObj.selectionEnd || newTextObj.text.length);
    } else {
      // otherwise put the selection to a custom single caret
      textArea.selectionStart = selection[0] + newTextObj.defaultSelection;
      textArea.selectionEnd = selection[0] + newTextObj.defaultSelection;
    }

    // re-focus the textarea
    $(textArea).trigger('focusin');
  };
};

var getHotkeyFn = function(targetButton) {
  return function() {
    targetButton.trigger('click');
    return false;
  };
};

var handleCommentBoxInserted = function(box) {
  if (box.find('.chrome-github-editor').length > 0) {
    return;
  }
  var content = box.find(
    // only visible comment areas (avoid the hidden one that will be clones)
    '.write-content:visible, ' +
    '.inline-comment-form-container.open .write-content, ' +
    'form.js-comment-update .write-content'
  );
  if (content.length < 0) {
    return;
  }
  $.get(chrome.extension.getURL('/template.html'))
    .done(function(template) {
      if (content.find('.chrome-github-editor').length > 0) {
        return;
      }
      // set up click listeners
      var bar = content.prepend(template);
      for (var l in listeners) {
        bar.find('.' + l).click(applyEvent(l));
      }
      var textArea = content.find('textarea');
      textArea.on('focusin', function() {
        // prevent default handling by the GitHub scripts (scrolls to top)
        // TODO: check if previous behaviour was corrected by GitHub, then remove this and trigger 'focus' on textareas
        return false;
      });
      // set up hotkeys
      for (var fn in hotkeys) {
        for (var key in hotkeys[fn]) {
          textArea.on('keydown', null, hotkeys[fn][key], getHotkeyFn(bar.find('.' + fn)));
        }
      }
    });
};

var handleMultipleBoxesInserted = function(boxes) {
  boxes.each(function() {
    handleCommentBoxInserted($(this));
  });
};

// build an observer
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    var newNodes = mutation.addedNodes; // DOM NodeList
    if (newNodes !== null) { // If there are new nodes added
      var $nodes = $(newNodes);
      var $node = $nodes.find(
        '.previewable-comment-form, ' +     // regular comments (new replies)
        'div.comment-content'               // potential comment edits
      );
      if ($node.length > 0) {
        handleMultipleBoxesInserted($node);
      }
    }
  });
});

// Configuration of the observer:
var config = {
  childList: true,
  subtree: true
};

var init = function() {
  // watch the whole GitHub dynamic container
  var targets = $('.repo-container');
  // watch for comment forms additions
  targets.each(function(index, target) {
    // Pass in the target node, as well as the observer options
    observer.observe(target, config);
  });

  // register the comment forms pre-loaded in the page
  handleMultipleBoxesInserted($(
    '.previewable-comment-form, ' +     // regular comments (new replies)
    'div.comment-content'               // potential comment edits
  ));
};

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.type === 'init') {
      init();
    }
  }
);