text:
TEST (signature_checker, empty)
{
	nano::signature_checker checker (0);
	nano::signature_check_set check = { 0, nullptr, nullptr, nullptr, nullptr, nullptr };
	checker.verify (check);
}

TEST (signature_checker, bulk_single_thread)
{
	nano::keypair key;
	nano::state_block block (key.pub, 0, key.pub, 0, 0, key.prv, key.pub, 0);
	nano::signature_checker checker (0);
	std::vector<nano::uint256_union> hashes;
	size_t size (1000);
	hashes.reserve (size);
	std::vector<unsigned char const *> messages;
	messages.reserve (size);
	std::vector<size_t> lengths;
	lengths.reserve (size);
	std::vector<unsigned char const *> pub_keys;
	pub_keys.reserve (size);
	std::vector<unsigned char const *> signatures;
	signatures.reserve (size);
	std::vector<int> verifications;
	verifications.resize (size);
	for (auto i (0); i < size; ++i)
	{
		hashes.push_back (block.hash ());
		messages.push_back (hashes.back ().bytes.data ());
		lengths.push_back (sizeof (decltype (hashes)::value_type));
		pub_keys.push_back (block.hashables.account.bytes.data ());
		signatures.push_back (block.signature.bytes.data ());
	}
	nano::signature_check_set check = { size, messages.data (), lengths.data (), pub_keys.data (), signatures.data (), verifications.data () };
	checker.verify (check);
	bool all_valid = std::all_of (verifications.cbegin (), verifications.cend (), [](auto verification) { return verification == 1; });
	ASSERT_TRUE (all_valid);
}

TEST (signature_checker, many_multi_threaded)
{
	nano::signature_checker checker (4);

	auto signature_checker_work_func = [&checker]() {
		nano::keypair key;
		nano::state_block block (key.pub, 0, key.pub, 0, 0, key.prv, key.pub, 0);
		auto block_hash = block.hash ();

		nano::state_block invalid_block (key.pub, 0, key.pub, 0, 0, key.prv, key.pub, 0);
		invalid_block.signature.bytes[31] ^= 0x1;
		auto invalid_block_hash = block.hash ();

		constexpr auto num_check_sizes = 18;
		constexpr std::array<size_t, num_check_sizes> check_sizes{ 2048, 256, 1024, 1,
			4096, 512, 2050, 1024, 8092, 513, 17, 1024, 2047, 255, 513, 2049, 1025, 1023 };

		std::vector<nano::signature_check_set> signature_checker_sets;
		signature_checker_sets.reserve (num_check_sizes);

		// Create containers so everything is kept in scope while the threads work on the signature checks
		std::array<std::vector<unsigned char const *>, num_check_sizes> messages;
		std::array<std::vector<size_t>, num_check_sizes> lengths;
		std::array<std::vector<unsigned char const *>, num_check_sizes> pub_keys;
		std::array<std::vector<unsigned char const *>, num_check_sizes> signatures;
		std::array<std::vector<int>, num_check_sizes> verifications;

		// Populate all the signature check sets. The last one in each set is given an incorrect block signature.
		for (int i = 0; i < num_check_sizes; ++i)
		{
			auto check_size = check_sizes[i];
			ASSERT_GT (check_size, 0);
			auto last_signature_index = check_size - 1;

			messages[i].resize (check_size);
			std::fill (messages[i].begin (), messages[i].end (), block_hash.bytes.data ());
			messages[i][last_signature_index] = invalid_block_hash.bytes.data ();

			lengths[i].resize (check_size);
			std::fill (lengths[i].begin (), lengths[i].end (), sizeof (decltype (block_hash)));

			pub_keys[i].resize (check_size);
			std::fill (pub_keys[i].begin (), pub_keys[i].end (), block.hashables.account.bytes.data ());
			pub_keys[i][last_signature_index] = invalid_block.hashables.account.bytes.data ();

			signatures[i].resize (check_size);
			std::fill (signatures[i].begin (), signatures[i].end (), block.signature.bytes.data ());
			signatures[i][last_signature_index] = invalid_block.signature.bytes.data ();

			verifications[i].resize (check_size);

			signature_checker_sets.emplace_back (check_size, messages[i].data (), lengths[i].data (), pub_keys[i].data (), signatures[i].data (), verifications[i].data ());
			checker.verify (signature_checker_sets[i]);

			// Confirm all but last are valid
			auto all_valid = std::all_of (verifications[i].cbegin (), verifications[i].cend () - 1, [](auto verification) { return verification == 1; });
			ASSERT_TRUE (all_valid);
			ASSERT_EQ (verifications[i][last_signature_index], 0);
		}
	};

	std::thread signature_checker_thread1 (signature_checker_work_func);
	std::thread signature_checker_thread2 (signature_checker_work_func);

	signature_checker_thread1.join ();
	signature_checker_thread2.join ();
}

TEST (signature_checker, one)
{
	nano::signature_checker checker (0);

	auto verify_block = [&checker](auto & block, auto result) {
		std::vector<nano::uint256_union> hashes;
		std::vector<unsigned char const *> messages;
		std::vector<size_t> lengths;
		std::vector<unsigned char const *> pub_keys;
		std::vector<unsigned char const *> signatures;
		std::vector<int> verifications;
		size_t size (1);
		verifications.resize (size);
		for (auto i (0); i < size; ++i)
		{
			hashes.push_back (block.hash ());
			messages.push_back (hashes.back ().bytes.data ());
			lengths.push_back (sizeof (decltype (hashes)::value_type));
			pub_keys.push_back (block.hashables.account.bytes.data ());
			signatures.push_back (block.signature.bytes.data ());
		}
		nano::signature_check_set check = { size, messages.data (), lengths.data (), pub_keys.data (), signatures.data (), verifications.data () };
		checker.verify (check);
		ASSERT_EQ (verifications.front (), result);
	};

	nano::keypair key;
	nano::state_block block (key.pub, 0, key.pub, 0, 0, key.prv, key.pub, 0);

	// Make signaure invalid and check result is incorrect
	block.signature.bytes[31] ^= 0x1;
	verify_block (block, 0);

	// Make it valid and check for succcess
	block.signature.bytes[31] ^= 0x1;
	verify_block (block, 1);
}

TEST (signature_checker, boundary_checks)
{
	// sizes container must be in incrementing order
	std::vector<size_t> sizes{ 0, 1 };
	auto add_boundary = [&sizes](size_t boundary) {
		sizes.insert (sizes.end (), { boundary - 1, boundary, boundary + 1 });
	};

	for (auto i = 1; i <= 5; ++i)
	{
		add_boundary (nano::signature_checker::batch_size * i);
	}

	nano::signature_checker checker (1);
	auto max_size = *(sizes.end () - 1);
	std::vector<nano::uint256_union> hashes;
	hashes.reserve (max_size);
	std::vector<unsigned char const *> messages;
	messages.reserve (max_size);
	std::vector<size_t> lengths;
	lengths.reserve (max_size);
	std::vector<unsigned char const *> pub_keys;
	pub_keys.reserve (max_size);
	std::vector<unsigned char const *> signatures;
	signatures.reserve (max_size);
	nano::keypair key;
	nano::state_block block (key.pub, 0, key.pub, 0, 0, key.prv, key.pub, 0);

	auto last_size = 0;
	for (auto size : sizes)
	{
		// The size needed to append to existing containers, saves re-initializing from scratch each iteration
		auto extra_size = size - last_size;

		std::vector<int> verifications;
		verifications.resize (size);
		for (auto i (0); i < extra_size; ++i)
		{
			hashes.push_back (block.hash ());
			messages.push_back (hashes.back ().bytes.data ());
			lengths.push_back (sizeof (decltype (hashes)::value_type));
			pub_keys.push_back (block.hashables.account.bytes.data ());
			signatures.push_back (block.signature.bytes.data ());
		}
		nano::signature_check_set check = { size, messages.data (), lengths.data (), pub_keys.data (), signatures.data (), verifications.data () };
		checker.verify (check);
		bool all_valid = std::all_of (verifications.cbegin (), verifications.cend (), [](auto verification) { return verification == 1; });
		ASSERT_TRUE (all_valid);
		last_size = size;
	}
}


text:
  <form>

      <button type="button" class="close" data-dismiss="modal" aria-hidden="true" aria-label="Close" ng-click="cancel()">

      </button>

Confirm Delete

Are you sure you want to delete the {{typeDisplayName || (kind | humanizeKind)}}
        '{{displayName ? displayName : resourceName}}'?

          This will delete the deployment config, all rollout history, and any running pods.

          This will delete the deployment, all rollout history, and any running pods.

          This will delete the {{typeDisplayName || (kind | humanizeKind)}} and any running pods.

          {{displayName ? displayName : resourceName}} and its data will no longer be available to your applications.

          This will delete all resources associated with the
          project {{displayName ? displayName : resourceName}}.

        It cannot be undone. Make sure this is something you really want to do!

Type the name of the {{typeDisplayName || (kind | humanizeKind)}} to confirm.

          {{typeDisplayName || (kind | humanizeKind)}} to delete
          <input
              ng-model="confirmName"
              id="resource-to-delete"
              type="text"
              class="form-control input-lg"
              autocorrect="off"
              autocapitalize="none"
              spellcheck="false"
              autofocus>

          <input type="checkbox" ng-model="options.deleteImmediately">
          Delete pod immediately without waiting for the processes to terminate gracefully

 0">

            This resource has an autoscaler associated with it.
            It is recommended you delete the autoscaler with the resource it scales.

           1">
            This resource has autoscalers associated with it.
            It is recommended you delete the autoscalers with the resource they scale.

            <input type="checkbox" ng-model="options.deleteHPAs">
            Delete

              Horizontal Pod Autoscaler '{{hpaList[0].metadata.name}}'

             1">
              {{hpaList.length}} associated Horizontal Pod Autoscalers

      <button class="btn btn-default" type="button" ng-click="cancel();">Cancel</button>
      <button ng-disabled="typeNameToConfirm && confirmName !== resourceName && confirmName !== displayName" class="btn btn-danger" type="submit" ng-click="delete();">Delete</button>

  </form>

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) 2020, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "bin/dartdev_isolate.h"

#if !defined(DART_PRECOMPILED_RUNTIME)

#include <functional>
#include <memory>

#include "bin/directory.h"
#include "bin/error_exit.h"
#include "bin/exe_utils.h"
#include "bin/file.h"
#include "bin/lockers.h"
#include "bin/platform.h"
#include "bin/process.h"
#include "include/dart_embedder_api.h"
#include "platform/utils.h"

#define CHECK_RESULT(result)                                                   \
  if (Dart_IsError(result)) {                                                  \
    ProcessError(Dart_GetError(result), kErrorExitCode);                       \
    if (send_port_id != ILLEGAL_PORT) {                                        \
      Dart_CloseNativePort(send_port_id);                                      \
    }                                                                          \
    Dart_ExitScope();                                                          \
    Dart_ShutdownIsolate();                                                    \
    return;                                                                    \
  }

namespace dart {
namespace bin {

DartDevIsolate::DartDevRunner DartDevIsolate::runner_ =
    DartDevIsolate::DartDevRunner();
bool DartDevIsolate::should_run_dart_dev_ = false;
bool DartDevIsolate::print_usage_error_ = false;
Monitor* DartDevIsolate::DartDevRunner::monitor_ = new Monitor();
DartDevIsolate::DartDev_Result DartDevIsolate::DartDevRunner::result_ =
    DartDevIsolate::DartDev_Result_Unknown;
char** DartDevIsolate::DartDevRunner::script_ = nullptr;
char** DartDevIsolate::DartDevRunner::package_config_override_ = nullptr;
bool* DartDevIsolate::DartDevRunner::force_no_sound_null_safety_ = nullptr;
std::unique_ptr<char*[], void (*)(char*[])>
    DartDevIsolate::DartDevRunner::argv_ =
        std::unique_ptr<char*[], void (*)(char**)>(nullptr, [](char**) {});
intptr_t DartDevIsolate::DartDevRunner::argc_ = 0;

bool DartDevIsolate::ShouldParseCommand(const char* script_uri) {
  // If script_uri is not a file path or of a known URI scheme, we can assume
  // that this is a DartDev command.
  return (!File::ExistsUri(nullptr, script_uri) &&
          (strncmp(script_uri, "http://", 7) != 0) &&
          (strncmp(script_uri, "https://", 8) != 0) &&
          (strncmp(script_uri, "file://", 7) != 0) &&
          (strncmp(script_uri, "package:", 8) != 0) &&
          (strncmp(script_uri, "google3://", 10) != 0));
}

Utils::CStringUniquePtr DartDevIsolate::TryResolveArtifactPath(
    const char* filename) {
  // |dir_prefix| includes the last path separator.
  auto dir_prefix = EXEUtils::GetDirectoryPrefixFromExeName();

  // First assume we're in dart-sdk/bin.
  char* snapshot_path =
      Utils::SCreate("%ssnapshots/%s", dir_prefix.get(), filename);
  if (File::Exists(nullptr, snapshot_path)) {
    return Utils::CreateCStringUniquePtr(snapshot_path);
  }
  free(snapshot_path);

  // If we're not in dart-sdk/bin, we might be in one of the $SDK/out/*
  // directories. Try to use a snapshot from a previously built SDK.
  snapshot_path = Utils::SCreate("%s%s", dir_prefix.get(), filename);
  if (File::Exists(nullptr, snapshot_path)) {
    return Utils::CreateCStringUniquePtr(snapshot_path);
  }
  free(snapshot_path);
  return Utils::CreateCStringUniquePtr(nullptr);
}

Utils::CStringUniquePtr DartDevIsolate::TryResolveDartDevSnapshotPath() {
  return TryResolveArtifactPath("dartdev.dart.snapshot");
}

Utils::CStringUniquePtr DartDevIsolate::TryResolveDartDevKernelPath() {
  return TryResolveArtifactPath("dartdev.dill");
}

void DartDevIsolate::DartDevRunner::Run(
    Dart_IsolateGroupCreateCallback create_isolate,
    char** packages_file,
    char** script,
    bool* force_no_sound_null_safety,
    CommandLineOptions* dart_options) {
  create_isolate_ = create_isolate;
  dart_options_ = dart_options;
  package_config_override_ = packages_file;
  script_ = script;
  force_no_sound_null_safety_ = force_no_sound_null_safety;

  // We've encountered an error during preliminary argument parsing so we'll
  // output the standard help message and exit with an error code.
  if (print_usage_error_) {
    dart_options_->Reset();
    dart_options_->AddArgument("--help");
  }

  MonitorLocker locker(monitor_);
  int result = Thread::Start("DartDev Runner", RunCallback,
                             reinterpret_cast<uword>(this));
  if (result != 0) {
    FATAL1("Failed to start DartDev thread: %d", result);
  }
  monitor_->WaitMicros(Monitor::kNoTimeout);

  if (result_ == DartDevIsolate::DartDev_Result_Run) {
    // Clear the DartDev dart_options and replace them with the processed
    // options provided by DartDev.
    dart_options_->Reset();
    dart_options_->AddArguments(const_cast<const char**>(argv_.get()), argc_);
  }
}

static Dart_CObject* GetArrayItem(Dart_CObject* message, intptr_t index) {
  return message->value.as_array.values[index];
}

void DartDevIsolate::DartDevRunner::DartDevResultCallback(
    Dart_Port dest_port_id,
    Dart_CObject* message) {
  // These messages are produced in pkg/dartdev/lib/src/vm_interop_handler.dart.
  ASSERT(message->type == Dart_CObject_kArray);
  int32_t type = GetArrayItem(message, 0)->value.as_int32;
  switch (type) {
    case DartDevIsolate::DartDev_Result_Run: {
      result_ = DartDevIsolate::DartDev_Result_Run;
      ASSERT(GetArrayItem(message, 1)->type == Dart_CObject_kString);
      auto item2 = GetArrayItem(message, 2);

      ASSERT(item2->type == Dart_CObject_kString ||
             item2->type == Dart_CObject_kNull);

      auto item3 = GetArrayItem(message, 3);

      ASSERT(item3->type == Dart_CObject_kBool);

      if (*script_ != nullptr) {
        free(*script_);
      }
      if (*package_config_override_ != nullptr) {
        free(*package_config_override_);
        *package_config_override_ = nullptr;
      }
      *script_ = Utils::StrDup(GetArrayItem(message, 1)->value.as_string);

      if (item2->type == Dart_CObject_kString) {
        *package_config_override_ = Utils::StrDup(item2->value.as_string);
      }

      *force_no_sound_null_safety_ = item3->value.as_bool;

      ASSERT(GetArrayItem(message, 4)->type == Dart_CObject_kArray);
      Dart_CObject* args = GetArrayItem(message, 4);
      argc_ = args->value.as_array.length;
      Dart_CObject** dart_args = args->value.as_array.values;

      auto deleter = [](char** args) {
        for (intptr_t i = 0; i < argc_; ++i) {
          free(args[i]);
        }
        delete[] args;
      };
      argv_ =
          std::unique_ptr<char*[], void (*)(char**)>(new char*[argc_], deleter);
      for (intptr_t i = 0; i < argc_; ++i) {
        argv_[i] = Utils::StrDup(dart_args[i]->value.as_string);
      }
      break;
    }
    case DartDevIsolate::DartDev_Result_Exit: {
      ASSERT(GetArrayItem(message, 1)->type == Dart_CObject_kInt32);
      int32_t dartdev_exit_code = GetArrayItem(message, 1)->value.as_int32;

      // If we're given a non-zero exit code, DartDev is signaling for us to
      // shutdown.
      int32_t exit_code =
          print_usage_error_ ? kErrorExitCode : dartdev_exit_code;
      Process::SetGlobalExitCode(exit_code);

      // If DartDev hasn't signaled for us to do anything else, we can assume
      // there's nothing else for the VM to run and that we can exit.
      if (result_ == DartDevIsolate::DartDev_Result_Unknown) {
        result_ = DartDevIsolate::DartDev_Result_Exit;
      }

      // DartDev is done processing the command. Unblock the main thread and
      // continue the launch procedure.
      DartDevRunner::monitor_->Notify();
      break;
    }
    default:
      UNREACHABLE();
  }
}

void DartDevIsolate::DartDevRunner::RunCallback(uword args) {
  MonitorLocker locker_(DartDevRunner::monitor_);
  DartDevRunner* runner = reinterpret_cast<DartDevRunner*>(args);

  // Hardcode flags to match those used to generate the DartDev snapshot.
  Dart_IsolateFlags flags;
  Dart_IsolateFlagsInitialize(&flags);
  flags.enable_asserts = false;
  flags.null_safety = true;
  flags.use_field_guards = true;
  flags.use_osr = true;
  flags.is_system_isolate = true;
  flags.branch_coverage = false;

  char* error;
  Dart_Isolate dartdev_isolate = runner->create_isolate_(
      DART_DEV_ISOLATE_NAME, DART_DEV_ISOLATE_NAME, nullptr,
      runner->packages_file_, &flags, /* callback_data */ nullptr,
      const_cast<char**>(&error));

  if (dartdev_isolate == nullptr) {
    ProcessError(error, kErrorExitCode);
    free(error);
    return;
  }

  Dart_EnterIsolate(dartdev_isolate);
  Dart_EnterScope();

  // Retrieve the DartDev entrypoint.
  Dart_Port send_port_id = ILLEGAL_PORT;
  Dart_Handle root_lib = Dart_RootLibrary();
  Dart_Handle main_closure =
      Dart_GetField(root_lib, Dart_NewStringFromCString("main"));
  CHECK_RESULT(main_closure);

  if (!Dart_IsClosure(main_closure)) {
    ProcessError("Unable to find 'main' in root library 'dartdev'",
                 kErrorExitCode);
    Dart_ExitScope();
    Dart_ShutdownIsolate();
    return;
  }

  // Create a SendPort that DartDev can use to communicate its results over.
  send_port_id =
      Dart_NewNativePort(DART_DEV_ISOLATE_NAME, DartDevResultCallback, false);
  ASSERT(send_port_id != ILLEGAL_PORT);
  Dart_Handle send_port = Dart_NewSendPort(send_port_id);
  CHECK_RESULT(send_port);

  const intptr_t kNumIsolateArgs = 4;
  Dart_Handle isolate_args[kNumIsolateArgs];
  isolate_args[0] = main_closure;  // entryPoint
  isolate_args[1] = runner->dart_options_->CreateRuntimeOptions();  // args
  isolate_args[2] = send_port;                                      // message
  isolate_args[3] = Dart_True();  // isSpawnUri

  Dart_Handle isolate_lib =
      Dart_LookupLibrary(Dart_NewStringFromCString("dart:isolate"));
  Dart_Handle result =
      Dart_Invoke(isolate_lib, Dart_NewStringFromCString("_startIsolate"),
                  kNumIsolateArgs, isolate_args);
  CHECK_RESULT(result);
  CHECK_RESULT(Dart_RunLoop());

  Dart_CloseNativePort(send_port_id);

  Dart_ExitScope();
  Dart_ShutdownIsolate();
}

void DartDevIsolate::DartDevRunner::ProcessError(const char* msg,
                                                 int32_t exit_code) {
  Syslog::PrintErr("%s.\n", msg);
  Process::SetGlobalExitCode(exit_code);
  result_ = DartDevIsolate::DartDev_Result_Exit;
  DartDevRunner::monitor_->Notify();
}

DartDevIsolate::DartDev_Result DartDevIsolate::RunDartDev(
    Dart_IsolateGroupCreateCallback create_isolate,
    char** packages_file,
    char** script,
    bool* force_no_sound_null_safety,
    CommandLineOptions* dart_options) {
  runner_.Run(create_isolate, packages_file, script, force_no_sound_null_safety,
              dart_options);
  return runner_.result();
}

#endif  // if !defined(DART_PRECOMPILED_RUNTIME)

}  // namespace bin
}  // namespace dart


text:
<?php
namespace Payum\Klarna\Invoice\Tests\Action\Api;

use Payum\Core\GatewayInterface;
use Payum\Core\Tests\SkipOnPhp7Trait;
use Payum\Klarna\Invoice\Action\Api\CreditPartAction;
use Payum\Klarna\Invoice\Config;
use Payum\Klarna\Invoice\Request\Api\CreditPart;

class CreditPartActionTest extends \PHPUnit_Framework_TestCase
{
    use SkipOnPhp7Trait;

    /**
     * @test
     */
    public function shouldBeSubClassOfBaseApiAwareAction()
    {
        $rc = new \ReflectionClass('Payum\Klarna\Invoice\Action\Api\CreditPartAction');

        $this->assertTrue($rc->isSubclassOf('Payum\Klarna\Invoice\Action\Api\BaseApiAwareAction'));
    }

    /**
     * @test
     */
    public function shouldImplementsGatewayAwareInterface()
    {
        $rc = new \ReflectionClass('Payum\Klarna\Invoice\Action\Api\CreditPartAction');

        $this->assertTrue($rc->implementsInterface('Payum\Core\GatewayAwareInterface'));
    }

    /**
     * @test
     */
    public function couldBeConstructedWithoutAnyArguments()
    {
        new CreditPartAction();
    }

    /**
     * @test
     */
    public function couldBeConstructedWithKlarnaAsArgument()
    {
        new CreditPartAction($this->createKlarnaMock());
    }

    /**
     * @test
     */
    public function shouldAllowSetGateway()
    {
        $action = new CreditPartAction($this->createKlarnaMock());

        $action->setGateway($gateway = $this->getMock('Payum\Core\GatewayInterface'));

        $this->assertAttributeSame($gateway, 'gateway', $action);
    }

    /**
     * @test
     */
    public function shouldAllowSetConfigAsApi()
    {
        $action = new CreditPartAction($this->createKlarnaMock());

        $action->setApi($config = new Config());

        $this->assertAttributeSame($config, 'config', $action);
    }

    /**
     * @test
     *
     * @expectedException \Payum\Core\Exception\UnsupportedApiException
     * @expectedExceptionMessage Instance of Config is expected to be passed as api.
     */
    public function throwApiNotSupportedIfNotConfigGivenAsApi()
    {
        $action = new CreditPartAction($this->createKlarnaMock());

        $action->setApi(new \stdClass());
    }

    /**
     * @test
     */
    public function shouldSupportCreditPartWithArrayAsModel()
    {
        $action = new CreditPartAction();

        $this->assertTrue($action->supports(new CreditPart(array())));
    }

    /**
     * @test
     */
    public function shouldNotSupportAnythingNotCreditPart()
    {
        $action = new CreditPartAction();

        $this->assertFalse($action->supports(new \stdClass()));
    }

    /**
     * @test
     */
    public function shouldNotSupportCreditPartWithNotArrayAccessModel()
    {
        $action = new CreditPartAction();

        $this->assertFalse($action->supports(new CreditPart(new \stdClass())));
    }

    /**
     * @test
     *
     * @expectedException \Payum\Core\Exception\RequestNotSupportedException
     */
    public function throwIfNotSupportedRequestGivenAsArgumentOnExecute()
    {
        $action = new CreditPartAction();

        $action->execute(new \stdClass());
    }

    /**
     * @test
     *
     * @expectedException \Payum\Core\Exception\LogicException
     * @expectedExceptionMessage The invoice_number fields are required.
     */
    public function throwIfDetailsDoNotHaveInvoiceNumber()
    {
        $action = new CreditPartAction();

        $action->execute(new CreditPart(array()));
    }

    /**
     * @test
     */
    public function shouldCallKlarnaCreditPart()
    {
        $details = array(
            'invoice_number' => 'theInvNum',
        );

        $gatewayMock = $this->createGatewayMock();
        $gatewayMock
            ->expects($this->once())
            ->method('execute')
            ->with($this->isInstanceOf('Payum\Klarna\Invoice\Request\Api\PopulateKlarnaFromDetails'))
        ;

        $klarnaMock = $this->createKlarnaMock();
        $klarnaMock
            ->expects($this->once())
            ->method('creditPart')
            ->with($details['invoice_number'])
            ->will($this->returnValue('theRefundInvoiceNumber'))
        ;

        $action = new CreditPartAction($klarnaMock);
        $action->setApi(new Config());
        $action->setGateway($gatewayMock);

        $action->execute($creditPart = new CreditPart($details));

        $actualDetails = $creditPart->getModel();
        $this->assertContains('theRefundInvoiceNumber', $actualDetails['refund_invoice_number']);
    }

    /**
     * @test
     */
    public function shouldCatchKlarnaExceptionAndSetErrorInfoToDetails()
    {
        $details = array(
            'invoice_number' => 'theInvNum',
        );

        $gatewayMock = $this->createGatewayMock();
        $gatewayMock
            ->expects($this->once())
            ->method('execute')
            ->with($this->isInstanceOf('Payum\Klarna\Invoice\Request\Api\PopulateKlarnaFromDetails'))
        ;

        $klarnaMock = $this->createKlarnaMock();
        $klarnaMock
            ->expects($this->once())
            ->method('creditPart')
            ->will($this->throwException(new \KlarnaException('theMessage', 123)))
        ;

        $action = new CreditPartAction($klarnaMock);
        $action->setApi(new Config());
        $action->setGateway($gatewayMock);

        $action->execute($creditPart = new CreditPart($details));

        $actualDetails = $creditPart->getModel();
        $this->assertEquals(123, $actualDetails['error_code']);
        $this->assertEquals('theMessage', $actualDetails['error_message']);
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|\Klarna
     */
    protected function createKlarnaMock()
    {
        $klarnaMock =  $this->getMock('Klarna', array('config', 'activate', 'cancelReservation', 'checkOrderStatus', 'reserveAmount', 'creditPart'));

        $rp = new \ReflectionProperty($klarnaMock, 'xmlrpc');
        $rp->setAccessible(true);
        $rp->setValue($klarnaMock, $this->getMock('xmlrpc_client', array(), array(), '', false));
        $rp->setAccessible(false);

        return $klarnaMock;
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|GatewayInterface
     */
    protected function createGatewayMock()
    {
        return $this->getMock('Payum\Core\GatewayInterface');
    }
}


text:
cd NLua
xbuild /p:Configuration=Release NLua.Net45.sln
cd ..
#


text:
import os
import sys
import shutil
import numpy as np
import warnings
from astropy.io import fits
from astropy.utils.exceptions import AstropyWarning
from astropy.table import Table
from dlnpyutils import utils as dln, coords, job_daemon as jd
from astropy import units as u
from astropy.coordinates import SkyCoord
#import subprocess
import time
from argparse import ArgumentParser
import socket
import logging
import healpy as hp

# Combine data for one NSC healpix region
if __name__ == "__main__":
    parser = ArgumentParser(description='Combine NSC Instcal Catalogs.')
    parser.add_argument('version', type=str, nargs=1, help='Version number')
    parser.add_argument('--hosts', type=str, nargs=1, help='Delimited list of hosts')
    parser.add_argument('-l','--list', type=str, nargs=1, default='', help='List of HEALPix to run')
    parser.add_argument('-nm','--nmulti', type=int, nargs=1, default=15, help='Number of jobs')
    parser.add_argument('-r','--redo', action='store_true', help='Redo this HEALPIX')
    args = parser.parse_args()

    t0 = time.time()
    hostname = socket.gethostname()
    host = hostname.split('.')[0]

    # Inputs
    version = dln.first_el(args.version)
    redo = args.redo
    nmulti = dln.first_el(args.nmulti)
    if args.hosts is not None:
        hosts = args.hosts[0].split(',')
    else:
        hosts = [host]
    inplistfile = dln.first_el(args.list)
    if inplistfile == '': inplistfile = None
    nside = 128
    radeg = 180 / np.pi

    # on thing/hulk use
    if (host == "thing") or (host == "hulk"):
        #basedir = "/net/dl1/users/dnidever/nsc/instcal/"+version+"/"
        basedir = "/net/dl2/dnidever/nsc/instcal/"+version+"/"
        mssdir = "/mss1/"
        localdir = "/d0/"
        tmpdir = localdir+"dnidever/nsc/instcal/"+version+"/tmp/"
    # on gp09 use
    if (host == "gp09") or (host == "gp08") or (host == "gp07") or (host == "gp06") or (host == "gp05"):
        #basedir = "/net/dl1/users/dnidever/nsc/instcal/"+version+"/"
        basedir = "/net/dl2/dnidever/nsc/instcal/"+version+"/"
        mssdir = "/net/mss1/"
        localdir = "/data0/"
        tmpdir = localdir+"dnidever/nsc/instcal/"+version+"/tmp/"

    t0 = time.time()

    if not os.path.exists(tmpdir): os.mkdir(tmpdir)
    if not os.path.exists(basedir+'combine'): os.mkdir(basedir+'combine/')
    if not os.path.exists(basedir+'combine/logs/'): os.mkdir(basedir+'combine/logs/')
    if not os.path.exists(localdir+'dnidever/nsc/instcal/'+version+'/'): os.mkdir(localdir+'dnidever/nsc/instcal/'+version+'/')
    if not os.path.exists(basedir+'logs'): os.mkdir(basedir+'logs/')
    # Hosts
    #if hosts is None: hosts = ['gp09','hulk','thing']
    if (host not in hosts):
        print('Current HOST='+host+' not in list of HOSTS = [ '+','.join(hosts)+' ] ')
        sys.exit()

    # Turn off mulit-threading
    os.environ["OMP_NUM_THREADS"] = "1"
    os.environ["OPENBLAS_NUM_THREADS"] = "1"
    os.environ["MKL_NUM_THREADS"] = "1"
    os.environ["VECLIB_MAXIMUM_THREADS"] = "1"
    os.environ["NUMEXPR_NUM_THREADS"] = "1"

    # Log file
    #------------------
    # format is nsc_combine_main.DATETIME.log
    ltime = time.localtime()
    # time.struct_time(tm_year=2019, tm_mon=7, tm_mday=22, tm_hour=0, tm_min=30, tm_sec=20, tm_wday=0, tm_yday=203, tm_isdst=1)
    smonth = str(ltime[1])
    if ltime[1]<10: smonth = '0'+smonth
    sday = str(ltime[2])
    if ltime[2]<10: sday = '0'+sday
    syear = str(ltime[0])[2:]
    shour = str(ltime[3])
    if ltime[3]<10: shour='0'+shour
    sminute = str(ltime[4])
    if ltime[4]<10: sminute='0'+sminute
    ssecond = str(int(ltime[5]))
    if ltime[5]<10: ssecond='0'+ssecond
    logtime = smonth+sday+syear+shour+sminute+ssecond
    logfile = basedir+'combine/logs/nsc_instcal_combine_main.'+logtime+'.log'

    # Set up logging to screen and logfile
    logFormatter = logging.Formatter("%(asctime)s [%(levelname)-5.5s]  %(message)s")
    rootLogger = logging.getLogger()
    fileHandler = logging.FileHandler(logfile)
    fileHandler.setFormatter(logFormatter)
    rootLogger.addHandler(fileHandler)
    consoleHandler = logging.StreamHandler()
    consoleHandler.setFormatter(logFormatter)
    rootLogger.addHandler(consoleHandler)
    rootLogger.setLevel(logging.NOTSET)

    rootLogger.info("Combining NOAO InstCal catalogs")
    rootLogger.info("host = "+host)
    rootLogger.info("version = "+version)
    rootLogger.info("nmulti = "+str(nmulti))
    rootLogger.info("hosts = "+','.join(np.array(hosts)))
    rootLogger.info("redo = "+str(redo))

    # Healpix pixels to run
    listfile = basedir+'lists/nsc_instcal_combine_healpix_list.fits.gz'
    if inplistfile is None:
        if not os.path.exists(listfile):
            rootLogger.info(listfile+' NOT FOUND.  Run nsc_instcal_combine_qacuts.pro/py')
            sys.exit()

        rootLogger.info("Reading list from "+listfile)

        healstr = fits.getdata(listfile,1)
        index = fits.getdata(listfile,2)
        upix = index['pix']
        npix = len(index)
    else:
        rootLogger.info("Reading list from "+inplistfile)
        upix = dln.readlines(inplistfile)
        upix = np.array(upix,int)
        npix = len(upix)

    # Copy to local directory for faster reading speed
    if os.path.exists(localdir+'dnidever/nsc/instcal/'+version+'/'+os.path.basename(listfile)):
                 os.remove(localdir+'dnidever/nsc/instcal/'+version+'/'+os.path.basename(listfile))
    shutil.copyfile(listfile,localdir+'dnidever/nsc/instcal/'+version+'/'+os.path.basename(listfile))
    #file_copy,listfile,localdir+'dnidever/nsc/instcal/'+version+'/',/over

    # Create the commands
    allpix = upix.copy()
    allcmd = dln.strjoin("/home/dnidever/projects/noaosourcecatalog/python/nsc_instcal_combine_cluster.py ",allpix.astype(np.str))
    allcmd = dln.strjoin(allcmd," "+version+" --nside "+str(nside))
    if redo: allcmd = dln.strjoin(allcmd,' -r')
    alldirs = np.zeros(npix,(np.str,200))
    alldirs[:] = tmpdir
    nallcmd = len(allcmd)

    # Check what's been done already
    if not redo:
        rootLogger.info("Checking if any have already been done")
        exists = np.zeros(dln.size(allpix),bool)+False
        for ip,p in enumerate(allpix):
            outfile = basedir+'combine/'+str(p//1000)+'/'+str(p)+'.fits.gz'
            if os.path.exists(outfile): exists[ip]=True
        bd,nbd,gd,ngd = dln.where(exists,comp=True)
        if ngd==0:
            rootLogger.info('All pixels were previously completed. Nothing to run')
            sys.exit()
        if nbd>0:
            rootLogger.info(str(nbd)+' pixels previously completed.  Removing them. '+str(ngd)+' left.')
            allpix = allpix[gd]
            allcmd = allcmd[gd]
            alldirs = alldirs[gd]
            nallcmd = len(allcmd)

    rootLogger.info(str(nallcmd)+' healpix to process')

    ## Only keep MC region
    #ra,dec = hp.pix2ang(nside,allpix,lonlat=True)
    #coords = SkyCoord(ra=ra*u.degree,dec=dec*u.degree)
    #lmc = SkyCoord(ra=81.9*u.degree,dec=-69.866*u.degree)
    #lrad = lmc.separation(coords).deg
    #smc = SkyCoord(ra=13.183*u.degree,dec=-72.8283*u.degree)
    #srad = smc.separation(coords).deg
    ##gd,ngd = dln.where( (coords.galactic.b.deg<-10) & (lrad>6) & (srad>6) ((lrad>6) & (lrad<25)) | ((srad>6) & (srad<15)) )
    ##gd,ngd = dln.where( (coords.galactic.b.deg<-10) & (lrad>6) & (srad>6) & ((lrad<25) | (srad<15)) )
    #gd,ngd = dln.where( (coords.galactic.b.deg<-10) & ((lrad<25) | (srad<15)) )
    #rootLogger.info('Only processing '+str(ngd)+' Magellanic Clouds HEALPix')
    #allpix = allpix[gd]
    #allcmd = allcmd[gd]
    #alldirs = alldirs[gd]
    #nallcmd = ngd

    # RANDOMIZE
    np.random.seed(0)
    rnd = np.argsort(np.random.rand(nallcmd))
    allpix = allpix[rnd]
    allcmd = allcmd[rnd]
    alldirs = alldirs[rnd]

    # Parcel out the jobs
    nhosts = dln.size(hosts)
    torun = np.arange(nallcmd)
    nperhost = int(np.ceil(nallcmd/nhosts))
    for i in range(nhosts):
        if host==hosts[i]: torun=torun[i*nperhost:(i+1)*nperhost]
    ntorun = len(torun)
    pix = allpix[torun]
    cmd = allcmd[torun]
    dirs = alldirs[torun]
    rootLogger.info('Running '+str(len(torun))+' on '+host)

    ## Check what's been done already
    #if not redo:
    #    exists = np.zeros(dln.size(pix),bool)+False
    #    for ip,p in enumerate(pix):
    #        outfile = basedir+'combine/'+str(p//1000)+'/'+str(p)+'.fits.gz'
    #        if os.path.exists(outfile): exists[ip]=True
    #    bd,nbd,gd,ngd = dln.where(exists,comp=True)
    #    if ngd==0:
    #        rootLogger.info('All pixels were previously completed. Nothing to run')
    #        sys.exit()
    #    if nbd>0:
    #        rootLogger.info(str(nbd)+' pixels previously completed.  Removing them. '+str(ngd)+' left.')
    #        pix = pix[gd]
    #        cmd = cmd[gd]
    #        dirs = dirs[gd]

    # Saving the structure of jobs to run
    runfile = basedir+'lists/nsc_instcal_combine_main.'+host+'.'+logtime+'_run.fits'
    rootLogger.info('Writing running information to '+runfile)
    runstr = np.zeros(len(cmd),dtype=np.dtype([('pix',int),('host',(np.str,20))]))
    runstr['pix'] = pix
    runstr['host'] = host
    Table(runstr).write(runfile)

    # Now run the combination program on each healpix pixel
    import pdb; pdb.set_trace()
    a = input("Press RETURN to start")
    jobs = jd.job_daemon(cmd,dirs,hyperthread=True,prefix='nsccmb',nmulti=nmulti)

    # Save the jobs
    Table(jobs).write(basedir+'lists/nsc_instcal_combine_main.'+host+'.'+logtime+'_jobs.fits')


text:
using System;

namespace DeclarativeSql.Annotations;

/// <summary>
/// Provides an attribute that represents a primary key.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public sealed class PrimaryKeyAttribute : Attribute
{
    #region Constructors
    /// <summary>
    /// Creates instance.
    /// </summary>
    public PrimaryKeyAttribute()
    { }
    #endregion
}


text:
// vec_math.h
#ifndef NGE_MATH_VEC_MATH_H
#define NGE_MATH_VEC_MATH_H

#include "engine/math/math.h"

namespace nge
{

namespace math
{

template <typename T>
class TRef2;

template <typename T>
class TRef3;

template <typename T>
class TRef4;

template <typename T>
class TVec2;

template <typename T>
class TVec3;

template <typename T>
class TVec4;

template <typename T>
class TMat2x2;

template <typename T>
class TMat3x3;

template <typename T>
class TMat4x4;

struct Vec
{
    /**
     * Calculates the magnitude of the vector.
     *
     * @param v The vector.
     * @return The length.
     */
    template <typename T>
    static T length( const TVec2<T>& v );

    /**
     * Calculates the magnitude of the vector.
     *
     * @param v The vector.
     * @return The length.
     */
    template <typename T>
    static T length( const TVec3<T>& v );

    /**
     * Calculates the magnitude of the vector.
     *
     * @param v The vector.
     * @return The length.
     */
    template <typename T>
    static T length( const TVec4<T>& v );

    /**
     * Normalizes the vector.
     *
     * @param v The vector.
     * @return The unit vector.
     */
    template <typename T>
    static TVec2<T> normalize( const TVec2<T>& v );

    /**
     * Normalizes the vector.
     *
     * @param v The vector.
     * @return The unit vector.
     */
    template <typename T>
    static TVec3<T> normalize( const TVec3<T>& v );

    /**
     * Normalizes the vector.
     *
     * @param v The vector.
     * @return The unit vector.
     */
    template <typename T>
    static TVec4<T> normalize( const TVec4<T>& v );

    /**
     * Calculates the scalar product of the two vectors.
     *
     * @param a The first vector.
     * @param b The second vector.
     * @return The scalar product.
     */
    template <typename T>
    static T dot( const TVec2<T>& a, const TVec2<T>& b );

    /**
     * Calculates the scalar product of the two vectors.
     *
     * @param a The first vector.
     * @param b The second vector.
     * @return The scalar product.
     */
    template <typename T>
    static T dot( const TVec3<T>& a, const TVec3<T>& b );

    /**
     * Calculates the scalar product of the two vectors.
     *
     * @param a The first vector.
     * @param b The second vector.
     * @return The scalar product.
     */
    template <typename T>
    static T dot( const TVec4<T>& a, const TVec4<T>& b );

    /**
     * Calculates the cross product of two 3D vectors.
     *
     * @param a The first vector.
     * @param b The second vector.
     * @return The cross product.
     */
    template <typename T>
    static TVec3<T> cross( const TVec3<T>& a, const TVec3<T>& b );

    /**
     * Projects vector a onto vector b.
     *
     * @param a The vector to project.
     * @param b The vector to project onto.
     * @return The projection.
     */
    template <typename T>
    static TVec2<T> project( const TVec2<T>& a, const TVec2<T>& b );

    /**
     * Projects vector a onto vector b.
     *
     * @param a The vector to project.
     * @param b The vector to project onto.
     * @return The projection.
     */
    template <typename T>
    static TVec3<T> project( const TVec3<T>& a, const TVec3<T>& b );

    /**
     * Projects vector a onto vector b.
     *
     * @param a The vector to project.
     * @param b The vector to project onto.
     * @return The projection.
     */
    template <typename T>
    static TVec4<T> project( const TVec4<T>& a, const TVec4<T>& b );
};

template <typename T>
inline
T Vec::length( const TVec2<T>& v )
{
    return Math::sqrt( Math::pow( v.x, 2 ) + Math::pow( v.y, 2 ) );
}

template <typename T>
inline
T Vec::length( const TVec3<T>& v )
{
    return Math::sqrt( Math::pow( v.x, 2 ) + Math::pow( v.y, 2 ) + Math::pow( v.z, 2 ) );
}

template <typename T>
inline
T Vec::length( const TVec4<T>& v )
{
    return Math::sqrt( Math::pow( v.x, 2 ) + Math::pow( v.y, 2 ) + Math::pow( v.z, 2 ) +
        Math::pow( v.w, 2 ) );
}

template <typename T>
inline
TVec2<T> Vec::normalize( const TVec2<T>& v )
{
    return v / length( v );
}

template <typename T>
inline
TVec3<T> Vec::normalize( const TVec3<T>& v )
{
    return v / length( v );
}

template <typename T>
inline
TVec4<T> Vec::normalize( const TVec4<T>& v )
{
    return v / length( v );
}

template <typename T>
inline
T Vec::dot( const TVec2<T>& a, const TVec2<T>& b )
{
    return a.x * b.x + a.y * b.y;
}

template <typename T>
inline
T Vec::dot( const TVec3<T>& a, const TVec3<T>& b )
{
    return a.x * b.x + a.y * b.y + a.z * b.z;
}

template <typename T>
inline
T Vec::dot( const TVec4<T>& a, const TVec4<T>& b )
{
    return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
}

template <typename T>
inline
TVec3<T> Vec::cross( const TVec3<T>& a, const TVec3<T>& b )
{

}

template <typename T>
inline
TVec2<T> Vec::project( const TVec2<T>& a, const TVec2<T>& b )
{

}

template <typename T>
inline
TVec3<T> Vec::project( const TVec3<T>& a, const TVec3<T>& b )
{

}

template <typename T>
inline
TVec4<T> Vec::project( const TVec4<T>& a, const TVec4<T>& b )
{

}

} // End nspc math

} // End nspc nge

#endif // NGE_MATH_VEC_MATH_H


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE WMT_MS_Capabilities SYSTEM "http://schemas.opengis.net/wms/1.1.1/WMS_MS_Capabilities.dtd">
<WMT_MS_Capabilities version="1.1.1">
<Service>
<Name>OGC:WMS</Name>
<Title>NASA Global Imagery Browse Services for EOSDIS</Title>
<Abstract>
Near real time imagery from multiple NASA instruments
</Abstract>
<KeywordList>
<Keyword>GIBS</Keyword>
<Keyword>NASA</Keyword>
<Keyword>WMS</Keyword>
<Keyword>Earth</Keyword>
</KeywordList>
<OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://gibs.earthdata.nasa.gov/twms/epsg4326/nrt/" xlink:type="simple"/>
<ContactInformation>
<ContactPersonPrimary>
<ContactPerson/>
<ContactOrganization/>
</ContactPersonPrimary>
<ContactElectronicMailAddress/>
</ContactInformation>
<Fees>none</Fees>
<AccessConstraints>none</AccessConstraints>
</Service>
<Capability>
<Request>
<GetCapabilities>
<Format>application/vnd.ogc.wms_xml</Format>
<DCPType>
<HTTP>
<Get>
<OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://gibs.earthdata.nasa.gov/twms/epsg4326/nrt/twms.cgi?" xlink:type="simple"/>
</Get>
</HTTP>
</DCPType>
</GetCapabilities>
<GetMap>
<Format>image/jpeg</Format>
<Format>image/png</Format>
<DCPType>
<HTTP>
<Get>
<OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://gibs.earthdata.nasa.gov/twms/epsg4326/nrt/twms.cgi?" xlink:type="simple"/>
</Get>
</HTTP>
</DCPType>
</GetMap>
<GetTileService>
<Format>text/xml</Format>
<DCPType>
<HTTP>
<Get>
<OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://gibs.earthdata.nasa.gov/twms/epsg4326/nrt/twms.cgi?" xlink:type="simple"/>
</Get>
</HTTP>
</DCPType>
</GetTileService>
</Request>
<Exception>
<Format>application/vnd.ogc.se_xml</Format>
</Exception>
<VendorSpecificCapabilities/>
<UserDefinedSymbolization SupportSLD="0" UserLayer="0" UserStyle="1" RemoteWFS="0"/>
<Layer queryable="0">
<Title>Global Imagery Browse Services</Title>
<SRS>EPSG:4326</SRS>
<CRS>EPSG:4326</CRS>
</Layer>
</Capability>
</WMT_MS_Capabilities>


text:
module GamesHelper
  def status_string(game, separator="")
    if game.in_progress?
      game.characters.map { |c| c==nil ? '_' : c }.join(separator)
    else
      game.target_word
    end
  end

  def progress_message(game)
    if game.in_progress?
      "In progress"
    elsif game.won?
      "Won"
    elsif game.lost?
      "Lost"
    else
      fail
    end
  end

  def game_color(game)
    if game.in_progress?
      "#EDA807"
    elsif game.won?
      "#5BED07"
    elsif game.lost?
      "#D12E2E"
    else
      fail
    end
  end

  def dictionary_url(word)
    "http://dictionary.reference.com/browse/#{word}"
  end
end


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<module version="0.1">
    <name lang="en">Course Properties</name>
    <description lang="en">Allows instructors and administrators to delete a course, or manage its various properties such as title, description, access level, course icon and more. </description>
    <maintainers>
        <maintainer>
            <name>ATutor Team</name>
            <email>info@atutor.ca</email>
        </maintainer>
    </maintainers>
    <url>http://atutor.ca</url>
    <license>GPL</license>
	<release>
        <version>0.1</version>
		<privileges>
			<instructor_privilege>existing</instructor_privilege>
			<admin_privilege></admin_privilege>
		</privileges>
        <date>2005-08-22</date>
        <state>stable</state>
        <notes>This is a core module.</notes>
    </release>
</module>


text:
<?php

class EA_Socket_Exception extends EA_Exception
{}


text:
package net.mentalarray.doozie.Builders

import net.mentalarray.doozie.ValueProxy.TaskResult
import net.mentalarray.doozie.{WorkflowStep, WorkflowTask}

/**
 * Created by kdivincenzo on 9/9/14.
 */
class WorkflowBuilder(_wfName: String) extends Builder[WorkflowInstance] {

  private val graph: ExecutionGraph = new ExecutionGraph
  private var _inputPath: String = null

  def inputPath: String = _inputPath
  def setInputPath(path: String) = _inputPath = path

  protected var workflowName = _wfName

  def this() {
    this("{Unnamed Workflow}")
  }

  def appendStep(step: WorkflowStep) : WorkflowBuilder = {
    graph += step
    this
  }

  def appendStep(task: WorkflowTask) : WorkflowBuilder = {
    graph += WorkflowStep(task)
    this
  }

  def getResultFrom[T](task: WorkflowTask with TaskHasResult[T]): TaskResult[T] = {
    graph += WorkflowStep(task)
    TaskResult[T](_ => task.get)
  }

  def build : WorkflowInstance = {
    new WorkflowInstance(_wfName, graph)
  }

}


text:
'use strict';

// Npcs controller
angular.module('npcs').controller('NpcsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Npcs',
	function($scope, $stateParams, $location, Authentication, Npcs ) {
		$scope.authentication = Authentication;

		// Create new Npc
		$scope.create = function() {
			// Create new Npc object
			var npc = new Npcs ({
				name: this.name
			});

			// Redirect after save
			npc.$save(function(response) {
				$location.path('npcs/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Npc
		$scope.remove = function( npc ) {
			if ( npc ) { npc.$remove();

				for (var i in $scope.npcs ) {
					if ($scope.npcs [i] === npc ) {
						$scope.npcs.splice(i, 1);
					}
				}
			} else {
				$scope.npc.$remove(function() {

				});
			}
		};

		// Update existing Npc
		$scope.update = function() {
			var npc = $scope.npc ;

			npc.$update(function() {

			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Npcs
		$scope.find = function() {
			$scope.npcs = Npcs.query(
				function(response) {
					console.log(response);
				}
			);
		};

		// Find existing Npc
		$scope.findOne = function() {
			$scope.npc = Npcs.get({
				npcId: $stateParams.npcId
			});
		};
	}
]);


text:
<?php

namespace app\models;

use Yii;
use yii\behaviors\SluggableBehavior;

/**
 * This is the model class for table "product".
 *
 * @property integer $id
 * @property string $title
 * @property string $name
 * @property string $slug
 * @property string $description
 * @property string $more_info
 * @property integer $category_id
 * @property string $price
 * @property integer $old_price
 * @property string $quantity
 * @property integer $status
 * @property integer $type
 * @property string $model
 * @property string $brand
 *
 * @property OrderItem[] $orderItems
 * @property Category $category
 */
class Product extends \yii\db\ActiveRecord
{
    public $image;

    public function behaviors()
    {
        return [
            'slug' => [
                'class' => 'Zelenin\yii\behaviors\Slug',
                'slugAttribute' => 'slug',
                'attribute' => 'title',
                // optional params
                'ensureUnique' => true,
                'replacement' => '-',
                'lowercase' => true,
                'immutable' => false,
                // If intl extension is enabled, see http://userguide.icu-project.org/transforms/general.
                'transliterateOptions' => 'Russian-Latin/BGN; Any-Latin; Latin-ASCII; NFD; [:Nonspacing Mark:] Remove; NFC;'
            ]
        ];
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'product';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name','price','title','model' ], 'required'],
            [['description', 'more_info','small_description'], 'string'],
            [['category_id', 'price', 'old_price', 'quantity', 'status', 'type'], 'integer'],
            [['title', 'name', 'slug', 'model', 'brand'], 'string', 'max' => 255],
            [['image'], 'file', 'maxFiles' => 20],
            [['quantity'], 'default', 'value' => '1'],
            [['status'], 'default', 'value' => '1'],
            [['category_id'], 'default', 'value' => null],
            [['category_id'], 'exist', 'skipOnError' => true, 'targetClass' => Category::className(), 'targetAttribute' => ['category_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'СЕО заголовок',
            'name' => 'Название',
            'slug' => 'Slug',
            'description' => 'Описание',
            'more_info' => 'Дополнительное описание',
            'category_id' => 'Категория',
            'price' => 'Цена',
            'old_price' => 'Старая цена',
            'quantity' => 'Кол-во',
            'status' => 'Статус',
            'type' => 'Тип',
            'model' => 'Модель',
            'brand' => 'Бренд',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getOrderItems()
    {
        return $this->hasMany(OrderItem::className(), ['product_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCategory()
    {
        return $this->hasOne(Category::className(), ['id' => 'category_id']);
    }

    public function GetOneImg($id)
    {
        $img = Image::find()->where(['models' => 'Product'])->andWhere(['product_id' => $id])->andWhere(['sort' => '0'])->one();
        return $img;
    }
    public function GetAllImg($id)
    {
        $img = Image::find()->where(['models' => 'Product'])->andWhere(['product_id' => $id])->andWhere(['>=','sort' , 1])->orderBy('sort ASC')->all();
        return $img;
    }
    public function getParams()
    {
        return $this->hasMany(Params::className(), ['product_id' => 'id']);
    }
    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProductTags()
    {
        return $this->hasMany(ProductTag::className(), ['product_id' => 'id']);
    }
    /**
     * @return \yii\db\ActiveQuery
     */
    public function getTags()
    {
        return $this->hasMany(Tag::className(), ['id' => 'tag_id'])->viaTable('{{%product_tag}}', ['product_id' => 'id']);
    }
    public function getImages()
    {
        return $this->hasMany(Image::className(), ['product_id' => 'id']);
    }

    public function badImg()
    {
        return'/placeHolder.png';
    }
}


text:
namespace g{namespace Uno{namespace Graphics{struct GraphicsContext;}}}
namespace g{namespace Uno{namespace Platform{struct Window;}}}
namespace g{namespace Uno{struct Application;}}

namespace g{
namespace Uno{

// public abstract class Application :68
// {
uType* Application_typeof();
void Application__ctor__fn(Application* __this);
void Application__get_ClearColor_fn(Application* __this, ::g::Uno::Float4* __retval);
void Application__set_ClearColor_fn(Application* __this, ::g::Uno::Float4* value);
void Application__get_ClearDepth_fn(Application* __this, float* __retval);
void Application__set_ClearDepth_fn(Application* __this, float* value);
void Application__get_Current_fn(Application** __retval);
void Application__set_Current_fn(Application* value);
void Application__Draw_fn(Application* __this);
void Application__get_DrawNextFrame_fn(Application* __this, bool* __retval);
void Application__set_DrawNextFrame_fn(Application* __this, bool* value);
void Application__get_GraphicsContext_fn(Application* __this, ::g::Uno::Graphics::GraphicsContext** __retval);
void Application__set_GraphicsContext_fn(Application* __this, ::g::Uno::Graphics::GraphicsContext* value);
void Application__Load_fn(Application* __this);
void Application__Update_fn(Application* __this);
void Application__get_Window_fn(Application* __this, ::g::Uno::Platform::Window** __retval);
void Application__set_Window_fn(Application* __this, ::g::Uno::Platform::Window* value);

struct Application : uObject
{
    ::g::Uno::Float4 _ClearColor;
    float _ClearDepth;
    static uSStrong<Application*> _Current_;
    static uSStrong<Application*>& _Current() { return _Current_; }
    bool _DrawNextFrame;
    uStrong< ::g::Uno::Graphics::GraphicsContext*> _GraphicsContext;
    uStrong< ::g::Uno::Platform::Window*> _Window;

    void ctor_();
    ::g::Uno::Float4 ClearColor();
    void ClearColor(::g::Uno::Float4 value);
    float ClearDepth();
    void ClearDepth(float value);
    void Draw();
    bool DrawNextFrame();
    void DrawNextFrame(bool value);
    ::g::Uno::Graphics::GraphicsContext* GraphicsContext();
    void GraphicsContext(::g::Uno::Graphics::GraphicsContext* value);
    void Load();
    void Update();
    ::g::Uno::Platform::Window* Window();
    void Window(::g::Uno::Platform::Window* value);
    static Application* Current();
    static void Current(Application* value);
};
// }

}} // ::g::Uno


text:
package com.sequenceiq.cloudbreak.reactor.api.event.cluster;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.sequenceiq.cloudbreak.common.event.FlowPayload;
import com.sequenceiq.cloudbreak.reactor.api.ClusterPlatformResult;

public class ClusterStartPollingResult extends ClusterPlatformResult<ClusterStartPollingRequest> implements FlowPayload {

    public ClusterStartPollingResult(ClusterStartPollingRequest request) {
        super(request);
    }

    @JsonCreator
    public ClusterStartPollingResult(
            @JsonProperty("statusReason") String statusReason,
            @JsonProperty("errorDetails") Exception errorDetails,
            @JsonProperty("request") ClusterStartPollingRequest request) {
        super(statusReason, errorDetails, request);
    }
}


text:
.td_datagrid_container {
	position: relative;
	width: 100%;
	height: 100%;
}
.td_datagrid_container .td_datagrid_content {
	position:absolute;
	width:100%;
	border:solid 1px #eee;
	padding-left:10px;
	padding-right:10px;
	background-color:#fff;
	box-shadow: 0 6px 12px rgba(0, 0, 0, 0.176);
	-ms-filter:"progid:DXImageTransform.Microsoft.Shadow(Strength=3, Direction=135, Color='#cccccc')";
	filter:progid:DXImageTransform.Microsoft.Shadow(Strength=3, Direction=135, Color='#cccccc');
	z-index:5;
}
table.td_datagrid {
	table-layout: fixed;
	margin-bottom:0px;
}
table.td_datagrid>thead>tr>th {
	border-top: 0px none;
	border-bottom: 0px none;
}
table.td_datagrid>thead>tr>th>input[type="text"],
table.td_datagrid>tbody>tr>td>div>input[type="text"],
table.td_datagrid>thead>tr>th>select,
table.td_datagrid>tbody>tr>td>div>select {
	background-color: transparent;
	height: 22px;
	line-height: 22px;
	outline: 0 none;
	padding: 0;
	border-radius: 0;
	border: 0px none;
	border-bottom: solid 1px #ddd;
	-webkit-box-sizing: content-box;
    -moz-box-sizing: content-box;
    box-sizing: content-box;
}
table.td_datagrid>thead>tr>th>input[type="text"]:focus,
table.td_datagrid>tbody>tr>td>div>input[type="text"]:focus,
table.td_datagrid>thead>tr>th>select:focus,
table.td_datagrid>tbody>tr>td>div>select:focus {
	transition: all .3s;
	border-bottom: solid 1px #009688;
}

table.td_datagrid>thead>tr>th,
table.td_datagrid>tbody>tr>td {
	transition: all .3s;
	padding: 5px;
	padding-left: 15px;
	height: 42px;
	cursor: default;
	white-space:nowrap;
	overflow:hidden;
	text-overflow:ellipsis;
}
table.td_datagrid>thead>tr>th {
	cursor: pointer;
}

table.td_datagrid>tbody>tr>td>div>.btn {
	padding: 4px 12px;
	margin: 0px;
}
table.td_datagrid>thead>tr>td>input[type="button"] {
	height: 25px;
	line-height: 25px;
}

table.td_datagrid>thead {
	border-bottom: solid 1px #ddd;
}
table.td_datagrid>tbody>tr.td_datagrid_tr_edit {
	background-color: #80cbc4;
	box-shadow: 5px 5px 5px #888888;
}
table.td_datagrid>tbody>tr.td_datagrid_tr_edit>td {
	-webkit-box-shadow: 5px 5px 5px #888888;
}

table.td_datagrid tr.td_datagrid_tr_selected td {
	border-bottom: solid 1px #009688;
}

.td_datagrid_container .td_datagrid_actions {
	position: absolute;
	right: -10px;
	bottom: 20px;
	width: 55px;
}
.td_datagrid_container .td_datagrid_actions>a {
	margin-top: 5px;
	margin-bottom: 0px;
	border-radius: 25px;
	padding: 8px 12px;
}

.td_datagrid_container i.td_datagrid_icon {
	display: inline-block;
	margin-top: 2px;
	width: 18px;
	height: 18px;
	line-height: 18px;
	vertical-align: text-top;
	background-repeat: no-repeat;
}
.td_datagrid_container .td_datagrid_padding {
    padding: 0 5px;
}
.td_datagrid_container .td_datagrid_checked {
	background-image:url(../img/datagrid/checked.png);
}
.td_datagrid_container .td_datagrid_unchecked {
	background-image:url(../img/datagrid/unchecked.png);
}


text:
*The easiest way to work with attributed strings in Swift*

![Swift Version 4](https://img.shields.io/badge/Swift-v4-yellow.svg)
[![Percentage Documented Badge](http://svdo.github.io/swift-RichString/badge.svg)](http://svdo.github.io/swift-RichString/)
[![CocoaPods Version Badge](https://img.shields.io/cocoapods/v/RichString.svg)](https://cocoapods.org/pods/RichString)
![Supported Platforms Badge](https://img.shields.io/cocoapods/p/RichString.svg)
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
[![license](https://img.shields.io/github/license/mashape/apistatus.svg)](https://github.com/svdo/swift-RichString/blob/master/LICENSE)
[![Build Status](https://travis-ci.org/svdo/swift-RichString.svg?branch=master)](https://travis-ci.org/svdo/swift-RichString)

## Introduction

This Swift framework was built to simplify working with `NSAttributedString`. It
does so without adding additional types; it just extends the existing types that
you already have, ensuring that it is fully interoperable with any other method
of using `NSAttributedString`.

The core assumption this framework makes, is that you set up your attributed
strings by first configuring all components appropriately, and then
concatenating them.

It allows you to do things like this:

```swift
let title = "This is a title".fontSize(17).color(.blue)
let text = "This is some text".paragraphStyle {
    $0.firstLineHeadIndent = 20
}
let content = title + text
```

## Overview

This framework provides the following primitives. There are unit tests; have a
look at them for more examples.

### Operator `+` For Concatenating Attributed Strings

Given two strings, you can append one to the other using the `+` operator:

```swift
let s1 = NSAttributedString()
let s2 = NSAttributedString()
let concatenated = s1 + s2
```

### `RichString` protocol for `String`, `NSString` and `NSAttributedString`

#### font(_:)

Apply the given font. The type `Font` is a type alias of `UIFont` on iOS, and of
`NSFont` on macOS.

```swift
let attributedString = "text".font(.systemFont(ofSize: 12))
```

#### fontSize(_:)

Applies the given font size. If no font was set on the attributed string yet,
`Font.systemFont` will be assumed.

Note: unlike on iOS, on macOS this returns an *optional* attributed string
instead.

```swift
let attributedString = "text".fontSize(12)
```

#### paragraphStyle(configure:)

Applies a paragraph style, configuring it with the given closure. If the
attributed string already had a paragraph style attribute, the `configure`
closure is called on that paragraph style; otherwise a new
`NSMutableParagraphStyle` is used.

```swift
let attributedString = "Hello World".paragraphStyle {
    $0.firstLineHeadIndent = 10
}
```

#### paragraphStyle(_:)

Applies the given paragraph style.

```swift
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.firstLineHeadIndent = 10
let attributedString = "text".paragraphStyle(paragraphStyle)
```

#### color(_:)

Applies the given (foreground) color.

```swift
let attributedString = "text".color(.blue)
```

#### backgroundColor(_:)

Applies the given background color.

```swift
let attributedString = "text".backgroundColor(.yellow)
```

#### ligature(_:)

Configures whether or not to use ligatures. Default is that they are used.

```swift
let attributedString = "text".ligature(false)
```

#### kern(_:)

Configures the amount with which to modify the default kerning. The default `0`
means that no kerning change is applied.

```swift
let attributedString = "text".kern(0.1)
```

#### strikeThrough(style:)

Configures the strike through style. Please note that depending on OS and
version not all styles may actually work.

```swift
let attributedString = "text".strikeThrough(style: .styleSingle)
```

#### strikeThrough(color:)

Configures the strike through color. Only setting the color has no effect, the
style must be configured as well.

```swift
let attributedString = "text".strikeThrough(color: .red)
```

#### strikeThrough(color:, style:)

Configures both the strike through color and style. Please note that depending
on OS and version not all styles may actually work.

```swift
let attributedString = "text".strikeThrough(color: .red, style: .styleDouble)
```

#### underline(style:)

Configures the underline style. Please note that depending on OS and version not
all styles may actually work.

```swift
let attributedString = "text".underline(style: .styleSingle)
```

#### underline(color:)

Configures the underline color. Only setting the color has no effect, the style
must be configured as well.

```swift
let attributedString = "text".underline(color: .blue)
```

#### underline(color:, style:)

Configures both the underline color and style. Please note that depending on OS
and version not all styles may actually work.

```swift
let attributedString = "text".underline(color: .blue, style: .styleSingle)
```

#### stroke(width:, color:)

Configures the stroke.

```swift
let attributedString = "text".stroke(width: 2, color: .green)
```

#### shadow(configure:)

Configures the shadow using a closure that receives
an `NSShadow` instance. Not available on watchOS.

```swift
let result = "Hello World".shadow {
    $0.shadowOffset = CGSize(width: 3, height: 3)
    $0.shadowBlurRadius = 2
    $0.shadowColor = Color.gray
}
```

#### shadow(_:)

Configures the shadow by setting an `NSShadow` instance. Not available on
watchOS.

```swift
let shadow = NSShadow()
shadow.shadowColor = .green
shadow.shadowBlurRadius = 2
shadow.shadowOffset = 3
let attributedString = "text".shadow(shadow)
```

#### letterPressed()

Adds the "letter pressed" text effect.

```swift
let attributedString = "text".letterPressed()
```

#### link(url:)

Creates hyperlink to the given URL with the receiver as text.

```swift
let url = URL(string: "https://example.com")
let attributedString = "text".link(url: url)
```

#### link(string:)

Creates hyperlink to the given URL with the receiver as text.

```swift
let urlString = "https://example.com"
let attributedString = "text".link(string: urlString)
```

#### attachment(configure:)

Creates a new `NSTextAttachment` and passes it to the `configure` closure. Not
available on watchOS.

```swift
let attributedString = NSAttributedString().attachment {
    $0.image = UIImage(...)
    $0.bounds = CGRect(...)
}
```

#### baselineOffset(_:)

Configures the baseline offset.

```swift
let attributedString = "text".baselineOffset(-0.5)
```

#### obliqueness(_:)

Configures the skew to be applied to glyphs.

```swift
let attributedString = "text".obliqueness(1.5)
```

#### expansion(_:)

Configures the expansion to be applied to glyphs.

```swift
let attributedString = "text".expansion(2)
```

### `NSAttributedString` Extension for Getting Attribute Values

All of the above methods have corresponding getters to retrieve the attribute
values from the attributed string. The all return an optional; if the attribute
is not configured on the attributed string, `nil` will be returned.

The getters are:

- `attachment: NSTextAttachment?` (not available on watchOS)
- `backgroundColor: Color?`
- `baselineOffset: Float?`
- `color: Color?`
- `expansion: Float?`
- `fontSize: CGFloat?`
- `isLetterPressed: Bool?`
- `kern: Float?`
- `ligature: Bool?`
- `link: NSURL?`
- `obliqueness: Float?`
- `paragraphStyle: NSParagraphStyle?`
- `shadow: NSShadow?` (not available on watchOS)
- `strikeThroughColor: Color?`
- `strikeThroughStyle: NSUnderlineStyle?`
- `strokeColor: Color?`
- `strokeWidth: Float?`
- `underlineColor: Color?`
- `underlineStyle: NSUnderlineStyle?`

## Usage

You can use the library any way you like, but two easy ways are Carthage and
CocoaPods. For CocoaPods, put `pod RichString` in your `Podfile`.

## Alternative Frameworks

Back when I started, I found a couple other frameworks that have the same goal
as this one: simplifying using `NSAttributedString`. I like mine better, mostly
because it has a simpler API that doesn't use any additional types. But I'll let
you choose for yourself. I haven't researched this anymore after that, so this
is probably outdated.

[TextAttributes](https://github.com/delba/TextAttributes) is similar to this
framework, but it introduces a new type that you have to set up the attributes,
instead of working directly on the strings themselves. It doesn't feature the
cool closure-based way of setting up `shadow { ... }` and `paragraphStyle { ...
}` that this framework has. And it doesn't provide the super-convenient `+`
operator that this framework does. Finally, I didn't test this framework on tvOS
and watchOS. I'm rather confident that those will work as well, but you'll have
to try. Pull requests are wellcome of course.

[TextAttributesUtil](https://github.com/muukii/TextAttributesUtil) also
introduces a new type for setting up the attributes. Also, it's API forces you
to have more levels of nesting in your source code. It only supports iOS, not
macOS.


text:
L = 0;  //Left position of the innerContentBox
T = 0;  //Top position of the innerContentBox
aMsg = new Array(); //Messages to show in the page
aToDoWhenLoaded = new Array(); //Array with some methods to execute when the page is loaded.

function toggle(id){
	obj = document.getElementById(id);
	if (obj.style.display=='none' || obj.style.display==''){
		obj.style.display = "block";
	} else	{
		obj.style.display = "none";
	}
	resizeInnerContentBox();
}

function writeMsg(i){
	txt = "";
	if (aMsg[i]){
		txt +="
" + aMsg[i][0] + "
\n";
		txt +="
" + aMsg[i][1] + "
\n";
		document.getElementById("msgBox").innerHTML = txt;
	}
}

function cb(){}
function resizeInnerContentBox(){}
function repositionMsgBox(){}
function repositionLoginBox(){}
function findPosX(obj){}
function findPosY(obj){}

function init(){
	objNav = document.getElementById("navigation");
	aLI = objNav.getElementsByTagName("li");
	if (navStatus>-1 && aLI[navStatus]){
		aLI[navStatus].className="on";
	}else{
		aLI[0].className="on";
	}

	if(aToDoWhenLoaded.length>0){
		for(iii=0;iii<aToDoWhenLoaded.length;iii++){
			eval(aToDoWhenLoaded[iii]);
		}
	}
}

window.onload   = init;
window.onresize = init;


text:
class PrefService;

namespace chromeos {

// BootTimesRecorder is used to record times of boot, login, and logout.
class BootTimesRecorder : public content::NotificationObserver,
                          public LoginEventRecorder::Delegate {
 public:
  BootTimesRecorder();
  virtual ~BootTimesRecorder();

  static BootTimesRecorder* Get();

  // LoginEventRecorder::Delegate override.
  virtual void AddLoginTimeMarker(const std::string& marker_name,
                                  bool send_to_uma) override;
  virtual void RecordAuthenticationSuccess() override;
  virtual void RecordAuthenticationFailure() override;

  // Add a time marker for logout. A timeline will be dumped to
  // /tmp/logout-times-sent after logout is done. If |send_to_uma| is true
  // the time between this marker and the last will be sent to UMA with
  // the identifier ShutdownTime.|marker_name|.
  void AddLogoutTimeMarker(const std::string& marker_name, bool send_to_uma);

  // Records current uptime and disk usage for metrics use.
  // Posts task to file thread.
  // name will be used as part of file names in /tmp.
  // Existing stats files will not be overwritten.
  void RecordCurrentStats(const std::string& name);

  // Saves away the stats at main, so the can be recorded later. At main() time
  // the necessary threads don't exist yet for recording the data.
  void SaveChromeMainStats();

  // Records the data previously saved by SaveChromeMainStats(), using the
  // file thread. Existing stats files will not be overwritten.
  void RecordChromeMainStats();

  // Records the time that a login was attempted. This will overwrite any
  // previous login attempt times.
  void RecordLoginAttempted();

  // content::NotificationObserver implementation.
  virtual void Observe(int type,
                       const content::NotificationSource& source,
                       const content::NotificationDetails& details) override;

  // Records "LoginDone" event.
  void LoginDone(bool is_user_new);

  // Writes the logout times to a /tmp/logout-times-sent. Unlike login
  // times, we manually call this function for logout times, as we cannot
  // rely on notification service to tell when the logout is done.
  void WriteLogoutTimes();

  // Mark that WriteLogoutTimes should handle restart.
  void set_restart_requested() { restart_requested_ = true; }

  // This is called on Chrome process startup to write saved logout stats.
  void OnChromeProcessStart();

  // This saves logout-started metric to Local State.
  void OnLogoutStarted(PrefService* state);

 private:
  class TimeMarker {
   public:
    TimeMarker(const std::string& name, bool send_to_uma)
        : name_(name),
          time_(base::Time::NowFromSystemTime()),
          send_to_uma_(send_to_uma) {}
    std::string name() const { return name_; }
    base::Time time() const { return time_; }
    bool send_to_uma() const { return send_to_uma_; }

    // comparitor for sorting
    bool operator<(const TimeMarker& other) const {
      return time_ < other.time_;
    }

   private:
    friend class std::vector<TimeMarker>;
    std::string name_;
    base::Time time_;
    bool send_to_uma_;
  };

  class Stats {
   public:
    // Initializes stats with current /proc values.
    static Stats GetCurrentStats();

    // Returns JSON representation.
    std::string SerializeToString() const;

    // Creates new object from JSON representation.
    static Stats DeserializeFromString(const std::string& value);

    const std::string& uptime() const { return uptime_; }
    const std::string& disk() const { return disk_; }

    // Writes "uptime in seconds" to result. (This is first field in uptime_.)
    // Returns true on successful conversion.
    bool UptimeDouble(double* result) const;

    void RecordStats(const std::string& name) const;
    void RecordStatsWithCallback(const std::string& name,
                                 const base::Closure& callback) const;

   private:
    // Runs on BlockingPool
    void RecordStatsImpl(const std::string& name) const;

    std::string uptime_;
    std::string disk_;
  };

  static void WriteTimes(const std::string base_name,
                         const std::string uma_name,
                         const std::string uma_prefix,
                         std::vector<TimeMarker> login_times);
  static void AddMarker(std::vector<TimeMarker>* vector, TimeMarker marker);

  // Clear saved logout-started metric in Local State.
  // This method is called when logout-state was writen to file.
  static void ClearLogoutStartedLastPreference();

  // Used to hold the stats at main().
  Stats chrome_main_stats_;

  // Used to track notifications for login.
  content::NotificationRegistrar registrar_;
  base::AtomicSequenceNumber num_tabs_;
  bool have_registered_;

  std::vector<TimeMarker> login_time_markers_;
  std::vector<TimeMarker> logout_time_markers_;
  std::set<content::RenderWidgetHost*> render_widget_hosts_loading_;

  bool login_done_;

  bool restart_requested_;

  DISALLOW_COPY_AND_ASSIGN(BootTimesRecorder);
};

}  // namespace chromeos

#endif  // CHROME_BROWSER_CHROMEOS_BOOT_TIMES_RECORDER_H_


text:
package io.yawp.driver.api;

public interface TransactionDriver {

	public TransactionDriver begin();

	public TransactionDriver beginX();

	public void rollback();

	public void commit();

}


text:
class Spec < ActiveRecord::Base
  belongs_to :user
  attr_accessible :first_name, :last_name, :gender, :birthdate,:occupation, :city, :state, :zip_code
 # attr_accessor :first_name, :last_name, :gender, :birthdate,:occupation, :city, :state, :zip_code

  ALL_FIELDS = %w(first_name last_name occupation gender birthdate city state zip_code)
  STRING_FIELDS = %w(first_name last_name occupation city state)
  VALID_GENDERS = ["Male","Female"]
  START_YEAR = 1900
  VALID_DATES = DateTime.new(START_YEAR)..DateTime.now
  ZIP_CODE_LENGTH = 5
  validates_length_of STRING_FIELDS,:maximum => DB_STRING_MAX_LENGTH
  validates_inclusion_of :gender,
                         :in => VALID_GENDERS,
                         :allow_nil => true,
                         :message => "must be male or female"
  validates_inclusion_of :birthdate,
    :in => VALID_DATES,
    :allow_nil => true,
    :message => "is invalid"
  validates_format_of :zip_code,:with => /(^$|^[0-9]{#{ZIP_CODE_LENGTH}}$)/,
                                :message => "must be a five digit number"

  def full_name
    [first_name,last_name].join(" ")
  end

  def location
    [city,state,zip_code].join(" ")
  end

  def age
    return if birthdate.nil?
    today = Time.current
    if today.month >= birthdate.month and today.day >= birthdate.day
      today.year - birthdate.year
    else
      today.year - birthdate.year - 1
    end
  end
end


text:
import { Label as LabelDefinition } from '.';
import { Background } from '../styling/background';
import { Length, borderTopWidthProperty, borderRightWidthProperty, borderBottomWidthProperty, borderLeftWidthProperty, paddingTopProperty, paddingRightProperty, paddingBottomProperty, paddingLeftProperty } from '../styling/style-properties';
import { booleanConverter } from '../core/view-base';
import { View, CSSType } from '../core/view';
import { CoreTypes } from '../../core-types';
import { TextBase, whiteSpaceProperty } from '../text-base';
import { layout } from '../../utils';

import { ios } from '../styling/background';

enum FixedSize {
	NONE = 0,
	WIDTH = 1,
	HEIGHT = 2,
	BOTH = 3,
}

@CSSType('Label')
export class Label extends TextBase implements LabelDefinition {
	nativeViewProtected: TNSLabel;
	private _fixedSize: FixedSize;

	public createNativeView() {
		const view = TNSLabel.new();
		view.userInteractionEnabled = true;

		return view;
	}

	// @ts-ignore
	get ios(): TNSLabel {
		return this.nativeTextViewProtected;
	}

	get textWrap(): boolean {
		return this.style.whiteSpace === 'normal';
	}
	set textWrap(value: boolean) {
		if (typeof value === 'string') {
			value = booleanConverter(value);
		}

		this.style.whiteSpace = value ? 'normal' : 'nowrap';
	}

	_requestLayoutOnTextChanged(): void {
		if (this._fixedSize === FixedSize.BOTH) {
			return;
		}
		if (this._fixedSize === FixedSize.WIDTH && !this.textWrap && this.getMeasuredHeight() > 0) {
			// Single line label with fixed width will skip request layout on text change.
			return;
		}
		super._requestLayoutOnTextChanged();
	}

	public onMeasure(widthMeasureSpec: number, heightMeasureSpec: number): void {
		const nativeView = this.nativeTextViewProtected;
		if (nativeView) {
			const width = layout.getMeasureSpecSize(widthMeasureSpec);
			const widthMode = layout.getMeasureSpecMode(widthMeasureSpec);

			const height = layout.getMeasureSpecSize(heightMeasureSpec);
			const heightMode = layout.getMeasureSpecMode(heightMeasureSpec);

			this._fixedSize = (widthMode === layout.EXACTLY ? FixedSize.WIDTH : FixedSize.NONE) | (heightMode === layout.EXACTLY ? FixedSize.HEIGHT : FixedSize.NONE);

			let nativeSize;
			if (this.textWrap) {
				// https://github.com/NativeScript/NativeScript/issues/4834
				// NOTE: utils.measureNativeView(...) relies on UIView.sizeThatFits(...) that
				// seems to have various issues when laying out UILabel instances.
				// We use custom measure logic here that relies on overriden
				// UILabel.textRectForBounds:limitedToNumberOfLines: in TNSLabel widget.
				nativeSize = this._measureNativeView(width, widthMode, height, heightMode);
			} else {
				// https://github.com/NativeScript/NativeScript/issues/6059
				// NOTE: _measureNativeView override breaks a scenario with StackLayout that arranges
				// labels horizontally (with textWrap=false) e.g. we are measuring label #2 within 356px,
				// label #2 needs more, and decides to show ellipsis(...) but because of this its native size
				// returned from UILabel.textRectForBounds:limitedToNumberOfLines: logic becomes 344px, so
				// StackLayout tries to measure label #3 within the remaining 12px which is wrong;
				// label #2 with ellipsis should take the whole 356px and label #3 should not be visible at all.
				nativeSize = layout.measureNativeView(nativeView, width, widthMode, height, heightMode);
			}

			let labelWidth = nativeSize.width;

			if (this.textWrap && widthMode === layout.AT_MOST) {
				labelWidth = Math.min(labelWidth, width);
			}

			const measureWidth = Math.max(labelWidth, this.effectiveMinWidth);
			const measureHeight = Math.max(nativeSize.height, this.effectiveMinHeight);

			const widthAndState = View.resolveSizeAndState(measureWidth, width, widthMode, 0);
			const heightAndState = View.resolveSizeAndState(measureHeight, height, heightMode, 0);

			this.setMeasuredDimension(widthAndState, heightAndState);
		}
	}

	private _measureNativeView(width: number, widthMode: number, height: number, heightMode: number): { width: number; height: number } {
		const view = <UILabel>this.nativeTextViewProtected;

		const nativeSize = view.textRectForBoundsLimitedToNumberOfLines(CGRectMake(0, 0, widthMode === 0 /* layout.UNSPECIFIED */ ? Number.POSITIVE_INFINITY : layout.toDeviceIndependentPixels(width), heightMode === 0 /* layout.UNSPECIFIED */ ? Number.POSITIVE_INFINITY : layout.toDeviceIndependentPixels(height)), view.numberOfLines).size;

		nativeSize.width = layout.round(layout.toDevicePixels(nativeSize.width));
		nativeSize.height = layout.round(layout.toDevicePixels(nativeSize.height));

		return nativeSize;
	}

	[whiteSpaceProperty.setNative](value: CoreTypes.WhiteSpaceType) {
		const nativeView = this.nativeTextViewProtected;
		switch (value) {
			case 'normal':
				nativeView.lineBreakMode = NSLineBreakMode.ByWordWrapping;
				nativeView.numberOfLines = this.maxLines;
				break;
			case 'nowrap':
			case 'initial':
				nativeView.lineBreakMode = NSLineBreakMode.ByTruncatingTail;
				nativeView.numberOfLines = 1;
				break;
		}
	}

	_redrawNativeBackground(value: UIColor | Background): void {
		if (value instanceof Background) {
			ios.createBackgroundUIColor(
				this,
				(color: UIColor) => {
					const cgColor = color ? color.CGColor : null;
					this.nativeTextViewProtected.layer.backgroundColor = cgColor;
				},
				true
			);
		}

		this._setNativeClipToBounds();
	}

	[borderTopWidthProperty.setNative](value: CoreTypes.LengthType) {
		const nativeView = this.nativeTextViewProtected;
		const border = nativeView.borderThickness;
		nativeView.borderThickness = {
			top: layout.toDeviceIndependentPixels(this.effectiveBorderTopWidth),
			right: border.right,
			bottom: border.bottom,
			left: border.left,
		};
	}

	[borderRightWidthProperty.setNative](value: CoreTypes.LengthType) {
		const nativeView = this.nativeTextViewProtected;
		const border = nativeView.borderThickness;
		nativeView.borderThickness = {
			top: border.top,
			right: layout.toDeviceIndependentPixels(this.effectiveBorderRightWidth),
			bottom: border.bottom,
			left: border.left,
		};
	}

	[borderBottomWidthProperty.setNative](value: CoreTypes.LengthType) {
		const nativeView = this.nativeTextViewProtected;
		const border = nativeView.borderThickness;
		nativeView.borderThickness = {
			top: border.top,
			right: border.right,
			bottom: layout.toDeviceIndependentPixels(this.effectiveBorderBottomWidth),
			left: border.left,
		};
	}

	[borderLeftWidthProperty.setNative](value: CoreTypes.LengthType) {
		const nativeView = this.nativeTextViewProtected;
		const border = nativeView.borderThickness;
		nativeView.borderThickness = {
			top: border.top,
			right: border.right,
			bottom: border.bottom,
			left: layout.toDeviceIndependentPixels(this.effectiveBorderLeftWidth),
		};
	}

	[paddingTopProperty.setNative](value: CoreTypes.LengthType) {
		const nativeView = this.nativeTextViewProtected;
		const padding = nativeView.padding;
		nativeView.padding = {
			top: layout.toDeviceIndependentPixels(this.effectivePaddingTop),
			right: padding.right,
			bottom: padding.bottom,
			left: padding.left,
		};
	}

	[paddingRightProperty.setNative](value: CoreTypes.LengthType) {
		const nativeView = this.nativeTextViewProtected;
		const padding = nativeView.padding;
		nativeView.padding = {
			top: padding.top,
			right: layout.toDeviceIndependentPixels(this.effectivePaddingRight),
			bottom: padding.bottom,
			left: padding.left,
		};
	}

	[paddingBottomProperty.setNative](value: CoreTypes.LengthType) {
		const nativeView = this.nativeTextViewProtected;
		const padding = nativeView.padding;
		nativeView.padding = {
			top: padding.top,
			right: padding.right,
			bottom: layout.toDeviceIndependentPixels(this.effectivePaddingBottom),
			left: padding.left,
		};
	}

	[paddingLeftProperty.setNative](value: CoreTypes.LengthType) {
		const nativeView = this.nativeTextViewProtected;
		const padding = nativeView.padding;
		nativeView.padding = {
			top: padding.top,
			right: padding.right,
			bottom: padding.bottom,
			left: layout.toDeviceIndependentPixels(this.effectivePaddingLeft),
		};
	}
}

Label.prototype.recycleNativeView = 'auto';


text:
cask 'x-lite' do
  version '5.5.0_97576'
  sha256 '85a0b7e48a12bb6d4aecf48b0180f9fd2a5f491bd6170bbf5d8350cdbc56e582'

  # counterpath.s3.amazonaws.com was verified as official when first introduced to the cask
  url "https://counterpath.s3.amazonaws.com/downloads/X-Lite_#{version}.dmg"
  appcast 'https://www.macupdater.net/cgi-bin/check_urls/check_url_redirect.cgi?url=https://www.counterpath.com/XLiteForMac'
  name 'X-Lite'
  homepage 'https://www.counterpath.com/x-lite/'

  app 'X-Lite.app'
end


text:
'use strict';

var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();

// Extends jquery ajaxTransport too support binary reading of files
// Method taken from http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/
$.ajaxTransport("+binary", function (options, originalOptions, jqXHR) {
    // check for conditions and support for blob / arraybuffer response type
    if (window.FormData && ((options.dataType && (options.dataType == 'binary')) ||
        (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) ||
        (window.Blob && options.data instanceof Blob))))) {
        return {
            // create new XMLHttpRequest
            send: function (headers, callback) {
                // setup all variables
                var xhr = new XMLHttpRequest(),
		        url = options.url,
		        type = options.type,
		        async = options.async || true,
		        // blob or arraybuffer. Default is blob
		        dataType = options.responseType || "blob",
		        data = options.data || null,
		        username = options.username || null,
		        password = options.password || null;

                xhr.addEventListener('load', function () {
                    var data = {};
                    data[options.dataType] = xhr.response;
                    // make callback and send data
                    callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders());
                });

                xhr.open(type, url, async, username, password);

                // setup custom headers
                for (var i in headers) {
                    xhr.setRequestHeader(i, headers[i]);
                }

                xhr.responseType = dataType;
                xhr.send(data);
            },
            abort: function () {
                jqXHR.abort();
            }
        };
    }
});

var hostWebUrl,
    appWebUrl,
    hostWebContext,
    destinationServerRelativeUrl,
    destinationFileName;

// Define base object
Type.registerNamespace("BinaryUpload");

BinaryUpload.Uploader = function () {

    var hostWebUrl,
        hostWebContext,
        appWebUrl;

    var state = {
        ERROR: "error",
        WARNING: "warning",
        SUCCESS: "success"
    }

    // Read the Host Web Url and the App Web Url from query string
    var init = function () {
        var hostWebUrlFromQS = $.getUrlVar("SPHostUrl");
        hostWebUrl = (hostWebUrlFromQS !== undefined) ? decodeURIComponent(hostWebUrlFromQS) : undefined;

        var appWebUrlFromQS = $.getUrlVar("SPAppWebUrl");
        appWebUrl = (appWebUrlFromQS !== undefined) ? decodeURIComponent(appWebUrlFromQS) : undefined;
    };

    var logMessage = function (logMessage, status) {
        var message = String.format("
{1}
", status, logMessage);
        $("#msgBinUpload").append(message);
    };
    var clearMessages = function () {
        $("#msgBinUpload").text("");
    };
    var executeUpload = function (sourcePath, targetPath) {

        // initialise base variables base from query string
        init();
        clearMessages();

        hostWebContext = new SP.ClientContext(getRelativeUrlFromAbsolute(hostWebUrl));
        var web = hostWebContext.get_web();

        hostWebContext.load(web);
        hostWebContext.executeQueryAsync(
            // in case of success
            function () {
                logMessage("Host Web successfully loaded", state.SUCCESS);

                var sourceFile = appWebUrl + sourcePath;
                logMessage("Reading file from App Web " + sourcePath + "

", state.SUCCESS);
                logMessage("
", state.SUCCESS);
                // Read file from app web
                $.ajax({
                    url: sourceFile,
                    type: "GET",
                    dataType: "binary",
                    processData: false,
                    responseType: 'arraybuffer',
                    cache: false
                }).done(function (contents) {

                    var fileName = getFilenameFromUrl(targetPath);
                    var folder = getPathFromUrl(targetPath);

                    logMessage("Create file at
    " + hostWebUrl + "/" + folder + fileName, state.SUCCESS);

                    // Create new file
                    var createInfo = new SP.FileCreationInformation();

                    // Convert ArrayBuffer to Base64 string
                    createInfo.set_content(arrayBufferToBase64(contents));

                    // Overwrite if already exists
                    createInfo.set_overwrite(true);

                    // set target url
                    createInfo.set_url(fileName);

                    // retrieve file collection of folder
                    var files = hostWebContext.get_web().getFolderByServerRelativeUrl(getRelativeUrlFromAbsolute(hostWebUrl) + folder).get_files();

                    // load file collection from host web
                    hostWebContext.load(files);

                    // add the new file
                    files.add(createInfo);

                    // upload file
                    hostWebContext.executeQueryAsync(function () {

                        var loadImage = hostWebUrl + "/" + folder + fileName;
                        logMessage("File uploaded succeeded", state.SUCCESS);
                        logMessage("Try to embed file from host web

", state.SUCCESS);
                        logMessage("", state.SUCCESS);
                        logMessage("" + folder + fileName + "", state.SUCCESS);
                        logMessage("File was successfully uploaded as binary file
Image can be loaded successfully.", state.SUCCESS);

                    }, function (sender, args) {

                        logMessage("File upload failed "+args.get_message(), state.ERROR);

                    });

                }).fail(function (jqXHR, textStatus) {
                    logMessage(textStatus, state.ERROR);
                    logMessage("File '" + appWebUrl + sourcePath + "' failed.
"+textStatus);
                });

            },
            // in case of error
            function (sender, args) {
                logMessage(args.get_message(), state.ERROR);
            })

    }

    var getRelativeUrlFromAbsolute = function (absoluteUrl) {
        absoluteUrl = absoluteUrl.replace('https://', '');

        var parts = absoluteUrl.split('/');
        var relativeUrl = '/';

        for (var i = 1; i < parts.length; i++) {
            relativeUrl += parts[i] + '/';
        }

        return relativeUrl;

    }

    var getFilenameFromUrl = function (url) {

        var filename = url.substring(url.lastIndexOf('/') + 1);
        return filename;

    }

    var getPathFromUrl = function (url) {

        var path = url.substring(1, url.lastIndexOf('/') + 1);
        return path;

    }

    var arrayBufferToBase64 = function (buffer) {
        var binary = '';
        var bytes = new Uint8Array(buffer);
        var len = bytes.byteLength;
        for (var i = 0; i < len; i++) {
            binary += String.fromCharCode(bytes[i]);
        }
        return window.btoa(binary);
    }

    return {
        Upload: function (sourcePath, targetPath) {

            executeUpload(sourcePath, targetPath);

        }
    }

}


text:
package br.edu.eribeiro;

import org.jboss.byteman.contrib.bmunit.BMScript;
import org.jboss.byteman.contrib.bmunit.BMUnitConfig;
import org.jboss.byteman.contrib.bmunit.BMUnitRunner;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@RunWith(BMUnitRunner.class)
@BMUnitConfig(loadDirectory="target/test-classes", debug=true)
@BMScript(value="check.btm")
public class ScriptBytemanTest {

    @Test
    public void testFooWithScript() {
        new Foo().call();
    }

// TODO: the Byteman rule has some error(s)
//    @Test(expected = IOException.class)
//    public void testFileInputStream() throws IOException {
//        File tmpFile = File.createTempFile("test-", ".txt");
//        try (FileOutputStream fis =  new FileOutputStream(tmpFile)) {
//            fis.write("Hello".getBytes());
//            fis.write("Hello".getBytes());
//            fis.write("Hello".getBytes());
//        }
//    }
}


text:
{% extends "sentry/teams/groups/details.html" %}

{% load crispy_forms_tags %}
{% load i18n %}

{% block title %}{% trans "Remove Access Group" %} | {{ block.super }}{% endblock %}

{% block main %}

        <form action="" method="post">

{% trans "Are you sure you wish to remove this access group? This change is permanent!" %}

            {% csrf_token %}
            {{ form|as_crispy_errors }}
            {% for field in form %}
                {{ field|as_crispy_field }}
            {% endfor %}
            <fieldset class="form-actions">
                <button type="submit" class="btn btn-danger">{% trans "Confirm" %}</button> {% trans "Cancel" %}
            </fieldset>
        </form>

{% endblock %}


text:
'use strict'

const superagent = require('superagent')

const Candidate = require('./models/candidate')

const CANDIDATE_ID = 'candidate_name'

const baseUrl = 'https://services2.arcgis.com/tuFQUQg1xd48W6M5/arcgis/rest/services/PowerBallotHI2018P/FeatureServer/1/query'

const result = superagent.get(baseUrl)
  .query({
    where: "1=1",
    outFields: '*',
    f: 'pjson',
  })

function setCandidateContestId(candidateName, contestAbbr) {
  return Candidate.where({ [CANDIDATE_ID]:candidateName})
    .save({contest_id: contestAbbr}, {patch:true})
    .then(function(x) {
      console.log(x.toJSON().contest_id)
    })
}

return result.then((data) => {
  const candidates = JSON.parse(data.text).features

  let contestsToAbbr = {}
  candidates.map (data => {
    const candidate = data.attributes
    delete candidate.OBJECTID

    const candidateName = candidate.Ballot_Name
    const contestAbbr = candidate.Contest_Abbr
    contestsToAbbr[candidate.Contests] = contestAbbr

    setCandidateContestId(candidateName, contestAbbr)
  })

  // Ensure/log that we were properly mapping the full name to abbreviation
  console.log(contestsToAbbr)
})


text:
namespace submissiv.commandline
{
    public enum CommandOptionType
    {
        MultipleValue,
        SingleValue,
        NoValue
    }
}


text:
module Matrix
  class MainMatrix < Matrix::Base

    attr_reader :result

    def accumulate_by sub_matrix
      current_value = 0
      sub_matrix.each do |element|
        x = element.x_index
        y = element.y_index
        @rows[y] ||= []
        main_element_value = @rows[y][x].to_i
        current_value += main_element_value
        set x: x, y: y, value: current_value
      end
      @result = current_value
      @result_matrix
    end

    def set options={}
      @result_matrix ||= @rows.clone
      @result_matrix[options[:y]][options[:x]] = options[:value]
    end

  end
end


text:
![HistoryX for Chrome](https://www.fyianlai.com/img/historyx.png)

[![Install via Chrome Web Store](https://developer.chrome.com/webstore/images/ChromeWebStore_Badge_v2_206x58.png)][install]

_A work in progress._

A Chrome extension to enhance your browsing history experience.

[Announcement][announcement] | [Screenshot (v2.4.0)][screenshot]

[install]: https://goo.gl/d8D1JP
[announcement]: https://www.fyianlai.com/2015/09/introducing-historyx-for-chrome/
[screenshot]: http://i.imgur.com/cbZpdSo.png


text:
function distance = collisionRaycast(obj, kinsol, origins, ray_endpoints, ...
  use_margins)
% function distance = collisionRaycast(obj,kinsol, origin, point_on_ray)
%
% Uses bullet to perform a raycast, returning the distance or -1 on no hit.
%
% See systems/plants/test/bullet_raycast_test.m for example usage.
%
% @param kinsol result of calling doKinematics(obj, q) where q is a
%   position vector.
% @param origin vector of size indicating the origin of the ray. Size is
%   3 x N.
% @param ray_endpoint vector of size 3 indicating the end point of the ray,
%   specifying the direction and maximum length of the raycast.
%   Size is 3 x N.
% @param use_margins boolean indicating whether or not to use a collision
%   model whose boxes and meshes are padded with a margin to improve
%   numerical stability of contact gradient. Default true.
%
% @retval distance distance to the nearest hit on the ray, or -1 on no
%    collision.

if (nargin < 5)
  use_margins = true;
end

checkDependency('bullet');

if (obj.mex_model_ptr == 0)
  error('RigidBodyManipulator:collisionRaycast:MexPtrZero', ...
    'Collision raycast requires a mex model (obj.mex_model_ptr == 0 for you)');
end

if ~isstruct(kinsol)
  % treat input as collisionRaycast(obj,q,origin,ray_endpoint)
  kinsol = doKinematics(obj,kinsol);
end

if (kinsol.mex ~= true)
  error('RigidBodyManipulator:collisionRaycast:kinsolMex', ...
    'Call doKinematics using mex before proceeding (got kinsol.mex ~= true).');
end

distance = collisionRaycastmex(obj.mex_model_ptr, kinsol.mex_ptr, origins, ray_endpoints, use_margins);