text:
<?php
namespace InterExperts\BalanceCalculator;

use \InterExperts\BalanceCalculator\Year;
use \InterExperts\BalanceCalculator\Action;
use \InterExperts\BalanceCalculator\UsedBalance;
use \InterExperts\BalanceCalculator\AddBalanceAction;

/**
 * Calculator for quota and balance operations
 */
class Calculator {
	/**
	 * Array of balance actions, sorted on the action date.
	 * @var array<Action> Array with Action objects
	 */
	protected $actions = array();

	/**
	 * Array of years used in calculating quota. Use addYear() to add new years
	 *
	 * @see addYear()
	 * @var array<Year> Array of Year objects
	 */
	public $years = array();

	/**
	 * Array of used balance. Use addUsedBalance() to add new used balance
	 *
	 * @see addUsedBalance()
	 * @var array<UsedBalance> Array of UsedBalance objects
	 */
	public $usedBalance = array();

	/**
	 * Flag if the calculated version is up to date
	 *
	 * @see recalculate()
	 * @var boolean Flag if the calculated version is up to date
	 */
	protected $isDirty = false;

	/**
	 * Add a Year object to be used for calculations.
	 * This method triggers recalculating quota.
	 *
	 * @param Year $year
	 */
	public function addYear(Year $year) {
		$this->years[] = $year;
		$this->isDirty = true;

	}

	public function addUsedBalance(UsedBalance $balance) {
		$this->usedBalance[] = $balance;
		$this->isDirty = true;
	}

	/**
	 * Recalculate quota based on $this->years.
	 * This method fills $this->actions which is used for balance queries
	 * like getBalanceForDate().
	 */
	protected function recalculate(){
		// Empty actions array:
		$this->actions = array();

		// Add balance actions to $this->actions for each year.
		// Each year triggers an 'add balance' action and a 'expire balance'
		// action. One add/expire pair for legal quotum and one pair for extra quotum.
		foreach($this->years as $year){
			$this->addDefaultActions($year);
		}

		// Process used balance
		foreach($this->usedBalance as $balance){
			$this->addUsedBalanceAction($balance);
		}

		// Sort $this->actions by the date attribute:
		usort($this->actions, function($a, $b){
			if($a->date == $b->date){
				return 0;
			}
			return ($a->date < $b->date) ? -1 : 1;
		});

		// Loop over actions, calculate expiring balance correctly:
		foreach($this->actions as &$action){
			if(is_a($action, '\InterExperts\BalanceCalculator\ExpireAction')){
				$action->calculateExpiringBalance($this->actions);
			}
		}
		$this->isDirty = false;
	}

	/**
	 * Retrieve the actual quotum for the given $date.
	 *
	 * This method returns the actual quotum for the given date,
	 * including quota from previous years and including quota expiry dates.
	 *
	 * @param  \DateTime $date Date for which the balance is queried
	 * @return int             Quotum
	 */
	public function getBalanceForDate(\DateTime $date, \DateTime $expireDate = null){
		$balanceActions = $this->getBalanceActionsForDate($date, $expireDate);
		return $balanceActions['balance'];
	}

	public function getAddBalanceActionsForDate(\DateTime $date, \DateTime $startDate){
		$balanceActions = $this->getBalanceActionsForDate($date);
		$actions = array();
		foreach($balanceActions['actions'] as $action){
			if($action->remainingBalance <> 0 && $action->expirationDate >= $startDate){
				$actions[] = $action;
			}
		}
		return $actions;
	}

	/**
	 * Retrieve the actual quotum and addBalanceActions for the given $date.
	 *
	 * This method returns the actual quotum  and addBalanceActions for the given date,
	 * including quota from previous years and including quota expiry dates.
	 *
	 * @param  \DateTime $date Date for which the balance is queried
	 * @return Array           Balance and AddBalance actions
	 */
	public function getBalanceActionsForDate(\DateTime $date, \DateTime $expireDate = null){
		if($this->isDirty){
			$this->recalculate();
		}
		$addActions = array();
		$currentBalance = 0;
		foreach($this->actions as &$action){
			if($action->date <= $date){
				if(is_a($action, '\InterExperts\BalanceCalculator\AddBalanceAction')){
					$action->remainingBalance = $action->addOperation;
					$addActions[] = &$action;
					$currentBalance -= $action->subOperation;
					$currentBalance += $action->addOperation;
				}elseif(is_a($action, '\InterExperts\BalanceCalculator\ExpireAction')){
					if(is_null($expireDate) || $action->date <= $expireDate){
						$action->originalAdd->remainingBalance -= $action->subOperation;
						$action->originalAdd->remainingBalance += $action->addOperation;
						$currentBalance -= $action->subOperation;
						$currentBalance += $action->addOperation;
					}
				}elseif(is_a($action, '\InterExperts\BalanceCalculator\UsedBalanceAction')){
					if(!is_null($action->processedBy) && !empty($action->processedBy)){
						foreach($action->processedBy as &$processAction) {
							$processAction->originalAdd->remainingBalance -= $action->subOperation;
							$processAction->originalAdd->remainingBalance += $action->addOperation;
						}
					}
					$currentBalance -= $action->subOperation;
					$currentBalance += $action->addOperation;
				}

			}else{
				break;
			}
		}
		return array('balance'=>$currentBalance, 'actions'=>$addActions);
	}

	/**
	 * Retrieve all ExpireActions from the actions list between $startDate and $endDate
	 * @param  \DateTime $startDate Start date
	 * @return array Array with all expire actions
	 */
	public function getExpireActions(\DateTime $startDate) {
		if($this->isDirty){
			$this->recalculate();
		}

		$expireActions = array();

		foreach ($this->actions as $action) {
			if (is_a($action, '\InterExperts\BalanceCalculator\ExpireAction')) {
				if ($action->date >= $startDate) {
					$expireActions[] = $action;
				}
			}
		}

		return $expireActions;
	}

	/**
	 * Retrieve the actual quotum for the given $date.
	 *
	 * This method returns the actual quotum for the given date,
	 * including quota from previous years and including quota expiry dates.
	 *
	 * @param  \DateTime $date Date for which the balance is queried
	 * @return int             Quotum
	 */
	public function getUnexpiredBalance(\DateTime $date, \DateTime $expireDate){
		if($this->isDirty){
			$this->recalculate();
		}
		$currentBalance = 0;
		foreach($this->actions as $action){
			if($action->date <= $date){
				if(!($action->date > $expireDate && is_a($action, '\InterExperts\BalanceCalculator\ExpireAction'))){
					$currentBalance -= $action->subOperation;
					$currentBalance += $action->addOperation;
				}
			}else{
				break;
			}
		}
		return $currentBalance;
	}

	protected function addDefaultActions(Year $year){
		$legalAction = new AddBalanceAction($year->startDate, $year->quotumLegal, 0);
		$legalAction->expirationDate = $year->getQuotumLegalExpirationDate();
		$this->actions[] = $legalAction;
		$this->actions[] = new ExpireAction($year->getQuotumLegalExpirationDate(), 0, $year->quotumLegal, $legalAction);

		$extraAction = new AddBalanceAction($year->startDate, $year->quotumExtra, 0);
		$extraAction->expirationDate = $year->getQuotumExtraExpirationDate();
		$this->actions[] = $extraAction;
		$this->actions[] = new ExpireAction($year->getQuotumExtraExpirationDate(), 0, $year->quotumExtra, $extraAction);
	}

	/**
	 * Add 'used balance' action to $this->actions for the given UsedBalance.
	 *
	 * @param UsedBalance $balance UsedBalance object
	 */
	protected function addUsedBalanceAction(UsedBalance $balance){
		$this->actions[] = new UsedBalanceAction($balance->date, 0, $balance->amount);
	}
}


text:
package builds

import (
	"fmt"
	"sync"
	"time"

	"k8s.io/kubernetes/pkg/util/wait"

	g "github.com/onsi/ginkgo"
	o "github.com/onsi/gomega"

	buildapi "github.com/openshift/origin/pkg/build/api"
	exutil "github.com/openshift/origin/test/extended/util"
)

var _ = g.Describe("builds: parallel: oc start-build", func() {
	defer g.GinkgoRecover()
	var (
		buildFixture = exutil.FixturePath("..", "extended", "fixtures", "test-build.json")
		oc           = exutil.NewCLI("cli-start-build", exutil.KubeConfigPath())
	)

	g.JustBeforeEach(func() {
		g.By("waiting for builder service account")
		err := exutil.WaitForBuilderAccount(oc.KubeREST().ServiceAccounts(oc.Namespace()))
		o.Expect(err).NotTo(o.HaveOccurred())
		oc.Run("create").Args("-f", buildFixture).Execute()
	})

	g.Describe("oc start-build --wait", func() {
		g.It("should start a build and wait for the build to complete", func() {
			g.By("starting the build with --wait flag")
			out, err := oc.Run("start-build").Args("sample-build", "--wait").Output()
			o.Expect(err).NotTo(o.HaveOccurred())

			g.By(fmt.Sprintf("verifying the build %q status", out))
			build, err := oc.REST().Builds(oc.Namespace()).Get(out)
			o.Expect(err).NotTo(o.HaveOccurred())
			o.Expect(build.Status.Phase).Should(o.BeEquivalentTo(buildapi.BuildPhaseComplete))

		})

		g.It("should start a build and wait for the build to fail", func() {
			g.By("starting the build with --wait flag but wrong --commit")
			out, err := oc.Run("start-build").
				Args("sample-build", "--wait", "--commit", "fffffff").
				Output()
			o.Expect(err).To(o.HaveOccurred())
			o.Expect(out).Should(o.ContainSubstring(`status is "Failed"`))
		})
	})

	g.Describe("cancelling build started by oc start-build --wait", func() {
		g.It("should start a build and wait for the build to cancel", func() {
			g.By("starting the build with --wait flag")
			var wg sync.WaitGroup
			wg.Add(1)
			go func() {
				defer g.GinkgoRecover()
				out, err := oc.Run("start-build").Args("sample-build", "--wait").Output()
				defer wg.Done()
				o.Expect(err).To(o.HaveOccurred())
				o.Expect(out).Should(o.ContainSubstring(`status is "Cancelled"`))
			}()

			g.By("getting the build name")
			var buildName string
			wait.Poll(time.Duration(100*time.Millisecond), time.Duration(60*time.Second), func() (bool, error) {
				out, err := oc.Run("get").
					Args("build", "-t", "{{ (index .items 0).metadata.name }}").Output()
				// Give it second chance in case the build resource was not created yet
				if err != nil || len(out) == 0 {
					return false, nil
				}
				buildName = out
				return true, nil
			})

			o.Expect(buildName).ToNot(o.BeEmpty())

			g.By(fmt.Sprintf("cancelling the build %q", buildName))
			err := oc.Run("cancel-build").Args(buildName).Execute()
			o.Expect(err).ToNot(o.HaveOccurred())
			wg.Wait()
		})

	})

})

redpajama_set_name: RedPajamaGithub


text:
/**
 */
package pipeline.tests;

import junit.textui.TestRunner;

import pipeline.PipelineFactory;
import pipeline.Source;

/**
 *
 * A test case for the model object 'Source'.
 *
 * @generated
 */
public class SourceTest extends PipelineNodeTest
{

  /**
	 *
   *
	 * @generated
	 */
  public static void main(String[] args)
  {
		TestRunner.run(SourceTest.class);
	}

  /**
	 * Constructs a new Source test case with the given name.
	 *
   *
	 * @generated
	 */
  public SourceTest(String name)
  {
		super(name);
	}

  /**
	 * Returns the fixture for this Source test case.
	 *
   *
	 * @generated
	 */
  @Override
  protected Source getFixture()
  {
		return (Source)fixture;
	}

  /**
	 *
   *
	 * @see junit.framework.TestCase#setUp()
	 * @generated
	 */
  @Override
  protected void setUp() throws Exception
  {
		setFixture(PipelineFactory.eINSTANCE.createSource());
	}

  /**
	 *
   *
	 * @see junit.framework.TestCase#tearDown()
	 * @generated
	 */
  @Override
  protected void tearDown() throws Exception
  {
		setFixture(null);
	}

} //SourceTest


text:
Copyright 2007-2008 Alexey Radul.
----------------------------------------------------------------------
This file is part of Test Manager.

Test Manager is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Test Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Test Manager.  If not, see <http://www.gnu.org/licenses/>.
----------------------------------------------------------------------

=pod

=head1 NAME

test-manager/ - An automatic unit-testing framework for MIT Scheme or Guile

=head1 SYNOPSYS

  (load "test-manager/load.scm")

  (in-test-group
   simple-stuff
   (define-test (arithmetic)
     "Checking that set! and arithmetic work"
     (define foo 5)
     (assert-= 5 foo "Foo should start as five.")
     (set! foo 6)
     (assert-= 36 (* foo foo)))
   ; Each of these will become a separate anonymous one-form test
   (define-each-test
     (assert-= 4 (+ 2 2) "Two and two should make four.")
     (assert-= 6 (+ 2 2 2))
     (assert-= 2147483648 (+ 2147483647 1) "Addition shouldn't overflow.")
     (assert-equal '(1 2 3) (cons 1 '(2 3))))

  (run-registered-tests)

=head1 DESCRIPTION

This test framework defines a language for specifying test suites and
a simple set of commands for running them.  A test suite is a
collection of individual tests grouped into a hierarchy of test
groups.  The test group hierarchy serves to semantically aggregate the
tests, allowing the definition of shared code for set up, tear down,
and surround, and also partition the test namespace to avoid
collisions.

The individual tests are ordinary procedures, with some associated
bookkeeping.  A test is considered to pass if it returns normally,
and to fail if it raises some condition that it does not handle
(tests escaping into continuations leads to unspecified behavior).
The framework provides a library of assertions that can be invoked
in tests and have the desired behavior of raising an appropriate
condition if they fail.

=head2 Defining Test Suites

All tests are grouped into a hierarchy of test groups.
At any point in the definition of a test suite, there is an implicit
"current test group", into which tests and subgroups can be added.  By
default, the current test group is the top-level test group, which is
the root of the test group hierarchy.

=over

=item (define-test (name) expression ... )

Define a test named C<name> that consists of the given expressions,
and add it to the current test group.  When the test is run, the
expressions will be executed in order, just like the body of any
procedure.  If the test raises any condition that it does not handle,
it is considered to have failed.  If it returns normally, it is
considered to have passed.  Usually, tests will contain assertions
from the list below, which raise appropriate conditions when they
fail.  In the spirit of Lisp docstrings, if the first expression in
the test body is a literal string, that string will be included in the
failure report if the test should fail.

This is the most verbose and most expressive test definition syntax.
The three test definition syntaxes provided below are increasingly
terse syntactic sugar for common usage patterns of this syntax.

=item (define-test () expression ... )

Define an explicitly anonymous test.  I can't see why you would want
to do this, but it is provided for completeness.

=item (define-test expression)

Define a one-expression anonymous test.  The single expression will be
printed in the failure report if the test fails.  This is a special
case of C<define-each-test>, below.

=item (define-each-test expression ... )

Define a one-expression anonymous test for each of the given
expressions.  If any of the tests fail, the corresponding expression
will be printed in that test's failure report.

If you have many simple independent assertions you need to make and
you don't want to invent names for each individual one, this is the
test definition syntax for you.

=item (in-test-group name expression ... )

Locate (or create) a test subgroup called C<name> in the current test
group.  Then temporarily make this subgroup the current test group,
and execute the expressions in the body of C<in-test-group>.  This
groups any tests and further subgroups defined by those expressions
into this test group.  Test groups can nest arbitrarily deep.  Test
groups serve to disambiguate the names of tests, and to group them
semantically.  In particular, should a test fail, the names of the
stack of groups it's in will be displayed along with the test name
itself.

=item (define-set-up expression ...)

Defines a sequence of expressions to be run before every test in
the current test group.  Clobbers any previously defined set up
for this group.

=item (define-tear-down expression ...)

Defines a sequence of expressions to be run after every test in
the current test group.  Clobbers any previously defined tear down
for this group.

=item (define-surround expression ...)

Defines a sequence of expressions to be run surrounding every test in
the current test group.  Inside the C<define-surround>, the identifier
C<run-test> is bound to a nullary procedure that actually runs the
test.  Clobbers any previously defined surround for this group.

=item (define-group-set-up expression ...)

Defines a sequence of expressions to be run once before running any
test in the current test group.  Clobbers any previously defined group
set up for this group.

=item (define-group-tear-down expression ...)

Defines a sequence of expressions to be run once after running all
tests in the current test group.  Clobbers any previously defined
group tear down for this group.

=item (define-group-surround expression ...)

Defines a sequence of expressions to be run once surrounding running
the tests in the current test group.  Inside the
C<define-group-surround>, the identifier C<run-test> is bound to a
nullary procedure that actually runs the tests in this group.
Clobbers any previously defined group surround for this group.

=back

=head2 Running Test Suites

The following procedures are provided for running test suites:

=over

=item (run-test name-stack)

Looks up the test indicated by name-stack in the current test group,
runs it, and prints a report of the results.  Returns the number of
tests that did not pass.  An empty list for a name stack indicates the
whole group, a singleton list indicates that immediate descendant, a
two-element list indicates a descendant of a descendant, etc.  For
example, C<(run-test '(simple-stuff harder))> would run the second
test defined in the example at the top of this page.

=item (run-registered-tests)

Runs all tests registered so far, and prints a report of the results.
Returns the number of tests that did not pass.  This could have been
defined as C<(run-test '())>.

=back

=head2 Assertions

The following assertions are provided for writing tests.  The
C<message> arguments to the assertions are user-specified messages to
print to the output if the given assertion fails.  The C<assert-proc>
assertion requires a message argument because it cannot construct a
useful output without one, and because it is not really meant for
extensive direct use.  The message is optional for the other
assertions because they can say something at least mildly informative
even without a user-supplied message.  In any case, the message can be
either a string or a promise (as created by C<delay>) to produce a
string.  The latter is useful for assertions with dynamically computed
messages, because that computation will then only be performed if the
test actually fails.

=over

=item (assert-proc message proc)

Passes iff the given procedure, invoked with no arguments, returns a
true value.  On failure, arranges for the given C<message> to appear in
the failure report.  This is a primitive assertion in whose terms
other assertions are defined.

=item (assert-true thing [message])

Passes iff the given value is a true value (to wit, not #f).

=item (assert-false thing [message])

Passes iff the given value is a false value (to wit, #f).

=item (assert-equal expected actual [message])
 Likewise assert-eqv, assert-eq, and assert-=

Passes iff the given C<actual> value is equivalent, according to the
corresponding predicate, to the C<expected> value.  Produces a
reasonably helpful message on failure, and includes the optional
C<message> argument in it if present.  When in doubt, use
C<assert-equal> to compare most things; use C<assert-=> to compare
exact numbers like integers; and use C<assert-in-delta>, below, for
inexact numbers like floating points.

=item assert-equals, assert=

Are aliases for assert-equal and assert-=, respectively.

=item (assert-equivalent predicate [pred-name])

This is intended as a tool for building custom assertions.  Returns an
assertion procedure that compares an expected and an actual value with
the given predicate and produces a reasonable failure message.
C<assert-equal> and company could have been defined in terms of
C<assert-equivalent> as, for example, C<(define assert-equal
(assert-equivalent equal? "equal?"))>.

=item (assert-matches regexp string [message])

Passes iff the given regular expression matches the given string.

=item (assert-no-match regexp string [message])

Passes iff the given regular expression does not match the given
string.

=item (assert-in-delta expected actual delta [message])

Passes iff the given C<actual> value differs, in absolute value, from
the given C<expected> value by no more than C<delta>.  Use this in
preference to C<assert-=> to check sameness of inexact numerical
values.

=back

=head1 BUGS

This unit testing framework is a work in progress.  The assertion
library is quite impoverished, the test groups do not support as much
shared set up code among their tests as I would like, and the language
for explicit test group handling is ill-specified and undocumented
(peruse test-group.scm if interested).  Suggestions are welcome.

=head1 AUTHOR

Alexey Radul, axch@mit.edu

=cut


text:
<?php
class Musermanual extends APP_Model {
	public function getData($page, $row, $order_by = null, $order = null, $filter_by = null, $filter_value = null)
	{
		$ex_or = $ex_filter = '';
		$par = false;

		if ($order_by != null) {
			$order_by = $order_by;
			$ex_or = ' order by '.$order_by.' '.$order;
		}

		if ($filter_by != null && $filter_value != null) {
			$ex_filter = ' where '.$filter_by.' like ? ';
			$par['p1'] = '%'.$filter_value.'%';
		}

		$sql = "select
				a.*, b.display_name as created_by_v,
				date_format(a.created_date, '%d-%m-%Y') as created_date_v,
				case when status = 1 then 'Published'
				else 'Unpublished'
				end as status_v
				from t_user_manual a left join
				m_user b on a.created_by = b.username"
				.$ex_filter
				.$ex_or;
		$res = $this->getPagingData($sql, $par, $page, $row, 'id', true);
		return $res;
	}

	public function getAll()
	{
		$sql = "select
				a.*, b.display_name as created_by_v,
				date_format(a.created_date, '%d-%m-%Y') as created_date_v,
				case when status = 1 then 'Published'
				else 'Unpublished'
				end as status_v
				from t_user_manual a left join
				m_user b on a.created_by = b.username";
		$query = $this->db->query($sql);

		$res = array();
		foreach($query->result_array() as $row) {
			$res[] = $row;
		}

		return $res;
	}

	public function getAllPublished()
	{
		$role = $this->session->credential['role_id'];
		if($role == 3){
		$sql = "select
				a.*, b.display_name as created_by_v,
				date_format(a.created_date, '%d-%m-%Y') as created_date_v,
				case when status = 1 then 'Published'
				else 'Unpublished'
				end as status_v
				from t_user_manual a left join
				m_user b on a.created_by = b.username
				where a.status = 1 and a.id_user = 3";
		}else if($role == 4){
		$sql = "select
				a.*, b.display_name as created_by_v,
				date_format(a.created_date, '%d-%m-%Y') as created_date_v,
				case when status = 1 then 'Published'
				else 'Unpublished'
				end as status_v
				from t_user_manual a left join
				m_user b on a.created_by = b.username
				where a.status = 1 and a.id_user = 4";
		}else if($role == 5){
		$sql = "select
				a.*, b.display_name as created_by_v,
				date_format(a.created_date, '%d-%m-%Y') as created_date_v,
				case when status = 1 then 'Published'
				else 'Unpublished'
				end as status_v
				from t_user_manual a left join
				m_user b on a.created_by = b.username
				where a.status = 1 and a.id_user = 5";
		}else if($role == 2){
		$sql = "select
				a.*, b.display_name as created_by_v,
				date_format(a.created_date, '%d-%m-%Y') as created_date_v,
				case when status = 1 then 'Published'
				else 'Unpublished'
				end as status_v
				from t_user_manual a left join
				m_user b on a.created_by = b.username
				where a.status = 1 and a.id_user = 2";
		}else if($role == 1){
		$sql = "select
				a.*, b.display_name as created_by_v,
				date_format(a.created_date, '%d-%m-%Y') as created_date_v,
				case when status = 1 then 'Published'
				else 'Unpublished'
				end as status_v
				from t_user_manual a left join
				m_user b on a.created_by = b.username
				where a.status = 1";
		}

		$query = $this->db->query($sql);

		$res = array();
		foreach($query->result_array() as $row) {
			$res[] = $row;
		}

		return $res;
	}

	public function getDataById($id)
	{
		$sql = "select
				a.*, b.display_name as created_by_v,
				date_format(a.created_date, '%d-%m-%Y') as created_date_v,
				case when status = 1 then 'Published'
				else 'Unpublished'
				end as status_v
				from t_user_manual a left join
				m_user b on a.created_by = b.username
				where a.id = ?";
		$query = $this->db->query($sql, array('divid' => $id));
		$row = $query->row_array();
		return $row;
	}

	public function insertData($data)
	{
		$sql = "insert into t_user_manual
				(title, filename, status, created_by, created_date,content,id_user)
				values(?, ?, ?, ?, NOW(), ?, ?)
				";
		$par = $data;
		$res = $this->db->query($sql, $par);
		return $res;
	}

	public function updateData($data_id, $data, $uid)
	{
		if (isset($data['filename'])) {
			$sql = "update t_user_manual
					set title = ?, filename = ?, status = ?, created_by = ?,
						created_date = NOW(), content = ?, id_user = ?
					where id = ?
					";
			$par = $data;
			$par['data_id'] = $data_id;

		} else {
			$sql = "update t_user_manual
					set title = ?, status = ?, created_by = ?,
						created_date = NOW(), content = ?, id_user = ?
					where id = ?
					";
			$par = $data;
			$par['data_id'] = $data_id;
		}
		$res = $this->db->query($sql, $par);
		return $res;
	}

	public function deleteData($data_id, $path, $uid)
	{
		$news = $this->getDataById($data_id);
		if ($news) {
			@unlink($path.'/'.$news['filename']);

			$sql = "delete from t_user_manual
					where id = ?
					";
			$par['data_id'] = $data_id;

			$res = $this->db->query($sql, $par);
			return $res;
		}
		return false;
	}

}


text:
var opent2t = require("./opent2t");
/**
 * Sample of a server that use polling to execute a set of predefined rules
 * Once the ruleEngine is initialized, it start running a polling loop
 * and execute the rules defined in the rules/ directory.
 * Rules use APIs available in the thingTranslator file that can be used
 * to retrieve the state of a device. For instance, a Temperature Sensor exposes
 * a method getCurrentTemperature that can be used to retrieve the last
 * temperature registered by the sensor.
 *
 */
opent2t.init(process.argv[2], process.argv[3], function(err) {
    if(err)
        console.error(err);
     else {
        console.log("launching ruleEngine ....");
        // starts the polling cycle and execute the rules in the rules/ directory
        // polling interval is determined by the 'pollingInterval' value in the config file
        opent2t.startPolling();
     }

});


text:
package org.apache.hadoop.hdfs.server.blockmanagement;

import com.google.common.collect.Lists;
import io.hops.common.INodeUtil;
import io.hops.exception.StorageException;
import io.hops.metadata.hdfs.entity.INodeIdentifier;
import io.hops.transaction.handler.HDFSOperationType;
import io.hops.transaction.handler.HopsTransactionalRequestHandler;
import io.hops.transaction.lock.LockFactory;
import io.hops.transaction.lock.TransactionLocks;
import java.io.Closeable;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSTestUtil;
import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.MiniDFSCluster.DataNodeProperties;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.server.datanode.DataNode;
import org.apache.hadoop.hdfs.server.datanode.DataNodeTestUtils;
import org.apache.hadoop.hdfs.server.namenode.FSNamesystem;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.hadoop.hdfs.server.namenode.ha.HATestUtil;
import org.apache.hadoop.hdfs.server.namenode.ha.TestDNFencing;
import org.apache.hadoop.io.IOUtils;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;

/**
 * Test when RBW block is removed. Invalidation of the corrupted block happens
 * and then the under replicated block gets replicated to the datanode.
 */
public class TestRBWBlockInvalidation {
  private static final Log LOG = LogFactory.getLog(TestRBWBlockInvalidation.class);

  private static NumberReplicas countReplicas(final FSNamesystem namesystem,
      final ExtendedBlock block) throws IOException {
    return (NumberReplicas) new HopsTransactionalRequestHandler(
        HDFSOperationType.COUNT_NODES) {
      INodeIdentifier inodeIdentifier;

      @Override
      public void setUp() throws StorageException, IOException {
        inodeIdentifier =
            INodeUtil.resolveINodeFromBlock(block.getLocalBlock());
      }

      @Override
      public void acquireLock(TransactionLocks locks) throws IOException {
        LockFactory lf = LockFactory.getInstance();
        locks
            .add(lf.getIndividualBlockLock(block.getBlockId(), inodeIdentifier))
            .add(lf.getBlockRelated(LockFactory.BLK.RE, LockFactory.BLK.ER,
                LockFactory.BLK.CR));
      }

      @Override
      public Object performTask() throws StorageException, IOException {
        return namesystem.getBlockManager().countNodes(block.getLocalBlock());
      }

    }.handle(namesystem);
  }

  /**
   * Test when a block's replica is removed from RBW folder in one of the
   * datanode, namenode should ask to invalidate that corrupted block and
   * schedule replication for one more replica for that under replicated block.
   */
  @Test(timeout = 600000)
  public void testBlockInvalidationWhenRBWReplicaMissedInDN()
      throws IOException, InterruptedException {
    // This test cannot pass on Windows due to file locking enforcement.  It will
    // reject the attempt to delete the block file from the RBW folder.
    assumeTrue(!Path.WINDOWS);
    Configuration conf = new HdfsConfiguration();
    conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, 2);
    conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 300);
    conf.setLong(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 1);
    conf.setLong(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1);
    MiniDFSCluster cluster =
        new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
    FSDataOutputStream out = null;
    try {
      final FSNamesystem namesystem = cluster.getNamesystem();
      FileSystem fs = cluster.getFileSystem();
      Path testPath = new Path("/tmp/TestRBWBlockInvalidation", "foo1");
      out = fs.create(testPath, (short) 2);
      out.writeBytes("HDFS-3157: " + testPath);
      out.hsync();
      cluster.startDataNodes(conf, 1, true, null, null, null);
      String bpid = namesystem.getBlockPoolId();
      ExtendedBlock blk = DFSTestUtil.getFirstBlock(fs, testPath);
      Block block = blk.getLocalBlock();
      DataNode dn = cluster.getDataNodes().get(0);

      // Delete partial block and its meta information from the RBW folder
      // of first datanode.
      File blockFile = DataNodeTestUtils.getBlockFile(dn, bpid, block);
      File metaFile = DataNodeTestUtils.getMetaFile(dn, bpid, block);
      assertTrue("Could not delete the block file from the RBW folder",
          blockFile.delete());
      assertTrue("Could not delete the block meta file from the RBW folder",
          metaFile.delete());

      out.close();

      int liveReplicas = 0;
      while (true) {
        if ((liveReplicas = countReplicas(namesystem, blk).liveReplicas()) < 2) {
          // This confirms we have a corrupt replica
          LOG.info("Live Replicas after corruption: " + liveReplicas);
          break;
        }
        Thread.sleep(100);
      }
      assertEquals("There should be less than 2 replicas in the liveReplicasMap", 1, liveReplicas);

      while (true) {
        if ((liveReplicas = countReplicas(namesystem, blk).liveReplicas()) > 1) {
          //Wait till the live replica count becomes equal to Replication Factor
          LOG.info("Live Replicas after Rereplication: " + liveReplicas);
          break;
        }
        Thread.sleep(100);
      }
      assertEquals("There should be two live replicas", 2, liveReplicas);

      while (true) {
        Thread.sleep(100);
        if (countReplicas(namesystem, blk).corruptReplicas() == 0) {
          LOG.info("Corrupt Replicas becomes 0");
          break;
        }
      }
    } finally {
      if (out != null) {
        out.close();
      }
      cluster.shutdown();
    }
  }

  /**
   * Regression test for HDFS-4799, a case where, upon restart, if there
   * were RWR replicas with out-of-date genstamps, the NN could accidentally
   * delete good replicas instead of the bad replicas.
   */
  @Test(timeout = 60000)
  public void testRWRInvalidation() throws Exception {
    Configuration conf = new HdfsConfiguration();

    // Set the deletion policy to be randomized rather than the default.
    // The default is based on disk space, which isn't controllable
    // in the context of the test, whereas a random one is more accurate
    // to what is seen in real clusters (nodes have random amounts of free
    // space)
    conf.setClass(DFSConfigKeys.DFS_BLOCK_REPLICATOR_CLASSNAME_KEY,
        TestDNFencing.RandomDeleterPolicy.class, BlockPlacementPolicy.class);

    // Speed up the test a bit with faster heartbeats.
    conf.setInt(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1);

    // Test with a bunch of separate files, since otherwise the test may
    // fail just due to "good luck", even if a bug is present.
    List<Path> testPaths = Lists.newArrayList();
    for (int i = 0; i < 10; i++) {
      testPaths.add(new Path("/test" + i));
    }

    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2)
        .build();
    try {
      List<FSDataOutputStream> streams = Lists.newArrayList();
      try {
        // Open the test files and write some data to each
        for (Path path : testPaths) {
          FSDataOutputStream out = cluster.getFileSystem().create(path, (short) 2);
          streams.add(out);

          out.writeBytes("old gs data\n");
          out.hflush();
        }

        // Shutdown one of the nodes in the pipeline
        DataNodeProperties oldGenstampNode = cluster.stopDataNode(0);

        // Write some more data and flush again. This data will only
        // be in the latter genstamp copy of the blocks.
        for (int i = 0; i < streams.size(); i++) {
          Path path = testPaths.get(i);
          FSDataOutputStream out = streams.get(i);

          out.writeBytes("new gs data\n");
          out.hflush();

          // Set replication so that only one node is necessary for this block,
          // and close it.
          cluster.getFileSystem().setReplication(path, (short) 1);
          out.close();
        }

        // Upon restart, there will be two replicas, one with an old genstamp
        // and one current copy. This test wants to ensure that the old genstamp
        // copy is the one that is deleted.
        LOG.info("=========================== restarting cluster");
        DataNodeProperties otherNode = cluster.stopDataNode(0);
        cluster.restartNameNode(false);

        // Restart the datanode with the corrupt replica first.
        cluster.restartDataNode(oldGenstampNode);
        cluster.waitActive();

        // Then the other node
        cluster.restartDataNode(otherNode);
        cluster.waitActive();

        // Compute and send invalidations, waiting until they're fully processed.
        cluster.getNameNode().getNamesystem().getBlockManager()
            .computeInvalidateWork(2);
        cluster.triggerHeartbeats();
        HATestUtil.waitForDNDeletions(cluster);
        cluster.triggerDeletionReports();

        // Make sure we can still read the blocks.
        for (Path path : testPaths) {
          String ret = DFSTestUtil.readFile(cluster.getFileSystem(), path);
          assertEquals("old gs data\n" + "new gs data\n", ret);
        }
      } finally {
        IOUtils.cleanup(LOG, streams.toArray(new Closeable[0]));
      }
    } finally {
      cluster.shutdown();
    }

  }
}


text:
require_relative 'payload'
#
module Pushofy
  class ApplePayload < Payload
    attr_accessor :message
    attr_accessor :sound_name
    attr_accessor :badge_number
    attr_accessor :action_key_caption
    attr_accessor :dict
    def initialize(message, sound_name, badge_number, action_key_caption, dict)
      @message = message
      @sound_name = sound_name
      @badge_number = badge_number
      @action_key_caption = action_key_caption
      @dict = dict
    end
  end
end


text:
//
// Multivariate Guassian Noise
// Original from Humphrey Hu
// (https://github.com/Humhu/argus_utils/blob/devel/include/argus_utils/random/MultivariateGaussian.hpp)
// Adapted by Arun Venkatraman
//

#include <utils/multivariate_gaussian.hh>

#include <utils/debug_utils.hh>

namespace math
{

MultivariateGaussian::MultivariateGaussian(const int dim)
    : MultivariateGaussian(Eigen::VectorXd::Zero(dim), Eigen::MatrixXd::Identity(dim, dim))
{
}

MultivariateGaussian::MultivariateGaussian(const int dim, const int seed)
    : MultivariateGaussian(Eigen::VectorXd::Zero(dim), Eigen::MatrixXd::Identity(dim, dim), seed)
{
}

MultivariateGaussian::MultivariateGaussian(const Eigen::VectorXd& mu, const Eigen::MatrixXd& sigma)
    : distribution_(0.0, 1.0),
      mean_(mu)
{
    IS_GREATER(mu.size(), 0);
    std::random_device rng;
    gen_.seed(rng());
    initialize_cov(sigma);
}

MultivariateGaussian::MultivariateGaussian(const Eigen::VectorXd& mu,
        const Eigen::MatrixXd& sigma, const int seed)
    : distribution_(0.0, 1.0),
      mean_(mu)
{
    IS_GREATER(mu.size(), 0);
    gen_.seed(seed);
    initialize_cov(sigma);
}

MultivariateGaussian::MultivariateGaussian(const MultivariateGaussian& other)
    : gen_(other.gen_),
      distribution_(0.0, 1.0),
      mean_(other.mean_)
{
}

MultivariateGaussian& MultivariateGaussian::operator=(const MultivariateGaussian& other)
{
    mean_ = other.mean_;
    z_ = other.z_;
    llt_ = other.llt_;
    gen_ = other.gen_;
    return *this;
}

void MultivariateGaussian::set_mean(const Eigen::VectorXd& mu)
{
    IS_EQUAL(mu.size(), mean_.size());
    mean_ = mu;
}
void MultivariateGaussian::set_covariance(const Eigen::MatrixXd& sigma)
{
    IS_EQUAL(sigma.rows(), llt_.matrixL().rows());
    IS_EQUAL(sigma.cols(), llt_.matrixL().cols());
    initialize_cov(sigma);
}

void MultivariateGaussian::set_information(const Eigen::MatrixXd& inv_sigma)
{
    IS_EQUAL(inv_sigma.rows(), llt_.matrixL().rows());
    IS_EQUAL(inv_sigma.cols(), llt_.matrixL().cols());

    Eigen::LDLT<Eigen::MatrixXd> llti(inv_sigma);
    Eigen::MatrixXd cov = llti.solve(Eigen::MatrixXd::Identity(inv_sigma.rows(), inv_sigma.cols()));
    initialize_cov(cov);
}

Eigen::VectorXd MultivariateGaussian::sample(double max_var)
{
    Eigen::VectorXd samples(mean_.size());
    for(int i = 0; i < mean_.size(); i++)
    {
        double s;
        do
        {
            s = distribution_(gen_);
        } while(std::abs(s) > max_var);
        samples(i) = s;
    }

    return mean_ + llt_.matrixL()*samples;
}

/*! \brief Evaluate the multivariate normal PDF for the specified sample. */
double MultivariateGaussian::evaluate_probability(const Eigen::VectorXd& x) const
{
    IS_EQUAL(x.size(), mean_.size());

    Eigen::VectorXd diff = x - mean_;
    Eigen::MatrixXd exponent = -0.5 * diff.transpose() * llt_.solve(diff);
    return z_ * std::exp(exponent(0));
}

void MultivariateGaussian::initialize_cov(const Eigen::MatrixXd& cov)
{
    IS_EQUAL(mean_.size(), cov.rows());
    IS_EQUAL(mean_.size(), cov.cols());

    llt_ = Eigen::LLT<Eigen::MatrixXd>(cov);
    z_ = std::pow(2*M_PI, -static_cast<double>(mean_.size())*0.5)
         * std::pow(cov.determinant(), -0.5);
}

} // namespace math


text:
@implementation EmailableCellViewController

@synthesize demoTableView, emailAddresses;

- (void) viewDidLoad
{
    [super viewDidLoad];

    self.emailAddresses = [NSArray arrayWithObjects:
                           @"macbeth@example.com", @"ladymacbeth@example.com", @"duncan@example.com",
                           @"banquo@example.com", @"lennox@example.com", @"macduff@example.com", nil];
}

- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

- (void) didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void) viewDidUnload
{
}

- (void) dealloc
{
    [self.demoTableView release];
    [self.emailAddresses release];
    [super dealloc];
}

#pragma mark -
#pragma mark Table Data Source / Delegate Methods

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.emailAddresses.count;
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellId = @"EmailableCell";
    EmailableCell *cell = (EmailableCell *) [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil) {
        cell = [[[EmailableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId] autorelease];
    }
    [cell setIndexPath:indexPath];
    [cell setDelegate:self];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.textLabel.text = [self.emailAddresses objectAtIndex:indexPath.row];

    return cell;
}

#pragma mark -
#pragma mark EmailableCellDelegate Methods

- (void) emailableCell:(EmailableCell *)cell selectCellAtIndexPath:(NSIndexPath *)indexPath
{
    [self.demoTableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
}

- (void) emailableCell:(EmailableCell *)cell deselectCellAtIndexPath:(NSIndexPath *)indexPath
{
    [self.demoTableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (NSString *) emailableCell:(EmailableCell *)cell emailAddressForCellAtIndexPath:(NSIndexPath *)indexPath
{
    return [self.emailAddresses objectAtIndex:indexPath.row];
}

- (void) emailableCell:(EmailableCell *)cell didPressSendEmailOnCellAtIndexPath:(NSIndexPath *)indexPath
{
    MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
    if (controller == nil) {
        return;
    }
    controller.mailComposeDelegate = self;
    NSString *emailAddress = [self.emailAddresses objectAtIndex:indexPath.row];
    [controller setToRecipients:[NSArray arrayWithObject:emailAddress]];
    [self presentModalViewController:controller animated:YES];
    [controller release];
}

#pragma mark -
#pragma mark MFMailComposeViewControllerDelegate

- (void) mailComposeController:(MFMailComposeViewController *)controller
           didFinishWithResult:(MFMailComposeResult)result
                         error:(NSError *)error
{
    if (result == MFMailComposeResultSent) {
        NSLog(@"Mail sent successfully.");
    }
    else if (result == MFMailComposeResultFailed) {
        NSLog(@"Mail could not be sent: %@", [error description]);
    }
    [self dismissModalViewControllerAnimated:YES];
}

@end


text:
from typing import Optional
from games.stumped.game_object import GameObject

# <<-- Creer-Merge: imports -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
# you can add additional import(s) here
# <<-- /Creer-Merge: imports -->>

class Job(GameObject):
    """The class representing the Job in the Stumped game.

    Information about a beaver's job.
    """

    def __init__(self):
        """Initializes a Job with basic logic as provided by the Creer code generator.
        """
        GameObject.__init__(self)

        # private attributes to hold the properties so they appear read only
        self._actions = 0
        self._carry_limit = 0
        self._chopping = 0
        self._cost = 0
        self._damage = 0
        self._distraction_power = 0
        self._health = 0
        self._moves = 0
        self._munching = 0
        self._title = ""

    @property
    def actions(self) -> int:
        """int: The number of actions this Job can make per turn.
        """
        return self._actions

    @property
    def carry_limit(self) -> int:
        """int: How many combined resources a beaver with this Job can hold at once.
        """
        return self._carry_limit

    @property
    def chopping(self) -> int:
        """int: Scalar for how many branches this Job harvests at once.
        """
        return self._chopping

    @property
    def cost(self) -> int:
        """int: How much food this Job costs to recruit.
        """
        return self._cost

    @property
    def damage(self) -> int:
        """int: The amount of damage this Job does per attack.
        """
        return self._damage

    @property
    def distraction_power(self) -> int:
        """int: How many turns a beaver attacked by this Job is distracted by.
        """
        return self._distraction_power

    @property
    def health(self) -> int:
        """int: The amount of starting health this Job has.
        """
        return self._health

    @property
    def moves(self) -> int:
        """int: The number of moves this Job can make per turn.
        """
        return self._moves

    @property
    def munching(self) -> int:
        """int: Scalar for how much food this Job harvests at once.
        """
        return self._munching

    @property
    def title(self) -> str:
        """str: The Job title.
        """
        return self._title

    def recruit(self, tile: 'games.stumped.tile.Tile') -> Optional['games.stumped.beaver.Beaver']:
        """Recruits a Beaver of this Job to a lodge.

        Args:
            tile (games.stumped.tile.Tile): The Tile that is a lodge owned by you that you wish to spawn the Beaver of this Job on.

        Returns:
            games.stumped.beaver.Beaver or None: The recruited Beaver if successful, None otherwise.
        """
        return self._run_on_server('recruit', {
            'tile': tile
        })

    # <<-- Creer-Merge: functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
    # if you want to add any client side logic (such as state checking functions) this is where you can add them
    # <<-- /Creer-Merge: functions -->>


text:
#include "berryResetPerspectiveHandler.h"

#include <berryIWorkbenchWindow.h>
#include <berryHandlerUtil.h>

#include <internal/berryWorkbenchPage.h>
#include <internal/berryPerspectiveDescriptor.h>

#include <QMessageBox>

namespace berry {

Object::Pointer ResetPerspectiveHandler::Execute(const SmartPointer<const ExecutionEvent>& event)
{

  IWorkbenchWindow::Pointer activeWorkbenchWindow = HandlerUtil::GetActiveWorkbenchWindow(event);
  if (activeWorkbenchWindow.IsNotNull())
  {
    WorkbenchPage::Pointer page = activeWorkbenchWindow->GetActivePage().Cast<WorkbenchPage>();
    if (page.IsNotNull())
    {
      IPerspectiveDescriptor::Pointer descriptor = page->GetPerspective();
      if (descriptor.IsNotNull())
      {
        bool offerRevertToBase = false;
        if (PerspectiveDescriptor::Pointer desc = descriptor.Cast<PerspectiveDescriptor>())
        {
          offerRevertToBase = desc->IsPredefined() && desc->HasCustomDefinition();
        }

        if (offerRevertToBase)
        {
          QString message = QString("Do you want to reset the current %1 perspective to its saved state?").arg(
                              descriptor->GetLabel());
//          bool toggleState = false;
//          MessageDialogWithToggle dialog = MessageDialogWithToggle.open(
//                                             MessageDialog.QUESTION, activeWorkbenchWindow.getShell(),
//                                             WorkbenchMessages.RevertPerspective_title, message,
//                                             WorkbenchMessages.RevertPerspective_option,
//                                             toggleState, null, null, SWT.SHEET);
//          if (dialog.getReturnCode() == IDialogConstants.YES_ID) {
//            if (dialog.getToggleState()) {
//              PerspectiveRegistry* reg = PlatformUI::GetWorkbench()->GetPerspectiveRegistry();
//              reg->RevertPerspective(descriptor);
//            }
//            page->ResetPerspective();
//          }
          qDebug() << "****** " << message;
        }
        else
        {
          QString message = QString("Do you want to reset the current %1 perspective to its defaults?").arg(
                                    descriptor->GetLabel());
          if (QMessageBox::question(activeWorkbenchWindow->GetShell()->GetControl(), "Reset Perspective",
                                    message, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ==
              QMessageBox::Yes)
          {
            page->ResetPerspective();
          }
        }
      }
    }
  }

  return Object::Pointer();
}

}


text:
    {{ profile.FirstName }}

    <pw-item *ngFor="let item of items"
        [attr.data-position]="position"
        [item]="item">
    </pw-item>

{{ displayDate }}


text:
<?php

namespace Psdtg\SiteBundle\Entity\Circuits;

use Psdtg\SiteBundle\Entity\MMSyncableEntity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Psdtg\SiteBundle\Entity\Repositories\Circuits\ConnectivityTypesRepository")
 * @Gedmo\SoftDeleteable(fieldName="deletedAt")
 */
class ConnectivityType extends MMSyncableEntity
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", unique=true, nullable=true)
     */
    protected $name;

    /**
     * @ORM\OneToMany(targetEntity="Psdtg\SiteBundle\Entity\Circuits\BandwidthProfile", mappedBy="connectivityType")
     */
    protected $bandwidthProfiles;

    /**
     * @ORM\Column(type="boolean")
     */
    protected $noLease = false;

    /**
     * @ORM\Column(type="boolean")
     */
    protected $isService = false;

    /**
     * @ORM\Column(type="boolean")
     */
    protected $requiresNumber = false;

    /**
     * @ORM\Column(type="datetime", nullable=true)
     */
    protected $deletedAt;

    public function getId() {
        return $this->id;
    }

    public function setId($id) {
        $this->id = $id;
    }

    public function getName() {
        return $this->name;
    }

    public function setName($name) {
        $this->name = $name;
    }

    public function getBandwidthProfiles() {
        return $this->bandwidthProfiles;
    }

    public function setBandwidthProfiles($bandwidthProfiles) {
        $this->bandwidthProfiles = $bandwidthProfiles;
    }

    public function getNoLease() {
        return $this->noLease;
    }

    public function setNoLease($noLease) {
        $this->noLease = $noLease;
    }

    public function getIsService() {
        return $this->isService;
    }

    public function setIsService($isService) {
        $this->isService = $isService;
    }

    public function getRequiresNumber() {
        return $this->requiresNumber;
    }

    public function setRequiresNumber($requiresNumber) {
        $this->requiresNumber = $requiresNumber;
    }

    public function requiresNumber() {
        return $this->getRequiresNumber();
    }

    public function getDeletedAt() {
        return $this->deletedAt;
    }

    public function setDeletedAt($deletedAt) {
        $this->deletedAt = $deletedAt;
    }

    public function isActive() {
        return !isset($this->deletedAt);
    }

    public function __toString() {
        return $this->getName();
    }
}


text:
static NSString *MTPlayTimerTickNotification = @"MTPlayTimerTickNotification";
static NSString *MTPlayTimerTickTimeKey = @"MTPlayTimerTickTimeKey";

@interface MTViewController : UIViewController<MTUserJoinViewControllerDelegate>

@end


text:
package borra.duplicados.arraylist;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class Principal {

	public static void init() {

		List<Persona> list = new ArrayList<Persona>();

		// Persona(nombre, id)
		Persona p1 = new Persona("p1","123455");
		Persona p2 = new Persona("p1","123455");
		Persona p3 = new Persona("p2","1255");
		Persona p4 = new Persona("p4","123455");
		Persona p5 = new Persona("p1","123455");
		Persona p7 = new Persona("123455fasdf","123455");

		List<String> lstr = new ArrayList<String>();

		lstr.add(new String("uno"));
		lstr.add(new String("uno"));
		lstr.add(new String("uno"));
		lstr.add(new String("uno"));

		list.add(p1);
		list.add(p2);
		list.add(p3);
		list.add(p4);
		list.add(p5);

		HashSet<String> hset = new HashSet<String>(lstr);
		lstr.clear();
		lstr.addAll(hset);

		Set<Persona> linkedHashSet = new LinkedHashSet<Persona>();
		linkedHashSet.addAll(list);
		list.clear();
		list.addAll(linkedHashSet);

		Iterator<Persona> it = list.iterator();
		while(it.hasNext()){

			System.out.println((Persona)it.next());
		}

		if(list.contains(p7))
			System.out.println("Si");
		else
			System.out.println("No");

		System.out.println("\nLista sin dublicados\n");
		// Con los duplicados fuera
		for(String i : lstr){
			System.out.println(i);
		}

	}
}


text:
/*************************************************************************/
/*  control_editor_plugin.cpp                                            */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* 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.                */
/*************************************************************************/

#include "control_editor_plugin.h"

#include "editor/editor_node.h"
#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
#include "editor/editor_undo_redo_manager.h"
#include "editor/plugins/canvas_item_editor_plugin.h"
#include "scene/gui/separator.h"

// Inspector controls.

void ControlPositioningWarning::_update_warning() {
	if (!control_node) {
		title_icon->set_texture(nullptr);
		title_label->set_text("");
		hint_label->set_text("");
		return;
	}

	Node *parent_node = control_node->get_parent_control();
	if (!parent_node) {
		title_icon->set_texture(get_theme_icon(SNAME("SubViewport"), SNAME("EditorIcons")));
		title_label->set_text(TTR("This node doesn't have a control parent."));
		hint_label->set_text(TTR("Use the appropriate layout properties depending on where you are going to put it."));
	} else if (Object::cast_to<Container>(parent_node)) {
		title_icon->set_texture(get_theme_icon(SNAME("ContainerLayout"), SNAME("EditorIcons")));
		title_label->set_text(TTR("This node is a child of a container."));
		hint_label->set_text(TTR("Use container properties for positioning."));
	} else {
		title_icon->set_texture(get_theme_icon(SNAME("ControlLayout"), SNAME("EditorIcons")));
		title_label->set_text(TTR("This node is a child of a regular control."));
		hint_label->set_text(TTR("Use anchors and the rectangle for positioning."));
	}

	bg_panel->add_theme_style_override("panel", get_theme_stylebox(SNAME("bg_group_note"), SNAME("EditorProperty")));
}

void ControlPositioningWarning::_update_toggler() {
	Ref<Texture2D> arrow;
	if (hint_label->is_visible()) {
		arrow = get_theme_icon(SNAME("arrow"), SNAME("Tree"));
		set_tooltip(TTR("Collapse positioning hint."));
	} else {
		if (is_layout_rtl()) {
			arrow = get_theme_icon(SNAME("arrow_collapsed"), SNAME("Tree"));
		} else {
			arrow = get_theme_icon(SNAME("arrow_collapsed_mirrored"), SNAME("Tree"));
		}
		set_tooltip(TTR("Expand positioning hint."));
	}

	hint_icon->set_texture(arrow);
}

void ControlPositioningWarning::set_control(Control *p_node) {
	control_node = p_node;
	_update_warning();
}

void ControlPositioningWarning::gui_input(const Ref<InputEvent> &p_event) {
	Ref<InputEventMouseButton> mb = p_event;
	if (mb.is_valid() && mb->is_pressed() && mb->get_button_index() == MouseButton::LEFT) {
		bool state = !hint_label->is_visible();

		hint_filler_left->set_visible(state);
		hint_label->set_visible(state);
		hint_filler_right->set_visible(state);

		_update_toggler();
	}
}

void ControlPositioningWarning::_notification(int p_notification) {
	switch (p_notification) {
		case NOTIFICATION_ENTER_TREE:
		case NOTIFICATION_THEME_CHANGED:
			_update_warning();
			_update_toggler();
			break;
	}
}

ControlPositioningWarning::ControlPositioningWarning() {
	set_mouse_filter(MOUSE_FILTER_STOP);

	bg_panel = memnew(PanelContainer);
	bg_panel->set_mouse_filter(MOUSE_FILTER_IGNORE);
	add_child(bg_panel);

	grid = memnew(GridContainer);
	grid->set_columns(3);
	bg_panel->add_child(grid);

	title_icon = memnew(TextureRect);
	title_icon->set_stretch_mode(TextureRect::StretchMode::STRETCH_KEEP_CENTERED);
	grid->add_child(title_icon);

	title_label = memnew(Label);
	title_label->set_autowrap_mode(TextServer::AutowrapMode::AUTOWRAP_WORD);
	title_label->set_h_size_flags(Control::SIZE_EXPAND_FILL);
	title_label->set_vertical_alignment(VerticalAlignment::VERTICAL_ALIGNMENT_CENTER);
	grid->add_child(title_label);

	hint_icon = memnew(TextureRect);
	hint_icon->set_stretch_mode(TextureRect::StretchMode::STRETCH_KEEP_CENTERED);
	grid->add_child(hint_icon);

	// Filler.
	hint_filler_left = memnew(Control);
	hint_filler_left->hide();
	grid->add_child(hint_filler_left);

	hint_label = memnew(Label);
	hint_label->set_autowrap_mode(TextServer::AutowrapMode::AUTOWRAP_WORD);
	hint_label->set_h_size_flags(Control::SIZE_EXPAND_FILL);
	hint_label->set_vertical_alignment(VerticalAlignment::VERTICAL_ALIGNMENT_CENTER);
	hint_label->hide();
	grid->add_child(hint_label);

	// Filler.
	hint_filler_right = memnew(Control);
	hint_filler_right->hide();
	grid->add_child(hint_filler_right);
}

void EditorPropertyAnchorsPreset::_set_read_only(bool p_read_only) {
	options->set_disabled(p_read_only);
};

void EditorPropertyAnchorsPreset::_option_selected(int p_which) {
	int64_t val = options->get_item_metadata(p_which);
	emit_changed(get_edited_property(), val);
}

void EditorPropertyAnchorsPreset::update_property() {
	int64_t which = get_edited_object()->get(get_edited_property());

	for (int i = 0; i < options->get_item_count(); i++) {
		Variant val = options->get_item_metadata(i);
		if (val != Variant() && which == (int64_t)val) {
			options->select(i);
			return;
		}
	}
}

void EditorPropertyAnchorsPreset::setup(const Vector<String> &p_options) {
	options->clear();

	Vector<String> split_after;
	split_after.append("Custom");
	split_after.append("PresetFullRect");
	split_after.append("PresetBottomLeft");
	split_after.append("PresetCenter");

	for (int i = 0, j = 0; i < p_options.size(); i++, j++) {
		Vector<String> text_split = p_options[i].split(":");
		int64_t current_val = text_split[1].to_int();

		String option_name = text_split[0];
		if (option_name.begins_with("Preset")) {
			String preset_name = option_name.trim_prefix("Preset");
			String humanized_name = preset_name.capitalize();
			String icon_name = "ControlAlign" + preset_name;
			options->add_icon_item(EditorNode::get_singleton()->get_gui_base()->get_theme_icon(icon_name, "EditorIcons"), humanized_name);
		} else {
			options->add_item(option_name);
		}

		options->set_item_metadata(j, current_val);
		if (split_after.has(option_name)) {
			options->add_separator();
			j++;
		}
	}
}

EditorPropertyAnchorsPreset::EditorPropertyAnchorsPreset() {
	options = memnew(OptionButton);
	options->set_clip_text(true);
	options->set_flat(true);
	add_child(options);
	add_focusable(options);
	options->connect("item_selected", callable_mp(this, &EditorPropertyAnchorsPreset::_option_selected));
}

void EditorPropertySizeFlags::_set_read_only(bool p_read_only) {
	for (CheckBox *check : flag_checks) {
		check->set_disabled(p_read_only);
	}
	flag_presets->set_disabled(p_read_only);
};

void EditorPropertySizeFlags::_preset_selected(int p_which) {
	int preset = flag_presets->get_item_id(p_which);
	if (preset == SIZE_FLAGS_PRESET_CUSTOM) {
		flag_options->set_visible(true);
		return;
	}
	flag_options->set_visible(false);

	uint32_t value = 0;
	switch (preset) {
		case SIZE_FLAGS_PRESET_FILL:
			value = Control::SIZE_FILL;
			break;
		case SIZE_FLAGS_PRESET_SHRINK_BEGIN:
			value = Control::SIZE_SHRINK_BEGIN;
			break;
		case SIZE_FLAGS_PRESET_SHRINK_CENTER:
			value = Control::SIZE_SHRINK_CENTER;
			break;
		case SIZE_FLAGS_PRESET_SHRINK_END:
			value = Control::SIZE_SHRINK_END;
			break;
	}

	bool is_expand = flag_expand->is_visible() && flag_expand->is_pressed();
	if (is_expand) {
		value |= Control::SIZE_EXPAND;
	}

	emit_changed(get_edited_property(), value);
}

void EditorPropertySizeFlags::_expand_toggled() {
	uint32_t value = get_edited_object()->get(get_edited_property());

	if (flag_expand->is_visible() && flag_expand->is_pressed()) {
		value |= Control::SIZE_EXPAND;
	} else {
		value ^= Control::SIZE_EXPAND;
	}

	// Keep the custom preset selected as we toggle individual flags.
	keep_selected_preset = true;
	emit_changed(get_edited_property(), value);
}

void EditorPropertySizeFlags::_flag_toggled() {
	uint32_t value = 0;
	for (int i = 0; i < flag_checks.size(); i++) {
		if (flag_checks[i]->is_pressed()) {
			int flag_value = flag_checks[i]->get_meta("_value");
			value |= flag_value;
		}
	}

	bool is_expand = flag_expand->is_visible() && flag_expand->is_pressed();
	if (is_expand) {
		value |= Control::SIZE_EXPAND;
	}

	// Keep the custom preset selected as we toggle individual flags.
	keep_selected_preset = true;
	emit_changed(get_edited_property(), value);
}

void EditorPropertySizeFlags::update_property() {
	uint32_t value = get_edited_object()->get(get_edited_property());

	for (int i = 0; i < flag_checks.size(); i++) {
		int flag_value = flag_checks[i]->get_meta("_value");
		if (value & flag_value) {
			flag_checks[i]->set_pressed(true);
		} else {
			flag_checks[i]->set_pressed(false);
		}
	}

	bool is_expand = value & Control::SIZE_EXPAND;
	flag_expand->set_pressed(is_expand);

	if (keep_selected_preset) {
		keep_selected_preset = false;
		return;
	}

	FlagPreset preset = SIZE_FLAGS_PRESET_CUSTOM;
	if (value == Control::SIZE_FILL || value == (Control::SIZE_FILL | Control::SIZE_EXPAND)) {
		preset = SIZE_FLAGS_PRESET_FILL;
	} else if (value == Control::SIZE_SHRINK_BEGIN || value == (Control::SIZE_SHRINK_BEGIN | Control::SIZE_EXPAND)) {
		preset = SIZE_FLAGS_PRESET_SHRINK_BEGIN;
	} else if (value == Control::SIZE_SHRINK_CENTER || value == (Control::SIZE_SHRINK_CENTER | Control::SIZE_EXPAND)) {
		preset = SIZE_FLAGS_PRESET_SHRINK_CENTER;
	} else if (value == Control::SIZE_SHRINK_END || value == (Control::SIZE_SHRINK_END | Control::SIZE_EXPAND)) {
		preset = SIZE_FLAGS_PRESET_SHRINK_END;
	}

	int preset_idx = flag_presets->get_item_index(preset);
	if (preset_idx >= 0) {
		flag_presets->select(preset_idx);
	}
	flag_options->set_visible(preset == SIZE_FLAGS_PRESET_CUSTOM);
}

void EditorPropertySizeFlags::setup(const Vector<String> &p_options, bool p_vertical) {
	vertical = p_vertical;

	if (p_options.size() == 0) {
		flag_presets->clear();
		flag_presets->add_item(TTR("Container Default"));
		flag_presets->set_disabled(true);
		flag_expand->set_visible(false);
		return;
	}

	HashMap<int, String> flags;
	for (int i = 0, j = 0; i < p_options.size(); i++, j++) {
		Vector<String> text_split = p_options[i].split(":");
		int64_t current_val = text_split[1].to_int();
		flags[current_val] = text_split[0];

		if (current_val == SIZE_EXPAND) {
			continue;
		}

		CheckBox *cb = memnew(CheckBox);
		cb->set_text(text_split[0]);
		cb->set_clip_text(true);
		cb->set_meta("_value", current_val);
		cb->connect("pressed", callable_mp(this, &EditorPropertySizeFlags::_flag_toggled));
		add_focusable(cb);

		flag_options->add_child(cb);
		flag_checks.append(cb);
	}

	Control *gui_base = EditorNode::get_singleton()->get_gui_base();
	String wide_preset_icon = SNAME("ControlAlignHCenterWide");
	String begin_preset_icon = SNAME("ControlAlignCenterLeft");
	String end_preset_icon = SNAME("ControlAlignCenterRight");
	if (vertical) {
		wide_preset_icon = SNAME("ControlAlignVCenterWide");
		begin_preset_icon = SNAME("ControlAlignCenterTop");
		end_preset_icon = SNAME("ControlAlignCenterBottom");
	}

	flag_presets->clear();
	if (flags.has(SIZE_FILL)) {
		flag_presets->add_icon_item(gui_base->get_theme_icon(wide_preset_icon, SNAME("EditorIcons")), TTR("Fill"), SIZE_FLAGS_PRESET_FILL);
	}
	// Shrink Begin is the same as no flags at all, as such it cannot be disabled.
	flag_presets->add_icon_item(gui_base->get_theme_icon(begin_preset_icon, SNAME("EditorIcons")), TTR("Shrink Begin"), SIZE_FLAGS_PRESET_SHRINK_BEGIN);
	if (flags.has(SIZE_SHRINK_CENTER)) {
		flag_presets->add_icon_item(gui_base->get_theme_icon(SNAME("ControlAlignCenter"), SNAME("EditorIcons")), TTR("Shrink Center"), SIZE_FLAGS_PRESET_SHRINK_CENTER);
	}
	if (flags.has(SIZE_SHRINK_END)) {
		flag_presets->add_icon_item(gui_base->get_theme_icon(end_preset_icon, SNAME("EditorIcons")), TTR("Shrink End"), SIZE_FLAGS_PRESET_SHRINK_END);
	}
	flag_presets->add_separator();
	flag_presets->add_item(TTR("Custom"), SIZE_FLAGS_PRESET_CUSTOM);

	flag_expand->set_visible(flags.has(SIZE_EXPAND));
}

EditorPropertySizeFlags::EditorPropertySizeFlags() {
	VBoxContainer *vb = memnew(VBoxContainer);
	add_child(vb);

	flag_presets = memnew(OptionButton);
	flag_presets->set_clip_text(true);
	flag_presets->set_flat(true);
	vb->add_child(flag_presets);
	add_focusable(flag_presets);
	set_label_reference(flag_presets);
	flag_presets->connect("item_selected", callable_mp(this, &EditorPropertySizeFlags::_preset_selected));

	flag_options = memnew(VBoxContainer);
	flag_options->hide();
	vb->add_child(flag_options);

	flag_expand = memnew(CheckBox);
	flag_expand->set_text(TTR("Expand"));
	vb->add_child(flag_expand);
	add_focusable(flag_expand);
	flag_expand->connect("pressed", callable_mp(this, &EditorPropertySizeFlags::_expand_toggled));
}

bool EditorInspectorPluginControl::can_handle(Object *p_object) {
	return Object::cast_to<Control>(p_object) != nullptr;
}

void EditorInspectorPluginControl::parse_group(Object *p_object, const String &p_group) {
	Control *control = Object::cast_to<Control>(p_object);
	if (!control || p_group != "Layout") {
		return;
	}

	ControlPositioningWarning *pos_warning = memnew(ControlPositioningWarning);
	pos_warning->set_control(control);
	add_custom_control(pos_warning);
}

bool EditorInspectorPluginControl::parse_property(Object *p_object, const Variant::Type p_type, const String &p_path, const PropertyHint p_hint, const String &p_hint_text, const uint32_t p_usage, const bool p_wide) {
	Control *control = Object::cast_to<Control>(p_object);
	if (!control) {
		return false;
	}

	if (p_path == "anchors_preset") {
		EditorPropertyAnchorsPreset *prop_editor = memnew(EditorPropertyAnchorsPreset);
		Vector<String> options = p_hint_text.split(",");
		prop_editor->setup(options);
		add_property_editor(p_path, prop_editor);

		return true;
	}

	if (p_path == "size_flags_horizontal" || p_path == "size_flags_vertical") {
		EditorPropertySizeFlags *prop_editor = memnew(EditorPropertySizeFlags);
		Vector<String> options;
		if (!p_hint_text.is_empty()) {
			options = p_hint_text.split(",");
		}
		prop_editor->setup(options, p_path == "size_flags_vertical");
		add_property_editor(p_path, prop_editor);

		return true;
	}

	return false;
}

// Toolbars controls.

Size2 ControlEditorPopupButton::get_minimum_size() const {
	Vector2 base_size = Vector2(26, 26) * EDSCALE;

	if (arrow_icon.is_null()) {
		return base_size;
	}

	Vector2 final_size;
	final_size.x = base_size.x + arrow_icon->get_width();
	final_size.y = MAX(base_size.y, arrow_icon->get_height());

	return final_size;
}

void ControlEditorPopupButton::toggled(bool p_pressed) {
	if (!p_pressed) {
		return;
	}

	Size2 size = get_size() * get_viewport()->get_canvas_transform().get_scale();

	popup_panel->set_size(Size2(size.width, 0));
	Point2 gp = get_screen_position();
	gp.y += size.y;
	if (is_layout_rtl()) {
		gp.x += size.width - popup_panel->get_size().width;
	}
	popup_panel->set_position(gp);

	popup_panel->popup();
}

void ControlEditorPopupButton::_popup_visibility_changed(bool p_visible) {
	set_pressed(p_visible);
}

void ControlEditorPopupButton::_notification(int p_what) {
	switch (p_what) {
		case NOTIFICATION_ENTER_TREE:
		case NOTIFICATION_THEME_CHANGED: {
			arrow_icon = get_theme_icon("select_arrow", "Tree");
		} break;

		case NOTIFICATION_DRAW: {
			if (arrow_icon.is_valid()) {
				Vector2 arrow_pos = Point2(26, 0) * EDSCALE;
				arrow_pos.y = get_size().y / 2 - arrow_icon->get_height() / 2;
				draw_texture(arrow_icon, arrow_pos);
			}
		} break;

		case NOTIFICATION_LAYOUT_DIRECTION_CHANGED: {
			popup_panel->set_layout_direction((Window::LayoutDirection)get_layout_direction());
		} break;

		case NOTIFICATION_VISIBILITY_CHANGED: {
			if (!is_visible_in_tree()) {
				popup_panel->hide();
			}
		} break;
	}
}

ControlEditorPopupButton::ControlEditorPopupButton() {
	set_flat(true);
	set_toggle_mode(true);
	set_focus_mode(FOCUS_NONE);

	popup_panel = memnew(PopupPanel);
	popup_panel->set_theme_type_variation("ControlEditorPopupButton");
	add_child(popup_panel);
	popup_panel->connect("about_to_popup", callable_mp(this, &ControlEditorPopupButton::_popup_visibility_changed).bind(true));
	popup_panel->connect("popup_hide", callable_mp(this, &ControlEditorPopupButton::_popup_visibility_changed).bind(false));

	popup_vbox = memnew(VBoxContainer);
	popup_panel->add_child(popup_vbox);
}

void ControlEditorPresetPicker::_add_row_button(HBoxContainer *p_row, const int p_preset, const String &p_name) {
	ERR_FAIL_COND(preset_buttons.has(p_preset));

	Button *b = memnew(Button);
	b->set_custom_minimum_size(Size2i(36, 36) * EDSCALE);
	b->set_icon_alignment(HORIZONTAL_ALIGNMENT_CENTER);
	b->set_tooltip(p_name);
	b->set_flat(true);
	p_row->add_child(b);
	b->connect("pressed", callable_mp(this, &ControlEditorPresetPicker::_preset_button_pressed).bind(p_preset));

	preset_buttons[p_preset] = b;
}

void ControlEditorPresetPicker::_add_separator(BoxContainer *p_box, Separator *p_separator) {
	p_separator->add_theme_constant_override("separation", grid_separation);
	p_separator->set_custom_minimum_size(Size2i(1, 1));
	p_box->add_child(p_separator);
}

void AnchorPresetPicker::_preset_button_pressed(const int p_preset) {
	emit_signal("anchors_preset_selected", p_preset);
}

void AnchorPresetPicker::_notification(int p_notification) {
	switch (p_notification) {
		case NOTIFICATION_ENTER_TREE:
		case NOTIFICATION_THEME_CHANGED: {
			preset_buttons[PRESET_TOP_LEFT]->set_icon(get_theme_icon(SNAME("ControlAlignTopLeft"), SNAME("EditorIcons")));
			preset_buttons[PRESET_CENTER_TOP]->set_icon(get_theme_icon(SNAME("ControlAlignCenterTop"), SNAME("EditorIcons")));
			preset_buttons[PRESET_TOP_RIGHT]->set_icon(get_theme_icon(SNAME("ControlAlignTopRight"), SNAME("EditorIcons")));

			preset_buttons[PRESET_CENTER_LEFT]->set_icon(get_theme_icon(SNAME("ControlAlignCenterLeft"), SNAME("EditorIcons")));
			preset_buttons[PRESET_CENTER]->set_icon(get_theme_icon(SNAME("ControlAlignCenter"), SNAME("EditorIcons")));
			preset_buttons[PRESET_CENTER_RIGHT]->set_icon(get_theme_icon(SNAME("ControlAlignCenterRight"), SNAME("EditorIcons")));

			preset_buttons[PRESET_BOTTOM_LEFT]->set_icon(get_theme_icon(SNAME("ControlAlignBottomLeft"), SNAME("EditorIcons")));
			preset_buttons[PRESET_CENTER_BOTTOM]->set_icon(get_theme_icon(SNAME("ControlAlignCenterBottom"), SNAME("EditorIcons")));
			preset_buttons[PRESET_BOTTOM_RIGHT]->set_icon(get_theme_icon(SNAME("ControlAlignBottomRight"), SNAME("EditorIcons")));

			preset_buttons[PRESET_TOP_WIDE]->set_icon(get_theme_icon(SNAME("ControlAlignTopWide"), SNAME("EditorIcons")));
			preset_buttons[PRESET_HCENTER_WIDE]->set_icon(get_theme_icon(SNAME("ControlAlignHCenterWide"), SNAME("EditorIcons")));
			preset_buttons[PRESET_BOTTOM_WIDE]->set_icon(get_theme_icon(SNAME("ControlAlignBottomWide"), SNAME("EditorIcons")));

			preset_buttons[PRESET_LEFT_WIDE]->set_icon(get_theme_icon(SNAME("ControlAlignLeftWide"), SNAME("EditorIcons")));
			preset_buttons[PRESET_VCENTER_WIDE]->set_icon(get_theme_icon(SNAME("ControlAlignVCenterWide"), SNAME("EditorIcons")));
			preset_buttons[PRESET_RIGHT_WIDE]->set_icon(get_theme_icon(SNAME("ControlAlignRightWide"), SNAME("EditorIcons")));

			preset_buttons[PRESET_FULL_RECT]->set_icon(get_theme_icon(SNAME("ControlAlignFullRect"), SNAME("EditorIcons")));
		} break;
	}
}

void AnchorPresetPicker::_bind_methods() {
	ADD_SIGNAL(MethodInfo("anchors_preset_selected", PropertyInfo(Variant::INT, "preset")));
}

AnchorPresetPicker::AnchorPresetPicker() {
	VBoxContainer *main_vb = memnew(VBoxContainer);
	main_vb->add_theme_constant_override("separation", grid_separation);
	add_child(main_vb);

	HBoxContainer *top_row = memnew(HBoxContainer);
	top_row->set_alignment(BoxContainer::ALIGNMENT_CENTER);
	top_row->add_theme_constant_override("separation", grid_separation);
	main_vb->add_child(top_row);

	_add_row_button(top_row, PRESET_TOP_LEFT, TTR("Top Left"));
	_add_row_button(top_row, PRESET_CENTER_TOP, TTR("Center Top"));
	_add_row_button(top_row, PRESET_TOP_RIGHT, TTR("Top Right"));
	_add_separator(top_row, memnew(VSeparator));
	_add_row_button(top_row, PRESET_TOP_WIDE, TTR("Top Wide"));

	HBoxContainer *mid_row = memnew(HBoxContainer);
	mid_row->set_alignment(BoxContainer::ALIGNMENT_CENTER);
	mid_row->add_theme_constant_override("separation", grid_separation);
	main_vb->add_child(mid_row);

	_add_row_button(mid_row, PRESET_CENTER_LEFT, TTR("Center Left"));
	_add_row_button(mid_row, PRESET_CENTER, TTR("Center"));
	_add_row_button(mid_row, PRESET_CENTER_RIGHT, TTR("Center Right"));
	_add_separator(mid_row, memnew(VSeparator));
	_add_row_button(mid_row, PRESET_HCENTER_WIDE, TTR("HCenter Wide"));

	HBoxContainer *bot_row = memnew(HBoxContainer);
	bot_row->set_alignment(BoxContainer::ALIGNMENT_CENTER);
	bot_row->add_theme_constant_override("separation", grid_separation);
	main_vb->add_child(bot_row);

	_add_row_button(bot_row, PRESET_BOTTOM_LEFT, TTR("Bottom Left"));
	_add_row_button(bot_row, PRESET_CENTER_BOTTOM, TTR("Center Bottom"));
	_add_row_button(bot_row, PRESET_BOTTOM_RIGHT, TTR("Bottom Right"));
	_add_separator(bot_row, memnew(VSeparator));
	_add_row_button(bot_row, PRESET_BOTTOM_WIDE, TTR("Bottom Wide"));

	_add_separator(main_vb, memnew(HSeparator));

	HBoxContainer *extra_row = memnew(HBoxContainer);
	extra_row->set_alignment(BoxContainer::ALIGNMENT_CENTER);
	extra_row->add_theme_constant_override("separation", grid_separation);
	main_vb->add_child(extra_row);

	_add_row_button(extra_row, PRESET_LEFT_WIDE, TTR("Left Wide"));
	_add_row_button(extra_row, PRESET_VCENTER_WIDE, TTR("VCenter Wide"));
	_add_row_button(extra_row, PRESET_RIGHT_WIDE, TTR("Right Wide"));
	_add_separator(extra_row, memnew(VSeparator));
	_add_row_button(extra_row, PRESET_FULL_RECT, TTR("Full Rect"));
}

void SizeFlagPresetPicker::_preset_button_pressed(const int p_preset) {
	int flags = (SizeFlags)p_preset;
	if (expand_button->is_pressed()) {
		flags |= SIZE_EXPAND;
	}

	emit_signal("size_flags_selected", flags);
}

void SizeFlagPresetPicker::set_allowed_flags(Vector<SizeFlags> &p_flags) {
	preset_buttons[SIZE_SHRINK_BEGIN]->set_disabled(!p_flags.has(SIZE_SHRINK_BEGIN));
	preset_buttons[SIZE_SHRINK_CENTER]->set_disabled(!p_flags.has(SIZE_SHRINK_CENTER));
	preset_buttons[SIZE_SHRINK_END]->set_disabled(!p_flags.has(SIZE_SHRINK_END));
	preset_buttons[SIZE_FILL]->set_disabled(!p_flags.has(SIZE_FILL));

	expand_button->set_disabled(!p_flags.has(SIZE_EXPAND));
	if (p_flags.has(SIZE_EXPAND)) {
		expand_button->set_tooltip(TTR("Enable to also set the Expand flag.\nDisable to only set Shrink/Fill flags."));
	} else {
		expand_button->set_pressed(false);
		expand_button->set_tooltip(TTR("Some parents of the selected nodes do not support the Expand flag."));
	}
}

void SizeFlagPresetPicker::_notification(int p_notification) {
	switch (p_notification) {
		case NOTIFICATION_ENTER_TREE:
		case NOTIFICATION_THEME_CHANGED: {
			if (vertical) {
				preset_buttons[SIZE_SHRINK_BEGIN]->set_icon(get_theme_icon(SNAME("ControlAlignCenterTop"), SNAME("EditorIcons")));
				preset_buttons[SIZE_SHRINK_CENTER]->set_icon(get_theme_icon(SNAME("ControlAlignCenter"), SNAME("EditorIcons")));
				preset_buttons[SIZE_SHRINK_END]->set_icon(get_theme_icon(SNAME("ControlAlignCenterBottom"), SNAME("EditorIcons")));

				preset_buttons[SIZE_FILL]->set_icon(get_theme_icon(SNAME("ControlAlignVCenterWide"), SNAME("EditorIcons")));
			} else {
				preset_buttons[SIZE_SHRINK_BEGIN]->set_icon(get_theme_icon(SNAME("ControlAlignCenterLeft"), SNAME("EditorIcons")));
				preset_buttons[SIZE_SHRINK_CENTER]->set_icon(get_theme_icon(SNAME("ControlAlignCenter"), SNAME("EditorIcons")));
				preset_buttons[SIZE_SHRINK_END]->set_icon(get_theme_icon(SNAME("ControlAlignCenterRight"), SNAME("EditorIcons")));

				preset_buttons[SIZE_FILL]->set_icon(get_theme_icon(SNAME("ControlAlignHCenterWide"), SNAME("EditorIcons")));
			}
		} break;
	}
}

void SizeFlagPresetPicker::_bind_methods() {
	ADD_SIGNAL(MethodInfo("size_flags_selected", PropertyInfo(Variant::INT, "size_flags")));
}

SizeFlagPresetPicker::SizeFlagPresetPicker(bool p_vertical) {
	vertical = p_vertical;

	VBoxContainer *main_vb = memnew(VBoxContainer);
	add_child(main_vb);

	HBoxContainer *main_row = memnew(HBoxContainer);
	main_row->set_alignment(BoxContainer::ALIGNMENT_CENTER);
	main_row->add_theme_constant_override("separation", grid_separation);
	main_vb->add_child(main_row);

	_add_row_button(main_row, SIZE_SHRINK_BEGIN, TTR("Shrink Begin"));
	_add_row_button(main_row, SIZE_SHRINK_CENTER, TTR("Shrink Center"));
	_add_row_button(main_row, SIZE_SHRINK_END, TTR("Shrink End"));
	_add_separator(main_row, memnew(VSeparator));
	_add_row_button(main_row, SIZE_FILL, TTR("Fill"));

	expand_button = memnew(CheckBox);
	expand_button->set_flat(true);
	expand_button->set_text(TTR("Align with Expand"));
	expand_button->set_tooltip(TTR("Enable to also set the Expand flag.\nDisable to only set Shrink/Fill flags."));
	main_vb->add_child(expand_button);
}

// Toolbar.

void ControlEditorToolbar::_anchors_preset_selected(int p_preset) {
	LayoutPreset preset = (LayoutPreset)p_preset;
	List<Node *> selection = editor_selection->get_selected_node_list();

	undo_redo->create_action(TTR("Change Anchors, Offsets, Grow Direction"));

	for (Node *E : selection) {
		Control *control = Object::cast_to<Control>(E);
		if (control) {
			undo_redo->add_do_property(control, "anchors_preset", preset);
			undo_redo->add_undo_method(control, "_edit_set_state", control->_edit_get_state());
		}
	}

	undo_redo->commit_action();

	anchors_mode = false;
	anchor_mode_button->set_pressed(anchors_mode);
}

void ControlEditorToolbar::_anchors_to_current_ratio() {
	List<Node *> selection = editor_selection->get_selected_node_list();

	undo_redo->create_action(TTR("Change Anchors, Offsets (Keep Ratio)"));

	for (Node *E : selection) {
		Control *control = Object::cast_to<Control>(E);
		if (control) {
			Point2 top_left_anchor = _position_to_anchor(control, Point2());
			Point2 bottom_right_anchor = _position_to_anchor(control, control->get_size());
			undo_redo->add_do_method(control, "set_anchor", SIDE_LEFT, top_left_anchor.x, false, true);
			undo_redo->add_do_method(control, "set_anchor", SIDE_RIGHT, bottom_right_anchor.x, false, true);
			undo_redo->add_do_method(control, "set_anchor", SIDE_TOP, top_left_anchor.y, false, true);
			undo_redo->add_do_method(control, "set_anchor", SIDE_BOTTOM, bottom_right_anchor.y, false, true);
			undo_redo->add_do_method(control, "set_meta", "_edit_use_anchors_", true);

			const bool use_anchors = control->get_meta("_edit_use_anchors_", false);
			undo_redo->add_undo_method(control, "_edit_set_state", control->_edit_get_state());
			if (use_anchors) {
				undo_redo->add_undo_method(control, "set_meta", "_edit_use_anchors_", true);
			} else {
				undo_redo->add_undo_method(control, "remove_meta", "_edit_use_anchors_");
			}

			anchors_mode = true;
			anchor_mode_button->set_pressed(anchors_mode);
		}
	}

	undo_redo->commit_action();
}

void ControlEditorToolbar::_anchor_mode_toggled(bool p_status) {
	List<Control *> selection = _get_edited_controls();
	for (Control *E : selection) {
		if (Object::cast_to<Container>(E->get_parent())) {
			continue;
		}

		if (p_status) {
			E->set_meta("_edit_use_anchors_", true);
		} else {
			E->remove_meta("_edit_use_anchors_");
		}
	}

	anchors_mode = p_status;
	CanvasItemEditor::get_singleton()->update_viewport();
}

void ControlEditorToolbar::_container_flags_selected(int p_flags, bool p_vertical) {
	List<Node *> selection = editor_selection->get_selected_node_list();

	if (p_vertical) {
		undo_redo->create_action(TTR("Change Vertical Size Flags"));
	} else {
		undo_redo->create_action(TTR("Change Horizontal Size Flags"));
	}

	for (Node *E : selection) {
		Control *control = Object::cast_to<Control>(E);
		if (control) {
			if (p_vertical) {
				undo_redo->add_do_method(control, "set_v_size_flags", p_flags);
			} else {
				undo_redo->add_do_method(control, "set_h_size_flags", p_flags);
			}
			undo_redo->add_undo_method(control, "_edit_set_state", control->_edit_get_state());
		}
	}

	undo_redo->commit_action();
}

Vector2 ControlEditorToolbar::_anchor_to_position(const Control *p_control, Vector2 anchor) {
	ERR_FAIL_COND_V(!p_control, Vector2());

	Transform2D parent_transform = p_control->get_transform().affine_inverse();
	Rect2 parent_rect = p_control->get_parent_anchorable_rect();

	if (p_control->is_layout_rtl()) {
		return parent_transform.xform(parent_rect.position + Vector2(parent_rect.size.x - parent_rect.size.x * anchor.x, parent_rect.size.y * anchor.y));
	} else {
		return parent_transform.xform(parent_rect.position + Vector2(parent_rect.size.x * anchor.x, parent_rect.size.y * anchor.y));
	}
}

Vector2 ControlEditorToolbar::_position_to_anchor(const Control *p_control, Vector2 position) {
	ERR_FAIL_COND_V(!p_control, Vector2());

	Rect2 parent_rect = p_control->get_parent_anchorable_rect();

	Vector2 output = Vector2();
	if (p_control->is_layout_rtl()) {
		output.x = (parent_rect.size.x == 0) ? 0.0 : (parent_rect.size.x - p_control->get_transform().xform(position).x - parent_rect.position.x) / parent_rect.size.x;
	} else {
		output.x = (parent_rect.size.x == 0) ? 0.0 : (p_control->get_transform().xform(position).x - parent_rect.position.x) / parent_rect.size.x;
	}
	output.y = (parent_rect.size.y == 0) ? 0.0 : (p_control->get_transform().xform(position).y - parent_rect.position.y) / parent_rect.size.y;
	return output;
}

bool ControlEditorToolbar::_is_node_locked(const Node *p_node) {
	return p_node->get_meta("_edit_lock_", false);
}

List<Control *> ControlEditorToolbar::_get_edited_controls() {
	List<Control *> selection;
	for (const KeyValue<Node *, Object *> &E : editor_selection->get_selection()) {
		Control *control = Object::cast_to<Control>(E.key);
		if (control && control->is_visible_in_tree() && control->get_viewport() == EditorNode::get_singleton()->get_scene_root() && !_is_node_locked(control)) {
			selection.push_back(control);
		}
	}

	return selection;
}

void ControlEditorToolbar::_selection_changed() {
	// Update toolbar visibility.
	bool has_controls = false;
	bool has_control_parents = false;
	bool has_container_parents = false;

	// Also update which size flags can be configured for the selected nodes.
	Vector<SizeFlags> allowed_h_flags = {
		SIZE_SHRINK_BEGIN,
		SIZE_SHRINK_CENTER,
		SIZE_SHRINK_END,
		SIZE_FILL,
		SIZE_EXPAND,
	};
	Vector<SizeFlags> allowed_v_flags = {
		SIZE_SHRINK_BEGIN,
		SIZE_SHRINK_CENTER,
		SIZE_SHRINK_END,
		SIZE_FILL,
		SIZE_EXPAND,
	};

	for (const KeyValue<Node *, Object *> &E : editor_selection->get_selection()) {
		Control *control = Object::cast_to<Control>(E.key);
		if (!control) {
			continue;
		}
		has_controls = true;

		if (Object::cast_to<Control>(control->get_parent())) {
			has_control_parents = true;
		}
		if (Object::cast_to<Container>(control->get_parent())) {
			has_container_parents = true;

			Container *parent_container = Object::cast_to<Container>(control->get_parent());

			Vector<int> container_h_flags = parent_container->get_allowed_size_flags_horizontal();
			Vector<SizeFlags> tmp_flags = allowed_h_flags.duplicate();
			for (int i = 0; i < allowed_h_flags.size(); i++) {
				if (!container_h_flags.has((int)allowed_h_flags[i])) {
					tmp_flags.erase(allowed_h_flags[i]);
				}
			}
			allowed_h_flags = tmp_flags;

			Vector<int> container_v_flags = parent_container->get_allowed_size_flags_vertical();
			tmp_flags = allowed_v_flags.duplicate();
			for (int i = 0; i < allowed_v_flags.size(); i++) {
				if (!container_v_flags.has((int)allowed_v_flags[i])) {
					tmp_flags.erase(allowed_v_flags[i]);
				}
			}
			allowed_v_flags = tmp_flags;
		}
	}

	// Set general toolbar visibility.
	set_visible(has_controls);

	// Set anchor tools visibility.
	if (has_controls && (!has_control_parents || !has_container_parents)) {
		anchors_button->set_visible(true);
		anchor_mode_button->set_visible(true);

		// Update anchor mode.
		int nb_valid_controls = 0;
		int nb_anchors_mode = 0;

		List<Node *> selection = editor_selection->get_selected_node_list();
		for (Node *E : selection) {
			Control *control = Object::cast_to<Control>(E);
			if (!control) {
				continue;
			}
			if (Object::cast_to<Container>(control->get_parent())) {
				continue;
			}

			nb_valid_controls++;
			if (control->get_meta("_edit_use_anchors_", false)) {
				nb_anchors_mode++;
			}
		}

		anchors_mode = (nb_valid_controls == nb_anchors_mode);
		anchor_mode_button->set_pressed(anchors_mode);
	} else {
		anchors_button->set_visible(false);
		anchor_mode_button->set_visible(false);
		anchor_mode_button->set_pressed(false);
	}

	// Set container tools visibility.
	if (has_controls && (!has_control_parents || has_container_parents)) {
		containers_button->set_visible(true);

		// Update allowed size flags.
		if (has_container_parents) {
			container_h_picker->set_allowed_flags(allowed_h_flags);
			container_v_picker->set_allowed_flags(allowed_v_flags);
		} else {
			Vector<SizeFlags> allowed_all_flags = {
				SIZE_SHRINK_BEGIN,
				SIZE_SHRINK_CENTER,
				SIZE_SHRINK_END,
				SIZE_FILL,
				SIZE_EXPAND,
			};

			container_h_picker->set_allowed_flags(allowed_all_flags);
			container_v_picker->set_allowed_flags(allowed_all_flags);
		}
	} else {
		containers_button->set_visible(false);
	}
}

void ControlEditorToolbar::_notification(int p_what) {
	switch (p_what) {
		case NOTIFICATION_ENTER_TREE:
		case NOTIFICATION_THEME_CHANGED: {
			anchors_button->set_icon(get_theme_icon(SNAME("ControlLayout"), SNAME("EditorIcons")));
			anchor_mode_button->set_icon(get_theme_icon(SNAME("Anchor"), SNAME("EditorIcons")));
			containers_button->set_icon(get_theme_icon(SNAME("ContainerLayout"), SNAME("EditorIcons")));
		} break;
	}
}

ControlEditorToolbar::ControlEditorToolbar() {
	add_child(memnew(VSeparator));

	// Anchor and offset tools.
	anchors_button = memnew(ControlEditorPopupButton);
	anchors_button->set_tooltip(TTR("Presets for the anchor and offset values of a Control node."));
	add_child(anchors_button);

	Label *anchors_label = memnew(Label);
	anchors_label->set_text(TTR("Anchor preset"));
	anchors_button->get_popup_hbox()->add_child(anchors_label);
	AnchorPresetPicker *anchors_picker = memnew(AnchorPresetPicker);
	anchors_picker->set_h_size_flags(SIZE_SHRINK_CENTER);
	anchors_button->get_popup_hbox()->add_child(anchors_picker);
	anchors_picker->connect("anchors_preset_selected", callable_mp(this, &ControlEditorToolbar::_anchors_preset_selected));

	anchors_button->get_popup_hbox()->add_child(memnew(HSeparator));

	Button *keep_ratio_button = memnew(Button);
	keep_ratio_button->set_text_alignment(HORIZONTAL_ALIGNMENT_LEFT);
	keep_ratio_button->set_text(TTR("Set to Current Ratio"));
	keep_ratio_button->set_tooltip(TTR("Adjust anchors and offsets to match the current rect size."));
	anchors_button->get_popup_hbox()->add_child(keep_ratio_button);
	keep_ratio_button->connect("pressed", callable_mp(this, &ControlEditorToolbar::_anchors_to_current_ratio));

	anchor_mode_button = memnew(Button);
	anchor_mode_button->set_flat(true);
	anchor_mode_button->set_toggle_mode(true);
	anchor_mode_button->set_tooltip(TTR("When active, moving Control nodes changes their anchors instead of their offsets."));
	add_child(anchor_mode_button);
	anchor_mode_button->connect("toggled", callable_mp(this, &ControlEditorToolbar::_anchor_mode_toggled));

	// Container tools.
	containers_button = memnew(ControlEditorPopupButton);
	containers_button->set_tooltip(TTR("Sizing settings for children of a Container node."));
	add_child(containers_button);

	Label *container_h_label = memnew(Label);
	container_h_label->set_text(TTR("Horizontal alignment"));
	containers_button->get_popup_hbox()->add_child(container_h_label);
	container_h_picker = memnew(SizeFlagPresetPicker(false));
	containers_button->get_popup_hbox()->add_child(container_h_picker);
	container_h_picker->connect("size_flags_selected", callable_mp(this, &ControlEditorToolbar::_container_flags_selected).bind(false));

	containers_button->get_popup_hbox()->add_child(memnew(HSeparator));

	Label *container_v_label = memnew(Label);
	container_v_label->set_text(TTR("Vertical alignment"));
	containers_button->get_popup_hbox()->add_child(container_v_label);
	container_v_picker = memnew(SizeFlagPresetPicker(true));
	containers_button->get_popup_hbox()->add_child(container_v_picker);
	container_v_picker->connect("size_flags_selected", callable_mp(this, &ControlEditorToolbar::_container_flags_selected).bind(true));

	// Editor connections.
	undo_redo = EditorNode::get_singleton()->get_undo_redo();
	editor_selection = EditorNode::get_singleton()->get_editor_selection();
	editor_selection->add_editor_plugin(this);
	editor_selection->connect("selection_changed", callable_mp(this, &ControlEditorToolbar::_selection_changed));

	singleton = this;
}

ControlEditorToolbar *ControlEditorToolbar::singleton = nullptr;

// Editor plugin.

ControlEditorPlugin::ControlEditorPlugin() {
	toolbar = memnew(ControlEditorToolbar);
	toolbar->hide();
	add_control_to_container(CONTAINER_CANVAS_EDITOR_MENU, toolbar);

	Ref<EditorInspectorPluginControl> plugin;
	plugin.instantiate();
	add_inspector_plugin(plugin);
}


text:
module.exports = {
    "$schema": "http://json-schema.org/draft-04/schema#",
    name: "EKAP KÝK Ihale Bilgileri",
    type: "object",
    required: ["EkapId","raw"],
    additionalProperties: false,
    properties: {
        EkapId: {type: "number",default:0},
        WebAdresi: {type: "string"},
        SartnameAdresi: {type: "string"},
        raw: {type: "string",default:""}
    }
};


text:
var util = require("util");
var EE = require("events").EventEmitter;

function Client(providerId, predicates){
  EE.call(this);
  this.id = providerId;
  this.predicates = predicates;
}

util.inherits(Client, EE);

Client.prototype.init = function(){
  this.emit("provider-initializing", {
    provider:this.id,
    predicates:this.predicates
  });
}

Client.prototype.updatePredicate = function(predicate, groundings, payload){
  this.emit("update-predicate", {
    predicate:predicate,
    groundings:groundings,
    provider:this.id,
    payload:payload
  });
}

function SharedMemoryAdapter(){
  EE.call(this);
  this.interface = "shared_memory";
  this.defaults = {};
}

util.inherits(SharedMemoryAdapter, EE);

SharedMemoryAdapter.prototype.init = function(){};

SharedMemoryAdapter.prototype.createProviderHandler = function(event, interfaceManager){
  interfaceManager.on(event.client.id + ":invoke-rule", function(client){
    return function(data){
      client.emit("invoke-rule", data);
    };
  }(event.client));

  event.client.on("update-predicate", function(data){
    interfaceManager.emit("predicate-updated", data);
  });

  event.client.once("provider-initializing", function(data){
    interfaceManager.emit("provider-initializing", data);
  });
};

SharedMemoryAdapter.prototype.createProvider = function(providerId, predicates){
  var client = new Client(providerId, predicates);
  this.emit("create-provider", {protocol:this.protocol, client:client});
  return client;
};

module.exports = SharedMemoryAdapter;


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>{{ site.title }}</title>
    <link href="{{ site.url }}/components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="{{ site.url }}/css/haroo-cloud-common.css" rel="stylesheet">

    <form id="signup-form" method="POST" class="form-horizontal form-signin">
        <input type="hidden" name="_csrf" value="{{ _csrf }}">
        <legend>Sign Up</legend>

            Email

                <input type="email" name="email" id="email" placeholder="Email" autofocus="" class="form-control">

Password

                <input type="password" name="password" id="password" placeholder="Password" class="form-control">

            Confirm Password

                <input type="password" name="confirm_password" id="confirm_password" placeholder="Confirm Password" class="form-control">

                <button class="btn btn-primary" type="submit">Sign Up</button>
                Already Has Account

    </form>


text:
using FalcoA.Core;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Xml;

namespace RuleCrawlTool
{
    public partial class MainForm : Form
    {
        List<Object> results = new List<object>();

        public MainForm()
        {
            InitializeComponent();
            btnOutputResult.Enabled = false;
        }

        private void btnStartJob_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(txtRule.Text))
                {
                    MessageBox.Show("The rule can't be empty!");
                    return;
                }

                btnOutputResult.Enabled = false;
                results.Clear();
                ITemplateFactory factory = new GeneralTemplateFactory();
                IDataProvider pp = BasicDataProvider.CreateFromXml(
                                                @"<?xml version=""1.0"" encoding=""utf-8"" ?>
                                                <ParameterProvider></ParameterProvider>"
                                            );

                XmlDocument doc = new XmlDocument();
                try
                {
                    doc.LoadXml(txtRule.Text);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("The rule is wrong! please check it again." + Environment.NewLine + ex.ToString());
                    return;
                }

                ITemplate template = factory.GetCrawlTemplate(doc);
                var result = template.Run(pp);

                foreach (string item in result.JsonResult)
                    results.Add(JsonConvert.DeserializeObject(item));

                dgvResult.DataSource = null;
                dgvResult.DataSource = results;
                dgvResult.Refresh();

                btnOutputResult.Enabled = true;

                MessageBox.Show("Crawl successful!");
            }
            catch (Exception ex2)
            {
                MessageBox.Show("This is something wrong about this program." + Environment.NewLine + ex2.ToString());
                return;
            }
        }

        private void btnOutputResult_Click(object sender, EventArgs e)
        {
            if (results != null && results.Count > 0)
            {
                SaveFileDialog fileDialog = new SaveFileDialog();
                fileDialog.Filter = "JSON|*.json";
                if (fileDialog.ShowDialog() == DialogResult.OK)
                {
                    if (fileDialog.FileName.ToLower().EndsWith("json"))
                    {
                        using (StreamWriter write = new StreamWriter(fileDialog.FileName))
                        {
                            write.Write(JsonConvert.SerializeObject(results));
                        }
                    }
                    MessageBox.Show("Output the result successful!");
                }
            }
            else
            {
                MessageBox.Show("The result is null!");
            }
        }
    }
}