text:
namespace sandbox {

namespace {

typedef decltype(::CreateAppContainerProfile) CreateAppContainerProfileFunc;

typedef decltype(::DeriveAppContainerSidFromAppContainerName)
    DeriveAppContainerSidFromAppContainerNameFunc;

typedef decltype(::DeleteAppContainerProfile) DeleteAppContainerProfileFunc;

typedef decltype(::GetAppContainerFolderPath) GetAppContainerFolderPathFunc;

typedef decltype(
    ::GetAppContainerRegistryLocation) GetAppContainerRegistryLocationFunc;

struct FreeSidDeleter {
  inline void operator()(void* ptr) const { ::FreeSid(ptr); }
};

bool IsValidObjectType(SE_OBJECT_TYPE object_type) {
  switch (object_type) {
    case SE_FILE_OBJECT:
    case SE_REGISTRY_KEY:
      return true;
    default:
      break;
  }
  return false;
}

bool GetGenericMappingForType(SE_OBJECT_TYPE object_type,
                              GENERIC_MAPPING* generic_mapping) {
  if (!IsValidObjectType(object_type))
    return false;
  if (object_type == SE_FILE_OBJECT) {
    generic_mapping->GenericRead = FILE_GENERIC_READ;
    generic_mapping->GenericWrite = FILE_GENERIC_WRITE;
    generic_mapping->GenericExecute = FILE_GENERIC_EXECUTE;
    generic_mapping->GenericAll = FILE_ALL_ACCESS;
  } else {
    generic_mapping->GenericRead = KEY_READ;
    generic_mapping->GenericWrite = KEY_WRITE;
    generic_mapping->GenericExecute = KEY_EXECUTE;
    generic_mapping->GenericAll = KEY_ALL_ACCESS;
  }
  return true;
}

class ScopedImpersonation {
 public:
  ScopedImpersonation(const base::win::ScopedHandle& token) {
    BOOL result = ::ImpersonateLoggedOnUser(token.Get());
    DCHECK(result);
  }

  ~ScopedImpersonation() {
    BOOL result = ::RevertToSelf();
    DCHECK(result);
  }
};

}  // namespace

// static
AppContainerProfileBase* AppContainerProfileBase::Create(
    const wchar_t* package_name,
    const wchar_t* display_name,
    const wchar_t* description) {
  static auto create_app_container_profile =
      reinterpret_cast<CreateAppContainerProfileFunc*>(GetProcAddress(
          GetModuleHandle(L"userenv"), "CreateAppContainerProfile"));
  if (!create_app_container_profile)
    return nullptr;

  PSID package_sid = nullptr;
  HRESULT hr = create_app_container_profile(
      package_name, display_name, description, nullptr, 0, &package_sid);
  if (hr == HRESULT_FROM_WIN32(ERROR_ALREADY_EXISTS))
    return Open(package_name);

  if (FAILED(hr))
    return nullptr;
  std::unique_ptr<void, FreeSidDeleter> sid_deleter(package_sid);
  return new AppContainerProfileBase(Sid(package_sid));
}

// static
AppContainerProfileBase* AppContainerProfileBase::Open(
    const wchar_t* package_name) {
  static auto derive_app_container_sid =
      reinterpret_cast<DeriveAppContainerSidFromAppContainerNameFunc*>(
          GetProcAddress(GetModuleHandle(L"userenv"),
                         "DeriveAppContainerSidFromAppContainerName"));
  if (!derive_app_container_sid)
    return nullptr;

  PSID package_sid = nullptr;
  HRESULT hr = derive_app_container_sid(package_name, &package_sid);
  if (FAILED(hr))
    return nullptr;

  std::unique_ptr<void, FreeSidDeleter> sid_deleter(package_sid);
  return new AppContainerProfileBase(Sid(package_sid));
}

// static
bool AppContainerProfileBase::Delete(const wchar_t* package_name) {
  static auto delete_app_container_profile =
      reinterpret_cast<DeleteAppContainerProfileFunc*>(GetProcAddress(
          GetModuleHandle(L"userenv"), "DeleteAppContainerProfile"));
  if (!delete_app_container_profile)
    return false;

  return SUCCEEDED(delete_app_container_profile(package_name));
}

AppContainerProfileBase::AppContainerProfileBase(const Sid& package_sid)
    : ref_count_(0),
      package_sid_(package_sid),
      enable_low_privilege_app_container_(false) {}

AppContainerProfileBase::~AppContainerProfileBase() {}

void AppContainerProfileBase::AddRef() {
  ::InterlockedIncrement(&ref_count_);
}

void AppContainerProfileBase::Release() {
  LONG ref_count = ::InterlockedDecrement(&ref_count_);
  if (ref_count == 0) {
    delete this;
  }
}

bool AppContainerProfileBase::GetRegistryLocation(
    REGSAM desired_access,
    base::win::ScopedHandle* key) {
  static GetAppContainerRegistryLocationFunc*
      get_app_container_registry_location =
          reinterpret_cast<GetAppContainerRegistryLocationFunc*>(GetProcAddress(
              GetModuleHandle(L"userenv"), "GetAppContainerRegistryLocation"));
  if (!get_app_container_registry_location)
    return false;

  base::win::ScopedHandle token;
  if (!BuildLowBoxToken(&token))
    return false;

  ScopedImpersonation impersonation(token);
  HKEY key_handle;
  if (FAILED(get_app_container_registry_location(desired_access, &key_handle)))
    return false;
  key->Set(key_handle);
  return true;
}

bool AppContainerProfileBase::GetFolderPath(base::FilePath* file_path) {
  static GetAppContainerFolderPathFunc* get_app_container_folder_path =
      reinterpret_cast<GetAppContainerFolderPathFunc*>(GetProcAddress(
          GetModuleHandle(L"userenv"), "GetAppContainerFolderPath"));
  if (!get_app_container_folder_path)
    return false;
  std::wstring sddl_str;
  if (!package_sid_.ToSddlString(&sddl_str))
    return false;
  base::win::ScopedCoMem<wchar_t> path_str;
  if (FAILED(get_app_container_folder_path(sddl_str.c_str(), &path_str)))
    return false;
  *file_path = base::FilePath(path_str.get());
  return true;
}

bool AppContainerProfileBase::GetPipePath(const wchar_t* pipe_name,
                                          base::FilePath* pipe_path) {
  std::wstring sddl_str;
  if (!package_sid_.ToSddlString(&sddl_str))
    return false;
  *pipe_path = base::FilePath(base::StringPrintf(L"\\\\.\\pipe\\%ls\\%ls",
                                                 sddl_str.c_str(), pipe_name));
  return true;
}

bool AppContainerProfileBase::AccessCheck(const wchar_t* object_name,
                                          SE_OBJECT_TYPE object_type,
                                          DWORD desired_access,
                                          DWORD* granted_access,
                                          BOOL* access_status) {
  GENERIC_MAPPING generic_mapping;
  if (!GetGenericMappingForType(object_type, &generic_mapping))
    return false;
  MapGenericMask(&desired_access, &generic_mapping);
  PSECURITY_DESCRIPTOR sd = nullptr;
  PACL dacl = nullptr;
  if (GetNamedSecurityInfo(
          object_name, object_type,
          OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
              DACL_SECURITY_INFORMATION | LABEL_SECURITY_INFORMATION,
          nullptr, nullptr, &dacl, nullptr, &sd) != ERROR_SUCCESS) {
    return false;
  }

  std::unique_ptr<void, LocalFreeDeleter> sd_ptr(sd);

  if (enable_low_privilege_app_container_) {
    Sid any_package_sid(::WinBuiltinAnyPackageSid);
    // We can't create a LPAC token directly, so modify the DACL to simulate it.
    // Set mask for ALL APPLICATION PACKAGE Sid to 0.
    for (WORD index = 0; index < dacl->AceCount; ++index) {
      PVOID temp_ace;
      if (!GetAce(dacl, index, &temp_ace))
        return false;
      PACE_HEADER header = static_cast<PACE_HEADER>(temp_ace);
      if ((header->AceType != ACCESS_ALLOWED_ACE_TYPE) &&
          (header->AceType != ACCESS_DENIED_ACE_TYPE)) {
        continue;
      }
      // Allowed and deny aces have the same underlying structure.
      PACCESS_ALLOWED_ACE ace = static_cast<PACCESS_ALLOWED_ACE>(temp_ace);
      if (!::IsValidSid(&ace->SidStart)) {
        continue;
      }
      if (::EqualSid(&ace->SidStart, any_package_sid.GetPSID())) {
        ace->Mask = 0;
      }
    }
  }

  PRIVILEGE_SET priv_set = {};
  DWORD priv_set_length = sizeof(PRIVILEGE_SET);

  base::win::ScopedHandle token;
  if (!BuildLowBoxToken(&token))
    return false;

  return !!::AccessCheck(sd, token.Get(), desired_access, &generic_mapping,
                         &priv_set, &priv_set_length, granted_access,
                         access_status);
}

bool AppContainerProfileBase::AddCapability(const wchar_t* capability_name) {
  return AddCapability(Sid::FromNamedCapability(capability_name), false);
}

bool AppContainerProfileBase::AddCapability(WellKnownCapabilities capability) {
  return AddCapability(Sid::FromKnownCapability(capability), false);
}

bool AppContainerProfileBase::AddCapabilitySddl(const wchar_t* sddl_sid) {
  return AddCapability(Sid::FromSddlString(sddl_sid), false);
}

bool AppContainerProfileBase::AddCapability(const Sid& capability_sid,
                                            bool impersonation_only) {
  if (!capability_sid.IsValid())
    return false;
  if (!impersonation_only)
    capabilities_.push_back(capability_sid);
  impersonation_capabilities_.push_back(capability_sid);
  return true;
}

bool AppContainerProfileBase::AddImpersonationCapability(
    const wchar_t* capability_name) {
  return AddCapability(Sid::FromNamedCapability(capability_name), true);
}

bool AppContainerProfileBase::AddImpersonationCapability(
    WellKnownCapabilities capability) {
  return AddCapability(Sid::FromKnownCapability(capability), true);
}

bool AppContainerProfileBase::AddImpersonationCapabilitySddl(
    const wchar_t* sddl_sid) {
  return AddCapability(Sid::FromSddlString(sddl_sid), true);
}

const std::vector<Sid>& AppContainerProfileBase::GetCapabilities() {
  return capabilities_;
}

const std::vector<Sid>&
AppContainerProfileBase::GetImpersonationCapabilities() {
  return impersonation_capabilities_;
}

Sid AppContainerProfileBase::GetPackageSid() const {
  return package_sid_;
}

void AppContainerProfileBase::SetEnableLowPrivilegeAppContainer(bool enable) {
  enable_low_privilege_app_container_ = enable;
}

bool AppContainerProfileBase::GetEnableLowPrivilegeAppContainer() {
  return enable_low_privilege_app_container_;
}

std::unique_ptr<SecurityCapabilities>
AppContainerProfileBase::GetSecurityCapabilities() {
  return std::unique_ptr<SecurityCapabilities>(
      new SecurityCapabilities(package_sid_, capabilities_));
}

bool AppContainerProfileBase::BuildLowBoxToken(base::win::ScopedHandle* token) {
  return CreateLowBoxToken(nullptr, IMPERSONATION,
                           GetSecurityCapabilities().get(), nullptr, 0,
                           token) == ERROR_SUCCESS;
}

}  // namespace sandbox


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

/**
 * @fileoverview Basic animation controls.
 *
 */
goog.provide('goog.fx.anim');
goog.provide('goog.fx.anim.Animated');

goog.require('goog.Timer');
goog.require('goog.events');
goog.require('goog.object');

/**
 * An interface for programatically animated objects. I.e. rendered in
 * javascript frame by frame.
 *
 * @interface
 */
goog.fx.anim.Animated = function() {};

/**
 * Function called when a frame is requested for the animation.
 *
 * @param {number} now Current time in milliseconds.
 */
goog.fx.anim.Animated.prototype.onAnimationFrame;

/**
 * Default wait timeout for animations (in milliseconds).  Only used for timed
 * animation, which uses a timer (setTimout) to schedule animation.
 *
 * @type {number}
 * @const
 */
goog.fx.anim.TIMEOUT = 20;

/**
 * Name of event received from the requestAnimationFrame in Firefox.
 *
 * @type {string}
 * @const
 * @private
 */
goog.fx.anim.MOZ_BEFORE_PAINT_EVENT_ = 'MozBeforePaint';

/**
 * A map of animations which should be cycled on the global timer.
 *
 * @type {Object.<number, goog.fx.anim.Animated>}
 * @private
 */
goog.fx.anim.activeAnimations_ = {};

/**
 * An optional animation window.
 * @type {Window}
 * @private
 */
goog.fx.anim.animationWindow_ = null;

/**
 * A timing control function.
 * @type {?function(?function(number))}
 * @private
 */
goog.fx.anim.requestAnimationFrameFn_ = null;

/**
 * Cancel function for timing control.
 * @type {?function(number)}
 * @private
 */
goog.fx.anim.cancelRequestAnimationFrameFn_ = null;

/**
 * An interval ID for the global timer or event handler uid.
 * @type {?number}
 * @private
 */
goog.fx.anim.animationTimer_ = null;

/**
 * Registers an animation to be cycled on the global timer.
 * @param {goog.fx.anim.Animated} animation The animation to register.
 */
goog.fx.anim.registerAnimation = function(animation) {
  var uid = goog.getUid(animation);
  if (!(uid in goog.fx.anim.activeAnimations_)) {
    goog.fx.anim.activeAnimations_[uid] = animation;
  }

  // If the timer is not already started, start it now.
  goog.fx.anim.requestAnimationTimer_();
};

/**
 * Removes an animation from the list of animations which are cycled on the
 * global timer.
 * @param {goog.fx.anim.Animated} animation The animation to unregister.
 */
goog.fx.anim.unregisterAnimation = function(animation) {
  var uid = goog.getUid(animation);
  delete goog.fx.anim.activeAnimations_[uid];

  // If a timer is running and we no longer have any active timers we stop the
  // timers.
  if (goog.object.isEmpty(goog.fx.anim.activeAnimations_)) {
    goog.fx.anim.cancelAnimationTimer_();
  }
};

/**
 * Registers an animation window. This allows usage of the timing control API
 * for animations. Note that this window must be visible, as non-visible
 * windows can potentially stop animating. This window does not necessarily
 * need to be the window inside which animation occurs, but must remain visible.
 * See: https://developer.mozilla.org/en/DOM/window.mozRequestAnimationFrame.
 *
 * @param {Window} animationWindow The window in which to animate elements.
 */
goog.fx.anim.setAnimationWindow = function(animationWindow) {
  goog.fx.anim.animationWindow_ = animationWindow;

  var hasTimer = !!goog.fx.anim.animationTimer_;
  // If a timer is currently running, reset it and restart with new functions
  // after a timeout. This is to avoid mismatching timer UIDs if we change the
  // animation window during a running animation.
  //
  // In practice this cannot happen before some animation window and timer
  // control functions has already been set.
  if (hasTimer) {
    goog.fx.anim.cancelAnimationTimer_();
  }

  if (!animationWindow) {
    goog.fx.anim.requestAnimationFrameFn_ = null;
    goog.fx.anim.cancelRequestAnimationFrameFn_ = null;
  } else {
    goog.fx.anim.requestAnimationFrameFn_ =
        animationWindow['requestAnimationFrame'] ||
        animationWindow['webkitRequestAnimationFrame'] ||
        animationWindow['mozRequestAnimationFrame'] ||
        animationWindow['oRequestAnimationFrame'] ||
        animationWindow['msRequestAnimationFrame'] ||
        null;

    goog.fx.anim.cancelRequestAnimationFrameFn_ =
        animationWindow['cancelRequestAnimationFrame'] ||
        animationWindow['webkitCancelRequestAnimationFrame'] ||
        animationWindow['mozCancelRequestAnimationFrame'] ||
        animationWindow['oCancelRequestAnimationFrame'] ||
        animationWindow['msCancelRequestAnimationFrame'] ||
        null;
  }

  // Set up matching render timing functions, the requestAnimationTimer_ and
  // cancelAnimationTimer_ functions.
  if (goog.fx.anim.requestAnimationFrameFn_ &&
      animationWindow['mozRequestAnimationFrame'] &&
      !goog.fx.anim.cancelRequestAnimationFrameFn_) {
    // Because Firefox (Gecko) runs animation in separate threads, it also saves
    // time by running the requestAnimationFrame callbacks in that same thread.
    // Sadly this breaks the assumption of implicit thread-safety in JS, and can
    // thus create thread-based inconsistencies on counters etc.
    //
    // Calling cycleAnimations_ using the MozBeforePaint event instead of as
    // callback fixes this.
    //
    // Trigger this condition only if the mozRequestAnimationFrame is available,
    // but not the W3C requestAnimationFrame function (as in draft) or the
    // equivalent cancel functions.
    goog.fx.anim.requestAnimationTimer_ =
        goog.fx.anim.requestMozAnimationFrame_;
    goog.fx.anim.cancelAnimationTimer_ = goog.fx.anim.cancelMozAnimationFrame_;
  } else if (goog.fx.anim.requestAnimationFrameFn_ &&
             goog.fx.anim.cancelRequestAnimationFrameFn_) {
    goog.fx.anim.requestAnimationTimer_ = goog.fx.anim.requestAnimationFrame_;
    goog.fx.anim.cancelAnimationTimer_ = goog.fx.anim.cancelAnimationFrame_;
  } else {
    goog.fx.anim.requestAnimationTimer_ = goog.fx.anim.requestTimer_;
    goog.fx.anim.cancelAnimationTimer_ = goog.fx.anim.cancelTimer_;
  }

  // If the timer was running, start it again.
  if (hasTimer) {
    goog.fx.anim.requestAnimationTimer_();
  }
};

/**
 * Requests a scheduled timer call.
 * @private
 */
goog.fx.anim.requestTimer_ = function() {
  if (!goog.fx.anim.animationTimer_) {
    goog.fx.anim.animationTimer_ = goog.Timer.callOnce(function() {
      goog.fx.anim.animationTimer_ = null;
      // Cycle all animations at 'the same time'.
      goog.fx.anim.cycleAnimations_(goog.now());
    }, goog.fx.anim.TIMEOUT);
  }
};

/**
 * Cancels a timer created by requestTimer_().
 * @private
 */
goog.fx.anim.cancelTimer_ = function() {
  if (goog.fx.anim.animationTimer_) {
    goog.Timer.clear(goog.fx.anim.animationTimer_);
    goog.fx.anim.animationTimer_ = null;
  }
};

/**
 * Requests an animation frame based on the requestAnimationFrame and
 * cancelRequestAnimationFrame function pair.
 * @private
 */
goog.fx.anim.requestAnimationFrame_ = function() {
  if (!goog.fx.anim.animationTimer_) {
    // requestAnimationFrame will call cycleAnimations_ with the current
    // time in ms, as returned from goog.now().
    goog.fx.anim.animationTimer_ =
        goog.fx.anim.requestAnimationFrameFn_.call(
            goog.fx.anim.animationWindow_, function(now) {
              goog.fx.anim.animationTimer_ = null;
              goog.fx.anim.cycleAnimations_(now);
            });
  }
};

/**
 * Cancels an animation frame created by requestAnimationFrame_().
 * @private
 */
goog.fx.anim.cancelAnimationFrame_ = function() {
  if (goog.fx.anim.animationTimer_) {
    goog.fx.anim.cancelRequestAnimationFrameFn_.call(
        goog.fx.anim.animationWindow_,
        goog.fx.anim.animationTimer_);
    goog.fx.anim.animationTimer_ = null;
  }
};

/**
 * Requests an animation frame based on the requestAnimationFrame and
 * cancelRequestAnimationFrame function pair.
 * @private
 */
goog.fx.anim.requestMozAnimationFrame_ = function() {
  if (!goog.fx.anim.animationTimer_) {
    goog.fx.anim.animationTimer_ = goog.events.listen(
        goog.fx.anim.animationWindow_, goog.fx.anim.MOZ_BEFORE_PAINT_EVENT_,
        function(event) {
          goog.fx.anim.cycleAnimations_(event['timeStamp'] || goog.now());
        }, false);
  }
  goog.fx.anim.requestAnimationFrameFn_.call(
      goog.fx.anim.animationWindow_, null);
};

/**
 * Cancels an animation frame created by requestAnimationFrame_().
 * @private
 */
goog.fx.anim.cancelMozAnimationFrame_ = function() {
  if (goog.fx.anim.animationTimer_) {
    goog.events.unlistenByKey(goog.fx.anim.animationTimer_);
    goog.fx.anim.animationTimer_ = null;
  }
};

/**
 * Starts the animation timer.  This is the currently active function selected
 * based on the animation window.
 * @private
 */
goog.fx.anim.requestAnimationTimer_ = goog.fx.anim.requestTimer_;

/**
 * Cancels the animation timer.  This is the currently active function selected
 * based on the animation window.
 * @private
 */
goog.fx.anim.cancelAnimationTimer_ = goog.fx.anim.cancelTimer_;

/**
 * Cycles through all registered animations.
 * @param {number} now Current time in milliseconds.
 * @private
 */
goog.fx.anim.cycleAnimations_ = function(now) {
  goog.object.forEach(goog.fx.anim.activeAnimations_, function(anim) {
    anim.onAnimationFrame(now);
  });

  if (!goog.object.isEmpty(goog.fx.anim.activeAnimations_)) {
    goog.fx.anim.requestAnimationTimer_();
  }
};

redpajama_set_name: RedPajamaGithub


text:
package zornco.reploidcraft.items;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;

public class ContainerReploidBuster extends Container
{
	/** The Item Inventory for this Container */
	public final InventoryBuster inventory;

	/** Using these will make transferStackInSlot easier to understand and implement
	 * INV_START is the index of the first slot in the Player's Inventory, so our
	 * InventoryItem's number of slots (e.g. 5 slots is array indices 0-4, so start at 5)
	 * Notice how we don't have to remember how many slots we made? We can just use
	 * InventoryItem.INV_SIZE and if we ever change it, the Container updates automatically. */
	private static final int INV_START = InventoryBuster.INV_SIZE, INV_END = INV_START+26,
			HOTBAR_START = INV_END+1, HOTBAR_END = HOTBAR_START+8;

	//If you're planning to add Buster slots, put those first like this:
	//Buster_START = InventoryItem.INV_SIZE, Buster_END = Buster_START+3,
	//INV_START = Buster_END+1, and then carry on like above.

	public ContainerReploidBuster(EntityPlayer par1Player, InventoryPlayer inventoryPlayer, InventoryBuster inventoryItem)
	{
		this.inventory = inventoryItem;

		int i;

		//ITEM INVENTORY - you'll need to adjust the slot locations to match your texture file
		//I have them set vertically in columns of 4 to the right of the player model
		for (i = 0; i < InventoryBuster.INV_SIZE; ++i)
		{
			//You can make a custom Slot if you need different behavior,
			//such as only certain item types can be put into this slot
			//We made a custom slot to prevent our inventory-storing item
			//from being stored within itself, but if you want to allow that and
			//you followed my advice at the end of the above step, then you
			//could get away with using the vanilla Slot class
			this.addSlotToContainer(new SlotItemInv(this.inventory, i, 80 + (18 * (int)(i/4)), 8 + (18*(i%4))));
		}

		//If you want, you can add Buster SLOTS here as well, but you need to
		//make a public version of SlotBuster. I won't be doing that in this tutorial.
		/*
for (i = 0; i < 4; ++i)
{
//These are the standard positions for survival inventory layout
this.addSlotToContainer(new SlotBuster(this.player, inventoryPlayer, inventoryPlayer.getSizeInventory() - 1 - i, 8, 8 + i * 18, i));
}
		 */

		//PLAYER INVENTORY - uses default locations for standard inventory texture file
		for (i = 0; i < 3; ++i)
		{
			for (int j = 0; j < 9; ++j)
			{
				this.addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, 8 + j * 18, 84 + i * 18));
			}
		}

		//PLAYER ACTION BAR - uses default locations for standard action bar texture file
		for (i = 0; i < 9; ++i)
		{
			this.addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 142));
		}
	}

	@Override
	public boolean canInteractWith(EntityPlayer player) {
		//be sure to return the inventory's isUseableByPlayer method
		//if you defined special behavior there:
		return inventory.isUseableByPlayer(player);
	}

	/**
	 * Called when a player shift-clicks on a slot. You must override this or you will crash when someone does that.
	 * Only real change we make to this is to set needsUpdate to true at the end
	 */
	public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int par2)
	{
		ItemStack itemstack = null;
		Slot slot = (Slot) this.inventorySlots.get(par2);

		if (slot != null && slot.getHasStack())
		{
			ItemStack itemstack1 = slot.getStack();
			itemstack = itemstack1.copy();

			//If item is in our custom Inventory or Buster slot
			if (par2 < INV_START)
			{
				//try to place in player inventory / action bar
				if (!this.mergeItemStack(itemstack1, INV_START, HOTBAR_END + 1, true))
				{
					return null;
				}

				slot.onSlotChange(itemstack1, itemstack);
			}
			//Item is in inventory / hotbar, try to place in custom inventory or Buster slots
			else
			{
				/* If your inventory only stores certain instances of Items,
				 * you can implement shift-clicking to your inventory like this:
//Check that the item is the right type
if (itemstack1.getItem() instanceof ItemCustom)
{
//Try to merge into your custom inventory slots
//We use 'InventoryItem.INV_SIZE' instead of INV_START just in case
//you also add Buster or other custom slots
if (!this.mergeItemStack(itemstack1, 0, InventoryItem.INV_SIZE, false))
{
return null;
}
}
//If you added Buster slots, check them here as well:
//Item being shift-clicked is Buster - try to put in Buster slot
if (itemstack1.getItem() instanceof ItemBuster)
{
int type = ((ItemBuster) itemstack1.getItem()).BusterType;
if (!this.mergeItemStack(itemstack1, Buster_START + type, Buster_START + type + 1, false))
{
return null;
}
}
				 * Otherwise, you have basically 2 choices:
				 * 1. shift-clicking between action bar and inventory
				 * 2. shift-clicking between player inventory and custom inventory
				 * I've implemented number 1:
				 */
				//item is in player's inventory, but not in action bar
				if (par2 >= INV_START && par2 < HOTBAR_START)
				{
					//place in action bar
					if (!this.mergeItemStack(itemstack1, HOTBAR_START, HOTBAR_END + 1, false))
					{
						return null;
					}
				}
				//item in action bar - place in player inventory
				else if (par2 >= HOTBAR_START && par2 < HOTBAR_END + 1)
				{
					if (!this.mergeItemStack(itemstack1, INV_START, INV_END + 1, false))
					{
						return null;
					}
				}
			}

			if (itemstack1.stackSize == 0)
			{
				slot.putStack((ItemStack) null);
			}
			else
			{
				slot.onSlotChanged();
			}

			if (itemstack1.stackSize == itemstack.stackSize)
			{
				return null;
			}

			slot.onPickupFromSlot(par1EntityPlayer, itemstack1);
		}

		return itemstack;
	}

	//NOTE: The following is necessary if you want to prevent the player from moving the item while the
	//inventory is open; if you don't and the player moves the item, the inventory will not be able to save properly
	@Override
	public ItemStack slotClick(int slot, int button, int flag, EntityPlayer player) {
		//this will prevent the player from interacting with the item that opened the inventory:
		if (slot >= 0 && getSlot(slot) != null && getSlot(slot).getStack() == player.getHeldItem()) {
			return null;
		}
		return super.slotClick(slot, button, flag, player);
	}
	/*
	 * Vanilla mergeItemStack method doesn't correctly handle inventories whose
	 * max stack size is 1 when you shift-click into the inventory.
	 * This is a modified method I wrote to handle such cases.
	 * Note you only need it if your slot / inventory's max stack size is 1
	 */
	@Override
	protected boolean mergeItemStack(ItemStack par1ItemStack, int par2, int par3, boolean par4)
	{
		boolean flag1 = false;
		int k = par2;

		if (par4)
		{
			k = par3 - 1;
		}

		Slot slot;
		ItemStack itemstack1;

		if (par1ItemStack.isStackable())
		{
			while (par1ItemStack.stackSize > 0 && (!par4 && k < par3 || par4 && k >= par2))
			{
				slot = (Slot) this.inventorySlots.get(k);
				itemstack1 = slot.getStack();

				if (itemstack1 != null && itemstack1.getItem() == par1ItemStack.getItem() && (!par1ItemStack.getHasSubtypes() || par1ItemStack.getItemDamage() == itemstack1.getItemDamage()) && ItemStack.areItemStackTagsEqual(par1ItemStack, itemstack1))
				{
					int l = itemstack1.stackSize + par1ItemStack.stackSize;

					if (l <= par1ItemStack.getMaxStackSize() && l <= slot.getSlotStackLimit())
					{
						par1ItemStack.stackSize = 0;
						itemstack1.stackSize = l;
						inventory.markDirty();
						flag1 = true;
					}
					else if (itemstack1.stackSize < par1ItemStack.getMaxStackSize() && l < slot.getSlotStackLimit())
					{
						par1ItemStack.stackSize -= par1ItemStack.getMaxStackSize() - itemstack1.stackSize;
						itemstack1.stackSize = par1ItemStack.getMaxStackSize();
						inventory.markDirty();
						flag1 = true;
					}
				}

				if (par4)
				{
					--k;
				}
				else
				{
					++k;
				}
			}
		}

		if (par1ItemStack.stackSize > 0)
		{
			if (par4)
			{
				k = par3 - 1;
			}
			else
			{
				k = par2;
			}

			while (!par4 && k < par3 || par4 && k >= par2)
			{
				slot = (Slot)this.inventorySlots.get(k);
				itemstack1 = slot.getStack();

				if (itemstack1 == null)
				{
					int l = par1ItemStack.stackSize;

					if (l <= slot.getSlotStackLimit())
					{
						slot.putStack(par1ItemStack.copy());
						par1ItemStack.stackSize = 0;
						inventory.markDirty();
						flag1 = true;
						break;
					}
					else
					{
						this.putStackInSlot(k, new ItemStack(par1ItemStack.getItem(), slot.getSlotStackLimit()));
						par1ItemStack.stackSize -= slot.getSlotStackLimit();
						inventory.markDirty();
						flag1 = true;
					}
				}

				if (par4)
				{
					--k;
				}
				else
				{
					++k;
				}
			}
		}

		return flag1;
	}

	public class SlotItemInv extends Slot
	{
		public SlotItemInv(IInventory par1iInventory, int par2, int par3, int par4)
		{
			super(par1iInventory, par2, par3, par4);
		}

		//This is the only method we need to override so that
		//we can't place our inventory-storing Item within
		//its own inventory (thus making it permanently inaccessible)
		//as well as preventing abuse of storing backpacks within backpacks
		/**
		 * Check if the stack is a valid item for this slot.
		 */
		@Override
		public boolean isItemValid(ItemStack itemstack)
		{
			//Everything returns true except an instance of our Item
			return (itemstack.getItem() instanceof ItemChip );
		}
	}
}


text:
<?php

namespace Statamic\API;

class Cache
{
    /**
     * Get the cache instance
     *
     * @return  \Illuminate\Contracts\Cache\Store
     */
    public static function cache()
    {
        return app('cache');
    }

    /**
     * Save a key to the cache
     *
     * @param string $key   Key to save under
     * @param mixed  $data  Data to cache
     * @param int    $mins  Minutes to keep in the cache (defaults to null which means forever)
     */
    public static function put($key, $data, $mins = null)
    {
        if (is_null($mins)) {
            self::cache()->forever($key, $data);
        } else {
            self::cache()->put($key, $data, $mins);
        }
    }

    /**
     * Get a key from the cache
     *
     * @param string $key      Key to retrieve
     * @param null   $default  Fallback data if the value doesn't exist
     * @return mixed
     */
    public static function get($key, $default = null)
    {
        return self::cache()->get($key, $default);
    }

    /**
     * Does a key exist in the cache?
     *
     * @param string $key      Key to retrieve
     * @return boolean
     */
    public static function has($key)
    {
        return self::cache()->has($key);
    }

    /**
     * Remove a key from the cache
     *
     * @param string $key  Key to forget
     * @return bool
     */
    public static function forget($key)
    {
        return self::cache()->forget($key);
    }

    /**
     * Clear the entire cache
     */
    public static function clear()
    {
        \Artisan::call('cache:clear');
    }
}


text:
import { UISref } from '@uirouter/react';
import { useSelector } from 'react-redux';

import { getUser } from '@waldur/workspace/selectors';

export const UserDetailsLink = ({ uuid, name }) => {
  const currentUser = useSelector(getUser);
  if (currentUser.is_staff || currentUser.is_support) {
    return (
      <UISref to="users.details" params={{ uuid }}>
        <a>{name}</a>
      </UISref>
    );
  } else {
    return name;
  }
};


text:
(function (app) {
  'use strict';

  app.registerModule('crimes', ['core']);// The core module is required for special route handling; see /core/client/config/core.client.routes
  app.registerModule('crimes.services');
  app.registerModule('crimes.routes', ['ui.router', 'core.routes', 'crimes.services']);
}(ApplicationConfiguration));


text:
using System.Collections.Generic;

namespace WebApiToTypeScript.Cmd.Mapper
{
    internal class FunctionInfo
    {
        public string Name { get; set; }
        public string ReturnType { get; set; }
        public string HttpVerb { get; set; }
        public IEnumerable<ParameterInfo> Parameters { get; set; }
    }
}


text:
package org.apache.skywalking.oap.server.library.util;

public class BooleanUtils {

    public static final int TRUE = 1;
    public static final int FALSE = 0;

    public static boolean valueToBoolean(int value) {
        if (TRUE == value) {
            return true;
        } else if (FALSE == value) {
            return false;
        } else {
            throw new RuntimeException("Boolean value error, must be 0 or 1");
        }
    }

    public static int booleanToValue(Boolean booleanValue) {
        if (booleanValue) {
            return TRUE;
        } else {
            return FALSE;
        }
    }
}


text:
/**
 * Autogenerated by Thrift Compiler (0.10.0)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package org.apache.airavata.registry.api;

@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
public class registry_apiConstants {

  public static final java.lang.String REGISTRY_API_VERSION = "0.18.0";

}


text:
'use strict';

var InputState = require('./InputState');

function getCommandHandler (surface, history, fn) {
  return function handleCommand (e) {
    surface.focus(history.inputMode);
    history.setCommandMode();

    var state = new InputState(surface, history.inputMode);
    var chunks = state.getChunks();
    var asyncHandler = {
      async: async, immediate: true
    };

    fn.call(asyncHandler, e, history.inputMode, chunks);

    if (asyncHandler.immediate) {
      done();
    }

    function async () {
      asyncHandler.immediate = false;
      return done;
    }

    function done () {
      surface.focus(history.inputMode);
      state.setChunks(chunks);
      state.restore();
    }
  };
}

module.exports = getCommandHandler;


text:
import colorsys
import random

from pynodegl_utils.misc import SceneCfg
from pynodegl_utils.tests.debug import get_debug_points

import pynodegl as ngl

_FIELDS_VERT = """
void main()
{
    ngl_out_pos = ngl_projection_matrix * ngl_modelview_matrix * vec4(ngl_position, 1.0);
    var_uvcoord = ngl_uvcoord;
}
"""

_FIELDS_FRAG = """
float in_rect(vec4 rect, vec2 pos)
{
    return (1.0 - step(pos.x, rect.x)) * step(pos.x, rect.x + rect.z) *
           (1.0 - step(pos.y, rect.y)) * step(pos.y, rect.y + rect.w);
}

%(func_definitions)s

void main()
{
    float w = 1.0;
    float h = 1.0 / float(nb_fields);
    vec3 res = %(func_calls)s;
    ngl_out_color = vec4(res, 1.0);
}
"""

_ARRAY_TPL = """
vec3 get_color_%(field_name)s(float w, float h, float x, float y)
{
    float amount = 0.0;
    int len = %(field_len)d;
    for (int i = 0; i < len; i++) {
        %(amount_code)s
    }
    return %(colors_prefix)s%(field_name)s * amount;
}
"""

_SINGLE_TPL = """
vec3 get_color_%(field_name)s(float w, float h, float x, float y)
{
    float amount = 0.0;
    %(amount_code)s
    return %(colors_prefix)s%(field_name)s * amount;
}
"""

_COMMON_INT_TPL = "amount += float(%(fields_prefix)s%(field_name)s%(vec_field)s) * %(scale)f * in_rect(rect_%(comp_id)d, var_uvcoord);"
_COMMON_FLT_TPL = "amount += %(fields_prefix)s%(field_name)s%(vec_field)s * in_rect(rect_%(comp_id)d, var_uvcoord);"

_RECT_ARRAY_TPL = "vec4 rect_%(comp_id)d = vec4(x + %(row)f * w / (%(nb_rows)f * float(len)) + float(i) * w / float(len), y + %(col)f * h / %(nb_cols)f, w / %(nb_rows)f / float(len), h / %(nb_cols)f);"
_RECT_SINGLE_TPL = "vec4 rect_%(comp_id)d = vec4(x + %(col)f * w / %(nb_cols)f, y + %(row)f * h / %(nb_rows)f, w / %(nb_cols)f, h / %(nb_rows)f);"

ANIM_DURATION = 5.0
LAYOUTS = ("std140", "std430", "uniform")

# row, col, scale
_TYPE_SPEC = dict(
    # fmt: off
    bool=     (1, 1, 1.0),
    float=    (1, 1, None),
    vec2=     (1, 2, None),
    vec3=     (1, 3, None),
    vec4=     (1, 4, None),
    mat4=     (4, 4, None),
    int=      (1, 1, 1. / 255.),
    ivec2=    (1, 2, 1. / 255.),
    ivec3=    (1, 3, 1. / 255.),
    ivec4=    (1, 4, 1. / 255.),
    uint=     (1, 1, 1. / 255.),
    uvec2=    (1, 2, 1. / 255.),
    uvec3=    (1, 3, 1. / 255.),
    uvec4=    (1, 4, 1. / 255.),
    quat_mat4=(4, 4, None),
    quat_vec4=(1, 4, None),
    color=    (1, 3, None),
    # fmt: on
)

def _get_display_glsl_func(layout, field_name, field_type, field_len=None):
    rows, cols, scale = _TYPE_SPEC[field_type]
    nb_comp = rows * cols

    is_array = field_len is not None
    tpl = _ARRAY_TPL if is_array else _SINGLE_TPL
    rect_tpl = _RECT_ARRAY_TPL if is_array else _RECT_SINGLE_TPL
    amount_tpl = _COMMON_INT_TPL if scale is not None else _COMMON_FLT_TPL

    tpl_data = dict(
        colors_prefix="color_" if layout == "uniform" else "colors.",
        fields_prefix="field_" if layout == "uniform" else "fields.",
        field_name=field_name,
        field_len=field_len,
        nb_comp=nb_comp,
        scale=scale if scale is not None else 1.0,
        nb_cols=cols,
        nb_rows=rows,
    )

    rect_lines = []
    amount_lines = []
    for row in range(rows):
        for col in range(cols):
            comp_id = row * cols + col

            tpl_data["col"] = col
            tpl_data["row"] = row

            if nb_comp == 16:
                tpl_data["vec_field"] = "[%d][%d]" % (col, row)
            elif nb_comp >= 1 and nb_comp <= 4:
                tpl_data["vec_field"] = "." + "xyzw"[comp_id] if nb_comp != 1 else ""
            else:
                assert False

            if is_array:
                tpl_data["vec_field"] = "[i]" + tpl_data["vec_field"]

            tpl_data["comp_id"] = comp_id
            rect_lines.append(rect_tpl % tpl_data)
            amount_lines.append(amount_tpl % tpl_data)

    tpl_data["amount_code"] = ("\n" + (1 + is_array) * 4 * " ").join(rect_lines + amount_lines)

    return tpl % tpl_data

def _get_debug_point(rect):
    xpos = rect[0] + rect[2] / 2.0
    ypos = rect[1] + rect[3] / 2.0
    xpos = xpos * 2.0 - 1
    ypos = ypos * 2.0 - 1
    return xpos, ypos

def get_data_debug_positions(fields):
    debug_points = {}
    for i, field in enumerate(fields):
        array_len = field.get("len")
        nb_rows, nb_cols, _ = _TYPE_SPEC[field["type"]]

        name = field["name"]
        comp_id = 0

        w = 1.0
        h = 1.0 / float(len(fields))
        x = 0.0
        y = float(i) * h

        if array_len is None:
            for row in range(nb_rows):
                for col in range(nb_cols):
                    rect = (
                        x + col * w / float(nb_cols),
                        y + row * h / float(nb_rows),
                        w / float(nb_cols),
                        h / float(nb_rows),
                    )
                    debug_points[f"{name}_{comp_id}"] = _get_debug_point(rect)
                    comp_id += 1

        else:
            for i in range(array_len):
                for row in range(nb_rows):
                    for col in range(nb_cols):
                        rect = (
                            x + row * w / (nb_rows * array_len) + i * w / float(array_len),
                            y + col * h / float(nb_cols),
                            w / float(nb_rows) / float(array_len),
                            h / float(nb_cols),
                        )
                        debug_points[f"{name}_{comp_id}"] = _get_debug_point(rect)
                        comp_id += 1

    return debug_points

def match_fields(fields, category, field_type):
    target = (category, field_type)
    return [f for f in fields if (f["category"], f["type"]) == target]

def gen_floats(n):
    return [(i + 0.5) / float(n) for i in range(n)]

def gen_ints(n):
    return [int(i * 256) for i in gen_floats(n)]

def _get_anim_kf(key_cls, data):
    t0, t1, t2 = 0, ANIM_DURATION / 2.0, ANIM_DURATION
    if data is None:
        _, v1, v2, _ = gen_floats(4)
        return [key_cls(t0, v1), key_cls(t1, v2), key_cls(t2, v1)]
    return [
        key_cls(t0, data),
        key_cls(t1, data[::-1]),
        key_cls(t2, data),
    ]

_FUNCS = dict(
    # fmt: off
    animated_float=       lambda data: ngl.AnimatedFloat(keyframes=_get_anim_kf(ngl.AnimKeyFrameFloat, data)),
    animated_vec2=        lambda data: ngl.AnimatedVec2(keyframes=_get_anim_kf(ngl.AnimKeyFrameVec2, data)),
    animated_vec3=        lambda data: ngl.AnimatedVec3(keyframes=_get_anim_kf(ngl.AnimKeyFrameVec3, data)),
    animated_vec4=        lambda data: ngl.AnimatedVec4(keyframes=_get_anim_kf(ngl.AnimKeyFrameVec4, data)),
    animated_buffer_float=lambda data: ngl.AnimatedBufferFloat(keyframes=_get_anim_kf(ngl.AnimKeyFrameBuffer, data)),
    animated_buffer_vec2= lambda data: ngl.AnimatedBufferVec2(keyframes=_get_anim_kf(ngl.AnimKeyFrameBuffer, data)),
    animated_buffer_vec3= lambda data: ngl.AnimatedBufferVec3(keyframes=_get_anim_kf(ngl.AnimKeyFrameBuffer, data)),
    animated_buffer_vec4= lambda data: ngl.AnimatedBufferVec4(keyframes=_get_anim_kf(ngl.AnimKeyFrameBuffer, data)),
    animated_quat_mat4=   lambda data: ngl.AnimatedQuat(keyframes=_get_anim_kf(ngl.AnimKeyFrameQuat, data), as_mat4=True),
    animated_quat_vec4=   lambda data: ngl.AnimatedQuat(keyframes=_get_anim_kf(ngl.AnimKeyFrameQuat, data), as_mat4=False),
    array_float=          lambda data: ngl.BufferFloat(data=data),
    array_int=            lambda data: ngl.BufferInt(data=data),
    array_ivec2=          lambda data: ngl.BufferIVec2(data=data),
    array_ivec3=          lambda data: ngl.BufferIVec3(data=data),
    array_ivec4=          lambda data: ngl.BufferIVec4(data=data),
    array_mat4=           lambda data: ngl.BufferMat4(data=data),
    array_vec2=           lambda data: ngl.BufferVec2(data=data),
    array_vec3=           lambda data: ngl.BufferVec3(data=data),
    array_vec4=           lambda data: ngl.BufferVec4(data=data),
    single_bool=          lambda data: ngl.UniformBool(data),
    single_float=         lambda data: ngl.UniformFloat(data),
    single_int=           lambda data: ngl.UniformInt(data),
    single_ivec2=         lambda data: ngl.UniformIVec2(data),
    single_ivec3=         lambda data: ngl.UniformIVec3(data),
    single_ivec4=         lambda data: ngl.UniformIVec4(data),
    single_uint=          lambda data: ngl.UniformUInt(data),
    single_uvec2=         lambda data: ngl.UniformUIVec2(data),
    single_uvec3=         lambda data: ngl.UniformUIVec3(data),
    single_uvec4=         lambda data: ngl.UniformUIVec4(data),
    single_mat4=          lambda data: ngl.UniformMat4(data),
    single_quat_mat4=     lambda data: ngl.UniformQuat(data, as_mat4=True),
    single_quat_vec4=     lambda data: ngl.UniformQuat(data, as_mat4=False),
    single_vec2=          lambda data: ngl.UniformVec2(data),
    single_vec3=          lambda data: ngl.UniformVec3(data),
    single_vec4=          lambda data: ngl.UniformVec4(data),
    # fmt: on
)

def get_field_scene(cfg: SceneCfg, spec, category, field_type, seed, debug_positions, layout, color_tint):
    """
    Build a scene testing that a given data has been properly uploaded to the
    GPU memory.

    - `spec` contains all the fields that should also be declared (either in a
      block or as uniforms). All the fields are shuffled such that the field we
      are testing is always in a random position. This makes sure that we get
      the data alignment right.
    - `category` and `field_type` are filters in the spec to select the
      field(s) from which we want to read the data
    - `seed` is used to control the fields shuffling
    - `debug_positions` controls whether there are debug circles in the scene
      in order to make sure we are reading back the data colors at the
      appropriate position
    - `layout` controls the block layout or whether we are working with uniforms
    - `color_tint` is a debug helper to give a different color for each field
      (because if they have the same data, it is hard to indiscriminate them).
    """

    cfg.aspect_ratio = (1, 1)

    # Seed only defines the random for the position of the fields
    fields_pos = random.Random(seed).sample(range(len(spec)), len(spec))

    # Always the same colors whatever the user seed
    clr_rng = random.Random(0)

    fields_info = []
    for i, field_info in enumerate(spec):
        create_func = field_info.get("func")
        if create_func is None:
            create_func = _FUNCS["{category}_{type}".format(**field_info)]
        node = create_func(field_info.get("data"))
        node.set_label(field_info["name"])
        field_info["node"] = node
        if color_tint:
            hue = clr_rng.uniform(0, 1)
            field_info["color"] = colorsys.hls_to_rgb(hue, 0.6, 1.0)
        else:
            field_info["color"] = (1, 1, 1)
        fields_info.append(field_info)

    fields = match_fields(fields_info, category, field_type)

    func_calls = []
    func_definitions = []
    for i, field in enumerate(fields):
        field_len = field.get("len")
        func_calls.append("get_color_{}(w, h, 0.0, {:f} * h)".format(field["name"], i))
        func_definitions.append(_get_display_glsl_func(layout, field["name"], field["type"], field_len=field_len))

    frag_data = dict(
        func_definitions="\n".join(func_definitions),
        func_calls=" + ".join(func_calls),
    )

    fragment = _FIELDS_FRAG % frag_data
    vertex = _FIELDS_VERT

    program = ngl.Program(vertex=vertex, fragment=fragment)
    program.update_vert_out_vars(var_uvcoord=ngl.IOVec2())
    quad = ngl.Quad((-1, -1, 0), (2, 0, 0), (0, 2, 0))
    render = ngl.Render(quad, program)

    shuf_fields = [fields_info[pos] for pos in fields_pos]
    color_fields = [(f["name"], ngl.UniformVec3(f["color"], label=f["name"])) for f in fields_info]
    block_fields = [(f["name"], f["node"]) for f in shuf_fields]
    if layout == "uniform":
        color_fields = dict(color_fields)
        block_fields = dict(block_fields)
        field_names = {f["name"] for f in fields}
        d = {}
        d.update(("color_" + n, u) for (n, u) in color_fields.items() if n in field_names)
        d.update(("field_" + n, u) for (n, u) in block_fields.items() if n in field_names)
        render.update_frag_resources(**d)
    else:
        color_fields = ngl.Block(fields=[f for _, f in color_fields], layout=layout, label="colors_block")
        block_fields = ngl.Block(fields=[f for _, f in block_fields], layout=layout, label="fields_block")
        render.update_frag_resources(fields=block_fields, colors=color_fields)

    render.update_frag_resources(nb_fields=ngl.UniformInt(len(fields)))

    if debug_positions:
        debug_points = get_data_debug_positions(fields)
        dbg_circles = get_debug_points(cfg, debug_points, text_size=(0.2, 0.1))
        g = ngl.Group(children=(render, dbg_circles))
        return g

    return render


text:
package com.brownfield.pss.client;

public class Flight {

  	long id;

	String flightNumber;
	String origin;
	String destination;
	String flightDate;

 	Fares fares;

	public Flight() {
		super();
	}

	public Flight(String flightNumber, String origin, String destination, String flightDate, Fares fares) {
		super();
		this.flightNumber = flightNumber;
		this.origin = origin;
		this.destination = destination;
		this.flightDate = flightDate;
		this.fares = fares;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getFlightNumber() {
		return flightNumber;
	}

	public void setFlightNumber(String flightNumber) {
		this.flightNumber = flightNumber;
	}

	public String getOrigin() {
		return origin;
	}

	public void setOrigin(String origin) {
		this.origin = origin;
	}

	public String getDestination() {
		return destination;
	}

	public void setDestination(String destination) {
		this.destination = destination;
	}

	public String getFlightDate() {
		return flightDate;
	}

	public void setFlightDate(String flightDate) {
		this.flightDate = flightDate;
	}
	public Fares getFares() {
		return fares;
	}

	public void setFares(Fares fares) {
		this.fares = fares;
	}

	@Override
	public String toString() {
		return "Flight [id=" + id + ", flightNUmber=" + flightNumber + ", origin=" + origin + ", destination="
				+ destination + ", flightDate=" + flightDate + ", fares=" + fares + "]";
	}

}


text:
/*
	@file infared.c
	@brief Using the ADC driver with an infared sensor.
	@author B. Brown (bbrown1867@gmail.com)
*/

// Includes
#include "../inc/pwm.h"
#include "../inc/serial.h"
#include <util/delay.h>
#include <stdio.h>

// Defines
#define ADC_INPUT_PIN 4
#define ADC_PRESCALER 128
#define BUFFER_SIZE 32

// Globals
static uint16_t adc_result;
static char buffer[BUFFER_SIZE];

int main(void)
{
    // On-board LED for debug
    DDRB = (1 << DDB5);

    // Setup serial TX for debug printing
    init_TX();

    // Initialize ADC
    init_ADC();

    // Initialize the timer for every 2 seconds
    init_TIMER1(2);

    // Start the conversion
    start_ADC(ADC_INPUT_PIN, ADC_PRESCALER, 1);

    while(1);

    return 0;
}

/*
	@brief ADC ISR
*/
ISR(ADC_vect)
{
    // The duty value is now determined by the pentiometer
    adc_result = ADC;

    // Start another conversion (we aren't using auto-triggering)
    start_ADC();
}

/*
	@brief Timer1 ISR
*/
ISR(TIMER1_COMPA_vect)
{
    // Toggle the LED
    PORTB ^= (1 << PORTB5);

    // Print the ADC result
    sprintf(buffer,"%d\r\n",adc_result);
    write_TX(buffer, BUFFER_SIZE);
}


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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * TemplateAd.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
 */

package com.google.api.ads.adwords.axis.v201809.cm;

/**
 * Represents a Display Ad Builder template ad. A template ad is
 *             composed of a template (specified by its ID) and the data
 * that populates
 *             the template's fields. For a list of available templates
 * and their required
 *             fields, see Template
 * Ads.
 *             This is disabled for
 * AdX when it is contained within Operators: ADD, SET.
 */
public class TemplateAd  extends com.google.api.ads.adwords.axis.v201809.cm.Ad  implements java.io.Serializable {
    /* ID of the template to use.
     *                     This field
     * can be selected using the value "TemplateId".This field can be filtered on. */
    private java.lang.Long templateId;

    /* Group ID of all template ads, which should be created together.
     * Template ads in the same union reference the same data but have different
     * dimensions. Single ads do not have a union ID. If a template ad specifies
     * an ad union with only one ad, no union will be created.
     *                     This field
     * can be selected using the value "TemplateAdUnionId". */
    private com.google.api.ads.adwords.axis.v201809.cm.AdUnionId adUnionId;

    /* List of elements (each containing a set of fields) for the
     * template
     *                     referenced by {@code templateId}. See
     *                     Template
     * Ads for the elements and fields required for each template. */
    private com.google.api.ads.adwords.axis.v201809.cm.TemplateElement[] templateElements;

    /* The template ad rendered as an image. */
    private com.google.api.ads.adwords.axis.v201809.cm.Image adAsImage;

    /* The dimensions for this ad. */
    private com.google.api.ads.adwords.axis.v201809.cm.Dimensions dimensions;

    /* Name of this ad.
     *
     *                     This field is required and should not be {@code
     * null}.
     *                     This field
     * can be selected using the value "TemplateAdName". */
    private java.lang.String name;

    /* Duration of this ad (if it contains playable media).
     *                     This field
     * can be selected using the value "TemplateAdDuration".
     *                     This field is
     * read only and will be ignored when sent to the API. */
    private java.lang.Integer duration;

    /* For copies, the ad id of the ad this was or should be copied
     * from.
     *                     This field
     * can be selected using the value "TemplateOriginAdId". */
    private java.lang.Long originAdId;

    public TemplateAd() {
    }

    public TemplateAd(
           java.lang.Long id,
           java.lang.String url,
           java.lang.String displayUrl,
           java.lang.String[] finalUrls,
           java.lang.String[] finalMobileUrls,
           com.google.api.ads.adwords.axis.v201809.cm.AppUrl[] finalAppUrls,
           java.lang.String trackingUrlTemplate,
           java.lang.String finalUrlSuffix,
           com.google.api.ads.adwords.axis.v201809.cm.CustomParameters urlCustomParameters,
           com.google.api.ads.adwords.axis.v201809.cm.UrlData[] urlData,
           java.lang.Boolean automated,
           com.google.api.ads.adwords.axis.v201809.cm.AdType type,
           java.lang.Long devicePreference,
           com.google.api.ads.adwords.axis.v201809.cm.SystemManagedEntitySource systemManagedEntitySource,
           java.lang.String adType,
           java.lang.Long templateId,
           com.google.api.ads.adwords.axis.v201809.cm.AdUnionId adUnionId,
           com.google.api.ads.adwords.axis.v201809.cm.TemplateElement[] templateElements,
           com.google.api.ads.adwords.axis.v201809.cm.Image adAsImage,
           com.google.api.ads.adwords.axis.v201809.cm.Dimensions dimensions,
           java.lang.String name,
           java.lang.Integer duration,
           java.lang.Long originAdId) {
        super(
            id,
            url,
            displayUrl,
            finalUrls,
            finalMobileUrls,
            finalAppUrls,
            trackingUrlTemplate,
            finalUrlSuffix,
            urlCustomParameters,
            urlData,
            automated,
            type,
            devicePreference,
            systemManagedEntitySource,
            adType);
        this.templateId = templateId;
        this.adUnionId = adUnionId;
        this.templateElements = templateElements;
        this.adAsImage = adAsImage;
        this.dimensions = dimensions;
        this.name = name;
        this.duration = duration;
        this.originAdId = originAdId;
    }

    @Override
    public String toString() {
        return com.google.common.base.MoreObjects.toStringHelper(this.getClass())
            .omitNullValues()
            .add("adAsImage", getAdAsImage())
            .add("adType", getAdType())
            .add("adUnionId", getAdUnionId())
            .add("automated", getAutomated())
            .add("devicePreference", getDevicePreference())
            .add("dimensions", getDimensions())
            .add("displayUrl", getDisplayUrl())
            .add("duration", getDuration())
            .add("finalAppUrls", getFinalAppUrls())
            .add("finalMobileUrls", getFinalMobileUrls())
            .add("finalUrlSuffix", getFinalUrlSuffix())
            .add("finalUrls", getFinalUrls())
            .add("id", getId())
            .add("name", getName())
            .add("originAdId", getOriginAdId())
            .add("systemManagedEntitySource", getSystemManagedEntitySource())
            .add("templateElements", getTemplateElements())
            .add("templateId", getTemplateId())
            .add("trackingUrlTemplate", getTrackingUrlTemplate())
            .add("type", getType())
            .add("url", getUrl())
            .add("urlCustomParameters", getUrlCustomParameters())
            .add("urlData", getUrlData())
            .toString();
    }

    /**
     * Gets the templateId value for this TemplateAd.
     *
     * @return templateId   * ID of the template to use.
     *                     This field
     * can be selected using the value "TemplateId".This field can be filtered on.
     */
    public java.lang.Long getTemplateId() {
        return templateId;
    }

    /**
     * Sets the templateId value for this TemplateAd.
     *
     * @param templateId   * ID of the template to use.
     *                     This field
     * can be selected using the value "TemplateId".This field can be filtered on.
     */
    public void setTemplateId(java.lang.Long templateId) {
        this.templateId = templateId;
    }

    /**
     * Gets the adUnionId value for this TemplateAd.
     *
     * @return adUnionId   * Group ID of all template ads, which should be created together.
     * Template ads in the same union reference the same data but have different
     * dimensions. Single ads do not have a union ID. If a template ad specifies
     * an ad union with only one ad, no union will be created.
     *                     This field
     * can be selected using the value "TemplateAdUnionId".
     */
    public com.google.api.ads.adwords.axis.v201809.cm.AdUnionId getAdUnionId() {
        return adUnionId;
    }

    /**
     * Sets the adUnionId value for this TemplateAd.
     *
     * @param adUnionId   * Group ID of all template ads, which should be created together.
     * Template ads in the same union reference the same data but have different
     * dimensions. Single ads do not have a union ID. If a template ad specifies
     * an ad union with only one ad, no union will be created.
     *                     This field
     * can be selected using the value "TemplateAdUnionId".
     */
    public void setAdUnionId(com.google.api.ads.adwords.axis.v201809.cm.AdUnionId adUnionId) {
        this.adUnionId = adUnionId;
    }

    /**
     * Gets the templateElements value for this TemplateAd.
     *
     * @return templateElements   * List of elements (each containing a set of fields) for the
     * template
     *                     referenced by {@code templateId}. See
     *                     Template
     * Ads for the elements and fields required for each template.
     */
    public com.google.api.ads.adwords.axis.v201809.cm.TemplateElement[] getTemplateElements() {
        return templateElements;
    }

    /**
     * Sets the templateElements value for this TemplateAd.
     *
     * @param templateElements   * List of elements (each containing a set of fields) for the
     * template
     *                     referenced by {@code templateId}. See
     *                     Template
     * Ads for the elements and fields required for each template.
     */
    public void setTemplateElements(com.google.api.ads.adwords.axis.v201809.cm.TemplateElement[] templateElements) {
        this.templateElements = templateElements;
    }

    public com.google.api.ads.adwords.axis.v201809.cm.TemplateElement getTemplateElements(int i) {
        return this.templateElements[i];
    }

    public void setTemplateElements(int i, com.google.api.ads.adwords.axis.v201809.cm.TemplateElement _value) {
        this.templateElements[i] = _value;
    }

    /**
     * Gets the adAsImage value for this TemplateAd.
     *
     * @return adAsImage   * The template ad rendered as an image.
     */
    public com.google.api.ads.adwords.axis.v201809.cm.Image getAdAsImage() {
        return adAsImage;
    }

    /**
     * Sets the adAsImage value for this TemplateAd.
     *
     * @param adAsImage   * The template ad rendered as an image.
     */
    public void setAdAsImage(com.google.api.ads.adwords.axis.v201809.cm.Image adAsImage) {
        this.adAsImage = adAsImage;
    }

    /**
     * Gets the dimensions value for this TemplateAd.
     *
     * @return dimensions   * The dimensions for this ad.
     */
    public com.google.api.ads.adwords.axis.v201809.cm.Dimensions getDimensions() {
        return dimensions;
    }

    /**
     * Sets the dimensions value for this TemplateAd.
     *
     * @param dimensions   * The dimensions for this ad.
     */
    public void setDimensions(com.google.api.ads.adwords.axis.v201809.cm.Dimensions dimensions) {
        this.dimensions = dimensions;
    }

    /**
     * Gets the name value for this TemplateAd.
     *
     * @return name   * Name of this ad.
     *
     *                     This field is required and should not be {@code
     * null}.
     *                     This field
     * can be selected using the value "TemplateAdName".
     */
    public java.lang.String getName() {
        return name;
    }

    /**
     * Sets the name value for this TemplateAd.
     *
     * @param name   * Name of this ad.
     *
     *                     This field is required and should not be {@code
     * null}.
     *                     This field
     * can be selected using the value "TemplateAdName".
     */
    public void setName(java.lang.String name) {
        this.name = name;
    }

    /**
     * Gets the duration value for this TemplateAd.
     *
     * @return duration   * Duration of this ad (if it contains playable media).
     *                     This field
     * can be selected using the value "TemplateAdDuration".
     *                     This field is
     * read only and will be ignored when sent to the API.
     */
    public java.lang.Integer getDuration() {
        return duration;
    }

    /**
     * Sets the duration value for this TemplateAd.
     *
     * @param duration   * Duration of this ad (if it contains playable media).
     *                     This field
     * can be selected using the value "TemplateAdDuration".
     *                     This field is
     * read only and will be ignored when sent to the API.
     */
    public void setDuration(java.lang.Integer duration) {
        this.duration = duration;
    }

    /**
     * Gets the originAdId value for this TemplateAd.
     *
     * @return originAdId   * For copies, the ad id of the ad this was or should be copied
     * from.
     *                     This field
     * can be selected using the value "TemplateOriginAdId".
     */
    public java.lang.Long getOriginAdId() {
        return originAdId;
    }

    /**
     * Sets the originAdId value for this TemplateAd.
     *
     * @param originAdId   * For copies, the ad id of the ad this was or should be copied
     * from.
     *                     This field
     * can be selected using the value "TemplateOriginAdId".
     */
    public void setOriginAdId(java.lang.Long originAdId) {
        this.originAdId = originAdId;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof TemplateAd)) return false;
        TemplateAd other = (TemplateAd) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = super.equals(obj) &&
            ((this.templateId==null && other.getTemplateId()==null) ||
             (this.templateId!=null &&
              this.templateId.equals(other.getTemplateId()))) &&
            ((this.adUnionId==null && other.getAdUnionId()==null) ||
             (this.adUnionId!=null &&
              this.adUnionId.equals(other.getAdUnionId()))) &&
            ((this.templateElements==null && other.getTemplateElements()==null) ||
             (this.templateElements!=null &&
              java.util.Arrays.equals(this.templateElements, other.getTemplateElements()))) &&
            ((this.adAsImage==null && other.getAdAsImage()==null) ||
             (this.adAsImage!=null &&
              this.adAsImage.equals(other.getAdAsImage()))) &&
            ((this.dimensions==null && other.getDimensions()==null) ||
             (this.dimensions!=null &&
              this.dimensions.equals(other.getDimensions()))) &&
            ((this.name==null && other.getName()==null) ||
             (this.name!=null &&
              this.name.equals(other.getName()))) &&
            ((this.duration==null && other.getDuration()==null) ||
             (this.duration!=null &&
              this.duration.equals(other.getDuration()))) &&
            ((this.originAdId==null && other.getOriginAdId()==null) ||
             (this.originAdId!=null &&
              this.originAdId.equals(other.getOriginAdId())));
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = super.hashCode();
        if (getTemplateId() != null) {
            _hashCode += getTemplateId().hashCode();
        }
        if (getAdUnionId() != null) {
            _hashCode += getAdUnionId().hashCode();
        }
        if (getTemplateElements() != null) {
            for (int i=0;
                 i<java.lang.reflect.Array.getLength(getTemplateElements());
                 i++) {
                java.lang.Object obj = java.lang.reflect.Array.get(getTemplateElements(), i);
                if (obj != null &&
                    !obj.getClass().isArray()) {
                    _hashCode += obj.hashCode();
                }
            }
        }
        if (getAdAsImage() != null) {
            _hashCode += getAdAsImage().hashCode();
        }
        if (getDimensions() != null) {
            _hashCode += getDimensions().hashCode();
        }
        if (getName() != null) {
            _hashCode += getName().hashCode();
        }
        if (getDuration() != null) {
            _hashCode += getDuration().hashCode();
        }
        if (getOriginAdId() != null) {
            _hashCode += getOriginAdId().hashCode();
        }
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(TemplateAd.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "TemplateAd"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("templateId");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "templateId"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("adUnionId");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "adUnionId"));
        elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "AdUnionId"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("templateElements");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "templateElements"));
        elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "TemplateElement"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        elemField.setMaxOccursUnbounded(true);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("adAsImage");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "adAsImage"));
        elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "Image"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("dimensions");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "dimensions"));
        elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "Dimensions"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("name");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "name"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("duration");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "duration"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("originAdId");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "originAdId"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
package com.sproutigy.commons.binary;

import org.junit.Test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import static org.junit.Assert.*;

/**
 * @author LukeAheadNET
 */
public class BinaryTest {

    @Test
    public void testEmpty() {
        assertEquals(0, Binary.EMPTY.length());
        assertEquals(0, Binary.EMPTY.asByteArray().length);
    }

    @Test
    public void testStrings() throws UnsupportedEncodingException {
        UncheckedBinary dataFromString = Binary.fromString("HELLO", "UTF-8");
        assertEquals(5, dataFromString.length());
        assertArrayEquals("HELLO".getBytes("UTF-8"), dataFromString.asByteArray());
        assertEquals("HELLO", Binary.fromString("HELLO", Charset.forName("US-ASCII")).asStringASCII());
    }

    @Test
    public void testFileAsString() throws IOException {
        File file = File.createTempFile("binary-test", ".tmp").getAbsoluteFile();
        file.deleteOnExit();
        FileOutputStream output = new FileOutputStream(file);
        try {
            output.write("Hello".getBytes("UTF-8"));
            Binary.fromString(" World", Charset.forName("US-ASCII")).to(output);
        } finally {
            output.close();
        }
        assertEquals("Hello World", Binary.fromFile(file).asStringUTF8());
    }

    @Test
    public void testSubrange() throws IOException {
        assertEquals("ello", Binary.fromString("Hello World", Charset.forName("US-ASCII")).subrange(1, 4).asStringASCII());
        String file = Binary.fromString("ABCDEFGHIJK", Charset.forName("US-ASCII")).toTempFile();
        assertEquals("BC", Binary.fromFile(file).subrange(1,2).asStringASCII());
    }

    @Test
    public void testHex() {
        UncheckedBinary b = Binary.fromHex("48454c4c4f");
        assertEquals("HELLO", b.asStringASCII());
        assertEquals("48454C4C4F", b.asHex());
    }

    @Test
    public void testBase64() {
        UncheckedBinary b = Binary.fromBase64("SEVMTE8");
        assertEquals("HELLO", b.asStringASCII());
        assertEquals("SEVMTE8=", b.asBase64(BaseEncoding.Padding.STANDARD));
        assertEquals("SEVMTE8.", b.asBase64(BaseEncoding.Padding.SAFE));
        assertEquals("SEVMTE8", b.asBase64(BaseEncoding.Padding.NO));

        UncheckedBinary b2 = Binary.fromBase64("zs/Q0dI=");
        byte[] bytes = b2.asByteArray();
        assertEquals((byte)206, bytes[0]);
        assertEquals((byte)207, bytes[1]);
        assertEquals((byte)208, bytes[2]);
        assertEquals((byte)209, bytes[3]);
        assertEquals((byte)210, bytes[4]);
        assertEquals("zs_Q0dI", b2.asBase64(BaseEncoding.Dialect.SAFE, BaseEncoding.Padding.NO));

        assertArrayEquals(bytes, Binary.fromBase64("zs_Q0dI").asByteArray());
    }

    @Test
    public void testStringCharset() {
        String s = "tęśt";

        UncheckedBinary b1 = Binary.fromString(s, Charsets.UTF_32);
        assertTrue(b1.hasCharset());
        assertEquals(Charsets.UTF_32, b1.getCharset());
        String t1 = b1.asString();
        assertEquals(s, t1);

        UncheckedBinary b2 = Binary.fromString(s, Charsets.ISO_8859_1);
        assertTrue(b2.hasCharset());
        assertEquals(Charsets.ISO_8859_1, b2.getCharset());
        String t2 = b2.asString();
        assertNotEquals(s, t2);
        assertEquals("t??t", t2);
    }

}


text:
require 'spec_helper'

describe Mongo::Operation::Commands::Command do

  let(:selector) { { :ismaster => 1 } }
  let(:options) { { :limit => -1 } }
  let(:spec) do
    { :selector => selector,
      :options     => options,
      :db_name  => TEST_DB
    }
  end
  let(:op) { described_class.new(spec) }

  describe '#initialize' do

    it 'sets the spec' do
      expect(op.spec).to be(spec)
    end
  end

  describe '#==' do

    context 'when the ops have different specs' do

      let(:other_selector) { { :ping => 1 } }
      let(:other_spec) do
        { :selector => other_selector,
          :options => {},
          :db_name => 'test',
        }
      end
      let(:other) { described_class.new(other_spec) }

      it 'returns false' do
        expect(op).not_to eq(other)
      end
    end
  end

  describe '#execute' do

    context 'when the command succeeds' do

      let(:response) do
        op.execute(authorized_primary.context)
      end

      it 'returns the reponse' do
        expect(response).to be_successful
      end
    end

    context 'when the command fails' do

      let(:selector) do
        { notacommand: 1 }
      end

      it 'raises an exception' do
        expect {
          op.execute(authorized_primary.context)
        }.to raise_error(Mongo::Error::OperationFailure)
      end
    end

    context 'when a document exceeds max bson size' do

      let(:selector) do
        { :ismaster => '1'*17000000 }
      end

      it 'raises an error' do
        expect {
          op.execute(authorized_primary.context)
        }.to raise_error(Mongo::Error::MaxBSONSize)
      end
    end
  end
end


text:
<?php

namespace ymaker\newsletter\tests\unit;

/**
 * Base test case class
 *
 * @author Vladimir Kuprienko <vldmr.kuprienko@gmail.com>
 * @since 1.0
 */
class TestCase extends \Codeception\Test\Unit
{
    /**
     * @var \UnitTester
     */
    protected $tester;
}


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

namespace Dnn.PersonaBar.SiteGroups.Services
{
    using System;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;

    using Dnn.PersonaBar.Library;
    using Dnn.PersonaBar.Library.Attributes;
    using Dnn.PersonaBar.SiteGroups.Models;
    using DotNetNuke.Instrumentation;
    using DotNetNuke.Web.Api;

    [MenuPermission(Scope = ServiceScope.Host)]
    public class SiteGroupsController : PersonaBarApiController
    {
        private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SiteGroupsController));

        private IManagePortalGroups GroupManager
        {
            get
            {
                return SiteGroups.Instance;
            }
        }

        [HttpGet]
        public HttpResponseMessage GetSiteGroups()
        {
            var groups = this.GroupManager.SiteGroups();
            return this.Request.CreateResponse(HttpStatusCode.OK, groups);
        }

        [HttpGet]
        public HttpResponseMessage GetAvailablePortals()
        {
            var portals = this.GroupManager.AvailablePortals();
            return this.Request.CreateResponse(HttpStatusCode.OK, portals);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public HttpResponseMessage Save(PortalGroupInfo portalGroup)
        {
            try
            {
                var id = this.GroupManager.Save(portalGroup);
                return this.Request.CreateResponse(HttpStatusCode.OK, id);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public HttpResponseMessage Delete(int groupId)
        {
            try
            {
                this.GroupManager.Delete(groupId);
                return this.Request.CreateResponse(HttpStatusCode.OK, groupId);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Using as: Fail</title>

<meta name="description" content="Using as: Fail">
<meta name="keywords" content="Using as: Fail">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="AS-Index.html#AS-Index" rel="index" title="AS Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Pseudo-Ops.html#Pseudo-Ops" rel="up" title="Pseudo Ops">
<link href="File.html#File" rel="next" title="File">
<link href="Extern.html#Extern" rel="prev" title="Extern">

Next: File, Previous: Extern, Up: Pseudo Ops   [Contents][Index]

7.52 .fail <var>expression</var>

Generates an error or a warning.  If the value of the <var>expression</var> is 500
or more, as will print a warning message.  If the value is less
than 500, as will print an error message.  The message will
include the value of <var>expression</var>.  This can occasionally be useful inside
complex nested macros or conditional assembly.


text:
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using Azure.Core;

namespace Azure.Messaging.EventGrid.Models
{
    [JsonConverter(typeof(EventGridEventInternalConverter))]
    internal partial class EventGridEventInternal : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("id");
            writer.WriteStringValue(Id);
            if (Optional.IsDefined(Topic))
            {
                writer.WritePropertyName("topic");
                writer.WriteStringValue(Topic);
            }
            writer.WritePropertyName("subject");
            writer.WriteStringValue(Subject);
            writer.WritePropertyName("data");
            Data.WriteTo(writer);
            writer.WritePropertyName("eventType");
            writer.WriteStringValue(EventType);
            writer.WritePropertyName("eventTime");
            writer.WriteStringValue(EventTime, "O");
            writer.WritePropertyName("dataVersion");
            writer.WriteStringValue(DataVersion);
            writer.WriteEndObject();
        }

        internal static EventGridEventInternal DeserializeEventGridEventInternal(JsonElement element)
        {
            string id = default;
            Optional<string> topic = default;
            string subject = default;
            JsonElement data = default;
            string eventType = default;
            DateTimeOffset eventTime = default;
            Optional<string> metadataVersion = default;
            string dataVersion = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("id"))
                {
                    id = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("topic"))
                {
                    topic = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("subject"))
                {
                    subject = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("data"))
                {
                    data = property.Value.Clone();
                    continue;
                }
                if (property.NameEquals("eventType"))
                {
                    eventType = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("eventTime"))
                {
                    eventTime = property.Value.GetDateTimeOffset("O");
                    continue;
                }
                if (property.NameEquals("metadataVersion"))
                {
                    metadataVersion = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("dataVersion"))
                {
                    dataVersion = property.Value.GetString();
                    continue;
                }
            }
            return new EventGridEventInternal(id, topic.Value, subject, data, eventType, eventTime, metadataVersion.Value, dataVersion);
        }

        internal partial class EventGridEventInternalConverter : JsonConverter<EventGridEventInternal>
        {
            public override void Write(Utf8JsonWriter writer, EventGridEventInternal model, JsonSerializerOptions options)
            {
                writer.WriteObjectValue(model);
            }
            public override EventGridEventInternal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
            {
                using var document = JsonDocument.ParseValue(ref reader);
                return DeserializeEventGridEventInternal(document.RootElement);
            }
        }
    }
}


text:
function test() {
  Harness.downloadProgressCallback = download_progress;
  Harness.installEndedCallback = install_ended;
  Harness.installsCompletedCallback = finish_test;
  Harness.setup();

  var pm = Services.perms;
  pm.add(makeURI("http://example.com/"), "install", pm.ALLOW_ACTION);

  var triggers = encodeURIComponent(JSON.stringify({
    "Unsigned XPI": TESTROOT + "unsigned.xpi"
  }));
  gBrowser.selectedTab = gBrowser.addTab();
  gBrowser.loadURI(TESTROOT + "installtrigger.html?" + triggers);
}

function download_progress(addon, value, maxValue) {
  gBrowser.removeCurrentTab();
}

function install_ended(install, addon) {
  install.cancel();
}

function finish_test(count) {
  is(count, 1, "1 Add-on should have been successfully installed");

  Services.perms.remove("example.com", "install");

  Harness.finish();
}


text:
require 'pathname'
require 'retriable'
require "active_support/core_ext/date"
require "active_support/core_ext/time"
require "active_support/core_ext/integer"
require "mint/helper/version"
require "mint/helper/scraper"
require "mint/helper/database"
require "mint/helper/transaction"
require "mint/helper/notifier"

module Mint
  Email = ENV['MINT_EMAIL']
  Password = ENV['MINT_PASSWORD']

  module Helper
    DataDirectory = Pathname('./data')

    def self.latest_csv_path
      Dir.glob(DataDirectory.expand_path.join('*.csv')).last
    end
  end
end


text:
package gwt.material.design.client.events;

import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HasHandlers;
import gwt.material.design.client.events.ClearActiveEvent.ClearActiveHandler;

public class ClearActiveEvent extends GwtEvent<ClearActiveHandler> {

    public interface ClearActiveHandler extends EventHandler {
        void onClearActive(ClearActiveEvent event);
    }

    public static final Type<ClearActiveHandler> TYPE = new Type<>();

    public static void fire(HasHandlers source) {
        source.fireEvent(new ClearActiveEvent());
    }

    @Override
    public Type<ClearActiveHandler> getAssociatedType() {
        return TYPE;
    }

    @Override
    protected void dispatch(ClearActiveHandler handler) {
        handler.onClearActive(this);
    }
}


text:
package com.microsoft.bingads.api.test.entities.campaign_product_scope;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({
        BulkCampaignProductScopeReadTests.class,
        BulkCampaignProductScopeWriteTests.class
})
public class BulkCampaignProductScopeTests {
}


text:
//
// leak-at-exit.c
//
// Author:
//   Rolf Bjarne Kvinge
//
// Copyright 2017 Microsoft
//

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <time.h>

static void my__exit (int status);

typedef void (*ExitFunc) (int status);
ExitFunc system__exit = exit;

static void
my__exit (int status)
{
	const char *ready_file = getenv ("LEAK_READY_FILE");
	const char *done_file = getenv ("LEAK_DONE_FILE");
	if (!ready_file || !done_file)
		return;

	fprintf (stderr, "Checking for leaks\n");

	int rv = unlink (ready_file);
	if (rv != 0) {
		fprintf (stderr, "Could not delete ready file %s: %s\n", ready_file, strerror (errno));;
		return;
	}

	rv = access (done_file, F_OK);
	while (rv == 0) {
		// fprintf (stdout, "Waiting for done file to be deleted...\n");
		struct timespec ts;
		ts.tv_sec = 0;
		ts.tv_nsec = 100000000; /* 100 ms */
		nanosleep (&ts, NULL);
		rv = access (done_file, F_OK);
	}
	if (errno != ENOENT)
		fprintf (stdout, "Failed to access done file %s: %s\n", done_file, strerror (errno));

	fprintf (stdout, "Leak check performed\n");

	system__exit (status);
}

typedef struct interpose_s {
	void *new_func;
	void *orig_func;
} interpose_t;

static const interpose_t interposers[] __attribute__ ((used)) \
	__attribute__ ((section("__DATA,__interpose"))) = {
		{ (void *) &my__exit,  (void *) &exit  },
    };


text:
FROM sitback/proxy:nginx
MAINTAINER Chinthaka Godawita <chin@sitback.com.au>

# Remove default config.
RUN rm -v /etc/nginx/nginx.conf

# Add custom config.
ADD ./conf/nginx/nginx.conf /etc/nginx/nginx.conf


text:
<?xml version="1.0" encoding="utf-8"?>
<OrleansConfiguration xmlns="urn:orleans">
  <Globals >
    <StorageProviders>
      <Provider Type="Orleans.Storage.MemoryStorage" Name="MemoryStore" />
      <Provider Type="Pk.OrleansUtils.ElasticSearch.ElasticStorageProvider" Name="Default" DataConnectionString="index=orleans;Host=localhost" />
      <!-- To use Azure storage, uncomment one of the following lines: -->
      <!--<Provider Type="Orleans.Storage.AzureTableStorage" Name="AzureStore" DataConnectionString="UseDevelopmentStorage=true" />-->
      <!--<Provider Type="Orleans.Storage.AzureTableStorage" Name="AzureStore" DataConnectionString="DefaultEndpointsProtocol=https;AccountName=MYACCOUNTNAME;AccountKey=MYACCOUNTKEY" />-->
    </StorageProviders>
    <StatisticsProviders>
      <Provider Type="Pk.OrleansUtils.ApplicationInsights.AppInStatisticsPublisher"
                    Name="Statistics"
                    InstrumentationKey="%OrleansInstrumentationKey%"
                    ReportsStatsEnabled="true"
    />
    </StatisticsProviders>

    <SeedNode Address="localhost" Port="11111" />
    <SystemStore SystemStoreType="Custom"  DataConnectionString="host=localhost;datacenter=dc1;index=reminders;mode=2"
             MembershipTableAssembly="Pk.OrleansUtils.Consul"
             ReminderTableAssembly="Pk.OrleansUtils.ElasticSearch"
             DataConnectionStringForReminders="host=localhost;index=reminders;mode=2"
             DeploymentId="DevHost"

                 />
    <Liveness IAmAliveTablePublishTimeout="5s" DeathVoteExpirationTimeout="5s" LivenessEnabled="true"
          TableRefreshTimeout="5s" UseLivenessGossip="true"
              />
    <Application>
        <Defaults>
          <Deactivation AgeLimit="1m"/>
        </Defaults>
    </Application>

  </Globals>
  <Defaults>
    <Networking Address="localhost" Port="11111" />
    <ProxyingGateway Address="localhost" Port="30000"  />
    <!--
    <Tracing DefaultTraceLevel="Info" TraceToConsole="true" TraceToFile="{0}-{1}.log">
      <TraceLevelOverride LogPrefix="Application" TraceLevel="Info" />
    </Tracing>
    -->
    <Statistics MetricsTableWriteInterval="1000s" PerfCounterWriteInterval="1000s" LogWriteInterval="2000s" WriteLogStatisticsToTable="true"
                />
  </Defaults>
  <Override Node="Primary" >
    <Networking Address="localhost" Port="11111" />
    <ProxyingGateway Address="localhost" Port="30000" />
  </Override>
</OrleansConfiguration>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Column Chart</title>
    <link rel="stylesheet" type="text/css" href="../shared/example.css" />

Bar Column Sample

        Display a sets of random data in a column series. Reload data will randomly generate a new set of data in the store.  View Source