text:
Demo of Kubernetes Horizontal Pod Autoscaler using custom RUM data as scaling metric.

Based on [Akamai's Boomerang](https://github.com/akamai/boomerang) and [Boomcatch](https://github.com/springernature/boomcatch) beacon metric receiver.

Metrics are pushed to statsd_prometheus_exporter which is then scraped and stored by prometheus.
Kubernetes HPA can then use these metrics using the k8s prometheus adapter.

Currently only the roundtrip 99th percentile rt.load time is used but boomerange exposes many more metrics with different plugins.

## Architecture:
```
+----------------------+           +-------------------+                       +--------------+     +--------------------+     +----------------+
|  Frontend/Boomcatch  |---(UDP)-->|  statsd_exporter  |<---(scrape/metrics)---|  Prometheus  |<----| Prometheus Adapter |<----| K8s Custom HPA |
+----------------------+           +-------------------+                       +--------------+     +--------------------+     +----------------+
```

# Setup
### Install prometheus-statsd-exporter
```
kubectl apply -f ./prometheus-statsd
```
### Install prometheus
```
kubectl apply -f ./prometheus
```
### Install prometheus k8s adapter
```
kubectl apply -f ./prometheus-adapter
```
### Install frontend
```
kubectl apply -f ./frontend
```
### Install custom metric HPA
```
kubectl apply -f ./hpa
```

# Usage
- Hit the external IP created via k8s frontend service a few times
- Test metrics are incoming:
```
kubectl get --raw "/apis/custom.metrics.k8s.io/v1beta1/namespaces/default/services/*/boomcatch_load"
```
You should see something like this:
```
{"kind":"MetricValueList","apiVersion":"custom.metrics.k8s.io/v1beta1","metadata":{"selfLink":"/apis/custom.metrics.k8s.io/v1beta1/namespaces/default/services/%2A/boomcatch_load"},"items":[{"describedObject":{"kind":"Service","namespace":"default","name":"statsd-exporter","apiVersion":"/v1"},"metricName":"boomcatch_load","timestamp":"2019-02-21T02:49:46Z","value":"325"}]}
```

- Watch k8s hpa resource: `kubectl get hpa -w`
- Watch HPA scale pods up and down for custom metric being out of target latency (defaults to 20ms)

### *Note:*
I noticed that uBlock Origin doesn't like Boomerang embedded in the frontend site. You may need to whitelist the external IP for this to properly work.


text:
"""Manages execution of keystone test suites"""
from keystone.test import KeystoneTest

class SQLTest(KeystoneTest):
    config_name = 'sql.conf.template'
    test_files = ('keystone.db',)

class MemcacheTest(KeystoneTest):
    config_name = 'memcache.conf.template'
    test_files = ('keystone.db',)

class LDAPTest(KeystoneTest):
    config_name = 'ldap.conf.template'
    test_files = ('keystone.db', 'ldap.db', 'ldap.db.db',)

TESTS = [
    SQLTest,
    # currently failing, and has yet to pass in jenkins: MemcacheTest,
    LDAPTest,
]

if __name__ == '__main__':
    for test_num, test_cls in enumerate(TESTS):
        print 'Starting test %d of %d with config: %s' % \
            (test_num + 1, len(TESTS), test_cls.config_name)
        test_cls().run()

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using Csla;
using ParentLoadRO.DataAccess.ERLevel;

namespace ParentLoadRO.Business.ERLevel
{

    ///
    /// A11_CityRoadColl (read only list).

    /// This is a generated base class of <see cref="A11_CityRoadColl"/> business object.
    ///
    /// <remarks>
    /// This class is child of <see cref="A10_City"/> read only object.

    /// The items of the collection are <see cref="A12_CityRoad"/> objects.
    /// </remarks>
    [Serializable]
    public partial class A11_CityRoadColl : ReadOnlyListBase<A11_CityRoadColl, A12_CityRoad>
    {

        #region Collection Business Methods

        ///
        /// Determines whether a <see cref="A12_CityRoad"/> item is in the collection.
        ///
        /// <param name="cityRoad_ID">The CityRoad_ID of the item to search for.</param>
        /// <returns><c>true</c> if the A12_CityRoad is a collection item; otherwise, <c>false</c>.</returns>
        public bool Contains(int cityRoad_ID)
        {
            foreach (var a12_CityRoad in this)
            {
                if (a12_CityRoad.CityRoad_ID == cityRoad_ID)
                {
                    return true;
                }
            }
            return false;
        }

        #endregion

        #region Factory Methods

        ///
        /// Factory method. Loads a <see cref="A11_CityRoadColl"/> object from the given list of A12_CityRoadDto.
        ///
        /// <param name="data">The list of <see cref="A12_CityRoadDto"/>.</param>
        /// <returns>A reference to the fetched <see cref="A11_CityRoadColl"/> object.</returns>
        internal static A11_CityRoadColl GetA11_CityRoadColl(List<A12_CityRoadDto> data)
        {
            A11_CityRoadColl obj = new A11_CityRoadColl();
            obj.Fetch(data);
            return obj;
        }

        #endregion

        #region Constructor

        ///
        /// Initializes a new instance of the <see cref="A11_CityRoadColl"/> class.
        ///
        /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
        [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
        public A11_CityRoadColl()
        {
            // Use factory methods and do not use direct creation.

            var rlce = RaiseListChangedEvents;
            RaiseListChangedEvents = false;
            AllowNew = false;
            AllowEdit = false;
            AllowRemove = false;
            RaiseListChangedEvents = rlce;
        }

        #endregion

        #region Data Access

        ///
        /// Loads all <see cref="A11_CityRoadColl"/> collection items from the given list of A12_CityRoadDto.
        ///
        /// <param name="data">The list of <see cref="A12_CityRoadDto"/>.</param>
        private void Fetch(List<A12_CityRoadDto> data)
        {
            IsReadOnly = false;
            var rlce = RaiseListChangedEvents;
            RaiseListChangedEvents = false;
            var args = new DataPortalHookArgs(data);
            OnFetchPre(args);
            foreach (var dto in data)
            {
                Add(A12_CityRoad.GetA12_CityRoad(dto));
            }
            OnFetchPost(args);
            RaiseListChangedEvents = rlce;
            IsReadOnly = true;
        }

        ///
        /// Loads <see cref="A12_CityRoad"/> items on the A11_CityRoadObjects collection.
        ///
        /// <param name="collection">The grand parent <see cref="A09_CityColl"/> collection.</param>
        internal void LoadItems(A09_CityColl collection)
        {
            foreach (var item in this)
            {
                var obj = collection.FindA10_CityByParentProperties(item.parent_City_ID);
                obj.A11_CityRoadObjects.IsReadOnly = false;
                var rlce = obj.A11_CityRoadObjects.RaiseListChangedEvents;
                obj.A11_CityRoadObjects.RaiseListChangedEvents = false;
                obj.A11_CityRoadObjects.Add(item);
                obj.A11_CityRoadObjects.RaiseListChangedEvents = rlce;
                obj.A11_CityRoadObjects.IsReadOnly = true;
            }
        }

        #endregion

        #region DataPortal Hooks

        ///
        /// Occurs after setting query parameters and before the fetch operation.
        ///
        partial void OnFetchPre(DataPortalHookArgs args);

        ///
        /// Occurs after the fetch operation (object or collection is fully loaded and set up).
        ///
        partial void OnFetchPost(DataPortalHookArgs args);

        #endregion

    }
}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

			<title>Docs for page GitLogFormat.class.php</title>
			<link rel="stylesheet" href="../../media/stylesheet.css" />
			<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'/>

/commands/GitLogFormat.class.php

Description

					Description |
							Classes

This file is part of the phpCollab3 package.

(c) 2009 Ideato s.r.l. <phpcollab@ideato.it>

For the full copyright and license information, please view the LICENSE  file that was distributed with this source code.

GitLogFormat

Classes

			Description |
			Classes

					Class
					Description

						GitLogFormat

											Class that provides a way to specify which format has to have the log report of a git-log call

		Documentation generated on Thu, 28 May 2009 17:40:14 +0200 by phpDocumentor 1.4.2


text:
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
#pragma warning disable
/// <summary>
/// Inspector class used to edit UIWidgets.
/// </summary>

[CustomEditor(typeof(UIWidget))]
public class UIWidgetInspector : Editor
{
	enum Action
	{
		None,
		Move,
		Scale,
		Rotate,
	}

	Action mAction = Action.None;
	Action mActionUnderMouse = Action.None;
	bool mAllowSelection = true;

	protected UIWidget mWidget;

	static protected bool mUseShader = false;
	static Color mOutlineColor = Color.green;
	static GUIStyle mSelectedDot = null;
	static GUIStyle mNormalDot = null;
	static MouseCursor mCursor = MouseCursor.Arrow;

	static UIWidget.Pivot[] mPivots =
	{
		UIWidget.Pivot.TopLeft,
		UIWidget.Pivot.BottomLeft,
		UIWidget.Pivot.BottomRight,
		UIWidget.Pivot.TopRight,
		UIWidget.Pivot.Left,
		UIWidget.Pivot.Bottom,
		UIWidget.Pivot.Right,
		UIWidget.Pivot.Top,
	};

	static int s_Hash = "WidgetHash".GetHashCode();
	Vector3 mStartPos = Vector3.zero;
	Vector3 mStartScale = Vector3.zero;
	Vector3 mStartDrag = Vector3.zero;
	Vector2 mStartMouse = Vector2.zero;
	Vector3 mStartRot = Vector3.zero;
	Vector3 mStartDir = Vector3.right;
	UIWidget.Pivot mDragPivot = UIWidget.Pivot.Center;

	/// <summary>
	/// Register an Undo command with the Unity editor.
	/// </summary>

	void RegisterUndo ()
	{
		NGUIEditorTools.RegisterUndo("Widget Change", mWidget);
	}

	/// <summary>
	/// Raycast into the screen.
	/// </summary>

	static bool Raycast (Vector3[] corners, out Vector3 hit)
	{
		Plane plane = new Plane(corners[0], corners[1], corners[2]);
		Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
		float dist = 0f;
		bool isHit = plane.Raycast(ray, out dist);
		hit = isHit ? ray.GetPoint(dist) : Vector3.zero;
		return isHit;
	}

	/// <summary>
	/// Draw a control dot at the specified world position.
	/// </summary>

	static void DrawKnob (Vector3 point, bool selected, int id)
	{
		if (mSelectedDot == null) mSelectedDot = "sv_label_5";
		if (mNormalDot == null) mNormalDot = "sv_label_3";

		Vector2 screenPoint = HandleUtility.WorldToGUIPoint(point);

		Rect rect = new Rect(screenPoint.x - 7f, screenPoint.y - 7f, 14f, 14f);
		if (selected) mSelectedDot.Draw(rect, GUIContent.none, id);
		else mNormalDot.Draw(rect, GUIContent.none, id);
	}

	/// <summary>
	/// Whether the mouse position is within one of the specified rectangles.
	/// </summary>

	static bool IsMouseOverRect (Vector2 mouse, List<Rect> rects)
	{
		for (int i = 0; i < rects.Count; ++i)
		{
			Rect r = rects[i];
			if (r.Contains(mouse)) return true;
		}
		return false;
	}

	/// <summary>
	/// Screen-space distance from the mouse position to the specified world position.
	/// </summary>

	static float GetScreenDistance (Vector3 worldPos, Vector2 mousePos)
	{
		Vector2 screenPos = HandleUtility.WorldToGUIPoint(worldPos);
		return Vector2.Distance(mousePos, screenPos);
	}

	/// <summary>
	/// Closest screen-space distance from the mouse position to one of the specified world points.
	/// </summary>

	static float GetScreenDistance (Vector3[] worldPoints, Vector2 mousePos, out int index)
	{
		float min = float.MaxValue;
		index = 0;

		for (int i = 0; i < worldPoints.Length; ++i)
		{
			float distance = GetScreenDistance(worldPoints[i], mousePos);

			if (distance < min)
			{
				index = i;
				min = distance;
			}
		}
		return min;
	}

	/// <summary>
	/// Set the mouse cursor rectangle, refreshing the screen when it gets changed.
	/// </summary>

	static void SetCursorRect (Rect rect, MouseCursor cursor)
	{
		EditorGUIUtility.AddCursorRect(rect, cursor);

		if (Event.current.type == EventType.MouseMove)
		{
			if (mCursor != cursor)
			{
				mCursor = cursor;
				Event.current.Use();
			}
		}
	}

	/// <summary>
	/// Draw the on-screen selection, knobs, and handle all interaction logic.
	/// </summary>

	public void OnSceneGUI ()
	{
		if (!UIWidget.showHandles) return;

		mWidget = target as UIWidget;

		Handles.color = mOutlineColor;
		Transform t = mWidget.cachedTransform;

		Event e = Event.current;
		int id = GUIUtility.GetControlID(s_Hash, FocusType.Passive);
		EventType type = e.GetTypeForControl(id);

		Vector3[] corners = NGUIMath.CalculateWidgetCorners(mWidget);
		Handles.DrawLine(corners[0], corners[1]);
		Handles.DrawLine(corners[1], corners[2]);
		Handles.DrawLine(corners[2], corners[3]);
		Handles.DrawLine(corners[0], corners[3]);

		Vector3[] worldPos = new Vector3[8];

		worldPos[0] = corners[0];
		worldPos[1] = corners[1];
		worldPos[2] = corners[2];
		worldPos[3] = corners[3];

		worldPos[4] = (corners[0] + corners[1]) * 0.5f;
		worldPos[5] = (corners[1] + corners[2]) * 0.5f;
		worldPos[6] = (corners[2] + corners[3]) * 0.5f;
		worldPos[7] = (corners[0] + corners[3]) * 0.5f;

		Vector2[] screenPos = new Vector2[8];
		for (int i = 0; i < 8; ++i) screenPos[i] = HandleUtility.WorldToGUIPoint(worldPos[i]);

		Bounds b = new Bounds(screenPos[0], Vector3.zero);
		for (int i = 1; i < 8; ++i) b.Encapsulate(screenPos[i]);

		// Time to figure out what kind of action is underneath the mouse
		Action actionUnderMouse = mAction;
		UIWidget.Pivot pivotUnderMouse = UIWidget.Pivot.Center;

		if (actionUnderMouse == Action.None)
		{
			int index = 0;
			float dist = GetScreenDistance(worldPos, e.mousePosition, out index);

			if (mWidget.showResizeHandles && dist < 10f)
			{
				pivotUnderMouse = mPivots[index];
				actionUnderMouse = Action.Scale;
			}
			else if (e.modifiers == 0 && SceneViewDistanceToRectangle(corners, e.mousePosition) == 0f)
			{
				actionUnderMouse = Action.Move;
			}
			else if (dist < 30f)
			{
				actionUnderMouse = Action.Rotate;
			}
		}

		// Change the mouse cursor to a more appropriate one
#if !UNITY_3_5
		{
			Vector2 min = b.min;
			Vector2 max = b.max;

			min.x -= 30f;
			max.x += 30f;
			min.y -= 30f;
			max.y += 30f;

			Rect rect = new Rect(min.x, min.y, max.x - min.x, max.y - min.y);

			if (actionUnderMouse == Action.Rotate)
			{
				SetCursorRect(rect, MouseCursor.RotateArrow);
			}
			else if (actionUnderMouse == Action.Move)
			{
				SetCursorRect(rect, MouseCursor.MoveArrow);
			}
			else if (mWidget.showResizeHandles && actionUnderMouse == Action.Scale)
			{
				SetCursorRect(rect, MouseCursor.ScaleArrow);
			}
			else SetCursorRect(rect, MouseCursor.Arrow);
		}
#endif

		switch (type)
		{
			case EventType.Repaint:
			{
				if (mWidget.showResizeHandles)
				{
					Handles.BeginGUI();
					{
						for (int i = 0; i < 8; ++i)
						{
							DrawKnob(worldPos[i], mWidget.pivot == mPivots[i], id);
						}
					}
					Handles.EndGUI();
				}
			}
			break;

			case EventType.MouseDown:
			{
				mStartMouse = e.mousePosition;
				mAllowSelection = true;

				if (e.button == 1)
				{
					if (e.modifiers == 0)
					{
						GUIUtility.hotControl = GUIUtility.keyboardControl = id;
						e.Use();
					}
				}
				else if (e.button == 0 && actionUnderMouse != Action.None && Raycast(corners, out mStartDrag))
				{
					mStartPos = t.position;
					mStartRot = t.localRotation.eulerAngles;
					mStartDir = mStartDrag - t.position;
					mStartScale = t.localScale;
					mDragPivot = pivotUnderMouse;
					mActionUnderMouse = actionUnderMouse;
					GUIUtility.hotControl = GUIUtility.keyboardControl = id;
					e.Use();
				}
			}
			break;

			case EventType.MouseDrag:
			{
				// Prevent selection once the drag operation begins
				bool dragStarted = (e.mousePosition - mStartMouse).magnitude > 3f;
				if (dragStarted) mAllowSelection = false;

				if (GUIUtility.hotControl == id)
				{
					e.Use();

					if (mAction != Action.None || mActionUnderMouse != Action.None)
					{
						Vector3 pos;

						if (Raycast(corners, out pos))
						{
							if (mAction == Action.None && mActionUnderMouse != Action.None)
							{
								// Wait until the mouse moves by more than a few pixels
								if (dragStarted)
								{
									if (mActionUnderMouse == Action.Move)
									{
										mStartPos = t.position;
										NGUIEditorTools.RegisterUndo("Move widget", t);
									}
									else if (mActionUnderMouse == Action.Rotate)
									{
										mStartRot = t.localRotation.eulerAngles;
										mStartDir = mStartDrag - t.position;
										NGUIEditorTools.RegisterUndo("Rotate widget", t);
									}
									else if (mActionUnderMouse == Action.Scale)
									{
										mStartPos = t.localPosition;
										mStartScale = t.localScale;
										mDragPivot = pivotUnderMouse;
										NGUIEditorTools.RegisterUndo("Scale widget", t);
									}
									mAction = actionUnderMouse;
								}
							}

							if (mAction != Action.None)
							{
								if (mAction == Action.Move)
								{
									t.position = mStartPos + (pos - mStartDrag);
									pos = t.localPosition;
									pos.x = Mathf.RoundToInt(pos.x);
									pos.y = Mathf.RoundToInt(pos.y);
									t.localPosition = pos;
								}
								else if (mAction == Action.Rotate)
								{
									Vector3 dir = pos - t.position;
									float angle = Vector3.Angle(mStartDir, dir);

									if (angle > 0f)
									{
										float dot = Vector3.Dot(Vector3.Cross(mStartDir, dir), t.forward);
										if (dot < 0f) angle = -angle;
										angle = mStartRot.z + angle;
										if (e.modifiers != EventModifiers.Shift) angle = Mathf.Round(angle / 15f) * 15f;
										else angle = Mathf.Round(angle);
										t.localRotation = Quaternion.Euler(mStartRot.x, mStartRot.y, angle);
									}
								}
								else if (mAction == Action.Scale)
								{
									// World-space delta since the drag started
									Vector3 delta = pos - mStartDrag;

									// Adjust the widget's position and scale based on the delta, restricted by the pivot
									AdjustPosAndScale(mWidget, mStartPos, mStartScale, delta, mDragPivot);
								}
							}
						}
					}
				}
			}
			break;

			case EventType.MouseUp:
			{
				if (GUIUtility.hotControl == id)
				{
					GUIUtility.hotControl = 0;
					GUIUtility.keyboardControl = 0;

					if (e.button < 2)
					{
						bool handled = false;

						if (e.button == 1)
						{
							// Right-click: Select the widget below
							SelectWidget(mWidget, e.mousePosition, false);
							handled = true;
						}
						else if (mAction == Action.None)
						{
							if (mAllowSelection)
							{
								// Left-click: Select the widget above
								SelectWidget(mWidget, e.mousePosition, true);
								handled = true;
							}
						}
						else
						{
							// Finished dragging something
							mAction = Action.None;
							mActionUnderMouse = Action.None;
							Vector3 pos = t.localPosition;
							Vector3 scale = t.localScale;

							if (mWidget.pixelPerfectAfterResize)
							{
								t.localPosition = pos;
								t.localScale = scale;

								mWidget.MakePixelPerfect();
							}
							else
							{
								pos.x = Mathf.Round(pos.x);
								pos.y = Mathf.Round(pos.y);
								scale.x = Mathf.Round(scale.x);
								scale.y = Mathf.Round(scale.y);

								t.localPosition = pos;
								t.localScale = scale;
							}
							handled = true;
						}

						if (handled)
						{
							mActionUnderMouse = Action.None;
							mAction = Action.None;
							e.Use();
						}
					}
				}
				else if (mAllowSelection)
				{
					BetterList<UIWidget> widgets = SceneViewRaycast(mWidget.panel, e.mousePosition);
					if (widgets.size > 0) Selection.activeGameObject = widgets[0].gameObject;
				}
				mAllowSelection = true;
			}
			break;

			case EventType.KeyDown:
			{
				if (e.keyCode == KeyCode.UpArrow)
				{
					Vector3 pos = t.localPosition;
					pos.y += 1f;
					t.localPosition = pos;
					e.Use();
				}
				else if (e.keyCode == KeyCode.DownArrow)
				{
					Vector3 pos = t.localPosition;
					pos.y -= 1f;
					t.localPosition = pos;
					e.Use();
				}
				else if (e.keyCode == KeyCode.LeftArrow)
				{
					Vector3 pos = t.localPosition;
					pos.x -= 1f;
					t.localPosition = pos;
					e.Use();
				}
				else if (e.keyCode == KeyCode.RightArrow)
				{
					Vector3 pos = t.localPosition;
					pos.x += 1f;
					t.localPosition = pos;
					e.Use();
				}
				else if (e.keyCode == KeyCode.Escape)
				{
					if (GUIUtility.hotControl == id)
					{
						if (mAction != Action.None)
						{
							if (mAction == Action.Move)
							{
								t.position = mStartPos;
							}
							else if (mAction == Action.Rotate)
							{
								t.localRotation = Quaternion.Euler(mStartRot);
							}
							else if (mAction == Action.Scale)
							{
								t.position = mStartPos;
								t.localScale = mStartScale;
							}
						}

						GUIUtility.hotControl = 0;
						GUIUtility.keyboardControl = 0;

						mActionUnderMouse = Action.None;
						mAction = Action.None;
						e.Use();
					}
					else Selection.activeGameObject = null;
				}
			}
			break;
		}
	}

	/// <summary>
	/// Select the next widget in line.
	/// </summary>

	static public bool SelectWidget (UIWidget start, Vector2 pos, bool inFront)
	{
		GameObject go = null;
		UIPanel p = start.panel;
		if (p == null) p = NGUITools.FindInParents<UIPanel>(start.gameObject);
		BetterList<UIWidget> widgets = SceneViewRaycast(p, pos);

		if (inFront)
		{
			if (widgets.size > 0)
			{
				for (int i = 0; i < widgets.size; ++i)
				{
					UIWidget w = widgets[i];
					if (w == start) break;
					go = w.gameObject;
				}
			}
		}
		else
		{
			for (int i = widgets.size; i > 0; )
			{
				UIWidget w = widgets[--i];
				if (w == start) break;
				go = w.gameObject;
			}
		}

		if (go != null)
		{
			Selection.activeGameObject = go;
			return true;
		}
		return false;
	}

	/// <summary>
	/// Adjust the transform's position and scale.
	/// </summary>

	static void AdjustPosAndScale (UIWidget w, Vector3 startLocalPos, Vector3 startLocalScale, Vector3 worldDelta, UIWidget.Pivot dragPivot)
	{
		Transform t = w.cachedTransform;
		Transform parent = t.parent;
		Matrix4x4 parentToLocal = (parent != null) ? t.parent.worldToLocalMatrix : Matrix4x4.identity;
		Matrix4x4 worldToLocal = parentToLocal;
		Quaternion invRot = Quaternion.Inverse(t.localRotation);
		worldToLocal = worldToLocal * Matrix4x4.TRS(Vector3.zero, invRot, Vector3.one);
		Vector3 localDelta = worldToLocal.MultiplyVector(worldDelta);

		bool canBeSquare = false;
		float left = 0f;
		float right = 0f;
		float top = 0f;
		float bottom = 0f;

		switch (dragPivot)
		{
			case UIWidget.Pivot.TopLeft:
			canBeSquare = (w.pivot == UIWidget.Pivot.BottomRight);
			left = localDelta.x;
			top = localDelta.y;
			break;

			case UIWidget.Pivot.Left:
			left = localDelta.x;
			break;

			case UIWidget.Pivot.BottomLeft:
			canBeSquare = (w.pivot == UIWidget.Pivot.TopRight);
			left = localDelta.x;
			bottom = localDelta.y;
			break;

			case UIWidget.Pivot.Top:
			top = localDelta.y;
			break;

			case UIWidget.Pivot.Bottom:
			bottom = localDelta.y;
			break;

			case UIWidget.Pivot.TopRight:
			canBeSquare = (w.pivot == UIWidget.Pivot.BottomLeft);
			right = localDelta.x;
			top = localDelta.y;
			break;

			case UIWidget.Pivot.Right:
			right = localDelta.x;
			break;

			case UIWidget.Pivot.BottomRight:
			canBeSquare = (w.pivot == UIWidget.Pivot.TopLeft);
			right = localDelta.x;
			bottom = localDelta.y;
			break;
		}

		AdjustWidget(w, startLocalPos, startLocalScale, left, top, right, bottom, canBeSquare && Event.current.modifiers == EventModifiers.Shift);
	}

	/// <summary>
	/// Adjust the widget's rectangle based on the specified modifier values.
	/// </summary>

	static void AdjustWidget (UIWidget w, Vector3 pos, Vector3 scale, float left, float top, float right, float bottom, bool makeSquare)
	{
		Vector2 offset = w.pivotOffset;
		Vector4 padding = w.relativePadding;
		Vector2 size = w.relativeSize;

		offset.x -= padding.x;
		offset.y -= padding.y;
		size.x += padding.x + padding.z;
		size.y += padding.y + padding.w;

		scale.Scale(size);

		offset.y = -offset.y;

		Transform t = w.cachedTransform;
		Quaternion rot = t.localRotation;
		UIWidget.Pivot pivot = w.pivot;

		Vector2 rotatedTL = new Vector2(left, top);
		Vector2 rotatedTR = new Vector2(right, top);
		Vector2 rotatedBL = new Vector2(left, bottom);
		Vector2 rotatedBR = new Vector2(right, bottom);
		Vector2 rotatedL  = new Vector2(left, 0f);
		Vector2 rotatedR  = new Vector2(right, 0f);
		Vector2 rotatedT  = new Vector2(0f, top);
		Vector2 rotatedB  = new Vector2(0f, bottom);

		rotatedTL = rot * rotatedTL;
		rotatedTR = rot * rotatedTR;
		rotatedBL = rot * rotatedBL;
		rotatedBR = rot * rotatedBR;
		rotatedL  = rot * rotatedL;
		rotatedR  = rot * rotatedR;
		rotatedT  = rot * rotatedT;
		rotatedB  = rot * rotatedB;

		switch (pivot)
		{
			case UIWidget.Pivot.TopLeft:
			pos.x += rotatedTL.x;
			pos.y += rotatedTL.y;
			break;

			case UIWidget.Pivot.BottomRight:
			pos.x += rotatedBR.x;
			pos.y += rotatedBR.y;
			break;

			case UIWidget.Pivot.BottomLeft:
			pos.x += rotatedBL.x;
			pos.y += rotatedBL.y;
			break;

			case UIWidget.Pivot.TopRight:
			pos.x += rotatedTR.x;
			pos.y += rotatedTR.y;
			break;

			case UIWidget.Pivot.Left:
			pos.x += rotatedL.x + (rotatedT.x + rotatedB.x) * 0.5f;
			pos.y += rotatedL.y + (rotatedT.y + rotatedB.y) * 0.5f;
			break;

			case UIWidget.Pivot.Right:
			pos.x += rotatedR.x + (rotatedT.x + rotatedB.x) * 0.5f;
			pos.y += rotatedR.y + (rotatedT.y + rotatedB.y) * 0.5f;
			break;

			case UIWidget.Pivot.Top:
			pos.x += rotatedT.x + (rotatedL.x + rotatedR.x) * 0.5f;
			pos.y += rotatedT.y + (rotatedL.y + rotatedR.y) * 0.5f;
			break;

			case UIWidget.Pivot.Bottom:
			pos.x += rotatedB.x + (rotatedL.x + rotatedR.x) * 0.5f;
			pos.y += rotatedB.y + (rotatedL.y + rotatedR.y) * 0.5f;
			break;

			case UIWidget.Pivot.Center:
			pos.x += (rotatedL.x + rotatedR.x + rotatedT.x + rotatedB.x) * 0.5f;
			pos.y += (rotatedT.y + rotatedB.y + rotatedL.y + rotatedR.y) * 0.5f;
			break;
		}

		scale.x -= left - right;
		scale.y += top - bottom;

		scale.x /= size.x;
		scale.y /= size.y;

		Vector4 border = w.border;
		float minx = Mathf.Max(2f, padding.x + padding.z + border.x + border.z);
		float miny = Mathf.Max(2f, padding.y + padding.w + border.y + border.w);

		if (scale.x < minx) scale.x = minx;
		if (scale.y < miny) scale.y = miny;

		// NOTE: This will only work correctly when dragging the corner opposite of the pivot point
		if (makeSquare)
		{
			scale.x = Mathf.Min(scale.x, scale.y);
			scale.y = scale.x;
		}

		t.localPosition = pos;
		t.localScale = scale;
	}

	/// <summary>
	/// Cache the reference.
	/// </summary>

	protected virtual void OnEnable ()
	{
		mWidget = target as UIWidget;
	}

	/// <summary>
	/// Draw the inspector widget.
	/// </summary>

	public override void OnInspectorGUI ()
	{
		EditorGUIUtility.LookLikeControls(80f);
		EditorGUILayout.Space();

		// Check to see if we can draw the widget's default properties to begin with
		if (DrawProperties())
		{
			// Draw all common properties next
			DrawCommonProperties();
			DrawExtraProperties();
		}
	}

	/// <summary>
	/// All widgets have depth, color and make pixel-perfect options
	/// </summary>

	protected void DrawCommonProperties ()
	{
		PrefabType type = PrefabUtility.GetPrefabType(mWidget.gameObject);
		NGUIEditorTools.DrawSeparator();

#if UNITY_3_5
		// Pivot point -- old school drop-down style
		UIWidget.Pivot pivot = (UIWidget.Pivot)EditorGUILayout.EnumPopup("Pivot", mWidget.pivot);

		if (mWidget.pivot != pivot)
		{
		    NGUIEditorTools.RegisterUndo("Pivot Change", mWidget);
		    mWidget.pivot = pivot;
		}
#else
		// Pivot point -- the new, more visual style
		GUILayout.BeginHorizontal();
		GUILayout.Label("Pivot", GUILayout.Width(76f));
		Toggle("\u25C4", "ButtonLeft", UIWidget.Pivot.Left, true);
		Toggle("\u25AC", "ButtonMid", UIWidget.Pivot.Center, true);
		Toggle("\u25BA", "ButtonRight", UIWidget.Pivot.Right, true);
		Toggle("\u25B2", "ButtonLeft", UIWidget.Pivot.Top, false);
		Toggle("\u258C", "ButtonMid", UIWidget.Pivot.Center, false);
		Toggle("\u25BC", "ButtonRight", UIWidget.Pivot.Bottom, false);
		GUILayout.EndHorizontal();
#endif

		// Depth navigation
		if (type != PrefabType.Prefab)
		{
			GUILayout.Space(2f);
			GUILayout.BeginHorizontal();
			{
				EditorGUILayout.PrefixLabel("Depth");

				int depth = mWidget.depth;
				if (GUILayout.Button("Back", GUILayout.Width(60f))) --depth;
				depth = EditorGUILayout.IntField(depth);
				if (GUILayout.Button("Forward", GUILayout.Width(60f))) ++depth;

				if (mWidget.depth != depth)
				{
					NGUIEditorTools.RegisterUndo("Depth Change", mWidget);
					mWidget.depth = depth;
				}
			}
			GUILayout.EndHorizontal();

			int matchingDepths = 0;

			for (int i = 0; i < UIWidget.list.size; ++i)
			{
				UIWidget w = UIWidget.list[i];
				if (w != null && w.depth == mWidget.depth)
					++matchingDepths;
			}

			if (matchingDepths > 1)
			{
				EditorGUILayout.HelpBox(matchingDepths + " widgets are using the depth value of " + mWidget.depth +
					". It may not be clear what should be in front of what.", MessageType.Warning);
			}
		}

		// Pixel-correctness
		if (type != PrefabType.Prefab)
		{
			GUILayout.BeginHorizontal();
			{
				EditorGUILayout.PrefixLabel("Correction");

				if (GUILayout.Button("Make Pixel-Perfect"))
				{
					NGUIEditorTools.RegisterUndo("Make Pixel-Perfect", mWidget.transform);
					mWidget.MakePixelPerfect();
				}
			}
			GUILayout.EndHorizontal();
		}

		EditorGUILayout.Space();

		// Color tint
		GUILayout.BeginHorizontal();
		Color color = EditorGUILayout.ColorField("Color Tint", mWidget.color);
		if (GUILayout.Button("Copy", GUILayout.Width(50f)))
			NGUISettings.color = color;
		GUILayout.EndHorizontal();

		GUILayout.BeginHorizontal();
		NGUISettings.color = EditorGUILayout.ColorField("Clipboard", NGUISettings.color);
		if (GUILayout.Button("Paste", GUILayout.Width(50f)))
			color = NGUISettings.color;
		GUILayout.EndHorizontal();

		if (mWidget.color != color)
		{
			NGUIEditorTools.RegisterUndo("Color Change", mWidget);
			mWidget.color = color;
		}
	}

	/// <summary>
	/// Draw a toggle button for the pivot point.
	/// </summary>

	void Toggle (string text, string style, UIWidget.Pivot pivot, bool isHorizontal)
	{
		bool isActive = false;

		switch (pivot)
		{
			case UIWidget.Pivot.Left:
			isActive = IsLeft(mWidget.pivot);
			break;

			case UIWidget.Pivot.Right:
			isActive = IsRight(mWidget.pivot);
			break;

			case UIWidget.Pivot.Top:
			isActive = IsTop(mWidget.pivot);
			break;

			case UIWidget.Pivot.Bottom:
			isActive = IsBottom(mWidget.pivot);
			break;

			case UIWidget.Pivot.Center:
			isActive = isHorizontal ? pivot == GetHorizontal(mWidget.pivot) : pivot == GetVertical(mWidget.pivot);
			break;
		}

		if (GUILayout.Toggle(isActive, text, style) != isActive)
			SetPivot(pivot, isHorizontal);
	}

	static bool IsLeft (UIWidget.Pivot pivot)
	{
		return pivot == UIWidget.Pivot.Left ||
			pivot == UIWidget.Pivot.TopLeft ||
			pivot == UIWidget.Pivot.BottomLeft;
	}

	static bool IsRight (UIWidget.Pivot pivot)
	{
		return pivot == UIWidget.Pivot.Right ||
			pivot == UIWidget.Pivot.TopRight ||
			pivot == UIWidget.Pivot.BottomRight;
	}

	static bool IsTop (UIWidget.Pivot pivot)
	{
		return pivot == UIWidget.Pivot.Top ||
			pivot == UIWidget.Pivot.TopLeft ||
			pivot == UIWidget.Pivot.TopRight;
	}

	static bool IsBottom (UIWidget.Pivot pivot)
	{
		return pivot == UIWidget.Pivot.Bottom ||
			pivot == UIWidget.Pivot.BottomLeft ||
			pivot == UIWidget.Pivot.BottomRight;
	}

	static UIWidget.Pivot GetHorizontal (UIWidget.Pivot pivot)
	{
		if (IsLeft(pivot)) return UIWidget.Pivot.Left;
		if (IsRight(pivot)) return UIWidget.Pivot.Right;
		return UIWidget.Pivot.Center;
	}

	static UIWidget.Pivot GetVertical (UIWidget.Pivot pivot)
	{
		if (IsTop(pivot)) return UIWidget.Pivot.Top;
		if (IsBottom(pivot)) return UIWidget.Pivot.Bottom;
		return UIWidget.Pivot.Center;
	}

	static UIWidget.Pivot Combine (UIWidget.Pivot horizontal, UIWidget.Pivot vertical)
	{
		if (horizontal == UIWidget.Pivot.Left)
		{
			if (vertical == UIWidget.Pivot.Top) return UIWidget.Pivot.TopLeft;
			if (vertical == UIWidget.Pivot.Bottom) return UIWidget.Pivot.BottomLeft;
			return UIWidget.Pivot.Left;
		}

		if (horizontal == UIWidget.Pivot.Right)
		{
			if (vertical == UIWidget.Pivot.Top) return UIWidget.Pivot.TopRight;
			if (vertical == UIWidget.Pivot.Bottom) return UIWidget.Pivot.BottomRight;
			return UIWidget.Pivot.Right;
		}
		return vertical;
	}

	/// <summary>
	/// Determine the distance from the mouse position to the world rectangle specified by the 4 points.
	/// </summary>

	static public float SceneViewDistanceToRectangle (Vector3[] worldPoints, Vector2 mousePos)
	{
		Vector2[] screenPoints = new Vector2[4];
		for (int i = 0; i < 4; ++i)
			screenPoints[i] = HandleUtility.WorldToGUIPoint(worldPoints[i]);
		return NGUIMath.DistanceToRectangle(screenPoints, mousePos);
	}

	/// <summary>
	/// Raycast into the specified panel, returning a list of widgets.
	/// Just like NGUIMath.Raycast, but doesn't rely on having a camera.
	/// </summary>

	static public BetterList<UIWidget> SceneViewRaycast (UIPanel panel, Vector2 mousePos)
	{
		BetterList<UIWidget> list = new BetterList<UIWidget>();

		for (int i = 0; i < UIWidget.list.size; ++i)
		{
			UIWidget w = UIWidget.list[i];
			Vector3[] corners = NGUIMath.CalculateWidgetCorners(w);
			if (SceneViewDistanceToRectangle(corners, mousePos) == 0f)
				list.Add(w);
		}

		list.Sort(delegate(UIWidget w1, UIWidget w2) { return w2.depth.CompareTo(w1.depth); });
		return list;
	}

	void SetPivot (UIWidget.Pivot pivot, bool isHorizontal)
	{
		UIWidget.Pivot horizontal = GetHorizontal(mWidget.pivot);
		UIWidget.Pivot vertical = GetVertical(mWidget.pivot);

		pivot = isHorizontal ? Combine(pivot, vertical) : Combine(horizontal, pivot);

		if (mWidget.pivot != pivot)
		{
			NGUIEditorTools.RegisterUndo("Pivot change", mWidget);
			mWidget.pivot = pivot;
		}
	}

	/// <summary>
	/// Any and all derived functionality.
	/// </summary>

	protected virtual void OnInit() { }
	protected virtual bool DrawProperties () { return true; }
	protected virtual void DrawExtraProperties () { }
}


text:
module core {
    /**
     * 声音控制
     * 本类为游戏音乐及音效管理类,并依赖于音效配置表的配置,使用本类先应先熟悉音效配置表的相关字段说明。
     */
    export class SoundUtils {
        /**
         * 声音字典
         */
        private m_sounds: Dictionary<egret.Sound>;
        /**
         * 加载列表
         */
        private m_loadings: Dictionary<any>
        /**
         * 音频字典
         */
        private m_channels: Dictionary<egret.SoundChannel>;
        /**
         * 当前播放音效字典
         */
        private m_curEffect: Dictionary<egret.Sound>;
        /**
         * 当前播放背景音乐字典
         */
        private m_curBGM: Dictionary<egret.Sound>;
        /**
         * 回调字典
         */
        private m_callbacks: Dictionary<() => void>;
        /**
         * 播放通道 同一通道音乐覆盖
         */
        private m_playChannel: Dictionary<egret.Sound>;

        private m_BGMVolume: number = 1;

        private m_effectVolume: number = 1;
        /**
         * 音效开关
         */
        private m_effectEnable: boolean = false;
        /**
         * 音乐开关
         */
        private m_musicEnable: boolean = false;

        private static s_instance: SoundUtils;
        public static getInstance(): SoundUtils {
            if (SoundUtils.s_instance == null) {
                SoundUtils.s_instance = new SoundUtils();
            }
            return SoundUtils.s_instance;
        }

        public constructor() {
            this.m_sounds = new Dictionary<egret.Sound>();
            this.m_loadings = new Dictionary<any>();
            this.m_channels = new Dictionary<egret.SoundChannel>();
            this.m_curBGM = new Dictionary<egret.Sound>();
            this.m_curEffect = new Dictionary<egret.Sound>();
            this.m_callbacks = new Dictionary<() => void>();
            this.m_playChannel = new Dictionary<egret.Sound>();
            let value: string = egret.localStorage.getItem('soundEffect');
            if (value) {
                this.m_effectVolume = parseInt(value);
            }
            value = egret.localStorage.getItem('soundBGM');
            if (value) {
                this.m_BGMVolume = parseInt(value);
            }
        }
        /**
         * 音乐播放完成
         * @param  {egret.Event} event
         */
        private onPlayComplete(event: egret.Event): void {
            let channel: egret.SoundChannel = event.currentTarget;
            let callback: () => void = this.m_callbacks.get(channel.hashCode);
            if (callback) {
                callback();
            }
            channel['count']++;
            if (channel['count'] >= channel['maxCount']) {
                this.stop(channel['owner']);
            }
        }
        /**
         * 停止音乐通道播放
         * @param  {number} coverChannel
         */
        private stopSound(coverChannel: number): void {
            let sound: egret.Sound = this.m_playChannel.get(coverChannel);
            if (sound) {
                this.stop(sound);
            }
        }
        /**
         * 停止播放音乐
         * @param  {egret.Sound} sound
         */
        private stop(sound: egret.Sound): void {
            let channel: egret.SoundChannel = this.m_channels.get(sound.hashCode);
            if (channel) {
                egret.setTimeout(() => {
                    if (channel) {
                        channel.stop();
                        if (channel.hasEventListener(egret.Event.SOUND_COMPLETE)) {
                            channel.removeEventListener(egret.Event.SOUND_COMPLETE, this.onPlayComplete, this);
                        }
                        this.m_callbacks.remove(channel.hashCode);
                        this.m_channels.remove(sound.hashCode);
                    }
                }, this, 500);
            }
            this.m_playChannel.remove(sound['cover']);
            if (sound.type == egret.Sound.EFFECT) {
                this.m_curEffect.remove(this.m_sounds.getKeyByValue(sound));
            } else {
                this.m_curBGM.remove(this.m_sounds.getKeyByValue(sound));
            }
        }
        /**
         * 停止所有音乐
         */
        private stopAllMusic(): void {
            let sounds: egret.Sound[] = this.m_curBGM.values;
            for (let i: number = 0, iLen: number = sounds.length; i < iLen; i++) {
                let sound: egret.Sound = sounds[i];
                if (sound) {
                    this.stop(sound);
                }
            }
        }
        /**
         * 停止所有音效
         */
        private stopAllEffect(): void {
            let sounds: egret.Sound[] = this.m_curEffect.values;
            for (let i: number = 0, iLen: number = sounds.length; i < iLen; i++) {
                let sound: egret.Sound = sounds[i];
                if (sound) {
                    this.stop(sound);
                }
            }
        }

        /**
         * 播放音乐或音效
         * @param  {number} id  声音配置ID
         * @param  {number=1} loop 播放次数,默认值是 1,循环播放。 大于 0 为播放次数,如 1 为播放 1 次;小于等于 0,为循环播放。
         * @param  {()=>void} onPlayComplete?   播放完毕回调
         */
        public playSound(id: number, loop: number = 1, onPlayComplete?: () => void): void {
            let config: SoundConfig = Config.getConfig(SoundConfig).get(id);
            if (config) {
                if (this.isSoundPlaying(id) && config.soundType == 1) {
                    return;
                }
                this.stopSound(config.coverKey);
            } else {
                egret.warn(`ID为${id}的音效在SoundConfig中不存在`);
                return;
            }
            if ((config.soundType == 0 && !this.m_effectEnable) ||
                (config.soundType != 0 && !this.m_musicEnable)) {
                return;
            }
            let sound: egret.Sound = this.m_sounds.get(id);
            if (!sound) {
                sound = RES.getRes(config.soundName);
                if (sound) {
                    sound.type = config.soundType == 0 ? egret.Sound.EFFECT : egret.Sound.MUSIC;
                    this.m_sounds.add(id, sound);
                } else {
                    let data = {
                        config: config,
                        loop: loop,
                        callback: onPlayComplete
                    }
                    if (config.soundType != 0) {
                        this.m_loadings.add(id, data);
                    }
                    RES.getResAsync(config.soundName, function (): RES.GetResAsyncCallback {
                        return function (value, key): void {
                            egret.log(`名称为${config.soundName}的音效资源加载完成`);
                            if (this.m_loadings.remove(id)) {
                                this.playSound(id, loop, onPlayComplete);
                            }
                        }
                    } (), this);
                }
            }
            if (sound) {
                if (sound.type == egret.Sound.EFFECT) {
                    this.m_curEffect.add(id, sound);
                } else {
                    this.m_curBGM.add(id, sound);
                }
                this.m_playChannel.add(config.coverKey, sound);
                sound['cover'] = config.coverKey;
                let channel: egret.SoundChannel = sound.play(0, loop);
                if (channel) {
                    channel['owner'] = sound;
                    channel['maxCount'] = loop > 0 ? loop : Number.MAX_VALUE;
                    channel['count'] = 0;
                    if (sound.type == egret.Sound.EFFECT) {
                        channel.volume = this.m_effectVolume;
                    } else {
                        channel.volume = this.m_BGMVolume;
                    }
                    if (onPlayComplete) {
                        this.m_callbacks.add(channel.hashCode, onPlayComplete);
                    }
                    channel.addEventListener(egret.Event.SOUND_COMPLETE, this.onPlayComplete, this);
                    this.m_channels.add(sound.hashCode, channel);
                }
            } else {
                egret.warn(`名称为${config.soundName}的音效资源不存在`);
                return;
            }
        }
        /**
         * 停止播放音乐
         * @param id 声音ID
         */
        public stopSoundByID(id: number): void {
            let sound: egret.Sound = this.m_sounds.get(id);
            if (sound) {
                this.stop(sound);
                this.m_loadings.remove(id);
            }
        }
        /**
         * 停止播放所有音乐及音效
         */
        public stopAllSound(): void {
            //停止所有音效
            this.stopAllEffect();
            //停止所有音乐
            this.stopAllMusic();
            if (this.m_loadings) {
                this.m_loadings.clear();
            }
        }
        /**
         * 设置背景音乐音量
         * @param  {number} volume
         */
        public setBGMValume(volume: number): void {
            egret.localStorage.setItem('soundBGM', volume.toString());
            this.m_BGMVolume = volume;
            let sounds: egret.Sound[] = this.m_curBGM.values;
            for (let i: number = 0, iLen: number = sounds.length; i < iLen; i++) {
                let sound: egret.Sound = sounds[i];
                if (sound) {
                    let channel: egret.SoundChannel = this.m_channels.get(sound.hashCode);
                    if (channel) {
                        channel.volume = this.m_musicEnable ? volume : 0;
                    }
                }
            }
        }
        /**
         * 得到背景音乐音量
         * @return number
         */
        public getBGMValue(): number {
            return this.m_BGMVolume;
        }
        /**
         * 设置音效音量
         * @param  {number} volume
         */
        public setEffectValume(volume: number): void {
            egret.localStorage.setItem('soundEffect', volume.toString());
            this.m_effectVolume = volume;
            let sounds: egret.Sound[] = this.m_curEffect.values;
            for (let i: number = 0, iLen: number = sounds.length; i < iLen; i++) {
                let sound: egret.Sound = sounds[i];
                if (sound) {
                    let channel: egret.SoundChannel = this.m_channels.get(sound.hashCode);
                    if (channel) {
                        channel.volume = this.m_effectEnable ? volume : 0;
                    }
                }
            }
        }

        /**
         * 得到音效音量
         * @returns number
         */
        public getEffectValue(): number {
            return this.m_effectVolume;
        }

        /**
         * 开关音效
         * @param  {boolean} bool
         */
        public setEffectEnable(bool: boolean): void {
            this.m_effectEnable = bool;
            this.setEffectValume(this.m_effectVolume);
        }
        /**
         * 开关音乐
         * @param  {boolean} bool
         */
        public setMusicEnable(bool: boolean): void {
            this.m_musicEnable = bool;
            this.setBGMValume(this.m_BGMVolume);
        }
        /**
         * 检测ID是否播放
         * @param  {number} id
         */
        public isSoundPlaying(id: number): boolean {
            let sound: egret.Sound = this.m_sounds.get(id);
            if (sound) {
                let channel: egret.SoundChannel = this.m_channels.get(sound.hashCode);
                if (channel) {
                    return true;
                }
            }
            return false;
        }
    }
}


text:
<ion-view view-title="Comments">
  <ion-content>
    <ion-refresher
      pulling-text="Release to refresh..."
      on-refresh="vm.storeSupport.refresh()">
    </ion-refresher>
    <ion-list>
      <ion-item ng-repeat="comment in vm.comments" class="item-button-right">

            {{ comment.by }}

              {{ comment.time * 1000 | timeAgo }}

        {{ comment.kids.length }}
      </ion-item>
    </ion-list>
    <ion-infinite-scroll
      ng-if="vm.storeSupport.hasMoreItemsToLoad()"
      on-infinite="vm.storeSupport.loadMoreItems()"
      distance="1%">
    </ion-infinite-scroll>
  </ion-content>
</ion-view>


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace System.Buffers
{
    public interface IOutput
    {
        Span<byte> Buffer { get; }
        void Advance(int bytes);

        /// <summary>desiredBufferLength == 0 means "i don't care"</summary>
        void Enlarge(int desiredBufferLength = 0);
    }
}


text:
using System;

using Foundation;
using UIKit;

namespace HelloXamarin
{
	public partial class UserInfoCell : UITableViewCell
	{
		bool InfoTf_ShouldReturn(UITextField textField)
		{
			return textField.ResignFirstResponder();
		}

		public static readonly NSString Key = new NSString("UserInfoCell");
		public static readonly UINib Nib;
		public String mTfinfo;

		static UserInfoCell()
		{
			Nib = UINib.FromName("UserInfoCell", NSBundle.MainBundle);
		}

		protected UserInfoCell(IntPtr handle) : base(handle)
		{
			// Note: this .ctor should not contain any initialization logic.
		}

		public void updateCell(int index) {
			switch (index) {
				case 0:
					//注意这里要严格注意图片路径的大小写,真机上会严格检查,模拟器不会
					iconImage.Image = UIImage.FromFile("Images/icon_user_account.png");
					infoLa.Text = "员工号";
					infoTf.Text = CacheHelper.getInstance().userData.accountId;
					mTfinfo = CacheHelper.getInstance().userData.accountId;
					infoTf.UserInteractionEnabled = false;
					break;
				case 1:
					iconImage.Image = UIImage.FromFile("Images/icon_user_2_disabled.png");
					infoLa.Text = "昵称";
					infoTf.Text = CacheHelper.getInstance().userData.nickName;
					mTfinfo = CacheHelper.getInstance().userData.nickName;
					break;
				case 2:
					iconImage.Image = UIImage.FromFile("Images/icon_user_4_disabled.png");
					infoLa.Text = "项目组";
					infoTf.Text = CacheHelper.getInstance().userData.pCode;
					mTfinfo = CacheHelper.getInstance().userData.pCode;
					break;
				case 3:
					iconImage.Image = UIImage.FromFile("Images/icon_user_3_disabled.png");
					infoLa.Text = "签名";
					infoTf.Text = CacheHelper.getInstance().userData.idiograph;
					mTfinfo = CacheHelper.getInstance().userData.idiograph;
					break;
			}
			infoTf.ShouldReturn += InfoTf_ShouldReturn;

			infoTf.Ended += (sender, e) =>
			{
				mTfinfo = infoTf.Text;
				Console.WriteLine(mTfinfo);
			};
		}
	}
}


text:
				<input type="checkbox" name="item_index[]" />

			<?php
			//Query description data
			$con=mysqli_connect('localhost',"root","root","whap");
			$results = mysqli_query($con,"select description from questionCode_description where questionCode = '" . $_GET['questionCode'] . "'");
			$result = mysqli_fetch_array($results);
			//Fill description and variable code in
			echo "<input type='text' class='form-control' name='item_name[]' value ='" . htmlspecialchars($_GET['questionCode']). "'/>"
			?>


text:
<resources xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="windowActionModeOverlay">true</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:actionModeBackground">@color/colorPrimary</item>
        <item name="actionModeBackground">@color/colorPrimary</item>
        <item name="android:textColorHighlight">#afff</item>
    </style>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="OverlayDialog" parent="@android:style/Theme.Dialog">
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowFrame">@null</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowIsFloating">true</item>
        <item name="android:windowIsTranslucent">false</item>
        <item name="android:backgroundDimEnabled">false</item>
    </style>

    <style name="AppTheme.Collapsed" parent="android:TextAppearance">
        <item name="android:textColor">@android:color/white</item>
        <item name="android:textSize">16sp</item>
    </style>

    <style name="AppTheme.Expanded" parent="android:TextAppearance">
        <item name="android:textColor">@android:color/white</item>
        <item name="android:textSize">28sp</item>
    </style>
    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

    <style name="FullscreenTheme" parent="AppTheme">
        <item name="android:actionBarStyle">@style/FullscreenActionBarStyle</item>
        <item name="android:windowActionBarOverlay">true</item>
        <item name="android:windowBackground">@null</item>
        <item name="metaButtonBarStyle">?android:attr/buttonBarStyle</item>
        <item name="metaButtonBarButtonStyle">?android:attr/buttonBarButtonStyle</item>
    </style>

    <style name="FullscreenActionBarStyle" parent="Widget.AppCompat.ActionBar">
        <item name="android:background">@color/black_overlay</item>
    </style>

</resources>


text:
/**
@module ember
@submodule ember-htmlbars
*/

import Ember from "ember-metal/core"; // assert
import { uuid } from "ember-metal/utils";
import run from "ember-metal/run_loop";
import { readUnwrappedModel } from "ember-views/streams/utils";
import { isSimpleClick } from "ember-views/system/utils";
import ActionManager from "ember-views/system/action_manager";

/**
  The `{{action}}` helper provides a useful shortcut for registering an HTML
  element within a template for a single DOM event and forwarding that
  interaction to the template's controller or specified `target` option.

  If the controller does not implement the specified action, the event is sent
  to the current route, and it bubbles up the route hierarchy from there.

  For more advanced event handling see [Ember.Component](/api/classes/Ember.Component.html)

  ### Use
  Given the following application Handlebars template on the page

  ```handlebars
  <div {{action 'anActionName'}}>
    click me
  </div>
  ```

  And application code

  ```javascript
  App.ApplicationController = Ember.Controller.extend({
    actions: {
      anActionName: function() {
      }
    }
  });
  ```

  Will result in the following rendered HTML

  ```html
  <div class="ember-view">
    <div data-ember-action="1">
      click me
    </div>
  </div>
  ```

  Clicking "click me" will trigger the `anActionName` action of the
  `App.ApplicationController`. In this case, no additional parameters will be passed.

  If you provide additional parameters to the helper:

  ```handlebars
  <button {{action 'edit' post}}>Edit</button>
  ```

  Those parameters will be passed along as arguments to the JavaScript
  function implementing the action.

  ### Event Propagation

  Events triggered through the action helper will automatically have
  `.preventDefault()` called on them. You do not need to do so in your event
  handlers. If you need to allow event propagation (to handle file inputs for
  example) you can supply the `preventDefault=false` option to the `{{action}}` helper:

  ```handlebars
  <div {{action "sayHello" preventDefault=false}}>
    <input type="file" />
    <input type="checkbox" />
  </div>
  ```

  To disable bubbling, pass `bubbles=false` to the helper:

  ```handlebars
  <button {{action 'edit' post bubbles=false}}>Edit</button>
  ```

  If you need the default handler to trigger you should either register your
  own event handler, or use event methods on your view class. See [Ember.View](/api/classes/Ember.View.html)
  'Responding to Browser Events' for more information.

  ### Specifying DOM event type

  By default the `{{action}}` helper registers for DOM `click` events. You can
  supply an `on` option to the helper to specify a different DOM event name:

  ```handlebars
  <div {{action "anActionName" on="doubleClick"}}>
    click me
  </div>
  ```

  See `Ember.View` 'Responding to Browser Events' for a list of
  acceptable DOM event names.

  ### Specifying whitelisted modifier keys

  By default the `{{action}}` helper will ignore click event with pressed modifier
  keys. You can supply an `allowedKeys` option to specify which keys should not be ignored.

  ```handlebars
  <div {{action "anActionName" allowedKeys="alt"}}>
    click me
  </div>
  ```

  This way the `{{action}}` will fire when clicking with the alt key pressed down.

  Alternatively, supply "any" to the `allowedKeys` option to accept any combination of modifier keys.

  ```handlebars
  <div {{action "anActionName" allowedKeys="any"}}>
    click me with any key pressed
  </div>
  ```

  ### Specifying a Target

  There are several possible target objects for `{{action}}` helpers:

  In a typical Ember application, where templates are managed through use of the
  `{{outlet}}` helper, actions will bubble to the current controller, then
  to the current route, and then up the route hierarchy.

  Alternatively, a `target` option can be provided to the helper to change
  which object will receive the method call. This option must be a path
  to an object, accessible in the current context:

  ```handlebars
  {{! the application template }}
  <div {{action "anActionName" target=view}}>
    click me
  </div>
  ```

  ```javascript
  App.ApplicationView = Ember.View.extend({
    actions: {
      anActionName: function() {}
    }
  });

  ```

  ### Additional Parameters

  You may specify additional parameters to the `{{action}}` helper. These
  parameters are passed along as the arguments to the JavaScript function
  implementing the action.

  ```handlebars
  {{#each person in people}}
    <div {{action "edit" person}}>
      click me
    </div>
  {{/each}}
  ```

  Clicking "click me" will trigger the `edit` method on the current controller
  with the value of `person` as a parameter.

  @method action
  @for Ember.Handlebars.helpers
  @param {String} actionName
  @param {Object} [context]*
  @param {Hash} options
*/
export default {
  setupState: function(state, env, scope, params, hash) {
    var getStream = env.hooks.get;
    var read = env.hooks.getValue;

    var actionName = read(params[0]);

    Ember.assert("You specified a quoteless path to the {{action}} helper " +
                 "which did not resolve to an action name (a string). " +
                 "Perhaps you meant to use a quoted actionName? (e.g. {{action 'save'}}).",
                 typeof actionName === 'string');

    var actionArgs = [];
    for (var i = 1, l = params.length; i < l; i++) {
      actionArgs.push(readUnwrappedModel(params[i]));
    }

    var target;
    if (hash.target) {
      if (typeof hash.target === 'string') {
        target = read(getStream(env, scope, hash.target));
      } else {
        target = read(hash.target);
      }
    } else {
      target = read(scope.locals.controller) || read(scope.self);
    }

    return { actionName, actionArgs, target };
  },

  isStable: function(state, env, scope, params, hash) {
    return true;
  },

  render: function(node, env, scope, params, hash, template, inverse, visitor) {
    var actionId = ActionHelper.registerAction({
      node: node,
      eventName: hash.on || "click",
      bubbles: hash.bubbles,
      preventDefault: hash.preventDefault,
      withKeyCode: hash.withKeyCode,
      allowedKeys: hash.allowedKeys
    });

    node.cleanup = function() {
      ActionHelper.unregisterAction(actionId);
    };

    env.dom.setAttribute(node.element, 'data-ember-action', actionId);
  }
};

export var ActionHelper = {};

// registeredActions is re-exported for compatibility with older plugins
// that were using this undocumented API.
ActionHelper.registeredActions = ActionManager.registeredActions;

ActionHelper.registerAction = function({ node, eventName, preventDefault, bubbles, allowedKeys }) {
  var actionId = uuid();

  ActionManager.registeredActions[actionId] = {
    eventName,
    handler(event) {
      if (!isAllowedEvent(event, allowedKeys)) {
        return true;
      }

      if (preventDefault !== false) {
        event.preventDefault();
      }

      if (bubbles === false) {
        event.stopPropagation();
      }

      let { target, actionName, actionArgs } = node.state;

      run(function runRegisteredAction() {
        if (target.send) {
          target.send.apply(target, [actionName, ...actionArgs]);
        } else {
          Ember.assert(
            "The action '" + actionName + "' did not exist on " + target,
            typeof target[actionName] === 'function'
          );

          target[actionName].apply(target, actionArgs);
        }
      });
    }
  };

  return actionId;
};

ActionHelper.unregisterAction = function(actionId) {
  delete ActionManager.registeredActions[actionId];
};

var MODIFIERS = ["alt", "shift", "meta", "ctrl"];
var POINTER_EVENT_TYPE_REGEX = /^click|mouse|touch/;

function isAllowedEvent(event, allowedKeys) {
  if (typeof allowedKeys === "undefined") {
    if (POINTER_EVENT_TYPE_REGEX.test(event.type)) {
      return isSimpleClick(event);
    } else {
      allowedKeys = '';
    }
  }

  if (allowedKeys.indexOf("any") >= 0) {
    return true;
  }

  for (var i=0, l=MODIFIERS.length;i<l;i++) {
    if (event[MODIFIERS[i] + "Key"] && allowedKeys.indexOf(MODIFIERS[i]) === -1) {
      return false;
    }
  }

  return true;
}


text:
<!doctype html>

		<meta charset="utf-8">

		<title>Fermented Vegetables</title>

		<meta name="description" content="Learn how easy it is to ferment your own vegetables at home.">
		<meta name="author" content="Branden Byers">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<link rel="stylesheet" href="css/reveal.min.css">
		<link rel="stylesheet" href="css/theme/beige-edited.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">

How to Ferment Vegetables

Fermentation Basics

Fermentation is Easy

Vegetable(s)

Fermentation Vessel

Salt

(sometimes water)

Controlled Rot

Time

Temperature

Lower Temps = higher quality

Higher temps = less complex flavor

Salinity

Oxygen

Lactic Acid Bacteria

Salt-tolerant

Acid-producing

homofermentative

heterofermentative

Some of the nicest and most beneficial

Spontaneous Fermenation VS Starter Cultures

Stages of Microbial Transformation

Stage 1: Leuconostoc mesenteroides

Produces carbon dioxide

Replaces oxygen

Acid sensitive

Lactobacillus plantarum

Continues to consume sugars

Homofermentative

Lactobacillus brevis

Continues to lower pH

Once finished, no more bubbles

Fermentation as Luxury

Simple Sauerkraut

Ingredients/Materials

900 grams cabbage

20 grams salt

chef's knife

cutting board

large bowl

quart-size jars

scale

weights (optional)

Basic Knife Skills

Knife grip

Finger curl

Thumb push

How to make sauerkraut

Prep Cabbage

Remove and save outer leaves

Slice cabbage into quarters

Save the core

Shred the cabbage

Thin

Thick

Squares

Choose Your Salt

Types of Salt

Table Salt

Iodine

Anti-Caking Agents

Kosher Salt

No iodine

Sometimes anti-caking

Sea Salt

Refined or unrefined

Sometimes iodized

Pickling Salt

Highly refined

Measuring Salt

Volumentric measurements are not accurate

Weigh your salt

Or keep batches small

Salt Percentage

2 to 3%

More and bacteria can't thrive

Less and might develop slimy or off flavors

Salt and Massage Cabbage

Break down cellular walls

Osmosis

Juice, Juice, Juic

Water is plain

Pack cabbage

Keep Below the Brine

Finger method

Weights

Glass weights

Clay weights

Rocks

Jar-inside-jar method

Cover with cloth

Or close inside jar lid

Plastic bag

Release CO2

Check for first week

May overflow

Mild danger of pressure buildup

Fermentation Length

3 days to 6 months

Colder = slower

Warmer = faster

pH Drop

4.6 or lower

High acid food

Resists spoilage

Refrigerate when ready

Alternative Flavors

Juniper Berry & Caraway Seeds

Spicy Sauerkraut

Brussels Sprouts Sauerkraut

Final thoughts: Cabbage Juice

Giardiniera

1 head cauliflower

2 large carrots

1 zucchini

3 cloves garlic

750 grams water

38 grams salt

2 quart-sized jars

glass weights

pint size jar

Different brining process

2-3% salt by weight of vegatables

5% salt by weight of water

Chopping the Vegetables

Julliened carrots

Sliced zucchini

Diced Garlic

Mix Salt Brine

Pack in Jar & Cover with Brine

Weight Down Vegetables

Variable size is more challenging

Glass weights

Half-pint jar

Don't forget to release CO2

Fermentation Time

2-6 weeks

Shorter than sauerkraut

Cauliflower tastes better long but not too long

Long-Term Storage

Refrigerator

Basement or Root Cellar

Slowly more acidic

At first will taste great by itself

Eventually, use for cooking

Final Thoughts: Two ways, most vegetables


text:
@interface CubeViewController : GLKViewController

- (void)payActionSuccess;

@end


text:
<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Created by PhpStorm.
 * User: Vitalik
 * Date: 07.03.2016
 * Time: 10:40
 */

class Controller_Pages_CacheClear extends Controller  {

    public function action_index() {

        $data = array();
        if ($this->request->post('password') == '21Sxq6y09v6dj4S') {

            $data['syses'] = 'Success';

            HTML::removeDirectory($_SERVER['DOCUMENT_ROOT'].'/application/cache');

        }

        $this->response->body(View::factory('pages/cache_clear', $data));
    }

}


text:
class CRPCTable;

void RegisterZMQRPCCommands(CRPCTable& t);

#endif // BITCOIN_ZMQ_ZMRRPC_H


text:
package com.suchasplus.jconcurrent.week11;

/**
 * Powered by suchasplus@gmail.com on 2017/5/4.
 */
public class Week11Main {

    public static void main(String[] args) {
        System.out.println("HEAD OFFSET : " + (MemoryUtils.getIntegersPerCacheLine() - 1));
        System.out.println("TAIL OFFSET : " + ((MemoryUtils.getIntegersPerCacheLine() - 1) + MemoryUtils.getIntegersPerCacheLine()));

        BlockingArrayQueue<Integer> baq = new BlockingArrayQueue<>(3, 1, 6);

        baq.offer(11);

        baq.offer(23);

        baq.offer(123);

        baq.poll();

        baq.offer(321);

        baq.offer(56);

        baq.offer(78);

        baq.clear();
    }
}


text:
package org.apache.carbondata.core.datastore.chunk.store.impl.safe;

import java.nio.ByteBuffer;

import org.apache.carbondata.core.constants.CarbonCommonConstants;
import org.apache.carbondata.core.scan.result.vector.CarbonColumnVector;
import org.apache.carbondata.core.util.ByteUtil;

import org.apache.spark.sql.types.BooleanType;
import org.apache.spark.sql.types.DataType;
import org.apache.spark.sql.types.IntegerType;
import org.apache.spark.sql.types.LongType;
import org.apache.spark.sql.types.ShortType;
import org.apache.spark.sql.types.StringType;

/**
 * Below class is responsible to store variable length dimension data chunk in
 * memory Memory occupied can be on heap or offheap using unsafe interface
 */
public class SafeVariableLengthDimensionDataChunkStore extends SafeAbsractDimensionDataChunkStore {

  /**
   * total number of rows
   */
  private int numberOfRows;

  /**
   * offset of the data this will be used during search, as we can directly jump
   * to particular location
   */
  private int[] dataOffsets;

  public SafeVariableLengthDimensionDataChunkStore(boolean isInvertedIndex, int numberOfRows) {
    super(isInvertedIndex);
    this.numberOfRows = numberOfRows;
    this.dataOffsets = new int[numberOfRows];
  }

  /**
   * Below method will be used to put the rows and its metadata in offheap
   *
   * @param invertedIndex        inverted index to be stored
   * @param invertedIndexReverse inverted index reverse to be stored
   * @param data                 data to be stored
   */
  @Override public void putArray(final int[] invertedIndex, final int[] invertedIndexReverse,
      byte[] data) {
    // first put the data, inverted index and reverse inverted index to memory
    super.putArray(invertedIndex, invertedIndexReverse, data);
    // As data is of variable length and data format is
    // <length in short><data><length in short><data>
    // we need to store offset of each data so data can be accessed directly
    // for example:
    //data = {0,5,1,2,3,4,5,0,6,0,1,2,3,4,5,0,2,8,9}
    //so value stored in offset will be position of actual data
    // [2,9,17]
    // to store this value we need to get the actual data length + 2 bytes used for storing the
    // length

    // start position will be used to store the current data position
    int startOffset = 0;
    // as first position will be start from 2 byte as data is stored first in the memory block
    // we need to skip first two bytes this is because first two bytes will be length of the data
    // which we have to skip
    dataOffsets[0] = CarbonCommonConstants.SHORT_SIZE_IN_BYTE;
    // creating a byte buffer which will wrap the length of the row
    ByteBuffer buffer = ByteBuffer.wrap(data);
    for (int i = 1; i < numberOfRows; i++) {
      buffer.position(startOffset);
      // so current row position will be
      // previous row length + 2 bytes used for storing previous row data
      startOffset += buffer.getShort() + CarbonCommonConstants.SHORT_SIZE_IN_BYTE;
      // as same byte buffer is used to avoid creating many byte buffer for each row
      // we need to clear the byte buffer
      dataOffsets[i] = startOffset + CarbonCommonConstants.SHORT_SIZE_IN_BYTE;
    }
  }

  @Override public byte[] getRow(int rowId) {
    // if column was explicitly sorted we need to get the rowid based inverted index reverse
    if (isExplictSorted) {
      rowId = invertedIndexReverse[rowId];
    }
    // now to get the row from memory block we need to do following thing
    // 1. first get the current offset
    // 2. if it's not a last row- get the next row offset
    // Subtract the current row offset + 2 bytes(to skip the data length) with next row offset
    // else subtract the current row offset with complete data
    // length get the offset of set of data
    int currentDataOffset = dataOffsets[rowId];
    short length = 0;
    // calculating the length of data
    if (rowId < numberOfRows - 1) {
      length = (short) (dataOffsets[rowId + 1] - (currentDataOffset
          + CarbonCommonConstants.SHORT_SIZE_IN_BYTE));
    } else {
      // for last record
      length = (short) (this.data.length - currentDataOffset);
    }
    byte[] currentRowData = new byte[length];
    System.arraycopy(data, currentDataOffset, currentRowData, 0, length);
    return currentRowData;
  }

  @Override public void fillRow(int rowId, CarbonColumnVector vector, int vectorRow) {
    // if column was explicitly sorted we need to get the rowid based inverted index reverse
    if (isExplictSorted) {
      rowId = invertedIndexReverse[rowId];
    }
    // now to get the row from memory block we need to do following thing
    // 1. first get the current offset
    // 2. if it's not a last row- get the next row offset
    // Subtract the current row offset + 2 bytes(to skip the data length) with next row offset
    // else subtract the current row offset with complete data
    // length get the offset of set of data
    int currentDataOffset = dataOffsets[rowId];
    short length = 0;
    // calculating the length of data
    if (rowId < numberOfRows - 1) {
      length = (short) (dataOffsets[rowId + 1] - (currentDataOffset
          + CarbonCommonConstants.SHORT_SIZE_IN_BYTE));
    } else {
      // for last record
      length = (short) (this.data.length - currentDataOffset);
    }
    if (ByteUtil.UnsafeComparer.INSTANCE.equals(CarbonCommonConstants.MEMBER_DEFAULT_VAL_ARRAY, 0,
        CarbonCommonConstants.MEMBER_DEFAULT_VAL_ARRAY.length, data, currentDataOffset, length)) {
      vector.putNull(vectorRow);
    } else {
      DataType dt = vector.getType();
      if (dt instanceof StringType) {
        vector.putBytes(vectorRow, currentDataOffset, length, data);
      } else if (dt instanceof BooleanType) {
        vector.putBoolean(vectorRow, ByteUtil.toBoolean(data[currentDataOffset]));
      } else if (dt instanceof ShortType) {
        vector.putShort(vectorRow, ByteUtil.toShort(data, currentDataOffset, length));
      } else if (dt instanceof IntegerType) {
        vector.putInt(vectorRow, ByteUtil.toInt(data, currentDataOffset, length));
      } else if (dt instanceof LongType) {
        vector.putLong(vectorRow, ByteUtil.toLong(data, currentDataOffset, length));
      }
    }
  }

  @Override public int compareTo(int index, byte[] compareValue) {
    // now to get the row from memory block we need to do following thing
    // 1. first get the current offset
    // 2. if it's not a last row- get the next row offset
    // Subtract the current row offset + 2 bytes(to skip the data length) with next row offset
    // else subtract the current row offset with complete data
    // length

    // get the offset of set of data
    int currentDataOffset = dataOffsets[index];
    short length = 0;
    // calculating the length of data
    if (index < numberOfRows - 1) {
      length = (short) (dataOffsets[index + 1] - (currentDataOffset
          + CarbonCommonConstants.SHORT_SIZE_IN_BYTE));
    } else {
      // for last record
      length = (short) (this.data.length - currentDataOffset);
    }
    return ByteUtil.UnsafeComparer.INSTANCE
        .compareTo(data, currentDataOffset, length, compareValue, 0, compareValue.length);
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<ldswebml type="image" uri="/media-library/images/temples/atlanta-georgia#atlanta-temple-lds-811747" xml:lang="eng" locale="eng" status="publish" xmlns:its="http://www.w3.org/2005/11/its">
  <search-meta>
      <uri-title its:translate="no">atlanta-temple-lds-811747</uri-title>
      <source>atlanta-temple-lds-811747</source>
      <publication-type its:translate="no">image</publication-type>
      <media-type its:translate="no">image</media-type>
      <publication value="ldsorg">LDS.org</publication>
      <publication-date value="2012-12-14">2012-12-14</publication-date>
      <title/>
      <description/>
      <collections>
          <collection its:translate="no">global-search</collection>
          <collection its:translate="no">media</collection>
          <collection its:translate="no">images</collection>
      </collections>
      <subjects>
          <subject>Atlanta Georgia Temple</subject>
          <subject>Reier</subject>
          <subject>Matthew</subject>
          <subject>Temples</subject>
          <subject>Night</subject>
      </subjects>
  </search-meta>
  <no-search>
      <path>http://media.ldscdn.org/images/media-library/temples/atlanta-georgia/atlanta-temple-lds-811747-gallery.jpg</path>
      <images>
          http://media.ldscdn.org/images/media-library/temples/atlanta-georgia/atlanta-temple-lds-811747-thumbnail.jpg
      </images>
          <download-urls>
              <download-url>
                  Mobile
                  <size>50 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/temples/atlanta-georgia/atlanta-temple-lds-811747-mobile.jpg</path>
              </download-url>
              <download-url>
                  Tablet
                  <size>68 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/temples/atlanta-georgia/atlanta-temple-lds-811747-tablet.jpg</path>
              </download-url>
              <download-url>
                  Print
                  <size>151 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/temples/atlanta-georgia/atlanta-temple-lds-811747-print.jpg</path>
              </download-url>
              <download-url>
                  Wallpaper
                  <size>261 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/temples/atlanta-georgia/atlanta-temple-lds-811747-wallpaper.jpg</path>
              </download-url>
          </download-urls>
  </no-search>
</ldswebml>


text:
package org.critterai.nmgen;

import java.util.ArrayList;

/**
 * Represents the detailed and simplified versions of a contour.
 * A contour is expected to always represent a simple polygon.
 * (Convex or concave.)
 *

 *
 *
 *

 * @see ContourSetBuilder
 */
public final class Contour
{
    /*
     * Recast Reference: rcContour in Recast.h
     */

    /**
     * The region associated with the contour.
     */
    public final int regionID;

    /**
     * The vertices which represent the raw (or detailed) contour.
     *
Vertices are clockwise wrapped in the form (x, y, z, regionID),
     * where regionID is the external region the vertex is considered to be
     * connected to.

     */
    public final int[] rawVerts;

    /**
     * The raw vertex count.  (A convenience value.)
     */
    public final int rawVertCount;

    /**
     * The vertices which represent the simplified contour.
     *
Vertices are clockwise wrapped in the form (x, y, z, regionID),
     * where regionID is the external region the vertex is considered to be
     * connected to.

     */
    public final int[] verts;

    /**
     * The detail vertex count.  (A convenience value.)
     */
    public final int vertCount;

    /**
     * Constructor
     *
All vertex lists are expected to be clockwise wrapped in
     * the form (x, y, z, regionID), where regionID is the external
     * region the vertex is considered to be connected to.

     * @param regionID The region associated with the contour.
     * @param rawList The vertices which represent the raw (or detailed)
     * contour.
     * @param vertList The vertices which represent the detailed contour.
     * @throws IllegalArgumentException  If either vertex list is null.
     * The size of the vertex lists is not checked.
     */
    public Contour(int regionID
                    , ArrayList<Integer> rawList
                    , ArrayList<Integer> vertList)
        throws IllegalArgumentException
    {
        if (rawList == null || vertList == null)
            throw new IllegalArgumentException(
                            "One or both vertex lists are null.");

        this.regionID = regionID;

        rawVerts = new int[rawList.size()];
        for (int i = 0; i < rawVerts.length; i++)
            rawVerts[i] = rawList.get(i);

        rawVertCount = rawVerts.length / 4;

        verts = new int[vertList.size()];
        for (int i = 0; i < verts.length; i++)
            verts[i] = vertList.get(i);

        vertCount = verts.length / 4;
    }

}


text:
codejam2013
===========
Power Response through Machine Learning: Guessing the future Power Usage


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

    // Declare root variable

    var root = window,
        module = {};

    module.collection = (function ()
    {
        var exports = {},
            methods = [
                'all', 'any', 'at', 'collect', 'contains', 'countBy', 'detect',
                'each', 'eachRight', 'every', 'filter', 'find', 'findlast',
                'findWhere', 'foldl', 'foldr', 'forEach', 'forEachRight',
                'groupBy', 'include', 'includes', 'indexBy', 'inject', 'invoke',
                'map', 'partition', 'pluck', 'reduce', 'reduceRight', 'reject',
                'sample', 'select', 'shuffle', 'size', 'some', 'sortBy',
                'sortByAll', 'sortByOrder', 'where'
            ];

        // Inherit Lodash Methods

        for (var i = 0; i < methods.length; i++) {
            exports[methods[i]] = root._[methods[i]];
        }

        return exports;

    })();

    // Export module to root Longdash object

    root.__ = root._.extend((root.__ || {}), module);

    // Shortcut

    root.__.col = root.__.collection;

}).call(this);


text:
#ifndef _CSHARP_PROTOCOL_WRITER_H_
#define _CSHARP_PROTOCOL_WRITER_H_

#include "ProtocolHelper/ProtocolParse/MsgTypeDef.h"
#include <fstream>
#include <vector>

class CCSharpProtocolWriter
{
public:
    // Write client msg to CShape file
    static void WriteCSProtocolFile(const std::vector<IMsgType*>& vClientMsgList, const char* pszFilePath);

private:
    // Write the base msg class in cs file.
    static void WriteBaseMessage(std::ofstream& ofs);

    // Write message factory for all client msg
    static void WriteMessageFactory(std::ofstream& ofs, const std::vector<IMsgType*>& vClientMsgList);

    // Write enum struct to cs file.
    static bool WriteEnum( std::ofstream& ofs, const CMsgTypeEnum* pEnum );

    // Write struct to cs file
    static bool WriteStruct( std::ofstream& ofs, const CMsgTypeStruct* pStruct );

    // Write ToBytes function for a struct
    static void WriteToBytesFun( std::ofstream& ofs, const CMsgTypeStruct* pStruct );

    // Write FromBytes function for a struct
    static void WriteFromBytesFun( std::ofstream& ofs, const CMsgTypeStruct* pStruct );

    // Get the read function name for a type
    static std::string GetReadFunction(const std::string& strTypeName);

    // Write constructor function for a struct
    static void WriteConstructor( std::ofstream& ofs, const CMsgTypeStruct* pStruct );
};

#endif // _CSHARP_PROTOCOL_WRITER_H_


text:
'''
Created on Mar 1, 2016

@author: PJ
'''
from BaseScouting.api_scraper.fake_data_scripts.TempRetrofilSrFromOfficialResults import TempRetrofillSrFromOfficialResults
from BaseScouting.load_django import load_django

class TempRetrofillSrFromOfficialResults2017(TempRetrofillSrFromOfficialResults):

    gear_lookup = {0: 0,
                   1: 1,
                   2: 3,
                   3: 7,
                   4: 13,
                   }

    def __get_common_fields(self, official_match_sr, round_up=False):
        output = {}

#         auto_rotor_count = official_match_sr.rotor1Auto + official_match_sr.rotor2Auto
#         tele_rotor_count = official_match_sr.rotor1Engaged + official_match_sr.rotor2Engaged + official_match_sr.rotor3Engaged + official_match_sr.rotor4Engaged

#         auto_gears = self.gear_lookup[auto_rotor_count]
#         tele_gears = self.gear_lookup[tele_rotor_count]

        auto_gears = 0
        if official_match_sr.rotor2Auto:
            auto_gears = 3
        elif official_match_sr.rotor1Auto:
            auto_gears = 1

        tele_gears = 0
        if official_match_sr.rotor4Engaged:
            tele_gears = 13
        elif official_match_sr.rotor3Engaged:
            tele_gears = 7
        elif official_match_sr.rotor2Engaged:
            tele_gears = 3
        elif official_match_sr.rotor1Engaged:
            tele_gears = 1

        output['auto_fuel_high_score'] = int(official_match_sr.autoFuelHigh / 3.0)
        output['auto_fuel_low_score'] = int(official_match_sr.autoFuelLow / 3.0)
        output['auto_gears'] = int(auto_gears / 3.0)

        output['tele_fuel_high_score'] = int(official_match_sr.teleopFuelHigh / 3.0)
        output['tele_fuel_low_score'] = int(official_match_sr.teleopFuelLow / 3.0)
        output['tele_gears'] = int(tele_gears / 3.0)

        if round_up:
            output['auto_fuel_high_score'] += int(official_match_sr.autoFuelHigh % 3.0)
            output['auto_fuel_low_score'] += int(official_match_sr.autoFuelLow % 3.0)
            output['auto_gears'] += int(auto_gears % 3.0)

            output['tele_fuel_high_score'] += int(official_match_sr.teleopFuelHigh % 3.0)
            output['tele_fuel_low_score'] += int(official_match_sr.teleopFuelLow % 3.0)
            output['tele_gears'] += int(tele_gears % 3.0)

        output['auto_fuel_high_shots'] = output['auto_fuel_high_score']
        output['auto_fuel_low_shots'] = output['auto_fuel_low_score']
        output['tele_fuel_high_shots'] = output['tele_fuel_high_score']
        output['tele_fuel_low_shots'] = output['tele_fuel_low_score']

        return output

    def get_team1_stats(self, official_match_sr):
        output = self.__get_common_fields(official_match_sr)

        output['auto_baseline']  = official_match_sr.robot1Auto == "Mobility"
        output['rope']      = official_match_sr.touchpadFar == 1
        output['foul']      = official_match_sr.foulCount >= 1
        output['tech_foul'] = official_match_sr.techFoulCount >= 1

        return output

    def get_team2_stats(self, official_match_sr):
        output = self.__get_common_fields(official_match_sr)

        output['auto_baseline']  = official_match_sr.robot2Auto == "Mobility"
        output['rope']      = official_match_sr.touchpadMiddle == 1
        output['foul']      = official_match_sr.foulCount >= 2
        output['tech_foul'] = official_match_sr.techFoulCount >= 2

        return output

    def get_team3_stats(self, official_match_sr):
        output = self.__get_common_fields(official_match_sr, round_up=True)

        output['auto_baseline']  = official_match_sr.robot3Auto == "Mobility"
        output['rope']      = official_match_sr.touchpadNear == 1
        output['foul']      = official_match_sr.foulCount >= 3
        output['tech_foul'] = official_match_sr.techFoulCount >= 3

        return output

def retrofill_results(min_match_number, max_match_number):
    from Scouting2017.model.reusable_models import OfficialMatch, Match
    from Scouting2017.model.models2017 import OfficialMatchScoreResult, ScoreResult

    populater = TempRetrofillSrFromOfficialResults2017()

    for match_number in range(min_match_number, max_match_number):
        official_matches = OfficialMatch.objects.filter(matchNumber=match_number)
        if len(official_matches) != 1:
            continue

        official_match = official_matches[0]
        official_srs = OfficialMatchScoreResult.objects.filter(official_match=official_match)
        match, _ = Match.objects.get_or_create(matchNumber=official_match.matchNumber)

        populater.populate_matchresults(official_match, Match, ScoreResult, OfficialMatchScoreResult)

if __name__ == "__main__":
    load_django()
    retrofill_results(1, 40)
#     retrofill_results(7, 8)


text:
package org.bgp4j.net;

import org.apache.commons.lang3.StringUtils;

/**
 * @author Rainer Bieniek (Rainer.Bieniek@web.de)
 *
 */
public enum ORFType {
	ADDRESS_PREFIX_BASED;

	/** Address prefix based outbound route filter type (RFC 5292) */
	private static final int BGP_OUTBOUND_ROUTE_FILTER_TYPE_ADDRESS_PREFIX_BASED = 64;

	public int toCode() {
		switch(this) {
		case ADDRESS_PREFIX_BASED:
			return BGP_OUTBOUND_ROUTE_FILTER_TYPE_ADDRESS_PREFIX_BASED;
		default:
			throw new IllegalArgumentException("cannot encode OutboudRouteFilter type " + this);
		}
	}

	public static ORFType fromCode(int code) {
		switch(code) {
		case BGP_OUTBOUND_ROUTE_FILTER_TYPE_ADDRESS_PREFIX_BASED:
			return ADDRESS_PREFIX_BASED;
		default:
			throw new IllegalArgumentException("cannot encode OutboudRouteFilter type code " + code);
		}
	}

	public static ORFType fromString(String value) {
		if(StringUtils.equalsIgnoreCase("addressPrefixBased", value)) {
			return ADDRESS_PREFIX_BASED;
		} else
			throw new IllegalArgumentException("cannot encode OutboudRouteFilter type: " + value);
	}
}


text:
namespace chromeos {

namespace secure_channel {

// Connection implementation which creates a connection to a remote device via
// mojom::NearbyConnector. Implements mojom::NearbyMessageReceiver to receive
// messages from the NearbyConnector and uses a
// mojo::Remote<mojom::NearbyMessageSender> to send messages to the
// NearbyConnector.
//
// When requested to send a message, this class queues messages and only sends
// one message after the previous one has been sent successfully. If sending a
// message fails, this is considered a fatal error, and the connection is
// disconnected.
//
// Also implements mojom::FilePayloadListener to listen to transfer
// updates for file payloads registered via RegisterPayloadFile.
class NearbyConnection : public Connection,
                         public mojom::NearbyMessageReceiver,
                         public mojom::FilePayloadListener {
 public:
  class Factory {
   public:
    static std::unique_ptr<Connection> Create(
        multidevice::RemoteDeviceRef remote_device,
        const std::vector<uint8_t>& eid,
        mojom::NearbyConnector* nearby_connector);
    static void SetFactoryForTesting(Factory* factory);
    virtual ~Factory() = default;

   protected:
    virtual std::unique_ptr<Connection> CreateInstance(
        multidevice::RemoteDeviceRef remote_device,
        const std::vector<uint8_t>& eid,
        mojom::NearbyConnector* nearby_connector) = 0;

   private:
    static Factory* factory_instance_;
  };

  ~NearbyConnection() override;

 private:
  NearbyConnection(multidevice::RemoteDeviceRef remote_device,
                   const std::vector<uint8_t>& eid,
                   mojom::NearbyConnector* nearby_connector);

  // Connection:
  void Connect() override;
  void Disconnect() override;
  std::string GetDeviceAddress() override;
  void SendMessageImpl(std::unique_ptr<WireMessage> message) override;
  void RegisterPayloadFileImpl(
      int64_t payload_id,
      mojom::PayloadFilesPtr payload_files,
      FileTransferUpdateCallback file_transfer_update_callback,
      base::OnceCallback<void(bool)> registration_result_callback) override;

  // mojom::NearbyMessageReceiver:
  void OnMessageReceived(const std::string& message) override;

  // mojom::FilePayloadListener:
  void OnFileTransferUpdate(mojom::FileTransferUpdatePtr update) override;

  // Returns the the remote device's address as a byte array; note that
  // GetDeviceAddress() returns a colon-separated hex string.
  std::vector<uint8_t> GetRemoteDeviceBluetoothAddressAsVector();

  void OnConnectResult(
      mojo::PendingRemote<mojom::NearbyMessageSender> message_sender,
      mojo::PendingRemote<mojom::NearbyFilePayloadHandler>
          file_payload_handler);
  void OnSendMessageResult(bool success);
  void ProcessQueuedMessagesToSend();
  // Called when Disconnect() is called by the client. Can also be called when
  // the remote endpoint drops the connection and the other remotes, e.g.
  // MessageSender, triggers Disconnect() before the |disconnect_handler|s of
  // the NearbyPayloadListeners are called.
  void CleanUpPendingFileTransfersOnDisconnect();
  // Called when a FilePayloadListener remote endpoint is disconnected.
  void OnFilePayloadListenerRemoteDisconnected();

  mojom::NearbyConnector* nearby_connector_;
  mojo::Receiver<mojom::NearbyMessageReceiver> message_receiver_{this};
  mojo::Remote<mojom::NearbyMessageSender> message_sender_;
  mojo::Remote<mojom::NearbyFilePayloadHandler> file_payload_handler_;
  // Set of receivers created to listen to file payload transfer updates, one
  // for each payload registered via RegisterPayloadFile(). These receivers will
  // be automatically removed from the set when their corresponding Remote
  // endpoints are destroyed upon transfer completion. current_context() will
  // return the corresponding payload ID when a receiver is called or
  // disconnected.
  mojo::ReceiverSet<mojom::FilePayloadListener, int64_t>
      file_payload_listener_receivers_;

  std::vector<uint8_t> eid_;

  base::queue<std::unique_ptr<WireMessage>> queued_messages_to_send_;

  // Null if no message is being sent.
  std::unique_ptr<WireMessage> message_being_sent_;

  // Callbacks to receive FileTransferUpdates for registered file payloads.
  // Keyed by payload ID. A callback will be emitted from this map when the
  // corresponding mojo::Remote<mojom::FilePayloadListener> is disconnected.
  base::flat_map<int64_t, FileTransferUpdateCallback>
      file_transfer_update_callbacks_;

  base::WeakPtrFactory<NearbyConnection> weak_ptr_factory_{this};
};

}  // namespace secure_channel

}  // namespace chromeos

#endif  // CHROMEOS_SERVICES_SECURE_CHANNEL_NEARBY_CONNECTION_H_