text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.UI.WebControls;

using DotNetNuke.Common.Lists;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Profile;
using DotNetNuke.Entities.Users;
using DotNetNuke.Security;
using DotNetNuke.Security.Permissions;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Skins.Controls;
using DotNetNuke.UI.Utilities;
using DotNetNuke.Web.UI.WebControls;
using Telerik.Web.UI;
using Globals = DotNetNuke.Common.Globals;

#endregion

// ReSharper disable CheckNamespace
namespace DotNetNuke.Modules.Admin.Users
// ReSharper restore CheckNamespace
{
    /// <summary>
    /// The Users PortalModuleBase is used to manage the Registered Users of a portal
    /// </summary>
    public partial class UserAccounts : PortalModuleBase
    {
		#region Private Members

        public UserAccounts()
        {
            Users = new ArrayList();
            FilterProperty = "";
            Filter = "";
        }

        #endregion

		#region Protected Members

        protected string Filter { get; set; }

        protected string FilterProperty { get; set; }

        protected bool IsSuperUser
        {
            get
            {
            	return Globals.IsHostTab(PortalSettings.ActiveTab.TabID);
            }
        }

        protected int UsersPortalId
        {
            get
            {
                var intPortalId = PortalId;
                if (IsSuperUser)
                {
                    intPortalId = Null.NullInteger;
                }
                return intPortalId;
            }
        }

        protected ArrayList Users { get; set; }

        #endregion

		#region Private Methods

        protected string UserFilter(bool newFilter)
        {
            var page = "currentpage=" + grdUsers.CurrentPageIndex;
            string filterString;
            string filterPropertyString;
            if (!newFilter)
            {
                filterString = !string.IsNullOrEmpty(Filter) ? "filter=" + Filter : "";
                filterPropertyString = !string.IsNullOrEmpty(FilterProperty) ? "filterproperty=" + FilterProperty : "";
            }
            else
            {
                filterString = !string.IsNullOrEmpty(txtSearch.Text) ? "filter=" + Server.UrlEncode(txtSearch.Text) : "";
                filterPropertyString = !string.IsNullOrEmpty(ddlSearchType.SelectedValue) ? "filterproperty=" + ddlSearchType.SelectedValue : "";
            }
            if (!string.IsNullOrEmpty(filterString))
            {
                filterString += "&";
            }
            if (!string.IsNullOrEmpty(filterPropertyString))
            {
                filterString += filterPropertyString + "&";
            }
            filterString += "pagesize=" + grdUsers.PageSize + "&";
            if (!string.IsNullOrEmpty(page))
            {
                filterString += page;
            }
            return filterString;
        }

        private DnnComboBoxItem AddSearchItem(string name)
        {
            var propertyName = Null.NullString;
            if (Request.QueryString["filterProperty"] != null)
            {
                propertyName = Request.QueryString["filterProperty"];
            }
            var text = Localization.GetString(name, LocalResourceFile);
            if (String.IsNullOrEmpty(text))
            {
                text = name;
            }
            var item = new DnnComboBoxItem(text, name);
            if (name.Equals(propertyName, StringComparison.InvariantCultureIgnoreCase))
            {
                item.Selected = true;
            }
            return item;
        }

        private void InitializeGrid()
        {
            grdUsers.MasterTableView.PagerStyle.PageSizeLabelText = LocalizeString("PagerPageSize.Text");
            grdUsers.MasterTableView.PagerStyle.PagerTextFormat = LocalizeString("PagerTextFormat.Text");
        }

        private void SetGridDataSource()
        {
            var searchText = Filter;
            var searchField = ddlSearchType.SelectedValue;

            CreateLetterSearch();

            int totalRecords = 0;

            if (searchText.Equals(Localization.GetString("Unauthorized"), StringComparison.InvariantCultureIgnoreCase))
            {
                Users = UserController.GetUnAuthorizedUsers(UsersPortalId, true, IsSuperUser);
				totalRecords = Users.Count;
            }
            else if (searchText.Equals(Localization.GetString("Deleted"), StringComparison.InvariantCultureIgnoreCase))
            {
                Users = UserController.GetDeletedUsers(UsersPortalId);
				totalRecords = Users.Count;
            }
            else if (searchText.Equals(Localization.GetString("OnLine"), StringComparison.InvariantCultureIgnoreCase))
            {
                Users = UserController.GetOnlineUsers(UsersPortalId);
	            totalRecords = Users.Count;
            }
            else if (searchText.Equals(Localization.GetString("All"), StringComparison.InvariantCultureIgnoreCase))
            {
                Users = UserController.GetUsers(UsersPortalId, grdUsers.CurrentPageIndex, grdUsers.PageSize, ref totalRecords, true, IsSuperUser);
            }
            else if (!searchText.Equals("None", StringComparison.InvariantCultureIgnoreCase))
            {
                if (searchText.Length > 1)
                {
                    searchText = "%" + searchText;
                }
                switch (searchField.ToLowerInvariant())
                {
                    case "email":
                        Users = UserController.GetUsersByEmail(UsersPortalId, searchText + "%", grdUsers.CurrentPageIndex, grdUsers.PageSize, ref totalRecords, true, IsSuperUser);
                        break;
                    case "username":
                        Users = UserController.GetUsersByUserName(UsersPortalId, searchText + "%", grdUsers.CurrentPageIndex, grdUsers.PageSize, ref totalRecords, true, IsSuperUser);
                        break;
					case "displayname":
						Users = UserController.GetUsersByDisplayName(UsersPortalId, searchText + "%", grdUsers.CurrentPageIndex, grdUsers.PageSize, ref totalRecords, true, IsSuperUser);
                        break;
                    default:
                        Users = UserController.GetUsersByProfileProperty(UsersPortalId, searchField, searchText + "%", grdUsers.CurrentPageIndex, grdUsers.PageSize, ref totalRecords, true, IsSuperUser);
                        break;
                }
            }

            grdUsers.DataSource = Users;
            grdUsers.VirtualItemCount = totalRecords;
        }

        private void CreateLetterSearch()
        {
            var filters = Localization.GetString("Filter.Text", LocalResourceFile);

            filters += "," + Localization.GetString("All");
            filters += "," + Localization.GetString("OnLine");
            if (!IsSuperUser)
            {
                filters += "," + Localization.GetString("Unauthorized");
            }
            filters += "," + Localization.GetString("Deleted");
            var strAlphabet = filters.Split(',');
            rptLetterSearch.DataSource = strAlphabet;
            rptLetterSearch.DataBind();
        }

        private void DeleteUnAuthorizedUsers()
        {
            try
            {
                UserController.DeleteUnauthorizedUsers(UsersPortalId);
                RebindGrid();
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        private void RebindGrid()
        {
            SetGridDataSource();
            grdUsers.Rebind();
        }

        private void RemoveDeletedUsers()
        {
            try
            {
                UserController.RemoveDeletedUsers(UsersPortalId);
                RebindGrid();
            }
            catch (Exception exc)   //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        private bool IsCommandAllowed(UserInfo user, string command)
        {
            var imageVisibility = !(user.IsSuperUser) || UserInfo.IsSuperUser;

            if (imageVisibility)
            {
				imageVisibility = !IsPortalAdministrator(user.UserID)
                                        && (!user.IsInRole(PortalSettings.AdministratorRoleName)
                                            || (PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName)))
                                        && user.UserID != UserId;
            }

            if ((imageVisibility))
            {
                switch (command)
                {
                    case "Delete":
                        if ((user.IsDeleted))
                        {
                            imageVisibility = false;
                        }
                        break;
                    case "Restore":
                    case "Remove":
                        imageVisibility = (user.IsDeleted);
                        break;
                }
            }
            return imageVisibility;
        }

		private bool IsPortalAdministrator(int userId)
		{
            var groupId = PortalController.Instance.GetPortal(PortalSettings.PortalId).PortalGroupID;
			if (groupId != Null.NullInteger)
			{
				return PortalGroupController.Instance.GetPortalsByGroup(groupId).Any(p => p.AdministratorId == userId);
			}

			return userId == PortalSettings.AdministratorId;
		}

		#endregion

		#region Public Methods

        public string DisplayAddress(object unit, object street, object city, object region, object country, object postalCode)
        {
            var address = Null.NullString;
            try
            {
                address = Globals.FormatAddress(unit, street, city, region, country, postalCode);
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
            return address;
        }

        public string DisplayEmail(string email)
        {
            var displayEmail = Null.NullString;
            try
            {
                if (email != null)
                {
                    displayEmail = HtmlUtils.FormatEmail(email, false);
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
            return displayEmail;
        }

        public string DisplayDate(DateTime userDate)
        {
            var date = Null.NullString;
            try
            {
                date = !Null.IsNull(userDate) ? userDate.ToString() : "";
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
            return date;
        }

        protected string FormatURL(string strKeyName, string strKeyValue)
        {
            var url = Null.NullString;
            try
            {
                url = !String.IsNullOrEmpty(Filter) ? EditUrl(strKeyName, strKeyValue, "", "filter=" + Filter) : EditUrl(strKeyName, strKeyValue);
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
            return url;
        }

        protected string FilterURL(string filter)
        {
            var parameters = new List<string> {string.Format("pagesize=" + grdUsers.PageSize)};

            if (!String.IsNullOrEmpty(Filter))
            {
                parameters.Add("filter=" + filter);
            }

            return Globals.NavigateURL(TabId, "", parameters.ToArray());
        }

		#endregion

		#region Event Handlers

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            cmdSearch.Click += OnSearchClick;
            deleteUnAuthorizedButton.Click += DeleteUnAuthorizedButtonClick;
            removeDeletedButton.Click += RemoveDeletedButtonClick;
            grdUsers.ItemDataBound += GrdUsersOnItemDataBound;
            grdUsers.ItemCommand += GrdUsersOnItemCommand;
            grdUsers.PreRender += GrdUsersOnPreRender;

            addUserButton.NavigateUrl = EditUrl("Edit");
            if (ModulePermissionController.CanAdminModule(this.ModuleConfiguration))
            {
                addUserButton.Visible = true;
                removeDeletedButton.Visible = true;
                deleteUnAuthorizedButton.Visible = true;
            }

            InitializeGrid();
            if (!Page.IsPostBack)
            {
                SetInitialPageSize();
            }

            if (Request.QueryString["filter"] != null)
            {
                Filter = Request.QueryString["filter"];
            }
            if (Request.QueryString["filterproperty"] != null)
            {
                FilterProperty = Request.QueryString["filterproperty"];
            }
            if (String.IsNullOrEmpty(Filter))
            {
				//Get Default View
                var setting = UserModuleBase.GetSetting(PortalSettings.PortalId, "Display_Mode");
                var mode = (DisplayMode) setting;
                switch (mode)
                {
                    case DisplayMode.All:
                        Filter = Localization.GetString("All");
                        break;
                    case DisplayMode.FirstLetter:
                        Filter = Localization.GetString("Filter.Text", LocalResourceFile).Substring(0, 1);
                        break;
                    case DisplayMode.None:
                        Filter = "None";
                        break;
                }
            }
            foreach (GridColumn column in grdUsers.Columns)
            {
                bool isVisible;
                var header = column.HeaderText;
                if (String.IsNullOrEmpty(header) || header.ToLower() == "username")
                {
                    isVisible = true;
                }
                else
                {
                    var settingKey = "Column_" + header;
                    var setting = UserModuleBase.GetSetting(PortalSettings.PortalId, settingKey);
                    isVisible = Convert.ToBoolean(setting);
                }

                if (ReferenceEquals(column.GetType(), typeof(DnnGridTemplateColumn)) && column.UniqueName == "DeleteActions")
                {
                    isVisible = ModulePermissionController.HasModulePermission(ModuleConfiguration.ModulePermissions, "EDIT");
                }
                else if (ReferenceEquals(column.GetType(), typeof (DnnGridImageCommandColumn)))
                {
                    isVisible = ModulePermissionController.HasModulePermission(ModuleConfiguration.ModulePermissions, "EDIT");

                    var imageColumn = (DnnGridImageCommandColumn)column;

                    //Manage Edit Column NavigateURLFormatString
                    if (imageColumn.CommandName == "Edit")
                    {
                        //so first create the format string with a dummy value and then
                        //replace the dummy value with the FormatString place holder
                        var formatString = EditUrl("UserId", "KEYFIELD", "Edit", UserFilter(false));
                        formatString = formatString.Replace("KEYFIELD", "{0}");
                        imageColumn.NavigateURLFormatString = formatString;
                    }

                    //Manage Roles Column NavigateURLFormatString
                    if (imageColumn.CommandName == "UserRoles")
                    {
                        if (IsHostMenu)
                        {
                            isVisible = false;
                        }
                        else
                        {
                            //The Friendly URL parser does not like non-alphanumeric characters
                            //so first create the format string with a dummy value and then
                            //replace the dummy value with the FormatString place holder
                            var formatString = EditUrl("UserId", "KEYFIELD", "User Roles", UserFilter(false));
                            formatString = formatString.Replace("KEYFIELD", "{0}");
                            imageColumn.NavigateURLFormatString = formatString;
                        }
                    }

                    //Localize Image Column Text
                    if (!String.IsNullOrEmpty(imageColumn.CommandName))
                    {
                        imageColumn.Text = Localization.GetString(imageColumn.CommandName, LocalResourceFile);
                    }
                }
                column.Visible = isVisible;
            }
        }

        private void SetInitialPageSize()
        {
            if (Request.QueryString["pagesize"] != null)
            {
                int pageSize;
                if (Int32.TryParse(Request.QueryString["pagesize"], out pageSize))
                {
                    grdUsers.PageSize = pageSize;
                }
            }
            else
            {
                var pageSizeSetting = GetPageSizeSetting(PortalSettings.PortalId, UserInfo.UserID);
                if (pageSizeSetting != Null.NullInteger)
                {
                    grdUsers.PageSize = pageSizeSetting;
                }
                else
                {
                    var setting = UserModuleBase.GetSetting(PortalSettings.PortalId, "Records_PerPage");
                    grdUsers.PageSize = Convert.ToInt32(setting);
                }
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                if (!Page.IsPostBack)
                {
					ClientAPI.RegisterKeyCapture(txtSearch, cmdSearch, 13);
					//Load the Search Combo
                    ddlSearchType.Items.Add(AddSearchItem("Username"));
                    ddlSearchType.Items.Add(AddSearchItem("Email"));
					ddlSearchType.Items.Add(AddSearchItem("DisplayName"));
					var controller = new ListController();
					ListEntryInfo imageDataType = controller.GetListEntryInfo("DataType", "Image");
                    ProfilePropertyDefinitionCollection profileProperties = ProfileController.GetPropertyDefinitionsByPortal(PortalId, false, false);
                    foreach (ProfilePropertyDefinition definition in profileProperties)
                    {
                        if (imageDataType != null && definition.DataType != imageDataType.EntryID)
                        {
							ddlSearchType.Items.Add(AddSearchItem(definition.PropertyName));
                        }
                    }

					//Sent controls to current Filter
					if ((!String.IsNullOrEmpty(Filter) && Filter.ToUpper() != "NONE") && !String.IsNullOrEmpty(FilterProperty))
                    {
                        txtSearch.Text = Filter;
                        var findedItem = ddlSearchType.Items.FindItemByValue(FilterProperty, true);
                        if (findedItem != null)
                        {
                            findedItem.Selected = true;
                        }
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        void RemoveDeletedButtonClick(object sender, EventArgs e)
        {
            RemoveDeletedUsers();
        }

        void DeleteUnAuthorizedButtonClick(object sender, EventArgs e)
        {
            DeleteUnAuthorizedUsers();
        }

        private void OnSearchClick(Object sender, EventArgs e)
        {
            txtSearch.Text = txtSearch.Text.Trim();
            Response.Redirect(Globals.NavigateURL(TabId, "", UserFilter(true)));
        }

        private void GrdUsersOnItemCommand(object source, GridCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Delete":
                    DeleteUser(GetUserId(e));
                    break;
                case "Remove":
                    RemoveUser(GetUserId(e));
                    break;
                case "Restore":
                    RestoreUser(GetUserId(e));
                    break;
                case "ChangePageSize":
                    ChangePageSizeSetting(PortalSettings.PortalId, UserInfo.UserID, ((GridPageSizeChangedEventArgs)e).NewPageSize);
                    break;
            }
        }
        private void ChangePageSizeSetting(int portalId, int userId, int pageSize)
        {
            var personalizationController = new Services.Personalization.PersonalizationController();
            var personalization = personalizationController.LoadProfile(userId, portalId);
            personalization.Profile["User-Accounts:" + "pageSize_" + portalId] = pageSize.ToString(CultureInfo.InvariantCulture);
            personalization.IsModified = true;
            personalizationController.SaveProfile(personalization);
        }

        private int GetPageSizeSetting(int portalId, int userId)
        {
            var personalizationController = new Services.Personalization.PersonalizationController();
            var personalization = personalizationController.LoadProfile(userId, portalId);
            var pageSizeValue = personalization.Profile["User-Accounts:" + "pageSize_" + portalId];
            if (pageSizeValue == null)
            {
                return Null.NullInteger;
            }
            return Int32.Parse(pageSizeValue.ToString(), CultureInfo.InvariantCulture);
        }

        private int GetUserId(GridCommandEventArgs e)
        {
            return Convert.ToInt32(e.CommandArgument);
        }

        private void DeleteUser(int userId)
        {
            try
            {
                var user = UserController.GetUserById(UsersPortalId, userId);
                if (user != null)
                {
                    if (UserController.DeleteUser(ref user, true, false))
                    {
                        UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("UserDeleted", LocalResourceFile), ModuleMessage.ModuleMessageType.GreenSuccess);
                    }
                    else
                    {
                        UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("UserDeleteError", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                    }
                }
                if (!String.IsNullOrEmpty(txtSearch.Text))
                {
                    Filter = txtSearch.Text;
                }
                RebindGrid();
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        private void RemoveUser(int userId)
        {
            try
            {
                UserInfo user = UserController.GetUserById(UsersPortalId, userId);

                if ((user != null))
                {
                    if (UserController.RemoveUser(user))
                    {
                        UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("UserRemoved", LocalResourceFile), ModuleMessage.ModuleMessageType.GreenSuccess);
                    }
                    else
                    {
                        UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("UserRemoveError", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                    }
                }

                if (!string.IsNullOrEmpty(txtSearch.Text))
                {
                    Filter = txtSearch.Text;
                }
                RebindGrid();

            }
            catch (Exception exc)   //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        private void RestoreUser(int userId)
        {
            try
            {
                var user = UserController.GetUserById(UsersPortalId, userId);

                if ((user != null))
                {
                    if (UserController.RestoreUser(ref user))
                    {
                        UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("UserRestored", LocalResourceFile), ModuleMessage.ModuleMessageType.GreenSuccess);
                    }
                    else
                    {
                        UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("UserRestoreError", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                    }
                }

                if (!string.IsNullOrEmpty(txtSearch.Text))
                {
                    Filter = txtSearch.Text;
                }
                RebindGrid();

                //Module failed to load
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        void GrdUsersOnPreRender(object sender, EventArgs e)
        {
            grdUsers.Columns.FindByUniqueName("UsersOnline").Visible = Entities.Host.Host.EnableUsersOnline;
        }

        private void GrdUsersOnItemDataBound(object sender, GridItemEventArgs e)
        {
            var item = e.Item;
            if (item.ItemType == GridItemType.Item || item.ItemType == GridItemType.AlternatingItem || item.ItemType == GridItemType.SelectedItem)
            {
                var imgApprovedDeleted = item.FindControl("imgApprovedDeleted");
                var imgNotApprovedDeleted = item.FindControl("imgNotApprovedDeleted");
                var imgApproved = item.FindControl("imgApproved");
                var imgNotApproved = item.FindControl("imgNotApproved");

                var user = (UserInfo)item.DataItem;

                if (user == null)
                {
                    return;
                }

                if (user.IsDeleted)
                {
                    foreach (WebControl control in item.Controls)
                    {
                        control.Attributes.Remove("class");
                        control.Attributes.Add("class", "NormalDeleted");
                    }
                    if (imgApprovedDeleted != null && user.Membership.Approved)
                    {
                        imgApprovedDeleted.Visible = true;
                    }
                    else if (imgNotApprovedDeleted != null && !user.Membership.Approved)
                    {
                        imgNotApprovedDeleted.Visible = true;
                    }
                }
                else
                {
                    if (imgApproved != null && user.Membership.Approved)
                    {
                        imgApproved.Visible = true;
                    }
                    else if (imgNotApproved != null && !user.Membership.Approved)
                    {
                        imgNotApproved.Visible = true;
                    }
                }

                var gridDataItem = (GridDataItem)item;

                var editLink = gridDataItem["EditButton"].Controls[0] as HyperLink;
                if (editLink != null)
                {
                    editLink.Visible = (!user.IsInRole(PortalSettings.AdministratorRoleName) || (PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName)));
                    if (editLink.Visible)
                    {
                        if (user.IsSuperUser)
                        {
                            editLink.Visible = PortalSettings.UserInfo.IsSuperUser;
                        }
                    }
                }

                var delete = (DnnImageButton)item.FindControl("Delete");
                delete.Visible = IsCommandAllowed(user, "Delete");
                delete.CommandArgument = user.UserID.ToString(CultureInfo.InvariantCulture);
                delete.ToolTip = Localization.GetString("Delete.Text", LocalResourceFile);

                var restore = (DnnImageButton)item.FindControl("Restore");
                restore.Visible = IsCommandAllowed(user, "Restore");
                restore.CommandArgument = user.UserID.ToString(CultureInfo.InvariantCulture);
                restore.ToolTip = Localization.GetString("Restore.Text", LocalResourceFile);

                var remove = (DnnImageButton)item.FindControl("Remove");
                remove.Visible = IsCommandAllowed(user, "Remove");
                remove.CommandArgument = user.UserID.ToString(CultureInfo.InvariantCulture);
                remove.ToolTip = Localization.GetString("Remove.Text", LocalResourceFile);

                var rolesColumn = gridDataItem["RolesButton"].Controls[0];
                rolesColumn.Visible = !user.IsSuperUser && (!user.IsInRole(PortalSettings.AdministratorRoleName)
                                                              || (PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName)));

                var onlineControl = (DnnImage)item.FindControl("imgOnline");
                if (onlineControl != null)
                {
                    onlineControl.Visible = user.Membership.IsOnLine;
                    onlineControl.ToolTip = Localization.GetString("Online.Text", LocalResourceFile);
                }
            }
        }

        protected void NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            SetGridDataSource();
        }

        #endregion
    }
}


text:
{=controller|caps} list

There are {ldelim}={=controller|plural}.length|counter}

{ldelim}include name={=controller|plural}:hdr}
{ldelim}foreach from={=controller|plural} item={=controller}}
{ldelim}include name={=controller|plural}:row}
{ldelim}/foreach}

Add

redpajama_set_name: RedPajamaGithub


text:
{% extends "templates/web.html" %}

{% block title %}{{ _("Connection Success") }}{% endblock %}

{%- block page_content -%}

			{{ _("Success") }}

{{ _("Your connection request to Google Calendar was successfully accepted") }}

		{{ _("Back to Desk") }}

{% endblock %}


text:
#include <stdio.h>
__CCAPRICE_INTERNAL_FUNC(int, _rename, (const char *, const char *));

int rename(const char *old, const char *new) {
    return _rename(old, new);
}


text:
module SourcesHelper
  # Return HTML with a link to the the external source URL.
  def source_url_link(source)
    return link_to source.url, source.url, { :rel => "nofollow", :target => "_BLANK" }
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Logic.Algorithms.ObjectFittingStrategies._3D;
using Logic.Domain.Containers._3D;
using Logic.Domain.Containers._2D.Guillotine;
using Logic.Domain.Containers._3D.Guillotine;

namespace Logic.Algorithms.Implementations._3D.Guillotine
{
	public class MaxVolumeGuillotineCut3DAlgorithm : AbstractGuillotineCut3DAlgorithm
	{
		public MaxVolumeGuillotineCut3DAlgorithm(Container3D initialContainer, AbstractFittingStrategy3D strategy) : base(initialContainer, strategy)
		{
			containers = new List<Container3D>();

			containers.Add(new GuillotineCutMaxVolumeContainer3D(initialContainer.Width, initialContainer.Height, initialContainer.Depth));
		}

		public override void AddContainer()
		{
			if (containers != null)
				containers.Add(new GuillotineCutMaxVolumeContainer3D(containers.First().Width, containers.First().Height, containers.First().Depth));
		}
	}
}


text:
use super::bitmask::BitMask;
use super::EMPTY;
use core::{mem, ptr};

// Use the native word size as the group size. Using a 64-bit group size on
// a 32-bit architecture will just end up being more expensive because
// shifts and multiplies will need to be emulated.
#[cfg(any(
    target_pointer_width = "64",
    target_arch = "aarch64",
    target_arch = "x86_64",
))]
type GroupWord = u64;
#[cfg(all(
    target_pointer_width = "32",
    not(target_arch = "aarch64"),
    not(target_arch = "x86_64"),
))]
type GroupWord = u32;

pub type BitMaskWord = GroupWord;
pub const BITMASK_STRIDE: usize = 8;
// We only care about the highest bit of each byte for the mask.
#[allow(clippy::cast_possible_truncation, clippy::unnecessary_cast)]
pub const BITMASK_MASK: BitMaskWord = 0x8080_8080_8080_8080_u64 as GroupWord;

/// Helper function to replicate a byte across a `GroupWord`.
#[inline]
fn repeat(byte: u8) -> GroupWord {
    GroupWord::from_ne_bytes([byte; Group::WIDTH])
}

/// Abstraction over a group of control bytes which can be scanned in
/// parallel.
///
/// This implementation uses a word-sized integer.
#[derive(Copy, Clone)]
pub struct Group(GroupWord);

// We perform all operations in the native endianess, and convert to
// little-endian just before creating a BitMask. The can potentially
// enable the compiler to eliminate unnecessary byte swaps if we are
// only checking whether a BitMask is empty.
#[allow(clippy::use_self)]
impl Group {
    /// Number of bytes in the group.
    pub const WIDTH: usize = mem::size_of::<Self>();

    /// Returns a full group of empty bytes, suitable for use as the initial
    /// value for an empty hash table.
    ///
    /// This is guaranteed to be aligned to the group size.
    pub const fn static_empty() -> &'static [u8; Group::WIDTH] {
        #[repr(C)]
        struct AlignedBytes {
            _align: [Group; 0],
            bytes: [u8; Group::WIDTH],
        }
        const ALIGNED_BYTES: AlignedBytes = AlignedBytes {
            _align: [],
            bytes: [EMPTY; Group::WIDTH],
        };
        &ALIGNED_BYTES.bytes
    }

    /// Loads a group of bytes starting at the given address.
    #[inline]
    #[allow(clippy::cast_ptr_alignment)] // unaligned load
    pub unsafe fn load(ptr: *const u8) -> Self {
        Group(ptr::read_unaligned(ptr.cast()))
    }

    /// Loads a group of bytes starting at the given address, which must be
    /// aligned to `mem::align_of::<Group>()`.
    #[inline]
    #[allow(clippy::cast_ptr_alignment)]
    pub unsafe fn load_aligned(ptr: *const u8) -> Self {
        // FIXME: use align_offset once it stabilizes
        debug_assert_eq!(ptr as usize & (mem::align_of::<Self>() - 1), 0);
        Group(ptr::read(ptr.cast()))
    }

    /// Stores the group of bytes to the given address, which must be
    /// aligned to `mem::align_of::<Group>()`.
    #[inline]
    #[allow(clippy::cast_ptr_alignment)]
    pub unsafe fn store_aligned(self, ptr: *mut u8) {
        // FIXME: use align_offset once it stabilizes
        debug_assert_eq!(ptr as usize & (mem::align_of::<Self>() - 1), 0);
        ptr::write(ptr.cast(), self.0);
    }

    /// Returns a `BitMask` indicating all bytes in the group which *may*
    /// have the given value.
    ///
    /// This function may return a false positive in certain cases where
    /// the byte in the group differs from the searched value only in its
    /// lowest bit. This is fine because:
    /// - This never happens for `EMPTY` and `DELETED`, only full entries.
    /// - The check for key equality will catch these.
    /// - This only happens if there is at least 1 true match.
    /// - The chance of this happening is very low (< 1% chance per byte).
    #[inline]
    pub fn match_byte(self, byte: u8) -> BitMask {
        // This algorithm is derived from
        // http://graphics.stanford.edu/~seander/bithacks.html##ValueInWord
        let cmp = self.0 ^ repeat(byte);
        BitMask((cmp.wrapping_sub(repeat(0x01)) & !cmp & repeat(0x80)).to_le())
    }

    /// Returns a `BitMask` indicating all bytes in the group which are
    /// `EMPTY`.
    #[inline]
    pub fn match_empty(self) -> BitMask {
        // If the high bit is set, then the byte must be either:
        // 1111_1111 (EMPTY) or 1000_0000 (DELETED).
        // So we can just check if the top two bits are 1 by ANDing them.
        BitMask((self.0 & (self.0 << 1) & repeat(0x80)).to_le())
    }

    /// Returns a `BitMask` indicating all bytes in the group which are
    /// `EMPTY` or `DELETED`.
    #[inline]
    pub fn match_empty_or_deleted(self) -> BitMask {
        // A byte is EMPTY or DELETED iff the high bit is set
        BitMask((self.0 & repeat(0x80)).to_le())
    }

    /// Returns a `BitMask` indicating all bytes in the group which are full.
    #[inline]
    pub fn match_full(self) -> BitMask {
        self.match_empty_or_deleted().invert()
    }

    /// Performs the following transformation on all bytes in the group:
    /// - `EMPTY => EMPTY`
    /// - `DELETED => EMPTY`
    /// - `FULL => DELETED`
    #[inline]
    pub fn convert_special_to_empty_and_full_to_deleted(self) -> Self {
        // Map high_bit = 1 (EMPTY or DELETED) to 1111_1111
        // and high_bit = 0 (FULL) to 1000_0000
        //
        // Here's this logic expanded to concrete values:
        //   let full = 1000_0000 (true) or 0000_0000 (false)
        //   !1000_0000 + 1 = 0111_1111 + 1 = 1000_0000 (no carry)
        //   !0000_0000 + 0 = 1111_1111 + 0 = 1111_1111 (no carry)
        let full = !self.0 & repeat(0x80);
        Group(!full + (full >> 7))
    }
}


text:
package unfiltered.response

trait BaseContentType extends Responder[Any] {
  def respond(res: HttpResponse[Any]) {
    res.setContentType(contentType)
  }
  def contentType: String
}

case class CharContentType(content_type: String) extends BaseContentType {
  def contentType = "%s; charset=%s".format(content_type, charset)
  def charset = "utf-8"
}

object CssContent extends CharContentType("text/css")
object HtmlContent extends CharContentType("text/html")
object JsContent extends CharContentType("text/javascript")
object CsvContent extends CharContentType("text/csv")
object TextXmlContent extends CharContentType("text/xml")
object PlainTextContent extends CharContentType("text/plain")
object JsonContent extends CharContentType("application/json")
object ApplicationXmlContent extends CharContentType("application/xml")
object FormEncodedContent extends ContentType("application/x-www-form-urlencoded")

case class ContentType(override val contentType: String) extends BaseContentType
object PdfContent extends ContentType("application/pdf")


text:
A small script for zooming IMG elements with the mousewheel/trackpad.  Wheelzoom works by replacing the img element's src with a transparent image, then using the original src as a background image, which can be sized and positioned. Wheelzoom is dependency free, doesn't add any extra elements to the DOM, or change the positioning of the IMG element.

## Usage:
````javascript
wheelzoom(document.querySelectorAll('img'));
// or
wheelzoom(document.querySelectorAll('img'), {zoom:0.05});
// zoom sets the zoom percent.
````

## License
[MIT License](http://opensource.org/licenses/MIT)

## Supported Browsers:
Chrome, Safari, Opera, FireFox 17+, IE9+.

## Changelog:

##### v.4.0.1 - 2019/08/13
* Added initialX and initialY for setting the initial zoomed coordinates

##### v.4.0.0 - 2018/10/09
* Replaced canvas data URI with base64 svg for creating placeholder
* Dropped IE9 support

##### v.3.1.3 - 2018/01/31
* Added 'initialZoom' option. Resolves #32

##### v.3.1.2 - 2017/04/20
* Added package.json & added to NPM.

##### v.3.1.0 - 2017/04/10
* Added 'maxZoom' option for maximum zoom level.

##### v.3.0.4 - 2015/12/15
* Automatically account for changes to the img src, to avoid requiring manually calling destroy and reapply.

##### v.3.0.3 - 2015/09/05
* Fixed zoom positioning issue in Firefox.  Fixes #17
* Fixed error when calling destroy in Firefox.  Fixes #16
* Removed debugging statement.  Fixes #15

##### v.3.0.2 - 2015/09/05
* Fixed lint warnings and bug introduced in 3.0.1

##### v.3.0.1 - 2015/09/05
* Fixed issue with src URLs that contain single quotes. Fixes #13.

##### v.3.0.0 - 2014/10/14
* Removed jQuery dependency
* Added 'wheelzoom.destroy' event for removing changes that wheelzoom has made to an element.

##### v.2.0.1 - 2014/9/9
* Merged bugfix to wrap background-image path in quotes.  Ref #8.

##### v.2.0.0 - 2014/4/17
* Simplified by dropping support for having border and padding on the img element. Borders and/or padding should be applied to the parent element, rather than the img element.

##### v.1.1.3 - 2014/4/13
* Minor code improvement.

##### v.1.1.2 - 2013/1/31
* Fixed bug with unzoom trigger.

##### v1.1.1 - 2013/1/29
* Added trigger to unzoom image:
````javascript
	$('#example').trigger('wheelzoom.reset')
````

##### v1.1.0 - 2012/11/28
* Added dragging.

##### v1.0 - 2012/11/26
* Initial release.


text:
VERSION := $(shell node -e "console.log(require('./package.json').version)")

.PHONY: default release smoke

test:
	npm test

smoke:
	npm install --build-from-source
	node smoke/smoketest.js
	npm test

release:
	@echo "Tagging release $(VERSION)"
	@git tag -m "$(VERSION)" v$(VERSION)

	@echo "Pushing tags to GitHub"
	@git push --tags

	@echo "Switching to osx-binaries branch"
	@git checkout osx-binaries

	@echo "Merging master into osx-binaries"
	@git merge --no-ff --commit -m "Merge master into osx-binaries [publish binary]" master

	@echo "Pushing osx-binaries"
	@git push

	@echo "Switching to master branch"
	@git checkout master

	@echo "Publishing to NPM"
	@npm publish


text:
Full-text search engine built with Node.JS and SQLite FTS for desktop search.

# Installation

```
npm install
npm install -g mocha
```

# Testing

```
mocha test.js
```


text:
using System.Data.Common;
using System.Net;
using System.Threading.Tasks;
using NServiceBus;
using SFA.DAS.EmployerFinance.Configuration;
using SFA.DAS.EmployerFinance.Extensions;
using SFA.DAS.EmployerFinance.Startup;
using SFA.DAS.EmployerFinance.Web.App_Start;
using SFA.DAS.NServiceBus.Configuration;
using SFA.DAS.NServiceBus.Configuration.NewtonsoftJsonSerializer;
using SFA.DAS.NServiceBus.Configuration.NLog;
using SFA.DAS.NServiceBus.SqlServer.Configuration;
using SFA.DAS.NServiceBus.Configuration.StructureMap;
using SFA.DAS.UnitOfWork.NServiceBus.Configuration;

namespace SFA.DAS.EmployerFinance.Web
{
    public class NServiceBusStartup : IStartup
    {
        private IEndpointInstance _endpoint;

        public async Task StartAsync()
        {
            var container = StructuremapMvc.StructureMapDependencyScope.Container;

            var endpointConfiguration = new EndpointConfiguration("SFA.DAS.EmployerAccounts.Web")
                .UseAzureServiceBusTransport(() => container.GetInstance<EmployerFinanceConfiguration>().ServiceBusConnectionString, container)
                .UseErrorQueue("SFA.DAS.EmployerAccounts.Web-errors")
                .UseInstallers()
                .UseLicense(WebUtility.HtmlDecode(container.GetInstance<EmployerFinanceConfiguration>().NServiceBusLicense))
                .UseSqlServerPersistence(() => container.GetInstance<DbConnection>())
                .UseNewtonsoftJsonSerializer()
                .UseNLogFactory()
                .UseOutbox(true)
                .UseStructureMapBuilder(container)
                .UseUnitOfWork();

            _endpoint = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false);

            container.Configure(c =>
            {
                c.For<IMessageSession>().Use(_endpoint);
            });
        }

        public Task StopAsync()
        {
            return _endpoint.Stop();
        }
    }
}


text:
package com.intellij.codeInsight.intention.impl;

import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.daemon.impl.analysis.HighlightControlFlowUtil;
import com.intellij.codeInsight.generation.RecordConstructorMember;
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.util.JavaPsiRecordUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;

import java.util.Objects;

public class ConvertCompactConstructorToCanonicalAction extends PsiElementBaseIntentionAction {
  @Override
  public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {
    PsiMethod method = getMethod(element);
    if (method == null) return;
    PsiClass recordClass = method.getContainingClass();
    if (recordClass == null) return;
    PsiMethod prototype = new RecordConstructorMember(recordClass, false).generateRecordConstructor();
    PsiModifierList modifierList = method.getModifierList();
    prototype.getModifierList().replace(modifierList);
    PsiElement beforeModifier = modifierList.getPrevSibling();
    if (beforeModifier != null) {
      prototype.addRangeBefore(method.getFirstChild(), beforeModifier, prototype.getModifierList());
    }
    PsiCodeBlock oldBody = Objects.requireNonNull(method.getBody());
    PsiCodeBlock body = (PsiCodeBlock)Objects.requireNonNull(prototype.getBody()).replace(oldBody);
    PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
    for (PsiRecordComponent component : recordClass.getRecordComponents()) {
      PsiField field = JavaPsiRecordUtil.getFieldForComponent(component);
      if (field != null && !HighlightControlFlowUtil.variableDefinitelyAssignedIn(field, body)) {
        body.add(factory.createStatementFromText("this." + field.getName() + "=" + field.getName() + ";", body));
      }
    }
    int offset = editor.getCaretModel().getOffset();
    if (oldBody.getTextRange().contains(offset)) {
      offset += body.getTextRangeInParent().getStartOffset() - oldBody.getTextRangeInParent().getStartOffset();
    }
    method.replace(prototype);
    editor.getCaretModel().moveToOffset(offset);
  }

  @Nls(capitalization = Nls.Capitalization.Sentence)
  @Override
  public @NotNull String getText() {
    return getFamilyName();
  }

  @Override
  public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) {
    PsiMethod method = getMethod(element);
    return method != null &&
           JavaPsiRecordUtil.isCompactConstructor(method) &&
           method.getBody() != null &&
           method.getContainingClass() != null &&
           method.getContainingClass().isRecord();
  }

  private static PsiMethod getMethod(@NotNull PsiElement element) {
    return PsiTreeUtil.getParentOfType(element, PsiMethod.class, true, PsiLambdaExpression.class, PsiMember.class);
  }

  @Nls(capitalization = Nls.Capitalization.Sentence)
  @Override
  public @NotNull String getFamilyName() {
    return CodeInsightBundle.message("intention.convert.compact.constructor.to.canonical");
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>29-XJumbotronTest</title>
    <link href="../dist/css/bootstrap.css" rel="stylesheet" />


text:
/*
 * SPI.h
 *
 *  Created on: 07/08/2012
 *      Author: podonoghue
 */

#ifndef LCD_SPI_H_
#define LCD_SPI_H_

#ifndef LCD_SPI_PRIVATE
#error "This is a private header file - don't include"
#endif

#include <stdint.h>

//! Initialise SPI
//!
//! @note a default frequency is used.
//!
void lcd_spiInitialise(void);

//! Sets Communication speed for SPI
//!
//! @param freq => Frequency in kHz (0 => use default value)
//!
//! @return  \ref BDM_RC_OK              => Success                 \n
//!          \ref BDM_RC_ILLEGAL_PARAMS  => Speed is not supported
//!
uint8_t lcd_spiSetSpeed(uint16_t freq);

//! Transmit a 8-bit command to display
//!
//! @param send - command to send
//!
void lcd_spiTxCommand(uint8_t data);

//! Transmit 8-bit data to display
//!
//! @param send - data to send
//!
void lcd_spiTxData(uint8_t data);

#endif /* LCD_SPI_H_ */


text:
<title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="css/styles.css">
  <link rel="stylesheet" type="text/css" href="/ServletApp/css/styles.css"/>
  <img src="img/header.png">


text:
package pry

import (
	"fmt"
	"io"
	"log"
	"path/filepath"
	"runtime"
	"strings"

	"go/ast"

	"github.com/mgutz/ansi"
)

// Pry does nothing. It only exists so running code without go-pry doesn't throw an error.
func Pry(v ...interface{}) {
}

// Apply drops into a pry shell in the location required.
func Apply(scope *Scope) {
	out, tty := openTTY()
	defer tty.Close()

	_, filePathRaw, lineNum, _ := runtime.Caller(1)
	filePath := filepath.Dir(filePathRaw) + "/." + filepath.Base(filePathRaw) + "pry"

	if err := apply(scope, out, tty, filePath, filePathRaw, lineNum); err != nil {
		log.Fatalf("%+v", err)
	}
}

type genericTTY interface {
	ReadRune() (rune, error)
	Size() (int, int, error)
	Close() error
}

func apply(
	scope *Scope,
	out io.Writer,
	tty genericTTY,
	filePath, filePathRaw string,
	lineNum int,
) error {
	if scope.Files == nil {
		scope.Files = map[string]*ast.File{}
	}

	if err := scope.ConfigureTypes(filePath, lineNum); err != nil {
		return err
	}

	displayFilePosition(out, filePathRaw, filePath, lineNum)

	history, err := NewHistory()
	if err != nil {
		fmt.Errorf("Failed to initiliaze history %+v", err)
	}
	if err := history.Load(); err != nil {
		fmt.Errorf("Failed to load the history %+v", err)
	}

	currentPos := history.Len()

	line := ""
	count := history.Len()
	index := 0
	r := rune(0)
	for {
		prompt := fmt.Sprintf("[%d] go-pry> ", currentPos)
		fmt.Fprintf(out, "\r\033[K%s%s \033[0J\033[%dD", prompt, Highlight(line), len(line)-index+1)

		promptWidth := len(prompt) + index
		displaySuggestions(scope, out, tty, line, index, promptWidth)

		bPrev := r

		r = 0
		for r == 0 {
			var err error
			r, err = tty.ReadRune()
			if err != nil {
				return err
			}
		}
		switch r {
		default:
			if bPrev == 27 && r == 91 {
				continue
			} else if bPrev == 91 {
				switch r {
				case 66: // Down
					currentPos++
					if history.Len() < currentPos {
						currentPos = history.Len()
					}
					if history.Len() == currentPos {
						line = ""
					} else {
						line = history.Records[currentPos]
					}
					index = len(line)
				case 65: // Up
					currentPos--
					if currentPos < 0 {
						currentPos = 0
					}
					if history.Len() > 0 {
						line = history.Records[currentPos]
					}
					index = len(line)
				case 67: // Right
					index++
					if index > len(line) {
						index = len(line)
					}
				case 68: // Left
					index--
					if index < 0 {
						index = 0
					}
				}
				continue
			} else if bPrev == 51 && r == 126 { // DELETE
				if len(line) > 0 && index < len(line) {
					line = line[:index] + line[index+1:]
				}
				if index > len(line) {
					index = len(line)
				}
				continue
			}
			line = line[:index] + string(r) + line[index:]
			index++
		case 127, '\b': // Backspace
			if len(line) > 0 && index > 0 {
				line = line[:index-1] + line[index:]
				index--
			}
			if index > len(line) {
				index = len(line)
			}
		case 27: // ? This happens on key press
		case 9: //TAB
		case 10, 13: //ENTER
			fmt.Fprintln(out, "\033[100000C\033[0J")
			if len(line) == 0 {
				continue
			}
			if line == "continue" || line == "exit" {
				return nil
			}
			resp, err := scope.InterpretString(line)
			if err != nil {
				fmt.Fprintln(out, "Error: ", err, resp)
			} else {
				respStr := Highlight(fmt.Sprintf("%#v", resp))
				fmt.Fprintf(out, "=> %s\n", respStr)
			}
			history.Add(line)
			err = history.Save()
			if err != nil {
				fmt.Fprintln(out, "Error: ", err)
			}

			count++
			currentPos = count
			line = ""
			index = 0
		case 4: // Ctrl-D
			fmt.Fprintln(out)
			return nil
		}
	}
}

func displayFilePosition(
	out io.Writer, filePathRaw, filePath string, lineNum int,
) {
	fmt.Fprintf(out, "\nFrom %s @ line %d :\n\n", filePathRaw, lineNum)
	file, err := readFile(filePath)
	if err != nil {
		fmt.Fprintln(out, err)
	}
	lines := strings.Split((string)(file), "\n")
	lineNum--
	start := lineNum - 5
	if start < 0 {
		start = 0
	}
	end := lineNum + 6
	if end > len(lines) {
		end = len(lines)
	}
	maxLen := len(fmt.Sprint(end))
	for i := start; i < end; i++ {
		caret := "  "
		if i == lineNum {
			caret = "=>"
		}
		numStr := fmt.Sprint(i + 1)
		if len(numStr) < maxLen {
			numStr = " " + numStr
		}
		num := ansi.Color(numStr, "blue+b")
		highlightedLine := Highlight(strings.Replace(lines[i], "\t", "  ", -1))
		fmt.Fprintf(out, " %s %s: %s\n", caret, num, highlightedLine)
	}
	fmt.Fprintln(out)
}

// displaySuggestions renders the live autocomplete from GoCode.
func displaySuggestions(
	scope *Scope,
	out io.Writer,
	tty genericTTY,
	line string,
	index, promptWidth int,
) {
	var err error
	var suggestions []string
	if runtime.GOOS == "js" {
		suggestions, err = scope.SuggestionsPry(line, index)
	} else {
		suggestions, err = scope.SuggestionsGoCode(line, index)
	}
	if err != nil {
		suggestions = []string{"ERR", err.Error()}
	}

	maxLength := 0
	if len(suggestions) > 10 {
		suggestions = suggestions[:10]
	}
	for _, term := range suggestions {
		if len(term) > maxLength {
			maxLength = len(term)
		}
	}
	termWidth, _, _ := tty.Size()
	for _, term := range suggestions {
		paddedTerm := term
		for len(paddedTerm) < maxLength {
			paddedTerm += " "
		}
		var leftPadding string
		for i := 0; i < promptWidth; i++ {
			leftPadding += " "
		}
		if promptWidth > termWidth {
			return
		} else if len(paddedTerm)+promptWidth > termWidth {
			paddedTerm = paddedTerm[:termWidth-promptWidth]
		}
		fmt.Fprintf(out, "\n%s%s\033[%dD", leftPadding, ansi.Color(paddedTerm, "white+b:magenta"), len(paddedTerm))
	}
	if len(suggestions) > 0 {
		fmt.Fprintf(out, "\033[%dA", len(suggestions))
	}
}


text:
require 'spec_helper'

describe 'android::11' do
  let(:facts) do
    {
      :boxen_home => '/opt/boxen',
    }
  end

  context "ensure => absent" do
    let(:params) do
      {
        :ensure    => 'absent',
        :options   => ['platform', 'add_on', 'system_image']
      }
    end
    it do
      should contain_android__version('11').with(
        :ensure  => 'absent',
        :options => ['platform', 'add_on', 'system_image']
      )
    end
  end

  context "default" do
    it do
      should contain_android__version('11').with(
        :ensure  => 'present',
        :options => ['platform', 'add_on']
      )
    end
  end
end


text:
package org.wso2.carbon.identity.oauth2.model;

import org.wso2.carbon.identity.oauth.cache.CacheEntry;

/**
 * OAuth 2 resource scope cache entry.
 */
public class ResourceScopeCacheEntry extends CacheEntry {

    private static final long serialVersionUID = 8986718905978405685L;

    private String scope;

    private int tenantId;

    public ResourceScopeCacheEntry(String scope) {
        this.scope = scope;
    }

    public String getScope() {
        return scope;
    }

    public void setScope(String scope) {
        this.scope = scope;
    }

    public int getTenantId() {
        return tenantId;
    }

    public void setTenantId(int tenantId) {
        this.tenantId = tenantId;
    }

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycol. Pap. 128: 74 (1972)

#### Original name
Chionomyces Deighton & Piroz.

### Remarks
null


text:
require 'spec_helper'

describe "GoogleApps::DocumentHandler" do
  let (:handler) { GoogleApps::DocumentHandler.new }
  let (:documents) { to_meth GoogleApps::Atom::Document.types }

  describe "#create_doc" do
    it "Returns a XML document when given xml and @format is :atom" do
      handler.create_doc(finished_export, :export).should be_a LibXML::XML::Document
    end

    it "Returns a XML document when given xml and @format is :xml" do
      handler.create_doc(finished_export, :export).should be_a LibXML::XML::Document
    end
  end

  describe "#unknown_type" do
    it "Returns an XML Document when given a string and @format is :atom" do
      handler.unknown_type(finished_export).should be_a LibXML::XML::Document
    end

    it "Returns an XML Document when given a string and @format is :xml" do
      handler.unknown_type(finished_export).should be_a LibXML::XML::Document
    end
  end

  describe "#doc_of_type" do
    it "Returns an object of the specified type if the type is valid for the format" do
      user = handler.doc_of_type File.read('spec/fixture_xml/user.xml'), :user

      user.should be_a GoogleApps::Atom::User
    end

    it "Raises a RuntimeError if the type is not valid for the format" do
      lambda { handler.doc_of_type :goat, File.read('spec/fixture_xml/user.xml') }.should raise_error
    end
  end

  describe "#look_up_doc_types" do
    it "Returns a list of all Atom documents when @format is :atom" do
      handler.send(:look_up_doc_types).should == documents
    end

    it "Returns a list of all Atom documents when @format is :xml" do
      handler.send(:look_up_doc_types).should == documents
    end
  end
end


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var web_image_cache_common_1 = require("./web-image-cache.common");
var view_1 = require("tns-core-modules/ui/core/view");
var appSettings = require("tns-core-modules/application-settings");
var helpers_1 = require("./ios-ts-lib/helpers");
var enums = require("tns-core-modules/ui/enums");
var placeholderProperty = new view_1.Property({
    name: "placeholder",
    defaultValue: undefined,
    affectsLayout: true
}), stretchProperty = new view_1.Property({
    name: "stretch",
    defaultValue: "none",
    affectsLayout: true
});
web_image_cache_common_1.srcProperty.register(web_image_cache_common_1.WebImageCommon);
web_image_cache_common_1.isLoadingProperty.register(web_image_cache_common_1.WebImageCommon);
placeholderProperty.register(web_image_cache_common_1.WebImageCommon);
stretchProperty.register(web_image_cache_common_1.WebImageCommon);
var WebImage = (function (_super) {
    __extends(WebImage, _super);
    function WebImage() {
        return _super.call(this) || this;
    }
    WebImage.prototype.createNativeView = function () {
        var imageView = new UIImageView();
        imageView.contentMode = UIViewContentMode.UIViewContentModeScaleAspectFit;
        imageView.clipsToBounds = true;
        imageView.userInteractionEnabled = true;
        return imageView;
    };
    Object.defineProperty(WebImage.prototype, "ios", {
        get: function () {
            return this.nativeView;
        },
        set: function (view) {
            this.nativeView = view;
        },
        enumerable: true,
        configurable: true
    });
    WebImage.prototype.onMeasure = function (widthMeasureSpec, heightMeasureSpec) {
        var utils = require("utils/utils"), width = utils.layout.getMeasureSpecSize(widthMeasureSpec), widthMode = utils.layout.getMeasureSpecMode(widthMeasureSpec), height = utils.layout.getMeasureSpecSize(heightMeasureSpec), heightMode = utils.layout.getMeasureSpecMode(heightMeasureSpec), nativeWidth = this.nativeView ? (this.nativeView.image ? this.nativeView.image.size.width : 0) : 0, nativeHeight = this.nativeView ? (this.nativeView.image ? this.nativeView.image.size.height : 0) : 0, measureWidth = Math.max(nativeWidth, this.minWidth), measureHeight = Math.max(nativeHeight, this.minHeight), finiteWidth = widthMode !== utils.layout.UNSPECIFIED, finiteHeight = heightMode !== utils.layout.UNSPECIFIED;
        if (nativeWidth !== 0 && nativeHeight !== 0 && (finiteWidth || finiteHeight)) {
            var scale = this.computeScaleFactor(width, height, finiteWidth, finiteHeight, nativeWidth, nativeHeight, this.stretch), resultW = Math.floor(nativeWidth * scale.width), resultH = Math.floor(nativeHeight * scale.height);
            measureWidth = finiteWidth ? Math.min(resultW, width) : resultW;
            measureHeight = finiteHeight ? Math.min(resultH, height) : resultH;
            var trace = require("trace");
            trace.write("Image stretch: " + this.stretch +
                ", nativeWidth: " + nativeWidth +
                ", nativeHeight: " + nativeHeight, trace.categories.Layout);
        }
        var view = require("ui/core/view");
        var widthAndState = view.View.resolveSizeAndState(measureWidth, width, widthMode, 0);
        var heightAndState = view.View.resolveSizeAndState(measureHeight, height, heightMode, 0);
        this.setMeasuredDimension(widthAndState, heightAndState);
    };
    WebImage.prototype.computeScaleFactor = function (measureWidth, measureHeight, widthIsFinite, heightIsFinite, nativeWidth, nativeHeight, imageStretch) {
        var scaleW = 1, scaleH = 1;
        if ((imageStretch === enums.Stretch.aspectFill || imageStretch === enums.Stretch.aspectFit || imageStretch === enums.Stretch.fill) &&
            (widthIsFinite || heightIsFinite)) {
            scaleW = (nativeWidth > 0) ? measureWidth / nativeWidth : 0;
            scaleH = (nativeHeight > 0) ? measureHeight / nativeHeight : 0;
            if (!widthIsFinite) {
                scaleW = scaleH;
            }
            else if (!heightIsFinite) {
                scaleH = scaleW;
            }
            else {
                switch (imageStretch) {
                    case enums.Stretch.aspectFit:
                        scaleH = scaleW < scaleH ? scaleW : scaleH;
                        scaleW = scaleH;
                        break;
                    case enums.Stretch.aspectFill:
                        scaleH = scaleW > scaleH ? scaleW : scaleH;
                        scaleW = scaleH;
                        break;
                }
            }
        }
        return {
            width: scaleW,
            height: scaleH
        };
    };
    WebImage.prototype[placeholderProperty.getDefault] = function () {
        return undefined;
    };
    WebImage.prototype[placeholderProperty.setNative] = function (value) {
    };
    WebImage.prototype[stretchProperty.getDefault] = function () {
        return "none";
    };
    WebImage.prototype[stretchProperty.setNative] = function (value) {
        helpers_1.Helpers.onStretchPropertyChanged(this.nativeView, value);
    };
    WebImage.prototype[web_image_cache_common_1.isLoadingProperty.getDefault] = function () {
        return false;
    };
    WebImage.prototype[web_image_cache_common_1.isLoadingProperty.setNative] = function (value) {
    };
    WebImage.prototype[web_image_cache_common_1.srcProperty.getDefault] = function () {
    };
    WebImage.prototype[web_image_cache_common_1.srcProperty.setNative] = function (value) {
        helpers_1.Helpers.onSrcPropertySet(this, value);
    };
    return WebImage;
}(web_image_cache_common_1.WebImageCommon));
exports.WebImage = WebImage;
function setCacheLimit(numberOfDays) {
    var noOfSecondsInAMinute = 60, noOfMinutesInAHour = 60, noOfHoursInADay = 24, noOfSecondsADay = noOfSecondsInAMinute * noOfMinutesInAHour * noOfHoursInADay, noOfSecondsInDays = noOfSecondsADay * numberOfDays, currentSeconds = Math.round(new Date().getTime() / 1000), referenceTime = 0;
    if (true === appSettings.getBoolean("isAppOpenedFirstTime") || undefined === appSettings.getBoolean("isAppOpenedFirstTime") || null == appSettings.getBoolean("isAppOpenedFirstTime")) {
        appSettings.setBoolean("isAppOpenedFirstTime", false);
        this.clearCache();
        appSettings.setNumber("cacheTimeReference", currentSeconds);
    }
    else {
        referenceTime = appSettings.getNumber("cacheTimeReference");
        if (null == referenceTime || undefined === referenceTime) {
            appSettings.setNumber("cacheTimeReference", currentSeconds);
        }
        else if ((currentSeconds - referenceTime) > noOfSecondsInDays) {
            this.clearCache();
            appSettings.setNumber("cacheTimeReference", currentSeconds);
        }
    }
}
exports.setCacheLimit = setCacheLimit;
function clearCache() {
    var imageCache = SDImageCache.sharedImageCache();
    imageCache.clearMemory();
    imageCache.clearDiskOnCompletion(function () { });
}
exports.clearCache = clearCache;
function initializeOnAngular() {
    throw new Error("'initializeOnAngular' has been removed from 'nativescript-web-image-cache', see its readme for details!");
}
exports.initializeOnAngular = initializeOnAngular;
//# sourceMappingURL=web-image-cache.ios.js.map


text:
// ===============================================================================
//						  NVIDIA PHYSX SDK TRAINING PROGRAMS
//			              LESSON 502: VISUAL REMOTE DEBUGGER
//
//						    Written by Bob Schade, 5-1-06
// ===============================================================================

#include <GL/glut.h>
#include <stdio.h>

#include "NxPhysics.h"
#include "CommonCode.h"
#include "Actors.h"
#include "Lesson502.h"

// Physics SDK globals
extern NxPhysicsSDK*     gPhysicsSDK;
extern NxScene*          gScene;
extern NxVec3            gDefaultGravity;

// User report globals
extern DebugRenderer     gDebugRenderer;
extern UserAllocator*	 gAllocator;
extern ErrorStream       gErrorStream;
extern NxRemoteDebugger* gRemoteDebugger;

// HUD globals
extern HUD hud;

// Force globals
extern NxVec3 gForceVec;
extern NxReal gForceStrength;
extern bool bForceMode;

// Simulation globals
extern bool bHardwareScene;
extern bool bPause;
extern bool bShadows;
extern bool bDebugWireframeMode;

// Actor globals
NxActor* groundPlane;
NxActor* box;
NxActor* sphere;
NxActor* capsule;
NxActor* pyramid;

extern NxActor* gSelectedActor;

void PrintControls()
{
	printf("\n Flight Controls:\n ----------------\n w = forward, s = back\n a = strafe left, d = strafe right\n q = up, z = down\n");
    printf("\n Force Controls:\n ---------------\n i = +z, k = -z\n j = +x, l = -x\n u = +y, m = -y\n");
	printf("\n Miscellaneous:\n --------------\n p = Pause\n r = Select Next Actor\n f = Toggle Force Mode\n b = Toggle Debug Wireframe Mode\n x = Toggle Shadows\n t = Move Focus Actor to (0,5,0)\n");
}

void RenderActors(bool shadows)
{
    // Render all the actors in the scene
    NxU32 nbActors = gScene->getNbActors();
    NxActor** actors = gScene->getActors();
    while (nbActors--)
    {
        NxActor* actor = *actors++;
	    DrawActor(actor, gSelectedActor, true);

        // Handle shadows
        if (shadows)
        {
			DrawActorShadow(actor, true);
        }
    }
}

void ProcessInputs()
{
    ProcessForceKeys();

    // Show debug wireframes
	if (bDebugWireframeMode)
	{
		if (gScene)  gDebugRenderer.renderData(*gScene->getDebugRenderable());
	}
}

void RenderCallback()
{
    // Clear buffers
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	ProcessCameraKeys();
	SetupCamera();

    if (gScene && !bPause)
	{
		GetPhysicsResults();
        ProcessInputs();
		StartPhysics();
	}

    // Display scene
 	RenderActors(bShadows);

	if (bForceMode)
		DrawForce(gSelectedActor, gForceVec, NxVec3(1,1,0));
	else
		DrawForce(gSelectedActor, gForceVec, NxVec3(0,1,1));
	gForceVec = NxVec3(0,0,0);

	// Render HUD
	hud.Render();

    glFlush();
    glutSwapBuffers();
}

void SpecialKeys(unsigned char key, int x, int y)
{
}

void InitNx()
{
	// Create a memory allocator
    gAllocator = new UserAllocator;

    // Create the physics SDK
    gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, gAllocator);
	if (!gPhysicsSDK)  return;

	// Create the remote debugger
	gRemoteDebugger = gPhysicsSDK->getFoundationSDK().getRemoteDebugger();
/*
    gRemoteDebugger()->writeParameter(NxVec3(5,5,5), &gCameraObj, true, "Origin", NX_DBG_EVENTMASK_EVERYTHING);
    gRemoteDebugger()->writeParameter(NxVec3(0,0,0), &gCameraObj, true, "Target", NX_DBG_EVENTMASK_EVERYTHING);
    gRemoteDebugger()->writeParameter(NxVec3(0,1,0), &gCameraObj, true, "Up", NX_DBG_EVENTMASK_EVERYTHING);
*/
	gRemoteDebugger->connect("localhost");

	// Set the physics parameters
	gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.01);

	// Set the debug visualization parameters
	gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_FNORMALS, 1);

    // Create the scene
    NxSceneDesc sceneDesc;
    sceneDesc.gravity               = gDefaultGravity;
	sceneDesc.simType				= NX_SIMULATION_HW;

    gScene = gPhysicsSDK->createScene(sceneDesc);
 if(!gScene){
		sceneDesc.simType				= NX_SIMULATION_SW;
		gScene = gPhysicsSDK->createScene(sceneDesc);
		if(!gScene) return;
	}

	// If hardware is unavailable, fall back on software
	if (!gScene)
	{
        sceneDesc.simType				= NX_SIMULATION_SW;
        gScene = gPhysicsSDK->createScene(sceneDesc);
 if(!gScene){
		sceneDesc.simType				= NX_SIMULATION_SW;
		gScene = gPhysicsSDK->createScene(sceneDesc);
		if(!gScene) return;
	}
	}

	// Create the default material
	NxMaterial* defaultMaterial = gScene->getMaterialFromIndex(0);
	defaultMaterial->setRestitution(0.5);
	defaultMaterial->setStaticFriction(0.5);
	defaultMaterial->setDynamicFriction(0.5);

	// Create the objects in the scene
	groundPlane = CreateGroundPlane();

	box = CreateBox(NxVec3(5,0,0), NxVec3(0.5,1,0.5), 20);
	sphere = CreateSphere(NxVec3(0,0,5), 1, 10);
	capsule = CreateCapsule(NxVec3(-5,0,0), 2, 0.5, 10);
	pyramid = CreatePyramid(NxVec3(0,0,0), NxVec3(1,0.5,1.5), 10);

	AddUserDataToActors(gScene);

	gSelectedActor = pyramid;

	// Initialize HUD
	InitializeHUD();

	// Get the current time
	getElapsedTime();

	// Start the first frame of the simulation
	if (gScene)  StartPhysics();
}

int main(int argc, char** argv)
{
	PrintControls();
	InitGlut(argc, argv, "Lesson 502: Visual Remote Debugger");
    InitNx();
    glutMainLoop();
	ReleaseNx();
	return 0;
}


text:
package twitch

import (
	"fmt"
	"log"
	"sync"
	"time"
)

const (
	heartBeatRate  = time.Minute
	heartBeatLimit = 100
	heartDumpEvery = time.Minute * 30
)

// HeartbeatData - Single Beat of the Heart
type HeartbeatData struct {
	Status    string    `json:"status"`
	Game      string    `json:"game"`
	Time      time.Time `json:"time"`
	IsLive    bool      `json:"live"`
	ViewCount int       `json:"view"`
}

// Heartbeat - A beat which captures some data
// * Live Status
// * Viewer Count
// * host notifications
type Heartbeat struct {
	beats     []HeartbeatData
	hosts     map[ID]time.Time
	heartLock sync.RWMutex

	prevFollowCount int
	followers       []ChannelFollow

	internalBeat *time.Ticker
	client       *Client
}

// StartBeat - Blocking Loop Which
func (heart *Heartbeat) StartBeat() {
	heart.prevFollowCount = -1
	heart.hosts = make(map[ID]time.Time)

	// First Beat
	heart.beat(time.Now())

	timeSinceDump := time.Duration(0)
	heart.internalBeat = time.NewTicker(heartBeatRate)

	// Beat every X minutes
	for ts := range heart.internalBeat.C {
		heart.beat(ts)

		// Dumping to File
		timeSinceDump += heartBeatRate
		if timeSinceDump > heartDumpEvery {
			timeSinceDump = 0
			err := heart.client.DumpViewers()
			if err != nil {
				fmt.Printf("DUMP ERROR: %s", err)
			}

		}
	}
}

// GetBeat - Get Sepecific Beat
func (heart *Heartbeat) GetBeat(beatNum int) HeartbeatData {
	heart.heartLock.RLock()
	defer heart.heartLock.RUnlock()
	return heart.beats[beatNum]
}

// GetAllBeats - Get All the Beats
func (heart *Heartbeat) GetAllBeats() []HeartbeatData {
	heart.heartLock.RLock()
	defer heart.heartLock.RUnlock()

	log.Printf("Beats Source %d", len(heart.beats))
	return heart.beats[0:]
}

// GetAllHosts - Get All Hosts
func (heart *Heartbeat) GetAllHosts() []ID {
	keys := make([]ID, len(heart.hosts), len(heart.hosts))
	i := 0
	for k := range heart.hosts {
		keys[i] = k
		i++
	}
	return keys
}

func (heart *Heartbeat) beat(t time.Time) {
	heart.heartLock.Lock()
	defer heart.heartLock.Unlock()

	fmt.Println("-- BEAT --")

	var prevDataPoint *HeartbeatData
	if len(heart.beats) > 0 {
		prevDataPoint = &heart.beats[len(heart.beats)-1]
	}

	// Stream Viewer Count
	sb, err := heart.client.Stream.GetStreamByUser(heart.client.RoomID)
	fmt.Println(sb)
	fmt.Println(err)

	if err != nil || sb == nil || (sb.AverageFPS == 0) {
		if prevDataPoint == nil || prevDataPoint.IsLive {
			heart.beats = append(heart.beats, HeartbeatData{Time: t})
			prevDataPoint = &heart.beats[len(heart.beats)-1]
		}
		return
	}
	heart.client.RoomStream = sb

	hbd := HeartbeatData{
		Status:    sb.Channel.Status,
		Game:      sb.Game,
		Time:      t,
		IsLive:    true,
		ViewCount: sb.Viewers,
	}
	if prevDataPoint == nil {
		prevDataPoint = &hbd
	}

	// Get Channel Followers
	// If there are more then 30 follows in a SECOND who cares
	fList, followNum, err := heart.client.Channel.GetFollowers(heart.client.RoomID, 30, true)
	heart.client.Viewers.UpdateFollowers(fList)

	// Check for new followers
	for _, f := range fList {
		t, err := time.Parse(time.RFC3339, f.CreatedAtString)
		if err != nil {
			panic(err)
		}

		if t.After(prevDataPoint.Time) {
			// New Follow
			heart.client.Alerts.Post(f.User.Name, AlertFollow, t)
		} else {
			// Avoid 99% of the work
			break
		}
	}

	heart.prevFollowCount = followNum

	// List of Hosts
	hostList, err := heart.client.Stream.GetHostsByUser(heart.client.RoomID)
	if err != nil {
		fmt.Printf("Host Check failed: %s\n", err.Error())
		return
	}

	hostDiff := len(heart.hosts) - len(hostList)
	for _, h := range hostList {
		srcID := IDFromInt(h.HostID)
		_, ok := heart.hosts[srcID]
		if !ok {
			// Trigger Alert
			heart.hosts[srcID] = time.Now()
			heart.client.Alerts.Post(IrcNick(h.HostLogin), AlertHost, h)
			hostDiff++
		}
	}

	// We lost a host
	if hostDiff > 0 {
		for k := range heart.hosts {
			isFound := false
			for k2 := 0; !isFound && k2 < len(hostList); k2++ {
				srcID := IDFromInt(hostList[k2].HostID)
				isFound = (k == srcID)
			}

			if isFound == false {
				delete(heart.hosts, k)
			}
		}
	}

	// Update Data Points
	prevDataPoint = &hbd
	if len(heart.beats) < heartBeatLimit {
		heart.beats = append(heart.beats, hbd)
	} else {
		heart.beats = append(heart.beats[1:], hbd)
	}

	heart.client.Alerts.Post(heart.client.RoomName, AlertNone, hbd)
}


text:
#include "softdevice_handler.h"
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "nordic_common.h"
#include "app_error.h"
#include "nrf_assert.h"
#include "nrf_nvic.h"
#include "nrf.h"
#include "nrf_log.h"
#include "sdk_common.h"
#include "nrf_drv_config.h"
#if CLOCK_ENABLED
#include "nrf_drv_clock.h"
#endif

#if defined(ANT_STACK_SUPPORT_REQD) && defined(BLE_STACK_SUPPORT_REQD)
    #include "ant_interface.h"
#elif defined(ANT_STACK_SUPPORT_REQD)
    #include "ant_interface.h"
#elif defined(BLE_STACK_SUPPORT_REQD)
    #include "ble.h"
#endif

#if defined(NRF_LOG_USES_RTT) && NRF_LOG_USES_RTT == 1
#define SD_HANDLER_LOG(...) NRF_LOG_PRINTF(__VA_ARGS__)
#else
#define SD_HANDLER_LOG(...)
#endif

#if defined(NRF_LOG_USES_RTT) && NRF_LOG_USES_RTT == 1
#define SD_HANDLER_LOG_INIT() NRF_LOG_INIT()
#else
#define SD_HANDLER_LOG_INIT()
#endif

#define RAM_START_ADDRESS         0x20000000
#define SOFTDEVICE_EVT_IRQ        SD_EVT_IRQn       /**< SoftDevice Event IRQ number. Used for both protocol events and SoC events. */
#define SOFTDEVICE_EVT_IRQHandler SD_EVT_IRQHandler
#define RAM_TOTAL_SIZE            ((NRF_FICR->INFO.RAM)*1024)
#define RAM_END_ADDRESS           (RAM_START_ADDRESS + RAM_TOTAL_SIZE)

#define SOFTDEVICE_VS_UUID_COUNT       0
#define SOFTDEVICE_GATTS_ATTR_TAB_SIZE BLE_GATTS_ATTR_TAB_SIZE_DEFAULT
#define SOFTDEVICE_GATTS_SRV_CHANGED   0
#define SOFTDEVICE_PERIPH_CONN_COUNT   1
#define SOFTDEVICE_CENTRAL_CONN_COUNT  4
#define SOFTDEVICE_CENTRAL_SEC_COUNT   1

/* Global nvic state instance, required by nrf_nvic.h */
nrf_nvic_state_t nrf_nvic_state;

static softdevice_evt_schedule_func_t m_evt_schedule_func;              /**< Pointer to function for propagating SoftDevice events to the scheduler. */

static volatile bool                  m_softdevice_enabled = false;     /**< Variable to indicate whether the SoftDevice is enabled. */

#ifdef BLE_STACK_SUPPORT_REQD
// The following three definitions is needed only if BLE events are needed to be pulled from the stack.
static uint8_t                      * mp_ble_evt_buffer;                /**< Buffer for receiving BLE events from the SoftDevice. */
static uint16_t                       m_ble_evt_buffer_size;            /**< Size of BLE event buffer. */
static ble_evt_handler_t              m_ble_evt_handler;                /**< Application event handler for handling BLE events. */
#endif

#ifdef ANT_STACK_SUPPORT_REQD
// The following two definition is needed only if ANT events are needed to be pulled from the stack.
static ant_evt_t                      m_ant_evt_buffer;                 /**< Buffer for receiving ANT events from the SoftDevice. */
static ant_evt_handler_t              m_ant_evt_handler;                /**< Application event handler for handling ANT events.  */
#endif

static sys_evt_handler_t              m_sys_evt_handler;                /**< Application event handler for handling System (SOC) events.  */

/**@brief       Callback function for asserts in the SoftDevice.
 *
 * @details     A pointer to this function will be passed to the SoftDevice. This function will be
 *              called by the SoftDevice if certain unrecoverable errors occur within the
 *              application or SoftDevice.
 *
 *              See @ref nrf_fault_handler_t for more details.
 *
 * @param[in] id    Fault identifier. See @ref NRF_FAULT_IDS.
 * @param[in] pc    The program counter of the instruction that triggered the fault.
 * @param[in] info  Optional additional information regarding the fault. Refer to each fault
 *                  identifier for details.
 */
void softdevice_fault_handler(uint32_t id, uint32_t pc, uint32_t info)
{
    app_error_fault_handler(id, pc, info);
}

void intern_softdevice_events_execute(void)
{
    if (!m_softdevice_enabled)
    {
        // SoftDevice not enabled. This can be possible if the SoftDevice was enabled by the
        // application without using this module's API (i.e softdevice_handler_init)

        return;
    }
#if CLOCK_ENABLED
    bool no_more_soc_evts = false;
#else
    bool no_more_soc_evts = (m_sys_evt_handler == NULL);
#endif
#ifdef BLE_STACK_SUPPORT_REQD
    bool no_more_ble_evts = (m_ble_evt_handler == NULL);
#endif
#ifdef ANT_STACK_SUPPORT_REQD
    bool no_more_ant_evts = (m_ant_evt_handler == NULL);
#endif

    for (;;)
    {
        uint32_t err_code;

        if (!no_more_soc_evts)
        {
            uint32_t evt_id;

            // Pull event from SOC.
            err_code = sd_evt_get(&evt_id);

            if (err_code == NRF_ERROR_NOT_FOUND)
            {
                no_more_soc_evts = true;
            }
            else if (err_code != NRF_SUCCESS)
            {
                APP_ERROR_HANDLER(err_code);
            }
            else
            {
                // Call application's SOC event handler.
#if CLOCK_ENABLED
                nrf_drv_clock_on_soc_event(evt_id);
                if (m_sys_evt_handler)
                {
                    m_sys_evt_handler(evt_id);
                }
#else
                m_sys_evt_handler(evt_id);
#endif
            }
        }

#ifdef BLE_STACK_SUPPORT_REQD
        // Fetch BLE Events.
        if (!no_more_ble_evts)
        {
            // Pull event from stack
            uint16_t evt_len = m_ble_evt_buffer_size;

            err_code = sd_ble_evt_get(mp_ble_evt_buffer, &evt_len);
            if (err_code == NRF_ERROR_NOT_FOUND)
            {
                no_more_ble_evts = true;
            }
            else if (err_code != NRF_SUCCESS)
            {
                APP_ERROR_HANDLER(err_code);
            }
            else
            {
                // Call application's BLE stack event handler.
                m_ble_evt_handler((ble_evt_t *)mp_ble_evt_buffer);
            }
        }
#endif

#ifdef ANT_STACK_SUPPORT_REQD
        // Fetch ANT Events.
        if (!no_more_ant_evts)
        {
            // Pull event from stack
            err_code = sd_ant_event_get(&m_ant_evt_buffer.channel,
                                        &m_ant_evt_buffer.event,
                                        m_ant_evt_buffer.msg.evt_buffer);
            if (err_code == NRF_ERROR_NOT_FOUND)
            {
                no_more_ant_evts = true;
            }
            else if (err_code != NRF_SUCCESS)
            {
                APP_ERROR_HANDLER(err_code);
            }
            else
            {
                // Call application's ANT stack event handler.
                m_ant_evt_handler(&m_ant_evt_buffer);
            }
        }
#endif

        if (no_more_soc_evts)
        {
            // There are no remaining System (SOC) events to be fetched from the SoftDevice.
#if defined(ANT_STACK_SUPPORT_REQD) && defined(BLE_STACK_SUPPORT_REQD)
            // Check if there are any remaining BLE and ANT events.
            if (no_more_ble_evts && no_more_ant_evts)
            {
                break;
            }
#elif defined(BLE_STACK_SUPPORT_REQD)
            // Check if there are any remaining BLE events.
            if (no_more_ble_evts)
            {
                break;
            }
#elif defined(ANT_STACK_SUPPORT_REQD)
            // Check if there are any remaining ANT events.
            if (no_more_ant_evts)
            {
                break;
            }
#else
            // No need to check for BLE or ANT events since there is no support for BLE and ANT
            // required.
            break;
#endif
        }
    }
}

bool softdevice_handler_isEnabled(void)
{
    return m_softdevice_enabled;
}

uint32_t softdevice_handler_init(nrf_clock_lf_cfg_t	*           p_clock_lf_cfg,
                                 void *                         p_ble_evt_buffer,
                                 uint16_t                       ble_evt_buffer_size,
                                 softdevice_evt_schedule_func_t evt_schedule_func)
{
    uint32_t err_code;

    SD_HANDLER_LOG_INIT();

    // Save configuration.
#if defined (BLE_STACK_SUPPORT_REQD)
    // Check that buffer is not NULL.
    if (p_ble_evt_buffer == NULL)
    {
        return NRF_ERROR_INVALID_PARAM;
    }

    // Check that buffer is correctly aligned.
    if (!is_word_aligned(p_ble_evt_buffer))
    {
        return NRF_ERROR_INVALID_PARAM;
    }

    mp_ble_evt_buffer     = (uint8_t *)p_ble_evt_buffer;
    m_ble_evt_buffer_size = ble_evt_buffer_size;
#else
    // The variables p_ble_evt_buffer and ble_evt_buffer_size is not needed if BLE Stack support
    // is not required.
    UNUSED_PARAMETER(p_ble_evt_buffer);
    UNUSED_PARAMETER(ble_evt_buffer_size);
#endif

    m_evt_schedule_func = evt_schedule_func;

    // Initialize SoftDevice.
#if defined(S212) || defined(S332)
    err_code = sd_softdevice_enable(p_clock_lf_cfg, softdevice_fault_handler, ANT_LICENSE_KEY);
#else
    err_code = sd_softdevice_enable(p_clock_lf_cfg, softdevice_fault_handler);
#endif
    if (err_code != NRF_SUCCESS)
    {
        return err_code;
    }

    m_softdevice_enabled = true;

    // Enable BLE event interrupt (interrupt priority has already been set by the stack).
#ifdef SOFTDEVICE_PRESENT
    return sd_nvic_EnableIRQ((IRQn_Type)SOFTDEVICE_EVT_IRQ);
#else
    //In case of Serialization NVIC must be accessed directly.
    NVIC_EnableIRQ(SOFTDEVICE_EVT_IRQ);
    return NRF_SUCCESS;
#endif
}

uint32_t softdevice_handler_sd_disable(void)
{
    uint32_t err_code = sd_softdevice_disable();

    m_softdevice_enabled = !(err_code == NRF_SUCCESS);

    return err_code;
}

#ifdef BLE_STACK_SUPPORT_REQD
uint32_t softdevice_ble_evt_handler_set(ble_evt_handler_t ble_evt_handler)
{
    VERIFY_PARAM_NOT_NULL(ble_evt_handler);

    m_ble_evt_handler = ble_evt_handler;

    return NRF_SUCCESS;
}
#endif

#ifdef ANT_STACK_SUPPORT_REQD
uint32_t softdevice_ant_evt_handler_set(ant_evt_handler_t ant_evt_handler)
{
    VERIFY_PARAM_NOT_NULL(ant_evt_handler);

    m_ant_evt_handler = ant_evt_handler;

    return NRF_SUCCESS;
}
#endif

uint32_t softdevice_sys_evt_handler_set(sys_evt_handler_t sys_evt_handler)
{
    VERIFY_PARAM_NOT_NULL(sys_evt_handler);

    m_sys_evt_handler = sys_evt_handler;

    return NRF_SUCCESS;
}

/**@brief   Function for handling the Application's BLE Stack events interrupt.
 *
 * @details This function is called whenever an event is ready to be pulled.
 */
void SOFTDEVICE_EVT_IRQHandler(void)
{
    if (m_evt_schedule_func != NULL)
    {
        uint32_t err_code = m_evt_schedule_func();
        APP_ERROR_CHECK(err_code);
    }
    else
    {
        intern_softdevice_events_execute();
    }
}

#if defined(BLE_STACK_SUPPORT_REQD)
uint32_t softdevice_enable_get_default_config(uint8_t central_links_count,
                                              uint8_t periph_links_count,
                                              ble_enable_params_t * p_ble_enable_params)
{
    memset(p_ble_enable_params, 0, sizeof(ble_enable_params_t));
    p_ble_enable_params->common_enable_params.vs_uuid_count   = 1;
    p_ble_enable_params->gatts_enable_params.attr_tab_size    = SOFTDEVICE_GATTS_ATTR_TAB_SIZE;
    p_ble_enable_params->gatts_enable_params.service_changed  = SOFTDEVICE_GATTS_SRV_CHANGED;
    p_ble_enable_params->gap_enable_params.periph_conn_count  = periph_links_count;
    p_ble_enable_params->gap_enable_params.central_conn_count = central_links_count;
    if (p_ble_enable_params->gap_enable_params.central_conn_count != 0)
    {
        p_ble_enable_params->gap_enable_params.central_sec_count  = SOFTDEVICE_CENTRAL_SEC_COUNT;
    }

    return NRF_SUCCESS;
}

#if defined(NRF_LOG_USES_RTT) && NRF_LOG_USES_RTT == 1
static inline uint32_t ram_total_size_get(void)
{
#ifdef NRF51
    uint32_t size_ram_blocks = (uint32_t)NRF_FICR->SIZERAMBLOCKS;
    uint32_t total_ram_size = size_ram_blocks;
    total_ram_size = total_ram_size*(NRF_FICR->NUMRAMBLOCK);
    return total_ram_size;
#elif defined (NRF52)
    return RAM_TOTAL_SIZE;
#endif /* NRF51 */
}

/*lint --e{528} -save suppress 528: symbol not referenced */
/**@brief   Function for finding the end address of the RAM.
 *
 * @retval  ram_end_address  Address of the end of the RAM.
 */
static inline uint32_t ram_end_address_get(void)
{
    uint32_t ram_end_address = (uint32_t)RAM_START_ADDRESS;
    ram_end_address+= ram_total_size_get();
    return ram_end_address;
}
/*lint -restore*/
#endif  //ENABLE_DEBUG_LOG_SUPPORT

/*lint --e{10} --e{19} --e{27} --e{40} --e{529} -save suppress Error 27: Illegal character */
uint32_t sd_check_ram_start(uint32_t sd_req_ram_start)
{
#if (defined(S130) || defined(S132) || defined(S332))
#if defined ( __CC_ARM )
    extern uint32_t Image$$RW_IRAM1$$Base;
    const volatile uint32_t ram_start = (uint32_t) &Image$$RW_IRAM1$$Base;
#elif defined ( __ICCARM__ )
    extern uint32_t __ICFEDIT_region_RAM_start__;
    volatile uint32_t ram_start = (uint32_t) &__ICFEDIT_region_RAM_start__;
#elif defined   ( __GNUC__ )
    extern uint32_t __data_start__;
    volatile uint32_t ram_start = (uint32_t) &__data_start__;
#endif//__CC_ARM
    if (ram_start != sd_req_ram_start)
    {
#if defined(NRF_LOG_USES_RTT) && NRF_LOG_USES_RTT == 1
        uint32_t app_ram_size= ram_end_address_get();
        SD_HANDLER_LOG("RAM START ADDR 0x%x should be adjusted to 0x%x\r\n",
                  ram_start,
                  sd_req_ram_start);
        app_ram_size -= sd_req_ram_start;
        SD_HANDLER_LOG("RAM SIZE should be adjusted to 0x%x \r\n",
                  app_ram_size);
#endif //NRF_LOG_USES_RTT
        return NRF_SUCCESS;
    }
#endif//defined(S130) || defined(S132) || defined(S332)
    return NRF_SUCCESS;
}

uint32_t softdevice_enable(ble_enable_params_t * p_ble_enable_params)
{
#if (defined(S130) || defined(S132) || defined(S332))
    uint32_t err_code;
    uint32_t app_ram_base;

#if defined ( __CC_ARM )
    extern uint32_t Image$$RW_IRAM1$$Base;
    const volatile uint32_t ram_start = (uint32_t) &Image$$RW_IRAM1$$Base;
#elif defined ( __ICCARM__ )
    extern uint32_t __ICFEDIT_region_RAM_start__;
    volatile uint32_t ram_start = (uint32_t) &__ICFEDIT_region_RAM_start__;
#elif defined   ( __GNUC__ )
    extern uint32_t __data_start__;
    volatile uint32_t ram_start = (uint32_t) &__data_start__;
#endif

    app_ram_base = ram_start;
    SD_HANDLER_LOG("sd_ble_enable: RAM START at 0x%x\r\n",
                    app_ram_base);
    err_code = sd_ble_enable(p_ble_enable_params, &app_ram_base);

#if defined(NRF_LOG_USES_RTT) && NRF_LOG_USES_RTT == 1
    if (app_ram_base != ram_start)
    {
        uint32_t app_ram_size= ram_end_address_get();
        SD_HANDLER_LOG("sd_ble_enable: app_ram_base should be adjusted to 0x%x\r\n",
                  app_ram_base);
        app_ram_size -= app_ram_base;
        SD_HANDLER_LOG("ram size should be adjusted to 0x%x \r\n",
                  app_ram_size);
    }
    else if (err_code != NRF_SUCCESS)
    {
        SD_HANDLER_LOG("sd_ble_enable: error 0x%x\r\n", err_code);
        while(1);
    }
#endif   // NRF_LOG_USES_RTT
    return err_code;
#else
    return NRF_SUCCESS;
#endif   //defined(S130) || defined(S132) || defined(S332)

}
/*lint -restore*/

#endif //BLE_STACK_SUPPORT_REQD


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ListMakerTwo
{
    public struct LugBulkReservation
    {
        public LugBulkElement Element { get; set; }
        public LugBulkBuyer Buyer { get; set; }
        public int Amount { get; set; }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--Generated by crowdin.com-->
<!--
     Copyright (C) 2012-2014 The CyanogenMod Project

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

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

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
  <string name="app_name">Zaawansowane ustawienia ekranu</string>
  <!-- Screen Preference -->
  <string name="category_screen_title">Ekran</string>
  <string name="screen_colors_title">Kolory</string>
  <!-- mDNIe -->
  <string name="mdnie_scenario_title_head">Scenerie</string>
  <string name="mdnie_scenario_summary_head">Ustaw scenariusz mDNIe</string>
  <string name="mdnie_negative_title_head">Tryb negatywu</string>
  <string name="mdnie_negative_summary_head">Włącz/wyłącz odwrócone kolory</string>
</resources>


text:
class CharacterSkillqueueImporter < CharacterBaseImporter
  def import!
    character.skillqueues.destroy_all

    esi.skills.each do |skill|
      character.skillqueues.create!(skill.as_json)
    end
  end

  def esi
    @esi ||= EveOnline::ESI::CharacterSkillQueue.new(character_id: character.character_id)
  end
end


text:
package com.goodgame.profiling.graphite_bifroest.systems.cassandra;

import java.util.Collections;

import org.apache.commons.lang3.tuple.Pair;

import org.json.JSONObject;

import com.goodgame.profiling.commons.model.Interval;
import com.goodgame.profiling.commons.model.Metric;
import com.goodgame.profiling.graphite_bifroest.systems.prefixtree.PrefixTree;

public final class MemoryOnlyAccessLayer implements CassandraAccessLayer {
    @Override
    public Iterable<String> loadMetricNames() {
        return Collections.emptyList();
    }

    @Override
    public Pair<PrefixTree, Integer> loadMostRecentTimestamps() {
        return Pair.of( PrefixTree.fromJSONObject( new JSONObject() ), 0);
    }

    @Override
    public Iterable<Metric> loadMetrics( String name, Interval interval ) {
        return Collections.emptyList();
    }
}


text:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service'

@Injectable()//This must be here, if we want to inject authService!
export class AdminGuard implements CanActivate{

    constructor(private authService: AuthService){
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
        return this.authService.isAdmin();
    }
}


text:
layout: post
title: "Claiming an Inactive GitHub Account"
---

I recently found out that GitHub has a [Name Squatting Policy](https://help.github.com/articles/name-squatting-policy) whereby inactive accounts will be removed upon request.
This means that nice short handle someone claimed years ago and never used could be yours, assuming the account doesn't have loads of private activity.

## Considerations
After changing my account name, I had to update my domain settings to properly point to this website (hosted through github pages), and update the github pages repository to regenerate under this address.

URL's to your repositories will be properly forwarded, but your old account page will not forward to the new one. Remember to update any public references!