text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

    <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <link rel="stylesheet" href="style.css">

            <fieldset>
                <legend>New Transaction </legend>
                <form id="newTxnForm" name="burn.newTransactionForm" ng-submit="burn.addTransaction(burn.newTransactionForm)">

                        Description
                        <input ng-model="burn.description" class="form-control" type="test" name="description">

                        Amount
                        <input ng-model="burn.amount" class="form-control" type="test" name="amount">

                        Start Date
                        <input ng-model="burn.startDate" class="form-control" type="date" name="start-date">

                        End Date
                        <input ng-model="burn.endDate" class="form-control" type="date" name="end-date">

                        Frequency
                        <select ng-model="burn.frequency" class="form-control" name="frequency">
                            <option value="day">Daily</option>
                            <option value="week">Weekly</option>
                            <option value="biweek">Bi-weekly</option>
                            <option value="month">Monthly</option>
                        </select>

                    <input class="btn btn-primary" type="submit" value="Add Transaction">
                </form>
            </fieldset>

            <fieldset>
                <legend>Current Transactions:
                <input class="form-inline form-control" type="text"
                ng-model="burn.collection.name" ng-change="burn.saveActive=true;">
                </legend>

                        Description
                        Amount
                        Start Date
                        End Date
                        Frequency

                        <input class="form-control" ng-model="txn.description">
                        <input class="form-control" ng-model="txn.amount"
                            ng-model-options="{updateOn: 'blur'}"
                            ng-change="burn.updateEverything()">
                        <input class="form-control" type="date"
                            ng-model-options="{updateOn: 'blur'}"
                            ng-change="burn.updateEverything()" ng-model="txn.startDate">
                        <input class="form-control"
                            ng-model-options="{updateOn: 'blur'}"
                            ng-if="txn.frequency!=='none'" type="date"
                        ng-change="burn.updateEverything()" ng-model="txn.endDate">

                            <select ng-model="txn.frequency"
                                class="form-control" name="frequency"
                                ng-change="burn.updateEverything()">
                                <option value="none">None</option>
                                <option value="day">Daily</option>
                                <option value="week">Weekly</option>
                                <option value="biweek">Bi-weekly</option>
                                <option value="month">Monthly</option>
                            </select>

                        <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="false">Load</button>

                                {{t.name}}

                    <button ng-disabled="!burn.saveActive" class="btn btn-success" ng-click="burn.saveTransactions()">Save</button>
                    <button class="btn btn-danger" ng-click="burn.newCollection()">New</button>
                    <button class="btn btn-danger pull-right" ng-click="burn.deleteCollection()">Delete</button>

            </fieldset>

            <fieldset>
                <legend>Results</legend>

                    Target Date
                    <input class="form-control"
                        type="date"
                        ng-model="burn.targetDate"
                        ng-change="burn.updateValue()"
                        name="target-date">

                        {{burn.valueOnDate | currency}}

                        Lowest: {{ burn.minValue | currency}}

                        Final: {{ burn.endValue | currency}}

            </fieldset>


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Layout to add a room to the favorites rooms. -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/PocketCampusRow"
    android:gravity="left"
    android:orientation="horizontal" >

    <!-- TextView to hold the name of the room -->

    <TextView
        android:id="@+id/freeroom_layout_list_room_add_room"
        style="@style/PocketCampusListItemTitle"
        android:layout_gravity="left|center_vertical"
        android:drawableLeft="@drawable/freeroom_ic_action_new"
        android:text="mock room name" />

</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
FOUNDATION_EXPORT double Pods_HurryPorter_TestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_HurryPorter_TestsVersionString[];


text:
namespace net {

class ProxyInfo;
struct SSLConfig;

class Preconnect:  public base::RefCountedThreadSafe<Preconnect> {
 public:
  // Try to preconnect.  Typically used by predictor when a subresource probably
  // needs a connection. |count| may be used to request more than one connection
  // be established in parallel.
  static void DoPreconnect(HttpNetworkSession* session, const GURL& url,
      int count = 1, HttpRequestInfo::RequestMotivation motivation =
          HttpRequestInfo::PRECONNECT_MOTIVATED);

 private:
  friend class base::RefCountedThreadSafe<Preconnect>;

  ~Preconnect();

  explicit Preconnect(HttpNetworkSession* session);

  void OnPreconnectComplete(int error_code);

  // Request actual connection, via interface that tags request as needed for
  // preconnect only (so that they can be merged with connections needed for
  // navigations).
  void Connect(const GURL& url, int count,
      HttpRequestInfo::RequestMotivation motivation);

  HttpNetworkSession * session_;
  // HttpRequestInfo used for connecting.
  scoped_ptr<HttpRequestInfo> request_info_;

  // SSLConfig used for connecting.
  scoped_ptr<SSLConfig> ssl_config_;

  // ProxyInfo used for connecting.
  scoped_ptr<ProxyInfo> proxy_info_;

  // A net log to use for this preconnect.
  BoundNetLog net_log_;

  // Our preconnect.
  scoped_ptr<HttpStreamRequest> stream_request_;

  base::Callback<void(int)> io_callback_;

  DISALLOW_COPY_AND_ASSIGN(Preconnect);
};
}  // namespace net
#endif // NET_HTTP_HTTP_REQUEST_INFO_H__


text:
wordpress_id: 443
title: "Tom's Hardware Guide Mobile Devices:"
wordpress_url: http://spaetzel.com/PermaLink,guid,242.aspx
layout: post
---
Tom's Hardware Guide
        Mobile Devices: Getting Organized with PDAs

        Tom's Hardware has an excellent roundup of all the hot PDAs of the day, give it a
        look if you are thinking about getting yourself one soon.


text:
<?php
	_deprecated_file( __FILE__, '3.10', 'Tribe__Events__Pro__Custom_Meta' );

	class TribeEventsCustomMeta extends Tribe__Events__Pro__Custom_Meta {

	}


text:
<?php

namespace UltraMVC\Responses\Abstracts;

use UltraMVC\Views\Loader;

/**
 * Class ResponsesAbstract
 * @package UltraMVC\Responses\Abstracts
 */
abstract class ResponsesAbstract extends \Exception {

	/**
	 * @var int
	 */
	protected $response_code = 0;

	/**
	 * @var bool
	 */
	protected $internal_error = false;

	/**
	 * @var null|string
	 */
	protected $error_message = null;

	/**
	 * @var array
	 */
	protected $list_of_response_codes = array();

	/**
	 * @var bool|callable
	 */
	protected $callable = false;

	/**
	 * @var array
	 */
	private $allowed = array();

	/**
	 * Construct the http response exception
	 *
	 * @param int $response_code
	 * @param string|callable $message_or_callback
	 * @param int $code
	 * @param \Exception $previous
	 */
	public function __construct($response_code = 0, $message_or_callback, $code = 0, \Exception $previous = null)
	{

		$this->response_code = $response_code;

		// allowed response numbers
		$this->list_of_response_codes = array(
			'100' => 'Continue',
			'101' => 'Switching Protocols',
			'102' => 'Processing',
			'103' => 'checkpoint',
			'200' => 'OK',
			'201' => 'Created',
			'202' => 'Accepted',
			'203' => 'Non-Authoritative Information',
			'204' => 'No Content',
			'205' => 'Reset Content',
			'206' => 'Partial Content',
			'207' => 'Multi-Status',
			'208' => 'Already Reported',
			'226' => 'IM Used',
			'300' => 'Multiple Choices',
			'301' => 'Moved Permanently',
			'302' => 'Found',
			'303' => 'See Other',
			'304' => 'Not Modified',
			'305' => 'Use Proxy',
			'306' => 'Switch Proxy',
			'307' => 'Temporary Redirect',
			'308' => 'Permanent Redirect',
			//'404' => 'error on German Wikipedia',
			'400' => 'Bad Request',
			'401' => 'Unauthorized',
			'402' => 'Payment Required',
			'403' => 'Forbidden',
			'404' => 'Not Found',
			'405' => 'Method Not Allowed',
			'406' => 'Not Acceptable',
			'407' => 'Proxy Authentication Required',
			'408' => 'Request Timeout',
			'409' => 'Conflict',
			'410' => 'Gone',
			'411' => 'Length Required',
			'412' => 'Precondition Failed',
			'413' => 'Payload Too Large',
			'414' => 'URI Too Long',
			'415' => 'Unsupported Media Type',
			'416' => 'Range Not Satisfiable',
			'417' => 'Expectation Failed',
			'418' => 'I\'m a teapot',
			'419' => 'Authentication Timeout',
			'421' => 'Misdirected Request',
			'422' => 'Unprocessable Entity',
			'423' => 'Locked',
			'424' => 'Failed Dependency',
			'426' => 'Upgrade Required',
			'428' => 'Precondition Required',
			'429' => 'Too Many Requests',
			'431' => 'Request Header Fields Too Large',
			'451' => 'Unavailable For Legal Reasons',
			'500' => 'Internal Server Error',
			'501' => 'Not Implemented',
			'502' => 'Bad Gateway',
			'503' => 'Service Unavailable',
			'504' => 'Gateway Timeout',
			'505' => 'HTTP Version Not Supported',
			'506' => 'Variant Also Negotiates',
			'507' => 'Insufficient Storage',
			'508' => 'Loop Detected',
			'510' => 'Not Extended',
			'511' => 'Network Authentication Required',
			'420' => 'Method Failure',
			//'420' => 'Enhance Your Calm',
			'450' => 'Blocked by Windows Parental Controls',
			'498' => 'Invalid Token',
			'499' => 'Token Required',
			'509' => 'Bandwidth Limit Exceeded',
			'440' => 'Login Timeout',
			'449' => 'Retry With',
			//'451' => 'Redirect',
			'444' => 'No Response',
			'495' => 'SSL Certificate Error',
			'496' => 'SSL Certificate Required',
			'497' => 'HTTP Request Sent to HTTPS Port',
			//'499' => 'Client Closed Request',
			'520' => 'Unknown Error',
			'521' => 'Web Server Is Down',
			'522' => 'Connection Timed Out',
			'523' => 'Origin Is Unreachable',
			'524' => 'A Timeout Occurred',
			'525' => 'SSL Handshake Failed',
			'526' => 'Invalid SSL Certificate',
		);

		$found = in_array($this->response_code, array_keys($this->list_of_response_codes));

		if (!$found) {
			$this->internal_error = true;
			$this->error_message = 'Response Code ' . $response_code . ' is not a valid http response code';
		} else {
			if (is_callable($message_or_callback)) {
				$this->callable = $message_or_callback;
				$message = 'Error: ' . $this->response_code . ' ' . $this->list_of_response_codes[$this->response_code];
			} else {
				$message = $message_or_callback;
			}
			parent::__construct($message, $response_code, $previous);
			$this->response_code = $response_code;
			if ($this->response_code == 0) {
				$this->internal_error = true;
				$this->error_message = 'Response Code set 0: Not a valid http response code';
			}
		}

	}

	/**
	 * @param array $params
	 * @throws ResponseAbstractException
	 */
	public function redirect($params = array())
	{
		if (isSet($params['force_code']) && in_array($params['force_code'], $this->allowed)) {
			$code = $params['force_code'];
		} else {
			$code = $this->response_code;
		}
		if (is_array($params) && empty($params)) {
			throw new ResponseAbstractException('Redirect parameter not set. String or array must be given');
		} else {
			if (is_array($params) && !isSet($params['redirect_url'])) {
				throw new ResponseAbstractException('Redirect url parameter not set. String must be given');
			} elseif (is_array($params)) {
				$redirect = $params['redirect_url'];
			} elseif (is_string($params)) {
				$redirect = $params;
			} else {
				throw new ResponseAbstractException('Invalid type set for redirect url paramter. String must be given');
			}
		}
		header('Location: ' . $redirect, true, $code);
		die;

	}

	/**
	 * @param bool $html
	 * @throws \UltraMVC\Views\LoaderException
	 */
	public function loadView($html = true)
	{
		$response_code_message = $this->list_of_response_codes[$this->response_code];
		header('HTTP/1.1 '.$this->response_code. ' '.$response_code_message);
		$Loader = new Loader();
		if (is_callable($this->callable)) {
			call_user_func($this->{'callable'});
		} elseif ($Loader->viewExists('responses/'.$this->response_code)) {
			$Loader->view('responses/' . $this->response_code);
		} else {
			if ($html) {
			print '
				<!DOCTYPE html>
					<html>
						<head>
							<title>'.$this->response_code.' ' . $response_code_message . '</title>
						</head>
						<body>
							There was an error processing your request.  Response code: '.$this->response_code.' ' .
							$response_code_message . '
						</body>
					</html>'
				;
			}
		}
	}

	/**
	 * @return bool
	 */
	public function hasError()
	{
		return $this->internal_error;
	}

	/**
	 * @return null|string
	 */
	public function getErrorMessage()
	{
		return $this->error_message;
	}
}

class ResponseAbstractException extends \Exception {}


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

using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics.X86;

using Internal.Runtime.CompilerServices;

// Some routines inspired by the Stanford Bit Twiddling Hacks by Sean Eron Anderson:
// http://graphics.stanford.edu/~seander/bithacks.html

namespace System.Numerics
{
    /// <summary>
    /// Utility methods for intrinsic bit-twiddling operations.
    /// The methods use hardware intrinsics when available on the underlying platform,
    /// otherwise they use optimized software fallbacks.
    /// </summary>
    public static class BitOperations
    {
        // C# no-alloc optimization that directly wraps the data section of the dll (similar to string constants)
        // https://github.com/dotnet/roslyn/pull/24621

        private static ReadOnlySpan<byte> TrailingZeroCountDeBruijn => new byte[32]
        {
            00, 01, 28, 02, 29, 14, 24, 03,
            30, 22, 20, 15, 25, 17, 04, 08,
            31, 27, 13, 23, 21, 19, 16, 07,
            26, 12, 18, 06, 11, 05, 10, 09
        };

        private static ReadOnlySpan<byte> Log2DeBruijn => new byte[32]
        {
            00, 09, 01, 10, 13, 21, 02, 29,
            11, 14, 16, 18, 22, 25, 03, 30,
            08, 12, 20, 28, 15, 17, 24, 07,
            19, 27, 23, 06, 26, 05, 04, 31
        };

        /// <summary>
        /// Count the number of leading zero bits in a mask.
        /// Similar in behavior to the x86 instruction LZCNT.
        /// </summary>
        /// <param name="value">The value.</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        [CLSCompliant(false)]
        public static int LeadingZeroCount(uint value)
        {
            if (Lzcnt.IsSupported)
            {
                // LZCNT contract is 0->32
                return (int)Lzcnt.LeadingZeroCount(value);
            }

            // Unguarded fallback contract is 0->31
            if (value == 0)
            {
                return 32;
            }

            return 31 - Log2SoftwareFallback(value);
        }

        /// <summary>
        /// Count the number of leading zero bits in a mask.
        /// Similar in behavior to the x86 instruction LZCNT.
        /// </summary>
        /// <param name="value">The value.</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        [CLSCompliant(false)]
        public static int LeadingZeroCount(ulong value)
        {
            if (Lzcnt.X64.IsSupported)
            {
                // LZCNT contract is 0->64
                return (int)Lzcnt.X64.LeadingZeroCount(value);
            }

            uint hi = (uint)(value >> 32);

            if (hi == 0)
            {
                return 32 + LeadingZeroCount((uint)value);
            }

            return LeadingZeroCount(hi);
        }

        /// <summary>
        /// Returns the integer (floor) log of the specified value, base 2.
        /// Note that by convention, input value 0 returns 0 since Log(0) is undefined.
        /// </summary>
        /// <param name="value">The value.</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        [CLSCompliant(false)]
        public static int Log2(uint value)
        {
            // value    lzcnt   actual  expected
            // ..0000   32      0        0 (by convention, guard clause)
            // ..0001   31      31-31    0
            // ..0010   30      31-30    1
            // 0010..    2      31-2    29
            // 0100..    1      31-1    30
            // 1000..    0      31-0    31
            if (Lzcnt.IsSupported)
            {
                // Enforce conventional contract 0->0 (Log(0) is undefined)
                if (value == 0)
                {
                    return 0;
                }

                // LZCNT contract is 0->32
                return 31 - (int)Lzcnt.LeadingZeroCount(value);
            }

            // Fallback contract is 0->0
            return Log2SoftwareFallback(value);
        }

        /// <summary>
        /// Returns the integer (floor) log of the specified value, base 2.
        /// Note that by convention, input value 0 returns 0 since Log(0) is undefined.
        /// </summary>
        /// <param name="value">The value.</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        [CLSCompliant(false)]
        public static int Log2(ulong value)
        {
            if (Lzcnt.X64.IsSupported)
            {
                // Enforce conventional contract 0->0 (Log(0) is undefined)
                if (value == 0)
                {
                    return 0;
                }

                // LZCNT contract is 0->64
                return 63 - (int)Lzcnt.X64.LeadingZeroCount(value);
            }

            uint hi = (uint)(value >> 32);

            if (hi == 0)
            {
                return Log2((uint)value);
            }

            return 32 + Log2(hi);
        }

        /// <summary>
        /// Returns the integer (floor) log of the specified value, base 2.
        /// Note that by convention, input value 0 returns 0 since Log(0) is undefined.
        /// Does not directly use any hardware intrinsics, nor does it incur branching.
        /// </summary>
        /// <param name="value">The value.</param>
        private static int Log2SoftwareFallback(uint value)
        {
            // No AggressiveInlining due to large method size
            // Has conventional contract 0->0 (Log(0) is undefined)

            // Fill trailing zeros with ones, eg 00010010 becomes 00011111
            value |= value >> 01;
            value |= value >> 02;
            value |= value >> 04;
            value |= value >> 08;
            value |= value >> 16;

            // uint.MaxValue >> 27 is always in range [0 - 31] so we use Unsafe.AddByteOffset to avoid bounds check
            return Unsafe.AddByteOffset(
                // Using deBruijn sequence, k=2, n=5 (2^5=32) : 0b_0000_0111_1100_0100_1010_1100_1101_1101u
                ref MemoryMarshal.GetReference(Log2DeBruijn),
                // uint|long -> IntPtr cast on 32-bit platforms does expensive overflow checks not needed here
                (IntPtr)(int)((value * 0x07C4ACDDu) >> 27));
        }

        /// <summary>
        /// Returns the population count (number of bits set) of a mask.
        /// Similar in behavior to the x86 instruction POPCNT.
        /// </summary>
        /// <param name="value">The value.</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        [CLSCompliant(false)]
        public static int PopCount(uint value)
        {
            if (Popcnt.IsSupported)
            {
                return (int)Popcnt.PopCount(value);
            }

            return SoftwareFallback(value);

            static int SoftwareFallback(uint value)
            {
                const uint c1 = 0x_55555555u;
                const uint c2 = 0x_33333333u;
                const uint c3 = 0x_0F0F0F0Fu;
                const uint c4 = 0x_01010101u;

                value -= (value >> 1) & c1;
                value = (value & c2) + ((value >> 2) & c2);
                value = (((value + (value >> 4)) & c3) * c4) >> 24;

                return (int)value;
            }
        }

        /// <summary>
        /// Returns the population count (number of bits set) of a mask.
        /// Similar in behavior to the x86 instruction POPCNT.
        /// </summary>
        /// <param name="value">The value.</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        [CLSCompliant(false)]
        public static int PopCount(ulong value)
        {
            if (Popcnt.X64.IsSupported)
            {
                return (int)Popcnt.X64.PopCount(value);
            }

#if BIT32
            return PopCount((uint)value) // lo
                + PopCount((uint)(value >> 32)); // hi
#else
            return SoftwareFallback(value);

            static int SoftwareFallback(ulong value)
            {
                const ulong c1 = 0x_55555555_55555555ul;
                const ulong c2 = 0x_33333333_33333333ul;
                const ulong c3 = 0x_0F0F0F0F_0F0F0F0Ful;
                const ulong c4 = 0x_01010101_01010101ul;

                value -= (value >> 1) & c1;
                value = (value & c2) + ((value >> 2) & c2);
                value = (((value + (value >> 4)) & c3) * c4) >> 56;

                return (int)value;
            }
#endif
        }

        /// <summary>
        /// Count the number of trailing zero bits in an integer value.
        /// Similar in behavior to the x86 instruction TZCNT.
        /// </summary>
        /// <param name="value">The value.</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int TrailingZeroCount(int value)
            => TrailingZeroCount((uint)value);

        /// <summary>
        /// Count the number of trailing zero bits in an integer value.
        /// Similar in behavior to the x86 instruction TZCNT.
        /// </summary>
        /// <param name="value">The value.</param>
        [CLSCompliant(false)]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int TrailingZeroCount(uint value)
        {
            if (Bmi1.IsSupported)
            {
                // TZCNT contract is 0->32
                return (int)Bmi1.TrailingZeroCount(value);
            }

            // Unguarded fallback contract is 0->0
            if (value == 0)
            {
                return 32;
            }

            // uint.MaxValue >> 27 is always in range [0 - 31] so we use Unsafe.AddByteOffset to avoid bounds check
            return Unsafe.AddByteOffset(
                // Using deBruijn sequence, k=2, n=5 (2^5=32) : 0b_0000_0111_0111_1100_1011_0101_0011_0001u
                ref MemoryMarshal.GetReference(TrailingZeroCountDeBruijn),
                // uint|long -> IntPtr cast on 32-bit platforms does expensive overflow checks not needed here
                (IntPtr)(int)(((value & (uint)-(int)value) * 0x077CB531u) >> 27)); // Multi-cast mitigates redundant conv.u8
        }

        /// <summary>
        /// Count the number of trailing zero bits in a mask.
        /// Similar in behavior to the x86 instruction TZCNT.
        /// </summary>
        /// <param name="value">The value.</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int TrailingZeroCount(long value)
            => TrailingZeroCount((ulong)value);

        /// <summary>
        /// Count the number of trailing zero bits in a mask.
        /// Similar in behavior to the x86 instruction TZCNT.
        /// </summary>
        /// <param name="value">The value.</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        [CLSCompliant(false)]
        public static int TrailingZeroCount(ulong value)
        {
            if (Bmi1.X64.IsSupported)
            {
                // TZCNT contract is 0->64
                return (int)Bmi1.X64.TrailingZeroCount(value);
            }

            uint lo = (uint)value;

            if (lo == 0)
            {
                return 32 + TrailingZeroCount((uint)(value >> 32));
            }

            return TrailingZeroCount(lo);
        }

        /// <summary>
        /// Rotates the specified value left by the specified number of bits.
        /// Similar in behavior to the x86 instruction ROL.
        /// </summary>
        /// <param name="value">The value to rotate.</param>
        /// <param name="offset">The number of bits to rotate by.
        /// Any value outside the range [0..31] is treated as congruent mod 32.</param>
        /// <returns>The rotated value.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        [CLSCompliant(false)]
        public static uint RotateLeft(uint value, int offset)
            => (value << offset) | (value >> (32 - offset));

        /// <summary>
        /// Rotates the specified value left by the specified number of bits.
        /// Similar in behavior to the x86 instruction ROL.
        /// </summary>
        /// <param name="value">The value to rotate.</param>
        /// <param name="offset">The number of bits to rotate by.
        /// Any value outside the range [0..63] is treated as congruent mod 64.</param>
        /// <returns>The rotated value.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        [CLSCompliant(false)]
        public static ulong RotateLeft(ulong value, int offset)
            => (value << offset) | (value >> (64 - offset));

        /// <summary>
        /// Rotates the specified value right by the specified number of bits.
        /// Similar in behavior to the x86 instruction ROR.
        /// </summary>
        /// <param name="value">The value to rotate.</param>
        /// <param name="offset">The number of bits to rotate by.
        /// Any value outside the range [0..31] is treated as congruent mod 32.</param>
        /// <returns>The rotated value.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        [CLSCompliant(false)]
        public static uint RotateRight(uint value, int offset)
            => (value >> offset) | (value << (32 - offset));

        /// <summary>
        /// Rotates the specified value right by the specified number of bits.
        /// Similar in behavior to the x86 instruction ROR.
        /// </summary>
        /// <param name="value">The value to rotate.</param>
        /// <param name="offset">The number of bits to rotate by.
        /// Any value outside the range [0..63] is treated as congruent mod 64.</param>
        /// <returns>The rotated value.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        [CLSCompliant(false)]
        public static ulong RotateRight(ulong value, int offset)
            => (value >> offset) | (value << (64 - offset));
    }
}


text:
using System;

namespace Unium.Test
{
    class Program
    {
        static void Main( string[] args )
        {
            Console.WriteLine( "Use the Visual Studio test runner to run the tests ..." );
            Console.WriteLine( "  Test -> Run -> All Tests" );
            Console.ReadKey();
        }
    }
}


text:
// Dependencies
import PropTypes from 'prop-types';

import React from 'react';
import find from 'lodash/collection/find';
import result from 'lodash/object/result';
import { addRefToPropsIfNotPure, INPUT, DISPLAY } from '../../../utils/is-react-class-component';
// Components
import AutocompleteSelectComponent from '../../../components/input/autocomplete-select/field';
import AutocompleteTextComponent from '../../../components/input/autocomplete-text/field';
import InputText from '../../../components/input/text';
import DisplayText from '../../../components/display/text';
import SelectClassic from '../../../components/input/select';
import Label from '../../../components/label';
// Mixins
import fieldGridBehaviourMixin from '../../field-grid-behaviour';

const fieldBuiltInComponentsMixin = {
    mixins: [fieldGridBehaviourMixin],
    getDefaultProps() {
        return {
            /**
            * Does the component has a Label.
            * @type {Boolean}
            */
            hasLabel: true,
            /**
            * Redefine complety the component.
            * @type {Object}
            */
            FieldComponent: undefined,
            /**
            * Redefine only the input and label component.
            * @type {Object}
            */
            InputLabelComponent: undefined,
            /**
            * Component for the input.
            * @type {Object}
            */
            InputComponent: InputText,
            /**
             * Autocomplete component
             * @type {Object}
             */
            AutocompleteSelectComponent,
            AutocompleteTextComponent,
            /**
            * Component for the select.
            * @type {Object}
            */
            SelectComponent: SelectClassic,
            /**
            * Component for the display.
            * @type {Object}
            */
            DisplayComponent: DisplayText,
            /**
            * Component for the label.
            * @type {Object}
            */
            LabelComponent: Label
        };
    },
    /** @inheriteDoc */
    propTypes: {
        AutocompleteComponent: PropTypes.func,
        AutocompleteSelectComponent: PropTypes.func,
        DisplayComponent: PropTypes.func,
        FieldComponent: PropTypes.func,
        InputComponent: PropTypes.func,
        InputLabelComponent: PropTypes.func,
        LabelComponent: PropTypes.func,
        SelectComponent: PropTypes.func,
        hasLabel: PropTypes.bool,
        labelSize: PropTypes.number
    },
    _buildStyle() {
        let { style } = this.props;
        style = style || {};
        style.className = style && style.className ? style.className : '';
        return style;
    },
    /**
    * Render the label part of the component.
    * @returns {Component} - The builded label component.
    */
    label() {
        const { name, label, LabelComponent, domain, isEdit, isRequired } = this.props;
        return (
            <div
                className={`${this._getLabelGridClassName()}`}
                data-focus='field-label-container'
            >
                <LabelComponent
                    domain={domain}
                    name={name}
                    text={label}
                    isEdit={isEdit}
                    isRequired={isRequired}
                />
            </div>
        );
    },
    /**
    * Rendet the input part of the component.
    * @return {Component} - The constructed input component.
    */
    input() {
        const { name: id, placeholder } = this.props;
        const { value, error } = this.state;
        const { onInputChange: onChange } = this;
        const inputBuildedProps = {
            ...this.props,
            id,
            onChange,
            value,
            error,
            placeholder
        };
        const finalInputProps = addRefToPropsIfNotPure(this.props.InputComponent, inputBuildedProps, INPUT)
        return (
            <this.props.InputComponent {...finalInputProps} />
        );
    },
    /**
     * Autocomplete render
     * @return {JSX} rendered component
     */
    autocomplete() {
        const { name: id, placeholder } = this.props;
        const { value, error } = this.state;
        const { onInputChange: onChange } = this;
        const inputBuildedProps = {
            ...this.props,
            id,
            onChange,
            value,
            error,
            placeholder
        };
        const finalInputProps = addRefToPropsIfNotPure(this.props.AutocompleteComponent, inputBuildedProps, INPUT);
        return (
            <this.props.AutocompleteComponent {...finalInputProps} />
        );
    },
    autocompleteSelect() {
        const { name: id, label: placeHolder } = this.props;
        const { value, error } = this.state;
        const { onInputChange: onChange } = this;
        const inputBuildedProps = {
            ...this.props,
            id,
            onChange,
            value,
            error,
            placeHolder
        };
        const finalInputProps = addRefToPropsIfNotPure(this.props.AutocompleteSelectComponent, inputBuildedProps, INPUT)
        return (
            <this.props.AutocompleteSelectComponent {...finalInputProps} />
        );
    },
    autocompleteText() {
        const { name: id, label: placeHolder } = this.props;
        const { value, error } = this.state;
        const { onInputChange: onChange } = this;
        const inputBuildedProps = {
            ...this.props,
            id,
            onChange,
            value,
            error,
            placeHolder
        };
        const finalInputProps = addRefToPropsIfNotPure(this.props.AutocompleteTextComponent, inputBuildedProps, INPUT);
        return (
            <this.props.AutocompleteTextComponent {...finalInputProps} />
        );
    },
    /**
     * Build a select component depending on the domain, definition and props.
     * @return {Component} - The builded select component.
     */
    select() {
        const { error, value } = this.state;
        const buildedSelectProps = {
            ...this.props,
            value,
            style: this._buildStyle(),
            onChange: this.onInputChange,
            error
        };
        const finalSelectProps = addRefToPropsIfNotPure(this.props.SelectComponent, buildedSelectProps, INPUT);
        return (
            <this.props.SelectComponent {...finalSelectProps} />
        );
    },
    /**
    * Render the display part of the component.
    * @return {object} - The display part of the compoennt if the mode is not edit.
    */
    display() {
        const { value } = this.state;
        const { name, valueKey, labelKey, values } = this.props;
        const _processValue = values ? result(find(values, { [valueKey || 'code']: value }), labelKey || 'label') : value;
        const buildedDislplayProps = {
            ...this.props,
            id: name,
            style: this._buildStyle(),
            value: _processValue
        };
        const finalDisplayProps = addRefToPropsIfNotPure(this.props.DisplayComponent, buildedDislplayProps, DISPLAY);
        return (
            <this.props.DisplayComponent {...finalDisplayProps} />
        );
    },
    /**
    * Render the error part of the component.
    * @return {object} - The error part of the component.
    */
    error() {
        let { error } = this.state;
        if (error) {
            return (
                <span className='mdl-textfield__error'>
                    {error}
                </span>
            );
        }
    },
    /**
    * Render the help component.
    * @return {object} - The help part of the component.
    */
    help() {
        let { help, name } = this.props;
        if (help) {
            return (
                <label
                    className='mdl-textfield__label'
                    htmFor={`${name}`}
                >
                    {help}
                </label>
            );
        }
    },
    /**
     * Render the field component if it is overriden in the component definition.
     * @return {Component} - The builded field component.
     */
    _renderFieldComponent() {
        const FieldComponent = this.props.FieldComponent || this.props.InputLabelComponent;
        const { value, error } = this.state;
        const buildedProps = {
            ...this.props,
            id: this.props.name,
            value: value,
            error: error,
            onChange: this.onInputChange
        };
        const finalBuildedProps = addRefToPropsIfNotPure(FieldComponent, buildedProps, INPUT);
        return (
            <FieldComponent {...finalBuildedProps} />
        );
    }
};

export default fieldBuiltInComponentsMixin;


text:
package com.facebook.imagepipeline.animated.base;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.view.animation.LinearInterpolator;

import com.facebook.common.internal.VisibleForTesting;
import com.facebook.common.logging.FLog;
import com.facebook.common.references.CloseableReference;
import com.facebook.common.time.MonotonicClock;
import com.facebook.drawable.base.DrawableWithCaches;

import com.nineoldandroids.animation.ValueAnimator;

/**
 * A {@link Drawable} that renders a animated image. The details of the format are abstracted by the
 * {@link AnimatedDrawableBackend} interface. The drawable can work either as an {@link Animatable}
 * where the client calls start/stop to animate it or it can work as a level-based drawable where
 * the client drives the animation by calling {@link Drawable#setLevel}.
 */
public class AnimatedDrawable extends Drawable implements AnimatableDrawable, DrawableWithCaches {

  private static final Class<?> TAG = AnimatedDrawable.class;

  private static final long WATCH_DOG_TIMER_POLL_INTERVAL_MS = 2000;
  private static final long WATCH_DOG_TIMER_MIN_TIMEOUT_MS = 1000;

  private static final int POLL_FOR_RENDERED_FRAME_MS = 5;
  private static final int NO_FRAME = -1;

  private final ScheduledExecutorService mScheduledExecutorServiceForUiThread;
  private final AnimatedDrawableDiagnostics mAnimatedDrawableDiagnostics;
  private final MonotonicClock mMonotonicClock;
  private final int mDurationMs;
  private final int mFrameCount;
  private final int mTotalLoops;

  // Paint used to draw on a Canvas
  private final Paint mPaint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG);
  private final Rect mDstRect = new Rect();
  private final Paint mTransparentPaint;

  private volatile String mLogId;

  private AnimatedDrawableCachingBackend mAnimatedDrawableBackend;
  private long mStartTimeMs;

  // Index of frame scheduled to be drawn. Between 0 and mFrameCount - 1
  private int mScheduledFrameNumber;

  // Index of frame scheduled to be drawn but never is reset to zero. Keeps growing.
  private int mScheduledFrameMonotonicNumber;

  // Index of frame that will be drawn next. Between 0 and mFrameCount - 1. May fall behind
  // mScheduledFrameIndex if we can't keep up.
  private int mPendingRenderedFrameNumber;

  // Corresponds to mPendingRenderedFrameNumber but keeps growing.
  private int mPendingRenderedFrameMonotonicNumber;

  // Index of last frame that was drawn.
  private int mLastDrawnFrameNumber = -1;

  // Corresponds to mLastDrawnFrameNumber but keeps growing.
  private int mLastDrawnFrameMonotonicNumber = -1;

  // Bitmap for last drawn frame. Corresponds to mLastDrawnFrameNumber.
  private CloseableReference<Bitmap> mLastDrawnFrame;

  private boolean mWaitingForDraw;
  private long mLastInvalidateTimeMs = -1;

  private boolean mIsRunning;
  private boolean mHaveWatchdogScheduled;

  private float mSx = 1f;
  private float mSy = 1f;
  private boolean mApplyTransformation;
  private boolean mInvalidateTaskScheduled;
  private long mNextFrameTaskMs = -1;

  private final Runnable mStartTask = new Runnable() {
    @Override
    public void run() {
      onStart();
    }
  };

  private final Runnable mNextFrameTask = new Runnable() {
    @Override
    public void run() {
      FLog.v(TAG, "(%s) Next Frame Task", mLogId);
      onNextFrame();
    }
  };

  private final Runnable mInvalidateTask = new Runnable() {
    @Override
    public void run() {
      FLog.v(TAG, "(%s) Invalidate Task", mLogId);
      mInvalidateTaskScheduled = false;
      doInvalidateSelf();
    }
  };

  private final Runnable mWatchdogTask = new Runnable() {
    @Override
    public void run() {
      FLog.v(TAG, "(%s) Watchdog Task", mLogId);
      doWatchdogCheck();
    }
  };

  public AnimatedDrawable(
      ScheduledExecutorService scheduledExecutorServiceForUiThread,
      AnimatedDrawableCachingBackend animatedDrawableBackend,
      AnimatedDrawableDiagnostics animatedDrawableDiagnostics,
      MonotonicClock monotonicClock) {
    mScheduledExecutorServiceForUiThread = scheduledExecutorServiceForUiThread;
    mAnimatedDrawableBackend = animatedDrawableBackend;
    mAnimatedDrawableDiagnostics = animatedDrawableDiagnostics;
    mMonotonicClock = monotonicClock;
    mDurationMs = mAnimatedDrawableBackend.getDurationMs();
    mFrameCount = mAnimatedDrawableBackend.getFrameCount();
    mAnimatedDrawableDiagnostics.setBackend(mAnimatedDrawableBackend);
    mTotalLoops = mAnimatedDrawableBackend.getLoopCount();
    mTransparentPaint = new Paint();
    mTransparentPaint.setColor(Color.TRANSPARENT);
    mTransparentPaint.setStyle(Paint.Style.FILL);

    // Show last frame when not animating.
    resetToPreviewFrame();
  }

  private void resetToPreviewFrame() {
    mScheduledFrameNumber = mAnimatedDrawableBackend.getFrameForPreview();
    mScheduledFrameMonotonicNumber = mScheduledFrameNumber;
    mPendingRenderedFrameNumber = NO_FRAME;
    mPendingRenderedFrameMonotonicNumber = NO_FRAME;
  }

  @Override
  protected void finalize() throws Throwable {
    super.finalize();
    if (mLastDrawnFrame != null) {
      mLastDrawnFrame.close();
      mLastDrawnFrame = null;
    }
  }

  /**
   * Sets an id that will be logged with any of the logging calls. Useful for debugging.
   *
   * @param logId the id to log
   */
  public void setLogId(String logId) {
    mLogId = logId;
  }

  @Override
  public int getIntrinsicWidth() {
    return mAnimatedDrawableBackend.getWidth();
  }

  @Override
  public int getIntrinsicHeight() {
    return mAnimatedDrawableBackend.getHeight();
  }

  @Override
  public void setAlpha(int alpha) {
    mPaint.setAlpha(alpha);
    doInvalidateSelf();
  }

  @Override
  public void setColorFilter(ColorFilter cf) {
    mPaint.setColorFilter(cf);
    doInvalidateSelf();
  }

  @Override
  public int getOpacity() {
    return PixelFormat.TRANSLUCENT;
  }

  @Override
  protected void onBoundsChange(Rect bounds) {
    super.onBoundsChange(bounds);
    mApplyTransformation = true;
    if (mLastDrawnFrame != null) {
      mLastDrawnFrame.close();
      mLastDrawnFrame = null;
    }
    mLastDrawnFrameNumber = -1;
    mLastDrawnFrameMonotonicNumber = -1;
    mAnimatedDrawableBackend.dropCaches();
  }

  private void onStart() {
    if (!mIsRunning) {
      return;
    }
    mAnimatedDrawableDiagnostics.onStartMethodBegin();
    try {
      mStartTimeMs = mMonotonicClock.now();
      mScheduledFrameNumber = 0;
      mScheduledFrameMonotonicNumber = 0;
      long nextFrameMs = mStartTimeMs + mAnimatedDrawableBackend.getDurationMsForFrame(0);
      scheduleSelf(mNextFrameTask, nextFrameMs);
      mNextFrameTaskMs = nextFrameMs;
      doInvalidateSelf();
    } finally {
      mAnimatedDrawableDiagnostics.onStartMethodEnd();
    }
  }

  private void onNextFrame() {
    mNextFrameTaskMs = -1;
    if (!mIsRunning) {
      return;
    }
    if (mDurationMs == 0) {
      return;
    }
    mAnimatedDrawableDiagnostics.onNextFrameMethodBegin();
    try {
      computeAndScheduleNextFrame(true /* schedule next frame */);
    } finally {
      mAnimatedDrawableDiagnostics.onNextFrameMethodEnd();
    }
  }

  private void computeAndScheduleNextFrame(boolean scheduleNextFrame) {
    if (mDurationMs == 0) {
      return;
    }
    long nowMs = mMonotonicClock.now();
    int loops = (int) ((nowMs - mStartTimeMs) / mDurationMs);
    if (mTotalLoops > 0 && loops >= mTotalLoops) {
      //we stop the animation if we have exceeded the total loop count
      return;
    }
    int timestampMs = (int) ((nowMs - mStartTimeMs) % mDurationMs);
    int newCurrentFrameNumber = mAnimatedDrawableBackend.getFrameForTimestampMs(timestampMs);
    boolean changed = mScheduledFrameNumber != newCurrentFrameNumber;
    mScheduledFrameNumber = newCurrentFrameNumber;
    mScheduledFrameMonotonicNumber = loops * mFrameCount + newCurrentFrameNumber;

    if (!scheduleNextFrame) {
      // We're about to draw. We don't need to schedule anything because we're going to draw
      // that frame right now. the onDraw method just wants to make sure the current frame is set.
      return;
    }

    if (changed) {
      doInvalidateSelf();
    } else {
      int durationMs = mAnimatedDrawableBackend.getTimestampMsForFrame(mScheduledFrameNumber) +
          mAnimatedDrawableBackend.getDurationMsForFrame(mScheduledFrameNumber) -
          timestampMs;
      int nextFrame = (mScheduledFrameNumber + 1) % mFrameCount;
      long nextFrameMs = nowMs + durationMs;
      if (mNextFrameTaskMs == -1 || mNextFrameTaskMs > nextFrameMs) {
        FLog.v(TAG, "(%s) Next frame (%d) in %d ms", mLogId, nextFrame, durationMs);
        unscheduleSelf(mNextFrameTask); // Cancel any existing task.
        scheduleSelf(mNextFrameTask, nextFrameMs);
        mNextFrameTaskMs = nextFrameMs;
      }
    }
  }

  @Override
  public void draw(Canvas canvas) {
    mAnimatedDrawableDiagnostics.onDrawMethodBegin();
    try {
      mWaitingForDraw = false;
      if (mIsRunning && !mHaveWatchdogScheduled) {
        mScheduledExecutorServiceForUiThread.schedule(
            mWatchdogTask,
            WATCH_DOG_TIMER_POLL_INTERVAL_MS,
            TimeUnit.MILLISECONDS);
        mHaveWatchdogScheduled = true;
      }

      if (mApplyTransformation) {
        mDstRect.set(getBounds());
        if (!mDstRect.isEmpty()) {
          AnimatedDrawableCachingBackend newBackend =
              mAnimatedDrawableBackend.forNewBounds(mDstRect);
          if (newBackend != mAnimatedDrawableBackend) {
            mAnimatedDrawableBackend.dropCaches();
            mAnimatedDrawableBackend = newBackend;
            mAnimatedDrawableDiagnostics.setBackend(newBackend);
          }
          mSx = (float) mDstRect.width() / mAnimatedDrawableBackend.getRenderedWidth();
          mSy = (float) mDstRect.height() / mAnimatedDrawableBackend.getRenderedHeight();
          mApplyTransformation = false;
        }
      }

      if (mDstRect.isEmpty()) {
        // Don't try to draw if the dest rect is empty.
        return;
      }

      canvas.save();
      canvas.scale(mSx, mSy);

      // TODO(6169940) we overdraw if both pending frame is ready and current frame is ready.
      boolean didDrawFrame = false;
      if (mPendingRenderedFrameNumber != NO_FRAME) {
        // We tried to render a frame and it wasn't yet ready. See if it's ready now.
        boolean rendered =
            renderFrame(canvas, mPendingRenderedFrameNumber, mPendingRenderedFrameMonotonicNumber);
        didDrawFrame |= rendered;
        if (rendered) {
          FLog.v(TAG, "(%s) Rendered pending frame %d", mLogId, mPendingRenderedFrameNumber);
          mPendingRenderedFrameNumber = NO_FRAME;
          mPendingRenderedFrameMonotonicNumber = NO_FRAME;
        } else {
          // Try again later.
          FLog.v(TAG, "(%s) Trying again later for pending %d", mLogId, mPendingRenderedFrameNumber);
          scheduleInvalidatePoll();
        }
      }

      if (mPendingRenderedFrameNumber == NO_FRAME) {
        // We don't have a frame that's pending so render the current frame.
        if (mIsRunning) {
          computeAndScheduleNextFrame(false /* don't schedule yet */);
        }
        boolean rendered = renderFrame(
            canvas,
            mScheduledFrameNumber,
            mScheduledFrameMonotonicNumber);
        didDrawFrame |= rendered;
        if (rendered) {
          FLog.v(TAG, "(%s) Rendered current frame %d", mLogId, mScheduledFrameNumber);
          if (mIsRunning) {
            computeAndScheduleNextFrame(true /* schedule next frame */);
          }
        } else {
          FLog.v(TAG, "(%s) Trying again later for current %d", mLogId, mScheduledFrameNumber);
          mPendingRenderedFrameNumber = mScheduledFrameNumber;
          mPendingRenderedFrameMonotonicNumber = mScheduledFrameMonotonicNumber;
          scheduleInvalidatePoll();
        }
      }

      if (!didDrawFrame) {
        if (mLastDrawnFrame != null) {
          canvas.drawBitmap(mLastDrawnFrame.get(), 0f, 0f, mPaint);
          didDrawFrame = true;
          FLog.v(TAG, "(%s) Rendered last known frame %d", mLogId, mLastDrawnFrameNumber);
        }
      }

      if (!didDrawFrame) {
        // Last ditch effort, use preview bitmap.
        CloseableReference<Bitmap> previewBitmapReference =
            mAnimatedDrawableBackend.getPreviewBitmap();
        if (previewBitmapReference != null) {
          canvas.drawBitmap(previewBitmapReference.get(), 0f, 0f, mPaint);
          previewBitmapReference.close();
          FLog.v(TAG, "(%s) Rendered preview frame", mLogId);
          didDrawFrame = true;
        }
      }

      if (!didDrawFrame) {
        // TODO(6169940) this may not be necessary. Confirm with Rich.
        canvas.drawRect(0, 0, mDstRect.width(), mDstRect.height(), mTransparentPaint);
        FLog.v(TAG, "(%s) Failed to draw a frame", mLogId);
      }

      canvas.restore();
      mAnimatedDrawableDiagnostics.drawDebugOverlay(canvas, mDstRect);
    } finally {
      mAnimatedDrawableDiagnostics.onDrawMethodEnd();
    }
  }

  /**
   * Schedule a task to invalidate the drawable. Used to poll for a rendered frame.
   */
  private void scheduleInvalidatePoll() {
    if (mInvalidateTaskScheduled) {
      return;
    }
    mInvalidateTaskScheduled = true;
    scheduleSelf(mInvalidateTask, POLL_FOR_RENDERED_FRAME_MS);
  }

  /**
   * Returns whether a previous call to {@link #draw} would have rendered a frame.
   *
   * @return whether a previous call to {@link #draw} would have rendered a frame
   */
  public boolean didLastDrawRender() {
    return mLastDrawnFrame != null;
  }

  /**
   * Renders the specified frame to the canvas.
   *
   * @param canvas the canvas to render to
   * @param frameNumber the relative frame number (between 0 and frame count)
   * @param frameMonotonicNumber the absolute frame number for stats purposes
   * @return whether the frame was available and was rendered
   */
  private boolean renderFrame(
      Canvas canvas,
      int frameNumber,
      int frameMonotonicNumber) {
    CloseableReference<Bitmap> bitmapReference =
        mAnimatedDrawableBackend.getBitmapForFrame(frameNumber);
    if (bitmapReference != null) {
      canvas.drawBitmap(bitmapReference.get(), 0f, 0f, mPaint);
      if (mLastDrawnFrame != null) {
        mLastDrawnFrame.close();
      }

      if (mIsRunning && frameMonotonicNumber > mLastDrawnFrameMonotonicNumber) {
        int droppedFrames = frameMonotonicNumber - mLastDrawnFrameMonotonicNumber - 1;
        mAnimatedDrawableDiagnostics.incrementDrawnFrames(1);
        mAnimatedDrawableDiagnostics.incrementDroppedFrames(droppedFrames);
        if (droppedFrames > 0) {
          FLog.v(TAG, "(%s) Dropped %d frames", mLogId, droppedFrames);
        }
      }
      mLastDrawnFrame = bitmapReference;
      mLastDrawnFrameNumber = frameNumber;
      mLastDrawnFrameMonotonicNumber = frameMonotonicNumber;
      FLog.v(TAG, "(%s) Drew frame %d", mLogId, frameNumber);
      return true;
    }
    return false;
  }

  /**
   * Checks to make sure we drop our caches if we haven't drawn in a while. There's no reliable
   * way for a Drawable to determine if it's still actively part of a View, so we use a heuristic
   * instead.
   */
  private void doWatchdogCheck() {
    mHaveWatchdogScheduled = false;
    if (!mIsRunning) {
      return;
    }
    long now = mMonotonicClock.now();

    // Timeout if it's been more than 2 seconds with drawn since invalidation.
    boolean hasNotDrawnWithinTimeout =
        mWaitingForDraw && now - mLastInvalidateTimeMs > WATCH_DOG_TIMER_MIN_TIMEOUT_MS;

    // Also timeout onNextFrame is more than 2 seconds late.
    boolean hasNotAdvancedFrameWithinTimeout =
        mNextFrameTaskMs != -1 && now - mNextFrameTaskMs > WATCH_DOG_TIMER_MIN_TIMEOUT_MS;

    if (hasNotDrawnWithinTimeout || hasNotAdvancedFrameWithinTimeout) {
      dropCaches();
      doInvalidateSelf();
    } else {
      mScheduledExecutorServiceForUiThread.schedule(
          mWatchdogTask,
          WATCH_DOG_TIMER_POLL_INTERVAL_MS,
          TimeUnit.MILLISECONDS);
      mHaveWatchdogScheduled = true;
    }
  }

  private void doInvalidateSelf() {
    mWaitingForDraw = true;
    mLastInvalidateTimeMs = mMonotonicClock.now();
    invalidateSelf();
  }

  @VisibleForTesting
  boolean isWaitingForDraw() {
    return mWaitingForDraw;
  }

  @VisibleForTesting
  boolean isWaitingForNextFrame() {
    return mNextFrameTaskMs != -1;
  }

  @VisibleForTesting
  int getScheduledFrameNumber() {
    return mScheduledFrameNumber;
  }

  @Override
  public void start() {
    if (mDurationMs == 0 || mFrameCount <= 1) {
      return;
    }
    mIsRunning = true;
    scheduleSelf(mStartTask, mMonotonicClock.now());
  }

  @Override
  public void stop() {
    mIsRunning = false;
  }

  @Override
  public boolean isRunning() {
    return mIsRunning;
  }

  @Override
  protected boolean onLevelChange(int level) {
    if (mIsRunning) {
      // If the client called start on us, they expect us to run the animation. In that case,
      // we ignore level changes.
      return false;
    }
    int frame = mAnimatedDrawableBackend.getFrameForTimestampMs(level);
    if (frame == mScheduledFrameNumber) {
      return false;
    }

    try {
      mScheduledFrameNumber = frame;
      mScheduledFrameMonotonicNumber = frame;
      doInvalidateSelf();
      return true;
    } catch (IllegalStateException e) {
      // The underlying image was disposed.
      return false;
    }
  }

  @Override
  public ValueAnimator createValueAnimator(int maxDurationMs) {
    ValueAnimator animator = createValueAnimator();
    int repeatCount = Math.max((maxDurationMs / mAnimatedDrawableBackend.getDurationMs()), 1);
    animator.setRepeatCount(repeatCount);
    return animator;
  }

  @Override
  public ValueAnimator createValueAnimator() {
    int loopCount = mAnimatedDrawableBackend.getLoopCount();
    ValueAnimator animator = new ValueAnimator();
    animator.setIntValues(0, mDurationMs);
    animator.setDuration(mDurationMs);
    animator.setRepeatCount(loopCount != 0 ? loopCount : ValueAnimator.INFINITE);
    animator.setRepeatMode(ValueAnimator.RESTART);
    animator.setInterpolator(new LinearInterpolator());
    animator.addUpdateListener(createAnimatorUpdateListener());
    return animator;
  }

  @Override
  public ValueAnimator.AnimatorUpdateListener createAnimatorUpdateListener() {
    return new ValueAnimator.AnimatorUpdateListener() {
      @Override
      public void onAnimationUpdate(ValueAnimator animation) {
        setLevel((Integer) animation.getAnimatedValue());
      }
    };
  }

  @Override
  public void dropCaches() {
    FLog.v(TAG, "(%s) Dropping caches", mLogId);
    if (mLastDrawnFrame != null) {
      mLastDrawnFrame.close();
      mLastDrawnFrame = null;
      mLastDrawnFrameNumber = -1;
      mLastDrawnFrameMonotonicNumber = -1;
    }
    mAnimatedDrawableBackend.dropCaches();
  }
}


text:
<!DOCTYPE public "-//w3c//dtd html 4.01 transitional//en"
		"http://www.w3.org/TR/html4/loose.dtd">

  <title>introduction</title>
  <link rel="stylesheet" type="text/css" href="../../../css/format.css"/>
  <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"/>
  <meta name="description" content="introduction into collision avoidance and overtaking"/>
  <meta name="author" content="Bernhard Wymann"/>
  <meta name="keywords" content="torcs, berniw, bernhard wymann, collision, avoidance, overtaking, opponent"/>

7.1 Collecting Data About Opponents

Introduction

		  In this chapter we implement the ability to avoid collisions and to overtake
		  opponents. I show you quite simple implementations, therefore there is much
		  room left for improvements. For me it is one of the most interesting parts of the robots,
		  because you can implement it in very different ways and it is not easy to predict
		  which ideas will work well and which will not. The following implementation
		  starts with collecting data about the opponents. After that we implement collision
		  avoidance and finally overtaking.

The Opponent Class

		  First we define a class for our opponents. It holds data about the opponents relative
		  to our robot, e. g. the distance between opponent X's car and ours. For simplicity
		  I will also put some data into it which is just dependent of the opponent. This is not
		  efficient if we run more than one robot with our module, it would be better to put
		  that data into a separate class whose instances are visible from all robots of our
		  module and are just updated
		  once per timestep (e. g. when we start bt 1
		  and bt 2 both will compute the speed
		  of opponent X, that is neither efficient nor necessary).
		  You can achieve such an update with checking the simulation time and just update the
		  data when the simulation time has changed. The code would then look somelike that:

static double currenttime;   /* class variable in Driver */
...
if (currenttime != situation->currentTime) {
    currenttime = situation->currentTime;
    allcars.update();
}

The Opponents Class

		  The Opponents class will just hold an array of opponents.

The opponent.h File

		  Put the following stuff into opponent.h in the bt
		  directory. I will explain the details
		  in the discussion of opponent.cpp.

/***************************************************************************

    file                 : opponent.h
    created              : Thu Apr 22 01:20:19 CET 2003
    copyright            : (C) 2003 Bernhard Wymann

 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#ifndef _OPPONENT_H_
#define _OPPONENT_H_

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#include <tgf.h>
#include <track.h>
#include <car.h>
#include <raceman.h>
#include <robottools.h>
#include <robot.h>

#include "linalg.h"
#include "driver.h"

		  The following lines define bitmasks which we will use to classify the opponents. I will
		  explain them later.

#define OPP_IGNORE	0
#define OPP_FRONT	(1<<0)
#define OPP_BACK	(1<<1)
#define OPP_SIDE	(1<<2)
#define OPP_COLL	(1<<3)

		  Because of a cross dependency we need to define a Driver class prototype. After that
		  the declaration of the Opponent class starts.

class Driver;

/* Opponent maintains the data for one opponent */
class Opponent {
    public:
        Opponent();

        void setCarPtr(tCarElt *car) { this->car = car; }
        static void setTrackPtr(tTrack *track) { Opponent::track = track; }

        static float getSpeed(tCarElt *car);
        tCarElt *getCarPtr() { return car; }
        int getState() { return state; }
        float getCatchDist() { return catchdist; }
        float getDistance() { return distance; }
        float getSideDist() { return sidedist; }
        float getWidth() { return width; }
        float getSpeed() { return speed; }

        void update(tSituation *s, Driver *driver);

    private:
        float getDistToSegStart();

        tCarElt *car;       /* pointer to the opponents car */
        float distance;     /* approximation of the real distance */
        float speed;        /* speed in direction of the track */
        float catchdist;    /* distance needed to catch the opponent */
        float width;        /* the cars needed width on the track */
        float sidedist;     /* distance of center of gravity of the cars */
        int state;          /* state bitmask of the opponent */

        /* class variables */
        static tTrack *track;

        /* constants */
        static float FRONTCOLLDIST;
        static float BACKCOLLDIST;
        static float SIDECOLLDIST;
        static float LENGTH_MARGIN;
        static float SIDE_MARGIN;
};

		  Finally follows the declaration of the Opponents class. Like you can see it is just
		  responsible for the update of the opponents.

/* The Opponents class holds an array of all Opponents */
class Opponents {
    public:
        Opponents(tSituation *s, Driver *driver);
        ~Opponents();

        void update(tSituation *s, Driver *driver);
        Opponent *getOpponentPtr() { return opponent; }
        int getNOpponents() { return nopponents; }

    private:
        Opponent *opponent;
        int nopponents;
};

#endif // _OPPONENT_H_

Summary

You have created opponent.h.

You have an idea of the data we collect.

Back

Collecting data.


text:
<?php

error_reporting(E_ALL | E_STRICT);

define('TEST_DIR', __DIR__);
define('TEMP_DIR', TEST_DIR . '/tmp');
define('VENDOR_DIR', dirname(TEST_DIR) . '/vendor');
define('DS', DIRECTORY_SEPARATOR);

if (!file_exists(VENDOR_DIR . '/autoload.php')) {
    exit('Please install Composer in the root folder before running tests!');
}

$loader = require VENDOR_DIR . '/autoload.php';
$loader->add('Titon\\Utility', TEST_DIR);


text:
package org.elasticsearch.action;

import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.rest.RestStatus;

/**
 *
 */
public class RoutingMissingException extends ElasticsearchException {

    private final String index;

    private final String type;

    private final String id;

    public RoutingMissingException(String index, String type, String id) {
        super("routing is required for [" + index + "]/[" + type + "]/[" + id + "]");
        this.index = index;
        this.type = type;
        this.id = id;
    }

    public String index() {
        return index;
    }

    public String type() {
        return type;
    }

    public String id() {
        return id;
    }

    @Override
    public RestStatus status() {
        return RestStatus.BAD_REQUEST;
    }
}


text:
package migrations

import (
	"xorm.io/xorm"
)

func removeOrganizationWatchRepo(x *xorm.Engine) error {
	// UserType defines the user type
	type UserType int

	const (
		// UserTypeIndividual defines an individual user
		UserTypeIndividual UserType = iota // Historic reason to make it starts at 0.

		// UserTypeOrganization defines an organization
		UserTypeOrganization
	)

	sess := x.NewSession()
	defer sess.Close()
	if err := sess.Begin(); err != nil {
		return err
	}
	if _, err := sess.Exec("DELETE FROM `watch` WHERE `user_id` IN (SELECT `id` FROM `user` WHERE `type` = ?)", UserTypeOrganization); err != nil {
		return err
	}
	if _, err := sess.Exec("UPDATE `repository` SET num_watches = (SELECT count(*) FROM watch WHERE `repository`.`id` = watch.repo_id)"); err != nil {
		return err
	}

	return sess.Commit()
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Repo2.Core.ns11.DomainModels;
using Repo2.Core.ns11.Extensions.StringExtensions;
using Repo2.Core.ns11.FileSystems;
using Repo2.SDK.WPF45.Encryption;
using Repo2.SDK.WPF45.Extensions.FileInfoExtensions;
using Repo2.SDK.WPF45.PackageFinders;
using Repo2.SDK.WPF45.Serialization;
using static System.Environment;

namespace Repo2.SDK.WPF45.FileSystems
{
    public class FileSystemAccesor1 : IFileSystemAccesor
    {
        public Task<bool> Delete(IEnumerable<string> filePaths)
            => Delete(filePaths.ToArray());

        public async Task<bool> Delete(params string[] filePaths)
        {
            foreach (var file in filePaths)
            {
                if (!File.Exists(file)) continue;
                await Task.Run(() =>
                {
                    try   { File.Delete(file); }
                    catch { }
                });
                if (File.Exists(file)) return false;
            }
            return true;
        }

        public async Task<bool> Move(string originalPath, string targetPath)
        {
            var deletd = await Delete(targetPath);
            if (!deletd) return false;

            await Task.Run(() =>
            {
                try   { File.Move(originalPath, targetPath); }
                catch { }
            });
            return File.Exists(targetPath);
        }

        public async Task<string> IsolateFile(R2Package localPkg)
        {
            var srcPath  = Chain(localPkg.LocalDir, localPkg.Filename);
            var destPath = Path.GetTempFileName();

            var task = Task.Run(()
                => File.Copy(srcPath, destPath, true));

            await task;
            return destPath;
        }

        private string Chain(params string[] paths)
            => Path.Combine(paths);

        public string GetSHA1(string filePath)
            => filePath.SHA1ForFile();

        public string WriteTempFile(byte[] byts)
        {
            var path = Path.GetTempFileName();
            File.WriteAllBytes(path, byts);
            return path;
        }

        public string WriteDesktopFile(string filename, string contents)
        {
            var path = GetDesktopFilePath(filename);
            WriteTextFile(contents, path);
            return path;
        }

        public string WriteFileBesideExe(string filename, string contents)
        {
            var path = GetBesideExeFilePath(filename);
            WriteTextFile(contents, path);
            return path;
        }

        public bool DesktopFileFound(string filename)
            => File.Exists(GetDesktopFilePath(filename));

        public string WriteDesktopJsonFile<T>(string filename, T objectToSerialize)
        {
            var json = Json.Serialize(objectToSerialize);
            return WriteDesktopFile(filename, json);
        }

        public string WriteJsonFileBesideExe<T>(string filename, T objectToSerialize)
        {
            var json = Json.Serialize(objectToSerialize, true);
            return WriteFileBesideExe(filename, json);
        }

        public T ReadDesktopJsonFile<T>(string filename)
        {
            var json = File.ReadAllText(GetDesktopFilePath(filename));
            return Json.Deserialize<T>(json);
        }

        public T ReadJsonFileBesideExe<T>(string filename)
        {
            var json = File.ReadAllText(GetBesideExeFilePath(filename));
            return Json.Deserialize<T>(json);
        }

        public bool WriteRepo2LogFile(string fileNameSuffix, string content, bool raiseError)
        {
            try
            {
                var date = $"{DateTime.Now:yyyy-MM-dd_hhmm}";
                var fNme = $"{date}_{fileNameSuffix}.log";
                var envF = GetFolderPath(SpecialFolder.LocalApplicationData);
                var dir  = Chain(envF, "Repo2", "Logs");
                WriteTextFile(content, Chain(dir, fNme));
                return true;
            }
            catch (Exception ex)
            {
                if (raiseError) throw ex;
                return false;
            }
        }

        public T DecryptJsonFile<T>(string filePath, string decryptKey)
        {
            var raw  = File.ReadAllText(filePath);
            if (raw.Length == 0) return default(T);
            if (raw[0] == Char.Parse("{")) return Json.Deserialize<T>(raw);

            var decryptd = AESThenHMAC.SimpleDecryptWithPassword(raw, decryptKey);
            return Json.Deserialize<T>(decryptd);
        }

        public void EncryptJsonToFile<T>(string filePath, T obj, string encryptKey)
        {
            var json = Json.Serialize(obj);
            var raw  = AESThenHMAC.SimpleEncryptWithPassword(json, encryptKey);
            WriteTextFile(raw, filePath);
        }

        public void WriteJsonFile(object objectToSerialize, string filePath)
            => WriteTextFile(Json.Serialize(objectToSerialize), filePath);

        public void WriteTextFile(string text, string filePath)
        {
            CreateDir(Path.GetDirectoryName(filePath));
            File.WriteAllText(filePath, text);
        }

        public string ReadBase64(string filePath)
            => Convert.ToBase64String(
                  File.ReadAllBytes(filePath));

        public bool Found(string filePath)
            => File.Exists(filePath);

        public R2Package ToR2Package(string filePath)
            => LocalR2Package.From(filePath);

        //public void AppendTo(string filePath, string text)
        //    => File.AppendAllText(filePath, text);

        public void CreateDir(string foldrPath)
            => Directory.CreateDirectory(foldrPath);

        public string GetTempFilePath(string filename = null)
            => filename.IsBlank() ? Path.GetTempFileName()
                                  : Chain(TempDir, filename);

        public string GetDesktopFilePath(string filename)
            => Chain(DesktopDir, filename);

        public string GetBesideExeFilePath(string filename)
            => Chain(CurrentExeDir, filename);

        public string GetAppDataFilePath(string subFoldername, string filename, string parentDir)
            => Chain(AppDataDir, parentDir, subFoldername, filename);

        public string AppDataDir        => GetFolderPath(SpecialFolder.LocalApplicationData);
        public string DesktopDir        => GetFolderPath(SpecialFolder.DesktopDirectory);
        //public string BesideExeDir      => GetBesideExeFileDir();
        public string CurrentExeFile    => Assembly.GetEntryAssembly()?.Location;
        public string CurrentExeDir     => GetBesideExeFileDir();
        public string CurrentExeVersion => GetFileVersion(CurrentExeFile);

        private string GetBesideExeFileDir()
        {
            //Directory.GetParent(Assembly.GetEntryAssembly().Location).FullName;

            var dir = CurrentExeFile ?? AppDomain.CurrentDomain.BaseDirectory;

            return Directory.GetParent(dir).FullName;
        }

        public string ParentDir(string path)
            => Directory.GetParent(path).FullName;

        public string TempDir      => Chain(Path.GetTempPath(), GetType().Name);

        private string GetFileVersion(string filePath)
            => FileVersionInfo.GetVersionInfo(filePath).FileVersion;
    }

    public class FileIO
    {
        public static void Delete(IEnumerable<string> filePaths)
            => new FileSystemAccesor1().Delete(filePaths);
    }
}


text:
INSTALL_STAMP=.install.stamp

all: install
install: $(INSTALL_STAMP)

$(INSTALL_STAMP):
	npm install
	touch $(INSTALL_STAMP)

test: install
	@./node_modules/mocha-phantomjs/bin/mocha-phantomjs test/index.html

clean:
	rm -rf node_modules/ $(INSTALL_STAMP)

.PHONY: test


text:
#pragma once

#include <string>
#include <pangolin/platform.h>
#include <pangolin/utils/params.h>

namespace pangolin
{

struct PANGOLIN_EXPORT Uri : public Params
{
    std::string scheme;
    std::string url;
    std::string full_uri;
};

//! Parse string as Video URI
PANGOLIN_EXPORT
Uri ParseUri(const std::string& str_uri);

}


text:
<?php
use fay\helpers\HtmlHelper;
use fay\services\FileService;

/**
 * @var $widget \fay\widgets\images\controllers\IndexController
 * @var $files array
 */
?>
<div class="widget widget-images" id="widget-<?php echo HtmlHelper::encode($widget->alias)?>">

	<?php foreach($files as $f){
		if(empty($f['link'])){
			$f['link'] = 'javascript:;';
		}
		echo HtmlHelper::link(HtmlHelper::img($f['file_id'], FileService::PIC_ORIGINAL, array(
			'width'=>false,
			'height'=>false,
			'alt'=>HtmlHelper::encode($f['title']),
		)), str_replace('{$base_url}', \F::config()->get('base_url'), $f['link']), array(
			'encode'=>false,
			'title'=>HtmlHelper::encode($f['title']),
			'wrapper'=>'li',
			'target'=>'_blank',
		));
	}?>


text:
<?php defined('SYSPATH') or die('No direct script access.');

class Model_Instagram extends Model {

	const PATH = 'https://api.instagram.com/';

	private $v         = 'v1';
	private $client_id = '95f94e473c5f4151b4dc8c6d0fbe49d7';
	private $secret    = '2f9bcc10c14e4fc08574c925025396df';

	public function set_client_id($client_id)
	{
		$this->client_id = $client_id;
	}

	public function set_secret($secret)
	{
		$this->secret = $secret;
	}

	public function set_v($v)
	{
		$v = $this->v;
	}

	private function get_client_id()
	{
		return($this->client_id);
	}

	private function get_secret()
	{
		return($this->secret);
	}

	private function get_v()
	{
		return($this->v);
	}

	private function get_path()
	{
		return(self::PATH.$this->v);
	}

	// give a latitude (lat) and longitude (lng), returns an Instagram location id. returns bool FALSE if none found
	public function search_location($params)
	{
		// init
		$request       = '';
		$response      = FALSE;
		$return        = 'first_result';
		$lat           = 0;
		$lng           = 0;
		$foursquare_id = 0;
		$distance      = 4000; //in meters
		extract($params);

		// create api call
		$client_id = $this->get_client_id();
		$path      = $this->get_path();
		$endpoint  = '/locations/search';
		if ($foursquare_id)
		{
			$query = '?foursquare_v2_id='.$foursquare_id.'&distance='.$distance.'&client_id='.$client_id;
		}
		else
		{
			$query = '?lat='.$lat.'&lng='.$lng.'&distance='.$distance.'&client_id='.$client_id;
		}
		$url = $path.$endpoint.$query;

		// call, check and return
		$request  = Request::factory($url);
		$response = json_decode($request->execute());
		$check    = $this->check($response);
		if ( ! $check)
		{
			return(FALSE);
		}
		else
		{
			if ($return === 'first_result' and isset($response->data['0']))
			{
				return($response->data['0']);
			}
			else
			{
				return($response->data);
			}
		}
	}

	public function get_location_media($params)
	{
		// init
		$request       = '';
		$response      = FALSE;
		$location_id   = 0;
		$min_timestamp = 0;
		$max_timestamp = 0;
		$min_id        = NULL;
		$max_id        = NULL;
		extract($params);

		// create api call
		$client_id = $this->get_client_id();
		$path      = $this->get_path();
		$endpoint  = '/locations/'.$location_id.'/media/recent';
		$query     = '?min_timestamp='.$min_timestamp.'&max_timestamp='.$max_timestamp.'&min_id='.$min_id.'&max_id='.$max_id.'&client_id='.$client_id;
		$url       = $path.$endpoint.$query;

		// call, check and return
		$request  = Request::factory($url);
		$response = json_decode($request->execute());
		$check    = $this->check($response);
		if ( ! $check)
		{
			return(FALSE);
		}
		else
		{
			return($response->data);
		}
	}

	// error check for response call. Returns FALSE on error and TRUE on success.
	public function check($response)
	{
		if ($response AND $response->meta->code !== 200)
		{
			Kohana::$log->add(Log::ERROR, 'Instagram search_location code: '.$response->meta->code.' Type: '.$response->meta->error_type.' Message: '.$response->meta->error_message);
			return(FALSE);
		}
		else
		{
			return(TRUE);
		}
	}

} // End


text:
An exchange for messages shared by different services. This connects with Redis to publish incoming messages to a
configurable topic.

# Quick Start

Start Redis
```
➜  hailstorm-sdk$ docker-compose up -d hailstorm-mq
```

Run it from the command line.
```bash
➜  hailstorm-client-exchange$ ./gradlew bootRun
```

If Redis is running on a different host, pass ``redisHost`` as an argument.
```bash
➜  hailstorm-client-exchange$ ./gradlew bootRun --args=--redisHost=hailstorm-mq.somewhere
```

# Docker

Build a docker image.
```
➜  hailstorm-client-exchange$ make package
```


text:
<?php

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace PhpCsFixer\Tests\Tokenizer\Analyzer\Analysis;

use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\CaseAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\SwitchAnalysis;

/**
 * @author Kuba Werłos <werlos@gmail.com>
 *
 * @covers \PhpCsFixer\Tokenizer\Analyzer\Analysis\SwitchAnalysis
 *
 * @internal
 */
final class SwitchAnalysisTest extends TestCase
{
    public function testCasesStart()
    {
        $analysis = new SwitchAnalysis(10, 20, []);
        static::assertSame(10, $analysis->getCasesStart());
    }

    public function testCasesEnd()
    {
        $analysis = new SwitchAnalysis(10, 20, []);
        static::assertSame(20, $analysis->getCasesEnd());
    }

    public function testCases()
    {
        $cases = [new CaseAnalysis(12), new CaseAnalysis(16)];

        $analysis = new SwitchAnalysis(10, 20, $cases);
        static::assertSame($cases, $analysis->getCases());
    }
}


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

using System;

namespace Microsoft.Azure.Commands.Automation.Common
{
    public class Constants
    {
        public const string ClientIdentity = "PowerShell";

        public const char RunbookTagsSeparatorChar = ',';

        public const string RunbookTagsSeparatorString = ",";

        public const string Published = "Published";

        public const string Draft = "Draft";

        public const string DefaultPlan = "Free";

        public const string AutomationServicePrefix = "OaasCS";

        public const string JobStartedByParameterName = "MicrosoftApplicationManagementStartedBy";

        public const string JobRunOnParameterName = "MicrosoftApplicationManagementRunOn";

        public const string ClientRequestIdHeaderName = "x-ms-client-request-id";

        public const string ActivityIdHeaderName = "x-ms-activity-id";

        // default schedule expiry time for daily schedule, consistent with UX
        // 12/31/9999 12:00:00 AM
        public static readonly DateTimeOffset DefaultScheduleExpiryTime = DateTimeOffset.MaxValue;

        public class AutomationAccountState
        {
            public const string Ready = "Ready";

            public const string Suspended = "Suspended";
        }

        public const string PsCommandConvertToJson = "ConvertTo-Json";

        public const string PsCommandConvertFromJson = "ConvertFrom-Json";

        public const string PsCommandParamInputObject = "InputObject";

        public const string PsCommandParamDepth = "Depth";

        public const int PsCommandValueDepth = 10;

        public const int JobSummaryLength = 80;

        public const int MaxWaitSeconds = 10800;

        // The template file is a json
        public const string TemplateFile = @"https://eus2oaasibizamarketprod1.blob.core.windows.net/automationdscpreview/azuredeployV2.json";

        // The metaconfig file
        public const string ModulesUrl = @"https://eus2oaasibizamarketprod1.blob.core.windows.net/automationdscpreview/RegistrationMetaConfigV2.zip";

        public const string ConfigurationFunction = @"RegistrationMetaConfigV2.ps1\RegistrationMetaConfigV2";

        public static class RunbookType
        {
            public const string PowerShell = "PowerShell";

            public const string PowerShellWorkflow = "PowerShellWorkflow";

            public const string Graph = "Graph";

            public const string GraphicalPowerShell = "GraphicalPowerShell";

            public const string GraphicalPowerShellWorkflow = "GraphicalPowerShellWorkflow";
        }

        public static class SupportedFileExtensions
        {
            public const string PowerShellScript = ".ps1";

            public const string Graph = ".graphrunbook";
        }
    }
}


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

     Copyright 2014-2016 CyberVision, Inc.

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.

-->

<configuration>
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{ISO8601} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="fileLogAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${server_log_dir}/kaa-operations-server${server_log_sufix}.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>30</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>%d{ISO8601} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <logger name="org.kaaproject.kaa.server.common.dao.cassandra" level="INFO"/>
    <logger name="org.apache.cassandra" level="WARN"/>

    <root level="INFO">
        <appender-ref ref="console"/>
        <appender-ref ref="fileLogAppender"/>
    </root>

</configuration>


text:
int w;
int k;
int l;

//minimizer() function
std::string minimizer(std::string subString){
  std::set<std::string> sortedItems;
  for(int i=0; i<(int)subString.size()-k+1; i++){
    sortedItems.insert(subString.substr(i,k));
    //std::cout << subString.substr(i,k) << std::endl;
  }
  //std::cout << *sortedItems.begin() << std::endl;

  return *sortedItems.begin();
}

//left_end() function
std::vector<std::string> left_end(std::string subString){
  std::vector<std::string> leftEndSeeds;
  for(int i=k; i<l; i++){
    leftEndSeeds.push_back(minimizer(subString.substr(0,i)));
    //std::cout << subString.substr(0,i) << std::endl;
  }
  return leftEndSeeds;
}

//right_end() function
std::vector<std::string> right_end(std::string subString){
  std::vector<std::string> rightEndSeeds;
  for(int i=0; i<l-k; i++){
    rightEndSeeds.push_back(minimizer(subString.substr(i,l-1)));
    //std::cout << subString.substr(i,l-1) << std::endl;
  }
  //for(auto i=rightEndSeeds.begin(); i!=rightEndSeeds.end(); ++i){
  //  std::cout << *i << std::endl;
  //}
  return rightEndSeeds;
}

//main() function
int main(int argc, char *argv[])
{
  //Init
  char* inputFile = argv[1];
  std::vector<std::string> minimizers;
  std::vector<std::string> leftEndMin;
  std::vector<std::string> rightEndMin;
  //w = (int)(argv[2][0] - '0');
  //k = (int)(argv[3][0] - '0');
  w = atoi(argv[2]);
  k = atoi(argv[3]);
  l = w+k-1;

  std::cout << "w=" << w << ", k=" << k << ", l=" << l << std::endl;

  //Loading input file to string and removing \n and \r
  std::ifstream ifs(inputFile);
  std::string genome( (std::istreambuf_iterator<char>(ifs) ),
                       (std::istreambuf_iterator<char>()    ) );
  genome.erase(std::remove(genome.begin(), genome.end(), '\n'), genome.end());
  genome.erase(std::remove(genome.begin(), genome.end(), '\r'), genome.end());

  std::cout << "Loaded " << genome.size() << " chars from string!" << std::endl;
  //std::cout << genome << std::endl;

  //Find left end minimizers
  leftEndMin = left_end(genome.substr(0,l-1));
  //std::cout << "leftEndMin: " << leftEndMin.size() << std::endl;
  for(int i=0; i<(int)leftEndMin.size(); i++){
    minimizers.push_back(leftEndMin[i]);
  }

  //Find interior minimizers
  for(int i=0; i<(int)genome.size()-l+1; i++){
    //std::cout << minimizer(genom.substr(i,k+w-1)) << std::endl;
    minimizers.push_back(minimizer(genome.substr(i,l)));
  }

  //Find right end minimizers
  rightEndMin = right_end(genome.substr(genome.size()-l+1,l-1));
  //std::cout << "rightEndMin: " << rightEndMin.size() << std::endl;
  for(int i=0; i<(int)rightEndMin.size(); i++){
    minimizers.push_back(rightEndMin[i]);
  }

  //Delete duplicates and print to stdout
  minimizers.erase(unique(minimizers.begin(), minimizers.end()), minimizers.end());
  //for(auto i=minimizers.begin(); i!=minimizers.end(); ++i){
  //  std::cout << *i << std::endl;
  //}

  //Write the results to a text file
  std::ofstream output_file("./output.txt");
  std::ostream_iterator<std::string> output_iterator(output_file, "\n");
  std::copy(minimizers.begin(), minimizers.end(), output_iterator);
  std::cout << "Stored " << minimizers.size() << " minimizers to output.txt" << std::endl;

  return 0;
}


text:
<?php defined('BASEPATH') or exit('No direct script access allowed');

$lang['streams:choice.name'] 				= 'Výběr z možností';
$lang['streams:choice.instructions'] 		= 'Napište každou možnost na jeden řádek. Pokud chcete oddělit hodnotu pro každou možnost, můžete použít dvojtečku (:). Např.
PyroCMS'."\n".'pyro : PyroCMS
';
$lang['streams:choice.choice_data'] 		= 'Možnosti na výběr';
$lang['streams:choice.choice_type'] 		= 'Typ výběru';
$lang['streams:choice.dropdown'] 			= 'Rozbalovací výběr';
$lang['streams:choice.radio_buttons'] 		= 'Jedna možnost (radio button)';
$lang['streams:choice.checkboxes'] 			= 'Více možností (checkbox)';
$lang['streams:choice.min_choices'] 		= 'Minimum Number of Selections'; #translate
$lang['streams:choice.max_choices'] 		= 'Maximum Number of Selections'; #translate
$lang['streams:choice.checkboxes_only'] 	= 'Only available for checkboxes.'; #translate
$lang['streams:choice.must_select_num'] 	= 'You must select {val} items from the %s list.';				#translate
$lang['streams:choice.must_at_least'] 		= 'You must select at least {val} items from the %s list.';		#translate
$lang['streams:choice.must_max_num'] 		= 'You can only select {val} items from the %s list.';			#translate
$lang['streams:choice.multiselect'] 		= 'Multiselect Type.'; 											#translate


text:
class Ability
  include CanCan::Ability

  def initialize(user)
    can :manage, :all if user.admin
  end
end


text:
noob-os
=======

Because I really have no idea what I'm doing

A list of resources;
* [Bochs](http://wiki.osdev.org/Bochs).
* [Current Status](http://wiki.osdev.org/Babystep1).
* [Bare Bones Setup](http://wiki.osdev.org/Bare_Bones).
* [Boot Sequence](http://wiki.osdev.org/Boot_Sequence).
* [Tutorials](http://wiki.osdev.org/Tutorials).
* [Assembly](http://wiki.osdev.org/Assembly).
* [Environment Setup](http://www.jamesmolloy.co.uk/tutorial_html/1.-Environment%20setup.html).


text:
from os import listdir
from os.path import abspath
from os.path import dirname
from os.path import isfile
from os.path import realpath
import cherrypy
import json
import os.path
import re

from PressUI.cherrypy.PressConfig import PressConfig
from PressUI.cherrypy.react import compile_react
from PressUI.cherrypy.static import press_get_static_file_by_dig
from PressUI.cherrypy.static import press_static_file
from PressUI.utils.browser_cache import add_cache_control_header
import PressUI.cherrypy.PressProduction as PressProduction

class _PressImageController():
    @cherrypy.tools.allow(methods = ['GET'])
    @cherrypy.expose
    def throbber_svg(self):
        cherrypy.response.headers['content-type'] = 'image/svg+xml'
        add_cache_control_header(years = 1)
        with open('PressUI/images/throbber.svg', 'rb') as f:
            return f.read()

class PressApp():
    __JQUERY_VERSION = '2.1.3'
    __REACT_VERSION = '0.13.1'

    def __init__(self):
        with open('PressUI/reactive/index.html', 'r') as f:
            self.__index_html = f.read()
        if PressProduction.is_production():
            to_remove = 'development'
        else:
            to_remove = 'production'
        self.__index_html = re.sub(
            '<!-- {to_remove} -->.*<!-- end_{to_remove} -->'.format(
                to_remove = to_remove,
            ),
            '',
            self.__index_html,
            flags = re.DOTALL,
        )

    def _js_sources(self):
        return []

    def _json(self, output):
        cherrypy.response.headers['content-type'] = 'application/json'
        add_cache_control_header()
        return json.dumps(output).encode('utf-8')

    @cherrypy.tools.allow(methods = ['GET'])
    @cherrypy.expose
    def fb_login_info_json(self):
        ret = self._json({
            'app_id': PressConfig.get('fb_app_id'),
            'hostname': cherrypy.request.base,
        })
        add_cache_control_header(years = 1)
        return ret

    @cherrypy.tools.allow(methods = ['GET'])
    @cherrypy.expose
    def favicon_png(self):
        cherrypy.response.headers['content-type'] = 'image/png'
        add_cache_control_header(years = 1)
        path = os.path.join(dirname(dirname(__file__)), 'FirefoxOS/icon.png')
        with open(path, 'rb') as f:
            return f.read()

    @cherrypy.tools.allow(methods = ['GET'])
    @cherrypy.expose
    def channel_html(self):
        add_cache_control_header(years = 1)
        return '<script src="//connect.facebook.net/en_US/all.js"></script>'

    # Same as `all_js` but for development.  Diffrerent path to avoid cache
    # problems.
    @cherrypy.tools.allow(methods = ['GET'])
    @cherrypy.expose
    def all_jsx_js(self, dig):
        return press_get_static_file_by_dig(dig, 'text/jsx')

    @cherrypy.tools.allow(methods = ['GET'])
    @cherrypy.expose
    def all_js(self, dig):
        return press_get_static_file_by_dig(dig, 'application/javascript')

    @cherrypy.tools.allow(methods = ['GET'])
    @cherrypy.expose
    def all_css(self, dig):
        return press_get_static_file_by_dig(dig, 'text/css')

    @cherrypy.tools.allow(methods = ['GET'])
    @cherrypy.expose
    def default(self, *args, **kwargs):
        add_cache_control_header(hours = 1)

        # Will be added twice but why not.
        js_sources = ['PressUI/reactive/jsx_header.js']
        for path in listdir('PressUI/reactive'):
            path = realpath('PressUI/reactive/' + path)
            if isfile(path) and path.endswith('.js'):
                js_sources.append(path)
        js_sources.extend(self._js_sources())

        compile_fun = None
        if PressProduction.is_production():
            compile_fun = lambda x: compile_react(self.__REACT_VERSION, x)
        js_dig = press_static_file(list(map(abspath, js_sources)), compile_fun)
        css_dig = press_static_file([abspath('style/all.css')])

        return self.__index_html.format(
            js_dig = js_dig,
            css_dig = css_dig,
            jquery_version = self.__JQUERY_VERSION,
            react_version = self.__REACT_VERSION,
        ).encode('utf-8')

    press_images = _PressImageController()


text:
Clazz.load(["java.util.AbstractList"],"java.util.AbstractSequentialList",["java.lang.IndexOutOfBoundsException"],function(){
c$=Clazz.declareType(java.util,"AbstractSequentialList",java.util.AbstractList);
Clazz.defineMethod(c$,"add",
function(location,object){
this.listIterator(location).add(object);
},"~N,~O");
Clazz.defineMethod(c$,"addAll",
function(location,collection){
var it=this.listIterator(location);
var colIt=collection.iterator();
var next=it.nextIndex();
while(colIt.hasNext()){
it.add(colIt.next());
it.previous();
}
return next!=it.nextIndex();
},"~N,java.util.Collection");
Clazz.overrideMethod(c$,"get",
function(location){
try{
return this.listIterator(location).next();
}catch(e){
if(Clazz.instanceOf(e,java.util.NoSuchElementException)){
throw new IndexOutOfBoundsException();
}else{
throw e;
}
}
},"~N");
Clazz.overrideMethod(c$,"iterator",
function(){
return this.listIterator(0);
});
Clazz.defineMethod(c$,"remove",
function(location){
try{
var it=this.listIterator(location);
var result=it.next();
it.remove();
return result;
}catch(e){
if(Clazz.instanceOf(e,java.util.NoSuchElementException)){
throw new IndexOutOfBoundsException();
}else{
throw e;
}
}
},"~N");
Clazz.overrideMethod(c$,"set",
function(location,object){
var it=this.listIterator(location);
var result=it.next();
it.set(object);
return result;
},"~N,~O");
});


text:
using System;
using System.Reflection;
using System.Runtime.Serialization;
using Orleans.Runtime;

namespace Orleans.Streams
{
    public delegate bool StreamFilterPredicate(IStreamIdentity stream, object filterData, object item);

    /// <summary>
    /// This class is a [Serializable] function pointer to a static predicate method, used for stream filtering.
    /// </summary>
    [Serializable]
    internal class FilterPredicateWrapperData : IStreamFilterPredicateWrapper
    {
        public object FilterData { get; private set; }

        private string methodName;
        private string className;

        [NonSerialized]
        private StreamFilterPredicate predicateFunc;

        internal FilterPredicateWrapperData(object filterData, StreamFilterPredicate pred)
        {
            FilterData = filterData;
            predicateFunc = pred;
            DehydrateStaticFunc(pred);
        }

        #region ISerializable methods
        protected FilterPredicateWrapperData(SerializationInfo info, StreamingContext context)
        {
            FilterData = info.GetValue("FilterData", typeof(object));
            methodName = info.GetString("MethodName");
            className = info.GetString("ClassName");
            predicateFunc = RehydrateStaticFuncion(className, methodName);
        }
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("FilterData", FilterData);
            info.AddValue("MethodName", methodName);
            info.AddValue("ClassName", className);
        }
        #endregion

        public bool ShouldReceive(IStreamIdentity stream, object filterData, object item)
        {
            if (predicateFunc == null)
            {
                predicateFunc = RehydrateStaticFuncion(className, methodName);
            }
            return predicateFunc(stream, filterData, item);
        }

        private static StreamFilterPredicate RehydrateStaticFuncion(string funcClassName, string funcMethodName)
        {
            var funcClassType = CachedTypeResolver.Instance.ResolveType(funcClassName);
            var method = funcClassType.GetMethod(funcMethodName);
            return (StreamFilterPredicate)method.CreateDelegate(typeof(StreamFilterPredicate));
        }

        private void DehydrateStaticFunc(StreamFilterPredicate pred)
        {
            var method = pred.Method;

            if (!CheckStaticFunc(method)) throw new ArgumentException("Filter function must be static and not abstract.");

            className = method.DeclaringType.FullName;
            methodName = method.Name;
        }

        private static bool CheckStaticFunc(MethodInfo method)
        {
            return method.IsStatic && !method.IsAbstract;
        }

        public override string ToString()
        {
            return string.Format("StreamFilterFunction:Class={0},Method={1}", className, methodName);
        }
    }
}