text:
#ifndef __MALI_DMA_H__
#define __MALI_DMA_H__

#include "mali_osk.h"
#include "mali_osk_mali.h"
#include "mali_hw_core.h"

#define MALI_DMA_CMD_BUF_SIZE 1024

typedef struct mali_dma_cmd_buf {
	u32 *virt_addr;           /**< CPU address of command buffer */
	u32 phys_addr;            /**< Physical address of command buffer */
	u32 size;                 /**< Number of prepared words in command buffer */
} mali_dma_cmd_buf;

/** @brief Create a new DMA unit
 *
 * This is called from entry point of the driver in order to create and
 * intialize the DMA resource
 *
 * @param resource it will be a pointer to a DMA resource
 * @return DMA object on success, NULL on failure
 */
struct mali_dma_core *mali_dma_create(_mali_osk_resource_t *resource);

/** @brief Delete DMA unit
 *
 * This is called on entry point of driver if the driver initialization fails
 * after initialization of the DMA unit. It is also called on the exit of the
 * driver to delete the DMA resource
 *
 * @param dma Pointer to DMA unit object
 */
void mali_dma_delete(struct mali_dma_core *dma);

/** @brief Retrieves the MALI DMA core object (if there is)
 *
 * @return The Mali DMA object otherwise NULL
 */
struct mali_dma_core *mali_dma_get_global_dma_core(void);

/**
 * @brief Run a command buffer on the DMA unit
 *
 * @param dma Pointer to the DMA unit to use
 * @param buf Pointer to the command buffer to use
 * @return _MALI_OSK_ERR_OK if the buffer was started successfully,
 *         _MALI_OSK_ERR_BUSY if the DMA unit is busy.
 */
_mali_osk_errcode_t mali_dma_start(struct mali_dma_core* dma, mali_dma_cmd_buf *buf);

/**
 * @brief Create a DMA command
 *
 * @param core Mali core
 * @param reg offset to register of core
 * @param n number of registers to write
 */
MALI_STATIC_INLINE u32 mali_dma_command_write(struct mali_hw_core *core, u32 reg, u32 n)
{
	u32 core_offset = core->phys_offset;

	MALI_DEBUG_ASSERT(reg < 0x2000);
	MALI_DEBUG_ASSERT(n < 0x800);
	MALI_DEBUG_ASSERT(core_offset < 0x30000);
	MALI_DEBUG_ASSERT(0 == ((core_offset + reg) & ~0x7FFFF));

	return (n << 20) | (core_offset + reg);
}

/**
 * @brief Add a array write to DMA command buffer
 *
 * @param buf DMA command buffer to fill in
 * @param core Core to do DMA to
 * @param reg Register on core to start writing to
 * @param data Pointer to data to write
 * @param count Number of 4 byte words to write
 */
MALI_STATIC_INLINE void mali_dma_write_array(mali_dma_cmd_buf *buf, struct mali_hw_core *core,
        u32 reg, u32 *data, u32 count)
{
	MALI_DEBUG_ASSERT((buf->size + 1 + count ) < MALI_DMA_CMD_BUF_SIZE / 4);

	buf->virt_addr[buf->size++] = mali_dma_command_write(core, reg, count);

	_mali_osk_memcpy(buf->virt_addr + buf->size, data, count * sizeof(*buf->virt_addr));

	buf->size += count;
}

/**
 * @brief Add a conditional array write to DMA command buffer
 *
 * @param buf DMA command buffer to fill in
 * @param core Core to do DMA to
 * @param reg Register on core to start writing to
 * @param data Pointer to data to write
 * @param count Number of 4 byte words to write
 * @param ref Pointer to referance data that can be skipped if equal
 */
MALI_STATIC_INLINE void mali_dma_write_array_conditional(mali_dma_cmd_buf *buf, struct mali_hw_core *core,
        u32 reg, u32 *data, u32 count, const u32 *ref)
{
	/* Do conditional array writes are not yet implemented, fallback to a
	 * normal array write. */
	mali_dma_write_array(buf, core, reg, data, count);
}

/**
 * @brief Add a conditional register write to the DMA command buffer
 *
 * If the data matches the reference the command will be skipped.
 *
 * @param buf DMA command buffer to fill in
 * @param core Core to do DMA to
 * @param reg Register on core to start writing to
 * @param data Pointer to data to write
 * @param ref Pointer to referance data that can be skipped if equal
 */
MALI_STATIC_INLINE void mali_dma_write_conditional(mali_dma_cmd_buf *buf, struct mali_hw_core *core,
        u32 reg, u32 data, const u32 ref)
{
	/* Skip write if reference value is equal to data. */
	if (data == ref) return;

	buf->virt_addr[buf->size++] = mali_dma_command_write(core, reg, 1);

	buf->virt_addr[buf->size++] = data;

	MALI_DEBUG_ASSERT(buf->size < MALI_DMA_CMD_BUF_SIZE / 4);
}

/**
 * @brief Add a register write to the DMA command buffer
 *
 * @param buf DMA command buffer to fill in
 * @param core Core to do DMA to
 * @param reg Register on core to start writing to
 * @param data Pointer to data to write
 */
MALI_STATIC_INLINE void mali_dma_write(mali_dma_cmd_buf *buf, struct mali_hw_core *core,
                                       u32 reg, u32 data)
{
	buf->virt_addr[buf->size++] = mali_dma_command_write(core, reg, 1);

	buf->virt_addr[buf->size++] = data;

	MALI_DEBUG_ASSERT(buf->size < MALI_DMA_CMD_BUF_SIZE / 4);
}

/**
 * @brief Prepare DMA command buffer for use
 *
 * This function allocates the DMA buffer itself.
 *
 * @param buf The mali_dma_cmd_buf to prepare
 * @return _MALI_OSK_ERR_OK if the \a buf is ready to use
 */
_mali_osk_errcode_t mali_dma_get_cmd_buf(mali_dma_cmd_buf *buf);

/**
 * @brief Check if a DMA command buffer is ready for use
 *
 * @param buf The mali_dma_cmd_buf to check
 * @return MALI_TRUE if buffer is usable, MALI_FALSE otherwise
 */
MALI_STATIC_INLINE mali_bool mali_dma_cmd_buf_is_valid(mali_dma_cmd_buf *buf)
{
	return NULL != buf->virt_addr;
}

/**
 * @brief Return a DMA command buffer
 *
 * @param buf Pointer to DMA command buffer to return
 */
void mali_dma_put_cmd_buf(mali_dma_cmd_buf *buf);

#endif /* __MALI_DMA_H__ */


text:
package com.android.launcher3.util;

import android.util.Log;
import android.view.View;
import android.view.View.OnAttachStateChangeListener;
import android.view.ViewTreeObserver.OnDrawListener;

import com.android.launcher3.DeferredHandler;
import com.android.launcher3.Launcher;

import java.util.ArrayList;
import java.util.concurrent.Executor;

/**
 * An executor which runs all the tasks after the first onDraw is called on the target view.
 */
public class ViewOnDrawExecutor implements Executor, OnDrawListener, Runnable,
        OnAttachStateChangeListener {

    private final ArrayList<Runnable> mTasks = new ArrayList<>();
    private final DeferredHandler mHandler;

    private Launcher mLauncher;
    private View mAttachedView;
    private boolean mCompleted;

    private boolean mLoadAnimationCompleted;
    private boolean mFirstDrawCompleted;

    public ViewOnDrawExecutor(DeferredHandler handler) {
        mHandler = handler;
    }

    public void attachTo(Launcher launcher) {
        mLauncher = launcher;
        mAttachedView = launcher.getWorkspace();
        mAttachedView.addOnAttachStateChangeListener(this);

        attachObserver();
    }

    private void attachObserver() {
        if (!mCompleted) {
            mAttachedView.getViewTreeObserver().addOnDrawListener(this);
        }
    }

    @Override
    public void execute(Runnable command) {
        mTasks.add(command);
    }

    @Override
    public void onViewAttachedToWindow(View v) {
        attachObserver();
    }

    @Override
    public void onViewDetachedFromWindow(View v) { }

    @Override
    public void onDraw() {
        mFirstDrawCompleted = true;
        mAttachedView.post(this);
    }

    public void onLoadAnimationCompleted() {
        mLoadAnimationCompleted = true;
        if (mAttachedView != null) {
            mAttachedView.post(this);
        }
    }

    @Override
    public void run() {
        // Post the pending tasks after both onDraw and onLoadAnimationCompleted have been called.
        if (mLoadAnimationCompleted && mFirstDrawCompleted && !mCompleted) {
            for (final Runnable r : mTasks) {
                mHandler.post(r);
            }
            markCompleted();
        }
    }

    public void markCompleted() {
        mTasks.clear();
        mCompleted = true;
        if (mAttachedView != null) {
            mAttachedView.getViewTreeObserver().removeOnDrawListener(this);
            mAttachedView.removeOnAttachStateChangeListener(this);
        }
        if (mLauncher != null) {
            mLauncher.clearPendingExecutor(this);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
layout: page
title: Elliott Entertainment Dinner
date: 2016-05-24
author: Christina Henry
tags: weekly links, java
status: published
summary: Donec ac felis id tellus egestas viverra a sed.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 06/08/2017
  endDate: 06/09/2017
  ctyhocn: SANPBHX
  groupCode: EED
published: true
---
Duis sit amet ligula vitae enim aliquam tincidunt in rhoncus tellus. Sed pharetra ligula mi, non tincidunt orci vulputate ultrices. Proin euismod condimentum dolor, ut mattis justo maximus tincidunt. Phasellus blandit nisi mauris, sed interdum eros iaculis malesuada. Nullam quis mi tortor. Quisque pulvinar a urna nec pretium. Nulla semper nulla ac purus placerat semper. Interdum et malesuada fames ac ante ipsum primis in faucibus. Phasellus ultrices faucibus tortor at condimentum.

* Donec lacinia ante ut mauris ultrices, quis tincidunt erat mollis
* In hendrerit felis quis dolor laoreet, a pretium magna pulvinar
* Proin vitae sapien interdum, efficitur lectus sed, cursus est
* Suspendisse imperdiet mauris sit amet odio varius, vitae convallis nibh luctus
* In dignissim felis a mauris feugiat ullamcorper eget id mi
* Aenean finibus sapien nec purus tincidunt pharetra.

Nunc scelerisque mi ante. Nullam tincidunt dapibus nisi, vitae viverra tortor convallis in. Curabitur congue ipsum massa, ac suscipit lectus fermentum eu. Suspendisse lectus felis, viverra porttitor pulvinar aliquam, lobortis vel nulla. In hendrerit nec ligula in maximus. Curabitur placerat ligula vel est eleifend ultricies. Curabitur molestie urna ac felis varius porta. Fusce bibendum rhoncus felis in tempor. In hac habitasse platea dictumst. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam id dignissim quam, nec ullamcorper orci.


text:
/*

	PROJECTOR

	Converts mouse coordinates into 3D and detects mouse interaction

	--

	@author Mark Lundin - http://www.mark-lundin.com

*/

ERNO.Projector = (function(){

	//	The Cube Projector is a specialised class that detects mouse interaction.
	//	It's designed specifically for cubic geometry, in that it makes assumptions
	//  that cannot be applied to other 3D geometry. This makes the performance faster
	//  than other more generalised mouse picking techniques.

	return function( cube, domElement ){

		var api,
			screen,
			viewProjectionMatrix = new THREE.Matrix4(),
			inverseMatrix = new THREE.Matrix4(),
			mouse 	= new THREE.Vector3(),
			end 	= new THREE.Vector3( 1, 1, 1 ),
			normal 	= new THREE.Vector3(),
			ray 	= new THREE.Ray(),
			box 	= new THREE.Box3(),
			sphere  = new THREE.Sphere(),
			projectionMatrixInverse = new THREE.Matrix4(),
			unitCubeBoundingRadius = mouse.distanceTo( end );

		//	Configure the bounding spehere and Axis Aligned Bounding Box dimensions.
		box.min.set( -cube.size*0.5, -cube.size*0.5, -cube.size*0.5 );
		box.max.set(  cube.size*0.5,  cube.size*0.5,  cube.size*0.5 );
		sphere.radius = unitCubeBoundingRadius * cube.size * 0.5;

		//	Utility function that unprojects 2D normalised screen coordinate to 3D.
		//	Taken from Three.js Projector class

		function unprojectVector( vector, camera ) {

			projectionMatrixInverse.getInverse( camera.projectionMatrix );
			viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, projectionMatrixInverse );
			return vector.applyMatrix4( viewProjectionMatrix );

		}

		// Returns the bounding area of the element
		function getBoundingClientRect( element ){

			var bounds = element !== document ? element.getBoundingClientRect() : {
				left: 0,
				top: 0,
				width: window.innerWidth,
				height: window.innerHeight
			};

			if( element !== document ){
				var d = element.ownerDocument.documentElement;
		 		bounds.left += window.pageXOffset - d.clientLeft;
		 		bounds.top  += window.pageYOffset - d.clientTop;
		 	}

		 	return bounds;

		}

		/*
		 *	Returns a THREE.Ray instance in cube space!
		 */
		function setRay( camera, mouseX, mouseY ){

			//	Get the bounding area
			screen = getBoundingClientRect( domElement );

			//	Convert screen coords indo normalized device coordinate space
			mouse.x = ( mouseX - screen.left ) / screen.width * 2 - 1;
			mouse.y = ( mouseY - screen.top  ) / screen.height * -2 + 1;
			mouse.z = -1.0;

			// set two vectors with opposing z values
			end.set( mouse.x, mouse.y, 1.0 );

			//	Unproject screen coordinates into 3D
			unprojectVector( mouse, camera );
			unprojectVector( end, camera );

			// find direction from vector to end
			end.sub( mouse ).normalize();

			//	Configure the ray caster
			ray.set( mouse, end );

			//	Apply the world inverse
			inverseMatrix.getInverse( cube.matrixWorld );
			ray.applyMatrix4( inverseMatrix );

			return ray;

		}

		/*
		 *	Given an intersection point on the surface of the cube,
		 * 	this returns a vector indicating the normal of the face
		 */

		 function getFaceNormalForIntersection ( intersection, optionalTarget ){

			var target = optionalTarget || new THREE.Vector3();

			target.copy( intersection )
				.set( Math.round( target.x ), Math.round( target.y ), Math.round( target.z ))
			  	.multiplyScalar( 2 / cube.size )
			  	.set( target.x|0, target.y|0, target.z|0 );

			return normal;

		}

		/*
		 *	Given a three.js camera instance and a 2D mouse coordinates local to the domElement,
		 * 	this method tests for any intersection against the cube
		 *	and returns a cubelet if one is found, otherwise it returns null indicating no intersection.
		 */

		api = {

			getIntersection: function( camera, mouseX, mouseY, optionalIntersectionTarget, optionalPlaneTarget ){

				var intersection = optionalIntersectionTarget || new THREE.Vector3();

				//	If we haven't detected any mouse movement, then we've not made interacted!

				if( mouseX === null || mouseY === null ) return null;

				//	Shoot the camera ray into 3D

				setRay( camera, mouseX, mouseY );

				//	Check ray casting against the bounding sphere first as it's easier to compute,
				//	if it passes, then check the Axis Aligned Bounding Box.

				if( ray.intersectsSphere( sphere ) &&
					ray.intersectBox( box, intersection ) !== null ){

					if( optionalPlaneTarget ){
						getFaceNormalForIntersection( intersection, normal );
						optionalPlaneTarget.setFromNormalAndCoplanarPoint( normal, intersection );
					}

					return intersection;

				}

				return null;

			},

			getIntersectionOnPlane: function( camera, mouseX, mouseY, plane, optionalTarget ){

				//	If we haven't detected any mouse movement, then we've not interacted!
				if( mouseX === null || mouseY === null ) return null;

				//	Shoot the camera ray into 3D
				setRay( camera, mouseX, mouseY );

				return ray.intersectPlane( plane, optionalTarget );

			},

			// Given
			getCubeletAtIntersection : (function(){

				var tmp = new THREE.Vector3();

				return function( intersection ){

					//	Translate the world coordinates to a 3D index of the intersected cubelets location.

					tmp.copy( intersection ).add( box.max )
						.multiplyScalar( 3 / cube.size )
						.set( Math.min( tmp.x|0, 2 ), Math.min( 3 - tmp.y|0, 2 ), Math.min( 3 - tmp.z|0, 2 ));

					//	Translate the 3D position to an array index
					return cube.cubelets[ tmp.z * 9 + tmp.y * 3 + tmp.x ];

				};

			}())

		};

		return api;
	};

}());


text:
var _ = require('lodash');

handleObjectMerge = function (configObj, settingObj) {
    if (_.isPlainObject(configObj)) {
        return _.merge(configObj, settingObj);
    } else if (_.isArray(configObj)) {
        return settingObj.concat(configObj);
    } else {
        return settingObj;
    }
};

handleFileMerge = function (configObj, settingObj) {
    if (_.isArray(configObj)) {
        return settingObj.concat(configObj);
    } else {
        return settingObj;
    }
};

var handleConfigType = function (result, value, key, config) {
    if (_.has(result, key)) {
        switch (key) {
            case 'exclude':
            case 'reporters':
            case 'proxies':
            case 'plugins':
            case 'preprocessors':
            case 'coverageReporter':
            case 'client':
            case 'coffeePreprocessor':
            case 'yamlPreprocessor':
            case 'frameworks':
                result[key] = handleObjectMerge(result[key], value, config[key]);
                break;

            case 'files':
                result[key] = handleFileMerge(result[key], value, config[key]);
                break;

            default:
                if (!_.has(config, key)) {
                    result[key] = value;
                }
                break;
        }
        return result;
    } else {
        result[key] = value;
        return result;
    }
};

module.exports = handleConfigType;


text:
module AppDrone
class Dragonfly < Drone
  desc "Rack framework for on-the-fly image handling"
  category :uploads

  depends_on :bundle

  def align
    bundle.add 'rack-cache', require: 'rack/cache'
    bundle.add 'dragonfly'
  end

  def execute
    do! :initializer
  end

end
end


text:
namespace metaforce {
CScriptActorRotate::CScriptActorRotate(TUniqueId uid, std::string_view name, const CEntityInfo& info,
                                       const zeus::CVector3f& rotation, float maxTime, bool updateActors,
                                       bool updateOnCreation, bool active)
: CEntity(uid, info, active, name)
, x34_rotation(rotation)
, x40_maxTime(maxTime)
, x58_26_updateActors(updateActors)
, x58_27_updateOnCreation(updateOnCreation) {}

void CScriptActorRotate::Accept(IVisitor& visitor) { visitor.Visit(this); }

void CScriptActorRotate::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CStateManager& mgr) {
  if (msg == EScriptObjectMessage::Activate) {
    CEntity::AcceptScriptMsg(msg, uid, mgr);
    return;
  }

  if (msg == EScriptObjectMessage::Action || msg == EScriptObjectMessage::Next ||
      (msg == EScriptObjectMessage::Registered && x58_27_updateOnCreation)) {
    UpdateActors(msg == EScriptObjectMessage::Next, mgr);
  }

  CEntity::AcceptScriptMsg(msg, uid, mgr);
}

void CScriptActorRotate::Think(float dt, CStateManager& mgr) {
  if (x58_24_updateRotation && GetActive()) {
    x44_currentTime += dt;
    if (x44_currentTime >= x40_maxTime) {
      x58_24_updateRotation = false;
      x44_currentTime = x40_maxTime;
    }

    const float timeOffset = x44_currentTime / x40_maxTime;

    for (const auto& actorPair : x48_actors) {
      if (const TCastToPtr<CActor> act = mgr.ObjectById(actorPair.first)) {
        const zeus::CTransform xf = zeus::CTransform::RotateZ(zeus::degToRad(timeOffset * x34_rotation.z())) *
                                    zeus::CTransform::RotateY(zeus::degToRad(timeOffset * x34_rotation.y())) *
                                    zeus::CTransform::RotateX(zeus::degToRad(timeOffset * x34_rotation.x()));
        zeus::CTransform localRot = actorPair.second * xf;
        localRot.origin = act->GetTranslation();
        act->SetTransform(localRot);

        if (const TCastToPtr<CScriptPlatform> plat = mgr.ObjectById(actorPair.first)) {
          UpdatePlatformRiders(*plat.GetPtr(), xf, mgr);
        }
      }
    }

    if (x58_24_updateRotation) {
      if (!x58_25_skipSpiderBallWaypoints) {
        UpdateSpiderBallWaypoints(mgr);
      }

      if (x58_26_updateActors) {
        UpdateActors(false, mgr);
      }
    }
  }
}

void CScriptActorRotate::UpdatePlatformRiders(CScriptPlatform& plat, const zeus::CTransform& xf, CStateManager& mgr) {
  UpdatePlatformRiders(plat.GetStaticSlaves(), plat, xf, mgr);
  UpdatePlatformRiders(plat.GetDynamicSlaves(), plat, xf, mgr);
}

void CScriptActorRotate::UpdatePlatformRiders(std::vector<SRiders>& riders, CScriptPlatform& plat,
                                              const zeus::CTransform& xf, CStateManager& mgr) {
  for (SRiders& rider : riders) {
    if (const TCastToPtr<CActor> act = mgr.ObjectById(rider.x0_uid)) {
      zeus::CTransform& riderXf = rider.x8_transform;
      act->SetTransform(rider.x8_transform);
      act->SetTranslation(act->GetTranslation() + plat.GetTranslation());

      if (x58_24_updateRotation) {
        riderXf = {act->GetTransform().basis, act->GetTranslation() - plat.GetTranslation()};

        if (TCastToConstPtr<CScriptSpiderBallWaypoint>(act.GetPtr())) {
          x58_25_skipSpiderBallWaypoints = true;
        }
      }

      if (const TCastToPtr<CScriptPlatform> plat2 = mgr.ObjectById(rider.x0_uid)) {
        UpdatePlatformRiders(*plat2.GetPtr(), xf, mgr);
      }
    }
  }
}

void CScriptActorRotate::UpdateActors(bool next, CStateManager& mgr) {
  if (x58_24_updateRotation) {
    return;
  }

  x48_actors.clear();

  for (const SConnection& conn : x20_conns) {
    if (conn.x0_state != EScriptObjectState::Play || conn.x4_msg != EScriptObjectMessage::Play) {
      continue;
    }

    auto search = mgr.GetIdListForScript(conn.x8_objId);
    for (auto it = search.first; it != search.second; ++it) {
      if (const TCastToConstPtr<CActor> act = mgr.ObjectById(it->second)) {
        x48_actors.insert_or_assign(it->second, act->GetTransform().getRotation());
      }
    }
  }

  SendScriptMsgs(EScriptObjectState::Play, mgr, EScriptObjectMessage::None);

  if (!x48_actors.empty()) {
    x58_24_updateRotation = true;
    x44_currentTime = (next ? x40_maxTime : 0.f);
  }
}

void CScriptActorRotate::UpdateSpiderBallWaypoints(CStateManager& mgr) {
  rstl::reserved_vector<TUniqueId, 1024> waypointIds;
  CObjectList& objectList = mgr.GetAllObjectList();
  for (const CEntity* ent : objectList) {
    if (const TCastToConstPtr<CScriptSpiderBallWaypoint> wp = ent) {
      waypointIds.push_back(wp->GetUniqueId());
    }
  }

  for (const TUniqueId& uid : waypointIds) {
    auto* wp = static_cast<CScriptSpiderBallWaypoint*>(mgr.ObjectById(uid));
    if (wp) {
#if 0
      wp->sub_801187B4(mgr);
      wp->xe4_27_ = true;
#endif
    }
  }

  x58_25_skipSpiderBallWaypoints = false;
}
} // namespace metaforce


text:
define(["Tone/core/Tone", "Tone/event/Part", "Tone/core/Transport"], function (Tone) {

	"use strict";

	/**
	 *  @class A sequence is an alternate notation of a part. Instead
	 *         of passing in an array of [time, event] pairs, pass
	 *         in an array of events which will be spaced at the
	 *         given subdivision. Sub-arrays will subdivide that beat
	 *         by the number of items are in the array.
	 *         Sequence notation inspiration from [Tidal](http://yaxu.org/tidal/)
	 *  @param  {Function}  callback  The callback to invoke with every note
	 *  @param  {Array}    events  The sequence
	 *  @param  {Time} subdivision  The subdivision between which events are placed.
	 *  @extends {Tone.Part}
	 *  @example
	 * var seq = new Tone.Sequence(function(time, note){
	 * 	console.log(note);
	 * //straight quater notes
	 * }, ["C4", "E4", "G4", "A4"], "4n");
	 *  @example
	 * var seq = new Tone.Sequence(function(time, note){
	 * 	console.log(note);
	 * //subdivisions are given as subarrays
	 * }, ["C4", ["E4", "D4", "E4"], "G4", ["A4", "G4"]]);
	 */
	Tone.Sequence = function(){

		var options = this.optionsObject(arguments, ["callback", "events", "subdivision"], Tone.Sequence.defaults);

		//remove the events
		var events = options.events;
		delete options.events;

		Tone.Part.call(this, options);

		/**
		 *  The subdivison of each note
		 *  @type  {Ticks}
		 *  @private
		 */
		this._subdivision = this.toTicks(options.subdivision);

		//if no time was passed in, the loop end is the end of the cycle
		if (this.isUndef(options.loopEnd) && !this.isUndef(events)){
			this._loopEnd = (events.length * this._subdivision);
		}
		//defaults to looping
		this._loop = true;

		//add all of the events
		if (!this.isUndef(events)){
			for (var i = 0; i < events.length; i++){
				this.add(i, events[i]);
			}
		}
	};

	Tone.extend(Tone.Sequence, Tone.Part);

	/**
	 *  The default values.
	 *  @type  {Object}
	 */
	Tone.Sequence.defaults = {
		"subdivision" : "4n",
	};

	/**
	 *  The subdivision of the sequence. This can only be
	 *  set in the constructor. The subdivision is the
	 *  interval between successive steps.
	 *  @type {Time}
	 *  @memberOf Tone.Sequence#
	 *  @name subdivision
	 *  @readOnly
	 */
	Object.defineProperty(Tone.Sequence.prototype, "subdivision", {
		get : function(){
			return Tone.Time(this._subdivision, "i").toNotation();
		}
	});

	/**
	 *  Get/Set an index of the sequence. If the index contains a subarray,
	 *  a Tone.Sequence representing that sub-array will be returned.
	 *  @example
	 * var sequence = new Tone.Sequence(playNote, ["E4", "C4", "F#4", ["A4", "Bb3"]])
	 * sequence.at(0)// => returns "E4"
	 * //set a value
	 * sequence.at(0, "G3");
	 * //get a nested sequence
	 * sequence.at(3).at(1)// => returns "Bb3"
	 * @param {Positive} index The index to get or set
	 * @param {*} value Optionally pass in the value to set at the given index.
	 */
	Tone.Sequence.prototype.at = function(index, value){
		//if the value is an array,
		if (this.isArray(value)){
			//remove the current event at that index
			this.remove(index);
		}
		//call the parent's method
		return Tone.Part.prototype.at.call(this, this._indexTime(index), value);
	};

	/**
	 *  Add an event at an index, if there's already something
	 *  at that index, overwrite it. If `value` is an array,
	 *  it will be parsed as a subsequence.
	 *  @param {Number} index The index to add the event to
	 *  @param {*} value The value to add at that index
	 *  @returns {Tone.Sequence} this
	 */
	Tone.Sequence.prototype.add = function(index, value){
		if (value === null){
			return this;
		}
		if (this.isArray(value)){
			//make a subsequence and add that to the sequence
			var subSubdivision = Math.round(this._subdivision / value.length);
			value = new Tone.Sequence(this._tick.bind(this), value, Tone.Time(subSubdivision, "i"));
		}
		Tone.Part.prototype.add.call(this, this._indexTime(index), value);
		return this;
	};

	/**
	 *  Remove a value from the sequence by index
	 *  @param {Number} index The index of the event to remove
	 *  @returns {Tone.Sequence} this
	 */
	Tone.Sequence.prototype.remove = function(index, value){
		Tone.Part.prototype.remove.call(this, this._indexTime(index), value);
		return this;
	};

	/**
	 *  Get the time of the index given the Sequence's subdivision
	 *  @param  {Number}  index
	 *  @return  {Time}  The time of that index
	 *  @private
	 */
	Tone.Sequence.prototype._indexTime = function(index){
		if (index instanceof Tone.TransportTime){
			return index;
		} else {
			return Tone.TransportTime(index * this._subdivision + this.startOffset, "i");
		}
	};

	/**
	 *  Clean up.
	 *  @return {Tone.Sequence} this
	 */
	Tone.Sequence.prototype.dispose = function(){
		Tone.Part.prototype.dispose.call(this);
		return this;
	};

	return Tone.Sequence;
});


text:
(function() {

    'use strict';

    var app = angular.module('formlyExample', ['formly', 'formlyBootstrap']);

    app.controller('MainCtrl', function MainCtrl() {
        var vm = this;
        vm.model = {};
        vm.fields = [
            {
                type: 'checkbox',
                key: "control",
                templateOptions: {
                    label: 'Click to show'
                }
            },
            {
                type: 'input',
                key: "nothing",
                templateOptions: {
                    label: "Show when checkbox checked"
                },
                expressionProperties: {
                    hide: function($viewValue, $modelValue, scope) {
                        console.log(scope.model.control);
                        return !scope.model.control;
                    }
                }
            }
        ];
    });

})();


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

<title>Player</title>
<meta name="date" content="2016-01-07">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

capstone.element

Class Player

java.lang.Object

capstone.element.Element

capstone.element.Player

public class Player
extends Element

In MVC terms, the Player is the View and a Profile the Model, the
 ProfileWindow possibly acting as the Controller. A Player is thus
 the visual representation of a Profile. A Player is also an Element,
 therefore has a point and a representation that can be rendered on
 the screen. Different from most other Elements, the Player class provides
 a variety of methods to perform motion on the Player's point. Also, a
 Player is defined as having a certain number of lives, the maximum
 and initial count being defined in the static variable MAXIMUM_LIVES
 contained in the Player class. When the life-count of Player goes to
 zero (by repetitive calls to injure()), a Player is said to be "Dead"
 and before that the Player is defined as "Alive". Moreover, for various
 purposes of game-logic a Player has the option of going-back (i.e.
 going to the Point the Player was before its last motion), given the
 Player has performed at least one such motion.

Nested Class Summary

Nested classes/interfaces inherited from class capstone.element.Element

Element.Kind

Field Summary

Fields

Modifier and Type
Field and Description

private int
_lives

private Point
_previousPoint

private Profile
_profile

static int
MAXIMUM_LIVES

Fields inherited from class capstone.element.Element

_kind, _point, _representation

Constructor Summary

Constructors

Constructor and Description

Player(Player other)

Copy-Constructor.

Player(Point point,
      Profile profile)

Constructs the Player at the given Point, with the given Profile.

Method Summary

All Methods Static Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

private static java.lang.String
_empty(int width)

boolean
canGoBack()

boolean
equals(java.lang.Object object)

Checks equality between this Player and an object.

Player
goBack()

Goes back to the previous Point of the Player

 Only allowed if the Player has performed at least one movement.

boolean
hasFullHealth()

void
heal()

Increases the life-count of the Player if possible.

java.lang.String
id()

void
injure()

Reduces the life-count of the Player, given the life-count is non-zero.

boolean
isAlive()

boolean
isDead()

Constraints are such that the life-count will never be negative.

java.lang.Integer
lives()

Player
move(Delta delta)

Moves the Player by the given Delta.

Player
move(Direction direction)

Moves the Player in the given Direction.

Player
move(int dx,
    int dy)

Moves the Player by the given delta-x and delta-y.

Player
moveDown()

Moves the Player in the downward direction.

Player
moveLeft()

Moves the Player in the leftward direction.

Player
moveRight()

Moves the Player in the rightward direction.

Player
moveUp()

Moves the Player in the upward direction.

Point
previousPoint()

Profile
profile()

void
render(com.googlecode.lanterna.screen.Screen screen,
      Region relativeTo)

Renders the Player onto the Screen, relative to the Region.

java.lang.String
toString()

java.lang.String
toString(int width)

Pads the result of toString() such that the Position information
 is right-adjusted and the ID and life-count information is left-
 adjusted.

boolean
wouldGoNegative(Delta delta)

Checks if the Player's Point would go negative on either
 component if the Delta were applied to the Player's Point.

Methods inherited from class capstone.element.Element

_render, Create, kind, point, point, representation, representation, unrender

Methods inherited from class java.lang.Object

clone, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

MAXIMUM_LIVES

public static final int MAXIMUM_LIVES

See Also:

Constant Field Values

_profile

private Profile _profile

_lives

private int _lives

_previousPoint

private Point _previousPoint

Constructor Detail

Player

public Player(Point point,
              Profile profile)

Constructs the Player at the given Point, with the given Profile.

Parameters:

point - The Point at which to construct the Player.

profile - The Profile for the Player.

Player

public Player(Player other)

Copy-Constructor.

Parameters:

other - The other Player.

Method Detail

render

public void render(com.googlecode.lanterna.screen.Screen screen,
                   Region relativeTo)

Renders the Player onto the Screen, relative to the Region.

 A Player has the Property that he/she is given an additional
 styling in that he/she blinks on the screen.

Overrides:

render in class Element

Parameters:

screen - The Screen to render the Element onto.

relativeTo - The Region containing the Element.

injure

public void injure()

Reduces the life-count of the Player, given the life-count is non-zero.

heal

public void heal()

Increases the life-count of the Player if possible.
 The life-count will never be increased past the MAXIMUM_LIVES.

move

public Player move(Direction direction)

Moves the Player in the given Direction.

Parameters:

direction - The Direction to move the Player towards.

Returns:

The modified Player instance (this).

move

public Player move(int dx,
                   int dy)

Moves the Player by the given delta-x and delta-y.

 Non-negativity-constraints are of course
 maintained for the both coordinates.

Parameters:

dx - How much to move the x-component of the Player's point by.

dy - How much to move the y-component of the Player's point by.

Returns:

The modified Player instance (this).

move

public Player move(Delta delta)

Moves the Player by the given Delta.

Parameters:

delta - The Delta to move the Player by.

Returns:

The modified Player instance (this).

moveUp

public Player moveUp()

Moves the Player in the upward direction.

Returns:

The modified Player instance (this).

moveDown

public Player moveDown()

Moves the Player in the downward direction.

Returns:

The modified Player instance (this).

moveLeft

public Player moveLeft()

Moves the Player in the leftward direction.

Returns:

The modified Player instance (this).

moveRight

public Player moveRight()

Moves the Player in the rightward direction.

Returns:

The modified Player instance (this).

goBack

public Player goBack()

Goes back to the previous Point of the Player

 Only allowed if the Player has performed at least one movement.

 The previous point of the Player is not reset, i.e. successive
 calls to goBack() have no effect before any new motion is performed.
 This is a cautionary measure to handle the case where a Player may
 be asked to go back multiple times before having the chance to move
 (like: dynamic-obstacle running against the Player).

Returns:

The modified Player instance (this).

wouldGoNegative

public boolean wouldGoNegative(Delta delta)

Checks if the Player's Point would go negative on either
 component if the Delta were applied to the Player's Point.

Parameters:

delta - The Delta to test.

Returns:

True if the Delta would invalidate the constraints set
         for Points (non-negativity on both components), else true
         if the resulting Point were a valid one, such that move
         can be called with this Delta.

canGoBack

public boolean canGoBack()

Returns:

True if the Player has yet performed
         at least one motion, else false.

previousPoint

public Point previousPoint()

Returns:

The previous point of the player, which is null initially.

id

public java.lang.String id()

Returns:

The ID of the player.

profile

public Profile profile()

Returns:

The Profile of the player.

lives

public java.lang.Integer lives()

Returns:

The number of lives of the Player.

isAlive

public boolean isAlive()

Returns:

True if the life-count of the Player is positive, else false.

isDead

public boolean isDead()

Constraints are such that the life-count will never be negative.

Returns:

True if the life-count of the Player is zero, else false.

hasFullHealth

public boolean hasFullHealth()

Returns:

Whether the Player's life-count is the maximum it can be.

equals

public boolean equals(java.lang.Object object)

Checks equality between this Player and an object.

Overrides:

equals in class Element

Parameters:

object - The object to check equality for.

Returns:

True if the object is a Player with the same ID.

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

Returns:

A string-representation of the Player, of the format:
         ID: life-count/maximum-life-count Lives Position: position
         if the Player is alive, else ID: DEAD

See Also:

toString(int)

toString

public java.lang.String toString(int width)

Pads the result of toString() such that the Position information
 is right-adjusted and the ID and life-count information is left-
 adjusted. The resulting String will have at least the width
 specified.

Parameters:

width - The minimum width the resulting String should have.

Returns:

A string-representation with the same format as the toString()
         method, but with ID and life-count information left-adjusted
         and Position ifnormation right-adjusted to the width.

See Also:

toString()

_empty

private static java.lang.String _empty(int width)

Parameters:

width - How many spaces to create the empty string with.

Returns:

A string with *width*-many space characters if the
         width is non-negative, else an empty string.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2022 Ryo Suzuki
//	Copyright (c) 2016-2022 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# include <Siv3D/Wave.hpp>
# include <Siv3D/AudioDecoder.hpp>
# include <Siv3D/AudioEncoder.hpp>
# include <Siv3D/Dialog.hpp>
# include <Siv3D/EngineLog.hpp>
# include <Siv3D/SoundFont/ISoundFont.hpp>
# include <Siv3D/Common/Siv3DEngine.hpp>
# include <Siv3D/AudioFormat/WAVEEncoder.hpp>
# include <Siv3D/AudioFormat/OggVorbisEncoder.hpp>

namespace s3d
{
	namespace detail
	{
		// https://stackoverflow.com/a/55112294
		inline constexpr size_t DeinterleaveIndex(const size_t i, const size_t length) noexcept
		{
			const size_t mid = (length - length / 2);

			if (i < mid)
			{
				return (i * 2);
			}

			return ((i - mid) * 2 + 1);
		}

		template <class Type>
		inline void Deinterleave(Type* arr, const size_t length) noexcept
		{
			if (length <= 1)
			{
				return;
			}

			for (size_t i = 1; i < length; ++i)
			{
				size_t k = DeinterleaveIndex(i, length);

				while (k < i)
				{
					k = DeinterleaveIndex(k, length);
				}

				std::swap(arr[i], arr[k]);
			}
		}
	}

	Wave::Wave(const FilePathView path, const AudioFormat format)
	{
		*this = AudioDecoder::Decode(path, format);
	}

	Wave::Wave(IReader&& reader, const AudioFormat format)
	{
		*this = AudioDecoder::Decode(reader, format);
	}

	Wave::Wave(const GMInstrument instrument, const uint8 key, const Duration& duration, const double velocity, const Arg::sampleRate_<uint32> sampleRate)
		: Wave{ instrument, key, duration, SecondsF{ 1.0 }, velocity, sampleRate } {}

	Wave::Wave(const GMInstrument instrument, const uint8 key, const Duration& noteOn, const Duration& noteOff, const double velocity, const Arg::sampleRate_<uint32> sampleRate)
	{
		*this = SIV3D_ENGINE(SoundFont)->render(instrument, key, noteOn, noteOff, velocity, sampleRate);
	}

	Wave& Wave::swapLR() noexcept
	{
		for (auto& sample : m_data)
		{
			sample.swapChannel();
		}

		return *this;
	}

	Wave& Wave::removeSilenceFromBeginning()
	{
		size_t count = 0;

		for (auto it = m_data.begin(); it != m_data.end(); ++it)
		{
			if (it->left || it->right)
			{
				break;
			}

			++count;
		}

		if (2 <= count)
		{
			m_data.pop_front_N(count - 1);
		}

		return *this;
	}

	Wave& Wave::removeSilenceFromEnd()
	{
		size_t count = 0;

		for (auto it = m_data.rbegin(); it != m_data.rend(); ++it)
		{
			if (it->left || it->right)
			{
				break;
			}

			++count;
		}

		if (2 <= count)
		{
			m_data.pop_back_N(count - 1);
		}

		return *this;
	}

	Wave& Wave::fadeIn(size_t samples) noexcept
	{
		if (not m_data)
		{
			return *this;
		}

		samples = Min(samples, m_data.size());

		const float delta = (1.0f / samples);
		WaveSample* pDst = m_data.data();

		for (size_t i = 0; i < samples; ++i)
		{
			*pDst++ *= (delta * i);
		}

		return *this;
	}

	Wave& Wave::fadeOut(size_t samples) noexcept
	{
		if (not m_data)
		{
			return *this;
		}

		samples = Min(samples, m_data.size());

		const float delta = (1.0f / samples);
		WaveSample* pDst = &m_data.back();

		for (size_t i = 0; i < samples; ++i)
		{
			*pDst-- *= (delta * i);
		}

		return *this;
	}

	void Wave::deinterleave() noexcept
	{
		detail::Deinterleave(&m_data[0].left, m_data.size() * 2);
	}

	bool Wave::save(const FilePathView path, const AudioFormat format) const
	{
		return AudioEncoder::Save(*this, format, path);
	}

	Blob Wave::encode(const AudioFormat format) const
	{
		return AudioEncoder::Encode(*this, format);
	}

	bool Wave::saveWithDialog() const
	{
		if (isEmpty())
		{
			LOG_FAIL(U"Wave::saveWithDialog(): Wave is empty");
			return false;
		}

		if (const auto path = Dialog::SaveWave())
		{
			return save(*path);
		}
		else
		{
			return false;
		}
	}

	bool Wave::saveWAVE(const FilePathView path, const WAVEFormat format) const
	{
		return WAVEEncoder{}.save(*this, path, format);
	}

	Blob Wave::encodeWAVE(const WAVEFormat format) const
	{
		return WAVEEncoder{}.encode(*this, format);
	}

	bool Wave::saveOggVorbis(const FilePathView path, const int32 quality, const AudioLoopTiming& loopTiming) const
	{
		return OggVorbisEncoder{}.save(*this, path, quality, loopTiming);
	}

	Blob Wave::encodeOggVorbis(const int32 quality, const AudioLoopTiming& loopTiming) const
	{
		return OggVorbisEncoder{}.encode(*this, quality, loopTiming);
	}

	Wave& Wave::fill(const value_type& value)
	{
		m_data.fill(value);

		return *this;
	}

	Wave& Wave::append(const Array<value_type>& other)
	{
		m_data.insert(end(), other.begin(), other.end());

		return *this;
	}

	Wave& Wave::append(const Wave& other)
	{
		m_data.insert(end(), other.begin(), other.end());

		return *this;
	}

	Wave& Wave::remove_at(const size_t index)
	{
		m_data.remove_at(index);

		return *this;
	}

	Wave& Wave::reverse()
	{
		m_data.reverse();

		return *this;
	}

	Wave Wave::reversed() const
	{
		return Wave(rbegin(), rend());
	}

	Wave Wave::slice(const size_t index) const
	{
		if (index >= size())
		{
			return{};
		}

		return Wave(begin() + index, end());
	}

	Wave Wave::slice(const size_t index, const size_t length) const
	{
		if (index >= size())
		{
			return{};
		}

		return Wave(begin() + index, begin() + Min(index + length, size()));
	}
}


text:
@interface ScreenshotMetricsRecorder : NSObject

// Will start recording UMA metrics.
- (void)startRecordingMetrics;

@end

#endif  // IOS_CHROME_BROWSER_SCREENSHOT_SCREENSHOT_METRICS_RECORDER_H_


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Torrey bot. Club 34: 475 (1907)

#### Original name
Trametes williamsii Murrill

### Remarks
null


text:
using Discord.Commands;
using System;
using System.Threading.Tasks;

namespace NoAdsHere.Common.Preconditions
{
    public class HiddenAttribute : PreconditionAttribute
    {
        public override Task<PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command,
            IServiceProvider services) => Task.FromResult(PreconditionResult.FromSuccess());
    }
}


text:
module GravatarImageTag

  class << self
    attr_accessor :configuration
  end

  def self.configuration
    @configuration ||= Configuration.new
  end

  def self.configure
    yield(configuration)
  end

  class Configuration
     attr_accessor :default_image, :filetype, :include_size_attributes,
       :rating, :size, :secure

     def initialize
        @include_size_attributes = true
     end
  end

  def self.included(base)
    GravatarImageTag.configure { |c| nil }
    base.extend ClassMethods
    base.send :include, InstanceMethods
  end

  module ClassMethods
    def default_gravatar_filetype=(value)
      warn "DEPRECATION WARNING: configuration of filetype= through this method is deprecated! Use the block configuration instead. http://github.com/mdeering/gravatar_image_tag"
      GravatarImageTag.configure do |c|
        c.filetype = value
      end
    end
    def default_gravatar_image=(value)
      warn "DEPRECATION WARNING: configuration of default_gravatar_image= through this method is deprecated! Use the block configuration instead. http://github.com/mdeering/gravatar_image_tag"
      GravatarImageTag.configure do |c|
        c.default_image = value
      end
    end
    def default_gravatar_rating=(value)
      warn "DEPRECATION WARNING: configuration of default_gravatar_rating= through this method is deprecated! Use the block configuration instead. http://github.com/mdeering/gravatar_image_tag"
      GravatarImageTag.configure do |c|
        c.rating = value
      end
    end
    def default_gravatar_size=(value)
      warn "DEPRECATION WARNING: configuration of default_gravatar_size= through this method is deprecated! Use the block configuration instead. http://github.com/mdeering/gravatar_image_tag"
      GravatarImageTag.configure do |c|
        c.size = value
      end
    end
    def secure_gravatar=(value)
      warn "DEPRECATION WARNING: configuration of secure_gravatar= through this method is deprecated! Use the block configuration instead. http://github.com/mdeering/gravatar_image_tag"
      GravatarImageTag.configure do |c|
        c.secure = value
      end
    end
  end

  module InstanceMethods
    def gravatar_image_tag(email, options = {})
      gravatar_overrides = options.delete(:gravatar)
      options[:src] = gravatar_image_url(email, gravatar_overrides)
      options[:alt] ||= 'Gravatar'
      if GravatarImageTag.configuration.include_size_attributes
        size = GravatarImageTag::gravatar_options(gravatar_overrides)[:size] || 80
        options[:height] = options[:width] = size.to_s
      end

      # Patch submitted to rails to allow image_tag here
      # https://rails.lighthouseapp.com/projects/8994/tickets/2878
      tag 'img', options, false, false
    end

    def gravatar_image_url(email, gravatar_overrides = {})
      email = email.strip.downcase if email.is_a? String
      GravatarImageTag::gravatar_url(email, gravatar_overrides)
    end
  end

  def self.gravatar_url(email, overrides = {})
    gravatar_params = gravatar_options(overrides || {})
    url_base        = gravatar_url_base(gravatar_params.delete(:secure))
    hash            = gravatar_id(email, gravatar_params.delete(:filetype))
    url_params      = url_params(gravatar_params)
    "#{url_base}/#{hash}#{url_params}"
  end

  private

    def self.gravatar_options(overrides = {})
      {
        :default  => GravatarImageTag.configuration.default_image,
        :filetype => GravatarImageTag.configuration.filetype,
        :rating   => GravatarImageTag.configuration.rating,
        :secure   => GravatarImageTag.configuration.secure,
        :size     => GravatarImageTag.configuration.size
      }.merge(overrides || {}).delete_if { |key, value| value.nil? }
    end

    def self.gravatar_url_base(secure = false)
      'http' + (!!secure ? 's://secure.' : '://') + 'gravatar.com/avatar'
    end

    def self.gravatar_id(email, filetype = nil)
      return nil unless email
      "#{ Digest::MD5.hexdigest(email) }#{ ".#{filetype}" unless filetype.nil? }"
    end

    def self.url_params(gravatar_params)
      return nil if gravatar_params.keys.size == 0
      array = gravatar_params.map { |k, v| "#{k}=#{value_cleaner(v)}" }
      "?#{array.join('&')}"
    end

    def self.value_cleaner(value)
      value = value.to_s
      URI.escape(value, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
    end

end

ActionView::Base.send(:include, GravatarImageTag) if defined?(ActionView::Base)


text:
package org.elasticsearch.zeromq;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestResponse;
import org.zeromq.ZMQException;

/**
 * @author tlrx
 */
public class ZMQRestImpl extends AbstractComponent {

	private final RestController restController;

	@Inject
	public ZMQRestImpl(Settings settings, RestController restController) {
		super(settings);
		this.restController = restController;
	}

	public ZMQRestResponse process(ZMQRestRequest request){

		final CountDownLatch latch = new CountDownLatch(1);
        final AtomicReference<ZMQRestResponse> ref = new AtomicReference<ZMQRestResponse>();

		this.restController.dispatchRequest(request, new RestChannel() {

			@Override
			public void sendResponse(RestResponse response) {
				try {
					if(logger.isTraceEnabled()){
						logger.info("Response to ØMQ client: {}", new String(response.content()));
					}
					ref.set(convert(response));
				} catch (IOException e) {
					// ignore
				}
				latch.countDown();
			}
		});

		try {
            latch.await();
            return ref.get();
        } catch (Exception e) {
            throw new ZMQException("failed to generate response", 0);
        }
	}

	private ZMQRestResponse convert(RestResponse response) throws IOException {
		ZMQRestResponse zmqResponse = new ZMQRestResponse(response.status());

		if(response.contentType() != null){
			zmqResponse.setContentType(response.contentType());
		}
        if (response.contentLength() > 0) {
            if (response.contentThreadSafe()) {
            	zmqResponse.setBody(ByteBuffer.wrap(response.content(), 0, response.contentLength()));
            } else {
                // argh!, we need to copy it over since we are not on the same thread...
                byte[] body = new byte[response.contentLength()];
                System.arraycopy(response.content(), 0, body, 0, response.contentLength());
                zmqResponse.setBody(ByteBuffer.wrap(body));
            }
        }
        return zmqResponse;
    }
}


text:
                    {{nxt.title}}

        <googlemaps ng-if="nxt.place && nxt.place.address" class="google-maps" options="map"></googlemaps>
{{nxt.place.address}}

300}"  data-ng-if="nxt.text && !over.next" marked="nxt.text">

            <embed-video ng-if="nxt.video" href="{{nxt.video}}" width="320px" height="240px"></embed-video>

{{next.letter}}


text:
package basic

import (
	"github.com/tmacychen/UFG/framework"
	"github.com/tmacychen/UFG/widget"
	"github.com/tmacychen/UFG/math"
)

func createLabel(theme *Theme) framework.Label {
	l := &widget.Label{}
	l.Init(l, theme, theme.DefaultFont(), theme.LabelStyle.FontColor)
	l.SetMargin(math.Spacing{L: 3, T: 3, R: 3, B: 3})
	println("create label end")
	return l
}


text:
var app = angular.module(uberfireAngularAppName, []);
var ids_components = new Array();
var ids_perspectives = new Array();
uberfireAsExternalLibrary = true;
var parameters_components = {};
var parameters_perspectives = {};
app.directive('uberfirecomponent', function () {
    return {
        restrict: 'AE',
        replace: true,
        scope: {
            screen: '@'
        },
        template:  "

",
        link: function (scope, elem, attrs) {
            callUFComponent(attrs.id);
        }
    };
});

app.directive('uberfireperspective', function () {
    return {
        restrict: 'AE',
        replace: true,
        scope: {
            screen: '@'
        },
        template:  "

",
        link: function (scope, elem, attrs) {
            callUFPerspective(attrs.id);
        }
    };
});

function callUFPerspective(_id, _screenName) {
    prepareUfDataPerspective(_id, _screenName);
    waitForUFPerspective();
}

function callUFComponent(_id, _screenName) {
    prepareUfDataComponent(_id, _screenName);
    waitForUFComponent();
}

function prepareUfDataComponent(_id){
    ids_components.push(_id);
    var parameter = {};
    Array.prototype.slice.call(document.getElementById(_id).attributes).forEach(function(item) {
        parameter[item.name] = item.value;
    });
    parameters_components[_id] = parameter;
}
function prepareUfDataPerspective(_id){
    ids_perspectives.push(_id);
    var parameter = {};
    Array.prototype.slice.call(document.getElementById(_id).attributes).forEach(function(item) {
        parameter[item.name] = item.value;
    });
    parameters_perspectives[_id] = parameter;
}

function waitForUFPerspective() {
    if (typeof $uf_load_perspective == 'function') {
        while (ids_perspectives.length > 0) {
            var id = ids_perspectives.pop();
            $uf_load_perspective(parameters_perspectives[id])
        }
    }
    else {
        window.setTimeout(waitForUFPerspective, 1000);
    }
}

function waitForUFComponent() {
    if (typeof $uf_load_component == 'function') {
        while (ids_components.length > 0) {
            var id = ids_components.pop();
            $uf_load_component(parameters_components[id])
        }
    }
    else {
        window.setTimeout(waitForUFComponent, 1000);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json4.Converters;
using NUnit.Framework;

namespace Newtonsoft.Json4.Tests.Converters
{
  public class CustomCreationConverterTests : TestFixtureBase
  {
    public interface IPerson
    {
      string FirstName { get; set; }
      string LastName { get; set; }
      DateTime BirthDate { get; set; }
    }

    public class Employee : IPerson
    {
      public string FirstName { get; set; }
      public string LastName { get; set; }
      public DateTime BirthDate { get; set; }

      public string Department { get; set; }
      public string JobTitle { get; set; }
    }

    public class PersonConverter : CustomCreationConverter<IPerson>
    {
      public override IPerson Create(Type objectType)
      {
        return new Employee();
      }
    }

    public void DeserializeObject()
    {
      string json = JsonConvert.SerializeObject(new List<Employee>
        {
          new Employee
            {
              BirthDate = new DateTime(1977, 12, 30, 1, 1, 1, DateTimeKind.Utc),
              FirstName = "Maurice",
              LastName = "Moss",
              Department = "IT",
              JobTitle = "Support"
            },
          new Employee
            {
              BirthDate = new DateTime(1978, 3, 15, 1, 1, 1, DateTimeKind.Utc),
              FirstName = "Jen",
              LastName = "Barber",
              Department = "IT",
              JobTitle = "Manager"
            }
        }, Formatting.Indented);

      //[
      //  {
      //    "FirstName": "Maurice",
      //    "LastName": "Moss",
      //    "BirthDate": "\/Date(252291661000)\/",
      //    "Department": "IT",
      //    "JobTitle": "Support"
      //  },
      //  {
      //    "FirstName": "Jen",
      //    "LastName": "Barber",
      //    "BirthDate": "\/Date(258771661000)\/",
      //    "Department": "IT",
      //    "JobTitle": "Manager"
      //  }
      //]

      List<IPerson> people = JsonConvert.DeserializeObject<List<IPerson>>(json, new PersonConverter());

      IPerson person = people[0];

      Console.WriteLine(person.GetType());
      // Newtonsoft.Json4.Tests.Employee

      Console.WriteLine(person.FirstName);
      // Maurice

      Employee employee = (Employee)person;

      Console.WriteLine(employee.JobTitle);
      // Support
    }

    public class MyClass
    {
      public string Value { get; set; }

      [JsonConverter(typeof(MyThingConverter))]
      public IThing Thing { get; set; }
    }

    public interface IThing
    {
      int Number { get; }
    }

    public class MyThing : IThing
    {
      public int Number { get; set; }
    }

    public class MyThingConverter : CustomCreationConverter<IThing>
    {
      public override IThing Create(Type objectType)
      {
        return new MyThing();
      }
    }

    [Test]
    public void AssertDoesDeserialize()
    {
      const string json = @"{
""Value"": ""A value"",
""Thing"": {
""Number"": 123
}
}
";
      MyClass myClass = JsonConvert.DeserializeObject<MyClass>(json);
      Assert.IsNotNull(myClass);
      Assert.AreEqual("A value", myClass.Value);
      Assert.IsNotNull(myClass.Thing);
      Assert.AreEqual(123, myClass.Thing.Number);
    }

    [Test]
    public void AssertShouldSerializeTest()
    {
      MyClass myClass = new MyClass
      {
        Value = "Foo",
        Thing = new MyThing { Number = 456, }
      };
      string json = JsonConvert.SerializeObject(myClass); // <-- Exception here

      const string expected = @"{""Value"":""Foo"",""Thing"":{""Number"":456}}";
      Assert.AreEqual(expected, json);
    }

    internal interface IRange<T>
    {
      T First { get; }
      T Last { get; }
    }

    internal class Range<T> : IRange<T>
    {
      public T First { get; set; }
      public T Last { get; set; }
    }

    internal class NullInterfaceTestClass
    {
      public virtual Guid Id { get; set; }
      public virtual int? Year { get; set; }
      public virtual string Company { get; set; }
      public virtual IRange<decimal> DecimalRange { get; set; }
      public virtual IRange<int> IntRange { get; set; }
      public virtual IRange<decimal> NullDecimalRange { get; set; }
    }

    internal class DecimalRangeConverter : CustomCreationConverter<IRange<decimal>>
    {
      public override IRange<decimal> Create(Type objectType)
      {
        return new Range<decimal>();
      }
    }

    internal class IntRangeConverter : CustomCreationConverter<IRange<int>>
    {
      public override IRange<int> Create(Type objectType)
      {
        return new Range<int>();
      }
    }

    [Test]
    public void DeserializeAndConvertNullValue()
    {
      NullInterfaceTestClass initial = new NullInterfaceTestClass
      {
        Company = "Company!",
        DecimalRange = new Range<decimal> { First = 0, Last = 1 },
        Id = new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11),
        IntRange = new Range<int> { First = int.MinValue, Last = int.MaxValue },
        Year = 2010,
        NullDecimalRange = null
      };

      string json = JsonConvert.SerializeObject(initial, Formatting.Indented);

      Assert.AreEqual(@"{
  ""Id"": ""00000001-0002-0003-0405-060708090a0b"",
  ""Year"": 2010,
  ""Company"": ""Company!"",
  ""DecimalRange"": {
    ""First"": 0.0,
    ""Last"": 1.0
  },
  ""IntRange"": {
    ""First"": -2147483648,
    ""Last"": 2147483647
  },
  ""NullDecimalRange"": null
}", json);

      NullInterfaceTestClass deserialized = JsonConvert.DeserializeObject<NullInterfaceTestClass>(
        json, new IntRangeConverter(), new DecimalRangeConverter());

      Assert.AreEqual("Company!", deserialized.Company);
      Assert.AreEqual(new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), deserialized.Id);
      Assert.AreEqual(0, deserialized.DecimalRange.First);
      Assert.AreEqual(1, deserialized.DecimalRange.Last);
      Assert.AreEqual(int.MinValue, deserialized.IntRange.First);
      Assert.AreEqual(int.MaxValue, deserialized.IntRange.Last);
      Assert.AreEqual(null, deserialized.NullDecimalRange);
      Assert.AreEqual(2010, deserialized.Year);
    }
  }
}


text:
package org.intellij.sdk.language;

import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.util.ProcessingContext;
import org.intellij.sdk.language.psi.SimpleTypes;
import org.jetbrains.annotations.NotNull;

public class SimpleCompletionContributor extends CompletionContributor {

  public SimpleCompletionContributor() {
    extend(CompletionType.BASIC, PlatformPatterns.psiElement(SimpleTypes.VALUE),
            new CompletionProvider<CompletionParameters>() {
              public void addCompletions(@NotNull CompletionParameters parameters,
                                         @NotNull ProcessingContext context,
                                         @NotNull CompletionResultSet resultSet) {
                resultSet.addElement(LookupElementBuilder.create("Hello"));
              }
            }
    );
  }

}


text:
/* Author: Robert Gazdziak (gazdzia2) */
/* Collaborated with: Thomas Lesniak (tlesnia2) */

import java.util.Random;
import java.util.ArrayList;

public class QLearningAgent implements Agent {
  public QLearningAgent() {
    this.rand = new Random();
  }

  public void initialize(int numOfStates, int numOfActions) {
    this.q = new double[numOfStates][numOfActions];
    this.numOfStates = numOfStates;
    this.numOfActions = numOfActions;
  }
//Returns best possible action (or random action of multiple best actions)
  private int bestUtility(int state) {
		double max = q[state][0];
		//Array list that holds best actions
		  ArrayList<Integer> bestActions = new ArrayList<Integer>();
		  bestActions.add(0);
		  for(int i = 1; i<numOfActions; i++) {
			  //if greater than max, clear list and put this action on
			  if(q[state][i] > max) {
				  max = q[state][i];
				  bestActions.clear();
				  bestActions.add(i);
			  }
			  //If equal, add on to the list
			  else if(q[state][i] == max) {
				  bestActions.add(i);
			  }
		  }
		  //Choose random action from list of best actions
		  int action = rand.nextInt(bestActions.size());
		  return bestActions.get(action);
	}
  //Returns best possible action or random action depending on epsilon
  public int chooseAction(int state) {
	  //Random double for epsilon-greedy
	  double greedy = rand.nextDouble();
	  int action = 0;
	  //if smaller, choose (one of the possible) best option(s)
	  if(greedy < (1.0-epsilon))
		  action = bestUtility(state);
	  //If equal or larger choose random action
	  else
		  action = rand.nextInt(numOfActions);
	  return action;
  }
//update the policy of oldState+action
  public void updatePolicy(double reward, int action,
                           int oldState, int newState) {
	  q[oldState][action] = q[oldState][action] +
			  rate*(reward+discount*(q[newState][chooseAction(newState)]-q[oldState][action]));
  }
//Returns best policy for every state
  public Policy getPolicy() {
	  int[] actions = new int[numOfStates];
	  //run through all states
	  for(int i = 0; i<numOfStates; i++) {
		  //for each state pick the best action
		  actions[i] = bestUtility(i);
	  }
	  return new Policy(actions);
  }

  private static final double discount = 0.9;
  private static final double rate = 0.1;
  private static final double epsilon = 0.00;

  private Random rand;
  private int numOfStates;
  private int numOfActions;
  private double[][] q;
}


text:
import json
from utils.csv_stuff import write_to_csv

def format_json_from_locations(locations):
    # Set vehicles.
    instance = {"vehicles": []}
    for i in range(len(locations["vehicles"]["coordinates"])):
        instance["vehicles"].append(
            {
                "id": i + 1,
                "start": locations["vehicles"]["coordinates"][i],
                "end": locations["vehicles"]["coordinates"][i],
            }
        )

        if ("names" in locations["vehicles"]) and (
            locations["vehicles"]["names"][i] is not None
        ):
            instance["vehicles"][-1]["startDescription"] = locations["vehicles"][
                "names"
            ][i]
            instance["vehicles"][-1]["endDescription"] = locations["vehicles"]["names"][
                i
            ]

    # Set jobs.
    job_coords = []
    if ("jobs" in locations) and (len(locations["jobs"]["coordinates"]) > 0):
        job_coords = locations["jobs"]["coordinates"]
        instance["jobs"] = []

    j = len(job_coords)
    for i in range(j):
        current = {"id": i + 1, "location": job_coords[i]}
        if ("names" in locations["jobs"]) and (
            locations["jobs"]["names"][i] is not None
        ):
            current["description"] = locations["jobs"]["names"][i]
        instance["jobs"].append(current)

    # Set shipments.
    shipment_coords = []
    if ("shipments" in locations) and (len(locations["shipments"]["coordinates"]) > 0):
        shipment_coords = locations["shipments"]["coordinates"]
        instance["shipments"] = []

    s = round(len(shipment_coords) / 2)
    for i in range(s):
        current = {
            "pickup": {"id": j + 2 * i + 1, "location": shipment_coords[2 * i]},
            "delivery": {"id": j + 2 * i + 2, "location": shipment_coords[2 * i + 1]},
        }
        if "names" in locations["shipments"]:
            if locations["shipments"]["names"][2 * i] is not None:
                current["pickup"]["description"] = locations["shipments"]["names"][
                    2 * i
                ]
            if locations["shipments"]["names"][2 * i + 1] is not None:
                current["delivery"]["description"] = locations["shipments"]["names"][
                    2 * i + 1
                ]

        instance["shipments"].append(current)

    return instance

def format_geojson_from_locations(locations):
    geo_content = {"type": "FeatureCollection", "features": []}

    for key in locations:
        for i in range(len(locations[key]["coordinates"])):
            current = {
                "type": "Feature",
                "properties": {"id": i, "status": key, "name": key + " " + str(i)},
                "geometry": {
                    "type": "Point",
                    "coordinates": locations[key]["coordinates"][i],
                },
            }
            if ("names" in locations[key]) and (locations[key]["names"][i] is not None):
                # Override if name is known
                current["properties"]["name"] = locations[key]["names"][i]

            geo_content["features"].append(current)

    return geo_content

def write_files(file_name, locations, geojson, csv):
    json_input = format_json_from_locations(locations)

    with open(file_name + ".json", "w") as out:
        print("Writing problem to " + file_name + ".json")
        json.dump(json_input, out, indent=2)
    if geojson:
        with open(file_name + ".geojson", "w") as out:
            print("Writing geojson file to " + file_name + ".geojson")
            json.dump(format_geojson_from_locations(locations), out, indent=2)

    if csv:
        write_to_csv(file_name, json_input)


text:
package udf

import (
	"fmt"
	"github.com/viant/toolbox"
	"github.com/viant/toolbox/data"
	"gopkg.in/yaml.v2"
	"strings"
)

//AsInt converts source into int
func AsInt(source interface{}, state data.Map) (interface{}, error) {
	return toolbox.ToInt(source)
}

//AsInt converts source into int
func AsString(source interface{}, state data.Map) (interface{}, error) {
	isNonByteSlice := toolbox.IsSlice(source)
	if isNonByteSlice {
		if _, isByteArray := source.([]byte); isByteArray {
			isNonByteSlice = false
		}
	}
	if isNonByteSlice || toolbox.IsMap(source) || toolbox.IsStruct(source) {
		text, err := toolbox.AsJSONText(source)
		if err == nil {
			return text, nil
		}
	}
	if toolbox.IsNumber(source) {
		source, _ = AsNumber(source, state)
	}

	return toolbox.AsString(source), nil
}

//Lower converts string to lower case
func ToLower(source interface{}, state data.Map) (interface{}, error) {
	return strings.ToLower(toolbox.AsString(source)), nil
}

//Lower converts string to upper case
func ToUpper(source interface{}, state data.Map) (interface{}, error) {
	return strings.ToUpper(toolbox.AsString(source)), nil
}

//AsFloat converts source into float64
func AsFloat(source interface{}, state data.Map) (interface{}, error) {
	return toolbox.AsFloat(source), nil
}

//AsFloat32 converts source into float32
func AsFloat32(source interface{}, state data.Map) (interface{}, error) {
	return float32(toolbox.AsFloat(source)), nil
}

//AsFloat32 converts source into float32
func AsFloat32Ptr(source interface{}, state data.Map) (interface{}, error) {
	result := float32(toolbox.AsFloat(source))
	return &result, nil
}

//AsBool converts source into bool
func AsBool(source interface{}, state data.Map) (interface{}, error) {
	return toolbox.AsBoolean(source), nil
}

//AsMap converts source into map
func AsMap(source interface{}, state data.Map) (interface{}, error) {
	if source == nil || toolbox.IsMap(source) {
		return source, nil
	}
	source = convertToTextIfNeeded(source)
	if text, ok := source.(string); ok {
		text = strings.TrimSpace(text)
		aMap := map[string]interface{}{}
		if strings.HasPrefix(text, "{") || strings.HasSuffix(text, "}") {
			if err := toolbox.NewJSONDecoderFactory().Create(strings.NewReader(text)).Decode(&aMap); err != nil {
				return nil, err
			}
		}
		if err := yaml.NewDecoder(strings.NewReader(toolbox.AsString(source))).Decode(&aMap); err != nil {
			return nil, err
		}
		return toolbox.NormalizeKVPairs(aMap)
	}
	return toolbox.ToMap(source)
}

//AsCollection converts source into a slice
func AsCollection(source interface{}, state data.Map) (interface{}, error) {
	if source == nil || toolbox.IsSlice(source) {
		return source, nil
	}
	source = convertToTextIfNeeded(source)
	if text, ok := source.(string); ok {
		text = strings.TrimSpace(text)
		if strings.HasPrefix(text, "[") || strings.HasSuffix(text, "[") {
			aSlice := []interface{}{}
			if err := toolbox.NewJSONDecoderFactory().Create(strings.NewReader(text)).Decode(&aSlice); err != nil {
				return nil, err
			}
		}
		var aSlice interface{}
		if err := yaml.NewDecoder(strings.NewReader(toolbox.AsString(source))).Decode(&aSlice); err != nil {
			return nil, err
		}
		return toolbox.NormalizeKVPairs(aSlice)
	}
	return nil, fmt.Errorf("unable convert to slice, unsupported type: %T", source)
}

//AsData converts source into map or slice
func AsData(source interface{}, state data.Map) (interface{}, error) {
	if source == nil || toolbox.IsMap(source) || toolbox.IsSlice(source) {
		return source, nil
	}
	var aData interface{}
	source = convertToTextIfNeeded(source)
	if text, ok := source.(string); ok {
		text = strings.TrimSpace(text)
		if strings.HasPrefix(text, "[") || strings.HasSuffix(text, "[") || strings.HasPrefix(text, "{") || strings.HasSuffix(text, "}") {
			if err := toolbox.NewJSONDecoderFactory().Create(strings.NewReader(text)).Decode(&aData); err != nil {
				return nil, err
			}
		}
		if err := yaml.NewDecoder(strings.NewReader(toolbox.AsString(source))).Decode(&aData); err != nil {
			return nil, err
		}
		return toolbox.NormalizeKVPairs(aData)
	}
	return source, nil
}

func convertToTextIfNeeded(data interface{}) interface{} {
	if data == nil {
		return data
	}
	if bs, ok := data.([]byte); ok {
		return string(bs)
	}
	return data
}

//AsJSON converts source to JSON
func AsJSON(source interface{}, state data.Map) (interface{}, error) {
	return toolbox.AsIndentJSONText(source)
}

//Type returns source type
func Type(source interface{}, state data.Map) (interface{}, error) {
	return fmt.Printf("%T", source)
}

//AsStringMap returns map[string]string
func AsStringMap(source interface{}, state data.Map) (interface{}, error) {
	if source == nil && !toolbox.IsMap(source) {
		return nil, fmt.Errorf("not a map")
	}
	var result = make(map[string]string)
	for k, v := range toolbox.AsMap(source) {
		result[k] = toolbox.AsString(v)
	}
	return result, nil
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<sect1 xml:id="ClientSecurity" version="5.0"
       xmlns="http://docbook.org/ns/docbook"
       xmlns:xi="http://www.w3.org/2001/XInclude"
       xmlns:xlink="http://www.w3.org/1999/xlink"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://docbook.org/ns/docbook http://www.docbook.org/xml/5.0/xsd/docbook.xsd
       http://www.w3.org/1999/xlink http://www.w3.org/1999/xlink.xsd">
    <title>Native Client Security</title>
    <para>Hazelcast's Client security includes both authentication and authorization.</para>

    <sect2>
        <title>Authentication</title>
        <para>Authentication mechanism just works the same as cluster member authentication. Implementation of client
            authentication requires a
            <literal>Credentials</literal>
            and one or more
            <literal>LoginModule</literal>(s). Client side does not have/need a factory object to
            create
            <literal>Credentials</literal>
            objects like<literal>ICredentialsFactory</literal>.
            <literal>Credentials</literal>
            must be created at client side and sent to connected node
            during connection process.
            <programlisting language="xml"><![CDATA[
<security enabled="true">
    <client-login-modules>
        <login-module class-name="com.hazelcast.examples.MyRequiredClientLoginModule" usage="required">
            <properties>
                <property name="property3">value3</property>
            </properties>
        </login-module>
        <login-module class-name="com.hazelcast.examples.MySufficientClientLoginModule" usage="sufficient">
            <properties>
                <property name="property4">value4</property>
            </properties>
        </login-module>
        <login-module class-name="com.hazelcast.examples.MyOptionalClientLoginModule" usage="optional">
            <properties>
                <property name="property5">value5</property>
            </properties>
        </login-module>
    </client-login-modules>
    ...
</security>
]]></programlisting>
        </para>
        <para>You can define as many as<literal>LoginModule</literal>s you wanted in
            configuration. Those are executed in given order. Usage attribute has 4 values; 'required',
            'requisite', 'sufficient' and 'optional' as defined in
            javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag.
        </para>

        <para>
            <programlisting language="java"><![CDATA[
final Credentials credentials = new UsernamePasswordCredentials("dev", "dev-pass");
HazelcastInstance client = HazelcastClient.newHazelcastClient(credentials, "localhost");
]]></programlisting>
        </para>
    </sect2>

    <sect2>
        <title>Authorization</title>
        <para>Hazelcast client authorization is configured by a client permission policy. Hazelcast has a default
            permission policy
            implementation that uses permission configurations defined in Hazelcast security configuration. Default
            policy permission checks are done
            against instance types (map, queue...), instance names (map, queue etc. name), instance actions (put, get,
            remove, add...),
            client endpoint addresses and client principal defined by
            <literal>Credentials</literal>
            object.
            <emphasis role="italic">Instance and principal names and endpoint addresses
                can be defined as wildcards(*). Take a look at
                <link xlink:href="#WildcardConfiguration">Wildcard Name Configuration</link>
                and
                <link xlink:href="#ConfigSpecifyInterfaces">Newtwork Configuration</link>
                pages.
            </emphasis>
        </para>

        <para>
            <programlisting language="xml"><![CDATA[
<security enabled="true">
    <client-permissions>

        <all-permissions principal="admin">
            <endpoints>
                <endpoint>127.0.0.1</endpoint>
            </endpoints>
        </all-permissions>

        <map-permission name="default" principal="dev">
            <actions>
                <action>create</action>
                <action>destroy</action>
                <action>put</action>
                <action>get</action>
            </actions>
        </map-permission>

        <map-permission name="com.foo.entity.*">
            <endpoints>
                <endpoint>10.10.*.*</endpoint>
                <endpoint>127.0.0.1</endpoint>
            </endpoints>
            <actions>
                <action>put</action>
                <action>get</action>
                <action>remove</action>
            </actions>
        </map-permission>

        <queue-permission name="*" principal="dev">
            <endpoints>
                <endpoint>192.168.1.1-100</endpoint>
                <endpoint>192.168.2.*</endpoint>
            </endpoints>
            <actions>
                <action>create</action>
                <action>offer</action>
                <action>poll</action>
            </actions>
        </queue-permission>

        <transaction-permission />
    </client-permissions>
</security>
]]></programlisting>
        </para>

        <para>Users also can define their own policy by implementing<literal>
            com.hazelcast.security.IPermissionPolicy</literal>.
            <programlisting language="java"><![CDATA[
package com.hazelcast.security;
/**
 * IPermissionPolicy is used to determine any Subject's
 * permissions to perform a security sensitive Hazelcast operation.
 *
 */
public interface IPermissionPolicy {
    void configure(SecurityConfig securityConfig, Properties properties);

    PermissionCollection getPermissions(Subject subject, Class<? extends Permission> type);

    void destroy();
}]]></programlisting>
        </para>
        <para>Permission policy implementations can access
            client-permissions
            in
            configuration by using
            SecurityConfig.getClientPermissionConfigs()
            during
            configure(SecurityConfig securityConfig, Properties properties)
            method
            is called by Hazelcast.
            IPermissionPolicy.getPermissions(Subject subject,
                Class<? extends Permission> type)

            method is used to determine a client
            request has been granted permission to do a security-sensitive operation. Permission
            policy should return a
            <literal>PermissionCollection</literal>
            containing permissions of
            given type for given<literal>Subject</literal>. Hazelcast access controller will call
            PermissionCollection.implies(Permission)
            on returning
            <literal>PermissionCollection</literal>
            and will decide if current
            <literal>Subject</literal>
            has permitted to access to requested resources or
            not.
        </para>
    </sect2>

    <sect2>
        <title>Permissions</title>
        <para>
            <orderedlist>
                <listitem>
                    <para>
                        <emphasis role="bold">All Permission</emphasis>
                    </para>
                    <para>
                        <programlisting language="xml"><![CDATA[
<all-permissions principal="principal">
    <endpoints>
        ...
    </endpoints>
</all-permissions>
]]></programlisting>
                    </para>
                </listitem>
                <listitem>
                    <para>
                        <emphasis role="bold">Map Permission</emphasis>
                    </para>
                    <para>
                        <programlisting language="xml"><![CDATA[
<map-permission name="name" principal="principal">
    <endpoints>
        ...
    </endpoints>
    <actions>
        ...
    </actions>
</map-permission>
]]></programlisting>
                    </para>
                    <para>
                        <emphasis role="bold">Actions:</emphasis>
                        <emphasis role="italic">all, create, destroy,
                            put, get, remove, listen, lock, stats
                        </emphasis>
                    </para>
                </listitem>

                <listitem>
                    <para>
                        <emphasis role="bold">Queue Permission</emphasis>
                    </para>
                    <para>
                        <programlisting language="xml"><![CDATA[
<queue-permission name="name" principal="principal">
    <endpoints>
        ...
    </endpoints>
    <actions>
        ...
    </actions>
</queue-permission>
]]></programlisting>
                    </para>
                    <para>
                        <emphasis role="bold">Actions:</emphasis>
                        <emphasis role="italic">all, create, destroy,
                            offer, poll, get, remove, listen, stats
                        </emphasis>
                    </para>
                </listitem>

                <listitem>
                    <para>
                        <emphasis role="bold">Multimap Permission</emphasis>
                    </para>
                    <para>
                        <programlisting language="xml"><![CDATA[
<multimap-permission name="name" principal="principal">
    <endpoints>
        ...
    </endpoints>
    <actions>
        ...
    </actions>
</multimap-permission>
]]></programlisting>
                    </para>
                    <para>
                        <emphasis role="bold">Actions:</emphasis>
                        <emphasis role="italic">all, create, destroy,
                            put, get, remove, listen, lock, stats
                        </emphasis>
                    </para>
                </listitem>

                <listitem>
                    <para>
                        <emphasis role="bold">Topic Permission</emphasis>
                    </para>
                    <para>
                        <programlisting language="xml"><![CDATA[
<topic-permission name="name" principal="principal">
    <endpoints>
        ...
    </endpoints>
    <actions>
        ...
    </actions>
</topic-permission>
]]></programlisting>
                    </para>
                    <para>
                        <emphasis role="bold">Actions:</emphasis>
                        <emphasis role="italic">create, destroy,
                            publish, listen, stats
                        </emphasis>
                    </para>
                </listitem>

                <listitem>
                    <para>
                        <emphasis role="bold">List Permission</emphasis>
                    </para>
                    <para>
                        <programlisting language="xml"><![CDATA[
<list-permission name="name" principal="principal">
    <endpoints>
        ...
    </endpoints>
    <actions>
        ...
    </actions>
</list-permission>
]]></programlisting>
                    </para>
                    <para>
                        <emphasis role="bold">Actions:</emphasis>
                        <emphasis role="italic">all, create, destroy,
                            add, set, get, remove, listen
                        </emphasis>
                    </para>
                </listitem>

                <listitem>
                    <para>
                        <emphasis role="bold">Set Permission</emphasis>
                    </para>
                    <para>
                        <programlisting language="xml"><![CDATA[
<set-permission name="name" principal="principal">
    <endpoints>
        ...
    </endpoints>
    <actions>
        ...
    </actions>
</set-permission>
]]></programlisting>
                    </para>
                    <para>
                        <emphasis role="bold">Actions:</emphasis>
                        <emphasis role="italic">all, create, destroy,
                            add, get, remove, listen
                        </emphasis>
                    </para>
                </listitem>

                <listitem>
                    <para>
                        <emphasis role="bold">Lock Permission</emphasis>
                    </para>
                    <para>
                        <programlisting language="xml"><![CDATA[
<lock-permission name="name" principal="principal">
    <endpoints>
        ...
    </endpoints>
    <actions>
        ...
    </actions>
</lock-permission>
]]></programlisting>
                    </para>
                    <para>
                        <emphasis role="bold">Actions:</emphasis>
                        <emphasis role="italic">all, create, destroy,
                            lock, stats
                        </emphasis>
                    </para>
                </listitem>

                <listitem>
                    <para>
                        <emphasis role="bold">AtomicNumber Permission</emphasis>
                    </para>
                    <para>
                        <programlisting language="xml"><![CDATA[
<atomic-number-permission name="name" principal="principal">
    <endpoints>
        ...
    </endpoints>
    <actions>
        ...
    </actions>
</atomic-number-permission>
]]></programlisting>
                    </para>
                    <para>
                        <emphasis role="bold">Actions:</emphasis>
                        <emphasis role="italic">all, create, destroy,
                            increment, decrement, get, set, add, stats
                        </emphasis>
                    </para>
                </listitem>

                <listitem>
                    <para>
                        <emphasis role="bold">CountDownLatch Permission</emphasis>
                    </para>
                    <para>
                        <programlisting language="xml"><![CDATA[
<countdown-latch-permission name="name" principal="principal">
    <endpoints>
        ...
    </endpoints>
    <actions>
        ...
    </actions>
</countdown-latch-permission>
]]></programlisting>
                    </para>
                    <para>
                        <emphasis role="bold">Actions:</emphasis>
                        <emphasis role="italic">all, create, destroy,
                            countdown, set, stats
                        </emphasis>
                    </para>
                </listitem>

                <listitem>
                    <para>
                        <emphasis role="bold">Semaphore Permission</emphasis>
                    </para>
                    <para>
                        <programlisting language="xml"><![CDATA[
<semaphore-permission name="name" principal="principal">
    <endpoints>
        ...
    </endpoints>
    <actions>
        ...
    </actions>
</semaphore-permission>
]]></programlisting>
                    </para>
                    <para>
                        <emphasis role="bold">Actions:</emphasis>
                        <emphasis role="italic">all, create, destroy,
                            acquire, release, drain, stats
                        </emphasis>
                    </para>
                </listitem>

                <listitem>
                    <para>
                        <emphasis role="bold">Executor Service Permission</emphasis>
                    </para>
                    <para>
                        <programlisting language="xml"><![CDATA[
<executor-service-permission name="name" principal="principal">
    <endpoints>
        ...
    </endpoints>
    <actions>
        ...
    </actions>
</executor-service-permission>
]]></programlisting>
                    </para>
                    <para>
                        <emphasis role="bold">Actions:</emphasis>
                        <emphasis role="italic">all, create, destroy,
                            execute
                        </emphasis>
                    </para>
                </listitem>

                <listitem>
                    <para>
                        <emphasis role="bold">Listener Permission</emphasis>
                    </para>
                    <para>
                        <programlisting language="xml"><![CDATA[
<listener-permission name="name" principal="principal">
    <endpoints>
        ...
    </endpoints>
</listener-permission>
]]></programlisting>
                    </para>
                    <para>
                        <emphasis role="bold">Names:</emphasis>
                        <emphasis role="italic">all, instance,
                            member
                        </emphasis>
                    </para>
                </listitem>

                <listitem>
                    <para>
                        <emphasis role="bold">Transaction Permission</emphasis>
                    </para>
                    <para>
                        <programlisting language="xml"><![CDATA[
<transaction-permission principal="principal">
    <endpoints>
        ...
    </endpoints>
</transaction-permission>
]]></programlisting>
                    </para>
                </listitem>
            </orderedlist>
        </para>
    </sect2>
</sect1>


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.videoanalyzer.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;

/** RTSP source allows for media from an RTSP camera or generic RTSP server to be ingested into a pipeline. */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@type")
@JsonTypeName("#Microsoft.VideoAnalyzer.RtspSource")
@Fluent
public final class RtspSource extends SourceNodeBase {
    /*
     * Network transport utilized by the RTSP and RTP exchange: TCP or HTTP.
     * When using TCP, the RTP packets are interleaved on the TCP RTSP
     * connection. When using HTTP, the RTSP messages are exchanged through
     * long lived HTTP connections, and the RTP packages are interleaved in the
     * HTTP connections alongside the RTSP messages.
     */
    @JsonProperty(value = "transport")
    private RtspTransport transport;

    /*
     * RTSP endpoint information for Video Analyzer to connect to. This
     * contains the required information for Video Analyzer to connect to RTSP
     * cameras and/or generic RTSP servers.
     */
    @JsonProperty(value = "endpoint", required = true)
    private EndpointBase endpoint;

    /**
     * Get the transport property: Network transport utilized by the RTSP and RTP exchange: TCP or HTTP. When using TCP,
     * the RTP packets are interleaved on the TCP RTSP connection. When using HTTP, the RTSP messages are exchanged
     * through long lived HTTP connections, and the RTP packages are interleaved in the HTTP connections alongside the
     * RTSP messages.
     *
     * @return the transport value.
     */
    public RtspTransport transport() {
        return this.transport;
    }

    /**
     * Set the transport property: Network transport utilized by the RTSP and RTP exchange: TCP or HTTP. When using TCP,
     * the RTP packets are interleaved on the TCP RTSP connection. When using HTTP, the RTSP messages are exchanged
     * through long lived HTTP connections, and the RTP packages are interleaved in the HTTP connections alongside the
     * RTSP messages.
     *
     * @param transport the transport value to set.
     * @return the RtspSource object itself.
     */
    public RtspSource withTransport(RtspTransport transport) {
        this.transport = transport;
        return this;
    }

    /**
     * Get the endpoint property: RTSP endpoint information for Video Analyzer to connect to. This contains the required
     * information for Video Analyzer to connect to RTSP cameras and/or generic RTSP servers.
     *
     * @return the endpoint value.
     */
    public EndpointBase endpoint() {
        return this.endpoint;
    }

    /**
     * Set the endpoint property: RTSP endpoint information for Video Analyzer to connect to. This contains the required
     * information for Video Analyzer to connect to RTSP cameras and/or generic RTSP servers.
     *
     * @param endpoint the endpoint value to set.
     * @return the RtspSource object itself.
     */
    public RtspSource withEndpoint(EndpointBase endpoint) {
        this.endpoint = endpoint;
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public RtspSource withName(String name) {
        super.withName(name);
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    @Override
    public void validate() {
        super.validate();
        if (endpoint() == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException("Missing required property endpoint in model RtspSource"));
        } else {
            endpoint().validate();
        }
    }

    private static final ClientLogger LOGGER = new ClientLogger(RtspSource.class);
}


text:
package ucar.units;

/**
 * Provides support for prefix database failures.
 *
 * @author Steven R. Emmerson
 */
public class PrefixExistsException extends PrefixDBException {
	private static final long	serialVersionUID	= 1L;

	/**
	 * Constructs from an old prefix and a new prefix.
	 *
	 * @param oldPrefix
	 *            The previously-existing prefix.
	 * @param newPrefix
	 *            The replacement prefix.
	 */
	public PrefixExistsException(final Prefix oldPrefix, final Prefix newPrefix) {
		super("Attempt to replace \"" + oldPrefix + "\" with \"" + newPrefix
				+ "\" in prefix database");
	}
}


text:
package repositoryundeprecate

import _ "github.com/bufbuild/buf/private/usage"