text:
#import <Foundation/Foundation.h>
#import "HZShowOptions.h"

@class HZShowOptions;

@protocol HZAdsDelegate;

/** HZInterstitialAd is responsible for fetching and showing interstitial ads. All methods on this class must be called from the main queue. */
@interface HZInterstitialAd : NSObject

#pragma mark - Showing Ads

/** Shows an interstitial ad. */
+ (void) show;

/**
 *  Shows an interstitial ad for a given tag, if available.
 *
 *  @param tag An identifier for the location of the ad which you can use to disable the ad from your dashboard.
 */
+ (void) showForTag:(NSString *)tag;

/**
 *  Shows an interstitial ad for a given tag, if available.
 *
 *  @param tag An identifier for the location/context of the ad which you can use to disable the ad from your dashboard.
 *  @param completion A block called when the ad is shown or failed to show. result contains whether
 *         or not the fetch was successful, and if not, error contains the reason why.
 */
+ (void) showForTag:(NSString *)tag completion:(void (^)(BOOL result, NSError *error))completion;

/** Shows an interstitial ad with the given options.
 *
 * @param options HZShowOptions object containing properties for configuring how the ad is shown.
 */
+ (void) showWithOptions: (HZShowOptions *) options;

#pragma mark - Callbacks

/** Sets the delegate to receive the messages listed in the `HZAdsDelegate` protocol.

 @param delegate The object to receive the callbacks.
 */
+ (void) setDelegate: (id<HZAdsDelegate>) delegate;

/** Fetches a new ad from Heyzap.  */
+ (void) fetch;

/**
 *  Fetches an interstitial ad with an optional completion handler
 *
 *  @param completion A block called when the ad is fetched or failed to fetch. result contains whether or not the fetch was successful, and if not, error contains the reason why.
 */
+ (void) fetchWithCompletion:(void (^)(BOOL result, NSError *error))completion;

/**
 *  Fetches an interstitial ad for the given tag.
 *
 *  @param tag An identifier for the location of the ad which you can use to disable the ad from your dashboard.
 */
+ (void) fetchForTag:(NSString *) tag;

/**
 *  Fetches an interstitial ad for the given tag with an optional completion handler.
 *
 *  @param tag        An identifier for the location of the ad which you can use to disable the ad from your dashboard.
 *  @param completion A block called when the ad is fetched or fails to fetch. `result` states whether the fetch was sucessful; the error object describes the issue, if there was one.
 */
+ (void) fetchForTag:(NSString *)tag withCompletion:(void (^)(BOOL result, NSError *error))completion;

/**
 *  Fetches an interstitial ad for each of the given tags.
 *
 *  @param tags An NSArray of NSString* identifiers for the location of ads which you can use to disable ads from your dashboard.
 */
+ (void) fetchForTags:(NSArray *)tags;

/**
 *  Fetches an interstitial ad for each of the given tags with an optional completion handler.
 *
 *  @param tag        An NSArray of NSString* identifiers for the location of ads which you can use to disable ads from your dashboard.
 *  @param completion A block called when an ad for each tag is fetched or fails to fetch. `result` states whether the fetch was sucessful; the error object describes the issue, if there was one.
 */
+ (void) fetchForTags:(NSArray *)tags withCompletion:(void (^)(BOOL result, NSError *error))completion;

/** Whether or not an interstitial ad is available to show. */
+ (BOOL) isAvailable;

/**
 *  Whether or not an ad is available to show for the given tag.
 *
 *  @param tag An identifier for the location of the ad which you can use to disable the ad from your dashboard.
 *
 *  @return If an interstitial ad is available to show.
 */
+ (BOOL) isAvailableForTag:(NSString *)tag;

#pragma mark - Private methods

+ (void) setCreativeID:(int)creativeID;
+ (void)forceTestCreative:(BOOL)forceTestCreative;
+ (void)setCreativeType:(NSString *)creativeType;

@end


text:
class Brakeman::Report::Hash < Brakeman::Report::Base
  def generate_report
    report = { :errors => tracker.errors,
               :controllers => tracker.controllers,
               :models => tracker.models,
               :templates => tracker.templates
              }

    [:generic_warnings, :controller_warnings, :model_warnings, :template_warnings].each do |meth|
      report[meth] = self.send(meth)
      report[meth].each do |w|
        w.message = w.format_message
        w.context = context_for(@app_tree, w).join("\n")
      end
    end

    report[:config] = tracker.config
    report[:checks_run] = tracker.checks.checks_run

    report
  end
end

redpajama_set_name: RedPajamaGithub


text:
/**
 * @file
 *   This file implements notifications triggered directly by the nrf 802.15.4 radio driver.
 *
 */

#include "nrf_drv_radio802154_notification.h"

#include <stdbool.h>
#include <stdint.h>

#include "nrf_drv_radio802154.h"

void nrf_drv_radio802154_notification_init(void)
{
    // Intentionally empty
}

void nrf_drv_radio802154_notify_received(uint8_t * p_data, int8_t power, int8_t lqi)
{
    nrf_drv_radio802154_received(p_data, power, lqi);
}

void nrf_drv_radio802154_notify_transmitted(uint8_t * p_ack, int8_t power, int8_t lqi)
{
    nrf_drv_radio802154_transmitted(p_ack, power, lqi);
}

void nrf_drv_radio802154_notify_busy_channel(void)
{
    nrf_drv_radio802154_busy_channel();
}

void nrf_drv_radio802154_notify_energy_detected(int8_t result)
{
    nrf_drv_radio802154_energy_detected(result);
}


text:
import os
import subprocess
import json
import tempfile

import pytest
import six
from conda_shell import main
from conda_shell import conda_cli

@pytest.fixture
def remove_shell_envs():
    """Return a dict of shell environment variables to use with subprocess."""
    # Use an alternate environment prefix to distinguish between the
    # environments only used for testing
    base_env = os.environ.copy()
    base_env['CONDA_SHELL_ENV_PREFIX'] = '__testme_shell_'
    main.DEFAULT_ENV_PREFIX = '__testme_shell_'
    shell_envs_json = subprocess.check_output('conda info --envs --json',
                                              universal_newlines=True,
                                              shell=True)
    shell_envs = filter(lambda dpath: main.is_shell_env(dpath),
                        json.loads(shell_envs_json)['envs'])
    for env_dpath in shell_envs:
        subprocess.check_call('conda env remove -y -p '+env_dpath,
                              universal_newlines=True,
                              shell=True)
    return base_env

@pytest.fixture
def tmp_dir():
    """Create a temporary directory that can be populated by test code.
    Return the tempfile.TemporaryDirectory directory object.
    Directory is automatically removed after the test finishes.
    """
    if six.PY2:
        # Python 2.7 has no tempfile.TemporaryDirectory
        import shutil
        import mock
        tmpdir_dpath = tempfile.mkdtemp()
        tmpdir = mock.Mock(cleanup=lambda: shutil.rmtree(tmpdir_dpath))
        tmpdir.name = tmpdir_dpath # "name" attr is a special case for Mock
    else:
        tmpdir = tempfile.TemporaryDirectory()
    yield tmpdir
    tmpdir.cleanup()

@pytest.fixture
def cli():
    """Return an instance of conda_shell.conda_cli.CondaShellCLI"""
    # Use an alternate environment prefix to distinguish between the
    # environments only used for testing
    main.DEFAULT_ENV_PREFIX = '__testme_shell_'
    return conda_cli.CondaShellCLI()


text:
layout: page
title: Emerald Growth Solutions Dinner
date: 2016-05-24
author: Patricia Calderon
tags: weekly links, java
status: published
summary: Quisque odio quam, varius tempus volutpat.
banner: images/banner/office-01.jpg
booking:
  startDate: 06/11/2016
  endDate: 06/15/2016
  ctyhocn: MIAWEHX
  groupCode: EGSD
published: true
---
Suspendisse tortor justo, interdum consectetur pulvinar in, iaculis ac nisl. Nunc id purus quis tellus tristique ultricies. Fusce eget turpis rhoncus, sodales mauris vel, bibendum tortor. Suspendisse ac semper diam, vel maximus sem. Cras id varius quam. Morbi ac pretium libero. Sed sollicitudin, neque ut dapibus dictum, dui mi imperdiet elit, et efficitur urna nibh id risus. Suspendisse fringilla quis leo vitae fermentum. Aliquam eleifend at diam vel finibus.
Pellentesque ac diam enim. Donec eleifend congue massa vel dapibus. Ut dolor ligula, commodo ac sem fermentum, eleifend eleifend nulla. Suspendisse ante erat, elementum et euismod non, condimentum et lacus. Aliquam erat volutpat. Quisque vitae placerat eros. Suspendisse potenti. Aliquam interdum quis sem sit amet ultricies. Fusce pharetra purus eu mauris dictum egestas cursus vitae metus. Mauris malesuada ipsum id eros consequat, tristique commodo sapien aliquam.

* Nam varius dui vel quam iaculis lobortis.

Cras laoreet sodales augue a pretium. Nullam cursus ut libero sed aliquet. In sit amet facilisis enim. Fusce vel mi nibh. Duis faucibus venenatis ipsum vitae malesuada. Vestibulum hendrerit nisi non eleifend sodales. Aenean ipsum ex, eleifend in pharetra quis, hendrerit sit amet ligula. Donec ac ante sed tortor efficitur placerat. Mauris ut enim ut metus rhoncus commodo. Nunc sagittis est eu enim efficitur vehicula. In consequat ligula nec mi vehicula, sit amet suscipit ipsum sodales. Mauris dignissim vehicula risus non auctor. Lorem ipsum dolor sit amet, consectetur adipiscing elit.


text:
<!-- RATING: MEDIUM -->
<!-- NAME: CAESAR UNCHAINED MEDIUM -->
##Caesar Unchained

A Caesar Cipher is a subset of Rot-X ciphers, where every character is replaced with 3 characters up in the alphabet, wrapping around if necessary.
For example, A would be replace with D, B would be replaced with E, Y would be replaced with B, and Z would be replaced with C.
Simple enough. So let's make things a little more complicated.
We assign each letter in the alphabet a number as follows:

	A -> 1
	B -> 2
	.
	.
	.
	Y -> 25
	Z -> 26

We define a Chained Caesar Cipher as follows:
For the first character to be encrypted, we use a normal Caesar encryption, replacing the character with 3 characters up.
For the second character to be encrypted, we replace the character with X characters up, where X is the number assigned to the character resulting from the first encryption.
For each successive character, we replace it with the letter of the alphabet X characters up, where X is the value for the result of the previous encryption.

Example: We encrypt the word TEST.

	Step 1:  T -> W  (First character, so we use a normal Caesar encryption. W is 3 characters up from T)
	Step 2:  E -> B  (W, the result of step 1, has a value of 23. B is 23 characters after E)
	Step 3:  S -> U  (B, the result of step 2, has a value of 2. U is 2 characters up from S)
	Step 4:  T -> O  (U, the result of step 3, has a value of 21. O is 21 characters up from T)

##INPUT
Each file will contain 1 or more input lines containing a string of uppercase letters, spaces, and punctuation representing a ciphertext generated by the Chained Caesar Cipher algorithm.
ONLY letters are affected by the encryption, you should skip punctuation and spaces and print them out as is.

	A -> 1, Z-> 26

Assume that the string starts in column 1 and will not exceed column 40,

##The Output
Print out the decrypted message

## Sample Input 1

	WRNKIHHIKNR
	#

## Sample Output 1

	TUVWXYZABCD

## Sample Input 2

	WENG PI J DIBV.
	#

## Sample Output 2

	THIS IS A TEST.


text:
package org.apache.catalina;

/**
 * An Engine is a Container that represents the entire Catalina servlet
 * engine.  It is useful in the following types of scenarios:
 *

 *
You wish to use Interceptors that see every single request processed
 *     by the entire engine.
 *
You wish to run Catalina in with a standalone HTTP connector, but still
 *     want support for multiple virtual hosts.
 *

 * In general, you would not use an Engine when deploying Catalina connected
 * to a web server (such as Apache), because the Connector will have
 * utilized the web server's facilities to determine which Context (or
 * perhaps even which Wrapper) should be utilized to process this request.
 *

 * The child containers attached to an Engine are generally implementations
 * of Host (representing a virtual host) or Context (representing individual
 * an individual servlet context), depending upon the Engine implementation.
 *

 * If used, an Engine is always the top level Container in a Catalina
 * hierarchy. Therefore, the implementation's setParent() method
 * should throw IllegalArgumentException.
 *
 * @author Craig R. McClanahan
 * @version $Revision: 515 $ $Date: 2008-03-17 22:02:23 +0100 (Mon, 17 Mar 2008) $
 */

public interface Engine extends Container {

    // ------------------------------------------------------------- Properties

    /**
     * Return the default hostname for this Engine.
     */
    public String getDefaultHost();

    /**
     * Set the default hostname for this Engine.
     *
     * @param defaultHost The new default host
     */
    public void setDefaultHost(String defaultHost);

    /**
     * Retrieve the JvmRouteId for this engine.
     */
    public String getJvmRoute();

    /**
     * Set the JvmRouteId for this engine.
     *
     * @param jvmRouteId the (new) JVM Route ID. Each Engine within a cluster
     *        must have a unique JVM Route ID.
     */
    public void setJvmRoute(String jvmRouteId);

    /**
     * Return the Service with which we are associated (if any).
     */
    public Service getService();

    /**
     * Set the Service with which we are associated (if any).
     *
     * @param service The service that owns this Engine
     */
    public void setService(Service service);

}


text:
<?php
function exitWithHttpStatus($errorCode, $message) {
  $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
  header($protocol . ' ' . $errorCode . ' ' . $message);
  exit($errorCode);
}
?>


text:
function chrpar = partition_genome(betahat)
% USAGE: get the starting and ending positions of each chromosome
% INPUT:
%	betahat: single-SNP effect estimates, 22 by 1 cell
% OUTPUT:
%	chrpar: starting and ending positions, 22 by 2 array

  if length(betahat) ~= 1
    % get the length of each chromosome
    chr_length = cellfun(@length, betahat);

    % get the ending positions of each chromosome
    chr_end = cumsum(chr_length);

    % get the starting positions of each chromosome
    chr_start = [1; chr_end(1:end-1)+1];

    % combine results
    chrpar = [chr_start chr_end];

  else
    chrpar = [1 length(cell2mat(betahat))];
  end

end


text:
<?php

namespace Quaver\Controller;
use Quaver\Model\Lang;

$language = new Lang;
$langCurrent = $language->getFromSlug($this->url_var[1]);

if ($langCurrent) {
    $language->setCookie();
    if (!empty($_SERVER['HTTP_REFERER'])){
        header("Location: " . $_SERVER['HTTP_REFERER']);
        exit;
    } else {
    	$newLang = new url;
        header("Location: " . $newLang->getFromId(1)->url);
        exit;
    }
} else {
    header("Location: " . $this->getUrlFromId(2) . "?ref=" . $this->getUrl());
    exit;
}

?>


text:
module Charger

  class LineItem::OnOff < LineItem
    attribute :enabled, Boolean

    # @return [Float]
    def total
      if enabled
        component.total_for(1)
      else
        0
      end
    end

    # @return [Boolean]
    def allocated?
      enabled
    end
  end

end


text:
<?php
namespace Zodream\Module\Gzo\Service;

use Zodream\Infrastructure\Http\Request;
use Zodream\Service\Controller\ModuleController as BaseController;

abstract class Controller extends BaseController {
    protected function getActionArguments($action, $vars = array()) {
        if (!Request::isCli()) {
            return parent::getActionArguments($action, $vars);
        }
        $args = Request::argv('arguments');
        if (empty($args)) {
            return parent::getActionArguments($action, Request::argv('options'));
        }
        array_shift($args);
        return $args;
    }
}


text:
<?php

// This file was auto-generated from sdk-root/src/data/mediastore-data/2017-09-01/paginators-1.json
return ['pagination' => []];


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Arabis pendulocarpa A. Nelson

### Remarks
null


text:
/*!
	@file
	@author		George Evmenov
	@date		07/2010
*/
#include "Precompiled.h"
#include "DemoKeeper.h"
#include "Base/Main.h"

namespace demo
{

	const int PointsCount = 4;
	int bezierQuality = 16;
	MyGUI::Widget* point[PointsCount];

	DemoKeeper::DemoKeeper() :
		mClient(nullptr),
		mPolygonalSkin(nullptr),
		mQualityText(nullptr)
	{
	}

	void DemoKeeper::setupResources()
	{
		base::BaseManager::setupResources();
		addResourceLocation(getRootMedia() + "/Common/Demos");
		addResourceLocation(getRootMedia() + "/Common/Tools");
		addResourceLocation(getRootMedia() + "/UnitTests/UnitTest_Spline");
	}

	void DemoKeeper::createScene()
	{
		MyGUI::ResourceManager::getInstance().load("FrameworkSkin.xml");
		MyGUI::ResourceManager::getInstance().load("SelectionSkins.xml");

		const MyGUI::VectorWidgetPtr& root = MyGUI::LayoutManager::getInstance().loadLayout("HelpPanel.layout");
		root.at(0)->findWidget("Text")->castType<MyGUI::TextBox>()->setCaption("PolygonalSkin usage. Drag white rectangles to move points for bezier curve.");

		MyGUI::VectorWidgetPtr widgets = MyGUI::LayoutManager::getInstance().loadLayout("SplineWindow.layout");
		mQualityText = widgets.at(0)->findWidget("SplineText")->castType<MyGUI::TextBox>();
		MyGUI::ScrollBar* qualityScroll = widgets.at(0)->findWidget("SplineQuality")->castType<MyGUI::ScrollBar>();
		qualityScroll->eventScrollChangePosition += MyGUI::newDelegate(this, &DemoKeeper::notifyChangeQuality);
		mClient = widgets.at(0)->findWidget("SplineClient");

		// create widget with skin that contain specific sub skin - PolygonalSkin
		MyGUI::Widget* widget = mClient->createWidget<MyGUI::Widget>("PolygonalSkin", MyGUI::IntCoord(MyGUI::IntPoint(), mClient->getSize()), MyGUI::Align::Stretch);
		widget->setColour(MyGUI::Colour::Red);
		// get main subskin
		MyGUI::ISubWidget* main = widget->getSubWidgetMain();
		mPolygonalSkin = main->castType<MyGUI::PolygonalSkin>();

		// set PolygonalSkin properties and points
		mPolygonalSkin->setWidth(8.0f);

		for (int i = 0; i < PointsCount; ++i)
		{
			point[i] = mClient->createWidget<MyGUI::Button>("Button", MyGUI::IntCoord(10 + (i + i % 2 * 3) * 40, 10 + (i + i / 2 * 3) * 40, 16, 16), MyGUI::Align::Default);
			point[i]->eventMouseDrag += newDelegate(this, &DemoKeeper::notifyPointMove);
			point[i]->eventMouseButtonPressed += newDelegate(this, &DemoKeeper::notifyPointPressed);
		}

		notifyChangeQuality(qualityScroll, 12);
		updateSpline();
	}

	void DemoKeeper::makeBezier(const std::vector<MyGUI::FloatPoint>& _points, size_t _pointsNumber)
	{
		mLinePoints.clear();
		for (size_t i = 0; i < _pointsNumber; ++i)
		{
			float t = float(i) / (_pointsNumber - 1);
			float left = _points[0].left * pow(1 - t, 3) + 3 * _points[1].left * pow(1 - t, 2) * t + 3 * _points[2].left * (1 - t) * t * t + t * t * t * _points[3].left;
			float top = _points[0].top * pow(1 - t, 3) + 3 * _points[1].top * pow(1 - t, 2) * t + 3 * _points[2].top * (1 - t) * t * t + t * t * t * _points[3].top;
			mLinePoints.push_back(MyGUI::FloatPoint(left, top));
		}
	}

	void DemoKeeper::updateSpline()
	{
		std::vector<MyGUI::FloatPoint> points;
		for (int i = 0; i < PointsCount; ++i)
		{
			points.push_back(MyGUI::FloatPoint(point[i]->getLeft() + 8.0f, point[i]->getTop() + 8.0f));
		}
		makeBezier(points, bezierQuality);
		mPolygonalSkin->setPoints(mLinePoints);
	}

	void DemoKeeper::notifyPointMove(MyGUI::Widget* _sender, int _left, int _top, MyGUI::MouseButton _id)
	{
		_sender->setPosition(MyGUI::IntPoint(_left, _top) - _sender->getCroppedParent()->getAbsolutePosition() - mOffset);
		updateSpline();
	}

	void DemoKeeper::notifyPointPressed(MyGUI::Widget* _sender, int _left, int _top, MyGUI::MouseButton _id)
	{
		mOffset = MyGUI::IntPoint(_left, _top) - _sender->getAbsolutePosition();
	}

	void DemoKeeper::notifyChangeQuality(MyGUI::ScrollBar* _sender, size_t _position)
	{
		bezierQuality = _position + 4;
		mQualityText->setCaption(MyGUI::utility::toString("Quality: ", bezierQuality));
		updateSpline();
	}

} // namespace demo

MYGUI_APP(demo::DemoKeeper)


text:
package gov.samhsa.consent2share.domain.audit;

import gov.samhsa.consent2share.common.SpringContext;
import gov.samhsa.consent2share.common.UserContext;

import java.io.Serializable;

import org.hibernate.envers.EntityTrackingRevisionListener;
import org.hibernate.envers.RevisionListener;
import org.hibernate.envers.RevisionType;

/**
 * The Class RevisionListenerImpl.
 */
public class RevisionListenerImpl implements RevisionListener,
		EntityTrackingRevisionListener {

	/** The modified entity type entity repository. */
	ModifiedEntityTypeEntityRepository modifiedEntityTypeEntityRepository;

	/**
	 * Instantiates a new revision listener impl.
	 */
	public RevisionListenerImpl() {
		super();
	}

	/**
	 * Instantiates a new revision listener impl.
	 *
	 * @param modifiedEntityTypeEntityRepository
	 *            the modified entity type entity repository
	 */
	public RevisionListenerImpl(
			ModifiedEntityTypeEntityRepository modifiedEntityTypeEntityRepository) {
		super();
		this.modifiedEntityTypeEntityRepository = modifiedEntityTypeEntityRepository;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.hibernate.envers.RevisionListener#newRevision(java.lang.Object)
	 */
	@Override
	public void newRevision(Object revisionEntity) {
		if (SpringContext.getApplicationContext() != null) {
			UserContext userContext = SpringContext.getApplicationContext()
					.getBean(UserContext.class);
			if (userContext.getCurrentUser() != null) {
				String username = userContext.getCurrentUser().getUsername();
				((RevisionInfoEntity) revisionEntity).setUsername(username);
			}
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.hibernate.envers.EntityTrackingRevisionListener#entityChanged(java
	 * .lang.Class, java.lang.String, java.io.Serializable,
	 * org.hibernate.envers.RevisionType, java.lang.Object)
	 */
	@Override
	public void entityChanged(@SuppressWarnings("rawtypes") Class entityClass,
			String entityName, Serializable entityId,
			RevisionType revisionType, Object revisionEntity) {
		String type = entityClass.getName();
		Byte rt = revisionType.getRepresentation();
		((RevisionInfoEntity) revisionEntity).addModifiedEntityType(type, rt,
				(RevisionInfoEntity) revisionEntity);

	}

}


text:
package com.rtg.vcf;

import java.util.ArrayList;

import com.rtg.AbstractTest;
import com.rtg.util.StringUtils;
import com.rtg.util.diagnostic.Diagnostic;
import com.rtg.vcf.header.FormatField;
import com.rtg.vcf.header.InfoField;
import com.rtg.vcf.header.MetaType;
import com.rtg.vcf.header.VcfHeader;
import com.rtg.vcf.header.VcfHeaderMerge;
import com.rtg.vcf.header.VcfNumber;

/**
 * Tests the corresponding class.
 */
public class VcfRecordMergerTest extends AbstractTest {

  private static final String VCF_RECORD_FORMAT = "%1$s\t%2$d\t.\t%3$s\t%4$s\t.\tPASS\t.\tGT:E1:E2\t%5$d/%6$d:.:.";
  private static final String VCF_RECORD_FORMAT_MISSING = "%1$s\t%2$d\t.\t%3$s\t.\t.\tPASS\t.\tGT:E1:E2\t.";

  static VcfRecord createRecord(String chrom, int pos, String ref, int gt1, int gt2, String... alts) {
    final String altsStr = StringUtils.join(",", alts, false);
    return VcfReaderTest.vcfLineToRecord(String.format(VCF_RECORD_FORMAT, chrom, pos, ref, altsStr, gt1, gt2));
  }

  static VcfRecord createRecord(String chrom, int pos, String ref) {
    return VcfReaderTest.vcfLineToRecord(String.format(VCF_RECORD_FORMAT_MISSING, chrom, pos, ref));
  }

  public void testAllelesChanged() {
    VcfRecord r1 = createRecord("chr1", 50, "A", 0, 1, "C");
    VcfRecord r2 = createRecord("chr1", 50, "A", 1, 2, "C", "G");
    VcfRecord r3 = createRecord("chr1", 50, "A", 1, 2, "G", "C");

    VcfRecordMerger.AlleleMap map = new VcfRecordMerger.AlleleMap("A", new ArrayList<>(), new VcfRecord[]{r2, r2});
    assertFalse(map.altsChanged());

    map = new VcfRecordMerger.AlleleMap("A", new ArrayList<>(), new VcfRecord[]{r2, r1});
    assertTrue(map.altsChanged());

    map = new VcfRecordMerger.AlleleMap("A", new ArrayList<>(), new VcfRecord[]{r1, r2});
    assertTrue(map.altsChanged());

    map = new VcfRecordMerger.AlleleMap("A", new ArrayList<>(), new VcfRecord[]{r1, r3});
    assertTrue(map.altsChanged());
  }

  public void testMerge() {
    final VcfHeader h1 = new VcfHeader();
    h1.addSampleName("sample1");
    final VcfHeader h2 = new VcfHeader();
    h2.addSampleName("sample2");
    final VcfHeader mh = new VcfHeader();
    mh.addSampleName("sample1");
    mh.addSampleName("sample2");
    VcfRecord r1 = createRecord("chr1", 50, "A", 0, 1, "C");
    VcfRecord r2 = createRecord("chr1", 50, "A", 0, 1, "G");
    assertEquals(2, new VcfRecordMerger().setHeader(mh).setAllowMerging(false).mergeRecords(new VcfRecord[]{r1, r2}, new VcfHeader[]{h1, h2}).length);
    final VcfRecordMerger merger = new VcfRecordMerger().setHeader(mh);
    VcfRecord[] mergedArr = merger.mergeRecords(new VcfRecord[]{r1, r2}, new VcfHeader[]{h1, h2});
    assertEquals(1, mergedArr.length);
    VcfRecord merged = mergedArr[0];
    assertEquals("chr1", merged.getSequenceName());
    assertEquals("A", merged.getRefCall());
    assertEquals(50, merged.getOneBasedStart());
    assertEquals(2, merged.getAltCalls().size());
    assertEquals("C", merged.getAltCalls().get(0));
    assertEquals("G", merged.getAltCalls().get(1));
    assertEquals(2, merged.getFormat(VcfUtils.FORMAT_GENOTYPE).size());
    assertEquals("0/1", merged.getFormat(VcfUtils.FORMAT_GENOTYPE).get(0));
    assertEquals("0/2", merged.getFormat(VcfUtils.FORMAT_GENOTYPE).get(1));

    r1 = createRecord("chr1", 50, "A", 0, 1, "C");
    r2 = createRecord("chr1", 50, "A", 1, 2, "G", "C");
    mergedArr = merger.mergeRecords(new VcfRecord[]{r1, r2}, new VcfHeader[]{h1, h2});
    assertEquals(1, mergedArr.length);
    merged = mergedArr[0];
    assertEquals("chr1", merged.getSequenceName());
    assertEquals("A", merged.getRefCall());
    assertEquals(50, merged.getOneBasedStart());
    assertEquals(2, merged.getAltCalls().size());
    assertEquals("C", merged.getAltCalls().get(0));
    assertEquals("G", merged.getAltCalls().get(1));
    assertEquals(2, merged.getFormat(VcfUtils.FORMAT_GENOTYPE).size());
    assertEquals("0/1", merged.getFormat(VcfUtils.FORMAT_GENOTYPE).get(0));
    assertEquals("2/1", merged.getFormat(VcfUtils.FORMAT_GENOTYPE).get(1));

    // Outputs separate records due to different REF
    r1 = createRecord("chr1", 50, "A", 0, 1, "C");
    r2 = createRecord("chr1", 50, "AC", 1, 2, "GG", "CG");
    mergedArr = merger.mergeRecords(new VcfRecord[]{r1, r2}, new VcfHeader[]{h1, h2});
    assertEquals(2, mergedArr.length);
    VcfRecordTest.checkRecord(mergedArr[0], r1, new String[]{"0/1", "."});
    VcfRecordTest.checkRecord(mergedArr[1], r2, new String[]{".", "1/2"});

    // Outputs separate records due to different REF
    r1 = createRecord("chr1", 50, "A", 0, 1, "C");
    r2 = createRecord("chr1", 50, "AC", 1, 1, "AC"); //this tests the preservation of a buggy case
    mergedArr = merger.mergeRecords(new VcfRecord[]{r1, r2}, new VcfHeader[]{h1, h2});
    assertEquals(2, mergedArr.length);
    VcfRecordTest.checkRecord(mergedArr[0], r1, new String[]{"0/1", "."});
    VcfRecordTest.checkRecord(mergedArr[1], r2, new String[0], new String[]{".", "1/1"});

    //test blank filling
    mh.addSampleName("sample3");
    r1 = createRecord("chr1", 50, "A", 0, 1, "C");
    r2 = createRecord("chr1", 50, "AC", 1, 1, "AG");
    mergedArr = merger.mergeRecords(new VcfRecord[]{r1, r2}, new VcfHeader[]{h1, h2});
    assertEquals(2, mergedArr.length);
    VcfRecordTest.checkRecord(mergedArr[0], r1, new String[]{"0/1", "."});
    VcfRecordTest.checkRecord(mergedArr[1], r2, new String[0], new String[]{".", "1/1"});

    //test reading of GT containing missing values
    r1 = createRecord("chr1", 50, "A", 0, 1, "C");
    r2 = createRecord("chr1", 50, "A");
    mergedArr = merger.mergeRecords(new VcfRecord[]{r1, r2}, new VcfHeader[]{h1, h2});
    assertEquals(1, mergedArr.length);
    merged = mergedArr[0];
    assertEquals("chr1", merged.getSequenceName());
    assertEquals("A", merged.getRefCall());
    assertEquals(50, merged.getOneBasedStart());
    assertEquals(1, merged.getAltCalls().size());
    assertEquals("C", merged.getAltCalls().get(0));
    assertEquals(3, merged.getFormat(VcfUtils.FORMAT_GENOTYPE).size());
    assertEquals("0/1", merged.getFormat(VcfUtils.FORMAT_GENOTYPE).get(0));
    assertEquals(".", merged.getFormat(VcfUtils.FORMAT_GENOTYPE).get(1));
    assertEquals(".", merged.getFormat(VcfUtils.FORMAT_GENOTYPE).get(2));

    //test merge handling with multiple refs, some mergeable, some not
    final VcfHeader h3 = new VcfHeader();
    h3.addSampleName("sample3");
    r1 = createRecord("chr1", 50, "A", 0, 1, "C");
    r2 = createRecord("chr1", 50, "A", 1, 2, "G", "C");
    final VcfRecord r3 = createRecord("chr1", 50, "AC", 0, 1, "AG");
    mergedArr = merger.mergeRecords(new VcfRecord[]{r1, r2, r3}, new VcfHeader[]{h1, h2, h3});
    assertEquals(2, mergedArr.length);
    merged = mergedArr[0];
    assertEquals("chr1", merged.getSequenceName());
    assertEquals("A", merged.getRefCall());
    assertEquals(50, merged.getOneBasedStart());
    assertEquals(2, merged.getAltCalls().size());
    assertEquals("C", merged.getAltCalls().get(0));
    assertEquals("G", merged.getAltCalls().get(1));
    assertEquals(3, merged.getFormat(VcfUtils.FORMAT_GENOTYPE).size());
    assertEquals("0/1", merged.getFormat(VcfUtils.FORMAT_GENOTYPE).get(0));
    assertEquals("2/1", merged.getFormat(VcfUtils.FORMAT_GENOTYPE).get(1));
    assertEquals(".", merged.getFormat(VcfUtils.FORMAT_GENOTYPE).get(2));
    merged = mergedArr[1];
    assertEquals("chr1", merged.getSequenceName());
    assertEquals("AC", merged.getRefCall());
    assertEquals(50, merged.getOneBasedStart());
    assertEquals(1, merged.getAltCalls().size());
    assertEquals("AG", merged.getAltCalls().get(0));
    assertEquals(3, merged.getFormat(VcfUtils.FORMAT_GENOTYPE).size());
    assertEquals(".", merged.getFormat(VcfUtils.FORMAT_GENOTYPE).get(0));
    assertEquals(".", merged.getFormat(VcfUtils.FORMAT_GENOTYPE).get(1));
    assertEquals("0/1", merged.getFormat(VcfUtils.FORMAT_GENOTYPE).get(2));
  }

  // Test behaviour in presence of unmergeable FORMAT fields
  public void testUnmergeableHandling() {
    final FormatField unmergeable = new FormatField("Unmergeable", MetaType.FLOAT, VcfNumber.ALTS, "Some number per alt");
    final VcfHeader h1 = new VcfHeader();
    h1.addCommonHeader();
    h1.addSampleName("sample1");
    h1.addFormatField(unmergeable);
    final VcfHeader h2 = new VcfHeader();
    h2.addCommonHeader();
    h2.addSampleName("sample2");
    h2.addFormatField(unmergeable);
    final VcfHeader mh = VcfHeaderMerge.mergeHeaders(h1, h2, null);
//    final Set<String> hardSet = VcfMerge.alleleBasedFormats(mh);
//    assertTrue(hardSet.contains(unmergeable.getId()));

    final VcfRecordMerger merger = new VcfRecordMerger().setHeader(mh);

    // Alts have same set, but the ordering is different
    VcfRecord r1 = createRecord("chr1", 50, "A", 0, 1, "C", "G");
    r1.addFormatAndSample(unmergeable.getId(), "1.0");
    VcfRecord r2 = createRecord("chr1", 50, "A", 1, 2, "G", "C");
    r2.addFormatAndSample(unmergeable.getId(), "2.0,3.0");
    VcfRecord[] mergedArr = merger.mergeRecords(new VcfRecord[]{r1, r2}, new VcfHeader[]{h1, h2});
    assertEquals(2, mergedArr.length);
    assertTrue(mergedArr[0].hasFormat(unmergeable.getId()));
    assertTrue(mergedArr[1].hasFormat(unmergeable.getId()));

    // Alts have different alleles
    r1 = createRecord("chr1", 50, "A", 0, 1, "C");
    r1.addFormatAndSample(unmergeable.getId(), "1.0");
    r2 = createRecord("chr1", 50, "A", 1, 2, "G", "C");
    r2.addFormatAndSample(unmergeable.getId(), "2.0,3.0");
    mergedArr = merger.mergeRecords(new VcfRecord[]{r1, r2}, new VcfHeader[]{h1, h2});
    assertEquals(2, mergedArr.length);
    assertTrue(mergedArr[0].hasFormat(unmergeable.getId()));
    assertTrue(mergedArr[1].hasFormat(unmergeable.getId()));

    // Alts have different alleles, but allow merge by dropping the FORMAT fields
    merger.setDropUnmergeable(true);
    mergedArr = merger.mergeRecords(new VcfRecord[]{r1, r2}, new VcfHeader[]{h1, h2});
    assertEquals(1, mergedArr.length);
    assertFalse(mergedArr[0].hasFormat(unmergeable.getId()));

    // Single record edge cases.
    // These are kind of dodgy records since they have redundant alleles, so allele normalization on these can cause problems
    // We just pass them through after reordering the samples into the order expected in the destination.
    merger.setDropUnmergeable(false);
    for (String rr : new String[]{"chr1\t100\t.\tg\ta,C,a\t.\tPASS\t.", "chr1\t100\t.\tg\ta,G\t.\tPASS\t.", "chr1\t100\t.\tg\tg\t.\tPASS\t.", "chr1\t100\t.\tg\ta,C,A\t.\tPASS\t."}) {
      r2 = VcfReaderTest.vcfLineToRecord(rr);
      r2.setNumberOfSamples(1);
      r2.addFormatAndSample(unmergeable.getId(), "1.0");
      mergedArr = merger.mergeRecords(new VcfRecord[]{r2}, new VcfHeader[] {h2});
      assertEquals(1, mergedArr.length);
      final VcfRecord mr = mergedArr[0];
      assertNotNull(mr);
      assertTrue(mr.hasFormat(unmergeable.getId()));
      assertEquals(2, mr.getNumberOfSamples());
      assertEquals(2, mr.getFormat(unmergeable.getId()).size());
      assertEquals(".", mr.getFormat(unmergeable.getId()).get(0));
      assertEquals("1.0", mr.getFormat(unmergeable.getId()).get(1));
    }
  }

  public void testMergeFormat() {
    //Testing the merging of records with FORMAT fields with a number equal to genotype or alternate allele count
    final VcfHeader h1 = new VcfHeader();
    h1.addSampleName("sample1");
    h1.addFormatField("ZZ", MetaType.INTEGER, new VcfNumber("A"), "Number on Alt Allele");
    h1.addFormatField("ZX", MetaType.INTEGER, new VcfNumber("G"), "Number on Genotype");
    final VcfHeader h2 = new VcfHeader();
    h2.addSampleName("sample2");
    h2.addFormatField("ZZ", MetaType.INTEGER, new VcfNumber("A"), "Number on Alt Allele");
    h2.addFormatField("ZX", MetaType.INTEGER, new VcfNumber("G"), "Number on Genotype");
    final VcfHeader[] heads = {h1, h2};
    final VcfHeader mh = new VcfHeader();
    mh.addSampleName("sample1");
    mh.addSampleName("sample2");
    mh.addFormatField("ZZ", MetaType.INTEGER, new VcfNumber("A"), "Number on Alt Allele");
    mh.addFormatField("ZX", MetaType.INTEGER, new VcfNumber("G"), "Number on Genotype");

    final VcfRecordMerger merger = new VcfRecordMerger().setHeader(mh);

    VcfRecord r1 = VcfReaderTest.vcfLineToRecord("chr1\t100\t.\tG\tA,C\t.\tPASS\t.\tGT:ZZ\t1/2:1,2");
    VcfRecord r2 = VcfReaderTest.vcfLineToRecord("chr1\t100\t.\tG\tA,C\t.\tPASS\t.\tGT:ZX\t1/2:3,4,5");
    VcfRecord[] mergedArr = merger.mergeRecords(new VcfRecord[]{r1, r2}, heads);
    assertEquals(1, mergedArr.length);
    assertEquals("chr1\t100\t.\tG\tA,C\t.\tPASS\t.\tGT:ZZ:ZX\t1/2:1,2\t1/2:.:3,4,5", mergedArr[0].toString());

    // Check that GT is moved to front
    r2 = VcfReaderTest.vcfLineToRecord("chr1\t100\t.\tG\tA,C\t.\tPASS\t.\tZX\t3,4,5");
    mergedArr = merger.mergeRecords(new VcfRecord[]{r2, r1}, heads);
    assertEquals(1, mergedArr.length);
    assertEquals("chr1\t100\t.\tG\tA,C\t.\tPASS\t.\tGT:ZX:ZZ\t.:3,4,5\t1/2:.:1,2", mergedArr[0].toString());

    r2 = VcfReaderTest.vcfLineToRecord("chr1\t100\t.\tG\tC,A\t.\tPASS\t.\tGT:ZX\t1/2:3,4,5");
    mergedArr = merger.mergeRecords(new VcfRecord[]{r1, r2}, heads);
    assertEquals(2, mergedArr.length);
    assertEquals("chr1\t100\t.\tG\tA,C\t.\tPASS\t.\tGT:ZZ\t1/2:1,2\t.", mergedArr[0].toString());
    assertEquals("chr1\t100\t.\tG\tC,A\t.\tPASS\t.\tGT:ZX\t.\t1/2:3,4,5", mergedArr[1].toString());

    r2 = VcfReaderTest.vcfLineToRecord("chr1\t100\t.\tG\tA\t.\tPASS\t.\tGT:ZZ\t1/1:3");
    mergedArr = merger.mergeRecords(new VcfRecord[]{r1, r2}, heads);
    assertEquals(2, mergedArr.length);
    assertEquals("chr1\t100\t.\tG\tA,C\t.\tPASS\t.\tGT:ZZ\t1/2:1,2\t.", mergedArr[0].toString());
    assertEquals("chr1\t100\t.\tG\tA\t.\tPASS\t.\tGT:ZZ\t.\t1/1:3", mergedArr[1].toString());

    r1 = VcfReaderTest.vcfLineToRecord("chr1\t100\t.\tGGG\tAAA\t.\tPASS\t.\tGT:ZX\t0/1:1,2,3");
    r2 = VcfReaderTest.vcfLineToRecord("chr1\t100\t.\tGGG\tCCC\t.\tPASS\t.\tGT:ZX\t0/1:4,5,6");
    mergedArr = merger.mergeRecords(new VcfRecord[]{r1, r2}, heads);
    assertEquals(2, mergedArr.length);
    assertEquals("chr1\t100\t.\tGGG\tAAA\t.\tPASS\t.\tGT:ZX\t0/1:1,2,3\t.", mergedArr[0].toString());
    assertEquals("chr1\t100\t.\tGGG\tCCC\t.\tPASS\t.\tGT:ZX\t.\t0/1:4,5,6", mergedArr[1].toString());
  }

  public void testMergeInfo() {
    //Testing clearing of INFO fields with a number equal to genotype or alternate allele count
    final VcfHeader h1 = new VcfHeader();
    InfoField zz = new InfoField("ZZ", MetaType.INTEGER, new VcfNumber("A"), "Number on Alt Allele");
    InfoField zx = new InfoField("ZX", MetaType.INTEGER, new VcfNumber("A"), "Number on Genotype");
    h1.addSampleName("sample1");
    h1.addInfoField(zz);
    h1.addInfoField(zx);
    final VcfHeader h2 = new VcfHeader();
    h2.addSampleName("sample2");
    h2.addInfoField(zz);
    h2.addInfoField(zx);
    final VcfHeader[] heads = {h1, h2};
    final VcfHeader mh = new VcfHeader();
    mh.addSampleName("sample1");
    mh.addSampleName("sample2");
    mh.addInfoField(zz);
    mh.addInfoField(zx);

    final VcfRecordMerger merger = new VcfRecordMerger().setHeader(mh);

    VcfRecord r1 = VcfReaderTest.vcfLineToRecord("chr1\t100\t.\tG\tA,C\t.\tPASS\tZZ=1,2\tGT\t1/2");

    VcfRecord r2 = VcfReaderTest.vcfLineToRecord("chr1\t100\t.\tG\tA,C\t.\tPASS\tZX=3,4,5\tGT\t1|2");  // No ALT change
    VcfRecord[] mergedArr = merger.mergeRecords(new VcfRecord[]{r1, r2}, heads);
    assertEquals(1, mergedArr.length);
    assertEquals("chr1\t100\t.\tG\tA,C\t.\tPASS\tZZ=1,2\tGT\t1/2\t1|2", mergedArr[0].toString());

    r2 = VcfReaderTest.vcfLineToRecord("chr1\t100\t.\tG\tC,A\t.\tPASS\tZX=3,4,5\tGT\t1|2"); // Alt change
    mergedArr = merger.mergeRecords(new VcfRecord[]{r1, r2}, heads);
    assertEquals(2, mergedArr.length);
    assertEquals("chr1\t100\t.\tG\tA,C\t.\tPASS\tZZ=1,2\tGT\t1/2\t.", mergedArr[0].toString());
    assertEquals("chr1\t100\t.\tG\tC,A\t.\tPASS\tZX=3,4,5\tGT\t.\t1|2", mergedArr[1].toString());

    merger.setDropUnmergeable(true);
    mergedArr = merger.mergeRecords(new VcfRecord[]{r1, r2}, heads);
    assertEquals(1, mergedArr.length);
    assertEquals("chr1\t100\t.\tG\tA,C\t.\tPASS\t.\tGT\t1/2\t2|1", mergedArr[0].toString());
  }

  public void testIdMerge() {
    Diagnostic.setLogStream();
    final VcfRecord rec = new VcfRecord("chr1", 1209, "a");
    rec.setId("b;c")
      .setQuality("12.8")
      .addAltCall("c")
      .addAltCall("t")
      .addFilter("TEST1")
      .addFilter("TEST2")
      .setInfo("DP", "23")
      .setInfo("TEST", "45", "46", "47", "48")
      .setNumberOfSamples(1)
      .addFormatAndSample("GT", "0/0")
      .addFormatAndSample("GQ", "100")
    ;
    final VcfRecord rec2 = new VcfRecord("chr1", 1209, "a");
    rec2.setId("a")
      .setQuality("12.8")
      .addAltCall("c")
      .addAltCall("t")
      .addFilter("TEST1")
      .addFilter("TEST2")
      .setInfo("DP", "23")
      .setInfo("TEST", "45", "46", "47", "48")
      .setNumberOfSamples(1)
      .addFormatAndSample("GT", "0/1")
      .addFormatAndSample("GQ", "95")
    ;
    final VcfHeader h1 = new VcfHeader();
    h1.addSampleName("sample1");
    final VcfHeader h2 = new VcfHeader();
    h2.addSampleName("sample2");
    final VcfRecord[] recs = {rec, rec2};

    final VcfHeader mh = VcfHeaderMerge.mergeHeaders(h1, h2, null);
    final VcfRecordMerger merger = new VcfRecordMerger().setHeader(mh);

    final VcfRecord[] mergedArr = merger.mergeRecords(recs, new VcfHeader[]{h1, h2});
    assertEquals(1, mergedArr.length);
    final VcfRecord merged = mergedArr[0];
    assertEquals("b;c;a", merged.getId());
  }

  public void testPreserveDuplicateSamples() {
    final VcfHeader h1 = new VcfHeader();
    h1.addSampleName("sample1");
    final VcfHeader h2 = new VcfHeader();
    h2.addSampleName("sample1");
    final VcfHeader mh = VcfHeaderMerge.mergeHeaders(h1, h2, null);
    final VcfRecordMerger merger = new VcfRecordMerger().setHeader(mh).setDropUnmergeable(true);

    final VcfHeader[] heads = {h1, h2};
    final VcfRecord r1 = VcfReaderTest.vcfLineToRecord("chr1\t100\t.\tG\tA\t.\tPASS\t.\tGT\t1/1");
    final VcfRecord r2 = VcfReaderTest.vcfLineToRecord("chr1\t100\t.\tG\tC\t.\tPASS\t.\tGT\t0/1");

    VcfRecord[] mergedArr = merger.mergeRecords(new VcfRecord[]{r1, r2}, heads);
    assertEquals(1, mergedArr.length);
    // All alleles have nucleotide case normalized
    assertEquals("chr1\t100\t.\tG\tA,C\t.\tPASS\t.\tGT\t1/1", mergedArr[0].toString());

    merger.setDropUnmergeable(false);

    mergedArr = merger.mergeRecords(new VcfRecord[]{r1, r2}, heads);
    assertEquals(2, mergedArr.length);
    // All alleles have nucleotide case normalized
    assertEquals("chr1\t100\t.\tG\tA\t.\tPASS\t.\tGT\t1/1", mergedArr[0].toString());
    assertEquals("chr1\t100\t.\tG\tC\t.\tPASS\t.\tGT\t0/1", mergedArr[1].toString());
  }

  public void testCaseHandling() {
    final VcfHeader h1 = new VcfHeader();
    final VcfHeader h2 = new VcfHeader();
    final VcfHeader h3 = new VcfHeader();
    VcfHeader mh = VcfHeaderMerge.mergeHeaders(h1, h2, null);
    mh = VcfHeaderMerge.mergeHeaders(mh, h3, null);
    final VcfRecordMerger merger = new VcfRecordMerger().setHeader(mh);

    final VcfHeader[] heads = {h1, h2, h3};
    final VcfRecord r1 = VcfReaderTest.vcfLineToRecord("chr1\t100\t.\tg\ta,C\t.\tPASS\t.");
    final VcfRecord r2 = VcfReaderTest.vcfLineToRecord("chr1\t100\t.\tG\tc,t\t.\tPASS\t.");
    final VcfRecord r3 = VcfReaderTest.vcfLineToRecord("chr1\t100\t.\tG\tc]Chr1:123]g\t.\tPASS\t.");

    final VcfRecord[] mergedArr = merger.mergeRecords(new VcfRecord[]{r1, r2, r3}, heads);
    assertEquals(1, mergedArr.length);
    // All alleles have nucleotide case normalized
    assertEquals("chr1\t100\t.\tG\tA,C,T,C]Chr1:123]G\t.\tPASS\t.", mergedArr[0].toString());
  }
}


text:
using CorDebugInterop;
using nanoFramework.Tools.Debugger.WireProtocol;
using BreakpointDef = nanoFramework.Tools.Debugger.WireProtocol.Commands.Debugging_Execution_BreakpointDef;
using Debug = System.Diagnostics.Debug;

namespace nanoFramework.Tools.VisualStudio.Extension
{
    //Superclass for all nanoCLR breakpoints
    public abstract class CorDebugBreakpointBase
    {
        static ushort s_idNull = 0;
        static ushort s_idNext = 1;

        private CorDebugProcess m_process;
        private CorDebugAppDomain m_appDomain;
        private bool m_fActive;

        protected readonly BreakpointDef m_breakpointDef;

        protected CorDebugBreakpointBase( CorDebugProcess process )
        {
            m_breakpointDef = new BreakpointDef();
            m_breakpointDef.m_id = s_idNext++;
            m_breakpointDef.m_pid = BreakpointDef.c_PID_ANY;

            m_appDomain = null;
            m_process = process;

            Debug.Assert(s_idNext != s_idNull);
        }

        protected CorDebugBreakpointBase(CorDebugAppDomain appDomain) : this(appDomain.Process)
        {
            m_appDomain = appDomain;
        }

        public CorDebugAppDomain AppDomain
        {
            [System.Diagnostics.DebuggerHidden]
            get { return m_appDomain; }
        }

        public virtual bool IsMatch( BreakpointDef breakpointDef )
        {
            return breakpointDef.m_id == this.m_breakpointDef.m_id;
        }

        public ushort Kind
        {
            [System.Diagnostics.DebuggerHidden]
            get { return m_breakpointDef.m_flags; }

            set
            {
                m_breakpointDef.m_flags = value;
                Dirty();
            }
        }

        protected CorDebugProcess Process
        {
            [System.Diagnostics.DebuggerHidden]
            get { return m_process; }
        }

        public bool Active
        {
            [System.Diagnostics.DebuggerHidden]
            get { return m_fActive; }

            set
            {
                if (m_fActive != value)
                {
                    m_fActive = value;
                    m_process.RegisterBreakpoint(this, m_fActive);
                    Dirty();
                }
            }
        }

        public void Dirty()
        {
            m_process.DirtyBreakpoints();
        }

        public virtual void Hit(BreakpointDef breakpointDef)
        {
        }

        public virtual bool ShouldBreak(BreakpointDef breakpointDef)
        {
            return true;
        }

        public virtual bool Equals(CorDebugBreakpointBase breakpoint)
        {
            return this.Equals( (object)breakpoint );
        }

        public BreakpointDef Debugging_Execution_BreakpointDef
        {
            [System.Diagnostics.DebuggerHidden]
            get { return m_breakpointDef; }
        }
    }

    public class CLREventsBreakpoint : CorDebugBreakpointBase
    {
        public CLREventsBreakpoint(CorDebugProcess process) : base (process)
        {
            this.Kind = BreakpointDef.c_EXCEPTION_THROWN |
                        BreakpointDef.c_EXCEPTION_CAUGHT |
#if NO_THREAD_CREATED_EVENTS
                        BreakpointDef.c_EVAL_COMPLETE    |
#else
                        BreakpointDef.c_THREAD_CREATED |
                        BreakpointDef.c_THREAD_TERMINATED |
#endif
                        BreakpointDef.c_ASSEMBLIES_LOADED |
                        BreakpointDef.c_BREAK;

            this.Active = true;
        }

        public override void Hit(BreakpointDef breakpointDef)
        {
#if NO_THREAD_CREATED_EVENTS
            if ((breakpointDef.m_flags & BreakpointDef.c_EVAL_COMPLETE) != 0)
                EvalComplete(breakpointDef);
#else
            if ((breakpointDef.m_flags & BreakpointDef.c_THREAD_CREATED) != 0)
                ThreadCreated(breakpointDef);
            else if ((breakpointDef.m_flags & BreakpointDef.c_THREAD_TERMINATED) != 0)
                ThreadTerminated(breakpointDef);
#endif
            else if ((breakpointDef.m_flags & BreakpointDef.c_EXCEPTION_THROWN) != 0)
                ExceptionThrown(breakpointDef);
            else if ((breakpointDef.m_flags & BreakpointDef.c_EXCEPTION_CAUGHT) != 0)
                ExceptionCaught(breakpointDef);
            else if ((breakpointDef.m_flags & BreakpointDef.c_ASSEMBLIES_LOADED) != 0)
                AssembliesLoaded(breakpointDef);
            else if ((breakpointDef.m_flags & BreakpointDef.c_BREAK) != 0)
                Break(breakpointDef);
            else
                Debug.Assert(false, "unknown CLREvent breakpoint");
        }

#if NO_THREAD_CREATED_EVENTS
        private void EvalComplete(BreakpointDef breakpointDef)
        {
            CorDebugThread thread = Process.GetThread(breakpointDef.m_pid);

            //This currently gets called after BreakpointHit updates the list of threads.
            //This should nop as long as func-eval happens on separate threads.

            Debug.Assert(thread == null);

            Process.RemoveThread(thread);
        }
#else
        private void ThreadTerminated(BreakpointDef breakpointDef)
        {
            CorDebugThread thread = Process.GetThread(breakpointDef.m_pid);

            // Thread could be NULL if this function is called as result of Thread.Abort in
            // managed application and application does not catch expeption.
            // ThreadTerminated is called after thread exits in managed application.
            if ( thread != null )
            {
                Process.RemoveThread( thread );
            }
        }

        private void ThreadCreated(BreakpointDef breakpointDef)
        {
            CorDebugThread thread = this.Process.GetThread(breakpointDef.m_pid);

            Debug.Assert(thread == null || thread.IsVirtualThread);
            if (thread == null)
            {
                thread = new CorDebugThread(this.Process, breakpointDef.m_pid, null);
                this.Process.AddThread(thread);
            }
        }
#endif

        public override bool ShouldBreak(Commands.Debugging_Execution_BreakpointDef breakpointDef)
        {
            if ((breakpointDef.m_flags & BreakpointDef.c_EXCEPTION_CAUGHT) != 0)
            {
                //This if statement remains for compatibility with nanoCLR pre exception filtering support.
                if((breakpointDef.m_flags & BreakpointDef.c_EXCEPTION_UNWIND) == 0)
                    return false;
            }

            return true;
        }

        private void ExceptionThrown(BreakpointDef breakpointDef)
        {
            CorDebugThread thread = this.Process.GetThread(breakpointDef.m_pid);

            thread.StoppedOnException();

            CorDebugFrame frame = thread.Chain.GetFrameFromDepthnanoCLR(breakpointDef.m_depth);
            bool fIsEval        = thread.IsVirtualThread;
            bool fUnhandled     = (breakpointDef.m_depthExceptionHandler == BreakpointDef.c_DEPTH_UNCAUGHT);

            if (this.Process.Engine.Capabilities.ExceptionFilters)
            {
                switch (breakpointDef.m_depthExceptionHandler)
                {
                    case BreakpointDef.c_DEPTH_EXCEPTION_FIRST_CHANCE:
                        Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackException(thread, frame, breakpointDef.m_IP, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_FIRST_CHANCE));
                        break;
                    case BreakpointDef.c_DEPTH_EXCEPTION_USERS_CHANCE:
                        Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackException(thread, frame, breakpointDef.m_IP, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_USER_FIRST_CHANCE));
                        break;
                    case BreakpointDef.c_DEPTH_EXCEPTION_HANDLER_FOUND:
                        Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackException(thread, frame, breakpointDef.m_IP, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_CATCH_HANDLER_FOUND));
                        break;
                }
            }
            else
            {
                Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackException(thread, frame, breakpointDef.m_IP, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_FIRST_CHANCE));

                uint depthMin = (fUnhandled) ? 0 : breakpointDef.m_depthExceptionHandler;

                for (uint depth = breakpointDef.m_depth; depth >= depthMin; depth--)
                {
                    frame = thread.Chain.GetFrameFromDepthnanoCLR(depth);

                    if (frame != null && frame.Function.HasSymbols && frame.Function.PdbxMethod.IsJMC)
                    {
                        Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackException(thread, frame, frame.IP_nanoCLR, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_USER_FIRST_CHANCE));
                        break;
                    }

                    if (depth == 0)
                    {
                        break;
                    }
                }

                if(!fUnhandled)
                {
                    frame = thread.Chain.GetFrameFromDepthnanoCLR(breakpointDef.m_depthExceptionHandler);
                    Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackException(thread, frame, breakpointDef.m_IP, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_CATCH_HANDLER_FOUND));
                }
            }

            if (fUnhandled)
            {
                //eval threads are virtual, and although the physical thread has an unhandled exception, the
                //virtual thread does not.  The eval thread will get killed, but the rest of the thread chain will
                //survive, no need to confuse cpde by throwing an unhandled exception
                if (fIsEval)
                {
                    CorDebugEval eval = thread.CurrentEval;
                    eval.StoppedOnUnhandledException();

                    Debug.Assert(thread.IsVirtualThread);

                    CorDebugThread threadT = thread.GetRealCorDebugThread();
                    CorDebugFrame frameT = threadT.Chain.ActiveFrame;

                    //fake event to let debugging of unhandled exception occur.
                    //Frame probably needs to be an InternalStubFrame???
                    frame = thread.Chain.GetFrameFromDepthCLR(thread.Chain.NumFrames - 1);
#if DEBUG
                    CorDebugInternalFrame internalFrame = frame as CorDebugInternalFrame;
                    Debug.Assert(internalFrame != null && internalFrame.FrameType == CorDebugInternalFrameType.STUBFRAME_FUNC_EVAL);

#endif
                    Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackException(thread, frame, 0, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_CATCH_HANDLER_FOUND));
                }
                else
                {
                    Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackException(thread, null, uint.MaxValue, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_UNHANDLED));
                }
            }
        }

        private void ExceptionCaught(BreakpointDef breakpointDef)
        {
            CorDebugThread thread = this.Process.GetThread(breakpointDef.m_pid);

            CorDebugFrame frame = thread.Chain.GetFrameFromDepthnanoCLR(breakpointDef.m_depth);

            Debug.Assert((breakpointDef.m_flags & BreakpointDef.c_EXCEPTION_UNWIND) != 0);

            Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackExceptionUnwind(thread, frame, CorDebugExceptionUnwindCallbackType.DEBUG_EXCEPTION_INTERCEPTED));
        }

        private void AssembliesLoaded(BreakpointDef breakpointDef)
        {
            this.Process.UpdateAssemblies();
        }

        private void Break(BreakpointDef breakpointDef)
        {
            CorDebugThread thread = Process.GetThread(breakpointDef.m_pid);

            Process.EnqueueEvent( new ManagedCallbacks.ManagedCallbackBreak( thread ) );
        }
    }
}


text:
class CreateOfferingRestrictions < ActiveRecord::Migration
  def self.up
    create_table :offering_restrictions do |t|
      t.integer :offering_id
      t.integer :offering_restriction_type_id

      t.timestamps
    end
  end

  def self.down
    drop_table :offering_restrictions
  end
end


text:
<problem>
  <version id="1">
    <authors>nschank</authors>
    <year>1995</year>
    <topics>set_theory probability</topics>
    <types>piece proof</types>
    Body 1
    <solution>Solution 1</solution>
    <rubric>Rubric 1</rubric>
  </version>
  <version id="0">
    <authors>nschank</authors>
    <year>1994</year>
    <topics>set_theory probability</topics>
    <types>piece proof</types>
    Body 0
    <solution>Solution 0</solution>
    <rubric>Rubric 0</rubric>
  </version>
</problem>


text:
from django.contrib import messages
from django.contrib.auth import login as do_login, logout as do_logout
from django.contrib.auth.forms import AuthenticationForm
from django.shortcuts import redirect, render
from django.template.context import RequestContext

def login(request):
    #messages.debug(request, "Debug!")
    #messages.info(request, "Info!")
    #messages.success(request, "Success!")
    #messages.warning(request, "Warning!")
    #messages.error(request, "Error!")

    if request.user.is_authenticated():
        return redirect("/student")

    context = {}
    if request.method == "POST":
        form = AuthenticationForm(None, request.POST)
        if form.is_valid():
            user = form.get_user()
            print(user)
            if user.is_active:
                do_login(request, user)
                return redirect("/student")
            else:
                messages.error(request, "Benutzeraccount ist deaktiviert!")
    else:
        form = AuthenticationForm()
    context["form"] = form
    return render(request, "session/login.html", context, context_instance=RequestContext(request))

def logout(request):
    if request.user.is_authenticated():
        messages.info(request, "Erfolgreich ausgeloggt!")
        do_logout(request)
    return redirect("/login")


text:
project_path: /web/_project.yaml
book_path: /web/updates/_book.yaml
description: An introduction to Mutation Observers.

{# wf_updated_on: 2019-02-01 #}
{# wf_published_on: 2012-02-15 #}
{# wf_tags: news,mutationobserver,dom #}
{# wf_blink_components: N/A #}

# Detect DOM changes with Mutation Observers {: .page-title }

{% include "web/_shared/contributors/paulkinlan.html" %}

Back in 2000, the [Mutation Events API was specified](https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-mutationevents) to make it easy for developers to react to changes in a DOM (e.g. DOMNodeRemoved, DOMAttrModified, etc).

This feature wasn't widely used by web developers but it presented a very convenient and popular use case for Chrome Extensions if they wanted to perform some action when something in the page changed.

Mutation Events are useful, but at the same time they create some performance issues. The Events are slow and they are fired too frequently in a synchronous way, which causes some undesired browser bugs.

Introduced in the [DOM4 specification](https://www.w3.org/TR/dom/){: .external }, [DOM Mutation Observers](https://www.w3.org/TR/dom/#mutation-observers) will replace Mutation Events. Whereas Mutation Events fired slow events for every single change, Mutation Observers are faster using callback functions that can be delivered after multiple changes in the DOM.

You can [manually handle the list of changes](https://www.w3.org/TR/dom/#mutationrecord) the API offers, or use a library such as [Mutation Summary](https://github.com/rafaelw/mutation-summary) which makes this task easier and adds a layer of reliability about the changes that took place in the DOM.

You can start using Mutation Observers in Chrome Beta to detect changes in the DOM and be ready to use it when it comes to stable (Chrome 18). If you are currently using  the deprecated Mutation Events, just migrate to Mutation Observers.

Here's an example of listing inserted nodes with Mutation Events:

    var insertedNodes = [];
    document.addEventListener("DOMNodeInserted", function(e) {
      insertedNodes.push(e.target);
    }, false);
    console.log(insertedNodes);

And here's how it looks with Mutation Observers:

    var insertedNodes = [];
    var observer = new MutationObserver(function(mutations) {
     mutations.forEach(function(mutation) {
       for (var i = 0; i < mutation.addedNodes.length; i++)
         insertedNodes.push(mutation.addedNodes[i]);
     })
    });
    observer.observe(document, { childList: true });
    console.log(insertedNodes);


text:
			<img class="img-ceo img-circle img-responsive" src="<?php echo get_template_directory_uri(); ?>/assets/img/gule.jpg">

Gulé Sheikh

Founder and CEO

Gule has been in the tech sector for 16+ years, where she has led and managed large enterprise wide teams. Through her career she has managed large scale Program Management Offices overseeing cross enterprise projects in several industries including financial and healthcare sectors. She has worked with her clients on building strategic roadmaps, implementation plans and execution strategies. She is creative by nature and passionate about the process of an idea and creating it into a product.

			<img class="img-ceo img-circle img-responsive" src="<?php echo get_template_directory_uri(); ?>/assets/img/poulose.jpg">

Poulose Matthen

iOS Engineer

Since graduating from the Rochester Institute of Technology, Poulose has worked as a designer of innovative product packaging, and as a copywriter in an advertising agency. Additionally, he helped set up and start an online flavors and fragrances company and worked with a freelancer to develop a digital catalogue/menu application focusing on wine for Android and iOS tablets. Thoroughly enjoying the app development process, he learned how to code for iOS and has been developing applications since.

			<img class="img-ceo img-circle img-responsive" src="<?php echo get_template_directory_uri(); ?>/assets/img/steph.jpg">

Stephanie Cruz

UX/UI Designer

A graduate of OCAD University in Toronto, ON, Stephanie has always been a creative problem solver and storyteller. With a strong background in graphic design, her love for the craft evolved into a love for all things digital and interactive.  Ultimately, Stephanie strives to get the BIG idea across through beautifully designed interfaces that create the best user experiences possible.

			<img class="img-ceo img-circle img-responsive" src="<?php echo get_template_directory_uri(); ?>/assets/img/sonya.jpg">

Sonya Gill

Social Media and Marketing Strategist

Sonya Gill, has combined her love for Journalism with Social Media to create a full cycle brand profile for our clients. She creates a complete social strategy where she will focus and drive our customers online and mobile presence through digital marketing, social networking and connecting brands to social influencers.

			<img class="img-ceo img-circle img-responsive" src="<?php echo get_template_directory_uri(); ?>/assets/img/jani.jpg">

Dimple Jani

Business Development

Dimple is the Business Development lead for ZettaNode. She has extensive experience in managing demanding timelines for our client and has a deep passion for technology. She puts all her clients needs first and foremost and has worked to identify the needs of each of the client and oversee's the day to day tasks to ensure nothing is delayed.

			<img class="img-ceo img-circle img-responsive" src="<?php echo get_template_directory_uri(); ?>/assets/img/guping.jpg">

Guping Ma

Social Media and Marketing Rep

Guping graduated from University of Georgia with master degree in advertising. She has in-depth experience in advertising, communication, sales, HR and Campaign Design and Branding. Her strong experience and solid academic background in advertising and mass communication allows her to focus on each of our clients with quality, care and precision.

			<img class="img-ceo img-circle img-responsive" src="<?php echo get_template_directory_uri(); ?>/assets/img/daisy.jpg">

Ziwei Han

Marketing and Advertising Rep

Ziwei is a second-year graduate student at the Illinois Institute of Technology, Stuart School of Business, concentrating in Marketing Analytics and Communication.She has extensive experience in marketing and previously was as an account executive at a digital company.She has experience with using databases to analyze consumer behaviours and preference. She has worked with several digital platforms skillfully and found suitable marketing strategies for consumers.

			<img class="img-ceo img-circle img-responsive" src="<?php echo get_template_directory_uri(); ?>/assets/img/ashley.jpg">

Ashley Kane

Social Media Marketing and Blogger

Vestibulum sit amet facilisis mauris, nec elementum justo. Nulla dignissim lorem quam, sed facilisis tortor commodo vel. Cras mattis venenatis aliquet. Phasellus eget dignissim velit, sit amet porttitor metus. Quisque blandit ligula vel nibh convallis, vitae vulputate enim sodales. Etiam euismod vulputate lacus, fermentum tincidunt diam tempus sit amet. Maecenas a imperdiet nunc. Sed facilisis arcu mi, nec malesuada est aliquam et.


text:
#ifndef SRC_VNET_SESSION_SEGMENT_MANAGER_H_
#define SRC_VNET_SESSION_SEGMENT_MANAGER_H_

#include <svm/message_queue.h>
#include <vppinfra/lock.h>
#include <vppinfra/valloc.h>
#include <svm/fifo_segment.h>
#include <vnet/session/session_types.h>

typedef struct _segment_manager_props
{
  u32 rx_fifo_size;			/**< receive fifo size */
  u32 tx_fifo_size;			/**< transmit fifo size */
  u32 evt_q_size;			/**< event queue length */
  u32 prealloc_fifos;			/**< preallocated fifo pairs */
  u32 prealloc_fifo_hdrs;		/**< preallocated fifo hdrs */
  uword segment_size;			/**< first segment size */
  uword add_segment_size;		/**< additional segment size */
  u8 add_segment:1;			/**< can add new segments flag */
  u8 use_mq_eventfd:1;			/**< use eventfds for mqs flag */
  u8 reserved:6;			/**< reserved flags */
  u8 n_slices;				/**< number of fs slices/threads */
  ssvm_segment_type_t segment_type;	/**< seg type: if set to SSVM_N_TYPES,
					     private segments are used */
  u32 max_fifo_size;			/**< max fifo size */
  u8 high_watermark;			/**< memory usage high watermark % */
  u8 low_watermark;			/**< memory usage low watermark % */
  u8 pct_first_alloc;			/**< pct of fifo size to alloc */
  u8 huge_page;				/**< use hugepage */
} segment_manager_props_t;

typedef enum seg_manager_flag_
{
  SEG_MANAGER_F_DETACHED = 1 << 0,
  SEG_MANAGER_F_DETACHED_LISTENER = 1 << 1,
} seg_manager_flag_t;

typedef struct _segment_manager
{
  /** Pool of segments allocated by this manager */
  fifo_segment_t *segments;

  /** rwlock that protects the segments pool */
  clib_rwlock_t segments_rwlock;

  /** Owner app worker index */
  u32 app_wrk_index;

  /**
   * First segment should not be deleted unless segment manger is deleted.
   * This also indicates that the segment manager is the first to have been
   * allocated for the app.
   */
  u8 first_is_protected;

  /**
   * App event queue allocated in first segment
   */
  svm_msg_q_t *event_queue;

  u8 flags;

  u32 max_fifo_size;
  u8 high_watermark;
  u8 low_watermark;
} segment_manager_t;

#define SEGMENT_MANAGER_INVALID_APP_INDEX ((u32) ~0)

segment_manager_t *segment_manager_alloc (void);
int segment_manager_init (segment_manager_t * sm);
int segment_manager_init_first (segment_manager_t * sm);

/**
 * Cleanup segment manager
 *
 * @param sm	segment manager to be freed
 */
void segment_manager_free (segment_manager_t * sm);
void segment_manager_free_safe (segment_manager_t *sm);

/**
 * Initiate segment manager cleanup
 *
 * @param sm	segment manager to be freed
 */
void segment_manager_init_free (segment_manager_t * sm);
segment_manager_t *segment_manager_get (u32 index);
segment_manager_t *segment_manager_get_if_valid (u32 index);
u32 segment_manager_index (segment_manager_t * sm);

/**
 * Add segment without lock
 *
 * @param sm		Segment manager
 * @param segment_size	Size of segment to be added
 * @param notify_app	Flag set if app notification requested
 */
int segment_manager_add_segment (segment_manager_t *sm, uword segment_size,
				 u8 notify_app);

/**
 * Add segment with lock
 *
 * @param sm		Segment manager
 * @param segment_size	Size of segment to be added
 * @param flags		Flags to be set on segment
 */
int segment_manager_add_segment2 (segment_manager_t *sm, uword segment_size,
				  u8 flags);
void segment_manager_del_segment (segment_manager_t * sm,
				  fifo_segment_t * fs);
void segment_manager_lock_and_del_segment (segment_manager_t * sm,
					   u32 fs_index);
fifo_segment_t *segment_manager_get_segment (segment_manager_t * sm,
					     u32 segment_index);
fifo_segment_t *segment_manager_get_segment_w_handle (u64 sh);
fifo_segment_t *segment_manager_get_segment_w_lock (segment_manager_t * sm,
						    u32 segment_index);
int segment_manager_add_first_segment (segment_manager_t * sm,
				       u32 segment_size);
u64 segment_manager_make_segment_handle (u32 segment_manager_index,
					 u32 segment_index);
u64 segment_manager_segment_handle (segment_manager_t * sm,
				    fifo_segment_t * segment);
void segment_manager_segment_reader_unlock (segment_manager_t * sm);

int segment_manager_alloc_session_fifos (segment_manager_t * sm,
					 u32 thread_index,
					 svm_fifo_t ** rx_fifo,
					 svm_fifo_t ** tx_fifo);
int segment_manager_try_alloc_fifos (fifo_segment_t * fs,
				     u32 thread_index,
				     u32 rx_fifo_size, u32 tx_fifo_size,
				     svm_fifo_t ** rx_fifo,
				     svm_fifo_t ** tx_fifo);
void segment_manager_dealloc_fifos (svm_fifo_t * rx_fifo,
				    svm_fifo_t * tx_fifo);
void segment_manager_detach_fifo (segment_manager_t *sm, svm_fifo_t **f);
void segment_manager_attach_fifo (segment_manager_t *sm, svm_fifo_t **f,
				  session_t *s);

void segment_manager_set_watermarks (segment_manager_t * sm,
				     u8 high_watermark, u8 low_watermark);

u8 segment_manager_has_fifos (segment_manager_t * sm);

svm_msg_q_t *segment_manager_alloc_queue (fifo_segment_t * fs,
					  segment_manager_props_t * props);
void segment_manager_dealloc_queue (segment_manager_t * sm, svm_queue_t * q);
svm_msg_q_t *segment_manager_event_queue (segment_manager_t * sm);
u32 segment_manager_evt_q_expected_size (u32 q_size);

u8 segment_manager_app_detached (segment_manager_t * sm);
void segment_manager_app_detach (segment_manager_t * sm);

/**
 * Cleanup segment manager sessions
 *
 * Initiates disconnects for all sessions 'owned' by a segment manager by
 * leveraging the backpointers that fifos keep.
 *
 * @param sm	segment manager whose sessions are to be disconnected
 */
void segment_manager_del_sessions (segment_manager_t * sm);
void segment_manager_del_sessions_filter (segment_manager_t *sm,
					  session_state_t *states);
void segment_manager_format_sessions (segment_manager_t * sm, int verbose);

void segment_manager_main_init (void);

segment_manager_props_t *segment_manager_props_init (segment_manager_props_t *
						     sm);

static inline void
segment_manager_parse_segment_handle (u64 segment_handle, u32 * sm_index,
				      u32 * segment_index)
{
  *sm_index = segment_handle >> 32;
  *segment_index = segment_handle & 0xFFFFFFFF;
}

#endif /* SRC_VNET_SESSION_SEGMENT_MANAGER_H_ */
/*
 * fd.io coding-style-patch-verification: ON
 *
 * Local Variables:
 * eval: (c-set-style "gnu")
 * End:
 */


text:
#ifndef WEBRTC_SYSTEM_WRAPPERS_INTERFACE_ALIGNED_MALLOC_H_
#define WEBRTC_SYSTEM_WRAPPERS_INTERFACE_ALIGNED_MALLOC_H_

// The functions declared here
// 1) Allocates block of aligned memory.
// 2) Re-calculates a pointer such that it is aligned to a higher or equal
//    address.
// Note: alignment must be a power of two. The alignment is in bytes.

#include <stddef.h>

#include "webrtc/system_wrappers/interface/scoped_ptr.h"

namespace webrtc {

// Returns a pointer to the first boundry of |alignment| bytes following the
// address of |ptr|.
// Note that there is no guarantee that the memory in question is available.
// |ptr| has no requirements other than it can't be NULL.
void* GetRightAlign(const void* ptr, size_t alignment);

// Allocates memory of |size| bytes aligned on an |alignment| boundry.
// The return value is a pointer to the memory. Note that the memory must
// be de-allocated using AlignedFree.
void* AlignedMalloc(size_t size, size_t alignment);
// De-allocates memory created using the AlignedMalloc() API.
void AlignedFree(void* mem_block);

// Templated versions to facilitate usage of aligned malloc without casting
// to and from void*.
template<typename T>
T* GetRightAlign(const T* ptr, size_t alignment) {
  return reinterpret_cast<T*>(GetRightAlign(reinterpret_cast<const void*>(ptr),
                                            alignment));
}
template<typename T>
T* AlignedMalloc(size_t size, size_t alignment) {
  return reinterpret_cast<T*>(AlignedMalloc(size, alignment));
}

// Scoped pointer to AlignedMalloc-memory.
template<typename T>
struct Allocator {
  typedef scoped_ptr_malloc<T, AlignedFree> scoped_ptr_aligned;
};

}  // namespace webrtc

#endif // WEBRTC_SYSTEM_WRAPPERS_INTERFACE_ALIGNED_MALLOC_H_


text:
function Controller() {
    require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
    this.__controllerPath = "doctorOne";
    arguments[0] ? arguments[0]["__parentSymbol"] : null;
    arguments[0] ? arguments[0]["$model"] : null;
    arguments[0] ? arguments[0]["__itemTemplate"] : null;
    var $ = this;
    var exports = {};
    $.__views.doctorOne = Ti.UI.createView({
        id: "doctorOne"
    });
    $.__views.doctorOne && $.addTopLevelView($.__views.doctorOne);
    exports.destroy = function() {};
    _.extend($, $.__views);
    arguments[0] || {};
    _.extend($, exports);
}

var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;

module.exports = Controller;


text:
namespace rxcpp {

namespace operators {

namespace detail {

template<class T, class Observable, class Count>
struct repeat : public operator_base<T>
{
    typedef rxu::decay_t<Observable> source_type;
    typedef rxu::decay_t<Count> count_type;
    struct values
    {
        values(source_type s, count_type t)
            : source(std::move(s))
            , remaining(std::move(t))
            , repeat_infinitely(t == 0)
        {
        }
        source_type source;
        count_type remaining;
        bool repeat_infinitely;
    };
    values initial;

    repeat(source_type s, count_type t)
        : initial(std::move(s), std::move(t))
    {
    }

    template<class Subscriber>
    void on_subscribe(const Subscriber& s) const {

        typedef Subscriber output_type;
        struct state_type
            : public std::enable_shared_from_this<state_type>
            , public values
        {
            state_type(const values& i, const output_type& oarg)
                : values(i)
                , source_lifetime(composite_subscription::empty())
                , out(oarg)
            {
            }
            composite_subscription source_lifetime;
            output_type out;
            composite_subscription::weak_subscription lifetime_token;

            void do_subscribe() {
                auto state = this->shared_from_this();

                state->out.remove(state->lifetime_token);
                state->source_lifetime.unsubscribe();

                state->source_lifetime = composite_subscription();
                state->lifetime_token = state->out.add(state->source_lifetime);

                state->source.subscribe(
                    state->out,
                    state->source_lifetime,
                // on_next
                    [state](T t) {
                        state->out.on_next(t);
                    },
                // on_error
                    [state](std::exception_ptr e) {
                        state->out.on_error(e);
                    },
                // on_completed
                    [state]() {
                        if (state->repeat_infinitely || (--state->remaining > 0)) {
                            state->do_subscribe();
                        } else {
                            state->out.on_completed();
                        }
                    }
                );
            }
        };

        // take a copy of the values for each subscription
        auto state = std::make_shared<state_type>(initial, s);

        // start the first iteration
        state->do_subscribe();
    }
};

template<class T>
class repeat_factory
{
    typedef rxu::decay_t<T> count_type;
    count_type count;
public:
    repeat_factory(count_type t) : count(std::move(t)) {}

    template<class Observable>
    auto operator()(Observable&& source)
        ->      observable<rxu::value_type_t<rxu::decay_t<Observable>>, repeat<rxu::value_type_t<rxu::decay_t<Observable>>, Observable, count_type>> {
        return  observable<rxu::value_type_t<rxu::decay_t<Observable>>, repeat<rxu::value_type_t<rxu::decay_t<Observable>>, Observable, count_type>>(
                                                                        repeat<rxu::value_type_t<rxu::decay_t<Observable>>, Observable, count_type>(std::forward<Observable>(source), count));
    }
};

}

template<class T>
auto repeat(T&& t)
->      detail::repeat_factory<T> {
    return  detail::repeat_factory<T>(std::forward<T>(t));
}

}

}

#endif


text:
var args = arguments[0] || {};
var paso = args.paso;
var banInicio = args.banInicio;

$.lblDistancia.applyProperties($.createStyle(Alloy.FuenteTitulo()));
$.lblIndicacion.applyProperties($.createStyle(Alloy.FuenteMedia()));

if (!banInicio) {
	$.lblDistancia.text = paso.distance.text;
	var pattern = new RegExp( '<[^>]+>', 'g' );
	$.lblIndicacion.text = paso.html_instructions;
	$.lblIndicacion.text = $.lblIndicacion.text.replace(pattern, '');
}
else{
	$.lblDistancia.text = paso.distance.text;
	$.lblIndicacion.text = paso.duration.text;
};


text:
use super::*;

use rustc_ast as ast;
use rustc_span::create_default_session_globals_then;
use rustc_span::symbol::Ident;

fn fun_to_string(
    decl: &ast::FnDecl,
    header: ast::FnHeader,
    name: Ident,
    generics: &ast::Generics,
) -> String {
    to_string(|s| {
        s.head("");
        s.print_fn(decl, header, Some(name), generics);
        s.end(); // Close the head box.
        s.end(); // Close the outer box.
    })
}

fn variant_to_string(var: &ast::Variant) -> String {
    to_string(|s| s.print_variant(var))
}

#[test]
fn test_fun_to_string() {
    create_default_session_globals_then(|| {
        let abba_ident = Ident::from_str("abba");

        let decl =
            ast::FnDecl { inputs: Vec::new(), output: ast::FnRetTy::Default(rustc_span::DUMMY_SP) };
        let generics = ast::Generics::default();
        assert_eq!(
            fun_to_string(&decl, ast::FnHeader::default(), abba_ident, &generics),
            "fn abba()"
        );
    })
}

#[test]
fn test_variant_to_string() {
    create_default_session_globals_then(|| {
        let ident = Ident::from_str("principal_skinner");

        let var = ast::Variant {
            ident,
            vis: ast::Visibility {
                span: rustc_span::DUMMY_SP,
                kind: ast::VisibilityKind::Inherited,
                tokens: None,
            },
            attrs: ast::AttrVec::new(),
            id: ast::DUMMY_NODE_ID,
            data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
            disr_expr: None,
            span: rustc_span::DUMMY_SP,
            is_placeholder: false,
        };

        let varstr = variant_to_string(&var);
        assert_eq!(varstr, "principal_skinner");
    })
}


text:
<?php
namespace Cms\MainBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * BlockRepository
 */
class BlockRepository extends EntityRepository
{

}


text:
{% extends "includes/base.html" %}

{% block page_title %}
{% if user.is_authenticated %}
Stránka je nedostupná
{% else %}
Registrace úspěšná
{% endif %}
{% endblock page_title %}

{% block content %}

{% if user.is_authenticated %}

Tato stránka je nedostupná, zatímco jste přihlášení.

{% else %}
Klikněte zde k přihlášení

{% endif %}

            <button type="button" class="close" data-dismiss="modal">×</button>

 Login

            <form action="/accounts/auth/" method="post">{% csrf_token %}

                 Username
                <input data-toggle="tooltip" data-placement="right" title="enter your username" type="text" name="username" value="" id="username" placeholder="your username">

                 Password
                <input data-toggle="tooltip" data-placement="right" title="enter your password" type="password" name="password" value="" placeholder="your password" id="password">

                <input type="checkbox" value="" checked>Remember me

                <button type="submit" class="btn btn-success btn-block"> Login</button>
            </form>

            <button type="submit" class="btn btn-danger btn-default pull-left" data-dismiss="modal"> Cancel</button>

Not a member? Sign Up

{% endblock %}


text:
The following individuals have contributed code, documentation, or expertise to leather:

* `Christopher Groskopf <https://github.com/onyxfish/>`_


text:
class MenusController < ApplicationController
  before_action :set_menu, only: [:show, :edit, :update, :destroy]
  before_action :authorize_menu, except: [:index, :create, :new]

  # GET /menus
  # GET /menus.json
  def index
    @menus = Menu.all
    authorize @menus
  end

  # GET /menus/1
  # GET /menus/1.json
  def show
  end

  # GET /menus/new
  def new
    @menu = Menu.new
    authorize_menu
  end

  # GET /menus/1/edit
  def edit
  end

  # POST /menus
  # POST /menus.json
  def create
    @menu = Menu.new(menu_params)
    authorize_menu

    respond_to do |format|
      if @menu.save
        format.html { redirect_to @menu, notice: 'Menu was successfully created.' }
        format.json { render :show, status: :created, location: @menu }
      else
        format.html { render :new }
        format.json { render json: @menu.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /menus/1
  # PATCH/PUT /menus/1.json
  def update
    respond_to do |format|
      if @menu.update(menu_params)
        format.html { redirect_to @menu, notice: 'Menu was successfully updated.' }
        format.json { render :show, status: :ok, location: @menu }
      else
        format.html { render :edit }
        format.json { render json: @menu.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /menus/1
  # DELETE /menus/1.json
  def destroy
    @menu.destroy
    respond_to do |format|
      format.html { redirect_to menus_url, notice: 'Menu was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_menu
      @menu = Menu.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def menu_params
      params.require(:menu).permit(:name)
    end

    def authorize_menu
      authorize @menu
    end
end


text:
A list of awesome resources and tools

## Mock up and UI Design

- **[Balsamiq Mockups](https://balsamiq.com/products/mockups/)** powerful and simple mockup tool
- **[Precursor](https://precursorapp.com/)** Real time collaborative mockups and blackboard
- **[Unsplash](https://unsplash.com/)** Stock photos that don't suck
- **[js-sequence-diagram](http://bramp.github.io/js-sequence-diagrams/)** Sequence diagrams in javascript

## Learning

- **[Egghead](https://egghead.io/articles/gentle-introduction-to-the-react-flux-architecture)** Courses focused on web development
- **[Papers we love](https://github.com/papers-we-love/papers-we-love)** List of CS papers worth reading
- **[Neural Network Course](https://www.youtube.com/playlist?list=PL6Xpj9I5qXYEcOhn7TqghAJ6NAPrNmUBH)** from Sherbrooke University on youtube

## Generic

- **[Regexr](http://regexr.com/)** Powerful regular expression tool
- **[Socrates](http://socrates.io/)** A collaborative Markdown editor
- **[myTemp.email](https://mytemp.email/)** Reliable temporary email service


text:
<?php

	namespace vps\tools\modules\queue;

	use vps\tools\helpers\ConfigurationHelper;
	use Yii;
	use yii\base\BootstrapInterface;

	/**
	 * Class Module Queue
	 *
	 * @package vps\tools\modules\queue
	 */
	class Module extends \yii\base\Module implements BootstrapInterface
	{
		/**
		 * @var string the namespace that controller classes are in
		 */
		public $controllerNamespace = 'vps\tools\modules\queue\controllers';

		public $title = "View queue";

		/**
		 * @inheritdoc
		 */
		public function bootstrap ($app)
		{
			$app->setAliases([ '@queueViews' => __DIR__ . '/views' ]);
			$app->getUrlManager()->addRules([
				[
					'class'   => 'yii\web\UrlRule',
					'pattern' => 'queue/<action:[\w\-]+>',
					'route'   => $this->id . '/queue/<action>'
				],
                [
                    'class'   => 'yii\web\UrlRule',
                    'pattern' => 'queue-redis/<action:[\w\-]+>',
                    'route'   => $this->id . '/queue-redis/<action>'
                ],
			], false);

			// Add module I18N category.
			ConfigurationHelper::addTranslation('queue', [ 'queue' => 'queue.php' ], __DIR__ . '/messages');
		}
	}