text:
using App.Common.Db;
using App.Api.Models;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Ganss.XSS;

namespace App.Api.Controllers
{
    [Route("api/[controller]")]
    public class PostsController : Controller
    {
	    private readonly AppDb _db;

	    public PostsController(AppDb db)
	    {
		    _db = db;
	    }

        // GET api/posts
        [HttpGet]
        public async Task<IActionResult> ListAsync()
        {
			var results = await _db.Posts.Include(m => m.Author).OrderByDescending(m => m.Id).ToListAsync();
			return new OkObjectResult(results);
        }

        // GET api/posts/5
        [HttpGet("{id}")]
        public async Task<IActionResult> GetAsync(int id)
        {
			var model = await _db.Posts.Include(m => m.Author).FirstOrDefaultAsync(m => m.Id == id);
			if (model != null)
			{
				return new OkObjectResult(model);
			}
			return NotFound();
        }

        // POST api/posts
        [HttpPost]
        public async Task<IActionResult> CreateAsync([FromBody] Post body)
        {
			var sanitizer = new HtmlSanitizer();
			body.Content = sanitizer.Sanitize(body.Content);
	        _db.Posts.Add(body);
			await _db.SaveChangesAsync();
			return new OkObjectResult(body);
        }

        // PUT api/posts/5
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateAsync(int id, [FromBody] Post body)
        {
			var model = await _db.Posts.FindAsync(id);
			if (model != null)
			{
				model.Title = body.Title;
				var sanitizer = new HtmlSanitizer();
				model.Content = sanitizer.Sanitize(body.Content);
				model.AuthorId = body.AuthorId;
				await _db.SaveChangesAsync();
				return new OkObjectResult(model);
			}
			return NotFound();
        }

        // DELETE api/posts/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteAsync(int id)
        {
			var model = await _db.Posts.FindAsync(id);
			if (model != null)
			{
				_db.Posts.Remove(model);
				await _db.SaveChangesAsync();
				return Ok();
			}
			return NotFound();
        }
    }
}


text:
/**
 * Used internally by the Replayer.
 * Makes a proxy for the given object's function that will wrap it, allowing it to be recorded and replayed later.
 *
 * @param {object} obj              Object to wrap
 * @param {Replayer} replayer       Replayer used to record
 * @param {string} fnName           Name of the function to record
 * @returns {Function}              Proxy function that will do the recording
 */
function makeProxy(obj, replayer, fnName) {
    return function() {
        var args = Array.prototype.slice.call(arguments);
        replayer.record.push([ fnName, args ]);
        var result;
        if (args.length == 1) {
            result = obj[fnName].call(obj, args[0]);
        } else {
            result = obj[fnName].call(obj, args);
        }
        return result === obj ? replayer : result;
    };
}

/**
 * Builds a Replayer object, wrapping the given object instance.
 *
 * @param {object} obj              Object instance to wrap
 * @constructor
 */
var Replayer = function(obj) {
    this.record = [];
    this.wrapped = obj;
    var self = this;
    for (var k in obj) {
        if (typeof obj[k] === 'function') {
            self[k] = makeProxy(obj, self, k);
        }
    }
};

/**
 * Allows access to wrapped object.  Should only be used to avoid capturing calls that should avoid capture.
 *
 * @function getWrapped
 * @returns {object}                Wrapped object.
 */
Replayer.prototype.getWrapped = function() { return this.wrapped; };

/**
 * Replays any recorded function calls, in order, on the passed-in instance.
 * Must be duck-type compatible with the original instance for all recorded functions.
 *
 * @param {object} newSelf          Object on which to play back recorded function calls.
 * @returns {Array}                 Results from all calls, in order.  Calls with no result get recorded as 'undefined'.
 */
Replayer.prototype.replay = function(newSelf) {
    var results = [];
    for (var idx in this.record) {
        var curMethod = this.record[idx][0];
        var curArgs = this.record[idx][1];
        var curResult;
        if (curArgs.length == 1) {
            curResult = newSelf[curMethod].call(newSelf, curArgs[0]);
        } else {
            curResult = newSelf[curMethod].call(newSelf, curArgs);
        }
        results.push(curResult);
    }

    return results;
};

module.exports.watch = function(obj) { return new Replayer(obj); };

redpajama_set_name: RedPajamaGithub


text:
import re
from lepl import (List, Token, Delayed, RuntimeLexerError,
                  FullFirstMatchException, sexpr_to_tree)

from errors import TypeIncorrectlySpecifiedError

class PType:

    # Literals.
    INT = 0
    FLOAT = 1
    STRING = 2
    UNICODE = 3
    BOOL = 4
    UNIT = 5

    # Containers.
    LIST = 6
    TUPLE = 7
    ARROW = 8

    # Polymorphism stuff.
    VAR = 9
    UNIV = 10

    def __init__(self, tag):
        assert type(tag) is int and 0 <= tag <= 10
        self.tag = tag

    ## Type constructor dispatchers.

    @staticmethod
    def from_str(s):
        """Create a PType object from a string."""

        parsed = TypeSpecParser.parse(s)
        return PType.from_type_ast(parsed)

    @staticmethod
    def from_type_ast(ast):
        """Create a PType object from a LEPL-generated type AST."""

        # shorthand.
        from_ast = PType.from_type_ast

        if type(ast) is str:
            if ast == "int":
                return PType.INT_T
            elif ast == "float":
                return PType.FLOAT_T
            elif ast == "str":
                return PType.STR_T
            elif ast == "unicode":
                return PType.UNICODE_T
            elif ast == "bool":
                return PType.BOOL_T
            elif ast == "unit":
                return PType.UNIT_T
            elif ast.index("'") == 0:
                return PType.var(ast)
            else:
                assert True, ast
        elif ast.__class__ == Lst:
            return PType.list(from_ast(ast.elt_t()))
        elif ast.__class__ == Tup:
            return PType.tuple([from_ast(t) for t in ast.elt_ts()])
        elif ast.__class__ == Arr:
            return PType.arrow(from_ast(ast.domain_t()),
                               from_ast(ast.range_t()))
        else:
            # Note that there's no UNIV case; shouldn't be user-specifiable.
            assert True, ast.__class__.__name__

    ## Type constructors.

    @staticmethod
    def int():
        if not hasattr(PType, 'INT_T'):
            PType.INT_T = PType(PType.INT)
        return PType.INT_T

    @staticmethod
    def float():
        if not hasattr(PType, 'FLOAT_T'):
            PType.FLOAT_T = PType(PType.FLOAT)
        return PType.FLOAT_T

    @staticmethod
    def string():
        if not hasattr(PType, 'STR_T'):
            PType.STR_T = PType(PType.STRING)
        return PType.STR_T

    @staticmethod
    def unicode():
        if not hasattr(PType, 'UNICODE_T'):
            PType.UNICODE_T = PType(PType.UNICODE)
        return PType.UNICODE_T

    @staticmethod
    def bool():
        if not hasattr(PType, 'BOOL_T'):
            PType.BOOL_T = PType(PType.BOOL)
        return PType.BOOL_T

    @staticmethod
    def unit():
        if not hasattr(PType, 'UNIT_T'):
            PType.UNIT_T = PType(PType.UNIT)
        return PType.UNIT_T

    @staticmethod
    def list(elt):
        t = PType(PType.LIST)
        t.elt = elt
        return t

    @staticmethod
    def tuple(elts):
        t = PType(PType.TUPLE)
        t.elts = elts
        return t

    @staticmethod
    def arrow(dom, ran):
        t = PType(PType.ARROW)
        t.dom = dom
        t.ran = ran
        return t

    @staticmethod
    def var(idn):
        t = PType(PType.VAR)
        t.idn = idn
        return t

    @staticmethod
    def univ(qnt, ovr):
        t = PType(PType.UNIV)
        t.qnt = qnt
        t.ovr = ovr
        return t

    ## Type tests.
    # Note these are unnecessary for the nullary type constructors becasue those
    # are singletons and can be compared with object equality.

    def is_base(self):
        return self.tag <= PType.UNIT

    def is_list(self):
        return self.tag == PType.LIST

    def is_tuple(self):
        return self.tag == PType.TUPLE

    def is_arrow(self):
        return self.tag == PType.ARROW

    def is_var(self):
        return self.tag == PType.VAR

    def is_univ(self):
        return self.tag == PType.UNIV

    ## Basic methods.

    def __nonzero__(self):
        return True
    __bool__ = __nonzero__

    def __repr__(self):

        if self.tag == PType.INT:
            return "int"
        elif self.tag == PType.FLOAT:
            return "float"
        elif self.tag == PType.STRING:
            return "str"
        elif self.tag == PType.UNICODE:
            return "unicode"
        elif self.tag == PType.BOOL:
            return "bool"
        elif self.tag == PType.UNIT:
            return "unit"

        elif self.is_list():
            return "[" + self.elt.__repr__() + "]"
        elif self.is_tuple():
            if self.tuple_len() == 1:
                return "(%s,)" % self.elts[0].__repr__()
            else:
                return "(" + ", ".join(elt.__repr__() for elt in self.elts) + ")"
        elif self.is_arrow():
            return self.dom.__repr__() + " -> " + self.ran.__repr__()

        elif self.is_var():
            return self.idn
        elif self.is_univ():
            return "V" + self.qnt.__repr__() + "." + self.ovr.__repr__()

        else:
            assert True, self.tag

    def __hash__(self):
        return hash(self.__repr__())

    def __eq__(self, other):
        return self.__repr__() == other.__repr__()

    def __ne__(self, other):
        return not self.__eq__(other)

    ## Special methods.

    def tuple_slice(self, start=0, end=None, step=1):

        assert self.is_tuple()

        if end is None:
            end = len(self.elts)

        return PType.tuple(self.elts[start:end:step])

    def tuple_len(self):
        assert self.is_tuple()
        return len(self.elts)

    def free_type_vars(self):

        if self.is_base():
            return set()
        elif self.is_list():
            return self.elt.free_type_vars()
        elif self.is_tuple():
            return set().union(*[elt.free_type_vars() for elt in self.elts])
        elif self.is_arrow():
            return self.dom.free_type_vars() | self.ran.free_type_vars()

        elif self.is_var():
            return {self}
        elif self.is_univ():
            return self.ovr.free_type_vars() - {self.qnt}

        else:
            assert True, self.tag

    def quantify(self):

        quant = self

        for v in self.free_type_vars():
            quant = PType.univ(v, quant)

        return quant

def better_sexpr_to_tree(a):
    if type(a) == str:
        return a
    else:
        return sexpr_to_tree(a)

class Lst(List):
    def elt_t(self):
        return self[0]

class Tup(List):
    def elt_ts(self):
        return [t for t in self]

class Arr(List):
    def domain_t(self):
        return self[0]

    def range_t(self):
        return self[1]

class TypeSpecParser:
    int_tok = Token(r'int')
    float_tok = Token(r'float')
    str_tok = Token(r'str')
    unicode_tok = Token(r'unicode')
    bool_tok = Token(r'bool')
    unit_tok = Token(r'unit')
    var_tok = Token(r"'[a-zA-Z0-9]+")

    list_start = Token(r'\[')
    list_end = Token(r'\]')

    tuple_start = Token(r'\(')
    tuple_div = Token(r',')
    tuple_end = Token(r'\)')

    arrow_div = Token(r'\->')

    tight_typ = Delayed()
    typ = Delayed()

    num_typ = int_tok | float_tok # | long_tok | complex_tok
    str_typ = str_tok | unicode_tok
    base_typ = num_typ | str_typ | bool_tok | unit_tok | var_tok

    lst = ~list_start & typ & ~list_end > Lst

    empty_tup = ~tuple_start & ~tuple_end > Tup
    comma_tup = ~tuple_start & (typ & ~tuple_div)[1:] & ~tuple_end > Tup
    no_comma_tup = ~tuple_start & (typ & ~tuple_div)[1:] & typ & ~tuple_end > Tup
    tup = empty_tup | comma_tup | no_comma_tup

    arr = tight_typ & ~arrow_div & typ > Arr

    parens = ~tuple_start & typ & ~tuple_end
    tight_typ += base_typ | lst | tup | parens
    typ += arr | tight_typ

    @staticmethod
    def parse(s):
        try:
            return TypeSpecParser.typ.parse(s)[0]
        except (RuntimeLexerError, FullFirstMatchException):
            raise TypeIncorrectlySpecifiedError(s)

    @staticmethod
    def print_parse(s):
        try:
            return better_sexpr_to_tree(TypeSpecParser.typ.parse(s)[0])
        except (RuntimeLexerError, FullFirstMatchException):
            raise TypeIncorrectlySpecifiedError(s)


text:
using System;
using System.IO;
using UnityEngine;
using DaggerfallWorkshop.Game;
using DaggerfallWorkshop.Game.Serialization;
using DaggerfallWorkshop.Utility.AssetInjection;
using DaggerfallWorkshop.Game.UserInterfaceWindows;

namespace LoadingScreen.Components
{
    /// <summary>
    /// Implements a component for the loading screen.
    /// </summary>
    public abstract class LoadingScreenComponent : ILoadingEventsHandler
    {
        #region Fields & Properties

        protected bool enabled = true;
        protected Rect rect;
        protected GUIStyle style;

        readonly Rect relRect;
        readonly int referenceFontSize = -1;

        /// <summary>
        /// Show or hide the component.
        /// </summary>
        public bool Enabled
        {
            get { return enabled; }
            set { enabled = value; }
        }

        public Rect Rect
        {
            get { return rect; }
        }

        public int Font
        {
            set { SetFont(value); }
        }

        public int FontSize
        {
            get { return style.fontSize; }
            set { style.fontSize = value; }
        }

        public FontStyle FontStyle
        {
            get { return style.fontStyle; }
            set { style.fontStyle = value; }
        }

        public Color FontColor
        {
            get { return style.normal.textColor; }
            set { style.normal.textColor = value; }
        }

        public LoadingScreenPanel Parent { get; set; }

        #endregion

        #region Constructor

        /// <summary>
        /// Set component rect and style.
        /// </summary>
        /// <param name="virtualRect">Rect in a 100x100 resolution.</param>
        protected LoadingScreenComponent(Rect virtualRect)
        {
            Rect relRect = new Rect(
                virtualRect.position / 100f,
                virtualRect.size / 100f);

            var style = new GUIStyle();
            style.alignment = GetTextAnchor(relRect);

            if (relRect.x < 0)
                relRect.x += 1 - relRect.width;
            if (relRect.y < 0)
                relRect.y += 1 - relRect.height;
            relRect.x = Mathf.Clamp(relRect.x, 0, 1 - relRect.width);
            relRect.y = Mathf.Clamp(relRect.y, 0, 1 - relRect.height);

            this.relRect = relRect;
            this.rect = new Rect(RelToScreen(relRect.position), RelToScreen(relRect.size));
            this.style = style;
        }

        /// <summary>
        /// Set component rect and style.
        /// Font size will be automatically scaled on resolution and rect size.
        /// </summary>
        /// <param name="virtualRect">Rect in a 100x100 resolution.</param>
        /// <param name="referenceFontSize">A font size that fits the rect.</param>
        protected LoadingScreenComponent(Rect virtualRect, int referenceFontSize)
            :this(virtualRect)
        {
            this.referenceFontSize = referenceFontSize;
            this.style.fontSize = CalcFontSize(referenceFontSize);
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Draws on OnGui().
        /// </summary>
        public abstract void Draw();

        /// <summary>
        /// Called when the user load a save.
        /// </summary>
        /// <param name="saveData">Save being loaded.</param>
        public abstract void OnLoadingScreen(SaveData_v1 saveData);

        /// <summary>
        /// Called during a fast travel.
        /// </summary>
        /// <param name="sender">Travel popup..</param>
        public abstract void OnLoadingScreen(DaggerfallTravelPopUp sender);

        /// <summary>
        /// Called during transition (entering/exiting building).
        /// </summary>
        /// <param name="args">Transition parameters.</param>
        public abstract void OnLoadingScreen(PlayerEnterExit.TransitionEventArgs args);

        /// <summary>
        /// Called once per frame.
        /// </summary>
        public virtual void UpdateScreen()
        {
        }

        /// <summary>
        /// Called on press-any-key screen.
        /// </summary>
        public virtual void OnEndScreen()
        {
        }

        /// <summary>
        /// Hide components that don't support death screen.
        /// Override to show and do something.
        /// </summary>
        public virtual void OnDeathScreen()
        {
            enabled = false;
        }

        public virtual void RefreshRect()
        {
            rect.position = RelToScreen(relRect.position);
            rect.size = RelToScreen(relRect.size);

            if (referenceFontSize != -1)
                style.fontSize = CalcFontSize(referenceFontSize);
        }

        public static implicit operator bool(LoadingScreenComponent plugin)
        {
            return !object.ReferenceEquals(plugin, null);
        }

        #endregion

        #region Protected Methods

        /// <summary>
        /// Gets font size scaled on resolution and rect size.
        /// </summary>
        /// <param name="referenceSize">A font size that fits the rect.</param>
        /// <returns>Font size for the guistyle</returns>
        protected int CalcFontSize(int referenceSize)
        {
            Vector2 scale = new Vector2(rect.width / 100, rect.height / 100);
            return Mathf.RoundToInt(referenceSize * (scale.x + scale.y) / 2);
        }

        /// <summary>
        /// Import a texture from resources. This texture can be overriden with loose files.
        /// </summary>
        protected Texture2D ImportTexture(string name)
        {
            Texture2D tex;
            if (!TextureReplacement.TryImportTextureFromLooseFiles(Path.Combine(LoadingScreenPanel.ResourcesPath, name), false, false, true, out tex))
                tex = LoadingScreen.Mod.GetAsset<Texture2D>(name);

            return tex;
        }

        #endregion

        #region Private Methods

        private void SetFont(int fontID)
        {
            string name = GetFontName(fontID);
            style.font = name != null ? Resources.Load<Font>(name) : null;
        }

        /// <summary>
        /// Get text alignment for this relative rect.
        /// </summary>
        /// <remarks>
        /// From 0 to 1 is left(up) alignment, from 0 to -1 is right(bottom) aligment.
        /// Center and Middle are used according to center point.
        /// </remarks>
        private static TextAnchor GetTextAnchor(Rect relRect)
        {
            bool isCenter = Mathf.Approximately(Mathf.Abs(relRect.center.x), 0.5f);
            bool isMiddle = Mathf.Approximately(Mathf.Abs(relRect.center.y), 0.5f);

            // Center
            if (isCenter)
            {
                if (isMiddle)
                    return TextAnchor.MiddleCenter;

                if (relRect.y > 0)
                    return TextAnchor.UpperCenter;
                return TextAnchor.LowerCenter;
            }

            // Left
            if (relRect.x > 0)
            {
                if (isMiddle)
                    return TextAnchor.MiddleLeft;

                if (relRect.y > 0)
                    return TextAnchor.UpperLeft;
                return TextAnchor.LowerLeft;
            }

            // Right
            if (isMiddle)
                return TextAnchor.MiddleRight;

            if (relRect.y > 0)
                return TextAnchor.UpperRight;
            return TextAnchor.LowerRight;
        }

        private static Vector2 RelToScreen(Vector2 rel)
        {
            return new Vector2(rel.x * Screen.width, rel.y * Screen.height);
        }

        /// <summary>
        /// Convert font id to font path.
        /// </summary>
        private static string GetFontName(int fontID)
        {
            switch (fontID)
            {
                case 0:     return null; // Arial or Liberation Sans
                case 1:     return "Fonts/OpenSans/OpenSans-ExtraBold";
                case 2:     return "Fonts/OpenSans/OpenSansBold";
                case 3:     return "Fonts/OpenSans/OpenSansSemibold";
                case 4:     return "Fonts/OpenSans/OpenSansRegular";
                case 5:     return "Fonts/OpenSans/OpenSansLight";
                case 6:     return "Fonts/TESFonts/Kingthings Exeter";
                case 7:     return "Fonts/TESFonts/Kingthings Petrock";
                case 8:     return "Fonts/TESFonts/Kingthings Petrock light";
                case 9:     return "Fonts/TESFonts/MorrisRomanBlack";
                case 10:    return "Fonts/TESFonts/oblivion-font";
                case 11:    return "Fonts/TESFonts/Planewalker";
            }

            throw new ArgumentException(string.Format("Undefined fontID: {0}", fontID));
        }

        #endregion
    }
}


text:
package org.apache.tapestry5.internal.services.assets;

import java.util.Map;

import org.apache.tapestry5.http.services.CompressionAnalyzer;

public class CompressionAnalyzerImpl implements CompressionAnalyzer
{
    private final Map<String, Boolean> configuration;

    public CompressionAnalyzerImpl(Map<String, Boolean> configuration)
    {
        this.configuration = configuration;
    }

    public boolean isCompressable(String contentType)
    {
        if (contentType == null) {
            throw new IllegalStateException("Content type provided to CompressionAnalyzer is null, which is not allowed.");
        }

        int x = contentType.indexOf(';');

        String key = x < 0 ? contentType : contentType.substring(0, x);

        Boolean result = configuration.get(key);

        if (result != null) {
            return result;
        }

        // Now look for a wild card.

        x = contentType.indexOf('/');

        String wildKey = contentType.substring(0, x) + "/*";

        result = configuration.get(wildKey);

        return result == null ? true : result;
    }
}


text: {% include 'django/forms/widgets/textarea.html' %}


text:
PACKAGE_NAME=paping
PACKAGE_VERSION=$1
PACKAGE_URL=https://github.com/koolhazz/paping.git
dnf install git make gcc-c++ -y

if [ -z "$1" ]
  then
    PACKAGE_VERSION=v1.5.5
fi

mkdir -p /home/tester/output
cd /home/tester

OS_NAME=$(cat /etc/os-release | grep ^PRETTY_NAME | cut -d= -f2)

#Remove older package if any
rm -rf $PACKAGE_NAME

#Clone the package
if ! git clone $PACKAGE_URL $PACKAGE_NAME; then
    	echo "------------------$PACKAGE_NAME:clone_fails---------------------------------------"
		echo "$PACKAGE_URL $PACKAGE_NAME" > /home/tester/output/clone_fails
        echo "$PACKAGE_NAME  |  $PACKAGE_URL |  $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Clone_Fails" > /home/tester/output/version_tracker
    	exit 0
fi

cd /home/tester/$PACKAGE_NAME
git checkout $PACKAGE_VERSION

#Install package and dependency
if ! g++ -m64 ./src/print.cpp ./src/stats.cpp ./src/timer.cpp ./src/arguments.cpp ./src/i18n.cpp ./src/host.cpp ./src/socket.cpp ./src/main.cpp -o /bin/paping; then
     	echo "------------------$PACKAGE_NAME:install_fails-------------------------------------"
	echo "$PACKAGE_URL $PACKAGE_NAME" > /home/tester/output/install_fails
	echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Install_Fails" > /home/tester/output/version_tracker
	exit 1
fi

#Run the test cases
cd /home/tester/$PACKAGE_NAME
if ! paping www.google.com -p 80 -c 4; then
	echo "------------------$PACKAGE_NAME:install_success_but_test_fails---------------------"
	echo "$PACKAGE_URL $PACKAGE_NAME" > /home/tester/output/test_fails
	echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Install_success_but_test_Fails" > /home/tester/output/version_tracker
	exit 1
else
	echo "------------------$PACKAGE_NAME:install_&_test_both_success-------------------------"
	echo "$PACKAGE_URL $PACKAGE_NAME" > /home/tester/output/test_success
	echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub  | Pass |  Both_Install_and_Test_Success" > /home/tester/output/version_tracker
	exit 0
fi


text:
int nanosleep(const struct timespec *rqtp, struct timespec *rem) {
  int error = clock_nanosleep(CLOCK_REALTIME, 0, rqtp, rem);
  if (error != 0) {
    errno = error;
    return -1;
  }
  return 0;
}

#if defined(_REENTRANT)
__strong_reference(nanosleep, thrd_sleep);
#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FamilySafetyControl;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Drawing;
using System.Diagnostics;
namespace FamilySafetyControl.Tests
{
    [TestClass()]
    public class TimingTests
    {
        [TestMethod()]
        public void SaveTimingSettingsTest()
        {
            TimingSettings sets = new TimingSettings();
            sets.rules = new string[168];
            // initialize
            // 7*24 = 168
            for (int i = 0; i < 168; i++ )
            {
                sets.rules[i] = "W";
                //Debug.WriteLine(i.ToString() + sets.rules[i]);
                //sets.rules[i * k].color =
            }
            Timing.settings = sets;
            Timing.SaveTimingSettings();
            Assert.IsTrue(true);
        }
    }
}


text:
/*
* JS FILE FOR ADMIN PANEL
* AUTHOR: MERKURY
* DATE: JUNE 2013
* */

$('.dropdown-toggle').dropdown();

jQuery.noConflict()(function($)
{
    var userToDel = "";
    $('.delUser').click(function(){
        $('#delModal').modal('show');
        $('.okDel').attr('href', '../users/block/'+$(this).attr('data-user'));
    });

    $('.delUserFilter').click(function(){
        $('#delModal').modal('show');
        $('.okDelFilter').attr('href', '../../../block/'+$(this).attr('data-user'));
    });

    $('.desEmpresa').click(function(){
        $('#empModal').modal('show');
        $('.okDes').attr('href', '../empresa/disable/'+$(this).attr('data-emp'));
    });

    $('.newMsg').click(function(){
        $('#selectEmpModal').modal('show');

    });

    $('.newGest').click(function(){
        $('#selectClientModal').modal('show');
    });

    $('.newDest').click(function(){
        $('#chatIdCont').val($(this).data('idchat'));
        $('#changeDest').modal('show');
    });

    $('.blockRepo').click(function(){
        $('#repoModal').modal('show');
        $('.okRepoBlock').attr('href', '../repositorio/disable/'+$(this).attr('data-repo'));
    });

    $('.blockRepoFilter').click(function(){
        $('#repoModal').modal('show');
        $('.okRepoBlockFilter').attr('href', '../../../../repositorio/disable/'+$(this).attr('data-repo'));
    });

    $('.blockServ').click(function(){
        $('#servModal').modal('show');
        $('.okServBlock').attr('href', '../servicio/disable/'+$(this).attr('data-serv'));
    });

    $('.blockServFilter').click(function(){
        $('#servModal').modal('show');

        $('.okServBlockFilter').attr('href', '../../../../servicio/disable/'+$(this).attr('data-serv'));
    });

    $('.blockCat').click(function(){
        $('#catModal').modal('show');
        $('.okCatBlock').attr('href', '../categoria/disable/'+$(this).attr('data-cat'));
    });

    $('.blockCatFilter').click(function(){
        $('#catModal').modal('show');
        $('.okCatBlockFilter').attr('href', '../../../../categoria/disable/'+$(this).attr('data-cat'));
    });

    $('.delContacto').click(function(){
        $('#delContacto').modal('show');
        $('.okDel').attr('href', $(this).data('conv'));
    });

    $('.reContacto').click(function(){
        $('#reContacto').modal('show');
        $('.okRe').attr('href', $(this).data('conv'));
    });

    $('.showcc').click(function(){
        var cc = $(this).data('info');

        var first = cc.slice(0, 4);
        var second = cc.slice(4, 8);
        var third = cc.slice(8, 10);
        var fourth = cc.slice(10);

        var ccf = first + ' - ' + second + ' - ' + third + ' - ' + fourth;

        $('.cccn').html(ccf);
        $('#ccModal').modal('show');
    });

    $('.closeMod').click(function(){
       $(this).parent().parent().modal('hide');
    });

//CONTROLADOR PARA LA SELECCION DE EMPRESA PRO EL USUARIO MULTEMPRESA - USER
    $('#sel_empresa').change(function(){
        var idEmp = $(this).val();

        var path = window.location.pathname;
        var check_path = path.split('/admin/');

        if(idEmp != 'none' && check_path[1].indexOf('filter') == -1)
        {
            if(check_path[1].indexOf('view') != -1)
            {
                window.location = '../../../filter/'+idEmp+'/list/1';
            }else
            {
                window.location = '../users/filter/'+idEmp+'/list/1';
            }
        }else if(idEmp != 'none' && check_path[1].indexOf('filter') != -1)
        {

            window.location = '../../../filter/'+idEmp+'/list/1';
        }

    });

    //CONTROLADOR PARA LA SELECCION DE USURIO ROL
    $('#sel_role').change(function(){
        var idRol = $(this).val();
        var empId = $(this).attr('data-emp');

        var path = window.location.pathname;
        var check_path = path.split('/admin/');

        if(idRol != 'none' && empId != 'none' && check_path[1].indexOf('filter') == -1)
        {
            window.location = '../../'+idRol+'/'+empId+'/1';
        }else if(empId != 'none' && check_path[1].indexOf('filter') != -1)
        {
            window.location = '../../../view/'+idRol+'/'+empId+'/1';
        }

    });

    //CONTROLADOR PARA LA SELECCION DE EMPRESA POR EL USUARIO MULTEMPRESA - REPO
    $('#sel_empresaRepo').change(function(){
        var idEmp = $(this).val();

        var path = window.location.pathname;
        var check_path = path.split('/admin/');

        if(idEmp != 'none' && check_path[1].indexOf('filter') == -1)
        {
            window.location = '../repositorios/filter/'+idEmp+'/list/1';
        }else if(idEmp != 'none' && check_path[1].indexOf('filter') != -1)
        {
            window.location = '../../../filter/'+idEmp+'/list/1';
        }

    });

    //CONTROLADOR PARA LA SELECCION DE EMPRESA POR EL USUARIO MULTEMPRESA - USER
    $('#sel_empresaServ').change(function(){
        var idEmp = $(this).val();

        var path = window.location.pathname;
        var check_path = path.split('/admin/');

        if(idEmp != 'none' && check_path[1].indexOf('filter') == -1)
        {
            window.location = '../servicios/filter/'+idEmp+'/list/1';
        }else if(idEmp != 'none' && check_path[1].indexOf('filter') != -1)
        {

            window.location = '../../../filter/'+idEmp+'/list/1';
        }

    });

    //CONTROLADOR PARA LA SELECCION DE EMPRESA POR EL USUARIO MULTEMPRESA - USER
    $('#sel_empresaCat').change(function(){
        var idEmp = $(this).val();

        var path = window.location.pathname;
        var check_path = path.split('/admin/');

        if(idEmp != 'none' && check_path[1].indexOf('filter') == -1)
        {
            window.location = '../categorias/filter/'+idEmp+'/list/1';
        }else if(idEmp != 'none' && check_path[1].indexOf('filter') != -1)
        {

            window.location = '../../../filter/'+idEmp+'/list/1';
        }

    });

    //CONTROLADOR PARA LA SELECCION DE EMPRESA PORA FILTRO GESTIONES
    $('#sel_empresaGestion').change(function(){
        var idEmp = $(this).val();

        var path = window.location.pathname;
        var check_path = path.split('/admin/');

        if(idEmp != 'none' && check_path[1].indexOf('filter') == -1)
        {

            window.location = '../filter/'+idEmp+'/list/1';
        }else if(idEmp != 'none' && check_path[1].indexOf('filter') != -1 && check_path[1].indexOf('by') == -1 )
        {

            window.location = '../../../filter/'+idEmp+'/list/1';
        }else if(idEmp != 'none' && check_path[1].indexOf('by') != -1)
        {
            check_path_2 = path.split('/by/');

            check_path_3 = check_path_2[0].split('/filter/');

           window.location = check_path_3[0] + '/filter/'+ idEmp + '/list/1';
        }

    });

    $('#sel_estadoGest').change(function(){
        var idEst = $(this).val();

        //gestiones/filter/{empId}/list/{page}/by/{estId}/{ord}

        var path = window.location.pathname;
        var check_path = path.split('/admin/');

        if(idEst != 'none' && check_path[1].search('filter') != -1 && check_path[1].search('by') == -1 )
        {
            window.location = '../list/1/by/'+idEst+'/0';
        }
        if(idEst != 'none' && check_path[1].search('filter') != -1 && check_path[1].search('by') != -1)
        {
            check_path_2 = path.split('/by/');
            window.location = check_path_2[0] + '/by/'+idEst+'/0'
        }

    });

    $('#sel_estadoGestion').change(function(){
        var idEst = $(this).val();
        var idGest = $('#estForm').attr('data-foo');
        var est = $('#estForm').attr('data-check');

       if(est != idEst)
       {
           if(idEst != 'none' && idGest > 0)
           {
               window.location = '../gestion/update/'+idGest+'/to/'+idEst;
           }
       }

    });

    /***NUEVO MENSAJE ADMIN***/
    $('.newMsgAdmin').click(function(){
        var empId = $('.empName:selected').val();

        if(empId != 'none' && empId > 0)
        {
            window.location = '../messages/new/admin/conv/'+empId;
        }
    });

    /**** NUEVO DESTINATARIO ***/
    $('.okNewDest').click(function(){
        var userId = $('.userId:selected').val();
        var chatId = $('#chatIdCont').val();

        if(userId != 'none' && userId > 0 && chatId > 0)
        {
            window.location = '../messages/change/reciever/'+chatId+'/to/'+ userId;
        }

    });

    /****BORRAR NOTIFICACIONES ADMIN****/

    $('.delNotif').click(function(){
        var table = $(this).closest('table').children('tbody').children('tr').length;
        var url = $(this).data('path');

        $(this).parent().parent().fadeOut('slow', function(){
            $(this).remove();
            if(table-1 == 0)
            {
                $('#notifCont').append('

No existen notificaciones

');
            }
            $.post(url);
        });
    });

    /*****NUEVA GESTIÓN PANEL ADMINISTRACIÓN*********/
    $('.newGestAdmin').click(function(){
        var clientId = $('.cliName:selected').val();
        var path = $('.cliName:selected').data('url');

        if(clientId != 'none' && clientId > 0)
        {
            window.location = path;
        }
    });

    /*****MOSTRAR FORM DE BUSQUEDA******/

    $('.showS').click(function(){
        $(this).fadeOut('slow', function(){
            $('.formContainer').show('slow');
        });

    });

    $('.hideS').click(function(){
        event.preventDefault();
        $('.formContainer').hide('slow', function(){
            $('.showS').show('slow');
        });
    });

    $('.toolTip').popover(function(){
        event.preventDefault();
    });

    $('.refreshForm').click(function(){
        var path = $(this).data('path');
        window.location = path;
    });

    /**SELECCION DE SERVICIOS PARA AMPLIACIÓN CONTRATACIÓN**/

    $('.selectServBut').click(function(){
        var selectID = $(this).data('info');
        var toHighligth = $(this).parent().parent();

        $('.checkservice input:checkbox').each(function(){
            if($(this).val() == selectID)
            {
                if(!$(this).is(':checked'))
                {
                    toHighligth.addClass('serv_selected');
                    $(this).prop('checked', true);

                }else
                {
                    toHighligth.removeClass('serv_selected');
                    $(this).prop('checked', false);

                }
            }
        });
    });

    $('.checkservice input:checkbox').each(function(){
       if($(this).is(':checked'))
       {
            var value = $(this).val();
            $('.thumbnail').each(function(){
                if($(this).data('val') == value)
                {
                    $(this).addClass('serv_selected');
                }
            })
       }
    });

});


text:
namespace AsignadorCitas
{
    partial class FrmPrincipal
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.ofdElegirExcel = new System.Windows.Forms.OpenFileDialog();
            this.menuStrip1 = new System.Windows.Forms.MenuStrip();
            this.archivoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.importarAchivoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.salirToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.agentesServicioToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.prgbAsignacion = new System.Windows.Forms.ProgressBar();
            this.btnAsignar = new System.Windows.Forms.Button();
            this.label3 = new System.Windows.Forms.Label();
            this.lblCantidadCitas = new System.Windows.Forms.Label();
            this.sfdExportar = new System.Windows.Forms.SaveFileDialog();
            this.menuStrip1.SuspendLayout();
            this.SuspendLayout();
            //
            // ofdElegirExcel
            //
            this.ofdElegirExcel.Filter = "Excel|*.xlsx";
            //
            // menuStrip1
            //
            this.menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
            this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.archivoToolStripMenuItem,
            this.agentesServicioToolStripMenuItem});
            this.menuStrip1.Location = new System.Drawing.Point(0, 0);
            this.menuStrip1.Name = "menuStrip1";
            this.menuStrip1.Padding = new System.Windows.Forms.Padding(4, 2, 0, 2);
            this.menuStrip1.Size = new System.Drawing.Size(593, 24);
            this.menuStrip1.TabIndex = 2;
            this.menuStrip1.Text = "menuStrip1";
            //
            // archivoToolStripMenuItem
            //
            this.archivoToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.importarAchivoToolStripMenuItem,
            this.salirToolStripMenuItem});
            this.archivoToolStripMenuItem.Name = "archivoToolStripMenuItem";
            this.archivoToolStripMenuItem.Size = new System.Drawing.Size(60, 20);
            this.archivoToolStripMenuItem.Text = "Archivo";
            //
            // importarAchivoToolStripMenuItem
            //
            this.importarAchivoToolStripMenuItem.Name = "importarAchivoToolStripMenuItem";
            this.importarAchivoToolStripMenuItem.Size = new System.Drawing.Size(158, 22);
            this.importarAchivoToolStripMenuItem.Text = "Importar achivo";
            this.importarAchivoToolStripMenuItem.Click += new System.EventHandler(this.importarAchivoToolStripMenuItem_Click);
            //
            // salirToolStripMenuItem
            //
            this.salirToolStripMenuItem.Name = "salirToolStripMenuItem";
            this.salirToolStripMenuItem.Size = new System.Drawing.Size(158, 22);
            this.salirToolStripMenuItem.Text = "Salir";
            this.salirToolStripMenuItem.Click += new System.EventHandler(this.salirToolStripMenuItem_Click);
            //
            // agentesServicioToolStripMenuItem
            //
            this.agentesServicioToolStripMenuItem.Name = "agentesServicioToolStripMenuItem";
            this.agentesServicioToolStripMenuItem.Size = new System.Drawing.Size(106, 20);
            this.agentesServicioToolStripMenuItem.Text = "Agentes Servicio";
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label1.Location = new System.Drawing.Point(80, 37);
            this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(147, 13);
            this.label1.TabIndex = 4;
            this.label1.Text = "Estado de la importación";
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label2.Location = new System.Drawing.Point(85, 166);
            this.label2.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(143, 13);
            this.label2.TabIndex = 6;
            this.label2.Text = "Estado de la asignación";
            //
            // prgbAsignacion
            //
            this.prgbAsignacion.Location = new System.Drawing.Point(87, 182);
            this.prgbAsignacion.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
            this.prgbAsignacion.Name = "prgbAsignacion";
            this.prgbAsignacion.Size = new System.Drawing.Size(425, 19);
            this.prgbAsignacion.Style = System.Windows.Forms.ProgressBarStyle.Continuous;
            this.prgbAsignacion.TabIndex = 5;
            //
            // btnAsignar
            //
            this.btnAsignar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.btnAsignar.Location = new System.Drawing.Point(117, 118);
            this.btnAsignar.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
            this.btnAsignar.Name = "btnAsignar";
            this.btnAsignar.Size = new System.Drawing.Size(358, 33);
            this.btnAsignar.TabIndex = 7;
            this.btnAsignar.Text = "Asignar Citas";
            this.btnAsignar.UseVisualStyleBackColor = true;
            this.btnAsignar.Click += new System.EventHandler(this.btnAsignar_Click);
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(80, 62);
            this.label3.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(93, 13);
            this.label3.TabIndex = 8;
            this.label3.Text = "Cantidad de Citas:";
            //
            // lblCantidadCitas
            //
            this.lblCantidadCitas.AutoSize = true;
            this.lblCantidadCitas.Location = new System.Drawing.Point(176, 62);
            this.lblCantidadCitas.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
            this.lblCantidadCitas.Name = "lblCantidadCitas";
            this.lblCantidadCitas.Size = new System.Drawing.Size(13, 13);
            this.lblCantidadCitas.TabIndex = 9;
            this.lblCantidadCitas.Text = "0";
            //
            // sfdExportar
            //
            this.sfdExportar.CreatePrompt = true;
            this.sfdExportar.Filter = "Excel|*.xlsx";
            //
            // FrmPrincipal
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(593, 318);
            this.Controls.Add(this.lblCantidadCitas);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.btnAsignar);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.prgbAsignacion);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.menuStrip1);
            this.MainMenuStrip = this.menuStrip1;
            this.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
            this.MaximizeBox = false;
            this.MaximumSize = new System.Drawing.Size(609, 357);
            this.MinimumSize = new System.Drawing.Size(609, 357);
            this.Name = "FrmPrincipal";
            this.Text = "Asignador Citas";
            this.menuStrip1.ResumeLayout(false);
            this.menuStrip1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.OpenFileDialog ofdElegirExcel;
        private System.Windows.Forms.MenuStrip menuStrip1;
        private System.Windows.Forms.ToolStripMenuItem archivoToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem salirToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem agentesServicioToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem importarAchivoToolStripMenuItem;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.ProgressBar prgbAsignacion;
        private System.Windows.Forms.Button btnAsignar;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label lblCantidadCitas;
        private System.Windows.Forms.SaveFileDialog sfdExportar;
    }
}


text:
package com.amazonaws.services.glacier.model.transform;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.List;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.glacier.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;

/**
 * Complete Multipart Upload Request Marshaller
 */
public class CompleteMultipartUploadRequestMarshaller implements Marshaller<Request<CompleteMultipartUploadRequest>, CompleteMultipartUploadRequest> {

    public Request<CompleteMultipartUploadRequest> marshall(CompleteMultipartUploadRequest completeMultipartUploadRequest) {
		if (completeMultipartUploadRequest == null) {
		    throw new AmazonClientException("Invalid argument passed to marshall(...)");
		}

        Request<CompleteMultipartUploadRequest> request = new DefaultRequest<CompleteMultipartUploadRequest>(completeMultipartUploadRequest, "AmazonGlacier");
        String target = "Glacier.CompleteMultipartUpload";
        request.addHeader("X-Amz-Target", target);
        request.addHeader("Content-Type", "application/x-amz-json-1.0");

        request.setHttpMethod(HttpMethodName.POST);
        if (completeMultipartUploadRequest.getArchiveSize() != null)
        	request.addHeader("x-amz-archive-size", StringUtils.fromString(completeMultipartUploadRequest.getArchiveSize()));

        if (completeMultipartUploadRequest.getChecksum() != null)
        	request.addHeader("x-amz-sha256-tree-hash", StringUtils.fromString(completeMultipartUploadRequest.getChecksum()));

        String uriResourcePath = "/{accountId}/vaults/{vaultName}/multipart-uploads/{uploadId}";
        uriResourcePath = uriResourcePath.replace("{accountId}", getString(completeMultipartUploadRequest.getAccountId()));
        uriResourcePath = uriResourcePath.replace("{vaultName}", getString(completeMultipartUploadRequest.getVaultName()));
        uriResourcePath = uriResourcePath.replace("{uploadId}", getString(completeMultipartUploadRequest.getUploadId()));

        uriResourcePath = uriResourcePath.replaceAll("//", "/");

        if (uriResourcePath.contains("?")) {
            String queryString = uriResourcePath.substring(uriResourcePath.indexOf("?") + 1);
            uriResourcePath    = uriResourcePath.substring(0, uriResourcePath.indexOf("?"));

            for (String s : queryString.split("[;&]")) {
                String[] nameValuePair = s.split("=");
                if (nameValuePair.length == 2) {
                    request.addParameter(nameValuePair[0], nameValuePair[1]);
                } else {
                    request.addParameter(s, null);
                }
            }
        }

        request.setResourcePath(uriResourcePath);

        request.setContent(new ByteArrayInputStream(new byte[0]));

        return request;
    }

    private String getString(String s) {
        if (s == null) return "";
        return s;
    }
}


text:
using base::android::JavaParamRef;
using base::android::JavaRef;
using base::android::ScopedJavaLocalRef;
using base::android::ScopedJavaGlobalRef;

class SurveyInfoBarDelegate : public infobars::InfoBarDelegate {
 public:
  SurveyInfoBarDelegate(JNIEnv* env,
                        int displayLogoResourceId,
                        jobject surveyInfoBarDelegate)
      : display_logo_resource_id_(displayLogoResourceId),
        survey_info_bar_delegate_(
            ScopedJavaGlobalRef<jobject>(env, surveyInfoBarDelegate)) {}

  ~SurveyInfoBarDelegate() override {}

  infobars::InfoBarDelegate::InfoBarIdentifier GetIdentifier() const override {
    return InfoBarDelegate::InfoBarIdentifier::SURVEY_INFOBAR_ANDROID;
  }

  bool EqualsDelegate(infobars::InfoBarDelegate* delegate) const override {
    if (delegate->GetIdentifier() != GetIdentifier())
      return false;
    return true;
  }

  int GetDisplayLogoResourceId() { return display_logo_resource_id_; }

  const ScopedJavaGlobalRef<jobject>& GetSurveyInfoBarDelegate() {
    return survey_info_bar_delegate_;
  }

 private:
  int display_logo_resource_id_;
  ScopedJavaGlobalRef<jobject> survey_info_bar_delegate_;
};

SurveyInfoBar::SurveyInfoBar(std::unique_ptr<SurveyInfoBarDelegate> delegate)
    : infobars::InfoBarAndroid(std::move(delegate)) {}

SurveyInfoBar::~SurveyInfoBar() = default;

base::android::ScopedJavaLocalRef<jobject> SurveyInfoBar::GetTab(
    JNIEnv* env,
    const JavaParamRef<jobject>& obj) {
  content::WebContents* web_contents =
      infobars::ContentInfoBarManager::WebContentsFromInfoBar(this);
  DCHECK(web_contents);

  TabAndroid* tab_android = TabAndroid::FromWebContents(web_contents);
  return tab_android->GetJavaObject();
}

infobars::InfoBarDelegate* SurveyInfoBar::GetDelegate() {
  return delegate();
}

void SurveyInfoBar::ProcessButton(int action) {}

ScopedJavaLocalRef<jobject> SurveyInfoBar::CreateRenderInfoBar(
    JNIEnv* env,
    const ResourceIdMapper& resource_id_mapper) {
  SurveyInfoBarDelegate* survey_delegate =
      static_cast<SurveyInfoBarDelegate*>(delegate());
  return Java_SurveyInfoBar_create(
      env,
      survey_delegate->GetDisplayLogoResourceId(),
      survey_delegate->GetSurveyInfoBarDelegate());
}

void JNI_SurveyInfoBar_Create(
    JNIEnv* env,
    const JavaParamRef<jobject>& j_web_contents,
    jint j_display_logo_resource_id,
    const JavaParamRef<jobject>& j_survey_info_bar_delegate) {
  infobars::ContentInfoBarManager* manager =
      infobars::ContentInfoBarManager::FromWebContents(
          content::WebContents::FromJavaWebContents(j_web_contents));

  manager->AddInfoBar(
      std::make_unique<SurveyInfoBar>(std::make_unique<SurveyInfoBarDelegate>(
          env, j_display_logo_resource_id, j_survey_info_bar_delegate.obj())));
}


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

	<title>FCKeditor - Sample</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="robots" content="noindex, nofollow" />
	<link href="../sample.css" rel="stylesheet" type="text/css" />

		FCKeditor - JavaScript - Sample 11

		This sample shows a form with two FCKeditor instance loaded inside an IFRAME. Both instances share the same
		toolbar, available in the main page (top).


text:
    <title>Backbone.BootstrapModal example</title>

    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">

Backbone.BootstrapModal example


text:
module MergePullRequest where

import qualified Github.PullRequests as Github
import Github.Auth

main :: IO ()
main = do
  mergeResult  <- Github.updatePullRequest (GithubOAuth "authtoken") "repoOwner" "repoName" 22 (EditPullRequest { editPullRequestTitle = Just "Brand new title", editPullRequestBody = Nothing, editPullRequestState = Just EditPullRequestStateClosed })
  case mergeResult of
       (Left err) -> putStrLn $ "Error: " ++ (show err)
       (Right dpr) -> putStrLn . show $ dpr


text:
package io.runidle.testing.tests.spring;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = {"com.comcast.ace.testing.tests.spring"})
public class Configuration1 {
    @Bean
    public TestBean testBean() {
        return new TestBean();
    }

    @Bean
    public TestBean testBean3() {
        return new TestBean3();
    }
}


text:
package br.usp.each.saeg.code.forest.metaphor;

/**
 * @author Danilo Mutti (dmutti@gmail.com)
 */
public enum Size {

    BIG(1F, 3F, .66F), NORMAL(.66F, 1.8F, .33F), SMALL(.5F, 1.5F, .33F), EXTRA_SMALL(.33F, 1F, .33F);

    private final float radius;
    private final float step;
    private final float maxHorizontal;

    Size(float radius, float height, float maxHorizontal) {
        this.radius = radius;
        this.step = height;
        this.maxHorizontal = maxHorizontal;
    }

    public float getRadius() {
        return radius;
    }
    public float getStep() {
        return step;
    }
    public float getMaxHorizontal() {
        return maxHorizontal;
    }

    public static Size from(float score) {
        if (score >= .85F) {
            return BIG;
        }
        if (score >= .65F) {
            return NORMAL;
        }
        if (score >= .45) {
            return SMALL;
        }
        return EXTRA_SMALL;
    }
}


text:
This module is intended to be used to manage remote OpenWRT installations that act as network routers. The
functionality exposed by the module should be a simplified subset of the functionality provided by the Luci web
interface.

## Functional Requirements ##

#### Port Forwarding Management ###
It should provide the capability to
* list all the active port forwarding rules
* delete a specific port forwarding rule
* modify a specific port forwarding rule
* create a new port forwarding rule

#### System User Name and Password Management ####
It should provide the capability to
* change the password of a specific user
* create a new user

#### Network management ####
It should provide the capability to
* retrieve the network information associated with all the available network interfaces
* retrieve the network information associated with a specific available network interface
* set the network information for a specific network interface
* ping an external network location from within the OpenWRT instance

#### Configuration backup ####
It should provide the capability to
* archive and compress the configuration files and respond with the compressed binary tar file

## Non-functional Requirements ##
* Pure Python code only
* Should be usable on Python 2.7

## Architecture ##
At the core of the module there should be an internal abstraction layer responsible for relaying all the RPC messages
back and forth while being presented as regular Python method calls of the exported RPC libraries.

The actual top-layer functionality provided by the module should be grouped by similarity so as not to clutter the
top-level interface.

### Fault-tolerance ###
Failing operations should never pass silently. Errors should always be propagated as Python exceptions.

## Testing ##
*TODO*


text:
package org.perfidix.element;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

/**
 * This class represents a shuffle random arrangement of elements. All elements are shuffled and executed in a complete
 * random order.
 *
 * @author Sebastian Graf, University of Konstanz
 */
public final class ShuffleMethodArrangement extends AbstractMethodArrangement {

    /**
     * Seed for the random arrangement of the elements.
     */
    private static final long SEED = 1L;

    /**
     * Constructor for shuffle arrangement. That means that the order which is given as an input is shuffled in a random
     * way and given back as the output. The order is complete randomlike and depends on a seed.
     *
     * @param elements with benchmarkable elements.
     */
    ShuffleMethodArrangement(final List<BenchmarkElement> elements) {
        super(elements);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected List<BenchmarkElement> arrangeList(final List<BenchmarkElement> methods) {
        final Random ran = new Random(SEED);
        final List<BenchmarkElement> inputList = new LinkedList<BenchmarkElement>();
        inputList.addAll(methods);
        Collections.shuffle(inputList, ran);
        return inputList;
    }
}


text:
import json

from sovrin_client.agent.walleted_agent import WalletedAgent
from sovrin_client.test.agent.mock_backend_system import MockBackendSystem

import anoncreds.protocol.types
from sovrin_client.client.wallet.wallet import Wallet
from sovrin_client.test.constants import primes
from sovrin_common.identity import Identity
from sovrin_common.constants import TRUST_ANCHOR
from sovrin_node.pool.local_pool import create_local_pool

# noinspection PyUnresolvedReferences
from sovrin_node.test.conftest import tdir, conf, nodeSet, tconf, \
    updatedPoolTxnData, updatedDomainTxnFile, txnPoolNodeSet, poolTxnData, \
    dirName, tdirWithDomainTxns, tdirWithPoolTxns, \
    domainTxnOrderedFields, genesisTxns, stewardWallet, poolTxnStewardData, \
    poolTxnStewardNames, trusteeWallet, trusteeData, poolTxnTrusteeNames, \
    patchPluginManager, txnPoolNodesLooper, tdirWithPoolTxns, \
    poolTxnNodeNames, allPluginsPath, tdirWithNodeKeepInited, testNodeClass, \
    genesisTxns

BANK_SEED = b'BANK0000000000000000000000000000'

class RefAgent(WalletedAgent):

    def create_connection_request(self, internal_id, name):

        nonce = str(self.verifier.generateNonce())
        # endpoint = self.endpoint.host_address()
        # TODO: this should be done by endpoint
        endpoint = "127.0.0.1" + ":" + str(self.endpoint.ha[1])

        msg = {'connection-request': {
            'name': self.name,
            'identifier': self._wallet.defaultId,
            'nonce': nonce,
            'endpoint': endpoint,
            'verkey': self._wallet.getVerkey(self.wallet.defaultId)
        },
            'sig': None
        }

        self._invites[nonce] = (internal_id, name)

        signature = self.wallet.signMsg(msg, self.wallet.defaultId)

        msg['sig'] = signature

        return json.dumps(msg)

def test_end_to_end(tconf):
    base_dir = tconf.baseDir

    print('*' * 20)
    print(base_dir)
    print('*' * 20)

    with create_local_pool(base_dir) as network:

        print(network.genesis_transactions)

        network.runFor(5)

        client = network.create_client(5555)

        bank_wallet = Wallet()
        bank_agent = RefAgent(name="bank",
                              basedirpath=base_dir,
                              client=client,
                              wallet=bank_wallet,
                              port=8787,
                              endpointArgs={'seed': BANK_SEED,
                                            'onlyListener': True})

        network.add(bank_agent)

        bank_id, bank_verkey = bank_agent.new_identifier(seed=BANK_SEED)

        print(bank_id)
        print(bank_verkey)

        s1_agent = network.steward_agent()

        s1_agent.publish_trust_anchor(Identity(identifier=bank_id,
                                               verkey=bank_verkey,
                                               role=TRUST_ANCHOR))
        network.runFor(5)

        # this allows calling asynchronous functions from a synchronous context
        run_async = network.run

        bank_attribute_definition = anoncreds.protocol.types.AttribDef(
            'basic', [
                anoncreds.protocol.types.AttribType(
                    'title', encode=True), anoncreds.protocol.types.AttribType(
                    'first_name', encode=True), anoncreds.protocol.types.AttribType(
                    'last_name', encode=True), anoncreds.protocol.types.AttribType(
                        'address_1', encode=True), anoncreds.protocol.types.AttribType(
                            'address_2', encode=True), anoncreds.protocol.types.AttribType(
                                'address_3', encode=True), anoncreds.protocol.types.AttribType(
                                    'postcode_zip', encode=True), anoncreds.protocol.types.AttribType(
                                        'date_of_birth', encode=True), anoncreds.protocol.types.AttribType(
                                            'account_type', encode=True), anoncreds.protocol.types.AttribType(
                                                'year_opened', encode=True), anoncreds.protocol.types.AttribType(
                                                    'account_status', encode=True)])

        bank_agent.add_attribute_definition(bank_attribute_definition)

        backend = MockBackendSystem(bank_attribute_definition)

        alices_id_in_banks_system = 1999891343
        bobs_id_in_banks_system = 2911891343

        backend.add_record(alices_id_in_banks_system,
                           title='Mrs.',
                           first_name='Alicia',
                           last_name='Garcia',
                           address_1='H-301',
                           address_2='Street 1',
                           address_3='UK',
                           postcode_zip='G61 3NR',
                           date_of_birth='December 28, 1990',
                           account_type='savings',
                           year_opened='2000',
                           account_status='active')
        backend.add_record(bobs_id_in_banks_system,
                           title='Mrs.',
                           first_name='Jay',
                           last_name='Raj',
                           address_1='222',
                           address_2='Baker Street',
                           address_3='UK',
                           postcode_zip='G61 3NR',
                           date_of_birth='January 15, 1980',
                           account_type='savings',
                           year_opened='1999',
                           account_status='active')

        bank_agent.set_issuer_backend(backend)

        schema_id = run_async(
            bank_agent.publish_schema('basic',
                                      schema_name='Bank Membership',
                                      schema_version='1.0'))

        # NOTE: do NOT use known primes in a non-test environment

        issuer_pub_key, revocation_pub_key = run_async(
            bank_agent.publish_issuer_keys(schema_id,
                                           p_prime=primes["prime1"][0],
                                           q_prime=primes["prime1"][1]))
        print(issuer_pub_key)
        print(revocation_pub_key)

        # TODO: Not implemented yet
        # accPK = run_async(bank_agent.publish_revocation_registry(
        #     schema_id=schema_id))

        # print(accPK)

        run_async(bank_agent._set_available_claim_by_internal_id(
            alices_id_in_banks_system, schema_id))
        run_async(bank_agent._set_available_claim_by_internal_id(
            bobs_id_in_banks_system, schema_id))

        alice_wallet = Wallet()
        alice_agent = RefAgent(name="Alice",
                               basedirpath=base_dir,
                               client=client,
                               wallet=alice_wallet,
                               port=8786)

        network.add(alice_agent)

        network.runFor(1)

        request = bank_agent.create_connection_request(
            alices_id_in_banks_system, "Alice")

        # Transfer of this request happens out-of-band (website, QR code, etc)

        alices_link_to_bank = alice_agent.load_request_str(request)

        # notice the link is not accepted
        print(alices_link_to_bank)

        alice_agent.accept_request(alices_link_to_bank)

        network.runFor(10)

        # notice that the link is accepted
        print(alices_link_to_bank)

        banks_link_to_alice = bank_agent.get_link_by_name(
            alices_id_in_banks_system)

        # note the available claims are now there
        print(banks_link_to_alice)

        claim_to_request = alices_link_to_bank.find_available_claim(
            name='Bank Membership')

        print(claim_to_request)

        run_async(alice_agent.send_claim(alices_link_to_bank,
                                         claim_to_request))
        network.runFor(5)

        claim = run_async(alice_agent.get_claim(schema_id))
        print(claim)

        # ########
        # # PROOF
        # ########
        # bank_agent._proofRequestsSchema['Address'] = {
        #     "name": "Address",
        #     "version": "0.2",
        #     "attributes": {
        #         "address_1": "string",
        #         "address_2": "string",
        #         "address_3": "string",
        #         "state": "string",
        #         "postcode_zip": "string",
        #     },
        #     "verifiableAttributes": ["postcode_zip"]
        # }
        #
        # bank_agent.sendProofReq(banks_link_to_alice, 'Address')
        #
        # network.runFor(3)
        # print()


text:
Send Content to our website, and store them.

Working on it!


text:
<Record>
<Term>Deaf-Blind Disorders</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<ParentTerm>Deafness</ParentTerm>
<ParentTerm>Blindness</ParentTerm>
<ParentTerm>Abnormalities, Multiple</ParentTerm>
<ClassificationPath>Nervous System Diseases/Neurologic Manifestations/Sensation Disorders/Vision Disorders/Blindness/Deaf-Blind Disorders</ClassificationPath>
<ClassificationPath>Pathological Conditions, Signs and Symptoms/Signs and Symptoms/Neurologic Manifestations/Sensation Disorders/Hearing Disorders/Hearing Loss/Deafness/Deaf-Blind Disorders</ClassificationPath>
<ClassificationPath>Otorhinolaryngologic Diseases/Ear Diseases/Hearing Disorders/Hearing Loss/Deafness/Deaf-Blind Disorders</ClassificationPath>
<ClassificationPath>Pathological Conditions, Signs and Symptoms/Signs and Symptoms/Neurologic Manifestations/Sensation Disorders/Vision Disorders/Blindness/Deaf-Blind Disorders</ClassificationPath>
<ClassificationPath>Eye Diseases/Vision Disorders/Blindness/Deaf-Blind Disorders</ClassificationPath>
<ClassificationPath>Nervous System Diseases/Neurologic Manifestations/Sensation Disorders/Hearing Disorders/Hearing Loss/Deafness/Deaf-Blind Disorders</ClassificationPath>
<ClassificationPath>Congenital, Hereditary, and Neonatal Diseases and Abnormalities/Congenital Abnormalities/Abnormalities, Multiple/Deaf-Blind Disorders</ClassificationPath>
<BroaderTerm>Pathological Conditions, Signs and Symptoms</BroaderTerm>
<BroaderTerm>Hearing Disorders</BroaderTerm>
<BroaderTerm>Blindness</BroaderTerm>
<BroaderTerm>Nervous System Diseases</BroaderTerm>
<BroaderTerm>Deaf-Blind Disorders</BroaderTerm>
<BroaderTerm>Abnormalities, Multiple</BroaderTerm>
<BroaderTerm>Eye Diseases</BroaderTerm>
<BroaderTerm>Neurologic Manifestations</BroaderTerm>
<BroaderTerm>Signs and Symptoms</BroaderTerm>
<BroaderTerm>Congenital, Hereditary, and Neonatal Diseases and Abnormalities</BroaderTerm>
<BroaderTerm>Vision Disorders</BroaderTerm>
<BroaderTerm>Ear Diseases</BroaderTerm>
<BroaderTerm>Hearing Loss</BroaderTerm>
<BroaderTerm>Otorhinolaryngologic Diseases</BroaderTerm>
<BroaderTerm>Deafness</BroaderTerm>
<BroaderTerm>Congenital Abnormalities</BroaderTerm>
<BroaderTerm>Sensation Disorders</BroaderTerm>
<ChildTerm>Usher Syndromes</ChildTerm>
<ChildTerm>Wolfram Syndrome</ChildTerm>
<Synonym>Prelingual Deaf Blind Disorders</Synonym>
<Synonym>Deaf Blind Syndromes</Synonym>
<Synonym>Prelingual Deafness-Blindness</Synonym>
<Synonym>Deaf-Blindness Disorder</Synonym>
<Synonym>Vision and Hearing Loss</Synonym>
<Synonym>Deafness-Blindness</Synonym>
<Synonym>Deaf-Mutism-Blind Disorder</Synonym>
<Synonym>Deaf-Blind Disorders</Synonym>
<Synonym>Blind-Deaf Disorder</Synonym>
<Synonym>Blind Deaf Disorders</Synonym>
<Synonym>Blindness Deafness</Synonym>
<Synonym>Blindness-Deafness</Synonym>
<Synonym>Prelingual Deafness-Blindnesses</Synonym>
<Synonym>Deaf-Mutism-Blind Disorders</Synonym>
<Synonym>Blind-Deaf Disorders</Synonym>
<Synonym>Deafness Blindness</Synonym>
<Synonym>Deaf Blind Disorders</Synonym>
<Synonym>Deaf-Blind Syndrome</Synonym>
<Synonym>Deaf Mutism Blind Disorders</Synonym>
<Synonym>Prelingual Deaf-Blind Disorder</Synonym>
<Synonym>Deaf-Blindness Disorders</Synonym>
<Synonym>Deaf-Blind Syndromes</Synonym>
<Synonym>Hearing and Vision Loss</Synonym>
<Synonym>Prelingual Deaf-Blind Disorders</Synonym>
<Synonym>Deaf-Blind Disorder</Synonym>
<Synonym>Prelingual Deafness Blindness</Synonym>
<Synonym>Deaf Blindness Disorders</Synonym>
<Description>The absence of both hearing and vision.</Description>
<Source>MeSH</Source>
</Record>


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

<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
<title>TimeToLiveLogCleaner xref</title>
<link type="text/css" rel="stylesheet" href="../../../../../../stylesheet.css" />

View Javadoc

1
18  package org.apache.hadoop.hbase.master.cleaner;
19
20  import org.apache.commons.logging.Log;
21  import org.apache.commons.logging.LogFactory;
22  import org.apache.hadoop.classification.InterfaceAudience;
23  import org.apache.hadoop.conf.Configuration;
24  import org.apache.hadoop.fs.FileStatus;
25  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
26
27  /**
28   * Log cleaner that uses the timestamp of the hlog to determine if it should
29   * be deleted. By default they are allowed to live for 10 minutes.
30   */
31  @InterfaceAudience.Private
32  public class TimeToLiveLogCleaner extends BaseLogCleanerDelegate {
33    static final Log LOG = LogFactory.getLog(TimeToLiveLogCleaner.class.getName());
34    // Configured time a log can be kept after it was closed
35    private long ttl;
36    private boolean stopped = false;
37
38    @Override
39    public boolean isLogDeletable(FileStatus fStat) {
40      long currentTime = EnvironmentEdgeManager.currentTimeMillis();
41      long time = fStat.getModificationTime();
42      long life = currentTime - time;
43
44      if (LOG.isTraceEnabled()) {
45        LOG.trace("Log life:" + life + ", ttl:" + ttl + ", current:" + currentTime + ", from: "
46            + time);
47      }
48      if (life < 0) {
49        LOG.warn("Found a log (" + fStat.getPath() + ") newer than current time (" + currentTime
50            + " < " + time + "), probably a clock skew");
51        return false;
52      }
53      return life > ttl;
54    }
55
56    @Override
57    public void setConf(Configuration conf) {
58      super.setConf(conf);
59      this.ttl = conf.getLong("hbase.master.logcleaner.ttl", 600000);
60    }
61
62
63    @Override
64    public void stop(String why) {
65      this.stopped = true;
66    }
67
68    @Override
69    public boolean isStopped() {
70      return this.stopped;
71    }
72  }

This page was automatically generated by Maven


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Linq;
using GameRes.Utility;

namespace GameRes.Formats.DaiSystem
{
    [Export(typeof(ArchiveFormat))]
    public class PacOpener : ArchiveFormat
    {
        public override string         Tag { get { return "PAC/DAI"; } }
        public override string Description { get { return "DAI system resource archive"; } }
        public override uint     Signature { get { return 0x5F494144; } } // 'DAI_SYSTEM_01000'
        public override bool  IsHierarchic { get { return false; } }
        public override bool      CanWrite { get { return false; } }

        public override ArcFile TryOpen (ArcView file)
        {
            if (!file.View.AsciiEqual (4, "SYSTEM_01000"))
                return null;
            int count = Binary.BigEndian (file.View.ReadUInt16 (0x10));
            if (!IsSaneCount (count))
                return null;
            uint index_size = Binary.BigEndian (file.View.ReadUInt32 (0x12));
            var index = file.View.ReadBytes (0x16, index_size);
            for (int i = 0; i < index.Length; ++i)
                index[i] -= (byte)(i + 0x28);

            int index_offset = 0;
            var dir = new List<Entry> (count);
            for (int i = 0; i < count; ++i)
            {
                int name_end = Array.IndexOf<byte> (index, (byte)',', index_offset);
                if (-1 == name_end)
                    return null;
                var name = Encodings.cp932.GetString (index, index_offset, name_end - index_offset);
                index_offset = name_end + 1;
                var entry = FormatCatalog.Instance.Create<Entry> (name);
                entry.Offset = BigEndian.ToUInt32 (index, index_offset);
                index_offset += 5;
                dir.Add (entry);
            }
            for (int i = 1; i < dir.Count; ++i)
            {
                var entry = dir[i-1];
                entry.Size = (uint)(dir[i].Offset - entry.Offset);
                if (!entry.CheckPlacement (file.MaxOffset))
                    return null;
            }
            dir[dir.Count-1].Size = (uint)(file.MaxOffset - dir[dir.Count-1].Offset);
            DetectFileTypes (file, dir);
            return new ArcFile (file, this, dir);
        }

        void DetectFileTypes (ArcView file, List<Entry> dir)
        {
            foreach (var entry in dir.Where (e => string.IsNullOrEmpty (e.Type)))
            {
                uint signature = file.View.ReadUInt32 (entry.Offset);
                if (0x05304148 == signature)
                {
                    entry.Type = "image";
                    continue;
                }
                else if (0x304148 == (signature & 0xFFFFFF))
                {
                    uint encryption = file.View.ReadUInt32 (entry.Offset+8);
                    long offset = entry.Offset + 0x10 + (signature >> 24);
                    if (0 != encryption)
                    {
                        if (4 == encryption)
                        {
                            uint bits = Binary.BigEndian (file.View.ReadUInt32 (offset + 8));
                            if (bits > entry.Size)
                                continue;
                            if (file.View.AsciiEqual (offset+12+bits, "BM"))
                            {
                                entry.ChangeType (ImageFormat.Bmp);
                            }
                            else if (file.View.AsciiEqual (entry.Offset+entry.Size-0x12, "TRUEVISION"))
                            {
                                entry.ChangeType (ImageFormat.Tga);
                            }
                        }
                        continue;
                    }
                    signature = file.View.ReadUInt32 (offset);
                }
                entry.ChangeType (AutoEntry.DetectFileType (signature));
            }
        }

        public override Stream OpenEntry (ArcFile arc, Entry entry)
        {
            if (!arc.File.View.AsciiEqual (entry.Offset, "HA0"))
                return base.OpenEntry (arc, entry);
            byte header_length = arc.File.View.ReadByte (entry.Offset+3);
            uint ha0_header_length = 0x10u + header_length;
            if (ha0_header_length >= entry.Size)
                return base.OpenEntry (arc, entry);
            uint unpacked_size = Binary.BigEndian (arc.File.View.ReadUInt32 (entry.Offset+4));
            uint pattern = arc.File.View.ReadUInt32 (entry.Offset+8);
            var header = arc.File.View.ReadBytes (entry.Offset+0x10, header_length);
            var input = arc.File.View.ReadBytes (entry.Offset + ha0_header_length, entry.Size - ha0_header_length);
            while (pattern != 0)
            {
                uint code = pattern >> 24;
                switch (code)
                {
                case 0: break;
                case 2: input = Decrypt2 (input); break;
                case 3: input = Decrypt3 (input); break;
                case 4: input = Unpack4 (input); break;
                default:
                    Trace.WriteLine (string.Format ("Unknown encryption method ({0})", code), "[DAI_SYSTEM]");
                    return base.OpenEntry (arc, entry);
                }
                pattern <<= 8;
            }
            return new BinMemoryStream (input, entry.Name);
        }

        byte[] Decrypt2 (byte[] input)
        {
            var output = new byte[input.Length];
            int src = 0;
            for (int i = 0; i < 3; ++i)
            {
                for (int dst = i; dst < output.Length; dst += 3)
                    output[dst] = input[src++];
            }
            return output;
        }

        byte[] Decrypt3 (byte[] input)
        {
            for (int i = 1; i < input.Length; ++i)
            {
                input[i] += input[i-1];
            }
            return input;
        }

        byte[] Unpack4 (byte[] input)
        {
            int unpacked_size = BigEndian.ToInt32 (input, 0);
            var output = new byte[unpacked_size];
            int ctl_bits = BigEndian.ToInt32 (input, 4);
            int ctl_bytes = BigEndian.ToInt32 (input, 8);
            int ctl = 12;
            int src = 12 + ctl_bytes;
            int dst = 0;
            int bits = 2;
            while (dst < output.Length)
            {
                bits >>= 1;
                if (1 == bits)
                {
                    bits = input[ctl++] | 0x100;
                }
                if (0 == (bits & 1))
                {
                    output[dst++] = input[src++];
                }
                else
                {
                    int offset = input[src++];
                    int count  = input[src++];
                    Binary.CopyOverlapped (output, dst-offset, dst, count);
                    dst += count;
                }
            }
            return output;
        }
    }
}


text:
#include "includes/BinaryBuffer_private.h"

/*******Private Functions*******/
/* Calculates what the next expansion size would be provided the given size. */
static void calculate_expansion(BinaryBuffer* buff, size_t* size)
{
	if(!*size)
		*size = 1;
	else
	{
		size_t new_size = (*size > buff->max_expand) ?
				*size + buff->max_expand : *size << 1;
		if(new_size < *size)
			*size = ULONG_MAX;
		else
			*size = new_size;
	}
}

/* Private resize resizes the allocated memory to be exactly
 * the number of bytes long received.  This differs from the public
 * resize function in that we do not calculate whether or not the
 * allocated space is below the object's minimum.
 *
 * If an error returns, memory will not have been modified. */
alib_error BinaryBuffer_hard_resize(BinaryBuffer* buff, size_t new_size)
{
	if(!buff)return(ALIB_BAD_ARG);

	if(buff->capacity == new_size)
		return(ALIB_OK);

	/* A size of zero was given, we simply need to free everything. */
	if(!new_size)
	{
		if(buff->buff)
			free(buff->buff);
		buff->buff = NULL;
		buff->capacity = 0;
		buff->len = 0;
	}
	/* Use realloc() to resize the memory. */
	else
	{
		buff->buff = (unsigned char*)realloc(buff->buff, new_size);
		if(!buff->buff)
			return(ALIB_MEM_ERR);

		buff->capacity = new_size;
		if(buff->len > new_size)
			buff->len = new_size;
	}

	return(ALIB_OK);
}
/*******************************/

/*******Public Functions*******/

/* Attempts to resize the buffer capacity by 2 times or by
 * the BinaryBuffer's maximum expansion value, whichever is smaller.
 */
alib_error BinaryBuffer_expand(BinaryBuffer* buff)
{
	size_t new_cap;

	/* Ensure we can expand. */
	if(!buff)return(ALIB_BAD_ARG);
	if(buff->capacity == ULONG_MAX)
		return(ALIB_INTERNAL_MAX_REACHED);

	/* Find a new buffer size for expansion. */
	calculate_expansion(buff, &new_cap);

	/* Resize. */
	return(BinaryBuffer_resize(buff, new_cap));
}
/* Works similarly to BinarBuffer_expand, except it will continue to expand
 * until the capacity is greater than or equal to the targeted capacity.
 *
 * This is more efficient if you must expand more than one time. */
alib_error BinaryBuffer_expand_to_target(BinaryBuffer* buff, size_t target)
{
	/* Ensure we can expand. */
	if(!buff)return(ALIB_BAD_ARG);

	/* Calculate what the expanded capacity will be. */
	size_t new_cap = buff->capacity;
	while(new_cap < target)
		calculate_expansion(buff, &new_cap);

	/* Resize the buffer. */
	return(BinaryBuffer_resize(buff, new_cap));
}

/* Simply resizes the */
/* Resizes the BinaryBuffer's buffer to equal the 'new_size' unless
 * the new size is smaller than the minimum capacity.
 *
 * If resizing to a smaller capacity, any old data that exceeds the new
 * capacity will be truncated.
 *
 * Parameters:
 * 		'buff': The BinaryBuffer to modify.
 * 		'new_size': The new size to resize the internal buffer to.
 */
alib_error BinaryBuffer_resize(BinaryBuffer* buff, size_t new_size)
{
	if(!buff)return(ALIB_BAD_ARG);

	if(new_size < buff->min_cap)
		new_size = buff->min_cap;

	return(BinaryBuffer_hard_resize(buff, new_size));
}

/* Appends a block of data to the end of the buffer.
 * The internal buffer memory will be expanded/doubled until the given data can
 * fit into the buffer.
 *
 * Parameters:
 * 		buff: The BinaryBuffer to append to.
 * 		data: The data to append to the buffer.
 * 		data_len: The number of bytes to append to the buffer.
 */
alib_error BinaryBuffer_append(BinaryBuffer* buff, const void* data, size_t data_len)
{
	if(!buff || !data)return(ALIB_BAD_ARG);
	if(buff->len + data_len > ULONG_MAX)return(ALIB_INTERNAL_MAX_REACHED);

	size_t new_data_len = buff->len + data_len;

	if(buff->capacity < new_data_len)
	{
		alib_error err;
		if((err = BinaryBuffer_expand_to_target(buff, new_data_len)))
			return(err);
	}

	/* Copy the memory over. */
	memcpy((buff->buff + buff->len), data, data_len);
	buff->len = new_data_len;
	return(ALIB_OK);
}
/* Reads from an already opened file and places all data into the buffer.
 * The file is read from the current position, therefore if the entire file
 * should be read, ensure that the file has been set to the beginning or only
 * a partial file will be read.
 *
 * Parameters:
 *             buff: The buffer to append the file to.
 *             file: The file to read from. */
alib_error BinaryBuffer_append_file(BinaryBuffer* buff, FILE* file)
{
       if(!buff || !file)return(ALIB_BAD_ARG);

       long rval = ftell(file);
       size_t fileLen;

       if(fseek(file, 0, SEEK_END))
               return(ALIB_FILE_ERR);
       fileLen = ftell(file) - rval;
       if(fseek(file, rval, SEEK_SET))
               return(ALIB_FILE_ERR);

       /* Resize the buffer. */
       if((rval = BinaryBuffer_expand_to_target(buff, buff->len + fileLen)))
               return(rval);

       rval = fread(buff->buff + buff->len, 1, fileLen, file);
       if(rval < fileLen)
               return(ALIB_FILE_READ_ERR);

       buff->len += fileLen;
       return(ALIB_OK);
}

/* Inserts a block of data into the BinaryBuffer at the specified index.
 *
 * Parameters:
 * 		buff: The BinaryBuffer to modify.
 * 		index: The index to insert the data into. (All bytes at and after this index
 * 			will be placed after the new data.  Therefore if insert was used on a
 * 			string such as 'hello world' at index of 5, then the string would be
 * 			'hello{data} world' upon return.)
 * 		data: The block of data to insert.
 * 		data_len: The length of the data in bytes. */
alib_error BinaryBuffer_insert(BinaryBuffer* buff, size_t index, const void* data,
		size_t data_len)
{
	if(!buff || !data)return(ALIB_BAD_ARG);
	if(index > buff->len)return(ALIB_BAD_INDEX);
	if(buff->len + data_len > ULONG_MAX)return(ALIB_INTERNAL_MAX_REACHED);

	size_t new_len = buff->len + data_len;

	/* Expand to fit the required length. */
	if(buff->capacity < new_len)
	{
		alib_error err;
		if((err = BinaryBuffer_expand_to_target(buff, new_len)))
			return(err);
	}

	/* Copy the memory around. */
	memcpy_back(buff->buff + index + data_len, buff->buff + index,
			buff->len - (index + 1));
	memcpy(buff->buff + index, data, data_len);
	buff->len = new_len;

	return(ALIB_OK);
}

/* Clears all the memory in the internal buffer.  This does not
 * modify the values within memory, but modifies the BinaryBuffer's
 * length member.
 *
 * If the capacity exceeds the buffer's minimum capacity
 * then the internal buffer will be freed. */
void BinaryBuffer_clear(BinaryBuffer* buff)
{
	if(buff)
	{
		if(buff->capacity > buff->min_cap)
			BinaryBuffer_hard_resize(buff, 0);
		else
			buff->len = 0;
	}
}
/* Works similarly to BinaryBuffer_clear() but if the buffer's
 * capacity exceeds the minimum, no memory will be freed. */
void BinaryBuffer_clear_no_resize(BinaryBuffer* buff)
{
	if(buff)
		buff->len = 0;
}
/* Shrinks the BinaryBuffer's buffer to fit size of the data
 * currently stored. */
void BinaryBuffer_shrink_to_fit(BinaryBuffer* buff)
{
	BinaryBuffer_hard_resize(buff, buff->len);
}

/* Removes data from the BinaryBuffer from the 'begin' to the 'end' index.
 *
 * Parameters:
 * 		buff: The buffer to modify.
 * 		begin: The index to start removing from (inclusive).
 * 		end: The index to stop removing from (exclusive).
 */
alib_error BinaryBuffer_remove(BinaryBuffer* buff, size_t begin, size_t end)
{
	if(!buff)return(ALIB_BAD_ARG);

	if(begin > end)
	{
		size_t tmp = end;
		end = begin;
		begin = tmp;
	}

	if(end >= buff->len - 1)
		buff->len = begin;
	else
	{
		memcpy(buff->buff + begin, buff->buff + end, buff->len - end);
		buff->len -= end - begin;
	}

	return(ALIB_OK);
}

/* Copy memory from the BinaryBuffer to a user allocated buffer.
 *
 * Parameters:
 * 		buff: The BinaryBuffer to copy data from.
 * 		to: The user defined buffer to copy data into.
 * 		count: The size of 'to' in bytes. If larger than
 * 			the length of the actual 'to' buffer, then behavior
 * 			is undefined. */
alib_error BinaryBuffer_copy(BinaryBuffer* buff, void* to, size_t count)
{
	if(!buff || !to)return(ALIB_BAD_ARG);

	memcpy(to, buff->buff, (count < buff->len)?count:buff->len);
	return(ALIB_OK);
}
/* Copies memory from the BinaryBuffer to a user defined buffer. The data
 * that is copied is then removed from the BinaryBuffer.
 *
 * Parameters:
 * 		buff: The BinaryBuffer to copy data from.
 * 		to: The user defined buffer to copy data into.
 * 		count: The size of 'to' in bytes. If larger than
 * 			the length of the actual 'to' buffer, then behavior
 * 			is undefined. */
alib_error BinaryBuffer_copy_and_drain(BinaryBuffer* buff, void* to, size_t count)
{
	if(!buff || !to)return(ALIB_BAD_ARG);

	if(count > buff->len)
		count = buff->len;
	memcpy(to, buff->buff, count);
	return(BinaryBuffer_remove(buff, 0, count));
}
/* Similar to BinaryBuffer_copy() but the memory that is copies is within the two
 * indices rather than from the beginning of the BinaryBuffer.
 *
 * Parameters:
 * 		buff: The BinaryBuffer to copy from.
 * 		begin: The index to begin copying from (inclusive).
 * 		end: The index to stop copying from (exclusive).
 * 		to: The user defined buffer to copy data into.
 * 		count: The size of 'to' in bytes.  If larger than the
 * 			actual size of 'to', behavior is undefined. */
alib_error BinaryBuffer_copy_block(BinaryBuffer* buff, size_t begin, size_t end,
		void* to, size_t count)
{
	if(!buff)return(ALIB_BAD_ARG);

	/* Ensure the 'begin' and 'end' are valid. */
	if(begin > end)
	{
		size_t index = begin;
		begin = end;
		end = index;
	}
	if(end >= buff->len)
		return(ALIB_BAD_INDEX);

	/* Find the largest number of bytes that can be copied. */
	end = end - begin;
	if(count > end)
		count = end;

	memcpy(to, buff->buff + begin, count);
	return(ALIB_OK);
}
/* Same as BinaryBuffer_copy_block() but the the memory that is copied will be removed from
 * the buffer.
 *
 * Parameters:
 * 		buff: The BinaryBuffer to copy from.
 * 		begin: The index to begin copying from (inclusive).
 * 		end: The index to stop copying from (exclusive).
 * 		to: The user defined buffer to copy data into.
 * 		count: The size of 'to' in bytes.  If larger than the
 * 			actual size of 'to', behavior is undefined.
 */
alib_error BinaryBuffer_copy_block_and_drain(BinaryBuffer* buff, size_t begin, size_t end,
		void* to, size_t count)
{
	/* Copy. */
	alib_error err = BinaryBuffer_copy_block(buff, begin, end, to, count);
	if(err)return(err);

	/* Find how many bytes we removed. */
	{
		size_t new_count = end - begin;
		if(count > new_count)
			count = new_count;
	}

	/* Remove. */
	err = BinaryBuffer_remove(buff, begin, begin + count);
	return(err);
}

/* Returns the internal buffer of the BinaryBuffer and sets the
 * BinaryBuffers buffer to NULL.  This means that the returned memory
 * is no longer handled by the BinaryBuffer and MUST BE FREED by the caller.
 *
 * If you need to know the length of the buffer, you must check by calling
 * 'BinaryBuffer_get_length()' before calling this as the buffer's members
 * will be reset to 0.
 *
 * Parameters:
 * 		buff: The BinaryBuffer to extract data from.
 *
 * Returns a pointer to the internal buffer.  This buffer is no longer part
 * of the object and MUST BE FREED by the caller when no longer needed. */
void* BinaryBuffer_extract_buffer(BinaryBuffer* buff)
{
	if(!buff)return(NULL);

	void* rval = buff->buff;
	buff->buff = NULL;
	buff->capacity = 0;
	buff->len = 0;

	return(rval);
}

/* Writes the BinaryBuffer to a file pointer.  This is simply a convenience
 * function.
 *
 * Assumes 'buff' and 'file' are not null. */
size_t BinaryBuffer_write_to_file(BinaryBuffer* buff, FILE* file)
{
	return(fwrite(buff->buff, 1, buff->len, file));
}

/* Replaces a section of data in the buffer with new data.
 *
 * If 'new_data' belongs to the buffer, behavior is undefined.
 *
 * Parameters:
 * 		buff: The BinaryBuffer to modify.
 * 		index: The index to replace.
 * 		old_len: The number of bytes to replace.
 * 		new_data: The data that should replace the existing data.
 * 		new_data_len: The length of the new data array. */
alib_error BinaryBuffer_replace(BinaryBuffer* buff, size_t index, size_t old_len,
		const void* new_data, size_t new_data_len)
{
	if(!buff || index > buff->len)return(ALIB_BAD_ARG);

	/* Calculate out the index ptr. */
	unsigned char* index_ptr = buff->buff + index;

	/* Expand memory as needed. */
	if(buff->capacity < buff->len + new_data_len - old_len)
	{
		alib_error err = BinaryBuffer_expand_to_target(buff,
				buff->len + new_data_len - old_len);
		if(err)return(err);
	}

	/* Resize and copy existing data into a later position in the buffer. */
	if(old_len != new_data_len)
		memcpy_safe(index_ptr + new_data_len,
				index_ptr + old_len, buff->len - index - old_len);

	/* Copy the new data into the buffer. */
	memcpy(index_ptr, new_data, new_data_len);

	/* Modify length. */
	buff->len += new_data_len - old_len;

	return(ALIB_OK);
}

	/* Getters */
/* Returns a pointer to the raw internal buffer.
 * READONLY - MODIFY AT YOUR OWN RISK.
 *
 * Assumes 'buff' is not null. */
const void* BinaryBuffer_get_raw_buff(BinaryBuffer* buff)
{
	return(buff->buff);
}
/* Returns the length of the internal buffer in bytes.
 *
 * Assumes 'buff' is not null. */
size_t BinaryBuffer_get_length(BinaryBuffer* buff)
{
	return(buff->len);
}
/* Returns the capacity of the internal buffer in bytes.
 *
 * Assumes 'buff' is not null. */
size_t BinaryBuffer_get_capacity(BinaryBuffer* buff)
{
	return(buff->capacity);
}
/* Returns the minimum capacity of the internal buffer in bytes.
 *
 * Assumes 'buff' is not null. */
size_t BinaryBuffer_get_min_capacity(BinaryBuffer* buff)
{
	return(buff->min_cap);
}
/* Returns the maximum number of bytes the internal buffer may
 * expand per iteration.
 *
 * Assumes 'buff' is not null. */
size_t BinaryBuffer_get_max_expand_size(BinaryBuffer* buff)
{
	return(buff->max_expand);
}
	/***********/

	/* Setters */
/* Sets the minimum capacity of the internal buffer in bytes.
 *
 * Assumes 'buff' is not null. */
void BinaryBuffer_set_min_capacity(BinaryBuffer* buff, size_t min_cap)
{
	buff->min_cap = min_cap;
}
/* Sets the maximum number of bytes the internal buffer may expand by.
 * If 'max_expand' is set to zero, the buffer's value will be set to
 * ULONG_MAX.
 *
 * Assumes 'buff' is not null. */
void BinaryBuffer_set_max_expand_size(BinaryBuffer* buff, size_t max_expand)
{
	if(max_expand)
		buff->max_expand = max_expand;
	else
		buff->max_expand = ULONG_MAX;
}
	/***********/
/******************************/

/*******Lifecycle*******/
/* Instantiates a new BinaryBuffer with detailed data.  Usually
 * newBinaryBuffer() is sufficient.
 *
 * Parameters:
 * 		data: The data to place into the buffer upon instantiation.
 * 		data_len: The length of the data in bytes.
 * 		start_cap: The capacity to start the buffer with.
 * 		min_cap: The minimum capacity that should be allocated
 * 			for the buffer.
 * 		max_expand: (OPTIONA) The number of bytes that the buffer may expand
 * 			by per iteration.  If set to zero, then the maximum expansion will
 * 			be set to ULONG_MAX.
 */
BinaryBuffer* newBinaryBuffer_ex(unsigned char* data, size_t data_len,
		size_t start_cap, size_t min_cap, size_t max_expand)
{
	BinaryBuffer* buff = (BinaryBuffer*)malloc(sizeof(BinaryBuffer));
	if(!buff)return(NULL);

	/* Check argument values. */
	if(data_len > start_cap)
		start_cap = data_len;
	if(min_cap > start_cap)
		start_cap = min_cap;

	/* Set non-dynamic members. */
	buff->capacity = start_cap;
	buff->len = data_len;
	buff->min_cap = min_cap;
	if(max_expand)
		buff->max_expand = max_expand;
	else
		buff->max_expand = ULONG_MAX;

	/* Allocate internal memory. */
	if(start_cap)
	{
		if(!(buff->buff = (unsigned char*)malloc(start_cap)))
			delBinaryBuffer(&buff);
	}
	else
		buff->buff = NULL;

	/* Fill buffer. */
	if(data && data_len)
		memcpy(buff->buff, data, data_len);

	return(buff);
}
/* Instantiates a new BinaryBuffer with a default minimum memory capacity. */
BinaryBuffer* newBinaryBuffer()
{
	return(newBinaryBuffer_ex(NULL, 0, 0, BINARY_BUFFER_DEFAULT_MIN_CAP,
			BINARY_BUFFER_DEFUALT_MAX_EXPAND));
}
/* Deletes a BinaryBuffer meaning all memory allocated by the object is
 * freed and the pointer is set to NULL. */
void delBinaryBuffer(BinaryBuffer** buff)
{
	if(!buff || !*buff)return;

	if((*buff)->buff)
		free((*buff)->buff);

	free(*buff);
	*buff = NULL;
}
/***********************/