text:
$(document).ready(function()
{
    // Fixes selection bugs when you click on the slider or empty space.
    $("select.multi-select").mousedown(function(event)
    {
        return false;
    });

    var options = $("select.multi-select option");

    options.unbind("click").click(option_click_event);

    // This is necessary to fix "click and drag scrolling on the options" bug in Chrome
    options.mousemove(option_mousemove_event);
});

function option_click_event(event)
{
    $(this).prop("selected", !$(this).prop("selected"));

    return false;
}

// This is necessary to fix "click and drag scrolling on the options" bug in Chrome
function option_mousemove_event(event)
{
    return false;
}


text:
<?php

namespace Magento\Vault\Test\TestStep;

use Magento\Customer\Test\Fixture\Customer;
use Magento\Customer\Test\Page\CustomerAccountIndex;
use Magento\Mtf\Fixture\FixtureFactory;
use Magento\Mtf\Fixture\InjectableFixture;
use Magento\Mtf\ObjectManager;
use Magento\Mtf\TestStep\TestStepInterface;
use Magento\Vault\Test\Constraint\AssertStoredPaymentDeletedMessage;
use Magento\Vault\Test\Page\StoredPaymentMethods;

/**
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class DeleteCreditCardFromMyAccountStep implements TestStepInterface
{
    /**
     * @var Customer
     */
    private $customer;

    /**
     * @var ObjectManager
     */
    private $objectManager;

    /**
     * @var CustomerAccountIndex
     */
    private $customerAccountIndex;

    /**
     * @var FixtureFactory
     */
    private $fixtureFactory;

    /**
     * @var \Magento\Mtf\Fixture\FixtureInterface
     */
    private $creditCard;

    /**
     * @var AssertStoredPaymentDeletedMessage
     */
    private $assertStoredPaymentDeletedMessage;

    /**
     * @var StoredPaymentMethods
     */
    private $storedPaymentMethodsPage;

    /**
     * DeleteCreditCardFromMyAccountStep constructor.
     *
     * @param StoredPaymentMethods $storedPaymentMethodsPage
     * @param Customer $customer
     * @param ObjectManager $objectManager
     * @param CustomerAccountIndex $customerAccountIndex
     * @param FixtureFactory $fixtureFactory
     * @param AssertStoredPaymentDeletedMessage $assertStoredPaymentDeletedMessage
     * @param array $creditCard
     * @param string $creditCardClass
     */
    public function __construct(
        StoredPaymentMethods $storedPaymentMethodsPage,
        Customer $customer,
        ObjectManager $objectManager,
        CustomerAccountIndex $customerAccountIndex,
        FixtureFactory $fixtureFactory,
        AssertStoredPaymentDeletedMessage $assertStoredPaymentDeletedMessage,
        array $creditCard,
        $creditCardClass = 'credit_card'
    ) {
        $this->storedPaymentMethodsPage = $storedPaymentMethodsPage;
        $this->customer = $customer;
        $this->objectManager = $objectManager;
        $this->customerAccountIndex = $customerAccountIndex;
        $this->fixtureFactory = $fixtureFactory;
        $this->assertStoredPaymentDeletedMessage = $assertStoredPaymentDeletedMessage;
        $this->creditCard = $fixtureFactory->createByCode($creditCardClass, ['dataset' => $creditCard['dataset']]);
    }

    /**
     * @inheritdoc
     *
     * @return array
     */
    public function run()
    {
        $this->objectManager->create(
            \Magento\Customer\Test\TestStep\LoginCustomerOnFrontendStep::class,
            ['customer' => $this->customer]
        )->run();
        $this->customerAccountIndex->getAccountMenuBlock()->openMenuItem('Stored Payment Methods');
        $storedPaymentsBlock = $this->storedPaymentMethodsPage->getStoredPaymentsBlock();

        $creditCardData = $this->creditCard->getData();
        $creditCardNumber = preg_grep('/([a-z]+)_number/', array_flip($creditCardData));
        $lastFourDigits = substr(key($creditCardNumber), -4, 4);

        $availableCreditCards = $storedPaymentsBlock->getCreditCards();
        if (key_exists($lastFourDigits, $availableCreditCards)) {
            $storedPaymentsBlock->deleteCreditCard($availableCreditCards[$lastFourDigits]);
        }
        $this->assertStoredPaymentDeletedMessage->processAssert($this->storedPaymentMethodsPage);

        return ['deletedCreditCard' => $lastFourDigits];
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace distbench {

ProtocolDriverOptions PdoFromString(const std::string& s) {
  ProtocolDriverOptions pdo;
  google::protobuf::TextFormat::ParseFromString(s, &pdo);
  return pdo;
}

class ProtocolDriverTest : public testing::TestWithParam<std::string> {};

TEST_P(ProtocolDriverTest, Allocate) {
  ProtocolDriverOptions pdo = PdoFromString(GetParam());
  int port = 0;
  auto maybe_pd = AllocateProtocolDriver(pdo, &port);
  ASSERT_OK(maybe_pd.status());
}

TEST_P(ProtocolDriverTest, SetNumPeers) {
  ProtocolDriverOptions pdo = PdoFromString(GetParam());
  int port = 0;
  auto maybe_pd = AllocateProtocolDriver(pdo, &port);
  ASSERT_OK(maybe_pd.status());
  auto& pd = maybe_pd.value();
  pd->SetNumPeers(1);
  pd->SetHandler([](ServerRpcState* s) {
    ADD_FAILURE() << "should not get here";
    return std::function<void()>();
  });
}

TEST_P(ProtocolDriverTest, GetConnectionHandle) {
  ProtocolDriverOptions pdo = PdoFromString(GetParam());
  int port = 0;
  auto maybe_pd = AllocateProtocolDriver(pdo, &port);
  ASSERT_OK(maybe_pd.status());
  auto& pd = maybe_pd.value();
  pd->SetNumPeers(1);
  std::atomic<int> server_rpc_count = 0;
  pd->SetHandler([&](ServerRpcState* s) {
    ++server_rpc_count;
    return std::function<void()>();
  });
  std::string addr = pd->HandlePreConnect("", 0).value();
  ASSERT_EQ(server_rpc_count, 0);
}

TEST_P(ProtocolDriverTest, HandleConnect) {
  ProtocolDriverOptions pdo = PdoFromString(GetParam());
  int port = 0;
  auto maybe_pd = AllocateProtocolDriver(pdo, &port);
  ASSERT_OK(maybe_pd.status());
  auto& pd = maybe_pd.value();
  pd->SetNumPeers(1);
  std::atomic<int> server_rpc_count = 0;
  pd->SetHandler([&](ServerRpcState* s) {
    ++server_rpc_count;
    return std::function<void()>();
  });
  std::string addr = pd->HandlePreConnect("", 0).value();
  ASSERT_OK(pd->HandleConnect(addr, 0));
  ASSERT_EQ(server_rpc_count, 0);
}

TEST_P(ProtocolDriverTest, Invoke) {
  ProtocolDriverOptions pdo = PdoFromString(GetParam());
  int port = 0;
  auto maybe_pd = AllocateProtocolDriver(pdo, &port);
  ASSERT_OK(maybe_pd.status());
  auto& pd = maybe_pd.value();
  pd->SetNumPeers(1);
  std::atomic<int> server_rpc_count = 0;
  pd->SetHandler([&](ServerRpcState* s) {
    ++server_rpc_count;
    if (s->have_dedicated_thread) {
      std::string str;
      s->request->SerializeToString(&str);
      s->SendResponseIfSet();
      s->FreeStateIfSet();
      return std::function<void()>();
    } else {
      std::function<void()> fct = [=]() {
        usleep(100'000);
        std::string str;
        s->request->SerializeToString(&str);
        s->SendResponseIfSet();
        s->FreeStateIfSet();
      };
      return fct;
    }
  });
  std::string addr = pd->HandlePreConnect("", 0).value();
  ASSERT_OK(pd->HandleConnect(addr, 0));

  std::atomic<int> client_rpc_count = 0;
  const int kNumIterations = 1000;
  ClientRpcState rpc_state[kNumIterations];
  for (int i = 0; i < kNumIterations; ++i) {
    pd->InitiateRpc(0, &rpc_state[i], [&, i]() {
      if (rpc_state[i].success) ++client_rpc_count;
    });
  }
  pd->ShutdownClient();

  EXPECT_EQ(server_rpc_count, kNumIterations);
  EXPECT_EQ(client_rpc_count, kNumIterations);
}

TEST_P(ProtocolDriverTest, SelfEcho) {
  ProtocolDriverOptions pdo = PdoFromString(GetParam());
  int port = 0;
  auto maybe_pd = AllocateProtocolDriver(pdo, &port);
  ASSERT_OK(maybe_pd.status());
  auto& pd = maybe_pd.value();
  pd->SetNumPeers(1);
  std::atomic<int> server_rpc_count = 0;
  pd->SetHandler([&](ServerRpcState* s) {
    ++server_rpc_count;
    s->response.set_payload(s->request->payload());
    s->SendResponseIfSet();
    s->FreeStateIfSet();
    return std::function<void()>();
  });
  std::string addr = pd->HandlePreConnect("", 0).value();
  ASSERT_OK(pd->HandleConnect(addr, 0));

  std::atomic<int> client_rpc_count = 0;
  ClientRpcState rpc_state;
  rpc_state.request.set_payload("ping!");
  pd->InitiateRpc(0, &rpc_state, [&]() {
    ++client_rpc_count;
    EXPECT_EQ(rpc_state.request.payload(), rpc_state.response.payload());
    EXPECT_EQ(rpc_state.response.payload(), "ping!");
  });
  pd->ShutdownClient();
  EXPECT_EQ(server_rpc_count, 1);
  EXPECT_EQ(client_rpc_count, 1);
}

TEST_P(ProtocolDriverTest, Echo) {
  ProtocolDriverOptions pdo = PdoFromString(GetParam());
  int port1 = 0;
  auto maybe_pd1 = AllocateProtocolDriver(pdo, &port1);
  ASSERT_OK(maybe_pd1.status());
  auto& pd1 = maybe_pd1.value();
  int port2 = 0;
  auto maybe_pd2 = AllocateProtocolDriver(pdo, &port2);
  ASSERT_OK(maybe_pd2.status());
  auto& pd2 = maybe_pd2.value();
  std::atomic<int> server_rpc_count = 0;
  pd2->SetNumPeers(1);
  pd2->SetHandler([&](ServerRpcState* s) {
    ++server_rpc_count;
    s->response.set_payload(s->request->payload());
    s->SendResponseIfSet();
    s->FreeStateIfSet();
    return std::function<void()>();
  });
  pd1->SetNumPeers(1);
  pd1->SetHandler([&](ServerRpcState* s) {
    ADD_FAILURE() << "should not get here";
    return std::function<void()>();
  });
  std::string addr1 = pd1->HandlePreConnect("", 0).value();
  std::string addr2 = pd2->HandlePreConnect("", 0).value();
  ASSERT_OK(pd1->HandleConnect(addr2, 0));
  ASSERT_OK(pd2->HandleConnect(addr1, 0));

  std::atomic<int> client_rpc_count = 0;
  ClientRpcState rpc_state;
  rpc_state.request.set_payload("ping!");
  pd1->InitiateRpc(0, &rpc_state, [&]() {
    ++client_rpc_count;
    EXPECT_EQ(rpc_state.request.payload(), rpc_state.response.payload());
    EXPECT_EQ(rpc_state.response.payload(), "ping!");
  });
  pd1->ShutdownClient();
  EXPECT_EQ(server_rpc_count, 1);
  EXPECT_EQ(client_rpc_count, 1);
}

void Echo(benchmark::State& state, std::string opts_string) {
  ProtocolDriverOptions opts = PdoFromString(opts_string);
  int port1 = 0;
  auto maybe_pd1 = AllocateProtocolDriver(opts, &port1);
  ASSERT_OK(maybe_pd1.status());
  auto& pd1 = maybe_pd1.value();
  int port2 = 0;
  auto maybe_pd2 = AllocateProtocolDriver(opts, &port2);
  ASSERT_OK(maybe_pd2.status());
  auto& pd2 = maybe_pd2.value();
  std::atomic<int> server_rpc_count = 0;
  pd2->SetNumPeers(1);
  pd2->SetHandler([&](ServerRpcState* s) {
    ++server_rpc_count;
    s->response.set_payload(s->request->payload());
    s->SendResponseIfSet();
    s->FreeStateIfSet();
    return std::function<void()>();
  });
  pd1->SetNumPeers(1);
  pd1->SetHandler([&](ServerRpcState* s) {
    ADD_FAILURE() << "should not get here";
    return std::function<void()>();
  });
  std::string addr1 = pd1->HandlePreConnect("", 0).value();
  std::string addr2 = pd2->HandlePreConnect("", 0).value();
  ASSERT_OK(pd1->HandleConnect(addr2, 0));
  ASSERT_OK(pd2->HandleConnect(addr1, 0));

  std::atomic<int> client_rpc_count = 0;
  ClientRpcState rpc_state;
  rpc_state.request.set_payload("ping!");
  for (auto s : state) {
    pd1->InitiateRpc(0, &rpc_state, [&]() {
      ++client_rpc_count;
      EXPECT_EQ(rpc_state.request.payload(), rpc_state.response.payload());
      EXPECT_EQ(rpc_state.response.payload(), "ping!");
    });
    pd1->ShutdownClient();
  }
}

std::string GrpcOptions() {
  ProtocolDriverOptions pdo;
  pdo.set_protocol_name("grpc");
  return pdo.DebugString();
}

std::string GrpcAsynCallbackOptions() {
  ProtocolDriverOptions pdo;
  pdo.set_protocol_name("grpc_async_callback");
  return pdo.DebugString();
}

std::string DoubleBarrelGrpc() {
  ProtocolDriverOptions pdo;
  pdo.set_protocol_name("double_barrel");
  AddClientStringOptionTo(pdo, "client_type", "polling");
  AddServerStringOptionTo(pdo, "server_type", "inline");
  AddServerStringOptionTo(pdo, "next_protocol_driver", "grpc");
  return pdo.DebugString();
}

std::string GrpcPollingClientHandoffServer() {
  ProtocolDriverOptions pdo;
  pdo.set_protocol_name("grpc");
  AddClientStringOptionTo(pdo, "client_type", "polling");
  AddServerStringOptionTo(pdo, "server_type", "handoff");
  return pdo.DebugString();
}

std::string GrpcPollingClientPollingServer() {
  ProtocolDriverOptions pdo;
  pdo.set_protocol_name("grpc");
  AddClientStringOptionTo(pdo, "client_type", "polling");
  AddServerStringOptionTo(pdo, "server_type", "polling");
  return pdo.DebugString();
}

std::string GrpcCallbackClientInlineServer() {
  ProtocolDriverOptions pdo;
  pdo.set_protocol_name("grpc");
  AddClientStringOptionTo(pdo, "client_type", "callback");
  AddServerStringOptionTo(pdo, "server_type", "inline");
  return pdo.DebugString();
}

std::string HomaOptions() {
  ProtocolDriverOptions pdo;
  pdo.set_protocol_name("homa");
  return pdo.DebugString();
}

std::string HomaTransport(std::string pdo_in) {
  ProtocolDriverOptions pdo = PdoFromString(pdo_in);
  auto opt = pdo.add_server_settings();
  opt->set_name("transport");
  opt->set_string_value("homa");
  return pdo.DebugString();
}

std::string MercuryOptions() {
  ProtocolDriverOptions pdo;
  pdo.set_protocol_name("mercury");
  return pdo.DebugString();
}

void BM_GrpcEcho(benchmark::State& state) { Echo(state, GrpcOptions()); }

void BM_GrpcCallbackEcho(benchmark::State& state) {
  Echo(state, GrpcAsynCallbackOptions());
}

BENCHMARK(BM_GrpcEcho);
BENCHMARK(BM_GrpcCallbackEcho);

// clang-format off
INSTANTIATE_TEST_SUITE_P(ProtocolDriverTests, ProtocolDriverTest,
                         testing::Values(
                           GrpcOptions(),
                           GrpcAsynCallbackOptions(),
                           GrpcPollingClientHandoffServer(),
                           GrpcPollingClientPollingServer(),
                           GrpcCallbackClientInlineServer(),
#ifdef WITH_HOMA
                           HomaOptions(),
#endif
#ifdef WITH_HOMA_GRPC
                           HomaTransport(GrpcOptions()),
                           HomaTransport(GrpcAsynCallbackOptions()),
                           HomaTransport(GrpcPollingClientHandoffServer()),
                           HomaTransport(GrpcPollingClientPollingServer()),
                           HomaTransport(GrpcCallbackClientInlineServer()),
#endif
#ifdef WITH_MERCURY
                           MercuryOptions(),
#endif
                           DoubleBarrelGrpc()
                           )
                         );
// clang-format on

}  // namespace distbench


text:
<?php

namespace Google\Service\ServiceUsage;

class MetricDescriptorMetadata extends \Google\Model
{
  /**
   * @var string
   */
  public $ingestDelay;
  /**
   * @var string
   */
  public $launchStage;
  /**
   * @var string
   */
  public $samplePeriod;

  /**
   * @param string
   */
  public function setIngestDelay($ingestDelay)
  {
    $this->ingestDelay = $ingestDelay;
  }
  /**
   * @return string
   */
  public function getIngestDelay()
  {
    return $this->ingestDelay;
  }
  /**
   * @param string
   */
  public function setLaunchStage($launchStage)
  {
    $this->launchStage = $launchStage;
  }
  /**
   * @return string
   */
  public function getLaunchStage()
  {
    return $this->launchStage;
  }
  /**
   * @param string
   */
  public function setSamplePeriod($samplePeriod)
  {
    $this->samplePeriod = $samplePeriod;
  }
  /**
   * @return string
   */
  public function getSamplePeriod()
  {
    return $this->samplePeriod;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(MetricDescriptorMetadata::class, 'Google_Service_ServiceUsage_MetricDescriptorMetadata');


text:
using System;
using System.Linq.Expressions;
using System.Reflection;

namespace OdataToEntity.Infrastructure
{
    public static class FastActivator
    {
        public static T CreateInstance<T>() => FastActivatorImpl<T>.Factory();

        private static class FastActivatorImpl<T>
        {
            public static readonly Func<T> Factory = GetFactory();

            private static Func<T> GetFactory()
            {
                ConstructorInfo? ctor = typeof(T).GetConstructor(Type.EmptyTypes);
                if (ctor == null)
                    throw new InvalidOperationException(typeof(T).Name + " must have default constructor or override OeDataAdapter.CreateDataContext()");

                return (Func<T>)Expression.Lambda(Expression.New(ctor)).Compile();
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Musings on Leif Madsen.</title>
    <link>http://blog.leifmadsen.com/categories/musings/</link>
    <description>Recent content in Musings on Leif Madsen.</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <copyright>Leif Madsen</copyright>
    <lastBuildDate>Fri, 25 Jul 2014 02:49:12 +0000</lastBuildDate>
    <atom:link href="/categories/musings/" rel="self" type="application/rss+xml" />

    <item>
      <title>Rumors of my death have been greatly exaggerated</title>
      <link>http://blog.leifmadsen.com/blog/2014/07/25/rumors-of-my-death-have-been-greatly-exaggerated/</link>
      <pubDate>Fri, 25 Jul 2014 02:49:12 +0000</pubDate>

      <guid>http://blog.leifmadsen.com/blog/2014/07/25/rumors-of-my-death-have-been-greatly-exaggerated/</guid>
      <description>It&rsquo;s been way too long since I&rsquo;ve blogged. And this post isn&rsquo;t going to be all the impressive unfortunately. However, I recently have been running a BBS and some friends and I have been playing LORD.
We&rsquo;ve been playing this for the last few months, and I think I&rsquo;m going to run a tournament. Perhaps with some sort of buy in like $10 or something, winner takes all.
Going to build it out in such a way that first person to beat the dragon 3 times will win the game, and at that point that person will win the pot.</description>
    </item>

    <item>
      <title>Digium D40 and D70 Phone Unboxing</title>
      <link>http://blog.leifmadsen.com/blog/2012/10/11/digium-d40-and-d70-phone-unboxing/</link>
      <pubDate>Thu, 11 Oct 2012 20:43:35 +0000</pubDate>

      <guid>http://blog.leifmadsen.com/blog/2012/10/11/digium-d40-and-d70-phone-unboxing/</guid>
      <description>Today I received a couple of phones from Digium; the D40 and D70. I&rsquo;ll be using these phones for testing and documentation in the 4th edition of Asterisk: The Definitive Guide (which Jim Van Meggelen, Russell Bryant and myself are working on right now).
Here is my unboxing of the phones and some commentary about my initial impressions of the hardware itself.
[caption id=&ldquo;attachment_484&rdquo; align=&ldquo;aligncenter&rdquo; width=&ldquo;300&rdquo;] Pretty boxes![/caption]
Phones arrived in some nice looking boxes.</description>
    </item>

    <item>
      <title>bash creating files named '1' everywhere!</title>
      <link>http://blog.leifmadsen.com/blog/2012/07/19/bash-creating-files-named-1-everywhere/</link>
      <pubDate>Thu, 19 Jul 2012 15:03:05 +0000</pubDate>

      <guid>http://blog.leifmadsen.com/blog/2012/07/19/bash-creating-files-named-1-everywhere/</guid>
      <description>So I ran into something kind of stupid today :) Adding a little note for anyone who might run into a similar instance.
I have some ssh-add stuff that gets run in my .bashrc file, but when I was outputting it, I was doing:
ssh-add ~/.ssh/some_key &gt; /dev/null 2&amp;&gt;1  Note the 2&amp;&gt;1 at the end. That means to redirect output to a file named 1. You need to flip the &amp;&gt; into &gt;&amp;, so the fixed version looks like:</description>
    </item>

    <item>
      <title>Commodore 64 Turns 30 This Year</title>
      <link>http://blog.leifmadsen.com/blog/2012/01/09/commodore-64-turns-30-this-year/</link>
      <pubDate>Mon, 09 Jan 2012 13:05:51 +0000</pubDate>

      <guid>http://blog.leifmadsen.com/blog/2012/01/09/commodore-64-turns-30-this-year/</guid>
      <description>Having found an article about the Commodore 64 turning 30 this year, I reflected back in a comment on that page about what it is like to be only 1 year older than the Commodore 64, a computer which spiked my interest in technology away from a games system to something much more. The original article is available at http://www.linuxjournal.com/content/commodor-64-30-year
&ldquo;I just turned 31 a couple of days ago on January 7th, and when I was in grade 2 (about 8-9 years old I guess) I started getting interested in the Commodore 64s we had at our school that were plentiful, but rarely used.</description>
    </item>

    <item>
      <title>#AstriCon 2011 Quote of the Conference (@abalashov)</title>
      <link>http://blog.leifmadsen.com/blog/2011/10/30/#astricon-2011-quote-of-the-conference-abalashov/</link>
      <pubDate>Sun, 30 Oct 2011 15:46:23 +0000</pubDate>

      <guid>http://blog.leifmadsen.com/blog/2011/10/30/#astricon-2011-quote-of-the-conference-abalashov/</guid>
      <description>I think the best quote I heard the entire time came from @abalashov (Alex Balashov) during the AstriDevCon when we were talking about Asterisk documentation, and how we might better organize it within the source.
We were discussing perhaps moving some of the existing configuration file examples to a manpage, and Alex piped up to say, &ldquo;Manpages are a vestige of our glorious, prehensile, curly-tailed past.&rdquo;
There wasn&rsquo;t much left to be said after that :)</description>
    </item>

    <item>
      <title>Connecting two conferences on initial join (with cleanup)</title>
      <link>http://blog.leifmadsen.com/blog/2011/08/11/connecting-two-conferences-on-initial-join-with-cleanup/</link>
      <pubDate>Thu, 11 Aug 2011 15:48:54 +0000</pubDate>

      <guid>http://blog.leifmadsen.com/blog/2011/08/11/connecting-two-conferences-on-initial-join-with-cleanup/</guid>
      <description>Update 2011/12/15: Updated the code to deal with a couple of people joining at about the same time by using GROUP() and GROUP_COUNT(). Additionally updated the &lsquo;h&rsquo; extension which was missing some code
 For the last week or so at work, people have been saying, &ldquo;Hey, I can&rsquo;t join the conference call this morning because I&rsquo;m driving but I can&rsquo;t call into the conference room on that server&rdquo;. There are really a couple solutions to the problem, 1) everyone should use the conference room that is accessible via the PSTN, 2) get the IT staff to allow PSTN access to the internal conference room.</description>
    </item>

    <item>
      <title>LeifMadsen Enterprises, Inc. enters its 7th year of operation!</title>
      <link>http://blog.leifmadsen.com/blog/2011/08/02/leifmadsen-enterprises-inc.-enters-its-7th-year-of-operation/</link>
      <pubDate>Tue, 02 Aug 2011 18:26:57 +0000</pubDate>

      <guid>http://blog.leifmadsen.com/blog/2011/08/02/leifmadsen-enterprises-inc.-enters-its-7th-year-of-operation/</guid>
      <description>On this day in 2005, LeifMadsen Enterprises, Inc. was formally registered as an incorporation by the government of Canada! I&rsquo;ve now been consulting on Asterisk professionally for over 6 years full time (and a few years before that!). I graduated from the telecommuncations technology program at Sheridan Institute of Technology in 2004. In that time I&rsquo;ve spoken at every AstriCon since 2004 (the first one), and have helped write 4 books on the subject of Asterisk (The Future of Telephony 1st, 2nd editions, The Definitive Guide 3rd edition, Cookbook).</description>
    </item>

    <item>
      <title>Chopsticks Played On The Phone</title>
      <link>http://blog.leifmadsen.com/blog/2011/07/29/chopsticks-played-on-the-phone/</link>
      <pubDate>Fri, 29 Jul 2011 17:17:07 +0000</pubDate>

      <guid>http://blog.leifmadsen.com/blog/2011/07/29/chopsticks-played-on-the-phone/</guid>
      <description>As I haven&rsquo;t updated my blog in a while (been very busy with wedding planning!) I thought I&rsquo;d share this with you :)
Enjoy!
http://www.break.com/index/chopsticks-played-on-phone.html</description>
    </item>

    <item>
      <title>Asterisk 1.8 And The Importance Of Looking Ahead</title>
      <link>http://blog.leifmadsen.com/blog/2011/05/17/asterisk-1.8-and-the-importance-of-looking-ahead/</link>
      <pubDate>Tue, 17 May 2011 20:40:55 +0000</pubDate>

      <guid>http://blog.leifmadsen.com/blog/2011/05/17/asterisk-1.8-and-the-importance-of-looking-ahead/</guid>
      <description>With the end of maintenance for the Asterisk 1.4 (the previous long term support (LTS) release) and Asterisk 1.6.2 (the previous standard, short term support release) branches, the time to look at using Asterisk 1.8 (the next long term support release, which provides another 4 years of maintenance, followed by a year of security support) is upon us. For those who have successful deployments of Asterisk 1.4 and 1.6.2 (heck, even 1.</description>
    </item>

    <item>
      <title>Asterisk Cookbook Is On! (We Think :))</title>
      <link>http://blog.leifmadsen.com/blog/2011/01/27/asterisk-cookbook-is-on-we-think-/</link>
      <pubDate>Thu, 27 Jan 2011 14:33:00 +0000</pubDate>

      <guid>http://blog.leifmadsen.com/blog/2011/01/27/asterisk-cookbook-is-on-we-think-/</guid>
      <description>After finishing the first draft of Asterisk: The Definitive Guide (3rd Edition), I&rsquo;ve been a bit antsy with wanting to do some more writing. After about a week of a break (i.e. sleeping in past 7am for the first time in nearly a year), Russell Bryant and I have decided to team up on delivering the long awaited Asterisk Cookbook.
To start off with, we&rsquo;ll be writing a short, 80-100 page eBook that will be distributed by O&rsquo;Reilly in all the formats they support (http://oreilly.</description>
    </item>

    <item>
      <title>Asterisk: The Definitive Guide, First Draft Complete!</title>
      <link>http://blog.leifmadsen.com/blog/2011/01/12/asterisk-the-definitive-guide-first-draft-complete/</link>
      <pubDate>Wed, 12 Jan 2011 01:30:09 +0000</pubDate>

      <guid>http://blog.leifmadsen.com/blog/2011/01/12/asterisk-the-definitive-guide-first-draft-complete/</guid>
      <description>Today we marked the finishing of Asterisk: The Definitive Guide (3rd Edition) by sending the first draft off to the O&rsquo;Reilly production team. We finished nearly on schedule (within a few days, which is remarkable considering we added 150 more pages than originally intentioned) and have our favourite copy editor Rachel Head (formerly Wheeler) who did the first edition of Asterisk: The Future of Telephony who we emphatically enjoyed working with.</description>
    </item>

    <item>
      <title>2010 in review</title>
      <link>http://blog.leifmadsen.com/blog/2011/01/03/2010-in-review/</link>
      <pubDate>Mon, 03 Jan 2011 18:21:21 +0000</pubDate>

      <guid>http://blog.leifmadsen.com/blog/2011/01/03/2010-in-review/</guid>
      <description>The stats helper monkeys at WordPress.com mulled over how this blog did in 2010, and here&rsquo;s a high level summary of its overall blog health:
The Blog-Health-o-Meter™ reads Wow.
Crunchy numbers A helper monkey made this abstract painting, inspired by your stats.
About 3 million people visit the Taj Mahal every year. This blog was viewed about 39,000 times in 2010. If it were the Taj Mahal, it would take about 5 days for that many people to see it.</description>
    </item>

    <item>
      <title>Wow, lost ticket recovery for VIA Rail is pretty much garbage</title>
      <link>http://blog.leifmadsen.com/blog/2010/10/29/wow-lost-ticket-recovery-for-via-rail-is-pretty-much-garbage/</link>
      <pubDate>Fri, 29 Oct 2010 18:35:10 +0000</pubDate>

      <guid>http://blog.leifmadsen.com/blog/2010/10/29/wow-lost-ticket-recovery-for-via-rail-is-pretty-much-garbage/</guid>
      <description>Here is the response I got from VIA Rail for a lost ticket, which was printed off at the time of departure for my return trip. Why they insist on printing the return ticket the time of departure I don&rsquo;t know, but how ridiculous is this?
&ldquo;VIA Rail will not issue a free ticket against a lost or stolen ticket being reported. Customers are required to purchase a new ticket at the original fare and complete a Lost Ticket Indemnity Bond.</description>
    </item>

    <item>
      <title>Long-term 'shopping list' helps couple furnish Caledon townhouse</title>
      <link>http://blog.leifmadsen.com/blog/2010/04/15/long-term-shopping-list-helps-couple-furnish-caledon-townhouse/</link>
      <pubDate>Thu, 15 Apr 2010 21:30:21 +0000</pubDate>

      <guid>http://blog.leifmadsen.com/blog/2010/04/15/long-term-shopping-list-helps-couple-furnish-caledon-townhouse/</guid>
      <description>Recently, @jenspeedy of http://www.yourhome.ca interviewed my fiancée and I about our recently purchased townhouse in Caledon after our designer @melissadavis of http://www.melissadavis.ca and http://www.designerfriend.ca recommended she speak to us. Danielle (my fiancée) and I had a pretty good idea about the items we wanted for our new townhouse build, but were looking for a designer to make sure we didn&rsquo;t get too far off track, and to steer us into the direction we ultimately wanted to achieve, while not breaking the bank (i.</description>
    </item>

    <item>
      <title>Musings about ENUMplus and ISNs</title>
      <link>http://blog.leifmadsen.com/blog/2010/02/19/musings-about-enumplus-and-isns/</link>
      <pubDate>Fri, 19 Feb 2010 15:38:07 +0000</pubDate>

      <guid>http://blog.leifmadsen.com/blog/2010/02/19/musings-about-enumplus-and-isns/</guid>
      <description>Recently I&rsquo;ve been playing around with a couple of technologies that I haven&rsquo;t used in quite a while; ENUM and ISN. First, a little information on what these technologies are about.
ISNs and ITADs First, lets talk about ISN (ITAD Subscriber Number) and ITAD (Internet Telephony Administrative Domain). I think the http://www.freenum.org website does a good job of succinctly describing the problem attempting to be addressed:
&ldquo;The Freenum/ISN system is 12-digit-keypad (telephone handset) friendly method of providing mapping between users.</description>
    </item>

  </channel>
</rss>


text:
<?php

class CommentNotifierTest extends SapphireTest {

	protected static $fixture_file = 'CommentNotifications.yml';

	protected $oldhost = null;

	protected $extraDataObjects = array(
		'CommentNotifiableTest_DataObject'
	);

	public function setUp() {
		parent::setUp();
		Email::set_mailer(new EmailTest_Mailer());
		Config::nest();
		Config::inst()->update('Email', 'admin_email', 'myadmin@mysite.com');
		$this->oldhost = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : null;
		$_SERVER['HTTP_HOST'] = 'www.mysite.com';
		Commenting::add('CommentNotifiableTest_DataObject');
	}

	public function tearDown() {
		Commenting::remove('CommentNotifiableTest_DataObject');
		$_SERVER['HTTP_HOST'] = $this->oldhost;
		Config::unnest();
		Email::set_mailer(new Mailer());
		parent::tearDown();
	}

	public function testSendEmail() {
		$author = $this->objFromFixture('Member', 'author');
		$item1 = $this->objFromFixture('CommentNotifiableTest_DataObject', 'item1');
		$item2 = $this->objFromFixture('CommentNotifiableTest_DataObject', 'item2');
		$comment1 = $this->objFromFixture('Comment', 'comment1');
		$comment2 = $this->objFromFixture('Comment', 'comment2');
		$comment3 = $this->objFromFixture('Comment', 'comment3');
		$controller = new CommentNotifierTest_Controller();

		// Commen 1
		$result = $controller->notifyCommentRecipient($comment1, $item1, $author);
		$this->assertEquals('andrew@address.com', $result['to']);
		$this->assertEquals('noreply@mysite.com', $result['from']);
		$this->assertEquals('A new comment has been posted', $result['subject']);
		$this->assertContains('
Bob Bobberson
', $result['content']);
		$this->assertContains('
bob@address.com
', $result['content']);
		$this->assertContains('
Hey what a lovely comment
', $result['content']);
		$this->assertContains(
			'You can view or moderate this comment at ID . '">An Object',
			$result['content']
		);

		// Comment 2
		$result = $controller->notifyCommentRecipient($comment2, $item2, $author);
		$this->assertEquals('andrew@address.com', $result['to']);
		$this->assertEquals('noreply@mysite.com', $result['from']);
		$this->assertEquals('A new comment has been posted', $result['subject']);
		$this->assertContains('
Secret
', $result['content']);
		$this->assertContains('
secret@notallowed.com
', $result['content']);
		$this->assertContains('
I don't want to disclose my details
', $result['content']);
		$this->assertContains(
			'You can view or moderate this comment at ID . '">Another One',
			$result['content']
		);

		// Comment 3
		$result = $controller->notifyCommentRecipient($comment3, $item1, $author);
		$this->assertEquals('andrew@address.com', $result['to']);
		$this->assertEquals('noreply@mysite.com', $result['from']);
		$this->assertEquals('A new comment has been posted', $result['subject']);
		$this->assertContains('
Anonymous
', $result['content']);
		$this->assertContains('
notlogged@in.com
', $result['content']);
		$this->assertContains('
I didn't log in
', $result['content']);
		$this->assertContains(
			'You can view or moderate this comment at ID . '">An Object',
			$result['content']
		);
	}
}

class CommentNotifierTest_Controller extends Controller implements TestOnly {
	private static $extensions = array(
		'CommentNotifier'
	);
}


text:
from setuptools import setup
from setuptools import find_packages

setup(
    name='alvi',
    version='1.1.1',
    packages=find_packages(),
    author='Piotr Lewalski',
    author_email='piotr@lewalski.pl',
    license='MIT',
    url='https://github.com/alviproject/alvi',
    description='Algorithm Visualization framework',
    long_description='Algorithm Visualization framework',
    install_requires=open("requirements.txt").read().split('\n'),
    tests_require=open("requirements_tests.txt").read().split('\n'),
    test_suite='discover_tests',
    include_package_data=True,
    #platform
    #keywords
    classifiers=[
        "Development Status :: 3 - Alpha",
        "Environment :: Console",
        "Environment :: MacOS X",
        "Environment :: No Input/Output (Daemon)",
        "Environment :: Web Environment",
        "Environment :: Win32 (MS Windows)",
        "Framework :: Django",
        "Intended Audience :: Developers",
        "Intended Audience :: Education",
        "Intended Audience :: Information Technology",
        "Intended Audience :: Other Audience",
        "Intended Audience :: Science/Research",
        "License :: DFSG approved",
        "License :: Free For Educational Use",
        "License :: Free For Home Use",
        "License :: Free for non-commercial use",
        "License :: Freely Distributable",
        "License :: Freeware",
        "License :: OSI Approved",
        "License :: OSI Approved :: MIT License",
        "License :: Public Domain",
        "Natural Language :: English",
        "Operating System :: BeOS",
        "Operating System :: MacOS",
        "Operating System :: MacOS :: MacOS 9",
        "Operating System :: MacOS :: MacOS X",
        "Operating System :: Microsoft",
        "Operating System :: Microsoft :: MS-DOS",
        "Operating System :: Microsoft :: Windows",
        "Operating System :: Microsoft :: Windows :: Windows 7",
        "Operating System :: Microsoft :: Windows :: Windows 95/98/2000",
        "Operating System :: Microsoft :: Windows :: Windows NT/2000",
        "Operating System :: Microsoft :: Windows :: Windows Server 2003",
        "Operating System :: Microsoft :: Windows :: Windows Server 2008",
        "Operating System :: Microsoft :: Windows :: Windows Vista",
        "Operating System :: Microsoft :: Windows :: Windows XP",
        "Operating System :: OS/2",
        "Operating System :: OS Independent",
        "Operating System :: Other OS",
        "Operating System :: POSIX",
        "Operating System :: POSIX :: AIX",
        "Operating System :: POSIX :: BSD",
        "Operating System :: POSIX :: BSD :: BSD/OS",
        "Operating System :: POSIX :: BSD :: FreeBSD",
        "Operating System :: POSIX :: BSD :: NetBSD",
        "Operating System :: POSIX :: BSD :: OpenBSD",
        "Operating System :: POSIX :: GNU Hurd",
        "Operating System :: POSIX :: HP-UX",
        "Operating System :: POSIX :: IRIX",
        "Operating System :: POSIX :: Linux",
        "Operating System :: POSIX :: Other",
        "Operating System :: POSIX :: SCO",
        "Operating System :: POSIX :: SunOS/Solaris",
        "Operating System :: Unix",
        "Programming Language :: Cython",
        "Programming Language :: JavaScript",
        "Programming Language :: Other",
        "Programming Language :: Other Scripting Engines",
        "Programming Language :: Python",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.3",
        "Programming Language :: Python :: Implementation",
        "Programming Language :: Python :: Implementation :: CPython",
        "Programming Language :: Python :: Implementation :: PyPy",
        "Topic :: Education",
        "Topic :: Education :: Testing",
        "Topic :: Internet",
        "Topic :: Internet :: WWW/HTTP",
        "Topic :: Internet :: WWW/HTTP :: Browsers",
        "Topic :: Internet :: WWW/HTTP :: Dynamic Content",
        "Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries",
        "Topic :: Internet :: WWW/HTTP :: HTTP Servers",
        "Topic :: Internet :: WWW/HTTP :: WSGI",
        "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
        "Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware",
        "Topic :: Internet :: WWW/HTTP :: WSGI :: Server",
        "Topic :: Scientific/Engineering",
        "Topic :: Scientific/Engineering :: Artificial Intelligence",
        "Topic :: Scientific/Engineering :: Human Machine Interfaces",
        "Topic :: Scientific/Engineering :: Information Analysis",
        "Topic :: Scientific/Engineering :: Visualization",
        "Topic :: Security",
        "Topic :: Security :: Cryptography",
        "Topic :: Software Development",
        "Topic :: Software Development :: Libraries",
        "Topic :: Software Development :: Libraries :: Application Frameworks",
        "Topic :: Software Development :: Libraries :: Python Modules",
        "Topic :: Text Processing :: Markup",
        "Topic :: Text Processing :: Markup :: HTML",
        "Topic :: Utilities",
    ]
)


text:
package br.ufba.dcc.mata62.ufbaboards.boards;

import br.ufba.dcc.mata62.ufbaboards.chessgame.pieces.BlankPiece;
import br.ufba.dcc.mata62.ufbaboards.chessgame.pieces.ChessPiece;
import br.ufba.dcc.mata62.ufbaboards.chessgame.pieces.ChessPieceAlive;
import br.ufba.dcc.mata62.ufbaboards.chessgame.pieces.PieceFactory;
import br.ufba.dcc.mata62.ufbaboards.chessgame.pieces.movements.ChessPieceMovementStrategy;
import br.ufba.dcc.mata62.ufbaboards.pieces.AbstractPiece;
import br.ufba.dcc.mata62.ufbaboards.utils.CoordinatesMovement;
import java.awt.Color;
import java.awt.Dimension;
import java.util.ArrayList;
import javax.swing.BorderFactory;

/**
 *
 * @author jeferson
 */
public class BoardMatrixPanel extends javax.swing.JPanel {
    protected AbstractPiece[][] piecesMatrix;
    protected boolean whiteLocations[][];
    protected boolean blackLocations[][];

    protected int tam;

    public void removePiece(AbstractPiece newPiece, AbstractPiece piece, int x, int y){
        int pieceIndex = (8 * y) + x;

        piecesMatrix[y][x] = newPiece;
        piecesMatrix[y][x].setBorder(BorderFactory.createLineBorder(new Color(0, 0, 0)));
        piecesMatrix[y][x].setPreferredSize(new Dimension(54, 54));
        this.add(piecesMatrix[y][x], pieceIndex);
        this.remove(piece);
    }
    public void addPiece(AbstractPiece lastPiece, AbstractPiece newPiece, int x, int y){
        int pieceIndex = (8 * y) + x;

        piecesMatrix[y][x] = newPiece;

        ChessPiece aff = (ChessPiece) newPiece;

        if((x % 2) == (y % 2))
            aff.setBackColor(new Color(51, 102, 255));
        else
            aff.setBackColor(new Color(204, 204, 255));

        this.add(piecesMatrix[y][x], pieceIndex);
        this.remove(lastPiece);
    }

    /**
     * Creates new form BoardPanel
     * @param size
     */
    public BoardMatrixPanel(int size) {
        initComponents();

        this.tam = size;

        /* Create matrix of pieces */
        piecesMatrix = new AbstractPiece[size][size];

        int pieceSide = 432 / size;
        Dimension pieceDimension = new Dimension(pieceSide, pieceSide);

        /* Populate Panel */
        for(int i = 0; i < size; i++)
            for(int j = 0; j < size; j++){
                /* Select Heavy Blue Pieces */
                if((i % 2) == (j % 2)){
                    piecesMatrix[i][j] = new BlankPiece(j, i, new Color(51, 102, 255));
                    piecesMatrix[i][j].setBackground(new Color(51, 102, 255));
                }
                /* Select Light Blue Pieces */
                else{
                    piecesMatrix[i][j] = new BlankPiece(j, i, new Color(204, 204, 255));
                    piecesMatrix[i][j].setBackground(new Color(204, 204, 255));
                }

                /* Define black thin border */
                piecesMatrix[i][j].setBorder(BorderFactory.createLineBorder(new Color(0, 0, 0)));
                piecesMatrix[i][j].setPreferredSize(pieceDimension);

                /* Add the piece to the panel */
                add(piecesMatrix[i][j]);
            }
    }

    public BoardMatrixPanel(String[][] matrix, String[][] colorPieces){
        initComponents();

        this.tam = 8;

        /* Create matrix of pieces */
        int size = 8;
        piecesMatrix = new AbstractPiece[size][size];
        whiteLocations = new boolean[size][size];
        blackLocations = new boolean[size][size];

        int pieceSide = 54;
        Dimension pieceDimension = new Dimension(pieceSide, pieceSide);

        /* Populate Panel */
        for(int i = 0; i < size; i++)
            for(int j = 0; j < size; j++){

                /* Initialize locations */
                whiteLocations[i][j] = false;
                blackLocations[i][j] = false;

                /* Start Piece */
                if(colorPieces[i][j].equals("black"))
                    blackLocations[i][j] = true;
                else if(colorPieces[i][j].equals("white"))
                    whiteLocations[i][j] = true;

                /* Select Heavy Blue Pieces */
                if((i % 2) == (j % 2)){
                    piecesMatrix[i][j] = PieceFactory.getNewPiece(  matrix[i][j],
                                                colorPieces[i][j], j, i,
                                                new Color(51, 102, 255));
                    piecesMatrix[i][j].setBackground(new Color(51, 102, 255));
                }
                /* Select Light Blue Pieces */
                else{
                    piecesMatrix[i][j] = PieceFactory.getNewPiece(  matrix[i][j],
                                                                    colorPieces[i][j], j, i,
                                                                    new Color(204, 204, 255));
                    piecesMatrix[i][j].setBackground(new Color(204, 204, 255));
                }
                /* Define black thin border */
                piecesMatrix[i][j].setBorder(BorderFactory.createLineBorder(new Color(0, 0, 0)));
                piecesMatrix[i][j].setPreferredSize(pieceDimension);

                /* Add the piece to the panel */
                add(piecesMatrix[i][j]);
            }
    }

    public BoardMatrixPanel() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public void addObservers(AbstractBoard board){
        for(int i = 0; i < tam; i++)
            for(int j = 0; j < tam; j++){
                piecesMatrix[i][j].addObserver(board);
            }
    }

    public void highlightMovements(AbstractPiece piece){
        ChessPieceMovementStrategy movementStrategy = piece.getMovementStrategy();
        ArrayList<CoordinatesMovement> possibleMovements = movementStrategy.getPossibleMovements();
        ChessPiece myPiece = (ChessPiece) piece;
        int actualX = myPiece.getXCoordinate();
        int actualY = myPiece.getYCoordinate();

        for(CoordinatesMovement possibleMovement : possibleMovements){
            int wantedX = possibleMovement.getX();
            int wantedY = possibleMovement.getY();

            if(possibleMovement.isX_inf() && possibleMovement.isY_inf()){
                while(((actualX + wantedX >= 0) && (actualX + wantedX < tam)) &&
                    ((actualY + wantedY >= 0) && (actualY + wantedY < tam)) &&
                    piecesMatrix[actualY + wantedY][actualX + wantedX].canMoveTo()){
                    piecesMatrix[actualY + wantedY][actualX + wantedX].highlightPiece();
                    wantedX += 1;
                    wantedY += 1;
                }
            }
            if(possibleMovement.isX_inf()){
                while(((actualX + wantedX >= 0) && (actualX + wantedX < tam)) &&
                    ((actualY + wantedY >= 0) && (actualY + wantedY < tam)) &&
                    piecesMatrix[actualY + wantedY][actualX + wantedX].canMoveTo()){
                    piecesMatrix[actualY + wantedY][actualX + wantedX].highlightPiece();
                    wantedX += 1;
                }
            }
            if(possibleMovement.isY_inf()){
                while(((actualX + wantedX >= 0) && (actualX + wantedX < tam)) &&
                    ((actualY + wantedY >= 0) && (actualY + wantedY < tam)) &&
                    piecesMatrix[actualY + wantedY][actualX + wantedX].canMoveTo()){
                    piecesMatrix[actualY + wantedY][actualX + wantedX].highlightPiece();
                    wantedY += 1;
                }
            }
            else{
                if( ((actualX + wantedX >= 0) && (actualX + wantedX < tam)) &&
                    ((actualY + wantedY >= 0) && (actualY + wantedY < tam)) &&
                    piecesMatrix[actualY + wantedY][actualX + wantedX].canMoveTo())
                    piecesMatrix[actualY + wantedY][actualX + wantedX].highlightPiece();
            }
        }
    }

    public void removeHighlight(){
        for(int i = 0; i < tam; i++)
            for(int j = 0; j < tam; j++){
                piecesMatrix[i][j].deSelect();
            }
    }

    public void moveWhitePiece(int lastX, int lastY, int newX, int newY){
        whiteLocations[lastX][lastY]    = false;
        whiteLocations[newX][newY]      = true;
    }

    public void moveBlackPiece(int lastX, int lastY, int newX, int newY){
        blackLocations[lastX][lastY]    = false;
        blackLocations[newX][newY]      = true;
    }

    public void changeTurn(String turn){
        if(turn.equals("white")){
            for(int i = 0; i < tam; i++)
                for(int j = 0; j < tam; j++){
                    if(blackLocations[i][j])
                        piecesMatrix[i][j].turnAlly();
                    if(whiteLocations[i][j])
                        piecesMatrix[i][j].turnOpponent();
                }
        }
        else{
            for(int i = 0; i < tam; i++)
                for(int j = 0; j < tam; j++){
                    if(whiteLocations[i][j])
                        piecesMatrix[i][j].turnAlly();
                    if(blackLocations[i][j])
                        piecesMatrix[i][j].turnOpponent();
                }
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setMaximumSize(new java.awt.Dimension(432, 432));
        setMinimumSize(new java.awt.Dimension(432, 432));
        setName("boardGamePanel"); // NOI18N
        setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));
        getAccessibleContext().setAccessibleName("Board Game Panel");
        getAccessibleContext().setAccessibleDescription("Board Game Panel");
    }// </editor-fold>//GEN-END:initComponents

    public void turnAlive(int actualX, int actualY) {
        piecesMatrix[actualX][actualY].setState(new ChessPieceAlive());
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
}


text:
Taco Pasta

1 lb lean (at least 80%) ground beef
1 cup Progresso™ beef-flavored broth (from 32-oz carton)
1 cup water
1 package (1 oz) Old El Paso™ taco seasoning mix
1 can (14.5 oz) Muir Glen™ organic diced tomatoes, undrained
1/4 cup finely chopped white onion
1 garlic clove, finely chopped
1 package (8 oz) Old El Paso™ chile and roasted garlic Mexican cooking sauce
4 oz (half of 8-oz package) cream cheese, soften, cut into 1-inch pieces
3 cups cooked medium pasta shells
2 cups shredded Cheddar cheese (8 oz)
Toppings, if desired

#### Sour cream
Old El Paso™ Thick 'n Chunky salsa
Shredded cheese
Directions
1In 10-inch skillet, cook beef over medium-high heat 5 to 8 minutes, stirring frequently, until beef is thoroughly cooked; drain.
2In 5- to 6-quart slow cooker, place cooked beef and remaining Taco Pasta ingredients except pasta shells and Cheddar cheese; stir until well combined.
3Cover; cook on Low heat setting 4 to 5 hours.
4About 15 minutes before serving, cook and drain pasta as directed on package. Uncover slow cooker; stir in pasta and shredded Cheddar cheese until well combined.
5Cook uncovered on High heat setting 10 to 15 minutes longer or until cheese is melted.
6Serve topped with sour cream, salsa and/or shredded cheese.


text:
<?php
declare(strict_types=1);

namespace App\DataSource\Legacy\Runde;

use Atlas\Mapper\Record;

/**
 * @method RundeRow getRow()
 */
class RundeRecord extends Record
{
    use RundeFields;
}


text:
using System;
using System.Collections.Generic;
using Couchbase.Lite;

namespace Couchbase.Lite {

    /// <summary>
    /// Context passed to a <see cref="Couchbase.Lite.ValidateDelegate"/>.
    /// </summary>
    public partial interface IValidationContext {

    #region Instance Members
        //Properties
        /// <summary>
        /// Gets the current <see cref="Couchbase.Lite.Revision"/> of the <see cref="Couchbase.Lite.Document"/>,
        /// or null if this is a new <see cref="Couchbase.Lite.Document"/>.
        /// </summary>
        /// <value>The current revision.</value>
        SavedRevision CurrentRevision { get; }

        /// <summary>
        /// Gets the keys whose values have changed between the current and new <see cref="Couchbase.Lite.Revision"/>s.
        /// </summary>
        /// <value>The changed keys.</value>
        IEnumerable<String> ChangedKeys { get; }

        //Methods
        /// <summary>
        /// Rejects the new <see cref="Couchbase.Lite.Revision"/>.
        /// </summary>
        void Reject();

        /// <summary>
        /// Rejects the new <see cref="Couchbase.Lite.Revision"/>. The specified message will be included with
        /// the resulting error.
        /// </summary>
        /// <param name="message">The message to include with the resulting error.</param>
        void Reject(String message);

        /// <summary>
        /// Calls the ValidateChangeDelegate for each key/value that has changed, passing both the old and new values.
        /// If any delegate call returns false, the enumeration stops and false is returned, otherwise true is returned.
        /// </summary>
        /// <returns><c>false</c> if any call to the ValidateChangeDelegate, otherwise <c>true</c>.</returns>
        /// <param name="changeValidator">The delegate to use to validate each change.</param>
        Boolean ValidateChanges(ValidateChangeDelegate changeValidator);
    #endregion

    }

}


text:
var should = require('should'),
    testUtils = require('../../utils'),
    _ = require('lodash'),
    dbAPI = require('../../../server/api/db'),
    models = require('../../../server/models');

describe('DB API', function () {
    // Keep the DB clean
    before(testUtils.teardown);
    afterEach(testUtils.teardown);
    beforeEach(testUtils.setup('users:roles', 'settings', 'posts', 'subscriber', 'perms:db', 'perms:init'));

    should.exist(dbAPI);

    it('delete all content (owner)', function () {
        return dbAPI.deleteAllContent(testUtils.context.owner).then(function (result) {
            should.exist(result.db);
            result.db.should.be.instanceof(Array);
            result.db.should.be.empty();
        }).then(function () {
            return models.Tag.findAll(testUtils.context.owner).then(function (results) {
                should.exist(results);
                results.length.should.equal(0);
            });
        }).then(function () {
            return models.Post.findAll(testUtils.context.owner).then(function (results) {
                should.exist(results);
                results.length.should.equal(0);
            });
        }).then(function () {
            return models.Subscriber.findAll(testUtils.context.owner).then(function (results) {
                should.exist(results);
                results.length.should.equal(1);
            });
        });
    });

    it('delete all content (admin)', function () {
        return dbAPI.deleteAllContent(testUtils.context.admin).then(function (result) {
            should.exist(result.db);
            result.db.should.be.instanceof(Array);
            result.db.should.be.empty();
        }).then(function () {
            return models.Tag.findAll(testUtils.context.admin).then(function (results) {
                should.exist(results);
                results.length.should.equal(0);
            });
        }).then(function () {
            return models.Post.findAll(testUtils.context.admin).then(function (results) {
                should.exist(results);
                results.length.should.equal(0);
            });
        });
    });

    it('delete all content is denied (editor, author & without authentication)', function () {
        return dbAPI.deleteAllContent(testUtils.context.editor).then(function () {
            throw new Error('Delete all content is not denied for editor.');
        }, function (error) {
            error.errorType.should.eql('NoPermissionError');
            return dbAPI.deleteAllContent(testUtils.context.author);
        }).then(function () {
            throw new Error('Delete all content is not denied for author.');
        }, function (error) {
            error.errorType.should.eql('NoPermissionError');
            return dbAPI.deleteAllContent();
        }).then(function () {
            throw new Error('Delete all content is not denied without authentication.');
        }).catch(function (error) {
            error.errorType.should.eql('NoPermissionError');
        });
    });

    it('export content is denied (editor, author & without authentication)', function () {
        return dbAPI.exportContent(testUtils.context.editor).then(function () {
            throw new Error('Export content is not denied for editor.');
        }, function (error) {
            error.errorType.should.eql('NoPermissionError');
            return dbAPI.exportContent(testUtils.context.author);
        }).then(function () {
            throw new Error('Export content is not denied for author.');
        }, function (error) {
            error.errorType.should.eql('NoPermissionError');
            return dbAPI.exportContent();
        }).then(function () {
            throw new Error('Export content is not denied without authentication.');
        }).catch(function (error) {
            error.errorType.should.eql('NoPermissionError');
        });
    });

    it('import content is denied (editor, author & without authentication)', function () {
        var file = {
            originalname: 'myFile.json',
            path: '/my/path/myFile.json',
            mimetype: 'application/json'
        };

        return dbAPI.importContent(_.extend(testUtils.context.editor, file)).then(function () {
            throw new Error('Import content is not denied for editor.');
        }, function (error) {
            error.errorType.should.eql('NoPermissionError');
            return dbAPI.importContent(_.extend(testUtils.context.author, file));
        }).then(function () {
            throw new Error('Import content is not denied for author.');
        }, function (error) {
            error.errorType.should.eql('NoPermissionError');
            return dbAPI.importContent(file);
        }).then(function () {
            throw new Error('Import content is not denied without authentication.');
        }).catch(function (error) {
            error.errorType.should.eql('NoPermissionError');
        });
    });
});


text:
package keynuker

import (
	"log"
	"testing"
	"time"

	"fmt"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/iam"
	"github.com/google/go-github/github"
	"github.com/stretchr/testify/assert"
	"gopkg.in/mailgun/mailgun-go.v1"
)

func TestSendPostNukeNotifications(t *testing.T) {

	fakeUserEmail := "fakeUser@fake.co"
	fakeAdminEmail := "fakeAdmin@fake.co"

	// Mailgun instance -- either live or mock depending on whether integration tests enabled
	var mg mailgun.Mailgun
	var err error

	// Create fake inputs that include nuked key events
	params := ParamsPostNukeNotifier{
		NukedKeyEvents: []NukedKeyEvent{
			{
				NukedOn: time.Now(),
				LeakedKeyEvent: LeakedKeyEvent{
					GithubUser: &github.User{
						Email: aws.String(fakeUserEmail),
					},
					GithubEvent: &github.Event{},
					AccessKeyMetadata: FetchedAwsAccessKey{
						AccessKeyId: aws.String("fake-aws-access-key"),
					},
				},
				DeleteAccessKeyOutput: &iam.DeleteAccessKeyOutput{},
			},
		},
		KeynukerAdminEmailCCAddress: fakeAdminEmail,
		EmailFromAddress:            fakeAdminEmail,
		MailerParams:                MailerParams{},
	}

	// Unless integration tests are enabled, use mock
	mockTest := !IntegrationTestsEnabled()

	if mockTest {
		// Create mock mailgun and configure it to use that
		mg = NewMockMailGun()
	} else {

		// Integration test instructions -- set env variables MAILERDOMAIN, MAILERAPIKEY, and MAILERPUBLICAPIKEY

		mg, err = NewMailgunFromEnvironmentVariables()
		assert.NoError(t, err, fmt.Sprintf("Unexpected error"))

		fakeUserEmail = "youremail@your.org" // Replace these to receive emails
		fakeAdminEmail = "fakeAdmin@your.org"

	}

	// Call post nuke notifier
	result, err := SendPostNukeMockNotifications(mg, params)
	assert.NoError(t, err, fmt.Sprintf("Unexpected error"))

	if mockTest {

		mockMailgun := mg.(*MockMailGun)

		// Wait until mock mailgun is invoked
		msg, err := mockMailgun.WaitForNextMessage(time.Second)
		assert.NoError(t, err, fmt.Sprintf("Unexpected error"))
		log.Printf("Mailgun message: %v", msg)

		// Verify that the correct outputs are returned (should propagate checkpoints)
		log.Printf("result: %v", result)
		assert.EqualValues(t, len(result.NukedKeyEvents), len(params.NukedKeyEvents))
		assert.EqualValues(t, result.NukedKeyEvents, params.NukedKeyEvents)

		// Should have at least one delivery id
		assert.True(t, len(result.DeliveryIds) >= 1)

	}

}


text:
package v1alpha1

import (
	"fmt"
	"io/ioutil"
	netUrl "net/url"
	"os"
	"path"
	"strings"

	"github.com/ghodss/yaml"
	gogetter "github.com/hashicorp/go-getter"
	"github.com/hashicorp/go-getter/helper/url"
	"github.com/kubeflow/kfctl/v3/config"
	kfapis "github.com/kubeflow/kfctl/v3/pkg/apis"
	"github.com/pkg/errors"
	log "github.com/sirupsen/logrus"
	v1 "k8s.io/api/core/v1"
	valid "k8s.io/apimachinery/pkg/api/validation"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
)

// KfDefSpec holds common attributes used by each platform
type KfDefSpec struct {
	config.ComponentConfig `json:",inline"`
	// TODO(jlewi): Why is AppDir a part of the spec? AppDir is currently used
	// to refer to the location on disk where all the manifests are stored.
	// But that should be treated as a local cache and not part of the spec.
	// For example, if the app is checked out on a different machine the AppDir will change.
	// AppDir. AppDir is stored in KfDefSpec because we pass a KfDef around to
	// as a way to pass the information to all the KfApps that need to know the local AppDir.
	// A better solution might be to store AppDir in KfDef.Status to better reflect its
	// ephemeral nature and match K8s semantics.
	AppDir     string `json:"appdir,omitempty"`
	Version    string `json:"version,omitempty"`
	MountLocal bool   `json:"mountLocal,omitempty"`

	// TODO(jlewi): Project, Email, IpName, Hostname, Zone and other
	// GCP specific values should be moved into GCP plugin.
	Project            string   `json:"project,omitempty"`
	Email              string   `json:"email,omitempty"`
	IpName             string   `json:"ipName,omitempty"`
	Hostname           string   `json:"hostname,omitempty"`
	Zone               string   `json:"zone,omitempty"`
	UseBasicAuth       bool     `json:"useBasicAuth"`
	SkipInitProject    bool     `json:"skipInitProject,omitempty"`
	UseIstio           bool     `json:"useIstio"`
	EnableApplications bool     `json:"enableApplications"`
	ServerVersion      string   `json:"serverVersion,omitempty"`
	DeleteStorage      bool     `json:"deleteStorage,omitempty"`
	PackageManager     string   `json:"packageManager,omitempty"`
	Repos              []Repo   `json:"repos,omitempty"`
	Secrets            []Secret `json:"secrets,omitempty"`
	Plugins            []Plugin `json:"plugins,omitempty"`

	// Applications defines a list of applications to install
	Applications []Application `json:"applications,omitempty"`
}

var DefaultRegistry = RegistryConfig{
	Name: "kubeflow",
	Repo: "https://github.com/kubeflow/kubeflow.git",
	Path: "kubeflow",
}

// Application defines an application to install
type Application struct {
	Name            string           `json:"name,omitempty"`
	KustomizeConfig *KustomizeConfig `json:"kustomizeConfig,omitempty"`
}

type KustomizeConfig struct {
	RepoRef    *RepoRef           `json:"repoRef,omitempty"`
	Overlays   []string           `json:"overlays,omitempty"`
	Parameters []config.NameValue `json:"parameters,omitempty"`
}

type RepoRef struct {
	Name string `json:"name,omitempty"`
	Path string `json:"path,omitempty"`
}

// Plugin can be used to customize the generation and deployment of Kubeflow
// TODO(jlewi): Should Plugin contain K8s TypeMeta so that we can use ApiVersion and Kind
// to identify what it refers to?
type Plugin struct {
	Name string `json:"name,omitempty"`
	// TODO(jlewi): Should we be using runtime.Object or runtime.RawExtension
	Spec *runtime.RawExtension `json:"spec,omitempty"`
}

// SecretRef is a reference to a secret
type SecretRef struct {
	// Name of the secret
	Name string `json:"name,omitempty"`
}

// Repo provides information about a repository providing config (e.g. kustomize packages,
// Deployment manager configs, etc...)
type Repo struct {
	// Name is a name to identify the repository.
	Name string `json:"name,omitempty"`
	// URI where repository can be obtained.
	// Can use any URI understood by go-getter:
	// https://github.com/hashicorp/go-getter/blob/master/README.md#installation-and-usage
	Uri string `json:"uri,omitempty"`

	// Root is the relative path to use as the root.
	// TODO(jlewi): Get rid of this field. SyncCache now takes care of setting the directory
	// as needed.
	Root string `json:"root,omitempty"`
}

// Secret provides information about secrets needed to configure Kubeflow.
// Secrets can be provided via references e.g. a URI so that they won't
// be serialized as part of the KfDefSpec which is intended to be written into source control.
type Secret struct {
	Name         string        `json:"name,omitempty"`
	SecretSource *SecretSource `json:"secretSource,omitempty"`
}

type SecretSource struct {
	LiteralSource *LiteralSource `json:"literalSource,omitempty"`
	HashedSource  *HashedSource  `json:"hashedSource,omitempty"`
	EnvSource     *EnvSource     `json:"envSource,omitempty"`
}

type LiteralSource struct {
	Value string `json:"value,omitempty"`
}

type HashedSource struct {
	HashedValue string `json:"value,omitempty"`
}

type EnvSource struct {
	Name string `json:"Name,omitempty"`
}

// RegistryConfig is used for two purposes:
// 1. used during image build, to configure registries that should be baked into the bootstrapper docker image.
//  (See: https://github.com/kubeflow/kubeflow/blob/master/bootstrap/image_registries.yaml)
// 2. used during app create rpc call, specifies a registry to be added to an app.
//      required info for registry: Name, Repo, Version, Path
//  Additionally if any of required fields is blank we will try to map with one of
//  the registries baked into the Docker image using the name.
type RegistryConfig struct {
	Name    string `json:"name,omitempty"`
	Repo    string `json:"repo,omitempty"`
	Version string `json:"version,omitempty"`
	Path    string `json:"path,omitempty"`
	RegUri  string `json:"reguri,omitempty"`
}

type KsComponent struct {
	Name      string `json:"name,omitempty"`
	Prototype string `json:"prototype,omitempty"`
}

type KsLibrary struct {
	Name     string `json:"name"`
	Registry string `json:"registry"`
	Version  string `json:"version"`
}

type KsParameter struct {
	// nested components are referenced as "a.b.c" where "a" or "b" may be a module name
	Component string `json:"component,omitempty"`
	Name      string `json:"name,omitempty"`
	Value     string `json:"value,omitempty"`
}

type KsModule struct {
	Name       string         `json:"name"`
	Components []*KsComponent `json:"components,omitempty"`
	Modules    []*KsModule    `json:"modules,omitempty"`
}

type KsPackage struct {
	Name string `json:"name,omitempty"`
	// Registry should be the name of the registry containing the package.
	Registry string `json:"registry,omitempty"`
}

type Registry struct {
	// Name is the user defined name of a registry.
	Name string `json:"-"`
	// Protocol is the registry protocol for this registry. Currently supported
	// values are `github`, `fs`, `helm`.
	Protocol string `json:"protocol"`
	// URI is the location of the registry.
	URI string `json:"uri"`
}

type LibrarySpec struct {
	Version string
	Path    string
}

// KsRegistry corresponds to ksonnet.io/registry
// which is the registry.yaml file found in every registry.
type KsRegistry struct {
	ApiVersion string
	Kind       string
	Libraries  map[string]LibrarySpec
}

// RegistriesConfigFile corresponds to a YAML file specifying information
// about known registries.
type RegistriesConfigFile struct {
	// Registries provides information about known registries.
	Registries []*RegistryConfig
}

type AppConfig struct {
	Registries []*RegistryConfig `json:"registries,omitempty"`
	Packages   []KsPackage       `json:"packages,omitempty"`
	Components []KsComponent     `json:"components,omitempty"`
	Parameters []KsParameter     `json:"parameters,omitempty"`
	// Parameters to apply when creating the ksonnet components
	ApplyParameters []KsParameter `json:"applyParameters,omitempty"`
}

// KfDefStatus defines the observed state of KfDef
type KfDefStatus struct {
	Conditions []KfDefCondition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,6,rep,name=conditions"`
	// ReposCache is used to cache information about local caching of the URIs.
	ReposCache map[string]RepoCache `json:"reposCache,omitempty"`
}

type RepoCache struct {
	LocalPath string `json:"localPath,string"`
}

type KfDefConditionType string

const (
	// KfCreated means the KfDef spec has been created.
	KfCreated KfDefConditionType = "Created"

	// KfDeploying means Kubeflow is in the process of being deployed.
	KfDeploying KfDefConditionType = "Deploying"

	// KfSucceeded means Kubeflow was successfully deployed.
	KfSucceeded KfDefConditionType = "Succeeded"

	// KfFailed meansthere was a problem deploying Kubeflow.
	KfFailed KfDefConditionType = "Failed"

	// Reasons for conditions

	// InvalidKfDefSpecReason indicates the KfDef was not valid.
	InvalidKfDefSpecReason = "InvalidKfDefSpec"
)

type KfDefCondition struct {
	// Type of deployment condition.
	Type KfDefConditionType `json:"type" protobuf:"bytes,1,opt,name=type,casttype=KfDefConditionType"`
	// Status of the condition, one of True, False, Unknown.
	Status v1.ConditionStatus `json:"status" protobuf:"bytes,2,opt,name=status,casttype=k8s.io/api/core/v1.ConditionStatus"`
	// The last time this condition was updated.
	LastUpdateTime metav1.Time `json:"lastUpdateTime,omitempty" protobuf:"bytes,6,opt,name=lastUpdateTime"`
	// Last time the condition transitioned from one status to another.
	LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" protobuf:"bytes,7,opt,name=lastTransitionTime"`
	// The reason for the condition's last transition.
	Reason string `json:"reason,omitempty" protobuf:"bytes,4,opt,name=reason"`
	// A human readable message indicating details about the transition.
	Message string `json:"message,omitempty" protobuf:"bytes,5,opt,name=message"`
}

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// KfDef is the Schema for the applications API
// +k8s:openapi-gen=true
type KfDef struct {
	metav1.TypeMeta   `json:",inline"`
	metav1.ObjectMeta `json:"metadata,omitempty"`

	Spec   KfDefSpec   `json:"spec,omitempty"`
	Status KfDefStatus `json:"status,omitempty"`
}

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// KfDefList contains a list of KfDef
type KfDefList struct {
	metav1.TypeMeta `json:",inline"`
	metav1.ListMeta `json:"metadata,omitempty"`
	Items           []KfDef `json:"items"`
}

// GetDefaultRegistry return reference of a newly copied Default Registry
func GetDefaultRegistry() *RegistryConfig {
	newReg := DefaultRegistry
	return &newReg
}

const DefaultCacheDir = ".cache"

func isValidUrl(toTest string) bool {
	_, err := netUrl.ParseRequestURI(toTest)
	if err != nil {
		return false
	} else {
		return true
	}
}

// TODO: THIS FUNCTION IS DEPRECATED. PLEASE USE `LoadKFDefFromURI` in kfloader.go
// LoadKFDefFromURI constructs a KfDef given the path to a YAML file
// specifying a YAML config file.
// configFile is the path to the YAML file containing the KfDef spec. Can be any URI supported by hashicorp
// go-getter.
func LoadKFDefFromURI(configFile string) (*KfDef, error) {
	if configFile == "" {
		return nil, fmt.Errorf("config file must be the URI of a KfDef spec")
	}

	// TODO(jlewi): We should check if configFile doesn't specify a protocol or the protocol
	// is file:// then we can just read it rather than fetching with go-getter.
	appDir, err := ioutil.TempDir("", "")
	if err != nil {
		return nil, fmt.Errorf("Create a temporary directory to copy the file to.")
	}
	// Open config file
	//
	// TODO(jlewi): Should we use hashicorp go-getter.GetAny here? We use that to download
	// the tarballs for the repos. Maybe we should use that here as well to be consistent.
	appFile := path.Join(appDir, "tmp_app.yaml")
	log.Infof("Downloading %v to %v", configFile, appFile)
	configFileUri, err := netUrl.Parse(configFile)
	if err != nil {
		log.Errorf("Could not parse configFile url")
	}
	if isValidUrl(configFile) {
		errGet := gogetter.GetFile(appFile, configFile)
		if errGet != nil {
			return nil, &kfapis.KfError{
				Code:    int(kfapis.INVALID_ARGUMENT),
				Message: fmt.Sprintf("could not fetch specified config %s: %v", configFile, err),
			}
		}
	} else {
		g := new(gogetter.FileGetter)
		g.Copy = true
		errGet := g.GetFile(appFile, configFileUri)
		if errGet != nil {
			return nil, &kfapis.KfError{
				Code:    int(kfapis.INVALID_ARGUMENT),
				Message: fmt.Sprintf("could not fetch specified config %s: %v", configFile, err),
			}
		}
	}

	// Read contents
	configFileBytes, err := ioutil.ReadFile(appFile)
	if err != nil {
		return nil, &kfapis.KfError{
			Code:    int(kfapis.INTERNAL_ERROR),
			Message: fmt.Sprintf("could not read from config file %s: %v", configFile, err),
		}
	}
	// Unmarshal content onto KfDef struct
	kfDef := &KfDef{}
	if err := yaml.Unmarshal(configFileBytes, kfDef); err != nil {
		return nil, &kfapis.KfError{
			Code:    int(kfapis.INTERNAL_ERROR),
			Message: fmt.Sprintf("could not unmarshal config file onto KfDef struct: %v", err),
		}
	}

	return kfDef, nil
}

// SyncCache will synchronize the local cache of any repositories.
// On success the status is updated with pointers to the cache.
//
// TODO(jlewi): I'm not sure this handles head references correctly.
// e.g. suppose we have a URI like
// https://github.com/kubeflow/manifests/tarball/pull/189/head?archive=tar.gz
// This gets unpacked to: kubeflow-manifests-e2c1bcb where e2c1bcb is the commit.
// I don't think the code is currently setting the local directory for the cache correctly in
// that case.
//
//
// Using tarball vs. archive in github links affects the download path
// e.g.
// https://github.com/kubeflow/manifests/tarball/master?archive=tar.gz
//    unpacks to  kubeflow-manifests-${COMMIT}
// https://github.com/kubeflow/manifests/archive/master.tar.gz
//    unpacks to manifests-master
// Always use archive format so that the path is predetermined.
//
// Instructions: https://github.com/hashicorp/go-getter#protocol-specific-options
//
// What is the correct syntax for downloading pull requests?
// The following doesn't seem to work
// https://github.com/kubeflow/manifests/archive/master.tar.gz?ref=pull/188
//   * Appears to download master
//
// This appears to work
// https://github.com/kubeflow/manifests/tarball/pull/188/head?archive=tar.gz
// But unpacks it into
// kubeflow-manifests-${COMMIT}
//
func (d *KfDef) SyncCache() error {
	if d.Spec.AppDir == "" {
		return fmt.Errorf("AppDir must be specified")
	}

	if d.Status.ReposCache == nil {
		d.Status.ReposCache = make(map[string]RepoCache)
	}
	appDir := d.Spec.AppDir
	// Loop over all the repos and download them.
	// TODO(https://github.com/kubeflow/kubeflow/issues/3545): We should check if we already have a local copy and
	// not redownload it.

	baseCacheDir := path.Join(appDir, DefaultCacheDir)
	if _, err := os.Stat(baseCacheDir); os.IsNotExist(err) {
		log.Infof("Creating directory %v", baseCacheDir)
		appdirErr := os.MkdirAll(baseCacheDir, os.ModePerm)
		if appdirErr != nil {
			log.Errorf("Couldn't create directory %v: %v", baseCacheDir, appdirErr)
			return appdirErr
		}
	}

	for _, r := range d.Spec.Repos {
		cacheDir := path.Join(baseCacheDir, r.Name)

		// Can we use a checksum or other mechanism to verify if the existing location is good?
		// If there was a problem the first time around then removing it might provide a way to recover.
		if _, err := os.Stat(cacheDir); err == nil {
			if _, ok := d.Status.ReposCache[r.Name]; ok && d.Status.ReposCache[r.Name].LocalPath != "" {
				log.Infof("%v exists; not resyncing ", cacheDir)
				continue
			}

			log.Infof("Deleting cachedir %v because Status.ReposCache is out of date", cacheDir)

			// TODO(jlewi): The reason the cachedir might exist but not be stored in KfDef.status
			// is because of a backwards compatibility path in which we download the cache to construct
			// the KfDef. Specifically coordinator.CreateKfDefFromOptions is calling kftypes.DownloadFromCache
			// We don't want to rely on that method to set the cache because we have logic
			// below to set LocalPath that we don't want to duplicate.
			// Unfortunately this means we end up fetching the repo twice which is very inefficient.
			if err := os.RemoveAll(cacheDir); err != nil {
				log.Errorf("There was a problem deleting directory %v; error %v", cacheDir, err)
				return errors.WithStack(err)
			}
		}

		u, err := url.Parse(r.Uri)

		if err != nil {
			log.Errorf("Could not parse URI %v; error %v", r.Uri, err)
			return errors.WithStack(err)
		}

		log.Infof("Fetching %v to %v", r.Uri, cacheDir)
		tarballUrlErr := gogetter.GetAny(cacheDir, r.Uri)
		if tarballUrlErr != nil {
			return &kfapis.KfError{
				Code:    int(kfapis.INVALID_ARGUMENT),
				Message: fmt.Sprintf("couldn't download URI %v: %v", r.Uri, tarballUrlErr),
			}
		}

		// This is a bit of a hack to deal with the fact that GitHub tarballs
		// can unpack to a directory containing the commit.
		localPath := cacheDir
		if u.Scheme == "http" || u.Scheme == "https" {
			files, filesErr := ioutil.ReadDir(cacheDir)
			if filesErr != nil {
				log.Errorf("Error reading cachedir; error %v", filesErr)
				return errors.WithStack(filesErr)
			}
			subdir := files[0].Name()
			localPath = path.Join(cacheDir, subdir)
		}

		d.Status.ReposCache[r.Name] = RepoCache{
			LocalPath: localPath,
		}

		log.Infof("Fetch succeeded; LocalPath %v", d.Status.ReposCache[r.Name].LocalPath)
	}
	return nil
}

// GetSecret returns the specified secret or an error if the secret isn't specified.
func (d *KfDef) GetSecret(name string) (string, error) {
	for _, s := range d.Spec.Secrets {
		if s.Name != name {
			continue
		}
		if s.SecretSource.LiteralSource != nil {
			return s.SecretSource.LiteralSource.Value, nil
		}
		if s.SecretSource.HashedSource != nil {
			return s.SecretSource.HashedSource.HashedValue, nil
		}
		if s.SecretSource.EnvSource != nil {
			return os.Getenv(s.SecretSource.EnvSource.Name), nil
		}

		return "", fmt.Errorf("No secret source provided for secret %v", name)
	}
	return "", NewSecretNotFound(name)
}

// SetSecret sets the specified secret; if a secret with the given name already exists it is overwritten.
func (d *KfDef) SetSecret(newSecret Secret) {
	for i, s := range d.Spec.Secrets {
		if s.Name == newSecret.Name {
			d.Spec.Secrets[i] = newSecret
			return
		}
	}

	d.Spec.Secrets = append(d.Spec.Secrets, newSecret)
}

// GetPluginSpec will try to unmarshal the spec for the specified plugin to the supplied
// interface. Returns an error if the plugin isn't defined or if there is a problem
// unmarshaling it.
func (d *KfDef) GetPluginSpec(pluginName string, s interface{}) error {
	for _, p := range d.Spec.Plugins {
		if p.Name != pluginName {
			continue
		}

		// To deserialize it to a specific type we need to first serialize it to bytes
		// and then unserialize it.
		specBytes, err := yaml.Marshal(p.Spec)

		if err != nil {
			log.Errorf("Could not marshal plugin %v args; error %v", pluginName, err)
			return err
		}

		err = yaml.Unmarshal(specBytes, s)

		if err != nil {
			log.Errorf("Could not unmarshal plugin %v to the provided type; error %v", pluginName, err)
		}
		return nil
	}

	return NewPluginNotFound(pluginName)
}

// SetPluginSpec sets the requested parameter. The plugin is added if it doesn't already exist.
func (d *KfDef) SetPluginSpec(pluginName string, spec interface{}) error {
	// Convert spec to RawExtension

	r := &runtime.RawExtension{}

	// To deserialize it to a specific type we need to first serialize it to bytes
	// and then unserialize it.
	specBytes, err := yaml.Marshal(spec)

	if err != nil {
		log.Errorf("Could not marshal spec; error %v", err)
		return err
	}

	err = yaml.Unmarshal(specBytes, r)

	if err != nil {
		log.Errorf("Could not unmarshal plugin to RawExtension; error %v", err)
	}

	index := -1

	for i, p := range d.Spec.Plugins {
		if p.Name == pluginName {
			index = i
			break
		}
	}

	if index == -1 {
		// Plugin in doesn't exist so add it
		log.Infof("Adding plugin %v", pluginName)

		d.Spec.Plugins = append(d.Spec.Plugins, Plugin{
			Name: pluginName,
		})

		index = len(d.Spec.Plugins) - 1
	}

	d.Spec.Plugins[index].Spec = r
	return nil
}

// IsValid returns true if the spec is a valid and complete spec.
// If false it will also return a string providing a message about why its invalid.
func (d *KfDef) IsValid() (bool, string) {
	// TODO(jlewi): Add more validation and a unittest.
	// Validate kfDef
	errs := valid.NameIsDNSLabel(d.Name, false)
	if errs != nil && len(errs) > 0 {
		return false, fmt.Sprintf("invalid name due to %v", strings.Join(errs, ","))
	}

	// PackageManager is currently required because we will try to load the package manager and get an error if
	// none is specified.
	if d.Spec.PackageManager == "" {
		return false, fmt.Sprintf("KfDef.Spec.PackageManager is required")
	}

	return true, ""
}

// WriteToFile write the KfDef to a file.
// WriteToFile will strip out any literal secrets before writing it
func (d *KfDef) WriteToFile(path string) error {
	stripped := d.DeepCopy()

	secrets := make([]Secret, 0)

	for _, s := range stripped.Spec.Secrets {
		if s.SecretSource.LiteralSource != nil {
			log.Warnf("Stripping literal secret %v from KfDef before serializing it", s.Name)
			continue
		}
		secrets = append(secrets, s)
	}

	stripped.Spec.Secrets = secrets

	// Rewrite app.yaml
	buf, bufErr := yaml.Marshal(stripped)
	if bufErr != nil {
		log.Errorf("Error marshaling kfdev; %v", bufErr)
		return bufErr
	}
	log.Infof("Writing stripped KfDef to %v", path)
	return ioutil.WriteFile(path, buf, 0644)
}

type PluginNotFound struct {
	Name string
}

func (e *PluginNotFound) Error() string {
	return fmt.Sprintf("Missing plugin %v", e.Name)
}

func NewPluginNotFound(n string) *PluginNotFound {
	return &PluginNotFound{
		Name: n,
	}
}

func IsPluginNotFound(e error) bool {
	if e == nil {
		return false
	}
	_, ok := e.(*PluginNotFound)
	return ok
}

type SecretNotFound struct {
	Name string
}

func (e *SecretNotFound) Error() string {
	return fmt.Sprintf("Missing secret %v", e.Name)
}

func NewSecretNotFound(n string) *SecretNotFound {
	return &SecretNotFound{
		Name: n,
	}
}

func IsSecretNotFound(e error) bool {
	if e == nil {
		return false
	}
	_, ok := e.(*SecretNotFound)
	return ok
}

func getParameter(parameters []config.NameValue, paramName string) (string, bool) {
	for _, p := range parameters {
		if p.Name == paramName {
			return p.Value, true
		}
	}

	return "", false
}

func setParameter(parameters []config.NameValue, paramName string, value string) []config.NameValue {
	pIndex := -1

	for i, p := range parameters {
		if p.Name == paramName {
			pIndex = i
		}
	}

	if pIndex < 0 {
		parameters = append(parameters, config.NameValue{})
		pIndex = len(parameters) - 1
	}

	parameters[pIndex].Name = paramName
	parameters[pIndex].Value = value

	return parameters
}

type AppNotFound struct {
	Name string
}

func (e *AppNotFound) Error() string {
	return fmt.Sprintf("Application %v is missing", e.Name)
}

func IsAppNotFound(e error) bool {
	if e == nil {
		return false
	}
	_, ok := e.(*AppNotFound)
	return ok
}

// GetApplicationParameter gets the desired application parameter.
func (d *KfDef) GetApplicationParameter(appName string, paramName string) (string, bool) {
	// First we check applications for an application with the specified name.
	if d.Spec.Applications != nil {
		for _, a := range d.Spec.Applications {
			if a.Name == appName {
				return getParameter(a.KustomizeConfig.Parameters, paramName)
			}
		}
	}

	// Since an application with the specified name wasn't found check the deprecated componentParams
	if _, ok := d.Spec.ComponentParams[appName]; ok {
		return getParameter(d.Spec.ComponentParams[appName], paramName)
	}

	return "", false
}

// SetApplicationParameter sets the desired application parameter.
func (d *KfDef) SetApplicationParameter(appName string, paramName string, value string) error {
	// First we check applications for an application with the specified name.
	if d.Spec.Applications != nil {
		appIndex := -1
		for i, a := range d.Spec.Applications {
			if a.Name == appName {
				appIndex = i
			}
		}

		if appIndex >= 0 {

			if d.Spec.Applications[appIndex].KustomizeConfig == nil {
				return errors.WithStack(fmt.Errorf("Application %v doesn't have KustomizeConfig", appName))
			}

			d.Spec.Applications[appIndex].KustomizeConfig.Parameters = setParameter(
				d.Spec.Applications[appIndex].KustomizeConfig.Parameters, paramName, value)

			return nil
		}
	}

	// Since an application with the specified name wasn't found check the deprecated componentParams
	if _, ok := d.Spec.ComponentParams[appName]; ok {
		d.Spec.ComponentParams[appName] = setParameter(d.Spec.ComponentParams[appName], paramName, value)
		return nil
	}

	return &AppNotFound{Name: appName}
}


text:
package org.multibit.hd.brit.core.matcher;

import java.io.File;
import java.util.Arrays;

/**
 *
Value object to provide the following to BRIT API:

 *

 *
Matcher configuration

 *

 *
 * @since 0.0.1
 */
public class MatcherConfig {

  /**
   * The location of the secret key ring containing the Matcher secret key
   */
  private File matcherSecretKeyringFile;

  /**
   * The credentials to use to decrypt the secret key ring
   */
  private char[] password;

  public MatcherConfig(File matcherSecretKeyringFile, char[] password) {
    this.matcherSecretKeyringFile = matcherSecretKeyringFile;
    this.password = Arrays.copyOf(password, password.length);
  }

  public File getMatcherSecretKeyringFile() {
    return matcherSecretKeyringFile;
  }

  public char[] getPassword() {
    return Arrays.copyOf(password, password.length);
  }

}


text: """Unifi LED Lights integration."""


text:
/**
 *
 */
package app.dict;

import static org.junit.Assert.*;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import app.MainView;
import app.dict.country.Country;
import app.dict.country.CountryDAO;

/**
 * @author serg
 *
 */
public class CountryDAOtst {

	private static final transient Logger log = LoggerFactory.getLogger(CountryDAOtst.class);

	/**
	 * Test method for {@link app.dict.country.CountryDAO#CountryDAO()}.
	 * @throws SQLException
	 * @throws IOException
	 */
	//@Test
	public void testCountryDAO() throws IOException, SQLException {
		CountryDAO c = new CountryDAO();
		assertNotNull(c);
	}

	/**
	 * Test method for {@link das.base.CRUDSingleDAO#getAll()}.
	 * @throws IOException
	 * @throws SQLException
	 */
	//@Test
	public void testGetAll() throws IOException, SQLException {
		CountryDAO c = new CountryDAO();
		assertNotNull(c);
		List<Country> l = c.getAll();
		assertNotNull(l);
	}

	/**
	 * Test method for {@link das.base.CRUDSingleDAO#insert(), #update(), #delete(), #findByN3c()}.
	 * @throws IOException
	 * @throws SQLException
	 */
	@Test
	public void testCUD() throws IOException, SQLException {
		CountryDAO c = new CountryDAO();
		assertNotNull(c);
		Country item;
		//попытка найти ранее добавленную строку
		try {
			item = c.findByN3c(1);
			log.debug("item.ID="+item.getId());
			//если найдена, удаляем её
			c.delete(item);
		} catch (Exception e) {
            log.error("", e);
        }
		item = new Country(null, "name01", 1, "00", "000");
		assertNotNull(item);
		c.insert(item);
		log.debug("item.ID={}, name={}, number3code={}, alpha2code={}, alpha3code={}", item.getId(), item.getName(), item.getNumber3code(), item.getAlpha2code(), item.getAlpha3code());
		assertNotNull(item.getId());
		item = c.findByN3c(1);
		assertNotNull(item);
		log.debug("item.ID="+item.getId());
		assertEquals(1L, item.getNumber3code().longValue());
		c.update(item);
		c.delete(item);
	}

	/**
	 * Test method for {@link das.base.CRUDSingleDAO#update(java.lang.Object)}.
	 */
	//@Test
	public void testUpdate() {
		fail("Not yet implemented");
	}

	/**
	 * Test method for {@link das.base.CRUDSingleDAO#delete(java.lang.Object)}.
	 */
	//@Test
	public void testDelete() {
		fail("Not yet implemented");
	}

}


text:
package com.krazy.kcfw.modules.gen.dao;

import com.krazy.kcfw.common.persistence.CrudDao;
import com.krazy.kcfw.common.persistence.annotation.MyBatisDao;
import com.krazy.kcfw.modules.gen.entity.GenScheme;

/**
 * 生成方案DAO接口
 * @author krazy
 * @version 2013-10-15
 */
@MyBatisDao
public interface GenSchemeDao extends CrudDao<GenScheme> {

}


text:
"""Benchmarking Relay VM using models from MXNet."""
import numpy as np

import tvm
from tvm.contrib import graph_runtime
from tvm import relay
from tvm.relay import testing

def benchmark_execution(mod,
                        params,
                        measure=False,
                        data_shape=(1, 3, 224, 224),
                        out_shape=(1, 1000),
                        dtype='float32'):
    def get_tvm_output(mod, data, params, target, ctx, dtype='float32'):
        with relay.build_config(opt_level=1):
            graph, lib, params = relay.build(mod, target, params=params)

        m = graph_runtime.create(graph, lib, ctx)
        # set inputs
        m.set_input("data", data)
        m.set_input(**params)
        m.run()
        out = m.get_output(0, tvm.nd.empty(out_shape, dtype))

        if measure:
            print("Evaluate graph runtime inference time cost...")
            ftimer = m.module.time_evaluator("run", ctx, number=1, repeat=20)
            # Measure in millisecond.
            prof_res = np.array(ftimer().results) * 1000
            print("Mean inference time (std dev): %.2f ms (%.2f ms)" %
                  (np.mean(prof_res), np.std(prof_res)))

        return out.asnumpy()

    def get_tvm_vm_output(mod, data, params, target, ctx, dtype='float32'):
        ex = relay.create_executor('vm', mod=mod, ctx=ctx)
        result = ex.evaluate()(data, **params)
        return result.asnumpy().astype(dtype)

    # random input
    data = np.random.uniform(size=data_shape).astype(dtype)
    target = "llvm"
    ctx = tvm.cpu(0)

    tvm_out = get_tvm_output(mod, tvm.nd.array(data.astype(dtype)), params,
                             target, ctx, dtype)
    vm_out = get_tvm_vm_output(mod, tvm.nd.array(data.astype(dtype)), params,
                               target, ctx, dtype)
    tvm.testing.assert_allclose(vm_out, tvm_out, rtol=1e-5, atol=1e-5)

def test_mlp():
    image_shape = (1, 1, 28, 28)
    mod, params = testing.mlp.get_workload(1)
    benchmark_execution(mod, params, data_shape=image_shape, out_shape=(1, 10))

def test_vgg():
    for n in [11, 16]:
        mod, params = testing.vgg.get_workload(1, num_layers=n)
        benchmark_execution(mod, params)

def test_resnet():
    for n in [18, 50]:
        mod, params = testing.resnet.get_workload(batch_size=1, num_layers=n)
        benchmark_execution(mod, params, True)

def test_squeezenet():
    for version in ['1.0', '1.1']:
        mod, params = testing.squeezenet.get_workload(version=version)
        benchmark_execution(mod, params)

def test_inception_v3():
    image_shape = (1, 3, 299, 299)
    mod, params = testing.inception_v3.get_workload(image_shape=image_shape)
    benchmark_execution(mod, params, data_shape=image_shape)

def test_dqn():
    image_shape = (1, 4, 84, 84)
    mod, params = testing.dqn.get_workload(
        batch_size=1, image_shape=image_shape)
    benchmark_execution(mod, params, data_shape=image_shape, out_shape=(1, 18))

def test_dcgan():
    image_shape = (1, 100)
    mod, params = testing.dcgan.get_workload(batch_size=1)
    benchmark_execution(mod, params, data_shape=image_shape)

def test_mobilenet():
    mod, params = testing.mobilenet.get_workload(batch_size=1)
    benchmark_execution(mod, params)

def test_densenet():
    mod, params = testing.densenet.get_workload(batch_size=1)
    benchmark_execution(mod, params)

if __name__ == '__main__':
    test_resnet()
    test_vgg()
    test_squeezenet()
    test_mobilenet()
    test_densenet()
    # The following networks fail
    # test_inception_v3()
    # test_mlp()
    # test_dqn()
    # test_dcgan()


text:
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.

## [0.2.2](https://github.com/google/blockly-samples/compare/@blockly/disable-top-blocks@0.2.1...@blockly/disable-top-blocks@0.2.2) (2022-10-27)

**Note:** Version bump only for package @blockly/disable-top-blocks

## [0.2.1](https://github.com/google/blockly-samples/compare/@blockly/disable-top-blocks@0.2.0...@blockly/disable-top-blocks@0.2.1) (2022-10-13)

**Note:** Version bump only for package @blockly/disable-top-blocks

## [0.2.0](https://github.com/google/blockly-samples/compare/@blockly/disable-top-blocks@0.1.42...@blockly/disable-top-blocks@0.2.0) (2022-10-05)

### ⚠ BREAKING CHANGES

* update peer and devDependencies of all plugins to require Blockly v9 (#1314)

### Bug Fixes

* references to deprecated functions in v9 ([#1313](https://github.com/google/blockly-samples/issues/1313)) ([cb2e679](https://github.com/google/blockly-samples/commit/cb2e67987e0b62a77c26adc660cc6ade1ba67954))

### Miscellaneous Chores

* update peer and devDependencies of all plugins to require Blockly v9 ([#1314](https://github.com/google/blockly-samples/issues/1314)) ([03d4912](https://github.com/google/blockly-samples/commit/03d4912c42c8de0f30493037ccc28dddaea0f266))

## 0.1.42 (2022-08-11)

### Bug Fixes

* Remove the deprecated block-extension-tooltip ([#1215](https://github.com/google/blockly-samples/issues/1215)) ([a044478](https://github.com/google/blockly-samples/commit/a044478c86a73e3065bc866e427f175cbec6fc13))

## 0.1.41 (2022-08-04)

### Bug Fixes

* fix the name of the package of suggested-blocks ([#1214](https://github.com/google/blockly-samples/issues/1214)) ([35aa8ec](https://github.com/google/blockly-samples/commit/35aa8ec73a60a4eb5b1e80cb2fc71dcd83d05e27))

## 0.1.39 (2022-07-21)

**Note:** Version bump only for package @blockly/disable-top-blocks

## 0.1.38 (2022-07-06)

### Bug Fixes

* Update blockly-react to use functional components instead of class components. ([#1178](https://github.com/google/blockly-samples/issues/1178)) ([fa21187](https://github.com/google/blockly-samples/commit/fa21187cdbe4ec3a5c69f185540dd68a98eb69d7))

## 0.1.37 (2022-06-27)

### Bug Fixes

* Update package import for keyboard navigation demo ([#1170](https://github.com/google/blockly-samples/issues/1170)) ([69c1725](https://github.com/google/blockly-samples/commit/69c1725b775279fcc397dc178935208d5f42b08c))

## 0.1.36 (2022-06-21)

**Note:** Version bump only for package @blockly/disable-top-blocks

## 0.1.35 (2022-06-08)

### Bug Fixes

* package versions to support patch releases ([#1150](https://github.com/google/blockly-samples/issues/1150)) ([e1ae378](https://github.com/google/blockly-samples/commit/e1ae378d779531621c3d948566257d069002963f))

## 0.1.34 (2022-06-02)

### Bug Fixes

* add git identity ([#1156](https://github.com/google/blockly-samples/issues/1156)) ([8d80924](https://github.com/google/blockly-samples/commit/8d809243b277375beb2ce75d4e157b5e17f78193))


text:
package sync

import (
	"fmt"
	"os"

	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
	dsq "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore/query"
)

type datastore struct {
	child ds.Datastore
}

// Wrap shims a datastore such than _any_ operation failing triggers a panic
// This is useful for debugging invariants.
func Wrap(d ds.Datastore) ds.Shim {
	return &datastore{child: d}
}

func (d *datastore) Children() []ds.Datastore {
	return []ds.Datastore{d.child}
}

func (d *datastore) Put(key ds.Key, value interface{}) error {
	err := d.child.Put(key, value)
	if err != nil {
		fmt.Fprintf(os.Stdout, "panic datastore: %s", err)
		panic("panic datastore: Put failed")
	}
	return nil
}

func (d *datastore) Get(key ds.Key) (interface{}, error) {
	val, err := d.child.Get(key)
	if err != nil {
		fmt.Fprintf(os.Stdout, "panic datastore: %s", err)
		panic("panic datastore: Get failed")
	}
	return val, nil
}

func (d *datastore) Has(key ds.Key) (bool, error) {
	e, err := d.child.Has(key)
	if err != nil {
		fmt.Fprintf(os.Stdout, "panic datastore: %s", err)
		panic("panic datastore: Has failed")
	}
	return e, nil
}

func (d *datastore) Delete(key ds.Key) error {
	err := d.child.Delete(key)
	if err != nil {
		fmt.Fprintf(os.Stdout, "panic datastore: %s", err)
		panic("panic datastore: Delete failed")
	}
	return nil
}

func (d *datastore) Query(q dsq.Query) (dsq.Results, error) {
	r, err := d.child.Query(q)
	if err != nil {
		fmt.Fprintf(os.Stdout, "panic datastore: %s", err)
		panic("panic datastore: Query failed")
	}
	return r, nil
}


text:
.. -*- coding: utf-8; mode: rst -*-

.. _CA_GET_DESCR_INFO:

=================
CA_GET_DESCR_INFO
=================

Name
----

CA_GET_DESCR_INFO

Synopsis
--------

.. c:function:: int  ioctl(fd, CA_GET_DESCR_INFO, struct ca_descr_info *desc)
    :name: CA_GET_DESCR_INFO

Arguments
---------

``fd``
  File descriptor returned by a previous call to :c:func:`open() <dvb-ca-open>`.

``desc``
  Pointer to struct :c:type:`ca_descr_info`.

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

Returns information about all descrambler slots.

Return Value
------------

On success 0 is returned, and :c:type:`ca_descr_info` is filled.

On error -1 is returned, and the ``errno`` variable is set
appropriately. The generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.


text:
FOUNDATION_EXPORT double SlidingTabbarControllerVersionNumber;
FOUNDATION_EXPORT const unsigned char SlidingTabbarControllerVersionString[];


text:
var yy = alasql.yy;

yy.Echo = function (params) { return yy.extend(this, params); }
yy.Echo.prototype.toString = function() {
	var s =  'TEST '+this.expr.toString();
	return s;
}

yy.Echo.prototype.execute = function (databaseid, params, cb) {
//	var self = this;
//	console.log(this.expr.toJS());
	var fn = new Function('params, alasql','return '+this.expr.toJS());
	var res = fn(params, alasql);
	if(cb) res = cb(res);
	return res;
}