text:
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/blkdev.h>
#include <linux/freezer.h>
#include <linux/kthread.h>
#include <linux/scatterlist.h>
#include <linux/dma-mapping.h>

#include <linux/mmc/card.h>
#include <linux/mmc/host.h>
#include "queue.h"

#define MMC_QUEUE_BOUNCESZ	65536

/*
 * Prepare a MMC request. This just filters out odd stuff.
 */
static int mmc_prep_request(struct request_queue *q, struct request *req)
{
	struct mmc_queue *mq = q->queuedata;

	/*
	 * We only like normal block requests and discards.
	 */
	if (req->cmd_type != REQ_TYPE_FS && !(req->cmd_flags & REQ_DISCARD)) {
		blk_dump_rq_flags(req, "MMC bad request");
		return BLKPREP_KILL;
	}

	if (mq && (mmc_card_removed(mq->card) || mmc_access_rpmb(mq)))
		return BLKPREP_KILL;

	req->cmd_flags |= REQ_DONTPREP;

	return BLKPREP_OK;
}

static int mmc_queue_thread(void *d)
{
	struct mmc_queue *mq = d;
	struct request_queue *q = mq->queue;

	current->flags |= PF_MEMALLOC;

	down(&mq->thread_sem);
	do {
		struct request *req = NULL;
		unsigned int cmd_flags = 0;

		spin_lock_irq(q->queue_lock);
		set_current_state(TASK_INTERRUPTIBLE);
		req = blk_fetch_request(q);
		mq->mqrq_cur->req = req;
		spin_unlock_irq(q->queue_lock);

		if (req || mq->mqrq_prev->req) {
			set_current_state(TASK_RUNNING);
			cmd_flags = req ? req->cmd_flags : 0;
			mq->issue_fn(mq, req);
			cond_resched();
			if (mq->flags & MMC_QUEUE_NEW_REQUEST) {
				mq->flags &= ~MMC_QUEUE_NEW_REQUEST;
				continue; /* fetch again */
			}

			/*
			 * Current request becomes previous request
			 * and vice versa.
			 * In case of special requests, current request
			 * has been finished. Do not assign it to previous
			 * request.
			 */
			if (cmd_flags & MMC_REQ_SPECIAL_MASK)
				mq->mqrq_cur->req = NULL;

			mq->mqrq_prev->brq.mrq.data = NULL;
			mq->mqrq_prev->req = NULL;
			swap(mq->mqrq_prev, mq->mqrq_cur);
		} else {
			if (kthread_should_stop()) {
				set_current_state(TASK_RUNNING);
				break;
			}
			up(&mq->thread_sem);
			schedule();
			down(&mq->thread_sem);
		}
	} while (1);
	up(&mq->thread_sem);

	return 0;
}

/*
 * Generic MMC request handler.  This is called for any queue on a
 * particular host.  When the host is not busy, we look for a request
 * on any queue on this host, and attempt to issue it.  This may
 * not be the queue we were asked to process.
 */
static void mmc_request_fn(struct request_queue *q)
{
	struct mmc_queue *mq = q->queuedata;
	struct request *req;
	unsigned long flags;
	struct mmc_context_info *cntx;

	if (!mq) {
		while ((req = blk_fetch_request(q)) != NULL) {
			req->cmd_flags |= REQ_QUIET;
			__blk_end_request_all(req, -EIO);
		}
		return;
	}

	cntx = &mq->card->host->context_info;
	if (!mq->mqrq_cur->req && mq->mqrq_prev->req) {
		/*
		 * New MMC request arrived when MMC thread may be
		 * blocked on the previous request to be complete
		 * with no current request fetched
		 */
		spin_lock_irqsave(&cntx->lock, flags);
		if (cntx->is_waiting_last_req) {
			cntx->is_new_req = true;
			wake_up_interruptible(&cntx->wait);
		}
		spin_unlock_irqrestore(&cntx->lock, flags);
	} else if (!mq->mqrq_cur->req && !mq->mqrq_prev->req)
		wake_up_process(mq->thread);
}

static struct scatterlist *mmc_alloc_sg(int sg_len, int *err)
{
	struct scatterlist *sg;

	sg = kmalloc(sizeof(struct scatterlist)*sg_len, GFP_KERNEL);
	if (!sg)
		*err = -ENOMEM;
	else {
		*err = 0;
		sg_init_table(sg, sg_len);
	}

	return sg;
}

static void mmc_queue_setup_discard(struct request_queue *q,
				    struct mmc_card *card)
{
	unsigned max_discard;

	max_discard = mmc_calc_max_discard(card);
	if (!max_discard)
		return;

	queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, q);
	blk_queue_max_discard_sectors(q, max_discard);
	if (card->erased_byte == 0 && !mmc_can_discard(card))
		q->limits.discard_zeroes_data = 1;
	q->limits.discard_granularity = card->pref_erase << 9;
	/* granularity must not be greater than max. discard */
	if (card->pref_erase > max_discard)
		q->limits.discard_granularity = 0;
	if (mmc_can_secure_erase_trim(card))
		queue_flag_set_unlocked(QUEUE_FLAG_SECDISCARD, q);
}

/**
 * mmc_init_queue - initialise a queue structure.
 * @mq: mmc queue
 * @card: mmc card to attach this queue
 * @lock: queue lock
 * @subname: partition subname
 *
 * Initialise a MMC card request queue.
 */
int mmc_init_queue(struct mmc_queue *mq, struct mmc_card *card,
		   spinlock_t *lock, const char *subname)
{
	struct mmc_host *host = card->host;
	u64 limit = BLK_BOUNCE_HIGH;
	int ret;
	struct mmc_queue_req *mqrq_cur = &mq->mqrq[0];
	struct mmc_queue_req *mqrq_prev = &mq->mqrq[1];

	if (mmc_dev(host)->dma_mask && *mmc_dev(host)->dma_mask)
		limit = (u64)dma_max_pfn(mmc_dev(host)) << PAGE_SHIFT;

	mq->card = card;
	mq->queue = blk_init_queue(mmc_request_fn, lock);
	if (!mq->queue)
		return -ENOMEM;

	mq->mqrq_cur = mqrq_cur;
	mq->mqrq_prev = mqrq_prev;
	mq->queue->queuedata = mq;

	blk_queue_prep_rq(mq->queue, mmc_prep_request);
	queue_flag_set_unlocked(QUEUE_FLAG_NONROT, mq->queue);
	queue_flag_clear_unlocked(QUEUE_FLAG_ADD_RANDOM, mq->queue);
	if (mmc_can_erase(card))
		mmc_queue_setup_discard(mq->queue, card);

#ifdef CONFIG_MMC_BLOCK_BOUNCE
	if (host->max_segs == 1) {
		unsigned int bouncesz;

		bouncesz = MMC_QUEUE_BOUNCESZ;

		if (bouncesz > host->max_req_size)
			bouncesz = host->max_req_size;
		if (bouncesz > host->max_seg_size)
			bouncesz = host->max_seg_size;
		if (bouncesz > (host->max_blk_count * 512))
			bouncesz = host->max_blk_count * 512;

		if (bouncesz > 512) {
			mqrq_cur->bounce_buf = kmalloc(bouncesz, GFP_KERNEL);
			if (!mqrq_cur->bounce_buf) {
				pr_warn("%s: unable to allocate bounce cur buffer\n",
					mmc_card_name(card));
			} else {
				mqrq_prev->bounce_buf =
						kmalloc(bouncesz, GFP_KERNEL);
				if (!mqrq_prev->bounce_buf) {
					pr_warn("%s: unable to allocate bounce prev buffer\n",
						mmc_card_name(card));
					kfree(mqrq_cur->bounce_buf);
					mqrq_cur->bounce_buf = NULL;
				}
			}
		}

		if (mqrq_cur->bounce_buf && mqrq_prev->bounce_buf) {
			blk_queue_bounce_limit(mq->queue, BLK_BOUNCE_ANY);
			blk_queue_max_hw_sectors(mq->queue, bouncesz / 512);
			blk_queue_max_segments(mq->queue, bouncesz / 512);
			blk_queue_max_segment_size(mq->queue, bouncesz);

			mqrq_cur->sg = mmc_alloc_sg(1, &ret);
			if (ret)
				goto cleanup_queue;

			mqrq_cur->bounce_sg =
				mmc_alloc_sg(bouncesz / 512, &ret);
			if (ret)
				goto cleanup_queue;

			mqrq_prev->sg = mmc_alloc_sg(1, &ret);
			if (ret)
				goto cleanup_queue;

			mqrq_prev->bounce_sg =
				mmc_alloc_sg(bouncesz / 512, &ret);
			if (ret)
				goto cleanup_queue;
		}
	}
#endif

	if (!mqrq_cur->bounce_buf && !mqrq_prev->bounce_buf) {
		blk_queue_bounce_limit(mq->queue, limit);
		blk_queue_max_hw_sectors(mq->queue,
			min(host->max_blk_count, host->max_req_size / 512));
		blk_queue_max_segments(mq->queue, host->max_segs);
		blk_queue_max_segment_size(mq->queue, host->max_seg_size);

		mqrq_cur->sg = mmc_alloc_sg(host->max_segs, &ret);
		if (ret)
			goto cleanup_queue;

		mqrq_prev->sg = mmc_alloc_sg(host->max_segs, &ret);
		if (ret)
			goto cleanup_queue;
	}

	sema_init(&mq->thread_sem, 1);

	mq->thread = kthread_run(mmc_queue_thread, mq, "mmcqd/%d%s",
		host->index, subname ? subname : "");

	if (IS_ERR(mq->thread)) {
		ret = PTR_ERR(mq->thread);
		goto free_bounce_sg;
	}

	return 0;
 free_bounce_sg:
	kfree(mqrq_cur->bounce_sg);
	mqrq_cur->bounce_sg = NULL;
	kfree(mqrq_prev->bounce_sg);
	mqrq_prev->bounce_sg = NULL;

 cleanup_queue:
	kfree(mqrq_cur->sg);
	mqrq_cur->sg = NULL;
	kfree(mqrq_cur->bounce_buf);
	mqrq_cur->bounce_buf = NULL;

	kfree(mqrq_prev->sg);
	mqrq_prev->sg = NULL;
	kfree(mqrq_prev->bounce_buf);
	mqrq_prev->bounce_buf = NULL;

	blk_cleanup_queue(mq->queue);
	return ret;
}

void mmc_cleanup_queue(struct mmc_queue *mq)
{
	struct request_queue *q = mq->queue;
	unsigned long flags;
	struct mmc_queue_req *mqrq_cur = mq->mqrq_cur;
	struct mmc_queue_req *mqrq_prev = mq->mqrq_prev;

	/* Make sure the queue isn't suspended, as that will deadlock */
	mmc_queue_resume(mq);

	/* Then terminate our worker thread */
	kthread_stop(mq->thread);

	/* Empty the queue */
	spin_lock_irqsave(q->queue_lock, flags);
	q->queuedata = NULL;
	blk_start_queue(q);
	spin_unlock_irqrestore(q->queue_lock, flags);

	kfree(mqrq_cur->bounce_sg);
	mqrq_cur->bounce_sg = NULL;

	kfree(mqrq_cur->sg);
	mqrq_cur->sg = NULL;

	kfree(mqrq_cur->bounce_buf);
	mqrq_cur->bounce_buf = NULL;

	kfree(mqrq_prev->bounce_sg);
	mqrq_prev->bounce_sg = NULL;

	kfree(mqrq_prev->sg);
	mqrq_prev->sg = NULL;

	kfree(mqrq_prev->bounce_buf);
	mqrq_prev->bounce_buf = NULL;

	mq->card = NULL;
}
EXPORT_SYMBOL(mmc_cleanup_queue);

int mmc_packed_init(struct mmc_queue *mq, struct mmc_card *card)
{
	struct mmc_queue_req *mqrq_cur = &mq->mqrq[0];
	struct mmc_queue_req *mqrq_prev = &mq->mqrq[1];
	int ret = 0;

	mqrq_cur->packed = kzalloc(sizeof(struct mmc_packed), GFP_KERNEL);
	if (!mqrq_cur->packed) {
		pr_warn("%s: unable to allocate packed cmd for mqrq_cur\n",
			mmc_card_name(card));
		ret = -ENOMEM;
		goto out;
	}

	mqrq_prev->packed = kzalloc(sizeof(struct mmc_packed), GFP_KERNEL);
	if (!mqrq_prev->packed) {
		pr_warn("%s: unable to allocate packed cmd for mqrq_prev\n",
			mmc_card_name(card));
		kfree(mqrq_cur->packed);
		mqrq_cur->packed = NULL;
		ret = -ENOMEM;
		goto out;
	}

	INIT_LIST_HEAD(&mqrq_cur->packed->list);
	INIT_LIST_HEAD(&mqrq_prev->packed->list);

out:
	return ret;
}

void mmc_packed_clean(struct mmc_queue *mq)
{
	struct mmc_queue_req *mqrq_cur = &mq->mqrq[0];
	struct mmc_queue_req *mqrq_prev = &mq->mqrq[1];

	kfree(mqrq_cur->packed);
	mqrq_cur->packed = NULL;
	kfree(mqrq_prev->packed);
	mqrq_prev->packed = NULL;
}

/**
 * mmc_queue_suspend - suspend a MMC request queue
 * @mq: MMC queue to suspend
 *
 * Stop the block request queue, and wait for our thread to
 * complete any outstanding requests.  This ensures that we
 * won't suspend while a request is being processed.
 */
void mmc_queue_suspend(struct mmc_queue *mq)
{
	struct request_queue *q = mq->queue;
	unsigned long flags;

	if (!(mq->flags & MMC_QUEUE_SUSPENDED)) {
		mq->flags |= MMC_QUEUE_SUSPENDED;

		spin_lock_irqsave(q->queue_lock, flags);
		blk_stop_queue(q);
		spin_unlock_irqrestore(q->queue_lock, flags);

		down(&mq->thread_sem);
	}
}

/**
 * mmc_queue_resume - resume a previously suspended MMC request queue
 * @mq: MMC queue to resume
 */
void mmc_queue_resume(struct mmc_queue *mq)
{
	struct request_queue *q = mq->queue;
	unsigned long flags;

	if (mq->flags & MMC_QUEUE_SUSPENDED) {
		mq->flags &= ~MMC_QUEUE_SUSPENDED;

		up(&mq->thread_sem);

		spin_lock_irqsave(q->queue_lock, flags);
		blk_start_queue(q);
		spin_unlock_irqrestore(q->queue_lock, flags);
	}
}

static unsigned int mmc_queue_packed_map_sg(struct mmc_queue *mq,
					    struct mmc_packed *packed,
					    struct scatterlist *sg,
					    enum mmc_packed_type cmd_type)
{
	struct scatterlist *__sg = sg;
	unsigned int sg_len = 0;
	struct request *req;

	if (mmc_packed_wr(cmd_type)) {
		unsigned int hdr_sz = mmc_large_sector(mq->card) ? 4096 : 512;
		unsigned int max_seg_sz = queue_max_segment_size(mq->queue);
		unsigned int len, remain, offset = 0;
		u8 *buf = (u8 *)packed->cmd_hdr;

		remain = hdr_sz;
		do {
			len = min(remain, max_seg_sz);
			sg_set_buf(__sg, buf + offset, len);
			offset += len;
			remain -= len;
			sg_unmark_end(__sg++);
			sg_len++;
		} while (remain);
	}

	list_for_each_entry(req, &packed->list, queuelist) {
		sg_len += blk_rq_map_sg(mq->queue, req, __sg);
		__sg = sg + (sg_len - 1);
		sg_unmark_end(__sg++);
	}
	sg_mark_end(sg + (sg_len - 1));
	return sg_len;
}

/*
 * Prepare the sg list(s) to be handed of to the host driver
 */
unsigned int mmc_queue_map_sg(struct mmc_queue *mq, struct mmc_queue_req *mqrq)
{
	unsigned int sg_len;
	size_t buflen;
	struct scatterlist *sg;
	enum mmc_packed_type cmd_type;
	int i;

	cmd_type = mqrq->cmd_type;

	if (!mqrq->bounce_buf) {
		if (mmc_packed_cmd(cmd_type))
			return mmc_queue_packed_map_sg(mq, mqrq->packed,
						       mqrq->sg, cmd_type);
		else
			return blk_rq_map_sg(mq->queue, mqrq->req, mqrq->sg);
	}

	BUG_ON(!mqrq->bounce_sg);

	if (mmc_packed_cmd(cmd_type))
		sg_len = mmc_queue_packed_map_sg(mq, mqrq->packed,
						 mqrq->bounce_sg, cmd_type);
	else
		sg_len = blk_rq_map_sg(mq->queue, mqrq->req, mqrq->bounce_sg);

	mqrq->bounce_sg_len = sg_len;

	buflen = 0;
	for_each_sg(mqrq->bounce_sg, sg, sg_len, i)
		buflen += sg->length;

	sg_init_one(mqrq->sg, mqrq->bounce_buf, buflen);

	return 1;
}

/*
 * If writing, bounce the data to the buffer before the request
 * is sent to the host driver
 */
void mmc_queue_bounce_pre(struct mmc_queue_req *mqrq)
{
	if (!mqrq->bounce_buf)
		return;

	if (rq_data_dir(mqrq->req) != WRITE)
		return;

	sg_copy_to_buffer(mqrq->bounce_sg, mqrq->bounce_sg_len,
		mqrq->bounce_buf, mqrq->sg[0].length);
}

/*
 * If reading, bounce the data from the buffer after the request
 * has been handled by the host driver
 */
void mmc_queue_bounce_post(struct mmc_queue_req *mqrq)
{
	if (!mqrq->bounce_buf)
		return;

	if (rq_data_dir(mqrq->req) != READ)
		return;

	sg_copy_from_buffer(mqrq->bounce_sg, mqrq->bounce_sg_len,
		mqrq->bounce_buf, mqrq->sg[0].length);
}


text:
using content::BrowserThread;
using content::NavigationController;
using content::RenderViewHost;
using content::RenderViewHostTester;
using content::WebContents;

BrowserWithTestWindowTest::BrowserWithTestWindowTest()
    : ui_thread_(BrowserThread::UI, message_loop()),
      db_thread_(BrowserThread::DB),
      file_thread_(BrowserThread::FILE, message_loop()),
      file_user_blocking_thread_(
          BrowserThread::FILE_USER_BLOCKING, message_loop()),
      host_desktop_type_(chrome::HOST_DESKTOP_TYPE_NATIVE) {
  db_thread_.Start();
}

BrowserWithTestWindowTest::~BrowserWithTestWindowTest() {
  db_thread_.Stop();
}

void BrowserWithTestWindowTest::SetHostDesktopType(
    chrome::HostDesktopType host_desktop_type) {
  DCHECK(!window_);
  host_desktop_type_ = host_desktop_type;
}

void BrowserWithTestWindowTest::SetUp() {
  testing::Test::SetUp();
#if defined(OS_CHROMEOS)
  // TODO(jamescook): Windows Ash support. This will require refactoring
  // AshTestHelper and AuraTestHelper so they can be used at the same time,
  // perhaps by AshTestHelper owning an AuraTestHelper.
  ash_test_helper_.reset(new ash::test::AshTestHelper(&ui_loop_));
  ash_test_helper_->SetUp();
#elif defined(USE_AURA)
  aura_test_helper_.reset(new aura::test::AuraTestHelper(&ui_loop_));
  aura_test_helper_->SetUp();
#endif  // USE_AURA

  // Subclasses can provide their own Profile.
  profile_.reset(CreateProfile());
  // Subclasses can provide their own test BrowserWindow. If they return NULL
  // then Browser will create the a production BrowserWindow and the subclass
  // is responsible for cleaning it up (usually by NativeWidget destruction).
  window_.reset(CreateBrowserWindow());

  Browser::CreateParams params(profile(), host_desktop_type_);
  params.window = window_.get();
  browser_.reset(new Browser(params));
}

void BrowserWithTestWindowTest::TearDown() {
  // Some tests end up posting tasks to the DB thread that must be completed
  // before the profile can be destroyed and the test safely shut down.
  base::WaitableEvent done(false, false);
  BrowserThread::PostTask(BrowserThread::DB, FROM_HERE,
      base::Bind(&base::WaitableEvent::Signal, base::Unretained(&done)));
  done.Wait();

  // Reset the profile here because some profile keyed services (like the
  // audio service) depend on test stubs that the helpers below will remove.
  DestroyBrowserAndProfile();

#if defined(OS_CHROMEOS)
  ash_test_helper_->TearDown();
#elif defined(USE_AURA)
  aura_test_helper_->TearDown();
#endif
  testing::Test::TearDown();

  // A Task is leaked if we don't destroy everything, then run the message
  // loop.
  base::MessageLoop::current()->PostTask(FROM_HERE,
                                         base::MessageLoop::QuitClosure());
  base::MessageLoop::current()->Run();
}

void BrowserWithTestWindowTest::AddTab(Browser* browser, const GURL& url) {
  chrome::NavigateParams params(browser, url, content::PAGE_TRANSITION_TYPED);
  params.tabstrip_index = 0;
  params.disposition = NEW_FOREGROUND_TAB;
  chrome::Navigate(&params);
  CommitPendingLoad(&params.target_contents->GetController());
}

void BrowserWithTestWindowTest::CommitPendingLoad(
  NavigationController* controller) {
  if (!controller->GetPendingEntry())
    return;  // Nothing to commit.

  RenderViewHost* old_rvh =
      controller->GetWebContents()->GetRenderViewHost();

  RenderViewHost* pending_rvh = RenderViewHostTester::GetPendingForController(
      controller);
  if (pending_rvh) {
    // Simulate the ShouldClose_ACK that is received from the current renderer
    // for a cross-site navigation.
    DCHECK_NE(old_rvh, pending_rvh);
    RenderViewHostTester::For(old_rvh)->SendShouldCloseACK(true);
  }
  // Commit on the pending_rvh, if one exists.
  RenderViewHost* test_rvh = pending_rvh ? pending_rvh : old_rvh;
  RenderViewHostTester* test_rvh_tester = RenderViewHostTester::For(test_rvh);

  // For new navigations, we need to send a larger page ID. For renavigations,
  // we need to send the preexisting page ID. We can tell these apart because
  // renavigations will have a pending_entry_index while new ones won't (they'll
  // just have a standalong pending_entry that isn't in the list already).
  if (controller->GetPendingEntryIndex() >= 0) {
    test_rvh_tester->SendNavigateWithTransition(
        controller->GetPendingEntry()->GetPageID(),
        controller->GetPendingEntry()->GetURL(),
        controller->GetPendingEntry()->GetTransitionType());
  } else {
    test_rvh_tester->SendNavigateWithTransition(
        controller->GetWebContents()->
            GetMaxPageIDForSiteInstance(test_rvh->GetSiteInstance()) + 1,
        controller->GetPendingEntry()->GetURL(),
        controller->GetPendingEntry()->GetTransitionType());
  }

  if (pending_rvh)
    RenderViewHostTester::For(old_rvh)->SimulateSwapOutACK();
}

void BrowserWithTestWindowTest::NavigateAndCommit(
    NavigationController* controller,
    const GURL& url) {
  controller->LoadURL(
      url, content::Referrer(), content::PAGE_TRANSITION_LINK, std::string());
  CommitPendingLoad(controller);
}

void BrowserWithTestWindowTest::NavigateAndCommitActiveTab(const GURL& url) {
  NavigateAndCommit(&browser()->tab_strip_model()->GetActiveWebContents()->
                        GetController(),
                    url);
}

void BrowserWithTestWindowTest::NavigateAndCommitActiveTabWithTitle(
    Browser* navigating_browser,
    const GURL& url,
    const string16& title) {
  NavigationController* controller = &navigating_browser->tab_strip_model()->
      GetActiveWebContents()->GetController();
  NavigateAndCommit(controller, url);
  controller->GetActiveEntry()->SetTitle(title);
}

void BrowserWithTestWindowTest::DestroyBrowserAndProfile() {
  if (browser_.get()) {
    // Make sure we close all tabs, otherwise Browser isn't happy in its
    // destructor.
    browser()->tab_strip_model()->CloseAllTabs();
    browser_.reset(NULL);
  }
  window_.reset(NULL);
  // Destroy the profile here - otherwise, if the profile is freed in the
  // destructor, and a test subclass owns a resource that the profile depends
  // on (such as g_browser_process()->local_state()) there's no way for the
  // subclass to free it after the profile.
  profile_.reset(NULL);
}

TestingProfile* BrowserWithTestWindowTest::CreateProfile() {
  return new TestingProfile();
}

BrowserWindow* BrowserWithTestWindowTest::CreateBrowserWindow() {
  return new TestBrowserWindow();
}

redpajama_set_name: RedPajamaGithub


text:
/* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/* ------------------------------------------------------------------------- */
namespace Cube.Xui.Tests.Behaviors;

using System.Collections.Generic;
using System.ComponentModel;
using System.Threading;
using Cube.Xui.Behaviors;
using Microsoft.Xaml.Behaviors;
using NUnit.Framework;

/* ------------------------------------------------------------------------- */
///
/// EventToCommandTest
///
/// <summary>
/// Tests event to command behaviors.
/// </summary>
///
/* ------------------------------------------------------------------------- */
[TestFixture]
[Apartment(ApartmentState.STA)]
class EventToCommandTest : ViewFixture
{
    #region Tests

    /* --------------------------------------------------------------------- */
    ///
    /// Show
    ///
    /// <summary>
    /// Tests the ShownToCommand class.
    /// </summary>
    ///
    /* --------------------------------------------------------------------- */
    [Test]
    public void Show()
    {
        var count = 0;
        var view  = Hack(new MockWindow());
        var src   = Attach(view, new ShownToCommand
        {
            Command = new DelegateCommand(() =>
            {
                ++count;
                view.Close();
            })
        });

        Assert.That(view.ShowDialog().Value, Is.False);
        src.Detach();
        Assert.That(count, Is.EqualTo(1));
    }

    /* --------------------------------------------------------------------- */
    ///
    /// Close
    ///
    /// <summary>
    /// Tests the ClosingToCommand, ClosedToCommand, and DisposeBehavior
    /// classes.
    /// </summary>
    ///
    /* --------------------------------------------------------------------- */
    [Test]
    public void Close()
    {
        var closing  = 0;
        var closed   = 0;

        var view = Hack(new MockWindow());
        var vm   = (MockViewModel)view.DataContext;
        var src  = new List<Behavior>
        {
            Attach(view, new ClosingToCommand { Command = new DelegateCommand<CancelEventArgs>(e => e.Cancel = ++closing % 2 == 1) }),
            Attach(view, new ClosedToCommand  { Command = new DelegateCommand(() => ++closed) }),
            Attach(view, new ClosedToDispose())
        };

        view.Show();
        for (var i = 0; i < 2; ++i) view.Close();
        foreach (var obj in src) obj.Detach();

        Assert.That(closing,     Is.EqualTo(2));
        Assert.That(closed,      Is.EqualTo(1));
        Assert.That(vm.Disposed, Is.True);
    }

    #endregion
}


text:
package authorizer

import (
	kapi "k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/auth/user"
	kerrors "k8s.io/kubernetes/pkg/util/errors"
	"k8s.io/kubernetes/pkg/util/sets"

	"github.com/openshift/origin/pkg/authorization/rulevalidation"
)

type openshiftAuthorizer struct {
	ruleResolver          rulevalidation.AuthorizationRuleResolver
	forbiddenMessageMaker ForbiddenMessageMaker
}

func NewAuthorizer(ruleResolver rulevalidation.AuthorizationRuleResolver, forbiddenMessageMaker ForbiddenMessageMaker) Authorizer {
	return &openshiftAuthorizer{ruleResolver, forbiddenMessageMaker}
}

func (a *openshiftAuthorizer) Authorize(ctx kapi.Context, passedAttributes AuthorizationAttributes) (bool, string, error) {
	attributes := coerceToDefaultAuthorizationAttributes(passedAttributes)

	// keep track of errors in case we are unable to authorize the action.
	// It is entirely possible to get an error and be able to continue determine authorization status in spite of it.
	// This is most common when a bound role is missing, but enough roles are still present and bound to authorize the request.
	errs := []error{}

	masterContext := kapi.WithNamespace(ctx, kapi.NamespaceNone)
	globalAllowed, globalReason, err := a.authorizeWithNamespaceRules(masterContext, attributes)
	if globalAllowed {
		return true, globalReason, nil
	}
	if err != nil {
		errs = append(errs, err)
	}

	namespace, _ := kapi.NamespaceFrom(ctx)
	if len(namespace) != 0 {
		namespaceAllowed, namespaceReason, err := a.authorizeWithNamespaceRules(ctx, attributes)
		if namespaceAllowed {
			return true, namespaceReason, nil
		}
		if err != nil {
			errs = append(errs, err)
		}
	}

	if len(errs) > 0 {
		return false, "", kerrors.NewAggregate(errs)
	}

	user, _ := kapi.UserFrom(ctx)
	denyReason, err := a.forbiddenMessageMaker.MakeMessage(MessageContext{user, namespace, attributes})
	if err != nil {
		denyReason = err.Error()
	}

	return false, denyReason, nil
}

// GetAllowedSubjects returns the subjects it knows can perform the action.
// If we got an error, then the list of subjects may not be complete, but it does not contain any incorrect names.
// This is done because policy rules are purely additive and policy determinations
// can be made on the basis of those rules that are found.
func (a *openshiftAuthorizer) GetAllowedSubjects(ctx kapi.Context, attributes AuthorizationAttributes) (sets.String, sets.String, error) {
	errs := []error{}

	masterContext := kapi.WithNamespace(ctx, kapi.NamespaceNone)
	globalUsers, globalGroups, err := a.getAllowedSubjectsFromNamespaceBindings(masterContext, attributes)
	if err != nil {
		errs = append(errs, err)
	}
	localUsers, localGroups, err := a.getAllowedSubjectsFromNamespaceBindings(ctx, attributes)
	if err != nil {
		errs = append(errs, err)
	}

	users := sets.String{}
	users.Insert(globalUsers.List()...)
	users.Insert(localUsers.List()...)

	groups := sets.String{}
	groups.Insert(globalGroups.List()...)
	groups.Insert(localGroups.List()...)

	return users, groups, kerrors.NewAggregate(errs)
}

func (a *openshiftAuthorizer) getAllowedSubjectsFromNamespaceBindings(ctx kapi.Context, passedAttributes AuthorizationAttributes) (sets.String, sets.String, error) {
	attributes := coerceToDefaultAuthorizationAttributes(passedAttributes)

	errs := []error{}

	roleBindings, err := a.ruleResolver.GetRoleBindings(ctx)
	if err != nil {
		return nil, nil, err
	}

	users := sets.String{}
	groups := sets.String{}
	for _, roleBinding := range roleBindings {
		role, err := a.ruleResolver.GetRole(roleBinding)
		if err != nil {
			// If we got an error, then the list of subjects may not be complete, but it does not contain any incorrect names.
			// This is done because policy rules are purely additive and policy determinations
			// can be made on the basis of those rules that are found.
			errs = append(errs, err)
			continue
		}

		for _, rule := range role.Rules() {
			matches, err := attributes.RuleMatches(rule)
			if err != nil {
				errs = append(errs, err)
				continue
			}

			if matches {
				users.Insert(roleBinding.Users().List()...)
				groups.Insert(roleBinding.Groups().List()...)
			}
		}
	}

	return users, groups, kerrors.NewAggregate(errs)
}

// authorizeWithNamespaceRules returns isAllowed, reason, and error.  If an error is returned, isAllowed and reason are still valid.  This seems strange
// but errors are not always fatal to the authorization process.  It is entirely possible to get an error and be able to continue determine authorization
// status in spite of it.  This is most common when a bound role is missing, but enough roles are still present and bound to authorize the request.
func (a *openshiftAuthorizer) authorizeWithNamespaceRules(ctx kapi.Context, passedAttributes AuthorizationAttributes) (bool, string, error) {
	attributes := coerceToDefaultAuthorizationAttributes(passedAttributes)

	allRules, ruleRetrievalError := a.ruleResolver.GetEffectivePolicyRules(ctx)

	for _, rule := range allRules {
		matches, err := attributes.RuleMatches(rule)
		if err != nil {
			return false, "", err
		}
		if matches {
			namespace := kapi.NamespaceValue(ctx)
			if len(namespace) == 0 {
				return true, "allowed by cluster rule", nil
			}
			return true, "allowed by rule in " + namespace, nil
		}
	}

	return false, "", ruleRetrievalError
}

// TODO this may or may not be the behavior we want for managing rules.  As a for instance, a verb might be specified
// that our attributes builder will never satisfy.  For now, I think gets us close.  Maybe a warning message of some kind?
func coerceToDefaultAuthorizationAttributes(passedAttributes AuthorizationAttributes) *DefaultAuthorizationAttributes {
	attributes, ok := passedAttributes.(*DefaultAuthorizationAttributes)
	if !ok {
		attributes = &DefaultAuthorizationAttributes{
			Verb:              passedAttributes.GetVerb(),
			RequestAttributes: passedAttributes.GetRequestAttributes(),
			Resource:          passedAttributes.GetResource(),
			ResourceName:      passedAttributes.GetResourceName(),
			NonResourceURL:    passedAttributes.IsNonResourceURL(),
			URL:               passedAttributes.GetURL(),
		}
	}

	return attributes
}

func doesApplyToUser(ruleUsers, ruleGroups sets.String, user user.Info) bool {
	if ruleUsers.Has(user.GetName()) {
		return true
	}

	for _, currGroup := range user.GetGroups() {
		if ruleGroups.Has(currGroup) {
			return true
		}
	}

	return false
}


text:
@interface TDLiteralTest : SenTestCase {
    PKParser *p;
    PKAssembly *a;
    NSString *s;
}

@end


text:
import os
import re
import pickle
import shutil
from datetime import datetime, date
from postproc.report import QuickReport
from postproc.plotting import *
from postproc.settings import *
from settings import RESEARCH_REL_DIR

# Create RESEARCH-ID. It is a small research which should link different local directories (with reports and time-integration) and ssh directories (with continuation, for example)
# What is included in RESEARCH?
# 1) It should be multistep. So we can always continue RESEARCH if we want
# 2) Everything should be dated and timed!
# 3) For every research we should create local directory having format @date@_@name@. Inside we should have directory "report" and file research.log where all stuff is stored
# If there are some remote calculations, then there should be "remote" directory where all that stuff is organized. Another directory is "local" which contains local results
# Somehow we should save python script reproducing the results (think about it).
# 4)

# Local directory hierarchy:
# ROOT for us is the directory where research.py was launch (as it is a part of postproc package, postproc.research is rather used)
# ROOT/RESEARCH_REL_DIR is main directory
# ROOT/RESEARCH_REL_DIR/research.log
# ROOT/RESEARCH_REL_DIR/report
# ROOT/RESEARCH_REL_DIR/1-some_task
# ROOT/RESEARCH_REL_DIR/2-another_task
# ROOT/RESEARCH_REL_DIR/3-one_more_task

# As we can have multiple remotes, a remote root directory should be set somewhere out of Research.
# One possible solution is a factory for Task.
# Anyway, we create directory hierarchy relative to REMOTE_ROOT as follows:
# REMOTE_ROOT/RESEARCH_REL_DIR/1-some_task
# REMOTE_ROOT/RESEARCH_REL_DIR/2-another_task
# REMOTE_ROOT/RESEARCH_REL_DIR/3-one_more_task

# Some usual cases:
# 1) Remote calculation on some cluster.
#       1.1 COPY-EXECUTE TASK
#           1.1.1 copy input files from local to remote
#           1.1.2 copy program from remote to remote
#           1.1.3 execute program
#       1.2 wait for finishing (at this moment, we just have to wait and check)
#       1.3 COPY-TASK
#           1.3.1 copy results from remote to local
#       1.4 as result, we will have results directly in the task directory

REPORT_DIR = 'report'
LOG_FILE = 'research.log'

class Task:
    def __init__(self, execution_host, command, is_global_command, copies_list):
        #self.remote_execution = remote_execution
        self.execution_host = execution_host
        self.command = command
        self.is_global_command = is_global_command
        self.copies_list = copies_list

class Research:
    def __init__(self, name, comm, continuing = False, comment = ''):
        self.__tasks_number = 0
        self.__communication = comm
        suitable_name = self.__make_suitable_name(name)
        if not continuing:
            # interpret name as name without date
            self.__research_id = str(date.today()) + '_' + suitable_name
            if os.path.exists(os.path.join(RESEARCH_REL_DIR, self.__research_id)):
                raise ResearchAlreadyExists("Research with name '%s' already exists, choose another name" % self.__research_id)
            os.makedirs(os.path.join(RESEARCH_REL_DIR, self.__research_id, REPORT_DIR))

            # Add to log
            log_lines = ['NEW RESEARCH: ' + str(self.__research_id), '\n', comment]
            self.write_log(log_lines, new_research = True)
        else:
            # interpret name as the full research id
            self.__research_id = suitable_name
            self.__load_research_data(self.__research_id)

    @classmethod
    def start_research(cls, name, comm, comment=''):
        return Research(name, comm, comment=comment)

    @classmethod
    def continue_research(cls, name, comm):
        return Research(name, comm, continuing=True)

    def __load_research_data(self, research_id):
        # find corresponding date/name
        # construct object from all data inside
        if not os.path.exists(os.path.join(RESEARCH_REL_DIR, research_id)):
            raise ResearchDoesNotExist("Research with name '%s' does not exist" % self.__research_id)
        dirnames = next(os.walk(os.path.join(RESEARCH_REL_DIR, research_id)))[1]
        self.__tasks_number = len(dirnames) - 1 # -1 corresponds to report dir

    def launch_task(self, task, name):
        is_remote_execution = isinstance(task.execution_host, RemoteHost)
        task_number = self.__get_next_task_number()
        local_task_dir = self.get_task_path(task_number, name)
        os.mkdir(local_task_dir)
        working_task_dir = self.get_task_path(task_number, name, task.execution_host)

        for copy_target in task.copies_list:
            self.__communication.copy(copy_target['path'], working_task_dir, copy_target['mode'])

        if task.command != '':
            full_command = ''
            if task.is_global_command:
                # to treat arguments of command properly, we need to go to the task directory
                full_command = 'cd ' + working_task_dir + ';' + task.command
            else:
                # assume that remote host has Unix-type path
                full_command = working_task_dir + '/' + task.command if is_remote_execution else os.path.join(working_task_dir, task.command)
            self.__communication.execute(full_command, is_remote=is_remote_execution)

        # Add to log
        log_lines = ['\tNEW TASK: ' + str(task_number), '\n', '\t\tCommand: ' + task.command, '\n']
        self.write_log(log_lines)

    def grab_task_results(self, task_number, copies_list=[]):
        task_name = self.__get_task_name_by_number(task_number)
        task_results_local_path = self.get_task_path(task_number, task_name)
        task_results_remote_path = self.get_task_path(task_number, task_name, self.__communication.remote_host)
        if len(copies_list) == 0: # copy all data
            pathes = self.__communication.listdir(task_results_remote_path)
            for file_or_dir in pathes:
                self.__communication.copy('/'.join((task_results_remote_path, file_or_dir)), task_results_local_path, 'from_remote')
        else:
            for copy_target in copies_list:
                remote_copy_target_path = '/'.join((task_results_remote_path, copy_target['path'])) # we consider copy targets as relative to task's dir
                self.__communication.copy(remote_copy_target_path, task_results_local_path, 'from_remote')
                if 'new_name' in copy_target:
                    os.rename(os.path.join(task_results_local_path, os.path.basename(copy_target['path'])), \
                              os.path.join(task_results_local_path, copy_target['new_name']))

    def cleanup(self, task_number, removes_list):
        for remove_target in removes_list:
            full_target_path = os.path.join(self.get_task_path(task_number), remove_target)
            print('\tRemoving ' + full_target_path)
            if os.path.isdir(full_target_path):
                shutil.rmtree(full_target_path)
            else:
                os.remove(full_target_path)

    def call_on_each(self, task_number, copies_list, percopy_func):
        for copy_target in copies_list:
            yield self.call_on_lazy_remote_data(task_number, copy_target, percopy_func)

    def call_on_lazy_remote_data(self, task_number, copy_target, func):
        self.grab_task_results(task_number, (copy_target,))
        actual_copy = copy_target['new_name'] if 'new_name' in copy_target else os.path.basename(copy_target['path'])
        print('Calling on ' + actual_copy)
        res = func(os.path.join(self.get_task_path(task_number), actual_copy))
        self.cleanup(task_number, (actual_copy,))
        return res

    def put_into_report(self, report_data):
        pass

    def write_log(self, lines, new_research = False):
        f = open(os.path.join(RESEARCH_REL_DIR, LOG_FILE), 'a')
        dt_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        if not new_research:
            dt_str += ', RESEARCH-ID: ' + self.__research_id
        f.writelines([dt_str, '\n'] + lines + ['\n\n'])

    def get_task_path(self, task_number, task_name=None, execution_host=None):
        if task_name is None:
            task_name = self.__get_task_name_by_number(task_number)
        task_path = ''
        rel_task_dir = os.path.join(self.__research_id, self.__get_task_full_name(task_number, task_name))
        if execution_host is None:
            task_path = os.path.join(RESEARCH_REL_DIR, rel_task_dir)
        else:
            task_path = os.path.join(execution_host.research_abs_path, rel_task_dir)
        return task_path

    def dump_object(self, task_number, obj, obj_name):
        print('Dumping ' + obj_name)
        f = open(os.path.join(self.get_task_path(task_number), obj_name + '.pyo'),'w')
        pickle.dump(obj, f)
        f.close()

    def load_object(self, task_number, obj_name):
        print('Loading ' + obj_name)
        f = open(os.path.join(self.get_task_path(task_number), obj_name + '.pyo'),'r')
        obj = pickle.load(f)
        f.close()
        return obj

#    def continue_task(self, task_number, task):
#        task_dir = '/'.join([RESEARCH_REL_DIR, research_id, task_name])
#        if not os.path.exists(task_dir):
#            raise Exception('Task named ' + task_name + ' does not exist')
#
#        self.__move_task_data(task.copies_list, comm, task_dir)
#        if task.command != '':
#            comm.execute(task.command)

    def __get_next_task_number(self):
        self.__tasks_number += 1
        return self.__tasks_number - 1

    def __get_task_full_name(self, task_number, task_name):
        return str(task_number) + '-' + self.__make_suitable_name(task_name)

    def __get_task_name_by_number(self, task_number):
        dirnames = next(os.walk(os.path.join(RESEARCH_REL_DIR, self.__research_id)))[1]
        for dir_ in dirnames:
            matching = re.search('%i-(?P<task_name>\w+)' % task_number, dir_)
            if matching is not None:
                return matching.group('task_name')
        raise Exception('No task with number ' + str(task_number) + ' is found')

    def __get_research_path(self, execution_host=None):
        path = ''
        if execution_host:
            is_remote_execution = isinstance(task.__execution_host, RemoteHost)
            rel_task_dir = os.path.join(self._research_id, str(task_number) + '-' + task)
            path = execution_host.research_abs_path if is_remote_execution else self.__get_local_research_path()
        else:
            path = self.__get_local_research_path()
        return path

    def __get_local_research_path(self):
        return os.path.join(RESEARCH_REL_DIR, self.__research_id)

    def __move_task_data(self, copies_list, task_dir):
        for copy_target in copies_list:
            self.__communication.copy(copy_target["path"], os.path.join(comm.main_dir, task_dir), copy_target["mode"])

    def __make_suitable_name(self, name):
        return '_'.join(name.split())

class ResearchAlreadyExists(Exception):
    pass

class ResearchDoesNotExist(Exception):
    pass

def get_all_research_ids():
    return os.listdir('.%s' % RESEARCH_REL_DIR)


text:
import pkg
__import__('pkg.a')
__import__('pkg.b')
print pkg.b


text:
<?xml version="1.0"?>
<!--
  ~ Yet Another UserAgent Analyzer
  ~ Copyright (C) 2013-2022 Niels Basjes
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~ https://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <artifactId>yauaa-udf-parent</artifactId>
    <groupId>nl.basjes.parse.useragent</groupId>
    <version>7.8.1-SNAPSHOT</version>
  </parent>
  <artifactId>yauaa-snowflake</artifactId>

  <name>Yauaa : UDF : Snowflake</name>
  <description>A parsing and analyzing library to get information from a useragent string.</description>

  <url>https://yauaa.basjes.nl</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>

    <dependency>
      <groupId>nl.basjes.parse.useragent</groupId>
      <artifactId>yauaa</artifactId>
    </dependency>

    <!-- The default logging implementation for Yauaa -->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>${log4j2.version}</version>
    </dependency>

    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-slf4j-impl</artifactId>
      <version>${log4j2.version}</version>
    </dependency>

    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-jcl</artifactId>
      <version>${log4j2.version}</version>
    </dependency>

  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>${maven-assembly-plugin.version}</version>
        <executions>
          <execution>
            <id>make-super-jar</id>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
            <configuration>
              <descriptors>
                <descriptor>src/main/assembly/udf.xml</descriptor>
              </descriptors>
              <archive>
                <addMavenDescriptor>true</addMavenDescriptor>
                <manifestEntries>
                  <Class-Path>/</Class-Path>
                </manifestEntries>
              </archive>
            </configuration>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <groupId>com.github.spotbugs</groupId>
        <artifactId>spotbugs-maven-plugin</artifactId>
        <version>${spotbugs-maven-plugin.version}</version>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-checkstyle-plugin</artifactId>
        <version>${maven-checkstyle-plugin.version}</version>
      </plugin>

      <plugin>
        <groupId>org.jacoco</groupId>
        <artifactId>jacoco-maven-plugin</artifactId>
        <version>${jacoco-maven-plugin.version}</version>
      </plugin>

      <plugin>
        <groupId>com.alexecollins.maven.plugin</groupId>
        <artifactId>script-maven-plugin</artifactId>
        <version>${script-maven-plugin.version}</version>
        <executions>
          <execution>
            <id>Verify jar contents to ensure the shading of dependencies went right</id>
            <phase>verify</phase>
            <goals>
              <goal>execute</goal>
            </goals>

            <configuration>
              <language>beanshell</language>
              <script>
                import java.io.*;
                import java.util.jar.*;
                import java.util.Arrays;
                import org.codehaus.plexus.util.*;

                System.out.println("Verifying if the shading went correctly");

                String[] libraryWanted = {
                  "nl/basjes/parse/useragent/utils/YauaaVersion.class",
                  "org/slf4j/LoggerFactory.class",
                  "nl/basjes/shaded/org/antlr/v4/runtime/Parser.class",
                  "nl/basjes/shaded/org/springframework/core/io/support/PathMatchingResourcePatternResolver.class",
                  "nl/basjes/parse/useragent/snowflake/ParseUserAgent.class",
                };

                String[] libraryUnwanted = {
                  "org/antlr/v4/runtime/Parser.class",
                  "org/springframework/core/io/support/PathMatchingResourcePatternResolver.class",
                };

                JarFile libraryJarFile = new JarFile( new File( "${project.basedir}/target", "yauaa-snowflake-${project.version}-udf.jar" ) );

                for ( String path : libraryWanted ) {
                  if ( libraryJarFile.getEntry( path ) == null ) {
                    throw new IllegalStateException( "Library: wanted path is missing: " + path );
                  }
                }

                for ( String path : libraryUnwanted ) {
                  if ( libraryJarFile.getEntry( path ) != null ) {
                    throw new IllegalStateException( "Library: unwanted path is present: " + path );
                  }
                }
              </script>
            </configuration>
          </execution>
        </executions>
        <dependencies>
          <dependency>
            <groupId>org.apache-extras.beanshell</groupId>
            <artifactId>bsh</artifactId>
            <version>2.0b6</version>
          </dependency>
        </dependencies>
      </plugin>

    </plugins>

  </build>

  <licenses>
    <license>
      <name>Apache License, Version 2.0</name>
      <url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
      <distribution>repo</distribution>
    </license>
  </licenses>

  <developers>
    <developer>
      <name>Niels Basjes</name>
      <email>niels@basjes.nl</email>
      <roles>
        <role>Architect</role>
        <role>Developer</role>
      </roles>
      <timezone>Europe/Amsterdam</timezone>
    </developer>
  </developers>

  <scm>
    <url>https://github.com/nielsbasjes/yauaa</url>
    <connection>scm:git:https://github.com/nielsbasjes/yauaa.git</connection>
    <developerConnection>scm:git:file:///${project.basedir}</developerConnection>
    <tag>v7.6.0</tag>
  </scm>

</project>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>

Loading...

  HCTX
  WintabDN

  HCtx
  WintabDN::CWintabContext

  HWND
  WintabDN

Searching...

No Matches


text:
class MessageCenterSettingsControllerTest : public testing::Test {
 protected:
  MessageCenterSettingsControllerTest()
      : testing_profile_manager_(TestingBrowserProcess::GetGlobal()) {};
  virtual ~MessageCenterSettingsControllerTest() {};

  base::FilePath GetProfilePath(const std::string& base_name) {
    return testing_profile_manager_.profile_manager()->user_data_dir()
        .AppendASCII(base_name);
  }

  virtual void SetUp() OVERRIDE {
    ASSERT_TRUE(testing_profile_manager_.SetUp());
  }

  ProfileInfoCache* GetCache() {
    return testing_profile_manager_.profile_info_cache();
  }

  void CreateProfile(const std::string& name) {
    testing_profile_manager_.CreateTestingProfile(name);
  }

  TestingProfileManager testing_profile_manager_;
};

TEST_F(MessageCenterSettingsControllerTest, NotifierGroups) {
  CreateProfile("Profile-1");
  CreateProfile("Profile-2");

  scoped_ptr<MessageCenterSettingsController> controller(
      new MessageCenterSettingsController(GetCache()));

  EXPECT_EQ(controller->GetNotifierGroupCount(), 2u);

  EXPECT_EQ(controller->GetNotifierGroupAt(0).name, UTF8ToUTF16("Profile-1"));
  EXPECT_EQ(controller->GetNotifierGroupAt(0).index, 0u);

  EXPECT_EQ(controller->GetNotifierGroupAt(1).name, UTF8ToUTF16("Profile-2"));
  EXPECT_EQ(controller->GetNotifierGroupAt(1).index, 1u);

  EXPECT_EQ(controller->GetActiveNotifierGroup().name,
            UTF8ToUTF16("Profile-1"));
  EXPECT_EQ(controller->GetActiveNotifierGroup().index, 0u);

  controller->SwitchToNotifierGroup(1);
  EXPECT_EQ(controller->GetActiveNotifierGroup().name,
            UTF8ToUTF16("Profile-2"));
  EXPECT_EQ(controller->GetActiveNotifierGroup().index, 1u);

  controller->SwitchToNotifierGroup(0);
  EXPECT_EQ(controller->GetActiveNotifierGroup().name,
            UTF8ToUTF16("Profile-1"));
}

// TODO(mukai): write a test case to reproduce the actual guest session scenario
// in ChromeOS -- no profiles in the profile_info_cache but GetDefaultProfile
// returns a new one.


text:
<?php
session_start();

$GLOBALS['config'] = array(
		'mysql' => array(
				'host' => 'localhost',
				'username' => 'basic',
				'password' => 'SAew2FdMHVYAHP9F',
				'db' => 'ronin',
		),
		'remember' => array(
				'cookie_name' => 'hash',
				'cookie_expiry' => 604800,
		),
		'session' => array(
				'user_session_name' => 'user',
				'token_name' => 'token',
		),
);

spl_autoload_register(function($className) {
	$className = ltrim($className, '\\');
	$fileName = '';
	$namespace = '';

	if ($lastNsPos = strripos($className, '\\')) {
		$namespace = substr($className, 0, $lastNsPos);
		$className = substr($className, $lastNsPos + 1);
		$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
	}

	$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';

	try {
		if (!file_exists($fileName)) {
			throw new Exception("$className does not exist");
		} else {
			require $fileName;
		}
	} catch (Exception $e) { //this catch is simply accepting its own thrown error - probably not the best method...no seems ok..
		//echo $e->getMessage() . "<br>";
	}
});


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ============================================================
//
// AssemblyName.cpp
//

//
// Implements the AssemblyName class
//
// ============================================================

#define DISABLE_BINDER_DEBUG_LOGGING

#include "assemblyname.hpp"
#include "assembly.hpp"
#include "utils.hpp"
#include "variables.hpp"

#include "fusionassemblyname.hpp"

#include "textualidentityparser.hpp"

#include "corpriv.h"

#include "ex.h"

namespace BINDER_SPACE
{
    AssemblyName::AssemblyName()
    {
        m_cRef = 1;
        m_dwNameFlags = NAME_FLAG_NONE;
        // Default values present in every assembly name
        SetHave(AssemblyIdentity::IDENTITY_FLAG_CULTURE |
                AssemblyIdentity::IDENTITY_FLAG_PUBLIC_KEY_TOKEN_NULL);
    }

    AssemblyName::~AssemblyName()
    {
        //  Nothing to do here
    }

    HRESULT AssemblyName::Init(IMDInternalImport       *pIMetaDataAssemblyImport,
                               PEKIND                   PeKind,
                               mdAssemblyRef            mdar /* = 0 */,
                               BOOL                     fIsDefinition /* = TRUE */)
    {
        HRESULT hr = S_OK;
        mdAssembly mda = 0;
        AssemblyMetaDataInternal amd = {0};
        CONST VOID *pvPublicKeyToken = NULL;
        DWORD dwPublicKeyToken = 0;
        LPCSTR pAssemblyName = NULL;
        DWORD dwRefOrDefFlags = 0;
        DWORD dwHashAlgId = 0;

        BINDER_LOG_ENTER(L"AssemblyName::Init(IMetaDataAssemblyImport)");

        if (fIsDefinition)
        {
            // Get the assembly token
            IF_FAIL_GO(pIMetaDataAssemblyImport->GetAssemblyFromScope(&mda));
        }

        BINDER_LOG(L"Have mda scope!");

        // Get name and metadata
        if (fIsDefinition)
        {
            IF_FAIL_GO(pIMetaDataAssemblyImport->GetAssemblyProps(
                            mda,            // [IN] The Assembly for which to get the properties.
                            &pvPublicKeyToken,  // [OUT] Pointer to the PublicKeyToken blob.
                            &dwPublicKeyToken,  // [OUT] Count of bytes in the PublicKeyToken Blob.
                            &dwHashAlgId,   // [OUT] Hash Algorithm.
                            &pAssemblyName, // [OUT] Name.
                            &amd,           // [OUT] Assembly MetaData.
                            &dwRefOrDefFlags // [OUT] Flags.
                            ));
        }
        else
        {
            IF_FAIL_GO(pIMetaDataAssemblyImport->GetAssemblyRefProps(
                            mdar,            // [IN] The Assembly for which to get the properties.
                            &pvPublicKeyToken,  // [OUT] Pointer to the PublicKeyToken blob.
                            &dwPublicKeyToken,  // [OUT] Count of bytes in the PublicKeyToken Blob.
                            &pAssemblyName, // [OUT] Name.
                            &amd,           // [OUT] Assembly MetaData.
                            NULL, // [OUT] Hash blob.
                            NULL, // [OUT] Count of bytes in hash blob.
                            &dwRefOrDefFlags // [OUT] Flags.
                            ));
        }

        BINDER_LOG(L"Have props!");

        {
            StackSString culture;
            culture.SetUTF8(amd.szLocale);
            culture.Normalize();

            SString::CIterator itr = culture.Begin();
            if (culture.Find(itr, L';'))
            {
                culture = SString(culture, culture.Begin(), itr-1);
            }

            SetCulture(culture);
        }

        {
            StackSString assemblyName;
            assemblyName.SetUTF8(pAssemblyName);
            assemblyName.Normalize();

            COUNT_T assemblyNameLength = assemblyName.GetCount();
            if (assemblyNameLength == 0 || assemblyNameLength >= MAX_PATH_FNAME)
            {
                IF_FAIL_GO(FUSION_E_INVALID_NAME);
            }

            SetSimpleName(assemblyName);
        }

        // See if the assembly[def] is retargetable (ie, for a generic assembly).
        if (IsAfRetargetable(dwRefOrDefFlags))
        {
            SetIsRetargetable(TRUE);
        }

        // Set ContentType
        if (IsAfContentType_Default(dwRefOrDefFlags))
        {
            SetContentType(AssemblyContentType_Default);
        }
        else if (IsAfContentType_WindowsRuntime(dwRefOrDefFlags))
        {
            SetContentType(AssemblyContentType_WindowsRuntime);
        }
        else
        {
            IF_FAIL_GO(FUSION_E_INVALID_NAME);
        }

        // Set the assembly version
        {
            AssemblyVersion *pAssemblyVersion = GetVersion();

            pAssemblyVersion->SetFeatureVersion(amd.usMajorVersion, amd.usMinorVersion);
            pAssemblyVersion->SetServiceVersion(amd.usBuildNumber, amd.usRevisionNumber);
            SetHave(AssemblyIdentity::IDENTITY_FLAG_VERSION);
        }

        // Set public key and/or public key token (if we have it)
        if (pvPublicKeyToken && dwPublicKeyToken)
        {
            SBuffer publicKeyOrTokenBLOB((const BYTE *) pvPublicKeyToken, dwPublicKeyToken);

            if (IsAfPublicKey(dwRefOrDefFlags))
            {
                SBuffer publicKeyTokenBLOB;

                IF_FAIL_GO(GetTokenFromPublicKey(publicKeyOrTokenBLOB, publicKeyTokenBLOB));
                GetPublicKeyTokenBLOB().Set(publicKeyTokenBLOB);
            }
            else
            {
                GetPublicKeyTokenBLOB().Set(publicKeyOrTokenBLOB);
            }

            SetHave(AssemblyIdentity::IDENTITY_FLAG_PUBLIC_KEY_TOKEN);
        }

        SetArchitecture(PeKind);

    Exit:
        BINDER_LOG_LEAVE_HR(L"AssemblyName::Init(IMetaDataAssemblyImport)", hr);
        return hr;
    }

    HRESULT AssemblyName::Init(SString &assemblyDisplayName)
    {
        HRESULT hr = S_OK;
        BINDER_LOG_ENTER(L"AssemblyName::Init(assemblyDisplayName)");

        BINDER_LOG_STRING(L"assemblyDisplayName", assemblyDisplayName);

        IF_FAIL_GO(TextualIdentityParser::Parse(assemblyDisplayName, this));

    Exit:
        BINDER_LOG_LEAVE_HR(L"AssemblyName::Init(assemblyDisplayName)", hr);
        return hr;
    }

    HRESULT AssemblyName::Init(IAssemblyName *pIAssemblyName)
    {
        HRESULT hr = S_OK;

        _ASSERTE(pIAssemblyName != NULL);

        EX_TRY
        {
            {
                // Set the simpleName
                StackSString simpleName;
                hr = fusion::util::GetSimpleName(pIAssemblyName, simpleName);
                IF_FAIL_GO(hr);
                SetSimpleName(simpleName);
                SetHave(BINDER_SPACE::AssemblyIdentity::IDENTITY_FLAG_SIMPLE_NAME);
            }

            // Display version
            DWORD dwVersionParts[4] = {0,0,0,0};
            DWORD cbVersionSize = sizeof(dwVersionParts[0]);
            hr = fusion::util::GetProperty(pIAssemblyName, ASM_NAME_MAJOR_VERSION, static_cast<PVOID>(&dwVersionParts[0]), &cbVersionSize);
            IF_FAIL_GO(hr);
            if ((hr == S_OK) && (cbVersionSize != 0))
            {
                // Property is present - loop to get the individual version details
                for(DWORD i = 0; i < 4; i++)
                {
                    cbVersionSize = sizeof(dwVersionParts[i]);
                    hr = fusion::util::GetProperty(pIAssemblyName, ASM_NAME_MAJOR_VERSION+i, static_cast<PVOID>(&dwVersionParts[i]), &cbVersionSize);
                    IF_FAIL_GO(hr);
                }

                m_version.SetFeatureVersion(dwVersionParts[0], dwVersionParts[1]);
                m_version.SetServiceVersion(dwVersionParts[2], dwVersionParts[3]);
                SetHave(BINDER_SPACE::AssemblyIdentity::IDENTITY_FLAG_VERSION);
            }

            {
                // Display culture
                StackSString culture;
                hr = fusion::util::GetProperty(pIAssemblyName, ASM_NAME_CULTURE, culture);
                IF_FAIL_GO(hr);
                if (hr == S_OK)
                {
                    SetCulture(culture);
                    SetHave(BINDER_SPACE::AssemblyIdentity::IDENTITY_FLAG_CULTURE);
                }
            }

            {
                // Display public key token
                NewArrayHolder<BYTE> pPublicKeyToken;
                DWORD cbPublicKeyToken = 0;
                hr = fusion::util::GetProperty(pIAssemblyName, ASM_NAME_PUBLIC_KEY_TOKEN, static_cast<PBYTE*>(&pPublicKeyToken), &cbPublicKeyToken);
                IF_FAIL_GO(hr);
                if ((hr == S_OK) && (cbPublicKeyToken != 0))
                {
                    m_publicKeyOrTokenBLOB.Set(pPublicKeyToken, cbPublicKeyToken);
                    SetHave(BINDER_SPACE::AssemblyIdentity::IDENTITY_FLAG_PUBLIC_KEY_TOKEN);
                }
                else
                {
                    SetHave(BINDER_SPACE::AssemblyIdentity::IDENTITY_FLAG_PUBLIC_KEY_TOKEN_NULL);
                }
            }

            // Display processor architecture
            DWORD peKind = 0;
            DWORD cbPeKind = sizeof(peKind);
            hr = fusion::util::GetProperty(pIAssemblyName, ASM_NAME_ARCHITECTURE, static_cast<PVOID>(&peKind), &cbPeKind);
            IF_FAIL_GO(hr);
            if ((hr == S_OK) && (cbPeKind != 0))
            {
                PEKIND PeKind = (PEKIND)peKind;
                if (PeKind != peNone)
                {
                    SetArchitecture(PeKind);
                    SetHave(BINDER_SPACE::AssemblyIdentity::IDENTITY_FLAG_PROCESSOR_ARCHITECTURE);
                }
            }

            // Display retarget flag
            BOOL fRetarget = FALSE;
            DWORD cbRetarget = sizeof(fRetarget);
            hr = fusion::util::GetProperty(pIAssemblyName, ASM_NAME_RETARGET, static_cast<PVOID>(&fRetarget), &cbRetarget);
            IF_FAIL_GO(hr);
            if ((hr == S_OK) && (cbRetarget != 0))
            {
                if (fRetarget)
                {
                    SetIsRetargetable(fRetarget);
                    SetHave(BINDER_SPACE::AssemblyIdentity::IDENTITY_FLAG_RETARGETABLE);
                }
            }

            // Display content type
            DWORD dwContentType = AssemblyContentType_Default;
            DWORD cbContentType = sizeof(dwContentType);
            hr = fusion::util::GetProperty(pIAssemblyName, ASM_NAME_CONTENT_TYPE, static_cast<PVOID>(&dwContentType), &cbContentType);
            IF_FAIL_GO(hr);
            if ((hr == S_OK) && (cbContentType != 0))
            {
                if (dwContentType != AssemblyContentType_Default)
                {
                    SetHave(BINDER_SPACE::AssemblyIdentity::IDENTITY_FLAG_CONTENT_TYPE);
                    SetContentType((AssemblyContentType)dwContentType);
                }
            }

            {
                // Display custom flag. Dont set it if it is not present since that will end up adding the "Custom=null" attribute
                // in the displayname of the assembly that maybe generated using this AssemblyName instance. This could create conflict when
                // the displayname is generated from the assembly directly as that will not have a "Custom" field set.
                NewArrayHolder<BYTE> pCustomBLOB;
                DWORD cbCustomBLOB = 0;
                hr = fusion::util::GetProperty(pIAssemblyName, ASM_NAME_CUSTOM, static_cast<PBYTE*>(&pCustomBLOB), &cbCustomBLOB);
                IF_FAIL_GO(hr);
                if ((hr == S_OK) && (cbCustomBLOB != 0))
                {
                    m_customBLOB.Set(pCustomBLOB, cbCustomBLOB);
                    SetHave(BINDER_SPACE::AssemblyIdentity::IDENTITY_FLAG_CUSTOM);
                }
            }
        }
        EX_CATCH_HRESULT(hr);
Exit:
        return hr;
    }

    HRESULT AssemblyName::CreateFusionName(IAssemblyName **ppIAssemblyName)
    {
        HRESULT hr = S_OK;
        ReleaseHolder<IAssemblyName> pIAssemblyName;

        IF_FAIL_GO(CreateAssemblyNameObject(&pIAssemblyName, NULL, 0, NULL));

        IF_FAIL_GO(LegacyFusion::SetStringProperty(pIAssemblyName, ASM_NAME_NAME, GetSimpleName()));

        if (Have(AssemblyIdentity::IDENTITY_FLAG_VERSION))
        {
            AssemblyVersion *pAssemblyVersion = GetVersion();

            IF_FAIL_GO(LegacyFusion::SetWordProperty(pIAssemblyName,
                                       ASM_NAME_MAJOR_VERSION,
                                       pAssemblyVersion->GetMajor()));
            IF_FAIL_GO(LegacyFusion::SetWordProperty(pIAssemblyName,
                                       ASM_NAME_MINOR_VERSION,
                                       pAssemblyVersion->GetMinor()));
            IF_FAIL_GO(LegacyFusion::SetWordProperty(pIAssemblyName,
                                       ASM_NAME_BUILD_NUMBER,
                                       pAssemblyVersion->GetBuild()));
            IF_FAIL_GO(LegacyFusion::SetWordProperty(pIAssemblyName,
                                       ASM_NAME_REVISION_NUMBER,
                                       pAssemblyVersion->GetRevision()));
        }

        if (Have(AssemblyIdentity::IDENTITY_FLAG_CULTURE))
        {
            IF_FAIL_GO(LegacyFusion::SetStringProperty(pIAssemblyName, ASM_NAME_CULTURE, GetCulture()));
        }

        if (Have(AssemblyIdentity::IDENTITY_FLAG_PUBLIC_KEY))
        {
            // GetPublicKeyTokenBLOB contains either PK or PKT.
            IF_FAIL_GO(LegacyFusion::SetBufferProperty(pIAssemblyName,
                                         ASM_NAME_PUBLIC_KEY,
                                         GetPublicKeyTokenBLOB()));
        }
        else if (Have(AssemblyIdentity::IDENTITY_FLAG_PUBLIC_KEY_TOKEN))
        {
            // GetPublicKeyTokenBLOB contains either PK or PKT.
            IF_FAIL_GO(LegacyFusion::SetBufferProperty(pIAssemblyName,
                                         ASM_NAME_PUBLIC_KEY_TOKEN,
                                         GetPublicKeyTokenBLOB()));
        }

        if (Have(AssemblyIdentity::IDENTITY_FLAG_PROCESSOR_ARCHITECTURE))
        {
            IF_FAIL_GO(LegacyFusion::SetDwordProperty(pIAssemblyName,
                                        ASM_NAME_ARCHITECTURE,
                                        static_cast<DWORD>(GetArchitecture())));
        }

        if (Have(AssemblyIdentity::IDENTITY_FLAG_CONTENT_TYPE))
        {
            IF_FAIL_GO(LegacyFusion::SetDwordProperty(pIAssemblyName,
                                        ASM_NAME_CONTENT_TYPE,
                                        GetContentType()));
        }

        *ppIAssemblyName = pIAssemblyName.Extract();

    Exit:
        return hr;
    }

    ULONG AssemblyName::AddRef()
    {
        return InterlockedIncrement(&m_cRef);
    }

    ULONG AssemblyName::Release()
    {
        ULONG ulRef = InterlockedDecrement(&m_cRef);
        if (ulRef == 0)
        {
            delete this;
        }
        return ulRef;
    }

    SString &AssemblyName::GetDeNormalizedCulture()
    {
        SString &culture = GetCulture();

        if (EqualsCaseInsensitive(culture, g_BinderVariables->cultureNeutral))
        {
            culture = g_BinderVariables->emptyString;
        }

        return culture;
    }

    BOOL AssemblyName::IsStronglyNamed()
    {
        return Have(AssemblyIdentity::IDENTITY_FLAG_PUBLIC_KEY_TOKEN);
    }

    BOOL AssemblyName::IsMscorlib()
    {
        // TODO: Is this simple comparison enough?
        return EqualsCaseInsensitive(GetSimpleName(), g_BinderVariables->mscorlib);
    }

    HRESULT AssemblyName::SetArchitecture(SString &architecture)
    {
        HRESULT hr = S_OK;

        if (architecture.IsEmpty())
        {
            SetArchitecture(peNone);
        }
        else if (EqualsCaseInsensitive(architecture, g_BinderVariables->architectureMSIL))
        {
            SetArchitecture(peMSIL);
        }
        else if (EqualsCaseInsensitive(architecture, g_BinderVariables->architectureX86))
        {
            SetArchitecture(peI386);
        }
        else if (EqualsCaseInsensitive(architecture, g_BinderVariables->architectureAMD64))
        {
            SetArchitecture(peAMD64);
        }
        else if (EqualsCaseInsensitive(architecture, g_BinderVariables->architectureARM))
        {
            SetArchitecture(peARM);
        }
        else if (EqualsCaseInsensitive(architecture, g_BinderVariables->architectureARM64))
        {
            SetArchitecture(peARM64);
        }
        else
        {
            hr = FUSION_E_MANIFEST_PARSE_ERROR;
        }

        return hr;
    }

    ULONG AssemblyName::Hash(DWORD dwIncludeFlags)
    {
        DWORD dwHash = 0;
        DWORD dwUseIdentityFlags = m_dwIdentityFlags;

        // Prune unwanted name parts
        if ((dwIncludeFlags & INCLUDE_VERSION) == 0)
        {
            dwUseIdentityFlags &= ~AssemblyIdentity::IDENTITY_FLAG_VERSION;
        }
        if ((dwIncludeFlags & INCLUDE_ARCHITECTURE) == 0)
        {
            dwUseIdentityFlags &= ~AssemblyIdentity::IDENTITY_FLAG_PROCESSOR_ARCHITECTURE;
        }
        if ((dwIncludeFlags & INCLUDE_RETARGETABLE) == 0)
        {
            dwUseIdentityFlags &= ~AssemblyIdentity::IDENTITY_FLAG_RETARGETABLE;
        }
        if ((dwIncludeFlags & INCLUDE_CONTENT_TYPE) == 0)
        {
            dwUseIdentityFlags &= ~AssemblyIdentity::IDENTITY_FLAG_CONTENT_TYPE;
        }
        if ((dwIncludeFlags & INCLUDE_PUBLIC_KEY_TOKEN) == 0)
        {
            dwUseIdentityFlags &= ~AssemblyIdentity::IDENTITY_FLAG_PUBLIC_KEY;
            dwUseIdentityFlags &= ~AssemblyIdentity::IDENTITY_FLAG_PUBLIC_KEY_TOKEN;
        }
        if ((dwIncludeFlags & EXCLUDE_CULTURE) != 0)
        {
            dwUseIdentityFlags &= ~AssemblyIdentity::IDENTITY_FLAG_CULTURE;
        }

        dwHash ^= static_cast<DWORD>(HashCaseInsensitive(GetSimpleName()));
        dwHash = _rotl(dwHash, 4);

        if (AssemblyIdentity::Have(dwUseIdentityFlags,
                                   AssemblyIdentity::IDENTITY_FLAG_PUBLIC_KEY) ||
            AssemblyIdentity::Have(dwUseIdentityFlags,
                                   AssemblyIdentity::IDENTITY_FLAG_PUBLIC_KEY_TOKEN))
        {
            const BYTE *pbPublicKeyOrToken = GetPublicKeyTokenBLOB();
            DWORD dwcbPublicKeyOrToken = GetPublicKeyTokenBLOB().GetSize();

            _ASSERTE(pbPublicKeyOrToken != NULL);

            dwHash ^= HashBytes(pbPublicKeyOrToken, dwcbPublicKeyOrToken);
            dwHash = _rotl(dwHash, 4);
        }

        if (AssemblyIdentity::Have(dwUseIdentityFlags, AssemblyIdentity::IDENTITY_FLAG_VERSION))
        {
            AssemblyVersion *pAssemblyVersion = GetVersion();

            dwHash ^= pAssemblyVersion->GetMajor();
            dwHash = _rotl(dwHash, 8);
            dwHash ^= pAssemblyVersion->GetMinor();
            dwHash = _rotl(dwHash, 8);
            dwHash ^= pAssemblyVersion->GetBuild();
            dwHash = _rotl(dwHash, 8);
            dwHash ^= pAssemblyVersion->GetRevision();
            dwHash = _rotl(dwHash, 8);
        }

        if (AssemblyIdentity::Have(dwUseIdentityFlags, AssemblyIdentity::IDENTITY_FLAG_CULTURE))
        {
            dwHash ^= static_cast<DWORD>(HashCaseInsensitive(GetNormalizedCulture()));
            dwHash = _rotl(dwHash, 4);
        }

        if (AssemblyIdentity::Have(dwUseIdentityFlags,
                                   AssemblyIdentity::IDENTITY_FLAG_RETARGETABLE))
        {
            dwHash ^= 1;
            dwHash = _rotl(dwHash, 4);
        }

        if (AssemblyIdentity::Have(dwUseIdentityFlags,
                                   AssemblyIdentity::IDENTITY_FLAG_PROCESSOR_ARCHITECTURE))
        {
            dwHash ^= static_cast<DWORD>(GetArchitecture());
            dwHash = _rotl(dwHash, 4);
        }

        if (AssemblyIdentity::Have(dwUseIdentityFlags,
                                   AssemblyIdentity::IDENTITY_FLAG_CONTENT_TYPE))
        {
            dwHash ^= static_cast<DWORD>(GetContentType());
            dwHash = _rotl(dwHash, 4);
        }

        return static_cast<ULONG>(dwHash);
    }

    BOOL AssemblyName::Equals(AssemblyName *pAssemblyName,
                              DWORD         dwIncludeFlags)
    {
        BOOL fEquals = FALSE;

        if (GetContentType() == AssemblyContentType_WindowsRuntime)
        {   // Assembly is meaningless for WinRT, all assemblies form one joint type namespace
            return (GetContentType() == pAssemblyName->GetContentType());
        }

        if (EqualsCaseInsensitive(GetSimpleName(), pAssemblyName->GetSimpleName()) &&
            (GetContentType() == pAssemblyName->GetContentType()))
        {
            fEquals = TRUE;

            if ((dwIncludeFlags & EXCLUDE_CULTURE) == 0)
            {
                fEquals = EqualsCaseInsensitive(GetNormalizedCulture(), pAssemblyName->GetNormalizedCulture());
            }

            if (fEquals && (dwIncludeFlags & INCLUDE_PUBLIC_KEY_TOKEN) != 0)
            {
                fEquals = (GetPublicKeyTokenBLOB().Equals(pAssemblyName->GetPublicKeyTokenBLOB()));
            }

            if (fEquals && ((dwIncludeFlags & INCLUDE_ARCHITECTURE) != 0))
            {
                fEquals = (GetArchitecture() == pAssemblyName->GetArchitecture());
            }

            if (fEquals && ((dwIncludeFlags & INCLUDE_VERSION) != 0))
            {
                fEquals = GetVersion()->Equals(pAssemblyName->GetVersion());
            }

            if (fEquals && ((dwIncludeFlags & INCLUDE_RETARGETABLE) != 0))
            {
                fEquals = (GetIsRetargetable() == pAssemblyName->GetIsRetargetable());
            }
        }

        return fEquals;
    }

    BOOL AssemblyName::RefEqualsDef(AssemblyName *pAssemblyNameDef,
                                    BOOL          fInspectionOnly)
    {
        BOOL fEquals = FALSE;

        if (GetContentType() == AssemblyContentType_WindowsRuntime)
        {   // Assembly is meaningless for WinRT, all assemblies form one joint type namespace
            return (GetContentType() == pAssemblyNameDef->GetContentType());
        }

        if (EqualsCaseInsensitive(GetSimpleName(), pAssemblyNameDef->GetSimpleName()) &&
            EqualsCaseInsensitive(GetNormalizedCulture(),
                                  pAssemblyNameDef->GetNormalizedCulture()) &&
            GetPublicKeyTokenBLOB().Equals(pAssemblyNameDef->GetPublicKeyTokenBLOB()) &&
            (GetContentType() == pAssemblyNameDef->GetContentType()))
        {
            PEKIND kRefArchitecture = GetArchitecture();
            PEKIND kDefArchitecture = pAssemblyNameDef->GetArchitecture();

            if (kRefArchitecture == peNone)
            {
                fEquals = (fInspectionOnly ||
                           (kDefArchitecture == peNone) ||
                           (kDefArchitecture == peMSIL) ||
                           (kDefArchitecture == Assembly::GetSystemArchitecture()));
            }
            else
            {
                fEquals = (kRefArchitecture == kDefArchitecture);
            }
        }

        return fEquals;
    }

    HRESULT AssemblyName::Clone(AssemblyName **ppAssemblyName)
    {
        HRESULT hr = S_OK;
        AssemblyName *pClonedAssemblyName = NULL;

        SAFE_NEW(pClonedAssemblyName, AssemblyName);
        CloneInto(pClonedAssemblyName);
        pClonedAssemblyName->m_dwNameFlags = m_dwNameFlags;

        *ppAssemblyName = pClonedAssemblyName;

    Exit:
        return hr;
    }

    void AssemblyName::GetDisplayName(PathString &displayName,
                                      DWORD       dwIncludeFlags)
    {
        DWORD dwUseIdentityFlags = m_dwIdentityFlags;

        // Prune unwanted name parts
        if ((dwIncludeFlags & INCLUDE_VERSION) == 0)
        {
            dwUseIdentityFlags &= ~AssemblyIdentity::IDENTITY_FLAG_VERSION;
        }
        if ((dwIncludeFlags & INCLUDE_ARCHITECTURE) == 0)
        {
            dwUseIdentityFlags &= ~AssemblyIdentity::IDENTITY_FLAG_PROCESSOR_ARCHITECTURE;
        }
        if ((dwIncludeFlags & INCLUDE_RETARGETABLE) == 0)
        {
            dwUseIdentityFlags &= ~AssemblyIdentity::IDENTITY_FLAG_RETARGETABLE;
        }
        if ((dwIncludeFlags & INCLUDE_CONTENT_TYPE) == 0)
        {
            dwUseIdentityFlags &= ~AssemblyIdentity::IDENTITY_FLAG_CONTENT_TYPE;
        }

        TextualIdentityParser::ToString(this, dwUseIdentityFlags, displayName);
    }

    SString &AssemblyName::ArchitectureToString(PEKIND kArchitecture)
    {
            switch (kArchitecture)
            {
            case peNone:
                return g_BinderVariables->emptyString;
            case peMSIL:
                return g_BinderVariables->architectureMSIL;
            case peI386:
                return g_BinderVariables->architectureX86;
            case peAMD64:
                return g_BinderVariables->architectureAMD64;
            case peARM:
                return g_BinderVariables->architectureARM;
            case peARM64:
                return g_BinderVariables->architectureARM64;
            default:
                _ASSERTE(0);
                return g_BinderVariables->emptyString;
            }
    }

    SString &AssemblyName::GetNormalizedCulture()
    {
        SString &culture = GetCulture();

        if (culture.IsEmpty())
        {
            culture = g_BinderVariables->cultureNeutral;
        }

        return culture;
    }
};  // namespace BINDER_SPACE


text:
@interface DJImagePreviewCell ()

@end

@implementation DJImagePreviewCell

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.zoomImageView = [[DJZoomImageView alloc] init];
        [self.contentView addSubview:self.zoomImageView];
    }

    return self;
}

- (void)layoutSubviews{
    self.zoomImageView.frame = self.contentView.bounds;
}
@end


text:
<?php

class CM_Mail_Message extends Swift_Message implements CM_ArrayConvertible {

    /** @var string|null */
    private $_text;

    /** @var string|null */
    private $_html;

    /**
     * @return string|null
     */
    public function getHtml() {
        return $this->_html;
    }

    /**
     * @return string|null
     */
    public function getText() {
        return $this->_text;
    }

    /**
     * @return array
     */
    public function getCustomHeaders() {
        $result = [];
        $headers = $this->getHeaders()->getAll();
        foreach ($headers as $header) {
            if (
                $header instanceof Swift_Mime_Headers_UnstructuredHeader &&
                preg_match('/^X-.*/', $header->getFieldName())
            ) {
                $result[$header->getFieldName()][] = $header->getFieldBody();
            }
        }
        return $result;
    }

    /**
     * @param string      $text
     * @param string|null $html
     * @return $this
     */
    public function setBodyWithAlternative($text, $html = null) {
        $text = (string) $text;
        $html = null !== $html ? (string) $html : null;
        if (null === $html) {
            $this->setBody($text, 'text/plain');
        } else {
            $this->setBody($html, 'text/html');
            $this->addPart($text, 'text/plain');
        }
        return $this;
    }

    public function addPart($body, $contentType = null, $charset = null) {
        if ($contentType === 'text/html') {
            $this->_html = (string) $body;
        } elseif ($contentType === 'text/plain') {
            $this->_text = (string) $body;
        }
        return parent::addPart($body, $contentType, $charset);
    }

    public function setBody($body, $contentType = null, $charset = null) {
        if ($contentType === 'text/html') {
            $this->_html = (string) $body;
        } elseif ($contentType === 'text/plain') {
            $this->_text = (string) $body;
        }
        return parent::setBody($body, $contentType, $charset);
    }

    public function toArray() {
        return [
            'subject'       => $this->getSubject(),
            'html'          => $this->getHtml(),
            'text'          => $this->getText(),
            'sender'        => $this->getSender(),
            'from'          => $this->getFrom(),
            'replyTo'       => $this->getReplyTo(),
            'to'            => $this->getTo(),
            'cc'            => $this->getCc(),
            'bcc'           => $this->getBcc(),
            'customHeaders' => $this->getCustomHeaders(),
        ];
    }

    public static function fromArray(array $array) {
        $message = new self($array['subject']);
        if (null !== $array['sender']) {
            $message->setSender($array['sender']);
        }
        if (null !== $array['from']) {
            $message->setFrom($array['from']);
        }
        if (null !== $array['to']) {
            $message->setTo($array['to']);
        }
        if (null !== $array['replyTo']) {
            $message->setReplyTo($array['replyTo']);
        }
        if (null !== $array['cc']) {
            $message->setCc($array['cc']);
        }
        if (null !== $array['bcc']) {
            $message->setBcc($array['bcc']);
        }
        if (null !== $array['text']) {
            $message->setBodyWithAlternative($array['text'], $array['html']);
        }
        foreach ($array['customHeaders'] as $label => $valueList) {
            foreach ($valueList as $value) {
                $message->getHeaders()->addTextHeader($label, $value);
            }
        }
        return $message;
    }

    public static function register() {
        $dep = Swift_DependencyContainer::getInstance();
        if (!$dep->has('message.cm-message')) {
            $dep->register('message.cm-message')->asNewInstanceOf('CM_Mail_Message');
        }
    }
}


text:
package integration

import (
	"fmt"
	"net"
	"os"

	"github.com/miekg/dns"
	"github.com/traefik/traefik/v2/pkg/log"
)

type handler struct{}

// ServeDNS a fake DNS server
// Simplified version of the Challenge Test Server from Boulder
// https://github.com/letsencrypt/boulder/blob/a6597b9f120207eff192c3e4107a7e49972a0250/test/challtestsrv/dnsone.go#L40
func (s *handler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
	logger := log.WithoutContext()

	m := new(dns.Msg)
	m.SetReply(r)
	m.Compress = false

	fakeDNS := os.Getenv("DOCKER_HOST_IP")
	if fakeDNS == "" {
		fakeDNS = "127.0.0.1"
	}

	for _, q := range r.Question {
		logger.Infof("Query -- [%s] %s", q.Name, dns.TypeToString[q.Qtype])

		switch q.Qtype {
		case dns.TypeA:
			record := new(dns.A)
			record.Hdr = dns.RR_Header{
				Name:   q.Name,
				Rrtype: dns.TypeA,
				Class:  dns.ClassINET,
				Ttl:    0,
			}
			record.A = net.ParseIP(fakeDNS)

			m.Answer = append(m.Answer, record)
		case dns.TypeCAA:
			addCAARecord := true

			var value string
			switch q.Name {
			case "bad-caa-reserved.com.":
				value = "sad-hacker-ca.invalid"
			case "good-caa-reserved.com.":
				value = "happy-hacker-ca.invalid"
			case "accounturi.good-caa-reserved.com.":
				uri := os.Getenv("ACCOUNT_URI")
				value = fmt.Sprintf("happy-hacker-ca.invalid; accounturi=%s", uri)
			case "recheck.good-caa-reserved.com.":
				// Allow issuance when we're running in the past
				// (under FAKECLOCK), otherwise deny issuance.
				if os.Getenv("FAKECLOCK") != "" {
					value = "happy-hacker-ca.invalid"
				} else {
					value = "sad-hacker-ca.invalid"
				}
			case "dns-01-only.good-caa-reserved.com.":
				value = "happy-hacker-ca.invalid; validationmethods=dns-01"
			case "http-01-only.good-caa-reserved.com.":
				value = "happy-hacker-ca.invalid; validationmethods=http-01"
			case "dns-01-or-http-01.good-caa-reserved.com.":
				value = "happy-hacker-ca.invalid; validationmethods=dns-01,http-01"
			default:
				addCAARecord = false
			}
			if addCAARecord {
				record := new(dns.CAA)
				record.Hdr = dns.RR_Header{
					Name:   q.Name,
					Rrtype: dns.TypeCAA,
					Class:  dns.ClassINET,
					Ttl:    0,
				}
				record.Tag = "issue"
				record.Value = value
				m.Answer = append(m.Answer, record)
			}
		}
	}

	auth := new(dns.SOA)
	auth.Hdr = dns.RR_Header{Name: "boulder.invalid.", Rrtype: dns.TypeSOA, Class: dns.ClassINET, Ttl: 0}
	auth.Ns = "ns.boulder.invalid."
	auth.Mbox = "master.boulder.invalid."
	auth.Serial = 1
	auth.Refresh = 1
	auth.Retry = 1
	auth.Expire = 1
	auth.Minttl = 1
	m.Ns = append(m.Ns, auth)

	if err := w.WriteMsg(m); err != nil {
		logger.Fatalf("Failed to write message %v", err)
	}
}

func startFakeDNSServer() *dns.Server {
	srv := &dns.Server{
		Addr:    ":5053",
		Net:     "udp",
		Handler: &handler{},
	}

	go func() {
		log.WithoutContext().Infof("Start a fake DNS server.")
		if err := srv.ListenAndServe(); err != nil {
			log.WithoutContext().Fatalf("Failed to set udp listener %v", err)
		}
	}()

	return srv
}


text:
package net.wandroid.answer.view;

public interface IControllButtonListener {
    void onSaveEntry();

    void onSlideBack();

    void onNextSlide();

    void onCancel();

    static final IControllButtonListener NO_LISTENER = new IControllButtonListener() {

        @Override
        public void onSlideBack() {
        }

        @Override
        public void onSaveEntry() {
        }

        @Override
        public void onNextSlide() {
        }

        @Override
        public void onCancel() {
        }
    };
}


text:
namespace oak {
namespace internal {

string16 GetNodeTitleForWindow(aura::Window* window) {
  std::string window_name = window->name();
  if (window_name.empty())
    window_name.append("Unnamed window");
  return ASCIIToUTF16(window_name);
}

void AddChildWindows(aura::Window* parent_window, WindowNode* parent_node) {
  aura::Window::Windows::const_iterator it = parent_window->children().begin();
  for (; it != parent_window->children().end(); ++it) {
    WindowNode* child_node = new WindowNode(GetNodeTitleForWindow(*it), *it);
    parent_node->Add(child_node, parent_node->child_count());
    AddChildWindows(*it, child_node);
  }
}

TreeOfWindows* GenerateModel(aura::Window* root) {
  WindowNode* root_node = new WindowNode(GetNodeTitleForWindow(root), root);
  TreeOfWindows* tree = new TreeOfWindows(root_node);
  AddChildWindows(root, root_node);
  return tree;
}

}  // namespace internal
}  // namespace oak


text:
(function () {
    'use strict';
    angular.module('article')
        .directive('svEditorArticlesTabs', function (userAuth, ArticlesServ, toastr) {

            function processArticles(articles) {
                var filteredList = _.filter(articles, function (article) {
                    return article.isPublic && !article.isBlog;
                });
                var sortedList = _.sortBy(filteredList, 'newsOrder');
                return sortedList;
            }

            return {
                replace: true,
                templateUrl: 'scripts/article/directives/sv-editor-articles-tabs.html',
                scope: {},
                controller: function ($scope) {
                    this.moveToTop = function (article) {
                        article.newsOrder = 1;
                        var rankArts = [];
                        rankArts.push(article);

                        for ( var i = 0; i < $scope.articles.length; i++ ) {
                            var art = $scope.articles[ i ];
                            if ( art.fbkey === article.fbkey ) {
                                continue;
                            }
                            art.newsOrder++;
                            rankArts.push(art);
                        }
                        $scope.articles = processArticles(rankArts);
                        $scope.isRankChanged = true;

                    };
                },
                link: function ($scope, el, attrs) {
                    $scope.user = userAuth.profile;
                    ArticlesServ.all().then(function (articles) {
                        $scope.articles = processArticles(articles);

                    })

                    $scope.isRankChanged = false;
                    $scope.sortableOptions = {
                        update: function (e, ui) {
                            $scope.isRankChanged = true;
                        },
                        axis: 'y'
                    };
                    $scope.saveArticlesRank = function () {
                        ArticlesServ.changeRank($scope.articles).then(function () {
                            $scope.isRankChanged = false;
                            toastr.info('Home Ranking has been changed');
                        })
                    };
                }
            };
        });
})();


text:
package org.anc.lapps.converters.gate;

import org.junit.*;

import java.io.File;

import static org.junit.Assert.*;

/**
 * @author Keith Suderman
 */
@Ignore
public class ConstantsTests
{
	public ConstantsTests()
	{

	}

	@Test
	public void testPaths()
	{
		Configuration K = new Configuration();
		exists(K.GATE_HOME);
		exists(K.PLUGINS_HOME);
		exists(K.SITE_CONFIG);
		exists(K.USER_CONFIG);
	}

	protected void exists(String path)
	{
		File file = new File(path);
		assertTrue("File not found: " + file.getPath(), file.exists());
	}
}


text:
START_ATF_NAMESPACE
    struct StreamVtbl
    {
        int (WINAPIV *QueryCb)(Stream *_this);
        BYTE gap8[8];
        int (WINAPIV *Write)(Stream *_this, int, void *, int);
        int (WINAPIV *Replace)(Stream *_this, void *, int);
        int (WINAPIV *Append)(Stream *_this, void *, int);
        int (WINAPIV *Delete)(Stream *_this);
        int (WINAPIV *Release)(Stream *_this);
        int (WINAPIV *Read2)(Stream *_this, int, void *, int);
        int (WINAPIV *Truncate)(Stream *_this, int);
    };
END_ATF_NAMESPACE


text:
Visualizing statistical values of students enrolled at institutions of higher education in Germany.

done by the some random student at the University of Applied Sciences Karlsruhe for the course "Advanced Visualization" :D

# About:

Visualizing statistical values of students enrolled at institutions of higher education in Germany.
Uses javascript files created in a project I worked on last semester (-> GeoViz repository)

# Authors:
Random Student

# Data and data sources

All datasets used in this project are stored inside the folder "data\" and were derived from the following sources:

-	GADM database of Global Administrative Areas - Counties in Germany - http://www.gadm.org/
-	statistical values provided by the Federal Statistical Office (Statistisches Bundesamt) - https://www.destatis.de/DE/Startseite.html

# External libraries (stored in folder "js"):

-	jQueryUI
-	BootStrap
-	d3.js

# License:
Please refer to the license file


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using System;
using System.Runtime.InteropServices;
using Microsoft.Azure.Management.DataFactory.Models;

namespace Microsoft.Azure.Commands.DataFactoryV2.Models
{
    public class PSIntegrationRuntime
    {
        internal readonly IntegrationRuntimeResource IntegrationRuntime;

        public PSIntegrationRuntime(IntegrationRuntimeResource integrationRuntime, string resourceGroupName, string factoryName)
        {
            if (integrationRuntime == null)
            {
                throw new ArgumentNullException(nameof(integrationRuntime));
            }

            IntegrationRuntime = integrationRuntime;
            ResourceGroupName = resourceGroupName;
            DataFactoryName = factoryName;
        }

        public string Id => IntegrationRuntime.Id;

        public string Type
        {
            get
            {
                if (IntegrationRuntime.Properties is ManagedIntegrationRuntime)
                {
                    return  Constants.IntegrationRuntimeTypeManaged;
                }
                else if (IntegrationRuntime.Properties is SelfHostedIntegrationRuntime)
                {
                    return Constants.IntegrationRuntimeSelfhosted;
                }

                return string.Empty;
            }
        }

        public string ResourceGroupName { get; private set; }

        public string DataFactoryName { get; private set; }

        public string Name => IntegrationRuntime.Name;

        public string Description
        {
            get { return IntegrationRuntime.Properties.Description; }
            set { IntegrationRuntime.Properties.Description = value; }
        }
    }
}


text:
typedef void (*CursorNextFunc)(void*, Document**);
typedef int64_t (*CompareFunc)(Document*, Document*);
typedef Document* (*MergeFunc)(Document*, Document*);

typedef uint64_t CursorKey;

typedef enum {
    NONE = 0,
    INNER = 1,
    LEFT = 3, // 2 | INNER
    RIGHT = 5, // 4 | INNER
    OUTER = 7, // LEFT | RIGHT | INNER
} MergeType;

typedef struct {
    void* memo;
    Document* head;
    CursorNextFunc next;
} Cursor;

Cursor* cursor_create(CursorNextFunc next, void* memo);
Cursor* cursor_from_array(Document** array, size_t n);
void cursor_delete(Cursor* cursor);
bool cursor_done(Cursor* cursor);
Cursor* cursor_join(Cursor* ac, Cursor* bc, MergeType type, CompareFunc cmp, MergeFunc merge);
Cursor* cursor_merge(Cursor* ac, Cursor* bc, MergeType type);
size_t cursor_to_array(Cursor* cursor, Document** array, size_t n);

inline Document* cursor_peek(Cursor* cursor) {
    return cursor->head;
}

inline Document* cursor_next(Cursor* cursor) {
    cursor->next(cursor->memo, &cursor->head);
    return cursor->head;
}

#endif


text:
var path = require('path');
import h from 'spec/spec_helper';
import { t }  from 'azk';
import { Cli, Command } from 'azk/cli/cli';
import {
  InvalidOptionError,
  InvalidValueError,
  RequiredOptionError
} from 'azk/utils/errors';

describe('Azk cli module', function() {
  var outputs = [];
  var UI = h.mockUI(beforeEach, outputs);

  var cmds = path.join(__dirname, '../fixtures/cmds');
  var cli  = new Cli('azk-test', UI, cmds);

  it("should load and connect commands", function() {
    h.expect(cli).have.deep.property('commands.test_options')
      .and.instanceOf(Command);
  });

  it("should run a command", function() {
    cli.run(['test_options', '-n', '20']);
    h.expect(outputs).to.eql([{ number: 20, __leftover: []}]);
  });

  it("should raise a invalid command", function() {
    var func = () => cli.run(['invalid_cmd']);
    h.expect(func).to.throw(InvalidValueError, /invalid_cmd.*command/);
  });

  it("should show a usage subcommand", function() {
    cli.showUsage("test_options");
    h.expect(outputs).to.deep.property("[00]",
      t("commands.help.usage", 'azk-test test_options [options]')
    );
  });
});


text:
Go handler to create external network extensions for Docker.

## Usage

This library is designed to be integrated in your program.

1. Implement the `network.Driver` interface.
2. Initialize a `network.Handler` with your implementation.
3. Call either `ServeTCP`, `ServeUnix` or `ServeWindows` from the `network.Handler`.
4. On Windows, docker daemon data dir must be provided for ServeTCP and ServeWindows functions.
On Unix, this parameter is ignored.

### Example using TCP sockets:

```go
  import "github.com/docker/go-plugins-helpers/network"

  d := MyNetworkDriver{}
  h := network.NewHandler(d)
  h.ServeTCP("test_network", ":8080", "")
  // on windows:
  h.ServeTCP("test_network", ":8080", WindowsDefaultDaemonRootDir())
```

### Example using Unix sockets:

```go
  import "github.com/docker/go-plugins-helpers/network"

  d := MyNetworkDriver{}
  h := network.NewHandler(d)
  h.ServeUnix("test_network", 0)
```

### Example using Windows named pipes:

```go
import "github.com/docker/go-plugins-helpers/network"
import "github.com/docker/go-plugins-helpers/sdk"

d := MyNetworkDriver{}
h := network.NewHandler(d)

config := sdk.WindowsPipeConfig{
  // open, read, write permissions for everyone
  // (uses Windows Security Descriptor Definition Language)
  SecurityDescriptor: AllowServiceSystemAdmin,
  InBufferSize:       4096,
  OutBufferSize:      4096,
}

h.ServeWindows("//./pipe/testpipe", "test_network", WindowsDefaultDaemonRootDir(), &config)
```

## Full example plugins

- [docker-ovs-plugin](https://github.com/gopher-net/docker-ovs-plugin) - An Open vSwitch Networking Plugin


text:
{% extends 'base.html' %}

{% load staticfiles %}

{% block title %}{{ category_name }}{% endblock %}

{% block body_block %}

{{ category_name }}

    {% if category %}
        {% if pages %}

                {% for page in pages %}

{{ page.title }}

                {% endfor %}

        {% else %}
                No pages currently in category.
                {% endif %}

        {% if user.is_authenticated %}
                {% url 'rango:add_page' category_name_slug as the_url%}
                Add a New Page to {{category_name}}
                {#Add a New Page to {{category_name}}#}
                {% endif %}
        {% else %}
                 The specified category {{ category_name }} does not exist!
    {% endif %}

{% endblock %}