text:
package github

import (
	"fmt"
	"github.com/google/go-github/github"
	minitesting "github.com/minishift/minishift/pkg/testing"
	minishiftos "github.com/minishift/minishift/pkg/util/os"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"testing"
)

var (
	gitHubClient = Client()
	err          error
	release      *github.RepositoryRelease
	resp         *github.Response
)

var testVersion = "v1.3.1"
var assetSet = []struct {
	binary           OpenShiftBinaryType
	os               minishiftos.OS
	version          string
	expectedAssetId  int
	expectedFilename string
}{
	{OPENSHIFT, minishiftos.LINUX, testVersion, 2489309, "openshift-origin-server-v1.3.1-dad658de7465ba8a234a4fb40b5b446a45a4cee1-linux-64bit.tar.gz"},
	{OC, minishiftos.LINUX, testVersion, 2489310, "openshift-origin-client-tools-v1.3.1-dad658de7465ba8a234a4fb40b5b446a45a4cee1-linux-64bit.tar.gz"},
	{OC, minishiftos.DARWIN, testVersion, 2586147, "openshift-origin-client-tools-v1.3.1-2748423-mac.zip"},
	{OC, minishiftos.WINDOWS, testVersion, 2489312, "openshift-origin-client-tools-v1.3.1-dad658de7465ba8a234a4fb40b5b446a45a4cee1-windows.zip"},
}

func TestGetAssetIdAndFilename(t *testing.T) {
	EnsureGitHubApiAccessTokenSet(t)

	for _, testAsset := range assetSet {
		release, resp, err = gitHubClient.Repositories.GetReleaseByTag("openshift", "origin", testAsset.version)
		if err != nil {
			t.Fatal(err, "Could not get OpenShift release")
		}
		defer func() {
			_ = resp.Body.Close()
		}()

		actualAssetID, actualFilename := getAssetIdAndFilename(testAsset.binary, testAsset.os, release)
		if actualAssetID != testAsset.expectedAssetId {
			t.Fatalf("Unexpected asset id for binary %d for OS %d. Expected %d, got %d",
				testAsset.binary, testAsset.os, testAsset.expectedAssetId, actualAssetID)
		}

		if actualFilename != testAsset.expectedFilename {
			t.Fatalf("Unexpected filename for binary %d for OS %d. Expected %s, got %s",
				testAsset.binary, testAsset.os, testAsset.expectedFilename, actualFilename)
		}
	}
}

func TestDownloadOc(t *testing.T) {
	EnsureGitHubApiAccessTokenSet(t)

	client := http.DefaultClient
	client.Transport = minitesting.NewMockRoundTripper()
	defer minitesting.ResetDefaultRoundTripper()

	testDir, err := ioutil.TempDir("", "minishift-test-")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(testDir)

	for _, testAsset := range assetSet {
		// don't test with openshift binary
		if testAsset.binary == OPENSHIFT {
			continue
		}

		err = DownloadOpenShiftReleaseBinary(testAsset.binary, testAsset.os, testAsset.version, testDir)
		if err != nil {
			t.Fatal(err)
		}

		expectedBinaryPath := filepath.Join(testDir, testAsset.binary.String())
		if testAsset.os == minishiftos.WINDOWS {
			expectedBinaryPath += ".exe"
		}
		fileInfo, err := os.Lstat(expectedBinaryPath)
		if err != nil {
			t.Fatal(err)
		}

		if runtime.GOOS != "windows" {
			expectedFilePermissions := "-rwxrwxrwx"
			if fileInfo.Mode().String() != expectedFilePermissions {
				t.Fatalf("Wrong file permisisons. Expected %s. Got %s", expectedFilePermissions, fileInfo.Mode().String())
			}
		}

		err = os.Remove(expectedBinaryPath)
		if err != nil {
			t.Fatalf("Unable to delete %s", expectedBinaryPath)
		}
	}
}

func TestInvalidVersion(t *testing.T) {
	EnsureGitHubApiAccessTokenSet(t)

	testDir, err := ioutil.TempDir("", "minishift-test-")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(testDir)

	dummyVersion := "foo"
	err = DownloadOpenShiftReleaseBinary(OPENSHIFT, minishiftos.WINDOWS, dummyVersion, testDir)
	if err == nil {
		t.Fatal("There should have been an error")
	}

	expectedErrorMessage := fmt.Sprintf("Cannot get the OpenShift release version %s", dummyVersion)
	if !strings.HasPrefix(err.Error(), expectedErrorMessage) {
		t.Fatalf("Expected error: '%s'. Got: '%s'\n", expectedErrorMessage, err.Error())
	}
}

func TestInvalidBinaryFormat(t *testing.T) {
	EnsureGitHubApiAccessTokenSet(t)

	testDir, err := ioutil.TempDir("", "minishift-test-")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(testDir)

	err = DownloadOpenShiftReleaseBinary(OPENSHIFT, minishiftos.WINDOWS, testVersion, testDir)
	if err == nil {
		t.Fatal("There should have been an error")
	}

	expectedErrorMessage := "Cannot get binary 'openshift' in version v1.3.1 for the target environment Windows"
	if err.Error() != expectedErrorMessage {
		t.Fatalf("Expected error: '%s'. Got: '%s'\n", expectedErrorMessage, err.Error())
	}
}

// See https://github.com/minishift/minishift/issues/331
func Test_Download_Oc_1_4_1(t *testing.T) {
	EnsureGitHubApiAccessTokenSet(t)

	client := http.DefaultClient
	client.Transport = minitesting.NewMockRoundTripper()
	defer minitesting.ResetDefaultRoundTripper()

	testDir, err := ioutil.TempDir("", "minishift-test-")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(testDir)

	err = DownloadOpenShiftReleaseBinary(OC, minishiftos.LINUX, "v1.4.1", testDir)
	if err != nil {
		t.Fatal(err)
	}

	expectedBinaryPath := filepath.Join(testDir, "oc")

	fileInfo, err := os.Lstat(expectedBinaryPath)
	if err != nil {
		t.Fatal(err)
	}

	if runtime.GOOS != "windows" {
		expectedFilePermissions := "-rwxrwxrwx"
		if fileInfo.Mode().String() != expectedFilePermissions {
			t.Fatalf("Wrong file permisisons. Expected %s. Got %s", expectedFilePermissions, fileInfo.Mode().String())
		}
	}

	err = os.Remove(expectedBinaryPath)
	if err != nil {
		t.Fatalf("Unable to delete %s", expectedBinaryPath)
	}
}

func EnsureGitHubApiAccessTokenSet(t *testing.T) {
	if GetGitHubApiToken() == "" {
		t.Skip("Skipping GitHub API based test, because no access token is defined in the environment.\n " +
			"To run this test check https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/ and set for example MINISHIFT_GITHUB_API_TOKEN (see github.go).")
	}
}


text:
require 'rubygems'
require 'rspec'
require 'rspec/its'
require 'awspec/version'
require 'awspec/cli'
require 'awspec/matcher'
require 'awspec/helper'
require 'awspec/ext'
require 'awspec/generator'

module Awspec
end

redpajama_set_name: RedPajamaGithub


text:
package org.vaadin.viritin;

import org.vaadin.viritinv7.ListContainer;
import org.vaadin.viritinv7.DynaBeanItem;
import com.vaadin.v7.data.Item;
import com.vaadin.v7.data.Property;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 *
 * @author Matti Tahvonen
 */
public class NestedPropertyTest {

    public static class Entity {

        static long counter = 0;

        private final Long id = counter++;
        private String property = "foo";
        private Detail detail = new Detail();
        private List<Long> numbers = Arrays.asList(1 * counter, 2 * counter,
                3 * counter);
        private List<Detail> detailList = Arrays.asList(new Detail(),
                new Detail());

        private Map<String, Integer> stringToInteger = new HashMap<>();

        public Entity() {
            stringToInteger.put("id", id.intValue());
            stringToInteger.put("foo", 69);
        }

        public List<Detail> getDetailList() {
            return detailList;
        }

        public void setDetailList(List<Detail> detailList) {
            this.detailList = detailList;
        }

        public Map<String, Integer> getStringToInteger() {
            return stringToInteger;
        }

        public void setStringToInteger(Map<String, Integer> stringToInteger) {
            this.stringToInteger = stringToInteger;
        }

        public Long getId() {
            return id;
        }

        public List<Long> getNumbers() {
            return numbers;
        }

        public void setNumbers(List<Long> numbers) {
            this.numbers = numbers;
        }

        public String getProperty() {
            return property;
        }

        public void setProperty(String property) {
            this.property = property;
        }

        public Detail getDetail() {
            return detail;
        }

        public void setDetail(Detail detail) {
            this.detail = detail;
        }

    }

    public static class Detail {

        private String property = "bar";

        private Detail2 detail2 = new Detail2();

        private List<Detail2> moreDetails = Arrays.asList(new Detail2(),
                new Detail2());
        private List nonTypedDetails = Arrays.asList(new Detail2(),
                new Detail2());

        public List getNonTypedDetails() {
            return nonTypedDetails;
        }

        public void setNonTypedDetails(List nonTypedDetails) {
            this.nonTypedDetails = nonTypedDetails;
        }

        public Detail2 getDetail2() {
            return detail2;
        }

        public void setDetail2(Detail2 detail2) {
            this.detail2 = detail2;
        }

        public List<Detail2> getMoreDetails() {
            return moreDetails;
        }

        public void setMoreDetails(List<Detail2> moreDetails) {
            this.moreDetails = moreDetails;
        }

        public String getProperty() {
            return property;
        }

        public void setProperty(String property) {
            this.property = property;
        }

    }

    public static class Detail2 {

        private Integer property = 69;

        public Integer getProperty() {
            return property;
        }

        public void setProperty(Integer property) {
            this.property = property;
        }

    }

    public NestedPropertyTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    @Test
    public void testDynaBeanItem() {

        DynaBeanItem<Entity> dynaBeanItem = new DynaBeanItem<>(
                new Entity());

        Property itemProperty = dynaBeanItem.getItemProperty("property");

        Assert.assertNotNull(itemProperty);
        Assert.assertEquals("foo", itemProperty.getValue());

        Property nestedProperty = dynaBeanItem.
                getItemProperty("detail.property");
        Assert.assertNotNull(nestedProperty);
        Assert.assertEquals("bar", nestedProperty.getValue());
        Assert.assertEquals(String.class, nestedProperty.getType());

    }

    @Test
    public void testListContainer() {

        ListContainer<Entity> listContainer = getTestListContainer();

        Entity entity = listContainer.getIdByIndex(0);
        Item dynaBeanItem = listContainer.getItem(entity);
        Property itemProperty = dynaBeanItem.getItemProperty("property");

        Assert.assertNotNull(itemProperty);
        Assert.assertEquals("foo", itemProperty.getValue());

        // Should not be reported by default...
        boolean contains = listContainer.getContainerPropertyIds().contains(
                "detail.property");
        Assert.assertFalse(contains);

        // But should be found if explicitly requested
        Property nestedProperty = dynaBeanItem.
                getItemProperty("detail.property");
        Assert.assertNotNull(nestedProperty);
        Assert.assertEquals("bar", nestedProperty.getValue());

        Assert.assertEquals(String.class, nestedProperty.getType());

        Property indexedProperty = dynaBeanItem.
                getItemProperty("numbers[2]");
        Assert.assertNotNull(indexedProperty);
        Assert.assertEquals((entity.getId() + 1) * 3l, indexedProperty.
                getValue());
        Assert.assertEquals(Long.class, indexedProperty.getType());

        Property mappedProperty = dynaBeanItem.
                getItemProperty("stringToInteger(id)");
        Assert.assertNotNull(mappedProperty);
        Assert.
                assertEquals(entity.getId().intValue(), mappedProperty.
                        getValue());
        Assert.assertEquals(Integer.class, mappedProperty.getType());

        Property thirdLevel = dynaBeanItem.
                getItemProperty("detailList[1].property");
        Assert.assertNotNull(thirdLevel);
        Assert.assertEquals("bar", thirdLevel.getValue());
        Assert.assertEquals(String.class, thirdLevel.getType());

        Property awkward = dynaBeanItem.
                getItemProperty("detailList[1].moreDetails[0]");
        Assert.assertNotNull(awkward);
        Detail2 value = (Detail2) awkward.getValue();
        Assert.assertEquals(Integer.valueOf(69), value.getProperty());
        Assert.assertEquals(Detail2.class, awkward.getType());

        Property weird = dynaBeanItem.
                getItemProperty("detailList[1].detail2.property");
        Assert.assertNotNull(weird);
        Assert.assertEquals(69, weird.getValue());
        Assert.assertEquals(Integer.class, weird.getType());

        Property weirdest = dynaBeanItem.
                getItemProperty("detailList[1].moreDetails[1].property");
        Assert.assertNotNull(weirdest);
        Assert.assertEquals(69, weirdest.getValue());
        Assert.assertEquals(Integer.class, weirdest.getType());

        Property nonTypedListItem = dynaBeanItem.
                getItemProperty("detailList[1].nonTypedDetails[0]");
        Assert.assertNotNull(weirdest);
        final Detail2 value1 = (Detail2) nonTypedListItem.getValue();

        // Is of type Detail2, but reported type should be Object
        // (can't be inspected)
        Assert.assertEquals(Integer.valueOf(69), value1.getProperty());
        Assert.assertEquals(Object.class, nonTypedListItem.getType());
    }

    public static ListContainer<Entity> getTestListContainer() {
        ListContainer<Entity> listContainer = new ListContainer<>(
                getEntities(3));
        return listContainer;
    }

    public static List<Entity> getEntities(int n) {
        ArrayList<Entity> arrayList = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            final Entity entity = new Entity();
            if(i==1) {
                entity.getDetail().property = null;
            }
            if(i==2) {
                entity.setDetail(null);
            }
            arrayList.add(entity);
        }
        return arrayList;
    }

}


text:
/*
  FCBKcomplete 1.06
  - Jquery version required: 1.2.x, 1.3.x

  Changelog:
  - 1.06 auto heigth fix
  		 event bind on main element for better user frendly experience
  		 filter for items
  		 up/down keys supported from now

  - 1.05 bindEvents function fixed thanks to idgnarn

  - 1.04 IE7  tag replace fixed

  - 1.03 IE7 & IE6 crash fixed
  		 IE7 css fixed

  - 1.02 json parsing fixed
         remove element fixed

  - 1.01: some bugs fixed

  - 1.0: migration from prototype
*/

/* Coded by: emposha <admin@emposha.com> */
/* Copyright: Emposha.com <http://www.emposha.com/> - Distributed under MIT - Keep this message! */
/*
* elem - input element id or object
* list - preadded elements
* complete - autocomplete div id or object
* ajax - url to fetch json object
* height - maximum number of element shown before scroll will apear
* usefileter - show/hide filtered items
*/

jQuery.facebooklist = function(elem, list, complete, ajax, feed, height, usefilter) {
	var feed_name = feed;
	var addHiddenInput = function(value) {
    	var input = document.createElement('input');
        $(input).attr({'type': 'hidden', 'name': (elem.attr('id')+'['+value+']'), 'id': (elem.attr('id')+'['+value+']'), 'value': value});
        return input;
  }
  var getChar = function(e) {
		if(window.event) {
			keynum = e.keyCode;
		} else if(e.which) {
  		keynum = e.which;
  	}
  	if (keynum == 8)
  		return '';

  	return String.fromCharCode(keynum);
  }
  var addItem = function(item, preadded) {
			var title = item.html().replace(//gi,'').replace(/<\/em>/gi,'');
			var value = (item.attr('val') && item.attr('val') != -1 ? item.attr('val') : title);
			var li = document.createElement('li');
			var txt = document.createTextNode(title);
			var aclose = document.createElement('a');
			var input = addHiddenInput(value);

        $(li).attr({'val': value, 'class': 'bit-box'});
        $(li).prepend(txt);
        $(aclose).attr({'class': 'closebutton','href': '#'});
        li.appendChild(aclose);
        li.appendChild(input);
        holder.appendChild(li);
        $(aclose).click(function() {
            $(this).parent('li').fadeOut('fast',function() {
                $(this).remove();
            });
            return false;
        });
        if (!preadded) {
        	holder.removeChild(document.getElementById(feed_name + '_annoninput'));
        	addInput();
        }
        $('.default').show();
        feed.hide();
    }
  var addItemFeed = function(data,input) {
		var counter = 1;
		feed.children('li[fckb=2]').remove();
    $.each(data, function(i, val) {
		  if (val.name) {
		    if (usefilter) {
				  if (val.name.indexOf(input)!= -1) {
					  var li = document.createElement('li');
						$(li).attr({'val': val.id,'fckb': '2'});
						$(li).html(val.name.replace(input, '' + input + ''));
						feed.append(li);
						counter++;
					 }
				}
			else {
				var li = document.createElement('li');
				$(li).attr({'val': val.id,'fckb': '2'});
				$(li).html(val.name.replace(input, '' + input + ''));
				feed.append(li);
				counter++;
			}
	  }
  });
		if (counter > height) {
			feed.css({'height':(height*24)+'px', 'overflow':'auto'});
		} else {
			feed.css('height','auto');
		}
  }
  var addTextItemFeed = function(value) {
		feed.children('li[fckb=1]').remove();
		var li = document.createElement('li');
		$(li).attr({'val':value,'fckb': '1'});
		$(li).html(value);
		feed.prepend(li);
  }
    //thanks to idgnarn for fix
  var bindEvents = function () {
		var nowFocusOn;
		var maininput = $('.maininput');
		feed.children('li').hover(
	      function () {
	        $(this).addClass("auto-focus");
					nowFocusOn=$(this);
	      },
	      function () {
	        $(this).removeClass("auto-focus");
					nowFocusOn=null;
	      }
	  );
    feed.children('li').unbind('click');
    feed.children('li').click(function(){
        addItem($(this));
        complete.hide();
    });
		maininput.unbind('keydown');
		maininput.keydown(function(event){
			if (event.keyCode == 13 && nowFocusOn != null) {
				addItem($(nowFocusOn));
				complete.hide();
				event.preventDefault();
			}
			if (event.keyCode == 40) {
				if (typeof(nowFocusOn) == 'undefined' || nowFocusOn.length == 0) {
					nowFocusOn = $(feed.children('li:first'));
					nowFocusOn.addClass("auto-focus");
				}
				else {
					nowFocusOn.removeClass("auto-focus");
					nowFocusOn = nowFocusOn.next('li');
					nowFocusOn.addClass("auto-focus");
				}
			}
			if (event.keyCode == 38) {
				if (typeof(nowFocusOn) == 'undefined' || nowFocusOn.length == 0) {
					nowFocusOn = $(feed.children('li:last'));
					nowFocusOn.addClass("auto-focus");
				}
				else {
					nowFocusOn.removeClass("auto-focus");
					nowFocusOn = nowFocusOn.prev('li');
					nowFocusOn.addClass("auto-focus");
				}
			}
			if (event.keyCode == 9){
				complete.hide();
			}
		});
  }
  var addInput = function () {
		var li = document.createElement('li');
		var input = document.createElement('input');
		$(li).attr({'class': 'bit-input', 'id': feed_name + '_annoninput'});
		$(input).attr({'type': 'text', 'class': 'maininput'});
		li.appendChild(input);
		holder.appendChild(li);
		$(input).focus(function() {
	    complete.fadeIn('fast');
    });
		$(holder).click(function() {
			$(input).focus();
    });
    $(input).keyup(function(event) {
			if (event.keyCode != 40 && event.keyCode != 38) {
				var etext = $(input).val();
				addTextItemFeed(etext);
				if (ajax) {
	  			$.getJSON(ajax + '?tag=' + etext, null, function(data){
		  			addItemFeed(data, etext);
			  		bindEvents();
  			  });
			  } else {
				 bindEvents();
			  }
			  $('.default').hide();
			  feed.show();
		  } else if(event.keyCode == 9){
			  complete.hide();
		  }
    });
  }
  if (typeof(elem) != 'object') elem = $(elem);
  if (typeof(list) != 'object') list = $(list);
  if (typeof(complete) != 'object') complete = $(complete);
  var feed = $(feed);
  var holder = document.createElement('ul');
  elem.css('display','none');
  $(holder).attr('class', 'holder');
  if (list && list.children('li').length) {
      $.each(list.children('li'), function(i, val) {
      	addItem($(list.children('li')[i]),1);
      });
  }
  addInput();
  elem.before(holder);
}


text:
namespace Microsoft.AspNet.SignalR.Configuration
{
    public class MessageBusOptions
    {
        public MessageBusOptions()
        {
            MessageBufferSize = 1000;
            MaxTopicsWithNoSubscriptions = 1000;
        }

        /// <summary>
        /// Gets or sets the number of messages to buffer for a specific signal.
        /// The default value is 1000.
        /// </summary>
        public int MessageBufferSize { get; set; }

        /// <summary>
        /// Gets or sets the number of topics to allow with no subscriptions
        /// </summary>
        public int MaxTopicsWithNoSubscriptions { get; set; }
    }
}


text:
define({
  "_widgetLabel": "A propos"
});


text:
using System;
using System.Collections.Generic;
using CocosSharp;

namespace tests
{
    public class LabelFNTAdditionalKerningTest : AtlasDemoNew
    {

        private const float ArrowsMax = 0.95f;
        private const float ArrowsMin = 0.7f;

		private CCSprite arrowsBar;
		private CCSprite arrows;
		private CCLabel label;
		private bool drag;

        private float arrowsWidth;
        private float arrowsWidthCenter;

        public LabelFNTAdditionalKerningTest()
        {

            Color = new CCColor3B(200, 191, 231);
            Opacity = 255;
			// Register Touch Event
			var touchListener = new CCEventListenerTouchAllAtOnce();

			touchListener.OnTouchesBegan = onTouchesBegan;
			touchListener.OnTouchesMoved = onTouchesMoved;
			touchListener.OnTouchesEnded = onTouchesEnded;

			AddEventListener(touchListener);
        }

        public override void OnEnter()
        {
            base.OnEnter();

            // ask director the the window size
            var size = VisibleBoundsWorldspace.Size;

            arrowsWidth = (ArrowsMax - ArrowsMin) * size.Width;
            arrowsWidthCenter = arrowsWidth * 0.5f;

            // create and initialize a Label
            label = new CCLabel("Test\nadditional\nkerning", "fonts/arial-unicode-26.fnt");
            label.LabelFormat.Alignment = CCTextAlignment.Center;
            label.Scale = 2;
            label.Color = CCColor3B.Red;

            arrowsBar = new CCSprite("Images/arrowsBar");
            arrows = new CCSprite("Images/arrows");
            arrows.Color = CCColor3B.Blue;

            // position the label on the center of the screen
            label.Position = size.Center;

            arrowsBar.Visible = false;

            arrowsBar.ScaleX = (arrowsWidth / arrowsBar.ContentSize.Width);

            arrowsBar.Position = new CCPoint(size.Width / 2.0f, size.Height * 0.15f + arrowsBar.ContentSize.Height * 2.0f);

            snapArrowsToEdge();

            AddChild(label);
            AddChild(arrowsBar);
            AddChild(arrows);

        }

		void onTouchesBegan(List<CCTouch> pTouches, CCEvent touchEvent)
        {
            CCTouch touch = pTouches[0];
            CCPoint location = touch.Location;

            if (arrows.BoundingBox.ContainsPoint(location))
            {
                drag = true;
                arrowsBar.Visible = true;
            }
        }

		void onTouchesEnded(List<CCTouch> pTouches, CCEvent touchEvent)
        {
            drag = false;
            snapArrowsToEdge();

            arrowsBar.Visible = false;
            UpdateAdditionalKerning();
        }

		void onTouchesMoved(List<CCTouch> pTouches, CCEvent touchEvent)
        {
            if (!drag)
            {
                return;
            }

            var touch = pTouches[0];
            var location = touch.Location;

            var left = arrowsBar.PositionX - arrowsWidthCenter;
            var right = arrowsBar.PositionX + arrowsWidthCenter;

            arrows.PositionX = Math.Max(Math.Min(location.X, right), left);
            arrows.PositionY = arrowsBar.Position.Y;

            UpdateAdditionalKerning();

        }

        private void SetPercentage (float percent)
        {
            var left = arrowsBar.PositionX - arrowsWidthCenter;
            percent /= 100f;
            left += arrowsWidth * percent;
            arrows.PositionX = Math.Max(Math.Min(left, arrowsBar.PositionX + arrowsWidth), arrowsBar.PositionX - arrowsWidth);
        }

        private void UpdateAdditionalKerning ()
        {
            var left = arrowsBar.PositionX - arrowsWidthCenter;
            var newKerning = (arrows.PositionX - left) / arrowsWidth * 100;

            label.AdditionalKerning = newKerning;
        }

        private void snapArrowsToEdge()
        {

            if (arrows.Position == CCPoint.Zero)
            {
                SetPercentage(label.AdditionalKerning);
            }
            else
            {
                arrows.PositionX = Math.Max(Math.Min(arrows.PositionX, arrowsBar.PositionX + arrowsWidthCenter), arrowsBar.PositionX - arrowsWidthCenter);
            }
            arrows.PositionY = arrowsBar.PositionY;
        }

        public override string Title
        {
            get { return "New Label - .FNT file"; }
        }

        public override string Subtitle
        {
            get
            {
                return "Testing additional kerning of label";
            }
        }
    }
}


text:
export default (data = {}) =>
  fetch(`/api/v1/job/create`, {
    headers: {
      'Content-Type': 'application/json',
    },
    credentials: 'include',
    method: 'POST',
    body: JSON.stringify(data),
  })
    .then(res => res.json())
    .catch(err => console.log(err));


text:
<!DOCTYPE html>
<html ng-app="test">
  <body>
    <gm-map-context>
      <div id="map"
           gm-map-canvas
           ng-cloak
           disable-default-ui="true"
           center="{ lat: 53.4152431, lng: -8.2390307 }"
           zoom="7"
           style="height: 400px; width: 400px;">
      </div>
      <gm-add-ons>
        <button gm-control position="LEFT_TOP" type="button" class="control1" style="margin: 10px;">Control 1</button>
      </gm-add-ons>
    </gm-map-context>

    <script src="http://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyAUG4boz_od9qa4Xbd36wXbwyYw8a8p7kM"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
    <script src="../../../src/js/directives/module.js"></script>
    <script type="text/javascript">
      angular.module("test", ["gm-google-map"])
    </script>

  </body>
</html>


text:
ENV['BOXEN_REPO_NAME'] = 'donaldpiret/our-boxen'

# Change the location of the projects
ENV['BOXEN_SRC_DIR'] = "/Users/#{ENV["USER"]}/Projects"

# Boxen binary packaging
# ENV["BOXEN_S3_ACCESS_KEY"] = ''
# ENV["BOXEN_S3_SECRET_KEY"] = ''
# ENV["BOXEN_S3_BUCKET"] = ''

# Auto-report issues on failed runs
# ENV["BOXEN_ISSUES_ENABLED"] = 'yes'

# Submit audit data to an arbitrary HTTP endpoint
# ENV["BOXEN_WEB_HOOK_URL"] = 'https://some-uri.com/boxen'
#
# required for Github Enterprise
# ENV["BOXEN_GITHUB_ENTERPRISE_URL"] = 'https://github.yourdomain.com'

# required for Github Enterprise (defaults to "https://github.com/%s")
# ENV['BOXEN_REPO_URL_TEMPLATE'] = 'https://github.yourdomain.com/%s'


text:
using UISleuth.Android.App.Tests.CanvasSelecting;
using UISleuth.Android.App.Tests.ListView;
using Xamarin.Forms;

namespace UISleuth.Android.App
{
    internal class App : Application
    {
        internal App()
        {
            MainPage = new DataSelectorPage();
            //MainPage = new StackLayoutPage();
        }
    }
}


text:
/*
++++++++++++++++++++++++++++++++++++++++++++++++++++++
AUTHOR : Vijayan PP
PROJECT : DEV Coming-Soon Page
VERSION : 1.1
++++++++++++++++++++++++++++++++++++++++++++++++++++++
*/

.themecolor
{
    color:#f17a06;/*Defines the theme color*/
}

.theme_background_color,#downloadbt:hover
{
    background-color:#f17a06; /*Defines the theme bakcground color*/
}

.borderColor
{
    border-color:#000;/*Defines the color of the border*/
}
.social a,.social-big a
{
    color:#f17a06;
}
.footer
{
    border-top-color:#f17a06;
}
.black
{
    color:#000;
}

.white
{
    color:#fff;
}
.black-background
{
    background-color:#000;
}

.white-background
{
    background-color:#fff;
}

.grey
{
    color:#676565;
}
.grey_background_color
{
    background-color:#676565;
}

.sectionTitle hr
{
  border-color:#f17a06;
}

.sectionTitle .line{
    border-color:#fff;
}

.sectionTitle .line hr
{
    border-color:#dbdbdb;
}

ol.type li a:hover{ color:#f17a06;}

.ramsh-menu.navbar-default .navbar-nav > li > a:hover,a.fa.fa-angle-down:hover,.navbar-default .navbar-nav > .active > a,.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus
{
    color:#f17a06;
}

.navbar-toggle
{

 color:#f17a06;
}

.owl-theme .owl-controls .owl-page.active span,
.owl-theme .owl-controls.clickable .owl-page:hover span,#contactbtn:hover {

	background:#f17a06;
}
.owl-theme .owl-controls .owl-page.active span{
	background:#f17a06;
}

.btn-style:hover
{
    background:#f17a06;
    color:#fff;
}

.footer .footer-social-icons li a:hover
{
    color:#f17a06;
}


text:
role :app, %w{root@server.cricketsfu.com}
role :web, %w{root@server.cricketsfu.com}
role :db,  %w{root@server.cricketsfu.com}

# Extended Server Syntax
# ======================
# This can be used to drop a more detailed server
# definition into the server list. The second argument
# something that quacks like a hash can be used to set
# extended properties on the server.
server 'server.cricketsfu.com', user: 'root', roles: %w{web app}, my_property: :my_value

# you can set custom ssh options
# it's possible to pass any option but you need to keep in mind that net/ssh understand limited list of options
# you can see them in [net/ssh documentation](http://net-ssh.github.io/net-ssh/classes/Net/SSH.html#method-c-start)
# set it globally
  set :ssh_options, {
    keys: %w(/Users/utsav01/.ssh/known_hosts),
    forward_agent: false,
    auth_methods: %w(password),
    password: '4?Uttsavisme'
  }
# and/or per server
# server 'example.com',
#   user: 'user_name',
#   roles: %w{web app},
#   ssh_options: {
#     user: 'user_name', # overrides user setting above
#     keys: %w(/home/user_name/.ssh/id_rsa),
#     forward_agent: false,
#     auth_methods: %w(publickey password)
#     # password: 'please use keys'
#   }
# setting per server overrides global ssh_options


text:
namespace ExtensionMethodsDelegatesLambdaLINQ
{
    using System;
    using System.Linq;

    class Program
    {
        static void Main()
        {
            Student[] students = new Student[]
            {
                new Student("Vasil", "Levski", 35),
                new Student("Hristo", "Botev", 28),    // (How long lived)
                new Student("Georgi", "Rakovski", 46),
                new Student("Ivan", "Vazov", 71),
                new Student("Hadji", "Dimityr", 28)
            };

            //using lambda expression
            var selectedStudents = students
                .Where(s => s.Age < 24 && s.Age > 18)
                .Select(s => new { FirstName = s.FirstName, LastName = s.LastName });

            foreach (var student in selectedStudents)
            {
                Console.WriteLine(student);

            }

            Console.WriteLine();
            //using linq query
            var selectedStudents1 = from student in students
                                    where student.Age > 18 && student.Age < 24
                                    select new { FirstName = student.FirstName, LastName = student.LastName };

            foreach (var student in selectedStudents1)
            {
                Console.WriteLine(student);

            }
        }
    }
}


text:
// Copyright 2018, Google LLC
//
// 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.

using Document = Google.Cloud.Firestore.V1Beta1.Document;
using Xunit;

namespace Google.Cloud.Firestore.Tests
{
    using Google.Cloud.ClientTesting;
    using static ProtoHelpers;

    public class DocumentChangeTest
    {
        private static readonly FirestoreDb s_db = FirestoreDb.Create("proj", "db", new FakeFirestoreClient());

        [Fact]
        public void Equality()
        {
            var snapshot = GetSampleSnapshot("doc1");

            var control = new DocumentChange(snapshot, DocumentChange.Type.Modified, 3, 2);
            EqualityTester.AssertEqual(control,
                // Distinct but equal document snapshots
                equal: new[] { new DocumentChange(GetSampleSnapshot("doc1"), DocumentChange.Type.Modified, 3, 2) },
                unequal: new[] {
                    // Different document
                    new DocumentChange(GetSampleSnapshot("doc2"), DocumentChange.Type.Modified, 3, 2),
                    // These indexes don't actually make sense for added, but it's simplest to change things independently
                    new DocumentChange(snapshot, DocumentChange.Type.Added, 3, 2),
                    new DocumentChange(snapshot, DocumentChange.Type.Modified, 4, 2),
                    new DocumentChange(snapshot, DocumentChange.Type.Modified, 3, 1),
                    new DocumentChange(snapshot, DocumentChange.Type.Modified, null, 2),
                    new DocumentChange(snapshot, DocumentChange.Type.Modified, 3, null),
                });

            // Null matching checks
            EqualityTester.AssertEqual(new DocumentChange(snapshot, DocumentChange.Type.Added, null, 2),
                equal: new[] { new DocumentChange(snapshot, DocumentChange.Type.Added, null, 2) },
                unequal: new[] { new DocumentChange(snapshot, DocumentChange.Type.Added, 0, 2) });
            EqualityTester.AssertEqual(new DocumentChange(snapshot, DocumentChange.Type.Removed, 1, null),
                equal: new[] { new DocumentChange(snapshot, DocumentChange.Type.Removed, 1, null) },
                unequal: new[] { new DocumentChange(snapshot, DocumentChange.Type.Removed, 1, 1) });
        }

        private static DocumentSnapshot GetSampleSnapshot(string docId)
        {
            var readTime = new Timestamp(10, 2);
            var proto = new Document
            {
                CreateTime = CreateProtoTimestamp(1, 10),
                UpdateTime = CreateProtoTimestamp(2, 20),
                Name = $"projects/proj/databases/db/documents/col1/{docId}",
                Fields = { ValueSerializer.SerializeMap(new { Name = docId }) }
            };
            return DocumentSnapshot.ForDocument(s_db, proto, readTime);
        }
    }
}


text:
'use strict';

// FUNCTIONS //

// PARTIAL //

/**
* FUNCTION: partial( lambda )
*	Partially applies rate parameter `lambda` and returns a function for evaluating the moment-generating function (MGF) for an exponential distribution.
*
* @param {Number} lambda - rate parameter
* @returns {Function} MGF
*/
function partial( lambda ) {

	/**
	* FUNCTION: mgf( t )
	*	Evaluates the moment-generating function (MGF) for an exponential distribution.
	*
	* @private
	* @param {Number} t - input value
	* @returns {Number} evaluated MGF
	*/
	return function mgf( t ) {
		if ( t >= lambda ) {
			return NaN;
		}
		return lambda / ( lambda - t );
	};
} // end FUNCTION partial()

// EXPORTS //

module.exports = partial;


text:
package org.hl7.types;

import java.util.Iterator;

public interface QSET<T extends QTY> extends SET<T> {
    QSET<T> union(QSET<T> otherset);

    QSET<T> except(T element);

    QSET<T> except(QSET<T> otherset);

    QSET<T> intersection(QSET<T> otherset);

    IVL<T> hull();

    IVL<T> nextTo(T element);

    IVL<T> nextAfter(T element);

    QSET<T> periodicHull(QSET<T> otherset);

    /*
     * The "interleaves" method is not implemented because it is a particular
     * challenging operation which has very little practical value besides being
     * used in an assertion about the definition of the periodic hull.
     */

    /**
     * An iterator over partitions or elements of the QSET such
     * that this QSET would be the union of the partitions.
     */
    /*
     * FIXME: this hasn't been sorted out yet. Something like this is clearly
     * needed, but it's not clear whether to return partitions or subterms.
     */
    Iterator<T> iterator();

    /**
     * @deprecated this is here only temporarily, do not use!
     */
    @Deprecated
    void setOperator(org.hl7.types.enums.SetOperator operator);

    /** @deprecated this is here only temporarily, do not use! */
    @Deprecated
    org.hl7.types.enums.SetOperator getOperator();
}


text:
case node["platform_family"]
when "rhel", "fedora"
  user = "apache"
  group = "apache"
  conf_dir = "/etc/php.d"
  pool_conf_dir = "/etc/php-fpm.d"
  conf_file = "/etc/php-fpm.conf"
  error_log = "/var/log/php-fpm/error.log"
  pid = "/var/run/php-fpm/php-fpm.pid"
else
  user = "www-data"
  group = "www-data"
  conf_dir = "/etc/php5/fpm/conf.d"
  pool_conf_dir = "/etc/php5/fpm/pool.d"
  if node.platform == "ubuntu" and node.platform_version.to_f <= 10.04
    conf_file = "/etc/php5/fpm/php5-fpm.conf"
  else
    conf_file = "/etc/php5/fpm/php-fpm.conf"
  end
  error_log = "/var/log/php5-fpm.log"
  pid ="/var/run/php5-fpm.pid"
end

default['php-fpm']['user'] = user
default['php-fpm']['group'] = group
default['php-fpm']['conf_dir'] = conf_dir
default['php-fpm']['pool_conf_dir'] = pool_conf_dir
default['php-fpm']['conf_file'] = conf_file
default['php-fpm']['pid'] = pid
default['php-fpm']['log_dir'] = '/var/log/php-fpm'
default['php-fpm']['error_log'] =  error_log
default['php-fpm']['log_level'] = "notice"
default['php-fpm']['emergency_restart_threshold'] = 0
default['php-fpm']['emergency_restart_interval'] = 0
default['php-fpm']['process_control_timeout'] = 0
default['php-fpm']['pools'] = {
  "www" => {
    :enable => true
  }
}

default['php-fpm']['skip_repository_install'] = false
default['php-fpm']['installation_action'] = :install
default['php-fpm']['version'] = nil

case node["platform_family"]
when "rhel"
  default['php-fpm']['yum_url'] = "http://rpms.famillecollet.com/enterprise/$releasever/remi/$basearch/"
  default['php-fpm']['yum_mirrorlist'] = "http://rpms.famillecollet.com/enterprise/$releasever/remi/mirror"
when "fedora"
  default['php-fpm']['skip_repository_install'] = true
end

default['php-fpm']['dotdeb_repository']['uri'] = "http://packages.dotdeb.org"
default['php-fpm']['dotdeb_repository']['key'] = "http://www.dotdeb.org/dotdeb.gpg"
default['php-fpm']['dotdeb-php53_repository']['uri'] = "http://php53.dotdeb.org"


text:
#ifndef OPENIMAGEIO_PNG_PVT_H
#define OPENIMAGEIO_PNG_PVT_H

#include <png.h>
#include <zlib.h>
#include <OpenEXR/ImathColor.h>

#include "OpenImageIO/dassert.h"
#include "OpenImageIO/typedesc.h"
#include "OpenImageIO/imageio.h"
#include "OpenImageIO/strutil.h"
#include "OpenImageIO/filesystem.h"
#include "OpenImageIO/fmath.h"
#include "OpenImageIO/sysutil.h"

#define OIIO_LIBPNG_VERSION (PNG_LIBPNG_VER_MAJOR*10000 + PNG_LIBPNG_VER_MINOR*100 + PNG_LIBPNG_VER_RELEASE)

/*
This code has been extracted from the PNG plugin so as to provide access to PNG
images embedded within any container format, without redundant code
duplication.

It's been done in the course of development of the ICO plugin in order to allow
reading and writing Vista-style PNG icons.

For further information see the following mailing list threads:
http://lists.openimageio.org/pipermail/oiio-dev-openimageio.org/2009-April/000586.html
http://lists.openimageio.org/pipermail/oiio-dev-openimageio.org/2009-April/000656.html
*/

OIIO_PLUGIN_NAMESPACE_BEGIN

#define ICC_PROFILE_ATTR "ICCProfile"

namespace PNG_pvt {

/// Initializes a PNG read struct.
/// \return empty string on success, error message on failure.
///
inline const std::string
create_read_struct (png_structp& sp, png_infop& ip)
{
    sp = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (! sp)
        return "Could not create PNG read structure";

    ip = png_create_info_struct (sp);
    if (! ip)
        return "Could not create PNG info structure";

    // Must call this setjmp in every function that does PNG reads
    if (setjmp (png_jmpbuf(sp)))
        return "PNG library error";

    // success
    return "";
}

/// Helper function - reads background colour.
///
inline bool
get_background (png_structp& sp, png_infop& ip, ImageSpec& spec,
                int& bit_depth, float *red, float *green, float *blue)
{
    if (setjmp (png_jmpbuf (sp)))
        return false;
    if (! png_get_valid (sp, ip, PNG_INFO_bKGD))
        return false;

    png_color_16p bg;
    png_get_bKGD (sp, ip, &bg);
    if (spec.format == TypeDesc::UINT16) {
        *red   = bg->red   / 65535.0;
        *green = bg->green / 65535.0;
        *blue  = bg->blue  / 65535.0;
    } else if (spec.nchannels < 3 && bit_depth < 8) {
        if (bit_depth == 1)
            *red = *green = *blue = (bg->gray ? 1 : 0);
        else if (bit_depth == 2)
            *red = *green = *blue = bg->gray / 3.0;
        else // 4 bits
            *red = *green = *blue = bg->gray / 15.0;
    } else {
        *red   = bg->red   / 255.0;
        *green = bg->green / 255.0;
        *blue  = bg->blue  / 255.0;
    }
    return true;
}

/// Read information from a PNG file and fill the ImageSpec accordingly.
///
inline void
read_info (png_structp& sp, png_infop& ip, int& bit_depth, int& color_type,
           int& interlace_type, Imath::Color3f& bg, ImageSpec& spec,
           bool keep_unassociated_alpha)
{
    png_read_info (sp, ip);

    // Auto-convert 1-, 2-, and 4- bit images to 8 bits, palette to RGB,
    // and transparency to alpha.
    png_set_expand (sp);

    // PNG files are naturally big-endian
    if (littleendian())
        png_set_swap (sp);

    png_read_update_info (sp, ip);

    png_uint_32 width, height;
    png_get_IHDR (sp, ip, &width, &height,
                  &bit_depth, &color_type, NULL, NULL, NULL);

    spec = ImageSpec ((int)width, (int)height,
                       png_get_channels (sp, ip),
                       bit_depth == 16 ? TypeDesc::UINT16 : TypeDesc::UINT8);

    spec.default_channel_names ();
    if (spec.nchannels == 2) {
        // Special case: PNG spec says 2-channel image is Gray & Alpha
        spec.channelnames[0] = "Y";
        spec.channelnames[1] = "A";
        spec.alpha_channel = 1;
    }

    int srgb_intent;
    if (png_get_sRGB (sp, ip, &srgb_intent)) {
        spec.attribute ("oiio:ColorSpace", "sRGB");
    } else {
        double gamma;
        if (png_get_gAMA (sp, ip, &gamma)) {
            spec.attribute ("oiio:Gamma", (float)(1.0f/gamma));
            spec.attribute ("oiio:ColorSpace", (gamma == 1) ? "Linear" : "GammaCorrected");
        }
    }

    if (png_get_valid(sp, ip, PNG_INFO_iCCP)) {
        png_charp profile_name = NULL;
#if OIIO_LIBPNG_VERSION > 10500   /* PNG function signatures changed */
        png_bytep profile_data = NULL;
#else
        png_charp profile_data = NULL;
#endif
        png_uint_32 profile_length = 0;
        int compression_type;
        png_get_iCCP (sp, ip, &profile_name, &compression_type,
                      &profile_data, &profile_length);
        if (profile_length && profile_data)
            spec.attribute (ICC_PROFILE_ATTR, TypeDesc(TypeDesc::UINT8, profile_length), profile_data);
    }

    png_timep mod_time;
    if (png_get_tIME (sp, ip, &mod_time)) {
        std::string date = Strutil::format ("%4d:%02d:%02d %2d:%02d:%02d",
                           mod_time->year, mod_time->month, mod_time->day,
                           mod_time->hour, mod_time->minute, mod_time->second);
        spec.attribute ("DateTime", date);
    }

    png_textp text_ptr;
    int num_comments = png_get_text (sp, ip, &text_ptr, NULL);
    if (num_comments) {
        std::string comments;
        for (int i = 0;  i < num_comments;  ++i) {
            if (Strutil::iequals (text_ptr[i].key, "Description"))
                spec.attribute ("ImageDescription", text_ptr[i].text);
            else if (Strutil::iequals (text_ptr[i].key, "Author"))
                spec.attribute ("Artist", text_ptr[i].text);
            else if (Strutil::iequals (text_ptr[i].key, "Title"))
                spec.attribute ("DocumentName", text_ptr[i].text);
            else
                spec.attribute (text_ptr[i].key, text_ptr[i].text);
        }
    }
    spec.x = png_get_x_offset_pixels (sp, ip);
    spec.y = png_get_y_offset_pixels (sp, ip);

    int unit;
    png_uint_32 resx, resy;
    if (png_get_pHYs (sp, ip, &resx, &resy, &unit)) {
        float scale = 1;
        if (unit == PNG_RESOLUTION_METER) {
            // Convert to inches, to match most other formats
            scale = 2.54 / 100.0;
            spec.attribute ("ResolutionUnit", "inch");
        } else
            spec.attribute ("ResolutionUnit", "none");
        spec.attribute ("XResolution", (float)resx*scale);
        spec.attribute ("YResolution", (float)resy*scale);
    }

    float aspect = (float)png_get_pixel_aspect_ratio (sp, ip);
    if (aspect != 0 && aspect != 1)
        spec.attribute ("PixelAspectRatio", aspect);

    float r, g, b;
    if (get_background (sp, ip, spec, bit_depth, &r, &g, &b)) {
        bg = Imath::Color3f (r, g, b);
        // FIXME -- should we do anything with the background color?
    }

    interlace_type = png_get_interlace_type (sp, ip);

    // PNG files are always "unassociated alpha" but we convert to associated
    // unless requested otherwise
    if (keep_unassociated_alpha)
        spec.attribute ("oiio:UnassociatedAlpha", (int)1);

    // FIXME -- look for an XMP packet in an iTXt chunk.
}

/// Reads from an open PNG file into the indicated buffer.
/// \return empty string on success, error message on failure.
///
inline const std::string
read_into_buffer (png_structp& sp, png_infop& ip, ImageSpec& spec,
                  int& bit_depth, int& color_type, std::vector<unsigned char>& buffer)
{
    // Must call this setjmp in every function that does PNG reads
    if (setjmp (png_jmpbuf (sp)))
        return "PNG library error";

#if 0
    // ?? This doesn't seem necessary, but I don't know why
    // Make the library handle fewer significant bits
    // png_color_8p sig_bit;
    // if (png_get_sBIT (sp, ip, &sig_bit)) {
    //        png_set_shift (sp, sig_bit);
    // }
#endif

    DASSERT (spec.scanline_bytes() == png_get_rowbytes(sp,ip));
    buffer.resize (spec.image_bytes());

    std::vector<unsigned char *> row_pointers (spec.height);
    for (int i = 0;  i < spec.height;  ++i)
        row_pointers[i] = &buffer[0] + i * spec.scanline_bytes();

    png_read_image (sp, &row_pointers[0]);
    png_read_end (sp, NULL);

    // success
    return "";
}

/// Reads the next scanline from an open PNG file into the indicated buffer.
/// \return empty string on success, error message on failure.
///
inline const std::string
read_next_scanline (png_structp& sp, void *buffer)
{
    // Must call this setjmp in every function that does PNG reads
    if (setjmp (png_jmpbuf (sp)))
        return "PNG library error";

    png_read_row (sp, (png_bytep)buffer, NULL);

    // success
    return "";
}

/// Destroys a PNG read struct.
///
inline void
destroy_read_struct (png_structp& sp, png_infop& ip)
{
    if (sp && ip) {
        png_destroy_read_struct (&sp, &ip, NULL);
        sp = NULL;
        ip = NULL;
    }
}

/// Initializes a PNG write struct.
/// \return empty string on success, C-string error message on failure.
///
inline const std::string
create_write_struct (png_structp& sp, png_infop& ip, int& color_type,
                     ImageSpec& spec)
{
    // Check for things this format doesn't support
    if (spec.width < 1 || spec.height < 1)
        return Strutil::format ("Image resolution must be at least 1x1, "
                               "you asked for %d x %d",
                               spec.width, spec.height);
    if (spec.depth < 1)
        spec.depth = 1;
    if (spec.depth > 1)
        return "PNG does not support volume images (depth > 1)";

    switch (spec.nchannels) {
    case 1 :
        color_type = PNG_COLOR_TYPE_GRAY;
        spec.alpha_channel = -1;
        break;
    case 2 :
        color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
        spec.alpha_channel = 1;
        break;
    case 3 :
        color_type = PNG_COLOR_TYPE_RGB;
        spec.alpha_channel = -1;
        break;
    case 4 :
        color_type = PNG_COLOR_TYPE_RGB_ALPHA;
        spec.alpha_channel = 3;
        break;
    default:
        return Strutil::format  ("PNG only supports 1-4 channels, not %d",
                                 spec.nchannels);
    }
    // N.B. PNG is very rigid about the meaning of the channels, so enforce
    // which channel is alpha, that's the only way PNG can do it.

    sp = png_create_write_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (! sp)
        return "Could not create PNG write structure";

    ip = png_create_info_struct (sp);
    if (! ip)
        return "Could not create PNG info structure";

    // Must call this setjmp in every function that does PNG writes
    if (setjmp (png_jmpbuf(sp)))
        return "PNG library error";

    // success
    return "";
}

/// Helper function - writes a single parameter.
///
inline bool
put_parameter (png_structp& sp, png_infop& ip, const std::string &_name,
               TypeDesc type, const void *data, std::vector<png_text>& text)
{
    std::string name = _name;

    // Things to skip
    if (Strutil::iequals(name, "planarconfig"))  // No choice for PNG files
        return false;
    if (Strutil::iequals(name, "compression"))
        return false;
    if (Strutil::iequals(name, "ResolutionUnit") ||
          Strutil::iequals(name, "XResolution") || Strutil::iequals(name, "YResolution"))
        return false;

    // Remap some names to PNG conventions
    if (Strutil::iequals(name, "Artist") && type == TypeDesc::STRING)
        name = "Author";
    if ((Strutil::iequals(name, "name") || Strutil::iequals(name, "DocumentName")) &&
          type == TypeDesc::STRING)
        name = "Title";
    if ((Strutil::iequals(name, "description") || Strutil::iequals(name, "ImageDescription")) &&
          type == TypeDesc::STRING)
        name = "Description";

    if (Strutil::iequals(name, "DateTime") && type == TypeDesc::STRING) {
        png_time mod_time;
        int year, month, day, hour, minute, second;
        if (sscanf (*(const char **)data, "%4d:%02d:%02d %2d:%02d:%02d",
                    &year, &month, &day, &hour, &minute, &second) == 6) {
            mod_time.year = year;
            mod_time.month = month;
            mod_time.day = day;
            mod_time.hour = hour;
            mod_time.minute = minute;
            mod_time.second = second;
            png_set_tIME (sp, ip, &mod_time);
            return true;
        } else {
            return false;
        }
    }

#if 0
    if (Strutil::iequals(name, "ResolutionUnit") && type == TypeDesc::STRING) {
        const char *s = *(char**)data;
        bool ok = true;
        if (Strutil::iequals (s, "none"))
            PNGSetField (m_tif, PNGTAG_RESOLUTIONUNIT, RESUNIT_NONE);
        else if (Strutil::iequals (s, "in") || Strutil::iequals (s, "inch"))
            PNGSetField (m_tif, PNGTAG_RESOLUTIONUNIT, RESUNIT_INCH);
        else if (Strutil::iequals (s, "cm"))
            PNGSetField (m_tif, PNGTAG_RESOLUTIONUNIT, RESUNIT_CENTIMETER);
        else ok = false;
        return ok;
    }
    if (Strutil::iequals(name, "ResolutionUnit") && type == TypeDesc::UINT) {
        PNGSetField (m_tif, PNGTAG_RESOLUTIONUNIT, *(unsigned int *)data);
        return true;
    }
    if (Strutil::iequals(name, "XResolution") && type == TypeDesc::FLOAT) {
        PNGSetField (m_tif, PNGTAG_XRESOLUTION, *(float *)data);
        return true;
    }
    if (Strutil::iequals(name, "YResolution") && type == TypeDesc::FLOAT) {
        PNGSetField (m_tif, PNGTAG_YRESOLUTION, *(float *)data);
        return true;
    }
#endif
    if (type == TypeDesc::STRING) {
        png_text t;
        t.compression = PNG_TEXT_COMPRESSION_NONE;
        t.key = (char *)ustring(name).c_str();
        t.text = *(char **)data;   // Already uniquified
        text.push_back (t);
    }

    return false;
}

/// Writes PNG header according to the ImageSpec.
///
inline void
write_info (png_structp& sp, png_infop& ip, int& color_type,
            ImageSpec& spec, std::vector<png_text>& text,
            bool& convert_alpha, float& gamma)
{
    // Force either 16 or 8 bit integers
    if (spec.format == TypeDesc::UINT8 || spec.format == TypeDesc::INT8)
        spec.set_format (TypeDesc::UINT8);
    else
        spec.set_format (TypeDesc::UINT16); // best precision available

    png_set_IHDR (sp, ip, spec.width, spec.height,
                  spec.format.size()*8, color_type, PNG_INTERLACE_NONE,
                  PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);

    png_set_oFFs (sp, ip, spec.x, spec.y, PNG_OFFSET_PIXEL);

    // PNG specifically dictates unassociated (un-"premultiplied") alpha
    convert_alpha = spec.alpha_channel != -1 &&
                    !spec.get_int_attribute("oiio:UnassociatedAlpha", 0);

    gamma = spec.get_float_attribute ("oiio:Gamma", 1.0);

    std::string colorspace = spec.get_string_attribute ("oiio:ColorSpace");
    if (Strutil::iequals (colorspace, "Linear")) {
        png_set_gAMA (sp, ip, 1.0);
    }
    else if (Strutil::iequals (colorspace, "GammaCorrected")) {
        png_set_gAMA (sp, ip, 1.0f/gamma);
    }
    else if (Strutil::iequals (colorspace, "sRGB")) {
        png_set_sRGB_gAMA_and_cHRM (sp, ip, PNG_sRGB_INTENT_ABSOLUTE);
    }

    // Write ICC profile, if we have anything
    const ImageIOParameter* icc_profile_parameter = spec.find_attribute(ICC_PROFILE_ATTR);
    if (icc_profile_parameter != NULL) {
        unsigned int length = icc_profile_parameter->type().size();
#if OIIO_LIBPNG_VERSION > 10500 /* PNG function signatures changed */
        unsigned char *icc_profile = (unsigned char*)icc_profile_parameter->data();
        if (icc_profile && length)
            png_set_iCCP (sp, ip, "Embedded Profile", 0, icc_profile, length);
#else
        char *icc_profile = (char*)icc_profile_parameter->data();
        if (icc_profile && length)
            png_set_iCCP (sp, ip, (png_charp)"Embedded Profile", 0, icc_profile, length);
#endif
    }

    if (false && ! spec.find_attribute("DateTime")) {
        time_t now;
        time (&now);
        struct tm mytm;
        Sysutil::get_local_time (&now, &mytm);
        std::string date = Strutil::format ("%4d:%02d:%02d %2d:%02d:%02d",
                               mytm.tm_year+1900, mytm.tm_mon+1, mytm.tm_mday,
                               mytm.tm_hour, mytm.tm_min, mytm.tm_sec);
        spec.attribute ("DateTime", date);
    }

    string_view unitname = spec.get_string_attribute ("ResolutionUnit");
    float xres = spec.get_float_attribute ("XResolution");
    float yres = spec.get_float_attribute ("YResolution");
    float paspect = spec.get_float_attribute ("PixelAspectRatio");
    if (xres || yres || paspect || unitname.size()) {
        int unittype = PNG_RESOLUTION_UNKNOWN;
        float scale = 1;
        if (Strutil::iequals (unitname, "meter") || Strutil::iequals (unitname, "m"))
            unittype = PNG_RESOLUTION_METER;
        else if (Strutil::iequals (unitname, "cm")) {
            unittype = PNG_RESOLUTION_METER;
            scale = 100;
        } else if (Strutil::iequals (unitname, "inch") || Strutil::iequals (unitname, "in")) {
            unittype = PNG_RESOLUTION_METER;
            scale = 100.0/2.54;
        }
        if (paspect) {
            // If pixel aspect is given, allow resolution to be reset
            if (xres)
                yres = 0.0f;
            else
                xres = 0.0f;
        }
        if (xres == 0.0f && yres == 0.0f) {
            xres = 100.0f;
            yres = xres * (paspect ? paspect : 1.0f);
        } else if (xres == 0.0f) {
            xres = yres / (paspect ? paspect : 1.0f);
        } else if (yres == 0.0f) {
            yres = xres * (paspect ? paspect : 1.0f);
        }
        png_set_pHYs (sp, ip, (png_uint_32)(xres*scale),
                      (png_uint_32)(yres*scale), unittype);
    }

    // Deal with all other params
    for (size_t p = 0;  p < spec.extra_attribs.size();  ++p)
        put_parameter (sp, ip,
                       spec.extra_attribs[p].name().string(),
                       spec.extra_attribs[p].type(),
                       spec.extra_attribs[p].data(),
                       text);

    if (text.size())
        png_set_text (sp, ip, &text[0], text.size());

    png_write_info (sp, ip);
    png_set_packing (sp);   // Pack 1, 2, 4 bit into bytes
}

/// Writes a scanline.
///
inline bool
write_row (png_structp& sp, png_byte *data)
{
    if (setjmp (png_jmpbuf(sp))) {
        //error ("PNG library error");
        return false;
    }
    png_write_row (sp, data);
    return true;
}

/// Helper function - finalizes writing the image.
///
inline void
finish_image (png_structp& sp)
{
    // Must call this setjmp in every function that does PNG writes
    if (setjmp (png_jmpbuf(sp))) {
        //error ("PNG library error");
        return;
    }
    png_write_end (sp, NULL);
}

/// Destroys a PNG write struct.
///
inline void
destroy_write_struct (png_structp& sp, png_infop& ip)
{
    if (sp && ip) {
        finish_image (sp);
        png_destroy_write_struct (&sp, &ip);
        sp = NULL;
        ip = NULL;
    }
}

}  // namespace PNG_pvt

OIIO_PLUGIN_NAMESPACE_END

#endif  // OPENIMAGEIO_PNG_PVT_H


text:
package com.github.tomakehurst.wiremock.client;

import com.github.tomakehurst.wiremock.admin.model.ListStubMappingsResult;
import com.github.tomakehurst.wiremock.admin.model.SingleStubMappingResult;
import com.github.tomakehurst.wiremock.common.*;
import com.github.tomakehurst.wiremock.stubbing.*;
import com.github.tomakehurst.wiremock.core.Admin;
import com.github.tomakehurst.wiremock.extension.Parameters;
import com.github.tomakehurst.wiremock.global.GlobalSettings;
import com.github.tomakehurst.wiremock.global.GlobalSettingsHolder;
import com.github.tomakehurst.wiremock.http.DelayDistribution;
import com.github.tomakehurst.wiremock.http.Request;
import com.github.tomakehurst.wiremock.http.RequestMethod;
import com.github.tomakehurst.wiremock.matching.*;
import com.github.tomakehurst.wiremock.recording.RecordSpecBuilder;
import com.github.tomakehurst.wiremock.recording.RecordingStatusResult;
import com.github.tomakehurst.wiremock.recording.SnapshotRecordResult;
import com.github.tomakehurst.wiremock.security.ClientAuthenticator;
import com.github.tomakehurst.wiremock.standalone.RemoteMappingsLoader;
import com.github.tomakehurst.wiremock.verification.*;
import com.github.tomakehurst.wiremock.verification.diff.Diff;

import java.io.File;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.github.tomakehurst.wiremock.matching.RequestPattern.thatMatch;
import static com.github.tomakehurst.wiremock.matching.RequestPatternBuilder.allRequests;
import static com.google.common.collect.FluentIterable.from;
import static com.google.common.net.HttpHeaders.CONTENT_TYPE;
import static com.google.common.net.HttpHeaders.LOCATION;

public class WireMock {

	private static final int DEFAULT_PORT = 8080;
	private static final String DEFAULT_HOST = "localhost";

	private final Admin admin;
	private final GlobalSettingsHolder globalSettingsHolder = new GlobalSettingsHolder();

	private static InheritableThreadLocal<WireMock> defaultInstance = new InheritableThreadLocal<WireMock>(){
            @Override
            protected WireMock initialValue() {
            	return WireMock.create().build();
            }
	};

	public static WireMockBuilder create() {
	    return new WireMockBuilder();
    }

    public WireMock(Admin admin) {
        this.admin = admin;
    }

    public WireMock(int port) {
        this(DEFAULT_HOST, port);
    }

    public WireMock(String host, int port) {
		admin = new HttpAdminClient(host, port);
	}

	public WireMock(String host, int port, String urlPathPrefix) {
		admin = new HttpAdminClient(host, port, urlPathPrefix);
	}

	public WireMock(String scheme, String host, int port) {
		admin = new HttpAdminClient(scheme, host, port);
	}

	public WireMock(String scheme, String host, int port, String urlPathPrefix) {
		admin = new HttpAdminClient(scheme, host, port, urlPathPrefix);
	}

    public WireMock(String scheme, String host, int port, String urlPathPrefix, String hostHeader, String proxyHost, int proxyPort, ClientAuthenticator authenticator) {
        admin = new HttpAdminClient(scheme, host, port, urlPathPrefix, hostHeader, proxyHost, proxyPort, authenticator);
    }

	public WireMock() {
		admin = new HttpAdminClient(DEFAULT_HOST, DEFAULT_PORT);
	}

	public static StubMapping givenThat(MappingBuilder mappingBuilder) {
		return defaultInstance.get().register(mappingBuilder);
	}

	public static StubMapping stubFor(MappingBuilder mappingBuilder) {
		return givenThat(mappingBuilder);
	}

	public static void editStub(MappingBuilder mappingBuilder) {
		defaultInstance.get().editStubMapping(mappingBuilder);
	}

	public static void removeStub(MappingBuilder mappingBuilder) {
		defaultInstance.get().removeStubMapping(mappingBuilder);
	}

    public static void removeStub(StubMapping stubMapping) {
        defaultInstance.get().removeStubMapping(stubMapping);
    }

    public static ListStubMappingsResult listAllStubMappings() {
        return defaultInstance.get().allStubMappings();
    }

    public static StubMapping getSingleStubMapping(UUID id) {
        return defaultInstance.get().getStubMapping(id).getItem();
    }

    public static void configureFor(int port) {
        defaultInstance.set(WireMock.create().port(port).build());
    }

	public static void configureFor(String host, int port) {
		defaultInstance.set(WireMock.create().host(host).port(port).build());
	}

	public static void configureFor(String host, int port, String urlPathPrefix) {
		defaultInstance.set(WireMock.create().host(host).port(port).urlPathPrefix(urlPathPrefix).build());
	}

	public static void configureFor(String scheme, String host, int port, String urlPathPrefix) {
		defaultInstance.set(WireMock.create().scheme(scheme).host(host).port(port).urlPathPrefix(urlPathPrefix).build());
	}

	public static void configureFor(String scheme, String host, int port) {
		defaultInstance.set(WireMock.create().scheme(scheme).host(host).port(port).build());
	}

    public static void configureFor(String scheme, String host, int port, String proxyHost, int proxyPort) {
        defaultInstance.set(WireMock.create().scheme(scheme).host(host).port(port).urlPathPrefix("").hostHeader(null).proxyHost(proxyHost).proxyPort(proxyPort).build());
    }

    public static void configureFor(WireMock client) {
	    defaultInstance.set(client);
    }

	public static void configure() {
		defaultInstance.set(WireMock.create().build());
	}

    public static StringValuePattern equalTo(String value) {
        return new EqualToPattern(value);
    }

    public static BinaryEqualToPattern binaryEqualTo(byte[] content) {
        return new BinaryEqualToPattern(content);
    }

    public static BinaryEqualToPattern binaryEqualTo(String content) {
        return new BinaryEqualToPattern(content);
    }

	public static StringValuePattern equalToIgnoreCase(String value) {
		return new EqualToPattern(value, true);
	}

    public static StringValuePattern equalToJson(String value) {
        return new EqualToJsonPattern(value, null, null);
    }

    public static StringValuePattern equalToJson(String value, boolean ignoreArrayOrder, boolean ignoreExtraElements) {
        return new EqualToJsonPattern(value, ignoreArrayOrder, ignoreExtraElements);
    }

    public static StringValuePattern matchingJsonPath(String value) {
        return new MatchesJsonPathPattern(value);
    }

    public static StringValuePattern matchingJsonPath(String value, StringValuePattern valuePattern) {
        return new MatchesJsonPathPattern(value, valuePattern);
    }

    public static EqualToXmlPattern equalToXml(String value) {
        return new EqualToXmlPattern(value);
    }

    public static EqualToXmlPattern equalToXml(String value, boolean enablePlaceholders) {
        return new EqualToXmlPattern(value, enablePlaceholders, null, null, null);
    }

    public static EqualToXmlPattern equalToXml(String value, boolean enablePlaceholders, String placeholderOpeningDelimiterRegex, String placeholderClosingDelimiterRegex) {
	    return new EqualToXmlPattern(value, enablePlaceholders, placeholderOpeningDelimiterRegex, placeholderClosingDelimiterRegex, null);
    }

    public static MatchesXPathPattern matchingXPath(String value) {
        return new MatchesXPathPattern(value, Collections.<String, String>emptyMap());
    }

    public static StringValuePattern matchingXPath(String value, Map<String, String> namespaces) {
        return new MatchesXPathPattern(value, namespaces);
    }

    public static StringValuePattern matchingXPath(String value, StringValuePattern valuePattern) {
        return new MatchesXPathPattern(value, valuePattern);
    }

    // Use this with the date/time matchers to avoid an explicit cast
    public static MatchesXPathPattern matchesXPathWithSubMatcher(String value, StringValuePattern valuePattern) {
	    return new MatchesXPathPattern(value, valuePattern);
    }

    public static StringValuePattern containing(String value) {
        return new ContainsPattern(value);
    }

    public static StringValuePattern matching(String regex) {
        return new RegexPattern(regex);
    }

    public static StringValuePattern notMatching(String regex) {
        return new NegativeRegexPattern(regex);
    }

    public static BeforeDateTimePattern before(String dateTimeSpec) {
	    return new BeforeDateTimePattern(dateTimeSpec);
    }

    public static BeforeDateTimePattern before(ZonedDateTime dateTime) {
	    return new BeforeDateTimePattern(dateTime);
    }

    public static BeforeDateTimePattern before(LocalDateTime dateTime) {
	    return new BeforeDateTimePattern(dateTime);
    }

    public static BeforeDateTimePattern beforeNow() {
	    return new BeforeDateTimePattern("now");
    }

    public static EqualToDateTimePattern equalToDateTime(String dateTimeSpec) {
	    return new EqualToDateTimePattern(dateTimeSpec);
    }

    public static EqualToDateTimePattern equalToDateTime(ZonedDateTime dateTime) {
	    return new EqualToDateTimePattern(dateTime);
    }

    public static EqualToDateTimePattern equalToDateTime(LocalDateTime dateTime) {
	    return new EqualToDateTimePattern(dateTime);
    }

    public static EqualToDateTimePattern isNow() {
        return new EqualToDateTimePattern("now");
    }

    public static AfterDateTimePattern after(String dateTimeSpec) {
        return new AfterDateTimePattern(dateTimeSpec);
    }

    public static AfterDateTimePattern after(ZonedDateTime dateTime) {
        return new AfterDateTimePattern(dateTime);
    }

    public static AfterDateTimePattern after(LocalDateTime dateTime) {
        return new AfterDateTimePattern(dateTime);
    }

    public static AfterDateTimePattern afterNow() {
        return new AfterDateTimePattern("now");
    }

    public static StringValuePattern absent() {
        return AbsentPattern.ABSENT;
    }

    public static StringValuePattern and(StringValuePattern... matchers) {
	    return new LogicalAnd(matchers);
    }

    public static StringValuePattern or(StringValuePattern... matchers) {
	    return new LogicalOr(matchers);
    }

    public void saveMappings() {
        admin.saveMappings();
    }

    public static void saveAllMappings() {
        defaultInstance.get().saveMappings();
    }

    public void removeMappings() {
        admin.resetMappings();
    }

    public static void removeAllMappings() {
        defaultInstance.get().removeMappings();
    }

	public void resetMappings() {
		admin.resetAll();
	}

	public static void reset() {
		defaultInstance.get().resetMappings();
	}

	public static void resetAllRequests() {
		defaultInstance.get().resetRequests();
	}

	public void resetRequests() {
		admin.resetRequests();
	}

	public void resetScenarios() {
		admin.resetScenarios();
	}

    public static List<Scenario> getAllScenarios() {
        return defaultInstance.get().getScenarios();
    }

    private List<Scenario> getScenarios() {
        return admin.getAllScenarios().getScenarios();
    }

    public static void resetAllScenarios() {
		defaultInstance.get().resetScenarios();
	}

    public void resetToDefaultMappings() {
        admin.resetToDefaultMappings();
    }

    public static void resetToDefault() {
        defaultInstance.get().resetToDefaultMappings();
    }

	public StubMapping register(MappingBuilder mappingBuilder) {
		StubMapping mapping = mappingBuilder.build();
		register(mapping);
		return mapping;
	}

    public void register(StubMapping mapping) {
        admin.addStubMapping(mapping);
    }

	public void editStubMapping(MappingBuilder mappingBuilder) {
		admin.editStubMapping(mappingBuilder.build());
	}

	public void removeStubMapping(MappingBuilder mappingBuilder) {
		admin.removeStubMapping(mappingBuilder.build());
	}

	public void removeStubMapping(StubMapping stubMapping) {
		admin.removeStubMapping(stubMapping);
	}

    public ListStubMappingsResult allStubMappings() {
        return admin.listAllStubMappings();
    }

    public SingleStubMappingResult getStubMapping(UUID id) {
        return admin.getStubMapping(id);
    }

    public static UrlPattern urlEqualTo(String testUrl) {
        return new UrlPattern(equalTo(testUrl), false);
    }

    public static UrlPattern urlMatching(String urlRegex) {
        return new UrlPattern(matching(urlRegex), true);
    }

    public static UrlPathPattern urlPathEqualTo(String testUrl) {
        return new UrlPathPattern(equalTo(testUrl), false);
    }

    public static UrlPathPattern urlPathMatching(String urlRegex) {
        return new UrlPathPattern(matching(urlRegex), true);
    }

    public static UrlPattern anyUrl() {
        return UrlPattern.ANY;
    }

	public static CountMatchingStrategy lessThan(int expected) {
		return new CountMatchingStrategy(CountMatchingStrategy.LESS_THAN, expected);
	}

	public static CountMatchingStrategy lessThanOrExactly(int expected) {
		return new CountMatchingStrategy(CountMatchingStrategy.LESS_THAN_OR_EQUAL, expected);
	}

	public static CountMatchingStrategy exactly(int expected) {
		return new CountMatchingStrategy(CountMatchingStrategy.EQUAL_TO, expected);
	}

	public static CountMatchingStrategy moreThanOrExactly(int expected) {
		return new CountMatchingStrategy(CountMatchingStrategy.GREATER_THAN_OR_EQUAL, expected);
	}

	public static CountMatchingStrategy moreThan(int expected) {
		return new CountMatchingStrategy(CountMatchingStrategy.GREATER_THAN, expected);
	}

	public static MappingBuilder get(UrlPattern urlPattern) {
		return new BasicMappingBuilder(RequestMethod.GET, urlPattern);
	}

	public static MappingBuilder post(UrlPattern urlPattern) {
		return new BasicMappingBuilder(RequestMethod.POST, urlPattern);
	}

	public static MappingBuilder put(UrlPattern urlPattern) {
		return new BasicMappingBuilder(RequestMethod.PUT, urlPattern);
	}

	public static MappingBuilder delete(UrlPattern urlPattern) {
		return new BasicMappingBuilder(RequestMethod.DELETE, urlPattern);
	}

	public static MappingBuilder patch(UrlPattern urlPattern) {
		return new BasicMappingBuilder(RequestMethod.PATCH, urlPattern);
	}

	public static MappingBuilder head(UrlPattern urlPattern) {
		return new BasicMappingBuilder(RequestMethod.HEAD, urlPattern);
	}

	public static MappingBuilder options(UrlPattern urlPattern) {
		return new BasicMappingBuilder(RequestMethod.OPTIONS, urlPattern);
	}

	public static MappingBuilder trace(UrlPattern urlPattern) {
		return new BasicMappingBuilder(RequestMethod.TRACE, urlPattern);
	}

	public static MappingBuilder any(UrlPattern urlPattern) {
		return new BasicMappingBuilder(RequestMethod.ANY, urlPattern);
	}

    public static MappingBuilder request(String method, UrlPattern urlPattern) {
        return new BasicMappingBuilder(RequestMethod.fromString(method), urlPattern);
    }

	public static MappingBuilder requestMatching(String customRequestMatcherName) {
		return new BasicMappingBuilder(customRequestMatcherName, Parameters.empty());
	}

	public static MappingBuilder requestMatching(String customRequestMatcherName, Parameters parameters) {
		return new BasicMappingBuilder(customRequestMatcherName, parameters);
	}

	public static MappingBuilder requestMatching(ValueMatcher<Request> requestMatcher) {
		return new BasicMappingBuilder(requestMatcher);
	}

	public static ResponseDefinitionBuilder aResponse() {
		return new ResponseDefinitionBuilder();
	}

    public static ResponseDefinitionBuilder ok() {
        return aResponse().withStatus(200);
    }

    public static ResponseDefinitionBuilder ok(String body) {
        return aResponse().withStatus(200).withBody(body);
    }

    public static ResponseDefinitionBuilder okForContentType(String contentType, String body) {
        return aResponse()
            .withStatus(200)
            .withHeader(CONTENT_TYPE, contentType)
            .withBody(body);
    }

    public static ResponseDefinitionBuilder okJson(String body) {
        return okForContentType("application/json", body);
    }

    public static ResponseDefinitionBuilder okXml(String body) {
        return okForContentType("application/xml", body);
    }

    public static ResponseDefinitionBuilder okTextXml(String body) {
        return okForContentType("text/xml", body);
    }

    public static MappingBuilder proxyAllTo(String url) {
        return any(anyUrl()).willReturn(aResponse().proxiedFrom(url));
    }

    public static MappingBuilder get(String url) {
        return get(urlEqualTo(url));
    }

    public static MappingBuilder post(String url) {
        return post(urlEqualTo(url));
    }

    public static MappingBuilder put(String url) {
        return put(urlEqualTo(url));
    }

    public static MappingBuilder delete(String url) {
        return delete(urlEqualTo(url));
    }

    public static ResponseDefinitionBuilder created() {
        return aResponse().withStatus(201);
    }

    public static ResponseDefinitionBuilder noContent() {
        return aResponse().withStatus(204);
    }

    public static ResponseDefinitionBuilder permanentRedirect(String location) {
        return aResponse().withStatus(301).withHeader(LOCATION, location);
    }

    public static ResponseDefinitionBuilder temporaryRedirect(String location) {
        return aResponse().withStatus(302).withHeader(LOCATION, location);
    }

    public static ResponseDefinitionBuilder seeOther(String location) {
        return aResponse().withStatus(303).withHeader(LOCATION, location);
    }

    public static ResponseDefinitionBuilder badRequest() {
        return aResponse().withStatus(400);
    }

    public static ResponseDefinitionBuilder badRequestEntity() {
        return aResponse().withStatus(422);
    }

    public static ResponseDefinitionBuilder unauthorized() {
        return aResponse().withStatus(401);
    }

    public static ResponseDefinitionBuilder forbidden() {
        return aResponse().withStatus(403);
    }

    public static ResponseDefinitionBuilder notFound() {
        return aResponse().withStatus(404);
    }

    public static ResponseDefinitionBuilder serverError() {
        return aResponse().withStatus(500);
    }

    public static ResponseDefinitionBuilder serviceUnavailable() {
        return aResponse().withStatus(503);
    }

    public static ResponseDefinitionBuilder status(int status) {
        return aResponse().withStatus(status);
    }

	public void verifyThat(RequestPatternBuilder requestPatternBuilder) {
		verifyThat(moreThanOrExactly(1), requestPatternBuilder);
	}

	public void verifyThat(int expectedCount, RequestPatternBuilder requestPatternBuilder) {
		verifyThat(exactly(expectedCount), requestPatternBuilder);
	}

	public void verifyThat(CountMatchingStrategy expectedCount, RequestPatternBuilder requestPatternBuilder) {
		final RequestPattern requestPattern = requestPatternBuilder.build();

		int actualCount;
		if (requestPattern.hasInlineCustomMatcher()) {
            List<LoggedRequest> requests = admin.findRequestsMatching(RequestPattern.everything()).getRequests();
            actualCount = from(requests).filter(thatMatch(requestPattern)).size();
        } else {
            VerificationResult result = admin.countRequestsMatching(requestPattern);
            result.assertRequestJournalEnabled();
            actualCount = result.getCount();
        }

        if (!expectedCount.match(actualCount)) {
            throw actualCount == 0 ?
                verificationExceptionForNearMisses(requestPatternBuilder, requestPattern) :
			    new VerificationException(requestPattern, expectedCount, actualCount);
		}
	}

    private VerificationException verificationExceptionForNearMisses(RequestPatternBuilder requestPatternBuilder, RequestPattern requestPattern) {
        List<NearMiss> nearMisses = findAllNearMissesFor(requestPatternBuilder);
        if (nearMisses.size() > 0) {
            Diff diff = new Diff(requestPattern, nearMisses.get(0).getRequest());
            return VerificationException.forUnmatchedRequestPattern(diff);
        }

        return new VerificationException(requestPattern, find(allRequests()));
    }

	public static void verify(RequestPatternBuilder requestPatternBuilder) {
		defaultInstance.get().verifyThat(requestPatternBuilder);
	}

	public static void verify(int count, RequestPatternBuilder requestPatternBuilder) {
		defaultInstance.get().verifyThat(count, requestPatternBuilder);
	}

	public static void verify(CountMatchingStrategy countMatchingStrategy, RequestPatternBuilder requestPatternBuilder) {
		defaultInstance.get().verifyThat(countMatchingStrategy, requestPatternBuilder);
	}

    public List<LoggedRequest> find(RequestPatternBuilder requestPatternBuilder) {
        FindRequestsResult result = admin.findRequestsMatching(requestPatternBuilder.build());
        result.assertRequestJournalEnabled();
        return result.getRequests();
    }

    public static List<LoggedRequest> findAll(RequestPatternBuilder requestPatternBuilder) {
        return defaultInstance.get().find(requestPatternBuilder);
    }

	public static List<ServeEvent> getAllServeEvents() {
        return defaultInstance.get().getServeEvents();
    }

    public List<ServeEvent> getServeEvents() {
        return admin.getServeEvents().getRequests();
    }

    public static void removeServeEvent(UUID eventId) {
	    defaultInstance.get().removeEvent(eventId);
    }

    public void removeEvent(UUID eventId) {
	    admin.removeServeEvent(eventId);
    }

    public List<ServeEvent> removeEvents(RequestPatternBuilder requestPatternBuilder) {
        return admin.removeServeEventsMatching(requestPatternBuilder.build()).getServeEvents();
    }

    public static List<ServeEvent> removeServeEvents(RequestPatternBuilder requestPatternBuilder) {
	    return defaultInstance.get().removeEvents(requestPatternBuilder);
    }

    public static List<ServeEvent> removeEventsByStubMetadata(StringValuePattern pattern) {
	    return defaultInstance.get().removeEventsByMetadata(pattern);
    }

    public List<ServeEvent> removeEventsByMetadata(StringValuePattern pattern) {
	    return admin.removeServeEventsForStubsMatchingMetadata(pattern).getServeEvents();
    }

    public static RequestPatternBuilder getRequestedFor(UrlPattern urlPattern) {
		return new RequestPatternBuilder(RequestMethod.GET, urlPattern);
	}

	public static RequestPatternBuilder postRequestedFor(UrlPattern urlPattern) {
		return new RequestPatternBuilder(RequestMethod.POST, urlPattern);
	}

	public static RequestPatternBuilder putRequestedFor(UrlPattern urlPattern) {
		return new RequestPatternBuilder(RequestMethod.PUT, urlPattern);
	}

	public static RequestPatternBuilder deleteRequestedFor(UrlPattern urlPattern) {
		return new RequestPatternBuilder(RequestMethod.DELETE, urlPattern);
	}

	public static RequestPatternBuilder patchRequestedFor(UrlPattern urlPattern) {
		return new RequestPatternBuilder(RequestMethod.PATCH, urlPattern);
	}

	public static RequestPatternBuilder headRequestedFor(UrlPattern urlPattern) {
		return new RequestPatternBuilder(RequestMethod.HEAD, urlPattern);
	}

	public static RequestPatternBuilder optionsRequestedFor(UrlPattern urlPattern) {
		return new RequestPatternBuilder(RequestMethod.OPTIONS, urlPattern);
	}

	public static RequestPatternBuilder traceRequestedFor(UrlPattern urlPattern) {
		return new RequestPatternBuilder(RequestMethod.TRACE, urlPattern);
	}

	public static RequestPatternBuilder anyRequestedFor(UrlPattern urlPattern) {
		return new RequestPatternBuilder(RequestMethod.ANY, urlPattern);
	}

    public static RequestPatternBuilder requestMadeFor(String customMatcherName, Parameters parameters) {
        return RequestPatternBuilder.forCustomMatcher(customMatcherName, parameters);
    }

	public static RequestPatternBuilder requestMadeFor(ValueMatcher<Request> requestMatcher) {
		return RequestPatternBuilder.forCustomMatcher(requestMatcher);
	}

	public static void setGlobalFixedDelay(int milliseconds) {
		defaultInstance.get().setGlobalFixedDelayVariable(milliseconds);
	}

	public void setGlobalFixedDelayVariable(int milliseconds) {
		GlobalSettings settings = globalSettingsHolder.get()
                .copy()
                .fixedDelay(milliseconds)
                .build();
		updateGlobalSettings(settings);
	}

	public static void setGlobalRandomDelay(DelayDistribution distribution) {
		defaultInstance.get().setGlobalRandomDelayVariable(distribution);
	}

	public void setGlobalRandomDelayVariable(DelayDistribution distribution) {
		GlobalSettings settings = globalSettingsHolder.get()
                .copy()
                .delayDistribution(distribution)
                .build();
		updateGlobalSettings(settings);
	}

	public static void updateSettings(GlobalSettings settings) {
	    defaultInstance.get().updateGlobalSettings(settings);
    }

	public void updateGlobalSettings(GlobalSettings settings) {
		globalSettingsHolder.replaceWith(settings);
		admin.updateGlobalSettings(settings);
	}

    public void shutdown() {
        admin.shutdownServer();
    }

    public static void shutdownServer() {
        defaultInstance.get().shutdown();
    }

    public static List<NearMiss> findNearMissesForAllUnmatched() {
        return defaultInstance.get().findNearMissesForAllUnmatchedRequests();
    }

    public List<NearMiss> findNearMissesForAllUnmatchedRequests() {
        FindNearMissesResult nearMissesResult = admin.findNearMissesForUnmatchedRequests();
        return nearMissesResult.getNearMisses();
    }

    public static List<LoggedRequest> findUnmatchedRequests() {
        return defaultInstance.get().findAllUnmatchedRequests();
    }

    public List<LoggedRequest> findAllUnmatchedRequests() {
        FindRequestsResult unmatchedResult = admin.findUnmatchedRequests();
        return unmatchedResult.getRequests();
    }

    public static List<NearMiss> findNearMissesFor(LoggedRequest loggedRequest) {
        return defaultInstance.get().findTopNearMissesFor(loggedRequest);
    }

    public List<NearMiss> findTopNearMissesFor(LoggedRequest loggedRequest) {
        FindNearMissesResult nearMissesResult = admin.findTopNearMissesFor(loggedRequest);
        return nearMissesResult.getNearMisses();
    }

    public static List<NearMiss> findNearMissesFor(RequestPatternBuilder requestPatternBuilder) {
        return defaultInstance.get().findAllNearMissesFor(requestPatternBuilder);
    }

    public List<NearMiss> findAllNearMissesFor(RequestPatternBuilder requestPatternBuilder) {
        FindNearMissesResult nearMissesResult = admin.findTopNearMissesFor(requestPatternBuilder.build());
        return nearMissesResult.getNearMisses();
    }

    public void loadMappingsFrom(String rootDir) {
        loadMappingsFrom(new File(rootDir));
    }

	public void loadMappingsFrom(File rootDir) {
		FileSource mappingsSource = new SingleRootFileSource(rootDir);
		new RemoteMappingsLoader(mappingsSource, this).load();
	}

    public static List<StubMapping> snapshotRecord() {
        return defaultInstance.get().takeSnapshotRecording();
    }

    public static List<StubMapping> snapshotRecord(RecordSpecBuilder spec) {
        return defaultInstance.get().takeSnapshotRecording(spec);
    }

    public List<StubMapping> takeSnapshotRecording() {
        return admin.snapshotRecord().getStubMappings();
    }

    public List<StubMapping> takeSnapshotRecording(RecordSpecBuilder spec) {
        return admin.snapshotRecord(spec.build()).getStubMappings();
    }

    public static MultipartValuePatternBuilder aMultipart() {
        return new MultipartValuePatternBuilder();
    }

    public static MultipartValuePatternBuilder aMultipart(String name) {
        return new MultipartValuePatternBuilder(name);
    }

    public static void startRecording(String targetBaseUrl) {
        defaultInstance.get().startStubRecording(targetBaseUrl);
    }

    public static void startRecording(RecordSpecBuilder spec) {
        defaultInstance.get().startStubRecording(spec);
    }

    public void startStubRecording(String targetBaseUrl) {
        admin.startRecording(targetBaseUrl);
    }

    public void startStubRecording(RecordSpecBuilder spec) {
        admin.startRecording(spec.build());
    }

    public static SnapshotRecordResult stopRecording() {
        return defaultInstance.get().stopStubRecording();
    }

    public SnapshotRecordResult stopStubRecording() {
        return admin.stopRecording();
    }

    public static RecordingStatusResult getRecordingStatus() {
        return defaultInstance.get().getStubRecordingStatus();
    }

    public RecordingStatusResult getStubRecordingStatus() {
        return admin.getRecordingStatus();
    }

    public static RecordSpecBuilder recordSpec() {
        return new RecordSpecBuilder();
    }

    public List<StubMapping> findAllStubsByMetadata(StringValuePattern pattern) {
	    return admin.findAllStubsByMetadata(pattern).getMappings();
    }

    public static List<StubMapping> findStubsByMetadata(StringValuePattern pattern) {
	    return defaultInstance.get().findAllStubsByMetadata(pattern);
    }

    public void removeStubsByMetadataPattern(StringValuePattern pattern) {
	    admin.removeStubsByMetadata(pattern);
    }

    public static void removeStubsByMetadata(StringValuePattern pattern) {
	    defaultInstance.get().removeStubsByMetadataPattern(pattern);
    }

    public void importStubMappings(StubImport stubImport) {
        admin.importStubs(stubImport);
    }

    public void importStubMappings(StubImportBuilder stubImport) {
	    importStubMappings(stubImport.build());
    }

    public static void importStubs(StubImportBuilder stubImport) {
	    importStubs(stubImport.build());
    }

    public static void importStubs(StubImport stubImport) {
        defaultInstance.get().importStubMappings(stubImport);
    }

    public GlobalSettings getGlobalSettings() {
	    return admin.getGlobalSettings().getSettings();
    }

    public static GlobalSettings getSettings() {
        return defaultInstance.get().getGlobalSettings();
    }
}


text:
import { Component, ReactNode } from "react";

interface BaseProps {
  children: (ref: any) => ReactNode;
}

export interface ObserverInterface {
  disconnect: () => void;
  observe: (element: Element, options?: { [key: string]: any }) => void;
}

export class Observer<Props extends BaseProps> extends Component<Props> {
  protected name: string = "Observer";
  protected childNode: null | Element = null;
  protected observer: null | ObserverInterface = null;

  componentDidMount() {
    if (this.childNode === null) {
      throw new Error(`${this.name} did not receive a ref`);
    }
  }

  componentWillUnmount() {
    if (this.observer !== null) {
      this.observer.disconnect();
    }
  }

  updateChildNode = (ref: Element) => {
    if (this.childNode === ref) return; // node hasn't changed

    // if there's an existing observer disconnect it
    if (this.observer !== null) {
      this.observer.disconnect();
      this.observer = null;
    }

    this.childNode = ref;

    if (this.childNode !== null) {
      this.beginObserve();
    }
  };

  beginObserve: () => void = () => {
    throw new Error("Observer has no default observation method");
  };

  render() {
    const { children }: BaseProps = this.props;
    return children(this.updateChildNode);
  }
}


text:
using System.Collections;
using UnityEngine;
namespace Zios{
	public static class BitArrayExtension{
		public static int GetInt(this BitArray bitArray){
			int[] array = new int[1];
			bitArray.CopyTo(array,0);
			return array[0];
		}
		public static bool Contains(this BitArray bitArray,int value,int start=0){
			for(int index=start;index < bitArray.Length;++index){
				bool active = bitArray[index];
				if(active && ((value | (1<<index)) == value)){
					return true;
				}
			}
			return false;
		}
		public static void Set(this BitArray bitArray,int value,int start=0){
			for(int index=start;index < bitArray.Length;++index){
				if((value | (1<<index)) == value){
					bitArray[index] = true;
				}
			}
		}
		public static void Clear(this BitArray bitArray,int value,int start=0){
			for(int index=start;index < bitArray.Length;++index){
				if((value | (1<<index)) == value){
					bitArray[index] = false;
				}
			}
		}
		public static bool Check(this BitArray bitArray,sbyte[] values){
			for(int index=0;index < values.Length;++index){
				bool state = values[index] < 0 ? false : true;
				int target = Mathf.Abs(values[index]);
				if(bitArray[target] != state){
					return false;
				}
			}
			return true;
		}
		public static bool Check(this BitArray bitArray,int value){
			int current = bitArray.GetInt();
			return (value & current) != 0;
		}
		public static bool Matches(this BitArray bitArray,int value){
			int current = bitArray.GetInt();
			return current == value;
		}
	}
}