text:
<?xml version="1.0"?>
<doc>
    <assembly>
        <name>GHI.Premium.System</name>
    </assembly>
    <members>
        <member name="T:GHI.Premium.System.MathEx">

            Provides constants and static methods for trigonometric, logarithmic, and other common mathematical functions.

        </member>
        <member name="F:GHI.Premium.System.MathEx.E">

            Represents the natural logarithmic base, specified by the constant, e.

        </member>
        <member name="F:GHI.Premium.System.MathEx.PI">

            Represents the ratio of the circumference of a circle to its diameter, specified by the constant, π.

        </member>
        <member name="M:GHI.Premium.System.MathEx.Cos(System.Double)">

            Returns the cosine of the specified angle.

            <param name="d">An angle, measured in radians.</param>
            <returns>The cosine of d. If d is equal to NaN, NegativeInfinity, or PositiveInfinity, this method returns NaN.</returns>
        </member>
        <member name="M:GHI.Premium.System.MathEx.Sin(System.Double)">

            Returns the sine of the specified angle.

            <param name="a">An angle, measured in radians.</param>
            <returns>The sine of a. If a is equal to NaN, NegativeInfinity, or PositiveInfinity, this method returns NaN.</returns>
        </member>
        <member name="M:GHI.Premium.System.MathEx.Tan(System.Double)">

            Returns the tangent of the specified angle.

            <param name="a">An angle, measured in radians.</param>
            <returns>The tangent of a. If a is equal to NaN, NegativeInfinity, or PositiveInfinity, this method returns NaN.</returns>
        </member>
        <member name="M:GHI.Premium.System.MathEx.Acos(System.Double)">

            Returns the angle whose cosine is the specified number.

            <param name="d">A number representing a cosine, where -1 ≤d≤ 1.</param>
            <returns>An angle, θ, measured in radians, such that 0 ≤θ≤π or NaN if d < -1 or d > 1.</returns>
        </member>
        <member name="M:GHI.Premium.System.MathEx.Asin(System.Double)">

            Returns the angle whose sine is the specified number.

            <param name="d">A number representing a sine, where -1 ≤d≤ 1.</param>
            <returns>An angle, θ, measured in radians, such that -π/2 ≤θ≤π/2 or NaN if d < -1 or d > 1.</returns>
        </member>
        <member name="M:GHI.Premium.System.MathEx.Atan(System.Double)">

            Returns the angle whose tangent is the specified number.

            <param name="d">A number representing a tangent.</param>
            <returns>An angle, θ, measured in radians, such that -π/2 ≤θ≤π/2 or NaN if d equals NaN, -π/2 rounded to double precision (-1.5707963267949) if d equals NegativeInfinity, or π/2 rounded to double precision (1.5707963267949) if d equals PositiveInfinity.</returns>
        </member>
        <member name="M:GHI.Premium.System.MathEx.Atan2(System.Double,System.Double)">

            Returns the angle whose tangent is the quotient of two specified numbers.

            <param name="y">The y coordinate of a point.</param>
            <param name="x">The x coordinate of a point.</param>
            <returns>An angle, θ, measured in radians, such that -π≤θ≤π, and tan(θ) = y / x, where (x, y) is a point in the Cartesian plane.</returns>
        </member>
        <member name="M:GHI.Premium.System.MathEx.Cosh(System.Double)">

            Returns the hyperbolic cosine of the specified angle.

            <param name="value">An angle, measured in radians.</param>
            <returns>The hyperbolic cosine of value. If value is equal to NegativeInfinity or PositiveInfinity, PositiveInfinity is returned. If value is equal to NaN, NaN is returned.</returns>
        </member>
        <member name="M:GHI.Premium.System.MathEx.Sinh(System.Double)">

            Returns the hyperbolic sine of the specified angle.

            <param name="value">An angle, measured in radians.</param>
            <returns>The hyperbolic sine of value. If value is equal to NegativeInfinity, PositiveInfinity, or NaN, this method returns a Double equal to value.</returns>
        </member>
        <member name="M:GHI.Premium.System.MathEx.Tanh(System.Double)">

            Returns the hyperbolic tangent of the specified angle.

            <param name="value">An angle, measured in radians.</param>
            <returns>The hyperbolic tangent of value. If value is equal to NegativeInfinity, this method returns -1. If value is equal to PositiveInfinity, this method returns 1. If value is equal to NaN, this method returns NaN.</returns>
        </member>
        <member name="M:GHI.Premium.System.MathEx.Pow(System.Double,System.Double)">

            Returns a specified number raised to the specified power.

            <param name="x">A double-precision floating-point number to be raised to a power.</param>
            <param name="y">A double-precision floating-point number that specifies a power.</param>
            <returns>The number x raised to the power y.</returns>
        </member>
        <member name="M:GHI.Premium.System.MathEx.Sqrt(System.Double)">

            Returns the square root of a specified number.

            <param name="d">A number.</param>
            <returns>The positive square root of d.</returns>
        </member>
        <member name="M:GHI.Premium.System.MathEx.Exp(System.Double)">

            Returns e raised to the specified power.

            <param name="d">A number specifying a power.</param>
            <returns>The number e raised to the power d. If d equals NaN or PositiveInfinity, that value is returned. If d equals NegativeInfinity, 0 is returned.</returns>
        </member>
        <member name="M:GHI.Premium.System.MathEx.Log(System.Double)">

            Returns the natural (base e) logarithm of a specified number.

            <param name="d">A number whose logarithm is to be found. </param>
            <returns>The natural logarithm of d.</returns>
        </member>
        <member name="M:GHI.Premium.System.MathEx.Log10(System.Double)">

            Returns the base 10 logarithm of a specified number.

            <param name="d">A number whose logarithm is to be found.</param>
            <returns>The base 10 log of d.</returns>
        </member>
        <member name="M:GHI.Premium.System.MathEx.Ceiling(System.Double)">

            Returns the smallest integral value that is greater than or equal to the specified double-precision floating-point number.

            <param name="a">A double-precision floating-point number.</param>
            <returns>The smallest integral value that is greater than or equal to a. If a is equal to NaN, NegativeInfinity, or PositiveInfinity, that value is returned. Note that this method returns a Double instead of an integral type.</returns>
        </member>
        <member name="M:GHI.Premium.System.MathEx.Floor(System.Double)">

            Returns the largest integer less than or equal to the specified double-precision floating-point number.

            <param name="d">A double-precision floating-point number. </param>
            <returns>The largest integer less than or equal to d. If d is equal to NaN, NegativeInfinity, or PositiveInfinity, that value is returned.</returns>
        </member>
        <member name="M:GHI.Premium.System.MathEx.Round(System.Double)">

            Rounds a double-precision floating-point value to the nearest integral value.

            <param name="a">A double-precision floating-point number to be rounded.</param>
            <returns>The integer nearest a. If the fractional component of a is halfway between two integers, one of which is even and the other odd, then the even number is returned. Note that this method returns a Double instead of an integral type.</returns>
        </member>
        <member name="M:GHI.Premium.System.MathEx.Truncate(System.Double)">

            Calculates the integral part of a specified double-precision floating-point number.

            <param name="d">A number to truncate.</param>
            <returns>The integral part of d; that is, the number that remains after any fractional digits have been discarded.</returns>
        </member>
        <member name="T:GHI.Premium.System.XTEA">

            Extended Tiny Encryption Algorithm.

            <remarks>
            Extended Tiny Encryption Algorithm uses 128 bit key. It is secure and has simple implementation. The algorithm is explained in length at various sources including Wikipedia.

            The version used in this class does 32 cycles of XTEA encryption (most common).

            The data length to be encrypted or decrypted MUST be a multiple of 8. To work around this restriction, pad the data until it is a multiple of 8. Also, an implementation that does not have this limitation and is the same as NETMF's Key_TinyEncryptionAlgorithm is explained in the book "Expert .NET Micro Framework", Second Edition by Jens Kühner. It includes source example that implements XTEA in addition to cipher block chaining with cipher byte stealing. See chapter 8 source code in the book link.

            </remarks>
            <example>

<![CDATA[
using System;
using System.Text;
using Microsoft.SPOT;

using GHI.Premium.System;

public class Program
{
    public static void Main()
    {
        // 16-byte (128-bit) key
        byte[] XTEAKey = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ,16};

        XTEA xtea = new XTEA(XTEAKey);

        // The data to encrypt. Must be multiple of 8.
        string originalString = "FEZ rocks!!";

        // Append spaces to make it multiple of 8
        if(originalString.Length % 8 != 0)
            originalString += new string(' ', 8 - originalString.Length % 8);

        // Convert to byte array
        byte[] originalData = UTF8Encoding.UTF8.GetBytes(originalString);

        // Encrypt the data
        byte[] encryptedData = new byte[originalData.Length];
        xtea.Encrypt(originalData, 0, encryptedData, 0, encryptedData.Length);

        // Decrypt the data
        byte[] decryptedData = new byte[encryptedData.Length];
        xtea.Decrypt(encryptedData, 0, decryptedData, 0, decryptedData.Length);

        // Print the decrypted data
        string decryptedString = new string(Encoding.UTF8.GetChars(decryptedData));
        Debug.Print(originalString);
        Debug.Print(decryptedString);
    }
}
]]>

            </example>
        </member>
        <member name="M:GHI.Premium.System.XTEA.#ctor(System.Byte[])">

            Creates an XTEA using the encryption key.

            <param name="key">The key must be 16 bytes long (128 bits).</param>
        </member>
        <member name="M:GHI.Premium.System.XTEA.Encrypt(System.Byte[],System.Int32,System.Byte[],System.Int32,System.Int32)">

            Encrypts the data.

            <param name="plainData">Data to be encrypted. This array is not changed.</param>
            <param name="plainDataOffset">Offset into the plain data array.</param>
            <param name="encryptedData">Encrypted data will be written to this array.</param>
            <param name="encryptedDataOffset">Offset into the encrypted data array.</param>
            <param name="dataCount">Data count to be processed. It MUST be a multiple of 8.</param>
        </member>
        <member name="M:GHI.Premium.System.XTEA.Decrypt(System.Byte[],System.Int32,System.Byte[],System.Int32,System.Int32)">

            Decrypts the data.

            <param name="encryptedData">Data to be decrypted. This array is not changed.</param>
            <param name="encryptedDataOffset">Offset into the encrypted data array.</param>
            <param name="plainData">Decrypted data will be written to this array.</param>
            <param name="plainDataOffset">Offset into the plain data array.</param>
            <param name="dataCount">Data count to be processed. It MUST be a multiple of 8.</param>
        </member>
        <member name="T:GHI.Premium.System.CRC">

            Provides a cyclic redundancy check.

        </member>
        <member name="M:GHI.Premium.System.CRC.CRC_16_CCITT(System.Byte[],System.Int32,System.Int32,System.UInt16)">

            Computes CRC.

            <param name="buffer">Buffer.</param>
            <param name="offset">Offset.</param>
            <param name="count">Count.</param>
            <param name="seed">Seed.</param>
            <returns>CRC.</returns>
            <remarks>
            This is used in XMODEM and many others.
            </remarks>
        </member>
        <member name="M:GHI.Premium.System.CRC.CRC_32_IEEE_802_3(System.Byte[],System.Int32,System.Int32,System.UInt32)">

            Computes CRC.

            <param name="buffer">Buffer.</param>
            <param name="offset">Offset.</param>
            <param name="count">Conut.</param>
            <param name="seed">Seed.</param>
            <returns>CRC.</returns>
            <remarks>
            This is used in ZMODEM and many others.
            </remarks>
        </member>
        <member name="T:GHI.Premium.System.USBH_Device">

            Represents a device connected to USB Host.

        </member>
        <member name="F:GHI.Premium.System.USBH_Device.ID">

            Device ID.

            <remarks>
            This is unique among the currently connected USB devices. It will be the same for a device with multiple interfaces.
            </remarks>
        </member>
        <member name="F:GHI.Premium.System.USBH_Device.INTERFACE_INDEX">

            Logical device interface index.

            <remarks>
            Some USB devices might have multiple functions represented as multiple interfaces. If a device functions as a whole, this will be equal to <c>NO_INTERFACE_ASSOCIATED</c>.
            </remarks>
        </member>
        <member name="F:GHI.Premium.System.USBH_Device.TYPE">

            Device type.

        </member>
        <member name="F:GHI.Premium.System.USBH_Device.VENDOR_ID">

            Device Vendor ID.

            <remarks>
            This is unique per company.
            </remarks>
        </member>
        <member name="F:GHI.Premium.System.USBH_Device.PRODUCT_ID">

            Device Product ID.

            <remarks>
            This is unique per product for a certain company.
            </remarks>
        </member>
        <member name="F:GHI.Premium.System.USBH_Device.PORT_NUMBER">

            Device USB port number.

        </member>
        <member name="M:GHI.Premium.System.USBH_Device.#ctor(System.UInt32,System.Byte,GHI.Premium.System.USBH_DeviceType,System.UInt16,System.UInt16,System.Byte)">

            Constructor to create fields data.

            <param name="ID">ID.</param>
            <param name="INTERFACE_INDEX">INTERFACE_INDEX.</param>
            <param name="TYPE">TYPE.</param>
            <param name="VENDOR_ID">VENDOR_ID.</param>
            <param name="PRODUCT_ID">PRODUCT_ID.</param>
            <param name="PORT_NUMBER">PORT_NUMBER.</param>
        </member>
        <member name="M:GHI.Premium.System.USBH_Device.#ctor(GHI.Premium.System.USBH_Device)">

             Constructor to create fields data identical to a given device.

            <param name="device">Target device.</param>
        </member>
        <member name="T:GHI.Premium.System.USBH_DeviceType">

            Available devices' types.

        </member>
        <member name="F:GHI.Premium.System.USBH_DeviceType.Unknown">
            Device is not recognized.
        </member>
        <member name="F:GHI.Premium.System.USBH_DeviceType.Hub">
            USB Hub.
        </member>
        <member name="F:GHI.Premium.System.USBH_DeviceType.HID">
            Human Interface Device.
        </member>
        <member name="F:GHI.Premium.System.USBH_DeviceType.Mouse">
            Mouse.
        </member>
        <member name="F:GHI.Premium.System.USBH_DeviceType.Keyboard">
            Keyboard.
        </member>
        <member name="F:GHI.Premium.System.USBH_DeviceType.Joystick">
            Joystick.
        </member>
        <member name="F:GHI.Premium.System.USBH_DeviceType.MassStorage">
            Mass Storage. This includes USB storage devices such as USB Thumbs drives and USB hard disks.
        </member>
        <member name="F:GHI.Premium.System.USBH_DeviceType.Printer">
            Printer.
        </member>
        <member name="F:GHI.Premium.System.USBH_DeviceType.Serial_FTDI">
            USB to Serial device.
        </member>
        <member name="F:GHI.Premium.System.USBH_DeviceType.Serial_Prolific">
            USB to Serial device.
        </member>
        <member name="F:GHI.Premium.System.USBH_DeviceType.Serial_Prolific2">
            USB to Serial device.
        </member>
        <member name="F:GHI.Premium.System.USBH_DeviceType.Serial_SiLabs">
            USB to Serial device.
        </member>
        <member name="F:GHI.Premium.System.USBH_DeviceType.Serial_CDC">
            USB to Serial device.
        </member>
        <member name="F:GHI.Premium.System.USBH_DeviceType.Serial_Sierra_C885">
            USB to Serial device.
        </member>
        <member name="F:GHI.Premium.System.USBH_DeviceType.Sierra_Installer">
            Sierra Installer.
        </member>
        <member name="F:GHI.Premium.System.USBH_DeviceType.Video">
            Video device.
        </member>
        <member name="F:GHI.Premium.System.USBH_DeviceType.Webcamera">
            Webcamera.
        </member>
        <member name="T:GHI.Premium.System.SystemModelType">

            System model types.

            <remarks>
            To get the system model type use <c>Microsoft.SPOT.Hardware.SystemInfo.SystemID.Model</c>.
            </remarks>
        </member>
        <member name="F:GHI.Premium.System.SystemModelType.EMX">
            Model Type.
        </member>
        <member name="T:GHI.Premium.System.NetworkInterface">

            Network Interface.

            <remarks>
            To get the NetworkInterface use.
            </remarks>
        </member>
        <member name="F:GHI.Premium.System.NetworkInterface.Built_In_Ethernet">
            NetworkInterface.
        </member>
        <member name="T:GHI.Premium.System.ApplicationProtectionLevel">

            Application protect level.

            <remarks>
            To get the Application protect level use.
            </remarks>
        </member>
        <member name="T:GHI.Premium.System.Util">

            Utilities.

        </member>
        <member name="M:GHI.Premium.System.Util.SetApplicationProtection(GHI.Premium.System.ApplicationProtectionLevel,System.Byte[])">

             Allows Set Application Protect

             <param name="level">Application protect level</param>
             <param name="key">key value</param>
        </member>
        <member name="M:GHI.Premium.System.Util.SetApplicationProtection(System.Byte,System.Byte[])">

             Allows Set Application Protect

             <param name="level">Application protect level</param>
             <param name="key">key value</param>
        </member>
        <member name="M:GHI.Premium.System.Util.SetMACAddress(GHI.Premium.System.NetworkInterface,System.Byte[])">

             Allows Update MAC address

             <param name="network_interface">Network Interface</param>
             <param name="mac_addess">MAC address value</param>
        </member>
        <member name="M:GHI.Premium.System.Util.PlayPCMAudio(Microsoft.SPOT.Hardware.Cpu.AnalogOutputChannel,System.Byte[],System.Int32,System.Int32,System.Int32)">

             Allows .wav file playback through AnalogOut

             <param name="channel">AnalogOut Channel</param>
             <param name="data">.wav file buffer</param>
             <param name="offset">Array offset</param>
             <param name="count">Size of playback sample</param>
             <param name="dataRate">Frequency in Hz</param>
        </member>
        <member name="M:GHI.Premium.System.Util.FlushExtendedWeakReferences">

            Forces Extended Weak References to flush.

            <remarks>
            Extended Weak References are normally flushed in the background. Use this method to force flushing.
            </remarks>
        </member>
        <member name="M:GHI.Premium.System.Util.InsertValueIntoArray(System.String,System.Byte[],System.Int32,System.Boolean)">

            Converts a string to UTF-8 and inserts into a byte array.

            <param name="str">String.</param>
            <param name="bytes">Buffer.</param>
            <param name="offset">Insert offset in buffer.</param>
            <param name="nullTerminate"><c>true</c> to terminate the string with a null. If this is used, the <c>buffer</c> must have extra byte to store the null.</param>
        </member>
        <member name="M:GHI.Premium.System.Util.InsertValueIntoArray(System.Single,System.Byte[],System.Int32)">

            Converts a value into little-endian binary bytes representation and insert them into an array.

            <param name="f">Value.</param>
            <param name="buffer">Buffer.</param>
            <param name="offset">Insert offset in buffer.</param>
        </member>
        <member name="M:GHI.Premium.System.Util.ExtractValueFromArray(System.Single@,System.Byte[],System.Int32)">

            Converts little-endian binary bytes representation to an equivalent value.

            <param name="f">Output value.</param>
            <param name="buffer">Buffer.</param>
            <param name="offset">Extract offset in buffer.</param>
        </member>
        <member name="M:GHI.Premium.System.Util.BitmapConvertBPP(System.Byte[],System.Byte[],GHI.Premium.System.Util.BPP_Type)">

            Converts <c>Bitmap</c> pixel bytes into different BPP representation.

            <param name="bitmapBuffer">Bitmap bytes.</param>
            <param name="outputBuffer">Output buffer after conversion.</param>
            <param name="bpp">Target bits per pixel representation.</param>
            <remarks>
            GHI Electronics' devices support Bitmap and WPF graphics natively on color TFT displays. A design may require a small low-cost SPI-based displays. Different SPI LCDs can have different BPP requirements. This function converts the Bitmap bytes, where each pixel is represented as 4 bytes, into the needed BPP representation and then it can be transferred to the display.

            Start by doing all necessary graphics in NETMF on a Bitmap object. When you need to flush the results to the LCD:

            1) Get the Bitmap bytes using <c>myBitmap.GetBitmap()</c>.

            2) Use this conversion method to convert the buffer into the needed BPP.

            3) Send output buffer to LCD over SPI.

            This drawing technique can be used also with Windows Presentation Foundation but it does not work on old non-TFT Embedded Master and it requires the following:

            1) Set the display size to match your SPI-display using SetLCD. Use any values for timing and 0 for <c>PixelClockRateKHZ</c> which will disable TFT LCD refresh.

            2) Use the following code to fetch the Bitmap object from the WPF system.

            WindowManager.Instance.PostRender += new PostRenderEventHandler(Instance_PostRender);
            // …
            void Instance_PostRender(DrawingContext dc)
            {
               // get bitmap bytes
               byte[] MyBitmapBytes = dc.Bitmap.GetBitmap();

               // do any necessary conversion
               Util.ConvertBPP(MyBitmapBytes, output, Util.BPP_Type.BPP16_RGB_LE);

               // send over SPI
               MySPIDisplay.FlushData(output);
            }

            </remarks>
        </member>
        <member name="M:GHI.Premium.System.Util.BitmapToBMPFile(System.Byte[],System.Int32,System.Int32,System.Byte[])">

            Converts <c>Bitmap</c> pixel bytes to a BMP file.

            <remarks>
            This method coverts .NET Micro Framework's <c>Bitmap</c> pixels to a BMP file. This file can be stored on a storage device or transferred over a network.

            First allocate a buffer for the BMP file. Its size must be: imageWidth * imageHeight * 3 + 54. Then pass the buffer along with the Bitmap's pixels to this method. The Bitmap's pixels can be obtained using <c>Bitmap.GetBitmap()</c>.

            </remarks>
            <example>
            The following example creates an image using the <c>Bitmap</c> class. Then it is converted to a BMP file and saved to an SD card.

<![CDATA[
using System;
using System.IO;
using Microsoft.SPOT.Presentation.Media;
using Microsoft.SPOT;
using GHI.Premium.IO;
using GHI.Premium.System;

public class Program
{
    public static void Main()
    {
        // init SD card
        PersistentStorage ps = new PersistentStorage("SD");
        ps.MountFileSystem();

        // assume we have some image
        Bitmap image = new Bitmap(320, 240);
        image.DrawRectangle(Colors.Blue, 1, 0, 0, 320, 240, 0, 0, Colors.Blue, 0, 0, Colors.Blue, 0, 0, Bitmap.OpacityOpaque);
        image.DrawLine(Colors.Orange, 1, 0, 0, 320 - 1, 0);
        image.DrawLine(Colors.Red, 1, 0, 0, 0, 240-1);
        image.DrawLine(Colors.Yellow, 1, 320-1, 240-1, 0, 240-1);
        image.DrawLine(Colors.Magenta, 1, 320-1, 240-1, 320 - 1, 0);
        image.DrawEllipse(Colors.Red, 320/2, 240/2, 50, 50);

        // allocate buffer
        byte[] outputFile = new byte[image.Width * image.Height * 3 + 54];

        // convert to BMP file
        Util.BitmapToBMPFile(image.GetBitmap(), image.Width, image.Height, outputFile);

        // save image
        File.WriteAllBytes("\\SD\\CreatedBMPFile.bmp", outputFile);

        ps.Dispose();
    }

}
]]>

            </example>
            <param name="bitmapBuffer">Pixel data. This is done using <c>Bitmap.GetBitmap()</c>.</param>
            <param name="bitmapWidth">Image width (<c>Bitmap.Width</c>).</param>
            <param name="bitmapHeight">Image height (<c>Bitmap.Height</c>).</param>
            <param name="outputFileBuffer">BMP file buffer. Its size must be: imageWidth * imageHeight * 3 + 54.</param>
        </member>
        <member name="M:GHI.Premium.System.Util.IOCTL(System.UInt32,System.UInt32,System.UInt32,System.Byte[],System.Byte[],System.UInt32[])">

            Low level use.

            <param name="driverID">driverID.</param>
            <param name="n1">n1.</param>
            <param name="n2">n2.</param>
            <param name="b1">b1.</param>
            <param name="b2">b2.</param>
            <param name="a">a.</param>
            <returns>Return value.</returns>
        </member>
        <member name="M:GHI.Premium.System.Util.SplitToArray(System.Byte[],System.Int32,System.Char,System.Single[])">

             Splits a passed in string using a delimiter and fills out an array with the parsed values.

             <param name="line">The string to be split.</param>
             <param name="length">The length of the string.</param>
             <param name="delim">The delimiter character that will be used to split the string.</param>
             <param name="values">An array of values to be filled out from the parsed string.</param>
             <returns>Returns the number of values that were parsed.</returns>
             <remarks>

             <![CDATA[
             public static void Main()
            {
                // This is the string that we will decode to extract values from.
                // We are using an example GPS stream for this test.
                string gpss = "$GPGGA,,,092750.000,5321.6802,N,00630.3372,W,1,,,8,1.03,61.7,M,55.2,M,FFF,0.515151,,,,*76";
                byte[] gps = System.Text.UTF8Encoding.UTF8.GetBytes(gpss);

                // Our buffer to hold our line with comma separated values
                byte[] CSVLine = new byte[256];

                // Our list of values that we want filled in from the string.
                float[] values = new float[100];

                // Find the start of the line we care about.
                int lineStart = Array.IndexOf(gps, '$');
                int firstComma = Array.IndexOf(gps, ',', lineStart);

                // Skip the first comma
                firstComma++;

                // Find the end of the line that we care about.
                int lineEnd = Array.IndexOf(gps, '*', lineStart);
                int length = lineEnd - firstComma;

                // Copy the string from the first comma to the end of the line into the string we will pass in.
                Array.Copy(gps, firstComma, CSVLine, 0, length);

                // "CSVLine" now holds a single line of the length "length" and looks like this.
                // ,,092750.000,5321.6802,N,00630.3372,W,1,,,8,1.03,61.7,M,55.2,M,FFF,0.515151,,,,

                // An array of values will be extracted and put in the float array that we created and passed in.
                // in this example it use ',' but this can be anything!
                int floatCount = GHI.Premium.System.Util.SplitToArray(CSVLine, length, ',', values);
                /* from values above it will be
                 * values[0] = NaN; (not a number)
                 * values[1] = NaN; (not a number)
                 * values[2] = 092750.000;
                 * values[3] = 5321.6802;
                 * values[4] = (float)'N';
                 * ...etc.
                */

                // show the byte array
                string extracted = new string(System.Text.UTF8Encoding.UTF8.GetChars(CSVLine));

                //show the decoded values
                for (int i = 0; i < floatCount; i++)
                {
                    Debug.Print(values[i].ToString());

                    if (double.IsNaN(values[i]))
                        Debug.Print("Value[" + i + "] is a NaN!");
                }

                Debug.Print(extracted);

                Thread.Sleep(-1);

            ]]>

            </remarks>
        </member>
        <member name="T:GHI.Premium.System.Util.BPP_Type">

            Bits per pixel conversion type.

        </member>
        <member name="F:GHI.Premium.System.Util.BPP_Type.BPP1_x128">

            1 BPP for displays of 128 width and 128 or 64 height. The 1-bit pixel is set if the bitmap pixel has any color besides black.

        </member>
        <member name="F:GHI.Premium.System.Util.BPP_Type.BPP8_RGB">

            8 BPP with RGB 3:3:2.

        </member>
        <member name="F:GHI.Premium.System.Util.BPP_Type.BPP8_RED">

            8 BPP from red channel.

        </member>
        <member name="F:GHI.Premium.System.Util.BPP_Type.BPP8_GREEN">

            8 BPP from green channel.

        </member>
        <member name="F:GHI.Premium.System.Util.BPP_Type.BPP8_BLUE">

            8 BPP from blue channel.

        </member>
        <member name="F:GHI.Premium.System.Util.BPP_Type.BPP16_RGB_BE">

            Big Endian 16 BPP with RGB 5:6:5.

        </member>
        <member name="F:GHI.Premium.System.Util.BPP_Type.BPP16_RGB_LE">

            Little Endian 16 BPP with RGB 5:6:5.

        </member>
        <member name="F:GHI.Premium.System.Util.BPP_Type.BPP16_BGR_BE">

            Big Endian 16 BPP with BGR 5:6:5.

        </member>
        <member name="F:GHI.Premium.System.Util.BPP_Type.BPP16_BGR_LE">

            Little Endian 16 BPP with BGR 5:6:5.

        </member>
    </members>
</doc>


text:
/*eslint-disable no-magic-numbers*/
import React from "react";
import { storiesOf } from "@storybook/react";
import { VictoryErrorBar } from "../src/index";
import { VictoryTooltip, VictoryTheme } from "victory-core";
import { range } from "lodash";
import seedrandom from "seedrandom";
import { getChartDecorator } from "./decorators";

const getData = (num, symmetric, seed) => {
  seed = seed || "getData";
  const baseSeed = seedrandom(seed);
  const rand = () => baseSeed.quick() * 3;
  return range(num).map((v) => {
    return {
      x: v + 3,
      y: baseSeed.quick() * 20 + 5,
      errorX: symmetric ? rand() : [rand(), rand()],
      errorY: symmetric ? rand() : [rand(), rand()]
    };
  });
};

storiesOf("VictoryErrorBar", module)
  .add("default rendering", () => <VictoryErrorBar/>);

storiesOf("VictoryErrorBar.theme", module)
  .addDecorator(getChartDecorator({ theme: VictoryTheme.material }))
  .add("material theme", () => <VictoryErrorBar data={getData(5)}/>);
storiesOf("VictoryErrorBar.theme", module)
  .addDecorator(getChartDecorator({ theme: VictoryTheme.grayscale }))
  .add("grayscale (default) theme", () => <VictoryErrorBar data={getData(5)}/>);

storiesOf("VictoryErrorBar.borderWidth", module)
  .addDecorator(getChartDecorator({ domainPadding: 25 }))
  .add("borderWidth = 0", () => <VictoryErrorBar data={getData(5)} borderWidth={0}/>)
  .add("borderWidth = 10", () => <VictoryErrorBar data={getData(5)} borderWidth={10}/>);

storiesOf("VictoryErrorBar.data", module)
  .addDecorator(getChartDecorator({ domainPadding: 25 }))
  .add("with data accessors", () => {
    return (
      <VictoryErrorBar
        data={[
          { series: 1, value: 9, error: 3 },
          { series: 2, value: 80, error: 4 },
          { series: 3, value: 50, error: 8 },
          { series: 4, value: 70, error: 2 },
          { series: 5, value: 20, error: 3 }
        ]}
        x="series"
        y="value"
        errorY={(d) => ([d.error, d.error + 2])}
      />
    );
  });

storiesOf("VictoryErrorBar.labels", module)
  .addDecorator(getChartDecorator({ domainPadding: 25 }))
  .add("function labels", () => (
    <VictoryErrorBar data={getData(5)} labels={(d) => `x: ${d.x}`}/>
  ))
  .add("array labels", () => (
    <VictoryErrorBar data={getData(5)} labels={["", "", "three", "4"]}/>
  ))
  .add("data labels", () => (
    <VictoryErrorBar
      data={[
        { x: 1, y: 9, errorX: 0.3, errorY: 3, label: "first" },
        { x: 2, y: 80, errorX: 0.5, errorY: 2 },
        { x: 3, y: 50, errorX: 1.1, errorY: 2, label: "third" },
        { x: 4, y: 70, errorX: 0.2, errorY: 3 },
        { x: 5, y: 20, errorX: 0.3, errorY: 2, label: ["last", "label"] }
      ]}
    />
  ));

storiesOf("VictoryErrorBar.tooltips", module)
  .addDecorator(getChartDecorator({ domainPadding: 25 }))
  .add("tooltips", () => (
    <VictoryErrorBar
      data={getData(5)}
      labels={(d) => `x: ${d.x}`}
      labelComponent={<VictoryTooltip active/>}
    />
  ))
  .add("tooltips with long and short strings", () => (
    <VictoryErrorBar
      data={getData(5)}
      labels={["one", "two", 3, "wow, four tooltips", "five"]}
      labelComponent={<VictoryTooltip active/>}
    />
  ));

storiesOf("VictoryErrorBar.style", module)
  .addDecorator(getChartDecorator({ domainPadding: 25 }))
  .add("with styles", () => (
    <VictoryErrorBar
      data={getData(4)}
      labels={(d) => d.x}
      style={{
        labels: { fontSize: 20, fill: "tomato", fontFamily: "monospace" },
        data: { fill: "tomato", fillOpacity: 0.7, stroke: "tomato", strokeWidth: 2 }
      }}
    />
  ))
  .add("with functional styles", () => (
    <VictoryErrorBar
      style={{
        labels: {
          fill: (d) => d.errorX > d.errorY ? "red" : "black"
        },
        data: {
          stroke: (d) => d.errorX > d.errorY ? "red" : "black"
        }
      }}
      labels={(d) => d.x}
      data={getData(4, "symmetric")}
    />
  ));

redpajama_set_name: RedPajamaGithub


text:
package org.apache.jackrabbit.oak.segment;

import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;

/**
 * A record of type "BLOCK".
 */
class BlockRecord extends Record {

    private final int size;

    BlockRecord(RecordId id, int size) {
        super(id);
        this.size = size;
    }

    /**
     * Reads bytes from this block. Up to the given number of bytes are
     * read starting from the given position within this block. The number
     * of bytes read is returned.
     *
     * @param position position within this block
     * @param buffer target buffer
     * @param offset offset within the target buffer
     * @param length maximum number of bytes to read
     * @return number of bytes that could be read
     */
    public int read(int position, byte[] buffer, int offset, int length) {
        checkElementIndex(position, size);
        checkNotNull(buffer);
        checkPositionIndexes(offset, offset + length, buffer.length);

        if (position + length > size) {
            length = size - position;
        }
        if (length > 0) {
            getSegment().readBytes(getOffset(position), buffer, offset, length);
        }
        return length;
    }

}


text:
/* === Check Button Rtl ==*/
.duiListItemRtl .duiDomButtonWhiteCheck > div,
.duiListItemRtl .duiDomButtonCheck > div {
  right: 0px;
  -webkit-transform: scaleX(-0.7) rotate(-135deg);
  transform: scaleX(-0.7) rotate(-135deg);
  border-width: 3px 0px 0px 4px;
}


text:
/**
 * Autogenerated by Thrift
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
#include "module_fatal_constant.h"

namespace test_cpp2 { namespace cpp_reflection {

}} // test_cpp2::cpp_reflection


text:
published: true
title: Hunters vs. Farmers in IT Professions
layout: post
---
You should look at the Wikipedia article:

[Hunter vs Farmer Hypothesis](https://en.wikipedia.org/wiki/Hunter_vs._farmer_hypothesis/)

Really good software developers are Farmers.

Really good software support and maintenance technicians are Hunters.

Superprogrammers have traits of both Hunters and Farmers.

I'm a really good support guy.

I'm in awe of Superprogrammers.

Truth be known, I've not run into many Superprogrammers in the Fortune 500 IT world.  I've seen a couple, but generally their output was way over the heads of their colleagues, and way beyond the ability of a non-software business to maintain long-term -- for the most part Superprogrammers don't want to go to work for non-software industry organizations, and don't want to be in creativity-suppressing big organizations.  Superprogrammers created cool stuff, then left, and eventually their neat output replaced with out of the box software, as software vendors caught up with a need and filled it.

In addition to Superprogrammers, since doing the bits of freelancing that I've done, I've run across a super-set of that class:  The Super-Individuals.  ... Midas-touch people, who become acknowledged experts at everything they touch, make lots of money and/or have lots of freedom, and are entertaining and articulate in conversation.  Damn.  More than in awe of them:  Are those folks even the same species that I am?  Nonetheless, I always feel blessed when coming into contact with someone like that; glad to have the opportunity to see what the human spirit can create given a good attitude and a bit of luck (which admittedly might include luck of the draw in the genetic pool...)


text:
package com.cloudray.scalapress.search

import org.scalatest.{OneInstancePerTest, FunSuite}
import org.scalatest.mock.MockitoSugar
import javax.servlet.http.HttpServletRequest
import com.cloudray.scalapress.item.{ItemDao, Item}
import org.mockito.{Matchers, Mockito}
import com.cloudray.scalapress.search.widget.SearchResultsWidget
import com.cloudray.scalapress.framework.{ScalapressRequest, ScalapressContext}

/** @author Stephen Samuel */
class SearchResultsWidgetTest extends FunSuite with MockitoSugar with OneInstancePerTest {

  val section = new SearchResultsWidget
  val req = mock[HttpServletRequest]
  val context = new ScalapressContext
  context.searchService = mock[SearchService]
  context.itemDao = mock[ItemDao]

  val obj1 = new Item
  obj1.name = "michael"
  obj1.status = Item.STATUS_LIVE
  obj1.id = 1

  val obj2 = new Item
  obj2.name = "april"
  obj2.status = Item.STATUS_LIVE
  obj2.id = 2

  val obj3 = new Item
  obj3.name = "devon"
  obj3.status = Item.STATUS_LIVE
  obj3.id = 3

  val ref1 = ItemRef(obj1.id, 55, obj1.name, Item.STATUS_LIVE, Map.empty, Nil)
  val ref2 = ItemRef(obj2.id, 55, obj2.name, Item.STATUS_LIVE, Map.empty, Nil)
  val ref3 = ItemRef(obj3.id, 55, obj3.name, Item.STATUS_LIVE, Map.empty, Nil)

  val sreq = ScalapressRequest(req, context)
  section.search = new SavedSearch

  test("that the bulk loaded objects should use the same ordering as the search results") {

    val sortedObjs = Seq(obj1, obj2, obj3)
    val sortedRefs = Seq(ref2, ref3, ref1)
    val result = SearchResult(sortedRefs)

    // search returns sorted refs
    Mockito.when(context.searchService.search(Search(section.search))).thenReturn(result)
    // bulk dao method returns them in id order
    Mockito.when(context.itemDao.findBulk(Matchers.any[Seq[Long]])).thenReturn(sortedObjs)

    // test should be that they are re-ordered back to the sorted refs order
    val expected = Seq(obj2, obj3, obj1)
    val actual = section._objects(sreq)
    assert(expected === actual)
  }
}


text:
package fr.liglab.adele.cream.runtime.internal.factories;

import fr.liglab.adele.cream.annotations.entity.ContextEntity;
import fr.liglab.adele.cream.utils.CreamGenerator;
import fr.liglab.adele.cream.utils.CreamProxyFactory;
import fr.liglab.adele.cream.utils.GeneratedDelegatorProxy;
import org.apache.felix.ipojo.ComponentFactory;
import org.apache.felix.ipojo.HandlerManager;
import org.apache.felix.ipojo.InstanceManager;
import org.osgi.framework.BundleContext;

import java.lang.reflect.Method;
import java.util.*;

/**
 * Created by aygalinc on 31/05/16.
 */
public class ContextEntityInstanceManager extends InstanceManager implements CreamGenerator {

    private final CreamProxyFactory creamProxyFactory = new CreamProxyFactory(this.getClass().getClassLoader(), this);

    private Map<Method, GeneratedDelegatorProxy> proxyDelegatorMap = new HashMap<>();

    /**
     * Creates a new Component Manager.
     * The instance is not initialized.
     *
     * @param factory  the factory managing the instance manager
     * @param context  the bundle context to give to the instance
     * @param handlers handler object array
     */
    public ContextEntityInstanceManager(ComponentFactory factory, BundleContext context, HandlerManager[] handlers) {
        super(factory, context, handlers);

    }

    public Map<Method, GeneratedDelegatorProxy> getProxyDelegationMap() {
        if (proxyDelegatorMap.isEmpty()) {
            Class clazz = getClazz();
            ContextEntity[] contextEntities = (ContextEntity[]) clazz.getAnnotationsByType(ContextEntity.class);
            for (ContextEntity entity : contextEntities) {
                Class[] entityClass = entity.coreServices();
                Set<Class> classesFlatten = flattenClass(entityClass);
                proxyDelegatorMap = ProxyGeneratorUtils.getGeneratedProxyByMethodMap(classesFlatten, creamProxyFactory);
            }
        }
        return proxyDelegatorMap;
    }

    private Set<Class> flattenClass(Class[] classes) {
        Set<Class> classSet = new HashSet<>();

        for (Class clazz : classes) {
            boolean put = true;
            List<Class> classesToRemove = new ArrayList<>();
            for (Class classOfSet : classSet) {
                if (clazz.isAssignableFrom(classOfSet)) {
                    put = false;
                }
                if (classOfSet.isAssignableFrom(clazz) && !(classOfSet.equals(clazz))) {
                    classesToRemove.add(classOfSet);
                }
            }

            if (put) {
                classSet.add(clazz);
            }
            for (Class classToRemove : classesToRemove) {
                classSet.remove(classToRemove);
            }
        }
        return classSet;
    }
}


text:
<?php

namespace Google\AdsApi\AdManager\v202205;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class RefreshType
{
    const AUTOMATIC = 'AUTOMATIC';
    const MANUAL = 'MANUAL';
    const UNKNOWN = 'UNKNOWN';

}


text:
package com.russo_oppido_marzucco.sweng.smartgreenhouse;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;

public class DeviceList extends ActionBarActivity
{

    Button btnPaired;
    ListView devicelist;

     public static BluetoothAdapter myBluetooth = null;
    private Set<BluetoothDevice> pairedDevices;
    public static String EXTRA_ADDRESS = "device_address";

    Context context;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_list);
        context=getApplicationContext();

        btnPaired = (Button)findViewById(R.id.button);

        devicelist = (ListView)findViewById(R.id.listView);

        myBluetooth = BluetoothAdapter.getDefaultAdapter();

        if(myBluetooth == null)
        {
            Toast.makeText(getApplicationContext(), "Dispositivo Bluetooth non disponibile!", Toast.LENGTH_LONG).show();
            finish();
        }
        else if(!myBluetooth.isEnabled())
        {
            Intent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(turnBTon,1);
        }

        btnPaired.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                pairedDevicesList();
            }
        });

    }

    private void pairedDevicesList()
    {
        pairedDevices = myBluetooth.getBondedDevices();
        ArrayList list = new ArrayList();

        if (pairedDevices.size()>0)
        {
            for(BluetoothDevice bt : pairedDevices)
            {
                list.add(bt.getName() + "\n" + bt.getAddress());
            }
        }
        else
        {
            Toast.makeText(getApplicationContext(), "Nessun dispositivo accoppiato trovato!", Toast.LENGTH_LONG).show();
        }

        final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
        devicelist.setAdapter(adapter);
        devicelist.setOnItemClickListener(myListClickListener);
    }

    private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener()
    {
        public void onItemClick (AdapterView<?> av, View v, int arg2, long arg3)
        {
            String info = ((TextView) v).getText().toString();
            String address = info.substring(info.length() - 17);

                    Intent i = new Intent(DeviceList.this, Dati.class);
                    i.putExtra(EXTRA_ADDRESS, address);
                    startActivity(i);
            finish();

        }
    };

}


text:
import time
from ConfigParser import ConfigParser
from syslog import syslog

import pika

from codinghyde.enigma.messages import service_pb2

class EnigmaService(object):
    domain = 'codinghyde.enigma'
    name = '__service__'

    def __init__(self, config, root, daemon):
        self.config = ConfigParser()
        self.config.read(config)
        self.root = root
        self.daemon = daemon
        self.service = self.domain + '.' + self.name
    def start(self):
        syslog("Starting service...")

        # Connect to broker
        self.connection = pika.BlockingConnection(
            pika.ConnectionParameters('localhost', virtual_host='/enigma'))
        self.channel = self.connection.channel()

        # Service-specific initialization
        self._start()

        # Setup service control queue
        self.channel.exchange_declare(exchange='service', type='topic')
        result = self.channel.queue_declare(exclusive=True, auto_delete=True)
        name = result.method.queue
        self.channel.queue_bind(exchange='service', queue=name,
                                routing_key=self.service)
        self.channel.queue_bind(exchange='service', queue=name,
                                routing_key='all')
        self.channel.queue_bind(exchange='service', queue=name,
                                routing_key=self.domain + '.#')
        self.channel.basic_consume(self._service_control, queue=name,
                                   no_ack=True)

        # Clients exchange
        self.channel.exchange_declare(exchange='client', type='direct')

        # Uptime
        self.start_time = time.time()

        # Done
        syslog("Service ready.")
        self.channel.start_consuming()

    def stop(self):
        syslog("Stopping service...")

        # Service-specific shutdown
        self._stop()

        # Stop AMQP client
        self.channel.stop_consuming()

    def _start(self):
        pass    # Override me

    def _stop(self):
        pass    # Override me

    def _service_control(self, channel, method, properties, body):
        request = service_pb2.ServiceRequest()
        request.ParseFromString(body)

        response = service_pb2.ServiceResponse()
        response.type = service_pb2.PING
        response.name = self.service

        stop = False
        if request.type == service_pb2.PING:
            syslog("Received PING request from client '{0}'." \
                   .format(request.client))
            response.status = service_pb2.SUCCESS
        elif request.type == service_pb2.STOP:
            syslog("Received STOP request from client '{0}'." \
                   .format(request.client))
            response.status = service_pb2.SUCCESS
            stop = True
        elif request.type == service_pb2.RESTART:
            response.status = service_pb2.ERROR;
            response.error = "Operation Not Supported";

        response.uptime = int(time.time() - self.start_time)

        self.channel.basic_publish(exchange='client',
                                   routing_key=request.client+'.status',
                                   body=response.SerializeToString())

        if stop:
            self.stop()


text:
using System.Threading.Tasks;
using CompaniesHouse.Response.CompanyFiling;
using NUnit.Framework;

namespace CompaniesHouse.IntegrationTests.Tests.CompanyFilingHistoryTests
{
    [TestFixture]
    public class FilingHistoryByTransactionIdTestsInvalid : CompanyFilingHistoryTestBase
    {
        private const string InvalidCompanyNumber = "ABC00000";
        private const string InvalidTransactionId = "00000000";

        private CompaniesHouseClientResponse<FilingHistoryItem> _result;

        protected override async Task When()
        {
            await WhenRetrievingAnCompanyFilingHistoryForAnInvalidCompany()
                .ConfigureAwait(false);
        }

        [Test]
        public void ThenTheDataItemsAreNull()
        {
            Assert.That(_result.Data, Is.Null);
        }

        private async Task WhenRetrievingAnCompanyFilingHistoryForAnInvalidCompany()
        {
            _result = await _client.GetFilingHistoryByTransactionAsync(InvalidCompanyNumber, InvalidTransactionId)
                .ConfigureAwait(false);
        }
    }
}


text:
require 'tempfile'
require 'forwardable'
require "rubygems/package"

module Bringit
  class Repository
    include Bringit::Popen

    SEARCH_CONTEXT_LINES = 3

    NoRepository = Class.new(StandardError)
    InvalidBlobName = Class.new(StandardError)
    InvalidRef = Class.new(StandardError)

    # Full path to repo
    attr_reader :path

    # Directory name of repo
    attr_reader :name

    # Rugged repo object
    attr_reader :rugged

    # 'path' must be the path to a _bare_ git repository, e.g.
    # /path/to/my-repo.git
    def initialize(path)
      @path = path
      @name = path.split("/").last
      @attributes = Bringit::Attributes.new(path)
    end

    delegate  :empty?,
              :bare?,
              to: :rugged

    # Default branch in the repository
    def root_ref
      @root_ref ||= discover_default_branch
    end

    # Alias to old method for compatibility
    def raw
      rugged
    end

    def rugged
      @rugged ||= Rugged::Repository.new(path)
    rescue Rugged::RepositoryError, Rugged::OSError
      raise NoRepository.new('no repository for such path')
    end

    # Returns an Array of branch names
    # sorted by name ASC
    def branch_names
      branches.map(&:name)
    end

    # Returns an Array of Branches
    def branches
      rugged.branches.map do |rugged_ref|
        begin
          Bringit::Branch.new(self, rugged_ref.name, rugged_ref.target)
        rescue Rugged::ReferenceError
          # Omit invalid branch
        end
      end.compact.sort_by(&:name)
    end

    def reload_rugged
      @rugged = nil
    end

    # Directly find a branch with a simple name (e.g. master)
    #
    # force_reload causes a new Rugged repository to be instantiated
    #
    # This is to work around a bug in libgit2 that causes in-memory refs to
    # be stale/invalid when packed-refs is changed.
    # See https://gitlab.com/gitlab-org/gitlab-ce/issues/15392#note_14538333
    def find_branch(name, force_reload = false)
      reload_rugged if force_reload

      rugged_ref = rugged.branches[name]
      Bringit::Branch.new(self, rugged_ref.name, rugged_ref.target) if rugged_ref
    end

    def local_branches
      rugged.branches.each(:local).map do |branch|
        Bringit::Branch.new(self, branch.name, branch.target)
      end
    end

    # Returns the number of valid branches
    def branch_count
      rugged.branches.count do |ref|
        begin
          ref.name && ref.target # ensures the branch is valid

          true
        rescue Rugged::ReferenceError
          false
        end
      end
    end

    # Returns an Array of tag names
    def tag_names
      rugged.tags.map { |t| t.name }
    end

    # Returns an Array of Tags
    def tags
      rugged.references.each("refs/tags/*").map do |ref|
        message = nil

        if ref.target.is_a?(Rugged::Tag::Annotation)
          tag_message = ref.target.message

          if tag_message.respond_to?(:chomp)
            message = tag_message.chomp
          end
        end

        Bringit::Tag.new(self, ref.name, ref.target, message)
      end.sort_by(&:name)
    end

    # Returns true if the given tag exists
    #
    # name - The name of the tag as a String.
    def tag_exists?(name)
      !!rugged.tags[name]
    end

    # Returns true if the given branch exists
    #
    # name - The name of the branch as a String.
    def branch_exists?(name)
      rugged.branches.exists?(name)

    # If the branch name is invalid (e.g. ".foo") Rugged will raise an error.
    # Whatever code calls this method shouldn't have to deal with that so
    # instead we just return `false` (which is true since a branch doesn't
    # exist when it has an invalid name).
    rescue Rugged::ReferenceError
      false
    end

    # Returns an Array of branch and tag names
    def ref_names
      branch_names + tag_names
    end

    # Deprecated. Will be removed in 5.2
    def heads
      rugged.references.each("refs/heads/*").map do |head|
        Bringit::Ref.new(self, head.name, head.target)
      end.sort_by(&:name)
    end

    def has_commits?
      !empty?
    end

    def repo_exists?
      !!rugged
    end

    # Discovers the default branch based on the repository's available branches
    #
    # - If no branches are present, returns nil
    # - If one branch is present, returns its name
    # - If two or more branches are present, returns current HEAD or master or first branch
    def discover_default_branch
      names = branch_names

      return if names.empty?

      return names[0] if names.length == 1

      if rugged_head
        extracted_name = Ref.extract_branch_name(rugged_head.name)

        return extracted_name if names.include?(extracted_name)
      end

      if names.include?('master')
        'master'
      else
        names[0]
      end
    end

    def rugged_head
      rugged.head
    rescue Rugged::ReferenceError
      nil
    end

    def archive_prefix(ref, sha)
      project_name = self.name.chomp('.git')
      "#{project_name}-#{ref.tr('/', '-')}-#{sha}"
    end

    def archive_metadata(ref, storage_path, format = "tar.gz")
      ref ||= root_ref
      commit = Bringit::Commit.find(self, ref)
      return {} if commit.nil?

      prefix = archive_prefix(ref, commit.id)

      {
        'RepoPath' => path,
        'ArchivePrefix' => prefix,
        'ArchivePath' => archive_file_path(prefix, storage_path, format),
        'CommitId' => commit.id,
      }
    end

    def archive_file_path(name, storage_path, format = "tar.gz")
      # Build file path
      return nil unless name

      extension =
        case format
        when "tar.bz2", "tbz", "tbz2", "tb2", "bz2"
          "tar.bz2"
        when "tar"
          "tar"
        when "zip"
          "zip"
        else
          # everything else should fall back to tar.gz
          "tar.gz"
        end

      file_name = "#{name}.#{extension}"
      File.join(storage_path, self.name, file_name)
    end

    # Return repo size in megabytes
    def size
      size = Bringit::Popen.popen(%w(du -sk), path).first.strip.to_i
      (size.to_f / 1024).round(2)
    end

    # Returns an array of BlobSnippets for files at the specified +ref+ that
    # contain the +query+ string.
    def search_files(query, ref = nil)
      greps = []
      ref ||= root_ref

      populated_index(ref).each do |entry|
        # Discard submodules
        next if submodule?(entry)

        blob = Bringit::Blob.raw(self, entry[:oid])

        # Skip binary files
        next if blob.data.encoding == Encoding::ASCII_8BIT

        blob.load_all_data!
        greps += build_greps(blob.data, query, ref, entry[:path])
      end

      greps
    end

    # Use the Rugged Walker API to build an array of commits.
    #
    # Usage.
    #   repo.log(
    #     ref: 'master',
    #     path: 'app/models',
    #     limit: 10,
    #     offset: 5,
    #     after: Time.new(2016, 4, 21, 14, 32, 10)
    #   )
    #
    def log(options)
      default_options = {
        limit: 10,
        offset: 0,
        path: nil,
        follow: false,
        skip_merges: false,
        disable_walk: false,
        after: nil,
        before: nil,
        unsafe_range: false,
      }

      options = default_options.merge(options)
      options[:limit] ||= 0
      options[:offset] ||= 0
      actual_ref = options[:ref] || root_ref

      if options[:unsafe_range]
        log_by_shell(actual_ref, options)
      else
        begin
          sha = sha_from_ref(actual_ref)
        rescue Rugged::OdbError, Rugged::InvalidError, Rugged::ReferenceError
          # Return an empty array if the ref wasn't found
          return []
        end
        if log_using_shell?(options)
          log_by_shell(sha, options)
        else
          log_by_walk(sha, options)
        end
      end
    end

    def log_using_shell?(options)
      options[:path].present? ||
        options[:disable_walk] ||
        options[:skip_merges] ||
        options[:after] ||
        options[:before]
    end

    def log_by_walk(sha, options)
      walk_options = {
        show: sha,
        sort: Rugged::SORT_TOPO,
        limit: options[:limit],
        offset: options[:offset]
      }
      commits = Rugged::Walker.walk(rugged, walk_options).to_a
      if options[:only_commit_sha]
        commits.map(&:oid)
      else
        commits
      end
    end

    def log_by_shell(sha, options)
      limit = options[:limit].to_i
      offset = options[:offset].to_i
      use_follow_flag = options[:follow] && options[:path].present?

      # We will perform the offset in Ruby because --follow doesn't play well with --skip.
      # See: https://gitlab.com/gitlab-org/gitlab-ce/issues/3574#note_3040520
      offset_in_ruby = use_follow_flag && options[:offset].present?
      limit += offset if offset_in_ruby

      cmd = %W[git --git-dir=#{path} log]
      cmd << "--max-count=#{limit}" if limit > 0
      cmd << '--format=%H'
      cmd << "--skip=#{offset}" unless offset_in_ruby
      cmd << '--follow' if use_follow_flag
      cmd << '--no-merges' if options[:skip_merges]
      cmd << "--after=#{options[:after].iso8601}" if options[:after]
      cmd << "--before=#{options[:before].iso8601}" if options[:before]
      cmd << sha
      if options[:path].present?
        cmd += %W[-- #{options[:path].sub(%r{\A/*}, './')}]
      end

      raw_output = IO.popen(cmd) { |io| io.read }
      lines = offset_in_ruby ? raw_output.lines.drop(offset) : raw_output.lines

      if options[:only_commit_sha]
        lines.map(&:strip)
      else
        lines.map! { |c| Rugged::Commit.new(rugged, c.strip) }
      end
    end

    def count_commits(options)
      cmd = %W[git --git-dir=#{path} rev-list]
      cmd << "--after=#{options[:after].iso8601}" if options[:after]
      cmd << "--before=#{options[:before].iso8601}" if options[:before]
      cmd += %W[--count #{options[:ref]}]
      cmd += %W[-- #{options[:path]}] if options[:path].present?

      raw_output = IO.popen(cmd) { |io| io.read }

      raw_output.to_i
    end

    def sha_from_ref(ref)
      rev_parse_target(ref).oid
    end

    # Return the object that +revspec+ points to.  If +revspec+ is an
    # annotated tag, then return the tag's target instead.
    def rev_parse_target(revspec)
      obj = rugged.rev_parse(revspec)
      Ref.dereference_object(obj)
    end

    # Return a collection of Rugged::Commits between the two revspec arguments.
    # See http://git-scm.com/docs/git-rev-parse.html#_specifying_revisions for
    # a detailed list of valid arguments.
    def commits_between(from, to)
      walker = Rugged::Walker.new(rugged)
      walker.sorting(Rugged::SORT_TOPO | Rugged::SORT_REVERSE)

      sha_from = sha_from_ref(from)
      sha_to = sha_from_ref(to)

      walker.push(sha_to)
      walker.hide(sha_from)

      commits = walker.to_a
      walker.reset

      commits
    end

    # Counts the amount of commits between `from` and `to`.
    def count_commits_between(from, to)
      commits_between(from, to).size
    end

    # Returns the SHA of the most recent common ancestor of +from+ and +to+
    def merge_base_commit(from, to)
      rugged.merge_base(from, to)
    end

    # Return an array of Diff objects that represent the diff
    # between +from+ and +to+.  See Diff::filter_diff_options for the allowed
    # diff options.  The +options+ hash can also include :break_rewrites to
    # split larger rewrites into delete/add pairs.
    def diff(from, to, options = {}, *paths)
      Bringit::DiffCollection.new(diff_patches(from, to, options, *paths), options)
    end

    # Returns commits collection
    #
    # Ex.
    #   repo.find_commits(
    #     ref: 'master',
    #     max_count: 10,
    #     skip: 5,
    #     order: :date
    #   )
    #
    #   +options+ is a Hash of optional arguments to git
    #     :ref is the ref from which to begin (SHA1 or name)
    #     :contains is the commit contained by the refs from which to begin (SHA1 or name)
    #     :max_count is the maximum number of commits to fetch
    #     :skip is the number of commits to skip
    #     :order is the commits order and allowed value is :date(default) or :topo
    #
    def find_commits(options = {})
      actual_options = options.dup

      allowed_options = [:ref, :max_count, :skip, :contains, :order]

      actual_options.keep_if do |key|
        allowed_options.include?(key)
      end

      default_options = { skip: 0 }
      actual_options = default_options.merge(actual_options)

      walker = Rugged::Walker.new(rugged)

      if actual_options[:ref]
        walker.push(rugged.rev_parse_oid(actual_options[:ref]))
      elsif actual_options[:contains]
        branches_contains(actual_options[:contains]).each do |branch|
          walker.push(branch.target_id)
        end
      else
        rugged.references.each("refs/heads/*") do |ref|
          walker.push(ref.target_id)
        end
      end

      if actual_options[:order] == :topo
        walker.sorting(Rugged::SORT_TOPO)
      else
        walker.sorting(Rugged::SORT_DATE)
      end

      commits = []
      offset = actual_options[:skip]
      limit = actual_options[:max_count]
      walker.each(offset: offset, limit: limit) do |commit|
        bringit_commit = Bringit::Commit.decorate(commit, self)
        commits.push(bringit_commit)
      end

      walker.reset

      commits
    rescue Rugged::OdbError
      []
    end

    # Returns branch names collection that contains the special commit(SHA1
    # or name)
    #
    # Ex.
    #   repo.branch_names_contains('master')
    #
    def branch_names_contains(commit)
      branches_contains(commit).map { |c| c.name }
    end

    # Returns branch collection that contains the special commit(SHA1 or name)
    #
    # Ex.
    #   repo.branch_names_contains('master')
    #
    def branches_contains(commit)
      commit_obj = rugged.rev_parse(commit)
      parent = commit_obj.parents.first unless commit_obj.parents.empty?

      walker = Rugged::Walker.new(rugged)

      rugged.branches.select do |branch|
        walker.push(branch.target_id)
        walker.hide(parent) if parent
        result = walker.any? { |c| c.oid == commit_obj.oid }
        walker.reset

        result
      end
    end

    # Get refs hash which key is SHA1
    # and value is a Rugged::Reference
    def refs_hash
      # Initialize only when first call
      if @refs_hash.nil?
        @refs_hash = Hash.new { |h, k| h[k] = [] }

        rugged.references.each do |r|
          # Symbolic/remote references may not have an OID; skip over them
          target_oid = r.target.try(:oid)
          if target_oid
            sha = rev_parse_target(target_oid).oid
            @refs_hash[sha] << r
          end
        end
      end
      @refs_hash
    end

    # Lookup for rugged object by oid or ref name
    def lookup(oid_or_ref_name)
      rugged.rev_parse(oid_or_ref_name)
    end

    # Return hash with submodules info for this repository
    #
    # Ex.
    #   {
    #     "rack"  => {
    #       "id" => "c67be4624545b4263184c4a0e8f887efd0a66320",
    #       "path" => "rack",
    #       "url" => "git://github.com/chneukirchen/rack.git"
    #     },
    #     "encoding" => {
    #       "id" => ....
    #     }
    #   }
    #
    def submodules(ref)
      commit = rev_parse_target(ref)
      return {} unless commit

      begin
        content = blob_content(commit, ".gitmodules")
      rescue InvalidBlobName
        return {}
      end

      parse_gitmodules(commit, content)
    end

    # Return total commits count accessible from passed ref
    def commit_count(ref)
      walker = Rugged::Walker.new(rugged)
      walker.sorting(Rugged::SORT_TOPO | Rugged::SORT_REVERSE)
      oid = rugged.rev_parse_oid(ref)
      walker.push(oid)
      walker.count
    end

    # Sets HEAD to the commit specified by +ref+; +ref+ can be a branch or
    # tag name or a commit SHA.  Valid +reset_type+ values are:
    #
    #  [:soft]
    #    the head will be moved to the commit.
    #  [:mixed]
    #    will trigger a +:soft+ reset, plus the index will be replaced
    #    with the content of the commit tree.
    #  [:hard]
    #    will trigger a +:mixed+ reset and the working directory will be
    #    replaced with the content of the index. (Untracked and ignored files
    #    will be left alone)
    delegate :reset, to: :rugged

    # Mimic the `git clean` command and recursively delete untracked files.
    # Valid keys that can be passed in the +options+ hash are:
    #
    # :d - Remove untracked directories
    # :f - Remove untracked directories that are managed by a different
    #      repository
    # :x - Remove ignored files
    #
    # The value in +options+ must evaluate to true for an option to take
    # effect.
    #
    # Examples:
    #
    #   repo.clean(d: true, f: true) # Enable the -d and -f options
    #
    #   repo.clean(d: false, x: true) # -x is enabled, -d is not
    def clean(options = {})
      strategies = [:remove_untracked]
      strategies.push(:force) if options[:f]
      strategies.push(:remove_ignored) if options[:x]

      # TODO: implement this method
    end

    # Check out the specified ref. Valid options are:
    #
    #  :b - Create a new branch at +start_point+ and set HEAD to the new
    #       branch.
    #
    #  * These options are passed to the Rugged::Repository#checkout method:
    #
    #  :progress ::
    #    A callback that will be executed for checkout progress notifications.
    #    Up to 3 parameters are passed on each execution:
    #
    #    - The path to the last updated file (or +nil+ on the very first
    #      invocation).
    #    - The number of completed checkout steps.
    #    - The number of total checkout steps to be performed.
    #
    #  :notify ::
    #    A callback that will be executed for each checkout notification
    #    types specified with +:notify_flags+. Up to 5 parameters are passed
    #    on each execution:
    #
    #    - An array containing the +:notify_flags+ that caused the callback
    #      execution.
    #    - The path of the current file.
    #    - A hash describing the baseline blob (or +nil+ if it does not
    #      exist).
    #    - A hash describing the target blob (or +nil+ if it does not exist).
    #    - A hash describing the workdir blob (or +nil+ if it does not
    #      exist).
    #
    #  :strategy ::
    #    A single symbol or an array of symbols representing the strategies
    #    to use when performing the checkout. Possible values are:
    #
    #    :none ::
    #      Perform a dry run (default).
    #
    #    :safe ::
    #      Allow safe updates that cannot overwrite uncommitted data.
    #
    #    :safe_create ::
    #      Allow safe updates plus creation of missing files.
    #
    #    :force ::
    #      Allow all updates to force working directory to look like index.
    #
    #    :allow_conflicts ::
    #      Allow checkout to make safe updates even if conflicts are found.
    #
    #    :remove_untracked ::
    #      Remove untracked files not in index (that are not ignored).
    #
    #    :remove_ignored ::
    #      Remove ignored files not in index.
    #
    #    :update_only ::
    #      Only update existing files, don't create new ones.
    #
    #    :dont_update_index ::
    #      Normally checkout updates index entries as it goes; this stops
    #      that.
    #
    #    :no_refresh ::
    #      Don't refresh index/config/etc before doing checkout.
    #
    #    :disable_pathspec_match ::
    #      Treat pathspec as simple list of exact match file paths.
    #
    #    :skip_locked_directories ::
    #      Ignore directories in use, they will be left empty.
    #
    #    :skip_unmerged ::
    #      Allow checkout to skip unmerged files (NOT IMPLEMENTED).
    #
    #    :use_ours ::
    #      For unmerged files, checkout stage 2 from index (NOT IMPLEMENTED).
    #
    #    :use_theirs ::
    #      For unmerged files, checkout stage 3 from index (NOT IMPLEMENTED).
    #
    #    :update_submodules ::
    #      Recursively checkout submodules with same options (NOT
    #      IMPLEMENTED).
    #
    #    :update_submodules_if_changed ::
    #      Recursively checkout submodules if HEAD moved in super repo (NOT
    #      IMPLEMENTED).
    #
    #  :disable_filters ::
    #    If +true+, filters like CRLF line conversion will be disabled.
    #
    #  :dir_mode ::
    #    Mode for newly created directories. Default: +0755+.
    #
    #  :file_mode ::
    #    Mode for newly created files. Default: +0755+ or +0644+.
    #
    #  :file_open_flags ::
    #    Mode for opening files. Default:
    #    <code>IO::CREAT | IO::TRUNC | IO::WRONLY</code>.
    #
    #  :notify_flags ::
    #    A single symbol or an array of symbols representing the cases in
    #    which the +:notify+ callback should be invoked. Possible values are:
    #
    #    :none ::
    #      Do not invoke the +:notify+ callback (default).
    #
    #    :conflict ::
    #      Invoke the callback for conflicting paths.
    #
    #    :dirty ::
    #      Invoke the callback for "dirty" files, i.e. those that do not need
    #      an update but no longer match the baseline.
    #
    #    :updated ::
    #      Invoke the callback for any file that was changed.
    #
    #    :untracked ::
    #      Invoke the callback for untracked files.
    #
    #    :ignored ::
    #      Invoke the callback for ignored files.
    #
    #    :all ::
    #      Invoke the callback for all these cases.
    #
    #  :paths ::
    #    A glob string or an array of glob strings specifying which paths
    #    should be taken into account for the checkout operation. +nil+ will
    #    match all files.  Default: +nil+.
    #
    #  :baseline ::
    #    A Rugged::Tree that represents the current, expected contents of the
    #    workdir.  Default: +HEAD+.
    #
    #  :target_directory ::
    #    A path to an alternative workdir directory in which the checkout
    #    should be performed.
    def checkout(ref, options = {}, start_point = "HEAD")
      if options[:b]
        rugged.branches.create(ref, start_point)
        options.delete(:b)
      end
      default_options = { strategy: [:recreate_missing, :safe] }
      rugged.checkout(ref, default_options.merge(options))
    end

    # Delete the specified branch from the repository
    def delete_branch(branch_name)
      rugged.branches.delete(branch_name)
    end

    # Create a new branch named **ref+ based on **stat_point+, HEAD by default
    #
    # Examples:
    #   create_branch("feature")
    #   create_branch("other-feature", "master")
    def create_branch(ref, start_point = "HEAD")
      rugged_ref = rugged.branches.create(ref, start_point)
      Bringit::Branch.new(self, rugged_ref.name, rugged_ref.target)
    rescue Rugged::ReferenceError => e
      raise InvalidRef.new("Branch #{ref} already exists") if e.to_s =~ /'refs\/heads\/#{ref}'/
      raise InvalidRef.new("Invalid reference #{start_point}")
    end

    # Return an array of this repository's remote names
    def remote_names
      rugged.remotes.each_name.to_a
    end

    # Delete the specified remote from this repository.
    def remote_delete(remote_name)
      rugged.remotes.delete(remote_name)
    end

    # Add a new remote to this repository.  Returns a Rugged::Remote object
    def remote_add(remote_name, url)
      rugged.remotes.create(remote_name, url)
    end

    # Update the specified remote using the values in the +options+ hash
    #
    # Example
    # repo.update_remote("origin", url: "path/to/repo")
    def remote_update(remote_name, options = {})
      # TODO: Implement other remote options
      rugged.remotes.set_url(remote_name, options[:url]) if options[:url]
    end

    # Fetch the specified remote
    def fetch(remote_name)
      rugged.remotes[remote_name].fetch
    end

    # Push +*refspecs+ to the remote identified by +remote_name+.
    def push(remote_name, *refspecs)
      rugged.remotes[remote_name].push(refspecs)
    end

    # Merge the +source_name+ branch into the +target_name+ branch. This is
    # equivalent to `git merge --no_ff +source_name+`, since a merge commit
    # is always created.
    def merge(source_name, target_name, options = {})
      our_commit = rugged.branches[target_name].target
      their_commit = rugged.branches[source_name].target

      raise "Invalid merge target" if our_commit.nil?
      raise "Invalid merge source" if their_commit.nil?

      merge_index = rugged.merge_commits(our_commit, their_commit)
      return false if merge_index.conflicts?

      actual_options = options.merge(
        parents: [our_commit, their_commit],
        tree: merge_index.write_tree(rugged),
        update_ref: "refs/heads/#{target_name}"
      )
      Rugged::Commit.create(rugged, actual_options)
    end

    def commits_since(from_date)
      walker = Rugged::Walker.new(rugged)
      walker.sorting(Rugged::SORT_DATE | Rugged::SORT_REVERSE)

      rugged.references.each("refs/heads/*") do |ref|
        walker.push(ref.target_id)
      end

      commits = []
      walker.each do |commit|
        break if commit.author[:time].to_date < from_date
        commits.push(commit)
      end

      commits
    end

    AUTOCRLF_VALUES = {
      "true" => true,
      "false" => false,
      "input" => :input
    }.freeze

    def autocrlf
      AUTOCRLF_VALUES[rugged.config['core.autocrlf']]
    end

    def autocrlf=(value)
      rugged.config['core.autocrlf'] = AUTOCRLF_VALUES.invert[value]
    end

    # Returns result like "git ls-files" , recursive and full file path
    #
    # Ex.
    #   repo.ls_files('master')
    #
    def ls_files(ref)
      actual_ref = ref || root_ref

      begin
        sha_from_ref(actual_ref)
      rescue Rugged::OdbError, Rugged::InvalidError, Rugged::ReferenceError
        # Return an empty array if the ref wasn't found
        return []
      end

      cmd = %W(git --git-dir=#{path} ls-tree)
      cmd += %w(-r)
      cmd += %w(--full-tree)
      cmd += %w(--full-name)
      cmd += %W(-- #{actual_ref})

      raw_output = IO.popen(cmd, &:read).split("\n").map do |f|
        stuff, path = f.split("\t")
        _mode, type, _sha = stuff.split(" ")
        path if type == "blob"
        # Contain only blob type
      end

      raw_output.compact
    end

    def copy_gitattributes(ref)
      begin
        commit = lookup(ref)
      rescue Rugged::ReferenceError
        raise InvalidRef.new("Ref #{ref} is invalid")
      end

      # Create the paths
      info_dir_path = File.join(path, 'info')
      info_attributes_path = File.join(info_dir_path, 'attributes')

      begin
        # Retrieve the contents of the blob
        gitattributes_content = blob_content(commit, '.gitattributes')
      rescue InvalidBlobName
        # No .gitattributes found. Should now remove any info/attributes and return
        File.delete(info_attributes_path) if File.exist?(info_attributes_path)
        return
      end

      # Create the info directory if needed
      Dir.mkdir(info_dir_path) unless File.directory?(info_dir_path)

      # Write the contents of the .gitattributes file to info/attributes
      # Use binary mode to prevent Rails from converting ASCII-8BIT to UTF-8
      File.open(info_attributes_path, "wb") do |file|
        file.write(gitattributes_content)
      end
    end

    # Checks if the blob should be diffable according to its attributes
    def diffable?(blob)
      attributes(blob.path).fetch('diff') { blob.text? }
    end

    # Returns the Git attributes for the given file path.
    #
    # See `Bringit::Attributes` for more information.
    def attributes(path)
      @attributes.attributes(path)
    end

    private

    # Get the content of a blob for a given commit.  If the blob is a commit
    # (for submodules) then return the blob's OID.
    def blob_content(commit, blob_name)
      blob_entry = tree_entry(commit, blob_name)

      unless blob_entry
        raise InvalidBlobName.new("Invalid blob name: #{blob_name}")
      end

      case blob_entry[:type]
      when :commit
        blob_entry[:oid]
      when :tree
        raise InvalidBlobName.new("#{blob_name} is a tree, not a blob")
      when :blob
        rugged.lookup(blob_entry[:oid]).content
      end
    end

    # Parses the contents of a .gitmodules file and returns a hash of
    # submodule information.
    def parse_gitmodules(commit, content)
      results = {}

      current = ""
      content.split("\n").each do |txt|
        if txt =~ /^\s*\[/
          current = txt.match(/(?<=").*(?=")/)[0]
          results[current] = {}
        else
          next unless results[current]
          match_data = txt.match(/(\w+)\s*=\s*(.*)/)
          next unless match_data
          target = match_data[2].chomp
          results[current][match_data[1]] = target

          if match_data[1] == "path"
            begin
              results[current]["id"] = blob_content(commit, target)
            rescue InvalidBlobName
              results.delete(current)
            end
          end
        end
      end

      results
    end

    # Returns true if +commit+ introduced changes to +path+, using commit
    # trees to make that determination.  Uses the history simplification
    # rules that `git log` uses by default, where a commit is omitted if it
    # is TREESAME to any parent.
    #
    # If the +follow+ option is true and the file specified by +path+ was
    # renamed, then the path value is set to the old path.
    def commit_touches_path?(commit, path, follow, walker)
      entry = tree_entry(commit, path)

      if commit.parents.empty?
        # This is the root commit, return true if it has +path+ in its tree
        return !entry.nil?
      end

      num_treesame = 0
      commit.parents.each do |parent|
        parent_entry = tree_entry(parent, path)

        # Only follow the first TREESAME parent for merge commits
        if num_treesame > 0
          walker.hide(parent)
          next
        end

        if entry.nil? && parent_entry.nil?
          num_treesame += 1
        elsif entry && parent_entry && entry[:oid] == parent_entry[:oid]
          num_treesame += 1
        end
      end

      case num_treesame
      when 0
        detect_rename(commit, commit.parents.first, path) if follow
        true
      else false
      end
    end

    # Find the entry for +path+ in the tree for +commit+
    def tree_entry(commit, path)
      pathname = Pathname.new(path)
      first = true
      tmp_entry = nil

      pathname.each_filename do |dir|
        if first
          tmp_entry = commit.tree[dir]
          first = false
        elsif tmp_entry.nil?
          return nil
        else
          tmp_entry = rugged.lookup(tmp_entry[:oid])
          return nil unless tmp_entry.type == :tree
          tmp_entry = tmp_entry[dir]
        end
      end

      tmp_entry
    end

    # Compare +commit+ and +parent+ for +path+.  If +path+ is a file and was
    # renamed in +commit+, then set +path+ to the old filename.
    def detect_rename(commit, parent, path)
      diff = parent.diff(commit, paths: [path], disable_pathspec_match: true)

      # If +path+ is a filename, not a directory, then we should only have
      # one delta.  We don't need to follow renames for directories.
      return nil if diff.each_delta.count > 1

      delta = diff.each_delta.first
      if delta.added?
        full_diff = parent.diff(commit)
        full_diff.find_similar!

        full_diff.each_delta do |full_delta|
          if full_delta.renamed? && path == full_delta.new_file[:path]
            # Look for the old path in ancestors
            path.replace(full_delta.old_file[:path])
          end
        end
      end
    end

    def archive_to_file(treeish = 'master', filename = 'archive.tar.gz', format = nil, compress_cmd = %w(gzip -n))
      git_archive_cmd = %W(git --git-dir=#{path} archive)

      # Put files into a directory before archiving
      prefix = "#{archive_name(treeish)}/"
      git_archive_cmd << "--prefix=#{prefix}"

      # Format defaults to tar
      git_archive_cmd << "--format=#{format}" if format

      git_archive_cmd += %W(-- #{treeish})

      open(filename, 'w') do |file|
        # Create a pipe to act as the '|' in 'git archive ... | gzip'
        pipe_rd, pipe_wr = IO.pipe

        # Get the compression process ready to accept data from the read end
        # of the pipe
        compress_pid = spawn(*nice(compress_cmd), in: pipe_rd, out: file)
        # The read end belongs to the compression process now; we should
        # close our file descriptor for it.
        pipe_rd.close

        # Start 'git archive' and tell it to write into the write end of the
        # pipe.
        git_archive_pid = spawn(*nice(git_archive_cmd), out: pipe_wr)
        # The write end belongs to 'git archive' now; close it.
        pipe_wr.close

        # When 'git archive' and the compression process are finished, we are
        # done.
        Process.waitpid(git_archive_pid)
        raise "#{git_archive_cmd.join(' ')} failed" unless $?.success?
        Process.waitpid(compress_pid)
        raise "#{compress_cmd.join(' ')} failed" unless $?.success?
      end
    end

    def nice(cmd)
      nice_cmd = %w(nice -n 20)
      unless unsupported_platform?
        nice_cmd += %w(ionice -c 2 -n 7)
      end
      nice_cmd + cmd
    end

    def unsupported_platform?
      %w[darwin freebsd solaris].map { |platform| RUBY_PLATFORM.include?(platform) }.any?
    end

    # Returns true if the index entry has the special file mode that denotes
    # a submodule.
    def submodule?(index_entry)
      index_entry[:mode] == 57344
    end

    # Return a Rugged::Index that has read from the tree at +ref_name+
    def populated_index(ref_name)
      commit = rev_parse_target(ref_name)
      index = rugged.index
      index.read_tree(commit.tree)
      index
    end

    # Return an array of BlobSnippets for lines in +file_contents+ that match
    # +query+
    def build_greps(file_contents, query, ref, filename)
      # The file_contents string is potentially huge so we make sure to loop
      # through it one line at a time. This gives Ruby the chance to GC lines
      # we are not interested in.
      #
      # We need to do a little extra work because we are not looking for just
      # the lines that matches the query, but also for the context
      # (surrounding lines). We will use Enumerable#each_cons to efficiently
      # loop through the lines while keeping surrounding lines on hand.
      #
      # First, we turn "foo\nbar\nbaz" into
      # [
      #  [nil, -3], [nil, -2], [nil, -1],
      #  ['foo', 0], ['bar', 1], ['baz', 3],
      #  [nil, 4], [nil, 5], [nil, 6]
      # ]
      lines_with_index = Enumerator.new do |yielder|
        # Yield fake 'before' lines for the first line of file_contents
        (-SEARCH_CONTEXT_LINES..-1).each do |i|
          yielder.yield [nil, i]
        end

        # Yield the actual file contents
        count = 0
        file_contents.each_line do |line|
          line.chomp!
          yielder.yield [line, count]
          count += 1
        end

        # Yield fake 'after' lines for the last line of file_contents
        (count + 1..count + SEARCH_CONTEXT_LINES).each do |i|
          yielder.yield [nil, i]
        end
      end

      greps = []

      # Loop through consecutive blocks of lines with indexes
      lines_with_index.each_cons(2 * SEARCH_CONTEXT_LINES + 1) do |line_block|
        # Get the 'middle' line and index from the block
        line, _ = line_block[SEARCH_CONTEXT_LINES]

        next unless line && line.match(/#{Regexp.escape(query)}/i)

        # Yay, 'line' contains a match!
        # Get an array with just the context lines (no indexes)
        match_with_context = line_block.map(&:first)
        # Remove 'nil' lines in case we are close to the first or last line
        match_with_context.compact!

        # Get the line number (1-indexed) of the first context line
        first_context_line_number = line_block[0][1] + 1

        greps << Bringit::BlobSnippet.new(
          ref,
          match_with_context,
          first_context_line_number,
          filename
        )
      end

      greps
    end

    # Return the Rugged patches for the diff between +from+ and +to+.
    def diff_patches(from, to, options = {}, *paths)
      options ||= {}
      paths = paths.map { |p| p.sub(%r{\A/}, '') }
      break_rewrites = options[:break_rewrites]
      actual_options = Bringit::Diff.filter_diff_options(options.merge(paths: paths))

      diff = rugged.diff(from, to, actual_options)
      return [] if diff.nil?
      diff.find_similar!(break_rewrites: break_rewrites)
      diff.each_patch
    end
  end
end


text:
      Type

      Info

      Price

              Ballroom dress

United States

12-07-2015

      Gorgeous and Unusual Silver & Grey...

Size: US XS-S, Color: Silver Grey
Condition: Used

 Gorgeous silver dress, very sparkling and looks unusual on the floor. Very noticeable! Have had a lot of compliments about this dr...

      € 795.00

Negotiable

€ 795.00

              Ballroom dress

France

10-02-2013

      splendid Sylvia Design dress

Size: french 36-38, Color: fushia pink
Condition: Used

 Dress made by Silvia Design. Splendid dress with lot of stones, many different pink ruffles (organza and stiff net), floral cascad...

      € 900.00

Negotiable


text:
package com.gemstone.gemfire.cache.execute;

import java.util.concurrent.TimeUnit;

import com.gemstone.gemfire.distributed.DistributedMember;

/**
 *

 * Defines the interface for a container that gathers results from function
 * execution.

 * GemFire provides a default implementation for ResultCollector. Applications
 * can choose to implement their own custom ResultCollector. A custom
 * ResultCollector facilitates result sorting or aggregation. Aggregation
 * functions like sum, minimum, maximum and average can also be applied to the
 * result using a custom ResultCollector. Results arrive as they are sent using
 * the {@link ResultSender#sendResult(Object)} and can be used as they arrive.
 * To indicate that all results have been received {@link #endResults()} is
 * called.
 *
 *

 * Example:

 *
 *

 *  Region region ;
 *  Set keySet = Collections.singleton("myKey");
 *  Function multiGetFunction ;
 *  Object args ;
 *  ResultCollector rc = FunctionService.onRegion(region)
 *                                      .withArgs(args)
 *                                      .withFilter(keySet)
 *                                      .withCollector(new MyCustomResultCollector())
 *                                      .execute(multiGetFunction.getId());
 *  Application can do something else here before retrieving the result
 *  Or it can have some logic in {{@link #addResult(DistributedMember, Object)} to use the partial results.
 *  If it wants to see all the results it can use
 *  Object functionResult = rc.getResult();
 *  or
 *  Object functionResult = rc.getResult(timeout,TimeUnit);
 *  depending on if it wants to wait for all the results or wait for a timeout period.
 *

 *
 * GemFire provides default implementation of ResultCollector which collects
 * results in Arraylist. There is no need to provide a synchronization mechanism
 * in the user implementations of ResultCollector
 *
 * @author Yogesh Mahajan
 * @since 6.0
 *
 */
public interface ResultCollector<T,S> {

  /**
   * Method used to pull results from the ResultCollector. It returns the result
   * of function execution, potentially blocking until {@link #endResults() all
   * the results are available} has been called.
   *
   * @return the result
   * @throws FunctionException
   *           if result retrieval fails
   * @since 6.0
   */
  public S getResult() throws FunctionException;

  /**
   * Method used to pull results from the ResultCollector. It returns the result
   * of function execution, blocking for the timeout period until
   * {@link #endResults() all the results are available}. If all the results are
   * not received in provided time a FunctionException is thrown.
   *
   * @param timeout
   *          the maximum time to wait
   * @param unit
   *          the time unit of the timeout argument
   * @return the result
   * @throws FunctionException
   *           if result retrieval fails within timeout provided
   * @throws InterruptedException
   *           if the current thread was interrupted while waiting
   * @since 6.0
   *
   */
  public S getResult(long timeout, TimeUnit unit)
      throws FunctionException, InterruptedException;

  /**
   * Method used to feed result to the ResultCollector. It adds a single
   * function execution result to the ResultCollector It is invoked every time a
   * result is sent using ResultSender.
   *
   * @param resultOfSingleExecution
   * @since 6.0
   * @param memberID
   *          DistributedMember ID to which result belongs
   */
  public void addResult(DistributedMember memberID, T resultOfSingleExecution);

  /**
   * GemFire will invoke this method when function execution has completed and
   * all results for the execution have been obtained and
   * {@link #addResult(DistributedMember, Object) added to the ResultCollector}
   * Unless the {@link ResultCollector} has received
   * {@link ResultSender#lastResult(Object) last result} from all the
   * executing nodes, it keeps waiting for more results to come.
   *
   * @since 6.0
   *
   * @see ResultSender#lastResult(Object)
   */
  public void endResults();

  /**
   * GemFire will invoke this method before re-executing function (in case of
   * Function Execution HA). This is to clear the previous execution results from
   * the result collector
   *
   * @since 6.5
   */
  public void clearResults();

}


text:
current_dir = File.dirname(__FILE__)
log_level                :info
log_location             STDOUT
node_name                "vineethguna1993"
client_key               "/var/lib/jenkins/.chef/vineethguna1993.pem"
validation_client_name   "chefinfra-validator"
validation_key           "/var/lib/jenkins/.chef/chefinfra-validator.pem"
chef_server_url          "https://api.opscode.com/organizations/chefinfra"
cache_type               'BasicFile'
cookbook_path            ["#{current_dir}/../cookbooks"]


text:
require 'net/http'
require 'uri'
require 'cgi'

module SitemapNotifier
  class Notifier
    class << self
      # sitemap url
      attr_accessor :sitemap_url

      # source
      attr_writer :models
      def models
        @models ||= :all
      end

      # delay
      attr_writer :delay
      def delay
        @delay ||= 600
      end

      # environments
      attr_writer :environments
      def environments
        @environments ||= [:production]
      end

      # urls
      attr_writer :urls
      def urls
        @urls ||= ["http://www.google.com/webmasters/sitemaps/ping?sitemap=#{CGI::escape(sitemap_url)}",
                   "http://www.bing.com/webmaster/ping.aspx?siteMap=#{CGI::escape(sitemap_url)}",
                   "http://submissions.ask.com/ping?sitemap=#{CGI::escape(sitemap_url)}"]
                   # no Yahoo here, as they will be using Bing from september 15th, 2011
      end

      # running pid
      attr_accessor :running_pid

      def notify!
        raise "sitemap_url not set – use SitemapNotifier::Notifier.sitemap_url = 'xx'" unless sitemap_url

        if (environments == :all || environments.include?(Rails.env.to_sym)) && !running?
          self.running_pid = fork do
            Rails.logger.info "Notifying search engines of changes to sitemap..."

            urls.each do |url|
              if get_url(url)
                Rails.logger.info "#{url} – ok"
              else
                Rails.logger.info "#{url} – failed"
              end
            end

            sleep delay
            exit
          end
        end
      end

    protected

      def get_url(url)
        uri = URI.parse(url)
        begin
          return Net::HTTPSuccess === Net::HTTP.get_response(uri)
        rescue Exception
          return false
        end
      end

      def running?
        return false unless running_pid

        begin
          Process.getpgid(running_pid)
          true
        rescue Errno::ESRCH
          false
        end
      end
    end
  end
end


text:
namespace blink {

class LocalFrame;

class SctpTransportProxy : public webrtc::SctpTransportObserverInterface {
 public:
  // Delegate class for actions caused by the Proxy, but executed on the
  // main thread. The Delegate must remain alive until it has observed
  // the kClosed state, which is the last thing that can happen.
  class Delegate : public blink::GarbageCollectedMixin {
   public:
    virtual ~Delegate() = default;

    // Called when the Create() function is complete. Sends current state,
    // but does not indicate a state change.
    virtual void OnStartCompleted(webrtc::SctpTransportInformation info) = 0;
    // Called when a state change is signalled from transport.
    virtual void OnStateChange(webrtc::SctpTransportInformation info) = 0;
    void Trace(Visitor* visitor) override {}
  };

  // Constructs a SctpTransportProxy.  The caller is responsible for keeping
  // |sctp_transport| alive until after the SctpTransportProxy is deleted.
  // The SctpTransportProxy takes a <CrossThreadPersistent> reference to the
  // Delegate, preventing it from being garbage collected until the |kClosed|
  // state is reached.
  // The SctpTransportProxy can only be safely deleted after seeing the state
  // |kClosed|, since this is the last event that can happen on the transport.
  static std::unique_ptr<SctpTransportProxy> Create(
      LocalFrame& frame,
      scoped_refptr<base::SingleThreadTaskRunner> proxy_thread,
      scoped_refptr<base::SingleThreadTaskRunner> host_thread,
      rtc::scoped_refptr<webrtc::SctpTransportInterface> sctp_transport,
      Delegate* delegate);

  ~SctpTransportProxy() override {}

 private:
  SctpTransportProxy(
      LocalFrame& frame,
      scoped_refptr<base::SingleThreadTaskRunner> proxy_thread,
      scoped_refptr<base::SingleThreadTaskRunner> host_thread,
      rtc::scoped_refptr<webrtc::SctpTransportInterface> sctp_transport,
      Delegate* delegate);
  // Implementation of webrtc::SctpTransportObserver
  void OnStateChange(webrtc::SctpTransportInformation info) override;

  // Internal helper for Create()
  void StartOnHostThread();

  const scoped_refptr<base::SingleThreadTaskRunner> proxy_thread_;
  const scoped_refptr<base::SingleThreadTaskRunner> host_thread_;
  const rtc::scoped_refptr<webrtc::SctpTransportInterface> sctp_transport_;
  CrossThreadPersistent<Delegate> delegate_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_ADAPTERS_SCTP_TRANSPORT_PROXY_H_


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TreeModule } from 'angular-tree-component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { Import } from './import.component';
import { ImportTree } from './components/importtree';
import { ImportResults } from './components/importresults'

import { routing } from './import.routing';
import { RestApiService } from 'app/pages/api.service';
import { SimpleNotificationsModule } from 'angular2-notifications';

import { NgaModule } from 'app/theme/nga.module';
import { NgbDropdownModule } from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  imports: [
    CommonModule,
    TreeModule,
    FormsModule,
    ReactiveFormsModule,
    NgbDropdownModule,
    NgaModule,
    SimpleNotificationsModule.forRoot(),
    routing
  ],
  declarations: [
    Import,
    ImportTree,
    ImportResults
  ],
  providers: [
    RestApiService
  ]
})
export class ImportModule {}


text:
import { invoke } from "../index";
export = invoke;