text:
import luigi
from luigi.file import LocalTarget
from luigi.scheduler import CentralPlannerScheduler
import luigi.server
import luigi.worker
from mock import patch
from helpers import with_config, unittest
import os
import tempfile

class TestExternalFileTask(luigi.ExternalTask):
    """ Mocking tasks is a pain, so touch a file instead """
    path = luigi.Parameter()
    times_to_call = luigi.Parameter()

    def __init__(self, *args, **kwargs):
        super(TestExternalFileTask, self).__init__(*args, **kwargs)
        self.times_called = 0

    def complete(self):
        """
        Create the file we need after a number of preconfigured attempts
        """
        self.times_called += 1

        if self.times_called >= self.times_to_call:
            open(self.path, 'a').close()

        return os.path.exists(self.path)

    def output(self):
        return LocalTarget(path=self.path)

class TestTask(luigi.Task):
    """
    Requires a single file dependency
    """
    tempdir = luigi.Parameter()
    complete_after = luigi.Parameter()

    def __init__(self, *args, **kwargs):
        super(TestTask, self).__init__(*args, **kwargs)
        self.output_path = os.path.join(self.tempdir, "test.output")
        self.dep_path = os.path.join(self.tempdir, "test.dep")
        self.dependency = TestExternalFileTask(path=self.dep_path,
                                               times_to_call=self.complete_after)

    def requires(self):
        yield self.dependency

    def output(self):
        return LocalTarget(
            path=self.output_path)

    def run(self):
        open(self.output_path, 'a').close()

class WorkerExternalTaskTest(unittest.TestCase):

    def _assert_complete(self, tasks):
        for t in tasks:
            self.assert_(t.complete())

    def _build(self, tasks):
        self.scheduler = CentralPlannerScheduler(prune_on_get_work=True)
        w = luigi.worker.Worker(scheduler=self.scheduler, worker_processes=1)
        for t in tasks:
            w.add(t)
        w.run()
        w.stop()

    def test_external_dependency_already_complete(self):
        """
        Test that the test task completes when its dependency exists at the
        start of the execution.
        """
        tempdir = tempfile.mkdtemp(prefix='luigi-test-')
        test_task = TestTask(tempdir=tempdir, complete_after=1)
        luigi.build([test_task], local_scheduler=True)

        assert os.path.exists(test_task.dep_path)
        assert os.path.exists(test_task.output_path)

        os.unlink(test_task.dep_path)
        os.unlink(test_task.output_path)
        os.rmdir(tempdir)

        # complete() is called once per failure, twice per success
        assert test_task.dependency.times_called == 2

    @with_config({'worker': {'retry_external_tasks': 'true'},
                  'scheduler': {'retry_delay': '0.0'}})
    def test_external_dependency_gets_rechecked(self):
        """
        Test that retry_external_tasks re-checks external tasks
        """
        assert luigi.worker.worker().retry_external_tasks is True

        tempdir = tempfile.mkdtemp(prefix='luigi-test-')

        test_task = TestTask(tempdir=tempdir, complete_after=10)
        self._build([test_task])

        assert os.path.exists(test_task.dep_path)
        assert os.path.exists(test_task.output_path)

        os.unlink(test_task.dep_path)
        os.unlink(test_task.output_path)
        os.rmdir(tempdir)

        self.assertGreaterEqual(test_task.dependency.times_called, 10)

    @with_config({'worker': {'retry_external_tasks': 'true',
                             'keep_alive': 'true',
                             'wait_interval': '0.00001'},
                  'scheduler': {'retry_delay': '0.01'}})
    def test_external_dependency_worker_is_patient(self):
        """
        Test that worker doesn't "give up" with keep_alive option

        Instead, it should sleep for random.uniform() seconds, then ask
        scheduler for work.
        """
        assert luigi.worker.worker().retry_external_tasks is True

        tempdir = tempfile.mkdtemp(prefix='luigi-test-')

        with patch('random.uniform', return_value=0.001):
            test_task = TestTask(tempdir=tempdir, complete_after=5)
            self._build([test_task])

        assert os.path.exists(test_task.dep_path)
        assert os.path.exists(test_task.output_path)

        os.unlink(test_task.dep_path)
        os.unlink(test_task.output_path)
        os.rmdir(tempdir)

        self.assertGreaterEqual(test_task.dependency.times_called, 5)


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>
        <!-- SITE
        <parameter key="app_sonata.page.admin.site.class">Application\Sonata\PageBundle\Admin\SiteAdmin</parameter>
        <parameter key="app_sonata.page.admin.site.controller">SonataPageBundle:SiteAdmin</parameter>
        <parameter key="app_sonata.page.admin.site.translation_domain">SonataPageBundle</parameter>
        -->
        <parameter key="app_sonata.page.service.site.class">Application\Sonata\PageBundle\Page\Type\SitePageService</parameter>

        <!-- PAGE -->
        <parameter key="app_sonata.page.admin.page.class">Application\Sonata\PageBundle\Admin\PageAdmin</parameter>

        <!-- BLOCK -->
        <parameter key="app_sonata.page.admin.block.class">Application\Sonata\PageBundle\Admin\BlockAdmin</parameter>
        <parameter key="app_sonata.page.block.children_pages.class">Application\Sonata\PageBundle\Block\ChildrenPagesBlockService</parameter>
        <!--
        <parameter key="sonata.page.admin.page.class">Application\Sonata\PageBundle\Admin\PageAdmin</parameter>
        <parameter key="sonata.page.admin.block.class">Application\Sonata\PageBundle\Admin\BlockAdmin</parameter>
        -->
    </parameters>

    <services>
        <!--service id="sonata.block.form.type.block" class="Application\Sonata\PageBundle\Form\Type\ServiceListType">
            <tag name="form.type" alias="sonata_block_service_choice" />
            <argument type="service" id="sonata.block.manager" />
            <argument />
        </service-->

        <service id="app_sonata.page.block.children_pages" class="%app_sonata.page.block.children_pages.class%">
            <tag name="sonata.block" />
            <argument>app_sonata.page.block.children_pages</argument>
            <argument type="service" id="templating" />
            <argument type="service" id="sonata.page.site.selector" />
            <argument type="service" id="sonata.page.cms_manager_selector" />
        </service>

        <service id="app_sonata.page.service.site" class="%app_sonata.page.service.site.class%">
            <tag name="sonata.page"/>
            <argument>Site</argument>
            <argument type="service" id="sonata.page.template_manager" />
            <argument type="service" id="sonata.seo.page" />
        </service>

        <service id="sonata.page.admin.page" class="%app_sonata.page.admin.page.class%">
            <tag name="sonata.admin" manager_type="orm" label_translator_strategy="sonata.admin.label.strategy.underscore"
                 group="sonata_page"
                 label="page"
                 show_in_dashboard="true"
                 label_catalogue="%sonata.page.admin.page.translation_domain%"
            />
            <argument />
            <argument>%sonata.page.admin.page.entity%</argument>
            <argument>%sonata.page.admin.page.controller%</argument>
            <call method="setContainer">
                <argument type="service" id="service_container" />
            </call>
            <call method="addChild">
                <argument type="service" id="sonata.page.admin.block" />
            </call>

            <call method="addChild">
                <argument type="service" id="sonata.page.admin.snapshot" />
            </call>

            <call method="setPageManager">
                <argument type="service" id="sonata.page.manager.page" />
            </call>

            <call method="setCacheManager">
                <argument type="service" id="sonata.cache.manager" />
            </call>

            <call method="setSiteManager">
                <argument type="service" id="sonata.page.manager.site" />
            </call>

            <call method="setTranslationDomain">
                <argument>%sonata.page.admin.page.translation_domain%</argument>
            </call>
        </service>

        <service id="sonata.page.admin.block" class="%app_sonata.page.admin.block.class%">
            <tag name="sonata.admin" manager_type="orm" label_translator_strategy="sonata.admin.label.strategy.underscore"
                 group="sonata_page"
                 label="block"
                 show_in_dashboard="true"
                 label_catalogue="%sonata.page.admin.block.translation_domain%"
            />
            <argument />
            <argument>%sonata.page.admin.block.entity%</argument>
            <argument>%sonata.page.admin.block.controller%</argument>

            <call method="setContainer">
                <argument type="service" id="service_container" />
            </call>
            <call method="setCacheManager">
                <argument type="service" id="sonata.cache.manager" />
            </call>

            <call method="setBlockManager">
                <argument type="service" id="sonata.block.manager" />
            </call>

            <call method="setTranslationDomain">
                <argument>%sonata.page.admin.block.translation_domain%</argument>
            </call>
        </service>
        <!--
        <service id="app_sonata.page.admin.page" class="%sonata.page.admin.page.extension.class%">
            <tag name="sonata.admin.extension" target="sonata.page.admin.page" />
        </service>

        -->

    </services>

</container>

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Pantheon\Terminus\Commands\Connection;

use Pantheon\Terminus\Commands\TerminusCommand;
use Pantheon\Terminus\Site\SiteAwareInterface;
use Pantheon\Terminus\Site\SiteAwareTrait;
use Pantheon\Terminus\Exceptions\TerminusException;

/**
 * Class SetCommand
 * @package Pantheon\Terminus\Commands\Connection
 */
class SetCommand extends TerminusCommand implements SiteAwareInterface
{
    use SiteAwareTrait;

    /**
     * Sets Git or SFTP connection mode on a development environment (excludes Test and Live).
     *
     * @authorize
     *
     * @command connection:set
     *
     * @param string $site_env Site & development environment (excludes Test and Live) in the format `site-name.env`
     * @param string $mode [git|sftp] Connection mode
     *
     * @throws TerminusException
     *
     * @usage terminus connection:set <site>.<env> <mode>
     *     Sets the connection mode of <site>'s <env> environment to <mode>.
     */
    public function connectionSet($site_env, $mode)
    {
        list(, $env) = $this->getSiteEnv($site_env);

        if (in_array($env->id, ['test', 'live',])) {
            throw new TerminusException(
                'Connection mode cannot be set on the {env} environment',
                ['env' => $env->id,]
            );
        }

        $workflow = $env->changeConnectionMode($mode);
        if (is_string($workflow)) {
            $this->log()->notice($workflow);
        } else {
            while (!$workflow->checkProgress()) {
                // TODO: (ajbarry) Add workflow progress output
            }
            $this->log()->notice($workflow->getMessage());
        }
    }
}


text:
require File.expand_path("../../../../base", __FILE__)
require Vagrant.source_root.join("plugins/provisioners/shell/provisioner")

describe "Vagrant::Shell::Provisioner" do
  include_context "unit"

  let(:default_win_path) { "C:/tmp/vagrant-shell" }
  let(:env){ isolated_environment }
  let(:machine) {
    double(:machine, env: env, id: "ID").tap { |machine|
      allow(machine).to receive_message_chain(:config, :vm, :communicator).and_return(:not_winrm)
      allow(machine).to receive_message_chain(:config, :vm, :guest).and_return(:linux)
      allow(machine).to receive_message_chain(:communicate, :tap) {}
    }
  }

  before do
    allow(env).to receive(:tmp_path).and_return(Pathname.new("/dev/null"))
  end

  context "when reset is enabled" do
    let(:path) { nil }
    let(:inline) { "" }
    let(:communicator) { double("communicator") }

    let(:config) {
      double(
        :config,
        :args        => "doesn't matter",
        :env         => {},
        :upload_path => "arbitrary",
        :remote?     => false,
        :path        => path,
        :inline      => inline,
        :binary      => false,
        :reset       => true,
        :reboot      => false,
      )
    }

    let(:vsp) {
      VagrantPlugins::Shell::Provisioner.new(machine, config)
    }

    before {
      allow(machine).to receive(:communicate).and_return(communicator)
      allow(vsp).to receive(:provision_ssh)
    }

    it "should provision and then reset the connection" do
      expect(vsp).to receive(:provision_ssh)
      expect(communicator).to receive(:reset!)
      vsp.provision
    end

    context "when path and inline are not set" do
      let(:path) { nil }
      let(:inline) { nil }

      it "should reset the connection and not provision" do
        expect(vsp).not_to receive(:provision_ssh)
        expect(communicator).to receive(:reset!)
        vsp.provision
      end
    end
  end

  context "when reboot is enabled" do
    let(:path) { nil }
    let(:inline) { "" }
    let(:communicator) { double("communicator") }
    let(:guest) { double("guest") }

    let(:config) {
      double(
        :config,
        :args        => "doesn't matter",
        :env         => {},
        :upload_path => "arbitrary",
        :remote?     => false,
        :path        => path,
        :inline      => inline,
        :binary      => false,
        :reset       => false,
        :reboot      => true
      )
    }

    let(:vsp) {
      VagrantPlugins::Shell::Provisioner.new(machine, config)
    }

    before {
      allow(machine).to receive(:communicate).and_return(communicator)
      allow(machine).to receive(:guest).and_return(guest)
      allow(vsp).to receive(:provision_ssh)
    }

    it "should provision and then reboot the guest" do
      expect(vsp).to receive(:provision_ssh)
      expect(guest).to receive(:capability).with(:reboot)
      vsp.provision
    end

    context "when path and inline are not set" do
      let(:path) { nil }
      let(:inline) { nil }

      it "should reboot the guest and not provision" do
        expect(vsp).not_to receive(:provision_ssh)
        expect(guest).to receive(:capability).with(:reboot)
        vsp.provision
      end
    end
  end

  context "with a script that contains invalid us-ascii byte sequences" do
    let(:config) {
      double(
        :config,
        :args        => "doesn't matter",
        :env         => {},
        :upload_path => "arbitrary",
        :remote?     => false,
        :path        => nil,
        :inline      => script_that_is_incorrectly_us_ascii_encoded,
        :binary      => false,
        :reset       => false,
        :reboot      => false
      )
    }

    let(:script_that_is_incorrectly_us_ascii_encoded) {
      [207].pack("c*").force_encoding("US-ASCII")
    }

    it "does not raise an exception when normalizing newlines" do
      vsp = VagrantPlugins::Shell::Provisioner.new(machine, config)

      expect {
        vsp.provision
      }.not_to raise_error
    end
  end

  context "with a script that was set to freeze the string" do
    TEST_CONSTANT_VARIABLE = <<-TEST_CONSTANT_VARIABLE.freeze
      echo test
    TEST_CONSTANT_VARIABLE

    let(:script) { TEST_CONSTANT_VARIABLE }
    let(:config) {
      double(
        :config,
        :args        => "doesn't matter",
        :env         => {},
        :upload_path => "arbitrary",
        :remote?     => false,
        :path        => nil,
        :inline      => script,
        :binary      => false,
        :reset       => false,
        :reboot      => false
      )
    }

    it "does not raise an exception" do
      vsp = VagrantPlugins::Shell::Provisioner.new(machine, config)

      RSpec::Expectations.configuration.on_potential_false_positives = :nothing
      # This test should be fine, since we are specifically looking for the
      # string 'freeze' when RuntimeError is raised
      expect {
        vsp.provision
      }.not_to raise_error(RuntimeError)
    end
  end

  context "with remote script" do
    let(:filechecksum) { double("filechecksum", checksum: checksum_value) }
    let(:checksum_value) { double("checksum_value") }

    before do
      allow(FileChecksum).to receive(:new).and_return(filechecksum)
      allow_any_instance_of(Vagrant::Util::Downloader).to receive(:execute_curl).and_return(true)
    end

    context "that does not have matching sha1 checksum" do
      let(:checksum_value) { "INVALID_VALUE" }
      let(:config) {
        double(
          :config,
          :args        => "doesn't matter",
          :env         => {},
          :upload_path => "arbitrary",
          :remote?     => true,
          :path        => "http://example.com/script.sh",
          :binary      => false,
          :md5         => nil,
          :sha1        => 'EXPECTED_VALUE',
          :sha256      => nil,
          :sha384      => nil,
          :sha512      => nil,
          :reset       => false,
          :reboot      => false
        )
      }

      it "should raise an exception" do
        vsp = VagrantPlugins::Shell::Provisioner.new(machine, config)

        expect{ vsp.provision }.to raise_error(Vagrant::Errors::DownloaderChecksumError)
      end
    end

    context "that does not have matching sha256 checksum" do
      let(:checksum_value) { "INVALID_VALUE" }
      let(:config) {
        double(
          :config,
          :args        => "doesn't matter",
          :env         => {},
          :upload_path => "arbitrary",
          :remote?     => true,
          :path        => "http://example.com/script.sh",
          :binary      => false,
          :md5         => nil,
          :sha1        => nil,
          :sha256      => 'EXPECTED_VALUE',
          :sha384      => nil,
          :sha512      => nil,
          :reset       => false,
          :reboot      => false
        )
      }

      it "should raise an exception" do
        vsp = VagrantPlugins::Shell::Provisioner.new(machine, config)

        expect{ vsp.provision }.to raise_error(Vagrant::Errors::DownloaderChecksumError)
      end
    end

    context "that does not have matching sha384 checksum" do
      let(:checksum_value) { "INVALID_VALUE" }
      let(:config) {
        double(
          :config,
          :args        => "doesn't matter",
          :env         => {},
          :upload_path => "arbitrary",
          :remote?     => true,
          :path        => "http://example.com/script.sh",
          :binary      => false,
          :md5         => nil,
          :sha1        => nil,
          :sha256      => nil,
          :sha384      => 'EXPECTED_VALUE',
          :sha512      => nil,
          :reset       => false,
          :reboot      => false
        )
      }

      it "should raise an exception" do
        vsp = VagrantPlugins::Shell::Provisioner.new(machine, config)

        expect{ vsp.provision }.to raise_error(Vagrant::Errors::DownloaderChecksumError)
      end
    end

    context "that does not have matching sha512 checksum" do
      let(:checksum_value) { "INVALID_VALUE" }
      let(:config) {
        double(
          :config,
          :args        => "doesn't matter",
          :env         => {},
          :upload_path => "arbitrary",
          :remote?     => true,
          :path        => "http://example.com/script.sh",
          :binary      => false,
          :md5         => nil,
          :sha1        => nil,
          :sha256      => nil,
          :sha384      => nil,
          :sha512      => 'EXPECTED_VALUE',
          :reset       => false,
          :reboot      => false
        )
      }

      it "should raise an exception" do
        vsp = VagrantPlugins::Shell::Provisioner.new(machine, config)

        expect{ vsp.provision }.to raise_error(Vagrant::Errors::DownloaderChecksumError)
      end
    end

    context "that does not have matching md5 checksum" do
      let(:checksum_value) { "INVALID_VALUE" }
      let(:config) {
        double(
          :config,
          :args        => "doesn't matter",
          :env         => {},
          :upload_path => "arbitrary",
          :remote?     => true,
          :path        => "http://example.com/script.sh",
          :binary      => false,
          :md5         => 'EXPECTED_VALUE',
          :sha1        => nil,
          :sha256      => nil,
          :sha384      => nil,
          :sha512      => nil,
          :reset       => false,
          :reboot      => false
        )
      }

      it "should raise an exception" do
        vsp = VagrantPlugins::Shell::Provisioner.new(machine, config)

        expect{ vsp.provision }.to raise_error(Vagrant::Errors::DownloaderChecksumError)
      end
    end
  end

  describe "#upload_path" do
    context "when upload path is not set" do
      let(:vsp) {
        VagrantPlugins::Shell::Provisioner.new(machine, config)
      }

      let(:config) {
        double(
          :config,
          :args        => "doesn't matter",
          :env         => {},
          :upload_path => nil,
          :remote?     => false,
          :path        => "doesn't matter",
          :inline      => "doesn't matter",
          :binary      => false,
          :reset       => true,
          :reboot      => false,
        )
      }

      it "should default to /tmp/vagrant-shell" do
        expect(vsp.upload_path).to eq("/tmp/vagrant-shell")
      end

      context "windows" do
        before do
          allow(machine).to receive_message_chain(:config, :vm, :guest).and_return(:windows)
        end

        it "should default to C:/tmp/vagrant-shell" do
          expect(vsp.upload_path).to eq("C:/tmp/vagrant-shell")
        end
      end
    end

    context "when upload_path is set" do
      let(:upload_path) { "arbitrary" }

      let(:config) {
        double(
          :config,
          :args        => "doesn't matter",
          :env         => {},
          :upload_path => upload_path,
          :remote?     => false,
          :path        => "doesn't matter",
          :inline      => "doesn't matter",
          :binary      => false,
          :reset       => true,
          :reboot      => false,
        )
      }

      let(:vsp) {
        VagrantPlugins::Shell::Provisioner.new(machine, config)
      }

      it "should use the value from from config" do
        expect(vsp.upload_path).to eq("arbitrary")
      end

      context "windows" do
        let(:upload_path) { "C:\\Windows\\Temp" }

        before do
          allow(machine).to receive_message_chain(:config, :vm, :guest).and_return(:windows)
        end

        it "should normalize the slashes" do
          expect(vsp.upload_path).to eq("C:/Windows/Temp")
        end
      end
    end

    context "with cached value" do
      let(:config) { double(:config) }

      let(:vsp) {
        VagrantPlugins::Shell::Provisioner.new(machine, config)
      }

      before do
        vsp.instance_variable_set(:@_upload_path, "anything")
      end

      it "should use cached value" do
        expect(vsp.upload_path).to eq("anything")
      end
    end
  end

  describe "#provision_winrm" do
    let(:config) {
      double(
        :config,
        :args                            => "doesn't matter",
        :env                             => {},
        :upload_path                     => "arbitrary",
        :remote?                         => false,
        :path                            => "script/info.ps1",
        :binary                          => false,
        :md5                             => nil,
        :sha1                            => 'EXPECTED_VALUE',
        :sha256                          => nil,
        :sha384                          => nil,
        :sha512                          => nil,
        :reset                           => false,
        :reboot                          => false,
        :powershell_args                 => "",
        :name                            => nil,
        :privileged                      => false,
        :powershell_elevated_interactive => false
      )
    }

    let(:vsp) {
      VagrantPlugins::Shell::Provisioner.new(machine, config)
    }

    let(:communicator) { double("communicator") }
    let(:guest) { double("guest") }
    let(:ui) { double("ui") }

    before {
      allow(guest).to receive(:capability?).with(:wait_for_reboot).and_return(false)
      allow(ui).to receive(:detail)
      allow(communicator).to receive(:sudo)
      allow(machine).to receive(:communicate).and_return(communicator)
      allow(machine).to receive(:guest).and_return(guest)
      allow(machine).to receive(:ui).and_return(ui)
    }

    it "ensures that files are uploaded with an extension" do
      allow(vsp).to receive(:with_script_file).and_yield(config.path)
      expect(communicator).to receive(:upload).with(config.path, /arbitrary.ps1$/)
      vsp.send(:provision_winrm, "")
    end

    context "bat file being uploaded" do
      before do
        allow(config).to receive(:path).and_return("script/info.bat")
        allow(vsp).to receive(:with_script_file).and_yield(config.path)
      end

      it "ensures that files are uploaded same extension as provided path.bat" do
        expect(communicator).to receive(:upload).with(config.path, /arbitrary/)
        expect(communicator).to receive(:sudo).with(/arbitrary.bat/, anything)
        vsp.send(:provision_winrm, "")
      end
    end

    context "inline option set" do
      let(:config) {
        double(
          :config,
          :args                            => "doesn't matter",
          :env                             => {},
          :remote?                         => false,
          :inline                          => "some commands",
          :upload_path                     => nil,
          :path                            => nil,
          :binary                          => false,
          :md5                             => nil,
          :sha1                            => 'EXPECTED_VALUE',
          :sha256                          => nil,
          :sha384                          => nil,
          :sha512                          => nil,
          :reset                           => false,
          :reboot                          => false,
          :powershell_args                 => "",
          :name                            => nil,
          :privileged                      => false,
          :powershell_elevated_interactive => false
        )
      }

      it "creates an executable with an extension" do
        allow(machine).to receive_message_chain(:config, :winssh, :shell).and_return(nil)
        allow(vsp).to receive(:with_script_file).and_yield(default_win_path)
        allow(communicator).to receive(:upload).with(default_win_path, /vagrant-shell/)
        expect(communicator).to receive(:sudo).with(/vagrant-shell.ps1/, anything)
        vsp.send(:provision_winrm, "")
      end
    end
  end

  describe "#provision_winssh" do
    let(:config) {
      double(
        :config,
        :args                            => "doesn't matter",
        :env                             => {},
        :upload_path                     => "arbitrary",
        :remote?                         => false,
        :path                            => nil,
        :inline                          => "something",
        :binary                          => false,
        :md5                             => nil,
        :sha1                            => 'EXPECTED_VALUE',
        :sha256                          => nil,
        :sha384                          => nil,
        :sha512                          => nil,
        :reset                           => false,
        :reboot                          => false,
        :powershell_args                 => "",
        :name                            => nil,
        :privileged                      => false,
        :powershell_elevated_interactive => false
      )
    }

    let(:vsp) {
      VagrantPlugins::Shell::Provisioner.new(machine, config)
    }

    let(:communicator) { double("communicator") }
    let(:guest) { double("guest") }
    let(:ui) { double("ui") }

    before {
      allow(guest).to receive(:capability?).with(:wait_for_reboot).and_return(false)
      allow(ui).to receive(:detail)
      allow(communicator).to receive(:sudo)
      allow(communicator).to receive_message_chain(:machine_config_ssh, :shell)
      allow(machine).to receive(:communicate).and_return(communicator)
      allow(machine).to receive(:guest).and_return(guest)
      allow(machine).to receive(:ui).and_return(ui)
      allow(machine).to receive(:ssh_info).and_return(true)
    }

    context "ps1 file being uploaded" do
      before do
        allow(config).to receive(:path).and_return("script/info.ps1")
        allow(vsp).to receive(:with_script_file).and_yield(config.path)
      end

      it "ensures that files are uploaded same extension as provided path.ps1" do
        allow(machine).to receive_message_chain(:config, :winssh, :shell).and_return("cmd")
        expect(communicator).to receive(:upload).with(config.path, /arbitrary.ps1/)
        expect(communicator).to receive(:execute).with(/powershell.*arbitrary.ps1/, anything)
        vsp.send(:provision_winssh, "")
      end
    end

    context "bat file being uploaded" do
      before do
        allow(config).to receive(:path).and_return("script/info.bat")
        allow(vsp).to receive(:with_script_file).and_yield(config.path)
      end

      it "ensures that files are uploaded same extension as provided path.bat" do
        allow(machine).to receive_message_chain(:config, :winssh, :shell).and_return("cmd")
        expect(communicator).to receive(:upload).with(config.path, /arbitrary.bat/)
        expect(communicator).to receive(:execute).with(/cmd.*arbitrary.bat/, anything)
        vsp.send(:provision_winssh, "")
      end
    end

    context "with inline script" do
      before do
        allow(vsp).to receive(:with_script_file).and_yield("/tmp/file/contents")
      end

      context "when upload path has a .ps1 extension" do
        before do
          allow(config).to receive(:upload_path).and_return("c:/tmp/vagrant-shell.ps1")
        end

        it "executes the remote script with powershell" do
          expect(communicator).to receive(:upload).with(anything, config.upload_path)
          expect(communicator).to receive(:execute).with(/powershell.*\.ps1/, anything)
          vsp.send(:provision_winssh, "")
        end
      end

      context "when upload path has a .bat extension" do
        before do
          allow(config).to receive(:upload_path).and_return("c:/tmp/vagrant-shell.bat")
        end

        it "executes the remote script with cmd" do
          expect(communicator).to receive(:upload).with(anything, config.upload_path)
          expect(communicator).to receive(:execute).with(/cmd.*\.bat/, anything)
          vsp.send(:provision_winssh, "")
        end
      end

      context "when upload path has no extension" do
        before do
          allow(config).to receive(:upload_path).and_return("c:/tmp/vagrant-shell")
        end

        context "when winssh shell is cmd" do
          before do
            allow(machine).to receive_message_chain(:config, :winssh, :shell).and_return("cmd")
          end

          it "adds an extension and executes the remote script with cmd" do
            expect(communicator).to receive(:upload).with(anything, /\.bat$/)
            expect(communicator).to receive(:execute).with(/cmd.*\.bat/, anything)
            vsp.send(:provision_winssh, "")
          end
        end

        context "when winssh shell is powershell" do
          before do
            allow(machine).to receive_message_chain(:config, :winssh, :shell).and_return("powershell")
          end

          it "adds an extension executes the remote script with powershell" do
            expect(communicator).to receive(:upload).with(anything, /\.ps1$/)
            expect(communicator).to receive(:execute).with(/powershell.*\.ps1/, anything)
            vsp.send(:provision_winssh, "")
          end
        end
      end
    end
  end
end


text:
package powerschool.rest.vo.xsd;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for QueryIncludeListVO complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="QueryIncludeListVO">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="includes" type="{http://www.w3.org/2001/XMLSchema}int" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "QueryIncludeListVO", propOrder = {
    "includes"
})
public class QueryIncludeListVO {

    @XmlElement(nillable = true)
    protected List<Integer> includes;

    /**
     * Gets the value of the includes property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the includes property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getIncludes().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link Integer }
     *
     *
     */
    public List<Integer> getIncludes() {
        if (includes == null) {
            includes = new ArrayList<Integer>();
        }
        return this.includes;
    }

}


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel app\models\TinyurlSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Tinyurls';
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

        <?= Html::a('Create Tinyurl', ['create'], ['class' => 'btn btn-success']) ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'short',
            'full',
            'created_time',
            'last_access',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>


text:
package org.apache.helix.healthcheck;

import java.util.LinkedList;
import java.util.Map;

import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.model.HealthStat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ParticipantHealthReportCollectorImpl implements ParticipantHealthReportCollector {
  private final LinkedList<HealthReportProvider> _healthReportProviderList =
      new LinkedList<HealthReportProvider>();
  private static final Logger LOG = LoggerFactory
      .getLogger(ParticipantHealthReportCollectorImpl.class);
  private final HelixManager _helixManager;
  String _instanceName;

  public ParticipantHealthReportCollectorImpl(HelixManager helixManager, String instanceName) {
    _helixManager = helixManager;
    _instanceName = instanceName;
  }

  @Override
  public void addHealthReportProvider(HealthReportProvider provider) {
    try {
      synchronized (_healthReportProviderList) {
        if (!_healthReportProviderList.contains(provider)) {
          _healthReportProviderList.add(provider);
        } else {
          LOG.warn("Skipping a duplicated HealthCheckInfoProvider");
        }
      }
    } catch (Exception e) {
      LOG.error(e.toString());
    }
  }

  @Override
  public void removeHealthReportProvider(HealthReportProvider provider) {
    synchronized (_healthReportProviderList) {
      if (_healthReportProviderList.contains(provider)) {
        _healthReportProviderList.remove(provider);
      } else {
        LOG.warn("Skip removing a non-exist HealthCheckInfoProvider");
      }
    }
  }

  @Override
  public void reportHealthReportMessage(ZNRecord healthCheckInfoUpdate) {
    HelixDataAccessor accessor = _helixManager.getHelixDataAccessor();
    Builder keyBuilder = accessor.keyBuilder();
    if(!accessor.setProperty(keyBuilder.healthReport(_instanceName, healthCheckInfoUpdate.getId()),
        new HealthStat(healthCheckInfoUpdate))) {
      LOG.error("Failed to persist health report to zk!");
    }
  }

  @Override
  public synchronized void transmitHealthReports() {
    synchronized (_healthReportProviderList) {
      for (HealthReportProvider provider : _healthReportProviderList) {
        try {
          Map<String, String> report = provider.getRecentHealthReport();
          Map<String, Map<String, String>> partitionReport =
              provider.getRecentPartitionHealthReport();
          ZNRecord record = new ZNRecord(provider.getReportName());
          if (report != null) {
            record.setSimpleFields(report);
          }
          if (partitionReport != null) {
            record.setMapFields(partitionReport);
          }
          record.setSimpleField(HealthStat.TIMESTAMP_NAME, "" + System.currentTimeMillis());

          HelixDataAccessor accessor = _helixManager.getHelixDataAccessor();
          Builder keyBuilder = accessor.keyBuilder();
          if (!accessor.setProperty(keyBuilder.healthReport(_instanceName, record.getId()),
              new HealthStat(record))) {
            LOG.error("Failed to persist health report to zk!");
          }

          provider.resetStats();
        } catch (Exception e) {
          LOG.error("fail to transmit health report", e);
        }
      }
    }
  }
}


text:
package org.hoteia.qalingo.web.mvc.form;

import java.io.Serializable;

import org.hibernate.validator.constraints.NotEmpty;

import org.hoteia.qalingo.core.web.validation.annotation.TwoFieldsEquals;

/**
 *
 *
 */
public class ResetPasswordForm implements Serializable {

	/**
     *
     */
    private static final long serialVersionUID = -4398822690434901496L;

	@NotEmpty(message = "fo.auth.error_form_reset_password_email_empty")
	private String email;

	@NotEmpty(message = "fo.auth.error_form_reset_password_token_empty")
	private String token;

	@NotEmpty(message = "fo.auth.error_form_reset_password_new_password_empty")
	private String newPassword;

	@NotEmpty(message = "fo.auth.error_form_reset_password_confirm_password_empty")
    @TwoFieldsEquals(highlightFieldNames={"newPassword"}, message="fo.auth.error_form_reset_password_confirm_password_is_wrong")
	private String confirmNewPassword;

	public String getEmail() {
	    return email;
    }

	public void setEmail(String email) {
	    this.email = email;
    }

	public String getToken() {
	    return token;
    }

	public void setToken(String token) {
	    this.token = token;
    }

	public String getNewPassword() {
    	return newPassword;
    }

	public void setNewPassword(String newPassord) {
    	this.newPassword = newPassord;
    }

	public String getConfirmNewPassword() {
    	return confirmNewPassword;
    }

	public void setConfirmNewPassword(String confirmNewPassword) {
    	this.confirmNewPassword = confirmNewPassword;
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Arthopyrenia vainioana Räsänen ex Sbarbaro

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.Linq;
using OpenTK;
using OpenTK.Input;
using Gwen.Control;

namespace Sharp
{
	public static class InputHandler
	{
		internal static KeyboardState prevKeyState;
		internal static KeyboardState curKeyState;

		public static Action<KeyboardKeyEventArgs> OnKeyDown;
		public static Action<KeyboardKeyEventArgs> OnKeyUp;

		internal static MouseState prevMouseState;
		internal static MouseState curMouseState;

		public static Action<MouseButtonEventArgs> OnMouseDown;
		public static Action<MouseButtonEventArgs> OnMouseUp;
		public static Action<MouseMoveEventArgs> OnMouseMove;

		public static bool focused = false;
		public static Gwen.Input.OpenTK input=new Gwen.Input.OpenTK();

		static readonly IEnumerable<MouseButton> mouseCodes=typeof(MouseButton).GetEnumValues().Cast<MouseButton>();
		static readonly IEnumerable<Key> keyboardCodes=typeof(Key).GetEnumValues().Cast<Key>();

		public static void ProcessMouse(int oriX,int oriY){

			EventArgs evnt=null;
			var pressed = false;
			prevMouseState =curMouseState;
			curMouseState = Mouse.GetCursorState ();
            Gwen.Input.InputHandler.HoveredControl =input.m_Canvas.GetControlAt(curMouseState.X - oriX, curMouseState.Y - oriY);
            foreach (var mouseCode in mouseCodes)
				if (curMouseState[mouseCode]!=prevMouseState[mouseCode]){
                    evnt = new MouseButtonEventArgs(curMouseState.X - oriX, curMouseState.Y - oriY, mouseCode, true);//last param bugged
                    //evnt = new MouseButtonEventArgs (curMouseState.X, curMouseState.Y, mouseCode,true);//last param bugged
					if (curMouseState [mouseCode]) {
						pressed = true;
                        Gwen.Input.InputHandler.MouseFocus = Gwen.Input.InputHandler.HoveredControl;
                        OnMouseDown?.Invoke ((MouseButtonEventArgs)evnt);
					} else {
						OnMouseUp?.Invoke ((MouseButtonEventArgs)evnt);

					}
				}
			Vector2 delta =MainWindow.lastPos - new Vector2(curMouseState.X, curMouseState.Y);
			if (Math.Abs (delta.X) > 0 || Math.Abs (delta.Y) > 0) {

				evnt = new MouseMoveEventArgs (curMouseState.X-oriX, curMouseState.Y-oriY,(int)delta.X,(int)delta.Y);
				OnMouseMove?.Invoke (evnt as MouseMoveEventArgs);
			}
			input.ProcessMouseMessage (evnt,pressed);
			MainWindow.lastPos = new Vector2 (curMouseState.X, curMouseState.Y);
		}
		public static void ProcessKeyboard(){

			KeyboardKeyEventArgs evnt=null;
			prevKeyState = curKeyState;
			curKeyState = Keyboard.GetState();

			foreach(var keyboardCode in keyboardCodes)
				if (curKeyState[keyboardCode]!=prevKeyState[keyboardCode]){
					if (curKeyState[keyboardCode]) {
						OnKeyDown?.Invoke (evnt);

						input.ProcessKeyDown (keyboardCode);
					} else {
						OnKeyUp?.Invoke(evnt);
						input.ProcessKeyUp (keyboardCode);
					}
				}
		}
	}
}


text:
ActiveRecord::Schema.define(version: 20160129133231) do

  create_table "agents", force: :cascade do |t|
    t.string   "name"
    t.string   "email"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "customers", force: :cascade do |t|
    t.string   "name"
    t.string   "email"
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
    t.integer  "organization_id"
  end

  create_table "groups", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "message_queues", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "messages", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "organizations", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "ticket_threads", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "tickets", force: :cascade do |t|
    t.string   "title"
    t.string   "body"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingBottom="30dp"
    android:paddingTop="30dp">

    <TextView
        android:id="@+id/tv_chaptersEmpty"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/empty_list"
        android:textAppearance="?android:attr/textAppearanceSmall" />

</LinearLayout>


text:
#include "config.h"
#include "WebKitDLL.h"
#include "WebGeolocationPosition.h"
#include <WebCore/COMPtr.h>

#include <WebCore/GeolocationPosition.h>

using namespace WebCore;

COMPtr<WebGeolocationPosition> WebGeolocationPosition::createInstance()
{
    return new WebGeolocationPosition;
}

WebGeolocationPosition::WebGeolocationPosition()
    : m_refCount(0)
{
    gClassCount++;
    gClassNameCount.add("WebGeolocationPosition");
}

WebGeolocationPosition::~WebGeolocationPosition()
{
    gClassCount--;
    gClassNameCount.remove("WebGeolocationPosition");
}

HRESULT WebGeolocationPosition::QueryInterface(REFIID riid, void** ppvObject)
{
    *ppvObject = 0;
    if (IsEqualIID(riid, __uuidof(WebGeolocationPosition)))
        *ppvObject = this;
    else if (IsEqualIID(riid, __uuidof(IUnknown)))
        *ppvObject = static_cast<IWebGeolocationPosition*>(this);
    else if (IsEqualIID(riid, __uuidof(IWebGeolocationPosition)))
        *ppvObject = static_cast<IWebGeolocationPosition*>(this);
    else
        return E_NOINTERFACE;

    AddRef();
    return S_OK;
}

ULONG WebGeolocationPosition::AddRef()
{
    return ++m_refCount;
}

ULONG WebGeolocationPosition::Release()
{
    ULONG newRef = --m_refCount;
    if (!newRef)
        delete this;

    return newRef;
}

HRESULT WebGeolocationPosition::initWithTimestamp(double timestamp, double latitude, double longitude, double accuracy)
{
    m_position = GeolocationPosition::create(timestamp, latitude, longitude, accuracy);
    return S_OK;
}

GeolocationPosition* core(IWebGeolocationPosition* position)
{
    if (!position)
        return 0;

    COMPtr<WebGeolocationPosition> webGeolocationPosition(Query, position);
    if (!webGeolocationPosition)
        return 0;

    return webGeolocationPosition->impl();
}


text:
BC.js (v0.5.1)
===================================
BC.js is the core implementation of Bluetooth SDK for Android/iOS, in Bluetooth JavaScript API.

It supports both Bluetooth 4.0 GATT/BLE interface in IOS/Android and Bluetooth 2.1 Classical Rfcomm/L2cap socket interface in Android.

  * Online Bluetooth Javascript API document: http://www.bcsphere.org/portal.php?mod=topic&topicid=3

  * library based on BC.js, which can be re-used by applications to accelerate development.
  * [bcexplorer](https://github.com/bcsphere/bcexplorer) is the open source tool to explore the GATT services/characteristics of Bluetooth Smart devices. It helps debug devices as well as demostrates the Bluetooth Javascript API.
  * [bciBeacon](https://github.com/bcsphere/ibeacon) implements a demo iBeacon as a plugin based on BC.js.

Features
-----------------------------------
#### Multi-platform development and deployment
* Develop Bluetooth enabled cross-platform mobile Apps for iOS and Android using JavaScript, HTML5 and CSS3.
* Single team on a single project instead of several teams for different platforms.
* Uniform UI code in multi-platform.

#### Bluetooth Dual Mode
* Support Bluetooth 4.0 GATT interface in IOS/Android.
* Support Bluetooth 2.1 rfcomm interface in Android.

#### Beacon / iBeacon
* Support Beacon/iBeacon capability in IOS/Android.
* Support proximity with beacon

#### Bluetooth Common Services Library
* Implement Bluetooth 4.0 Standard GATT services. (extending)
* Integrate various customermized GATT services to access partners' Bluetooth Smart devices. (extending)

#### Offical profile & services implements
* BC.js implements some of offical profiles and services which defined in Bluetooth Specification(www.bluetooth.org)
* Profiles include [Find Me](https://github.com/bcsphere/bluetooth/blob/master/www/org.bluetooth.profile/find_me.js)/
[Proximity](https://github.com/bcsphere/bluetooth/blob/master/www/org.bluetooth.profile/proximity.js)
* Services include [TX Power](https://github.com/bcsphere/bluetooth/blob/master/www/org.bluetooth.service/tx_power.js)/
[Link Loss](https://github.com/bcsphere/bluetooth/blob/master/www/org.bluetooth.service/link_loss.js)/
[Immediate Alert](https://github.com/bcsphere/bluetooth/blob/master/www/org.bluetooth.service/immediate_alert.js)...
* Find Me example is [here](https://github.com/bcsphere/apps/tree/master/findme), it shows how to use the profiles.

#### Universal Bluetooth Serial Port
* Cross-platform implementation of Bluetooth serial port, covering the IOS/Android platform difference when using the [serial port profile](https://https://github.com/bcsphere/bluetooth/blob/master/www/org.bluetooth.profile/serial_port.js).
* Automatic Bluetooth 4.0/2.1 routing to establish appropriate connection, considering both phones and peripheral devices modes.

#### Reuse rich Apache Cordova/PhoneGap Ecosystem
* PhoneGap enables the implementation of many useful plugins such as  [Camera](http://docs.phonegap.com/en/edge/cordova_camera_camera.md.html#Camera)/[Accelerometer](http://docs.phonegap.com/en/edge/cordova_accelerometer_accelerometer.md.html#Accelerometer)/[Compass](http://docs.phonegap.com/en/edge/cordova_compass_compass.md.html#Compass)...
* Reuse many open-source plugins implements by third party ([PlugReg](http://plugreg.com/)).
* Implement your own [plugins](http://docs.phonegap.com/en/3.3.0/guide_hybrid_plugins_index.md.html#Plugin%20Development%20Guide) based on BC.js for others.

#### True Internet of Things
* Connect the Internet/Web with the objects in the real world via Bluetooth Javascript interface easily.

Usage
-----------------------------------
1. To use in BCSphere official APP

(1) Include bc.js and other profiles .js files in your own javascript file directly.

(2) Access the API.

2. To incorporate into your own APP

(1) Integrate [Apache Cordova](http://cordova.apache.org) / [PhoneGap](http://phonegap.com) into your Android/iOS project.

(2) Use this command to install bc.js as a plugin in your project:

    cordova plugin add https://github.com/bcsphere/bluetooth.git

Support platforms
-----------------------------------
For Bluetooth GATT
  * Android API 18+, All devices with Bluetooth 4.0 Low Energy HW
  * Android API 17+, Sumsung devices with Bluetooth 4.0 Low Energy HW
  * Android API 16+, HTC devices with Bluetooth Low Energy HW,
note: HTC use shared library to operate BLE device, you should add the 'com.htc.android.bluetooth.le.jar' in the build path manually to support HTC devices, the files is in /others/HTC for optional use.
  * IOS 6.0.1+,  iPhone4S+/iTouch5+/iPad3+/iPad-mini+/iPadAir

For Bluetooth 2.1 Classic
  * Android API 9+

Commercial Service
-----------------------------------
- Quick 1 solution for all platforms, with project schedule down to 1 week.
- For Bluetooth APPs customization service, please contact team@bcsphere.org.

[Version History & Roadmap](https://github.com/bcsphere/bluetooth/wiki/Version-History-&-Roadmap)


text:
package com.google.ads.googleads.v10.enums;

public interface ConversionAdjustmentTypeEnumOrBuilder extends
    // @@protoc_insertion_point(interface_extends:google.ads.googleads.v10.enums.ConversionAdjustmentTypeEnum)
    com.google.protobuf.MessageOrBuilder {
}


text:
package com.cirrus.persistence.service;

import com.cirrus.persistence.dao.meta.IMetaDataDAO;
import com.cirrus.persistence.dao.profile.IUserProfileDAO;
import com.mongodb.DB;

public interface IMongoDBService {

    //==================================================================================================================
    // Constants
    //==================================================================================================================
    final static String CIRRUS_DATABASE_NAME = "cirrus";
    final static String CIRRUS_META_DATA_COLLECTION = "cirrusMetaData";
    final static String CIRRUS_USER_PROFILE_COLLECTION = "cirrusUserProfile";

    /**
     * Returns the database provided by mongoDB service
     */
    DB getDatabase();

    /**
     * Returns the dao for cirrus meta data
     */
    IMetaDataDAO getMetaDataDAO();

    /**
     * Returns the dao for the user profile
     */
    IUserProfileDAO getUserProfileDAO();
}


text:
<!-- Jquery Core Js -->
    <script src="plugins/jquery/jquery.min.js"></script>

    <!-- Bootstrap Core Js -->
    <script src="plugins/bootstrap/js/bootstrap.js"></script>

    <!-- Select Plugin Js -->
    <script src="plugins/bootstrap-select/js/bootstrap-select.js"></script>

    <!-- Slimscroll Plugin Js -->
    <script src="plugins/jquery-slimscroll/jquery.slimscroll.js"></script>

    <!-- Waves Effect Plugin Js -->
    <script src="plugins/node-waves/waves.js"></script>

    <!-- Jquery DataTable Plugin Js -->
    <script src="plugins/jquery-datatable/jquery.dataTables.js"></script>
    <script src="plugins/jquery-datatable/skin/bootstrap/js/dataTables.bootstrap.js"></script>
    <script src="plugins/jquery-datatable/extensions/export/dataTables.buttons.min.js"></script>
    <script src="plugins/jquery-datatable/extensions/export/buttons.flash.min.js"></script>
    <script src="plugins/jquery-datatable/extensions/export/jszip.min.js"></script>
    <script src="plugins/jquery-datatable/extensions/export/pdfmake.min.js"></script>
    <script src="plugins/jquery-datatable/extensions/export/vfs_fonts.js"></script>
    <script src="plugins/jquery-datatable/extensions/export/buttons.html5.min.js"></script>
    <script src="plugins/jquery-datatable/extensions/export/buttons.print.min.js"></script>

    <!-- Autosize Plugin Js -->
    <script src="plugins/autosize/autosize.js"></script>

    <!-- Moment Plugin Js -->
    <script src="plugins/momentjs/moment.js"></script>

    <!-- Bootstrap Material Datetime Picker Plugin Js -->
    <script src="plugins/bootstrap-material-datetimepicker/js/bootstrap-material-datetimepicker.js"></script>

    <!-- Custom Js -->
    <script src="js/admin.js"></script>
    <script src="js/pages/forms/basic-form-elements.js"></script>
    <script src="js/pages/tables/jquery-datatable.js"></script>

    <!-- Demo Js -->
    <script src="js/demo.js"></script>


text:
package de.fun2code.android.piratebox.handler;

import sunlabs.brazil.server.Server;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import de.fun2code.android.piratebox.Constants;
import de.fun2code.android.piratebox.PirateBoxService;
import de.fun2code.android.piratebox.R;

/**
 * Wrapper class for the original PAW @{code PirateBoxFileHandler} to supper
 * the PirateBox {@literal domainName} preference
 *
 * @author joschi
 *
 */
public class PirateBoxFileHandler extends org.paw.handler.PirateBoxFileHandler {
	/*
	 *  Regular expression taken from:
	 *  http://www.mkyong.com/regular-expressions/domain-name-regular-expression-example/
	 */
	private static final String DOMAIN_NAME_PATTERN = "^[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$";

	@Override
	public boolean init(Server server, String prefix) {

		/*
		 * Do some sanity check
		 * If domain name is valid set the DOMAIN property
		 */
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(PirateBoxService.getService());
		String domain = prefs.getString(Constants.PREF_DOMAIN_NAME,
				PirateBoxService.getService().getResources().getString(R.string.pref_domain_name_default));

		if(domain.matches(DOMAIN_NAME_PATTERN)) {
			server.props.setProperty(prefix + DOMAIN, domain);
		}

		return super.init(server, prefix);
	}

}


text:
class SwiftMethod < SwiftEntityElement
end


text:
<?php

namespace Akamon\OAuth2\Server\Domain\Service\Token\RefreshTokenCreator;

use Akamon\OAuth2\Server\Domain\Model\RefreshToken\RefreshToken;
use Akamon\OAuth2\Server\Domain\Service\Token\TokenGenerator\TokenGeneratorInterface;
use felpado as f;

class RefreshTokenCreator implements RefreshTokenCreatorInterface
{
    private $tokenGenerator;
    private $lifetime;

    public function __construct(TokenGeneratorInterface $tokenGenerator, $params)
    {
        $this->tokenGenerator = $tokenGenerator;

        f\validate_coll_or_throw($params, ['lifetime' => f\required(['v' => 'is_int'])]);
        $this->lifetime = $params['lifetime'];
    }

    /**
     * @return \Akamon\OAuth2\Server\Domain\Model\RefreshToken\RefreshToken
     */
    public function create($accessTokenTokenToken)
    {
        return new RefreshToken([
            'token' => $this->tokenGenerator->generate(),
            'accessTokenToken' => $accessTokenTokenToken,
            'createdAt' => time(),
            'lifetime' => $this->lifetime
        ]);
    }
}


text:
	Utility functions involving binders and links. It's a common pattern to link
	back to a bound class. This allows you to quickly retrieve these objects.

	@class BoundLinkUtils
]=]

local require = require(script.Parent.loader).load(script)

local CollectionService = game:GetService("CollectionService")

local LinkUtils = require("LinkUtils")
local BinderUtils = require("BinderUtils")

local BoundLinkUtils = {}

--[=[
	Gets a linked object from the current instance.

	@param binder Binder<T>
	@param linkName string
	@param from Instance
	@return T?
]=]
function BoundLinkUtils.getLinkClass(binder, linkName, from)
	assert(type(binder) == "table", "Bad binder")
	assert(type(linkName) == "string", "Bad linkName")
	assert(typeof(from) == "Instance", "Bad froM")

	local linkValue = LinkUtils.getLinkValue(linkName, from)
	if not linkValue then
		return nil
	end

	return binder:Get(linkValue)
end

--[=[
	Gets a linked objects from the current instance.

	@param binder Binder<T>
	@param linkName string
	@param from Instance
	@return { T }
]=]
function BoundLinkUtils.getLinkClasses(binder, linkName, from)
	assert(type(binder) == "table", "Bad binder")
	assert(type(linkName) == "string", "Bad linkName")
	assert(typeof(from) == "Instance", "Bad from")

	local classes = {}
	for _, value in pairs(LinkUtils.getAllLinkValues(linkName, from)) do
		local class = binder:Get(value)
		if class then
			table.insert(classes, class)
		end
	end
	return classes
end

--[=[
	Gets a linked objects from the current instance.

	@param binders { Binder<T> }
	@param linkName string
	@param from Instance
	@return { T }
]=]
function BoundLinkUtils.getClassesForLinkValues(binders, linkName, from)
	assert(type(binders) == "table", "Bad binders")
	assert(type(linkName) == "string", "Bad linkName")
	assert(typeof(from) == "Instance", "Bad from")

	if not next(binders) then
		return {}
	end

	local tags = BinderUtils.mapBinderListToTable(binders)
	local classes = {}

	for _, instance in pairs(LinkUtils.getAllLinkValues(linkName, from)) do
		for _, tag in pairs(CollectionService:GetTags(instance)) do
			local binder = tags[tag]
			if binder then
				local obj = binder:Get(instance)
				if obj then
					table.insert(classes, obj)
				end
			end
		end
	end

	return classes
end

--[=[
	Calls a method on the binders

	@param binders { Binder<T> }
	@param linkName string
	@param from Instance
	@param methodName string
	@param args {}
]=]
function BoundLinkUtils.callMethodOnLinkedClasses(binders, linkName, from, methodName, args)
	assert(type(binders) == "table", "Bad arg 'binders'")
	assert(type(linkName) == "string", "Bad arg 'linkName'")
	assert(typeof(from) == "Instance", "Bad arg 'from'")
	assert(type(methodName) == "string", "Bad arg 'methodName'")
	assert(type(args) == "table", "Bad arg 'args'")

	if not next(binders) then
		return
	end

	local tags = BinderUtils.mapBinderListToTable(binders)

	local called = {}

	local function callForTag(value, tag)
		local binder = tags[tag]
		if not binder then
			return
		end

		local class = binder:Get(value)
		if not class then
			return
		end

		if not class[methodName] then
			return
		end

		if called[class] then
			warn(("[BoundLinkUtils.callMethodOnLinkedClasses] - Double-linked class %q for method %q"):format(tag, methodName))
			return
		end

		called[class] = true
		class[methodName](class, unpack(args))
	end

	for _, value in pairs(LinkUtils.getAllLinkValues(linkName, from)) do
		for _, tag in pairs(CollectionService:GetTags(value)) do
			callForTag(value, tag)
		end
	end
end

return BoundLinkUtils


text:
<?php

/**
 * @file
 * Definition of Drupal\Core\Template\AttributeArray.
 */

namespace Drupal\Core\Template;

use Drupal\Component\Utility\String;

/**
 * A class that defines a type of Attribute that can be added to as an array.
 *
 * To use with Attribute, the array must be specified.
 * Correct:
 * @code
 *  $attributes = new Attribute(array());
 *  $attributes['class'] = array();
 *  $attributes['class'][] = 'cat';
 * @endcode
 * Incorrect:
 * @code
 *  $attributes = new Attribute(array());
 *  $attributes['class'][] = 'cat';
 * @endcode
 *
 * @see Drupal\Core\Template\Attribute
 */
class AttributeArray extends AttributeValueBase implements \ArrayAccess, \IteratorAggregate {

  /**
   * Implements ArrayAccess::offsetGet().
   */
  public function offsetGet($offset) {
    return $this->value[$offset];
  }

  /**
   * Implements ArrayAccess::offsetSet().
   */
  public function offsetSet($offset, $value) {
    if (isset($offset)) {
      $this->value[$offset] = $value;
    }
    else {
      $this->value[] = $value;
    }
  }

  /**
   * Implements ArrayAccess::offsetUnset().
   */
  public function offsetUnset($offset) {
    unset($this->value[$offset]);
  }

  /**
   * Implements ArrayAccess::offsetExists().
   */
  public function offsetExists($offset) {
    return isset($this->value[$offset]);
  }

  /**
   * Implements the magic __toString() method.
   */
  public function __toString() {
    $this->printed = TRUE;
    return implode(' ', array_map(array('Drupal\Component\Utility\String', 'checkPlain'), $this->value));
  }

  /**
   * Implements IteratorAggregate::getIterator().
   */
  public function getIterator() {
    return new \ArrayIterator($this->value);
  }

  /**
   * Returns the whole array.
   */
  public function value() {
    return $this->value;
  }

}


text:
package cromwell.backend.standard

import cromwell.backend.BackendInitializationData
import cromwell.backend.io.{JobPaths, WorkflowPaths}

class StandardInitializationData
(
  val workflowPaths: WorkflowPaths,
  val runtimeAttributesBuilder: StandardValidatedRuntimeAttributesBuilder,
  val standardExpressionFunctionsClass: Class[_ <: StandardExpressionFunctions]
) extends BackendInitializationData {

  /* TODO: This could (should?) be monadic instead of reflection. */
  private lazy val standardExpressionFunctionsConstructor =
    standardExpressionFunctionsClass.getConstructor(classOf[StandardExpressionFunctionsParams])

  def expressionFunctions(jobPaths: JobPaths): StandardExpressionFunctions = {
    val pathBuilders = jobPaths.workflowPaths.pathBuilders
    val callContext = jobPaths.callContext
    val standardParams = DefaultStandardExpressionFunctionsParams(pathBuilders, callContext)
    standardExpressionFunctionsConstructor.newInstance(standardParams)
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ *************************************************************** ~
  ~ * This file is subject to the terms and conditions defined in * ~
  ~ * file 'LICENSE', which is part of this source code package.  * ~
  ~ *************************************************************** ~
  -->
<nine-patch xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/abc_list_section_divider_mtrl_alpha"
    android:alpha="0.12" />


text:
namespace media {

// A MIDIManagerClient registers with the MIDIManager to receive MIDI data.
// See MIDIManager::RequestAccess() and MIDIManager::ReleaseAccess()
// for details.
class MEDIA_EXPORT MIDIManagerClient {
 public:
   virtual ~MIDIManagerClient() {}

  // ReceiveMIDIData() is called when MIDI data has been received from the
  // MIDI system.
  // |port_index| represents the specific input port from input_ports().
  // |data| represents a series of bytes encoding one or more MIDI messages.
  // |length| is the number of bytes in |data|.
  // |timestamp| is the time the data was received, in seconds.
  virtual void ReceiveMIDIData(int port_index,
                               const uint8* data,
                               size_t length,
                               double timestamp) = 0;
};

// Manages access to all MIDI hardware.
class MEDIA_EXPORT MIDIManager {
 public:
  enum AccessType {
    kNoSystemExclusive,
    kSystemExclusive
  };

  static MIDIManager* Create();

  MIDIManager();
  virtual ~MIDIManager();

  // A client calls RequestAccess() to receive and send MIDI data.
  // If access is approved, the MIDI system is lazily initialized
  // and the client is registered to receive MIDI data.
  // Returns |true| if access is approved.
  bool RequestAccess(MIDIManagerClient* client, int access);

  // A client calls ReleaseAccess() to stop receiving MIDI data.
  void ReleaseAccess(MIDIManagerClient* client);

  // SendMIDIData() sends one or more messages at the given time.
  // |port_index| represents the specific output port from output_ports().
  // |data| represents a series of bytes encoding one or more MIDI messages.
  // |length| is the number of bytes in |data|.
  // |timestamp| is the time to send the data, in seconds.
  virtual void SendMIDIData(int port_index,
                            const uint8* data,
                            size_t length,
                            double timestamp) = 0;

  // input_ports() is a list of MIDI ports for receiving MIDI data.
  // Each individual port in this list can be identified by its
  // integer index into this list.
  const MIDIPortInfoList& input_ports() { return input_ports_; }

  // output_ports() is a list of MIDI ports for sending MIDI data.
  // Each individual port in this list can be identified by its
  // integer index into this list.
  const MIDIPortInfoList& output_ports() { return output_ports_; }

 protected:
  // Initializes the MIDI system, returning |true| on success.
  virtual bool Initialize() = 0;

  void AddInputPort(const MIDIPortInfo& info);
  void AddOutputPort(const MIDIPortInfo& info);

  // Dispatches to all clients.
  void ReceiveMIDIData(
      int port_index,
      const uint8* data,
      size_t length,
      double timestamp);

  bool initialized_;

  // Keeps track of all clients who wish to receive MIDI data.
  typedef std::set<MIDIManagerClient*> ClientList;
  ClientList clients_;

  // Protects access to our clients.
  base::Lock clients_lock_;

  MIDIPortInfoList input_ports_;
  MIDIPortInfoList output_ports_;

  DISALLOW_COPY_AND_ASSIGN(MIDIManager);
};

}  // namespace media

#endif  // MEDIA_MIDI_MIDI_MANAGER_H_


text:
layout: dynamic_navbar_footer
title: Home
permalink: /
---

Land registry digital service home


text:
from rl_coach.agents.actor_critic_agent import ActorCriticAgentParameters
from rl_coach.agents.policy_optimization_agent import PolicyGradientRescaler
from rl_coach.base_parameters import VisualizationParameters, PresetValidationParameters
from rl_coach.core_types import TrainingSteps, EnvironmentEpisodes, EnvironmentSteps
from rl_coach.environments.gym_environment import GymVectorEnvironment
from rl_coach.filters.filter import InputFilter
from rl_coach.filters.reward.reward_rescale_filter import RewardRescaleFilter
from rl_coach.graph_managers.basic_rl_graph_manager import BasicRLGraphManager
from rl_coach.graph_managers.graph_manager import ScheduleParameters

####################
# Graph Scheduling #
####################
schedule_params = ScheduleParameters()
schedule_params.improve_steps = TrainingSteps(10000000000)
schedule_params.steps_between_evaluation_periods = EnvironmentEpisodes(10)
schedule_params.evaluation_steps = EnvironmentEpisodes(1)
schedule_params.heatup_steps = EnvironmentSteps(0)

#########
# Agent #
#########
agent_params = ActorCriticAgentParameters()

agent_params.algorithm.policy_gradient_rescaler = PolicyGradientRescaler.GAE
agent_params.algorithm.discount = 0.99
agent_params.algorithm.apply_gradients_every_x_episodes = 1
agent_params.algorithm.num_steps_between_gradient_updates = 5
agent_params.algorithm.gae_lambda = 1
agent_params.algorithm.beta_entropy = 0.01

agent_params.network_wrappers['main'].optimizer_type = 'Adam'
agent_params.network_wrappers['main'].learning_rate = 0.0001

agent_params.input_filter = InputFilter()
agent_params.input_filter.add_reward_filter('rescale', RewardRescaleFilter(1/200.))

###############
# Environment #
###############
env_params = GymVectorEnvironment(level='CartPole-v0')

########
# Test #
########
preset_validation_params = PresetValidationParameters()
preset_validation_params.test = True
preset_validation_params.min_reward_threshold = 150
preset_validation_params.max_episodes_to_achieve_reward = 300
preset_validation_params.num_workers = 8

graph_manager = BasicRLGraphManager(agent_params=agent_params, env_params=env_params,
                                    schedule_params=schedule_params, vis_params=VisualizationParameters(),
                                    preset_validation_params=preset_validation_params)


text:
.. Copyright (C) 2004-2008 The Trustees of Indiana University.
   Use, modification and distribution is subject to the Boost Software
   License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
   http://www.boost.org/LICENSE_1_0.txt)

================================
|Logo| Concept Distributed Graph
================================

.. contents::

Description
-----------

A Distributed Graph is a graph whose vertices or edges are
distributed across multiple processes or address spaces. The
descriptors of a Distributed Graph must model the `Global
Descriptor`_ concept.

Notation
--------

G
  A type that models the Distributed Graph concept.

Refinement of
-------------

  - Graph_

Associated types
----------------

+----------------+---------------------------------------+---------------------------------+
|Vertex          |``graph_traits<G>::vertex_descriptor`` |Must model the                   |
|descriptor type |                                       |`Global Descriptor`_ concept.    |
+----------------+---------------------------------------+---------------------------------+
|Edge            |``graph_traits<G>::edge_descriptor``   |Must model the                   |
|descriptor type |                                       |`Global Descriptor`_ concept.    |
+----------------+---------------------------------------+---------------------------------+

Models
------

  - `Distributed adjacency list`_

-----------------------------------------------------------------------------

Copyright (C) 2005 The Trustees of Indiana University.

Authors: Douglas Gregor and Andrew Lumsdaine

.. |Logo| image:: pbgl-logo.png
            :align: middle
            :alt: Parallel BGL
            :target: http://www.osl.iu.edu/research/pbgl

.. _Graph: http://www.boost.org/libs/graph/doc/Graph.html
.. _Global descriptor: GlobalDescriptor.html
.. _Distributed adjacency list: distributed_adjacency_list.html


text:
require 'redmine_contacts/helpers/contacts_helper'
require 'redmine_contacts/helpers/crm_calendar_helper'

# Plugins
require 'acts_as_viewable/init'
require 'acts_as_priceable/init'

require_dependency 'redmine_contacts/utils/thumbnail'
require_dependency 'redmine_contacts/utils/check_mail'
require_dependency 'redmine_contacts/utils/date_utils'
require_dependency 'redmine_contacts/utils/csv_utils'
require_dependency 'redmine_contacts/contacts_project_setting'

# Patches
require_dependency 'redmine_contacts/patches/compatibility/active_record_base_patch'
require_dependency 'redmine_contacts/patches/compatibility/active_record_sanitization_patch.rb'
require_dependency 'redmine_contacts/patches/compatibility/user_patch.rb'
require_dependency 'redmine_contacts/patches/compatibility_patch'
require_dependency 'redmine_contacts/patches/issue_patch'
require_dependency 'redmine_contacts/patches/project_patch'
require_dependency 'redmine_contacts/patches/mailer_patch'
require_dependency 'redmine_contacts/patches/notifiable_patch'
require_dependency 'redmine_contacts/patches/application_controller_patch'
require_dependency 'redmine_contacts/patches/attachments_controller_patch'
require_dependency 'redmine_contacts/patches/auto_completes_controller_patch'
require_dependency 'redmine_contacts/patches/issue_query_patch'
require_dependency 'redmine_contacts/patches/queries_helper_patch'
require_dependency 'redmine_contacts/patches/timelog_helper_patch'
require_dependency 'redmine_contacts/patches/projects_helper_patch'

require_dependency 'redmine_contacts/wiki_macros/contacts_wiki_macros'

# Hooks
require_dependency 'redmine_contacts/hooks/views_projects_hook'
require_dependency 'redmine_contacts/hooks/views_issues_hook'
require_dependency 'redmine_contacts/hooks/views_layouts_hook'

require 'redmine_contacts/liquid/liquid' if Object.const_defined?("Liquid") rescue false

module RedmineContacts

  def self.companies_select
  	RedmineContacts.settings["select_companies_to_deal"]
  end

  def self.settings() Setting[:plugin_redmine_contacts].blank? ? {} : Setting[:plugin_redmine_contacts]  end

  def self.default_list_style
    return 'list_excerpt'
  end

end


text:
import {IAnnotatedImageData, ImageData} from '../image-data'
import {SharpImage} from '../sharp-image'
import {Colorspace, IBlock, ISaliencyOptions} from '../types'
import * as tf from '@tensorflow/tfjs-node'

const SIGMAC = 16

type IBlockWithSaliency = IBlock & {saliency: number; contrast: number}

interface IColorData {
  pixel: [number, number, number]
  count: number
  saliency: {overall: number; contrast: number; positional: number}
  x: number
  y: number
  width: number
  height: number
  _mx: number
  _Vx: number
  _my: number
  _Vy: number
  __coordinates: number[]
  __xSum: number
  __ySum: number
  __xSumOfSquares: number
  __ySumOfSquares: number
  __countWeightedColorDistance: number
  __exponentialXWeightedColorDistance: number
  __exponentialYWeightedColorDistance: number
  __exponentialXVarianceWeightedColorDistance: number
  __exponentialYVarianceWeightedColorDistance: number
  __exponentialCountWeightedColorDistance: number
}

function runMedianCut(
  pixels: Array<[number, number, number]>,
): [Array<[number, number, number]>, Array<[number, number, number]>] {
  if (!pixels.length) return [[], []]

  const minPixel = [255, 255, 255]
  const maxPixel = [0, 0, 0]
  for (let i = 0; i < pixels.length; i++) {
    minPixel[0] = Math.min(pixels[i][0], minPixel[0])
    minPixel[1] = Math.min(pixels[i][1], minPixel[1])
    minPixel[2] = Math.min(pixels[i][2], minPixel[2])
    maxPixel[0] = Math.max(pixels[i][0], maxPixel[0])
    maxPixel[1] = Math.max(pixels[i][1], maxPixel[1])
    maxPixel[2] = Math.max(pixels[i][2], maxPixel[2])
  }

  const ranges = maxPixel.map((x, i) => x - minPixel[i])
  const maxRangeIndex = ranges.indexOf(Math.max(...ranges))
  const sortedOnIndex = pixels.slice().sort((a, b) => a[maxRangeIndex] - b[maxRangeIndex])
  const medianIndex = Math.floor(sortedOnIndex.length / 2)
  const lowerBucket = sortedOnIndex.slice(0, medianIndex)
  const upperBucket = sortedOnIndex.slice(medianIndex)
  return [lowerBucket, upperBucket]
}

function computeCoordinateSum(nums: number[], start: number): number {
  let sum = 0
  for (let i = start; i < nums.length; i += 2) sum += nums[i]
  return sum
}
function computeCoordinateSumOfSquares(nums: number[], mean: number, start: number): number {
  let sum = 0
  for (let i = start; i < nums.length; i += 2) sum += (nums[i] - mean) ** 2
  return sum
}

function computeBucketAverage(bucket: Array<[number, number, number]>): [number, number, number] {
  const average: [number, number, number] = [0, 0, 0]
  for (const [r, g, b] of bucket) {
    average[0] += r
    average[1] += g
    average[2] += b
  }

  average[0] /= bucket.length
  average[1] /= bucket.length
  average[2] /= bucket.length

  return average
}

function getQuantizedColors(
  imageData: IAnnotatedImageData,
  targetCount: number,
): Array<[number, number, number]> {
  const primaryBucket: Array<[number, number, number]> = []
  for (let y = 0; y < imageData.height; y++) {
    for (let x = 0; x < imageData.width; x++) {
      const index = ImageData.indexFor(imageData, x, y)
      primaryBucket.push([
        imageData.data[index],
        imageData.data[index + 1],
        imageData.data[index + 2],
      ])
    }
  }

  let buckets = [primaryBucket]
  while (buckets.length < targetCount) {
    buckets = buckets.map(bucket => runMedianCut(bucket)).reduce((a, b) => a.concat(b), [] as any[])
  }

  const averagedBuckets = buckets.map(computeBucketAverage)
  return averagedBuckets
}

function pixelDifference(
  pixelA: [number, number, number],
  pixelB: [number, number, number],
): number {
  return (pixelA[0] - pixelB[0]) ** 2 + (pixelA[1] - pixelB[1]) ** 2 + (pixelA[2] - pixelB[2]) ** 2
}

function getClosestQuantizedColor(
  colors: IColorData[],
  pixel: [number, number, number],
): {color: [number, number, number]; colorIndex: number} {
  let minIndex = 0
  let minValue = Infinity
  for (let i = 0; i < colors.length; i++) {
    const distance = pixelDifference(pixel, colors[i].pixel)
    if (distance < minValue) {
      minIndex = i
      minValue = distance
    }
  }

  return {color: colors[minIndex].pixel, colorIndex: minIndex}
}

function computeColorData(colors: IColorData[]): void {
  for (const color of colors) {
    color.__xSum = computeCoordinateSum(color.__coordinates, 0)
    color.__ySum = computeCoordinateSum(color.__coordinates, 1)
  }

  for (const color of colors) {
    for (const otherColor of colors) {
      const colorDifference = pixelDifference(color.pixel, otherColor.pixel)
      const colorDistance = Math.sqrt(colorDifference)

      // Weighted color distance, used for global color contrast
      color.__countWeightedColorDistance += otherColor.count * colorDistance

      // Exponential color difference, used in size and position calculations
      const exponentialColorDifference = Math.exp(-colorDifference / (2 * SIGMAC))

      color.__exponentialXWeightedColorDistance += exponentialColorDifference * otherColor.__xSum
      color.__exponentialYWeightedColorDistance += exponentialColorDifference * otherColor.__ySum
      color.__exponentialCountWeightedColorDistance += otherColor.count * exponentialColorDifference
    }

    color._mx =
      color.__exponentialXWeightedColorDistance / color.__exponentialCountWeightedColorDistance
    color._my =
      color.__exponentialYWeightedColorDistance / color.__exponentialCountWeightedColorDistance
  }

  for (const color of colors) {
    color.__xSumOfSquares = computeCoordinateSumOfSquares(color.__coordinates, color._mx, 0)
    color.__ySumOfSquares = computeCoordinateSumOfSquares(color.__coordinates, color._my, 1)
  }

  for (const color of colors) {
    for (const otherColor of colors) {
      const colorDifference = pixelDifference(color.pixel, otherColor.pixel)
      const exponentialColorDifference = Math.exp(-colorDifference / (2 * SIGMAC))

      color.__exponentialXVarianceWeightedColorDistance +=
        exponentialColorDifference * otherColor.__xSumOfSquares
      color.__exponentialYVarianceWeightedColorDistance +=
        exponentialColorDifference * otherColor.__ySumOfSquares
    }

    color._Vx =
      color.__exponentialXVarianceWeightedColorDistance /
      color.__exponentialCountWeightedColorDistance
    color._Vy =
      color.__exponentialYVarianceWeightedColorDistance /
      color.__exponentialCountWeightedColorDistance
  }
}

function normalizeColorData(imageData: IAnnotatedImageData, colors: IColorData[]): void {
  const colorDistances = colors.map(c => c.__countWeightedColorDistance)
  const maxDistance = Math.max(...colorDistances)
  const minDistance = Math.min(...colorDistances)

  // Size and probability constants.
  const meanVector = tf.tensor([0.5555, 0.6449, 0.0002, 0.0063])
  const covarianceMatrix = tf.tensor([
    [43.3777, 1.7633, -0.4059, 1.0997],
    [1.7633, 40.7221, -0.0165, 0.0447],
    [-0.4059, -0.0165, 87.0455, -3.2744],
    [1.0997, 0.0447, -3.2744, 125.1503],
  ])

  for (const color of colors) {
    const contrastOutOf1 =
      (color.__countWeightedColorDistance - minDistance) / (maxDistance - minDistance + 0.0001)
    color.saliency.contrast = contrastOutOf1

    const centerX = color._mx / imageData.width
    const centerY = color._my / imageData.height
    const width = Math.sqrt(color._Vx * 12) / imageData.width
    const height = Math.sqrt(color._Vy * 12) / imageData.height

    const shapeVector = tf.tensor([width, height, centerX - 0.5, centerY - 0.5])
    const X = shapeVector.transpose().sub(meanVector)
    const Y = X
    const A = covarianceMatrix
    const result = X.dot(A)
      .mul(Y)
      .sum(0)
      .dataSync()

    color.x = clip01(centerX - width / 2)
    color.y = clip01(centerY - height / 2)
    color.width = clip01(centerX + width / 2 - color.x)
    color.height = clip01(centerY + height / 2 - color.y)
    color.saliency.positional = Math.exp(-result[0] / 2)
  }

  const sizeProbability = colors.map(c => c.saliency.positional)
  const minProbability = Math.min(...sizeProbability)
  const maxProbability = Math.max(...sizeProbability, 0.5)
  for (const color of colors) {
    const sizeProbability =
      (color.saliency.positional - minProbability) / (maxProbability - minProbability + 0.00001)
    color.saliency.positional = sizeProbability
    color.saliency.overall = Math.pow(
      color.saliency.contrast ** 3 * color.saliency.positional,
      1 / 4,
    )
  }

  const sizeSaliency = colors.map(c => c.saliency.overall)
  const minSaliency = Math.min(...sizeSaliency)
  const maxSaliency = Math.max(...sizeSaliency)
  for (const color of colors) {
    color.saliency.overall =
      (color.saliency.overall - minSaliency) / (maxSaliency - minSaliency + 0.00001)
  }
}

function initializeColorData(pixel: [number, number, number]): IColorData {
  return {
    pixel,
    count: 0,
    saliency: {overall: 0, contrast: 0, positional: 0},
    x: 0,
    y: 0,
    width: 0,
    height: 0,
    __xSum: 0,
    __ySum: 0,
    __xSumOfSquares: 0,
    __ySumOfSquares: 0,
    __countWeightedColorDistance: 0,
    __exponentialXWeightedColorDistance: 0,
    __exponentialYWeightedColorDistance: 0,
    __exponentialXVarianceWeightedColorDistance: 0,
    __exponentialYVarianceWeightedColorDistance: 0,
    __exponentialCountWeightedColorDistance: 0,
    __coordinates: [],
    _mx: 0,
    _Vx: 0,
    _my: 0,
    _Vy: 0,
  }
}

/**
 * This method quantizes the image and precomputes some useful data per color.
 *
 *    1. Create histograms and find the quantized colors using median cuts.
 *    2. For all pixels...
 *          - Replace it with the quantized version.
 *          - Keep track of the correct quantized color index.
 *          - Compute the average x/y for each color (weighted by similarity to other colors by distance).
 *    3. Do one more pass over the pixels to compute x/y variance.
 *    4. For all quantized colors...
 *          - Compute color distance.
 *          - Compute exponential color distance.
 *          - Compute weighted exponential color distance.
 *          - Compute weighted color distance (global color contrast).
 */
function precomputeColorData(
  unquantizedImageData: IAnnotatedImageData,
  quantiles: number,
): {
  imageData: IAnnotatedImageData
  colors: IColorData[]
  colorIndexes: Uint8Array
} {
  const colors = getQuantizedColors(unquantizedImageData, quantiles).map(initializeColorData)
  const imageData = {...unquantizedImageData, data: new Uint8Array(unquantizedImageData.data)}
  const colorIndexes = new Uint8Array(imageData.width * imageData.height)

  let i = 0
  for (let y = 0; y < imageData.height; y++) {
    for (let x = 0; x < imageData.width; x++) {
      const index = ImageData.indexFor(unquantizedImageData, x, y)
      const {color: quantized, colorIndex} = getClosestQuantizedColor(colors, [
        imageData.data[index + 0],
        imageData.data[index + 1],
        imageData.data[index + 2],
      ])
      colors[colorIndex].count++
      colors[colorIndex].__coordinates.push(x, y)
      colorIndexes[i] = colorIndex
      imageData.data[index + 0] = quantized[0]
      imageData.data[index + 1] = quantized[1]
      imageData.data[index + 2] = quantized[2]
      i++
    }
  }

  computeColorData(colors)
  normalizeColorData(imageData, colors)

  return {
    colors,
    colorIndexes,
    imageData,
  }
}

function clip01(x: number): number {
  if (x > 1) return 1
  if (x < 0) return 0
  return x
}

function createSaliencyMaps(
  imageData: IAnnotatedImageData,
  colors: IColorData[],
  colorIndexes: Uint8Array,
): {
  imageData: IAnnotatedImageData
  contrastImageData: IAnnotatedImageData
  positionImageData: IAnnotatedImageData
} {
  const saliencyMap = {
    ...imageData,
    channels: 1,
    colorspace: Colorspace.Greyscale,
    data: new Uint8Array(colorIndexes.length),
  }
  const contrastImageData = {
    ...imageData,
    channels: 1,
    colorspace: Colorspace.Greyscale,
    data: new Uint8Array(colorIndexes.length),
  }
  const positionImageData = {
    ...imageData,
    channels: 1,
    colorspace: Colorspace.Greyscale,
    data: new Uint8Array(colorIndexes.length),
  }

  for (let i = 0; i < colorIndexes.length; i++) {
    const color = colors[colorIndexes[i]]
    saliencyMap.data[i] = Math.round(color.saliency.overall * 255)
    contrastImageData.data[i] = Math.round(color.saliency.contrast * 255)
    positionImageData.data[i] = Math.round(color.saliency.positional * 255)
  }

  return {imageData: saliencyMap, contrastImageData, positionImageData}
}

/**
 * This version is inspired by the methods used by FASA (Fast, Accurate, and Size-Aware Salient Object Detection).
 * Here's the general idea.
 *
 *    1. Quantize the image into a much smaller colorspace (64 colors)
 *    2. For each quantized color, compute the centroid, x-variance, and y-variance.
 *       This provides center coordinates and a rough width/height for each color.
 *    3. Using the location and size, compute the saliency probability of each quantized block
 *       using the pixel-weighted gaussian distribution values.
 *    4. For each quantized color, compute a global color contrast value.
 *    5. Combine the probability using saliency from location/size and global color contrast.
 *
 * IDEA: We can do better than 1 box per quantized color, add some tests and logic for k-means clustering.
 *       If the *density* of a quanitzed color is low, try k+1 centroids and recheck density.
 *       If density does not improve much, stick with k centroids, otherwise repeat.
 *
 * @see https://github.com/mpatacchiola/deepgaze/blob/fddc129da9692d7a2002d0df5baf142eae3b722b/deepgaze/saliency_map.py
 * @see https://projet.liris.cnrs.fr/imagine/pub/proceedings/ACCV-2014/pages/PDF/544.pdf
 * @see https://www.epfl.ch/labs/ivrl/research/saliency/fast-saliency/
 */
export async function saliency(
  imageData: IAnnotatedImageData,
  options: ISaliencyOptions = {},
): Promise<{
  imageData: IAnnotatedImageData
  quantized: IAnnotatedImageData
  contrastImageData: IAnnotatedImageData
  positionImageData: IAnnotatedImageData
  blocks: IBlockWithSaliency[]
}> {
  const {quantizeBuckets = 64, saliencyMode = 'map'} = options
  const normalized = await SharpImage.toImageData(
    SharpImage.from(imageData)
      .resize(400, 400, {fit: 'inside'})
      .normalize(),
  )

  const {imageData: quantized, colors, colorIndexes} = precomputeColorData(
    {...normalized, data: new Uint8Array(normalized.data)},
    quantizeBuckets,
  )
  ImageData.assert(quantized, [Colorspace.RGB])

  const totalPixels = normalized.width * normalized.height
  const blocks: IBlockWithSaliency[] = colors.map(color => ({
    count: color.count / totalPixels,
    x: color.x,
    y: color.y,
    width: color.width,
    height: color.height,
    r: color.pixel[0],
    g: color.pixel[1],
    b: color.pixel[2],
    saliency: color.saliency.overall,
    contrast: color.saliency.contrast,
  }))

  const returnValue = {
    imageData,
    quantized,
    contrastImageData: imageData,
    positionImageData: imageData,
    blocks,
  }

  if (saliencyMode === 'analysis') return returnValue

  Object.assign(returnValue, createSaliencyMaps(quantized, colors, colorIndexes))

  const blurredSaliency = await SharpImage.toImageData(
    SharpImage.from(returnValue.imageData).blur(1),
  )

  const thresholdSaliency = ImageData.mapPixels(blurredSaliency, pixel =>
    pixel.values[0] < 96 ? [0, 0, 0] : pixel.values,
  )

  return {
    ...returnValue,
    imageData: thresholdSaliency,
  }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Contract extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('task_model');
        $this->load->model('offer_model');
        $this->load->model('contract_model');
        $this->load->model('status_model');
    }

	public function index() {
        if (!$this->session->userdata('logged_in')) {
            redirect('login', 'refresh');
            return;
        }

        $session_data = $this->session->userdata('logged_in');

        if ($session_data['user_role'] != ROLE_ADMIN) {
            redirect('home', 'refresh');
            return;
        }

        $data['username'] = $session_data['username'];
        $data['user_id'] = $session_data['user_id'];

        $data['contracts'] = $this->contract_model->get_all_contracts();

        $data['header'] = 'All Contracts';
        $data['page_title'] = 'All Contracts';
        $data['view'] = 'admin/contract/contract_view';
        $this->load->view('admin/application_view', $data);
	}

    public function create() {
        if (!$this->session->userdata('logged_in')) {
            redirect('login', 'refresh');
            return;
        }

        $session_data = $this->session->userdata('logged_in');

        if ($session_data['user_role'] != ROLE_ADMIN) {
            redirect('home', 'refresh');
            return;
        }

        $data['username'] = $session_data['username'];
        $data['user_id'] = $session_data['user_id'];

        // get tasks
        $all_tasks = $this->task_model->get_all_tasks();
        $all_task_titles = [];
        foreach($all_tasks as $row) {
            $all_task_titles[$row['id']] = $row['title'];
        }
        $data['all_task_titles'] = $all_task_titles;

        // get offers
        $all_offers = $this->offer_model->get_all_offers();
        $all_offers_options = [];
        foreach($all_offers as $row) {
            $all_offers_options[$row['offer_id']] = '['.$row['offer_id'].']: ('.$row['offer_creator'].', $'.$row['offer_price'].') => ('.$row['task_creator'].', '.$row['title'].')';
        }
        $data['all_offers_options'] = $all_offers_options;

        // completion status
        $data['completion_status_options'] = array_merge([''=>'Please Select'], $this->status_model->get_all_statuses());

        $data['header'] = 'Create Contract';
        $data['page_title'] = 'Create Contract';
        $data['view'] = 'admin/contract/contract_create_view';
        $this->load->view('admin/application_view', $data);
    }

    public function update($contract_id = -1) {
        if (!$this->session->userdata('logged_in')) {
            redirect('login', 'refresh');
            return;
        }

        $session_data = $this->session->userdata('logged_in');

        if ($session_data['user_role'] != ROLE_ADMIN) {
            redirect('home', 'refresh');
            return;
        }

        $data['username'] = $session_data['username'];
        $data['user_id'] = $session_data['user_id'];

        if (!$data['contract'] = $this->contract_model->get_contract_by_id($contract_id)) {
            redirect('admin/contract', 'refresh');
            return;
        }

        // get tasks
        $all_tasks = $this->task_model->get_all_tasks();
        $all_task_titles = [];
        foreach($all_tasks as $row) {
            $all_task_titles[$row['id']] = $row['title'];
        }
        $data['all_task_titles'] = $all_task_titles;

        // get offers
        $all_offers = $this->offer_model->get_all_offers();
        $all_offers_options = [];
        foreach($all_offers as $row) {
            $all_offers_options[$row['offer_id']] = '['.$row['offer_id'].']: ('.$row['offer_creator'].', $'.$row['offer_price'].') => ('.$row['task_creator'].', '.$row['title'].')';
        }
        $data['all_offers_options'] = $all_offers_options;

        // completion status
        $data['completion_status_options'] = $this->status_model->get_all_statuses();

        $data['header'] = 'Create Contract';
        $data['page_title'] = 'Create Contract';
        $data['view'] = 'admin/contract/contract_update_view';
        $this->load->view('admin/application_view', $data);
    }

    public function delete($contract_id = -1) {
        if (!$this->session->userdata('logged_in')) {
            redirect('login', 'refresh');
            return;
        }

        $session_data = $this->session->userdata('logged_in');
        $user_id = $session_data['user_id'];

        if ($this->contract_model->delete_admin($contract_id)) {
            $this->success('deleted');
        } else {
            $this->failure('deleted');
        }
    }

    public function validate() {
        if (!$this->session->userdata('logged_in')) {
            redirect('login', 'refresh');
            return;
        }

        $session_data = $this->session->userdata('logged_in');

        if ($session_data['user_role'] != ROLE_ADMIN) {
            redirect('home', 'refresh');
            return;
        }
        $task_id = $this->input->post('task_id');

        $this->form_validation->set_rules('task_id', 'Task', 'required');
        $this->form_validation->set_rules('offer_id', 'Offer', "required|callback_ensure_corresponding_offer[$task_id]");
        $this->form_validation->set_rules('completion_status', 'Completion Status', 'required');

        $this->form_validation->set_message('ensure_corresponding_offer','Selected offer is not created for the selected task!');

        if (!$this->form_validation->run()) {
            $this->create();
            return;
        }

        $offer_id = $this->input->post('offer_id');
        $completion_status = $this->input->post('completion_status');
        $employer_id = $this->task_model->get_creator_id($task_id);
        $employee_id = $this->offer_model->get_acceptee_id($offer_id);

        if ($this->contract_model->create($employer_id, $employee_id, $task_id, $offer_id, $completion_status)) {
            $this->task_model->close_task($task_id);
            $this->success("created");
        } else {
            $this->failure("created");
        }
    }

    public function validate_update() {
        if (!$this->session->userdata('logged_in')) {
            redirect('login', 'refresh');
            return;
        }

        $session_data = $this->session->userdata('logged_in');

        if ($session_data['user_role'] != ROLE_ADMIN) {
            redirect('home', 'refresh');
            return;
        }
        $contract_id = $this->input->post('contract_id');
        $task_id = $this->input->post('task_id');

        $this->form_validation->set_rules('task_id', 'Task', 'required');
        $this->form_validation->set_rules('offer_id', 'Offer', "required|callback_ensure_corresponding_offer[$task_id]");
        $this->form_validation->set_rules('completion_status', 'Completion Status', 'required');

        $this->form_validation->set_message('ensure_corresponding_offer','Selected offer is not created for the selected task!');

        if (!$this->form_validation->run()) {
            $this->update($contract_id);
            return;
        }

        $offer_id = $this->input->post('offer_id');
        $completion_status = $this->input->post('completion_status');
        $employer_id = $this->task_model->get_creator_id($task_id);
        $employee_id = $this->offer_model->get_acceptee_id($offer_id);

        if ($this->contract_model->update_admin($contract_id, $employer_id, $employee_id, $task_id, $offer_id, $completion_status)) {
            $this->success("updated");
        } else {
            $this->failure("updated");
        }
    }

    public function success($action = 'ACTION_PERFORMED') {
        if (!$this->session->userdata('logged_in')) {
            redirect('login', 'refresh');
            return;
        }

        $session_data = $this->session->userdata('logged_in');
        $data['username'] = $session_data['username'];
        $data['action_performed'] = $action;
        $data['view'] = 'admin/contract/contract_success_view';
        $this->load->view('admin/application_view', $data);
    }

    private function failure($action = 'ACTION_ATTEMPTED') {
        if (!$this->session->userdata('logged_in')) {
            redirect('login', 'refresh');
            return;
        }

        $session_data = $this->session->userdata('logged_in');
        $data['username'] = $session_data['username'];
        $data['action_attempted'] = $action;
        $data['view'] = 'admin/contract/contract_failure_view';
        $this->load->view('admin/application_view', $data);
    }

    // callback for contract validate
    public function ensure_corresponding_offer($offer_id, $task_id) {
        return $this->offer_model->is_offered_for_task($offer_id, $task_id);
    }
}
?>